sse_banded_LCS_alignment.c 33.3 KB
Newer Older
1 2 3 4 5 6 7 8 9
/****************************************************************************
 * LCS alignment of two sequences				                            *
 ****************************************************************************/

/**
 * @file sse_banded_LCS_alignment.c
 * @author Celine Mercier (celine.mercier@metabarcoding.org)
 * @date November 7th 2012
 * @brief Functions handling the alignment of two sequences to compute their Longest Common Sequence.
10 11 12
 */


13

14 15 16 17 18
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdint.h>
#include <stdbool.h>
19
#include <limits.h>
20 21 22 23 24 25

#include "obierrno.h"
#include "obidebug.h"
#include "utils.h"
#include "_sse.h"
#include "sse_banded_LCS_alignment.h"
26 27
#include "obiblob.h"
#include "encode.h"	// TODO move putBlobInSeq function to encode.c ?
28 29 30 31 32


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


33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257

/**************************************************************************
 *
 * 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
 *
 **************************************************************************/


/**
 * @brief Internal function printing a 128 bits register as 8 16-bits integers.
 *
 * @param r The register to print.
 *
 * @author Eric Coissac (eric.coissac@metabarcoding.org)
 */
static void printreg(__m128i r);


/**
 * @brief Internal function extracting a 16-bits integer from a 128 bits register.
 *
 * @param r The register to read.
 * @param p The position at which the integer should be read (between 0 and 7).
 *
 * @returns The extracted integer.
 *
 * @author Eric Coissac (eric.coissac@metabarcoding.org)
 */
static inline int extract_reg(__m128i r, int p);


/**
 * @brief Internal function aligning two sequences, computing the lengths of their Longest Common Subsequence and of their alignment.
 *
 * @warning The first argument (seq1) must correspond to the longest sequence.
 *
 * @param seq1 The first sequence, the longest of the two, as prepared by putSeqInSeq() or putBlobInSeq().
 * @param seq2 The second sequence, the shortest of the two, as prepared by putSeqInSeq() or putBlobInSeq().
 * @param l1 The length of the first sequence.
 * @param l2 The length of the second sequence.
 * @param bandLengthLeft The length of the left band for the banded alignment, as computed by calculateLeftBandLength().
 * @param bandLengthTotal The length of the complete band for the banded alignment, as computed by calculateSSEBandLength().
 * @param address A pointer, aligned on a 16 bits boundary, on the int array where the initial values for the alignment length are stored,
 *                as prepared for the alignment by initializeAddressWithGaps().
 * @param lcs_length A pointer on the int where the LCS length will be stored.
 * @param ali_length A pointer on the int where the alignment length will be stored.
 *
 * @since 2012
 * @author Celine Mercier (celine.mercier@metabarcoding.org)
 */
void sse_banded_align_lcs_and_ali_len(int16_t* seq1, int16_t* seq2, int l1, int l2, int bandLengthLeft, int bandLengthTotal, int16_t* address, int* lcs_length, int* ali_length);


/**
 * @brief Internal function aligning two sequences, computing the length of their Longest Common Subsequence (and not the alignment length).
 *
 * @warning The first argument (seq1) must correspond to the longest sequence.
 *
 * @param seq1 The first sequence, the longest of the two, as prepared by putSeqInSeq() or putBlobInSeq().
 * @param seq2 The second sequence, the shortest of the two, as prepared by putSeqInSeq() or putBlobInSeq().
 * @param l1 The length of the first sequence.
 * @param l2 The length of the second sequence.
 * @param bandLengthLeft The length of the left band for the banded alignment, as computed by calculateLeftBandLength().
 * @param bandLengthTotal The length of the complete band for the banded alignment, as computed by calculateSSEBandLength().
 * @param lcs_length A pointer on the int where the LCS length will be stored.
 *
 * @since 2012
 * @author Celine Mercier (celine.mercier@metabarcoding.org)
 */
void sse_banded_align_just_lcs(int16_t* seq1, int16_t* seq2, int l1, int l2, int bandLengthLeft, int bandLengthTotal, int* lcs_length);


/**
 * @brief Internal function calculating the length of the left band for the banded alignment.
 *
 * @param lmax The length of the longest sequence to align.
 * @param LCSmin The minimum length of the LCS to be above the chosen threshold, as computed by calculateLCSmin().
 *
 * @returns The length of the left band.
 *
 * @since 2012
 * @author Celine Mercier (celine.mercier@metabarcoding.org)
 */
int calculateLeftBandLength(int lmax, int LCSmin);


/**
 * @brief Internal function calculating the length of the right band for the banded alignment.
 *
 * @param lmin The length of the shortest sequence to align.
 * @param LCSmin The minimum length of the LCS to be above the chosen threshold, as computed by calculateLCSmin().
 *
 * @returns The length of the right band.
 *
 * @since 2012
 * @author Celine Mercier (celine.mercier@metabarcoding.org)
 */
int calculateRightBandLength(int lmin, int LCSmin);


/**
 * @brief Internal function calculating the length of the complete band for the banded alignment.
 *
 * @param bandLengthRight The length of the right band for the banded alignment, as computed by calculateRightBandLength().
 * @param bandLengthLeft The length of the left band for the banded alignment, as computed by calculateLeftBandLength().
 *
 * @returns The length of the complete band.
 *
 * @since 2012
 * @author Celine Mercier (celine.mercier@metabarcoding.org)
 */
