repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
bravegnu/mzero
|
src/clock.h
|
#ifndef CLOCK_H
#define CLOCK_H
#include <vector>
class ClockedIf
{
public:
virtual void execute(void) = 0;
};
class Clock
{
private:
std::vector<ClockedIf *> m_clocked_list;
public:
Clock();
void add_clocked(ClockedIf *clocked);
void tick();
};
#endif
|
bravegnu/mzero
|
src/alu.h
|
<reponame>bravegnu/mzero
// -*- mode: c++ -*-
#ifndef ALU_H
#define ALU_H
#include "decoder.h"
#include <cstdint>
class ALU;
typedef void (ALU::*ALUOp)();
enum class ShiftType {
LSL,
LSR,
ASR,
RRX,
ROR,
};
class ALU
{
private:
uint32_t *m_regs;
bool *m_c;
bool *m_v;
bool *m_n;
bool *m_z;
uint32_t *m_addr;
uint32_t *m_data;
DecodedInst m_i;
static const ALUOp alu_ops[OP_MAX];
uint32_t add_with_carry(uint32_t x, uint32_t y, bool carry_in,
bool *carry_out, bool *overflow);
void set_flags_nzcv(uint32_t result, bool carry, bool overflow);
void set_flags_nzc(uint32_t result, bool carry);
void set_flags_nz(uint32_t result);
uint32_t lsl_c(uint32_t value, unsigned amount, bool *carry_out);
uint32_t lsr_c(uint32_t value, unsigned amount, bool *carry_out);
uint32_t asr_c(uint32_t value, unsigned amount, bool *carry_out);
uint32_t ror_c(uint32_t value, unsigned amount, bool *carry_out);
void alu_write_pc(uint32_t address);
void branch_write_pc(uint32_t address);
bool condition_passed(enum Cond cond);
void exec_shifti_op();
void exec_add_sub();
void exec_addi_subi();
void exec_movi();
void exec_mov();
void exec_cmpi();
void exec_and();
void exec_eor();
void exec_shift_op();
void exec_adc();
void exec_sbc();
void exec_ror();
void exec_tst();
void exec_rsb();
void exec_cmp();
void exec_cmn();
void exec_orr();
void exec_mul();
void exec_bic();
void exec_mvn();
void exec_adr();
void exec_bx();
void exec_blx();
void exec_bcond();
void exec_svc();
void exec_str();
void exec_strh();
void exec_strb();
void exec_ldrsb();
void exec_ldr();
void exec_ldrh();
void exec_ldrb();
void exec_ldrsh();
void exec_stri();
void exec_ldri();
void exec_strbi();
void exec_ldrbi();
void exec_strhi();
void exec_ldrhi();
void exec_ldm();
void exec_stm();
void exec_ldrl();
void exec_sxth();
void exec_sxtb();
void exec_uxth();
void exec_uxtb();
void exec_push();
void exec_cps();
void exec_rev();
void exec_rev16();
void exec_revsh();
void exec_pop();
void exec_bkpt();
void exec_nop();
void exec_yield();
void exec_wfe();
void exec_wfi();
void exec_sev();
void exec_msr();
void exec_mrs();
void exec_bl();
void exec_dsb();
void exec_dmb();
void exec_isb();
void exec_udf();
public:
ALU(uint32_t *regs, bool *c, bool *o, bool *n, bool *z,
uint32_t *addr, uint32_t *data);
void execute(DecodedInst const *inst);
};
#endif
|
bravegnu/mzero
|
src/utils.h
|
<reponame>bravegnu/mzero<filename>src/utils.h
#ifndef UTILS_H
#define UTILS_H
#include <stdexcept>
#include <cstring>
#include <string>
class IOError: public std::runtime_error {
public:
IOError(int err, std::string message): std::runtime_error(message + strerror(err)) {}
};
#endif
|
bravegnu/mzero
|
src/sysbus.h
|
#ifndef SYSBUS_H
#define SYSBUS_H
#include <vector>
#include <cstdint>
#include "device.h"
struct SysDevice {
uint32_t base_addr;
DeviceIf *device;
};
class SystemBus: public DeviceIf
{
private:
std::vector<SysDevice> m_devs;
public:
SystemBus();
void register_device(uint32_t base_addr, DeviceIf *dev);
uint32_t read32(uint32_t addr);
void write32(uint32_t addr, uint32_t data);
uint32_t get_size();
};
#endif
|
bravegnu/mzero
|
src/arm.h
|
<reponame>bravegnu/mzero
#ifndef ARM_H
#define ARM_H
#include <cstdint>
#include "clock.h"
#include "sysbus.h"
#include "decoder.h"
#include "alu.h"
#include "debug.h"
class CortexM0: public ClockedIf
{
private:
static const int MAX_REGS = 16;
uint32_t m_regs[MAX_REGS];
bool m_c;
bool m_o;
bool m_n;
bool m_z;
uint32_t m_addr;
uint32_t m_data;
bool m_halted;
SystemBus *m_sysbus;
Decoder decoder;
ALU alu;
uint16_t fetch_inst();
public:
Debug debug;
CortexM0(Clock& clock, SystemBus *sysbus);
void execute();
bool is_halted();
};
#endif
|
bravegnu/mzero
|
src/device.h
|
<filename>src/device.h
#ifndef DEVICE_H
#define DEVICE_H
#include <cstdint>
class DeviceIf
{
public:
virtual uint32_t read32(uint32_t addr) = 0;
virtual void write32(uint32_t addr, uint32_t data) = 0;
virtual uint32_t get_size() = 0;
};
#endif
|
bravegnu/mzero
|
src/memory.h
|
#ifndef MEMORY_H
#define MEMORY_H
#include "device.h"
#include <string>
#include <cstdint>
class Memory: public DeviceIf
{
private:
uint8_t *m_memory;
unsigned int m_size_kb;
uint32_t m_base_addr;
public:
Memory(unsigned int size_kb);
void load_bin(std::string filename, uint32_t offset);
uint32_t read32(uint32_t addr);
void write32(uint32_t addr, uint32_t data);
uint32_t get_size();
};
#endif
|
AUAC-Technologies/AUAC-Core-Telemetry
|
Pipeline/PACKAGE_JSON.h
|
<reponame>AUAC-Technologies/AUAC-Core-Telemetry<filename>Pipeline/PACKAGE_JSON.h
/*MIT License
Copyright (c) 2020 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef JSON
#define JSON
#define INT 0
#include"../lib/ArduinoJson-6.16.1/ArduinoJson.h"
#define JSON_OBJECT StaticJsonDocument<50>
class PACKAGE_JSON {
public:
//Function serializes JSON object and returns JSON doc in array
char* serializeToJson(JSON_OBJECT object);
//Function desirializes json doc array
const char* deserialize(char* jsonDoc);
int deserialize(char* jsonDoc,int type);
//Function adds data to JSON object
//+1 OVERLOAD
int32_t addToJsonObject(JSON_OBJECT object, int32_t data);
char* addToJsonObject(JSON_OBJECT object, char* data);
};
#endif
|
UMM-CSci-3403-Fall-2018/lab-3-memory-management-and-multi-dimensional-arrays-in-c-megabittronmini
|
mergesort/mergesort.c
|
#include<stdlib.h>
#include<stdio.h>
#include"mergesort.h"
//There's no need to sort an array less than size 2
bool needsSorting(int rangeSize) {
return rangeSize >= 2;
}
void mergeRanges(int *values, int start, int midPoint, int end) {
int rangeSize = end - start;
int *destination = (int*) calloc(rangeSize+1, sizeof(int));
int first = start;
int second = midPoint;
int copy = 0;
while (first < midPoint && second < end) {
if (values[first] < values[second]) {
destination[copy] = values[first];
++first;
} else {
destination[copy] = values[second];
++second;
}
++copy;
}
while (first < midPoint) {
destination[copy] = values[first];
++copy;
++first;
}
while (second < end) {
destination[copy] = values[second];
++copy;
++second;
}
for (int i = 0; i < rangeSize; ++i) {
values[i + start] = destination[i];
}
free(destination);
}
void mergesortRange(int *values, int start, int end) {
int rangeSize = end - start;
if (needsSorting(rangeSize)) {
int midPoint = (start + end) / 2;
mergesortRange(values, start, midPoint);
mergesortRange(values, midPoint, end);
mergeRanges(values, start, midPoint, end);
}
}
void mergesort(int size, int *values) {
mergesortRange(values, 0, size);
}
|
UMM-CSci-3403-Fall-2018/lab-3-memory-management-and-multi-dimensional-arrays-in-c-megabittronmini
|
array_merge/array_merge.c
|
#include<stdlib.h>
#include<stdio.h>
#include"array_merge.h"
#include"../mergesort/mergesort.c"
int* array_merge(int num_arrays, int* sizes, int** values) {
// Count how many elements are in all arrays
int total_values = 0;
for (int i = 0; i < num_arrays; i++) {
total_values += sizes[i];
}
// If there are no elements, return an empty array
if (total_values == 0) {
int* empty_array = (int*) calloc(1, sizeof(int));
return empty_array;
}
// Concatenate elements from all arrays into one array
int* combined_array = (int*) calloc(total_values, sizeof(int));
int k = 0;
for(int i = 0; i < num_arrays; i++) {
for(int j = 0; j < sizes[i]; j++) {
combined_array[k] = values[i][j];
k++;
}
}
// Sort the combined array so we can remove repeated elements later
mergesort(total_values, combined_array);
// Count the repeated elements in the combined array
// Set repeated elements to -1 so we can keep track of values to ignore later
int repeated = 0;
for (int i = total_values - 1; i > 0; i--) {
if (combined_array[i] == combined_array[i-1]) {
combined_array[i] = -1;
repeated++;
}
}
// Create merged array with the proper size
int* merged_array = (int*) calloc(total_values - repeated + 1, sizeof(int));
// Insert the total number of elements at position 0
merged_array[0] = total_values - repeated;
// Set the rest of the elements to be non-repeated values
for (int i = 0, j = 1; i < total_values; i++) {
if (combined_array[i] != -1) {
merged_array[j] = combined_array[i];
j++;
}
}
free(combined_array);
return merged_array;
}
|
Jakobimatrix/warning_guards
|
test/third_party_headers/register.h
|
void f(int x) {
//register int y = 2 * x;
}
|
Jakobimatrix/warning_guards
|
include/warning_guards/warning_guards.h
|
#ifndef COMMON_MACROS_H
#define COMMON_MACROS_H
// clang-format off
/*! Suppresses warnings in third party header files.
* Works with
* - GCC (https://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Pragmas.html)
* - clang (http://clang.llvm.org/docs/UsersManual.html#controlling-diagnostics-via-pragmas)
*
* For reasons GCC can not ignored -Wall, so all warnings have to be ignored
* separatly.
*/
// clang-format on
#ifdef __clang__
#if __clang_major__ >= 8
// clang-format off
#define DISABLE_CLANG_8_WARNINGS \
_Pragma("GCC diagnostic ignored \"-Wextra-semi-stmt\"") \
_Pragma("GCC diagnostic ignored \"-Wempty-init-stmt\"") \
// clang-format on
#else
#define DISABLE_CLANG_8_WARNINGS /*nothing to do here */
#endif
#if __clang_major__ >= 6
// clang-format off
#define DISABLE_CLANG_6_WARNINGS \
_Pragma("GCC diagnostic ignored \"-Wdelete-non-virtual-dtor\"") \
_Pragma("GCC diagnostic ignored \"-Wsign-compare\"") \
_Pragma("GCC diagnostic ignored \"-Wredundant-parens\"") \
_Pragma("GCC diagnostic ignored \"-Woverloaded-virtual\"") \
_Pragma("GCC diagnostic ignored \"-Wnewline-eof\"") \
_Pragma("GCC diagnostic ignored \"-Wundef\"") \
_Pragma("GCC diagnostic ignored \"-Wtautological-constant-compare\"") \
// clang-format on
#else
#define DISABLE_CLANG_6_WARNINGS /*nothing to do here */
#endif
#if __clang_major__ >= 5
// clang-format off
#define DISABLE_CLANG_5_WARNINGS \
_Pragma("GCC diagnostic ignored \"-Wzero-as-null-pointer-constant\"") \
_Pragma("GCC diagnostic ignored \"-Wcast-qual\"") \
_Pragma("GCC diagnostic ignored \"-Wunused-lambda-capture\"") \
_Pragma("GCC diagnostic ignored \"-Wunused-template\"") \
_Pragma("GCC diagnostic ignored \"-Wshadow-field\"") \
_Pragma("GCC diagnostic ignored \"-Wimplicit-fallthrough\"") \
// clang-format on
#else
#define DISABLE_CLANG_5_WARNINGS /*nothing to do here */
#endif
// clang-format off
#define THIRD_PARTY_HEADERS_BEGIN \
_Pragma("GCC diagnostic push") \
_Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"") \
_Pragma("GCC diagnostic ignored \"-Wunused-local-typedefs\"") \
_Pragma("GCC diagnostic ignored \"-Wignored-qualifiers\"") \
_Pragma("GCC diagnostic ignored \"-Wunused-parameter\"") \
_Pragma("GCC diagnostic ignored \"-Wempty-body\"") \
_Pragma("GCC diagnostic ignored \"-Wconversion\"") \
_Pragma("GCC diagnostic ignored \"-Wpedantic\"") \
_Pragma("GCC diagnostic ignored \"-Wold-style-cast\"") \
_Pragma("GCC diagnostic ignored \"-Wnon-virtual-dtor\"") \
_Pragma("GCC diagnostic ignored \"-Wextra-semi\"") \
_Pragma("GCC diagnostic ignored \"-Wdocumentation\"") \
_Pragma("GCC diagnostic ignored \"-Wpedantic\"") \
_Pragma("GCC diagnostic ignored \"-Wpadded\"") \
_Pragma("GCC diagnostic ignored \"-Wdouble-promotion\"") \
_Pragma("GCC diagnostic ignored \"-Wweak-vtables\"") \
_Pragma("GCC diagnostic ignored \"-Wundefined-func-template\"") \
_Pragma("GCC diagnostic ignored \"-Wcomma\"") \
_Pragma("GCC diagnostic ignored \"-Wexit-time-destructors\"") \
_Pragma("GCC diagnostic ignored \"-Wreserved-id-macro\"") \
_Pragma("GCC diagnostic ignored \"-Wdeprecated\"") \
_Pragma("GCC diagnostic ignored \"-Wdocumentation-unknown-command\"") \
_Pragma("GCC diagnostic ignored \"-Wmissing-noreturn\"") \
_Pragma("GCC diagnostic ignored \"-Wglobal-constructors\"") \
_Pragma("GCC diagnostic ignored \"-Wundefined-reinterpret-cast\"") \
_Pragma("GCC diagnostic ignored \"-Wused-but-marked-unused\"") \
_Pragma("GCC diagnostic ignored \"-Wcast-align\"") \
_Pragma("GCC diagnostic ignored \"-Wfloat-equal\"") \
_Pragma("GCC diagnostic ignored \"-Wswitch-enum\"") \
_Pragma("GCC diagnostic ignored \"-Wshift-sign-overflow\"") \
_Pragma("GCC diagnostic ignored \"-Wformat-nonliteral\"") \
_Pragma("GCC diagnostic ignored \"-Wcovered-switch-default\"") \
_Pragma("GCC diagnostic ignored \"-Wmismatched-tags\"") \
_Pragma("GCC diagnostic ignored \"-Wzero-as-null-pointer-constant\"") \
_Pragma("GCC diagnostic ignored \"-Wreturn-type-c-linkage\"") \
_Pragma("GCC diagnostic ignored \"-Wmissing-variable-declarations\"") \
_Pragma("GCC diagnostic ignored \"-Wused-but-marked-unused\"") \
_Pragma("GCC diagnostic ignored \"-Wunused-variable\"") \
DISABLE_CLANG_5_WARNINGS \
DISABLE_CLANG_6_WARNINGS \
DISABLE_CLANG_8_WARNINGS \
// clang-format on
#else
#if __GNUC__ >= 8
// clang-format off
#define DISABLE_GCC_8_WARNINGS \
_Pragma("GCC diagnostic ignored \"-Wmultistatement-macros\"") \
_Pragma("GCC diagnostic ignored \"-Wstringop-truncation\"") \
_Pragma("GCC diagnostic ignored \"-Wcast-function-type\"") \
_Pragma("GCC diagnostic ignored \"-Wsizeof-pointer-div\"") \
_Pragma("GCC diagnostic ignored \"-Wcast-align=strict\"") \
_Pragma("GCC diagnostic ignored \"-Warray-bounds\"") \
_Pragma("GCC diagnostic ignored \"-Wclass-memaccess\"") \
// clang-format on
#else
#define DISABLE_GCC_8_WARNINGS /*nothing to do here */
#endif
#if __GNUC__ >= 7
// clang-format off
#define DISABLE_GCC_7_WARNINGS \
_Pragma("GCC diagnostic ignored \"-Wregister\"") \
_Pragma("GCC diagnostic ignored \"-Wshadow=local\"") \
_Pragma("GCC diagnostic ignored \"-Wshadow=compatible-local\"") \
_Pragma("GCC diagnostic ignored \"-Wimplicit-fallthrough\"") \
_Pragma("GCC diagnostic ignored \"-Wmemset-elt-size\"") \
_Pragma("GCC diagnostic ignored \"-Wint-in-bool-context\"") \
_Pragma("GCC diagnostic ignored \"-Wswitch-unreachable\"") \
_Pragma("GCC diagnostic ignored \"-Wexpansion-to-defined\"") \
_Pragma("GCC diagnostic ignored \"-Wdangling-else\"") \
// clang-format on
#else
#define DISABLE_GCC_7_WARNINGS /*nothing to do here */
#endif
#if __GNUC__ >= 6
// clang-format off
#define DISABLE_GCC_6_WARNINGS \
_Pragma("GCC diagnostic ignored \"-Wduplicated-cond\"") \
_Pragma("GCC diagnostic ignored \"-Wshift-negative-value\"") \
_Pragma("GCC diagnostic ignored \"-Wtautological-compare\"") \
_Pragma("GCC diagnostic ignored \"-Wmisleading-indentation\"") \
// clang-format on
#else
#define DISABLE_GCC_6_WARNINGS /*nothing to do here */
#endif
#if __GNUC__ >= 5
// clang-format off
#define DISABLE_GCC_5_WARNINGS \
_Pragma("GCC diagnostic ignored \"-Wswitch-bool\"") \
_Pragma("GCC diagnostic ignored \"-Wlogical-not-parentheses\"") \
_Pragma("GCC diagnostic ignored \"-Wbool-compare\"") \
_Pragma("GCC diagnostic ignored \"-Wsuggest-override\"") \
_Pragma("GCC diagnostic ignored \"-Wsuggest-final-types\"") \
_Pragma("GCC diagnostic ignored \"-Wsuggest-final-methods\"") \
// clang-format on
#else
#define DISABLE_GCC_5_WARNINGS /*nothing to do here */
#endif
// clang-format off
#define THIRD_PARTY_HEADERS_BEGIN \
_Pragma("GCC diagnostic push") \
_Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"") \
_Pragma("GCC diagnostic ignored \"-Wunused-local-typedefs\"") \
_Pragma("GCC diagnostic ignored \"-Wunused-but-set-parameter\"") \
_Pragma("GCC diagnostic ignored \"-Wuseless-cast\"") \
_Pragma("GCC diagnostic ignored \"-Wignored-qualifiers\"") \
_Pragma("GCC diagnostic ignored \"-Wunused-parameter\"") \
_Pragma("GCC diagnostic ignored \"-Wempty-body\"") \
_Pragma("GCC diagnostic ignored \"-Wconversion\"") \
_Pragma("GCC diagnostic ignored \"-Wformat=\"") \
_Pragma("GCC diagnostic ignored \"-Wold-style-cast\"") \
_Pragma("GCC diagnostic ignored \"-Wnon-virtual-dtor\"") \
_Pragma("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") \
_Pragma("GCC diagnostic ignored \"-Wzero-as-null-pointer-constant\"") \
_Pragma("GCC diagnostic ignored \"-Wcast-qual\"") \
_Pragma("GCC diagnostic ignored \"-Wlogical-op\"") \
_Pragma("GCC diagnostic ignored \"-Wredundant-decls\"") \
_Pragma("GCC diagnostic ignored \"-Wconversion\"") \
_Pragma("GCC diagnostic ignored \"-Wfloat-conversion\"") \
_Pragma("GCC diagnostic ignored \"-Wpedantic\"") \
_Pragma("GCC diagnostic ignored \"-Wsign-compare\"") \
_Pragma("GCC diagnostic ignored \"-Wunused-variable\"") \
DISABLE_GCC_5_WARNINGS \
DISABLE_GCC_6_WARNINGS \
DISABLE_GCC_7_WARNINGS \
DISABLE_GCC_8_WARNINGS \
// clang-format on
#endif
// clang-format off
#define THIRD_PARTY_HEADERS_END \
_Pragma("GCC diagnostic pop")
// clang-format on
#endif
|
Jakobimatrix/warning_guards
|
test/third_party_headers/oldstyle_cast.h
|
<reponame>Jakobimatrix/warning_guards
int f(double x) {
return (int)x;
}
|
HPTears/TimeSeparateHelper
|
XKTimeSeparateHelper/Classes/XKTimeSeparateHelper.h
|
<reponame>HPTears/TimeSeparateHelper
//
// XKTimeSeparateHelper.h
// TimeSeparate
//
// Created by hupan on 2018/8/2.
// Copyright © 2018年 Tears. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface XKTimeSeparateHelper : NSObject
/**
根据NSDate 返回年月 字符串 通过汉字分割
@param date date
@return 返回年月,通过汉字分割
*/
+ (NSString *)backYMStringByChineseSegmentWithDate:(NSDate *)date;
/**
根据时间字符串 返回年月 Date 通过汉字分割
@param timeString timeString
@return 返回年月,通过汉字分割
*/
+ (NSDate *)backYMDateByChineseSegmentWithTimeString:(NSString *)timeString;
/**
根据时间戳string 返回年月 字符串 通过汉字分割
@param timestampString timestampString
@return 返回年月,通过汉字分割
*/
+ (NSString *)backYMStringByChineseSegmentWithTimestampString:(NSString *)timestampString;
/**
根据NSDate 返回年月日 字符串 通过汉字分割
@param date date
@return 返回年月日,通过汉字分割
*/
+ (NSString *)backYMDStringByChineseSegmentWithDate:(NSDate *)date;
/**
根据时间字符串 返回年月日 Date 通过汉字分割
@param timeString timeString
@return 返回年月日,通过汉字分割
*/
+ (NSDate *)backYMDDateByChineseSegmentWithTimeString:(NSString *)timeString;
/**
根据时间戳string 返回年月日 字符串 通过汉字分割
@param timestampString timestampString
@return 返回年月日,通过汉字分割
*/
+ (NSString *)backYMDStringByChineseSegmentWithTimestampString:(NSString *)timestampString;
/**
根据NSDate 返回年月日时分字符串 通过汉字分割
@param date date
@return 返回年月日时分,通过汉字分割
*/
+ (NSString *)backYMDHMStringByChineseSegmentWithDate:(NSDate *)date;
/**
根据NSDate 返回年月日 周 时分字符串 通过汉字分割
@param date date
@return 返回年月日周时分,通过汉字分割
*/
+ (NSString *)backYMDWeekHMStringByChineseSegmentWithDate:(NSDate *)date;
/**
根据NSDate 返回年月日 周 时分字符串 通过汉字分割
@param date date
@return 返回年月日周时分,通过汉字分割
*/
+ (NSString *)backYMDWeakHMStringByVirguleSegmentWithDate:(NSDate *)date;
/**
根据时间字符串 返回年月日时分 Date 通过汉字分割
@param timeString timeString
@return 返回年月日时分,通过汉字分割
*/
+ (NSDate *)backYMDHMDateByChineseSegmentWithTimeString:(NSString *)timeString;
/**
根据时间戳string 返回年月日时分字符串 通过汉字分割
@param timestampString timestampString
@return 返回年月日时分,通过汉字分割
*/
+ (NSString *)backYMDHMStringByChineseSegmentWithTimestampString:(NSString *)timestampString;
/**
根据NSDate 返回年月日时分秒字符串 通过汉字分割
@param date date
@return 返回年月日时分秒,通过汉字分割
*/
+ (NSString *)backYMDHMSStringByChineseSegmentWithDate:(NSDate *)date;
/**
根据时间字符串 返回年月日时分秒 Date 通过汉字分割
@param timeString timeString
@return 返回年月日时分秒,通过汉字分割
*/
+ (NSDate *)backYMDHMSDateByChineseSegmentWithTimeString:(NSString *)timeString;
/**
根据时间戳string 返回年月日时分秒字符串 通过汉字分割
@param timestampString timestampString
@return 返回年月日时分秒,通过汉字分割
*/
+ (NSString *)backYMDHMSStringByChineseSegmentWithTimestampString:(NSString *)timestampString;
/**
根据NSDate 返回年月 字符串 通过斜线分割
@param date date
@return 返回年月,通过斜线分割
*/
+ (NSString *)backYMStringByVirguleSegmentWithDate:(NSDate *)date;
/**
根据时间字符串 返回年月 Date 通过斜线分割
@param timeString timeString
@return 返回年月,通过斜线分割
*/
+ (NSDate *)backYMDateByVirguleSegmentWithTimeString:(NSString *)timeString;
/**
根据时间戳string 返回年月 字符串 通过斜线分割
@param timestampString timestampString
@return 返回年月,通过斜线分割
*/
+ (NSString *)backYMStringByVirguleSegmentWithTimestampString:(NSString *)timestampString;
/**
根据NSDate 返回年月日 字符串 通过斜线分割
@param date date
@return 返回年月日,通过斜线分割
*/
+ (NSString *)backYMDStringByVirguleSegmentWithDate:(NSDate *)date;
/**
根据时间字符串 返回年月日 Date 通过斜线分割
@param timeString timeString
@return 返回年月日,通过斜线分割
*/
+ (NSDate *)backYMDDateByVirguleSegmentWithTimeString:(NSString *)timeString;
/**
根据时间戳string 返回年月日 字符串 通过斜线分割
@param timestampString timestampString
@return 返回年月日,通过斜线分割
*/
+ (NSString *)backYMDStringByVirguleSegmentWithTimestampString:(NSString *)timestampString;
/**
根据NSDate 返回年月日时分 字符串 通过斜线分割
@param date date
@return 返回年月日时分,通过斜线分割
*/
+ (NSString *)backYMDHMStringByVirguleSegmentWithDate:(NSDate *)date;
/**
根据时间字符串 返回年月日时分 Date 通过斜线分割
@param timeString timeString
@return 返回年月日时分,通过斜线分割
*/
+ (NSDate *)backYMDHMDateByVirguleSegmentWithTimeString:(NSString *)timeString;
/**
根据时间戳string 返回年月日时分 字符串 通过斜线分割
@param timestampString timestampString
@return 返回年月日时分,通过斜线分割
*/
+ (NSString *)backYMDHMStringByVirguleSegmentWithTimestampString:(NSString *)timestampString;
/**
根据时间戳string 返回年月日字符串 通过点分割
@param timestampString timestampString
@return 返回年月日,通过点分割
*/
+ (NSString *)backYMDHMStringByPointWithTimestampString:(NSString *)timestampString;
/**
根据NSDate 返回年月日时分秒 字符串 通过斜线分割
@param date date
@return 返回年月日时分,通过斜线分割
*/
+ (NSString *)backYMDHMSStringByVirguleSegmentWithDate:(NSDate *)date;
/**
根据时间字符串 返回年月日时分秒 Date 通过斜线分割
@param timeString timeString
@return 返回年月日时分,通过斜线分割
*/
+ (NSDate *)backYMDHMSDateByVirguleSegmentWithTimeString:(NSString *)timeString;
/**
根据时间戳string 返回年月日时分秒 字符串 通过斜线分割
@param timestampString timestampString
@return 返回年月日时分,通过斜线分割
*/
+ (NSString *)backYMDHMSStringByVirguleSegmentWithTimestampString:(NSString *)timestampString;
/**
根据NSDate 返回年月 字符串 通过短横线分割
@param date date
@return 返回年月,通过短横线分割
*/
+ (NSString *)backYMStringByStrigulaSegmentWithDate:(NSDate *)date;
/**
根据时间字符串 返回年月 Date 通过短横线分割
@param timeString timeString
@return 返回年月,通过短横线分割
*/
+ (NSDate *)backYMDateByStrigulaSegmentWithTimeString:(NSString *)timeString;
/**
根据时间戳string 返回年月 字符串 通过短横线分割
@param timestampString timestampString
@return 返回年月,通过短横线分割
*/
+ (NSString *)backYMStringByStrigulaSegmentWithTimestampString:(NSString *)timestampString;
/**
根据NSDate 返回年月日 字符串 通过短横线分割
@param date date
@return 返回年月日,通过短横线分割
*/
+ (NSString *)backYMDStringByStrigulaSegmentWithDate:(NSDate *)date;
/**
根据时间字符串 返回年月日 Date 通过短横线分割
@param timeString timeString
@return 返回年月日,通过短横线分割
*/
+ (NSDate *)backYMDDateByStrigulaSegmentWithTimeString:(NSString *)timeString;
/**
根据时间戳string 返回年月日 字符串 通过短横线分割
@param timestampString timestampString
@return 返回年月日,通过短横线分割
*/
+ (NSString *)backYMDStringByStrigulaSegmentWithTimestampString:(NSString *)timestampString;
/**
根据NSDate 返回年月日时分 字符串 通过短横线分割
@param date date
@return 返回年月日时分,通过短横线分割
*/
+ (NSString *)backYMDHMStringByStrigulaSegmentWithDate:(NSDate *)date;
/**
根据时间字符串 返回年月日时分 Date 通过短横线分割
@param timeString timeString
@return 返回年月日时分,通过短横线分割
*/
+ (NSDate *)backYMDHMDateByStrigulaSegmentWithTimeString:(NSString *)timeString;
/**
根据时间戳string 返回年月日时分 字符串 通过短横线分割
@param timestampString timestampString
@return 返回年月日时分,通过短横线分割
*/
+ (NSString *)backYMDHMStringByStrigulaSegmentWithTimestampString:(NSString *)timestampString;
/**
根据NSDate 返回年月日时分秒 字符串 通过短横线分割
@param date date
@return 返回年月日时分秒,通过短横线分割
*/
+ (NSString *)backYMDHMSStringByStrigulaSegmentWithDate:(NSDate *)date;
/**
根据时间字符串 返回年月日时分秒 Date 通过短横线分割
@param timeString timeString
@return 返回年月日时分秒,通过短横线分割
*/
+ (NSDate *)backYMDHMSDateByStrigulaSegmentWithTimeString:(NSString *)timeString;
/**
根据时间戳string 返回年月日时分秒 字符串 通过短横线分割
@param timestampString timestampString
@return 返回年月日时分秒,通过短横线分割
*/
+ (NSString *)backYMDHMSStringByStrigulaSegmentWithTimestampString:(NSString *)timestampString;
//年月日时分秒
+ (NSString *)backYMDHMSSStringByVirguleSegmentWithTimestampString:(NSString *)timestampString;
/**
根据NSDate 返回年 字符串
@param date date
@return 根据NSDate 返回年 字符串
*/
+ (NSString *)backYearStringWithDate:(NSDate *)date;
/**
根据NSDate 返回月 字符串
@param date date
@return 根据NSDate 返回月 字符串
*/
+ (NSString *)backMonthStringWithDate:(NSDate *)date;
/**
根据NSDate 返回日 字符串
@param date date
@return 根据NSDate 返回日 字符串
*/
+ (NSString *)backDayStringWithDate:(NSDate *)date;
/**
根据NSDate 返回月日 字符串
@param date date
@return 根据NSDate 返回月日 字符串
*/
+ (NSString *)backMonthAndDayStringWithDate:(NSDate *)date;
/**
根据NSDate 返回时分秒 字符串
@param date date
@return 根据NSDate 返回时分秒 字符串
*/
+ (NSString *)backHMSStringWithDate:(NSDate *)date;
/**
根据NSDate 返回时 字符串
@param date date
@return 根据NSDate 返回时 字符串
*/
+ (NSString *)backHStringWithDate:(NSDate *)date;
/**
根据NSDate 返回星期几 字符串
@param date date
@return 根据NSDate 返回星期几 字符串
*/
+ (NSString *)backWeekStringWithDate:(NSDate *)date;
/**
计算指定日期 指定天数 后的新日期
@param days days
@param timeString timeString
@return 计算指定日期 指定天数 后的新日期
*/
+ (NSString *)backNewDateWithDays:(NSInteger)days fromTimeString:(NSString *)timeString;
/**
返回两日期相差天数
@param startDateStr 开始时期
@param endDateStr 结束时间
@return 返回两个日期相差天数
*/
+ (NSInteger)backDaysWithStartDateStr:(NSString *)startDateStr endDateStr:(NSString *)endDateStr;
/**
返回指定月份天数
@param dateStr 2019-09
@return 返回指定月份天数
*/
+ (NSInteger)backDaysOfCountMonthWithDateStr:(NSString *)dateStr;
/**
返回指定时间戳与当前系统时间的时间差(秒)
@param stampString 时间戳
@return 返回指定时间戳与当前系统时间的时间差(秒)
*/
+ (NSInteger)backSecondWithTimestampString:(NSString *)stampString;
/**
根据日期Date 返回时间戳(精确到毫秒)
@param date date
@return 根据日期返回时间戳(精确到毫秒)
*/
+ (NSString *)backTimestampStringWithDate:(NSDate *)date;
//根据日期返回时间戳(精确到秒)
+ (NSString *)backTimestampSecondStringWithDate:(NSDate *)date;
/**
根据时间timeString 返回时间戳(
@param timeString timeString
@return 根据时间timeString 返回时间戳
*/
+ (NSString *)backTimestampStringWithTimeString:(NSString *)timeString;
/**
根据年月日string返回时间戳
@param timeString timeString
@return 根据年月日string返回时间戳
*/
+ (NSString *)backTimestampStringWithYMDTimeString:(NSString *)timeString;
/**
根据年月日 时分秒 timestring返回时间戳
@param timeString timeString
@return 根据年月日 时分秒 timestring返回时间戳
*/
+ (NSString *)backTimestampStringWithYMDHMSTimeString:(NSString *)timeString;
/**
根据年月日 时分 string返回时间戳
@param timeString timeString
@return 根据年月日 时分timestring返回时间戳
*/
+ (NSString *)backTimestampStringWithYMDHMTimeString:(NSString *)timeString;
/**
根据年月string返回时间戳
@param timeString timeString
@return 根据年月string返回时间戳
*/
+ (NSString *)backTimestampStringWithYMTimeString:(NSString *)timeString;
/**
根据时间timeString(2018-08-09 11:20:32:23) 返回自定义时间(xx小时前)
@param timeString timeString
@return 根据时间timeString(2018-08-09 11:20:32:23) 返回自定义时间(xx小时前)
*/
+ (NSString *)customTimeStyleWithTimeString:(NSString *)timeString;
/**
根据时间戳timestampString(127938373746) 返回自定义时间(xx小时前)
@param timestampString timestampString
@return 根据时间戳timestampString(127938373746) 返回自定义时间(xx小时前)
*/
+ (NSString *)customTimeStyleWithTimestampString:(NSString *)timestampString;
/**根据时间戳返回指定格式的时间 秒级时间戳*/
+ (NSString *)backStringWithFormatString:(NSString *)formatString timestampStringSecond:(NSString *)timestampString;
/**获取年龄*/
+ (NSString *)backAgeWithBrithdayTimeStampString:(NSString *)timeString;
/**
根据时间戳string 返回年月日时分 字符串 或者月时分(年相同时) 通过短横线分割
@param timestampString timestampString
@return 返回年月日时分 字符串 或者月时分(年相同时) 通过短横线分割
*/
+ (NSString *)backYMDHMOrMDHMStringWithTimestampString:(NSString *)timestampString;
@end
|
HPTears/TimeSeparateHelper
|
XKTimeSeparateHelper/Classes/XKTimeManager.h
|
<gh_stars>0
//
// XKTimeManager.h
// TimeSeparate
//
// Created by hupan on 2018/8/2.
// Copyright © 2018年 Tears. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface XKTimeManager : NSObject
@property (nonatomic, strong) NSDateFormatter *dateFormatter;
+ (instancetype)timeShareManager;
@end
|
MartinPippel/DAmar
|
msa/realigner.c
|
<filename>msa/realigner.c
/*****************************************************************************************\
* * *
* * These routines improve a multi-alignment of DNA sequences *
* * *
* * This is a re-implementation of realigner, the original by <NAME>, ~1997 and the *
* * algorithm design by <NAME>. This code is pretty much a complete rewrite *
* * although the spirit of the original code is retained with some coding refinements *
* * to improve space and time performance. The code is also modularized and commented *
* * so that other hackers can potentially integrate the code directly into another *
* * program. *
* * *
* * Routines have been added to build an initial multialignment from pairwise overlaps *
* * and to deliver columns and rows of the multi-alignment. The construction routines *
* * are space inefficient and could use a D&C alignment delivering approach but I have *
* * not as yet had the time to craft such a complicated code. *
* * *
* * Author: <NAME> *
* * Date : March 2007 *
* * *
* \*****************************************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include "realigner.h"
#undef DEBUG
#undef STATS
#undef CHECK_PRINT
#undef CHECK_MEMORY
#undef DEBUG_REALIGN
#undef DEBUG_SMALL /* Turn on if fragments are small, makes prettier debug display */
#undef SHOW_CUMULATIVE_SCORE /* Prints cumulative column score with alignment
in re_print_contig */
#define MIX .5 /* Mixture ratio of derivative vs. consensus score to use in realigning */
#define ALONE .5 /* Score for realigning a char in its own column (at a boundary) */
#define INIT_MAX_CONTIG_DEPTH 128
#define INIT_MAX_FRAG_LENGTH 1024
#define SPACE_GROWTH_RATE 1.2
#define LIST_SPACE_BLOCK_SIZE 8192
#define MAX_CODE 5
#define DASH_CODE 4 /* Code for -'s must be second to last code */
#define N_CODE 5 /* Code for N's must be the last code */
/* Internally a multi-alignment is represented as a sparse matrix of symbols
* that are in doubly-linked, circular, and anchored column and fragment sequence
* lists. The anchors of the column lists are themselves doubly-linked into
* a sequential list and further contain summary information on the frequency of
* characters in the column (ACGT-N --> 0-5). The list of columns is terminated at each
* end by an anchor ('first' and 'last') with an empty column. The anchors of each
* fragment are in a singly-linked list, in no particular order, have a '\0' char
* as their letter, and further contain a pointer to the column anchor containing
* the fragment's first character.
*
* NB: Leading and trailing '-'s are removed from fragments when they are read
* in. This may give rise to an empty fragment. These are not removed, but
* simply checked for where necessary and then ignored.
* */
typedef struct re_symbol
{ struct re_symbol *up; /* double column chain links */
struct re_symbol *down;
struct re_symbol *prev; /* double fragment sequence links */
struct re_symbol *next;
int letter; /* letter at position */
} re_symbol;
typedef struct re_column
{ struct re_symbol *up; /* anchor of circular, doubly-linked column chain */
struct re_symbol *down;
struct re_column *pred; /* double column node link */
struct re_column *succ;
int depth; /* total number of symbols in column */
int count[MAX_CODE+1]; /* number of each type of symbol in column */
/* Used during realignment: */
int bound; /* inter-column position to left is a boundary */
float score[MAX_CODE+1]; /* alignment scores for realignment */
} re_column;
typedef struct re_fragment
{ struct re_fragment *link; /* single linked list of fragment records */
struct re_column *scol; /* first column containing a symbol of the fragment */
struct re_symbol *prev; /* anchor of circular, doubly linked fragment sequence */
struct re_symbol *next;
int letter; /* '\0' char to identify record as a fragment and not a symbol */
int row; /* row sequence was on when input */
} re_fragment;
typedef struct
{ re_fragment *frags; /* anchor of singly-linked fragment list */
re_column *first; /* first and last columns of contig */
re_column *last;
} re_contig;
static int *encode = NULL; /* Map DNA + '-' to [0,MAX_CODE] */
static void setup_encode()
{ static int _encode[128];
int i;
encode = _encode;
for (i = 0; i < 128; i++)
encode[i] = 5;
encode['a'] = encode['A'] = 0;
encode['c'] = encode['C'] = 1;
encode['g'] = encode['G'] = 2;
encode['t'] = encode['T'] = 3;
encode['-'] = 4;
}
/* Uniform list space of symbol, column and fragment records
* (one macro defines all) */
static int avail_cells = 0;
#define LIST_SPACE(type,new_routine,free_routine,free_ptr,free_link) \
\
static type *free_ptr = NULL; \
\
static type *new_routine(void) \
{ type *ptr; \
\
if (free_ptr == NULL) \
{ int i; \
free_ptr = ptr = (type *) \
malloc(sizeof(type)*LIST_SPACE_BLOCK_SIZE); \
for (i = 0; i < LIST_SPACE_BLOCK_SIZE; i++) \
{ ptr->free_link = ptr+1; \
ptr += 1; \
} \
ptr[-1].free_link = NULL; \
avail_cells += LIST_SPACE_BLOCK_SIZE; \
} \
\
ptr = free_ptr; \
free_ptr = ptr->free_link; \
return (ptr); \
} \
\
static void free_routine(type *ptr) \
{ ptr->free_link = free_ptr; \
free_ptr = ptr; \
}
LIST_SPACE(re_symbol,new_symbol,free_symbol,free_symbol_ptr,next)
LIST_SPACE(re_column,new_column,free_column,free_column_ptr,succ)
LIST_SPACE(re_fragment,new_fragment,free_fragment,free_fragment_ptr,link)
#ifdef CHECK_MEMORY
static void check_memory()
{ re_symbol *s;
re_column *c;
re_fragment *f;
int free_cells;
free_cells = 0;
for (s = free_symbol_ptr; s != NULL; s = s->next)
free_cells += 1;
for (c = free_column_ptr; c != NULL; c = c->succ)
free_cells += 1;
for (f = free_fragment_ptr; f != NULL; f = f->link)
free_cells += 1;
fprintf(stderr,"Avail %d Free %d\n",avail_cells,free_cells);
}
#endif
Re_Contig *Re_Read_Contig(FILE *input, FILE *comments)
{ static re_contig readctg;
int sym;
re_column *curcol, *firstcol;
re_fragment *frags;
if (encode == NULL)
setup_encode();
/* Start with empty first column, and empty fragment list */
firstcol = curcol = new_column();
curcol->up = curcol->down = (re_symbol *) curcol;
curcol->pred = NULL;
frags = NULL;
/* NB: The "trick" in this code is that elements containing blank are initially
* placed in a column and then removed after the succeeding column is built. This
* allows one to easily detect when a new fragment is starting, i.e. blank in the
* previous column & non-blank in the current column of a *corresponding* row. */
do
{ if (firstcol != curcol) /* Not first time through this loop ==> saw a blank line */
{ free_column(curcol); /* on the last pass, clean up and start over */
curcol = firstcol;
}
do
{ re_column *prevcol;
re_symbol *p, *e;
int row;
sym = fgetc(input);
while (sym == '%') /* Pass on any comment lines if comments != NULL */
{ while (sym != '\n')
{ if (comments != NULL)
fputc(sym,comments);
sym = fgetc(input);
}
if (comments != NULL)
fputc('\n',comments);
sym = fgetc(input);
}
/* Add new, initially empty column */
prevcol = curcol;
curcol = new_column();
curcol->up = curcol->down = (re_symbol *) curcol;
prevcol->succ = curcol;
curcol->pred = prevcol;
{ int i;
for (i = 0; i <= MAX_CODE; i++)
curcol->count[i] = 0;
}
curcol->depth = 0;
/* Add symbols to the new column (including blanks), traversing previous one
* in synchrony in order to detect new fragment beginnings. If a new fragment
* begins with -'s, turn them into blanks and delay starting the fragment */
p = (re_symbol *) prevcol->down;
row = 0;
if (sym != EOF)
while (sym != '\n')
{ e = new_symbol();
e->down = (re_symbol *) curcol;
e->up = curcol->up;
e->down->up = e->up->down = e;
if (sym != ' ')
{ if (p == (re_symbol *) prevcol || p->letter == ' ') /* New fragment? */
if (sym == '-') /* Starts with -? */
sym = ' ';
else
{ re_fragment *f;
f = new_fragment();
f->scol = curcol;
f->letter = '\0';
f->link = frags;
f->row = row;
frags = f;
e->prev = e->next = (re_symbol *) f;
}
else
{ e->prev = p;
e->next = p->next;
}
if (sym != ' ')
{ e->prev->next = e->next->prev = e;
curcol->count[encode[sym]] += 1;
curcol->depth += 1;
}
}
e->letter = sym;
if (p != (re_symbol *) prevcol) /* Keep from running off the end */
p = p->down;
sym = fgetc(input);
row += 1;
}
/* Purge blank symbols from the previous column, and
* if a fragment ends with -'s peel them back. */
{ re_symbol *q, *r;
re_column *c;
e = curcol->down;
for (p = prevcol->down; p != (re_symbol *) prevcol; p = q)
{ q = p->down;
if (p->letter == ' ')
{ q->up = p->up;
p->up->down = q;
free_symbol(p);
}
else if (e == (re_symbol *) curcol || e->letter == ' ')
{ for (c = prevcol; p->letter == '-'; p = r)
{ r = p->prev;
p->next->prev = r;
r->next = p->next;
p->up->down = p->down;
p->down->up = p->up;
free_symbol(p);
c->count[DASH_CODE] -= 1;
c->depth -= 1;
c = c->pred;
}
}
if (e != (re_symbol *) curcol)
e = e->down;
}
}
}
while (curcol->depth > 0);
{ re_symbol *s; /* Remove any blank cells from the last column */
while ((s = curcol->down) != (re_symbol *) curcol)
{ s->up->down = s->down;
s->down->up = s->up;
free_symbol(s);
}
}
}
while (sym != EOF && firstcol->succ == curcol);
curcol->succ = NULL;
if (firstcol->succ == curcol) /* Nothing but zero or more blank lines and then EOF */
{ free_column(curcol); /* Free columns and return NULL */
free_column(firstcol);
return (NULL);
}
/* Fill in the contig record */
readctg.frags = frags;
readctg.first = firstcol;
readctg.last = curcol;
return ((Re_Contig *) (&readctg));
}
typedef struct
{ int next; /* Next unallocated row (in ordinal order) */
re_symbol *token; /* Current symbol element for this row, or NULL if unallocated */
} rowrec;
void Re_Print_Contig(Re_Contig *contig, FILE *output, int samerows)
{ static rowrec *row;
static int avail;
static int maxrows = 0;
#ifdef SHOW_CUMULATIVE_SCORE
int score;
#endif
re_column *col;
rowrec *top;
/* We keep an array, row[0..maxrows-1], that expands as necessary so that we
* can have a record row[i] for each row in which a fragment will be displayed.
* Each fragment is printed in a row in such a way that fragments in a given row
* are separated by at least one blank. At a given column, the top row 'top'
* that contains a fragment is maintained. A list of the rows to which
* a new fragment can be assigned is in the singly linked list anchored at
* avail and the list is ordered according to increasing row number. Integer
* indices into rows are used for the avail list as it may be moved by realloc. */
if (maxrows == 0)
{ rowrec *r;
maxrows = INIT_MAX_CONTIG_DEPTH;
row = (rowrec *) malloc(sizeof(rowrec)*maxrows);
for (r = row+(maxrows-1); r >= row; r--)
{ r->next = (r+1) - row;
r->token = NULL;
}
}
#ifdef SHOW_CUMULATIVE_SCORE
score = 0;
#endif
top = row-1;
avail = 0;
for (col = ((re_contig *) contig)->first->succ; col != NULL; col = col->succ)
{ rowrec *r;
re_symbol *s;
/* Examine column to find fragments starts and allocate them to new rows */
for (s = col->down; s != (re_symbol *) col; s = s->down)
if (s->prev->letter == '\0')
{ int slot;
if (samerows)
{ slot = ((re_fragment *) (s->prev))->row;
if (slot < maxrows && row[slot].token != NULL)
slot = avail;
}
else
slot = avail;
if (slot >= maxrows)
{ int oldmax;
oldmax = maxrows;
maxrows = SPACE_GROWTH_RATE*slot + INIT_MAX_CONTIG_DEPTH;
row = (rowrec *) realloc(row,sizeof(rowrec)*maxrows);
top = row + oldmax;
for (r = row+(maxrows-1); r >= top; r--)
{ r->next = (r+1) - row;
r->token = NULL;
}
if (avail != oldmax)
{ rowrec *t;
t = row + avail;
while (t->next != oldmax)
t = row + (t->next);
t->next = oldmax;
}
}
r = row + slot;
if (slot != avail)
{ rowrec *t;
t = row + avail;
while (t->next != slot)
t = row + (t->next);
t->next = r->next;
}
else
avail = r->next;
if (r > top) top = r;
r->token = s->prev;
}
#ifdef SHOW_CUMULATIVE_SCORE
{ int i, max;
max = col->count[DASH_CODE];
for (i = 0; i < DASH_CODE; i++)
if (col->count[i] > max)
max = col->count[i];
score += (col->depth-max);
}
#endif
/* Advance all active row pointers and rebuild avail
* list of all unallocated rows in the range row..top */
avail = (top+1) - row;
for (r = top; r >= row; r--)
{ if ((s = r->token) != NULL)
{ r->token = (s = s->next);
if (s->letter == '\0')
r->token = (s = NULL);
}
if (s == NULL)
{ r->next = avail;
avail = r - row;
if (r == top) top -= 1;
}
}
/* Print the current row */
for (r = row; r <= top; r++)
if ((s = r->token) == NULL)
fputc(' ',output);
else
fputc(s->letter,output);
#ifdef SHOW_CUMULATIVE_SCORE
fprintf(output," %d",score);
#endif
fputc('\n',output);
}
#ifdef CHECK_PRINT
{ rowrec *r;
if (top >= row)
fprintf(stderr,"Top is not reset correctly = %d\n",top-row);
for (r = row; r < row + (maxrows-1); r++)
if (r->next != (r+1)-row)
fprintf(stderr,"Free list broken %d->%d\n",r-row,r->next);
r = row + (maxrows-1);
if (r->next != maxrows)
fprintf(stderr,"Free list broken %d->%d\n",r-row,r->next);
if (avail != 0)
fprintf(stderr,"Free list broken Free->%d\n",r-row,r->next);
}
#endif
}
void Re_Print_Model(Re_Contig *contig, FILE *output)
{ int i;
re_column *c;
fprintf(output,"\n");
for (c = ((re_contig *) contig)->first; c != NULL; c = c->succ)
{ fprintf(output,"%p: ",c);
for (i = 0; i <= MAX_CODE; ++i)
fprintf(output,"%d ",c->count[i]);
fprintf(output,"\n");
}
fflush(output);
}
void Re_Print_Structure(Re_Contig *contig, FILE *output)
{ re_column *c;
re_fragment *f;
re_symbol *s;
int i;
fprintf(output,"\nContig dump:\n");
for (c = ((re_contig *) contig)->first; c != NULL; c = c->succ)
{ fprintf(output,"Column %p: ",c);
for (i = 0; i <= MAX_CODE; i++)
fprintf(output,"%d ",c->count[i]);
fprintf(output,"+= %d\n ",c->depth);
for (s = c->down; s != (re_symbol *) c; s = s->down)
fprintf(output," %c",s->letter);
fprintf(output,"\n");
}
for (f = ((re_contig *) contig)->frags; f != NULL; f = f->link)
{ fprintf(output,"Fragment %p(%p)\n '",f,f->scol);
for (s = f->next; s != (re_symbol *) f; s = s->next)
fprintf(output,"%c",s->letter);
fprintf(output,"'\n");
}
fflush(output);
}
void Re_Free_Contig(Re_Contig *contig)
{ re_contig *ctg = (re_contig *) contig;
re_fragment *f, *g;
re_symbol *s;
/* Each fragment list can be linked onto its free list as a
* linked block, as can the entire list of column anchors */
for (f = ctg->frags; f != NULL; f = g)
{ g = f->link;
s = (re_symbol *) f;
if (s != s->next)
{ s->prev->next = free_symbol_ptr;
free_symbol_ptr = s->next;
}
free_fragment(f);
}
ctg->last->succ = free_column_ptr;
free_column_ptr = ctg->first;
}
Re_Contig *Re_Start_Contig(int id, char *seq)
{ static re_contig seedctg;
re_column *c, *d;
re_symbol *e, *f;
char *s;
re_column *first, *last;
re_fragment *frag;
if (encode == NULL)
setup_encode();
d = first = new_column();
d->down = d->up = (re_symbol *) d;
d->pred = NULL;
f = (re_symbol *) (frag = new_fragment());
for (s = seq; *s != '\0'; s++)
{ c = new_column();
e = new_symbol();
c->down = c->up = e;
e->down = e->up = (re_symbol *) c;
e->letter = *s;
c->depth = 1;
{ int i;
for (i = 0; i <= MAX_CODE; i++)
c->count[i] = 0;
}
c->count[encode[(int)(*s)]] = 1;
e->prev = f;
f->next = e;
c->pred = d;
d->succ = c;
f = e;
d = c;
}
e = (re_symbol *) frag;
frag->letter = '\0';
frag->row = id;
frag->scol = (re_column *) e->next->up;
frag->link = NULL;
e->prev = f;
f->next = e;;
c = last = new_column();
c->down = c->up = (re_symbol *) c;
c->pred = d;
d->succ = c;
c->succ = NULL;
seedctg.first = first;
seedctg.last = last;
seedctg.frags = frag;
return ((Re_Contig *) (&seedctg));
}
/* Add the bread-sequence of overlap o to contig contig, where seq is
* the oriented sequence of the bread. It is assumed that the aread
* sequence seeded the multi-alignment with a call to re_start_contig. */
void Re_Add_Overlap(Re_Contig *contig, Overlap *o, char *seq, int bandsize)
{ static re_fragment *last;
static double *matrix = NULL;
static char *trace = NULL;
static int *cseq = NULL;
static int dpmax = -1;
static int segmax = -1;
re_contig *ctg = (re_contig *) contig;
re_fragment *base; /* The re_fragment record for the aread */
re_column *cstart, *cfinis; /* Column interval to realign against */
int lmargin, rmargin; /* Amount of band wrapped around left/right end of contig */
int seglen; /* The # of columns between cstart & cfinis, inclusive */
int blen; /* Length of bread + 1 */
double *ncol; /* Current dp array column */
char *cbck; /* Current traceback column */
re_column *mincol; /* Next column in traceback during realignment */
#define INS 0
#define SUB 1
#define DEL 2
if (encode == NULL)
setup_encode();
/* Find reference read in fragment list. Linear scan save always check for the
* last one => preorder traversal of overlap tree is linear time over all adds! */
{ int aid;
aid = o->aread;
if (ctg->frags->link != NULL && last->row == aid)
base = last;
else
{ re_fragment *f;
for (f = ctg->frags; f != NULL; f = f->link)
if (f->row == aid)
{ base = f;
break;
}
if (f == NULL)
{ fprintf(stderr,"Could not find read %d in current multi-alignment (Re_Add_Overlap)\n",
aid);
exit (1);
}
}
last = base;
}
/* Determine the range [cstart,cfinis) of columns against which to realign
* and the left and right margin counts the new read. */
{ re_symbol *s;
re_column *c;
int x;
c = base->scol;
s = base->next;
x = 1;
while (x <= o->path.abpos)
{ if (s->letter != '-')
x += 1;
c = c->succ;
s = s->next;
}
while (s->letter == '-')
{ c = c->succ;
s = s->next;
}
cstart = c;
seglen = 1 + 2*bandsize;
while (x <= o->path.aepos)
{ if (s->letter != '-')
x += 1;
c = c->succ;
s = s->next;
seglen += 1;
}
cfinis = c;
lmargin = rmargin = 0;
for (x = 0; x < bandsize; x++) /* Pad the read's column range +/- bandSize */
{ if (cstart != ctg->first)
cstart = cstart->pred;
else
lmargin += 1;
if (cfinis != ctg->last)
cfinis = cfinis->succ;
else
rmargin += 1;
}
if (cstart == ctg->first)
{ cstart = cstart->succ;
lmargin += 1;
}
}
/* Setup the cost of comparing each symbol against a relevant column in score */
{ re_column *c;
for (c = cstart; c != cfinis; c = c->succ)
{ int i, cnt, max;
cnt = c->depth - c->count[N_CODE];
if (cnt != 0)
{ max = c->count[DASH_CODE];
for (i = 0; i < DASH_CODE; i++)
if (max < c->count[i])
max = c->count[i];
for (i = 0; i < N_CODE; ++i)
{ c->score[i] = MIX - (MIX * c->count[i])/cnt;
if (c->count[i] != max)
c->score[i] += (1.-MIX);
}
}
else if (c->count[N_CODE] > 0)
{ for (i = 0; i < N_CODE; i++)
c->score[i] = 0.0;
}
else
{ for (i = 0; i < N_CODE; i++)
c->score[i] = ALONE;
}
c->score[N_CODE] = 0.0;
}
}
#ifdef DEBUG_REALIGN
{ int i;
printf("\nFragment %d\n",o->bread);
printf(" ");
for (i = o->path.bbpos; i < o->path.bepos; i++)
printf(" %c",seq[i]);
printf("\n");
fflush(stdout);
}
#endif
/* Space for d.p. trace, d.p. vectors, and encoded b-sequence sufficient? */
{ blen = (o->path.bepos - o->path.bbpos)+1;
seglen += 1;
if (seglen*blen > dpmax)
{ dpmax = SPACE_GROWTH_RATE*seglen*blen + INIT_MAX_FRAG_LENGTH;
trace = (char *) realloc(trace , sizeof(char)*dpmax);
}
seglen -= 1;
if (blen > segmax)
{ segmax = SPACE_GROWTH_RATE*blen + INIT_MAX_FRAG_LENGTH;
matrix = (double *) realloc(matrix,sizeof(double)*segmax*2);
cseq = (int *) realloc(cseq,sizeof(int)*segmax);
}
}
/* Do the d.p. in the forward direction computing successive
* column vectors, delivering the final one in 'ncol' */
{ int i;
re_column *c;
ncol = matrix;
cbck = trace;
for (i = 0; i <= lmargin; i++)
{ ncol[i] = 0.;
cbck[i] = INS;
}
for (i = lmargin+1; i < blen; i++)
{ ncol[i] = ncol[i-1]+1;
cbck[i] = INS;
}
seq += (o->path.bbpos-1);
for (i = 1; i <= blen; i++)
cseq[i] = encode[(int)(seq[i])];
lmargin = 2*bandsize-lmargin;
for (c = cstart; c != cfinis; c = c->succ)
{ int t;
float *m;
double x, n;
double *ccol, d;
ccol = ncol;
if (ccol == matrix)
ncol = ccol + blen;
else
ncol = matrix;
cbck = cbck + blen;
m = c->score;
d = m[DASH_CODE];
if (lmargin > 0)
{ ncol[0] = 0;
lmargin -= 1;
}
else
ncol[0] = ccol[0] + d;
cbck[0] = DEL;
for (i = 1; i < blen; i++)
{ t = INS;
n = ncol[i-1] + 1;
if ((x = ccol[i-1] + m[cseq[i]]) <= n)
{ n = x; t = SUB; }
if ((x = ccol[i] + d) < n)
{ n = x; t = DEL; }
ncol[i] = n;
cbck[i] = t;
}
*m = ncol[blen-1];
#ifdef DEBUG_REALIGN
{ for (i = 0; i <= MAX_CODE; i++)
printf(" %3.1f",c->score[i]);
printf(" : ");
for (i = 0; i < blen; i++)
printf(" %4.1f",ncol[i]);
printf("\n ");
for (i = 0; i < blen; i++)
printf(" %4d",cbck[i]);
printf("\n");
}
#endif
}
if (rmargin > 0)
{ for (i = blen-rmargin; i < blen; i++)
if (ncol[i-1] < ncol[i])
{ ncol[i] = ncol[i-1];
cbck[i] = INS;
}
}
}
/* Determine the column of the best path not ending in a deletion (mincol) */
{ int i;
double minval;
re_column *c;
char *t;
c = cfinis;
t = cbck;
minval = 1.e100;
for (i = 0; i <= 2*bandsize-rmargin; i++)
{ c = c->pred;
if (minval > c->score[0] && t[blen-1] != DEL)
{ cbck = t;
minval = c->score[0];
mincol = c;
#ifdef DEBUG_REALIGN
printf("\nSelecting %d as best\n",i);
#endif
}
t -= blen;
}
}
/* Trace back through matrix and interweave fragment
* always placing it at the bottom of each column */
{ int j;
re_symbol *s, *p;
re_fragment *read;
s = (re_symbol *) (read = new_fragment());
s->letter = '\0';
for (j = blen-1; j > 0; j--)
{ while (cbck[j] == DEL)
{
/* Weave a '-' into the column mincol for the read */
p = new_symbol();
p->next = s;
s->prev = p;
p->letter = '-';
p->up = mincol->up;
p->down = (re_symbol *) mincol;
p->down->up = p->up->down = p;
s = p;
mincol->depth += 1;
mincol->count[DASH_CODE] += 1;
mincol = mincol->pred;
cbck -= blen;
}
if (cbck[j] == INS)
{ re_column *c;
re_symbol *u, *t;
/* Add a new column between mincol and its successor that
* contains the non-dash char of the read and a column of
* '-'s for each read not ending at the boundary */
c = new_column();
c->pred = mincol;
c->succ = mincol->succ;
c->pred->succ = c->succ->pred = c;
c->up = c->down = (re_symbol *) c;
{ int i;
for (i = 0; i <= MAX_CODE; i++)
c->count[i] = 0;
}
c->depth = 1;
c->count[encode[s->letter]] += 1;
/* Add a '-' to fragments that span mincol and its successor */
for (t = mincol->up; t != (re_symbol *) mincol; t = t->up)
if (t->next->letter != '\0')
{ u = new_symbol();
u->letter = '-';
u->prev = t;
u->next = t->next;
u->down = c->down;
u->up = (re_symbol *) c;
u->prev->next = u->next->prev = u;
u->up->down = u->down->up = u;
c->depth += 1;
c->count[DASH_CODE] += 1;
}
p = new_symbol();
p->next = s;
s->prev = p;
p->letter = seq[j];
p->up = c->up;
p->down = (re_symbol *) c;
p->down->up = p->up->down = p;
s = p;
}
else
/* Weave the char of the read into column mincol */
{ p = new_symbol();
p->next = s;
s->prev = p;
p->letter = seq[j];
p->up = mincol->up;
p->down = (re_symbol *) mincol;
p->down->up = p->up->down = p;
s = p;
mincol->depth += 1;
mincol->count[encode[(int)(seq[j])]] += 1;
mincol = mincol->pred;
cbck -= blen;
}
}
read->scol = mincol->succ;
read->row = o->bread;
read->next = s;
s->prev = (re_symbol *) read;
read->link = ctg->frags;
ctg->frags = read;
}
}
static re_contig *Fetch_Contig = NULL;
static re_fragment *Next_Fragment = NULL;
static re_column *Next_Column = NULL;
void Re_Start_Scan(Re_Contig *contig)
{ Fetch_Contig = (re_contig *) contig;
Next_Fragment = NULL;
Next_Column = NULL;
}
char *Re_Next_Read(int *id)
{ static char *read = NULL;
static int fragmax = -1;
if (Fetch_Contig == NULL)
{ fprintf(stderr,"No contig is set up to be scanned (re_next_fragment)\n");
exit (1);
}
if (Next_Fragment == NULL)
Next_Fragment = Fetch_Contig->frags;
else
Next_Fragment = Next_Fragment->link;
if (Next_Fragment == NULL)
return (NULL);
{ re_symbol *s;
int len;
len = 0;
for (s = Next_Fragment->next; s != (re_symbol *) Next_Fragment; s = s->next)
len += 1;
if (len+1 >= fragmax)
{ fragmax = SPACE_GROWTH_RATE*(len+1) + INIT_MAX_FRAG_LENGTH;
read = (char *) realloc(read,sizeof(char)*fragmax);
}
len = 0;
for (s = Next_Fragment->next; s != (re_symbol *) Next_Fragment; s = s->next)
read[len++] = s->letter;
read[len] = '\0';
}
*id = Next_Fragment->row;
return (read);
}
char *Re_Next_Column(int **ids)
{ static char *column = NULL;
static int *idvect = NULL;
static re_symbol **nextel = NULL;
static int colmax = -1;
static int lastlen;
if (Fetch_Contig == NULL)
{ fprintf(stderr,"No contig is set up to be scanned (re_next_column)\n");
exit (1);
}
if (Next_Column == NULL)
{ Next_Column = Fetch_Contig->first->succ;
lastlen = 0;
}
else
Next_Column = Next_Column->succ;
if (Next_Column == Fetch_Contig->last)
{ Next_Column = NULL;
return (NULL);
}
{ re_symbol *s;
int i, j, len;
j = 0;
for (i = 0; i < lastlen; i++)
{ s = nextel[i];
if (s->letter == '\0') continue;
s = s->next;
nextel[j] = s;
if (s->letter == '\0')
column[j] = ' ';
else
column[j] = s->letter;
idvect[j] = idvect[i];
j += 1;
}
len = j;
for (s = Next_Column->down; s != (re_symbol *) Next_Column; s = s->down)
if (s->prev->letter == '\0')
len += 1;
if (len+1 >= colmax)
{ colmax = SPACE_GROWTH_RATE*(len+1) + INIT_MAX_FRAG_LENGTH;
column = (char *) realloc(column,sizeof(char)*colmax);
idvect = (int *) realloc(idvect,sizeof(int)*colmax);
nextel = (re_symbol **) realloc(nextel,sizeof(re_symbol *)*colmax);
}
for (s = Next_Column->down; s != (re_symbol *) Next_Column; s = s->down)
if (s->prev->letter == '\0')
{ nextel[j] = s;
column[j] = s->letter;
idvect[j] = ((re_fragment *) (s->prev))->row;
j += 1;
}
lastlen = j;
column[j] = '\0';
}
*ids = idvect;
return (column);
}
static void Re_Align_Fragment(re_fragment *read, int bandsize)
{ static double *matrix = NULL;
static char *trace = NULL;
static int readmax = -1;
int bandwidth; /* Bandwidth for realignment */
re_column *cstart, *cfinis; /* Column interval to realign against [cstart,cfinis) */
int readlen; /* Padded length of fragment (before realignment) */
double *crow; /* (bandwidth+1) vector of d.p. values for current row */
char *cbck; /* (bandwidth+1) vector of traceback values for current row */
re_column *ccol; /* Column of first char in current band */
int minpos; /* Traceback position in band vector during realignment */
re_column *mincol; /* Next column in traceback during realignment. */
#define INS 0
#define SUB 1
#define DEL 2
bandwidth = 2*bandsize;
if (encode == NULL)
setup_encode();
/* Strip fragment from structure, compute its padded length, and
* determine the range of columns against which to realign it. */
{ re_symbol *s;
re_column *c;
int i;
readlen = 1;
cstart = c = read->scol;
for (s = read->next; s != (re_symbol *) read; s = s->next)
{ s->up->down = s->down;
s->down->up = s->up;
c->depth -= 1;
c->count[encode[s->letter]] -= 1;
c = c->succ;
readlen += 1;
}
cfinis = c;
for (i = 0; i < bandsize; i++) /* Pad the read's column range +/- BandSize */
{ cstart = cstart->pred;
cfinis = cfinis->succ;
}
}
/* Setup the cost of comparing each symbol against a relevant column in score */
{ re_column *c;
int pemp;
pemp = (cstart->depth == 0);
for (c = cstart; c != cfinis; c = c->succ)
{ int i, cnt, max, nemp;
cnt = c->depth - c->count[N_CODE];
if (cnt != 0)
{ max = c->count[DASH_CODE];
for (i = 0; i < DASH_CODE; i++)
if (max < c->count[i])
max = c->count[i];
for (i = 0; i < N_CODE; ++i)
{ c->score[i] = MIX - (MIX * c->count[i])/cnt;
if (c->count[i] != max)
c->score[i] += (1.-MIX);
}
}
else if (c->count[N_CODE] > 0)
{ for (i = 0; i < N_CODE; i++)
c->score[i] = 0.0;
}
else
{ for (i = 0; i < N_CODE; i++)
c->score[i] = ALONE;
}
c->score[N_CODE] = 0.0;
nemp = (c->succ->depth == 0);
c->bound = (pemp || nemp);
pemp = nemp;
}
}
#ifdef DEBUG_REALIGN
{ int i;
re_column *c;
printf("\nFragment %p\n",read);
for (c = cstart; c != cfinis; c = c->succ)
{ printf(" ");
for (i = 0; i <= MAX_CODE; i++)
printf(" %3d",c->count[i]);
printf(" : ");
for (i = 0; i <= MAX_CODE; i++)
printf(" %3.1f",c->score[i]);
printf(" (%d)\n",c->bound);
}
fflush(stdout);
}
#endif
/* Space for d.p. band sufficient? */
if (readlen > readmax)
{ int newsize;
readmax = SPACE_GROWTH_RATE*readlen + INIT_MAX_FRAG_LENGTH;
newsize = readmax*(bandwidth+1);
matrix = (double *) realloc(matrix,sizeof(double)*newsize);
trace = (char *) realloc(trace , sizeof(char)*newsize);
}
/* Do the d.p. in the forward direction computing successive
* band vectors, delivering the final one in 'crow' */
{ int i;
re_symbol *s;
crow = matrix;
for (i = 0; i <= bandwidth; i++)
crow[i] = 0.;
cbck = trace;
ccol = cstart;
for (s = read->next; s != (re_symbol *) read; s = s->next)
{ int e, t;
double x, n;
re_column *c;
double *nrow;
nrow = crow + (bandwidth+1);
cbck = cbck + (bandwidth+1);
e = encode[s->letter];
c = ccol;
t = INS;
if (e >= DASH_CODE)
n = crow[1];
else if (c->bound)
n = crow[1] + ALONE;
else
n = crow[1] + 1;
if ((x = crow[0] + c->score[e]) <= n)
{ n = x; t = SUB; }
nrow[0] = n;
cbck[0] = t;
for (i = 1; i < bandwidth; i++)
{ c = c->succ;
t = INS;
if (e >= DASH_CODE)
n = crow[i+1];
else if (c->bound)
n = crow[i+1] + ALONE;
else
n = crow[i+1] + 1;
if ((x = crow[i] + c->score[e]) <= n)
{ n = x; t = SUB; }
if ((x = nrow[i-1] + c->score[DASH_CODE]) < n)
{ n = x; t = DEL; }
nrow[i] = n;
cbck[i] = t;
}
c = c->succ;
t = SUB;
n = crow[bandwidth] + c->score[e];
if ((x = nrow[bandwidth-1] + c->score[DASH_CODE]) < n)
{ n = x; t = DEL; }
nrow[bandwidth] = n;
cbck[bandwidth] = t;
#ifdef DEBUG_REALIGN
{ re_symbol *t;
printf(" %c:",s->letter);
#ifdef DEBUG_SMALL
for (t = (re_symbol *) read; t != s; t = t->next)
printf(" ");
#endif
for (i = 0; i <= bandwidth; i++)
printf(" %4.1f",nrow[i]);
printf("\n ");
#ifdef DEBUG_SMALL
for (t = (re_symbol *) read; t != s; t = t->next)
printf(" ");
#endif
for (i = 0; i <= bandwidth; i++)
printf(" %4d",cbck[i]);
printf("\n");
}
#endif
ccol = ccol->succ;
crow = nrow;
}
}
/* Determine the endpoint of the best path not ending in a
* deletion: index + column pointer (minpos, mincol) */
{ int i, minval;
minval = 0x7FFFFFFF;
for (i = bandsize; i >= 0; i--)
if (minval > crow[i] && cbck[i] != DEL)
{ minpos = i;
minval = crow[i];
}
for (i = bandsize+1; i <= bandwidth; i++)
if (minval > crow[i] && cbck[i] != DEL)
{ minpos = i;
minval = crow[i];
}
mincol = ccol->pred;
for (i = 0; i < minpos; i++)
mincol = mincol->succ;
}
#ifdef DEBUG_REALIGN
printf("\nSelected %d as best\n",minpos);
#endif
/* Trace back through matrix and interweave fragment
* always placing it at the bottom of each column */
{ re_symbol *s;
for (s = read->prev; s != (re_symbol *) read; s = s->prev)
{ while (cbck[minpos] == DEL)
{ re_symbol *p;
/* Weave a '-' into the column mincol for the read */
p = new_symbol();
p->prev = s;
p->next = s->next;
p->letter = '-';
p->up = mincol->up;
p->down = (re_symbol *) mincol;
p->down->up = p->up->down = p;
p->next->prev = p->prev->next = p;
mincol->depth += 1;
mincol->count[DASH_CODE] += 1;
mincol = mincol->pred;
minpos -= 1;
}
if (cbck[minpos] == INS)
{ if (s->letter == '-')
{ re_symbol *p;
/* Remove the '-' from the read (rather
* than align it against a new column of '-'s) */
p = s;
s = s->next;
s->prev = p->prev;
p->prev->next = s;
free_symbol(p);
}
else
{ re_column *c;
re_symbol *u, *t;
/* Add a new column between mincol and its successor that
* contains the non-dash char of the read and a column of
* '-'s for each read not ending at the boundary */
c = new_column();
c->pred = mincol;
c->succ = mincol->succ;
c->pred->succ = c->succ->pred = c;
c->up = c->down = (re_symbol *) c;
{ int i;
for (i = 0; i <= MAX_CODE; i++)
c->count[i] = 0;
}
c->depth = 1;
c->count[encode[s->letter]] += 1;
/* Add a '-' to fragments that span mincol and its successor */
for (t = mincol->up; t != (re_symbol *) mincol; t = t->up)
if (t->next->letter != '\0')
{ u = new_symbol();
u->letter = '-';
u->prev = t;
u->next = t->next;
u->down = c->down;
u->up = (re_symbol *) c;
u->prev->next = u->next->prev = u;
u->up->down = u->down->up = u;
c->depth += 1;
c->count[DASH_CODE] += 1;
}
s->up = c->up;
s->down = (re_symbol *) c;
s->down->up = s->up->down = s;
}
minpos += 1;
}
else
/* Weave the char of the read into column mincol */
{ s->up = mincol->up;
s->down = (re_symbol *) mincol;
s->down->up = s->up->down = s;
mincol->depth += 1;
mincol->count[encode[s->letter]] += 1;
mincol = mincol->pred;
}
cbck -= (bandwidth+1);
}
read->scol = mincol->succ;
}
}
int Re_Consensus_Score(Re_Contig *contig)
{ int i, max, score;
re_column *c;
score = 0;
for (c = ((re_contig *) contig)->first->succ; c != NULL; c = c->succ)
{ max = c->count[DASH_CODE];
for (i = 0; i < DASH_CODE; i++)
if (c->count[i] > max)
max = c->count[i];
score += (c->depth-max);
}
return (score);
}
#ifdef STATS
static int num_contigs;
static int total_iterations;
#endif
/* Return how much the consensus score was improved by */
int Re_Align_Contig(Re_Contig *contig, int bandsize)
{ static re_column* bprelft = NULL;
static re_column *bprergt, *bsufrgt, *bsuflft;
re_contig *ctg = (re_contig *) contig;
int score, oldscore, original;
/* If first time, create column padding for each end of consensus */
if (bprelft == NULL)
{ int j;
re_column *c;
bprelft = (re_column *) malloc(sizeof(re_column)*2*bandsize);
bprergt = bprelft + (bandsize-1);
bsuflft = bprergt + 1;
bsufrgt = bsuflft + (bandsize-1);
for (c = bprelft; c <= bsufrgt; c++)
{ c->succ = c+1;
c->pred = c-1;
c->down = c->up = (re_symbol *) c;
for (j = 0; j <= MAX_CODE; j++)
c->count[j] = 0;
c->depth = 0;
}
}
/* Splice in the border padding (Bandwidth empty columns to simplify boundary cases) */
bprergt->succ = ctg->first->succ;
bsuflft->pred = ctg->last->pred;
bprergt->succ->pred = bprergt;
bsuflft->pred->succ = bsuflft;
ctg->first->succ = bprelft;
bprelft->pred = ctg->first;
ctg->last->pred = bsufrgt;
bsufrgt->succ = ctg->last;
/* While score improves do realignment passes */
original = Re_Consensus_Score(ctg);
score = original;
oldscore = score+1;
#ifdef DEBUG
printf("\nInitial score %d\n\n",score);
#endif
while (oldscore > score)
{
/* Realign every fragment (in reverse order of list) */
{ re_fragment *f;
for (f = ctg->frags; f != NULL; f = f->link)
if (f->next != (re_symbol *) f)
{ Re_Align_Fragment(f,bandsize);
#ifdef DEBUG_REALIGN
printf("\nFragment = %p\n",f);
Re_Print_Structure(ctg,stdout);
#endif
}
}
/* If fragments got realigned with part of the border then re-establish it */
{ re_column *a, *b, *c;
re_symbol *s;
int j;
c = bprergt->succ;
for (b = bprergt; b->depth > 0; b = b->pred) /* Initial border */
{ a = new_column();
*a = *b;
a->down->up = a->up->down = (re_symbol *) a;
a->succ = c;
c->pred = a;
c = a;
b->up = b->down = (re_symbol *) b;
for (j = 0; j <= MAX_CODE; j++)
b->count[j] = 0;
b->depth = 0;
for (s = a->down; s != (re_symbol *) a; s = s->down)
if (s->prev->letter == '\0')
((re_fragment *) (s->prev))->scol = a;
}
bprergt->succ = c;
c->pred = bprergt;
c = bsuflft->pred;
for (b = bsuflft; b->depth > 0; b = b->succ) /* Tail border */
{ a = new_column();
*a = *b;
a->down->up = a->up->down = (re_symbol *) a;
a->pred = c;
c->succ = a;
c = a;
b->up = b->down = (re_symbol *) b;
for (j = 0; j <= MAX_CODE; j++)
b->count[j] = 0;
b->depth = 0;
}
bsuflft->pred = c;
c->succ = bsuflft;
}
/* Remove blank columns */
{ re_column *c, *d;
for (c = bprergt->succ; c != bsuflft; c = d)
{ d = c->succ;
if (c->depth == c->count[DASH_CODE])
{ re_symbol *s;
c->pred->succ = d;
d->pred = c->pred;
for (s = c->down; s != (re_symbol *) c; s = s->down)
{ if (s->prev->letter == '\0')
((re_fragment *) (s->prev))->scol = d;
s->prev->next = s->next;
s->next->prev = s->prev;
free_symbol(s);
}
free_column(c);
}
}
}
oldscore = score;
score = Re_Consensus_Score(ctg);
#ifdef DEBUG
printf("\nCycle: new score = %d\n",score);
Re_Print_Structure(ctg,stdout);
#endif
#ifdef STATS
total_iterations += 1;
#endif
}
/* Restore regular column boundary */
bprergt->succ->pred = ctg->first;
bsuflft->pred->succ = ctg->last;
ctg->first->succ = bprergt->succ;
ctg->last->pred = bsuflft->pred;
return (original - score);
}
|
MartinPippel/DAmar
|
utils/LAcheck.c
|
<filename>utils/LAcheck.c
/*******************************************************************************************
*
* performs basic sanity checks on the overlaps
*
* Author: <NAME>
*
* Date : December 2014
*
*******************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "db/DB.h"
#include "dalign/align.h"
#include "lib/oflags.h"
#include "lib/pass.h"
// switches
#undef PROGRESS // show verification progress
// command line defaults
#define DEF_ARG_P 0
#define DEF_ARG_S 0
#define DEF_ARG_D 0
// macros
#define CMP(a, b) cmp = (a) - (b); if (cmp != 0) return cmp;
// structs
typedef struct
{
HITS_DB* db;
ovl_header_twidth twidth;
int error; // file didn't pass check
int check_ptp; // pass through points
int check_sort; // sort order
int check_dupes; // duplicates
int ignoreDiscardedOvls;
ovl_header_novl novl; // Overlaps counted
int prev_a;
} CheckContext;
static void usage()
{
fprintf(stderr, "usage : [-p] [-s] [-d] [-i] <db> <las>\n");
fprintf(stderr, "options: -p ... check pass-through points (%d)\n", DEF_ARG_P);
fprintf(stderr, " -s ... check sort order (%d)\n", DEF_ARG_S);
fprintf(stderr, " -d ... report duplicates. implies -s (%d)\n", DEF_ARG_D);
fprintf(stderr, " -i ... ignore overlaps that are discarded (default: 0)\n");
}
inline static int compare_sort(Overlap* o1, Overlap* o2)
{
int cmp;
CMP(o1->aread, o2->aread);
CMP(o1->bread, o2->bread);
CMP(o1->flags & OVL_COMP, o2->flags & OVL_COMP);
CMP(o1->path.abpos, o2->path.abpos);
return cmp;
}
// used jointly with compare_sort
inline static int compare_duplicate(Overlap* o1, Overlap* o2)
{
int cmp;
CMP(o1->flags, o2->flags);
CMP(o1->path.aepos, o2->path.aepos);
CMP(o1->path.bbpos, o2->path.bbpos);
CMP(o1->path.bepos, o2->path.bepos);
CMP(o1->path.tlen, o2->path.tlen);
return cmp;
}
static void check_pre(PassContext* pctx, CheckContext* cctx)
{
cctx->twidth = pctx->twidth;
cctx->prev_a = 0;
}
static void check_post(PassContext* pctx, CheckContext* cctx)
{
if (!cctx->error && pctx->novl != cctx->novl)
{
fprintf(stderr, "novl of %lld doesn't match actual overlap count of %lld\n", pctx->novl, cctx->novl);
cctx->error = 1;
}
}
static int check_process(void* _ctx, Overlap* ovl, int novl)
{
CheckContext* ctx = (CheckContext*)_ctx;
int i, lena, lenb;
for (i = 0; i < novl; i++)
{
ctx->novl++;
if(ctx->ignoreDiscardedOvls && (ovl[i].flags & OVL_DISCARD))
continue;
if (i == 0)
{
if (ctx->check_sort && ctx->prev_a > ovl[i].aread)
{
fprintf(stderr, "overlap %lld: not sorted\n", ctx->novl);
ctx->error = 1;
}
}
else
{
int cmp = compare_sort(ovl + (i - 1), ovl + i);
if (cmp > 0 && ctx->check_sort)
{
printf("%d %d\n", ovl[i-1].aread, ovl[i-1].bread);
fprintf(stderr, "overlap %lld: not sorted\n", ctx->novl);
ctx->error = 1;
}
else if (cmp == 0 && ctx->check_dupes && compare_duplicate(ovl + (i - 1), ovl + i) == 0)
{
printf("%d %d\n", ovl[i].aread, ovl[i].bread);
fprintf(stderr, "overlap %lld: equal to previous overlap\n", ctx->novl);
ctx->error = 1;
}
}
lena = DB_READ_LEN(ctx->db, ovl[i].aread);
lenb = DB_READ_LEN(ctx->db, ovl[i].bread);
if (ovl[i].path.abpos < 0)
{
fprintf(stderr, "overlap %lld: abpos < 0\n", ctx->novl);
ctx->error = 1;
}
if (ovl[i].path.bbpos < 0)
{
fprintf(stderr, "overlap %lld: bbpos < 0\n", ctx->novl);
ctx->error = 1;
}
if (ovl[i].path.aepos > lena)
{
fprintf(stderr, "overlap %lld: aepos > lena\n", ctx->novl);
ctx->error = 1;
}
if (ovl[i].path.bepos > lenb)
{
fprintf(stderr, "overlap %lld: bepos > lenb\n", ctx->novl);
ctx->error = 1;
}
if (ovl[i].path.tlen < 0)
{
fprintf(stderr, "overlap %lld: invalid tlen %d\n", ctx->novl, ovl[i].path.tlen);
ctx->error = 1;
}
if (ctx->check_ptp)
{
ovl_trace* trace = ovl[i].path.trace;
int apos = ovl[i].path.abpos;
int bpos = ovl[i].path.bbpos;
int j;
for (j = 0; j < ovl[i].path.tlen; j += 2)
{
apos += (apos/ctx->twidth + 1) * ctx->twidth;
bpos += trace[j+1];
}
if (bpos != ovl[i].path.bepos)
{
fprintf(stderr, "overlap %lld (%d x %d): pass-through points inconsistent be = %d (expected %d)\n",
ctx->novl, ovl[i].aread, ovl[i].bread, bpos, ovl[i].path.bepos);
ctx->error = 1;
}
}
}
ctx->prev_a = ovl->aread;
return !ctx->error;
}
int main(int argc, char* argv[])
{
PassContext* pctx;
CheckContext cctx;
HITS_DB db;
FILE* fileOvlIn;
bzero(&cctx, sizeof(CheckContext));
cctx.db = &db;
// process arguments
cctx.check_ptp = DEF_ARG_P;
cctx.check_sort = DEF_ARG_S;
cctx.check_dupes = DEF_ARG_D;
cctx.ignoreDiscardedOvls = 0;
int c;
opterr = 0;
while ((c = getopt(argc, argv, "psdi")) != -1)
{
switch (c)
{
case 'p':
cctx.check_ptp = 1;
break;
case 'd':
cctx.check_dupes = 1;
cctx.check_sort = 1;
break;
case 's':
cctx.check_sort = 1;
break;
case 'i':
cctx.ignoreDiscardedOvls = 1;
break;
default:
usage();
exit(1);
}
}
if (opterr || argc - optind != 2)
{
usage();
exit(1);
}
char* pcPathReadsIn = argv[optind++];
char* pcPathOverlapsIn = argv[optind++];
if ( (fileOvlIn = fopen(pcPathOverlapsIn, "r")) == NULL )
{
fprintf(stderr, "could not open '%s'\n", pcPathOverlapsIn);
exit(1);
}
if ( Open_DB(pcPathReadsIn, &db) )
{
fprintf(stderr, "could not open database '%s'\n", pcPathReadsIn);
exit(1);
}
pctx = pass_init(fileOvlIn, NULL);
pctx->split_b = 0;
pctx->load_trace = cctx.check_ptp;
pctx->unpack_trace = cctx.check_ptp;
pctx->data = &cctx;
check_pre(pctx, &cctx);
pass(pctx, check_process);
check_post(pctx, &cctx);
pass_free(pctx);
Close_DB(&db);
fclose(fileOvlIn);
return cctx.error;
}
|
MartinPippel/DAmar
|
db/fileUtils.c
|
#include "fileUtils.h"
#include "DB.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int isPacBioHeader(char* header)
{
char* c = header;
char* nameEnd;
char *pch;
// check if pacbio header is available
{
nameEnd = strchr(c, ' ');
if (nameEnd == NULL)
nameEnd = c + strlen(c) - 1;
// TODO to be more flexible, ignore number of '_' symbols ??
/*
// check number of underscore symbols equals 6 (>m140913_050931_42139_c100713652400000001823152404301535_s1_p0/9/1607_26058)
int ucnt = 0;
pch = strchr(c, '_');
while (pch != NULL && pch < nameEnd)
{
ucnt++;
pch = strchr(pch + 1, '_');
}
if (ucnt != 6)
return 0;
*/
// check number of slash symbols equals 2 (>m140913_050931_42139_c100713652400000001823152404301535_s1_p0/9/1607_26058)
int scnt = 0;
pch = strchr(c, '/');
while (pch != NULL && pch < nameEnd)
{
scnt++;
pch = strchr(pch + 1, '/');
}
if (scnt != 2)
return 0;
}
return 1;
}
File_Iterator *init_file_iterator(int argc, char **argv, FILE *input, int first)
{ File_Iterator *it;
it = Malloc(sizeof(File_Iterator),"Allocating file iterator");
it->argc = argc;
it->argv = argv;
it->input = input;
if (input == NULL)
it->count = first;
else
{ it->count = 1;
rewind(input);
}
return (it);
}
int next_file(File_Iterator *it)
{ static char nbuffer[MAX_NAME+8];
if (it->input == NULL)
{ if (it->count >= it->argc)
return (0);
it->name = it->argv[it->count++];
}
else
{ char *eol;
if (fgets(nbuffer,MAX_NAME+8,it->input) == NULL)
{ if (feof(it->input))
return (0);
SYSTEM_READ_ERROR;
}
if ((eol = index(nbuffer,'\n')) == NULL)
{ fprintf(stderr,"%s: Line %d in file list is longer than %d chars!\n",
Prog_Name,it->count,MAX_NAME+7);
it->name = NULL;
}
*eol = '\0';
it->count += 1;
it->name = nbuffer;
}
return (1);
}
Read_Iterator *init_read_iterator(FILE *input)
{ Read_Iterator *it;
it = Malloc(sizeof(Read_Iterator),"Allocating file iterator");
it->input = input;
it->lineno = 1;
rewind(input);
return (it);
}
int next_read(Read_Iterator *it)
{ static char nbuffer[MAX_BUFFER];
char *eol;
int x;
if (fgets(nbuffer,MAX_BUFFER,it->input) == NULL)
{ if (feof(it->input))
return (1);
SYSTEM_READ_ERROR;
}
if ((eol = index(nbuffer,'\n')) == NULL)
{ fprintf(stderr,"%s: Line %d in read list is longer than %d chars!\n",
Prog_Name,it->lineno,MAX_BUFFER-1);
return (1);
}
*eol = '\0';
x = sscanf(nbuffer," %d %d %d",&(it->read),&(it->beg),&(it->end));
if (x == 1)
it->beg = -1;
else if (x != 3)
{ fprintf(stderr,"%s: Line %d of read list is improperly formatted\n",Prog_Name,it->lineno);
return (1);
}
it->lineno += 1;
return (0);
}
|
MartinPippel/DAmar
|
utils/LAmergeUtils.h
|
<reponame>MartinPippel/DAmar<filename>utils/LAmergeUtils.h
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <assert.h>
#include <errno.h>
#include <getopt.h>
#include <sys/stat.h>
#include "db/DB.h"
#include "lib/pass.h"
#include "dalign/align.h"
#include "dalign/filter.h"
#define MIN(a,b) (((a)<(b))?(a):(b))
#define MAX(a,b) (((a)>(b))?(a):(b))
#define MEMORY 4000 // in Mb
#define MAX_FWAY_MERGE 255
// used in sortAndMerge(MERGE_OPT *mopt) to sort ovls
// according: aread, bread, COMP, abpos
int SORT_OVL(const void *x, const void *y);
// Input block data structure and block fetcher
typedef struct {
FILE *stream;
char *block;
char *ptr;
char *top;
int64 count;
} IO_block;
void reheap(int s, Overlap **heap, int hsize);
void ovl_reload(IO_block *in, int64 bsize);
void showheap(Overlap **heap, int hsize);
typedef struct
{
// general parameter
int VERBOSE;
int KEEP; // keep intermediate merge files (default: 0)
int SORT; // sort initial input files (default: 0)
int CHECK_TRACE_POINTS;
int CHECK_SORT_ORDER;
int CHECK_NAME;
char *pathDB; // full path of database
char *nameDB; // Database name (without .db extension)
HITS_DB *db; // database, used for input file checks
char *dir; // all files within the directory will be merged, (if they belong to the given DB)
char *suffix; // file suffix, if present only those files that match the pattern DB.blockID.suffix will be merged
int nBlocks; // database blocks
int fway; // parallel merge
char *inputFileList; // if -f option is given
// merge on files
int maxIFiles;
int numOfFilesToMerge;
char **iFileNames; // input file names
char *oFile; // output file name
} MERGE_OPT;
typedef struct
{
HITS_DB* db;
ovl_header_twidth twidth;
int error; // file didn't pass check
int check_ptp; // pass through points
int check_sort; // sort order
ovl_header_novl novl; // Overlaps counted
int prev_a;
} CheckContext;
void printUsage(char *prog, FILE* out);
MERGE_OPT* parseMergeOptions(int argc, char* argv[]);
void printOptions(FILE* out, MERGE_OPT* mopt);
void clearMergeOptions(MERGE_OPT* mopt);
int checkOverlapFile(MERGE_OPT *mopt, char *filename, int silent);
void addInputFile(MERGE_OPT *mopt, char *fileName);
void getFilesFromDir(MERGE_OPT *mopt, char *dirName);
void getFilesFromFile(MERGE_OPT *mopt);
void getFilesBySuffix(MERGE_OPT *mopt);
|
MartinPippel/DAmar
|
lib/lasidx.h
|
#pragma once
#include <stdio.h>
#include <db/DB.h>
typedef off_t lasidx;
lasidx* lasidx_create(HITS_DB* db, const char* pathLas);
lasidx* lasidx_load(HITS_DB* db, const char* pathLas, int create);
void lasidx_close(lasidx* idx);
|
MartinPippel/DAmar
|
utils/CTtrim.h
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <assert.h>
#include <errno.h>
#include <getopt.h>
#include <sys/stat.h>
#include "db/DB.h"
#include "lib/pass.h"
#include "dalign/align.h"
#include "dalign/filter.h"
#define TRIM_BIONANO_SINGLETON (1 << 0) // was not incorporated from Bionano into a scffold
#define TRIM_BIONANO_SPLIT (1 << 1) // Bionano split before contig
#define TRIM_BIONANO_LEFTGAP (1 << 2) //
#define TRIM_BIONANO_RIGHTGAP (1 << 3) //
#define TRIM_LASCHAIN_LEFTGAP (1 << 4) //
#define TRIM_LASCHAIN_RIGHTGAP (1 << 5) //
#define TRIM_DISCARD (1 << 6) //
typedef struct
{
int alnLen;
float eRate;
int unalignedBases;
int trimPos; // if < 0 trim at contig begin, else trim at contig end
} LASchain;
typedef struct
{
int flag;
// info from AGP file
int aBeg; // most times this is the full contig length,
int aEnd; // only in case Bionano split contigs those are relevant
int bBeg;
int bEnd;
int agpGapSize; // this value must be positive: [13,N]
int bionanoGapSize; // this value can also be negative in case of overlapping contigs
} BionanoGap;
typedef struct
{
int contigA;
int contigB;
// evidence from LAS files
int nLASchains;
int maxLASchains;
LASchain *chains;
// evidence from Bionano AGP and GAP
int nBioNanoGaps;
int maxBionanoGaps;
BionanoGap *gaps;
} TrimEvidence;
// trim coordinates for contigs, initialized from contig DB, updated from Bionano-AGP file and/or LAS chain overlaps (corresponding to given purgeOpt)
typedef struct
{
int *coord; // from_1, to_1, flag_1, from_2, to_2, flag_2 ... from_N, to_N, flag_N, where flag can be TRIM_BIONANO_SINGLETON, TRIM_BIONANO_SPLIT, ...
int numCoordPairs;
int maxCoordPairs;
} TrimCoordinates;
int TrimEvidence_cmp(const void *x, const void *y)
{
TrimEvidence *te1 = (TrimEvidence*) x;
TrimEvidence *te2 = (TrimEvidence*) y;
if (te1->contigA != te2->contigA)
return (te1->contigA - te2->contigA);
return (te1->contigB - te2->contigB);
}
int TrimCoordinates_cmp(const void *x, const void *y)
{
return ( *(int*)x - *(int*)y );
}
typedef struct
{
// stats counters
int statsNumValidLASchains;
int statsNumValidLASchainOverlaps;
int statsNumInValidLASchains;
int statsNumInValidLASchainOverlaps;
int statsNumDuplicatedChains;
int statsNumDuplicatedChainOverlaps;
int statsNumLASChainsWithBionanoSupport;
int statsNumLASChainsWithoutBionanoSupport;
int statsTrimmedContigs;
int statsTrimmedBases;
int statsRemovedContigParts;
int statsRemovedContigPartBases;
int statsBionanoTrimmedContigs;
int statsBionanoGapsMissed;
int statsBionanoTrimmedBases;
int statsBionanoGapsLtMinThresh;
int statsBionanoGapsLtMinThreshContigBreak;
int statsBionanoGapsAll;
int statsBionanoContigBreaksPartOfAGap;
int statsBionanoContigBreaksNotClosable;
int numTrimEvidence;
int maxTrimEvidence;
TrimEvidence *trimEvid;
TrimCoordinates *trimCoord; // number must correspond to number of contigs
// db and I/O files
HITS_DB *db;
HITS_TRACK *trackDust;
HITS_TRACK *trackTan;
char *fileOutPattern;
ovl_header_twidth twidth;
// other options
int verbose;
int minBionanoGapLen;
int maxTrimLength;
int maxLowCompTrimPerc;
int trimOffset;
int maxFuzzyBases;
int lineWidth;
int purgeOpt;
// fasta header
int nfiles;
char **flist;
char **hlist;
int *findx;
} TrimContext;
/*
* increase bionano gap buffer if necessary
*/
void ensureBionanoGapBuffer(TrimEvidence *t, int numNewElements);
/*
* increase LAS chain buffer if necessary
*/
void ensureLASchainBuffer(TrimEvidence *t, int numNewElements);
/*
* add Bionano gap feature as new TrimEvidence
* bionano feature: Contig_A - GAP - Contig_B (plus oriention, i.e. coordinates of the contigs)
*/
void addBionanoAGPInfoToTrimEvidence(TrimContext *ctx, int contigA, int fromA, int toA, int contigB, int fromB, int toB, int gapLen);
/*
* add Bionano gap feature to an existing TrimEvidence.
* assumption: bionano AGP must be parsed before the Bionano GAP file, because Bionano gap features must be present before adding the actual gap information,
* this is mandatory as the contig orientation is unknown in the gap files and will become ambiguous if Bionano splitted the input contigs
*/
void addBionanoGAPInfoToTrimEvidence(TrimContext *ctx, int contigA, int aPartBeg, int aPartEnd, int contigB, int bPartBeg, int bPartEnd, int AdjustedGapLength);
/*
* add/create Contig-Vs-Contig overlap to an existing/a new TrimEvidence in an aymmetric way
* return
* 1: add LAS chain to an existing Bionano TrimEvidence
* 2: LAS-chain could not be added (e.g. already present due to symmetric overlaps)
* 0: create an TrimEvidence feature and add LASchain (no Bionano evidence available)
*/
int addLASchainInfoToTrimEvidence(TrimContext *ctx, int aread, int bread, int alnLen, int unAlnLen, float erate, int cutPosInA);
/*
* find if a TrimEvidence entity between contigA and contigB is present.
* if yes: return TrimEvidence pointer
* if no: return NULL
*/
TrimEvidence* find_TrimEvidence(TrimContext *ctx, const int contigA, const int contigB);
/*
* Insert a new trimEvidence entity for contigA and contigB
* returns a newly created TrimEvidanec pointer
*/
TrimEvidence* insert_TrimEvidence(TrimContext *ctx, const int contigA, const int contigB);
/*
* assign trim positions for contigA and contigB for a given overlap and a given trimPoint
* assumption: contigA and contigB have a single proper overlap (i.e. not a chain with multiple overlaps)
* if trace points are present, then find closest trace point to pointA, and assign cutA to this tracepoint and cutB to the corresonding coordinate in B
* otherwise: assign pointA to cutA, and set cutB to ovl->path.bbeg + (pointA-ovl->path.abeg)
*
* return 0: if everything was ok,
* return 1: if something went wrong
*/
int getTrimPositionsFromLAS(TrimContext *ctx, Overlap *ovl, int pointA, int *cutA, int *cutB);
/*
* Analyze alignment chains, and add potential trim positions to the TrimEvidence
*/
int analyzeContigOverlaps(TrimContext *ctx, Overlap *ovl, int novl);
/*
* get masked bases for a given mask track, contig and coordinates
*/
int getMaskedBases(TrimContext *ctx, HITS_TRACK *t, int contigID, int beg, int end);
/*
* trim of leading and tailing white spaces from a given string
* used when parsing Bionano AGP and GAP files
*/
char* trimwhitespace(char *str);
/*
* try to find a given contigContigName with a contig ID in the current database
*/
int getDBcontigID(TrimContext *ctx, char *contigName, int *from, int *to);
/*
* parse Bionano Gap file, which contains real gap estimates (even negative sizes, when contigs overlap)
* unfortunately: the contig orientations are missing, therefore we need the AGP file as well
*/
void parseBionanoGAPfile(TrimContext *ctx, char *pathInBionanoGAP);
/*
* parse Bionano AGP file
*/
void parseBionanoAGPfile(TrimContext *ctx, char *pathInBionanoAGP);
/*
* auxiliary function: get sequence names from the database file
* its used to match the DB-contig names with the bionano-contig names
*/
void getDBFastaHeader(TrimContext *ctx, char *fullDBPath);
/*
* This function trims the contigs based on the available TrimEvidence
*/
void trim_contigs(TrimContext *ctx);
/*
* print out how to use CTtrim tool
*/
void usage();
/*
* print bionano gap information
*/
void printBionanpGap(TrimContext *ctx, int contigA, int contigB, BionanoGap *g);
/*
* print LASchain information
*/
void printLASchain(TrimContext *ctx, int contigA, int contigB, LASchain *c);
/*
* get Contig Name
*/
char * getContigName(TrimContext *ctx, int id);
/*
* add Bionano contig beg-end-coordinates
*/
void addBionanoContigCoordinates(TrimContext *ctx, int contig, int from, int to);
|
MartinPippel/DAmar
|
lib/dmask.c
|
<filename>lib/dmask.c<gh_stars>10-100
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <netdb.h>
#include <errno.h>
#include "dmask.h"
#include "dmask_proto.h"
static int hostname_to_ip(const char* hostname, char* ip)
{
struct hostent *he;
struct in_addr **addr_list;
if ((he = gethostbyname(hostname)) == NULL)
{
herror("gethostbyname");
return 0;
}
addr_list = (struct in_addr**) he->h_addr_list;
if (addr_list[0] != NULL)
{
strcpy(ip, inet_ntoa(*addr_list[0]));
return 1;
}
return 0;
}
DynamicMask* dm_init(const char* host, uint16 port)
{
int sockfd;
struct sockaddr_in dest;
char ip[16];
if (!hostname_to_ip(host, ip))
{
fprintf(stderr, "failed to resolve hostname\n");
return NULL;
}
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
fprintf(stderr, "error creating socket\n");
return NULL;
}
bzero(&dest, sizeof(dest));
dest.sin_family = AF_INET;
dest.sin_port = htons(port);
if (inet_aton(ip, &(dest.sin_addr)) == 0)
{
fprintf(stderr, "failed to parse %s:%d\n", host, port);
return NULL;
}
int retry = 3;
int connected = 0;
while ( retry > 0 && connected != 1 )
{
if (connect(sockfd, (struct sockaddr*) &dest, sizeof(dest)) != 0)
{
fprintf(stderr, "could not connect to %s:%d - %s\n", host, port, strerror(errno));
retry--;
sleep(2);
}
else
{
connected = 1;
}
}
if (connected == 0)
{
return NULL;
}
DynamicMask* dm = calloc(1, sizeof(DynamicMask));
dm->sockfd = sockfd;
dm->dest = dest;
dm->send_next = 1;
return dm;
}
void dm_send_next(DynamicMask* dm, int run, HITS_DB* blocka, char* namea, HITS_DB* blockb, char* nameb)
{
char* dira = strdup(getDir(run, blocka->part));
char* dirb = strdup(getDir(run, blockb->part));
int send_next = 1;
char* path;
int self = (blocka == blockb);
path = Catenate(Catenate(dira, "/", namea, ""), ".", nameb, ".las");
if (access(path, F_OK) != -1)
send_next = 0;
if (!self)
{
path = Catenate(Catenate(dirb, "/", nameb, ""), ".", namea, ".las");
if (access(path, F_OK) != -1)
send_next = 0;
}
dm->send_next = send_next;
}
int dm_send_block_done(DynamicMask* dm, int run, HITS_DB* blocka, char* namea, HITS_DB* blockb, char* nameb)
{
if (dm->send_next == 0)
{
dm->send_next = 1;
return 0;
}
char* dira = strdup(getDir(run, blocka->part));
char* dirb = strdup(getDir(run, blockb->part));
int mmax = 1000;
int mcur = 0;
char* msg = malloc(mmax);
char* path;
char abspath[PATH_MAX + 1];
int self = (blocka == blockb);
mcur += sizeof(DmHeader);
msg[mcur] = '\0';
int len;
path = Catenate(Catenate(dira, "/", namea, ""), ".", nameb, ".las");
if (realpath(path, abspath) == NULL)
{
fprintf(stderr, "realpath failed. path: %s, abspath: %s\n", path, abspath);
exit(1);
}
len = strlen(abspath) + 1;
if (mcur + len > mmax)
{
mmax = (mcur + len) * 1.2 + 1000;
msg = realloc(msg, mmax);
}
memcpy(msg + mcur, abspath, len);
mcur += len;
if (!self)
{
path = Catenate(Catenate(dirb, "/", nameb, ""), ".", namea, ".las");
if (realpath(path, abspath) == NULL)
{
fprintf(stderr, "realpath failed. path: %s, abspath: %s\n", path, abspath);
exit(1);
}
len = strlen(abspath) + 1;
if (mcur + len > mmax)
{
mmax = (mcur + len) * 1.2 + 1000;
msg = realloc(msg, mmax);
}
memcpy(msg + mcur, abspath, len);
mcur += len;
}
DmHeader* header = (DmHeader*) msg;
header->version = DM_VERSION;
header->type = DM_TYPE_LAS_AVAILABLE;
header->length = mcur;
// TODO ... loop in case send didn't transfer the whole buffer
if (send(dm->sockfd, msg, mcur, 0) != mcur)
{
fprintf(stderr, "failed to send BLOCK DONE message\n");
return 0;
}
free(dira);
free(dirb);
return 1;
}
void dm_free(DynamicMask* dm)
{
if (dm == NULL)
{
return;
}
close(dm->sockfd);
free(dm);
}
static int socket_receive(int sock, uint64 data, void* buffer)
{
uint64 pending = data;
uint64 bcur = 0;
while (pending)
{
int received = recv(sock, buffer + bcur, pending, 0);
if (received < 1)
{
fprintf(stderr, "failed to receive\n");
break;
}
bcur += received;
pending -= received;
}
if (pending != 0)
{
fprintf(stderr, "%lld pending bytes\n", pending);
}
return (pending == 0);
}
static void dm_simple_message(DynamicMask* dm, int msg)
{
DmHeader header;
bzero(&header, sizeof(header));
header.version = DM_VERSION;
header.type = msg;
header.length = sizeof(header);
if (send(dm->sockfd, &header, sizeof(header), 0) != sizeof(header))
{
fprintf(stderr, "failed to send message\n");
}
}
void dm_shutdown(DynamicMask* dm)
{
dm_simple_message(dm, DM_TYPE_SHUTDOWN);
}
void dm_write_track(DynamicMask* dm)
{
dm_simple_message(dm, DM_TYPE_WRITE_TRACK);
}
void dm_lock(DynamicMask* dm)
{
dm_simple_message(dm, DM_TYPE_LOCK);
}
void dm_unlock(DynamicMask* dm)
{
dm_simple_message(dm, DM_TYPE_UNLOCK);
}
void dm_intervals(DynamicMask* dm)
{
dm_simple_message(dm, DM_TYPE_INTERVALS);
}
int dm_done(DynamicMask* dm, char** files)
{
if (dm->send_next == 0)
{
dm->send_next = 1;
return 0;
}
int mmax = 1000;
int mcur = 0;
char* msg = malloc(mmax);
char abspath[PATH_MAX + 1];
mcur += sizeof(DmHeader);
msg[mcur] = '\0';
int i, len;
i = 0;
while (files[i] != NULL)
{
if (realpath(files[i], abspath) == NULL)
{
perror("realpath failed");
exit(1);
}
len = strlen(abspath) + 1;
if (mcur + len > mmax)
{
mmax = (mcur + len) * 1.2 + 1000;
msg = realloc(msg, mmax);
}
memcpy(msg + mcur, abspath, len);
mcur += len;
i++;
}
if (mcur == 0)
{
free(msg);
return 0;
}
DmHeader* header = (DmHeader*) msg;
header->version = DM_VERSION;
header->type = DM_TYPE_LAS_AVAILABLE;
header->length = mcur;
// TODO ... loop in case send didn't transfer the whole buffer
if (send(dm->sockfd, msg, mcur, 0) != mcur)
{
fprintf(stderr, "failed to send BLOCK DONE message\n");
free(msg);
return 0;
}
free(msg);
return 1;
}
HITS_TRACK* dm_load_track(HITS_DB* db, DynamicMask* dm, char* trackName)
{
DmHeader header;
bzero(&header, sizeof(header));
header.version = DM_VERSION;
header.type = DM_TYPE_REQUEST_TRACK;
header.length = sizeof(header);
header.reserved1 = db->ufirst;
header.reserved2 = db->nreads;
// track request
if (send(dm->sockfd, &header, sizeof(header), 0) != sizeof(header))
{
fprintf(stderr, "failed to send BLOCK DONE message\n");
return NULL;
}
// response header
if (recv(dm->sockfd, &header, sizeof(header), 0) != sizeof(header))
{
fprintf(stderr, "failed to receive header\n");
return NULL;
}
// track anno part
uint64 len_anno = sizeof(track_anno) * (db->nreads + 1);
track_anno* buf_anno = malloc(len_anno);
if (!socket_receive(dm->sockfd, len_anno, buf_anno))
{
fprintf(stderr, "failed to receive track.anno\n");
return NULL;
}
// track data part
uint64 len_data = buf_anno[db->nreads];
track_data* buf_data = malloc(len_data);
if (!socket_receive(dm->sockfd, len_data, buf_data))
{
fprintf(stderr, "failed to receive track.data\n");
return NULL;
}
assert((len_anno + len_data + sizeof(DmHeader)) == header.length);
HITS_TRACK* track = (HITS_TRACK*) malloc(sizeof(HITS_TRACK));
track->name = strdup(trackName);
track->size = sizeof(track_anno);
track->anno = buf_anno;
track->data = buf_data;
track->next = db->tracks;
db->tracks = track;
printf("received %llu + %llu bytes\n", len_anno, len_data);
return track;
}
|
MartinPippel/DAmar
|
lib/laz.h
|
<reponame>MartinPippel/DAmar
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include "dalign/align.h"
#define LAZ_MAGIC 0x254c415a
typedef struct
{
uint32_t magic;
uint16_t version;
uint16_t twidth;
uint64_t novl;
uint64_t reserved1;
uint64_t reserved2;
uint64_t reserved3;
uint64_t reserved4;
} LAZ_HEADER;
typedef struct
{
uint64_t a_from;
uint64_t a_to;
uint64_t novl;
uint64_t next;
uint64_t data;
uint64_t reserved1;
uint64_t reserved2;
uint64_t reserved3;
uint64_t reserved4;
} LAZ_INDEX;
typedef struct
{
FILE* file;
uint16_t version;
uint16_t twidth;
uint64_t novl;
Overlap* ovl;
uint32_t on;
uint32_t omax;
uint32_t ocur;
void* buf;
uint32_t bmax;
} LAZ;
LAZ* laz_open(char* fpath, int create);
int laz_close(LAZ* laz);
Overlap* laz_read(LAZ* laz);
int laz_write(LAZ* laz, Overlap* ovl);
|
MartinPippel/DAmar
|
dalign/daligner.c
|
/************************************************************************************\
* *
* Copyright (c) 2014, Dr. <NAME> (EWM). All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without modification, *
* are permitted provided that the following conditions are met: *
* *
* · Redistributions of source code must retain the above copyright notice, this *
* list of conditions and the following disclaimer. *
* *
* · Redistributions in binary form must reproduce the above copyright notice, this *
* list of conditions and the following disclaimer in the documentation and/or *
* other materials provided with the distribution. *
* *
* · The name of EWM may not be used to endorse or promote products derived from *
* this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY EWM ”AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, *
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND *
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL EWM BE LIABLE *
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS *
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY *
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING *
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN *
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
* *
* For any issues regarding this software and its use, contact EWM at: *
* *
* <NAME>r. *
* Bautzner Str. 122e *
* 01099 Dresden *
* GERMANY *
* Email: <EMAIL> *
* *
\************************************************************************************/
/*********************************************************************************************\
*
* Find all local alignment between long, noisy DNA reads:
* Compare sequences in 'subject' database against those in the list of 'target' databases
* searching for local alignments of 1000bp or more (defined constant MIN_OVERLAP in
* filter.c). Subject is compared in both orientations againt each target. An output
* stream of 'Overlap' records (see align.h) is written in binary to the standard output,
* each encoding a given found local alignment between two of the sequences. The -v
* option turns on a verbose reporting mode that gives statistics on each major stage.
*
* There cannot be more than 65,535 reads in a given db, and each read must be less than
* 66,535 characters long.
*
* The filter operates by looking for a pair of diagonal bands of width 2^'s' that contain
* a collection of exact matching 'k'-mers between the two sequences, such that the total
* number of bases covered by 'k'-mer hits is 'h'. k cannot be larger than 15 in the
* current implementation.
*
* Some k-mers are significantly over-represented (e.g. homopolymer runs). These are
* suppressed as seed hits, with the parameter 'm' -- any k-mer that occurs more than
* 'm' times in either the subject or target is not counted as a seed hit. If the -m
* option is absent then no k-mer is suppressed.
*
* For each subject, target pair, say XXX and YYY, the program outputs a file containing
* overlaps of the form XXX.YYY.[C|N]#.las where C implies that the reads in XXX were
* complemented and N implies they were not (both comparisons are performed), and # is
* the thread that detected and wrote out the collection of overlaps. For example, if
* NTHREAD in the program is 4, then 8 files are output for each subject, target pair.
*
* Author: <NAME>
* Date : June 1, 2014
*
*********************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <ctype.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <sys/param.h>
#if defined(BSD)
#include <sys/sysctl.h>
#endif
extern char *optarg;
extern int optind, opterr, optopt;
#include "db/DB.h"
#include "filter.h"
#include "lib/dmask.h"
#include "lib/tracks.h"
#include "lib/compression.h"
#include "align.h"
static void usage()
{
fprintf(stderr, "usage: \n");
fprintf(stderr, "daligner [-vbAIOT] [-k<int(14)>] [-w<int(6)>] [-h<int(35)>] [-t<int>] [-M<int>]\n");
fprintf(stderr, " [-e<double(.70)] [-l<int(1000)>] [-s<int(100)>] [-H<int>] [-j<int>]\n");
#ifdef DMASK
fprintf(stderr, " [-D<host:port>]\n");
#endif
fprintf(stderr, " [-m<track>]+ <subject:db|dam> <target:db|dam> ...\n");
fprintf(stderr, " [-r<int()1>]\n");
fprintf(stderr, "options: -v ... verbose\n");
fprintf(stderr, " -b ... data has a strong compositional bias (e.g. >65%% AT rich)\n");
fprintf(stderr, " -A ... asymmetric, for block X and Y the symmetric alignments for Y vs X are suppressed.\n");
fprintf(stderr, " -I ... identity, overlaps of the same read will found and reported\n");
fprintf(stderr, " -O ... only identity reads will be reported\n");
fprintf(stderr, " -k ... kmer length (defaults: raw pacbio reads: 14, corrected reads: 25, mapping applications: 20)\n");
fprintf(stderr, " -w ... diagonal band width (default: 6)\n");
fprintf(stderr, " -h ... hit theshold (in bp.s, default: 35\n");
fprintf(stderr,
" -t ... tuple supression frequency, i.e. suppresses the use of any k-mer that occurs more than t times in either the subject or target block\n");
fprintf(stderr, " -M ... specify the memory usage limit (in GB). Automatically adjust the -t parameter\n");
fprintf(stderr, " -e ... average correlation rate for local alignments (default: 0.5). Must be in [.5,1.)\n");
fprintf(stderr, " -l ... minimum alignment length (defaul: 1000)\n");
fprintf(stderr, " -s ... trace spacing, i.e. report trace point every -s base pairs (default: raw pacbio reads: 100, corrected reads: 500)\n");
fprintf(stderr, " -H ... report only overlaps where the a-read is over -H base pairs long\n");
#ifdef DMASK
fprintf(stderr, " -D ... set up host and port where the dynamic mask server is running (default port: %d)\n", DMASK_DEFAULT_PORT);
#endif
fprintf(stderr, " -m ... specify an interval track that is to be softmasked\n");
fprintf(stderr, " -r ... run identifier (default: 1). i.e. all overlap files of Block X a written to a subdirectory: dRUN-IDENTIFIER_X\n");
fprintf(stderr, " -j ... number of threads (default: 4). Must be a power of 2!\n");
fprintf(stderr, " -T ... disable trace points (default: enabled)\n");
}
int VERBOSE; // Globally visible to filter.c
int BIASED;
int MINOVER;
int HGAP_MIN;
int SYMMETRIC;
int IDENTITY;
int ONLY_IDENTITY;
uint64 MEM_LIMIT;
uint64 MEM_PHYSICAL;
/* Adapted from code by <NAME> (http://NadeauSoftware.com) licensed under
* "Creative Commons Attribution 3.0 Unported License"
* (http://creativecommons.org/licenses/by/3.0/deed.en_US)
*
* I removed Windows options, reformated, and return int64 instead of size_t
*/
static int64 getMemorySize()
{
#if defined(CTL_HW) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM64))
// OSX, NetBSD, OpenBSD
int mib[2];
size_t size = 0;
size_t len = sizeof(size);
mib[0] = CTL_HW;
#if defined(HW_MEMSIZE)
mib[1] = HW_MEMSIZE; // OSX
#elif defined(HW_PHYSMEM64)
mib[1] = HW_PHYSMEM64; // NetBSD, OpenBSD
#endif
if (sysctl(mib, 2, &size, &len, NULL, 0) == 0)
return ((size_t) size);
return (0);
#elif defined(_SC_AIX_REALMEM)
// AIX
return ((size_t) sysconf( _SC_AIX_REALMEM ) * ((size_t) 1024L));
#elif defined(_SC_PHYS_PAGES) && defined(_SC_PAGESIZE)
// FreeBSD, Linux, OpenBSD, & Solaris
size_t size = 0;
size = (size_t) sysconf(_SC_PHYS_PAGES);
return (size * ((size_t) sysconf(_SC_PAGESIZE)));
#elif defined(_SC_PHYS_PAGES) && defined(_SC_PAGE_SIZE)
// ? Legacy ?
size_t size = 0;
size = (size_t) sysconf(_SC_PHYS_PAGES);
return (size * ((size_t) sysconf(_SC_PAGE_SIZE)));
#elif defined(CTL_HW) && (defined(HW_PHYSMEM) || defined(HW_REALMEM))
// DragonFly BSD, FreeBSD, NetBSD, OpenBSD, and OSX
int mib[2];
unsigned int size = 0;
size_t len = sizeof( size );
mib[0] = CTL_HW;
#if defined(HW_REALMEM)
mib[1] = HW_REALMEM; // FreeBSD
#elif defined(HW_PYSMEM)
mib[1] = HW_PHYSMEM; // Others
#endif
if (sysctl(mib,2,&size,&len,NULL,0) == 0)
return (size_t)size;
return (0);
#else
return (0);
#endif
}
typedef struct
{
int *ano;
int *end;
int idx;
int out;
} Event;
static void reheap(int s, Event **heap, int hsize)
{
int c, l, r;
Event *hs, *hr, *hl;
c = s;
hs = heap[s];
while ((l = 2 * c) <= hsize)
{
r = l + 1;
hl = heap[l];
hr = heap[r];
if (hr->idx > hl->idx)
{
if (hs->idx > hl->idx)
{
heap[c] = hl;
c = l;
}
else
break;
}
else
{
if (hs->idx > hr->idx)
{
heap[c] = hr;
c = r;
}
else
break;
}
}
if (c != s)
heap[c] = hs;
}
int64 Merge_Size(HITS_DB *block, int mtop)
{
Event ev[mtop + 1];
Event *heap[mtop + 2];
int r, mhalf;
int64 nsize;
{
HITS_TRACK *track;
int i;
track = block->tracks;
for (i = 0; i < mtop; i++)
{
ev[i].ano = ((int *) (track->data)) + ((int64 *) (track->anno))[0];
ev[i].out = 1;
heap[i + 1] = ev + i;
track = track->next;
}
ev[mtop].idx = INT32_MAX;
heap[mtop + 1] = ev + mtop;
}
mhalf = mtop / 2;
nsize = 0;
for (r = 0; r < block->nreads; r++)
{
int i, level, hsize;
HITS_TRACK *track;
track = block->tracks;
for (i = 0; i < mtop; i++)
{
ev[i].end = ((int *) (track->data)) + ((int64 *) (track->anno))[r + 1];
if (ev[i].ano < ev[i].end)
ev[i].idx = *(ev[i].ano);
else
ev[i].idx = INT32_MAX;
track = track->next;
}
hsize = mtop;
for (i = mhalf; i > 1; i--)
reheap(i, heap, hsize);
level = 0;
while (1)
{
Event *p;
reheap(1, heap, hsize);
p = heap[1];
if (p->idx == INT32_MAX)
break;
p->out = 1 - p->out;
if (p->out)
{
level -= 1;
if (level == 0)
nsize += 1;
}
else
{
if (level == 0)
nsize += 1;
level += 1;
}
p->ano += 1;
if (p->ano >= p->end)
p->idx = INT32_MAX;
else
p->idx = *(p->ano);
}
}
return (nsize);
}
HITS_TRACK *Merge_Tracks(HITS_DB *block, int mtop, int64 nsize)
{
HITS_TRACK *ntrack;
Event ev[mtop + 1];
Event *heap[mtop + 2];
int r, mhalf;
int64 *anno;
int *data;
ntrack = (HITS_TRACK *) Malloc(sizeof(HITS_TRACK), "Allocating merged track");
if (ntrack == NULL)
exit(1);
ntrack->name = Strdup("merge", "Allocating merged track");
ntrack->anno = anno = (int64 *) Malloc(sizeof(int64) * (block->nreads + 1), "Allocating merged track");
ntrack->data = data = (int *) Malloc(sizeof(int) * nsize, "Allocating merged track");
ntrack->size = sizeof(int);
ntrack->next = NULL;
if (anno == NULL || data == NULL || ntrack->name == NULL)
exit(1);
{
HITS_TRACK *track;
int i;
track = block->tracks;
for (i = 0; i < mtop; i++)
{
ev[i].ano = ((int *) (track->data)) + ((int64 *) (track->anno))[0];
ev[i].out = 1;
heap[i + 1] = ev + i;
track = track->next;
}
ev[mtop].idx = INT32_MAX;
heap[mtop + 1] = ev + mtop;
}
mhalf = mtop / 2;
nsize = 0;
for (r = 0; r < block->nreads; r++)
{
int i, level, hsize;
HITS_TRACK *track;
anno[r] = nsize;
track = block->tracks;
for (i = 0; i < mtop; i++)
{
ev[i].end = ((int *) (track->data)) + ((int64 *) (track->anno))[r + 1];
if (ev[i].ano < ev[i].end)
ev[i].idx = *(ev[i].ano);
else
ev[i].idx = INT32_MAX;
track = track->next;
}
hsize = mtop;
for (i = mhalf; i > 1; i--)
reheap(i, heap, hsize);
level = 0;
while (1)
{
Event *p;
reheap(1, heap, hsize);
p = heap[1];
if (p->idx == INT32_MAX)
break;
p->out = 1 - p->out;
if (p->out)
{
level -= 1;
if (level == 0)
data[nsize++] = p->idx;
}
else
{
if (level == 0)
data[nsize++] = p->idx;
level += 1;
}
p->ano += 1;
if (p->ano >= p->end)
p->idx = INT32_MAX;
else
p->idx = *(p->ano);
}
}
anno[r] = nsize;
return (ntrack);
}
#ifdef DMASK
static int read_DB(HITS_DB *block, char* name, char **mask, int *mstat, int mtop, int kmer, DynamicMask* dm)
#else
static int read_DB(HITS_DB *block, char* name, char **mask, int *mstat, int mtop, int kmer, void* dm)
#endif
{
int i, isdam, status, stop;
isdam = Open_DB(name, block);
if (isdam < 0)
exit(1);
stop = 0;
for (i = 0; i < mtop; i++)
{
HITS_TRACK *track;
int64 *anno;
int j;
// ugly hack: overrule this, to use marvel and dazzler tracks
status = 0;//Check_Track(block, mask[i]);
if (status > mstat[i])
mstat[i] = status;
if (status < 0)
continue;
stop += 1;
if (dm)
track = dm_load_track(block, dm, mask[i]);
else
track = track_load(block, mask[i]);
if (track == NULL)
{
printf("[ERROR] - Unable to load track %s!\n", mask[i]);
exit(1);
}
anno = (int64 *) (track->anno);
for (j = 0; j <= block->nreads; j++)
anno[j] /= sizeof(track_data);
}
if (stop > 1)
{
int64 nsize;
HITS_TRACK *track;
nsize = Merge_Size(block, stop);
track = Merge_Tracks(block, stop, nsize);
while (block->tracks != NULL)
Close_Track(block, block->tracks->name);
block->tracks = track;
}
for (i = 0; i < block->nreads; i++)
if (block->reads[i].rlen < kmer)
{
fprintf(stderr, "[ERROR] - daligner: Block %s contains reads < %dbp long ! Run DBsplit.\n", name, kmer);
exit(1);
}
Read_All_Sequences(block, 0);
return (isdam);
}
static void complement(char *s, int len)
{
char *t;
int c;
t = s + (len - 1);
while (s < t)
{
c = *s;
*s = (char) (3 - *t);
*t = (char) (3 - c);
s += 1;
t -= 1;
}
if (s == t)
*s = (char) (3 - *s);
}
static HITS_DB *complement_DB(HITS_DB *block, int inplace)
{
static HITS_DB _cblock, *cblock = &_cblock;
int nreads;
HITS_READ *reads;
char *seq;
nreads = block->nreads;
reads = block->reads;
if (inplace)
{
seq = (char *) block->bases;
cblock = block;
}
else
{
seq = (char *) Malloc(block->reads[nreads].boff + 1, "Allocating dazzler sequence block");
if (seq == NULL)
exit(1);
*seq++ = 4;
memcpy(seq, block->bases, block->reads[nreads].boff);
*cblock = *block;
cblock->bases = (void *) seq;
cblock->tracks = NULL;
}
{
int i;
float x;
x = cblock->freq[0];
cblock->freq[0] = cblock->freq[3];
cblock->freq[3] = x;
x = cblock->freq[1];
cblock->freq[1] = cblock->freq[2];
cblock->freq[2] = x;
for (i = 0; i < nreads; i++)
complement(seq + reads[i].boff, reads[i].rlen);
}
{
HITS_TRACK *src, *trg;
int *data, *tata;
int i, x, rlen;
int64 *tano, *anno;
int64 j, k;
for (src = block->tracks; src != NULL; src = src->next)
{
tano = (int64 *) src->anno;
tata = (int *) src->data;
if (inplace)
{
data = tata;
anno = tano;
trg = src;
}
else
{
data = (int *) Malloc(sizeof(int) * tano[nreads], "Allocating dazzler interval track data");
anno = (int64 *) Malloc(sizeof(int64) * (nreads + 1), "Allocating dazzler interval track index");
trg = (HITS_TRACK *) Malloc(sizeof(HITS_TRACK), "Allocating dazzler interval track header");
if (data == NULL || trg == NULL || anno == NULL)
exit(1);
trg->name = Strdup(src->name, "Copying track name");
if (trg->name == NULL)
exit(1);
trg->size = 4;
trg->anno = (void *) anno;
trg->data = (void *) data;
trg->next = cblock->tracks;
cblock->tracks = trg;
}
for (i = 0; i < nreads; i++)
{
rlen = reads[i].rlen;
anno[i] = tano[i];
j = tano[i + 1] - 1;
k = tano[i];
while (k < j)
{
x = tata[j];
data[j--] = rlen - tata[k];
data[k++] = rlen - x;
}
if (k == j)
data[k] = rlen - tata[k];
}
anno[nreads] = tano[nreads];
}
}
return (cblock);
}
static void createSubdir(HITS_DB* block, int RUN_ID)
{
int blockID = block->part;
struct stat s;
char* out;
out = getDir(RUN_ID, blockID);
int err = stat(out, &s);
if (err == -1)
{
if (errno == ENOENT)
{
mkdir(out, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
}
else
{
fprintf(stderr, "Cannot create output directory: %s\n", out);
exit(1);
}
}
else
{
if (!S_ISDIR(s.st_mode))
{
fprintf(stderr, "Output directory name: \"%s\" exist - but its not a directory\n", out);
exit(1);
}
}
}
int main(int argc, char *argv[])
{
HITS_DB _ablock, _bblock;
HITS_DB *ablock = &_ablock, *bblock = &_bblock;
char *afile, *bfile;
char *aroot, *broot;
void *aindex, *bindex;
int alen, blen;
Align_Spec *asettings;
#ifdef DMASK
DynamicMask* dm = NULL;
char* dm_arg = NULL;
#else
void* dm = NULL;
#endif
int isdam;
int MMAX, MTOP, *MSTAT;
char **MASK;
int KMER_LEN = 14;
int HIT_MIN = 35;
int BIN_SHIFT = 6;
int MAX_REPS = 0;
int HGAP_MIN = 0;
double AVE_ERROR = .70;
int SPACING = 100;
int RUN_ID = 0;
int NO_TRACE_POINTS = 0;
int NTHREADS = 4;
MINOVER = 1000; // Globally visible to filter.c
RUN_ID = 1;
IDENTITY = 0;
ONLY_IDENTITY = 0;
SYMMETRIC = 1;
MEM_PHYSICAL = getMemorySize();
MEM_LIMIT = MEM_PHYSICAL;
if (MEM_PHYSICAL == 0)
{
fprintf(stderr, "\nWarning: Could not get physical memory size\n");
fflush(stderr);
}
MTOP = 0;
MMAX = 10;
MASK = (char **) Malloc(MMAX * sizeof(char *), "Allocating mask track array");
MSTAT = (int *) Malloc(MMAX * sizeof(int), "Allocating mask status array");
if (MASK == NULL || MSTAT == NULL)
exit(1);
// parse arguments
int c;
opterr = 0;
while ((c = getopt(argc, argv, "vbOTAIk:w:h:t:M:e:l:s:H:D:m:r:j:")) != -1)
{
switch (c)
{
case 'v':
VERBOSE = 1;
break;
case 'b':
BIASED = 1;
break;
case 'T':
NO_TRACE_POINTS = 1;
break;
case 'I':
IDENTITY = 1;
break;
case 'O':
IDENTITY = 1;
ONLY_IDENTITY = 1;
break;
case 'A':
SYMMETRIC = 0;
break;
case 'k':
KMER_LEN = atoi(optarg);
break;
case 'w':
BIN_SHIFT = atoi(optarg);
break;
case 'h':
HIT_MIN = atoi(optarg);
break;
case 't':
MAX_REPS = atoi(optarg);
break;
case 'H':
HGAP_MIN = atoi(optarg);
break;
case 'e':
AVE_ERROR = atof(optarg);
break;
case 'l':
MINOVER = atoi(optarg);
break;
case 's':
SPACING = atoi(optarg);
break;
case 'j':
{
NTHREADS = atoi(optarg);
break;
}
#ifdef DMASK
case 'D':
dm_arg = optarg;
break;
#endif
case 'M':
{
int tmp = atoi(optarg);
if (tmp < 0)
fprintf(stderr, "invalid memory limit of (%d)\n", tmp);
MEM_LIMIT = tmp * 0x40000000ll;
}
break;
case 'm':
if (MTOP >= MMAX)
{
MMAX = 1.2 * MTOP + 10;
MASK = (char **) Realloc(MASK, MMAX * sizeof(char *), "Reallocating mask track array");
MSTAT = (int *) Realloc(MSTAT, MMAX * sizeof(int), "Reallocating mask status array");
if (MASK == NULL || MSTAT == NULL)
exit(1);
}
MSTAT[MTOP] = -2;
MASK[MTOP] = optarg;
MTOP++;
break;
case 'r':
RUN_ID = atoi(optarg);
if (RUN_ID < 0)
{
fprintf(stderr, "invalid run id of %d\n", RUN_ID);
exit(1);
}
break;
default:
fprintf(stderr, "Unsupported option: %s\n", argv[optind - 1]);
usage();
exit(1);
}
}
if (KMER_LEN < 0)
{
fprintf(stderr, "invalid kmer length of %d\n", KMER_LEN);
exit(1);
}
if (BIN_SHIFT < 0)
{
fprintf(stderr, "invalid log of bin width of %d\n", BIN_SHIFT);
exit(1);
}
if (HIT_MIN < 0)
{
fprintf(stderr, "invalid hit threshold of %d\n", HIT_MIN);
exit(1);
}
if (MAX_REPS < 0)
{
fprintf(stderr, "invalid tuple supression frequency of %d\n", MAX_REPS);
exit(1);
}
if (HGAP_MIN < 0)
{
fprintf(stderr, "invalid HGAP threshold of %d\n", HGAP_MIN);
exit(1);
}
if (AVE_ERROR < .5 || AVE_ERROR >= 1.)
{
fprintf(stderr, "Average correlation must be in [.5,1.) (%g)\n", AVE_ERROR);
exit(1);
}
if (MINOVER < 0)
{
fprintf(stderr, "invalid minimum alignmnet length of (%d)\n", MINOVER);
exit(1);
}
if (SPACING < 0)
{
fprintf(stderr, "invalid trace spacing of (%d)\n", SPACING);
exit(1);
}
if (optind + 2 > argc)
{
fprintf(stderr, "[ERROR] - at least one target and one subject block are required\n\n");
usage();
exit(1);
}
MINOVER *= 2;
if (Set_Filter_Params(KMER_LEN, BIN_SHIFT, MAX_REPS, HIT_MIN, NTHREADS))
{
fprintf(stderr, "Illegal combination of filter parameters\n");
exit(1);
}
#ifdef DMASK
if (dm_arg != NULL)
{
char* dm_host = dm_arg;
char* port;
int dm_port;
if ((port = strchr(dm_host, ':')) == NULL)
{
dm_port = DMASK_DEFAULT_PORT;
}
else
{
*port = '\0';
dm_port = atoi(port + 1);
}
dm = dm_init(dm_host, dm_port);
if (dm == NULL)
{
fprintf(stderr, "failed to initialise dynamic mask\n");
exit(1);
}
}
else
{
dm = NULL;
}
#endif
/* Read in the reads in A */
afile = argv[optind];
isdam = read_DB(ablock, afile, MASK, MSTAT, MTOP, KMER_LEN, dm);
if (isdam)
aroot = Root(afile, ".dam");
else
aroot = Root(afile, ".db");
// check if b-blocks belong to a different DB, if so unset SYMMETRIC flag!!!!
optind++;
if (SYMMETRIC)
{
int i;
broot = NULL;
for (i = optind; i < argc; i++)
{
bfile = argv[i];
if (strcmp(afile, bfile) != 0)
{
broot = Root(bfile, ".dam");
if (broot == NULL)
broot = Root(bfile, ".db");
if (broot)
{
char *adot;
char *bdot;
adot = strrchr(aroot, '.');
if (adot == NULL)
adot = aroot + strlen(aroot) - 1;
bdot = strrchr(broot, '.');
if (bdot == NULL)
bdot = broot + strlen(broot) - 1;
if (strncmp(aroot, broot, MAX(adot - aroot + 1, bdot - broot + 1)) != 0)
{
if (VERBOSE)
printf("[WARNING] - Daligner is performed on different databases (%s - %s). SYMMETRIC option is disabled!\n", aroot, broot);
SYMMETRIC = 0;
break;
}
}
}
}
}
/* Create subdirectory */
createSubdir(ablock, RUN_ID);
asettings = New_Align_Spec(AVE_ERROR, SPACING, ablock->freq, NTHREADS, SYMMETRIC, ONLY_IDENTITY, NO_TRACE_POINTS, 1);
/* Compare against reads in B in both orientations */
{
int i, j;
aindex = NULL;
broot = NULL;
for (i = optind; i < argc; i++)
{
bfile = argv[i];
if (strcmp(afile, bfile) != 0)
{
isdam = read_DB(bblock, bfile, MASK, MSTAT, MTOP, KMER_LEN, dm);
if (isdam)
broot = Root(bfile, ".dam");
else
broot = Root(bfile, ".db");
}
if (i == optind)
{
for (j = 0; j < MTOP; j++)
{
if (MSTAT[j] == -2)
printf("[WARNING]: daligner -m %s option given but no track found.\n", MASK[i]);
else if (MSTAT[j] == -1)
printf("[WARNING]: daligner %s track not sync'd with relevant db.\n", MASK[i]);
}
if (VERBOSE)
printf("\nBuilding index for %s\n", aroot);
aindex = Sort_Kmers(ablock, &alen);
}
if (strcmp(afile, bfile) != 0)
{
if (SYMMETRIC)
createSubdir(bblock, RUN_ID);
if (dm)
dm_send_next(dm, RUN_ID, ablock, aroot, bblock, broot);
if (VERBOSE)
printf("\nBuilding index for %s\n", broot);
bindex = Sort_Kmers(bblock, &blen);
Match_Filter(aroot, ablock, broot, bblock, aindex, alen, bindex, blen, 0, asettings);
bblock = complement_DB(bblock, 1);
if (VERBOSE)
printf("\nBuilding index for c(%s)\n", broot);
bindex = Sort_Kmers(bblock, &blen);
Match_Filter(aroot, ablock, broot, bblock, aindex, alen, bindex, blen, 1, asettings);
int lastRead;
if (bblock->part < ablock->part)
lastRead = bblock->ufirst + bblock->nreads - 1;
else
lastRead = ablock->ufirst + ablock->nreads - 1;
char *dirName1, *dirName2;
dirName1 = dirName2 = NULL;
if (ablock->part > 0)
dirName1 = getDir(RUN_ID, ablock->part);
if (bblock->part > 0)
dirName2 = getDir(RUN_ID, bblock->part);
Write_Overlap_Buffer(asettings, dirName1, dirName2, aroot, broot, lastRead);
Reset_Overlap_Buffer(asettings);
if (dm)
{
int sent = dm_send_block_done(dm, RUN_ID, ablock, aroot, bblock, broot);
if (VERBOSE && !sent)
printf("results not reported to dmask server\n");
}
free(broot);
if (dirName1)
free(dirName1);
if (dirName2)
free(dirName2);
}
else
{
if (dm)
dm_send_next(dm, RUN_ID, ablock, aroot, ablock, aroot);
Match_Filter(aroot, ablock, aroot, ablock, aindex, alen, aindex, alen, 0, asettings);
bblock = complement_DB(ablock, 0);
if (VERBOSE)
printf("\nBuilding index for c(%s)\n", aroot);
bindex = Sort_Kmers(bblock, &blen);
Match_Filter(aroot, ablock, aroot, bblock, aindex, alen, bindex, blen, 1, asettings);
char *dirName1 = NULL;
if (ablock->part > 0)
dirName1 = getDir(RUN_ID, ablock->part);
Write_Overlap_Buffer(asettings, dirName1, NULL, aroot, aroot, ablock->ufirst + ablock->nreads - 1);
Reset_Overlap_Buffer(asettings);
if (dm)
{
int sent = dm_send_block_done(dm, RUN_ID, ablock, aroot, ablock, aroot);
if (VERBOSE && !sent)
printf("results not reported to dmask server\n");
}
bblock->reads = NULL; // ablock & bblock share "reads" vector, don't let Close_DB
// free it !
if (dirName1)
free(dirName1);
}
Close_DB(bblock);
}
}
exit(0);
}
|
MartinPippel/DAmar
|
lib/borders.c
|
/*******************************************************************************************
*
* Date : January 2014
*
*******************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#include <assert.h>
#include "lib/stats.h"
#include "lib/tracks.h"
#include "lib/oflags.h"
#include "lib/colors.h"
#include "lib/anno.h"
#include "borders.h"
#include "lib/pass.h"
// switches
#undef BORDER_EXTEND
#ifdef BORDER_EXTEND
#define BORDER_EXTEND_DISTANCE 100
#endif
void find_borders(Border** ppBorder, int* bmax, int* bcur,
Event** pEvents, int l, int r,
float min_density, int min_events, int max_dist)
{
int len = r - l + 1;
/*
static int indent = -1;
indent++;
printf("%*sfind_borders %d %d %d..%d %d\n",
indent, "",
l, r,
pEvents[l]->pos, pEvents[r]->pos,
pEvents[r]->pos - pEvents[l]->pos);
if (len < min_events)
{
printf("%*smin_events\n", indent, "");
indent--;
return ;
}
*/
if (len < min_events)
{
return ;
}
int dist = pEvents[r]->pos - pEvents[l]->pos;
double density;
if (dist == 0)
{
density = min_density + 1;
}
else
{
density = (double)len / dist;
}
if (density > min_density && dist < max_dist)
{
if ( *bcur == *bmax )
{
*bmax = *bmax * 2 + 20;
*ppBorder = (Border*)realloc(*ppBorder, sizeof(Border) * (*bmax));
}
#ifdef BORDER_EXTEND
if ( (*bcur) > 0 )
{
Border* prev = (*ppBorder) + (*bcur) - 1;
if ( pEvents[l]->pos - pEvents[ prev->ee ]->pos < BORDER_EXTEND_DISTANCE )
{
prev->ee = r;
return;
}
}
#endif
Border* b = (*ppBorder) + (*bcur);
*bcur += 1;
b->peb = pEvents[l];
b->pee = pEvents[r];
b->eb = l;
b->ee = r;
b->link = -1;
b->type = pEvents[l]->type;
b->done = 0;
// printf("%*sborder\n", indent, "");
}
else
{
// recurse around pair with max distance
int mid = l + 1;
int dist_max = pEvents[mid]->pos - pEvents[mid-1]->pos;
int i;
for (i = mid+1; i <= r; i++)
{
if ( pEvents[i]->pos - pEvents[i-1]->pos > dist_max )
{
mid = i;
dist_max = pEvents[i]->pos - pEvents[i-1]->pos;
}
}
find_borders(ppBorder, bmax, bcur,
pEvents, l, mid-1, min_density, min_events, max_dist);
find_borders(ppBorder, bmax, bcur,
pEvents, mid, r, min_density, min_events, max_dist);
}
// indent--;
}
|
MartinPippel/DAmar
|
dalign/align.h
|
<gh_stars>10-100
/************************************************************************************\
* *
* Copyright (c) 2014, Dr. <NAME> (EWM). All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without modification, *
* are permitted provided that the following conditions are met: *
* *
* · Redistributions of source code must retain the above copyright notice, this *
* list of conditions and the following disclaimer. *
* *
* · Redistributions in binary form must reproduce the above copyright notice, this *
* list of conditions and the following disclaimer in the documentation and/or *
* other materials provided with the distribution. *
* *
* · The name of EWM may not be used to endorse or promote products derived from *
* this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY EWM ”AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, *
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND *
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL EWM BE LIABLE *
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS *
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY *
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING *
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN *
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
* *
* For any issues regarding this software and its use, contact EWM at: *
* *
* <NAME>r. *
* Bautzner Str. 122e *
* 01099 Dresden *
* GERMANY *
* Email: <EMAIL> *
* *
\************************************************************************************/
/*******************************************************************************************
*
* Local alignment module. Routines for finding local alignments given a seed position,
* representing such an l.a. with its interval and a set of pass-thru points, so that
* a detailed alignment can be efficiently computed on demand.
*
* All routines work on a numeric representation of DNA sequences, i.e. 0 for A, 1 for C,
* 2 for G, and 3 for T.
*
* Author: <NAME>
* Date : July 2013
*
********************************************************************************************/
#ifndef _A_MODULE
#define _A_MODULE
#include "db/DB.h"
#define TRACE_XOVR 125 // If the trace spacing is not more than this value, then can
// and do compress traces pts to 8-bit unsigned ints
/*** INTERACTIVE vs BATCH version
The defined constant INTERACTIVE (set in DB.h) determines whether an interactive or
batch version of the routines in this library are compiled. In batch mode, routines
print an error message and exit. In interactive mode, the routines place the error
message in EPLACE (also defined in DB.h) and return an error value, typically NULL
if the routine returns a pointer, and an unusual integer value if the routine returns
an integer.
Below when an error return is described, one should understand that this value is returned
only if the routine was compiled in INTERACTIVE mode.
***/
/*** PATH ABSTRACTION:
Coordinates are *between* characters where 0 is the tick just before the first char,
1 is the tick between the first and second character, and so on. Our data structure
is called a Path refering to its conceptualization in an edit graph.
A local alignment is specified by the point '(abpos,bbpos)' at which its path in
the underlying edit graph starts, and the point '(aepos,bepos)' at which it ends.
In otherwords A[abpos+1..aepos] is aligned to B[bbpos+1..bepos] (assuming X[1] is
the *first* character of X).
There are 'diffs' differences in an optimal local alignment between the beginning and
end points of the alignment (if computed by Compute_Trace), or nearly so (if computed
by Local_Alignment).
Optionally, a Path can have additional information about the exact nature of the
aligned substrings if the field 'trace' is not NULL. Trace points to either an
array of integers (if computed by a Compute_Trace routine), or an array of unsigned
short integers (if computed by Local_Alignment).
If computed by Local_Alignment 'trace' points at a list of 'tlen' (always even) short
values:
d_0, b_0, d_1, b_1, ... d_n-1, b_n-1, d_n, b_n
to be interpreted as follows. The alignment from (abpos,bbpos) to (aepos,bepos)
passes through the n trace points for i in [1,n]:
(a_i,b_i) where a_i = floor(abpos/TS)*TS + i*TS
and b_i = bbpos + (b_0 + b_1 + b_i-1)
where also let a_0,b_0 = abpos,bbpos and a_(n+1),b_(n+1) = aepos,bepos. That is, the
interior (i.e. i != 0 and i != n+1) trace points pass through every TS'th position of
the aread where TS is the "trace spacing" employed when finding the alignment (see
New_Align_Spec). Typically TS is 100. Then d_i is the number of differences in the
portion of the alignment between (a_i,b_i) and (a_i+1,b_i+1). These trace points allow
the Compute_Trace routines to efficiently compute the exact alignment between the two
reads by efficiently computing exact alignments between consecutive pairs of trace points.
Moreover, the diff values give one an idea of the quality of the alignment along every
segment of TS symbols of the aread.
If computed by a Compute_Trace routine, 'trace' points at a list of 'tlen' integers
< i1, i2, ... in > that encodes an exact alignment as follows. A negative number j
indicates that a dash should be placed before A[-j] and a positive number k indicates
that a dash should be placed before B[k], where A and B are the two sequences of the
overlap. The indels occur in the trace in the order in which they occur along the
alignment. For a good example of how to "decode" a trace into an alignment, see the
code for the routine Print_Alignment.
***/
typedef struct
{
void *trace;
int tlen;
int diffs;
int abpos, bbpos;
int aepos, bepos;
} Path;
/*** ALIGNMENT ABSTRACTION:
An alignment is modeled by an Alignment record, which in addition to a *pointer* to a
'path', gives pointers to the A and B sequences, their lengths, and indicates whether
the B-sequence needs to be complemented ('comp' non-zero if so). The 'trace' pointer
of the 'path' subrecord can be either NULL, a list of pass-through points, or an exact
trace depending on what routines have been called on the record.
One can (1) compute a trace, with Compute_Trace, either from scratch if 'path.trace' = NULL,
or using the sequence of pass-through points in trace, (2) print an ASCII representation
of an alignment, or (3) reverse the roles of A and B, and (4) complement a sequence
(which is a reversible process).
If the alignment record shows the B sequence as complemented, *** THEN IT IS THE
RESPONSIBILITY OF THE CALLER *** to make sure that bseq points at a complement of
the sequence before calling Compute_Trace or Print_Alignment. Complement_Seq complements
the sequence a of length n. The operation does the complementation/reversal in place.
Calling it a second time on a given fragment restores it to its original state.
***/
#define COMP_FLAG 0x1
#define ACOMP_FLAG 0x2 // A-sequence is complemented, not B ! Only Local_Alignment notices
#define COMP(x) ((x) & COMP_FLAG)
#define ACOMP(x) ((x) & ACOMP_FLAG)
#define START_FLAG 0x4 // LA is the first of a chain of 1 or more la's
#define NEXT_FLAG 0x8 // LA is the next segment of a chain.
#define BEST_FLAG 0x10 // This is the start of the best chain
#define CHAIN_START(x) ((x) & START_FLAG)
#define CHAIN_NEXT(x) ((x) & NEXT_FLAG)
#define BEST_CHAIN(x) ((x) & BEST_FLAG)
#define ELIM_FLAG 0x20 // This LA should be ignored
#define ELIM(x) ((x) & ELIM_FLAG)
typedef struct
{
Path *path;
uint32 flags; /* Pipeline status and complementation flags */
char *aseq; /* Pointer to A sequence */
char *bseq; /* Pointer to B sequence */
int alen; /* Length of A sequence */
int blen; /* Length of B sequence */
} Alignment;
void Complement_Seq(char *a, int n);
/* Many routines like Local_Alignment, Compute_Trace, and Print_Alignment need working
storage that is more efficiently reused with each call, rather than being allocated anew
with each call. Each *thread* can create a Work_Data object with New_Work_Data and this
object holds and retains the working storage for routines of this module between calls
to the routines. If enough memory for a Work_Data is not available then NULL is returned.
Free_Work_Data frees a Work_Data object and all working storage held by it.
*/
typedef void Work_Data;
Work_Data *New_Work_Data();
void Free_Work_Data(Work_Data *work);
/* Local_Alignment seeks local alignments of a quality determined by a number of parameters.
These are coded in an Align_Spec object that can be created with New_Align_Spec and
freed with Free_Align_Spec when no longer needed. There are 4 essential parameters:
ave_corr: the average correlation (1 - 2*error_rate) for the sought alignments. For Pacbio
data we set this to .70 assuming an average of 15% error in each read.
trace_space: the spacing interval for keeping trace points and segment differences (see
description of 'trace' for Paths above)
freq[4]: a 4-element vector where afreq[0] = frequency of A, f(A), freq[1] = f(C),
freq[2] = f(G), and freq[3] = f(T). This vector is part of the header
of every HITS database (see db.h).
If an alignment cannot reach the boundary of the d.p. matrix with this condition (i.e.
overlap), then the last/first 30 columns of the alignment are guaranteed to be
suffix/prefix positive at correlation ave_corr * g(freq) where g is an empirically
measured function that increases from 1 as the entropy of freq decreases. If memory is
unavailable or the freq distribution is too skewed then NULL is returned.
You can get back the original parameters used to create an Align_Spec with the simple
utility functions below.
*/
typedef void Align_Spec;
//Align_Spec *New_Align_Spec(double ave_corr, int trace_space, float *freq, int reach);// HEIDELBERG_MODIFICATION
Align_Spec *New_Align_Spec(double ave_corr, int trace_space, float *freq, int nthreads, int symmetric, int only_identity, int no_trace_points, int reach);
void Free_Align_Spec(Align_Spec *spec);
int Trace_Spacing(Align_Spec *spec);
double Average_Correlation(Align_Spec *spec);
float *Base_Frequencies(Align_Spec *spec);
int Overlap_If_Possible(Align_Spec *spec);
/* Local_Alignment finds the longest significant local alignment between the sequences in
'align' subject to:
(a) the alignment criterion given by the Align_Spec 'spec',
(b) it passes through one of the points (anti+k)/2,(anti-k)/2 for k in [low,hgh] within
the underlying dynamic programming matrix (i.e. the points on diagonals low to hgh
on anti-diagonal anti or anti-1 (depending on whether the diagonal is odd or even)),
(c) if lbord >= 0, then the alignment is always above diagonal low-lbord, and
(d) if hbord >= 0, then the alignment is always below diagonal hgh+hbord.
The path record of 'align' has its 'trace' filled from the point of view of an overlap
between the aread and the bread. In addition a Path record from the point of view of the
bread versus the aread is returned by the function, with this Path's 'trace' filled in
appropriately. The space for the returned path and the two 'trace's are in the working
storage supplied by the Work_Data packet and this space is reused with each call, so if
one wants to retain the bread-path and the two trace point sequences, then they must be
copied to user-allocated storage before calling the routine again. NULL is returned in
the event of an error.
Find_Extension is a variant of Local_Alignment that simply finds a local alignment that
either ends (if prefix is non-zero) or begins (if prefix is zero) at the point
(anti+diag)/2,(anti-diag)/2). All other parameters are as before. It returns a non-zero
value only when INTERACTIVE is on and it cannot allocate the memory it needs.
Only the path and trace with respect to the aread is returned. This routine is experimental
and may not persist in later versions of the code.
*/
Path *Local_Alignment(Alignment *align, Work_Data *work, Align_Spec *spec, int low, int hgh, int anti, int lbord, int hbord);
int Find_Extension(Alignment *align, Work_Data *work, Align_Spec *spec, // experimental !!
int diag, int anti, int lbord, int hbord, int prefix);
/* Given a legitimate Alignment object and associated trace point vector in 'align->path.trace',
Compute_Trace_X, computes an exact trace for the alignment and resets 'align->path.trace'
to point at an integer array within the storage of the Work_Data packet encoding an
exact optimal trace from the start to end points. If the trace is needed beyond the
next call to a routine that sets it, then it should be copied to an array allocated
and managed by the caller.
Compute_Trace_PTS computes a trace by computing the trace between successive trace points.
It is much, much faster than Compute_Alignment below but at the tradeoff of not necessarily
being optimal as pass-through points are not all perfect. Compute_Trace_MID computes a trace
by computing the trace between the mid-points of alignments between two adjacent pairs of trace
points. It is generally twice as slow as Compute_Trace_PTS, but it produces nearer optimal
alignments. Both these routines return 1 if an error occurred and 0 otherwise.
*/
#define LOWERMOST -1 // Possible modes for "mode" parameter below)
#define GREEDIEST 0
#define UPPERMOST 1
int Compute_Trace_PTS(Alignment *align, Work_Data *work, int trace_spacing, int mode);
int Compute_Trace_MID(Alignment *align, Work_Data *work, int trace_spacing, int mode);
/* Compute_Trace_IRR (IRR for IRRegular) computes a trace for the given alignment where
it assumes the spacing between trace points between both the A and B read varies, and
futher assumes that the A-spacing is given in the short integers normally occupied by
the differences in the alignment between the trace points. This routine is experimental
and may not persist in later versions of the code.
*/
int Compute_Trace_IRR(Alignment *align, Work_Data *work, int mode); // experimental !!
/* Compute Alignment determines the best alignment between the substrings specified by align.
If the task is DIFF_ONLY, then only the difference of this alignment is computed and placed
in the "diffs" field of align's path. If the task is PLUS_TRACE or DIFF_TRACE, then
'path.trace' is set to point at an integer array within the storage of the Work_Data packet
encoding a trace point sequence for an optimal alignment, whereas if the task is PLUS_ALIGN
or DIFF_ALIGN, then it points to an optimal trace of an optimatl alignment. The PLUS
tasks can only be called if the immmediately proceeding call was a DIFF_ONLY on the same
alignment record and sequences, in which case a little efficiency is gained by avoiding
the repetition of the top level search for an optimal mid-point.
*/
#define PLUS_ALIGN 0
#define PLUS_TRACE 1
#define DIFF_ONLY 2
#define DIFF_ALIGN 3
#define DIFF_TRACE 4
int Compute_Alignment(Alignment *align, Work_Data *work, int task, int trace_spacing);
/* Alignment_Cartoon prints an ASCII representation of the overlap relationhip between the
two reads of 'align' to the given 'file' indented by 'indent' space. Coord controls
the display width of numbers, it must be not less than the width of any number to be
displayed.
If the alignment trace is an exact trace, then one can ask Print_Alignment to print an
ASCII representation of the alignment 'align' to the file 'file'. Indent the display
by "indent" spaces and put "width" columns per line in the display. Show "border"
characters of sequence on each side of the aligned region. If upper is non-zero then
display bases in upper case. If coord is greater than 0, then the positions of the
first character in A and B in the given row is displayed with a field width given by
coord's value.
Print_Reference is like Print_Alignment but rather than printing exaclty "width" columns
per segment, it prints "block" characters of the A sequence in each segment. This results
in segments of different lengths, but is convenient when looking at two alignments involving
A as segments are guaranteed to cover the same interval of A in a segment.
Both Print routines return 1 if an error occurred (not enough memory), and 0 otherwise.
Flip_Alignment modifies align so the roles of A and B are reversed. If full is off then
the trace is ignored, otherwise the trace must be to a full alignment trace and this trace
is also appropriately inverted.
*/
void Alignment_Cartoon(FILE *file, Alignment *align, int indent, int coord);
int Print_Alignment(FILE *file, Alignment *align, Work_Data *work, int indent, int width, int border, int upper, int coord);
int Print_Reference(FILE *file, Alignment *align, Work_Data *work, int indent, int block, int border, int upper, int coord);
void Flip_Alignment(Alignment *align, int full);
/*** OVERLAP ABSTRACTION:
Externally, between modules an Alignment is modeled by an "Overlap" record, which
(a) replaces the pointers to the two sequences with their ID's in the HITS data bases,
(b) does not contain the length of the 2 sequences (must fetch from DB), and
(c) contains its path as a subrecord rather than as a pointer (indeed, typically the
corresponding Alignment record points at the Overlap's path sub-record). The trace pointer
is always to a sequence of trace points and can be either compressed (uint8) or
uncompressed (uint16). One can read and write binary records of an "Overlap".
***/
typedef struct
{
Path path; /* Path: begin- and end-point of alignment + diffs */
uint32 flags; /* Pipeline status and complementation flags */
int aread; /* Id # of A sequence */
int bread; /* Id # of B sequence */
} Overlap;
/* Read_Overlap reads the next Overlap record from stream 'input', not including the trace
(if any), and without modifying 'ovl's trace pointer. Read_Trace reads the ensuing trace
into the memory pointed at by the trace field of 'ovl'. It is assumed to be big enough to
accommodate the trace where each value take 'tbytes' bytes (1 if uint8 or 2 if uint16).
Write_Overlap write 'ovl' to stream 'output' followed by its trace vector (if any) that
occupies 'tbytes' bytes per value.
Print_Overlap prints an ASCII version of the contents of 'ovl' to stream 'output'
where the trace occupes 'tbytes' per value and the print out is indented from the left
margin by 'indent' spaces.
Compress_TraceTo8 converts a trace fo 16-bit values to 8-bit values in place, and
Decompress_TraceTo16 does the reverse conversion.
Check_Trace_Points checks that the number of trace points is correct and that the sum
of the b-read displacements equals the b-read alignment interval, assuming the trace
spacing is 'tspace'. It reports an error message if there is a problem and 'verbose'
is non-zero. The 'ovl' came from the file names 'fname'.
*/
int Read_Overlap(FILE *input, Overlap *ovl);
int Read_Trace(FILE *innput, Overlap *ovl, int tbytes);
int Write_Overlap(FILE *output, Overlap *ovl, int tbytes);
void Print_Overlap(FILE *output, Overlap *ovl, int tbytes, int indent);
int Compress_TraceTo8(Overlap *ovl, int check);
void Decompress_TraceTo16(Overlap *ovl);
int Check_Trace_Points(Overlap *ovl, int tspace, int verbose, char *fname);
/*
* BEGIN HEIDELBERG_ADDITION
*/
typedef struct
{
// trace buffer
int tbytes;
uint64 tmax;
uint64 ttop;
void *trace;
int no_trace;
// overlap buffer
int omax;
int otop;
Overlap *ovls;
} Overlap_IO_Buffer;
Overlap_IO_Buffer *CreateOverlapBuffer(int nthreads, int tbytes, int no_trace);
int AddOverlapToBuffer(Overlap_IO_Buffer *iobuf, Overlap *ovl, int tbytes);
void Write_Overlap_Buffer(Align_Spec *spec, char *dirName1, char *dirName2, char *ablock, char *bblock, int lastRead);
void Reset_Overlap_Buffer(Align_Spec* spec);
Overlap_IO_Buffer *OVL_IO_Buffer(Align_Spec *espec);
int Num_Threads(Align_Spec *espec);
Overlap_IO_Buffer *OVL_IO_Buffer(Align_Spec *espec);
int Only_Identity(Align_Spec *espec);
int Symmetric(Align_Spec *espec);
/*
* END HEIDELBERG_ADDITION
*/
#endif // _A_MODULE
|
MartinPippel/DAmar
|
lib.ext/bitarr.h
|
/* bitarr.h */
/*
Prototypes for bitarr.c
IMPORTANT NOTE: A version of this code appeared in
Dr. Dobb's Journal issue #233 (August 1995)
Volume 20 Issue 8
in an article entitled `Implementing Bit Vectors in C'
by <NAME>
Pages 42, 44, 46 (article) and pages 96, 98-100 (code)
The code is (c) copyright 1995 by <NAME>, Inc.
See "bitarr.c" for further details.
*/
#pragma once
elem_t ba_init(void);
bit *ba_new(const elem_t nelems);
void ba_copy(bit dst[], const bit src[], const elem_t size);
void ba_assign(bit arr[], elem_t elem, const bool value);
void ba_assign_range(bit arr[], elem_t elem_beg, elem_t elem_end, const bool value);
bool ba_value(const bit arr[], const elem_t elem);
void ba_toggle(bit arr[], const elem_t elem);
void ba_all_assign(bit arr[], const elem_t lsize, const bool value);
bit *ba_ul2b(unsigned long num, bit *arr, elem_t *size);
unsigned long ba_count(const bit arr[], const elem_t size);
bool ba_intersection(bit first[], bit second[], bit * result[], const elem_t size_first, const elem_t size_second);
bool ba_union(bit first[], bit second[], bit * result[], const elem_t size_first, const elem_t size_second);
bool ba_diff(bit first[], bit second[], bit * result[], const elem_t size_first, const elem_t size_second);
void ba_complement(bit arr[], const elem_t lsize);
unsigned long ba_dotprod(const bit first[], const bit second[], const elem_t size_first, const elem_t size_second);
char * ba_b2str(const bit arr[], const elem_t size, char * dest);
bool ba_print(const bit arr[], const elem_t size, FILE * dest);
size_t ba_bufsize(const elem_t nelems);
|
MartinPippel/DAmar
|
scrub/qsort_r.h
|
#ifndef __QSORTR_HEADER
#define __QSORTR_HEADER
// qsort_r is not part of the POSIX standard and the various incarnations of the
// function have different argument orders for the qsort_r call itself and the
// comparison function
#if defined (__APPLE__) || defined (__FreeBSD__)
#define QSORT_R(A,B,C,D,E) qsort_r(A,B,C,D,E)
#define QSORT_R_DATA_FIRST
#elif defined(__linux)
#ifndef __USE_GNU
#define __USE_GNU
#endif
#define QSORT_R(A,B,C,D,E) qsort_r(A,B,C,E,D)
#define QSORT_R_DATA_LAST
#else
#error "no qsort_r support"
#endif
#endif // not __QSORTR_HEADER
|
MartinPippel/DAmar
|
lib/trim.h
|
#pragma once
#include "db/DB.h"
#include "dalign/align.h"
#include "lib/tracks.h"
#include "lib/pass.h"
#include "lib/read_loader.h"
typedef struct
{
HITS_DB* db;
HITS_TRACK* track;
Read_Loader* rl;
ovl_header_twidth twidth; // trace point spacing
Work_Data* align_work; // working storage for the alignment module
Alignment align; // alignment and path record for computing the
Path path; // alignment in the gap region
uint64 nOvls;
uint64 nOvlBases;
uint64 nTrimmedOvls;
uint64 nTrimmedBases;
} TRIM;
TRIM* trim_init(HITS_DB* db, ovl_header_twidth twidth, HITS_TRACK *track, Read_Loader *rl);
void trim_overlap(TRIM* trim, Overlap* ovl);
void trim_close(TRIM* trim);
|
MartinPippel/DAmar
|
db/FA2db.c
|
<reponame>MartinPippel/DAmar<filename>db/FA2db.c
/************************************************************************************\
* *
* Copyright (c) 2014, Dr. <NAME> (EWM). All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without modification, *
* are permitted provided that the following conditions are met: *
* *
* · Redistributions of source code must retain the above copyright notice, this *
* list of conditions and the following disclaimer. *
* *
* · Redistributions in binary form must reproduce the above copyright notice, this *
* list of conditions and the following disclaimer in the documentation and/or *
* other materials provided with the distribution. *
* *
* · The name of EWM may not be used to endorse or promote products derived from *
* this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY EWM ”AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, *
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND *
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL EWM BE LIABLE *
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS *
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY *
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING *
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN *
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
* *
* For any issues regarding this software and its use, contact EWM at: *
* *
* <NAME> Jr. *
* Bautzner Str. 122e *
* 01099 Dresden *
* GERMANY *
* Email: <EMAIL> *
* *
\************************************************************************************/
/*******************************************************************************************
*
* Add .fasta files to a DB:
* Adds the given fasta files in the given order to <path>.db. If the db does not exist
* then it is created. All .fasta files added to a given data base must have the same
* header format and follow Pacbio's convention. A file cannot be added twice and this
* is enforced. The command either builds or appends to the .<path>.idx and .<path>.bps
* files, where the index file (.idx) contains information about each read and their offsets
* in the base-pair file (.bps) that holds the sequences where each base is compessed
* into 2-bits. The two files are hidden by virtue of their names beginning with a '.'.
* <path>.db is effectively a stub file with given name that contains an ASCII listing
* of the files added to the DB and possibly the block partitioning for the DB if DBsplit
* has been called upon it.
*
* Author: <NAME>
* Date : May 2013
* Modify: DB upgrade: now *add to* or create a DB depending on whether it exists, read
* multiple .fasta files (no longer a stdin pipe).
* Date : April 2014
*
********************************************************************************************/
#include <ctype.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/stat.h>
#include <unistd.h>
#include "DB.h"
#include "fileUtils.h"
#include "lib/tracks.h"
#include "FA2x.h"
#include "lib/utils.h"
#ifdef HIDE_FILES
#define PATHSEP "/."
#else
#define PATHSEP "/"
#endif
#define DEF_OPT_X 1000
extern char* optarg;
extern int optind, opterr, optopt;
static char number[ 128 ] =
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
static void parseOptions( int argc, char* argv[], CreateContext* ctx );
static void usage( const char* progname );
void initPacbioRead(pacbio_read* read, int createTracks)
{
read->maxPrologLen = MAX_NAME;
read->maxSequenceLen = MAX_NAME + 60000;
if ((read->prolog = (char*) malloc(read->maxPrologLen)) == NULL)
{
fprintf(stderr, "Unable to allocate prolog buffer\n");
exit(1);
}
if ((read->seq = malloc(read->maxSequenceLen)) == NULL)
{
fprintf(stderr, "Unable to allocate sequence buffer\n");
exit(1);
}
if (createTracks)
{
read->maxtracks = 10;
read->ntracks = 0;
read->maxName = 20;
int maxFields = 20;
read->trackName = (char**) malloc(read->maxtracks * sizeof(char*));
read->trackfields = (int**) malloc(read->maxtracks * sizeof(int*));
int i;
for (i = 0; i < read->maxtracks; i++)
{
if ((read->trackName[i] = (char*) malloc(read->maxName)) == NULL)
{
fprintf(stderr, "Unable to allocate track name buffer\n");
exit(1);
}
if ((read->trackfields[i] = (int*) malloc((maxFields + 2) * sizeof(int))) == NULL)
{
fprintf(stderr, "Unable to allocate track fields buffer\n");
exit(1);
}
bzero(read->trackfields[i], (maxFields + 2) * sizeof(int));
read->trackfields[i][0] = maxFields;
read->trackfields[i][1] = 2;
}
}
else
{
read->maxtracks = 0;
read->ntracks = 0;
read->maxName = 0;
}
}
void resetPacbioRead(pacbio_read* pr)
{
pr->ntracks = 0;
int i;
for (i = 0; i < pr->maxtracks; i++)
{
pr->trackfields[i][1] = 2;
}
pr->well = -1;
pr->beg = -1;
pr->end = -1;
pr->len = 0;
}
static void parse_header( CreateContext* ctx, char* header, pacbio_read* pr )
{
// reset pr
resetPacbioRead( pr );
char* c = header;
char* name = NULL;
char* value = NULL;
pr->hasPacbioHeader = isPacBioHeader( c );
if ( pr->hasPacbioHeader )
{
char* pch;
pch = strchr( c, '/' );
int x = sscanf( pch + 1, "%d/%d_%d\n", &( pr->well ), &( pr->beg ), &( pr->end ) );
if ( x != 3 )
pr->hasPacbioHeader = 0;
}
else
{
pr->well = -1;
pr->beg = -1;
pr->end = -1;
}
if ( ctx->t_create_n )
{
while ( *c != '\0' && *c != '\n' && *c != ' ' )
c++;
if ( *c == ' ' || *c == '\n' )
c++;
while ( *c != '\0' )
{
*( c - 1 ) = '\0';
name = c;
while ( *c != '\n' && (isalnum( *c ) || *c == '_') && *c != '=' )
{
c++;
}
if ( *c != '=' )
{
fprintf( stderr, "malformed track name: '%s'\n", c );
exit( 1 );
}
int i;
int skip = 1;
for ( i = 0 ; i < ctx->t_create_n ; i++ )
{
//printf("header %s <-> %.*s\n", ctx->t_create[i], (int)(c-name), name);
if ( strlen(ctx->t_create[i]) == (size_t)(c - name) && strncmp(ctx->t_create[i], name, c - name) == 0 )
{
skip = 0;
break;
}
}
if (skip)
{
c++;
while ( *c != '\0' && *c != '\n' && *c != ' ' )
c++;
int cont = ( *c == ' ' );
*c = '\0';
if (cont)
{
c += 1;
}
continue;
}
if ( pr->ntracks >= pr->maxtracks )
{
int newSize = pr->ntracks * 1.2 + 10;
pr->maxtracks = newSize;
pr->trackName = (char**)realloc( pr->trackName, newSize * sizeof( char* ) );
pr->trackfields = (int**)realloc( pr->trackfields, newSize * sizeof( int* ) );
int i;
int maxFields = 20;
for ( i = pr->ntracks; i < newSize; i++ )
{
if ( ( pr->trackName[ i ] = (char*)malloc( pr->maxName ) ) == NULL )
{
fprintf( stderr, "Unable to allocate track name buffer\n" );
exit( 1 );
}
if ( ( pr->trackfields[ i ] = (int*)malloc( ( maxFields + 2 ) * sizeof( int ) ) ) == NULL )
{
fprintf( stderr, "Unable to allocate track fields buffer\n" );
exit( 1 );
}
bzero( pr->trackfields[ i ], ( maxFields + 2 ) * sizeof( int ) );
pr->trackfields[ i ][ 0 ] = maxFields;
}
}
int len = strlen( name );
int cur = pr->ntracks;
if ( len > pr->maxName )
{
pr->maxName = len + 10;
int i;
for ( i = 0; i < cur; i++ )
{
pr->trackName[ i ] = (char*)realloc( pr->trackName[ i ], pr->maxName );
}
}
*c = '\0';
int mval = 0;
int cont = 0;
char* endptr;
long val;
do
{
c++;
// add assumption when RQ is parsed
if ( strcmp( name, "RQ" ) == 0 && strncasecmp( c, "0.", 2 ) == 0 )
c = c + 2;
value = c;
while ( *c != '\0' && *c != '\n' && *c != ' ' && *c != ',' )
c++;
mval = ( *c == ',' );
cont = ( *c == ' ' );
*c = '\0';
if ( strcmp( name, TRACK_PACBIO_CHEM ) == 0 )
{
int i = 0;
int numOfChar = strlen( value );
int curf = pr->trackfields[ cur ][ 1 ];
if ( curf + numOfChar >= pr->trackfields[ cur ][ 0 ] )
{
int newFields = curf * 1.2 + numOfChar;
pr->trackfields[ cur ] = (int*)realloc( pr->trackfields[ cur ], ( newFields + 2 ) * sizeof( int ) );
pr->trackfields[ cur ][ 0 ] = newFields;
}
while ( i < numOfChar )
{
pr->trackfields[ cur ][ curf++ ] = (char)value[ i++ ];
pr->trackfields[ cur ][ 1 ] += 1;
}
break;
}
// printf("'%s' -> '%s'\n", name, value);
val = strtol( value, &endptr, 10 );
if ( endptr != NULL && *endptr != '\0' )
{
printf( "non-numeric value %s\n", value );
exit( 1 );
}
int curf = pr->trackfields[ cur ][ 1 ];
if ( curf + 1 == pr->trackfields[ cur ][ 0 ] )
{
uint64 newFields = curf * 1.2 + 10;
pr->trackfields[ cur ] = (int*)realloc( pr->trackfields[ cur ], ( newFields + 2 ) * sizeof( int ) );
pr->trackfields[ cur ][ 0 ] = newFields;
}
pr->trackfields[ cur ][ curf ] = val;
pr->trackfields[ cur ][ 1 ] += 1;
} while ( mval );
// printf("memcpy: cur: %d, name: %s, len: %d\n", cur,name, strlen(name)+1);
memcpy( pr->trackName[ cur ], name, strlen( name ) + 1 );
pr->ntracks++;
if ( cont )
{
c++;
}
}
}
}
void errorExit( CreateContext* ctx )
{
// Error exit: Either truncate or remove the .idx and .bps files as appropriate.
// Remove the new image file <pwd>/<root>.dbx
if ( ctx->ioff != 0 )
{
fseeko( ctx->indx, 0, SEEK_SET );
if ( ftruncate( fileno( ctx->indx ), ctx->ioff ) < 0 )
SYSTEM_READ_ERROR
}
if ( ctx->boff != 0 )
{
fseeko( ctx->bases, 0, SEEK_SET );
if ( ftruncate( fileno( ctx->bases ), ctx->boff ) < 0 )
SYSTEM_READ_ERROR
}
fclose( ctx->indx );
fclose( ctx->bases );
if ( ctx->ioff == 0 )
unlink( Catenate( ctx->pwd, PATHSEP, ctx->root, ".idx" ) );
if ( ctx->boff == 0 )
unlink( Catenate( ctx->pwd, PATHSEP, ctx->root, ".bps" ) );
if ( ctx->istub != NULL )
fclose( ctx->istub );
fclose( ctx->ostub );
unlink( Catenate( ctx->pwd, "/", ctx->root, ".dbx" ) );
exit( 1 );
}
static void findAndAddAvailableTracks( CreateContext* ctx )
{
int rlen, dlen;
char *root, *pwd, *name;
int isdam;
DIR* dirp;
struct dirent* dp;
root = ctx->root;
pwd = ctx->pwd;
rlen = strlen( root );
if ( root == NULL || pwd == NULL )
{
fprintf( stderr, "[ERROR] findAndAddAvailableTracks - database name not available\n" );
exit( 1 );
}
if ( ( dirp = opendir( pwd ) ) == NULL )
{
fprintf( stderr, "[ERROR] findAndAddAvailableTracks - Cannot open directory %s\n", pwd );
}
isdam = 0;
while ( ( dp = readdir( dirp ) ) != NULL ) // Get case dependent root name (if necessary)
{
name = dp->d_name;
if ( strcmp( name, Catenate( "", "", root, ".db" ) ) == 0 )
break;
if ( strcmp( name, Catenate( "", "", root, ".dam" ) ) == 0 )
{
isdam = 1;
break;
}
if ( strcasecmp( name, Catenate( "", "", root, ".db" ) ) == 0 )
{
strncpy( root, name, rlen );
break;
}
if ( strcasecmp( name, Catenate( "", "", root, ".dam" ) ) == 0 )
{
strncpy( root, name, rlen );
isdam = 1;
break;
}
}
if ( dp == NULL )
{
fprintf( stderr, "findAndAddAvailableTracks - Cannot find %s (List_DB_Files)\n", pwd );
closedir( dirp );
exit( 1 );
}
if ( isdam )
printf( "%s\n", Catenate( pwd, "/", root, ".dam" ) );
else
printf( "%s\n", Catenate( pwd, "/", root, ".db" ) );
rewinddir( dirp ); // Report each auxiliary file
while ( ( dp = readdir( dirp ) ) != NULL )
{
name = dp->d_name;
dlen = strlen( name );
#ifdef HIDE_FILES
if ( name[ 0 ] != '.' )
continue;
dlen -= 1;
name += 1;
#endif
if ( dlen < rlen + 1 )
continue;
if ( name[ rlen ] != '.' )
continue;
if ( strncmp( name, root, rlen ) != 0 )
continue;
if ( strcasecmp( name + ( dlen - 4 ), "anno" ) == 0 )
{
name[ dlen - 5 ] = '\0';
char* ptr = strrchr( name, '.' );
if ( ptr != NULL )
find_track( ctx, ptr + 1 );
}
}
closedir( dirp );
}
void initDB( int argc, char** argv, CreateContext* ctx )
{
// parse program options
parseOptions( argc, argv, ctx );
{
int i;
ctx->root = Root( argv[ ctx->lastParameterIdx ], ".db" );
ctx->pwd = PathTo( argv[ ctx->lastParameterIdx ] );
ctx->dbname = Strdup( Catenate( ctx->pwd, "/", ctx->root, ".db" ), "Allocating db name" );
if ( ctx->dbname == NULL )
exit( 1 );
if ( ctx->IFILE == NULL )
ctx->ifiles = argc - ctx->lastParameterIdx - 1;
else
{
File_Iterator* ng;
ctx->ifiles = 0;
ng = init_file_iterator( argc, argv, ctx->IFILE, ctx->lastParameterIdx + 1 );
while ( next_file( ng ) )
ctx->ifiles += 1;
free( ng );
}
ctx->istub = fopen( ctx->dbname, "r" );
if ( ctx->istub == NULL )
{
ctx->ofiles = 0;
ctx->bases = Fopen( Catenate( ctx->pwd, PATHSEP, ctx->root, ".bps" ), "w+" );
ctx->indx = Fopen( Catenate( ctx->pwd, PATHSEP, ctx->root, ".idx" ), "w+" );
if ( ctx->bases == NULL || ctx->indx == NULL )
exit( 1 );
fwrite( ctx->db, sizeof( HITS_DB ), 1, ctx->indx );
ctx->ureads = 0;
ctx->offset = 0;
ctx->boff = 0;
ctx->ioff = 0;
ctx->initialUreads = 0;
}
else
{
if ( fscanf( ctx->istub, DB_NFILE, &ctx->ofiles ) != 1 )
SYSTEM_READ_ERROR
ctx->bases = Fopen( Catenate( ctx->pwd, PATHSEP, ctx->root, ".bps" ), "r+" );
ctx->indx = Fopen( Catenate( ctx->pwd, PATHSEP, ctx->root, ".idx" ), "r+" );
if ( ctx->bases == NULL || ctx->indx == NULL )
exit( 1 );
if ( fread( ctx->db, sizeof( HITS_DB ), 1, ctx->indx ) != 1 )
SYSTEM_READ_ERROR
fseeko( ctx->bases, 0, SEEK_END );
fseeko( ctx->indx, 0, SEEK_END );
ctx->initialUreads = ctx->db->ureads;
ctx->ureads = ctx->db->ureads;
ctx->offset = ftello( ctx->bases );
ctx->boff = ctx->offset;
ctx->ioff = ftello( ctx->indx );
if ( ctx->t_create_n > 0 )
{
findAndAddAvailableTracks( ctx );
}
}
ctx->flist = (char**)Malloc( sizeof( char* ) * ( ctx->ofiles + ctx->ifiles ), "Allocating file list" );
ctx->ostub = Fopen( Catenate( ctx->pwd, "/", ctx->root, ".dbx" ), "w+" );
if ( ctx->ostub == NULL || ctx->flist == NULL )
exit( 1 );
fprintf( ctx->ostub, DB_NFILE, ctx->ofiles + ctx->ifiles );
for ( i = 0; i < ctx->ofiles; i++ )
{
int last;
char prolog[ MAX_NAME ], fname[ MAX_NAME ];
if ( fscanf( ctx->istub, DB_FDATA, &last, fname, prolog ) != 3 )
errorExit( ctx );
if ( ( ctx->flist[ i ] = Strdup( fname, "Adding to file list" ) ) == NULL )
errorExit( ctx );
fprintf( ctx->ostub, DB_FDATA, last, fname, prolog );
}
}
ctx->pr1 = (pacbio_read*)malloc( sizeof( pacbio_read ) );
ctx->pr2 = (pacbio_read*)malloc( sizeof( pacbio_read ) );
initPacbioRead( ctx->pr1, ctx->t_create_n );
initPacbioRead( ctx->pr2, ctx->t_create_n );
ctx->rmax = MAX_NAME + 60000;
ctx->read = (char*)malloc( ctx->rmax + 1 );
if ( ctx->read == NULL )
{
fprintf( stderr, "[Error] Cannot allocate read buffer\n" );
exit( 1 );
}
}
static void addReadToDB( CreateContext* ctx, pacbio_read* prBest )
{
int i, x;
for ( i = 0; i < prBest->len; i++ )
{
x = number[ (int)prBest->seq[ i ] ];
ctx->count[ x ] += 1;
prBest->seq[ i ] = (char)x;
}
HITS_READ hr;
hr.boff = ctx->offset;
hr.rlen = prBest->len;
hr.coff = -1;
hr.flags = DB_BEST;
Compress_Read( prBest->len, prBest->seq );
size_t clen = COMPRESSED_LEN( prBest->len );
if ( fwrite( prBest->seq, 1, clen, ctx->bases ) != clen )
{
fprintf( stderr, "[ERROR] - Unable to write compressed sequence (%s, %d) to database\n", prBest->prolog, prBest->seqIDinFasta );
exit( 1 );
}
if ( fwrite( &hr, sizeof( HITS_READ ), 1, ctx->indx ) != 1 )
{
fprintf( stderr, "[ERROR] - Unable to write HITS_READ (%s, %d) to database\n", prBest->prolog, prBest->seqIDinFasta );
exit( 1 );
}
add_to_track( ctx, find_track( ctx, TRACK_SEQID ), ctx->ureads, prBest->seqIDinFasta );
if ( prBest->hasPacbioHeader )
{
add_to_track( ctx, find_track( ctx, TRACK_PACBIO_HEADER ), ctx->ureads, prBest->well );
add_to_track( ctx, find_track( ctx, TRACK_PACBIO_HEADER ), ctx->ureads, prBest->beg );
add_to_track( ctx, find_track( ctx, TRACK_PACBIO_HEADER ), ctx->ureads, prBest->end );
}
for ( i = 0; i < prBest->ntracks; i++ )
{
int j;
for ( j = 2; j < prBest->trackfields[ i ][ 1 ]; j++ )
add_to_track( ctx, find_track( ctx, prBest->trackName[ i ] ), ctx->ureads, prBest->trackfields[ i ][ j ] );
}
ctx->offset += clen;
ctx->ureads += 1;
ctx->totlen += prBest->len;
if ( prBest->len > ctx->maxlen )
ctx->maxlen = prBest->len;
}
static void readFastaFile( CreateContext* ctx, char* name )
{
FILE* input;
char *path, *core, *prolog;
int nline, eof, rlen;
// Open it: <path>/<core>.fasta, check that core is not too long,
// and checking that it is not already in flist.
path = PathTo( name );
core = Root( name, ".fasta" );
if ( ( input = fopen( Catenate( path, "/", core, ".fasta" ), "r" ) ) == NULL )
{
core = Root( name, ".fa" );
if ( ( input = fopen( Catenate( path, "/", core, ".fa" ), "r" ) ) == NULL )
errorExit( ctx );
}
free( path );
if ( strlen( core ) >= MAX_NAME )
{
fprintf( stderr, "File name over %d chars: '%.200s'\n",
MAX_NAME, core );
errorExit( ctx );
}
{
int j;
for ( j = 0; j < ctx->ofiles; j++ )
if ( strcmp( core, ctx->flist[ j ] ) == 0 )
{
fprintf( stderr, "File %s.fasta is already in database %s.db\n", core, Root( ctx->dbname, ".db" ) );
errorExit( ctx );
}
}
// Get the header of the first line. If the file is empty skip.
rlen = 0;
nline = 1;
eof = ( fgets( ctx->read, MAX_NAME, input ) == NULL );
if ( eof || strlen( ctx->read ) < 1 )
{
fprintf( stderr, "Skipping '%s', file is empty!\n", core );
fclose( input );
free( core );
return;
}
// Add the file name to flist
if ( ctx->VERBOSE )
{
fprintf( stderr, "Adding '%s' ...\n", core );
fflush( stderr );
}
ctx->flist[ ctx->ofiles++ ] = core;
// Check that the first line has PACBIO format, and record prolog in 'prolog'.
if ( ctx->read[ strlen( ctx->read ) - 1 ] != '\n' )
{
fprintf( stderr, "File %s.fasta, Line 1: Fasta line is too long (> %d chars)\n", core, MAX_NAME - 2 );
errorExit( ctx );
}
if ( !eof && ctx->read[ 0 ] != '>' )
{
fprintf( stderr, "File %s.fasta, Line 1: First header in fasta file is missing\n", core );
errorExit( ctx );
}
if ( isPacBioHeader( ctx->read + 1 ) )
{
char* find;
find = index( ctx->read + 1, '/' );
*find = '\0';
prolog = Strdup( ctx->read + 1, "Extracting prolog" );
*find = '/';
}
else
{
prolog = Strdup( "DAZZ_READ", "Extracting prolog" );
}
// Read in all the sequences until end-of-file
pacbio_read *prBest, *prNext;
prNext = ctx->pr1;
prBest = ( ctx->BEST ) ? NULL : ctx->pr1;
{
ctx->pr1->seqIDinFasta = -1;
ctx->pr2->seqIDinFasta = -1;
while ( !eof )
{
// parse header
parse_header( ctx, ctx->read + ( rlen + 1 ), prNext );
prNext->seqIDinFasta += 1;
rlen = 0;
while ( 1 )
{
char* line = NULL;
size_t linelen;
line = fgetln(input, &linelen);
if (!line)
{
eof = 1;
break;
}
if ( rlen + linelen > (size_t)ctx->rmax )
{
ctx->rmax = ( (int)( 1.2 * ctx->rmax ) ) + 1000 + linelen;
ctx->read = (char*)realloc( ctx->read, ctx->rmax + 1 );
if ( ctx->read == NULL )
{
fprintf( stderr, "File %s.fasta, Line %d:", core, nline );
fprintf( stderr, "Out of memory (Allocating line buffer)\n" );
errorExit( ctx );
}
}
if ( line[0] == '>' )
{
memcpy(ctx->read + rlen, line, linelen + 1);
}
else if ( line[linelen - 1] == '\n' )
{
line[linelen - 1] = '\0';
linelen -= 1;
memcpy(ctx->read + rlen, line, linelen);
}
nline += 1;
if (line[0] == '>')
{
break;
}
rlen += linelen;
}
if ( rlen < ctx->opt_min_length )
{
if ( ctx->VERBOSE > 1 )
{
fprintf( stderr, "Warning: skipping read of length %d\n", rlen );
}
continue;
}
if ( ctx->t_create_n && ctx->useFullHqReadsOnly )
{
int i;
for ( i = 0; i < prNext->ntracks; i++ )
{
if ( strcmp( prNext->trackName[ i ], "readType" ) == 0 )
{
break;
}
}
// ignore reads that do not have the readType attribute
if ( i == prNext->ntracks )
continue;
// ignore reads that have not the proper format of readType argument
if ( prNext->trackfields[ i ][ 1 ] != 3 )
continue;
// TODO use enum from dextractUtils
// typedef enum { type_Empty = 0, type_FullHqRead0 = 1, type_FullHqRead1 = 2, type_PartialHqRead0 = 3, type_PartialHqRead1 = 4, type_PartialHqRead2 = 5, type_Multiload = 6, type_Indeterminate = 7, type_NotDefined = 255} readType ;
if ( prNext->trackfields[ i ][ 2 ] != 1 && prNext->trackfields[ i ][ 2 ] != 2 )
continue;
}
prNext->len = rlen;
ctx->read[ rlen ] = '\0';
if ( rlen >= prNext->maxSequenceLen )
{
prNext->maxSequenceLen = ( (int)( 1.2 * rlen ) ) + 1000 + MAX_NAME;
prNext->seq = (char*)realloc( prNext->seq, prNext->maxSequenceLen + 1 );
if ( prNext->seq == NULL )
{
fprintf( stderr, "File %s.fasta, Line %d:", core, nline );
fprintf( stderr, " Out of memory (Allocating line buffer)\n" );
errorExit( ctx );
}
}
memcpy( prNext->seq, ctx->read, rlen );
if ( ctx->BEST )
{
if ( prBest == NULL )
{
if ( prNext == ctx->pr1 )
{
prBest = ctx->pr1;
prNext = ctx->pr2;
}
else
{
prBest = ctx->pr2;
prNext = ctx->pr1;
}
continue;
}
else if ( prBest->well == prNext->well )
{
if ( prBest->len < prNext->len )
{
prBest = prNext;
prNext = ( prBest == ctx->pr1 ) ? ctx->pr2 : ctx->pr1;
}
continue;
}
}
addReadToDB( ctx, prBest );
if ( ctx->BEST )
{
prBest = prNext;
prNext = ( prBest == ctx->pr1 ) ? ctx->pr2 : ctx->pr1;
}
}
// Complete processing of .fasta file: flush last well group, write file line
// in db image, free prolog, and close file
if ( ctx->BEST )
{
addReadToDB( ctx, prBest );
}
fprintf( ctx->ostub, DB_FDATA, ctx->ureads, core, prolog );
}
free( prolog );
fclose( input );
}
static void updateBlockDBOffsets( CreateContext* ctx )
{
// If db has been previously partitioned then calculate additional partition points and
// write to new db file image
int nblock;
if ( ctx->istub && fscanf( ctx->istub, DB_NBLOCK, &nblock ) == 1 )
{
int64 totlen, dbpos, size;
int ireads, rlen;
int ufirst;
HITS_READ record;
int i;
if ( ctx->VERBOSE )
{
fprintf( stderr, "Updating block partition ...\n" );
fflush( stderr );
}
// Read the block portion of the existing db image getting the indices of the first
// read in the last block of the exisiting db as well as the partition parameters.
// Copy the old image block information to the new block information (except for
// the indices of the last partial block)
dbpos = ftello( ctx->ostub );
fprintf( ctx->ostub, DB_NBLOCK, 0 );
if ( fscanf( ctx->istub, DB_PARAMS, &size ) != 1 )
SYSTEM_READ_ERROR
fprintf( ctx->ostub, DB_PARAMS, size );
size *= 1000000ll;
if ( !ctx->appendReadsToNewBlock )
nblock -= 1;
for ( i = 0; i <= nblock; i++ )
{
if ( fscanf( ctx->istub, DB_BDATA, &ufirst ) != 1 )
SYSTEM_READ_ERROR
fprintf( ctx->ostub, DB_BDATA, ufirst );
}
// Seek the first record of the last block of the existing db in .idx, and then
// compute and record partition indices for the rest of the db from this point
// forward.
fseeko( ctx->indx, sizeof( HITS_DB ) + sizeof( HITS_READ ) * ufirst, SEEK_SET );
totlen = 0;
ireads = 0;
for ( i = ufirst; i < ctx->ureads; i++ )
{
if ( fread( &record, sizeof( HITS_READ ), 1, ctx->indx ) != 1 )
SYSTEM_READ_ERROR
rlen = record.rlen;
ireads += 1;
totlen += rlen;
if ( totlen >= size )
{
fprintf( ctx->ostub, " %9d\n", i + 1 );
totlen = 0;
ireads = 0;
nblock += 1;
}
}
if ( ireads > 0 )
{
fprintf( ctx->ostub, DB_BDATA, ctx->ureads );
nblock += 1;
}
fseeko( ctx->ostub, dbpos, SEEK_SET );
fprintf( ctx->ostub, DB_NBLOCK, nblock ); // Rewind and record the new number of blocks
}
}
static void usage(const char* progname)
{
fprintf( stderr, "usage: %s [-vabQ] [-c <track>] [-x <int>] <path:db> (-f file | <path:string> <input:fasta> ...)\n", progname );
fprintf( stderr, "options: -v ... verbose\n" );
fprintf( stderr, " -Q ... only use pacbio reads with readtype FullHqRead\n" );
fprintf( stderr, " -a ... append new reads to new block\n" );
fprintf( stderr, " -b ... only the longest/best read from a pacbio well is incorporated into DB\n" );
fprintf( stderr, " -x ... min read length (%d)\n", DEF_OPT_X );
fprintf( stderr, " -c ... convert fasta header arguments (NAME=x,y) into database tracks\n" );
}
static void parseOptions( int argc, char* argv[], CreateContext* ctx )
{
// set default values
ctx->VERBOSE = 0;
ctx->useFullHqReadsOnly = 0;
// ctx->createTracks = 0;
ctx->BEST = 0;
ctx->appendReadsToNewBlock = 0;
ctx->opt_min_length = DEF_OPT_X;
// parse arguments
int c;
opterr = 0;
while ( ( c = getopt( argc, argv, "vc:abQx:f:" ) ) != -1 )
{
switch ( c )
{
case 'v':
ctx->VERBOSE += 1;
break;
case 'Q':
ctx->useFullHqReadsOnly = 1;
break;
case 'c':
// ctx->createTracks = 1;
if ( ctx->t_create_n + 1 >= ctx->t_create_max )
{
ctx->t_create_max += 10;
ctx->t_create = realloc( ctx->t_create, sizeof(char*) * ctx->t_create_max );
}
ctx->t_create[ ctx->t_create_n ] = optarg;
ctx->t_create_n += 1;
break;
case 'x':
ctx->opt_min_length = atoi( optarg );
break;
case 'b':
ctx->BEST = 1;
break;
case 'a':
ctx->appendReadsToNewBlock = 1;
break;
case 'f':
{
ctx->IFILE = fopen( optarg, "r" );
if ( ctx->IFILE == NULL )
{
fprintf( stderr, "Cannot open file of inputs '%s'\n", optarg );
exit( 1 );
}
break;
}
default:
usage( argv[ 0 ] );
exit( 1 );
}
}
if ( ctx->opt_min_length < 0 )
{
fprintf( stderr, "invalid min read length of %d\n", ctx->opt_min_length );
exit( 1 );
}
if ( ( ctx->IFILE == NULL ) && argc - optind < 2 )
{
usage( argv[ 0 ] );
exit( 1 );
}
ctx->lastParameterIdx = optind;
}
int main( int argc, char* argv[] )
{
HITS_DB db;
CreateContext ctx;
bzero( &ctx, sizeof( CreateContext ) );
ctx.db = &db;
// parse options and init db
initDB( argc, argv, &ctx );
int c;
File_Iterator* ng;
ctx.totlen = 0; // total # of bases in new .fasta files
ctx.maxlen = 0; // longest read in new .fasta files
for ( c = 0; c < 4; c++ ) // count of acgt in new .fasta files
ctx.count[ c ] = 0;
// For each new .fasta file do:
ng = init_file_iterator( argc, argv, ctx.IFILE, ctx.lastParameterIdx + 1 );
while ( next_file( ng ) )
{
if ( ng->name == NULL )
errorExit( &ctx );
readFastaFile( &ctx, ng->name );
}
// Finished loading all sequences: update relevant fields in db record
db.ureads = ctx.ureads;
if ( ctx.istub == NULL )
{
for ( c = 0; c < 4; c++ )
{
db.freq[ c ] = (float)( ( 1. * ctx.count[ c ] ) / ctx.totlen );
}
db.totlen = ctx.totlen;
db.maxlen = ctx.maxlen;
}
else
{
for ( c = 0; c < 4; c++ )
db.freq[ c ] = (float)( ( db.freq[ c ] * db.totlen + ( 1. * ctx.count[ c ] ) ) / ( db.totlen + ctx.totlen ) );
db.totlen += ctx.totlen;
if ( ctx.maxlen > db.maxlen )
db.maxlen = ctx.maxlen;
}
updateBlockDBOffsets( &ctx );
rewind( ctx.indx );
fwrite( &db, sizeof( HITS_DB ), 1, ctx.indx ); // Write the finalized db record into .idx
rewind( ctx.ostub ); // Rewrite the number of files actually added
fprintf( ctx.ostub, DB_NFILE, ctx.ofiles );
if ( ctx.istub != NULL )
fclose( ctx.istub );
fclose( ctx.ostub );
fclose( ctx.indx );
fclose( ctx.bases );
rename( Catenate( ctx.pwd, "/", ctx.root, ".dbx" ), ctx.dbname ); // New image replaces old image
write_tracks( &ctx, ctx.dbname );
// clean up
free_tracks( &ctx );
free( ng );
free( ctx.root );
free( ctx.pwd );
free( ctx.dbname );
return 0;
}
|
MartinPippel/DAmar
|
scrub/LAgap.c
|
/*******************************************************************************************
*
* Author : <NAME>
*
* Date : February 2016
*
*******************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#include <assert.h>
#include <unistd.h>
#include "lib/tracks.h"
#include "lib/pass.h"
#include "lib/oflags.h"
#include "lib/colors.h"
#include "lib/utils.h"
#include "lib/trim.h"
#include "db/DB.h"
#include "dalign/align.h"
// argument defaults
#define DEF_ARG_P 0
#define DEF_ARG_S 0
// thresholds
#define BIN_SIZE 100
#define MIN_LR 450
// switches
#define VERBOSE
#define DEBUG_GAPS
#define DEBUG_CGAPS
#undef DEBUG_CHAIN
#undef DEBUG_CHIMER
// constants
typedef struct
{
Overlap **ovls;
int novl;
int maxOvl;
} Chain;
typedef struct
{
HITS_DB* db;
int twidth;
HITS_TRACK* trackExclude;
HITS_TRACK* trackRepeat;
unsigned int stats_contained;
unsigned int stats_breaks;
unsigned int stats_breaks_novl;
unsigned int stats_chimers;
unsigned int stats_chimers_novl;
int stitch;
uint64* rm_bins;
int rm_maxbins;
int* rc_left;
int rc_maxright;
int* rc_right;
int rc_maxleft;
// for trimming
HITS_TRACK* trackTrim;
int useRLoader;
TRIM* trim;
Read_Loader *rl;
FILE* chimer;
Chain *ovlChains;
int curChains;
int maxChains;
} GapContext;
// for getopt()
extern char* optarg;
extern int optind, opterr, optopt;
static int loader_handler(void* _ctx, Overlap* ovl, int novl)
{
GapContext* ctx = (GapContext*) _ctx;
Read_Loader* rl = ctx->rl;
int i;
for (i = 0; i < novl; i++)
{
int b = ovl[i].bread;
int trim_b_left, trim_b_right;
get_trim(ctx->db, ctx->trackTrim, b, &trim_b_left, &trim_b_right);
if (ovl[i].flags & OVL_COMP)
{
int tmp = trim_b_left;
int blen = DB_READ_LEN(ctx->db, ovl[i].bread);
trim_b_left = blen - trim_b_right;
trim_b_right = blen - tmp;
}
if (trim_b_left >= trim_b_right)
{
continue;
}
int bbt = MAX(trim_b_left, ovl[i].path.bbpos);
int bet = MIN(trim_b_right, ovl[i].path.bepos);
if (bbt >= bet)
{
continue;
}
if (bbt == ovl[i].path.bbpos && bet == ovl[i].path.bepos)
{
continue;
}
bbt = MAX(trim_b_left, ovl[i].path.bbpos);
bet = MIN(trim_b_right, ovl[i].path.bepos);
if (bbt < bet && (bbt != ovl[i].path.bbpos || bet != ovl[i].path.bepos))
{
rl_add(rl, ovl[i].aread);
rl_add(rl, ovl[i].bread);
continue;
}
int bepos = ovl[i].path.bepos;
if (bepos > bet)
{
rl_add(rl, ovl[i].aread);
rl_add(rl, ovl[i].bread);
}
}
return 1;
}
static int drop_break(Overlap* pOvls, int nOvls, int p1, int p2)
{
int max = 0;
int left = 0;
int i;
for (i = 0; i < nOvls; i++)
{
if (pOvls[i].flags & OVL_DISCARD)
{
continue;
}
int len = pOvls[i].path.aepos - pOvls[i].path.abpos;
if (len > max)
{
max = len;
if (pOvls[i].path.abpos < p1)
{
left = 1;
}
else
{
left = 0;
}
}
}
if (max == 0)
{
return 0;
}
int dropped = 0;
if (!left)
{
#ifdef DEBUG_GAPS
printf("DROP L @ %5d..%5d\n", p1, p2);
#endif
for (i = 0; i < nOvls; i++)
{
if (pOvls[i].path.abpos < p1)
{
if (!(pOvls[i].flags & OVL_DISCARD))
{
dropped++;
}
pOvls[i].flags |= OVL_DISCARD | OVL_GAP;
}
}
}
else
{
#ifdef DEBUG_GAPS
printf("DROP R @ %5d..%5d\n", p1, p2);
#endif
for (i = 0; i < nOvls; i++)
{
if (pOvls[i].flags & OVL_DISCARD)
continue;
if (pOvls[i].path.aepos > p2)
{
if (!(pOvls[i].flags & OVL_DISCARD))
{
dropped++;
}
pOvls[i].flags |= OVL_DISCARD | OVL_GAP;
}
}
}
return dropped;
}
static int cmp_ovls_abeg(const void* a, const void* b)
{
Overlap* o1 = *(Overlap**) a;
Overlap* o2 = *(Overlap**) b;
int cmp = o1->path.abpos - o2->path.abpos;
if (!cmp)
{
cmp = (o1->path.aepos - o1->path.abpos) - (o2->path.aepos - o2->path.abpos);
}
return cmp;
}
static int contained(int ab, int ae, int bb, int be)
{
if (ab >= bb && ae <= be)
{
return 1;
}
if (bb >= ab && be <= ae)
{
return 2;
}
return 0;
}
static int cmp_chain_len(const void *a, const void *b)
{
Chain* c1 = (Chain *) a;
Chain* c2 = (Chain *) b;
int i;
int olen1 = c1->ovls[0]->path.aepos - c1->ovls[0]->path.abpos;
for (i = 1; i < c1->novl; i++)
{
olen1 += c1->ovls[i]->path.aepos - c1->ovls[i]->path.abpos;
if (c1->ovls[i - 1]->path.aepos > c1->ovls[i]->path.abpos)
olen1 -= c1->ovls[i - 1]->path.aepos > c1->ovls[i]->path.abpos;
}
int olen2 = c2->ovls[0]->path.aepos - c2->ovls[0]->path.abpos;
for (i = 1; i < c2->novl; i++)
{
olen2 += c2->ovls[i]->path.aepos - c2->ovls[i]->path.abpos;
if (c2->ovls[i - 1]->path.aepos > c2->ovls[i]->path.abpos)
olen2 -= c2->ovls[i - 1]->path.aepos > c2->ovls[i]->path.abpos;
}
return (olen2 - olen1);
}
static int stitchable(Overlap* pOvls, int n, int fuzz, int beg, int end)
{
if (n < 2)
{
return 0;
}
int t = 0;
int k, b;
int ab2, ae1;
int bb2, be1;
const int ignore_mask = OVL_TEMP | OVL_CONT | OVL_TRIM | OVL_STITCH;
int i;
for (i = 0; i < n; i++)
{
if (pOvls[i].flags & ignore_mask)
{
continue;
}
b = pOvls[i].bread;
ae1 = pOvls[i].path.aepos;
be1 = pOvls[i].path.bepos;
for (k = i + 1; k < n && pOvls[k].bread == b; k++)
{
if ((pOvls[k].flags & ignore_mask) || ((pOvls[i].flags & OVL_COMP) != (pOvls[k].flags & OVL_COMP)))
{
continue;
}
ab2 = pOvls[k].path.abpos;
bb2 = pOvls[k].path.bbpos;
int deltaa = abs(ae1 - ab2);
int deltab = abs(be1 - bb2);
if (deltaa < fuzz && deltab < fuzz)
{
if (pOvls[i].path.abpos < beg - MIN_LR && pOvls[k].path.aepos > end + MIN_LR)
{
t++;
// printf("stitch using b %d\n", b);
}
}
}
}
return t;
}
static int ovl_intersect(Overlap* a, Overlap* b)
{
return intersect(a->path.abpos, a->path.aepos, b->path.abpos, b->path.aepos);
}
static int getRepeatCount(GapContext* ctx, int readID, int beg, int end)
{
if (ctx->trackRepeat == NULL)
return 0;
track_anno* rep_anno = ctx->trackRepeat->anno;
track_data* rep_data = ctx->trackRepeat->data;
track_anno rb, re;
int repBases = 0;
int rBeg, rEnd;
if (readID < 0 || readID >= DB_NREADS(ctx->db))
{
fprintf(stderr, "[ERROR] - getRepeatCount readID: %d out of bounds [0, %d]\n", readID, DB_NREADS(ctx->db) - 1);
fflush(stderr);
exit(1);
}
// repeat bases in a-read
rb = rep_anno[readID] / sizeof(track_data);
re = rep_anno[readID + 1] / sizeof(track_data);
while (rb < re)
{
rBeg = rep_data[rb];
rEnd = rep_data[rb + 1];
repBases += intersect(beg, end, rBeg, rEnd);
rb += 2;
}
return repBases;
}
static int getRepeatBases(GapContext *ctx, Overlap *ovl, int read)
{
if (ctx->trackRepeat == NULL)
{
return 0;
}
assert(ovl->aread == read || ovl->bread == read);
int bLen = ovl->path.bepos - ovl->path.bbpos;
// get repeats track
track_anno* rep_anno = ctx->trackRepeat->anno;
track_data* rep_data = ctx->trackRepeat->data;
track_anno rb, re;
int nrep = 0;
rb = rep_anno[read] / sizeof(track_data);
re = rep_anno[read + 1] / sizeof(track_data);
// loop through all repeats in a
int rBeg, rEnd;
while (rb < re)
{
rBeg = rep_data[rb];
rEnd = rep_data[rb + 1];
if (ovl->aread == read)
{
nrep += intersect(ovl->path.abpos, ovl->path.aepos, rBeg, rEnd);
}
else
{
if (ovl->flags & OVL_COMP)
{
nrep += intersect(bLen - ovl->path.bepos, bLen - ovl->path.bbpos, rBeg, rEnd);
}
else
{
nrep += intersect(ovl->path.bbpos, ovl->path.bepos, rBeg, rEnd);
}
}
rb += 2;
}
return nrep;
}
static int spanningChain(GapContext*ctx, Overlap *ovls, int n, int chimerBeg, int chimerEnd, int trim_ab, int trim_ae)
{
/// TODO hard coded
int MIN_OVL_LOOKAHEAD = 2000;
int MAX_OVL_LOOKAHEAD = 10000;
int STRIDE_OVL_LOOKAHEAD = 2000;
int MIN_ANCHOR = 800;
int MIN_CHAIN_LEN = 3000;
int trim_bb, trim_be;
if (ctx->trackTrim)
{
get_trim(ctx->db, ctx->trackTrim, ovls->bread, &trim_bb, &trim_be);
}
else
{
trim_bb = 0;
trim_be = DB_READ_LEN(ctx->db, ovls->bread);
}
#ifdef DEBUG_CHAIN
printf("chain(%d,%d,%d) CHAIN: n%d m%d chim [%d, %d] trim [%d, %d]\n", ovls->aread, ovls->bread, n, ctx->curChains, ctx->maxChains, chimerBeg, chimerEnd, trim_ab, trim_ae);
#endif
if (n < 2)
{
if (
(ovls->path.abpos < chimerBeg && ovls->path.aepos > chimerEnd && (ovls->path.abpos == trim_ab || ovls->path.bbpos <= trim_bb) && (ovls->path.aepos == trim_ae || ovls->path.bepos >= trim_be))
|| (ovls->path.abpos == trim_ab && ovls->path.aepos == trim_ae) // fully spanning trim interval
)
{
#ifdef DEBUG_CHAIN
printf("found spanning overlap %d vs %d\n", ovls->aread, ovls->bread);
#endif
return 1;
}
return 0;
}
int aread, bread;
int alen, blen;
int i;
// reset OVL_TEMP flag
for (i = 0; i < n; i++)
{
if (ovls[i].flags & OVL_TEMP)
ovls[i].flags &= ~OVL_TEMP;
}
aread = ovls->aread;
bread = ovls->bread;
alen = DB_READ_LEN(ctx->db, aread);
blen = DB_READ_LEN(ctx->db, bread);
int nremain = n;
#ifdef DEBUG_CHAIN
printf("find detect already excluded overlaps\n");
#endif
{
for (i = 0; i < n; i++)
{
Overlap *ovl_i = ovls + i;
if (ovl_i->flags & (OVL_CONT))
{
nremain--;
}
}
}
#ifdef DEBUG_CHAIN
printf("nremain %d\n", nremain);
#endif
if (nremain == 0)
return 0;
// mark contained overlaps
#ifdef DEBUG_CHAIN
printf("mark contained overlaps\n");
#endif
{
int j;
for (i = 0; i < n; i++)
{
Overlap *ovl_i = ovls + i;
if (ovl_i->flags & (OVL_CONT | OVL_TEMP))
continue;
for (j = i + 1; j < n; j++)
{
Overlap *ovl_j = ovls + j;
if (ovl_j->flags & (OVL_CONT | OVL_TEMP))
continue;
if (contained(ovl_j->path.abpos, ovl_j->path.aepos, ovl_i->path.abpos, ovl_i->path.aepos)
&& contained(ovl_j->path.bbpos, ovl_j->path.bepos, ovl_i->path.bbpos, ovl_i->path.bepos))
{
nremain--;
ovl_j->flags |= (OVL_TEMP);
}
}
}
}
#ifdef DEBUG_CHAIN
printf("nremain %d\n", nremain);
#endif
assert(nremain >= 1);
while (nremain > 0)
{
int longestUniqOvlBases = -1;
int longestUniqOvlIdx = -1;
int longestOvlBases = -1;
int longestOvlIdx = -1;
// find longest overlap based on number of unique bases
for (i = 0; i < n; i++)
{
Overlap *ovl = ovls + i;
if (ovl->flags & (OVL_CONT | OVL_TEMP))
{
continue;
}
int aLen = ovl->path.aepos - ovl->path.abpos;
int bLen = ovl->path.bepos - ovl->path.bbpos;
int aRep = getRepeatBases(ctx, ovl, ovl->aread);
int bRep = getRepeatBases(ctx, ovl, ovl->bread);
#ifdef DEBUG_CHAIN
printf("%d - %d [%d, %d] [%d, %d], aR %d/%d, bR %d/%d\n", aread, bread, ovl->path.abpos, ovl->path.aepos, ovl->path.bbpos, ovl->path.bepos, aLen, aRep,
bLen, bRep);
#endif
int tmpBases = MAX(aLen - aRep, bLen - bRep);
if (tmpBases > longestUniqOvlBases)
{
longestUniqOvlBases = tmpBases;
longestUniqOvlIdx = i;
}
tmpBases = MAX(aLen, bLen);
if (tmpBases > longestOvlBases)
{
longestOvlBases = tmpBases;
longestOvlIdx = i;
}
}
assert(longestOvlIdx >= 0);
if (longestUniqOvlBases < ctx->twidth && longestOvlBases > longestUniqOvlBases)
{
#ifdef DEBUG_CHAIN
printf("Number of unique bases to low. Use longest overlap.\n");
#endif
longestUniqOvlBases = longestOvlBases;
longestUniqOvlIdx = longestOvlIdx;
}
#ifdef DEBUG_CHAIN
printf("longest overlap:\n");
printf("idx: %d --> uB %d, %d - %d [%d, %d] [%d, %d]\n", longestUniqOvlIdx, longestUniqOvlBases, ovls[longestUniqOvlIdx].aread,
ovls[longestUniqOvlIdx].bread, ovls[longestUniqOvlIdx].path.abpos, ovls[longestUniqOvlIdx].path.aepos, ovls[longestUniqOvlIdx].path.bbpos,
ovls[longestUniqOvlIdx].path.bepos);
#endif
// try to "elongate" longest overlap
// 1st on the right
// 2nd on the left side
if (ctx->curChains == ctx->maxChains)
{
ctx->maxChains = ctx->maxChains * 1.2 + 5;
ctx->ovlChains = (Chain*) realloc(ctx->ovlChains, sizeof(Chain) * ctx->maxChains);
bzero(ctx->ovlChains + ctx->curChains, sizeof(Chain) * (ctx->maxChains - ctx->curChains));
}
Chain *chain = ctx->ovlChains + ctx->curChains;
#ifdef DEBUG_CHAIN
printf("chain: nOvl: %d, maxOvl %d, nremain: %d\n", chain->novl, chain->maxOvl, nremain);
#endif
if (chain->ovls == NULL)
{
chain->novl = 0;
chain->maxOvl = 10;
chain->ovls = (Overlap**) malloc(sizeof(Overlap*) * chain->maxOvl);
#ifdef DEBUG_CHAIN
printf("chain: nOvl: %d, maxOvl %d\n", chain->novl, chain->maxOvl);
#endif
}
chain->ovls[0] = ovls + longestUniqOvlIdx;
chain->ovls[0]->flags |= OVL_TEMP;
chain->novl++;
nremain--;
#ifdef DEBUG_CHAIN
printf("chain: nOvl: %d, maxOvl %d, nremain %d\n", chain->novl, chain->maxOvl, nremain);
#endif
int ab1, ae1;
int bb1, be1;
int ab2, ae2;
int bb2, be2;
if (nremain && longestUniqOvlIdx + 1 < n)
{
ab1 = ovls[longestUniqOvlIdx].path.abpos;
ae1 = ovls[longestUniqOvlIdx].path.aepos;
bb1 = ovls[longestUniqOvlIdx].path.bbpos;
be1 = ovls[longestUniqOvlIdx].path.bepos;
#ifdef DEBUG_CHAIN
printf("extend longest overlap in right direction\n");
#endif
// 1st right
int cont = 1;
int curBestUniqOffset = 1;
int curBestUniqBases = -1;
int curBestBases = -1;
int curBestOffset = 1;
int curBestIntersection = MAX(alen, blen);
while (cont)
{
int stepSize;
for (stepSize = MIN_OVL_LOOKAHEAD; stepSize <= MAX_OVL_LOOKAHEAD && curBestUniqBases == -1; stepSize += STRIDE_OVL_LOOKAHEAD)
{
#ifdef DEBUG_CHAIN
printf("FOR LOOP stepsize %d\n", stepSize);
#endif
for (i = longestUniqOvlIdx + curBestUniqOffset; i < n; i++)
{
Overlap * ovl = ovls + i;
ab2 = ovl->path.abpos;
ae2 = ovl->path.aepos;
bb2 = ovl->path.bbpos;
be2 = ovl->path.bepos;
if ((ovl->flags & OVL_COMP) != (ovls[longestUniqOvlIdx].flags & OVL_COMP))
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> different orientations\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
if (ovl->flags & OVL_CONT)
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> really contained repeat\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
if (ovl->flags & OVL_TEMP)
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> is part of another chain\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
// todo mark those as discard ????
if (contained(ab2, ae2, ab1, ae1))
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> contained repeat in A-interval\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
// todo mark those as discard ????
if (contained(bb2, be2, bb1, be1))
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> contained repeat in B-interval\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
if (ae2 < ae1 || be2 < be1) // also overlap must follow right direction
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> improper right extension direction (stepSize %d)\n", i, ovl->aread, ovl->bread, ab2, ae2,
bb2, be2, stepSize);
#endif
continue;
}
if (MAX(ab2 - ae1, bb2 - be1) > stepSize)
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> gap size too large (stepSize %d)\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2,
stepSize);
#endif
continue;
}
if (ae1 - ab2 > ae2 - ae1 || be1 - bb2 > be2 - be1) // at least 50% overhang
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> overhang too short (stepSize %d)\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2,
stepSize);
#endif
continue;
}
// check if current overlap is better (longer/more unique bases ?) then curBest
int curUniqBasesInAIvl = (ae2 - ab2) - getRepeatBases(ctx, ovl, aread);
int curUniqBasesInBIvl = (be2 - bb2) - getRepeatBases(ctx, ovl, bread);
if (curBestIntersection > MAX(intersect(ab1, ae1, ab2, ae2), intersect(bb1, be1, bb2, be2)) && curBestBases < MIN(ae2 - ab2, be2 - bb2))
{
curBestBases = MIN(ae2 - ab2, be2 - bb2);
curBestOffset = i - longestUniqOvlIdx;
curBestIntersection = MAX(intersect(ab1, ae1, ab2, ae2), intersect(bb1, be1, bb2, be2));
}
if (curBestUniqBases < MIN(curUniqBasesInAIvl, curUniqBasesInBIvl))
{
#ifdef DEBUG_CHAIN
printf("found right current best overlap %d %d %d: [%d, %d] [%d, %d] right side\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
curBestUniqOffset = i - longestUniqOvlIdx;
curBestUniqBases = MIN(curUniqBasesInAIvl, curUniqBasesInBIvl);
}
else if (curBestUniqBases == -1 && stepSize + STRIDE_OVL_LOOKAHEAD > MAX_OVL_LOOKAHEAD) // for repetitive genomes
{
Overlap *tmpOvl = ovls + (longestUniqOvlIdx + curBestOffset);
if ((intersect(ab1, ae1, tmpOvl->path.abpos, tmpOvl->path.aepos) < ae1 - tmpOvl->path.abpos)
&& (intersect(bb1, be1, tmpOvl->path.bbpos, tmpOvl->path.bepos) < be1 - tmpOvl->path.bbpos))
{
curBestUniqOffset = curBestOffset;
curBestUniqBases = 1;
}
}
else
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> cannot be anchored (stepSize %d)\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2,
stepSize);
#endif
}
}
}
// check if left best overlap can be used to extend overlap group on the right side
if (curBestUniqBases < 0) // i.e. there was no good overlap at right side
{
#ifdef DEBUG_CHAIN
printf("could not extend ovlgroup on right side with proper overlap (with stepSize %d)\n", stepSize - STRIDE_OVL_LOOKAHEAD);
#endif
break;
}
/// todo further sanity check necessary ???
ab2 = ovls[longestUniqOvlIdx + curBestUniqOffset].path.abpos;
ae2 = ovls[longestUniqOvlIdx + curBestUniqOffset].path.aepos;
bb2 = ovls[longestUniqOvlIdx + curBestUniqOffset].path.bbpos;
be2 = ovls[longestUniqOvlIdx + curBestUniqOffset].path.bepos;
#ifdef DEBUG_CHAIN
printf("extend ovlgroup with (right): %d %d %d: [%d, %d] [%d, %d] stepSize %d\n", longestUniqOvlIdx + curBestUniqOffset,
ovls[longestUniqOvlIdx + curBestUniqOffset].aread, ovls[longestUniqOvlIdx + curBestUniqOffset].bread, ab1, ae1, ab2, ae2,
stepSize - STRIDE_OVL_LOOKAHEAD);
#endif
if (chain->novl == chain->maxOvl)
{
chain->maxOvl = chain->maxOvl * 1.2 + 5;
chain->ovls = (Overlap**) realloc(chain->ovls, sizeof(Overlap*) * chain->maxOvl);
}
// append left side overlaps at the end of chain, i.e. chain must be sorted afterwards by abpos
chain->ovls[chain->novl] = ovls + (longestUniqOvlIdx + curBestUniqOffset);
chain->ovls[chain->novl]->flags |= OVL_TEMP;
chain->novl++;
nremain--;
#ifdef DEBUG_CHAIN
printf("chain: nOvl: %d, maxOvl %d nremain %d\n", chain->novl, chain->maxOvl, nremain);
#endif
ab1 = ab2;
ae1 = ae2;
bb1 = bb2;
be1 = be2;
curBestUniqOffset++;
curBestOffset = curBestUniqOffset;
curBestUniqBases = -1;
curBestBases = -1;
curBestIntersection = MAX(alen, blen);
if (longestUniqOvlIdx + curBestUniqOffset >= n)
{
cont = 0;
}
}
}
if (nremain && longestUniqOvlIdx > 0)
{
ab1 = ovls[longestUniqOvlIdx].path.abpos;
ae1 = ovls[longestUniqOvlIdx].path.aepos;
bb1 = ovls[longestUniqOvlIdx].path.bbpos;
be1 = ovls[longestUniqOvlIdx].path.bepos;
#ifdef DEBUG_CHAIN
printf("extend longest overlap in left direction\n");
#endif
// 2nd left side
int cont = 1;
int curBestUniqOffset = 1;
int curBestUniqBases = -1;
int curBestBases = -1;
int curBestOffset = 1;
int curBestIntersection = MAX(alen, blen);
while (cont)
{
int stepSize;
for (stepSize = MIN_OVL_LOOKAHEAD; stepSize <= MAX_OVL_LOOKAHEAD && curBestUniqBases == -1; stepSize += STRIDE_OVL_LOOKAHEAD)
{
#ifdef DEBUG_CHAIN
printf("FOR LOOP stepsize %d\n", stepSize);
#endif
// try to find next best overlap with lookahead of stepSize bases
for (i = longestUniqOvlIdx - curBestUniqOffset; i >= 0; --i)
{
Overlap * ovl = ovls + i;
#ifdef DEBUG_CHAIN
printf("LEFT: Check ovl: a[%d, %d] b[%d,%d]\n", ovl->path.abpos, ovl->path.aepos, ovl->path.bbpos, ovl->path.bepos);
#endif
ab2 = ovl->path.abpos;
ae2 = ovl->path.aepos;
bb2 = ovl->path.bbpos;
be2 = ovl->path.bepos;
if ((ovl->flags & OVL_COMP) != (ovls[longestUniqOvlIdx].flags & OVL_COMP))
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> different orientations\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
if (ovl->flags & OVL_CONT)
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> really contained repeat\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
if (ovl->flags & OVL_TEMP)
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> is part of another chain\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
// todo mark those as discard ????
if (contained(ab2, ae2, ab1, ae1))
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> contained repeat in A-interval\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
// todo mark those as discard ????
if (contained(bb2, be2, bb1, be1))
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> contained repeat in B-interval\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
if (ab2 > ab1 || bb2 > bb1) // also overlap must follow left direction
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> improper left extension direction (stepSize %d)\n", i, ovl->aread, ovl->bread, ab2, ae2,
bb2, be2, stepSize);
#endif
continue;
}
if (MAX(ab1 - ae2, bb1 - be2) > stepSize)
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> gap size too large (stepSize %d)\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2,
stepSize);
#endif
continue;
}
if (ae2 - ab1 > ab1 - ab2 || be2 - bb1 > bb1 - bb2) // at least 50% overhang
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> overhang too short (stepSize %d)\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2,
stepSize);
#endif
continue;
}
// check if current overlap is better (longer/more unique bases ?) then curLeftBest
int curUniqBasesInAIvl = (ae2 - ab2) - getRepeatBases(ctx, ovl, aread);
int curUniqBasesInBIvl = (be2 - bb2) - getRepeatBases(ctx, ovl, bread);
if (curBestIntersection > MAX(intersect(ab2, ae2, ab1, ae1), intersect(bb2, be2, bb1, be1)) && curBestBases < MIN(ae2 - ab2, be2 - bb2))
{
curBestBases = MIN(ae2 - ab2, be2 - bb2);
curBestOffset = longestUniqOvlIdx - i;
curBestIntersection = MAX(intersect(ab2, ae2, ab1, ae1), intersect(bb2, be2, bb1, be1));
}
if (curBestUniqBases < MIN(curUniqBasesInAIvl, curUniqBasesInBIvl))
{
#ifdef DEBUG_CHAIN
printf("found left current best overlap %d %d %d: [ab2 %d, ae2 %d] [bb2 %d, be2 %d] left side\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
curBestUniqOffset = longestUniqOvlIdx - i;
curBestUniqBases = curUniqBasesInAIvl + curUniqBasesInBIvl;
}
else if (curBestUniqBases == -1 && stepSize + STRIDE_OVL_LOOKAHEAD > MAX_OVL_LOOKAHEAD) // for repetitive genomes
{
Overlap *tmpOvl = ovls + (longestUniqOvlIdx - curBestOffset);
if ((intersect(tmpOvl->path.abpos, tmpOvl->path.aepos, ab1, ae1) < ae1 - tmpOvl->path.abpos)
&& (intersect(tmpOvl->path.bbpos, tmpOvl->path.bepos, bb1, be1) < be1 - tmpOvl->path.bbpos))
{
curBestUniqOffset = curBestOffset;
curBestUniqBases = 1;
}
}
else
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> cannot be anchored (stepSize %d)\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2,
stepSize);
#endif
}
}
}
// check if left best overlap can be used to extend overlap group on the left side
if (curBestUniqBases < 0) // i.e. there was no good overlap at left side
{
#ifdef DEBUG_CHAIN
printf("could not extend ovlgroup on left side with proper overlap (stepSize %d)\n", stepSize - STRIDE_OVL_LOOKAHEAD);
#endif
break;
}
/// todo further sanity check necessary ???
ab2 = ovls[longestUniqOvlIdx - curBestUniqOffset].path.abpos;
ae2 = ovls[longestUniqOvlIdx - curBestUniqOffset].path.aepos;
bb2 = ovls[longestUniqOvlIdx - curBestUniqOffset].path.bbpos;
be2 = ovls[longestUniqOvlIdx - curBestUniqOffset].path.bepos;
#ifdef DEBUG_CHAIN
printf("extend ovlgroup with (left): %d %d %d: [%d, %d] [%d, %d] with stepSize %d\n", longestUniqOvlIdx - curBestUniqOffset,
ovls[longestUniqOvlIdx - curBestUniqOffset].aread, ovls[longestUniqOvlIdx - curBestUniqOffset].bread, ab1, ae1, ab2, ae2,
stepSize - STRIDE_OVL_LOOKAHEAD);
#endif
if (ctx->curChains == ctx->maxChains)
{
ctx->maxChains = ctx->maxChains * 1.2 + 5;
ctx->ovlChains = (Chain*) realloc(ctx->ovlChains, sizeof(Chain) * ctx->maxChains);
bzero(ctx->ovlChains + ctx->curChains, sizeof(Chain) * (ctx->maxChains - ctx->curChains));
}
if (chain->novl == chain->maxOvl)
{
chain->maxOvl = chain->maxOvl * 1.2 + 5;
chain->ovls = (Overlap**) realloc(chain->ovls, sizeof(Overlap*) * chain->maxOvl);
}
// append left side overlaps at the end of chain, i.e. chain must be sorted afterwards by abpos
chain->ovls[chain->novl] = ovls + (longestUniqOvlIdx - curBestUniqOffset);
chain->ovls[chain->novl]->flags |= OVL_TEMP;
chain->novl++;
nremain--;
#ifdef DEBUG_CHAIN
printf("chain: nOvl: %d, maxOvl %d nremain %d\n", chain->novl, chain->maxOvl, nremain);
#endif
ab1 = ab2;
ae1 = ae2;
bb1 = bb2;
be1 = be2;
curBestUniqOffset++;
curBestOffset = curBestUniqOffset;
curBestUniqBases = -1;
curBestBases = -1;
curBestIntersection = MAX(alen, blen);
if (longestUniqOvlIdx - curBestUniqOffset < 0)
{
cont = 0;
}
}
if (chain->novl > 1)
{ // sort chain
qsort(chain->ovls, chain->novl, sizeof(Overlap*), cmp_ovls_abeg);
}
}
#ifdef DEBUG_CHAIN
printf("chain: nOvl: %d, maxOvl %d nremain: %d\n", chain->novl, chain->maxOvl, nremain);
#endif
// find possible ovls that could be added to chain (i.e. fill gaps)
if (chain->novl > 1 && nremain > 0)
{
#ifdef DEBUG_CHAIN
printf("find possible ovls that could be added to chain (i.e. fill gaps)\n");
#endif
int chainIdx = 0;
int chainLastIdx = chain->novl - 1;
int j;
for (i = 0; i < n; i++)
{
Overlap *ovl = ovls + i;
if ((ovl->flags & (OVL_TEMP | OVL_CONT)) || ((ovl->flags & OVL_COMP) != (chain->ovls[chainIdx]->flags & OVL_COMP)))
continue;
if (ovl->path.abpos < chain->ovls[chainIdx]->path.abpos)
continue;
if (ovl->path.abpos > chain->ovls[chainLastIdx]->path.abpos)
break;
for (j = chainIdx; j < chainLastIdx; j++)
{
if (chain->ovls[j]->path.aepos <= ovl->path.abpos && chain->ovls[j + 1]->path.abpos >= ovl->path.aepos
&& chain->ovls[j]->path.bepos <= ovl->path.bbpos && chain->ovls[j + 1]->path.bbpos >= ovl->path.bepos)
{
Overlap *lastAddedOvl = chain->ovls[chain->novl - 1];
if (intersect(ovl->path.abpos, ovl->path.aepos, lastAddedOvl->path.abpos, lastAddedOvl->path.aepos)
|| intersect(ovl->path.bbpos, ovl->path.bepos, lastAddedOvl->path.bbpos, lastAddedOvl->path.bepos))
break;
if (chain->novl == chain->maxOvl)
{
chain->maxOvl = chain->maxOvl * 1.2 + 5;
chain->ovls = (Overlap**) realloc(chain->ovls, sizeof(Overlap*) * chain->maxOvl);
}
// append left side overlaps at the end of chain, i.e. chain must be sorted afterwards by abpos
ovl->flags |= OVL_TEMP;
chain->ovls[chain->novl] = ovl;
chain->novl++;
nremain--;
#ifdef DEBUG_CHAIN
printf("chain: nOvl: %d, maxOvl %d nremain %d\n", chain->novl, chain->maxOvl, nremain);
#endif
}
if (ovl->path.abpos > chain->ovls[j + 1]->path.abpos)
chainIdx++;
}
}
if (chainLastIdx < chain->novl - 1)
{
qsort(chain->ovls, chain->novl, sizeof(Overlap*), cmp_ovls_abeg);
}
}
if (nremain)
{
// mark remaining ovls as OVL_TEMP if the overlap with a chain overlap !!
#ifdef DEBUG_CHAIN
printf("// mark remaining ovls as DISC if they overlap with a chain overlap !!\n");
#endif
int chainIdx = 0;
int chainLastIdx = chain->novl - 1;
int j;
for (i = 0; i < n; i++)
{
Overlap *ovl = ovls + i;
if ((ovl->flags & (OVL_TEMP | OVL_CONT)) || ((ovl->flags & OVL_COMP) != (chain->ovls[chainIdx]->flags & OVL_COMP)))
continue;
for (j = chainIdx; j <= chainLastIdx; j++)
{
if (intersect(chain->ovls[j]->path.abpos, chain->ovls[j]->path.aepos, ovl->path.abpos, ovl->path.aepos)
|| intersect(chain->ovls[j]->path.bbpos, chain->ovls[j]->path.bepos, ovl->path.bbpos, ovl->path.bepos))
{
ovl->flags |= OVL_TEMP;
nremain--;
#ifdef DEBUG_CHAIN
printf("OVL_TEMP [%d, %d] [%d, %d] nremain %d\n", ovl->path.abpos, ovl->path.aepos, ovl->path.bbpos, ovl->path.bepos, nremain);
#endif
}
if (j + 1 < chain->novl && ovl->path.abpos > chain->ovls[j + 1]->path.abpos)
chainIdx++;
}
}
}
#ifdef DEBUG_CHAIN
printChain(chain);
#endif
// sanity check // there should be no intersection with other chains (with same orientation) possible
int valid = 1;
if (ctx->curChains)
{
#ifdef DEBUG_CHAIN
printf("DO SANITY CHECK\n");
#endif
int j;
for (i = 0; i < ctx->curChains && valid; i++)
{
if ((chain->ovls[0]->flags & OVL_COMP) == (ctx->ovlChains[i].ovls[0]->flags && OVL_COMP))
{
for (j = 0; j < chain->novl; j++)
{
if ((chain->ovls[j]->path.abpos > ctx->ovlChains[i].ovls[0]->path.abpos
&& chain->ovls[j]->path.aepos < ctx->ovlChains[i].ovls[ctx->ovlChains[i].novl - 1]->path.aepos)
|| (chain->ovls[j]->path.bbpos > ctx->ovlChains[i].ovls[0]->path.bbpos
&& chain->ovls[j]->path.bepos < ctx->ovlChains[i].ovls[ctx->ovlChains[i].novl - 1]->path.bepos))
{
#ifdef DEBUG_CHAIN
printf("CHAIN is invalid - DISCARD\n");
#endif
valid = 0;
break;
}
}
}
}
}
if (valid)
ctx->curChains++;
else
{
chain->novl = 0;
}
#ifdef DEBUG_CHAIN
printf("curChain: %d, remain unchained OVls: %d\n", ctx->curChains, nremain);
#endif
}
#ifdef DEBUG_CHAIN
printf("FINAL CHAINS: %d %7d vs %7d\n", ctx->curChains, ctx->ovlChains[0].ovls[0]->aread, ctx->ovlChains[0].ovls[0]->bread);
for (i = 0; i < ctx->curChains; i++)
{
printf(" CHAIN %d/%d: #novl %d\n", i + 1, ctx->curChains, ctx->ovlChains[0].novl);
int j;
for (j = 0; j < ctx->ovlChains[i].novl; j++)
{
printf(" OVL %d/%d: a[%7d, %7d] b[%7d, %7d] %s\n", j + 1, ctx->ovlChains[i].novl, ctx->ovlChains[i].ovls[j]->path.abpos,
ctx->ovlChains[i].ovls[j]->path.aepos, ctx->ovlChains[i].ovls[j]->path.bbpos, ctx->ovlChains[i].ovls[j]->path.bepos,
(ctx->ovlChains[i].ovls[j]->flags & OVL_COMP) ? "COMP" : "NORM");
}
}
#endif
// sort chains according to alignment lengths
if (ctx->curChains > 1)
{
#ifdef DEBUG_CHAIN
printf("SORT CHAINS (longest first):\n");
#endif
qsort(ctx->ovlChains, ctx->curChains, sizeof(Chain), cmp_chain_len);
#ifdef DEBUG_CHAIN
printf("FINAL CHAINS: %d %7d vs %7d\n", ctx->curChains, ctx->ovlChains[0].ovls[0]->aread, ctx->ovlChains[0].ovls[0]->bread);
for (i = 0; i < ctx->curChains; i++)
{
printf(" CHAIN %d/%d: #novl %d\n", i + 1, ctx->curChains, ctx->ovlChains[0].novl);
int j;
for (j = 0; j < ctx->ovlChains[i].novl; j++)
{
printf(" OVL %d/%d: a[%7d, %7d] b[%7d, %7d] %s\n", j + 1, ctx->ovlChains[i].novl, ctx->ovlChains[i].ovls[j]->path.abpos,
ctx->ovlChains[i].ovls[j]->path.aepos, ctx->ovlChains[i].ovls[j]->path.bbpos, ctx->ovlChains[i].ovls[j]->path.bepos,
(ctx->ovlChains[i].ovls[j]->flags & OVL_COMP) ? "COMP" : "NORM");
}
}
#endif
}
// check if chain spans putative chimer
Chain* bestChain = ctx->ovlChains;
if (bestChain->ovls[0]->path.abpos + MIN(MIN_ANCHOR, chimerBeg - trim_ab) > chimerBeg)
return 0;
if (bestChain->ovls[bestChain->novl - 1]->path.aepos - MIN(MIN_ANCHOR, trim_ae - chimerEnd) < chimerEnd)
return 0;
int chainLen = 0;
for (i = 0; i < bestChain->novl; i++)
chainLen += bestChain->ovls[i]->path.aepos - bestChain->ovls[i]->path.abpos;
if (chainLen < MIN_CHAIN_LEN)
return 0;
// chain must be proper
// todo
// 1. allow not fully proper chain? i.e. that start/end near the tips of the trim intervals????
// 2. set a minimum overlaps length to avoid 'sparse chains' (only induced be repeats)
// 3. set a minimum of non-repeat bases for a chain
if (((bestChain->ovls[0]->path.abpos <= trim_ab) || (bestChain->ovls[0]->path.bbpos <= trim_bb))
&& ((bestChain->ovls[bestChain->novl - 1]->path.aepos >= trim_ae) || (bestChain->ovls[bestChain->novl - 1]->path.bepos >= trim_be)))
{
#ifdef DEBUG_CHAIN
printf("found spanning chain %d vs %d\n", ovls->aread, ovls->bread);
#endif
return 1;
}
return 0;
}
static int oChainIntervalIntersection(GapContext *fctx, Overlap* ovls, int novl, int b, int e, int trim_ab, int trim_ae)
{
int spanningChains = 0;
int j, k;
j = k = 0;
while (j < novl)
{
while (k < novl - 1 && ovls[j].bread == ovls[k + 1].bread)
{
k++;
}
spanningChains += spanningChain(fctx, ovls + j, k - j + 1, b, e, trim_ab, trim_ae);
{
// reset chain and ovl counter
int i;
for (i = 0; i < fctx->curChains; i++)
fctx->ovlChains[i].novl = 0;
fctx->curChains = 0;
}
if(spanningChains)
return spanningChains;
j = k + 1;
}
return spanningChains;
}
static int handle_chimers(GapContext* ctx, Overlap* ovls, int novl)
{
int *alnBeg = (int *) malloc((DB_READ_MAXLEN(ctx->db) / ctx->twidth + 1) * sizeof(int));
memset(alnBeg, 0, (DB_READ_MAXLEN(ctx->db) / ctx->twidth + 1) * sizeof(int));
int *alnEnd = (int *) malloc((DB_READ_MAXLEN(ctx->db) / ctx->twidth + 1) * sizeof(int));
memset(alnEnd, 0, (DB_READ_MAXLEN(ctx->db) / ctx->twidth + 1) * sizeof(int));
int trim_ab, trim_ae;
if (ctx->trackTrim)
{
get_trim(ctx->db, ctx->trackTrim, ovls->aread, &trim_ab, &trim_ae);
}
else
{
trim_ab = 0;
trim_ae = DB_READ_LEN(ctx->db, ovls->aread);
}
if (trim_ab >= trim_ae)
{
return 1;
}
#ifdef DEBUG_CHIMER
printf("filter_chimers aread %d #ovls %d trim [%d, %d]\n", ovls->aread, novl, trim_ab, trim_ae);
#endif
int i;
for (i = 1; i < novl - 1; i++)
{
Overlap *opre = ovls + i - 1;
Overlap *ocur = ovls + i;
Overlap *opas = ovls + i + 1;
int prematEnd = (ocur->path.bepos + 1000 < DB_READ_LEN(ctx->db, ocur->bread)) && (ocur->path.aepos + 1000 < trim_ae) && (ocur->path.aepos - 100 > trim_ab);
int prematBeg = (ocur->path.bbpos > 1000) && (ocur->path.abpos > trim_ab + 1000) && (ocur->path.abpos + 100 < trim_ae);
// // check weird case first
if (prematBeg && prematEnd && (opre->bread != ocur->bread) && (ocur->bread != opas->bread)) // most probably a repeat
continue;
if ((ocur->bread != opas->bread) && prematEnd)
{
alnEnd[(ocur->path.aepos / ctx->twidth)] += 1;
#ifdef DEBUG_CHIMER
printf("found end %d vs %d a[%d, %d] b[%d, %d] ends[%d]=%d\n", ocur->aread, ocur->bread, ocur->path.abpos, ocur->path.aepos, ocur->path.bbpos,
ocur->path.bepos, (ocur->path.aepos / ctx->twidth), alnEnd[(ocur->path.aepos / ctx->twidth)]);
#endif
}
else if ((opre->bread != ocur->bread) && prematBeg)
{
alnBeg[(ocur->path.abpos / ctx->twidth)] += 1;
#ifdef DEBUG_CHIMER
printf("found beg %d vs %d a[%d, %d] b[%d, %d] beg[%d]=%d\n", ocur->aread, ocur->bread, ocur->path.abpos, ocur->path.aepos, ocur->path.bbpos,
ocur->path.bepos, (ocur->path.abpos / ctx->twidth), alnBeg[(ocur->path.abpos / ctx->twidth)]);
#endif
}
}
int chimBeg = -1;
int chimEnd = -1;
int numChim = 0;
int j;
i = j = 0;
// todo border coverage hard coded - find a dynamic approach
int BORDER_COV = 5;
// todo hard coded -
int MAX_CHIMER_LEN = 12000;
for (i = 0; i <= trim_ae / ctx->twidth && numChim == 0; i++)
{
if (alnEnd[i] >= BORDER_COV)
{
chimBeg = i;
}
else if (alnEnd[i + 1] >= BORDER_COV)
{
chimBeg = ++i;
}
else if (alnEnd[i] + alnEnd[i + 1] >= BORDER_COV)
{
chimBeg = i;
}
if (chimBeg < 0)
continue;
for (j = 0; j <= trim_ae / ctx->twidth && numChim == 0; j++)
{
if (alnBeg[j] >= BORDER_COV)
{
chimEnd = j;
}
else if (alnBeg[j + 1] >= BORDER_COV)
{
chimEnd = ++j;
}
else if (alnBeg[j] + alnBeg[j + 1] >= BORDER_COV)
{
chimEnd = j + 1;
}
if (chimEnd < 0)
continue;
#ifdef DEBUG_CHIMER
printf("check putative chimer indexes [%d, %d]\n", chimBeg, chimEnd);
#endif
chimBeg = i * ctx->twidth;
chimEnd *= ctx->twidth;
if (chimBeg > chimEnd)
{
int tmp = chimBeg;
chimBeg = chimEnd;
chimEnd = tmp;
}
#ifdef DEBUG_CHIMER
printf("check putative chimer interval [%d, %d]\n", chimBeg, chimEnd);
#endif
if((chimEnd - chimBeg) > MAX_CHIMER_LEN)
{
#ifdef DEBUG_CHIMER
printf("chimer interval too large [%d, %d] len %d-- IGNORED\n", chimBeg, chimEnd, (chimEnd - chimBeg));
#endif
chimEnd = -1;
continue;
}
int tmpRep = getRepeatCount(ctx, ovls->aread, chimBeg, chimEnd);
#ifdef DEBUG_CHIMER
printf("getRepeatCount %d %d %d: %d\n", ovls->aread, chimBeg, chimEnd, tmpRep);
#endif
if ((chimEnd - chimBeg) > 1000 && tmpRep * 1.0 / (chimEnd - chimBeg) < 0.7)
{
#ifdef DEBUG_CHIMER
printf("chimer interval too large [%d, %d] len %d but not repetitive %.2f%%-- IGNORED\n", chimBeg, chimEnd, (chimEnd - chimBeg),
tmpRep * 1.0 / (chimEnd - chimBeg));
#endif
chimEnd = -1;
continue;
}
int intersectBreads = oChainIntervalIntersection(ctx, ovls, novl, chimBeg, chimEnd, trim_ab, trim_ae);
#ifdef DEBUG_CHIMER
printf("intersectBreads %d\n", intersectBreads);
#endif
if (intersectBreads < 1)
{
++numChim;
#ifdef DEBUG_CHIMER
printf("FOUND CHIMER %d [%d, %d]\n", ovls->aread, chimBeg, chimEnd);
#endif
break;
}
chimEnd = -1;
j+=2; // don't check neighboring walls
}
chimBeg = -1;
i+=2; // don't check neighboring walls
}
if (numChim)
{
// discard all overlaps from current aread
// write and aread id to file
for (i = 0; i < novl; i++)
{
ovls[i].flags |= (OVL_GAP | OVL_DISCARD);
}
#ifdef DEBUG_CHIMER
fprintf(ctx->chimer, "%d\n", ovls->aread);
#endif
#ifdef VERBOSE
printf("CHIMER %d [%d, %d] - discarded overlaps %d\n", ovls->aread, chimBeg, chimEnd, novl);
#endif
ctx->stats_chimers++;
ctx->stats_chimers_novl += novl;
}
free(alnBeg);
free(alnEnd);
return 1;
}
static int handle_repeat_chimers(GapContext* ctx, Overlap* ovls, int novl)
{
HITS_TRACK* trackRepeat = ctx->trackRepeat;
int a = ovls->aread;
int trim_left, trim_right;
get_trim(ctx->db, ctx->trackTrim, a, &trim_left, &trim_right);
track_anno* ta = trackRepeat->anno;
track_data* td = trackRepeat->data;
track_anno tab = ta[a] / sizeof(track_data);
track_anno tae = ta[a + 1] / sizeof(track_data);
while (tab < tae)
{
track_data rb = td[tab];
track_data re = td[tab + 1];
while (tab < tae - 2 && re + 100 > td[tab + 2])
{
tab += 2;
re = td[tab + 1];
}
tab += 2;
if (rb - 100 <= trim_left || re + 100 >= trim_right)
{
continue;
}
int cross_l, cross_r;
int terminate_l, terminate_r;
cross_l = cross_r = terminate_l = terminate_r = 0;
int i;
for (i = 0; i < novl; i++)
{
Overlap* ovl = ovls + i;
if (ovl->path.abpos < rb - 100)
{
if (ovl->path.aepos > re - 100 && ovl->path.aepos < re + 100)
{
terminate_r += 1;
}
else if (ovl->path.aepos > re + 100)
{
cross_r += 1;
}
}
if (ovl->path.aepos > re + 100)
{
if (ovl->path.abpos > rb - 100 && ovl->path.abpos < rb + 100)
{
terminate_l += 1;
}
else if (ovl->path.abpos < rb - 100)
{
cross_l += 1;
}
}
}
if (cross_l < 2 && cross_r < 2 && terminate_l > 2 && terminate_r > 2)
{
drop_break(ovls, novl, rb, re);
#ifdef DEBUG_CGAPS
printf("%7d %5d..%5d CL %3d TL %3d CR %3d TR %3d\n", a, rb, re, cross_l, terminate_l, cross_r, terminate_r);
#endif
}
}
return 1;
}
static int handle_gaps_and_breaks(GapContext* ctx, Overlap* ovls, int novl)
{
int stitch = ctx->stitch;
HITS_TRACK* trackExclude = ctx->trackExclude;
bzero(ctx->rm_bins, sizeof(uint64) * ctx->rm_maxbins);
int trim_b = INT_MAX;
int trim_e = 0;
int i;
for (i = 0; i < novl; i++)
{
Overlap* ovl = ovls + i;
if ((ovl->flags & OVL_DISCARD) || (ovl->aread == ovl->bread))
{
continue;
}
int j;
for (j = i + 1; j < novl && ovls[j].bread == ovl->bread; j++)
{
if (ovl_intersect(ovl, ovls + j))
{
if (ovl->path.aepos - ovl->path.abpos < ovls[j].path.aepos - ovls[j].path.abpos)
{
ovl->flags |= OVL_TEMP;
}
else
{
ovls[j].flags |= OVL_TEMP;
}
}
}
if (ovl->flags & OVL_TEMP)
{
continue;
}
int b = (ovl->path.abpos + MIN_LR) / BIN_SIZE;
int e = (ovl->path.aepos - MIN_LR) / BIN_SIZE;
trim_b = MIN(ovl->path.abpos, trim_b);
trim_e = MAX(ovl->path.aepos, trim_e);
while (b < e)
{
ctx->rm_bins[b]++;
b++;
}
}
if (trim_b >= trim_e)
{
return 1;
}
// printf("trim %d..%d\n", trim_b, trim_e);
int b = (trim_b + MIN_LR) / BIN_SIZE;
int e = (trim_e - MIN_LR) / BIN_SIZE;
int beg = -1;
while (b < e)
{
// if (ctx->rm_bins[b] != 0)
if (ctx->rm_bins[b] > 1)
{
if (beg != -1)
{
int breakb = (beg - 1) * BIN_SIZE;
int breake = (b + 1) * BIN_SIZE;
#ifdef DEBUG_GAPS
printf("READ %7d BREAK %3d..%3d ", ovls->aread, beg, b);
#endif
// break covered by track interval
int skip = 0;
if (trackExclude)
{
track_anno* ta = trackExclude->anno;
track_data* td = trackExclude->data;
track_anno tab = ta[ovls->aread] / sizeof(track_data);
track_anno tae = ta[ovls->aread + 1] / sizeof(track_data);
int masked = 0;
track_data maskb, maske;
while (tab < tae)
{
maskb = td[tab];
maske = td[tab + 1];
if (breakb > maskb && breake < maske)
{
masked = 1;
break;
}
tab += 2;
}
if (masked)
{
#ifdef DEBUG_GAPS
printf(" MASKED %5d..%5d\n", maskb, maske);
#endif
skip = 1;
}
}
if (!skip && stitch > 0)
{
int nstitch = stitchable(ovls, novl, stitch, breakb, breake);
if (nstitch)
{
#ifdef DEBUG_GAPS
printf(" STITCHABLE using %d\n", nstitch);
#endif
skip = 1;
}
}
if (!skip)
{
#ifdef DEBUG_GAPS
printf("\n");
#endif
ctx->stats_breaks += 1;
ctx->stats_breaks_novl += drop_break(ovls, novl, breakb, breake);
}
beg = -1;
}
}
else
{
if (beg == -1)
{
beg = b;
}
}
b++;
}
if (beg != -1)
{
int breakb = (beg - 1) * BIN_SIZE;
int breake = (b + 1) * BIN_SIZE;
ctx->stats_breaks += 1;
ctx->stats_breaks_novl += drop_break(ovls, novl, breakb, breake);
}
return 1;
}
static int drop_containments(GapContext* ctx, Overlap* ovl, int novl)
{
if (novl < 2)
{
return 1;
}
int i;
int ab1, ab2, ae1, ae2;
int bb1, bb2, be1, be2;
for (i = 0; i < novl; i++)
{
int bread = ovl[i].bread;
if ((ovl[i].flags & OVL_DISCARD) || ovl[i].aread == bread)
{
continue;
}
int blen = DB_READ_LEN(ctx->db, bread);
ab1 = ovl[i].path.abpos;
ae1 = ovl[i].path.aepos;
if (ovl[i].flags & OVL_COMP)
{
bb1 = blen - ovl[i].path.bepos;
be1 = blen - ovl[i].path.bbpos;
}
else
{
bb1 = ovl[i].path.bbpos;
be1 = ovl[i].path.bepos;
}
int k;
for (k = i + 1; k < novl; k++)
{
if (ovl[k].flags & OVL_DISCARD)
{
continue;
}
if (ovl[k].bread != bread)
{
break;
}
ab2 = ovl[k].path.abpos;
ae2 = ovl[k].path.aepos;
if (ovl[k].flags & OVL_COMP)
{
bb2 = blen - ovl[k].path.bepos;
be2 = blen - ovl[k].path.bbpos;
}
else
{
bb2 = ovl[k].path.bbpos;
be2 = ovl[k].path.bepos;
}
int cont = contained(ab1, ae1, ab2, ae2);
if (cont && contained(bb1, be1, bb2, be2))
{
#ifdef VERBOSE_CONTAINMENT
printf("CONTAINMENT %8d @ %5d..%5d -> %8d @ %5d..%5d\n"
" %5d..%5d -> %8d @ %5d..%5d\n",
a, ab1, ae1, ovl[i].bread, bb1, be1,
ab2, ae2, ovl[k].bread, bb2, be2);
#endif
if (cont == 1)
{
ovl[i].flags |= OVL_DISCARD | OVL_CONT;
ctx->stats_contained++;
break;
}
else if (cont == 2)
{
ovl[k].flags |= OVL_DISCARD | OVL_CONT;
ctx->stats_contained++;
}
}
}
}
return 1;
}
static void gaps_pre(PassContext* pctx, GapContext* ctx)
{
#ifdef VERBOSE
printf(ANSI_COLOR_GREEN "PASS gaps" ANSI_COLOR_RESET "\n");
#endif
ctx->twidth = pctx->twidth;
ctx->rm_maxbins = ( DB_READ_MAXLEN(ctx->db) + BIN_SIZE) / BIN_SIZE;
ctx->rm_bins = malloc(sizeof(uint64) * ctx->rm_maxbins);
ctx->rc_left = NULL;
ctx->rc_maxleft = 0;
ctx->rc_right = NULL;
ctx->rc_maxright = 0;
// trim
ctx->trim = trim_init(ctx->db, pctx->twidth, ctx->trackTrim, ctx->rl);
// chimer detection
if (ctx->chimer != NULL)
{
ctx->curChains = 0;
ctx->maxChains = 5;
ctx->ovlChains = (Chain*) malloc(sizeof(Chain) * ctx->maxChains);
bzero(ctx->ovlChains, sizeof(Chain) * ctx->maxChains);
}
}
static void gaps_post(GapContext* ctx)
{
#ifdef VERBOSE
if (ctx->trackTrim)
{
printf("%13lld of %13lld overlaps trimmed\n", ctx->trim->nTrimmedOvls, ctx->trim->nOvls);
printf("%13lld of %13lld bases trimmed\n", ctx->trim->nTrimmedBases, ctx->trim->nOvlBases);
}
printf("dropped %d containments\n", ctx->stats_contained);
printf("dropped %d overlaps in %d break/gaps\n", ctx->stats_breaks_novl, ctx->stats_breaks);
if (ctx->chimer)
{
printf("dropped %d overlaps in %d chimers\n", ctx->stats_chimers_novl, ctx->stats_chimers);
}
#endif
free(ctx->rm_bins);
free(ctx->rc_left);
free(ctx->rc_right);
if (ctx->trackTrim)
{
trim_close(ctx->trim);
}
if (ctx->chimer)
{
int i;
for (i = 0; i < ctx->maxChains; i++)
{
Chain *chain = ctx->ovlChains + i;
if (chain)
free(chain->ovls);
else
break;
}
free(ctx->ovlChains);
}
}
static int gaps_handler(void* _ctx, Overlap* ovl, int novl)
{
GapContext* ctx = (GapContext*) _ctx;
// trim
if (ctx->trackTrim)
{
int i;
for (i = 0; i < novl; i++)
trim_overlap(ctx->trim, ovl + i);
}
drop_containments(ctx, ovl, novl);
handle_gaps_and_breaks(ctx, ovl, novl);
// if (ctx->trackRepeat)
// {
// handle_repeat_chimers(ctx, ovl, novl);
// }
if (ctx->chimer)
{
handle_chimers(ctx, ovl, novl);
}
return 1;
}
static void usage()
{
fprintf(stderr, "usage: [-s <int>] [-pL] [-etR <track>] [-C file] <db> <ovl.in> <ovl.out>\n");
fprintf(stderr, "options: -s ... stitch distance (%d)\n", DEF_ARG_S);
fprintf(stderr, " -p ... purge discarded overlaps\n");
fprintf(stderr, " -e ... exclude gaps in track intervals\n");
fprintf(stderr, " -t ... trim overlaps before gap detection\n");
fprintf(stderr, " -L ... two pass processing with read caching\n");
fprintf(stderr, "EXPERIMENTAL: \n");
fprintf(stderr, " -C ... discard chimeric reads and overlaps. Write chimer reads IDs into <file>.\n");
fprintf(stderr, " -R ... repeat track - used to detect chimers in large repeats\n");
}
int main(int argc, char* argv[])
{
HITS_DB db;
PassContext* pctx;
FILE* fileOvlIn;
FILE* fileOvlOut;
GapContext gctx;
// process arguments
int arg_purge = DEF_ARG_P;
char* arg_trimTrack = NULL;
char* excludeTrack = NULL;
char* repeatTrack = NULL;
char* chimerFile = NULL;
bzero(&gctx, sizeof(GapContext));
gctx.stitch = DEF_ARG_S;
opterr = 0;
int c;
while ((c = getopt(argc, argv, "Ls:pe:R:t:C:")) != -1)
{
switch (c)
{
case 'R':
repeatTrack = optarg;
break;
case 'e':
excludeTrack = optarg;
break;
case 'C':
chimerFile = optarg;
break;
case 't':
arg_trimTrack = optarg;
break;
case 's':
gctx.stitch = atoi(optarg);
break;
case 'p':
arg_purge = 1;
break;
case 'L':
gctx.useRLoader = 1;
break;
default:
usage();
exit(1);
}
}
if (argc - optind < 3)
{
usage();
exit(1);
}
char* pcPathReadsIn = argv[optind++];
char* pcPathOverlapsIn = argv[optind++];
char* pcPathOverlapsOut = argv[optind++];
if ((fileOvlIn = fopen(pcPathOverlapsIn, "r")) == NULL)
{
fprintf(stderr, "could not open input track '%s'\n", pcPathOverlapsIn);
exit(1);
}
if ((fileOvlOut = fopen(pcPathOverlapsOut, "w")) == NULL)
{
fprintf(stderr, "could not open output track '%s'\n", pcPathOverlapsOut);
exit(1);
}
if (Open_DB(pcPathReadsIn, &db))
{
fprintf(stderr, "could not open database '%s'\n", pcPathReadsIn);
exit(1);
}
if (excludeTrack)
{
gctx.trackExclude = track_load(&db, excludeTrack);
if (!gctx.trackExclude)
{
fprintf(stderr, "could not open track '%s'\n", excludeTrack);
exit(1);
}
}
if (chimerFile)
{
gctx.chimer = fopen(chimerFile, "w");
if (gctx.chimer == NULL)
{
fprintf(stderr, "could not open chimer file '%s'\n", chimerFile);
exit(1);
}
if (repeatTrack == NULL)
{
fprintf(stderr, "to detect chimers in large repeat regions a repeat track is necessary! \n");
exit(1);
}
if (arg_trimTrack == NULL)
{
fprintf(stderr, "to detect chimers in repeat regions a trim track is necessary! \n");
exit(1);
}
}
if (repeatTrack)
{
gctx.trackRepeat = track_load(&db, repeatTrack);
if (!gctx.trackRepeat)
{
fprintf(stderr, "could not open track '%s'\n", repeatTrack);
exit(1);
}
}
gctx.db = &db;
if (arg_trimTrack != NULL)
{
gctx.trackTrim = track_load(gctx.db, arg_trimTrack);
if (!gctx.trackTrim)
{
fprintf(stderr, "could not open track '%s'\n", arg_trimTrack);
exit(1);
}
if (gctx.useRLoader)
{
gctx.rl = rl_init(&db, 1);
pctx = pass_init(fileOvlIn, NULL);
pctx->data = &gctx;
pctx->split_b = 1;
pctx->load_trace = 0;
pass(pctx, loader_handler);
rl_load_added(gctx.rl);
pass_free(pctx);
}
}
pctx = pass_init(fileOvlIn, fileOvlOut);
pctx->split_b = 0;
pctx->load_trace = 1;
pctx->unpack_trace = (gctx.trackTrim == NULL ? 0 : 1);
pctx->data = &gctx;
pctx->write_overlaps = 1;
pctx->purge_discarded = arg_purge;
gaps_pre(pctx, &gctx);
pass(pctx, gaps_handler);
gaps_post(&gctx);
// cleanup
Close_DB(&db);
if (gctx.useRLoader)
{
rl_free(gctx.rl);
}
pass_free(pctx);
fclose(fileOvlIn);
fclose(fileOvlOut);
if (gctx.chimer)
fclose(gctx.chimer);
return 0;
}
|
MartinPippel/DAmar
|
scrub/LAlocal.c
|
<filename>scrub/LAlocal.c
/*******************************************************************************************
*
* creates a repeat annotation track (named -t) based on local alignments
*
* Date : February 2016
*
* Author : <NAME>
*
*******************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <sys/param.h>
#include <assert.h>
#include <unistd.h>
#include "lib/tracks.h"
#include "lib/colors.h"
#include "lib/oflags.h"
#include "lib/pass.h"
#include "lib/utils.h"
#include "db/DB.h"
#include "dalign/align.h"
// constants
#define DEF_ARG_H 5
#define DEF_ARG_L 3
#define DEF_ARG_T "lrepeats"
// toggles
#define VERBOSE
#undef DEBUG_LOCAL
// macros
typedef struct
{
HITS_DB* db;
HITS_TRACK* track_trim;
// arguments
int cnt_enter;
int cnt_leave;
char* rp_track;
int rp_block;
int merge_distance;
// repeat pass
int rp_emax;
int rp_dmax;
int rp_dcur;
track_data* rp_data;
track_anno* rp_anno;
int* rp_events;
uint64_t stats_bases;
uint64_t stats_repeat_bases;
uint64_t stats_merged;
} RepeatContext;
extern char* optarg;
extern int optind, opterr, optopt;
static int cmp_repeats_events(const void* x, const void* y)
{
int* e1 = (int*)x;
int* e2 = (int*)y;
int cmp = abs(*e1) - abs(*e2);
if (cmp == 0)
{
cmp = (*e1) - (*e2);
}
return cmp;
}
static void pre_repeats(RepeatContext* ctx)
{
#ifdef VERBOSE
printf(ANSI_COLOR_GREEN "PASS repeats\n" ANSI_COLOR_RESET);
#endif
ctx->track_trim = track_load(ctx->db, TRACK_TRIM);
if (!ctx->track_trim)
{
fprintf(stderr, "error: failed to load track %s\n", TRACK_TRIM);
exit(1);
}
ctx->rp_emax = 100;
ctx->rp_events = (int*)malloc(sizeof(int) * ctx->rp_emax);
ctx->rp_anno = (track_anno*)malloc(sizeof(track_anno) * ( DB_NREADS(ctx->db) + 1));
bzero(ctx->rp_anno, sizeof(track_anno)*( DB_NREADS(ctx->db) + 1));
ctx->rp_dcur = 0;
ctx->rp_dmax = 100;
ctx->rp_data = (track_data*)malloc(sizeof(track_data)*ctx->rp_dmax);
}
static void post_repeats(RepeatContext* ctx)
{
int j;
track_anno coff, off;
off = 0;
for (j = 0; j <= DB_NREADS(ctx->db); j++)
{
coff = ctx->rp_anno[j];
ctx->rp_anno[j] = off;
off += coff;
}
track_write(ctx->db, ctx->rp_track, ctx->rp_block, ctx->rp_anno, ctx->rp_data, ctx->rp_dcur);
free(ctx->rp_anno);
free(ctx->rp_data);
free(ctx->rp_events);
#ifdef VERBOSE
printf("BASES_TOTAL %" PRIu64 "\n", ctx->stats_bases);
printf("BASES_REPEAT %" PRIu64 "\n", ctx->stats_repeat_bases);
printf("BASES_REPEAT_PERCENT %d%%\n", (int)(ctx->stats_repeat_bases*100.0/ctx->stats_bases));
#endif
}
static int handler_repeats(void* _ctx, Overlap* ovls, int novl)
{
RepeatContext* ctx = (RepeatContext*)_ctx;
int a = ovls->aread;
int alen = DB_READ_LEN(ctx->db, a);
int trim_ab, trim_ae;
get_trim(ctx->db, ctx->track_trim, a, &trim_ab, &trim_ae);
if (trim_ab >= trim_ae)
{
return 1;
}
ctx->stats_bases += alen;
if (2 * novl > ctx->rp_emax)
{
ctx->rp_emax = 1.2 * ctx->rp_emax + 2 * novl;
ctx->rp_events = (int*)realloc(ctx->rp_events, sizeof(int) * ctx->rp_emax);
}
int i;
int j = 0;
for (i = 0; i < novl; i++)
{
Overlap* ovl = ovls + i;
if (ovl->flags & OVL_CONT)
{
continue;
}
if(ovl->aread == ovl->bread)
{
continue;
}
int trim_bb, trim_be;
get_trim(ctx->db, ctx->track_trim, ovl->bread, &trim_bb, &trim_be);
if (trim_bb >= trim_be)
{
continue;
}
if ( ovl->flags & OVL_COMP )
{
int blen = DB_READ_LEN(ctx->db, ovl->bread);
int t = trim_bb;
trim_bb = blen - trim_be;
trim_be = blen - t;
}
if ( ((ovl->path.abpos - trim_ab) > 0 && (ovl->path.bbpos - trim_bb) > 0) ||
((trim_ae - ovl->path.aepos) > 0 && (trim_be - ovl->path.bepos) > 0) )
{
#ifdef DEBUG_LOCAL
printf("%7d ALN %5d..%5d x %5d..%5d TRIM %5d..%5d %5d..%5d\n", a,
ovl->path.abpos, ovl->path.aepos, ovl->path.bbpos, ovl->path.bepos,
trim_ab, trim_ae, trim_bb, trim_be);
#endif
ctx->rp_events[j++] = ovl->path.abpos;
ctx->rp_events[j++] = -(ovl->path.aepos-1);
}
}
novl = j/2;
qsort(ctx->rp_events, 2*novl, sizeof(int), cmp_repeats_events);
int span = 0;
int span_leave = ctx->cnt_leave;
int span_enter = ctx->cnt_enter;
int span_max = 0;
int in_repeat = 0;
int rp_dcur = ctx->rp_dcur;
for (i = 0; i < 2*novl; i++)
{
if (ctx->rp_events[i] < 0) span--;
else span++;
if (span > span_max)
{
span_max = span;
}
if (in_repeat)
{
if (span < span_leave)
{
ctx->rp_anno[a] += 1 * sizeof(track_data);
ctx->rp_data[ctx->rp_dcur++] = -(ctx->rp_events[i]);
ctx->stats_repeat_bases += ctx->rp_data[ ctx->rp_dcur - 1 ] - ctx->rp_data[ ctx->rp_dcur - 2 ];
#ifdef DEBUG_LOCAL
printf("%7d L %3d %5d\n", a, span, -(ctx->rp_events[i]));
#endif
in_repeat = 0;
}
}
else
{
if (span > span_enter)
{
if (ctx->rp_dcur + 3 >= ctx->rp_dmax)
{
ctx->rp_dmax = 1.2 * ctx->rp_dmax + 20;
ctx->rp_data = (int*)realloc(ctx->rp_data, sizeof(int)*ctx->rp_dmax);
}
ctx->rp_anno[a] += 1 * sizeof(track_data);
ctx->rp_data[ctx->rp_dcur++] = ctx->rp_events[i];
#ifdef DEBUG_LOCAL
printf("%7d E %3d %5d\n", a, span, ctx->rp_events[i]);
#endif
in_repeat = 1;
span_max = 0;
}
}
}
if (ctx->rp_dcur - rp_dcur > 2)
{
i = rp_dcur;
j = i + 2;
while ( j < ctx->rp_dcur )
{
int e = ctx->rp_data[ i + 1 ];
int b_next = ctx->rp_data[ j ];
if ( b_next - e < ctx->merge_distance )
{
ctx->stats_merged++;
ctx->rp_data[ i + 1 ] = ctx->rp_data[ j + 1 ];
}
else
{
i += 2;
}
j += 2;
}
ctx->rp_dcur = i + 2;
ctx->rp_anno[a] = (ctx->rp_dcur - rp_dcur) * sizeof(track_data);
}
return 1;
}
static void usage()
{
printf("usage: [-h <float>] [-l <float>] [-t <string>] [-b <int>] <db> <overlaps>\n");
printf("options: -h ... enter count (%d)\n", DEF_ARG_H);
printf(" -l ... leave count (%d)\n", DEF_ARG_L);
printf(" -t ... track name (%s)\n", DEF_ARG_T);
printf(" -b ... track block\n");
}
int main(int argc, char* argv[])
{
HITS_DB db;
PassContext* pctx;
RepeatContext rctx;
FILE* fileOvlIn;
bzero(&rctx, sizeof(RepeatContext));
rctx.db = &db;
// process arguments
rctx.cnt_enter = DEF_ARG_H;
rctx.cnt_leave = DEF_ARG_L;
rctx.merge_distance = 0;
rctx.rp_track = DEF_ARG_T;
rctx.rp_block = 0;
int c;
opterr = 0;
while ((c = getopt(argc, argv, "h:l:t:b:")) != -1)
{
switch (c)
{
case 'b':
rctx.rp_block = atoi(optarg);
break;
case 'h':
rctx.cnt_enter = atof(optarg);
break;
case 'l':
rctx.cnt_leave = atof(optarg);
break;
case 't':
rctx.rp_track = optarg;
break;
default:
usage();
exit(1);
}
}
if (argc - optind != 2)
{
usage();
exit(1);
}
char* pcPathReadsIn = argv[optind++];
char* pcPathOverlaps = argv[optind++];
if (rctx.cnt_enter < rctx.cnt_leave)
{
fprintf(stderr, "invalid arguments: low %d > high %d\n", rctx.cnt_leave, rctx.cnt_enter);
exit(1);
}
if ( (fileOvlIn = fopen(pcPathOverlaps, "r")) == NULL )
{
fprintf(stderr, "could not open '%s'\n", pcPathOverlaps);
exit(1);
}
// init
pctx = pass_init(fileOvlIn, NULL);
pctx->split_b = 0;
pctx->load_trace = 0;
pctx->data = &rctx;
Open_DB(pcPathReadsIn, &db);
// passes
pre_repeats(&rctx);
pass(pctx, handler_repeats);
post_repeats(&rctx);
// cleanup
pass_free(pctx);
fclose(fileOvlIn);
Close_DB(&db);
return 0;
}
|
MartinPippel/DAmar
|
utils/gff2track.c
|
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <assert.h>
#include <sys/param.h>
#include "lib/colors.h"
#include "lib/oflags.h"
#include "lib/pass.h"
#include "lib/tracks.h"
#include "lib/utils.h"
#include "lib/lasidx.h"
#include "db/DB.h"
#include "dalign/align.h"
// getopt
extern char* optarg;
extern int optind, opterr, optopt;
static void usage()
{
printf("<db> <gff> <track>\n");
}
static int cmp_ints(const void* x, const void* y)
{
int* a = (int*)x;
int* b = (int*)y;
int l = a[0];
int r = b[0];
if (l == r)
{
l = a[1];
r = b[1];
}
return l - r;
}
int main(int argc, char* argv[])
{
HITS_DB db;
// process arguments
int c;
opterr = 0;
while ((c = getopt(argc, argv, "")) != -1)
{
switch (c)
{
default:
printf("Unknow option: %s\n", argv[optind - 1]);
usage();
exit(1);
}
}
if (argc - optind < 3)
{
usage();
exit(1);
}
char* pathDb = argv[optind++];
char* pathGff = argv[optind++];
char* nameTrack = argv[optind++];
if (Open_DB(pathDb, &db))
{
printf("could not open '%s'\n", pathDb);
return 1;
}
FILE* fileIn;
if (strcmp(pathGff, "-") == 0)
{
fileIn = stdin;
}
else
{
fileIn = fopen(pathGff, "r");
if (fileIn == NULL)
{
fprintf(stderr, "failed to open '%s'\n", pathGff);
exit(1);
}
}
char seq[128];
char source[128];
char feature[128];
int b, e, len;
char strand;
char dummy[128];
int* ints = NULL;
int nints = 0;
int maxints = 0;
while ( 1 )
{
int count = fscanf(fileIn, "%s\t%s\t%s\t%d\t%d\t%d\t%c\t%s\n", seq, source, feature, &b, &e, &len, &strand, dummy);
if (count != 8)
{
break;
}
if (nints + 3 >= maxints)
{
maxints = 1.2 * maxints + 1000;
ints = realloc(ints, maxints * sizeof(int));
}
int seqid = -1;
if (strstr(seq, "read_") != NULL)
{
sscanf(seq, "read_%d", &seqid);
}
else
{
seqid = atoi(seq);
}
ints[nints + 0] = seqid;
ints[nints + 1] = b;
ints[nints + 2] = e;
int rlen = DB_READ_LEN(&db, seqid);
if ( b < 0 || b > rlen || e < b || e > rlen )
{
printf("interval out of bounds %d..%d (%d)\n", b, e, rlen);
}
nints += 3;
}
qsort(ints, nints/3, sizeof(int) * 3, cmp_ints);
track_anno* anno = malloc( sizeof(track_anno) * (DB_NREADS(&db) + 1) );
track_data* data = NULL;
int ndata = 0;
int maxdata = 0;
bzero(anno, sizeof(track_anno) * (DB_NREADS(&db) + 1));
int i;
for (i = 0; i < nints; i += 3)
{
if (ndata + 2 >= maxdata)
{
maxdata = maxdata * 1.2 + 1000;
data = realloc( data, sizeof(track_data) * maxdata );
}
anno[ ints[i + 0] ] += 2 * sizeof(track_data);
data[ ndata + 0 ] = ints[ i + 1 ];
data[ ndata + 1 ] = ints[ i + 2 ];
ndata += 2;
}
track_anno coff, off;
off = 0;
for (i = 0; i <= DB_NREADS(&db); i++)
{
coff = anno[i];
anno[i] = off;
off += coff;
}
track_write(&db, nameTrack, 0, anno, data, ndata);
free(anno);
free(data);
Close_DB(&db);
return 0;
}
|
MartinPippel/DAmar
|
scrub/Catrack.c
|
<filename>scrub/Catrack.c
/************************************************************************************\
* *
* Copyright (c) 2014, Dr. <NAME> (EWM). All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without modification, *
* are permitted provided that the following conditions are met: *
* *
* · Redistributions of source code must retain the above copyright notice, this *
* list of conditions and the following disclaimer. *
* *
* · Redistributions in binary form must reproduce the above copyright notice, this *
* list of conditions and the following disclaimer in the documentation and/or *
* other materials provided with the distribution. *
* *
* · The name of EWM may not be used to endorse or promote products derived from *
* this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY EWM ”AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, *
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND *
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL EWM BE LIABLE *
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS *
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY *
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING *
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN *
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
* *
* For any issues regarding this software and its use, contact EWM at: *
* *
* <NAME>r. *
* Bautzner Str. 122e *
* 01099 Dresden *
* GERMANY *
* Email: <EMAIL> *
* *
\************************************************************************************/
/********************************************************************************************
*
* Concate in block order all "block tracks" <DB>.<track>.# into a single track
* <DB>.<track>
*
* Author: <NAME>
* Date : June 2014
*
********************************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include "db/DB.h"
#ifdef HIDE_FILES
#define PATHSEP "/."
#else
#define PATHSEP "/"
#endif
static char *Usage = "[-vfd] <path:db|dam> <track:name>";
int main(int argc, char *argv[])
{ char *prefix;
FILE *aout, *dout;
int nblocks;
int nfiles;
int VERBOSE;
int FORCE;
int DELETE;
// Process arguments
{ int i, j, k;
int flags[128];
ARG_INIT("Catrack")
j = 1;
for (i = 1; i < argc; i++)
if (argv[i][0] == '-')
{ ARG_FLAGS("vfd") }
else
argv[j++] = argv[i];
argc = j;
VERBOSE = flags['v'];
FORCE = flags['f'];
DELETE = flags['d'];
if (argc != 3)
{ fprintf(stderr,"Usage: %s %s\n",Prog_Name,Usage);
fprintf(stderr,"\n");
fprintf(stderr," -v: verbose\n");
fprintf(stderr," -d: delete individual blocks after a successful concatenation\n");
fprintf(stderr," -f: force overwrite of track if already present\n");
exit (1);
}
}
{ char *pwd, *root;
int i, plen, index, isdam;
FILE *dstub;
char *dstub_name;
plen = strlen(argv[1]);
if (strcmp(argv[1]+(plen-3),".dam") == 0)
root = Root(argv[1],".dam");
else
root = Root(argv[1],".db");
pwd = PathTo(argv[1]);
prefix = Strdup(Catenate(pwd,PATHSEP,root,"."),"Allocating track name");
dstub = fopen(Catenate(pwd,"/",root,".db"),"r");
isdam = 0;
if (dstub == NULL)
{ dstub = fopen(Catenate(pwd,"/",root,".dam"),"r");
isdam = 1;
if (dstub == NULL)
{ fprintf(stderr,"%s: Cannot find %s either as a .db or a .dam\n",Prog_Name,root);
exit (1);
}
}
dstub_name = Strdup(Catenate(pwd,"/",root,isdam?".dam":".db"),"Allocating db file name");
if (dstub_name == NULL)
exit (1);
FSCANF(dstub,DB_NFILE,&nblocks)
for (i = 0; i < nblocks; i++)
{ char prolog[MAX_NAME], fname[MAX_NAME];
FSCANF(dstub,DB_FDATA,&index,fname,prolog)
}
FSCANF(dstub,DB_NBLOCK,&nblocks)
fclose(dstub);
free(dstub_name);
free(pwd);
free(root);
aout = fopen(Catenate(prefix,argv[2],".","anno"),"r");
if (aout != NULL && !FORCE)
{ fprintf(stderr,"%s: Track file %s%s.anno already exists!\n",Prog_Name,prefix,argv[2]);
exit (1);
}
dout = fopen(Catenate(prefix,argv[2],".","data"),"r");
if (dout != NULL && !FORCE)
{ fprintf(stderr,"%s: Track file %s%s.data already exists!\n",Prog_Name,prefix,argv[2]);
exit (1);
}
aout = Fopen(Catenate(prefix,argv[2],".","anno"),"w");
if (aout == NULL)
exit (1);
dout = NULL;
}
{ int tracktot, tracksiz;
int64 trackoff;
char data[1024];
void *anno;
FILE *lfile = NULL;
// DAZZ_EXTRA *extra;
// int nextra;
int64 extail;
anno = NULL;
trackoff = 0;
tracktot = tracksiz = 0;
if (fwrite(&tracktot,sizeof(int),1,aout) != 1)
SYSTEM_WRITE_ERROR
if (fwrite(&tracksiz,sizeof(int),1,aout) != 1)
SYSTEM_WRITE_ERROR
// nextra = 0;
nfiles = 0;
while (1)
{ FILE *dfile, *afile;
char *dfile_name, *afile_name;
int i, size, esize, tracklen;
afile_name = Strdup(Numbered_Suffix(prefix,nfiles+1,Catenate(".",argv[2],".","anno")),
"Allocating .anno file name");
dfile_name = Strdup(Numbered_Suffix(prefix,nfiles+1,Catenate(".",argv[2],".","data")),
"Allocating .data file name");
if (afile_name == NULL || dfile_name == NULL)
goto error;
afile = fopen(afile_name,"r");
if (afile == NULL)
break;
dfile = fopen(Numbered_Suffix(prefix,nfiles+1,Catenate(".",argv[2],".","data")),"r");
if (dfile == NULL && errno != ENOENT)
{ fprintf(stderr,"%s: The file %s is corrupted\n",Prog_Name,dfile_name);
goto error;
}
if (nfiles > 0)
fclose(lfile);
lfile = afile;
if (VERBOSE)
{ fprintf(stderr,"Concatenating %s%d.%s ...\n",prefix,nfiles+1,argv[2]);
fflush(stderr);
}
FREAD(&tracklen,sizeof(int),1,afile)
FREAD(&size,sizeof(int),1,afile)
if (size == 0)
esize = 8;
else
esize = size;
if (nfiles == 0)
{ tracksiz = size;
if (dfile != NULL)
{ dout = Fopen(Catenate(prefix,argv[2],".","data"),"w");
if (dout == NULL)
goto error;
}
else
{ anno = Malloc(esize,"Allocating annotation record");
if (anno == NULL)
goto error;
}
}
else
{ int escape = 1;
if (tracksiz != size)
{ fprintf(stderr,"%s: Track block %d does not have the same annotation size (%d)",
Prog_Name,nfiles+1,size);
fprintf(stderr," as previous blocks (%d)\n",tracksiz);
}
else if (dfile == NULL && dout != NULL)
fprintf(stderr,"%s: Track block %d does not have data but previous blocks do\n",
Prog_Name,nfiles+1);
else if (dfile != NULL && dout == NULL)
fprintf(stderr,"%s: Track block %d has data but previous blocks do not\n",
Prog_Name,nfiles+1);
else
escape = 0;
if (escape)
goto error;
}
if (dfile != NULL)
{ int64 dlen;
if (esize == 4)
{ int anno4;
for (i = 0; i < tracklen; i++)
{ FREAD(&anno4,sizeof(int),1,afile)
anno4 += trackoff;
FWRITE(&anno4,sizeof(int),1,aout)
}
FREAD(&anno4,sizeof(int),1,afile)
dlen = anno4;
}
else
{ int64 anno8;
for (i = 0; i < tracklen; i++)
{ FREAD(&anno8,sizeof(int64),1,afile)
anno8 += trackoff;
FWRITE(&anno8,sizeof(int64),1,aout)
}
FREAD(&anno8,sizeof(int64),1,afile)
dlen = anno8;
}
trackoff += dlen;
for (i = 1024; i < dlen; i += 1024)
{ FREAD(data,1024,1,dfile)
FWRITE(data,1024,1,dout)
}
i -= 1024;
if (i < dlen)
{ FREAD(data,dlen-i,1,dfile)
FWRITE(data,dlen-i,1,dout)
}
}
else
{ for (i = 0; i < tracklen; i++)
{ FREAD(anno,esize,1,afile)
FWRITE(anno,esize,1,aout)
}
}
FSEEKO(afile,0,SEEK_END)
if (dfile != NULL)
extail = FTELLO(afile) - (esize*(tracklen+1) + 2*sizeof(int));
else
extail = FTELLO(afile) - (esize*tracklen + 2*sizeof(int));
FSEEKO(afile,-extail,SEEK_END)
// if (extail >= 20)
// { if (nfiles == 0)
// { nextra = 0;
// while (1)
// if (Read_Extra(afile,afile_name,NULL))
// break;
// else
// nextra += 1;
//
// extra = (DAZZ_EXTRA *) Malloc(sizeof(DAZZ_EXTRA)*(nextra+1),"Allocating extras");
// if (extra == NULL)
// goto error;
// FSEEKO(afile,-extail,SEEK_END)
//
// for (i = 0; i < nextra; i++)
// { extra[i].nelem = 0;
// Read_Extra(afile,afile_name,extra+i);
// }
// }
//
// else
// { for (i = 0; i < nextra; i++)
// if (Read_Extra(afile,afile_name,extra+i))
// { fprintf(stderr,"%s: File %s has fewer extras than previous .anno files\n",
// Prog_Name,afile_name);
// goto error;
// }
// if (Read_Extra(afile,afile_name,extra+nextra) == 0)
// { fprintf(stderr,"%s: File %s has more extras than previous .anno files\n",
// Prog_Name,afile_name);
// goto error;
// }
// }
// }
tracktot += tracklen;
nfiles += 1;
if (dfile != NULL)
fclose(dfile);
}
if (nfiles == 0)
{ fprintf(stderr,"%s: Couldn't find first track block %s1.%s.anno\n",
Prog_Name,prefix,argv[2]);
goto error;
}
else
{ char *byte;
if (dout != NULL)
{ if (tracksiz == 4)
{ int anno4 = trackoff;
FWRITE(&anno4,sizeof(int),1,aout)
}
else
{ int64 anno8 = trackoff;
FWRITE(&anno8,sizeof(int64),1,aout)
}
}
// if (nextra == 0)
{ while (fread(&byte,1,1,lfile) == 1)
FWRITE(&byte,1,1,aout)
}
// else
// { int i;
// for (i = 0; i < nextra; i++)
// Write_Extra(aout,extra+i);
// }
fclose(lfile);
FSEEKO(aout,0,SEEK_SET)
FWRITE(&tracktot,sizeof(int),1,aout)
FWRITE(&tracksiz,sizeof(int),1,aout)
}
}
FCLOSE(aout);
if (dout != NULL)
FCLOSE(dout);
if (nfiles != nblocks)
{ fprintf(stderr,"%s: Did not catenate all tracks of DB (nfiles %d != nblocks %d)\n",
Prog_Name, nfiles, nblocks);
goto error;
}
if (DELETE)
{ int i;
char *name;
for (i = 1; i <= nblocks ;i++)
{ name = Numbered_Suffix(prefix,i,Catenate(".",argv[2],".","anno"));
if (unlink(name) != 0)
fprintf(stderr,"%s: [WARNING] Couldn't delete file %s\n",Prog_Name,name);
if (dout != NULL)
{ name = Numbered_Suffix(prefix,i,Catenate(".",argv[2],".","data"));
if (unlink(name) != 0)
fprintf(stderr,"%s: [WARNING] Couldn't delete file %s\n",Prog_Name,name);
}
}
}
free(prefix);
exit (0);
error:
{ char *name;
fclose(aout);
name = Catenate(prefix,argv[2],".","anno");
if (unlink(name) != 0)
fprintf(stderr,"%s: [WARNING] Couldn't delete file %s during abort\n",Prog_Name,name);
if (dout != NULL)
{ fclose(dout);
name = Catenate(prefix,argv[2],".","data");
if (unlink(name) != 0)
fprintf(stderr,"%s: [WARNING] Couldn't delete file %s during abort\n",Prog_Name,name);
}
free(prefix);
}
exit (1);
}
|
MartinPippel/DAmar
|
utils/txt2track.c
|
/*
* txt2track.c
*
* Created on: 11 Jan 2017
* Author: pippelmn
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <assert.h>
#include <sys/param.h>
#include "lib/colors.h"
#include "lib/oflags.h"
#include "lib/pass.h"
#include "lib/tracks.h"
#include "lib/utils.h"
#include "lib/lasidx.h"
#include "db/DB.h"
#include "dalign/align.h"
// getopt
extern char* optarg;
extern int optind, opterr, optopt;
int SORT;
static void usage(FILE* out, char *name)
{
fprintf(out, "Usage:\n %s [-vmr] [-s <int>] <db> <txt> <track>\n", name);
fprintf(out, "Options: -m track is mask track and has the format readid pos pos\n");
fprintf(out, " -r track is read pair track and has the format: readID readID\n");
fprintf(out, " -s <int> sort fields from 0. to -s <int> \n");
fprintf(out, " -v verbose mode\n");
}
static int cmp_ints(const void* x, const void* y)
{
int* a = (int*) x;
int* b = (int*) y;
// compare areads
int l = a[0];
int r = b[0];
// compare breads or abpos
if (SORT == 2 && l == r)
{
l = a[1];
r = b[1];
}
// compare abepos
if (SORT > 2 && l == r)
{
l = a[2];
r = b[2];
}
return l - r;
}
int main(int argc, char* argv[])
{
HITS_DB db;
// process arguments
int c;
opterr = 0;
int verbose = 1;
int isMask = 0;
int isReadPair = 0;
SORT = -1;
while ((c = getopt(argc, argv, "vmrs:")) != -1)
{
switch (c)
{
case 'm':
isMask = 1;
break;
case 'r':
isReadPair = 1;
break;
case 's':
SORT = atoi(optarg);
break;
case 'v':
verbose = 1;
break;
default:
printf("Unknow option: %s\n", argv[optind]);
usage(stderr, argv[0]);
exit(1);
}
}
if (argc - optind < 3)
{
usage(stderr, argv[0]);
exit(1);
}
char* pathDb = argv[optind++];
char* pathTxt = argv[optind++];
char* nameTrack = argv[optind++];
if (Open_DB(pathDb, &db))
{
printf("could not open '%s'\n", pathDb);
return 1;
}
FILE* fileIn;
if (strcmp(pathTxt, "-") == 0)
{
fileIn = stdin;
}
else
{
fileIn = fopen(pathTxt, "r");
if (fileIn == NULL)
{
fprintf(stderr, "failed to open '%s'\n", pathTxt);
exit(1);
}
}
if(SORT>=0)
{
if(isMask && SORT > 2)
{
fprintf(stderr, "[WARNING]: Sort fields cannot be greater then 2, if isMask is set!\n");
exit(1);
}
if(isReadPair && SORT > 1)
{
fprintf(stderr, "[WARNING]: Sort fields cannot be greater then 1, if isReadPair is set!\n");
exit(1);
}
if(SORT > 2)
{
fprintf(stderr, "[WARNING]: Unsupported number for sort fields(%d). (isMask [0,1,2], isReadPair [0,1])\n", SORT);
exit(1);
}
}
int field1;
int field2;
int field3;
int* ints = NULL;
int nints = 0;
int maxints = 0;
// todo dynamically read number of fields from first lines
// for now: if isMask: 3 fields, aread, abpos, aepos
// if isReadPair: 2 fields, aread, bread
int count;
int nLines=0;
if(verbose)
printf("read file %s:", pathTxt);
while (1)
{
nLines++;
if(isMask)
{
count = fscanf(fileIn, "%d%*c%d%*c%d\n", &field1, &field2, &field3);
if (count != 3)
{
if(count != EOF)
fprintf(stderr, "[WARNING] - Line %d does not have proper mask format. Count is %d. Stop!\n", nLines, count);
break;
}
}
else
{
count = fscanf(fileIn, "%d%*c%d\n", &field1, &field2);
if (count != 2)
{
if(count !=EOF)
fprintf(stderr, "[WARNING] - Line %d does not have proper read pair format. Count is %d. Stop!\n", nLines, count);
break;
}
}
if (nints + count >= maxints)
{
maxints = 1.2 * maxints + 1000;
ints = realloc(ints, maxints * sizeof(int));
}
ints[nints + 0] = field1;
ints[nints + 1] = field2;
if(isMask)
ints[nints + 2] = field3;
int nReads = DB_NREADS(&db);
if (isMask)
{
int rlen = DB_READ_LEN(&db, field1);
if (field1 < 0 || field1 >= nReads || field3 > rlen || field2 > field3 || field3 > rlen)
{
printf("interval out of bounds %d %d..%d (%d)\n", field1, field2, field3, rlen);
}
}
else
{
if (field1 < 0 || field1 >= nReads || field2 < 0 || field2 >= nReads)
{
printf("read ids %d, %d are out of DB read range [%d, %d] \n", field1, field2, 0, nReads);
}
}
nints += count;
}
if(verbose)
printf(" found %d lines\n", nLines);
int fields = (isMask) ? 3 : 2;
if (SORT>=0)
{
if(verbose)
printf("Sort by: %d columns\n", SORT);
qsort(ints, nints / fields, sizeof(int) * fields, cmp_ints);
}
track_anno* anno = malloc(sizeof(track_anno) * (DB_NREADS(&db) + 1));
track_data* data = NULL;
int ndata = 0;
int maxdata = 0;
bzero(anno, sizeof(track_anno) * (DB_NREADS(&db) + 1));
int i;
for (i = 0; i < nints; i += fields)
{
if (ndata + fields >= maxdata)
{
maxdata = maxdata * 1.2 + 1000;
data = realloc(data, sizeof(track_data) * maxdata);
}
anno[ints[i]] += (fields - 1) * sizeof(track_data);
data[ndata] = ints[i + 1];
if(isMask)
data[ndata + 1] = ints[i + 2];
ndata += fields - 1;
}
track_anno coff, off;
off = 0;
for (i = 0; i <= DB_NREADS(&db); i++)
{
coff = anno[i];
anno[i] = off;
off += coff;
}
if(verbose)
printf("write track: %s\n", nameTrack);
track_write(&db, nameTrack, 0, anno, data, ndata);
free(anno);
free(data);
free(ints);
Close_DB(&db);
if(verbose)
printf("DONE\n");
return 0;
}
|
MartinPippel/DAmar
|
scrub/TKmerge.c
|
/*******************************************************************************************
*
* merge multiple tracks of the same type into one
*
* Date : October 2016
*
* Author : <NAME>
*
*******************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#if defined(__APPLE__)
#include <sys/syslimits.h>
#else
#include <linux/limits.h>
#endif
#include "db/DB.h"
#include "lib/tracks.h"
#include "lib/pass.h"
#include "lib/colors.h"
#include "lib/compression.h"
// toggles
#undef DEBUG
extern char* optarg;
extern int optind, opterr, optopt;
static void usage()
{
printf("[-d] <db> <track>\n");
printf("Options: -d ... remove single tracks after merging\n");
}
int main(int argc, char* argv[])
{
// args
int delete = 0;
opterr = 0;
int c;
while ((c = getopt(argc, argv, "d")) != -1)
{
switch (c)
{
case 'd':
delete = 1;
break;
}
}
if (argc - optind != 2)
{
usage();
exit(1);
}
char* pcDb = argv[optind++];
char* pcTrack = argv[optind++];
HITS_DB db;
if (Open_DB(pcDb, &db))
{
fprintf(stderr, "could not open database '%s'\n", pcDb);
exit(1);
}
int nblocks = DB_Blocks(pcDb);
if (nblocks < 1)
{
fprintf(stderr, "failed to get number of blocks\n");
exit(1);
}
uint64_t nreads = DB_NREADS(&db);
track_anno* offset = (track_anno*) malloc(sizeof(track_anno) * (nreads + 1));
bzero(offset, sizeof(track_anno) * (nreads + 1));
FILE* fileDataOut;
char path[PATH_MAX];
sprintf(path, "%s.%s.d2", db.path, pcTrack);
if ((fileDataOut = fopen(path, "w")) == NULL)
{
fprintf(stderr, "ERROR [mergeTracks]: Cannot open file %s!\n", path);
exit(1);
}
int i;
uint64_t cdata_total = 0;
for ( i = 1 ; i <= nblocks ; i++)
{
sprintf(path, "%d.%s", i, pcTrack);
HITS_TRACK* track = track_load(&db, path);
if (!track)
{
fprintf(stderr, "Unable to merge all tracks, stopped at block %d. Cannot open file %s\n", i, path);
exit(1);
}
track_anno* offset_in = track->anno;
uint64_t j;
for (j = 0; j < nreads; j++)
{
track_anno ob = offset_in[j];
track_anno oe = offset_in[j + 1];
if (ob > oe)
{
fprintf(stderr, "ERROR: block %d ob > oe read %" PRIu64 " ob %lld oe %lld\n", i, j, ob, oe);
exit(1);
}
if (ob < oe && offset[j] != 0)
{
fprintf(stderr, "ERROR: block %d not merging in proper order. ob < oe read %" PRIu64 " ob %lld oe %lld. read offset %lld \n", i, j, ob, oe, offset[j]);
exit(1);
}
offset[j] += (oe - ob);
}
void* canno = NULL;
uint64_t clen = 0;
compress_chunks(track->data, offset_in[nreads], &canno, &clen);
cdata_total += clen;
// fwrite(track->data, offset_in[nreads], 1, fileDataOut);
fwrite(canno, clen, 1, fileDataOut);
free(canno);
Close_Track(&db, track->name);
}
fclose(fileDataOut);
track_anno off = 0;
track_anno coff;
uint64_t j;
for (j = 0; j <= nreads; j++)
{
coff = offset[j];
offset[j] = off;
off += coff;
}
for (j = 0; j < nreads; j++)
{
assert(offset[j] <= offset[j + 1]);
}
track_write(&db, pcTrack, 0, offset, NULL, cdata_total);
if (delete)
{
for ( i = 1 ; i <= nblocks ; i++)
{
sprintf(path, "%d.%s", i, pcTrack);
track_delete(&db, path);
}
}
free(offset);
Close_DB(&db);
return 0;
}
|
MartinPippel/DAmar
|
msa/msa_main.c
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <sys/stat.h>
#include <sys/param.h>
#include <assert.h>
#include <unistd.h>
#include "lib/oflags.h"
#include "lib/tracks.h"
#include "lib/pass.h"
#include "lib/colors.h"
#include "lib/utils.h"
#include "msa.h"
#include "db/DB.h"
#include "dalign/align.h"
typedef struct
{
msa* m;
int rid;
int a_from;
int a_to;
int twidth;
int nreads;
char** reads;
char* base_out;
FILE* fileOutMsa;
FILE* fileOutConsensus;
FILE* fileOutIds;
HITS_DB* db;
// re-alignment
Work_Data* align_work_data;
Align_Spec* align_spec;
} MsaContext;
extern char *optarg;
extern int optind, opterr, optopt;
static void load_reads(MsaContext* mctx, Overlap* pOvls, int nOvls)
{
if (nOvls >= mctx->nreads)
{
int nreads = mctx->nreads * 1.2 + nOvls + 1;
mctx->reads = (char**)realloc(mctx->reads, sizeof(char*)*nreads);
for (;mctx->nreads < nreads; mctx->nreads++)
{
mctx->reads[ mctx->nreads ] = New_Read_Buffer(mctx->db);
}
}
Load_Read(mctx->db, pOvls->aread, mctx->reads[0], 0);
int i;
for (i = 0; i < nOvls; i++)
{
int bread = pOvls[i].bread;
Load_Read(mctx->db, bread, mctx->reads[i+1], 0);
if (pOvls[i].flags & OVL_COMP)
{
int len = DB_READ_LEN(mctx->db, bread);
Complement_Seq( mctx->reads[i+1], len );
}
}
}
static void write_seq(FILE* file, char* seq)
{
const int width = 80;
int len = strlen(seq);
int j;
for (j = 0; j + width < len; j += width)
{
fprintf(file, "%.*s\n", width, seq + j);
}
if (j < len)
{
fprintf(file, "%s\n", seq + j);
}
}
static void pre_msa(PassContext* pctx, MsaContext* mctx)
{
char* fname = (char*)malloc( strlen(mctx->base_out) + 100);
sprintf(fname, "%s.cons.fa", mctx->base_out);
mctx->fileOutConsensus = fopen(fname, "w");
sprintf(fname, "%s.msa", mctx->base_out);
mctx->fileOutMsa = fopen(fname, "w");
sprintf(fname, "%s.ids", mctx->base_out);
mctx->fileOutIds = fopen(fname, "w");
free(fname);
mctx->twidth = pctx->twidth;
}
static void post_msa(MsaContext* mctx)
{
fclose(mctx->fileOutConsensus);
fclose(mctx->fileOutMsa);
}
static int handler_msa(void* _ctx, Overlap* pOvls, int nOvls)
{
MsaContext* ctx = _ctx;
int a = pOvls->aread;
int alen = DB_READ_LEN(ctx->db, pOvls->aread);
if (ctx->rid != -1 && ctx->rid != a)
{
return 1;
}
msa* m;
m = msa_init();
m->twidth = ctx->twidth;
load_reads(ctx, pOvls, nOvls);
msa_add(m, ctx->reads[0], 0, alen, 0, alen, NULL, 0, a);
int j;
int used = 0;
for (j = 0; j < nOvls; j++)
{
Overlap* o = pOvls + j;
if (o->path.abpos <= ctx->a_from && o->path.aepos >= ctx->a_to)
{
msa_add( m, ctx->reads[ j + 1 ],
o->path.abpos, o->path.aepos,
o->path.bbpos, o->path.bepos,
o->path.trace, o->path.tlen,
o->bread );
if ( o->bread == 163126 )
{
msa_print( m, stdout, ctx->a_from, ctx->a_to );
msa_print_profile( m, stdout, ctx->a_from, ctx->a_to, 1 );
printf( "\n" );
}
used += 1;
}
}
msa_print_simple(m, ctx->fileOutMsa, ctx->fileOutIds, ctx->a_from, ctx->a_to);
// msa_print_profile(m, stdout, 1);
char* cons = msa_consensus(m, 0);
write_seq(ctx->fileOutConsensus, cons);
msa_free(m);
return ( ctx->rid == -1 );
}
static void usage()
{
printf("usage: <db> <overlaps> <base_out> <read.id> <max.ovls> <from> <to>\n");
}
int main(int argc, char* argv[])
{
FILE* fileOvls;
HITS_DB db;
PassContext* pctx;
MsaContext mctx;
bzero(&mctx, sizeof(MsaContext));
mctx.db = &db;
if (argc != 7)
{
usage();
exit(1);
}
char* pcPathReadsIn = argv[1];
char* pcPathOverlaps = argv[2];
mctx.base_out = argv[3];
mctx.rid = atoi(argv[4]);
mctx.a_from = atoi(argv[5]);
mctx.a_to = atoi(argv[6]);
if ( (fileOvls = fopen(pcPathOverlaps, "r")) == NULL )
{
fprintf(stderr, "could not open '%s'\n", pcPathOverlaps);
exit(1);
}
if (Open_DB(pcPathReadsIn, &db))
{
fprintf(stderr, "could not open '%s'\n", pcPathReadsIn);
exit(1);
}
pctx = pass_init(fileOvls, NULL);
pctx->split_b = 0;
pctx->load_trace = 1;
pctx->unpack_trace = 1;
pctx->data = &mctx;
pre_msa(pctx, &mctx);
pass(pctx, handler_msa);
post_msa(&mctx);
Close_DB(&db);
return 0;
}
|
MartinPippel/DAmar
|
utils/LAneighbors.c
|
<reponame>MartinPippel/DAmar<gh_stars>10-100
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "lib/pass.h"
#include "db/DB.h"
#include "lib/utils.h"
#include "lib/tracks.h"
#include "dalign/align.h"
#include "lib/oflags.h"
#undef DEBUG
#define OUTPUT_DOT 0
#define OUTPUT_NODES 1
// #define STATUS_UNDEFINED 0
#define STATUS_NEIGHBOR 1
#define STATUS_CONTAINED 2
extern char* optarg;
extern int optind, opterr, optopt;
static void usage()
{
printf("usage: [-r<int(1)>] <db> <overlaps_in:ovl> <overlaps_out:ovl> <read:int>\n");
printf("options: ...\n");
}
int main(int argc, char* argv[])
{
Overlap ovl;
HITS_DB db;
HITS_TRACK* trackTrim;
FILE* fileOvlIn;
FILE* fileOvlOut;
// ovl_header_novl novl_out;
ovl_header_novl novl;
ovl_header_twidth twidth;
int output = OUTPUT_DOT;
int radius = 1;
int drop_contained = 1;
int c;
opterr = 0;
while ((c = getopt(argc, argv, "r:")) != -1)
{
switch (c)
{
case 'r':
radius = atoi(optarg);
break;
default:
usage();
exit(1);
}
}
if (argc - optind != 4)
{
usage();
exit(1);
}
char* pcPathDb = argv[optind++];
char* pcPathOverlapsIn = argv[optind++];
char* pcPathOverlapsOut = argv[optind++];
int read = atoi( argv[optind++] );
if ( Open_DB(pcPathDb, &db) )
{
fprintf(stderr, "could not open %s\n", pcPathDb);
exit(1);
}
if ( (fileOvlIn = fopen(pcPathOverlapsIn, "r")) == NULL )
{
fprintf(stderr, "could not open %s\n", pcPathOverlapsIn);
exit(1);
}
if ( (fileOvlOut = fopen(pcPathOverlapsOut, "w")) == NULL )
{
fprintf(stderr, "could not open %s\n", pcPathOverlapsOut);
exit(1);
}
trackTrim = track_load(&db, TRACK_TRIM);
if (!trackTrim)
{
fprintf(stderr, "failed to open track %s\n", TRACK_TRIM);
exit(1);
}
// Trim_DB(&db);
if ( fread(&novl, sizeof(ovl_header_novl), 1, fileOvlIn) != 1 )
{
fprintf(stderr, "ERROR: reading novl failed\n");
exit(1);
}
if ( fread(&twidth, sizeof(ovl_header_twidth), 1, fileOvlIn) != 1)
{
fprintf(stderr, "ERROR: reading twidth failed\n");
exit(1);
}
int tbytes = TBYTES(twidth);
int* offsets = (int*)malloc(sizeof(int) * db.nreads);
bzero(offsets, sizeof(int) * db.nreads);
unsigned char* status = (unsigned char*)malloc((db.nreads));
bzero(status, db.nreads);
uint64 dmax = 100;
int* data = (int*)malloc(sizeof(int) * dmax);
uint64 dcur = 0;
// create edge list
printf("creating edge list\n");
while (!Read_Overlap(fileOvlIn, &ovl))
{
fseeko(fileOvlIn, tbytes * ovl.path.tlen, SEEK_CUR);
if (ovl.flags & OVL_DISCARD)
{
continue;
}
offsets[ ovl.aread ]++;
data[ dcur ] = ovl.bread;
dcur++;
int trim_ab, trim_ae, trim_bb, trim_be;
int ovlALen, ovlBLen;
ovlALen = DB_READ_LEN(&db, ovl.aread);
ovlBLen = DB_READ_LEN(&db, ovl.bread);
if (trackTrim)
{
get_trim(&db, trackTrim, ovl.aread, &trim_ab, &trim_ae);
get_trim(&db, trackTrim, ovl.bread, &trim_bb, &trim_be);
}
else
{
trim_ab = 0;
trim_ae = ovlALen;
trim_bb = 0;
trim_be = ovlBLen;
}
if (ovl.flags & OVL_COMP)
{
int t = trim_bb;
trim_bb = ovlBLen - trim_be;
trim_be = ovlBLen - t;
}
int begpos = (ovl.path.abpos - trim_ab) - (ovl.path.bbpos - trim_bb);
int endpos = (ovl.path.aepos - trim_ab) - (ovl.path.bepos - trim_bb) - ( (trim_ae - trim_ab) - (trim_be - trim_bb) );
// begpos = o.path.abpos - o.path.bbpos;
// endpos = (o.path.aepos - o.path.bepos) - (len[aread] - len[bread]);
if (begpos == 0 && endpos == 0)
{
if (ovl.aread > ovl.bread)
{
status[ovl.aread] = STATUS_CONTAINED;
}
}
else if (begpos <= 0 && endpos >= 0)
{
status[ovl.aread] = STATUS_CONTAINED;
}
if (dcur >= dmax)
{
dmax = dmax * 1.2 + 100;
data = (int*)realloc(data, sizeof(int)*dmax);
}
}
int nreads = ovl.aread;
int i, j;
uint64 off, coff;
off = 0;
for (i = 0; i <= nreads; i++)
{
coff = offsets[i];
offsets[i] = off;
off += coff;
}
// collect neighborhood
printf("collecting neighborhood");
int smax = 100;
int scur = 0;
int* stack = (int*)malloc(sizeof(int)*smax);
int* rsoff = (int*)malloc(sizeof(int)*(radius+1));
bzero(rsoff, sizeof(int)*(radius+1));
rsoff[0] = 0;
stack[ scur ] = read;
status[ read ] |= STATUS_NEIGHBOR;
scur++;
int rcur = 1;
while (rcur <= radius)
{
rsoff[rcur] = scur;
for (j = rsoff[rcur-1]; j < rsoff[rcur]; j++)
{
read = stack[j];
printf("r %d of %d\n", rcur, read);
uint64 ob = offsets[read];
uint64 oe = offsets[read+1];
while (ob < oe)
{
read = data[ob];
if (!(status[read] & STATUS_NEIGHBOR))
{
status[read] |= STATUS_NEIGHBOR;
stack[ scur ] = read;
scur++;
printf(" -> %d", read);
if (status[read] & STATUS_CONTAINED)
{
printf(" C\n");
}
else
{
printf("\n");
}
if (scur >= smax)
{
smax = 1.2 * smax + 100;
stack = (int*)realloc(stack, sizeof(int)*smax);
}
}
ob++;
}
}
rcur++;
}
printf("writing overlaps\n");
if (output == OUTPUT_NODES)
{
for (i = 0; i < scur; i++)
{
if (drop_contained && (status[ stack[i] ] & STATUS_CONTAINED))
{
continue;
}
fprintf(fileOvlOut, "%d\n", stack[i]);
}
}
else
{
fseeko(fileOvlIn, sizeof(ovl_header_novl) + sizeof(ovl_header_twidth), SEEK_SET);
fprintf(fileOvlOut, "digraph nh {\n");
while (!Read_Overlap(fileOvlIn, &ovl))
{
fseeko(fileOvlIn, tbytes * ovl.path.tlen, SEEK_CUR);
if (ovl.flags & OVL_DISCARD)
{
continue;
}
if ( (status[ ovl.aread ] & STATUS_NEIGHBOR) &&
(status[ ovl.bread ] & STATUS_NEIGHBOR) )
{
if (drop_contained && ((status[ ovl.aread ] & STATUS_CONTAINED) ||
(status[ ovl.bread ] & STATUS_CONTAINED)))
{
continue;
}
if (ovl.aread < ovl.bread)
{
fprintf(fileOvlOut, "%d -> %d [color=orange];\n", ovl.aread, ovl.bread);
}
else
{
fprintf(fileOvlOut, "%d -> %d;\n", ovl.aread, ovl.bread);
}
}
}
fprintf(fileOvlOut, "}\n");
}
fclose(fileOvlOut);
fclose(fileOvlIn);
free(status);
free(rsoff);
free(stack);
free(offsets);
free(data);
return 0;
}
|
MartinPippel/DAmar
|
utils/TKshow.c
|
<filename>utils/TKshow.c
/*******************************************************************************************
*
* Date : February 2015
*
*******************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "../db/DB.h"
#include "../lib/pass.h"
#include "../lib/tracks.h"
#define DEF_ARG_B 1000
extern char* optarg;
extern int optind, opterr, optopt;
static void usage()
{
printf("[-nBtpdi] [-s <int>] [-b <int>] <db> <track>\n");
printf("Options: -p ... prefix with track name\n");
printf(" -d ... distance between intervals\n");
printf(" -i ... annotation is in form of intervals\n");
printf(" -s ... # bytes for an entry\n");
printf(" -S ... summary stats for tracks containing intervals\n");
printf(" -b ... bin size for histogram (%d)\n", DEF_ARG_B);
printf(" -n ... new line after each track entry\n");
printf(" -B ... bed file format for interval tracks\n");
}
static int isPowerOfTwo(unsigned int x)
{
return ((x != 0) && ((x & (~x + 1)) == x));
}
static uint64_t value(void* v, int bytes)
{
if (bytes == 1)
{
return *(unsigned char*) (v);
}
else if (bytes == 2)
{
return *(unsigned short*) (v);
}
else if (bytes == 4)
{
return *(uint32_t*) (v);
}
else if (bytes == 8)
{
return *(uint64_t*) (v);
}
return 0;
}
int main(int argc, char* argv[])
{
HITS_DB db;
HITS_TRACK* track = NULL;
HITS_TRACK* pacbio_track = NULL;
HITS_TRACK* seqID_track = NULL;
HITS_TRACK* source_track = NULL;
int prefix, dist, intervals, dsize, stats, newline;
char* pcDb;
char* pcTrack;
int binsize = DEF_ARG_B;
int BED = 0;
// args
newline = prefix = dist = intervals = dsize = stats = 0;
opterr = 0;
int c;
while ((c = getopt(argc, argv, "BnStTpdis:b:")) != -1)
{
switch (c)
{
case 'n':
newline = 1;
break;
case 'B':
BED = 1;
break;
case 'b':
binsize = atoi(optarg);
break;
case 'p':
prefix = 1;
break;
case 'd':
dist = 1;
break;
case 'i':
intervals = 1;
break;
case 's':
dsize = atoi(optarg);
break;
case 'S':
stats = 1;
break;
}
}
if (argc - optind != 2)
{
usage();
exit(1);
}
if (!isPowerOfTwo(dsize))
{
fprintf(stderr, "-s must be a power of 2\n");
exit(1);
}
pcDb = argv[optind++];
pcTrack = argv[optind++];
if (Open_DB(pcDb, &db))
{
fprintf(stderr, "failed to open database '%s'\n", pcDb);
exit(1);
}
track = track_load(&db, pcTrack);
if (track == NULL)
{
fprintf(stderr, "could not open track '%s'\n", pcTrack);
exit(1);
}
int nfiles;
char **flist = NULL;
int *findx = NULL;
track_anno *pacbio_anno, *seqID_anno, *source_anno;
track_data *pacbio_data, *seqID_data, *source_data;
pacbio_anno = seqID_anno = source_anno = NULL;
pacbio_data = seqID_data = source_data = NULL;
if (BED)
{
prefix = 0;
newline = 1;
intervals = 1;
// try to load same tracks as DBshow, to recreate unique contig names
int status;
status = Check_Track(&db, TRACK_PACBIO_HEADER);
if (status == 0)
pacbio_track = track_load(&db, TRACK_PACBIO_HEADER);
status = Check_Track(&db, TRACK_SEQID);
if (status == 0)
seqID_track = track_load(&db, TRACK_SEQID);
status = Check_Track(&db, TRACK_SOURCE);
if (status == 0)
source_track = track_load(&db, TRACK_SOURCE);
if (pacbio_track)
{
pacbio_anno = pacbio_track->anno;
pacbio_data = pacbio_track->data;
}
if (seqID_track)
{
seqID_anno = seqID_track->anno;
seqID_data = seqID_track->data;
}
if (source_track)
{
source_anno = source_track->anno;
source_data = source_track->data;
}
{
char *pwd, *root;
FILE *dstub;
int i;
root = Root(pcDb, ".db");
pwd = PathTo(pcDb);
if (db.part > 0)
{
char* sep = rindex(root, '.');
*sep = '\0';
}
dstub = Fopen(Catenate(pwd, "/", root, ".db"), "r");
if (dstub == NULL)
exit(1);
free(pwd);
free(root);
if (fscanf(dstub, DB_NFILE, &nfiles) != 1)
SYSTEM_READ_ERROR
flist = (char **) Malloc(sizeof(char *) * nfiles, "Allocating file list");
findx = (int *) Malloc(sizeof(int *) * (nfiles + 1), "Allocating file index");
if (flist == NULL || findx == NULL)
exit(1);
findx += 1;
findx[-1] = 0;
for (i = 0; i < nfiles; i++)
{
char prolog[MAX_NAME], fname[MAX_NAME];
if (fscanf(dstub, DB_FDATA, findx + i, fname, prolog) != 3)
SYSTEM_READ_ERROR
if (Check_Track(&db, TRACK_PACBIO_HEADER) == 0)
{
if ((flist[i] = Strdup(prolog, "Adding to file list")) == NULL)
exit(1);
}
else
{
if ((flist[i] = Strdup(fname, "Adding to file list")) == NULL)
exit(1);
}
}
fclose(dstub);
if (db.part > 0)
{
for (i = 0; i < nfiles; i++)
findx[i] -= db.ufirst;
}
}
}
void* anno = track->anno;
void* data = track->data;
int i;
uint64_t b, e;
uint64_t stats_total = 0;
uint64_t stats_intervals = 0;
uint64_t stats_itotal = 0;
int maxlen = db.maxlen;
int nbin = (maxlen - 1) / binsize + 1;
int* hist = malloc(sizeof(int) * nbin);
uint64_t* tsum = malloc(sizeof(uint64_t) * nbin);
if (hist == NULL || tsum == NULL)
{
exit(1);
}
bzero(hist, nbin * sizeof(int));
bzero(tsum, nbin * sizeof(uint64_t));
int map = 0;
int len = 0;
for (i = 0; i < db.nreads; i++)
{
if (BED)
{
len = DB_READ_LEN(&db, i);
while (i < findx[map - 1])
map -= 1;
while (i >= findx[map])
map += 1;
}
if (track->size == sizeof(int))
{
b = ((uint32_t*) anno)[i];
e = ((uint32_t*) anno)[i + 1];
}
else
{
b = ((uint64_t*) anno)[i];
e = ((uint64_t*) anno)[i + 1];
}
if (stats)
{
stats_total += DB_READ_LEN(&db, i);
while (b < e)
{
stats_intervals++;
int len = value(data + b + dsize, dsize) - value(data + b, dsize);
stats_itotal += len;
hist[len / binsize] += 1;
tsum[len / binsize] += len;
b += 2 * dsize;
}
}
else
{
if (b >= e)
{
continue;
}
if (dist)
{
b += 2 * dsize;
}
if (prefix)
{
printf("%s ", pcTrack);
}
if (!newline)
{
printf("%d (%" PRIu64 ")", i, (e - b) / dsize);
}
if (strcmp(pcTrack, TRACK_PACBIO_CHEM) == 0)
{
printf(" %.*s\n", (int) ((e - b) / dsize), (char*) data + b);
continue;
}
while (b < e)
{
if (newline)
{
if (BED)
{
if (pacbio_track)
{
int s, f;
s = pacbio_anno[i] / sizeof(track_data);
f = pacbio_anno[i + 1] / sizeof(track_data);
if (s < f)
printf("%s/%d/%d_%d", flist[map], pacbio_data[s], pacbio_data[s + 1], pacbio_data[s + 2]);
else
printf("%s_%d_%d_%d", flist[map], -1, i, len);
}
else if (seqID_track)
{
int s, f;
s = seqID_anno[i] / sizeof(track_data);
f = seqID_anno[i + 1] / sizeof(track_data);
if (s < f)
printf("%s_%d_%d_%d", flist[map], seqID_data[s], i, len);
}
else
{
printf("%s_%d_%d_%d", flist[map], -1, i, len);
}
}
else
printf("%d", i);
}
if (dist)
{
printf(" %" PRIu64, value(data + b, dsize) - value(data + b - dsize, dsize));
b += 2 * dsize;
}
else if (intervals)
{
printf(" %" PRIu64 " %" PRIu64, value(data + b, dsize), value(data + b + dsize, dsize));
b += 2 * dsize;
}
else
{
printf(" %" PRIu64, value(data + b, dsize));
b += 1 * dsize;
}
if (newline)
{
printf("\n");
}
}
if (!newline)
{
printf("\n");
}
}
}
if (stats)
{
printf("%'10d reads\n", db.nreads);
printf("%'10" PRIu64 " bases\n", stats_total);
printf("%'10" PRIu64 " intervals\n", stats_intervals);
printf("%'10" PRIu64 " bases in intervals (%.1f%%)\n\n", stats_itotal, 100.0 * stats_itotal / stats_total);
printf("Statistics for %s-track\n\n", track->name);
printf("There are %" PRIu64 " intervals totaling %" PRIu64 " bases (%.1f%% of all data)\n\n", stats_intervals, stats_itotal, (100. * stats_itotal) / db.totlen);
{
int64_t btot;
uint64_t cum;
int k;
printf("Distribution of %s intervals (Bin size = %d)\n\n", track->name, binsize);
printf("%8s %8s %12s %7s %10s %10s\n", "Bin", "Count", "% Intervals", "% Bases", "cum avg", "bin avg");
cum = 0;
btot = 0;
for (k = nbin - 1; k >= 0; k--)
{
cum += hist[k];
btot += tsum[k];
if (hist[k] > 0)
{
printf("%'8d %'8d %12.1f %7.1f %'10" PRIu64 " %'10" PRIu64 "\n",
k * binsize,
hist[k],
(100. * cum) / stats_intervals,
(100. * btot) / stats_itotal,
btot / cum,
tsum[k] / hist[k]);
if (cum == stats_intervals)
{
break;
}
}
}
printf("\n");
}
}
// track_close(track);
Close_DB(&db);
free(tsum);
free(hist);
return 0;
}
|
MartinPippel/DAmar
|
lib/pass.c
|
<reponame>MartinPippel/DAmar
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "pass.h"
#include "oflags.h"
PassContext* pass_init(FILE* fileOvlIn, FILE* fileOvlOut)
{
PassContext* ctx = malloc(sizeof(PassContext));
ctx->fileOvlIn = fileOvlIn;
ctx->trace = NULL;
ctx->tmax = 0;
// get file size
fseek(ctx->fileOvlIn, 0L, SEEK_END);
ctx->sizeOvlIn = ftell(ctx->fileOvlIn);
fseek(ctx->fileOvlIn, 0L, SEEK_SET);
ctx->progress_tick = ctx->sizeOvlIn / 10;
ovl_header_read(fileOvlIn, &(ctx->novl), &(ctx->twidth));
ctx->tbytes = TBYTES( ctx->twidth );
ctx->off_start = ctx->off_end = 0;
ctx->progress = 0;
ctx->split_b = 0;
if (fileOvlOut)
{
ctx->fileOvlOut = fileOvlOut;
ctx->novl_out = 0;
ctx->novl_out_discarded = 0;
ovl_header_write(fileOvlOut, ctx->novl_out, ctx->twidth);
ctx->write_overlaps = 1;
}
else
{
ctx->fileOvlOut = NULL;
ctx->write_overlaps = 0;
}
return ctx;
}
void pass_part(PassContext* ctx, off_t start, off_t end)
{
assert(start < end);
ctx->off_start = start;
ctx->off_end = end;
}
void pass_free(PassContext* ctx)
{
if (ctx->write_overlaps)
{
ovl_header_write(ctx->fileOvlOut, ctx->novl_out, ctx->twidth);
}
free(ctx->trace);
free(ctx);
}
void read_unpacked_trace(FILE* fileOvl, Overlap* ovl, size_t tbytes)
{
Read_Trace(fileOvl, ovl, tbytes);
if (tbytes == sizeof(uint8))
{
Decompress_TraceTo16(ovl);
}
}
void pass(PassContext* ctx, pass_handler handler)
{
Overlap* pOvls = NULL;
int omax = 500;
pOvls = (Overlap*)malloc(sizeof(Overlap)*omax);
int split_b = ctx->split_b;
int load_trace = ctx->load_trace;
int unpack_trace = ctx->unpack_trace;
int write_overlaps = ctx->write_overlaps;
int purge_discarded = ctx->purge_discarded;
if (ctx->off_start)
{
fseek(ctx->fileOvlIn, ctx->off_start, SEEK_SET);
}
else
{
fseek(ctx->fileOvlIn, sizeof(ovl_header_novl) + sizeof(ovl_header_twidth), SEEK_SET);
}
if (Read_Overlap(ctx->fileOvlIn, pOvls))
{
free(pOvls);
return ;
}
int a, b, n, cont;
ovl_header_novl i;
n = i = 0;
cont = 1;
ctx->progress_nexttick = ctx->progress_tick;
while (cont)
{
if (ctx->progress)
{
long pos = ftell(ctx->fileOvlIn);
if (pos >= ctx->progress_nexttick)
{
printf("%3.0f%% done\n", 100.0 * pos / ctx->sizeOvlIn);
ctx->progress_nexttick += ctx->progress_tick;
}
}
pOvls[0] = pOvls[n];
a = pOvls->aread;
b = pOvls->bread;
if (load_trace)
{
if (pOvls[0].path.tlen > ctx->tmax)
{
ctx->tmax = 1.2 * ctx->tmax + pOvls[0].path.tlen;
ctx->trace = realloc(ctx->trace, ctx->tmax * sizeof(ovl_trace));
}
pOvls[0].path.trace = ctx->trace;
Read_Trace(ctx->fileOvlIn, pOvls, ctx->tbytes);
ctx->tcur = pOvls[0].path.tlen;
if (unpack_trace && ctx->tbytes == sizeof(uint8))
{
Decompress_TraceTo16(pOvls);
}
}
else
{
fseek(ctx->fileOvlIn, ctx->tbytes * pOvls[0].path.tlen, SEEK_CUR);
}
n = 1;
while (1)
{
if (Read_Overlap(ctx->fileOvlIn, pOvls+n) ||
pOvls[n].aread != a ||
(split_b && pOvls[n].bread != b))
{
break;
}
if (load_trace)
{
if (pOvls[n].path.tlen + ctx->tcur > ctx->tmax)
{
ctx->tmax = 1.2 * ctx->tmax + pOvls[n].path.tlen;
ovl_trace* trace = realloc(ctx->trace, ctx->tmax * sizeof(ovl_trace));
assert(trace != NULL);
int j;
for (j = 0; j < n; j++)
{
pOvls[j].path.trace = trace + ((ovl_trace*)(pOvls[j].path.trace) - ctx->trace);
}
ctx->trace = trace;
}
pOvls[n].path.trace = ctx->trace + ctx->tcur;
Read_Trace(ctx->fileOvlIn, pOvls+n, ctx->tbytes);
ctx->tcur += pOvls[n].path.tlen;
if (unpack_trace && ctx->tbytes == sizeof(uint8))
{
Decompress_TraceTo16(pOvls + n);
}
}
else
{
fseek(ctx->fileOvlIn, ctx->tbytes * pOvls[n].path.tlen, SEEK_CUR);
}
n += 1;
if (n >= omax)
{
omax = 1.2 * n + 10;
pOvls = (Overlap*)realloc(pOvls, sizeof(Overlap) * omax);
}
}
cont = handler(ctx->data, pOvls, n);
if (write_overlaps)
{
int j;
for (j = 0; j < n; j++)
{
int isDiscarded = (pOvls[j].flags & OVL_DISCARD);
if (!purge_discarded || !isDiscarded)
{
if (unpack_trace && ctx->tbytes == sizeof(uint8) && load_trace)
{
Compress_TraceTo8(pOvls + j, 1);
}
if (!load_trace)
{
pOvls[j].path.tlen = 0;
}
pOvls[j].flags &= ~OVL_TEMP;
Write_Overlap(ctx->fileOvlOut, pOvls + j, ctx->tbytes);
ctx->novl_out++;
if (isDiscarded)
{
ctx->novl_out_discarded++;
}
}
}
}
i += n;
if ( !cont || (ctx->off_start && ftello(ctx->fileOvlIn) >= ctx->off_end) || i >= ctx->novl )
{
cont = 0;
}
}
free(pOvls);
}
int ovl_header_read(FILE* fileOvl, ovl_header_novl* novl, ovl_header_twidth* twidth)
{
rewind(fileOvl);
if (fread(novl, sizeof(ovl_header_novl), 1, fileOvl) != 1)
{
return 0;
}
if (fread(twidth, sizeof(ovl_header_twidth), 1, fileOvl) != 1)
{
return 0;
}
return 1;
}
void ovl_header_write(FILE* fileOvl, ovl_header_novl novl, ovl_header_twidth twidth)
{
rewind(fileOvl);
fwrite(&novl, sizeof(ovl_header_novl), 1, fileOvl);
fwrite(&twidth, sizeof(ovl_header_twidth), 1, fileOvl);
}
|
MartinPippel/DAmar
|
db/FA2dam.c
|
/************************************************************************************\
* *
* Copyright (c) 2014, Dr. <NAME> (EWM). All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without modification, *
* are permitted provided that the following conditions are met: *
* *
* · Redistributions of source code must retain the above copyright notice, this *
* list of conditions and the following disclaimer. *
* *
* · Redistributions in binary form must reproduce the above copyright notice, this *
* list of conditions and the following disclaimer in the documentation and/or *
* other materials provided with the distribution. *
* *
* · The name of EWM may not be used to endorse or promote products derived from *
* this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY EWM ”AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, *
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND *
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL EWM BE LIABLE *
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS *
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY *
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING *
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN *
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
* *
* For any issues regarding this software and its use, contact EWM at: *
* *
* <NAME> Jr. *
* Bautzner Str. 122e *
* 01099 Dresden *
* GERMANY *
* Email: <EMAIL> *
* *
\************************************************************************************/
/*******************************************************************************************
*
* Add .fasta files to a DB:
* Adds the given fasta files in the given order to <path>.db. If the db does not exist
* then it is created. All .fasta files added to a given data base must have the same
* header format and follow Pacbio's convention. A file cannot be added twice and this
* is enforced. The command either builds or appends to the .<path>.idx and .<path>.bps
* files, where the index file (.idx) contains information about each read and their offsets
* in the base-pair file (.bps) that holds the sequences where each base is compessed
* into 2-bits. The two files are hidden by virtue of their names beginning with a '.'.
* <path>.db is effectively a stub file with given name that contains an ASCII listing
* of the files added to the DB and possibly the block partitioning for the DB if DBsplit
* has been called upon it.
*
* Author: <NAME>
* Date : May 2013
* Modify: DB upgrade: now *add to* or create a DB depending on whether it exists, read
* multiple .fasta files (no longer a stdin pipe).
* Date : April 2014
*
********************************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <sys/stat.h>
#include <unistd.h>
#include "lib/tracks.h"
#include "DB.h"
#include "fileUtils.h"
#include "FA2x.h"
#ifdef HIDE_FILES
#define PATHSEP "/."
#else
#define PATHSEP "/"
#endif
extern char *optarg;
extern int optind, opterr, optopt;
static char *Usage = "[-v] <path:string> ( -f<file> | <input:fasta> ... )";
static char number[128] =
{ 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1, 0, 0, 0, 2,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 3, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1, 0, 0, 0, 2,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 3, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
};
int main(int argc, char *argv[])
{ FILE *ostub;
char *dbname;
char *root, *pwd;
FILE *bases, *indx, *hdrs;
int64 boff, hoff;
int ifiles, ofiles;
char **flist;
HITS_DB db;
int ureads;
int VERBOSE;
FILE *IFILE;
CreateContext ctx;
bzero(&ctx, sizeof(CreateContext));
ctx.db = &db;
// Process command line
{ int i, j, k;
int flags[128];
ARG_INIT("fasta2DAM")
IFILE = NULL;
j = 1;
for (i = 1; i < argc; i++)
if (argv[i][0] == '-')
switch (argv[i][1])
{ default:
ARG_FLAGS("v")
break;
case 'f':
IFILE = fopen(argv[i]+2,"r");
if (IFILE == NULL)
{ fprintf(stderr,"%s: Cannot open file of inputs '%s'\n",Prog_Name,argv[i]+2);
exit (1);
}
break;
}
else
argv[j++] = argv[i];
argc = j;
VERBOSE = flags['v'];
if ((IFILE == NULL && argc <= 2) || (IFILE != NULL && argc != 2))
{ fprintf(stderr,"Usage: %s %s\n",Prog_Name,Usage);
exit (1);
}
}
// Try to open DB file, if present then adding to DB, otherwise creating new DB. Set up
// variables as follows:
// dbname = full name of map index = <pwd>/<root>.dam
// ostub = new image of db file (will overwrite old image at end)
// bases = .bps file positioned for appending
// indx = .idx file positioned for appending
// ureads = # of reads currently in db
// boff = offset in .bps at which to place next sequence
// hoff = offset in .hdr at which to place next header prefix
// ifiles = # of .fasta files to add
// ofiles = # of .fasta files added so far
// flist = [0..ifiles] list of file names (root only) added to db so far
root = Root(argv[1],".dam");
pwd = PathTo(argv[1]);
dbname = Strdup(Catenate(pwd,"/",root,".dam"),"Allocating map index name");
if (dbname == NULL)
exit (1);
if (IFILE == NULL)
ifiles = argc-2;
else
{ File_Iterator *ng;
ifiles = 0;
ng = init_file_iterator(argc,argv,IFILE,2);
while (next_file(ng))
ifiles += 1;
free(ng);
}
ofiles = 0;
bases = Fopen(Catenate(pwd,PATHSEP,root,".bps"),"w");
indx = Fopen(Catenate(pwd,PATHSEP,root,".idx"),"w");
hdrs = Fopen(Catenate(pwd,PATHSEP,root,".hdr"),"w");
if (bases == NULL || indx == NULL || hdrs == NULL)
exit (1);
flist = (char **) Malloc(sizeof(char *)*ifiles,"Allocating file list");
fwrite(&db,sizeof(HITS_DB),1,indx);
ureads = 0;
boff = 0;
hoff = 0;
ostub = Fopen(dbname,"w+");
if (ostub == NULL)
exit (1);
fprintf(ostub,DB_NFILE,argc-2);
{ int maxlen;
int64 totlen, count[4];
int rmax;
HITS_READ prec;
char *read;
int c;
File_Iterator *ng;
// Buffer for accumulating .fasta sequence over multiple lines
rmax = MAX_NAME + 60000;
read = (char *) Malloc(rmax+1,"Allocating line buffer");
if (read == NULL)
goto error;
totlen = 0; // total # of bases in new .fasta files
maxlen = 0; // longest read in new .fasta files
for (c = 0; c < 4; c++) // count of acgt in new .fasta files
count[c] = 0;
// For each .fasta file do:
ng = init_file_iterator(argc,argv,IFILE,2);
while (next_file(ng))
{ FILE *input;
char *path, *core;
int nline, eof, rlen;
if (ng->name == NULL) goto error;
// Open it: <path>/<core>.fasta, check that core is not too long,
// and checking that it is not already in flist.
path = PathTo(ng->name);
core = Root(ng->name,".fasta");
if ((input = Fopen(Catenate(path,"/",core,".fasta"),"r")) == NULL)
goto error;
free(path);
{ int j;
for (j = 0; j < ofiles; j++)
if (strcmp(core,flist[j]) == 0)
{ fprintf(stderr,"%s: File %s.fasta is already in database %s.db\n",
Prog_Name,core,Root(argv[1],".db"));
goto error;
}
}
// Get the header of the first line. If the file is empty skip.
rlen = 0;
nline = 1;
eof = (fgets(read,MAX_NAME,input) == NULL);
if (eof || strlen(read) < 1)
{ fprintf(stderr,"Skipping '%s', file is empty!\n",core);
fclose(input);
free(core);
continue;
}
// Add the file name to flist
if (VERBOSE)
{ fprintf(stderr,"Adding '%s' ...\n",core);
fflush(stderr);
}
flist[ofiles++] = core;
// Check that the first line has PACBIO format, and record prolog in 'prolog'.
if (read[strlen(read)-1] != '\n')
{ fprintf(stderr,"File %s.fasta, Line 1: Fasta line is too long (> %d chars)\n",
core,MAX_NAME-2);
goto error;
}
if (!eof && read[0] != '>')
{ fprintf(stderr,"File %s.fasta, Line 1: First header in fasta file is missing\n",core);
goto error;
}
// Read in all the sequences until end-of-file
{ int i, x, n;
while (!eof)
{ int hlen;
read[rlen] = '>';
hlen = strlen(read+rlen);
fwrite(read+rlen,1,hlen,hdrs);
rlen = 0;
while (1)
{ eof = (fgets(read+rlen,MAX_NAME,input) == NULL);
nline += 1;
x = strlen(read+rlen)-1;
if (read[rlen+x] != '\n')
{ fprintf(stderr,"File %s.fasta, Line %d:",core,nline);
fprintf(stderr," Fasta line is too long (> %d chars)\n",MAX_NAME-2);
goto error;
}
if (eof || read[rlen] == '>')
break;
rlen += x;
if (rlen + MAX_NAME > rmax)
{ rmax = ((int) (1.2 * rmax)) + 1000 + MAX_NAME;
read = (char *) realloc(read,rmax+1);
if (read == NULL)
{ fprintf(stderr,"File %s.fasta, Line %d:",core,nline);
fprintf(stderr," Out of memory (Allocating line buffer)\n");
goto error;
}
}
}
read[rlen] = '\0';
n = 0;
i = -1;
while (i < rlen)
{ int pbeg, plen, clen;
printf("i: %d\n",i);
while (i < rlen)
if (number[(int) read[++i]] < 4)
break;
if (i >= rlen) break;
pbeg = i;
add_to_track(&ctx, find_track(&ctx, TRACK_SCAFFOLD), ureads, n++);
add_to_track(&ctx, find_track(&ctx, TRACK_SCAFFOLD), ureads, pbeg);
prec.boff = boff;
prec.coff = hoff;
prec.flags = DB_BEST;
while (i < rlen)
{ x = number[(int) read[i]];
if (x >= 4) break;
count[x] += 1;
read[i++] = (char) x;
}
prec.rlen = plen = i-pbeg;
ureads += 1;
totlen += plen;
if (plen > maxlen)
maxlen = plen;
Compress_Read(plen,read+pbeg);
clen = COMPRESSED_LEN(plen);
fwrite(read+pbeg,1,clen,bases);
boff += clen;
fwrite(&prec,sizeof(HITS_READ),1,indx);
}
hoff += hlen;
}
fprintf(ostub,DB_FDATA,ureads,core,core);
fclose(input);
}
}
// Update relevant fields in db record
db.ureads = ureads;
// db.treads = ureads;
for (c = 0; c < 4; c++)
db.freq[c] = (float) ((1.*count[c])/totlen);
db.totlen = totlen;
db.maxlen = maxlen;
// db.cutoff = -1;
}
rewind(indx);
fwrite(&db,sizeof(HITS_DB),1,indx); // Write the finalized db record into .idx
write_tracks(&ctx, argv[optind]);
free_tracks(&ctx);
fclose(ostub);
fclose(indx);
fclose(bases);
fclose(hdrs);
exit (0);
// Error exit: Remove the .idx, .bps, and .dam files
error:
fclose(ostub);
fclose(indx);
fclose(hdrs);
fclose(bases);
unlink(Catenate(pwd,PATHSEP,root,".idx"));
unlink(Catenate(pwd,PATHSEP,root,".bps"));
unlink(Catenate(pwd,PATHSEP,root,".hdr"));
unlink(Catenate(pwd,"/",root,".dam"));
exit (1);
}
|
MartinPippel/DAmar
|
touring/OGlayout.c
|
/*******************************************************************************************
*
* Creates a Yifan Hu Layout from a given graph file.
*
* input : dot, graphml
* output: dot, svg
* parameter: adopted from Gephi (https://gephi.org/)
* -R ... remove reverse edges from output, i.e. create a directed graph with arbitrary direction
* -q ... QuadTree level (default: 10)
* Maximum value to be used in the QuadTree representation. Greater values mean more accuracy
* -t ... theta, Barnes Hut opening criteria (default: 1.2)
* Smaller values mean more accuracy
* -l ... Minimum level size (default: 3)
* Minimum amount of nodes every level must have. Bigger values mean less levels
* -c ... Coarsening rate (default: 0.75)
* Minimum relative size (number of nodes) between two levels. Smaller values mean less levels
* -s ... Step ratio (default: 0.97)
* The ratio used to update the step size across iterations
* -d ... Optimal distance (default: 100)
* The natural length of the springs (edge length). Bigger values mean nodes will be further apart
*
* Date : August 2016
*
* Author : <NAME>
*
*******************************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>
#include <sys/param.h>
#include <ctype.h>
#include <float.h>
#include <math.h>
#include <time.h>
#include "OGlayout.h"
// todo change recursive function calls of calculateForce to get rid of ForceVector mallocs
// constants
#define DEFAULT_QUADTREE_LEVEL 10
#define DEFAULT_BARNESHUT_THETA 1.2
#define DEFAULT_MIN_LEVEL 3
#define DEFAULT_COARSEN_RATE 0.75
#define DEFAULT_STEP_RATIO 0.97
#define DEFAULT_OPTIMAL_DISTANCE 100
#define DEFAULT_CONVERGENCE_THRESHOLD 0.0001
#define DEFAULT_ADAPTIVE_COOLING 0
#define DEFAULT_RELATIVE_STRENGTH 0.2
// switches
#undef DEBUG_READ_DOT
#undef DEBUG_READ_GRAPHML
// getopt
extern char* optarg;
extern int optind, opterr, optopt;
int cmpAttributes(const void* a, const void *b)
{
OgAttribute *at1 = (OgAttribute*) a;
OgAttribute *at2 = (OgAttribute*) b;
if (at1->forNode != at2->forNode)
return at2->forNode - at1->forNode;
return (at1->id - at2->id);
}
int cmpOgEdges(const void* a, const void *b)
{
OgEdge *e1 = (OgEdge*) a;
OgEdge *e2 = (OgEdge*) b;
if (e1->sourceId != e2->sourceId)
return e1->sourceId - e2->sourceId;
return e1->targetId - e2->targetId;
}
int cmpNodesById(const void* a, const void *b)
{
Node *n1 = (Node*) a;
Node *n2 = (Node*) b;
return n1->id - n2->id;
}
int cmpEdgeBySourceNode(const void* a, const void *b)
{
Edge *e1 = (Edge*) a;
Edge *e2 = (Edge*) b;
if (e1->source != e2->source)
return e1->source - e2->source;
return e1->target - e2->target;
}
void assimilateNode(QuadTree *t, Node *n)
{
#if DEBUG
printf("assimilate node: %f, %f, mass %d, cMass: %f. %f", n->x, n->y, t->mass, t->centerMassX, t->centerMassY);
#endif
t->centerMassX = (t->mass * t->centerMassX + n->x) / (t->mass + 1);
t->centerMassY = (t->mass * t->centerMassY + n->y) / (t->mass + 1);
t->mass++;
#if DEBUG
printf(" --> mass %d, cMass: %f. %f", t->mass, t->centerMassX, t->centerMassY);
#endif
}
int leafAdd(QuadTree *t, Node *n)
{
#if DEBUG
printf("leafAdd: node id: %d, idx: %d pos (%f, %f)\n", n->id, n->idx, n->x, n->y);
#endif
assimilateNode(t, n);
return 1;
}
int addNode(QuadTree *t, Node* n)
{
if (t->posX <= n->x && n->x <= t->posX + t->size && t->posY <= n->y && n->y <= t->posY + t->size)
{
#if DEBUG
printf("general add node: %f, %f in tree [%f, %f, - %f, %f]\n", n->x, n->y, t->posX, t->posY, t->posX + t->size, t->posY + t->size);
#endif
return t->add(t, n);
}
else
{
#if DEBUG
printf("out of bounds\n");
#endif
return 0;
}
}
int addToChildren(QuadTree *t, Node* n)
{
#if DEBUG
printf("addtochildren: id %d, idx: %d (%.3f, %.3f)\n", n->id, n->idx, n->x, n->y);
#endif
int i;
for (i = 0; i < 4; i++)
{
#if DEBUG
printf("try to add node id %d, idx: %d (%.3f, %.3f) to child %d\n", n->id, n->idx, n->x, n->y, i);
#endif
if (addNode(&(t->children[i]), n))
{
#if DEBUG
printf("success\n");
#endif
return i + 1;
}
}
return 0;
}
int rootAdd(QuadTree *t, Node *n)
{
#if DEBUG
printf("rootAdd: node id: %d, idx: %d pos (%f, %f)\n", n->id, n->idx, n->x, n->y);
#endif
assimilateNode(t, n);
return addToChildren(t, n);
}
int secondAdd(QuadTree *t, Node* n)
{
#if DEBUG
printf("secondAdd: node id: %d, idx: %d pos (%f, %f)\n", n->id, n->idx, n->x, n->y);
#endif
divideTree(t);
t->add = rootAdd;
static Node dummy;
dummy.x = t->centerMassX;
dummy.y = t->centerMassY;
dummy.id = -1234;
addToChildren(t, &dummy);
return t->add(t, n);
}
int firstAdd(QuadTree *t, Node* n)
{
#if DEBUG
printf("firstAdd: node id: %d, idx: %d pos (%f, %f)\n", n->id, n->idx, n->x, n->y);
#endif
t->mass = 1;
t->centerMassX = n->x;
t->centerMassY = n->y;
if (t->maxLevel == 0)
{
t->add = leafAdd;
}
else
{
t->add = secondAdd;
}
return 1;
}
void initQuadTree(struct QuadTree *t, float posX, float posY, float size)
{
t->posX = posX;
t->posY = posY;
t->size = size;
t->isLeaf = 1;
t->mass = 0;
t->add = firstAdd;
t->eps = (float) 1e-6;
#if DEBUG
printf("initQuadTree: %f %f %f --> [%f, %f - %f, %f]\n", posX, posY, size, posX, posY, posX + size, posY + size);
#endif
}
void divideTree(struct QuadTree *t)
{
float childSize = t->size / 2;
initQuadTree(t->children, t->posX + childSize, t->posY + childSize, childSize);
initQuadTree(t->children + 1, t->posX, t->posY + childSize, childSize);
initQuadTree(t->children + 2, t->posX, t->posY, childSize);
initQuadTree(t->children + 3, t->posX + childSize, t->posY, childSize);
t->isLeaf = 0;
}
void deleteQuadTree(QuadTree* t, int maxLevel)
{
int i;
if (t->children != NULL)
{
for (i = 0; i < 4; i++)
deleteQuadTree(t->children + i, maxLevel);
}
if (t->children != NULL)
free(t->children);
if (t->maxLevel == maxLevel)
free(t);
}
QuadTree* createQuadTree(int maxLevel)
{
size_t num = 0;
int i;
for (i = 1; i <= maxLevel; i++)
num += pow(4, i);
QuadTree* tree = (QuadTree*) malloc(sizeof(QuadTree) * (num + 2));
assert(tree != NULL);
bzero(tree, sizeof(QuadTree) * (num + 2));
QuadTree** list = (QuadTree**) malloc(sizeof(QuadTree*) * ((maxLevel + 1) * 4));
int n = 0;
tree->maxLevel = maxLevel;
list[n] = tree;
QuadTree* pos = tree + 1;
while (n >= 0)
{
QuadTree* t = list[n];
n--;
if (t->maxLevel <= 0)
{
t->children = NULL;
continue;
}
t->children = pos;
pos = pos + 4;
for (i = 0; i < 4; i++, n++)
{
t->children[i].maxLevel = t->maxLevel - 1;
list[n + 1] = t->children + i;
}
}
free(list);
return tree;
}
void buildQuadTree(QuadTree* tree, Graph *g)
{
#if DEBUG
printf("buildQuadTree, glevel: %d, mlevel: %d\n", g->level, maxLevel);
#endif
float minX = FLT_MAX;
float maxX = -FLT_MAX;
float minY = FLT_MAX;
float maxY = -FLT_MAX;
int i;
for (i = 0; i < g->curNodes; i++)
{
minX = min(minX, g->nodes[i].x);
maxX = max(maxX, g->nodes[i].x);
minY = min(minY, g->nodes[i].y);
maxY = max(maxY, g->nodes[i].y);
}
float size = max(maxY - minY, maxX - minX);
initQuadTree(tree, minX, minY, size);
for (i = 0; i < g->curNodes; i++)
{
#if DEBUG
printf("add node: id %d, idx %d pos(%f, %f)\n", g->nodes[i].id, g->nodes[i].idx, g->nodes[i].x, g->nodes[i].y);
#endif
addNode(tree, (g->nodes + i));
}
}
ForceVector* createForceVectorByVector(ForceVector *f)
{
ForceVector *nf = (ForceVector*) malloc(sizeof(ForceVector));
nf->x = f->x;
nf->y = f->y;
return nf;
}
ForceVector* createForceVectorByPair(float x, float y)
{
ForceVector *nf = (ForceVector*) malloc(sizeof(ForceVector));
nf->x = x;
nf->y = y;
return nf;
}
ForceVector* createForceVector()
{
ForceVector *nf = (ForceVector*) malloc(sizeof(ForceVector));
nf->x = 0;
nf->y = 0;
return nf;
}
void addForceVectorToForceVector(ForceVector* f1, ForceVector *f2)
{
if (f1 != NULL && f2 != NULL)
{
f1->x += f2->x;
f1->y += f2->y;
}
}
void multiplyForceVectorByConst(ForceVector* f1, float s)
{
if (f1 != NULL)
{
f1->x *= s;
f1->y *= s;
}
}
void subtractForceVectorFromForceVector(ForceVector* f1, ForceVector *f2)
{
if (f1 != NULL && f2 != NULL)
{
f1->x -= f2->x;
f1->y -= f2->y;
}
}
float getForceVectorEnergy(ForceVector *f)
{
return (f->x * f->x) + (f->y * f->y);
}
float getForceVectorNorm(ForceVector *f)
{
return sqrtf(getForceVectorEnergy(f));
}
ForceVector* normalizeForceVector(ForceVector *f)
{
static ForceVector fv =
{ 0, 0 };
float norm = getForceVectorNorm(f);
fv.x = f->x / norm;
fv.y = f->y / norm;
return &fv;
}
ForceVector* calculateElectricalForce(ElectricalForce *f, Node* n, QuadTree* t, float dist)
{
#if DEBUG
printf(" ELECTRICAL_FORCE ");
#endif
ForceVector *fv = createForceVector();
fv->x = t->centerMassX - n->x;
fv->y = t->centerMassY - n->y;
float scale = -f->relativeStrength * f->optimalDistance * f->optimalDistance / (dist * dist);
if (isnan(scale) || !isfinite(scale))
scale = -1;
#if DEBUG
printf("calclateElectricalForce: fv: %.3f, %.3f, scale %.3f, dist: %.3f node: %d %.3f, %.3f"
" tree mass %.3f %.3f pos %.3f %.3f", fv->x, fv->y, scale, dist, n->id, n->x, n->y, t->centerMassX, t->centerMassY, t->posX, t->posY);
#endif
multiplyForceVectorByConst(fv, scale);
#if DEBUG
printf("-> final fv: %.3f, %.3f\n", fv->x, fv->y);
#endif
return fv;
}
ForceVector* calculateSpringForce(SpringForce* f, Node *n1, Node *n2, float dist)
{
#if DEBUG
printf(" SPRING_FORCE ");
#endif
ForceVector *fv = createForceVector();
fv->x = n2->x - n1->x;
fv->y = n2->y - n1->y;
if (((n1->flag & NODE_HAS_PATH_ID) && (n2->flag & NODE_HAS_PATH_ID)) && n1->pathID != n2->pathID)
{
multiplyForceVectorByConst(fv, (5 * dist / (f->optimalDistance)));
}
// else if (((n1->flag & NODE_HAS_PATH_ID) || (n2->flag & NODE_HAS_PATH_ID)) && n1->pathID != n2->pathID)
// {
// multiplyForceVectorByConst(fv, (0.8 * dist / (f->optimalDistance)));
// }
else
{
multiplyForceVectorByConst(fv, (dist / f->optimalDistance));
}
return fv;
}
float getForceVectorDistanceToQuadTree(Node *n, QuadTree *t)
{
return (float) hypot(n->x - t->centerMassX, n->y - t->centerMassY);
}
float getForceVectorDistanceToNode(Node *n1, Node *n2)
{
return (float) hypot(n1->x - n2->x, n1->y - n2->y);
}
ForceVector *calculateForce(ElectricalForce* ef, Node* n, QuadTree *t)
{
#if DEBUG
printf("calculate force node %d %f %f and tree cmass %f, %f, mass %d, coord: %f, %f\n", n->id, n->x, n->y, t->centerMassX, t->centerMassY, t->mass, t->posX, t->posY);
#endif
if (t->mass <= 0)
{
#if DEBUG
printf(" --> mass is 0\n");
#endif
return NULL;
}
float distance = getForceVectorDistanceToQuadTree(n, t);
#if DEBUG
printf("distance node id %d idx %d pos: %f %f, tree pos: %f, %f mass: %d cmass: %f %f", n->id, n->idx, n->x, n->y, t->posX, t->posY, t->mass, t->centerMassX, t->centerMassY);
#endif
if (t->isLeaf || t->mass == 1)
{
if (distance < 1e-8)
{
#if DEBUG
printf(" --> return NULL\n");
#endif
return NULL;
}
#if DEBUG
printf(" --> calculateElectricalForce(ef, n, t, distance)\n");
#endif
return calculateElectricalForce(ef, n, t, distance);
}
if (distance * ef->theta > t->size)
{
#if DEBUG
printf("--> distance * theta > tree.size()\n");
#endif
ForceVector *tmp = calculateElectricalForce(ef, n, t, distance);
multiplyForceVectorByConst(tmp, t->mass);
return tmp;
}
ForceVector *fr = createForceVector();
int i;
for (i = 0; i < 4; i++)
{
#if DEBUG
printf("calculate force of child : %d\n", i);
#endif
ForceVector * tmp = calculateForce(ef, n, (t->children + i));
if (tmp)
{
addForceVectorToForceVector(fr, tmp);
free(tmp);
}
}
#if DEBUG
printf(" final force: %f, %f\n", fr->x, fr->y);
#endif
return fr;
}
char *trimwhitespace(char *str)
{
char *end;
// Trim leading space
while (isspace(*str))
str++;
if (*str == 0) // All spaces?
return str;
// Trim trailing space
end = str + strlen(str) - 1;
while (end > str && isspace(*end))
end--;
// Write new null terminator
*(end + 1) = '\0';
return str;
}
int read_graphml(OgLayoutContext* octx)
{
FILE* fileIn = fopen(octx->path_graph_in, "r");
if (fileIn == NULL)
return 0;
char* line = NULL;
size_t maxline = 0;
OgGraph *graph;
graph = (OgGraph*) malloc(sizeof(OgGraph));
bzero(graph, sizeof(OgGraph));
int nedges, nnodes, nattr, nEdgeAttr, nNodeAttr;
nedges = nnodes = nattr = nEdgeAttr = nNodeAttr = 0;
int maxNodes, maxEdges, maxAttr;
maxNodes = maxEdges = 1000;
maxAttr = 10;
OgNode* nodes = (OgNode*) malloc(sizeof(OgNode) * maxNodes);
if (nodes == NULL)
{
fprintf(stderr, "Cannot allocate node buffer!\n");
exit(1);
}
bzero(nodes, sizeof(OgNode) * maxNodes);
OgEdge* edges = (OgEdge*) malloc(sizeof(OgEdge) * maxEdges);
if (edges == NULL)
{
fprintf(stderr, "Cannot allocate edge buffer!\n");
exit(1);
}
bzero(edges, sizeof(OgEdge) * maxEdges);
OgAttribute* attrLookup = (OgAttribute*) malloc(sizeof(OgAttribute) * maxAttr);
if (attrLookup == NULL)
{
fprintf(stderr, "Cannot allocate attribute lookup buffer!\n");
exit(1);
}
bzero(attrLookup, sizeof(OgAttribute) * maxAttr);
int nline = 0;
int len;
char *pchrf, *pchrl;
int nodeId;
int maxNodeAttributes = 0;
int maxEdgeAttributes = 0;
while ((len = getline(&line, &maxline, fileIn)) > 0)
{
// printf("line: %s\n", line);
nline++;
char *tline = trimwhitespace(line);
// ignore empty lines
if (strlen(tline) == 0)
continue;
// printf("%s", tline);
// if (strncmp(tline, "<key", 4) == 0)
if (strstr(tline, "<key") != 0)
{
#ifdef DEBUG_READ_GRAPHML
printf("found attr: %d -> %s\n", nnodeattr + nedgeAttr, tline);
#endif
if (nattr == maxAttr)
{
int prev = maxAttr;
maxAttr = maxAttr * 1.2 + 10;
attrLookup = (OgAttribute*) realloc(attrLookup, sizeof(OgAttribute) * maxAttr);
if (attrLookup == NULL)
{
fprintf(stderr, "Cannot increase attribute lookup buffer!\n");
exit(1);
}
bzero(attrLookup + prev, sizeof(OgAttribute) * (maxAttr - prev));
}
OgAttribute * cattr = attrLookup + nattr;
size_t len;
// parse attribute name
pchrf = strstr(tline, "attr.name=\"");
if (pchrf == NULL)
{
fprintf(stderr, "readGraphml: cannot read attribute name at line %d\n", nline);
exit(1);
}
pchrl = strchr(pchrf + 11, '\"');
if (pchrl == NULL)
{
fprintf(stderr, "readGraphml: cannot read closing quote \" for attribute name at line %d\n", nline);
exit(1);
}
*pchrl = '\0';
len = strlen(pchrf + 11);
if(cattr->name == NULL)
cattr->name = (char*) malloc(sizeof(char) * (len + 1));
else
cattr->name = (char*) realloc(cattr->name, sizeof(char) * (len + 1));
assert(cattr->name != NULL);
strncpy(cattr->name, pchrf + 11, len);
cattr->name[len] = '\0';
*pchrl = '\"';
#ifdef DEBUG_READ_GRAPHML
printf("cattr->name: %s\n", cattr->name);
#endif
// parse attribute type
pchrf = strstr(pchrl, "attr.type=\"");
if (pchrf == NULL)
{
fprintf(stderr, "readGraphml: cannot read attr.type at line %d\n", nline);
exit(1);
}
pchrl = strchr(pchrf + 11, '\"');
if (pchrl == NULL)
{
fprintf(stderr, "readGraphml: cannot read closing quote \" for attr.type at line %d\n", nline);
exit(1);
}
*pchrl = '\0';
len = strlen(pchrf + 11);
if(cattr->type == NULL)
cattr->type = (char*) malloc(sizeof(char) * (len + 1));
else
cattr->type = (char*) realloc(cattr->type, sizeof(char) * (len + 1));
assert(cattr->type != NULL);
strncpy(cattr->type, pchrf + 11, len);
cattr->type[len] = '\0';
*pchrl = '\"';
#ifdef DEBUG_READ_GRAPHML
printf("cattr->type: %s\n", cattr->type);
#endif
// parse attribute for
pchrf = strstr(pchrl, "for=\"");
if (pchrf == NULL)
{
fprintf(stderr, "readGraphml: cannot read \"for\" at line %d\n", nline);
exit(1);
}
pchrl = strchr(pchrf + 5, '\"');
if (pchrl == NULL)
{
fprintf(stderr, "readGraphml: cannot read closing quote \" for \"for\" at line %d\n", nline);
exit(1);
}
*pchrl = '\0';
if (strcmp(pchrf + 5, "node") == 0)
{
cattr->forNode = 1;
nNodeAttr++;
}
else if (strcmp(pchrf + 5, "edge") == 0)
{
cattr->forNode = 0;
nEdgeAttr++;
}
else
{
fprintf(stderr, "readGraphml: Unknown value \"%s\" in \"for\" at line %d. Expected node or edge!\n", pchrf + 4, nline);
exit(1);
}
*pchrl = '\"';
#ifdef DEBUG_READ_GRAPHML
printf("cattr->forNode: %d\n", cattr->forNode);
#endif
// parse attribute id
pchrf = strstr(pchrl, "id=\"");
if (pchrf == NULL)
{
fprintf(stderr, "readGraphml: cannot read id at line %d\n", nline);
exit(1);
}
pchrl = strchr(pchrf + 4, '\"');
if (pchrl == NULL)
{
fprintf(stderr, "readGraphml: cannot read closing quote \" for id at line %d\n", nline);
exit(1);
}
*pchrl = '\0';
// if id is equal to name than skip attribute
if (strcmp(cattr->name, pchrf + 4) == 0)
{
;
}
else
{
if (*(pchrf + 4) != 'd')
{
fprintf(stderr, "readGraphml: invalid id format at line %d. (expected: dINT)\n", nline);
exit(1);
}
cattr->id = atoi(pchrf + 5);
*pchrl = '\"';
#ifdef DEBUG_READ_GRAPHML
printf("cattr->id: %d\n", cattr->id);
#endif
nattr++;
}
}
// parse edges
else if (strncmp(tline, "<edge", 5) == 0)
{
#ifdef DEBUG_READ_GRAPHML
printf("found edge: %d\n", nedges);
#endif
if (nedges == maxEdges)
{
int prev = maxEdges;
maxEdges = maxEdges * 1.2 + 10;
edges = (OgEdge*) realloc(edges, sizeof(OgEdge) * maxEdges);
if (edges == NULL)
{
fprintf(stderr, "Cannot increase edge buffer!\n");
exit(1);
}
bzero(edges + prev, sizeof(OgEdge) * (maxEdges - prev) );
}
// parse source id
pchrf = strstr(tline, "source=\"");
if (pchrf == NULL)
{
fprintf(stderr, "readGraphml: cannot read edge source id at line %d\n", nline);
exit(1);
}
pchrl = strchr(pchrf + 8, '\"');
if (pchrl == NULL)
{
fprintf(stderr, "readGraphml: cannot read closing quote \" for source attribute at line %d\n", nline);
exit(1);
}
*pchrl = '\0';
nodeId = atoi(pchrf + 8);
#ifdef DEBUG_READ_GRAPHML
printf("parsed source nodeID: %d\n", nodeId);
#endif
OgEdge* edge = edges + nedges;
bzero(edge, sizeof(OgEdge));
edge->maxAttributes = max(1, maxEdgeAttributes);
edge->numAttributes = 0;
edge->attributes = (Pair*) realloc(edge->attributes, sizeof(Pair) * (edge->maxAttributes));
assert(edge->attributes != NULL);
edge->sourceId = nodeId;
*pchrl = '\"';
// parse target id
pchrf = strstr(tline, "target=\"");
if (pchrf == NULL)
{
fprintf(stderr, "readGraphml: cannot read edge target id at line %d\n", nline);
exit(1);
}
pchrl = strchr(pchrf + 8, '\"');
if (pchrl == NULL)
{
fprintf(stderr, "readGraphml: cannot read closing quote \" for target attribute at line %d\n", nline);
exit(1);
}
*pchrl = '\0';
nodeId = atoi(pchrf + 8);
#ifdef DEBUG_READ_GRAPHML
printf("parsed target nodeID: %d\n", nodeId);
#endif
edge->targetId = nodeId;
*pchrl = '\"';
// parse edge attributes until closing edge tag is found
while ((len = getline(&line, &maxline, fileIn)) > 0)
{
nline++;
tline = trimwhitespace(line);
pchrf = strstr(tline, "</edge>");
if (pchrf != NULL)
break;
pchrf = strstr(tline, "<data");
if (pchrf == NULL)
{
printf("ignore line %d, expected <data tag!\n", nline);
continue;
}
pchrf = strstr(tline + 5, "key=\"");
if (pchrf == NULL)
{
printf("ignore line %d, expected key attribute!\n", nline);
continue;
}
pchrl = strchr(pchrf + 5, '\"');
if (pchrl == NULL)
{
printf("ignore line %d, missing closing quote for key attribute!\n", nline);
continue;
}
*pchrl = '\0';
// allocate attribute name buffer
size_t len = strlen(pchrf + 5);
Pair *attribute = edge->attributes + edge->numAttributes;
attribute->key = (char*) malloc(sizeof(char) * (len + 1));
assert(attribute->key != NULL);
strncpy(attribute->key, pchrf + 5, len);
attribute->key[len] = '\0';
*pchrl = '\"';
pchrf = strchr(pchrl, '>');
if (pchrf == NULL)
{
printf("ignore line %d, expected closing bracket \">\" of data tag!\n", nline);
continue;
}
pchrl = strstr(pchrf, "</data>");
if (pchrf == NULL)
{
printf("ignore line %d, expected closing tag </data>!\n", nline);
continue;
}
*pchrl = '\0';
// allocate attribute value buffer
len = strlen(pchrf + 1);
attribute->value = (char*) malloc(sizeof(char) * (len + 1));
assert(attribute->value != NULL);
strncpy(attribute->value, pchrf + 1, len);
attribute->value[len] = '\0';
*pchrl = '<';
#ifdef DEBUG_READ_GRAPHML
printf("parsed attribute %d: \"%s\" with value: \"%s\"\n", edge->numAttributes, attribute->key, attribute->value);
#endif
edge->numAttributes++;
if (maxEdgeAttributes < edge->numAttributes)
maxEdgeAttributes = edge->numAttributes;
if (edge->numAttributes == edge->maxAttributes)
{
edge->maxAttributes = (edge->numAttributes * 1.2 + 2);
edge->attributes = (Pair*) realloc(edge->attributes, sizeof(Pair) * (edge->maxAttributes + 1));
assert(edge->attributes != NULL);
}
}
nedges++;
}
// parse nodes
// else if (strncmp(tline, "<node", 5) == 0)
else if (strstr(tline, "<node") != 0)
{
if (nnodes == maxNodes)
{
int prev = maxNodes;
maxNodes = maxNodes * 1.2 + 10;
nodes = (OgNode*) realloc(nodes, sizeof(OgNode) * maxNodes);
if (nodes == NULL)
{
fprintf(stderr, "Cannot increase node buffer!\n");
exit(1);
}
bzero(nodes + prev, sizeof(OgNode) * (maxNodes - prev));
}
// parse id
pchrf = strstr(tline, "id=\"");
if (pchrf == NULL)
{
fprintf(stderr, "readGraphml: cannot read node id at line %d\n", nline);
exit(1);
}
pchrl = strchr(pchrf + 4, '\"');
if (pchrl == NULL)
{
fprintf(stderr, "readGraphml: cannot read node id at line %d\n", nline);
exit(1);
}
*pchrl = '\0';
nodeId = atoi(pchrf + 4);
#ifdef DEBUG_READ_GRAPHML
printf("parsed node ID: %d\n", nodeId);
#endif
OgNode * node = nodes + nnodes;
bzero(node, sizeof(OgNode));
node->maxAttributes = max(1, maxNodeAttributes);
node->numAttributes = 0;
node->attributes = (Pair*) realloc(node->attributes, sizeof(Pair) * (node->maxAttributes));
node->nodeID = nodeId;
assert(node->attributes != NULL);
*pchrl = '\"';
// parse node attributes until closing node tag is found
while ((len = getline(&line, &maxline, fileIn)) > 0)
{
nline++;
tline = trimwhitespace(line);
pchrf = strstr(tline, "</node>");
if (pchrf != NULL)
break;
pchrf = strstr(tline, "<data");
if (pchrf == NULL)
{
printf("ignore line %d, expected <data tag!\n", nline);
continue;
}
pchrf = strstr(tline + 5, "key=\"");
if (pchrf == NULL)
{
printf("ignore line %d, expected key attribute!\n", nline);
continue;
}
pchrl = strchr(pchrf + 5, '\"');
if (pchrl == NULL)
{
printf("ignore line %d, missing closing quote for key attribute!\n", nline);
continue;
}
*pchrl = '\0';
// allocate attribute name buffer
size_t len = strlen(pchrf + 5);
Pair *attribute = node->attributes + node->numAttributes;
attribute->key = (char*) malloc(sizeof(char) * (len + 1));
assert(attribute->key != NULL);
strncpy(attribute->key, pchrf + 5, len);
attribute->key[len] = '\0';
*pchrl = '\"';
pchrf = strchr(pchrl, '>');
if (pchrf == NULL)
{
printf("ignore line %d, expected closing bracket \">\" of data tag!\n", nline);
continue;
}
pchrl = strstr(pchrf, "</data>");
if (pchrf == NULL)
{
printf("ignore line %d, expected closing tag </data>!\n", nline);
continue;
}
*pchrl = '\0';
// allocate attribute value buffer
len = strlen(pchrf + 1);
attribute->value = (char*) malloc(sizeof(char) * (len + 1));
assert(attribute->value != NULL);
strncpy(attribute->value, pchrf + 1, len);
attribute->value[len] = '\0';
*pchrl = '<';
#ifdef DEBUG_READ_GRAPHML
printf("parsed attribute %d: \"%s\" with value: \"%s\"\n", node->numAttributes, attribute->key, attribute->value);
#endif
node->numAttributes++;
if (maxNodeAttributes < node->numAttributes)
maxNodeAttributes = node->numAttributes;
if (node->numAttributes == node->maxAttributes)
{
node->maxAttributes = (node->numAttributes * 1.2 + 2);
node->attributes = (Pair*) realloc(node->attributes, sizeof(Pair) * (node->maxAttributes + 1));
assert(node->attributes != NULL);
}
}
nnodes++;
}
// ignore rest
}
graph->numEdges = nedges;
graph->edges = edges;
graph->numNodes = nnodes;
graph->nodes = nodes;
qsort(attrLookup, nattr, sizeof(OgAttribute), cmpAttributes);
// sanity check
int i;
for (i = 0; i < nattr; i++)
{
if (i < nNodeAttr)
assert(attrLookup[i].forNode == 1);
assert(i == attrLookup[i].id);
}
graph->numAttr = nattr;
graph->attrLookup = attrLookup;
octx->graph = graph;
return 1;
}
int read_dot(OgLayoutContext* octx)
{
FILE* fileIn = fopen(octx->path_graph_in, "r");
if (fileIn == NULL)
return 0;
char* line = NULL;
size_t maxline = 0;
int nnodes = 0;
int nedges = 0;
OgEdge* edges;
OgNode* nodes;
int maxNodes = 1000;
nodes = (OgNode*) malloc(sizeof(OgNode) * maxNodes);
if (nodes == NULL)
{
fprintf(stderr, "Cannot allocate node buffer!\n");
exit(1);
}
bzero(nodes, sizeof(OgNode) * maxNodes);
int maxEdges = 1000;
edges = (OgEdge*) malloc(sizeof(OgEdge) * maxEdges);
if (edges == NULL)
{
fprintf(stderr, "Cannot allocate edge buffer!\n");
exit(1);
}
bzero(edges, sizeof(OgEdge) * maxEdges);
int nline = 0;
int len;
char *pchrf, *pchrl;
int nodeId;
int maxNodeAttributes = 0;
int maxEdgeAttributes = 0;
while ((len = getline(&line, &maxline, fileIn)) > 0)
{
#if DEBUG
printf("line: %s\n", line);
#endif
nline++;
char *tline = trimwhitespace(line);
if (!isdigit(tline[0]))
continue;
// get first space
pchrf = strchr(tline, ' ');
*pchrf = '\0';
pchrl = strchr(tline, '-');
if (pchrl == NULL) // its a node
{
if (nnodes == maxNodes)
{
maxNodes = maxNodes * 1.2 + 10;
nodes = (OgNode*) realloc(nodes, sizeof(OgNode) * maxNodes);
if (nodes == NULL)
{
fprintf(stderr, "Cannot increase node buffer!\n");
exit(1);
}
}
// parse nodeID
nodeId = atoi(tline);
OgNode * node = nodes + nnodes;
bzero(node, sizeof(OgNode));
node->maxAttributes = max(1, maxNodeAttributes);
node->numAttributes = 0;
node->attributes = (Pair*) realloc(node->attributes, sizeof(Pair) * (node->maxAttributes));
node->nodeID = nodeId;
assert(node->attributes != NULL);
#ifdef DEBUG_READ_DOT
printf("parsed nodeID: %d\n", nodeId);
#endif
// parse node attributes
*pchrf = ' ';
pchrl = strchr(tline, '[');
if (pchrl == NULL)
{
#ifdef DEBUG_READ_DOT
printf("node has no attributes\n");
#endif
}
else
{
pchrf = pchrl;
while ((pchrl = strchr(pchrf, '=')) != NULL)
{
if (*(pchrl + 1) == '\"')
{
// get attribute name
*pchrl = '\0';
if (*pchrf == '[')
pchrf++;
// allocate attribute name buffer
size_t len = strlen(pchrf);
Pair *attribute = node->attributes + node->numAttributes;
attribute->key = (char*) malloc(sizeof(char) * (len + 1));
assert(attribute->key != NULL);
strncpy(attribute->key, pchrf, len);
attribute->key[len] = '\0';
*pchrl = '=';
pchrf = pchrl;
pchrl = strchr(pchrf, ' ');
while (pchrl != NULL && *(pchrl - 1) != ',') // ... the attribute value contains itself spaces
pchrl = strchr(pchrl + 1, ' ');
if (pchrl == NULL)
pchrl = strchr(pchrf, ']');
if (pchrl == NULL)
{
#ifdef DEBUG_READ_DOT
printf("no values for last attribute");
#endif
continue;
}
*pchrl = '\0';
// allocate attribute value buffer
len = strlen(pchrf);
attribute->value = (char*) malloc(sizeof(char) * (len + 1));
assert(attribute->value != NULL);
char *from, *to;
if (pchrf[len - 1] == ',')
to = pchrf + len - 3;
else
to = pchrf + len - 2; // last attribute
from = pchrf + 2;
if (from > to) // empty attribute
attribute->value[0] = '\0';
else
{
strncpy(attribute->value, from, to - from + 1);
attribute->value[to - from + 1] = '\0';
}
#ifdef DEBUG_READ_DOT
printf("parsed attribute %d: \"%s\" with value: \"%s\"\n", node->numAttributes, attribute->key, attribute->value);
#endif
*pchrl = ' ';
node->numAttributes++;
if (maxNodeAttributes < node->numAttributes)
maxNodeAttributes = node->numAttributes;
if (node->numAttributes == node->maxAttributes)
{
node->maxAttributes = (node->numAttributes * 1.2 + 2);
node->attributes = (Pair*) realloc(node->attributes, sizeof(Pair) * (node->maxAttributes + 1));
assert(node->attributes != NULL);
}
}
pchrf = pchrl + 1;
}
}
nnodes++;
}
else // its an edge
{
if (nedges == maxEdges)
{
maxEdges = maxEdges * 1.2 + 10;
edges = (OgEdge*) realloc(edges, sizeof(OgEdge) * maxEdges);
if (edges == NULL)
{
fprintf(stderr, "Cannot increase edge buffer!\n");
exit(1);
}
}
// parse source and target node ids
*pchrl = '\0';
nodeId = atoi(tline);
#ifdef DEBUG_READ_DOT
printf("parsed source nodeID: %d\n", nodeId);
#endif
OgEdge* edge = edges + nedges;
bzero(edge, sizeof(OgEdge));
edge->maxAttributes = max(1, maxEdgeAttributes);
edge->numAttributes = 0;
edge->attributes = (Pair*) realloc(edge->attributes, sizeof(Pair) * (edge->maxAttributes));
edge->sourceId = nodeId;
assert(edge->attributes != NULL);
*pchrl = '-';
while (!isdigit(*pchrl))
pchrl++;
assert(pchrf != pchrl);
nodeId = atoi(pchrl);
#ifdef DEBUG_READ_DOT
printf("parsed target nodeID: %d\n", nodeId);
#endif
edge->targetId = nodeId;
// parse edge attributes
*pchrf = ' ';
pchrl = strchr(tline, '[');
if (pchrl == NULL)
{
#ifdef DEBUG_READ_DOT
printf("edge has not attributes\n");
#endif
}
else
{
pchrf = pchrl;
while ((pchrl = strchr(pchrf, '=')) != NULL)
{
if (*(pchrl + 1) == '\"')
{
// get attribute name
*pchrl = '\0';
if (*pchrf == '[')
pchrf++;
// allocate attribute name buffer
size_t len = strlen(pchrf);
Pair *attribute = edge->attributes + edge->numAttributes;
attribute->key = (char*) malloc(sizeof(char) * (len + 1));
assert(attribute->key != NULL);
strncpy(attribute->key, pchrf, len);
attribute->key[len] = '\0';
*pchrl = '=';
pchrf = pchrl;
pchrl = strchr(pchrf, ' ');
while (pchrl != NULL && *(pchrl - 1) != ',') // ... the attribute value contains itself spaces
pchrl = strchr(pchrl + 1, ' ');
if (pchrl == NULL)
pchrl = strchr(pchrf, ']');
if (pchrl == NULL)
{
#ifdef DEBUG_READ_DOT
printf("no values for last attribute");
#endif
continue;
}
*pchrl = '\0';
// allocate attribute value buffer
len = strlen(pchrf);
attribute->value = (char*) malloc(sizeof(char) * (len + 1));
assert(attribute->value != NULL);
char *from, *to;
if (pchrf[len - 1] == ',')
to = pchrf + len - 3;
else
to = pchrf + len - 2; // last attribute
from = pchrf + 2;
if (from > to) // empty attribute
attribute->value[0] = '\0';
else
{
strncpy(attribute->value, from, to - from + 1);
attribute->value[to - from + 1] = '\0';
}
#ifdef DEBUG_READ_DOT
printf("parsed attribute %d: \"%s\" with value: \"%s\"\n", edge->numAttributes, edge->attributes->key, edge->attributes->value);
#endif
*pchrl = ' ';
edge->numAttributes++;
if (maxEdgeAttributes < edge->numAttributes)
maxEdgeAttributes = edge->numAttributes;
if (edge->numAttributes == edge->maxAttributes)
{
edge->maxAttributes = (edge->numAttributes * 1.2 + 2);
edge->attributes = (Pair*) realloc(edge->attributes, sizeof(Pair) * (edge->maxAttributes + 1));
assert(edge->attributes != NULL);
}
}
pchrf = pchrl + 1;
}
}
nedges++;
}
}
OgGraph *graph = (OgGraph*) malloc(sizeof(OgGraph));
assert(graph != NULL);
bzero(graph, sizeof(OgGraph));
graph->numEdges = nedges;
graph->edges = edges;
graph->numNodes = nnodes;
graph->nodes = nodes;
octx->graph = graph;
return 1;
}
void write_svg(OgLayoutContext *octx, Graph *g)
{
FILE *f = fopen(octx->path_graph_out, "w");
if (f == NULL)
{
fprintf(stderr, "Cannot write graph into file: %s!\n", octx->path_graph_out);
}
int nnodes, nedges;
nnodes = nedges = 0;
float minX, minY;
float maxX, maxY;
minX = minY = FLT_MAX;
maxX = maxY = -FLT_MAX;
int i, j;
for (i = 0; i < g->curNodes; i++)
{
Node *n = g->nodes + i;
if (n->x < minX)
minX = n->x;
if (n->y < minY)
minY = n->y;
if (n->x > maxX)
maxX = n->x;
if (n->y > maxY)
maxY = n->y;
}
// move coordinates into positive range
if (minX < 0 || minY < 0)
{
if (minX < 0)
minX -= octx->optimalDistance;
if (minY < 0)
minY -= octx->optimalDistance;
for (i = 0; i < g->curNodes; i++)
{
Node *n = g->nodes + i;
if (minX < 0)
n->x += -minX;
if (minY < 0)
n->y += -minY;
}
}
// write header
fprintf(f, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
fprintf(f, "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n\n");
fprintf(f, "<svg xmlns=\"http://www.w3.org/2000/svg\"\n");
fprintf(f, " xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n");
fprintf(f, " xmlns:ev=\"http://www.w3.org/2001/xml-events\"\n");
fprintf(f, " version=\"1.1\" baseProfile=\"full\"\n");
fprintf(f, " width=\"%dpt\" height=\"%dpt\">\n", (int) ceil(minX < 0 ? maxX - minX : maxX), (int) ceil(
minY < 0 ? maxY - minY : maxY));
fprintf(f, " <title>OGLayout %s</title>\n", octx->path_graph_in);
// graph
Node dummy;
// edges
fprintf(f, " <g id=\"edges\">\n");
if (octx->cleanReverseEdges)
{
for (i = 0; i < octx->graph->numEdges; i++)
{
OgEdge *e = octx->graph->edges + i;
if (e->sourceId > e->targetId)
{
int tmp = e->sourceId;
e->sourceId = e->targetId;
e->targetId = tmp;
}
}
qsort(octx->graph->edges, octx->graph->numEdges, sizeof(OgEdge), cmpOgEdges);
}
for (i = 0; i < octx->graph->numEdges; i++)
{
OgEdge *edge = octx->graph->edges + i;
int use = -1;
if (octx->cleanReverseEdges)
{
if (i + 1 < octx->graph->numEdges && edge->sourceId == octx->graph->edges[i + 1].sourceId && edge->targetId == octx->graph->edges[i + 1].targetId)
{
for (j = 0; j < edge->numAttributes; j++)
{
if (octx->graph->numAttr) // i.e. attributes must be translated via idNUM into attribute name
{
int keyIdx = atoi(octx->graph->edges[i].attributes[j].key + 1);
assert(keyIdx >= 0 && keyIdx < octx->graph->numAttr);
if ((strcmp(octx->graph->attrLookup[keyIdx].name, "path") == 0) && (atoi(edge->attributes[j].value) >= 0))
{
use = i;
break;
}
}
else
{
if (strcmp(edge->attributes[j].key, "path") == 0)
{
if (atoi(edge->attributes[j].value) >= 0)
{
use = i;
break;
}
}
}
}
if (use < 0)
{
if (octx->graph->numAttr) // i.e. attributes must be translated via idNUM into attribute name
{
for (j = 0; j < octx->graph->edges[i + 1].numAttributes; j++)
{
int keyIdx = atoi(octx->graph->edges[i + 1].attributes[j].key + 1);
assert(keyIdx >= 0 && keyIdx < octx->graph->numAttr);
if ((strcmp(octx->graph->attrLookup[keyIdx].name, "path") == 0) && (atoi(octx->graph->edges[i + 1].attributes[j].value) >= 0))
{
use = i + 1;
break;
}
}
}
else
{
for (j = 0; j < octx->graph->edges[i + 1].numAttributes; j++)
{
if (strcmp(octx->graph->edges[i + 1].attributes[j].key, "path") == 0)
{
if (atoi(octx->graph->edges[i + 1].attributes[j].value) >= 0)
{
use = i + 1;
break;
}
}
}
}
}
if (use < 0 || use > i) // take reverse edge
edge = octx->graph->edges + i + 1;
i += 1;
}
}
dummy.id = edge->sourceId;
Node *c = bsearch(&dummy, g->nodes, g->curNodes, sizeof(Node), cmpNodesById);
assert(c != NULL);
fprintf(f, " <path d=\"M %f %f", c->x, c->y);
dummy.id = edge->targetId;
Node *d = bsearch(&dummy, g->nodes, g->curNodes, sizeof(Node), cmpNodesById);
assert(d != NULL);
fprintf(f, " L %f %f\"", d->x, d->y);
int foundColor = -1;
int foundPath = -1;
for (j = 0; j < edge->numAttributes; j++)
{
if (octx->graph->numAttr) // i.e. attributes must be translated via idNUM into attribute name
{
int keyIdx = atoi(edge->attributes[j].key + 1);
assert(keyIdx >= 0 && keyIdx < octx->graph->numAttr);
if (strcmp(octx->graph->attrLookup[keyIdx].name, "color") == 0)
foundColor = j;
if (strcmp(octx->graph->attrLookup[keyIdx].name, "path") == 0)
foundPath = j;
}
else
{
if (strcmp(edge->attributes[j].key, "color") == 0)
{
foundColor = j;
}
if (strcmp(edge->attributes[j].key, "path") == 0)
{
foundPath = j;
}
}
}
switch (octx->colorScheme)
{
case 1:
{
if (foundPath >= 0 && atoi(edge->attributes[foundPath].value) >= 0)
fprintf(f, " style=\"fill:none;stroke:red;");
else
fprintf(f, " style=\"fill:none;stroke:black;");
}
break;
case 2:
fprintf(f, " style=\"fill:none;stroke:black;");
break;
case 0:
default:
{
if (foundColor < 0)
fprintf(f, " style=\"fill:none;stroke:black;");
else
fprintf(f, " style=\"fill:none;stroke:%s;", edge->attributes[foundColor].value);
}
break;
}
int weight = 1;
if (foundPath >= 0)
{
int path = atoi(edge->attributes[foundPath].value);
if (path >= 0)
weight *= 10;
}
fprintf(f, "stroke-width:%d;\"/>\n", weight);
nedges++;
}
// closing edge group
fprintf(f, " </g>\n");
// nodes
fprintf(f, " <g id=\"nodes\">\n");
for (i = 0; i < octx->graph->numNodes; i++)
{
OgNode *node = octx->graph->nodes + i;
dummy.id = node->nodeID;
Node *c = bsearch(&dummy, g->nodes, g->curNodes, sizeof(Node), cmpNodesById);
assert(c != NULL);
if (c->id == 231953 || c->id == 338031)
{
fprintf(f, " <circle style=\"fill:red;stroke:red;stroke-width:2;\" cx=\"%f\" cy=\"%f\" r=\"10\"/>\n", c->x, c->y);
}
else if (c->id == 401251 || c->id == 430634)
{
fprintf(f, " <circle style=\"fill:orange;stroke:orange;stroke-width:2;\" cx=\"%f\" cy=\"%f\" r=\"10\"/>\n", c->x, c->y);
}
else if (octx->colorScheme > 0)
{
if (c->pathID >= 0)
{
if (octx->colorScheme == 1)
fprintf(f, " <circle style=\"fill:red;stroke:red;stroke-width:2;\" cx=\"%f\" cy=\"%f\" r=\"10\"/>\n", c->x, c->y);
else
// colorScheme is 2
fprintf(f, " <circle style=\"fill:black;stroke:black;stroke-width:2;\" cx=\"%f\" cy=\"%f\" r=\"10\"/>\n", c->x, c->y);
}
else
fprintf(f, " <circle style=\"fill:white;stroke:black;stroke-width:2;\" cx=\"%f\" cy=\"%f\" r=\"10\"/>\n", c->x, c->y);
}
else
{
int foundColor = 0;
for (j = 0; j < node->numAttributes; j++)
{
if (octx->graph->numAttr) // i.e. attributes must be translated via idNUM into attribute name
{
int keyIdx = atoi(node->attributes[j].key + 1);
assert(keyIdx >= 0 && keyIdx < octx->graph->numAttr);
if (strcmp(octx->graph->attrLookup[keyIdx].name, "color") == 0)
{
foundColor = 1;
fprintf(f, " <circle style=\"fill:%s;stroke:black;stroke-width:2;\" cx=\"%f\" cy=\"%f\" r=\"10\"/>\n", node->attributes[j].value, c->x, c->y);
break;
}
}
else
{
if (strcmp(node->attributes[j].key, "color") == 0)
{
fprintf(f, " <circle style=\"fill:%s;stroke:black;stroke-width:2;\" cx=\"%f\" cy=\"%f\" r=\"10\"/>\n", node->attributes[j].value, c->x, c->y);
foundColor = 1;
break;
}
}
#ifdef DEBUG
if (strcmp(node->attributes[j].key, "read") == 0)
fprintf(f, " <text text-anchor=\"middle\" x=\"%f\" y=\"%f\" style=\"fill:red;stroke:red;font-family:Bitstream Vera Sans;font-size:12.00pt;\">%s</text>\n", c->x, c->y, node->attributes[j].value);
#endif
}
if (!foundColor)
fprintf(f, " <circle style=\"fill:black;stroke:black;stroke-width:2;\" cx=\"%f\" cy=\"%f\" r=\"10\"/>\n", c->x, c->y);
}
nnodes++;
}
// closing node group
fprintf(f, " </g>\n");
// closing svg tag
fprintf(f, "</svg>\n");
fclose(f);
if (octx->verbose)
{
printf("write: %d nodes and %d edges\n", nnodes, nedges);
}
}
void write_graphml(OgLayoutContext *octx, Graph *g)
{
FILE *f = fopen(octx->path_graph_out, "w");
int nedges = 0;
int nnodes = 0;
if (f == NULL)
{
fprintf(stderr, "Cannot write graph into file: %s!\n", octx->path_graph_out);
}
// write header
fprintf(f, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
fprintf(f, "<graphml xmlns=\"http://graphml.graphdrawing.org/xmlns\"\n");
fprintf(f, " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n");
fprintf(f, " xsi:schemaLocation=\"http://graphml.graphdrawing.org/xmlns\n");
fprintf(f, " http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd\">\n");
// write node attributes
int i, j;
for (i=0; i<octx->graph->numAttr; i++)
{
OgAttribute* attr = octx->graph->attrLookup + i;
fprintf(f, " <key attr.name=\"%s\" attr.type=\"%s\" for=\"%s\" id=\"d%d\"/>\n",
attr->name, attr->type, (attr->forNode ? "node" : "edge"), attr->id);
}
// append coordinate attribute
fprintf(f, " <key attr.name=\"x\" attr.type=\"double\" for=\"node\" id=\"d%d\"/>\n",i++);
fprintf(f, " <key attr.name=\"y\" attr.type=\"double\" for=\"node\" id=\"d%d\"/>\n",i++);
// write graph
fprintf(f, " <graph id=\"G\" edgedefault=\"directed\">\n");
// dump out nodes
Node dummy;
for (i = 0; i < octx->graph->numNodes; i++)
{
OgNode *node = octx->graph->nodes + i;
dummy.id = node->nodeID;
Node *c = bsearch(&dummy, g->nodes, g->curNodes, sizeof(Node), cmpNodesById);
assert(c != NULL);
nnodes++;
fprintf(f, " <node id=\"%d\">\n", node->nodeID);
fflush(f);
for (j = 0; j < node->numAttributes; j++)
{
// ignore previous position
if (octx->graph->numAttr) // thats only true if input graph was graphml
{
int keyIdx = atoi(node->attributes[j].key + 1);
assert(keyIdx >= 0 && keyIdx < octx->graph->numAttr);
if ((strcmp(octx->graph->attrLookup[keyIdx].name, "pos") == 0))
continue;
fprintf(f, " <data key=\"%s\">%s</data>\n", node->attributes[j].key, node->attributes[j].value);
}
else
{
if (strcmp(node->attributes[j].key, "pos") == 0)
continue;
fprintf(f, " <data key=\"%s\">%s</data>\n", node->attributes[j].key, node->attributes[j].value);
}
fflush(f);
}
fprintf(f, " <data key=\"d%d\">%.3f</data>\n", octx->graph->numAttr, c->x);
fprintf(f, " <data key=\"d%d\">%.3f</data>\n", octx->graph->numAttr+1, c->y);
fflush(f);
fprintf(f, " </node>\n");
fflush(f);
}
if (octx->cleanReverseEdges)
{
for (i = 0; i < octx->graph->numEdges; i++)
{
OgEdge *e = octx->graph->edges + i;
if (e->sourceId > e->targetId)
{
int tmp = e->sourceId;
e->sourceId = e->targetId;
e->targetId = tmp;
}
}
qsort(octx->graph->edges, octx->graph->numEdges, sizeof(OgEdge), cmpOgEdges);
}
for (i = 0; i < octx->graph->numEdges; i++)
{
OgEdge *edge = octx->graph->edges + i;
int use = -1;
if (octx->cleanReverseEdges)
{
if (i + 1 < octx->graph->numEdges && edge->sourceId == octx->graph->edges[i + 1].sourceId && edge->targetId == octx->graph->edges[i + 1].targetId)
{
for (j = 0; j < edge->numAttributes; j++)
{
if (octx->graph->numAttr) // i.e. attributes must be translated via idNUM into attribute name
{
int keyIdx = atoi(octx->graph->edges[i].attributes[j].key + 1);
assert(keyIdx >= 0 && keyIdx < octx->graph->numAttr);
if ((strcmp(octx->graph->attrLookup[keyIdx].name, "path") == 0) && (atoi(edge->attributes[j].value) >= 0))
{
use = i;
break;
}
}
else
{
if (strcmp(edge->attributes[j].key, "path") == 0)
{
if (atoi(edge->attributes[j].value) >= 0)
{
use = i;
break;
}
}
}
}
if (use < 0)
{
if (octx->graph->numAttr) // i.e. attributes must be translated via idNUM into attribute name
{
for (j = 0; j < octx->graph->edges[i + 1].numAttributes; j++)
{
int keyIdx = atoi(octx->graph->edges[i + 1].attributes[j].key + 1);
assert(keyIdx >= 0 && keyIdx < octx->graph->numAttr);
if ((strcmp(octx->graph->attrLookup[keyIdx].name, "path") == 0) && (atoi(octx->graph->edges[i + 1].attributes[j].value) >= 0))
{
use = i + 1;
break;
}
}
}
else
{
for (j = 0; j < octx->graph->edges[i + 1].numAttributes; j++)
{
if (strcmp(octx->graph->edges[i + 1].attributes[j].key, "path") == 0)
{
if (atoi(octx->graph->edges[i + 1].attributes[j].value) >= 0)
{
use = i + 1;
break;
}
}
}
}
}
if (use < 0 || use > i) // take reverse edge
{
edge = octx->graph->edges + i + 1;
}
i += 1;
}
}
nedges++;
fprintf(f, " <edge id=\"%d\" source=\"%d\" target=\"%d\">\n",nedges, edge->sourceId, edge->targetId);
for (j = 0; j < edge->numAttributes; j++)
{
fprintf(f, " <data key=\"%s\">%s</data>\n", edge->attributes[j].key, edge->attributes[j].value);
}
fprintf(f, " </edge>\n");
}
fprintf(f, " </graph>\n");
fprintf(f, "</graphml>\n");
fclose(f);
if (octx->verbose)
{
printf("write: %d nodes and %d edges\n", nnodes, nedges);
}
}
void write_dot(OgLayoutContext *octx, Graph *g)
{
FILE *f = fopen(octx->path_graph_out, "w");
int nedges = 0;
int nnodes = 0;
if (f == NULL)
{
fprintf(stderr, "Cannot write graph into file: %s!\n", octx->path_graph_out);
}
fprintf(f, "digraph G {\n");
// dump out nodes
int i, j;
Node dummy;
for (i = 0; i < octx->graph->numNodes; i++)
{
OgNode *node = octx->graph->nodes + i;
dummy.id = node->nodeID;
Node *c = bsearch(&dummy, g->nodes, g->curNodes, sizeof(Node), cmpNodesById);
assert(c != NULL);
nnodes++;
fprintf(f, "%d", node->nodeID);
fprintf(f, " [");
fflush(f);
for (j = 0; j < node->numAttributes; j++)
{
// ignore previous position
if (octx->graph->numAttr)
{
int keyIdx = atoi(node->attributes[j].key + 1);
assert(keyIdx >= 0 && keyIdx < octx->graph->numAttr);
if ((strcmp(octx->graph->attrLookup[keyIdx].name, "pos") == 0))
continue;
fprintf(f, "%s=\"%s\", ", octx->graph->attrLookup[keyIdx].name, node->attributes[j].value);
}
else
{
if (strcmp(node->attributes[j].key, "pos") == 0)
continue;
fprintf(f, "%s=\"%s\", ", node->attributes[j].key, node->attributes[j].value);
}
fflush(f);
}
fprintf(f, "pos=\"%f,%f\"", c->x, c->y);
fflush(f);
fprintf(f, "]\n");
fflush(f);
}
if (octx->cleanReverseEdges)
{
for (i = 0; i < octx->graph->numEdges; i++)
{
OgEdge *e = octx->graph->edges + i;
if (e->sourceId > e->targetId)
{
int tmp = e->sourceId;
e->sourceId = e->targetId;
e->targetId = tmp;
}
}
qsort(octx->graph->edges, octx->graph->numEdges, sizeof(OgEdge), cmpOgEdges);
}
for (i = 0; i < octx->graph->numEdges; i++)
{
OgEdge *edge = octx->graph->edges + i;
int use = -1;
if (octx->cleanReverseEdges)
{
if (i + 1 < octx->graph->numEdges && edge->sourceId == octx->graph->edges[i + 1].sourceId && edge->targetId == octx->graph->edges[i + 1].targetId)
{
for (j = 0; j < edge->numAttributes; j++)
{
if (octx->graph->numAttr) // i.e. attributes must be translated via idNUM into attribute name
{
int keyIdx = atoi(octx->graph->edges[i].attributes[j].key + 1);
assert(keyIdx >= 0 && keyIdx < octx->graph->numAttr);
if ((strcmp(octx->graph->attrLookup[keyIdx].name, "path") == 0) && (atoi(edge->attributes[j].value) >= 0))
{
use = i;
break;
}
}
else
{
if (strcmp(edge->attributes[j].key, "path") == 0)
{
if (atoi(edge->attributes[j].value) >= 0)
{
use = i;
break;
}
}
}
}
if (use < 0)
{
if (octx->graph->numAttr) // i.e. attributes must be translated via idNUM into attribute name
{
for (j = 0; j < octx->graph->edges[i + 1].numAttributes; j++)
{
int keyIdx = atoi(octx->graph->edges[i + 1].attributes[j].key + 1);
assert(keyIdx >= 0 && keyIdx < octx->graph->numAttr);
if ((strcmp(octx->graph->attrLookup[keyIdx].name, "path") == 0) && (atoi(octx->graph->edges[i + 1].attributes[j].value) >= 0))
{
use = i + 1;
break;
}
}
}
else
{
for (j = 0; j < octx->graph->edges[i + 1].numAttributes; j++)
{
if (strcmp(octx->graph->edges[i + 1].attributes[j].key, "path") == 0)
{
if (atoi(octx->graph->edges[i + 1].attributes[j].value) >= 0)
{
use = i + 1;
break;
}
}
}
}
}
if (use < 0 || use > i) // take reverse edge
{
edge = octx->graph->edges + i + 1;
}
i += 1;
}
}
nedges++;
fprintf(f, "%d->%d", edge->sourceId, edge->targetId);
fprintf(f, " [");
for (j = 0; j < edge->numAttributes; j++)
{
if (octx->graph->numAttr)
{
int keyIdx = atoi(edge->attributes[j].key + 1);
assert(keyIdx >= 0 && keyIdx < octx->graph->numAttr);
fprintf(f, "%s=\"%s\"", octx->graph->attrLookup[keyIdx].name, edge->attributes[j].value);
}
else
fprintf(f, "%s=\"%s\"", edge->attributes[j].key, edge->attributes[j].value);
if (j + 1 < edge->numAttributes)
fprintf(f, ", ");
}
fprintf(f, "]\n");
}
fprintf(f, "}\n");
fclose(f);
if (octx->verbose)
{
printf("write: %d nodes and %d edges\n", nnodes, nedges);
}
}
void deleteGraph(Graph *g)
{
if (g != NULL)
{
free(g->edges);
free(g->nodes);
if (g->parent != NULL)
g->parent->child = NULL;
if (g->child != NULL)
g->child->parent = NULL;
free(g);
}
}
void refineGraph(Graph *g)
{
if (g->child == NULL)
return;
double r = 10;
int count = 0;
int refined = 0;
Graph * child = g->child;
Node * cNodes = child->nodes;
#if DEBUG
printf("refine graph\n");
#endif
int i, j;
for (i = 0; i < g->curNodes; i++)
{
count++;
Node *n = g->nodes + i;
#if DEBUG
printf("%d (%.3f, %.3f)", i, n->x, n->y);
#endif
if (n->flag & NODE_IS_MERGED)
{
refined++;
for (j = 0; j < 2; j++)
{
double t = ((double) rand() / (double) (RAND_MAX));
cNodes[n->childIds[j]].x = (float) (n->x + r * cos(t));
cNodes[n->childIds[j]].y = (float) (n->y + r * sin(t));
#if DEBUG
printf(" p: %d (%.3f, %.3f))", n->childIds[j], cNodes[n->childIds[j]].x, cNodes[n->childIds[j]].y);
#endif
}
}
else
{
cNodes[n->childIds[0]].x = n->x;
cNodes[n->childIds[0]].y = n->y;
#if DEBUG
printf(" p: %d (%.3fq, %.3f))", n->childIds[0], cNodes[n->childIds[0]].x, cNodes[n->childIds[0]].y);
#endif
}
#if DEBUG
printf("\n");
#endif
}
#if DEBUG
printf("refined Graph:\n");
printf("nodes: \n");
for (i = 0; i < child->curNodes; i++)
{
Node *n = child->nodes + i;
printf("node %d: id: %d, idx: %d, firstEdge: %d %d pos: %f, %f\n", i, n->id, n->idx, child->edges[n->firstEdgeIdx].source, child->edges[n->firstEdgeIdx].target, n->x, n->y);
}
printf("edges: \n");
for (i = 0; i < child->curEdges; i++)
{
Edge *e = child->edges + i;
printf("edge %d: %d - %d\n", i, e->source, e->target);
}
#endif
}
void updateEdges(Graph *g)
{
#if DEBUG
printf("update edges:\n");
#endif
// sort nodes and set idx appropriately
int i;
for (i = 0; i < g->curNodes; i++)
{
#if DEBUG
printf("node %d: id: %d idx: %d\n", i, g->nodes[i].id, g->nodes[i].idx);
#endif
}
qsort(g->nodes, g->curNodes, sizeof(Node), cmpNodesById);
for (i = 0; i < g->maxNodes; i++)
g->nodes[i].idx = i;
#if DEBUG
for (i = 0; i < g->curNodes; i++)
{
printf("node %d: id: %d idx: %d\n", i, g->nodes[i].id, g->nodes[i].idx);
}
#endif
Graph *child = g->child;
assert(child != NULL);
Node dummy;
for (i = 0; i < child->curEdges; i++)
{
Edge *e = child->edges + i;
if ((e->flag & EDGE_VISITED) || (e->flag & EDGE_IGNORE))
continue;
#if DEBUG
printf("check edge: %d - %d %d - %d, pID: %d - %d\n", e->source, e->target, child->nodes[e->source].id, child->nodes[e->target].id, child->nodes[e->source].parentId, child->nodes[e->target].parentId);
#endif
Node *a = child->nodes + e->source;
Node *b = child->nodes + e->target;
if (a->parentId == b->parentId && (a->flag & NODE_HAS_MERGED_PARENT))
{
#if DEBUG
printf("update edges: mark %d - %d as visited\n", a->id, b->id);
#endif
e->flag |= EDGE_VISITED;
}
else if ((a->flag & NODE_HAS_PARENT) && (b->flag & NODE_HAS_PARENT) && a->parentId != b->parentId)
{
#if DEBUG
printf("update edges: add adge %d - %d ---> %d - %d\n", a->id, b->id, a->parentId, b->parentId);
#endif
e->flag |= EDGE_VISITED;
dummy.id = a->parentId;
Node *c = bsearch(&dummy, g->nodes, g->curNodes, sizeof(Node), cmpNodesById);
assert(c != NULL);
dummy.id = b->parentId;
Node *d = bsearch(&dummy, g->nodes, g->curNodes, sizeof(Node), cmpNodesById);
assert(d != NULL);
g->edges[g->curEdges].source = c->idx;
g->edges[g->curEdges].target = d->idx;
#if DEBUG
printf("update edges: add adge idx: %d - %d\n", c->idx, d->idx);
#endif
g->curEdges++;
}
}
sortGraphEdges(g);
}
Graph* coarsenGraph(Graph *g, int verboseLevel)
{
Graph *cgraph = (Graph*) malloc(sizeof(Graph));
bzero(cgraph, sizeof(Graph));
cgraph->level = g->level + 1;
cgraph->child = g;
g->parent = cgraph;
cgraph->maxNodes = g->curNodes;
cgraph->nodes = (Node*) malloc(sizeof(Node) * cgraph->maxNodes);
assert(cgraph->nodes != NULL);
bzero(cgraph->nodes, sizeof(Node) * cgraph->maxNodes);
cgraph->maxEdges = g->curEdges;
cgraph->edges = (Edge*) malloc(sizeof(Edge) * cgraph->maxEdges);
assert(cgraph->edges != NULL);
bzero(cgraph->edges, sizeof(Edge) * cgraph->maxEdges);
int i;
int lastId = g->nodes[g->curNodes - 1].id;
// 1st: add all nodes the could be merge
for (i = 0; i < g->curEdges; i++)
{
Edge *e = g->edges + i;
if (e->flag & EDGE_VISITED)
continue;
Node *a = g->nodes + e->source;
Node *b = g->nodes + e->target;
if (a->parentId == b->parentId && !(a->flag & NODE_HAS_MERGED_PARENT))
{
Node *parent = cgraph->nodes + cgraph->curNodes;
parent->id = ++lastId;
parent->x = (a->x + b->x) / 2;
parent->y = (a->y + b->y) / 2;
parent->pathID = -1;
#if DEBUG
printf("COARSEN EDGE: %d - %d --> new node %d\n", a->id, b->id, parent->id);
#endif
parent->childIds[0] = a->idx;
parent->childIds[1] = b->idx;
parent->flag |= (NODE_HAS_CHILD | NODE_IS_MERGED);
// add nodes and edges
a->parentId = parent->id;
b->parentId = parent->id;
// printf("a->child: %d, b->child: %d\n", a->childIdx, b->childIdx);
a->flag |= (NODE_HAS_MERGED_PARENT | NODE_HAS_PARENT);
b->flag |= (NODE_HAS_MERGED_PARENT | NODE_HAS_PARENT);
e->flag |= EDGE_VISITED;
cgraph->curNodes++;
}
#if DEBUG
else
{
printf("NO COARSENING between node %d - %d level %d, %d parents %d, %d\n", a->id, b->id,
a->flag & a->flag & NODE_IS_MERGED ? 1 : 0, b->flag & NODE_IS_MERGED ? 1 : 0, a->parentId, b->parentId);
}
#endif
}
// 2nd add remaining nodes
for (i = 0; i < g->curNodes; i++)
{
Node *c = g->nodes + i;
if (!(c->flag & NODE_HAS_PARENT))
{
#if DEBUG
printf("add single node %d to parent graph\n", c->id);
#endif
Node *parent = cgraph->nodes + cgraph->curNodes;
parent->id = c->id;
parent->x = c->x;
parent->y = c->y;
parent->childIds[0] = c->idx;
parent->flag |= (NODE_HAS_CHILD);
// add nodes and edges
c->parentId = parent->id;
// printf("a->child: %d, b->child: %d\n", a->childIdx, b->childIdx);
c->flag |= (NODE_HAS_PARENT);
cgraph->curNodes++;
}
}
updateEdges(cgraph);
//
if (verboseLevel > 1)
{
printf("reduced number of nodes: from %d to %d\n", g->curNodes, cgraph->curNodes);
printf("reduced number of edges: from %d to %d\n", g->curEdges, cgraph->curEdges);
}
return cgraph;
}
void sortGraphEdges(Graph *g)
{
qsort(g->edges, g->curEdges, sizeof(Edge), cmpEdgeBySourceNode);
// 1st remove duplicate edges
int i, j;
i = 0;
j = 1;
while (j < g->curEdges)
{
assert(i != j);
if (cmpEdgeBySourceNode(g->edges + i, g->edges + j) == 0)
{
if (j + 1 == g->curEdges)
break;
g->edges[i + 1] = g->edges[j + 1];
j += 1;
}
else if (i + 1 < j)
{
g->edges[i + 1] = g->edges[j];
}
i++;
j++;
}
g->curEdges = i + 1;
// 2nd reset first edge indexes -1
for (i = 0; i < g->curNodes; i++)
g->nodes[i].firstEdgeIdx = -1;
// 2nd updates first edge for each node
g->nodes[g->edges[0].source].firstEdgeIdx = 0;
int prevEdgeSourceIdx = g->edges->source;
for (i = 1; i < g->curEdges; i++)
{
Edge *e = g->edges + i;
if (prevEdgeSourceIdx != e->source)
{
g->nodes[e->source].firstEdgeIdx = i;
prevEdgeSourceIdx = g->edges[i].source;
}
}
}
static void usage(FILE* fout, const char* app)
{
fprintf(fout, "usage: %s [-vRS] [-f [dot|graphml]] [-F [dot|svg|graphml]] [-qC n] [-tlcsdg f] input.graph output.graph\n\n", app);
fprintf( fout, "Computes a layout for the (usually toured) input graph.\n\n" );
fprintf(fout, "options: -v verbose\n");
fprintf(fout, " -S skip layout step (e.g. graph format conversion, or apply other color scheme)\n");
fprintf(fout, " -f format graph input format\n");
fprintf(fout, " -F format graph output format\n");
fprintf(fout, " -C n apply color scheme\n");
fprintf(fout, " 0 input colors (default)\n");
fprintf(fout, " 1 edges and nodes: black, path edges red, contig start/end: green\n");
fprintf(fout, " 2 edges and nodes: black\n");
fprintf(fout, " -R remove reverse edges from output, i.e. create a directed graph with arbitrary direction\n");
fprintf(fout, "\nlayout:\n");
fprintf(fout, " -q n QuadTree level (default: 10)\n");
fprintf(fout, " Maximum value to be used in the QuadTree representation. Greater values mean more accuracy\n");
fprintf(fout, " -t f theta, Barnes Hut opening criteria (default: 1.2)\n");
fprintf(fout, " Smaller values mean more accuracy\n");
fprintf(fout, " -l f Minimum level size (default: 3)\n");
fprintf(fout, " Minimum amount of nodes every level must have. Bigger values mean less levels\n");
fprintf(fout, " -c f Coarsening rate (default: 0.75)\n");
fprintf(fout, " Minimum relative size (number of nodes) between two levels. Smaller values mean less levels\n");
fprintf(fout, " -s f Step ratio (default: 0.97)\n");
fprintf(fout, " The ratio used to update the step size across iterations\n");
fprintf(fout, " -d f Optimal distance (default: 100)\n");
fprintf(fout, " The natural length of the springs (edge length). Bigger values mean nodes will be further apart\n");
fprintf(fout, " -g f convergence threshold (default: 0.0001)\n");
}
static int parseOptions(OgLayoutContext *octx, int argc, char *argv[])
{
char* app = argv[ 0 ];
bzero( octx, sizeof( OgLayoutContext ) );
// set default values
octx->quadTreeLevel = DEFAULT_QUADTREE_LEVEL;
octx->coarseningRate = DEFAULT_COARSEN_RATE;
octx->minLevelSize = DEFAULT_MIN_LEVEL;
octx->optimalDistance = DEFAULT_OPTIMAL_DISTANCE;
octx->stepRatio = DEFAULT_STEP_RATIO;
octx->barnesHutTheta = DEFAULT_BARNESHUT_THETA;
octx->convergenceThreshold = DEFAULT_CONVERGENCE_THRESHOLD;
octx->giformat = FORMAT_UNKNOWN;
octx->goformat = FORMAT_UNKNOWN;
octx->skipLayout = 0;
octx->colorScheme = 0;
char* giformat = "UNK";
char* goformat = "UNK";
// process arguments
opterr = 0;
int c;
while ((c = getopt(argc, argv, "vSRq:t:l:c:s:d:f:F:C:g:")) != -1)
{
switch (c)
{
case 'v':
octx->verbose++;
break;
case 'S':
octx->skipLayout = 1;
break;
case 'R':
octx->cleanReverseEdges = 1;
break;
case 'q':
octx->quadTreeLevel = atoi(optarg);
break;
case 't':
octx->barnesHutTheta = atof(optarg);
break;
case 'l':
octx->minLevelSize = atoi(optarg);
break;
case 'c':
octx->coarseningRate = atof(optarg);
break;
case 'g':
octx->convergenceThreshold = atof(optarg);
break;
case 's':
octx->stepRatio = atof(optarg);
break;
case 'd':
octx->optimalDistance = atoi(optarg);
break;
case 'C':
octx->colorScheme = atoi(optarg);
break;
case 'f':
giformat = optarg;
break;
case 'F':
goformat = optarg;
break;
default:
fprintf(stderr, "Unknown option: %s\n", argv[optind - 1]);
usage(stdout, app);
exit(1);
}
}
if (argc - optind < 2)
{
usage(stdout, app);
exit(1);
}
octx->path_graph_in = argv[optind++];
octx->path_graph_out = argv[optind++];
if (octx->colorScheme < 0 || octx->colorScheme > 2)
{
fprintf(stderr, "Unsupported color scheme %d. Available schemes: 0-2!\n", octx->colorScheme);
usage(stdout, app);
exit(1);
}
if (octx->quadTreeLevel < 1 && octx->quadTreeLevel > 100)
{
fprintf(stderr, "Unsupported quadtree level: %d! Allowed range: [1, 100]\n", octx->quadTreeLevel);
return 1;
}
if (octx->stepRatio <= 0 && octx->quadTreeLevel >= 1.0)
{
fprintf(stderr, "Unsupported step ratio: %f! Allowed range: ] 0, 1 [\n", octx->stepRatio);
return 1;
}
if (octx->optimalDistance < 0)
{
fprintf(stderr, "Unsupported optimal distance: %f! Should be a positive value\n", octx->optimalDistance);
return 1;
}
if (octx->barnesHutTheta <= 0)
{
fprintf(stderr, "Unsupported barnes hut theta : %f! Should be a positive value greater 0\n", octx->barnesHutTheta);
return 1;
}
if (octx->coarseningRate <= 0 && octx->coarseningRate >= 1.0)
{
fprintf(stderr, "Unsupported coarsening rate: %f! Allowed range: ] 0, 1 [\n", octx->coarseningRate);
return 1;
}
if (strcmp(giformat, "dot") == 0)
{
octx->giformat = FORMAT_DOT;
}
else if (strcmp(giformat, "graphml") == 0)
{
octx->giformat = FORMAT_GRAPHML;
}
else if (strcmp(giformat, "UNK") == 0)
{
// try to derive format from file extension
size_t len = strlen(octx->path_graph_in);
if (len > 3)
{
if (strcasecmp(octx->path_graph_in + len - 3, "dot") == 0)
octx->giformat = FORMAT_DOT;
}
if (len > 7)
{
if (strcasecmp(octx->path_graph_in + len - 7, "graphml") == 0)
octx->giformat = FORMAT_GRAPHML;
}
if (octx->giformat == FORMAT_UNKNOWN)
{
fprintf(stderr, "error: cannot determine input graph format. Use option -f graphml|dot\n");
usage(stdout, app);
exit(1);
}
}
else
{
fprintf(stderr, "error: unknown input graph format %s\n", giformat);
usage(stdout, app);
exit(1);
}
if (strcmp(goformat, "dot") == 0)
{
octx->goformat = FORMAT_DOT;
}
else if (strcmp(goformat, "grapml") == 0)
{
octx->goformat = FORMAT_GRAPHML;
}
else if (strcmp(goformat, "svg") == 0)
{
octx->goformat = FORMAT_SVG;
}
else if (strcmp(giformat, "UNK") == 0)
{
// try to derive format from file extension
size_t len = strlen(octx->path_graph_out);
if (len > 3)
{
if (strcasecmp(octx->path_graph_out + len - 3, "dot") == 0)
octx->goformat = FORMAT_DOT;
else if (strcasecmp(octx->path_graph_out + len - 3, "svg") == 0)
octx->goformat = FORMAT_SVG;
}
if (len > 7)
{
if (strcasecmp(octx->path_graph_out + len - 7, "graphml") == 0)
octx->goformat = FORMAT_GRAPHML;
}
if (octx->goformat == FORMAT_UNKNOWN)
{
fprintf(stderr, "error: cannot determine output graph format. Use option -f dot|svg\n");
usage(stdout, app);
exit(1);
}
}
else
{
fprintf(stderr, "error: unknown graph format %s\n", goformat);
usage(stdout, app);
exit(1);
}
return 0;
}
static Graph * createInitialGraph(OgLayoutContext *octx)
{
Graph *g = (Graph*) malloc(sizeof(Graph));
if (g == NULL)
return NULL;
bzero(g, sizeof(Graph));
g->maxNodes = octx->graph->numNodes;
g->maxEdges = octx->graph->numEdges;
g->nodes = (Node*) calloc(g->maxNodes, sizeof(Node));
g->edges = (Edge*) calloc(g->maxEdges, sizeof(Edge));
int i, j;
char *pchr;
for (i = 0; i < g->maxNodes; i++)
{
OgNode *node = octx->graph->nodes + i;
g->nodes[i].id = node->nodeID;
g->nodes[i].pathID = -1;
// check if coordinates are available
for (j = 0; j < node->numAttributes; j++)
{
if (strcmp(node->attributes[j].key, "pos") == 0)
{
// get x and y coordinates
pchr = strchr(node->attributes[j].value, ',');
if (pchr == NULL)
break;
if (strlen(pchr + 1) < 1)
break;
*pchr = '\0';
g->nodes[i].x = atof(node->attributes[j].value);
*pchr = ',';
g->nodes[i].y = atof(pchr + 1);
g->nodes[i].flag |= NODE_HAS_COORDINATES;
}
else if (strcmp(node->attributes[j].key, "path") == 0)
{
int path = atoi(node->attributes[j].value);
if (path >= 0)
{
g->nodes[i].pathID = path;
g->nodes[i].flag |= NODE_HAS_PATH_ID;
}
}
}
g->curNodes++;
}
// sort nodes and set idx appropriately
qsort(g->nodes, g->curNodes, sizeof(Node), cmpNodesById);
for (i = 0; i < g->maxNodes; i++)
g->nodes[i].idx = i;
Node dummy;
for (i = 0; i < g->maxEdges; i++)
{
dummy.id = octx->graph->edges[i].sourceId;
Node *a = bsearch(&dummy, g->nodes, g->curNodes, sizeof(Node), cmpNodesById);
assert(a != NULL);
dummy.id = octx->graph->edges[i].targetId;
Node *b = bsearch(&dummy, g->nodes, g->curNodes, sizeof(Node), cmpNodesById);
assert(b != NULL);
g->edges[i].source = a->idx;
g->edges[i].target = b->idx;
g->curEdges++;
}
// sort edges according node ids and set first edge for each node
sortGraphEdges(g);
// if there are two edges between nodes A and B i.e. A->B and B->A
// then ignore one of them
int ignEdge = 0;
for (i = 0; i < g->curEdges; i++)
{
Edge *e = g->edges + i;
if (e->flag & EDGE_IGNORE)
continue;
Node *target = g->nodes + e->target;
if (target->firstEdgeIdx >= 0)
{
Edge *re = g->edges + target->firstEdgeIdx;
assert(re != NULL);
while (re < g->edges + g->curEdges && re->source == e->target)
{
if (re->target == e->source)
{
re->flag |= EDGE_IGNORE;
ignEdge++;
}
re++;
}
}
}
if (octx->verbose > 1)
{
printf("ignore %d reverse edges\n", ignEdge);
}
return g;
}
static MultiLevelLayout* initMultiLevelLayout(OgLayoutContext *octx, Graph *g)
{
MultiLevelLayout *mlayout = (MultiLevelLayout*) malloc(sizeof(MultiLevelLayout));
if (mlayout == NULL)
return NULL;
mlayout->minSize = octx->minLevelSize;
mlayout->minCoarseningRate = octx->coarseningRate;
mlayout->level = 0;
mlayout->maxGraphs = 10;
mlayout->graphs = (Graph**) malloc(sizeof(Graph*) * mlayout->maxGraphs);
mlayout->graphs[0] = g;
mlayout->bestCoordinateSet = (float*) malloc(sizeof(float) * g->curNodes * 2);
if (mlayout->bestCoordinateSet == NULL)
return NULL;
// start coarsen graph
while (1)
{
if (mlayout->level + 1 >= mlayout->maxGraphs)
{
mlayout->maxGraphs = mlayout->maxGraphs * 1.2 + 10;
mlayout->graphs = (Graph**) realloc(mlayout->graphs, sizeof(Graph*) * mlayout->maxGraphs);
assert(mlayout->graphs != NULL);
}
int nnodes = mlayout->graphs[mlayout->level]->curNodes;
if (octx->verbose > 1)
printf("coarsen graph level(%d)\n", mlayout->level);
Graph *tmpG = coarsenGraph(mlayout->graphs[mlayout->level], octx->verbose);
mlayout->level++;
mlayout->graphs[mlayout->level] = tmpG;
int nchildnodes = tmpG->curNodes;
#if DEBUG
printf("nnodes: %d, nchildnodes: %d c-rate: %f\n", nnodes, nchildnodes, mlayout->minCoarseningRate);
#endif
if (nchildnodes < mlayout->minSize || nchildnodes > nnodes * mlayout->minCoarseningRate)
break;
}
#if DEBUG
printf("stopped coarsening at level: %d, nnodes: %d\n", mlayout->level, mlayout->graphs[mlayout->level]->curNodes - 1);
#endif
// initially create random coordinates
{
Graph *startG = mlayout->graphs[mlayout->level];
double size = 1000.0;
srand((unsigned int) time(NULL));
int i;
for (i = 0; i < startG->curNodes; i++)
{
Node *a = startG->nodes + i;
if (!(a->flag & NODE_HAS_COORDINATES))
{
a->x = (float) (-size / 2 + size * ((double) rand() / (double) (RAND_MAX)));
a->y = (float) (-size / 2 + size * ((double) rand() / (double) (RAND_MAX)));
#if DEBUG
printf("random coordinates: n%d: %.3f, %.3f\n", a->id, a->x, a->y);
#endif
}
}
}
return mlayout;
}
static void resetYifanHuLayout(OgLayoutContext *octx, YifanHuLayout *yfhLayout)
{
yfhLayout->stepRatio = octx->stepRatio;
yfhLayout->relativeStrength = DEFAULT_RELATIVE_STRENGTH;
yfhLayout->optimalDistance = octx->optimalDistance;
yfhLayout->initialStep = octx->optimalDistance / 5;
yfhLayout->quadTreeMaxLevel = octx->quadTreeLevel;
yfhLayout->barnesHutTheta = octx->barnesHutTheta;
yfhLayout->adaptiveCooling = DEFAULT_ADAPTIVE_COOLING;
yfhLayout->convergenceThreshold = octx->convergenceThreshold;
//
// init algorithm
// todo check if forcevector of nodes is really initiallized with (0,0)
yfhLayout->progress = 0;
yfhLayout->converged = 0;
yfhLayout->step = yfhLayout->initialStep;
}
static void doYiFanHuLayout(OgLayoutContext *octx, MultiLevelLayout *mlayout)
{
YifanHuLayout yfhLayout;
QuadTree *tree = createQuadTree(octx->quadTreeLevel);
int i;
int curLevel = mlayout->level;
while (curLevel >= 0)
{
Graph *tmpGraph = mlayout->graphs[curLevel];
resetYifanHuLayout(octx, &yfhLayout);
#ifdef DEBUG
int counter = 0;
#endif
float bestEnergy = FLT_MAX;
while (!yfhLayout.converged)
{
#if DEBUG
printf("goAlgo: %d\n", counter++);
#endif
buildQuadTree(tree, tmpGraph);
#if DEBUG
printf("QUADDTREE: cMass (%.3f, %.3f) pos: (%.3f, %.3f)"
" isLeaf %d, eps: %.3f size: %.3f, maxLevel: %d\n", tree->centerMassX, tree->centerMassY, tree->posX, tree->posY, tree->isLeaf, tree->eps, tree->size, tree->maxLevel);
#endif
double electricEnergy = 0;
double springEnergy = 0;
// update node forces
ElectricalForce ef;
ef.theta = yfhLayout.barnesHutTheta;
ef.optimalDistance = yfhLayout.optimalDistance;
ef.relativeStrength = yfhLayout.relativeStrength;
float distance;
for (i = 0; i < tmpGraph->curNodes; i++)
{
Node *n = tmpGraph->nodes + i;
ForceVector *fv = calculateForce(&ef, n, tree);
if (fv)
{
#if DEBUG
printf("node %d forcevector %.3f, %.3f, barnesForce: %.3f, %.3f\n", n->id, n->f.x, n->f.y, fv->x, fv->y);
#endif
addForceVectorToForceVector(&(n->f), fv);
#if DEBUG
printf("apply nodeforce fv: %.3f, %.3f electEnergy: %.3f\n", n->f.x, n->f.y, getForceVectorEnergy(fv));
#endif
electricEnergy += getForceVectorEnergy(fv);
free(fv);
}
}
// update edge forces
SpringForce sf;
sf.optimalDistance = yfhLayout.optimalDistance;
for (i = 0; i < tmpGraph->curEdges; i++)
{
Edge *e = tmpGraph->edges + i;
if (e->source == e->target)
continue;
Node * n1 = tmpGraph->nodes + e->source;
Node * n2 = tmpGraph->nodes + e->target;
distance = getForceVectorDistanceToNode(n1, n2);
ForceVector* f = calculateSpringForce(&sf, n1, n2, distance);
#if DEBUG
printf("edge: %d - %d dist: %.3f, fv (%.3f, %.3f)(%.3f, %.3f) force: %.3f, %.3f\n", n1->id, n2->id, distance, n1->f.x, n1->f.y, n2->f.x, n2->f.y, f->x, f->y);
#endif
addForceVectorToForceVector(&(n1->f), f);
subtractForceVectorFromForceVector(&(n2->f), f);
#if DEBUG
printf("apply edge force: n%d: (%.3f, %.3f), n%d: (%.3f, %.3f)\n", n1->id, n1->f.x, n1->f.y, n2->id, n2->f.x, n2->f.y);
#endif
free(f);
}
// calculate energy and max force
yfhLayout.energy0 = yfhLayout.energy;
yfhLayout.energy = 0;
double maxForce = 1;
for (i = 0; i < tmpGraph->curNodes; i++)
{
Node *n = tmpGraph->nodes + i;
float norm = getForceVectorNorm(&(n->f));
#if DEBUG
printf("node: %d energy: %.3f\n", n->id, norm);
#endif
yfhLayout.energy += norm;
if (maxForce < norm)
maxForce = norm;
}
#if DEBUG
printf("maxForce: %.3f energy0: %.3f energy: %.3f\n", maxForce, yfhLayout.energy0, yfhLayout.energy);
printf("node displacement:\n");
#endif
// displacement on nodes
for (i = 0; i < tmpGraph->curNodes; i++)
{
Node *n = tmpGraph->nodes + i;
#if DEBUG
printf("n%d c:(%.3f %.3f) f(%.5f, %.5f) step(%.10f)->", n->id, n->x, n->y, n->f.x, n->f.y, yfhLayout.step);
#endif
n->f.x *= (1.0 / maxForce);
n->f.y *= (1.0 / maxForce);
n->x = (n->x) + (n->f.x * yfhLayout.step);
n->y = (n->y) + (n->f.y * yfhLayout.step);
#if DEBUG
printf(" nc(%.3f %.3f)\n", n->x, n->y);
#endif
}
// postAlgo
// 1. update step
if (yfhLayout.adaptiveCooling)
{
if (yfhLayout.energy < yfhLayout.energy0)
{
yfhLayout.progress++;
if (yfhLayout.progress >= 5)
{
yfhLayout.progress = 0;
yfhLayout.step /= yfhLayout.stepRatio;
}
else
{
yfhLayout.progress = 0;
yfhLayout.step *= yfhLayout.stepRatio;
}
}
}
else
{
yfhLayout.step *= yfhLayout.stepRatio;
}
// 2. is converged ??
if (fabs(yfhLayout.energy - yfhLayout.energy0) / yfhLayout.energy < yfhLayout.convergenceThreshold)
yfhLayout.converged = 1;
if (bestEnergy > yfhLayout.energy)
{
bestEnergy = yfhLayout.energy;
int j;
for (i = 0, j = 0; i < tmpGraph->curNodes; i++, j += 2)
{
Node *n = tmpGraph->nodes + i;
mlayout->bestCoordinateSet[j] = n->x;
mlayout->bestCoordinateSet[j + 1] = n->y;
}
}
springEnergy = yfhLayout.energy - electricEnergy;
if (octx->verbose > 1 && yfhLayout.converged)
{
printf("curLevel: %d of %d\n", mlayout->level-curLevel, mlayout->level);
printf("convergence: %.8f < %.8f\n", fabs(yfhLayout.energy - yfhLayout.energy0) / yfhLayout.energy, yfhLayout.convergenceThreshold);
printf("electric: %f spring: %f\n", electricEnergy, springEnergy);
printf("energy0: %.8f energy: %.8f\n", yfhLayout.energy0, yfhLayout.energy);
printf("bestEnergy found: %f diff: %f\n", bestEnergy, yfhLayout.energy - bestEnergy);
}
if (yfhLayout.converged && bestEnergy < yfhLayout.energy)
{
int j;
for (i = 0, j = 0; i < tmpGraph->curNodes; i++, j += 2)
{
Node *n = tmpGraph->nodes + i;
n->x = mlayout->bestCoordinateSet[j];
n->y = mlayout->bestCoordinateSet[j + 1];
}
}
// deleteQuadTree(tree, yfhLayout.quadTreeMaxLevel);
}
refineGraph(tmpGraph);
#if DEBUG
char blub[100];
sprintf(blub, "test_%d.dot", curLevel);
write_dot(tmpGraph, blub);
#endif
curLevel--;
}
free(tree);
}
int main(int argc, char* argv[])
{
OgLayoutContext octx;
if (parseOptions(&octx, argc, argv))
return 1;
if(octx.giformat != FORMAT_GRAPHML && octx.goformat == FORMAT_GRAPHML)
{
fprintf(stderr, "When output format graphml is chosen the input format must be graphml as well (for now :)\n");
exit(1);
}
// read graph
if (octx.giformat == FORMAT_GRAPHML)
{
if (!read_graphml(&octx))
{
fprintf(stderr, "error: failed to read %s\n", octx.path_graph_in);
exit(1);
}
}
else
{
if (!read_dot(&octx))
{
fprintf(stderr, "error: failed to read %s\n", octx.path_graph_in);
exit(1);
}
}
if (octx.verbose)
printf("parsed: %d nodes and %d edges\n", octx.graph->numNodes, octx.graph->numEdges);
if (octx.graph->numNodes < 3 || octx.graph->numEdges < 2)
{
fprintf(stderr, "WARNING: Graph too small for layouting. %d nodes, %d edges.\n", octx.graph->numNodes, octx.graph->numEdges);
exit(0);
}
// init first graph based on parsed OGnodes + OGedges
Graph *ig = createInitialGraph(&octx);
if (ig == NULL)
{
fprintf(stderr, "Unable to create initial Graph. Stopp!\n");
exit(1);
}
MultiLevelLayout *mlayout = NULL;
if (octx.skipLayout == 0)
{
// create YifanHu Multilayout and coarsen graphs
mlayout = initMultiLevelLayout(&octx, ig);
if (mlayout == NULL)
{
fprintf(stderr, "Unable to create MultiLevelLayout. Stopp!\n");
exit(1);
}
// do layout
doYiFanHuLayout(&octx, mlayout);
}
// write graph
if (octx.goformat == FORMAT_DOT)
write_dot(&octx, ig);
else if (octx.goformat == FORMAT_GRAPHML)
write_graphml(&octx, ig);
else
write_svg(&octx, ig);
// cleanup
free(octx.graph->edges);
free(octx.graph->nodes);
free(octx.graph->attrLookup);
free(octx.graph);
if (octx.skipLayout == 0)
{
int l = mlayout->level;
while (l >= 0)
{
deleteGraph(mlayout->graphs[l]);
l--;
}
free(mlayout->graphs);
free(mlayout);
}
else
deleteGraph(ig);
return 0;
}
|
MartinPippel/DAmar
|
lib/lasidx.c
|
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <limits.h>
#include <sys/param.h>
#include <unistd.h>
#include "lasidx.h"
#include "pass.h"
static char* lasidx_filename(const char* pathLas)
{
char* pathIdx = strdup(pathLas);
char* pathDot = rindex(pathIdx, '.');
if (pathDot == NULL || strlen(pathIdx) - (pathDot - pathIdx) != 4)
{
fprintf(stderr, "malformed filename %s\n", pathLas);
free(pathIdx);
return NULL;
}
strcpy(pathDot + 1, "idx");
return pathIdx;
}
static time_t file_mtime(const char* path)
{
struct stat attr;
stat(path, &attr);
return attr.st_mtime;
}
lasidx* lasidx_create(HITS_DB* db, const char* pathLas)
{
FILE* fileLas;
FILE* fileIdx;
if ( (fileLas = fopen(pathLas, "r")) == NULL )
{
fprintf(stderr, "failed to open %s\n", pathLas);
return NULL;
}
char* pathIdx = lasidx_filename(pathLas);
if ( (fileIdx = fopen(pathIdx, "w")) == NULL)
{
fprintf(stderr, "failed to open %s\n", pathIdx);
free(pathIdx);
return NULL;
}
printf("indexing %s\n", pathLas);
PassContext* pctx = pass_init(fileLas, NULL);
int tbytes = TBYTES( pctx->twidth );
int nreads = DB_NREADS(db);
lasidx* lasIndex = malloc(sizeof(lasidx) * ( nreads + 1) );
if ( lasIndex == NULL )
{
fprintf(stderr, "Cannot allocate index buffer if size: %d\n!", nreads+1);
exit(1);
}
bzero(lasIndex, sizeof(lasidx) * ( nreads + 1) );
Overlap ovl;
int a = -1;
while (!Read_Overlap(fileLas, &ovl))
{
if (a != ovl.aread)
{
off_t cur = ftello(fileLas) - ( sizeof(Overlap) - sizeof(void*) );
lasIndex[ ovl.aread ] = cur;
a = ovl.aread;
}
fseek(fileLas, tbytes * ovl.path.tlen, SEEK_CUR);
}
if (a != ovl.aread)
{
off_t cur = ftello(fileLas) - ( sizeof(Overlap) - sizeof(void*) );
lasIndex[ ovl.aread ] = cur;
}
long mtime = file_mtime(pathLas);
fwrite(&mtime, sizeof(long), 1, fileIdx);
uint64 left = 0;
uint64 right = nreads;
while ( lasIndex[left] == 0 )
{
left++;
}
while ( lasIndex[right] == 0 )
{
right--;
}
fwrite(&left, sizeof(uint64), 1, fileIdx);
fwrite(&right, sizeof(uint64), 1, fileIdx);
fwrite(lasIndex + left, sizeof(lasidx), right - left + 1, fileIdx);
fclose(fileIdx);
fclose(fileLas);
pass_free(pctx);
free(pathIdx);
return lasIndex;
}
lasidx* lasidx_load(HITS_DB* db, const char* pathLas, int create)
{
FILE* fileIdx;
char* pathIdx = lasidx_filename(pathLas);
if ( (fileIdx = fopen(pathIdx, "r")) == NULL)
{
if (create)
{
return lasidx_create(db, pathLas);
}
fprintf(stderr, "failed to open %s\n", pathIdx);
free(pathIdx);
return NULL;
}
long mtime = 0;
if ( fread(&mtime, sizeof(long), 1, fileIdx) != 1 )
{
fprintf(stderr, "failed to read index header\n");
return NULL;
}
if ( mtime != file_mtime(pathLas) )
{
printf("las file has been modified after index creation\n");
if (create)
{
return lasidx_create(db, pathLas);
}
return NULL;
}
uint64 left, right;
if( fread(&left, sizeof(uint64), 1, fileIdx) != 1 )
{
fprintf(stderr, "ERROR: failed to read left offset\n");
exit(1);
}
if ( fread(&right, sizeof(uint64), 1, fileIdx) != 1 )
{
fprintf(stderr, "ERROR: failed to read right offset\n");
exit(1);
}
int nreads = DB_NREADS(db);
lasidx* lasIndex = malloc(sizeof(lasidx) * ( nreads + 1) );
bzero(lasIndex, sizeof(lasidx) * (nreads + 1));
if ( fread(lasIndex + left, sizeof(lasidx), right - left + 1, fileIdx) != (size_t)( right - left + 1 ) )
{
fprintf(stderr, "index file too short\n");
return NULL;
}
off_t end = ftello(fileIdx);
fseeko(fileIdx, 0, SEEK_END);
if (end != ftello(fileIdx))
{
fprintf(stderr, "index file too long\n");
return NULL;
}
fclose(fileIdx);
free(pathIdx);
return lasIndex;
}
void lasidx_close(lasidx* idx)
{
free(idx);
}
|
MartinPippel/DAmar
|
dalign/filter.c
|
/************************************************************************************\
* *
* Copyright (c) 2014, Dr. <NAME> (EWM). All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without modification, *
* are permitted provided that the following conditions are met: *
* *
* · Redistributions of source code must retain the above copyright notice, this *
* list of conditions and the following disclaimer. *
* *
* · Redistributions in binary form must reproduce the above copyright notice, this *
* list of conditions and the following disclaimer in the documentation and/or *
* other materials provided with the distribution. *
* *
* · The name of EWM may not be used to endorse or promote products derived from *
* this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY EWM ”AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, *
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND *
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL EWM BE LIABLE *
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS *
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY *
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING *
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN *
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
* *
* For any issues regarding this software and its use, contact EWM at: *
* *
* <NAME>. *
* Bautzner Str. 122e *
* 01099 Dresden *
* GERMANY *
* Email: <EMAIL> *
* *
\************************************************************************************/
/*******************************************************************************************
*
* Fast local alignment filter for long, noisy reads based on "dumbing down" of my RECOMB 2005
* filter with <NAME>, and a "smarting up" of the k-mer matching by turning it into
* a threaded sort and merge paradigm using a super cache coherent radix sort. Local
* alignment is accomplised with dynamically-banded O(nd) algorithm that terminates when
* it fails to find a e-matching patch for a significant distance, and polishes the match
* to the last e-prefix-positive 32-mer.
*
* Author : <NAME>
* First : June 2013
* Current: June 1, 2014
*
********************************************************************************************/
// A complete threaded code for the filter
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <math.h>
#include <pthread.h>
#include "db/DB.h"
#include "filter.h"
#include "dalign/align.h"
#define THREAD pthread_t
#undef THREAD_OUTPUT
#define MAX_BIAS 2 // In -b mode, don't consider tuples with specificity
// <= 4 ^ -(kmer-MAX_BIAS)
#define MAXGRAM 10000 // Cap on k-mer count histogram (in count_thread, merge_thread)
#define PANEL_SIZE 50000 // Size to break up very long A-reads
#define PANEL_OVERLAP 10000 // Overlap of A-panels
#define MATCH_CHUNK 100 // Max expected number of hits between two reads
#define TRACE_CHUNK 20000 // Max expected trace points in hits between two reads
#undef TEST_LSORT
#undef TEST_KSORT
#undef TEST_PAIRS
#undef TEST_CSORT
#if defined (TEST_LSORT) || defined (TEST_KSORT) || defined (TEST_PAIRS) || defined (TEST_CSORT)
#define HOW_MANY 3000 // Print first HOW_MANY items for each of the TEST options above
#endif
#undef TEST_GATHER
#undef TEST_CONTAIN
#undef TEST_BRIDGE
#undef SHOW_OVERLAP // Show the cartoon
#undef SHOW_ALIGNMENT // Show the alignment
#if defined (SHOW_ALIGNMENT) || defined (SHOW_OVERLAP)
#define ALIGN_WIDTH 80 // Parameters for alignment
#define ALIGN_BORDER 10
#endif
#if defined (SHOW_OVERLAP)
#define ALIGN_INDENT 20
#endif
#ifdef SHOW_OVERLAP
#define NOTHREAD
#endif
#ifdef TEST_GATHER
#define NOTHREAD
#endif
#ifdef TEST_CONTAIN
#define NOTHREAD
#endif
typedef struct
{
uint64 p1; // The lower half
uint64 p2;
} Double;
#if __ORDER_LITTLE_ENDIAN__ == __BYTE_ORDER__
typedef struct
{
uint64 code;
int rpos;
int read;
} KmerPos;
typedef struct
{
int diag;
int apos;
int aread;
int bread;
} SeedPair;
#else
typedef struct
{ uint64 code;
int read;
int rpos;
}KmerPos;
typedef struct
{ int apos;
int diag;
int bread;
int aread;
}SeedPair;
#endif
/*******************************************************************************************
*
* PARAMETER SETUP
*
********************************************************************************************/
static int Kmer;
static int Hitmin;
static int Binshift;
static int Suppress;
static int Kshift; // 2*Kmer
static uint64 Kmask; // 4^Kmer-1
static int TooFrequent; // (Suppress != 0) ? Suppress : INT32_MAX
static int NTHREADS; // Adjusted downward to nearest power of 2
static int NSHIFT; // NTHREADS = 1 << NSHIFT
int Set_Filter_Params(int kmer, int binshift, int suppress, int hitmin, int nthreads)
{
if (kmer <= 1)
return (1);
Kmer = kmer;
Binshift = binshift;
Suppress = suppress;
Hitmin = hitmin;
Kshift = 2 * Kmer;
if (Kmer == 32)
Kmask = 0xffffffffffffffffllu;
else
Kmask = (0x1llu << Kshift) - 1;
if (Suppress == 0)
TooFrequent = INT32_MAX;
else
TooFrequent = Suppress;
NTHREADS = 1;
NSHIFT = 0;
while (2 * NTHREADS <= nthreads)
{
NTHREADS *= 2;
NSHIFT += 1;
}
return (0);
}
/*******************************************************************************************
*
* LEXICOGRAPHIC SORT
*
********************************************************************************************/
#define BMER 4
#define BSHIFT 8 // = 2*BMER
#define BPOWR 256 // = 2^BSHIFT
#define BMASK 0xffllu // = BPOWR-1
static uint64 QMASK; // = BMASK << NSHIFT
static int LEX_shift;
static int64 LEX_zsize;
static int LEX_last;
static int LEX_next;
static Double *LEX_src;
static Double *LEX_trg;
typedef struct
{
int64 beg;
int64 end;
int64 tptr[BPOWR];
int64 *sptr;
} Lex_Arg;
static void *lex_thread(void *arg)
{
Lex_Arg *data = (Lex_Arg *) arg;
int64 *sptr = data->sptr;
int64 *tptr = data->tptr;
int shift = LEX_shift; // Must be a multiple of 8 in [0,120]
int qshift = (LEX_next - LEX_shift) - NSHIFT;
int64 zsize = LEX_zsize;
Double *src = LEX_src;
Double *trg = LEX_trg;
int64 i, n, x;
uint64 c, b;
n = data->end;
if (shift >= 64)
{
shift -= 64;
if (LEX_last)
for (i = data->beg; i < n; i++)
{
c = src[i].p2;
b = (c >> shift);
x = tptr[b & BMASK]++;
trg[x] = src[i];
}
else
for (i = data->beg; i < n; i++)
{
c = src[i].p2;
b = (c >> shift);
x = tptr[b & BMASK]++;
trg[x] = src[i];
sptr[((b >> qshift) & QMASK) + x / zsize] += 1;
}
}
else if (!LEX_last && LEX_next >= 64) // && LEX_shift < 64
{
qshift = (LEX_next - 64) - NSHIFT;
if (qshift < 0)
for (i = data->beg; i < n; i++)
{
c = src[i].p1;
b = (c >> shift);
x = tptr[b & BMASK]++;
trg[x] = src[i];
sptr[((src[i].p2 << NSHIFT) & QMASK) + x / zsize] += 1;
}
else
for (i = data->beg; i < n; i++)
{
c = src[i].p1;
b = (c >> shift);
x = tptr[b & BMASK]++;
trg[x] = src[i];
sptr[((src[i].p2 >> qshift) & QMASK) + x / zsize] += 1;
}
}
else // LEX_last || LEX_next < 64
if (LEX_last)
if (shift == 0)
for (i = data->beg; i < n; i++)
{
c = src[i].p1;
x = tptr[c & BMASK]++;
trg[x] = src[i];
}
else
for (i = data->beg; i < n; i++)
{
c = src[i].p1;
b = (c >> shift);
x = tptr[b & BMASK]++;
trg[x] = src[i];
}
else if (shift == 0)
for (i = data->beg; i < n; i++)
{
c = src[i].p1;
x = tptr[c & BMASK]++;
trg[x] = src[i];
sptr[((c >> qshift) & QMASK) + x / zsize] += 1;
}
else
for (i = data->beg; i < n; i++)
{
c = src[i].p1;
b = (c >> shift);
x = tptr[b & BMASK]++;
trg[x] = src[i];
sptr[((b >> qshift) & QMASK) + x / zsize] += 1;
}
return (NULL);
}
static Double *lex_sort(int bytes[16], Double *src, Double *trg, Lex_Arg *parmx)
{
THREAD threads[NTHREADS];
int64 len, x, y;
Double *xch;
int i, j, k, z;
int b, c, fb;
len = parmx[NTHREADS - 1].end;
LEX_zsize = (len - 1) / NTHREADS + 1;
LEX_src = src;
LEX_trg = trg;
QMASK = (BMASK << NSHIFT);
for (c = 0; c < 16; c++)
if (bytes[c])
break;
fb = c;
for (b = c; b < 16; b = c)
{
for (c = b + 1; c < 16; c++)
if (bytes[c])
break;
LEX_last = (c >= 16);
LEX_shift = (b << 3);
LEX_next = (c << 3);
if (b == fb)
{
for (i = 0; i < NTHREADS; i++)
for (z = 0; z < NTHREADS * BPOWR; z++)
parmx[i].sptr[z] = 0;
}
else
{
x = 0;
for (i = 0; i < NTHREADS; i++)
{
parmx[i].beg = x;
parmx[i].end = x = LEX_zsize * (i + 1);
for (j = 0; j < BPOWR; j++)
parmx[i].tptr[j] = 0;
}
parmx[NTHREADS - 1].end = len;
for (j = 0; j < BPOWR; j++)
{
k = (j << NSHIFT);
for (z = 0; z < NTHREADS; z++)
for (i = 0; i < NTHREADS; i++)
{
parmx[i].tptr[j] += parmx[z].sptr[k + i];
parmx[z].sptr[k + i] = 0;
}
}
}
x = 0;
for (j = 0; j < BPOWR; j++)
for (i = 0; i < NTHREADS; i++)
{
y = parmx[i].tptr[j];
parmx[i].tptr[j] = x;
x += y;
}
for (i = 0; i < NTHREADS; i++)
pthread_create(threads + i, NULL, lex_thread, parmx + i);
for (i = 0; i < NTHREADS; i++)
pthread_join(threads[i], NULL);
xch = LEX_src;
LEX_src = LEX_trg;
LEX_trg = xch;
#ifdef TEST_LSORT
printf("\nLSORT %d\n",LEX_shift);
if (LEX_shift >= 64)
{ x = (1 << ((LEX_shift-64)+BSHIFT))-1;
for (i = 0; i < len; i++)
{ printf("%6d: %8llx %8llx %8llx %8llx : %4llx",
i,LEX_src[i].p2>>32,(LEX_src[i].p2)&0xffffffffll,LEX_src[i].p1>>32,
LEX_src[i].p1&0xffffffffll,LEX_src[i].p2&x);
if (i > 0 && (LEX_src[i].p1 < LEX_src[i].p1 ||
(LEX_src[i].p1 == LEX_src[i].p1 &&
(LEX_src[i].p2 & x) < (LEX_src[i-1].p2 & x))))
printf(" OO");
printf("\n");
}
}
else
{ x = (1 << (LEX_shift+BSHIFT))-1;
for (i = 0; i < len; i++)
{ printf("%6d: %8llx %8llx %8llx %8llx : %4llx",
i,LEX_src[i].p2>>32,(LEX_src[i].p2)&0xffffffffll,LEX_src[i].p1>>32,
LEX_src[i].p1&0xffffffffll,LEX_src[i].p1&x);
if (i > 0 && (LEX_src[i].p1 & x) < (LEX_src[i-1].p1 & x))
printf(" OO");
printf("\n");
}
}
#endif
}
return (LEX_src);
}
/*******************************************************************************************
*
* INDEX BUILD
*
********************************************************************************************/
static int *NormShift = NULL;
static int LogNorm, LogThresh;
static int LogBase[4];
static HITS_DB *TA_block;
static KmerPos *TA_list;
static HITS_TRACK *TA_track;
typedef struct
{
int tnum;
int64 *kptr;
int fill;
} Tuple_Arg;
static void *tuple_thread(void *arg)
{
Tuple_Arg *data = (Tuple_Arg *) arg;
int tnum = data->tnum;
int64 *kptr = data->kptr;
KmerPos *list = TA_list;
int i, m, n, x, p;
uint64 c;
char *s;
c = TA_block->nreads;
i = (c * tnum) >> NSHIFT;
n = TA_block->reads[i].boff;
s = ((char *) (TA_block->bases)) + n;
n -= Kmer * i;
if (TA_track != NULL)
{
HITS_READ *reads = TA_block->reads;
int64 *anno1 = ((int64 *) (TA_track->anno)) + 1;
int *point = (int *) (TA_track->data);
int64 a, b, f;
int q = 0;
f = anno1[i - 1];
for (m = (c * (tnum + 1)) >> NSHIFT; i < m; i++)
{
b = f;
f = anno1[i];
for (a = b; a <= f; a += 2)
{
if (a == b)
p = 0;
else
p = point[a - 1];
if (a == f)
q = reads[i].rlen;
else
q = point[a];
if (p + Kmer <= q)
{
c = 0;
for (x = 1; x < Kmer; x++)
c = (c << 2) | s[p++];
while (p < q)
{
x = s[p];
c = ((c << 2) | x) & Kmask;
list[n].read = i;
list[n].rpos = p++;
list[n].code = c;
n += 1;
kptr[c & BMASK] += 1;
}
}
}
s += (q + 1);
}
m = TA_block->reads[m].boff - Kmer * m;
kptr[BMASK] += (data->fill = m - n);
while (n < m)
{
list[n].code = 0xffffffffffffffffllu;
list[n].read = -1;
list[n].rpos = -1;
n += 1;
}
}
else
for (m = (c * (tnum + 1)) >> NSHIFT; i < m; i++)
{
c = p = 0;
for (x = 1; x < Kmer; x++)
c = (c << 2) | s[p++];
while ((x = s[p]) != 4)
{
c = ((c << 2) | x) & Kmask;
list[n].read = i;
list[n].rpos = p++;
list[n].code = c;
n += 1;
kptr[c & BMASK] += 1;
}
s += (p + 1);
}
return (NULL);
}
static void *biased_tuple_thread(void *arg)
{
Tuple_Arg *data = (Tuple_Arg *) arg;
int tnum = data->tnum;
int64 *kptr = data->kptr;
KmerPos *list = TA_list;
int n, i, m;
int x, a, k, p;
uint64 d, c;
char *s, *t;
c = TA_block->nreads;
i = (c * tnum) >> NSHIFT;
n = TA_block->reads[i].boff;
s = ((char *) (TA_block->bases)) + n;
n -= Kmer * i;
if (TA_track != NULL)
{
HITS_READ *reads = TA_block->reads;
int64 *anno1 = ((int64 *) (TA_track->anno)) + 1;
int *point = (int *) (TA_track->data);
int64 j, b, f;
int q = 0;
f = anno1[i - 1];
for (m = (c * (tnum + 1)) >> NSHIFT; i < m; i++)
{
b = f;
f = anno1[i];
t = s + 1;
for (j = b; j <= f; j += 2)
{
if (j == b)
p = 0;
else
p = point[j - 1];
if (j == f)
q = reads[i].rlen;
else
q = point[j];
if (p + Kmer <= q)
{
c = 0;
a = 0;
k = 1;
while (p < q)
{
x = s[p];
a += LogBase[x];
c = ((c << 2) | x);
while (a < LogNorm && k < Kmer)
{
if (++p >= q)
break;
k += 1;
x = s[p];
a += LogBase[x];
c = ((c << 2) | x);
}
while (1)
{
int u = a - LogBase[(int) t[p - k]];
if (u < LogNorm)
break;
a = u;
k -= 1;
}
if (a > LogThresh)
{
d = ((c << NormShift[k]) & Kmask);
list[n].read = i;
list[n].rpos = p;
list[n].code = d;
n += 1;
kptr[d & BMASK] += 1;
}
p += 1;
a -= LogBase[(int) s[p - k]];
}
}
}
s += (q + 1);
}
}
else
for (m = (c * (tnum + 1)) >> NSHIFT; i < m; i++)
{
t = s + 1;
c = 0;
p = a = 0;
k = 1;
while ((x = s[p]) != 4)
{
a += LogBase[x];
c = ((c << 2) | x);
while (a < LogNorm && k < Kmer)
{
if ((x = s[++p]) == 4)
goto eoread2;
k += 1;
a += LogBase[x];
c = ((c << 2) | x);
}
while (1)
{
int u = a - LogBase[(int) t[p - k]];
if (u < LogNorm)
break;
a = u;
k -= 1;
}
if (a > LogThresh)
{
d = ((c << NormShift[k]) & Kmask);
list[n].read = i;
list[n].rpos = p;
list[n].code = d;
n += 1;
kptr[d & BMASK] += 1;
}
p += 1;
a -= LogBase[(int) s[p - k]];
}
eoread2: s += (p + 1);
}
m = TA_block->reads[m].boff - Kmer * m;
kptr[BMASK] += (data->fill = m - n);
while (n < m)
{
list[n].code = 0xffffffffffffffffllu;
list[n].read = -1;
list[n].rpos = -1;
n += 1;
}
return (NULL);
}
static KmerPos *FR_src;
static KmerPos *FR_trg;
typedef struct
{
int beg;
int end;
int kept;
} Comp_Arg;
static void *compsize_thread(void *arg)
{
Comp_Arg *data = (Comp_Arg *) arg;
int end = data->end;
KmerPos *src = FR_src;
int n, i, c, p;
uint64 h, g;
i = data->beg;
h = src[i].code;
n = 0;
while (i < end)
{
p = i++;
while ((g = src[i].code) == h)
i += 1;
if ((c = (i - p)) < TooFrequent)
n += c;
h = g;
}
data->kept = n;
return (NULL);
}
static void *compress_thread(void *arg)
{
Comp_Arg *data = (Comp_Arg *) arg;
int end = data->end;
KmerPos *src = FR_src;
KmerPos *trg = FR_trg;
int n, i, p;
uint64 h, g;
i = data->beg;
h = src[i].code;
n = data->kept;
while (i < end)
{
p = i++;
while ((g = src[i].code) == h)
i += 1;
if (i - p < TooFrequent)
{
while (p < i)
trg[n++] = src[p++];
}
h = g;
}
return (NULL);
}
void *Sort_Kmers(HITS_DB *block, int *len)
{
THREAD threads[NTHREADS];
Tuple_Arg parmt[NTHREADS];
Comp_Arg parmf[NTHREADS];
Lex_Arg parmx[NTHREADS];
int mersort[16];
KmerPos *src, *trg, *rez;
int kmers, nreads;
int i, j, x, z;
uint64 h;
for (i = 0; i < NTHREADS; i++)
parmx[i].sptr = (int64 *) alloca(NTHREADS * BPOWR * sizeof(int64));
for (i = 0; i < 16; i++)
mersort[i] = 0;
for (i = 0; i < Kshift; i += 8)
mersort[i >> 3] = 1;
if (NormShift == NULL && BIASED)
{
double scale;
NormShift = (int *) Malloc(sizeof(int) * (Kmer + 1), "Allocating Sort_Kmers bias shift");
if (NormShift == NULL)
exit(1);
for (i = 0; i <= Kmer; i++)
NormShift[i] = Kshift - 2 * i;
LogNorm = 10000 * Kmer;
LogThresh = 10000 * (Kmer - MAX_BIAS);
scale = -10000. / log(4.);
for (i = 0; i < 4; i++)
LogBase[i] = (int) ceil(scale * log(block->freq[i]));
}
nreads = block->nreads;
kmers = block->reads[nreads].boff - Kmer * nreads;
if (block->reads[nreads].boff > 0x7fffffffll)
{
fprintf(stderr, "%s: Fatal error, DB blocks are greater than 2Gbp!\n", Prog_Name);
exit(1);
}
if (kmers <= 0)
goto no_mers;
if (((Kshift - 1) / BSHIFT + (TooFrequent < INT32_MAX)) & 0x1)
{
trg = (KmerPos *) Malloc(sizeof(KmerPos) * (kmers + 2), "Allocating Sort_Kmers vectors");
src = (KmerPos *) Malloc(sizeof(KmerPos) * (kmers + 2), "Allocating Sort_Kmers vectors");
}
else
{
src = (KmerPos *) Malloc(sizeof(KmerPos) * (kmers + 2), "Allocating Sort_Kmers vectors");
trg = (KmerPos *) Malloc(sizeof(KmerPos) * (kmers + 2), "Allocating Sort_Kmers vectors");
}
if (src == NULL || trg == NULL)
exit(1);
if (VERBOSE)
{
printf("\n Kmer count = ");
Print_Number((int64) kmers, 0, stdout);
printf("\n Using %.2fGb of space\n", (1. * kmers) / 33554432);
fflush(stdout);
}
TA_block = block;
TA_list = src;
TA_track = block->tracks;
for (i = 0; i < NTHREADS; i++)
{
parmt[i].tnum = i;
parmt[i].kptr = parmx[i].tptr;
for (j = 0; j < BPOWR; j++)
parmt[i].kptr[j] = 0;
}
if (BIASED)
for (i = 0; i < NTHREADS; i++)
pthread_create(threads + i, NULL, biased_tuple_thread, parmt + i);
else
for (i = 0; i < NTHREADS; i++)
pthread_create(threads + i, NULL, tuple_thread, parmt + i);
for (i = 0; i < NTHREADS; i++)
pthread_join(threads[i], NULL);
x = 0;
for (i = 0; i < NTHREADS; i++)
{
parmx[i].beg = x;
j = (int) ((((int64) nreads) * (i + 1)) >> NSHIFT);
parmx[i].end = x = block->reads[j].boff - j * Kmer;
}
rez = (KmerPos *) lex_sort(mersort, (Double *) src, (Double *) trg, parmx);
if (BIASED || TA_track != NULL)
{
if (Kmer % 4 == 0)
{
int wedge[NTHREADS];
for (j = 0; j < NTHREADS; j++)
if (parmt[j].fill > 0)
break;
j += 1;
if (j < NTHREADS)
{
x = kmers - 1;
for (i = NTHREADS - 1; i >= j; i--)
{
x = x - parmt[i].fill;
z = x;
while (rez[x].read >= 0)
x -= 1;
wedge[i] = z - x;
}
x += 1;
z = x - parmt[j - 1].fill;
for (i = j; i < NTHREADS; i++)
{
memmove(rez + z, rez + x, wedge[i] * sizeof(KmerPos));
x += wedge[i] + parmt[i].fill;
z += wedge[i];
}
}
}
for (i = 0; i < NTHREADS; i++)
kmers -= parmt[i].fill;
}
if (TooFrequent < INT32_MAX && kmers > 0)
{
parmf[0].beg = 0;
for (i = 1; i < NTHREADS; i++)
{
x = (((int64) i) * kmers) >> NSHIFT;
h = rez[x - 1].code;
while (rez[x].code == h)
x += 1;
parmf[i - 1].end = parmf[i].beg = x;
}
parmf[NTHREADS - 1].end = kmers;
if (rez[kmers - 1].code == 0xffffffffffffffffllu)
rez[kmers].code = 0;
else
rez[kmers].code = 0xffffffffffffffffllu;
if (src == rez)
{
FR_src = src;
FR_trg = rez = trg;
}
else
{
FR_src = trg;
FR_trg = rez = src;
}
for (i = 0; i < NTHREADS; i++)
pthread_create(threads + i, NULL, compsize_thread, parmf + i);
for (i = 0; i < NTHREADS; i++)
pthread_join(threads[i], NULL);
x = 0;
for (i = 0; i < NTHREADS; i++)
{
z = parmf[i].kept;
parmf[i].kept = x;
x += z;
}
kmers = x;
for (i = 0; i < NTHREADS; i++)
pthread_create(threads + i, NULL, compress_thread, parmf + i);
for (i = 0; i < NTHREADS; i++)
pthread_join(threads[i], NULL);
}
rez[kmers].code = 0xffffffffffffffffllu;
rez[kmers + 1].code = 0;
if (src != rez)
free(src);
else
free(trg);
#ifdef TEST_KSORT
{ int i;
printf("\nKMER SORT:\n");
for (i = 0; i < HOW_MANY && i < kmers; i++)
{ KmerPos *c = rez+i;
printf(" %9d: %6d / %6d / %16llx\n",i,c->read,c->rpos,c->code);
}
fflush(stdout);
}
#endif
if (VERBOSE)
{
if (TooFrequent < INT32_MAX || BIASED || TA_track != NULL)
{
printf(" Revised kmer count = ");
Print_Number((int64) kmers, 0, stdout);
printf("\n");
}
printf(" Index occupies %.2fGb\n", (1. * kmers) / 67108864);
fflush(stdout);
}
if (kmers <= 0)
{
free(rez);
goto no_mers;
}
if (kmers > (int64) (MEM_LIMIT / (4 * sizeof(KmerPos))))
{
fprintf(stderr, "Warning: Block size too big, index occupies more than 1/4 of");
if (MEM_LIMIT == MEM_PHYSICAL)
fprintf(stderr, " physical memory (%.1fGb)\n", (1. * MEM_LIMIT) / 0x40000000ll);
else
fprintf(stderr, " desired memory allocation (%.1fGb)\n", (1. * MEM_LIMIT) / 0x40000000ll);
fflush(stderr);
}
*len = kmers;
return (rez);
no_mers: *len = 0;
return (NULL);
}
/*******************************************************************************************
*
* FILTER MATCH
*
********************************************************************************************/
static int find_tuple(uint64 x, KmerPos *a, int n)
{
int l, r, m;
// smallest k s.t. a[k].code >= x (or n if does not exist)
l = 0;
r = n;
while (l < r)
{
m = ((l + r) >> 1);
if (a[m].code < x)
l = m + 1;
else
r = m;
}
return (l);
}
// Determine what *will* be the size of the merged list and histogram of sizes for given cutoffs
static KmerPos *MG_alist;
static KmerPos *MG_blist;
static SeedPair *MG_hits;
static int MG_comp;
static int MG_self;
typedef struct
{
int abeg, aend;
int bbeg, bend;
int64 *kptr;
int64 nhits;
int limit;
int64 hitgram[MAXGRAM];
} Merge_Arg;
static void *count_thread(void *arg)
{
Merge_Arg *data = (Merge_Arg *) arg;
KmerPos *asort = MG_alist;
KmerPos *bsort = MG_blist;
int64 *gram = data->hitgram;
int64 nhits = 0;
int aend = data->aend;
int64 ct;
int ia, ib;
int jb, ja;
uint64 ca, cb;
uint64 da, db;
int ar, ap;
int a, b;
ia = data->abeg;
ca = asort[ia].code;
ib = data->bbeg;
cb = bsort[ib].code;
if (MG_self)
{
while (1)
{
while (cb < ca)
cb = bsort[++ib].code;
while (cb > ca)
ca = asort[++ia].code;
if (cb == ca)
{
ja = ia++;
while ((da = asort[ia].code) == ca)
ia += 1;
jb = ib++;
while ((db = bsort[ib].code) == cb)
ib += 1;
if (ia > aend)
{
if (ja >= aend)
break;
da = asort[ia = aend].code;
db = bsort[ib = data->bend].code;
}
ct = 0;
b = jb;
if (IDENTITY)
for (a = ja; a < ia; a++)
{
ar = asort[a].read;
if (MG_comp)
{
while (b < ib && bsort[b].read <= ar)
b += 1;
}
else
{
ap = asort[a].rpos;
while (b < ib && bsort[b].read < ar)
b += 1;
while (b < ib && bsort[b].read == ar && bsort[b].rpos < ap)
b += 1;
}
ct += (b - jb);
}
else
for (a = ja; a < ia; a++)
{
ar = asort[a].read;
while (b < ib && bsort[b].read < ar)
b += 1;
ct += (b - jb);
}
nhits += ct;
ca = da;
cb = db;
if (ct < MAXGRAM)
gram[ct] += 1;
}
}
}
else
{
while (1)
{
while (cb < ca)
cb = bsort[++ib].code;
while (cb > ca)
ca = asort[++ia].code;
if (cb == ca)
{
ja = ia++;
while ((da = asort[ia].code) == ca)
ia += 1;
jb = ib++;
while ((db = bsort[ib].code) == cb)
ib += 1;
if (ia > aend)
{
if (ja >= aend)
break;
da = asort[ia = aend].code;
db = bsort[ib = data->bend].code;
}
ct = (ia - ja);
ct *= (ib - jb);
nhits += ct;
ca = da;
cb = db;
if (ct < MAXGRAM)
gram[ct] += 1;
}
}
}
data->nhits = nhits;
return (NULL);
}
// Produce the merged list now that the list has been allocated and
// the appropriate cutoff determined.
static void *merge_thread(void *arg)
{
Merge_Arg *data = (Merge_Arg *) arg;
int64 *kptr = data->kptr;
KmerPos *asort = MG_alist;
KmerPos *bsort = MG_blist;
SeedPair *hits = MG_hits;
int64 nhits = data->nhits;
int aend = data->aend;
int limit = data->limit;
int64 ct;
int ia, ib;
int jb, ja;
uint64 ca, cb;
uint64 da, db;
int ar, ap;
int a, b, c;
ia = data->abeg;
ca = asort[ia].code;
ib = data->bbeg;
cb = bsort[ib].code;
if (MG_self)
{
while (1)
{
while (cb < ca)
cb = bsort[++ib].code;
while (cb > ca)
ca = asort[++ia].code;
if (cb == ca)
{
ja = ia++;
while ((da = asort[ia].code) == ca)
ia += 1;
jb = ib++;
while ((db = bsort[ib].code) == cb)
ib += 1;
if (ia > aend)
{
if (ja >= aend)
break;
da = asort[ia = aend].code;
db = bsort[ib = data->bend].code;
}
ct = 0;
b = jb;
if (IDENTITY)
for (a = ja; a < ia; a++)
{
ar = asort[a].read;
if (MG_comp)
{
while (b < ib && bsort[b].read <= ar)
b += 1;
}
else
{
ap = asort[a].rpos;
while (b < ib && bsort[b].read < ar)
b += 1;
while (b < ib && bsort[b].read == ar && bsort[b].rpos < ap)
b += 1;
}
ct += (b - jb);
}
else
for (a = ja; a < ia; a++)
{
ar = asort[a].read;
while (b < ib && bsort[b].read < ar)
b += 1;
ct += (b - jb);
}
if (ct < limit)
{
b = jb;
if (IDENTITY)
for (a = ja; a < ia; a++)
{
ap = asort[a].rpos;
ar = asort[a].read;
if (MG_comp)
{
while (b < ib && bsort[b].read <= ar)
b += 1;
}
else
{
while (b < ib && bsort[b].read < ar)
b += 1;
while (b < ib && bsort[b].read == ar && bsort[b].rpos < ap)
b += 1;
}
if ((ct = b - jb) > 0)
{
kptr[ap & BMASK] += ct;
for (c = jb; c < b; c++)
{
hits[nhits].bread = bsort[c].read;
hits[nhits].aread = ar;
hits[nhits].apos = ap;
hits[nhits].diag = ap - bsort[c].rpos;
nhits += 1;
}
}
}
else
for (a = ja; a < ia; a++)
{
ap = asort[a].rpos;
ar = asort[a].read;
while (b < ib && bsort[b].read < ar)
b += 1;
if ((ct = b - jb) > 0)
{
kptr[ap & BMASK] += ct;
for (c = jb; c < b; c++)
{
hits[nhits].bread = bsort[c].read;
hits[nhits].aread = ar;
hits[nhits].apos = ap;
hits[nhits].diag = ap - bsort[c].rpos;
nhits += 1;
}
}
}
}
ca = da;
cb = db;
}
}
}
else
{
while (1)
{
while (cb < ca)
cb = bsort[++ib].code;
while (cb > ca)
ca = asort[++ia].code;
if (cb == ca)
{
if (ia >= aend)
break;
ja = ia++;
while ((da = asort[ia].code) == ca)
ia += 1;
jb = ib++;
while ((db = bsort[ib].code) == cb)
ib += 1;
if (ia > aend)
{
if (ja >= aend)
break;
da = asort[ia = aend].code;
db = bsort[ib = data->bend].code;
}
ct = ib - jb;
if ((ia - ja) * ct < limit)
{
for (a = ja; a < ia; a++)
{
ap = asort[a].rpos;
kptr[ap & BMASK] += ct;
for (b = jb; b < ib; b++)
{
hits[nhits].bread = bsort[b].read;
hits[nhits].aread = asort[a].read;
hits[nhits].apos = ap;
hits[nhits].diag = ap - bsort[b].rpos;
nhits += 1;
}
}
}
ca = da;
cb = db;
}
}
}
return (NULL);
}
// Report threads: given a segment of merged list, find all seeds and from them all alignments.
static HITS_DB *MR_ablock;
static HITS_DB *MR_bblock;
static SeedPair *MR_hits;
static int MR_two;
static Align_Spec *MR_spec;
static int MR_tspace;
typedef struct
{
uint64 max;
uint64 top;
uint16 *trace;
} Trace_Buffer;
static inline int MapToTPAbove(Path *path, int *x, int isA, Trace_Buffer *tbuf)
{ uint16 *trace = tbuf->trace + (uint64) path->trace;
int a, b, i;
a = (path->abpos / MR_tspace) * MR_tspace;
b = path->bbpos;
for (i = 1; i < path->tlen; i += 2)
{ a += MR_tspace;
b += trace[i];
if (a > path->aepos)
a = path->aepos;
if (isA)
{ if (a >= *x)
{ *x = a;
return (b);
}
}
else
{ if (b >= *x)
{ *x = b;
return (a);
}
}
}
if (isA)
{ *x = a;
return (b);
}
else
{ *x = b;
return (a);
}
}
static inline int MapToTPBelow(Path *path, int *x, int isA, Trace_Buffer *tbuf)
{ uint16 *trace = tbuf->trace + (uint64) path->trace;
int a, b, i;
a = ((path->aepos + (MR_tspace-1)) / MR_tspace) * MR_tspace;
b = path->bepos;
for (i = path->tlen-1; i >= 0; i -= 2)
{ a -= MR_tspace;
b -= trace[i];
if (a < path->abpos)
a = path->abpos;
if (isA)
{ if (a <= *x)
{ *x = a;
return (b);
}
}
else
{ if (b <= *x)
{ *x = b;
return (a);
}
}
}
if (isA)
{ *x = a;
return (b);
}
else
{ *x = b;
return (a);
}
}
static int Check_Bridge(Path *path)
{ uint16 *trace = (uint16 *) path->trace;
int i;
if (MR_tspace <= TRACE_XOVR)
{ for (i = 0; i < path->tlen; i++)
if (trace[i] > 250)
return (1);
}
return (0);
}
static void Compute_Bridge_Path(Path *path1, Path *path2, Alignment *align, int comp,
int aovl, int bovl, Work_Data *work, Trace_Buffer *tbuf)
{ Path *apath;
int ain, aout;
int bin, bout, boff;
int err;
int i, j, p;
uint16 *trk;
apath = align->path;
if (bovl > aovl)
{ bin = path2->bbpos;
bout = path1->bepos;
ain = MapToTPBelow(path1,&bin,0,tbuf);
aout = MapToTPAbove(path2,&bout,0,tbuf);
}
else
{ ain = path2->abpos;
aout = path1->aepos;
bin = MapToTPBelow(path1,&ain,1,tbuf);
bout = MapToTPAbove(path2,&aout,1,tbuf);
}
#ifdef TEST_BRIDGE
printf("\n Tangle [%5d..%5d] vs [%5d..%5d] %4d\n",
path1->abpos,path1->aepos,path2->abpos,path2->aepos,abs(aovl-bovl));
printf(" [%5d..%5d] vs [%5d..%5d] %4d vs %4d\n",
path1->bbpos,path1->bepos,path2->bbpos,path2->bepos,aovl,bovl);
printf(" (%d,%d) to (%d,%d)\n",ain,bin,aout,bout);
#endif
apath->abpos = ain - 2*MR_tspace;
apath->aepos = aout + 2*MR_tspace;
apath->bbpos = MapToTPBelow(path1,&(apath->abpos),1,tbuf);
apath->bepos = MapToTPAbove(path2,&(apath->aepos),1,tbuf);
if (comp)
{ boff = MR_tspace - apath->aepos % MR_tspace;
p = align->alen - apath->abpos;
apath->abpos = align->alen - apath->aepos;
apath->aepos = p;
p = align->blen - apath->bbpos;
apath->bbpos = align->blen - apath->bepos;
apath->bepos = p;
boff = boff - apath->abpos % MR_tspace;
align->aseq -= boff;
apath->abpos += boff;
apath->aepos += boff;
align->alen += boff;
}
#ifdef TEST_BRIDGE
printf("\n (%d,%d) to (%d,%d)\n",apath->abpos,apath->bbpos,apath->aepos,apath->bepos);
fflush(stdout);
Compute_Alignment(align,work,DIFF_ALIGN,0);
Print_Reference(stdout,align,work,8,100,10,0,6);
fflush(stdout);
#endif
Compute_Alignment(align,work,DIFF_TRACE,MR_tspace);
trk = (uint16 *) apath->trace;
if (comp)
{ j = apath->tlen-2;
i = 0;
while (i < j)
{ p = trk[i];
trk[i] = trk[j];
trk[j] = p;
p = trk[i+1];
trk[i+1] = trk[j+1];
trk[j+1] = p;
i += 2;
j -= 2;
}
align->aseq += boff;
apath->abpos -= boff;
apath->aepos -= boff;
align->alen -= boff;
p = align->alen - apath->abpos;
apath->abpos = align->alen - apath->aepos;
apath->aepos = p;
p = align->blen - apath->bbpos;
apath->bbpos = align->blen - apath->bepos;
apath->bepos = p;
}
bin = apath->bbpos;
bout = apath->bepos;
err = apath->diffs;
p = 2*(ain / MR_tspace - apath->abpos / MR_tspace);
for (i = 0; i < p; i += 2)
{ bin += trk[i+1];
err -= trk[i];
}
p = 2*(apath->aepos / MR_tspace - aout / MR_tspace);
for (i = align->path->tlen, p = i-p; i > p; i -= 2)
{ bout -= trk[i-1];
err -= trk[i-2];
}
#ifdef TEST_BRIDGE
printf(" (%d,%d) to (%d,%d)\n",ain,bin,aout,bout);
printf(" Box %d vs %d -> %d %d%%\n",aout-ain,bout-bin,err,
(200*err)/((aout-ain)+(bout-bin)));
fflush(stdout);
#endif
}
static int Entwine(Path *jpath, Path *kpath, Trace_Buffer *tbuf, int *where)
{
int ac, b2, y2, ae;
int i, j, k;
int num, den, min;
#ifdef SEE_ENTWINE
int strt = 1;
int iflare, oflare;
#endif
uint16 *ktrace = tbuf->trace + (uint64) (kpath->trace);
uint16 *jtrace = tbuf->trace + (uint64) (jpath->trace);
min = 10000;
num = 0;
den = 0;
#ifdef SEE_ENTWINE
printf("\n");
#endif
y2 = jpath->bbpos;
j = jpath->abpos / MR_tspace;
b2 = kpath->bbpos;
k = kpath->abpos / MR_tspace;
if (jpath->abpos == kpath->abpos)
{
min = abs(y2 - b2);
if (min == 0)
*where = kpath->abpos;
}
if (j < k)
{
ac = k * MR_tspace;
j = 1 + 2 * (k - j);
k = 1;
for (i = 1; i < j; i += 2)
y2 += jtrace[i];
}
else
{
ac = j * MR_tspace;
k = 1 + 2 * (j - k);
j = 1;
for (i = 1; i < k; i += 2)
b2 += ktrace[i];
}
ae = jpath->aepos;
if (ae > kpath->aepos)
ae = kpath->aepos;
while (1)
{
ac += MR_tspace;
if (ac >= ae)
break;
y2 += jtrace[j];
b2 += ktrace[k];
j += 2;
k += 2;
#ifdef SEE_ENTWINE
printf(" @ %5d : %5d %5d = %4d\n",ac,y2,b2,abs(b2-y2));
#endif
i = abs(y2 - b2);
if (i <= min)
{
min = i;
if (i == 0)
*where = ac;
}
num += i;
den += 1;
#ifdef SEE_ENTWINE
if (strt)
{ strt = 0;
iflare = i;
}
oflare = i;
#endif
}
if (jpath->aepos == kpath->aepos)
{
i = abs(jpath->bepos - kpath->bepos);
if (i <= min)
{
min = i;
if (i == 0)
*where = kpath->aepos;
}
}
#ifdef SEE_ENTWINE
if (den == 0)
printf("Nothing\n");
else
printf("MINIM = %d AVERAGE = %d IFLARE = %d OFLARE = %d\n",min,num/den,iflare,oflare);
#endif
if (den == 0)
return (-1);
else
return (min);
}
// Produce the concatentation of path1 and path2 where they are known to meet at
// the trace point with coordinate ap. Place this result in a big growing buffer
static void Fusion(Path *path1, int ap, Path *path2, Trace_Buffer *tbuf)
{
int k, k1, k2;
int len, diff;
uint16 *trace;
k1 = 2 * ((ap / MR_tspace) - (path1->abpos / MR_tspace));
k2 = 2 * ((ap / MR_tspace) - (path2->abpos / MR_tspace));
len = k1 + (path2->tlen - k2);
if (tbuf->top + len >= tbuf->max)
{
tbuf->max = 1.2 * (tbuf->top + len) + 1000;
tbuf->trace = (uint16 *) Realloc(tbuf->trace, sizeof(uint16) * tbuf->max, "Allocating paths");
if (tbuf->trace == NULL)
exit(1);
}
trace = tbuf->trace + tbuf->top;
tbuf->top += len;
diff = 0;
len = 0;
if (k1 > 0)
{
uint16 *t = tbuf->trace + (uint64) (path1->trace);
for (k = 0; k < k1; k += 2)
{
trace[len++] = t[k];
trace[len++] = t[k + 1];
diff += t[k];
}
}
if (k2 < path2->tlen)
{
uint16 *t = tbuf->trace + (uint64) (path2->trace);
for (k = k2; k < path2->tlen; k += 2)
{
trace[len++] = t[k];
trace[len++] = t[k + 1];
diff += t[k];
}
}
path1->aepos = path2->aepos;
path1->bepos = path2->bepos;
path1->diffs = diff;
path1->trace = (void *) (trace - tbuf->trace);
path1->tlen = len;
}
// Produce the concatentation of path1, path2, and path3 where they are known to meet at
// the the ends of path2 which was produced by Compute-Alignment. Place this result in
// a big growing buffer
static void Bridge(Path *path1, Path *path2, Path *path3, Trace_Buffer *tbuf)
{ int k, k1, k2;
int len, diff;
uint16 *trace;
k1 = 2 * ((path2->abpos/MR_tspace) - (path1->abpos/MR_tspace));
if (path2->aepos == path3->aepos)
k2 = path3->tlen;
else
k2 = 2 * ((path2->aepos/MR_tspace) - (path3->abpos/MR_tspace));
len = k1 + path2->tlen + (path3->tlen-k2);
if (tbuf->top + len >= tbuf->max)
{ tbuf->max = 1.2*(tbuf->top+len) + 1000;
tbuf->trace = (uint16 *) Realloc(tbuf->trace,sizeof(uint16)*tbuf->max,"Allocating paths");
if (tbuf->trace == NULL)
exit (1);
}
trace = tbuf->trace + tbuf->top;
tbuf->top += len;
diff = 0;
len = 0;
if (k1 > 0)
{ uint16 *t = tbuf->trace + (uint64) (path1->trace);
for (k = 0; k < k1; k += 2)
{ trace[len++] = t[k];
trace[len++] = t[k+1];
diff += t[k];
}
}
if (path2->tlen > 0)
{ uint16 *t = (uint16 *) (path2->trace);
for (k = 0; k < path2->tlen; k += 2)
{ trace[len++] = t[k];
trace[len++] = t[k+1];
diff += t[k];
}
}
if (k2 < path3->tlen)
{ uint16 *t = tbuf->trace + (uint64) (path3->trace);
for (k = k2; k < path3->tlen; k += 2)
{ trace[len++] = t[k];
trace[len++] = t[k+1];
diff += t[k];
}
}
path1->aepos = path3->aepos;
path1->bepos = path3->bepos;
path1->diffs = diff;
path1->trace = (void *) (trace - tbuf->trace);
path1->tlen = len;
}
static int Handle_Redundancies(Path *amatch, int novls, Path *bmatch,
Alignment *align, Work_Data *work, Trace_Buffer *tbuf)
{ Path *jpath, *kpath, *apath;
Path _bpath, *bpath = &_bpath;
Alignment _blign, *blign = &_blign;
int j, k, no;
int dist;
int awhen = 0, bwhen = 0;
int hasB;
#if defined(TEST_CONTAIN) || defined(TEST_BRIDGE)
for (j = 0; j < novls; j++)
printf(" %3d: [%5d,%5d] x [%5d,%5d]\n",j,amatch[j].abpos,amatch[j].aepos,
amatch[j].bbpos,amatch[j].bepos);
#endif
// Loop to catch LA's that share a common trace point and fuse them
hasB = (bmatch != NULL);
if (hasB)
{ blign->aseq = align->bseq;
blign->bseq = align->aseq;
blign->alen = align->blen;
blign->blen = align->alen;
blign->path = bpath;
}
apath = align->path;
for (j = 1; j < novls; j++)
{ jpath = amatch+j;
for (k = j-1; k >= 0; k--)
{ kpath = amatch+k;
if (kpath->abpos < 0)
continue;
if (jpath->abpos < kpath->abpos)
{ if (kpath->abpos <= jpath->aepos && kpath->bbpos <= jpath->bepos)
{ dist = Entwine(jpath,kpath,tbuf,&awhen);
if (dist == 0)
{ if (kpath->aepos > jpath->aepos)
{ if (hasB)
{ if (MG_comp)
{ dist = Entwine(bmatch+k,bmatch+j,tbuf,&bwhen);
if (dist != 0)
continue;
Fusion(jpath,awhen,kpath,tbuf);
Fusion(bmatch+k,bwhen,bmatch+j,tbuf);
bmatch[j] = bmatch[k];
#ifdef TEST_CONTAIN
printf(" Really 1");
#endif
}
else
{ dist = Entwine(bmatch+j,bmatch+k,tbuf,&bwhen);
if (dist != 0)
continue;
Fusion(jpath,awhen,kpath,tbuf);
Fusion(bmatch+j,bwhen,bmatch+k,tbuf);
#ifdef TEST_CONTAIN
printf(" Really 2");
#endif
}
}
else
{ Fusion(jpath,awhen,kpath,tbuf);
#ifdef TEST_CONTAIN
printf(" Really 3");
#endif
}
k = j;
}
kpath->abpos = -1;
#ifdef TEST_CONTAIN
printf(" Fuse! A %d %d\n",j,k);
#endif
}
}
}
else // kpath->abpos <= jpath->abpos
{ if (jpath->abpos <= kpath->aepos && jpath->bbpos <= kpath->bepos)
{ dist = Entwine(kpath,jpath,tbuf,&awhen);
if (dist == 0)
{ if (kpath->abpos == jpath->abpos)
{ if (kpath->aepos > jpath->aepos)
{ *jpath = *kpath;
if (hasB)
bmatch[j] = bmatch[k];
}
}
else if (jpath->aepos > kpath->aepos)
{ if (hasB)
{ if (MG_comp)
{ dist = Entwine(bmatch+j,bmatch+k,tbuf,&bwhen);
if (dist != 0)
continue;
Fusion(kpath,awhen,jpath,tbuf);
*jpath = *kpath;
Fusion(bmatch+j,bwhen,bmatch+k,tbuf);
#ifdef TEST_CONTAIN
printf(" Really 4");
#endif
}
else
{ dist = Entwine(bmatch+k,bmatch+j,tbuf,&bwhen);
if (dist != 0)
continue;
Fusion(kpath,awhen,jpath,tbuf);
*jpath = *kpath;
Fusion(bmatch+k,bwhen,bmatch+j,tbuf);
bmatch[j] = bmatch[k];
#ifdef TEST_CONTAIN
printf(" Really 5");
#endif
}
}
else
{ Fusion(kpath,awhen,jpath,tbuf);
*jpath = *kpath;
#ifdef TEST_CONTAIN
printf(" Really 6");
#endif
}
k = j;
}
else
{ *jpath = *kpath;
if (hasB)
bmatch[j] = bmatch[k];
}
kpath->abpos = -1;
#ifdef TEST_CONTAIN
printf(" Fuse! B %d %d\n",j,k);
#endif
}
}
}
}
}
// Loop to catch LA's that have a narrow parallel overlap and bridge them
for (j = 1; j < novls; j++)
{ jpath = amatch+j;
if (jpath->abpos < 0)
continue;
for (k = j-1; k >= 0; k--)
{ Path *path1, *path2;
Path *bath1, *bath2;
int aovl, bovl;
Path jback, kback;
kpath = amatch+k;
if (kpath->abpos < 0)
continue;
if (jpath->abpos < kpath->abpos)
{ path1 = jpath;
path2 = kpath;
}
else
{ path1 = kpath;
path2 = jpath;
}
if (path2->abpos >= path1->aepos || path1->aepos >= path2->aepos ||
path1->bbpos >= path2->bbpos || path2->bbpos >= path1->bepos ||
path1->bepos >= path2->bepos)
continue;
aovl = path1->aepos - path2->abpos;
bovl = path1->bepos - path2->bbpos;
if (abs(aovl-bovl) > .2 * (aovl+bovl))
continue;
if (hasB)
{ if (MG_comp == (jpath->abpos < kpath->abpos))
{ bath1 = bmatch+k;
bath2 = bmatch+j;
}
else
{ bath1 = bmatch+j;
bath2 = bmatch+k;
}
if (bath1->abpos > bath2->abpos)
{ printf(" SYMFAIL %d %d\n",j,k);
continue;
}
}
Compute_Bridge_Path(path1,path2,align,0,aovl,bovl,work,tbuf);
if (Check_Bridge(apath))
continue;
jback = *jpath;
kback = *kpath;
Bridge(path1,apath,path2,tbuf);
*jpath = *path1;
kpath->abpos = -1;
#ifdef TEST_BRIDGE
{ Alignment extra;
Path pcopy;
pcopy = *jpath;
extra = *align;
pcopy.trace = tbuf->trace + (uint64) jpath->trace;
extra.path = &pcopy;
Compute_Trace_PTS(&extra,work,MR_tspace,GREEDIEST);
Print_Reference(stdout,&extra,work,8,100,10,0,6);
fflush(stdout);
}
#endif
if (hasB)
{ Compute_Bridge_Path(bath1,bath2,blign,MG_comp,bovl,aovl,work,tbuf);
if (Check_Bridge(bpath))
{ *jpath = jback;
*kpath = kback;
continue;
}
Bridge(bath1,bpath,bath2,tbuf);
bmatch[j] = *bath1;
#ifdef TEST_BRIDGE
{ Alignment extra;
Path pcopy;
pcopy = bmatch[j];
extra = *blign;
pcopy.trace = tbuf->trace + (uint64) bmatch[j].trace;
extra.path = &pcopy;
if (MG_comp)
{ Complement_Seq(extra.aseq,extra.alen);
Complement_Seq(extra.bseq,extra.blen);
}
Compute_Trace_PTS(&extra,work,MR_tspace,GREEDIEST);
Print_Reference(stdout,&extra,work,8,100,10,0,6);
fflush(stdout);
if (MG_comp)
{ Complement_Seq(extra.aseq,extra.alen);
Complement_Seq(extra.bseq,extra.blen);
}
}
#endif
}
}
}
no = 0;
for (j = 0; j < novls; j++)
if (amatch[j].abpos >= 0)
{ if (hasB)
bmatch[no] = bmatch[j];
amatch[no++] = amatch[j];
}
novls = no;
#if defined(TEST_CONTAIN) || defined(TEST_BRIDGE)
for (j = 0; j < novls; j++)
printf(" %3d: [%5d,%5d] x [%5d,%5d]\n",j,amatch[j].abpos,amatch[j].aepos,
amatch[j].bbpos,amatch[j].bepos);
#endif
return (novls);
}
void Diagonal_Span(Path *path, int *mind, int *maxd)
{
uint16 *points;
int i, tlen;
int dd, low, hgh;
points = path->trace;
tlen = path->tlen;
dd = path->abpos - path->bbpos;
low = hgh = dd;
dd = path->aepos - path->bepos;
if (dd < low)
low = dd;
else if (dd > hgh)
hgh = dd;
dd = (path->abpos / MR_tspace) * MR_tspace - path->bbpos;
tlen -= 2;
for (i = 1; i < tlen; i += 2)
{
dd += MR_tspace - points[i];
if (dd < low)
low = dd;
else if (dd > hgh)
hgh = dd;
}
*mind = (low >> Binshift) - 1;
*maxd = (hgh >> Binshift) + 1;
}
typedef struct
{
int64 beg, end;
int *score;
int *lastp;
int *lasta;
Work_Data *work;
#ifdef THREAD_OUTPUT
FILE *ofile1;
FILE *ofile2;
#endif
int64 nfilt;
int64 ncheck;
Overlap_IO_Buffer *iobuf;
} Report_Arg;
static void *report_thread(void *arg)
{
Report_Arg *data = (Report_Arg *) arg;
SeedPair *hits = MR_hits;
Double *hitd = (Double *) MR_hits;
char *aseq = (char *) (MR_ablock->bases);
char *bseq = (char *) (MR_bblock->bases);
HITS_READ *aread = MR_ablock->reads;
HITS_READ *bread = MR_bblock->reads;
int *score = data->score;
int *scorp = data->score + 1;
int *scorm = data->score - 1;
int *lastp = data->lastp;
int *lasta = data->lasta;
Work_Data *work = data->work;
#ifdef THREAD_OUTPUT
FILE *ofile1 = data->ofile1;
FILE *ofile2 = data->ofile2;
#endif
int afirst = MR_ablock->ufirst;
int bfirst = MR_bblock->ufirst;
int maxdiag = (MR_ablock->maxlen >> Binshift);
int mindiag = (-MR_bblock->maxlen >> Binshift);
Overlap_IO_Buffer *obuf = data->iobuf;
Overlap _ovla, *ovla = &_ovla;
Overlap _ovlb, *ovlb = &_ovlb;
Alignment _align, *align = &_align;
Path *apath = &(ovla->path);
Path *bpath;
int64 nfilt = 0;
int64 ahits = 0;
int64 bhits = 0;
int small, tbytes;
int AOmax, BOmax;
int novla, novlb;
Path *amatch, *bmatch;
Trace_Buffer _tbuf, *tbuf = &_tbuf;
Double *hitc;
int minhit;
uint64 cpair, npair;
int64 nidx, eidx;
// In ovl and align roles of A and B are reversed, as the B sequence must be the
// complemented sequence !!
align->flags = ovla->flags = ovlb->flags = MG_comp;
align->path = apath;
if (MR_tspace <= TRACE_XOVR)
{
small = 1;
tbytes = sizeof(uint8);
}
else
{
small = 0;
tbytes = sizeof(uint16);
}
AOmax = BOmax = MATCH_CHUNK;
amatch = Malloc(sizeof(Path) * AOmax, "Allocating match vector");
bmatch = Malloc(sizeof(Path) * BOmax, "Allocating match vector");
tbuf->max = 2 * TRACE_CHUNK;
tbuf->trace = Malloc(sizeof(short) * tbuf->max, "Allocating trace vector");
if (amatch == NULL || bmatch == NULL || tbuf->trace == NULL)
exit(1);
#ifdef THREAD_OUTPUT
fwrite(&ahits, sizeof(int64), 1, ofile1);
fwrite(&MR_tspace, sizeof(int), 1, ofile1);
if (MR_two)
{
fwrite(&bhits, sizeof(int64), 1, ofile2);
fwrite(&MR_tspace, sizeof(int), 1, ofile2);
}
#endif
minhit = (Hitmin - 1) / Kmer + 1;
hitc = hitd + (minhit - 1);
eidx = data->end - minhit;
nidx = data->beg;
for (cpair = hitd[nidx].p2; nidx < eidx; cpair = npair)
if (hitc[nidx].p2 != cpair)
{
nidx += 1;
while ((npair = hitd[nidx].p2) == cpair)
nidx += 1;
}
else
{
int ar, br;
int alen, blen;
int doA, doB;
int setaln, amark, amark2;
int apos, bpos, diag;
int64 lidx, sidx;
int64 f, h2;
ar = hits[nidx].aread;
br = hits[nidx].bread;
alen = aread[ar].rlen;
blen = bread[br].rlen;
if (alen < HGAP_MIN && blen < HGAP_MIN)
{
nidx += 1;
while ((npair = hitd[nidx].p2) == cpair)
nidx += 1;
continue;
}
#ifdef TEST_GATHER
printf("%5d vs %5d : %5d x %5d\n",br+bfirst,ar+afirst,blen,alen);
#endif
setaln = 1;
doA = doB = 0;
amark2 = 0;
novla = novlb = 0;
tbuf->top = 0;
for (sidx = nidx; hitd[nidx].p2 == cpair; nidx = h2)
{
amark = amark2 + PANEL_SIZE;
amark2 = amark - PANEL_OVERLAP;
h2 = lidx = nidx;
do
{
apos = hits[nidx].apos;
npair = hitd[++nidx].p2;
if (apos <= amark2)
h2 = nidx;
} while (npair == cpair && apos <= amark);
if (nidx - lidx < minhit)
continue;
for (f = lidx; f < nidx; f++)
{
apos = hits[f].apos;
diag = hits[f].diag >> Binshift;
if (apos - lastp[diag] >= Kmer)
score[diag] += Kmer;
else
score[diag] += apos - lastp[diag];
lastp[diag] = apos;
}
#ifdef TEST_GATHER
printf(" %6lld upto %6d",nidx-lidx,amark);
#endif
for (f = lidx; f < nidx; f++)
{
apos = hits[f].apos;
diag = hits[f].diag;
bpos = apos - diag;
diag = diag >> Binshift;
if (apos > lasta[diag] && (score[diag] + scorp[diag] >= Hitmin || score[diag] + scorm[diag] >= Hitmin))
{
if (setaln)
{
setaln = 0;
align->aseq = aseq + aread[ar].boff;
align->bseq = bseq + bread[br].boff;
align->alen = alen;
align->blen = blen;
ovlb->bread = ovla->aread = ar + afirst;
ovlb->aread = ovla->bread = br + bfirst;
doA = (alen >= HGAP_MIN);
doB = (SYMMETRIC && blen >= HGAP_MIN && (ar != br || !MG_self || !MG_comp));
}
#ifdef TEST_GATHER
else
printf("\n ");
if (scorm[diag] > scorp[diag])
printf(" %5d.. x %5d.. %5d (%3d)",
bpos,apos,apos-bpos,score[diag]+scorm[diag]);
else
printf(" %5d.. x %5d.. %5d (%3d)",
bpos,apos,apos-bpos,score[diag]+scorp[diag]);
#endif
nfilt += 1;
bpath = Local_Alignment(align, work, MR_spec, apos - bpos, apos - bpos, apos + bpos, -1, -1);
{
int low, hgh, ae;
Diagonal_Span(apath, &low, &hgh);
if (diag < low)
low = diag;
else if (diag > hgh)
hgh = diag;
ae = apath->aepos;
for (diag = low; diag <= hgh; diag++)
if (ae > lasta[diag])
lasta[diag] = ae;
#ifdef TEST_GATHER
printf(" %d - %d @ %d",low,hgh,apath->aepos);
#endif
}
if ((apath->aepos - apath->abpos) + (apath->bepos - apath->bbpos) >= MINOVER)
{
if (doA)
{
if (novla >= AOmax)
{
AOmax = 1.2 * novla + MATCH_CHUNK;
amatch = Realloc(amatch, sizeof(Path) * AOmax, "Reallocating match vector");
if (amatch == NULL)
exit(1);
}
if (tbuf->top + apath->tlen > tbuf->max)
{
tbuf->max = 1.2 * (tbuf->top + apath->tlen) + TRACE_CHUNK;
tbuf->trace = Realloc(tbuf->trace, sizeof(short) * tbuf->max, "Reallocating trace vector");
if (tbuf->trace == NULL)
exit(1);
}
amatch[novla] = *apath;
amatch[novla].trace = (void *) (tbuf->top);
memmove(tbuf->trace + tbuf->top, apath->trace, sizeof(short) * apath->tlen);
novla += 1;
tbuf->top += apath->tlen;
}
if (doB)
{
if (novlb >= BOmax)
{
BOmax = 1.2 * novlb + MATCH_CHUNK;
bmatch = Realloc(bmatch, sizeof(Path) * BOmax, "Reallocating match vector");
if (bmatch == NULL)
exit(1);
}
if (tbuf->top + bpath->tlen > tbuf->max)
{
tbuf->max = 1.2 * (tbuf->top + bpath->tlen) + TRACE_CHUNK;
tbuf->trace = Realloc(tbuf->trace, sizeof(short) * tbuf->max, "Reallocating trace vector");
if (tbuf->trace == NULL)
exit(1);
}
bmatch[novlb] = *bpath;
bmatch[novlb].trace = (void *) (tbuf->top);
memmove(tbuf->trace + tbuf->top, bpath->trace, sizeof(short) * bpath->tlen);
novlb += 1;
tbuf->top += bpath->tlen;
}
#ifdef TEST_GATHER
printf(" [%5d,%5d] x [%5d,%5d] = %4d",
apath->abpos,apath->aepos,apath->bbpos,apath->bepos,apath->diffs);
#endif
#ifdef SHOW_OVERLAP
printf("\n\n %d(%d) vs %d(%d)\n\n",
ovla->aread,ovla->alen,ovla->bread,ovla->blen);
Print_ACartoon(stdout,align,ALIGN_INDENT);
#ifdef SHOW_ALIGNMENT
Compute_Trace_ALL(align,work);
printf("\n Diff = %d\n",align->path->diffs);
Print_Alignment(stdout,align,work,
ALIGN_INDENT,ALIGN_WIDTH,ALIGN_BORDER,0,5);
#endif
#endif // SHOW_OVERLAP
}
#ifdef TEST_GATHER
else
printf(" No alignment %d",
((apath->aepos-apath->abpos) + (apath->bepos-apath->bbpos))/2);
#endif
}
}
for (f = lidx; f < nidx; f++)
{
diag = hits[f].diag >> Binshift;
score[diag] = lastp[diag] = 0;
}
#ifdef TEST_GATHER
printf("\n");
#endif
}
for (f = sidx; f < nidx; f++)
{
int d;
diag = hits[f].diag >> Binshift;
for (d = diag; d <= maxdiag; d++)
if (lasta[d] == 0)
break;
else
lasta[d] = 0;
for (d = diag - 1; d >= mindiag; d--)
if (lasta[d] == 0)
break;
else
lasta[d] = 0;
}
{
int i;
#ifdef TEST_CONTAIN
if (novla > 1 || novlb > 1)
printf("\n%5d vs %5d:\n",ar,br);
#endif
if (novla > 1)
{
if (novlb > 1)
novla = novlb = Handle_Redundancies(amatch,novla,bmatch,align,work,tbuf);
else
novla = Handle_Redundancies(amatch,novla,NULL,align,work,tbuf);
}
else if (novlb > 1)
novlb = Handle_Redundancies(bmatch,novlb,NULL,align,work,tbuf);
for (i = 0; i < novla; i++)
{
ovla->path = amatch[i];
ovla->path.trace = tbuf->trace + (uint64) (ovla->path.trace);
if (small)
Compress_TraceTo8(ovla,1);
#ifdef THREAD_OUTPUT
if (Write_Overlap(ofile1, ovla, tbytes))
{
fprintf(stderr, "%s: Cannot write to %s too small?\n",
SORT_PATH, Prog_Name);
exit(1);
}
#endif
AddOverlapToBuffer(obuf, ovla, tbytes);
}
for (i = 0; i < novlb; i++)
{
ovlb->path = bmatch[i];
ovlb->path.trace = tbuf->trace + (uint64) (ovlb->path.trace);
if (small)
Compress_TraceTo8(ovlb,1);
#ifdef THREAD_OUTPUT
if (Write_Overlap(ofile2, ovlb, tbytes))
{
fprintf(stderr, "%s: Cannot write to %s, too small?\n",
SORT_PATH, Prog_Name);
exit(1);
}
#endif
AddOverlapToBuffer(obuf, ovlb, tbytes);
}
ahits += novla;
bhits += novlb;
}
}
free(tbuf->trace);
free(bmatch);
free(amatch);
data->nfilt = nfilt;
data->ncheck = ahits + bhits;
#ifdef THREAD_OUTPUT
if (MR_two)
{
rewind(ofile2);
fwrite(&bhits, sizeof(int64), 1, ofile2);
fclose(ofile2);
}
else
ahits += bhits;
rewind(ofile1);
fwrite(&ahits, sizeof(int64), 1, ofile1);
fclose(ofile1);
#endif
return (NULL);
}
/*******************************************************************************************
*
* THE ALGORITHM
*
********************************************************************************************/
void Match_Filter(char *aname, HITS_DB *ablock, char *bname, HITS_DB *bblock, void *vasort, int alen, void *vbsort, int blen, int comp, Align_Spec *aspec)
{
THREAD threads[NTHREADS];
Merge_Arg parmm[NTHREADS];
Lex_Arg parmx[NTHREADS];
Report_Arg parmr[NTHREADS];
int pairsort[16];
SeedPair *khit, *hhit;
SeedPair *work1, *work2;
int64 nhits;
int64 nfilt, ncheck;
KmerPos *asort, *bsort;
int64 atot, btot;
asort = (KmerPos *) vasort;
bsort = (KmerPos *) vbsort;
atot = ablock->totlen;
btot = bblock->totlen;
MR_tspace = Trace_Spacing(aspec);
{
int i;
Overlap_IO_Buffer *buffer = OVL_IO_Buffer(aspec);
for (i = 0; i < NTHREADS; i++)
{
parmr[i].iobuf = &(buffer[i]);
if (parmr[i].iobuf == NULL)
exit(1);
}
}
{
int64 powr;
int i, nbyte;
for (i = 0; i < NTHREADS; i++)
parmx[i].sptr = (int64 *) alloca(NTHREADS * BPOWR * sizeof(int64));
for (i = 0; i < 16; i++)
pairsort[i] = 0;
powr = 1;
for (nbyte = 0; powr < ablock->maxlen; nbyte += 1)
powr <<= 8;
for (i = 4; i < 4 + nbyte; i++)
pairsort[i] = 1;
powr = 1;
for (nbyte = 0; powr < ablock->nreads; nbyte += 1)
powr <<= 8;
for (i = 8; i < 8 + nbyte; i++)
pairsort[i] = 1;
powr = 1;
for (nbyte = 0; powr < bblock->nreads; nbyte += 1)
powr <<= 8;
for (i = 12; i < 12 + nbyte; i++)
pairsort[i] = 1;
}
nfilt = ncheck = nhits = 0;
if (VERBOSE)
{
if (comp)
printf("\nComparing %s to c(%s)\n", aname, bname);
else
printf("\nComparing %s to %s\n", aname, bname);
}
if (alen == 0 || blen == 0)
goto zerowork;
{
int i, j, p;
uint64 c;
int limit;
MG_alist = asort;
MG_blist = bsort;
MG_self = (aname == bname);
MG_comp = comp;
parmm[0].abeg = parmm[0].bbeg = 0;
for (i = 1; i < NTHREADS; i++)
{
p = (int) ((((int64) alen) * i) >> NSHIFT);
if (p > 0)
{
c = asort[p - 1].code;
while (asort[p].code == c)
p += 1;
}
parmm[i].abeg = parmm[i - 1].aend = p;
parmm[i].bbeg = parmm[i - 1].bend = find_tuple(asort[p].code, bsort, blen);
}
parmm[NTHREADS - 1].aend = alen;
parmm[NTHREADS - 1].bend = blen;
for (i = 0; i < NTHREADS; i++)
for (j = 0; j < MAXGRAM; j++)
parmm[i].hitgram[j] = 0;
for (i = 0; i < NTHREADS; i++)
pthread_create(threads + i, NULL, count_thread, parmm + i);
for (i = 0; i < NTHREADS; i++)
pthread_join(threads[i], NULL);
if (VERBOSE)
printf("\n");
if (MEM_LIMIT > 0)
{
int64 histo[MAXGRAM];
int64 tom, avail;
for (j = 0; j < MAXGRAM; j++)
histo[j] = parmm[0].hitgram[j];
for (i = 1; i < NTHREADS; i++)
for (j = 0; j < MAXGRAM; j++)
histo[j] += parmm[i].hitgram[j];
avail = (int64) (MEM_LIMIT - (sizeof_DB(ablock) + sizeof_DB(bblock))) / sizeof(Double);
if (asort == bsort || avail > alen + 2 * blen)
avail = (avail - alen) / 2;
else
avail = avail - (alen + blen);
avail *= .98;
tom = 0;
for (j = 0; j < MAXGRAM; j++)
{
tom += j * histo[j];
if (tom > avail)
break;
}
limit = j;
if (limit <= 1)
{
fprintf(stderr, "\nError: Insufficient ");
if (MEM_LIMIT == MEM_PHYSICAL)
fprintf(stderr, " physical memory (%.1fGb), reduce block size\n", (1. * MEM_LIMIT) / 0x40000000ll);
else
{
fprintf(stderr, " memory allocation (%.1fGb),", (1. * MEM_LIMIT) / 0x40000000ll);
fprintf(stderr, " reduce block size or increase allocation\n");
}
fflush(stderr);
exit(1);
}
if (limit < 10)
{
fprintf(stderr, "\nWarning: Sensitivity hampered by low ");
if (MEM_LIMIT == MEM_PHYSICAL)
fprintf(stderr, " physical memory (%.1fGb), reduce block size\n", (1. * MEM_LIMIT) / 0x40000000ll);
else
{
fprintf(stderr, " memory allocation (%.1fGb),", (1. * MEM_LIMIT) / 0x40000000ll);
fprintf(stderr, " reduce block size or increase allocation\n");
}
fflush(stderr);
}
if (VERBOSE)
{
printf(" Capping mutual k-mer matches over %d (effectively -t%d)\n", limit, (int) sqrt(1. * limit));
fflush(stdout);
}
for (i = 0; i < NTHREADS; i++)
{
parmm[i].nhits = 0;
for (j = 1; j < limit; j++)
parmm[i].nhits += j * parmm[i].hitgram[j];
parmm[i].limit = limit;
}
}
else
for (i = 0; i < NTHREADS; i++)
parmm[i].limit = INT32_MAX;
nhits = parmm[0].nhits;
for (i = 1; i < NTHREADS; i++)
parmm[i].nhits = nhits += parmm[i].nhits;
if (VERBOSE)
{
printf(" Hit count = ");
Print_Number(nhits, 0, stdout);
if (asort == bsort || nhits >= blen)
printf("\n Highwater of %.2fGb space\n", (1. * (alen + 2 * nhits)) / 67108864);
else
printf("\n Highwater of %.2fGb space\n", (1. * (alen + blen + nhits)) / 67108864);
fflush(stdout);
}
if (nhits == 0)
goto zerowork;
if (asort == bsort)
hhit = work1 = (SeedPair *) Malloc(sizeof(SeedPair) * (nhits + 1), "Allocating dazzler hit vectors");
else
{
if (nhits >= blen)
bsort = (KmerPos *) Realloc(bsort, sizeof(SeedPair) * (nhits + 1), "Reallocating dazzler sort vectors");
hhit = work1 = (SeedPair *) bsort;
}
khit = work2 = (SeedPair *) Malloc(sizeof(SeedPair) * (nhits + 1), "Allocating dazzler hit vectors");
if (hhit == NULL || khit == NULL || bsort == NULL)
exit(1);
MG_blist = bsort;
MG_hits = khit;
for (i = NTHREADS - 1; i > 0; i--)
parmm[i].nhits = parmm[i - 1].nhits;
parmm[0].nhits = 0;
for (i = 0; i < NTHREADS; i++)
{
parmm[i].kptr = parmx[i].tptr;
for (p = 0; p < BPOWR; p++)
parmm[i].kptr[p] = 0;
}
for (i = 0; i < NTHREADS; i++)
pthread_create(threads + i, NULL, merge_thread, parmm + i);
for (i = 0; i < NTHREADS; i++)
pthread_join(threads[i], NULL);
#ifdef TEST_PAIRS
printf("\nSETUP SORT:\n");
for (i = 0; i < HOW_MANY && i < nhits; i++)
{ SeedPair *c = khit+i;
printf(" %5d / %5d / %5d /%5d\n",c->aread,c->bread,c->apos,c->apos-c->diag);
}
#endif
}
{
int i;
int64 x;
x = 0;
for (i = 0; i < NTHREADS - 1; i++)
{
parmx[i].beg = x;
parmx[i].end = x = parmm[i + 1].nhits;
}
parmx[NTHREADS - 1].beg = x;
parmx[NTHREADS - 1].end = nhits;
khit = (SeedPair *) lex_sort(pairsort, (Double *) khit, (Double *) hhit, parmx);
khit[nhits].aread = 0x7fffffff;
khit[nhits].bread = 0x7fffffff;
khit[nhits].diag = 0x7fffffff;
khit[nhits].apos = 0;
#ifdef TEST_CSORT
printf("\nCROSS SORT %lld:\n",nhits);
for (i = 0; i < HOW_MANY && i <= nhits; i++)
{ SeedPair *c = khit+i;
printf(" %5d / %5d / %5d /%5d\n",c->aread,c->bread,c->apos,c->apos-c->diag);
}
#endif
}
{
int i, w;
int64 p;
int d;
int *counters;
MR_ablock = ablock;
MR_bblock = bblock;
MR_hits = khit;
MR_two = !MG_self && SYMMETRIC;
MR_spec = aspec;
parmr[0].beg = 0;
for (i = 1; i < NTHREADS; i++)
{
p = (nhits * i) >> NSHIFT;
if (p > 0)
{
d = khit[p - 1].bread;
while ((khit[p].bread) == d)
p += 1;
}
parmr[i].beg = parmr[i - 1].end = p;
}
parmr[NTHREADS - 1].end = nhits;
w = ((ablock->maxlen >> Binshift) - ((-bblock->maxlen) >> Binshift)) + 1;
counters = (int *) Malloc(NTHREADS * 3 * w * sizeof(int), "Allocating diagonal buckets");
if (counters == NULL)
exit(1);
for (i = 0; i < 3 * w * NTHREADS; i++)
counters[i] = 0;
for (i = 0; i < NTHREADS; i++)
{
if (i == 0)
parmr[i].score = counters - ((-bblock->maxlen) >> Binshift);
else
parmr[i].score = parmr[i - 1].lasta + w;
parmr[i].lastp = parmr[i].score + w;
parmr[i].lasta = parmr[i].lastp + w;
parmr[i].work = New_Work_Data();
#ifdef THREAD_OUTPUT
parmr[i].ofile1 = Fopen(Catenate(aname, ".", bname, Numbered_Suffix((comp ? ".C" : ".N"), i, ".las")), "w");
if (parmr[i].ofile1 == NULL)
exit(1);
if (MG_self)
parmr[i].ofile2 = parmr[i].ofile1;
else if (SYMMETRIC)
{
parmr[i].ofile2 = Fopen(Catenate(bname, ".", aname, Numbered_Suffix((comp ? ".C" : ".N"), i, ".las")), "w");
if (parmr[i].ofile2 == NULL)
exit(1);
}
#endif
}
#ifdef NOTHREAD
for (i = 0; i < NTHREADS; i++)
report_thread(parmr+i);
#else
for (i = 0; i < NTHREADS; i++)
pthread_create(threads + i, NULL, report_thread, parmr + i);
for (i = 0; i < NTHREADS; i++)
pthread_join(threads[i], NULL);
#endif
if (VERBOSE)
for (i = 0; i < NTHREADS; i++)
{
nfilt += parmr[i].nfilt;
ncheck += parmr[i].ncheck;
}
for (i = 0; i < NTHREADS; i++)
Free_Work_Data(parmr[i].work);
free(counters);
// for (i = 0; i < NTHREADS; i++)
// free(parmx[i].sptr);
}
free(work2);
free(work1);
goto epilogue;
zerowork:
{
#ifdef THREAD_OUTPUT
FILE *ofile;
int i;
nhits = 0;
for (i = 0; i < NTHREADS; i++)
{
ofile = Fopen(Catenate(aname, ".", bname, Numbered_Suffix((comp ? ".C" : ".N"), i, ".las")), "w");
fwrite(&nhits, sizeof(int64), 1, ofile);
fwrite(&MR_tspace, sizeof(int), 1, ofile);
fclose(ofile);
if (!MG_self && SYMMETRIC)
{
ofile = Fopen(Catenate(bname, ".", aname, Numbered_Suffix((comp ? ".C" : ".N"), i, ".las")), "w");
fwrite(&nhits, sizeof(int64), 1, ofile);
fwrite(&MR_tspace, sizeof(int), 1, ofile);
fclose(ofile);
}
}
#endif
}
epilogue:
if (VERBOSE)
{
int width;
if (nhits <= 0)
width = 1;
else
width = ((int) log10((double) nhits)) + 1;
width += (width - 1) / 3;
printf("\n ");
Print_Number(nhits, width, stdout);
printf(" %d-mers (%e of matrix)\n ", Kmer, (1. * nhits / atot) / btot);
Print_Number(nfilt, width, stdout);
printf(" seed hits (%e of matrix)\n ", (1. * nfilt / atot) / btot);
Print_Number(ncheck, width, stdout);
printf(" confirmed hits (%e of matrix)\n", (1. * ncheck / atot) / btot);
fflush(stdout);
}
}
|
MartinPippel/DAmar
|
touring/OGtour.c
|
/*******************************************************************************************
*
* Tours the overlap graph
* (C implementation of touring_v2.py)
*
* Date : February 2016
*
* Author : <NAME>
*
*******************************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>
#include <sys/param.h>
#include "lib/colors.h"
#include "lib/oflags.h"
#include "lib/pass.h"
#include "lib/tracks.h"
#include "lib/utils.h"
#include "db/DB.h"
#include "dalign/align.h"
// defaults
// switches
// used to store overlaps, basically a copy of everything we need from an Overlap struct
typedef struct
{
int source, target;
unsigned char end;
int flags;
int ovh;
unsigned short div;
} OgEdge;
// maintains the state of the app
typedef struct
{
HITS_DB* db;
HITS_TRACK* trimtrack;
// command line args
char* path_graph_in;
char* path_graph_out;
// overlap graph
uint64* nedges;
OgEdge* edges;
} OgTourContext;
// getopt
extern char* optarg;
extern int optind, opterr, optopt;
static int read_graph_tgf(OgTourContext* octx)
{
FILE* fileIn = fopen(octx->path_graph_in, "r");
if (fileIn == NULL)
{
return 0;
}
char* line = NULL;
size_t maxline = 0;
int nedgestot = 0;
int nreads = octx->db->nreads;
OgEdge* edges;
int* curedges = malloc(sizeof(int) * nreads);
bzero(curedges, sizeof(int) * nreads);
uint64* nedges = octx->nedges = malloc(sizeof(uint64) * (nreads + 1));
bzero(nedges, sizeof(uint64) * (nreads + 1));
int parsing_edges = 0;
int nline = 0;
int len;
while ( (len = getline(&line, &maxline, fileIn)) > 0 )
{
nline++;
if (line[0] == '#')
{
printf("%d edges\n", nedgestot);
edges = octx->edges = malloc(sizeof(OgEdge) * nedgestot);
bzero(edges, sizeof(OgEdge) * nedgestot);
// convert counts to offsets
int i;
uint64 off = 0;
for ( i = 0 ; i <= nreads ; i++ )
{
uint64 coff = nedges[i];
nedges[i] = off;
off += coff;
}
parsing_edges = 1;
continue;
}
if (parsing_edges)
{
char end;
int source, target, ovh, flags, div;
if ( sscanf(line, "%d %d %d %d %d %c\n", &source, &target, &ovh, &flags, &div, &end) != 6 )
{
fprintf(stderr, "error: parsing tgf failed at line %d. '%s'\n", nline, line);
exit(1);
}
OgEdge* e = edges + nedges[source] + curedges[source];
e->source = source;
e->target = target;
e->ovh = ovh;
e->flags = flags;
e->div = div;
e->end = end;
curedges[source]++;
e = edges + nedges[target] + curedges[target];
e->source = source;
e->target = target;
e->ovh = ovh;
e->flags = flags;
e->div = div;
e->end = end;
curedges[target]++;
}
else
{
int rid, cont, edges_in, edges_out;
if ( sscanf(line, "%d %d %d %d\n", &rid, &cont, &edges_in, &edges_out) != 4 )
{
fprintf(stderr, "error: parsing tgf failed at line %d. '%s'\n", nline, line);
exit(1);
}
if (rid < 0 || rid >= nreads)
{
fprintf(stderr, "error: invalid read id %d\n", rid);
exit(1);
}
nedges[rid] += edges_in + edges_out;
nedgestot += edges_in + edges_out;
}
}
free(curedges);
fclose(fileIn);
return 1;
}
static void usage()
{
printf("OGtour <db> <overlap_graph.tgf>\n");
printf("options:\n");
};
int main(int argc, char* argv[])
{
HITS_DB db;
OgTourContext octx;
bzero(&octx, sizeof(OgTourContext));
// process arguments
opterr = 0;
int c;
while ((c = getopt(argc, argv, "")) != -1)
{
switch (c)
{
default:
usage();
exit(1);
}
}
if (argc - optind < 2)
{
usage();
exit(1);
}
char* pcPathReadsIn = argv[optind++];
octx.path_graph_in = argv[optind++];
if (Open_DB(pcPathReadsIn, &db))
{
fprintf(stderr, "could not open '%s'\n", pcPathReadsIn);
exit(1);
}
// init
octx.db = &db;
// work
printf("reading graph\n");
if (!read_graph_tgf(&octx))
{
fprintf(stderr, "error: failed to read %s\n", octx.path_graph_in);
exit(1);
}
// cleanup
free(octx.nedges);
free(octx.edges);
Close_DB(&db);
return 0;
}
|
MartinPippel/DAmar
|
utils/LAfilterMito.c
|
/*******************************************************************************************
*
* filters overlaps by various criteria
*
* Author : Martin
*
* Date : December 2018
*
*******************************************************************************************/
#include <assert.h>
#include <limits.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#include <unistd.h>
#include "lib/colors.h"
#include "lib/oflags.h"
#include "lib/pass.h"
#include "lib/read_loader.h"
#include "lib/tracks.h"
#include "lib/trim.h"
#include "lib/utils.h"
#include "dalign/align.h"
#include "db/DB.h"
#define DEF_ARG_U 1000
#define DEF_ARG_G 1000
#define DEF_ARG_O 25
#define DEF_ARG_C 75
#define VERBOSE
typedef struct
{
// stats counters
int nFiltReads;
int nFiltAlns;
int nFilteredMinLenReads;
int nFilteredMaxLenReads;
int nFilteredMinLenAln;
int nMinReadLength;
int nMaxReadLength;
int nMaxUnalignedTips;
int nMaxOverhangLength;
int nMaxGapLength;
int nMinCoveredReadLength;
// settings
int nVerbose;
HITS_DB* db;
ovl_header_twidth twidth;
} FilterContext;
extern char* optarg;
extern int optind, opterr, optopt;
static int cyclicChain(FilterContext *ctx, Overlap *ovls, int n)
{
int aread, bread;
int alen, blen;
int i;
// aread should be the mito reference
aread = ovls->aread;
// bread raw reads, that we want to fish out
bread = ovls->bread;
alen = DB_READ_LEN(ctx->db, aread);
blen = DB_READ_LEN(ctx->db, bread);
// only pull out reads that overlap front to end with following criteria
// 1. all alignments map in one orientation only
// 2. are within given length thresholds [Min, Max] --> exclude missed adapters, nucleic DNA
// 3. fulfill maximum unaligned sequence
Overlap *ovl1 = ovls;
if (ovl1->path.abpos > ctx->nMaxUnalignedTips && ovl1->path.bbpos > ctx->nMaxUnalignedTips)
{
printf("ctx->nMaxUnalignedTip! : %d > %d && %d > %d\n", ovl1->path.abpos, ctx->nMaxUnalignedTips, ovl1->path.bbpos, ctx->nMaxUnalignedTips);
return 0;
}
if (n == 1)
{
if (alen - ovl1->path.aepos > ctx->nMaxUnalignedTips && blen - ovl1->path.bepos > ctx->nMaxUnalignedTips)
return 0;
if ((ovl1->path.bepos - ovl1->path.bbpos)*100.0/blen < ctx->nMinCoveredReadLength)
return 0;
return 1;
}
int numCyclicBreaks = 0;
int bCumAlnLen = ovl1->path.bepos - ovl1->path.bbpos;
for (i = 1; i < n; i++)
{
Overlap *ovl2 = ovls + i;
bCumAlnLen += ovl2->path.bepos - ovl2->path.bbpos;
if ((ovl1->flags & OVL_COMP) != (ovl2->flags & OVL_COMP))
{
printf("wrong orientation\n");
return 0;
}
// TODO: urgent check gaps at the very end, otherwise we loos to many reads
if(ovl2->path.abpos - ovl1->path.aepos > ctx->nMaxGapLength)
{
printf("gap length to large: %d > %d\n",ovl2->path.abpos - ovl1->path.aepos, ctx->nMaxGapLength );
return 0;
}
if (ovl1->path.aepos - ctx->nMaxOverhangLength < ovl2->path.abpos)
{
// check if we have a valid extension into proper direction
if (ovl1->path.bepos - ctx->nMaxOverhangLength < ovl2->path.bbpos)
{
if(ovl2->path.bbpos - ovl1->path.bepos > ctx->nMaxGapLength)
return 0;
ovl1 = ovl2;
continue;
}
// check if we have a cyclic alignment
if (blen - ovl1->path.bepos < ctx->nMaxUnalignedTips && ovl2->path.bepos - ctx->nMaxUnalignedTips < ovls->path.bbpos)
{
ovl1 = ovl2;
numCyclicBreaks++;
continue;
}
}
return 0;
}
if (numCyclicBreaks > 1)
{
printf("numCyclicBreaks(%d) > 1\n",numCyclicBreaks);
return 0;
}
// check covered b-read percentage
if(bCumAlnLen*100.0/blen < ctx->nMinCoveredReadLength)
{
printf("bCumAlnLen*100.0/blen < ctx->nMinCoveredReadLength: %.3f < %d\n", bCumAlnLen*100.0/blen, ctx->nMinCoveredReadLength);
return 0;
}
return 1;
}
static void filter_pre(PassContext* pctx, FilterContext* fctx)
{
#ifdef VERBOSE
printf( ANSI_COLOR_GREEN "PASS filtering\n" ANSI_COLOR_RESET);
printf( ANSI_COLOR_RED " OPTIONS\n");
printf( " verbose : %d\n", fctx->nVerbose);
printf( " nMinReadLength : %d\n", fctx->nMinReadLength);
printf( " nMinCoveredReadLength : %d\n", fctx->nMinCoveredReadLength);
printf( " nMaxUnalignedTips : %d\n", fctx->nMaxUnalignedTips);
printf( " nMaxReadLength : %d\n", fctx->nMaxReadLength);
printf( " nMaxOverhangLength : %d\n", fctx->nMaxOverhangLength);
printf( " nMaxGapLength : %d\n", fctx->nMaxGapLength);
printf( " nFilteredMinLenReads : %d\n", fctx->nFilteredMinLenReads);
printf( " nFilteredMinLenAln : %d\n", fctx->nFilteredMinLenAln);
printf( " nFilteredMaxLenReads : %d\n", fctx->nFilteredMaxLenReads);
printf( " DB name : %s\n", fctx->db->path);
printf("\n" ANSI_COLOR_RESET);
#endif
fctx->twidth = pctx->twidth;
}
static void filter_post(FilterContext* ctx)
{
if (ctx->nVerbose)
{
if (ctx->nFiltAlns > 0)
{
printf("total discarded alignments %10d\n", ctx->nFiltAlns);
}
}
}
static int filter_handler(void* _ctx, Overlap* ovl, int novl)
{
FilterContext* ctx = (FilterContext*) _ctx;
int i, j, k;
j = k = 0;
while (j < novl)
{
int bReadLen = DB_READ_LEN(ctx->db, ovl[j].bread);
int skipAlns = 0;
if (ctx->nMinReadLength != -1 && (bReadLen < ctx->nMinReadLength || bReadLen > ctx->nMaxReadLength))
{
skipAlns = 1;
ovl[j].flags |= OVL_DISCARD | OVL_RLEN;
}
while (k < novl - 1 && ovl[j].bread == ovl[k + 1].bread)
{
if (skipAlns)
ovl[k + 1].flags |= OVL_DISCARD | OVL_RLEN;
k++;
}
if (!skipAlns)
{
// discard all alignments no valid chain could be found
if (cyclicChain(ctx, ovl + j, k - j + 1) == 0)
{
for (i = j; i<=k; i++)
{
printf("discard OVL: %d vs %d [%d, %d] [%d, %d] comp? %c, l [%d, %d]\n", ovl[i].aread, ovl[i].bread, ovl[i].path.abpos, ovl[i].path.aepos, ovl[i].path.bbpos, ovl[i].path.bepos, (ovl[i].flags & OVL_COMP) ? 'C' : 'N', DB_READ_LEN(ctx->db, ovl[j].aread), DB_READ_LEN(ctx->db, ovl[j].bread));
ovl[i].flags |= OVL_DISCARD;
}
}
}
j = k + 1;
}
return 1;
}
static void usage()
{
fprintf(stderr, "[-vp] [-lLugoc <int>] <db> <overlaps_in> <overlaps_out>\n");
fprintf(stderr, "options: -v ... verbose\n");
fprintf(stderr, " -l ... min read length\n");
fprintf(stderr, " -L ... max read length\n");
fprintf(stderr, " -p ... purge discarded overlaps\n");
fprintf(stderr, " -u ... maximum unaligned tips (default: %d)\n", DEF_ARG_U);
fprintf(stderr, " -g ... maximum gap length in overlap chain (default: %d)\n", DEF_ARG_G);
fprintf(stderr, " -o ... maximum overlap overhang of chained alignments (default: %d)\n", DEF_ARG_O);
fprintf(stderr, " -c ... minimum covered read length in percent (default: %d, must be in [50,100])\n", DEF_ARG_C);
}
int main(int argc, char* argv[])
{
HITS_DB db;
FilterContext fctx;
PassContext* pctx;
FILE* fileOvlIn;
FILE* fileOvlOut;
bzero(&fctx, sizeof(FilterContext));
fctx.db = &db;
// args
int arg_purge = 0;
fctx.nMinReadLength = -1;
fctx.nMaxReadLength = -1;
fctx.nMaxUnalignedTips = DEF_ARG_U;
fctx.nMaxOverhangLength = DEF_ARG_O;
fctx.nMaxGapLength = DEF_ARG_G;
fctx.nMinCoveredReadLength = DEF_ARG_C;
fctx.nVerbose = 0;
int c;
opterr = 0;
while ((c = getopt(argc, argv, "vpl:L:u:g:o:c:")) != -1)
{
switch (c)
{
case 'v':
fctx.nVerbose += 1;
break;
case 'p':
arg_purge = 1;
break;
case 'c':
fctx.nMinCoveredReadLength = atoi(optarg);
break;
case 'u':
fctx.nMaxUnalignedTips = atoi(optarg);
break;
case 'g':
fctx.nMaxGapLength = atoi(optarg);
break;
case 'o':
fctx.nMaxOverhangLength = atoi(optarg);
break;
case 'l':
fctx.nMinReadLength = atoi(optarg);
break;
case 'L':
fctx.nMaxReadLength = atoi(optarg);
break;
default:
fprintf(stderr, "unknown option %c\n", c);
usage();
exit(1);
}
}
if (argc - optind != 3)
{
usage();
exit(1);
}
if(fctx.nMinCoveredReadLength < 50 || fctx.nMinCoveredReadLength > 100)
{
fprintf(stderr, "Minimum covered read length in percent: %d not supported! Valid range [50, 100]\n", fctx.nMinCoveredReadLength);
exit(1);
}
char* pcPathReadsIn = argv[optind++];
char* pcPathOverlapsIn = argv[optind++];
char* pcPathOverlapsOut = argv[optind++];
if ((fileOvlIn = fopen(pcPathOverlapsIn, "r")) == NULL)
{
fprintf(stderr, "could not open %s\n", pcPathOverlapsIn);
exit(1);
}
if ((fileOvlOut = fopen(pcPathOverlapsOut, "w")) == NULL)
{
fprintf(stderr, "could not open %s\n", pcPathOverlapsOut);
exit(1);
}
if (Open_DB(pcPathReadsIn, &db))
{
fprintf(stderr, "could not open %s\n", pcPathReadsIn);
exit(1);
}
// passes
pctx = pass_init(fileOvlIn, fileOvlOut);
pctx->split_b = 0;
pctx->load_trace = 1;
pctx->unpack_trace = 1;
pctx->data = &fctx;
pctx->write_overlaps = 1;
pctx->purge_discarded = arg_purge;
filter_pre(pctx, &fctx);
pass(pctx, filter_handler);
filter_post(&fctx);
pass_free(pctx);
// cleanup
Close_DB(&db);
fclose(fileOvlOut);
fclose(fileOvlIn);
return 0;
}
|
MartinPippel/DAmar
|
lib/tracks.c
|
<reponame>MartinPippel/DAmar
#include "tracks.h"
#include "pass.h"
#include "tracks.h"
#include "lib/compression.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>
#if defined(__APPLE__)
#include <sys/syslimits.h>
#else
#include <linux/limits.h>
#endif
HITS_TRACK* track_load(HITS_DB *db, char* track)
{
FILE* afile = fopen(Catenate(db->path, ".", track, ".a2"), "r");
// printf("%s\n", Catenate(db->path, ".", track, ".a2"));
if (afile == NULL)
{
// printf("fall back to Load_Track\n");
return Load_Track(db, track);
}
track_anno_header header;
if (fread(&header, sizeof(track_anno_header), 1, afile) != 1)
{
fprintf(stderr, "ERROR: could not read header of track %s\n", track);
return NULL;
}
if (header.size <= 0)
{
fprintf(stderr, "ERROR: invalid size field in track %s\n", track);
return NULL;
}
uint64 nreads = db->nreads;
if (db->part == 0 && header.len != nreads)
{
fprintf(stderr, "ERROR: invalid track length in header of track %s\n", track);
return NULL;
}
void* canno = malloc(header.clen);
bzero(canno, header.clen);
if ( header.clen > 0 )
{
if ( fread(canno, header.clen, 1, afile) != 1 )
{
fprintf(stderr, "ERROR: failed to read anno track %s\n", track);
return NULL;
}
}
fclose(afile);
// printf("header len %" PRIu64 " clen %" PRIu64 " cdlen %" PRIu64 "\n", header.len, header.clen, header.cdlen);
uint64 alen = header.size * (header.len + 1);
uint64* anno = malloc(alen);
bzero(anno, alen);
uncompress_chunks(canno, header.clen, anno, alen);
free(canno);
char* name = Catenate(db->path, ".", track, ".d2");
FILE* dfile = fopen(name, "r");
if (dfile == NULL)
{
fprintf(stderr, "ERROR: failed to open data file for track %s\n", track);
return NULL;
}
void* cdata = malloc(header.cdlen);
bzero(cdata, header.cdlen);
if ( header.cdlen > 0 )
{
if ( fread(cdata, header.cdlen, 1, dfile) != 1 )
{
fprintf(stderr, "ERROR: failed to read data track %s\n", track);
return NULL;
}
}
fclose(dfile);
void* data = malloc( anno[header.len] );
uncompress_chunks(cdata, header.cdlen, data, anno[header.len]);
free(cdata);
if ( db->ufirst > 1 )
{
memmove(anno, anno + db->ufirst, (db->nreads + 1) * sizeof(uint64));
uint64_t start = anno[0];
uint64_t end = anno[ db->nreads ];
int i;
for ( i = 0 ; i <= db->nreads ; i++ )
{
anno[i] -= start;
}
memmove(data, data + start, end - start);
}
HITS_TRACK* record = malloc(sizeof(HITS_TRACK));
record->next = db->tracks;
db->tracks = record;
record->name = strdup(track);
record->data = data;
record->anno = anno;
record->size = header.size;
return record;
}
void track_close(HITS_TRACK* track)
{
free(track->name);
free(track->anno);
free(track->data);
free(track);
}
char* track_name(HITS_DB* db, const char* track, int block)
{
char* name = (char*) malloc(PATH_MAX);
if (block > 0)
{
sprintf(name, "%s.%d.%s", db->path, block, track);
}
else
{
sprintf(name, "%s.%s", db->path, track);
}
return name;
}
int track_delete(HITS_DB* db, const char* track)
{
char* root_track = track_name(db, track, 0);
char path[PATH_MAX];
int suc = 1;
sprintf(path, "%s.a2", root_track);
if ( unlink(path) != 0 )
{
suc = 0;
}
sprintf(path, "%s.d2", root_track);
if ( unlink(path) != 0 )
{
suc = 0;
}
return suc;
}
void track_write(HITS_DB* db, const char* track, int block, track_anno* anno, track_data* data, uint64_t dlen)
{
uint64_t tlen = DB_NREADS(db);
char* path_track = track_name(db, track, block);
int end = strlen(path_track);
// offsets
strcat(path_track, ".a2");
FILE* afile = fopen(path_track, "w");
if (afile == NULL)
{
fprintf(stderr, "failed to open %s\n", path_track);
return;
}
track_anno_header ahead;
bzero(&ahead, sizeof(track_anno_header));
ahead.version = TRACK_VERSION_2;
ahead.len = tlen;
ahead.size = sizeof(track_anno);
if (fwrite(&ahead, sizeof(track_anno_header), 1, afile) != 1)
{
fprintf(stderr, "failed to write track header\n");
return;
}
void* canno;
uint64_t clen;
compress_chunks(anno, sizeof(track_anno) * (tlen + 1), &canno, &clen);
if (fwrite(canno, clen, 1, afile) != 1)
{
fprintf(stderr, "failed to write track data offsets\n");
return;
}
ahead.clen = clen;
free(canno);
// data
if (data != NULL)
{
strcpy(path_track + end, ".d2");
FILE* dfile = fopen(path_track, "w");
if (dfile == NULL)
{
fprintf(stderr, "failed to open %s\n", path_track);
return;
}
compress_chunks(data, sizeof(track_data) * dlen, &canno, &clen);
if (fwrite(canno, clen, 1, dfile) != 1)
{
fprintf(stderr, "failed to write track data of %" PRIu64 " (%" PRIu64 ") bytes\n", sizeof(track_data) * dlen, clen);
return;
}
ahead.cdlen = clen;
free(canno);
fclose(dfile);
}
else if ( dlen != 0 )
{
ahead.cdlen = dlen;
}
free(path_track);
rewind(afile);
if (fwrite(&ahead, sizeof(track_anno_header), 1, afile) != 1)
{
fprintf(stderr, "failed to write track header\n");
return;
}
fclose(afile);
}
static void write_track(HITS_DB* db, const char* track, int block, track_header_len tlen, track_anno* anno, track_data* data, uint64_t dlen)
{
char* path_track = track_name(db, track, block);
int end = strlen(path_track);
// offsets
strcat(path_track, ".anno");
FILE* fileTrack = fopen(path_track, "w");
if (fileTrack == NULL)
{
fprintf(stderr, "failed to open %s\n", path_track);
return;
}
track_header_size tsize = sizeof(track_anno);
if (fwrite(&tlen, sizeof(track_header_len), 1, fileTrack) != 1)
{
fprintf(stderr, "failed to write track header\n");
return;
}
if (fwrite(&tsize, sizeof(track_header_size), 1, fileTrack) != 1)
{
fprintf(stderr, "failed to write track header\n");
return;
}
if (fwrite(anno, sizeof(track_anno), tlen + 1, fileTrack) != (size_t)(tlen + 1))
{
fprintf(stderr, "failed to write track data offsets\n");
return;
}
fclose(fileTrack);
// data
strcpy(path_track + end, ".data");
if ((fileTrack = fopen(path_track, "w")) == NULL)
{
fprintf(stderr, "failed to open %s\n", path_track);
return;
}
if (fwrite(data, sizeof(track_data), dlen, fileTrack) != dlen)
{
fprintf(stderr, "failed to write track data\n");
return;
}
fclose(fileTrack);
free(path_track);
}
void write_track_trimmed(HITS_DB* db, const char* track, int block, track_anno* anno, track_data* data, uint64_t dlen)
{
write_track(db, track, block, db->nreads, anno, data, dlen);
}
void write_track_untrimmed(HITS_DB* db, const char* track, int block, track_anno* anno, track_data* data, uint64_t dlen)
{
write_track(db, track, block, DB_NREADS(db), anno, data, dlen);
}
|
MartinPippel/DAmar
|
db/DBsplit.c
|
<filename>db/DBsplit.c
/************************************************************************************\
* *
* Copyright (c) 2014, Dr. <NAME> (EWM). All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without modification, *
* are permitted provided that the following conditions are met: *
* *
* · Redistributions of source code must retain the above copyright notice, this *
* list of conditions and the following disclaimer. *
* *
* · Redistributions in binary form must reproduce the above copyright notice, this *
* list of conditions and the following disclaimer in the documentation and/or *
* other materials provided with the distribution. *
* *
* · The name of EWM may not be used to endorse or promote products derived from *
* this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY EWM ”AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, *
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND *
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL EWM BE LIABLE *
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS *
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY *
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING *
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN *
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
* *
* For any issues regarding this software and its use, contact EWM at: *
* *
* <NAME>r. *
* Bautzner Str. 122e *
* 01099 Dresden *
* GERMANY *
* Email: <EMAIL> *
* *
\************************************************************************************/
/*******************************************************************************************
*
* Split a .db into a set of sub-database blocks for use by the Dazzler:
* Divide the database <path>.db conceptually into a series of blocks referable to on the
* command line as <path>.1.db, <path>.2.db, ... If the -x option is set then all reads
* less than the given length are ignored, and if the -a option is not set then secondary
* reads from a given well are also ignored. The remaining reads are split amongst the
* blocks so that each block is of size -s * 1Mbp except for the last which necessarily
* contains a smaller residual. The default value for -s is 400Mbp because blocks of this
* size can be compared by our "overlapper" dalign in roughly 16Gb of memory. The blocks
* are very space efficient in that their sub-index of the master .idx is computed on the
* fly when loaded, and the .bps file of base pairs is shared with the master DB. Any
* tracks associated with the DB are also computed on the fly when loading a database block.
*
* Author: <NAME>
* Date : September 2013
* Mod : New splitting definition to support incrementality, and new stub file format
* Date : April 2014
*
********************************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "DB.h"
#ifdef HIDE_FILES
#define PATHSEP "/."
#else
#define PATHSEP "/"
#endif
extern char *optarg;
extern int optind, opterr, optopt;
static void usage()
{
fprintf(stderr, "usage: [-s<int(200)>] <path:db|dam>\n");
fprintf(stderr, " -s ... set block size of -s * 1Mbp (default: 200MBs)\n");
}
int main(int argc, char *argv[])
{
HITS_DB db, dbs;
int64 dbpos;
FILE *dbfile, *ixfile;
int status;
int SIZE = 200;
// parse arguments
{
int c;
opterr = 0;
while ((c = getopt(argc, argv, "s:")) != -1)
{
switch (c)
{
case 's':
{
SIZE = atoi(optarg);
if (SIZE <= 0)
{
fprintf(stderr, "invalid split size value of %d\n", SIZE);
exit(1);
}
}
break;
default:
fprintf(stderr, "[ERROR] Unsupported option: %s\n", argv[optind]);
usage();
exit(1);
}
}
if (optind + 1 > argc)
{
fprintf(stderr, "[ERROR] - Database is required!\n");
usage();
exit(1);
}
}
// Open db
status = Open_DB(argv[optind], &db);
if (status < 0)
{
fprintf(stderr, "[ERROR] Cannot open database %s\n", argv[optind]);
exit(1);
}
if (db.part > 0)
{
fprintf(stderr, "[ERROR] Cannot be called on a block: %s\n", argv[optind]);
exit(1);
}
{
char *pwd, *root;
char buffer[2 * MAX_NAME + 100];
int nfiles;
int i, nblocks;
pwd = PathTo(argv[optind]);
if (status)
{
root = Root(argv[optind], ".dam");
dbfile = Fopen(Catenate(pwd, "/", root, ".dam"), "r+");
}
else
{
root = Root(argv[optind], ".db");
dbfile = Fopen(Catenate(pwd, "/", root, ".db"), "r+");
}
ixfile = Fopen(Catenate(pwd, PATHSEP, root, ".idx"), "r+");
if (dbfile == NULL || ixfile == NULL)
exit(1);
free(pwd);
free(root);
if (fscanf(dbfile, DB_NFILE, &nfiles) != 1)
SYSTEM_READ_ERROR
for (i = 0; i < nfiles; i++)
if (fgets(buffer, 2 * MAX_NAME + 100, dbfile) == NULL)
SYSTEM_READ_ERROR
if (fread(&dbs, sizeof(HITS_DB), 1, ixfile) != 1)
SYSTEM_READ_ERROR
dbpos = ftello(dbfile);
if (fscanf(dbfile, DB_NBLOCK, &nblocks) == 1)
{
printf("You are about to overwrite the current partition settings. This\n");
printf("will invalidate any tracks, overlaps, and other derivative files.\n");
printf("Are you sure you want to proceed? [Y/N] ");
fflush(stdout);
if (fgets(buffer, 100, stdin) == NULL)
SYSTEM_READ_ERROR
if (index(buffer, 'n') != NULL || index(buffer, 'N') != NULL)
{
printf("Aborted\n");
fflush(stdout);
fclose(dbfile);
exit(1);
}
}
fseeko(dbfile, dbpos, SEEK_SET);
fprintf(dbfile, DB_NBLOCK, 0);
fprintf(dbfile, DB_PARAMS, (int64) SIZE);
}
{
HITS_READ *reads = db.reads;
int nreads = db.ureads;
int64 size, totlen;
int nblock, ireads, rlen, fno;
int i;
size = SIZE * 1000000ll;
nblock = 0;
totlen = 0;
ireads = 0;
fprintf(dbfile, DB_BDATA, 0);
for (i = 0; i < nreads; i++)
{
rlen = reads[i].rlen;
ireads += 1;
totlen += rlen;
if (totlen >= size)
{
fprintf(dbfile, DB_BDATA, i + 1);
totlen = 0;
ireads = 0;
nblock += 1;
}
}
if (ireads > 0)
{
fprintf(dbfile, DB_BDATA, nreads);
nblock += 1;
}
fno = fileno(dbfile);
if (ftruncate(fno, ftello(dbfile)) < 0)
SYSTEM_READ_ERROR
fseeko(dbfile, dbpos, SEEK_SET);
fprintf(dbfile, DB_NBLOCK, nblock);
rewind(ixfile);
fwrite(&dbs, sizeof(HITS_DB), 1, ixfile);
}
fclose(ixfile);
fclose(dbfile);
Close_DB(&db);
return 0;
}
|
MartinPippel/DAmar
|
utils/CTanalyze.c
|
<filename>utils/CTanalyze.c
/*
* analyzeContigs.c
*
* assign contigs into following sets: haploid, alternative, repeat
*
* use:
* self alignment information from contigs
* union of fixed reads that map to the contigs (derived from fixedReadOverlaps)
*
*
* Created on: 3 Aug 2017
* Author: pippel
*/
#include <ctype.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <assert.h>
#include "lib/colors.h"
#include "lib/oflags.h"
#include "lib/pass.h"
#include "lib/tracks.h"
#include "lib/utils.h"
#include "lib.ext/types.h"
#include "lib.ext/bitarr.h"
#include "utils/CTanalyze.h"
#undef DEBUG_STEP1A
#undef DEBUG_STEP1B
#define DEBUG_STEP1C
#define MAX(a,b) (((a)>(b))?(a):(b))
#define MIN(a,b) (((a)<(b))?(a):(b))
#define DEF_REPEATS_TRACK "repeats"
#define DEF_SPUR_LEN 50000
#define DEF_TIP_LEN 100000
#define DEF_ARG_F 10000
#define DEF_ARG_CRF 50
#define DEF_ARG_CL 50
#define DEF_ARG_L 100000 // ... minimum contig length, to be considered as a primary contig
#define DEF_ARG_N 5 // ... minimum number of contig reads, to be considered as a primary contig
#define DEF_ARG_P 100 // ... maximum repeat percentage, to be considered as a primary contig, not considered
//compare contigs by length, longest first
static int cmp_contig_length(const void* a, const void* b)
{
Contig* c1 = *(Contig**) a;
Contig* c2 = *(Contig**) b;
int cmp = c2->property.len - c1->property.len;
if (!cmp)
{
cmp = (c2->avgCov - c1->avgCov);
}
return cmp;
}
void initAnalyzeContext(AnalyzeContext *actx)
{
int i, j, k, l;
int numOfContigs = DB_NREADS(actx->corContigDB);
if (actx->VERBOSE)
printf("numOfContigs: %d\n", numOfContigs);
printf("allocate contig buffer");
Contig *contigs = (Contig*) malloc(sizeof(Contig) * numOfContigs);
actx->numContigs = numOfContigs;
bzero(contigs, sizeof(Contig) * numOfContigs);
// patched read IDs and Beg,End position from contig
track_anno* patchedRead_anno = actx->corContigPatchReadsAndPos_track->anno;
track_data* patchedRead_data = actx->corContigPatchReadsAndPos_track->data;
// corrected read IDs and Beg,End position from corrected contig
track_anno* correctedRead_anno = actx->corContigCorrectReadsAndPos_track->anno;
track_data* correctedRead_data = actx->corContigCorrectReadsAndPos_track->data;
printf(" - done\n");
printf("allocate VreadMask");
fflush(stdout);
actx->maxVReadMask = 100;
actx->vreadMask = (int**) malloc(sizeof(int*) * actx->maxVReadMask);
assert(actx->vreadMask != NULL);
for (i = 0; i < actx->maxVReadMask; i++)
{
actx->vreadMask[i] = (int *) malloc(sizeof(int) * DB_NREADS(actx->patchedReadDB));
bzero(actx->vreadMask[i], sizeof(int) * DB_NREADS(actx->patchedReadDB));
}
printf(" - done\n");
actx->readSeq = New_Read_Buffer(actx->corContigDB);
bzero(actx->readSeq, DB_READ_MAXLEN(actx->corContigDB));
// parse Contig File Names and Offset, must be done before getFileID is called the first time
actx->contigFileNamesAndOffsets = malloc(sizeof(FileNamesAndOffsets));
bzero(actx->contigFileNamesAndOffsets, sizeof(FileNamesAndOffsets));
parseDBFileNames(actx->corContigDBName, actx->contigFileNamesAndOffsets);
printf(" init contigs - START\n");
for (i = 0; i < numOfContigs; i++)
{
// init contigs with reads
Contig *contig = contigs + i;
contig->property.len = DB_READ_LEN(actx->corContigDB, i);
contig->property.contigID = i;
contig->property.repBasesFromContigLAS = getRepeatBasesFromInterval(actx, 1, i, 0, contig->property.len);
contig->property.pathID = getPathID(actx, i);
contig->property.fileID = getFileID(actx->contigFileNamesAndOffsets, i);
track_anno patched_rb, patched_re;
track_anno corrected_rb, corrected_re;
patched_rb = patchedRead_anno[i] / sizeof(track_data);
patched_re = patchedRead_anno[i + 1] / sizeof(track_data);
assert(patched_rb < patched_re);
corrected_rb = correctedRead_anno[i] / sizeof(track_data);
corrected_re = correctedRead_anno[i + 1] / sizeof(track_data);
assert(corrected_rb < corrected_re);
// get number of contig reads
contig->numcReads = (int) ((patched_re - patched_rb) / 3);
assert(contig->numcReads == (int) ((corrected_re - corrected_rb) / 3));
if (contig->numcReads == 0)
{
fprintf(stderr, "!strange! - no reads found for contig: %d. DISCARDED\n", i);
contig->property.cflag |= CLASS_CONTIG_DISCARD;
continue;
}
contig->numReadRelations = 0;
contig->maxReadRelations = 1;
contig->readRelations = (ReadRelation*) malloc(sizeof(ReadRelation) * contig->maxReadRelations);
contig->numContigRelations = 0;
contig->maxContigRelations = 0;
contig->contigRelations = NULL;
// init contig read buffer for overlapping reads
contig->cReads = (ContigRead*) malloc(sizeof(ContigRead) * contig->numcReads);
// init position buffer
if (contig->cReads == NULL)
{
fprintf(stderr, "[ERROR] - ananlyzeContigs: Unable to allocate read buffers for Contig %d!\n", i);
exit(1);
}
bzero(contig->cReads, sizeof(ContigRead) * contig->numcReads);
int cov = MAX((int )(1.5 * actx->exp_cov), 30);
for (j = 0, k = patched_rb; j < contig->numcReads; j++, k += 3)
{
ContigRead *cread = contig->cReads + j;
cread->type |= CLASS_READ_VALID;
cread->patchedID = patchedRead_data[k];
cread->correctedID = correctedRead_data[k];
if (j)
{
cread->patchedContigPosBeg = contig->cReads[j - 1].patchedContigPosEnd;
cread->patchedContigPosEnd = cread->patchedContigPosBeg + abs(patchedRead_data[k + 2] - patchedRead_data[k + 1]);
cread->correctedContigPosBeg = contig->cReads[j - 1].correctedContigPosEnd;
cread->correctedContigPosEnd = cread->correctedContigPosBeg + abs(correctedRead_data[k + 2] - correctedRead_data[k + 1]);
}
else
{
cread->patchedContigPosBeg = 0;
cread->patchedContigPosEnd = abs(patchedRead_data[k + 2] - patchedRead_data[k + 1]);
cread->correctedContigPosBeg = 0;
cread->correctedContigPosEnd = abs(correctedRead_data[k + 2] - correctedRead_data[k + 1]);
}
cread->correctedReadPosBeg = correctedRead_data[k + 1];
cread->correctedReadPosEnd = correctedRead_data[k + 2];
cread->ovlReads = (OvlRead*) malloc(cov * sizeof(OvlRead));
if (cread->ovlReads == NULL)
{
fprintf(stderr, "[ERROR] - ananlyzeContigs: Unable to allocate OvlRead buffer for Contig %d at patchedRead %d!\n", i, patchedRead_data[k]);
exit(1);
}
cread->maxOvlReads = cov;
// add repeat bases from patched-reads repeat track to cread
if (patchedRead_data[k + 1] < patchedRead_data[k + 2])
cread->repeatBases = getRepeatBasesFromInterval(actx, 0, cread->patchedID, patchedRead_data[k + 1], patchedRead_data[k + 2]);
else
cread->repeatBases = getRepeatBasesFromInterval(actx, 0, cread->patchedID, patchedRead_data[k + 2], patchedRead_data[k + 1]);
contig->property.repBasesFromReadLAS += cread->repeatBases;
// insert cRead into ovlReads, cBeg and cEnd will be later translated into absolute contig positions!
cread->ovlReads->patchedID = -patchedRead_data[k];
cread->ovlReads->beg = patchedRead_data[k + 1];
cread->ovlReads->end = patchedRead_data[k + 2];
cread->ovlReads->cBeg = cread->patchedContigPosBeg;
cread->ovlReads->cEnd = cread->patchedContigPosEnd;
cread->numOvlReads = 1;
// set vmaskread
l = 0;
while (l < actx->maxVReadMask && actx->vreadMask[l][patchedRead_data[k]] != 0)
l++;
if (l == actx->maxVReadMask)
{
printf("TERROR read %d is part of %d contigs!!!!", patchedRead_data[k], l);
actx->maxVReadMask++;
actx->vreadMask = (int**) realloc(actx->vreadMask, sizeof(int*) * actx->maxVReadMask);
actx->vreadMask[l] = (int *) malloc(sizeof(int) * DB_NREADS(actx->patchedReadDB));
bzero(actx->vreadMask[l], sizeof(int) * DB_NREADS(actx->patchedReadDB));
}
// store negative 1-based contig id
actx->vreadMask[l][patchedRead_data[k]] = -(i + 1);
}
if (actx->VERBOSE)
{
printf(
"STATS of contig %d reads (%d): [ unCorRead bpos epos len cBpos cEpos | corRead bpos epos len cBpos cEpos| corCumLen unCorCumLen | NReadRep PReadRep CumPReadRep ]\n",
i, contig->numcReads);
int corCumLen = 0;
int unCorCumLen = 0;
int unCorCumRepBases = 0;
for (j = 0; j < contig->numcReads; j++)
{
unCorCumLen += contig->cReads[j].patchedContigPosEnd - contig->cReads[j].patchedContigPosBeg;
corCumLen += contig->cReads[j].correctedContigPosEnd - contig->cReads[j].correctedContigPosBeg;
unCorCumRepBases += contig->cReads[j].repeatBases;
// uncorrected (patched) coordinates
printf("%8d", contig->cReads[j].patchedID);
printf(" %8d", contig->cReads[j].ovlReads[0].beg);
printf(" %8d", contig->cReads[j].ovlReads[0].end);
printf(" %5d", abs(contig->cReads[j].ovlReads[0].end - contig->cReads[j].ovlReads[0].beg));
printf(" %8d", contig->cReads[j].patchedContigPosBeg);
printf(" %8d", contig->cReads[j].patchedContigPosEnd);
// correx=cted coordinates
printf(" | %8d", contig->cReads[j].correctedID);
printf(" %8d", contig->cReads[j].correctedReadPosBeg);
printf(" %8d", contig->cReads[j].correctedReadPosEnd);
printf(" %5d", abs(contig->cReads[j].correctedReadPosEnd - contig->cReads[j].correctedReadPosBeg));
printf(" %8d", contig->cReads[j].correctedContigPosBeg);
printf(" %8d", contig->cReads[j].correctedContigPosEnd);
printf(" | %8d", corCumLen);
printf(" %8d", unCorCumLen);
printf(" %5.3f%%", unCorCumLen * 100.0 / corCumLen);
printf(" | %5d %2.f%% %.2f%%\n", contig->cReads[j].repeatBases,
contig->cReads[j].repeatBases * 100.0 / (contig->cReads[j].patchedContigPosEnd - contig->cReads[j].patchedContigPosBeg),
unCorCumRepBases * 100.0 / unCorCumLen);
}
printf(" --> len: %10d | fileID %4d | path %3d \n", contig->property.len, contig->property.fileID, contig->property.pathID);
}
//todo reduce this to actual number of relations
int numContigsOfCurSubgraph = getNumberOfSubgraphContigs(actx->contigFileNamesAndOffsets, i);
printf("numContigsOfCurSubgraph: %d\n", numContigsOfCurSubgraph);
contig->tourRelations = (TourRelation*) malloc(sizeof(TourRelation) * numContigsOfCurSubgraph);
bzero(contig->tourRelations, sizeof(TourRelation) * numContigsOfCurSubgraph);
}
printf("create touring relations\n");
// create Touring relations
for (i = 0; i < numOfContigs; i++)
{
Contig *contig = contigs + i;
printf("contig id %d, len %d\n", contig->property.contigID, contig->property.len);
int contigEndPathIdx1, contigEndPathIdx2;
getContigsEndIDs(actx, i, &contigEndPathIdx1, &contigEndPathIdx2);
printf("contigEndPathIdx1: %d, contigEndPathIdx2 %d \n", contigEndPathIdx1, contigEndPathIdx2);
printf("contig->property.fileID: %d\n", contig->property.fileID);
printf("actx->contigFileNamesAndOffsets->toDbIdx[contig->property.fileID] %d\n", actx->contigFileNamesAndOffsets->toDbIdx[contig->property.fileID]);
printf("actx->contigFileNamesAndOffsets->fromDbIdx[contig->property.fileID]: %d\n", actx->contigFileNamesAndOffsets->fromDbIdx[contig->property.fileID]);
fflush(stdout);
int numContigsOfCurSubgraph = actx->contigFileNamesAndOffsets->toDbIdx[contig->property.fileID]
- actx->contigFileNamesAndOffsets->fromDbIdx[contig->property.fileID] + 1;
printf("numContigsOfCurSubgraph: %d\n", numContigsOfCurSubgraph);
assert(MAX(contigEndPathIdx1, contigEndPathIdx2) <= numContigsOfCurSubgraph - 1);
// 1. bubble
if (contigEndPathIdx1 != -1 && contigEndPathIdx1 == contigEndPathIdx2)
{
int curPathID = contig->property.pathID;
Contig *relatedContig = contigs + i - (curPathID - contigEndPathIdx1);
assert(relatedContig != NULL);
assert(contigEndPathIdx1 == relatedContig->property.pathID);
contig->tourRelations[contig->numTourRelations].contigID1 = relatedContig->property.contigID;
contig->tourRelations[contig->numTourRelations].flag |= REL_TOUR_IS_BUBBLE;
contig->numTourRelations++;
relatedContig->tourRelations[relatedContig->numTourRelations].contigID1 = contig->property.contigID;
relatedContig->tourRelations[relatedContig->numTourRelations].flag |= REL_TOUR_HAS_BUBBLE;
relatedContig->numTourRelations++;
}
// 2. spur
else if ((contigEndPathIdx1 == -1 && contigEndPathIdx2 != -1) || (contigEndPathIdx1 != -1 && contigEndPathIdx2 == -1))
{
int curPathID = contig->property.pathID;
int curPathRelID = MAX(contigEndPathIdx1, contigEndPathIdx2);
Contig *relatedContig = contigs + i - (curPathID - curPathRelID);
assert(relatedContig != NULL);
assert(curPathRelID == relatedContig->property.pathID);
contig->tourRelations[contig->numTourRelations].contigID1 = relatedContig->property.contigID;
contig->tourRelations[contig->numTourRelations].flag |= REL_TOUR_IS_SPUR;
contig->numTourRelations++;
relatedContig->tourRelations[relatedContig->numTourRelations].contigID1 = contig->property.contigID;
relatedContig->tourRelations[relatedContig->numTourRelations].flag |= REL_TOUR_HAS_SPUR;
relatedContig->numTourRelations++;
}
// 3. link between two different contigs
else if (contigEndPathIdx1 != -1 && contigEndPathIdx2 != -1)
{
int curPathID = contig->property.pathID;
Contig *relatedContig1 = contigs + i - (curPathID - contigEndPathIdx1);
assert(relatedContig1 != NULL);
assert(contigEndPathIdx1 == relatedContig1->property.pathID);
Contig *relatedContig2 = contigs + i - (curPathID - contigEndPathIdx2);
assert(relatedContig2 != NULL);
assert(contigEndPathIdx2 == relatedContig2->property.pathID);
contig->tourRelations[contig->numTourRelations].contigID1 = relatedContig1->property.contigID;
contig->tourRelations[contig->numTourRelations].contigID2 = relatedContig2->property.contigID;
contig->tourRelations[contig->numTourRelations].flag |= REL_TOUR_IS_BRIDGE;
contig->numTourRelations++;
relatedContig1->tourRelations[relatedContig1->numTourRelations].contigID1 = contig->property.contigID;
relatedContig1->tourRelations[relatedContig1->numTourRelations].contigID2 = relatedContig2->property.contigID;
relatedContig1->tourRelations[relatedContig1->numTourRelations].flag |= REL_TOUR_HAS_BRIDGE;
relatedContig1->numTourRelations++;
relatedContig2->tourRelations[relatedContig2->numTourRelations].contigID1 = contig->property.contigID;
relatedContig2->tourRelations[relatedContig2->numTourRelations].contigID2 = relatedContig1->property.contigID;
relatedContig2->tourRelations[relatedContig2->numTourRelations].flag |= REL_TOUR_HAS_BRIDGE;
relatedContig2->numTourRelations++;
}
else if (contigEndPathIdx1 == -1 && contigEndPathIdx2 == -1)
{
contig->tourRelations[contig->numTourRelations].contigID1 = -1;
contig->tourRelations[contig->numTourRelations].flag |= REL_TOUR_UNIQUE;
contig->numTourRelations++;
}
}
printf(" init contigs - DONE\n");
actx->contigs = contigs;
printf("sort contigs by length - START\n");
// sort contig pointer according length (longest first)
actx->contigs_sorted = malloc(sizeof(Contig*) * actx->numContigs);
assert(actx->contigs_sorted != NULL);
for (i = 0; i < actx->numContigs; i++)
{
actx->contigs_sorted[i] = actx->contigs + i;
}
qsort(actx->contigs_sorted, actx->numContigs, sizeof(Contig*), cmp_contig_length);
printf("sort contigs by length - DONE\n");
}
char* getContigFastaFileName(AnalyzeContext *actx, Contig *contig)
{
int i;
for (i = 0; i < actx->contigFileNamesAndOffsets->numFileNames; i++)
{
if (contig->property.contigID >= actx->contigFileNamesAndOffsets->fromDbIdx[i] && contig->property.contigID <= actx->contigFileNamesAndOffsets->toDbIdx[i])
{
return actx->contigFileNamesAndOffsets->fileNames[i];
}
}
fprintf(stderr, "[ERROR] - Cannot find contig file name of contig %d\n", contig->property.contigID);
exit(1);
}
void parseDBFileNames(char *dbName, FileNamesAndOffsets *fileNamesAndOffsets)
{
// parse old database file and store bax names as well as their read offsets
assert(fileNamesAndOffsets != NULL);
FILE *f;
int numFiles = 0;
char name[MAX_NAME];
f = fopen(dbName, "r");
if (f == NULL) // try to add .db extension
{
sprintf(name, "%s.db", dbName);
f = fopen(name, "r");
}
if (f == NULL)
{
fprintf(stderr, "[ERROR] parseDBFileNames: Cannot open file %s for reading\n", dbName);
exit(1);
}
if (fscanf(f, DB_NFILE, &numFiles) != 1)
{
fprintf(stderr, "[ERROR] parseDBFileNames: Cannot parse \"%s\" from file %s.\n",
DB_NFILE, dbName);
fclose(f);
exit(1);
}
fileNamesAndOffsets->numFileNames = numFiles;
fileNamesAndOffsets->fromDbIdx = (int *) malloc(sizeof(int) * (numFiles));
memset(fileNamesAndOffsets->fromDbIdx, 0, numFiles);
fileNamesAndOffsets->toDbIdx = (int *) malloc(sizeof(int) * (numFiles));
memset(fileNamesAndOffsets->toDbIdx, 0, numFiles);
fileNamesAndOffsets->fileNames = (char **) malloc(sizeof(char*) * (numFiles));
fileNamesAndOffsets->fastaNames = (char **) malloc(sizeof(char*) * (numFiles));
int i;
for (i = 0; i < numFiles; i++)
{
fileNamesAndOffsets->fileNames[i] = (char*) malloc(sizeof(char) * MAX_NAME);
fileNamesAndOffsets->fastaNames[i] = (char*) malloc(sizeof(char) * MAX_NAME);
}
int prevOffset, curOffset;
prevOffset = 0;
for (i = 0; i < numFiles; i++)
{
if (fscanf(f, DB_FDATA, &curOffset, fileNamesAndOffsets->fileNames[i], fileNamesAndOffsets->fastaNames[i]) != 3)
{
fprintf(stderr, "[ERROR] parseDBFileNames: Cannot parse \"%s\" in line %d from file %s.\n",
DB_FDATA, i, dbName);
fclose(f);
exit(1);
}
assert(curOffset > prevOffset);
fileNamesAndOffsets->fromDbIdx[i] = prevOffset;
fileNamesAndOffsets->toDbIdx[i] = curOffset - 1;
printf("fileNamesAndOffsets[%d]: %d %d\n", i, fileNamesAndOffsets->fromDbIdx[i], fileNamesAndOffsets->toDbIdx[i]);
prevOffset = curOffset;
}
}
static void pre(PassContext* pctx, AnalyzeContext* actx)
{
actx->twidth = pctx->twidth;
}
ContigRead* getContigRead(Contig* contig, int readID)
{
int i;
for (i = 0; i < contig->numcReads; i++)
{
if (contig->cReads[i].patchedID == readID)
{
return contig->cReads + i;
}
}
return NULL;
}
int getFullReadPositionInContig(AnalyzeContext *actx, Contig* contig, int readID, int *cbeg, int *cend)
{
int rbeg;
int tbeg, tend;
get_trim(actx->patchedReadDB, actx->patchedReadTrim_track, readID, &tbeg, &tend);
int i, j;
int readPos = -1;
for (i = 0; i < contig->numcReads; i++)
{
if (contig->cReads[i].patchedID == readID)
{
readPos = i;
break;
}
}
assert(readPos >= 0 && readPos < contig->numcReads);
ContigRead *cread = contig->cReads + readPos;
// printf("reads %d %d %d %d %d cIdx: %d\n", reads->id, reads->cBeg, reads->cEnd, reads->beg, reads->end, readPos);
assert(abs(cread->patchedID) == readID);
if (cread->ovlReads->beg < cread->ovlReads->end) // forward orientation
{
*cend = cread->ovlReads->cEnd;
assert(cread->ovlReads->end == tend);
*cbeg = cread->ovlReads->cBeg;
if (cread->ovlReads->beg != tbeg) // try to find overlaps for readID with previous cReads
{
i = 1;
while (readPos - i >= 0)
{
// printf("try to find aread %d in overlaps with previous Cread %d at position %d\n", readID, neighborCread, readPos - i);
cread = contig->cReads + (readPos - i);
// printf("cur cread %d %d %d %d %d\n", reads->id, reads->cBeg, reads->cEnd, reads->beg, reads->end);
int found = 0;
for (j = 1; j < cread->numOvlReads; j++)
{
// printf("check %d c(%d,%d) r(%d, %d)\n", reads[j].id, reads[j].cBeg, reads[j].cEnd, reads[j].beg, reads[j].end);
if (cread->ovlReads[j].patchedID == readID)
{
// printf("found\n");
assert(*cbeg > cread->ovlReads[j].cBeg);
*cbeg = cread->ovlReads[j].cBeg;
found = 1;
// i.e. previous cread is in forward orientation
if (((cread->ovlReads->beg < cread->ovlReads->end)))
{
rbeg = cread->ovlReads[j].beg;
if (cread->ovlReads[j].beg == tbeg)
found = 2;
}
if (cread->ovlReads->beg > cread->ovlReads->end)
{
rbeg = cread->ovlReads[j].end;
if (cread->ovlReads[j].end == tbeg)
found = 2;
}
break; // found start of current readID in contig
}
}
if (found == 2)
{
// printf("iteration %d: found proper start of aread. i.e. proper cut position\n", i);
break;
}
if (found == 0)
{
if (abs(rbeg) - tbeg < 1000) // i.e. there is no overlap, due to the minimum overlap length of daligner
{
*cbeg = (*cbeg) - (abs(rbeg) - tbeg);
assert((*cbeg) >= 0 && (*cbeg) < (*cend) && (*cend) <= contig->property.len);
}
else
{
fprintf(stderr, "TERROR: iteration %d: UNABLE to find proper start of aread. i.e. unclear cut position. Remaining bases: %d\n", i,
abs(rbeg) - tbeg);
}
break;
}
i++;
}
}
}
else // reverse complement orientation
{
*cend = cread->ovlReads->cEnd;
assert(cread->ovlReads->end == tbeg);
*cbeg = cread->ovlReads->cBeg;
if (cread->ovlReads->beg != tend) // try to find overlaps for readID with previous cReads
{
i = 1;
while (readPos - i >= 0)
{
// int neighborCread = contig->contigReadIds[readPos - i];
// printf("try to find aread %d in overlaps with previous Cread %d at position %d\n", readID, neighborCread, readPos - i);
cread = contig->cReads + (readPos - i);
// printf("cur cread %d %d %d %d %d\n", reads->id, reads->cBeg, reads->cEnd, reads->beg, reads->end);
int found = 0;
for (j = 1; j < cread->numOvlReads; j++)
{
// printf("check %d c(%d,%d) r(%d, %d)\n", reads[j].id, reads[j].cBeg, reads[j].cEnd, reads[j].beg, reads[j].end);
if (cread->ovlReads[j].patchedID == readID)
{
// printf("found\n");
assert(*cbeg > cread->ovlReads[j].cBeg);
*cbeg = cread->ovlReads[j].cBeg;
found = 1;
// i.e. previous cread is in forward orientation
if (cread->ovlReads->beg < cread->ovlReads->end)
{
rbeg = cread->ovlReads[j].beg;
if (cread->ovlReads[j].beg == tend)
found = 2;
}
if (cread->ovlReads->beg > cread->ovlReads->end)
{
rbeg = cread->ovlReads[j].end;
if (cread->ovlReads[j].end == tend)
found = 2;
}
break; // found start of current readID in contig
}
}
if (found == 2)
{
// printf("iteration %d: found proper start of aread. i.e. proper cut position\n", i);
break;
}
if (found == 0)
{
if (tend - abs(rbeg) < 1000) // i.e. there is no overlap, due to the minimum overlap length of daligner
{
*cbeg = (*cbeg) - (tend - abs(rbeg));
assert((*cbeg) >= 0 && (*cbeg) < (*cend) && (*cend) <= contig->property.len);
}
else
{
fprintf(stderr, "TERROR: iteration %d: UNABLE to find proper start of aread. i.e. unclear cut position. Remaining bases: %d\n", i,
tend - abs(rbeg));
}
break;
}
i++;
}
}
}
return 0;
}
void getCorrespondingPositionInARead(AnalyzeContext *actx, Overlap *ovl, int* pos1, int *pos2)
{
int cBeg = *pos1;
int cEnd = *pos2;
int abeg = ovl->path.abpos;
int aend = ovl->path.aepos;
int bbeg = ovl->path.bbpos;
int bend = ovl->path.bepos;
int twidth = actx->twidth;
#ifdef DEBUG_STEP1A
printf("getCorrespondingPositionInARead %d x %d, c(%d, %d), a(%d, %d) b(%d, %d)", ovl->aread, ovl->bread, cBeg, cEnd, abeg, aend, bbeg, bend);
if (ovl->flags & OVL_COMP)
printf(" COMP");
printf("\n");
#endif
#ifdef DEBUG_STEP1A
printf("comp: bbeg: %d, bend: %d\n", bbeg, bend);
#endif
// find corresponding begin
if (cBeg <= bbeg)
{
#ifdef DEBUG_STEP1A
printf("cBeg <= bbeg, %d <= %d\n", cBeg, bbeg);
#endif
*pos1 = abeg;
}
else
{
if (ovl->path.tlen)
{
#ifdef DEBUG_STEP1A
printf("ccBeg: %d\n", cBeg);
#endif
ovl_trace* trace = ovl->path.trace;
int apos = abeg;
int bpos = ovl->path.bbpos;
int j = 0;
while (j < ovl->path.tlen)
{
apos = (apos / twidth + 1) * twidth;
bpos += trace[j + 1];
#ifdef DEBUG_STEP1A
printf("apos %6d, bpos %6d\n", apos, bpos);
#endif
if (bpos + twidth / 2 > cBeg)
{
apos += cBeg - bpos;
#ifdef DEBUG_STEP1A
printf("apos %6d, bpos %6d\n", apos, bpos);
#endif
*pos1 = -apos;
break;
}
j += 2;
}
}
else
{
if ((bend - cBeg) < (cBeg - bbeg))
{
*pos1 = -(abeg + (bend - cBeg));
}
else
{
*pos1 = -(aend - (cBeg - bbeg));
}
}
}
// find corresponding end
if (cEnd >= bend)
{
*pos2 = aend;
}
else
{
if (ovl->path.tlen)
{
#ifdef DEBUG_STEP1A
printf("ccBeg: %d\n", cEnd);
#endif
ovl_trace* trace = ovl->path.trace;
int apos = abeg;
int bpos = ovl->path.bbpos;
int j = 0;
while (j < ovl->path.tlen)
{
apos = (apos / twidth + 1) * twidth;
bpos += trace[j + 1];
#ifdef DEBUG_STEP1A
printf("apos %6d, bpos %6d\n", apos, bpos);
#endif
if (bpos + twidth / 2 > cEnd)
{
apos += cEnd - bpos;
#ifdef DEBUG_STEP1A
printf("apos %6d, bpos %6d\n", apos, bpos);
#endif
*pos2 = -apos;
break;
}
j += 2;
}
}
else
{
if ((bend - cEnd) < (cEnd - bbeg))
{
*pos2 = -(abeg + (bend - cEnd));
}
else
{
*pos2 = -(aend - (cEnd - bbeg));
}
}
}
#ifdef DEBUG_STEP1A
printf("final range: %d, %d\n", *pos1, *pos2);
#endif
}
void getCorrespondingPositionInBRead(AnalyzeContext *actx, Overlap *ovl, int* pos1, int *pos2)
{
int cBeg = *pos1;
int cEnd = *pos2;
int abeg = ovl->path.abpos;
int aend = ovl->path.aepos;
int bbeg = ovl->path.bbpos;
int bend = ovl->path.bepos;
int twidth = actx->twidth;
int transCBeg;
int transCEnd;
#ifdef DEBUG_STEP1A
{
printf("getCorrespondingPositionInBRead %d x %d, c(%d, %d), a(%d, %d) b(%d, %d)", ovl->aread, ovl->bread, cBeg, cEnd, abeg, aend, bbeg, bend);
if (ovl->flags & OVL_COMP)
printf(" COMP");
printf("\n");
}
#endif
// find begin
if (cBeg <= abeg)
{
transCBeg = bbeg;
#ifdef DEBUG_STEP1A
printf("begin: %d <= %d, set transCBeg to %d\n", cBeg, abeg, transCBeg);
#endif
}
else
{
if (ovl->path.tlen)
{
ovl_trace* trace = ovl->path.trace;
int apos = abeg;
int bpos = bbeg;
int bb = 0;
int j = 0;
while (j < ovl->path.tlen)
{
apos = (apos / twidth + 1) * twidth;
bpos += trace[j + 1];
bb = bpos;
#ifdef DEBUG_STEP1A
printf("apos %6d, bpos %6d\t bb %6d\n", apos, bpos, bb);
#endif
if (apos + twidth / 2 > cBeg)
{
bb += (cBeg - apos);
#ifdef DEBUG_STEP1A
printf("apos %6d, bpos %6d\t bb %6d\n", apos, bpos, bb);
#endif
transCBeg = -bb;
break;
}
j += 2;
}
}
else
{
#ifdef DEBUG_STEP1A
printf("path.tlen is 0. set transCBeg\n");
#endif
if ((cBeg - abeg) < (aend - cBeg))
{
transCBeg = -(bbeg + (cBeg - abeg));
}
else
{
transCBeg = -(bend - (aend - cBeg));
}
}
}
// find end
if (cEnd >= aend)
{
#ifdef DEBUG_STEP1A
printf("end: %d >0 %d\n", cEnd, aend);
#endif
transCEnd = bend;
}
else
{
if (ovl->path.tlen)
{
ovl_trace* trace = ovl->path.trace;
int apos = abeg;
int bpos = bbeg;
int bb = 0;
int j = 0;
while (j < ovl->path.tlen)
{
apos = (apos / twidth + 1) * twidth;
bpos += trace[j + 1];
bb = bpos;
#ifdef DEBUG_STEP1A
printf("apos %6d, bpos %6d\t bb %6d\n", apos, bpos, bb);
#endif
if (apos + twidth / 2 > cEnd)
{
bb += (cEnd - apos);
#ifdef DEBUG_STEP1A
printf("apos %6d, bpos %6d\t bb %6d\n", apos, bpos, bb);
#endif
transCEnd = -bb;
break;
}
j += 2;
}
}
else
{
#ifdef DEBUG_STEP1A
printf("transCEnd path.tlen is 0\n");
#endif
if ((aend - cEnd) < (cEnd - abeg))
{
transCEnd = -(bend - (aend - cEnd));
}
else
{
transCEnd = -(bbeg + (cEnd - abeg));
}
}
}
if (ovl->flags & OVL_COMP)
{
#ifdef DEBUG_STEP1A
printf("switch positions transCBeg: %d, transCEnd: %d\n", transCBeg, transCEnd);
#endif
*pos1 = DB_READ_LEN(actx->patchedReadDB, ovl->bread) - abs(transCBeg);
*pos2 = DB_READ_LEN(actx->patchedReadDB, ovl->bread) - abs(transCEnd);
if (transCBeg < 0)
(*pos1) = -(*pos1);
if (transCEnd < 0)
(*pos2) = -(*pos2);
}
else
{
*pos1 = transCBeg;
*pos2 = transCEnd;
}
#ifdef DEBUG_STEP1A
printf("getCorrespondingPositionInBRead: final range: %d, %d\n", *pos1, *pos2);
#endif
}
int processReadOverlapsAndMapThemToContigs(void* _ctx, Overlap* ovls, int novl)
{
AnalyzeContext* actx = (AnalyzeContext*) _ctx;
int i;
int aread = ovls->aread;
int bread;
for (i = 0; i < novl; i++)
{
Overlap *ovl = ovls + i;
bread = ovl->bread;
if (ovl->flags & OVL_DISCARD)
{
#ifdef DEBUG_STEP1A
printf("skip overlap %d x %d, DISCARD\n", aread, bread);
#endif
continue;
}
if (aread == bread)
{
#ifdef DEBUG_STEP1A
printf("skip identity overlap %d == %d\n", aread, bread);
#endif
continue;
}
/// TODO ugly hack, to ignore reads that overlap multiple times with the current a-read, actually they should be removed in LAfilter, why are they still there????
{
int j = i;
while (j + 1 < novl && (ovl->bread == ovls[j + 1].bread))
{
printf("ovl[%d] and ovl[%d] have same bread %d? 1(%d vs %d [%d, %d][%d,%d]) and 2(%d vs %d [%d, %d][%d,%d])\n", i, j + 1, ovl->bread, ovl->aread,
ovl->bread, ovl->path.abpos, ovl->path.aepos, ovl->path.bbpos, ovl->path.bepos, ovls[j + 1].aread, ovls[j + 1].bread, ovls[j + 1].path.abpos,
ovls[j + 1].path.aepos, ovls[j + 1].path.bbpos, ovls[j + 1].path.bepos);
j++;
}
if (j > i)
{
#ifdef DEBUG_STEP1A
printf("FUCK skip read %d. maps multiple times (%d) with current read %d\n", aread, j-i, bread);
#endif
i = j;
continue;
}
}
// check if a-read is present in any contig, if yes than add corresponding breads to the contigs
int j, k, l;
for (j = 0; actx->vreadMask[j][aread] < 0; j++)
{
int conId = abs(actx->vreadMask[j][aread]);
Contig * contig = actx->contigs + (conId - 1);
#ifdef DEBUG_STEP1A
printf("found aread %d in contig %d: (len: %d, rep: %d) bread %d\n", aread, conId - 1, contig->property.len,
getRepeatBasesFromInterval(actx, contig->property.contigID, 0, contig->property.len), bread);
#endif
// check if corresponding b-read is already visited
int found = 0;
for (k = 0; k < actx->maxVReadMask; k++)
{
if (abs(actx->vreadMask[k][bread]) == conId)
found = 1;
if (actx->vreadMask[k][bread] == 0)
break;
}
if (k == actx->maxVReadMask)
{
//printf("TERROR b-read %d is part of %d contigs!!!!\n", bread, k);
l = 0;
while (l < k)
{
// printf("read %d is part of contig %d\n", bread, actx->vreadMask[l][bread]);
l++;
}
//fflush(stdout);
actx->maxVReadMask++;
actx->vreadMask = (int**) realloc(actx->vreadMask, sizeof(int*) * actx->maxVReadMask);
actx->vreadMask[k] = (int *) malloc(sizeof(int) * DB_NREADS(actx->patchedReadDB));
bzero(actx->vreadMask[k], sizeof(int) * DB_NREADS(actx->patchedReadDB));
}
// which coordinates of the a-read are used within the contig
ContigRead *cread = getContigRead(contig, aread);
assert(cread != NULL);
int areadContigBeg = cread->patchedContigPosBeg;
int areadContigEnd = cread->patchedContigPosEnd;
int areadReadBeg = cread->ovlReads->beg;
int areadReadEnd = cread->ovlReads->end;
#ifdef DEBUG_STEP1A
printf("OVERLAP: %d vs %d [%8d, %8d] %c [%8d, %8d] l [%8d, %8d]\n",ovl->aread, ovl->bread, ovl->path.abpos, ovl->path.aepos, (ovl->flags & OVL_COMP) ? 'C' : 'N', ovl->path.bbpos, ovl->path.bepos,
DB_READ_LEN(actx->patchedReadDB, ovl->aread), DB_READ_LEN(actx->patchedReadDB, ovl->bread));
printf("Aread %d in contig %d: cPos [%d, %d] rPos: [%d, %d] %c\n", aread, contig->property.contigID, areadContigBeg, areadContigEnd, areadReadBeg, areadReadEnd, (areadReadBeg > areadReadEnd) ? 'C' : 'N');
printf("convert overlap coordinates from %d %d [%d, %d] %c [%d, %d]\n", ovl->aread, ovl->bread, ovl->path.abpos, ovl->path.aepos,
(ovl->flags & OVL_COMP) ? 'C' : 'N', ovl->path.bbpos, ovl->path.bepos);
#endif
// complement sequence
int cReadInComplement = 0;
if (areadReadBeg > areadReadEnd)
{
int tmp = areadReadBeg;
areadReadBeg = areadReadEnd;
areadReadEnd = tmp;
cReadInComplement = 1;
}
// do the a-read contig coordinates have an intersection with the b-read?
int intersection = intersect(areadReadBeg, areadReadEnd, ovl->path.abpos, ovl->path.aepos);
if (intersection == 0)
{
#ifdef DEBUG_STEP1A
printf("skip overlap %d x %d, No intersection\n", aread, bread);
#endif
continue;
}
// mark b-read for current contig as visited
if (!found)
actx->vreadMask[k][bread] = conId;
// check if OvlRead is already included due to transitivity
int check = 1;
{
int u;
for (u = 0; u < cread->numOvlReads; u++)
{
OvlRead *ovlU = cread->ovlReads + u;
if (ovlU->patchedID == bread)
{
check = 0;
break;
}
}
}
if (check)
{
// add valid bread to set of OvlReads (--> proper read for correction)
if (cread->numOvlReads == cread->maxOvlReads)
{
cread->maxOvlReads = (int) (cread->maxOvlReads * 1.2) + 10;
cread->ovlReads = (OvlRead*) realloc(cread->ovlReads, cread->maxOvlReads * sizeof(OvlRead));
if (cread->ovlReads == NULL)
{
fprintf(stderr, "[ERROR]: Unable to increase OvlRead buffer of contig %d at read: %d, from %lu to %lu!\n", conId, aread,
cread->numOvlReads * sizeof(OvlRead), cread->maxOvlReads * sizeof(OvlRead));
exit(1);
}
}
OvlRead *curOvlRead = cread->ovlReads + cread->numOvlReads;
curOvlRead->patchedID = bread;
int pos1, pos2;
int abeg, aend;
abeg = ovl->path.abpos;
aend = ovl->path.aepos;
pos1 = ovl->path.bbpos;
pos2 = ovl->path.bepos;
if (abeg < areadReadBeg)
abeg = areadReadBeg;
if (aend > areadReadEnd)
aend = areadReadEnd;
// contig read sticks in reverse complements in contig
if (cReadInComplement)
{
if (aend > areadReadEnd)
curOvlRead->cBeg = areadContigBeg;
else
curOvlRead->cBeg = areadContigBeg + (areadReadEnd - aend);
if (abeg < areadReadBeg)
curOvlRead->cEnd = areadContigEnd;
else
curOvlRead->cEnd = areadContigBeg + (areadReadEnd - abeg);
}
else
{
if (abeg < areadReadBeg)
curOvlRead->cBeg = areadContigBeg;
else
curOvlRead->cBeg = areadContigBeg + (abeg - areadReadBeg);
if (aend > areadReadEnd)
curOvlRead->cEnd = areadContigEnd;
else
curOvlRead->cEnd = areadContigEnd - (areadReadEnd - aend);
}
if (abeg != ovl->path.abpos || aend != ovl->path.aepos)
{
pos1 = abeg;
pos2 = aend;
#ifdef DEBUG_STEP1A
printf("getCorrespondingPositionInBRead(actx, ovl, &pos1, &pos2);\n");
getCorrespondingPositionInBRead(actx, ovl, &pos1, &pos2);
#endif
}
#ifdef DEBUG_STEP1A
printf("set pos1 to %d and pos2 to %d\n", pos1, pos2);
#endif
if (cReadInComplement)
{
curOvlRead->beg = pos2;
curOvlRead->end = pos1;
}
else
{
curOvlRead->beg = pos1;
curOvlRead->end = pos2;
}
cread->numOvlReads++;
assert(curOvlRead->cBeg < curOvlRead->cEnd);
assert(curOvlRead->cBeg >= cread->patchedContigPosBeg);
assert(curOvlRead->cEnd <= cread->patchedContigPosEnd);
#ifdef DEBUG_STEP1A
ContigRead *falk = getContigRead(contig, aread);
assert(falk != NULL);
printf("add overlap %d x %d, a(%d, %d), b(%d, %d), l(%d, %d), %c at ConPos [%d, %d] in Read [%d, %d]\n", aread, bread, ovl->path.abpos, ovl->path.aepos, ovl->path.bbpos,
ovl->path.bepos, DB_READ_LEN(actx->patchedReadDB, ovl->aread), DB_READ_LEN(actx->patchedReadDB, ovl->bread), (ovl->flags & OVL_COMP) ? 'c' : 'n',
falk->patchedContigPosBeg, falk->patchedContigPosEnd, falk->ovlReads->beg, falk->ovlReads->end);
printf("=======<<<< added OVL-B-read: %d %d-%d, in c%d-%d-%d %c %c crLen %d oLen %d ocrLen %d ocLen %d\n", curOvlRead->patchedID, curOvlRead->beg, curOvlRead->end, contig->property.contigID, curOvlRead->cBeg, curOvlRead->cEnd,
(cReadInComplement) ? 'C': 'N', (ovl->flags & OVL_COMP) ? 'C': 'N', cread->ovlReads->cEnd - cread->ovlReads->cBeg, ovl->path.aepos - ovl->path.abpos, curOvlRead->cEnd - curOvlRead->cBeg, abs(abs(curOvlRead->beg)-abs(curOvlRead->end)));
#endif
}
}
/// As there is no proper transitivity given, we have to check if one of the b-reads from all overlaps of the current
/// aread is part of a contig as well, and was not already incorporated as valid overlap
// check if b-read is present in any contig, if yes than add corresponding breads to the contigs
for (j = 0; actx->vreadMask[j][bread] < 0; j++)
{
int conId = abs(actx->vreadMask[j][bread]);
Contig * contig = actx->contigs + (conId - 1);
#ifdef DEBUG_STEP1A
printf("found bread %d in contig %d: (len: %d, rep: %d)\n", bread, conId - 1, contig->property.len,
getRepeatBasesFromInterval(actx, contig->property.contigID, 0, contig->property.len));
#endif
// check if corresponding a-read is already visited
int found = 0;
for (k = 0; k < actx->maxVReadMask; k++)
{
if (abs(actx->vreadMask[k][aread]) == conId)
found = 1;
if (actx->vreadMask[k][aread] == 0)
break;
}
if (k == actx->maxVReadMask)
{
//printf("TERROR a-read %d is part of %d contigs!!!!\n", aread, k);
l = 0;
while (l < k)
{
//printf("read %d is part of contig %d\n", aread, actx->vreadMask[l][aread]);
l++;
}
//fflush(stdout);
actx->maxVReadMask++;
actx->vreadMask = (int**) realloc(actx->vreadMask, sizeof(int*) * actx->maxVReadMask);
actx->vreadMask[k] = (int *) malloc(sizeof(int) * DB_NREADS(actx->patchedReadDB));
bzero(actx->vreadMask[k], sizeof(int) * DB_NREADS(actx->patchedReadDB));
}
ContigRead *cread = getContigRead(contig, bread);
assert(cread != NULL);
int breadContigBeg = cread->patchedContigPosBeg;
int breadContigEnd = cread->patchedContigPosEnd;
int breadReadBeg = cread->ovlReads->beg;
int breadReadEnd = cread->ovlReads->end;
#ifdef DEBUG_STEP1A
printf("OVERLAP: %d vs %d [%8d, %8d] %c [%8d, %8d] l [%8d, %8d]\n",ovl->aread, ovl->bread, ovl->path.abpos, ovl->path.aepos, (ovl->flags & OVL_COMP) ? 'C' : 'N', ovl->path.bbpos, ovl->path.bepos,
DB_READ_LEN(actx->patchedReadDB, ovl->aread), DB_READ_LEN(actx->patchedReadDB, ovl->bread));
printf("Bread %d in contig %d: cPos [%d, %d] rPos: [%d, %d]\n", bread, contig->property.contigID, breadContigBeg, breadContigEnd, breadReadBeg, breadReadEnd);
printf("convert overlap coordinates from %d %d [%d, %d] %c [%d, %d]\n", ovl->aread, ovl->bread, ovl->path.abpos, ovl->path.aepos,
(ovl->flags & OVL_COMP) ? 'C' : 'N', ovl->path.bbpos, ovl->path.bepos);
#endif
int bBeg, bEnd;
int cReadInComplement = 0;
// complement sequence
if (breadReadBeg > breadReadEnd)
{
int tmp = breadReadBeg;
breadReadBeg = breadReadEnd;
breadReadEnd = tmp;
cReadInComplement = 1;
}
#ifdef DEBUG_STEP1A
printf("cBeg: %d, cEnd: %d\n", breadContigBeg, breadContigEnd);
#endif
if (ovl->flags & OVL_COMP)
{
bBeg = DB_READ_LEN(actx->patchedReadDB, ovl->bread) - ovl->path.bepos;
bEnd = DB_READ_LEN(actx->patchedReadDB, ovl->bread) - ovl->path.bbpos;
}
else
{
bBeg = ovl->path.bbpos;
bEnd = ovl->path.bepos;
}
#ifdef DEBUG_STEP1A
printf("get intersection from %d in contig (%d, %d) and b(%d, %d)\n", bread, breadReadBeg, breadReadEnd, bBeg, bEnd);
#endif
int intersection = intersect(breadReadBeg, breadReadEnd, bBeg, bEnd);
if (intersection == 0)
{
continue;
}
// mark a-read for current contig as visited
if (!found)
actx->vreadMask[k][aread] = conId;
// check if we added the same OvlRead twice due to symmetry
int check = 1;
{
int u;
for (u = 0; u < cread->numOvlReads; u++)
{
OvlRead *ovlU = cread->ovlReads + u;
if (ovlU->patchedID == aread)
{
check = 0;
break;
}
}
}
if (check)
{
if (cread->numOvlReads == cread->maxOvlReads)
{
cread->maxOvlReads = (int) (cread->maxOvlReads * 1.2) + 10;
cread->ovlReads = (OvlRead*) realloc(cread->ovlReads, sizeof(OvlRead) * cread->maxOvlReads);
if (cread->ovlReads == NULL)
{
fprintf(stderr, "[ERROR]: Unable to increase OvlRead buffer of contig %d at read: %d, from %d to %d!\n", contig->property.contigID, bread,
cread->numOvlReads, cread->maxOvlReads);
exit(1);
}
}
// add valid a-read to set of OvlReads (--> proper read for correction)
OvlRead *curOvlRead = cread->ovlReads + cread->numOvlReads;
curOvlRead->patchedID = aread;
int pos1, pos2;
if (ovl->flags & OVL_COMP)
{
if (bEnd > breadReadEnd)
pos1 = DB_READ_LEN(actx->patchedReadDB, ovl->bread) - bEnd + (bEnd - breadReadEnd);
else
pos1 = DB_READ_LEN(actx->patchedReadDB, ovl->bread) - bEnd;
if (bBeg < breadReadBeg)
pos2 = DB_READ_LEN(actx->patchedReadDB, ovl->bread) - bBeg - (breadReadBeg - bBeg);
else
pos2 = DB_READ_LEN(actx->patchedReadDB, ovl->bread) - bBeg;
}
else
{
if (bBeg < breadReadBeg)
pos1 = breadReadBeg;
else
pos1 = bBeg;
if (bEnd > breadReadEnd)
pos2 = breadReadEnd;
else
pos2 = bEnd;
}
#ifdef DEBUG_STEP1A
printf("set pos1 to %d and pos2 to %d\n", pos1, pos2);
#endif
if (cReadInComplement)
{
if (bEnd > breadReadEnd)
curOvlRead->cBeg = breadContigBeg;
else
curOvlRead->cBeg = breadContigBeg + (breadReadEnd - bEnd);
if (bBeg < breadReadBeg)
curOvlRead->cEnd = breadContigEnd;
else
curOvlRead->cEnd = breadContigBeg + (breadReadEnd - bBeg);
}
else
{
if (bBeg < breadReadBeg)
curOvlRead->cBeg = breadContigBeg;
else
curOvlRead->cBeg = breadContigBeg + (bBeg - breadReadBeg);
if (bEnd > breadReadEnd)
curOvlRead->cEnd = breadContigEnd;
else
curOvlRead->cEnd = breadContigEnd - (breadReadEnd - bEnd);
}
getCorrespondingPositionInARead(actx, ovl, &pos1, &pos2);
if (cReadInComplement != (ovl->flags & OVL_COMP))
{
curOvlRead->beg = pos2;
curOvlRead->end = pos1;
}
else
{
curOvlRead->beg = pos1;
curOvlRead->end = pos2;
}
cread->numOvlReads++;
#ifdef DEBUG_STEP1A
ContigRead *falk = getContigRead(contig, bread);
assert(falk != NULL);
printf("add overlap %d x %d, a(%d, %d), b(%d, %d), l(%d, %d) %c at ConPos [%d, %d] in Read [%d, %d]\n", aread, bread, ovl->path.abpos, ovl->path.aepos, ovl->path.bbpos,
ovl->path.bepos, DB_READ_LEN(actx->patchedReadDB, ovl->aread), DB_READ_LEN(actx->patchedReadDB, ovl->bread), (ovl->flags & OVL_COMP) ? 'c' : 'n',
falk->patchedContigPosBeg, falk->patchedContigPosEnd, falk->ovlReads->beg, falk->ovlReads->end);
printf("=======>>>> added OVL-A-read: %d %d-%d, in c%d-%d-%d %c %c crLen %d oLen %d ocrLen %d ocLen %d\n", curOvlRead->patchedID, curOvlRead->beg, curOvlRead->end, contig->property.contigID, curOvlRead->cBeg, curOvlRead->cEnd,
(cReadInComplement) ? 'C': 'N', (ovl->flags & OVL_COMP) ? 'C': 'N', cread->ovlReads->cEnd - cread->ovlReads->cBeg, ovl->path.aepos - ovl->path.abpos, curOvlRead->cEnd - curOvlRead->cBeg, abs(abs(curOvlRead->beg)-abs(curOvlRead->end)));
#endif
}
}
}
return 1;
}
int cmpOVLreadById(const void *a, const void *b)
{
return ((const OvlRead*) a)->patchedID - ((const OvlRead*) b)->patchedID;
}
int getRepeatBasesFromInterval(AnalyzeContext* actx, int contigDB, int readID, int beg, int end)
{
track_anno* rep_anno;
track_data* rep_data;
if (contigDB)
{
rep_anno = actx->corContigRepeats_track->anno;
rep_data = actx->corContigRepeats_track->data;
if (readID < 0 || readID >= DB_NREADS(actx->corContigDB))
{
fprintf(stderr, "[ERROR] - getRepeatBasesFromInterval readID: %d out of bounds [0, %d]\n", readID, DB_NREADS(actx->corContigDB) - 1);
fflush(stderr);
exit(1);
}
}
else // patched reads db
{
rep_anno = actx->patchedReadRepeat_track->anno;
rep_data = actx->patchedReadRepeat_track->data;
if (readID < 0 || readID >= DB_NREADS(actx->patchedReadDB))
{
fprintf(stderr, "[ERROR] - getRepeatBasesFromInterval readID: %d out of bounds [0, %d]\n", readID, DB_NREADS(actx->patchedReadDB) - 1);
fflush(stderr);
exit(1);
}
}
track_anno rb, re;
int repBases = 0;
int rBeg, rEnd;
// repeat bases in a-read
rb = rep_anno[readID] / sizeof(track_data);
re = rep_anno[readID + 1] / sizeof(track_data);
while (rb < re)
{
rBeg = rep_data[rb];
rEnd = rep_data[rb + 1];
repBases += intersect(beg, end, rBeg, rEnd);
rb += 2;
}
return repBases;
}
void analyzeContigCoverageOfMappedReads(AnalyzeContext *actx)
{
int i, j, k;
// sort b-reads according read id and remove duplicates
for (i = 0; i < actx->numContigs; i++)
{
Contig *contig = actx->contigs + i;
if (contig->property.cflag & CLASS_CONTIG_DISCARD)
continue;
for (j = 0; j < contig->numcReads; j++)
{
qsort(contig->cReads[j].ovlReads, contig->cReads[j].numOvlReads, sizeof(OvlRead), cmpOVLreadById);
}
}
// TODO pass variable, set by user ?
int COV_BIN_SIZE = 500;
int MIN_COV = 1;
bit *inReads = ba_new(DB_NREADS(actx->patchedReadDB));
bit *outReads = ba_new(DB_NREADS(actx->patchedReadDB));
int *readCovHist = (int *) malloc(sizeof(int) * (DB_READ_MAXLEN(actx->patchedReadDB) / COV_BIN_SIZE + 1));
// update cBeg, End intervals for each B-read according global contig positions
for (i = 0; i < actx->numContigs; i++)
{
Contig *contig = actx->contigs + i;
if (contig->property.cflag & CLASS_CONTIG_DISCARD)
continue;
#ifdef DEBUG_STEP1B
printf("Contig %d, reads: %d\n", contig->property.contigID, contig->numcReads);
#endif
for (j = 0; j < contig->numcReads; j++)
{
ContigRead *cread = contig->cReads + j;
#ifdef DEBUG_STEP1B
printf("prev: %d cbe %d %d, be %d, %d", cread->patchedID, cread->patchedContigPosBeg, cread->patchedContigPosEnd, cread->ovlReads->beg,cread->ovlReads->end);
#endif
#ifdef DEBUG_STEP1B
printf(" comp? %d, crlen: %d, nOvlReads %d\n", crComp, DB_READ_LEN(actx->patchedReadDB, abs(cread->patchedID)), cread->numOvlReads);
#endif
for (k = 1; k < cread->numOvlReads; k++)
{
#ifdef DEBUG_STEP1B
printf("\t %d beg,end [%d, %d], cBeg,cEnd [%d, %d]\n", cread->ovlReads[k].patchedID, cread->ovlReads[k].beg, cread->ovlReads[k].end,
cread->ovlReads[k].cBeg, cread->ovlReads[k].cEnd);
#endif
}
{
int l, m;
// 1. analyze in-coverage and mark them as visited
ba_all_assign(inReads, DB_NREADS(actx->patchedReadDB), FALSE);
for (l = 1; l < cread->numOvlReads; l++)
{
if (cread->patchedContigPosBeg == cread->ovlReads[l].cBeg)
{
ba_assign(inReads, cread->ovlReads[l].patchedID, TRUE);
cread->nInReads++;
}
}
// 2. analyze intersection of out-reads from prev reads and in-reads of current read
if (j) // skip first contig read
{
/////
///// r_i r_j r_k r_l r_m
///// contigA: -------|-------|-------|-------|-------
///// --- | | | | fixed reads that overlap with each r_i, ... , r_m
///// --- | | | |
/// --- | | | |
///// 1 2 1 2 1 2 1 2 1 ... OUT reads (arrival rate) and 2 ... IN reads (start rate)
int intersect = 0;
/// loop over IN-reads of current contig read
for (l = 1; l < cread->numOvlReads; l++)
{
if (ba_value(outReads, cread->ovlReads[l].patchedID))
intersect++;
}
contig->cReads[j - 1].nComReadsWithNextContigRead = intersect;
}
// 3. analyze
// a) out-coverage and mark them as visited
// b) average coverage
// c) low coverage
ba_all_assign(outReads, DB_NREADS(actx->patchedReadDB), FALSE);
bzero(readCovHist, sizeof(int) * (DB_READ_MAXLEN(actx->patchedReadDB) / COV_BIN_SIZE + 1));
// todo add contig read as well --> i.e. in most cases the number of common exiting/entering reads is not zero
// ba_assign(outReads, cread->id, TRUE);
//3a) + 3b)
for (l = 1; l < cread->numOvlReads; l++)
{
if (cread->patchedContigPosEnd == cread->ovlReads[l].cEnd)
{
ba_assign(outReads, cread->ovlReads[l].patchedID, TRUE);
cread->nOutReads++;
}
cread->avgCov += cread->ovlReads[l].cEnd - cread->ovlReads[l].cBeg;
}
contig->avgCov += cread->avgCov;
cread->avgCov /= (cread->patchedContigPosEnd - cread->patchedContigPosBeg);
// 3c) i.e. create coverage histogram ...
//printf("Coverage Histogram for read: %d PreOut-CurIn-Cov %d,%d\n", contig->reads[k][0].id, curCheckPoint[curNum-1].nComReadsWithNextRead, curCheckPoint[curNum].nComReadsWithprevRead);
m = cread->patchedContigPosBeg;
while (m < cread->patchedContigPosEnd)
{
int cFrom, cTo;
cFrom = m;
if (m + COV_BIN_SIZE > cread->patchedContigPosEnd)
cTo = cread->patchedContigPosEnd;
else
cTo = cFrom + COV_BIN_SIZE;
int bin = (cFrom - cread->patchedContigPosBeg) / COV_BIN_SIZE;
// increase coverage count only if read fully spans histogram bin
for (l = 1; l < cread->numOvlReads; l++)
{
if (cread->ovlReads[l].cBeg <= cFrom && cread->ovlReads[l].cEnd >= cTo)
readCovHist[bin]++;
}
// printf("<%9d, %9d> c %3d\n", cFrom, cTo, readCovHist[bin]);
m = cTo;
}
// 3c) ... and check coverage drops
for (l = 0, m = cread->patchedContigPosBeg; m < cread->patchedContigPosEnd; l++, m += COV_BIN_SIZE)
{
if (readCovHist[l] < MIN_COV)
{
cread->lowCov = 1;
break;
}
}
}
}
// calculate average coverage of contig
contig->avgCov /= contig->property.len;
// if(contig->property.contigID == 0)
{
printf("STATS of contig %d\n", contig->property.contigID);
printf("avgCov: %.2f\n", contig->avgCov);
for (j = 0; j < contig->numcReads; j++)
{
ContigRead *cread = contig->cReads + j;
printf("%9d - %9d, id %10d, c[%9d, %9d] r[%6d,%6d] inR %10d, outR %d, allR %d, avgCov %.2f, comWNR %d\n", cread->patchedContigPosBeg,
cread->patchedContigPosEnd, cread->patchedID, cread->ovlReads->cBeg, cread->ovlReads->cEnd, cread->ovlReads->beg, cread->ovlReads->end,
cread->nInReads, cread->nOutReads, cread->numOvlReads, cread->avgCov, cread->nComReadsWithNextContigRead);
}
}
}
// cleanup read coverage buffers
free(readCovHist);
free(inReads);
free(outReads);
}
int cmpContigLength(const void *a, const void *b)
{
return ((const ContigIDAndLen*) b)->len - ((const ContigIDAndLen *) a)->len;
}
int getPathID(AnalyzeContext *actx, int contigID)
{
if (contigID < 0 || contigID >= DB_NREADS(actx->corContigDB))
{
fprintf(stderr, "[ERROR] - getPathID: contigID %d out of bounds [%d, %d [\n", contigID, 0, DB_NREADS(actx->corContigDB));
fflush(stderr);
exit(1);
}
if (Check_Track(actx->corContigDB, "path") != 0)
return -1;
HITS_TRACK * pathTrack = track_load(actx->corContigDB, "path");
assert(pathTrack != NULL);
track_anno* path_anno = pathTrack->anno;
track_data* path_data = pathTrack->data;
track_anno b, e;
b = path_anno[contigID] / sizeof(track_data);
e = path_anno[contigID + 1] / sizeof(track_data);
assert(b < e);
return (int) path_data[b];
}
int getFileID(FileNamesAndOffsets *fileAndNameOffset, int contigID)
{
assert(fileAndNameOffset != NULL);
assert(contigID >= 0 && contigID <= fileAndNameOffset->toDbIdx[fileAndNameOffset->numFileNames - 1]);
int i;
for (i = 0; i < fileAndNameOffset->numFileNames; i++)
{
if (contigID >= fileAndNameOffset->fromDbIdx[i] && contigID <= fileAndNameOffset->toDbIdx[i])
{
break;
}
}
return i;
}
int getNumberOfSubgraphContigs(FileNamesAndOffsets *fileAndNameOffset, int contigID)
{
assert(fileAndNameOffset != NULL);
assert(contigID >= 0 && contigID <= fileAndNameOffset->toDbIdx[fileAndNameOffset->numFileNames - 1]);
int i;
for (i = 0; i < fileAndNameOffset->numFileNames; i++)
{
if (contigID >= fileAndNameOffset->fromDbIdx[i] && contigID <= fileAndNameOffset->toDbIdx[i])
{
break;
}
}
return (fileAndNameOffset->toDbIdx[i] - fileAndNameOffset->fromDbIdx[i]) + 1;
}
void getContigsEndIDs(AnalyzeContext *actx, int contigID, int* beg, int *end)
{
if (contigID < 0 || contigID >= DB_NREADS(actx->corContigDB))
{
fprintf(stderr, "[ERROR] - getContigsEndIDs: contigID %d out of bounds [%d, %d [\n", contigID, 0, DB_NREADS(actx->corContigDB));
fflush(stderr);
exit(1);
}
if (Check_Track(actx->corContigDB, "ends") != 0)
return;
HITS_TRACK * pathTrack = track_load(actx->corContigDB, "ends");
assert(pathTrack != NULL);
track_anno* path_anno = pathTrack->anno;
track_data* path_data = pathTrack->data;
track_anno b, e;
b = path_anno[contigID] / sizeof(track_data);
e = path_anno[contigID + 1] / sizeof(track_data);
assert(b < e);
(*beg) = path_data[b];
(*end) = path_data[b + 1];
}
void analyzeContigCreadIntersection(AnalyzeContext *actx)
{
int j, k, l, m;
ContigIDAndLen *contigIDAndLength = (ContigIDAndLen*) malloc(sizeof(ContigIDAndLen) * actx->numContigs);
int numCL = 0;
// todo define a proper struct?
bit * contigJReads, *contigKReads, *contigIntersectionJKReads;
int * contigJBegRange, *contigJEndRange;
int * contigKBegRange, *contigKEndRange;
int * contigJCovHist, *contigKCovHist;
int binSize = 100;
// FIX: due to a very fragmented insect assembly, where the corrected vs uncorrected contig lengths differ significatntly, we have to increase the nBin by 20%
// TODO: keep track of longest uncorrected contig
int nBins = (DB_READ_MAXLEN(actx->corContigDB)*1.2 / binSize) + 1;
contigJCovHist = (int*) malloc(sizeof(int) * nBins);
contigKCovHist = (int*) malloc(sizeof(int) * nBins);
int numReads = DB_NREADS(actx->patchedReadDB);
contigJReads = ba_new(numReads); // all raw reads of contig J
contigKReads = ba_new(numReads); // all raw reads of contig K
contigIntersectionJKReads = ba_new(numReads); // all reads that are common in both contigs K and J
contigJBegRange = (int*) malloc(sizeof(int) * numReads);
contigJEndRange = (int*) malloc(sizeof(int) * numReads);
contigKBegRange = (int*) malloc(sizeof(int) * numReads);
contigKEndRange = (int*) malloc(sizeof(int) * numReads);
// int faId;
//for (faId = 0; faId < actx->contigFileNamesAndOffsets->numFileNames; faId++)
{
//#ifdef DEBUG_STEP1C
// printf("i %d, %d %d\n", faId, actx->contigFileNamesAndOffsets->fromDbIdx[faId], actx->contigFileNamesAndOffsets->toDbIdx[faId]);
//#endif
// if (actx->contigFileNamesAndOffsets->fromDbIdx[faId] == actx->contigFileNamesAndOffsets->toDbIdx[faId])
// {
//#ifdef DEBUG_STEP1C
// printf("fasta file %d: %s --> has only one contig\n", faId, actx->contigFileNamesAndOffsets->fileNames[faId]);
//#endif
// actx->contigs[actx->contigFileNamesAndOffsets->fromDbIdx[faId]].property.readRelationFlags |= READ_IS_UNIQUE;
// }
// else // at this point, current compound contains at least 2 contigs
{
numCL = 0;
// add all contigs from current connected compound (same file == subgraph)
// for (j = actx->contigFileNamesAndOffsets->fromDbIdx[faId]; j <= actx->contigFileNamesAndOffsets->toDbIdx[faId]; j++)
for (j = 0; j < actx->numContigs; j++)
{
Contig *contig = actx->contigs + j;
if (contig->property.cflag & CLASS_CONTIG_DISCARD)
continue;
contigIDAndLength[numCL].idx = contig->property.contigID;
contigIDAndLength[numCL].len = contig->property.len;
#ifdef DEBUG_STEP1C
printf("%d len: %d\n", contig->property.contigID, contig->property.len);
#endif
numCL++;
}
// sort contigs according length
qsort(contigIDAndLength, numCL, sizeof(contigIDAndLength), cmpContigLength);
// check
for (j = 0; j < numCL; j++)
{
Contig * contig_j = actx->contigs + contigIDAndLength[j].idx;
int jBins = (contig_j->property.len / binSize) + 1;
if (contig_j->property.cflag & CLASS_CONTIG_DISCARD)
continue;
// if (contig_j->property.len < 200000)
// continue;
#ifdef DEBUG_STEP1C
printf("Check against contig_j: %d, len %d\n", contig_j->property.contigID, contig_j->property.len);
#endif
// if (contig_j->gClassificFlag & CONTIG_IS_CONTAINED)
// {
//#ifdef DEBUG_STEP1C
// printf("Skip contig %d, already contained!\n", contig_j->property.contigID);
//#endif
// continue;
// }
ba_all_assign(contigJReads, numReads, FALSE);
memset(contigJBegRange, -1, sizeof(int) * numReads);
memset(contigJEndRange, -1, sizeof(int) * numReads);
// fill breads and positions for contig_j
for (k = 0; k < contig_j->numcReads; k++)
{
ContigRead *cread = contig_j->cReads + k;
#ifdef DEBUG_STEP1C
printf("contig_j %d cread %d [nBreads %d]\n", contig_j->property.contigID, cread->patchedID, cread->numOvlReads);
#endif
for (l = 0; l < cread->numOvlReads; l++)
{
int readID = abs(cread->ovlReads[l].patchedID);
ba_assign(contigJReads, readID, TRUE);
if (contigJBegRange[readID] < 0)
{
contigJBegRange[readID] = cread->ovlReads[l].cBeg;
contigJEndRange[readID] = cread->ovlReads[l].cEnd;
}
else
{
if (contigJBegRange[readID] > cread->ovlReads[l].cBeg)
contigJBegRange[readID] = cread->ovlReads[l].cBeg;
if (contigJEndRange[readID] < cread->ovlReads[l].cEnd)
contigJEndRange[readID] = cread->ovlReads[l].cEnd;
}
}
}
// compare all other contigs from current subgraph against contig_j
for (k = j + 1; k < numCL; k++)
{
Contig * contig_k = actx->contigs + contigIDAndLength[k].idx;
int kBins = (contig_k->property.len / binSize) + 1;
if (contig_k->property.cflag & CLASS_CONTIG_DISCARD)
continue;
if ((contig_k->property.rflag & (REL_READ_IS_ALT)))
continue;
// if (contig_k->property.len > 200000)
// continue;
//
// if (contig_k->numcReads < 5)
// continue;
// if (contig_k->gClassificFlag & CONTIG_IS_CONTAINED)
// {
//#ifdef DEBUG_STEP1C
// printf("Skip contig %d, already contained!\n", contig_k->property.contigID);
//#endif
// continue;
// }
ba_all_assign(contigKReads, numReads, FALSE);
memset(contigKBegRange, -1, sizeof(int) * numReads);
memset(contigKEndRange, -1, sizeof(int) * numReads);
for (l = 0; l < contig_k->numcReads; l++)
{
ContigRead *cread = contig_k->cReads + l;
#ifdef DEBUG_STEP1C
printf("contig_k %d add breads for cread %d\n", contig_k->property.contigID, cread->patchedID);
#endif
for (m = 0; m < cread->numOvlReads; m++)
{
int readID = abs(cread->ovlReads[m].patchedID);
ba_assign(contigKReads, readID, TRUE);
if (contigKBegRange[readID] < 0)
{
contigKBegRange[readID] = cread->ovlReads[m].cBeg;
contigKEndRange[readID] = cread->ovlReads[m].cEnd;
}
else
{
if (contigKBegRange[readID] > cread->ovlReads[m].cBeg)
contigKBegRange[readID] = cread->ovlReads[m].cBeg;
if (contigKEndRange[readID] < cread->ovlReads[m].cEnd)
contigKEndRange[readID] = cread->ovlReads[m].cEnd;
}
}
}
// get read intersection between contig_k and contig_j
ba_intersection(contigKReads, contigJReads, &contigIntersectionJKReads, numReads, numReads);
int numComReads = ba_count(contigIntersectionJKReads, numReads);
int numkReads = ba_count(contigKReads, numReads);
if (numComReads * 100.0 / numkReads > 1.0)
{
memset(contigJCovHist, 0, sizeof(int) * (nBins));
memset(contigKCovHist, 0, sizeof(int) * (nBins));
int numCovIvlJ = 0;
int *covIvlJ = (int*) malloc(sizeof(int) * ((numCovIvlJ + 1) * 3));
int numCovIvlK = 0;
int *covIvlK = (int*) malloc(sizeof(int) * ((numCovIvlK + 1) * 3));
for (l = 0; l < numReads; l++)
{
if (ba_value(contigIntersectionJKReads, l))
{
int from = contigJBegRange[l] / binSize;
int to = contigJEndRange[l] / binSize;
// if (from < 0)
// {
// printf("contigIntersectionJKReads Jrange failed for read %d: from %d to %d\n", l, from, to);
// }
// if (to >= nBins)
// {
// printf("contigIntersectionJKReads Jrange failed for read %d: from %d to %d\n", l, from, to);
// }
while (from <= to)
{
contigJCovHist[from]++;
from++;
}
from = contigKBegRange[l] / binSize;
to = contigKEndRange[l] / binSize;
// if (from < 0)
// {
// printf("contigIntersectionJKReads Krange failed for read %d: from %d to %d\n", l, from, to);
// }
//
// if (to >= nBins)
// {
// printf("contigIntersectionJKReads Krange failed for read %d: from %d to %d\n", l, from, to);
// }
while (from <= to)
{
contigKCovHist[from]++;
from++;
}
}
}
#ifdef DEBUG_STEP1C
printf("analyze contigs: %d p%d (cov %.2f) %d p%d (cov %.2f) len %d %d --> numOfcommonReads: %d of %d: %.3f\n", contig_j->property.contigID,
contig_j->property.pathID, contig_j->avgCov, contig_k->property.contigID, contig_k->property.pathID, contig_k->avgCov, contig_j->property.len,
contig_k->property.len, numComReads, numkReads, numComReads * 100.0 / numkReads);
printf("contigKCovHist:\n");
#endif
int firstKbin, lastKbin, firstJbin, lastJbin;
int cumHistKreads, cumHistJreads;
cumHistKreads = cumHistJreads = 0;
firstKbin = lastKbin = firstJbin = lastJbin = -1;
for (l = 0; l < kBins; l++)
{
if (contigKCovHist[l] > 0)
{
if (firstKbin == -1)
firstKbin = l;
lastKbin = l;
cumHistKreads += contigKCovHist[l];
//#ifdef DEBUG_STEP1C
// printf("%10d-%10d: %4d\n", l * binSize, (l * binSize) + binSize - 1, contigKCovHist[l]);
//#endif
}
else if (firstKbin != -1) // add coverage block
{
covIvlK[numCovIvlK * 3] = firstKbin * binSize;
covIvlK[numCovIvlK * 3 + 1] = lastKbin * binSize + (binSize - 1);
covIvlK[numCovIvlK * 3 + 2] = cumHistKreads / (lastKbin - firstKbin + 1);
numCovIvlK++;
covIvlK = (int*) realloc(covIvlK, sizeof(int) * ((numCovIvlK + 1) * 3));
firstKbin = -1;
cumHistKreads = 0;
}
}
if (firstKbin != -1)
{
covIvlK[numCovIvlK * 3] = firstKbin * binSize;
covIvlK[numCovIvlK * 3 + 1] = lastKbin * binSize + (binSize - 1);
covIvlK[numCovIvlK * 3 + 2] = cumHistKreads / (lastKbin - firstKbin + 1);
numCovIvlK++;
}
//#ifdef DEBUG_STEP1C
// printf("contigJCovHist:\n");
//#endif
for (l = 0; l < jBins; l++)
{
if (contigJCovHist[l] > 0)
{
if (firstJbin == -1)
firstJbin = l;
cumHistJreads += contigJCovHist[l];
lastJbin = l;
//#ifdef DEBUG_STEP1C
// printf("%10d-%10d: %4d\n", l * binSize, (l * binSize) + binSize - 1, contigJCovHist[l]);
//#endif
}
else if (firstJbin != -1)
{
covIvlJ[numCovIvlJ * 3] = firstJbin * binSize;
covIvlJ[numCovIvlJ * 3 + 1] = lastJbin * binSize + (binSize - 1);
covIvlJ[numCovIvlJ * 3 + 2] = cumHistJreads / (lastJbin - firstJbin + 1);
numCovIvlJ++;
covIvlJ = (int*) realloc(covIvlJ, sizeof(int) * ((numCovIvlJ + 1) * 3));
firstJbin = -1;
cumHistJreads = 0;
}
}
if (firstJbin != -1)
{
covIvlJ[numCovIvlJ * 3] = firstJbin * binSize;
covIvlJ[numCovIvlJ * 3 + 1] = lastJbin * binSize + (binSize - 1);
covIvlJ[numCovIvlJ * 3 + 2] = cumHistJreads / (lastJbin - firstJbin + 1);
numCovIvlJ++;
}
#ifdef DEBUG_STEP1C
printf("common reads for both contigs\n");
m = 0;
for (l = 0; l < numReads; l++)
{
if (ba_value(contigIntersectionJKReads, l))
{
printf("%4d: c %7d vs c %7d read: %7d [%7d, %7d] --> [%7d, %7d]\n", m++, contig_j->property.contigID, contig_k->property.contigID, l,
contigJBegRange[l], contigJEndRange[l], contigKBegRange[l], contigKEndRange[l]);
}
}
#endif
int cumKGapBases = covIvlK[0] + contig_k->property.len - covIvlK[3 * numCovIvlK - 2];
int cumKCoveredBases = 0;
for (l = 0; l < numCovIvlK; l++)
{
#ifdef DEBUG_STEP1C
printf("CoveredBasesInK [%8d, %8d, cov %3d]\n", covIvlK[l * 3], covIvlK[l * 3 + 1], covIvlK[l * 3 + 2]);
#endif
cumKCoveredBases += (covIvlK[l * 3 + 1] - covIvlK[l * 3]);
if (l + 1 < numCovIvlK)
cumKGapBases += (covIvlK[(l + 1) * 3] - covIvlK[l * 3 + 1]);
}
#ifdef DEBUG_STEP1C
printf("cumKGapBases %d (%.2f%%) cumKCoveredBases %d (%.2f%%)\n", cumKGapBases, cumKGapBases * 100.0 / contig_k->property.len, cumKCoveredBases,
cumKCoveredBases * 100.0 / contig_k->property.len);
#endif
int cumJGapBases = 0;
int cumJCoveredBases = 0;
for (l = 0; l < numCovIvlJ; l++)
{
#ifdef DEBUG_STEP1C
printf("CoveredBasesInJ [%8d, %8d, cov %3d]\n", covIvlJ[l * 3], covIvlJ[l * 3 + 1], covIvlJ[l * 3 + 2]);
#endif
cumJCoveredBases += (covIvlJ[l * 3 + 1] - covIvlJ[l * 3]);
if (l + 1 < numCovIvlJ)
cumJGapBases += (covIvlJ[(l + 1) * 3] - covIvlJ[l * 3 + 1]);
}
#ifdef DEBUG_STEP1C
printf("cumJGapBases %d (%.2f%%) cumJCoveredBases %d (%.2f%%)\n", cumJGapBases, cumJGapBases * 100.0 / (covIvlJ[3 * numCovIvlJ - 2] - covIvlJ[0]),
cumJCoveredBases, cumJCoveredBases * 100.0 / (covIvlJ[3 * numCovIvlJ - 2] - covIvlJ[0]));
#endif
// preliminary classification
// contig k is contained in J
if (numComReads * 100.0 / numkReads > actx->contByReads_CommonReadFraction
|| (cumKCoveredBases * 100.0 / contig_k->property.len >= actx->contByReads_CoveredLenPerc))
{
int preClassFlagK = REL_READ_IS_ALT;
int preClassFlagJ = REL_READ_HAS_ALT;
if (contig_k->numReadRelations == contig_k->maxReadRelations)
{
contig_k->maxReadRelations = (int) (contig_k->maxReadRelations * 1.2) + 5;
contig_k->readRelations = (ReadRelation*) realloc(contig_k->readRelations, sizeof(ReadRelation) * contig_k->maxReadRelations);
}
int num = contig_k->numReadRelations;
contig_k->property.rflag |= preClassFlagK;
contig_k->readRelations[num].flag = preClassFlagK;
contig_k->readRelations[num].numCoveredIntervals = numCovIvlK;
contig_k->readRelations[num].coveredIntervals = covIvlK;
contig_k->readRelations[num].correspID = contig_j->property.contigID;
contig_k->readRelations[num].nJointReads = numComReads;
contig_k->numReadRelations++;
// store corresponding info for contig J
if (contig_j->numReadRelations == contig_j->maxReadRelations)
{
contig_j->maxReadRelations = (int) (contig_j->maxReadRelations * 1.2) + 5;
contig_j->readRelations = (ReadRelation*) realloc(contig_j->readRelations, sizeof(ReadRelation) * contig_j->maxReadRelations);
}
num = contig_j->numReadRelations;
contig_j->property.rflag |= preClassFlagJ;
contig_j->readRelations[num].flag = preClassFlagJ;
contig_j->readRelations[num].numCoveredIntervals = numCovIvlJ;
contig_j->readRelations[num].coveredIntervals = covIvlJ;
contig_j->readRelations[num].correspID = contig_k->property.contigID;
contig_j->readRelations[num].nJointReads = numComReads;
contig_j->numReadRelations++;
}
}
}
}
}
}
// cleanup
free(contigIDAndLength);
free(contigJReads);
free(contigKReads);
free(contigIntersectionJKReads);
free(contigJBegRange);
free(contigJEndRange);
free(contigKEndRange);
free(contigKBegRange);
}
int compareInt(const void * a, const void * b)
{
return (*(int*) a - *(int*) b);
}
int contained(int ab, int ae, int bb, int be)
{
if (ab >= bb && ae <= be)
{
return 1;
}
return 0;
}
int analyzeContigVsContigOverlaps(void* _ctx, Overlap* ovls, int novl)
{
AnalyzeContext* actx = (AnalyzeContext*) _ctx;
if (actx->contigs[ovls->aread].property.cflag & CLASS_CONTIG_DISCARD)
return 1;
if (actx->VERBOSE)
printf("BEGIN -- Analyze overlaps for contig: %d numOvls: %d\n", ovls->aread, novl);
Contig *conA = actx->contigs + ovls->aread;
// speed up things for long contigs
int i, j, k;
j = k = 0;
while (j < novl)
{
while (k < novl - 1 && ovls[j].bread == ovls[k + 1].bread)
k++;
Overlap *o1, *o2;
o1 = ovls + j;
int fail = 0;
int properBegA = 1;
int properEndA = 1;
int properBegB = 1;
int properEndB = 1;
int overlapBasesA = 0;
int overlapBasesB = 0;
int properGapLen = 1;
if (o1->path.abpos > actx->nFuzzBases)
{
properBegA = 0;
}
if (o1->path.bbpos > actx->nFuzzBases)
{
properBegB = 0;
}
if (ovls[k].path.aepos + actx->nFuzzBases < DB_READ_LEN(actx->corContigDB, ovls[j].aread))
{
properEndA = 0;
}
if (ovls[k].path.bepos + actx->nFuzzBases < DB_READ_LEN(actx->corContigDB, ovls[j].bread))
{
properEndB = 0;
}
overlapBasesA = o1->path.aepos - o1->path.abpos;
overlapBasesB = o1->path.bepos - o1->path.bbpos;
for (i = j + 1; i <= k; i++)
{
o2 = ovls + i;
overlapBasesA += o2->path.aepos - o2->path.abpos;
overlapBasesB += o2->path.bepos - o2->path.bbpos;
// validate oriantation
if ((o1->flags & OVL_COMP) != (o2->flags & OVL_COMP))
{
fail = 1;
break;
}
// validate direction
if (o1->path.abpos > o2->path.abpos || o1->path.bbpos > o2->path.bbpos || o1->path.aepos > o2->path.aepos || o1->path.bepos > o2->path.bepos)
{
fail = 2;
break;
}
// validate overlap between overlaps - A-coordinates
int len = o1->path.aepos - o2->path.abpos;
if (len > 0) // there is an overlap of neighboring alignments
{
if (len > MIN(o1->path.aepos - o1->path.abpos, o2->path.aepos - o2->path.abpos))
{
fail = 3;
break;
}
overlapBasesA -= len;
}
else // there is a gap between neighboring alignments
{
if (abs(len) > actx->nFuzzBases)
{
fail = 4;
break;
}
}
// validate overlap between overlaps - A-coordinates
len = o1->path.bepos - o2->path.bbpos;
if (len > 0) // there is an overlap of neighboring alignments
{
if (len > MIN(o1->path.bepos - o1->path.bbpos, o2->path.bepos - o2->path.bbpos))
{
fail = 5;
break;
}
overlapBasesB -= len;
}
else // there is a gap between neighboring alignments
{
if (abs(len) > actx->nFuzzBases)
{
fail = 6;
break;
}
}
o1 = o2;
}
Contig *conB = actx->contigs + ovls[j].bread;
int validContainment = 0;
int validBridge = 0;
int validRepeatContainment = 0;
if (properGapLen)
{
if (overlapBasesA >= (int) (actx->contByContigs_CoveredLenPerc / 100.0 * conA->property.len))
{
validContainment = 1;
}
// contigA ----------------
// contigB ---------
// min 50Kb overlap, both overhangs min 100Kb
else if (properBegA && !properEndA && properEndB && !properBegB && MAX(overlapBasesA, overlapBasesB) >= MIN(50000, 3 * actx->nFuzzBases)
&& ovls[k].path.aepos + 100000 < conA->property.len && ovls[j].path.bbpos - 100000 > 0)
{
validBridge = 1;
}
// contigA ----------------
// contigB ------------
// min 50Kb overlap, both overhangs min 100Kb
else if (!properBegA && properEndA && !properEndB && properBegB && MAX(overlapBasesA, overlapBasesB) >= MIN(50000, 3 * actx->nFuzzBases)
&& ovls[j].path.abpos - 100000 > 0 && ovls[k].path.bepos + 100000 < conB->property.len)
{
validBridge = 1;
}
}
if (!validBridge && !validContainment)
{
if ((fail == 0 || fail == 4 || fail == 6) && overlapBasesA >= (int) (0.4 * conA->property.len)
&& (MAX(conA->property.repBasesFromReadLAS,conA->property.repBasesFromContigLAS) / 100.0 * conA->property.len > actx->maxPrimContigRepeatPerc))
{
validRepeatContainment = 1;
}
}
if ((!fail && (validBridge || validContainment)) || validRepeatContainment)
{
if (conA->numContigRelations == conA->maxContigRelations)
{
conA->maxContigRelations = conA->maxContigRelations * 1.2 + 5;
conA->contigRelations = (ContigRelation*) realloc(conA->contigRelations, sizeof(ContigRelation) * conA->maxContigRelations);
bzero(conA->contigRelations + conA->numContigRelations, sizeof(ContigRelation) * (conA->maxContigRelations - conA->numContigRelations));
}
ContigRelation *crel = conA->contigRelations + conA->numContigRelations;
if (validContainment)
{
crel->flag |= REL_CONTIG_IS_ALT;
conA->property.rflag |= REL_CONTIG_IS_ALT;
}
else if (validBridge)
{
crel->flag |= REL_CONTIG_BRIDGE;
conA->property.rflag |= REL_CONTIG_BRIDGE;
}
else
{
crel->flag |= REL_CONTIG_IS_REPEAT_ALT;
conA->property.rflag |= REL_CONTIG_IS_REPEAT_ALT;
}
crel->corContigIdx = conB->property.contigID;
crel->numPos = (k - j + 1);
crel->abpos = (int*) malloc(sizeof(int) * (crel->numPos) * 4);
crel->aepos = crel->abpos + crel->numPos;
crel->bbpos = crel->aepos + crel->numPos;
crel->bepos = crel->bbpos + crel->numPos;
int cumAaln = ovls[j].path.aepos - ovls[j].path.abpos;
// add first coordinates
crel->abpos[0] = ovls[j].path.abpos;
crel->aepos[0] = ovls[j].path.aepos;
// add further coordinates, but subtract ovlapping neighboring overlaps
for (i = 1; i < crel->numPos; i++)
{
crel->abpos[i] = ovls[j + i].path.abpos;
crel->aepos[i] = ovls[j + i].path.aepos;
cumAaln += crel->aepos[i] - crel->abpos[i];
if (crel->abpos[i] < crel->aepos[i - 1])
{
cumAaln -= (crel->aepos[i - 1] - crel->abpos[i]);
}
}
int cumBaln;
if (ovls[k].flags & OVL_COMP)
{
cumBaln = ovls[j].path.bepos - ovls[j].path.bbpos;
crel->bbpos[0] = conB->property.len - ovls[j].path.bbpos;
crel->bepos[0] = conB->property.len - ovls[j].path.bepos;
for (i = 1; i < crel->numPos; i++)
{
crel->bbpos[i] = conB->property.len - ovls[j + i].path.bbpos;
crel->bepos[i] = conB->property.len - ovls[j + i].path.bepos;
cumBaln += crel->bbpos[i] - crel->bepos[i];
if (crel->bepos[i - 1] < crel->bbpos[i])
{
cumBaln -= (crel->bbpos[i] - crel->bepos[i - 1]);
}
}
}
else
{
cumBaln = ovls[j].path.bepos - ovls[j].path.bbpos;
crel->bbpos[0] = ovls[j].path.bbpos;
crel->bepos[0] = ovls[j].path.bepos;
for (i = 1; i < crel->numPos; i++)
{
crel->bbpos[i] = ovls[j + i].path.bbpos;
crel->bepos[i] = ovls[j + i].path.bepos;
cumBaln += crel->bepos[i] - crel->bbpos[i];
if (crel->bbpos[i] < crel->bepos[i - 1])
{
cumBaln -= (crel->bepos[i - 1] - crel->bbpos[i]);
}
}
}
conA->numContigRelations++;
printf(" ADD ContigRelation %d (l %d) vs %d (l %d) nOvls: %d alignedA %d / %d alignedB %d / %d (validBridge %d, validContainment %d)\n",
conA->property.contigID, conA->property.len, conB->property.contigID, conB->property.len, crel->numPos, cumAaln, conA->property.len, cumBaln,
conB->property.len, validBridge, validContainment);
}
else
{
Contig *conB = actx->contigs + ovls[j].bread;
printf(
" FAILED [%d,b%d,c%d,g%d] ContigRelation %d (l %d) vs %d (l %d) nOvls: %d pBegA %d , propEndA %d, propBegB %d, propEndB %d, ovlBasA %d, ovlBasB %d\n",
fail, validBridge, validContainment, properGapLen, conA->property.contigID, conA->property.len, conB->property.contigID, conB->property.len,
(k - j + 1), properBegA, properEndA, properBegB, properEndB, overlapBasesA, overlapBasesB);
}
k++;
j = k;
}
printf("END -- Analyze overlaps for contig: %d numOvls: %d\n", ovls->aread, novl);
return 1;
}
int createOutDir(char *out)
{
int res = 0;
if (out)
{
struct stat s;
int err = stat(out, &s);
if (err == -1)
{
if (errno == ENOENT)
{
err = mkdir(out, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
if (err != 0)
{
fprintf(stderr, "Cannot create output directory: %s\n", out);
res = 1;
}
}
else
{
fprintf(stderr, "Cannot create output directory: %s\n", out);
res = 1;
}
}
else
{
if (!S_ISDIR(s.st_mode))
{
fprintf(stderr, "Output directory name: \"%s\" exist - but its not a directory\n", out);
res = 1;
}
}
}
return res;
}
// todo check if cEndPos is really exclusive
void writeFasta(AnalyzeContext *actx, Contig* contig, FILE* contigFile, int splitIdx, int cBegPos, int cEndPos)
{
int i;
int WIDTH = 100;
int path = getPathID(actx, contig->property.contigID);
int end1, end2;
getContigsEndIDs(actx, contig->property.contigID, &end1, &end2);
char *InFastaName = getContigFastaFileName(actx, contig);
///// create header
// new name = fasta file name + Contig idx
fprintf(contigFile, ">%s_%d", InFastaName, contig->property.contigID);
///// add some track info
// path track
fprintf(contigFile, " path=%d", path);
// length track
fprintf(contigFile, " length=%d", cEndPos - cBegPos);
if (splitIdx == 0) // otherwise the ends can be invalid
{
// ends track
fprintf(contigFile, " ends=%d,%d", end1, end2);
// repeat track
//fprintf(contigFile, " repeat=%d,%d,%d", contig->repBases, contig->repBasesTipLeft, contig->repBasesTipRight);
}
else
{
fprintf(contigFile, " splitIdx=%d", splitIdx);
}
// reads track
if (contig->numcReads)
{
fprintf(contigFile, " reads=");
int curPos = 0;
for (i = 0; i < contig->numcReads; i++)
{
if (curPos < cBegPos)
{
curPos += abs(contig->cReads[i].ovlReads->end - contig->cReads[i].ovlReads->beg);
continue;
}
if (curPos > cEndPos)
break;
// first read of split contig
if (cBegPos > curPos && cBegPos < curPos + abs(contig->cReads[i].ovlReads->end - contig->cReads[i].ovlReads->beg))
{
if (contig->cReads[i].ovlReads->beg < contig->cReads[i].ovlReads->end) // forward orientation
{
fprintf(contigFile, "%d,%d,%d", abs(contig->cReads[i].patchedID), contig->cReads[i].ovlReads->beg + (cBegPos - curPos),
contig->cReads[i].ovlReads->end);
}
else
{
fprintf(contigFile, "%d,%d,%d", abs(contig->cReads[i].patchedID), contig->cReads[i].ovlReads->beg - (cBegPos - curPos),
contig->cReads[i].ovlReads->end);
}
}
// last read of split contig
else if (curPos < cEndPos && cEndPos < curPos + abs(contig->cReads[i].ovlReads->end - contig->cReads[i].ovlReads->beg))
{
if (contig->cReads[i].ovlReads->beg < contig->cReads[i].ovlReads->end) // forward orientation
{
fprintf(contigFile, "%d,%d,%d", abs(contig->cReads[i].patchedID), contig->cReads[i].ovlReads->beg,
contig->cReads[i].ovlReads->end - (curPos + abs(contig->cReads[i].ovlReads->end - contig->cReads[i].ovlReads->beg) - cEndPos));
}
else
{
fprintf(contigFile, "%d,%d,%d", abs(contig->cReads[i].patchedID), contig->cReads[i].ovlReads->beg,
contig->cReads[i].ovlReads->end + (curPos + abs(contig->cReads[i].ovlReads->end - contig->cReads[i].ovlReads->beg) - cEndPos));
}
break;
}
else
{
fprintf(contigFile, "%d,%d,%d", abs(contig->cReads[i].patchedID), contig->cReads[i].ovlReads->beg, contig->cReads[i].ovlReads->end);
}
curPos += abs(contig->cReads[i].ovlReads->end - contig->cReads[i].ovlReads->beg);
if (curPos < cEndPos)
fprintf(contigFile, ",");
}
}
// sreads track
if (actx->corContigRawReads_track)
{
// fixed source read ids from contig
track_anno* sreadanno = actx->corContigRawReads_track->anno;
track_data* sreaddata = actx->corContigRawReads_track->data;
track_anno rb = sreadanno[contig->property.contigID] / sizeof(track_data);
track_anno re = sreadanno[contig->property.contigID + 1] / sizeof(track_data);
assert(rb < re && (int) (re - rb) == contig->numcReads);
fprintf(contigFile, " sreads=");
int curPos = 0;
for (i = 0; i < contig->numcReads; i++, rb++)
{
if (curPos < cBegPos)
{
curPos += abs(contig->cReads[i].ovlReads->end - contig->cReads[i].ovlReads->beg);
continue;
}
if (curPos > cEndPos)
break;
fprintf(contigFile, "%d", sreaddata[rb]);
curPos += abs(contig->cReads[i].ovlReads->end - contig->cReads[i].ovlReads->beg);
if (curPos < cEndPos)
fprintf(contigFile, ",");
}
}
// classification tracks
// 1) based on fixed read overlaps
// if (contig->gClassificFlag & CONTIG_HAS_CONTAINED)
// {
// int multi = 0;
// ContigReadClassification *gclass;
// for (i = 0; i < contig->numGClassific; i++)
// {
// gclass = contig->gClassific + i;
//
// if (gclass->flag & CONTIG_HAS_CONTAINED)
// {
// if (multi)
// {
// fprintf(contigFile, ",%d,%d,%d", gclass->correspID, gclass->coveredIntervals[0], gclass->coveredIntervals[gclass->numCoveredIntervals * 3 - 2]);
// }
// else
// {
// fprintf(contigFile, " gContains=%d,%d,%d", gclass->correspID, gclass->coveredIntervals[0],
// gclass->coveredIntervals[gclass->numCoveredIntervals * 3 - 2]);
// multi = 1;
// }
// }
// }
// }
// if (contig->gClassificFlag & CONTIG_IS_CONTAINED)
// {
// int multi = 0;
// ContigReadClassification *gclass;
// for (i = 0; i < contig->numGClassific; i++)
// {
// gclass = contig->gClassific + i;
//
// if (gclass->flag & CONTIG_IS_CONTAINED)
// {
// if (multi)
// {
// fprintf(contigFile, ",%d,%d,%d", gclass->correspID, gclass->coveredIntervals[0], gclass->coveredIntervals[gclass->numCoveredIntervals * 3 - 2]);
// }
// else
// {
// fprintf(contigFile, " gContainedIn=%d,%d,%d", gclass->correspID, gclass->coveredIntervals[0],
// gclass->coveredIntervals[gclass->numCoveredIntervals * 3 - 2]);
// multi = 1;
// }
// }
// }
// }
//// 2) based on contig overlap groups
// if (contig->flag & CONTIG_HAS_CONTAINED)
// {
// int multi = 0;
// OverlapGroup *ogr;
//// for (i = 0; i < contig->numOvlGrps; i++)
//// {
//// ogr = contig->ovlGrps[i];
////
//// if ((ogr->flag & CONTIG_HAS_CONTAINED) && contig->property.len > DB_READ_LEN(actx->corContigDB, ogr->bread))
//// {
//// if (multi)
//// {
//// fprintf(contigFile, ",%d,%d,%d", ogr->bread, ogr->first_abpos, ogr->last_aepos);
//// }
//// else
//// {
//// fprintf(contigFile, " cContains=%d,%d,%d", ogr->bread, ogr->first_abpos, ogr->last_aepos);
//// multi = 1;
//// }
//// }
//// }
// }
// if (contig->flag & CONTIG_IS_CONTAINED)
// {
// int multi = 0;
// OverlapGroup *ogr;
//// for (i = 0; i < contig->numOvlGrps; i++)
//// {
//// ogr = contig->ovlGrps[i];
////
//// if ((ogr->flag & CONTIG_IS_CONTAINED) && contig->property.len < DB_READ_LEN(actx->corContigDB, ogr->bread))
//// {
//// if (multi)
//// {
//// fprintf(contigFile, ",%d,%d,%d", ogr->bread, ogr->first_abpos, ogr->last_aepos);
//// }
//// else
//// {
//// fprintf(contigFile, " cContainedIn=%d,%d,%d", ogr->bread, ogr->first_abpos, ogr->last_aepos);
//// multi = 1;
//// }
//// }
//// }
// }
//
// if (contig->flag & CONTIG_AL50PCTCOVERED)
// {
// int multi = 0;
//
// for (i = 0; i < actx->numContigs; i++)
// {
//// if ((int) contig->pctCoveredBasesInOtherContigs[i] >= 50)
//// {
//// if (multi)
//// {
//// fprintf(contigFile, ",%d,%d", i, (int) contig->pctCoveredBasesInOtherContigs[i]);
//// }
//// else
//// {
//// fprintf(contigFile, " cCoveredIn=%d,%d", i, (int) contig->pctCoveredBasesInOtherContigs[i]);
//// multi = 1;
//// }
//// }
// }
// }
// todo sort splits according positions ?
// todo write out only real splits, i.e. skip heterozygoues ones, and print out only one valid split position either left or, or right or sometimes both
// if (contig->numSplits && !(contig->split->type & SPLIT_IGNORE))
// {
// int multi = 0;
// // print absolute contig Positions
// for (i = 0; i < contig->numSplits; i++)
// {
// if (multi)
// {
// fprintf(contigFile, ",%d,%d,%d", contig->split[i].type, contig->split[i].contigPos1, contig->split[i].contigPos2);
// }
// else
// {
// fprintf(contigFile, " splitAbsPos=%d,%d,%d", contig->split[i].type, contig->split[i].contigPos1, contig->split[i].contigPos2);
// multi = 1;
// }
// }
// multi = 0;
// // print split reads and their positions
// for (i = 0; i < contig->numSplits; i++)
// {
// if (multi)
// {
// fprintf(contigFile, ",%d,%d,%d,%d,%d,%d", contig->split[i].leftProperRead, contig->split[i].leftProperReadPos1,
// contig->split[i].leftProperReadPos2, contig->split[i].rightProperRead, contig->split[i].rightProperReadPos1,
// contig->split[i].rightProperReadPos2);
// }
// else
// {
// fprintf(contigFile, " split=%d,%d,%d,%d,%d,%d", contig->split[i].leftProperRead, contig->split[i].leftProperReadPos1,
// contig->split[i].leftProperReadPos2, contig->split[i].rightProperRead, contig->split[i].rightProperReadPos1,
// contig->split[i].rightProperReadPos2);
// multi = 1;
// }
// }
// }
fprintf(contigFile, "\n");
///// add sequence
Load_Read(actx->corContigDB, contig->property.contigID, actx->readSeq, 1);
for (i = cBegPos; i + WIDTH < cEndPos; i += WIDTH)
fprintf(contigFile, "%.*s\n", WIDTH, actx->readSeq + i);
if (i < cEndPos)
fprintf(contigFile, "%.*s\n", cEndPos - i, actx->readSeq + i);
fflush(contigFile);
}
//static int cmpSplitEvents(const void * a, const void * b)
//{
// SplitEvent *sa = (SplitEvent*) a;
// SplitEvent *sb = (SplitEvent*) b;
//
// if ((sa->type & SPLIT_IGNORE) && (sb->type & SPLIT_IGNORE))
// return (sa->contigPos1 - sb->contigPos1);
// if (sa->type & SPLIT_IGNORE)
// return 1;
// if (sb->type & SPLIT_IGNORE)
// return -1;
// return (sa->contigPos1 - sb->contigPos1);
//}
/*
void printFinalAltContigClassification(FILE *out, FinalContigAltClass facc)
{
switch (facc)
{
case BUBBLE_ALT:
fprintf(out, "BUBBLE_ALT");
break;
case BUBBLE_HUGEDIF:
fprintf(out, "BUBBLE_HUGEDIF");
break;
case BUBBLE_LOWCOVEREDREPEAT:
fprintf(out, "BUBBLE_LOWCOVEREDREPEAT");
break;
case BUBBLE_REPEAT:
fprintf(out, "BUBBLE_REPEAT");
break;
case BUBBLE_WEIRD:
fprintf(out, "BUBBLE_WEIRD");
break;
case SPUR_ALT:
fprintf(out, "SPUR_ALT");
break;
case SPUR_ATCONTIGEND:
fprintf(out, "SPUR_ATCONTIGEND");
break;
default:
fprintf(out, "NONE");
break;
}
}
void printFinalContigClassification(FILE *out, FinalContigClass fcc)
{
switch (fcc)
{
case HAPLOID:
fprintf(out, "HAPLOID");
break;
case CONTAINED_BY_BOTH:
fprintf(out, "CONTAINED_BY_BOTH");
break;
case CONTAINED_BY_BOTHSTRANGE:
fprintf(out, "CONTAINED_BY_BOTHSTRANGE");
break;
case CONTAINED_BY_CONTIG:
fprintf(out, "CONTAINED_BY_CONTIG");
break;
case CONTAINED_BY_FIXREAD:
fprintf(out, "CONTAINED_BY_FIXREAD");
break;
case CONTAINED_BY_COVEREDBASES:
fprintf(out, "CONTAINED_BY_COVEREDBASES");
break;
default:
fprintf(out, "UNKNOWN");
break;
}
}
char getClassification(FinalContigClass fcc)
{
switch (fcc)
{
case HAPLOID:
return 'H';
case CONTAINED_BY_BOTH:
return 'A';
case CONTAINED_BY_BOTHSTRANGE:
return 'W';
case CONTAINED_BY_CONTIG:
return 'C';
case CONTAINED_BY_FIXREAD:
return 'R';
case CONTAINED_BY_COVEREDBASES:
return 'B';
default:
return 'U';
}
}*/
//char* getSplitType(SplitEvent* se)
//{
// static char* result = NULL;
//
// if (result == NULL)
// result = malloc(20);
//
// result[0] = '\0';
//
// if (se->type & SPLIT_IGNORE)
// {
// strcat(result, "I");
// }
// if (se->type & SPLIT_UNKNOWN)
// {
// strcat(result, "u");
// }
// if (se->type & SPLIT_MULTIREAD)
// {
// strcat(result, "M");
// }
// if (se->type & SPLIT_STARTEND)
// {
// strcat(result, "S");
// }
// if (se->type & SPLIT_FALSEJOINLEFT)
// {
// strcat(result, "f");
// }
// if (se->type & SPLIT_FALSEJOINRIGHT)
// {
// strcat(result, "F");
// }
// if (se->type & SPLIT_HETEROZYGLEFT)
// {
// strcat(result, "h");
// }
// if (se->type & SPLIT_HETEROZYGRIGHT)
// {
// strcat(result, "H");
// }
// if (se->type & SPLIT_DEADENDLEFT)
// {
// strcat(result, "d");
// }
// if (se->type & SPLIT_DEADENDRIGHT)
// {
// strcat(result, "D");
// }
//
// return result;
//}
//static int cmpGraphClassByPos(const void* a, const void* b)
//{
// ContigReadClassification* c1 = (ContigReadClassification*) a;
// ContigReadClassification* c2 = (ContigReadClassification*) b;
//
// if (c1->flag & (CONTIG_UNCLASSIFIED | CONTIG_DISCARD | CONTIG_NORELATION | CONTIG_UNIQUE))
// return 1;
//
// if (c2->flag & (CONTIG_UNCLASSIFIED | CONTIG_DISCARD | CONTIG_NORELATION | CONTIG_UNIQUE))
// return -1;
//
// return (c1->coveredIntervals - c2->coveredIntervals);
//}
/// evaluate all three relationship information: TourRelation, ContigAlnRelation, ReadIntersectionRelation
void classify(AnalyzeContext *actx)
{
int i, j;
// i ... [0, ..., numContigs-1
// j ... [0, ..., numContigs+2]
// j= [0, ..., numContigs-1]: contig relationships
// j= numContigs. position: keep number of distinct ALT relationships, only REL_CONTIG_IS_ALT, REL_CONTIG_IS_REPEATALT, REL_READ_IS_ALT, and REL_TOUR_IS_ALT if its a bubble
// j= numContigs+1. position: keep number of distinct CONTIG_BRIDGE relationships
// j= numContigs+2. position: flag - REL_TOUR_IS_ALT if its a spur, will be used to split and trim contigs if both are primary
int ** relTable = (int **) malloc(sizeof(int*) * (actx->numContigs));
for (i = 0; i < actx->numContigs; i++)
{
relTable[i] = (int*) malloc(sizeof(int) * (actx->numContigs + 3));
bzero(relTable[i], sizeof(int) * (actx->numContigs + 3));
}
for (i = actx->numContigs - 1; i >= 0; i--)
{
Contig *conA = actx->contigs_sorted[i];
// add containment contig relations to relation table
for (j = 0; j < conA->numContigRelations; j++)
{
ContigRelation *cRel = conA->contigRelations + j;
if (cRel->flag & (REL_CONTIG_IS_ALT | REL_CONTIG_IS_REPEAT_ALT))
{
if (relTable[conA->property.contigID][cRel->corContigIdx] == 0)
{
relTable[conA->property.contigID][actx->numContigs]++;
}
if (cRel->flag & REL_CONTIG_IS_ALT)
relTable[conA->property.contigID][cRel->corContigIdx] |= REL_CONTIG_IS_ALT;
else
relTable[conA->property.contigID][cRel->corContigIdx] |= REL_CONTIG_IS_REPEAT_ALT;
}
if (cRel->flag & (REL_CONTIG_BRIDGE))
{
if (relTable[conA->property.contigID][cRel->corContigIdx] == 0)
{
relTable[conA->property.contigID][actx->numContigs + 1]++;
}
relTable[conA->property.contigID][cRel->corContigIdx] |= REL_CONTIG_BRIDGE;
if (relTable[cRel->corContigIdx][conA->property.contigID] == 0)
{
relTable[cRel->corContigIdx][actx->numContigs + 1]++;
}
relTable[cRel->corContigIdx][conA->property.contigID] |= REL_CONTIG_BRIDGE;
}
}
// add containment read relations to relation table
for (j = 0; j < conA->numReadRelations; j++)
{
ReadRelation *rRel = conA->readRelations + j;
if ((rRel->flag & REL_READ_IS_ALT))
{
if (relTable[conA->property.contigID][rRel->correspID] == 0)
{
relTable[conA->property.contigID][actx->numContigs]++;
}
relTable[conA->property.contigID][rRel->correspID] |= REL_READ_IS_ALT;
}
else if (rRel->flag & REL_READ_HAS_ALT)
{
if (relTable[rRel->correspID][conA->property.contigID] == 0)
{
relTable[rRel->correspID][actx->numContigs]++;
}
relTable[rRel->correspID][conA->property.contigID] |= REL_READ_IS_ALT;
}
}
// add containment touring relations to relation table
for (j = 0; j < conA->numTourRelations; j++)
{
TourRelation *tRel = conA->tourRelations + j;
if (tRel->flag & REL_TOUR_IS_BUBBLE)
{
if (relTable[conA->property.contigID][tRel->contigID1] == 0)
{
relTable[conA->property.contigID][actx->numContigs]++;
}
relTable[conA->property.contigID][tRel->contigID1] |= REL_TOUR_IS_BUBBLE;
}
else if (tRel->flag & REL_TOUR_IS_SPUR)
{
relTable[conA->property.contigID][actx->numContigs + 2]++;
relTable[conA->property.contigID][tRel->contigID1] |= REL_TOUR_IS_SPUR;
}
}
}
// classify ALT, PRIM, and CRAP relationships
for (i = 0; i < actx->numContigs; i++)
{
Contig *conA = actx->contigs_sorted[i];
int validRepeatPerc =
(MAX(conA->property.repBasesFromContigLAS, conA->property.repBasesFromReadLAS) * 100.0 / conA->property.len < actx->maxPrimContigRepeatPerc) ? 1 : 0;
int validMinCreads = (conA->numcReads > actx->minPrimContigReads) ? 1 : 0;
int validMinLen = (conA->property.len > actx->minPrimContigLen) ? 1 : 0;
if (relTable[conA->property.contigID][actx->numContigs] == 0)
{
if ((validMinCreads && validRepeatPerc) || validMinLen)
{
printf("CLASSIFY[%d][%d][%d]: PRIM %d l%d r(%d %d) v(%d, %d ,%d)\n", relTable[conA->property.contigID][actx->numContigs],
relTable[conA->property.contigID][actx->numContigs + 1], relTable[conA->property.contigID][actx->numContigs + 2], conA->property.contigID,
conA->property.len, conA->property.repBasesFromContigLAS, conA->property.repBasesFromReadLAS, validRepeatPerc, validMinCreads, validMinLen);
conA->property.cflag |= (CLASS_CONTIG_CLASSIFIED | CLASS_CONTIG_PRIMARY);
}
else
{
printf("CLASSIFY[%d][%d][%d]: CRAP %d l%d r(%d %d) v(%d, %d ,%d)\n", relTable[conA->property.contigID][actx->numContigs],
relTable[conA->property.contigID][actx->numContigs + 1], relTable[conA->property.contigID][actx->numContigs + 2], conA->property.contigID,
conA->property.len, conA->property.repBasesFromContigLAS, conA->property.repBasesFromReadLAS, validRepeatPerc, validMinCreads, validMinLen);
conA->property.cflag |= (CLASS_CONTIG_CLASSIFIED | CLASS_CONTIG_DISCARD);
if (!validMinCreads)
conA->property.cflag |= CLASS_CONTIG_DISCARD_CREADS;
if (!validMinLen)
conA->property.cflag |= CLASS_CONTIG_DISCARD_LEN;
if (!validRepeatPerc)
conA->property.cflag |= CLASS_CONTIG_DISCARD_REPEAT;
}
}
else if (relTable[conA->property.contigID][actx->numContigs] == 1) // exactly one to one contained relationship
{
for (j = 0; j < actx->numContigs; j++)
{
if (relTable[conA->property.contigID][j] & (REL_CONTIG_IS_ALT | REL_CONTIG_IS_REPEAT_ALT | REL_READ_IS_ALT | REL_TOUR_IS_BUBBLE))
break;
}
assert(j < actx->numContigs);
printf("CLASSIFY[%d][%d][%d]: %d ALT{ of %d} l%d r(%d %d) v(%d, %d ,%d): ", relTable[conA->property.contigID][actx->numContigs],
relTable[conA->property.contigID][actx->numContigs + 1], relTable[conA->property.contigID][actx->numContigs + 2], conA->property.contigID, j,
conA->property.len, conA->property.repBasesFromContigLAS, conA->property.repBasesFromReadLAS, validRepeatPerc, validMinCreads, validMinLen);
if (relTable[conA->property.contigID][j] & REL_CONTIG_IS_ALT)
printf(" REL_CONTIG_IS_ALT");
if (relTable[conA->property.contigID][j] & REL_CONTIG_IS_REPEAT_ALT)
printf(" REL_CONTIG_IS_REPEAT_ALT");
if (relTable[conA->property.contigID][j] & REL_READ_IS_ALT)
printf(" REL_READ_IS_ALT");
if (relTable[conA->property.contigID][j] & REL_TOUR_IS_BUBBLE)
printf(" REL_TOUR_IS_BUBBLE");
printf("\n");
// special case if REL_TOUR_IS_ALT is true but no other ALT relationship is true and primary contig properties are met, then it must be PRIM contig
conA->property.cflag |= (CLASS_CONTIG_CLASSIFIED | CLASS_CONTIG_ALT);
}
}
// resolve one to many relationship
for (i = 0; i < actx->numContigs; i++)
{
Contig *conA = actx->contigs_sorted[i];
int validRepeatPerc =
(MAX(conA->property.repBasesFromContigLAS, conA->property.repBasesFromReadLAS) * 100.0 / conA->property.len < actx->maxPrimContigRepeatPerc) ? 1 : 0;
int validMinCreads = (conA->numcReads > actx->minPrimContigReads) ? 1 : 0;
int validMinLen = (conA->property.len > actx->minPrimContigLen) ? 1 : 0;
if (relTable[conA->property.contigID][actx->numContigs] > 1)
{
printf("CLASSIFY[%d][%d][%d]: %d MULTI l%d r(%d %d) v(%d, %d ,%d):\n", relTable[conA->property.contigID][actx->numContigs],
relTable[conA->property.contigID][actx->numContigs + 1], relTable[conA->property.contigID][actx->numContigs + 2], conA->property.contigID,
conA->property.len, conA->property.repBasesFromContigLAS, conA->property.repBasesFromReadLAS, validRepeatPerc, validMinCreads, validMinLen);
int count = 1;
for (j = 0; j < actx->numContigs; j++)
{
if (relTable[conA->property.contigID][j] & (REL_CONTIG_IS_ALT | REL_CONTIG_IS_REPEAT_ALT | REL_READ_IS_ALT | REL_TOUR_IS_BUBBLE))
{
printf(" %d. REL with c%d: ", count++, j);
if (relTable[conA->property.contigID][j] & REL_CONTIG_IS_ALT)
printf(" REL_CONTIG_IS_ALT");
if (relTable[conA->property.contigID][j] & REL_CONTIG_IS_REPEAT_ALT)
printf(" REL_CONTIG_IS_REPEAT_ALT");
if (relTable[conA->property.contigID][j] & REL_READ_IS_ALT)
printf(" REL_READ_IS_ALT");
if (relTable[conA->property.contigID][j] & REL_TOUR_IS_BUBBLE)
printf(" REL_TOUR_IS_BUBBLE");
printf("\n");
}
}
int numPrim = 0;
for (j = 0; j < actx->numContigs; j++)
{
if (relTable[conA->property.contigID][j] & (REL_CONTIG_IS_ALT | REL_CONTIG_IS_REPEAT_ALT | REL_READ_IS_ALT | REL_TOUR_IS_BUBBLE))
{
if (actx->contigs[j].property.cflag & CLASS_CONTIG_CLASSIFIED)
{
if (actx->contigs[j].property.cflag & CLASS_CONTIG_PRIMARY)
numPrim++;
}
}
}
if (numPrim == count)
{
conA->property.cflag |= (CLASS_CONTIG_CLASSIFIED | CLASS_CONTIG_ALT);
printf("CLASSIFY[%d][%d]: %d MULTIRSOLVED ALT l%d r(%d %d) v(%d, %d ,%d):\n", relTable[conA->property.contigID][0],
relTable[conA->property.contigID][1], conA->property.contigID, conA->property.len, conA->property.repBasesFromContigLAS,
conA->property.repBasesFromReadLAS, validRepeatPerc, validMinCreads, validMinLen);
}
else
{
conA->property.cflag |= (CLASS_CONTIG_CLASSIFIED | CLASS_CONTIG_DISCARD);
printf("CLASSIFY[%d][%d][%d]: %d MULTIRSOLVED CRAP ContInCont l%d r(%d %d) v(%d, %d ,%d):\n", relTable[conA->property.contigID][actx->numContigs],
relTable[conA->property.contigID][actx->numContigs + 1], relTable[conA->property.contigID][actx->numContigs + 2], conA->property.contigID,
conA->property.len, conA->property.repBasesFromContigLAS, conA->property.repBasesFromReadLAS, validRepeatPerc, validMinCreads, validMinLen);
}
}
}
// check bridging contigs and trim back overhang
for (i = 0; i < actx->numContigs; i++)
{
Contig *conA = actx->contigs_sorted[i];
if (relTable[conA->property.contigID][actx->numContigs + 1])
{
for (j = 0; j < actx->numContigs; j++)
{
if (relTable[conA->property.contigID][j] & REL_CONTIG_BRIDGE)
{
if (conA->property.contigID < j)
{
Contig *conB = actx->contigs + (j);
printf("found putative bridge: %d (%s) vs %d (%s)\n", conA->property.contigID, getContigFastaFileName(actx, conA) ,conB->property.contigID, getContigFastaFileName(actx, conB));
}
}
}
}
else if (relTable[conA->property.contigID][actx->numContigs + 2]) // is spur
{
for (j = 0; j < actx->numContigs; j++)
{
if (relTable[conA->property.contigID][j] & REL_TOUR_IS_SPUR)
{
Contig *conB = actx->contigs + (j);
if ((conA->property.cflag & CLASS_CONTIG_PRIMARY) && (conB->property.cflag & CLASS_CONTIG_PRIMARY))
{
printf("found putative touring issue PvsP join: %d (%s) vs %d (%s)\n", conA->property.contigID, getContigFastaFileName(actx, conA), conB->property.contigID, getContigFastaFileName(actx, conB));
}
if (((conA->property.cflag & CLASS_CONTIG_PRIMARY)
&& ((conB->property.cflag & CLASS_CONTIG_DISCARD_LEN) && !(conB->property.cflag & CLASS_CONTIG_DISCARD_REPEAT)))
|| ((conB->property.cflag & CLASS_CONTIG_PRIMARY)
&& ((conA->property.cflag & CLASS_CONTIG_DISCARD_LEN) && !(conA->property.cflag & CLASS_CONTIG_DISCARD_REPEAT))))
{
printf("found putative touring issue PvsCL join: %d (%s) vs %d (%s)\n", conA->property.contigID, getContigFastaFileName(actx, conA), conB->property.contigID, getContigFastaFileName(actx, conB));
}
}
}
}
}
}
void createOutput(AnalyzeContext *actx)
{
// Todo
// open file streams:
// 1. primary fasta + primary stats (LGX, LX, NX, NGX) + repeat mask bed file + potential issues file + raw read IDs file (for Arrow correction) + coverage file
// 2. alt fasta + secondary stats
// 3. crap fasta + crap stats
char *primContigName = malloc(strlen(actx->outDir) + 50);
sprintf(primContigName, "%s/classified/asm.p.fa", actx->outDir);
FILE *primContigs = fopen(primContigName, "w");
assert(primContigs != NULL);
char *altContigName = malloc(strlen(actx->outDir) + 50);
sprintf(altContigName, "%s/classified/asm.a.fa", actx->outDir);
FILE *altContigs = fopen(altContigName, "w");
assert(altContigs != NULL);
char *crapContigName = malloc(strlen(actx->outDir) + 50);
sprintf(crapContigName, "%s/classified/asm.c.fa", actx->outDir);
FILE *crapContigs = fopen(crapContigName, "w");
assert(crapContigs != NULL);
// stats files
char *primStatsName = malloc(strlen(actx->outDir) + 50);
sprintf(primStatsName, "%s/classified/asm.p.stats", actx->outDir);
FILE *primStats = fopen(primStatsName, "w");
assert(primStats != NULL);
char *altStatsName = malloc(strlen(actx->outDir) + 50);
sprintf(altStatsName, "%s/classified/asm.a.stats", actx->outDir);
FILE *altStats = fopen(altStatsName, "w");
assert(altStats != NULL);
char *crapStatsName = malloc(strlen(actx->outDir) + 50);
sprintf(crapStatsName, "%s/classified/asm.c.stats", actx->outDir);
FILE *crapStats = fopen(crapStatsName, "w");
assert(crapStats != NULL);
char FS = '\t';
int WIDTH = 200;
char *read = New_Read_Buffer(actx->corContigDB);
// sprintf(out, "%s/curatedAndClassified", actx.outDir);
// print stats header
fprintf(primStats, "#ID%cLEN%cCREPEAT%cRREPEAT%cPATH%cFILE%cENDS%cNCCONCOMP%cNCREADS%cAVGCOV%cCLASSIFICATION%cCONTAINEDVIALAS%cCONTAINEDVIAREADS%cCONTAINEDVIATOUR%cLOWCOV\n", FS, FS, FS, FS, FS, FS, FS, FS, FS, FS, FS, FS, FS, FS);
fprintf(altStats, "#ID%cLEN%cCREPEAT%cRREPEAT%cPATH%cFILE%cENDS%cNCCONCOMP%cNCREADS%cAVGCOV%cCLASSIFICATION%cCONTAINEDVIALAS%cCONTAINEDVIAREADS%cCONTAINEDVIATOUR%cLOWCOV\n", FS, FS, FS, FS, FS, FS, FS, FS, FS, FS, FS, FS, FS, FS);
fprintf(crapStats, "#ID%cLEN%cCREPEAT%cRREPEAT%cPATH%cFILE%cENDS%cNCCONCOMP%cNCREADS%cAVGCOV%cCLASSIFICATION%cCONTAINEDVIALAS%cCONTAINEDVIAREADS%cCONTAINEDVIATOUR%cLOWCOV\n", FS, FS, FS, FS, FS, FS, FS, FS, FS, FS, FS, FS, FS, FS);
int i, j, end1, end2;
for (i = 0; i < actx->numContigs; i++)
{
Contig *con = actx->contigs_sorted[i];
FILE *fout, *sout;
if (con->property.cflag & CLASS_CONTIG_PRIMARY)
{
fout = primContigs;
sout = primStats;
}
else if (con->property.cflag & CLASS_CONTIG_ALT)
{
fout = altContigs;
sout = altStats;
}
else
{
fout = crapContigs;
sout = crapStats;
}
Load_Read(actx->corContigDB, con->property.contigID, read, 1);
// print fa-header
fprintf(fout, ">%s_%d len=%d rep=%d\n", getContigFastaFileName(actx, con), con->property.pathID, con->property.len,
(int) (con->property.repBasesFromReadLAS * 100.0 / con->property.len));
// print fa-body
for (j = 0; j + WIDTH < con->property.len; j += WIDTH)
fprintf(fout, "%.*s\n", WIDTH, read + j);
if (j < con->property.len)
fprintf(fout, "%.*s\n", con->property.len - j, read + j);
// add stats
fprintf(sout, "%d%c", con->property.contigID, FS);
fprintf(sout, "%d%c", con->property.len, FS);
fprintf(sout, "%.2f%c", con->property.repBasesFromContigLAS*100.0/con->property.len, FS);
fprintf(sout, "%.2f%c", con->property.repBasesFromReadLAS*100.0/con->property.len, FS);
fprintf(sout, "%d%c", con->property.pathID, FS);
fprintf(sout, "%s%c", getContigFastaFileName(actx, con), FS);
getContigsEndIDs(actx, con->property.contigID, &end1, &end2);
fprintf(sout, "%d,%d%c", end1, end2, FS);
fprintf(sout, "%d%c", getNumberOfSubgraphContigs(actx->contigFileNamesAndOffsets, con->property.contigID), FS);
fprintf(sout, "%d%c", con->numcReads, FS);
fprintf(sout, "%.2f%c", con->avgCov, FS);
// classification
if(con->property.cflag & CLASS_CONTIG_PRIMARY)
{
fprintf(sout, "%s%c", "PRI", FS);
}
else if(con->property.cflag & CLASS_CONTIG_ALT)
{
fprintf(sout, "%s%cs", "ALT", FS);
}
else
{
fprintf(sout, "%s", "CRAP");
if(con->property.cflag & CLASS_CONTIG_DISCARD_CREADS)
fprintf(sout, "%c", 'c');
else
fprintf(sout, "%c", '_');
if(con->property.cflag & CLASS_CONTIG_DISCARD_REPEAT)
fprintf(sout, "%c", 'r');
else
fprintf(sout, "%c", '_');
if(con->property.cflag & CLASS_CONTIG_DISCARD_LEN)
fprintf(sout, "%c", 'l');
else
fprintf(sout, "%c", '_');
fprintf(sout, "%c", FS);
}
if(con->property.cflag & CLASS_CONTIG_ALT)
{
int found=0;
for(j=0; j<con->numContigRelations; j++)
{
if(con->contigRelations[j].flag & REL_CONTIG_IS_ALT)
{
if(found)
fprintf(sout, ",");
fprintf(sout, "%d", con->contigRelations[j].corContigIdx);
found=1;
}
}
if(found)
fprintf(sout, "%c", FS);
else
fprintf(sout, "-%c", FS);
found=0;
for(j=0; j<con->numReadRelations; j++)
{
if(con->readRelations[j].flag & REL_READ_IS_ALT)
{
if(found)
fprintf(sout, ",");
fprintf(sout, "%d", con->readRelations[j].correspID);
found=1;
}
}
if(found)
fprintf(sout, "%c", FS);
else
fprintf(sout, "-%c", FS);
found=0;
for(j=0; j<con->numTourRelations; j++)
{
if(con->tourRelations[j].flag & REL_TOUR_IS_BUBBLE)
{
if(found)
fprintf(sout, ",");
fprintf(sout, "%d", con->tourRelations[j].contigID1);
found=1;
}
}
if(found)
fprintf(sout, "%c", FS);
else
fprintf(sout, "-%c", FS);
}
else
fprintf(sout, "-%c-%c-%c", FS, FS, FS);
// coverage issues:
int lowCov=0;
for (j=0; j<con->numcReads-1; j++)
{
if(con->cReads[j].lowCov)
{
if (lowCov)
fprintf(sout, ",");
fprintf(sout, "%d", con->cReads[j].correctedContigPosEnd);
lowCov=1;
}
}
fprintf(sout, "\n");
fflush(fout);
fflush(sout);
}
fclose(primContigs);
fclose(altContigs);
fclose(crapContigs);
free(primContigName);
free(altContigName);
free(crapContigName);
fclose(primStats);
fclose(altStats);
fclose(crapStats);
free(primStatsName);
free(altStatsName);
free(crapStatsName);
free(read - 1);
}
static void usage()
{
fprintf(stderr,
" [-v] [-csfeLNP <int>] [-d <dir>] [-rt <Track>] -C <contigDB> <ContigOverlaps> -F <fixedReadDB> <fixedReadOverlaps> -D <correctedReadDB> \n");
fprintf(stderr, "options: -v ... verbose\n");
fprintf(stderr, " -c ... expected coverage\n");
fprintf(stderr, " -s ... maximum spur/bubble length (default: %d)\n", DEF_SPUR_LEN);
fprintf(stderr, " -e ... maximum contig end length (tips) to consider false joins (default: %d)\n", DEF_TIP_LEN);
fprintf(stderr, " -r ... repeats track for contigs (default: repeats)\n");
fprintf(stderr, " -R ... repeats track for patached reads (default: repeats)\n");
fprintf(stderr, " -t ... trim track for fixed reads (default: none)\n");
fprintf(stderr, " -C DB OVL ... contig database and contig overlaps, required to classify contigs\n");
fprintf(stderr, " -F DB OVL ... fixed read database and fixed read overlaps, required to extract all b-reads for blasr mapping\n");
fprintf(stderr, " -D DB ... corrected read database\n");
fprintf(stderr, " -d ... write classified contigs ands stats file into -d directoryName (default: cwd)\n");
fprintf(stderr, " -f ... allow maximum of -f bases of structural variations between two contig overlaps of a chain, (default %d)\n",
DEF_ARG_F);
fprintf(stderr, "\n\n");
fprintf(stderr, "EPERIMENTAL - contig filter + classification options:\n");
fprintf(stderr, " -L ... minimum primary contig length, (default %d)\n", DEF_ARG_L);
fprintf(stderr, " -N ... minimum number of contig reads for a primary contig (default %d)\n", DEF_ARG_N);
fprintf(stderr, " -P ... maximum repeat percentage of a primary contig, (default %d)\n", DEF_ARG_P);
}
int main(int argc, char* argv[])
{
HITS_DB correctedContigDB;
HITS_DB patchedReadDB;
HITS_DB correctedReadDB;
FILE* patchedReadLAS;
FILE* correctedContigLAS;
PassContext* contig_pctx;
PassContext* patched_pctx;
AnalyzeContext actx;
char *patchedReadTrimTrack = NULL;
char *patchedReadRepeatTrack = NULL;
char *corContigRepeatsTrack = DEF_REPEATS_TRACK;
bzero(&actx, sizeof(AnalyzeContext));
opterr = 0;
actx.VERBOSE = 0;
actx.SPUR_LEN = DEF_SPUR_LEN;
actx.TIP_LEN = DEF_TIP_LEN;
actx.nFuzzBases = DEF_ARG_F;
actx.contByReads_CommonReadFraction = DEF_ARG_CRF;
actx.contByReads_CoveredLenPerc = DEF_ARG_CL;
actx.contByContigs_CoveredLenPerc = DEF_ARG_CL;
actx.minPrimContigLen = DEF_ARG_L;
actx.minPrimContigReads = DEF_ARG_N;
actx.maxPrimContigRepeatPerc = DEF_ARG_P;
int c;
while ((c = getopt(argc, argv, "vc:d:t:r:C:F:s:e:D:R:f:L:N:P:")) != -1)
{
switch (c)
{
case 'v':
actx.VERBOSE++;
break;
case 'L':
actx.minPrimContigLen = atoi(optarg);
break;
case 'N':
actx.minPrimContigReads = atoi(optarg);
break;
case 'P':
actx.maxPrimContigRepeatPerc = atoi(optarg);
break;
case 'f':
actx.nFuzzBases = atoi(optarg);
break;
case 'e':
actx.TIP_LEN = atoi(optarg);
break;
case 's':
actx.SPUR_LEN = atoi(optarg);
break;
case 'c':
{
actx.exp_cov = atoi(optarg);
if (actx.exp_cov <= 0)
{
fprintf(stderr, "[ERROR] - analyzeContigs: expected coverage must be positive (>= 1)\n");
usage();
exit(1);
}
}
break;
case 'd':
actx.outDir = optarg;
break;
case 't':
patchedReadTrimTrack = optarg;
break;
case 'r':
corContigRepeatsTrack = optarg;
break;
case 'R':
patchedReadRepeatTrack = optarg;
break;
case 'C':
{
actx.corContigDBName = optarg;
if (optind < argc && *argv[optind] != '-')
{
actx.corContigLASName = argv[optind];
optind++;
}
else
{
fprintf(stderr, "\n-C option require TWO arguments <contigDB> <ContigOverlaps>\n\n");
usage();
exit(1);
}
break;
}
case 'F':
{
actx.patchedReadDBName = optarg;
if (optind < argc && *argv[optind] != '-')
{
actx.patchedReadLASName = argv[optind];
optind++;
}
else
{
fprintf(stderr, "\n-F option require TWO arguments <fixedReadDB> <fixedReadOverlaps>\n\n");
usage();
exit(1);
}
break;
}
case 'D':
actx.corReadDBName = optarg;
break;
default:
fprintf(stderr, "Unknown option: %s\n", argv[optind - 1]);
usage();
exit(1);
}
}
if (actx.corReadDBName == NULL)
{
fprintf(stderr, "[ERROR] - corrected read database is required!\n");
exit(1);
}
if (actx.corContigDBName == NULL && actx.corContigLASName == NULL)
{
fprintf(stderr, "[ERROR] - At least a contig dabase and the corresponding overlaps are required to analyze contigs!\n");
exit(1);
}
if ((correctedContigLAS = fopen(actx.corContigLASName, "r")) == NULL)
{
fprintf(stderr, "[ERROR] - could not open '%s'\n", actx.corContigLASName);
exit(1);
}
if (actx.VERBOSE)
printf("Open database: %s\n", actx.corReadDBName);
if (Open_DB(actx.corReadDBName, &correctedReadDB))
{
fprintf(stderr, "[ERROR] - could not open '%s'\n", actx.corReadDBName);
exit(1);
}
if (actx.VERBOSE)
printf("Open database: %s\n", actx.corContigDBName);
if (Open_DB(actx.corContigDBName, &correctedContigDB))
{
fprintf(stderr, "[ERROR] - could not open '%s'\n", actx.corContigDBName);
exit(1);
}
if (actx.VERBOSE)
printf("Load track %s for db %s\n", corContigRepeatsTrack, actx.corContigDBName);
if ((actx.corContigRepeats_track = track_load(&correctedContigDB, corContigRepeatsTrack)) == NULL)
{
fprintf(stderr, "[ERROR] - could not open track '%s' for database '%s'. Create a repeat track with LArepeat first!\n", corContigRepeatsTrack,
actx.corContigDBName);
exit(1);
}
if (actx.VERBOSE)
printf("Load track %s for db %s\n", "creads", actx.corReadDBName);
if ((actx.corContigCorrectReadsAndPos_track = track_load(&correctedContigDB, "creads")) == NULL)
{
fprintf(stderr, "[ERROR] - could not open track '%s' for database '%s'\n", "creads", actx.corContigDBName);
exit(1);
}
if (actx.VERBOSE)
printf("Load track %s for db %s\n", "rreads", actx.corContigDBName);
if ((actx.corContigRawReads_track = track_load(&correctedContigDB, "rreads")) == NULL)
{
fprintf(stderr, "[ERROR] - could not open track '%s' for database '%s'\n", "rreads", actx.corContigDBName);
exit(1);
}
if (actx.VERBOSE)
printf("Load track %s for db %s\n", "preads", actx.corContigDBName);
if ((actx.corContigPatchReadsAndPos_track = track_load(&correctedContigDB, "preads")) == NULL)
{
fprintf(stderr, "[ERROR] - could not open track '%s' for database '%s'\n", "preads", actx.corContigDBName);
exit(1);
}
if ((patchedReadLAS = fopen(actx.patchedReadLASName, "r")) == NULL)
{
fprintf(stderr, "[ERROR] - could not open '%s'\n", actx.patchedReadLASName);
exit(1);
}
///todo make this optional
if (actx.VERBOSE)
printf("Open database: %s\n", actx.patchedReadDBName);
if (Open_DB(actx.patchedReadDBName, &patchedReadDB))
{
fprintf(stderr, "could not open '%s'\n", actx.patchedReadDBName);
exit(1);
}
if (patchedReadTrimTrack != NULL)
{
if (actx.VERBOSE)
printf("Load track %s for db %s\n", patchedReadTrimTrack, actx.patchedReadDBName);
if ((actx.patchedReadTrim_track = track_load(&patchedReadDB, patchedReadTrimTrack)) == NULL)
{
fprintf(stderr, "could not open track '%s' for database '%s'\n", patchedReadTrimTrack, actx.patchedReadDBName);
exit(1);
}
}
else if ((actx.patchedReadTrim_track = track_load(&patchedReadDB,
TRACK_TRIM)) == NULL)
{
fprintf(stderr, "could not open track '%s' for database '%s'\n",
TRACK_TRIM, actx.patchedReadDBName);
exit(1);
}
if (actx.VERBOSE)
printf("Load track %s for db %s\n", patchedReadRepeatTrack, actx.patchedReadDBName);
if ((actx.patchedReadRepeat_track = track_load(&patchedReadDB, patchedReadRepeatTrack)) == NULL)
{
fprintf(stderr, "[ERROR] - could not open track '%s' for database '%s'!\n", patchedReadRepeatTrack, actx.patchedReadDBName);
exit(1);
}
if (actx.VERBOSE)
printf("Load track %s for db %s\n", "source", actx.patchedReadDBName);
if ((actx.patchedReadSource_track = track_load(&patchedReadDB, "source")) == NULL)
{
fprintf(stderr, "[ERROR] - could not open track '%s' for database '%s'\n", "source", actx.patchedReadDBName);
exit(1);
}
// init
actx.corContigDB = &correctedContigDB;
actx.patchedReadDB = &patchedReadDB;
actx.corReadDB = &correctedReadDB;
char *cwd = malloc(10);
if (actx.outDir == NULL)
{
sprintf(cwd, ".");
actx.outDir = cwd;
}
{
if (createOutDir(actx.outDir))
exit(1);
char *out = malloc(strlen(actx.outDir) + 30);
sprintf(out, "%s/classified", actx.outDir);
if (createOutDir(out))
exit(1);
sprintf(out, "%s/curatedAndClassified", actx.outDir);
if (createOutDir(out))
exit(1);
free(out);
}
// contig pass context
{
contig_pctx = pass_init(correctedContigLAS, NULL);
contig_pctx->split_b = 0;
contig_pctx->load_trace = 0;
contig_pctx->unpack_trace = 0;
contig_pctx->data = &actx;
pre(contig_pctx, &actx);
}
// fixed read pass context
{
patched_pctx = pass_init(patchedReadLAS, NULL);
patched_pctx->split_b = 0;
patched_pctx->load_trace = 1;
patched_pctx->unpack_trace = 1;
patched_pctx->data = &actx;
pre(patched_pctx, &actx);
}
// initialize contigs
printf("START --- STEP0a: initialize AnalyzeContext - START\n");
initAnalyzeContext(&actx);
printf("START --- STEP0a: initialize AnalyzeContext - DONE\n");
// todo for now do all steps: input format should be a MARVEL assembly run
// analyze overlaps of fixed reads for each contig ( coverage, containments, duplicate reads used in different contigs )
// STEP1
if (1)
{
printf("START --- STEP1A: -- use patched read overlaps (from touring) and assign those to corresponding contigs\n");
pass(patched_pctx, processReadOverlapsAndMapThemToContigs);
printf("DONE --- STEP1A: -- use patched read overlaps (from touring) and assign those to corresponding contigs\n");
printf("START --- STEP1B: -- do coverage analysis for contig-read-overlaps, set absolute contig positions\n");
analyzeContigCoverageOfMappedReads(&actx);
printf("DONE --- STEP1B: -- do coverage analysis for contig-read-overlaps, set absolute contig positions\n");
printf("START --- STEP1C: -- analyzeContigCreadIntersection by applying a read intersection strategy\n");
analyzeContigCreadIntersection(&actx);
printf("DONE --- STEP1C: -- analyzeContigCreadIntersection by applying a read intersection strategy\n");
}
// analyze overlaps between contigs
// STEP2
if (1)
{
printf("START --- STEP2a: analyze contig vs contig overlaps\n");
pass(contig_pctx, analyzeContigVsContigOverlaps);
printf("DONE --- STEP2a: analyze contig vs contig overlaps\n");
}
// final classification, based on STEP1 and STEP2
// STEP3
if (1)
{
printf("START --- STEP3: refine contig classification (based on STEP1 and STEP2)");
classify(&actx);
printf("DONE --- STEP3: refine contig classification (based on STEP1 and STEP2)");
}
createOutput(&actx);
// clean up - put everything in a method
pass_free(contig_pctx);
pass_free(patched_pctx);
fflush(stdout);
fflush(stderr);
Close_DB(&patchedReadDB);
Close_DB(&correctedReadDB);
Close_DB(&correctedContigDB);
free(actx.readSeq - 1);
int i;
if (actx.contigFileNamesAndOffsets)
{
for (i = 0; i < actx.contigFileNamesAndOffsets->numFileNames; i++)
{
free(actx.contigFileNamesAndOffsets->fastaNames[i]);
free(actx.contigFileNamesAndOffsets->fileNames[i]);
}
free(actx.contigFileNamesAndOffsets);
}
if (actx.rawReadFileNamesAndOffsets)
{
for (i = 0; i < actx.rawReadFileNamesAndOffsets->numFileNames; i++)
{
free(actx.rawReadFileNamesAndOffsets->fastaNames[i]);
free(actx.rawReadFileNamesAndOffsets->fileNames[i]);
}
free(actx.rawReadFileNamesAndOffsets);
}
for (i = 0; i < actx.maxVReadMask; i++)
{
free(actx.vreadMask[i]);
}
free(actx.vreadMask);
free(cwd);
return 0;
}
|
MartinPippel/DAmar
|
corrector/consensus.c
|
<reponame>MartinPippel/DAmar
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "consensus.h"
#include "lib/colors.h"
#define CONS_MIN_COV_FRACTION 0.5 // base calling threshold
#undef DEBUG_SHOW_ADD
typedef struct
{
char* B; // sequence that gets aligned to
profile_entry* A; // the profile B
int abpos, aepos; // regions to be aligned in A
int bbpos, bepos; // in B
int* pPtPoints; // pairs of pass-through points <profile, sequence>
int nPtPoints; // number of pass-through points ( pairs * 2 )
int diffs_a; // number of insertions in A
int diffs_b; // number of insertions in B
v3_consensus_alignment_ctx* pCtx; // points to context, working storage
} v3_consensus_alignment;
static int match(char* a, int ia, profile_entry* p, int ip)
{
profile_entry* pEntry = (p + ip);
char nMax = pEntry->counts[0];
char cMax = 0;
char nCount;
// loop unrolled
nCount = pEntry->counts[1];
if (nCount > nMax ) { nMax = nCount; cMax = 1; }
nCount = pEntry->counts[2];
if (nCount > nMax ) { nMax = nCount; cMax = 2; }
nCount = pEntry->counts[3];
if (nCount > nMax ) { nMax = nCount; cMax = 3; }
nCount = pEntry->counts[4];
if (nCount >= nMax ) { return 0; }
return (cMax == a[ia]);
}
static int v3_align_onp(v3_consensus_alignment* pAlign,
profile_entry* A, int M, char* B, int N)
{
int** PVF = pAlign->pCtx->PVF; // wave->PVF;
int** PHF = pAlign->pCtx->PHF; // wave->PHF;
int D;
int del = M - N;
{
int* F0, *F1, *F2;
int* HF;
int low, hgh;
if (del >= 0)
{
low = 0;
hgh = del;
}
else
{
low = del;
hgh = 0;
}
F1 = PVF[-2];
F0 = PVF[-1];
for (D = low - 1; D <= hgh + 1; D++)
{
F1[D] = F0[D] = -2;
}
F0[0] = -1;
low += 1;
hgh -= 1;
for (D = 0; 1; D += 1)
{
int k, i, j;
int am, ac, ap;
profile_entry* a;
F2 = F1;
F1 = F0;
F0 = PVF[D];
HF = PHF[D];
if ((D & 0x1) == 0)
{
hgh += 1;
low -= 1;
}
F0[hgh + 1] = F0[low - 1] = -2;
#define FS_MOVE(mdir,pdir) \
ac = F1[k]+1; \
if (ac < am) \
if (ap < am) \
{ HF[k] = mdir; \
j = am; \
} \
else \
{ HF[k] = pdir; \
j = ap; \
} \
else \
if (ap < ac) \
{ HF[k] = 0; \
j = ac; \
} \
else \
{ HF[k] = pdir; \
j = ap; \
} \
\
if (N < i) \
while (j < N && match(B,j,a,j)) \
j += 1; \
else \
while (j < i && match(B,j,a,j)) \
j += 1; \
F0[k] = j;
j = -2;
a = A + hgh;
i = M - hgh;
for (k = hgh; k > del; k--)
{
ap = j + 1;
am = F2[k - 1];
FS_MOVE(-1, 4)
a -= 1;
i += 1;
}
j = -2;
a = A + low;
i = M - low;
for (k = low; k < del; k++)
{
ap = F2[k + 1] + 1;
am = j;
FS_MOVE(2, 1)
a += 1;
i -= 1;
}
ap = F0[del + 1] + 1;
am = j;
FS_MOVE(2, 4)
if (F0[del] >= N)
{
break;
}
}
}
{
int k, h, m, e, c;
profile_entry* a;
int ap = (pAlign->pCtx->Aabs - A) - 1; // (wave->Aabs - A) - 1;
int bp = (B - pAlign->pCtx->Babs) + 1; // (B - wave->Babs) + 1;
PHF[0][0] = 3;
c = N;
k = del;
e = PHF[D][k];
PHF[D][k] = 3;
while (e != 3)
{
h = k + e;
if (e > 1)
{
h -= 3;
}
else if (e == 0)
{
D -= 1;
}
else
{
D -= 2;
}
if (h < k) // => e = -1 or 2
{
a = A + k;
if (k < 0)
{
m = -k;
}
else
{
m = 0;
}
if (PVF[D][h] <= c)
{
c = PVF[D][h] - 1;
}
while (c >= m && match(B,c,a,c)) // a[c] == B[c])
{
c -= 1;
}
if (e < 1) // => edge is 2, others are 1, and 0
{
if (c <= PVF[D + 2][k + 1])
{
e = 4;
h = k + 1;
D = D + 2;
}
else if (c == PVF[D + 1][k])
{
e = 0;
h = k;
D = D + 1;
}
else
{
PVF[D][h] = c + 1;
}
}
else // => edge is 0, others are 1, and 2 (if k != del), 0 (otherwise)
{
if (k == del)
{
m = D;
}
else
{
m = D - 2;
}
if (c <= PVF[m][k + 1])
{
if (k == del)
{
e = 4;
}
else
{
e = 1;
}
h = k + 1;
D = m;
}
else if (c == PVF[D - 1][k])
{
e = 0;
h = k;
D = D - 1;
}
else
{
PVF[D][h] = c + 1;
}
}
}
m = PHF[D][h];
PHF[D][h] = e;
e = m;
k = h;
}
k = D = 0;
e = PHF[D][k];
while (e != 3)
{
h = k - e;
c = PVF[D][k];
if (e > 1)
{
h += 3;
}
else if (e == 0)
{
D += 1;
}
else
{
D += 2;
}
if (h > k)
{
*(pAlign->pCtx->Stop) = bp + c;
(pAlign->pCtx->Stop)++;
pAlign->diffs_b++;
// *wave->Stop++ = bp + c;
}
else if (h < k)
{
*(pAlign->pCtx->Stop) = ap - (c + k);
(pAlign->pCtx->Stop)++;
pAlign->diffs_a++;
// *wave->Stop++ = ap - (c + k);
}
k = h;
e = PHF[D][h];
}
}
return (D + abs(del));
}
static int v3_align(v3_consensus_alignment* align)
{
v3_consensus_alignment_ctx* pCtx = align->pCtx;
char* bseq;
profile_entry* aseq;
int* points, tlen;
int ab, bb;
int ae, be;
int diffs;
aseq = align->A;
bseq = align->B;
tlen = align->nPtPoints;
points = align->pPtPoints;
{
int d, s;
int M, N;
int dmax, nmax, mmax;
int** PVF, **PHF;
M = align->aepos - align->abpos;
N = align->bepos - align->bbpos;
s = M>N ? M : N;
if (s > pCtx->ntrace)
{
pCtx->ntrace = 1.2 * pCtx->ntrace + s;
pCtx->trace = (int*)realloc(pCtx->trace, sizeof(int)*pCtx->ntrace);
}
mmax = 0;
nmax = 0;
dmax = 0;
ab = align->abpos;
bb = align->bbpos;
for (d = 0; d < tlen; d += 2)
{
ae = points[d];
be = points[d + 1];
M = ae - ab;
N = be - bb;
if (M < N)
{
diffs = M;
}
else
{
diffs = N;
}
if (diffs > dmax)
{
dmax = diffs;
}
if (M > mmax)
{
mmax = M;
}
if (N > nmax)
{
nmax = N;
}
ab = ae;
bb = be;
}
ae = align->aepos;
be = align->bepos;
M = ae - ab;
N = be - bb;
if (M < N)
{
diffs = M;
}
else
{
diffs = N;
}
if (diffs > dmax)
{
dmax = diffs;
}
if (M > mmax)
{
mmax = M;
}
if (N > nmax)
{
nmax = N;
}
s = (dmax + 3) * 2 * ((mmax + nmax + 3) * sizeof(int) + sizeof(int*));
if (s > pCtx->vecmax)
{
if (s > 256*1024*1024)
{
printf("v3_align> skipping alignment. excessive amount of memory needed.\n");
printf("dmax = %d mmax = %d nmax = %d s = %d\n", dmax, mmax, nmax, s);
return 0;
}
pCtx->vecmax = s * 1.2 + 10000;
pCtx->vector = (int*)realloc(pCtx->vector, pCtx->vecmax);
}
pCtx->PVF = PVF = ((int**) (pCtx->vector)) + 2;
pCtx->PHF = PHF = PVF + (dmax + 3);
// wave.PVF = PVF = ((int**) (work->vec.data())) + 2;
// wave.PHF = PHF = PVF + (dmax + 3);
s = mmax + nmax + 3;
PVF[-2] = ((int*) (PHF + (dmax + 1))) + (nmax + 1);
for (d = -1; d <= dmax; d++)
{
PVF[d] = PVF[d - 1] + s;
}
PHF[-2] = PVF[dmax] + s;
for (d = -1; d <= dmax; d++)
{
PHF[d] = PHF[d - 1] + s;
}
}
pCtx->Stop = pCtx->trace;
pCtx->Aabs = aseq;
pCtx->Babs = bseq;
{
int i;
diffs = 0;
ab = align->abpos;
bb = align->bbpos;
for (i = 0; i < tlen; i += 2)
{
be = points[i + 1];
ae = points[i];
diffs += v3_align_onp(align, aseq + ab, ae - ab, bseq + bb, be - bb);
ab = ae;
bb = be;
}
ae = align->aepos;
be = align->bepos;
diffs += v3_align_onp(align, aseq + ab, ae - ab, bseq + bb, be - bb);
}
pCtx->ntrace = pCtx->Stop - pCtx->trace;
// path->diffs = diffs;
return 1;
}
static char decode_base(unsigned char c)
{
static const char* pcTable = "ACGT-";
return pcTable[c];
}
consensus* consensus_init()
{
consensus* c = (consensus*)malloc(sizeof(consensus));
c->profile = NULL;
c->maxprof = 0;
c->added = 0;
c->seq = NULL;
c->nseq = 0;
c->aln_ctx = (v3_consensus_alignment_ctx*)malloc(sizeof(v3_consensus_alignment_ctx));
c->aln_ctx->ntrace = 0;
c->aln_ctx->trace = NULL;
c->aln_ctx->vecmax = 0;
c->aln_ctx->vector = NULL;
return c;
}
void consensus_free(consensus* c)
{
free(c->profile);
free(c->aln_ctx->trace);
free(c->aln_ctx->vector);
free(c->aln_ctx);
free(c->seq);
free(c);
}
void consensus_print_profile(consensus* c, FILE* fileOut, int colorize)
{
profile_entry* pEntry;
// counts
int i;
if (colorize) printf(ANSI_COLOR_BLUE);
printf(" ");
for (i = 0; i < c->curprof; i++)
{
pEntry = c->profile + i;
fprintf(fileOut, "%3d", i%100);
}
if (colorize) printf(ANSI_COLOR_RESET);
fprintf(fileOut, "\n");
int nBase;
for (nBase = 0; nBase < 5; nBase++)
{
fprintf(fileOut, "%c ", decode_base(nBase));
for (i = 0; i < c->curprof; i++)
{
pEntry = c->profile + i;
fprintf(fileOut, "%3d", pEntry->counts[nBase]);
}
fprintf(fileOut, "\n");
}
// consensus
if (colorize) printf(ANSI_COLOR_RED);
char* pcCons = consensus_sequence(c, 1);
printf("# ");
for (i = 0; i < c->curprof; i++)
{
fprintf(fileOut, "%3c", pcCons[i]);
}
if (colorize) printf(ANSI_COLOR_RESET);
fprintf(fileOut, "\n");
}
void consensus_reset(consensus* c)
{
c->curprof = 0;
c->added = 0;
}
static void consensus_add_first(consensus* c, char* seq, int len)
{
c->alen = len;
if (c->maxprof < len)
{
c->maxprof = 1.2 * len + 100;
c->profile = realloc(c->profile, sizeof(profile_entry)*c->maxprof);
}
c->curprof = len;
bzero(c->profile, sizeof(profile_entry)*c->maxprof);
int i;
for (i = 0; i < len; i++)
{
c->profile[i].counts[ (unsigned char)seq[i] ] = 1;
}
}
void consensus_add(consensus* cns, char* seq, int sb, int se) // , int pb, int pe)
{
int i;
#ifdef DEBUG_SHOW_ADD
printf("add %5d %5d ", sb, se);
for (i = sb; i < se; i++)
{
printf("%c", decode_base(seq[i]));
}
printf("\n");
#endif
if (cns->curprof == 0)
{
consensus_add_first(cns, seq+sb, se-sb);
cns->added++;
// consensus_print_profile(cns, stdout);
return;
}
v3_consensus_alignment aln;
aln.pCtx = cns->aln_ctx;
aln.diffs_a = 0;
aln.diffs_b = 0;
aln.B = seq;
aln.bbpos = sb;
aln.bepos = se;
aln.A = cns->profile;
aln.abpos = 0;
aln.aepos = cns->curprof;
assert( aln.bbpos >= 0 );
assert( aln.bbpos < aln.bepos );
// prepare pass through points
aln.nPtPoints = 0;
aln.pPtPoints = NULL;
if (!v3_align(&aln))
{
return ;
}
int c, p, b, n;
// enlarge profile if necessary
if (cns->curprof + aln.diffs_a > cns->maxprof)
{
cns->maxprof = cns->maxprof * 2 + aln.diffs_a;
cns->profile = (profile_entry*)realloc(cns->profile, sizeof(profile_entry)*cns->maxprof);
bzero(cns->profile + cns->curprof, sizeof(profile_entry)*aln.diffs_a);
}
// apply trace to profile and sequence in reverse order
// thereby allowing us to perform the update in place
// profile overhang right
n = cns->curprof - 1 + aln.diffs_a;
p = cns->curprof - 1;
while (p > aln.aepos-1)
{
cns->profile[n] = cns->profile[p];
p--;
n--;
}
b = aln.bepos - 1;
for (i = aln.pCtx->ntrace - 1; i >= 0; i--)
{
c = aln.pCtx->trace[i];
if (c > 0) // dash before B[-c]
{
c--;
while (c <= b)
{
cns->profile[n] = cns->profile[p];
cns->profile[n].counts[ (unsigned char)aln.B[b] ]++;
n--;
b--;
p--;
}
#ifdef CONSENSUS_KEEP_SEQUENCES
apply_gap(c + m_vecPositionTracking[nProfileStart] - nSeqStart, m_nSeqsAdded, m_nSeqsAdded+1);
#endif
cns->profile[n] = cns->profile[p];
cns->profile[n].counts[4]++;
n--;
p--;
}
else // dash before P[c]
{
c = -c;
c--;
while (c <= p)
{
cns->profile[n] = cns->profile[p];
cns->profile[n].counts[ (unsigned char)aln.B[b] ]++;
n--;
b--;
p--;
}
#ifdef CONSENSUS_KEEP_SEQUENCES
apply_gap(c, 0, m_nSeqsAdded);
#endif
memset(cns->profile + n, 0, sizeof(profile_entry));
cns->profile[n].counts[ (unsigned char)aln.B[b] ]++;
cns->profile[n].counts[4] = cns->added; // ++;
n--;
b--;
}
}
// aligned leftovers
while (b >= aln.bbpos)
{
cns->profile[n].counts[ (unsigned char)aln.B[b] ]++;
n--;
b--;
p--;
}
cns->curprof += aln.diffs_a;
cns->added++;
// consensus_print_profile(cns, stdout, 1);
}
int consensus_added(consensus* c)
{
return c->added;
}
char* consensus_sequence(consensus* c, int dashes)
{
profile_entry* pEntry;
if (c->nseq <= c->curprof)
{
c->nseq = c->curprof + 1;
c->seq = (char*)realloc(c->seq, c->nseq);
}
int curseq = 0;
unsigned char nMax, cMax;
unsigned short nCov;
// unsigned short nCovGaps;
int i, b;
for (i = 0; i < c->curprof; i++)
{
pEntry = c->profile + i;
nMax = cMax = 0;
// find out whether ACTG or - received the most "votes"
for (b = 0; b < 5; b++)
{
if (pEntry->counts[b] > nMax)
{
nMax = pEntry->counts[b];
cMax = b;
}
}
nCov = pEntry->counts[0] + pEntry->counts[1] + pEntry->counts[2] + pEntry->counts[3];
// nCovGaps = nCov + pEntry->counts[4];
if (c->added <= 2)
{
if ( c->added != nCov )
{
cMax = 4;
}
}
else if (nCov < c->added * CONS_MIN_COV_FRACTION)
{
cMax = 4;
}
// if it is a dash, but we don't have to add "-" to the consensus sequence
if ( cMax == 4 && !dashes )
{
continue;
}
c->seq[ curseq++ ] = decode_base(cMax);
}
c->seq[ curseq ] = '\0';
return c->seq;
}
|
MartinPippel/DAmar
|
utils/TKhist.c
|
/*
* TKhist.c
*
* Created on: 30 Nov 2016
* Author: pippelmn
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#include <unistd.h>
#include <math.h>
#include <sys/param.h>
#include "lib/colors.h"
#include "lib/oflags.h"
#include "lib/utils.h"
#include "lib/pass.h"
#include "lib/tracks.h"
#include "lib/stats.h"
#include "lib.ext/types.h"
#include "lib.ext/bitarr.h"
#include "db/DB.h"
#include "dalign/align.h"
#undef DEBUG
#define DEF_ARG_Q TRACK_Q
#define DEF_ARG_T TRACK_TRIM
#define DEF_ARG_R TRACK_REPEATS
typedef struct
{
HITS_DB* db;
HITS_TRACK *qTrack;
HITS_TRACK *rTrack;
HITS_TRACK *tTrack;
// file names
char* pcPathReadsIn;
char* pcPathOverlaps;
int verbose;
int nbin;
int64 *hist;
bit* vReads;
ovl_header_twidth twidth;
} TKhistContext;
static void usage()
{
printf("[-v] [-bs <int>] [-qrt track] <db> <ovl>\n");
printf("options: -v ... verbose\n");
printf(" -q ... q track (%s)\n", DEF_ARG_Q);
printf(" -r ... repeats track (%s)\n", DEF_ARG_R);
printf(" -t ... trim track (%s)\n", DEF_ARG_T);
}
static void tkhist_pre(PassContext *pctx, TKhistContext* tctx)
{
tctx->nbin = 100;
tctx->hist = (int64 *) malloc(sizeof(int64) * tctx->nbin);
bzero(tctx->hist, sizeof(int64) * tctx->nbin);
tctx->vReads = ba_new(DB_NREADS(tctx->db));
assert(tctx->vReads != NULL);
tctx->twidth = pctx->twidth;
}
static void tkhist_post(TKhistContext* tctx)
{
int i;
printf("qValue num\n");
for (i = tctx->nbin - 1; i >= 0; i--)
{
//if (tctx->hist[i] > 0)
{
printf("%d %lld\n", i, tctx->hist[i]);
}
}
}
static void addQvalues(TKhistContext *tctx, int rid)
{
int trim_b, trim_e;
track_anno* ranno = (track_anno*) (tctx->rTrack->anno);
track_data* rdata = (track_data*) (tctx->rTrack->data);
track_anno* qanno = (track_anno*) (tctx->qTrack->anno);
track_data* qdata = (track_data*) (tctx->qTrack->data);
// get trim track
get_trim(tctx->db, tctx->tTrack, rid, &trim_b, &trim_e);
//printf("%7d | trim %5d..%5d\n", rid, trim_b, trim_e);
if (trim_e - trim_b < 1000)
{
printf("trim interval too short!\n");
return;
}
track_anno rob = ranno[rid] / sizeof(track_data);
track_anno roe = ranno[rid + 1] / sizeof(track_data);
assert(rob <= roe);
track_anno qob = qanno[rid] / sizeof(track_data);
track_anno qoe = qanno[rid + 1] / sizeof(track_data);
assert(qob <= qoe);
// no repeats, take all complete segments within trim interval
if (rob >= roe)
{
int c = 0;
while (qob < qoe)
{
if(c >= trim_b + tctx->twidth && c <= trim_e - tctx->twidth)
{
int bin = qdata[qob];
if(bin > 100)
bin = 100;
if(tctx->verbose)
if(bin > 60 || bin == 0)
printf("Allert1! q%d in read %d in [%d, %d] trim [%d, %d]\n",bin, rid, c, c+tctx->twidth-1, trim_b, trim_e);
tctx->hist[bin]++;
#ifdef DEBUG
printf("%d - %d: q%d\n", rid, c, qdata[qob]);
#endif
}
qob++;
c += tctx->twidth;
}
}
else
{
int uniq_b, uniq_e;
uniq_b=trim_b;
int c = 0;
while (rob < roe)
{
#ifdef DEBUG
printf("%d trim [%d, %d] repeat [%d, %d]\n", rid, trim_b, trim_e, rdata[rob], rdata[rob+1]);
#endif
uniq_e = MIN(rdata[rob], trim_e);
if(uniq_e - uniq_b > tctx->twidth*3)
{
#ifdef DEBUG
printf("valid range: %d - %d\n", uniq_b, uniq_e);
#endif
//c=0;
while (qob < qoe && c < uniq_e)
{
if(c >= uniq_b + tctx->twidth && c <= uniq_e - tctx->twidth)
{
int bin = qdata[qob];
if(bin > 100)
bin = 100;
if(tctx->verbose)
if(bin > 60 || bin == 0)
printf("Allert2! q%d in read %d in [%d, %d] trim [%d, %d]\n",bin, rid, c, c+tctx->twidth-1, trim_b, trim_e);
tctx->hist[bin]++;
#ifdef DEBUG
printf("%d - %d: q%d\n", rid, c, qdata[qob]);
#endif
}
qob++;
c += tctx->twidth;
}
}
uniq_b=MAX(rdata[rob+1], trim_b);
rob+=2;
}
//c=0;
if(trim_e - uniq_b > tctx->twidth*3)
{
uniq_e = trim_e;
while (qob < qoe && c < uniq_e)
{
if(c >= uniq_b + tctx->twidth && c <= uniq_e - tctx->twidth)
{
int bin = qdata[qob];
if(bin > 100)
bin = 100;
if(tctx->verbose)
if(bin > 60 || bin == 0)
printf("Allert2! q%d in read %d in [%d, %d] trim [%d, %d]\n",bin, rid, c, c+tctx->twidth-1, trim_b, trim_e);
tctx->hist[bin]++;
#ifdef DEBUG
printf("%d - %d: q%d\n", rid, c, qdata[qob]);
#endif
}
qob++;
c += tctx->twidth;
}
}
}
}
static int tkhist_handler(void* _ctx, Overlap *ovls, int novl)
{
TKhistContext *tctx = (TKhistContext*) _ctx;
int i;
int aread, bread;
aread = ovls->aread;
if (ba_value(tctx->vReads, aread) == FALSE)
{
addQvalues(tctx, aread);
ba_assign(tctx->vReads, aread, TRUE);
}
for (i = 0; i < novl; i++)
{
Overlap *ovl = ovls + i;
bread = ovl->bread;
if (ba_value(tctx->vReads, bread) == TRUE)
{
continue;
}
addQvalues(tctx, bread);
ba_assign(tctx->vReads, bread, TRUE);
}
return 1;
}
int main(int argc, char* argv[])
{
HITS_DB db;
FILE* fileOvlIn;
PassContext *pctx;
TKhistContext tctx;
bzero(&tctx, sizeof(TKhistContext));
// set default values
tctx.verbose = 0;
char *qName = DEF_ARG_Q;
char *rName = DEF_ARG_R;
char *tName = DEF_ARG_T;
// process arguments
int c;
opterr = 0;
while ((c = getopt(argc, argv, "vq:r:t:")) != -1)
{
switch (c)
{
case 'v':
tctx.verbose++;
break;
case 'q':
qName = optarg;
break;
case 'r':
rName = optarg;
break;
case 't':
tName = optarg;
break;
default:
usage();
exit(1);
}
}
if (argc - optind == 2)
{
tctx.pcPathReadsIn = argv[optind++];
tctx.pcPathOverlaps = argv[optind++];
}
else
{
usage();
exit(1);
}
if ((fileOvlIn = fopen(tctx.pcPathOverlaps, "r")) == NULL)
{
fprintf(stderr, "could not open '%s'\n", tctx.pcPathOverlaps);
exit(1);
}
if (Open_DB(tctx.pcPathReadsIn, &db))
{
printf("could not open '%s'\n", tctx.pcPathReadsIn);
}
// load tracks
if ((tctx.qTrack = track_load(&db, qName)) == NULL)
{
printf("Could not load track %s\n", qName);
exit(1);
}
if ((tctx.rTrack = track_load(&db, rName)) == NULL)
{
printf("Could not load track %s\n", rName);
exit(1);
}
if ((tctx.tTrack = track_load(&db, tName)) == NULL)
{
printf("Could not load track %s\n", tName);
exit(1);
}
tctx.db = &db;
pctx = pass_init(fileOvlIn, NULL);
pctx->split_b = 0;
pctx->load_trace = 1;
pctx->unpack_trace = 1;
pctx->data = &tctx;
tkhist_pre(pctx, &tctx);
pass(pctx, tkhist_handler);
tkhist_post(&tctx);
Close_DB(&db);
return 0;
}
|
MartinPippel/DAmar
|
lib/stats.h
|
void ln_estimate(int* data, int n, double* mu, double* sig);
double ln_invcdf(double p, double mu, double sig);
double ln_p(double x, double mu, double sig);
void n_estimate(int* data, int n, double* mu, double* sig);
void n_estimate_double(double* data, int n, double* mu, double* sig);
|
MartinPippel/DAmar
|
utils/H5dextractUtils.h
|
#ifndef DEXTRACT_UTILS_H_
#define DEXTRACT_UTILS_H_
#include "stdio.h"
#include <math.h>
#include <sys/stat.h>
#include <ctype.h>
#include <hdf5.h>
typedef unsigned long long uint64;
typedef unsigned int uint32;
typedef unsigned short uint16;
typedef unsigned char uint8;
typedef signed long long int64;
typedef signed int int32;
typedef signed short int16;
typedef signed char int8;
// Exception codes
#define CANNOT_OPEN_BAX_FILE -1
#define BAX_BASECALL_ERR -2
#define BAX_DELETIONQV_ERR -3
#define BAX_DELETIONTAG_ERR -4
#define BAX_INSERTIONQV_ERR -5
#define BAX_MERGEQV_ERR -6
#define BAX_SUBSTITUTIONQV_ERR -7
#define BAX_QV_ERR -8
#define BAX_NR_EVENTS_ERR -9
#define BAX_REGION_ERR -10
#define BAX_HOLESTATUS_ERR -11
#define BAX_WIDTHINFRAMES_ERR -12
#define BAX_PREBASEFRAMES_ERR -13
#define BAX_HQREGIONSTARTTIME_ERR -14
#define BAX_HQREGIONENDTIME_ERR -15
#define BAX_PAUSINESS_ERR -16
#define BAX_PRODUCTIVITY_ERR -17
#define BAX_READTYPE_ERR -18
#define IGNORE_BAX -19
#define MAX_READ_LEN 100000
#define MAX_TIME_LIMIT 36000 // 10 hours
#define FRAME_RATE 75.0001831055
#define MAX_SUBREADS 1000
#define PHRED_OFFSET 33
#define NUC_COUNT 0
#define QV_SUM 1
#define DEL_SUM 2
#define INS_SUM 3
#define MER_SUM 4
#define SUB_SUM 5
// Print an error message
void printBaxError(int errorCode);
#define COMMA ','
void Print_Number(FILE* out, int64 num, int width);
enum subreadSelection { best, longest, shortest, all};
enum holeStatus { SEQUENCING, ANTIHOLE, FIDUCIAL, SUSPECT, ANTIMIRROR, FDZMW, FBZMW, ANTIBEAMLET, OUTSIDEFOV, UNKNOWN };
enum bases { BASE_A=0, BASE_C=1, BASE_G=2, BASE_T=3, BASE_N=4};
typedef enum { prod_Empty = 0, prod_Productive = 1, prod_Other = 2, prod_NotDefined = 255} productivity;
typedef enum { type_Empty = 0, type_FullHqRead0 = 1, type_FullHqRead1 = 2, type_PartialHqRead0 = 3, type_PartialHqRead1 = 4, type_PartialHqRead2 = 5, type_Multiload = 6, type_Indeterminate = 7, type_NotDefined = 255} readType ;
typedef struct
{
char *statOut;
char *fastaOut;
char *fastqOut;
char *quivaOut;
char *baxInFileName; // argument -F
char *wellNumbersInFileName; // argumen -w
int *numWellNumbers;
int **wellNumbers;
char **baxIn;
int nBax;
int nMaxBax;
int curBaxFile;
FILE *statFile;
FILE *fastaFile;
FILE *fastqFile;
FILE *quivaFile;
int zmw_minNrOfSubReads;
int MIN_LEN;
int MAX_LEN;
int MIN_QV;
int CUMULATIVE;
int READLEN_BIN_SIZE;
int TIME_BIN_SIZE;
int MIN_MOVIE_TIME;
int MAX_MOVIE_TIME;
int VERBOSE;
enum subreadSelection subreadSel;
} BAX_OPT;
BAX_OPT* parseBaxOptions(int argc, char ** argv);
void initBaxOptions(BAX_OPT *bopt);
void freeBaxOptions(BAX_OPT *bopt);
void printBaxOptions(BAX_OPT *bopt);
void readInputBaxFromFile(BAX_OPT *bopt);
void readWellNumbersFromFile(BAX_OPT *bopt);
typedef struct
{
char *fullName; // full file path
int shortNameBeg; // without path and file extension (used in header line)
int shortNameEnd;
// streams that are parsed from each bax file (per base)
unsigned char *baseCall; // base calls (ACGT)
unsigned char *delQV; // probability of a deletion error prior to the current base (PHRED QV)
unsigned char *delTag; // Likely identity of the deleted base, if it exists.
unsigned char *insQV; // probability that the current base is an insertion (PHRED QV)
unsigned char *mergeQV; // probability of a merged-pulse error at the current base (PHRED QV)
unsigned char *subQV; // probability of a substitution error at the current base (PHRED QV)
unsigned char *fastQV; // probability of a base calling error at the current base (PHRED QV)
unsigned short *widthInFrames; // duration of the base incorporation event, in frames
unsigned short *preBaseFrames; // duration between start of the base and the end of the previous base, in frames
char *holeStatus; // type of ZMW that produced the data (0 = SEQUENCING, 1 = ANTIHOLE, 2 = FIDUCIAL, 3 = SUSPECT,
// 4 = ANTIMIRROR, 5 = FDZMW, 6 = FBZMW, 7 = ANTIBEAMLET, 8 = OUTSIDEFOV)
int *numEvent; // event counts per zmw on the cell
int *region; // Regions table (read annotation)
int numZMW; // number of ZMW (Holes)
int numRegion; // number of region rows
int numBase; // number of raw bases
float *hqRegionBegTime, *hqRegionEndTime; // Start/End time of the HQ (Sequencing) region, in seconds (per ZMW)
float *pausiness; // Fraction of pause events over the HQ (sequencing) region
unsigned char *productivity; // ZMW productivity classification --> UnitsOrEncoding = 0:Empty,1:Productive,2:Other,255:NotDefined
unsigned char *readType; // ZMW read type classification --> UnitsOrEncoding = 0:Empty,1:FullHqRead0,2:FullHqRead1,3:PartialHqRead0,4:PartialHqRead1,5:PartialHqRead2,6:Multiload,7:Indeterminate,255:NotDefined
// information about the sequencing itself --> necessary for quiver
char *sequencingKit;
char *bindingKit;
char *softwareVersion;
char *sequencingChemistry; // optional
} BaxData;
void initBaxData(BaxData *b);
void ensureCapacity(BaxData *b, hsize_t numBaseCalls, hsize_t numHoles, hsize_t numHQReads);
void freeBaxData(BaxData *b);
void initBaxNames(BaxData *b, char *fname);
typedef struct
{
int minLen;
int minScore;
int cumulative;
int readLenBinSize;
int timeLenBinSize;
int minMovieTime;
int maxMovieTime;
int nLenBins;
int nTimBins;
int nFiles;
uint64 nZMWs;
uint64 readTypeHist[type_NotDefined+1];
uint64 productiveHist[prod_NotDefined+1];
uint64 stateHist[UNKNOWN+1];
float cumPausiness;
uint64 numSubreadBases;
uint64 numSubreads;
uint64 subreadHist[MAX_SUBREADS + 1];
uint64 *readLengthHist, *readLengthBasesHist, *readLengthTimeHist; // count read lengths and corresponding number of bases
uint64 **baseDistributionHist; // bins: 0 = A, 1 = C, 2 = G, 3 = T, 4 otherwise
uint64 **cumTimeDepQVs; // accessible via above definition
uint64 *cumSlowPolymeraseRegionLenHist, *nSlowPolymeraseRegionLenHist;
uint64 *cumSlowPolymeraseRegionTimeHist;
} BaxStatistic;
void initBaxStatistic(BaxStatistic *s, BAX_OPT *bopt);
void resetBaxStatistic(BaxStatistic *s);
void freeBaxStatistic(BaxStatistic* s);
typedef struct
{
int nRegions; // number of slow polymerase regions
int segmentWidth; // number of bases that are grouped together
int shift; // number of bases a segment window is shifted
int nmax; // allocated memory
int* beg; // begin of "slow/bad" region
int* end; // end of "slow/bad" region
int numSlowBases; //
} slowPolymeraseRegions;
void initSlowPolymeraseRegions(slowPolymeraseRegions *spr, int segmentWidth, int shift);
void resetSlowPolymeraseRegions(slowPolymeraseRegions *spr);
void ensureSlowPolymeraseRegionsCapacity(slowPolymeraseRegions *spr);
void deleteSlowPolymeraseRegions(slowPolymeraseRegions *spr);
int isBaseInSlowPolymeraseRegion(slowPolymeraseRegions *spr, int baseIdx);
typedef struct
{
int number; // one smart cell is usually stored in 3 files --> hole numbers: 1-54493, 54494-105k, 105k-160k
int index; // keeps index of hole number for current file
int regionRow; // keeps row from region table for current file
int hqBeg; // begin of high quality region within ZMW (corresponds to 2nd column of Regions table)
int hqEnd; // end of high quality region within ZMW (corresponds to 3rd column of Regions table)
int *insBeg; // begin of insert region within ZMW, can be more the one if adapter are present (corresponds to 2nd column of Regions table)
int *insEnd; // end of insert region within ZMW, can be more the one if adapter are present (corresponds to 3rd column of Regions table)
int *insTimeBeg; // in number of frames
int *insTimeEnd; // in number of frames
int regionScore; // corresponds to complete high quality region
enum holeStatus status;
productivity prod;
readType type;
float pausiness;
char *toReport; // [0|1] flags to specify which subreads from a ZMW should be reported
int numFrag;
int maxFrag;
int roff; // read offset
unsigned char **fragSequ; // keeps pointer on BaxData.basecall of current ZMW
unsigned char **fragQual; // keeps pointer on BaxData.fastQV of current ZMW
unsigned short **widthInFrames; // keeps pointer on BaxData.widthInFrames of current ZMW
unsigned short **preBaseFrames; // keeps pointer on BaxData.preBaseFrames of current ZMW
unsigned char **delQV; // keeps pointer on BaxData.delQV of current ZMW
unsigned char **delTag; // keeps pointer on BaxData.delTag of current ZMW
unsigned char **insQV; // keeps pointer on BaxData.insQV of current ZMW
unsigned char **mergeQV; // keeps pointer on BaxData.mergeQV of current ZMW
unsigned char **subQV; // keeps pointer on BaxData.subQV of current ZMW
int *len;
float *avgQV; // average qv per subread, based ion fragQV
slowPolymeraseRegions *spr;
} ZMW;
void initZMW(ZMW *z);
void resetZMW(ZMW *z);
void ensureZMWCapacity(ZMW *z);
void deleteZMW(ZMW *z);
void printZMW(ZMW *z);
///////////////////////////////// SOME GENERAL STUFF
#define SQR(a) ((a)*(a))
// estimates based on 2 data series (used for widthinframes+prebaseframes)
void ln_estimate2(unsigned short* data1, unsigned short* data2, int beg, int end, double* mu, double* sig);
void n_estimate2(unsigned short* data1, unsigned short* data2, int beg, int end, double* mu, double* sig);
char *trimwhitespace(char *str);
int parse_ranges(char *line, int* _reps, int** _pts);
int cmp_range(const void* l, const void* r);
#endif /* DEXTRACT_UTILS_H_ */
|
MartinPippel/DAmar
|
lib/oflags.c
|
<filename>lib/oflags.c
#include <stdlib.h>
#include "oflags.h"
OverlapFlag2Label oflag2label[] = {
{OVL_COMP, "complement", '<'},
{OVL_DISCARD, "discarded", 'x'},
{OVL_REPEAT, "repeat", '*'},
{OVL_STITCH, "stitched", '+'},
{OVL_TRIM, "trimmed", '-'},
{OVL_CONT, "contained", 'c'},
{OVL_GAP, "gap", '|'},
{OVL_OLEN, "overlap length", 'o'},
{OVL_RLEN, "read length", 'r'},
{OVL_LOCAL, "local alignment", 'l'},
{OVL_DIFF, "divergence", 'd'},
{OVL_SYMDISCARD, "symmetric discard", '#'},
{OVL_TEMP, "temporary flag", 't'},
{OVL_MODULE, "module", 'm'},
{OVL_OPTIONAL, "optional", '?'},
{0, NULL, '\0'}
};
void flags2str(char* pc, int flags)
{
int i;
int last = -1;
for (i = 0; oflag2label[i].mask; i++)
{
if ( flags & oflag2label[i].mask )
{
pc[i] = oflag2label[i].indicator;
last = i;
}
else
{
pc[i] = ' ';
}
}
pc[last+1] = '\0';
}
|
MartinPippel/DAmar
|
corrector/consensus.h
|
<filename>corrector/consensus.h
#pragma once
typedef struct
{
unsigned char counts[5]; // A C G T -
} profile_entry;
typedef struct
{
int* vector;
int vecmax;
int* trace;
int ntrace;
int* Stop; // Ongoing stack of alignment indels
char* Babs; // Absolute base of A and B sequences
int** PVF; // waves for NP alignment
int** PHF;
profile_entry* Aabs;
} v3_consensus_alignment_ctx;
typedef struct
{
profile_entry* profile;
int curprof;
int maxprof;
char* seq;
int nseq;
int alen;
int added;
v3_consensus_alignment_ctx* aln_ctx;
} consensus;
consensus* consensus_init();
void consensus_free(consensus* c);
void consensus_reset(consensus* c);
void consensus_add(consensus* c, char* seq, int sb, int se); // , int pb, int pe);
char* consensus_sequence(consensus* c, int dashes);
void consensus_print_profile(consensus* c, FILE* fileOut, int colorize);
int consensus_added(consensus* c);
|
MartinPippel/DAmar
|
touring/OGlayout.h
|
<reponame>MartinPippel/DAmar<gh_stars>10-100
/*
* OGLayout.h
*
* Created on: Jul 14, 2016
* Author: pippelmn
*/
#ifndef TOURING_OGLAYOUT_H_
#define TOURING_OGLAYOUT_H_
#define max(a,b) \
({ __typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a > _b ? _a : _b; })
#define min(a,b) \
({ __typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a < _b ? _a : _b; })
typedef struct Pair
{
char *key;
char *value;
} Pair;
typedef struct
{
int sourceId;
int targetId;
Pair* attributes;
int numAttributes;
int maxAttributes;
} OgEdge;
typedef struct
{
int nodeID;
Pair* attributes;
int numAttributes;
int maxAttributes;
} OgNode;
typedef struct
{
char *name;
char *type;
int id; // removed d, from ids d0, d1 ... dn
int forNode; // if forNode is 0, then its an edge attribute
} OgAttribute;
typedef struct
{
int numNodes;
OgNode* nodes;
int numEdges;
OgEdge* edges;
int numAttr;
OgAttribute *attrLookup;
} OgGraph;
// graph format
typedef enum
{
FORMAT_DOT, FORMAT_GRAPHML, FORMAT_SVG, FORMAT_UNKNOWN
} GraphFormat;
typedef struct
{
// command line args
int verbose;
int cleanReverseEdges;
int colorScheme;
int skipLayout;
int quadTreeLevel;
float barnesHutTheta;
int minLevelSize;
float coarseningRate;
float stepRatio;
float optimalDistance;
float convergenceThreshold;
char* path_graph_in;
char* path_graph_out;
// input graph
GraphFormat giformat;
GraphFormat goformat;
// overlap graph
OgGraph *graph;
} OgLayoutContext;
#define NODE_IS_MERGED (1 << 0)
#define NODE_HAS_PARENT (1 << 1)
#define NODE_HAS_CHILD (1 << 2)
#define NODE_HAS_MERGED_PARENT (1 << 3)
#define NODE_HAS_COORDINATES (1 << 4)
#define NODE_HAS_PATH_ID (1 << 5)
#define EDGE_VISITED (1 << 0)
#define EDGE_IGNORE (1 << 1)
typedef struct ForceVector
{
float x;
float y;
} ForceVector;
typedef struct
{
int flag;
int source; // represent indexes
int target; // from nodes (! not ids)
} Edge;
typedef struct Node
{
int flag;
int id;
int idx;
// 2D coordinates
float x;
float y;
// 2d force vector
ForceVector f;
// if path is in attributes
int pathID;
int childIds[2]; // pointer for Nodes of parent graph otherwise NULL
int parentId; // node pointer into child graph otherwise NULL
int firstEdgeIdx;
} Node;
typedef struct Graph
{
int maxNodes;
int curNodes;
int maxEdges;
int curEdges;
Node *nodes;
Edge *edges;
int level; // coarsening level
int maxNodeDegree;
struct Graph *parent;
struct Graph *child;
} Graph;
int cmpOgEdges(const void* a, const void *b);
int cmpNodesById(const void* a, const void *b);
int cmpEdgeBySourceNode(const void* a, const void *b);
void sortGraphEdges(Graph *g);
Graph* coarsenGraph(Graph *g, int verboseLevel);
void updateEdges(Graph *g);
void refineGraph(Graph *g);
void deleteGraph(Graph *g);
typedef struct YifanHuLayout
{
float optimalDistance;
float relativeStrength;
float step;
float initialStep;
int progress;
float stepRatio;
int quadTreeMaxLevel;
float barnesHutTheta;
float convergenceThreshold;
char adaptiveCooling;
double energy0;
double energy;
int converged;
} YifanHuLayout;
typedef struct MultiLevelLayout
{
Graph **graphs;
int maxGraphs;
int level;
double minCoarseningRate;
int minSize;
float *bestCoordinateSet;
} MultiLevelLayout;
typedef struct QuadTree
{
float posX;
float posY;
float size;
float centerMassX; // X and Y position of the center of mass
float centerMassY;
int mass; // Mass of this tree (the number of nodes it contains)
int maxLevel;
struct QuadTree* children;
int (*add)(struct QuadTree*, Node *);
char isLeaf;
float eps;
} QuadTree;
void initQuadTree(struct QuadTree *t, float posX, float posY, float size);
QuadTree* createQuadTree(int maxLevel);
void buildQuadTree(QuadTree* tree, Graph *g);
int addNode(QuadTree *t, Node* n);
void assimilateNode(QuadTree *t, Node *n);
int addToChildren(QuadTree *t, Node* n);
int firstAdd(QuadTree *t, Node* n);
int secondAdd(QuadTree *t, Node* n);
int rootAdd(QuadTree *t, Node *n);
int leafAdd(QuadTree *t, Node *n);
void divideTree(struct QuadTree *t);
ForceVector* createForceVectorByVector(ForceVector *f);
ForceVector* createForceVectorByPair(float x, float y);
ForceVector* createForceVector();
void addForceVectorToForceVector(ForceVector* f1, ForceVector *f2);
void multiplyForceVectorByConst(ForceVector* f1, float s);
void subtractForceVectorFromForceVector(ForceVector* f1, ForceVector *f2);
float getForceVectorEnergy(ForceVector *f);
float getForceVectorNorm(ForceVector *f);
ForceVector* normalizeForceVector(ForceVector *f);
typedef struct ElectricalForce
{
float theta;
float relativeStrength;
float optimalDistance;
} ElectricalForce;
typedef struct SpringForce
{
float optimalDistance;
} SpringForce;
ForceVector* calculateSpringForce(SpringForce* sf, Node *n1, Node *n2, float distance);
ForceVector* calculateElectricalForce(ElectricalForce* ef, Node* n, QuadTree *t, float distance);
ForceVector* calculateForce(ElectricalForce* fe, Node* n, QuadTree *t);
// ForceVector utils
float getForceVectorDistanceToQuadTree(Node *n, QuadTree *t);
float getForceVectorDistanceToNode(Node *n1, Node *n2);
// input / output
int read_dot(OgLayoutContext* octx);
int read_graphml(OgLayoutContext* octx);
void write_dot(OgLayoutContext *octx, Graph *g);
void write_svg(OgLayoutContext *octx, Graph *g);
void write_graphml(OgLayoutContext *octx, Graph *g);
#endif /* TOURING_OGLAYOUT_H_ */
|
MartinPippel/DAmar
|
utils/LAfilterChains.c
|
/*******************************************************************************************
*
* filters overlaps by various criteria
*
* Author : <NAME>
*
* Date : May 2015
*
*******************************************************************************************/
#include <assert.h>
#include <limits.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#include <unistd.h>
#include "lib/colors.h"
#include "lib/oflags.h"
#include "lib/pass.h"
#include "lib/read_loader.h"
#include "lib/tracks.h"
#include "lib/trim.h"
#include "lib/utils.h"
#include "dalign/align.h"
#include "db/DB.h"
#define DEF_ARG_R TRACK_REPEATS
#define DEF_ARG_T TRACK_TRIM
#define DEF_ARG_L TRACK_DUST
#define DEF_ARG_F 0
#define DEF_ARG_C 0
#define DEF_ARG_M 2400
#define DEF_ARG_W 600
#define DEF_ARG_D 28
#define DEF_ARG_O 4000
#define DEF_ARG_Z 20000
#define VERBOSE
#undef DEBUG_CHAIN
#undef CHAIN_DEBUG
#undef DEBUG_GAPS
#undef DEBUG_FILTER
#define ANCHOR_INVALID (1 << 0)
#define ANCHOR_TRIM (1 << 1)
#define ANCHOR_LOWCOMP (1 << 2)
typedef struct
{
Overlap **ovls;
int novl;
int maxOvl;
} Chain;
typedef struct
{
int beg;
int end;
int flag;
} anchorItv;
typedef struct
{
// stats counters
int statsFiltRepeat;
int statsFiltContained;
int statsFiltInvalidChain;
int statsLowCovALn;
int statsGapAlns;
// settings
int nMinNonRepeatBases;
int nFuzzBases;
int nContPerc;
int nVerbose;
int purgeLAS;
int dazzlerFlags;
int keepIdentity;
int maxBasesAtContigTips;
int maxOverallDiff; // add up all diffs from all chains divided by number of overlapping bases in A- and B-read
// repeat settings
int mergeRepDist;
int repeatWindowLookBack;
int rp_mergeTips;
int minChainLen;
// stitch settings
int stitchChain;
int stitchMaxTipFuzzy;
int stitchNonLowCompAnchorBases;
int stitchMaxGapSize;
int stitchMaxGapSizeInLowCompl;
int stitchMinChainLen;
int stitchMaxChainLASs;
int gapMinSpanners;
int minTipCoverage;
HITS_DB* db;
HITS_TRACK* trackRepeat;
HITS_TRACK* trackTrim;
HITS_TRACK* trackLowCompl;
FILE* fileOutDiscardedReads;
FILE* fileOutFullyDiscardedAreads;
int minLenOfFullyDiscardedAreads;
ovl_header_twidth twidth;
int nkeptChains; // 0 ... only best, otherwise keep all
Chain *ovlChains;
int curChains;
int maxChains;
int maxUniqAIntervals;
int curUniqAIntervals;
anchorItv *uniqAIntervals;
int maxUniqBIntervals;
int curUniqBIntervals;
anchorItv *uniqBIntervals;
TRIM* trim;
int areadID;
int trimLAS;
} FilterContext;
extern char* optarg;
extern int optind, opterr, optopt;
static int getRepeatBases(FilterContext *ctx, Overlap *ovl, int read)
{
if (ctx->trackRepeat == NULL)
{
return 0;
}
assert(ovl->aread == read || ovl->bread == read);
// int aLen = ovl->path.aepos - ovl->path.abpos;
int bLen = ovl->path.bepos - ovl->path.bbpos;
// get repeats track
track_anno* rep_anno = ctx->trackRepeat->anno;
track_data* rep_data = ctx->trackRepeat->data;
track_anno rb, re;
int nrep = 0;
rb = rep_anno[read] / sizeof(track_data);
re = rep_anno[read + 1] / sizeof(track_data);
// loop through all repeats in a
int rBeg, rEnd;
while (rb < re)
{
rBeg = rep_data[rb];
rEnd = rep_data[rb + 1];
if (ovl->aread == read)
{
nrep += intersect(ovl->path.abpos, ovl->path.aepos, rBeg, rEnd);
}
else
{
if (ovl->flags & OVL_COMP)
{
nrep += intersect(bLen - ovl->path.bepos, bLen - ovl->path.bbpos, rBeg, rEnd);
}
else
{
nrep += intersect(ovl->path.bbpos, ovl->path.bepos, rBeg, rEnd);
}
}
rb += 2;
}
return nrep;
}
static int cmp_chain_len(const void *a, const void *b)
{
Chain* c1 = (Chain *) a;
Chain* c2 = (Chain *) b;
int i;
int olen1 = c1->ovls[0]->path.aepos - c1->ovls[0]->path.abpos;
for (i = 1; i < c1->novl; i++)
{
olen1 += c1->ovls[i]->path.aepos - c1->ovls[i]->path.abpos;
if (c1->ovls[i - 1]->path.aepos > c1->ovls[i]->path.abpos)
olen1 -= c1->ovls[i - 1]->path.aepos > c1->ovls[i]->path.abpos;
}
int olen2 = c2->ovls[0]->path.aepos - c2->ovls[0]->path.abpos;
for (i = 1; i < c2->novl; i++)
{
olen2 += c2->ovls[i]->path.aepos - c2->ovls[i]->path.abpos;
if (c2->ovls[i - 1]->path.aepos > c2->ovls[i]->path.abpos)
olen2 -= c2->ovls[i - 1]->path.aepos > c2->ovls[i]->path.abpos;
}
return (olen2 - olen1);
}
static int cmp_ovls_abeg(const void* a, const void* b)
{
Overlap* o1 = *(Overlap**) a;
Overlap* o2 = *(Overlap**) b;
int cmp = o1->path.abpos - o2->path.abpos;
if (!cmp)
{
cmp = (o1->path.aepos - o1->path.abpos) - (o2->path.aepos - o2->path.abpos);
}
return cmp;
}
//#ifdef DEBUG_CHAIN
static void printChain(Chain *chain)
{
printf("CHAIN: nvols %d, %7d vs %7d %s\n", chain->novl, chain->ovls[0]->aread, chain->ovls[0]->bread, (chain->ovls[0]->flags & OVL_COMP) ? "COMP" : "NORM");
int i;
for (i = 0; i < chain->novl; ++i)
{
printf("%3d in A [%8d,%8d] in B [%8d,%8d] %5.2f\n", i, chain->ovls[i]->path.abpos, chain->ovls[i]->path.aepos, chain->ovls[i]->path.bbpos,
chain->ovls[i]->path.bepos, chain->ovls[i]->path.diffs * 100.0 / (chain->ovls[i]->path.aepos - chain->ovls[i]->path.abpos));
}
}
//#endif
static int contained(int ab, int ae, int bb, int be)
{
if (ab >= bb && ae <= be)
{
return 1;
}
return 0;
}
static void chain(FilterContext *ctx, Overlap *ovls, int n)
{
/// TODO hard coded
int MIN_OVL_LOOKAHEAD = 2000;
int MAX_OVL_LOOKAHEAD = 30000;
int STRIDE_OVL_LOOKAHEAD = 2000;
int aread, bread;
int alen, blen;
int i;
aread = ovls->aread;
bread = ovls->bread;
alen = DB_READ_LEN(ctx->db, aread);
blen = DB_READ_LEN(ctx->db, bread);
#ifdef DEBUG_CHAIN
printf("chain(%d,%d,%d) CHAIN: n%d m%d\n", ovls->aread, ovls->bread, n, ctx->curChains, ctx->maxChains);
#endif
if (n < 2)
{
if(ctx->maxBasesAtContigTips > 0)
{
if((ovls->path.abpos > ctx->maxBasesAtContigTips && ovls->path.aepos < alen - ctx->maxBasesAtContigTips)
|| (ovls->path.bbpos > ctx->maxBasesAtContigTips && ovls->path.bepos < blen - ctx->maxBasesAtContigTips) )
{
ovls->flags |= OVL_DISCARD;
return;
}
}
if (ctx->ovlChains->ovls == NULL)
{
ctx->ovlChains->novl = 0;
ctx->ovlChains->maxOvl = 10;
ctx->ovlChains->ovls = (Overlap**) malloc(sizeof(Overlap*) * ctx->ovlChains->maxOvl);
}
ctx->ovlChains->ovls[0] = ovls;
ovls->flags |= OVL_TEMP;
ctx->ovlChains->novl++;
ctx->curChains++;
#ifdef DEBUG_CHAIN
printChain(ctx->ovlChains);
#endif
return;
}
{
int i, j;
// get rid of contained overlaps or overlaps that are not in region of interest (in case -u bases was set)
for (i = 0; i < n; i++)
{
Overlap *ovl_i = ovls + i;
if(ctx->maxBasesAtContigTips > 0)
{
if((ovl_i->path.abpos > ctx->maxBasesAtContigTips && ovl_i->path.aepos < alen - ctx->maxBasesAtContigTips) ||
(ovl_i->path.bbpos > ctx->maxBasesAtContigTips && ovl_i->path.bepos < blen - ctx->maxBasesAtContigTips) )
{
ovl_i->flags |= OVL_CONT; // make use of OVL_CONT flag even they are not contained by defintion
continue;
}
}
if (ovl_i->flags & (OVL_CONT))
continue;
for (j = i + 1; j < n; j++)
{
Overlap *ovl_j = ovls + j;
if (contained(ovl_j->path.abpos, ovl_j->path.aepos, ovl_i->path.abpos, ovl_i->path.aepos) && contained(ovl_j->path.bbpos, ovl_j->path.bepos, ovl_i->path.bbpos, ovl_i->path.bepos))
{
ovl_j->flags |= (OVL_CONT);
ctx->statsFiltContained++;
}
}
}
}
int nremain = n;
#ifdef DEBUG_CHAIN
printf("find already excluded overlaps\n");
#endif
{
for (i = 0; i < n; i++)
{
Overlap *ovl_i = ovls + i;
if (ovl_i->flags & (OVL_CONT | OVL_TRIM))
{
nremain--;
}
}
}
#ifdef DEBUG_CHAIN
printf("nremain %d\n", nremain);
#endif
if (nremain == 0)
return;
int round = 0;
while (nremain > 0) // use nremain to find putative chain starting ovls
{
round++;
int longestUniqOvlBases = -1;
int longestUniqOvlIdx = -1;
int longestOvlBases = -1;
int longestOvlIdx = -1;
// find longest overlap based on number of unique bases
for (i = 0; i < n; i++)
{
Overlap *ovl = ovls + i;
if (ovl->flags & (OVL_CONT | OVL_TEMP | OVL_REPEAT | OVL_TRIM))
{
continue;
}
int aLen = ovl->path.aepos - ovl->path.abpos;
int bLen = ovl->path.bepos - ovl->path.bbpos;
int aRep = getRepeatBases(ctx, ovl, ovl->aread);
int bRep = getRepeatBases(ctx, ovl, ovl->bread);
#ifdef DEBUG_CHAIN
printf("%d - %d [%d, %d] [%d, %d], aR %d/%d, bR %d/%d\n", aread, bread, ovl->path.abpos, ovl->path.aepos, ovl->path.bbpos, ovl->path.bepos, aLen, aRep,
bLen, bRep);
#endif
int tmpBases = MAX(aLen - aRep, bLen - bRep);
if (tmpBases > longestUniqOvlBases)
{
longestUniqOvlBases = tmpBases;
longestUniqOvlIdx = i;
}
tmpBases = MAX(aLen, bLen);
if (tmpBases > longestOvlBases)
{
longestOvlBases = tmpBases;
longestOvlIdx = i;
}
}
if (longestOvlIdx < 0)
{
//printf("Unable to find new chain start ovl! nremain %d, curChains %d\n", nremain, ctx->curChains);
return;
}
if (longestUniqOvlBases < ctx->nMinNonRepeatBases + 1)
{
#ifdef DEBUG_CHAIN
printf("Number of unique bases to low. Use longest overlap.\n");
#endif
if (round > 1)
{
#ifdef DEBUG_CHAIN
printf("Break out of chain. Cannot find unique anchor alignment to start a chain.\n");
#endif
return;
}
longestUniqOvlBases = longestOvlBases;
longestUniqOvlIdx = longestOvlIdx;
}
#ifdef DEBUG_CHAIN
printf("longest overlap:\n");
printf("idx: %d --> uB %d, %d - %d [%d, %d] [%d, %d]\n", longestUniqOvlIdx, longestUniqOvlBases, ovls[longestUniqOvlIdx].aread,
ovls[longestUniqOvlIdx].bread, ovls[longestUniqOvlIdx].path.abpos, ovls[longestUniqOvlIdx].path.aepos, ovls[longestUniqOvlIdx].path.bbpos,
ovls[longestUniqOvlIdx].path.bepos);
#endif
// try to "elongate" longest overlap
// 1st on the right
// 2nd on the left side
if (ctx->curChains == ctx->maxChains)
{
ctx->maxChains = ctx->maxChains * 1.2 + 5;
ctx->ovlChains = (Chain*) realloc(ctx->ovlChains, sizeof(Chain) * ctx->maxChains);
bzero(ctx->ovlChains + ctx->curChains, sizeof(Chain) * (ctx->maxChains - ctx->curChains));
}
Chain *chain = ctx->ovlChains + ctx->curChains;
#ifdef DEBUG_CHAIN
printf("chain: nOvl: %d, maxOvl %d, nremain: %d\n", chain->novl, chain->maxOvl, nremain);
#endif
if (chain->ovls == NULL)
{
chain->novl = 0;
chain->maxOvl = 10;
chain->ovls = (Overlap**) malloc(sizeof(Overlap*) * chain->maxOvl);
#ifdef DEBUG_CHAIN
printf("chain: nOvl: %d, maxOvl %d\n", chain->novl, chain->maxOvl);
#endif
}
chain->ovls[0] = ovls + longestUniqOvlIdx;
chain->ovls[0]->flags |= OVL_TEMP;
chain->novl++;
nremain--;
#ifdef DEBUG_CHAIN
printf("chain: nOvl: %d, maxOvl %d, nremain %d\n", chain->novl, chain->maxOvl, nremain);
#endif
int ab1, ae1;
int bb1, be1;
int ab2, ae2;
int bb2, be2;
if (nremain && longestUniqOvlIdx + 1 < n)
{
ab1 = ovls[longestUniqOvlIdx].path.abpos;
ae1 = ovls[longestUniqOvlIdx].path.aepos;
bb1 = ovls[longestUniqOvlIdx].path.bbpos;
be1 = ovls[longestUniqOvlIdx].path.bepos;
#ifdef DEBUG_CHAIN
printf("extend longest overlap in right direction\n");
#endif
// 1st right
int cont = 1;
int curBestUniqOffset = 1;
int curBestUniqBases = -1;
int curBestBases = -1;
int curBestOffset = 1;
int curBestIntersection = MAX(alen, blen);
while (cont)
{
int stepSize;
for (stepSize = MIN_OVL_LOOKAHEAD; stepSize <= MAX_OVL_LOOKAHEAD && curBestUniqBases == -1; stepSize += STRIDE_OVL_LOOKAHEAD)
{
#ifdef DEBUG_CHAIN
printf("FOR LOOP stepsize %d\n", stepSize);
#endif
for (i = longestUniqOvlIdx + curBestUniqOffset; i < n; i++)
{
Overlap * ovl = ovls + i;
ab2 = ovl->path.abpos;
ae2 = ovl->path.aepos;
bb2 = ovl->path.bbpos;
be2 = ovl->path.bepos;
if ((ovl->flags & OVL_COMP) != (ovls[longestUniqOvlIdx].flags & OVL_COMP))
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> different orientations\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
if (ovl->flags & OVL_CONT)
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> really contained repeat\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
if (ovl->flags & OVL_TEMP)
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> is part of another chain\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
if (ovl->flags & OVL_DISCARD)
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> discarded\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
// todo mark those as discard ????
if (contained(ab2, ae2, ab1, ae1))
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> contained repeat in A-interval\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
// todo mark those as discard ????
if (contained(bb2, be2, bb1, be1))
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> contained repeat in B-interval\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
if (ae2 < ae1 || be2 < be1) // also overlap must follow right direction
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> improper right extension direction (stepSize %d)\n", i, ovl->aread, ovl->bread, ab2, ae2,
bb2, be2, stepSize);
#endif
continue;
}
if (MAX(ab2 - ae1, bb2 - be1) > stepSize)
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> gap size too large (stepSize %d)\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2,
stepSize);
#endif
continue;
}
if (ae1 - ab2 > ae2 - ae1 || be1 - bb2 > be2 - be1) // at least 50% overhang
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> overhang too short (stepSize %d)\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2,
stepSize);
#endif
continue;
}
// check if current overlap is better (longer/more unique bases ?) then curBest
int curUniqBasesInAIvl = (ae2 - ab2) - getRepeatBases(ctx, ovl, aread);
int curUniqBasesInBIvl = (be2 - bb2) - getRepeatBases(ctx, ovl, bread);
if (curBestIntersection > MAX(intersect(ab1, ae1, ab2, ae2), intersect(bb1, be1, bb2, be2)) && curBestBases < MIN(ae2 - ab2, be2 - bb2))
{
curBestBases = MIN(ae2 - ab2, be2 - bb2);
curBestOffset = i - longestUniqOvlIdx;
curBestIntersection = MAX(intersect(ab1, ae1, ab2, ae2), intersect(bb1, be1, bb2, be2));
}
if (curBestUniqBases < MIN(curUniqBasesInAIvl, curUniqBasesInBIvl))
{
#ifdef DEBUG_CHAIN
printf("found right current best overlap %d %d %d: [%d, %d] [%d, %d] right side\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
curBestUniqOffset = i - longestUniqOvlIdx;
curBestUniqBases = MIN(curUniqBasesInAIvl, curUniqBasesInBIvl);
}
else if (curBestUniqBases == -1 && stepSize + STRIDE_OVL_LOOKAHEAD > MAX_OVL_LOOKAHEAD) // for repetitive genomes
{
Overlap *tmpOvl = ovls + (longestUniqOvlIdx + curBestOffset);
if ((intersect(ab1, ae1, tmpOvl->path.abpos, tmpOvl->path.aepos) < ae1 - tmpOvl->path.abpos) && (intersect(bb1, be1, tmpOvl->path.bbpos, tmpOvl->path.bepos) < be1 - tmpOvl->path.bbpos))
{
curBestUniqOffset = curBestOffset;
curBestUniqBases = 1;
}
}
else
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> cannot be anchored (stepSize %d)\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2,
stepSize);
#endif
}
}
}
// check if left best overlap can be used to extend overlap group on the right side
if (curBestUniqBases < 0) // i.e. there was no good overlap at right side
{
#ifdef DEBUG_CHAIN
printf("could not extend ovlgroup on right side with proper overlap (with stepSize %d)\n", stepSize - STRIDE_OVL_LOOKAHEAD);
#endif
break;
}
/// todo further sanity check necessary ???
ab2 = ovls[longestUniqOvlIdx + curBestUniqOffset].path.abpos;
ae2 = ovls[longestUniqOvlIdx + curBestUniqOffset].path.aepos;
bb2 = ovls[longestUniqOvlIdx + curBestUniqOffset].path.bbpos;
be2 = ovls[longestUniqOvlIdx + curBestUniqOffset].path.bepos;
#ifdef DEBUG_CHAIN
printf("extend ovlgroup with (right): %d %d %d: [%d, %d] [%d, %d] stepSize %d\n", longestUniqOvlIdx + curBestUniqOffset,
ovls[longestUniqOvlIdx + curBestUniqOffset].aread, ovls[longestUniqOvlIdx + curBestUniqOffset].bread, ab1, ae1, ab2, ae2,
stepSize - STRIDE_OVL_LOOKAHEAD);
#endif
if (chain->novl == chain->maxOvl)
{
chain->maxOvl = chain->maxOvl * 1.2 + 5;
chain->ovls = (Overlap**) realloc(chain->ovls, sizeof(Overlap*) * chain->maxOvl);
}
// append left side overlaps at the end of chain, i.e. chain must be sorted afterwards by abpos
chain->ovls[chain->novl] = ovls + (longestUniqOvlIdx + curBestUniqOffset);
chain->ovls[chain->novl]->flags |= OVL_TEMP;
chain->novl++;
nremain--;
#ifdef DEBUG_CHAIN
printf("chain: nOvl: %d, maxOvl %d nremain %d\n", chain->novl, chain->maxOvl, nremain);
#endif
ab1 = ab2;
ae1 = ae2;
bb1 = bb2;
be1 = be2;
curBestUniqOffset++;
curBestOffset = curBestUniqOffset;
curBestUniqBases = -1;
curBestBases = -1;
curBestIntersection = MAX(alen, blen);
if (longestUniqOvlIdx + curBestUniqOffset >= n)
{
cont = 0;
}
}
}
if (nremain && longestUniqOvlIdx > 0)
{
ab1 = ovls[longestUniqOvlIdx].path.abpos;
ae1 = ovls[longestUniqOvlIdx].path.aepos;
bb1 = ovls[longestUniqOvlIdx].path.bbpos;
be1 = ovls[longestUniqOvlIdx].path.bepos;
#ifdef DEBUG_CHAIN
printf("extend longest overlap in left direction\n");
#endif
// 2nd left side
int cont = 1;
int curBestUniqOffset = 1;
int curBestUniqBases = -1;
int curBestBases = -1;
int curBestOffset = 1;
int curBestIntersection = MAX(alen, blen);
while (cont)
{
int stepSize;
for (stepSize = MIN_OVL_LOOKAHEAD; stepSize <= MAX_OVL_LOOKAHEAD && curBestUniqBases == -1; stepSize += STRIDE_OVL_LOOKAHEAD)
{
#ifdef DEBUG_CHAIN
printf("FOR LOOP stepsize %d\n", stepSize);
#endif
// try to find next best overlap with lookahead of stepSize bases
for (i = longestUniqOvlIdx - curBestUniqOffset; i >= 0; --i)
{
Overlap * ovl = ovls + i;
#ifdef DEBUG_CHAIN
printf("LEFT: Check ovl: a[%d, %d] b[%d,%d]\n", ovl->path.abpos, ovl->path.aepos, ovl->path.bbpos, ovl->path.bepos);
#endif
ab2 = ovl->path.abpos;
ae2 = ovl->path.aepos;
bb2 = ovl->path.bbpos;
be2 = ovl->path.bepos;
if ((ovl->flags & OVL_COMP) != (ovls[longestUniqOvlIdx].flags & OVL_COMP))
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> different orientations\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
if (ovl->flags & OVL_CONT)
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> really contained repeat\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
if (ovl->flags & OVL_TEMP)
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> is part of another chain\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
if (ovl->flags & OVL_DISCARD)
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> discarded\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
// todo mark those as discard ????
if (contained(ab2, ae2, ab1, ae1))
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> contained repeat in A-interval\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
// todo mark those as discard ????
if (contained(bb2, be2, bb1, be1))
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> contained repeat in B-interval\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
continue;
}
if (ab2 > ab1 || bb2 > bb1) // also overlap must follow left direction
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> improper left extension direction (stepSize %d)\n", i, ovl->aread, ovl->bread, ab2, ae2,
bb2, be2, stepSize);
#endif
continue;
}
if (MAX(ab1 - ae2, bb1 - be2) > stepSize)
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> gap size too large (stepSize %d)\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2,
stepSize);
#endif
continue;
}
if (ae2 - ab1 > ab1 - ab2 || be2 - bb1 > bb1 - bb2) // at least 50% overhang
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> overhang too short (stepSize %d)\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2,
stepSize);
#endif
continue;
}
// check if current overlap is better (longer/more unique bases ?) then curLeftBest
int curUniqBasesInAIvl = (ae2 - ab2) - getRepeatBases(ctx, ovl, aread);
int curUniqBasesInBIvl = (be2 - bb2) - getRepeatBases(ctx, ovl, bread);
if (curBestIntersection > MAX(intersect(ab2, ae2, ab1, ae1), intersect(bb2, be2, bb1, be1)) && curBestBases < MIN(ae2 - ab2, be2 - bb2))
{
curBestBases = MIN(ae2 - ab2, be2 - bb2);
curBestOffset = longestUniqOvlIdx - i;
curBestIntersection = MAX(intersect(ab2, ae2, ab1, ae1), intersect(bb2, be2, bb1, be1));
}
if (curBestUniqBases < MIN(curUniqBasesInAIvl, curUniqBasesInBIvl))
{
#ifdef DEBUG_CHAIN
printf("found left current best overlap %d %d %d: [ab2 %d, ae2 %d] [bb2 %d, be2 %d] left side\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2);
#endif
curBestUniqOffset = longestUniqOvlIdx - i;
curBestUniqBases = curUniqBasesInAIvl + curUniqBasesInBIvl;
}
else if (curBestUniqBases == -1 && stepSize + STRIDE_OVL_LOOKAHEAD > MAX_OVL_LOOKAHEAD) // for repetitive genomes
{
Overlap *tmpOvl = ovls + (longestUniqOvlIdx - curBestOffset);
if ((intersect(tmpOvl->path.abpos, tmpOvl->path.aepos, ab1, ae1) < ae1 - tmpOvl->path.abpos) && (intersect(tmpOvl->path.bbpos, tmpOvl->path.bepos, bb1, be1) < be1 - tmpOvl->path.bbpos))
{
curBestUniqOffset = curBestOffset;
curBestUniqBases = 1;
}
}
else
{
#ifdef DEBUG_CHAIN
printf("ignore overlap %d %d %d: [%d, %d] [%d, %d] --> cannot be anchored (stepSize %d)\n", i, ovl->aread, ovl->bread, ab2, ae2, bb2, be2,
stepSize);
#endif
}
}
}
// check if left best overlap can be used to extend overlap group on the left side
if (curBestUniqBases < 0) // i.e. there was no good overlap at left side
{
#ifdef DEBUG_CHAIN
printf("could not extend ovlgroup on left side with proper overlap (stepSize %d)\n", stepSize - STRIDE_OVL_LOOKAHEAD);
#endif
break;
}
/// todo further sanity check necessary ???
ab2 = ovls[longestUniqOvlIdx - curBestUniqOffset].path.abpos;
ae2 = ovls[longestUniqOvlIdx - curBestUniqOffset].path.aepos;
bb2 = ovls[longestUniqOvlIdx - curBestUniqOffset].path.bbpos;
be2 = ovls[longestUniqOvlIdx - curBestUniqOffset].path.bepos;
#ifdef DEBUG_CHAIN
printf("extend ovlgroup with (left): %d %d %d: [%d, %d] [%d, %d] with stepSize %d\n", longestUniqOvlIdx - curBestUniqOffset,
ovls[longestUniqOvlIdx - curBestUniqOffset].aread, ovls[longestUniqOvlIdx - curBestUniqOffset].bread, ab1, ae1, ab2, ae2,
stepSize - STRIDE_OVL_LOOKAHEAD);
#endif
if (ctx->curChains == ctx->maxChains)
{
ctx->maxChains = ctx->maxChains * 1.2 + 5;
ctx->ovlChains = (Chain*) realloc(ctx->ovlChains, sizeof(Chain) * ctx->maxChains);
bzero(ctx->ovlChains + ctx->curChains, sizeof(Chain) * (ctx->maxChains - ctx->curChains));
}
if (chain->novl == chain->maxOvl)
{
chain->maxOvl = chain->maxOvl * 1.2 + 5;
chain->ovls = (Overlap**) realloc(chain->ovls, sizeof(Overlap*) * chain->maxOvl);
}
// append left side overlaps at the end of chain, i.e. chain must be sorted afterwards by abpos
chain->ovls[chain->novl] = ovls + (longestUniqOvlIdx - curBestUniqOffset);
chain->ovls[chain->novl]->flags |= OVL_TEMP;
chain->novl++;
nremain--;
#ifdef DEBUG_CHAIN
printf("chain: nOvl: %d, maxOvl %d nremain %d\n", chain->novl, chain->maxOvl, nremain);
#endif
ab1 = ab2;
ae1 = ae2;
bb1 = bb2;
be1 = be2;
curBestUniqOffset++;
curBestOffset = curBestUniqOffset;
curBestUniqBases = -1;
curBestBases = -1;
curBestIntersection = MAX(alen, blen);
if (longestUniqOvlIdx - curBestUniqOffset < 0)
{
cont = 0;
}
}
if (chain->novl > 1)
{ // sort chain
qsort(chain->ovls, chain->novl, sizeof(Overlap*), cmp_ovls_abeg);
}
}
#ifdef DEBUG_CHAIN
printf("chain: nOvl: %d, maxOvl %d nremain: %d\n", chain->novl, chain->maxOvl, nremain);
#endif
// find possible ovls that could be added to chain (i.e. fill gaps)
if (chain->novl > 1 /*&& nremain > 0*/) // allow extension with previously repeat-marked overlaps
{
#ifdef DEBUG_CHAIN
printf("find possible ovls that could be added to chain (i.e. fill gaps)\n");
#endif
int chainIdx = 0;
int chainLastIdx = chain->novl - 1;
int j;
for (i = 0; i < n; i++)
{
Overlap *ovl = ovls + i;
if ((ovl->flags & (OVL_TEMP | OVL_CONT | OVL_TRIM)) || ((ovl->flags & OVL_COMP) != (chain->ovls[chainIdx]->flags & OVL_COMP)))
continue;
if (ovl->path.abpos < chain->ovls[chainIdx]->path.abpos)
continue;
if (ovl->path.abpos > chain->ovls[chainLastIdx]->path.abpos)
break;
int ovhBases = 100;
for (j = chainIdx; j < chainLastIdx; j++)
{
if (chain->ovls[j]->path.aepos - ovhBases < ovl->path.abpos && chain->ovls[j + 1]->path.abpos + ovhBases > ovl->path.aepos && chain->ovls[j]->path.bepos - ovhBases < ovl->path.bbpos && chain->ovls[j + 1]->path.bbpos + ovhBases > ovl->path.bepos)
{
Overlap *lastAddedOvl = chain->ovls[chain->novl - 1];
if (intersect(ovl->path.abpos, ovl->path.aepos, lastAddedOvl->path.abpos, lastAddedOvl->path.aepos) > ovhBases || intersect(ovl->path.bbpos, ovl->path.bepos, lastAddedOvl->path.bbpos, lastAddedOvl->path.bepos) > ovhBases)
break;
if (chain->novl == chain->maxOvl)
{
chain->maxOvl = chain->maxOvl * 1.2 + 5;
chain->ovls = (Overlap**) realloc(chain->ovls, sizeof(Overlap*) * chain->maxOvl);
}
// append left side overlaps at the end of chain, i.e. chain must be sorted afterwards by abpos
ovl->flags &= ~(OVL_DISCARD); //
ovl->flags |= OVL_TEMP;
chain->ovls[chain->novl] = ovl;
chain->novl++;
//nremain--;
#ifdef DEBUG_CHAIN
printf("chain: nOvl: %d, maxOvl %d nremain %d\n", chain->novl, chain->maxOvl, nremain);
#endif
}
if (ovl->path.abpos > chain->ovls[j + 1]->path.abpos)
chainIdx++;
}
}
if (chainLastIdx < chain->novl - 1)
{
qsort(chain->ovls, chain->novl, sizeof(Overlap*), cmp_ovls_abeg);
}
}
#ifdef DEBUG_CHAIN
printChain(chain);
#endif
ctx->curChains++;
}
// sort chains according to alignment lengths
if (ctx->curChains > 1)
{
#ifdef DEBUG_CHAIN
printf("SORT CHAINS (longest first):\n");
#endif
qsort(ctx->ovlChains, ctx->curChains, sizeof(Chain), cmp_chain_len);
}
}
static int filter(FilterContext* ctx, Overlap* ovl)
{
int ret = 0;
int ovlBLen = DB_READ_LEN(ctx->db, ovl->bread);
if (ctx->nMinNonRepeatBases != -1 && ovl->aread != ovl->bread)
{
int b, e, rb, re, ovllen, repeat;
track_anno* repeats_anno = ctx->trackRepeat->anno;
track_data* repeats_data = ctx->trackRepeat->data;
ovllen = ovl->path.aepos - ovl->path.abpos;
repeat = 0;
b = repeats_anno[ovl->aread] / sizeof(track_data);
e = repeats_anno[ovl->aread + 1] / sizeof(track_data);
for (; b < e; b += 2)
{
rb = repeats_data[b];
re = repeats_data[b + 1];
if (rb > ovl->path.aepos)
break;
else if (re < ovl->path.abpos)
continue;
repeat += intersect(ovl->path.abpos, ovl->path.aepos, rb, re);
}
if (repeat > 0 && ovllen - repeat < ctx->nMinNonRepeatBases)
{
if (ctx->nVerbose)
{
printf("overlap %d -> %d: drop due to repeat in a\n", ovl->aread, ovl->bread);
}
ctx->statsFiltRepeat++;
ret |= OVL_REPEAT;
}
if (!(ret & OVL_REPEAT))
{
ovllen = ovl->path.bepos - ovl->path.bbpos;
int bbpos, bepos;
if (ovl->flags & OVL_COMP)
{
bbpos = ovlBLen - ovl->path.bepos;
bepos = ovlBLen - ovl->path.bbpos;
}
else
{
bbpos = ovl->path.bbpos;
bepos = ovl->path.bepos;
}
repeat = 0;
b = repeats_anno[ovl->bread] / sizeof(track_data);
e = repeats_anno[ovl->bread + 1] / sizeof(track_data);
for (; b < e; b += 2)
{
rb = repeats_data[b];
re = repeats_data[b + 1];
if (rb > bepos)
break;
else if (re < bbpos)
continue;
repeat += intersect(bbpos, bepos, rb, re);
}
if (repeat > 0 && ovllen - repeat < ctx->nMinNonRepeatBases)
{
if (ctx->nVerbose)
{
printf("overlap %d -> %d: drop due to repeat in b\n", ovl->aread, ovl->bread);
}
ctx->statsFiltRepeat++;
ret |= OVL_REPEAT;
}
}
}
return ret;
}
static void filter_pre(PassContext* pctx, FilterContext* fctx)
{
#ifdef VERBOSE
printf( ANSI_COLOR_GREEN "PASS filtering\n" ANSI_COLOR_RESET);
printf( ANSI_COLOR_RED "OPTIONS\n" ANSI_COLOR_RESET);
printf( ANSI_COLOR_RED " keepIdentity %d\n" ANSI_COLOR_RESET, fctx->keepIdentity);
printf( ANSI_COLOR_RED " mergeRepDist %d\n" ANSI_COLOR_RESET, fctx->mergeRepDist);
printf( ANSI_COLOR_RED " nContPerc %d\n" ANSI_COLOR_RESET, fctx->nContPerc);
printf( ANSI_COLOR_RED " nFuzzBases %d\n" ANSI_COLOR_RESET, fctx->nFuzzBases);
printf( ANSI_COLOR_RED " nMinNonRepeatBases %d\n" ANSI_COLOR_RESET, fctx->nMinNonRepeatBases);
printf( ANSI_COLOR_RED " repeatWindowLookBack %d\n" ANSI_COLOR_RESET, fctx->repeatWindowLookBack);
printf( ANSI_COLOR_RED " maxBasesAtContigTips %d\n" ANSI_COLOR_RESET, fctx->maxBasesAtContigTips);
if(fctx->trackRepeat)
printf( ANSI_COLOR_RED " RepeatTrack %s\n" ANSI_COLOR_RESET, fctx->trackRepeat->name);
if(fctx->trackTrim)
printf( ANSI_COLOR_RED " TrimTrack %s\n" ANSI_COLOR_RESET, fctx->trackTrim->name);
if(fctx->trackLowCompl)
printf( ANSI_COLOR_RED " LowComplexityTrack %s\n" ANSI_COLOR_RESET, fctx->trackLowCompl->name);
#endif
fctx->twidth = pctx->twidth;
fctx->curChains = 0;
fctx->maxChains = 5;
fctx->ovlChains = (Chain*) malloc(sizeof(Chain) * MAX(fctx->maxChains, fctx->nkeptChains));
bzero(fctx->ovlChains, sizeof(Chain) * MAX(fctx->maxChains, fctx->nkeptChains));
fctx->maxUniqAIntervals = 20;
fctx->uniqAIntervals = malloc(sizeof(anchorItv) * fctx->maxUniqAIntervals);
bzero(fctx->uniqAIntervals, sizeof(anchorItv) * fctx->maxUniqAIntervals);
fctx->curUniqAIntervals = 0;
fctx->maxUniqBIntervals = 20;
fctx->uniqBIntervals = malloc(sizeof(anchorItv) * fctx->maxUniqBIntervals);
bzero(fctx->uniqBIntervals, sizeof(anchorItv) * fctx->maxUniqBIntervals);
fctx->curUniqBIntervals = 0;
if(fctx->trackTrim)
fctx->trim = trim_init(fctx->db, pctx->twidth, fctx->trackTrim, NULL);
}
static void filter_post(FilterContext* ctx)
{
#ifdef VERBOSE
if (ctx->statsFiltRepeat > 0)
{
printf("min non-repeat bases of %4d discarded %10d\n", ctx->nMinNonRepeatBases, ctx->statsFiltRepeat);
}
if (ctx->statsFiltContained > 0)
{
printf("contained LAS discarded %10d\n", ctx->statsFiltContained);
}
if (ctx->statsFiltInvalidChain > 0)
{
printf("invalid LAS chains discarded %10d\n", ctx->statsFiltInvalidChain);
}
if (ctx->statsGapAlns > 0)
{
printf("gap LAS discarded %10d\n", ctx->statsGapAlns);
}
if (ctx->statsLowCovALn > 0)
{
printf("low coverage LAS discarded %10d\n", ctx->statsLowCovALn);
}
#endif
int i;
for (i = 0; i < ctx->maxChains; i++)
{
Chain *chain = ctx->ovlChains + i;
if (chain)
free(chain->ovls);
else
break;
}
free(ctx->ovlChains);
free(ctx->uniqAIntervals);
free(ctx->uniqBIntervals);
if(ctx->trackTrim)
trim_close(ctx->trim);
}
static void getRepeatBasesFromInterval(HITS_TRACK* repeat, int readID, int beg, int end, int *cumBases, int *largest)
{
track_anno* rep_anno = repeat->anno;
track_data* rep_data = repeat->data;
track_anno rb, re;
*cumBases = 0;
*largest = 0;
int rBeg, rEnd, tmp;
// repeat bases in a-read
rb = rep_anno[readID] / sizeof(track_data);
re = rep_anno[readID + 1] / sizeof(track_data);
while (rb < re)
{
rBeg = rep_data[rb];
rEnd = rep_data[rb + 1];
tmp = intersect(beg, end, rBeg, rEnd);
if (tmp)
{
*cumBases += tmp;
if (*largest < (rEnd - rBeg))
*largest = (rEnd - rBeg);
}
rb += 2;
}
}
static int cmp_aIvl(const void *a, const void *b)
{
anchorItv * a1 = (anchorItv*) a;
anchorItv * a2 = (anchorItv*) b;
if (a1->flag & ANCHOR_INVALID)
{
return 1;
}
if (a2->flag & ANCHOR_INVALID)
{
return -1;
}
return a1->beg - a2->beg;
}
static void createUniqueMask(FilterContext *ctx, int read, int isAread)
{
int *numIntervals;
int *curItv;
anchorItv *uniqIntervals;
if (isAread)
{
numIntervals = &(ctx->maxUniqAIntervals);
curItv = &(ctx->curUniqAIntervals);
uniqIntervals = ctx->uniqAIntervals;
}
else
{
numIntervals = &(ctx->maxUniqBIntervals);
curItv = &(ctx->curUniqBIntervals);
uniqIntervals = ctx->uniqBIntervals;
}
int trim_beg, trim_end;
int rlen = DB_READ_LEN(ctx->db, read);
if (ctx->trackTrim)
{
get_trim(ctx->db, ctx->trackTrim, read, &trim_beg, &trim_end);
}
else
{
trim_beg = 0;
trim_end = rlen;
}
#ifdef DEBUG_CHAIN
printf("trim_beg %d, trim_end %d\n", trim_beg, trim_end);
#endif
if(ctx->trackRepeat == NULL)
{
ctx->curUniqAIntervals=1;
ctx->uniqAIntervals[0].beg = trim_beg;
ctx->uniqAIntervals[0].end = trim_end;
return;
}
int MINANCHOR = 10;
int WINDOW = ctx->repeatWindowLookBack;
int MAXMERGE = ctx->mergeRepDist;
int i, b, e;
track_anno* repeats_anno = ctx->trackRepeat->anno;
track_data* repeats_data = ctx->trackRepeat->data;
b = repeats_anno[read] / sizeof(track_data);
e = repeats_anno[read + 1] / sizeof(track_data);
if (*numIntervals < (e - b + 1) + 4)
{
*numIntervals = (e - b + 1) + 4;
if (isAread)
{
ctx->uniqAIntervals = (anchorItv*) realloc(ctx->uniqAIntervals, *numIntervals * sizeof(anchorItv));
uniqIntervals = ctx->uniqAIntervals;
}
else
{
ctx->uniqBIntervals = (anchorItv*) realloc(ctx->uniqBIntervals, *numIntervals * sizeof(anchorItv));
uniqIntervals = ctx->uniqBIntervals;
}
}
// reset current anchor interval index
*curItv = 0;
bzero(uniqIntervals, sizeof(anchorItv) * (*numIntervals));
int anchorbases = 0;
if (b < e)
{
int rb1, rb2;
int re1, re2;
rb1 = repeats_data[b];
re1 = repeats_data[b + 1];
if (rb1 > 0 && rb1 > MINANCHOR)
{
uniqIntervals[*curItv].beg = 0;
uniqIntervals[*curItv].end = rb1;
(*curItv)++;
}
b += 2;
while (b < e)
{
rb2 = repeats_data[b];
re2 = repeats_data[b + 1];
if (rb2 - re1 > MINANCHOR)
{
uniqIntervals[*curItv].beg = re1;
uniqIntervals[*curItv].end = rb2;
(*curItv)++;
}
rb1 = rb2;
re1 = re2;
b += 2;
}
if (re1 < rlen && rlen - re1 > MINANCHOR)
{
uniqIntervals[*curItv].beg = re1;
uniqIntervals[*curItv].end = rlen;
(*curItv)++;
}
anchorbases = 0;
for (i = 0; i < *curItv; i++)
{
anchorItv *a = uniqIntervals + i;
if (a->flag & ANCHOR_INVALID)
continue;
anchorbases += a->end - a->beg;
}
// update unique intervals based on trim track
if (trim_beg > 0 || trim_end < rlen)
{
for (i = 0; i < *curItv; i++)
{
anchorItv *a = uniqIntervals + i;
if (trim_beg >= a->end)
{
a->flag |= (ANCHOR_TRIM | ANCHOR_INVALID);
}
else if (trim_beg > a->beg)
{
a->beg = trim_beg;
}
if (a->beg >= trim_end)
{
a->flag |= (ANCHOR_TRIM | ANCHOR_INVALID);
}
else if (a->end > trim_end)
{
a->end = trim_end;
}
}
}
anchorbases = 0;
for (i = 0; i < *curItv; i++)
{
anchorItv *a = uniqIntervals + i;
if (a->flag & ANCHOR_INVALID)
continue;
anchorbases += a->end - a->beg;
}
// update unique intervals based on low complexity and tandem repeat
// todo hardcoded values !!!
int predust, dust, postdust, longestDust, longestDustl, longestDustr;
for (i = 0; i < *curItv; i++)
{
anchorItv *a = uniqIntervals + i;
if (a->flag & ANCHOR_INVALID)
continue;
if (a->end - a->beg > MAXMERGE)
continue;
getRepeatBasesFromInterval(ctx->trackLowCompl, read, a->beg, a->end, &dust, &longestDust);
if (dust * 100.0 / (a->end - a->beg) > 50.0)
{
a->flag |= (ANCHOR_LOWCOMP | ANCHOR_INVALID);
}
else if (dust * 100.0 / (a->end - a->beg) > 15.0 && longestDust > 100)
{
a->flag |= (ANCHOR_LOWCOMP | ANCHOR_INVALID);
}
else if ((a->end - a->beg) < 100 && longestDust > 20)
{
a->flag |= (ANCHOR_LOWCOMP | ANCHOR_INVALID);
}
else // check if neighboring repeats end in low complexity interval
{
int checkFlanks = MIN(100, WINDOW);
while (checkFlanks <= WINDOW)
{
getRepeatBasesFromInterval(ctx->trackLowCompl, read, MAX(0, a->beg - checkFlanks), a->beg, &predust, &longestDustl);
getRepeatBasesFromInterval(ctx->trackLowCompl, read, a->end, MIN(a->end + checkFlanks, rlen), &postdust, &longestDustr);
if ((predust * 100.0 / checkFlanks > 20.0 && longestDustl > 30) || (postdust * 100 / checkFlanks > 20.0 && longestDustr > 30))
{
a->flag |= (ANCHOR_LOWCOMP | ANCHOR_INVALID);
break;
}
if (checkFlanks < WINDOW && checkFlanks + 100 > WINDOW)
checkFlanks = WINDOW;
else
checkFlanks += 100;
}
}
#ifdef DEBUG_CHAIN
printf("#LC %d %d %d f%d PRE %d %d %.2f DUST %d %d %.2f post %d %d %.2f SUM %d %d %.2f\n", read, a->beg, a->end, a->flag, predust,
a->beg - MAX(0, a->beg - WINDOW), predust * 100.0 / (a->beg - MAX(0, a->beg - WINDOW)), dust, a->end - a->beg, dust * 100.0 / (a->end - a->beg),
postdust, MIN(a->end + WINDOW, rlen) - a->end, postdust * 100.0 / (MIN(a->end + WINDOW, rlen) - a->end), predust + dust + postdust,
(a->beg - MAX(0, a->beg - WINDOW)) + (a->end - a->beg) + (MIN(a->end + WINDOW, rlen) - a->end),
(predust + dust + postdust) * 100.0 / ((a->beg - MAX(0, a->beg - WINDOW)) + (a->end - a->beg) + (MIN(a->end + WINDOW, rlen) - a->end)));
#endif
}
}
else // add full read interval as unique range
{
uniqIntervals[0].beg = trim_beg;
uniqIntervals[0].end = trim_end;
(*curItv)++;
}
anchorbases = 0;
for (i = 0; i < *curItv; i++)
{
anchorItv *a = uniqIntervals + i;
if (a->flag & ANCHOR_INVALID)
continue;
anchorbases += a->end - a->beg;
}
repeats_anno = ctx->trackLowCompl->anno;
repeats_data = ctx->trackLowCompl->data;
b = repeats_anno[read] / sizeof(track_data);
e = repeats_anno[read + 1] / sizeof(track_data);
int rb, re;
// update unique anchors with all low complexity intervals !!!
int c = *curItv;
for (i = 0; i < c; i++)
{
if (uniqIntervals[i].flag & ANCHOR_INVALID)
continue;
while (b < e)
{
rb = repeats_data[b];
re = repeats_data[b + 1];
if (rb > uniqIntervals[i].end)
{
break;
}
if (re < uniqIntervals[i].beg)
{
b += 2;
continue;
}
// dust fully covers unique part
if (rb <= uniqIntervals[i].beg && re >= uniqIntervals[i].end)
{
uniqIntervals[i].flag |= (ANCHOR_LOWCOMP | ANCHOR_INVALID);
break;
}
// dust aligns left with unique part
if (rb <= uniqIntervals[i].beg)
{
uniqIntervals[i].beg = re;
}
// dust aligns with right unique part
if (re >= uniqIntervals[i].end)
{
uniqIntervals[i].end = rb;
}
// dust splits uniq part, i.e. make unique part invalid an append splits to the end of uniqueIntervals
if (*curItv >= *numIntervals)
{
*numIntervals = 1.2 * (*numIntervals) + 10;
if (isAread)
{
ctx->uniqAIntervals = (anchorItv*) realloc(ctx->uniqAIntervals, *numIntervals * sizeof(anchorItv));
bzero(ctx->uniqAIntervals + (*curItv), sizeof(anchorItv) * (*numIntervals - *curItv));
uniqIntervals = ctx->uniqAIntervals;
}
else
{
ctx->uniqBIntervals = (anchorItv*) realloc(ctx->uniqBIntervals, *numIntervals * sizeof(anchorItv));
bzero(ctx->uniqBIntervals + (*curItv), sizeof(anchorItv) * (*numIntervals - *curItv));
uniqIntervals = ctx->uniqBIntervals;
}
}
uniqIntervals[*curItv].beg = uniqIntervals[i].beg;
uniqIntervals[*curItv].end = rb;
uniqIntervals[i].beg = re;
(*curItv)++;
b += 2;
}
}
qsort(uniqIntervals, *curItv, sizeof(anchorItv), cmp_aIvl);
for (i = 0; i < *curItv; i++)
{
anchorItv *a = uniqIntervals + i;
if (a->flag & ANCHOR_INVALID)
break;
}
*curItv = i;
// merge tips if required, i.e. if there is any repeat annotation within the first/last 2k?! sequence
if (ctx->rp_mergeTips && *curItv > 0)
{
int resort = 0;
if (uniqIntervals[0].beg > trim_beg || uniqIntervals[0].end < trim_beg + ctx->rp_mergeTips)
{
for (i = 0; i < *curItv; i++)
{
anchorItv *a = uniqIntervals + i;
if (a->flag & ANCHOR_INVALID)
continue;
if (a->end < trim_beg + ctx->rp_mergeTips)
{
a->flag |= (ANCHOR_TRIM | ANCHOR_INVALID);
resort = 1;
}
else if (a->beg < trim_beg + ctx->rp_mergeTips)
{
a->beg = trim_beg + ctx->rp_mergeTips;
}
else
{
break;
}
}
}
if (uniqIntervals[*curItv - 1].end < trim_end || uniqIntervals[*curItv - 1].beg > trim_end - ctx->rp_mergeTips)
{
for (i = *curItv - 1; i >= 0; --i)
{
anchorItv *a = uniqIntervals + i;
if (a->flag & ANCHOR_INVALID)
continue;
if (a->beg > trim_end - ctx->rp_mergeTips)
{
a->flag |= (ANCHOR_TRIM | ANCHOR_INVALID);
resort = 1;
}
else if (a->end > trim_end - ctx->rp_mergeTips)
{
a->end = trim_end - ctx->rp_mergeTips;
}
else
{
break;
}
}
}
if (resort)
{
qsort(uniqIntervals, *curItv, sizeof(anchorItv), cmp_aIvl);
for (i = 0; i < *curItv; i++)
{
anchorItv *a = uniqIntervals + i;
if (a->flag & ANCHOR_INVALID)
break;
}
*curItv = i;
}
}
#ifdef DEBUG_CHAIN
// report final unique anchors:
anchorbases = 0;
printf("#final anchors %d", read);
for (i = 0; i < *curItv; i++)
{
anchorItv *a = uniqIntervals + i;
if (a->flag & ANCHOR_INVALID)
break;
printf(" %d-%d-%d", a->beg, a->end, a->flag);
anchorbases += a->end - a->beg;
}
printf(" sum n%d b%d\n", i, anchorbases);
#endif
}
static int gapIsLowComplexity(FilterContext *ctx, int read, int beg, int end, float fraction)
{
if (!ctx->trackLowCompl)
return 0;
int longest;
int cumLC;
getRepeatBasesFromInterval(ctx->trackLowCompl, read, beg, end, &cumLC, &longest);
if ((cumLC * 1.0) / (end - beg) < fraction)
return 0;
return 1;
}
static int stitchChain(FilterContext *ctx, Chain *chain)
{
int stitched = 0;
if (chain->novl < 2)
{
return stitched;
}
int i;
int ab2, ae1, ae2;
int bb2, be1, be2;
int aread = chain->ovls[0]->aread;
int bread = chain->ovls[0]->bread;
// check if any overlap is contained in low complexity interval, if so then don't stitch at all
if (ctx->trackLowCompl)
{
for (i = 0; i < chain->novl; i++)
{
Overlap *ovl = chain->ovls[i];
int repeatBases;
int longestRep;
// check LowComp of A-read
getRepeatBasesFromInterval(ctx->trackLowCompl, aread, ovl->path.abpos, ovl->path.aepos, &repeatBases, &longestRep);
if ((ovl->path.aepos - ovl->path.abpos) - repeatBases < ctx->stitchNonLowCompAnchorBases)
{
return stitched;
}
// check LowComp of B-read
if (ovl->flags & OVL_COMP)
{
getRepeatBasesFromInterval(ctx->trackLowCompl, bread, DB_READ_LEN(ctx->db, bread) - ovl->path.bepos, DB_READ_LEN(ctx->db, bread) - ovl->path.bbpos, &repeatBases, &longestRep);
}
else
{
getRepeatBasesFromInterval(ctx->trackLowCompl, bread, ovl->path.bbpos, ovl->path.bepos, &repeatBases, &longestRep);
}
if ((ovl->path.bepos - ovl->path.bbpos) - repeatBases < ctx->stitchNonLowCompAnchorBases)
{
return 0;
}
}
}
Overlap* ovli = chain->ovls[0];
ae1 = ovli->path.aepos;
be1 = ovli->path.bepos;
for (i = 1; i < chain->novl; i++)
{
Overlap* ovlk = chain->ovls[i];
assert((ovli->flags & OVL_COMP) == (ovlk->flags & OVL_COMP));
ab2 = ovlk->path.abpos;
ae2 = ovlk->path.aepos;
bb2 = ovlk->path.bbpos;
be2 = ovlk->path.bepos;
int deltaa = abs(ae1 - ab2);
int deltab = abs(be1 - bb2);
float LOWCOMPFRACTION = 0.8;
int isLowCompl = 0;
int cumLowCompBases = 0;
int longestLowCompBases = 0;
if(ae1 <= ab2)
{
getRepeatBasesFromInterval(ctx->trackLowCompl, ovli->aread, ae1, ab2, &cumLowCompBases, &longestLowCompBases);
}
else
{
getRepeatBasesFromInterval(ctx->trackLowCompl, ovli->aread, ab2, ae1, &cumLowCompBases, &longestLowCompBases);
}
if(deltaa*LOWCOMPFRACTION <= cumLowCompBases)
{
isLowCompl = 1;
}
else // check b-read
{
cumLowCompBases = 0;
longestLowCompBases = 0;
if(ovli->flags & OVL_COMP)
{
assert(ovlk->flags & OVL_COMP);
int cbe1 = DB_READ_LEN(ctx->db, ovli->bread) - be1;
int cbb2 = DB_READ_LEN(ctx->db, ovli->bread) - bb2;
if(cbe1 <= cbb2)
{
getRepeatBasesFromInterval(ctx->trackLowCompl, ovli->bread, cbe1, cbb2, &cumLowCompBases, &longestLowCompBases);
}
else
{
getRepeatBasesFromInterval(ctx->trackLowCompl, ovli->bread, cbb2, cbe1, &cumLowCompBases, &longestLowCompBases);
}
}
else
{
if(be1 <= bb2)
{
getRepeatBasesFromInterval(ctx->trackLowCompl, ovli->bread, be1, bb2, &cumLowCompBases, &longestLowCompBases);
}
else
{
getRepeatBasesFromInterval(ctx->trackLowCompl, ovli->bread, bb2, be1, &cumLowCompBases, &longestLowCompBases);
}
}
if(deltab*LOWCOMPFRACTION <= cumLowCompBases)
{
isLowCompl = 1;
}
}
if (ctx->stitchMaxGapSize < 0 || (deltaa < ctx->stitchMaxGapSize && deltab < ctx->stitchMaxGapSize)
|| (isLowCompl && (deltaa < ctx->stitchMaxGapSizeInLowCompl && deltab < ctx->stitchMaxGapSizeInLowCompl)))
{
#ifdef VERBOSE_STITCH
int ab1 = ovli->path.abpos;
int bb1 = ovli->path.bbpos;
printf("STITCH %8d @ %5d..%5d -> %8d @ %5d..%5d %c\n"
" %5d..%5d -> %8d @ %5d..%5d %c\n",
ovli->aread,
ab1, ae1, ovli->bread, bb1, be1, OVL_STRAND(ovli),
ab2, ae2, ovlk->bread, bb2, be2, OVL_STRAND(ovlk)));
#endif
ovli->path.aepos = ae2;
ovli->path.bepos = be2;
ovli->path.diffs += ovlk->path.diffs;
ovli->path.tlen = 0;
ae1 = ae2;
be1 = be2;
assert(ovli->bread == ovlk->bread);
ovli->flags &= ~( OVL_DISCARD | OVL_LOCAL); // force a re-evaluation of the OVL_LOCAL flags
ovlk->flags |= OVL_DISCARD | OVL_STITCH;
stitched += 1;
#ifdef VERBOSE_STITCH
printf( " -> %8d @ %5d..%5d -> %8d @ %5d..%5d %c delta a %3d b %3d\n",
ovli->aread,
ovli->path.abpos, ovli->path.aepos,
ovli->bread,
ovli->path.abpos, ovli->path.aepos,
OVL_STRAND( ovli ),
deltaa, deltab );
#endif
}
else
{
ovli = ovlk;
}
}
return stitched;
}
static void findGaps(FilterContext *ctx, Overlap *ovl, int novl)
{
// todo hard coded: use a dynamic window dependent on repeat track ?
int SWINDOW = 1000;
int ANCHOR = MAX(ctx->minChainLen / 2, 1 + SWINDOW / 2);
int MINSPANNER = ctx->gapMinSpanners;
int trim_abeg, trim_aend;
if (ctx->trackTrim)
{
get_trim(ctx->db, ctx->trackTrim, ovl->aread, &trim_abeg, &trim_aend);
}
else
{
trim_abeg = 0;
trim_aend = DB_READ_LEN(ctx->db, ovl->aread);
}
int foundGap = 0;
int i, j, k, l;
#ifdef DEBUG_GAPS
printf("find gaps: ");
#endif
int count = 0;
for (i = 0; i < novl; i++)
{
if (!(ovl[i].flags & OVL_DISCARD))
{
count++;
}
}
if(count == 0)
return;
#ifdef DEBUG_GAPS
printf("ovl: %d/%d\n", count, novl);
#endif
for (i = trim_abeg; i < trim_aend && foundGap == 0; i += SWINDOW)
{
int nspanner = 0;
j = k = 0;
while (j < novl)
{
while (k < novl - 1 && ovl[j].bread == ovl[k + 1].bread)
{
k++;
}
if (ovl[j].aread != ovl[j].bread)
{
int abpos = DB_READ_LEN(ctx->db, ovl[j].aread);
int aepos = 0;
for (l = j; l <= k; l++)
{
Overlap * o = ovl + l;
if (o->flags & OVL_DISCARD)
continue;
if (o->path.abpos < abpos)
abpos = o->path.abpos;
if (o->path.aepos > aepos)
aepos = o->path.aepos;
#ifdef DEBUG_GAPS
printf("t|%d,%d| i|%d,%d| [%d, %d] {%d %d} (%d %d)\n", trim_abeg, trim_aend, i - ANCHOR, i + ANCHOR, o->aread, o->bread, abpos, aepos, o->path.abpos, o->path.aepos);
#endif
}
if (abpos < aepos)
{
if ((abpos <= MAX(trim_abeg, i - ANCHOR)) && (aepos >= MIN(i + ANCHOR, trim_aend)))
{
nspanner++;
}
#ifdef DEBUG_GAPS
printf(" ---> nspanner: %d\n", nspanner);
#endif
}
if(nspanner >= MINSPANNER)
break;
}
k++;
j = k;
}
if (nspanner < MINSPANNER)
{
printf("FOUND GAP in READ %d in range [%d, %d]\n", ovl->aread, MAX(trim_abeg, i - ANCHOR), MIN(i + ANCHOR, trim_aend));
for (j = 0; j < novl; j++)
{
ovl[j].flags |= (OVL_DISCARD | OVL_GAP);
ctx->statsGapAlns++;
}
fprintf(ctx->fileOutDiscardedReads, "%d GAP\n", ovl->aread);
return;
}
}
}
static void checkTipCoverage(FilterContext *ctx, Overlap *ovl, int novl)
{
int trimBeg, trimEnd;
trimBeg = 0;
trimEnd = DB_READ_LEN(ctx->db, ovl->aread);
if (ctx->trackTrim)
get_trim(ctx->db, ctx->trackTrim, ovl->aread, &trimBeg, &trimEnd);
int i;
int count = 0;
for (i = 0; i < novl; i++)
{
if (!(ovl[i].flags & OVL_DISCARD))
{
count++;
}
}
if(count == 0)
return;
if (trimEnd - trimBeg)
{
int entercov = 0;
int leavecov = 0;
int bases = 0;
char * cov_read_active = malloc(DB_READ_MAXLEN(ctx->db));
bzero(cov_read_active, DB_READ_MAXLEN(ctx->db));
int j;
for (j = 0; j < novl; j++)
{
Overlap* ovl_j = ovl + j;
if (ovl_j->flags & OVL_DISCARD)
continue;
if (ovl_j->path.abpos <= trimBeg)
entercov++;
if (ovl_j->path.aepos >= trimEnd)
leavecov++;
bases += ovl_j->path.aepos - ovl_j->path.abpos;
memset(cov_read_active + ovl_j->path.abpos, 1, ovl_j->path.aepos - ovl_j->path.abpos);
}
int active = 0;
for (j = trimBeg; j < trimEnd; j++)
{
active += cov_read_active[j];
}
if (bases / (trimEnd - trimBeg) <= ctx->minTipCoverage || (leavecov < ctx->minTipCoverage || entercov < ctx->minTipCoverage) || ((trimEnd - trimBeg) - active > ctx->minTipCoverage))
{
for (j = 0; j < novl; j++)
{
Overlap* ovl_j = ovl + j;
if (ovl_j->flags & OVL_DISCARD)
continue;
ovl_j->flags |= OVL_DISCARD;
ctx->statsLowCovALn++;
}
printf("DROP LOWCOV AREAD %d (b: %d, e: %d, avgCov %d, gapBases: %d)\n", ovl->aread, entercov, leavecov, bases / (trimEnd - trimBeg), (trimEnd - trimBeg) - active);
fprintf(ctx->fileOutDiscardedReads, "%d LCOV\n", ovl->aread);
}
free(cov_read_active);
}
}
static int filter_handler(void* _ctx, Overlap* ovl, int novl)
{
FilterContext* ctx = (FilterContext*) _ctx;
int i, j, k;
if (ctx->areadID != -1)
{
if (ovl->aread < ctx->areadID)
{
return 1;
}
if (ovl->aread > ctx->areadID)
{
return 0;
}
}
int trim_abeg, trim_aend;
int trim_bbeg, trim_bend;
if(ctx->trackTrim && ctx->trimLAS)
{
for (j = 0; j < novl; j++)
{
trim_overlap(ctx->trim, ovl + j);
// if(ovl[j].flags & OVL_TRIM)
// printf("TRIMMED %d %d [%d, %d] [%d,%d]\n", ovl[j].aread, ovl[j].bread, ovl[j].path.abpos, ovl[j].path.aepos, ovl[j].path.bbpos, ovl[j].path.bepos);
}
// get_trim(ctx->db, ctx->trackTrim, ovl->aread, &trim_abeg, &trim_aend);
// printf("T[%d, %d]\n", trim_abeg, trim_aend);
}
// set filter flags
for (j = 0; j < novl; j++)
{
// get rid of all previous flags
ovl[j].flags &= ~(OVL_CONT | OVL_TEMP | OVL_REPEAT);
ovl[j].flags |= filter(ctx, ovl + j);
}
j = k = 0;
// create unique mask for a-read
createUniqueMask(ctx, ovl->aread, 1);
if (ctx->trackTrim)
{
get_trim(ctx->db, ctx->trackTrim, ovl->aread, &trim_abeg, &trim_aend);
}
else
{
trim_abeg = 0;
trim_aend = DB_READ_LEN(ctx->db, ovl->aread);
}
while (j < novl)
{
//printf("%d vs %d\n", ovl[j].aread, ovl[j].bread);
assert(k == j);
int nAnchorOvls = (ovl[j].flags & (OVL_REPEAT | OVL_TRIM)) ? 0 : 1;
//printf("---< nAnchorOvls: %d a(%d, %d) b(%d,%d) R? %d, T? %d\n", nAnchorOvls,ovl[j].path.abpos,ovl[j].path.aepos,ovl[j].path.bbpos,ovl[j].path.bepos, (ovl[j].flags & (OVL_REPEAT)), (ovl[j].flags & (OVL_TRIM)));
while (k < novl - 1 && ovl[j].bread == ovl[k + 1].bread)
{
k++;
nAnchorOvls += (ovl[k].flags & (OVL_REPEAT | OVL_TRIM)) ? 0 : 1;
//printf("---< nAnchorOvls: %d a(%d, %d) b(%d,%d) R? %d, T? %d\n", nAnchorOvls, ovl[k].path.abpos,ovl[k].path.aepos,ovl[k].path.bbpos,ovl[k].path.bepos, (ovl[j].flags & (OVL_REPEAT)), (ovl[j].flags & (OVL_TRIM)));
}
#ifdef CHAIN_DEBUG
printf("AnchorOvls: %d k: %d vs %d j: %d vs %d REP: %d, TRIM: %d\n", nAnchorOvls, ovl[j].aread, ovl[j].bread, ovl[k].aread, ovl[k].bread, ovl[j].flags & (OVL_REPEAT), ovl[j].flags & (OVL_TRIM));
#endif
// ignore all self alignments if those are present
if (ovl[j].aread == ovl[j].bread)
nAnchorOvls = 0;
if (nAnchorOvls)
{
#ifdef CHAIN_DEBUG
printf("read: %8d len(%10d) | read: %8d len(%10d) novl: %10d, anchorOvl: %5d\n", ovl[j].aread, DB_READ_LEN(ctx->db, ovl[j].aread), ovl[j].bread, DB_READ_LEN(ctx->db, ovl[j].bread), k - j + 1, nAnchorOvls);
fflush(stdout);
#endif
chain(ctx, ovl + j, k - j + 1);
#ifdef CHAIN_DEBUG
if (ctx->curChains)
printf("FINAL CHAINS: %d %7d vs %7d\n", ctx->curChains, ctx->ovlChains[0].ovls[0]->aread, ctx->ovlChains[0].ovls[0]->bread);
else
printf("FINAL CHAINS: NONE!!\n");
for (i = 0; i < ctx->curChains; i++)
{
printf(" CHAIN %d/%d: #novl %d\n", i + 1, ctx->curChains, ctx->ovlChains[i].novl);
int j;
for (j = 0; j < ctx->ovlChains[i].novl; j++)
{
printf(" OVL %d/%d: a[%7d, %7d] b[%7d, %7d] %s\n", j + 1, ctx->ovlChains[i].novl, ctx->ovlChains[i].ovls[j]->path.abpos, ctx->ovlChains[i].ovls[j]->path.aepos, ctx->ovlChains[i].ovls[j]->path.bbpos, ctx->ovlChains[i].ovls[j]->path.bepos,
(ctx->ovlChains[i].ovls[j]->flags & OVL_COMP) ? "COMP" : "NORM");
}
}
#endif
int a, b;
// discard all overlaps, that are not part of a putatively valid chain
for (i = j; i <= k; i++)
{
if (!(ovl[i].flags & OVL_TEMP))
{
ovl[i].flags |= OVL_DISCARD;
ctx->statsFiltInvalidChain++;
}
}
/*
if (ctx->nkeptChains == 0)
{
for (a = 1; a < ctx->curChains; a++)
for (b = 0; b < ctx->ovlChains[a].novl; b++)
{
ctx->ovlChains[a].ovls[b]->flags |= OVL_DISCARD;
ctx->statsFiltInvalidChain++;
}
}*/
{
// create unique mask for b-read
// printf("-----> create unique mask for b_read %d\n", ovl[j].bread);
createUniqueMask(ctx, ovl[j].bread, 0);
//printf("ctx->curUniqBIntervals: %d\n", ctx->curUniqBIntervals);
if (ctx->trackTrim)
{
get_trim(ctx->db, ctx->trackTrim, ovl[j].bread, &trim_bbeg, &trim_bend);
}
else
{
trim_bbeg = 0;
trim_bend = DB_READ_LEN(ctx->db, ovl[j].bread);
}
// check for proper chain
for (a = 0; a < ctx->curChains; a++)
{
//if (ctx->nkeptChains == 0 && a > 0) // do not check, they are already discarded
// break;
Chain *chain = ctx->ovlChains + a;
int properBegA = 0;
int properEndA = 0;
int properBegB = 0;
int properEndB = 0;
int coveredBasesInAread = 0;
int coveredBasesInBread = 0;
int properGapLen = 1;
int alignedBasesInAread;
int alignedBasesInBread;
int numdiffs = 0;
int fuzzy = ctx->nFuzzBases;
// check for proper begin
if (chain->ovls[0]->path.abpos <= trim_abeg + fuzzy)
properBegA = 1;
if (chain->ovls[0]->flags & OVL_COMP)
{
if (DB_READ_LEN(ctx->db,chain->ovls[0]->bread) - chain->ovls[0]->path.bbpos + fuzzy >= trim_bend)
properBegB = 1;
}
else
{
if (chain->ovls[0]->path.bbpos <= trim_bbeg + fuzzy)
properBegB = 1;
}
// check for proper end
if (chain->ovls[chain->novl - 1]->path.aepos + fuzzy >= trim_aend)
properEndA = 1;
if (chain->ovls[0]->flags & OVL_COMP)
{
if (DB_READ_LEN(ctx->db,chain->ovls[0]->bread) - chain->ovls[chain->novl - 1]->path.bepos - fuzzy <= trim_bbeg)
properEndB = 1;
}
else
{
if (chain->ovls[chain->novl - 1]->path.bepos + fuzzy >= trim_bend)
properEndB = 1;
}
coveredBasesInAread = chain->ovls[0]->path.aepos - chain->ovls[0]->path.abpos;
coveredBasesInBread = chain->ovls[0]->path.bepos - chain->ovls[0]->path.bbpos;
alignedBasesInAread = chain->ovls[0]->path.aepos - chain->ovls[0]->path.abpos;
alignedBasesInBread = chain->ovls[0]->path.bepos - chain->ovls[0]->path.bbpos;
numdiffs = chain->ovls[0]->path.diffs;
for (b = 1; b < chain->novl; b++)
{
coveredBasesInAread += chain->ovls[b]->path.aepos - chain->ovls[b]->path.abpos;
coveredBasesInBread += chain->ovls[b]->path.bepos - chain->ovls[b]->path.bbpos;
alignedBasesInAread += chain->ovls[b]->path.aepos - chain->ovls[b]->path.abpos;
alignedBasesInBread += chain->ovls[b]->path.bepos - chain->ovls[b]->path.bbpos;
numdiffs += chain->ovls[b]->path.diffs;
// check for intersection in A
if (chain->ovls[b]->path.abpos < chain->ovls[b - 1]->path.aepos)
{
coveredBasesInAread -= chain->ovls[b - 1]->path.aepos - chain->ovls[b]->path.abpos;
}
// check for gap in A
else
{
if (chain->ovls[b]->path.abpos - chain->ovls[b - 1]->path.aepos > fuzzy)
{
// check gap
//printf("gap [%d, %d] in %d is low complexity: %d\n", chain->ovls[b - 1]->path.aepos, chain->ovls[b]->path.abpos,chain->ovls[b]->aread, gapIsLowComplexity(ctx, chain->ovls[b]->aread, chain->ovls[b - 1]->path.aepos, chain->ovls[b]->path.abpos, 0.8),);
if (!gapIsLowComplexity(ctx, chain->ovls[b]->aread, chain->ovls[b - 1]->path.aepos, chain->ovls[b]->path.abpos, 0.8))
{
properGapLen = 0;
break;
}
}
}
// check for intersection in B
if (chain->ovls[b]->path.bbpos < chain->ovls[b - 1]->path.bepos)
{
coveredBasesInBread -= chain->ovls[b - 1]->path.bepos - chain->ovls[b]->path.bbpos;
}
// check for gap in B
else
{
if (chain->ovls[b]->path.bbpos - chain->ovls[b - 1]->path.bepos > fuzzy)
{
int bbpos = chain->ovls[b - 1]->path.bepos;
int bepos = chain->ovls[b]->path.bbpos;
if (chain->ovls[b]->flags & OVL_COMP)
{
int tmp = bbpos;
bbpos = DB_READ_LEN(ctx->db, chain->ovls[b]->bread) - bepos;
bepos = DB_READ_LEN(ctx->db, chain->ovls[b]->bread) - tmp;
}
//printf("gap [%d, %d] in %d is low complexity: %d\n", bbpos, bepos, chain->ovls[b]->bread, gapIsLowComplexity(ctx, chain->ovls[b]->bread, bbpos, bepos, 0.8));
if (!gapIsLowComplexity(ctx, chain->ovls[b]->bread, bbpos, bepos, 0.8))
{
properGapLen = 0;
break;
}
}
}
}
int validContainment = 0;
int validDiff = 0;
int validMinLen = 0;
if (ctx->nFuzzBases || ctx->nContPerc)
{
if (properGapLen && ((properBegA || properBegB) && (properEndA || properEndB)))
{
if (MAX(coveredBasesInAread, coveredBasesInBread) >= (int) (ctx->nContPerc / 100.0 * MIN(DB_READ_LEN(ctx->db, chain->ovls[0]->aread), DB_READ_LEN(ctx->db, chain->ovls[0]->bread))))
{
validContainment = 1;
}
}
}
else // containments are irrelevant
{
validContainment = 1;
}
if (numdiffs * 100.0 / alignedBasesInAread <= ctx->maxOverallDiff && numdiffs * 100.0 / alignedBasesInBread <= ctx->maxOverallDiff)
validDiff = 1;
if (coveredBasesInAread > ctx->minChainLen && coveredBasesInBread > ctx->minChainLen)
validMinLen = 1;
int containedChain=0;
// check if they are contained or overlapping by more then -fuzzy base pairs with previous chains
{
int b;
for (b=0; b<a && !containedChain; b++)
{
if(ctx->ovlChains[b].ovls[0]->flags & OVL_DISCARD)
continue;
if(intersect(chain->ovls[0]->path.abpos, chain->ovls[chain->novl - 1]->path.aepos, ctx->ovlChains[b].ovls[0]->path.abpos, ctx->ovlChains[b].ovls[ctx->ovlChains[b].novl - 1]->path.aepos) > MIN(ctx->nFuzzBases, 1000) ||
intersect(chain->ovls[0]->path.bbpos, chain->ovls[chain->novl - 1]->path.bepos, ctx->ovlChains[b].ovls[0]->path.bbpos, ctx->ovlChains[b].ovls[ctx->ovlChains[b].novl - 1]->path.bepos) > MIN(ctx->nFuzzBases, 1000))
{
printf("CHAIN is invalid (overlaps with previous chain) - DISCARD\n");
printChain(chain);
containedChain = 1;
break;
}
if ((chain->ovls[0]->flags & OVL_COMP) == (ctx->ovlChains[b].ovls[0]->flags & OVL_COMP))
{
for (j = 0; j < chain->novl; j++)
{
if ((chain->ovls[j]->path.abpos >= ctx->ovlChains[b].ovls[0]->path.abpos && chain->ovls[j]->path.aepos <= ctx->ovlChains[b].ovls[ctx->ovlChains[b].novl - 1]->path.aepos)
|| (chain->ovls[j]->path.bbpos >= ctx->ovlChains[b].ovls[0]->path.bbpos && chain->ovls[j]->path.bepos <= ctx->ovlChains[b].ovls[ctx->ovlChains[b].novl - 1]->path.bepos))
{
#if CHAIN_DEBUG
printf("CHAIN is invalid - DISCARD\n");
printChain(chain);
#endif
containedChain = 1;
break;
}
}
}
}
}
#ifdef CHAIN_DEBUG
printf("properBegA %d properBegB %d properEndA %d properEndB %d properGapLen %d validContainment %d validDiff %d validMinLen: %d containedChain %d\n", properBegA, properBegB, properEndA, properEndB, properGapLen, validContainment, validDiff, validMinLen, containedChain );
#endif
if ((!properBegA && !properBegB) || (!properEndA && !properEndB) || !properGapLen || !validContainment || !validDiff || !validMinLen || containedChain)
{
#ifdef CHAIN_DEBUG
printf(" *** DISCARD chain ****\n");
#endif
for (b = 0; b < chain->novl; b++)
{
chain->ovls[b]->flags |= OVL_DISCARD;
ctx->statsFiltInvalidChain++;
}
}
else
{
int count = 0;
for (b = 0; b < chain->novl; b++)
{
if (!(chain->ovls[b]->flags & OVL_DISCARD))
count++;
}
#ifdef DEBUG_FILTER
printf(" validLAS %d\n", count);
#endif
if (ctx->stitchChain)
{
int nStitch = stitchChain(ctx, chain);
if (chain->novl - nStitch > ctx->stitchMaxChainLASs)
{
for (b = 0; b < chain->novl; b++)
{
chain->ovls[b]->flags |= OVL_DISCARD;
ctx->statsFiltInvalidChain++;
}
}
}
count = 0;
#ifdef DEBUG_FILTER
for (b = 0; b < chain->novl; b++)
{
if (!(chain->ovls[b]->flags & OVL_DISCARD))
count++;
}
printf(" validLAS %d\n", count);
#endif
// after the first valid chain is found, mark the rest as invalid if nkeptChains is 0
if (ctx->nkeptChains == 0)
{
for (a = a+1; a < ctx->curChains; a++)
{
for (b = 0; b < ctx->ovlChains[a].novl; b++)
{
ctx->ovlChains[a].ovls[b]->flags |= OVL_DISCARD;
ctx->statsFiltInvalidChain++;
}
}
}
}
}
}
// reset chain and ovl counter
for (a = 0; a < ctx->curChains; a++)
ctx->ovlChains[a].novl = 0;
ctx->curChains = 0;
}
else
{
//printf("DISCARD all overlaps\n");
if (ovl[j].aread != ovl[j].bread || (ctx->keepIdentity == 0))
{ // discard all overlaps
for (i = j; i <= k; i++)
{
//printf("DISCARD: %d vs %d a[%d, %d] b[%d, %d] \n",ovl[i].aread,ovl[i].bread,ovl[i].path.abpos,ovl[i].path.aepos,ovl[i].path.bbpos,ovl[i].path.bepos);
ovl[i].flags |= OVL_DISCARD;
ctx->statsFiltInvalidChain++;
}
}
}
k++;
j = k;
}
if (ctx->fileOutDiscardedReads)
{
findGaps(ctx, ovl, novl);
}
if (ctx->minTipCoverage)
{
checkTipCoverage(ctx, ovl, novl);
}
if(ctx->fileOutFullyDiscardedAreads)
{
if(trim_aend - trim_abeg > ctx->minLenOfFullyDiscardedAreads)
{
int count=0;
for (i = 0; i < novl; i++)
{
if (ovl[i].flags & OVL_DISCARD)
{
count++;
}
}
if(count == novl)
{
fprintf(ctx->fileOutFullyDiscardedAreads, "%d %d %d\n", ovl->aread, trim_abeg, trim_aend);
}
}
}
// convert all DAmar into Dazzler flags - this should always sit at the end !!!!!
if(ctx->dazzlerFlags)
{
j = k = 0;
while (j < novl)
{
while (k < novl - 1 && ovl[j].bread == ovl[k + 1].bread)
{
k++;
}
int n = k - j + 1;
int start=1;
for (i=0; i < n; i++)
{
int newFlag=0;
Overlap *o = ovl+j+i;
assert(ovl[j].bread == o->bread);
if(o->flags & OVL_COMP)
newFlag = COMP_FLAG;
if (o->flags & OVL_DISCARD)
{
newFlag |= ELIM_FLAG;
}
else if(start)
{
newFlag |= (START_FLAG | BEST_FLAG);
start=0;
}
else
newFlag |= NEXT_FLAG;
o->flags = newFlag;
// overrule flags if purging is enabled
if(ctx->purgeLAS)
o->flags |= OVL_DISCARD;
}
k++;
j = k;
}
}
return 1;
}
static void usage()
{
fprintf(stderr, "[-vpiSDT] [-nkfcmwdyoULGOCMZu <int>] [-BR <file>][-rlt <track>] <db> <overlaps_in> <overlaps_out>\n");
fprintf(stderr, "options: -v verbose\n");
fprintf(stderr, " -i keep identity overlaps\n");
fprintf(stderr, " -p purge discarded overlaps\n");
fprintf(stderr, " -D replace DMar alignment flags with Dazzler alignment flags.\n");
fprintf(stderr, " -r <trc> repeat track name (%s)\n", DEF_ARG_R);
fprintf(stderr, " -l <trc> low complexity track (e.g. tan, dust, tan_dust, default: %s)\n", DEF_ARG_L);
fprintf(stderr, " -t <trc> trim-track (default: %s)\n", DEF_ARG_T);
fprintf(stderr, " -T trim all overlaps with given trim track. (Default: do not trim)\n");
fprintf(stderr, " -k <int> keep valid overlap chains: 0 ... best, 1 ... all\n");
fprintf(stderr, " -u <int> restrict chain detection to a maximum of -u bases near contig begin and end\n");
fprintf(stderr, "\n 1. Chain overlaps\n");
fprintf(stderr, " -n <int> at least one alignment of a valid chain must have n non-repetitive bases\n");
fprintf(stderr, " -m <int> max merge distance of neighboring repeats (default: %d)\n", DEF_ARG_M);
fprintf(stderr, " -w <int> window size in bases. Merge repeats that are closer then -V bases and have a decent number of low complexity bases in between both repeats\n");
fprintf(stderr, " or at -W bases at the tips of the neighboring repeat. Those can cause a fragmented repeat mask. (default: %d)\n", DEF_ARG_W);
fprintf(stderr, " -d <int> max overall divergence allowed [0,100] (default: %d)\n", DEF_ARG_D);
fprintf(stderr, " -y <int> merge repeats with start/end position of read if repeat interval starts/ends with fewer then -Y\n");
fprintf(stderr, " -o <int> minimum chain length (default: %d)\n", DEF_ARG_O);
fprintf(stderr, " -f <int> allow maximum of -f fuzzy bases \"of structural variations\" between two neighboring overlaps of a chain, (default %d)\n", DEF_ARG_F);
fprintf(stderr, " -c <int> chain alignment must cover at least -p percent of the shorter read. p=[1,100], (default: %d)\n", DEF_ARG_C);
fprintf(stderr, "\n 2. Stitch chains (optional)\n");
fprintf(stderr, " -S stitch LASchains\n");
fprintf(stderr, " -U <int> maximum unaligned bases for first and last overlap of LAchain (default: 0)\n");
fprintf(stderr, " -L <int> do not merge LAS that cover low complexity regions and have less than -L \"unique\" anchor bases (default: 1000)\n");
fprintf(stderr, " -G <int> maximum merge distance (default: -1)\n");
fprintf(stderr, " -M <int> maximum merge distance in low complexity regions (default: -1)\n");
fprintf(stderr, " -O <int> minimum chain length (default: -1)\n");
fprintf(stderr, " -C <int> max number of LAS in a LASchain (default: 1)\n");
fprintf(stderr, "\n 3. find Gaps and exclude all those reads (optional)\n");
fprintf(stderr, " -B <file> find breaks and gaps and write corresponding read ID into <file>\n");
fprintf(stderr, " -N <int> min number of spanning alignments, to be not a gap (default: 1)\n");
fprintf(stderr, "\n 4. further Filter parameter (optional)\n");
fprintf(stderr, " -E <int> minimum leaving/entering coverage (default: 0). If coverage is less then -E, than all overlaps are discarded.\n");
fprintf(stderr, " -R <file> Write out Aread ids, that are at least Z-bases <int> long and were fully filtered with LAfilterChains.\n");
fprintf(stderr, " -Z <int> minimum A-read length for repeatitive reads (default: %d)\n", DEF_ARG_Z);
fprintf(stderr, "\n 5. DEBUG options\n");
fprintf(stderr, "\n -I <int> specify single A-read ID\n");
}
int main(int argc, char* argv[])
{
HITS_DB db;
FilterContext fctx;
PassContext* pctx;
FILE* fileOvlIn;
FILE* fileOvlOut;
bzero(&fctx, sizeof(FilterContext));
fctx.db = &db;
// args
char* pcTrackRepeats = DEF_ARG_R;
char* pcTrackTrim = DEF_ARG_T;
char* pcTrackLowCompl = DEF_ARG_L;
char* pathOutDiscardReads = NULL;
char* pathOutFullyDiscardAReads = NULL;
int arg_purge = 0;
fctx.nMinNonRepeatBases = -1;
fctx.nVerbose = 0;
fctx.purgeLAS = arg_purge;
fctx.dazzlerFlags = 0;
fctx.nkeptChains = 0;
fctx.nFuzzBases = DEF_ARG_F;
fctx.nContPerc = DEF_ARG_C;
fctx.keepIdentity = 0;
fctx.maxOverallDiff = DEF_ARG_D;
fctx.mergeRepDist = DEF_ARG_M;
fctx.repeatWindowLookBack = DEF_ARG_W;
fctx.rp_mergeTips = 0;
fctx.minChainLen = DEF_ARG_O;
fctx.stitchChain = 0;
fctx.stitchNonLowCompAnchorBases = 1000;
fctx.stitchMaxGapSize = -1; // by default stitch all valid chains
fctx.stitchMaxGapSizeInLowCompl = -1; // by default stitch all valid chains
fctx.stitchMaxTipFuzzy = 0;
fctx.stitchMinChainLen = fctx.minChainLen;
fctx.stitchMaxChainLASs = 1;
fctx.minTipCoverage = 0;
fctx.fileOutDiscardedReads = NULL;
fctx.gapMinSpanners = 1;
fctx.fileOutFullyDiscardedAreads = NULL;
fctx.minLenOfFullyDiscardedAreads = DEF_ARG_Z;
fctx.maxBasesAtContigTips = -1;
fctx.areadID = -1;
fctx.trimLAS = 0;
int c;
opterr = 0;
while ((c = getopt(argc, argv, "vpn:k:r:f:c:l:t:d:n:m:w:y:io:U:L:G:O:SC:B:E:M:N:R:Z:DI:Tu:")) != -1)
{
switch (c)
{
case 'T':
fctx.trimLAS = 1;
break;
case 'I':
fctx.areadID = atoi(optarg);
break;
case 'v':
fctx.nVerbose = 1;
break;
case 'p':
arg_purge = 1;
fctx.purgeLAS = 1;
break;
case 'S':
fctx.stitchChain = 1;
break;
case 'i':
fctx.keepIdentity = 1;
break;
case 'n':
fctx.nMinNonRepeatBases = atoi(optarg);
break;
case 'B':
pathOutDiscardReads = optarg;
break;
case 'R':
pathOutFullyDiscardAReads = optarg;
break;
case 'Z':
fctx.minLenOfFullyDiscardedAreads = atoi(optarg);
break;
case 'E':
fctx.minTipCoverage = atoi(optarg);
break;
case 'C':
fctx.stitchMaxChainLASs = atoi(optarg);
break;
case 'U':
fctx.stitchMaxTipFuzzy = atoi(optarg);
break;
case 'L':
fctx.stitchNonLowCompAnchorBases = atoi(optarg);
break;
case 'G':
fctx.stitchMaxGapSize = atoi(optarg);
break;
case 'M':
fctx.stitchMaxGapSizeInLowCompl = atoi(optarg);
break;
case 'N':
fctx.gapMinSpanners = atoi(optarg);
break;
case 'O':
fctx.stitchMinChainLen = atoi(optarg);
break;
case 'o':
fctx.minChainLen = atoi(optarg);
break;
case 'y':
fctx.rp_mergeTips = atoi(optarg);
break;
case 'f':
fctx.nFuzzBases = atoi(optarg);
break;
case 'c':
fctx.nContPerc = atoi(optarg);
break;
case 'r':
pcTrackRepeats = optarg;
break;
case 'l':
pcTrackLowCompl = optarg;
break;
case 't':
pcTrackTrim = optarg;
break;
case 'd':
fctx.maxOverallDiff = atoi(optarg);
break;
case 'k':
fctx.nkeptChains = atoi(optarg);
break;
case 'm':
fctx.mergeRepDist = atoi(optarg);
break;
case 'w':
fctx.repeatWindowLookBack = atoi(optarg);
break;
case 'D':
fctx.dazzlerFlags=1;
break;
case 'u':
fctx.maxBasesAtContigTips = atoi(optarg);
break;
default:
fprintf(stderr, "unknown option %c\n", optopt);
usage();
exit(1);
}
}
if (argc - optind != 3)
{
usage();
exit(1);
}
char* pcPathReadsIn = argv[optind++];
char* pcPathOverlapsIn = argv[optind++];
char* pcPathOverlapsOut = argv[optind++];
if ((fileOvlIn = fopen(pcPathOverlapsIn, "r")) == NULL)
{
fprintf(stderr, "could not open %s\n", pcPathOverlapsIn);
exit(1);
}
if ((fileOvlOut = fopen(pcPathOverlapsOut, "w")) == NULL)
{
fprintf(stderr, "could not open %s\n", pcPathOverlapsOut);
exit(1);
}
if (Open_DB(pcPathReadsIn, &db))
{
fprintf(stderr, "could not open %s\n", pcPathReadsIn);
exit(1);
}
if (fctx.nMinNonRepeatBases != -1)
{
fctx.trackRepeat = track_load(&db, pcTrackRepeats);
if (!fctx.trackRepeat)
{
fprintf(stderr, "could not load track %s\n", pcTrackRepeats);
exit(1);
}
}
if(fctx.dazzlerFlags && fctx.nkeptChains != 0)
{
fprintf(stderr, "If conversion to dazzler LAS flags is enabled, then number of chains should to keep must be 1 (for now)!\n");
exit(1);
}
// try to load further non-mandatory tracks
fctx.trackTrim = track_load(&db, pcTrackTrim);
if (!fctx.trackTrim)
fprintf(stderr, "[WARNING] - could not load track %s\n", pcTrackTrim);
fctx.trackLowCompl = track_load(&db, pcTrackLowCompl);
if (!fctx.trackLowCompl)
fprintf(stderr, "[WARNING] - could not load track %s\n", pcTrackLowCompl);
if (fctx.nContPerc < 0 || fctx.nContPerc > 100)
{
fprintf(stderr, "[ERROR] Invalid range for minimum percent of chain alignments %d. Must be in [1,100]\n", fctx.nContPerc);
exit(1);
}
if (fctx.nFuzzBases < 0)
{
fprintf(stderr, "[ERROR] -c fuzzy SV bases must be positive! (%d)\n", fctx.nFuzzBases);
exit(1);
}
if (pathOutDiscardReads)
{
FILE* fileOut = fopen(pathOutDiscardReads, "w");
if (fileOut == NULL)
{
fprintf(stderr, "could not open %s\n", pathOutDiscardReads);
exit(1);
}
fctx.fileOutDiscardedReads = fileOut;
}
if (pathOutFullyDiscardAReads)
{
FILE* fileOut = fopen(pathOutFullyDiscardAReads, "w");
if (fileOut == NULL)
{
fprintf(stderr, "could not open %s\n", pathOutFullyDiscardAReads);
exit(1);
}
fctx.fileOutFullyDiscardedAreads = fileOut;
}
// passes
pctx = pass_init(fileOvlIn, fileOvlOut);
pctx->split_b = 0;
pctx->load_trace = 1;
pctx->unpack_trace = 1;
pctx->data = &fctx;
pctx->write_overlaps = 1;
pctx->purge_discarded = arg_purge;
filter_pre(pctx, &fctx);
pass(pctx, filter_handler);
filter_post(&fctx);
pass_free(pctx);
// cleanup
Close_DB(&db);
if (fctx.fileOutDiscardedReads)
{
fclose(fctx.fileOutDiscardedReads);
}
if (fctx.fileOutFullyDiscardedAreads)
{
fclose(fctx.fileOutFullyDiscardedAreads);
}
fclose(fileOvlOut);
fclose(fileOvlIn);
return 0;
}
|
MartinPippel/DAmar
|
utils/TKtrim.c
|
<gh_stars>10-100
/*******************************************************************************************
*
* Date : November 2016
*
*******************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "lib/tracks.h"
#include "db/DB.h"
#include "dalign/align.h"
#include "lib/pass.h"
#define DEF_ARG_E 1500
#define DEF_ARG_S 4
extern char* optarg;
extern int optind, opterr, optopt;
static void usage()
{
fprintf(stderr, "[-voS] [-es <int>] <db> <trackIn> <trackOut>\n");
fprintf(stderr, "Options: -v ... verbose\n");
fprintf(stderr, " -S ... summary stats for trimmed track\n");
fprintf(stderr, " -e ... remove n bases from given interval track (%d)\n", DEF_ARG_E);
fprintf(stderr, " -s ... # bytes for an entry (%d)\n", DEF_ARG_S);
fprintf(stderr, " -o ... old version (-1)\n");
}
static int isPowerOfTwo(unsigned int x)
{
return ((x != 0) && ((x & (~x + 1)) == x));
}
static uint64_t value(void* v, int bytes)
{
if (bytes == 1)
{
return *(unsigned char*) (v);
}
else if (bytes == 2)
{
return *(unsigned short*) (v);
}
else if (bytes == 4)
{
return *(uint32*) (v);
}
else if (bytes == 8)
{
return *(uint64_t*) (v);
}
return 0;
}
int main(int argc, char* argv[])
{
HITS_DB db;
HITS_TRACK* trackIn = NULL;
HITS_TRACK* trackOut = NULL;
char* pcDb;
char* pcTrackIn;
char* pcTrackOut;
int numBases = DEF_ARG_E;
int dsize = DEF_ARG_S;
int verbose = 0;
int stats = 0;
int oldVersion = 0;
// args
opterr = 0;
int c;
while ((c = getopt(argc, argv, "voSe:s:")) != -1)
{
switch (c)
{
case 'v':
verbose = 1;
break;
case 'S':
stats = 1;
break;
case 'o':
oldVersion = 1;
break;
case 'e':
numBases = atoi(optarg);
break;
case 's':
dsize = atoi(optarg);
break;
default:
usage();
exit(1);
}
}
if (argc - optind != 3)
{
usage();
exit(1);
}
pcDb = argv[optind++];
pcTrackIn = argv[optind++];
pcTrackOut = argv[optind++];
if (!isPowerOfTwo(dsize))
{
fprintf(stderr, "-s must be a power of 2\n");
exit(1);
}
if (strcmp(pcTrackIn, pcTrackOut) == 0)
{
fprintf(stderr, "trackIn and trackOut cannot be the same!\n");
exit(1);
}
if (Open_DB(pcDb, &db))
{
fprintf(stderr, "failed to open database '%s'\n", pcDb);
exit(1);
}
trackIn = track_load(&db, pcTrackIn);
if (trackIn == NULL)
{
fprintf(stderr, "could not open track '%s'\n", pcTrackIn);
exit(1);
}
void* annoIn = trackIn->anno;
void* dataIn = trackIn->data;
int nreads = DB_NREADS(&db);
track_anno* annoOut = (track_anno*)malloc(sizeof(track_anno) * (nreads + 1));
track_data* dataOut = (track_data*)malloc( ((track_anno*)annoIn)[nreads] );
track_anno tcur = 0;
bzero(annoOut, sizeof(track_anno) * (nreads + 1));
track_anno_header header;
bzero(&header, sizeof(track_anno_header));
trackOut = malloc(sizeof(HITS_TRACK));
trackOut->name = strdup(pcTrackOut);
trackOut->data = dataOut;
trackOut->anno = annoOut;
trackOut->size = header.size;
int i, j, rlen;
uint64_t bi, ei;
track_data v1 ,v2;
uint64_t nTrimIn, nTrimOut;
nTrimIn = nTrimOut = 0;
for (i = 0; i < db.nreads; i++)
{
if (trackIn->size == sizeof(int))
{
bi = ((uint32*) annoIn)[i];
ei = ((uint32*) annoIn)[i + 1];
}
else
{
bi = ((uint64_t*) annoIn)[i];
ei = ((uint64_t*) annoIn)[i + 1];
}
if (bi >= ei)
{
continue;
}
if (((ei - bi) / dsize) & 1)
{
fprintf(stderr, "ERROR: Track %s is not an interval track!\n", pcTrackIn);
exit(1);
}
if(verbose)
printf("%d (%" PRIu64 ")", i, (ei - bi) / dsize);
rlen = DB_READ_LEN(&db, i);
if(verbose)
printf(" l(%d)", rlen);
while (bi < ei)
{
v1 = value(dataIn + bi, dsize);
v2 = value(dataIn + bi + dsize, dsize);
nTrimIn += v2 - v1;
if(verbose)
printf(" %d %d", v1, v2);
if(v2 < numBases || v1 > rlen - numBases)
{
v1 = -1;
v2 = -1;
}
else
{
if(v1 < numBases)
{
v1 = numBases;
}
if(v2 > rlen - numBases)
{
v2 = rlen - numBases;
}
}
if(v2 > v1)
{
dataOut[ tcur++ ] = v1;
dataOut[ tcur++ ] = v2;
annoOut[ i ] += 2 * sizeof(track_data);
nTrimOut += v2 - v1;
}
if(verbose)
{
if(v2 > v1)
printf(" --> [%d %d]", v1, v2);
else
printf(" --> skip");
}
bi += 2 * dsize;
}
if(verbose)
printf("\n");
}
track_anno qoff, coff;
qoff = 0;
for (j = 0; j <= nreads; j++)
{
coff = annoOut[j];
annoOut[j] = qoff;
qoff += coff;
}
if(oldVersion)
write_track_trimmed(&db, trackOut->name, 0, trackOut->anno, trackOut->data, tcur);
else
track_write(&db, trackOut->name, 0, trackOut->anno, trackOut->data, tcur);
if (db.tracks == NULL)
track_close(trackIn);
track_close(trackOut);
Close_DB(&db);
if(stats)
{
printf("pre bases: %10" PRIu64 "\n", nTrimIn);
printf("post bases:%10" PRIu64 "\n", nTrimOut);
}
return 0;
}
|
MartinPippel/DAmar
|
utils/LAindex.c
|
<gh_stars>10-100
/**
* Index an overlap file.
* - index is used in LAexplorer
*/
/**
* Idea: add repeats track to contig database
*
* Input:
* 1. Contig-db with reads track (readID,beg,end)
* 2. database with interval track that should be added to Contig-db
* 3. interval track
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/param.h>
#include "db/DB.h"
#include "lib/lasidx.h"
static void usage()
{
printf("Index an overlap file. Creates an ovl.idx file.\n\n");
printf("LAindex <db> <ovl> \n");
}
;
int main(int argc, char* argv[])
{
HITS_DB db;
if (argc != 3)
{
usage();
exit(1);
}
if (Open_DB(argv[1], &db))
{
fprintf(stderr, "could not open '%s'\n", argv[1]);
exit(1);
}
lasidx* idx = lasidx_create(&db, argv[2]);
if(idx == NULL)
{
fprintf(stderr, "Cannot create index file '%s'\n", argv[2]);
exit(1);
}
// cleanup
free(idx);
Close_DB(&db);
return 0;
}
|
MartinPippel/DAmar
|
dalign/align.c
|
<filename>dalign/align.c
/************************************************************************************\
* *
* Copyright (c) 2014, Dr. <NAME> (EWM). All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without modification, *
* are permitted provided that the following conditions are met: *
* *
* · Redistributions of source code must retain the above copyright notice, this *
* list of conditions and the following disclaimer. *
* *
* · Redistributions in binary form must reproduce the above copyright notice, this *
* list of conditions and the following disclaimer in the documentation and/or *
* other materials provided with the distribution. *
* *
* · The name of EWM may not be used to endorse or promote products derived from *
* this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY EWM ”AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, *
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND *
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL EWM BE LIABLE *
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS *
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY *
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING *
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN *
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
* *
* For any issues regarding this software and its use, contact EWM at: *
* *
* <NAME>. *
* Bautzner Str. 122e *
* 01099 Dresden *
* GERMANY *
* Email: <EMAIL> *
* *
\************************************************************************************/
/*******************************************************************************************
*
* Fast alignment discovery and trace generation along with utilites for displaying alignments
* Based on previously unpublished ideas from 2005, subsequently refined in 2013-14. Basic
* idea is to keep a dynamically selected interval of the f.r. waves from my 1986 O(nd) paper.
* A recent cool idea is to not record all the details of an alignment while discovering it
* but simply record trace points through which the optimal alignment passes every 100bp,
* allowing rapid recomputation of the alignment details between trace points.
*
* Author : <NAME>
* First : June 2013
* Current: June 1, 2014
*
********************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <math.h>
#include <limits.h>
#include <assert.h>
#include "db/DB.h"
#include "align.h"
#undef DEBUG_PASSES // Show forward / backward extension termini for Local_Alignment
#undef DEBUG_POINTS // Show trace points
#undef DEBUG_WAVE // Show waves of Local_Alignment
#undef SHOW_MATCH_WAVE // For waves of Local_Alignment also show # of matches
#undef SHOW_TRAIL // Show trace at the end of forward and reverse passes
#undef SHOW_TPS // Show trace points as they are encountered in a wave
#undef DEBUG_EXTEND // Show waves of Extend_Until_Overlap
#undef DEBUG_ALIGN // Show division points of Compute_Trace
#undef DEBUG_TRACE // Show trace additions for Compute_Trace
#undef DEBUG_SCRIPT // Show script additions for Compute_Trace
#undef DEBUG_AWAVE // Show F/R waves of Compute_Trace
#undef SHOW_TRACE // Show full trace for Print_Alignment
#undef WAVE_STATS
/****************************************************************************************\
* *
* Working Storage Abstraction *
* *
\****************************************************************************************/
typedef struct // Hidden from the user, working space for each thread
{
int vecmax;
void *vector;
int celmax;
void *cells;
int pntmax;
void *points;
int tramax;
void *trace;
} _Work_Data;
Work_Data *New_Work_Data()
{
_Work_Data *work;
work = (_Work_Data *) Malloc(sizeof(_Work_Data), "Allocating work data block");
if (work == NULL)
EXIT(NULL);
work->vecmax = 0;
work->vector = NULL;
work->pntmax = 0;
work->points = NULL;
work->tramax = 0;
work->trace = NULL;
work->celmax = 0;
work->cells = NULL;
return ((Work_Data *) work);
}
static int enlarge_vector(_Work_Data *work, int newmax)
{
void *vec;
int max;
max = ((int) (newmax * 1.2)) + 10000;
vec = Realloc(work->vector, max, "Enlarging DP vector");
if (vec == NULL)
EXIT(1);
work->vecmax = max;
work->vector = vec;
return (0);
}
static int enlarge_points(_Work_Data *work, int newmax)
{
void *vec;
int max;
max = ((int) (newmax * 1.2)) + 10000;
vec = Realloc(work->points, max, "Enlarging point vector");
if (vec == NULL)
EXIT(1);
work->pntmax = max;
work->points = vec;
return (0);
}
static int enlarge_trace(_Work_Data *work, int newmax)
{
void *vec;
int max;
max = ((int) (newmax * 1.2)) + 10000;
vec = Realloc(work->trace, max, "Enlarging trace vector");
if (vec == NULL)
EXIT(1);
work->tramax = max;
work->trace = vec;
return (0);
}
void Free_Work_Data(Work_Data *ework)
{
_Work_Data *work = (_Work_Data *) ework;
if (work->vector != NULL)
free(work->vector);
if (work->cells != NULL)
free(work->cells);
if (work->trace != NULL)
free(work->trace);
if (work->points != NULL)
free(work->points);
free(work);
}
/****************************************************************************************\
* *
* ADAPTIVE PATH FINDING *
* *
\****************************************************************************************/
// Absolute/Fixed Parameters
#define BVEC uint64 // Can be uint32 if PATH_LEN <= 32
#define TRIM_LEN 15 // Report as the tip, the last wave maximum for which the last
// 2*TRIM_LEN edits are prefix-positive at rate ave_corr*f(bias)
// (max value is 20)
#define PATH_LEN 60 // Follow the last PATH_LEN columns/edges (max value is 63)
// Derivative fixed parameters
#define PATH_TOP 0x1000000000000000ll // Must be 1 << PATH_LEN
#define PATH_INT 0x0fffffffffffffffll // Must be PATH_TOP-1
#define TRIM_MASK 0x7fff // Must be (1 << TRIM_LEN) - 1
#define TRIM_MLAG 200 // How far can last trim point be behind best point
#define WAVE_LAG 30 // How far can worst point be behind the best point
static double Bias_Factor[10] =
{ .690, .690, .690, .690, .780, .850, .900, .933, .966, 1.000 };
// Adjustable paramters
typedef struct
{
double ave_corr;
int trace_space;
int reach;
float freq[4];
int ave_path;
int16 *score;
int16 *table;
int nthreads; // HEIDELBERG_MODIFICATION
Overlap_IO_Buffer *ioBuffer; // HEIDELBERG_MODIFICATION
int symmetric; // HEIDELBERG_MODIFICATION
int only_identity; // HEIDELBERG_MODIFICATION
int no_trace_points; // HEIDELBERG_MODIFICATION
} _Align_Spec;
/* Fill in bit table: TABLE[x] = 1 iff the alignment modeled by x (1 = match, 0 = mismatch)
has a non-negative score for every suffix of the alignment under the scoring scheme
where match = MATCH and mismatch = -1. MATCH is set so that an alignment with TRIM_PCT
matches has zero score ( (1-TRIM_PCT) / TRIM_PCT ). */
#define FRACTION 1000 // Implicit fractional part of scores, i.e. score = x/FRACTION
typedef struct
{
int mscore;
int dscore;
int16 *table;
int16 *score;
} Table_Bits;
static void set_table(int bit, int prefix, int score, int max, Table_Bits *parms)
{
if (bit >= TRIM_LEN)
{
parms->table[prefix] = (int16) (score - max);
parms->score[prefix] = (int16) score;
}
else
{
if (score > max)
max = score;
set_table(bit + 1, (prefix << 1), score - parms->dscore, max, parms);
set_table(bit + 1, (prefix << 1) | 1, score + parms->mscore, max, parms);
}
}
/* Create an alignment specification record including path tip tables & values */
Align_Spec *New_Align_Spec(double ave_corr, int trace_space, float *freq, int nthreads, int symmetric, int only_identity, int no_trace_points, int reach)
{
_Align_Spec *spec;
Table_Bits parms;
double match;
int bias;
spec = (_Align_Spec *) Malloc(sizeof(_Align_Spec), "Allocating alignment specification");
if (spec == NULL)
EXIT(NULL);
spec->ave_corr = ave_corr;
spec->trace_space = trace_space;
spec->reach = reach;
spec->freq[0] = freq[0];
spec->freq[1] = freq[1];
spec->freq[2] = freq[2];
spec->freq[3] = freq[3];
match = freq[0] + freq[3];
if (match > .5)
match = 1. - match;
bias = (int) ((match + .025) * 20. - 1.);
if (match < .2)
{
fprintf(stderr, "Warning: Base bias worse than 80/20%% ! (New_Align_Spec)\n");
fprintf(stderr, " Capping bias at this ratio.\n");
bias = 3;
}
spec->ave_path = (int) (PATH_LEN * (1. - Bias_Factor[bias] * (1. - ave_corr)));
parms.mscore = (int) (FRACTION * Bias_Factor[bias] * (1. - ave_corr));
parms.dscore = FRACTION - parms.mscore;
parms.score = (int16 *) Malloc(sizeof(int16) * (TRIM_MASK + 1) * 2, "Allocating trim table");
if (parms.score == NULL)
{
free(spec);
EXIT(NULL);
}
parms.table = parms.score + (TRIM_MASK + 1);
set_table(0, 0, 0, 0, &parms);
spec->table = parms.table;
spec->score = parms.score;
{ // HEIDELBERG_MODIFICATION
spec->nthreads = nthreads;
spec->symmetric = symmetric;
spec->only_identity = only_identity;
int i;
spec->ioBuffer = (Overlap_IO_Buffer*) malloc(sizeof(Overlap_IO_Buffer) * nthreads);
for (i = 0; i < nthreads; i++)
{
Overlap_IO_Buffer *ob = CreateOverlapBuffer(nthreads, (trace_space <= TRACE_XOVR) ? sizeof(uint8) : sizeof(uint16), no_trace_points);
if (ob == NULL)
exit(1);
spec->ioBuffer[i] = *ob;
}
}
return ((Align_Spec *) spec);
}
void Free_Align_Spec(Align_Spec *espec)
{
_Align_Spec *spec = (_Align_Spec *) espec;
free(spec->score);
free(spec);
}
double Average_Correlation(Align_Spec *espec)
{
return (((_Align_Spec *) espec)->ave_corr);
}
int Trace_Spacing(Align_Spec *espec)
{
return (((_Align_Spec *) espec)->trace_space);
}
float *Base_Frequencies(Align_Spec *espec)
{
return (((_Align_Spec *) espec)->freq);
}
int Overlap_If_Possible(Align_Spec *espec)
{
return (((_Align_Spec *) espec)->reach);
}
/****************************************************************************************\
* *
* LOCAL ALIGNMENT FINDER: forward_/reverse_wave and Local_Alignment *
* *
\****************************************************************************************/
#ifdef WAVE_STATS
static int64 MAX, TOT, NWV;
static int64 RESTARTS;
void Init_Stats()
{ MAX = TOT = NWV = 0;
RESTARTS = 0;
}
void Print_Stats()
{ printf("\nMax = %lld Ave = %.1f # = %lld\n",MAX,(1.*TOT)/NWV,NWV);
printf("\nRestarts = %lld\n",RESTARTS);
}
#endif
#ifdef DEBUG_WAVE
static void print_wave(int *V, int *M, int low, int hgh, int besta)
{ int k, bestk;
(void) M;
printf(" [%6d,%6d]: ",low,hgh);
for (k = low; k <= hgh; k++)
{ if (besta == V[k])
bestk = k;
// printf(" %3d",(V[k]+k)/2);
printf(" %3d",besta-V[k]);
}
printf(" : %d (%d,%d)\n",besta,(besta+bestk)/2,(besta-bestk)/2);
#ifdef SHOW_MATCH_WAVE
printf(" ");
for (k = low; k <= hgh; k++)
printf(" %3d",M[k]);
printf("\n");
#endif
fflush(stdout);
}
#endif
/* At each furthest reaching point, keep a-coordinate of point (V), bitvector
recording the last TRIM_LEN columns of the implied alignment (T), and the
# of matches (1-bits) in the bitvector (M). */
typedef struct
{
int ptr;
int diag;
int diff;
int mark;
} Pebble;
static int VectorEl = 6 * sizeof(int) + sizeof(BVEC);
static int forward_wave(_Work_Data *work, _Align_Spec *spec, Alignment *align, Path *bpath, int *mind, int maxd, int mida, int minp, int maxp, int aoff,
int boff)
{
char *aseq = align->aseq;
char *bseq = align->bseq;
Path *apath = align->path;
int hgh, low, dif;
int vlen, vmin, vmax;
int *V, *M;
int *_V, *_M;
BVEC *T;
BVEC *_T;
int *HA, *HB;
int *_HA, *_HB;
int *NA, *NB;
int *_NA, *_NB;
Pebble *cells;
int avail, cmax;
int TRACE_SPACE = spec->trace_space;
int PATH_AVE = spec->ave_path;
int REACH = spec->reach;
int16 *SCORE = spec->score;
int16 *TABLE = spec->table;
int besta, besty;
int trima, trimy, trimd;
int trimha, trimhb;
int morea, morey, mored;
int moreha, morehb;
int more, morem, lasta;
int aclip, bclip;
hgh = maxd;
low = *mind;
dif = 0;
{
int span, wing;
span = (hgh - low) + 1;
vlen = work->vecmax / VectorEl;
wing = (vlen - span) / 2;
vmin = low - wing;
vmax = hgh + wing;
_V = ((int *) work->vector);
_M = _V + vlen;
_HA = _M + vlen;
_HB = _HA + vlen;
_NA = _HB + vlen;
_NB = _NA + vlen;
_T = ((BVEC *) (_NB + vlen));
V = _V - vmin;
M = _M - vmin;
HA = _HA - vmin;
HB = _HB - vmin;
NA = _NA - vmin;
NB = _NB - vmin;
T = _T - vmin;
cells = (Pebble *) (work->cells);
cmax = work->celmax;
avail = 0;
}
/* Compute 0-wave starting from mid-line */
more = 1;
aclip = INT32_MAX;
bclip = -INT32_MAX;
besta = trima = morea = lasta = mida;
besty = trimy = morey = (mida - hgh) >> 1;
trimd = mored = 0;
trimha = moreha = 0;
trimhb = morehb = 1;
morem = -1;
{
int k;
char *a;
a = aseq + hgh;
for (k = hgh; k >= low; k--)
{
int y, c, d;
int ha, hb;
int na, nb;
Pebble *pb;
y = (mida - k) >> 1;
if (avail >= cmax - 1)
{
cmax = ((int) (avail * 1.2)) + 10000;
cells = (Pebble *) Realloc(cells, cmax * sizeof(Pebble), "Reallocating trace cells");
if (cells == NULL)
EXIT(1);
work->celmax = cmax;
work->cells = (void *) cells;
}
na = (((y + k) + (TRACE_SPACE - aoff)) / TRACE_SPACE - 1) * TRACE_SPACE + aoff;
#ifdef SHOW_TPS
printf(" A %d: %d,%d,0,%d\n",avail,-1,k,na); fflush(stdout);
#endif
pb = cells + avail;
pb->ptr = -1;
pb->diag = k;
pb->diff = 0;
pb->mark = na;
ha = avail++;
na += TRACE_SPACE;
nb = ((y + (TRACE_SPACE - boff)) / TRACE_SPACE - 1) * TRACE_SPACE + boff;
#ifdef SHOW_TPS
printf(" B %d: %d,%d,0,%d\n",avail,-1,k,nb); fflush(stdout);
#endif
pb = cells + avail;
pb->ptr = -1;
pb->diag = k;
pb->diff = 0;
pb->mark = nb;
hb = avail++;
nb += TRACE_SPACE;
while (1)
{
c = bseq[y];
if (c == 4)
{
more = 0;
if (bclip < k)
bclip = k;
break;
}
d = a[y];
if (c != d)
{
if (d == 4)
{
more = 0;
aclip = k;
}
break;
}
y += 1;
}
c = (y << 1) + k;
while (y + k >= na)
{
if (avail >= cmax)
{
cmax = ((int) (avail * 1.2)) + 10000;
cells = (Pebble *) Realloc(cells, cmax * sizeof(Pebble), "Reallocating trace cells");
if (cells == NULL)
EXIT(1);
work->celmax = cmax;
work->cells = (void *) cells;
}
#ifdef SHOW_TPS
printf(" A %d: %d,%d,0,%d\n",avail,ha,k,na); fflush(stdout);
#endif
pb = cells + avail;
pb->ptr = ha;
pb->diag = k;
pb->diff = 0;
pb->mark = na;
ha = avail++;
na += TRACE_SPACE;
}
while (y >= nb)
{
if (avail >= cmax)
{
cmax = ((int) (avail * 1.2)) + 10000;
cells = (Pebble *) Realloc(cells, cmax * sizeof(Pebble), "Reallocating trace cells");
if (cells == NULL)
EXIT(1);
work->celmax = cmax;
work->cells = (void *) cells;
}
#ifdef SHOW_TPS
printf(" B %d: %d,%d,0,%d\n",avail,hb,k,nb); fflush(stdout);
#endif
pb = cells + avail;
pb->ptr = hb;
pb->diag = k;
pb->diff = 0;
pb->mark = nb;
hb = avail++;
nb += TRACE_SPACE;
}
if (c > besta)
{
besta = trima = lasta = c;
besty = trimy = y;
trimha = ha;
trimhb = hb;
}
V[k] = c;
T[k] = PATH_INT;
M[k] = PATH_LEN;
HA[k] = ha;
HB[k] = hb;
NA[k] = na;
NB[k] = nb;
a -= 1;
}
}
if (more == 0)
{
if (bseq[besty] != 4 && aseq[besta - besty] != 4)
more = 1;
if (hgh >= aclip)
{
hgh = aclip - 1;
if (morem <= M[aclip])
{
morem = M[aclip];
morea = V[aclip];
morey = (morea - aclip) / 2;
moreha = HA[aclip];
morehb = HB[aclip];
}
}
if (low <= bclip)
{
low = bclip + 1;
if (morem <= M[bclip])
{
morem = M[bclip];
morea = V[bclip];
morey = (morea - bclip) / 2;
moreha = HA[bclip];
morehb = HB[bclip];
}
}
aclip = INT32_MAX;
bclip = -INT32_MAX;
}
#ifdef DEBUG_WAVE
printf("\nFORWARD WAVE:\n");
print_wave(V,M,low,hgh,besta);
#endif
/* Compute successive waves until no furthest reaching points remain */
while (more && lasta >= besta - TRIM_MLAG)
{
int k, n;
int ua, ub;
BVEC t;
int am, ac, ap;
char *a;
low -= 1;
hgh += 1;
if (low <= vmin || hgh >= vmax)
{
int span, wing;
int64 move;
int64 vd, md, had, hbd, nad, nbd, td;
span = (hgh - low) + 1;
if (.8 * vlen < span)
{
if (enlarge_vector(work, vlen * VectorEl))
EXIT(1);
move = ((void *) _V) - work->vector;
vlen = work->vecmax / VectorEl;
_V = (int *) work->vector;
_M = _V + vlen;
_HA = _M + vlen;
_HB = _HA + vlen;
_NA = _HB + vlen;
_NB = _NA + vlen;
_T = ((BVEC *) (_NB + vlen));
}
else
move = 0;
wing = (vlen - span) / 2;
vd = ((void *) (_V + wing)) - (((void *) (V + low)) - move);
md = ((void *) (_M + wing)) - (((void *) (M + low)) - move);
had = ((void *) (_HA + wing)) - (((void *) (HA + low)) - move);
hbd = ((void *) (_HB + wing)) - (((void *) (HB + low)) - move);
nad = ((void *) (_NA + wing)) - (((void *) (NA + low)) - move);
nbd = ((void *) (_NB + wing)) - (((void *) (NB + low)) - move);
td = ((void *) (_T + wing)) - (((void *) (T + low)) - move);
if (vd < 0)
memmove(_V + wing, ((void *) (V + low)) - move, span * sizeof(int));
if (md < 0)
memmove(_M + wing, ((void *) (M + low)) - move, span * sizeof(int));
if (had < 0)
memmove(_HA + wing, ((void *) (HA + low)) - move, span * sizeof(int));
if (hbd < 0)
memmove(_HB + wing, ((void *) (HB + low)) - move, span * sizeof(int));
if (nad < 0)
memmove(_NA + wing, ((void *) (NA + low)) - move, span * sizeof(int));
if (nbd < 0)
memmove(_NB + wing, ((void *) (NB + low)) - move, span * sizeof(int));
if (td < 0)
memmove(_T + wing, ((void *) (T + low)) - move, span * sizeof(BVEC));
if (td > 0)
memmove(_T + wing, ((void *) (T + low)) - move, span * sizeof(BVEC));
if (nbd > 0)
memmove(_NB + wing, ((void *) (NB + low)) - move, span * sizeof(int));
if (nad > 0)
memmove(_NA + wing, ((void *) (NA + low)) - move, span * sizeof(int));
if (hbd > 0)
memmove(_HB + wing, ((void *) (HB + low)) - move, span * sizeof(int));
if (had > 0)
memmove(_HA + wing, ((void *) (HA + low)) - move, span * sizeof(int));
if (md > 0)
memmove(_M + wing, ((void *) (M + low)) - move, span * sizeof(int));
if (vd > 0)
memmove(_V + wing, ((void *) (V + low)) - move, span * sizeof(int));
vmin = low - wing;
vmax = hgh + wing;
V = _V - vmin;
M = _M - vmin;
HA = _HA - vmin;
HB = _HB - vmin;
NA = _NA - vmin;
NB = _NB - vmin;
T = _T - vmin;
}
if (low >= minp)
{
NA[low] = NA[low + 1];
NB[low] = NB[low + 1];
V[low] = -1;
}
else
low += 1;
if (hgh <= maxp)
{
NA[hgh] = NA[hgh - 1];
NB[hgh] = NB[hgh - 1];
V[hgh] = am = -1;
}
else
am = V[--hgh];
dif += 1;
ac = V[hgh + 1] = V[low - 1] = -1;
a = aseq + hgh;
t = PATH_INT;
n = PATH_LEN;
ua = ub = -1;
for (k = hgh; k >= low; k--)
{
int y, m;
int ha, hb;
int c, d;
BVEC b;
Pebble *pb;
ap = ac;
ac = am;
am = V[d = k - 1];
if (ac < am)
if (am < ap)
{
c = ap + 1;
m = n;
b = t;
ha = ua;
hb = ub;
}
else
{
c = am + 1;
m = M[d];
b = T[d];
ha = HA[d];
hb = HB[d];
}
else if (ac < ap)
{
c = ap + 1;
m = n;
b = t;
ha = ua;
hb = ub;
}
else
{
c = ac + 2;
m = M[k];
b = T[k];
ha = HA[k];
hb = HB[k];
}
if ((b & PATH_TOP) != 0)
m -= 1;
b <<= 1;
y = (c - k) >> 1;
while (1)
{
c = bseq[y];
if (c == 4)
{
more = 0;
if (bclip < k)
bclip = k;
break;
}
d = a[y];
if (c != d)
{
if (d == 4)
{
more = 0;
aclip = k;
}
break;
}
y += 1;
if ((b & PATH_TOP) == 0)
m += 1;
b = (b << 1) | 1;
}
c = (y << 1) + k;
while (y + k >= NA[k])
{
if (cells[ha].mark < NA[k])
{
if (avail >= cmax)
{
cmax = ((int) (avail * 1.2)) + 10000;
cells = (Pebble *) Realloc(cells, cmax * sizeof(Pebble), "Reallocating trace cells");
if (cells == NULL)
EXIT(1);
work->celmax = cmax;
work->cells = (void *) cells;
}
#ifdef SHOW_TPS
printf(" A %d: %d,%d,%d,%d\n",avail,ha,k,dif,NA[k]); fflush(stdout);
#endif
pb = cells + avail;
pb->ptr = ha;
pb->diag = k;
pb->diff = dif;
pb->mark = NA[k];
ha = avail++;
}
NA[k] += TRACE_SPACE;
}
while (y >= NB[k])
{
if (cells[hb].mark < NB[k])
{
if (avail >= cmax)
{
cmax = ((int) (avail * 1.2)) + 10000;
cells = (Pebble *) Realloc(cells, cmax * sizeof(Pebble), "Reallocating trace cells");
if (cells == NULL)
EXIT(1);
work->celmax = cmax;
work->cells = (void *) cells;
}
#ifdef SHOW_TPS
printf(" B %d: %d,%d,%d,%d\n",avail,hb,k,dif,NB[k]); fflush(stdout);
#endif
pb = cells + avail;
pb->ptr = hb;
pb->diag = k;
pb->diff = dif;
pb->mark = NB[k];
hb = avail++;
}
NB[k] += TRACE_SPACE;
}
if (c > besta)
{
besta = c;
besty = y;
if (m >= PATH_AVE)
{
lasta = c;
if (TABLE[b & TRIM_MASK] >= 0)
if (TABLE[(b >> TRIM_LEN) & TRIM_MASK] + SCORE[b & TRIM_MASK] >= 0)
{
trima = c;
trimy = y;
trimd = dif;
trimha = ha;
trimhb = hb;
}
}
}
t = T[k];
n = M[k];
ua = HA[k];
ub = HB[k];
V[k] = c;
T[k] = b;
M[k] = m;
HA[k] = ha;
HB[k] = hb;
a -= 1;
}
if (more == 0)
{
if (bseq[besty] != 4 && aseq[besta - besty] != 4)
more = 1;
if (hgh >= aclip)
{
hgh = aclip - 1;
if (morem <= M[aclip])
{
morem = M[aclip];
morea = V[aclip];
morey = (morea - aclip) / 2;
mored = dif;
moreha = HA[aclip];
morehb = HB[aclip];
}
}
if (low <= bclip)
{
low = bclip + 1;
if (morem <= M[bclip])
{
morem = M[bclip];
morea = V[bclip];
morey = (morea - bclip) / 2;
mored = dif;
moreha = HA[bclip];
morehb = HB[bclip];
}
}
aclip = INT32_MAX;
bclip = -INT32_MAX;
}
n = besta - WAVE_LAG;
while (hgh >= low)
if (V[hgh] < n)
hgh -= 1;
else
{
while (V[low] < n)
low += 1;
break;
}
#ifdef WAVE_STATS
k = (hgh-low)+1;
if (k > MAX)
MAX = k;
TOT += k;
NWV += 1;
#endif
#ifdef DEBUG_WAVE
print_wave(V,M,low,hgh,besta);
#endif
}
{
uint16 *atrace = (uint16 *) apath->trace;
uint16 *btrace = (uint16 *) bpath->trace;
int atlen, btlen;
int trimx;
int a, b, k, h;
int d, e;
if (morem >= 0 && REACH)
{
trimx = morea - morey;
trimy = morey;
trimd = mored;
trimha = moreha;
trimhb = morehb;
}
else
trimx = trima - trimy;
atlen = btlen = 0;
a = -1;
for (h = trimha; h >= 0; h = b)
{
b = cells[h].ptr;
cells[h].ptr = a;
a = h;
}
h = a;
k = cells[h].diag;
b = (mida - k) / 2;
e = 0;
#ifdef SHOW_TRAIL
printf(" A path = (%5d,%5d)\n",(mida+k)/2,b); fflush(stdout);
#endif
for (h = cells[h].ptr; h >= 0; h = cells[h].ptr)
{
k = cells[h].diag;
a = cells[h].mark - k;
d = cells[h].diff;
atrace[atlen++] = (uint16) (d - e);
atrace[atlen++] = (uint16) (a - b);
#ifdef SHOW_TRAIL
printf(" %4d: (%5d,%5d): %3d / %3d\n",h,a+k,a,d-e,a-b); fflush(stdout);
#endif
b = a;
e = d;
}
if (b + k != trimx)
{
atrace[atlen++] = (uint16) (trimd - e);
atrace[atlen++] = (uint16) (trimy - b);
#ifdef SHOW_TRAIL
printf(" (%5d,%5d): %3d / %3d\n",trimx,trimy,trimd-e,trimy-b); fflush(stdout);
#endif
}
else if (b != trimy)
{
atrace[atlen - 1] = (uint16) (atrace[atlen - 1] + (trimy - b));
atrace[atlen - 2] = (uint16) (atrace[atlen - 2] + (trimd - e));
#ifdef SHOW_TRAIL
printf(" @ (%5d,%5d): %3d / %3d\n",trimx,trimy,trimd-e,trimy-b); fflush(stdout);
#endif
}
a = -1;
for (h = trimhb; h >= 0; h = b)
{
b = cells[h].ptr;
cells[h].ptr = a;
a = h;
}
h = a;
k = cells[h].diag;
b = (mida + k) / 2;
e = 0;
low = k;
#ifdef SHOW_TRAIL
printf(" B path = (%5d,%5d)\n",b,(mida-k)/2); fflush(stdout);
#endif
for (h = cells[h].ptr; h >= 0; h = cells[h].ptr)
{
k = cells[h].diag;
a = cells[h].mark + k;
d = cells[h].diff;
btrace[btlen++] = (uint16) (d - e);
btrace[btlen++] = (uint16) (a - b);
#ifdef SHOW_TRAIL
printf(" %4d: (%5d,%5d): %3d / %3d\n",h,a,a-k,d-e,a-b); fflush(stdout);
#endif
b = a;
e = d;
}
if (b - k != trimy)
{
btrace[btlen++] = (uint16) (trimd - e);
btrace[btlen++] = (uint16) (trimx - b);
#ifdef SHOW_TRAIL
printf(" (%5d,%5d): %3d / %3d\n",trimx,trimy,trimd-e,trimx-b); fflush(stdout);
#endif
}
else if (b != trimx)
{
btrace[btlen - 1] = (uint16) (btrace[btlen - 1] + (trimx - b));
btrace[btlen - 2] = (uint16) (btrace[btlen - 2] + (trimd - e));
#ifdef SHOW_TRAIL
printf(" @ (%5d,%5d): %3d / %3d\n",trimx,trimy,trimd-e,trimx-b); fflush(stdout);
#endif
}
apath->aepos = trimx;
apath->bepos = trimy;
apath->diffs = trimd;
apath->tlen = atlen;
bpath->tlen = btlen;
}
*mind = low;
return (0);
}
/*** Reverse Wave ***/
static int reverse_wave(_Work_Data *work, _Align_Spec *spec, Alignment *align, Path *bpath, int mind, int maxd, int mida, int minp, int maxp, int aoff,
int boff)
{
char *aseq = align->aseq - 1;
char *bseq = align->bseq - 1;
Path *apath = align->path;
int hgh, low, dif;
int vlen, vmin, vmax;
int *V, *M;
int *_V, *_M;
BVEC *T;
BVEC *_T;
int *HA, *HB;
int *_HA, *_HB;
int *NA, *NB;
int *_NA, *_NB;
Pebble *cells;
int avail, cmax;
int TRACE_SPACE = spec->trace_space;
int PATH_AVE = spec->ave_path;
int REACH = spec->reach;
int16 *SCORE = spec->score;
int16 *TABLE = spec->table;
int besta, besty;
int trima, trimy, trimd;
int trimha, trimhb;
int morea, morey, mored;
int moreha, morehb;
int more, morem, lasta;
int aclip, bclip;
hgh = maxd;
low = mind;
dif = 0;
{
int span, wing;
span = (hgh - low) + 1;
vlen = work->vecmax / VectorEl;
wing = (vlen - span) / 2;
vmin = low - wing;
vmax = hgh + wing;
_V = ((int *) work->vector);
_M = _V + vlen;
_HA = _M + vlen;
_HB = _HA + vlen;
_NA = _HB + vlen;
_NB = _NA + vlen;
_T = ((BVEC *) (_NB + vlen));
V = _V - vmin;
M = _M - vmin;
HA = _HA - vmin;
HB = _HB - vmin;
NA = _NA - vmin;
NB = _NB - vmin;
T = _T - vmin;
cells = (Pebble *) (work->cells);
cmax = work->celmax;
avail = 0;
}
more = 1;
aclip = -INT32_MAX;
bclip = INT32_MAX;
besta = trima = morea = lasta = mida;
besty = trimy = morey = (mida - hgh) >> 1;
trimd = mored = 0;
trimha = moreha = 0;
trimhb = morehb = 1;
morem = -1;
{
int k;
char *a;
a = aseq + low;
for (k = low; k <= hgh; k++)
{
int y, c, d;
int ha, hb;
int na, nb;
Pebble *pb;
y = (mida - k) >> 1;
if (avail >= cmax - 1)
{
cmax = ((int) (avail * 1.2)) + 10000;
cells = (Pebble *) Realloc(cells, cmax * sizeof(Pebble), "Reallocating trace cells");
if (cells == NULL)
EXIT(1);
work->celmax = cmax;
work->cells = (void *) cells;
}
na = (((y + k) + (TRACE_SPACE - aoff) - 1) / TRACE_SPACE - 1) * TRACE_SPACE + aoff;
#ifdef SHOW_TPS
printf(" A %d: -1,%d,0,%d\n",avail,k,na+TRACE_SPACE); fflush(stdout);
#endif
pb = cells + avail;
pb->ptr = -1;
pb->diag = k;
pb->diff = 0;
pb->mark = y + k;
ha = avail++;
nb = ((y + (TRACE_SPACE - boff) - 1) / TRACE_SPACE - 1) * TRACE_SPACE + boff;
#ifdef SHOW_TPS
printf(" B %d: -1,%d,0,%d\n",avail,k,nb+TRACE_SPACE); fflush(stdout);
#endif
pb = cells + avail;
pb->ptr = -1;
pb->diag = k;
pb->diff = 0;
pb->mark = y;
hb = avail++;
while (1)
{
c = bseq[y];
if (c == 4)
{
more = 0;
if (bclip > k)
bclip = k;
break;
}
d = a[y];
if (c != d)
{
if (d == 4)
{
more = 0;
aclip = k;
}
break;
}
y -= 1;
}
c = (y << 1) + k;
while (y + k <= na)
{
if (avail >= cmax)
{
cmax = ((int) (avail * 1.2)) + 10000;
cells = (Pebble *) Realloc(cells, cmax * sizeof(Pebble), "Reallocating trace cells");
if (cells == NULL)
EXIT(1);
work->celmax = cmax;
work->cells = (void *) cells;
}
#ifdef SHOW_TPS
printf(" A %d: %d,%d,0,%d\n",avail,ha,k,na); fflush(stdout);
#endif
pb = cells + avail;
pb->ptr = ha;
pb->diag = k;
pb->diff = 0;
pb->mark = na;
ha = avail++;
na -= TRACE_SPACE;
}
while (y <= nb)
{
if (avail >= cmax)
{
cmax = ((int) (avail * 1.2)) + 10000;
cells = (Pebble *) Realloc(cells, cmax * sizeof(Pebble), "Reallocating trace cells");
if (cells == NULL)
EXIT(1);
work->celmax = cmax;
work->cells = (void *) cells;
}
#ifdef SHOW_TPS
printf(" B %d: %d,%d,0,%d\n",avail,hb,k,nb); fflush(stdout);
#endif
pb = cells + avail;
pb->ptr = hb;
pb->diag = k;
pb->diff = 0;
pb->mark = nb;
hb = avail++;
nb -= TRACE_SPACE;
}
if (c < besta)
{
besta = trima = lasta = c;
besty = trimy = y;
trimha = ha;
trimhb = hb;
}
V[k] = c;
T[k] = PATH_INT;
M[k] = PATH_LEN;
HA[k] = ha;
HB[k] = hb;
NA[k] = na;
NB[k] = nb;
a += 1;
}
}
if (more == 0)
{
if (bseq[besty] != 4 && aseq[besta - besty] != 4)
more = 1;
if (low <= aclip)
{
low = aclip + 1;
if (morem <= M[aclip])
{
morem = M[aclip];
morea = V[aclip];
morey = (morea - aclip) / 2;
moreha = HA[aclip];
morehb = HB[aclip];
}
}
if (hgh >= bclip)
{
hgh = bclip - 1;
if (morem <= M[bclip])
{
morem = M[bclip];
morea = V[bclip];
morey = (morea - bclip) / 2;
moreha = HA[bclip];
morehb = HB[bclip];
}
}
aclip = -INT32_MAX;
bclip = INT32_MAX;
}
#ifdef DEBUG_WAVE
printf("\nREVERSE WAVE:\n");
print_wave(V,M,low,hgh,besta);
#endif
while (more && lasta <= besta + TRIM_MLAG)
{
int k, n;
int ua, ub;
BVEC t;
int am, ac, ap;
char *a;
low -= 1;
hgh += 1;
if (low <= vmin || hgh >= vmax)
{
int span, wing;
int64 move, vd, md, had, hbd, nad, nbd, td;
span = (hgh - low) + 1;
if (.8 * vlen < span)
{
if (enlarge_vector(work, vlen * VectorEl))
EXIT(1);
move = ((void *) _V) - work->vector;
vlen = work->vecmax / VectorEl;
_V = (int *) work->vector;
_M = _V + vlen;
_HA = _M + vlen;
_HB = _HA + vlen;
_NA = _HB + vlen;
_NB = _NA + vlen;
_T = ((BVEC *) (_NB + vlen));
}
else
move = 0;
wing = (vlen - span) / 2;
vd = ((void *) (_V + wing)) - (((void *) (V + low)) - move);
md = ((void *) (_M + wing)) - (((void *) (M + low)) - move);
had = ((void *) (_HA + wing)) - (((void *) (HA + low)) - move);
hbd = ((void *) (_HB + wing)) - (((void *) (HB + low)) - move);
nad = ((void *) (_NA + wing)) - (((void *) (NA + low)) - move);
nbd = ((void *) (_NB + wing)) - (((void *) (NB + low)) - move);
td = ((void *) (_T + wing)) - (((void *) (T + low)) - move);
if (vd < 0)
memmove(_V + wing, ((void *) (V + low)) - move, span * sizeof(int));
if (md < 0)
memmove(_M + wing, ((void *) (M + low)) - move, span * sizeof(int));
if (had < 0)
memmove(_HA + wing, ((void *) (HA + low)) - move, span * sizeof(int));
if (hbd < 0)
memmove(_HB + wing, ((void *) (HB + low)) - move, span * sizeof(int));
if (nad < 0)
memmove(_NA + wing, ((void *) (NA + low)) - move, span * sizeof(int));
if (nbd < 0)
memmove(_NB + wing, ((void *) (NB + low)) - move, span * sizeof(int));
if (td < 0)
memmove(_T + wing, ((void *) (T + low)) - move, span * sizeof(BVEC));
if (td > 0)
memmove(_T + wing, ((void *) (T + low)) - move, span * sizeof(BVEC));
if (nbd > 0)
memmove(_NB + wing, ((void *) (NB + low)) - move, span * sizeof(int));
if (nad > 0)
memmove(_NA + wing, ((void *) (NA + low)) - move, span * sizeof(int));
if (hbd > 0)
memmove(_HB + wing, ((void *) (HB + low)) - move, span * sizeof(int));
if (had > 0)
memmove(_HA + wing, ((void *) (HA + low)) - move, span * sizeof(int));
if (md > 0)
memmove(_M + wing, ((void *) (M + low)) - move, span * sizeof(int));
if (vd > 0)
memmove(_V + wing, ((void *) (V + low)) - move, span * sizeof(int));
vmin = low - wing;
vmax = hgh + wing;
V = _V - vmin;
M = _M - vmin;
HA = _HA - vmin;
HB = _HB - vmin;
NA = _NA - vmin;
NB = _NB - vmin;
T = _T - vmin;
}
if (low >= minp)
{
NA[low] = NA[low + 1];
NB[low] = NB[low + 1];
V[low] = ap = INT32_MAX;
}
else
ap = V[++low];
if (hgh <= maxp)
{
NA[hgh] = NA[hgh - 1];
NB[hgh] = NB[hgh - 1];
V[hgh] = INT32_MAX;
}
else
hgh -= 1;
dif += 1;
ac = V[hgh + 1] = V[low - 1] = INT32_MAX;
a = aseq + low;
t = PATH_INT;
n = PATH_LEN;
ua = ub = -1;
for (k = low; k <= hgh; k++)
{
int y, m;
int ha, hb;
int c, d;
BVEC b;
Pebble *pb;
am = ac;
ac = ap;
ap = V[d = k + 1];
if (ac > ap)
if (ap > am)
{
c = am - 1;
m = n;
b = t;
ha = ua;
hb = ub;
}
else
{
c = ap - 1;
m = M[d];
b = T[d];
ha = HA[d];
hb = HB[d];
}
else if (ac > am)
{
c = am - 1;
m = n;
b = t;
ha = ua;
hb = ub;
}
else
{
c = ac - 2;
m = M[k];
b = T[k];
ha = HA[k];
hb = HB[k];
}
if ((b & PATH_TOP) != 0)
m -= 1;
b <<= 1;
y = (c - k) >> 1;
while (1)
{
c = bseq[y];
if (c == 4)
{
more = 0;
if (bclip > k)
bclip = k;
break;
}
d = a[y];
if (c != d)
{
if (d == 4)
{
more = 0;
aclip = k;
}
break;
}
y -= 1;
if ((b & PATH_TOP) == 0)
m += 1;
b = (b << 1) | 1;
}
c = (y << 1) + k;
while (y + k <= NA[k])
{
if (cells[ha].mark > NA[k])
{
if (avail >= cmax)
{
cmax = ((int) (avail * 1.2)) + 10000;
cells = (Pebble *) Realloc(cells, cmax * sizeof(Pebble), "Reallocating trace cells");
if (cells == NULL)
EXIT(1);
work->celmax = cmax;
work->cells = (void *) cells;
}
#ifdef SHOW_TPS
printf(" A %d: %d,%d,%d,%d\n",avail,ha,k,dif,NA[k]); fflush(stdout);
#endif
pb = cells + avail;
pb->ptr = ha;
pb->diag = k;
pb->diff = dif;
pb->mark = NA[k];
ha = avail++;
}
NA[k] -= TRACE_SPACE;
}
while (y <= NB[k])
{
if (cells[hb].mark > NB[k])
{
if (avail >= cmax)
{
cmax = ((int) (avail * 1.2)) + 10000;
cells = (Pebble *) Realloc(cells, cmax * sizeof(Pebble), "Reallocating trace cells");
if (cells == NULL)
EXIT(1);
work->celmax = cmax;
work->cells = (void *) cells;
}
#ifdef SHOW_TPS
printf(" B %d: %d,%d,%d,%d\n",avail,hb,k,dif,NB[k]); fflush(stdout);
#endif
pb = cells + avail;
pb->ptr = hb;
pb->diag = k;
pb->diff = dif;
pb->mark = NB[k];
hb = avail++;
}
NB[k] -= TRACE_SPACE;
}
if (c < besta)
{
besta = c;
besty = y;
if (m >= PATH_AVE)
{
lasta = c;
if (TABLE[b & TRIM_MASK] >= 0)
if (TABLE[(b >> TRIM_LEN) & TRIM_MASK] + SCORE[b & TRIM_MASK] >= 0)
{
trima = c;
trimy = y;
trimd = dif;
trimha = ha;
trimhb = hb;
}
}
}
t = T[k];
n = M[k];
ua = HA[k];
ub = HB[k];
V[k] = c;
T[k] = b;
M[k] = m;
HA[k] = ha;
HB[k] = hb;
a += 1;
}
if (more == 0)
{
if (bseq[besty] != 4 && aseq[besta - besty] != 4)
more = 1;
if (low <= aclip)
{
low = aclip + 1;
if (morem <= M[aclip])
{
morem = M[aclip];
morea = V[aclip];
morey = (morea - aclip) / 2;
mored = dif;
moreha = HA[aclip];
morehb = HB[aclip];
}
}
if (hgh >= bclip)
{
hgh = bclip - 1;
if (morem <= M[bclip])
{
morem = M[bclip];
morea = V[bclip];
morey = (morea - bclip) / 2;
mored = dif;
moreha = HA[bclip];
morehb = HB[bclip];
}
}
aclip = -INT32_MAX;
bclip = INT32_MAX;
}
n = besta + WAVE_LAG;
while (hgh >= low)
if (V[hgh] > n)
hgh -= 1;
else
{
while (V[low] > n)
low += 1;
break;
}
#ifdef WAVE_STATS
k = (hgh-low)+1;
if (k > MAX)
MAX = k;
TOT += k;
NWV += 1;
#endif
#ifdef DEBUG_WAVE
print_wave(V,M,low,hgh,besta);
#endif
}
{
uint16 *atrace = (uint16 *) apath->trace;
uint16 *btrace = (uint16 *) bpath->trace;
int atlen, btlen;
int trimx;
int a, b, k, h;
int d, e;
if (morem >= 0 && REACH)
{
trimx = morea - morey;
trimy = morey;
trimd = mored;
trimha = moreha;
trimhb = morehb;
}
else
trimx = trima - trimy;
atlen = btlen = 0;
a = -1;
for (h = trimha; h >= 0; h = b)
{
b = cells[h].ptr;
cells[h].ptr = a;
a = h;
}
h = a;
k = cells[h].diag;
b = cells[h].mark - k;
e = 0;
#ifdef SHOW_TRAIL
printf(" A path = (%5d,%5d)\n",b+k,b); fflush(stdout);
#endif
if ((b + k) % TRACE_SPACE != aoff)
{
h = cells[h].ptr;
if (h < 0)
{
a = trimy;
d = trimd;
}
else
{
k = cells[h].diag;
a = cells[h].mark - k;
d = cells[h].diff;
}
#ifdef SHOW_TRAIL
printf(" +%4d: (%5d,%5d): %3d / %3d\n",h,a+k,a,d-e,b-a); fflush(stdout);
#endif
if (apath->tlen == 0)
{
atrace[--atlen] = (uint16) (b - a);
atrace[--atlen] = (uint16) (d - e);
}
else
{
atrace[1] = (uint16) (atrace[1] + (b - a));
atrace[0] = (uint16) (atrace[0] + (d - e));
}
b = a;
e = d;
}
if (h >= 0)
{
for (h = cells[h].ptr; h >= 0; h = cells[h].ptr)
{
k = cells[h].diag;
a = cells[h].mark - k;
atrace[--atlen] = (uint16) (b - a);
d = cells[h].diff;
atrace[--atlen] = (uint16) (d - e);
#ifdef SHOW_TRAIL
printf(" %4d: (%5d,%5d): %3d / %3d\n",h,a+k,a,d-e,b-a); fflush(stdout);
#endif
b = a;
e = d;
}
if (b + k != trimx)
{
atrace[--atlen] = (uint16) (b - trimy);
atrace[--atlen] = (uint16) (trimd - e);
#ifdef SHOW_TRAIL
printf(" (%5d,%5d): %3d / %3d\n",trimx,trimy,trimd-e,b-trimy); fflush(stdout);
#endif
}
else if (b != trimy)
{
atrace[atlen + 1] = (uint16) (atrace[atlen + 1] + (b - trimy));
atrace[atlen] = (uint16) (atrace[atlen] + (trimd - e));
#ifdef SHOW_TRAIL
printf(" @ (%5d,%5d): %3d / %3d\n",trimx,trimy,trimd-e,b-trimy); fflush(stdout);
#endif
}
}
a = -1;
for (h = trimhb; h >= 0; h = b)
{
b = cells[h].ptr;
cells[h].ptr = a;
a = h;
}
h = a;
k = cells[h].diag;
b = cells[h].mark + k;
e = 0;
#ifdef SHOW_TRAIL
printf(" B path = (%5d,%5d)\n",b,b-k); fflush(stdout);
#endif
if ((b - k) % TRACE_SPACE != boff)
{
h = cells[h].ptr;
if (h < 0)
{
a = trimx;
d = trimd;
}
else
{
k = cells[h].diag;
a = cells[h].mark + k;
d = cells[h].diff;
}
#ifdef SHOW_TRAIL
printf(" +%4d: (%5d,%5d): %3d / %3d\n",h,a,a-k,d-e,b-a); fflush(stdout);
#endif
if (bpath->tlen == 0)
{
btrace[--btlen] = (uint16) (b - a);
btrace[--btlen] = (uint16) (b - a);
}
else
{
btrace[1] = (uint16) (btrace[1] + (b - a));
btrace[0] = (uint16) (btrace[0] + (d - e));
}
b = a;
e = d;
}
if (h >= 0)
{
for (h = cells[h].ptr; h >= 0; h = cells[h].ptr)
{
k = cells[h].diag;
a = cells[h].mark + k;
btrace[--btlen] = (uint16) (b - a);
d = cells[h].diff;
btrace[--btlen] = (uint16) (d - e);
#ifdef SHOW_TRAIL
printf(" %4d: (%5d,%5d): %3d / %3d\n",h,a,a-k,d-e,b-a); fflush(stdout);
#endif
b = a;
e = d;
}
if (b - k != trimy)
{
btrace[--btlen] = (uint16) (b - trimx);
btrace[--btlen] = (uint16) (trimd - e);
#ifdef SHOW_TRAIL
printf(" (%5d,%5d): %3d / %3d\n",trimx,trimy,trimd-e,b-trimx); fflush(stdout);
#endif
}
else if (b != trimx)
{
btrace[btlen + 1] = (uint16) (btrace[btlen + 1] + (b - trimx));
btrace[btlen] = (uint16) (btrace[btlen] + (trimd - e));
#ifdef SHOW_TRAIL
printf(" @ (%5d,%5d): %3d / %3d\n",trimx,trimy,trimd-e,b-trimx); fflush(stdout);
#endif
}
}
apath->abpos = trimx;
apath->bbpos = trimy;
apath->diffs = apath->diffs + trimd;
apath->tlen = apath->tlen - atlen;
apath->trace = atrace + atlen;
bpath->tlen = bpath->tlen - btlen;
bpath->trace = btrace + btlen;
}
return (0);
}
/* Find the longest local alignment between aseq and bseq through (xcnt,ycnt)
See associated .h file for the precise definition of the interface.
*/
Path *Local_Alignment(Alignment *align, Work_Data *ework, Align_Spec *espec, int low, int hgh, int anti, int lbord, int hbord)
{
_Work_Data *work = (_Work_Data *) ework;
_Align_Spec *spec = (_Align_Spec *) espec;
Path *apath, *bpath;
int aoff, boff;
int minp, maxp;
int selfie;
{
int alen, blen;
int maxtp, wsize;
alen = align->alen;
blen = align->blen;
if (hgh - low >= 7500)
wsize = VectorEl * (hgh - low + 1);
else
wsize = VectorEl * 10000;
if (wsize >= work->vecmax)
if (enlarge_vector(work, wsize))
EXIT(NULL);
if (alen < blen)
maxtp = 2 * (blen / spec->trace_space + 2);
else
maxtp = 2 * (alen / spec->trace_space + 2);
wsize = 4 * maxtp * sizeof(uint16) + sizeof(Path);
if (wsize > work->pntmax)
if (enlarge_points(work, wsize))
EXIT(NULL);
apath = align->path;
bpath = (Path *) work->points;
apath->trace = ((uint16 *) (bpath + 1)) + maxtp;
bpath->trace = ((uint16 *) apath->trace) + 2 * maxtp;
}
#ifdef DEBUG_PASSES
printf("\n");
#endif
selfie = (align->aseq == align->bseq);
if (lbord < 0)
{
if (selfie && low >= 0)
minp = 1;
else
minp = -INT32_MAX;
}
else
minp = low - lbord;
if (hbord < 0)
{
if (selfie && hgh <= 0)
maxp = -1;
else
maxp = INT32_MAX;
}
else
maxp = hgh + hbord;
if (ACOMP(align->flags))
{
aoff = align->alen % spec->trace_space;
boff = 0;
}
else if (COMP(align->flags))
{
aoff = 0;
boff = align->blen % spec->trace_space;
}
else
{
aoff = 0;
boff = 0;
}
if (forward_wave(work, spec, align, bpath, &low, hgh, anti, minp, maxp, aoff, boff))
EXIT(NULL);
#ifdef DEBUG_PASSES
printf("F1 (%d,%d) ~ %d => (%d,%d) %d\n",
(2*anti+(low+hgh))/4,(anti-(low+hgh))/4,hgh-low,
apath->aepos,apath->bepos,apath->diffs);
#endif
if (reverse_wave(work, spec, align, bpath, low, low, anti, minp, maxp, aoff, boff))
EXIT(NULL);
#ifdef DEBUG_PASSES
printf("R1 (%d,%d) => (%d,%d) %d\n",
(anti+low)/2,(anti-low)/2,apath->abpos,apath->bbpos,apath->diffs);
#endif
bpath->diffs = apath->diffs;
if (ACOMP(align->flags))
{
uint16 *trace = (uint16 *) apath->trace;
uint16 p;
int i, j;
bpath->aepos = apath->bepos;
bpath->bepos = apath->aepos;
bpath->abpos = apath->bbpos;
bpath->bbpos = apath->abpos;
apath->abpos = align->alen - bpath->bepos;
apath->bbpos = align->blen - bpath->aepos;
apath->aepos = align->alen - bpath->bbpos;
apath->bepos = align->blen - bpath->abpos;
i = apath->tlen - 2;
j = 0;
while (j < i)
{
p = trace[i];
trace[i] = trace[j];
trace[j] = p;
p = trace[i + 1];
trace[i + 1] = trace[j + 1];
trace[j + 1] = p;
i -= 2;
j += 2;
}
}
else if (COMP(align->flags))
{
uint16 *trace = (uint16 *) bpath->trace;
uint16 p;
int i, j;
bpath->abpos = align->blen - apath->bepos;
bpath->bbpos = align->alen - apath->aepos;
bpath->aepos = align->blen - apath->bbpos;
bpath->bepos = align->alen - apath->abpos;
i = bpath->tlen - 2;
j = 0;
while (j < i)
{
p = trace[i];
trace[i] = trace[j];
trace[j] = p;
p = trace[i + 1];
trace[i + 1] = trace[j + 1];
trace[j + 1] = p;
i -= 2;
j += 2;
}
}
else
{
bpath->aepos = apath->bepos;
bpath->bepos = apath->aepos;
bpath->abpos = apath->bbpos;
bpath->bbpos = apath->abpos;
}
#ifdef DEBUG_POINTS
{ uint16 *trace = (uint16 *) apath->trace;
int a, h;
printf("\nA-path (%d,%d)->(%d,%d)",apath->abpos,apath->bbpos,apath->aepos,apath->bepos);
printf(" %c\n",((COMP(align->flags) || ACOMP(align->flags)) ? 'c' : 'n'));
a = apath->bbpos;
for (h = 1; h < apath->tlen; h += 2)
{ int dif = trace[h-1];
int del = trace[h];
a += del;
printf(" %d / %d (%d)\n",dif,del,a);
}
}
{ uint16 *trace = (uint16 *) bpath->trace;
int a, h;
printf("\nB-path (%d,%d)->(%d,%d)",bpath->abpos,bpath->bbpos,bpath->aepos,bpath->bepos);
printf(" %c [%d,%d]\n",((COMP(align->flags) || ACOMP(align->flags)) ? 'c' : 'n'),
align->blen,align->alen);
a = bpath->bbpos;
for (h = 1; h < bpath->tlen; h += 2)
{ int dif = trace[h-1];
int del = trace[h];
a += del;
printf(" %d / %d (%d)\n",dif,del,a);
}
}
#endif
return (bpath);
}
/****************************************************************************************\
* *
* EXTENSION VERSION OF LOCAL ALIGNMENT *
* *
\****************************************************************************************/
static int VectorEn = 4 * sizeof(int) + sizeof(BVEC);
static int forward_extend(_Work_Data *work, _Align_Spec *spec, Alignment *align, int midd, int mida, int minp, int maxp)
{
char *aseq = align->aseq;
char *bseq = align->bseq;
Path *apath = align->path;
int hgh, low, dif;
int vlen, vmin, vmax;
int *V, *M;
int *_V, *_M;
BVEC *T;
BVEC *_T;
int *HA, *NA;
int *_HA, *_NA;
Pebble *cells;
int avail, cmax;
int TRACE_SPACE = spec->trace_space;
int PATH_AVE = spec->ave_path;
int16 *SCORE = spec->score;
int16 *TABLE = spec->table;
int besta, besty;
int trima, trimy, trimd;
int trimha;
int morea, morey, mored;
int moreha;
int more, morem, lasta;
int aclip, bclip;
hgh = midd;
low = midd;
dif = 0;
{
int span, wing;
span = (hgh - low) + 1;
vlen = work->vecmax / VectorEn;
wing = (vlen - span) / 2;
vmin = low - wing;
vmax = hgh + wing;
_V = ((int *) work->vector);
_M = _V + vlen;
_HA = _M + vlen;
_NA = _HA + vlen;
_T = ((BVEC *) (_NA + vlen));
V = _V - vmin;
M = _M - vmin;
HA = _HA - vmin;
NA = _NA - vmin;
T = _T - vmin;
cells = (Pebble *) (work->cells);
cmax = work->celmax;
avail = 0;
}
/* Compute 0-wave starting from mid-line */
more = 1;
aclip = INT32_MAX;
bclip = -INT32_MAX;
besta = trima = morea = lasta = mida;
besty = trimy = morey = (mida - hgh) >> 1;
trimd = mored = 0;
trimha = moreha = 0;
morem = -1;
{
int k;
char *a;
a = aseq + hgh;
for (k = hgh; k >= low; k--)
{
int y, c, d;
int ha, na;
Pebble *pb;
y = (mida - k) >> 1;
if (avail >= cmax - 1)
{
cmax = ((int) (avail * 1.2)) + 10000;
cells = (Pebble *) Realloc(cells, cmax * sizeof(Pebble), "Reallocating trace cells");
if (cells == NULL)
EXIT(1);
work->celmax = cmax;
work->cells = (void *) cells;
}
na = ((y + k) / TRACE_SPACE) * TRACE_SPACE;
#ifdef SHOW_TPS
printf(" A %d: %d,%d,0,%d\n",avail,-1,k,na); fflush(stdout);
#endif
pb = cells + avail;
pb->ptr = -1;
pb->diag = k;
pb->diff = 0;
pb->mark = na;
ha = avail++;
na += TRACE_SPACE;
while (1)
{
c = bseq[y];
if (c == 4)
{
more = 0;
if (bclip < k)
bclip = k;
break;
}
d = a[y];
if (c != d)
{
if (d == 4)
{
more = 0;
aclip = k;
}
break;
}
y += 1;
}
c = (y << 1) + k;
while (y + k >= na)
{
if (avail >= cmax)
{
cmax = ((int) (avail * 1.2)) + 10000;
cells = (Pebble *) Realloc(cells, cmax * sizeof(Pebble), "Reallocating trace cells");
if (cells == NULL)
EXIT(1);
work->celmax = cmax;
work->cells = (void *) cells;
}
#ifdef SHOW_TPS
printf(" A %d: %d,%d,0,%d\n",avail,ha,k,na); fflush(stdout);
#endif
pb = cells + avail;
pb->ptr = ha;
pb->diag = k;
pb->diff = 0;
pb->mark = na;
ha = avail++;
na += TRACE_SPACE;
}
if (c > besta)
{
besta = trima = lasta = c;
besty = trimy = y;
trimha = ha;
}
V[k] = c;
T[k] = PATH_INT;
M[k] = PATH_LEN;
HA[k] = ha;
NA[k] = na;
a -= 1;
}
}
if (more == 0)
{
if (bseq[besty] != 4 && aseq[besta - besty] != 4)
more = 1;
if (hgh >= aclip)
{
hgh = aclip - 1;
if (morem <= M[aclip])
{
morem = M[aclip];
morea = V[aclip];
morey = (morea - aclip) / 2;
moreha = HA[aclip];
}
}
if (low <= bclip)
{
low = bclip + 1;
if (morem <= M[bclip])
{
morem = M[bclip];
morea = V[bclip];
morey = (morea - bclip) / 2;
moreha = HA[bclip];
}
}
aclip = INT32_MAX;
bclip = -INT32_MAX;
}
#ifdef DEBUG_WAVE
printf("\nFORWARD WAVE:\n");
print_wave(V,M,low,hgh,besta);
#endif
/* Compute successive waves until no furthest reaching points remain */
while (more && lasta >= besta - TRIM_MLAG)
{
int k, n;
int ua;
BVEC t;
int am, ac, ap;
char *a;
if (low <= vmin || hgh >= vmax)
{
int span, wing;
int64 move;
int64 vd, md, had, nad, td;
span = (hgh - low) + 1;
if (.8 * vlen < span)
{
if (enlarge_vector(work, vlen * VectorEn))
EXIT(1);
move = ((void *) _V) - work->vector;
vlen = work->vecmax / VectorEn;
_V = (int *) work->vector;
_M = _V + vlen;
_HA = _M + vlen;
_NA = _HA + vlen;
_T = ((BVEC *) (_NA + vlen));
}
else
move = 0;
wing = (vlen - span) / 2;
vd = ((void *) (_V + wing)) - (((void *) (V + low)) - move);
md = ((void *) (_M + wing)) - (((void *) (M + low)) - move);
had = ((void *) (_HA + wing)) - (((void *) (HA + low)) - move);
nad = ((void *) (_NA + wing)) - (((void *) (NA + low)) - move);
td = ((void *) (_T + wing)) - (((void *) (T + low)) - move);
if (vd < 0)
memmove(_V + wing, ((void *) (V + low)) - move, span * sizeof(int));
if (md < 0)
memmove(_M + wing, ((void *) (M + low)) - move, span * sizeof(int));
if (had < 0)
memmove(_HA + wing, ((void *) (HA + low)) - move, span * sizeof(int));
if (nad < 0)
memmove(_NA + wing, ((void *) (NA + low)) - move, span * sizeof(int));
if (td < 0)
memmove(_T + wing, ((void *) (T + low)) - move, span * sizeof(BVEC));
if (td > 0)
memmove(_T + wing, ((void *) (T + low)) - move, span * sizeof(BVEC));
if (nad > 0)
memmove(_NA + wing, ((void *) (NA + low)) - move, span * sizeof(int));
if (had > 0)
memmove(_HA + wing, ((void *) (HA + low)) - move, span * sizeof(int));
if (md > 0)
memmove(_M + wing, ((void *) (M + low)) - move, span * sizeof(int));
if (vd > 0)
memmove(_V + wing, ((void *) (V + low)) - move, span * sizeof(int));
vmin = low - wing;
vmax = hgh + wing;
V = _V - vmin;
M = _M - vmin;
HA = _HA - vmin;
NA = _NA - vmin;
T = _T - vmin;
}
if (low > minp)
{
low -= 1;
NA[low] = NA[low + 1];
V[low] = -1;
}
if (hgh < maxp)
{
hgh += 1;
NA[hgh] = NA[hgh - 1];
V[hgh] = am = -1;
}
else
am = V[hgh];
dif += 1;
ac = V[hgh + 1] = V[low - 1] = -1;
a = aseq + hgh;
t = PATH_INT;
n = PATH_LEN;
ua = -1;
for (k = hgh; k >= low; k--)
{
int y, m;
int ha;
int c, d;
BVEC b;
Pebble *pb;
ap = ac;
ac = am;
am = V[d = k - 1];
if (ac < am)
if (am < ap)
{
c = ap + 1;
m = n;
b = t;
ha = ua;
}
else
{
c = am + 1;
m = M[d];
b = T[d];
ha = HA[d];
}
else if (ac < ap)
{
c = ap + 1;
m = n;
b = t;
ha = ua;
}
else
{
c = ac + 2;
m = M[k];
b = T[k];
ha = HA[k];
}
if ((b & PATH_TOP) != 0)
m -= 1;
b <<= 1;
y = (c - k) >> 1;
while (1)
{
c = bseq[y];
if (c == 4)
{
more = 0;
if (bclip < k)
bclip = k;
break;
}
d = a[y];
if (c != d)
{
if (d == 4)
{
more = 0;
aclip = k;
}
break;
}
y += 1;
if ((b & PATH_TOP) == 0)
m += 1;
b = (b << 1) | 1;
}
c = (y << 1) + k;
while (y + k >= NA[k])
{
if (cells[ha].mark < NA[k])
{
if (avail >= cmax)
{
cmax = ((int) (avail * 1.2)) + 10000;
cells = (Pebble *) Realloc(cells, cmax * sizeof(Pebble), "Reallocating trace cells");
if (cells == NULL)
EXIT(1);
work->celmax = cmax;
work->cells = (void *) cells;
}
#ifdef SHOW_TPS
printf(" A %d: %d,%d,%d,%d\n",avail,ha,k,dif,NA[k]); fflush(stdout);
#endif
pb = cells + avail;
pb->ptr = ha;
pb->diag = k;
pb->diff = dif;
pb->mark = NA[k];
ha = avail++;
}
NA[k] += TRACE_SPACE;
}
if (c > besta)
{
besta = c;
besty = y;
if (m >= PATH_AVE)
{
lasta = c;
if (TABLE[b & TRIM_MASK] >= 0)
if (TABLE[(b >> TRIM_LEN) & TRIM_MASK] + SCORE[b & TRIM_MASK] >= 0)
{
trima = c;
trimy = y;
trimd = dif;
trimha = ha;
}
}
}
t = T[k];
n = M[k];
ua = HA[k];
V[k] = c;
T[k] = b;
M[k] = m;
HA[k] = ha;
a -= 1;
}
if (more == 0)
{
if (bseq[besty] != 4 && aseq[besta - besty] != 4)
more = 1;
if (hgh >= aclip)
{
hgh = aclip - 1;
if (morem <= M[aclip])
{
morem = M[aclip];
morea = V[aclip];
morey = (morea - aclip) / 2;
mored = dif;
moreha = HA[aclip];
}
}
if (low <= bclip)
{
low = bclip + 1;
if (morem <= M[bclip])
{
morem = M[bclip];
morea = V[bclip];
morey = (morea - bclip) / 2;
mored = dif;
moreha = HA[bclip];
}
}
aclip = INT32_MAX;
bclip = -INT32_MAX;
}
n = besta - WAVE_LAG;
while (hgh >= low)
if (V[hgh] < n)
hgh -= 1;
else
{
while (V[low] < n)
low += 1;
break;
}
#ifdef WAVE_STATS
k = (hgh-low)+1;
if (k > MAX)
MAX = k;
TOT += k;
NWV += 1;
#endif
#ifdef DEBUG_WAVE
print_wave(V,M,low,hgh,besta);
#endif
}
{
uint16 *atrace = (uint16 *) apath->trace;
int atlen;
int trimx;
int a, b, k, h;
int d, e;
if (morem >= 0)
{
trimx = morea - morey;
trimy = morey;
trimd = mored;
trimha = moreha;
}
else
trimx = trima - trimy;
atlen = 0;
a = -1;
for (h = trimha; h >= 0; h = b)
{
b = cells[h].ptr;
cells[h].ptr = a;
a = h;
}
h = a;
k = cells[h].diag;
b = (mida - k) / 2;
e = 0;
#ifdef SHOW_TRAIL
printf(" A path = (%5d,%5d)\n",(mida+k)/2,b); fflush(stdout);
#endif
for (h = cells[h].ptr; h >= 0; h = cells[h].ptr)
{
k = cells[h].diag;
a = cells[h].mark - k;
d = cells[h].diff;
atrace[atlen++] = (uint16) (d - e);
atrace[atlen++] = (uint16) (a - b);
#ifdef SHOW_TRAIL
printf(" %4d: (%5d,%5d): %3d / %3d\n",h,a+k,a,d-e,a-b); fflush(stdout);
#endif
b = a;
e = d;
}
if (b + k != trimx)
{
atrace[atlen++] = (uint16) (trimd - e);
atrace[atlen++] = (uint16) (trimy - b);
#ifdef SHOW_TRAIL
printf(" (%5d,%5d): %3d / %3d\n",trimx,trimy,trimd-e,trimy-b); fflush(stdout);
#endif
}
else if (b != trimy)
{
atrace[atlen - 1] = (uint16) (atrace[atlen - 1] + (trimy - b));
atrace[atlen - 2] = (uint16) (atrace[atlen - 2] + (trimd - e));
#ifdef SHOW_TRAIL
printf(" @ (%5d,%5d): %3d / %3d\n",trimx,trimy,trimd-e,trimy-b); fflush(stdout);
#endif
}
apath->aepos = trimx;
apath->bepos = trimy;
apath->diffs = trimd;
apath->tlen = atlen;
}
return (0);
}
static int reverse_extend(_Work_Data *work, _Align_Spec *spec, Alignment *align, int midd, int mida, int minp, int maxp)
{
char *aseq = align->aseq - 1;
char *bseq = align->bseq - 1;
Path *apath = align->path;
int hgh, low, dif;
int vlen, vmin, vmax;
int *V, *M;
int *_V, *_M;
BVEC *T;
BVEC *_T;
int *HA, *NA;
int *_HA, *_NA;
Pebble *cells;
int avail, cmax;
int TRACE_SPACE = spec->trace_space;
int PATH_AVE = spec->ave_path;
int16 *SCORE = spec->score;
int16 *TABLE = spec->table;
int besta, besty;
int trima, trimy, trimd;
int trimha;
int morea, morey, mored;
int moreha;
int more, morem, lasta;
int aclip, bclip;
hgh = midd;
low = midd;
dif = 0;
{
int span, wing;
span = (hgh - low) + 1;
vlen = work->vecmax / VectorEn;
wing = (vlen - span) / 2;
vmin = low - wing;
vmax = hgh + wing;
_V = ((int *) work->vector);
_M = _V + vlen;
_HA = _M + vlen;
_NA = _HA + vlen;
_T = ((BVEC *) (_NA + vlen));
V = _V - vmin;
M = _M - vmin;
HA = _HA - vmin;
NA = _NA - vmin;
T = _T - vmin;
cells = (Pebble *) (work->cells);
cmax = work->celmax;
avail = 0;
}
more = 1;
aclip = -INT32_MAX;
bclip = INT32_MAX;
besta = trima = morea = lasta = mida;
besty = trimy = morey = (mida - hgh) >> 1;
trimd = mored = 0;
trimha = moreha = 0;
morem = -1;
{
int k;
char *a;
a = aseq + low;
for (k = low; k <= hgh; k++)
{
int y, c, d;
int ha, na;
Pebble *pb;
y = (mida - k) >> 1;
if (avail >= cmax - 1)
{
cmax = ((int) (avail * 1.2)) + 10000;
cells = (Pebble *) Realloc(cells, cmax * sizeof(Pebble), "Reallocating trace cells");
if (cells == NULL)
EXIT(1);
work->celmax = cmax;
work->cells = (void *) cells;
}
na = ((y + k + TRACE_SPACE - 1) / TRACE_SPACE - 1) * TRACE_SPACE;
#ifdef SHOW_TPS
printf(" A %d: -1,%d,0,%d\n",avail,k,na+TRACE_SPACE); fflush(stdout);
#endif
pb = cells + avail;
pb->ptr = -1;
pb->diag = k;
pb->diff = 0;
pb->mark = y + k;
ha = avail++;
while (1)
{
c = bseq[y];
if (c == 4)
{
more = 0;
if (bclip > k)
bclip = k;
break;
}
d = a[y];
if (c != d)
{
if (d == 4)
{
more = 0;
aclip = k;
}
break;
}
y -= 1;
}
c = (y << 1) + k;
while (y + k <= na)
{
if (avail >= cmax)
{
cmax = ((int) (avail * 1.2)) + 10000;
cells = (Pebble *) Realloc(cells, cmax * sizeof(Pebble), "Reallocating trace cells");
if (cells == NULL)
EXIT(1);
work->celmax = cmax;
work->cells = (void *) cells;
}
#ifdef SHOW_TPS
printf(" A %d: %d,%d,0,%d\n",avail,ha,k,na); fflush(stdout);
#endif
pb = cells + avail;
pb->ptr = ha;
pb->diag = k;
pb->diff = 0;
pb->mark = na;
ha = avail++;
na -= TRACE_SPACE;
}
if (c < besta)
{
besta = trima = lasta = c;
besty = trimy = y;
trimha = ha;
}
V[k] = c;
T[k] = PATH_INT;
M[k] = PATH_LEN;
HA[k] = ha;
NA[k] = na;
a += 1;
}
}
if (more == 0)
{
if (bseq[besty] != 4 && aseq[besta - besty] != 4)
more = 1;
if (low <= aclip)
{
low = aclip + 1;
if (morem <= M[aclip])
{
morem = M[aclip];
morea = V[aclip];
morey = (morea - aclip) / 2;
moreha = HA[aclip];
}
}
if (hgh >= bclip)
{
hgh = bclip - 1;
if (morem <= M[bclip])
{
morem = M[bclip];
morea = V[bclip];
morey = (morea - bclip) / 2;
moreha = HA[bclip];
}
}
aclip = -INT32_MAX;
bclip = INT32_MAX;
}
#ifdef DEBUG_WAVE
printf("\nREVERSE WAVE:\n");
print_wave(V,M,low,hgh,besta);
#endif
while (more && lasta <= besta + TRIM_MLAG)
{
int k, n;
int ua;
BVEC t;
int am, ac, ap;
char *a;
if (low <= vmin || hgh >= vmax)
{
int span, wing;
int64 move, vd, md, had, nad, td;
span = (hgh - low) + 1;
if (.8 * vlen < span)
{
if (enlarge_vector(work, vlen * VectorEn))
EXIT(1);
move = ((void *) _V) - work->vector;
vlen = work->vecmax / VectorEn;
_V = (int *) work->vector;
_M = _V + vlen;
_HA = _M + vlen;
_NA = _HA + vlen;
_T = ((BVEC *) (_NA + vlen));
}
else
move = 0;
wing = (vlen - span) / 2;
vd = ((void *) (_V + wing)) - (((void *) (V + low)) - move);
md = ((void *) (_M + wing)) - (((void *) (M + low)) - move);
had = ((void *) (_HA + wing)) - (((void *) (HA + low)) - move);
nad = ((void *) (_NA + wing)) - (((void *) (NA + low)) - move);
td = ((void *) (_T + wing)) - (((void *) (T + low)) - move);
if (vd < 0)
memmove(_V + wing, ((void *) (V + low)) - move, span * sizeof(int));
if (md < 0)
memmove(_M + wing, ((void *) (M + low)) - move, span * sizeof(int));
if (had < 0)
memmove(_HA + wing, ((void *) (HA + low)) - move, span * sizeof(int));
if (nad < 0)
memmove(_NA + wing, ((void *) (NA + low)) - move, span * sizeof(int));
if (td < 0)
memmove(_T + wing, ((void *) (T + low)) - move, span * sizeof(BVEC));
if (td > 0)
memmove(_T + wing, ((void *) (T + low)) - move, span * sizeof(BVEC));
if (nad > 0)
memmove(_NA + wing, ((void *) (NA + low)) - move, span * sizeof(int));
if (had > 0)
memmove(_HA + wing, ((void *) (HA + low)) - move, span * sizeof(int));
if (md > 0)
memmove(_M + wing, ((void *) (M + low)) - move, span * sizeof(int));
if (vd > 0)
memmove(_V + wing, ((void *) (V + low)) - move, span * sizeof(int));
vmin = low - wing;
vmax = hgh + wing;
V = _V - vmin;
M = _M - vmin;
HA = _HA - vmin;
NA = _NA - vmin;
T = _T - vmin;
}
if (low > minp)
{
low -= 1;
NA[low] = NA[low + 1];
V[low] = ap = INT32_MAX;
}
else
ap = V[low];
if (hgh < maxp)
{
hgh += 1;
NA[hgh] = NA[hgh - 1];
V[hgh] = INT32_MAX;
}
dif += 1;
ac = V[hgh + 1] = V[low - 1] = INT32_MAX;
a = aseq + low;
t = PATH_INT;
n = PATH_LEN;
ua = -1;
for (k = low; k <= hgh; k++)
{
int y, m;
int ha;
int c, d;
BVEC b;
Pebble *pb;
am = ac;
ac = ap;
ap = V[d = k + 1];
if (ac > ap)
if (ap > am)
{
c = am - 1;
m = n;
b = t;
ha = ua;
}
else
{
c = ap - 1;
m = M[d];
b = T[d];
ha = HA[d];
}
else if (ac > am)
{
c = am - 1;
m = n;
b = t;
ha = ua;
}
else
{
c = ac - 2;
m = M[k];
b = T[k];
ha = HA[k];
}
if ((b & PATH_TOP) != 0)
m -= 1;
b <<= 1;
y = (c - k) >> 1;
while (1)
{
c = bseq[y];
if (c == 4)
{
more = 0;
if (bclip > k)
bclip = k;
break;
}
d = a[y];
if (c != d)
{
if (d == 4)
{
more = 0;
aclip = k;
}
break;
}
y -= 1;
if ((b & PATH_TOP) == 0)
m += 1;
b = (b << 1) | 1;
}
c = (y << 1) + k;
while (y + k <= NA[k])
{
if (cells[ha].mark > NA[k])
{
if (avail >= cmax)
{
cmax = ((int) (avail * 1.2)) + 10000;
cells = (Pebble *) Realloc(cells, cmax * sizeof(Pebble), "Reallocating trace cells");
if (cells == NULL)
EXIT(1);
work->celmax = cmax;
work->cells = (void *) cells;
}
#ifdef SHOW_TPS
printf(" A %d: %d,%d,%d,%d\n",avail,ha,k,dif,NA[k]); fflush(stdout);
#endif
pb = cells + avail;
pb->ptr = ha;
pb->diag = k;
pb->diff = dif;
pb->mark = NA[k];
ha = avail++;
}
NA[k] -= TRACE_SPACE;
}
if (c < besta)
{
besta = c;
besty = y;
if (m >= PATH_AVE)
{
lasta = c;
if (TABLE[b & TRIM_MASK] >= 0)
if (TABLE[(b >> TRIM_LEN) & TRIM_MASK] + SCORE[b & TRIM_MASK] >= 0)
{
trima = c;
trimy = y;
trimd = dif;
trimha = ha;
}
}
}
t = T[k];
n = M[k];
ua = HA[k];
V[k] = c;
T[k] = b;
M[k] = m;
HA[k] = ha;
a += 1;
}
if (more == 0)
{
if (bseq[besty] != 4 && aseq[besta - besty] != 4)
more = 1;
if (low <= aclip)
{
low = aclip + 1;
if (morem <= M[aclip])
{
morem = M[aclip];
morea = V[aclip];
morey = (morea - aclip) / 2;
mored = dif;
moreha = HA[aclip];
}
}
if (hgh >= bclip)
{
hgh = bclip - 1;
if (morem <= M[bclip])
{
morem = M[bclip];
morea = V[bclip];
morey = (morea - bclip) / 2;
mored = dif;
moreha = HA[bclip];
}
}
aclip = -INT32_MAX;
bclip = INT32_MAX;
}
n = besta + WAVE_LAG;
while (hgh >= low)
if (V[hgh] > n)
hgh -= 1;
else
{
while (V[low] > n)
low += 1;
break;
}
#ifdef WAVE_STATS
k = (hgh-low)+1;
if (k > MAX)
MAX = k;
TOT += k;
NWV += 1;
#endif
#ifdef DEBUG_WAVE
print_wave(V,M,low,hgh,besta);
#endif
}
{
uint16 *atrace = (uint16 *) apath->trace;
int atlen;
int trimx;
int a, b, k, h;
int d, e;
if (morem >= 0)
{
trimx = morea - morey;
trimy = morey;
trimd = mored;
trimha = moreha;
}
else
trimx = trima - trimy;
atlen = 0;
a = -1;
for (h = trimha; h >= 0; h = b)
{
b = cells[h].ptr;
cells[h].ptr = a;
a = h;
}
h = a;
k = cells[h].diag;
b = cells[h].mark - k;
e = 0;
#ifdef SHOW_TRAIL
printf(" A path = (%5d,%5d)\n",b+k,b); fflush(stdout);
#endif
if ((b + k) % TRACE_SPACE != 0)
{
h = cells[h].ptr;
if (h < 0)
{
a = trimy;
d = trimd;
}
else
{
k = cells[h].diag;
a = cells[h].mark - k;
d = cells[h].diff;
}
#ifdef SHOW_TRAIL
printf(" +%4d: (%5d,%5d): %3d / %3d\n",h,a+k,a,d-e,b-a); fflush(stdout);
#endif
atrace[--atlen] = (uint16) (b - a);
atrace[--atlen] = (uint16) (d - e);
b = a;
e = d;
}
if (h >= 0)
{
for (h = cells[h].ptr; h >= 0; h = cells[h].ptr)
{
k = cells[h].diag;
a = cells[h].mark - k;
atrace[--atlen] = (uint16) (b - a);
d = cells[h].diff;
atrace[--atlen] = (uint16) (d - e);
#ifdef SHOW_TRAIL
printf(" %4d: (%5d,%5d): %3d / %3d\n",h,a+k,a,d-e,b-a); fflush(stdout);
#endif
b = a;
e = d;
}
if (b + k != trimx)
{
atrace[--atlen] = (uint16) (b - trimy);
atrace[--atlen] = (uint16) (trimd - e);
#ifdef SHOW_TRAIL
printf(" (%5d,%5d): %3d / %3d\n",trimx,trimy,trimd-e,b-trimy); fflush(stdout);
#endif
}
else if (b != trimy)
{
atrace[atlen + 1] = (uint16) (atrace[atlen + 1] + (b - trimy));
atrace[atlen] = (uint16) (atrace[atlen] + (trimd - e));
#ifdef SHOW_TRAIL
printf(" @ (%5d,%5d): %3d / %3d\n",trimx,trimy,trimd-e,b-trimy); fflush(stdout);
#endif
}
}
apath->abpos = trimx;
apath->bbpos = trimy;
apath->diffs = trimd;
apath->tlen = -atlen;
apath->trace = atrace + atlen;
}
return (0);
}
/* Find the longest local alignment between aseq and bseq through (xcnt,ycnt)
See associated .h file for the precise definition of the interface.
*/
int Find_Extension(Alignment *align, Work_Data *ework, Align_Spec *espec, int diag, int anti, int lbord, int hbord, int prefix)
{
_Work_Data *work = (_Work_Data *) ework;
_Align_Spec *spec = (_Align_Spec *) espec;
Path *apath;
int minp, maxp;
{
int alen, blen;
int maxtp, wsize;
alen = align->alen;
blen = align->blen;
wsize = VectorEn * 10000;
if (wsize >= work->vecmax)
if (enlarge_vector(work, wsize))
EXIT(1);
if (alen < blen)
maxtp = 2 * (blen / spec->trace_space + 2);
else
maxtp = 2 * (alen / spec->trace_space + 2);
wsize = 2 * maxtp * sizeof(uint16);
if (wsize > work->pntmax)
if (enlarge_points(work, wsize))
EXIT(1);
apath = align->path;
apath->trace = ((uint16 *) work->points) + maxtp;
}
#ifdef DEBUG_PASSES
printf("\n");
#endif
if (lbord < 0)
minp = -INT32_MAX;
else
minp = diag - lbord;
if (hbord < 0)
maxp = INT32_MAX;
else
maxp = diag + hbord;
if (prefix)
{
if (reverse_extend(work, spec, align, diag, anti, minp, maxp))
EXIT(1);
apath->aepos = (anti + diag) / 2;
apath->bepos = (anti - diag) / 2;
#ifdef DEBUG_PASSES
printf("E1 (%d,%d) => (%d,%d) %d\n",
(anti+diag)/2,(anti-diag)/2,apath->abpos,apath->bbpos,apath->diffs);
#endif
}
else
{
if (forward_extend(work, spec, align, diag, anti, minp, maxp))
EXIT(1);
apath->abpos = (anti + diag) / 2;
apath->bbpos = (anti - diag) / 2;
#ifdef DEBUG_PASSES
printf("F1 (%d,%d) => (%d,%d) %d\n",
(anti+diag)/2,(anti-diag)/2,apath->aepos,apath->bepos,apath->diffs);
#endif
}
#ifdef DEBUG_POINTS
{ uint16 *trace = (uint16 *) apath->trace;
int a, h;
printf("\nA-path (%d,%d)->(%d,%d)",apath->abpos,apath->bbpos,apath->aepos,apath->bepos);
printf(" %c\n",(COMP(align->flags) ? 'c' : 'n'));
a = apath->bbpos;
for (h = 1; h < apath->tlen; h += 2)
{ int dif = trace[h-1];
int del = trace[h];
a += del;
printf(" %d / %d (%d)\n",dif,del,a);
}
}
#endif
return (0);
}
/****************************************************************************************\
* *
* OVERLAP MANIPULATION *
* *
\****************************************************************************************/
static int64 PtrSize = sizeof(void *);
static int64 OvlIOSize = sizeof(Overlap) - sizeof(void *);
int Read_Overlap(FILE *input, Overlap *ovl)
{
if (fread(((char *) ovl) + PtrSize, OvlIOSize, 1, input) != 1)
return (1);
return (0);
}
int Read_Trace(FILE *input, Overlap *ovl, int tbytes)
{
if (tbytes > 0 && ovl->path.tlen > 0)
{
if (fread(ovl->path.trace, tbytes * ovl->path.tlen, 1, input) != 1)
return (1);
}
return (0);
}
int Write_Overlap(FILE *output, Overlap *ovl, int tbytes)
{
if (fwrite(((char *) ovl) + PtrSize, OvlIOSize, 1, output) != 1)
return (1);
if (ovl->path.trace != NULL)
if (fwrite(ovl->path.trace, tbytes, ovl->path.tlen, output) != (size_t) ovl->path.tlen)
return (1);
return (0);
}
int Compress_TraceTo8(Overlap *ovl, int check)
{
uint16 *t16 = (uint16 *) ovl->path.trace;
uint8 *t8 = (uint8 *) ovl->path.trace;
int j, x;
if (check)
for (j = 0; j < ovl->path.tlen; j++)
{
x = t16[j];
if (x > 255)
{
fprintf(stderr, "%s: Compression of trace to bytes fails, value too big\n", Prog_Name);
EXIT(1);
}
t8[j] = (uint8) x;
}
else
for (j = 0; j < ovl->path.tlen; j++)
t8[j] = (uint8) (t16[j]);
return (0);
}
void Decompress_TraceTo16(Overlap *ovl)
{
uint16 *t16 = (uint16 *) ovl->path.trace;
uint8 *t8 = (uint8 *) ovl->path.trace;
int j;
for (j = ovl->path.tlen - 1; j >= 0; j--)
t16[j] = t8[j];
}
void Print_Overlap(FILE *output, Overlap *ovl, int tbytes, int indent)
{
int i;
fprintf(output, "%*s%d vs. ", indent, "", ovl->aread);
if (COMP(ovl->flags))
fprintf(output, "c(%d)\n", ovl->bread);
else
fprintf(output, "%d\n", ovl->bread);
fprintf(output, "%*s [%d,%d] vs [%d,%d] w. %d diffs\n", indent, "", ovl->path.abpos, ovl->path.aepos, ovl->path.bbpos, ovl->path.bepos, ovl->path.diffs);
if (tbytes == 1)
{
uint8 *trace = (uint8 *) (ovl->path.trace);
if (trace != NULL)
{
int p = ovl->path.bbpos + trace[1];
fprintf(output, "%*sTrace: %3d/%5d", indent, "", trace[0], p);
for (i = 3; i < ovl->path.tlen; i += 2)
{
if (i % 10 == 0)
fprintf(output, "\n%*s", indent + 6, "");
p += trace[i];
fprintf(output, " %3d/%5d", trace[i - 1], p);
}
fprintf(output, "\n");
}
}
else
{
uint16 *trace = (uint16 *) (ovl->path.trace);
if (trace != NULL)
{
int p = ovl->path.bbpos + trace[1];
fprintf(output, "%*sTrace: %3d/%5d", indent, "", trace[0], p);
for (i = 3; i < ovl->path.tlen; i += 2)
{
if (i % 10 == 0)
fprintf(output, "\n%*s", indent + 6, "");
p += trace[i];
fprintf(output, " %3d/%5d", trace[i - 1], p);
}
fprintf(output, "\n");
}
}
}
int Check_Trace_Points(Overlap *ovl, int tspace, int verbose, char *fname)
{
int i, p, q;
if (tspace != 0)
{
if (((ovl->path.aepos - 1) / tspace - ovl->path.abpos / tspace) * 2 != ovl->path.tlen - 2)
{
if (verbose)
EPRINTF(EPLACE, " %s: Wrong number of trace points\n", fname);
return (1);
}
p = ovl->path.bbpos;
if (tspace <= TRACE_XOVR)
{
uint8 *trace8 = (uint8 *) ovl->path.trace;
for (i = 1; i < ovl->path.tlen; i += 2)
p += trace8[i];
}
else
{
uint16 *trace16 = (uint16 *) ovl->path.trace;
for (i = 1; i < ovl->path.tlen; i += 2)
p += trace16[i];
}
if (p != ovl->path.bepos)
{
if (verbose)
EPRINTF(EPLACE, " %s: Trace point sum != aligned interval\n", fname);
return (1);
}
}
else
{
uint16 *trace16 = (uint16 *) ovl->path.trace;
p = ovl->path.bbpos;
q = ovl->path.abpos;
for (i = 1; i < ovl->path.tlen; i += 2)
{
p += trace16[i];
q += trace16[i - 1];
}
if (p != ovl->path.bepos || q != ovl->path.aepos)
{
if (verbose)
EPRINTF(EPLACE, " %s: Trace point sum != aligned interval\n", fname);
return (1);
}
}
return (0);
}
void Flip_Alignment(Alignment *align, int full)
{
char *aseq = align->aseq;
char *bseq = align->bseq;
int alen = align->alen;
int blen = align->blen;
Path *path = align->path;
int comp = COMP(align->flags);
int *trace = (int *) path->trace;
int tlen = path->tlen;
int i, j, p;
if (comp)
{
p = path->abpos;
path->abpos = blen - path->bepos;
path->bepos = alen - p;
p = path->aepos;
path->aepos = blen - path->bbpos;
path->bbpos = alen - p;
if (full)
{
alen += 2;
blen += 2;
for (i = 0; i < tlen; i++)
if ((p = trace[i]) < 0)
trace[i] = alen + p;
else
trace[i] = p - blen;
i = tlen - 1;
j = 0;
while (j < i)
{
p = trace[i];
trace[i] = trace[j];
trace[j] = p;
i -= 1;
j += 1;
}
alen -= 2;
blen -= 2;
}
}
else
{
p = path->abpos;
path->abpos = path->bbpos;
path->bbpos = p;
p = path->aepos;
path->aepos = path->bepos;
path->bepos = p;
if (full)
for (i = 0; i < tlen; i++)
trace[i] = -(trace[i]);
}
align->aseq = bseq;
align->bseq = aseq;
align->alen = blen;
align->blen = alen;
}
/****************************************************************************************\
* *
* ALIGNMENT PRINTING *
* *
\****************************************************************************************/
/* Complement the sequence in fragment aseq. The operation does the
complementation/reversal in place. Calling it a second time on a
given fragment restores it to its original state. */
void Complement_Seq(char *aseq, int len)
{
char *s, *t;
int c;
s = aseq;
t = aseq + (len - 1);
while (s < t)
{
c = 3 - *s;
*s++ = (char) (3 - *t);
*t-- = (char) c;
}
if (s == t)
*s = (char) (3 - *s);
}
/* Print an alignment to file between a and b given in trace (unpacked).
Prefix gives the length of the initial prefix of a that is unaligned. */
static char ToL[8] =
{ 'a', 'c', 'g', 't', '.', '[', ']', '-' };
static char ToU[8] =
{ 'A', 'C', 'G', 'T', '.', '[', ']', '-' };
int Print_Alignment(FILE *file, Alignment *align, Work_Data *ework, int indent, int width, int border, int upper, int coord)
{
_Work_Data *work = (_Work_Data *) ework;
int *trace = align->path->trace;
int tlen = align->path->tlen;
char *Abuf, *Bbuf, *Dbuf;
int i, j, o;
char *a, *b;
char mtag, dtag;
int prefa, prefb;
int aend, bend;
int comp, blen;
int sa, sb;
int match, diff;
char *N2A;
if (trace == NULL)
return (0);
#ifdef SHOW_TRACE
fprintf(file,"\nTrace:\n");
for (i = 0; i < tlen; i++)
fprintf(file," %3d\n",trace[i]);
#endif
o = sizeof(char) * 3 * (width + 1);
if (o > work->vecmax)
if (enlarge_vector(work, o))
EXIT(1);
if (upper)
N2A = ToU;
else
N2A = ToL;
Abuf = (char *) work->vector;
Bbuf = Abuf + (width + 1);
Dbuf = Bbuf + (width + 1);
aend = align->path->aepos;
bend = align->path->bepos;
comp = COMP(align->flags);
blen = align->blen;
Abuf[width] = Bbuf[width] = Dbuf[width] = '\0';
/* buffer/output next column */
#define COLUMN(x,y) \
{ int u, v; \
if (o >= width) \
{ fprintf(file,"\n"); \
fprintf(file,"%*s",indent,""); \
if (coord > 0) \
{ if (sa < aend) \
fprintf(file," %*d",coord,sa); \
else \
fprintf(file," %*s",coord,""); \
fprintf(file," %s\n",Abuf); \
fprintf(file,"%*s %*s %s\n",indent,"",coord,"",Dbuf); \
fprintf(file,"%*s",indent,""); \
if (sb < bend) \
if (comp) \
fprintf(file," %*d",coord,blen-sb); \
else \
fprintf(file," %*d",coord,sb); \
else \
fprintf(file," %*s",coord,""); \
fprintf(file," %s",Bbuf); \
} \
else \
{ fprintf(file," %s\n",Abuf); \
fprintf(file,"%*s %s\n",indent,"",Dbuf); \
fprintf(file,"%*s %s",indent,"",Bbuf); \
} \
fprintf(file," %5.1f%%\n",(100.*diff)/(diff+match)); \
o = 0; \
sa = i-1; \
sb = j-1; \
match = diff = 0; \
} \
u = (x); \
v = (y); \
if (u == 4 || v == 4) \
Dbuf[o] = ' '; \
else if (u == v) \
Dbuf[o] = mtag; \
else \
Dbuf[o] = dtag; \
Abuf[o] = N2A[u]; \
Bbuf[o] = N2A[v]; \
o += 1; \
}
a = align->aseq - 1;
b = align->bseq - 1;
o = 0;
i = j = 1;
prefa = align->path->abpos;
prefb = align->path->bbpos;
if (prefa > border)
{
i = prefa - (border - 1);
prefa = border;
}
if (prefb > border)
{
j = prefb - (border - 1);
prefb = border;
}
sa = i - 1;
sb = j - 1;
mtag = ':';
dtag = ':';
while (prefa > prefb)
{
COLUMN(a[i], 4)
i += 1;
prefa -= 1;
}
while (prefb > prefa)
{
COLUMN(4, b[j])
j += 1;
prefb -= 1;
}
while (prefa > 0)
{
COLUMN(a[i], b[j])
i += 1;
j += 1;
prefa -= 1;
}
mtag = '[';
if (prefb > 0)
COLUMN(5, 5)
mtag = '|';
dtag = '*';
match = diff = 0;
{
int p, c; /* Output columns of alignment til reach trace end */
for (c = 0; c < tlen; c++)
if ((p = trace[c]) < 0)
{
p = -p;
while (i != p)
{
COLUMN(a[i], b[j])
if (a[i] == b[j])
match += 1;
else
diff += 1;
i += 1;
j += 1;
}
COLUMN(7, b[j])
j += 1;
diff += 1;
}
else
{
while (j != p)
{
COLUMN(a[i], b[j])
if (a[i] == b[j])
match += 1;
else
diff += 1;
i += 1;
j += 1;
}
COLUMN(a[i], 7)
i += 1;
diff += 1;
}
p = align->path->aepos;
while (i <= p)
{
COLUMN(a[i], b[j])
if (a[i] == b[j])
match += 1;
else
diff += 1;
i += 1;
j += 1;
}
}
{
int c; /* Output remaining column including unaligned suffix */
mtag = ']';
if (a[i] != 4 && b[j] != 4 && border > 0)
COLUMN(6, 6)
mtag = ':';
dtag = ':';
c = 0;
while (c < border && (a[i] != 4 || b[j] != 4))
{
if (a[i] != 4)
if (b[j] != 4)
{
COLUMN(a[i], b[j])
i += 1;
j += 1;
}
else
{
COLUMN(a[i], 4)
i += 1;
}
else
{
COLUMN(4, b[j])
j += 1;
}
c += 1;
}
}
/* Print remainder of buffered col.s */
fprintf(file, "\n");
fprintf(file, "%*s", indent, "");
if (coord > 0)
{
if (sa < aend)
fprintf(file, " %*d", coord, sa);
else
fprintf(file, " %*s", coord, "");
fprintf(file, " %.*s\n", o, Abuf);
fprintf(file, "%*s %*s %.*s\n", indent, "", coord, "", o, Dbuf);
fprintf(file, "%*s", indent, "");
if (sb < bend)
if (comp)
fprintf(file, " %*d", coord, blen - sb);
else
fprintf(file, " %*d", coord, sb);
else
fprintf(file, " %*s", coord, "");
fprintf(file, " %.*s", o, Bbuf);
}
else
{
fprintf(file, " %.*s\n", o, Abuf);
fprintf(file, "%*s %.*s\n", indent, "", o, Dbuf);
fprintf(file, "%*s %.*s", indent, "", o, Bbuf);
}
if (diff + match > 0)
fprintf(file, " %5.1f%%\n", (100. * diff) / (diff + match));
else
fprintf(file, "\n");
fflush(file);
return (0);
}
int Print_Reference(FILE *file, Alignment *align, Work_Data *ework, int indent, int block, int border, int upper, int coord)
{
_Work_Data *work = (_Work_Data *) ework;
int *trace = align->path->trace;
int tlen = align->path->tlen;
char *Abuf, *Bbuf, *Dbuf;
int i, j, o;
char *a, *b;
char mtag, dtag;
int prefa, prefb;
int aend, bend;
int comp, blen;
int sa, sb, s0;
int match, diff;
char *N2A;
int vmax;
if (trace == NULL)
return (0);
#ifdef SHOW_TRACE
fprintf(file,"\nTrace:\n");
for (i = 0; i < tlen; i++)
fprintf(file," %3d\n",trace[i]);
#endif
vmax = work->vecmax / 3;
o = sizeof(char) * 6 * (block + 1);
if (o > vmax)
{
if (enlarge_vector(work, 3 * o))
EXIT(1);
vmax = work->vecmax / 3;
}
Abuf = (char *) work->vector;
Bbuf = Abuf + vmax;
Dbuf = Bbuf + vmax;
if (upper)
N2A = ToU;
else
N2A = ToL;
aend = align->path->aepos;
bend = align->path->bepos;
comp = COMP(align->flags);
blen = align->blen;
#define BLOCK(x,y) \
{ int u, v; \
if (i%block == 1 && i != s0 && x < 4 && o > 0) \
{ fprintf(file,"\n"); \
fprintf(file,"%*s",indent,""); \
if (coord > 0) \
{ if (sa < aend) \
fprintf(file," %*d",coord,sa); \
else \
fprintf(file," %*s",coord,""); \
fprintf(file," %.*s\n",o,Abuf); \
fprintf(file,"%*s %*s %.*s\n",indent,"",coord,"",o,Dbuf); \
fprintf(file,"%*s",indent,""); \
if (sb < bend) \
if (comp) \
fprintf(file," %*d",coord,blen-sb); \
else \
fprintf(file," %*d",coord,sb); \
else \
fprintf(file," %*s",coord,""); \
fprintf(file," %.*s",o,Bbuf); \
} \
else \
{ fprintf(file," %.*s\n",o,Abuf); \
fprintf(file,"%*s %.*s\n",indent,"",o,Dbuf); \
fprintf(file,"%*s %.*s",indent,"",o,Bbuf); \
} \
fprintf(file," %5.1f%%\n",(100.*diff)/(diff+match)); \
o = 0; \
sa = i-1; \
sb = j-1; \
match = diff = 0; \
} \
u = (x); \
v = (y); \
if (u == 4 || v == 4) \
Dbuf[o] = ' '; \
else if (u == v) \
Dbuf[o] = mtag; \
else \
Dbuf[o] = dtag; \
Abuf[o] = N2A[u]; \
Bbuf[o] = N2A[v]; \
o += 1; \
if (o >= vmax) \
{ if (enlarge_vector(work,3*o)) \
EXIT(1); \
vmax = work->vecmax/3; \
memmove(work->vector+2*vmax,Dbuf,o); \
memmove(work->vector+vmax,Bbuf,o); \
memmove(work->vector,Abuf,o); \
Abuf = (char *) work->vector; \
Bbuf = Abuf + vmax; \
Dbuf = Bbuf + vmax; \
} \
}
a = align->aseq - 1;
b = align->bseq - 1;
o = 0;
i = j = 1;
prefa = align->path->abpos;
prefb = align->path->bbpos;
if (prefa > border)
{
i = prefa - (border - 1);
prefa = border;
}
if (prefb > border)
{
j = prefb - (border - 1);
prefb = border;
}
s0 = i;
sa = i - 1;
sb = j - 1;
mtag = ':';
dtag = ':';
while (prefa > prefb)
{
BLOCK(a[i], 4)
i += 1;
prefa -= 1;
}
while (prefb > prefa)
{
BLOCK(4, b[j])
j += 1;
prefb -= 1;
}
while (prefa > 0)
{
BLOCK(a[i], b[j])
i += 1;
j += 1;
prefa -= 1;
}
mtag = '[';
if (prefb > 0)
BLOCK(5, 5)
mtag = '|';
dtag = '*';
match = diff = 0;
{
int p, c; /* Output columns of alignment til reach trace end */
for (c = 0; c < tlen; c++)
if ((p = trace[c]) < 0)
{
p = -p;
while (i != p)
{
BLOCK(a[i], b[j])
if (a[i] == b[j])
match += 1;
else
diff += 1;
i += 1;
j += 1;
}
BLOCK(7, b[j])
j += 1;
diff += 1;
}
else
{
while (j != p)
{
BLOCK(a[i], b[j])
if (a[i] == b[j])
match += 1;
else
diff += 1;
i += 1;
j += 1;
}
BLOCK(a[i], 7)
i += 1;
diff += 1;
}
p = align->path->aepos;
while (i <= p)
{
BLOCK(a[i], b[j])
if (a[i] == b[j])
match += 1;
else
diff += 1;
i += 1;
j += 1;
}
}
{
int c; /* Output remaining column including unaligned suffix */
mtag = ']';
if (a[i] != 4 && b[j] != 4 && border > 0)
BLOCK(6, 6)
mtag = ':';
dtag = ':';
c = 0;
while (c < border && (a[i] != 4 || b[j] != 4))
{
if (a[i] != 4)
if (b[j] != 4)
{
BLOCK(a[i], b[j])
i += 1;
j += 1;
}
else
{
BLOCK(a[i], 4)
i += 1;
}
else
{
BLOCK(4, b[j])
j += 1;
}
c += 1;
}
}
/* Print remainder of buffered col.s */
fprintf(file, "\n");
fprintf(file, "%*s", indent, "");
if (coord > 0)
{
if (sa < aend)
fprintf(file, " %*d", coord, sa);
else
fprintf(file, " %*s", coord, "");
fprintf(file, " %.*s\n", o, Abuf);
fprintf(file, "%*s %*s %.*s\n", indent, "", coord, "", o, Dbuf);
fprintf(file, "%*s", indent, "");
if (sb < bend)
if (comp)
fprintf(file, " %*d", coord, blen - sb);
else
fprintf(file, " %*d", coord, sb);
else
fprintf(file, " %*s", coord, "");
fprintf(file, " %.*s", o, Bbuf);
}
else
{
fprintf(file, " %.*s\n", o, Abuf);
fprintf(file, "%*s %.*s\n", indent, "", o, Dbuf);
fprintf(file, "%*s %.*s", indent, "", o, Bbuf);
}
if (diff + match > 0)
fprintf(file, " %5.1f%%\n", (100. * diff) / (diff + match));
else
fprintf(file, "\n");
fflush(file);
return (0);
}
/* Print an ASCII representation of the overlap in align between fragments
a and b to given file. */
static inline void repchar(FILE *file, int symbol, int rep)
{
while (rep-- > 0)
fputc(symbol, file);
}
void Alignment_Cartoon(FILE *file, Alignment *align, int indent, int coord)
{
int alen = align->alen;
int blen = align->blen;
Path *path = align->path;
int comp = COMP(align->flags);
int w;
fprintf(file, "%*s", indent, "");
if (path->abpos > 0)
fprintf(file, " %*d ", coord, path->abpos);
else
fprintf(file, "%*s", coord + 5, "");
if (path->aepos < alen)
fprintf(file, "%*s%d", coord + 8, "", alen - path->aepos);
fprintf(file, "\n");
fprintf(file, "%*s", indent, "");
if (path->abpos > 0)
{
fprintf(file, "A ");
w = Number_Digits((int64) path->abpos);
repchar(file, ' ', coord - w);
repchar(file, '=', w + 3);
fputc('+', file);
repchar(file, '-', coord + 5);
}
else
{
fprintf(file, "A %*s", coord + 4, "");
repchar(file, '-', coord + 5);
}
if (path->aepos < alen)
{
fputc('+', file);
w = Number_Digits((int64) (alen - path->aepos));
repchar(file, '=', w + 2);
fputc('>', file);
repchar(file, ' ', w);
}
else
{
fputc('>', file);
repchar(file, ' ', coord + 3);
}
{
int asub, bsub;
asub = path->aepos - path->abpos;
bsub = path->bepos - path->bbpos;
fprintf(file, " dif/(len1+len2) = %d/(%d+%d) = %5.2f%%\n", path->diffs, asub, bsub, (200. * path->diffs) / (asub + bsub));
}
{
int sym1e, sym2e;
int sym1p, sym2p;
if (comp > 0)
{
sym1p = '<';
sym2p = '-';
sym1e = '<';
sym2e = '=';
}
else
{
sym1p = '-';
sym2p = '>';
sym1e = '=';
sym2e = '>';
}
fprintf(file, "%*s", indent, "");
if (path->bbpos > 0)
{
fprintf(file, "B ");
w = Number_Digits((int64) path->bbpos);
repchar(file, ' ', coord - w);
fputc(sym1e, file);
repchar(file, '=', w + 2);
fputc('+', file);
repchar(file, '-', coord + 5);
}
else
{
fprintf(file, "B ");
repchar(file, ' ', coord + 3);
fputc(sym1p, file);
repchar(file, '-', coord + 5);
}
if (path->bepos < blen)
{
fprintf(file, "+");
w = Number_Digits((int64) (blen - path->bepos));
repchar(file, '=', w + 2);
fprintf(file, "%c\n", sym2e);
}
else
fprintf(file, "%c\n", sym2p);
}
fprintf(file, "%*s", indent, "");
if (path->bbpos > 0)
fprintf(file, " %*d ", coord, path->bbpos);
else
fprintf(file, "%*s", coord + 5, "");
if (path->bepos < blen)
fprintf(file, "%*s%d", coord + 8, "", blen - path->bepos);
fprintf(file, "\n");
fflush(file);
}
/****************************************************************************************\
* *
* O(ND) trace algorithm *
* *
\****************************************************************************************/
#ifdef DEBUG_AWAVE
static void print_awave(int *V, int low, int hgh)
{ int k;
printf(" [%6d,%6d]: ",low,hgh);
for (k = low; k <= hgh; k++)
printf(" %3d",V[k]);
printf("\n");
fflush(stdout);
}
#endif
#ifdef DEBUG_ALIGN
static int depth = 0;
#endif
typedef struct
{
int *Stop; // Ongoing stack of alignment indels
uint16 *Trace; // Base of Trace Vector
char *Aabs, *Babs; // Absolute base of A and B sequences
int **PVF, **PHF; // List of waves for iterative np algorithms
int mida, midb; // mid point division for mid-point algorithms
int *VF, *VB; // Forward/Reverse waves for nd algorithms
} Trace_Waves;
static int split_nd(char *A, int M, char *B, int N, Trace_Waves *wave, int *px, int *py)
{
int x, y;
int D;
int *VF = wave->VF;
int *VB = wave->VB;
int flow; // fhgh == D !
int blow, bhgh;
char *a;
y = 0;
if (N < M)
while (y < N && B[y] == A[y])
y += 1;
else
{
while (y < M && B[y] == A[y])
y += 1;
if (y >= M && N == M)
{
*px = *py = M;
return (0);
}
}
flow = 0;
VF[0] = y;
VF[-1] = -2;
x = N - M;
a = A - x;
y = N - 1;
if (N > M)
while (y >= x && B[y] == a[y])
y -= 1;
else
while (y >= 0 && B[y] == a[y])
y -= 1;
blow = bhgh = -x;
VB += x;
VB[blow] = y;
VB[blow - 1] = N + 1;
for (D = 1; 1; D += 1)
{
int k, r;
int am, ac, ap;
// Forward wave
flow -= 1;
am = ac = VF[flow - 1] = -2;
a = A + D;
x = M - D;
for (k = D; k >= flow; k--)
{
ap = ac;
ac = am + 1;
am = VF[k - 1];
if (ac < am)
if (ap < am)
y = am;
else
y = ap;
else if (ap < ac)
y = ac;
else
y = ap;
if (blow <= k && k <= bhgh)
{
r = VB[k];
if (y > r)
{
D = (D << 1) - 1;
if (ap > r)
y = ap;
else if (ac > r)
y = ac;
else
y = r + 1;
x = k + y;
*px = x;
*py = y;
return (D);
}
}
if (N < x)
while (y < N && B[y] == a[y])
y += 1;
else
while (y < x && B[y] == a[y])
y += 1;
VF[k] = y;
a -= 1;
x += 1;
}
#ifdef DEBUG_AWAVE
print_awave(VF,flow,D);
#endif
// Reverse Wave
bhgh += 1;
blow -= 1;
am = ac = VB[blow - 1] = N + 1;
a = A + bhgh;
x = -bhgh;
for (k = bhgh; k >= blow; k--)
{
ap = ac + 1;
ac = am;
am = VB[k - 1];
if (ac > am)
if (ap > am)
y = am;
else
y = ap;
else if (ap > ac)
y = ac;
else
y = ap;
if (flow <= k && k <= D)
{
r = VF[k];
if (y <= r)
{
D = (D << 1);
if (ap <= r)
y = ap;
else if (ac <= r)
y = ac;
else
y = r;
x = k + y;
*px = x;
*py = y;
return (D);
}
}
y -= 1;
if (x > 0)
while (y >= x && B[y] == a[y])
y -= 1;
else
while (y >= 0 && B[y] == a[y])
y -= 1;
VB[k] = y;
a -= 1;
x += 1;
}
#ifdef DEBUG_AWAVE
print_awave(VB,blow,bhgh);
#endif
}
}
static int trace_nd(char *A, int M, char *B, int N, Trace_Waves *wave, int tspace)
{
int x, y;
int D, s;
#ifdef DEBUG_ALIGN
printf("%*s %ld,%ld: %d vs %d\n",depth,"",A-wave->Aabs,B-wave->Babs,M,N);
fflush(stdout);
#endif
if (M <= 0)
{
y = (((A - wave->Aabs) / tspace) << 1);
wave->Trace[y] += N;
wave->Trace[y + 1] += N;
#ifdef DEBUG_TRACE
printf("%*s Adding1 (%d,%d) to tp %d(%d,%d)\n",depth,"",N,N,y>>1,
wave->Trace[y+1],wave->Trace[y]);
fflush(stdout);
#endif
return (N);
}
if (N <= 0)
{
x = A - wave->Aabs;
y = x / tspace;
x = (y + 1) * tspace - x;
y <<= 1;
for (s = M; s > 0; s -= x, x = tspace)
{
if (x > s)
x = s;
wave->Trace[y] += x;
#ifdef DEBUG_TRACE
printf("%*s Adding2 (0,%d) to tp %d(%d,%d)\n",depth,"",x,y>>1,
wave->Trace[y+1],wave->Trace[y]);
fflush(stdout);
#endif
y += 2;
}
return (M);
}
D = split_nd(A, M, B, N, wave, &x, &y);
if (D > 1)
{
#ifdef DEBUG_ALIGN
printf("%*s (%d,%d) @ %d\n",depth,"",x,y,D);
fflush(stdout);
depth += 2;
#endif
s = A - wave->Aabs;
if ((s / tspace + 1) * tspace - s >= x)
{
s = ((s / tspace) << 1);
wave->Trace[s] += (D + 1) / 2;
wave->Trace[s + 1] += y;
#ifdef DEBUG_TRACE
printf("%*s Adding3 (%d,%d) to tp %d(%d,%d)\n",depth,"",y,(D+1)/2,s>>1,
wave->Trace[s+1],wave->Trace[s]);
fflush(stdout);
#endif
}
else
trace_nd(A, x, B, y, wave, tspace);
s = (A + x) - wave->Aabs;
if ((s / tspace + 1) * tspace - s >= M - x)
{
s = ((s / tspace) << 1);
wave->Trace[s] += D / 2;
wave->Trace[s + 1] += N - y;
#ifdef DEBUG_TRACE
printf("%*s Adding4 (%d,%d)) to tp %d(%d,%d)\n",depth,"",N-y,D/2,s>>1,
wave->Trace[s+1],wave->Trace[s]);
fflush(stdout);
#endif
}
else
trace_nd(A + x, M - x, B + y, N - y, wave, tspace);
#ifdef DEBUG_ALIGN
depth -= 2;
#endif
}
else
{
int u, v;
if (D == 0 || M < N)
s = x;
else
s = x - 1;
if (s > 0)
{
u = A - wave->Aabs;
v = u / tspace;
u = (v + 1) * tspace - u;
for (v <<= 1; s > 0; s -= u, u = tspace)
{
if (u > s)
u = s;
wave->Trace[v + 1] += u;
#ifdef DEBUG_TRACE
printf("%*s Adding5 (%d,0)) to tp %d(%d,%d)\n",depth,"",u,v>>1,
wave->Trace[v+1],wave->Trace[v]);
fflush(stdout);
#endif
v += 2;
}
}
if (D == 0)
return (D);
if (M < N)
y = ((((A + x) - wave->Aabs) / tspace) << 1);
else
y = ((((A + (x - 1)) - wave->Aabs) / tspace) << 1);
wave->Trace[y] += 1;
if (M <= N)
wave->Trace[y + 1] += 1;
#ifdef DEBUG_TRACE
printf("%*s Adding5 (%d,1)) to tp %d(%d,%d)\n",depth,"",N>=M,y>>1,
wave->Trace[y+1],wave->Trace[y]);
fflush(stdout);
#endif
s = M - x;
if (s > 0)
{
u = (A + x) - wave->Aabs;
v = u / tspace;
u = (v + 1) * tspace - u;
for (v <<= 1; s > 0; s -= u, u = tspace)
{
if (u > s)
u = s;
wave->Trace[v + 1] += u;
#ifdef DEBUG_TRACE
printf("%*s Adding5 (%d,0)) to tp %d(%d,%d)\n",depth,"",u,v>>1,
wave->Trace[v+1],wave->Trace[v]);
fflush(stdout);
#endif
v += 2;
}
}
}
return (D);
}
static int dandc_nd(char *A, int M, char *B, int N, Trace_Waves *wave)
{
int x, y;
int D;
#ifdef DEBUG_ALIGN
printf("%*s %ld,%ld: %d vs %d\n",depth,"",A-wave->Aabs,B-wave->Babs,M,N);
#endif
if (M <= 0)
{
x = (wave->Aabs - A) - 1;
for (y = 1; y <= N; y++)
{
*wave->Stop++ = x;
#ifdef DEBUG_SCRIPT
printf("%*s *I %ld(%ld)\n",depth,"",y+(B-wave->Babs),(A-wave->Aabs)+1);
#endif
}
return (N);
}
if (N <= 0)
{
y = (B - wave->Babs) + 1;
for (x = 1; x <= M; x++)
{
*wave->Stop++ = y;
#ifdef DEBUG_SCRIPT
printf("%*s *D %ld(%ld)\n",depth,"",x+(A-wave->Aabs),(B-wave->Babs)+1);
#endif
}
return (M);
}
D = split_nd(A, M, B, N, wave, &x, &y);
if (D > 1)
{
#ifdef DEBUG_ALIGN
printf("%*s (%d,%d) @ %d\n",depth,"",x,y,D);
fflush(stdout);
depth += 2;
#endif
dandc_nd(A, x, B, y, wave);
dandc_nd(A + x, M - x, B + y, N - y, wave);
#ifdef DEBUG_ALIGN
depth -= 2;
#endif
}
else if (D == 1)
{
if (M > N)
{
*wave->Stop++ = (B - wave->Babs) + y + 1;
#ifdef DEBUG_SCRIPT
printf("%*s D %ld(%ld)\n",depth,"",(A-wave->Aabs)+x,(B-wave->Babs)+y+1);
#endif
}
else if (M < N)
{
*wave->Stop++ = (wave->Aabs - A) - x - 1;
#ifdef DEBUG_SCRIPT
printf("%*s I %ld(%ld)\n",depth,"",(B-wave->Babs)+y,(A-wave->Aabs)+x+1);
#endif
}
#ifdef DEBUG_SCRIPT
else
printf("%*s %ld S %ld\n",depth,"",(wave->Aabs-A)+x,(B-wave->Babs)+y);
#endif
}
return (D);
}
int Compute_Alignment(Alignment *align, Work_Data *ework, int task, int tspace)
{ _Work_Data *work = (_Work_Data *) ework;
Trace_Waves wave;
int L, D;
int asub, bsub;
char *aseq, *bseq;
Path *path;
int *trace;
uint16 *strace;
path = align->path;
asub = path->aepos-path->abpos;
bsub = path->bepos-path->bbpos;
aseq = align->aseq+path->abpos;
bseq = align->bseq+path->bbpos;
L=0;
if (task != DIFF_ONLY)
{ if (task == DIFF_TRACE || task == PLUS_TRACE)
L = 2*(((path->aepos + (tspace-1))/tspace - path->abpos/tspace) + 1)*sizeof(uint16);
else if (asub < bsub)
L = bsub*sizeof(int);
else
L = asub*sizeof(int);
if (L > work->tramax)
if (enlarge_trace(work,L))
EXIT(1);
}
trace = ((int *) work->trace);
strace = ((uint16 *) work->trace);
if (asub > bsub)
D = (4*asub+6)*sizeof(int);
else
D = (4*bsub+6)*sizeof(int);
if (D > work->vecmax)
if (enlarge_vector(work,D))
EXIT(1);
if (asub > bsub)
{ wave.VF = ((int *) work->vector) + (asub+1);
wave.VB = wave.VF + (2*asub+3);
}
else
{ wave.VF = ((int *) work->vector) + (bsub+1);
wave.VB = wave.VF + (2*bsub+3);
}
wave.Aabs = align->aseq;
wave.Babs = align->bseq;
if (task == DIFF_ONLY)
{ wave.mida = -1;
if (asub <= 0)
path->diffs = bsub;
else if (bsub <= 0)
path->diffs = asub;
else
path->diffs = split_nd(aseq,asub,bseq,bsub,&wave,&wave.mida,&wave.midb);
path->trace = NULL;
path->tlen = -1;
return (0);
}
else if (task < DIFF_ONLY && wave.mida >= 0)
{ int x = wave.mida;
int y = wave.midb;
if (task == PLUS_ALIGN)
{ wave.Stop = trace;
dandc_nd(aseq,x,bseq,y,&wave);
dandc_nd(aseq+x,asub-x,bseq+y,bsub-y,&wave);
path->tlen = wave.Stop - trace;
}
else
{ int i, n;
wave.Trace = strace - 2*(path->abpos/tspace);
n = L/sizeof(uint16);
for (i = 0; i < n; i++)
strace[i] = 0;
trace_nd(aseq,x,bseq,y,&wave,tspace);
trace_nd(aseq+x,asub-x,bseq+y,bsub-y,&wave,tspace);
if (strace[n-1] != 0) // Last element is to capture all inserts on TP boundary
{ strace[n-3] += strace[n-1];
strace[n-4] += strace[n-2];
}
path->tlen = n-2;
#ifdef DEBUG_SCRIPT
printf(" Trace:\n");
for (i = 0; i < path->tlen; i += 2)
printf(" %3d %3d\n",strace[i],strace[i+1]);
fflush(stdout);
#endif
}
}
else
{ if (task == DIFF_ALIGN)
{ wave.Stop = trace;
path->diffs = dandc_nd(aseq,asub,bseq,bsub,&wave);
path->tlen = wave.Stop - trace;
}
else
{ int i, n;
wave.Trace = strace - 2*(path->abpos/tspace);
n = L/sizeof(uint16);
for (i = 0; i < n; i++)
strace[i] = 0;
path->diffs = trace_nd(aseq,asub,bseq,bsub,&wave,tspace);
if (strace[n-1] != 0) // Last element is to capture all inserts on TP boundary
{ strace[n-3] += strace[n-1];
strace[n-4] += strace[n-2];
}
path->tlen = n-2;
#ifdef DEBUG_SCRIPT
printf(" Trace:\n");
for (i = 0; i < path->tlen; i += 2)
printf(" %3d %3d\n",strace[i],strace[i+1]);
fflush(stdout);
#endif
}
}
path->trace = trace;
return (0);
}
/****************************************************************************************\
* *
* O(NP) tracing algorithms *
* *
\****************************************************************************************/
/* Iterative O(np) algorithm for finding the alignment between two substrings (specified
by a Path record). The variation includes handling substitutions and guarantees
to find left-most alignments so that low complexity runs are always aligned in
the same way.
*/
#ifdef DEBUG_ALIGN
static int ToA[4] =
{ 'a', 'c', 'g', 't'};
#endif
static char *TP_Align = "Bad alignment between trace points (Compute_Trace), source DB likely incorrect";
static int iter_np(char *A, int M, char *B, int N, Trace_Waves *wave, int mode, int dmax)
{
int **PVF = wave->PVF;
int **PHF = wave->PHF;
int D;
int del = M - N;
{
int *F0, *F1, *F2;
int *HF;
int low, hgh;
int posl, posh;
#ifdef DEBUG_ALIGN
printf("\n BASE %ld,%ld: %d vs %d\n",A-wave->Aabs,B-wave->Babs,M,N);
printf(" A = ");
for (D = 0; D < M; D++)
printf("%c",ToA[(int) A[D]]);
printf("\n");
printf(" B = ");
for (D = 0; D < N; D++)
printf("%c",ToA[(int) B[D]]);
printf("\n");
#endif
if (del >= 0)
{
low = 0;
hgh = del;
}
else
{
low = del;
hgh = 0;
}
posl = -dmax;
posh = dmax;
if (wave->Aabs == wave->Babs)
{
if (B == A)
{
EPRINTF(EPLACE, "%s: self comparison starts on diagonal 0 (Compute_Trace)\n", Prog_Name);
EXIT(-1);
}
else if (B < A)
{
if ((B - A) + 1 > posl)
posl = (B - A) + 1;
}
else
{
if ((B - A) - 1 < posh)
posh = (B - A) - 1;
}
}
F1 = PVF[-2];
F0 = PVF[-1];
for (D = low - 1; D <= hgh + 1; D++)
F1[D] = F0[D] = -2;
F0[0] = -1;
low += 1;
hgh -= 1;
for (D = 0; 1; D += 1)
{
int k, i, j;
int am, ac, ap;
char *a;
if (D > dmax)
{
EPRINTF(EPLACE, "%s: %s\n", Prog_Name, TP_Align);
EXIT(-1);
}
F2 = F1;
F1 = F0;
F0 = PVF[D];
HF = PHF[D];
if ((D & 0x1) == 0)
{
if (low > posl)
low -= 1;
if (hgh < posh)
hgh += 1;
}
F0[hgh + 1] = F0[low - 1] = -2;
#define FS_MOVE(mdir,pdir) \
ac = F1[k]+1; \
if (ac < am) \
if (ap < am) \
{ HF[k] = mdir; \
j = am; \
} \
else \
{ HF[k] = pdir; \
j = ap; \
} \
else \
if (ap < ac) \
{ HF[k] = 0; \
j = ac; \
} \
else \
{ HF[k] = pdir; \
j = ap; \
} \
\
if (N < i) \
while (j < N && B[j] == a[j]) \
j += 1; \
else \
while (j < i && B[j] == a[j]) \
j += 1; \
F0[k] = j;
j = -2;
a = A + hgh;
i = M - hgh;
for (k = hgh; k > del; k--)
{
ap = j + 1;
am = F2[k - 1];
FS_MOVE(-1, 4)
a -= 1;
i += 1;
}
j = -2;
a = A + low;
i = M - low;
for (k = low; k < del; k++)
{
ap = F2[k + 1] + 1;
am = j;
FS_MOVE(2, 1)
a += 1;
i -= 1;
}
ap = F0[del + 1] + 1;
am = j;
FS_MOVE(2, 4)
#ifdef DEBUG_AWAVE
print_awave(F0,low,hgh);
print_awave(HF,low,hgh);
#endif
if (F0[del] >= N)
break;
}
}
{
int k, h, m, e, c;
int ap = (wave->Aabs - A) - 1;
int bp = (B - wave->Babs) + 1;
PHF[0][0] = 3;
c = N;
k = del;
e = PHF[D][k];
PHF[D][k] = 3;
if (mode == UPPERMOST)
while (e != 3)
{
h = k + e;
if (e > 1)
h -= 3;
else if (e == 0)
D -= 1;
else
D -= 2;
if (h < k) // => e = -1 or 2, UPPERMOST
{
char *a;
a = A + k;
if (k < 0)
m = -k;
else
m = 0;
if (PVF[D][h] <= c)
c = PVF[D][h] - 1;
while (c >= m && a[c] == B[c])
c -= 1;
if (e == -1) // => edge is 2, others are 1, and 0
{
if (c <= PVF[D + 2][k + 1])
{
e = 4;
h = k + 1;
D = D + 2;
}
else if (c == PVF[D + 1][k])
{
e = 0;
h = k;
D = D + 1;
}
else
PVF[D][h] = c + 1;
}
else // => edge is 0, others are 1, and 2 (if k != del), 0 (otherwise)
{
if (k == del)
m = D;
else
m = D - 2;
if (c <= PVF[m][k + 1])
{
if (k == del)
e = 4;
else
e = 1;
h = k + 1;
D = m;
}
else if (c == PVF[D - 1][k])
{
e = 0;
h = k;
D = D - 1;
}
else
PVF[D][h] = c + 1;
}
}
m = PHF[D][h];
PHF[D][h] = e;
e = m;
k = h;
}
else if (mode == LOWERMOST)
while (e != 3)
{
h = k + e;
if (e > 1)
h -= 3;
else if (e == 0)
D -= 1;
else
D -= 2;
if (h > k) // => e = 1 or 4, LOWERMOST
{
char *a;
a = A + k;
if (k < 0)
m = -k;
else
m = 0;
if (PVF[D][h] < c)
c = PVF[D][h];
while (c >= m && a[c] == B[c])
c -= 1;
if (e == 1) // => edge is 2, others are 1, and 0
{
if (c < PVF[D + 2][k - 1])
{
e = 2;
h = k - 1;
D = D + 2;
}
else if (c == PVF[D + 1][k])
{
e = 0;
h = k;
D = D + 1;
}
else
PVF[D][h] = c--;
}
else // => edge is 0, others are 1, and 2 (if k != del), 0 (otherwise)
{
if (k == del)
m = D;
else
m = D - 2;
if (c < PVF[m][k - 1])
{
if (k == del)
e = 2;
else
e = -1;
h = k - 1;
D = m;
}
else if (c == PVF[D - 1][k])
{
e = 0;
h = k;
D = D - 1;
}
else
PVF[D][h] = c--;
}
}
m = PHF[D][h];
PHF[D][h] = e;
e = m;
k = h;
}
else
// mode == GREEDIEST
while (e != 3)
{
h = k + e;
if (e > 1)
h -= 3;
else if (e == 0)
D -= 1;
else
D -= 2;
m = PHF[D][h];
PHF[D][h] = e;
e = m;
k = h;
}
k = D = 0;
e = PHF[D][k];
while (e != 3)
{
h = k - e;
c = PVF[D][k];
if (e > 1)
h += 3;
else if (e == 0)
D += 1;
else
D += 2;
#ifdef DEBUG_SCRIPT
if (h > k)
printf(" D %d(%d)\n",(c-k)-(ap-1),c+bp);
else if (h < k)
printf(" I %d(%d)\n",c+(bp-1),(c+k)-ap);
else
printf(" %d S %d\n",(c+k)-(ap+1),c+(bp-1));
#endif
if (h > k)
*wave->Stop++ = bp + c;
else if (h < k)
*wave->Stop++ = ap - (c + k);
k = h;
e = PHF[D][h];
}
}
return (D + abs(del));
}
static int middle_np(char *A, int M, char *B, int N, Trace_Waves *wave, int mode, int dmax)
{
int **PVF = wave->PVF;
int **PHF = wave->PHF;
int D;
int del = M - N;
{
int *F0, *F1, *F2;
int *HF;
int low, hgh;
int posl, posh;
#ifdef DEBUG_ALIGN
printf("\n%*s BASE %ld,%ld: %d vs %d\n",depth,"",A-wave->Aabs,B-wave->Babs,M,N);
printf("%*s A = ",depth,"");
for (D = 0; D < M; D++)
printf("%c",ToA[(int) A[D]]);
printf("\n");
printf("%*s B = ",depth,"");
for (D = 0; D < N; D++)
printf("%c",ToA[(int) B[D]]);
printf("\n");
#endif
if (del >= 0)
{
low = 0;
hgh = del;
}
else
{
low = del;
hgh = 0;
}
posl = -dmax;
posh = dmax;
if (wave->Aabs == wave->Babs)
{
if (B == A)
{
EPRINTF(EPLACE, "%s: self comparison starts on diagonal 0 (Compute_Trace)\n", Prog_Name);
EXIT(1);
}
else if (B < A)
{
if ((B - A) + 1 > posl)
posl = (B - A) + 1;
}
else
{
if ((B - A) - 1 < posh)
posh = (B - A) - 1;
}
}
F1 = PVF[-2];
F0 = PVF[-1];
for (D = low - 1; D <= hgh + 1; D++)
F1[D] = F0[D] = -2;
F0[0] = -1;
low += 1;
hgh -= 1;
for (D = 0; 1; D += 1)
{
int k, i, j;
int am, ac, ap;
char *a;
if (D > dmax)
{
EPRINTF(EPLACE, "%s: %s\n", Prog_Name, TP_Align);
EXIT(-1);
}
F2 = F1;
F1 = F0;
F0 = PVF[D];
HF = PHF[D];
if ((D & 0x1) == 0)
{
if (low > posl)
low -= 1;
if (hgh < posh)
hgh += 1;
}
F0[hgh + 1] = F0[low - 1] = -2;
j = -2;
a = A + hgh;
i = M - hgh;
for (k = hgh; k > del; k--)
{
ap = j + 1;
am = F2[k - 1];
FS_MOVE(-1, 4)
a -= 1;
i += 1;
}
j = -2;
a = A + low;
i = M - low;
for (k = low; k < del; k++)
{
ap = F2[k + 1] + 1;
am = j;
FS_MOVE(2, 1)
a += 1;
i -= 1;
}
ap = F0[del + 1] + 1;
am = j;
FS_MOVE(2, 4)
#ifdef DEBUG_AWAVE
print_awave(F0,low,hgh);
print_awave(HF,low,hgh);
#endif
if (F0[del] >= N)
break;
}
}
{
int k, h, m, e, c;
int d, f;
d = D + abs(del);
c = N;
k = del;
if (mode == UPPERMOST)
for (f = d / 2; d > f; d--)
{
e = PHF[D][k];
h = k + e;
if (e > 1)
h -= 3;
else if (e == 0)
D -= 1;
else
D -= 2;
if (h < k) // => e = -1 or 2, UPPERMOST
{
char *a;
a = A + k;
if (k < 0)
m = -k;
else
m = 0;
if (PVF[D][h] <= c)
c = PVF[D][h] - 1;
while (c >= m && a[c] == B[c])
c -= 1;
if (e == -1) // => edge is 2, others are 1, and 0
{
if (c <= PVF[D + 2][k + 1])
{
e = 4;
h = k + 1;
D = D + 2;
}
else if (c == PVF[D + 1][k])
{
e = 0;
h = k;
D = D + 1;
}
else
PVF[D][h] = c + 1;
}
else // => edge is 0, others are 1, and 2 (if k != del), 0 (otherwise)
{
if (k == del)
m = D;
else
m = D - 2;
if (c <= PVF[m][k + 1])
{
if (k == del)
e = 4;
else
e = 1;
h = k + 1;
D = m;
}
else if (c == PVF[D - 1][k])
{
e = 0;
h = k;
D = D - 1;
}
else
PVF[D][h] = c + 1;
}
}
k = h;
}
else if (mode == LOWERMOST)
for (f = d / 2; d > f; d--)
{
e = PHF[D][k];
h = k + e;
if (e > 1)
h -= 3;
else if (e == 0)
D -= 1;
else
D -= 2;
if (h > k) // => e = 1 or 4, LOWERMOST
{
char *a;
a = A + k;
if (k < 0)
m = -k;
else
m = 0;
if (PVF[D][h] < c)
c = PVF[D][h];
while (c >= m && a[c] == B[c])
c -= 1;
if (e == 1) // => edge is 2, others are 1, and 0
{
if (c < PVF[D + 2][k - 1])
{
e = 2;
h = k - 1;
D = D + 2;
}
else if (c == PVF[D + 1][k])
{
e = 0;
h = k;
D = D + 1;
}
else
PVF[D][h] = c--;
}
else // => edge is 0, others are 1, and 2 (if k != del), 0 (otherwise)
{
if (k == del)
m = D;
else
m = D - 2;
if (c < PVF[m][k - 1])
{
if (k == del)
e = 2;
else
e = -1;
h = k - 1;
D = m;
}
else if (c == PVF[D - 1][k])
{
e = 0;
h = k;
D = D - 1;
}
else
PVF[D][h] = c--;
}
}
k = h;
}
else
// mode == GREEDIEST
for (f = d / 2; d > f; d--)
{
e = PHF[D][k];
h = k + e;
if (e > 1)
h -= 3;
else if (e == 0)
D -= 1;
else
D -= 2;
k = h;
}
wave->midb = (B - wave->Babs) + PVF[D][k];
wave->mida = (A - wave->Aabs) + k + PVF[D][k];
}
return (0);
}
/****************************************************************************************\
* *
* COMPUTE_TRACE FLAVORS *
* *
\****************************************************************************************/
static char *TP_Error = "Trace point out of bounds (Compute_Trace), source DB likely incorrect";
int Compute_Trace_PTS(Alignment *align, Work_Data *ework, int trace_spacing, int mode)
{
_Work_Data *work = (_Work_Data *) ework;
Trace_Waves wave;
Path *path;
char *aseq, *bseq;
int alen, blen;
uint16 *points;
int tlen;
int ab, bb;
int ae, be;
int diffs, dmax;
alen = align->alen;
blen = align->blen;
path = align->path;
aseq = align->aseq;
bseq = align->bseq;
tlen = path->tlen;
points = (uint16 *) path->trace;
{
int64 s;
int d;
int M, N;
int nmax;
int **PVF, **PHF;
M = path->aepos - path->abpos;
N = path->bepos - path->bbpos;
if (M < N)
s = N * sizeof(int);
else
s = M * sizeof(int);
if (s > work->tramax)
if (enlarge_trace(work, s))
EXIT(1);
nmax = 0;
dmax = 0;
for (d = 1; d < tlen; d += 2)
{
if (points[d - 1] > dmax)
dmax = points[d - 1];
if (points[d] > nmax)
nmax = points[d];
}
if (tlen <= 1)
nmax = N;
s = (dmax + 3) * 2 * ((trace_spacing + nmax + 3) * sizeof(int) + sizeof(int *));
if (s > work->vecmax)
if (enlarge_vector(work, s))
EXIT(1);
wave.PVF = PVF = ((int **) (work->vector)) + 2;
wave.PHF = PHF = PVF + (dmax + 3);
s = trace_spacing + nmax + 3;
PVF[-2] = ((int *) (PHF + (dmax + 1))) + (nmax + 1);
for (d = -1; d <= dmax; d++)
PVF[d] = PVF[d - 1] + s;
PHF[-2] = PVF[dmax] + s;
for (d = -1; d <= dmax; d++)
PHF[d] = PHF[d - 1] + s;
}
wave.Stop = (int *) (work->trace);
wave.Aabs = aseq;
wave.Babs = bseq;
{
int i, d;
diffs = 0;
ab = path->abpos;
ae = (ab / trace_spacing) * trace_spacing;
bb = path->bbpos;
tlen -= 2;
for (i = 1; i < tlen; i += 2)
{
ae = ae + trace_spacing;
be = bb + points[i];
if (ae > alen || be > blen)
{
EPRINTF(EPLACE, "%s: %s\n", Prog_Name, TP_Error);
EXIT(1);
}
d = iter_np(aseq + ab, ae - ab, bseq + bb, be - bb, &wave, mode, dmax);
if (d < 0)
EXIT(1);
diffs += d;
ab = ae;
bb = be;
}
ae = path->aepos;
be = path->bepos;
if (ae > alen || be > blen)
{
EPRINTF(EPLACE, "%s: %s\n", Prog_Name, TP_Error);
EXIT(1);
}
d = iter_np(aseq + ab, ae - ab, bseq + bb, be - bb, &wave, mode, dmax);
if (d < 0)
EXIT(1);
diffs += d;
}
path->trace = work->trace;
path->tlen = wave.Stop - ((int *) path->trace);
path->diffs = diffs;
return (0);
}
int Compute_Trace_MID(Alignment *align, Work_Data *ework, int trace_spacing, int mode)
{
_Work_Data *work = (_Work_Data *) ework;
Trace_Waves wave;
Path *path;
char *aseq, *bseq;
int alen, blen;
uint16 *points;
int tlen;
int ab, bb;
int ae, be;
int diffs, dmax;
alen = align->alen;
blen = align->blen;
path = align->path;
aseq = align->aseq;
bseq = align->bseq;
tlen = path->tlen;
points = (uint16 *) path->trace;
{
int64 s;
int d;
int M, N;
int nmax;
int **PVF, **PHF;
M = path->aepos - path->abpos;
N = path->bepos - path->bbpos;
if (M < N)
s = N * sizeof(int);
else
s = M * sizeof(int);
if (s > work->tramax)
if (enlarge_trace(work, s))
EXIT(1);
nmax = 0;
dmax = 0;
for (d = 1; d < tlen; d += 2)
{
if (points[d - 1] > dmax)
dmax = points[d - 1];
if (points[d] > nmax)
nmax = points[d];
}
if (tlen <= 1)
nmax = N;
s = (dmax + 3) * 4 * ((trace_spacing + nmax + 3) * sizeof(int) + sizeof(int *));
if (s > work->vecmax)
if (enlarge_vector(work, s))
EXIT(1);
wave.PVF = PVF = ((int **) (work->vector)) + 2;
wave.PHF = PHF = PVF + (dmax + 3);
s = trace_spacing + nmax + 3;
PVF[-2] = ((int *) (PHF + (dmax + 1))) + (nmax + 1);
for (d = -1; d <= dmax; d++)
PVF[d] = PVF[d - 1] + s;
PHF[-2] = PVF[dmax] + s;
for (d = -1; d <= dmax; d++)
PHF[d] = PHF[d - 1] + s;
}
wave.Stop = ((int *) work->trace);
wave.Aabs = aseq;
wave.Babs = bseq;
{
int i, d;
int as, bs;
int af, bf;
diffs = 0;
ab = as = af = path->abpos;
ae = (ab / trace_spacing) * trace_spacing;
bb = bs = bf = path->bbpos;
tlen -= 2;
for (i = 1; i < tlen; i += 2)
{
ae = ae + trace_spacing;
be = bb + points[i];
if (ae > alen || be > blen)
{
EPRINTF(EPLACE, "%s: %s\n", Prog_Name, TP_Error);
EXIT(1);
}
if (middle_np(aseq + ab, ae - ab, bseq + bb, be - bb, &wave, mode, dmax))
EXIT(1);
af = wave.mida;
bf = wave.midb;
d = iter_np(aseq + as, af - as, bseq + bs, bf - bs, &wave, mode, dmax);
if (d < 0)
EXIT(1);
diffs += d;
ab = ae;
bb = be;
as = af;
bs = bf;
}
ae = path->aepos;
be = path->bepos;
if (ae > alen || be > blen)
{
EPRINTF(EPLACE, "%s: %s\n", Prog_Name, TP_Error);
EXIT(1);
}
if (middle_np(aseq + ab, ae - ab, bseq + bb, be - bb, &wave, mode, dmax))
EXIT(1);
af = wave.mida;
bf = wave.midb;
d = iter_np(aseq + as, af - as, bseq + bs, bf - bs, &wave, mode, dmax);
if (d < 0)
EXIT(1);
diffs += d;
as = af;
bs = bf;
d += iter_np(aseq + af, ae - as, bseq + bf, be - bs, &wave, mode, dmax);
if (d < 0)
EXIT(1);
diffs += d;
}
path->trace = work->trace;
path->tlen = wave.Stop - ((int *) path->trace);
path->diffs = diffs;
return (0);
}
int Compute_Trace_IRR(Alignment *align, Work_Data *ework, int mode)
{
_Work_Data *work = (_Work_Data *) ework;
Trace_Waves wave;
Path *path;
char *aseq, *bseq;
int alen, blen;
uint16 *points;
int tlen;
int ab, bb;
int ae, be;
int diffs, dmax;
alen = align->alen;
blen = align->blen;
path = align->path;
aseq = align->aseq;
bseq = align->bseq;
tlen = path->tlen;
points = (uint16 *) path->trace;
{
int64 s;
int d;
int M, N;
int mmax, nmax;
int **PVF, **PHF;
M = path->aepos - path->abpos;
N = path->bepos - path->bbpos;
if (M < N)
s = N * sizeof(int);
else
s = M * sizeof(int);
if (s > work->tramax)
if (enlarge_trace(work, s))
EXIT(1);
nmax = mmax = 0;
for (d = 0; d < tlen; d += 2)
{
if (points[d] > mmax)
mmax = points[d];
if (points[d + 1] > nmax)
nmax = points[d + 1];
}
if (tlen <= 1)
{
mmax = M;
nmax = N;
}
if (mmax > nmax)
dmax = nmax;
else
dmax = mmax;
s = (dmax + 3) * 2 * ((mmax + nmax + 3) * sizeof(int) + sizeof(int *));
if (s > work->vecmax)
if (enlarge_vector(work, s))
EXIT(1);
wave.PVF = PVF = ((int **) (work->vector)) + 2;
wave.PHF = PHF = PVF + (dmax + 3);
s = mmax + nmax + 3;
PVF[-2] = ((int *) (PHF + (dmax + 1))) + (nmax + 1);
for (d = -1; d <= dmax; d++)
PVF[d] = PVF[d - 1] + s;
PHF[-2] = PVF[dmax] + s;
for (d = -1; d <= dmax; d++)
PHF[d] = PHF[d - 1] + s;
}
wave.Stop = (int *) (work->trace);
wave.Aabs = aseq;
wave.Babs = bseq;
{
int i, d;
diffs = 0;
ab = path->abpos;
bb = path->bbpos;
for (i = 0; i < tlen; i += 2)
{
ae = ab + points[i];
be = bb + points[i + 1];
if (ae > alen || be > blen)
{
EPRINTF(EPLACE, "%s: %s\n", Prog_Name, TP_Error);
EXIT(1);
}
d = iter_np(aseq + ab, ae - ab, bseq + bb, be - bb, &wave, mode, dmax);
if (d < 0)
EXIT(1);
diffs += d;
ab = ae;
bb = be;
}
}
path->trace = work->trace;
path->tlen = wave.Stop - ((int *) path->trace);
path->diffs = diffs;
return (0);
}
/*
* HEIDELBERG_ADDITION
*/
int Num_Threads(Align_Spec *espec)
{
return (((_Align_Spec *) espec)->nthreads);
}
Overlap_IO_Buffer *OVL_IO_Buffer(Align_Spec *espec)
{
return (((_Align_Spec*) espec)->ioBuffer);
}
int Only_Identity(Align_Spec *espec)
{
return (((_Align_Spec *) espec)->only_identity);
}
int Symmetric(Align_Spec *espec)
{
return (((_Align_Spec *) espec)->symmetric);
}
// set initial overlap buffer size to 500'000 overlaps
#define BUFFER_NOVLS 500000
Overlap_IO_Buffer *CreateOverlapBuffer(int nthreads, int tbytes, int no_trace)
{
Overlap_IO_Buffer *iobuf = (Overlap_IO_Buffer*) malloc(sizeof(Overlap_IO_Buffer));
if (iobuf == NULL)
{
fprintf(stderr, "[ERROR] - Cannot allocate Overlap_IO_Buffer!\n");
return NULL;
}
iobuf->omax = BUFFER_NOVLS / nthreads + 1;
iobuf->otop = 0;
iobuf->ovls = (Overlap*) malloc(sizeof(Overlap) * iobuf->omax);
iobuf->no_trace = no_trace;
if (iobuf->ovls == NULL)
{
fprintf(stderr, "[ERROR] - Cannot allocate Overlap buffer of size: %d!\n", iobuf->omax);
return NULL;
}
if (no_trace)
{
iobuf->tbytes = 0;
iobuf->tmax = 0;
iobuf->ttop = 0;
return iobuf;
}
if (tbytes < 1 || tbytes > 2)
{
fprintf(stderr, "[ERROR] - Unsupported size of trace: %d!\n", tbytes);
return NULL;
}
iobuf->tbytes = tbytes;
iobuf->tmax = iobuf->omax * 150; // assumption: in average 150 trace points per overlap
iobuf->ttop = 0;
if (tbytes == 1)
iobuf->trace = (uint8*) malloc(sizeof(uint8) * iobuf->tmax);
else
iobuf->trace = (uint16*) malloc(sizeof(uint16) * iobuf->tmax);
if (iobuf->trace == NULL)
{
fprintf(stderr, "[ERROR] - Cannot allocate trace buffer of size: %llu!\n", iobuf->tmax);
return NULL;
}
return iobuf;
}
int AddOverlapToBuffer(Overlap_IO_Buffer *iobuf, Overlap *ovl, int tbytes)
{
if (iobuf == NULL)
{
fprintf(stderr, "[ERROR] - Cannot add overlap to Overlap_IO_Buffer. Buffer is NULL!\n");
return 1;
}
// reallocate buffers
if (iobuf->otop == iobuf->omax)
{
iobuf->omax = (iobuf->omax * 1.2) + 1000;
iobuf->ovls = (Overlap*) realloc(iobuf->ovls, sizeof(Overlap) * iobuf->omax);
if (iobuf->ovls == NULL)
{
fprintf(stderr, "[ERROR] - Cannot add increase overlap buffer size to %d!\n", iobuf->omax);
return 1;
}
}
if (ovl->path.trace != NULL && (iobuf->no_trace == 0))
{
if (iobuf->ttop + (tbytes * ovl->path.tlen) >= iobuf->tmax)
{
iobuf->tmax = (iobuf->tmax * 1.2) + 1000;
void *t;
if (iobuf->tbytes == 1)
t = (uint8*) realloc(iobuf->trace, sizeof(uint8) * iobuf->tmax);
else
t = (uint16*) realloc(iobuf->trace, sizeof(uint16) * iobuf->tmax);
if (t == NULL)
{
fprintf(stderr, "[ERROR] - Cannot add increase trace point buffer size to %llu!\n", iobuf->tmax);
return 1;
}
if (t != iobuf->trace)
{
// adjust trace offset
int i, cumOff = 0;
for (i = 0; i < iobuf->otop; i++)
{
if (iobuf->tbytes == 1)
iobuf->ovls[i].path.trace = (uint8*)t + cumOff;
else
iobuf->ovls[i].path.trace = (uint16*)t + cumOff;
cumOff += iobuf->ovls[i].path.tlen;
}
iobuf->trace = t;
}
}
}
// add overlap
Overlap *o = iobuf->ovls + iobuf->otop;
o->aread = ovl->aread;
o->bread = ovl->bread;
o->flags = ovl->flags;
o->path.abpos = ovl->path.abpos;
o->path.aepos = ovl->path.aepos;
o->path.bbpos = ovl->path.bbpos;
o->path.bepos = ovl->path.bepos;
o->path.diffs = ovl->path.diffs;
// add trace
if (ovl->path.trace == NULL || iobuf->no_trace)
{
o->path.trace = NULL;
o->path.tlen = 0;
}
else
{
o->path.tlen = ovl->path.tlen;
memcpy(iobuf->trace + iobuf->ttop, ovl->path.trace, tbytes * ovl->path.tlen);
o->path.trace = iobuf->trace + iobuf->ttop;
}
// adjust offsets
iobuf->otop++;
iobuf->ttop += tbytes * ovl->path.tlen;
return 0;
}
static int SORT_OVL(const void *x, const void *y)
{
Overlap* l = (Overlap *) x;
Overlap* r = (Overlap *) y;
int al, ar;
int bl, br;
int cl, cr;
int pl, pr;
al = l->aread;
bl = l->bread;
ar = r->aread;
br = r->bread;
// check areads
if (al != ar)
return (al - ar);
// check breads
if (bl != br)
return (bl - br);
// check orientation
cl = COMP(l->flags);
cr = COMP(r->flags);
if (cl != cr)
return (cl - cr);
// check check alignment beg position in aread
pl = l->path.abpos;
pr = r->path.abpos;
if (pl != pr)
return (pl - pr);
// check check alignment end position in aread
pl = l->path.aepos;
pr = r->path.aepos;
if (pl != pr)
return (pl - pr);
// check check alignment beg position in bread
pl = l->path.bbpos;
pr = r->path.bbpos;
if (pl != pr)
return (pl - pr);
// check check alignment end position in bread
pl = l->path.bepos;
pr = r->path.bepos;
if (pl != pr)
return (pl - pr);
if (l < r)
return (-1);
else if (l > r)
return (1);
else
return (0);
}
void Write_Overlap_Buffer(Align_Spec *spec, char *dirName1, char *dirName2, char *ablock, char* bblock, int lastRead)
{
// sort all overlaps
Overlap_IO_Buffer *buf = OVL_IO_Buffer(spec);
int nthreads = Num_Threads(spec);
int symmetric = Symmetric(spec);
int only_identity = Only_Identity(spec);
int nallOvls = 0;
int i, j;
for (i = 0; i < nthreads; i++)
nallOvls += buf[i].otop;
// TODO use smaller chunks for real sorting and merging
Overlap *allOvls = (Overlap*) malloc(sizeof(Overlap) * nallOvls);
if (allOvls == NULL)
{
fprintf(stderr, "[ERROR] - Write_Overlap_Buffer: Cannot create file overlap buffer for all threads\n");
exit(1);
}
int count = 0;
for (i = 0; i < nthreads; i++)
for (j = 0; j < buf[i].otop; j++)
if (only_identity)
{
if (buf[i].ovls[j].aread == buf[i].ovls[j].bread)
allOvls[count++] = buf[i].ovls[j];
}
else
allOvls[count++] = buf[i].ovls[j];
if (only_identity)
nallOvls = count;
assert(count == nallOvls);
// sort overlaps
qsort(allOvls, nallOvls, sizeof(Overlap), SORT_OVL);
// get blocks ids and root
int ablockID, bblockID;
char *aroot = malloc(strlen(ablock) + 10);
char *broot = malloc(strlen(bblock) + 10);
ablockID = bblockID = 0;
{
char *dot;
dot = strrchr(ablock, '.');
if (dot != NULL)
{
ablockID = atoi(++dot);
snprintf(aroot, dot - ablock, "%s", ablock);
}
dot = strrchr(bblock, '.');
if (dot != NULL)
{
bblockID = atoi(++dot);
snprintf(broot, dot - bblock, "%s", bblock);
}
}
// if parts are equal, then dump out all overlaps into a single file
if (strcmp(ablock, bblock) == 0 || symmetric == 0)
{
char *path = (char*) malloc(strlen(aroot) + strlen(broot) + 40);
if (path == NULL)
{
fprintf(stderr, "[ERROR] - Write_Overlap_Buffer: Cannot create file name buffer\n");
exit(1);
}
if (ablockID > 0)
sprintf(path, "%s/%s.%d.%s.%d.las", dirName1, aroot, ablockID, broot, bblockID);
else
sprintf(path, "%s.las", ablock);
FILE *out = fopen(path, "w");
if (out == NULL)
{
fprintf(stderr, "[ERROR] - Write_Overlap_Buffer: Cannot open file %s for writing\n", path);
exit(1);
}
int64 nhits = 0;
int tspace = Trace_Spacing(spec);
int tbytes = buf->tbytes;
fwrite(&nhits, sizeof(int64), 1, out);
fwrite(&tspace, sizeof(int), 1, out);
for (j = 0; j < nallOvls; j++, nhits++)
Write_Overlap(out, allOvls + j, tbytes);
assert(nhits == nallOvls);
rewind(out);
fwrite(&nhits, sizeof(int64), 1, out);
fclose(out);
free(path);
}
else // dump out ablock-vs-bblock ovls into one file and bblock-vs-ablock into a second file
{
char *tmp = (char*) malloc(strlen(aroot) + strlen(broot) + 40);
char *path1 = (char*) malloc(strlen(aroot) + strlen(broot) + 40);
char *path2 = (char*) malloc(strlen(aroot) + strlen(broot) + 40);
if (path1 == NULL || path2 == NULL)
{
fprintf(stderr, "[ERROR] - Write_Overlap_Buffer: Cannot create file name buffers\n");
exit(1);
}
if (ablockID > 0)
{
if (bblockID > 0)
{
sprintf(path1, "%s/%s.%d.%s.%d.las", dirName1, aroot, ablockID, broot, bblockID);
sprintf(path2, "%s/%s.%d.%s.%d.las", dirName2, broot, bblockID, aroot, ablockID);
}
else
{
sprintf(path1, "%s/%s.%d.%s.las", dirName1, aroot, ablockID, bblock);
sprintf(path2, "%s.%s.%d.las", bblock, aroot, ablockID);
}
}
else
{
if (bblockID > 0)
{
sprintf(path1, "%s.%s.%d.las", ablock, broot, bblockID);
sprintf(path2, "%s/%s.%d.%s.las", dirName2, broot, bblockID, ablock);
}
else
{
sprintf(path1, "%s.%s.las", ablock, bblock);
sprintf(path2, "%s.%s.las", bblock, ablock);
}
}
if (bblockID < ablockID)
{
tmp = path1;
path1 = path2;
path2 = tmp;
}
// printf("path1: %s, path2: %s\n", path1, path2);
// dump out reads to first overlap file
FILE *out = fopen(path1, "w");
if (out == NULL)
{
fprintf(stderr, "[ERROR] - Write_Overlap_Buffer: Cannot open file %s for writing\n", path1);
exit(1);
}
int64 nhits = 0;
int tspace = Trace_Spacing(spec);
int tbytes = buf->tbytes;
fwrite(&nhits, sizeof(int64), 1, out);
fwrite(&tspace, sizeof(int), 1, out);
for (j = 0; j < nallOvls; j++, nhits++)
{
if (allOvls[j].aread > lastRead)
break;
Write_Overlap(out, allOvls + j, tbytes);
}
rewind(out);
fwrite(&nhits, sizeof(int64), 1, out);
fclose(out);
// dump out reads to second overlap file
out = fopen(path2, "w");
if (out == NULL)
{
fprintf(stderr, "[ERROR] - Write_Overlap_Buffer: Cannot open file %s for writing\n", path2);
exit(1);
}
nhits = 0;
fwrite(&nhits, sizeof(int64), 1, out);
fwrite(&tspace, sizeof(int), 1, out);
for (; j < nallOvls; j++, nhits++)
Write_Overlap(out, allOvls + j, tbytes);
rewind(out);
fwrite(&nhits, sizeof(int64), 1, out);
fclose(out);
// cleanup
free(path1);
free(path2);
}
// cleanup
free(allOvls);
}
void Reset_Overlap_Buffer(Align_Spec* spec)
{
Overlap_IO_Buffer *buf = OVL_IO_Buffer(spec);
int nthreads = Num_Threads(spec);
int i;
for (i = 0; i < nthreads; i++)
{
buf[i].otop = 0;
buf[i].ttop = 0;
}
}
|
MartinPippel/DAmar
|
db/TKcat.c
|
<filename>db/TKcat.c
/************************************************************************************\
* *
* Copyright (c) 2014, Dr. <NAME> (EWM). All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without modification, *
* are permitted provided that the following conditions are met: *
* *
* · Redistributions of source code must retain the above copyright notice, this *
* list of conditions and the following disclaimer. *
* *
* · Redistributions in binary form must reproduce the above copyright notice, this *
* list of conditions and the following disclaimer in the documentation and/or *
* other materials provided with the distribution. *
* *
* · The name of EWM may not be used to endorse or promote products derived from *
* this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY EWM ”AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, *
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND *
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL EWM BE LIABLE *
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS *
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY *
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING *
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN *
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
* *
* For any issues regarding this software and its use, contact EWM at: *
* *
* <NAME>r. *
* Bautzner Str. 122e *
* 01099 Dresden *
* GERMANY *
* Email: <EMAIL> *
* *
\************************************************************************************/
/********************************************************************************************
*
* Concate in block order all "block tracks" <DB>.<track>.# into a single track
* <DB>.<track>
*
* Author: <NAME>
* Date : June 2014
*
********************************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "DB.h"
#ifdef HIDE_FILES
#define PATHSEP "/."
#else
#define PATHSEP "/"
#endif
// needed for getopt
extern char *optarg;
extern int optind, opterr, optopt;
static void usage()
{
fprintf(stderr, "[-vd] <path:db> <track:name>\n");
}
int main(int argc, char* argv[])
{
char* prefix;
FILE* aout, *dout;
int VERBOSE = 0;
int DELETE = 0;
// Process arguments
int c;
opterr = 0;
while ((c = getopt(argc, argv, "vd")) != -1)
{
switch (c)
{
case 'v':
VERBOSE = 1;
break;
case 'd':
DELETE = 1;
break;
default:
usage();
exit(1);
}
}
if (argc - optind != 2)
{
usage();
exit(1);
}
char* path_db = argv[optind];
char* track_name = argv[optind+1];
{
char* pwd, *root;
pwd = PathTo(path_db);
root = Root(path_db, ".db");
prefix = Strdup(Catenate(pwd, PATHSEP, root, "."), "Allocating track name");
free(pwd);
free(root);
aout = fopen(Catenate(prefix, track_name, ".", "anno"), "r");
if (aout != NULL)
{
fprintf(stderr, "%s: Track file %s%s.anno already exists!\n", Prog_Name, prefix, track_name);
fclose(aout);
exit (1);
}
dout = fopen(Catenate(prefix, track_name, ".", "data"), "r");
if (dout != NULL)
{
fprintf(stderr, "%s: Track file %s%s.data already exists!\n", Prog_Name, prefix, track_name);
fclose(aout);
exit (1);
}
aout = Fopen(Catenate(prefix, track_name, ".", "anno"), "w");
if (aout == NULL)
{
exit (1);
}
dout = NULL;
}
{
int tracktot, tracksiz;
int64 trackoff;
int nfiles;
char data[1024];
void* anno;
anno = NULL;
trackoff = 0;
tracktot = tracksiz = 0;
fwrite(&tracktot, sizeof(int), 1, aout);
fwrite(&tracksiz, sizeof(int), 1, aout);
nfiles = 0;
if (VERBOSE)
{
printf("concatenating ... \n");
}
while (1)
{
FILE* afile, *dfile;
int i, size, tracklen;
afile = fopen(Numbered_Suffix(prefix, nfiles + 1, Catenate(".", track_name, ".", "anno")), "r");
if (afile == NULL)
{
break;
}
dfile = fopen(Numbered_Suffix(prefix, nfiles + 1, Catenate(".", track_name, ".", "data")), "r");
if (VERBOSE)
{
printf(" %s%d.%s\n", prefix, nfiles + 1, track_name);
}
if (fread(&tracklen, sizeof(int), 1, afile) != 1)
{
SYSTEM_ERROR;
}
if (fread(&size, sizeof(int), 1, afile) != 1)
{
SYSTEM_ERROR;
}
if (nfiles == 0)
{
tracksiz = size;
if (dfile != NULL)
{
dout = Fopen(Catenate(prefix, track_name, ".", "data"), "w");
if (dout == NULL)
{
fclose(afile);
fclose(dfile);
goto error;
}
}
else
{
anno = Malloc(size, "Allocating annotation record");
if (anno == NULL)
{
fclose(afile);
goto error;
}
}
}
else
{
int escape = 1;
if (tracksiz != size)
{
fprintf(stderr, "%s: Track block %d does not have the same annotation size (%d)",
Prog_Name, nfiles + 1, size);
fprintf(stderr, " as previous blocks (%d)\n", tracksiz);
}
else if (dfile == NULL && dout != NULL)
fprintf(stderr, "%s: Track block %d does not have data but previous blocks do\n",
Prog_Name, nfiles + 1);
else if (dfile != NULL && dout == NULL)
fprintf(stderr, "%s: Track block %d has data but previous blocks do not\n",
Prog_Name, nfiles + 1);
else
{
escape = 0;
}
if (escape)
{
fclose(afile);
if (dfile != NULL)
{
fclose(dfile);
}
if (anno != NULL)
{
free(anno);
}
goto error;
}
}
if (dfile != NULL)
{
int64 dlen;
if (size == 4)
{
int anno4;
for (i = 0; i < tracklen; i++)
{
if (fread(&anno4, sizeof(int), 1, afile) != 1)
{
SYSTEM_ERROR;
}
anno4 += trackoff;
fwrite(&anno4, sizeof(int), 1, aout);
}
if (fread(&anno4, sizeof(int), 1, afile) != 1)
{
SYSTEM_ERROR;
}
dlen = anno4;
}
else
{
int64 anno8;
for (i = 0; i < tracklen; i++)
{
if (fread(&anno8, sizeof(int64), 1, afile) != 1)
{
SYSTEM_ERROR;
}
anno8 += trackoff;
fwrite(&anno8, sizeof(int64), 1, aout);
}
if (fread(&anno8, sizeof(int64), 1, afile) != 1)
{
SYSTEM_ERROR;
}
dlen = anno8;
}
trackoff += dlen;
for (i = 1024; i < dlen; i += 1024)
{
if (fread(data, 1024, 1, dfile) != 1)
{
SYSTEM_ERROR;
}
fwrite(data, 1024, 1, dout);
}
i -= 1024;
if (i < dlen)
{
if (fread(data, dlen - i, 1, dfile) != 1)
{
SYSTEM_ERROR;
}
fwrite(data, dlen - i, 1, dout);
}
}
else
{
for (i = 0; i < tracklen; i++)
{
if (fread(anno, size, 1, afile) != 1)
{
SYSTEM_ERROR;
}
fwrite(anno, size, 1, aout);
}
}
tracktot += tracklen;
nfiles += 1;
if (dfile != NULL)
{
fclose(dfile);
}
fclose(afile);
}
if (nfiles == 0)
{
fprintf(stderr, "%s: Couldn't find first track block %s1.%s.anno\n",
Prog_Name, prefix, track_name);
goto error;
}
else
{
if (dout != NULL)
{
if (tracksiz == 4)
{
int anno4 = trackoff;
fwrite(&anno4, sizeof(int), 1, aout);
}
else
{
int64 anno8 = trackoff;
fwrite(&anno8, sizeof(int64), 1, aout);
}
}
else
{
fwrite(anno, tracksiz, 1, aout);
free(anno);
}
rewind(aout);
fwrite(&tracktot, sizeof(int), 1, aout);
fwrite(&tracksiz, sizeof(int), 1, aout);
}
}
fclose(aout);
if (dout != NULL)
{
fclose(dout);
}
if (DELETE)
{
int nfiles = 1;
while (1)
{
if ( unlink(Numbered_Suffix(prefix, nfiles, Catenate(".", track_name, ".", "anno"))) != 0 )
{
break;
}
unlink(Numbered_Suffix(prefix, nfiles, Catenate(".", track_name, ".", "data")));
nfiles++;
}
}
free(prefix);
exit (0);
error:
fclose(aout);
unlink(Catenate(prefix, track_name, ".", "anno"));
if (dout != NULL)
{
fclose(dout);
unlink(Catenate(prefix, track_name, ".", "data"));
}
free(prefix);
exit (1);
}
|
MartinPippel/DAmar
|
lib/trim.c
|
<filename>lib/trim.c<gh_stars>10-100
#include <stdlib.h>
#include <sys/param.h>
#include <assert.h>
#include <string.h>
#include "trim.h"
#include "lib/oflags.h"
#include "lib/utils.h"
#include "lib/colors.h"
#undef DEBUG_VALIDATE
#undef DEBUG_TRIM
static void align(TRIM* trim, Overlap* ovl, int ab, int ae, int bb, int be)
{
#ifdef DEBUG_TRIM
printf("align %d %d %d %d", ab, ae, bb, be);
#endif
Alignment* align = &(trim->align);
Path* path = trim->align.path;
if (trim->rl)
{
Read_Loader* rl = trim->rl;
rl_load_read(rl, ovl->aread, align->aseq, 0);
rl_load_read(rl, ovl->bread, align->bseq, 0);
}
else
{
Load_Read(trim->db, ovl->aread, align->aseq, 0);
Load_Read(trim->db, ovl->bread, align->bseq, 0);
}
align->alen = DB_READ_LEN(trim->db, ovl->aread);
align->blen = DB_READ_LEN(trim->db, ovl->bread);
if (ovl->flags & OVL_COMP)
{
Complement_Seq(trim->align.bseq, align->blen);
}
path->diffs = MAX((ae - ab) + (be - bb), 30);
path->abpos = ab;
path->aepos = ae;
path->bbpos = bb;
path->bepos = be;
Compute_Alignment(align, trim->align_work, DIFF_ALIGN, trim->twidth);
// { Alignment extra;
// Path pcopy;
//
// pcopy = *jpath;
// extra = *align;
// pcopy.trace = tbuf->trace + (uint64) jpath->trace;
// extra.path = &pcopy;
// Compute_Trace_PTS(&extra,work,MR_tspace,GREEDIESTX);
// Print_Reference(stdout,align, trim->align_work,8,100,10,0,6);
// fflush(stdout);
// }
#ifdef DEBUG_TRIM
printf(" -> %d\n", path->diffs);
#endif
}
static void eval_trace(TRIM* trim, int stop_b, int* stop_a, int* diff_left, int* diff_right)
{
// int twidth = trim->twidth;
int a = trim->align.path->abpos;
int b = trim->align.path->bbpos;
int p, t;
int diffs = 0;
int matches = 0;
// int aprev = a;
// int bprev = b;
// int tcur = 0;
for (t = 0; t < trim->align.path->tlen; t++)
{
if ((p = ((int*)(trim->align.path->trace))[t]) < 0)
{
p = -p - 1;
while (a < p)
{
if (trim->align.aseq[a] != trim->align.bseq[b]) diffs++;
else matches++;
a += 1;
b += 1;
if (b == stop_b)
{
*stop_a = a;
*diff_left = diffs;
diffs = 0;
}
}
diffs++;
b += 1;
if (b == stop_b)
{
*stop_a = a;
*diff_left = diffs;
diffs = 0;
}
}
else
{
p--;
while (b < p)
{
if (trim->align.aseq[a] != trim->align.bseq[b]) diffs++;
else matches++;
a += 1;
b += 1;
if (b == stop_b)
{
*stop_a = a;
*diff_left = diffs;
diffs = 0;
}
}
diffs++;
a += 1;
}
}
p = trim->align.path->aepos;
while (a < p)
{
if (trim->align.aseq[a] != trim->align.bseq[b]) diffs++;
else matches++;
a += 1;
b += 1;
if (b == stop_b)
{
*stop_a = a;
*diff_left = diffs;
diffs = 0;
}
}
*diff_right = diffs;
}
#ifdef DEBUG_TRIM
static void print_trace(Overlap* ovl)
{
ovl_trace* trace = ovl->path.trace;
int tlen = ovl->path.tlen;
int b = ovl->path.bbpos;
int i;
for (i = 0; i < tlen; i += 2)
{
if ( i > 0 && i%10 == 0 )
{
printf("\n");
}
printf("%5d (%3d %3d) ", b, trace[i], trace[i+1]);
b += trace[i+1];
}
printf("%5d\n", b);
}
#endif
void trim_overlap(TRIM* trim, Overlap* ovl)
{
ovl_trace* trace = ovl->path.trace;
trim->nOvls++;
trim->nOvlBases += (ovl->path.aepos - ovl->path.abpos) + (ovl->path.bepos - ovl->path.bbpos);
int a = ovl->aread;
int b = ovl->bread;
int trim_a_left, trim_a_right;
get_trim(trim->db, trim->track, a, &trim_a_left, &trim_a_right);
int trim_b_left, trim_b_right;
get_trim(trim->db, trim->track, b, &trim_b_left, &trim_b_right);
if (trim_a_left >= trim_a_right || trim_b_left >= trim_b_right)
{
ovl->flags |= OVL_DISCARD | OVL_TRIM;
return ;
}
if (ovl->flags & OVL_COMP)
{
int tmp = trim_b_left;
int ovlBLen = DB_READ_LEN(trim->db, ovl->bread);
trim_b_left = ovlBLen - trim_b_right;
trim_b_right = ovlBLen - tmp;
}
int abt = MAX(trim_a_left, ovl->path.abpos);
int aet = MIN(trim_a_right, ovl->path.aepos);
int bbt = MAX(trim_b_left, ovl->path.bbpos);
int bet = MIN(trim_b_right, ovl->path.bepos);
if (abt >= aet || bbt >= bet)
{
ovl->flags |= OVL_DISCARD | OVL_TRIM;
return ;
}
if (abt == ovl->path.abpos && aet == ovl->path.aepos &&
bbt == ovl->path.bbpos && bet == ovl->path.bepos)
{
return ;
}
#ifdef DEBUG_TRIM
printf("%6d (%5d) %c %6d (%5d) " ANSI_COLOR_GREEN "OVL" ANSI_COLOR_RESET " %5d..%5d %5d..%5d " ANSI_COLOR_GREEN "TRIM" ANSI_COLOR_RESET " %5d..%5d %5d..%5d\n",
a, DB_READ_LEN(trim->db, ovl->aread), ovl->flags & OVL_COMP ? 'c' : 'n', b, DB_READ_LEN(trim->db, ovl->bread),
ovl->path.abpos, ovl->path.aepos,
ovl->path.bbpos, ovl->path.bepos,
trim_a_left, trim_a_right,
trim_b_left, trim_b_right);
#endif
if (abt != ovl->path.abpos || aet != ovl->path.aepos)
{
int seg_old = ovl->path.abpos / trim->twidth;
int seg_new = abt / trim->twidth;
ovl->path.tlen -= 2 * (seg_new - seg_old);
int j = 0;
while (seg_new != seg_old)
{
ovl->path.bbpos += trace[j+1];
j += 2;
seg_old++;
}
trace += j;
ovl->path.trace += sizeof(ovl_trace) * j;
seg_old = (ovl->path.aepos - 1) / trim->twidth;
seg_new = (aet - 1) / trim->twidth;
j = ovl->path.tlen - 2;
while (seg_new != seg_old)
{
ovl->path.bepos -= trace[j+1];
j -= 2;
seg_old--;
}
ovl->path.tlen = j + 2;
ovl->path.abpos = MAX(trim_a_left, ovl->path.abpos);
ovl->path.aepos = MIN(trim_a_right, ovl->path.aepos);
#ifdef DEBUG_TRIM
printf(ANSI_COLOR_BLUE);
#endif
}
#ifdef DEBUG_TRIM
printf("%35s %5d..%5d %5d..%5d\n", "",
ovl->path.abpos, ovl->path.aepos,
ovl->path.bbpos, ovl->path.bepos);
printf(ANSI_COLOR_RESET);
#endif
trim->nTrimmedOvls++;
bbt = MAX(trim_b_left, ovl->path.bbpos);
bet = MIN(trim_b_right, ovl->path.bepos);
if (bbt < bet && (bbt != ovl->path.bbpos || bet != ovl->path.bepos))
{
int abpos, aepos, bbpos, bepos, j;
// align segment on the left
bbpos = ovl->path.bbpos;
if (bbpos < bbt)
{
// printf("left trim\n");
abpos = ovl->path.abpos;
aepos = (abpos / trim->twidth + 1) * trim->twidth;
bepos = bbpos + trace[1];
// print_trace(ovl);
for (j = 2; j < ovl->path.tlen; j += 2)
{
if (bbpos <= bbt && bepos > bbt)
{
// printf("L %d %5d..%5d %5d..%5d\n", j, abpos, aepos, bbpos, bepos);
break;
}
abpos = aepos;
aepos += trim->twidth;
bbpos = bepos;
bepos += trace[j+1];
}
if (bbpos != bbt)
{
align(trim, ovl, abpos, aepos, bbpos, bepos);
int stop_a, diffs_left, diffs_right;
eval_trace(trim, bbt, &stop_a, &diffs_left, &diffs_right);
trace[j-1] = bepos - bbt;
trace[j-2] = diffs_right;
// rare case, see e.coli dataset 729 -> 15957 for an example
if (aepos == stop_a) stop_a--;
trim->nTrimmedBases += (stop_a - ovl->path.abpos) + (bbt - ovl->path.bbpos);
ovl->path.abpos = stop_a;
ovl->path.bbpos = bbt;
// printf("STOP @ %5d %5d DIFFS %2d %2d\n", stop_a, bbt, diffs_left, diffs_right);
}
else
{
trim->nTrimmedBases += (abpos - ovl->path.abpos) + (bbpos - ovl->path.bbpos);
ovl->path.abpos = abpos;
ovl->path.bbpos = bbpos;
}
trace += j - 2;
ovl->path.trace += sizeof(ovl_trace) * (j - 2);
ovl->path.tlen -= j - 2;
// print_trace(ovl);
}
// align segment on the right
bepos = ovl->path.bepos;
if (bepos > bet)
{
aepos = ovl->path.aepos;
abpos = (aepos % trim->twidth) ? aepos - (aepos % trim->twidth) : aepos - trim->twidth;
bbpos = bepos - trace[ ovl->path.tlen - 1 ];
// print_trace(ovl);
for (j = ovl->path.tlen - 4; j >= 0; j -= 2)
{
if (bbpos < bet && bepos >= bet)
{
// printf("R %d %5d..%5d %5d..%5d\n", ovl->path.tlen - j-2, abpos, aepos, bbpos, bepos);
break;
}
aepos = abpos;
abpos -= trim->twidth;
bepos = bbpos;
bbpos -= trace[j+1];
}
if (bepos != bet)
{
align(trim, ovl, abpos, aepos, bbpos, bepos);
int stop_a, diffs_left, diffs_right;
eval_trace(trim, bet, &stop_a, &diffs_left, &diffs_right);
trim->nTrimmedBases += (ovl->path.aepos - stop_a) + (ovl->path.bepos - bet);
ovl->path.aepos = stop_a;
ovl->path.bepos = bet;
trace[j+2] = diffs_left;
trace[j+3] = bet - bbpos;
// printf("STOP @ %5d %5d DIFFS %2d %2d\n", stop_a, bet, diffs_left, diffs_right);
}
else
{
trim->nTrimmedBases += (ovl->path.aepos - aepos) + (ovl->path.bepos - bepos);
ovl->path.aepos = aepos;
ovl->path.bepos = bepos;
}
ovl->path.tlen = j + 4;
// print_trace(ovl);
}
#ifdef DEBUG_TRIM
printf(ANSI_COLOR_BLUE);
#endif
}
#ifdef DEBUG_TRIM
printf("%35s %5d..%5d %5d..%5d nTOvl(%lld) nTBas(%lld)\n", "",
ovl->path.abpos, ovl->path.aepos,
ovl->path.bbpos, ovl->path.bepos,
trim->nTrimmedOvls, trim->nTrimmedBases
);
printf(ANSI_COLOR_RESET);
#endif
// this can happen if we trim the alignment to a very short length
// covering mostly noisy regions in either a or b
if (ovl->path.abpos >= ovl->path.aepos || ovl->path.bepos < trim_b_left || ovl->path.bbpos > trim_b_right)
{
ovl->flags |= OVL_DISCARD | OVL_TRIM;
}
else
{
ovl->path.diffs = 0;
int j;
for (j = 0; j < ovl->path.tlen; j += 2)
{
ovl->path.diffs += trace[j];
}
}
#ifdef DEBUG_VALIDATE
{
int cura = ovl->path.abpos;
int curb = ovl->path.bbpos;
int j;
for (j = 0; j < ovl->path.tlen; j += 2)
{
cura = (cura/trim->twidth + 1) * trim->twidth;
curb += trace[j+1];
}
assert(curb == ovl->path.bepos);
}
#endif
}
TRIM* trim_init(HITS_DB* db, ovl_header_twidth twidth, HITS_TRACK *track, Read_Loader *rl)
{
TRIM* trim = malloc( sizeof(TRIM) );
trim->db = db;
trim->twidth = twidth;
trim->track = track;
trim->align_work = New_Work_Data();
trim->align.path = &(trim->path);
trim->align.aseq = New_Read_Buffer(db);
trim->align.bseq = New_Read_Buffer(db);
trim->nTrimmedBases = 0;
trim->nTrimmedOvls = 0;
trim->nOvls = 0;
trim->nOvlBases = 0;
trim->rl = rl;
return trim;
}
void trim_close(TRIM* trim)
{
// track_close(trim->track);
Free_Work_Data(trim->align_work);
free(trim->align.aseq - 1);
free(trim->align.bseq - 1);
bzero(trim, sizeof(TRIM));
free(trim);
}
|
MartinPippel/DAmar
|
lib/anno.h
|
#pragma once
#define ANNO_TYPE_FLIP 1
#define ANNO_TYPE_WEAK 2
#define ANNO_TYPE_GAP 3
|
MartinPippel/DAmar
|
scrub/datander.c
|
/*********************************************************************************************\
*
* Find all local self-alignment between long, noisy DNA reads:
* Compare sequences in each supplied blocks against themselves search for local alignments
* of MIN_OVERLAP or more above the diagonal (A start coord > B start coord). An output
* stream of 'Overlap' records (see align.h) is written in binary to a set of files, one
* per thread, each encoding a given found local alignment. The -v option turns on a verbose
* reporting mode that reports progress and gives statistics on each major stage.
*
* The filter operates by looking for a pair of diagonal bands of width 2^'s' that contain
* a collection of exact matching 'k'-mers between positions of a sequence, such that the total
* number of bases covered by 'k'-mer hits is 'h'. k cannot be larger than 15 in the
* current implementation.
*
* For each subject, say XXX, the program outputs a file containing LAs of the form
* XXX.XXX.T#.las where # is the thread that detected and wrote out the collection of LAs.
* For example, if NTHREAD in the program is 4, then 4 files are output for each subject block.
*
* Author: <NAME>
* Date : March 27, 2016
*
*********************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <ctype.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <errno.h>
#include <sys/param.h>
#if defined(BSD)
#include <sys/sysctl.h>
#endif
#include "lib/oflags.h"
#include "lib/colors.h"
#include "lib/utils.h"
#include "lib/tracks.h"
#include "db/DB.h"
#include "tandem.h"
extern char *optarg;
extern int optind, opterr, optopt;
#define DEF_ARG_O "tan"
static void usage()
{
fprintf(stderr, "usage: \n\n");
fprintf(stderr, "datander [-v] [-kwhjls<int>] [-e<double(.70)] [-o<string(tan)] <subject:db|dam>\n\n");
fprintf(stderr, "options: -v ... verbose\n");
fprintf(stderr, " -k ... kmer length (defaults: raw pacbio reads: 12)\n");
fprintf(stderr, " -w ... diagonal band width (default: 4)\n");
fprintf(stderr, " -h ... hit theshold (in bp.s, default: 35\n");
fprintf(stderr, " -j ... number of threads (default: 4). Must be a power of 2!\n");
fprintf(stderr, " -e ... average correlation rate for local alignments (default: 0.7). Must be in [.5,1.)\n");
fprintf(stderr, " -l ... minimum alignment length (defaul: 500)\n");
fprintf(stderr, " -s ... trace spacing, i.e. report trace point every -s base pairs (default: raw pacbio reads: 100)\n");
fprintf(stderr, " -o ... output folder (default: %s)\n", DEF_ARG_O);
}
int VERBOSE; // Globally visible to tandem.c
int MINOVER;
static int read_DB(HITS_DB *block, char *name, int kmer)
{
int i, isdam;
isdam = Open_DB(name, block);
if (isdam < 0)
{
exit(1);
}
{
for (i = 0; i < block->nreads; i++)
if (block->reads[i].rlen < kmer)
{
fprintf(stderr, "%s: Block %s contains reads < %dbp long ! Run DBsplit.\n", Prog_Name, name, kmer);
exit(1);
}
}
Read_All_Sequences(block, 0);
return (isdam);
}
static void createSubdir(char *out)
{
struct stat s;
int err = stat(out, &s);
if (err == -1)
{
if (errno == ENOENT)
{
mkdir(out, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
}
else
{
fprintf(stderr, "Cannot create output directory: %s\n", out);
exit(1);
}
}
else
{
if (!S_ISDIR(s.st_mode))
{
fprintf(stderr, "Output directory name: \"%s\" exist - but its not a directory\n", out);
exit(1);
}
}
}
int main(int argc, char *argv[])
{
HITS_DB _bblock;
HITS_DB *bblock = &_bblock;
char *bfile;
char *broot;
Align_Spec *settings;
int isdam;
int KMER_LEN;
int BIN_SHIFT;
int HIT_MIN;
double AVE_ERROR;
int SPACING;
int NTHREADS;
char *OUT_DIR;
{
KMER_LEN = 12;
HIT_MIN = 35;
BIN_SHIFT = 4;
AVE_ERROR = .70;
SPACING = 100;
MINOVER = 500; // Globally visible to filter.c
NTHREADS = 4;
OUT_DIR = DEF_ARG_O;
// parse arguments
int c;
opterr = 0;
while ((c = getopt(argc, argv, "vk:w:h:e:l:s:o:j:")) != -1)
{
switch (c)
{
case 'v':
VERBOSE = 1;
break;
case 'k':
KMER_LEN = atoi(optarg);
break;
case 'w':
BIN_SHIFT = atoi(optarg);
break;
case 'h':
HIT_MIN = atoi(optarg);
break;
case 'e':
AVE_ERROR = atof(optarg);
break;
case 'l':
MINOVER = atoi(optarg);
break;
case 's':
SPACING = atoi(optarg);
break;
case 'j':
NTHREADS = atoi(optarg);
break;
case 'o':
OUT_DIR = optarg;
break;
default:
fprintf(stderr, "Unsupported option: %s\n", argv[optind - 1]);
usage();
exit(1);
}
}
if (KMER_LEN < 0)
{
fprintf(stderr, "invalid kmer length of %d\n", KMER_LEN);
exit(1);
}
if (HIT_MIN < 0)
{
fprintf(stderr, "invalid hit threshold of %d\n", HIT_MIN);
exit(1);
}
if (AVE_ERROR < .5 || AVE_ERROR >= 1.)
{
fprintf(stderr, "Average correlation must be in [.5,1.) (%g)\n", AVE_ERROR);
exit(1);
}
if (MINOVER < 0)
{
fprintf(stderr, "invalid minimum alignmnet length of (%d)\n", MINOVER);
exit(1);
}
if (SPACING < 0)
{
fprintf(stderr, "invalid trace spacing of (%d)\n", SPACING);
exit(1);
}
if (optind + 1 > argc)
{
fprintf(stderr, "[ERROR] - at least one subject block is required\n\n");
usage();
exit(1);
}
}
MINOVER *= 2;
if (Set_Filter_Params(KMER_LEN, BIN_SHIFT, HIT_MIN, NTHREADS))
{
fprintf(stderr, "Illegal combination of filter parameters\n");
exit(1);
}
/* Create subdirectory */
createSubdir(OUT_DIR);
/* Compare each block against itself */
{
int i;
broot = NULL;
for (i = optind; i < argc; i++)
{
bfile = argv[i];
isdam = read_DB(bblock, bfile, KMER_LEN);
if (isdam)
broot = Root(bfile, ".dam");
else
broot = Root(bfile, ".db");
settings = New_Align_Spec(AVE_ERROR, SPACING, bblock->freq, NTHREADS, 1, 0, 0, 0);
Match_Self(broot, bblock, settings);
Write_Overlap_Buffer(settings, OUT_DIR, OUT_DIR, broot, broot, bblock->ufirst + bblock->nreads - 1);
Reset_Overlap_Buffer(settings);
Free_Align_Spec(settings);
Close_DB(bblock);
}
}
exit(0);
}
|
MartinPippel/DAmar
|
db/fileUtils.h
|
<reponame>MartinPippel/DAmar<gh_stars>10-100
#ifndef _FASTA_UTILS
#define _FASTA_UTILS
#include <stdio.h>
// checks if fasta header has pacbio format
int isPacBioHeader(char* header);
typedef struct
{ int argc;
char **argv;
FILE *input;
int count;
char *name;
} File_Iterator;
File_Iterator *init_file_iterator(int argc, char **argv, FILE *input, int first);
int next_file(File_Iterator *it);
#define MAX_BUFFER 10001
typedef struct
{ FILE *input;
int lineno;
int read;
int beg;
int end;
} Read_Iterator;
Read_Iterator *init_read_iterator(FILE *input);
int next_read(Read_Iterator *it);
#endif //_FASTA_UTILS
|
MartinPippel/DAmar
|
lib/colors.h
|
#ifndef __COLOR_H
#define __COLOR_H
#define COLORIZE
#ifdef COLORIZE
#define ANSI_COLOR_RED "\x1b[31m"
#define ANSI_COLOR_GREEN "\x1b[32m"
#define ANSI_COLOR_YELLOW "\x1b[33m"
#define ANSI_COLOR_BLUE "\x1b[34m"
#define ANSI_COLOR_MAGENTA "\x1b[35m"
#define ANSI_COLOR_CYAN "\x1b[36m"
#define ANSI_COLOR_WHITE "\x1b[37m"
#define ANSI_COLOR_RESET "\x1b[0m"
#else
#define ANSI_COLOR_RED ""
#define ANSI_COLOR_GREEN ""
#define ANSI_COLOR_YELLOW ""
#define ANSI_COLOR_BLUE ""
#define ANSI_COLOR_MAGENTA ""
#define ANSI_COLOR_CYAN ""
#define ANSI_COLOR_WHITE ""
#define ANSI_COLOR_RESET ""
#endif // ifdef COLORIZE
#endif // ifndef __COLOR_H
|
MartinPippel/DAmar
|
msa/msa.c
|
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#include "lib/colors.h"
#include "msa.h"
#define CONS_MIN_COV_FRACTION 0.5 // base calling threshold
typedef struct
{
char* B; // sequence that gets aligned to
msa_profile_entry* A; // the profile B
int abpos, aepos; // regions to be aligned in A
int bbpos, bepos; // in B
int* ptp;
int ptpmax;
int ptpcur;
int* pPtPoints; // pairs of pass-through points <profile, sequence>
int nPtPoints; // number of pass-through points ( pairs * 2 )
int diffs_a; // number of insertions in A
int diffs_b; // number of insertions in B
msa_alignment_ctx* pCtx; // points to context, working storage
} msa_alignment;
static int match( char* a, int ia, msa_profile_entry* p, int ip )
{
msa_profile_entry* pEntry = ( p + ip );
char nMax = pEntry->counts[ 0 ];
char cMax = 0;
char nCount;
// loop unrolled
nCount = pEntry->counts[ 1 ];
if ( nCount > nMax )
{
nMax = nCount;
cMax = 1;
}
nCount = pEntry->counts[ 2 ];
if ( nCount > nMax )
{
nMax = nCount;
cMax = 2;
}
nCount = pEntry->counts[ 3 ];
if ( nCount > nMax )
{
nMax = nCount;
cMax = 3;
}
nCount = pEntry->counts[ 4 ];
if ( nCount >= nMax )
{
return 0;
}
return ( cMax == a[ ia ] );
}
static int v3_align_onp( msa_alignment* pAlign,
msa_profile_entry* A, int M, char* B, int N )
{
int** PVF = pAlign->pCtx->PVF; // wave->PVF;
int** PHF = pAlign->pCtx->PHF; // wave->PHF;
int D;
int del = M - N;
{
int *F0, *F1, *F2;
int* HF;
int low, hgh;
if ( del >= 0 )
{
low = 0;
hgh = del;
}
else
{
low = del;
hgh = 0;
}
F1 = PVF[ -2 ];
F0 = PVF[ -1 ];
for ( D = low - 1; D <= hgh + 1; D++ )
{
F1[ D ] = F0[ D ] = -2;
}
F0[ 0 ] = -1;
low += 1;
hgh -= 1;
for ( D = 0; 1; D += 1 )
{
int k, i, j;
int am, ac, ap;
msa_profile_entry* a;
F2 = F1;
F1 = F0;
F0 = PVF[ D ];
HF = PHF[ D ];
if ( ( D & 0x1 ) == 0 )
{
hgh += 1;
low -= 1;
}
F0[ hgh + 1 ] = F0[ low - 1 ] = -2;
#define FS_MOVE( mdir, pdir ) \
ac = F1[ k ] + 1; \
if ( ac < am ) \
if ( ap < am ) \
{ \
HF[ k ] = mdir; \
j = am; \
} \
else \
{ \
HF[ k ] = pdir; \
j = ap; \
} \
else if ( ap < ac ) \
{ \
HF[ k ] = 0; \
j = ac; \
} \
else \
{ \
HF[ k ] = pdir; \
j = ap; \
} \
\
if ( N < i ) \
while ( j < N && match( B, j, a, j ) ) \
j += 1; \
else \
while ( j < i && match( B, j, a, j ) ) \
j += 1; \
F0[ k ] = j;
j = -2;
a = A + hgh;
i = M - hgh;
for ( k = hgh; k > del; k-- )
{
ap = j + 1;
am = F2[ k - 1 ];
FS_MOVE( -1, 4 )
a -= 1;
i += 1;
}
j = -2;
a = A + low;
i = M - low;
for ( k = low; k < del; k++ )
{
ap = F2[ k + 1 ] + 1;
am = j;
FS_MOVE( 2, 1 )
a += 1;
i -= 1;
}
ap = F0[ del + 1 ] + 1;
am = j;
FS_MOVE( 2, 4 )
if ( F0[ del ] >= N )
{
break;
}
}
}
{
int k, h, m, e, c;
msa_profile_entry* a;
int ap = ( pAlign->pCtx->Aabs - A ) - 1; // (wave->Aabs - A) - 1;
int bp = ( B - pAlign->pCtx->Babs ) + 1; // (B - wave->Babs) + 1;
PHF[ 0 ][ 0 ] = 3;
c = N;
k = del;
e = PHF[ D ][ k ];
PHF[ D ][ k ] = 3;
while ( e != 3 )
{
h = k + e;
if ( e > 1 )
{
h -= 3;
}
else if ( e == 0 )
{
D -= 1;
}
else
{
D -= 2;
}
if ( h < k ) // => e = -1 or 2
{
a = A + k;
if ( k < 0 )
{
m = -k;
}
else
{
m = 0;
}
if ( PVF[ D ][ h ] <= c )
{
c = PVF[ D ][ h ] - 1;
}
while ( c >= m && match( B, c, a, c ) ) // a[c] == B[c])
{
c -= 1;
}
if ( e < 1 ) // => edge is 2, others are 1, and 0
{
if ( c <= PVF[ D + 2 ][ k + 1 ] )
{
e = 4;
h = k + 1;
D = D + 2;
}
else if ( c == PVF[ D + 1 ][ k ] )
{
e = 0;
h = k;
D = D + 1;
}
else
{
PVF[ D ][ h ] = c + 1;
}
}
else // => edge is 0, others are 1, and 2 (if k != del), 0 (otherwise)
{
if ( k == del )
{
m = D;
}
else
{
m = D - 2;
}
if ( c <= PVF[ m ][ k + 1 ] )
{
if ( k == del )
{
e = 4;
}
else
{
e = 1;
}
h = k + 1;
D = m;
}
else if ( c == PVF[ D - 1 ][ k ] )
{
e = 0;
h = k;
D = D - 1;
}
else
{
PVF[ D ][ h ] = c + 1;
}
}
}
m = PHF[ D ][ h ];
PHF[ D ][ h ] = e;
e = m;
k = h;
}
k = D = 0;
e = PHF[ D ][ k ];
while ( e != 3 )
{
h = k - e;
c = PVF[ D ][ k ];
if ( e > 1 )
{
h += 3;
}
else if ( e == 0 )
{
D += 1;
}
else
{
D += 2;
}
if ( h > k )
{
*( pAlign->pCtx->Stop ) = bp + c;
( pAlign->pCtx->Stop )++;
pAlign->diffs_b++;
// *wave->Stop++ = bp + c;
}
else if ( h < k )
{
*( pAlign->pCtx->Stop ) = ap - ( c + k );
( pAlign->pCtx->Stop )++;
pAlign->diffs_a++;
// *wave->Stop++ = ap - (c + k);
}
k = h;
e = PHF[ D ][ h ];
}
}
return ( D + abs( del ) );
}
static int v3_align( msa_alignment* align )
{
msa_alignment_ctx* pCtx = align->pCtx;
char* bseq;
msa_profile_entry* aseq;
int *points, tlen;
int ab, bb;
int ae, be;
int diffs;
aseq = align->A;
bseq = align->B;
tlen = align->nPtPoints;
points = align->pPtPoints;
{
int d, s;
int M, N;
int dmax, nmax, mmax;
int **PVF, **PHF;
M = align->aepos - align->abpos;
N = align->bepos - align->bbpos;
s = M > N ? M : N;
if ( s > pCtx->ntrace )
{
pCtx->ntrace = 1.2 * pCtx->ntrace + s;
pCtx->trace = (int*)realloc( pCtx->trace, sizeof( int ) * pCtx->ntrace );
}
mmax = 0;
nmax = 0;
dmax = 0;
ab = align->abpos;
bb = align->bbpos;
for ( d = 0; d < tlen; d += 2 )
{
ae = points[ d ];
be = points[ d + 1 ];
M = ae - ab;
N = be - bb;
if ( M < N )
{
diffs = M;
}
else
{
diffs = N;
}
if ( diffs > dmax )
{
dmax = diffs;
}
if ( M > mmax )
{
mmax = M;
}
if ( N > nmax )
{
nmax = N;
}
ab = ae;
bb = be;
}
ae = align->aepos;
be = align->bepos;
M = ae - ab;
N = be - bb;
if ( M < N )
{
diffs = M;
}
else
{
diffs = N;
}
if ( diffs > dmax )
{
dmax = diffs;
}
if ( M > mmax )
{
mmax = M;
}
if ( N > nmax )
{
nmax = N;
}
s = ( dmax + 3 ) * 2 * ( ( mmax + nmax + 3 ) * sizeof( int ) + sizeof( int* ) );
if ( s > pCtx->vecmax )
{
if ( s > 256 * 1024 * 1024 )
{
printf( "v3_align> skipping alignment. excessive amount of memory needed.\n" );
printf( "dmax = %d mmax = %d nmax = %d s = %d\n", dmax, mmax, nmax, s );
return 0;
}
pCtx->vecmax = s * 1.2 + 10000;
pCtx->vector = (int*)realloc( pCtx->vector, pCtx->vecmax );
}
pCtx->PVF = PVF = ( (int**)( pCtx->vector ) ) + 2;
pCtx->PHF = PHF = PVF + ( dmax + 3 );
// wave.PVF = PVF = ((int**) (work->vec.data())) + 2;
// wave.PHF = PHF = PVF + (dmax + 3);
s = mmax + nmax + 3;
PVF[ -2 ] = ( (int*)( PHF + ( dmax + 1 ) ) ) + ( nmax + 1 );
for ( d = -1; d <= dmax; d++ )
{
PVF[ d ] = PVF[ d - 1 ] + s;
}
PHF[ -2 ] = PVF[ dmax ] + s;
for ( d = -1; d <= dmax; d++ )
{
PHF[ d ] = PHF[ d - 1 ] + s;
}
}
pCtx->Stop = pCtx->trace;
pCtx->Aabs = aseq;
pCtx->Babs = bseq;
{
int i;
diffs = 0;
ab = align->abpos;
bb = align->bbpos;
for ( i = 0; i < tlen; i += 2 )
{
be = points[ i + 1 ];
ae = points[ i ];
diffs += v3_align_onp( align, aseq + ab, ae - ab, bseq + bb, be - bb );
ab = ae;
bb = be;
}
ae = align->aepos;
be = align->bepos;
diffs += v3_align_onp( align, aseq + ab, ae - ab, bseq + bb, be - bb );
}
pCtx->ntrace = pCtx->Stop - pCtx->trace;
// path->diffs = diffs;
return 1;
}
static char decode_base( unsigned char c )
{
assert( c <= 4 );
static const char* pcTable = "ACGT-";
return pcTable[ c ];
}
msa* msa_init()
{
msa* m = (msa*)malloc( sizeof( msa ) );
m->track = NULL;
m->tmax = 0;
m->curprof = 0;
m->profile = NULL;
m->maxprof = 0;
m->added = 0;
m->seq = NULL;
m->nseq = 0;
m->msa_len = NULL;
m->msa_seq = NULL;
m->msa_max = 0;
m->msa_smax = NULL;
m->msa_lgaps = NULL;
m->msa_ids = NULL;
m->aln_ctx = (msa_alignment_ctx*)malloc( sizeof( msa_alignment_ctx ) );
m->aln_ctx->ntrace = 0;
m->aln_ctx->trace = NULL;
m->aln_ctx->vecmax = 0;
m->aln_ctx->vector = NULL;
m->ptp = NULL;
m->ptpmax = 0;
return m;
}
void msa_free( msa* m )
{
free( m->profile );
free( m->ptp );
int i;
for ( i = 0; i < m->added; i++ )
{
free( m->msa_seq[ i ] );
}
free( m->msa_len );
free( m->msa_smax );
free( m->msa_seq );
free( m->msa_lgaps );
free( m->aln_ctx->trace );
free( m->aln_ctx->vector );
free( m->aln_ctx );
free( m->track );
free( m );
}
void msa_print( msa* m, FILE* fileOut, int b, int e )
{
int i;
b = ( b == -1 ? 0 : m->track[b] );
e = ( e == -1 ? m->curprof : m->track[e] );
for ( i = 0; i < m->added; i++ )
{
/*
int j;
for ( j = 0; j < m->msa_lgaps[ i ]; j++ )
{
putc( '-', fileOut );
}
fprintf( fileOut, "%s\n", m->msa_seq[ i ] );
*/
fprintf( fileOut, "%-8d %-5d ", m->msa_ids[ i ], m->msa_len[ i ] );
int j;
for ( j = b; j < m->msa_lgaps[ i ]; j++ )
{
putc( '-', fileOut );
}
char* beg = m->msa_seq[ i ] + MAX( b - m->msa_lgaps[ i ], 0 );
int len = ( e - b ) - MAX( m->msa_lgaps[ i ] - b, 0 );
fprintf( fileOut, "%.*s\n", len, beg );
}
}
void msa_print_simple( msa* m, FILE* filemsa, FILE* filerids, int b, int e )
{
int i;
b = m->track[ b ];
e = m->track[ e ];
for ( i = 0; i < m->added; i++ )
{
int j;
for ( j = b; j < m->msa_lgaps[ i ]; j++ )
{
putc( '-', filemsa );
}
char* beg = m->msa_seq[ i ] + MAX( b - m->msa_lgaps[ i ], 0 );
int len = ( e - b ) - MAX( m->msa_lgaps[ i ] - b, 0 );
fprintf( filemsa, "%.*s\n", len, beg );
fprintf( filerids, "%d\n", m->msa_ids[ i ] );
}
}
void msa_print_v( msa* m, FILE* fileOut )
{
char* cons = msa_consensus( m, 1 );
int col, row;
for ( col = 0; col < m->curprof; col++ )
{
putc( cons[ col ], fileOut );
// printf("%*s", indent, "");
for ( row = 0; row < m->added; row++ )
{
int abscol = col - m->msa_lgaps[ row ];
if ( abscol >= 0 && abscol < m->msa_len[ row ] )
{
putc( m->msa_seq[ row ][ abscol ], fileOut );
}
else
{
putc( ' ', fileOut );
}
}
putc( '\n', fileOut );
}
}
void msa_print_profile( msa* m, FILE* fileOut, int b, int e, int colorize )
{
msa_profile_entry* pEntry;
b = ( b == -1 ? 0 : m->track[ b ] );
e = ( e == -1 ? m->curprof : m->track[ e ] );
// counts
int i;
if ( colorize )
{
printf( ANSI_COLOR_BLUE );
}
printf( " " );
for ( i = b; i < e; i++ )
{
pEntry = m->profile + i;
fprintf( fileOut, "%7d", i % 100 );
}
if ( colorize )
{
printf( ANSI_COLOR_RESET );
}
fprintf( fileOut, "\n" );
int nBase;
for ( nBase = 0; nBase < 5; nBase++ )
{
fprintf( fileOut, "%c ", decode_base( nBase ) );
for ( i = b; i < e; i++ )
{
pEntry = m->profile + i;
fprintf( fileOut, "%7lu", pEntry->counts[ nBase ] );
}
fprintf( fileOut, "\n" );
}
// consensus
if ( colorize )
{
printf( ANSI_COLOR_RED );
}
char* pcCons = msa_consensus( m, 1 );
printf( "# " );
for ( i = b; i < e; i++ )
{
fprintf( fileOut, "%7c", pcCons[ i ] );
}
if ( colorize )
{
printf( ANSI_COLOR_RESET );
}
fprintf( fileOut, "\n" );
}
void msa_reset( msa* m )
{
m->curprof = 0;
m->added = 0;
}
static void msa_add_first( msa* m, char* seq, int len )
{
if ( len > m->maxprof )
{
m->maxprof = 1.2 * m->maxprof + len;
m->profile = realloc( m->profile, sizeof( msa_profile_entry ) * m->maxprof );
}
if ( len > m->tmax )
{
m->tmax = 1.2 * m->tmax + len;
m->track = realloc( m->track, sizeof( int ) * m->tmax );
}
m->curprof = len;
bzero( m->profile, sizeof( msa_profile_entry ) * m->maxprof );
int i;
for ( i = 0; i < len; i++ )
{
m->profile[ i ].counts[ (unsigned char)seq[ i ] ] = 1;
m->track[ i ] = i;
}
}
static void apply_gap( msa* m, int pos, int seq_from, int seq_to )
{
int i;
int abspos;
for ( i = seq_from; i < seq_to; i++ )
{
if ( pos <= m->msa_lgaps[ i ] )
{
m->msa_lgaps[ i ]++;
continue;
}
abspos = pos - m->msa_lgaps[ i ];
if ( abspos > m->msa_len[ i ] )
{
continue;
}
if ( m->msa_len[ i ] + 1 >= m->msa_smax[ i ] )
{
m->msa_smax[ i ] = m->msa_smax[ i ] * 1.2 + 100;
m->msa_seq[ i ] = realloc( m->msa_seq[ i ], m->msa_smax[ i ] );
}
memmove( m->msa_seq[ i ] + abspos + 1,
m->msa_seq[ i ] + abspos,
strlen( m->msa_seq[ i ] + abspos ) + 1 );
m->msa_seq[ i ][ abspos ] = '-';
m->msa_len[ i ]++;
}
}
void msa_add( msa* m, char* seq, int pb, int pe, int sb, int se, ovl_trace* trace, int tlen, int id )
{
int i;
/*
printf("add ");
for (i = sb; i < se; i++)
{
printf("%c", decode_base(seq[i]));
}
printf("\n");
*/
/*
if ( m->added > 0 && m->added % 10 == 0 )
{
for ( i = 0; i < m->curprof; i++ )
{
msa_profile_entry* pe = m->profile + i;
unsigned long sum = pe->counts[ 0 ] + pe->counts[ 1 ] + pe->counts[ 2 ] + pe->counts[ 3 ];
if ( sum < pe->counts[ 4 ] )
{
pe->counts[0] = pe->counts[1] = pe->counts[2] = pe->counts[3] = 0;
pe->counts[4] += sum;
}
}
}
*/
if ( m->msa_max <= m->added )
{
m->msa_max = m->msa_max * 1.2 + 10;
m->msa_seq = (char**)realloc( m->msa_seq, sizeof( char* ) * m->msa_max );
m->msa_smax = (int*)realloc( m->msa_smax, sizeof( int ) * m->msa_max );
m->msa_lgaps = (int*)realloc( m->msa_lgaps, sizeof( int ) * m->msa_max );
m->msa_len = (int*)realloc( m->msa_len, sizeof( int ) * m->msa_max );
m->msa_ids = (int*)realloc( m->msa_ids, sizeof( int ) * m->msa_max );
}
int smax = ( se - sb ) * 2;
m->msa_seq[ m->added ] = (char*)malloc( smax );
m->msa_smax[ m->added ] = smax;
for ( i = sb; i < se; i++ )
{
m->msa_seq[ m->added ][ i - sb ] = decode_base( seq[ i ] );
}
m->msa_seq[ m->added ][ i - sb ] = '\0';
m->msa_len[ m->added ] = i - sb; // se - sb;
m->msa_ids[ m->added ] = id;
if ( m->curprof == 0 )
{
m->msa_lgaps[ m->added ] = 0;
m->alen = se - sb;
msa_add_first( m, seq + sb, se - sb );
m->added++;
// consensus_print_profile(cns, stdout);
return;
}
msa_alignment aln;
aln.pCtx = m->aln_ctx;
aln.diffs_a = 0;
aln.diffs_b = 0;
aln.B = seq;
aln.bbpos = sb;
aln.bepos = se;
aln.A = m->profile;
// convert to profile relative coordinates
if ( pb != -1 )
{
aln.abpos = m->track[ pb ];
}
else
{
aln.abpos = 0;
}
if ( pe != -1 )
{
aln.aepos = m->track[ pe - 1 ] + 1;
}
else
{
aln.aepos = m->curprof;
}
m->msa_lgaps[ m->added ] = aln.abpos;
assert( aln.bbpos >= 0 );
assert( aln.bbpos < aln.bepos );
// prepare pass through points
if ( tlen > 0 )
{
int ptp = tlen - 2;
assert( ( ptp % 2 ) == 0 );
if ( ptp > m->ptpmax )
{
m->ptpmax = ptp * 1.2 + 100;
m->ptp = (int*)realloc( m->ptp, sizeof( int ) * m->ptpmax );
}
int ptp_p = ( pb / m->twidth ) * m->twidth;
int ptp_s = sb;
aln.nPtPoints = tlen - 2;
aln.pPtPoints = m->ptp;
for ( i = 1; i < tlen - 2; i += 2 )
{
ptp_p += m->twidth;
ptp_s += trace[ i ];
aln.pPtPoints[ i - 1 ] = m->track[ ptp_p ];
aln.pPtPoints[ i ] = ptp_s;
}
}
else
{
aln.nPtPoints = 0;
}
// align
if ( !v3_align( &aln ) )
{
return;
}
int c, p, b, n;
// enlarge profile if necessary
if ( m->curprof + aln.diffs_a > m->maxprof )
{
m->maxprof = m->maxprof * 2 + aln.diffs_a;
m->profile = (msa_profile_entry*)realloc( m->profile, sizeof( msa_profile_entry ) * m->maxprof );
bzero( m->profile + m->curprof, sizeof( msa_profile_entry ) * aln.diffs_a );
}
// apply trace to profile and sequence in reverse order
// thereby allowing us to perform the update in place
// profile overhang right
n = m->curprof - 1 + aln.diffs_a;
p = m->curprof - 1;
while ( p > aln.aepos - 1 )
{
m->profile[ n ] = m->profile[ p ];
p--;
n--;
}
b = aln.bepos - 1;
for ( i = aln.pCtx->ntrace - 1; i >= 0; i-- )
{
c = aln.pCtx->trace[ i ];
if ( c > 0 ) // dash before B[-c]
{
c--;
while ( c <= b )
{
m->profile[ n ] = m->profile[ p ];
m->profile[ n ].counts[ (unsigned char)aln.B[ b ] ]++;
n--;
b--;
p--;
}
apply_gap( m, c + aln.abpos - sb, m->added, m->added + 1 );
m->profile[ n ] = m->profile[ p ];
m->profile[ n ].counts[ 4 ]++;
n--;
p--;
}
else // dash before P[c]
{
c = -c;
c--;
while ( c <= p )
{
m->profile[ n ] = m->profile[ p ];
m->profile[ n ].counts[ (unsigned char)aln.B[ b ] ]++;
n--;
b--;
p--;
}
apply_gap( m, c, 0, m->added );
memset( m->profile + n, 0, sizeof( msa_profile_entry ) );
m->profile[ n ].counts[ (unsigned char)aln.B[ b ] ]++;
m->profile[ n ].counts[ 4 ] = m->profile[ n + 1 ].counts[ 0 ] +
m->profile[ n + 1 ].counts[ 1 ] +
m->profile[ n + 1 ].counts[ 2 ] +
m->profile[ n + 1 ].counts[ 3 ] +
m->profile[ n + 1 ].counts[ 4 ];
n--;
b--;
}
}
// aligned leftovers
while ( b >= aln.bbpos )
{
m->profile[ n ].counts[ (unsigned char)aln.B[ b ] ]++;
n--;
b--;
p--;
}
m->curprof += aln.diffs_a;
// keep track of where the bases of the main read have ended up in the profile
if ( aln.diffs_a > 0 )
{
int nPosIncr = 0;
int nPos = 0;
int t;
for ( t = 0; t < aln.pCtx->ntrace; t++ )
{
c = aln.pCtx->trace[ t ];
if ( c > 0 )
{
continue;
}
c = -c;
// c--;
while ( nPos < m->alen && m->track[ nPos ] < c - 1 )
{
m->track[ nPos ] += nPosIncr;
nPos++;
}
nPosIncr++;
}
while ( nPos < m->alen )
{
m->track[ nPos ] += nPosIncr;
nPos++;
}
}
m->added++;
// consensus_print_profile(cns, stdout, 1);
}
char* msa_consensus( msa* m, int dashes )
{
msa_profile_entry* pEntry;
if ( m->nseq <= m->curprof )
{
m->nseq = m->curprof + 1;
m->seq = (char*)realloc( m->seq, m->nseq );
}
int curseq = 0;
unsigned char nMax, cMax;
unsigned short nCovGaps, nCov;
int i, b;
for ( i = 0; i < m->curprof; i++ )
{
pEntry = m->profile + i;
nMax = cMax = 0;
// find out whether ACTG or - received the most "votes"
for ( b = 0; b < 5; b++ )
{
if ( pEntry->counts[ b ] > nMax )
{
nMax = pEntry->counts[ b ];
cMax = b;
}
}
nCov = pEntry->counts[ 0 ] + pEntry->counts[ 1 ] + pEntry->counts[ 2 ] + pEntry->counts[ 3 ];
nCovGaps = nCov + pEntry->counts[ 4 ];
if ( nCov < nCovGaps * CONS_MIN_COV_FRACTION )
{
cMax = 4;
}
// if it is a dash, but we don't have to add "-" to the consensus sequence
if ( cMax == 4 && !dashes )
{
continue;
}
m->seq[ curseq++ ] = decode_base( cMax );
}
m->seq[ curseq ] = '\0';
return m->seq;
}
|
MartinPippel/DAmar
|
db/DB2fa.c
|
/************************************************************************************\
* *
* Copyright (c) 2014, Dr. <NAME> (EWM). All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without modification, *
* are permitted provided that the following conditions are met: *
* *
* · Redistributions of source code must retain the above copyright notice, this *
* list of conditions and the following disclaimer. *
* *
* · Redistributions in binary form must reproduce the above copyright notice, this *
* list of conditions and the following disclaimer in the documentation and/or *
* other materials provided with the distribution. *
* *
* · The name of EWM may not be used to endorse or promote products derived from *
* this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY EWM ”AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, *
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND *
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL EWM BE LIABLE *
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS *
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY *
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING *
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN *
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
* *
* For any issues regarding this software and its use, contact EWM at: *
* *
* <NAME>r. *
* Bautzner Str. 122e *
* 01099 Dresden *
* GERMANY *
* Email: <EMAIL> *
* *
\************************************************************************************/
/********************************************************************************************
*
* Recreate all the .fasta files that have been loaded into a specified database.
*
* Author: <NAME>
* Date : May 2014
*
********************************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#include "DB.h"
#include "lib/tracks.h"
static void usage()
{
fprintf(stderr, "usage: [-vhUS] [-m <track>] [-w<int(80)>] <path:db>\n");
fprintf(stderr, "options: -v ... verbose\n");
fprintf(stderr, " -h ... print this help message\n");
fprintf(stderr, " -U ... upper case bases\n");
fprintf(stderr, " -w ... line width (default: 80)\n");
fprintf(stderr, " -m ... add track to fasta header (multiple -m possible)\n");
fprintf(stderr, " -S ... sort DB according read length (longest first) \n");
}
extern char *optarg;
extern int optind, opterr, optopt;
HITS_DB _db;
static int cmp_read_by_len(const void* a, const void* b)
{
return (_db.reads[*((int*) b)].rlen - _db.reads[*((int*) a)].rlen);
}
typedef struct
{
int from;
int to;
char *fileName;
char *readName;
} Prolog;
typedef struct
{
int numHeader;
int maxHeader;
Prolog *headers;
} DB_Header;
static void addProlog(DB_Header* dbh, int from, int to, char *fname, char *rname)
{
#if DEBUG
printf("addProlog, %d %d %s %s %d %d\n", from, to, fname, rname, strlen(fname), strlen(rname));
fflush(stdout);
#endif
if (dbh->maxHeader == 0)
{
dbh->maxHeader = 20;
dbh->headers = (Prolog*) malloc(sizeof(Prolog) * dbh->maxHeader);
if (dbh->headers == NULL)
{
fprintf(stderr, "[ERROR] - DB2fasta: Cannot allocate Prolog buffer\n.");
exit(1);
}
}
else if (dbh->maxHeader == dbh->numHeader)
{
dbh->maxHeader = (1.2 * dbh->numHeader) + 10;
dbh->headers = (Prolog*) realloc(dbh->headers, sizeof(Prolog) * dbh->maxHeader);
if (dbh->headers == NULL)
{
fprintf(stderr, "[ERROR] - DB2fasta: Cannot allocate Prolog buffer\n.");
exit(1);
}
}
Prolog *p = dbh->headers + dbh->numHeader;
bzero(p, sizeof(Prolog));
char *fileName = (char*) malloc(50);
if (fileName == NULL)
{
printf("[ERROR] - DB2fasta: Cannot allocate Prolog header buffer\n.");
exit(1);
}
char *readName = (char*) malloc(strlen(rname) + 10);
if (readName == NULL)
{
fprintf(stderr, "[ERROR] - DB2fasta: Cannot allocate Prolog header buffer\n.");
exit(1);
}
p->from = from;
p->to = to;
strcpy(fileName, fname);
strcpy(readName, rname);
p->fileName = fileName;
p->readName = readName;
dbh->numHeader++;
fflush(stdout);
}
static int getPrologIndexOfRead(DB_Header* dbh, int readID)
{
if (readID < 0 || readID > dbh->headers[dbh->numHeader - 1].to)
return -1;
else if (dbh->numHeader == 1)
return 0;
int min = 0;
int max = dbh->numHeader - 1;
Prolog *headers = dbh->headers;
while (max >= min)
{
int i = (min + max) / 2;
if (readID < headers[i].from)
max = i - 1;
else if (readID > headers[i].to)
min = i + 1;
else
return i;
}
return -1;
}
int main(int argc, char *argv[])
{
HITS_DB *db = &_db;
FILE *dbfile;
char *dbName;
int nfiles;
int VERBOSE, UPPER, WIDTH, SORT;
HITS_TRACK **out_tracks = NULL;
int curTracks = 0;
int maxTracks = 0;
HITS_TRACK *pacbio = NULL;
int *readIDs = NULL;
// Process arguments
{
VERBOSE = 0;
UPPER = 1;
WIDTH = 80;
SORT = 0;
int c;
opterr = 0;
while ((c = getopt(argc, argv, "hvUSw:m:")) != -1)
{
switch (c)
{
case 'v':
VERBOSE += 1;
break;
case 'U':
UPPER = 2;
break;
case 'm':
if (curTracks >= maxTracks)
{
maxTracks += 10;
out_tracks = (HITS_TRACK**)realloc(out_tracks, sizeof(HITS_TRACK*) * maxTracks);
}
// use the HITS_TRACK* array as temporary storage of the track names
out_tracks[curTracks] = (HITS_TRACK*) optarg;
curTracks++;
break;
case 'S':
SORT = 1;
break;
case 'h':
usage();
return 0;
case 'w':
{
WIDTH = atoi(optarg);
if (WIDTH < 1)
{
fprintf(stderr, "Invalid line width of %d\n", WIDTH);
exit(1);
}
}
break;
default:
fprintf(stderr, "Unsupported argument: %s\n", argv[optind - 1]);
usage();
exit(1);
}
}
}
if (optind == argc)
{
fprintf(stderr, "[ERROR] - DB2fasta: A database is required\n\n");
usage();
exit(1);
}
// Open db
{
int status;
dbName = argv[optind];
status = Open_DB(dbName, db);
if (status < 0)
exit(1);
if (status == 1)
{
fprintf(stderr, "%s: Cannot be called on a .dam index: %s\n", argv[0], dbName);
exit(1);
}
if (db->part > 0)
{
fprintf(stderr, "%s: Cannot be called on a block: %s\n", argv[0], dbName);
exit(1);
}
}
// Load Tracks
{
int i;
for (i = 0; i < curTracks; i++)
{
char* track = (char*) out_tracks[i];
out_tracks[i] = track_load(db, track);
if (out_tracks[i] == NULL)
{
fprintf(stderr, "could not open track '%s'\n", track);
exit(1);
}
}
// load pacbio track if available
pacbio = track_load(db, TRACK_PACBIO_HEADER);
}
{
char *pwd, *root;
pwd = PathTo(dbName);
root = Root(dbName, ".db");
dbfile = Fopen(Catenate(pwd, "/", root, ".db"), "r");
free(pwd);
free(root);
if (dbfile == NULL)
exit(1);
}
if (SORT)
{
int num = db->nreads;
readIDs = (int*) malloc(sizeof(int) * num);
if (readIDs == NULL)
{
fprintf(stderr, "[ERROR] - DB2fasta: Cannot allocate read id buffer for sorting!\n");
exit(1);
}
int i;
for (i = 0; i < num; i++)
readIDs[i] = i;
if (VERBOSE)
printf("sorting ...");
qsort(readIDs, num, sizeof(int), cmp_read_by_len);
if (VERBOSE)
printf(" done\n");
}
// nfiles = # of files in data base
if (fscanf(dbfile, DB_NFILE, &nfiles) != 1)
SYSTEM_READ_ERROR
DB_Header *dbh = (DB_Header*) malloc(sizeof(DB_Header));
if (dbh == NULL)
{
fprintf(stderr, "[ERROR] - DB2fasta: Cannot allocate hprolog buffer\n");
exit(1);
}
bzero(dbh, sizeof(DB_Header));
// parse prolog
{
int i;
int first = 0;
int last = 0;
char file[MAX_NAME], fname[MAX_NAME];
for (i = 0; i < nfiles; i++)
{
if (fscanf(dbfile, DB_FDATA, &last, fname, file) != 3)
{
fprintf(stderr, "[ERROR] - DB2fasta: Cannot read prolog at line %d of file %s\n", i + 2, argv[optind]);
exit(1);
}
addProlog(dbh, first, last, fname, file);
}
}
// For each file do:
{
HITS_READ *reads;
char *read;
int f, first;
int b, e;
track_anno* pacbio_anno;
track_data* pacbio_data;
if (pacbio)
{
pacbio_anno = pacbio->anno;
pacbio_data = pacbio->data;
}
reads = db->reads;
read = New_Read_Buffer(db);
first = 0;
for (f = 0; f < nfiles; f++)
{
int i, last;
FILE *ofile;
if (SORT)
{
ofile = stdout;
last = db->nreads;
nfiles = 1;
}
else
{
if ((ofile = Fopen(Catenate(".", "/", dbh->headers[f].fileName, ".fasta"), "w")) == NULL)
exit(1);
last = dbh->headers[f].to;
if (VERBOSE)
{
fprintf(stderr, "Creating %s.fasta ...\n", dbh->headers[f].fileName);
fflush(stdout);
}
}
// For the relevant range of reads, write each to the file
// recreating the original headers with the index meta-data about each read
for (i = first; i < last; i++)
{
int j, len;
HITS_READ *r;
int h = i;
if (SORT)
h = readIDs[i];
r = reads + h;
len = r->rlen;
if (SORT)
{
int pidx = getPrologIndexOfRead(dbh, h);
if (pidx < 0)
{
printf("Cannot find read: %d\n", h);
fflush(stdout);
exit(1);
}
if (pacbio)
{
int b, e;
b = pacbio_anno[pidx] / sizeof(track_data);
e = pacbio_anno[pidx + 1] / sizeof(track_data);
if (b < e)
fprintf(ofile, ">%s/%d/%d_%d", dbh->headers[f].readName, pacbio_data[b], pacbio_data[b + 1], pacbio_data[b + 2]);
else
fprintf(ofile, ">%s_%d_%d_%d", dbh->headers[f].readName, -1, i, len);
}
else
{
fprintf(ofile, ">%s_%d_%d_%d", dbh->headers[f].readName, -1, i, len);
}
fprintf(ofile, " fileID=%d", pidx + 1);
}
else
{
if (pacbio)
{
int b, e;
b = pacbio_anno[i] / sizeof(track_data);
e = pacbio_anno[i + 1] / sizeof(track_data);
if (b < e)
fprintf(ofile, ">%s/%d/%d_%d", dbh->headers[f].readName, pacbio_data[b], pacbio_data[b + 1], pacbio_data[b + 2]);
else
fprintf(ofile, ">%s_%d_%d_%d", dbh->headers[f].readName, -1, i, len);
}
else
fprintf(ofile, ">%s_%d_%d_%d", dbh->headers[f].readName, -1, i, len);
}
for (j = 0; j < curTracks; j++)
{
track_anno *anno = out_tracks[j]->anno;
track_data *data = out_tracks[j]->data;
fprintf(ofile, " %s=", out_tracks[j]->name);
b = anno[h] / sizeof(track_data);
e = anno[h + 1] / sizeof(track_data);
while (b < e)
{
fprintf(ofile, "%d", data[b]);
b++;
if (b < e)
fprintf(ofile, ",");
}
}
fprintf(ofile, "\n");
Load_Read(db, h, read, UPPER);
for (j = 0; j + WIDTH < len; j += WIDTH)
fprintf(ofile, "%.*s\n", WIDTH, read + j);
if (j < len)
fprintf(ofile, "%s\n", read + j);
}
first = last;
if (SORT)
break;
}
}
fclose(dbfile);
Close_DB(db);
exit(0);
}
|
MartinPippel/DAmar
|
db/QV2db.c
|
<reponame>MartinPippel/DAmar
/************************************************************************************\
* *
* Copyright (c) 2014, Dr. <NAME> (EWM). All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without modification, *
* are permitted provided that the following conditions are met: *
* *
* · Redistributions of source code must retain the above copyright notice, this *
* list of conditions and the following disclaimer. *
* *
* · Redistributions in binary form must reproduce the above copyright notice, this *
* list of conditions and the following disclaimer in the documentation and/or *
* other materials provided with the distribution. *
* *
* · The name of EWM may not be used to endorse or promote products derived from *
* this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY EWM ”AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, *
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND *
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL EWM BE LIABLE *
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS *
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY *
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING *
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN *
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
* *
* For any issues regarding this software and its use, contact EWM at: *
* *
* <NAME>r. *
* Bautzner Str. 122e *
* 01099 Dresden *
* GERMANY *
* Email: <EMAIL> *
* *
\************************************************************************************/
/*******************************************************************************************
*
* Adds the given .quiva files to an existing DB "path". The input files must be added in
* the same order as the .fasta files were and have the same root names, e.g. FOO.fasta
* and FOO.quiva. The files can be added incrementally but must be added in the same order
* as the .fasta files. This is enforced by the program. With the -l option set the
* compression scheme is a bit lossy to get more compression (see the description of dexqv
* in the DEXTRACTOR module).
*
* Author: <NAME>
* Date : July 2014
*
********************************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <sys/stat.h>
#include <unistd.h>
#include "DB.h"
#include "QV.h"
#include "fileUtils.h"
#ifdef HIDE_FILES
#define PATHSEP "/."
#else
#define PATHSEP "/"
#endif
static char *Usage = "[-vl] <path:string> ( -f<file> | <input:quiva> ... )";
int main(int argc, char *argv[])
{ FILE *istub, *quiva, *indx;
int64 coff;
int ofile;
HITS_DB db;
HITS_READ *reads;
int VERBOSE;
int LOSSY;
FILE *IFILE;
// Process command line
{ int i, j, k;
int flags[128];
ARG_INIT("quiva2DB")
IFILE = NULL;
j = 1;
for (i = 1; i < argc; i++)
if (argv[i][0] == '-')
switch (argv[i][1])
{ default:
ARG_FLAGS("vl")
break;
case 'f':
IFILE = fopen(argv[i]+2,"r");
if (IFILE == NULL)
{ fprintf(stderr,"%s: Cannot open file of inputs '%s'\n",Prog_Name,argv[i]+2);
exit (1);
}
break;
}
else
argv[j++] = argv[i];
argc = j;
VERBOSE = flags['v'];
LOSSY = flags['l'];
if ((IFILE == NULL && argc <= 2) || (IFILE != NULL && argc != 2))
{ fprintf(stderr,"Usage: %s %s\n",Prog_Name,Usage);
exit (1);
}
}
// Open DB stub file and index, load db and read records. Confirm that the .fasta files
// corresponding to the command line .quiva files are in the DB and in order where the
// index of the first file is ofile and the index of the first read to be added is ofirst.
// Record in coff the current size of the .qvs file in case an error occurs and it needs
// to be truncated back to its size at the start.
{ int i;
char *pwd, *root;
int nfiles;
File_Iterator *ng;
root = Root(argv[1],".db");
pwd = PathTo(argv[1]);
istub = Fopen(Catenate(pwd,"/",root,".db"),"r");
if (istub == NULL)
exit (1);
indx = Fopen(Catenate(pwd,PATHSEP,root,".idx"),"r+");
if (indx == NULL)
exit (1);
if (fread(&db,sizeof(HITS_DB),1,indx) != 1)
SYSTEM_READ_ERROR
reads = (HITS_READ *) Malloc(sizeof(HITS_READ)*db.ureads,"Allocating DB index");
if (reads == NULL)
exit (1);
if (fread(reads,sizeof(HITS_READ),db.ureads,indx) != (size_t) (db.ureads))
SYSTEM_READ_ERROR
{ int first, last;
char prolog[MAX_NAME], fname[MAX_NAME];
char *core;
ng = init_file_iterator(argc,argv,IFILE,2);
if ( ! next_file(ng))
{ fprintf(stderr,"%s: file list is empty!\n",Prog_Name);
exit (1);
}
if (ng->name == NULL) exit (1);
core = Root(ng->name,".quiva");
if (fscanf(istub,DB_NFILE,&nfiles) != 1)
SYSTEM_READ_ERROR
first = 0;
for (i = 0; i < nfiles; i++)
{ if (fscanf(istub,DB_FDATA,&last,fname,prolog) != 3)
SYSTEM_READ_ERROR
if (strcmp(core,fname) == 0)
break;
first = last;
}
if (i >= nfiles)
{ fprintf(stderr,"%s: %s.fasta has never been added to DB\n",Prog_Name,core);
exit (1);
}
ofile = i;
if (first > 0 && reads[first-1].coff < 0)
{ fprintf(stderr,"%s: Predecessor of %s.quiva has not been added yet\n",Prog_Name,core);
exit (1);
}
if (reads[first].coff >= 0)
{ fprintf(stderr,"%s: %s.quiva has already been added\n",Prog_Name,core);
exit (1);
}
while (next_file(ng))
{ if (ng->name == NULL)
exit (1);
core = Root(ng->name,".quiva");
if (++i >= nfiles)
{ fprintf(stderr,"%s: %s.fasta has never been added to DB\n",Prog_Name,core);
exit (1);
}
if (fscanf(istub,DB_FDATA,&last,fname,prolog) != 3)
SYSTEM_READ_ERROR
if (strcmp(core,fname) != 0)
{ fprintf(stderr,"%s: Files not being added in order (expect %s, given %s)",
Prog_Name,fname,core);
exit (1);
}
}
if (ofile == 0)
quiva = Fopen(Catenate(pwd,PATHSEP,root,".qvs"),"w");
else
quiva = Fopen(Catenate(pwd,PATHSEP,root,".qvs"),"r+");
if (quiva == NULL)
exit (1);
fseeko(quiva,0,SEEK_END);
coff = ftello(quiva);
free(core);
free(ng);
}
free(root);
free(pwd);
}
// For each .quiva file, determine its compression scheme in a fast scan and append it to
// the .qvs file Then compress every .quiva entry in the file, appending its compressed
// form to the .qvs file as you go and recording the offset in the .qvs in the .coff field
// of each read record (*except* the first, that points at the compression scheme immediately
// preceding it). Ensure that the # of .quiva entries matches the # of .fasta entries
// in each added file.
{ int i;
int last, cur;
File_Iterator *ng;
// For each .quiva file do:
rewind(istub);
if (fscanf(istub,"files = %*d\n") != 0)
SYSTEM_READ_ERROR
last = 0;
for (i = 0; i < ofile; i++)
if (fscanf(istub," %9d %*s %*s\n",&last) != 1)
SYSTEM_READ_ERROR
ng = init_file_iterator(argc,argv,IFILE,2);
cur = last;
while (next_file(ng))
{ FILE *input;
int64 qpos;
char *pwd, *root;
QVcoding *coding;
// Open next .quiva file and create its compression scheme
pwd = PathTo(ng->name);
root = Root(ng->name,".quiva");
if ((input = Fopen(Catenate(pwd,"/",root,".quiva"),"r")) == NULL)
goto error;
if (VERBOSE)
{ fprintf(stderr,"Analyzing '%s' ...\n",root);
fflush(stderr);
}
QVcoding_Scan(input);
coding = Create_QVcoding(LOSSY);
coding->prefix = Strdup(".qvs","Allocating header prefix");
qpos = ftello(quiva);
Write_QVcoding(quiva,coding);
// Then compress and append to the .qvs each compressed QV entry
if (VERBOSE)
{ fprintf(stderr,"Compressing '%s' ...\n",root);
fflush(stderr);
}
rewind(input);
while (Read_Lines(input,1) > 0)
{ reads[cur++].coff = qpos;
Compress_Next_QVentry(input,quiva,coding,LOSSY);
qpos = ftello(quiva);
}
if (fscanf(istub," %9d %*s %*s\n",&last) != 1)
SYSTEM_READ_ERROR
if (last != cur)
{ fprintf(stderr,"%s: Number of reads in %s.quiva doesn't match number in %s.fasta\n",
Prog_Name,root,root);
goto error;
}
Free_QVcoding(coding);
free(root);
free(pwd);
}
free(ng);
}
// Write the db record and read index into .idx and clean up
rewind(indx);
fwrite(&db,sizeof(HITS_DB),1,indx);
fwrite(reads,sizeof(HITS_READ),db.ureads,indx);
fclose(istub);
fclose(indx);
fclose(quiva);
exit (0);
// Error exit: Either truncate or remove the .qvs file as appropriate.
error:
if (coff != 0)
{ fseeko(quiva,0,SEEK_SET);
if (ftruncate(fileno(quiva),coff) < 0)
SYSTEM_READ_ERROR
}
fclose(istub);
fclose(indx);
fclose(quiva);
if (coff == 0)
{ char *root = Root(argv[1],".db");
char *pwd = PathTo(argv[1]);
unlink(Catenate(pwd,PATHSEP,root,".qvs"));
free(pwd);
free(root);
}
exit (1);
}
|
MartinPippel/DAmar
|
utils/LAshow.c
|
/*******************************************************************************************
*
* Displays the contents of a .las file
*
* Date : May 2015
*
* Author : <NAME>
*
*******************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <assert.h>
#include <sys/param.h>
#include "lib/colors.h"
#include "lib/oflags.h"
#include "lib/pass.h"
#include "lib/tracks.h"
#include "lib/utils.h"
#include "db/DB.h"
#include "dalign/align.h"
// defaults
#define DEF_ARG_F 0
// constants
#define SORT_NATIVE 0
#define SORT_ID 1
#define SORT_AB 2
#define SORT_LENGTH 3
#define SORT_AE 4
#define SHOW_TRACE_BREAK_AFTER 5
typedef struct {
HITS_DB* db_a;
HITS_DB* db_b;
HITS_TRACK* trimtrack_a;
HITS_TRACK* trimtrack_b;
int trace; // display trace
int color; // colorise output
int sort; // sort order (SORT_xxx)
int revsort; // reverse sort order
int min_rlen; // min read length
int min_olen; // min overlap length
float min_identity; // min overlap identity
int show_aln;
int flags; // show flags
int raw;
int self_matches; // only show A -> A overlaps
// for displaying rangers of a.read ids
int ranges_in;
int* ranges;
int ranges_npt;
int ranges_idx;
int twidth; // trace point spacing
char *pathReads;
Alignment* align; // alignment record (reused)
Work_Data* align_work; // global alignment module work data
} ShowContext;
// getopt
extern char* optarg;
extern int optind, opterr, optopt;
// oflags.c
extern OverlapFlag2Label oflag2label[];
// comparison functions for sorting overlaps
static int cmp_range(const void* l, const void* r) {
int x = *((int32*) l);
int y = *((int32*) r);
return (x - y);
}
static int cmp_ovls_abpos(const void* a, const void* b) {
Overlap* o1 = (Overlap*) a;
Overlap* o2 = (Overlap*) b;
int cmp = o1->path.abpos - o2->path.abpos;
if (!cmp) {
cmp = (o1->path.aepos - o1->path.abpos)
- (o2->path.aepos - o2->path.abpos);
}
return cmp;
}
static int cmp_ovls_aepos(const void* a, const void* b) {
Overlap* o1 = (Overlap*) a;
Overlap* o2 = (Overlap*) b;
int cmp = o1->path.aepos - o2->path.aepos;
if (!cmp) {
cmp = (o1->path.aepos - o1->path.abpos)
- (o2->path.aepos - o2->path.abpos);
}
return cmp;
}
static int cmp_ovls_id(const void* a, const void* b) {
Overlap* o1 = (Overlap*) a;
Overlap* o2 = (Overlap*) b;
return o1->bread - o2->bread;
}
static int cmp_ovls_length(const void* a, const void* b) {
Overlap* o1 = (Overlap*) a;
Overlap* o2 = (Overlap*) b;
return (o1->path.aepos - o1->path.abpos) - (o2->path.aepos - o2->path.abpos);
}
// displays a set of overlaps
static void show(ShowContext* ctx, Overlap* ovls, int novl) {
int i, end, incr;
int rev = ctx->revsort;
int show_trace = ctx->trace;
int show_flags = ctx->flags;
int show_aln = ctx->show_aln;
HITS_TRACK* trim_a = ctx->trimtrack_a;
HITS_TRACK* trim_b = ctx->trimtrack_b;
HITS_DB* db_a = ctx->db_a;
HITS_DB* db_b = ctx->db_b;
char* color_a = (ctx->color ? ANSI_COLOR_GREEN : "");
char* color_ovh = (ctx->color ? ANSI_COLOR_RED : "");
char* color_flags = (ctx->color ? ANSI_COLOR_BLUE : "");
char* color_reset = (ctx->color ? ANSI_COLOR_RESET : "");
// load sequence in case we have to show the alignment
int ovlALen = DB_READ_LEN(db_a, ovls->aread);
if (show_aln) {
ctx->align->alen = ovlALen;
Load_Read(db_a, ovls->aread, ctx->align->aseq, 0);
}
// sort overlaps
switch (ctx->sort) {
case SORT_ID:
qsort(ovls, novl, sizeof(Overlap), cmp_ovls_id);
break;
case SORT_LENGTH:
qsort(ovls, novl, sizeof(Overlap), cmp_ovls_length);
break;
case SORT_AB:
qsort(ovls, novl, sizeof(Overlap), cmp_ovls_abpos);
break;
case SORT_AE:
qsort(ovls, novl, sizeof(Overlap), cmp_ovls_aepos);
break;
case SORT_NATIVE:
default:
break;
}
// reverse sort (or not)
if (rev) {
incr = -1;
end = -1;
i = novl - 1;
} else {
incr = 1;
end = novl;
i = 0;
}
int trim_ab, trim_ae;
// display trim track data
if (trim_a) {
get_trim(db_a, trim_a, ovls->aread, &trim_ab, &trim_ae);
} else {
trim_ab = 0;
trim_ae = ovlALen;
}
for (; i != end; i += incr) {
Overlap* ovl = ovls + i;
if (ctx->self_matches && ovl->aread != ovl->bread) {
continue;
}
// length filter
int ovlBLen = DB_READ_LEN(db_b, ovl->bread);
if (ovlBLen < ctx->min_rlen) {
continue;
}
// length filter
int ovlLen = MAX(ovl->path.aepos - ovl->path.abpos,
abs(ovl->path.bepos - ovl->path.bbpos));
if (ovlLen < ctx->min_olen) {
continue;
}
int len = ovl->path.aepos - ovl->path.abpos;
float diff = 100.0 * ovl->path.diffs / len;
// diff filter
if (100 - diff < ctx->min_identity) {
continue;
}
// read ids and overlap coordinates
if (ctx->raw) {
printf("%d %d %d %d %d %d %d %d\n", ovl->aread, ovl->bread,
ovl->flags & OVL_COMP ? 1 : 0,
ovl->path.abpos, ovl->path.aepos, ovl->path.bbpos, ovl->path.bepos,
ovl->path.diffs);
if (show_aln) {
ctx->align->blen = ovlBLen;
Load_Read(db_b, ovls[i].bread, ctx->align->bseq, 0);
ctx->align->path = &(ovls[i].path);
if (ovls[i].flags & OVL_COMP) {
Complement_Seq(ctx->align->bseq, ovlBLen);
}
Compute_Trace_PTS(ctx->align, ctx->align_work, ctx->twidth, 0);
int width = db_a->reads[ovls[i].aread].rlen
+ db_b->reads[ovls[i].bread].rlen;
Print_Reference(stdout, ctx->align, ctx->align_work, 0, width,
0, 0, 0);
}
continue;
}
printf("%s%7d%s %s%c%s %7d %s%5d..%5d%s x %5d..%5d", color_a,
ovls[i].aread, color_reset,
color_flags, ovls[i].flags & OVL_COMP ? 'c' : 'n', color_reset,
ovls[i].bread, color_a, ovls[i].path.abpos, ovls[i].path.aepos,
color_reset, ovls[i].path.bbpos, ovls[i].path.bepos);
int trim_bb, trim_be;
// read lengths and trim track data
if (trim_b) {
get_trim(db_b, trim_b, ovls[i].bread, &trim_bb, &trim_be);
printf(" %s%5d [%5d..%5d]%s x %5d [%5d..%5d]", color_a, ovlALen,
trim_ab, trim_ae, color_reset, ovlBLen, trim_bb, trim_be);
} else {
trim_bb = 0;
trim_be = ovlBLen;
printf(" %s%5d%s x %5d", color_a, ovlALen, color_reset, ovlBLen);
}
printf(" %4.1f", diff);
// indicate true overlaps (not containments or local alignments)
printf(" %s%c%c%s", color_ovh,
ovls[i].path.abpos == trim_ab ? '<' : ' ',
ovls[i].path.aepos == trim_ae ? '>' : ' ', color_reset);
// show overlap record flags
if (show_flags && (ovls[i].flags & ~OVL_COMP)) {
char flags[OVL_FLAGS + 1];
flags2str(flags, ovls[i].flags);
// ignore OVL_COMP
printf(" %s%s%s\n", color_flags, flags + 1, color_reset);
} else {
printf("\n");
}
// show trace points
if (show_trace) {
int j;
ovl_trace* trace = ovls[i].path.trace;
assert((ovls[i].path.tlen % 2) == 0);
for (j = 0; j < ovls[i].path.tlen; j += 2) {
if (j > 0 && (j % (SHOW_TRACE_BREAK_AFTER * 2)) == 0)
printf("\n");
printf(" (%3d, %2d)", trace[j + 1], trace[j]);
}
printf("\n");
}
// show full alignment
if (show_aln) {
ctx->align->blen = ovlBLen;
Load_Read(db_b, ovls[i].bread, ctx->align->bseq, 0);
ctx->align->path = &(ovls[i].path);
if (ovls[i].flags & OVL_COMP) {
Complement_Seq(ctx->align->bseq, ovlBLen);
}
Compute_Trace_PTS(ctx->align, ctx->align_work, ctx->twidth, 0);
Print_Reference(stdout, ctx->align, ctx->align_work, 0, 100, 0, 0,
5);
printf("\n");
}
}
}
int fread_integer_range(FILE* fileIn, int** out_values, int* out_nvalues) {
int maxvalues = 100;
int nvalues = 0;
int* values = (int *)malloc(sizeof(int) * maxvalues);
int n;
while (fscanf(fileIn, "%d\n", &n) == 1)
{
if (nvalues + 1 >= maxvalues)
{
maxvalues = 1.2 * maxvalues + 100;
values = (int *)realloc(values, sizeof(int) * maxvalues);
}
values[nvalues++] = n;
values[nvalues++] = n;
}
qsort(values, nvalues / 2, sizeof(int64), cmp_range);
n = 0;
int c;
for (c = 0; c < nvalues; c += 2) {
if (n > 0 && values[n - 1] >= values[c] - 1) {
if (values[c + 1] > values[n - 1]) {
values[n - 1] = values[c + 1];
}
} else {
values[n++] = values[c];
values[n++] = values[c + 1];
}
}
values[n++] = INT32_MAX;
nvalues = n;
*out_values = values;
*out_nvalues = nvalues;
return nvalues;
}
static int parse_ranges(int argc, char* argv[], int* _reps, int** _pts) {
int *pts = (int*) malloc(sizeof(int) * 2 * (2 + argc));
int reps = 0;
if (argc > 0) {
int c, b, e;
char* eptr, *fptr;
for (c = 0; c < argc; c++) {
if (argv[c][0] == '#') {
fprintf(stderr, "# is not allowed as range start, '%s'\n",
argv[c]);
return 0;
} else {
b = strtol(argv[c], &eptr, 10);
if (b < 0) {
fprintf(stderr, "Non-positive index?, '%d'\n", b);
return 0;
}
}
if (eptr > argv[c]) {
if (*eptr == '\0') {
pts[reps++] = b;
pts[reps++] = b;
continue;
} else if (*eptr == '-') {
if (eptr[1] == '#') {
e = INT32_MAX;
fptr = eptr + 2;
} else {
e = strtol(eptr + 1, &fptr, 10);
}
if (fptr > eptr + 1 && *fptr == 0 && eptr[1] != '-') {
pts[reps++] = b;
pts[reps++] = e;
if (b > e) {
fprintf(stderr, "Empty range '%s'\n", argv[c]);
return 0;
}
continue;
}
}
}
fprintf(stderr, "argument '%s' is not an integer range\n", argv[c]);
return 0;
}
qsort(pts, reps / 2, sizeof(int64), cmp_range);
b = 0;
for (c = 0; c < reps; c += 2) {
if (b > 0 && pts[b - 1] >= pts[c] - 1) {
if (pts[c + 1] > pts[b - 1]) {
pts[b - 1] = pts[c + 1];
}
} else {
pts[b++] = pts[c];
pts[b++] = pts[c + 1];
}
}
pts[b++] = INT32_MAX;
reps = b;
} else {
pts[reps++] = 0;
pts[reps++] = INT32_MAX;
}
*_reps = reps;
*_pts = pts;
return 1;
}
static void pre_show(PassContext* pctx, ShowContext* sctx) {
sctx->twidth = pctx->twidth;
sctx->ranges_idx = 1;
sctx->ranges_npt = sctx->ranges[0];
}
static void post_show() {
}
static int handler_show(void* _ctx, Overlap* ovls, int novl) {
ShowContext* ctx = (ShowContext*) _ctx;
if (DB_READ_LEN(ctx->db_a, ovls->aread) < ctx->min_rlen) {
return 1;
}
int a = ovls->aread;
if (ctx->ranges_in) {
while (a > ctx->ranges_npt) {
ctx->ranges_npt = ctx->ranges[ctx->ranges_idx++];
if (a < ctx->ranges_npt) {
ctx->ranges_in = 0;
break;
}
ctx->ranges_npt = ctx->ranges[ctx->ranges_idx++];
}
} else {
if (ctx->ranges_npt == INT32_MAX) {
return 0;
}
while (a >= ctx->ranges_npt) {
ctx->ranges_npt = ctx->ranges[ctx->ranges_idx++];
if (a <= ctx->ranges_npt) {
ctx->ranges_in = 1;
break;
}
ctx->ranges_npt = ctx->ranges[ctx->ranges_idx++];
}
}
if (ctx->ranges_in) {
show(ctx, ovls, novl);
}
return 1;
}
static void usage() {
fprintf(stderr,
"[-tfrcm] [-s <liLI>] [-xo <int>] [-T <track>] [-i <float>] [-F <file> ] <db> [db.2] <overlaps> [ <reads:range> ... ]\n");
fprintf(stderr, "options: -t ... show trace\n");
fprintf(stderr, " -c ... colorise output\n");
fprintf(stderr, " -f ... show flags\n");
fprintf(stderr, " -a ... show alignment\n");
fprintf(stderr,
" -s <liLI> ... sort by length or id (ASCENDING or descending)\n");
fprintf(stderr, " -x <int> ... minimum read length\n");
fprintf(stderr, " -o <int> ... minimum overlap length\n");
fprintf(stderr, " -i <float> ... minimum identity\n");
fprintf(stderr,
" -T <track> ... use trim track (if [db.2] is present then two -T possible)\n");
fprintf(stderr, " -r ... unformatted output\n");
fprintf(stderr, " -m ... mixed db mode\n");
fprintf(stderr, "\n\n EXPERIMENTAL\n");
fprintf(stderr, " -F <file> ... get Reads from file\n");
}
;
int main(int argc, char* argv[]) {
HITS_DB* db_a = malloc(sizeof(HITS_DB));
HITS_DB* db_b = NULL;
FILE* fileOvlIn;
PassContext* pctx;
ShowContext sctx;
bzero(&sctx, sizeof(ShowContext));
// process arguments
int c;
int mixed = 0;
char* trim_a = NULL;
char* trim_b = NULL;
opterr = 0;
sctx.raw = 0;
sctx.min_rlen = 0;
sctx.min_olen = 0;
sctx.min_identity = -1;
sctx.sort = SORT_NATIVE;
sctx.flags = DEF_ARG_F;
sctx.pathReads = NULL;
while ((c = getopt(argc, argv, "mrIfactx:i:o:s:T:F:")) != -1) {
switch (c) {
case 'm':
mixed = 1;
break;
case 'F':
sctx.pathReads = optarg;
break;
case 'r':
sctx.raw = 1;
break;
case 'I':
sctx.self_matches = 1;
break;
case 'f':
sctx.flags = 1;
break;
case 'T': {
if (trim_a == NULL)
trim_a = optarg;
else
trim_b = optarg;
}
break;
case 'a':
sctx.show_aln = 1;
break;
case 'c':
sctx.color = 1;
break;
case 't':
sctx.trace = 1;
break;
case 'x':
sctx.min_rlen = atoi(optarg);
break;
case 'o':
sctx.min_olen = atoi(optarg);
break;
case 's':
if (islower(optarg[0])) {
sctx.revsort = 1;
}
switch (tolower(optarg[0])) {
case 'i':
sctx.sort = SORT_ID;
break;
case 'l':
sctx.sort = SORT_LENGTH;
break;
case 'e':
sctx.sort = SORT_AE;
break;
case 'b':
default:
sctx.sort = SORT_AB;
break;
}
break;
case 'i':
sctx.min_identity = atof(optarg);
break;
default:
printf("Unknown option: %s\n", argv[optind - 1]);
usage();
exit(1);
}
}
if (argc - optind < (2 + mixed)) {
usage();
exit(1);
}
char* pcPathReadsIn_a = argv[optind++];
char* pcPathReadsIn_b = NULL;
if (mixed) {
pcPathReadsIn_b = argv[optind++];
}
char* pcPathOverlaps = argv[optind++];
if ((fileOvlIn = fopen(pcPathOverlaps, "r")) == NULL) {
fprintf(stderr, "could not open '%s'\n", pcPathOverlaps);
exit(1);
}
if (Open_DB(pcPathReadsIn_a, db_a)) {
printf("could not open '%s'\n", pcPathReadsIn_a);
}
if (mixed) {
db_b = malloc(sizeof(HITS_DB));
if (Open_DB(pcPathReadsIn_b, db_b)) {
printf("could not open '%s'\n", pcPathReadsIn_b);
}
} else {
db_b = db_a;
}
int reps;
int* pts = NULL;
if (sctx.pathReads) {
FILE* fileIn = fopen(sctx.pathReads, "r");
if (fileIn == NULL) {
fprintf(stderr, "could not open %s\n", sctx.pathReads);
exit(1);
}
fread_integer_range(fileIn, &pts, &reps);
fclose(fileIn);
} else {
parse_ranges(argc - optind, argv + optind, &reps, &pts);
}
// init
if (trim_a != NULL) {
sctx.trimtrack_a = track_load(db_a, trim_a);
if (!sctx.trimtrack_a) {
fprintf(stderr, "failed to load track %s\n", trim_a);
exit(1);
}
if (trim_b == NULL)
trim_b = trim_a;
sctx.trimtrack_b = track_load(db_b, trim_b);
if (!sctx.trimtrack_b) {
fprintf(stderr, "failed to load track %s\n", trim_b);
exit(1);
}
}
if (sctx.show_aln) {
sctx.align = (Alignment*) malloc(sizeof(Alignment));
sctx.align->aseq = New_Read_Buffer(db_a);
sctx.align->bseq = New_Read_Buffer(db_b);
sctx.align_work = New_Work_Data();
}
sctx.ranges = pts;
sctx.db_a = db_a;
sctx.db_b = db_b;
pctx = pass_init(fileOvlIn, NULL);
pctx->split_b = 0;
pctx->load_trace = (sctx.show_aln || sctx.trace);
pctx->unpack_trace = (sctx.show_aln || sctx.trace);
pctx->data = &sctx;
// pass
pre_show(pctx, &sctx);
pass(pctx, handler_show);
post_show();
// cleanup
if (sctx.show_aln) {
free(sctx.align->aseq - 1);
free(sctx.align->bseq - 1);
free(sctx.align);
Free_Work_Data(sctx.align_work);
}
Close_DB(db_a);
pass_free(pctx);
fclose(fileOvlIn);
free(db_a);
if (mixed) {
Close_DB(db_b);
free(db_b);
}
return 0;
}
|
MartinPippel/DAmar
|
utils/H5dextractUtils.c
|
#include "H5dextractUtils.h"
#include <string.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
static char *Usage = " [options] -F file | <input:bax_h5> ...";
static void printUsage(char *prog, FILE* out)
{
fprintf(out, "\nUsage:\t%s\t%s\n\n", prog, Usage);
fprintf(out, " %s takes some number of .bax.h5 files as input and following options:\n\n", prog);
fprintf(out, " -h / --help Print this help dialog.\n");
fprintf(out, " -c / --cum cumulative option, if set the statistic report is generated from all given .bax.h5 files\n"
" Otherwise, for each input file an own statistic is reported\n\n");
fprintf(out, " -s ARG / --stat ARG statistics file name. If not present the statistics is dumped to stdout.\n");
fprintf(out, " -f ARG / --fasta ARG fasta file name\n");
fprintf(out, " -q ARG / --fastq ARG fastq file name\n");
fprintf(out, " -i ARG / --quiva ARG quiva file name\n\n");
fprintf(out, " -X ARG / --Len ARG specify a maximum subread length. All subreads larger than this cutoff are discarded.\n");
fprintf(out, " -x ARG / --len ARG specify a minimum subread length. All subreads smaller than this cutoff are discarded.\n");
fprintf(out, " -Q ARG / --qual ARG specify a minimum subread quality. All subreads with a quality value (RQ) less than this cutoff are discarded.\n\n");
fprintf(out, " -S ARG / --subread ARG specify which subreads should be pulled from each ZMW (with respect to -x and -Q options)\n"
" possible values [a, b, l, s] \n"
" a: all subreads from a ZMW (default value)\n"
" l: longest subread from a ZMW\n"
" s: shortest subread from a ZMW\n"
" b: best subread from a ZMW -> for now this is computed as follows:\n"
" 0.2*(subreadLen/HQregionLength) + 0.4*(#subreadSegments - #slowPolymeraseSegments/#subreadSegments) + 0.4(avgQV/max(QVsFromWholeZMW))\n\n");
fprintf(out, " -m ARG / --movMin ARG Specify a minimum time threshold in seconds. High quality subreads (nucleotides) starting before that threshold are ignored.\n");
fprintf(out, " -M ARG / --movMax ARG Specify a maximum time threshold in seconds. High quality subreads (nucleotides) starting after that threshold are ignored.\n");
fprintf(out, " Both options -m and -M are mainly used for deep analysis bax.h5 files. (e.g.: Do read qualities drop after a certain runtime?)\n\n");
fprintf(out, " -t ARG / --timeBinSize ARG specify the time bin size for the quality value histograms in seconds (default 600 = 10 min)\n");
fprintf(out, " -l ARG / --lenBinSize ARG specify the length bin size for the subread length histograms (default 1000)\n");
fprintf(out, " -w FILE list of well numbers (e.g. '1 12 567 765-12234'), each line corresponds to input bax file, empty line: all wells (no selection)\n\n");
fprintf(out, " -F FILE file with list of input bax.h5 files (one file per line) \n");
fprintf(out, " -z INT extract subreads only from ZMW's with INT number of subreads (default: -1)\n");
}
BAX_OPT* parseBaxOptions(int argc, char ** argv)
{
BAX_OPT *bopt = (BAX_OPT*) malloc(sizeof(BAX_OPT));
initBaxOptions(bopt);
int c;
while (1)
{
static struct option long_options[] =
{
{ "help", no_argument, 0, 'h' },
{ "cum", no_argument, 0, 'c' },
{ "verbose", no_argument, 0, 'v' },
{ "fasta", required_argument, 0, 'f' },
{ "fastq", required_argument, 0, 'q' },
{ "quiva", required_argument, 0, 'i' },
{ "stat", required_argument, 0, 's' },
{ "len", required_argument, 0, 'x' },
{ "Len", required_argument, 0, 'X' },
{ "qual", required_argument, 0, 'Q' },
{ "movMin", required_argument, 0, 'm' },
{ "movMax", required_argument, 0, 'M' },
{ "timeBinSize", required_argument, 0, 't' },
{ "lenBinSize", required_argument, 0, 'l' },
{ "subread", required_argument, 0, 'S' },
{ "wellNumbers", required_argument, 0, 'w' },
{ "zmw", required_argument, 0, 'z' },
{ "file", required_argument, 0, 'F' } };
/* getopt_long stores the option index here. */
int option_index = 0;
c = getopt_long(argc, argv, "vchf:q:i:s:x:X:Q:m:M:t:l:S:w:F:z:", long_options, &option_index);
/* Detect the end of the options. */
if (c == -1)
break;
switch (c)
{
case 0:
/* If this option set a flag, do nothing else now. */
if (long_options[option_index].flag != 0)
break;
break;
case 'h':
printUsage(argv[0], stderr);
exit(1);
case 'c':
bopt->CUMULATIVE = 1;
break;
case 'v':
bopt->VERBOSE++;
break;
case 'f':
bopt->fastaOut = optarg;
break;
case 'q':
bopt->fastqOut = optarg;
break;
case 'i':
bopt->quivaOut = optarg;
break;
case 's':
bopt->statOut = optarg;
break;
case 'F':
bopt->baxInFileName = optarg;
break;
case 'w':
bopt->wellNumbersInFileName = optarg;
break;
case 'x':
bopt->MIN_LEN = (int) strtol(optarg, NULL, 10);
if (errno)
{
fprintf(stderr, "Cannot parse argument of minimum read length (-x ARG)! Must be a positive number.\n");
exit(1);
}
break;
case 'X':
bopt->MAX_LEN = (int) strtol(optarg, NULL, 10);
if (errno)
{
fprintf(stderr, "Cannot parse argument of maximum read length (-X ARG)! Must be a positive number\n");
exit(1);
}
break;
case 'Q':
bopt->MIN_QV = (int) strtol(optarg, NULL, 10);
if (errno)
{
fprintf(stderr, "Cannot parse argument of minimum read quality (-q ARG)! Must be an integer in [0, 1000]\n");
exit(1);
}
break;
case 'm':
bopt->MIN_MOVIE_TIME = (int) strtol(optarg, NULL, 10);
if (errno)
{
fprintf(stderr, "Cannot parse argument for movie start time (-m ARG)! Must be an integer in [0, 36000]\n");
exit(1);
}
break;
case 'M':
bopt->MAX_MOVIE_TIME = (int) strtol(optarg, NULL, 10);
if (errno)
{
fprintf(stderr, "Cannot parse argument for movie end time (-M ARG)! Must be an integer in [0, 36000]\n");
exit(1);
}
break;
case 'z':
bopt->zmw_minNrOfSubReads = (int) strtol(optarg, NULL, 10);
if (errno || bopt->zmw_minNrOfSubReads < 1)
{
fprintf(stderr, "Cannot parse argument for zmw (-z ARG)! Must be a positive number\n");
exit(1);
}
break;
case 't':
bopt->TIME_BIN_SIZE = (int) strtol(optarg, NULL, 10);
if (errno)
{
fprintf(stderr, "Cannot parse argument of time histogram bin size (-t ARG)! Must an integer in [300, 3600]\n");
exit(1);
}
break;
case 'l':
bopt->READLEN_BIN_SIZE = (int) strtol(optarg, NULL, 10);
if (errno)
{
fprintf(stderr, "Cannot parse argument of length histogram bin size (-l ARG)! Must be an integer in [1000, 10000]\n");
exit(1);
}
break;
case 'S':
switch (*optarg)
{
case 'a':
bopt->subreadSel = all;
break;
case 'b':
bopt->subreadSel = best;
break;
case 'l':
bopt->subreadSel = longest;
break;
case 's':
bopt->subreadSel = shortest;
break;
default:
fprintf(stderr, "Cannot parse argument subread selection (-S ARG)! Possible values: [ a (all), b (best), l (longest), s (shortest) ]\n");
exit(1);
}
break;
case '?':
printUsage(argv[0], stderr);
exit(1);
default:
printUsage(argv[0], stderr);
exit(1);
}
}
if (bopt->statOut != NULL)
{
if ((bopt->statFile = fopen(bopt->statOut, "w")) == NULL)
{
fprintf(stderr, "Cannot open statistic file: %s!\n", bopt->statOut);
exit(1);
}
}
else
bopt->statFile = stdout;
if (bopt->fastaOut != NULL)
{
if ((bopt->fastaFile = fopen(bopt->fastaOut, "w")) == NULL)
{
fprintf(stderr, "Cannot open fasta file: %s!\n", bopt->fastaOut);
exit(1);
}
}
if (bopt->fastqOut != NULL)
{
if ((bopt->fastqFile = fopen(bopt->fastqOut, "w")) == NULL)
{
fprintf(stderr, "Cannot open fastq file: %s!\n", bopt->fastqOut);
exit(1);
}
}
if (bopt->quivaOut != NULL)
{
if ((bopt->quivaFile = fopen(bopt->quivaOut, "w")) == NULL)
{
fprintf(stderr, "Cannot open fasta file: %s!\n", bopt->quivaOut);
exit(1);
}
}
//parse file with list of bax.h5 files if present
if (bopt->baxInFileName != NULL)
{
readInputBaxFromFile(bopt);
if (optind < argc)
{
fprintf(stderr, "[WARNING] : if -F option is set, then further bax.h5 files given in command line are ignored!!\n");
}
}
else
{
if (optind == argc)
{
fprintf(stderr, "At least one bax.h5 file is needed!\n");
printUsage(argv[0], stderr);
exit(1);
}
while (optind < argc)
{
if (bopt->nBax == bopt->nMaxBax)
{
bopt->nMaxBax = ((int) (1.2 * bopt->nMaxBax)) + 10;
bopt->baxIn = (char**) realloc(bopt->baxIn, sizeof(char*) * bopt->nMaxBax);
}
FILE *in;
if ((in = fopen(argv[optind], "r")) == NULL)
{
fprintf(stderr, "%s: Cannot find file %s !\n", argv[0], argv[optind]);
optind++;
continue;
}
else
fclose(in);
bopt->baxIn[bopt->nBax] = (char*) malloc(strlen(argv[optind]) + 10);
strcpy(bopt->baxIn[bopt->nBax], argv[optind]);
optind++;
bopt->nBax++;
}
}
if (bopt->wellNumbersInFileName != NULL)
readWellNumbersFromFile(bopt);
return bopt;
}
char *trimwhitespace(char *str)
{
char *end;
// Trim leading space
while (isspace(*str))
str++;
if (*str == 0) // All spaces?
return str;
// Trim trailing space
end = str + strlen(str) - 1;
while (end > str && isspace(*end))
end--;
// Write new null terminator
*(end + 1) = 0;
return str;
}
int parse_ranges(char *line, int* _reps, int** _pts)
{
int num = 10;
int b, e;
int *pts = (int*) malloc(sizeof(int) * 2 * (2 + num));
int reps = 0;
char *s = line;
char *eptr = line;
while (eptr[0] != '\0')
{
if (reps + 4 >= num)
{
num = (reps + 4) * 1.2 + 10;
pts = (int *) realloc(pts, sizeof(int) * num);
}
b = strtol(s, &eptr, 10);
if (eptr[0] == '\0' || eptr[0] == ' ')
{
pts[reps++] = b;
pts[reps++] = b;
e = b;
if (eptr[0] == ' ')
s = eptr++;
}
if (eptr[0] == '-')
{
s = eptr;
e = strtol(s + 1, &eptr, 10);
pts[reps++] = b;
pts[reps++] = e;
s = eptr;
}
}
if (reps > 0)
{
qsort(pts, reps / 2, sizeof(int64), cmp_range);
int c;
b = 0;
for (c = 0; c < reps; c += 2)
{
if (b > 0 && pts[b - 1] >= pts[c] - 1)
{
if (pts[c + 1] > pts[b - 1])
{
pts[b - 1] = pts[c + 1];
}
}
else
{
pts[b++] = pts[c];
pts[b++] = pts[c + 1];
}
}
pts[b++] = INT32_MAX;
reps = b;
}
else
{
pts[reps++] = 1;
pts[reps++] = INT32_MAX;
}
*_reps = reps;
*_pts = pts;
return 1;
}
int cmp_range(const void* l, const void* r)
{
int x = *((int32*) l);
int y = *((int32*) r);
return (x - y);
}
void readWellNumbersFromFile(BAX_OPT *bopt)
{
if (bopt->wellNumbersInFileName == NULL)
{
fprintf(stderr, "[WARNING] - readWellNumbersFromFile: Input file name not available!\n");
return;
}
FILE *in;
if ((in = fopen(bopt->wellNumbersInFileName, "r")) == NULL)
{
fprintf(stderr, "[WARNING] - readWellNumbersFromFile: Cannot open file \"%s\"!\n", bopt->wellNumbersInFileName);
return;
}
// read file line by line
char * line = NULL;
size_t len = 0;
ssize_t read;
int lineNumber = 0;
while ((read = getline(&line, &len, in)) != -1)
{
if (bopt->VERBOSE > 1)
{
printf("Retrieved line of length %zu :\n", read);
printf("%s", line);
}
// get rid of newline
if (line[read - 1] == '\n')
line[read - 1] = '\0';
// trim leading and trailing white spaces
line = trimwhitespace(line);
if (lineNumber >= bopt->nBax)
{
fprintf(stderr, "Number of wellNumber lines greater than number of bax.h5 files!\n");
exit(1);
}
// parse lines
int reps = 0;
int* pts = NULL;
parse_ranges(line, &reps, &pts);
if (bopt->VERBOSE > 2)
{
int i;
printf("reps: %d\n", reps);
for (i = 1; i < reps; i += 2)
printf("%d, %d; \n", pts[i - 1], pts[i]);
}
bopt->numWellNumbers[lineNumber] = reps;
bopt->wellNumbers[lineNumber] = pts;
lineNumber++;
}
if (line)
free(line);
fclose(in);
}
void readInputBaxFromFile(BAX_OPT *bopt)
{
if (bopt->baxInFileName == NULL)
{
fprintf(stderr, "[WARNING] - readInputBaxFromFile: Input file name not available!\n");
return;
}
FILE *in, *baxTest;
if ((in = fopen(bopt->baxInFileName, "r")) == NULL)
{
fprintf(stderr, "[WARNING] - readInputBaxFromFile: Cannot open file \"%s\"!\n", bopt->baxInFileName);
return;
}
// read file line by line
char * line = NULL;
size_t len = 0;
ssize_t read;
int lineNumber = 0;
while ((read = getline(&line, &len, in)) != -1)
{
lineNumber++;
if (bopt->VERBOSE > 1)
{
printf("Retrieved line of length %zu :\n", read);
printf("%s", line);
}
// trim leading and trailing white spaces
trimwhitespace(line);
// sanity check file name extension: .bax.h5
size_t blen = strlen(line);
if (strcmp(line + (blen - 7), ".bax.h5") != 0)
{
fprintf(stderr, "[Warning] - readInputBaxFromFile: ignore line %d, file name extension .bax.h5 is missing (%s)\n", lineNumber, line);
continue;
}
if (bopt->nBax == bopt->nMaxBax)
{
bopt->nMaxBax = ((int) (1.2 * bopt->nMaxBax)) + 10;
bopt->baxIn = (char**) realloc(bopt->baxIn, sizeof(char*) * bopt->nMaxBax);
bopt->numWellNumbers = (int*) realloc(bopt->numWellNumbers, sizeof(int) * bopt->nMaxBax);
bopt->wellNumbers = (int**) realloc(bopt->wellNumbers, sizeof(int*) * bopt->nMaxBax);
}
// sanity check file is accessible
if ((baxTest = fopen(line, "r")) == NULL)
{
fprintf(stderr, "[WARNING] - readInputBaxFromFile: Cannot find file %s !\n", line);
continue;
}
else
fclose(baxTest);
// add bax file name to list
bopt->baxIn[bopt->nBax] = (char*) malloc(blen + 10);
strcpy(bopt->baxIn[bopt->nBax], line);
bopt->numWellNumbers[bopt->nBax] = 0;
bopt->nBax++;
}
if (line)
free(line);
fclose(in);
}
void initBaxOptions(BAX_OPT *bopt)
{
bopt->statOut = NULL;
bopt->fastaOut = NULL;
bopt->fastqOut = NULL;
bopt->quivaOut = NULL;
bopt->wellNumbersInFileName = NULL;
bopt->baxInFileName = NULL;
bopt->statFile = NULL;
bopt->fastaFile = NULL;
bopt->fastqFile = NULL;
bopt->quivaFile = NULL;
bopt->nBax = 0;
bopt->nMaxBax = 10;
bopt->baxIn = (char**) malloc(sizeof(char*) * bopt->nMaxBax);
bopt->wellNumbers = (int **) malloc(sizeof(int *) * bopt->nMaxBax);
bopt->numWellNumbers = (int *) malloc(sizeof(int) * bopt->nMaxBax);
bopt->VERBOSE = 0;
bopt->MAX_LEN = INT_MAX;
bopt->MIN_LEN = 500;
bopt->MIN_QV = 750;
bopt->CUMULATIVE = 0;
bopt->READLEN_BIN_SIZE = 1000;
bopt->TIME_BIN_SIZE = 600;
bopt->MIN_MOVIE_TIME = 0;
bopt->MAX_MOVIE_TIME = MAX_TIME_LIMIT;
bopt->subreadSel = all;
bopt->zmw_minNrOfSubReads = -1;
}
void printBaxOptions(BAX_OPT *bopt)
{
int i = 0;
if (bopt->statOut)
printf("statout: \t%s\n", bopt->statOut);
else
printf("statout: \tstdout\n");
if (bopt->fastaOut)
printf("fastaout: \t%s\n", bopt->fastaOut);
if (bopt->fastqOut)
printf("fastqout: \t%s\n", bopt->fastqOut);
if (bopt->quivaOut)
printf("quivaOut: \t%s\n", bopt->quivaOut);
printf("#BaxFiles: \t%d\n", bopt->nBax);
for (i = 0; i < bopt->nBax; i++)
{
printf("file%5d: \t%s\n", i, bopt->baxIn[i]);
if (bopt->numWellNumbers[i] > 0)
{
int j;
printf("selected wells: \t");
for (j = 1; j < bopt->numWellNumbers[i]; j += 2)
{
if (bopt->wellNumbers[i][j - 1] == bopt->wellNumbers[i][j])
printf("%d ", bopt->wellNumbers[i][j - 1]);
else
printf("%d-%d ", bopt->wellNumbers[i][j - 1], bopt->wellNumbers[i][j]);
}
printf("\n");
}
}
if (bopt->CUMULATIVE)
printf("Cumulative: \tYES\n");
else
printf("Cumulative: \tNO\n");
printf("MinLen: \t%d\n", bopt->MIN_LEN);
printf("MinQV: \t%d\n", bopt->MIN_QV);
printf("LenBinSize: \t%d\n", bopt->READLEN_BIN_SIZE);
printf("TimeBinSize: \t%d\n", bopt->TIME_BIN_SIZE);
if (bopt->MIN_MOVIE_TIME < 0)
printf("movieStartTime: \tNOT SET\n");
else
printf("movieStartTime: \t%d\n", bopt->MIN_MOVIE_TIME);
if (bopt->MAX_MOVIE_TIME < 0)
printf("movieEndTime: \tNOT SET\n");
else
printf("movieEndTime: \t%d\n", bopt->MAX_MOVIE_TIME);
switch (bopt->subreadSel)
{
case all:
default:
printf("subreadSelection:\tall\n");
break;
case best:
printf("subreadSelection:\tbest\n");
break;
case shortest:
printf("subreadSelection:\tshortest\n");
break;
case longest:
printf("subreadSelection:\tlongest\n");
break;
}
}
void freeBaxOptions(BAX_OPT *bopt)
{
if (bopt->statFile)
fclose(bopt->statFile);
if (bopt->fastaFile)
fclose(bopt->fastaFile);
if (bopt->fastqFile)
fclose(bopt->fastqFile);
if (bopt->quivaFile)
fclose(bopt->quivaFile);
int i;
for (i = 0; i < bopt->nBax; i++)
free(bopt->baxIn[i]);
if (bopt->wellNumbersInFileName)
{
free(bopt->numWellNumbers);
for (i = 0; i < bopt->nBax; i++)
free(bopt->wellNumbers[i]);
free(bopt->wellNumbers);
}
free(bopt->baxIn);
}
void initBaxData(BaxData *b)
{
b->fullName = NULL;
b->shortNameBeg = 0;
b->shortNameEnd = 0;
b->baseCall = NULL;
b->delQV = NULL;
b->delTag = NULL;
b->insQV = NULL;
b->mergeQV = NULL;
b->subQV = NULL;
b->fastQV = NULL;
b->holeStatus = NULL;
b->numEvent = NULL;
b->region = NULL;
b->numBase = 0;
b->numZMW = 0;
b->numRegion = 0;
b->widthInFrames = NULL;
b->preBaseFrames = NULL;
b->hqRegionBegTime = NULL;
b->hqRegionEndTime = NULL;
b->pausiness = NULL;
b->productivity = NULL;
b->readType = NULL;
}
void freeBaxData(BaxData *b)
{
free(b->baseCall);
free(b->widthInFrames);
free(b->numEvent);
free(b->holeStatus);
free(b->hqRegionBegTime);
free(b->region);
free(b->pausiness);
free(b->productivity);
free(b->bindingKit);
free(b->sequencingKit);
free(b->softwareVersion);
if(b->sequencingChemistry != NULL)
free(b->sequencingChemistry);
}
void initZMW(ZMW *z)
{
z->number = 0;
z->index = 0;
z->regionRow = 0;
z->status = UNKNOWN;
z->hqBeg = 0;
z->hqEnd = 0;
z->regionScore = -1;
z->roff = 0;
z->maxFrag = 10;
z->numFrag = 0;
z->insBeg = (int*) malloc(z->maxFrag * sizeof(int));
z->insEnd = (int*) malloc(z->maxFrag * sizeof(int));
z->insTimeBeg = (int*) malloc(z->maxFrag * sizeof(int));
z->insTimeEnd = (int*) malloc(z->maxFrag * sizeof(int));
z->toReport = (char*) malloc(z->maxFrag);
z->fragQual = (unsigned char**) malloc(z->maxFrag * sizeof(unsigned char*));
z->fragSequ = (unsigned char**) malloc(z->maxFrag * sizeof(unsigned char*));
z->widthInFrames = (unsigned short**) malloc(z->maxFrag * sizeof(unsigned short*));
z->preBaseFrames = (unsigned short**) malloc(z->maxFrag * sizeof(unsigned short*));
z->delQV = (unsigned char**) malloc(z->maxFrag * sizeof(unsigned char*));
z->delTag = (unsigned char**) malloc(z->maxFrag * sizeof(unsigned char*));
z->insQV = (unsigned char**) malloc(z->maxFrag * sizeof(unsigned char*));
z->mergeQV = (unsigned char**) malloc(z->maxFrag * sizeof(unsigned char*));
z->subQV = (unsigned char**) malloc(z->maxFrag * sizeof(unsigned char*));
z->len = (int*) malloc(z->maxFrag * sizeof(int));
z->avgQV = (float*) malloc(z->maxFrag * sizeof(float));
z->spr = (slowPolymeraseRegions*) malloc(z->maxFrag * sizeof(slowPolymeraseRegions));
int i;
for (i = 0; i < z->maxFrag; i++)
initSlowPolymeraseRegions(z->spr + i, 100, 50);
}
void resetZMW(ZMW *z)
{
z->status = UNKNOWN;
z->prod = prod_NotDefined;
z->type = type_NotDefined;
z->pausiness = .0;
z->numFrag = 0;
z->hqBeg = 0;
z->hqEnd = 0;
z->regionScore = -1;
int i;
for (i = 0; i < z->maxFrag; i++)
resetSlowPolymeraseRegions(z->spr + i);
}
void ensureZMWCapacity(ZMW *z)
{
if (z->numFrag + 1 == z->maxFrag)
{
z->maxFrag = (int) (z->maxFrag * 1.2) + 5;
z->insBeg = (int*) realloc(z->insBeg, z->maxFrag * sizeof(int));
z->insEnd = (int*) realloc(z->insEnd, z->maxFrag * sizeof(int));
z->insTimeBeg = (int*) realloc(z->insTimeBeg, z->maxFrag * sizeof(int));
z->insTimeEnd = (int*) realloc(z->insTimeEnd, z->maxFrag * sizeof(int));
z->toReport = (char*) realloc(z->toReport, z->maxFrag);
z->len = (int*) realloc(z->len, z->maxFrag * sizeof(int));
z->fragQual = (unsigned char**) realloc(z->fragQual, z->maxFrag * sizeof(unsigned char*));
z->fragSequ = (unsigned char**) realloc(z->fragSequ, z->maxFrag * sizeof(unsigned char*));
z->widthInFrames = (unsigned short**) realloc(z->widthInFrames, z->maxFrag * sizeof(unsigned short*));
z->preBaseFrames = (unsigned short**) realloc(z->preBaseFrames, z->maxFrag * sizeof(unsigned short*));
z->delQV = (unsigned char**) realloc(z->delQV, z->maxFrag * sizeof(unsigned char*));
z->delTag = (unsigned char**) realloc(z->delTag, z->maxFrag * sizeof(unsigned char*));
z->insQV = (unsigned char**) realloc(z->insQV, z->maxFrag * sizeof(unsigned char*));
z->mergeQV = (unsigned char**) realloc(z->mergeQV, z->maxFrag * sizeof(unsigned char*));
z->subQV = (unsigned char**) realloc(z->subQV, z->maxFrag * sizeof(unsigned char*));
z->avgQV = (float*) realloc(z->avgQV, z->maxFrag * sizeof(float));
z->spr = (slowPolymeraseRegions*) realloc(z->spr, z->maxFrag * sizeof(slowPolymeraseRegions));
int i;
for (i = z->numFrag + 1; i < z->maxFrag; i++)
initSlowPolymeraseRegions(z->spr + i, 100, 50);
}
}
void deleteZMW(ZMW *z)
{
z->numFrag = 0;
z->maxFrag = 0;
deleteSlowPolymeraseRegions(z->spr);
free(z->insBeg);
free(z->insEnd);
free(z->insTimeBeg);
free(z->insTimeEnd);
free(z->toReport);
free(z->len);
free(z->fragSequ);
free(z->fragQual);
free(z->avgQV);
free(z->widthInFrames);
free(z->preBaseFrames);
free(z->delQV);
free(z->delTag);
free(z->insQV);
free(z->mergeQV);
free(z->subQV);
free(z);
}
void printZMW(ZMW* z)
{
printf("--------- ZMW ---------\n");
printf("hole number: %d (index: %d) (regionRow: %d) (roff: %d)\n", z->number, z->index, z->regionRow, z->roff);
printf("status: %d\n", z->status);
printf("pausiness: %.5f\n", z->pausiness);
printf("readType: %d\n", z->type);
printf("product: %d\n", z->prod);
printf("hqBeg: %d\n", z->hqBeg);
printf("hqEnd: %d\n", z->hqEnd);
printf("score: %d\n", z->regionScore);
printf("fragments: %d\n", z->numFrag);
int i;
for (i = 0; i < z->numFrag; i++)
{
printf("frag %d: report: %d, ins: %d_%d, time: %d-%d len: %d\n", i, z->toReport[i], z->insBeg[i], z->insEnd[i], (int) (z->insTimeBeg[i] / FRAME_RATE / 60), (int) (z->insTimeEnd[i] / FRAME_RATE / 60), z->len[i]);
}
}
void initBaxNames(BaxData *b, char *fname)
{
// set pointer from fname to b->fullname
b->fullName = fname;
char *c;
int epos;
c = strrchr(fname, '/');
if (c != NULL)
b->shortNameBeg = c - fname + 1;
else
b->shortNameBeg = 0;
epos = strlen(fname);
if ((epos >= 9) && ((strcasecmp(fname + (epos - 9), ".1.bax.h5") == 0) || (strcasecmp(fname + (epos - 9), ".2.bax.h5") == 0) || (strcasecmp(fname + (epos - 9), ".3.bax.h5") == 0)))
b->shortNameEnd = epos - 9;
else
b->shortNameEnd = epos;
}
// Check if memory needed is above high water mark, and if so allocate
void ensureCapacity(BaxData *b, hsize_t numBaseCalls, hsize_t numHoles, hsize_t numHQReads)
{
static hsize_t bmax = 0; // base call streams + metrics (number of bases)
static hsize_t hmax = 0; // streams corresponding to a single ZMW (number of ZMW)
static hsize_t rmax = 0; // streams correspiding to singles hq subreads (number of all HQ subreads)
if (bmax < numBaseCalls)
{
bmax = 1.2 * numBaseCalls + 10000;
if ((b->baseCall = (unsigned char *) realloc(b->baseCall, 8ll * bmax)) == NULL)
{
fprintf(stderr, "Cannot allocate basecall buffer\n");
exit(1);
}
b->fastQV = b->baseCall + bmax;
b->delQV = b->fastQV + bmax;
b->delTag = b->delQV + bmax;
b->insQV = b->delTag + bmax;
b->mergeQV = b->insQV + bmax;
b->subQV = b->mergeQV + bmax;
if ((b->widthInFrames = (unsigned short *) realloc(b->widthInFrames, 2ll * bmax * sizeof(unsigned short))) == NULL)
{
fprintf(stderr, "Cannot allocate frame buffer\n");
exit(1);
}
b->preBaseFrames = b->widthInFrames + bmax;
}
if (hmax < numHoles)
{
hmax = 1.2 * numHoles + 1000;
if ((b->numEvent = (int *) realloc(b->numEvent, hmax * sizeof(int))) == NULL)
{
fprintf(stderr, "Cannot allocate event buffer\n");
exit(1);
}
if ((b->holeStatus = (char *) realloc(b->holeStatus, hmax)) == NULL)
{
fprintf(stderr, "Cannot allocate status buffer\n");
exit(1);
}
if ((b->hqRegionBegTime = (float *) realloc(b->hqRegionEndTime, 2ll * hmax * sizeof(float))) == NULL)
{
fprintf(stderr, "Cannot allocate HQregion buffer\n");
exit(1);
}
b->hqRegionEndTime = b->hqRegionBegTime + hmax;
if ((b->productivity = (unsigned char *) realloc(b->productivity, 2ll * hmax)) == NULL)
{
fprintf(stderr, "Cannot allocate productivity buffer\n");
exit(1);
}
b->readType = b->productivity + hmax;
if ((b->pausiness = (float *) realloc(b->pausiness, hmax * sizeof(float))) == NULL)
{
fprintf(stderr, "Cannot allocate pausiness buffer\n");
exit(1);
}
}
if (rmax < numHQReads)
{
rmax = 1.1 * numHQReads + 1000;
if ((b->region = (int *) realloc(b->region, 5ll * rmax * sizeof(int))) == NULL)
{
fprintf(stderr, "Cannot allocate HQregion buffer\n");
exit(1);
}
}
}
void initBaxStatistic(BaxStatistic *s, BAX_OPT *bopt)
{
s->nFiles = 0;
s->nZMWs = 0;
memset(s->readTypeHist, 0, (type_NotDefined + 1) * sizeof(s->readTypeHist[0]));
memset(s->productiveHist, 0, (prod_NotDefined + 1) * sizeof(s->productiveHist[0]));
memset(s->stateHist, 0, (UNKNOWN + 1) * sizeof(s->stateHist[0]));
s->cumPausiness = .0f;
s->minLen = bopt->MIN_LEN;
s->minScore = bopt->MIN_QV;
s->cumulative = bopt->CUMULATIVE;
s->readLenBinSize = bopt->READLEN_BIN_SIZE;
s->timeLenBinSize = bopt->TIME_BIN_SIZE;
s->minMovieTime = bopt->MIN_MOVIE_TIME;
s->maxMovieTime = bopt->MAX_MOVIE_TIME;
s->numSubreadBases = 0;
s->numSubreads = 0;
s->nLenBins = (MAX_READ_LEN / bopt->READLEN_BIN_SIZE) + 1;
s->readLengthHist = NULL;
if ((s->readLengthHist = (uint64*) malloc(3ll * sizeof(uint64) * s->nLenBins)) == NULL)
{
fprintf(stderr, "Cannot allocate read length histogram buffer\n");
exit(1);
}
s->readLengthBasesHist = s->readLengthHist + s->nLenBins;
s->readLengthTimeHist = s->readLengthBasesHist + s->nLenBins;
s->nTimBins = (MAX_TIME_LIMIT / bopt->TIME_BIN_SIZE) + 1;
s->cumTimeDepQVs = (uint64**) malloc((SUB_SUM + 1) * sizeof(uint64*));
int i;
for (i = NUC_COUNT; i <= SUB_SUM; i++)
{
s->cumTimeDepQVs[i] = (uint64*) malloc(s->nTimBins * sizeof(uint64));
memset(s->cumTimeDepQVs[i], 0, s->nTimBins * sizeof(uint64));
}
if ((s->baseDistributionHist = (uint64**) malloc(BASE_N + 1 * sizeof(uint64*) * s->nTimBins)) == NULL)
{
fprintf(stderr, "Cannot allocate base distribution histogram buffer\n");
exit(1);
}
for (i = BASE_A; i <= BASE_N; i++)
{
s->baseDistributionHist[i] = (uint64*) malloc(s->nTimBins * sizeof(uint64));
memset(s->baseDistributionHist[i], 0, s->nTimBins * sizeof(uint64));
}
memset(s->readLengthHist, 0, 3 * s->nLenBins * sizeof(s->readLengthHist[0]));
memset(s->subreadHist, 0, (MAX_SUBREADS + 1) * sizeof(s->subreadHist[0]));
s->cumSlowPolymeraseRegionLenHist = (uint64*) malloc(2ll * s->nLenBins * sizeof(uint64));
s->nSlowPolymeraseRegionLenHist = s->cumSlowPolymeraseRegionLenHist + s->nLenBins;
memset(s->cumSlowPolymeraseRegionLenHist, 0, 2ll * s->nLenBins * sizeof(uint64));
s->cumSlowPolymeraseRegionTimeHist = (uint64*) malloc(s->nTimBins * sizeof(uint64));
memset(s->cumSlowPolymeraseRegionTimeHist, 0, s->nTimBins * sizeof(uint64));
}
void resetBaxStatistic(BaxStatistic *s)
{
s->numSubreadBases = 0;
s->numSubreads = 0;
s->nFiles = 0;
s->nZMWs = 0;
memset(s->readTypeHist, 0, (type_NotDefined + 1) * sizeof(s->readTypeHist[0]));
memset(s->productiveHist, 0, (prod_NotDefined + 1) * sizeof(s->productiveHist[0]));
memset(s->stateHist, 0, (UNKNOWN + 1) * sizeof(s->stateHist[0]));
s->cumPausiness = .0f;
memset(s->readLengthHist, 0, 3 * s->nLenBins * sizeof(s->readLengthHist[0]));
int i;
for (i = BASE_A; i <= BASE_N; i++)
memset(s->baseDistributionHist[i], 0, s->nTimBins * sizeof(uint64));
memset(s->subreadHist, 0, (MAX_SUBREADS + 1) * sizeof(s->subreadHist[0]));
for (i = NUC_COUNT; i <= SUB_SUM; i++)
memset(s->cumTimeDepQVs[i], 0, s->nTimBins * sizeof(uint64));
memset(s->cumSlowPolymeraseRegionLenHist, 0, 2ll * s->nLenBins * sizeof(uint64));
memset(s->cumSlowPolymeraseRegionTimeHist, 0, s->nTimBins * sizeof(uint64));
}
void freeBaxStatistic(BaxStatistic* s)
{
free(s->readLengthHist);
int i;
for (i = NUC_COUNT; i <= SUB_SUM; i++)
if (s->cumTimeDepQVs[i])
free(s->cumTimeDepQVs[i]);
for (i = BASE_A; i <= BASE_N; i++)
if (s->baseDistributionHist[i])
free(s->baseDistributionHist[i]);
free(s->cumTimeDepQVs);
free(s->baseDistributionHist);
free(s->cumSlowPolymeraseRegionLenHist);
free(s->cumSlowPolymeraseRegionTimeHist);
}
void ln_estimate2(unsigned short* data1, unsigned short* data2, int beg, int end, double* mu, double* sig)
{
double _mu = 0.0;
double _sig = 0.0;
int i;
for (i = beg; i < end; i++)
{
_mu += log(data1[i] + data2[i]);
}
_mu = _mu / (end - beg);
for (i = beg; i < end; i++)
{
_sig += SQR(log(data1[i] + data2[i]) - _mu);
}
_sig = sqrt(_sig / (end - beg));
*mu = _mu;
*sig = _sig;
}
void n_estimate2(unsigned short* data1, unsigned short* data2, int beg, int end, double* mu, double* sig)
{
double _mu = 0.0;
double _sig = 0.0;
int i;
for (i = beg; i < end; i++)
{
_mu += data1[i] + data2[i];
}
_mu = _mu / (end - beg);
for (i = beg; i < end; i++)
{
_sig += SQR((data1[i] + data2[i]) - _mu);
}
_sig = sqrt(_sig / (end - beg));
*mu = _mu;
*sig = _sig;
}
void printBaxError(int errorCode)
{
fprintf(stderr, " *** Warning ***: ");
switch (errorCode)
{
case CANNOT_OPEN_BAX_FILE:
fprintf(stderr, "Cannot open bax file:\n");
break;
case BAX_BASECALL_ERR:
fprintf(stderr, "Cannot parse /PulseData/BaseCalls/Basecall from file:\n");
break;
case BAX_DELETIONQV_ERR:
fprintf(stderr, "Cannot parse /PulseData/BaseCalls/DeletionQV from file:\n");
break;
case BAX_DELETIONTAG_ERR:
fprintf(stderr, "Cannot parse /PulseData/BaseCalls/DeletionTag from file:\n");
break;
case BAX_INSERTIONQV_ERR:
fprintf(stderr, "Cannot parse /PulseData/BaseCalls/InsertionQV from file:\n");
break;
case BAX_MERGEQV_ERR:
fprintf(stderr, "Cannot parse /PulseData/BaseCalls/MergeQV from file:\n");
break;
case BAX_SUBSTITUTIONQV_ERR:
fprintf(stderr, "Cannot parse /PulseData/BaseCalls/SubstitutionQV from file:\n");
break;
case BAX_QV_ERR:
fprintf(stderr, "Cannot parse /PulseData/BaseCalls/QualityValue from file:\n");
break;
case BAX_NR_EVENTS_ERR:
fprintf(stderr, "Cannot parse /PulseData/BaseCalls/ZMW/NumEvent from file:\n");
break;
case BAX_REGION_ERR:
fprintf(stderr, "Cannot parse /PulseData/Regions from file:\n");
break;
case BAX_HOLESTATUS_ERR:
fprintf(stderr, "Cannot parse /PulseData/BaseCalls/ZMW/HoleStatus from file:\n");
break;
case BAX_WIDTHINFRAMES_ERR:
fprintf(stderr, "Cannot parse /PulseData/BaseCalls/WidthInFrames from file:\n");
break;
case BAX_PREBASEFRAMES_ERR:
fprintf(stderr, "Cannot parse /PulseData/BaseCalls/PreBaseFrames from file:\n");
break;
case BAX_HQREGIONSTARTTIME_ERR:
fprintf(stderr, "Cannot parse /PulseData/BaseCalls/ZMWMetrics/HQRegionStartTime from file:\n");
break;
case BAX_HQREGIONENDTIME_ERR:
fprintf(stderr, "Cannot parse /PulseData/BaseCalls/ZMWMetrics/HQRegionEndTime from file:\n");
break;
case BAX_PAUSINESS_ERR:
fprintf(stderr, "Cannot parse /PulseData/BaseCalls/ZMWMetrics/Pausiness from file:\n");
break;
case BAX_PRODUCTIVITY_ERR:
fprintf(stderr, "Cannot parse /PulseData/BaseCalls/ZMWMetrics/Productivity from file:\n");
break;
case BAX_READTYPE_ERR:
fprintf(stderr, "Cannot parse /PulseData/BaseCalls/ZMWMetrics/ReadType from file:\n");
break;
case IGNORE_BAX:
fprintf(stderr, "Ignore bax file\n");
break;
default:
fprintf(stderr, "Cannot parse bax file:\n");
break;
}
fflush(stderr);
}
void initSlowPolymeraseRegions(slowPolymeraseRegions *spr, int segmentWidth, int shift)
{
spr->segmentWidth = segmentWidth;
spr->shift = shift;
spr->nRegions = 0;
spr->nmax = 10;
spr->beg = (int*) malloc(spr->nmax * sizeof(int));
spr->end = (int*) malloc(spr->nmax * sizeof(int));
spr->numSlowBases = 0;
}
void resetSlowPolymeraseRegions(slowPolymeraseRegions *spr)
{
spr->nRegions = 0;
spr->numSlowBases = 0;
}
void ensureSlowPolymeraseRegionsCapacity(slowPolymeraseRegions *spr)
{
if (spr->nRegions + 1 == spr->nmax)
{
spr->nmax = (int) (spr->nmax * 1.2) + 5;
spr->beg = realloc(spr->beg, spr->nmax * sizeof(int));
spr->end = realloc(spr->end, spr->nmax * sizeof(int));
}
}
void deleteSlowPolymeraseRegions(slowPolymeraseRegions *spr)
{
free(spr->beg);
free(spr->end);
free(spr);
}
int isBaseInSlowPolymeraseRegion(slowPolymeraseRegions *spr, int baseIdx)
{
if (spr == NULL)
return 0;
int i;
for (i = 0; i < spr->nRegions; i++)
if (baseIdx >= spr->beg[i] && baseIdx <= spr->end[i])
return 1;
return 0;
}
void Print_Number(FILE* out, int64 num, int width)
{
if (width == 0)
{
if (num < 1000ll)
fprintf(out, "%lld", num);
else if (num < 1000000ll)
fprintf(out, "%lld%c%03lld", num / 1000ll, COMMA, num % 1000ll);
else if (num < 1000000000ll)
fprintf(out, "%lld%c%03lld%c%03lld", num / 1000000ll, COMMA, (num % 1000000ll) / 1000ll, COMMA, num % 1000ll);
else
fprintf(out, "%lld%c%03lld%c%03lld%c%03lld", num / 1000000000ll,
COMMA, (num % 1000000000ll) / 1000000ll, COMMA, (num % 1000000ll) / 1000ll, COMMA, num % 1000ll);
}
else
{
if (num < 1000ll)
fprintf(out, "%*lld", width, num);
else if (num < 1000000ll)
fprintf(out, "%*lld%c%03lld", width - 4, num / 1000ll, COMMA, num % 1000ll);
else if (num < 1000000000ll)
fprintf(out, "%*lld%c%03lld%c%03lld", width - 8, num / 1000000ll,
COMMA, (num % 1000000ll) / 1000ll, COMMA, num % 1000ll);
else
fprintf(out, "%*lld%c%03lld%c%03lld%c%03lld", width - 12, num / 1000000000ll, COMMA, (num % 1000000000ll) / 1000000ll,
COMMA, (num % 1000000ll) / 1000ll, COMMA, num % 1000ll);
}
}
|
MartinPippel/DAmar
|
scrub/LArepeat.c
|
/*******************************************************************************************
*
* creates a repeat annotation track (named -t) based on coverage statistics
*
* intervals are tagged as repetitive when the -h coverage threshold is reached
* and terminated when the coverage drops below -l
*
* -n ... max number of overlap groups that should be used for the coverage estimate
* -m ... merge consecutive repeats with distance less than -m
*
* Date : February 2017
*
* Author : <NAME>
*
*******************************************************************************************/
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#include <unistd.h>
#include "lib/colors.h"
#include "lib/oflags.h"
#include "lib/pass.h"
#include "lib/tracks.h"
#include "lib/utils.h"
#include "dalign/align.h"
#include "db/DB.h"
// constants
#define MIN_OVERLAP_GROUPS 1000 // min number of groups for coverage estimate
#define EDGE_TAGGING_DIST 1000 // max distance of the repeat to the repeat ends
#define EDGE_TAGGING_FUZZ 200 // number of wiggle bases for alignment termination at repeat ends
#define DEFAULT_RP_XCOV_ENTER 2.0
#define DEFAULT_RP_XCOV_LEAVE 1.7
#define DEFAULT_RP_MERGE_DIST -1
#define DEFAULT_COV -1
#define DEFAULT_COV_MAX_READS -1
#define DEFAULT_MAX_COVERAGE 100 // max for coverage histogram
#define DEF_ARG_IC 0
#define DEF_ARG_O 0
// toggles
#define VERBOSE
#undef DEBUG
// macros
typedef struct
{
HITS_DB* db;
int cov; // expected/estimated coverage
int avg_rlen; // average read length
int inccov; // include coverage in the resulting track
int min_aln_len;
int inc_Iovls;
int max_cov;
// coverage pass
int64 *cov_histo;
int64 cov_bases;
int64 cov_inactive_bases;
char* cov_read_active;
int cov_areads;
int cov_max_areads;
int64 bases;
int64 reads;
// repeat pass
int rp_emax;
int rp_dmax;
int rp_dcur;
track_data* rp_data;
track_anno* rp_anno;
int* rp_events;
int rp_merge_dist;
int rp_merged;
int64 rp_bases;
int64 rp_repeat_bases;
char* rp_track;
int rp_block;
double rp_xcov_enter;
double rp_xcov_leave;
} RepeatContext;
extern char* optarg;
extern int optind, opterr, optopt;
static int cmp_repeats_events( const void* x, const void* y )
{
int* e1 = (int*)x;
int* e2 = (int*)y;
int cmp = abs( *e1 ) - abs( *e2 );
if ( cmp == 0 )
{
cmp = ( *e1 ) - ( *e2 );
}
return cmp;
}
static void pre_coverage( RepeatContext* ctx )
{
#ifdef VERBOSE
printf( ANSI_COLOR_GREEN "PASS estimate coverage\n" ANSI_COLOR_RESET );
#endif
ctx->cov_read_active = (char*)malloc( DB_READ_MAXLEN( ctx->db ) );
ctx->cov_histo = malloc(sizeof( int64 ) * ctx->max_cov);
bzero( ctx->cov_histo, sizeof( int64 ) * ctx->max_cov );
}
static void post_coverage( RepeatContext* ctx )
{
int max = 0;
int cov = ctx->cov_histo[ 0 ];
ctx->avg_rlen = ctx->bases / ctx->reads;
int j;
for ( j = 1; j < ctx->max_cov; j++ )
{
if ( cov < ctx->cov_histo[ j ] )
{
cov = ctx->cov_histo[ j ];
max = j;
}
}
ctx->cov = max;
free( ctx->cov_read_active );
#ifdef VERBOSE
for ( j = 0; j < ctx->max_cov; j++ )
{
printf( "COV %d READS %lld\n", j, ctx->cov_histo[ j ] );
}
printf( "MAX %d\n", max );
printf( "INACTIVE %lld (%d%%) OF %lld\n",
ctx->cov_inactive_bases, (int)( 100.0 * ctx->cov_inactive_bases / ctx->cov_bases ), ctx->cov_bases );
printf( "AVG_RLEN %d\n", ctx->avg_rlen );
#endif
free(ctx->cov_histo);
}
static int handler_coverage( void* _ctx, Overlap* ovl, int novl )
{
RepeatContext* ctx = (RepeatContext*)_ctx;
int ovlArlen = DB_READ_LEN( ctx->db, ovl->aread );
ctx->bases += ovlArlen;
ctx->reads++;
int i;
int64 cov;
int64 bases = 0;
bzero( ctx->cov_read_active, DB_READ_MAXLEN( ctx->db ) );
for ( i = 0; i < novl; i++ )
{
if ( !( DB_READ_FLAGS( ctx->db, ovl[ i ].bread ) & DB_BEST ) || ( ovl[ i ].flags & OVL_DISCARD ) )
{
continue;
}
if ( ovl[ i ].aread == ovl[ i ].bread )
continue;
if ( ovl[i].path.aepos - ovl[i].path.abpos < ctx->min_aln_len )
{
continue;
}
bases += ovl[ i ].path.aepos - ovl[ i ].path.abpos;
memset( ctx->cov_read_active + ovl[ i ].path.abpos, 1, ovl[ i ].path.aepos - ovl[ i ].path.abpos );
}
int active = 0;
for ( i = 0; i < ovlArlen; i++ )
{
active += ctx->cov_read_active[ i ];
}
if ( active > 0 )
{
cov = bases / active;
}
else
{
cov = 0;
}
if ( cov < ctx->max_cov )
{
ctx->cov_histo[ cov ]++;
}
ctx->cov_bases += ovlArlen;
ctx->cov_inactive_bases += ovlArlen - active;
ctx->cov_areads++;
if ( ctx->cov_areads > ctx->cov_max_areads )
{
return 0;
}
return 1;
}
static void pre_repeats( RepeatContext* ctx )
{
#ifdef VERBOSE
printf( ANSI_COLOR_GREEN "PASS repeats\n" ANSI_COLOR_RESET );
#endif
ctx->rp_emax = 100;
ctx->rp_events = (int*)malloc( sizeof( int ) * ctx->rp_emax );
ctx->rp_anno = (track_anno*)malloc( sizeof( track_anno ) * ( DB_NREADS( ctx->db ) + 1 ) );
bzero( ctx->rp_anno, sizeof( track_anno ) * ( DB_NREADS( ctx->db ) + 1 ) );
ctx->rp_dcur = 0;
ctx->rp_dmax = 100;
ctx->rp_data = (track_data*)malloc( sizeof( track_data ) * ctx->rp_dmax );
}
static void post_repeats( RepeatContext* ctx )
{
int j;
track_anno coff, off;
off = 0;
for ( j = 0; j <= DB_NREADS( ctx->db ); j++ )
{
coff = ctx->rp_anno[ j ];
ctx->rp_anno[ j ] = off;
off += coff;
}
track_write( ctx->db, ctx->rp_track, ctx->rp_block, ctx->rp_anno, ctx->rp_data, ctx->rp_dcur );
free( ctx->rp_anno );
free( ctx->rp_data );
free( ctx->rp_events );
#ifdef VERBOSE
printf( "COV_ENTER %.1f\n", ctx->rp_xcov_enter );
printf( "COV_LEAVE %.1f\n", ctx->rp_xcov_leave );
printf( "REGIONS %d\n", ( ctx->rp_dcur ) / ( 2 + ctx->inccov ) );
printf( "MERGED %d\n", ctx->rp_merged );
printf( "BASES_TOTAL %lld\n", ctx->rp_bases );
printf( "BASES_REPEAT %lld\n", ctx->rp_repeat_bases );
printf( "BASES_REPEAT_PERCENT %d%%\n", (int)( ctx->rp_repeat_bases * 100.0 / ctx->rp_bases ) );
#endif
}
static int handler_repeats( void* _ctx, Overlap* ovl, int novl )
{
RepeatContext* ctx = (RepeatContext*)_ctx;
int* rp_events = ctx->rp_events;
uint64_t rp_repeat_bases = 0;
uint64_t rp_merged = 0;
int rp_merge_dist = ctx->rp_merge_dist;
ctx->rp_bases += DB_READ_LEN( ctx->db, ovl->aread );
if ( 2 * novl > ctx->rp_emax )
{
ctx->rp_emax = 1.2 * ctx->rp_emax + 2 * novl;
ctx->rp_events = rp_events = (int*)realloc( rp_events, sizeof( int ) * ctx->rp_emax );
}
int i;
int j = 0;
for ( i = 0; i < novl; i++ )
{
// TODO ... check if OVL_DISCARD flag is needed
if ( ovl[ i ].flags & OVL_DISCARD )
{
continue;
}
if (!ctx->inc_Iovls && ovl[ i ].aread == ovl[ i ].bread )
{
continue;
}
if ( ovl[i].path.aepos - ovl[i].path.abpos < ctx->min_aln_len )
{
continue;
}
rp_events[ j++ ] = ovl[ i ].path.abpos;
rp_events[ j++ ] = -( ovl[ i ].path.aepos - 1 );
}
novl = j / 2;
qsort( rp_events, 2 * novl, sizeof( int ), cmp_repeats_events );
int span = 0;
int span_leave = ctx->cov * ctx->rp_xcov_leave;
int span_enter = ctx->cov * ctx->rp_xcov_enter;
int a = ovl->aread;
int inccov = ctx->inccov;
track_data* rp_data = ctx->rp_data;
track_anno* rp_anno = ctx->rp_anno;
int span_max = 0;
int in_repeat = 0;
int rp_dcur = ctx->rp_dcur;
for ( i = 0; i < 2 * novl; i++ )
{
if ( rp_events[ i ] < 0 )
{
span--;
}
else
{
span++;
if ( span > span_max )
{
span_max = span;
}
}
if ( in_repeat )
{
if ( span < span_leave )
{
#ifdef DEBUG
printf( "repeat <- %d @ %d\n", a, -( rp_events[ i ] ) );
#endif
rp_anno[ a ] += ( inccov + 1 ) * sizeof( track_data );
rp_data[ rp_dcur++ ] = -( rp_events[ i ] );
rp_repeat_bases += rp_data[ rp_dcur - 1 ] - rp_data[ rp_dcur - 2 ];
if ( inccov )
{
rp_data[ rp_dcur++ ] = span_max;
}
in_repeat = 0;
}
}
else
{
if ( span > span_enter )
{
#ifdef DEBUG
printf( "repeat -> %d @ %d\n", a, rp_events[ i ] );
#endif
if ( rp_dcur + 3 >= ctx->rp_dmax )
{
ctx->rp_dmax = 1.2 * ctx->rp_dmax + 20;
ctx->rp_data = rp_data = (int*)realloc( rp_data, sizeof( int ) * ctx->rp_dmax );
}
if ( rp_dcur - ctx->rp_dcur >= ( inccov + 2 ) &&
rp_events[ i ] - rp_data[ rp_dcur - ( 1 + inccov ) ] < rp_merge_dist )
{
#ifdef DEBUG
printf( " merge\n" );
#endif
span_max = rp_data[ rp_dcur - 1 ];
rp_dcur -= ( inccov + 1 );
rp_anno[ a ] -= 2 * sizeof( track_data );
rp_merged++;
}
else
{
span_max = 0;
rp_anno[ a ] += 1 * sizeof( track_data );
rp_data[ rp_dcur++ ] =rp_events[ i ];
}
in_repeat = 1;
}
}
}
#ifdef DEBUG
if ( ctx->rp_dcur != rp_dcur )
{
for ( i = ctx->rp_dcur; i < rp_dcur; i += ( 2 + inccov ) )
{
if ( i != ctx - rp_dcur )
{
printf( " " );
}
if ( inccov )
{
printf( "(%d %d @ %d)", rp_data[ i ], rp_data[ i + 1 ], rp_data[ i + 2 ] );
}
else
{
printf( "(%d %d)", rp_data[ i ], rp_data[ i + 1 ] );
}
}
printf( "\n" );
}
#endif
int alen = DB_READ_LEN(ctx->db, a);
for ( i = ctx->rp_dcur ; i < rp_dcur ; i += ( 2 + inccov) )
{
int rb = rp_data[i];
int re = rp_data[i+1];
if ( rb > 0 && rb < EDGE_TAGGING_DIST && re < alen - EDGE_TAGGING_DIST )
{
int support = 0;
for ( j = 0; j < novl; j++)
{
Overlap* o = ovl + j;
if ( o->path.aepos > re - EDGE_TAGGING_FUZZ && o->path.aepos < re + EDGE_TAGGING_FUZZ && o->path.abpos == 0 )
{
support += 1;
}
}
if ( support > 2 )
{
// printf("%7d repeat %5d..%5d extended to %5d..%5d\n", a, rp_data[i], rp_data[i+1], 0, rp_data[i+1]);
rp_data[i] = 0;
}
}
if ( re < alen - 1 && re > alen - EDGE_TAGGING_DIST && rb > EDGE_TAGGING_DIST )
{
int support = 0;
for ( j = 0; j < novl; j++)
{
Overlap* o = ovl + j;
if ( o->path.abpos > rb - EDGE_TAGGING_FUZZ && o->path.abpos < rb + EDGE_TAGGING_FUZZ && o->path.aepos == alen )
{
support += 1;
}
}
if ( support > 2 )
{
// printf("%7d repeat %5d..%5d extended to %5d..%5d\n", a, rp_data[i], rp_data[i+1], rp_data[i], alen);
rp_data[i + 1] = alen;
}
}
}
ctx->rp_dcur = rp_dcur;
ctx->rp_repeat_bases += rp_repeat_bases;
ctx->rp_merged += rp_merged;
return 1;
}
static void usage()
{
printf( "usage: [-EI] [-hl <float>] [-tT <track>] [-bcmno <int>] <db> <overlaps>\n" );
printf( "options: -h ... repeat enter coverage (%.1f)\n", DEFAULT_RP_XCOV_ENTER );
printf( " -l ... repeat leave coverage (%.1f)\n", DEFAULT_RP_XCOV_LEAVE );
printf( " -t ... track name (" TRACK_REPEATS ")\n" );
printf( " -o ... min overlap length\n");
printf( " -E ... only report coverage based on overlaps\n" );
printf( " -I ... include identity overlaps\n" );
printf( " -b ... track block\n" );
printf( " -c ... expected coverage (%d)\n", DEFAULT_COV );
printf( " -m ... merge distance in bp (%d)\n", DEFAULT_RP_MERGE_DIST );
printf( " -n ... # of a reads used for coverage estimate (%d)\n", DEFAULT_COV_MAX_READS );
printf( " -M ... maximum coverage (%d)\n", DEFAULT_MAX_COVERAGE);
}
int main( int argc, char* argv[] )
{
HITS_DB db;
PassContext* pctx;
RepeatContext rctx;
FILE* fileOvlIn;
bzero( &rctx, sizeof( RepeatContext ) );
rctx.db = &db;
// process arguments
rctx.rp_xcov_enter = DEFAULT_RP_XCOV_ENTER;
rctx.rp_xcov_leave = DEFAULT_RP_XCOV_LEAVE;
rctx.rp_merge_dist = DEFAULT_RP_MERGE_DIST;
rctx.cov = DEFAULT_COV;
rctx.cov_max_areads = DEFAULT_COV_MAX_READS;
rctx.rp_track = TRACK_REPEATS;
rctx.rp_block = 0;
rctx.inccov = DEF_ARG_IC;
rctx.min_aln_len = DEF_ARG_O;
rctx.inc_Iovls = 0;
rctx.max_cov = DEFAULT_MAX_COVERAGE;
int COV_ONLY = 0;
int c;
opterr = 0;
while ( ( c = getopt( argc, argv, "Ch:l:m:c:n:t:b:o:EIM:" ) ) != -1 )
{
switch ( c )
{
case 'E':
COV_ONLY = 1;
break;
case 'I':
rctx.inc_Iovls = 1;
break;
case 'o':
rctx.min_aln_len = atoi(optarg);
break;
case 'C':
rctx.inccov = 1;
break;
case 'M':
rctx.max_cov = atoi(optarg);
break;
case 'b':
rctx.rp_block = atoi( optarg );
break;
case 'h':
rctx.rp_xcov_enter = atof( optarg );
break;
case 'l':
rctx.rp_xcov_leave = atof( optarg );
break;
case 'm':
rctx.rp_merge_dist = atoi( optarg );
break;
case 'c':
rctx.cov = atoi( optarg );
break;
case 'n':
rctx.cov_max_areads = atoi( optarg );
break;
case 't':
rctx.rp_track = optarg;
break;
default:
usage();
exit( 1 );
}
}
if ( argc - optind != 2 )
{
usage();
exit( 1 );
}
char* pcPathReadsIn = argv[ optind++ ];
char* pcPathOverlaps = argv[ optind++ ];
if ( rctx.rp_xcov_enter < rctx.rp_xcov_leave )
{
fprintf( stderr, "invalid arguments: low %.2f > high %.2f\n", rctx.rp_xcov_leave, rctx.rp_xcov_enter );
exit( 1 );
}
if ( rctx.cov_max_areads != -1 && rctx.cov_max_areads < MIN_OVERLAP_GROUPS )
{
fprintf( stderr, "invalid arguments: number of overlap groups tested should be larger than %d\n", MIN_OVERLAP_GROUPS );
exit( 1 );
}
if ( ( fileOvlIn = fopen( pcPathOverlaps, "r" ) ) == NULL )
{
fprintf( stderr, "could not open '%s'\n", pcPathOverlaps );
exit( 1 );
}
if(rctx.max_cov < DEFAULT_MAX_COVERAGE)
{
fprintf( stderr, "maximum coverage cannot be smallert than '%d'\n", DEFAULT_MAX_COVERAGE );
exit( 1 );
}
// init
pctx = pass_init( fileOvlIn, NULL );
pctx->split_b = 0;
pctx->load_trace = 1;
pctx->unpack_trace = 1;
pctx->data = &rctx;
Open_DB( pcPathReadsIn, &db );
if ( rctx.cov_max_areads == -1 )
{
rctx.cov_max_areads = db.nreads;
}
// passes
if ( rctx.cov <= 0 || COV_ONLY)
{
pre_coverage( &rctx );
pass( pctx, handler_coverage );
post_coverage( &rctx );
if ( rctx.cov <= 0 )
{
fprintf( stderr, "ERROR: coverage estimation resulted in %d\n", rctx.cov );
fprintf( stderr, " bypass estimation using the -c <coverage> argument\n" );
exit( 1 );
}
}
if (!COV_ONLY)
{
pre_repeats( &rctx );
pass( pctx, handler_repeats );
post_repeats( &rctx );
}
// cleanup
pass_free( pctx );
fclose( fileOvlIn );
Close_DB( &db );
return 0;
}
|
MartinPippel/DAmar
|
utils/LAstats.c
|
/*******************************************************************************************
*
* display basic stats on the overlaps contained in a .las file
*
* Author : <NAME>
*
* Date : May 2015
*
*******************************************************************************************/
#include <assert.h>
#include <limits.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#include <unistd.h>
#include "lib/colors.h"
#include "lib/oflags.h"
#include "lib/pass.h"
#include "lib/tracks.h"
#include "lib/utils.h"
#include "dalign/align.h"
#include "db/DB.h"
// command line defaults
#define DEF_ARG_S -1
#define DEF_ARG_F 0
#define DEF_ARG_B 1000
#define DEF_ARG_T TRACK_TRIM
// read flags
#define R_CONTAINED ( 1 << 0 )
#define R_USED_A ( 1 << 1 )
#define R_USED_B ( 1 << 2 )
#define R_CONTAINED_G ( 1 << 3 )
#define R_USED_A_G ( 1 << 4 )
#define R_USED_B_G ( 1 << 5 )
#define R_MASK_G ( R_CONTAINED_G | R_USED_A_G | R_USED_B_G )
typedef struct
{
// stat counters for a single overlap file
uint32_t nContainedReads;
uint64_t nContainedBases;
uint64_t nOverlaps;
uint64_t nComplementOverlaps;
uint64_t nIdentityOverlaps;
uint64_t nStitched;
// overall stat counters for all overlap files
uint32_t nAllContainedReads;
uint64_t nAllContainedBases;
uint64_t nAllBases;
uint64_t nAllOverlaps;
uint64_t nAllComplementOverlaps;
uint64_t nAllIdentityOverlaps;
// command line switches
int verbose;
int fuzzing;
int stitch;
int dumpOutContainedReads;
int raw;
int minRlen;
int minOlen;
// overlap length binning
int ovlBinSize;
int nbin;
int* hist;
uint64_t* bsum;
// db
HITS_DB* db;
HITS_TRACK* tracktrim;
} StatsContext;
// for getopt
extern char* optarg;
extern int optind, opterr, optopt;
static void stitch( StatsContext* ctx, Overlap* pOvls, int n, int sfuzz )
{
if ( n < 2 )
{
return;
}
int i, k, b;
int ab2, ae1, ae2;
int bb2, be1, be2;
const int ignore_mask = OVL_CONT | OVL_STITCH | OVL_GAP | OVL_TRIM;
for ( i = 0; i < n; i++ )
{
if ( pOvls[ i ].flags & ignore_mask )
{
continue;
}
b = pOvls[ i ].bread;
ae1 = pOvls[ i ].path.aepos;
be1 = pOvls[ i ].path.bepos;
for ( k = i + 1; k < n && pOvls[ k ].bread <= b; k++ )
{
if ( ( pOvls[ k ].flags & ignore_mask ) || ( pOvls[ i ].flags & OVL_COMP ) != ( pOvls[ k ].flags & OVL_COMP ) )
{
continue;
}
ab2 = pOvls[ k ].path.abpos;
ae2 = pOvls[ k ].path.aepos;
bb2 = pOvls[ k ].path.bbpos;
be2 = pOvls[ k ].path.bepos;
int deltaa = abs( ae1 - ab2 );
int deltab = abs( be1 - bb2 );
if ( deltaa < sfuzz && deltab < sfuzz && ( abs( deltaa - deltab ) < 40 ) )
{
pOvls[ i ].path.aepos = ae2;
pOvls[ i ].path.bepos = be2;
pOvls[ i ].path.diffs += pOvls[ k ].path.diffs;
pOvls[ i ].path.tlen = 0;
pOvls[ i ].flags &= ~( OVL_DISCARD | OVL_LOCAL ); // force a re-evaluation of the OVL_LOCAL flags
pOvls[ i ].flags |= OVL_OPTIONAL;
pOvls[ k ].flags |= OVL_DISCARD | OVL_STITCH | OVL_TEMP;
ctx->nStitched++;
}
}
}
}
static int contained_stats( StatsContext* ctx, Overlap* pOvls, int n )
{
int i, a, b;
int ab, ae, bb, be;
int rLenA, rLenB;
int tab, tae, tbb, tbe;
rLenA = DB_READ_LEN( ctx->db, pOvls->aread );
rLenB = DB_READ_LEN( ctx->db, pOvls->bread );
a = pOvls->aread;
b = pOvls->bread;
if ( ctx->tracktrim )
{
get_trim( ctx->db, ctx->tracktrim, a, &tab, &tae );
get_trim( ctx->db, ctx->tracktrim, b, &tbb, &tbe );
}
else
{
tab = 0;
tae = rLenA;
tbb = 0;
tbe = rLenB;
}
for ( i = 0; i < n; i++ )
{
Overlap* ovl = pOvls + i;
if ( ovl->flags & OVL_DISCARD )
{
continue;
}
ctx->nOverlaps++;
ab = ovl->path.abpos;
ae = ovl->path.aepos;
if ( ovl->flags & OVL_COMP )
{
ctx->nComplementOverlaps++;
bb = rLenB - ovl->path.bepos;
be = rLenB - ovl->path.bbpos;
}
else
{
bb = ovl->path.bbpos;
be = ovl->path.bepos;
}
// count identity overlaps
if ( ovl->aread == ovl->bread )
{
ctx->nIdentityOverlaps++;
}
// check for contained reads
if ( bb <= tbb + ctx->fuzzing && be >= tbe - ctx->fuzzing )
{
ctx->db->reads[ b ].flags |= R_CONTAINED | R_CONTAINED_G;
}
if ( ab <= tab + ctx->fuzzing && ae >= tae - ctx->fuzzing )
{
ctx->db->reads[ a ].flags |= R_CONTAINED | R_CONTAINED_G;
}
}
return 1;
}
static void stats_pre( StatsContext* fctx )
{
int nreads = fctx->db->nreads;
fctx->nContainedReads = 0;
fctx->nContainedBases = 0;
fctx->nOverlaps = 0;
fctx->nComplementOverlaps = 0;
fctx->nIdentityOverlaps = 0;
// allocate bit masks
if ( fctx->hist == NULL )
{
fctx->nbin = DB_READ_MAXLEN( fctx->db ) / fctx->ovlBinSize + 1;
fctx->hist = (int*)malloc( sizeof( int ) * fctx->nbin );
fctx->bsum = (uint64_t*)malloc( sizeof( uint64_t ) * fctx->nbin );
}
int i;
HITS_READ* reads = fctx->db->reads;
for ( i = 0; i < nreads; i++ )
{
reads[ i ].flags &= R_MASK_G;
}
bzero( fctx->hist, sizeof( int ) * fctx->nbin );
bzero( fctx->bsum, sizeof( uint64_t ) * fctx->nbin );
}
static void stats_post( StatsContext* ctx, int last )
{
// update stats
int i;
int dbReads = DB_NREADS( ctx->db );
int used = 0;
int useda = 0;
int usedb = 0;
int contained = 0;
uint64_t containedb = 0;
int raw = ctx->raw;
for ( i = 0; i < dbReads; i++ )
{
HITS_READ* read = ctx->db->reads + i;
int flags = read->flags;
if ( flags & R_CONTAINED )
{
contained += 1;
containedb += DB_READ_LEN( ctx->db, i );
}
if ( flags & ( R_USED_A | R_USED_B ) )
{
used += 1;
}
if ( flags & R_USED_A )
{
useda += 1;
}
if ( flags & R_USED_B )
{
usedb += 1;
}
}
uint64_t nbases = 0;
for ( i = ctx->nbin - 1; i >= 0; i-- )
{
if ( ctx->hist[ i ] )
{
nbases += ctx->bsum[ i ];
}
}
ctx->nAllBases += nbases;
// update overall stats
ctx->nAllOverlaps += ctx->nOverlaps;
ctx->nAllComplementOverlaps += ctx->nComplementOverlaps;
ctx->nAllIdentityOverlaps += ctx->nIdentityOverlaps;
// output
if (!raw)
{
printf( "a-reads: %7d\n", useda );
printf( "b-reads: %7d\n", usedb );
printf( "reads: %7d\n", used );
if ( contained > 0 )
{
printf( "#contained reads: %d (%.2f%%), contained bases: %" PRIu64 " (%.2f%%), avgLen: %" PRIu64 "\n",
contained,
100.0 * contained / used,
containedb,
100.0 * containedb / nbases,
containedb / contained );
}
if ( ctx->nIdentityOverlaps > 0 )
{
printf( "#identity overlaps %" PRIu64 " from %d reads\n",
ctx->nIdentityOverlaps,
useda );
}
}
if ( ctx->nOverlaps > 0 )
{
uint64_t nfwd = ctx->nOverlaps - ctx->nComplementOverlaps;
if (raw)
{
printf( "%" PRIu64 " %" PRIu64 "\n", ctx->nOverlaps, nbases / ctx->nOverlaps );
}
else
{
printf( "#overlaps %" PRIu64 ", n: %" PRIu64 " (%.2f%%), c: %" PRIu64 " (%.2f%%), avgLen %" PRIu64 "\n",
ctx->nOverlaps,
nfwd,
nfwd * 100.0 / ctx->nOverlaps,
ctx->nComplementOverlaps,
ctx->nComplementOverlaps * 100.0 / ctx->nOverlaps,
nbases / ctx->nOverlaps );
}
}
if ( !raw && ctx->nStitched > 0 )
{
printf( "#stitched overlaps %" PRIu64 "\n", ctx->nStitched );
}
if ( !raw )
{
printf( "\n Distribution of Overlap Lengths (Bin size = %d)\n\n Bin: Count %% Overlaps %% Bases cumAverage binAverage\n", ctx->ovlBinSize );
}
uint64_t cum = 0;
uint64_t btot = 0;
for ( i = ctx->nbin - 1; i >= 0; i-- )
{
cum += ctx->hist[ i ];
btot += ctx->bsum[ i ];
if ( ( ctx->hist[ i ] > 0 ) )
{
if (raw)
{
printf( "%d %d %.1f %.1f %" PRIu64 " %" PRIu64 "\n",
i * ctx->ovlBinSize,
ctx->hist[ i ],
( 100. * cum ) / ctx->nOverlaps,
( 100. * btot ) / nbases,
btot / cum,
ctx->bsum[ i ] / ctx->hist[ i ] );
}
else
{
printf( "%11d: %8d %5.1f %5.1f %9" PRIu64 " %9" PRIu64 "\n",
i * ctx->ovlBinSize,
ctx->hist[ i ],
( 100. * cum ) / ctx->nOverlaps,
( 100. * btot ) / nbases,
btot / cum,
ctx->bsum[ i ] / ctx->hist[ i ] );
}
}
}
if ( !raw && last )
{
int used_g = 0;
int useda_g = 0;
int usedb_g = 0;
int contained_g = 0;
uint64_t containedb_g = 0;
uint64_t nfwd_g = ctx->nAllOverlaps - ctx->nAllComplementOverlaps;
for ( i = 0; i < dbReads; i++ )
{
HITS_READ* read = ctx->db->reads + i;
int flags = read->flags;
if ( flags & R_CONTAINED_G )
{
contained_g += 1;
containedb_g += DB_READ_LEN( ctx->db, i );
}
if ( flags & ( R_USED_A_G | R_USED_B_G ) )
{
used_g += 1;
}
if ( flags & R_USED_A_G )
{
useda_g += 1;
}
if ( flags & R_USED_B_G )
{
usedb_g += 1;
}
}
if ( used_g != used )
{
printf( "#overall Areads: %d\n", useda_g );
printf( "#overall Breads: %d\n", usedb_g );
printf( "#overall reads: %d\n", used_g );
if ( contained_g > 0 )
{
printf( "#overall contained reads: %d (%.2f%%), contained bases: %" PRIu64 " (%.2f%%), avgLen: %" PRIu64 "\n",
contained_g, 100.0 * contained_g / used_g, containedb_g, 100.0 * containedb_g / ctx->nAllBases, containedb_g / contained_g );
}
if ( ctx->nAllIdentityOverlaps > 0 )
{
printf( "#overall identity overlaps %" PRIu64 " (%.2f%%) from %d reads\n",
ctx->nAllIdentityOverlaps, 100.0 * ctx->nAllIdentityOverlaps / ctx->nAllOverlaps, useda_g );
}
if ( ctx->nAllOverlaps > 0 )
{
printf( "#overall overlaps %" PRIu64 ", n: %" PRIu64 ", (%.2f%%), c: %" PRIu64 " (%.2f%%) avgLen %" PRIu64 "\n",
ctx->nAllOverlaps, nfwd_g, nfwd_g * 100.0 / ctx->nAllOverlaps,
ctx->nAllComplementOverlaps, ctx->nAllComplementOverlaps * 100.0 / ctx->nAllOverlaps, ctx->nAllBases / ctx->nAllOverlaps );
}
}
if ( ctx->dumpOutContainedReads && last )
{
for ( i = 0; i < dbReads; i++ )
{
if ( ctx->db->reads[ i ].flags & R_CONTAINED_G )
printf( "%d\n", i );
}
}
}
}
static int stats_handler( void* _ctx, Overlap* ovls, int novl )
{
StatsContext* ctx = (StatsContext*)_ctx;
int j;
ctx->db->reads[ ovls->aread ].flags |= R_USED_A | R_USED_A_G;
// stitch
if ( ctx->stitch >= 0 )
{
int k;
j = k = 0;
while ( j < novl )
{
while ( k < novl - 1 && ovls[ j ].bread == ovls[ k + 1 ].bread )
k++;
stitch( ctx, ovls + j, k - j + 1, ctx->stitch );
j = k + 1;
}
}
// contained stats
{
int k;
j = k = 0;
while ( j < novl )
{
while ( k < novl - 1 && ovls[ j ].bread == ovls[ k + 1 ].bread )
k++;
contained_stats( ctx, ovls + j, k - j + 1 );
ctx->db->reads[ ovls[ j ].bread ].flags |= R_USED_B | R_USED_B_G;
j = k + 1;
}
}
// overlap length histogram
for ( j = 0; j < novl; j++ )
{
Overlap* ovl = ovls + j;
if ( ovl->flags & OVL_DISCARD )
continue;
int aread, bread;
int rLenA, rLenB;
int tab, tae, tbb, tbe;
int oab, oae, obb, obe;
rLenA = DB_READ_LEN( ctx->db, ovl->aread );
rLenB = DB_READ_LEN( ctx->db, ovl->bread );
aread = ovl->aread;
bread = ovl->bread;
// check both read lengths, apply trim track if available
if ( ctx->tracktrim )
{
get_trim( ctx->db, ctx->tracktrim, aread, &tab, &tae );
get_trim( ctx->db, ctx->tracktrim, bread, &tbb, &tbe );
}
else
{
tab = 0;
tae = rLenA;
tbb = 0;
tbe = rLenB;
}
if(ctx->minRlen > tae - tab || ctx->minRlen > tbe - tbb)
continue;
int l;
// check both overlap lengths, apply trim track if available
if ( ctx->tracktrim )
{
oab = MAX(ovl->path.abpos, tab);
oae = MIN(ovl->path.aepos, tae);
obb = MAX(ovl->path.bbpos, tbb);
obe = MIN(ovl->path.bepos, tbe);
l=MIN(oae - oab, obe - obb);
}
else
{
l=MIN(ovl->path.aepos - ovl->path.abpos, ovl->path.bepos - ovl->path.bbpos);
}
if(ctx->minOlen > l || l == 0)
continue;
assert(l>=0);
int b = l / ctx->ovlBinSize;
if ( b >= ctx->nbin )
b = ctx->nbin - 1;
ctx->hist[ b ] += 1;
ctx->bsum[ b ] += l;
}
return 1;
}
static void usage()
{
fprintf( stderr, "[-vdr] [-bfsol <int>] <db> <overlaps_in> ... | <overlaps.#.las> \n" );
fprintf( stderr, "options: -v ... verbose\n" );
fprintf( stderr, " -f ... containment fuzzing, i.e. #fuzzing bases, that are ignored from begin or end of overlap (default: %d)\n", DEF_ARG_F );
fprintf( stderr, " -s ... stitch (%d)\n", DEF_ARG_S );
fprintf( stderr, " -d ... dump out contained reads\n" );
fprintf( stderr, " -b ... bucket size of histogram length (%d)\n", DEF_ARG_B );
fprintf( stderr, " -t ... trim track (%s)\n", DEF_ARG_T );
fprintf( stderr, " -r ... raw output\n");
fprintf( stderr, " -l ... minimum read length\n");
fprintf( stderr, " -o ... minimum overlap length\n");
}
int main( int argc, char* argv[] )
{
HITS_DB db;
StatsContext sctx;
PassContext* pctx;
FILE* fileOvlIn;
bzero( &sctx, sizeof( StatsContext ) );
sctx.db = &db;
sctx.fuzzing = DEF_ARG_F;
sctx.stitch = DEF_ARG_S;
sctx.dumpOutContainedReads = 0;
sctx.ovlBinSize = DEF_ARG_B;
sctx.raw = 0;
sctx.minOlen = 0;
sctx.minRlen = 0;
// args
int c;
char* trimname = DEF_ARG_T;
opterr = 0;
while ( ( c = getopt( argc, argv, "rvdf:s:t:b:o:l:" ) ) != -1 )
{
switch ( c )
{
case 'r':
sctx.raw = 1;
break;
case 't':
trimname = optarg;
break;
case 'v':
sctx.verbose++;
break;
case 'd':
sctx.dumpOutContainedReads = 1;
break;
case 'f':
sctx.fuzzing = atoi( optarg );
if ( sctx.fuzzing < 0 )
{
fprintf( stderr,
"[ERROR] - LAstats: -f argument must be positive!\n" );
usage();
exit( 1 );
}
break;
case 's':
sctx.stitch = atoi( optarg );
break;
case 'o':
sctx.minOlen = atoi( optarg );
break;
case 'l':
sctx.minRlen = atoi( optarg );
break;
case 'b':
{
sctx.ovlBinSize = atoi(optarg);
if (sctx.ovlBinSize <= 0)
{
fprintf(stderr, "Invalid histogram bucket size of %d\n", sctx.ovlBinSize);
exit(1);
}
}
break;
default:
usage();
exit( 1 );
}
}
if ( argc - optind < 2 )
{
usage();
exit( 1 );
}
char* pcPathReadsIn = argv[ optind++ ];
if ( sctx.verbose )
printf( "Open database: %s\n", pcPathReadsIn );
if ( Open_DB( pcPathReadsIn, &db ) )
{
fprintf( stderr, "could not open %s\n", pcPathReadsIn );
exit( 1 );
}
if ( !( sctx.tracktrim = track_load( &db, trimname ) ) )
{
fprintf( stderr, "could not open %s\n", trimname );
}
char* pcPathOverlapsIn = argv[ optind ];
char* hashPos = strchr( pcPathOverlapsIn, '#' );
int blocks = 1;
char* pathLas = malloc( strlen( pcPathOverlapsIn ) + 100 );
char *prefix, *suffix;
if ( hashPos != NULL )
{
blocks = DB_Blocks( pcPathReadsIn );
prefix = pcPathOverlapsIn;
suffix = hashPos + 1;
*hashPos = '\0';
}
else
{
blocks = argc - optind;
}
int b;
for ( b = 1; b <= blocks; b++ )
{
if ( hashPos != NULL )
{
sprintf( pathLas, "%s%d%s", prefix, b, suffix );
if ( ( fileOvlIn = fopen( pathLas, "r" ) ) == NULL )
{
fprintf( stderr, "could not open %s\n", pathLas );
exit( 1 );
}
if ( sctx.verbose )
printf( ANSI_COLOR_GREEN "PASS stats %s\n" ANSI_COLOR_RESET,
pathLas );
}
else
{
if ( ( fileOvlIn = fopen( argv[ optind ], "r" ) ) == NULL )
{
fprintf( stderr, "could not open %s\n", argv[ optind ] );
exit( 1 );
}
if ( sctx.verbose )
printf( ANSI_COLOR_GREEN "PASS stats %s\n" ANSI_COLOR_RESET,
argv[ optind ] );
optind++;
}
// passes
pctx = pass_init( fileOvlIn, NULL );
pctx->split_b = 0;
pctx->load_trace = 0;
pctx->data = &sctx;
pctx->write_overlaps = 0;
pctx->purge_discarded = 0;
stats_pre( &sctx );
pass( pctx, stats_handler );
int last = 0;
if ( b == blocks )
{
last = 1;
}
stats_post( &sctx, last );
// cleanup
pass_free( pctx );
fclose( fileOvlIn );
}
if ( hashPos != NULL )
{
*hashPos = '#';
}
Close_DB( &db );
free( pathLas );
return 0;
}
|
MartinPippel/DAmar
|
utils/LAcartoons.c
|
<reponame>MartinPippel/DAmar<filename>utils/LAcartoons.c<gh_stars>10-100
/*******************************************************************************************
*
* Prints an ASCII representation of the overlaps. Uses ANSI color codes.
* Best used jointly with 'less -SR'
*
* Date : October 2014
*
* Author : <NAME>
*
*******************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#include <unistd.h>
#include <math.h>
#include <sys/param.h>
#include "lib/colors.h"
#include "lib/oflags.h"
#include "lib/utils.h"
#include "lib/pass.h"
#include "lib/tracks.h"
#include "db/DB.h"
#include "dalign/align.h"
#define OVL_HIDE OVL_TEMP // use the temp flag to hide overlaps
// not matching the criteria
#define SORT_ID 1
#define SORT_AB 2
#define SORT_LENGTH 3
#define SCALE(x, tw) ( (int) ((x)/(float)(tw)) )
#define REVSCALE(x, tw) ( (int) ((x)*(float)(tw)) )
#define REPEAT(c,n) { char strrep[1024]; memset(strrep, c, n); strrep[(n)] = '\0'; printf("%s", strrep); }
typedef struct
{
HITS_DB* db;
HITS_TRACK* qtrack;
ovl_header_twidth twidth;
int q;
int trim;
int ruler;
int discarded;
int coverage;
int show_overlaps;
int flags;
int sort;
int revsort;
float q_scale;
int histo_max;
int64* histo_cov;
int min_len;
float min_identity;
int ranges_in;
int* ranges;
int ranges_npt;
int ranges_idx;
} CartoonsContext;
extern char *optarg;
extern int optind, opterr, optopt;
static int ORDER(const void* l, const void* r)
{
int x = *((int32*) l);
int y = *((int32*) r);
return (x - y);
}
static int cmp_ovls_abpos(const void* a, const void* b)
{
Overlap* o1 = (Overlap*)a;
Overlap* o2 = (Overlap*)b;
int cmp = o1->path.abpos - o2->path.abpos;
if (!cmp)
{
cmp = (o1->path.aepos - o1->path.abpos) - (o2->path.aepos - o2->path.abpos);
}
return cmp;
}
static int cmp_ovls_id(const void* a, const void* b)
{
Overlap* o1 = (Overlap*)a;
Overlap* o2 = (Overlap*)b;
return o1->bread - o2->bread;
}
static int cmp_ovls_length(const void* a, const void* b)
{
Overlap* o1 = (Overlap*)a;
Overlap* o2 = (Overlap*)b;
return (o1->path.aepos - o1->path.abpos) - (o2->path.aepos - o2->path.abpos);
}
static char* match_string(CartoonsContext* cctx, Overlap* ovl, ovl_header_twidth twidth)
{
static char match[64 * 1024];
int i, q;
char* color = "";
char* cur = match;
char* pcolor = NULL;
int width;
char c;
ovl_trace* trace = ovl->path.trace;
int bp = ovl->path.bbpos;
if (ovl->path.tlen == 0)
{
int len = (ovl->path.aepos - ovl->path.abpos) / twidth;
memset(match, '*', len);
match[len] = '\0';
return match;
}
for (i = 0; i < ovl->path.tlen; i += 2)
{
if (i == 0)
{
width = twidth - (ovl->path.abpos % twidth) + trace[i + 1];
bp += trace[i + 1];
}
else if (i == ovl->path.tlen - 1)
{
width = (ovl->path.aepos % twidth) + (ovl->path.bepos - bp);
bp = ovl->path.bepos;
}
else
{
width = twidth + trace[i + 1];
bp += trace[i + 1];
}
q = 200. * trace[i] / width * cctx->q_scale;
if (q < 5)
{
color = ANSI_COLOR_WHITE;
c = '0';
}
else if (q < 10)
{
color = ANSI_COLOR_GREEN;
c = '1';
}
else if (q < 20)
{
color = ""; // ANSI_COLOR_YELLOW;
c = '2';
}
else if (q < 30)
{
color = ANSI_COLOR_YELLOW;
c = '3';
}
else
{
color = ANSI_COLOR_RED;
c = '.';
}
if (pcolor != color)
{
sprintf(cur, "%s", ANSI_COLOR_RESET);
cur += strlen(ANSI_COLOR_RESET);
sprintf(cur, "%s", color);
pcolor = color;
cur += strlen(color);
}
*cur = c;
cur++;
}
sprintf(cur, "%s", ANSI_COLOR_RESET);
cur += strlen(ANSI_COLOR_RESET);
*cur = '\0';
return match;
}
static int round_up(int n, int f)
{
return (n + f - 1) - ((n - 1) % f);
}
static int round_down(int n, int f)
{
return n - n % f;
}
static char* read_string(int len, int a, HITS_TRACK* track_q)
{
static char string[128*1024];
char* cur = string;
char* color = "";
char* pcolor = NULL;
if (track_q != NULL)
{
track_anno* q_anno = track_q->anno;
track_data* q_data = track_q->data;
track_anno aob = q_anno[a] / sizeof(track_data);
track_anno aoe = q_anno[a+1] / sizeof(track_data);
track_anno aoc = 0;
int q;
char c;
assert((track_anno)len == aoe - aob);
for (; aoc < (aoe-aob); aoc++)
{
q = q_data[aob + aoc];
if (q == 0)
{
color = "";
c = '*';
}
else if (q < 5)
{
color = ANSI_COLOR_WHITE;
c = '0';
}
else if (q < 10)
{
color = ANSI_COLOR_GREEN;
c = '1';
}
else if (q < 20)
{
color = ""; // ANSI_COLOR_GREEN;
c = '2';
}
else if (q < 30)
{
color = ANSI_COLOR_YELLOW;
c = '3';
}
else
{
color = ANSI_COLOR_RED;
c = '.';
}
if (pcolor != color)
{
sprintf(cur, "%s", ANSI_COLOR_RESET);
cur += strlen(ANSI_COLOR_RESET);
sprintf(cur, "%s", color);
pcolor = color;
cur += strlen(color);
}
*cur = c;
cur++;
}
*cur = '\0';
}
else
{
int i;
for (i = 0; i < len; i++)
{
string[i] = '*';
}
string[len] = '\0';
}
return string;
}
static char* ruler_string(int len, int twidth)
{
static char str[1024];
char num[10];
int i = 0;
while (i < len)
{
if (i % 10)
{
str[i++] = ' ';
}
else
{
str[i] = '|';
sprintf(num, "%d", (i * twidth) / 1000);
i++;
char* c = num;
while (*c)
{
str[i++] = *c++;
}
}
}
str[i] = '\0';
return str;
}
static void draw(CartoonsContext* ctx, Overlap* pOvls, int novls)
{
HITS_DB* db = ctx->db;
HITS_TRACK* qtrack = ctx->qtrack;
char flags[OVL_FLAGS+1];
ovl_header_twidth twidth = ctx->twidth;
int ovhtrim = ctx->trim;
int ruler = ctx->ruler;
int rev = ctx->revsort;
int coverage = ctx->coverage;
int show_flags = ctx->flags;
int flags_width = show_flags * (OVL_FLAGS + 2);
int nMaxLeftOvh, left;
int i;
int ovlALen = DB_READ_LEN(db, pOvls[0].aread);
int alen = round_up( ovlALen, twidth );
if (ovhtrim)
{
nMaxLeftOvh = REVSCALE(10, twidth);
}
else
{
nMaxLeftOvh = 0;
for (i = 0; i < novls; i++)
{
left = round_down(pOvls[i].path.bbpos, twidth) - round_down(pOvls[i].path.abpos, twidth);
nMaxLeftOvh = MAX(left, nMaxLeftOvh);
}
nMaxLeftOvh += REVSCALE(1, twidth);
}
if (ruler)
{
REPEAT(' ', SCALE(nMaxLeftOvh, twidth) + 25 + flags_width);
printf("%s\n", ruler_string( SCALE(ovlALen, twidth), twidth ));
}
printf(ANSI_COLOR_CYAN "% 10d#[%5d..%5d]", pOvls[0].aread + 1, 0, ovlALen );
REPEAT(' ', SCALE(nMaxLeftOvh, twidth) + flags_width);
printf("%s" ANSI_COLOR_RESET, read_string( SCALE(alen, twidth), pOvls->aread, qtrack ) );
printf("\n");
if (coverage)
{
// UNDECIDED: count partial segments or not
int alen_seg = alen / ctx->twidth;
bzero(ctx->histo_cov, sizeof(int64) * ctx->histo_max);
for (i = 0; i < novls; i++)
{
int j;
int last = pOvls[i].path.aepos / ctx->twidth;
for (j = pOvls[i].path.abpos / ctx->twidth; j <= last; j++)
{
ctx->histo_cov[j]++;
}
}
int cov_max = 0;
for (i = 0; i <= alen_seg; i++)
{
if (ctx->histo_cov[i] == 0)
{
continue;
}
ctx->histo_cov[i] = log10( ctx->histo_cov[i] );
if (ctx->histo_cov[i] > cov_max)
{
cov_max = ctx->histo_cov[i];
}
}
for (i = cov_max; i != 0; i--)
{
REPEAT(' ', SCALE(nMaxLeftOvh, twidth) + 25 + flags_width);
int j;
for (j = 0; j < alen_seg; j++)
{
if (ctx->histo_cov[j] >= i)
{
printf("*");
}
else
{
printf(" ");
}
}
printf(" %5dx\n", (int)pow(10, i));
}
}
if (ctx->show_overlaps)
{
int pre, post, indent, pre_match, incr, end;
char orient;
char* color;
if (rev)
{
incr = -1;
end = -1;
i = novls - 1;
}
else
{
incr = 1;
end = novls;
i = 0;
}
int ovlBLen;
for (; i != end; i += incr)
{
if ( (!ctx->discarded && (pOvls[i].flags & OVL_DISCARD)) || pOvls[i].flags & OVL_HIDE )
{
continue;
}
ovlBLen = DB_READ_LEN(db,pOvls[i].bread);
pre = round_down(pOvls[i].path.bbpos, twidth);
post = round_up(ovlBLen, twidth) - round_up(pOvls[i].path.bepos, twidth);
indent = nMaxLeftOvh + round_down(pOvls[i].path.abpos, twidth) - pre;
orient = pOvls[i].flags & OVL_COMP ? '<' : '>';
if (pOvls[i].flags & OVL_DISCARD)
{
color = ANSI_COLOR_RED;
}
else
{
color = pOvls[i].flags & OVL_COMP ? ANSI_COLOR_BLUE : "";
}
pre_match = SCALE(indent + pre, twidth);
indent = SCALE(indent, twidth);
pre = pre_match - indent;
post = SCALE(post, twidth);
printf("%s%10d%c[%5d..%5d]" ANSI_COLOR_RESET, color, pOvls[i].bread + 1, orient, pOvls[i].path.abpos, pOvls[i].path.aepos);
if (show_flags)
{
flags2str(flags, pOvls[i].flags);
printf("[%s]", flags);
}
if (ovhtrim)
{
indent = SCALE(round_down(pOvls[i].path.abpos, twidth), twidth);
if (pre < 10)
{
REPEAT(' ', 10 - pre + indent);
REPEAT('-', pre);
}
else
{
REPEAT(' ', indent);
printf(" %5d]", pOvls[i].path.bbpos);
REPEAT('-', 3);
}
}
else
{
REPEAT(' ', indent);
REPEAT('-', pre);
}
printf("%s", match_string(ctx, pOvls + i, twidth) );
if (ovhtrim && post > 9)
{
REPEAT('-', 3);
printf("[%d", ovlBLen - pOvls[i].path.bepos);
}
else
{
REPEAT('-', post);
}
printf("\n");
}
}
printf("\n");
}
static int parse_ranges(int argc, char* argv[], int* _reps, int** _pts)
{
int *pts = (int*)malloc(sizeof(int) * 2 * (2 + argc));
int reps = 0;
if (argc > 0)
{
int c, b, e;
char* eptr, *fptr;
for (c = 0; c < argc; c++)
{
if (argv[c][0] == '#')
{
fprintf(stderr, "# is not allowed as range start, '%s'\n", argv[c]);
return 0;
}
else
{
b = strtol(argv[c], &eptr, 10);
if (b < 1)
{
fprintf(stderr, "Non-positive index?, '%d'\n", b);
return 0;
}
}
if (eptr > argv[c])
{
if (*eptr == '\0')
{
pts[reps++] = b;
pts[reps++] = b;
continue;
}
else if (*eptr == '-')
{
if (eptr[1] == '#')
{
e = INT32_MAX;
fptr = eptr + 2;
}
else
{
e = strtol(eptr + 1, &fptr, 10);
}
if (fptr > eptr + 1 && *fptr == 0 && eptr[1] != '-')
{
pts[reps++] = b;
pts[reps++] = e;
if (b > e)
{
fprintf(stderr, "Empty range '%s'\n", argv[c]);
return 0;
}
continue;
}
}
}
fprintf(stderr, "argument '%s' is not an integer range\n", argv[c]);
return 0;
}
qsort(pts, reps / 2, sizeof(int64), ORDER);
b = 0;
for (c = 0; c < reps; c += 2)
{
if (b > 0 && pts[b - 1] >= pts[c] - 1)
{
if (pts[c + 1] > pts[b - 1])
{
pts[b - 1] = pts[c + 1];
}
}
else
{
pts[b++] = pts[c];
pts[b++] = pts[c + 1];
}
}
pts[b++] = INT32_MAX;
reps = b;
}
else
{
pts[reps++] = 1;
pts[reps++] = INT32_MAX;
}
*_reps = reps;
*_pts = pts;
return 1;
}
static void pre_cartoons(PassContext* pctx, CartoonsContext* cctx)
{
cctx->twidth = pctx->twidth;
cctx->ranges_idx = 1;
cctx->ranges_npt = cctx->ranges[0];
cctx->histo_max = (DB_READ_MAXLEN(cctx->db) + pctx->twidth - 1) / pctx->twidth;
cctx->histo_cov = (int64*)malloc(sizeof(int64) * cctx->histo_max);
if (cctx->q)
{
cctx->qtrack = track_load(cctx->db, TRACK_Q);
if (!cctx->qtrack)
{
fprintf(stderr, "could not load track %s\n", TRACK_Q);
exit(1);
}
}
}
static void post_cartoons(CartoonsContext* cctx)
{
free(cctx->histo_cov);
Close_Track(cctx->db, TRACK_Q);
}
static int handler_cartoons(void* _ctx, Overlap* ovls, int novl)
{
CartoonsContext* ctx = (CartoonsContext*)_ctx;
// filter
int i;
int kept = 0;
int len;
if (DB_READ_LEN(ctx->db, ovls->aread) < ctx->min_len)
{
return 1;
}
for (i = 0; i < novl; i++)
{
if (DB_READ_LEN(ctx->db, ovls[i].bread) < ctx->min_len)
{
ovls[i].flags |= OVL_HIDE;
continue;
}
len = ovls[i].path.aepos - ovls[i].path.abpos;
if (100 - (100.0 * ovls[i].path.diffs / len) < ctx->min_identity)
{
ovls[i].flags |= OVL_HIDE;
continue;
}
kept++;
}
if (kept == 0)
{
return 1;
}
int a = ovls->aread + 1;
if (ctx->ranges_in)
{
while (a > ctx->ranges_npt)
{
ctx->ranges_npt = ctx->ranges[ctx->ranges_idx++];
if (a < ctx->ranges_npt)
{
ctx->ranges_in = 0;
break;
}
ctx->ranges_npt = ctx->ranges[ctx->ranges_idx++];
}
}
else
{
if (ctx->ranges_npt == INT32_MAX)
{
return 0;
}
while (a >= ctx->ranges_npt)
{
ctx->ranges_npt = ctx->ranges[ctx->ranges_idx++];
if (a <= ctx->ranges_npt)
{
ctx->ranges_in = 1;
break;
}
ctx->ranges_npt = ctx->ranges[ctx->ranges_idx++];
}
}
if (ctx->ranges_in)
{
switch (ctx->sort)
{
case SORT_ID:
qsort(ovls, novl, sizeof(Overlap), cmp_ovls_id);
break;
case SORT_LENGTH:
qsort(ovls, novl, sizeof(Overlap), cmp_ovls_length);
break;
case SORT_AB:
default:
qsort(ovls, novl, sizeof(Overlap), cmp_ovls_abpos);
break;
}
draw(ctx, ovls, novl);
}
return 1;
}
static void usage()
{
printf("[-rtqdF] [-s <l|i>] [-x <int>] [-i <double>] [-F <double>] <reads:db> <overlaps:ovl> [ <reads:range> ... ]\n");
printf("options: -r ... show ruler\n");
printf(" -t ... trim overhangs\n");
printf(" -q ... show a read quality (requires a quality track)\n");
printf(" -d ... show discarded overlaps\n");
printf(" -c ... show coverage\n");
printf(" -C ... only coverage (hide overlaps)\n");
printf(" -f ... show flags\n");
printf(" -s [li] ... oder by length or read id\n");
printf(" -x <int> ... set minimum read length to <int>\n");
printf(" -i <float> ... set minimum identity to <float>\n");
printf(" -F <float> ... scale quality scores by <float>\n");
};
int main(int argc, char* argv[])
{
HITS_DB db;
FILE* fileOvlIn;
PassContext* pctx;
CartoonsContext cctx;
bzero(&cctx, sizeof(CartoonsContext));
// process arguments
int c;
opterr = 0;
cctx.q_scale = 1.0;
cctx.min_len = 0;
cctx.min_identity = -1;
cctx.show_overlaps = 1;
while ((c = getopt(argc, argv, "cCdqotrx:i:s:F:f")) != -1)
{
switch (c)
{
case 'f':
cctx.flags = 1;
break;
case 'C':
cctx.show_overlaps = 0;
cctx.coverage = 1;
break;
case 'c':
cctx.coverage = 1;
break;
case 'd':
cctx.discarded = 1;
break;
case 'F':
cctx.q_scale = atof(optarg);
break;
case 'q':
cctx.q = 1;
break;
case 't':
cctx.trim = 1;
break;
case 'r':
cctx.ruler = 1;
break;
case 'x':
cctx.min_len = atoi(optarg);
break;
case 's':
if (islower(optarg[0]))
{
cctx.revsort = 1;
}
switch( tolower(optarg[0]) )
{
case 'i': cctx.sort = SORT_ID;
break;
case 'l': cctx.sort = SORT_LENGTH;
break;
case 'a':
default : cctx.sort = SORT_AB;
break;
}
break;
case 'i':
cctx.min_identity = atof(optarg);
break;
default:
usage();
exit(1);
}
}
if (argc - optind < 2)
{
usage();
exit(1);
}
char* pcPathReadsIn = argv[optind++];
char* pcPathOverlaps = argv[optind++];
if ( (fileOvlIn = fopen(pcPathOverlaps, "r")) == NULL )
{
fprintf(stderr, "could not open '%s'\n", pcPathOverlaps);
exit(1);
}
if (Open_DB(pcPathReadsIn, &db))
{
printf("could not open '%s'\n", pcPathReadsIn);
}
int reps;
int* pts = NULL;
parse_ranges(argc - optind, argv + optind, &reps, &pts);
// init
cctx.ranges = pts;
cctx.db = &db;
pctx = pass_init(fileOvlIn, NULL);
pctx->split_b = 0;
pctx->load_trace = 1;
pctx->unpack_trace = 1;
pctx->data = &cctx;
// pass
pre_cartoons(pctx, &cctx);
// Trim_DB(&db);
pass(pctx, handler_cartoons);
post_cartoons(&cctx);
// cleanup
Close_DB(&db);
fclose(fileOvlIn);
return 0;
}
|
MartinPippel/DAmar
|
utils/CTanalyze.h
|
/*
* analyzeContigs.h
*
* Created on: 3 Aug 2017
* Author: pippel
*/
#ifndef UTILS_LAANALYZE_H_
#define UTILS_LAANALYZE_H_
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include "db/DB.h"
#include "dalign/align.h"
// if abs(beg) > abs(end), i.e. overlap is in complement orientation
// if beg < 0 || end < 0, i.e. abs(positions) are not exact, only derived from nearest trace point
typedef struct
{
int patchedID; // fixed read ID that overlaps with a fixed read X that was incorporated in a contig
int beg; // corresponding beg, end positions
int end; // within read ID
int cBeg; // corresponding begin, end positions
int cEnd; // within fixed read X --> is then converted into corresponding contig position
} OvlRead;
typedef struct
{
int type; // see above types, only contigPosBeg and contigPosEnd modified if necessary, (original position are still available ovlReads[0])
// information according to corrected reads
int correctedID;
int correctedContigPosBeg; // absolute coordinates in
int correctedContigPosEnd; // corrected contig
int correctedReadPosBeg; // absolute coordinates in
int correctedReadPosEnd; // corrected contig
// information according to patched reads and patched LAS
int patchedID;
int patchedContigPosBeg; // absolute coordinates in
int patchedContigPosEnd; // uncorrected (patched only) contig
int repeatBases;
// overlap information from final patched-reads overlap graph, that went into touring
int nOutReads;
int nInReads;
int nComReadsWithNextContigRead; // out
float avgCov;
int lowCov; // yes or no, indicates a problem e.g. chimeric read
OvlRead *ovlReads;
int numOvlReads;
int maxOvlReads;
} ContigRead;
typedef struct _ContigFlag2Label ContigFlag2Label;
struct _ContigFlag2Label
{
int mask;
char* label;
char indicator;
};
typedef struct
{
int flag;
int correspID; /// contained in Contig id, || contains read id || has left exit with read id etc. ....
int numCoveredIntervals;
int *coveredIntervals; // begPos, endPos, avgCov --> positions according to the contig where this ContigGraphClassification belongs to
int nJointReads;
} ReadRelation;
typedef struct
{
int duplicRead;
int contigPos1;
int contigPos2;
int type;
int leftProperRead;
int leftProperReadPos1;
int leftProperReadPos2;
int rightProperRead;
int rightProperReadPos1;
int rightProperReadPos2;
} SplitEvent;
typedef struct
{
int flag;
int corContigIdx;
int *abpos;
int *aepos;
int *bbpos;
int *bepos;
int numPos;
} ContigRelation;
typedef struct
{
int contigID1;
int contigID2; // only necessary if a contig bridges 2 other contigs
int flag;
} TourRelation;
// CONTIG RELATION FLAGS
/// TourRelationFlags - based on touring evaluates ends arguments
#define REL_TOUR_IS_SPUR (1 << 0) // contig is spur
#define REL_TOUR_IS_BUBBLE (1 << 1) // contig is bubble
#define REL_TOUR_HAS_SPUR (1 << 2) // contig contains spur(s)
#define REL_TOUR_HAS_BUBBLE (1 << 3) // contig contains bubble(s)
#define REL_TOUR_UNIQUE (1 << 4) // contig has no other tour relationship
#define REL_TOUR_IS_BRIDGE (1 << 5) // contig bridges two other contigs
#define REL_TOUR_HAS_BRIDGE (1 << 6) // contig has another contig that is a bridge contig
/// ContigRelationFlags - based on Contig vs Contig overlaps
#define REL_CONTIG_IS_ALT (1 << 7)
#define REL_CONTIG_IS_REPEAT_ALT (1 << 8)
#define REL_CONTIG_UNIQUE (1 << 9)
#define REL_CONTIG_BRIDGE (1 << 10)
/// ReadRelationFlags - based on Contig vs patched read overlaps
#define REL_READ_IS_ALT (1 << 12)
#define REL_READ_HAS_ALT (1 << 13)
#define REL_READ_BRIDGE (1 << 14)
#define REL_READ_UNIQE (1 << 15) // 32768
// CONTIG CLASSIFICATION FLAGS
#define CLASS_CONTIG_CLASSIFIED (1 << 0)
#define CLASS_CONTIG_PRIMARY (1 << 1)
#define CLASS_CONTIG_ALT (1 << 2)
#define CLASS_CONTIG_DISCARD (1 << 3)
#define CLASS_CONTIG_DISCARD_REPEAT (1 << 4)
#define CLASS_CONTIG_DISCARD_LEN (1 << 5)
#define CLASS_CONTIG_DISCARD_CREADS (1 << 6)
#define CLASS_CONTIG_MODIFIED_FALSEJOIN (1 << 7) // i.e. cut out corresponding Cread and keep classification, blacklist C-read!!!!
#define CLASS_CONTIG_MODIFIED_TRIMLEFT (1 << 8) // i.e. trim position: find trim_ab of corresponding Cread -> left contig part becomes ALT right part PRIM
#define CLASS_CONTIG_MODIFIED_TRIMRIGHT (1 << 9) // i.e. trim position: trim_ae of corresponding Cread -> left contig part stays PRIM right part becomes ALT
/// READ JUNCTION FLAGS // TODO in development
#define CLASS_READ_VALID (1 << 10) // 1024 initially all reads are valid, because they are part of a contig
#define CLASS_READ_CHECKED (1 << 11) // 2048
#define CLASS_READ_DISCARD (1 << 12) // 4096 contig read should be completely cut out from contig
#define CLASS_READ_NEWEND (1 << 13) // 8192 contig ends at current read at position contigPosEnd
#define CLASS_READ_NEWSTART (1 << 14) // 16384 contig starts at current read at position: contigPosBeg
typedef struct
{
int len;
int contigID;
int fileID; // contigs are usually split into connected compounds and stored different files
int pathID; // pathID represents an individual contig ID within a connected compound
int cflag; // contig classification flags
int rflag; // contig relation flags
int repBasesFromContigLAS;
int repBasesFromReadLAS;
int tmp;
} ContigProperties;
typedef struct
{
TourRelation *correspTourRelation;
ContigRelation *correspContigRelation;
ReadRelation *correspReadRelation;
} Classification;
typedef struct
{
ContigProperties property;
ContigRead *cReads;
int numcReads;
float avgCov;
ContigRelation *contigRelations;
int numContigRelations;
int maxContigRelations;
ReadRelation *readRelations;
int numReadRelations;
int maxReadRelations;
TourRelation *tourRelations;
int numTourRelations;
Classification *classif;
} Contig;
typedef struct
{
int numFileNames;
char **fileNames;
char **fastaNames;
int *fromDbIdx;
int *toDbIdx; // inclusive
} FileNamesAndOffsets;
typedef struct
{
// corrected contigs
char *corContigDBName;
char *corContigLASName;
HITS_DB* corContigDB;
HITS_TRACK *corContigPatchReadsAndPos_track;
HITS_TRACK *corContigCorrectReadsAndPos_track;
HITS_TRACK *corContigRawReads_track;
HITS_TRACK *corContigRepeats_track;
// patched reads DB and LAS
char *patchedReadDBName;
char *patchedReadLASName;
HITS_DB* patchedReadDB;
HITS_TRACK *patchedReadSource_track;
HITS_TRACK *patchedReadTrim_track;
HITS_TRACK *patchedReadRepeat_track;
// corrected reads DB
char *corReadDBName;
HITS_DB* corReadDB;
int exp_cov;
// save output files in sub dir
char *outDir;
// output stuff
char *readSeq;
int numContigs;
int **vreadMask; // len: number of reads of fixedDB times number of times a read can occur in different contigs
int maxVReadMask; // number of times the same read can occur in different contigs (should not be greater than 2-3??)
Contig* contigs;
Contig** contigs_sorted;
int twidth; // trace point spacing
int VERBOSE;
int SPUR_LEN;
int TIP_LEN;
int nFuzzBases;
int contByReads_CommonReadFraction; // how many raw reads (in percent) must a contained contig have in common with a primary contig
int contByReads_CoveredLenPerc; // length of a contained contig (in percent) that is covered from a primary contig
int contByContigs_CoveredLenPerc;
int minPrimContigLen;
int minPrimContigReads;
int maxPrimContigRepeatPerc;
FileNamesAndOffsets *contigFileNamesAndOffsets;
FileNamesAndOffsets *rawReadFileNamesAndOffsets;
} AnalyzeContext;
void initAnalyzeContext(AnalyzeContext *actx);
void finalContigValidation(AnalyzeContext *actx);
//void printSplitEvent(Contig *contig, SplitEvent *split);
//void printFinalAltContigClassification(FILE *out, FinalContigAltClass facc);
//void printFinalContigClassification(FILE *out, FinalContigClass fcc);
int getFullReadPositionInContig(AnalyzeContext *actx, Contig* c, int readID, int *cbeg, int *cend);
ContigRead* getContigRead(Contig* contig, int readID);
char* getContigFastaFileName(AnalyzeContext *actx, Contig *contig);
int createOutDir(char *out);
//////// analyze contigs based on fixed-read overlaps and intersection of read ids
int processFixedReadOverlap_handler1(void* _ctx, Overlap* ovls, int novl);
int processFixedReadOverlap_handler2(void* _ctx, Overlap* ovls, int novl);
void getCorrespondingPositionInBRead(AnalyzeContext *actx, Overlap *ovl, int* pos1, int *pos2);
void getCorrespondingPositionInARead(AnalyzeContext *actx, Overlap *ovl, int* pos1, int *pos2);
/// do coverage analysis for contig-read-overlaps, set absolute contig positions
void analyzeContigOverlapGraph(AnalyzeContext *actx);
int cmpOVLreadById(const void *a, const void *b);
void parseDBFileNames(char *dbName, FileNamesAndOffsets *fileNamesAndOffsets);
void classifyContigsByBReadsAndPath(AnalyzeContext *actx);
typedef struct
{
int idx;
int len;
} ContigIDAndLen;
int cmpContigLength(const void *a, const void *b);
int getPathID(AnalyzeContext *actx, int contigID);
int getFileID(FileNamesAndOffsets *fileAndNameOffset, int contigID);
int getNumberOfSubgraphContigs(FileNamesAndOffsets *fileAndNameOffset, int contigID);
void getContigsEndIDs(AnalyzeContext *actx, int contigID, int* beg, int *end);
//////// analyze contigs on their alignments with each other
int processContigOverlap_handler(void* _ctx, Overlap* ovls, int novl);
int compareInt(const void * a, const void * b);
int contained(int ab, int ae, int bb, int be);
void classifyContigsByOverlaps(AnalyzeContext *actx);
/// use all info from classifyContigsByOverlaps and classifyContigsByBReadsAndPath and tracks
/// to make final decision about contig class
void classify(AnalyzeContext *actx);
void createOutput(AnalyzeContext *actx);
void analyzeCoveredBases(AnalyzeContext* actx, Overlap* pOvls, int n);
//char getClassification(FinalContigClass fcc);
//char* getSplitType(SplitEvent* se);
void analyzeJunction(AnalyzeContext* actx, int read, int numContigs);
void createSplitEvent(AnalyzeContext * actx, Contig *contig, int read, int sType);
int checkJunctionCoverage(AnalyzeContext *actx, Contig *contig, int read); // returns true if everything is ok, false otherwise
int getRepeatBasesFromInterval(AnalyzeContext* actx, int contigDB, int readID, int beg, int end);
#endif /* UTILS_LAANALYZE_H_ */
|
MartinPippel/DAmar
|
msa/redriver.c
|
<reponame>MartinPippel/DAmar
/*****************************************************************************************\
* *
* This program improves a multi-alignment of DNA sequences *
* *
* This is the driver that calls library routines to read, realign, and write a series *
* of contigs in vertical format *
* *
* Author: <NAME> *
* Date : March 2007 *
* *
\*****************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>
#include "realigner.h"
#undef DEBUG
#define OPT_B_DEFAULT 8
#define OPT_R_DEFAULT 0
#define OPT_C_DEFAULT 0
extern char *optarg;
extern int optind, opterr, optopt;
static void usage()
{
printf("[-b <int>] [-r] [-c]\n");
printf("options: -b ... band width (%d)\n", OPT_B_DEFAULT);
printf(" -r ... same rows (%d)\n", OPT_R_DEFAULT);
printf(" -c ... comments (%d)\n", OPT_C_DEFAULT);
}
int main(int argc, char *argv[])
{
int bandwidth = OPT_B_DEFAULT;
int samerows = OPT_R_DEFAULT;
int comments = OPT_C_DEFAULT;
int c;
opterr = 0;
while ((c = getopt(argc, argv, "crb:")) != -1)
{
switch (c)
{
case 'c':
comments = 1;
break;
case 'b':
bandwidth = atoi(optarg);
break;
case 'r':
samerows = 1;
break;
default:
usage();
exit(1);
}
}
/* Read in each contig, realign, print, and free */
while (1)
{ Re_Contig *ctg;
if (comments)
ctg = Re_Read_Contig(stdin,stdout);
else
ctg = Re_Read_Contig(stdin,NULL);
if (ctg == NULL) break;
#ifdef DEBUG
Re_Print_Structure(ctg,stdout);
#endif
Re_Align_Contig(ctg,bandwidth);
#ifdef DEBUG
Re_Print_Structure(ctg,stdout);
#endif
Re_Print_Contig(ctg,stdout,samerows);
Re_Free_Contig(ctg);
}
}
|
MartinPippel/DAmar
|
corrector/LAcorrect.c
|
/*******************************************************************************************
*
* Consensus based read correction
*
* Date : revisited April 2017
*
* Author : <NAME>
*
*******************************************************************************************/
#include <assert.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <unistd.h>
#include "consensus.h"
#include "lib/colors.h"
#include "lib/oflags.h"
#include "lib/pass.h"
#include "lib/tracks.h"
#include "lib/utils.h"
#include "dalign/align.h"
#include "db/DB.h"
// settings
#define MIN_TWIDTH 20
#define MAX_COVERAGE 20
#define MAX_TILES 40
#undef ADJUST_OFFSETS // use mid-points to adjust pass through points
#undef FIX_BOUNDARY_ERRORS // perform multi-tile alignment around segment boundary
#define USE_A_TILES // add the A tile to the tile-pile
#define TRACK_POSITIONS
#ifdef FIX_BOUNDARY_ERRORS
#define CE_CENTER_DISTANCE 0.4 // consensus error fixing, max fraction of twidth from tile boundary
#endif
// read flags
#define READ_CORRECT 1
#define READ_CORRECTED 2
// defaults
#define DEF_ARG_Q TRACK_Q
#define DEF_ARG_B -1
// development only
#undef DEBUG
#undef DEBUG_FIX_CONSENSUS
#undef DEBUG_MULTI
#undef DEBUG_OFFSETS
#ifdef DEBUG_MULTI
#include "msa/msa.h"
#endif
// parameters for each correction thread
typedef struct
{
int verbose;
int thread; // thread number
int twidth; // spacing between the alignment trace points
off_t start; // start offset in the overlap file
off_t end; // end offset in the overlap
FILE* fileOvls; // overlaps
FILE* fileOut; // output file
HITS_DB db; // database
HITS_TRACK* qtrack; // quality track
char* fastaHeader;
} corrector_arg;
// relative to the A read the overlaps are decomposed into so called tiles.
// where each tile represents the interval between two alignment trace points
typedef struct
{
int a;
int b; // read id the tile comes from
int read; // index of the sequence
int bbpos, bepos; // b relative interval of the tile
int qv; // tile's quality value
int apos; // 0 ... if the tile covers twidth bases in A
// <0 ... position in a * -1, if the tile ends before a trace point in A
// >0 ... position in a, if the tile starts after a trace point in A
} tile_overlap;
// each thread maintains its state using a corrector_context struct
typedef struct
{
consensus* cons; // consensus state
#ifdef DEBUG_MULTI
msa* malign; // multi-align state
int malign_indent; // multi-align indentation (display only)
#endif
int verbose;
int thread; // thread #
int twidth; // spacing of trace points
int ntoff;
int* toff;
int ntovl;
tile_overlap* tovl;
int maxreads;
int nreads;
char** reads;
FILE* fileOut;
HITS_DB* db;
char* seqcons;
int maxcons;
int curcons;
int* tiles;
int curtiles;
int ncorrected;
track_anno* qtrack_offset; // quality track offsets
track_data* qtrack_data; // quality track data
// read a -> qtrack_data[ qtrack_offset[a] .. qtrack_offset[a+1]-1 ]
int* mtc_data;
int mtc_dmax;
int** mtc_dsort;
int stats_tiles_single;
int stats_tiles_multi;
Work_Data* align_work_data; // alignment work data
// base pair position tracking
int* track;
// single/multi-tile alignment and boundary artefact elimination
int ce_smax;
char* ce_seq_singles;
int ce_first_tile;
int* ce_tiles;
int ce_tcur;
char* fastaHeader; // keeps pointer to base_out
} corrector_context;
// needed for getopt
extern char* optarg;
extern int optind, opterr, optopt;
static int has_valid_pt_points( Overlap* ovl )
{
int bb, be, t;
unsigned short* trace = ovl->path.trace;
be = ovl->path.bbpos + trace[ 1 ];
for ( t = 2; t < ovl->path.tlen; t += 2 )
{
bb = be;
if ( t == ovl->path.tlen - 1 )
{
be = ovl->path.bepos + 1;
}
else
{
be += trace[ t + 1 ];
}
if ( bb > be ||
bb < ovl->path.bbpos || bb > ovl->path.bepos ||
be < ovl->path.bbpos || be > ovl->path.bepos + 1 )
{
return 0;
}
}
return 1;
}
static off_t* partition_overlaps( FILE* fileOvls, int parts )
{
Overlap ovl;
ovl_header_novl novl;
ovl_header_twidth twidth;
off_t* offsets = calloc( parts + 1, sizeof( off_t ) );
ovl_header_read( fileOvls, &novl, &twidth );
if ( parts == 1 )
{
offsets[ 0 ] = ftello( fileOvls );
}
else
{
int64 ovls_chunk = novl / parts;
off_t offprev = ftello( fileOvls );
int aprev, chunk;
aprev = chunk = 0;
int64 novl = 0;
while ( !Read_Overlap( fileOvls, &ovl ) )
{
if ( ovl.aread != aprev )
{
offprev = ftello( fileOvls ) - OVERLAP_IO_SIZE;
aprev = ovl.aread;
}
fseek( fileOvls, TBYTES( twidth ) * ovl.path.tlen, SEEK_CUR );
if ( ( novl % ovls_chunk ) == 0 )
{
offsets[ chunk++ ] = offprev;
}
novl++;
}
}
struct stat info;
fstat( fileno( fileOvls ), &info );
offsets[ parts ] = info.st_size;
return offsets;
}
static int cmp_tovl_qv( const void* a, const void* b )
{
tile_overlap* tovl1 = (tile_overlap*)a;
tile_overlap* tovl2 = (tile_overlap*)b;
return tovl1->qv - tovl2->qv;
}
#ifdef DEBUG
static void print_tiles( corrector_context* cctx, int tile )
{
int j;
printf( "TILE %3d %5d..%5d\n", tile, cctx->toff[ tile ], cctx->toff[ tile + 1 ] );
for ( j = cctx->toff[ tile ]; j < cctx->toff[ tile + 1 ]; j++ )
{
printf( "(" ANSI_COLOR_BLUE "%8d %8d" ANSI_COLOR_RESET " %5d..%5d %3d %3d %6d) ",
cctx->tovl[ j ].a,
cctx->tovl[ j ].b,
cctx->tovl[ j ].bbpos, cctx->tovl[ j ].bepos,
cctx->tovl[ j ].bepos - cctx->tovl[ j ].bbpos,
cctx->tovl[ j ].qv, cctx->tovl[ j ].apos );
if ( j != cctx->toff[ tile + 1 ] - 1 && ( j - cctx->toff[ tile ] + 1 ) % 5 == 0 )
printf( "\n" );
}
printf( "\n" );
}
#endif
static char* single_tile_consensus( corrector_context* cctx, int t, int* tiles_used )
{
cctx->stats_tiles_single++;
consensus_reset( cctx->cons );
#ifdef DEBUG_MULTI
msa_reset( cctx->malign );
#endif
int j;
for ( j = cctx->toff[ t ]; j < cctx->toff[ t + 1 ]; j++ )
{
int bb = cctx->tovl[ j ].bbpos;
int be = cctx->tovl[ j ].bepos;
if ( bb > be )
{
printf( "T%d bb > be %d %d ... a %d b %d\n", cctx->thread, bb, be, cctx->tovl[ j ].a, cctx->tovl[ j ].b );
fflush( stdout );
}
assert( bb <= be );
if ( cctx->tovl[ j ].apos == 0 && ( be - bb ) >= MIN_TWIDTH )
{
consensus_add( cctx->cons, cctx->reads[ cctx->tovl[ j ].read ], bb, be );
#ifdef DEBUG_MULTI
msa_add( cctx->malign, cctx->reads[ cctx->tovl[ j ].read ],
-1, -1, // 0, cctx->malign->alen,
bb, be, NULL, 0 );
#endif
if ( cctx->cons->added >= MAX_COVERAGE )
{
break;
}
}
}
#ifdef DEBUG_MULTI
msa_print( cctx->malign, stdout );
cctx->malign_indent += cctx->malign->added + 1;
printf( " %s\n", consensus_sequence( cctx->cons, 1 ) );
#endif
*tiles_used = consensus_added( cctx->cons );
return consensus_sequence( cctx->cons, 0 );
}
#ifdef FIX_BOUNDARY_ERRORS
static int cmp_mtc_data( const void* x, const void* y )
{
int** a = (int**)x;
int** b = (int**)y;
return ( *a )[ 4 ] - ( *b )[ 4 ];
}
static char* multi_tile_consensus( corrector_context* cctx, Overlap* ovls, int novls, int tb, int te )
{
cctx->stats_tiles_multi++;
int re_ab = tb * cctx->twidth;
int len = DB_READ_LEN( cctx->db, ovls->aread );
int re_ae = MIN( len, ( te + 1 ) * cctx->twidth );
#ifdef DEBUG
printf( "multi_tile_consensus tb %3d te %3d re_ab %5d re_ae %5d\n", tb, te, re_ab, re_ae );
#endif
int i, j, ovl, ab, ae;
int doff = 5; // ab, ae, bb, be, q
if ( novls >= cctx->mtc_dmax )
{
cctx->mtc_data = realloc( cctx->mtc_data, sizeof( int ) * novls * doff );
cctx->mtc_dsort = realloc( cctx->mtc_dsort, sizeof( int* ) * novls );
}
int* data = cctx->mtc_data;
int** sort = cctx->mtc_dsort;
bzero( data, sizeof( int ) * doff * novls );
for ( i = 0; i < novls; i++ )
{
sort[ i ] = data + i * doff;
}
// collect intervals that need to be aligned
for ( i = tb; i <= te; i++ )
{
ab = i * cctx->twidth;
ae = ( i + 1 ) * cctx->twidth;
if ( ae > re_ae )
{
ae = re_ae;
}
for ( j = cctx->toff[ i ]; j < cctx->toff[ i + 1 ]; j++ )
{
ovl = cctx->tovl[ j ].ovl;
if ( ovl == -1 )
{
continue;
}
data[ ovl * doff + 4 ] += cctx->tovl[ j ].qv;
if ( data[ ovl * doff + 1 ] == 0 )
{
data[ ovl * doff + 0 ] = ab;
data[ ovl * doff + 2 ] = cctx->tovl[ j ].bbpos;
}
data[ ovl * doff + 1 ] = ae;
data[ ovl * doff + 3 ] = cctx->tovl[ j ].bepos;
if ( cctx->tovl[ j ].apos < 0 )
{
data[ ovl * doff + 1 ] = -cctx->tovl[ j ].apos;
}
else if ( cctx->tovl[ j ].apos > 0 )
{
data[ ovl * doff + 0 ] = cctx->tovl[ j ].apos;
}
}
}
qsort( sort, novls, sizeof( int* ), cmp_mtc_data );
consensus_reset( cctx->cons );
#ifdef DEBUG_MULTI
msa_reset( cctx->malign );
#endif
int bb, be;
for ( i = 0; i < novls; i++ )
{
ovl = ( sort[ i ] - data ) / doff;
ab = sort[ i ][ 0 ];
ae = sort[ i ][ 1 ];
bb = sort[ i ][ 2 ];
be = sort[ i ][ 3 ];
// need to span the region fully
if ( ae == 0 || ae != re_ae || ab != re_ab )
{
continue;
}
consensus_add( cctx->cons, cctx->reads[ ovl + 1 ], bb, be );
#ifdef DEBUG_MULTI
msa_add( cctx->malign, cctx->reads[ ovl + 1 ], -1, -1, bb, be, NULL, 0 );
#endif
if ( cctx->cons->added == MAX_COVERAGE )
{
break;
}
}
if ( cctx->cons->added == 0 )
{
return NULL;
}
#ifdef DEBUG_MULTI
msa_print( cctx->malign, stdout, 0 );
// msa_print_v(cctx->malign, stdout, cctx->malign_indent);
cctx->malign_indent += cctx->malign->added + 1;
#endif
return consensus_sequence( cctx->cons, 0 );
}
#endif // FIX_BOUNDARY_ERRORS
static int load_read( corrector_context* cctx, int rid, int comp )
{
if ( cctx->nreads == cctx->maxreads )
{
int maxreads = cctx->maxreads * 1.2 + 100;
cctx->reads = realloc( cctx->reads, sizeof( char* ) * maxreads );
for ( ; cctx->maxreads < maxreads; cctx->maxreads++ )
{
cctx->reads[ cctx->maxreads ] = New_Read_Buffer( cctx->db );
}
}
Load_Read( cctx->db, rid, cctx->reads[ cctx->nreads ], 0 );
if ( comp )
{
Complement_Seq( cctx->reads[ cctx->nreads ], DB_READ_LEN( cctx->db, rid ) );
}
cctx->nreads++;
return cctx->nreads - 1;
}
#ifdef ADJUST_OFFSETS
static int round_down( int n, int f )
{
return n - ( n % f );
}
static int round_up( int n, int f )
{
return ( n + f - 1 ) - ( ( n - 1 ) % f );
}
static void adjust_offsets( corrector_context* cctx, Overlap** ovls, int novl )
{
Alignment aln;
Path path;
int twidth = cctx->twidth;
aln.path = &path;
aln.aseq = cctx->reads[ 0 ];
aln.alen = DB_READ_LEN( cctx->db, ovls[ 0 ]->aread );
int ntmax = 1000;
int* ntrace = malloc( sizeof( int ) * ntmax );
int ntlen;
int i;
for ( i = 0; i < novl; i++ )
{
Overlap* ovl = ovls[ i ];
#ifdef DEBUG_OFFSETS
printf( "OVL %5d x %5d @ %5d..%5d x %5d..%5d\n",
ovl->alen, ovl->blen,
ovl->path.abpos, ovl->path.aepos,
ovl->path.bbpos, ovl->path.bepos );
#endif
aln.bseq = cctx->reads[ i + 1 ];
aln.blen = DB_READ_LEN( cctx->db, ovl->aread );
path = ovl->path;
Compute_Trace_MID( &aln, cctx->align_work_data, twidth, GREEDIEST );
{
int a = ovl->path.abpos;
int b = ovl->path.bbpos;
int p, t;
int diffs = 0;
int matches = 0;
int ntcur = 0;
ntlen = ( round_down( ovl->path.aepos - 1, twidth ) - round_up( ovl->path.abpos + 1, twidth ) + twidth ) / twidth * 2 + 2;
if ( ntlen > ntmax )
{
ntmax = 1.2 * ntmax + ntlen;
ntrace = malloc( sizeof( int ) * ntmax );
}
int bprev = aln.path->bbpos;
for ( t = 0; t < aln.path->tlen; t++ )
{
if ( ( p = ( (int*)( aln.path->trace ) )[ t ] ) < 0 )
{
p = -p - 1;
while ( a < p )
{
if ( aln.aseq[ a ] != aln.bseq[ b ] )
diffs++;
else
matches++;
a += 1;
b += 1;
if ( a % twidth == 0 )
{
ntrace[ ntcur++ ] = diffs;
ntrace[ ntcur++ ] = b - bprev;
bprev = b;
diffs = matches = 0;
}
}
diffs++;
b += 1;
}
else
{
p--;
while ( b < p )
{
if ( aln.aseq[ a ] != aln.bseq[ b ] )
diffs++;
else
matches++;
a += 1;
b += 1;
if ( a % twidth == 0 )
{
ntrace[ ntcur++ ] = diffs;
ntrace[ ntcur++ ] = b - bprev;
bprev = b;
diffs = matches = 0;
}
}
diffs++;
a += 1;
if ( a % twidth == 0 )
{
ntrace[ ntcur++ ] = diffs;
ntrace[ ntcur++ ] = b - bprev;
bprev = b;
diffs = matches = 0;
}
}
}
p = aln.path->aepos;
while ( a < p )
{
if ( aln.aseq[ a ] != aln.bseq[ b ] )
diffs++;
else
matches++;
a += 1;
b += 1;
if ( a % twidth == 0 && a != ovl->path.aepos )
{
ntrace[ ntcur++ ] = diffs;
ntrace[ ntcur++ ] = b - bprev;
bprev = b;
diffs = matches = 0;
}
}
ntrace[ ntcur++ ] = diffs;
ntrace[ ntcur++ ] = b - bprev;
#ifdef DEBUG_OFFSETS
if ( ntcur != ntlen )
{
a = round_up( ovl->path.abpos + 1, twidth );
b = ovl->path.bbpos;
printf( "ntcur %d != ntlen %d\n", ntcur, ntlen );
printf( "%d..%d x %d..%d -> %d pts\n",
ovl->path.abpos, ovl->path.aepos,
ovl->path.bbpos, ovl->path.bepos, ntlen );
printf( "npts " );
for ( t = 0; t < ntcur - 1; t += 2 )
{
b += ntrace[ t + 1 ];
printf( " %d@%d/%dx%d", ntrace[ t ], ntrace[ t + 1 ], a, b );
a += twidth;
}
printf( " %d@end", ntrace[ ntcur - 1 ] );
printf( "\n" );
}
#endif
}
int j;
#ifdef DEBUG_OFFSETS
printf( "(%3d)", ovl->path.tlen );
for ( j = 1; j < ovl->path.tlen; j += 2 )
{
if ( j > ntlen || j > ovl->path.tlen || ( (uint16*)( ovl->path.trace ) )[ j ] != ntrace[ j ] )
{
printf( ANSI_COLOR_RED " %3d" ANSI_COLOR_RESET, ( (uint16*)( ovl->path.trace ) )[ j ] );
}
else
{
printf( " %3d", ( (uint16*)( ovl->path.trace ) )[ j ] );
}
}
printf( "\n" );
printf( "(%3d)", ntlen );
for ( j = 1; j < ntlen; j += 2 )
{
printf( " %3d", ntrace[ j ] );
}
printf( "\n\n" );
#endif
assert( ovl->path.tlen == ntlen );
for ( j = 0; j < ntlen; j++ )
{
( (uint16*)ovl->path.trace )[ j ] = ntrace[ j ];
}
}
}
#endif
static void write_seq( FILE* file, char* seq )
{
const int width = 100;
int len = strlen( seq );
int j;
for ( j = 0; j + width < len; j += width )
{
fprintf( file, "%.*s\n", width, seq + j );
}
if ( j < len )
{
fprintf( file, "%s\n", seq + j );
}
}
static char* append_consensus( corrector_context* cctx, char* seqcons, int tiles_used )
{
int ncons = strlen( seqcons );
if ( ncons + cctx->curcons >= cctx->maxcons )
{
cctx->maxcons = cctx->maxcons * 1.2 + ncons + 100;
cctx->seqcons = realloc( cctx->seqcons, cctx->maxcons );
}
cctx->tiles[ cctx->curtiles + 0 ] = ncons;
cctx->tiles[ cctx->curtiles + 1 ] = tiles_used;
cctx->curtiles += 2;
char* start = cctx->seqcons + cctx->curcons;
strcpy( start, seqcons );
cctx->curcons += ncons;
return start;
}
#ifdef FIX_BOUNDARY_ERRORS
static char* fix_boundary_errors( corrector_context* cctx, Overlap* ovl, int novl )
{
static char n2a[] = {'a', 'c', 'g', 't'};
Alignment aln;
Path path;
aln.path = &path;
int i, t, slen;
int last_tile = cctx->ce_first_tile + cctx->ce_tcur - 2;
char* seq_multi;
int boundary;
int boundary_b, boundary_e;
int tmax = 0;
int tcur = 0;
int* trace = NULL;
int diffs_a = 0;
int diffs_b = 0;
for ( i = 0, t = cctx->ce_first_tile; t < last_tile; t++, i++ )
{
seq_multi = multi_tile_consensus( cctx, ovl, novl, t, t + 1 );
#ifdef DEBUG_FIX_CONSENSUS
printf( "\n\nTILE %d OFF %d", t, cctx->ce_tiles[ i ] );
#endif
if ( seq_multi == NULL )
{
#ifdef DEBUG_FIX_CONSENSUS
printf( " -> no multi\n" );
#endif
continue;
}
slen = cctx->ce_tiles[ i + 2 ] - cctx->ce_tiles[ i ];
boundary = cctx->ce_tiles[ i + 1 ] - cctx->ce_tiles[ i ];
boundary_b = (int)( boundary * ( 1. - CE_CENTER_DISTANCE ) );
boundary_e = (int)( boundary * ( 1. + CE_CENTER_DISTANCE ) );
if ( slen >= cctx->ce_smax )
{
cctx->ce_smax = slen * 1.2;
cctx->ce_seq_singles = realloc( cctx->ce_seq_singles, sizeof( char ) * cctx->ce_smax );
}
strncpy( cctx->ce_seq_singles, cctx->seqcons + cctx->ce_tiles[ i ], slen );
cctx->ce_seq_singles[ slen ] = '\0';
aln.aseq = cctx->ce_seq_singles;
aln.alen = slen;
aln.bseq = seq_multi;
aln.blen = strlen( seq_multi );
if ( aln.alen == aln.blen )
{
#ifdef DEBUG_FIX_CONSENSUS
printf( " -> alen = blen\n" );
#endif
continue;
}
#ifdef DEBUG_FIX_CONSENSUS
printf( "\n%3d %s\n%3d %s\n", aln.alen, aln.aseq, aln.blen, aln.bseq );
#endif
Number_Read( aln.aseq );
Number_Read( aln.bseq );
path.tlen = 0;
path.trace = NULL;
path.abpos = 0;
path.aepos = aln.alen;
path.bbpos = 0;
path.bepos = aln.blen;
path.diffs = aln.alen + aln.blen;
Compute_Trace_ALL( &aln, cctx->align_work_data );
int j;
#ifdef DEBUG_FIX_CONSENSUS
printf( "%d / boundary %d %d..%d\n", path.diffs, boundary, boundary_b, boundary_e );
Print_Reference( stdout, &aln, cctx->align_work_data, 0, 100, 0, 0, 5 );
printf( "\n" );
printf( "trace" );
for ( j = 0; j < path.tlen; j++ )
{
int tp = ( (int*)path.trace )[ j ];
if ( abs( tp ) > boundary * ( 1 - CE_CENTER_DISTANCE ) &&
abs( tp ) < boundary * ( 1 + CE_CENTER_DISTANCE ) )
{
printf( ANSI_COLOR_GREEN " %d" ANSI_COLOR_RESET, tp );
}
else
{
printf( " %d", tp );
}
}
printf( "\n" );
#endif
if ( 2 * path.tlen + tcur > tmax )
{
tmax = tmax * 1.2 + path.tlen * 2;
trace = realloc( trace, sizeof( int ) * tmax );
}
int a = 0;
int b = 0;
for ( j = 0; j < path.tlen; j++ )
{
int c = ( (int*)path.trace )[ j ];
if ( c < 0 )
{
c = -c - 1;
while ( a < c )
{
a++;
b++;
}
if ( c >= boundary_b && c <= boundary_e )
{
trace[ tcur++ ] = -cctx->ce_tiles[ i ] - ( c + 1 );
trace[ tcur++ ] = aln.bseq[ b ];
diffs_a++;
}
b++;
}
else
{
c = c - 1;
while ( b < c )
{
a++;
b++;
}
if ( c >= boundary_b && c <= boundary_e )
{
trace[ tcur++ ] = a + 2 + cctx->ce_tiles[ i ];
trace[ tcur++ ] = -1;
diffs_b++;
}
a++;
}
}
#ifdef DEBUG_FIX_CONSENSENSUS
printf( "trace" );
for ( j = 0; j < tcur; j += 2 )
{
printf( " (%d %d)", trace[ j ], trace[ j + 1 ] );
}
printf( "\n\n" );
#endif
}
if ( diffs_a + cctx->curcons >= cctx->maxcons )
{
cctx->maxcons = cctx->maxcons * 1.2 + diffs_a + 100;
cctx->seqcons = realloc( cctx->seqcons, cctx->maxcons );
}
int n = cctx->curcons - 1 + diffs_a;
int p = cctx->curcons - 1;
#ifdef DEBUG_FIX_CONSENSUS
write_seq( stdout, cctx->seqcons );
printf( "diffs_a = %d ... diffs_b = %d\n", diffs_a, diffs_b );
#endif
for ( i = tcur - 2; i >= 0; i -= 2 )
{
int c = trace[ i ];
if ( c > 0 )
{
c--;
while ( c <= p )
{
cctx->seqcons[ n ] = cctx->seqcons[ p ];
n--;
p--;
}
/*
cctx->seqcons[n] = '-';
n--;
*/
p--;
}
else
{
c = -c;
c--;
while ( c <= p )
{
cctx->seqcons[ n ] = cctx->seqcons[ p ];
n--;
p--;
}
cctx->seqcons[ n ] = n2a[ trace[ i + 1 ] ]; // '+';
n--;
}
}
while ( p >= 0 )
{
cctx->seqcons[ n ] = cctx->seqcons[ p ];
n--;
p--;
}
n++;
cctx->curcons += diffs_a;
cctx->seqcons[ cctx->curcons ] = '\0';
#ifdef DEBUG_FIX_CONSENSUS
write_seq( stdout, cctx->seqcons + n );
#endif
free( trace );
return cctx->seqcons + n;
}
#endif // FIX_BOUNDARY_ERRORS
static int break_read( corrector_context* cctx, int aread )
{
if ( cctx->curcons == 0 )
{
return 0;
}
// validate consensus using multi-tile alignments
#ifdef DEBUG_FIX_CONSENSUS
fprintf( cctx->fileOut, ">%d.%d source=%d\n", aread, cctx->ncorrected, aread );
write_seq( cctx->fileOut, cctx->seqcons );
#endif
char* seq;
#ifdef FIX_BOUNDARY_ERRORS
seq = fix_boundary_errors( cctx, ovl, novl );
#else
seq = cctx->seqcons;
#endif
#ifdef DEBUG_MULTI
cctx->malign_indent = 0;
#endif
int ab = cctx->ce_first_tile * cctx->twidth;
int alen = cctx->db->reads[ aread ].rlen;
int ae = MIN( alen, ( cctx->ce_first_tile + cctx->ce_tcur - 1 ) * cctx->twidth );
fprintf( cctx->fileOut, ">%d.%d source=%d,%d,%d correctionq=", aread, cctx->ncorrected, aread, ab, ae );
int i;
for ( i = 0; i < cctx->curtiles; i += 2 )
{
if ( i > 0 )
fprintf( cctx->fileOut, "," );
fprintf( cctx->fileOut, "%d,%d", cctx->tiles[ i ], cctx->tiles[ i + 1 ] );
}
#ifdef TRACK_POSITIONS
Alignment aln;
Path path;
aln.path = &path;
aln.aseq = cctx->reads[ 0 ];
aln.alen = DB_READ_LEN( cctx->db, aread );
aln.bseq = seq;
aln.blen = strlen( aln.bseq );
Number_Read( aln.bseq );
path.tlen = 0;
path.trace = NULL;
path.abpos = 0;
path.aepos = aln.alen;
path.bbpos = 0;
path.bepos = aln.blen;
//path.diffs = aln.alen + aln.blen;
if(Compute_Alignment(&aln,cctx->align_work_data,DIFF_ALIGN,cctx->twidth))
printf("Compute_Alignment failed\n");
if ( path.tlen > 0 )
{
fprintf( cctx->fileOut, " postrace=" );
for ( i = 0; i < path.tlen; i++ )
{
if ( i > 0 )
{
fprintf( cctx->fileOut, "," );
}
fprintf( cctx->fileOut, "%d", ( (int*)( path.trace ) )[ i ] );
}
}
Lower_Read( aln.bseq );
#endif
fprintf( cctx->fileOut, "\n" );
write_seq( cctx->fileOut, seq );
cctx->ncorrected++;
cctx->seqcons[ 0 ] = '\0';
cctx->curcons = 0;
cctx->curtiles = 0;
cctx->ce_tcur = 0;
return 1;
}
static int cmp_povl_length( const void* a, const void* b )
{
Overlap* x = *(Overlap**)a;
Overlap* y = *(Overlap**)b;
int len_x = x->path.aepos - x->path.abpos;
int len_y = y->path.aepos - y->path.abpos;
return len_y - len_x;
}
static void correct_overlaps( corrector_context* cctx, Overlap** ovls, int nOvls )
{
int a = ovls[ 0 ]->aread;
if ( ! ( cctx->db->reads[a].flags & READ_CORRECT ) )
{
return ;
}
if ( cctx->verbose )
{
// printf( "READ %8d (%5d) CONSENSUS [ SINGLE %5d MULTI %5d ]\n", a, cctx->db->reads[ a ].rlen, cctx->stats_tiles_single, cctx->stats_tiles_multi );
printf( "T%d READ %8d (%5d)\n", cctx->thread, a, cctx->db->reads[ a ].rlen);
}
// verify that the PT points are valid
int i;
for ( i = 0; i < nOvls; i++ )
{
if ( !has_valid_pt_points( ovls[ i ] ) )
{
printf( "ERROR: bad pt points ovl %d aread %d bread %d\n", i, ovls[ i ]->aread, ovls[ i ]->bread );
return;
}
}
// init pos tracking
int alen = DB_READ_LEN( cctx->db, a );
// alloc & init
int ntiles = ( alen + cctx->twidth - 1 ) / cctx->twidth;
if ( ntiles + 1 >= cctx->ntoff )
{
cctx->ntoff = cctx->ntoff * 1.2 + ntiles + 1;
cctx->toff = realloc( cctx->toff, sizeof( int ) * cctx->ntoff );
}
bzero( cctx->toff, sizeof( int ) * cctx->ntoff );
int t;
for ( i = 0; i < nOvls; i++ )
{
// int tb = round_down( ovls[ i ]->path.abpos, cctx->twidth ) / cctx->twidth;
// int te = round_down( ovls[ i ]->path.aepos - 1, cctx->twidth ) / cctx->twidth;
int tb = ovls[ i ]->path.abpos / cctx->twidth;
int te = tb + ovls[ i ]->path.tlen / 2 - 1;
for ( t = tb; t <= te; t++ )
{
if ( cctx->toff[ t + 1 ] < MAX_TILES )
{
cctx->toff[ t + 1 ]++;
}
}
}
#ifdef USE_A_TILES
for ( i = 0; i < ntiles; i++ )
{
if ( cctx->toff[ i + 1 ] < MAX_TILES )
{
cctx->toff[ i + 1 ]++;
}
}
#endif
for ( i = 1; i <= ntiles; i++ )
{
cctx->toff[ i ] += cctx->toff[ i - 1 ];
}
if ( cctx->toff[ ntiles ] >= cctx->ntovl )
{
cctx->ntovl = cctx->ntovl * 1.2 + cctx->toff[ ntiles ] + 1;
cctx->tovl = realloc( cctx->tovl, sizeof( tile_overlap ) * cctx->ntovl );
}
// fill in tiles
int bb, be, tile;
unsigned short* trace;
int p = 0;
int* curtiles = calloc( ntiles, sizeof( int ) );
// A tiles
#ifdef USE_A_TILES
track_anno oqa = cctx->qtrack_offset[ a ] / sizeof( track_data );
int readidx = load_read( cctx, a, 0 );
for ( i = 0; i < ntiles; i++ )
{
p = cctx->toff[ i ] + curtiles[ i ];
curtiles[ i ] += 1;
cctx->tovl[ p ].read = readidx;
cctx->tovl[ p ].a = a;
cctx->tovl[ p ].b = -1;
cctx->tovl[ p ].apos = 0;
cctx->tovl[ p ].bbpos = cctx->twidth * i;
cctx->tovl[ p ].bepos = cctx->twidth * ( i + 1 );
cctx->tovl[ p ].qv = cctx->qtrack_data[ oqa + i ];
}
cctx->tovl[ p ].bepos = alen;
#endif // USE_A_TILES
// B tiles
for ( i = 0; i < nOvls; i++ )
{
int bread = ovls[ i ]->bread;
tile = ovls[ i ]->path.abpos / cctx->twidth;
trace = ovls[ i ]->path.trace;
be = ovls[ i ]->path.bbpos + trace[ 1 ];
readidx = -1;
if ( curtiles[ tile ] < MAX_TILES )
{
p = cctx->toff[ tile ] + curtiles[ tile ];
curtiles[ tile ] += 1;
readidx = load_read( cctx, bread, ovls[ i ]->flags & OVL_COMP );
cctx->tovl[ p ].read = readidx;
cctx->tovl[ p ].a = a;
cctx->tovl[ p ].b = bread;
cctx->tovl[ p ].bbpos = ovls[ i ]->path.bbpos;
cctx->tovl[ p ].bepos = be;
cctx->tovl[ p ].qv = trace[ 0 ];
if ( ovls[ i ]->path.abpos % cctx->twidth )
{
cctx->tovl[ p ].apos = ovls[ i ]->path.abpos;
}
else
{
cctx->tovl[ p ].apos = 0;
}
}
for ( t = 2; t < ovls[ i ]->path.tlen; t += 2 )
{
tile++;
bb = be;
if ( t == ovls[ i ]->path.tlen - 1 )
{
be = ovls[ i ]->path.bepos + 1;
}
else
{
be += trace[ t + 1 ];
}
if ( curtiles[ tile ] < MAX_TILES )
{
p = cctx->toff[ tile ] + curtiles[ tile ];
curtiles[ tile ] += 1;
if ( readidx == -1 )
{
readidx = load_read( cctx, bread, ovls[ i ]->flags & OVL_COMP );
}
cctx->tovl[ p ].read = readidx;
cctx->tovl[ p ].a = a;
cctx->tovl[ p ].b = bread;
cctx->tovl[ p ].bbpos = bb;
cctx->tovl[ p ].bepos = be;
cctx->tovl[ p ].apos = 0;
cctx->tovl[ p ].qv = trace[ t ];
}
else
{
p = -1;
}
}
if ( p != -1 && ovls[ i ]->path.aepos < alen && ( ovls[ i ]->path.aepos % cctx->twidth ) )
{
cctx->tovl[ p ].apos = -1 * ovls[ i ]->path.aepos;
}
}
free( curtiles );
cctx->curcons = 0;
for ( i = 0; i < ntiles; i++ )
{
int tovl_b = cctx->toff[ i ];
int tovl_e = cctx->toff[ i + 1 ];
#ifdef USE_A_TILES
qsort( cctx->tovl + tovl_b + 1, tovl_e - ( tovl_b + 1 ), sizeof( tile_overlap ), cmp_tovl_qv );
#else
qsort( cctx->tovl + tovl_b, tovl_e - tovl_b, sizeof( tile_overlap ), cmp_tovl_qv );
#endif
}
// correct tiles
cctx->ce_tcur = 0;
/*
int trim_b, trim_e;
get_trim( cctx->db, cctx->trimtrack, a, &trim_b, &trim_e );
trim_b = trim_b / cctx->twidth;
trim_e = ( trim_e + cctx->twidth - 1 ) / cctx->twidth;
assert( trim_e <= ntiles );
*/
for ( i = 0; i < ntiles; i++ )
// for ( i = trim_b ; i < trim_e ; i++ )
{
#ifdef DEBUG
print_tiles( cctx, i );
#endif
int tiles_used;
char* seqcons = single_tile_consensus( cctx, i, &tiles_used );
if ( cctx->ce_tcur == 0 )
{
cctx->ce_first_tile = i;
}
cctx->ce_tiles[ cctx->ce_tcur ] = cctx->curcons;
cctx->ce_tcur++;
append_consensus( cctx, seqcons, tiles_used );
}
if ( cctx->curcons > 0 )
{
break_read( cctx, a );
}
cctx->db->reads[ a ].flags |= READ_CORRECTED;
cctx->nreads = 0;
}
static void* corrector_thread( void* arg )
{
corrector_arg* carg = (corrector_arg*)arg;
FILE* fileOvls = carg->fileOvls;
corrector_context cctx;
cctx.cons = consensus_init();
#ifdef DEBUG_MULTI
cctx.malign = msa_init();
cctx.malign_indent = 0;
#endif
cctx.ntoff = cctx.ntovl = 0;
cctx.nreads = cctx.maxreads = 0;
cctx.verbose = carg->verbose;
cctx.toff = NULL;
cctx.tovl = NULL;
cctx.reads = NULL;
cctx.fileOut = carg->fileOut;
cctx.fastaHeader = carg->fastaHeader;
cctx.db = &( carg->db );
cctx.seqcons = NULL;
cctx.maxcons = 0;
cctx.tiles = malloc( sizeof( int ) * 2 * ( carg->db.maxlen / carg->twidth + 1 ) );
cctx.curtiles = 0;
cctx.twidth = carg->twidth;
cctx.qtrack_offset = carg->qtrack->anno;
cctx.qtrack_data = carg->qtrack->data;
cctx.track = malloc( sizeof( int ) * carg->db.maxlen );
cctx.stats_tiles_single = 0;
cctx.stats_tiles_multi = 0;
cctx.thread = carg->thread;
cctx.mtc_dmax = 0;
cctx.mtc_data = NULL;
cctx.mtc_dsort = NULL;
cctx.ce_smax = 0;
cctx.ce_seq_singles = NULL;
cctx.ce_tcur = 0;
cctx.ce_tiles = malloc( sizeof( int ) * ( cctx.db->maxlen / cctx.twidth + 1 ) );
cctx.align_work_data = New_Work_Data();
ovl_trace* trace = NULL;
int tmax, tcur;
tcur = tmax = 0;
size_t tbytes = TBYTES( cctx.twidth );
int omax = 5000;
Overlap* pOvls = malloc( sizeof( Overlap ) * omax );
Overlap** ovls_sorted = malloc( sizeof( Overlap* ) * omax );
fseek( fileOvls, carg->start, SEEK_SET );
while ( !Read_Overlap( fileOvls, pOvls ) && ( (pOvls->flags & OVL_DISCARD) || (pOvls->path.tlen == 0) ) )
{
fseek( fileOvls, tbytes * pOvls->path.tlen, SEEK_CUR );
}
int a, n;
n = 0;
cctx.ncorrected = 0;
while ( ftell( fileOvls ) < carg->end )
{
pOvls[ 0 ] = pOvls[ n ];
ovls_sorted[ 0 ] = pOvls;
a = pOvls->aread;
if ( pOvls->path.tlen > tmax )
{
tmax = tmax * 1.2 + pOvls->path.tlen;
trace = realloc( trace, sizeof( ovl_trace ) * tmax );
}
tcur = 0;
pOvls->path.trace = trace;
read_unpacked_trace( fileOvls, pOvls, tbytes );
tcur += pOvls->path.tlen;
n = 1;
while ( 1 )
{
if ( Read_Overlap( fileOvls, pOvls + n ) || pOvls[ n ].aread != a )
{
break;
}
ovls_sorted[ n ] = pOvls + n;
if ( (pOvls[ n ].flags & OVL_DISCARD) || (pOvls[ n ].path.tlen == 0 ) )
{
fseek( fileOvls, tbytes * pOvls[ n ].path.tlen, SEEK_CUR );
continue;
}
if ( tcur + pOvls[ n ].path.tlen >= tmax )
{
tmax = tmax * 1.2 + pOvls[ n ].path.tlen;
trace = realloc( trace, sizeof( ovl_trace ) * tmax );
tcur = 0;
int k;
for ( k = 0; k < n; k++ )
{
pOvls[ k ].path.trace = trace + tcur;
tcur += pOvls[ k ].path.tlen;
}
}
pOvls[ n ].path.trace = trace + tcur;
tcur += pOvls[ n ].path.tlen;
read_unpacked_trace( fileOvls, pOvls + n, tbytes );
n += 1;
if ( n >= omax )
{
omax = 1.2 * n + 10;
pOvls = realloc( pOvls, sizeof( Overlap ) * omax );
ovls_sorted = realloc( ovls_sorted, sizeof( Overlap* ) * omax );
}
}
qsort( ovls_sorted, n, sizeof( Overlap* ), cmp_povl_length );
#ifdef ADJUST_OFFSETS
adjust_offsets( &cctx, ovls_sorted, n );
#endif
correct_overlaps( &cctx, ovls_sorted, n );
}
if ( cctx.toff != NULL )
{
free( cctx.toff );
}
if ( cctx.tovl != NULL )
{
free( cctx.tovl );
}
int i;
for ( i = 0; i < cctx.maxreads; i++ )
{
free( cctx.reads[ i ] - 1 );
}
free( cctx.reads );
free( cctx.mtc_data );
free( cctx.mtc_dsort );
free( cctx.ce_tiles );
free( cctx.ce_seq_singles );
free( cctx.track );
free( cctx.tiles );
free( cctx.seqcons );
free( pOvls );
free( ovls_sorted );
free( trace );
Free_Work_Data( cctx.align_work_data );
consensus_free( cctx.cons );
#ifdef DEBUG_MULTI
msa_free( cctx.malign );
#endif
return NULL;
}
static void usage()
{
printf( "[-v] [-r <file>] [-jx <int>] [-q <track>] <db> <in.las> <out.fasta>\n" );
printf( "options: -v ... verbose\n" );
printf( " -j ... number of threads\n" );
printf( " -q ... q track (%s)\n", DEF_ARG_Q );
printf( " -b ... block (%d)\n", DEF_ARG_B );
printf( " -r ... text file with ids of the reads to be corrected\n");
}
int main( int argc, char* argv[] )
{
FILE* fileOvls;
HITS_DB db;
int64 novl;
int twidth;
int verbose = 0;
int nThreads = 1;
int block = DEF_ARG_B;
char* qTrackName = DEF_ARG_Q;
char* pathReadIds = NULL;
// process arguments
int c;
opterr = 0;
while ( ( c = getopt( argc, argv, "vr:b:j:q:" ) ) != -1 )
{
switch ( c )
{
case 'r':
pathReadIds = optarg;
break;
case 'v':
verbose++;
break;
case 'j':
nThreads = atoi( optarg );
break;
case 'b':
block = atoi( optarg );
break;
case 'q':
qTrackName = optarg;
break;
default:
usage();
exit( 1 );
}
}
if ( argc - optind != 3 )
{
usage();
exit( 1 );
}
char* pcPathReadsIn = argv[ optind++ ];
char* pcPathOverlaps = argv[ optind++ ];
char* pcBaseOut = argv[ optind++ ];
if ( ( fileOvls = fopen( pcPathOverlaps, "r" ) ) == NULL )
{
fprintf( stderr, "could not open '%s'\n", pcPathOverlaps );
exit( 1 );
}
if ( fread( &novl, sizeof( novl ), 1, fileOvls ) != 1 )
{
fprintf( stderr, "failed to read %s header\n", pcPathOverlaps );
exit( 1 );
}
if ( fread( &twidth, sizeof( twidth ), 1, fileOvls ) != 1 )
{
fprintf( stderr, "failed to read %s header\n", pcPathOverlaps );
exit( 1 );
}
// init
if ( Open_DB( pcPathReadsIn, &db ) )
{
fprintf( stderr, "could not open '%s'\n", pcPathReadsIn );
exit( 1 );
}
HITS_TRACK* qtrack = track_load( &db, qTrackName );
if ( qtrack == NULL )
{
fprintf( stderr, "could not load quality track %s\n", qTrackName );
exit( 1 );
}
off_t* offsets = partition_overlaps( fileOvls, nThreads );
fclose( fileOvls );
int i;
for ( i = 0; i < DB_NREADS( &db ); i++ )
{
db.reads[ i ].flags = 0;
}
if ( pathReadIds )
{
FILE* fileIn = fopen( pathReadIds, "r" );
if ( fileIn == NULL )
{
fprintf( stderr, "could not open %s\n", pathReadIds );
exit( 1 );
}
int* values;
int nvalues;
fread_integers( fileIn, &values, &nvalues );
for ( i = 0; i < nvalues; i++ )
{
db.reads[ values[ i ] ].flags = READ_CORRECT;
}
free(values);
fclose( fileIn );
}
else
{
for ( i = 0; i < DB_NREADS( &db ); i++ )
{
db.reads[ i ].flags = READ_CORRECT;
}
}
pthread_t* threads = malloc( sizeof( pthread_t ) * nThreads );
corrector_arg* cargs = malloc( sizeof( corrector_arg ) * nThreads );
char* pcOut = malloc( strlen( pcBaseOut ) + 20 );
for ( i = 0; i < nThreads; i++ )
{
cargs[ i ].qtrack = qtrack;
cargs[ i ].verbose = verbose;
cargs[ i ].thread = i;
cargs[ i ].start = offsets[ i ];
cargs[ i ].end = offsets[ i + 1 ];
cargs[ i ].twidth = twidth;
cargs[ i ].fileOvls = fopen( pcPathOverlaps, "r" );
sprintf( pcOut, "%s.%02d.fasta", pcBaseOut, i );
cargs[ i ].fileOut = fopen( pcOut, "w" );
memcpy( &( cargs[ i ].db ), &db, sizeof( HITS_DB ) );
cargs[ i ].db.bases = NULL;
cargs[ i ].fastaHeader = pcBaseOut;
}
free( offsets );
free( pcOut );
for ( i = 0; i < nThreads; i++ )
{
pthread_create( threads + i, NULL, corrector_thread, cargs + i );
}
for ( i = 0; i < nThreads; i++ )
{
pthread_join( threads[ i ], NULL );
}
char* buf = New_Read_Buffer( &db );
int rb, re;
if ( block > 0 )
{
DB_block_range( pcPathReadsIn, block, &rb, &re );
}
else
{
rb = 0;
re = DB_NREADS( &db );
}
for ( i = rb; i < re; i++ )
{
int flags = db.reads[i].flags;
if ( (flags & READ_CORRECT) && !(flags & READ_CORRECTED) )
{
FILE* fileOut = cargs[ i % nThreads ].fileOut;
Load_Read( &db, i, buf, 1 );
fprintf( fileOut, ">copy.%d source=%d,%d,%d\n", i, i, -1, -1 );
write_seq( fileOut, buf );
}
}
free( buf - 1 );
for ( i = 0; i < nThreads; i++ )
{
fclose( cargs[ i ].fileOvls );
fclose( cargs[ i ].fileOut );
if(cargs[ i ].db.bases) // can still be NULL in rare cases - especially when last block has only a few reads that are not part of any contig
fclose( cargs[ i ].db.bases );
}
free( cargs );
free( threads );
Close_DB( &db );
return 0;
}
|
MartinPippel/DAmar
|
dalign/DMserver.c
|
<filename>dalign/DMserver.c<gh_stars>10-100
/*
maintains coverage statistics for all reads based on .las files produced by daligner and serves mask track
Author: <NAME>
Date: September 2016
overall usage:
- create initial mask track with DBdust and split database into blocks with DBsplit
- start dmask_server with db, expected coverage and optional checkpoint file
- server listenes on <port> (argument -p) for messages
- daligner jobs connect to server and retrieve mask track for the block to be processed
- finished daligner jobs report path of .las file to the dmask server
- server processes .las files, updates coverage statistics and derives new mask track from it
- regions of reads receiving an excess of coverage are masked
- on server shutdown a mask track is written to disk
- every -c <minutes> the server outputs a checkpoint file containing
its current state. checkpoints receive an alternating suffix of either .0 or .1. This ensures
at least one intact file in case the server crashes while writing a checkpoint.
- to resume from a checkpoint drop the suffix, the server will resume from the file automatically
on startup
- amount of worker threads for processing .las files can be set using -t <threads>
memory usage:
50x human genome needs roughly 20GB of memory
CPU/IO requirements:
.las files are large initially when no repeat regions have been masked
notes:
we recommend processing the diagonal of the block vs block matrix initially in order
to mask the highly repetitive regions of all reads first
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>
#include <pthread.h>
#include <semaphore.h>
#include <fcntl.h>
#include <signal.h>
#include <locale.h>
#if defined(__APPLE__)
#include <sys/syslimits.h>
#else
#include <linux/limits.h>
#endif
#include "lib/dmask.h"
#include "lib/pass.h"
#include "lib/tracks.h"
#include "lib/dmask_proto.h"
#include "lib/utils.h"
#include "lib/oflags.h"
#define DEF_ARG_P DMASK_DEFAULT_PORT
#define DEF_ARG_T 4 // worker threads
#define DEF_ARG_C 10 // checkpoint intervals (min)
#define DEF_ARG_U 10 // track update (min)
#define DEF_ARG_R 10 // report every (min)
#define DEF_ARG_CC 0 // mask contained reads completely
#define DEF_ARG_E 0 // no repeat masking n bases from the read ends
#define COV_LOCK_GRANULARITY 4 // must be a power of 2
#define MAX_COV 255
#define BACKLOG 20 // Passed to listen()
#define COV_FACTOR_THRESHOLD 2 // mask if more than 2 times expected coverage
#define REPORT_INTERVALS "dmask.report.txt"
#define SEMAPHORE_FILL_COUNT_PREFIX "sem.queue.fill.count" // semaphore name prefix
#define IO_BUFFER_SIZE (1024 * 1024)
#undef TRANSFER_ANNOTATION
typedef struct _ServerContext ServerContext;
typedef struct _WorkerContext WorkerContext;
typedef struct _WorkQueueItem WorkQueueItem;
typedef struct _ReadCoverageRle ReadCoverageRle;
typedef struct _ReadCoverage ReadCoverage;
struct _WorkQueueItem
{
char path[PATH_MAX + 1];
WorkQueueItem* next;
};
struct _ReadCoverageRle
{
unsigned char value;
uint32 count;
};
struct _ReadCoverage
{
ReadCoverageRle* data;
size_t dmax;
};
/*
context for each worker thread
*/
struct _WorkerContext
{
HITS_DB* db; // database
int id; // thread id
ServerContext* sctx; // pointer to server context
Overlap* ovls; // storage for overlaps
ovl_header_novl maxovl; // size allocated for ovls
Overlap** ovls_sorted; // pointers to sorted overlaps
unsigned char* read_cov; // used for collecting per-base coverage stats
unsigned char* read_cov_temp; // only used by rle_unpack
ReadCoverage cov_temp; // temporary location outside ServerContext for reduced (un)locking
uint32 trace_max; // allocated elements for trace
uint32 trace_cur; // next free element in trace
ovl_trace* trace; // overlap trace points
};
/*
global state of the dmask server
*/
struct _ServerContext
{
HITS_DB* db; // database
uint64 bases; // number of bases in the db
// socket buffer
char* data; // socket input buffer
int dmax; // buffer size
// threads
pthread_t thread_socket_listener;
pthread_t thread_reporter;
pthread_t thread_track;
pthread_t thread_checkpoint;
// work queue
WorkQueueItem* queue_start; // global work queue containing .las files
WorkQueueItem* queue_end; // pointers to start and end of the single-linked list
pthread_mutex_t queue_lock; // lock for the work queue
sem_t* queue_fill_count; // semaphore containing queue length
char* path_sem_fill_count;
int queue_len;
// coverage statistics
ReadCoverage* cov; // coverage statistics for each read
int cov_changed; // have the coverage stats changed since the last update_track call
// pthread_mutex_t cov_lock; // lock for cov and cov_changed
pthread_mutex_t cov_locks[COV_LOCK_GRANULARITY];
uint32 lock_mask;
uint32 lock_shift;
// track data
uint64 t_dmax;
track_anno* t_anno;
track_data* t_data;
pthread_mutex_t t_lock;
// command line arguments
int cov_expected;
int port;
int worker_threads;
char* checkpoint;
int checkpoint_suffix;
int shutdown;
int report_intervals; // write detailed intervals to disk with next report
int lock; // don't update coverage statistics
int checkpoint_wait; // wait time between checkpoints
int report_wait;
int track_update_wait;
int mask_contained;
int keep_ends; // keep n bases at the read ends not masked
};
/*
we keep a pointer to the ServerContext in the global namespace in order to
make it available to the signal handlers
*/
ServerContext* g_sctx;
#define rid2lock(rid) ( (rid) >> g_sctx->lock_shift )
/*
static int rid2lock(uint32 rid)
{
return ( rid >> g_sctx->lock_shift );
}
*/
static void queue_add(ServerContext* ctx, char* path)
{
WorkQueueItem* item = (WorkQueueItem*)malloc(sizeof(WorkQueueItem));
if (ctx->queue_end != NULL)
{
ctx->queue_end->next = (WorkQueueItem*)item;
}
else
{
ctx->queue_start = item;
}
ctx->queue_end = item;
item->next = NULL;
strcpy(item->path, path);
ctx->queue_len++;
}
static char* queue_remove(ServerContext* ctx)
{
char* path = strdup(ctx->queue_start->path);
WorkQueueItem* item = ctx->queue_start;
if (ctx->queue_start == ctx->queue_end)
{
ctx->queue_end = NULL;
}
ctx->queue_start = (WorkQueueItem*)(item->next);
free(item);
ctx->queue_len--;
return path;
}
static int cmp_ovls(const void* a, const void* b)
{
Overlap* x = *(Overlap**)a;
Overlap* y = *(Overlap**)b;
return x->aread - y->aread;
}
static int rle_pack(unsigned char* data, int ndata, ReadCoverageRle** _packed, size_t* _maxpacked)
{
ReadCoverageRle* packed = *_packed;
int maxpacked = *_maxpacked;
int i, j;
int segments = 1;
for (i = 1; i < ndata; i++)
{
if (data[i-1] != data[i])
{
segments++;
}
}
if (segments + 2 >= maxpacked)
{
*_maxpacked = maxpacked = segments * 1.2 + 20;
*_packed = packed = realloc(packed, maxpacked * sizeof(ReadCoverageRle) );
}
unsigned char value = data[0];
uint32 count = 1;
for (i = 1, j = 0; i < ndata; i++)
{
if (value == data[i])
{
count++;
}
else
{
packed[j].count = count;
packed[j++].value = value;
count = 1;
value = data[i];
}
}
packed[j].count = count;
packed[j++].value = value;
packed[j].count = 0;
return (j+1);
}
static int rle_unpack(unsigned char* unpacked, ReadCoverageRle* packed)
{
int i, j;
for (i = 0, j = 0; packed[i].count != 0; i++)
{
uint32 count = packed[i].count;
unsigned char value = packed[i].value;
while (count)
{
unpacked[j++] = value;
count--;
}
}
return j;
}
static void mask_contained_read(WorkerContext* wctx, int aread, int alen)
{
ServerContext* sctx = wctx->sctx;
int unpack = 0;
int lock = rid2lock(aread); // aread & ( COV_LOCK_GRANULARITY - 1 );
pthread_mutex_lock( sctx->cov_locks + lock );
sctx->db->reads[aread].flags = 1;
// TODO --- redundant ... fix
// pthread_mutex_lock( &(sctx->cov_lock) );
{
if (sctx->cov[aread].data != NULL)
{
memcpy(wctx->cov_temp.data, sctx->cov[aread].data, sctx->cov[aread].dmax * sizeof(ReadCoverageRle));
unpack = 1;
}
}
// pthread_mutex_unlock( &(sctx->cov_lock) );
if (unpack)
{
bzero(wctx->read_cov_temp, sizeof(unsigned char) * alen);
rle_unpack(wctx->read_cov_temp, wctx->cov_temp.data);
int i;
for (i = 0; i < alen; i++)
{
wctx->read_cov[i] = MAX_COV;
}
}
size_t dcur = rle_pack(wctx->read_cov, alen, &(wctx->cov_temp.data), &(wctx->cov_temp.dmax));
// pthread_mutex_lock( &(sctx->cov_lock) );
{
if (dcur >= sctx->cov[aread].dmax)
{
sctx->cov[aread].dmax = dcur * 1.2 + 10;
sctx->cov[aread].data = realloc(sctx->cov[aread].data, sctx->cov[aread].dmax * sizeof(ReadCoverageRle));
}
memcpy(sctx->cov[aread].data, wctx->cov_temp.data, dcur * sizeof(ReadCoverageRle));
sctx->cov_changed = 1;
}
// pthread_mutex_unlock( &(sctx->cov_lock) );
pthread_mutex_unlock( sctx->cov_locks + lock );
}
static void update_coverage(WorkerContext* wctx, int aread, int alen)
{
ServerContext* sctx = wctx->sctx;
int unpack = 0;
int lock = rid2lock(aread); // aread & ( COV_LOCK_GRANULARITY - 1 );
pthread_mutex_lock( sctx->cov_locks + lock );
// TODO --- redundant ... fix
// pthread_mutex_lock( &(sctx->cov_lock) );
{
if (sctx->cov[aread].data != NULL)
{
memcpy(wctx->cov_temp.data, sctx->cov[aread].data, sctx->cov[aread].dmax * sizeof(ReadCoverageRle));
unpack = 1;
}
}
// pthread_mutex_unlock( &(sctx->cov_lock) );
if (unpack)
{
bzero(wctx->read_cov_temp, sizeof(unsigned char) * alen);
rle_unpack(wctx->read_cov_temp, wctx->cov_temp.data);
int i;
for (i = 0; i < alen; i++)
{
uint32 cov = wctx->read_cov[i] + wctx->read_cov_temp[i];
if (cov > MAX_COV)
{
cov = MAX_COV;
}
wctx->read_cov[i] = cov;
}
}
size_t dcur = rle_pack(wctx->read_cov, alen, &(wctx->cov_temp.data), &(wctx->cov_temp.dmax));
// pthread_mutex_lock( &(sctx->cov_lock) );
{
if (dcur >= sctx->cov[aread].dmax)
{
sctx->cov[aread].dmax = dcur * 1.2 + 10;
sctx->cov[aread].data = realloc(sctx->cov[aread].data, sctx->cov[aread].dmax * sizeof(ReadCoverageRle));
}
memcpy(sctx->cov[aread].data, wctx->cov_temp.data, dcur * sizeof(ReadCoverageRle));
sctx->cov_changed = 1;
}
// pthread_mutex_unlock( &(sctx->cov_lock) );
pthread_mutex_unlock( sctx->cov_locks + lock );
}
static void write_mask_tracks(ServerContext* sctx)
{
HITS_DB* db = sctx->db;
int nreads = db->nreads;
track_anno* anno_r = malloc(sizeof(track_anno) * (db->nreads + 1));
track_data* data_r = malloc( sctx->t_anno[nreads] );
int dcur_r = 0;
track_anno* anno_c = malloc(sizeof(track_anno) * (db->nreads + 1));
track_data* data_c = malloc( 2 * sizeof(track_data) * db->nreads );
int dcur_c = 0;
int i;
for ( i = 0; i < nreads; i++ )
{
track_anno beg = sctx->t_anno[i] / sizeof(track_data);
track_anno end = sctx->t_anno[i + 1] / sizeof(track_data);
anno_r[i] = 0;
anno_c[i] = 0;
if (db->reads[i].flags == 1)
{
data_c[dcur_c++] = 0;
data_c[dcur_c++] = DB_READ_LEN(db, i);
anno_c[i] += 2 * sizeof(track_data);
}
else
{
while (beg < end)
{
track_data b = sctx->t_data[beg];
track_data e = sctx->t_data[beg + 1];
data_r[dcur_r++] = b;
data_r[dcur_r++] = e;
beg += 2;
anno_r[i] += 2 * sizeof(track_data);
}
}
}
track_anno off_r = 0;
track_anno off_c = 0;
for (i = 0; i <= nreads; i++)
{
track_anno tmp = anno_c[i];
anno_c[i] = off_c;
off_c += tmp;
tmp = anno_r[i];
anno_r[i] = off_r;
off_r += tmp;
}
track_write(db, TRACK_MASK_R, 0, anno_r, data_r, anno_r[ nreads ] / sizeof(track_data));
track_write(db, TRACK_MASK_C, 0, anno_c, data_c, anno_c[ nreads ] / sizeof(track_data));
// write_track_trimmed(db, TRACK_MASK_R, 0, anno_r, data_r, anno_r[ nreads ] / sizeof(track_data));
// write_track_trimmed(db, TRACK_MASK_C, 0, anno_c, data_c, anno_c[ nreads ] / sizeof(track_data));
}
static void process_las(WorkerContext* ctx, const char* path)
{
int mask_contained = ctx->sctx->mask_contained;
FILE* fileIn = fopen(path, "r");
if (fileIn == NULL)
{
fprintf(stderr, "could not open %s\n", path);
return ;
}
ovl_header_novl novl;
ovl_header_twidth twidth;
if (!ovl_header_read(fileIn, &novl, &twidth))
{
fprintf(stderr, "failed to read header of %s\n", path);
return ;
}
// TODO ... handle garbage novl value
int tbytes = TBYTES(twidth);
if (novl > ctx->maxovl)
{
ctx->maxovl = novl * 1.2 + 100;
ctx->ovls = (Overlap*)realloc(ctx->ovls, ctx->maxovl * sizeof(Overlap));
ctx->ovls_sorted = (Overlap**)realloc(ctx->ovls_sorted, ctx->maxovl * sizeof(Overlap*));
}
ovl_header_novl i;
for (i = 0; i < novl; i++)
{
Overlap* ovl = ctx->ovls + i;
if (Read_Overlap(fileIn, ovl))
{
break;
}
#ifdef TRANSFER_ANNOTATION
if (ovl->path.tlen + ctx->trace_cur > ctx->trace_max)
{
ctx->trace_max = 1.2 * ctx->trace_max + ovl->path.tlen;
ovl_trace* trace = realloc(ctx->trace, ctx->trace_max * sizeof(ovl_trace));
ovl_header_novl j;
for (j = 0; j < i; j++)
{
ctx->ovls[j].path.trace = trace + ((ovl_trace*) (ctx->ovls[j].path.trace) - ctx->trace);
}
ctx->trace = trace;
}
ovl->path.trace = ctx->trace + ctx->trace_cur;
Read_Trace(fileIn, ovl, tbytes);
ctx->trace_cur += ovl->path.tlen;
if (tbytes == sizeof(uint8))
{
Decompress_TraceTo16(ovl);
}
#else
fseeko(fileIn, ovl->path.tlen * tbytes, SEEK_CUR);
#endif
ctx->ovls_sorted[i] = ovl;
}
novl = i;
fclose(fileIn);
if (novl == 0)
{
fprintf(stderr, "reading las file yielded %lld overlaps\n", novl);
return ;
}
qsort(ctx->ovls_sorted, novl, sizeof(Overlap*), cmp_ovls);
// count multiple B-read overlaps as a single hit
int ovlALen = DB_READ_LEN(ctx->db, ctx->ovls_sorted[0]->aread);
for ( i = 0; i < novl; i++ )
{
Overlap* ovl_o = ctx->ovls_sorted[i];
if (mask_contained)
{
if (ovl_o->path.abpos == 0 && ovl_o->path.aepos == ovlALen)
{
mask_contained_read(ctx, ovl_o->aread, ovlALen);
}
if (ovl_o->path.bbpos == 0)
{
int blen = DB_READ_LEN(ctx->db, ovl_o->bread);
if (ovl_o->path.bepos == blen)
{
mask_contained_read(ctx, ovl_o->bread, blen);
}
}
}
ovl_header_novl j;
for ( j = i + 1; j < novl ; j++ )
{
Overlap* ovl_i = ctx->ovls_sorted[j];
if ( ovl_o->bread != ovl_i->bread )
{
break ;
}
if ( ovl_i->path.abpos <= ovl_o->path.aepos &&
ovl_o->path.abpos <= ovl_i->path.aepos )
{
int ab = MIN(ovl_o->path.abpos, ovl_i->path.abpos);
int ae = MAX(ovl_o->path.aepos, ovl_i->path.aepos);
ovl_i->path.abpos = ab;
ovl_i->path.aepos = ae;
ovl_o->flags |= OVL_DISCARD;
break ;
}
}
}
int keep_ends = ctx->sctx->keep_ends;
if (keep_ends != -1)
{
int prevovlALen = 0;
bzero(ctx->read_cov, ovlALen);
Overlap* prevovl = NULL;
for (i = 0; i < novl; i++)
{
Overlap* ovl = ctx->ovls_sorted[i];
ovlALen = DB_READ_LEN(ctx->db, ovl->aread);
if (ovl->flags & OVL_DISCARD)
{
continue;
}
if (ovl->aread == ovl->bread)
{
continue;
}
if (prevovl && prevovl->aread != ovl->aread)
{
update_coverage(ctx, prevovl->aread, prevovlALen);
bzero(ctx->read_cov, ovlALen);
}
int beg, end;
if (keep_ends > 0)
{
beg = MAX(ovl->path.abpos, keep_ends);
end = MIN(ovl->path.aepos, ovlALen - keep_ends);
}
else
{
beg = ovl->path.abpos;
end = ovl->path.aepos;
}
int j;
for (j = beg; j < end; j++)
{
if (ctx->read_cov[j] == MAX_COV)
{
continue;
}
ctx->read_cov[j]++;
}
prevovl = ovl;
prevovlALen = ovlALen;
}
update_coverage(ctx, prevovl->aread, prevovlALen);
}
#ifdef TRANSFER_ANNOTATION
int preva = -1;
ServerContext* sctx = ctx->sctx;
int cov_threshold = sctx->cov_expected * COV_FACTOR_THRESHOLD;
int has_repeat = 0;
for ( i = 0; i < novl; i++ )
{
Overlap* ovl = ctx->ovls + i;
int aread = ovl->aread;
if (aread != preva)
{
has_repeat = 0;
int lock = rid2lock(aread);
pthread_mutex_lock( sctx->cov_locks + lock );
unsigned char* unpacked = ctx->read_cov;
ReadCoverageRle* packed = sctx->cov[aread].data;
// TODO --- trim intervals to next segment boundary
int k, j;
for (k = 0, j = 0; packed[k].count != 0; k++)
{
uint32 count = packed[k].count;
unsigned char value = packed[k].value;
if (value > cov_threshold)
{
// TODO --- only keep mod 100 intervals
has_repeat = 1;
memset(unpacked + j, MAX_COV, count);
}
j += count;
}
pthread_mutex_unlock( ctx->sctx->cov_locks + lock );
preva = ovl->aread;
}
}
#endif
}
/*
static int map_repeat_to_b(Overlap* ovl, int* _beg, int* _end)
{
int beg = *_beg;
int end = *_end;
int ab = ovl->path.abpos;
int ae = ovl->path.aepos;
if (end - beg < MIN_INT_LEN)
{
return 0;
}
// does the repeat interval intersect with overlap
int iab = MAX(beg, ab);
int iae = MIN(end, ae);
if (iab >= iae)
{
return 0;
}
// establish conservative estimate of the repeat extent
// relative to the b read given the trace points
ovl_trace* trace = ovl->path.trace;
int tlen = ovl->path.tlen;
int ibb = -1;
int ibe = -1;
int aoff = ovl->path.abpos;
int boff = ovl->path.bbpos;
int j;
for (j = 0; j < tlen; j += 2)
{
if ( (aoff >= iab || j == tlen - 2) && ibb == -1 )
{
ibb = boff;
}
aoff = ( (aoff + twidth) / twidth) * twidth;
if ( aoff >= iae && ibe == -1 )
{
if (ibb == -1)
{
ibb = boff;
}
ibe = boff + trace[j + 1];
break;
}
boff += trace[j + 1];
}
if (ibb == -1 || ibe == -1)
{
return 0;
}
if (ovl->flags & OVL_COMP)
{
int t = ibb;
int blen = DB_READ_LEN(ctx->db, ovl->bread);
ibb = blen - ibe;
ibe = blen - t;
}
assert(ibb <= ibe);
*_beg = ibb;
*_end = ibe;
return 1;
}
*/
static void update_track(ServerContext* sctx)
{
time_t time_beg = time(NULL);
int nreads = sctx->db->nreads;
int i;
uint64 dcur = 0;
/*
for (i = 0; i < COV_LOCK_GRANULARITY; i++)
{
pthread_mutex_lock( sctx->cov_locks + i );
}
*/
bzero(sctx->t_anno, sizeof(track_anno) * (nreads + 1));
track_data* t_data = sctx->t_data;
track_anno* t_anno = sctx->t_anno;
uint64 t_dmax = sctx->t_dmax;
int cov_threshold = sctx->cov_expected * COV_FACTOR_THRESHOLD;
for (i = 0; i < nreads; i++)
{
ReadCoverage* cov = sctx->cov + i;
ReadCoverageRle* rle = cov->data;
if (rle)
{
int j = 0;
int pos = 0;
uint64 dcur_prev = dcur;
while (rle[j].count)
{
if (rle[j].value > cov_threshold)
{
if (dcur + 2 >= t_dmax)
{
sctx->t_dmax = t_dmax = dcur * 1.2 + 1000;
sctx->t_data = t_data = (track_data*)realloc(t_data, sizeof(track_data) * t_dmax );
}
if (dcur != dcur_prev && pos == t_data[dcur-1])
{
t_data[dcur-1] = pos + rle[j].count;
}
else
{
t_data[dcur++] = pos;
t_data[dcur++] = pos + rle[j].count;
t_anno[i] += sizeof(track_data) * 2;
}
}
pos += rle[j].count;
j++;
}
}
}
/*
for (i = 0; i < COV_LOCK_GRANULARITY; i++)
{
pthread_mutex_unlock( sctx->cov_locks + i );
}
*/
track_anno off = 0;
for (i = 0; i <= nreads; i++)
{
track_anno tmp = t_anno[i];
t_anno[i] = off;
off += tmp;
}
sctx->cov_changed = 0;
printf("UPDATE TRACK (%ld secs)\n", time(NULL) - time_beg);
}
static void shutdown_server(ServerContext* ctx)
{
ctx->shutdown = 1;
// TODO ... cheap hack to wake up all worker threads so they terminate
int i;
for (i = 0; i < ctx->worker_threads; i++)
{
sem_post( ctx->queue_fill_count );
}
}
static void socket_data_handler(ServerContext* ctx, int newsock, fd_set *set)
{
DmHeader header;
if (recv(newsock, &header, sizeof(header), 0) != sizeof(header))
{
fprintf(stderr, "CLOSE CONNECTION\n");
FD_CLR(newsock, set);
close(newsock);
return ;
}
char* data;
int dcur = 0;
int pending = header.length - sizeof(header);
if (ctx->dmax < pending)
{
ctx->dmax = pending * 2;
ctx->data = realloc(ctx->data, ctx->dmax);
}
data = ctx->data;
while (pending)
{
int received = recv(newsock, data + dcur, pending, 0);
if (received < 1)
{
break;
}
dcur += received;
pending -= received;
}
if (pending != 0)
{
fprintf(stderr, "error %d bytes pending\n", pending);
return;
}
switch (header.type)
{
case DM_TYPE_SHUTDOWN:
shutdown_server(ctx);
break;
case DM_TYPE_LOCK:
if (ctx->lock)
{
printf("LOCK FAILED ... already locked\n");
}
else
{
printf("LOCK SUCCESS\n");
ctx->lock = 1;
}
break;
case DM_TYPE_UNLOCK:
if (ctx->lock)
{
printf("UNLOCK SUCCESS\n");
ctx->lock = 0;
}
else
{
printf("UNLOCK FAILED ... not locked\n");
}
break;
case DM_TYPE_INTERVALS:
ctx->report_intervals = 1;
break;
case DM_TYPE_WRITE_TRACK:
pthread_mutex_lock( &(ctx->t_lock) );
write_mask_tracks(ctx);
pthread_mutex_unlock( &(ctx->t_lock) );
break;
case DM_TYPE_LAS_AVAILABLE:
if (ctx->lock)
{
printf("updates locked, ignoring available .las files\n");
}
else
{
pthread_mutex_lock(&(ctx->queue_lock));
{
int i;
int beg = 0;
for (i = 0; i < dcur; i++)
{
if (data[i] == '\0')
{
queue_add(ctx, data + beg);
sem_post( ctx->queue_fill_count );
printf("QUEUE LEN %3d ADD %s\n", ctx->queue_len, data + beg);
beg = i + 1;
}
}
}
pthread_mutex_unlock(&(ctx->queue_lock));
}
break;
case DM_TYPE_REQUEST_TRACK:
{
uint64 bfirst = header.reserved1;
uint64 nreads = header.reserved2;
printf("REQUEST TRACK ... bfirst = %llu nreads = %llu\n", bfirst, nreads);
track_anno* anno = (track_anno*)malloc( sizeof(track_anno) * (nreads + 1) );
pthread_mutex_lock( &(ctx->t_lock) );
{
memcpy(anno, ctx->t_anno + bfirst, sizeof(track_anno) * (nreads + 1));
uint64 i;
track_anno off = anno[0];
for (i = 0; i <= nreads; i++)
{
anno[i] -= off;
}
uint64 dlen = anno[nreads];
// DATA: ctx->t_data[ off : off + dlen ]
DmHeader headerResp;
bzero(&headerResp, sizeof(DmHeader));
headerResp.version = DM_VERSION;
headerResp.type = DM_TYPE_RESPONSE_TRACK;
headerResp.length = sizeof(DmHeader) +
sizeof(track_anno) * (nreads + 1) +
dlen;
printf(" SENDING %llu bytes (ANNO %llu DATA %llu)\n",
headerResp.length,
sizeof(track_anno) * (nreads + 1),
dlen);
send(newsock, &headerResp, sizeof(DmHeader), 0);
// send track
send(newsock, anno, sizeof(track_anno) * (nreads + 1), 0);
send(newsock, ctx->t_data + off / sizeof(track_data), dlen, 0);
}
pthread_mutex_unlock( &(ctx->t_lock) );
free(anno);
}
break;
default:
fprintf(stderr, "unknown message type %d\n", header.type);
break;
}
}
static void* socket_listener_thread(void *arg)
{
ServerContext* ctx = (ServerContext*)arg;
int sock;
fd_set socks;
fd_set readsocks;
int maxsock;
int reuseaddr = 1; /* True */
/* Create the socket */
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0)
{
perror("socket");
return NULL;
}
/* Enable the socket to reuse the address */
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(int)) < 0)
{
perror("setsockopt");
return NULL;
}
/* Bind to the address */
struct sockaddr_in serv_addr;
bzero(&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(ctx->port);
if (bind(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0)
{
perror("bind");
return NULL;
}
/* Listen */
if (listen(sock, BACKLOG) < 0)
{
perror("listen");
return NULL;
}
/* Set up the fd_set */
FD_ZERO(&socks);
FD_SET(sock, &socks);
maxsock = sock;
printf("socket listener thread reporting for duty (port %d)\n", ctx->port);
/* Main loop */
while (1)
{
if (ctx->shutdown)
{
printf("socket listener thread shutting down\n");
break;
}
int s;
readsocks = socks;
if (select(maxsock + 1, &readsocks, NULL, NULL, NULL) == -1)
{
perror("select");
return NULL;
}
for (s = 0; s <= maxsock; s++)
{
if (FD_ISSET(s, &readsocks))
{
// printf("SOCKET %d READY\n", s);
if (s == sock)
{
/* New connection */
int newsock;
struct sockaddr_in their_addr;
socklen_t size = sizeof(struct sockaddr_in);
newsock = accept(sock, (struct sockaddr*)&their_addr, &size);
if (newsock == -1)
{
perror("accept");
}
else
{
printf("CONNECT FROM %s:%d\n", inet_ntoa(their_addr.sin_addr), htons(their_addr.sin_port));
FD_SET(newsock, &socks);
if (newsock > maxsock)
{
maxsock = newsock;
}
}
}
else
{
socket_data_handler(ctx, s, &socks);
}
}
}
}
close(sock);
return NULL;
}
static void* worker_thread(void *arg)
{
WorkerContext* wctx = (WorkerContext*)arg;
ServerContext* sctx = wctx->sctx;
printf("worker thread %d reporting for duty\n", wctx->id);
while (1)
{
if (sem_wait( sctx->queue_fill_count ))
{
perror("sem_wait");
}
if (sctx->shutdown)
{
break;
}
pthread_mutex_lock(&(sctx->queue_lock));
// TODO ... file doesn't necessarily have to be visible to us (slow distributed filesystem, etc)
char* path = queue_remove(sctx);
printf("THREAD %2d PROCESS %s\n", wctx->id, path);
pthread_mutex_unlock(&(sctx->queue_lock));
process_las(wctx, path);
free(path);
}
return NULL;
}
static void worker_ctx_init(ServerContext* sctx, WorkerContext* wctx)
{
wctx->sctx = sctx;
wctx->maxovl = 1000;
wctx->ovls = (Overlap*)malloc(sizeof(Overlap) * wctx->maxovl);
wctx->ovls_sorted = (Overlap**)malloc(sizeof(Overlap*) * wctx->maxovl);
wctx->read_cov = malloc( sctx->db->maxlen );
wctx->read_cov_temp = malloc( sctx->db->maxlen );
wctx->cov_temp.dmax = sctx->db->maxlen * sizeof(ReadCoverageRle);
wctx->cov_temp.data = malloc( wctx->cov_temp.dmax );
wctx->db = sctx->db;
wctx->trace_max = 1 * 1024 * 1024;
wctx->trace_cur = 0;
wctx->trace = malloc( sizeof(ovl_trace) * wctx->trace_max );
}
static void worker_ctx_free(WorkerContext* wctx)
{
free(wctx->ovls);
free(wctx->ovls_sorted);
free(wctx->read_cov);
free(wctx->read_cov_temp);
free(wctx->cov_temp.data);
free(wctx->trace);
}
static void* update_track_thread(void* arg)
{
ServerContext* sctx = (ServerContext*)arg;
printf("track update thread reporting for duty\n");
while (1)
{
int i = sctx->track_update_wait * 60;
while (i > 0 && !sctx->shutdown)
{
sleep(1);
i--;
}
if (sctx->shutdown)
{
break;
}
for ( i = 0 ; i < COV_LOCK_GRANULARITY; i++ )
{
pthread_mutex_lock( sctx->cov_locks + i );
}
// pthread_mutex_lock( &(sctx->cov_lock) );
if (sctx->cov_changed)
{
pthread_mutex_lock( &(sctx->t_lock) );
update_track(sctx);
pthread_mutex_unlock( &(sctx->t_lock) );
}
// pthread_mutex_unlock( &(sctx->cov_lock) );
for ( i = 0 ; i < COV_LOCK_GRANULARITY; i++ )
{
pthread_mutex_unlock( sctx->cov_locks + i );
}
}
return NULL;
}
static int checkpoint_write(ServerContext* sctx, FILE* fileOut)
{
time_t time_beg = time(NULL);
fwrite( &(sctx->db->nreads), sizeof(sctx->db->nreads), 1, fileOut );
int i;
for (i = 0; i < sctx->db->nreads; i++)
{
ReadCoverage* cov = sctx->cov + i;
// count data elements
size_t items = 0;
if (cov->data)
{
while (cov->data[items].count)
{
items++;
}
}
// write count & elements
fwrite(&items, sizeof(size_t), 1, fileOut);
if (items > 0)
{
fwrite(cov->data, sizeof(ReadCoverageRle), items, fileOut);
}
}
printf("CHECKPOINT (%ld secs)\n", time(NULL) - time_beg);
return 1;
}
static int checkpoint_read(ServerContext* sctx, FILE* fileIn)
{
int nreads = 0;
if (fread(&nreads, sizeof(nreads), 1, fileIn) != 1)
{
fprintf(stderr, "failed to read nreads from checkpoint file\n");
return 0;
}
if (nreads != sctx->db->nreads)
{
fprintf(stderr, "failed to restore checkpoint. nreads in db not the same as in checkpoint\n");
return 0;
}
size_t items;
int read;
for (read = 0; read < nreads && !feof(fileIn); read++)
{
if (fread(&items, sizeof(size_t), 1, fileIn) != 1)
{
break;
}
ReadCoverage* cov = sctx->cov + read;
if (items >= cov->dmax)
{
cov->dmax = items * 1.2 + 10;
cov->data = (ReadCoverageRle*)realloc(cov->data, sizeof(ReadCoverageRle) * cov->dmax);
}
if (fread(cov->data, sizeof(ReadCoverageRle), items, fileIn) != items)
{
break;
}
cov->data[items].count = 0;
cov->data[items].value = 0;
}
if (read != nreads)
{
fprintf(stderr, "warning: checkpoint didn't contain data for all reads.\n");
for (read = 0; read < nreads; read++)
{
ReadCoverage* cov = sctx->cov + read;
if (cov->data)
{
cov->data[0].count = 0;
cov->data[0].value = 0;
}
}
}
return 1;
}
static void* checkpoint_thread(void* arg)
{
ServerContext* sctx = (ServerContext*)arg;
// pthread_mutex_t* cov_lock = &(sctx->cov_lock);
char* path = malloc( strlen(sctx->checkpoint) + 20 );
printf("checkpoint thread reporting for duty\n");
while (1)
{
int i = sctx->checkpoint_wait * 60;
while (i > 0 && !sctx->shutdown)
{
sleep(1);
i--;
}
for ( i = 0 ; i < COV_LOCK_GRANULARITY ; i++)
{
pthread_mutex_lock( sctx->cov_locks + i );
}
// pthread_mutex_lock(cov_lock);
sprintf(path, "%s.%d", sctx->checkpoint, sctx->checkpoint_suffix);
sctx->checkpoint_suffix = (sctx->checkpoint_suffix + 1) % 2;
FILE* fileOut = fopen(path, "w");
setvbuf(fileOut, NULL, _IOFBF, IO_BUFFER_SIZE);
checkpoint_write(sctx, fileOut);
fclose(fileOut);
// pthread_mutex_unlock(cov_lock);
for ( i = 0 ; i < COV_LOCK_GRANULARITY ; i++)
{
pthread_mutex_unlock( sctx->cov_locks + i );
}
if (sctx->shutdown)
{
break;
}
}
free(path);
return NULL;
}
static void* reporter_thread(void* arg)
{
int suffix = 0;
char* path_report = (char*)malloc(strlen(REPORT_INTERVALS) + 20);
ServerContext* sctx = (ServerContext*)arg;
uint64 nreads = sctx->db->nreads;
// pthread_mutex_t* cov_lock = &(sctx->cov_lock);
FILE* fileOut = NULL;
printf("report thread reporting for duty\n");
while (1)
{
uint64 i = sctx->report_wait * 60;
while (i > 0 && !sctx->shutdown)
{
sleep(1);
i--;
}
if (sctx->shutdown)
{
break;
}
if (sctx->report_intervals)
{
sprintf(path_report, "%s.%d", REPORT_INTERVALS, suffix);
suffix++;
fileOut = fopen(path_report, "w");
if (!fileOut)
{
printf("failed to open %s\n", path_report);
}
}
uint64 reads_with_intervals, bases_masked;
reads_with_intervals = bases_masked = 0;
for (i = 0; i < COV_LOCK_GRANULARITY; i++)
{
pthread_mutex_lock( sctx->cov_locks + i );
}
// pthread_mutex_lock(cov_lock);
{
track_anno* t_anno = sctx->t_anno;
track_data* t_data = sctx->t_data;
printf("REPORT");
if (fileOut)
{
printf(" (dumping intervals to %s)", path_report);
}
printf("\n");
for (i = 0; i < nreads; i++)
{
track_anno ob = t_anno[i];
track_anno oe = t_anno[i+1];
if (ob >= oe)
{
continue;
}
ob /= sizeof(track_data);
oe /= sizeof(track_data);
reads_with_intervals++;
while (ob < oe)
{
track_data db = t_data[ ob++ ];
track_data de = t_data[ ob++ ];
bases_masked += de - db;
if (sctx->report_intervals)
{
if (fileOut)
{
fprintf(fileOut, "%llu %d %d\n", i, db, de);
}
}
}
}
}
// pthread_mutex_unlock(cov_lock);
for (i = 0; i < COV_LOCK_GRANULARITY; i++)
{
pthread_mutex_unlock( sctx->cov_locks + i );
}
if (sctx->report_intervals)
{
sctx->report_intervals = 0;
if (fileOut)
{
fclose(fileOut);
fileOut = NULL;
}
}
printf(" reads %'12d bases %'18llu\n",
sctx->db->nreads, sctx->bases);
printf(" annotated %'12llu masked %'18llu (%2d%%)\n",
reads_with_intervals, bases_masked, (int)(100.0 * bases_masked / sctx->bases));
}
free(path_report);
return NULL;
}
static void ctx_init(ServerContext* ctx, HITS_DB* db, HITS_TRACK* mask)
{
ctx->shutdown = 0;
ctx->checkpoint_suffix = 0;
ctx->report_intervals = 0;
ctx->lock = 0;
ctx->t_anno = (track_anno*)malloc(sizeof(track_anno) * (db->nreads + 1));
ctx->t_dmax = db->nreads * 2;
ctx->t_data = (track_data*)malloc(sizeof(track_data) * ctx->t_dmax);
bzero(ctx->t_anno, sizeof(track_anno) * (db->nreads + 1));
ctx->dmax = 10 * 1024;
ctx->data = malloc( ctx->dmax );
ctx->db = db;
ctx->queue_start = NULL;
ctx->queue_end = NULL;
ctx->queue_len = 0;
ctx->path_sem_fill_count = malloc( sizeof(SEMAPHORE_FILL_COUNT_PREFIX) + 20 );
sprintf(ctx->path_sem_fill_count, "%s.%d", SEMAPHORE_FILL_COUNT_PREFIX, getpid());
sem_unlink(ctx->path_sem_fill_count);
ctx->queue_fill_count = sem_open(ctx->path_sem_fill_count, O_CREAT, 0666, 0);
if (ctx->queue_fill_count == SEM_FAILED)
{
perror("sem_open");
exit(1);
}
pthread_mutex_init(&(ctx->t_lock), NULL);
pthread_mutex_init(&(ctx->queue_lock), NULL);
ctx->cov = malloc( sizeof(ReadCoverage) * db->nreads );
bzero(ctx->cov, sizeof(ReadCoverage) * db->nreads);
// pthread_mutex_init(&(ctx->cov_lock), NULL);
int i;
for (i = 0; i < COV_LOCK_GRANULARITY; i++)
{
pthread_mutex_init( ctx->cov_locks + i, NULL );
}
FILE* fileIn;
if (ctx->checkpoint && (fileIn = fopen(ctx->checkpoint, "r")))
{
printf("initialising from checkpoint\n");
checkpoint_read(ctx, fileIn);
fclose(fileIn);
}
else if (mask)
{
printf("initialising from mask track\n");
int i;
uint64 b, e, alen;
track_data* data = mask->data;
track_anno* anno = mask->anno;
unsigned char* read_cov = malloc( DB_READ_MAXLEN(db) );
for (i = 0; i < db->nreads; i++)
{
b = anno[i] / sizeof(track_data);
e = anno[i+1] / sizeof(track_data);
if (b >= e)
{
continue;
}
// TODO ... rewrite, no need for read_cov
alen = DB_READ_LEN(db, i);
bzero(read_cov, alen);
while (b < e)
{
int dust_beg = data[b];
int dust_end = data[b+1];
memset(read_cov + dust_beg, MAX_COV, dust_end - dust_beg);
/*
while (dust_beg < dust_end)
{
read_cov[ dust_beg ] = MAX_COV;
dust_beg++;
}
*/
b += 2;
}
rle_pack(read_cov, alen, &(ctx->cov[i].data), &(ctx->cov[i].dmax));
}
ctx->cov_changed = 1;
free(read_cov);
}
else
{
printf("no dust track or checkpoint for initialisation\n");
unsigned char* read_cov = malloc( DB_READ_MAXLEN(db) );
bzero(read_cov, DB_READ_MAXLEN(db));
int i;
for (i = 0; i < db->nreads; i++)
{
int alen = DB_READ_LEN(db, i);
rle_pack(read_cov, alen, &(ctx->cov[i].data), &(ctx->cov[i].dmax));
}
ctx->cov_changed = 1;
free(read_cov);
}
update_track(ctx);
HITS_READ* reads = ctx->db->reads;
int64 bases = 0;
for (i = 0; i < ctx->db->nreads; i++)
{
bases += reads[i].rlen;
}
ctx->bases = bases;
}
static void ctx_free(ServerContext* ctx)
{
free(ctx->t_anno);
free(ctx->t_data);
sem_close(ctx->queue_fill_count);
sem_unlink(ctx->path_sem_fill_count);
free(ctx->path_sem_fill_count);
pthread_mutex_destroy( &(ctx->t_lock) );
pthread_mutex_destroy( &(ctx->queue_lock) );
// pthread_mutex_destroy( &(ctx->cov_lock) );
int i;
for (i = 0; i < COV_LOCK_GRANULARITY; i++)
{
pthread_mutex_destroy( ctx->cov_locks + i );
}
for (i = 0; i < ctx->db->nreads; i++)
{
if (ctx->cov[i].data)
{
free(ctx->cov[i].data);
}
}
free(ctx->cov);
free(ctx->data);
}
static void sigint_handler(int sig, siginfo_t *si, void *unused)
{
printf("SIGINT received ... shutting down\n");
// silence unused variable warnings
UNUSED(sig);
UNUSED(si);
UNUSED(unused);
pthread_cancel(g_sctx->thread_socket_listener);
shutdown_server(g_sctx);
}
static void usage()
{
printf("usage: [-cd] [-t <threads>] [-p <port>] [-c <minutes>] [-r <minutes>] [-u <minutes>] <db> <expected.coverage> [checkpoint.file]\n");
printf(" -t ... worker threads (%d)\n", DEF_ARG_T);
printf(" -p ... listen port (%d)\n", DEF_ARG_P);
printf(" -c ... minutes between checkpoints (%d)\n", DEF_ARG_C);
printf(" -r ... minutes between reports (%d)\n", DEF_ARG_R);
printf(" -u ... minutes between track updates (%d)\n", DEF_ARG_U);
printf(" -d ... don't initialize from dust track\n");
printf(" -e ... (EXPERIMENTAL) no repeat masking <int> bases from the read ends. -1 to disable repeat masking altogether (%d)\n", DEF_ARG_E);
printf(" -C ... (EXPERIMENTAL) mask contained reads completely (%d)\n", DEF_ARG_CC);
}
uint32 ilog2(uint32 x)
{
uint32 shift = 0;
while ( x )
{
x >>= 1;
shift += 1;
}
return shift;
}
int main(int argc, char* argv[])
{
HITS_DB db;
HITS_TRACK* dust;
ServerContext ctx;
int i;
int init_dust = 1;
pthread_t* socket_listener = &(ctx.thread_socket_listener);
pthread_t* reporter = &(ctx.thread_reporter);
pthread_t* track = &(ctx.thread_track);
pthread_t* checkpoint = &(ctx.thread_checkpoint);
pthread_t* worker;
WorkerContext* wctx;
// use the environments locale
setlocale(LC_ALL, "");
// global pointer to the ServerContext, only used by the signal handlers
// which otherwise wouldn't have access to it
g_sctx = &ctx;
// process arguments
ctx.port = DEF_ARG_P;
ctx.worker_threads = DEF_ARG_T;
ctx.checkpoint = NULL;
ctx.checkpoint_wait = DEF_ARG_C;
ctx.report_wait = DEF_ARG_R;
ctx.track_update_wait = DEF_ARG_U;
ctx.mask_contained = DEF_ARG_CC;
ctx.keep_ends = DEF_ARG_E;
int c;
opterr = 0;
while ((c = getopt(argc, argv, "Cde:u:r:t:p:c:")) != -1)
{
switch (c)
{
case 'e':
ctx.keep_ends = atoi(optarg);
break;
case 'C':
ctx.mask_contained = 1;
break;
case 'd':
init_dust = 0;
break;
case 'c':
ctx.checkpoint_wait = atoi(optarg);
break;
case 'r':
ctx.report_wait = atoi(optarg);
break;
case 'u':
ctx.track_update_wait = atoi(optarg);
break;
case 'p':
ctx.port = atoi(optarg);
break;
case 't':
ctx.worker_threads = atoi(optarg);
break;
default:
usage();
exit(1);
}
}
if (opterr || argc - optind < 2)
{
usage();
exit(1);
}
char* pathDb = argv[optind++];
ctx.cov_expected = atoi(argv[optind++]);
if (argc - optind == 1)
{
printf("checkpointing enabled\n");
ctx.checkpoint = argv[optind++];
}
if (ctx.checkpoint_wait < 1)
{
fprintf(stderr, "checkpoint interval is too low\n");
exit(1);
}
if (ctx.report_wait < 1)
{
fprintf(stderr, "report interval is too low\n");
exit(1);
}
if (ctx.track_update_wait < 1)
{
fprintf(stderr, "track update interval is too low\n");
exit(1);
}
if (ctx.worker_threads < 1)
{
fprintf(stderr, "number of workers threads must be greater than zero\n");
exit(1);
}
if ( ctx.port == 0 )
{
fprintf(stderr, "invalid listen port %d\n", ctx.port);
exit(1);
}
if (ctx.cov_expected < 1 || ctx.cov_expected > MAX_COV)
{
fprintf(stderr, "expected coverage outside valid internval [1..%d]\n", MAX_COV);
exit(1);
}
// initialise
// catch ctrl+c
struct sigaction sa;
sa.sa_flags = SA_SIGINFO;
sigemptyset(&sa.sa_mask);
sa.sa_sigaction = sigint_handler;
if (sigaction(SIGINT, &sa, NULL) == -1)
{
fprintf(stderr, "failed to register SIGINT handler\n");
}
if (Open_DB(pathDb, &db))
{
fprintf(stderr, "could not open db %s\n", pathDb);
exit(1);
}
// lock mask & shift
uint32 n_shift = ilog2(db.nreads);
uint32 g_shift = ilog2(COV_LOCK_GRANULARITY - 1);
ctx.lock_shift = n_shift - g_shift;
ctx.lock_mask = (COV_LOCK_GRANULARITY - 1) << ctx.lock_shift;
// reset db flags
for (i = 0; i < db.nreads; i++)
{
db.reads[i].flags = 0;
}
worker = (pthread_t*)malloc( sizeof(pthread_t) * ctx.worker_threads );
wctx = (WorkerContext*)malloc( sizeof(WorkerContext) * ctx.worker_threads );
printf("db opened\n");
if (init_dust)
{
dust = track_load(&db, TRACK_DUST);
printf("dust track loaded\n");
}
else
{
dust = NULL;
}
ctx_init(&ctx, &db, dust);
if (dust)
{
Close_Track(&db, TRACK_DUST);
}
printf("initialised\n");
// debug_add_las(&ctx);
// start threads
pthread_create(socket_listener, NULL, socket_listener_thread, &ctx);
pthread_create(reporter, NULL, reporter_thread, &ctx);
pthread_create(track, NULL, update_track_thread, &ctx);
if (ctx.checkpoint)
{
pthread_create(checkpoint, NULL, checkpoint_thread, &ctx);
}
for (i = 0; i < ctx.worker_threads; i++)
{
worker_ctx_init(&ctx, wctx + i);
wctx[i].id = i;
pthread_create(worker + i, NULL, worker_thread, wctx + i);
}
// wait for threads
pthread_join(*socket_listener, NULL);
pthread_join(*reporter, NULL);
pthread_join(*track, NULL);
for (i = 0; i < ctx.worker_threads; i++)
{
pthread_join(worker[i], NULL);
}
for (i = 0; i < ctx.worker_threads; i++)
{
worker_ctx_free(wctx+i);
}
// clean up
update_track(&ctx);
write_mask_tracks(&ctx);
ctx_free(&ctx);
Close_DB(&db);
free(worker);
free(wctx);
return 0;
}
|
MartinPippel/DAmar
|
corrector/LAconvert.c
|
<filename>corrector/LAconvert.c
/*******************************************************************************************
*
* conversion from unccorected db to corrected db and las
*
* Author: <NAME>
*
* Date : March 2017
*
*******************************************************************************************/
#include <assert.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "dalign/align.h"
#include "db/DB.h"
#include "lib/oflags.h"
#include "lib/pass.h"
#include "lib/tracks.h"
// command line defaults
#define DEF_ARG_T TRACK_TRIM
#define DEF_ARG_TT TRACK_TRIM
// switches
#undef DEBUG
// structs
typedef struct
{
HITS_DB* db_u;
HITS_DB* db_c;
// uncorrected tracks
HITS_TRACK* trim;
HITS_TRACK* postrace;
HITS_TRACK* source;
track_anno* trim_a_c;
track_data* trim_d_c;
int* amap;
int* bmap;
char* nameTrim_c;
int tbytes;
ovl_header_twidth twidth;
int* riduc_to_ridc;
FILE* fileLas_c;
} ConvertContext;
static void trace_to_posmap( int32_t* trace, int tlen, int alen, int* posmap )
{
int t, a, ac, p;
a = ac = 0;
for ( t = 0; t < tlen; t++ )
{
p = trace[ t ];
if ( p < 0 )
{
p = -p - 1;
while ( a < p )
{
posmap[ a ] = ac;
a += 1;
ac += 1;
}
ac += 1;
}
else
{
p--;
while ( ac < p )
{
posmap[ a ] = ac;
a += 1;
ac += 1;
}
posmap[ a ] = -1;
a += 1;
}
}
p = alen;
while ( a < p )
{
posmap[ a ] = ac;
a += 1;
ac += 1;
}
}
static void convert_pre( PassContext* pctx, ConvertContext* cctx )
{
ovl_header_write( cctx->fileLas_c, pctx->novl, pctx->twidth );
cctx->tbytes = pctx->tbytes;
cctx->amap = malloc( sizeof( int ) * cctx->db_u->maxlen );
cctx->bmap = malloc( sizeof( int ) * cctx->db_u->maxlen );
// mapping of uncorrected read ids to corrected rids
cctx->riduc_to_ridc = malloc( sizeof( int ) * cctx->db_u->nreads );
int i;
for ( i = 0; i < cctx->db_u->nreads; i++ )
{
cctx->riduc_to_ridc[ i ] = -1;
}
track_data* data_src = cctx->source->data;
track_anno* anno_src = cctx->source->anno;
for ( i = 0; i < cctx->db_c->nreads; i++ )
{
track_anno b = anno_src[ i ] / sizeof( track_data );
track_anno e = anno_src[ i + 1 ] / sizeof( track_data );
assert( b < e );
assert( cctx->riduc_to_ridc[ data_src[ b ] ] == -1 );
cctx->riduc_to_ridc[ data_src[ b ] ] = i;
}
// convert trim track
track_data* data_trim_u = cctx->trim->data;
track_anno* anno_trim_u = cctx->trim->anno;
track_anno* anno_trim_c = cctx->trim_a_c = calloc( cctx->db_c->nreads + 1, sizeof( track_anno ) );
track_data* data_trim_c = cctx->trim_d_c = calloc( cctx->db_c->nreads * 2, sizeof( track_data ) );
track_anno* anno_pos_c = cctx->postrace->anno;
track_data* data_pos_c = cctx->postrace->data;
int* amap = cctx->amap;
track_anno dcur = 0;
assert( cctx->db_c->nreads == cctx->db_u->nreads );
for ( i = 0; i < cctx->db_c->nreads; i++ )
{
// source read id
track_anno b = anno_src[ i ] / sizeof( track_data );
track_anno e = anno_src[ i + 1 ] / sizeof( track_data );
assert( b < e );
int rid_u = data_src[ b ];
// trim data of source read
b = anno_trim_u[ rid_u ] / sizeof( track_data );
e = anno_trim_u[ rid_u + 1 ] / sizeof( track_data );
if ( b == e )
{
continue;
}
assert( b + 2 == e );
track_data tb = data_trim_u[ b ];
track_data te = data_trim_u[ b + 1 ];
track_data tb_c = -1;
track_data te_c = -1;
if ( tb == te )
{
tb_c = 0;
te_c = 0;
}
else
{
// create position mapping
track_anno ab = anno_pos_c[ i ] / sizeof( track_data );
track_anno ae = anno_pos_c[ i + 1 ] / sizeof( track_data );
trace_to_posmap( (int32_t*)( data_pos_c + ab ), ae - ab, DB_READ_LEN( cctx->db_u, rid_u ), amap );
// convert trim interval
while ( ( tb_c = amap[ tb ] ) == -1 )
{
tb++;
}
te--;
while ( ( te_c = amap[ te ] ) == -1 )
{
te--;
}
te_c++;
}
// printf("mapping %5d..%5d -> %5d..%5d\n", data[b], data[b+1], tb_c, te_c);
data_trim_c[ dcur++ ] = tb_c;
data_trim_c[ dcur++ ] = te_c;
anno_trim_c[ i ] += 2 * sizeof( track_data );
}
track_anno qoff, coff;
qoff = 0;
for ( i = 0; i <= cctx->db_c->nreads; i++ )
{
coff = anno_trim_c[ i ];
anno_trim_c[ i ] = qoff;
qoff += coff;
}
}
static void convert_post( ConvertContext* cctx )
{
int nreads = cctx->db_c->nreads;
track_write( cctx->db_c, cctx->nameTrim_c, 0, cctx->trim_a_c, cctx->trim_d_c, cctx->trim_a_c[ nreads ] / sizeof( track_data ) );
free( cctx->amap );
free( cctx->bmap );
free( cctx->riduc_to_ridc );
free( cctx->trim_a_c );
free( cctx->trim_d_c );
}
static int convert_process( void* _ctx, Overlap* ovl, int novl )
{
ConvertContext* ctx = (ConvertContext*)_ctx;
FILE* fileLas_c = ctx->fileLas_c;
int tbytes = ctx->tbytes;
int a_u = ovl->aread;
int a_c = ctx->riduc_to_ridc[ a_u ];
if ( a_c == -1 )
{
fprintf( stderr, "could not map source read %d to corrected read\n", a_u );
exit( 1 );
}
#ifdef DEBUG
printf( "u %5d -> c %5d\n", a_u, a_c );
#endif
track_anno* anno = ctx->postrace->anno;
track_data* data = ctx->postrace->data;
track_anno ab = anno[ a_c ] / sizeof( track_data );
track_anno ae = anno[ a_c + 1 ] / sizeof( track_data );
int* amap = ctx->amap;
int* bmap = ctx->bmap;
trace_to_posmap( (int32_t*)( data + ab ), ae - ab, DB_READ_LEN( ctx->db_u, a_u ), amap );
int i;
for ( i = 0; i < novl; i++ )
{
Overlap* o = ovl + i;
if ( o->flags & OVL_DISCARD )
{
continue;
}
#ifdef DEBUG
printf( "%7d x %7d | %5d..%5d %5d -> %5d..%5d %5d\n",
a_u, o->bread,
o->path.abpos, o->path.aepos, DB_READ_LEN( ctx->db_u, a_u ),
o->path.bbpos, o->path.bepos, DB_READ_LEN( ctx->db_u, o->bread ) );
#endif
o->path.tlen = 0;
int b_u = o->bread;
int b_c = ctx->riduc_to_ridc[ b_u ];
if ( b_c == -1 )
{
fprintf( stderr, "could not map source read %d to corrected read\n", b_u );
exit( 1 );
}
track_anno tbb = anno[ b_c ] / sizeof( track_data );
track_anno tbe = anno[ b_c + 1 ] / sizeof( track_data );
trace_to_posmap( (int32_t*)( data + tbb ), tbe - tbb, DB_READ_LEN( ctx->db_u, b_u ), bmap );
int ab_u = o->path.abpos;
int ae_u = o->path.aepos - 1;
int ab_c = -1;
int ae_c = -1;
while ( ( ab_c = amap[ ab_u ] ) == -1 )
{
ab_u++;
}
while ( ( ae_c = amap[ ae_u ] ) == -1 )
{
ae_u--;
}
ae_c++;
o->path.abpos = ab_c;
o->path.aepos = ae_c;
#ifdef DEBUG
printf( "%7d | %5d..%5d %5d\n",
a_c,
ab_c, ae_c, DB_READ_LEN( ctx->db_c, a_c ) );
#endif
assert( 0 <= ab_c && ab_c < ae_c && ae_c <= DB_READ_LEN( ctx->db_c, a_c ) );
int bb_u;
int be_u;
int bb_c = -1;
int be_c = -1;
if ( o->flags & OVL_COMP )
{
int blen_u = DB_READ_LEN( ctx->db_u, b_u );
bb_u = blen_u - o->path.bepos;
be_u = blen_u - o->path.bbpos - 1;
}
else
{
bb_u = o->path.bbpos;
be_u = o->path.bepos - 1;
}
while ( ( bb_c = bmap[ bb_u ] ) == -1 )
{
bb_u++;
}
while ( ( be_c = bmap[ be_u ] ) == -1 )
{
be_u--;
}
if ( o->flags & OVL_COMP )
{
int blen_c = DB_READ_LEN( ctx->db_c, b_c );
o->path.bbpos = blen_c - be_c - 1;
o->path.bepos = blen_c - bb_c;
#ifdef DEBUG
printf( "%7d < %5d..%5d (%5d..%5d) %5d\n",
b_c,
o->path.bbpos, o->path.bepos, bb_c, be_c, DB_READ_LEN( ctx->db_c, b_c ) );
#endif
}
else
{
o->path.bbpos = bb_c;
o->path.bepos = be_c + 1;
#ifdef DEBUG
printf( "%7d > %5d..%5d %5d\n",
b_c,
o->path.bbpos, o->path.bepos, DB_READ_LEN( ctx->db_c, b_c ) );
#endif
}
o->aread = a_c;
o->bread = b_c;
assert( 0 <= o->path.bbpos && o->path.bbpos < o->path.bepos && o->path.bepos <= DB_READ_LEN( ctx->db_c, b_c ) );
Write_Overlap( fileLas_c, o, tbytes );
}
return 1;
}
static void usage()
{
fprintf( stderr, "usage : [-tT <track>] <uncorrected.db> <uncorrected.las> <corrected.db> <corrected.las>\n" );
fprintf( stderr, "options: -t ... uncorrected db trim track (%s)\n", DEF_ARG_T );
fprintf( stderr, " -T ... corrected db trim track (%s)\n", DEF_ARG_TT );
}
int main( int argc, char* argv[] )
{
PassContext* pctx;
ConvertContext cctx;
HITS_DB db_u, db_c;
FILE* fileLas_u;
bzero( &cctx, sizeof( ConvertContext ) );
cctx.db_u = &db_u;
cctx.db_c = &db_c;
// process arguments
char* trim_u = DEF_ARG_T;
cctx.nameTrim_c = DEF_ARG_TT;
int c;
opterr = 0;
while ( ( c = getopt( argc, argv, "t:T:" ) ) != -1 )
{
switch ( c )
{
case 't':
trim_u = optarg;
break;
case 'T':
cctx.nameTrim_c = optarg;
break;
default:
usage();
exit( 1 );
}
}
if ( opterr || argc - optind != 4 )
{
usage();
exit( 1 );
}
char* pathdb_u = argv[ optind++ ];
char* pathlas_u = argv[ optind++ ];
char* pathdb_c = argv[ optind++ ];
char* pathlas_c = argv[ optind++ ];
if ( ( fileLas_u = fopen( pathlas_u, "r" ) ) == NULL )
{
fprintf( stderr, "could not open '%s'\n", pathlas_u );
exit( 1 );
}
if ( ( cctx.fileLas_c = fopen( pathlas_c, "w" ) ) == NULL )
{
fprintf( stderr, "could not open '%s'\n", pathlas_c );
exit( 1 );
}
if ( Open_DB( pathdb_u, &db_u ) )
{
fprintf( stderr, "could not open database '%s'\n", pathdb_u );
exit( 1 );
}
if ( Open_DB( pathdb_c, &db_c ) )
{
fprintf( stderr, "could not open database '%s'\n", pathdb_c );
exit( 1 );
}
if ( !( cctx.trim = track_load( &db_u, trim_u ) ) )
{
fprintf( stderr, "failed load track %s", trim_u );
}
if ( !( cctx.postrace = track_load( &db_c, "postrace" ) ) )
{
fprintf( stderr, "failed load track %s", "postrace" );
}
if ( !( cctx.source = track_load( &db_c, "source" ) ) )
{
fprintf( stderr, "failed load track %s", "source" );
}
pctx = pass_init( fileLas_u, NULL );
pctx->split_b = 0;
pctx->load_trace = 0;
pctx->data = &cctx;
convert_pre( pctx, &cctx );
pass( pctx, convert_process );
convert_post( &cctx );
pass_free( pctx );
Close_DB( &db_u );
Close_DB( &db_c );
fclose( fileLas_u );
fclose( cctx.fileLas_c );
return 0;
}
|
MartinPippel/DAmar
|
scrub/LAq.c
|
/*******************************************************************************************
*
* calculate the quality and trim track
*
* Date : October 2015
*
* Author : <NAME>
*
*******************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <assert.h>
#include <math.h>
#include <sys/param.h>
#include <unistd.h>
#include "lib/oflags.h"
#include "lib/colors.h"
#include "lib/stats.h"
#include "lib/tracks.h"
#include "lib/pass.h"
#include "lib/utils.h"
#include "db/DB.h"
#include "dalign/align.h"
// toggles
#define VERBOSE
#undef DEBUG_Q
#define TRIM_WINDOW 5
// command line defaults
#define DEF_ARG_B 0
#define DEF_ARG_U 0
#define DEF_ARG_O 1000
#define DEF_ARG_D 25
#define DEF_ARG_S 1
#define DEF_ARG_SS 20
#define DEF_ARG_T TRACK_TRIM
#define DEF_ARG_Q TRACK_Q
// structs
typedef struct
{
HITS_DB* db;
int tblock; // db block
int min_trimmed_len; // min length of read after trimming
int twidth; // trace point spacing
unsigned int segmin; // min number of segments for q estimate
unsigned int segmax;
uint32* q_histo;
size_t q_histo_len;
track_anno* q_anno;
track_data* q_data;
int q_dprev, q_dcur, q_dmax;
// re-annotate only
HITS_TRACK* q_track; // q track
HITS_TRACK* trim_track; // trim track
int trim_q; // trimming quality cutoff
char *track_trim_in;
char *track_trim_out;
char *track_q_in;
char *track_q_out;
track_anno* trim_anno;
track_data* trim_data;
track_anno tcur;
int CCS_READ;
} AnnotateContext;
// for getopt()
extern char* optarg;
extern int optind, opterr, optopt;
static int trim_q_offsets(AnnotateContext* actx, int rid, int rlen, track_data* dataq, track_anno* annoq, int* trim_b, int* trim_e)
{
int min_trimmed_len = actx->min_trimmed_len;
int twidth = actx->twidth;
int left = (*trim_b) ? (*trim_b) / twidth : 0;
int right = (*trim_e) ? (*trim_e) / twidth : ( rlen + twidth - 1 ) / twidth;
track_anno ob = annoq[rid] / sizeof(track_data);
track_anno oe = annoq[rid + 1] / sizeof(track_data);
int trim_q = actx->trim_q;
if (ob >= oe)
{
*trim_b = *trim_e = 0;
return 0;
}
#ifdef DEBUG_Q
{
track_anno k;
printf("Q");
for (k = ob; k < oe; k++)
{
if (dataq[k] == 0 || dataq[k] > trim_q)
{
printf(ANSI_COLOR_RED " %2d" ANSI_COLOR_RESET, dataq[k]);
}
else
{
printf(" %2d", dataq[k]);
}
}
printf("\n");
}
#endif
ob += left;
oe -= ( rlen + twidth - 1 ) / twidth - right;
track_anno wnd_left;
int sum = 0;
for (wnd_left = ob ; wnd_left - ob <= TRIM_WINDOW && ob < oe ; wnd_left++)
{
track_data q = dataq[wnd_left];
if (q >= trim_q || (!actx->CCS_READ && q == 0))
{
// printf("reset left\n");
ob = wnd_left + 1;
sum = 0;
continue;
}
if (wnd_left - ob == TRIM_WINDOW && sum / TRIM_WINDOW >= trim_q)
{
// printf("move left %d\n", sum / TRIM_WINDOW);
sum -= dataq[ob];
ob++;
}
sum += q;
}
track_anno wnd_right;
sum = 0;
for (wnd_right = oe ; oe - wnd_right <= TRIM_WINDOW && ob < oe ; wnd_right--)
{
track_data q = dataq[wnd_right - 1];
if (q >= trim_q || (!actx->CCS_READ && q == 0))
{
// printf("reset right q %d oe %llu wnd_right %llu\n", q, oe, wnd_right);
oe = wnd_right - 1;
sum = 0;
continue;
}
if (oe - wnd_right == TRIM_WINDOW && sum / TRIM_WINDOW >= trim_q)
{
// printf("move right %d\n", sum / TRIM_WINDOW);
sum -= dataq[oe];
oe--;
}
sum += q;
}
int tb = MIN( rlen, ((int) (ob - annoq[rid] / sizeof(track_data))) * twidth );
int te = MIN( rlen, ((int) (oe - annoq[rid] / sizeof(track_data))) * twidth );
if (te - tb < min_trimmed_len)
{
tb = te = 0;
}
*trim_b = tb;
*trim_e = te;
return 1;
}
static void calculate_trim(AnnotateContext* actx)
{
int dcur = 0;
int dmax = 1000;
track_data* data = (track_data*)malloc( sizeof(track_data) * dmax );
track_anno* anno = (track_anno*)malloc( sizeof(track_anno) * (DB_NREADS(actx->db) + 1) );
bzero(anno, sizeof(track_anno) * (DB_NREADS(actx->db) + 1));
track_data* dataq = actx->q_data;
track_anno* annoq = actx->q_anno;
int a;
for (a = 0; a < actx->db->nreads; a++)
{
int alen = DB_READ_LEN(actx->db, a);
int tb = 0;
int te = 0;
if (trim_q_offsets(actx, a, alen, dataq, annoq, &tb, &te) )
{
// assert(dbg_tb == data[dcur-2] && dbg_te == data[dcur-1]);
if (dcur + 2 >= dmax)
{
dmax = dmax * 1.2 + 1000;
data = (track_data*)realloc(data, sizeof(track_data) * dmax);
}
data[dcur++] = tb;
data[dcur++] = te;
anno[ a ] += 2 * sizeof(track_data);
#ifdef DEBUG_Q
printf("trimming %6d (%5d) to %5d..%5d\n",
a, alen,
tb, te);
#endif
}
}
track_anno off = 0;
track_anno coff;
int j;
for (j = 0; j <= DB_NREADS(actx->db); j++)
{
coff = anno[j];
anno[j] = off;
off += coff;
}
track_write(actx->db, actx->track_trim_out, actx->tblock, anno, data, dcur);
free(data);
free(anno);
}
static void pre_annotate(PassContext* pctx, AnnotateContext* ctx)
{
#ifdef VERBOSE
printf(ANSI_COLOR_GREEN "PASS quality estimate and trimming" ANSI_COLOR_RESET "\n");
#endif
ctx->twidth = pctx->twidth;
ctx->q_anno = (track_anno*)malloc(sizeof(track_anno)*(DB_NREADS(ctx->db)+1));
bzero(ctx->q_anno, sizeof(track_anno)*(DB_NREADS(ctx->db)+1));
ctx->q_dmax = DB_NREADS(ctx->db);
ctx->q_dcur = ctx->q_dprev = 0;
ctx->q_data = (track_data*)malloc(sizeof(track_data)*ctx->q_dmax);
int maxtiles = (DB_READ_MAXLEN(ctx->db) + ctx->twidth - 1) / ctx->twidth;
ctx->q_histo_len = ctx->twidth * 2 * maxtiles;
ctx->q_histo = malloc( sizeof(uint32) * ctx->q_histo_len );
}
static void post_annotate(AnnotateContext* ctx)
{
int j;
track_anno qoff, coff;
qoff = 0;
for (j = 0; j <= DB_NREADS(ctx->db); j++)
{
coff = ctx->q_anno[j];
ctx->q_anno[j] = qoff;
qoff += coff;
}
assert( qoff / sizeof(track_data) == (uint64_t)ctx->q_dcur );
calculate_trim(ctx);
track_write(ctx->db, ctx->track_q_out, ctx->tblock, ctx->q_anno, ctx->q_data, ctx->q_dcur);
free(ctx->q_anno);
free(ctx->q_data);
free(ctx->q_histo);
}
static int handler_annotate(void* _ctx, Overlap* ovls, int novl)
{
AnnotateContext* ctx = (AnnotateContext*)_ctx;
unsigned int segmin = ctx->segmin;
unsigned int segmax = ctx->segmax;
int a = ovls->aread;
int alen = DB_READ_LEN(ctx->db, a);
int ntiles = (alen + ctx->twidth - 1) / ctx->twidth;
bzero(ctx->q_histo, ctx->q_histo_len * sizeof(uint32));
int i;
for (i = 0; i < novl; i++)
{
Overlap* ovl = ovls + i;
if ( ovl->aread == ovl->bread )
{
continue;
}
int comp = (ovl->flags & OVL_COMP) ? 1 : 0;
int tile = ovl->path.abpos / ctx->twidth;
ovl_trace* trace = ovl->path.trace;
if ( (ovl->path.abpos % ctx->twidth) == 0 )
{
int q = trace[0];
ctx->q_histo[ ctx->twidth * 2 * tile + 2 * q + comp] += 1;
}
tile++;
int t;
for (t = 2; t < ovls[i].path.tlen - 2; t+=2)
{
int q = trace[t];
ctx->q_histo[ ctx->twidth * 2 * tile + 2 * q + comp] += 1;
tile += 1;
}
if ( (ovl->path.aepos % ctx->twidth) == 0 || ovl->path.aepos == alen )
{
int q = trace[t];
ctx->q_histo[ ctx->twidth * 2 * tile + 2 * q + comp] += 1;
}
}
// estimate mean q
if (ctx->q_dcur + ntiles >= ctx->q_dmax)
{
ctx->q_dmax = ctx->q_dmax * 1.2 + ntiles;
ctx->q_data = realloc(ctx->q_data, sizeof(track_data) * ctx->q_dmax);
}
for (i = 0; i < ntiles; i++)
{
uint32* tile_qhisto = ctx->q_histo + 2 * ctx->twidth * i;
uint32 sum = 0;
uint32 count = 0;
int q;
for ( q = 0 ; q < ctx->twidth && count != segmax ; q++ )
{
uint32 has = MIN(tile_qhisto[2 * q] + tile_qhisto[2 * q + 1], segmax - count);
count += has;
sum += has * q;
}
if (count < segmin)
{
if (ctx->CCS_READ)
q = 25; // set to a very high value
else
q = 0;
}
else
{
if (sum == 0)
{
sum = count;
}
q = (int)( ((float)sum)/count + 0.5 );
}
ctx->q_data[ ctx->q_dcur++ ] = q;
ctx->q_anno[ a ] += 1 * sizeof(track_data);
}
return 1;
}
static void pre_update_anno(PassContext* pctx, AnnotateContext* actx)
{
#ifdef VERBOSE
printf(ANSI_COLOR_GREEN "PASS update quality estimate and trimming" ANSI_COLOR_RESET "\n");
#endif
actx->q_track = track_load(actx->db, actx->track_q_in);
if (!actx->q_track)
{
fprintf(stderr, "could not open %s track\n", actx->track_q_in);
exit(1);
}
actx->trim_track = track_load(actx->db, actx->track_trim_in);
if (!actx->trim_track)
{
fprintf(stderr, "could not open %s track\n", actx->track_trim_in);
exit(1);
}
int nreads = DB_NREADS(actx->db);
actx->twidth = pctx->twidth;
actx->trim_anno = (track_anno*)malloc(sizeof(track_anno) * (nreads + 1));
actx->trim_data = (track_data*)malloc( ((track_anno*)actx->trim_track->anno)[ nreads ] );
actx->tcur = 0;
bzero(actx->trim_anno, sizeof(track_anno) * (nreads + 1));
}
static void post_update_anno(AnnotateContext* actx)
{
int j;
track_anno qoff, coff;
qoff = 0;
for (j = 0; j <= DB_NREADS(actx->db); j++)
{
coff = actx->trim_anno[j];
actx->trim_anno[j] = qoff;
qoff += coff;
}
track_write(actx->db, actx->track_trim_out, actx->tblock, actx->trim_anno, actx->trim_data, actx->tcur);
free(actx->trim_anno);
free(actx->trim_data);
}
static int handler_update_anno(void* _ctx, Overlap* ovls, int novl)
{
AnnotateContext* actx = _ctx;
track_anno* trim_anno = actx->trim_anno;
track_data* trim_data = actx->trim_data;
int a = ovls->aread;
track_anno* annoq = actx->q_track->anno;
track_data* dataq = actx->q_track->data;
int ab_min = INT_MAX;
int ae_max = 0;
int i;
for (i = 0; i < novl; i++)
{
if (ovls[i].flags & OVL_DISCARD)
{
continue;
}
if (ovls[i].aread == ovls[i].bread)
{
continue;
}
ab_min = MIN(ab_min, ovls[i].path.abpos);
ae_max = MAX(ae_max, ovls[i].path.aepos);
}
track_anno ob = ((track_anno*)actx->trim_track->anno)[a] / sizeof(track_data);
track_anno oe = ((track_anno*)actx->trim_track->anno)[a + 1] / sizeof(track_data);
assert( ob + 2 == oe );
int tb, te, tb_new, te_new;
tb_new = tb = ((track_data*)actx->trim_track->data)[ob];
te_new = te = ((track_data*)actx->trim_track->data)[ob + 1];
// tighten trim
if (tb < ab_min || te > ae_max)
{
int alen = DB_READ_LEN(actx->db, ovls->aread);
#ifdef DEBUG_Q
printf("READ %6d (%5d) ... CURRENT %5d..%5d ... NEW %5d..%5d\n", a, alen, tb, te, ab_min, ae_max);
#endif
if (ab_min == INT_MAX)
{
tb_new = te_new = 0;
}
else
{
tb_new = ab_min + actx->twidth - 1;
te_new = ae_max; // - actx->twidth + 1;
trim_q_offsets(actx, a, alen, dataq, annoq, &tb_new, &te_new);
/*
if (ae_max == alen)
{
te_new = alen;
}
*/
}
#ifdef DEBUG_Q
printf(" ... UPDATED %5d..%5d\n\n", tb_new, te_new);
#endif
}
trim_data[ actx->tcur++ ] = tb_new;
trim_data[ actx->tcur++ ] = te_new;
trim_anno[ a ] += 2 * sizeof(track_data);
return 1;
}
static void usage()
{
fprintf(stderr, "[-uc] [-mbdsS <int>] [-L <file>] [-tT <track>] <db> <overlaps>\n");
fprintf(stderr, "options: -b ... track block number\n");
fprintf(stderr, " -d ... trim with Q cutoff (diff: %d)\n", DEF_ARG_D);
fprintf(stderr, " -s ... min number of segments for Q estimate (%d)\n", DEF_ARG_S);
fprintf(stderr, " -S ... max number of segments for Q estimate (%d)\n", DEF_ARG_SS);
fprintf(stderr, " -o ... min overlap length after trim (%d)\n", DEF_ARG_O);
fprintf(stderr, " -u ... update trim %s using overlaps and existing %s track (%d)\n", DEF_ARG_T, DEF_ARG_Q, DEF_ARG_U);
fprintf(stderr, " -L ... log Q cutoff to file\n");
fprintf(stderr, " -t ... input trim track (%s)\n", DEF_ARG_T);
fprintf(stderr, " -T ... output trim track (%s)\n", DEF_ARG_T);
fprintf(stderr, " -q ... input q track (%s)\n", DEF_ARG_Q);
fprintf(stderr, " -Q ... output q track (%s)\n", DEF_ARG_Q);
fprintf(stderr, "\nEXPERIMENTAL\n");
fprintf(stderr, " -c ... CCS- or HiFI-reads: allow quality values of 0!\n");
}
int main(int argc, char* argv[])
{
HITS_DB db;
PassContext* pctx;
AnnotateContext actx;
FILE* fileOvlIn;
bzero(&actx, sizeof(AnnotateContext));
actx.db = &db;
// process arguments
int arg_u = DEF_ARG_U;
char* qlog = NULL;
opterr = 0;
actx.tblock = DEF_ARG_B;
actx.min_trimmed_len = DEF_ARG_O;
actx.trim_q = DEF_ARG_D;
actx.segmin = DEF_ARG_S;
actx.segmax = DEF_ARG_SS;
actx.track_trim_in = DEF_ARG_T;
actx.track_trim_out = DEF_ARG_T;
actx.track_q_in = DEF_ARG_Q;
actx.track_q_out = DEF_ARG_Q;
int c;
while ((c = getopt(argc, argv, "s:S:o:ub:d:L:t:T:q:Q:c")) != -1)
{
switch (c)
{
case 's':
actx.segmin = atoi(optarg);
break;
case 'S':
actx.segmax = atoi(optarg);
break;
case 'L':
qlog = optarg;
break;
case 'd':
actx.trim_q = atoi(optarg);
break;
case 'o':
actx.min_trimmed_len = atoi(optarg);
break;
case 'u':
arg_u = 1;
break;
case 'b':
actx.tblock = atoi(optarg);
break;
case 't':
actx.track_trim_in = optarg;
break;
case 'T':
actx.track_trim_out = optarg;
break;
case 'q':
actx.track_q_in = optarg;
break;
case 'Q':
actx.track_q_out = optarg;
break;
case 'c':
actx.CCS_READ = 1;
break;
default:
usage();
exit(1);
}
}
if (argc - optind != 2)
{
usage();
exit(1);
}
if (actx.trim_q == 0)
{
fprintf(stderr, "error: -q not specified\n");
exit(1);
}
if (actx.segmin < 1)
{
fprintf(stderr, "error: invalid -s\n");
exit(1);
}
if (actx.segmin > actx.segmax)
{
fprintf(stderr, "error: invalid -s -S combination\n");
exit(1);
}
char* pcPathReadsIn = argv[optind++];
char* pcPathOverlaps = argv[optind++];
if ( (fileOvlIn = fopen(pcPathOverlaps, "r")) == NULL )
{
fprintf(stderr, "could not open '%s'\n", pcPathOverlaps);
exit(1);
}
// init
if (Open_DB(pcPathReadsIn, &db))
{
fprintf(stderr, "failed to open %s\n", pcPathReadsIn);
exit(1);
}
pctx = pass_init(fileOvlIn, NULL);
pctx->split_b = 0;
pctx->data = &actx;
pctx->load_trace = 1;
pctx->unpack_trace = 1;
// passes
// update existing trim track
if (arg_u)
{
pre_update_anno(pctx, &actx);
pass(pctx, handler_update_anno);
post_update_anno(&actx);
}
else
{
pre_annotate(pctx, &actx);
pass(pctx, handler_annotate);
post_annotate(&actx);
}
if (qlog != NULL)
{
FILE* fileq = fopen(qlog, "w");
if (fileq)
{
fprintf(fileq, "%d\n", actx.trim_q);
fclose(fileq);
}
else
{
fprintf(stderr, "error: failed to open %s\n", qlog);
}
}
// cleanup
pass_free(pctx);
fclose(fileOvlIn);
Close_DB(&db);
return 0;
}
|
MartinPippel/DAmar
|
lib.ext/bitarr.c
|
/* bitarr.c */
/**************************************************************************
Bit Vectors in C
FILENAME: bitarr.c
LANGUAGE: ANSI C
REQUIRES: "types.h" (see below for minimal contents)
AUTHOR: <NAME> <<EMAIL>>
CREATED: 22 March 1995
MODIFIED: 20 July 1996
(see http://www.csd.uwo.ca/~jamie/BitVectors/changes.html
for a record of changes).
IMPORTANT NOTE: A version of this code appeared in
Dr. Dobb's Journal issue #233 (August 1995)
Volume 20 Issue 8
in an article entitled `Implementing Bit Vectors in C'
by <NAME>
Pages 42, 44, 46 (article) and pages 96, 98-100 (code)
The code is (c) copyright 1995 by Miller Freeman, Inc.
DESCRIPTION: Functions to create and manipulate arrays of bits, i.e. `bit
vectors'. Functions to: dynamically create arrays, access (read and
write) elements; convert from numbers to bit vectors and bit vectors
to strings. Additional mathematical functions (union, intersection,
complement, number of set bits) are provided that are more efficient
than naive implementations.
The module was designed to be robust enough to work with
machines of different word sizes. Only a couple of minor changes are
required to change it from using unsigned char for `bits' to another
integer type. See ba_init() and the definition of BITS_SZ for details.
Only minimal optimization has been attempted.
It is the caller's responsibility to know the size of the
bit vector. One way to keep track of the size is to wrap the bit
vector in a data structure like the one below. Note that the // is
used to mark a single line comment. Only the first two items are
necessary -- the others are included for illustration only.
typedef struct {
elem_t size; // how many items in selected
bits * selected; // bit vector recording which
// elements are selected
elem_t max; // maximum possible size
char ** name; // array of names of items
elem_t max_len; // maximum possible length of a name
char * title; // what data is represented
// by this struct?
} chose_t;
TYPEDEF NAMES
"types.h" must include definitions of the following 4 types
bool = a Boolean type (0 == FALSE, !0 == TRUE)
string = char *
elem_t = a number (used as a count, i.e. never < 0,
throughout).
bit = an unsigned integer
+ If this is not unsigned char then the #define
of BITS_SZ as CHAR_BIT should be changed.
+ If this is not internally represented by 8
bits then the lookup table in ba_count() must
be replaced.
+ SEE NOTE dated 13 August 1996 in changes.html
for a better solution.
***************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include "types.h"
#include "bitarr.h" /* exported prototypes */
#ifdef NEED_FPUTS_PROTO
int fputs(char *s, FILE *stream);
#endif
typedef struct {elem_t size; bit *vector;} BitVector;
static void first_is_biggest(BitVector bv[2], unsigned *, unsigned *);
/* *\
----------------------------------------------------------------
Macros
----------------------------------------------------------------
\* */
/*
macro NELEM()
The number of elements, nelem, in an array of N bits can be
computed using the formula:
if (0 == (N % BITS_SZ))
nelem = N/BITS_SZ
else
nelem = N/BITS_SZ + 1
This can be represented in any of these ways:
nelem = N/(BITS_SZ) + 1 - (0 == (N %(BITS_SZ)))
nelem = N/(BITS_SZ) + !(0 == (N %(BITS_SZ)))
nelem = N/(BITS_SZ) + (0 != (N %(BITS_SZ)))
The macro NELEM used this last form until <NAME>
<Frans_LiXia at wxs dot nl> suggested the form below (see changes.html).
*/
#define NELEM(N,ELEMPER) ((N + (ELEMPER) - 1) / (ELEMPER))
/*
macro CANONIZE()
Array is an array of `NumInts' type `bit' representing `NumElem' bits
Forces `Array' into canonical form, i.e. all unused bits are set to 0
*/
#define CANONIZE(Array,NumInts,NumElem) \
(Array)[NumInts - 1] &= (bit)~0 >> (BITS_SZ - ((NumElem % BITS_SZ) \
? (NumElem % BITS_SZ) \
: BITS_SZ));
/*
BITS_SZ
BITS_SZ is the number of bits in a single `bits' type.
*/
/* Definition of BITS_SZ */
#ifdef CHAR_BIT
/* assumes typedef unsigned char bits */
#define BITS_SZ (CHAR_BIT)
/** SEE 13 August 1996 note in changes.html for suggested improvement **/
#else
static elem_t bits_size(void);
elem_t BITS_SZ = 0; /* until it is initialized by ba_init() */
static elem_t bits_size(void) {
/*
Adapted from the wordlength() function on page 54 (Exercise
2-8) of _The C Answer Book_ (2nd ed.) by <NAME>
and <NAME>. Prentice-Hall, Inc., 1989.
*/
elem_t i;
bit v = (bit)~0;
for (i=1; (v = v >> 1) > 0; i++)
; /* EMPTY */
return (i);
}
#endif
/* *\
----------------------------------------------------------------
Initialization and Creation Code
----------------------------------------------------------------
\* */
elem_t ba_init(void)
{
/*
ba_init()
PRE: Must be called before use of any other ba_ functions. Should
only be called once.
POST: Returns the number of values that can be stored in one
variable of type `bit'. If <limits.h> does not define
`CHAR_BIT' then the module global variable `BITS_SZ' has been
set to the appropriate value.
*/
#ifndef BITS_SZ
if (!BITS_SZ) {
BITS_SZ = bits_size();
}
#endif
return (BITS_SZ);
} /* ba_init() */
bit *ba_new(const elem_t nelems)
{
/*
ba_new()
PURPOSE: dynamically allocate space for an array of `nelems' bits
and initalize the bits to all be zero.
PRE: nelems is the number of Boolean values required in an array
POST: either a pointer to an initialized (all zero) array of bit
OR
space was not available and NULL was returned
NOTE: calloc() guarantees that the space has been initialized to 0.
Used by: ba_ul2b(), ba_intersection() and ba_union().
*/
size_t howmany = NELEM(nelems,(BITS_SZ));
return ((bit *)calloc(howmany, sizeof(bit)));
} /* ba_new() */
size_t ba_bufsize(const elem_t nelems)
{
return NELEM(nelems, (BITS_SZ)) * sizeof(bit);
}
void ba_copy( bit dst[],
const bit src[],
const elem_t size)
{
/*
ba_copy()
PRE: `dst' has been initialized to hold `size' elements. `src'
is the array of bit to be copied to `dst'.
POST: `dst' is identical to the first `size' bits of `src'.
`src' is unchanged.
Used by: ba_union()
*/
elem_t nelem = NELEM(size,(BITS_SZ));
register elem_t i;
for (i=0; i < nelem; i++) {
dst[i] = src[i];
}
} /* ba_copy() */
/* *\
---------------------------------------------------------------
Assigning and Retrieving Values
---------------------------------------------------------------
\* */
void ba_assign( bit arr[],
elem_t elem,
const bool value)
{
/*
ba_assign()
PURPOSE: set or clear the bit in position `elem' of the array
`arr'
PRE: arr[elem] is to be set (assigned to 1) if value is TRUE,
otherwise it is to be cleared (assigned to 0).
POST: PRE fulfilled. All other bits unchanged.
SEE ALSO: ba_all_assign()
Used by: ba_ul2b()
*/
if (value) {
arr[elem / BITS_SZ] |= (1 << (elem % BITS_SZ));
} else {
arr[elem / BITS_SZ] &= ~(1 << (elem % BITS_SZ));
}
} /* ba_assign() */
void ba_assign_range(bit arr[], elem_t elem_beg, elem_t elem_end, const bool value)
{
if (value)
{
do
{
arr[elem_beg / BITS_SZ] |= (1 << (elem_beg % BITS_SZ));
elem_beg++;
} while ( elem_beg % BITS_SZ && elem_beg <= elem_end);
while ( (elem_end + 1) % BITS_SZ && elem_end >= elem_beg)
{
arr[elem_end / BITS_SZ] |= (1 << (elem_end % BITS_SZ));
elem_end--;
}
while (elem_beg < elem_end)
{
arr[elem_beg / BITS_SZ] = ~0;
elem_beg += BITS_SZ;
}
}
else
{
do
{
arr[elem_beg / BITS_SZ] &= ~(1 << (elem_beg % BITS_SZ));
elem_beg++;
} while ( elem_beg % BITS_SZ && elem_beg <= elem_end);
while ( (elem_end + 1) % BITS_SZ && elem_end >= elem_beg)
{
arr[elem_end / BITS_SZ] &= ~(1 << (elem_end % BITS_SZ));
elem_end--;
}
while (elem_beg < elem_end)
{
arr[elem_beg / BITS_SZ] = 0;
elem_beg += BITS_SZ;
}
}
}
bool ba_value(const bit arr[],
const elem_t elem)
{
/*
ba_value()
PRE: arr must have at least elem elements
POST: The value of the `elem'th element of arr has been returned
(as though `arr' was just a 1-dimensional array of bit)
Used by: ba_b2str() and ba_count()
*/
return( (arr[elem / BITS_SZ] & (1 << (elem % BITS_SZ))) ?TRUE :FALSE );
} /* ba_value() */
void ba_toggle( bit arr[],
const elem_t elem)
{
/*
ba_toggle()
PRE: arr must have at least elem elements
POST: The value of the `elem'th element of arr has been flipped,
i.e. if it was 1 it is 0; if it was 0 it is 1.
SEE ALSO: ba_complement()
*/
arr[elem / BITS_SZ] ^= (1 << (elem % BITS_SZ));
} /* ba_toggle() */
void ba_all_assign( bit arr[],
const elem_t size,
const bool value)
{
/*
ba_all_assign()
PRE: arr has been initialized to have *exactly* size elements.
POST: All `size' elements of arr have been set to `value'.
The array is in canonical form, i.e. trailing elements are
all 0.
NOTE: The array allocated by ba_new() has all elements 0 and is
therefore in canonical form.
SEE ALSO: ba_assign()
Used by: ba_ul2b()
*/
elem_t nelem = NELEM(size,(BITS_SZ));
bit setval = (value) ?~0 :0;
register elem_t i;
for (i=0; i < nelem; i++) {
arr[i] = setval;
}
/* force canonical form */
CANONIZE(arr,nelem,size);
} /* ba_all_assign() */
/* *\
----------------------------------------------------------------
Conversion Routines
----------------------------------------------------------------
\* */
bit * ba_ul2b(unsigned long num,
bit * arr,
elem_t * size)
{
/*
ba_ul2b()
PRE: Either
`arr' points to space allocated to hold enough `bit's to
represent `num' (namely the ceiling of the base 2 logarithm
of `num'). `size' points to the number of bit to use.
OR
`arr' is NULL and the caller is requesting that enough
space be allocated to hold the representation before the
translation is made. `size' points to space allocated to
hold the count of the number of bit needed for the
conversion (enough for MAXLONG).
POST: A pointer to a right-aligned array of bits representing the
unsigned value num has been returned and `size' points to
the number of `bit's needed to hold the value.
OR
the request to allocate space for such an array could not
be granted
NOTES: - The first argument is unsigned.
- It is bad to pass a `size' that is too small to hold the
bit array representation of `num' [K&R II, p.100].
- Should the `size' be the maximum size (if size > 0) even
if more bits are needed? The user can always use a filter
composed of all 1s (see ba_all_assign()) intersected with
result (see ba_intersection()).
*/
register elem_t i;
if (NULL != arr) {
ba_all_assign(arr, *size, 0);
} else {
*size = NELEM(sizeof(num),sizeof(bit));
*size *= BITS_SZ;
if (NULL == (arr = ba_new(*size))) {
return (arr);
}
}
/* usual base conversion algorithm */
for (i=0; num; num >>= 1, i++) {
ba_assign(arr, (*size - i - 1), (1 == (num & 01)));
}
return (arr);
} /* ba_ul2b() */
char * ba_b2str(const bit arr[],
const elem_t size,
char * dest)
{
/*
ba_b2str()
PRE: `arr' is a bit array with at least `size' elements. Either
`dest' points to enough allocated space to hold `size' + 1
characters or `dest' is NULL and such space is to be
dynamically allocated.
POST: Either `dest' points to a null-terminated string that
contains a character representation of the first `size'
elements of the bit array `arr';
OR
`dest' is NULL and a request to dynamically allocate memory
for a string to hold a character representation of `arr' was
not be granted.
Used by: ba_print()
*/
register elem_t i;
if ((NULL != dest) || \
(NULL != (dest = (char *)malloc(size + 1)))) {
for (i=0; i < size; i++) {
dest[i] = (ba_value(arr,i) ?'1' :'0');
}
dest[size] = '\0';
}
return (dest);
} /* ba_b2str() */
/* *\
----------------------------------------------------------------
Mathematical Applications
----------------------------------------------------------------
\* */
unsigned long ba_count(const bit arr[],
const elem_t size)
{
/*
ba_count()
PRE: `arr' is an allocated bit array with at least `size'
elements
POST: The number of 1 bits in the first `size' elements of `arr'
have been returned.
NOTE: if arr is not in canonical form, i.e. if some unused bits
are 1, then an unexpected value may be returned.
*/
register unsigned long count;
register elem_t i;
elem_t nelem = NELEM(size,(BITS_SZ));
static const unsigned bitcount[256] = {0, 1, 1, 2, 1, 2, 2, 3, 1, \
2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, \
4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, \
3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, \
3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, \
4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, \
5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, \
2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, \
4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, \
4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, \
6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, \
4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, \
5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, \
6, 6, 7, 6, 7, 7, 8};
if (bitcount[(sizeof bitcount / sizeof bitcount[0]) - 1] == BITS_SZ) {
/* lookup table will speed this up a lot */
for (count = 0L, i = 0; i < nelem; i++) {
count += bitcount[arr[i]];
}
} else {
for (count = 0L, i = 0; i < size; i++) {
if (ba_value(arr, i)) {
count++;
}
}
}
return (count);
} /* ba_count() */
bool ba_intersection( bit first[],
bit second[],
bit * result[],
const elem_t size_first,
const elem_t size_second)
{
/*
ba_intersection()
PRE: `first' is a bit array of at least `size_first' elements.
`second' is a bit array of at least `size_second' elements.
`result' points to enough space to hold the as many elements
as the smallest of `size_first' and `size_second';
OR
`result' points to NULL and such space is to be dynamically
allocated.
POST: TRUE has been returned and
`result' points to a bit array containing the intersection
of the two arrays up to the smallest of the two sizes;
OR
FALSE has been returned and
`result' pointed to NULL (a request was made to allocate
enough memory to store the intersection) but the required
memory could not be obtained.
NOTE: This runs faster if the `first' array is not smaller than
`second'.
*/
register elem_t i;
elem_t numints;
unsigned largest=0, smallest=1;
BitVector bv[2];
bv[largest].size = size_first;
bv[largest].vector = first;
bv[smallest].size = size_second;
bv[smallest].vector = second;
first_is_biggest(bv, &largest, &smallest);
/* allocate space if *result is NULL */
if ((NULL == *result) && \
(NULL == (*result = ba_new(bv[largest].size)))) {
return(FALSE); /* can't get memory, so can't continue */
} else {
numints = NELEM(size_second,(BITS_SZ));
for (i=0; i < numints; i++) {
(*result)[i] = (bv[smallest].vector[i] & \
bv[largest].vector[i]);
}
/* bits beyond size_second should be zero -- canonical form */
CANONIZE(*result, numints, size_second);
return(TRUE);
}
} /* ba_intersection() */
bool ba_union( bit first[],
bit second[],
bit * result[],
const elem_t size_first,
const elem_t size_second)
{
/*
ba_union()
PRE: `first' is a bit array of at least `size_first' elements.
`second' is a bit array of at least `size_second' elements.
`result' points to enough space to hold the as many elements
as the largest of `size_first' and `size_second';
OR
`result' points to NULL and such space is to be dynamically
allocated.
POST: TRUE has been returned and
`result' points to a bit array containing the union of the
two arrays (up to the size of the largest of the two sizes);
OR
FALSE has been returned and
`result' pointed to NULL (a request was made to allocate
enough memory to store the union) but the required memory
could not be obtained.
NOTE: This runs faster if the `first' array is not smaller than
`second'.
*/
register elem_t i;
elem_t numints;
unsigned largest=0, smallest=1;
BitVector bv[2];
bv[largest].size = size_first;
bv[largest].vector = first;
bv[smallest].size = size_second;
bv[smallest].vector = second;
first_is_biggest(bv, &largest, &smallest);
if ((NULL == *result) && \
(NULL == (*result = ba_new(bv[largest].size)))) {
return(FALSE);
} else {
ba_copy(*result, bv[largest].vector, bv[largest].size);
numints = NELEM(bv[smallest].size,(BITS_SZ));
for (i=0; i < numints; i++) {
(*result)[i] |= bv[smallest].vector[i];
}
CANONIZE(*result, numints, bv[largest].size);
return(TRUE);
}
} /* ba_union() */
bool ba_diff( bit first[],
bit second[],
bit * diff[],
const elem_t size_first,
const elem_t size_second)
{
/*
ba_diff()
PRE: `first' is a bit array of at least `size_first' elements.
`second' is a bit array of at least `size_second' elements.
`diff' points to enough space to hold the as many elements
as the largest of `size_first' and `size_second';
OR
`diff' points to NULL and such space is to be dynamically
allocated.
POST: TRUE has been returned and
`diff' points to a bit array containing the union of the
two arrays (up to the size of the largest of the two sizes);
OR
FALSE has been returned and
`result' pointed to NULL (a request was made to allocate
enough memory to store the result) but the required memory
could not be obtained.
NOTE: This runs faster if the `first' array is not smaller than
`second'.
*/
register elem_t i;
elem_t numints;
unsigned largest=0, smallest=1;
BitVector bv[2];
bv[largest].size = size_first;
bv[largest].vector = first;
bv[smallest].size = size_second;
bv[smallest].vector = second;
first_is_biggest(bv, &largest, &smallest);
if ((NULL == *diff) && \
(NULL == (*diff = ba_new(bv[largest].size)))) {
return(FALSE);
} else {
ba_copy(*diff, bv[largest].vector, bv[largest].size);
numints = NELEM(bv[smallest].size,(BITS_SZ));
for (i=0; i < numints; i++) {
(*diff)[i] ^= bv[smallest].vector[i];
}
CANONIZE(*diff, numints, bv[largest].size);
return(TRUE);
}
} /* ba_diff() */
void ba_complement( bit arr[],
const elem_t size)
{
/*
ba_complement()
PRE: `arr' is a bit array composed of *exactly* `size' elements.
POST: All the bits in `arr' have been flipped and `arr' is in
canonical form.
SEE ALSO: ba_toggle()
*/
elem_t nelem = NELEM(size,(BITS_SZ));
register elem_t i;
for (i=0; i < nelem; i++) {
arr[i] = ~arr[i];
}
/* force canonical form */
CANONIZE(arr, nelem, size);
} /* ba_complement() */
unsigned long ba_dotprod(const bit first[],
const bit second[],
const elem_t size_first,
const elem_t size_second)
{
/*
ba_dotprod()
PRE: `first' is an array of at least `size_first' bits. `second'
is an array of at least `size_second' bits.
POST: The scalar product of the two vectors represented by the
first `size_first' elements of `first' and the first
`size_second' elements of `second' have been returned.
*/
register elem_t i, j;
register unsigned long sum = 0L;
for (i=0; i < size_first; i++) {
for (j=0; j < size_second; j++) {
sum += (first[i/BITS_SZ] & (1<<(i % BITS_SZ))) \
&& \
(second[j/BITS_SZ] & (1<<(j % BITS_SZ)));
}
}
return (sum);
} /* ba_dotprod() */
/* *\
----------------------------------------------------------------
Internal Function
----------------------------------------------------------------
\* */
static
void first_is_biggest(BitVector bv[2],
unsigned * big,
unsigned * small)
{
if (bv[*big].size < bv[*small].size) {
unsigned temp;
temp = *big;
*big = *small;
*small = temp;
}
} /* first_is_biggest() */
/* *\
----------------------------------------------------------------
Miscellaneous
----------------------------------------------------------------
\* */
bool ba_print(const bit arr[],
const elem_t size,
FILE * dest)
{
char * to_print = ba_b2str(arr, size, NULL);
if (NULL != to_print) {
bool status = (EOF != fputs(to_print, dest) );
free(to_print);
return (status);
} else {
return (FALSE);
}
} /* ba_print() */
|
MartinPippel/DAmar
|
scrub/LAfilter.c
|
<reponame>MartinPippel/DAmar
/*******************************************************************************************
*
* filters overlaps by various criteria
*
* Author : <NAME>
*
* Date : May 2015
*
*******************************************************************************************/
#include <assert.h>
#include <limits.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#include <unistd.h>
#include "lib/colors.h"
#include "lib/oflags.h"
#include "lib/pass.h"
#include "lib/read_loader.h"
#include "lib/tracks.h"
#include "lib/trim.h"
#include "lib/utils.h"
#include "dalign/align.h"
#include "db/DB.h"
#define DEF_ARG_S -1
#define DEF_ARG_T TRACK_TRIM
#define DEF_ARG_TT 0
#define DEF_ARG_R TRACK_REPEATS
#define BIN_SIZE 100
#define MIN_LR 500
#define READ_NONE 0x0
#define READ_DISCARD ( 0x1 << 0 )
#define READ_KEEP ( 0x1 << 1 )
#define VERBOSE
#undef VERBOSE_STITCH
#ifdef VERBOSE_STITCH
#define OVL_STRAND( ovl ) ( ( ( ovl )->flags & OVL_COMP ) ? 'c' : 'n' )
#endif
#define REMOVE_STITCH_OVL ( 1 << 0 )
#define REMOVE_MOD_OVL ( 1 << 1 )
#define REMOVE_TP ( 1 << 2 )
#define REMOVE_NONID_OVL ( 1 << 3 )
#define REMOVE_SPECREP_OVL ( 1 << 4 )
#define REMOVE_ID_OVL ( 1 << 5 )
#define REMOVE_CONT_OVL ( 1 << 6 )
#define ANCHOR_INVALID (1 << 0)
#define ANCHOR_TRIM (1 << 1)
#define ANCHOR_LOWCOMP (1 << 2)
#define DEBUG_CHIMER
typedef struct
{
int beg;
int end;
int flag;
} anchorItv;
typedef struct
{
// stats counters
int nFilteredDiffs;
int nFilteredDiffsSegments;
int nFilteredUnalignedBases;
int nFilteredContainedOvls;
int nFilteredLength;
int nFilteredRepeat;
int nFilteredReadLength;
int nRepeatOvlsKept;
int nFilteredLocalEnd;
int nLowCovALn;
int nSymDiscard;
int nMultiMapper;
int nMultiMapperBases;
int nCovFiltReads;
int64 nCovFiltOverlaps, nCovFiltBases;
// settings
int nStitched;
float fMaxDiffs;
int nMaxUnalignedBases, nMinAlnLength;
int nMinNonRepeatBases, nMinReadLength;
int nVerbose;
int stitch;
int stitch_aggressively;
int rm_cov; // repeat modules, coverage
int rm_aggressive; // -M
int do_trim;
int downsample;
int remUpToXPercAln;
int removeFlags; // 1 << 0 ... stitched overlaps, 1 << 1 ... module overlaps, 1 << 2 .. trace points, 1 << 3 .. non-identity overlaps,
// 1 << 4 .. remove B-read repeat overlaps, if a proper overlap between A and B exist i.e A ------------ or A ------------ or A ------------ or A ------------
// B -----E|B B E|B----- B E|B---E|B B ------------------
// 1 << 5 .. identity overlaps,
// 1 << 6 .. contained overlaps (this includes duplicates)
int includeReadFlag;
int removeLowCoverageOverlaps;
int removeMultiMappers;
int rp_mergeTips; // increase repeat interval if it ends with rp_mergeTips Bases according to trim annotation
// repeat modules - merged repeats
int rm_merge;
int rm_mode;
track_data* rm_repeat;
unsigned int rm_maxrepeat;
uint64_t* rm_bins;
int rm_maxbins;
int trimIndels;
// repeat modules - result track
track_anno* rm_anno;
track_data* rm_data;
track_anno rm_ndata;
track_anno rm_maxdata;
// local ends
int* le_lbins;
int* le_rbins;
int le_maxbins;
FILE* fileSpanningReads;
HITS_DB* db;
HITS_TRACK* trackRepeat;
HITS_TRACK* trackTrim;
HITS_TRACK* trackDust;
int* r2bin;
int max_r2bin;
int useRLoader;
TRIM* trim;
Read_Loader* rl;
ovl_header_twidth twidth;
FILE* fileOutDiscardedOverlaps;
int ** discardedAreadList;
int * discardedBreads;
// experimental keep track of unique read intervals
int numIntervals;
int curItv;
anchorItv *uniqIntervals;
int mergeRepeatsWindow;
int mergeRepeatsMaxLen;
int maxSegmentErrorRate;
int chimerCoverage;
int chimerAnchorBases;
} FilterContext;
extern char* optarg;
extern int optind, opterr, optopt;
static int loader_handler(void* _ctx, Overlap* ovl, int novl)
{
FilterContext* ctx = (FilterContext*) _ctx;
Read_Loader* rl = ctx->rl;
static int firstCall = 1;
int i;
for (i = 0; i < novl; i++)
{
int b = ovl[i].bread;
int trim_b_left, trim_b_right;
if (ctx->trackTrim)
get_trim(ctx->db, ctx->trackTrim, b, &trim_b_left, &trim_b_right);
else
{
if (ctx->trackTrim == NULL && firstCall)
{
printf("[WARNING] - Read loader is used without trim track. This can cause issues!\n");
firstCall = 0;
}
trim_b_left = 0;
trim_b_right = DB_READ_LEN(ctx->db, b);
}
if (ovl[i].flags & OVL_COMP)
{
int tmp = trim_b_left;
int blen = DB_READ_LEN(ctx->db, ovl[i].bread);
trim_b_left = blen - trim_b_right;
trim_b_right = blen - tmp;
}
if (trim_b_left >= trim_b_right)
{
continue;
}
int bbt = MAX(trim_b_left, ovl[i].path.bbpos);
int bet = MIN(trim_b_right, ovl[i].path.bepos);
if (bbt >= bet)
{
continue;
}
if (bbt == ovl[i].path.bbpos && bet == ovl[i].path.bepos)
{
continue;
}
bbt = MAX(trim_b_left, ovl[i].path.bbpos);
bet = MIN(trim_b_right, ovl[i].path.bepos);
if (bbt < bet && (bbt != ovl[i].path.bbpos || bet != ovl[i].path.bepos))
{
rl_add(rl, ovl[i].aread);
rl_add(rl, ovl[i].bread);
continue;
}
int bepos = ovl[i].path.bepos;
if (bepos > bet)
{
rl_add(rl, ovl[i].aread);
rl_add(rl, ovl[i].bread);
}
}
return 1;
}
static int contained(int ab, int ae, int bb, int be)
{
if (ab >= bb && ae <= be)
{
return 1;
}
return 0;
}
static int duplicated(int ab, int ae, int bb, int be)
{
if (ab == bb && ae == be)
{
return 1;
}
return 0;
}
static void removeOvls(FilterContext *fctx, Overlap* ovls, int novls, int rmFlag)
{
int i;
for (i = 0; i < novls; i++)
{
if (rmFlag & REMOVE_TP)
{
ovls[i].path.tlen = 0;
ovls[i].path.trace = NULL;
}
if ((rmFlag & REMOVE_MOD_OVL) && (ovls[i].flags & OVL_MODULE))
{
ovls[i].flags |= OVL_DISCARD;
}
else if ((rmFlag & REMOVE_STITCH_OVL) && (ovls[i].path.tlen == 0))
{
ovls[i].flags |= OVL_DISCARD;
}
else if ((rmFlag & REMOVE_NONID_OVL) && (ovls[i].aread != ovls[i].bread))
{
ovls[i].flags |= OVL_DISCARD;
}
else if ((rmFlag & REMOVE_ID_OVL) && (ovls[i].aread == ovls[i].bread))
{
ovls[i].flags |= OVL_DISCARD;
}
}
// special case: REMOVE_SPECREP_OVL
if ((rmFlag & REMOVE_SPECREP_OVL))
{
printf("REMOVE_SPECREP_OVL\n");
int j, k;
j = k = 0;
int proper;
int alen = DB_READ_LEN(fctx->db, ovls->aread);
while (j < novls)
{
int blen = DB_READ_LEN(fctx->db, ovls[j].bread);
proper = 0;
if ((ovls[j].path.abpos == 0 || ovls[j].path.bbpos == 0) && (ovls[j].path.aepos == alen || ovls[j].path.bepos == blen))
proper++;
while (k < novls - 1 && ovls[j].bread == ovls[k + 1].bread)
{
if ((ovls[k + 1].path.abpos == 0 || ovls[k + 1].path.bbpos == 0) && (ovls[k + 1].path.aepos == alen || ovls[k + 1].path.bepos == blen))
proper++;
k++;
}
printf("aread: %d bread: %d novl: %d proper: %d\n", ovls[j].aread, ovls[j].bread, k - j + 1, proper);
if (proper == 1 && k - j + 1 > 1)
{
int l;
for (l = 0; l < k - j + 1; l++)
{
Overlap *ovl = ovls + j + l;
if (!((ovl->path.abpos == 0 || ovl->path.bbpos == 0) && (ovl->path.aepos == alen || ovl->path.bepos == blen)))
ovl->flags |= OVL_DISCARD;
}
}
j = k + 1;
}
}
if (rmFlag & REMOVE_CONT_OVL)
{
int j, k, l, m;
j = k = 0;
while (j < novls)
{
while (k < novls - 1 && ovls[j].bread == ovls[k + 1].bread)
{
k++;
}
int num = k - j + 1;
if (num > 1)
{
for (l = j; l <= k; l++)
{
Overlap *o1 = ovls + l;
if (o1->flags & OVL_DISCARD)
continue;
if (o1->aread == o1->bread && o1->path.abpos == o1->path.bbpos && o1->path.aepos == o1->path.bepos)
{
o1->flags |= (OVL_DISCARD | OVL_CONT);
fctx->nFilteredContainedOvls++;
if (fctx->nVerbose)
{
printf("found contained OVL: %d vs %d a[%d,%d] equals b[%d,%d]\n", o1->aread, o1->bread, o1->path.abpos, o1->path.aepos, o1->path.bbpos, o1->path.bepos);
}
continue;
}
for (m = l + 1; m <= k; m++)
{
Overlap *o2 = ovls + m;
if (o2->flags & OVL_DISCARD)
continue;
int RM = 0;
if (ovls[j].aread != ovls[j].bread) // ignore identity overlaps, as they can be removed with another -R option
{
RM = (contained(o2->path.abpos, o2->path.aepos, o1->path.abpos, o1->path.aepos) && contained(o2->path.bbpos, o2->path.bepos, o1->path.bbpos, o1->path.bepos));
}
else // identity overlaps, remove duplicates
{
RM = (duplicated(o2->path.abpos, o2->path.aepos, o1->path.abpos, o1->path.aepos) && duplicated(o2->path.bbpos, o2->path.bepos, o1->path.bbpos, o1->path.bepos));
}
if (RM)
{
o2->flags |= (OVL_DISCARD | OVL_CONT);
fctx->nFilteredContainedOvls++;
if (fctx->nVerbose)
{
printf("found contained OVL: %d vs %d a[%d,%d] b[%d,%d] in a[%d,%d] b[%d,%d]\n", o2->aread, o2->bread, o2->path.abpos, o2->path.aepos, o2->path.bbpos, o2->path.bepos, o1->path.abpos, o1->path.aepos, o1->path.bbpos, o1->path.bepos);
}
}
}
}
}
else
{
// remove self alignments with exact same start and end coordinates
if (ovls[j].aread == ovls[j].bread && ovls[j].path.abpos == ovls[j].path.bbpos && ovls[j].path.aepos == ovls[j].path.bepos)
{
ovls[j].flags |= (OVL_DISCARD | OVL_CONT);
fctx->nFilteredContainedOvls++;
if (fctx->nVerbose)
{
printf("found contained OVL: %d vs %d a[%d,%d] equals b[%d,%d]\n", ovls[j].aread, ovls[j].bread, ovls[j].path.abpos, ovls[j].path.aepos, ovls[j].path.bbpos, ovls[j].path.bepos);
}
}
}
j = k + 1;
}
}
}
static void trimOffLeadingIndels(Overlap *ovl, ovl_header_twidth twidth)
{
ovl_trace* trace = ovl->path.trace;
int trim_a_left, trim_a_right;
int tlen = ovl->path.tlen;
trim_a_left = trim_a_right = -1;
int begSegA = (ovl->path.abpos == 0) ? ovl->path.abpos : (((ovl->path.abpos - 1) / twidth + 1) * twidth) - ovl->path.abpos;
int endSegA = ovl->path.aepos - ((((ovl->path.aepos) / twidth)) * twidth);
//printf("%d vs %d a[%d, %d] b[%d,%d] aseg %d, %d\n",ovl->aread, ovl->bread, ovl->path.abpos, ovl->path.aepos, ovl->path.bbpos, ovl->path.bepos,begSegA, endSegA);
// check first segment
if ((trace[0] == trace[1] && trace[0] == begSegA) || (trace[0] > 0 && trace[1] == 0))
{
printf("trace[0] %d == trace[1] %d\n", trace[0], trace[1]);
trim_a_left = (((ovl->path.abpos) / twidth) + 1) * twidth;
}
// check last segment
if ((trace[tlen - 2] == trace[tlen - 1] && trace[tlen - 2] == endSegA) || (trace[tlen - 2] > 2 && trace[tlen - 1] == 0))
{
printf("trace[tlen - 2] %d == trace[tlen - 1] %d\n", trace[tlen - 2], trace[tlen - 1]);
trim_a_right = (((ovl->path.aepos) / twidth)) * twidth;
}
if (trim_a_left > -1)
{
printf("trimBeg: %d vs %d a[%d,%d -> %d,%d] b[%d,%d -> %d,%d]\n", ovl->aread, ovl->bread, ovl->path.abpos, ovl->path.aepos, trim_a_left, ovl->path.aepos, ovl->path.bbpos, ovl->path.bepos, ovl->path.bbpos + trace[0], ovl->path.bepos);
ovl->path.abpos = trim_a_left;
ovl->path.bbpos += trace[0];
trace += 2;
tlen -= 2;
ovl->path.tlen = tlen;
ovl->path.trace = trace;
}
if (trim_a_right > -1)
{
printf("trimEnd: %d vs %d a[%d,%d -> %d,%d] b[%d,%d -> %d,%d]\n", ovl->aread, ovl->bread, ovl->path.abpos, ovl->path.aepos, ovl->path.abpos, trim_a_right, ovl->path.bbpos, ovl->path.bepos, ovl->path.bbpos, ovl->path.bepos - trace[tlen - 2]);
ovl->path.aepos = trim_a_right;
ovl->path.bepos -= trace[tlen - 2];
ovl->path.tlen -= 2;
}
}
static int filterMaxSegmentErrorRate(Overlap *ovl, int maxSegmentErrorRate)
{
ovl_trace* trace = ovl->path.trace;
int tlen = ovl->path.tlen;
// printf("o[%d, %d] %c a[%d, %d] b[%d, %d]", ovl->aread, ovl->bread, ovl->flags & OVL_COMP ? 'C' : 'N', ovl->path.abpos, ovl->path.aepos, ovl->path.bbpos, ovl->path.bepos);
int i;
for (i = 0; i < tlen - 2; i += 2)
{
// ignore substitutions for now // TODO
if ((trace[i]) * 100.0 / (trace[i + 1]) > maxSegmentErrorRate)
{
ovl->flags |= (OVL_DISCARD | OVL_DIFF);
// printf(" (%3d %3d) erate: %f DISCARD\n", trace[i], trace[i+1], (trace[i])*100.0/(trace[i+1]));
return 1;
}
}
// printf("\n");
return 0;
}
static int stitch(Overlap* ovls, int n, int fuzz, int aggressive)
{
int stitched = 0;
if (n < 2)
{
return stitched;
}
int i, k, b;
int ab2, ae1, ae2;
int bb2, be1, be2;
const int ignore_mask = OVL_CONT | OVL_STITCH | OVL_GAP | OVL_TRIM;
for (i = 0; i < n; i++)
{
Overlap* ovli = ovls + i;
if (ovli->flags & ignore_mask)
{
continue;
}
b = ovli->bread;
ae1 = ovli->path.aepos;
be1 = ovli->path.bepos;
int found = 1;
while (found)
{
found = 0;
int maxk = 0;
int maxlen = 0;
for (k = i + 1; k < n && ovls[k].bread <= b; k++)
{
Overlap* ovlk = ovls + k;
if ((ovlk->flags & ignore_mask) || (ovli->flags & OVL_COMP) != (ovlk->flags & OVL_COMP))
{
continue;
}
ab2 = ovlk->path.abpos;
ae2 = ovlk->path.aepos;
bb2 = ovlk->path.bbpos;
be2 = ovlk->path.bepos;
int deltaa = abs(ae1 - ab2);
int deltab = abs(be1 - bb2);
if (deltaa < fuzz && deltab < fuzz && (aggressive || abs(deltaa - deltab) < 40))
{
if (ae2 - ab2 > maxlen)
{
found = 1;
maxk = k;
maxlen = ae2 - ab2;
}
}
}
if (found)
{
Overlap* ovlk = ovls + maxk;
ab2 = ovlk->path.abpos;
ae2 = ovlk->path.aepos;
bb2 = ovlk->path.bbpos;
be2 = ovlk->path.bepos;
#ifdef VERBOSE_STITCH
int ab1 = ovli->path.abpos;
int bb1 = ovli->path.bbpos;
printf("STITCH %8d @ %5d..%5d -> %8d @ %5d..%5d %c\n"
" %5d..%5d -> %8d @ %5d..%5d %c\n",
ovli->aread,
ab1, ae1, ovli->bread, bb1, be1, OVL_STRAND(ovli),
ab2, ae2, ovlk->bread, bb2, be2, OVL_STRAND(ovlk)));
#endif
ovli->path.aepos = ae2;
ovli->path.bepos = be2;
ovli->path.diffs += ovlk->path.diffs;
ovli->path.tlen = 0;
ae1 = ae2;
be1 = be2;
assert(ovli->bread == ovlk->bread);
ovli->flags &= ~( OVL_DISCARD | OVL_LOCAL); // force a re-evaluation of the OVL_LOCAL flags
ovlk->flags |= OVL_DISCARD | OVL_STITCH;
stitched += 1;
#ifdef VERBOSE_STITCH
printf( " -> %8d @ %5d..%5d -> %8d @ %5d..%5d %c delta a %3d b %3d\n",
ovli->aread,
ovli->path.abpos, ovli->path.aepos,
ovli->bread,
ovli->path.abpos, ovli->path.aepos,
OVL_STRAND( ovli ),
deltaa, deltab );
#endif
}
}
}
return stitched;
}
static int find_repeat_modules(FilterContext* ctx, Overlap* ovls, int novl)
{
int a = ovls->aread;
int trim_ab, trim_ae;
const int exclude_mask = OVL_LOCAL | OVL_TRIM | OVL_CONT | OVL_STITCH | OVL_GAP | OVL_DIFF;
const int allowed_mask = OVL_DISCARD | OVL_REPEAT | OVL_COMP; // | OVL_OLEN | OVL_RLEN;
if (ctx->trackTrim)
{
get_trim(ctx->db, ctx->trackTrim, a, &trim_ab, &trim_ae);
}
else
{
trim_ab = 0;
trim_ae = DB_READ_LEN(ctx->db, a);
}
if (trim_ab >= trim_ae)
{
return 1;
}
int i;
uint32_t left = 0;
uint32_t right = 0;
int left_potential = 0;
int right_potential = 0;
// if there are non-repeat overlaps, entering left and leaving right, then no module overlaps are needed
for (i = 0; i < novl; i++)
{
Overlap* ovl = ovls + i;
int abpos = ovl->path.abpos;
int aepos = ovl->path.aepos;
int flags = ovl->flags;
// contained
if (abpos == trim_ab && aepos == trim_ae)
{
left = 1;
right = 1;
break;
}
// potential exits, only allowed to have discard, repeat or comp flag
if ((flags & (~allowed_mask)) == 0)
{
if (abpos == trim_ab)
{
left_potential += 1;
}
if (aepos == trim_ae)
{
right_potential += 1;
}
}
// exits left / right
if (flags & OVL_DISCARD)
{
continue;
}
if (abpos == trim_ab)
{
left += 1;
}
if (aepos == trim_ae)
{
right += 1;
}
}
if ((left > 0 && right > 0) || (left == 0 && right == 0))
{
return 1;
}
track_anno* ranno = (track_anno*) (ctx->trackRepeat->anno);
track_data* rdata = (track_data*) (ctx->trackRepeat->data);
track_anno ob = ranno[a];
track_anno oe = ranno[a + 1];
// no repeats, nothing to do
if (ob >= oe)
{
return 1;
}
if (oe - ob > ctx->rm_maxrepeat) // bytes
{
ctx->rm_maxrepeat = (oe - ob) + 128;
ctx->rm_repeat = malloc(ctx->rm_maxrepeat);
}
// merge repeats close to each other
int nrepeat = 0;
ob /= sizeof(track_data);
oe /= sizeof(track_data);
int rm_merge = ctx->rm_merge;
if (rm_merge < ctx->nMinNonRepeatBases)
rm_merge = ctx->nMinNonRepeatBases;
while (ob < oe)
{
int b = MAX(trim_ab, rdata[ob]);
int e = MIN(trim_ae, rdata[ob + 1]);
ob += 2;
if (b >= e)
{
continue;
}
/// try to ignore to add up low complexity intervals from DBdust
if ((nrepeat > 0) && (b - ctx->rm_repeat[nrepeat - 1] < rm_merge) && (rm_merge < 100 || (e - b > 100)))
{
// ctx->stats_merged++;
ctx->rm_repeat[nrepeat - 1] = e;
}
else
{
ctx->rm_repeat[nrepeat++] = b;
ctx->rm_repeat[nrepeat++] = e;
}
}
// for each segment count number of reads anchored with at least MIN_LR
bzero(ctx->rm_bins, sizeof(uint64_t) * ctx->rm_maxbins);
for (i = 0; i < novl; i++)
{
Overlap* ovl = ovls + i;
if (ovl->flags & ( OVL_STITCH | OVL_TRIM))
{
continue;
}
int b = (ovl->path.abpos + MIN_LR) / BIN_SIZE;
int e = (ovl->path.aepos - MIN_LR) / BIN_SIZE;
// spanning local alignments indicate non-reliable points inside the repeat
int incr = 1;
if (ctx->rm_aggressive == 0 && (ovl->flags & OVL_LOCAL))
{
incr = ctx->rm_cov;
}
while (b < e)
{
ctx->rm_bins[b] += incr;
b++;
}
}
track_anno prev_offset = ctx->rm_ndata;
for (i = 0; i < nrepeat; i += 2)
{
int rb = ctx->rm_repeat[i];
int re = ctx->rm_repeat[i + 1];
// skip repeats if there are valid spanning overlaps
int skip = 0;
int j;
for (j = 0; j < novl; j++)
{
Overlap* ovl = ovls + j;
if ((ovl->flags & OVL_DISCARD))
{
continue;
}
if (ovl->path.abpos + MIN_LR <= rb && ovl->path.aepos - MIN_LR >= re)
{
skip = 1;
break;
}
}
if (skip)
{
continue;
}
// gaps inside the repeat with < expected coverage are potential repeat modules
int b = MAX(trim_ab + 1000, rb + MIN_LR) / BIN_SIZE;
int e = MIN(trim_ae - 1000, re - MIN_LR) / BIN_SIZE;
int beg = -1;
while (b < e)
{
if (ctx->rm_bins[b] > 0 && ctx->rm_bins[b] < (uint64_t) ctx->rm_cov)
{
//printf("READ %7d POINT @ %5d..%5d %3d %2llu\n", a, b * BIN_SIZE - 50, b * BIN_SIZE + 50, b, ctx->rm_bins[b]);
if (beg == -1)
{
beg = b;
}
}
else
{
if (beg != -1)
{
if (b - beg > 7)
{
//printf("MOD %7d POINT @ %5d %5d %5d..%5d\n", a, (b + beg) / 2, (b + beg) * BIN_SIZE / 2, beg, b);
if (ctx->rm_ndata + 2 > ctx->rm_maxdata)
{
ctx->rm_maxdata = 1.2 * ctx->rm_ndata + 100;
ctx->rm_data = realloc(ctx->rm_data, ctx->rm_maxdata * sizeof(track_data));
}
int intb = (b + beg) / 2 * BIN_SIZE - 50;
int inte = intb + 100;
ctx->rm_anno[a] += 2 * sizeof(track_data);
ctx->rm_data[ctx->rm_ndata++] = intb;
ctx->rm_data[ctx->rm_ndata++] = inte;
}
beg = -1;
}
}
b++;
}
}
// restore discarded overlaps spanning the repeat module junction
uint32_t enabled = 0;
while (prev_offset < ctx->rm_ndata)
{
int b = ctx->rm_data[prev_offset++];
int e = ctx->rm_data[prev_offset++];
// ignore module that would result in excessive coverage at the junction
//printf("MODULE @ %d..%d\n", b, e);
int cov = 0;
for (i = 0; i < novl; i++)
{
Overlap* ovl = ovls + i;
if (ovl->path.abpos + 100 < b && ovl->path.aepos - 100 > e)
{
if (!(ovl->flags & OVL_DISCARD) || ((ovl->flags & OVL_REPEAT) && !(ovl->flags & exclude_mask)))
{
cov++;
}
}
}
if (cov > ctx->rm_cov || cov < ctx->rm_cov / 2)
{
continue;
}
for (i = 0; i < novl; i++)
{
Overlap* ovl = ovls + i;
if (!(ovl->flags & OVL_REPEAT) || (ovl->flags & exclude_mask))
{
continue;
}
// MARTIN ignore overlaps that do not have an overhang
if (ovl->path.abpos > trim_ab && ovl->path.aepos < trim_ae)
{
continue;
}
if (ovl->path.abpos + MIN_LR < b && ovl->path.aepos - MIN_LR > e)
{
ovl->flags &= ~OVL_DISCARD;
ovl->flags |= OVL_MODULE;
ctx->nRepeatOvlsKept++;
enabled += 1;
}
}
}
if (enabled)
{
return 1;
}
printf("%d | left = %d right %d lp %d rp %d\n", a, left, right, left_potential, right_potential);
/*
// try to relax the min non-repeat bases condition
ob = ranno[a] / sizeof(track_data);
oe = ranno[a + 1] / sizeof(track_data);
int dist_left = INT_MAX;
int dist_right = INT_MAX;
while ( ob < oe )
{
int rb = MAX(trim_ab, rdata[ob]);
int re = MIN(trim_ae, rdata[ob + 1]);
ob += 2;
if (rb >= re)
{
continue;
}
dist_left = MIN( rb - trim_ab, dist_left );
dist_right = MIN( trim_ae - re, dist_right );
}
printf("%d | min dist left %d right %d\n", a, dist_left, dist_right);
if ( (left == 0 && left_potential <= ctx->rm_cov && dist_left > 100 && dist_left != INT_MAX) ||
(right == 0 && right_potential <= ctx->rm_cov && dist_right > 100 && dist_right != INT_MAX) )
{
for ( i = 0 ; i < novl ; i++ )
{
Overlap* ovl = ovls + i;
if ( (left == 0 && ovl->path.abpos == trim_ab && !(ovl->flags & (~allowed_mask)) ) ||
(right == 0 && ovl->path.aepos == trim_ae && !(ovl->flags & (~allowed_mask)) ) )
{
ovl->flags &= ~OVL_DISCARD;
ovl->flags |= OVL_MODULE;
ctx->nRepeatOvlsKept++;
enabled += 1;
}
}
}
printf("%d | enabled %d\n", a, enabled);
if (enabled)
{
return 1;
}
*/
//
// TODO --- coverage ... don't count multiple overlaps with the same b ????
//
if (ctx->rm_mode < 2)
{
return 1;
}
// look at b reads and see if they would lead is to a unique region
if (novl > ctx->max_r2bin)
{
ctx->max_r2bin = novl * 1.2 + 128;
ctx->r2bin = realloc(ctx->r2bin, sizeof(int) * ctx->max_r2bin);
}
int potential = 0;
bzero(ctx->r2bin, sizeof(int) * ctx->max_r2bin);
bzero(ctx->rm_bins, sizeof(uint64_t) * ctx->rm_maxbins);
int binsize = MAX(BIN_SIZE, 1000);
for (i = 0; i < novl; i++)
{
Overlap* ovl = ovls + i;
int trim_bb, trim_be;
int b = ovl->bread;
if ((ovl->flags & exclude_mask) || (left == 0 && ovl->path.abpos != trim_ab) || (right == 0 && ovl->path.aepos != trim_ae))
{
continue;
}
get_trim(ctx->db, ctx->trackTrim, b, &trim_bb, &trim_be);
printf("%7d | btrim %5d..%5d\n", b, trim_bb, trim_be);
int bb, be;
if (ovl->flags & OVL_COMP)
{
int blen = DB_READ_LEN(ctx->db, b);
bb = blen - ovl->path.bepos;
be = blen - ovl->path.bbpos;
}
else
{
bb = ovl->path.bbpos;
be = ovl->path.bepos;
}
ob = ranno[b] / sizeof(track_data);
oe = ranno[b + 1] / sizeof(track_data);
int rb, re;
int nrb = 0;
int prev_end = trim_bb;
int rlen_in_b = 0;
while (ob < oe)
{
rb = MAX(trim_bb, rdata[ob]);
re = MIN(trim_be, rdata[ob + 1]);
ob += 2;
printf("%d | %7d | b repeat %5d..%5d\n", a, b, rb, re);
if (rb >= re)
{
continue;
}
if (left == 0)
{
if (ovl->flags & OVL_COMP)
{
if (rb < be && be < re)
{
rlen_in_b = re - be;
}
}
else
{
if (rb < bb && bb < re)
{
rlen_in_b = bb - rb;
}
}
}
else
{
if (ovl->flags & OVL_COMP)
{
if (rb < bb && bb < re)
{
rlen_in_b = bb - rb;
}
}
else
{
if (rb < be && be < re)
{
rlen_in_b = re - be;
}
}
}
nrb += rb - prev_end;
prev_end = re;
}
nrb += trim_be - prev_end;
if (nrb < ctx->nMinNonRepeatBases || rlen_in_b == 0)
{
continue;
}
printf("%d -> %7d | leftover rlen %5d nrb %5d", a, b, rlen_in_b, nrb);
if (!(ovl->flags & (~allowed_mask)))
{
ovl->flags |= OVL_TEMP;
potential += 1;
printf(" YES");
int bin = rlen_in_b / binsize;
ctx->rm_bins[bin] += 1;
ctx->r2bin[i] = bin;
}
printf("\n");
}
if (potential > 0)
{
for (i = 0; i < novl; i++)
{
Overlap* ovl = ovls + i;
if (ovl->flags & OVL_TEMP)
{
int bin = ctx->r2bin[i];
ovl->flags &= ~OVL_TEMP;
if (ctx->rm_bins[bin] > 2 && ctx->rm_bins[bin] < (uint32_t) ctx->rm_cov)
{
ovl->flags &= ~OVL_DISCARD;
ovl->flags |= OVL_OPTIONAL;
ctx->nRepeatOvlsKept++;
enabled += 1;
}
}
}
if (enabled)
{
return 1;
}
}
if (ctx->rm_mode < 3)
{
return 1;
}
int prevb = -1;
int distinctb = 1;
for (i = 0; i < novl; i++)
{
Overlap* ovl = ovls + i;
int b = ovl->bread;
if ((ovl->flags & exclude_mask) || (left == 0 && ovl->path.abpos != trim_ab) || (right == 0 && ovl->path.aepos != trim_ae))
{
continue;
}
if (prevb != b)
{
distinctb += 1;
prevb = b;
}
}
if (distinctb < ctx->rm_cov)
{
prevb = -1;
int maxbidx = -1;
int maxblen = -1;
for (i = 0; i < novl; i++)
{
Overlap* ovl = ovls + i;
int b = ovl->bread;
int len = ovl->path.aepos - ovl->path.abpos;
if ((ovl->flags & exclude_mask) || (left == 0 && ovl->path.abpos != trim_ab) || (right == 0 && ovl->path.aepos != trim_ae))
{
continue;
}
if (prevb != b)
{
if (maxbidx != -1)
{
ovls[maxbidx].flags &= ~OVL_DISCARD;
ovls[maxbidx].flags |= OVL_OPTIONAL;
ctx->nRepeatOvlsKept++;
enabled += 1;
}
prevb = b;
maxbidx = i;
maxblen = len;
}
else
{
if (len > maxblen)
{
maxbidx = i;
maxblen = len;
}
}
}
if (maxbidx != -1)
{
ovls[maxbidx].flags &= ~OVL_DISCARD;
ovls[maxbidx].flags |= OVL_OPTIONAL;
ctx->nRepeatOvlsKept++;
enabled += 1;
}
}
return 1;
}
static void getRepeatBasesFromInterval(HITS_TRACK* repeat, int readID, int beg, int end, int *cumBases, int *largest)
{
track_anno* rep_anno = repeat->anno;
track_data* rep_data = repeat->data;
track_anno rb, re;
*cumBases = 0;
*largest = 0;
int rBeg, rEnd, tmp;
// repeat bases in a-read
rb = rep_anno[readID] / sizeof(track_data);
re = rep_anno[readID + 1] / sizeof(track_data);
while (rb < re)
{
rBeg = rep_data[rb];
rEnd = rep_data[rb + 1];
tmp = intersect(beg, end, rBeg, rEnd);
if (tmp)
{
*cumBases += tmp;
if (*largest < (rEnd - rBeg))
*largest = (rEnd - rBeg);
}
rb += 2;
}
}
static int filter(FilterContext* ctx, Overlap* ovl)
{
int nLen = ovl->path.aepos - ovl->path.abpos;
int nLenB = ovl->path.bepos - ovl->path.bbpos;
int ret = 0;
if (nLenB < nLen)
{
nLen = nLenB;
}
int trim_ab, trim_ae, trim_bb, trim_be;
int trim_alen, trim_blen;
int ovlALen = DB_READ_LEN(ctx->db, ovl->aread);
int ovlBLen = DB_READ_LEN(ctx->db, ovl->bread);
if (ctx->trackTrim)
{
get_trim(ctx->db, ctx->trackTrim, ovl->aread, &trim_ab, &trim_ae);
trim_alen = trim_ae - trim_ab;
get_trim(ctx->db, ctx->trackTrim, ovl->bread, &trim_bb, &trim_be);
trim_blen = trim_be - trim_bb;
if (ovl->flags & OVL_COMP)
{
int t = trim_bb;
trim_bb = ovlBLen - trim_be;
trim_be = ovlBLen - t;
}
}
else
{
trim_ab = 0;
trim_ae = ovlALen;
trim_bb = 0;
trim_be = ovlBLen;
trim_alen = ovlALen;
trim_blen = ovlBLen;
}
// check list of discarded overlaps
if (ctx->discardedAreadList && ctx->discardedBreads)
{
int a, b;
if (ovl->aread < ovl->bread)
{
a = ovl->aread;
b = ovl->bread;
}
else
{
a = ovl->bread;
b = ovl->aread;
}
if (ctx->discardedAreadList[a])
{
int j;
for (j = 0; ctx->discardedAreadList[a][j] > -1; j++)
{
if (ctx->discardedAreadList[a][j] == b)
{
ret |= OVL_DISCARD | OVL_SYMDISCARD;
ctx->nSymDiscard++;
if (ctx->nVerbose)
{
printf("overlap (%d x %d): in list of discarded overlaps\n", ovl->aread, ovl->bread);
}
break;
}
}
}
}
if (ctx->nMinReadLength != -1 && (trim_alen < ctx->nMinReadLength || trim_blen < ctx->nMinReadLength))
{
ctx->nFilteredReadLength++;
ret |= OVL_DISCARD | OVL_RLEN;
}
if (ctx->nMinAlnLength != -1 && nLen < ctx->nMinAlnLength)
{
if (ctx->nVerbose)
{
printf("overlap %d -> %d: drop due to length %d\n", ovl->aread, ovl->bread, nLen);
}
ctx->nFilteredLength++;
ret |= OVL_DISCARD | OVL_OLEN;
}
if (ctx->nMaxUnalignedBases != -1)
{
if (((ovl->path.abpos - trim_ab) > ctx->nMaxUnalignedBases && (ovl->path.bbpos - trim_bb) > ctx->nMaxUnalignedBases) || ((trim_ae - ovl->path.aepos) > ctx->nMaxUnalignedBases && (trim_be - ovl->path.bepos) > ctx->nMaxUnalignedBases))
{
if (ctx->nVerbose)
{
printf("overlap %d -> %d: drop due to unaligned overhang [%d, %d -> trim %d, %d], [%d, %d -> trim %d, %d]\n", ovl->aread, ovl->bread, ovl->path.abpos, ovl->path.aepos, trim_ab, trim_ae, ovl->path.bbpos, ovl->path.bepos, trim_bb, trim_be);
}
ctx->nFilteredUnalignedBases++;
ret |= OVL_DISCARD | OVL_LOCAL;
}
}
if (ctx->fMaxDiffs > 0 && ctx->remUpToXPercAln == 0)
{
if (1.0 * ovl->path.diffs / nLen > ctx->fMaxDiffs)
{
if (ctx->nVerbose)
{
printf("overlap %d -> %d: drop due to diffs %d length %d\n", ovl->aread, ovl->bread, ovl->path.diffs, nLen);
}
ctx->nFilteredDiffs++;
ret |= OVL_DISCARD | OVL_DIFF;
}
}
if (ctx->nMinNonRepeatBases != -1)
{
if (ctx->trackDust)
{
int i;
int anchorBases = 0;
for (i = 0; i < ctx->curItv; i++)
{
anchorBases += intersect(ovl->path.abpos, ovl->path.aepos, ctx->uniqIntervals[i].beg, ctx->uniqIntervals[i].end);
if (ovl->aread == 8221478)
printf("repeat %d %d [%d, %d] %d\n", ovl->aread, ovl->bread, ctx->uniqIntervals[i].beg, ctx->uniqIntervals[i].end, anchorBases);
}
if (anchorBases < ctx->nMinNonRepeatBases)
{
if (ctx->nVerbose)
{
printf("overlap %d -> %d: drop due to repeat in b\n", ovl->aread, ovl->bread);
}
ctx->nFilteredRepeat++;
ret |= OVL_DISCARD | OVL_REPEAT;
}
}
else
{
int b, e, rb, re, ovllen, repeat;
track_anno* repeats_anno = ctx->trackRepeat->anno;
track_data* repeats_data = ctx->trackRepeat->data;
int rp_mergeTip_ab = trim_ab;
int rp_mergeTip_ae = trim_ae;
if (ctx->rp_mergeTips)
{
int cumRep = 0;
b = repeats_anno[ovl->aread] / sizeof(track_data);
e = repeats_anno[ovl->aread + 1] / sizeof(track_data);
while (b < e)
{
rb = repeats_data[b];
re = repeats_data[b + 1];
// ignore repeats starting behind rp_mergeTip offset
if (rb > trim_ab + ctx->rp_mergeTips)
break;
// ignore repeat in front of trim intervaL
if (re < trim_ab)
{
b += 2;
continue;
}
if (rb < trim_ab)
{
cumRep += re - trim_ab;
}
else
{
cumRep += re - rb;
}
if (re > trim_ab + ctx->rp_mergeTips)
break;
b += 2;
}
if (cumRep > 1 + ctx->rp_mergeTips / 3)
{
rp_mergeTip_ab = trim_ab + ctx->rp_mergeTips;
}
// check end of the Aread
cumRep = 0;
b = repeats_anno[ovl->aread] / sizeof(track_data);
e = repeats_anno[ovl->aread + 1] / sizeof(track_data);
while (b < e)
{
rb = repeats_data[b];
re = repeats_data[b + 1];
// ignore repeats that end before trim_ae - rp_mergeTip offset
if (re < trim_ae - ctx->rp_mergeTips)
{
b += 2;
continue;
}
// ignore repeat behind end of trim intervaL
if (rb > trim_ae)
{
break;
}
if (re > trim_ae)
{
cumRep += trim_ae - rb;
}
else
{
cumRep += re - rb;
}
b += 2;
}
if (cumRep > 1 + ctx->rp_mergeTips / 3)
{
rp_mergeTip_ae = trim_ae - ctx->rp_mergeTips;
}
}
if (rp_mergeTip_ae < rp_mergeTip_ab)
{
if (ctx->nVerbose)
{
printf("overlap %d -> %d: drop due to repeat in a\n", ovl->aread, ovl->bread);
}
ctx->nFilteredRepeat++;
ret |= OVL_DISCARD | OVL_REPEAT;
}
if (!(ret & OVL_REPEAT))
{
// Check A-read !!!!
ovllen = MIN(ovl->path.aepos, rp_mergeTip_ae) - MAX(ovl->path.abpos, rp_mergeTip_ab);
repeat = 0;
if (ovllen < ctx->nMinNonRepeatBases)
{
if (ctx->nVerbose)
{
printf("overlap %d -> %d: drop due to repeat in a\n", ovl->aread, ovl->bread);
}
ctx->nFilteredRepeat++;
ret |= OVL_DISCARD | OVL_REPEAT;
}
}
if (!(ret & OVL_REPEAT))
{
b = repeats_anno[ovl->aread] / sizeof(track_data);
e = repeats_anno[ovl->aread + 1] / sizeof(track_data);
while (b < e)
{
rb = repeats_data[b];
re = repeats_data[b + 1];
if (re < rp_mergeTip_ab || rb > rp_mergeTip_ae)
{
b += 2;
continue;
}
if (rb < rp_mergeTip_ab)
{
rb = rp_mergeTip_ab;
}
if (re > rp_mergeTip_ae)
{
re = rp_mergeTip_ae;
}
repeat += intersect(ovl->path.abpos, ovl->path.aepos, rb, re);
b += 2;
}
if (repeat > 0 && ovllen - repeat < ctx->nMinNonRepeatBases)
{
if (ctx->nVerbose)
{
printf("overlap %d -> %d: drop due to repeat in a\n", ovl->aread, ovl->bread);
}
ctx->nFilteredRepeat++;
ret |= OVL_DISCARD | OVL_REPEAT;
}
}
if (!(ret & OVL_REPEAT))
{
// check B-Read only if we don't know yet if overlap is discarded by repeat
b = repeats_anno[ovl->bread] / sizeof(track_data);
e = repeats_anno[ovl->bread + 1] / sizeof(track_data);
// roughly map rp_mergeTip positions to B-read
ovllen = ovl->path.bepos - ovl->path.bbpos;
if (ovl->path.aepos > rp_mergeTip_ae)
ovllen -= (ovl->path.aepos - rp_mergeTip_ae);
if (ovl->path.abpos < rp_mergeTip_ab)
ovllen -= (rp_mergeTip_ab - ovl->path.abpos);
if (ovllen < ctx->nMinNonRepeatBases)
{
if (ctx->nVerbose)
{
printf("overlap %d -> %d: drop due to repeat in a\n", ovl->aread, ovl->bread);
}
ctx->nFilteredRepeat++;
ret |= OVL_DISCARD | OVL_REPEAT;
}
}
if (!(ret & OVL_REPEAT))
{
int bbpos, bepos;
if (ovl->flags & OVL_COMP)
{
if (ovl->path.aepos > rp_mergeTip_ae)
bbpos = ovlBLen - (ovl->path.bepos - (ovl->path.aepos - rp_mergeTip_ae));
else
bbpos = ovlBLen - ovl->path.bepos;
if (ovl->path.abpos < rp_mergeTip_ab)
bepos = ovlBLen - (ovl->path.bbpos - (rp_mergeTip_ab - ovl->path.abpos));
else
bepos = ovlBLen - ovl->path.bbpos;
}
else
{
bbpos = ovl->path.bbpos;
if (ovl->path.abpos < rp_mergeTip_ab)
bbpos += rp_mergeTip_ab - ovl->path.abpos;
bepos = ovl->path.bepos;
if (ovl->path.aepos > rp_mergeTip_ae)
bepos -= ovl->path.aepos - rp_mergeTip_ae;
}
repeat = 0;
while (b < e)
{
rb = repeats_data[b];
re = repeats_data[b + 1];
repeat += intersect(bbpos, bepos, rb, re);
b += 2;
}
if (repeat > 0 && ovllen - repeat < ctx->nMinNonRepeatBases)
{
if (ctx->nVerbose)
{
printf("overlap %d -> %d: drop due to repeat in b\n", ovl->aread, ovl->bread);
}
ctx->nFilteredRepeat++;
ret |= OVL_DISCARD | OVL_REPEAT;
}
}
}
}
// check tracepoints
if (!(ovl->flags & OVL_DISCARD) && (ctx->removeFlags & REMOVE_TP))
{
ovl_trace* trace = (ovl_trace*) ovl->path.trace;
int bpos = ovl->path.bbpos;
int j;
for (j = 0; j < ovl->path.tlen; j += 2)
{
bpos += trace[j + 1];
}
if (bpos != ovl->path.bepos)
{
ret |= OVL_DISCARD;
if (ctx->nVerbose)
{
printf("overlap (%d x %d): pass-through points inconsistent be = %d (expected %d)\n", ovl->aread, ovl->bread, bpos, ovl->path.bepos);
}
}
}
return ret;
}
static void write_spanning_reads(FilterContext* ctx, int aread)
{
int b, e, rb, re;
int trim_ab, trim_ae;
track_anno* repeats_anno = ctx->trackRepeat->anno;
track_data* repeats_data = ctx->trackRepeat->data;
if (ctx->trackTrim)
{
get_trim(ctx->db, ctx->trackTrim, aread, &trim_ab, &trim_ae);
}
else
{
trim_ab = 0;
trim_ae = DB_READ_LEN(ctx->db, aread);
}
b = repeats_anno[aread] / sizeof(track_data);
e = repeats_anno[aread + 1] / sizeof(track_data);
int minbases = MAX(ctx->nMinNonRepeatBases, 300);
while (b < e)
{
rb = repeats_data[b];
re = repeats_data[b + 1];
if (rb - minbases > trim_ab && re + minbases < trim_ae)
{
fprintf(ctx->fileSpanningReads, "%d %d\n", aread, re - rb);
}
b += 2;
}
}
static void filter_pre(PassContext* pctx, FilterContext* fctx)
{
#ifdef VERBOSE
printf( ANSI_COLOR_GREEN "PASS filtering\n" ANSI_COLOR_RESET);
#endif
fctx->twidth = pctx->twidth;
// trim
if (fctx->do_trim)
{
fctx->trim = trim_init(fctx->db, pctx->twidth, fctx->trackTrim, fctx->rl);
}
// repeat modules
fctx->rm_anno = (track_anno*) malloc(sizeof(track_anno) * ( DB_NREADS( fctx->db ) + 1));
bzero(fctx->rm_anno, sizeof(track_anno) * ( DB_NREADS( fctx->db ) + 1));
fctx->rm_ndata = 0;
fctx->rm_maxdata = 100;
fctx->rm_data = (track_data*) malloc(sizeof(track_data) * fctx->rm_maxdata);
fctx->rm_maxbins = ( DB_READ_MAXLEN( fctx->db ) + BIN_SIZE) / BIN_SIZE;
fctx->rm_bins = malloc(sizeof(uint64_t) * fctx->rm_maxbins);
fctx->le_maxbins = ( DB_READ_MAXLEN( fctx->db ) + BIN_SIZE) / BIN_SIZE;
fctx->le_lbins = malloc(sizeof(int) * fctx->le_maxbins);
fctx->le_rbins = malloc(sizeof(int) * fctx->le_maxbins);
if (fctx->trackDust)
{
fctx->numIntervals = 20;
fctx->uniqIntervals = malloc(sizeof(anchorItv) * fctx->numIntervals);
bzero(fctx->uniqIntervals, sizeof(anchorItv) * fctx->numIntervals);
fctx->curItv = 0;
}
}
static void filter_post(FilterContext* ctx)
{
#ifdef VERBOSE
if (ctx->trim)
{
printf("trimmed %'lld of %'lld overlaps\n", ctx->trim->nTrimmedOvls, ctx->trim->nOvls);
printf("trimmed %'lld of %'lld bases\n", ctx->trim->nTrimmedBases, ctx->trim->nOvlBases);
}
if (ctx->nFilteredContainedOvls > 0)
{
printf("contained overlaps discarded %10d\n", ctx->nFilteredContainedOvls);
}
if (ctx->nFilteredReadLength > 0)
{
printf("min read length of %5d discarded %10d\n", ctx->nMinReadLength, ctx->nFilteredReadLength);
}
if (ctx->nFilteredRepeat > 0)
{
printf("min non-repeat bases of %4d discarded %10d\n", ctx->nMinNonRepeatBases, ctx->nFilteredRepeat);
}
if (ctx->nRepeatOvlsKept > 0)
{
printf(" kept %d repeat overlaps (mode %d)\n", ctx->nRepeatOvlsKept, ctx->rm_mode);
}
if (ctx->nFilteredDiffs > 0)
{
printf("diff threshold of %.1f discarded %d\n", ctx->fMaxDiffs * 100., ctx->nFilteredDiffs);
}
if (ctx->nFilteredDiffsSegments > 0)
{
printf("diff threshold of %3.1f on segments discarded %10d\n", ctx->fMaxDiffs * 100., ctx->nFilteredDiffsSegments);
}
if (ctx->nFilteredLength > 0)
{
printf("min overlap length of %d discarded %10d\n", ctx->nMinAlnLength, ctx->nFilteredLength);
}
if (ctx->nFilteredUnalignedBases > 0)
{
printf("unaligned bases threshold of %4d discarded %10d\n", ctx->nMaxUnalignedBases, ctx->nFilteredUnalignedBases);
}
if (ctx->nMultiMapper > 0)
{
printf("multiMapper of %4d discarded %10d\n", ctx->nMultiMapper, ctx->nMultiMapperBases);
}
if (ctx->nStitched > 0)
{
printf("stitched %4d at fuzzing of %10d\n", ctx->nStitched, ctx->stitch);
}
if (ctx->nFilteredLocalEnd)
{
printf("local ends discarded %10d\n", ctx->nFilteredLocalEnd);
}
if (ctx->nLowCovALn)
{
printf("low tip coverage of <%2d discarded %10d\n", ctx->removeLowCoverageOverlaps, ctx->nLowCovALn);
}
if (ctx->nSymDiscard)
{
printf("symmetrically remove discarded overlaps %10d\n", ctx->nSymDiscard);
}
if (ctx->nCovFiltReads)
{
printf("coverage filtered reads %4d -> overlaps %10lld -> bases %10lld\n", ctx->nCovFiltReads, ctx->nCovFiltOverlaps, ctx->nCovFiltBases);
}
#endif
if (ctx->trim)
{
trim_close(ctx->trim);
}
free(ctx->le_lbins);
free(ctx->le_rbins);
free(ctx->rm_bins);
free(ctx->rm_anno);
free(ctx->rm_data);
if (ctx->discardedBreads)
free(ctx->discardedBreads);
if (ctx->discardedAreadList)
free(ctx->discardedAreadList);
if (ctx->trackDust)
free(ctx->uniqIntervals);
}
static int cmp_ovls_qual(const void* a, const void* b)
{
Overlap* o1 = *(Overlap**) a;
Overlap* o2 = *(Overlap**) b;
return ((100 - (o1->path.diffs * 100.0 / (o1->path.aepos - o1->path.abpos))) * 10 - (100 - (o2->path.diffs * 100.0 / (o2->path.aepos - o2->path.abpos))) * 10);
}
static void removeChimerOvls(FilterContext* ctx, Overlap *ovl, int novl)
{
#ifdef DEBUG_CHIMER
printf("CHIMER: a[%d] minCov %d minAnchor: %d\n", ovl->aread, ctx->chimerCoverage, ctx->chimerAnchorBases);
#endif
int trimABeg = 0;
int trimAEnd = DB_READ_LEN(ctx->db, ovl->aread);
if (ctx->trackTrim)
get_trim(ctx->db, ctx->trackTrim, ovl->aread, &trimABeg, &trimAEnd);
int i, j;
if (novl < ctx->chimerCoverage)
{
#ifdef DEBUG_CHIMER
printf("CHIMER: a[%d] has less then chimerCoverage (%d) overlaps (%d)\n", ovl->aread, ctx->chimerCoverage, novl);
#endif
for (i = 0; i < novl; i++)
{
ovl[i].flags |= OVL_DISCARD;
#ifdef DEBUG_CHIMER
printf("CHIMER: discard %d vs %d a[%d, %d] %c b[%d, %d]\n", ovl[i].aread, ovl[i].bread, ovl[i].path.abpos, ovl[i].path.aepos, (ovl[i].flags & OVL_COMP) ? 'c' : 'n', ovl[i].path.bbpos, ovl[i].path.bepos);
#endif
}
}
// check if trim interval fits to alignments
i = j = 0;
int left = trimAEnd;
int right = trimABeg;
int numMostLeftLAS = 0;
int numMostRightLAS = 0;
while (i < novl)
{
if (!(ovl[i].flags & OVL_DISCARD))
{
if (ovl[i].path.abpos < left)
{
left = ovl[i].path.abpos;
j = i;
numMostLeftLAS = 1;
}
else if (ovl[i].path.abpos == left)
{
if (ovl[i].path.aepos > ovl[j].path.aepos)
j = i;
numMostLeftLAS++;
}
if (ovl[i].path.aepos > right)
{
right = ovl[i].path.aepos;
numMostRightLAS = 1;
}
else if (ovl[i].path.aepos == right)
{
numMostRightLAS++;
}
}
i++;
}
if (left == trimAEnd)
{
#ifdef DEBUG_CHIMER
printf("CHIMER: Nothing todo all reads already discarded OR trim track does not correspond to LAS file\n");
#endif
return;
}
if(numMostLeftLAS < ctx->chimerCoverage || numMostRightLAS < ctx->chimerCoverage)
{
#ifdef DEBUG_CHIMER
printf("CHIMER: Number of entering/leaving overlaps of trim interval is lower than non-chimeric minimum number of overlaps L(%d) || R (%d) < %d\n", numMostLeftLAS, numMostRightLAS, ctx->chimerCoverage);
#endif
for (i = 0; i < novl; i++)
{
ovl[i].flags |= OVL_DISCARD;
#ifdef DEBUG_CHIMER
printf("CHIMER: discard %d vs %d a[%d, %d] %c b[%d, %d]\n", ovl[i].aread, ovl[i].bread, ovl[i].path.abpos, ovl[i].path.aepos, (ovl[i].flags & OVL_COMP) ? 'c' : 'n', ovl[i].path.bbpos, ovl[i].path.bepos);
#endif
}
return;
}
Overlap * o1 = ovl + j;
Overlap * o3 = ovl + j;
while (o1->path.aepos < right)
{
int curCov = 0;
for (i = 0; i < novl; i++)
{
Overlap * o2 = ovl + i;
if (o2->flags == OVL_DISCARD)
continue;
#ifdef DEBUG_CHIMER
printf("CHIMER: check position [%d] curCov [%d] ovl b%d a[%d, %d] %c b[%d, %d]\n", o1->path.aepos, curCov, o2->bread, o2->path.abpos, o2->path.aepos, (o2->flags & OVL_COMP) ? 'c' : 'n', o2->path.bbpos, o2->path.bepos);
#endif
if (o1->path.aepos == right)
{
#ifdef DEBUG_CHIMER
printf("CHIMER: skip trimAEnd position a[%d, %d] %c b[%d, %d]\n", o1->path.abpos, o1->path.aepos, (o1->flags & OVL_COMP) ? 'c' : 'n', o1->path.bbpos, o1->path.bepos);
#endif
curCov = ctx->chimerCoverage;
break;
}
if (o1->path.aepos == right)
{
#ifdef DEBUG_CHIMER
printf("CHIMER: found fully spanning B-read %d. Skip chimer detection! a[%d, %d] %c b[%d, %d]\n", o1->bread, o1->path.abpos, o1->path.aepos, (o1->flags & OVL_COMP) ? 'c' : 'n', o1->path.bbpos, o1->path.bepos);
#endif
curCov = ctx->chimerCoverage;
break;
}
if (o2->path.abpos <= o1->path.aepos - MIN(ctx->chimerAnchorBases, o1->path.aepos - left) && o2->path.aepos >= o1->path.aepos + MIN(ctx->chimerAnchorBases, right - o1->path.aepos))
{
curCov++;
#ifdef DEBUG_CHIMER
printf("CHIMER: anchorCov %d (a[%d, %d] %c b[%d, %d])\n", curCov, o2->path.abpos, o2->path.aepos, (o2->flags & OVL_COMP) ? 'c' : 'n', o2->path.bbpos, o2->path.bepos);
#endif
if (o2->path.aepos > o3->path.aepos)
{
#ifdef DEBUG_CHIMER
printf("CHIMER: mark overlap with largest aepos! a[%d, %d] %c b[%d, %d]\n", o2->path.abpos, o2->path.aepos, (o2->flags & OVL_COMP) ? 'c' : 'n', o2->path.bbpos, o2->path.bepos);
#endif
o3 = o2;
}
}
if (curCov >= ctx->chimerCoverage)
{
#ifdef DEBUG_CHIMER
printf("CHIMER: No chimer at %d anchorCov %d\n", o1->path.aepos, curCov);
#endif
curCov = 0;
o1 = o3;
}
}
if (curCov < ctx->chimerCoverage)
{
#ifdef DEBUG_CHIMER
printf("CHIMER: found chimer at position %d. Remove all overlaps.\n", o1->path.aepos);
#endif
for (i = 0; i < novl; i++)
{
ovl[i].flags |= OVL_DISCARD;
#ifdef DEBUG_CHIMER
printf("CHIMER: discard %d vs %d a[%d, %d] %c b[%d, %d]\n", ovl[i].aread, ovl[i].bread, ovl[i].path.abpos, ovl[i].path.aepos, (ovl[i].flags & OVL_COMP) ? 'c' : 'n', ovl[i].path.bbpos, ovl[i].path.bepos);
#endif
}
break;
}
}
}
static void removeWorstAlignments(FilterContext* ctx, Overlap* ovl, int novl)
{
int i;
Overlap** ovl_sort = (Overlap**) malloc(sizeof(Overlap*) * novl);
int numIncomingReads, numLeavingReads;
int cumOverallBases;
numIncomingReads = numLeavingReads = cumOverallBases = 0;
int trimABeg, trimAEnd;
trimABeg = 0;
trimAEnd = DB_READ_LEN(ctx->db, ovl->aread);
if (ctx->trackTrim)
get_trim(ctx->db, ctx->trackTrim, ovl->aread, &trimABeg, &trimAEnd);
int aTrimLen = trimAEnd - trimABeg;
for (i = 0; i < novl; i++)
{
ovl_sort[i] = ovl + i;
if (ovl_sort[i]->flags & OVL_DISCARD)
continue;
if (ovl_sort[i]->path.abpos <= trimABeg)
numIncomingReads += 1;
if (ovl_sort[i]->path.aepos >= trimAEnd)
numLeavingReads += 1;
cumOverallBases += ovl_sort[i]->path.aepos - ovl_sort[i]->path.abpos;
}
if (ctx->nVerbose)
printf("Coverage[%d]: beg,end [%3d, %3d] avgCov %.2f\n", ovl->aread, numIncomingReads, numLeavingReads, cumOverallBases * 1.0 / aTrimLen);
qsort(ovl_sort, novl, sizeof(Overlap*), cmp_ovls_qual);
// todo hard coded
int MinTipCov = MIN(3, ctx->removeLowCoverageOverlaps);
int MaxRemovedAlnBasesPerc = ctx->remUpToXPercAln;
float maxQV = (ctx->fMaxDiffs > 0) ? ctx->fMaxDiffs : 28;
int removeAlnBases = 0;
int numRemovedIncomingReads, numRemovedLeavingReads;
numRemovedIncomingReads = numRemovedLeavingReads = 0;
for (i = 0; i < novl; i++)
{
Overlap* so = ovl_sort[i];
if (so->flags & OVL_DISCARD)
continue;
int err = (int) (so->path.diffs * 100.0 / MIN(so->path.aepos - so->path.abpos, so->path.bepos - so->path.bbpos));
if (so->path.abpos <= trimABeg)
numRemovedIncomingReads++;
if (so->path.aepos >= trimAEnd)
numRemovedLeavingReads++;
removeAlnBases += so->path.aepos - so->path.abpos;
if (removeAlnBases * 100.0 / cumOverallBases < MaxRemovedAlnBasesPerc && numIncomingReads - numRemovedIncomingReads >= MinTipCov && numLeavingReads - numRemovedLeavingReads >= MinTipCov)
{
so->flags |= OVL_DISCARD | OVL_DIFF;
ctx->nFilteredDiffs += 1;
if (ctx->nVerbose)
printf("DISCARD %d%% bad overlaps [%d, %d] a[%d, %d] b [%d, %d] %c ODIF %d\n", MaxRemovedAlnBasesPerc, so->aread, so->bread, so->path.abpos, so->path.aepos, so->path.bbpos, so->path.bepos, (so->flags & OVL_COMP) ? 'C' : 'N', err);
}
else
{
if (ctx->nVerbose)
printf("DO NOT DISCARD %d%% bad overlaps [%d, %d] a[%d, %d] b [%d, %d] %c ODIF %d\n", MaxRemovedAlnBasesPerc, so->aread, so->bread, so->path.abpos, so->path.aepos, so->path.bbpos, so->path.bepos, (so->flags & OVL_COMP) ? 'C' : 'N', err);
break;
}
if (err < maxQV)
{
if (ctx->nVerbose)
printf("STOP reached maxqv of %d [%d, %d] a[%d, %d] b [%d, %d] %c\n", err, so->aread, so->bread, so->path.abpos, so->path.aepos, so->path.bbpos, so->path.bepos, (so->flags & OVL_COMP) ? 'C' : 'N');
break;
}
}
free(ovl_sort);
}
static int cmp_aIvl(const void *a, const void *b)
{
anchorItv * a1 = (anchorItv*) a;
anchorItv * a2 = (anchorItv*) b;
if (a1->flag & ANCHOR_INVALID)
{
return 1;
}
if (a2->flag & ANCHOR_INVALID)
{
return -1;
}
return a1->beg - a2->beg;
}
static void analyzeRepeatIntervals(FilterContext *ctx, int aread)
{
int trim_ab, trim_ae;
int trim_alen;
int arlen = DB_READ_LEN(ctx->db, aread);
trim_ab = 0;
trim_ae = arlen;
if (ctx->trackTrim)
{
get_trim(ctx->db, ctx->trackTrim, aread, &trim_ab, &trim_ae);
trim_alen = trim_ae - trim_ab;
}
else
{
trim_ab = 0;
trim_ae = arlen;
trim_alen = arlen;
}
int MINANCHOR = 10;
int WINDOW = ctx->mergeRepeatsWindow;
int MAXMERGE = ctx->mergeRepeatsMaxLen;
int i, b, e;
track_anno* repeats_anno = ctx->trackRepeat->anno;
track_data* repeats_data = ctx->trackRepeat->data;
b = repeats_anno[aread] / sizeof(track_data);
e = repeats_anno[aread + 1] / sizeof(track_data);
if (ctx->numIntervals < (e - b + 1) + 4)
{
ctx->numIntervals = (e - b + 1) + 4;
ctx->uniqIntervals = (anchorItv*) realloc(ctx->uniqIntervals, ctx->numIntervals * sizeof(anchorItv));
}
// reset current anchor interval index
ctx->curItv = 0;
bzero(ctx->uniqIntervals, sizeof(anchorItv) * (ctx->numIntervals));
int anchorbases = 0;
if (b < e)
{
int rb1, rb2;
int re1, re2;
rb1 = repeats_data[b];
re1 = repeats_data[b + 1];
if (rb1 > 0 && rb1 > MINANCHOR)
{
ctx->uniqIntervals[ctx->curItv].beg = 0;
ctx->uniqIntervals[ctx->curItv].end = rb1;
ctx->curItv++;
}
b += 2;
while (b < e)
{
rb2 = repeats_data[b];
re2 = repeats_data[b + 1];
if (rb2 - re1 > MINANCHOR)
{
ctx->uniqIntervals[ctx->curItv].beg = re1;
ctx->uniqIntervals[ctx->curItv].end = rb2;
ctx->curItv++;
}
rb1 = rb2;
re1 = re2;
b += 2;
}
if (re1 < arlen && arlen - re1 > MINANCHOR)
{
ctx->uniqIntervals[ctx->curItv].beg = re1;
ctx->uniqIntervals[ctx->curItv].end = arlen;
ctx->curItv++;
}
anchorbases = 0;
printf("#anchors_0 %d", aread);
for (i = 0; i < ctx->curItv; i++)
{
anchorItv *a = ctx->uniqIntervals + i;
if (a->flag & ANCHOR_INVALID)
continue;
printf(" %d-%d-%d", a->beg, a->end, a->flag);
anchorbases += a->end - a->beg;
}
printf(" sum n%d b%d\n", i, anchorbases);
// update unique intervals based on trim track
if (trim_ab > 0 || trim_ae < arlen)
{
for (i = 0; i < ctx->curItv; i++)
{
anchorItv *a = ctx->uniqIntervals + i;
if (trim_ab >= a->end)
{
a->flag |= (ANCHOR_TRIM | ANCHOR_INVALID);
}
else if (trim_ab > a->beg)
{
a->beg = trim_ab;
}
if (a->beg >= trim_ae)
{
a->flag |= (ANCHOR_TRIM | ANCHOR_INVALID);
}
else if (a->end > trim_ae)
{
a->end = trim_ae;
}
}
}
anchorbases = 0;
printf("#anchors_1 %d", aread);
for (i = 0; i < ctx->curItv; i++)
{
anchorItv *a = ctx->uniqIntervals + i;
if (a->flag & ANCHOR_INVALID)
continue;
printf(" %d-%d-%d", a->beg, a->end, a->flag);
anchorbases += a->end - a->beg;
}
printf(" sum n%d b%d\n", i, anchorbases);
// update unique intervals based on low complexity and tandem repeat
// todo hardcoded values !!!
int predust, dust, postdust, longestDust, longestDustl, longestDustr;
for (i = 0; i < ctx->curItv; i++)
{
anchorItv *a = ctx->uniqIntervals + i;
if (a->flag & ANCHOR_INVALID)
continue;
if (a->end - a->beg > MAXMERGE)
continue;
getRepeatBasesFromInterval(ctx->trackDust, aread, a->beg, a->end, &dust, &longestDust);
if (dust * 100.0 / (a->end - a->beg) > 50.0)
{
a->flag |= (ANCHOR_LOWCOMP | ANCHOR_INVALID);
}
else if (dust * 100.0 / (a->end - a->beg) > 15.0 && longestDust > 100)
{
a->flag |= (ANCHOR_LOWCOMP | ANCHOR_INVALID);
}
else if ((a->end - a->beg) < 100 && longestDust > 20)
{
a->flag |= (ANCHOR_LOWCOMP | ANCHOR_INVALID);
}
else // check if neighboring repeats end in low complexity interval
{
int checkFlanks = MIN(100, WINDOW);
while (checkFlanks <= WINDOW)
{
getRepeatBasesFromInterval(ctx->trackDust, aread, MAX(0, a->beg - checkFlanks), a->beg, &predust, &longestDustl);
getRepeatBasesFromInterval(ctx->trackDust, aread, a->end, MIN(a->end + checkFlanks, arlen), &postdust, &longestDustr);
if ((predust * 100.0 / checkFlanks > 20.0 && longestDustl > 30) || (postdust * 100 / checkFlanks > 20.0 && longestDustr > 30))
{
a->flag |= (ANCHOR_LOWCOMP | ANCHOR_INVALID);
break;
}
if (checkFlanks < WINDOW && checkFlanks + 100 > WINDOW)
checkFlanks = WINDOW;
else
checkFlanks += 100;
}
}
printf("#LC %d %d %d f%d PRE %d %d %.2f DUST %d %d %.2f post %d %d %.2f SUM %d %d %.2f\n", aread, a->beg, a->end, a->flag, predust, a->beg - MAX(0, a->beg - WINDOW), predust * 100.0 / (a->beg - MAX(0, a->beg - WINDOW)), dust, a->end - a->beg, dust * 100.0 / (a->end - a->beg), postdust,
MIN(a->end + WINDOW, arlen) - a->end, postdust * 100.0 / (MIN(a->end + WINDOW, arlen) - a->end), predust + dust + postdust, (a->beg - MAX(0, a->beg - WINDOW)) + (a->end - a->beg) + (MIN(a->end + WINDOW, arlen) - a->end),
(predust + dust + postdust) * 100.0 / ((a->beg - MAX(0, a->beg - WINDOW)) + (a->end - a->beg) + (MIN(a->end + WINDOW, arlen) - a->end)));
}
}
else // add full read interval as uniq range
{
ctx->uniqIntervals[0].beg = trim_ab;
ctx->uniqIntervals[0].end = trim_ae;
ctx->curItv++;
}
anchorbases = 0;
printf("#anchors_2 %d", aread);
for (i = 0; i < ctx->curItv; i++)
{
anchorItv *a = ctx->uniqIntervals + i;
if (a->flag & ANCHOR_INVALID)
continue;
printf(" %d-%d-%d", a->beg, a->end, a->flag);
anchorbases += a->end - a->beg;
}
printf(" sum n%d b%d\n", i, anchorbases);
repeats_anno = ctx->trackDust->anno;
repeats_data = ctx->trackDust->data;
b = repeats_anno[aread] / sizeof(track_data);
e = repeats_anno[aread + 1] / sizeof(track_data);
int rb, re;
// update unique anchors with all low complexity intervals !!!
int c = ctx->curItv;
for (i = 0; i < c; i++)
{
if (ctx->uniqIntervals[i].flag & ANCHOR_INVALID)
continue;
printf("check valid unique region %d, %d\n", ctx->uniqIntervals[i].beg, ctx->uniqIntervals[i].end);
while (b < e)
{
rb = repeats_data[b];
re = repeats_data[b + 1];
printf("check dust region [%d, %d]\n", rb, re);
if (rb > ctx->uniqIntervals[i].end)
{
printf("dust behind unique region %d, %d\n", ctx->uniqIntervals[i].beg, ctx->uniqIntervals[i].end);
break;
}
if (re < ctx->uniqIntervals[i].beg)
{
printf("dust before unique region %d, %d\n", ctx->uniqIntervals[i].beg, ctx->uniqIntervals[i].end);
b += 2;
continue;
}
// dust fully covers unique part
if (rb <= ctx->uniqIntervals[i].beg && re >= ctx->uniqIntervals[i].end)
{
printf("dust fully covers unique region %d, %d\n", ctx->uniqIntervals[i].beg, ctx->uniqIntervals[i].end);
ctx->uniqIntervals[i].flag |= (ANCHOR_LOWCOMP | ANCHOR_INVALID);
break;
}
// dust aligns left with unique part
if (rb <= ctx->uniqIntervals[i].beg)
{
ctx->uniqIntervals[i].beg = re;
}
// dust aligns with right unique part
if (re >= ctx->uniqIntervals[i].end)
{
ctx->uniqIntervals[i].end = rb;
}
// dust splits uniq part, i.e. make unique part invalid an append splits to the end of uniqueIntervals
printf("dust %d,%d splits unique range %d, %d\n", rb, re, ctx->uniqIntervals[i].beg, ctx->uniqIntervals[i].end);
printf("curItv %d >= numIntervals %d\n", ctx->curItv, ctx->numIntervals);
if (ctx->curItv >= ctx->numIntervals)
{
ctx->numIntervals = 1.2 * ctx->numIntervals + 10;
ctx->uniqIntervals = (anchorItv*) realloc(ctx->uniqIntervals, sizeof(anchorItv) * ctx->numIntervals);
bzero(ctx->uniqIntervals + ctx->curItv, sizeof(anchorItv) * (ctx->numIntervals - ctx->curItv));
}
printf("curItv %d >= numIntervals %d\n", ctx->curItv, ctx->numIntervals);
ctx->uniqIntervals[ctx->curItv].beg = ctx->uniqIntervals[i].beg;
ctx->uniqIntervals[ctx->curItv].end = rb;
ctx->uniqIntervals[i].beg = re;
printf(" decrease cutItv_%d: [%d, %d] append new interval %d [%d, %d] f%d\n", i, ctx->uniqIntervals[i].beg, ctx->uniqIntervals[i].end, ctx->curItv, ctx->uniqIntervals[ctx->curItv].beg, ctx->uniqIntervals[ctx->curItv].end, ctx->uniqIntervals[ctx->curItv].flag);
ctx->curItv++;
b += 2;
}
}
anchorbases = 0;
printf("#anchors_3 %d", aread);
for (i = 0; i < ctx->curItv; i++)
{
anchorItv *a = ctx->uniqIntervals + i;
// if (a->flag & ANCHOR_INVALID)
// continue;
printf(" %d-%d-%d", a->beg, a->end, a->flag);
anchorbases += a->end - a->beg;
}
printf(" sum n%d b%d\n", i, anchorbases);
qsort(ctx->uniqIntervals, ctx->curItv, sizeof(anchorItv), cmp_aIvl);
for (i = 0; i < ctx->curItv; i++)
{
anchorItv *a = ctx->uniqIntervals + i;
if (a->flag & ANCHOR_INVALID)
break;
}
ctx->curItv = i;
anchorbases = 0;
printf("#anchors_3s %d", aread);
for (i = 0; i < ctx->curItv; i++)
{
anchorItv *a = ctx->uniqIntervals + i;
if (a->flag & ANCHOR_INVALID)
break;
printf(" %d-%d-%d", a->beg, a->end, a->flag);
anchorbases += a->end - a->beg;
}
printf(" sum n%d b%d\n", i, anchorbases);
// merge tips if required, i.e. if there is any repeat annotation within the first/last 2k?! sequence
if (ctx->rp_mergeTips && ctx->curItv > 0)
{
int resort = 0;
if (ctx->uniqIntervals[0].beg > trim_ab || ctx->uniqIntervals[0].end < trim_ab + ctx->rp_mergeTips)
{
for (i = 0; i < ctx->curItv; i++)
{
anchorItv *a = ctx->uniqIntervals + i;
if (a->flag & ANCHOR_INVALID)
continue;
if (a->end < trim_ab + ctx->rp_mergeTips)
{
a->flag |= (ANCHOR_TRIM | ANCHOR_INVALID);
resort = 1;
}
else if (a->beg < trim_ab + ctx->rp_mergeTips)
{
a->beg = trim_ab + ctx->rp_mergeTips;
}
else
{
break;
}
}
}
if (ctx->uniqIntervals[ctx->curItv - 1].end < trim_ae || ctx->uniqIntervals[ctx->curItv - 1].beg > trim_ae - ctx->rp_mergeTips)
{
for (i = ctx->curItv - 1; i >= 0; --i)
{
anchorItv *a = ctx->uniqIntervals + i;
if (a->flag & ANCHOR_INVALID)
continue;
if (a->beg > trim_ae - ctx->rp_mergeTips)
{
a->flag |= (ANCHOR_TRIM | ANCHOR_INVALID);
resort = 1;
}
else if (a->end > trim_ae - ctx->rp_mergeTips)
{
a->end = trim_ae - ctx->rp_mergeTips;
}
else
{
break;
}
}
}
if (resort)
{
qsort(ctx->uniqIntervals, ctx->curItv, sizeof(anchorItv), cmp_aIvl);
for (i = 0; i < ctx->curItv; i++)
{
anchorItv *a = ctx->uniqIntervals + i;
if (a->flag & ANCHOR_INVALID)
break;
}
ctx->curItv = i;
}
}
// report final unique anchors:
anchorbases = 0;
printf("#anchors_4 %d", aread);
for (i = 0; i < ctx->curItv; i++)
{
anchorItv *a = ctx->uniqIntervals + i;
if (a->flag & ANCHOR_INVALID)
break;
printf(" %d-%d-%d", a->beg, a->end, a->flag);
anchorbases += a->end - a->beg;
}
printf(" sum n%d b%d\n", i, anchorbases);
}
static int filter_handler(void* _ctx, Overlap* ovl, int novl)
{
FilterContext* ctx = (FilterContext*) _ctx;
int j;
if (ctx->downsample)
{
int max_rid = (int) (ctx->downsample * DB_NREADS(ctx->db) / 100.0);
for (j = 0; j < novl; j++)
{
Overlap* o = ovl + j;
if (o->aread > max_rid || o->bread > max_rid)
{
o->flags |= OVL_DISCARD;
}
}
}
if (ctx->trimIndels)
{
for (j = 0; j < novl; j++)
trimOffLeadingIndels(ovl + j, ctx->twidth);
}
if (ctx->maxSegmentErrorRate >= 0 && ctx->maxSegmentErrorRate <= 100)
{
for (j = 0; j < novl; j++)
{
if (filterMaxSegmentErrorRate(ovl + j, ctx->maxSegmentErrorRate))
{
ctx->nFilteredDiffs++;
}
}
}
if (ctx->trim)
{
for (j = 0; j < novl; j++)
{
trim_overlap(ctx->trim, ovl + j);
}
}
if (ctx->stitch >= 0)
{
int k;
j = k = 0;
while (j < novl)
{
while (k < novl - 1 && ovl[j].bread == ovl[k + 1].bread)
{
k++;
}
ctx->nStitched += stitch(ovl + j, k - j + 1, ctx->stitch, ctx->stitch_aggressively);
j = k + 1;
}
}
if (ctx->trackDust)
{
analyzeRepeatIntervals(ctx, ovl->aread);
}
// set filter flags
for (j = 0; j < novl; j++)
{
ovl[j].flags |= filter(ctx, ovl + j);
}
if (ctx->removeMultiMappers)
{
int foundMultiMapper = 0;
int k, l, m;
j = k = 0;
while (j < novl)
{
while (k < novl - 1 && ovl[j].bread == ovl[k + 1].bread)
{
k++;
}
if (k > j)
{
foundMultiMapper = 0;
for (l = j; l <= k && !foundMultiMapper; l++)
{
Overlap *o1 = ovl + l;
// ignore stitched overlaps as those are contained anyway and we want to keep the non-stitched overlap !!!
if (o1->flags & (OVL_STITCH | OVL_DISCARD))
continue;
for (m = l + 1; m <= k && !foundMultiMapper; m++)
{
Overlap *o2 = ovl + m;
if (o2->flags & (OVL_STITCH | OVL_DISCARD))
continue;
if (contained(o1->path.abpos, o1->path.aepos, o2->path.abpos, o2->path.aepos) || contained(o2->path.abpos, o2->path.aepos, o1->path.abpos, o1->path.aepos) || contained(o1->path.bbpos, o1->path.bepos, o2->path.bbpos, o2->path.bepos)
|| contained(o2->path.bbpos, o2->path.bepos, o1->path.bbpos, o1->path.bepos))
{
foundMultiMapper = 1;
break;
}
}
}
if (foundMultiMapper)
{
for (l = j; l <= k; l++)
{
ovl[l].flags |= OVL_DISCARD;
#ifdef VERBOSE
printf("remove ovl, falls into multi mapper interval: %d vs %d [%d, %d] %c [%d, %d]\n", ovl[l].aread, ovl[l].bread, ovl[l].path.abpos, ovl[l].path.aepos, (ovl[l].flags & OVL_COMP) ? 'c' : 'n', ovl[l].path.bbpos, ovl[l].path.bepos);
#endif
ctx->nMultiMapper++;
ctx->nMultiMapperBases += ovl[l].path.aepos - ovl[l].path.abpos;
}
}
}
k++;
j = k;
}
}
if (ctx->remUpToXPercAln)
{
removeWorstAlignments(ctx, ovl, novl);
}
// detect weird overlaps and discard them, i.e. those that are obviously wrong but couldn't be removed with repeat annotation or local alignment filter
// TODO extract + create own function
// TODO perform tests
if (ctx->removeLowCoverageOverlaps)
{
int trimBeg, trimEnd;
trimBeg = 0;
trimEnd = DB_READ_LEN(ctx->db, ovl->aread);
if (ctx->trackTrim)
get_trim(ctx->db, ctx->trackTrim, ovl->aread, &trimBeg, &trimEnd);
if (trimEnd - trimBeg)
{
int entercov = 0;
int leavecov = 0;
int bases = 0;
char * cov_read_active = malloc(DB_READ_MAXLEN(ctx->db));
bzero(cov_read_active, DB_READ_MAXLEN(ctx->db));
for (j = 0; j < novl; j++)
{
Overlap* ovl_j = ovl + j;
if (ovl_j->flags & OVL_DISCARD)
continue;
if (ovl_j->path.abpos <= trimBeg)
entercov++;
if (ovl_j->path.aepos >= trimEnd)
leavecov++;
bases += ovl_j->path.aepos - ovl_j->path.abpos;
memset(cov_read_active + ovl_j->path.abpos, 1, ovl_j->path.aepos - ovl_j->path.abpos);
}
int active = 0;
for (j = trimBeg; j < trimEnd; j++)
{
active += cov_read_active[j];
}
if (bases / (trimEnd - trimBeg) <= ctx->removeLowCoverageOverlaps || (leavecov < ctx->removeLowCoverageOverlaps || entercov < ctx->removeLowCoverageOverlaps) || (ctx->nMaxUnalignedBases != -1 && (trimEnd - trimBeg) - active > ctx->nMaxUnalignedBases))
{
for (j = 0; j < novl; j++)
{
Overlap* ovl_j = ovl + j;
if (ovl_j->flags & OVL_DISCARD)
continue;
ovl_j->flags |= OVL_DISCARD;
ctx->nLowCovALn++;
}
}
free(cov_read_active);
}
}
// find repeat modules and rescue overlaps
if (ctx->rm_cov != -1)
{
find_repeat_modules(ctx, ovl, novl);
}
// evaluate remove flags
if (ctx->removeFlags != 0)
removeOvls(ctx, ovl, novl, ctx->removeFlags);
// check for chimers and gaps
if (ctx->chimerCoverage > 0)
removeChimerOvls(ctx, ovl, novl);
// filter by read flags
int aread = ovl->aread;
HITS_READ* reads = ctx->db->reads;
if (reads[aread].flags & READ_DISCARD)
{
for (j = 0; j < novl; j++)
{
ovl[j].flags |= OVL_DISCARD;
}
}
else
{
for (j = 0; j < novl; j++)
{
int bread = ovl[j].bread;
if (reads[bread].flags & READ_DISCARD)
{
ovl[j].flags |= OVL_DISCARD;
}
}
}
if (ctx->includeReadFlag)
{
for (j = 0; j < novl; j++)
{
if (!(reads[ovl[j].aread].flags & READ_KEEP) && !(reads[ovl[j].bread].flags & READ_KEEP))
{
ovl[j].flags |= OVL_DISCARD;
}
}
}
if (ctx->fileSpanningReads)
{
write_spanning_reads(ctx, ovl->aread);
}
if (ctx->fileOutDiscardedOverlaps)
{
for (j = 0; j < novl; j++)
{
if (ovl[j].flags & OVL_DISCARD)
fprintf(ctx->fileOutDiscardedOverlaps, "%d %d\n", ovl[j].aread, ovl[j].bread);
}
}
return 1;
}
static void usage()
{
fprintf(stderr, "[-vpLqTwZj] [-dnolRsSumMfyYzZVWb <int>] [-rtD <track>] [-xPIaA <file>] [-c<int,int>] <db> <overlaps_in> <overlaps_out>\n");
fprintf(stderr, "options: -v ... verbose\n");
fprintf(stderr, " -d ... max divergence allowed [0,100]\n");
fprintf(stderr, " -n ... min number of non-repeat bases\n");
fprintf(stderr, " -o ... min overlap length\n");
fprintf(stderr, " -l ... min read length\n");
fprintf(stderr, " -p ... purge discarded overlaps\n");
fprintf(stderr, " -s ... stitch (%d)\n", DEF_ARG_S);
fprintf(stderr, " -S ... stitch aggressively (%d)\n", DEF_ARG_S);
fprintf(stderr, " -r ... repeat track name (%s)\n", DEF_ARG_R);
fprintf(stderr, " -t ... trim track name (%s)\n", DEF_ARG_T);
fprintf(stderr, " -T ... trim overlaps (%d)\n", DEF_ARG_TT);
fprintf(stderr, " -u ... max number of unaligned bases\n");
fprintf(stderr, " -R ... remove (multiple -R possible) ... \n");
fprintf(stderr, " 0 stitched overlaps, i.e. overlaps with invalid trace points\n");
fprintf(stderr, " 1 module overlaps\n");
fprintf(stderr, " 2 trace points\n");
fprintf(stderr, " 3 non-identity overlaps\n");
fprintf(stderr, " 4 remove B-read repeat overlaps, if a proper overlap between A and B exists \n");
fprintf(stderr, " 5 identity overlaps\n");
fprintf(stderr, " 6 contained overlaps (includes duplicates)\n");
fprintf(stderr, " -L ... two pass processing with read caching\n");
fprintf(stderr, "experimental features:\n");
fprintf(stderr, " -f ... percentage of overlaps to keep (downsampling)\n");
fprintf(stderr, " -m ... resolve repeat modules, pass coverage as argument\n");
fprintf(stderr, " -M ... -m + more aggressive module detection\n");
fprintf(stderr, " -x ... exclude read ids found in file\n");
fprintf(stderr, " -I ... include read ids found in file, all other are excluded\n");
fprintf(stderr, " -P ... write read ids of repeat spanners to file\n");
fprintf(stderr, " -z ... drop entering/leaving alignments if number is below -z <int>\n");
fprintf(stderr, " -y ... merge repeats if they are closer then -y bases apart (if distance > 100, then smaller repeats (< 100) usually from DBdust are ignored)\n");
fprintf(stderr, " -Y ... merge repeats with start/end position of read if repeat interval starts/ends with fewer then -Y\n");
fprintf(stderr, " -a ... write discarded overlaps that may not symmetrically removed to file\n");
fprintf(stderr, " -A ... read file of discarded overlaps and remove them symmetrically\n");
fprintf(stderr, " -w ... remove multi-mapper overlaps within the same read\n");
fprintf(stderr, " -Z ... remove at most -Z percent of the worst alignments. Set -d INT to avoid loss of good alignments. Set -z INT to avoid loss of contiguity !\n");
fprintf(stderr, " This option was included to get rid of low coverage repeats or random alignments, that clearly get separated by diff scores\n");
fprintf(stderr, " -D ... read low complexity track (dust or tan_dust)\n");
fprintf(stderr, " -V ... max merge distance of neighboring repeats (default: 2400)\n");
fprintf(stderr, " -W ... window size in bases. Merge repeats that are closer then -V bases and have a decent number of low complexity bases in between both repeats\n");
fprintf(stderr, " or at -W bases at the tips of the neighboring repeat. Those can cause a fragmented repeat mask. (default: 600)\n");
fprintf(stderr, " -b ... remove alignments which have segments error rates above -b <int>%% (default: not set)\n");
fprintf(stderr, " -c <inta,intb> remove overlaps from chimeric reads (Chimer detection: locations that have less then <inta> coverage and less then in <intb> anchor bases around that location)\n");
fprintf(stderr, "OBSOLETE - will be removed in future\n");
fprintf(stderr, " -j ... trim off unaligned bases (indels) from start/end of alignments\n");
}
static int opt_repeat_count(int argc, char** argv, char opt)
{
int i;
int count = 0;
for (i = 1; i < argc; i++)
{
char* arg = argv[i];
if (*arg == '-')
{
arg += 1;
while (*arg == opt)
{
count += 1;
arg += 1;
}
if (count)
{
argv[i][2] = '\0';
break;
}
}
}
return count;
}
int main(int argc, char* argv[])
{
HITS_DB db;
FilterContext fctx;
PassContext* pctx;
FILE* fileOvlIn;
FILE* fileOvlOut;
bzero(&fctx, sizeof(FilterContext));
fctx.db = &db;
// args
char* pathSpanningReads = NULL;
char* pathExcludeReads = NULL;
char* pathIncludeReads = NULL;
char* pathOutDiscardedOvls = NULL;
char* pathInDiscardedOvls = NULL;
char* pcTrackRepeats = DEF_ARG_R;
char* arg_trimTrack = DEF_ARG_T;
char* arg_dustTrack = NULL;
int arg_purge = 0;
fctx.fileSpanningReads = NULL;
fctx.fMaxDiffs = -1;
fctx.nMaxUnalignedBases = -1;
fctx.nMinAlnLength = -1;
fctx.nMinNonRepeatBases = -1;
fctx.nMinReadLength = -1;
fctx.nVerbose = 0;
fctx.stitch = DEF_ARG_S;
fctx.rm_cov = -1;
fctx.rm_aggressive = 0;
fctx.useRLoader = 0;
fctx.do_trim = DEF_ARG_TT;
fctx.rm_mode = 0;
fctx.downsample = 0;
fctx.includeReadFlag = 0;
fctx.removeLowCoverageOverlaps = 0;
fctx.maxSegmentErrorRate = -1;
fctx.chimerCoverage = -1;
fctx.chimerAnchorBases = 1000;
fctx.stitch_aggressively = 0;
fctx.removeFlags = 0;
fctx.rm_merge = 50;
fctx.rp_mergeTips = 0;
fctx.discardedAreadList = NULL;
fctx.discardedBreads = NULL;
fctx.removeMultiMappers = 0;
fctx.remUpToXPercAln = 0;
fctx.mergeRepeatsWindow = 600;
fctx.mergeRepeatsMaxLen = 2400;
int c;
fctx.rm_mode = opt_repeat_count(argc, argv, 'm');
if (fctx.rm_mode == 0)
{
fctx.rm_mode = opt_repeat_count(argc, argv, 'M');
}
opterr = 0;
while ((c = getopt(argc, argv, "TvLpwy:z:d:n:o:l:R:s:S:u:m:M:r:t:P:x:f:I:Y:a:A:Z:D:V:W:b:jc:")) != -1)
{
switch (c)
{
case 'f':
fctx.downsample = atoi(optarg);
break;
case 'T':
fctx.do_trim = 1;
break;
case 'j':
fctx.trimIndels = 1;
break;
case 'x':
pathExcludeReads = optarg;
break;
case 'Z':
fctx.remUpToXPercAln = atoi(optarg);
break;
case 'b':
fctx.maxSegmentErrorRate = atoi(optarg);
break;
case 'I':
pathIncludeReads = optarg;
break;
case 'P':
pathSpanningReads = optarg;
break;
case 'a':
pathOutDiscardedOvls = optarg;
break;
case 'A':
pathInDiscardedOvls = optarg;
break;
case 'L':
fctx.useRLoader = 1;
break;
case 'w':
fctx.removeMultiMappers = 1;
break;
case 'z':
fctx.removeLowCoverageOverlaps = atoi(optarg);
break;
case 'y':
fctx.rm_merge = atoi(optarg);
break;
case 'Y':
fctx.rp_mergeTips = atoi(optarg);
break;
case 'M':
fctx.rm_aggressive = 1;
// fall through
case 'm':
fctx.rm_cov = atoi(optarg);
break;
case 'R':
{
int flag = atoi(optarg);
if (flag < 0 || flag > 6)
{
fprintf(stderr, "[ERROR]: Unsupported -R [%d] option.\n", flag);
usage();
exit(1);
}
fctx.removeFlags |= (1 << flag);
}
break;
case 'S':
fctx.stitch_aggressively = 1;
// fall through
case 's':
fctx.stitch = atoi(optarg);
break;
case 'v':
fctx.nVerbose = 1;
break;
case 'p':
arg_purge = 1;
break;
case 'd':
fctx.fMaxDiffs = atof(optarg) / 100.0;
break;
case 'o':
fctx.nMinAlnLength = atoi(optarg);
break;
case 'l':
fctx.nMinReadLength = atoi(optarg);
break;
case 'u':
fctx.nMaxUnalignedBases = atoi(optarg);
break;
case 'n':
fctx.nMinNonRepeatBases = atoi(optarg);
break;
case 'r':
pcTrackRepeats = optarg;
break;
case 't':
arg_trimTrack = optarg;
break;
case 'D':
arg_dustTrack = optarg;
break;
case 'W':
fctx.mergeRepeatsWindow = atoi(optarg);
break;
case 'V':
fctx.mergeRepeatsMaxLen = atoi(optarg);
break;
case 'c':
{
char * pch;
pch = strchr(optarg, ',');
if (pch == NULL)
{
fprintf(stderr, "[ERROR]: Unsupported argument for chimer detection: \"%s\". format must be -c <int>,<int> \n", optarg);
usage();
exit(1);
}
*pch = '\0';
fctx.chimerCoverage = atoi(optarg);
*pch = ',';
fctx.chimerAnchorBases = atoi(pch + 1);
}
break;
default:
fprintf(stderr, "[ERROR] unknown option -%c\n", optopt);
usage();
exit(1);
}
}
if (argc - optind != 3)
{
usage();
exit(1);
}
char* pcPathReadsIn = argv[optind++];
char* pcPathOverlapsIn = argv[optind++];
char* pcPathOverlapsOut = argv[optind++];
if ((fileOvlIn = fopen(pcPathOverlapsIn, "r")) == NULL)
{
fprintf(stderr, "could not open %s\n", pcPathOverlapsIn);
exit(1);
}
if ((fileOvlOut = fopen(pcPathOverlapsOut, "w")) == NULL)
{
fprintf(stderr, "could not open %s\n", pcPathOverlapsOut);
exit(1);
}
if (Open_DB(pcPathReadsIn, &db))
{
fprintf(stderr, "could not open %s\n", pcPathReadsIn);
exit(1);
}
int i;
for (i = 0; i < DB_NREADS(&db); i++)
{
db.reads[i].flags = READ_NONE;
}
if (fctx.downsample)
{
if (fctx.downsample > 99 || fctx.downsample < 0)
{
fprintf(stderr, "invalid downsampling factor %d. must be in [1, 99]\n", fctx.downsample);
exit(1);
}
}
if (pathSpanningReads)
{
fctx.fileSpanningReads = fopen(pathSpanningReads, "w");
if (fctx.fileSpanningReads == NULL)
{
fprintf(stderr, "could not open %s\n", pathSpanningReads);
exit(1);
}
}
if (fctx.nMinNonRepeatBases != -1 || fctx.fileSpanningReads)
{
fctx.trackRepeat = track_load(&db, pcTrackRepeats);
if (!fctx.trackRepeat)
{
fprintf(stderr, "could not load track %s\n", pcTrackRepeats);
exit(1);
}
}
if (arg_dustTrack)
{
fctx.trackDust = track_load(&db, arg_dustTrack);
if (!fctx.trackDust)
{
fprintf(stderr, "could not load track %s\n", arg_dustTrack);
exit(1);
}
}
fctx.trackTrim = track_load(&db, arg_trimTrack);
if (!fctx.trackTrim)
{
fprintf(stderr, "could not load track %s\n", arg_trimTrack);
// exit( 1 );
}
if (pathExcludeReads && pathIncludeReads)
{
fprintf(stderr, "-x and -I cannot be used at the same time!!!");
exit(1);
}
if (pathExcludeReads)
{
FILE* fileIn = fopen(pathExcludeReads, "r");
if (fileIn == NULL)
{
fprintf(stderr, "could not open %s\n", pathExcludeReads);
exit(1);
}
int* values;
int nvalues;
fread_integers(fileIn, &values, &nvalues);
printf("excluding %d reads\n", nvalues);
for (i = 0; i < nvalues; i++)
{
if (values[i] < 0 || values[i] >= DB_NREADS(&db))
{
fprintf(stderr, "[WARNING] LAfilter: excluding read %d not possible! Must be in range: [0, %d]", values[i], DB_NREADS(&db) - 1);
continue;
}
db.reads[values[i]].flags = READ_DISCARD;
}
free(values);
fclose(fileIn);
}
if (pathIncludeReads)
{
FILE* fileIn = fopen(pathIncludeReads, "r");
if (fileIn == NULL)
{
fprintf(stderr, "could not open %s\n", pathIncludeReads);
exit(1);
}
int* values;
int nvalues;
fread_integers(fileIn, &values, &nvalues);
printf("including %d reads\n", nvalues);
for (i = 0; i < nvalues; i++)
{
if (values[i] < 0 || values[i] >= DB_NREADS(&db))
{
fprintf(stderr, "[WARNING] LAfilter: including read %d not possible! Must be in range: [0, %d]", values[i], DB_NREADS(&db) - 1);
continue;
}
db.reads[values[i]].flags = READ_KEEP;
}
fctx.includeReadFlag = 1;
free(values);
fclose(fileIn);
}
if (pathOutDiscardedOvls)
{
FILE* fileOut = fopen(pathOutDiscardedOvls, "w");
if (fileOut == NULL)
{
fprintf(stderr, "could not open %s\n", pathOutDiscardedOvls);
exit(1);
}
fctx.fileOutDiscardedOverlaps = fileOut;
}
if (pathInDiscardedOvls)
{
FILE* fileIn = fopen(pathInDiscardedOvls, "r");
if (fileIn == NULL)
{
fprintf(stderr, "could not open %s\n", pathInDiscardedOvls);
exit(1);
}
// todo check if memory consumption is reasonable for larger projects
int ** discardedAreadList = (int **) calloc((DB_NREADS(fctx.db) + 1), sizeof(int *));
assert(discardedAreadList);
int aread, bread;
int prevAread, prevBread;
prevAread = -2;
prevBread = -1;
int numAreads = 0;
int numBreads = 0;
int line = 0;
// search for exact number of areads and breads, to avoid a bread reallocation
// printf("check for proper file format\n");
while (fscanf(fileIn, "%d %d\n", &aread, &bread) == 2)
{
if (aread != prevAread)
numAreads++;
if (aread > bread)
{
fprintf(stderr, "[ERROR] - read list must be sorted aread <= bread! Failed at %d, %d!\n", aread, bread);
fprintf(stderr, " Please sort your file first! awk '{if($1>$2) print $2\" \"$1; else print $1\" \"$2}' INFILE | sort -k 1,1n -k2,2n | uniq > OUTFILE\n");
exit(1);
}
numBreads++;
assert(prevAread <= aread);
if (prevAread == aread)
assert(prevBread < bread);
assert(aread < DB_NREADS(fctx.db) + 1);
line++;
// printf("line %5d: prev [%7d, %7d] cur [%7d, %7d] #a %5d #b %5d\n", line, prevAread, prevBread, aread, bread, numAreads, numBreads);
prevAread = aread;
prevBread = bread;
}
// printf("#areads: %6d, #breads %6d\n", numAreads, numBreads);
fseek(fileIn, 0L, SEEK_SET);
int * discardedBreads = (int*) malloc(sizeof(int) * (numBreads + numAreads + 10));
assert(discardedBreads);
prevAread = -2;
prevBread = -1;
int curBreadIdx = 0;
// printf("put overlaps into data structure\n");
while (fscanf(fileIn, "%d %d\n", &aread, &bread) == 2)
{
assert(prevAread <= aread);
if (prevAread == aread)
assert(prevBread < bread);
if (prevAread != aread)
{
if (prevAread > 0)
discardedBreads[curBreadIdx++] = -1;
discardedAreadList[aread] = discardedBreads + curBreadIdx;
}
discardedBreads[curBreadIdx++] = bread;
// printf("line %5d: prev [%7d, %7d] cur [%7d, %7d] #a %5d #b %5d \n", line, prevAread, prevBread, aread, bread, numAreads, numBreads);
prevAread = aread;
prevBread = bread;
}
discardedBreads[curBreadIdx++] = -1;
// printf("output data structure:\n");
// int i;
// for(i=0; i<DB_NREADS(fctx.db)+1; i++)
// {
// printf("i %d\n",i);
// if(discardedAreadList[i])
// {
// printf("discard ovls from aread %7d:", i);
// int j=0;
// while(discardedAreadList[i][j] > -1)
// {
// printf(" %7d", discardedAreadList[i][j++]);
// }
// printf("\n");
// }
// }
fctx.discardedAreadList = discardedAreadList;
fctx.discardedBreads = discardedBreads;
fclose(fileIn);
}
if (fctx.maxSegmentErrorRate < -1 && fctx.maxSegmentErrorRate > 100)
{
printf("[ERROR]: invalid maxSegmentErrorRate %d! Must be within [0,100]\n", fctx.maxSegmentErrorRate);
usage();
exit(1);
}
// passes
if (fctx.useRLoader)
{
fctx.rl = rl_init(&db, 1);
pctx = pass_init(fileOvlIn, NULL);
pctx->data = &fctx;
pctx->split_b = 1;
pctx->load_trace = 0;
pass(pctx, loader_handler);
rl_load_added(fctx.rl);
pass_free(pctx);
}
pctx = pass_init(fileOvlIn, fileOvlOut);
pctx->split_b = 0;
pctx->load_trace = 1;
pctx->unpack_trace = 1;
pctx->data = &fctx;
pctx->write_overlaps = 1;
pctx->purge_discarded = arg_purge;
filter_pre(pctx, &fctx);
pass(pctx, filter_handler);
filter_post(&fctx);
pass_free(pctx);
// cleanup
if (fctx.useRLoader)
{
rl_free(fctx.rl);
}
Close_DB(&db);
if (fctx.fileSpanningReads)
{
fclose(fctx.fileSpanningReads);
}
if (fctx.fileOutDiscardedOverlaps)
{
fclose(fctx.fileOutDiscardedOverlaps);
}
fclose(fileOvlOut);
fclose(fileOvlIn);
return 0;
}
|
MartinPippel/DAmar
|
utils/LAmerge.c
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <math.h>
#include "lib/pass.h"
#include "dalign/align.h"
#include "dalign/filter.h"
#include "LAmergeUtils.h"
#undef DEBUG
// is only called once, and if the sort flag is enabled
void sortFile(char* fout, char* fin, int verbose)
{
Overlap *allOvls;
uint64 novls;
int twidth;
uint16 *traces;
uint64 nTraces;
uint64 tcur;
uint64 j;
FILE *inFile, *outFile;
novls = 0;
if ((inFile = fopen(fin, "r")) == NULL)
{
fprintf(stderr, "[ERROR] - LAmerge: Cannot open file for reading: %s\n",
fin);
exit(1);
}
if (fread(&novls, sizeof(uint64), 1, inFile) != 1)
{
fprintf(stderr,
"[ERROR] - LAmerge: failed to read header novl of file %s\n",
fin);
fclose(inFile);
exit(1);
}
if (fread(&twidth, sizeof(int), 1, inFile) != 1)
{
fprintf(stderr,
"[ERROR] - LAmerge: failed to read header twidth of file %s\n",
fin);
fclose(inFile);
exit(1);
}
if (verbose)
printf("%s, novl: %llu\n", fin, novls);
// open output file
outFile = fopen(fout, "w");
if (!outFile)
{
fprintf(stderr, "[ERROR] - LAmerge: Cannot open output file %s\n",
fout);
fclose(inFile);
exit(1);
}
allOvls = (Overlap*) malloc(sizeof(Overlap) * novls);
nTraces = novls * 60;
traces = (uint16*) malloc(sizeof(uint16) * nTraces);
// parse all overlaps
tcur = 0;
size_t tbytes = TBYTES(twidth);
{
for (j = 0; j < novls; j++)
{
if (Read_Overlap(inFile, allOvls + j))
break;
// check if trace buffer is still sufficient
if (allOvls[j].path.tlen + tcur > nTraces)
{
nTraces = allOvls[j].path.tlen + tcur + 100;
uint16* traces2 = realloc(traces, nTraces * sizeof(uint16));
uint64 k;
for (k = 0; k < j; k++)
allOvls[k].path.trace = traces2
+ ((uint16*) (allOvls[k].path.trace) - traces);
traces = traces2;
}
allOvls[j].path.trace = traces + tcur;
Read_Trace(inFile, allOvls + j, tbytes);
tcur += allOvls[j].path.tlen;
if (tbytes == sizeof(uint8))
Decompress_TraceTo16(allOvls + j);
}
// check if j agrees with novls[i]
assert(j <= novls);
}
qsort(allOvls, novls, sizeof(Overlap), SORT_OVL);
if (verbose)
fprintf(stdout, "sortFile %llu overlaps\n", j);
// write header
fwrite(&novls, sizeof(novls), 1, outFile);
fwrite(&twidth, sizeof(twidth), 1, outFile);
for (j = 0; j < novls; j++)
{
if (tbytes == sizeof(uint8))
Compress_TraceTo8(allOvls + j, 1);
Write_Overlap(outFile, allOvls + j, tbytes);
}
// clean up
fclose(outFile);
fclose(inFile);
free(allOvls);
free(traces);
}
void sortAndMerge(char* fout, char** fin, int numF, int verbose)
{
assert(fout != NULL);
if (numF < 2)
{
fprintf(stderr, "ERROR: merge requires at least 2 input files!\n");
exit(1);
}
if (numF > MAX_FWAY_MERGE)
{
fprintf(stderr, "ERROR: merge cannot merge more then %d files!\n",
MAX_FWAY_MERGE);
exit(1);
}
Overlap *allOvls;
uint64 nAllOvls = 0;
uint64 ovlIdx;
FILE **inFiles;
uint64 *novls;
int twidth;
uint16 *traces;
uint64 nTraces;
uint64 tcur;
int i;
uint64 j;
inFiles = (FILE**) malloc(sizeof(FILE*) * numF);
novls = (uint64*) malloc(sizeof(uint64) * numF);
{
int twidthTMP;
// open files and parse header
for (i = 0; i < numF; i++)
{
if ((inFiles[i] = fopen(fin[i], "r")) == NULL)
{
fprintf(stderr,
"[ERROR] - LAmerge: cannot open file for reading: %s (%d)\n",
fin[i], i);
exit(0);
}
if (fread(novls + i, sizeof(novls[0]), 1, inFiles[i]) != 1)
{
fprintf(stderr,
"[ERROR] - LAmerge: failed to read header novl of file %s\n",
fin[i]);
exit(1);
}
if (fread(&twidthTMP, sizeof(twidthTMP), 1, inFiles[i]) != 1)
{
fprintf(stderr,
"[ERROR] - LAmerge: failed to read header twidth of file %s\n",
fin[i]);
exit(1);
}
nAllOvls += novls[i];
if (i == 0)
twidth = twidthTMP;
else if (twidth != twidthTMP)
{
fprintf(stderr,
"Cannot merge overlap files with different trace widths!!! (%d != %d)\n",
twidth, twidthTMP);
exit(1);
}
if (verbose)
printf("%s, novl: %llu,sumOVLs: %llu\n", fin[i], novls[i],
nAllOvls);
}
}
allOvls = (Overlap*) malloc(sizeof(Overlap) * nAllOvls);
nTraces = nAllOvls * 60;
traces = (uint16*) malloc(sizeof(uint16) * nTraces);
// try to open output file
FILE* out = fopen(fout, "w");
if (!out)
{
fprintf(stderr,
"[ERROR] - LAmerge: cannot open output file %s for writing\n",
fout);
exit(1);
}
// parse all overlaps
ovlIdx = 0;
tcur = 0;
size_t tbytes = TBYTES(twidth);
for (i = 0; i < numF; i++)
{
FILE *f = inFiles[i];
for (j = 0; j < novls[i]; j++)
{
if (ovlIdx >= nAllOvls) // should never happen, i.e. a header was broken
{
fprintf(stderr, "TERROR to many ovls!! %llu >= %llu\n", ovlIdx,
nAllOvls);
exit(1);
}
if (Read_Overlap(f, allOvls + ovlIdx))
break;
// check if trace buffer is still sufficient
if (allOvls[ovlIdx].path.tlen + tcur > nTraces)
{
nTraces = allOvls[ovlIdx].path.tlen + tcur + 100;
uint16* traces2 = realloc(traces, nTraces * sizeof(uint16));
uint64 k;
for (k = 0; k < ovlIdx; k++)
allOvls[k].path.trace = traces2
+ ((uint16*) (allOvls[k].path.trace) - traces);
traces = traces2;
}
allOvls[ovlIdx].path.trace = traces + tcur;
Read_Trace(f, allOvls + ovlIdx, tbytes);
tcur += allOvls[ovlIdx].path.tlen;
if (tbytes == sizeof(uint8))
Decompress_TraceTo16(allOvls + ovlIdx);
ovlIdx++;
}
// check if j agrees with novls[i]
assert(j <= novls[i]);
}
qsort(allOvls, nAllOvls, sizeof(Overlap), SORT_OVL);
if (verbose)
fprintf(stdout, "SortAndMerged %llu overlaps\n", ovlIdx);
// write header
fwrite(&nAllOvls, sizeof(nAllOvls), 1, out);
fwrite(&twidth, sizeof(twidth), 1, out);
for (j = 0; j < nAllOvls; j++)
{
if (tbytes == sizeof(uint8))
Compress_TraceTo8(allOvls + j, 1);
Write_Overlap(out, allOvls + j, tbytes);
}
// clean up
fclose(out);
for (i = 0; i < numF; i++)
fclose(inFiles[i]);
free(inFiles);
free(novls);
free(allOvls);
free(traces);
}
void merge(char* fout, char** fin, int numInFiles, int verbose)
{
assert(fout != NULL);
if (numInFiles < 2)
{
fprintf(stderr, "ERROR: merge requires at least 2 input files!\n");
exit(1);
}
if (numInFiles > MAX_FWAY_MERGE)
{
fprintf(stderr, "ERROR: merge cannot merge more then %d files!\n",
MAX_FWAY_MERGE);
exit(1);
}
IO_block * in;
int64 bsize, osize, psize;
char *block, *oblock;
int i, fway;
Overlap **heap;
int hsize;
Overlap *ovls;
int64 totl;
int tspace, tbytes;
FILE *output;
char *optr, *otop;
// Open all the input files and initialize their buffers
fway = numInFiles;
psize = sizeof(void *);
osize = sizeof(Overlap) - psize;
bsize = (MEMORY * 1000000ll) / (fway + 1);
block = (char *) Malloc(bsize * (fway + 1) + psize,
"Allocating LAmerge blocks");
in = (IO_block *) Malloc(sizeof(IO_block) * fway,
"Allocating LAmerge IO-reacords");
if (block == NULL || in == NULL)
exit(1);
block += psize;
totl = 0;
tbytes = 0;
tspace = 0;
for (i = 0; i < fway; i++)
{
int64 novl;
int mspace;
FILE *input;
char *iblock;
input = fopen(fin[i], "r");
if (input == NULL)
{
fprintf(stderr,
"[ERROR] - LAmerge: Cannot open file \"%s\" for reading\n",
fin[i]);
exit(1);
}
if (fread(&novl, sizeof(int64), 1, input) != 1)
SYSTEM_READ_ERROR
totl += novl;
if (fread(&mspace, sizeof(int), 1, input) != 1)
SYSTEM_READ_ERROR
if (i == 0)
{
tspace = mspace;
if (tspace <= TRACE_XOVR)
tbytes = sizeof(uint8);
else
tbytes = sizeof(uint16);
}
else if (tspace != mspace)
{
fprintf(stderr, "%s: PT-point spacing conflict (%d vs %d)\n",
Prog_Name, tspace, mspace);
exit(1);
}
in[i].stream = input;
in[i].block = iblock = block + i * bsize;
in[i].ptr = iblock;
in[i].top = iblock + fread(in[i].block, 1, bsize, input);
in[i].count = 0;
}
// Open the output file buffer and write (novl,tspace) header
{
output = fopen(fout, "w");
if (output == NULL)
{
fprintf(stderr,
"[ERROR] - LAmerge: Cannot open file \"%s\" for writing\n",
fout);
exit(1);
}
fwrite(&totl, sizeof(int64), 1, output);
fwrite(&tspace, sizeof(int), 1, output);
oblock = block + fway * bsize;
optr = oblock;
otop = oblock + bsize;
}
if (verbose)
{
printf("Merging %d files totalling ", fway);
Print_Number(totl, 0, stdout);
printf(" records\n");
}
// Initialize the heap
heap = (Overlap **) Malloc(sizeof(Overlap *) * (fway + 1),
"Allocating heap");
ovls = (Overlap *) Malloc(sizeof(Overlap) * fway, "Allocating heap");
if (heap == NULL || ovls == NULL)
exit(1);
hsize = 0;
for (i = 0; i < fway; i++)
{
if (in[i].ptr < in[i].top)
{
ovls[i] = *((Overlap *) (in[i].ptr - psize));
in[i].ptr += osize;
hsize += 1;
heap[hsize] = ovls + i;
}
}
if (hsize > 3)
for (i = hsize / 2; i > 1; i--)
reheap(i, heap, hsize);
// While the heap is not empty do
while (hsize > 0)
{
Overlap *ov;
IO_block *src;
int64 tsize, span;
reheap(1, heap, hsize);
ov = heap[1];
src = in + (ov - ovls);
src->count += 1;
tsize = ov->path.tlen * tbytes;
span = osize + tsize;
if (src->ptr + span > src->top)
ovl_reload(src, bsize);
if (optr + span > otop)
{
fwrite(oblock, 1, optr - oblock, output);
optr = oblock;
}
memcpy(optr, ((char *) ov) + psize, osize);
optr += osize;
memcpy(optr, src->ptr, tsize);
optr += tsize;
src->ptr += tsize;
if (src->ptr < src->top)
{
*ov = *((Overlap *) (src->ptr - psize));
src->ptr += osize;
}
else
{
heap[1] = heap[hsize];
hsize -= 1;
}
}
// Flush output buffer and wind up
if (optr > oblock)
fwrite(oblock, 1, optr - oblock, output);
fclose(output);
for (i = 0; i < fway; i++)
fclose(in[i].stream);
for (i = 0; i < fway; i++)
totl -= in[i].count;
if (totl != 0)
{
fprintf(stderr, "ERROR: Did not write all records (%lld)\n", totl);
exit(1);
}
free(ovls);
free(heap);
free(in);
free(block - psize);
}
static void doMergeAll(MERGE_OPT *mopt)
{
int mergeRounds = 0;
int tmp = mopt->numOfFilesToMerge;
char *fout;
fout = (char*) malloc(strlen(mopt->oFile) + 20);
sprintf(fout, "%s.las", mopt->oFile);
while (tmp > 1)
{
tmp = ceil(tmp / (double) mopt->fway);
mergeRounds++;
}
if (mergeRounds < 2)
{
if (mopt->SORT)
sortAndMerge(fout, mopt->iFileNames, mopt->numOfFilesToMerge,
mopt->VERBOSE);
else
merge(fout, mopt->iFileNames, mopt->numOfFilesToMerge,
mopt->VERBOSE);
}
else // merging in multiple rounds
{
char **tmpIN = (char**) malloc(
sizeof(char*) * mopt->numOfFilesToMerge * 2);
char **tmpOUT = tmpIN + mopt->numOfFilesToMerge;
void *tmp;
int i, j;
for (i = 0; i < mopt->numOfFilesToMerge * 2; i++)
tmpIN[i] = (char*) malloc(MAX_NAME);
int currentMergeRound = 1;
int numIn = mopt->numOfFilesToMerge;
int numOut = 0;
while (currentMergeRound < mergeRounds)
{
for (i = 0; i + mopt->fway < numIn; i += mopt->fway)
{
if (currentMergeRound == 1)
{
#ifdef DEBUG
printf("mergeIN:");
for (j = i; j < i + mopt->fway; j++)
{
printf(" %s", mopt->iFileNames[j]);
}
printf("\nmergeOut: %s\n", tmpOUT[numOut]);
#endif
sprintf(tmpOUT[numOut], "%s.L%d.%d.las", mopt->oFile,
currentMergeRound, numOut);
if (mopt->SORT)
sortAndMerge(tmpOUT[numOut], (mopt->iFileNames + i),
mopt->fway, mopt->VERBOSE);
else
merge(tmpOUT[numOut], (mopt->iFileNames + i),
mopt->fway, mopt->VERBOSE);
numOut++;
}
else
{
#ifdef DEBUG
printf("mergeIN:");
for (j = i; j < i + mopt->fway; j++)
{
printf(" %s", tmpIN[j]);
}
printf("\nmergeOut: %s\n", tmpOUT[numOut]);
#endif
sprintf(tmpOUT[numOut], "%s.L%d.%d.las", mopt->oFile,
currentMergeRound, numOut);
merge(tmpOUT[numOut], (tmpIN + i), mopt->fway,
mopt->VERBOSE);
numOut++;
}
}
if (i < numIn)
{
// if only a single input file remains, than add it directly to the tmpOUT
// if SORT is enabled, then sort the file first
if (i + 1 == numIn)
{
if (currentMergeRound == 1)
{
if (mopt->SORT)
{
#ifdef DEBUG
printf("sortIN: %s", mopt->iFileNames[i]);
printf("\nmergeOut: %s\n", tmpOUT[numOut]);
#endif
sprintf(tmpOUT[numOut], "%s.L%d.%d.las",
mopt->oFile, currentMergeRound, numOut);
sortFile(tmpOUT[numOut], mopt->iFileNames[i],
mopt->VERBOSE);
}
else
{
sprintf(tmpOUT[numOut], "%s", mopt->iFileNames[i]);
#ifdef DEBUG
printf("Add to mergeOut: %s\n", tmpOUT[numOut]);
#endif
}
numOut++;
}
else
{
sprintf(tmpOUT[numOut], "%s", tmpIN[i]);
#ifdef DEBUG
printf("Add to mergeOut: %s\n", tmpOUT[numOut]);
#endif
// reduce number of numIn by 1, as this file is used in the next merge round, an should not be removed now!!!!
numIn--;
numOut++;
}
}
else
{
if (currentMergeRound == 1)
{
#ifdef DEBUG
printf("mergeIN:");
for (j = i; j < numIn; j++)
{
printf(" %s", mopt->iFileNames[j]);
}
printf("\nmergeOut: %s\n", tmpOUT[numOut]);
#endif
sprintf(tmpOUT[numOut], "%s.L%d.%d.las", mopt->oFile,
currentMergeRound, numOut);
if (mopt->SORT)
sortAndMerge(tmpOUT[numOut], (mopt->iFileNames + i),
numIn - i, mopt->VERBOSE);
else
merge(tmpOUT[numOut], (mopt->iFileNames + i),
numIn - i, mopt->VERBOSE);
numOut++;
}
else
{
#ifdef DEBUG
printf("mergeIN:");
for (j = i; j < numIn; j++)
{
printf(" %s", tmpIN[j]);
}
printf("\nmergeOut: %s\n", tmpOUT[numOut]);
#endif
sprintf(tmpOUT[numOut], "%s.L%d.%d.las", mopt->oFile,
currentMergeRound, numOut);
merge(tmpOUT[numOut], (tmpIN + i), numIn - i,
mopt->VERBOSE);
numOut++;
}
}
}
#if DEBUG
// check all written files for correctness
for (j = 0; j < numOut; j++)
{
if (checkFile(mopt->db, tmpOUT[j], 1, mopt->CHECK_TRACE_POINTS, 0, mopt->SORT))
{
fprintf(stderr, "[ERROR] : LAmerge - intermediate overlap file %s failed check! Stop here!\n", tmpOUT[j]);
exit(1);
}
}
#endif
// remove intermediate files
if (!mopt->KEEP && currentMergeRound > 1)
{
for (j = 0; j + 1 < numIn; j++)
{
if(mopt->VERBOSE)
printf("1-delete intermediate file: %s\n", tmpIN[j]);
if (unlink(tmpIN[j]))
fprintf(stderr,
"WARNING - Cannot remove intermediate overlap file: %s\n",
tmpIN[j]);
}
}
tmp = tmpIN;
tmpIN = tmpOUT;
tmpOUT = (char**) tmp;
numIn = numOut;
numOut = 0;
currentMergeRound++;
}
// last merge step
#ifdef DEBUG
printf("LAST mergeIN:");
for (j = 0; j < numIn; j++)
{
printf(" %s", tmpIN[j]);
}
printf("\nLAST mergeOut: %s.las\n", mopt->oFile);
#endif
sprintf(tmpOUT[0], "%s.las", mopt->oFile);
merge(tmpOUT[0], tmpIN, numIn, mopt->VERBOSE);
// remove intermediate files
if (!mopt->KEEP && currentMergeRound > 1)
{
for (j = 0; j + 1 < numIn; j++)
{
if(mopt->VERBOSE)
printf("2-delete intermediate file: %s\n", tmpIN[j]);
if (unlink(tmpIN[j]))
fprintf(stderr,
"WARNING - Cannot remove intermediate overlap file: %s\n",
tmpIN[j]);
}
// remove last file, only if its not an initial input file
if (strcmp(tmpIN[j], mopt->iFileNames[mopt->numOfFilesToMerge - 1])
!= 0)
{
if(mopt->VERBOSE)
printf("3-delete intermediate file: %s\n", tmpIN[j]);
if (unlink(tmpIN[j]))
fprintf(stderr,
"WARNING - Cannot remove intermediate overlap file: %s\n",
tmpIN[j]);
}
}
//cleanup
if (tmpIN < tmpOUT)
{
for (i = 0; i < mopt->numOfFilesToMerge * 2; i++)
free(tmpIN[i]);
free(tmpIN);
}
else
{
for (i = 0; i < mopt->numOfFilesToMerge * 2; i++)
free(tmpOUT[i]);
free(tmpOUT);
}
}
// check final las file, this file must fulfill at least
if (mopt->CHECK_SORT_ORDER == 0)
mopt->CHECK_SORT_ORDER = 1;
if (checkOverlapFile(mopt, fout, 0))
{
fprintf(stderr,
"[ERROR] : LAmerge - overlap file %s failed check! Use -s option to sort the input files!\n",
fout);
exit(1);
}
free(fout);
}
static void copyFile(char *in, char *out)
{
FILE *from, *to;
char ch;
char *fout;
fout = (char*) malloc(strlen(out) + 20);
sprintf(fout, "%s.las", out);
/* open source file */
if ((from = fopen(in, "rb")) == NULL)
{
fprintf(stderr, "Cannot open source file: %s.\n", in);
exit(1);
}
/* open destination file */
if ((to = fopen(fout, "wb")) == NULL)
{
fprintf(stderr, "Cannot open destination file: %s.\n", fout);
exit(1);
}
/* copy the file */
while (!feof(from))
{
ch = fgetc(from);
if (ferror(from))
{
fprintf(stderr, "Error reading source file.\n");
exit(1);
}
if (!feof(from))
fputc(ch, to);
if (ferror(to))
{
fprintf(stderr, "Error writing destination file.\n");
exit(1);
}
}
if (fclose(from) == EOF)
{
fprintf(stderr, "Error closing source file.\n");
exit(1);
}
if (fclose(to) == EOF)
{
fprintf(stderr, "Error closing destination file.\n");
exit(1);
}
free(fout);
}
int main(int argc, char* argv[])
{
MERGE_OPT* mopt = parseMergeOptions(argc, argv);
if (!mopt)
{
fprintf(stderr, "[ERROR] - LAmerge: Unable to parse arguments\n");
exit(1);
}
if (mopt->numOfFilesToMerge == 0)
{
fprintf(stderr,
"[WARNING] - LAmerge: No input files. Nothing to do!\n");
return 0;
}
if (mopt->numOfFilesToMerge == 1)
{
copyFile(mopt->iFileNames[0], mopt->oFile);
return 0;
}
doMergeAll(mopt);
//cleanup
clearMergeOptions(mopt);
return 0;
}
|
MartinPippel/DAmar
|
utils/TKcombine.c
|
<gh_stars>10-100
/*
takes two tracks containing intervals and merges them
into a single track, removing contained/duplicate intervals
in the process and merging overlapping ones.
Source tracks and result track can be trimmed and/or untrimmed
Date: March 2015
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "lib/colors.h"
#include "lib/tracks.h"
#include "db/DB.h"
// toggles
#undef DEBUG
static void usage()
{
printf( "usage: [-vd] <db> <track.out> <track.in1> <track.in2> ... | <#.track>\n" );
printf( "Options: -v ... verbose\n" );
printf( " -d ... remove single tracks after merging\n" );
printf( " <#.track> ... read in all 1 .. nblocks tracks \n" );
}
static int cmp_intervals( const void* a, const void* b )
{
track_data* x = (track_data*)a;
track_data* y = (track_data*)b;
return x[ 0 ] - y[ 0 ];
}
int main( int argc, char* argv[] )
{
HITS_DB db;
int verbose = 0;
int delete = 0;
int ntracks;
char** track_name;
int c;
opterr = 0;
while ( ( c = getopt( argc, argv, "hvd" ) ) != -1 )
{
switch ( c )
{
case 'h':
usage();
exit( 1 );
case 'v':
verbose = 1;
break;
case 'd':
delete = 1;
break;
default:
usage();
exit( 1 );
}
}
/*
if ( argc - optind == 3 )
{
if ( argv[ optind + 2 ][ 0 ] != '#' )
{
usage();
exit( 1 );
}
}
else */ if ( argc - optind < 3 )
{
usage();
exit( 1 );
}
char* pathReadsIn = argv[ optind++ ];
char* nameTrackResult = argv[ optind++ ];
ntracks = argc - optind;
track_name = malloc( sizeof( char* ) * ntracks );
int i, j;
i = 0;
while ( optind != argc )
{
track_name[ i ] = argv[ optind ];
optind++;
i++;
}
if ( Open_DB( pathReadsIn, &db ) )
{
printf( "could not open db %s\n", pathReadsIn );
exit( 1 );
}
int nblocks = DB_Blocks( pathReadsIn );
if ( nblocks < 1 )
{
fprintf( stderr, "failed to get number of blocks\n" );
exit( 1 );
}
int nreads = db.ureads;
track_anno* offset_out = (track_anno*)malloc( sizeof( track_anno ) * ( nreads + 1 ) );
bzero( offset_out, sizeof( track_anno ) * ( nreads + 1 ) );
int dcur = 0;
int dmax = 100;
track_data* data_out = (track_data*)malloc( sizeof( track_data ) * dmax );
int tcur = 0;
int tmax = 100;
track_data* temp = (track_data*)malloc( sizeof( track_data ) * tmax );
track_anno* offset_tmp = (track_anno*)malloc( sizeof( track_anno ) * ( nreads + 1 ) );
bzero( offset_tmp, sizeof( track_anno ) * ( nreads + 1 ) );
int64 noverlap = 0;
int64 ncontain = 0;
HITS_TRACK* inTrack;
char* tmpTrackName = malloc( 1000 );
for ( i = 0; i < ntracks; i++ )
{
int cBlock = 1;
int cont = 1;
while ( cont && cBlock <= nblocks )
{
if ( track_name[ i ][ 0 ] == '#' )
{
sprintf( tmpTrackName, "%d.%s", cBlock++, track_name[ i ] + 2 );
if ( ( inTrack = track_load( &db, tmpTrackName ) ) == NULL )
{
fprintf( stderr, "could not open track %s\n", tmpTrackName );
exit( 1 );
}
}
else
{
if ( ( inTrack = track_load( &db, track_name[ i ] ) ) == NULL )
{
fprintf( stderr, "could not open track %s\n", track_name[ i ] );
exit( 1 );
}
cont = 0;
}
track_anno* anno_in = inTrack->anno;
track_data* data_in = inTrack->data;
if ( verbose )
{
printf( "%lld in %s", anno_in[ db.nreads ] / sizeof( track_data ), inTrack->name );
}
bzero( offset_tmp, sizeof( track_anno ) * ( nreads + 1 ) );
tcur = 0;
dcur = 0;
for ( j = 0; j < db.nreads; j++ )
{
// check input track
int ispace, ospace;
offset_tmp[ j ] = tcur;
track_anno i_ob = anno_in[ j ] / sizeof( track_data );
track_anno i_oe = anno_in[ j + 1 ] / sizeof( track_data );
assert( i_ob <= i_oe );
ispace = i_oe - i_ob;
// check current out track
track_anno o_ob = offset_out[ j ] / sizeof( track_data );
track_anno o_oe = offset_out[ j + 1 ] / sizeof( track_data );
assert( o_ob <= o_oe );
ospace = o_oe - o_ob;
if ( ispace == 0 && ospace == 0 )
continue;
if ( tcur + ospace + ispace >= tmax )
{
tmax = tmax * 1.2 + ospace + ispace;
temp = (track_data*)realloc( temp, sizeof( track_data ) * tmax );
}
// merge inTrack and current out-track into temp
if ( ispace > 0 )
{
memcpy( temp + tcur, data_in + i_ob, sizeof( track_data ) * ( i_oe - i_ob ) );
tcur += ispace;
}
if ( ospace > 0 )
{
memcpy( temp + tcur, data_out + o_ob, sizeof( track_data ) * ( o_oe - o_ob ) );
tcur += ospace;
}
if ( ispace != 0 && ospace != 0 )
{
qsort( temp + ( tcur - ispace - ospace ), ( ispace + ospace ) / 2, sizeof( track_data ) * 2, cmp_intervals );
int k;
for ( k = tcur - ispace - ospace + 2; k < tcur; k += 2 )
{
// contained -> replace with previous
if ( temp[ k + 1 ] <= temp[ k - 1 ] )
{
temp[ k ] = temp[ k - 2 ];
temp[ k + 1 ] = temp[ k - 1 ];
temp[ k - 2 ] = temp[ k - 1 ] = -1;
ncontain++;
}
// overlapping
else if ( temp[ k ] <= temp[ k - 1 ] )
{
temp[ k ] = temp[ k - 2 ];
temp[ k - 2 ] = temp[ k - 1 ] = -1;
noverlap++;
}
}
}
}
// copy tmp into data_out
if ( dcur + tcur >= dmax )
{
dmax = dmax * 1.2 + tcur;
data_out = (track_data*)realloc( data_out, sizeof( track_data ) * dmax );
}
bzero( offset_out, sizeof( track_anno ) * ( nreads + 1 ) );
offset_tmp[ nreads ] = tcur;
for ( j = 0; j < nreads; j++ )
{
track_anno k;
for ( k = offset_tmp[ j ]; k < offset_tmp[ j + 1 ]; k += 2 )
{
if ( temp[ k ] == -1 )
{
continue;
}
data_out[ dcur++ ] = temp[ k ];
data_out[ dcur++ ] = temp[ k + 1 ];
offset_out[ j ] += sizeof( track_data ) * 2;
}
}
track_anno coff, off;
off = 0;
for ( j = 0; j <= nreads; j++ )
{
coff = offset_out[ j ];
offset_out[ j ] = off;
off += coff;
}
for ( j = 0; j < nreads; j++ )
{
assert( offset_out[ j ] <= offset_out[ j + 1 ] );
}
// TODO use track_close, but it has to be adapted to update the linked list of DB tracks
Close_Track( &db, inTrack->name );
if ( verbose )
{
printf( " %lld contained, %lld overlapped, %lld cum\n", ncontain, noverlap, offset_out[ nreads ] / sizeof( track_data ) );
}
}
}
if ( verbose )
{
printf( "%lld contained\n%lld overlapped\n", ncontain, noverlap );
printf( "%lld in %s\n", offset_out[ nreads ] / sizeof( track_data ),
nameTrackResult );
}
track_write( &db, nameTrackResult, 0, offset_out, data_out,
offset_out[ nreads ] / sizeof( track_data ) );
free( temp );
free( data_out );
free( offset_out );
free( offset_tmp );
if ( delete )
{
for ( i = 0; i < ntracks; i++ )
{
if ( track_name[ i ][ 0 ] == '#' )
{
for ( j = 1; j <= nblocks; j++ )
{
sprintf( tmpTrackName, "%d.%s", j, track_name[ i ] + 2 );
track_delete( &db, tmpTrackName );
}
}
else
{
track_delete( &db, track_name[ i ] );
}
}
}
free( track_name );
free( tmpTrackName );
Close_DB( &db );
return 0;
}
|
MartinPippel/DAmar
|
scrub/LAstitch.c
|
/*******************************************************************************************
*
* A->B overlaps can be split into multiple A->B records due to bad regions in either one
* of the reads, causing the overlapper to stop aligning. Here we look for those records
* (with a maximum gap of -f), join the two overlaps into a single record, discard the
* superfluous one, and (re-)compute pass-through points & diffs for the segments surrounding
* the break point.
*
* Author : <NAME>
*
* Date : November 2014
*
*******************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <math.h>
#include <unistd.h>
#include <sys/param.h>
#include "lib/read_loader.h"
#include "lib/pass.h"
#include "lib/oflags.h"
#include "lib/colors.h"
#include "lib/utils.h"
#include "lib/tracks.h"
#include "db/DB.h"
#include "dalign/align.h"
// command line defaults
#define DEF_ARG_F 40
#define DEF_ARG_P 0
#define DEF_ARG_A 500
#define DEF_ARG_M 10
#define DEF_ARG_S 200
#define DEF_ARG_L 500
#define DEF_ARG_D 0.3
#define MAX_STITCH_ALIGN_ERROR 0.57
// switches
#define VERBOSE
#undef DEBUG_STITCH
// macros
#define OVL_STRAND(ovl) ( ( (ovl)->flags & OVL_COMP) ? 'c' : 'n' )
// context
typedef struct
{
HITS_DB* db; // database
int64 stitched; // how many stitch operations have occurred
int64 stitchedLC; // how many stitch low complexity operations have occurred
int fuzz; // max gap between the A/B overlaps
int verbose;
int minLength;
int anchorBases;
int mergeDistance;
int minLCLenToMerge;
float gapLenDifference;
int useRLoader;
ovl_header_twidth twidth; // trace point spacing
size_t tbytes; // bytes used for trace point storage
ovl_trace* trace; // new trace buffer for all B reads in the stitch_handler
int tcur; // current position in the buffer
int tmax; // size of the buffer
Work_Data* align_work; // working storage for the alignment module
Alignment align; // alignment and path record for computing the
Path path; // alignment in the gap region
Read_Loader* rl;
HITS_TRACK* lowCompTrack;
HITS_TRACK* repeatTrack;
} StitchContext;
// externals for getopt()
extern char *optarg;
extern int optind, opterr, optopt;
static void create_pass_through_points(StitchContext* ctx, ovl_trace* trace)
{
int twidth = ctx->twidth;
int a = ctx->align.path->abpos;
int b = ctx->align.path->bbpos;
int p, t;
int diffs = 0;
int matches = 0;
int aprev = a;
int bprev = b;
int tcur = 0;
for (t = 0; t < ctx->align.path->tlen; t++)
{
if ((p = ((ovl_trace*) (ctx->align.path->trace))[t]) < 0)
{
p = -p - 1;
while (a < p)
{
if (ctx->align.aseq[a] != ctx->align.bseq[b])
diffs++;
else
matches++;
a += 1;
b += 1;
if (a % twidth == 0)
{
trace[tcur++] = diffs;
trace[tcur++] = b - bprev;
aprev = a;
bprev = b;
#ifdef DEBUG_STITCH
printf(" a(%4dx%4d %3d %3d %3d)", a, b, diffs, matches, tcur);
#endif
diffs = matches = 0;
}
}
diffs++;
b += 1;
}
else
{
p--;
while (b < p)
{
if (ctx->align.aseq[a] != ctx->align.bseq[b])
diffs++;
else
matches++;
a += 1;
b += 1;
if (a % twidth == 0)
{
trace[tcur++] = diffs;
trace[tcur++] = b - bprev;
aprev = a;
bprev = b;
#ifdef DEBUG_STITCH
printf(" b(%4dx%4d %3d %3d %3d)", a, b, diffs, matches, tcur);
#endif
diffs = matches = 0;
}
}
diffs++;
a += 1;
if (a % twidth == 0)
{
trace[tcur++] = diffs;
trace[tcur++] = b - bprev;
aprev = a;
bprev = b;
#ifdef DEBUG_STITCH
printf(" c(%4dx%4d %3d %3d %3d)", a, b, diffs, matches, tcur);
#endif
diffs = matches = 0;
}
}
}
p = ctx->align.path->aepos;
while (a < p)
{
if (ctx->align.aseq[a] != ctx->align.bseq[b])
diffs++;
else
matches++;
a += 1;
b += 1;
if (a % twidth == 0 && a != ctx->align.path->aepos)
{
trace[tcur++] = diffs;
trace[tcur++] = b - bprev;
aprev = a;
bprev = b;
#ifdef DEBUG_STITCH
printf(" d(%4dx%4d %3d %3d %3d)", a, b, diffs, matches, tcur);
#endif
diffs = matches = 0;
}
}
if (a != aprev)
{
trace[tcur++] = diffs;
trace[tcur++] = b - bprev;
#ifdef DEBUG_STITCH
printf(" e(%4dx%4d %3d %3d %3d)", a, b, diffs, matches, tcur);
#endif
}
else
{
trace[tcur - 1] += b - bprev;
}
#ifdef DEBUG_STITCH
printf("\n");
#endif
}
/*
ensures that there is enough space in StitchContext.trace for
an additional needed values.
*/
static void ensure_trace(StitchContext* sctx, int needed)
{
// space needed
fflush(stdout);
if (needed + sctx->tcur >= sctx->tmax)
{
// void* traceb_old = sctx->trace;
// void* tracee_old = sctx->trace + sctx->tmax;
int tmax = (needed + sctx->tcur) * 2 + 1000;
void* trace = realloc(sctx->trace, sizeof(ovl_trace) * tmax);
/*
// re-adjust trace pointers from the overlap records
int i;
for (i = 0; i < novl; i++)
{
if (ovl[i].path.trace >= traceb_old && ovl[i].path.trace <= tracee_old)
{
printf("adjust %d\n", i);
ovl[i].path.trace = trace + (ovl[i].path.trace - traceb_old);
}
}
*/
sctx->tmax = tmax;
sctx->trace = trace;
}
}
/*
initialises the StitchContext
*/
static void stitch_pre(PassContext* pctx, StitchContext* sctx)
{
#ifdef VERBOSE
printf(ANSI_COLOR_GREEN "PASS stitching" ANSI_COLOR_RESET "\n");
#endif
sctx->tbytes = pctx->tbytes;
sctx->twidth = pctx->twidth;
sctx->align_work = New_Work_Data();
sctx->tmax = 2 * (( DB_READ_MAXLEN( sctx->db ) + pctx->twidth) / pctx->twidth);
sctx->trace = (ovl_trace*) malloc(sizeof(ovl_trace) * sctx->tmax);
sctx->align.path = &(sctx->path);
sctx->align.aseq = New_Read_Buffer(sctx->db);
sctx->align.bseq = New_Read_Buffer(sctx->db);
}
/*
cleanup the StitchContext
*/
static void stitch_post(PassContext* pctx, StitchContext* sctx)
{
#ifdef VERBOSE
printf("stitched %lld out of %lld overlaps\n", sctx->stitched, pctx->novl);
if (sctx->lowCompTrack)
printf("stitched low complexity %lld out of %lld overlaps\n", sctx->stitchedLC, pctx->novl);
#endif
Free_Work_Data(sctx->align_work);
free(sctx->align.aseq - 1);
free(sctx->align.bseq - 1);
free(sctx->trace);
}
static int getAnchorBases(StitchContext *ctx, int read, int from, int to)
{
if (from >= to)
return 0;
track_anno* rep_anno;
track_data* rep_data;
// if available use repeat track to analyze anchor bases
if (ctx->repeatTrack)
{
rep_anno = ctx->repeatTrack->anno;
rep_data = ctx->repeatTrack->data;
}
else
{
if (ctx->lowCompTrack == NULL)
return (to - from);
rep_anno = ctx->lowCompTrack->anno;
rep_data = ctx->lowCompTrack->data;
}
track_anno rb, re;
int repBases = 0;
int rBeg, rEnd;
if (read < 0 || read >= DB_NREADS(ctx->db))
{
fprintf(stderr, "[ERROR] - getAnchorBases readID: %d out of bounds [0, %d]\n", read, DB_NREADS(ctx->db) - 1);
fflush(stderr);
exit(1);
}
// repeat bases in a-read
rb = rep_anno[read] / sizeof(track_data);
re = rep_anno[read + 1] / sizeof(track_data);
while (rb < re)
{
rBeg = rep_data[rb];
rEnd = rep_data[rb + 1];
repBases += intersect(from, to, rBeg, rEnd);
rb += 2;
}
// printf("getRepeatBasesFromInterval: %d %d %d --> %d", readID, beg, end, repBases);
return MAX((to - from) - repBases, 0);
}
static int isLowComplexityBreak(StitchContext *ctx, Overlap *ovl1, Overlap *ovl2)
{
// todo check if anchor bases are really unique bases, i.e. include repeat mask, other low complexity bases
// todo do we need to check the alignment coordinates, anchor bases ,etc. according to bread too?
if (ctx->lowCompTrack)
{
assert(ovl1->aread == ovl2->aread);
assert(ovl1->bread == ovl2->bread);
assert((ovl1->flags & OVL_COMP) == (ovl2->flags & OVL_COMP));
track_anno* tanno = (track_anno*) (ctx->lowCompTrack->anno);
track_data* tdata = (track_data*) (ctx->lowCompTrack->data);
track_anno ob = tanno[ovl1->aread];
track_anno oe = tanno[ovl1->aread + 1];
if (ob < oe)
{
ob /= sizeof(track_data);
oe /= sizeof(track_data);
// try to merge close by low complexity intervals
int merge_dist = ctx->mergeDistance;
int anchor_dist = ctx->anchorBases;
int minLCLenToMerge = ctx->minLCLenToMerge;
int b = tdata[ob];
int e = tdata[ob + 1];
// printf("LAS %d vs %d %c a1[%d, %d] a2[%d, %d] --- b1[%d, %d] b2[%d, %d]\n", ovl1->aread, ovl1->bread, (ovl1->flags & OVL_COMP) ? 'C' : 'N',
// ovl1->path.abpos, ovl1->path.aepos, ovl2->path.abpos, ovl2->path.aepos, ovl1->path.bbpos, ovl1->path.bepos, ovl2->path.bbpos, ovl2->path.bepos);
ob += 2;
while (ob < oe)
{
// printf("b %d, e: %d\n", tdata[ob], tdata[ob + 1]);
if (e + merge_dist >= tdata[ob])
{
if (tdata[ob + 1] - tdata[ob] >= minLCLenToMerge)
{
e = tdata[ob + 1];
// printf("LAstitch LC - MERGE: [%d, %d]\n", b, e);
}
else
{
// printf("LAstitch LC - IGNORE TINY REPEAT: [%d, %d] len %d < %d\n", tdata[ob], tdata[ob + 1], tdata[ob + 1] - tdata[ob],
// minLCLenToMerge);
}
ob += 2;
continue;
}
else
{
// check overlap pattern
// XXXXX_LOW_COMPLEX_XXXXXX
// A read ----------------------------------------------------------
// B read --------------------------
// B read -------------------------------------
if (e - b >= ctx->minLength) // LOW COMPLEXITY MUST BVE AT LEAST 500 BASES LONG ?
{
int validIn = 0;
int validOut = 0;
// printf("LAstitch LC - CHECK OVL: [%d, %d]\n", b, e);
if (getAnchorBases(ctx, ovl1->aread, ovl1->path.abpos, b) >= anchor_dist && ovl1->path.aepos + 200 > b && ovl1->path.aepos - 25 < e)
validIn = 1;
if (getAnchorBases(ctx, ovl2->aread, e, ovl2->path.aepos) >= anchor_dist && ovl2->path.abpos + 25 > b && ovl2->path.abpos - 200 < e)
validOut = 1;
if (validIn && validOut)
{
// check gap length differences in both reads
int gLenA = ovl2->path.abpos - ovl1->path.aepos;
int gLenB = ovl2->path.bbpos - ovl1->path.bepos;
// printf("glenA %d, glenB %d", gLenA, gLenB);
int valid = 0;
double diff = 1.0;
// case 1: gap in both reads - bad region in both reads
if (gLenA > 0 && gLenB > 0)
{
if (gLenA < gLenB)
{
diff = 1.0 - gLenA * 1.0 / gLenB;
valid = 1;
}
else
{
diff = 1.0 - gLenB * 1.0 / gLenA;
valid = 2;
}
}
// case 2: overhang in both reads - why?
else if (gLenA < 0 && gLenB < 0)
{
if (gLenA < gLenB)
{
diff = 1.0 - gLenB * 1.0 / gLenA;
valid = 3;
}
else
{
diff = 1.0 - gLenA * 1.0 / gLenB;
valid = 4;
}
}
// case 3: one TE is larger then the other
else
{
if (gLenA < 0)
{
gLenB = gLenB + abs(gLenA);
diff = 1.0 - abs(gLenA) * 1.0 / gLenB;
valid = 5;
}
else
{
gLenA = gLenA + abs(gLenB);
diff = 1.0 - abs(gLenB) * 1.0 / gLenA;
valid = 6;
}
}
// printf("valid? %d, diff %.5f glen(%d, %d)", valid, diff, gLenA, gLenB);
if (diff < ctx->gapLenDifference)
return 1;
return 0;
}
}
b = tdata[ob];
e = tdata[ob + 1];
// printf("LAstitch LC - ASSIGN NEW: [%d, %d]\n", b, e);
ob += 2;
}
}
// check remaining lowComplexity interval (either there is only one, or its the last from the while loop)
if (e - b >= ctx->minLength)
{
// printf("LAstitch LC - LAST CHECK OVL: [%d, %d]\n", b, e);
int validIn = 0;
int validOut = 0;
if (getAnchorBases(ctx, ovl1->aread, ovl1->path.abpos, b) >= anchor_dist && ovl1->path.aepos + 200 > b && ovl1->path.aepos - 25 < e)
validIn = 1;
if (getAnchorBases(ctx, ovl2->aread, e, ovl2->path.aepos) >= anchor_dist && ovl2->path.abpos + 25 > b && ovl2->path.abpos - 200 < e)
validOut = 1;
if (validIn && validOut)
{
// check gap length differences in both reads
int gLenA = ovl2->path.abpos - ovl1->path.aepos;
int gLenB = ovl2->path.bbpos - ovl1->path.bepos;
// printf("glenA %d, glenB %d", gLenA, gLenB);
int valid = 0;
double diff = 1.0;
// case 1: gap in both reads - bad region in both reads
if (gLenA > 0 && gLenB > 0)
{
if (gLenA < gLenB)
{
diff = 1.0 - gLenA * 1.0 / gLenB;
valid = 1;
}
else
{
diff = 1.0 - gLenB * 1.0 / gLenA;
valid = 2;
}
}
// case 2: overhang in both reads - why?
else if (gLenA < 0 && gLenB < 0)
{
if (gLenA < gLenB)
{
diff = 1.0 - gLenB * 1.0 / gLenA;
valid = 3;
}
else
{
diff = 1.0 - gLenA * 1.0 / gLenB;
valid = 4;
}
}
// case 3: one TE is larger then the other
else
{
if (gLenA < 0)
{
gLenB = gLenB + abs(gLenA);
diff = 1.0 - abs(gLenA) * 1.0 / gLenB;
valid = 5;
}
else
{
gLenA = gLenA + abs(gLenB);
diff = 1.0 - abs(gLenB) * 1.0 / gLenB;
valid = 6;
}
}
// printf("valid? %d, diff %.5f glen(%d, %d)\n", valid, diff, gLenA, gLenB);
if (diff < ctx->gapLenDifference)
return 1;
return 0;
}
}
}
}
return 0;
}
// Produce the concatentation of path1, path2, and path3 where they are known to meet at
// the the ends of path2 which was produced by Compute-Alignment. Place this result in
// a big growing buffer, that gets reset when Bridge is called with path1 = NULL.
static void Bridge(StitchContext *ctx, Path *path1, Path *path3)
{
int k, k1, k2;
int len, diff;
ovl_trace *trace;
Path *path2 = ctx->align.path;
k1 = 2 * ((path2->abpos / ctx->twidth) - (path1->abpos / ctx->twidth));
if (path2->aepos == path3->aepos)
k2 = path3->tlen;
else
k2 = 2 * ((path2->aepos / ctx->twidth) - (path3->abpos / ctx->twidth));
len = k1 + path2->tlen + (path3->tlen - k2);
#ifdef DEBUG_BRIDGE
printf("k1: %d, k2: %d, len: %d\n", k1, k2, len);
#endif
int tcur = ctx->tcur;
trace = ctx->trace + tcur;
diff = 0;
len = 0;
if (k1 > 0)
{
ovl_trace *t = (ovl_trace*) (path1->trace);
for (k = 0; k < k1; k += 2)
{
trace[len++] = t[k];
trace[len++] = t[k + 1];
diff += t[k];
#ifdef DEBUG_BRIDGE
printf("path1 %d %d %d %d\n", k, path1->abpos / ctx->twidth * ctx->twidth + len / 2 * ctx->twidth, t[k], t[k + 1]);
#endif
}
}
if (path2->tlen > 0)
{
ovl_trace *t = (ovl_trace *) (path2->trace);
for (k = 0; k < path2->tlen; k += 2)
{
trace[len++] = t[k];
trace[len++] = t[k + 1];
diff += t[k];
#ifdef DEBUG_BRIDGE
printf("path2 %d %d %d %d\n", k, path1->abpos / ctx->twidth * ctx->twidth + len / 2 * ctx->twidth, t[k], t[k + 1]);
#endif
}
}
if (k2 < path3->tlen)
{
ovl_trace *t = (ovl_trace*) (path3->trace);
for (k = k2; k < path3->tlen; k += 2)
{
trace[len++] = t[k];
trace[len++] = t[k + 1];
diff += t[k];
#ifdef DEBUG_BRIDGE
printf("path3 %d %d %d %d\n", k, path1->abpos / ctx->twidth * ctx->twidth + len / 2 * ctx->twidth, t[k], t[k + 1]);
#endif
}
}
path1->aepos = path3->aepos;
path1->bepos = path3->bepos;
path1->diffs = diff;
path1->trace = (void *) (ctx->trace + tcur);
path1->tlen = len;
ctx->tcur += len;
}
static inline int MapToTPAbove(Path *path, int *x, int isA, int MR_tspace)
{
ovl_trace *trace = (ovl_trace*) path->trace;
int a, b, i;
a = (path->abpos / MR_tspace) * MR_tspace;
b = path->bbpos;
for (i = 1; i < path->tlen; i += 2)
{
a += MR_tspace;
b += trace[i];
if (a > path->aepos)
a = path->aepos;
if (isA)
{
if (a >= *x)
{
*x = a;
return (b);
}
}
else
{
if (b >= *x)
{
*x = b;
return (a);
}
}
}
if (isA)
{
*x = a;
return (b);
}
else
{
*x = b;
return (a);
}
}
static inline int MapToTPBelow(Path *path, int *x, int isA, int MR_tspace)
{
ovl_trace *trace = (ovl_trace*) path->trace;
int a, b, i;
a = ((path->aepos + (MR_tspace - 1)) / MR_tspace) * MR_tspace;
b = path->bepos;
for (i = path->tlen - 1; i >= 0; i -= 2)
{
a -= MR_tspace;
b -= trace[i];
if (a < path->abpos)
a = path->abpos;
if (isA)
{
if (a <= *x)
{
*x = a;
return (b);
}
}
else
{
if (b <= *x)
{
*x = b;
return (a);
}
}
}
if (isA)
{
*x = a;
return (b);
}
else
{
*x = b;
return (a);
}
}
static int Check_Bridge(Path *path, int MR_tspace)
{
uint16 *trace = (uint16 *) path->trace;
int i;
int cumDiff = 0;
int cntBadSegments = 0;
int apos = path->abpos;
int bpos = path->bbpos;
for (i = 0; i < path->tlen; i += 2)
{
apos = (apos / MR_tspace) * MR_tspace + MR_tspace;
bpos += trace[i + 1];
if (MR_tspace <= TRACE_XOVR && (trace[i] > 250 || trace[i + 1] > 250))
return (1);
cumDiff += trace[i];
if (1.0 * trace[i] / trace[i + 1] > MAX_STITCH_ALIGN_ERROR && i + 2 < path->tlen) // ignore last segment
{
#ifdef DEBUG_BRIDGE
printf("found bad segment at (a: %d -> b: %d) erate: %f\n", apos, bpos, 1.0 * trace[i] / trace[i + 1]);
#endif
cntBadSegments++;
}
}
if (cumDiff != path->diffs || cntBadSegments > 0)
return (1);
return (0);
}
static int Compute_Bridge_Path(StitchContext *ctx, Overlap *ovl1, Overlap *ovl2)
{
Path *apath;
int ain, aout;
int bin, bout;
int err;
int i, j, p;
ovl_trace *trk;
Read_Loader* rl = ctx->rl;
assert(ovl1->aread == ovl2->aread);
assert(ovl1->bread == ovl2->bread);
assert((ovl1->flags & OVL_COMP) == (ovl2->flags & OVL_COMP));
if (ctx->useRLoader)
{
rl_load_read(rl, ovl1->aread, ctx->align.aseq, 0);
rl_load_read(rl, ovl1->bread, ctx->align.bseq, 0);
}
else
{
Load_Read(ctx->db, ovl1->aread, ctx->align.aseq, 0);
Load_Read(ctx->db, ovl1->bread, ctx->align.bseq, 0);
}
Path *path1 = &(ovl1->path);
Path *path2 = &(ovl2->path);
apath = ctx->align.path;
ain = path2->abpos;
aout = path1->aepos;
bin = MapToTPBelow(path1, &ain, 1, ctx->twidth);
bout = MapToTPAbove(path2, &aout, 1, ctx->twidth);
#ifdef DEBUG_BRIDGE
printf("\n Tangle [%5d..%5d] vs [%5d..%5d] \n", path1->abpos, path1->aepos, path2->abpos, path2->aepos);
printf(" [%5d..%5d] vs [%5d..%5d] \n", path1->bbpos, path1->bepos, path2->bbpos, path2->bepos);
printf(" (%d,%d) to (%d,%d)\n", ain, bin, aout, bout);
fflush(stdout);
#endif
for (i = 0; bin > ovl2->path.bbpos && i < 10; i++)
{
ain = (ain - ctx->twidth) / ctx->twidth * ctx->twidth;
aout = (aout + ctx->twidth) / ctx->twidth * ctx->twidth;
if (ain < ovl1->path.abpos || aout > ovl2->path.aepos)
return 1;
bin = MapToTPBelow(path1, &ain, 1, ctx->twidth);
bout = MapToTPAbove(path2, &aout, 1, ctx->twidth);
#ifdef DEBUG_BRIDGE
printf("\n Tangle [%5d..%5d] vs [%5d..%5d] \n", path1->abpos, path1->aepos, path2->abpos, path2->aepos);
printf(" [%5d..%5d] vs [%5d..%5d] \n", path1->bbpos, path1->bepos, path2->bbpos, path2->bepos);
printf(" (%d,%d) to (%d,%d)\n", ain, bin, aout, bout);
fflush(stdout);
#endif
}
if (bout < bin)
return 1;
apath->abpos = ain - 2 * ctx->twidth;
apath->aepos = aout + 2 * ctx->twidth;
apath->bbpos = MapToTPBelow(path1, &(apath->abpos), 1, ctx->twidth);
apath->bepos = MapToTPAbove(path2, &(apath->aepos), 1, ctx->twidth);
if ((ovl1->flags & OVL_COMP))
{
Complement_Seq(ctx->align.bseq, DB_READ_LEN(ctx->db, ovl1->bread));
int p = apath->bbpos;
apath->bbpos = DB_READ_LEN(ctx->db, ovl1->bread) - apath->bepos;
apath->bepos = DB_READ_LEN(ctx->db, ovl1->bread) - p;
}
#ifdef DEBUG_BRIDGE
printf("align path: (%d,%d) to (%d,%d)\n", apath->abpos, apath->bbpos, apath->aepos, apath->bepos);
fflush(stdout);
#endif
if (Compute_Alignment(&(ctx->align), ctx->align_work, DIFF_TRACE, ctx->twidth))
printf("Compute_Trace_ALL failed\n");
#ifdef DEBUG_BRIDGE
printf("TRACE diffs: %d, len %d\n", ctx->align.path->diffs, ctx->align.path->tlen);
for (j = 0; j < ctx->align.path->tlen; j += 2)
{
printf(" %d %d\n", ((ovl_trace*) (ctx->align.path->trace))[j], ((ovl_trace*) (ctx->align.path->trace))[j + 1]);
}
printf("\n");
fflush(stdout);
#endif
trk = (ovl_trace *) apath->trace;
if (ovl1->flags & OVL_COMP)
{
j = apath->tlen - 2;
i = 0;
while (i < j)
{
p = trk[i];
trk[i] = trk[j];
trk[j] = p;
p = trk[i + 1];
trk[i + 1] = trk[j + 1];
trk[j + 1] = p;
i += 2;
j -= 2;
}
int p = apath->bbpos;
apath->bbpos = DB_READ_LEN(ctx->db, ovl1->bread) - apath->bepos;
apath->bepos = DB_READ_LEN(ctx->db, ovl1->bread) - p;
}
bin = apath->bbpos;
bout = apath->bepos;
err = apath->diffs;
p = 2 * (ain / ctx->twidth - apath->abpos / ctx->twidth);
for (i = 0; i < p; i += 2)
{
bin += trk[i + 1];
err -= trk[i];
}
p = 2 * (apath->aepos / ctx->twidth - aout / ctx->twidth);
for (i = ctx->align.path->tlen, p = i - p; i > p; i -= 2)
{
bout -= trk[i - 1];
err -= trk[i - 2];
}
#ifdef DEBUG_BRIDGE
printf(" (%d,%d) to (%d,%d)\n", ain, bin, aout, bout);
printf(" Box %d vs %d -> %d %d%%\n", aout - ain, bout - bin, err, (200 * err) / ((aout - ain) + (bout - bin)));
fflush(stdout);
#endif
return 0;
}
static int stitch_handler2(void* _ctx, Overlap* ovl, int novl)
{
StitchContext* ctx = (StitchContext*) _ctx;
if (novl < 2)
{
return 1;
}
if (ovl->aread == ovl->bread)
{
return 1;
}
int fuzz = ctx->fuzz;
int i, j, k;
int ab2, ae1, ae2;
int bb2, be1, be2;
int ab1, bb1;
ctx->tcur = 0;
int tsum = 0;
for (i = 0; i < novl; i++)
{
tsum += ovl[i].path.tlen;
}
ensure_trace(ctx, tsum * 4);
for (i = 0; i < novl; i++)
{
if (ovl[i].flags & OVL_DISCARD)
continue;
// b = ovl[i].bread;
ab1 = ovl[i].path.abpos;
ae1 = ovl[i].path.aepos;
bb1 = ovl[i].path.bbpos;
be1 = ovl[i].path.bepos;
for (k = i + 1; k < novl; k++)
{
if ((ovl[k].flags & OVL_DISCARD) || (ovl[i].flags & OVL_COMP) != (ovl[k].flags & OVL_COMP))
{
continue;
}
ab2 = ovl[k].path.abpos;
ae2 = ovl[k].path.aepos;
bb2 = ovl[k].path.bbpos;
be2 = ovl[k].path.bepos;
if (ab1 > ab2 || ae1 > ae2 || bb1 > bb2 || be1 > be2)
continue;
// check always for anchor bases
// todo check bread as well???
if (getAnchorBases(ctx, ovl[i].aread, ovl[i].path.abpos, ovl[i].path.aepos) < ctx->anchorBases ||
getAnchorBases(ctx, ovl[k].aread, ovl[k].path.abpos, ovl[k].path.aepos) < ctx->anchorBases)
continue;
// todo check also bread?
int lowCompBreak = isLowComplexityBreak(ctx, ovl + i, ovl + k);
#ifdef DEBUG_STITCH
if (lowCompBreak)
{
printf("ovl %d vs %d a len %d blen %d ratio: %f\n", ovl[i].aread, ovl[i].bread, abs(ae1 - ab2), abs(be1 - bb2),
fabs(1 - abs(ae1 - ab2) / (1.0 * abs(be1 - bb2))));
}
#endif
if ((abs(ae1 - ab2) < fuzz && abs(be1 - bb2) < fuzz && abs((ae1 - ab2) - (be1 - bb2)) < fuzz) // added 2016-02-17
|| lowCompBreak) // added 2018-02-14
{
// try to stitch
#ifdef DEBUG_STITCH
printf("overlap i %d vs %d [%d, %d] [%d, %d] %c\n", ovl[i].aread, ovl[i].bread, ovl[i].path.abpos, ovl[i].path.aepos, ovl[i].path.bbpos,
ovl[i].path.bepos, ovl[i].flags & OVL_COMP ? 'c' : 'n');
#endif
int cntBadSegments = 0;
int apos = ovl[i].path.abpos;
int bpos = ovl[i].path.bbpos;
ovl_trace* trace = ovl[i].path.trace;
for (j = 0; j < ovl[i].path.tlen; j += 2)
{
apos = (apos / ctx->twidth) * ctx->twidth + ctx->twidth;
bpos += trace[j + 1];
#ifdef DEBUG_STITCH
if (j > 0 && j % 10 == 0)
printf("\n");
printf("(%3d, %3d (%.2f) %5d, %5d) ", trace[j + 1], trace[j], 100.0 * trace[j] / trace[j + 1], apos, bpos);
#endif
if (1.0 * ctx->trace[j] / ctx->trace[j + 1] > MAX_STITCH_ALIGN_ERROR && j + 2 < ctx->tcur) // ignore last segment
{
#ifdef DEBUG_STITCH
printf("found bad segment at %d erate: %f\n", apos, 1.0 * trace[j] / trace[j + 1]);
#endif
cntBadSegments++;
}
}
#ifdef DEBUG_STITCH
printf("\n");
printf("overlap k %d vs %d [%d, %d] [%d, %d] %c\n", ovl[k].aread, ovl[k].bread, ovl[k].path.abpos, ovl[k].path.aepos, ovl[k].path.bbpos,
ovl[k].path.bepos, ovl[k].flags & OVL_COMP ? 'c' : 'n');
#endif
cntBadSegments = 0;
apos = ovl[k].path.abpos;
bpos = ovl[k].path.bbpos;
trace = ovl[k].path.trace;
for (j = 0; j < ovl[k].path.tlen; j += 2)
{
apos = (apos / ctx->twidth) * ctx->twidth + ctx->twidth;
bpos += trace[j + 1];
#ifdef DEBUG_STITCH
if (j > 0 && j % 10 == 0)
printf("\n");
printf("(%3d, %3d (%.2f) %5d, %5d) ", trace[j + 1], trace[j], 100.0 * trace[j] / trace[j + 1], apos, bpos);
#endif
if (1.0 * ctx->trace[j] / ctx->trace[j + 1] > MAX_STITCH_ALIGN_ERROR && j + 2 < ctx->tcur) // ignore last segment
{
#ifdef DEBUG_STITCH
printf("found bad segment at %d erate: %f\n", apos, 1.0 * trace[j] / trace[j + 1]);
#endif
cntBadSegments++;
}
}
#ifdef DEBUG_STITCH
printf("\n\n");
#endif
int tcur_start = ctx->tcur;
if (Compute_Bridge_Path(ctx, ovl + i, ovl + k))
continue;
if (Check_Bridge(ctx->align.path, ctx->twidth))
{
#ifdef DEBUG_BRIDGE
printf("Check_Bridge FAILED: %d vs %d [%d, %d] [%d,%d] ---- [%d, %d] [%d,%d]\n", ovl[i].aread, ovl[i].bread, ovl[i].path.abpos, ovl[i].path.aepos,
ovl[i].path.bbpos, ovl[i].path.bepos, ovl[k].path.abpos, ovl[k].path.aepos, ovl[k].path.bbpos, ovl[k].path.bepos);
#endif
continue;
}
Bridge(ctx, &(ovl[i].path), &(ovl[k].path));
cntBadSegments = 0;
apos = ovl[i].path.abpos;
bpos = ovl[i].path.bbpos;
for (j = tcur_start; j < ctx->tcur; j += 2)
{
apos = (apos / ctx->twidth) * ctx->twidth + ctx->twidth;
bpos += ctx->trace[j + 1];
#ifdef DEBUG_STITCH
if (j > 0 && j % 10 == 0)
printf("\n");
printf("(%3d, %3d (%.2f) %5d, %5d) ", ctx->trace[j + 1], ctx->trace[j], 100.0 * ctx->trace[j] / ctx->trace[j + 1], apos, bpos);
#endif
if (1.0 * ctx->trace[j] / ctx->trace[j + 1] > MAX_STITCH_ALIGN_ERROR && j + 2 < ctx->tcur) // ignore last segment
{
#ifdef DEBUG_STITCH
printf("found bad segment at %d erate: %f\n", apos, 1.0 * ctx->trace[j] / ctx->trace[j + 1]);
#endif
cntBadSegments++;
}
}
#ifdef DEBUG_STITCH
printf("\n\n");
#endif
assert(bpos == ovl[k].path.bepos);
ovl[k].flags |= OVL_DISCARD | OVL_STITCH;
ae1 = ae2;
be1 = be2;
if (lowCompBreak)
ctx->stitchedLC++;
else
ctx->stitched++;
}
}
}
return 1;
}
/*
called for each distinct A->B overlap pair
*/
static int stitch_handler(void* _ctx, Overlap* ovl, int novl)
{
StitchContext* ctx = (StitchContext*) _ctx;
Read_Loader* rl = ctx->rl;
if (novl < 2)
{
return 1;
}
if (ovl->aread == ovl->bread)
{
return 1;
}
int fuzz = ctx->fuzz;
int i, j, k;
int ab2, ae1, ae2;
int bb2, be1, be2;
int ab1, bb1;
ctx->tcur = 0;
int tsum = 0;
for (i = 0; i < novl; i++)
{
tsum += ovl[i].path.tlen;
}
ensure_trace(ctx, tsum * 4);
for (i = 0; i < novl; i++)
{
if (ovl[i].flags & OVL_DISCARD)
continue;
// b = ovl[i].bread;
ab1 = ovl[i].path.abpos;
ae1 = ovl[i].path.aepos;
bb1 = ovl[i].path.bbpos;
be1 = ovl[i].path.bepos;
for (k = i + 1; k < novl; k++)
{
if ((ovl[k].flags & OVL_DISCARD) || (ovl[i].flags & OVL_COMP) != (ovl[k].flags & OVL_COMP))
{
continue;
}
ab2 = ovl[k].path.abpos;
ae2 = ovl[k].path.aepos;
bb2 = ovl[k].path.bbpos;
be2 = ovl[k].path.bepos;
// todo check also bread?
int lowCompBreak = isLowComplexityBreak(ctx, ovl + i, ovl + k);
#ifdef DEBUG_STITCH
if (lowCompBreak)
{
printf("ovl %d vs %d a len %d blen %d ratio: %f\n", ovl[i].aread, ovl[i].bread, abs(ae1 - ab2), abs(be1 - bb2),
fabs(1 - abs(ae1 - ab2) / (1.0 * abs(be1 - bb2))));
}
#endif
if ((abs(ae1 - ab2) < fuzz && abs(be1 - bb2) < fuzz && abs((ae1 - ab2) - (be1 - bb2)) < fuzz) // added 2016-02-17
|| lowCompBreak) // added 2018-02-14
{
int segb = (MIN(ae1, ab2) - (ctx->twidth / 2)) / ctx->twidth;
int sege = (MAX(ae1, ab2) + (ctx->twidth / 2)) / ctx->twidth;
{
#ifdef DEBUG_STITCH
printf("TRACE diffs: %d, len %d\n", ovl[i].path.diffs, ovl[i].path.tlen);
#endif
int apos = ovl[i].path.abpos;
int bpos = ovl[i].path.bbpos;
for (j = 0; j < ovl[i].path.tlen; j += 2)
{
apos = (apos / ctx->twidth) * ctx->twidth + ctx->twidth;
bpos += ((ovl_trace*) (ovl[i].path.trace))[j + 1];
#ifdef DEBUG_STITCH
printf(" %d %d, %d %d\n", ((ovl_trace*) (ovl[i].path.trace))[j + 1], ((ovl_trace*) (ovl[i].path.trace))[j], apos, bpos);
#endif
}
#ifdef DEBUG_STITCH
printf("TRACE diffs: %d, len %d\n", ovl[k].path.diffs, ovl[k].path.tlen);
#endif
apos = ovl[k].path.abpos;
bpos = ovl[k].path.bbpos;
for (j = 0; j < ovl[k].path.tlen; j += 2)
{
apos = (apos / ctx->twidth) * ctx->twidth + ctx->twidth;
bpos += ((ovl_trace*) (ovl[k].path.trace))[j + 1];
#ifdef DEBUG_STITCH
printf(" %d %d, %d %d\n", ((ovl_trace*) (ovl[k].path.trace))[j + 1], ((ovl_trace*) (ovl[k].path.trace))[j], apos, bpos);
#endif
}
}
#ifdef DEBUG_STITCH
printf("[DEBUG] segB %3d segE %3d\n", segb, sege);
#endif
//TODO experimental - increase segb,sege interval by 1 trace space to the left and right (if possible)
{
int shift = 1;
segb = MAX(ab1 / ctx->twidth, segb - shift);
sege = MIN(ae2 / ctx->twidth, sege + shift);
}
#ifdef DEBUG_STITCH
printf("[DEBUG] update segB %3d segE %3d\n", segb, sege);
#endif
ovl_trace* tracei = ovl[i].path.trace;
ovl_trace* tracek = ovl[k].path.trace;
int align_bb, align_be, seg, apos, bpos;
assert(segb <= sege);
int tcur = ctx->tcur;
int tcur_start = tcur;
if (ctx->verbose)
{
if (lowCompBreak)
printf("STITCH LC ");
else
printf("STITCH ");
printf("%8d %2d @ %5d..%5d -> %8d @ %5d..%5d %c\n", ovl[i].aread, i, ab1, ae1, ovl[i].bread, bb1, be1, OVL_STRAND(ovl + i));
printf(" %2d @ %5d..%5d -> %8d @ %5d..%5d %c\n", k, ab2, ae2, ovl[k].bread, bb2, be2, OVL_STRAND(ovl + k));
}
#ifdef DEBUG_STITCH
char* color1 = (ae1 > ab2) ? ANSI_COLOR_RED : "";
char* color2 = (be1 > bb2) ? ANSI_COLOR_RED : "";
printf("[DFEBUG] STITCH %8d %2d @ %5d..%s%5d" ANSI_COLOR_RESET " -> %8d @ %5d..%s%5d" ANSI_COLOR_RESET " %c", ovl[i].aread, i, ab1, color1, ae1,
ovl[i].bread, bb1, color2, be1, OVL_STRAND(ovl + i));
apos = ovl[i].path.abpos;
bpos = ovl[i].path.bbpos;
for (j = 0; j < ovl[i].path.tlen; j += 2)
{
if (j == ovl[i].path.tlen - 2)
{
apos = ovl[i].path.aepos;
}
else
{
apos = (apos / ctx->twidth + 1) * ctx->twidth;
}
bpos += tracei[j + 1];
if (j >= ovl[i].path.tlen - 6)
printf(" (%3d, %3d, %5d, %5d)", tracei[j + 1], tracei[j], apos, bpos);
}
printf("\n");
printf(" %2d @ %s%5d" ANSI_COLOR_RESET "..%5d -> %8d @ %s%5d" ANSI_COLOR_RESET "..%5d %c", k, color1, ab2, ae2, ovl[k].bread,
color2, bb2, be2, OVL_STRAND(ovl + k));
apos = ovl[k].path.abpos;
bpos = ovl[k].path.bbpos;
for (j = 0; j < ovl[k].path.tlen; j += 2)
{
if (j == ovl[i].path.tlen - 2)
{
apos = ovl[i].path.aepos;
}
else
{
apos = (apos / ctx->twidth + 1) * ctx->twidth;
}
bpos += tracek[j + 1];
if (j < 6)
printf(" (%3d, %3d, %5d, %5d)", tracek[j + 1], tracek[j], apos, bpos);
}
printf("\n");
#endif
bpos = ovl[i].path.bbpos;
for (seg = ovl[i].path.abpos / ctx->twidth, j = 0; j < ovl[i].path.tlen && seg < segb; j += 2, seg++)
{
//// ctx->trace[tcur++] = tracei[j];
//// ctx->trace[tcur++] = tracei[j + 1];
bpos += tracei[j + 1];
}
align_bb = bpos;
align_be = 0;
for (j = segb; j <= sege; j++)
{
// ctx->trace[tcur++] = 0;
// ctx->trace[tcur++] = 0;
}
bpos = ovl[k].path.bbpos;
for (seg = ovl[k].path.abpos / ctx->twidth, j = 0; j < ovl[k].path.tlen; j += 2, seg++)
{
if (seg == sege)
{
align_be = bpos + tracek[j + 1];
}
else if (seg > sege)
{
// ctx->trace[tcur++] = tracek[j];
// ctx->trace[tcur++] = tracek[j + 1];
}
bpos += tracek[j + 1];
}
if ((align_bb >= align_be)
// ||
// (fabs(1.0 - ((((sege + 1) * ctx->twidth) - (segb * ctx->twidth)) / (1.0 *(align_be - align_bb)))) > ctx->gapLenDifference + 0.05)
)
{
#ifdef DEBUG_STITCH
printf("Stitching failed due to gap length differences: %f > %f\n",
fabs(1.0 - ((((sege + 1) * ctx->twidth) - (segb * ctx->twidth)) / (1.0 * (align_be - align_bb)))), ctx->gapLenDifference + 0.05);
#endif
continue;
}
#ifdef DEBUG_STITCH
printf("[DEBUG] %3d..%3d %5d..%5d %5d..%5d\n", segb, sege, segb * ctx->twidth,
MIN((sege + 1) * ctx->twidth, DB_READ_LEN(ctx->db, ovl[i].aread)), align_bb, align_be);
#endif
if (ctx->useRLoader)
{
rl_load_read(rl, ovl[i].aread, ctx->align.aseq, 0);
rl_load_read(rl, ovl[i].bread, ctx->align.bseq, 0);
}
else
{
Load_Read(ctx->db, ovl[i].aread, ctx->align.aseq, 0);
Load_Read(ctx->db, ovl[i].bread, ctx->align.bseq, 0);
}
if ((ovl[i].flags & OVL_COMP))
{
Complement_Seq(ctx->align.bseq, DB_READ_LEN(ctx->db, ovl[i].bread));
}
ctx->align.alen = DB_READ_LEN(ctx->db, ovl[i].aread);
ctx->align.blen = DB_READ_LEN(ctx->db, ovl[i].bread);
ctx->align.path->abpos = MIN(ae1, ab2) - 2 * ctx->twidth; //MAX(segb * ctx->twidth, ab1);
ctx->align.path->aepos = MAX(ae1, ab2) + 2 * ctx->twidth;
ctx->align.path->bbpos = MapToTPBelow(&(ovl[i].path), &(ctx->align.path->abpos), 1, ctx->twidth);
ctx->align.path->bepos = MapToTPAbove(&(ovl[k].path), &(ctx->align.path->aepos), 1, ctx->twidth);
// ctx->align.path->diffs = (ctx->align.path->aepos - ctx->align.path->abpos) + (ctx->align.path->bepos - ctx->align.path->bbpos);
#ifdef DEBUG_STITCH
printf("Compute_Alignment: %d - %d and %d - %d\n", ctx->align.path->abpos, ctx->align.path->aepos, ctx->align.path->bbpos, ctx->align.path->bepos);
#endif
if (Compute_Alignment(&(ctx->align), ctx->align_work, DIFF_TRACE, ctx->twidth))
printf("Compute_Trace_ALL failed\n");
#ifdef DEBUG_STITCH
printf("TRACE diffs: %d, len %d\n", ctx->align.path->diffs, ctx->align.path->tlen);
for (j = 0; j < ctx->align.path->tlen; j += 2)
{
printf(" %d %d\n", ((ovl_trace*) (ctx->align.path->trace))[j], ((ovl_trace*) (ctx->align.path->trace))[j + 1]);
}
printf("\n");
fflush(stdout);
#endif
// int falk = tcur_start + 2 * (segb - ovl[i].path.abpos / ctx->twidth);
// int test = ctx->align.path->abpos;
// for (j = 0; j < ctx->align.path->tlen; j+=2)
// {
// ctx->trace[falk++] = ((ovl_trace*) (ctx->align.path->trace))[j];
// ctx->trace[falk++] = ((ovl_trace*) (ctx->align.path->trace))[j+1];
// test+=ctx->twidth;
// }
//create_pass_through_points(ctx, ctx->trace + tcur_start + 2 * (segb - ovl[i].path.abpos / ctx->twidth));
Bridge(ctx, &(ovl[i].path), &(ovl[k].path));
#ifdef DEBUG_STITCH
printf("TRACE");
for (j = 0; j < ctx->align.path->tlen; j++)
{
printf(" %d", ((ovl_trace*) (ctx->align.path->trace))[j]);
}
printf("\n");
#endif
int cntBadSegments = 0;
apos = ovl[i].path.abpos;
bpos = ovl[i].path.bbpos;
for (j = tcur_start; j < ctx->tcur; j += 2)
{
apos = (apos / ctx->twidth) * ctx->twidth + ctx->twidth;
bpos += ctx->trace[j + 1];
#ifdef DEBUG_STITCH
if (j > 0 && j % 10 == 0)
printf("\n");
printf("(%3d, %3d (%.2f) %5d, %5d) ", ctx->trace[j + 1], ctx->trace[j], 100.0 * ctx->trace[j] / ctx->trace[j + 1], apos, bpos);
#endif
if (1.0 * ctx->trace[j] / ctx->trace[j + 1] > MAX_STITCH_ALIGN_ERROR && j + 2 < tcur) // ignore last segment
{
#ifdef DEBUG_STITCH
printf("found bad segment at %d erate: %f\n", apos, 1.0 * ctx->trace[j] / ctx->trace[j + 1]);
#endif
cntBadSegments++;
}
}
#ifdef DEBUG_STITCH
printf("\n\n");
#endif
assert(bpos == ovl[k].path.bepos);
// trace points can overflow if we stitch across a big gap
int bOverflow = 0;
if (ctx->tbytes == sizeof(uint8))
{
for (j = 0; j < tcur; j += 2)
{
if (ctx->trace[j + 1] > 255)
{
bOverflow = 1;
break;
}
}
}
if (!bOverflow && cntBadSegments == 0)
{
ctx->tcur = tcur;
ovl[i].path.aepos = ae1 = ae2;
ovl[i].path.bepos = be1 = be2;
ovl[i].path.diffs += ovl[k].path.diffs;
ovl[i].path.trace = ctx->trace + tcur_start;
ovl[i].path.tlen = ctx->tcur - tcur_start;
ovl[k].flags |= OVL_DISCARD | OVL_STITCH;
if (lowCompBreak)
ctx->stitchedLC++;
else
ctx->stitched++;
}
else
{
if(ctx->verbose)
printf("overflow recognized or bad #segements %d > 0 \n", cntBadSegments);
}
}
}
}
return 1;
}
static int loader_handler(void* _ctx, Overlap* ovl, int novl)
{
StitchContext* ctx = (StitchContext*) _ctx;
Read_Loader* rl = ctx->rl;
if (novl < 2)
{
return 1;
}
int fuzz = ctx->fuzz;
int i, k; // , b;
int ab2, ae1; // , ae2;
int bb2, be1; // , be2;
// int ab1, bb1;
for (i = 0; i < novl; i++)
{
if (ovl[i].flags & OVL_DISCARD)
continue;
// b = ovl[i].bread;
// ab1 = ovl[i].path.abpos;
ae1 = ovl[i].path.aepos;
// bb1 = ovl[i].path.bbpos;
be1 = ovl[i].path.bepos;
for (k = i + 1; k < novl; k++)
{
if ((ovl[k].flags & OVL_DISCARD) || (ovl[i].flags & OVL_COMP) != (ovl[k].flags & OVL_COMP))
{
continue;
}
ab2 = ovl[k].path.abpos;
// ae2 = ovl[k].path.aepos;
bb2 = ovl[k].path.bbpos;
// be2 = ovl[k].path.bepos;
int lowCompBreak = 0;
if (ctx->lowCompTrack)
lowCompBreak = isLowComplexityBreak(ctx, ovl + i, ovl + k);
if ((abs(ae1 - ab2) < fuzz && abs(be1 - bb2) < fuzz) || lowCompBreak)
{
rl_add(rl, ovl[i].aread);
rl_add(rl, ovl[i].bread);
}
}
}
return 1;
}
static void usage()
{
fprintf(stderr, "usage: [-pvL] [-amlf <int>] [-rt <track>] <db> <ovl.in> <ovl.out>\n");
fprintf(stderr, "options: -v ... verbose\n");
fprintf(stderr, " -f ... fuzzing for stitch (%d)\n", DEF_ARG_F);
fprintf(stderr, " -L ... two pass processing with read caching\n");
fprintf(stderr, " -p ... purge discarded overlaps\n");
fprintf(stderr, "\nEXPERIMENTAL\n");
fprintf(stderr, " try to stitch overlaps, that break in low complexity regions. Only works if trace spacing is >= 126\n");
fprintf(stderr, " -t ... low complexity (LC) or tandem repeat (TR) interval track (e.g. dust, tan)\n");
fprintf(stderr, " -r ... repeat track - is used to evaluate unique anchor bases\n");
fprintf(stderr, " -a ... anchor bases left and right of LC/TR interval (default: %d)\n", DEF_ARG_A);
fprintf(stderr, " -m ... merge LC/TR intervals that are closer then m bases (default: %d)\n", DEF_ARG_M);
fprintf(stderr, " -l ... consider only LC/TR intervals of length greater than -l bases (default: %d)\n", DEF_ARG_L);
fprintf(stderr, " -M ... merge only LC/TR intervals that are at least -M bases long (default: %d)\n", DEF_ARG_S);
fprintf(stderr,
" -d ... gap difference in percent (default: %.2f). Stitch only overlaps where gap size difference in A-read and B-read is lower then -m %%\n",
DEF_ARG_D);
}
int main(int argc, char* argv[])
{
HITS_DB db;
StitchContext sctx;
PassContext* pctx;
FILE* fileOvlIn;
FILE* fileOvlOut;
bzero(&sctx, sizeof(StitchContext));
sctx.fuzz = DEF_ARG_F;
sctx.anchorBases = DEF_ARG_A;
sctx.mergeDistance = DEF_ARG_M;
sctx.minLength = DEF_ARG_L;
sctx.minLCLenToMerge = DEF_ARG_S;
sctx.gapLenDifference = DEF_ARG_D;
sctx.verbose = 0;
sctx.db = &db;
sctx.useRLoader = 0;
char* arg_lowCompTrack = NULL;
char* arg_repeatTrack = NULL;
// process arguments
int arg_purge = DEF_ARG_P;
opterr = 0;
int c;
while ((c = getopt(argc, argv, "Lpvf:t:a:m:l:d:r:M:")) != -1)
{
switch (c)
{
case 'p':
arg_purge = 1;
break;
case 'L':
sctx.useRLoader = 1;
break;
case 'v':
sctx.verbose = 1;
break;
case 'f':
sctx.fuzz = atoi(optarg);
break;
case 'M':
sctx.minLCLenToMerge = atoi(optarg);
break;
case 'a':
sctx.anchorBases = atoi(optarg);
break;
case 'm':
sctx.mergeDistance = atoi(optarg);
break;
case 'l':
sctx.minLength = atoi(optarg);
break;
case 'd':
sctx.gapLenDifference = atof(optarg);
break;
case 't':
arg_lowCompTrack = optarg;
break;
case 'r':
arg_repeatTrack = optarg;
break;
default:
usage();
exit(1);
}
}
if (argc - optind < 3)
{
usage();
exit(1);
}
char* pcPathReadsIn = argv[optind++];
char* pcPathOverlapsIn = argv[optind++];
char* pcPathOverlapsOut = argv[optind++];
if ((fileOvlIn = fopen(pcPathOverlapsIn, "r")) == NULL)
{
fprintf(stderr, "could not open '%s'\n", pcPathOverlapsIn);
exit(1);
}
if ((fileOvlOut = fopen(pcPathOverlapsOut, "w")) == NULL)
{
fprintf(stderr, "could not open '%s'\n", pcPathOverlapsOut);
exit(1);
}
if (Open_DB(pcPathReadsIn, &db))
{
fprintf(stderr, "could not open database '%s'\n", pcPathReadsIn);
exit(1);
}
if (sctx.fuzz < 0)
{
fprintf(stderr, "invalid fuzzing value of %d\n", sctx.fuzz);
exit(1);
}
if (arg_lowCompTrack != NULL)
{
sctx.lowCompTrack = track_load(&db, arg_lowCompTrack);
if (!sctx.lowCompTrack)
{
fprintf(stderr, "could not load track %s\n", arg_lowCompTrack);
exit(1);
}
}
if (arg_repeatTrack != NULL)
{
sctx.repeatTrack = track_load(&db, arg_repeatTrack);
if (!sctx.repeatTrack)
{
fprintf(stderr, "could not load track %s\n", arg_repeatTrack);
exit(1);
}
}
if (sctx.useRLoader)
{
// collect read ids for loading
sctx.rl = rl_init(&db, 1);
pctx = pass_init(fileOvlIn, NULL);
pctx->data = &sctx;
pctx->split_b = 1;
pctx->load_trace = 0;
pass(pctx, loader_handler);
rl_load_added(sctx.rl);
pass_free(pctx);
}
// process overlaps
pctx = pass_init(fileOvlIn, fileOvlOut);
pctx->data = &sctx;
pctx->split_b = 1;
pctx->load_trace = 1;
pctx->unpack_trace = 1;
pctx->write_overlaps = 1;
pctx->purge_discarded = arg_purge;
stitch_pre(pctx, &sctx);
pass(pctx, stitch_handler2);
stitch_post(pctx, &sctx);
// cleanup
if (sctx.useRLoader)
{
rl_free(sctx.rl);
}
Close_DB(&db);
pass_free(pctx);
fclose(fileOvlIn);
fclose(fileOvlOut);
return 0;
}
|
MartinPippel/DAmar
|
lib/oflags.h
|
#pragma once
#define OVL_COMP (1 << 0) // B on reverse strand
#define OVL_DISCARD (1 << 1) // overlap tagged for removal
#define OVL_REPEAT (1 << 3) // repeat induced overlap
#define OVL_LOCAL (1 << 4) // local alignment
#define OVL_DIFF (1 << 5) // too many differences
#define OVL_STITCH (1 << 7) // stitched to another overlap
#define OVL_SYMDISCARD (1 << 8) //
#define OVL_OLEN (1 << 9) // overlap length
#define OVL_RLEN (1 << 10) // read length
#define OVL_TEMP (1 << 11) // temporary flag, not written to disk
#define OVL_CONT (1 << 15) // containment
#define OVL_GAP (1 << 16) // gap
#define OVL_TRIM (1 << 17) // trimmed
#define OVL_MODULE (1 << 18) // overlap spans unique repeat modules junction
#define OVL_OPTIONAL (1 << 19) // optional (risky) overlaps for touring
#define OVL_FLAGS 15 // number of flags
typedef struct _OverlapFlag2Label OverlapFlag2Label;
struct _OverlapFlag2Label
{
int mask;
char* label;
char indicator;
};
void flags2str(char* pc, int flags);
|
MartinPippel/DAmar
|
lib/utils.c
|
<gh_stars>10-100
#include <assert.h>
#include <stdlib.h>
#include <sys/param.h>
#include <ctype.h>
#include <string.h>
#include "tracks.h"
#include "lib/pass.h"
/*
fgetln is only available on bsd derived systems.
getline on the other hand is only in gnu libc derived systems.
if fgetln is missing emulate it using getline
*/
#if !defined( fgetln )
char* fgetln_( FILE* stream, size_t* len )
{
static char* linep = NULL;
static size_t linecap = 0;
ssize_t length = getline( &linep, &linecap, stream );
if ( length == -1 )
{
free( linep );
linep = NULL;
linecap = 0;
length = 0;
}
if ( len )
{
*len = length;
}
return linep;
}
#endif
uint64_t bp_parse(const char* num)
{
char* ptr;
double count = strtod(num, &ptr);
if ( *ptr == '\0' )
{
return count;
}
char unit = tolower( *ptr );
switch (unit)
{
case 'g':
count *= 1000;
// fall through
case 'm':
count *= 1000;
// fall through
case 'k':
count *= 1000;
break;
default:
fprintf(stderr, "unknown suffix '%c' specified\n", unit);
break;
}
return count;
}
char* bp_format_alloc(uint64_t num, int dec, int alloc)
{
static char sstr[128];
static char* str;
if (alloc)
{
str = malloc(128);
}
else
{
str = sstr;
}
char* suffix = "KMG";
double dnum = num;
int ns = -1;
while ( dnum > 1000 )
{
dnum /= 1000;
ns += 1;
}
sprintf(str, "%.*f", dec, dnum);
if (ns != -1)
{
int len = strlen(str);
str[len] = suffix[ns];
str[len + 1] = '\0';
}
return str;
}
char* bp_format(uint64_t num, int dec)
{
return bp_format_alloc(num, dec, 0);
}
int fread_integers(FILE* fileIn, int** out_values, int* out_nvalues)
{
int maxvalues = 100;
int nvalues = 0;
int* values = malloc( sizeof(int) * maxvalues ) ;
int n;
while ( fscanf(fileIn, "%d\n", &n) == 1 )
{
if ( maxvalues == nvalues )
{
maxvalues = 1.2 * maxvalues + 100;
values = realloc(values, sizeof(int) * maxvalues);
}
values[nvalues] = n;
nvalues += 1;
}
*out_values = values;
*out_nvalues = nvalues;
return nvalues;
}
char* format_bytes(unsigned long bytes)
{
const char* suffix[] = {"b", "kb", "mb", "gb", "tb", "eb"};
char* buf = malloc(128);
if (bytes < 1024)
{
sprintf(buf, "%lub", bytes);
}
else
{
double b = bytes;
int i = 0;
while ( b >= 1024 )
{
b /= 1024.0;
i++;
}
sprintf(buf, "%.1f%s", b, suffix[i]);
}
return buf;
}
void wrap_write(FILE* fileOut, char* seq, int len, int width)
{
int j;
for (j = 0; j + width < len; j += width)
{
fprintf(fileOut, "%.*s\n", width, seq + j);
}
if (j < len)
{
fprintf(fileOut, "%.*s\n", len - j, seq + j);
}
}
void revcomp(char* c, int len)
{
static char comp[128] =
{
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 't', 0, 'g', 0, 0, 0, 'c',
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 'a', 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 't', 0, 'g', 0, 0, 0, 'c',
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 'a', 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
};
char* b = c;
char* e = c + len;
while (b < e)
{
unsigned char t = *b;
*b = comp[ (int)(*e) ];
*e = comp[ t ];
b++;
e--;
}
if (b == e)
{
*b = comp[ (int)(*b) ];
}
}
void rev(char* c, int len)
{
char* b = c;
char* e = c + len;
while (b < e)
{
unsigned char t = *b;
*b = *e;
*e = t;
b++;
e--;
}
}
int intersect(int ab, int ae, int bb, int be)
{
int b = MAX(ab, bb);
int e = MIN(ae, be);
return (b < e ? (e-b) : 0);
}
void get_trim(HITS_DB* db, HITS_TRACK* trimtrack, int rid, int* b, int* e)
{
track_anno* anno = (track_anno*)trimtrack->anno;
track_anno ob = anno[rid] / sizeof(track_data);
track_anno oe = anno[rid+1] / sizeof(track_data);
assert( (ob == oe) || ((oe - ob) == 2) );
if (ob == oe)
{
*b = 0;
*e = 0; // DB_READ_LEN(db, rid); MODIFIED 14.06.2019: If a trim track is present and a read has no interval we actually do not want that read at all !!!
}
else
{
track_data* data = (track_data*)trimtrack->data;
*b = data[ob];
*e = data[ob+1];
if (*b >= *e)
{
*b = *e = 0;
}
}
}
|
MartinPippel/DAmar
|
utils/LAextract.c
|
<filename>utils/LAextract.c
/*******************************************************************************************
*
* extract overlaps for specific a-read ids
*
* Author : <NAME>
*
* Date : September 2014
*
*******************************************************************************************/
#include <string.h>
#include <stdlib.h>
#include "lib/colors.h"
#include "lib/pass.h"
#include "lib/oflags.h"
#include "db/DB.h"
#include "dalign/align.h"
#define VERBOSE
static void usage()
{
printf("<db> <overlaps_in> <overlaps_out>\n");
}
typedef struct
{
int* rid;
int nrid;
int currid;
} FilterContext;
static int filter_handler(void* _ctx, Overlap* ovl, int novl)
{
FilterContext* ctx = (FilterContext*)_ctx;
int* rid = ctx->rid;
int nrid = ctx->nrid;
int currid = ctx->currid;
int a = ovl->aread;
while ( currid < nrid && rid[currid] < a )
{
currid++;
}
if ( currid < nrid && rid[currid] != a )
{
int i;
for ( i = 0 ; i < novl ; i++ )
{
ovl[i].flags |= OVL_DISCARD;
}
}
else if ( rid[currid] == a )
{
currid++;
}
ctx->currid = currid;
if (currid == nrid)
{
return 0;
}
return 1;
}
static int cmp_int(const void* x, const void* y)
{
int* a = (int*)x;
int* b = (int*)y;
return (*a) - (*b);
}
int main(int argc, char* argv[])
{
HITS_DB db;
PassContext* pctx;
FilterContext fctx;
FILE* fileOvlIn;
FILE* fileOvlOut;
bzero(&fctx, sizeof(FilterContext));
// args
if (argc < 4)
{
usage();
exit(1);
}
int* rid = malloc(sizeof(int) * argc);
int nrid = 0;
int i;
for (i = 4; i < argc; i++)
{
char* end;
int t = strtol(argv[i], &end, 10);
if (*end == '\0')
{
rid[nrid] = t;
nrid++;
}
else
{
fprintf(stderr, "invalid argument %s\n", argv[i]);
}
}
if (nrid == 0)
{
fprintf(stderr, "nothing to do\n");
exit(0);
}
qsort(rid, nrid, sizeof(int), cmp_int);
fctx.nrid = nrid;
fctx.rid = rid;
char* pcPathReadsIn = argv[1];
char* pcPathOverlapsIn = argv[2];
char* pcPathOverlapsOut = argv[3];
if ( (fileOvlIn = fopen(pcPathOverlapsIn, "r")) == NULL )
{
fprintf(stderr, "could not open %s\n", pcPathOverlapsIn);
exit(1);
}
if ( (fileOvlOut = fopen(pcPathOverlapsOut, "w")) == NULL )
{
fprintf(stderr, "could not open %s\n", pcPathOverlapsOut);
exit(1);
}
if (Open_DB(pcPathReadsIn, &db))
{
fprintf(stderr, "could not open %s\n", pcPathReadsIn);
exit(1);
}
// passes
pctx = pass_init(fileOvlIn, fileOvlOut);
pctx->split_b = 0;
pctx->load_trace = 1;
pctx->unpack_trace = 0;
pctx->data = &fctx;
pctx->write_overlaps = 1;
pctx->purge_discarded = 1;
pctx->progress = 1;
#ifdef VERBOSE
printf(ANSI_COLOR_GREEN "PASS extracting\n" ANSI_COLOR_RESET);
#endif
pass(pctx, filter_handler);
// cleanup
pass_free(pctx);
Close_DB(&db);
free(rid);
fclose(fileOvlOut);
fclose(fileOvlIn);
return 0;
}
|
MartinPippel/DAmar
|
msa/realigner.h
|
/*****************************************************************************************\
* *
* This is the interface library for a restructured version of realigner *
* *
* Author: <NAME> *
* Date : March 2007 *
* *
\*****************************************************************************************/
#ifndef _REALIGN_MODULE
#define _REALIGN_MODULE
#include "dalign/align.h"
typedef void Re_Contig;
// Read and write a contig in vertical format without consensus or dots (see converter)
Re_Contig *Re_Read_Contig(FILE *input, FILE *comments);
void Re_Print_Contig(Re_Contig *contig, FILE *output, int samerows);
// Debug routines that print a representation of the model (symbols only)
// and the entire data structure
void Re_Print_Model(Re_Contig *contig, FILE *output);
void Re_Print_Structure(Re_Contig *contig, FILE *output);
// Return the consensus score of a contig
int Re_Consensus_Score(Re_Contig *contig);
// Optimize the alignment of a contig, using round-robin realignment in a band of size bandsize
int Re_Align_Contig(Re_Contig *contig, int bandsize);
// Free the storage for a contig
void Re_Free_Contig(Re_Contig *contig);
/* Routines for building multi-alignments from layout trees of overlaps.
Start by calling re_start_contig with the sequence, seq, and id, aread, of the root.
Then if you want the multi-alignment of aread with every read segment that overlaps
it, call re_add_overlap with each overlap o and the sequence of the bread, bseq.
If you want an intial alignment of a layout tree, then call re_add_read with a preorder
traversal of the overlaps in the tree. Because the tree is a layout tree, it is true
that the bread of overlap o, either is contained within the aread, or the aread extends
to the current right end of the growing multi-alignment. If reads are not added
in such an order, then the routine emits an error message and terminates execution. */
Re_Contig *Re_Start_Contig(int aread, char *aseq);
void Re_Add_Overlap(Re_Contig *contig, Overlap *o, char *bseq, int bandsize);
void Re_Add_Read (Re_Contig *contig, Overlap *o, char *bseq, int bandsize);
/* Routines for getting columns or dashed-reads out of a multi-alignment.
re_start_scan sets starts a "scan" of a given contig, each subsequent call
to re_next_read or re_next_column gets the next read or column of the
multi-alignment. re_next_read returns a pointer to the sequence of a read
wherein the dashes used to align it in the multi-alignment *are present*. The
integer pointed at by id is set to the id stored for the read (or row # if it
was read in from a vertical multi-alignment). re_next_column returns a pointer the
sequence of the next column, including dash symbols. The integer array pointed at
by ids gives the id of each read in the return sequence and is of the same length as
that sequencee. When the end of a read is reached, a '\n' is output for it in the
column just to the right of the end of the sequence. When a read is introduced into
a column it is always introduced at the end. */
void Re_Start_Scan (Re_Contig *contig);
char *Re_Next_Read (int *id);
char *Re_Next_Column(int **ids);
#endif // _REALIGN_MODULE
|
MartinPippel/DAmar
|
utils/LAexplorer.c
|
#include <gtk/gtk.h>
#include <stdlib.h>
#include <strings.h>
#include <math.h>
#include <string.h>
#include "lib/oflags.h"
#include "lib/utils.h"
#include "lib/pass.h"
#include "lib/tracks.h"
#include "lib/lasidx.h"
#include "db/DB.h"
#include "dalign/align.h"
// drawing area padding
#define PADDING 20
#define HIGHLIGHT_COLORS 32
// defaults
#define DEF_LINEWIDTH 4
// track type
#define TRACK_INTERVAL 1
#define TRACK_POINT 2
#undef DEBUG
// sort type
typedef enum
{
sort_abpos = 0, sort_aepos = 1, sort_length = 2, sort_readID = 3, sort_qual = 4
} sortType;
typedef enum
{
show_q = 0, show_distinct = 1, show_same = 2
} showType;
typedef enum
{
filter_include = 0, filter_exclude = 1, filter_highlight = 2
} filterType;
typedef struct
{
Overlap ovl;
GdkRGBA color;
} OverlapDetails;
typedef struct
{
int rid;
gdouble scroll_x;
gdouble scroll_y;
int filter_ab;
int filter_ae;
int hzoom;
} CurrentView;
// global status
typedef struct
{
HITS_DB db;
// FILE* fileLas;
HITS_TRACK* qtrack;
HITS_TRACK* srctrack;
lasidx* lasIndex;
int* lasIndexFile;
FILE** lasFiles;
char* pathDb;
char* pathLas;
// Overlap* ovls;
// GdkRGBA* ovl_color;
OverlapDetails* ovls;
OverlapDetails** ovls_sorted;
int omax;
int ocur;
int* ovl_display;
int novl_display;
int tmax;
int tcur;
ovl_trace* trace;
size_t tbytes;
int twidth;
GdkRGBA highlight_color[HIGHLIGHT_COLORS];
int* highlight;
int hmax;
int hcur;
int rid_hover_highlight;
GtkScrolledWindow* scrolled_wnd; // container for drawing_area
GtkWidget* drawing_area;
GtkWidget* drawing_tracks;
float hscale;
int pad;
HITS_TRACK** tracks;
int* track_type;
int maxtracks;
int ntracks;
// toolbar
GtkWidget* edit_read;
GtkWidget* edit_linewidth;
GtkWidget* check_revSort;
GtkWidget* edit_hzoom;
GtkWidget* combo_show;
GtkWidget* edit_filter_ab;
GtkWidget* edit_filter_ae;
// overlap details bar
GtkWidget* overlap_details;
int idx_details;
// filter panel
GtkWidget* filter_panel;
int filter_mask;
filterType filter;
int line_width;
int revSort;
sortType sort;
showType show;
int ovl_y_start; // y offset of first overlap
CurrentView* viewstack;
int viewstack_cur;
int viewstack_fill;
int viewstack_max;
} ExplorerContext;
static ExplorerContext g_ectx;
// oflags.c
extern OverlapFlag2Label oflag2label[];
// overlap sorting
static CurrentView* view_current()
{
if (g_ectx.viewstack_cur >= 0)
{
return g_ectx.viewstack + g_ectx.viewstack_cur;
}
return NULL;
}
static CurrentView* view_prev()
{
if (g_ectx.viewstack_cur > 0)
{
return g_ectx.viewstack + (g_ectx.viewstack_cur - 1);
}
return NULL;
}
static void view_new(int rid)
{
CurrentView* prev = view_current();
if ( prev != NULL )
{
prev->scroll_x = gtk_adjustment_get_value( gtk_scrolled_window_get_hadjustment(g_ectx.scrolled_wnd) );
prev->scroll_y = gtk_adjustment_get_value( gtk_scrolled_window_get_vadjustment(g_ectx.scrolled_wnd) );
}
g_ectx.viewstack_cur += 1;
g_ectx.viewstack_fill = g_ectx.viewstack_cur;
if ( g_ectx.viewstack_cur >= g_ectx.viewstack_max )
{
g_ectx.viewstack_max = g_ectx.viewstack_max * 1.2 + 20;
g_ectx.viewstack = realloc( g_ectx.viewstack, sizeof(CurrentView) * g_ectx.viewstack_max );
}
CurrentView* view = view_current();
view->rid = rid;
view->scroll_x = 0;
view->scroll_y = 0;
view->filter_ab = 0;
view->filter_ae = -1;
if ( prev != NULL )
{
view->hzoom = prev->hzoom;
}
else
{
view->hzoom = 1;
}
}
static int view_back()
{
if ( g_ectx.viewstack_cur < 1 )
{
return FALSE;
}
g_ectx.viewstack_cur -= 1;
return TRUE;
}
static int view_forward()
{
if (g_ectx.viewstack_cur == g_ectx.viewstack_fill)
{
return FALSE;
}
g_ectx.viewstack_cur += 1;
return TRUE;
}
static int cmp_ovls_abpos(const void* a, const void* b)
{
OverlapDetails* o1 = *(OverlapDetails**) a;
OverlapDetails* o2 = *(OverlapDetails**) b;
int cmp = o1->ovl.path.abpos - o2->ovl.path.abpos;
if (!cmp)
{
cmp = (o1->ovl.path.aepos - o1->ovl.path.abpos) - (o2->ovl.path.aepos - o2->ovl.path.abpos);
}
return cmp;
}
static int cmp_ovls_id(const void* a, const void* b)
{
OverlapDetails* o1 = *(OverlapDetails**) a;
OverlapDetails* o2 = *(OverlapDetails**) b;
int cmp = o1->ovl.bread - o2->ovl.bread;
if (cmp == 0)
{
cmp = o1->ovl.path.abpos - o2->ovl.path.abpos;
}
if (cmp == 0)
{
cmp = o1->ovl.path.aepos - o2->ovl.path.aepos;
}
return cmp;
}
static int cmp_ovls_aepos(const void* a, const void* b)
{
OverlapDetails* o1 = *(OverlapDetails**) a;
OverlapDetails* o2 = *(OverlapDetails**) b;
int cmp = o1->ovl.path.aepos - o2->ovl.path.aepos;
if (!cmp)
{
cmp = (o1->ovl.path.aepos - o1->ovl.path.abpos) - (o2->ovl.path.aepos - o2->ovl.path.abpos);
}
return cmp;
}
static int cmp_ovls_length(const void* a, const void* b)
{
OverlapDetails* o1 = *(OverlapDetails**) a;
OverlapDetails* o2 = *(OverlapDetails**) b;
return (o1->ovl.path.aepos - o1->ovl.path.abpos) - (o2->ovl.path.aepos - o2->ovl.path.abpos);
}
static int cmp_ovls_qual(const void* a, const void* b)
{
OverlapDetails* o1 = *(OverlapDetails**) a;
OverlapDetails* o2 = *(OverlapDetails**) b;
return ((100 - (o2->ovl.path.diffs * 100.0 / (o2->ovl.path.aepos - o2->ovl.path.abpos))) * 10 - (100 - (o1->ovl.path.diffs * 100.0 / (o1->ovl.path.aepos - o1->ovl.path.abpos))) * 10);
}
static void adjust_drawing_area_size()
{
GtkWidget* p = gtk_widget_get_parent(g_ectx.drawing_area);
int pwidth = gtk_widget_get_allocated_width(p) * view_current()->hzoom;
// gtk_widget_set_size_request(g_ectx.drawing_tracks, gtk_widget_get_allocated_width(p),
// PADDING + (g_ectx.ntracks + 1) * DEF_LINEWIDTH + PADDING);
gtk_widget_set_size_request(g_ectx.drawing_area, pwidth,
(g_ectx.novl_display + 1) * g_ectx.line_width * (g_ectx.pad + 1) + PADDING);
}
static void redraw()
{
g_ectx.idx_details = -1;
adjust_drawing_area_size();
gtk_widget_queue_draw(g_ectx.drawing_area);
gtk_widget_queue_draw(g_ectx.drawing_tracks);
}
// convert HSL to RGB
//
static double hue2rgb(double p, double q, double t)
{
if (t < 0)
{
t += 1;
}
if (t > 1)
{
t -= 1;
}
if (t < 1. / 6)
{
return p + (q - p) * 6. * t;
}
if (t < 1. / 2)
{
return q;
}
if (t < 2. / 3)
{
return p + (q - p) * (2. / 3 - t) * 6.;
}
return p;
}
static void hsl2rgb(double h, double s, double l, GdkRGBA* rgb)
{
double r, g, b;
if (s == 0)
{
r = g = b = l; // achromatic
}
else
{
double q = l < 0.5 ? l * (1 + s) : l + s - l * s;
double p = 2. * l - q;
r = hue2rgb(p, q, h + 1. / 3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1. / 3);
}
rgb->red = r;
rgb->green = g;
rgb->blue = b;
rgb->alpha = 0;
}
static double rand2()
{
return (double) rand() / (double) RAND_MAX;
}
static void get_unique_color(int color, int ncolors, GdkRGBA* rgb)
{
double hue = color * 360.0 / ncolors;
hsl2rgb(hue / 360.0, (50 + rand2() * 20) / 100.0, (50 + rand2() * 20) / 100.0, rgb);
}
//
// ///
// assign unique colors to b's occuring more than once
static void assign_colors()
{
OverlapDetails* ovls = g_ectx.ovls;
// how many colors do we need
int i;
int colors = 0;
int beg = 0;
for (i = 1; i < g_ectx.ocur; i++)
{
if (ovls[beg].ovl.bread != ovls[i].ovl.bread)
{
if (i - beg > 1)
{
colors++;
}
beg = i;
}
}
if (i - beg > 1)
{
colors++;
}
// go through the HSL cylinder
int col = 0;
GdkRGBA rgb_default;
rgb_default.red = 0.3;
rgb_default.green = 0.3;
rgb_default.blue = 0.3;
rgb_default.alpha = 0.0;
beg = 0;
for (i = 1; i < g_ectx.ocur; i++)
{
if (ovls[beg].ovl.bread != ovls[i].ovl.bread)
{
if (i - beg > 1)
{
get_unique_color(col, colors, &(ovls[beg].color));
col++;
while (beg != i)
{
ovls[beg + 1].color = ovls[beg].color;
beg++;
}
}
else
{
ovls[beg].color = rgb_default;
beg++;
}
beg = i;
}
}
if (i - beg > 1)
{
get_unique_color(col, colors, &(ovls[beg].color));
while (beg != i)
{
ovls[beg + 1].color = ovls[beg].color;
beg++;
}
}
else
{
ovls[i - 1].color = rgb_default;
beg++;
}
}
static int ypos2index(int y)
{
return (y - PADDING - g_ectx.line_width) / ((1 + g_ectx.pad) * g_ectx.line_width);
}
static int ypos2overlap(int y)
{
int ovl = (y - PADDING - g_ectx.line_width) / ((1 + g_ectx.pad) * g_ectx.line_width);
if (ovl >= 0 && ovl < g_ectx.novl_display)
{
return g_ectx.ovl_display[ovl];
}
return -1;
}
static int overlap2ypos(int i)
{
return g_ectx.ovl_y_start + (i + 1) * g_ectx.line_width * (1 + g_ectx.pad);
}
static int xpos2apos(int x)
{
x -= PADDING;
if (x < 0)
{
return 0;
}
x /= g_ectx.hscale;
int ovlALen = DB_READ_LEN(&g_ectx.db, g_ectx.ovls->ovl.aread);
if (x > ovlALen)
{
x = ovlALen;
}
return x;
}
static void sort_overlaps()
{
int i;
OverlapDetails** ovls_sorted = g_ectx.ovls_sorted;
int n = g_ectx.ocur;
for (i = 0; i < n; i++)
{
ovls_sorted[i] = g_ectx.ovls + i;
}
switch (g_ectx.sort)
{
case sort_abpos:
qsort(ovls_sorted, n, sizeof(OverlapDetails*), cmp_ovls_abpos);
break;
case sort_aepos:
qsort(ovls_sorted, n, sizeof(OverlapDetails*), cmp_ovls_aepos);
break;
case sort_length:
qsort(ovls_sorted, n, sizeof(OverlapDetails*), cmp_ovls_length);
break;
case sort_readID:
qsort(ovls_sorted, n, sizeof(OverlapDetails*), cmp_ovls_id);
break;
case sort_qual:
qsort(ovls_sorted, n, sizeof(OverlapDetails*), cmp_ovls_qual);
break;
default:
break;
}
if (g_ectx.revSort)
{
int j = n - 1;
OverlapDetails* temp;
for ( i = 0 ; i < n / 2 ; i++, j-- )
{
temp = ovls_sorted[i];
ovls_sorted[i] = ovls_sorted[j];
ovls_sorted[j] = temp;
}
if ( i != j )
{
temp = ovls_sorted[i];
ovls_sorted[i] = ovls_sorted[j];
ovls_sorted[j] = temp;
}
}
}
static void filter_overlaps(void)
{
OverlapDetails** ovls_sorted = g_ectx.ovls_sorted;
int ocur = g_ectx.ocur;
int i;
g_ectx.novl_display = 0;
int filter_ab = view_current()->filter_ab;
int filter_ae = view_current()->filter_ae;
for (i = 0; i < ocur; i++)
{
Overlap* ovl = &(ovls_sorted[i]->ovl);
switch (g_ectx.filter)
{
case filter_exclude:
if ( ovl->flags & g_ectx.filter_mask )
{
continue;
}
break;
case filter_include:
if ( !(ovl->flags & g_ectx.filter_mask) )
{
continue;
}
break;
default:
break;
}
if (ovl->path.aepos < filter_ab || ovl->path.abpos > filter_ae)
{
continue;
}
g_ectx.ovl_display[g_ectx.novl_display++] = i;
}
}
// load overlaps for read g_ectx.rid from las file
static void load_overlaps()
{
int rid = view_current()->rid;
int fileIdx = g_ectx.lasIndexFile[rid];
off_t lasOffset = g_ectx.lasIndex[rid];
int n = 0;
int a = rid;
if (lasOffset > 0)
{
OverlapDetails* ovls = g_ectx.ovls;
int omax = g_ectx.omax;
FILE* fileLas = g_ectx.lasFiles[fileIdx];
g_ectx.tcur = 0;
fseeko(fileLas, lasOffset, SEEK_SET);
while (1)
{
if (Read_Overlap(fileLas, &(ovls[n].ovl)) || ovls[n].ovl.aread != a)
{
break;
}
if (ovls[n].ovl.path.tlen + g_ectx.tcur > g_ectx.tmax)
{
g_ectx.tmax = 1.2 * g_ectx.tmax + ovls[n].ovl.path.tlen;
ovl_trace* trace = realloc(g_ectx.trace, g_ectx.tmax * sizeof(ovl_trace));
int j;
for (j = 0; j < n; j++)
{
ovls[j].ovl.path.trace = trace + ((ovl_trace*) (ovls[j].ovl.path.trace) - g_ectx.trace);
}
g_ectx.trace = trace;
}
ovls[n].ovl.path.trace = g_ectx.trace + g_ectx.tcur;
Read_Trace(fileLas, &(ovls[n].ovl), g_ectx.tbytes);
g_ectx.tcur += ovls[n].ovl.path.tlen;
if (g_ectx.tbytes == sizeof(uint8))
{
Decompress_TraceTo16(&(ovls[n].ovl));
}
n += 1;
if (n >= omax)
{
omax = 1.2 * n + 100;
ovls = realloc(ovls, sizeof(OverlapDetails) * omax);
g_ectx.ovls_sorted = realloc(g_ectx.ovls_sorted, sizeof(OverlapDetails*) * omax);
g_ectx.ovl_display = realloc(g_ectx.ovl_display, sizeof(int) * omax);
}
}
g_ectx.ovls = ovls;
g_ectx.omax = omax;
g_ectx.ocur = n;
}
else
{
g_ectx.ocur = n = 0;
}
assign_colors();
sort_overlaps();
int ovlALen = DB_READ_LEN(&g_ectx.db, a);
view_current()->filter_ab = 0;
view_current()->filter_ae = ovlALen;
gtk_spin_button_set_range(GTK_SPIN_BUTTON(g_ectx.edit_filter_ab), 0, ovlALen);
gtk_spin_button_set_value(GTK_SPIN_BUTTON(g_ectx.edit_filter_ab), 0);
gtk_spin_button_set_range(GTK_SPIN_BUTTON(g_ectx.edit_filter_ae), 0, ovlALen);
gtk_spin_button_set_value(GTK_SPIN_BUTTON(g_ectx.edit_filter_ae), ovlALen);
filter_overlaps();
redraw();
}
static void set_segment_color(cairo_t* cr, int diffs, int len, int bHighlight)
{
const int q_colors[] =
{ 22, 178, 0, 122, 195, 0, 211, 183, 0, 228, 82, 0, 245, 0, 34 };
int q = ((double) diffs / len) * g_ectx.twidth;
q = q / 10;
if (q > 4)
{
q = 4;
}
float shift = 1.0;
if (bHighlight)
{
shift -= 0.3;
}
cairo_set_source_rgb(cr, (q_colors[q * 3] * shift) / 255.0, (q_colors[q * 3 + 1] * shift) / 255.0, (q_colors[q * 3 + 2] * shift) / 255.0);
}
static int highlight_has(int rid)
{
int i;
for (i = 0; i < g_ectx.hcur; i++)
{
int h = g_ectx.highlight[i];
if (h > rid)
{
return -1;
}
else if (g_ectx.highlight[i] == rid)
{
return i;
}
}
return -1;
}
static int cmp_int(const void* x, const void* y)
{
int* a = (int*) x;
int* b = (int*) y;
return (*a) - (*b);
}
static void highlight_add(int rid)
{
if (g_ectx.hcur + 1 >= g_ectx.hmax)
{
g_ectx.hmax += 20;
g_ectx.highlight = realloc(g_ectx.highlight, sizeof(int) * g_ectx.hmax);
}
g_ectx.highlight[g_ectx.hcur] = rid;
g_ectx.hcur++;
qsort(g_ectx.highlight, g_ectx.hcur, sizeof(int), cmp_int);
}
static void highlight_remove(int rid)
{
int i;
for (i = 0; i < g_ectx.hcur; i++)
{
if (g_ectx.highlight[i] == rid)
{
g_ectx.highlight[i] = INT_MAX;
i = -1;
break;
}
}
if (i == -1)
{
qsort(g_ectx.highlight, g_ectx.hcur, sizeof(int), cmp_int);
g_ectx.hcur--;
}
}
static void draw_ovl(cairo_t* cr, OverlapDetails* ovld, int y, float scale, int clip_xb, int clip_xe, int bHighlight)
{
Overlap* ovl = &(ovld->ovl);
if (g_ectx.show == show_q)
{
int x = ovl->path.abpos;
if (ovl->path.tlen == 0)
{
set_segment_color(cr, ovl->path.diffs, ovl->path.aepos - ovl->path.abpos, bHighlight);
cairo_move_to(cr, PADDING + ovl->path.abpos * scale, y + 0.5);
cairo_line_to(cr, PADDING + ovl->path.aepos * scale, y + 0.5);
cairo_stroke(cr);
}
else
{
ovl_trace* trace = ovl->path.trace;
int j;
for (j = 0; j < ovl->path.tlen - 2; j += 2)
{
int x_next = (x / g_ectx.twidth + 1) * g_ectx.twidth;
if (x_next * scale + PADDING < clip_xb)
{
x = x_next;
continue;
}
cairo_move_to(cr, PADDING + x * scale, y + 0.5);
set_segment_color(cr, trace[j], trace[j + 1], bHighlight);
cairo_line_to(cr, PADDING + x_next * scale, y + 0.5);
cairo_stroke(cr);
x = x_next;
if (x * scale + PADDING > clip_xe)
{
break;
}
}
if (x * scale + PADDING <= clip_xe)
{
set_segment_color(cr, trace[j], trace[j + 1], bHighlight);
cairo_move_to(cr, PADDING + x * scale, y + 0.5);
cairo_line_to(cr, PADDING + ovl->path.aepos * scale, y + 0.5);
cairo_stroke(cr);
}
}
}
else
{
if (g_ectx.show == show_same)
{
int base = 0;
if (bHighlight)
{
base = 1;
}
cairo_set_source_rgb(cr, fabs(base - 0.3), fabs(base - 0.3), fabs(base - 0.8));
}
else
{
if (bHighlight)
{
cairo_set_source_rgb(cr, 1.0 - ovld->color.red, 1.0 - ovld->color.green, 1.0 - ovld->color.blue);
}
else
{
cairo_set_source_rgb(cr, ovld->color.red, ovld->color.green, ovld->color.blue);
}
}
cairo_move_to(cr, PADDING + ovl->path.abpos * scale, y + 0.5);
cairo_line_to(cr, PADDING + ovl->path.aepos * scale, y + 0.5);
cairo_stroke(cr);
}
int hidx = highlight_has(ovl->bread);
CurrentView* prev = view_prev();
if (prev != NULL && prev->rid == ovl->bread)
{
cairo_set_source_rgb(cr, 0, 0, 0);
cairo_move_to(cr, PADDING + ovl->path.abpos * scale - 10, y + 0.5);
cairo_line_to(cr, PADDING + ovl->path.abpos * scale - 5, y + 0.5);
cairo_move_to(cr, PADDING + ovl->path.aepos * scale + 5, y + 0.5);
cairo_line_to(cr, PADDING + ovl->path.aepos * scale + 10, y + 0.5);
cairo_stroke(cr);
}
else if (hidx != -1)
{
hidx = hidx % HIGHLIGHT_COLORS;
GdkRGBA* color = g_ectx.highlight_color + hidx;
cairo_set_source_rgb(cr, color->red, color->green, color->blue);
cairo_move_to(cr, PADDING + ovl->path.abpos * scale - 10, y + 0.5);
cairo_line_to(cr, PADDING + ovl->path.abpos * scale - 5, y + 0.5);
cairo_move_to(cr, PADDING + ovl->path.aepos * scale + 5, y + 0.5);
cairo_line_to(cr, PADDING + ovl->path.aepos * scale + 10, y + 0.5);
cairo_stroke(cr);
}
}
static gboolean track_draw_callback(GtkWidget* widget, cairo_t* cr, gpointer data)
{
UNUSED(data);
int rid = view_current()->rid;
int line_width = DEF_LINEWIDTH;
int width = gtk_widget_get_allocated_width(widget);
GdkRectangle clip;
gdk_cairo_get_clip_rectangle(cr, &clip);
int clip_xb = clip.x;
int clip_xe = clip.x + clip.width;
int clip_yb = clip.y;
// int clip_ye = clip.y + clip.height;
int alen = DB_READ_LEN(&g_ectx.db, rid);
int hzoom = view_current()->hzoom;
float scale = (width * hzoom - 2.0 * PADDING) / alen;
int x_offset = gtk_adjustment_get_value( gtk_scrolled_window_get_hadjustment(g_ectx.scrolled_wnd) );
cairo_set_line_width(cr, line_width);
// background
cairo_set_source_rgb(cr, 0.9, 0.9, 0.9);
cairo_rectangle(cr, clip_xb, clip_xe, clip.width, clip.height);
cairo_fill(cr);
int y = PADDING;
// tracks
int i;
for (i = 0; i < g_ectx.ntracks; i++, y += line_width * 2)
{
track_anno* anno = g_ectx.tracks[i]->anno;
track_data* data = g_ectx.tracks[i]->data;
track_anno b = anno[rid] / sizeof(track_data);
track_anno e = anno[rid + 1] / sizeof(track_data);
cairo_set_source_rgb(cr, i % 2, (i % 3) / 2.0, (i % 4) / 3.0);
switch (g_ectx.track_type[i])
{
case TRACK_INTERVAL:
{
for ( ; b < e ; b += 2 )
{
track_data rb = data[b];
track_data re = data[b + 1];
int xb = MIN(width, MAX(0, PADDING + rb * scale - x_offset));
int xe = MIN(width, MAX(0, PADDING + re * scale - x_offset));
if ( xb >= xe )
{
continue;
}
cairo_move_to(cr, xb, y); // PADDING + rb * scale, y);
cairo_line_to(cr, xe, y); // PADDING + re * scale, y);
}
break;
}
case TRACK_POINT:
{
// TODO
break;
}
default:
break;
}
cairo_stroke(cr);
// y += line_width * 2;
}
if (y > clip_yb)
{
// a read
cairo_set_line_width(cr, line_width);
cairo_set_source_rgb(cr, 1, 0, 0);
int xb = MIN(width, MAX(0, PADDING - x_offset));
int xe = MIN(width, MAX(0, width * hzoom - PADDING - x_offset));
cairo_move_to(cr, xb, y + 0.5);
cairo_line_to(cr, xe, y + 0.5);
cairo_stroke(cr);
// a read ticks
cairo_set_source_rgb(cr, 0, 0, 0);
cairo_set_line_width(cr, 2.5);
for (i = 500; i < alen; i += 500)
{
int x = PADDING + i * scale - x_offset;
if ( x < 0 )
{
continue;
}
if ( x > width )
{
break;
}
cairo_move_to(cr, x, y - line_width);
cairo_line_to(cr, x, y - line_width / 2);
}
cairo_stroke(cr);
}
return FALSE;
}
static gboolean read_draw_callback(GtkWidget* widget, cairo_t* cr, gpointer data)
{
UNUSED(data);
guint width; // , height;
OverlapDetails** ovls_sorted = g_ectx.ovls_sorted;
int rid = view_current()->rid;
width = gtk_widget_get_allocated_width(widget);
// height = gtk_widget_get_allocated_height(widget);
GdkRectangle clip;
gdk_cairo_get_clip_rectangle(cr, &clip);
int clip_xb = clip.x;
int clip_xe = clip.x + clip.width;
int clip_yb = clip.y;
int clip_ye = clip.y + clip.height;
#ifdef DEBUG
printf("draw clip rect %4d..%4d -> %4d..%4d\n", clip_xb, clip_yb, clip_xe, clip_ye);
#endif
// background
cairo_set_source_rgb(cr, 0.9, 0.9, 0.9);
cairo_rectangle(cr, clip_xb, clip_xe, clip.width, clip.height);
cairo_fill(cr);
cairo_set_line_width(cr, g_ectx.line_width);
int alen = DB_READ_LEN(&g_ectx.db, rid);
float scale = g_ectx.hscale = (width - 2.0 * PADDING) / alen;
// printf("drawing %d overlaps @ scale %.2f\n", ocur, scale);
// b reads
int y = PADDING;
int i;
cairo_set_line_width(cr, g_ectx.line_width);
// y += g_ectx.line_width;
g_ectx.ovl_y_start = y;
int draw_start = MAX(0, ypos2index( clip_yb ) - 1);
int draw_end = ypos2index( clip_ye );
if (draw_end == -1 || draw_end > g_ectx.novl_display)
{
draw_end = g_ectx.novl_display;
}
else
{
draw_end = MIN(g_ectx.novl_display, draw_end + 1);
}
#ifdef DEBUG
printf("draw_start %d .. draw_end %d\n", draw_start, draw_end);
#endif
y += draw_start * g_ectx.line_width * (1 + g_ectx.pad);
for ( i = draw_start ; i < draw_end ; i++ )
{
int idx = g_ectx.ovl_display[i];
Overlap* ovl = &(ovls_sorted[idx]->ovl);
y += g_ectx.line_width * (1 + g_ectx.pad);
#ifdef DEBUG
printf("drawing %d @ y %4d .. bread %8d .. highlight %8d\n", i, y, ovl->bread, g_ectx.rid_hover_highlight);
#endif
int highlight = 0;
if ( ovl->bread == g_ectx.rid_hover_highlight ||
( g_ectx.filter == filter_highlight && ovl->flags & g_ectx.filter_mask ) )
{
highlight = 1;
}
draw_ovl(cr, ovls_sorted[idx], y, scale, clip_xb, clip_xe, highlight);
}
return FALSE;
}
static gboolean on_key_press(GtkWidget* widget, GdkEventKey* event, gpointer user_data)
{
UNUSED(widget);
UNUSED(user_data);
switch (event->keyval)
{
case GDK_KEY_plus:
gtk_spin_button_spin(GTK_SPIN_BUTTON(g_ectx.edit_read), GTK_SPIN_STEP_FORWARD, 1);
break;
case GDK_KEY_minus:
gtk_spin_button_spin(GTK_SPIN_BUTTON(g_ectx.edit_read), GTK_SPIN_STEP_BACKWARD, 1);
break;
case GDK_KEY_f:
if (view_forward())
{
gtk_spin_button_set_value(GTK_SPIN_BUTTON(g_ectx.edit_read), view_current()->rid);
}
break;
case GDK_KEY_b:
if (view_back())
{
gtk_spin_button_set_value(GTK_SPIN_BUTTON(g_ectx.edit_read), view_current()->rid);
}
break;
case GDK_KEY_q:
g_ectx.show = show_q;
gtk_combo_box_set_active_id(GTK_COMBO_BOX(g_ectx.combo_show), "q");
redraw();
break;
case GDK_KEY_w:
g_ectx.show = show_distinct;
gtk_combo_box_set_active_id(GTK_COMBO_BOX(g_ectx.combo_show), "distinct");
redraw();
break;
case GDK_KEY_e:
g_ectx.show = show_same;
gtk_combo_box_set_active_id(GTK_COMBO_BOX(g_ectx.combo_show), "same");
redraw();
break;
case GDK_KEY_h:
{
int rid = g_ectx.rid_hover_highlight;
if (rid != -1)
{
if (highlight_has(rid) != -1)
{
highlight_remove(rid);
}
else
{
highlight_add(rid);
}
redraw();
}
}
break;
case GDK_KEY_H:
{
int rid = view_current()->rid;
if (rid != -1)
{
if (highlight_has(rid) != -1)
{
highlight_remove(rid);
}
else
{
highlight_add(rid);
}
}
}
break;
case GDK_KEY_c:
g_ectx.hcur = 0;
redraw();
break;
case GDK_KEY_l:
gtk_spin_button_spin(GTK_SPIN_BUTTON(g_ectx.edit_linewidth), GTK_SPIN_STEP_BACKWARD, 1);
break;
case GDK_KEY_L:
gtk_spin_button_spin(GTK_SPIN_BUTTON(g_ectx.edit_linewidth), GTK_SPIN_STEP_FORWARD, 1);
break;
}
return FALSE;
}
static gboolean frame_callback(GtkWindow* window, GdkEvent* event, gpointer data)
{
UNUSED(window);
UNUSED(event);
UNUSED(data);
adjust_drawing_area_size();
return FALSE;
}
static void edit_read_value_changed(GtkSpinButton* spin_button, gpointer user_data)
{
UNUSED(user_data);
int rid = gtk_spin_button_get_value_as_int(spin_button);
if ( view_current()->rid != rid )
{
view_new(rid);
}
load_overlaps();
gtk_widget_grab_focus(GTK_WIDGET(g_ectx.scrolled_wnd));
}
static void edit_hzoom_changed(GtkSpinButton* spin_button, gpointer user_data)
{
UNUSED(spin_button);
UNUSED(user_data);
view_current()->hzoom = gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(g_ectx.edit_hzoom));
gtk_widget_grab_focus(GTK_WIDGET(g_ectx.scrolled_wnd));
redraw();
}
static void edit_filter_pos_changed(GtkSpinButton* spin_button, gpointer user_data)
{
UNUSED(spin_button);
UNUSED(user_data);
int filter_ab = view_current()->filter_ab = gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(g_ectx.edit_filter_ab));
int filter_ae = view_current()->filter_ae = gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(g_ectx.edit_filter_ae));
if (filter_ab >= filter_ae)
{
view_current()->filter_ab = 0;
view_current()->filter_ae = DB_READ_LEN(&g_ectx.db, g_ectx.ovls->ovl.aread);
}
gtk_widget_grab_focus(GTK_WIDGET(g_ectx.scrolled_wnd));
filter_overlaps();
redraw();
}
static void edit_linewidth_value_changed(GtkSpinButton* sbtn, gpointer user_data)
{
UNUSED(user_data);
g_ectx.line_width = gtk_spin_button_get_value_as_int(sbtn);
adjust_drawing_area_size();
gtk_widget_grab_focus(GTK_WIDGET(g_ectx.scrolled_wnd));
}
static void check_revSort_toggled(GtkToggleButton* togglebutton, gpointer user_data)
{
UNUSED(user_data);
g_ectx.revSort = gtk_toggle_button_get_active(togglebutton);
sort_overlaps();
filter_overlaps();
redraw();
}
static void check_pad_toggled(GtkToggleButton* togglebutton, gpointer user_data)
{
UNUSED(user_data);
g_ectx.pad = gtk_toggle_button_get_active(togglebutton);
adjust_drawing_area_size();
gtk_widget_grab_focus(GTK_WIDGET(g_ectx.scrolled_wnd));
}
static void combo_filter_changed(GtkComboBox* widget, gpointer user_data)
{
UNUSED(user_data);
if (strcmp(gtk_combo_box_get_active_id(widget), "exclude") == 0)
{
g_ectx.filter = filter_exclude;
}
else if (strcmp(gtk_combo_box_get_active_id(widget), "include") == 0)
{
g_ectx.filter = filter_include;
}
else if (strcmp(gtk_combo_box_get_active_id(widget), "highlight") == 0)
{
g_ectx.filter = filter_highlight;
}
gtk_widget_grab_focus(GTK_WIDGET(g_ectx.scrolled_wnd));
filter_overlaps();
redraw();
}
static void combo_show_changed(GtkComboBox* widget, gpointer user_data)
{
UNUSED(user_data);
if (strcmp(gtk_combo_box_get_active_id(widget), "q") == 0)
{
g_ectx.show = show_q;
}
else if (strcmp(gtk_combo_box_get_active_id(widget), "distinct") == 0)
{
g_ectx.show = show_distinct;
}
else
{
g_ectx.show = show_same;
}
gtk_widget_grab_focus(GTK_WIDGET(g_ectx.scrolled_wnd));
redraw();
}
static void combo_sort_changed(GtkComboBox* widget, gpointer user_data)
{
UNUSED(user_data);
if (strcmp(gtk_combo_box_get_active_id(widget), "abpos") == 0)
{
g_ectx.sort = sort_abpos;
}
else if (strcmp(gtk_combo_box_get_active_id(widget), "aepos") == 0)
{
g_ectx.sort = sort_aepos;
}
else if (strcmp(gtk_combo_box_get_active_id(widget), "length") == 0)
{
g_ectx.sort = sort_length;
}
else if (strcmp(gtk_combo_box_get_active_id(widget), "readID") == 0)
{
g_ectx.sort = sort_readID;
}
else
{
g_ectx.sort = sort_qual;
}
gtk_widget_grab_focus(GTK_WIDGET(g_ectx.scrolled_wnd));
sort_overlaps();
filter_overlaps();
redraw();
}
static GtkWidget* setup_toolbar()
{
GtkWidget* toolbar = gtk_grid_new();
gtk_grid_set_column_spacing(GTK_GRID(toolbar), 10);
// read
gtk_grid_attach_next_to(GTK_GRID(toolbar), gtk_label_new("Read"), NULL, GTK_POS_RIGHT, 1, 1);
GtkWidget* edit_read = g_ectx.edit_read = gtk_spin_button_new_with_range(0, g_ectx.db.nreads - 1, 1);
gtk_grid_attach_next_to(GTK_GRID(toolbar), edit_read, NULL, GTK_POS_RIGHT, 1, 1);
g_signal_connect(G_OBJECT(edit_read), "value-changed", G_CALLBACK(edit_read_value_changed), NULL);
// sort mode
GtkWidget* combo_show = g_ectx.combo_show = gtk_combo_box_text_new();
gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(combo_show), "q", "Q");
gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(combo_show), "distinct", "Distinct");
gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(combo_show), "same", "Same");
gtk_combo_box_set_active_id(GTK_COMBO_BOX(combo_show), "same");
g_ectx.show = show_same;
g_signal_connect(G_OBJECT(combo_show), "changed", G_CALLBACK(combo_show_changed), NULL);
gtk_grid_attach_next_to(GTK_GRID(toolbar), combo_show, NULL, GTK_POS_RIGHT, 1, 1);
// line width
gtk_grid_attach_next_to(GTK_GRID(toolbar), gtk_label_new("Width"), NULL, GTK_POS_RIGHT, 1, 1);
GtkWidget* edit_linewidth = g_ectx.edit_linewidth = gtk_spin_button_new_with_range(1, 10, 1);
gtk_spin_button_set_value(GTK_SPIN_BUTTON(edit_linewidth), DEF_LINEWIDTH);
gtk_grid_attach_next_to(GTK_GRID(toolbar), edit_linewidth, NULL, GTK_POS_RIGHT, 1, 1);
g_signal_connect(G_OBJECT(edit_linewidth), "value-changed", G_CALLBACK(edit_linewidth_value_changed), NULL);
GtkWidget* check_pad = gtk_check_button_new();
gtk_grid_attach_next_to(GTK_GRID(toolbar), check_pad, NULL, GTK_POS_RIGHT, 1, 1);
g_signal_connect(G_OBJECT(check_pad), "toggled", G_CALLBACK(check_pad_toggled), NULL);
// h-zoom
gtk_grid_attach_next_to(GTK_GRID(toolbar), gtk_label_new("H-Zoom"), NULL, GTK_POS_RIGHT, 1, 1);
GtkWidget* edit_hzoom = g_ectx.edit_hzoom = gtk_spin_button_new_with_range(1, 1000, 1);
gtk_grid_attach_next_to(GTK_GRID(toolbar), edit_hzoom, NULL, GTK_POS_RIGHT, 1, 1);
g_signal_connect(G_OBJECT(edit_hzoom), "value-changed", G_CALLBACK(edit_hzoom_changed), NULL);
// begin/end filter
gtk_grid_attach_next_to(GTK_GRID(toolbar), gtk_label_new("Range"), NULL, GTK_POS_RIGHT, 1, 1);
GtkWidget* edit_filter_ab = g_ectx.edit_filter_ab = gtk_spin_button_new_with_range(0, 100, 100);
gtk_grid_attach_next_to(GTK_GRID(toolbar), edit_filter_ab, NULL, GTK_POS_RIGHT, 1, 1);
g_signal_connect(G_OBJECT(edit_filter_ab), "value-changed", G_CALLBACK(edit_filter_pos_changed), NULL);
GtkWidget* edit_filter_ae = g_ectx.edit_filter_ae = gtk_spin_button_new_with_range(0, 100, 100);
gtk_grid_attach_next_to(GTK_GRID(toolbar), edit_filter_ae, NULL, GTK_POS_RIGHT, 1, 1);
g_signal_connect(G_OBJECT(edit_filter_ae), "value-changed", G_CALLBACK(edit_filter_pos_changed), NULL);
// sort mode
gtk_grid_attach_next_to(GTK_GRID(toolbar), gtk_label_new("Sort"), NULL, GTK_POS_RIGHT, 1, 1);
GtkWidget* combo_sort = gtk_combo_box_text_new();
gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(combo_sort), "abpos", "begin");
gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(combo_sort), "aepos", "end");
gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(combo_sort), "readID", "read id");
gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(combo_sort), "length", "length");
gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(combo_sort), "qual", "quality");
gtk_combo_box_set_active_id(GTK_COMBO_BOX(combo_sort), "abpos");
g_ectx.sort = sort_abpos;
g_signal_connect(G_OBJECT(combo_sort), "changed", G_CALLBACK(combo_sort_changed), NULL);
gtk_grid_attach_next_to(GTK_GRID(toolbar), combo_sort, NULL, GTK_POS_RIGHT, 1, 1);
// reverse Sort
GtkWidget* check_revSort = g_ectx.check_revSort = gtk_check_button_new();
gtk_grid_attach_next_to(GTK_GRID(toolbar), check_revSort, NULL, GTK_POS_RIGHT, 1, 1);
g_signal_connect(G_OBJECT(check_revSort), "toggled", G_CALLBACK(check_revSort_toggled), NULL);
gtk_grid_attach_next_to(GTK_GRID(toolbar), gtk_label_new("reverse"), NULL, GTK_POS_RIGHT, 1, 1);
return toolbar;
}
static void update_details_bar(int x, int idx)
{
GtkWidget* bar = g_ectx.overlap_details;
OverlapDetails* ovls = g_ectx.ovls;
OverlapDetails** ovls_sorted = g_ectx.ovls_sorted;
Overlap* ovl = &(ovls_sorted[idx]->ovl);
int i;
int cov = 0;
for (i = 0; i < g_ectx.ocur; i++)
{
// TODO --- compute coverage stats in filter_overlaps
if (ovls[i].ovl.path.abpos <= x && x <= ovls[i].ovl.path.aepos)
{
cov++;
}
}
char flags[OVL_FLAGS + 1];
flags2str(flags, ovl->flags);
char q[8];
if (g_ectx.qtrack)
{
track_anno* qanno = g_ectx.qtrack->anno;
track_data* qdata = g_ectx.qtrack->data;
int ob = qanno[ovl->aread] / sizeof(track_data);
// int oe = qanno[ovl->aread + 1] / sizeof(track_data);
int qvalue = qdata[ ob + x / g_ectx.twidth ];
sprintf(q, " q %2d", qvalue);
}
else
{
q[0] = '\0';
}
char src[64];
if (g_ectx.srctrack)
{
track_anno* srcanno = g_ectx.srctrack->anno;
track_data* srcdata = g_ectx.srctrack->data;
uint64 srca = srcdata[ srcanno[ovl->aread] / sizeof(track_data) ];
uint64 srcb = srcdata[ srcanno[ovl->bread] / sizeof(track_data) ];
sprintf(src, " source reads %8llu x %8llu", srca, srcb);
}
else
{
src[0] = '\0';
}
gchar* text = g_markup_printf_escaped(
"<tt>@ %5dbp cov %3d%s <b>%8d</b> (%5d) x <b>%8d</b> (%5d) <b>%5d..%5d</b> (%5d) %c <b>%5d..%5d</b> (%5d)%s flags %s</tt>",
x, cov, q,
ovl->aread, DB_READ_LEN(&g_ectx.db, ovl->aread),
ovl->bread, DB_READ_LEN(&g_ectx.db, ovl->bread),
ovl->path.abpos, ovl->path.aepos, ovl->path.aepos - ovl->path.abpos,
ovl->flags & OVL_COMP ? '<' : '>',
ovl->path.bbpos, ovl->path.bepos, ovl->path.bepos - ovl->path.bbpos,
src, flags);
gtk_label_set_markup(GTK_LABEL(bar), text);
#if GTK_CHECK_VERSION(3, 14, 0)
gtk_list_box_unselect_all(GTK_LIST_BOX(g_ectx.filter_panel));
i = 0;
while (oflag2label[i].mask)
{
if (oflag2label[i].mask & ovl->flags)
{
gtk_list_box_select_row(GTK_LIST_BOX(g_ectx.filter_panel),
gtk_list_box_get_row_at_index(GTK_LIST_BOX(g_ectx.filter_panel), i));
}
i++;
}
#endif
g_free(text);
}
static gboolean read_mouse_move(GtkWidget* widget, GdkEvent* event, gpointer user_data)
{
UNUSED(widget);
UNUSED(user_data);
int idx = ypos2overlap(event->button.y);
int x = xpos2apos(event->button.x);
if (idx != -1) // && idx != g_ectx.idx_details)
{
g_ectx.idx_details = idx;
update_details_bar(x, idx);
}
if (idx != -1)
{
int bread = g_ectx.ovls_sorted[idx]->ovl.bread;
int bprev = g_ectx.rid_hover_highlight;
if (bread != bprev)
{
int i;
int width = gtk_widget_get_allocated_width(widget);
g_ectx.rid_hover_highlight = bread;
if (bprev != -1)
{
#ifdef DEBUG
printf("clear highlight bread %8d\n", bprev);
#endif
for (i = 0; i < g_ectx.novl_display; i++)
{
if (g_ectx.ovls_sorted[g_ectx.ovl_display[i]]->ovl.bread == bprev)
{
gtk_widget_queue_draw_area(g_ectx.drawing_area,
PADDING, overlap2ypos(i) - g_ectx.line_width, width - 2 * PADDING, g_ectx.line_width * (2 + g_ectx.pad));
}
}
}
#ifdef DEBUG
printf("add highlight bread %8d\n", bread);
#endif
for (i = 0; i < g_ectx.novl_display; i++)
{
if (g_ectx.ovls_sorted[g_ectx.ovl_display[i]]->ovl.bread == bread)
{
gtk_widget_queue_draw_area(g_ectx.drawing_area,
PADDING, overlap2ypos(i) - g_ectx.line_width, width - 2 * PADDING, g_ectx.line_width * (2 + g_ectx.pad));
}
}
}
}
return GDK_EVENT_PROPAGATE;
}
static gboolean context_go_to(GtkWidget* widget, GdkEvent* event, gpointer user_data)
{
UNUSED(widget);
UNUSED(event);
UNUSED(user_data);
int rid = g_ectx.rid_hover_highlight;
if (rid >= 0)
{
gtk_spin_button_set_value(GTK_SPIN_BUTTON(g_ectx.edit_read), rid);
view_new(rid);
load_overlaps();
}
return TRUE;
}
static gboolean menuitem_track(GtkWidget* widget, GdkEvent* event, gpointer user_data)
{
UNUSED(widget);
UNUSED(event);
UNUSED(user_data);
int rid = g_ectx.rid_hover_highlight;
if (highlight_has(rid) != -1)
{
highlight_remove(rid);
}
else
{
highlight_add(rid);
}
redraw();
return TRUE;
}
static gint show_right_click_menu(GdkEvent* event)
{
GtkMenu* menu = GTK_MENU(gtk_menu_new());
// GdkEventButton* event_button = (GdkEventButton*) event;
g_return_val_if_fail(event != NULL, FALSE);
char label[255];
int rid = g_ectx.rid_hover_highlight;
sprintf(label, "READ %d", rid);
GtkWidget* track_item = gtk_menu_item_new_with_label(label);
int i = 0;
gtk_menu_attach(menu, track_item, 0, 1, i, i + 1);
i++;
sprintf(label, "go to");
track_item = gtk_menu_item_new_with_label(label);
gtk_menu_attach(menu, track_item, 0, 1, i, i + 1);
g_signal_connect(G_OBJECT(track_item), "activate", G_CALLBACK(context_go_to), NULL);
i++;
if (highlight_has(rid) != -1)
{
sprintf(label, "remove highlight");
rid = -rid;
}
else
{
sprintf(label, "highlight");
}
track_item = gtk_menu_item_new_with_label(label);
gtk_menu_attach(menu, track_item, 0, 1, i, i + 1);
i++;
g_signal_connect(G_OBJECT(track_item), "activate", G_CALLBACK(menuitem_track), NULL);
gtk_widget_show_all(GTK_WIDGET(menu));
#if GTK_CHECK_VERSION(3, 22, 0)
gtk_menu_popup_at_pointer(menu, event);
#endif
return TRUE;
}
static gboolean read_button_press(GtkWidget* widget, GdkEvent* event, gpointer user_data)
{
UNUSED(widget);
UNUSED(user_data);
if (event->type == GDK_BUTTON_PRESS)
{
GdkEventButton* event_button = (GdkEventButton*) event;
int idx = ypos2overlap(event->button.y);
if (event_button->button == GDK_BUTTON_PRIMARY)
{
if (idx != -1)
{
int rid = g_ectx.ovls_sorted[idx]->ovl.bread;
gtk_spin_button_set_value(GTK_SPIN_BUTTON(g_ectx.edit_read), rid);
}
}
else if (event_button->button == GDK_BUTTON_SECONDARY)
{
show_right_click_menu(event);
}
}
return GDK_EVENT_PROPAGATE;
}
static void check_filter_toggled(GtkToggleButton* togglebutton, gpointer user_data)
{
UNUSED(togglebutton);
OverlapFlag2Label* label = (OverlapFlag2Label*) user_data;
int flag = label->mask;
if (g_ectx.filter == filter_highlight)
{
g_ectx.rid_hover_highlight = -1;
}
g_ectx.filter_mask ^= flag;
filter_overlaps();
redraw();
}
#if GTK_CHECK_VERSION(3, 10, 0)
static GtkWidget* setup_filter_panel(GtkWidget** listbox)
{
GtkWidget* right_panel = gtk_grid_new();
// filter mode
GtkWidget* combo_filter = gtk_combo_box_text_new();
gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(combo_filter), "exclude", "exclude selected");
gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(combo_filter), "include", "only selected");
gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(combo_filter), "highlight", "highlight selected");
gtk_combo_box_set_active_id(GTK_COMBO_BOX(combo_filter), "exclude");
g_ectx.filter = filter_exclude;
g_signal_connect(G_OBJECT(combo_filter), "changed", G_CALLBACK(combo_filter_changed), NULL);
gtk_grid_attach( GTK_GRID(right_panel), combo_filter, 0, 0, 1, 1);
GtkWidget* panel = gtk_list_box_new();
gtk_widget_set_vexpand(panel, TRUE);
gtk_list_box_set_selection_mode(GTK_LIST_BOX(panel), GTK_SELECTION_MULTIPLE);
gtk_grid_attach_next_to( GTK_GRID(right_panel), panel, combo_filter, GTK_POS_BOTTOM, 1, 1);
int i = 0;
while (oflag2label[i].mask)
{
GtkWidget* box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 5);
gtk_widget_set_halign(box, GTK_ALIGN_START);
gtk_box_pack_end(GTK_BOX(box), gtk_label_new(oflag2label[i].label), FALSE, FALSE, 0);
GtkWidget* check = gtk_check_button_new();
gtk_box_pack_end(GTK_BOX(box), check, FALSE, FALSE, 0);
g_signal_connect(G_OBJECT(check), "toggled", G_CALLBACK(check_filter_toggled), oflag2label + i);
gtk_list_box_insert(GTK_LIST_BOX(panel), box, i);
i++;
}
*listbox = panel;
return right_panel;
}
#endif
static gboolean on_scroll_event(GtkWidget* widget, GdkEvent* event, gpointer user_data)
{
UNUSED(widget);
UNUSED(event);
UNUSED(user_data);
// double dx, dy;
// gdk_event_get_scroll_deltas(event, &dx, &dy);
gtk_widget_queue_draw(g_ectx.drawing_tracks);
return FALSE;
}
static void activate(GtkApplication* app, gpointer user_data)
{
UNUSED(user_data);
GtkWidget* window;
// window title
int needed = 30 + strlen(g_ectx.pathDb) + strlen(g_ectx.pathLas);
int i;
for (i = 0; i < g_ectx.ntracks; i++)
{
needed += strlen(g_ectx.tracks[i]->name);
}
char* title = malloc(needed);
int tpos = sprintf(title, "LA Explorer - %s %s", g_ectx.pathDb, g_ectx.pathLas);
for (i = 0; i < g_ectx.ntracks; i++)
{
tpos += sprintf(title + tpos, " %s", g_ectx.tracks[i]->name);
}
// main window
window = gtk_application_window_new(app);
gtk_window_set_title(GTK_WINDOW(window), title);
free(title);
gtk_widget_add_events(GTK_WIDGET(window), GDK_CONFIGURE);
g_signal_connect(G_OBJECT(window), "configure-event", G_CALLBACK(frame_callback), NULL);
g_signal_connect(G_OBJECT (window), "key_press_event", G_CALLBACK (on_key_press), NULL);
GtkWidget* grid = gtk_grid_new();
// options bar
GtkWidget* bar = setup_toolbar();
gtk_grid_attach(GTK_GRID(grid), bar, 0, 0, 2, 1);
// overlap display
g_ectx.scrolled_wnd = GTK_SCROLLED_WINDOW(gtk_scrolled_window_new(NULL, NULL));
gtk_widget_set_hexpand(GTK_WIDGET(g_ectx.scrolled_wnd), TRUE);
gtk_widget_set_vexpand(GTK_WIDGET(g_ectx.scrolled_wnd), TRUE);
g_ectx.drawing_area = gtk_drawing_area_new();
gtk_widget_add_events(g_ectx.drawing_area, GDK_BUTTON_PRESS_MASK | GDK_POINTER_MOTION_MASK);
g_signal_connect(G_OBJECT(g_ectx.drawing_area), "draw", G_CALLBACK(read_draw_callback), NULL);
g_signal_connect(G_OBJECT(g_ectx.drawing_area), "button-press-event", G_CALLBACK(read_button_press), NULL);
g_signal_connect(G_OBJECT(g_ectx.drawing_area), "motion-notify-event", G_CALLBACK(read_mouse_move), NULL);
g_signal_connect(G_OBJECT(g_ectx.scrolled_wnd), "scroll-event", G_CALLBACK(on_scroll_event), NULL);
g_ectx.drawing_tracks = gtk_drawing_area_new();
g_signal_connect(G_OBJECT(g_ectx.drawing_tracks), "draw", G_CALLBACK(track_draw_callback), NULL);
gtk_widget_set_hexpand(GTK_WIDGET(g_ectx.drawing_tracks), TRUE);
gtk_widget_set_size_request(GTK_WIDGET(g_ectx.drawing_tracks), -1, PADDING + (g_ectx.ntracks + 1) * DEF_LINEWIDTH + PADDING);
gtk_grid_attach(GTK_GRID(grid), GTK_WIDGET(g_ectx.drawing_tracks), 0, 1, 1, 1);
gtk_container_add(GTK_CONTAINER(g_ectx.scrolled_wnd), g_ectx.drawing_area);
gtk_widget_set_can_focus(GTK_WIDGET(g_ectx.scrolled_wnd), TRUE);
gtk_grid_attach(GTK_GRID(grid), GTK_WIDGET(g_ectx.scrolled_wnd), 0, 2, 1, 1);
// overlap details bar
bar = g_ectx.overlap_details = gtk_label_new("");
gtk_widget_set_halign(bar, GTK_ALIGN_START);
gtk_grid_attach(GTK_GRID(grid), bar, 0, 3, 2, 1);
#if GTK_CHECK_VERSION(3, 10, 0)
// flags / filter panel
GtkWidget* panel = setup_filter_panel(&(g_ectx.filter_panel));
gtk_grid_attach(GTK_GRID(grid), panel, 1, 1, 1, 3);
#endif
gtk_container_add(GTK_CONTAINER(window), grid);
gtk_widget_show_all(window);
view_new(0);
load_overlaps();
}
static int command_line(GApplication* application, GApplicationCommandLine* cmdline)
{
gchar** argv;
gint argc;
argv = g_application_command_line_get_arguments(cmdline, &argc);
gchar* qname = TRACK_Q;
gchar* tname = TRACK_TRIM;
gchar* sname = TRACK_SOURCE;
gchar** inames = NULL;
gchar** remaining = NULL;
GOptionEntry entries[] = {
{"quality", 'q', 0, G_OPTION_ARG_STRING, &qname, "Quality track name", NULL},
{"trim", 't', 0, G_OPTION_ARG_STRING, &tname, "Trim track name", NULL},
{"source", 's', 0, G_OPTION_ARG_STRING, &sname, "Source read id track name", NULL},
{"interval", 'i', 0, G_OPTION_ARG_STRING_ARRAY, &inames, "Name of intervals track for display", NULL},
{G_OPTION_REMAINING, 0, 0, G_OPTION_ARG_STRING_ARRAY, &remaining, NULL, NULL},
{NULL, 0, 0, 0, NULL, NULL, NULL}
};
GOptionContext* optctx = g_option_context_new("database las");
g_option_context_add_main_entries(optctx, entries, NULL);
GError* error = NULL;
if ( ! g_option_context_parse(optctx, &argc, &argv, &error) )
{
g_print("failed to parse command line: %s\n", error->message);
exit(1);
}
if (remaining == NULL || remaining[0] == NULL || remaining[1] == NULL)
{
gchar* help = g_option_context_get_help(optctx, TRUE, NULL);
g_print("%s", help);
g_free(help);
exit(1);
}
g_ectx.pathDb = remaining[0];
if (Open_DB(g_ectx.pathDb, &g_ectx.db))
{
printf("could not open '%s'\n", g_ectx.pathDb);
exit(1);
}
int nreads = DB_NREADS(&(g_ectx.db));
int blocks = DB_Blocks(g_ectx.pathDb);
// open las files and their indices
g_ectx.lasFiles = malloc(sizeof(FILE*) * blocks);
bzero(g_ectx.lasFiles, sizeof(FILE*) * blocks);
g_ectx.lasIndexFile = malloc(sizeof(int) * nreads);
g_ectx.pathLas = remaining[1];
int rid;
for (rid = 0; rid < nreads; rid++)
{
g_ectx.lasIndexFile[rid] = -1;
}
char* num = strchr(g_ectx.pathLas, '#');
if (num != NULL)
{
char* pathLas = malloc(strlen(g_ectx.pathLas) + 10);
char* prefix = g_ectx.pathLas;
char* suffix = num + 1;
*num = '\0';
int b;
for (b = 1; b <= blocks; b++)
{
sprintf(pathLas, "%s%d%s", prefix, b, suffix);
if ((g_ectx.lasFiles[b - 1] = fopen(pathLas, "r")) == NULL)
{
fprintf(stderr, "could not open '%s'\n", pathLas);
exit(1);
}
if (b == 1)
{
g_ectx.lasIndex = lasidx_load(&(g_ectx.db), pathLas, 1);
int j;
for (j = 0; j < nreads; j++)
{
if (g_ectx.lasIndex[j] != 0)
{
g_ectx.lasIndexFile[j] = 0;
}
}
}
else
{
lasidx* lasIndex = lasidx_load(&(g_ectx.db), pathLas, 1);
int j;
for (j = 0; j < nreads; j++)
{
if (lasIndex[j] == 0)
{
continue;
}
if (g_ectx.lasIndex[j] != 0)
{
fprintf(stderr, "error: read id %d used in two indices\n", j);
// printf("%lld %lld\n", lasIndex[j], g_ectx.lasIndex[j]);
exit(1);
}
g_ectx.lasIndex[j] = lasIndex[j];
g_ectx.lasIndexFile[j] = b - 1;
}
free(lasIndex);
}
}
*num = '#';
}
else
{
if ((g_ectx.lasFiles[0] = fopen(g_ectx.pathLas, "r")) == NULL)
{
fprintf(stderr, "could not open '%s'\n", g_ectx.pathLas);
exit(1);
}
g_ectx.lasIndex = lasidx_load(&(g_ectx.db), g_ectx.pathLas, 1);
int j;
for (j = 0; j < nreads; j++)
{
if (g_ectx.lasIndex[j] != 0)
{
g_ectx.lasIndexFile[j] = 0;
}
}
}
g_ectx.qtrack = track_load(&g_ectx.db, qname);
g_ectx.srctrack = track_load(&g_ectx.db, sname);
int i = 0;
if (inames != NULL)
{
while ( inames[i] != NULL )
{
char* iname = inames[i];
if (g_ectx.ntracks >= g_ectx.maxtracks)
{
g_ectx.maxtracks = 1.2 * g_ectx.maxtracks + 100;
g_ectx.tracks = realloc(g_ectx.tracks, sizeof(HITS_TRACK*) * g_ectx.maxtracks);
g_ectx.track_type = realloc(g_ectx.track_type, sizeof(int) * g_ectx.maxtracks);
}
g_ectx.track_type[g_ectx.ntracks] = TRACK_INTERVAL;
if (!(g_ectx.tracks[g_ectx.ntracks] = track_load(&g_ectx.db, iname)))
{
printf("failed to load track %s\n", iname);
exit(1);
}
g_ectx.ntracks++;
i++;
}
}
// init
g_ectx.line_width = DEF_LINEWIDTH;
g_ectx.viewstack_cur = -1;
g_ectx.viewstack_fill = -1;
g_ectx.viewstack_max = 0;
g_ectx.viewstack = NULL;
g_ectx.omax = 500;
g_ectx.ovls = malloc(sizeof(OverlapDetails) * g_ectx.omax);
g_ectx.ovls_sorted = malloc(sizeof(OverlapDetails*) * g_ectx.omax);
g_ectx.ovl_display = malloc(sizeof(int) * g_ectx.omax);
g_ectx.hmax = 0;
g_ectx.hcur = 0;
g_ectx.highlight = NULL;
g_ectx.rid_hover_highlight = -1;
// view_new(0);
for (i = 0; i < HIGHLIGHT_COLORS; i++)
{
get_unique_color(i, HIGHLIGHT_COLORS, g_ectx.highlight_color + i);
}
// get trace info from header
ovl_header_novl novl;
ovl_header_read(g_ectx.lasFiles[0], &novl, &(g_ectx.twidth));
g_ectx.tbytes = TBYTES(g_ectx.twidth);
// enter even loop
g_option_context_free(optctx);
g_application_activate(application);
return 0;
}
int main(int argc, char** argv)
{
GtkApplication* app;
int status;
bzero(&g_ectx, sizeof(ExplorerContext));
// g_object_set (gtk_settings_get_default (), "gtk-enable-animations", FALSE, NULL);
app = gtk_application_new(NULL, G_APPLICATION_HANDLES_COMMAND_LINE);
g_signal_connect(app, "command-line", G_CALLBACK(command_line), NULL);
g_signal_connect(app, "activate", G_CALLBACK(activate), NULL);
status = g_application_run(G_APPLICATION(app), argc, argv);
g_object_unref(app);
return status;
}
|
MartinPippel/DAmar
|
db/FA2x.c
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "DB.h"
#include "lib/tracks.h"
#include "FA2x.h"
#ifdef HIDE_FILES
#define PATHSEP "/."
#else
#define PATHSEP "/"
#endif
int find_track(CreateContext* ctx, const char* name)
{
int i;
for (i = 0; i < ctx->t_cur; i++)
{
if (strcmp(ctx->t_name[i], name) == 0)
{
return i;
}
}
if (ctx->t_cur >= ctx->t_max)
{
int nmax = ctx->t_cur * 1.2 + 10;
ctx->t_name = (char**) realloc(ctx->t_name, sizeof(char*) * nmax);
ctx->t_anno = (track_anno**) realloc(ctx->t_anno, sizeof(track_anno*) * nmax);
ctx->t_data = (track_data**) realloc(ctx->t_data, sizeof(track_data*) * nmax);
ctx->t_max_anno = (int*) realloc(ctx->t_max_anno, sizeof(int) * nmax);
ctx->t_max_data = (int*) realloc(ctx->t_max_data, sizeof(int) * nmax);
ctx->t_cur_anno = (int*) realloc(ctx->t_cur_anno, sizeof(int) * nmax);
ctx->t_cur_data = (int*) realloc(ctx->t_cur_data, sizeof(int) * nmax);
ctx->t_max = nmax;
}
// printf("find_track> creating '%s' -> %d\n", name, i);
ctx->t_name[i] = strdup(name);
ctx->t_max_anno[i] = 1000;
ctx->t_cur_anno[i] = 0;
ctx->t_anno[i] = (track_anno*) malloc(sizeof(track_anno) * ctx->t_max_anno[i]);
bzero(ctx->t_anno[i], sizeof(track_anno) * ctx->t_max_anno[i]);
ctx->t_max_data[i] = 1000;
ctx->t_cur_data[i] = 0;
ctx->t_data[i] = (track_data*) malloc(sizeof(track_data) * ctx->t_max_data[i]);
ctx->t_cur++;
return i;
}
void add_to_track(CreateContext* ctx, int track, int64 read, track_data value)
{
if (read >= ctx->t_max_anno[track])
{
uint64 omax = ctx->t_max_anno[track];
uint64 nmax = read * 1.2 + 1000;
ctx->t_anno[track] = (track_anno*) realloc(ctx->t_anno[track], sizeof(track_anno) * nmax);
bzero(ctx->t_anno[track] + omax, sizeof(track_anno) * (nmax - omax));
ctx->t_max_anno[track] = nmax;
}
if (ctx->t_cur_data[track] >= ctx->t_max_data[track])
{
uint64 nmax = ctx->t_cur_data[track] * 1.2 + 1000;
ctx->t_data[track] = (track_data*) realloc(ctx->t_data[track], sizeof(track_data) * nmax);
ctx->t_max_data[track] = nmax;
}
if (strcmp(ctx->t_name[track], TRACK_PACBIO_CHEM) == 0)
{
ctx->t_anno[track][read] += sizeof(char);
}
else
{
ctx->t_anno[track][read] += sizeof(track_data);
}
ctx->t_data[track][ctx->t_cur_data[track]] = value;
ctx->t_cur_data[track]++;
}
static int getOffsetFromTrack(CreateContext* ctx, char* tname)
{
FILE* tfile;
char* fileName = NULL;
fileName = (char*) malloc(strlen(ctx->pwd) + strlen(ctx->root) + strlen(tname) + 30);
sprintf(fileName, "%s%s%s.%s.anno", ctx->pwd, PATHSEP, ctx->root, tname);
if ((tfile = fopen(fileName, "r")) == NULL)
{
return 0;
}
track_header_len tracklen;
track_header_size tracksize;
if (fread(&tracklen, sizeof(track_header_len), 1, tfile) != 1)
{
fclose(tfile);
free(fileName);
return 0;
}
if (tracklen != ctx->initialUreads)
{
printf("tracklen != ctx->initialUreads (%d, %d)\n", tracklen, ctx->initialUreads);
fclose(tfile);
free(fileName);
return 0;
}
if (fread(&tracksize, sizeof(track_header_size), 1, tfile) != 1)
{
fprintf(stderr, "[WARNING] Annotation file %s is corrupt. Unable to parse header size!\n", tname);
fclose(tfile);
free(fileName);
return 0;
}
track_anno offset;
if (fseek(tfile, sizeof(track_anno) * (ctx->initialUreads), SEEK_CUR))
{
free(fileName);
fclose(tfile);
fprintf(stderr, "[ERROR] - Unable to get last annotation field of track %s\n", tname);
return 0;
}
if (fread(&offset, sizeof(track_anno), 1, tfile) != 1)
{
free(fileName);
fclose(tfile);
fprintf(stderr, "[ERROR] - Unable to get last annotation field of track %s\n", tname);
return 0;
}
free(fileName);
fclose(tfile);
return offset;
}
static void finalize_tracks(CreateContext* ctx)
{
track_anno coff, off;
int i;
for (i = 0; i < ctx->t_cur; i++)
{
if (ctx->db->ureads >= ctx->t_max_anno[i])
{
int omax = ctx->t_max_anno[i];
int nmax = ctx->db->ureads + 1;
ctx->t_anno[i] = (track_anno*) realloc(ctx->t_anno[i], sizeof(track_anno) * nmax);
bzero(ctx->t_anno[i] + omax, sizeof(track_anno) * (nmax - omax));
ctx->t_max_anno[i] = nmax;
}
off = getOffsetFromTrack(ctx, ctx->t_name[i]);
int j;
for (j = ctx->initialUreads; j <= ctx->ureads; j++)
{
coff = ctx->t_anno[i][j];
ctx->t_anno[i][j] = off;
off += coff;
}
}
}
void write_tracks(CreateContext* ctx, char* dbpath)
{
if (ctx->t_cur == 0)
{
return;
}
finalize_tracks(ctx);
char* root = Root(dbpath, ".db");
char* pwd = PathTo(dbpath);
FILE* fileOut;
int i;
int tmax = strlen(ctx->t_name[0]);
for (i = 1; i < ctx->t_cur; i++)
{
int slen = strlen(ctx->t_name[i]);
if (tmax < slen)
{
tmax = slen;
}
}
int len = strlen(pwd) + 2 + strlen(root) + 1 + tmax + 6;
char* fname = (char*) malloc(len);
track_header_len tlen = ctx->ureads;
track_header_size tsize = sizeof(track_anno);
for (i = 0; i < ctx->t_cur; i++)
{
// anno
sprintf(fname, "%s/.%s.%s.anno", pwd, root, ctx->t_name[i]);
// check if file is already available
int fileExists = 0;
if ((fileOut = fopen(fname, "r")) != NULL)
{
fileExists = 1;
fclose(fileOut);
}
if (fileExists)
{
if ((fileOut = fopen(fname, "r+")) == NULL)
{
fprintf(stderr, "[ERROR] - Cannot open file %s for appending track %s\n", fname, ctx->t_name[i]);
exit(1);
}
fwrite(&tlen, sizeof(track_header_len), 1, fileOut);
fwrite(&tsize, sizeof(track_header_size), 1, fileOut);
fflush(fileOut);
fseeko(fileOut, -sizeof(track_anno), SEEK_END);
fwrite(ctx->t_anno[i] + ctx->initialUreads, sizeof(track_anno), (tlen + 1) - ctx->initialUreads, fileOut);
}
else
{
if ((fileOut = fopen(fname, "w")) == NULL)
{
fprintf(stderr, "[WARNING] Cannot create file %s. Skip track %s.\n", fname, ctx->t_name[i]);
continue;
}
fwrite(&tlen, sizeof(track_header_len), 1, fileOut);
fwrite(&tsize, sizeof(track_header_size), 1, fileOut);
fflush(fileOut);
fwrite(ctx->t_anno[i], sizeof(track_anno), (tlen + 1), fileOut);
}
fclose(fileOut);
// data
sprintf(fname, "%s/.%s.%s.data", pwd, root, ctx->t_name[i]);
fileOut = fopen(fname, "a");
if (strcmp(ctx->t_name[i], TRACK_PACBIO_CHEM) == 0)
{
int v;
for (v = 0; v < ctx->t_cur_data[i]; v++)
{
fputc((char) ctx->t_data[i][v], fileOut);
}
}
else
{
fwrite(ctx->t_data[i], sizeof(track_data), ctx->t_cur_data[i], fileOut);
}
fclose(fileOut);
}
free(fname);
}
void free_tracks(CreateContext* ctx)
{
int i;
for (i = 0; i < ctx->t_cur; i++)
{
free(ctx->t_name[i]);
free(ctx->t_anno[i]);
free(ctx->t_data[i]);
}
free(ctx->t_name);
free(ctx->t_anno);
free(ctx->t_data);
free(ctx->t_max_anno);
free(ctx->t_cur_anno);
free(ctx->t_max_data);
free(ctx->t_cur_data);
}
|
MartinPippel/DAmar
|
lib/laz.c
|
<reponame>MartinPippel/DAmar
#include "laz.h"
#include <zlib.h>
LAZ* laz_open(char* fpath, int create)
{
FILE* fin = NULL;
LAZ* laz = NULL;
if (create)
{
laz->file = fopen(fpath, "wb");
}
else
{
laz->file = fopen(fpath, "rb");
}
if (laz->file == NULL)
{
return NULL;
}
laz = calloc( 1, sizeof(LAZ) );
laz->file = fin;
return laz;
}
int laz_read_header(LAZ* laz)
{
LAZ_HEADER header;
if ( fread(&header, sizeof(LAZ_HEADER), 1, laz->file) != 1 )
{
return 0;
}
if (header.magic != LAZ_MAGIC)
{
return 0;
}
laz->version = header.version;
laz->novl = header.novl;
laz->twidth = header.twidth;
return 1;
}
int laz_read_index(LAZ* laz, LAZ_INDEX* lidx)
{
if ( fread(lidx, sizeof(LAZ_INDEX), 1, laz->file) != 1 )
{
return 0;
}
return 1;
}
int laz_close(LAZ* laz)
{
if (laz->file)
{
fclose(laz->file);
}
if (laz)
{
free(laz);
}
return 1;
}
Overlap* laz_read(LAZ* laz)
{
Overlap* ovl = NULL;
if ( laz->ocur < laz->on )
{
ovl = laz->ovl + laz->ocur;
laz->ocur += 1;
}
else
{
LAZ_INDEX lidx;
if ( laz_read_index(laz, &lidx) )
{
if ( laz->omax < lidx.novl )
{
laz->omax = lidx.novl;
laz->ovl = realloc( laz->ovl, sizeof(Overlap) * laz->omax );
}
laz->on = lidx.novl;
laz->ocur = 0;
off_t cur = ftell(laz->file);
uint64_t olen = lidx.data - cur;
uint64_t dlen = lidx.next - lidx.data;
if ( olen > laz->bmax )
{
laz->bmax = olen;
laz->buf = realloc( laz->buf, laz->bmax );
}
uLongf destlen;
fread( laz->buf, olen, 1, laz->file );
uncompress(laz->ovl, &destlen, laz->buf, olen);
fseek( laz->file, dlen, SEEK_CUR );
}
}
return ovl;
}
int laz_write(LAZ* laz, Overlap* ovl)
{
}
|
MartinPippel/DAmar
|
utils/LAcount.c
|
/*******************************************************************************************
*
* validates the overlaps prior to sorting and merging
*
* Author: <NAME>
*
* Date : January 2015
*
*******************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "db/DB.h"
#include "dalign/filter.h"
#include "lib/oflags.h"
#include "lib/pass.h"
static void usage()
{
fprintf(stderr, "usage :<nthreads> <db> <blocks.dir>\n");
}
int main(int argc, char* argv[])
{
if (argc != 4)
{
usage();
exit(1);
}
int nthreads = atoi(argv[1]);
char* pcDb = argv[2];
char* pcPathOverlaps = argv[3];
char* pwd = PathTo(pcDb);
char* root = Root(pcDb, ".db");
FILE* fileDb;
int nfiles, nblocks, i;
// read the .db file and get the number blocks
if ( (fileDb = fopen(Catenate(pwd,"/",root,".db"),"r")) == NULL )
{
fprintf(stderr, "failed to open database\n");
exit(1);
}
if ( fscanf(fileDb, "files = %d\n", &nfiles) != 1 )
{
fprintf(stderr, "format error in database file\n");
exit(1);
}
for (i = 0; i < nfiles; i++)
{
char buffer[30001];
if (fgets(buffer, 30000, fileDb) == NULL)
{
fprintf(stderr, "format error in database file\n");
exit(1);
}
}
if ( fscanf(fileDb, "blocks = %d\n", &nblocks) != 1 )
{
fprintf(stderr, "format error in database file\n");
exit(1);
}
// which block are we checking
int len = strlen(pcPathOverlaps);
if (pcPathOverlaps[len-1] == '/')
{
pcPathOverlaps[len-1] = '\0';
}
char* pcBlock = strrchr(pcPathOverlaps, '_');
if (!pcBlock)
{
fprintf(stderr, "format error in overlaps directory\n");
exit(1);
}
char* end;
int nblock = strtol(pcBlock + 1, &end, 10);
if ( *end != '\0' || nblock < 1 || nblock > nblocks )
{
fprintf(stderr, "format error in overlaps directory\n");
exit(1);
}
// make sure all .las files for this block exist and are not truncated
printf("%d blocks total\n", nblocks);
printf("%d threads\n", nthreads);
printf("checking block %d\n", nblock);
char* path = malloc( strlen(pcPathOverlaps) + 100 );
int passed = 0;
int failed = 0;
int block;
for (block = 1; block <= nblocks; block++)
{
int type;
for (type = 0; type < 2; type++)
{
int thread;
for (thread = 0; thread < nthreads; thread++)
{
sprintf(path, "%s/%s.%d.%s.%d.%c%d.las", pcPathOverlaps, root, nblock, root, block, "CN"[type], thread);
FILE* fileLas = fopen(path, "r");
// missing
if (fileLas == NULL)
{
printf("missing %s\n", path);
failed++;
continue;
}
// truncated ( 0-byte file )
struct stat st;
stat(path, &st);
if (st.st_size == 0)
{
printf("zero-size %s\n", path);
failed++;
fclose(fileLas);
continue;
}
// not 0-byte, but header empty ( overlapper crashed most likely )
ovl_header_novl novl = 0;
ovl_header_twidth twidth;
ovl_header_read(fileLas, &novl, &twidth);
if (novl == 0)
{
printf("bad header %s\n", path);
failed++;
fclose(fileLas);
continue;
}
passed++;
fclose(fileLas);
}
}
}
free(path);
printf("passed %d\n", passed);
printf("failed %d\n", failed);
return (failed != 0);
}
|
MartinPippel/DAmar
|
msa/msa.h
|
<filename>msa/msa.h
#pragma once
#include "lib/pass.h"
#include "dalign/align.h"
typedef struct
{
unsigned long counts[5]; // A C G T -
} msa_profile_entry;
typedef struct
{
int* vector;
int vecmax;
int* trace;
int ntrace;
int* Stop; // Ongoing stack of alignment indels
char* Babs; // Absolute base of A and B sequences
int** PVF; // waves for NP alignment
int** PHF;
msa_profile_entry* Aabs;
} msa_alignment_ctx;
typedef struct
{
msa_profile_entry* profile;
int curprof;
int maxprof;
char** msa_seq; // points to sequences
int msa_max; // mem for msa_seq and msa_smax allocated
int* msa_smax; // mem for msa_seq[i] allocated
int* msa_lgaps; // number of leading gaps in seq[i]
int* msa_len; // length of seq[i]
int* msa_ids; // ids for the added sequences
int* track;
int tmax;
char* seq;
int nseq;
int alen;
int added;
int twidth;
int* ptp; // storage for pass through points
int ptpmax;
msa_alignment_ctx* aln_ctx;
} msa;
msa* msa_init();
void msa_free(msa* m);
void msa_reset(msa* m);
void msa_add(msa* m, char* seq, int pb, int pe, int sb, int se, ovl_trace* trace, int tlen, int id);
char* msa_consensus(msa* m, int dashes);
void msa_print(msa* m, FILE* fileOut, int b, int e);
void msa_print_v(msa* m, FILE* fileOut);
void msa_print_profile(msa* m, FILE* fileOut, int b, int e, int colorize);
void msa_print_simple( msa* m, FILE* filemsa, FILE* filerids, int b, int e );
|
MartinPippel/DAmar
|
utils/LAZtest.c
|
/*******************************************************************************************
*
* Displays the contents of a .las file
*
* Date : May 2015
*
* Author : <NAME>
*
*******************************************************************************************/
#include <assert.h>
#include <ctype.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/param.h>
#include "lib/colors.h"
#include "lib/oflags.h"
#include "lib/pass.h"
#include "lib/tracks.h"
#include "lib/utils.h"
#include "dalign/align.h"
#include "db/DB.h"
// getopt
extern char* optarg;
extern int optind, opterr, optopt;
typedef struct
{
} TestContext;
static void pre_test( PassContext* pctx, TestContext* tctx )
{
}
static void post_test()
{
}
static int handler_test( void* _ctx, Overlap* ovls, int novl )
{
TestContext* ctx = (TestContext*)_ctx;
return 1;
}
static void usage()
{
printf( "<db> <overlaps>\n" );
};
int main( int argc, char* argv[] )
{
HITS_DB db;
PassContext* pctx;
TestContext tctx;
bzero( &tctx, sizeof( TestContext ) );
// process arguments
int c;
while ( ( c = getopt( argc, argv, "" ) ) != -1 )
{
switch ( c )
{
default:
printf( "Unknown option: %s\n", argv[ optind - 1 ] );
usage();
exit( 1 );
}
}
if ( argc - optind < 2 )
{
usage();
exit( 1 );
}
char* dbpath = argv[ optind++ ];
char* ovlpath = argv[ optind++ ];
if ( Open_DB( dbpath, &db ) )
{
printf( "could not open '%s'\n", dbpath );
exit( 1 );
}
Close_DB( &db );
return 0;
}
|
MartinPippel/DAmar
|
scrub/tandem.c
|
/************************************************************************************\
* *
* Copyright (c) 2014, Dr. <NAME> (EWM). All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without modification, *
* are permitted provided that the following conditions are met: *
* *
* · Redistributions of source code must retain the above copyright notice, this *
* list of conditions and the following disclaimer. *
* *
* · Redistributions in binary form must reproduce the above copyright notice, this *
* list of conditions and the following disclaimer in the documentation and/or *
* other materials provided with the distribution. *
* *
* · The name of EWM may not be used to endorse or promote products derived from *
* this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY EWM ”AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, *
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND *
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL EWM BE LIABLE *
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS *
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY *
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING *
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN *
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
* *
* For any issues regarding this software and its use, contact EWM at: *
* *
* <NAME>r. *
* Bautzner Str. 122e *
* 01099 Dresden *
* GERMANY *
* Email: <EMAIL> *
* *
\************************************************************************************/
/*******************************************************************************************
*
* Adaption of the fast local alignment filter of "daligner" for finding alignments between
* a read and itself above the diagonal. Satellites create a "ladder" of these self alignments
* that can be detected in order to recognize said repetitive sequences within the read.
*
* Author : <NAME>
* First : March 2016
* Current: March 27, 2016
*
********************************************************************************************/
// A complete threaded code for the filter
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <math.h>
#include <pthread.h>
#include "db/DB.h"
#include "dalign/align.h"
#include "tandem.h"
#define THREAD pthread_t
#define PANEL_SIZE 50000 // Size to break up very long A-reads
#define PANEL_OVERLAP 10000 // Overlap of A-panels
#define MATCH_CHUNK 100 // Max initial number of hits between two reads
#define TRACE_CHUNK 20000 // Max initial trace points in hits between two reads
#undef TEST_LSORT
#undef TEST_KSORT
#undef TEST_PAIRS
#undef TEST_CSORT
#define HOW_MANY 3000 // Print first HOW_MANY items for each of the TEST options above
#undef TEST_GATHER
#undef TEST_CONTAIN
#undef SHOW_OVERLAP // Show the cartoon
#undef SHOW_ALIGNMENT // Show the alignment
#define ALIGN_WIDTH 80 // Parameters for alignment
#define ALIGN_INDENT 20
#define ALIGN_BORDER 10
#ifdef SHOW_OVERLAP
#define NOTHREAD
#endif
#ifdef TEST_GATHER
#define NOTHREAD
#endif
#ifdef TEST_CONTAIN
#define NOTHREAD
#endif
typedef struct
{ uint64 p1; // The lower half
uint64 p2;
} Double;
#if __ORDER_LITTLE_ENDIAN__ == __BYTE_ORDER__
typedef struct
{ uint64 code;
int rpos;
int read;
} KmerPos;
#else
typedef struct
{ uint64 code;
int read;
int rpos;
} KmerPos;
#endif
/*******************************************************************************************
*
* PARAMETER SETUP
*
********************************************************************************************/
static int Kmer;
static int Hitmin;
static int Binshift;
static int Kshift; // 2*Kmer
static uint64 Kmask; // 4^Kmer-1
static int NTHREADS; // Must be a power of 2
static int NSHIFT; // log_2 NTHREADS
int Set_Filter_Params(int kmer, int binshift, int hitmin, int nthreads)
{ if (kmer <= 1)
return (1);
Kmer = kmer;
Binshift = binshift;
Hitmin = hitmin;
Kshift = 2*Kmer;
if (Kmer == 32)
Kmask = 0xffffffffffffffffllu;
else
Kmask = (0x1llu << Kshift) - 1;
NTHREADS = 1;
NSHIFT = 0;
while (2*NTHREADS <= nthreads)
{ NTHREADS *= 2;
NSHIFT += 1;
}
return (0);
}
/*******************************************************************************************
*
* LEXICOGRAPHIC SORT
*
********************************************************************************************/
#define BMER 4
#define BSHIFT 8 // = 2*BMER
#define BPOWR 256 // = 2^BSHIFT
#define BMASK 0xffllu // = BPOWR-1
static uint64 QMASK; // = BMASK << NSHIFT
static int LEX_shift;
static int64 LEX_zsize;
static int LEX_last;
static int LEX_next;
static Double *LEX_src;
static Double *LEX_trg;
typedef struct
{ int64 beg;
int64 end;
int64 tptr[BPOWR];
int64 *sptr;
} Lex_Arg;
static void *lex_thread(void *arg)
{ Lex_Arg *data = (Lex_Arg *) arg;
int64 *sptr = data->sptr;
int64 *tptr = data->tptr;
int shift = LEX_shift; // Must be a multiple of 8 in [0,120]
int qshift = (LEX_next - LEX_shift) - NSHIFT;
int64 zsize = LEX_zsize;
Double *src = LEX_src;
Double *trg = LEX_trg;
int64 i, n, x;
uint64 c, b;
n = data->end;
if (shift >= 64)
{ shift -= 64;
if (LEX_last)
for (i = data->beg; i < n; i++)
{ c = src[i].p2;
b = (c >> shift);
x = tptr[b&BMASK]++;
trg[x] = src[i];
}
else
for (i = data->beg; i < n; i++)
{ c = src[i].p2;
b = (c >> shift);
x = tptr[b&BMASK]++;
trg[x] = src[i];
sptr[((b >> qshift) & QMASK) + x/zsize] += 1;
}
}
else if ( ! LEX_last && LEX_next >= 64) // && LEX_shift < 64
{ qshift = (LEX_next - 64) - NSHIFT;
if (qshift < 0)
for (i = data->beg; i < n; i++)
{ c = src[i].p1;
b = (c >> shift);
x = tptr[b&BMASK]++;
trg[x] = src[i];
sptr[((src[i].p2 << NSHIFT) & QMASK) + x/zsize] += 1;
}
else
for (i = data->beg; i < n; i++)
{ c = src[i].p1;
b = (c >> shift);
x = tptr[b&BMASK]++;
trg[x] = src[i];
sptr[((src[i].p2 >> qshift) & QMASK) + x/zsize] += 1;
}
}
else // LEX_last || LEX_next < 64
if (LEX_last)
if (shift == 0)
for (i = data->beg; i < n; i++)
{ c = src[i].p1;
x = tptr[c&BMASK]++;
trg[x] = src[i];
}
else
for (i = data->beg; i < n; i++)
{ c = src[i].p1;
b = (c >> shift);
x = tptr[b&BMASK]++;
trg[x] = src[i];
}
else
if (shift == 0)
for (i = data->beg; i < n; i++)
{ c = src[i].p1;
x = tptr[c&BMASK]++;
trg[x] = src[i];
sptr[((c >> qshift) & QMASK) + x/zsize] += 1;
}
else
for (i = data->beg; i < n; i++)
{ c = src[i].p1;
b = (c >> shift);
x = tptr[b&BMASK]++;
trg[x] = src[i];
sptr[((b >> qshift) & QMASK) + x/zsize] += 1;
}
return (NULL);
}
static Double *lex_sort(int bytes[16], Double *src, Double *trg, Lex_Arg *parmx)
{ THREAD threads[NTHREADS];
int64 len, x, y;
Double *xch;
int i, j, k, z;
int b, c, fb;
len = parmx[NTHREADS-1].end;
LEX_zsize = (len-1)/NTHREADS + 1;
LEX_src = src;
LEX_trg = trg;
QMASK = (BMASK << NSHIFT);
for (c = 0; c < 16; c++)
if (bytes[c])
break;
fb = c;
for (b = c; b < 16; b = c)
{ for (c = b+1; c < 16; c++)
if (bytes[c])
break;
LEX_last = (c >= 16);
LEX_shift = (b << 3);
LEX_next = (c << 3);
if (b == fb)
{ for (i = 0; i < NTHREADS; i++)
for (z = 0; z < NTHREADS*BPOWR; z++)
parmx[i].sptr[z] = 0;
}
else
{ x = 0;
for (i = 0; i < NTHREADS; i++)
{ parmx[i].beg = x;
x = LEX_zsize*(i+1);
if (x > len)
x = len;
parmx[i].end = x;
for (j = 0; j < BPOWR; j++)
parmx[i].tptr[j] = 0;
}
parmx[NTHREADS-1].end = len;
for (j = 0; j < BPOWR; j++)
{ k = (j << NSHIFT);
for (z = 0; z < NTHREADS; z++)
for (i = 0; i < NTHREADS; i++)
{ parmx[i].tptr[j] += parmx[z].sptr[k+i];
parmx[z].sptr[k+i] = 0;
}
}
}
x = 0;
for (j = 0; j < BPOWR; j++)
for (i = 0; i < NTHREADS; i++)
{ y = parmx[i].tptr[j];
parmx[i].tptr[j] = x;
x += y;
}
for (i = 0; i < NTHREADS; i++)
pthread_create(threads+i,NULL,lex_thread,parmx+i);
for (i = 0; i < NTHREADS; i++)
pthread_join(threads[i],NULL);
xch = LEX_src;
LEX_src = LEX_trg;
LEX_trg = xch;
#ifdef TEST_LSORT
printf("\nLSORT %d\n",LEX_shift);
if (LEX_shift >= 64)
{ x = (1 << ((LEX_shift-64)+BSHIFT))-1;
for (i = 0; i < len; i++)
{ printf("%6d: %8llx %8llx %8llx %8llx : %4llx",
i,LEX_src[i].p2>>32,(LEX_src[i].p2)&0xffffffffll,LEX_src[i].p1>>32,
LEX_src[i].p1&0xffffffffll,LEX_src[i].p2&x);
if (i > 0 && (LEX_src[i].p1 < LEX_src[i].p1 ||
(LEX_src[i].p1 == LEX_src[i].p1 &&
(LEX_src[i].p2 & x) < (LEX_src[i-1].p2 & x))))
printf(" OO");
printf("\n");
}
}
else
{ x = (1 << (LEX_shift+BSHIFT))-1;
for (i = 0; i < len; i++)
{ printf("%6d: %8llx %8llx %8llx %8llx : %4llx",
i,LEX_src[i].p2>>32,(LEX_src[i].p2)&0xffffffffll,LEX_src[i].p1>>32,
LEX_src[i].p1&0xffffffffll,LEX_src[i].p1&x);
if (i > 0 && (LEX_src[i].p1 & x) < (LEX_src[i-1].p1 & x))
printf(" OO");
printf("\n");
}
}
#endif
}
return (LEX_src);
}
/*******************************************************************************************
*
* INDEX BUILD
*
********************************************************************************************/
static HITS_DB *TA_block;
static KmerPos *TA_list;
typedef struct
{ int tnum;
int64 *kptr;
} Tuple_Arg;
static void *tuple_thread(void *arg)
{ Tuple_Arg *data = (Tuple_Arg *) arg;
int tnum = data->tnum;
int64 *kptr = data->kptr;
KmerPos *list = TA_list;
int i, m, n, x, p;
uint64 c;
char *s;
c = TA_block->nreads;
i = (c * tnum) >> NSHIFT;
n = TA_block->reads[i].boff;
s = ((char *) (TA_block->bases)) + n;
n -= Kmer*i;
for (m = (c * (tnum+1)) >> NSHIFT; i < m; i++)
{ c = p = 0;
for (x = 1; x < Kmer; x++)
c = (c << 2) | s[p++];
while ((x = s[p]) != 4)
{ c = ((c << 2) | x) & Kmask;
list[n].read = i;
list[n].rpos = ++p;
list[n].code = c;
n += 1;
kptr[c & BMASK] += 1;
}
s += (p+1);
}
return (NULL);
}
static KmerPos *Sort_Kmers(HITS_DB *block, int *len, KmerPos **buffer)
{ THREAD threads[NTHREADS];
Tuple_Arg parmt[NTHREADS];
Lex_Arg parmx[NTHREADS];
int mersort[16];
KmerPos *src, *trg, *rez;
int kmers, nreads;
int i, j, x;
for (i = 0; i < NTHREADS; i++)
parmx[i].sptr = (int64 *) alloca(NTHREADS*BPOWR*sizeof(int64));
for (i = 0; i < 16; i++)
mersort[i] = 0;
for (i = 0; i < Kshift; i += 8)
mersort[i>>3] = 1;
nreads = block->nreads;
kmers = block->reads[nreads].boff - Kmer * nreads;
if (kmers <= 0)
goto no_mers;
if (((Kshift-1)/BSHIFT) & 0x1)
{ trg = (KmerPos *) Malloc(sizeof(KmerPos)*(kmers+1),"Allocating Sort_Kmers vectors");
src = (KmerPos *) Malloc(sizeof(KmerPos)*(kmers+1),"Allocating Sort_Kmers vectors");
}
else
{ src = (KmerPos *) Malloc(sizeof(KmerPos)*(kmers+1),"Allocating Sort_Kmers vectors");
trg = (KmerPos *) Malloc(sizeof(KmerPos)*(kmers+1),"Allocating Sort_Kmers vectors");
}
if (src == NULL || trg == NULL)
exit (1);
if (VERBOSE)
{ printf("\n Kmer count = ");
Print_Number((int64) kmers,0,stdout);
printf("\n Using %.2fGb of space\n",(1. * kmers) / 33554432);
fflush(stdout);
}
TA_block = block;
TA_list = src;
for (i = 0; i < NTHREADS; i++)
{ parmt[i].tnum = i;
parmt[i].kptr = parmx[i].tptr;
for (j = 0; j < BPOWR; j++)
parmt[i].kptr[j] = 0;
}
for (i = 0; i < NTHREADS; i++)
pthread_create(threads+i,NULL,tuple_thread,parmt+i);
for (i = 0; i < NTHREADS; i++)
pthread_join(threads[i],NULL);
x = 0;
for (i = 0; i < NTHREADS; i++)
{ parmx[i].beg = x;
j = (int) ((((int64) nreads) * (i+1)) >> NSHIFT);
parmx[i].end = x = block->reads[j].boff - j*Kmer;
}
rez = (KmerPos *) lex_sort(mersort,(Double *) src,(Double *) trg,parmx);
if (rez[kmers-1].code == 0xffffffffffffffffllu)
rez[kmers].code = 0;
else
rez[kmers].code = 0xffffffffffffffffllu;
rez[kmers].read = nreads;
if (src != rez)
*buffer = src;
else
*buffer = trg;
#ifdef TEST_KSORT
{ int i;
printf("\nKMER SORT:\n");
for (i = 0; i < HOW_MANY && i < kmers; i++)
{ KmerPos *c = rez+i;
printf(" %5d / %5d / %10lld\n",c->read,c->rpos,c->code);
}
fflush(stdout);
}
#endif
if (VERBOSE)
{ printf(" Index occupies %.2fGb\n",(1. * kmers) / 67108864);
fflush(stdout);
}
if (kmers <= 0)
{ free(rez);
goto no_mers;
}
*len = kmers;
return (rez);
no_mers:
*len = 0;
return (NULL);
}
/*******************************************************************************************
*
* FILTER MATCH
*
********************************************************************************************/
// After the initial sort, all equal K-tuples are contiguous, and for a given K-tuple read,rpos
// is in sorted order because the sort is stable. For a given read, record the distance between
// consecutive positions with the same K-mer in the .code field. Afterwords, the array is
// stably resorted on read,rpos so that for each read one has effectively a "linked list" of
// positions with equal K-mers.
static KmerPos *MG_alist;
typedef struct
{ int abeg, aend;
int64 *kptr;
} Merge_Arg;
static void *count_thread(void *arg)
{ Merge_Arg *data = (Merge_Arg *) arg;
int64 *kptr = data->kptr;
KmerPos *asort = MG_alist;
int aend = data->aend;
uint64 ca, da;
int ia;
int ar, nr;
int ap, np;
ia = data->abeg;
da = asort[ia].code;
while (ia < aend)
{ ca = da;
ar = asort[ia].read;
ap = asort[ia].rpos;
kptr[ap & BMASK] += 1;
while ((da = asort[++ia].code) == ca)
{ np = asort[ia].rpos;
if ((nr = asort[ia].read) == ar)
asort[ia].code = np - ap;
else
{ asort[ia].code = 0;
ar = nr;
}
ap = np;
kptr[ap & BMASK] += 1;
}
asort[ia].code = 0;
}
return (NULL);
}
// Report threads: using the linked lists of consereved K-mers find likely seeds and then check
// for alignments as per "daligner".
static HITS_DB *MR_ablock;
static Align_Spec *MR_spec;
static int MR_tspace;
typedef struct
{ uint64 max;
uint64 top;
uint16 *trace;
} Trace_Buffer;
// Determine if the minimum B-distance between the overlapping trace points of jpath and kpath
// Return this minimum and also the A-coordinate of a trace point where it is acheived.
static int Entwine(Path *jpath, Path *kpath, Trace_Buffer *tbuf, int *where)
{ int ac, b2, y2, ae;
int i, j, k;
int num, den, min;
#ifdef SEE_ENTWINE
int strt, iflare, oflare;
#endif
uint16 *ktrace = tbuf->trace + (uint64) (kpath->trace);
uint16 *jtrace = tbuf->trace + (uint64) (jpath->trace);
min = 10000;
num = 0;
den = 0;
#ifdef SEE_ENTWINE
strt = 1;
printf("\n");
#endif
y2 = jpath->bbpos;
j = jpath->abpos/MR_tspace;
b2 = kpath->bbpos;
k = kpath->abpos/MR_tspace;
if (jpath->abpos == kpath->abpos)
{ min = abs(y2-b2);
if (min == 0)
*where = kpath->abpos;
}
if (j < k)
{ ac = k*MR_tspace;
j = 1 + 2*(k-j);
k = 1;
for (i = 1; i < j; i += 2)
y2 += jtrace[i];
}
else
{ ac = j*MR_tspace;
k = 1 + 2*(j-k);
j = 1;
for (i = 1; i < k; i += 2)
b2 += ktrace[i];
}
ae = jpath->aepos;
if (ae > kpath->aepos)
ae = kpath->aepos;
while (1)
{ ac += MR_tspace;
if (ac >= ae)
break;
y2 += jtrace[j];
b2 += ktrace[k];
j += 2;
k += 2;
#ifdef SEE_ENTWINE
printf(" @ %5d : %5d %5d = %4d\n",ac,y2,b2,abs(b2-y2));
#endif
i = abs(y2-b2);
if (i <= min)
{ min = i;
if (i == 0)
*where = ac;
}
num += i;
den += 1;
#ifdef SEE_ENTWINE
if (strt)
{ strt = 0;
iflare = i;
}
oflare = i;
#endif
}
if (jpath->aepos == kpath->aepos)
{ i = abs(jpath->bepos-kpath->bepos);
if (i <= min)
{ min = i;
if (i == 0)
*where = kpath->aepos;
}
}
#ifdef SEE_ENTWINE
if (den == 0)
printf("Nothing\n");
else
printf("MINIM = %d AVERAGE = %d IFLARE = %d OFLARE = %d\n",min,num/den,iflare,oflare);
#endif
if (den == 0)
return (-1);
else
return (min);
}
// Produce the concatentation of path1 and path2 where they are known to meet at
// the trace point with coordinate ap. Place this result in a big growing buffer,
// that gets reset when fusion is called with path1 = NULL
static void Fusion(Path *path1, int ap, Path *path2, Trace_Buffer *tbuf)
{ int k, k1, k2;
int len, diff;
uint16 *trace;
k1 = 2 * ((ap/MR_tspace) - (path1->abpos/MR_tspace));
k2 = 2 * ((ap/MR_tspace) - (path2->abpos/MR_tspace));
len = k1+(path2->tlen-k2);
if (tbuf->top + len >= tbuf->max)
{ tbuf->max = 1.2*(tbuf->top+len) + 1000;
tbuf->trace = (uint16 *) Realloc(tbuf->trace,sizeof(uint16)*tbuf->max,"Allocating paths");
if (tbuf->trace == NULL)
exit (1);
}
trace = tbuf->trace + tbuf->top;
tbuf->top += len;
diff = 0;
len = 0;
if (k1 > 0)
{ uint16 *t = tbuf->trace + (uint64) (path1->trace);
for (k = 0; k < k1; k += 2)
{ trace[len++] = t[k];
trace[len++] = t[k+1];
diff += t[k];
}
}
if (k2 < path2->tlen)
{ uint16 *t = tbuf->trace + (uint64) (path2->trace);
for (k = k2; k < path2->tlen; k += 2)
{ trace[len++] = t[k];
trace[len++] = t[k+1];
diff += t[k];
}
}
path1->aepos = path2->aepos;
path1->bepos = path2->bepos;
path1->diffs = diff;
path1->trace = (void *) (trace - tbuf->trace);
path1->tlen = len;
}
// Given all the LA's for a given read in amatch[0..novls-1], merge any overlapping LA's and
// remove any redundant ones.
static int Handle_Redundancies(Path *amatch, int novls, Trace_Buffer *tbuf)
{ Path *jpath, *kpath;
int j, k, no;
int dist, awhen = 0;
#ifdef TEST_CONTAIN
for (j = 0; j < novls; j++)
printf(" %3d: [%5d,%5d] x [%5d,%5d]\n",j,amatch[j].abpos,amatch[j].aepos,
amatch[j].bbpos,amatch[j].bepos);
#endif
for (j = 1; j < novls; j++)
{ jpath = amatch+j;
for (k = j-1; k >= 0; k--)
{ kpath = amatch+k;
if (kpath->abpos < 0)
continue;
if (jpath->abpos < kpath->abpos)
{ if (kpath->abpos <= jpath->aepos && kpath->bbpos <= jpath->bepos)
{ dist = Entwine(jpath,kpath,tbuf,&awhen);
if (dist == 0)
{ if (kpath->aepos > jpath->aepos)
{ Fusion(jpath,awhen,kpath,tbuf);
#ifdef TEST_CONTAIN
printf(" Really 3");
#endif
k = j;
}
kpath->abpos = -1;
#ifdef TEST_CONTAIN
printf(" Fuse! A %d %d\n",j,k);
#endif
}
}
}
else // kpath->abpos <= jpath->abpos
{ if (jpath->abpos <= kpath->aepos && jpath->bbpos <= kpath->bepos)
{ dist = Entwine(kpath,jpath,tbuf,&awhen);
if (dist == 0)
{ if (kpath->abpos == jpath->abpos)
{ if (kpath->aepos > jpath->aepos)
*jpath = *kpath;
}
else if (jpath->aepos > kpath->aepos)
{ Fusion(kpath,awhen,jpath,tbuf);
*jpath = *kpath;
#ifdef TEST_CONTAIN
printf(" Really 6");
#endif
k = j;
}
else
*jpath = *kpath;
kpath->abpos = -1;
#ifdef TEST_CONTAIN
printf(" Fuse! B %d %d\n",j,k);
#endif
}
}
}
}
}
no = 0;
for (j = 0; j < novls; j++)
if (amatch[j].abpos >= 0)
amatch[no++] = amatch[j];
novls = no;
#ifdef TEST_CONTAIN
for (j = 0; j < novls; j++)
printf(" %3d: [%5d,%5d] x [%5d,%5d]\n",j,amatch[j].abpos,amatch[j].aepos,
amatch[j].bbpos,amatch[j].bepos);
#endif
return (novls);
}
// Determine the range of diagonal bins containing trace points of path
void Diagonal_Span(Path *path, int *mind, int *maxd)
{ uint16 *points;
int i, tlen;
int dd, low, hgh;
points = path->trace;
tlen = path->tlen;
dd = path->abpos - path->bbpos;
low = hgh = dd;
dd = path->aepos - path->bepos;
if (dd < low)
low = dd;
else if (dd > hgh)
hgh = dd;
dd = (path->abpos/MR_tspace)*MR_tspace - path->bbpos;
tlen -= 2;
for (i = 1; i < tlen; i += 2)
{ dd += MR_tspace - points[i];
if (dd < low)
low = dd;
else if (dd > hgh)
hgh = dd;
}
*mind = (low >> Binshift)-1;
*maxd = (hgh >> Binshift)+1;
}
typedef struct
{ int64 beg, end;
int *score;
int *lastp;
int *lasta;
Work_Data *work;
FILE *ofile;
int64 nfilt;
int64 ncheck;
Overlap_IO_Buffer *iobuf;
} Report_Arg;
static void *report_thread(void *arg)
{ Report_Arg *data = (Report_Arg *) arg;
HITS_READ *aread = MR_ablock->reads;
KmerPos *asort = MG_alist;
int *score = data->score;
int *scorp = data->score + 1;
int *scorm = data->score - 1;
int *lastp = data->lastp;
int *lasta = data->lasta;
int maxdiag = ( MR_ablock->maxlen >> Binshift);
int mindiag = (-MR_ablock->maxlen >> Binshift);
Overlap_IO_Buffer *obuf = data->iobuf;
// FILE *ofile = data->ofile;
char *aseq = (char *) (MR_ablock->bases);
Work_Data *work = data->work;
int afirst = MR_ablock->ufirst;
Overlap _ovla, *ovla = &_ovla;
Alignment _align, *align = &_align;
Path *apath = &(ovla->path);
int64 nfilt = 0;
int64 ahits = 0;
int small, tbytes;
int novla;
int AOmax;
Path *amatch;
Trace_Buffer _tbuf, *tbuf = &_tbuf;
int ar, aend;
KmerPos *aoff;
align->flags = ovla->flags = 0;
align->path = apath;
if (MR_tspace <= TRACE_XOVR)
{ small = 1;
tbytes = sizeof(uint8);
}
else
{ small = 0;
tbytes = sizeof(uint16);
}
AOmax = MATCH_CHUNK;
amatch = Malloc(sizeof(Path)*AOmax,"Allocating match vector");
tbuf->max = 2*TRACE_CHUNK;
tbuf->trace = Malloc(sizeof(short)*tbuf->max,"Allocating trace vector");
if (amatch == NULL || tbuf->trace == NULL)
exit (1);
// fwrite(&ahits,sizeof(int64),1,ofile);
// fwrite(&MR_tspace,sizeof(int),1,ofile);
#ifdef TEST_GATHER
printf("\nNEW THREAD %5d(%5lld)-%5d(%5lld)\n",asort[data->beg].read,data->beg,
asort[data->end-1].read,data->end);
fflush(stdout);
#endif
aoff = asort + (data->beg - Kmer);
aend = asort[data->end-1].read;
for (ar = asort[data->beg].read; ar <= aend; ar++)
{ int alen, amarkb, amarke;
int apos, diag;
int setaln;
#ifdef TEST_GATHER
printf("Read %5d\n",ar);
fflush(stdout);
#endif
setaln = 1;
novla = 0;
tbuf->top = 0;
alen = aread[ar].rlen;
amarkb = Kmer;
amarke = PANEL_SIZE;
if (amarke >= alen)
amarke = alen+1;
while (1)
{
// Accumulate diagonal scores
for (apos = amarkb; apos < amarke; apos++)
{ diag = aoff[apos].code;
if (diag == 0) continue;
diag >>= Binshift;
if (apos - lastp[diag] >= Kmer)
score[diag] += Kmer;
else
score[diag] += apos - lastp[diag];
lastp[diag] = apos;
}
// Examine diagonal scores for hits to check out
for (apos = amarkb; apos < amarke; apos++)
{ diag = aoff[apos].code;
if (diag == 0) continue;
diag >>= Binshift;
if (apos > lasta[diag] &&
(score[diag] + scorp[diag] >= Hitmin || score[diag] + scorm[diag] >= Hitmin))
{ int bpos;
bpos = apos - aoff[apos].code;
if (setaln)
{ setaln = 0;
align->aseq = align->bseq = aseq + aread[ar].boff;
align->alen = align->blen = alen;
ovla->aread = ovla->bread = ar + afirst;
}
#ifdef TEST_GATHER
if (scorm[diag] > scorp[diag])
printf(" %5d.. x %5d.. %5d (%3d)",
bpos,apos,apos-bpos,score[diag]+scorm[diag]);
else
printf(" %5d.. x %5d.. %5d (%3d)",
bpos,apos,apos-bpos,score[diag]+scorp[diag]);
fflush(stdout);
#endif
nfilt += 1;
Local_Alignment(align,work,MR_spec,apos-bpos,apos-bpos,apos+bpos,-1,-1);
{ int low, hgh, ae;
Diagonal_Span(apath,&low,&hgh);
if (diag < low)
low = diag;
else if (diag > hgh)
hgh = diag;
ae = apath->aepos;
for (diag = low; diag <= hgh; diag++)
if (ae > lasta[diag])
lasta[diag] = ae;
#ifdef TEST_GATHER
printf(" %d - %d @ %d",low,hgh,apath->aepos);
#endif
}
if ((apath->aepos-apath->abpos) + (apath->bepos-apath->bbpos) >= MINOVER)
{ if (novla >= AOmax)
{ AOmax = 1.2*novla + MATCH_CHUNK;
amatch = Realloc(amatch,sizeof(Path)*AOmax,
"Reallocating match vector");
if (amatch == NULL)
exit (1);
}
if (tbuf->top + apath->tlen > tbuf->max)
{ tbuf->max = 1.2*(tbuf->top+apath->tlen) + TRACE_CHUNK;
tbuf->trace = Realloc(tbuf->trace,sizeof(short)*tbuf->max,
"Reallocating trace vector");
if (tbuf->trace == NULL)
exit (1);
}
amatch[novla] = *apath;
amatch[novla].trace = (void *) (tbuf->top);
memmove(tbuf->trace+tbuf->top,apath->trace,sizeof(short)*apath->tlen);
novla += 1;
tbuf->top += apath->tlen;
#ifdef TEST_GATHER
printf(" [%5d,%5d] x [%5d,%5d] = %4d",
apath->abpos,apath->aepos,apath->bbpos,apath->bepos,apath->diffs);
#endif
#ifdef SHOW_OVERLAP
printf("\n\n %d(%d) vs %d(%d)\n\n",
ovla->aread,ovla->alen,ovla->bread,ovla->blen);
Print_ACartoon(stdout,align,ALIGN_INDENT);
#ifdef SHOW_ALIGNMENT
Compute_Trace_ALL(align,work);
printf("\n Diff = %d\n",align->path->diffs);
Print_Alignment(stdout,align,work,
ALIGN_INDENT,ALIGN_WIDTH,ALIGN_BORDER,0,5);
#endif
#endif // SHOW_OVERLAP
}
#ifdef TEST_GATHER
else
printf(" No alignment %d",
((apath->aepos-apath->abpos) + (apath->bepos-apath->bbpos))/2);
printf("\n");
#endif
}
}
// Clear diagonal scores
for (apos = amarkb; apos < amarke; apos++)
{ diag = aoff[apos].code;
if (diag == 0) continue;
diag >>= Binshift;
score[diag] = lastp[diag] = 0;
}
if (amarke > alen) break;
amarkb = amarke - PANEL_OVERLAP;
amarke = amarkb + PANEL_SIZE;
if (amarke > alen)
amarke = alen+1;
}
// Clear diagonal last positions
for (apos = Kmer; apos <= alen; apos++)
{ int d;
diag = aoff[apos].code;
if (diag == 0) continue;
diag >>= Binshift;
for (d = diag; d <= maxdiag; d++)
if (lasta[d] == 0)
break;
else
lasta[d] = 0;
for (d = diag-1; d >= mindiag; d--)
if (lasta[d] == 0)
break;
else
lasta[d] = 0;
}
// Merge overlapping alignments and remove redundant ones
{ int i;
#ifdef TEST_CONTAIN
if (novla > 1)
printf("\n%5d vs %5d:\n",ar,ar);
#endif
if (novla > 1)
novla = Handle_Redundancies(amatch,novla,tbuf);
for (i = 0; i < novla; i++)
{ ovla->path = amatch[i];
ovla->path.trace = tbuf->trace + (uint64) (ovla->path.trace);
if (small)
Compress_TraceTo8(ovla,1);
#ifdef THREAD_OUTPUT
if (Write_Overlap(ofile, ovla, tbytes))
{
fprintf(stderr, "%s: Cannot write to %s too small?\n",
SORT_PATH, Prog_Name);
exit(1);
}
#endif
AddOverlapToBuffer(obuf, ovla, tbytes);
}
ahits += novla;
}
aoff += alen - (Kmer-1);
}
free(tbuf->trace);
free(amatch);
data->nfilt = nfilt;
data->ncheck = ahits;
#ifdef THREAD_OUTPUT
rewind(ofile);
fwrite(&ahits,sizeof(int64),1,ofile);
fclose(ofile);
#endif
return (NULL);
}
/*******************************************************************************************
*
* THE ALGORITHM
*
********************************************************************************************/
void Match_Self(char *aname, HITS_DB *ablock, Align_Spec *aspec)
{ THREAD threads[NTHREADS];
Merge_Arg parmm[NTHREADS];
Lex_Arg parmx[NTHREADS];
Report_Arg parmr[NTHREADS];
int pairsort[16];
int64 nfilt, ncheck;
KmerPos *asort, *osort;
int alen;
int64 atot;
// Setup
atot = ablock->totlen;
nfilt = ncheck = 0;
{ int64 powr;
int i, nbyte;
for (i = 0; i < NTHREADS; i++)
parmx[i].sptr = (int64 *) alloca(NTHREADS*BPOWR*sizeof(int64));
for (i = 0; i < 16; i++)
pairsort[i] = 0;
powr = 1;
for (nbyte = 0; powr < ablock->maxlen; nbyte += 1)
powr <<= 8;
for (i = 8; i < 8+nbyte; i++)
pairsort[i] = 1;
powr = 1;
for (nbyte = 0; powr < ablock->nreads; nbyte += 1)
powr <<= 8;
for (i = 12; i < 12+nbyte; i++)
pairsort[i] = 1;
{
Overlap_IO_Buffer *buffer = OVL_IO_Buffer(aspec);
for (i = 0; i < NTHREADS; i++)
{
parmr[i].iobuf = &(buffer[i]);
if (parmr[i].iobuf == NULL)
exit(1);
}
}
}
// Build K-mer sorted index of ablock
if (VERBOSE)
printf("\nIndexing %s\n",aname);
osort = NULL; // Just to shut up dumb compilers
asort = Sort_Kmers(ablock,&alen,&osort);
if (VERBOSE)
printf("\nComparing %s to itself\n",aname);
if (alen == 0)
goto zerowork;
// Determine equal K-mer links
{ int i, p;
uint64 c;
parmm[0].abeg = 0;
for (i = 1; i < NTHREADS; i++)
{ p = (int) ((((int64) alen) * i) >> NSHIFT);
if (p > 0)
{ c = asort[p-1].code;
while (asort[p].code == c)
p += 1;
}
parmm[i].abeg = parmm[i-1].aend = p;
}
parmm[NTHREADS-1].aend = alen;
for (i = 0; i < NTHREADS; i++)
{ parmm[i].kptr = parmx[i].tptr;
for (p = 0; p < BPOWR; p++)
parmm[i].kptr[p] = 0;
}
MG_alist = asort;
for (i = 0; i < NTHREADS; i++)
pthread_create(threads+i,NULL,count_thread,parmm+i);
for (i = 0; i < NTHREADS; i++)
pthread_join(threads[i],NULL);
#ifdef TEST_PAIRS
printf("\nCROSS SORT %d:\n",alen);
for (i = 0; i < HOW_MANY && i <= alen; i++)
{ KmerPos *c = asort+i;
printf(" %5d / %5d / %10lld\n",c->read,c->rpos,c->code);
fflush(stdout);
}
#endif
}
// Resort the list on read,rpos
{ int i;
KmerPos *rez;
for (i = 0; i < NTHREADS; i++)
{ parmx[i].beg = parmm[i].abeg;
parmx[i].end = parmm[i].aend;
}
rez = (KmerPos *) lex_sort(pairsort,(Double *) asort,(Double *) osort,parmx);
if (rez != asort)
{ osort = asort;
asort = rez;
}
#ifdef TEST_CSORT
printf("\nCROSS SORT %d:\n",alen);
for (i = 0; i < HOW_MANY && i <= alen; i++)
{ KmerPos *c = asort+i;
printf(" %5d / %5d / %10lld\n",c->read,c->rpos,c->code);
fflush(stdout);
}
#endif
}
// Apply the diagonal filter and find local alignments about seed hits
{ int i, w;
int64 p;
int ar;
int *counters;
MG_alist = asort;
MR_ablock = ablock;
MR_spec = aspec;
MR_tspace = Trace_Spacing(aspec);
asort[alen].read = ablock->nreads;
parmr[0].beg = 0;
for (i = 1; i < NTHREADS; i++)
{ p = (int) ((((int64) alen) * i) >> NSHIFT);
if (p > 0)
{ ar = asort[p-1].read;
while ((asort[p].read) == ar)
p += 1;
}
parmr[i].beg = parmr[i-1].end = p;
}
parmr[NTHREADS-1].end = alen;
w = ((ablock->maxlen >> Binshift) - ((-ablock->maxlen) >> Binshift)) + 1;
counters = (int *) Malloc(NTHREADS*3*w*sizeof(int),"Allocating diagonal buckets");
if (counters == NULL)
exit (1);
for (i = 0; i < 3*w*NTHREADS; i++)
counters[i] = 0;
for (i = 0; i < NTHREADS; i++)
{ if (i == 0)
parmr[i].score = counters - ((-ablock->maxlen) >> Binshift);
else
parmr[i].score = parmr[i-1].lasta + w;
parmr[i].lastp = parmr[i].score + w;
parmr[i].lasta = parmr[i].lastp + w;
parmr[i].work = New_Work_Data();
#ifdef THREAD_OUTPUT
parmr[i].ofile =
Fopen(Catenate(SORT_PATH,"/",aname,Numbered_Suffix(".T",i+1,".las")),"w");
if (parmr[i].ofile == NULL)
exit (1);
#endif
}
#ifdef NOTHREAD
for (i = 0; i < NTHREADS; i++)
report_thread(parmr+i);
#else
for (i = 0; i < NTHREADS; i++)
pthread_create(threads+i,NULL,report_thread,parmr+i);
for (i = 0; i < NTHREADS; i++)
pthread_join(threads[i],NULL);
#endif
if (VERBOSE)
for (i = 0; i < NTHREADS; i++)
{ nfilt += parmr[i].nfilt;
ncheck += parmr[i].ncheck;
}
for (i = 0; i < NTHREADS; i++)
Free_Work_Data(parmr[i].work);
free(counters);
}
// Finish up
goto epilogue;
zerowork:
{
// FILE *ofile;
// int i;
//
// nfilt = 0;
// for (i = 0; i < NTHREADS; i++)
// { ofile = Fopen(Catenate(SORT_PATH,"/",aname,Numbered_Suffix(".T",i+1,".las")),"w");
// fwrite(&nfilt,sizeof(int64),1,ofile);
// fwrite(&MR_tspace,sizeof(int),1,ofile);
// fclose(ofile);
// }
}
epilogue:
free(asort);
free(osort);
if (VERBOSE)
{ int width;
if (nfilt <= 0)
width = 1;
else
width = ((int) log10((double) nfilt)) + 1;
width += (width-1)/3;
printf("\n ");
Print_Number(nfilt,width,stdout);
printf(" seed hits (%e of matrix)\n ",(1.*nfilt/atot)/atot);
Print_Number(ncheck,width,stdout);
printf(" confirmed hits (%e of matrix)\n",(1.*ncheck/atot)/atot);
fflush(stdout);
}
}
|
MartinPippel/DAmar
|
scrub/TKhomogenize.c
|
<gh_stars>10-100
/*******************************************************************************************
*
* Reassign repeat intervals based on overlaps and an existing repeat annotation
*
* Date : January 2016
*
* Author : <NAME>
*
*******************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <sys/param.h>
#include <assert.h>
#include <unistd.h>
#include "lib/tracks.h"
#include "lib/colors.h"
#include "lib/oflags.h"
#include "lib/borders.h"
#include "lib/pass.h"
#include "lib/utils.h"
#include "lib.ext/types.h"
#include "lib.ext/bitarr.h"
#include "db/DB.h"
#include "dalign/align.h"
// defaults
#define DEF_ARG_B 0
#define DEF_ARG_M 0
#define DEF_ARG_I TRACK_REPEATS
#define DEF_ARG_II TRACK_HREPEATS
#define DEF_ARG_T TRACK_TRIM
#define DEF_ARG_E -1
#define DEF_ARG_R 1
// constants
#define MAX_BUF_SIZE ( 10L * 1024 * 1024 * 1024 )
#define MAX_BUFS ( 16 )
#define MIN_INT_LEN ( 500 ) // min intervals length
// toggles
#define VERBOSE
#define DEBUG_HOMOGENIZE
typedef struct
{
HITS_DB* db;
ovl_header_twidth twidth;
HITS_TRACK* track_repeats;
HITS_TRACK* track_trim;
char* track_in;
char* track_out;
char* track_trim_name;
uint64_t stats_bases_tagged;
int block;
int copy_existing;
int ends;
int res;
bit** read_masks; // repeat annotation bit masks for each read
bit** bufs; // buffers for repeat annotation
} HomogenizeContext;
// getopt()
extern char* optarg;
extern int optind, opterr, optopt;
static void pre_homogenize(PassContext* pctx, HomogenizeContext* ctx)
{
#ifdef VERBOSE
printf(ANSI_COLOR_GREEN "PASS homogenising\n" ANSI_COLOR_RESET);
#endif
int nreads = DB_NREADS(ctx->db);
ctx->track_repeats = track_load(ctx->db, ctx->track_in);
if (!ctx->track_repeats)
{
fprintf(stderr, "could not load track %s\n", ctx->track_in);
exit(1);
}
ctx->twidth = pctx->twidth;
// allocate bit mask buffer pointers
ctx->read_masks = malloc(sizeof(bit*) * nreads);
assert(ctx->read_masks != NULL);
// allocate buffers
int i;
uint64_t nbuf = 0;
uint64_t total = 0;
bit** bufs = ctx->bufs = calloc(MAX_BUFS, sizeof(bit*));
int curbuf = 0;
for (i = 0; i < nreads; i++)
{
int len = DB_READ_LEN(ctx->db, i);
if (ctx->res > 1)
{
len = ( len + ctx->res - 1) / ctx->res;
}
nbuf += ba_bufsize(len + 1);
if (nbuf > MAX_BUF_SIZE)
{
bufs[curbuf] = calloc(nbuf, sizeof(bit));
assert( bufs[curbuf] != NULL );
total += nbuf;
curbuf++;
nbuf = 0;
assert(curbuf < MAX_BUFS);
}
// ctx->read_masks[i] = ba_new( len + 1 );
}
if (nbuf > 0)
{
total += nbuf;
bufs[curbuf] = calloc(nbuf, sizeof(bit));
assert( bufs[curbuf] != NULL );
curbuf++;
}
// set bit mask pointers to buffers
nbuf = 0;
curbuf = 0;
for (i = 0; i < nreads; i++)
{
int len = DB_READ_LEN(ctx->db, i);
if (ctx->res > 1)
{
len = ( len + ctx->res - 1) / ctx->res;
}
ctx->read_masks[i] = bufs[curbuf] + nbuf;
nbuf += ba_bufsize(len + 1);
if (nbuf > MAX_BUF_SIZE)
{
nbuf = 0;
curbuf++;
}
}
#ifdef VERBOSE
char* buf = format_bytes(total);
printf("allocated %s in %d buffers\n", buf, curbuf + 1);
free(buf);
#endif
// initialize with existing annotation
if (ctx->copy_existing)
{
#ifdef VERBOSE
printf("copying existing annotation\n");
#endif
track_anno* tanno = ctx->track_repeats->anno;
track_data* tdata = ctx->track_repeats->data;
int a;
for (a = 0; a < nreads; a++)
{
track_anno ob = tanno[a] / sizeof(track_data);
track_anno oe = tanno[a + 1] / sizeof(track_data);
bit* amask = ctx->read_masks[a];
while (ob < oe)
{
int beg = tdata[ob];
int end = tdata[ob + 1];
ob += 2;
if (end - beg < MIN_INT_LEN)
{
continue;
}
beg = ( beg + ctx->res - 1) / ctx->res;
end = end / ctx->res;
ba_assign_range(amask, beg, end, 1);
}
}
}
}
static void post_homogenize(HomogenizeContext* ctx)
{
track_anno* anno = malloc(sizeof(track_anno) * (ctx->db->ureads + 1));
uint64_t dmax = 1000;
uint64_t dcur = 0;
track_data* data = malloc(sizeof(track_data) * dmax);
assert( anno != NULL && data != NULL );
bzero(anno, sizeof(track_anno) * (ctx->db->ureads + 1));
int i;
for (i = 0; i < ctx->db->nreads; i++)
{
bit* bitarr = ctx->read_masks[i];
int alen = DB_READ_LEN(ctx->db, i);
if (ctx->res > 1)
{
alen = ( alen + ctx->res - 1) / ctx->res;
}
if (ba_count(bitarr, alen) < 1)
{
continue;
}
int j = 0;
int beg = -1;
int end = -1;
for (j = 0; j < alen; j++)
{
int val = ba_value(bitarr, j);
if (val && beg == -1)
{
beg = j;
}
else if (!val && beg != -1)
{
end = j - 1;
if (dcur + 2 >= dmax)
{
dmax = 1.2 * dmax + 1000;
data = realloc(data, sizeof(track_data) * dmax);
}
beg = beg * ctx->res;
end = MIN(end * ctx->res, DB_READ_LEN(ctx->db, i));
data[dcur++] = beg;
data[dcur++] = end;
anno[i] += sizeof(track_data) * 2;
beg = -1;
}
}
// interval extends to the end of the read
if (beg != -1)
{
if (dcur + 2 >= dmax)
{
dmax = 1.2 * dmax + 1000;
data = realloc(data, sizeof(track_data) * dmax);
}
beg = beg * ctx->res;
data[dcur++] = beg;
data[dcur++] = DB_READ_LEN(ctx->db, i) - 1;
anno[i] += sizeof(track_data) * 2;
}
}
track_anno coff, off;
off = 0;
int j;
for (j = 0; j <= DB_NREADS(ctx->db); j++)
{
coff = anno[j];
anno[j] = off;
off += coff;
}
uint64_t k;
uint64_t tagged = 0;
for (k = 0; k < dcur; k += 2)
{
tagged += data[k+1] - data[k];
}
printf("tagged %" PRIu64 " as repeat\n", tagged);
track_write(ctx->db, ctx->track_out, ctx->block, anno, data, dcur);
for (j = 0; j < MAX_BUFS && ctx->bufs[j] != NULL; j++)
{
free(ctx->bufs[j]);
}
free(ctx->bufs);
free(ctx->read_masks);
free(anno);
free(data);
}
static int handler_homogenize(void* _ctx, Overlap* ovl, int novl)
{
HomogenizeContext* ctx = (HomogenizeContext*)_ctx;
ovl_header_twidth twidth = ctx->twidth;
int ends = ctx->ends;
track_anno* tanno = ctx->track_repeats->anno;
track_data* tdata = ctx->track_repeats->data;
int a = ovl->aread;
int i;
for (i = 0; i < novl; i++)
{
if ( ovl[i].aread == ovl[i].bread )
{
continue;
}
// get repeat annotation for a read
track_anno ob = tanno[a] / sizeof(track_data);
track_anno oe = tanno[a + 1] / sizeof(track_data);
int b = ovl[i].bread;
int trim_bb, trim_be;
int blen = DB_READ_LEN(ctx->db, b);
if (ctx->track_trim)
{
get_trim(ctx->db, ctx->track_trim, b, &trim_bb, &trim_be);
}
else
{
trim_bb = 0;
trim_be = blen;
}
#ifdef DEBUG_HOMOGENIZE
if (a == 592526)
{
printf("%d (%d) -> %d (%d) %5d..%5d -> %5d..%5d\n", a, DB_READ_LEN(ctx->db, a), b, DB_READ_LEN(ctx->db, b),
ovl[i].path.abpos, ovl[i].path.aepos, ovl[i].path.bbpos, ovl[i].path.bepos);
fflush(stdout);
}
#endif
int ab = ovl[i].path.abpos;
int ae = ovl[i].path.aepos;
while (ob < oe)
{
int beg = tdata[ob];
int end = tdata[ob + 1];
ob += 2;
if (end - beg < MIN_INT_LEN)
{
continue;
}
if (beg > ae)
{
break ;
}
// does the repeat interval intersect with overlap
int iab = MAX(beg, ab);
int iae = MIN(end, ae);
if (iab >= iae)
{
continue ;
}
// establish conservative estimate of the repeat extent
// relative to the b read given the trace points
ovl_trace* trace = ovl[i].path.trace;
int tlen = ovl[i].path.tlen;
int ibb = -1;
int ibe = -1;
int aoff = ovl[i].path.abpos;
int boff = ovl[i].path.bbpos;
int j;
for (j = 0; j < tlen; j += 2)
{
#ifdef DEBUG_HOMOGENIZE
if (a == 592526 && b == 5971679)
{
printf("%2d %2d %5d %5d %5d %5d\n", j, tlen, aoff, boff, ibb, ibe);
}
#endif
if(ibb == -1)
{
if (aoff + twidth >= iab )
{
int adiff = iab - aoff;
float curSegLenRatio = 1.0*twidth/trace[j + 1];
ibb = MIN(boff + (int)(adiff/curSegLenRatio), ovl[i].path.bepos);
}
else if(j == tlen - 2)
{
ibb = MIN(boff, ovl[i].path.bepos);
}
}
if ( aoff + twidth >= iae && ibe == -1 )
{
if (ibb == -1)
{
ibb = MIN(boff, ovl[i].path.bepos);
}
int adiff = iae - aoff;
float curSegLenRatio = 1.0*twidth/trace[j + 1];
ibe = MIN(boff + (int)(adiff/curSegLenRatio), ovl[i].path.bepos);
//ibe = MIN(boff + trace[j + 1], ovl[i].path.bepos);
break;
}
aoff = ( (aoff + twidth) / twidth) * twidth;
boff += trace[j + 1];
}
if (ibb == -1 || ibe == -1)
{
continue;
}
if (ovl[i].flags & OVL_COMP)
{
int t = ibb;
ibb = blen - ibe;
ibe = blen - t;
}
assert(ibb <= ibe);
#ifdef DEBUG_HOMOGENIZE
if (a == 592526)
{
printf("%6d %c %6d :: A %5d..%5d A_R %5d..%5d B %5d..%5d -> IA %5d..%5d IB %5d..%5d\n",
ovl[i].aread, ovl[i].flags & OVL_COMP ? 'c' : 'n', ovl[i].bread,
ab, ae,
beg, end,
ovl[i].path.bbpos, ovl[i].path.bepos,
iab, iae,
ibb, ibe);
return 0;
}
#endif
// repeat tag the b read
bit* bmask = ctx->read_masks[b];
if (ends != -1)
{
// printf("%5d..%5d %5d..%5d ->", trim_bb, trim_be, ibb, ibe);
if (ibb < ends + trim_bb)
{
// printf(" %5d..%5d", ibb, MIN( ends + trim_bb, ibe ));
int bab = ( ibb + ctx->res - 1) / ctx->res;
int bae = MIN( ends + trim_bb, ibe ) / ctx->res;
ba_assign_range(bmask, bab, bae, 1);
}
if (ibe > trim_be - ends)
{
// printf(" %5d..%5d", MAX( trim_be - ends, ibb ), ibe);
int bab = ( MAX( trim_be - ends, ibb ) + ctx->res - 1) / ctx->res;
int bae = ibe / ctx->res;
ba_assign_range(bmask, bab, bae, 1);
}
// printf("\n");
}
else
{
ibb = ( ibb + ctx->res - 1) / ctx->res;
ibe = ibe / ctx->res;
ba_assign_range(bmask, ibb, ibe, 1);
}
}
}
return 1;
}
static void usage()
{
printf("usage: [-m] [-ber <int>] [-iIt <track>] <db> <overlaps>\n");
printf("options: -b ... track block\n");
printf(" -m ... merge input intervals into the output track (%d)\n", DEF_ARG_M);
printf(" -i ... input interval track (%s)\n", DEF_ARG_I);
printf(" -I ... output interval track (%s)\n", DEF_ARG_II);
printf(" -e ... only annotate n bases at the ends of the reads (%d), requires -t \n", DEF_ARG_E);
printf(" -t ... trim track (%s)\n", DEF_ARG_T);
printf(" -r ... base pair resolution (%d)\n", DEF_ARG_R);
printf(" scales memory usage by the same factor and improves runtime\n");
}
int main(int argc, char* argv[])
{
HITS_DB db;
PassContext* pctx;
HomogenizeContext hctx;
FILE* fileOvlIn;
bzero(&hctx, sizeof(HomogenizeContext));
hctx.db = &db;
hctx.block = DEF_ARG_B;
hctx.track_in = DEF_ARG_I;
hctx.track_out = DEF_ARG_II;
hctx.ends = DEF_ARG_E;
hctx.track_trim_name = DEF_ARG_T;
hctx.res = DEF_ARG_R;
// process arguments
int c;
opterr = 0;
while ((c = getopt(argc, argv, "mr:e:b:i:I:t:")) != -1)
{
switch (c)
{
case 'm':
hctx.copy_existing = 1;
break;
case 'r':
hctx.res = atoi(optarg);
break;
case 'b':
hctx.block = atoi(optarg);
break;
case 'i':
hctx.track_in = optarg;
break;
case 'I':
hctx.track_out = optarg;
break;
case 't':
hctx.track_trim_name = optarg;
break;
case 'e':
hctx.ends = atoi(optarg);
break;
default:
usage();
exit(1);
}
}
if (argc - optind != 2)
{
usage();
exit(1);
}
if (hctx.ends < -1 || hctx.ends == 0)
{
fprintf(stderr, "invalid -e argument %d\n", hctx.ends);
exit(1);
}
char* pcPathReadsIn = argv[optind++];
char* pcPathOverlaps = argv[optind++];
if ( (fileOvlIn = fopen(pcPathOverlaps, "r")) == NULL )
{
fprintf(stderr, "could not open '%s'\n", pcPathOverlaps);
exit(1);
}
if ( Open_DB(pcPathReadsIn, &db) )
{
fprintf(stderr, "failed top open database %s\n", pcPathReadsIn);
exit(1);
}
if ( hctx.track_out == NULL )
{
fprintf(stderr, "output track not set\n");
exit(1);
}
if (hctx.ends != -1)
{
hctx.track_trim = track_load(&db, hctx.track_trim_name);
if (hctx.track_trim == NULL)
{
fprintf(stderr, "-e requires a trim track\n");
exit(1);
}
}
// init
ba_init();
pctx = pass_init(fileOvlIn, NULL);
pctx->split_b = 0;
pctx->load_trace = 1;
pctx->unpack_trace = 1;
pctx->data = &hctx;
// passes
pre_homogenize(pctx, &hctx);
pass(pctx, handler_homogenize);
post_homogenize(&hctx);
// cleanup
pass_free(pctx);
fclose(fileOvlIn);
Close_DB(&db);
return 0;
}
|
MartinPippel/DAmar
|
scrub/tandem.h
|
/************************************************************************************\
* *
* Copyright (c) 2014, Dr. <NAME> (EWM). All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without modification, *
* are permitted provided that the following conditions are met: *
* *
* · Redistributions of source code must retain the above copyright notice, this *
* list of conditions and the following disclaimer. *
* *
* · Redistributions in binary form must reproduce the above copyright notice, this *
* list of conditions and the following disclaimer in the documentation and/or *
* other materials provided with the distribution. *
* *
* · The name of EWM may not be used to endorse or promote products derived from *
* this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY EWM ”AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, *
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND *
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL EWM BE LIABLE *
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS *
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY *
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING *
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN *
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
* *
* For any issues regarding this software and its use, contact EWM at: *
* *
* <NAME>r. *
* Bautzner Str. 122e *
* 01099 Dresden *
* GERMANY *
* Email: <EMAIL> *
* *
\************************************************************************************/
/*******************************************************************************************
*
* Filter interface for the datandem.
*
* Author: <NAME>
* Date : March 2016
*
********************************************************************************************/
#ifndef _TANDEM
#define _TANDEM
#include "db/DB.h"
#include "dalign/align.h"
extern int VERBOSE;
extern int MINOVER;
extern char *SORT_PATH;
int Set_Filter_Params(int kmer, int binshift, int hitmin, int nthreads);
void Match_Self(char *aname, HITS_DB *ablock, Align_Spec *settings);
#endif
|
MartinPippel/DAmar
|
lib/read_loader.c
|
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "read_loader.h"
#define BLOCK_BUFFER (10*1024*1024)
Read_Loader* rl_init(HITS_DB* db, size_t max_mem)
{
Read_Loader* rl = malloc(sizeof(Read_Loader));
rl->db = db;
rl->max_mem = max_mem;
rl->index = (char**)malloc(sizeof(char*) * db->nreads);
bzero(rl->index, sizeof(char*) * db->nreads);
rl->reads = NULL;
rl->maxreads = 0;
rl->rid = NULL;
rl->currid = 0;
rl->nrid = 0;
return rl;
}
void rl_add(Read_Loader* rl, int rid)
{
if (rl->currid >= rl->nrid)
{
rl->nrid = rl->nrid * 1.2 + 1000;
rl->rid = (int*)realloc(rl->rid, sizeof(int) * rl->nrid);
}
rl->rid[ rl->currid ] = rid;
rl->currid++;
}
void rl_load_added(Read_Loader* rl)
{
rl_load(rl, rl->rid, rl->currid);
free(rl->rid);
rl->currid = 0;
rl->nrid = 0;
}
static int cmp_rids(const void* a, const void* b)
{
return *((int*)a) - *((int*)b);
}
static int unique(int* a, int len)
{
int i, j;
j = 0;
for (i = 1; i < len; i++)
{
if (a[i] != a[j])
{
j++;
a[j] = a[i];
}
}
return j+1;
}
void rl_load(Read_Loader* rl, int* rids, int nrids)
{
HITS_DB* db = rl->db;
FILE* bases = db->bases;
uint64 nreads = db->nreads;
HITS_READ* reads = db->reads;
if (bases)
{
rewind(bases);
}
else
{
db->bases = bases = fopen(Catenate(db->path, "", "", ".bps"), "r");
}
rewind(bases);
qsort(rids, nrids, sizeof(int), cmp_rids);
if(nrids)
nrids = unique(rids, nrids);
uint64 totallen = 0;
int i;
for (i = 0; i < nrids; i++)
{
totallen += reads[i].rlen;
}
// printf("%llu bytes needed for %d reads\n", totallen, nrids);
if (totallen > rl->maxreads)
{
rl->maxreads = totallen + 10*1000;
rl->reads = (char*)realloc(rl->reads, rl->maxreads);
}
int nbuf = BLOCK_BUFFER;
char* buffer = malloc(nbuf);
// uint64 rb = 0;
uint64 re = 0;
off_t offb = 0;
off_t offe = 0;
int currid = 0;
uint64 curreads = 0;
while (re < nreads && currid < nrids)
{
while (offe - offb < nbuf && re < nreads)
{
offe = reads[re].boff;
re++;
}
while (offe - offb > nbuf)
{
re--;
offe = reads[re].boff;
}
//printf("reading from %'llu..%'llu %'llu..%'llu\n", rb, re, offb, offe);
fseeko(bases, offb, SEEK_SET);
if (fread(buffer, offe - offb, 1, bases) != 1)
{
fprintf(stderr, "failed to read bases file\n");
exit(1);
}
while ( currid < nrids && (uint64)rids[currid] < re )
{
int rid = rids[currid];
int len = reads[rid].rlen;
int clen = COMPRESSED_LEN(len);
/*
printf(" %'8d @ %'8lld %'8lld %d %d\n",
rid, reads[rid].boff, reads[rid].boff - offb,
curreads, clen);
*/
memcpy(rl->reads + curreads, buffer + (reads[rid].boff - offb), clen);
rl->index[rid] = rl->reads + curreads;
curreads += clen;
currid++;
}
// rb = re;
offb = offe;
}
free(buffer);
}
void rl_load_read(Read_Loader* rl, int rid, char* read, int ascii)
{
char* compressed = rl->index[rid];
assert(compressed != NULL);
HITS_READ* reads = rl->db->reads;
int len = reads[rid].rlen;
int clen = COMPRESSED_LEN(len);
memcpy(read, compressed, clen);
Uncompress_Read(len, read);
if (ascii == 1)
{
Lower_Read(read);
read[-1] = '\0';
}
else if (ascii == 2)
{
Upper_Read(read);
read[-1] = '\0';
}
else
{
read[-1] = 4;
}
}
void rl_free(Read_Loader* rl)
{
free(rl->index);
free(rl->reads);
free(rl);
}
|
MartinPippel/DAmar
|
db/FA2x.h
|
typedef struct
{
int well;
int beg;
int end;
int len;
int hasPacbioHeader;
int seqIDinFasta;
int maxPrologLen;
char *prolog;
int maxSequenceLen;
char *seq;
int maxtracks;
int ntracks;
int maxName;
char **trackName;
int **trackfields;
} pacbio_read;
// used in fasta2DB and fasta2DAM
typedef struct
{
HITS_DB* db;
int t_cur;
int t_max;
char** t_name;
track_anno** t_anno;
track_data** t_data;
int t_create_max;
int t_create_n;
char** t_create;
int* t_max_anno;
int* t_max_data;
int* t_cur_anno;
int* t_cur_data;
//
int VERBOSE;
int BEST; // if true, incorporate only best read from each well of pacbio SMRT cell
int opt_min_length; // skip reads, that are shorter than this threshold
int appendReadsToNewBlock;
int lastParameterIdx;
int useFullHqReadsOnly;
// int createTracks;
FILE* IFILE;
char * root;
char *dbname; // dbname = full name of db = <pwd>/<root>.db
char *pwd;
int ifiles; // ifiles = # of .fasta files to add
int ofiles; // ofiles = # of .fasta files already in db
char **flist; // flist = [0..ifiles+ofiles] list of file names (root only) added to db so far
FILE* istub; // istub = open db file (if adding) or NULL (if creating)
FILE* ostub; // ostub = new image of db file (will overwrite old image at end)
FILE *bases; // bases = .bps file positioned for appending
FILE *indx; // indx = .idx file positioned for appending
int64 offset; // offset = offset in .bps at which to place next sequence
int64 boff; // boff = offset in .bps file to truncate to if command fails
int64 ioff; // ioff = offset in .idx file to truncate to if command fails
int initialUreads;
int ureads; // ureads = # of reads currently in db
int64 totlen; // total # of bases in new .fasta files
int maxlen; // longest read in new .fasta files
int64 count[4];
// used during file parsing
int rmax;
char *read;
pacbio_read* pr1;
pacbio_read* pr2;
} CreateContext;
int find_track(CreateContext* ctx, const char* name);
void add_to_track(CreateContext* ctx, int track, int64 read, track_data value);
void write_tracks(CreateContext* ctx, char* dbpath);
void free_tracks(CreateContext* ctx);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.