kmer_similarity.c 16.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
/****************************************************************************
 * Kmer similarity computation functions                                      *
 ****************************************************************************/

/**
 * @file kmer_similarity.c
 * @author Celine Mercier (celine.mercier@metabarcoding.org)
 * @date January 7th 2019
 * @brief Kmer similarity computation functions.
 */

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>

#include "utils.h"
#include "obidebug.h"
#include "obierrno.h"
#include "obitypes.h"

#include "kmer_similarity.h"
#include "obidmscolumn.h"
#include "obiview.h"
#include "encode.h"
#include "dna_seq_indexer.h"


#define DEBUG_LEVEL 0	// TODO has to be defined somewhere else (cython compil flag?)



/**************************************************************************
 *
 * D E C L A R A T I O N   O F   T H E   P R I V A T E   F U N C T I O N S
 *
 **************************************************************************/




/************************************************************************
 *
 * D E F I N I T I O N   O F   T H E   P R I V A T E   F U N C T I O N S
 *
 ************************************************************************/




/**********************************************************************
 *
 * D E F I N I T I O N   O F   T H E   P U B L I C   F U N C T I O N S
 *
 **********************************************************************/


void obi_free_shifted_ali(Obi_ali_p ali)
{
	free(ali->consensus_seq);
	free(ali->consensus_qual);
	free(ali);
}


Obi_ali_p kmer_similarity(Obiview_p view1, OBIDMS_column_p column1, index_t idx1, index_t elt_idx1,
67
						  Obiview_p view2, OBIDMS_column_p column2, index_t idx2, index_t elt_idx2,
68
						  OBIDMS_column_p qual_col1, OBIDMS_column_p qual_col2, OBIDMS_column_p reversed_column,
69
						  uint8_t kmer_size,
70 71 72
						  int32_t** kmer_pos_array_p, int32_t* kmer_pos_array_height_p,
						  int32_t** shift_array_p, int32_t* shift_array_height_p,
						  int32_t** shift_count_array_p, int32_t* shift_count_array_length_p,
73
						  bool build_consensus)