int calculateSSEBandLength(int bandLengthRight, int bandLengthLeft);


/**
 * @brief Internal function calculating the size to allocate for the int array where the alignment length will be stored in the matrix.
 *
 * @param maxLen The length of the longest sequence to align.
 * @param LCSmin The minimum length of the LCS to be above the chosen threshold, as computed by calculateLCSmin().
 *
 * @returns The size to allocate in bytes.
 *
 * @since 2012
 * @author Celine Mercier (celine.mercier@metabarcoding.org)
 */
int calculateSizeToAllocate(int maxLen, int LCSmin);


/**
 * @brief Internal function initializing the int array corresponding to a sequence to align with default values.
 *
 * @param seq The int array corresponding to the sequence to align, as prepared by putSeqInSeq() or putBlobInSeq().
 * @param size The number of positions to initialize.
 * @param iniValue The value that the positions should be initialized to.
 *
 * @since 2012
 * @author Celine Mercier (celine.mercier@metabarcoding.org)
 */
void iniSeq(int16_t* seq, int size, int16_t iniValue);


/**
 * @brief Internal function building the int array corresponding to a sequence to align.
 *
 * Each nucleotide is stored as a short int (int16_t).
 *
 * @param seq A pointer on the allocated int array.
 * @param s A pointer on the character string corresponding to the sequence.
 * @param l The length of the sequence.
 * @param reverse A boolean indicating whether the sequence should be written reversed
 *                (for the second sequence to align).
 *
 * @since 2012
 * @author Celine Mercier (celine.mercier@metabarcoding.org)
 */
void putSeqInSeq(int16_t* seq, char* s, int l, bool reverse);


/**
 * @brief Internal function building the int array corresponding to an obiblob containing a sequence.
 *
 * Each nucleotide is stored as a short int (int16_t).
 *
 * @param seq A pointer on the allocated int array.
 * @param b A pointer on the obiblob containing the sequence.
 * @param l The length of the (decoded) sequence.
 * @param reverse A boolean indicating whether the sequence should be written reversed
 *                (for the second sequence to align).
 *
 * @since 2012
 * @author Celine Mercier (celine.mercier@metabarcoding.org)
 */
void putBlobInSeq(int16_t* seq, Obi_blob_p b, int l, bool reverse);


/**
 * @brief Internal function preparing an int array with the initial values for the alignment lengths before the alignment.
 *
 * The int array containing the initial alignment lengths (corresponding to the first line of the diagonalized band of the alignment matrix)
 * needs to be initialized with external gap lengths before the alignment.
 *
 * @param address A pointer, aligned on a 16 bits boundary, on the int array where the initial values for the alignment length are to be stored.
 * @param bandLengthTotal The length of the complete band for the banded alignment, as computed by calculateSSEBandLength().
 * @param bandLengthLeft The length of the left band for the banded alignment, as computed by calculateLeftBandLength().
 * @param lmax The length of the longest sequence to align.
 *
 * @since 2012
 * @author Celine Mercier (celine.mercier@metabarcoding.org)
 */
void initializeAddressWithGaps(int16_t* address, int bandLengthTotal, int bandLengthLeft, int lmax);


/**
 * @brief Internal function aligning two sequences, computing the lengths of their Longest Common Subsequence and of their alignment.
 *
 * @warning The first argument (seq1) must correspond to the longest sequence.
 *
 * @param seq1 The first sequence, the longest of the two, as prepared by putSeqInSeq() or putBlobInSeq().
 * @param seq2 The second sequence, the shortest of the two, as prepared by putSeqInSeq() or putBlobInSeq().
 * @param l1 The length of the first sequence.
 * @param l2 The length of the second sequence.
 * @param normalize Whether the score should be normalized with the reference sequence length.
 * @param reference The reference length. 0: The alignment length; 1: The longest sequence's length; 2: The shortest sequence's length.
 * @param similarity_mode Whether the score should be expressed in similarity (true) or distance (false).
 * @param address A pointer, aligned on a 16 bits boundary, on an allocated int array where the initial values for the alignment length will be stored.
 * @param LCSmin The minimum length of the LCS to be above the chosen threshold, as computed by calculateLCSmin().
 * @param lcs_length A pointer on the int where the LCS length will be stored.
 * @param ali_length A pointer on the int where the alignment length will be stored.
 *
 * @returns The alignment score (normalized according to the parameters).
 *
 * @since 2012
 * @author Celine Mercier (celine.mercier@metabarcoding.org)
 */
double sse_banded_lcs_align(int16_t* seq1, int16_t* seq2, int l1, int l2, bool normalize, int reference, bool similarity_mode, int16_t* address, int LCSmin, int* lcs_length, int* ali_length);



/************************************************************************
 *
 * 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
 *
 ************************************************************************/


258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
static void  printreg(__m128i r)
{
	int16_t a0,a1,a2,a3,a4,a5,a6,a7;

	a0= _MM_EXTRACT_EPI16(r,0);
	a1= _MM_EXTRACT_EPI16(r,1);
	a2= _MM_EXTRACT_EPI16(r,2);
	a3= _MM_EXTRACT_EPI16(r,3);
	a4= _MM_EXTRACT_EPI16(r,4);
	a5= _MM_EXTRACT_EPI16(r,5);
	a6= _MM_EXTRACT_EPI16(r,6);
	a7= _MM_EXTRACT_EPI16(r,7);

fprintf(stderr, "a00 :-> %7d  %7d  %7d  %7d "
		" %7d  %7d  %7d  %7d "
		"\n"
		, a0,a1,a2,a3,a4,a5,a6,a7
		);
}


