sort.c 10.5 KB
Newer Older
Eric Coissac committed
1 2 3 4 5 6 7 8 9 10 11 12
/*
 * sort.c
 *
 *  Created on: 14 sept. 2012
 *      Author: coissac
 */

#include "orgasm.h"
#include "_sse.h"

#include "debug.h"

13 14 15
#include <unistd.h>
#include <stdio.h>

16 17 18 19
// We used the heavyiest bit of the order1 index to
// store the sorted status of a read
// these macro are setup to manipulate this bit

Eric Coissac committed
20 21 22 23
#define SETSORTED(x)   ((x) | 0x80000000)
#define CLEARSORTED(x) ((x) & 0x7FFFFFFF)
#define GETSORTED(x)   ((x) & 0x80000000)

24 25 26 27 28 29 30

// fillOrdored function fill the two int arrays
// pointed by the members order1 and order2 with
// increasing int values from 1 to n (order1)
// and fill the order2 array in a way that link
// paired reads which are interleaved by the
// loadpair function
Eric Coissac committed
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
void fillOrdored(buffer_t *buffer)
{
	um128 counter;
	um128 pair;
	uint32_t *index;
	uint32_t *endex;
	uint32_t *index2;

	index  = buffer->order1;
	index2 = buffer->order2;
	endex  = index + buffer->readCount;

	counter.u32[0]=0;
	counter.u32[1]=1;
	counter.u32[2]=2;
	counter.u32[3]=3;

	pair.u32[0]=1;
	pair.u32[1]=0;
	pair.u32[2]=3;
	pair.u32[3]=2;


	for (; index < (endex-3) ; index+=4,index2+=4)
	{
      _MM_STORE_SI128((__m128i*)index,counter.i);
      counter.i=_MM_ADD_EPI32(counter.i,_MM_SET1_EPI32(4));

      _MM_STORE_SI128((__m128i*)index2,pair.i);
      pair.i=_MM_ADD_EPI32(pair.i,_MM_SET1_EPI32(4));

      //      DEBUG("index : %d  %d:%d:%d:%d",index-(buffer->order),
//    		        index[0],index[1],index[2],index[3]);
	}

	for (; index < endex ; index++,index2++)
	{
		*index = *(index-1)+1;
		*index2= (*index ^ 0x1);
//		DEBUG("index : %d  %d",index-(buffer->order),
//  		        index[0]);

	}

}

77 78 79 80 81 82
// partialSortBuffer, sort lexicographically the reads suffix
// stored in buffer from the position [start;stop[.
// for this function reads are indexed from 0 to n-1 with
// n the read count.
//
// This function is recursive
Eric Coissac committed
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104

void partialSortBuffer(buffer_t *buffer,
		               uint32_t start, uint32_t stop,
		               uint32_t shift,
		               uint32_t nextprint)
{
	uint32_t wordStat[256];
	uint32_t *index = buffer->order1 + start;
	uint32_t *endex = buffer->order1 + stop;

	uint8_t  word;
	uint32_t i;
	uint32_t swap;
	uint32_t pairswap;
	uint32_t next;
	uint32_t first;
	uint32_t pair;
	uint32_t *pairp;
	uint32_t *swapp;
	uint32_t cumsum=start;
	uint32_t backtolastswap=FALSE;

105 106 107

	// Just print some stats on the sorting progress

Eric Coissac committed
108 109
	if (shift==1 && start > nextprint)
	{
110 111
		if (isatty(fileno(stderr)))
			fprintf(stderr,"%9d sequences sorted\r",start);
Eric Coissac committed
112 113 114
		nextprint=start;
	}

115 116 117
	// If we sort just one sequence or a suffix of length=0
	// this is finnished

Eric Coissac committed
118 119 120 121 122 123 124 125 126 127 128 129
	if ((stop - start)<=1 || shift==buffer->recordSize)
		return;

	// we clear all word occurrences

	bzero((void *)wordStat, 256 * sizeof(uint32_t));

	// we count occurrences of each word in one pass

	for (; index < endex; index++)
		wordStat[((uint8_t*)(buffer->records))[*index * buffer->recordSize + shift]]++;

130 131
    // And we compute the cumulative sum of ocurences

Eric Coissac committed
132 133 134 135 136 137 138 139 140 141 142
	for (i=0; i < 256; i++)
	{
		swap=wordStat[i];
		wordStat[i]=cumsum;
		cumsum+=swap;
	}

	// Do the card sorting by itself

	for (i=start; i < stop; i++)
	{
143
		// I skip already ordored sequences
Eric Coissac committed
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
		while (i < stop && GETSORTED(buffer->order1[i]))
			i++;

		// No more cells to sort
		if (i==stop) continue;

		// next contains the id of the next sequence to sort
		first  = buffer->order1[i];
		next   = first;
		// pair contains the id of the paired sequence
		pair  = buffer->order2[i];

		do
		{
			// this is the next word to sort
			word  = ((uint8_t*)(buffer->records))[next * buffer->recordSize + shift];


			// Now I know where I'll store the paired read
			//    See below for understanding this comment
			if (backtolastswap)
			{
				backtolastswap=FALSE;
				buffer->order2[pair]=wordStat[word];

			}

			// I compute the destination for this word
			swapp = buffer->order1 + wordStat[word];
			pairp = buffer->order2 + wordStat[word];

			// And I save the value previously stored at these locations.
			swap  = *swapp;
			pairswap = *pairp;

			// I save the new sequence id and set the SORTED flag

			*swapp= SETSORTED(next);


			// I save the pair info

			if (pair!=wordStat[word])
			{
				// in this case we are not swapping paired reads

				// I conserve in the new place the next pair information
				*pairp= pair;

				// I store for the paired reads the new position of its pair
				buffer->order2[pair]=wordStat[word];
			}
			else
			{
				// In this case I'm swapping to paired reads

				// I'm moving the next pair so I don't know yet where il will be placed
				*pairp= 0xFFFFFFFF;

				// I remember this strange status
				backtolastswap=TRUE;
			}

			// I initialize next for the following loop cycle
			next  = swap;

			// same for pair with a special case if we are swaping paired reads
			if (pair!=wordStat[word])
				pair = pairswap;

			wordStat[word]++;

		} while (next!=first);

	}

220
	// Clear all the sorted status
Eric Coissac committed
221 222 223
	for (i=start; i < stop; i++)
		buffer->order1[i]&=0x7FFFFFFF;

224
	// Run recurcively the algorithm on each sub set
Eric Coissac committed
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 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 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 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 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
	for (i=0; i < 256; i++)
	{
		if (i>0 && wordStat[i] < wordStat[i-1])
			wordStat[i]=wordStat[i-1];

		stop=wordStat[i];
		if (stop - start > 1)
			partialSortBuffer(buffer,start,stop,shift+1,nextprint);
		start=stop;
	}

}