74
{
75 76 77
	int32_t*        kmer_pos_array;
	int32_t*        shift_array;
	int32_t*        shift_count_array;
78
	Obi_ali_p       ali = NULL;
79 80
	int 			i, j;
	bool 			switched_seqs;
81
	bool			reversed;
82
	int 			score = 0;
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
	Obi_blob_p      blob1 = NULL;
	Obi_blob_p   	blob2 = NULL;
	Obi_blob_p   	temp_blob = NULL;
	char*			seq1 = NULL;
	char*			seq2 = NULL;
	int32_t         len1;
	int32_t         len2;
	int32_t			temp_len;
	int32_t         pos;
	int32_t         shift1;
	int32_t         shift2;
	const uint8_t*  qual1;
	const uint8_t*  qual2;
	int             qual1_len;
	int				qual2_len;
	char*           consensus_seq;
	uint8_t*        consensus_qual;
	int32_t  		empty_part;
	int32_t	        nuc_idx;
	int32_t    		kmer_idx;
	int32_t	        kmer_count;
	int32_t         best_shift_idx;
	int32_t         best_shift;
106
	int32_t         abs_shift;
107 108 109 110
	int32_t         max_common_kmers;
	int32_t         overlap_len;
	int32_t         consensus_len;
	int32_t  		cons_shift;
111 112
	int32_t  		copy_start;
	int32_t  		copy_len;
113 114 115 116 117 118 119 120 121 122
	uint8_t   		kmer;
	byte_t          nuc;
	uint8_t         encoding;
	int             total_len;
	int             shift;
	int32_t  		shift_idx;
	int32_t         kmer_pos_array_height    = *kmer_pos_array_height_p;
	int32_t         shift_array_height       = *shift_array_height_p;
	int32_t         shift_count_array_length = *shift_count_array_length_p;
	bool			free_blob1 = false;
123 124 125 126
	bool			keep_seq1_start;
	bool			keep_seq2_start;
	bool			keep_seq1_end;
	bool			keep_seq2_end;
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150

	// Check kmer size
	if ((kmer_size < 1) || (kmer_size > 4))
	{
		obi_set_errno(OBI_ALIGN_ERROR);
		obidebug(1, "\nError when computing the kmer similarity between two sequences: the kmer size must be >= 1 or <= 4");
		return NULL;
	}

	// Get sequence blobs
	blob1 = obi_get_blob_with_elt_idx_and_col_p_in_view(view1, column1, idx1, elt_idx1);
	if (blob1 == NULL)
	{
	 	obidebug(1, "\nError getting the blob of the 1st sequence when computing the kmer similarity between two sequences");
	 	return NULL;
	}
	blob2 = obi_get_blob_with_elt_idx_and_col_p_in_view(view2, column2, idx2, elt_idx2);
	if (blob2 == NULL)
	{
	 	obidebug(1, "\nError getting the blob of the 2nd sequence when computing the kmer similarity between two sequences");
	 	return NULL;
	}

	// Choose the shortest sequence to save kmer positions in array
151
	switched_seqs = false;
152 153
	len1 = blob1->length_decoded_value;
	len2 = blob2->length_decoded_value;
154
	if (len2 < len1)
155
	{
156
		switched_seqs = true;
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
		temp_len = len1;
		len1 = len2;
		len2 = temp_len;
		temp_blob = blob1;
		blob1 = blob2;
		blob2 = temp_blob;
	}

	// Force encoding on 2 bits by replacing ambiguous nucleotides by 'a's
	if (blob1->element_size == 4)
	{
		seq1 = obi_blob_to_seq(blob1);
		for (i=0; i<len1; i++)
		{
			if (seq1[i] != 'a' && seq1[i] != 't' && seq1[i] != 'g' && seq1[i] != 'c')
				seq1[i] = 'a';
		}
		blob1 = obi_seq_to_blob(seq1);
		free_blob1 = true;
	}
	if (blob2->element_size == 4)
	{
		seq2 = obi_blob_to_seq(blob2);
		for (i=0; i<len2; i++)
		{
			if (seq2[i] != 'a' && seq2[i] != 't' && seq2[i] != 'g' && seq2[i] != 'c')
				seq2[i] = 'a';
		}
	}

	// Reverse complement the other sequence    // TODO blob to seq to blob for now, could be more efficient
	if (seq2 == NULL)
		seq2 = obi_blob_to_seq(blob2);
	seq2 = reverse_complement_sequence(seq2);
	blob2 = obi_seq_to_blob(seq2);

193 194 195 196 197 198 199 200
	// Check if the sequences have been reverse-complemented by the ngsfilter tool
	if (reversed_column != NULL)
		reversed = obi_get_bool_with_elt_idx_and_col_p_in_view(view1, reversed_column, idx1, 0); // assuming that reversed_column is in view1 is dirty but faster
	else
		reversed = false;
	if (reversed)
		switched_seqs = !switched_seqs;

201 202 203 204
	// Save total length for the shift counts array
	total_len = len1 + len2 + 1;   // +1 for shift 0

	// Allocate or reallocate memory for the array of shift counts if necessary
205
	if (*shift_count_array_p == NULL)
206 207
	{
		shift_count_array_length = total_len;
208 209
		*shift_count_array_p = (int32_t*) malloc(shift_count_array_length * sizeof(int32_t));
		if (*shift_count_array_p == NULL)
210 211 212 213 214 215 216 217 218
		{
		 	obi_set_errno(OBI_MALLOC_ERROR);
		 	obidebug(1, "\nError computing the kmer similarity between two sequences: error allocating memory");
		 	return NULL;
		}
	}
	else if (total_len >= shift_count_array_length)
	{
		shift_count_array_length = total_len;
219 220
		*shift_count_array_p = (int32_t*) realloc(*shift_count_array_p, shift_count_array_length * sizeof(int32_t));
		if (*shift_count_array_p == NULL)
221 222 223 224 225 226 227 228
		{
		 	obi_set_errno(OBI_MALLOC_ERROR);
		 	obidebug(1, "\nError computing the kmer similarity between two sequences: error allocating memory");
		 	return NULL;
		}
	}

	// Allocate or reallocate memory for the array of shifts if necessary
229
	if (*shift_array_p == NULL)
230 231
	{
		shift_array_height = total_len;
232 233
		*shift_array_p = (int32_t*) malloc(ARRAY_LENGTH * shift_array_height * sizeof(int32_t));
		if (*shift_array_p == NULL)
234 235 236 237 238 239 240 241 242
		{
		 	obi_set_errno(OBI_MALLOC_ERROR);
		 	obidebug(1, "\nError computing the kmer similarity between two sequences: error allocating memory");
		 	return NULL;
		}
	}
	else if (len1 >= shift_array_height)
	{
		shift_array_height = total_len;
243 244
		*shift_array_p = (int32_t*) realloc(*shift_array_p, ARRAY_LENGTH * shift_array_height * sizeof(int32_t));
		if (*shift_array_p == NULL)
245 246 247 248 249 250 251 252
		{
		 	obi_set_errno(OBI_MALLOC_ERROR);
		 	obidebug(1, "\nError computing the kmer similarity between two sequences: error allocating memory");
		 	return NULL;
		}
	}

	// Allocate or reallocate memory for the array of positions if necessary
253
	if (*kmer_pos_array_p == NULL)
254 255
	{
		kmer_pos_array_height = len1;
256 257
		*kmer_pos_array_p = (int32_t*) malloc(ARRAY_LENGTH * kmer_pos_array_height * sizeof(int32_t));
		if (*kmer_pos_array_p == NULL)
258 259 260 261 262 263 264 265 266
		{
		 	obi_set_errno(OBI_MALLOC_ERROR);
		 	obidebug(1, "\nError computing the kmer similarity between two sequences: error allocating memory");
		 	return NULL;
		}
	}
	else if (len1 >= kmer_pos_array_height)
	{
		kmer_pos_array_height = len1;
267 268
		*kmer_pos_array_p = (int32_t*) realloc(*kmer_pos_array_p, ARRAY_LENGTH * kmer_pos_array_height * sizeof(int32_t));
		if (*kmer_pos_array_p == NULL)
269 270 271 272 273 274 275
		{
		 	obi_set_errno(OBI_MALLOC_ERROR);
		 	obidebug(1, "\nError computing the kmer similarity between two sequences: error allocating memory");
		 	return NULL;
		}
	}

276 277 278 279
	shift_count_array = *shift_count_array_p;
	shift_array = *shift_array_p;
	kmer_pos_array = *kmer_pos_array_p;

280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
	// Initialize all positions to -1
	for (i=0; i<(ARRAY_LENGTH * kmer_pos_array_height); i++)
		kmer_pos_array[i] = -1;
	// Initialize all shifts to the maximum value of an int32_t
	for (i=0; i<(ARRAY_LENGTH * shift_array_height); i++)
		shift_array[i] = INT32_MAX;
	//memset(shift_array, 1, ARRAY_LENGTH * shift_array_height * sizeof(int32_t)); // why doesn't this work?
	// Initialize all shift counts to 0
	memset(shift_count_array, 0, shift_count_array_length * sizeof(int32_t));

	*kmer_pos_array_height_p = kmer_pos_array_height;
	*shift_array_height_p = shift_array_height;
	*shift_count_array_length_p = shift_count_array_length;

	// Fill array with positions of kmers in the shortest sequence
	encoding = blob1->element_size;
	kmer_count = len1 - kmer_size + 1;
	for (kmer_idx=0; kmer_idx < kmer_count; kmer_idx++)
	{
		kmer = 0;
		for (nuc_idx=kmer_idx; nuc_idx<(kmer_idx+kmer_size); nuc_idx++)
		{
			nuc = get_nucleotide_from_encoded_seq(blob1->value, nuc_idx, encoding);
			kmer <<= encoding;
			kmer |= nuc;
		}

		i = 0;
		while (kmer_pos_array[(kmer*kmer_pos_array_height)+i] != -1)
			i++;
		kmer_pos_array[(kmer*kmer_pos_array_height)+i] = kmer_idx;
	}

	// Compare positions of kmers between both sequences and store shifts
	kmer_count = blob2->length_decoded_value - kmer_size + 1;
	for (kmer_idx=0; kmer_idx < kmer_count; kmer_idx++)
	{
		kmer = 0;
		for (nuc_idx=kmer_idx; nuc_idx<(kmer_idx+kmer_size); nuc_idx++)
		{
			nuc = get_nucleotide_from_encoded_seq(blob2->value, nuc_idx, encoding);
			kmer <<= encoding;
			kmer |= nuc;
		}

		// Get the index at which the new shifts should be stored for that kmer
		j = 0;
		while ((shift_array[(kmer*shift_array_height)+j] != INT32_MAX) && (j<shift_array_height))
			j++;
		// Store the shift between the kmer in the 1st and the 2nd sequence
		i = 0;
		while ((kmer_pos_array[(kmer*kmer_pos_array_height)+i] != -1) && (i<kmer_pos_array_height))
		{
			shift_array[(kmer*shift_array_height)+j] = kmer_idx - kmer_pos_array[(kmer*kmer_pos_array_height)+i];
			i++;
			j++;
		}
	}

	// Count how many times each shift is represented
	for (kmer=0;;kmer++)
	{
		for (i=0;;i++)
		{
			shift = shift_array[(kmer*shift_array_height)+i];
			if ((shift == INT32_MAX) || (i==shift_array_height))
				break;
			shift_idx = shift + len1;
			shift_count_array[shift_idx]++;
		}
		if (kmer == (ARRAY_LENGTH-1))  // stop condition can't be in for line because kmer can't be >= 255
			break;
	}

	// Find the most represented shift
	best_shift_idx = 0;
	max_common_kmers = 0;
357 358
	//empty_part = (shift_count_array_length-1)/2 - len1; //TODO wrong in some cases (len1 shorter than overlap or something like that)
	empty_part = 0;
359 360 361 362 363 364 365 366 367 368
	for (i=empty_part; i < (shift_count_array_length - empty_part); i++)  // skipping empty parts of the array
	{
		if (shift_count_array[i] > max_common_kmers)
		{
			best_shift_idx = i;
			max_common_kmers = shift_count_array[i];
		}
	}
	best_shift = best_shift_idx - len1;

369 370 371 372 373 374
	keep_seq1_start = false;
	keep_seq1_end = false;
	keep_seq2_start = false;
	keep_seq2_end = false;

	// The 873863 cases of hell
375
	if (best_shift > 0)
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
	{
		overlap_len = len2 - best_shift;
		if (len1 <= overlap_len)
		{
			overlap_len = len1;
			if (! switched_seqs)
				keep_seq2_end = true;
			else
				keep_seq2_start = true;
		}
		else if (switched_seqs)
		{
			keep_seq2_start = true;
			keep_seq1_end = true;
		}
	}
	else if (best_shift < 0)
	{
394
	    overlap_len = len1 + best_shift;
395 396 397 398 399 400 401 402 403 404 405 406
	    if (!switched_seqs)
	    {
	    	keep_seq1_start = true;
	    	keep_seq2_end = true;
	    }
	}
	else
	{
		overlap_len = len1;
		if ((!switched_seqs) && (len2 > len1))
			keep_seq2_end = true;
	}
407 408 409 410 411 412 413 414 415

	ali = (Obi_ali_p) malloc(sizeof(Obi_ali_t));
	if (ali == NULL)
	{
	 	obi_set_errno(OBI_MALLOC_ERROR);
	 	obidebug(1, "\nError computing the kmer similarity between two sequences: error allocating memory for the result structure");
	 	return NULL;
	}

416
	score = max_common_kmers + kmer_size - 1;  // aka the number of nucleotides in the longest stretch of kmers perfectly matching
417 418
	abs_shift = abs(best_shift);

419 420 421 422
	// Save result in Obi_ali structure
	ali->score = score;
	ali->consensus_length = 0;
	ali->overlap_length = overlap_len;
423
	ali->shift = abs_shift;
424 425
	ali->consensus_seq = NULL;
	ali->consensus_qual = NULL;
426
	if (((best_shift <= 0) && (!switched_seqs)) || ((best_shift > 0) && switched_seqs))
427 428 429
		strcpy(ali->direction, "left");
	else
		strcpy(ali->direction, "right");
430 431 432 433 434 435 436 437

	// Build the consensus sequence if asked
	if (build_consensus)
	{
		// Get the quality arrays
		qual1 = obi_get_qual_int_with_elt_idx_and_col_p_in_view(view1, qual_col1, idx1, 0, &qual1_len);
		if (qual1 == NULL)
		{
438
			obidebug(1, "\nError getting the quality of the 1st sequence when computing the kmer similarity between two sequences");
439 440 441 442 443
			return NULL;
		}
		qual2 = obi_get_qual_int_with_elt_idx_and_col_p_in_view(view2, qual_col2, idx2, 0, &qual2_len);
		if (qual2 == NULL)
		{
444
			obidebug(1, "\nError getting the quality of the 2nd sequence when computing the kmer similarity between two sequences");
445 446 447 448 449 450 451
			return NULL;
		}

		// Decode the first sequence if not already done
		if (seq1 == NULL)
			seq1 = obi_blob_to_seq(blob1);

452 453
		if (! switched_seqs)
		    consensus_len = len2 - best_shift;
454
		else
455
		    consensus_len = len1 + best_shift;
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478

		// Allocate memory for consensus sequence
		consensus_seq = (char*) malloc(consensus_len + 1 * sizeof(char)); // TODO keep malloced too maybe
		if (consensus_seq == NULL)
		{
		 	obi_set_errno(OBI_MALLOC_ERROR);
		 	obidebug(1, "\nError computing the kmer similarity between two sequences: error allocating memory for the consensus sequence");
		 	return NULL;
		}

		// Allocate memory for consensus quality
		consensus_qual = (uint8_t*) malloc(consensus_len * sizeof(uint8_t));
		if (consensus_qual == NULL)
		{
		 	obi_set_errno(OBI_MALLOC_ERROR);
		 	obidebug(1, "\nError computing the kmer similarity between two sequences: error allocating memory for the consensus quality");
		 	return NULL;
		}

		ali->consensus_length = consensus_len;
		ali->consensus_seq = consensus_seq;
		ali->consensus_qual = consensus_qual;

479 480
		// Compute consensus-relative shift for each sequence
		if (best_shift > 0)
481
		{
482 483
			shift1 = 0;
			shift2 = best_shift;
484 485 486
		}
		else
		{
487 488
			shift1 = -(best_shift);
			shift2 = 0;
489 490
		}

491 492
		// Copy first part of first or second sequence depending on cases
		if (keep_seq1_start)
493
		{
494 495 496 497 498 499 500 501 502
			strncpy(consensus_seq, seq1, abs_shift);
			memcpy(consensus_qual, qual1, abs_shift*sizeof(uint8_t));
			cons_shift = abs_shift;
		}
		else if (keep_seq2_start)
		{
			strncpy(consensus_seq, seq2, abs_shift);
			memcpy(consensus_qual, qual2, abs_shift*sizeof(uint8_t));
			cons_shift = abs_shift;
503 504 505 506 507 508 509 510 511 512 513 514 515 516
		}
		else
			cons_shift = 0;

		// Build consensus part
		for (pos=0; pos<overlap_len; pos++)
		{
			if (qual1[pos+shift1] >= qual2[pos+shift2])
				consensus_seq[pos+cons_shift] = seq1[pos+shift1];
			else
				consensus_seq[pos+cons_shift] = seq2[pos+shift2];
 			consensus_qual[pos+cons_shift] = round((qual1[pos+shift1] + qual2[pos+shift2])/2);    // TODO maybe use the (p1*(1-p2/3)) formula (but parenthesis bug???)
		}

517 518 519 520 521 522 523
		// Copy last part of first or second sequence depending on cases
		if (keep_seq1_end)
		{
			strncpy(consensus_seq+cons_shift+overlap_len, seq1+overlap_len, len1 - overlap_len);
			memcpy(consensus_qual+cons_shift+overlap_len, qual1+overlap_len, (len1 - overlap_len)*sizeof(uint8_t));
		}
		if (keep_seq2_end)
524
		{
525
			if (best_shift <= 0)
526
			{
527 528
				copy_start = overlap_len;
				copy_len = len2 - overlap_len;
529
			}
530
			if (best_shift > 0)
531
			{
532 533
				copy_start = overlap_len + best_shift;
				copy_len = len2 - overlap_len - best_shift;
534
			}
535 536
			strncpy(consensus_seq+cons_shift+overlap_len, seq2+copy_start, copy_len);
			memcpy(consensus_qual+cons_shift+overlap_len, qual2+copy_start, copy_len*sizeof(uint8_t));
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
		}

		consensus_seq[consensus_len] = '\0';
	}

	if (seq1 != NULL)
		free(seq1);
	if (free_blob1)
		free(blob1);
	free(seq2);
	free(blob2);

	return ali;
}