static inline int extract_reg(__m128i r, int p)
{
	switch (p) {
	case 0: return(_MM_EXTRACT_EPI16(r,0));
	case 1: return(_MM_EXTRACT_EPI16(r,1));
	case 2: return(_MM_EXTRACT_EPI16(r,2));
	case 3: return(_MM_EXTRACT_EPI16(r,3));
	case 4: return(_MM_EXTRACT_EPI16(r,4));
	case 5: return(_MM_EXTRACT_EPI16(r,5));
	case 6: return(_MM_EXTRACT_EPI16(r,6));
	case 7: return(_MM_EXTRACT_EPI16(r,7));
	}
	return(0);
}


295
void sse_banded_align_lcs_and_ali_len(int16_t* seq1, int16_t* seq2, int l1, int l2, int bandLengthLeft, int bandLengthTotal, int16_t* address, int* lcs_length, int* ali_length)
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
{
	register int j;
	int k1, k2;
	int max, diff;
	int l_reg, l_loc;
	int line;
	int numberOfRegistersPerLine;
	int numberOfRegistersFor3Lines;

	bool even_line;
	bool odd_line;
	bool even_BLL;
	bool odd_BLL;

	um128*  SSEregisters;
	um128*  p_diag;
	um128*  p_gap1;
	um128*  p_gap2;
	um128*  p_diag_j;
	um128*  p_gap1_j;
	um128*  p_gap2_j;
	um128   current;

	um128*  l_ali_SSEregisters;
	um128*  p_l_ali_diag;
	um128*  p_l_ali_gap1;
	um128*  p_l_ali_gap2;
	um128*  p_l_ali_diag_j;
	um128*  p_l_ali_gap1_j;
	um128*  p_l_ali_gap2_j;
	um128   l_ali_current;

	um128  nucs1;
	um128  nucs2;
	um128  scores;

	um128 boolean_reg;

	// Initialisations

	odd_BLL = bandLengthLeft & 1;
	even_BLL  = !odd_BLL;

	max = INT16_MAX - l1;

	numberOfRegistersPerLine = bandLengthTotal / 8;
342
	numberOfRegistersFor3Lines = 3 * numberOfRegistersPerLine;
343 344 345 346 347 348 349

	SSEregisters = (um128*) calloc(numberOfRegistersFor3Lines * 2, sizeof(um128));
	l_ali_SSEregisters = SSEregisters + numberOfRegistersFor3Lines;

	// preparer registres SSE

	for (j=0; j<numberOfRegistersFor3Lines; j++)
350
		l_ali_SSEregisters[j].i = _MM_LOAD_SI128((const __m128i*)(address+j*8));
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385

	p_diag    = SSEregisters;
	p_gap1    = SSEregisters+numberOfRegistersPerLine;
	p_gap2    = SSEregisters+2*numberOfRegistersPerLine;

	p_l_ali_diag    = l_ali_SSEregisters;
	p_l_ali_gap1    = l_ali_SSEregisters+numberOfRegistersPerLine;
	p_l_ali_gap2    = l_ali_SSEregisters+2*numberOfRegistersPerLine;

	// Loop on diagonals = 'lines' :
	for (line=2; line <= l1+l2; line++)
	{
		odd_line = line & 1;
		even_line  = !odd_line;

		// loop on the registers of a line :
		for (j=0; j < numberOfRegistersPerLine; j++)
		{
			p_diag_j       = p_diag+j;
			p_gap1_j       = p_gap1+j;
			p_gap2_j       = p_gap2+j;
			p_l_ali_diag_j = p_l_ali_diag+j;
			p_l_ali_gap1_j = p_l_ali_gap1+j;
			p_l_ali_gap2_j = p_l_ali_gap2+j;

		// comparing nucleotides for diagonal scores :

			// k1 = position of the 1st nucleotide to align for seq1 and k2 = position of the 1st nucleotide to align for seq2
			if (odd_line && odd_BLL)
				k1 = (line / 2) + ((bandLengthLeft+1) / 2) - j*8;
			else
				k1 = (line / 2) + (bandLengthLeft/2) - j*8;

			k2 = line - k1 - 1;

386 387
			nucs1.i = _MM_LOADU_SI128((const __m128i*)(seq1+l1-k1));
			nucs2.i = _MM_LOADU_SI128((const __m128i*)(seq2+k2));
388

389 390 391 392 393 394
//			if (print)
//			{
//				fprintf(stderr, "\nnucs, r %d, k1 = %d, k2 = %d\n", j, k1, k2);
//				printreg(nucs1.i);
//				printreg(nucs2.i);
//			}
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435

		// computing diagonal score :
			scores.i = _MM_AND_SI128(_MM_CMPEQ_EPI16(nucs1.i, nucs2.i), _MM_SET1_EPI16(1));
			current.i = _MM_ADDS_EPU16(p_diag_j->i, scores.i);

		// Computing alignment length

			l_ali_current.i = p_l_ali_diag_j->i;
			boolean_reg.i = _MM_CMPGT_EPI16(p_gap1_j->i, current.i);
			l_ali_current.i = _MM_OR_SI128(
								_MM_AND_SI128(p_l_ali_gap1_j->i, boolean_reg.i),
								_MM_ANDNOT_SI128(boolean_reg.i, l_ali_current.i));
			current.i = _MM_OR_SI128(
							_MM_AND_SI128(p_gap1_j->i, boolean_reg.i),
							_MM_ANDNOT_SI128(boolean_reg.i, current.i));
			boolean_reg.i = _MM_AND_SI128(
								_MM_CMPEQ_EPI16(p_gap1_j->i, current.i),
								_MM_CMPLT_EPI16(p_l_ali_gap1_j->i, l_ali_current.i));
			l_ali_current.i = _MM_OR_SI128(
								_MM_AND_SI128(p_l_ali_gap1_j->i, boolean_reg.i),
								_MM_ANDNOT_SI128(boolean_reg.i, l_ali_current.i));
			current.i = _MM_OR_SI128(
							_MM_AND_SI128(p_gap1_j->i, boolean_reg.i),
							_MM_ANDNOT_SI128(boolean_reg.i, current.i));
			boolean_reg.i = _MM_CMPGT_EPI16(p_gap2_j->i, current.i);
			l_ali_current.i = _MM_OR_SI128(
								_MM_AND_SI128(p_l_ali_gap2_j->i, boolean_reg.i),
								_MM_ANDNOT_SI128(boolean_reg.i, l_ali_current.i));
			current.i = _MM_OR_SI128(
							_MM_AND_SI128(p_gap2_j->i, boolean_reg.i),
							_MM_ANDNOT_SI128(boolean_reg.i, current.i));
			boolean_reg.i = _MM_AND_SI128(
								_MM_CMPEQ_EPI16(p_gap2_j->i, current.i),
								_MM_CMPLT_EPI16(p_l_ali_gap2_j->i, l_ali_current.i));
			l_ali_current.i = _MM_OR_SI128(
								_MM_AND_SI128(p_l_ali_gap2_j->i, boolean_reg.i),
								_MM_ANDNOT_SI128(boolean_reg.i, l_ali_current.i));
			current.i = _MM_OR_SI128(
							_MM_AND_SI128(p_gap2_j->i, boolean_reg.i),
							_MM_ANDNOT_SI128(boolean_reg.i, current.i));

436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
//			if (print)
//			{
//				fprintf(stderr, "\nline = %d", line);
//				fprintf(stderr, "\nDiag, r %d : ", j);
//				printreg((*(p_diag_j)).i);
//				fprintf(stderr, "Gap1      : ");
//				printreg((*(p_gap1_j)).i);
//				fprintf(stderr, "Gap2      : ");
//				printreg((*(p_gap2_j)).i);
//				fprintf(stderr, "current   : ");
//				printreg(current.i);
//				fprintf(stderr, "L ALI\nDiag  r %d : ", j);
//				printreg((*(p_l_ali_diag_j)).i);
//				fprintf(stderr, "Gap1      : ");
//				printreg((*(p_l_ali_gap1_j)).i);
//				fprintf(stderr, "Gap2      : ");
//				printreg((*(p_l_ali_gap2_j)).i);
//				fprintf(stderr, "current   : ");
//				printreg(l_ali_current.i);
//			}
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471

		// diag = gap1 and gap1 = current
			p_diag_j->i = p_gap1_j->i;
			p_gap1_j->i = current.i;

		// l_ali_diag = l_ali_gap1 and l_ali_gap1 = l_ali_current+1
			p_l_ali_diag_j->i = p_l_ali_gap1_j->i;
			p_l_ali_gap1_j->i = _MM_ADD_EPI16(l_ali_current.i, _MM_SET1_EPI16(1));
		}

		// shifts for gap2, to do only once all the registers of a line have been computed     Copier gap2 puis le charger depuis la copie?

		for (j=0; j < numberOfRegistersPerLine; j++)
		{
			if ((odd_line && even_BLL) || (even_line && odd_BLL))
			{
472 473
				p_gap2[j].i       = _MM_LOADU_SI128((const __m128i*)((p_gap1[j].s16)-1));
				p_l_ali_gap2[j].i = _MM_LOADU_SI128((const __m128i*)((p_l_ali_gap1[j].s16)-1));
474 475 476 477 478 479 480 481
				if (j == 0)
				{
					p_gap2[j].i = _MM_INSERT_EPI16(p_gap2[j].i, 0, 0);
					p_l_ali_gap2[j].i = _MM_INSERT_EPI16(p_l_ali_gap2[j].i, max, 0);
				}
			}
			else
			{
482 483
				p_gap2[j].i       = _MM_LOADU_SI128((const __m128i*)(p_gap1[j].s16+1));
				p_l_ali_gap2[j].i = _MM_LOADU_SI128((const __m128i*)(p_l_ali_gap1[j].s16+1));
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
				if (j == numberOfRegistersPerLine - 1)
				{
					p_gap2[j].i = _MM_INSERT_EPI16(p_gap2[j].i, 0, 7);
					p_l_ali_gap2[j].i = _MM_INSERT_EPI16(p_l_ali_gap2[j].i, max, 7);
				}
			}
		}
		// end shifts for gap2

	}

/*  /// Recovering LCS and alignment lengths  \\\  */

	// finding the location of the results in the registers :
	diff = l1-l2;
	if ((diff & 1) && odd_BLL)
		l_loc = (int) floor((double)(bandLengthLeft) / (double)2) - floor((double)(diff) / (double)2);
	else
		l_loc = (int) floor((double)(bandLengthLeft) / (double)2) - ceil((double)(diff) / (double)2);

	l_reg = (int)floor((double)l_loc/(double)8.0);
505 506 507 508

//	if (print)
//		fprintf(stderr, "\nl_reg = %d, l_loc = %d\n", l_reg, l_loc);

509 510 511 512 513 514 515 516 517 518 519
	l_loc = l_loc - l_reg*8;

	// extracting the results from the registers :
	*lcs_length = extract_reg(p_gap1[l_reg].i, l_loc);
	*ali_length = extract_reg(p_l_ali_gap1[l_reg].i, l_loc) - 1;

	// freeing the registers
	free(SSEregisters);
}


