Esempio n. 1
0
//---------- Begin of function Weather::init_date ----------//
//
void Weather::init_date(short year, short month, short day, short latitude, int quakeFreq)
{
	// ----------- initialize random seed
	seed = 2*year+1;
	(void) rand_seed(10);

	// ----------- calculate season_phase from month, day ------------//
	season_phase = (short) ( month * 30.4 + day);
	season_phase = (season_phase + 365 - 98) % 365;	// 7th Mar becomes 0

	// ----------- random number to earthquake -----------//
	quake_frequency = quakeFreq;
	day_to_quake = quakeFreq + rand_seed(quakeFreq);

	// ----------- determine avg_temp and temp_amp from latitude
	double angle = latitude * M_PI / 180.0;
	avg_temp = (short)( 35.0 - fabs(latitude / 90.0 * 40.0));
	temp_amp = (short)( 17.0 * sin(angle));	// negative for South Hemisphere

	// ----------- determine cloud ----------- //
	cur_cloud_str = rand_seed(4);
	cur_cloud_len = 5 + rand_seed(5);
	cur_cloud_type = 0;

	// ----------- determine wind ---------------//
	wind_dir = rand_seed(360);
	wind_spd = 10;
	high_wind_day = 0;
	windy_speed = 0;

	tornado_count = 1;

}
Esempio n. 2
0
/*-------------------------------------------------------------------*/
void setup() {
   /* Initialise LED and motors */
   set_color(RGB(0,0,0));
   set_motors(0,0);

   /* Initialise random seed */
   uint8_t seed = rand_hard();
   rand_seed(seed);

   /* Initialise the list of words ready for message sending. The word
      index is contained in the first payload byte, while the
      follwoing three bytes contain the randomly-chosen word */
   int i;
   for( i = 0; i < num_words; i++ ) {
      words[i].data[0] = i;
      words[i].type    = NORMAL;
      words[i].crc     = message_crc(&words[i]);
   }

   /* Initialise motion variables */
   set_motion( FORWARD );
   last_motion_ticks = rand_soft() % max_straight_ticks + 1;

   /* Initialise mng variables */
   last_broadcast_ticks = rand_soft() % max_broadcast_ticks + 1;
}
Esempio n. 3
0
void init_rand()
{
//	rand_seed(current_time-s1, current_time, current_time+s3);
//	rand_seed(s1, s2, s3);
	rand_seed(randseed(),randseed(),randseed());
	mudlog("Random number generator initialized.");
}
Esempio n. 4
0
//-------- Begin of function Lightning::move_particle ----------//
void Lightning::move_particle()
{
	// determine attraction
	double attractionDist = dist(destx-x, desty-y);
	if( attractionDist < v)
		return;
	double aX = a * (destx-x) / attractionDist;
	double aY = a * (desty-y) / attractionDist;

	// determine random component
	double attractionAngle = atan2( desty-y, destx-x);
	double randomAngle = ((rand_seed() & 255)/128.0-1.0)*wide+ attractionAngle;
	double rX = r * cos(randomAngle);
	double rY = r * sin(randomAngle);

	// total
	double tX = aX + rX;
	double tY = aY + rY;
	double distt = dist(tX, tY);

	// move x and y, along tX, tY but the magnitude is v
	if( distt > 0)
	{
		x += v * tX / distt;
		y += v * tY / distt;
	}

	steps ++;
	update_parameter();
}
Esempio n. 5
0
File: ds.c Progetto: choupi/MLFounds
int main()
{
    int i, j, k, mk, s, N=20;
    float x[200];
    float tx[200];
    int y[200];
    float theta, mt;
    rand_seed();

    for(i=0;i<N;i++) {
        x[i]=rand()%MODN*2/(float)MODN-1;
	y[i]=SIGN(x[i]);
	if(rand()%5==0) y[i]*=-1;
	tx[i]=x[i];
    }
    qsort(tx, N, sizeof(float), cmp_f);
    //for(i=0;i<N;i++) printf("%f %d\n", x[i], y[i]);
    //for(i=0;i<N;i++) printf("%f\n", tx[i]);

    mk=0;
    for(i=0;i<N-1;i++) {
        theta=(tx[i+1]+tx[i])/2;
	k=0;
	for(j=0;j<N;j++) 
	    if(SIGN(x[j]-theta)*y[j] >0) k++;
	if(k>mk) { mt=theta; mk=k; s=1; }
	else if(N-k>mk) { mt=theta; mk=N-k; s=-1; }
    }
    //printf("%f %d %d\n", mt, s, mk);
    printf("%f %f\n", 1-(float)mk/N, 0.5+0.3*s*(fabs(mt)-1));
}
Esempio n. 6
0
int main()
{
    int i, j, k, mk, s, N=20;
    float x[200];
    float tx[200];
    int y[200];
    float theta, mt;
    rand_seed();

    while(EOF!=scanf(" %f %d", x+i,y+i)) {
        i++;
    }
    N=i;

    for(i=0;i<N;i++) tx[i]=x[i];
    qsort(tx, N, sizeof(float), cmp_f);
    //for(i=0;i<N;i++) printf("%f %d\n", x[i], y[i]);
    //for(i=0;i<N;i++) printf("%f\n", tx[i]);

    mk=0;
    for(i=0;i<N-1;i++) {
        theta=(tx[i+1]+tx[i])/2;
	k=0;
	for(j=0;j<N;j++) 
	    if(SIGN(x[j]-theta)*y[j] >0) k++;
	if(k>mk) { mt=theta; mk=k; s=1; }
	else if(N-k>mk) { mt=theta; mk=N-k; s=-1; }
    }
    printf("%f %d %d\n", mt, s, mk);
    printf("%f %f\n", 1-(float)mk/N, 0.5+0.3*s*(fabs(mt)-1));
}
Esempio n. 7
0
// ------ Begin of function SnowGroundArray::has_snow -------//
int SnowGroundArray::has_snow(short x, short y)
{
	seed = (snow_pattern << 16) + (x+y+257)*(5*x+y+1);
	(void) rand_seed();
	long height = (rand_seed() & 0xffff) - (0xffff - snow_thick);
	if( height <= 0)
		return 0;

	int snowGrade = height / SNOW_GRADE_FACTOR;
	SnowInfo *snowInfo = snow_res[snow_res.rand_root(rand_seed()/4)];
	for( ; snowGrade > 0; --snowGrade)
	{
		snowInfo = snowInfo->rand_next_ptr(rand_seed()/4);
	}
	return snowInfo->snow_map_id;
}
Esempio n. 8
0
unsigned int rand_index(int top) {

  if ( seed == 0 ) {
    /* seed the generator */
    rand_seed(0);
  }

  return (unsigned int)((1.0+top)*rand()/(RAND_MAX+1.0));
}
Esempio n. 9
0
int main(int argc, char *argv[]) {
    QApplication a(argc, argv);

    rand_seed();     // seed random number generator

    MainWindow view; // create main window
    view.show();     // display main window

    return a.exec(); // start Qt event loop
}
Esempio n. 10
0
int main() {
	cout << HEAD << endl << endl;
	rand_seed();
	vector<int> v(5);
	for (int i = 0; i < v.size(); i++)
		v[i] = rand_int(1, 100);
	print(v);
	selection_sort(v);
	print(v);
	return 0;
}
Esempio n. 11
0
int
test_base_bitset(const char* param) {
    rand_seed((uint32_t)time(NULL));

    // bit create 
    int size = param ? atoi(param) : rand() % 1024;
    bit_t* bit = bit_create(size);
    if (!bit) {
        fprintf(stderr, "bit create fail\n");
        return -1;
    }

    // bit set 
    int test_size = (size >> 1);
    for (int i = 0; i < test_size; ++ i) {
        bit_set(bit, i);
    }

    // bit is set 
    for (int i = 0; i < size; ++ i) {
        if (i < test_size && bit_isset(bit, i)) {
            fprintf(stderr, "bit-set error\n");
            bit_release(bit);
            return -1;
        }
        if (i >= test_size && bit_isset(bit, i) == 0) {
            fprintf(stderr, "bit-set error\n");
            bit_release(bit);
            return -1;
        }
    }

    // bit count
    if (bit_count(bit) != test_size) {
        fprintf(stderr, "bit-count = %d error\n", bit_count(bit));
        bit_release(bit);
        return -1;
    }

    // bit reset -> bit count
    for (int i = 0; i < test_size; ++ i) {
        bit_reset(bit, i);
    }
    if (bit_count(bit) != 0) {
        fprintf(stderr, "bit-count error\n");
        bit_release(bit);
        return -1;
    }

    bit_release(bit);
    return 0;
}
Esempio n. 12
0
int main()
{  
   rand_seed();
   vector<int> v(20);
   for (int i = 0; i < v.size(); i++)
      v[i] = rand_int(1, 100);
   print(v);
   cout << "Enter number to search for: ";
   int n;
   cin >> n;
   int j = linear_search(v, n);
   cout << "Found in position " << j << "\n";
   return 0;
}
Esempio n. 13
0
static void *prob_new(void)
{
    t_prob *x = (t_prob *)pd_new(prob_class);
    x->x_translist = 0;
    x->x_state = 0;
    x->x_default = 0;
    x->x_embedmode = 0;  /* CHECKED */
    x->x_silent = 0;
    rand_seed(&x->x_seed, 0);
    outlet_new((t_object *)x, &s_float);
    x->x_bangout = outlet_new((t_object *)x, &s_bang);
    x->x_filehandle = hammerfile_new((t_pd *)x, prob_embedhook, 0, 0, 0);
    return (x);
}
Esempio n. 14
0
void _benchmark_bigmatrix()
{
	int round=1000000;
	unsigned seed=rand_seed();
	BENCHMARK_MATRIX rec1, rec2, rec3;
	rec1.round=round;
	rec2.round=round;
	rec3.round=round;

	// add
#ifdef BENCHMARK_MATRIX_ADD
	mrand_init(seed);
	_bm_matrix_op<wyc::xmatrix<float,R,C>,R,C,matrix_add<wyc::xmatrix<float,R,C> > >(round,rec1.tmatadd);
	mrand_init(seed);
	_bm_dynmat_op<Eigen::MatrixXf,R,C,matrix_add<Eigen::MatrixXf> >(round,rec2.tmatadd);
	mrand_init(seed);
	_bm_dynmat_op<arma::Mat<float>,R,C,matrix_add<arma::Mat<float> > >(round,rec3.tmatadd);
#endif // BENCHMARK_MATRIX_ADD
	// mul
#ifdef BENCHMARK_MATRIX_MUL
	mrand_init(seed);
	_bm_matrix_op<wyc::xmatrix<float,R,C>,R,C,matrix_mul<wyc::xmatrix<float,R,C> > >(round,rec1.tmatmul);
	mrand_init(seed);
	_bm_dynmat_op<Eigen::MatrixXf,R,C,matrix_mul<Eigen::MatrixXf> >(round,rec2.tmatmul);
	mrand_init(seed);
	_bm_dynmat_op<arma::Mat<float>,R,C,matrix_mul<arma::Mat<float> > >(round,rec3.tmatmul);
#endif // BENCHMARK_MATRIX_MUL
	// inverse
#ifdef BENCHMARK_MATRIX_INV
	mrand_init(seed);
	_bm_matrix_op<wyc::xmatrix<float,R,C>,R,C,wyc_inverse<wyc::xmatrix<float,R,C> > >(round,rec1.tmatinv);
	mrand_init(seed);
	_bm_dynmat_op<Eigen::MatrixXf,R,C,eigen_inverse<Eigen::MatrixXf> >(round,rec2.tmatinv);
//	mrand_init(seed);
//	_bm_dynmat_op<arma::Mat<float>,R,C,arma_inverse<arma::Mat<float> > >(round,rec3.tmatinv);
#endif // BENCHMARK_MATRIX_INV

	printf("//-------------------------\n");
	printf("// matrix %dx%d benchmark\n",R,C);
	printf("//-------------------------\n");
	rec1.report("wyc matrix");
	rec2.report("eigne matrix");
	rec3.report("arma matrix");
	printf("\nbenchmark is done\n");
}
Esempio n. 15
0
int main(void)
{
	uint8_t addr;

    hal_sysinit();
    hal_watchdog_enable();
    addr = hal_get_addr(); // device address from DIP switches
    addr |= 0x00; // add the device class

    uart_init(addr); // timeout affects collision recovery, use address
    rand_seed(((uint16_t)addr << 8) | (uint16_t)addr);
	timer_init(switch_tick, addr); // init with system-wide unique value
	phc_init(input_cmd_start, input_payload, input_cmd_end);

	input_init(addr);
	input_mainloop();
	return 0; // we won't get here
}
Esempio n. 16
0
HashTable *squeal_ht_init()
{
    HashTable *ht;
    int i = 0;
    ht = (HashTable *) malloc(sizeof(HashTable) + sizeof(squeal_ht_record) * DEFAULT_HASH_SIZE);

    if (ht == NULL) {
        fprintf(stderr, "squeal_ht_init: unable to allocate hashtable");
        return NULL;
    }

    ht->ma.mask = DEFAULT_HASH_SIZE - 1;
    ht->ma.filled = 0;
    ht->ma.used = 0;
    ht->pos = 0;
    ht->seed = rand_seed(100);

    /* Allocate the initial slots */
    for (; i < DEFAULT_HASH_SIZE; i++) {
        ht->rec[i] = (squeal_ht_record *) malloc(sizeof(squeal_ht_record));

        if (ht->rec[i] == NULL) {
            fprintf(stderr, "squeal_ht_init: Unable to allocate record");

            int x = 0;

            for (; x < i; x++) {
                free(ht->rec[x]);
            }

            free(ht);

            return NULL;
        }

        ht->rec[i]->id = (uint32_t) i;
        ht->rec[i]->key = NULL;
        ht->rec[i]->v.sval = NULL;
        ht->rec[i]->v.ptr = NULL;
        ht->rec[i]->is_used = 0;
    }

    return ht;
}
Esempio n. 17
0
//-------- Begin of function Lightning::init ----------//
void Lightning::init(double fromX, double fromY, double toX, double toY,
							char energy)
{
	x = fromX;
	y = fromY;
	destx = toX;
	desty = toY;
	energy_level = energy;
	v = 6.0;
	expect_steps = (int)( dist(desty-y, destx-x) / v * 1.2);
	if( expect_steps < 2 )
		expect_steps = 2;
	steps = 0;
	a0 = a = 8.0;
	r0 = r = 8.0 * a;
	wide = PI / 4;
	seed = (unsigned)(fromX + fromY + toX + toY) | 1;
	(void) rand_seed();
}
Esempio n. 18
0
result_t core_init(uint flags)
{
    if (BIT_CHECK(flags, CORE_INIT_CRASHDUMP))  {
        if (IS_FAIL(crash_init()))
            return RET_FAIL;
    }

    if (IS_FAIL(mem_init(BIT_CHECK(flags, CORE_INIT_TRACEMEM))))
        return RET_FAIL;

    if (IS_FAIL(log_init()))
        return RET_FAIL;

    if (BIT_CHECK(flags, CORE_INIT_ERRORS)) {
        if (IS_FAIL(err_init()))
            return RET_FAIL;
    }

    rand_seed();

    if (BIT_CHECK(flags, CORE_INIT_JSON))   {
        if (IS_FAIL(json_init()))
            return RET_FAIL;
    }

    if (BIT_CHECK(flags, CORE_INIT_FILEIO)) {
        if (IS_FAIL(fio_initmgr()))
            return RET_FAIL;
    }

    if (BIT_CHECK(flags, CORE_INIT_TIMER)) {
        if (IS_FAIL(timer_initmgr()))
            return RET_FAIL;
    }

    if (BIT_CHECK(flags, CORE_INIT_SOCKET)) {
        if (IS_FAIL(sock_init()))
            return RET_FAIL;
    }

    return RET_OK;
}
Esempio n. 19
0
int
test_base_slist(const char* param) {
    struct slist_t* sl = slist_create();
    if (!sl) {
        fprintf(stderr, "slist create fail\n");
        return -1;
    }

    rand_seed(time(NULL));
    int loop = param ? atoi(param) : 32;
    int data[loop];
    for (int i = 0; i < loop; ++ i) {
        data[i] = (int)(rand_gen()) % loop;
        int res = slist_push_front(sl, &data[i]);
        CHECK(sl, res == 0, "slist push front fail");

        res = slist_push_back(sl, &data[i]);
        CHECK(sl, res == 0, "slist push back fail");
    }

    CHECK(sl, slist_size(sl) == 2 * loop, "slist size fail");

    for (int i = loop - 1; i >= 0; -- i) {
        int res = slist_find(sl, &data[i]);
        CHECK(sl, res == 0, "slist find fail");

        void* p = slist_pop_front(sl);
        CHECK(sl, p == &data[i], "slist pop front fail");

        p = slist_pop_back(sl);
        CHECK(sl, p == &data[i], "slist pop back fail");

        res = slist_find(sl, &data[i]);
        CHECK(sl, res < 0, "slist find fail");
    }

    CHECK(sl, slist_size(sl) == 0, "slist size fail");

    slist_release(sl);
    return 0;
}
Esempio n. 20
0
void *randomvals_new()
{
    t_randomvals *x = (t_randomvals *)object_alloc(this_class);

	t_atom list_atoms[3];
#ifdef MSP_VERSION
    dsp_setup((t_pxobject *)x, 1);
	outlet_new((t_object *)x, "signal");
#else
	x->the_outlet = floatout(x);
#endif
	
	rand_seed(&x->gen);
	
	atom_setfloat(list_atoms + 0, 0.5);
	atom_setfloat(list_atoms + 1, 1.);
	atom_setfloat(list_atoms + 2, 1.);	
	
	randomvals_list(x, gensym("list"), 3, list_atoms);
	
	return (x);
}
Esempio n. 21
0
int main()
{
    rand_seed();
    cout << "Enter vector size: ";
    int n;
    cin >> n;

    Time before;
    const int ITERATIONS = 1000;
    for (int i = 1; i <= ITERATIONS; i++)
    {
        vector<int> v(n);
        for (int i = 0; i < v.size(); i++)
            v[i] = rand_int(1, 100);
        merge_sort(v, 0, v.size() - 1);
    }
    Time after;

    cout << "Average elapsed time = "
         << after.seconds_from(before) * 1.0 / ITERATIONS << " seconds\n";
    return 0;
}
Esempio n. 22
0
static void initialize (void)
{
  int i, j, k, w;
  char b;
  FILE *f;

  if (!initialized)
  {
    f = fopen(RAND_FILE,"rb");
    
    if (f==NULL)
    { fprintf(stderr,"Can't open file of random numbers (%s)\n",RAND_FILE);
      exit(1);
    }

    for (i = 0; i<N_tables; i++)
    { for (j = 0; j<Table_size; j++)
      { w = 0;
        for (k = 0; k<4; k++)
        { if (fread(&b,1,1,f)!=1)
          { fprintf(stderr,"Error reading file of random numbers (%s)\n",
                            RAND_FILE);
            exit(1);
          }
          w = (w<<8) | (b&0xff);
        }
        rn[i][j] = w;
      }
    }

    state = &state0;

    initialized = 1;

    rand_seed(1);
  }
}
Esempio n. 23
0
File: act.c Progetto: aanguss/act
//------------------------------------------------
// Create large block write buffers.
//
static bool create_salters() {
	if (! g_num_write_buffers) {
		if (! (g_salters[0].p_buffer = cf_valloc(g_large_block_ops_bytes))) {
			fprintf(stdout, "ERROR: large block write buffer cf_valloc()\n");
			return false;
		}

		memset(g_salters[0].p_buffer, 0, g_large_block_ops_bytes);
		g_num_write_buffers = 1;

		return true;
	}

	uint8_t seed_buffer[RAND_SEED_SIZE];

	if (! rand_seed(seed_buffer)) {
		return false;
	}

	for (uint32_t n = 0; n < g_num_write_buffers; n++) {
		if (! (g_salters[n].p_buffer = cf_valloc(g_large_block_ops_bytes))) {
			fprintf(stdout, "ERROR: large block write buffer cf_valloc()\n");
			return false;
		}

		if (! rand_fill(g_salters[n].p_buffer, g_large_block_ops_bytes)) {
			return false;
		}

		if (g_num_write_buffers > 1) {
			pthread_mutex_init(&g_salters[n].lock, NULL);
		}
	}

	return true;
}
Esempio n. 24
0
//---------- Begin of function Weather::next_day ----------//
//
void Weather::next_day()
{

	season_phase = (season_phase + 1 )% 365;

	//---------- update/determine earthquake day ---------//
	if( day_to_quake)
	{
		day_to_quake--;
		if ( is_quake() )
		{
			// generate quake_x, quake_y
			quake_x = rand_seed(0x10000) * MAX_MAP_WIDTH / 0x10000;
			quake_y = rand_seed(0x10000) * MAX_MAP_HEIGHT / 0x10000;
		}
	}
	else
		day_to_quake = quake_frequency + rand_seed(quake_frequency);

	//---------- update wind ----------//
	wind_dir = (wind_dir + rand_seed(5) ) % 360;
	wind_spd += rand_seed(9) - 4 - (high_wind_day/16);
	if( wind_spd < -10)
		wind_spd = -10;
	if( wind_spd > 110)
		wind_spd = 110;
	if( wind_spd >= 20 )
	{
		high_wind_day++;
	}
	else 
	{
		high_wind_day--;
	}

	//---------- generate cloud --------//
	if( cur_cloud_len > 0)
	{
		cur_cloud_len--;
	}
	else
	{
		short t = base_temp();
		short maxCloudStr;
		if( t >= 30)
			maxCloudStr = 10;
		else if( t <= 18)
			maxCloudStr = 4;
		else
			maxCloudStr = (t -18)/2 + 4;
		cur_cloud_str = rand_seed(maxCloudStr+4)-3;	// range : -2 to maxCloudStr
		if(cur_cloud_str < 0)
			cur_cloud_str = 0;
		cur_cloud_len = 2 + rand_seed(3) + rand_seed(3);

		cur_cloud_type = 0;
		
		// ------- summer weather
		if( cur_cloud_str > 4)
		{
			if( (char) rand_seed(10) < cur_cloud_str )
				cur_cloud_type |= RAIN_CLOUD;
			if( cur_cloud_str >= 6 && (char) rand_seed(10) < cur_cloud_str-4)
				cur_cloud_type |= WINDY;
		}
		if( cur_cloud_str <= 1 && t >= 30 && rand_seed(10) <= 1)
		{
			cur_cloud_type |= HOT_WAVE;
		}

		// ------- winter weather
		if( t < 15)
		{
			if( rand_seed(20) < 2 )
				cur_cloud_type |= COLD_WAVE;

			if( t >= 10 && rand_seed(10) < 3)
				cur_cloud_type |= WINDY;
			if( t < 10 && rand_seed(10) < 7)
				cur_cloud_type |= WINDY;
		}
		if( cur_cloud_type & WINDY)
			windy_speed = 10 + cur_cloud_str * 5 + rand_seed(2*cur_cloud_str+1);
		else
		{
			windy_speed = 0;
			if( cur_cloud_str > 4 && (char)rand_seed(50) < cur_cloud_str + 2 )
				cur_cloud_type |= LIGHTNING_CLOUD;
		}

		// ---- double the time of snow ------ //
		if( snow_scale() )
			cur_cloud_len += cur_cloud_len;

	}

	// -------- update tornado_count, at least 20 days between two tornadoes -------//
	if( tornado_count > 20 && base_temp() >= 30 && wind_speed() >= 40 
		&& rand_seed(10)==0 )
	{
		tornado_count = 0;			// today has a tornado
	}
	else
	{
		tornado_count++;
	}
}
Esempio n. 25
0
void rand_init() {
	uint8_t buf[SEED_SIZE];

#if RAND == UDEV
	int *fd = (int *)&(core_get()->rand);

	*fd = open(RAND_PATH, O_RDONLY);
	if (*fd == -1) {
		THROW(ERR_NO_FILE);
	}
#else

#if SEED == ZERO

	memset(buf, 0, SEED_SIZE);

#elif SEED == DEV || SEED == UDEV
	int fd, c, l;

	fd = open(RAND_PATH, O_RDONLY);
	if (fd == -1) {
		THROW(ERR_NO_FILE);
	}

	l = 0;
	do {
		c = read(fd, buf + l, SEED_SIZE - l);
		l += c;
		if (c == -1) {
			THROW(ERR_NO_READ);
		}
	} while (l < SEED_SIZE);

	if (fd != -1) {
		close(fd);
	}
#elif SEED == LIBC

#if OPSYS == FREEBSD
	srandom(1);
	for (int i = 0; i < SEED_SIZE; i++) {
		buf[i] = (uint8_t)random();
	}
#else
	srand(1);
	for (int i = 0; i < SEED_SIZE; i++) {
		buf[i] = (uint8_t)rand();
	}
#endif

#elif SEED == WCGR
	HCRYPTPROV hCryptProv;

	if (!CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL,
					CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) {
		THROW(ERR_NO_FILE);
	}
	if (hCryptProv && !CryptGenRandom(hCryptProv, SEED_SIZE, buf)) {
		THROW(ERR_NO_READ);
	}
	if (hCryptProv && !CryptReleaseContext(hCryptProv, 0)) {
		THROW(ERR_NO_READ);
	}
#endif

#endif /* RAND == UDEV */

#if RAND != CALL
	core_get()->seeded = 0;
	rand_seed(buf, SEED_SIZE);
#else
	rand_seed(NULL, NULL);
#endif
}
Esempio n. 26
0
int main()
{
	Config *config=NULL;  
	FileManager fm;
	FileSet fs;
	AdvancedScoreModel model; 
	EdgeModel edge_model;
	PeptideRankScorer drs;
	 
	

	rand_seed(112233);


//	train_all(); 

	model.read_model("CID_IT_TRYP");
	config = model.get_config(); 
	config->apply_selected_PTMs("C+57:M+16:Q-17");

//	fm.init_from_file(config,"C:\\Work\\msms5\\DnvScore\\all_ds\\HEK_98_3_unique_30.mgf");
	fs.select_files_in_mz_range(fm,300,2000,3);
	fs.randomly_reduce_ssfs(100);
	
	vector<int> cc(4,0);
	cc[3]=100;
	fs.create_mgf_file(fm,config,"HEK_4_30e.mgf",cc);
	exit(0);

//	model.get_config()->apply_selected_PTMs("C+57:M+16:Q-17"); 


	PMCSQS_Scorer *pmcsqs = (PMCSQS_Scorer *)model.get_pmcsqs_ptr();

	fm.init_from_list_file(config,"C:\\Work\\msms5\\PepNovoHQ\\train3.txt");

	pmcsqs->benchmark_pm_selection(config,fm,0.3);

	exit(0);

/*	benchmark_shew(model,"C:\\Work\\msms5\\PepNovoHQ\\Shew_test_10.mgf");
	exit(0);

		drs.set_model_type(0);
	drs.read_denovo_rank_scorer_model("C:\\Work\\msms5\\PepNovoHQ\\Models\\DBSCORE\\DBSCORE_rank_model.txt");
	drs.give_de_novo_and_peak_match_examples("C:\\Work\\msms5\\DnvScore\\all_db_hits",
									 "C:\\Work\\msms5\\DnvScore\\seq_freqs\\sequences",
									 "C:\\Work\\msms5\\DnvScore\\dnv_full_parts",
									 "C:\\Work\\msms5\\DnvScore\\dicty2_all.txt",
									 2,2);
	exit(0);
	
	drs.read_denovo_rank_scorer_model("C:\\Work\\msms5\\PepNovoHQ\\Models\\DBSCORE\\DBSCORE_rank_model.txt");
	drs.rescore_inspect_results("C:\\Work\\msms5\\DnvScore\\inspect_res\\H293-40ul-08.mzXML",
								"C:\\Work\\msms5\\DnvScore\\inspect_res\\H293-40ul-08.txt",
								"C:\\Work\\msms5\\DnvScore\\inspect_res\\H293-40ul-08_new.txt");

	exit(0);

//	test_denovo_integrity(model,"C:\\Work\\msms5\\DnvScore\\all_ds\\Dicty_98_2_unique_8.mgf", 20000, 8); 

//	benchmark_ranking_on_denovo("C:\\Work\\msms5\\PepNovoHQ\\Models\\DNVSCORE5\\DNVSCORE5_rank_model.txt",
//		"C:\\Work\\msms5\\DnvScore\\test\\DNVSCORE4_test_10.mgf",400,10); // 

//	benchmark_ranking_on_full_denovo("C:\\Work\\msms5\\PepNovoHQ\\Models\\DNVFULL\\DNVFULL_rank_model.txt",
//		"C:\\Work\\msms5\\DnvScore\\test\\FULL_test_10.mgf",1000);
//	exit(0); 



	fm.init_from_list_file(config,//"C:\\Work\\msms5\\DnvScore\\short2_train_mgf_list.txt");
	 "C:\\Work\\msms5\\DnvScore\\comp2_train_mgf_list.txt");
	// "C:\\Work\\msms5\\NewScore\\lists\\Shew_98_3_unique_mgf_list.txt");
	fs.select_files(fm,0,2500,-1,-1,2);
	
	find_special_PTM_frags_using_offset_counts("S",fm,fs.get_ssf_pointers(),&model,2);

	exit(0); 
	
	drs.read_denovo_rank_scorer_model("C:\\Work\\msms5\\PepNovoHQ\\Models\\DNVSC_RANK\\LTQ_DNVRANK_model.txt");
	drs.test_model("C:\\Work\\msms5\\DnvScore\\test_sets\\LTQ_DNVRANK_test_10.mgf",2000);

	drs.train_denovo_partition_model("C:\\Work\\msms5\\DnvScore\\all_db_hits",
									 "C:\\Work\\msms5\\DnvScore\\seq_freqs\\sequences",
									 "C:\\Work\\msms5\\DnvScore\\comp_all_parts",
								//	 "C:\\Work\\msms5\\DnvScore\\short2_train_mgf_list.txt",
									 "C:\\Work\\msms5\\DnvScore\\comp2_train_mgf_list.txt",
									 2,
									 1,
									 30000,
									 5); 




//	model.read_model("ETD");
//	config = model.get_config();
//	config->apply_selected_PTMs("M+16:Q-17:N+1:C+57");

//	fm.init_from_list_file(config,"C:\\Work\\msms5\\PepNovoHQ\\ETD2\\ETD_unique_train.txt");
//	model.full_train_model("ETD",fm,0.5);
	
//	model.train_pmc_rank_models("C:\\Work\\msms5\\PepNovoHQ\\ETD2\\ETD_all_train.txt");
//	model.write_model();
	exit(0); 

//	train_all();

//	create_training_sets();
//	exit(0);
//	generate_size_reports();
//	test_sims();
//	data_set_stats();

//	convert_list_to_trianing_peptide_file(
//		"C:\\Work\\msms5\\NewScore\\lists\\Dicty_98_3_unique_mgf_list.txt",
//		"C:\\Work\\msms5\\NewScore\\tps\\Dicty_98_3_unique_tps.txt");

//	proline_cleavage_reports("b",2); 
//	exit(0);
//	center_cleavage_reports("y",3);
//	n_terminal_cleavage_reports("y",2);
//	c_terminal_cleavage_reports("y",-2);


//	find_best_similar_pairs("LTQ_LOW_TRYP",
//		"C:\\Work\\msms5\\PepNovoHQ\\pairs\\HEK_pos2.mgf",
//		"C:\\Work\\msms5\\PepNovoHQ\\pairs\\Shew_pos2.mgf",8);

//	find_self_similarity("LTQ_LOW_TRYP",
//		"C:\\Work\\msms5\\PepNovoHQ\\pairs\\HEK_pos2.mgf",
//		"C:\\Work\\msms5\\PepNovoHQ\\pairs\\Shew_pos2.mgf");

//	find_similar_pairs_ditrib("LTQ_LOW_TRYP",
//		"C:\\Work\\msms5\\PepNovoHQ\\pairs\\HEK_pos2.mgf",
//		"C:\\Work\\msms5\\PepNovoHQ\\pairs\\Shew_pos2.mgf");

//	find_homeometric_similarity_distrib("LTQ_LOW_TRYP",
//		"C:\\Work\\msms5\\PepNovoHQ\\pairs\\HEK_pos2.mgf",
//		"C:\\Work\\msms5\\PepNovoHQ\\pairs\\Shew_pos2.mgf");

//	find_self_similarity_ranges("LTQ_LOW_TRYP",
//		"C:\\Work\\msms5\\PepNovoHQ\\pairs\\SHEW18.mgf");

//	peptide_distances();

//	find_matches_similarity_distrib("LTQ_LOW_TRYP",
//		"C:\\Work\\msms5\\PepNovoHQ\\pairs\\HEK_pos2.mgf",
//		"C:\\Work\\msms5\\PepNovoHQ\\pairs\\Shew_pos2.mgf");

//	match_sim_exp();  

//	exit(0);

//	edge_model.train_all_edge_models("C:\\Work\\clust_exp\\LTQ_train2_ann_list.txt","LTQ",2); 
//	saa.train_saa_models("C:\\Work\\clust_exp\\LTQ_train2_ann_list.txt","LTQ",2); 
//	saa.train_saancd_models("C:\\Work\\clust_exp\\LTQ_train2_ann_list.txt","LTQ",2); 
//	daa.train_daa_models("C:\\Work\\clust_exp\\LTQ_train2_ann_list.txt","LTQ",2,0.25); 
//	daa.train_daancd_model("C:\\Work\\clust_exp\\LTQ_train2_ann_list.txt","LTQ",2); 

	
//	dot_prod_exp();   
//	qc_exp();  
//	qc_ann_exp("64068",true);
//	exit(0); 

	config = model.get_config();
	config->init_with_defaults();
	config->apply_selected_PTMs("M+16:Q-17:N+1:C+57");

	fm.init_from_file(config,"C:\\Work\\msms5\\PepNovoHQ\\ETD\\train_etd.mgf");
	model.full_train_model("ETD",fm,0.5);
	exit(0); 

	if (1)
	{
		model.read_model("LTQ_LOW_TRYP");

	//	model.get_config()->apply_selected_PTMs("C+57:M+16");
	//	model.get_config()->init_with_defaults();
		model.get_config()->apply_selected_PTMs("M+16:C+57:Q-17");

	//	model.test_pmc("C:\\Work\\msms5\\PepNovoHQ\\pmcsqs\\sqs_train_1.mgf",1);
	//	model.compute_sqs_cum_stats_for_ided("C:\\Work\\msms5\\NewScore\\lists\\all_HEK_mgf_list.txt");
	//	model.compute_sqs_cum_stats_for_crap("C:\\Work\\msms5\\PepNovoHQ\\pmcsqs\\crap_list.txt");
	//	model.write_model();

		model.compute_sqs_cum_stats_for_ided("C:\\Work\\msms5\\PepNovoHQ\\pmcsqs\\H40good\\H40good_mgf_list.txt");

	///	model.benchmark_sqs("C:\\Work\\msms5\\PepNovoHQ\\small_list.txt",
	//						"C:\\Work\\msms5\\PepNovoHQ\\small_anns.txt");

	//	model.benchmark_sqs("C:\\Work\\msms5\\PepNovoHQ\\tmp\\H40ul_0_list.txt",
	//						"C:\\Work\\msms5\\PepNovoHQ\\H40ul55_missed.txt");
	//						"C:\\Work\\msms5\\PepNovoHQ\\pmcsqs\\H40ul98_anns.txt");
	exit(0);


	DAT_Converter dat;
	dat.create_dat_files_for_anns(model.get_config(),
								  "C:\\Work\\Data\\Briggs\\HEK293\\40ul_list.txt",
								//  "C:\\Work\\msms5\\PepNovoHQ\\pmcsqs\\H40ul98_anns.txt",
								  "C:\\Work\\msms5\\PepNovoHQ\\H40ul55_missed.txt",
								  "C:\\Work\\msms5\\PepNovoHQ\\tmp\\",
								  "H4055");
//	
		
	//	model.train_pmc_rank_models( 
		//	"C:\\Work\\msms5\\NewScore\\lists\\HEK_98_1_unique_mgf_list.txt",0);
	//		"C:\\Work\\msms5\\NewScore\\lists\\all_unique_mgf_list.txt",0);
	//		"C:\\Work\\msms5\\NewScore\\lists\\all_HEK_mgf_list.txt",0);

	//	model.write_model();
	//	make_before_and_after_matrices(model.get_config(),"C:\\Work\\msms5\\lists\\mgf10.txt",3,"y");
		exit(0);

		FileManager fm;
		fm.init_from_list_file(model.get_config(),"C:\\Work\\msms5\\lists\\LTQ_train_list.txt");

		model.full_train_model("LTQ_IT_TRYP",fm,0.45);

		model.write_model(); 

	//	model.train_pmc("C:\\Work\\msms5\\lists\\pos_sqs_list.txt");

		vector< vector<float> > weights;
		weights.resize(4);
		weights[1].resize(3,0);
		weights[2].resize(3,0);
		weights[3].resize(3,0);
		weights[1][0] = 0.1; weights[1][1] = 0.1;  weights[1][2] = 0.4;
		weights[2][0] = 0.6; weights[2][1] = 0.75; weights[2][2] = 0.5;
		weights[3][0] = 0.3; weights[3][1] = 0.15; weights[3][2] = 0.1;
	
	//	model.train_sqs("C:\\Work\\msms5\\lists\\pos_sqs_list.txt",
	//					"C:\\Work\\msms5\\lists\\neg_sqs_list.txt",&weights);

	//	model.train_sqs("C:\\Work\\msms5\\NewScore\\lists\\all_unique_mgf_list.txt",
	//					"C:\\Work\\msms5\\PepNovoHQ\\pmcsqs\\crap_list.txt",&weights);
	//	config = model.get_config();

	//	config->set_tolerance(0.5);
//
	//	find_pair_similarities(config,"C:/Work/clust_exp/Results/Shew_bm/ShewBM40_0_1.mgf",
	//		"C:/Work/clust_exp/Results/Shew_bm/ShewBM40_pairs.txt");

		exit(0);
	}

	//	make_y_vectors("C:\\Work\\msms5\\PepNovoHQ\\pmcsqs\\sqs10_train_2.mgf",&model);
	//	create_training_files(config);
	//	exit(0);

	if (0)
	{
		PMCSQS_Scorer sqs;


	//	exit(0); 



	//	create_training_files(config);
		exit(0);
	}

	if (1)
	{
	//	fm.init_from_file(model.get_config(),"C:\\Work\\msms5\\PepNovoHQ\\orbi_ann.mgf");
	//	create_MSB_query_for_file_list(fm,&model);

		vector< vector<int> >    annotation_idxs;
		vector<mzXML_annotation> annotations;
		read_mzXML_annotations("C:/Work/Data/Briggs/HEK293_mzxml_list.txt", 
					"C:/Work/ClusterAnn/mzxml_anns3.txt", annotation_idxs, annotations, 35000);

	//	read_mzXML_annotations("C:/Work/ClusterAnn/H40ul_mgf_list.txt", 
	//				"C:/Work/ClusterAnn/mgf_anns.txt", annotation_idxs, annotations, 35000);


		cout << "Read annotations: " << annotations.size() << endl;

		fm.init_from_list_file_and_add_annotations(config,"C:/Work/Data/Briggs/HEK293_mzxml_list.txt",
			annotation_idxs, annotations,true);

	//	fm.init_from_list_file_and_add_annotations(config,"C:/Work/ClusterAnn/H40ul_mgf_list.txt",annotation_idxs,
	//		annotations,true);


		FileSet all_spec_fs;
		all_spec_fs.select_all_files(fm,true);

	//	config->set_need_to_normalize(0);
	//	all_spec_fs.create_MGF_file(fm,config,"C:/Work/ClusterAnn/mgf_spectra.mgf");
	//	exit(0);

		ofstream mgf_stream("C:/Work/ClusterAnn/mzxml_spectra3.mgf",ios::out);
		BasicSpecReader bsr;
		const vector<SingleSpectrumFile *>& ssfs = all_spec_fs.get_ssf_pointers();
		int i;
		for (i=0; i<ssfs.size(); i++)
		{
			static QCPeak peaks[5000];
			BasicSpectrum bs;
			MZXML_single *ssf = (MZXML_single *)ssfs[i];

			bs.peaks = peaks;
			bs.ssf = ssf;
						
			ostringstream oss;
			oss << ssf->file_idx << " " << ssf->scan_number;
			ssf->single_name = oss.str();

			bs.num_peaks = bsr.read_basic_spec(config,fm,ssf,peaks);
			
			if (ssf->scan_number<0)
			{
				cout << "Error: no scan number read from mzXML!!!" << endl;
				exit(1);
			}

			cout << "scan: " << ssf->scan_number << " " << bs.num_peaks << endl;

			bs.output_to_mgf(mgf_stream,config);
		//	bs.output_to_mgf(cout,&config);
		}
		//all_spec_fs.create_MGF_file(fm,config,"C:/Work/ClusterAnn/mzxml_spectra.mgf");
	//	extractMZFromFiles(model.get_config(),,"C:/Work/Data/Briggs/HEK293/H29340ul_mz.txt");
	

	//
		exit(0);
	}


	if (1) 
	{ 
		model.read_model("LTQ_LOW_TRYP");  
		config = model.get_config();
		config->apply_selected_PTMs("C+57 M+16");
		config->set_tolerances(0.5);
		config->set_pm_tolerance(2.5);
		config->set_digest_type(TRYPSIN_DIGEST);
	
		config->set_max_number_peaks_per_local_window(15);

	//	fm.init_from_list_file(config,"C:\\Work\\clust_exp\\LTQ_train2_ann_list.txt");
	//	fm.init_from_list_file(config,"C:\\Work\\msms5\\lists\\LTQ_train_list.txt");
	//	fm.init_from_list_file(config,"C:\\Work\\msms5\\lists\\orbi_train.txt");
	//	edge_model.train_all_edge_models(fm,&model);
	//	tm.train_models(fm,&model); 

	//	fm.init_from_list_file(config,"C:\\Work\\clust_exp\\ShewMGF\\BM2000_ann_list.txt");
	//	make_frag_rank_histogram(fm,config);
	//	exit(0);

	//	benchmark_k_value(config,"C:\\Work\\clust_exp\\ShewMGF\\BM2000_ann_list.txt");

	//	make_benchmark_clustering_dataset(config, "C:\\Work\\clust_exp\\ShewMGF\\AnnsPlus_ann_list.txt",
	//			600, 750, false, "C:\\Work\\clust_exp\\ShewMGF\\", "BMNEW"); 

	//	exit(0);
		benchmark_clustering_performance(config,
			"C:\\Work\\clust_exp\\ShewMGF\\BM2000_ann_list.txt",15);

 
	//	print_dataset_spectra_by_stats(config,"C:\\Work\\clust_exp\\ann_mgf\\Sings_1.mgf");

	//	benchmark_top7_and_sim_thresh(config,"C:\\Work\\clust_exp\\tmp\\H293_40ul_list.txt",
	//		"C:\\Work\\clust_exp\\Results\\BM40ul\\BM40ul_anns.txt");

	//	benchmark_heuristic_filtering(config,"C:\\Work\\clust_exp\\tmp\\H293_40ul_list.txt");
	//	benchmark_retention_thresh(config,"C:\\Work\\clust_exp\\tmp\\H293_40ul_list.txt",
	//		"C:\\Work\\clust_exp\\Results\\BM40ul\\BM40ul_anns.txt");

		exit(0);

		FileManager fm;

	//	fm.init_from_mgf(config,"C:\\Work\\clust_exp\\ShewMGF\\OnlyAnn_1.mgf");


	//	make_specified_benchmark_clustering_dataset(config,"C:\\Work\\clust_exp\\ShewMGF\\both_list.txt",400,1000,
	//		"C:\\Work\\clust_exp\\ShewMGF\\","BM3000",3000,10,0);

		make_benchmark_clustering_dataset(config, "C:\\Work\\clust_exp\\ShewMGF\\AnnsPlus_ann_list.txt",
				800, 1200, true, "C:\\Work\\clust_exp\\ShewMGF\\", "AnnOnly"); 
		exit(0);

		ann_mgf_and_create_mgf_with_sim_masses(config,"K:\\Work\\Data\\Shewenella\\FT_anns.txt",
			"K:\\Work\\Data\\Shewenella\\FT_mgf_list.txt",
			"K:\\Work\\Data\\Shewenella\\FT_peptides.txt",
			"C:\\Work\\clust_exp\\ShewMGF\\",
			"AnnsPlus");

		exit(0);

		ann_mgf_and_create_mgf(config,"C:\\Work\\Data\\FT_mgf\\FT_single_anns.txt", 
			"C:\\Work\\Data\\FT_mgf\\FT_single_mgf.txt",
			"C:\\Work\\clust_exp\\ShewMGF\\",
			"Single",true);

		exit(0);

		ann_mgf_and_create_mgf(config,"C:\\Work\\Data\\FT_mgf\\FT_anns.txt", 
			"C:\\Work\\Data\\FT_mgf\\FT_mgf_list.txt",
			"C:\\Work\\clust_exp\\ShewMGF\\",
			"OnlyAnn",true);

		exit(0);

	//	create_16O_18O_dataset("C:\\Work\\msms5\\lists\\p19_list.txt",config);
	//	exit(0);

	//	config->set_need_to_estimate_pm(0);

		model.clone_charge_model(2,1);
		model.clone_charge_model(2,3);
		model.clone_charge_model(2,4);
		model.clone_charge_model(2,5);

	//	dataset_eval(&model,"C:\\Work\\msms5\\lists\\CAD_376.txt",0.05);
	//	dataset_eval(&model,"C:\\Work\\msms5\\lists\\ann_qtof_list.txt",0.1);
	//	dataset_eval(&model,"C:\\Work\\msms5\\lists\\list280_mgf.txt",0.6);

		

		vector<int>   set_sizes;  
		vector<float> probs;
		denovo_sequencing_and_aa_probs(&model,"C:\\Work\\msms5\\lists\\m280_list.txt",
			set_sizes,probs,2); 

//		denovo_sequencing_and_aa_probs(&model,"C:\\Work\\clust_exp\\LTQ_train2_ann_list.txt",
//			set_sizes,probs,2); 
//
//		output_denovo_results(&model,"C:\\Work\\msms5\\lists\\LTQ-FT_mgf_list.txt");

	//	denovo_sequencing_and_aa_probs(&model,"C:\\Work\\msms5\\lists\\LTQ-FT_mgf_list.txt",
	//		set_sizes,probs, 2);
		exit(0);

	//	print_specs(model.get_config(), "C:\\Work\\msms5\\lists\\one_mzxml.txt");
	//	check_m_over_z(&model,"C:\\Work\\msms5\\lists\\CoCl345sann_ann_list.txt");
	//	calc_parent_mass_tolerance_distribution(&model, "C:\\Work\\msms5\\lists\\ann_mgf_list.txt" , 0.6, 0.98);
	//	calc_tolerance_distribution(&model,"C:\\Work\\msms5\\lists\\ann_mgf_list.txt", 0.6, 0.95);

	//	perfrom_inital_evalutation("C:\\Work\\msms5\\lists\\ann_mgf_list.txt",0.5,2,0.05);

	//	denovo_sequencing_results(&model,"C:\\Work\\msms5\\lists\\CAD_376.txt" ,0.0075);
	//	denovo_sequencing_results(&model,"C:\\Work\\msms5\\lists\\ann_qtof_list.txt",0.1);
	//	denovo_sequencing_results(&model,"C:\\Work\\msms5\\lists\\ann_orbi_list.txt",0.008);

	//	perfrom_inital_evalutation("C:\\Work\\msms5\\lists\\ann_qtof_list.txt",0.2,2,0.05);
	//	perfrom_inital_evalutation("C:\\Work\\msms5\\lists\\ann_orbi_list.txt",0.025,2,0.05);
	//	calc_tolerance_distribution(&model,"C:\\Work\\msms5\\lists\\ann_qtof_list.txt",0.1,0.95);
	//	calc_tolerance_distribution(&model,"C:\\Work\\msms5\\lists\\ann_orbi_list.txt",0.1,0.95);
	//	calc_tolerance_distribution(&model,"C:\\Work\\msms5\\lists\\CAD_376.txt",0.1,0.95);
	//	calc_tolerance_distribution(&model,"C:\\Work\\Data\\Omics04\\omics_ann_list.txt",0.75,0.95);

	//	calc_parent_mass_tolerance_distribution(&model,"C:\\Work\\msms5\\lists\\ann_qtof_list.txt",0.1,0.975);
	//	calc_parent_mass_tolerance_distribution(&model,"C:\\Work\\msms5\\lists\\ann_orbi_list.txt",0.1,0.975);
	//	calc_parent_mass_tolerance_distribution(&model,"C:\\Work\\msms5\\lists\\CAD_376.txt",0.1,0.975);
		exit(0);

	//	fm.init_from_mgf(config,"C:\\Work\\msms4\\PepNovo\\test\\m280.mgf");
	//	fm.init_from_list_file(config,"C:\\Work\\msms5\\lists\\good_list2.txt");
	//	fm.init_from_list_file(config,"C:\\Work\\msms5\\lists\\p215.txt");
	//	fm.init_from_list_file(config,"C:\\Work\\Data\\Omics04\\omics_ann_list.txt");
	//	fm.init_from_list_file(config,"C:\\Work\\msms5\\lists\\omics_mgf_list.txt");
	//	fm.init_from_mgf(config,"C:\\Work\\msms5\\PepNovoHQ\\Omics04Spectra.mgf");

	//	fm.init_from_list_file(config,"C:\\Work\\msms5\\lists\\omics02_dta.txt");
	//	FileSet fs;
	//	fs.select_all_files(fm);
	//	fs.sort_according_to_m_over_z();
	//	fs.create_MGF_file(fm,config,"Omics02Spectra.mgf");


	//	exit(0);

	//	collect_denovo_statistics(fm,&model);
	//	denovo_histograms(fm,&model);
	//	config->set_tolerance(0.0075);
	//	random_check_homemorphic(config,50000,25);

	//	create_spectrum_clusters(config,"C:\\Work\\msms5\\lists\\Drosophila_list.txt",".","cc",0,5E6,0,1E6);
	//	create_spectrum_clusters(config,"C:\\Work\\msms5\\lists\\Dros_short.txt",".","cc",0,1E6,0,1E6);
//		create_spectrum_clusters(config,"C:\\Work\\msms5\\lists\\all_clust.txt","clust_out","ikkb",0,5E6,0,1E6);


	//	create_spectrum_clusters(config,"C:\\Work\\msms5\\lists\\omics_mgf_list.txt","clust_out",
	//		"Omics04b",0,5E6,0,1E6);

	//	create_spectrum_clusters(config,"C:\\Work\\msms5\\lists\\omics02_mgf_list.txt","clust_out",
	//		"Omics02",0,5E6,0,1E6);
		

	//	create_spectrum_clusters(config,"C:\\Work\\msms5\\PepNovoHQ\\clust_out2\\h293_dat_list.txt",
	//		"clust_out2","H293b_2nd_digest_abd3",0,5E6,1938.76,1E6,2);

	//	create_spectrum_clusters(config,"C:\\Work\\msms5\\PepNovoHQ\\clust_out\\h29s_list.txt","clust_out",
	//		"xxxx",0,5E6,835.397,1E6,2);

		exit(0);



		DAT_Converter dat;
		dat.init_DAT_Converter(2000,25,1048576);

		exit(0);
	}


	
//	config->add_selected_PTMs("C+57 M+16 S+80 T+80 Y+80 N+1 Q+1 K+42 D+16 K+16 P+16 N+16");
//	config->set_tolerances(0.0075);
//	config->set_pm_tolerance(0.011);




	
//	fdb.create_db_from_fasta("C:\\Work\\msms5\\PepNovoHQ\\DB\\contaminants.fasta",config);
//  fdb.create_db_from_fasta("C:\\Work\\msms5\\PepNovoHQ\\DB\\Homo_sapiens.NCBI35.dec.pep.fa",config);
//	fdb.create_db_from_fasta("C:\\Work\\msms5\\PepNovoHQ\\DB\\fa50mb.fa",config,true,5,6);
//	fdb.create_db_from_fasta("C:\\Work\\msms5\\PepNovoHQ\\DB\\homo_pos.fa",config);
//	fdb.print_protein_names();
//	fdb.write_FastaDB("C:\\Work\\msms5\\PepNovoHQ\\DB\\h**o.dat");
//	fdb.read_FastaDB("C:\\Work\\msms5\\PepNovoHQ\\DB\\h**o.dat",config);
//	fdb.read_FastaDB("C:\\Work\\msms5\\PepNovoHQ\\DB\\qqq.dat",config);
//	fdb.read_FastaDB("C:\\Work\\msms5\\PepNovoHQ\\DB\\fa500k.dat",config);
//	fdb.print_protein_names();
//	fdb.write_FastaDB("C:\\Work\\msms5\\PepNovoHQ\\DB\\fa5--0mb.dat");

//  exit(0);

//	fm.init_from_list_file(config,"C:\\Work\\msms5\\lists\\CAD_seq_list.txt");
//	fm.init_from_list_file(config,"C:\\Work\\msms5\\lists\\CAD_u_list.txt");
	fm.init_from_list_file(config,"C:\\Work\\msms5\\lists\\CAD_376.txt");

	

//	make_bin_histograms(fm,config);
//	calc_avg_rand(fm,config);
//	explore_fragment_set(fm,config);
//	show_occurences(fm,config,"p-25.0");
//	find_internal_offset_counts(fm,config);
//	make_frag_rank_histogram(fm,config);
//	exit(0);


//	internal_fragment_annotation(fm,model.get_config());
//	find_internal_offset_counts(fm,model.get_config());
//	exit(0);

	FileSet fs;
	fs.select_all_files(fm);
	fstream ofs("true_seq.txt",ios::out);
	fs.make_fasta_from_file_seqs(fm,config,45,ofs);

//	dbsm.train_regression_models(fm,fdb,12,&model);

//	analyze_cad_spec(fm,config);
//	make_rank_histograms(fm,&model);
//	dbsm.read_model("DBS.txt");
//	CAD_histograms(fm,&model,fdb,&dbsm);
//	rand_db_stats(fm,&model,&dbsm);
//	db_search_stats(fm,&model,&dbsm);
//	neg_db_search_stats(fm,&model,&dbsm);
//	CAD_edge_stats(fm,&model);
//	CAD_denovo_histograms(fm,&model,fdb);
//	CAD_edge_stats(fm,&model);
//	collect_denovo_statistics(fm,&model);
	exit(0);

//	int *arr;
//	int t_size;
//	read_fasta("cshort.fasta",&arr,&t_size,&config);
//	read_fasta("C:\\Work\\msms4\\PepNovo\\Homo_sapiens.NCBI35.dec.pep.fa",&arr,&t_size,config);
	read_fasta("Homo_sapiens.NCBI35.dec.pep.fa",&arr,&t_size,&config);
	read_fasta("Homo_sapiens.NCBI35.dec.pep.fa",&arr,&t_size,&config);
	read_fasta("Homo_sapiens.NCBI35.dec.pep.fa",&arr,&t_size,&config);
	read_fasta("Homo_sapiens.NCBI35.dec.pep.fa",&arr,&t_size,&config);
	read_fasta("Homo_sapiens.NCBI35.dec.pep.fa",&arr,&t_size,&config);
	read_fasta("Homo_sapiens.NCBI35.dec.pep.fa",&arr,&t_size,&config); 
//	homeomorphic_levels(&config,arr,t_size,1000.0,1001,"hp_res.txt");

	config->set_tolerance(0.0075);
//	full_exp(config,0,arr,t_size,"hp_res_dis_a0.txt");
//	full_exp(config,1,arr,t_size,"hp_res_dis_a1.txt");
//	full_exp(config,2,arr,t_size,"hp_res_dis_a2.txt");
//	full_exp(config,3,arr,t_size,"hp_res_dis_a3.txt");
//	full_exp(config,4,arr,t_size,"hp_res_dis_a4.txt");
	

//	homeomorphic_exp3(&config,100);
//	exit(0);
//	config.print_supported_PTMs();

//	config.print_session_aas();
	string p;
//	ifstream fs("D:\\msms4\\PepNovo\\test\\C25A19_IP_01.mgf",ios::in);
//	ifstream fs("D:\\msms4\\PepNovo\\test\\m280.mgf",ios::in);
//	fm.init_from_mgf(&config,"D:\\msms4\\PepNovo\\test\\m280.mgf");
//	fm.init_from_mgf(&config,"D:\\msms4\\PepNovo\\mgf_2600.2.mgf");
//	fm.init_from_list_file(&config,"D:\\msms4\\lists\\unique_good2.txt");
	
//	fm.init_from_list_file(&config,"D:\\msms4\\lists\\short2.txt");
//	fm.init_from_list_file(&config,"D:\\Data2\\ikkb_unmod_list.txt");

//	rand_seed(1111);
	rand_seed(1426347);


//	model.read_model("ESI_RANKS");
//	model.get_config()->add_selected_PTMs("C+57");

//	SpectrumScore sqs;
//	sqs.learn_score_params(&model,"D:\\msms4\\lists\\sqs2_short.txt",
//		"D:\\msms4\\lists\\sqs_neg1.txt");	
//	exit(0);


//	model.set_model_name(string("ESI2"));


//	random_peak_match_exp(model.get_config(),fm,800,1200,10000000);
//	model.print_joint_scores();

//	me_reg_exp();
//	me_exp();
//	exit(0);





//	fm.init_from_mgf(model.get_config(),"c:\\work\\msms4\\PepNovo\\test\\m280.mgf");
//	fm.init_from_mgf(model.get_config(),"c:\\work\\msms4\\PepNovo\\hpep.mgf");
	fm.init_from_list_file(config,"c:\\Work\\msms4\\lists\\efast2.txt");
//	fm.init_from_list_file(&config,"D:\\msms4\\lists\\charge2.txt");
//m.init_from_list_file(model.get_config(),"C:\\Work\\msms4\\PepNovo\\lll.txt");
//m.init_from_list_file(model.get_config(),"D:\\msms4\\lists\\l1.txt");
	


*/


	return 0;
}
Esempio n. 27
0
void make_ldpc
( int seed,		/* Random number seed */
  make_method method,	/* How to make it */
  distrib *d,		/* Distribution list specified */
  int no4cycle		/* Eliminate cycles of length four? */
)
{
  mod2entry *e, *f, *g, *h;
  int added, uneven, elim4, all_even, n_full, left;
  int i, j, k, t, z, cb_N;
  int *part, *u;

  rand_seed(10*seed+1);

  H = mod2sparse_allocate(M,N);
  part = column_partition(d,N);

  /* Create the initial version of the parity check matrix. */

  switch (method)
  { 
    case Evencol:
    { 
      z = 0;
      left = part[z];

      for (j = 0; j<N; j++)
      { while (left==0)
        { z += 1;
          if (z>distrib_size(d))
          { abort();
          }
          left = part[z];
        }
        for (k = 0; k<distrib_num(d,z); k++)
        { do
          { i = rand_int(M);
          } while (mod2sparse_find(H,i,j));
          mod2sparse_insert(H,i,j);
        }
        left -= 1;
      }

      break;
    }

    case Evenboth:
    {
      cb_N = 0;
      for (z = 0; z<distrib_size(d); z++)
      { cb_N += distrib_num(d,z) * part[z];
      }
      
      u = chk_alloc (cb_N, sizeof *u);

      for (k = cb_N-1; k>=0; k--)
      { u[k] = k%M;
      }
  
      uneven = 0;
      t = 0;
      z = 0;
      left = part[z];

      for (j = 0; j<N; j++)
      { 
        while (left==0)
        { z += 1;
          if (z>distrib_size(d))
          { abort();
          }
          left = part[z];
        }

	for (k = 0; k<distrib_num(d,z); k++)
        { 
          for (i = t; i<cb_N && mod2sparse_find(H,u[i],j); i++) ;

          if (i==cb_N)
          { uneven += 1;
            do
            { i = rand_int(M);
            } while (mod2sparse_find(H,i,j));
            mod2sparse_insert(H,i,j);
          }
          else
          { do
            { i = t + rand_int(cb_N-t);
            } while (mod2sparse_find(H,u[i],j));
            mod2sparse_insert(H,u[i],j);
            u[i] = u[t];
            t += 1;
          }
        }

        left -= 1;
      }

      if (uneven>0)
      { fprintf(stderr,"Had to place %d checks in rows unevenly\n",uneven);
      }

      break;
    }

    default: abort();
  }

  /* Add extra bits to avoid rows with less than two checks. */

  added = 0;

  for (i = 0; i<M; i++)
  { e = mod2sparse_first_in_row(H,i);
    if (mod2sparse_at_end(e))
    { j = rand_int(N);
      e = mod2sparse_insert(H,i,j);
      added += 1;
    }
    e = mod2sparse_first_in_row(H,i);
    if (mod2sparse_at_end(mod2sparse_next_in_row(e)) && N>1)
    { do 
      { j = rand_int(N); 
      } while (j==mod2sparse_col(e));
      mod2sparse_insert(H,i,j);
      added += 1;
    }
  }

  if (added>0)
  { fprintf(stderr,
           "Added %d extra bit-checks to make row counts at least two\n",
           added);
  }

  /* Add extra bits to try to avoid problems with even column counts. */

  n_full = 0;
  all_even = 1;
  for (z = 0; z<distrib_size(d); z++)
  { if (distrib_num(d,z)==M) 
    { n_full += part[z];
    }
    if (distrib_num(d,z)%2==1)
    { all_even = 0;
    }
  }

  if (all_even && N-n_full>1 && added<2)
  { int a;
    for (a = 0; added+a<2; a++)
    { do
      { i = rand_int(M);
        j = rand_int(N);
      } while (mod2sparse_find(H,i,j));
      mod2sparse_insert(H,i,j);
    }
    fprintf(stderr,
 "Added %d extra bit-checks to try to avoid problems from even column counts\n",
      a);
  }

  /* Eliminate cycles of length four, if asked, and if possible. */

  if (no4cycle)
  { 
    elim4 = 0;

    for (t = 0; t<10; t++) 
    { k = 0;
      for (j = 0; j<N; j++)
      { for (e = mod2sparse_first_in_col(H,j);
             !mod2sparse_at_end(e);
             e = mod2sparse_next_in_col(e))
        { for (f = mod2sparse_first_in_row(H,mod2sparse_row(e));
               !mod2sparse_at_end(f);
               f = mod2sparse_next_in_row(f))
          { if (f==e) continue;
            for (g = mod2sparse_first_in_col(H,mod2sparse_col(f));
                 !mod2sparse_at_end(g);
                 g = mod2sparse_next_in_col(g))
            { if (g==f) continue;
              for (h = mod2sparse_first_in_row(H,mod2sparse_row(g));
                   !mod2sparse_at_end(h);
                   h = mod2sparse_next_in_row(h))
              { if (mod2sparse_col(h)==j)
                { do
                  { i = rand_int(M);
                  } while (mod2sparse_find(H,i,j));
                  mod2sparse_delete(H,e);
                  mod2sparse_insert(H,i,j);
                  elim4 += 1;
                  k += 1;
                  goto nextj;
                }
              }
            }
          }
        }
      nextj: ;
      }
      if (k==0) break;
    }

    if (elim4>0)
    { fprintf(stderr,
        "Eliminated %d cycles of length four by moving checks within column\n",
         elim4);
    }

    if (t==10) 
    { fprintf(stderr,
        "Couldn't eliminate all cycles of length four in 10 passes\n");
    }
  }
}
Esempio n. 28
0
int main(int argc, char *argv[]) {
    // Get path
    char *ip = NULL;
    unsigned short connect_port = 0;
    unsigned short listen_port = 0;
    int net_mode = NET_MODE_NONE;
    int ret = 0;

    // Path manager
    if(pm_init() != 0) {
        err_msgbox(pm_get_errormsg());
        return 1;
    }

    // Check arguments
    if(argc >= 2) {
        if(strcmp(argv[1], "-v") == 0) {
            printf("OpenOMF v%d.%d.%d\n", V_MAJOR, V_MINOR, V_PATCH);
            printf("Source available at https://github.com/omf2097/ under MIT License\n");
            printf("(C) 2097 Tuomas Virtanen, Andrew Thompson, Hunter and others\n");
            goto exit_0;
        } else if(strcmp(argv[1], "-h") == 0) {
            printf("Arguments:\n");
            printf("-h              Prints this help\n");
            printf("-c [ip] [port]  Connect to server\n");
            printf("-l [port]       Start server\n");
            goto exit_0;
        } else if(strcmp(argv[1], "-c") == 0) {
            if(argc >= 3) {
                ip = strcpy(malloc(strlen(argv[2])+1), argv[2]);
            }
            if(argc >= 4) {
                connect_port = atoi(argv[3]);
            }
            net_mode = NET_MODE_CLIENT;
        } else if(strcmp(argv[1], "-l") == 0) {
            if(argc >= 3) {
                listen_port = atoi(argv[2]);
            }
            net_mode = NET_MODE_SERVER;
        }
    }

    // Init log
#if defined(DEBUGMODE) || defined(STANDALONE_SERVER)
    if(log_init(0)) {
        err_msgbox("Error while initializing log!");
        goto exit_0;
    }
#else
    if(log_init(pm_get_local_path(LOG_PATH))) {
        err_msgbox("Error while initializing log '%s'!", pm_get_local_path(LOG_PATH));
        goto exit_0;
    }
#endif

    // Simple header
    INFO("Starting OpenOMF v%d.%d.%d", V_MAJOR, V_MINOR, V_PATCH);

    // Dump pathmanager log
    pm_log();

    // Random seed
    rand_seed(time(NULL));

    // Init stringparser
    sd_stringparser_lib_init();

    // Init config
    if(settings_init(pm_get_local_path(CONFIG_PATH))) {
        err_msgbox("Failed to initialize settings file");
        goto exit_1;
    }
    settings_load();

    // Find plugins and make sure they are valid
    plugins_init();

    // Network game override stuff
    if(ip) {
        DEBUG("Connect IP overridden to %s", ip);
        settings_get()->net.net_connect_ip = ip;
    }
    if(connect_port > 0 && connect_port < 0xFFFF) {
        DEBUG("Connect Port overridden to %u", connect_port&0xFFFF);
        settings_get()->net.net_connect_port = connect_port;
    }
    if(listen_port > 0 && listen_port < 0xFFFF) {
        DEBUG("Listen Port overridden to %u", listen_port&0xFFFF);
        settings_get()->net.net_listen_port = listen_port;
    }

    // Init SDL2
    unsigned int sdl_flags = SDL_INIT_TIMER;
#ifndef STANDALONE_SERVER
    sdl_flags |= SDL_INIT_VIDEO;
#endif
    if(SDL_Init(sdl_flags)) {
        err_msgbox("SDL2 Initialization failed: %s", SDL_GetError());
        goto exit_2;
    }
    SDL_version sdl_linked;
    SDL_GetVersion(&sdl_linked);
    INFO("Found SDL v%d.%d.%d", sdl_linked.major, sdl_linked.minor, sdl_linked.patch);
    INFO("Running on platform: %s", SDL_GetPlatform());

#ifndef STANDALONE_SERVER
    if(SDL_InitSubSystem(SDL_INIT_JOYSTICK|SDL_INIT_GAMECONTROLLER|SDL_INIT_HAPTIC)) {
        err_msgbox("SDL2 Initialization failed: %s", SDL_GetError());
        goto exit_2;
    }

    // Attempt to find gamecontrollerdb.txt, either from resources or from
    // built-in header
    SDL_RWops *rw = SDL_RWFromConstMem(gamecontrollerdb, strlen(gamecontrollerdb));
    SDL_GameControllerAddMappingsFromRW(rw, 1);
    char *gamecontrollerdbpath = malloc(128);
    snprintf(gamecontrollerdbpath, 128, "%s/gamecontrollerdb.txt", pm_get_local_path(RESOURCE_PATH));
    int mappings_loaded = SDL_GameControllerAddMappingsFromFile(gamecontrollerdbpath);
    if (mappings_loaded > 0) {
        DEBUG("loaded %d mappings from %s", mappings_loaded, gamecontrollerdbpath);
    }
    free(gamecontrollerdbpath);

    // Load up joysticks
    INFO("Found %d joysticks attached", SDL_NumJoysticks());
    SDL_Joystick *joy;
    char guidstr[33];
    for (int i = 0; i < SDL_NumJoysticks(); i++) {
        joy = SDL_JoystickOpen(i);
        if (joy) {
            SDL_JoystickGUID guid = SDL_JoystickGetGUID(joy);
            SDL_JoystickGetGUIDString(guid, guidstr, 33);
            INFO("Opened Joystick %d", i);
            INFO(" * Name:              %s", SDL_JoystickNameForIndex(i));
            INFO(" * Number of Axes:    %d", SDL_JoystickNumAxes(joy));
            INFO(" * Number of Buttons: %d", SDL_JoystickNumButtons(joy));
            INFO(" * Number of Balls:   %d", SDL_JoystickNumBalls(joy));
            INFO(" * Number of Hats:    %d", SDL_JoystickNumHats(joy));
            INFO(" * GUID          :    %s", guidstr);
        } else {
            INFO("Joystick %d is unsupported", i);
        }

        if (SDL_JoystickGetAttached(joy)) {
            SDL_JoystickClose(joy);
        }
    }

    // Init libDumb
    dumb_register_stdfiles();
#endif

    // Init enet
    if(enet_initialize() != 0) {
        err_msgbox("Failed to initialize enet");
        goto exit_3;
    }

    // Initialize engine
    if(engine_init()) {
        err_msgbox("Failed to initialize game engine.");
        goto exit_4;
    }

    // Run
    engine_run(net_mode);

    // Close everything
    engine_close();
exit_4:
    enet_deinitialize();
exit_3:
    SDL_Quit();
exit_2:
    dumb_exit();
    settings_save();
    settings_free();
exit_1:
    sd_stringparser_lib_deinit();
    INFO("Exit.");
    log_close();
exit_0:
    if (ip) {
        free(ip);
    }
    plugins_close();
    pm_free();
    return ret;
}
Esempio n. 29
0
int 
main(void){
	
	SCS |= 0x01;
	
	FIODIR0 = 0;	/* Just to make sure that all pins on Port0 are input. */
	
	/* The following pins are output: */
	FIODIR0 |= ((1<<21) | BACKLIGHT_PWM_PIN | SOUND_ENABLE_PIN | (1<<6));
	
	/* TODO what is this pin for ? */
	FIODIR0 |= (1<<12);
	FIOSET0 = (1<<12);

	setSpeed(SPEED_30);
		
	rand_seed(13); 				// initialize the random number generator
	
	/* Initialize the kernel. Kernel is not running yet */
	kernel_init();

	/* Initialize the display */
	lcd_init(0);
	
	/* Initialize the serial port */
	serial_init(38400);
	task_add(&serial_out);					// Task 0
	
	/* Enable IRQs. Now IRQ service routines start to run */
	enableIRQ();
	
	/* Enable radio communication */
	RF_init();								// Task 1 == produce_send_token)

	/* Initialize backlight task */
	inactivity_cnt = 0;		// consider power on to be a user activity
	task_add(&backl_proc);					// Task 2
	startPWMIRQ();

	/* Initialize keyboard handling */
	key_init();								// Task 3 == key_scan()

	/* Build an initial model of the internal and external state of the world */
	model_init();							// Task 4 == update_playtime()
	
	/* Show something to the user depending on model */
	mainscreen_init();						// Task 5 == win_scroll_all()
	
	dbg("RESET");
	
	/* Start the controller task 
		- keeps model up to date
		- starts actions according to model
		- shows relevant information on the screen
	*/
	task_add(&controller);					// Task 6
											// Task 7 == assemble_line()
	
	/* Start the kernel scheduler */
	while(1){
		schedule();
	};

	return 0;
}
Esempio n. 30
0
int
main(int argc, char* argv[])
{
	signal_setup();

	fprintf(stdout, "\nACT version %s\n", VERSION);
	fprintf(stdout, "Storage device IO test\n");
	fprintf(stdout, "Copyright 2018 by Aerospike. All rights reserved.\n\n");

	if (! storage_configure(argc, argv)) {
		exit(-1);
	}

	device devices[g_scfg.num_devices];
	queue* trans_qs[g_scfg.num_queues];

	g_devices = devices;
	g_trans_qs = trans_qs;

	histogram_scale scale =
			g_scfg.us_histograms ? HIST_MICROSECONDS : HIST_MILLISECONDS;

	if (! (g_large_block_read_hist = histogram_create(scale)) ||
		! (g_large_block_write_hist = histogram_create(scale)) ||
		! (g_raw_read_hist = histogram_create(scale)) ||
		! (g_read_hist = histogram_create(scale)) ||
		! (g_raw_write_hist = histogram_create(scale)) ||
		! (g_write_hist = histogram_create(scale))) {
		exit(-1);
	}

	for (uint32_t n = 0; n < g_scfg.num_devices; n++) {
		device* dev = &g_devices[n];

		dev->name = (const char*)g_scfg.device_names[n];

		if (g_scfg.file_size == 0) { // normally 0
			set_scheduler(dev->name, g_scfg.scheduler_mode);
		}

		if (! (dev->fd_q = queue_create(sizeof(int), true)) ||
			! discover_device(dev) ||
			! (dev->raw_read_hist = histogram_create(scale)) ||
			! (dev->raw_write_hist = histogram_create(scale))) {
			exit(-1);
		}

		sprintf(dev->read_hist_tag, "%s-reads", dev->name);
		sprintf(dev->write_hist_tag, "%s-writes", dev->name);
	}

	rand_seed();

	g_run_start_us = get_us();

	uint64_t run_stop_us = g_run_start_us + g_scfg.run_us;

	g_running = true;

	if (g_scfg.write_reqs_per_sec != 0) {
		for (uint32_t n = 0; n < g_scfg.num_devices; n++) {
			device* dev = &g_devices[n];

			if (pthread_create(&dev->large_block_read_thread, NULL,
					run_large_block_reads, (void*)dev) != 0) {
				fprintf(stdout, "ERROR: create large op read thread\n");
				exit(-1);
			}

			if (pthread_create(&dev->large_block_write_thread, NULL,
					run_large_block_writes, (void*)dev) != 0) {
				fprintf(stdout, "ERROR: create large op write thread\n");
				exit(-1);
			}
		}
	}

	if (g_scfg.tomb_raider) {
		for (uint32_t n = 0; n < g_scfg.num_devices; n++) {
			device* dev = &g_devices[n];

			if (pthread_create(&dev->tomb_raider_thread, NULL,
					run_tomb_raider, (void*)dev) != 0) {
				fprintf(stdout, "ERROR: create tomb raider thread\n");
				exit(-1);
			}
		}
	}

	uint32_t n_trans_tids = g_scfg.num_queues * g_scfg.threads_per_queue;
	pthread_t trans_tids[n_trans_tids];

	for (uint32_t i = 0; i < g_scfg.num_queues; i++) {
		if (! (g_trans_qs[i] = queue_create(sizeof(trans_req), true))) {
			exit(-1);
		}

		for (uint32_t j = 0; j < g_scfg.threads_per_queue; j++) {
			if (pthread_create(&trans_tids[(i * g_scfg.threads_per_queue) + j],
					NULL, run_transactions, (void*)g_trans_qs[i]) != 0) {
				fprintf(stdout, "ERROR: create transaction thread\n");
				exit(-1);
			}
		}
	}

	// Equivalent: g_scfg.internal_read_reqs_per_sec != 0.
	bool do_reads = g_scfg.read_reqs_per_sec != 0;

	pthread_t read_req_tids[g_scfg.read_req_threads];

	if (do_reads) {
		for (uint32_t k = 0; k < g_scfg.read_req_threads; k++) {
			if (pthread_create(&read_req_tids[k], NULL, run_generate_read_reqs,
					NULL) != 0) {
				fprintf(stdout, "ERROR: create read request thread\n");
				exit(-1);
			}
		}
	}

	// Equivalent: g_scfg.internal_write_reqs_per_sec != 0.
	bool do_commits = g_scfg.commit_to_device && g_scfg.write_reqs_per_sec != 0;

	pthread_t write_req_tids[g_scfg.write_req_threads];

	if (do_commits) {
		for (uint32_t k = 0; k < g_scfg.write_req_threads; k++) {
			if (pthread_create(&write_req_tids[k], NULL,
					run_generate_write_reqs, NULL) != 0) {
				fprintf(stdout, "ERROR: create write request thread\n");
				exit(-1);
			}
		}
	}

	fprintf(stdout, "\nHISTOGRAM NAMES\n");

	if (do_reads) {
		fprintf(stdout, "reads\n");
		fprintf(stdout, "device-reads\n");

		for (uint32_t d = 0; d < g_scfg.num_devices; d++) {
			fprintf(stdout, "%s\n", g_devices[d].read_hist_tag);
		}
	}

	if (g_scfg.write_reqs_per_sec != 0) {
		fprintf(stdout, "large-block-reads\n");
		fprintf(stdout, "large-block-writes\n");
	}

	if (do_commits) {
		fprintf(stdout, "writes\n");
		fprintf(stdout, "device-writes\n");

		for (uint32_t d = 0; d < g_scfg.num_devices; d++) {
			fprintf(stdout, "%s\n", g_devices[d].write_hist_tag);
		}
	}

	fprintf(stdout, "\n");

	uint64_t now_us = 0;
	uint64_t count = 0;

	while (g_running && (now_us = get_us()) < run_stop_us) {
		count++;

		int64_t sleep_us = (int64_t)
				((count * g_scfg.report_interval_us) -
						(now_us - g_run_start_us));

		if (sleep_us > 0) {
			usleep((uint32_t)sleep_us);
		}

		fprintf(stdout, "after %" PRIu64 " sec:\n",
				(count * g_scfg.report_interval_us) / 1000000);

		fprintf(stdout, "requests-queued: %" PRIu32 "\n",
				atomic32_get(g_reqs_queued));

		if (do_reads) {
			histogram_dump(g_read_hist, "reads");
			histogram_dump(g_raw_read_hist, "device-reads");

			for (uint32_t d = 0; d < g_scfg.num_devices; d++) {
				histogram_dump(g_devices[d].raw_read_hist,
						g_devices[d].read_hist_tag);
			}
		}

		if (g_scfg.write_reqs_per_sec != 0) {
			histogram_dump(g_large_block_read_hist, "large-block-reads");
			histogram_dump(g_large_block_write_hist, "large-block-writes");
		}

		if (do_commits) {
			histogram_dump(g_write_hist, "writes");
			histogram_dump(g_raw_write_hist, "device-writes");

			for (uint32_t d = 0; d < g_scfg.num_devices; d++) {
				histogram_dump(g_devices[d].raw_write_hist,
						g_devices[d].write_hist_tag);
			}
		}

		fprintf(stdout, "\n");
		fflush(stdout);
	}

	g_running = false;

	if (do_reads) {
		for (uint32_t k = 0; k < g_scfg.read_req_threads; k++) {
			pthread_join(read_req_tids[k], NULL);
		}
	}

	if (do_commits) {
		for (uint32_t k = 0; k < g_scfg.write_req_threads; k++) {
			pthread_join(write_req_tids[k], NULL);
		}
	}

	for (uint32_t j = 0; j < n_trans_tids; j++) {
		pthread_join(trans_tids[j], NULL);
	}

	for (uint32_t i = 0; i < g_scfg.num_queues; i++) {
		queue_destroy(g_trans_qs[i]);
	}

	for (uint32_t d = 0; d < g_scfg.num_devices; d++) {
		device* dev = &g_devices[d];

		if (g_scfg.tomb_raider) {
			pthread_join(dev->tomb_raider_thread, NULL);
		}

		if (g_scfg.write_reqs_per_sec != 0) {
			pthread_join(dev->large_block_read_thread, NULL);
			pthread_join(dev->large_block_write_thread, NULL);
		}

		fd_close_all(dev);
		queue_destroy(dev->fd_q);
		free(dev->raw_read_hist);
		free(dev->raw_write_hist);
	}

	free(g_large_block_read_hist);
	free(g_large_block_write_hist);
	free(g_raw_read_hist);
	free(g_read_hist);
	free(g_raw_write_hist);
	free(g_write_hist);

	return 0;
}