void sortBuffer(buffer_t *buffer)
{
	fprintf(stderr,"\nSorting reads...\n\n");

	fillOrdored(buffer);
	partialSortBuffer(buffer,0,buffer->readCount,0,DISPLAYSTEP);

	fprintf(stderr,"%9zd sequences sorted\n",buffer->readCount);
}


void countLetterAt(buffer_t *buffer,uint32_t pos)
{
	uint32_t shift;
	uint32_t inshift;
	uint8_t  mask;
	uint8_t  *record;
	int32_t  *count=buffer->letterCount;
	uint32_t i;

	count[0]=count[1]=count[2]=count[3]=0;

	shift  = pos >> 2;
	inshift= (3 - (pos & 3)) * 2;
	mask   = (1 << inshift) | (1 << (inshift+1));

	for(record = (uint8_t*)(buffer->records) + shift, i=0;
		i < buffer->readCount;
		i++, record+=buffer->recordSize)
		count[(*record & mask) >> inshift]++;

	// DEBUG("At position %9d : A=%9d C=%9d T=%9d G=%9d",pos,count[0],count[1],count[2],count[3]);
}

int8_t cmpSuffix(buffer_t *buffer,uint32_t r1,uint32_t r2,uint32_t pos)
{
	uint32_t shift;
	uint8_t  mask;
	uint8_t  *pr1;
	uint8_t  *pr2;
	uint8_t  vr1=0;
	uint8_t  vr2=0;

	shift  = pos >> 2;
	mask= (1 << ((4 - (pos & 3)) * 2))-1;

	// DEBUG("pos : %d mask : %d,%x",pos,shift,mask);

	pr1 = ((uint8_t*)(buffer->records)) + shift + buffer->recordSize * r1;
	pr2 = ((uint8_t*)(buffer->records)) + shift + buffer->recordSize * r2;

	vr1 = *pr1 & mask;
	vr2 = *pr2 & mask;

	while(shift < buffer->recordSize  && vr1==vr2)
	{
	//	DEBUG("Shift:%d  %d  %d",shift,vr1,vr2);

		shift++;
		pr1++,
		pr2++,

		vr1 = *pr1;
		vr2 = *pr2;
	}

	return (vr1==vr2) ? 0 : (vr1 < vr2) ? -1:1;

}

uint32_t minSuffix(buffer_t *buffer,uint32_t pos)
{
	int32_t  mini;
	uint32_t current;
	int32_t  *count=buffer->letterCount;
	uint32_t *order = buffer->order1;

	mini=0;

	if (count[1]>=0)
	{
		if (count[mini] < 0)
			mini= 1;
		else
		{
			current= 1;
			// DEBUG("1 : mini=%d  current=%d (%d)",
			//            mini,
			//            current,
			//            cmpSuffix(buffer,order[count[mini]],order[count[current]],pos));
			if (cmpSuffix(buffer,order[count[mini]],order[count[current]],pos) > 0)
				mini = current;
		}
	}

	if (count[2]>=0)
	{
		if (count[mini] < 0)
			mini= 2;
		else
		{
			current= 2;
			// DEBUG("2 : mini=%d  current=%d (%d)",mini,current,cmpSuffix(buffer,order[count[mini]],order[count[current]],pos));
			if (cmpSuffix(buffer,order[count[mini]],order[count[current]],pos) > 0)
				mini = current;
		}
	}

	if (count[3]>=0)
	{
		if (count[mini] < 0)
			mini= 3;
		else
		{
			current= 3;
			// DEBUG("3 : mini=%d  current=%d (%d)",mini,current,cmpSuffix(buffer,order[count[mini]],order[count[current]],pos));
			if (cmpSuffix(buffer,order[count[mini]],order[count[current]],pos) > 0)
				mini = current;
		}
	}

	// DEBUG("4 : seqid=%d  current=%d (%d)",order[count[mini]],mini,cmpSuffix(buffer,order[count[mini]],order[count[current]],pos));
	return mini;
}