520
void sse_banded_align_just_lcs(int16_t* seq1, int16_t* seq2, int l1, int l2, int bandLengthLeft, int bandLengthTotal, int* lcs_length)
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
{
	register int j;
	int k1, k2;
	int diff;
	int l_reg, l_loc;
	int line;
	int numberOfRegistersPerLine;
	int numberOfRegistersFor3Lines;

	bool even_line;
	bool odd_line;
	bool even_BLL;
	bool odd_BLL;

	um128*  SSEregisters;
	um128*  p_diag;
	um128*  p_gap1;
	um128*  p_gap2;
	um128*  p_diag_j;
	um128*  p_gap1_j;
	um128*  p_gap2_j;
	um128   current;

	um128  nucs1;
	um128  nucs2;
	um128  scores;

	// Initialisations

	odd_BLL = bandLengthLeft & 1;
551
	even_BLL = !odd_BLL;
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594

	numberOfRegistersPerLine = bandLengthTotal / 8;
	numberOfRegistersFor3Lines   = 3 * numberOfRegistersPerLine;

	SSEregisters = malloc(numberOfRegistersFor3Lines * sizeof(um128));
	if (SSEregisters == NULL)
	{
		obi_set_errno(OBI_MALLOC_ERROR);
		obidebug(1, "\nError allocating memory for SSE registers for LCS alignment");
	}

	// preparer registres SSE

	for (j=0; j<numberOfRegistersFor3Lines; j++)
		(*(SSEregisters+j)).i       = _MM_SETZERO_SI128();

	p_diag    = SSEregisters;
	p_gap1    = SSEregisters+numberOfRegistersPerLine;
	p_gap2    = SSEregisters+2*numberOfRegistersPerLine;

	// Loop on diagonals = 'lines' :
	for (line=2; line <= l1+l2; line++)
	{
		odd_line = line & 1;
		even_line  = !odd_line;

		// loop on the registers of a line :
		for (j=0; j < numberOfRegistersPerLine; j++)
		{
			p_diag_j = p_diag+j;
			p_gap1_j = p_gap1+j;
			p_gap2_j = p_gap2+j;

		// comparing nucleotides for diagonal scores :

			// k1 = position of the 1st nucleotide to align for seq1 and k2 = position of the 1st nucleotide to align for seq2
			if (odd_line && odd_BLL)
				k1 = (line / 2) + ((bandLengthLeft+1) / 2) - j*8;
			else
				k1 = (line / 2) + (bandLengthLeft/2) - j*8;

			k2 = line - k1 - 1;

595 596
			nucs1.i = _MM_LOADU_SI128((const __m128i*)(seq1+l1-k1));
			nucs2.i = _MM_LOADU_SI128((const __m128i*)(seq2+k2));
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618

		// computing diagonal score :
			scores.i = _MM_AND_SI128(_MM_CMPEQ_EPI16(nucs1.i, nucs2.i), _MM_SET1_EPI16(1));
			current.i = _MM_ADDS_EPU16((*(p_diag_j)).i, scores.i);

		// current = max(gap1, current)
			current.i = _MM_MAX_EPI16((*(p_gap1_j)).i, current.i);

		// current  = max(gap2, current)
			current.i = _MM_MAX_EPI16((*(p_gap2_j)).i, current.i);

		// diag = gap1 and gap1 = current
			(*(p_diag_j)).i = (*(p_gap1_j)).i;
			(*(p_gap1_j)).i = current.i;
		}

		// shifts for gap2, to do only once all the registers of a line have been computed

			for (j=0; j < numberOfRegistersPerLine; j++)
			{
				if ((odd_line && even_BLL) || (even_line && odd_BLL))
				{
619
					(*(p_gap2+j)).i = _MM_LOADU_SI128((const __m128i*)(((*(p_gap1+j)).s16)-1));
620 621 622 623 624 625 626
					if (j == 0)
					{
						(*(p_gap2+j)).i = _MM_INSERT_EPI16((*(p_gap2+j)).i, 0, 0);
					}
				}
				else
				{
627
					(*(p_gap2+j)).i = _MM_LOADU_SI128((const __m128i*)(((*(p_gap1+j)).s16)+1));
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
					if (j == numberOfRegistersPerLine - 1)
					{
						(*(p_gap2+j)).i = _MM_INSERT_EPI16((*(p_gap2+j)).i, 0, 7);
					}
				}
			}
		// end shifts for gap2
	}

/*  /// Recovering LCS and alignment lengths  \\\  */

	// finding the location of the results in the registers :
	diff = l1-l2;
	if ((diff & 1) && odd_BLL)
		l_loc = (int) floor((double)(bandLengthLeft) / (double)2) - floor((double)(diff) / (double)2);
	else
		l_loc = (int) floor((double)(bandLengthLeft) / (double)2) - ceil((double)(diff) / (double)2);

	l_reg = (int)floor((double)l_loc/(double)8.0);
	//fprintf(stderr, "\nl_reg = %d, l_loc = %d\n", l_reg, l_loc);
	l_loc = l_loc - l_reg*8;

	// extracting LCS from the registers :
651
	*lcs_length = extract_reg((*(p_gap1+l_reg)).i, l_loc);
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677

	// freeing the registers
	free(SSEregisters);
}


int calculateLeftBandLength(int lmax, int LCSmin)
{
	return (lmax - LCSmin);
}


int calculateRightBandLength(int lmin, int LCSmin)
{
	return (lmin - LCSmin);
}


int calculateSSEBandLength(int bandLengthRight, int bandLengthLeft)
{
	int bandLengthTotal= (double)(bandLengthRight + bandLengthLeft) / 2.0 + 1.0;

	return (bandLengthTotal & (~ (int)7)) + (( bandLengthTotal & (int)7) ? 8:0); // Calcule le multiple de 8 superieur
}


678
int calculateSizeToAllocate(int maxLen, int LCSmin)
679 680 681 682 683 684
{
	int size;

	size = calculateLeftBandLength(maxLen, LCSmin);

	size *=  2;
685
	size  =  (size & (~ (int)7)) + ((size & (int)7) ? 8:0); // Closest greater 8 multiple
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
	size *=  3;
	size +=  16;

	return(size*sizeof(int16_t));
}


void iniSeq(int16_t* seq, int size, int16_t iniValue)
{
	int16_t* target = seq;
	int16_t* end = target + (size_t)size;

	for (; target < end; target++)
		*target = iniValue;
}


void putSeqInSeq(int16_t* seq, char* s, int l, bool reverse)
{
	int16_t *target=seq;
	int16_t *end = target + (size_t)l;
	char    *source=s;

	if (reverse)
		for (source=s + (size_t)l-1; target < end; target++, source--)
			*target=*source;
	else
		for (; target < end; source++,target++)
			*target=*source;
}