void sortSuffix(buffer_t *buffer,uint32_t pos)
{
	uint32_t nextmini;
	int32_t count[4];
	int32_t  *cumsum = buffer->letterCount;
	int32_t  max=0;
	int32_t  i;
	uint32_t nextprint=DISPLAYSTEP;

	fprintf(stderr,"\nSorting suffix @ %d...\n\n",pos);


	countLetterAt(buffer,pos);
	countLetterAt(buffer,pos-1);

	count[0]=cumsum[0];
	cumsum[0]= (count[0]) ? max:-1;
	max+=count[0];

	count[1]=cumsum[1];
	cumsum[1]= (count[1]) ? max:-1;
	max+=count[1];

	count[2]=cumsum[2];
	cumsum[2]= (count[2]) ? max:-1;
	max+=count[2];

	count[3]=cumsum[3];
	cumsum[3]= (count[3]) ? max:-1;

	// DEBUG("Cumsum    @ %9d : A=%9d C=%9d T=%9d G=%9d",pos,cumsum[0],cumsum[1],cumsum[2],cumsum[3]);


	for (i=0; i < (int32_t)buffer->readCount; i++)
	{
		nextmini = minSuffix(buffer,pos);
		buffer->order2[i]=buffer->order1[buffer->letterCount[nextmini]];
		cumsum[nextmini]++;
		count[nextmini]--;
		if (count[nextmini]==0)
			cumsum[nextmini]=-1;

		if (i > nextprint)
		{
408 409
			if (isatty(fileno(stderr)))
				fprintf(stderr,"%9d suffixes sorted\r",nextprint);
Eric Coissac committed
410 411 412 413 414 415 416 417 418 419 420
			nextprint+=DISPLAYSTEP;
		}

	}

	fprintf(stderr,"%9d suffixes sorted\n",i);


	// DEBUG("Minimum read @ pos = %4d is %9d",pos,nextmini);
}

421 422 423 424
// indexForward function fill the int array pointed by the member index1
// of the structure buffer with a hash index of the reads based on the
// eight first bases of the sequences

Eric Coissac committed
425 426 427
void indexForward(buffer_t *buffer)
{
	int32_t i;
Eric Coissac committed
428
	uint16_t hash;
Eric Coissac committed
429 430 431 432 433 434 435 436 437 438
	uint32_t swap;
	uint32_t cumsum=0;
	int32_t imax = 1 << 16;

	bzero((void *)(buffer->index1), imax * sizeof(uint32_t));

	for (i=0; i < buffer->readCount; i++)
	{
		hash=*((uint16_t*)(buffer->records + i * buffer->recordSize));
#ifdef LITTLE_END
Eric Coissac committed
439
		hash = ((hash & 0xFF) << 8) | (hash >> 8);
Eric Coissac committed
440 441 442 443 444 445 446 447 448 449 450 451
#endif
		buffer->index1[hash]++;
	}

	for (i=0; i < imax; i++)
	{
		swap=buffer->index1[i];
		buffer->index1[i]=cumsum;
		cumsum+=swap;
	}
}

452 453 454 455 456
// indexReverse function fill the int array pointed by the member index2
// of the structure buffer with a hash index of the reads based on the
// eight first bases of the reverse complement of the sequences


Eric Coissac committed
457 458 459
void indexReverse(buffer_t *buffer)
{
	int32_t i;
Eric Coissac committed
460
	uint16_t hash;
Eric Coissac committed
461 462 463 464 465 466 467 468 469 470 471
	uint32_t swap;
	uint32_t cumsum=0;
	int32_t imax = 1 << 16;


	bzero((void *)(buffer->index2), imax * sizeof(uint32_t));

	for (i=0; i < buffer->readCount; i++)
	{
		hash = *((uint16_t*)(buffer->records + i * buffer->recordSize + CODELENGTH(buffer->readSize))-1);
#ifdef LITTLE_END
Eric Coissac committed
472
		hash = complement4nuc[hash & 0x00FF] | (complement4nuc[(hash >> 8) & 0x00FF] << 8);
Eric Coissac committed
473
#else
Eric Coissac committed
474
		hash = (complement4nuc[hash & 0x00FF] << 8) | complement4nuc[(hash >> 8) & 0x00FF];
Eric Coissac committed
475 476 477 478 479 480 481 482 483 484 485
#endif
		buffer->index2[hash]++;
	}

	for (i=0; i < imax; i++)
	{
		swap=buffer->index2[i];
		buffer->index2[i]=cumsum;
		cumsum+=swap;
	}
}