718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
void putBlobInSeq(int16_t* seq, Obi_blob_p b, int l, bool reverse)
{
	size_t  i;
	uint8_t shift;
	uint8_t mask;
	uint8_t nuc;

	int16_t* target = seq;
	int16_t* end = target + (size_t) l;

	if (reverse)
	{
		for (i = l-1; target < end; target++, i--)
		{
			shift = 6 - 2*(i % 4);
			mask = NUC_MASK_2B << shift;
			nuc = (b->value[i/4] & mask) >> shift;

			*target = (int16_t)nuc+1;	// +1 because nucleotide can't be == 0 (0 is a default value used to initialize some registers)
		}
	}
	else
	{
		for (i=0; target < end; target++, i++)
		{
			shift = 6 - 2*(i % 4);
			mask = NUC_MASK_2B << shift;
			nuc = (b->value[i/4] & mask) >> shift;

			*target = (int16_t)nuc+1;	// +1 because nucleotide can't be == 0 (0 is a default value used to initialize some registers)
		}
	}
}


753
void initializeAddressWithGaps(int16_t* address, int bandLengthTotal, int bandLengthLeft, int lmax)
754 755 756 757 758
{
	int i;
	int address_00, x_address_10, address_01, address_01_shifted;
	int numberOfRegistersPerLine;
	int bm;
759
	int value=INT16_MAX-lmax;
760

761
	numberOfRegistersPerLine = bandLengthTotal / 8;
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
	bm = bandLengthLeft%2;

	for (i=0; i < (3*numberOfRegistersPerLine*8); i++)
		address[i] = value;


	// 0,0 set to 1 and 0,1 and 1,0 set to 2

	address_00   = bandLengthLeft / 2;

	x_address_10 = address_00 + bm - 1;
	address_01   = numberOfRegistersPerLine*8 + x_address_10;

	address_01_shifted = numberOfRegistersPerLine*16 + address_00 - bm;

	// fill address_00, address_01,+1, address_01_shifted,+1

	address[address_00] = 1;
	address[address_01] = 2;
	address[address_01+1] = 2;
	address[address_01_shifted] = 2;
	address[address_01_shifted+1] = 2;
}


787
double sse_banded_lcs_align(int16_t* seq1, int16_t* seq2, int l1, int l2, bool normalize, int reference, bool similarity_mode, int16_t* address, int LCSmin, int* lcs_length, int* ali_length)
788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
{
	double id;
	int bandLengthRight, bandLengthLeft, bandLengthTotal;

	bandLengthLeft = calculateLeftBandLength(l1, LCSmin);
	bandLengthRight = calculateRightBandLength(l2, LCSmin);

//	fprintf(stderr, "\nBLL = %d, BLR = %d, LCSmin = %d\n", bandLengthLeft, bandLengthRight, LCSmin);

	bandLengthTotal = calculateSSEBandLength(bandLengthRight, bandLengthLeft);

//	fprintf(stderr, "\nBLT = %d\n", bandLengthTotal);

	if ((reference == ALILEN) && (normalize || !similarity_mode))
	{
		initializeAddressWithGaps(address, bandLengthTotal, bandLengthLeft, l1);
804
		sse_banded_align_lcs_and_ali_len(seq1, seq2, l1, l2, bandLengthLeft, bandLengthTotal, address, lcs_length, ali_length);
805 806
	}
	else
807 808 809
		sse_banded_align_just_lcs(seq1, seq2, l1, l2, bandLengthLeft, bandLengthTotal, lcs_length);

	id = (double) *lcs_length;
810 811 812

//	fprintf(stderr, "\nid before normalizations = %f", id);

813
	//fprintf(stderr, "\nlcs = %f, ali length = %d\n", id, ali_length);
814 815 816

	if (!similarity_mode && !normalize)
		switch(reference) {
817
			case ALILEN: id = *ali_length - id;
818 819 820 821 822 823 824 825 826
						break;
			case MAXLEN: id = l1 - id;
						break;
			case MINLEN: id = l2 - id;
		}

//	fprintf(stderr, "\n2>>> %f, %d\n", id, ali_length);
	if (normalize)
		switch(reference) {
827
			case ALILEN: id = id / (double) *ali_length;
828 829 830 831 832 833 834 835 836 837 838 839
						break;
			case MAXLEN: id = id / (double) l1;
						break;
			case MINLEN: id = id / (double) l2;
		}

//	fprintf(stderr, "\nid = %f\n", id);
	return(id);
}



840 841 842 843 844
/**********************************************************************
 *
 * 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
 *
 **********************************************************************/
845 846


847
int calculateLCSmin(int lmax, int lmin, double threshold, bool normalize, int reference, bool similarity_mode)
848 849 850 851 852 853 854 855
{
	int LCSmin;

	if (threshold > 0)
	{
		if (normalize)
		{
			if (reference == MINLEN)
856
				LCSmin = threshold*lmin;
857
			else 		// ref = maxlen or alilen
858
				LCSmin = threshold*lmax;
859 860 861 862
		}
		else if (similarity_mode)
			LCSmin = threshold;
		else if (reference == MINLEN) // not similarity_mode
863
			LCSmin = lmin - threshold;
864
		else	// not similarity_mode and ref = maxlen or alilen
865
			LCSmin = lmax - threshold;
866 867 868 869 870 871 872 873
	}
	else
		LCSmin = 0;

	return(LCSmin);
}


874
double generic_sse_banded_lcs_align(char* seq1, char* seq2, double threshold, bool normalize, int reference, bool similarity_mode, int* lcs_length, int* ali_length)
875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
{
	double   id;
	int      l1, l2;
	int      lmax, lmin;
	int      sizeToAllocateForBand, sizeToAllocateForSeqs;
	int	     maxBLL;
	int      LCSmin;
	int      shift;
	int16_t* address;
	int16_t* iseq1;
	int16_t* iseq2;

	address = NULL;

	l1 = strlen(seq1);
	l2 = strlen(seq2);

	if (l1 > l2)
	{
		lmax = l1;
		lmin = l2;
	}
	else
	{
		lmax = l2;
		lmin = l1;
	}

903 904 905 906 907 908 909 910
	// Check that the sequences are not greater than what can be aligned using the 16 bits registers (as the LCS and alignment lengths are kept on 16 bits)
	if (lmax > SHRT_MAX)
	{
		obi_set_errno(OBI_ALIGN_ERROR);
		obidebug(1, "\nError: can not align sequences longer than %d (as the LCS and alignment lengths are kept on 16 bits)", SHRT_MAX);
		return 0; 		// TODO DOUBLE_MIN to flag error
	}

911 912 913 914 915 916 917 918 919 920
	// If the score is expressed as a normalized distance, get the corresponding identity
	if (!similarity_mode && normalize)
		threshold = 1.0 - threshold;

	// Calculate the minimum LCS length corresponding to the threshold
	LCSmin = calculateLCSmin(lmax, lmin, threshold, normalize, reference, similarity_mode);

	// Allocate space for matrix band if the alignment length must be computed
	if ((reference == ALILEN) && (normalize || !similarity_mode)) // cases in which alignment length must be computed
	{
921
		sizeToAllocateForBand = calculateSizeToAllocate(lmax, LCSmin);
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
		address = obi_get_memory_aligned_on_16(sizeToAllocateForBand, &shift);
		if (address == NULL)
		{
			obi_set_errno(OBI_MALLOC_ERROR);
			obidebug(1, "\nError getting a memory address aligned on 16 bytes boundary");
			return 0;	// TODO DOUBLE_MIN
		}
	}

	// Allocate space for the int16_t arrays representing the sequences
	maxBLL = calculateLeftBandLength(lmax, LCSmin);
	sizeToAllocateForSeqs = 2*maxBLL+lmax;
	iseq1 = (int16_t*) malloc(sizeToAllocateForSeqs*sizeof(int16_t));
	iseq2 = (int16_t*) malloc(sizeToAllocateForSeqs*sizeof(int16_t));
	if ((iseq1 == NULL) || (iseq2 == NULL))
	{
		obi_set_errno(OBI_MALLOC_ERROR);
		obidebug(1, "\nError allocating memory for integer arrays to use in LCS alignment");
		return 0; 	// TODO DOUBLE_MIN
	}

	// Initialize the int arrays
	iniSeq(iseq1, (2*maxBLL)+lmax, 0);
	iniSeq(iseq2, (2*maxBLL)+lmax, 255);

	// Shift addresses to where the sequences have to be put
	iseq1 = iseq1+maxBLL;
	iseq2 = iseq2+maxBLL;

	// Put the DNA sequences in the int arrays. Longest sequence must be first argument of sse_align function
	if (l2 > l1)
	{
		putSeqInSeq(iseq1, seq2, l2, TRUE);
		putSeqInSeq(iseq2, seq1, l1, FALSE);
		// Compute alignment
957
		id = sse_banded_lcs_align(iseq1, iseq2, l2, l1, normalize, reference, similarity_mode, address, LCSmin, lcs_length, ali_length);
958 959 960 961 962 963
	}
	else
	{
		putSeqInSeq(iseq1, seq1, l1, TRUE);
		putSeqInSeq(iseq2, seq2, l2, FALSE);
		// Compute alignment
964
		id = sse_banded_lcs_align(iseq1, iseq2, l1, l2, normalize, reference, similarity_mode, address, LCSmin, lcs_length, ali_length);
965 966 967 968 969 970 971 972 973 974 975
	}

	// Free allocated elements
	if (address != NULL)
		free(address-shift);
	free(iseq1-maxBLL);
	free(iseq2-maxBLL);

	return(id);
}

976

977
double obiblob_sse_banded_lcs_align(Obi_blob_p seq1, Obi_blob_p seq2, double threshold, bool normalize, int reference, bool similarity_mode, int* lcs_length, int* ali_length)
978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
{
	double   id;
	int      l1, l2;
	int      lmax, lmin;
	int      sizeToAllocateForBand, sizeToAllocateForSeqs;
	int	     maxBLL;
	int      LCSmin;
	int      shift;
	int16_t* address;
	int16_t* iseq1;
	int16_t* iseq2;

	address = NULL;

	l1 = seq1->length_decoded_value;
	l2 = seq2->length_decoded_value;

	if (l1 > l2)
	{
		lmax = l1;
		lmin = l2;
	}
	else
	{
		lmax = l2;
		lmin = l1;
	}

1006 1007 1008 1009 1010 1011 1012 1013
	// Check that the sequences are not greater than what can be aligned using the 16 bits registers (as the LCS and alignment lengths are kept on 16 bits)
	if (lmax > SHRT_MAX)
	{
		obi_set_errno(OBI_ALIGN_ERROR);
		obidebug(1, "\nError: can not align sequences longer than %d (as the LCS and alignment lengths are kept on 16 bits)", SHRT_MAX);
		return 0; 		// TODO DOUBLE_MIN to flag error
	}

1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
	// If the score is expressed as a normalized distance, get the corresponding identity
	if (!similarity_mode && normalize)
		threshold = 1.0 - threshold;

	// Calculate the minimum LCS length corresponding to the threshold
	LCSmin = calculateLCSmin(lmax, lmin, threshold, normalize, reference, similarity_mode);

	// Allocate space for matrix band if the alignment length must be computed
	if ((reference == ALILEN) && (normalize || !similarity_mode)) // cases in which alignment length must be computed
	{
1024
		sizeToAllocateForBand = calculateSizeToAllocate(lmax, LCSmin);
1025 1026 1027 1028
		address = obi_get_memory_aligned_on_16(sizeToAllocateForBand, &shift);
		if (address == NULL)
		{
			obi_set_errno(OBI_MALLOC_ERROR);
1029 1030
			obidebug(1, "\nError getting a memory address aligned on a 16 bits boundary");
			return 0;	// TODO DOUBLE_MIN to flag error
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
		}
	}

	// Allocate space for the int16_t arrays representing the sequences
	maxBLL = calculateLeftBandLength(lmax, LCSmin);
	sizeToAllocateForSeqs = 2*maxBLL+lmax;
	iseq1 = (int16_t*) malloc(sizeToAllocateForSeqs*sizeof(int16_t));
	iseq2 = (int16_t*) malloc(sizeToAllocateForSeqs*sizeof(int16_t));
	if ((iseq1 == NULL) || (iseq2 == NULL))
	{
		obi_set_errno(OBI_MALLOC_ERROR);
		obidebug(1, "\nError allocating memory for integer arrays to use in LCS alignment");
		return 0; 	// TODO DOUBLE_MIN
	}

	// Initialize the int arrays
	iniSeq(iseq1, (2*maxBLL)+lmax, 0);
	iniSeq(iseq2, (2*maxBLL)+lmax, 255);

	// Shift addresses to where the sequences have to be put
	iseq1 = iseq1+maxBLL;
	iseq2 = iseq2+maxBLL;

	// Put the DNA sequences in the int arrays. Longest sequence must be first argument of sse_align function
	if (l2 > l1)
	{
		putBlobInSeq(iseq1, seq2, l2, TRUE);
		putBlobInSeq(iseq2, seq1, l1, FALSE);
		// Compute alignment
1060
		id = sse_banded_lcs_align(iseq1, iseq2, l2, l1, normalize, reference, similarity_mode, address, LCSmin, lcs_length, ali_length);
1061 1062 1063 1064 1065 1066
	}
	else
	{
		putBlobInSeq(iseq1, seq1, l1, TRUE);
		putBlobInSeq(iseq2, seq2, l2, FALSE);
		// Compute alignment
1067
		id = sse_banded_lcs_align(iseq1, iseq2, l1, l2, normalize, reference, similarity_mode, address, LCSmin, lcs_length, ali_length);
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
	}

	// Free allocated elements
	if (address != NULL)
		free(address-shift);
	free(iseq1-maxBLL);
	free(iseq2-maxBLL);

	return(id);
}