예제 #1
0
mat kmeans(Array<vec> &DB, int SIZE, int NOITER, bool VERBOSE)
{
  int    DIM = DB(0).length(), T = DB.length();
  mat    codebook(DIM, SIZE);
  int    n, i, j;
  double   D, Dold;
  ivec   ind(SIZE);

  for (i = 0;i < SIZE;i++) {
    ind(i) = randi(0, T - 1);
    j = 0;
    while (j < i) {
      if (ind(j) == ind(i)) {
        ind(i) = randi(0, T - 1);
        j = 0;
      }
      j++;
    }
    codebook.set_col(i, DB(ind(i)));
  }


  if (VERBOSE) std::cout << "Training VQ..." << std::endl ;

  D = 1E20;
  for (n = 0;n < NOITER;n++) {
    Dold = D;
    D = kmeansiter(DB, codebook);
    if (VERBOSE) std::cout << n << ": " << D / T << " ";
    if (std::abs((D - Dold) / D) < 1e-4) break;
  }
  return codebook;
}
예제 #2
0
파일: Gene.cpp 프로젝트: bog2k3/bugs
Gene Gene::createRandomAttribGene() {
	GeneAttribute g;
	g.attribute = (gene_part_attribute_type)randi(GENE_ATTRIB_INVALID+1, GENE_ATTRIB_END-1);
	g.value.set(randf());
	g.attribIndex.set(randi(constants::MAX_ATTRIB_INDEX_COUNT));
	return g;
}
예제 #3
0
파일: Gene.cpp 프로젝트: bog2k3/bugs
Gene Gene::createRandomJointOffsetGene(int spaceLeftAfter) {
	GeneJointOffset g;
	g.maxDepth.set(randi(5));
	g.minDepth.set(0);
	g.offset.set(randi(spaceLeftAfter));
	return g;
}
예제 #4
0
파일: Body.cpp 프로젝트: fzzr-/2dboy
Body::Body(BodyType type, float posx, float posy, float velx, float vely)
{
	mType = type;
	mPos.x = posx;
	mPos.y = posy;
	mVel.x = velx;
	mVel.y = vely;
	mRotVel = 0;
	mRot = 0;
	mTimeOfDeath = 0;

	int w = Boy::Environment::screenWidth();
	int h = Boy::Environment::screenHeight();

	switch (mType)
	{
	case BIG_ASTEROID:
		mImage = Boy::Environment::getImage(
			Boy::UString::format("IMAGE_ASTEROID_BIG_%d",randi(1,3)).toUtf8());
		mRadius = 100;
		do
		{
			mPos.x = (float)randi(0,w);
			mPos.y = (float)randi(0,h);
		}
		while (dist(mPos.x,mPos.y,w/2.0f,h/2.0f) < mRadius+100);
		mVel = rotate(BoyLib::Vector2(BIG_ASTEROID_SPEED, 0), randf(0,6.28f));
		mRotVel = randf(-ASTEROID_ROTSPEED,ASTEROID_ROTSPEED);
		mRot = randf(0,6.28f);
		break;
	case MEDIUM_ASTEROID:
		mImage = Boy::Environment::getImage(
			Boy::UString::format("IMAGE_ASTEROID_MEDIUM_%d",randi(1,3)).toUtf8());
		mRadius = 50;
		mVel = rotate(BoyLib::Vector2(MEDIUM_ASTEROID_SPEED, 0), randf(0,6.28f));
		mRotVel = randf(-ASTEROID_ROTSPEED,ASTEROID_ROTSPEED);
		mRot = randf(0,6.28f);
		break;
	case SMALL_ASTEROID:
		mImage = Boy::Environment::getImage(
			Boy::UString::format("IMAGE_ASTEROID_SMALL_%d",randi(1,3)).toUtf8());
		mRadius = 25;
		mVel = rotate(BoyLib::Vector2(SMALL_ASTEROID_SPEED, 0), randf(0,6.28f));
		mRotVel = randf(-ASTEROID_ROTSPEED,ASTEROID_ROTSPEED);
		mRot = randf(0,6.28f);
		break;
	case SHIP:
		mImage = Boy::Environment::getImage("IMAGE_SHIP");
		mRadius = 20;
		mPos.x = w/2.0f;
		mPos.y = h/2.0f;
		break;
	case BULLET:
		mImage = Boy::Environment::getImage("IMAGE_BULLET");
		mRadius = 1;
		mTimeOfDeath = Boy::Environment::instance()->getTime() + BULLET_DURATION;
		break;
	}
}
예제 #5
0
파일: Gene.cpp 프로젝트: bog2k3/bugs
Gene Gene::createRandomProteinGene() {
	GeneProtein g;
	g.maxDepth.set(randi(8));
	g.minDepth.set(0);
	g.protein.set((gene_protein_type)randi(GENE_PROT_NONE+1, GENE_PROT_END-1));
	g.targetSegment.set(randi(BodyPart::MAX_CHILDREN));
	return g;
}
예제 #6
0
파일: Gene.cpp 프로젝트: bog2k3/bugs
Gene Gene::createRandomOffsetGene(int spaceLeftAfter) {
	GeneOffset g;
	g.maxDepth.set(randi(5));
	g.minDepth.set(0);
	g.targetSegment.set(randi(BodyPart::MAX_CHILDREN));
	g.offset.set(randi(spaceLeftAfter));
	return g;
}
예제 #7
0
파일: Gene.cpp 프로젝트: bog2k3/bugs
Gene Gene::createRandomSynapseGene(int nNeurons) {
	GeneSynapse g;
	g.from.set(randi(nNeurons-1));
	g.to.set(randi(nNeurons-1));
	g.weight.set(randf()*0.2f);
	g.priority.set(randf()*10);
	return g;
}
예제 #8
0
파일: Gene.cpp 프로젝트: bog2k3/bugs
Gene Gene::createRandomSkipGene(int spaceLeftAfter) {
	GeneSkip g;
	g.minDepth.set(randi(10));
	g.maxDepth.set(g.minDepth + randi(10-g.minDepth));
	// use a random distribution that favors small values:
	g.count.set(sqr(randd()) * spaceLeftAfter);
	return g;
}
예제 #9
0
/**********************************************************************
 * 迭代
 **********************************************************************/
void tran()
{
    int i, j, pos;
    int k;
    //找当前种群最优个体 
    min = cur[0];
    for ( i=1; i<SIZE-1; i++ ) {
        if ( cur[i].fitness<min.fitness ) {
            min = cur[i];
        }
    }
    for ( k=0; k<SIZE; k+=2 ) {
        // 选择交叉个体 
        i = sel();
        j = sel();
        
        // 选择交叉位置 
        pos = randi(LEN-1);
        
        //交叉
        if ( randd()<P_CORSS ) {
            memcpy(next[k].x, cur[i].x, pos);
            memcpy(next[k].x+pos, cur[j].x+pos, LEN-pos);
            memcpy(next[k+1].x,cur[j].x,pos);
            memcpy(next[k+1].x+pos,cur[i].x+pos,LEN-pos);
        } else {
            memcpy(next[k].x,cur[i].x,LEN);
            memcpy(next[k+1].x,cur[j].x,LEN);
        }
        //变异
        if ( randd()<P_MUTATION ) {
            pos = randi(LEN-1);
            next[k].x[pos] ^= next[k].x[pos];
         
            pos = randi(LEN-1);
            next[k+1].x[pos] ^= next[k+1].x[pos];
        }
    }
    //找下一代的最差个体 
    max = next[0];
    j = 0;
    
    for ( i=1; i<SIZE-1; i++ ) {
        if ( next[i].fitness<min.fitness ) {
            max = next[i];
            j = i;
        }
    }
    //用上一代的最优个体替换下一代的最差个体
    next[j] = min;
    
    memcpy(cur, next, sizeof(cur));
    
    cal_fitness();
}
예제 #10
0
파일: Gene.cpp 프로젝트: bog2k3/bugs
Gene Gene::createRandomBodyAttribGene() {
	GeneBodyAttribute g;
	g.attribute = (gene_body_attribute_type)randi(GENE_BODY_ATTRIB_INVALID+1, GENE_BODY_ATTRIB_END-1);
	switch (g.attribute) {
	case GENE_BODY_ATTRIB_ADULT_LEAN_MASS:
		g.value.set(BodyConst::initialAdultLeanMass);
		break;
	case GENE_BODY_ATTRIB_EGG_MASS:
		g.value.set(BodyConst::initialEggMass);
		break;
	case GENE_BODY_ATTRIB_GROWTH_SPEED:
		g.value.set(BodyConst::initialGrowthSpeed);
		break;
	case GENE_BODY_ATTRIB_INITIAL_FAT_MASS_RATIO:
		g.value.set(BodyConst::initialFatMassRatio);
		break;
	case GENE_BODY_ATTRIB_MIN_FAT_MASS_RATIO:
		g.value.set(BodyConst::initialMinFatMassRatio);
		break;
	case GENE_BODY_ATTRIB_REPRODUCTIVE_MASS_RATIO:
		g.value.set(BodyConst::initialReproductiveMassRatio);
		break;
	default:
		ERROR("unhandled body attrib type: " << g.attribute);
	}
	return g;
}
예제 #11
0
//render between 0-1.0f
void render_doids(int _seed)
{
	int old_seed = seed;
	seed = _seed;
	{
	int nboxes = 1 + randi(3);
	//random size
	float w = 0.1f + 0.5f*rand01();
	float h = (0.7f - w) + 0.5f* rand01();
	float hg = 0.01f + 0.2f*rand01();

	//pos
	float x = (1.0f - w) * rand01();
	float y = (1.0f - h*nboxes) * rand01();

	while(nboxes--)
	{
		glPushMatrix();
		glTranslatef(x, y + (h+ 0.01f)*nboxes, hg);
		glScalef(w, h, hg);
		cube_w();
		glPopMatrix();
		
	}
	}

	seed = old_seed;

	
}
예제 #12
0
core::MonteCarloMoverResult RelativePositionMover::do_propose() {
  last_transformation_ = rbA_.get_reference_frame().get_transformation_to();
  ::boost::uniform_real<> zeroone(0., 1.);
  double p = zeroone(random_number_generator);
  if (p < probability_of_random_move_) {
    algebra::Vector3D translation = algebra::get_random_vector_in(
        algebra::Sphere3D(rbA_.get_coordinates(), max_translation_));
    algebra::Vector3D axis = algebra::get_random_vector_on(
        algebra::Sphere3D(algebra::Vector3D(0.0, 0.0, 0.0), 1.));
    ::boost::uniform_real<> rand(-max_angle_, max_angle_);
    Float angle = rand(random_number_generator);
    algebra::Rotation3D r = algebra::get_rotation_about_axis(axis, angle);
    algebra::Rotation3D rc =
        r * rbA_.get_reference_frame().get_transformation_to().get_rotation();
    algebra::Transformation3D t(rc, translation);
    IMP_LOG_TERSE("proposing a random move " << t << std::endl);
    //   std::cout << "proposing a random move for " << rbA_->get_name() << " "
    //         << rbA_ << " Transformation " <<  t << std::endl;
    rbA_.set_reference_frame(algebra::ReferenceFrame3D(t));
  } else {
    ::boost::uniform_int<> randi(0, reference_rbs_.size() - 1);
    unsigned int i = randi(random_number_generator);

    ::boost::uniform_int<> randj(0, transformations_map_[i].size() - 1);
    unsigned int j = randj(random_number_generator);

    algebra::Transformation3D Tint = transformations_map_[i][j];
    IMP_LOG_TERSE("proposing a relative move. Rigid body "
                  << i << "Internal transformation " << j << " " << Tint
                  << std::endl);
    //    std::cout << "Proposing a relative move. Rigid body " <<
    // rbA_->get_name()
    //      << " " << rbA_  << " Relative transformation " <<  Tint<< std::endl;
    // core::RigidBody rb = reference_rbs_[i];
    algebra::Transformation3D T_reference =
        reference_rbs_[i].get_reference_frame().get_transformation_to();
    // std::cout << "RF receptor  ===> " << T_reference << std::endl;
    // new absolute reference frame for the rigid body of the ligand
    algebra::Transformation3D Tdock = algebra::compose(T_reference, Tint);
    rbA_.set_reference_frame(algebra::ReferenceFrame3D(Tdock));
    //    std::cout << "Finished proposing. Reference frame for the ligand"
    //          << rbA_.get_reference_frame() << std::endl;
  }
  return core::MonteCarloMoverResult(
      ParticleIndexes(1, rbA_.get_particle_index()), 1.0);
}
예제 #13
0
파일: Shell.cpp 프로젝트: kuro/fyreware
void Shell::explode ()
{
    QList<QScriptProgram> programs = scene->shellPrograms().values();
    QScriptProgram shellProgram = programs[randi(programs.size())];
    Cluster* cluster = new Cluster(d->trx.getOrigin(), shellProgram, scene);
    connect(scene, SIGNAL(update(qreal)), cluster, SLOT(update(qreal)));
    connect(scene, SIGNAL(drawClusters()), cluster, SLOT(draw()));
}
예제 #14
0
int *random_indicies_new(struct tree *t1, struct tree *t2)
{
    int *indicies = malloc(sizeof(int) * 2);

    if (t1->size > 2) {
        indicies[0] = randi(0, t1->size - 2);
    } else {
        indicies[0] = 0;
    }

    if (t2->size > 2) {
        indicies[1] = randi(0, t2->size - 2);
    } else {
        indicies[1] = 0;
    }

    return indicies;
}
예제 #15
0
//manage all bullet control
void final_boss_fire(struct actor_t* a)
{
	random_ship_t* s = (random_ship_t*)a->child;

	if(boss_timers.global-- == 0)
	{
		boss_timers.burst = 2 + randi(12);
		boss_timers.cburst = 0;
		boss_timers.inter_burst = 15 + randi(30);
		boss_timers.cinter_burst = boss_timers.inter_burst;
		boss_timers.type = randi(2) == 0?FIRE_RANDOM: FIRE_STAR;

		boss_timers.global = 90 + randi(200);
    }

	boss_timers.cinter_burst--;
	if(boss_timers.cinter_burst == 0)
	{
		boss_timers.burst--;
		if(boss_timers.burst >= 0)
		{
			switch(boss_timers.type)
			{
				case FIRE_RANDOM:
					boss_random_fire(a,7);
					break;
				case FIRE_STAR:
					boss_star_fire(a, 1.0f);
					break;

			}

			boss_timers.cinter_burst = boss_timers.inter_burst;
		}
	}




}
예제 #16
0
bool test_once(shenidam_t processor, float* base,size_t total_num_samples,double sample_rate,size_t num_samples_track, double sigma)
{
    int real_in = randi(0,total_num_samples-num_samples_track-1);
    float* track = (float*) std::malloc(num_samples_track*sizeof(float));
    std::memcpy(track,&base[real_in],num_samples_track*sizeof(float));
    add_gaussian_noise(track,num_samples_track,sigma);
    size_t dummy;
    int in;
    shenidam_get_audio_range(processor,FORMAT_SINGLE,track,num_samples_track,sample_rate,&in,&dummy);
    std::free(track);
    return std::abs(in - real_in)<sample_rate*threshold;

}
예제 #17
0
/*****************************************************************************
 * Population initial
 *****************************************************************************/
void population_init()
{
    int tmp;
    int i;
    int j;
  
    for ( i=0; i<SIZE; i++ ) {
        tmp = randi(N);
        for ( j=0; j<LEN; j++ ) {
            cur[i].x[j] = tmp%2;
            tmp = tmp>>1;
        }
    }
    cal_fitness();
}
예제 #18
0
파일: synth-funcs.c 프로젝트: bion/ats
void synth_residual_only(float a1, float a2,float freq,float frame_samps,int op,float *oscpt, RANDI* rdata)
{
  int k, samps=(int)frame_samps;
  float  a_inc, amp;
  float out=0.;
  
  if(a1!=0. || a2!=0.) { //no synthesis if no amplitude
    amp  =  a1;
    a_inc= (a2 - a1) / frame_samps;
    
    for(k=0; k<samps; k++) { 
      out  = ioscilator(amp,freq,op,oscpt);  
      amp  += a_inc;
      frbuf[k] += out * sparams->ramp * randi(rdata); 
    }
  }
}
예제 #19
0
void final_boss_init(struct actor_t* a)
{
	a->pos[2] = -100.0f;
	SHIP_generate(a, randi(12312312), 13, 6);
	a->collide_size[0] = 13.0f;
	a->collide_size[1] = 4.0f;

	boss_timers.global = 0;
	boss_timers.burst = 0;
	boss_timers.inter_burst = 0;

	final_boss = a;
	a->life = 1.1f;

	
	
}
예제 #20
0
파일: quick.c 프로젝트: juliords/pucrio_aa
static int do_quick_select(int *v, int low, int high, int k)
{
	if (low == high)
		return v[low];
	
	int pivot = randi(low, high), size_l;
	pivot = partition(v, low, high, pivot);
	size_l = pivot - low;
	
	if (toc() > TIME_LIMIT)
		return ABORTED;
	
	if (size_l == k - 1)
		return v[pivot];
	else if (size_l > k - 1)
		return do_quick_select(v, low, pivot - 1, k);
	else
		return do_quick_select(v, pivot + 1, high, k - size_l - 1);
}
예제 #21
0
/* This is the main routine, doRun. It is a bank of 2x6 randomly varying
   delays which feed back into themselves in a tricky way.
*/
void
RVB::doRun(double *input, double *output, long counter)
{
   register int i, j;
   double sig, delsig;

   for (i = 0; i < 2; ++i) {                /* loop for 2 output chans */
      output[i] = 0.0;
      for (j = 0; j < 6; ++j) {             /* loop for 6 delays per chan */
		 ReverbData *rvb = &m_rvbData[i][j];
	 	 ReverbData *rvb2 = rvb;
	 
         sig = input[i] + rvb->delin;      /* combine input w/ delay return */

         /* get new delay length (random) then 
            put samp into delay & get new delayed samp out
         */
         double delay = Nsdelay[i][j] + randi(&rvb->Rand_info[0]);
         delsig = delpipe(sig, &rvb->deltap, delay, rvbdelsize, &rvb->Rvb_del[0]);

#ifdef USE_BUGGY_CODE
         if (i == 1 && j > 0)
	     rvb2 = &m_rvbData[0][j];	// remap "incorrectly"
#endif
         /* filter with air simulation filters, set gains */
         rvb->delout = tone(delsig, &rvb2->Rvb_air[0]);

         /* sum outputs of all delays for 2 channels */
         output[i] += rvb->delout;
      }
      /* run outputs through Allpass filter */
	  double sigout = Allpass(output[i], &allpassTap[i], Allpass_del[i]);
#ifdef USE_HI_PASS
	  output[i] = 0.51 * sigout - 0.49 * m_rvbPast[i];	// Hi pass FIR filter
      m_rvbPast[i] = sigout;
#else
	  output[i] = sigout;
#endif
   }

   /* redistribute delpipe outs into delpipe ins */
   matrix_mix();
}
예제 #22
0
/* NOTE: This is identical to randmtzig_gv_randn() below except for the random number generation */
double randmtzig_randn (dsfmt_t *dsfmt)
{
    while (1)
    {
        /* arbitrary mantissa (selected by randi, with 1 bit for sign) */
        const randmtzig_uint64_t r = randi(dsfmt);
        const randmtzig_int64_t rabs=r>>1;
        const int idx = (int)(rabs&0xFF);
        const double x = ( r&1 ? -rabs : rabs) * wi[idx];

        if (rabs < (randmtzig_int64_t)ki[idx]) {
            return x;        /* 99.3% of the time we return here 1st try */
        } else if (idx == 0) {
            /* As stated in Marsaglia and Tsang
             *
             * For the normal tail, the method of Marsaglia[5] provides:
             * generate x = -ln(U_1)/r, y = -ln(U_2), until y+y > x*x,
             * then return r+x. Except that r+x is always in the positive
             * tail!!!! Any thing random might be used to determine the
             * sign, but as we already have r we might as well use it
             *
             * [PAK] but not the bottom 8 bits, since they are all 0 here!
             */
            double xx, yy;
            do {
                xx = - ZIGGURAT_NOR_INV_R * log (randu(dsfmt));
                yy = - log (randu(dsfmt));
            }
            while ( yy+yy <= xx*xx);
            return (rabs&0x100 ? -ZIGGURAT_NOR_R-xx : ZIGGURAT_NOR_R+xx);
        } else if ((fi[idx-1] - fi[idx]) * randu(dsfmt) + fi[idx] < exp(-0.5*x*x)) {
            return x;
        }

    }
}
예제 #23
0
파일: Gene.cpp 프로젝트: bog2k3/bugs
Gene Gene::createRandomNeuronOutputCoordGene(int nNeurons) {
	GeneNeuronOutputCoord g;
	g.srcNeuronVirtIndex.set(randi(nNeurons-1));
	g.outCoord.set(randf() * BodyConst::MaxVMSCoordinateValue);
	return g;
}
예제 #24
0
UBool
ResourceBundleTest::testTag(const char* frag,
                            UBool in_Root,
                            UBool in_te,
                            UBool in_te_IN)
{
    int32_t failOrig = fail;

    // Make array from input params

    UBool is_in[] = { in_Root, in_te, in_te_IN };

    const char* NAME[] = { "ROOT", "TE", "TE_IN" };

    // Now try to load the desired items

    char tag[100];
    UnicodeString action;

    int32_t i,j,actual_bundle;
//    int32_t row,col;
    int32_t index;
    UErrorCode status = U_ZERO_ERROR;
    const char* testdatapath;
    testdatapath=loadTestData(status);
    if(U_FAILURE(status))
    {
        dataerrln("Could not load testdata.dat %s " + UnicodeString(u_errorName(status)));
        return FALSE;
    }

    for (i=0; i<bundles_count; ++i)
    {
        action = "Constructor for ";
        action += param[i].name;

        status = U_ZERO_ERROR;
        ResourceBundle theBundle( testdatapath, *param[i].locale, status);
        //ResourceBundle theBundle( "c:\\icu\\icu\\source\\test\\testdata\\testdata", *param[i].locale, status);
        CONFIRM_UErrorCode(status, param[i].expected_constructor_status, action);

        if(i == 5)
          actual_bundle = 0; /* ne -> default */
        else if(i == 3)
          actual_bundle = 1; /* te_NE -> te */
        else if(i == 4)
          actual_bundle = 2; /* te_IN_NE -> te_IN */
        else
          actual_bundle = i;


        UErrorCode expected_resource_status = U_MISSING_RESOURCE_ERROR;
        for (j=e_te_IN; j>=e_Root; --j)
        {
            if (is_in[j] && param[i].inherits[j])
            {
                if(j == actual_bundle) /* it's in the same bundle OR it's a nonexistent=default bundle (5) */
                  expected_resource_status = U_ZERO_ERROR;
                else if(j == 0)
                  expected_resource_status = U_USING_DEFAULT_WARNING;
                else
                  expected_resource_status = U_USING_FALLBACK_WARNING;
                
                break;
            }
        }

        UErrorCode expected_status;

        UnicodeString base;
        for (j=param[i].where; j>=0; --j)
        {
            if (is_in[j])
            {
                base = NAME[j];
                break;
            }
        }

        //--------------------------------------------------------------------------
        // string

        uprv_strcpy(tag, "string_");
        uprv_strcat(tag, frag);

        action = param[i].name;
        action += ".getString(";
        action += tag;
        action += ")";


        status = U_ZERO_ERROR;

        UnicodeString string(theBundle.getStringEx(tag, status));

        if(U_FAILURE(status)) {
            string.setTo(TRUE, kErrorUChars, kErrorLength);
        }

        CONFIRM_UErrorCode(status, expected_resource_status, action);

        UnicodeString expected_string(kErrorUChars);
        if (U_SUCCESS(status)) {
            expected_string = base;
        }

        CONFIRM_EQ(string, expected_string, action);

        //--------------------------------------------------------------------------
        // array

        uprv_strcpy(tag, "array_");
        uprv_strcat(tag, frag);

        action = param[i].name;
        action += ".get(";
        action += tag;
        action += ")";

        status = U_ZERO_ERROR;
        ResourceBundle arrayBundle(theBundle.get(tag, status));
        CONFIRM_UErrorCode(status, expected_resource_status, action);
        int32_t count = arrayBundle.getSize();

        if (U_SUCCESS(status))
        {
            CONFIRM_GE(count, 1, action);

            for (j=0; j < count; ++j)
            {
                char buf[32];
                UnicodeString value(arrayBundle.getStringEx(j, status));
                expected_string = base;
                expected_string += itoa(j,buf);
                CONFIRM_EQ(value, expected_string, action);
            }

            action = param[i].name;
            action += ".getStringEx(";
            action += tag;
            action += ")";

            for (j=0; j<100; ++j)
            {
                index = count ? (randi(count * 3) - count) : (randi(200) - 100);
                status = U_ZERO_ERROR;
                string = kErrorUChars;
                UnicodeString t(arrayBundle.getStringEx(index, status));
                expected_status = (index >= 0 && index < count) ? expected_resource_status : U_MISSING_RESOURCE_ERROR;
                CONFIRM_UErrorCode(status, expected_status, action);

                if (U_SUCCESS(status))
                {
                    char buf[32];
                    expected_string = base;
                    expected_string += itoa(index,buf);
                }
                else
                {
                    expected_string = kErrorUChars;
                }
                CONFIRM_EQ(string, expected_string, action);
            }
        }
        else if (status != expected_resource_status)
        {
            record_fail("Error getting " + (UnicodeString)tag);
            return (UBool)(failOrig != fail);
        }

    }

    return (UBool)(failOrig != fail);
}
예제 #25
0
UBool
NewResourceBundleTest::testTag(const char* frag,
                            UBool in_Root,
                            UBool in_te,
                            UBool in_te_IN)
{
    int32_t failOrig = fail;

    // Make array from input params

    UBool is_in[] = { in_Root, in_te, in_te_IN };

    const char* NAME[] = { "ROOT", "TE", "TE_IN" };

    // Now try to load the desired items

    char tag[100];
    UnicodeString action;

    int32_t i,j,row,col, actual_bundle;
    int32_t index;
    const char* testdatapath;

    UErrorCode status = U_ZERO_ERROR;
    testdatapath=loadTestData(status);
    if(U_FAILURE(status))
    {
        dataerrln("Could not load testdata.dat %s " + UnicodeString(u_errorName(status)));
        return FALSE;
    }

    for (i=0; i<bundles_count; ++i)
    {
        action = "Constructor for ";
        action += param[i].name;

        status = U_ZERO_ERROR;
        ResourceBundle theBundle( testdatapath, *param[i].locale, status);
        //ResourceBundle theBundle( "c:\\icu\\icu\\source\\test\\testdata\\testdata", *param[i].locale, status);
        CONFIRM_UErrorCode(status,param[i].expected_constructor_status);

        if(i == 5)
          actual_bundle = 0; /* ne -> default */
        else if(i == 3)
          actual_bundle = 1; /* te_NE -> te */
        else if(i == 4)
          actual_bundle = 2; /* te_IN_NE -> te_IN */
        else
          actual_bundle = i;


        UErrorCode expected_resource_status = U_MISSING_RESOURCE_ERROR;
        for (j=e_te_IN; j>=e_Root; --j)
        {
            if (is_in[j] && param[i].inherits[j])
              {
                if(j == actual_bundle) /* it's in the same bundle OR it's a nonexistent=default bundle (5) */
                  expected_resource_status = U_ZERO_ERROR;
                else if(j == 0)
                  expected_resource_status = U_USING_DEFAULT_WARNING;
                else
                  expected_resource_status = U_USING_FALLBACK_WARNING;
                
                break;
            }
        }

        UErrorCode expected_status;

        UnicodeString base;
        for (j=param[i].where; j>=0; --j)
        {
            if (is_in[j])
            {
                base = NAME[j];
                break;
            }
        }

        //--------------------------------------------------------------------------
        // string

        uprv_strcpy(tag, "string_");
        uprv_strcat(tag, frag);

        action = param[i].name;
        action += ".getStringEx(";
        action += tag;
        action += ")";


        status = U_ZERO_ERROR;
        UnicodeString string = theBundle.getStringEx(tag, status);
        if(U_FAILURE(status)) {
            string.setTo(TRUE, kErrorUChars, kErrorLength);
        }

        CONFIRM_UErrorCode(status, expected_resource_status);

        UnicodeString expected_string(kErrorUChars);
        if (U_SUCCESS(status)) {
            expected_string = base;
        }

        CONFIRM_EQ(string, expected_string);

        //--------------------------------------------------------------------------
        // array   ResourceBundle using the key

        uprv_strcpy(tag, "array_");
        uprv_strcat(tag, frag);

        action = param[i].name;
        action += ".get(";
        action += tag;
        action += ")";

        int32_t count = kERROR_COUNT;
        status = U_ZERO_ERROR;
        ResourceBundle array = theBundle.get(tag, status);
        CONFIRM_UErrorCode(status,expected_resource_status);


        if (U_SUCCESS(status))
        {
            //confirm the resource type is an array
            UResType bundleType=array.getType();
            CONFIRM_EQ(bundleType, URES_ARRAY);

            count=array.getSize();
            CONFIRM_GE(count,1);
           
            for (j=0; j<count; ++j)
            {
                char buf[32];
                expected_string = base;
                expected_string += itoa(j,buf);
                CONFIRM_EQ(array.getNextString(status),expected_string);
            }

        }
        else
        {
            CONFIRM_EQ(count,kERROR_COUNT);
            //       CONFIRM_EQ((int32_t)(unsigned long)array,(int32_t)0);
            count = 0;
        }

        //--------------------------------------------------------------------------
        // arrayItem ResourceBundle using the index


        for (j=0; j<100; ++j)
        {
            index = count ? (randi(count * 3) - count) : (randi(200) - 100);
            status = U_ZERO_ERROR;
            string = kErrorUChars;
            ResourceBundle array = theBundle.get(tag, status);
            if(!U_FAILURE(status)){
                UnicodeString t = array.getStringEx(index, status);
                if(!U_FAILURE(status)) {
                   string=t;
                }
            }

            expected_status = (index >= 0 && index < count) ? expected_resource_status : U_MISSING_RESOURCE_ERROR;
            CONFIRM_UErrorCode(status,expected_status);

            if (U_SUCCESS(status)){
                char buf[32];
                expected_string = base;
                expected_string += itoa(index,buf);
            } else {
                expected_string = kErrorUChars;
            }
               CONFIRM_EQ(string,expected_string);

        }

        //--------------------------------------------------------------------------
        // 2dArray

        uprv_strcpy(tag, "array_2d_");
        uprv_strcat(tag, frag);

        action = param[i].name;
        action += ".get(";
        action += tag;
        action += ")";


        int32_t row_count = kERROR_COUNT, column_count = kERROR_COUNT;
        status = U_ZERO_ERROR;
        ResourceBundle array2d=theBundle.get(tag, status);

        //const UnicodeString** array2d = theBundle.get2dArray(tag, row_count, column_count, status);
        CONFIRM_UErrorCode(status,expected_resource_status);

        if (U_SUCCESS(status))
        {
            //confirm the resource type is an 2darray
            UResType bundleType=array2d.getType();
            CONFIRM_EQ(bundleType, URES_ARRAY);

            row_count=array2d.getSize();
            CONFIRM_GE(row_count,1);

            for(row=0; row<row_count; ++row){
                ResourceBundle tablerow=array2d.get(row, status);
                CONFIRM_UErrorCode(status, expected_resource_status);
                if(U_SUCCESS(status)){
                    //confirm the resourcetype of each table row is an array
                    UResType rowType=tablerow.getType();
                    CONFIRM_EQ(rowType, URES_ARRAY);

                    column_count=tablerow.getSize();
                    CONFIRM_GE(column_count,1);

                    for (col=0; j<column_count; ++j) {
                           char buf[32];
                           expected_string = base;
                           expected_string += itoa(row,buf);
                           expected_string += itoa(col,buf);
                           CONFIRM_EQ(tablerow.getNextString(status),expected_string);
                    }
                }
            }
        }else{
            CONFIRM_EQ(row_count,kERROR_COUNT);
            CONFIRM_EQ(column_count,kERROR_COUNT);
             row_count=column_count=0;
        }




       //--------------------------------------------------------------------------
       // 2dArrayItem
       for (j=0; j<200; ++j)
       {
           row = row_count ? (randi(row_count * 3) - row_count) : (randi(200) - 100);
           col = column_count ? (randi(column_count * 3) - column_count) : (randi(200) - 100);
           status = U_ZERO_ERROR;
           string = kErrorUChars;
           ResourceBundle array2d=theBundle.get(tag, status);
           if(U_SUCCESS(status)){
                ResourceBundle tablerow=array2d.get(row, status);
                if(U_SUCCESS(status)) {
                    UnicodeString t=tablerow.getStringEx(col, status);
                    if(U_SUCCESS(status)){
                       string=t;
                    }
                }
           }
           expected_status = (row >= 0 && row < row_count && col >= 0 && col < column_count) ?
                                  expected_resource_status: U_MISSING_RESOURCE_ERROR;
           CONFIRM_UErrorCode(status,expected_status);

           if (U_SUCCESS(status)){
               char buf[32];
               expected_string = base;
               expected_string += itoa(row,buf);
               expected_string += itoa(col,buf);
           } else {
               expected_string = kErrorUChars;
           }
               CONFIRM_EQ(string,expected_string);

        }

        //--------------------------------------------------------------------------
        // taggedArray

        uprv_strcpy(tag, "tagged_array_");
        uprv_strcat(tag, frag);

        action = param[i].name;
        action += ".get(";
        action += tag;
        action += ")";

        int32_t         tag_count;
        status = U_ZERO_ERROR;

        ResourceBundle tags=theBundle.get(tag, status);
        CONFIRM_UErrorCode(status, expected_resource_status);

        if (U_SUCCESS(status)) {
            UResType bundleType=tags.getType();
            CONFIRM_EQ(bundleType, URES_TABLE);

            tag_count=tags.getSize();
            CONFIRM_GE((int32_t)tag_count, (int32_t)0); 

            for(index=0; index <tag_count; index++){
                ResourceBundle tagelement=tags.get(index, status);
                UnicodeString key=tagelement.getKey();
                UnicodeString value=tagelement.getNextString(status);
                logln("tag = " + key + ", value = " + value );
                if(key.startsWith("tag") && value.startsWith(base)){
                    record_pass();
                }else{
                    record_fail();
                }

            }

            for(index=0; index <tag_count; index++){
                ResourceBundle tagelement=tags.get(index, status);
                const char *tkey=NULL;
                UnicodeString value=tagelement.getNextString(&tkey, status);
                UnicodeString key(tkey);
                logln("tag = " + key + ", value = " + value );
                if(value.startsWith(base)){
                    record_pass();
                }else{
                    record_fail();
                }
            }

        }else{
            tag_count=0;
        }




        //--------------------------------------------------------------------------
        // taggedArrayItem

        action = param[i].name;
        action += ".get(";
        action += tag;
        action += ")";

        count = 0;
        for (index=-20; index<20; ++index)
        {
            char buf[32];
            status = U_ZERO_ERROR;
            string = kErrorUChars;
            char item_tag[8];
            uprv_strcpy(item_tag, "tag");
            uprv_strcat(item_tag, itoa(index,buf));
            ResourceBundle tags=theBundle.get(tag, status);
            if(U_SUCCESS(status)){
                ResourceBundle tagelement=tags.get(item_tag, status);
                if(!U_FAILURE(status)){
                    UResType elementType=tagelement.getType();
                    CONFIRM_EQ(elementType, (int32_t)URES_STRING);
                    const char* key=tagelement.getKey();
                    CONFIRM_EQ((UnicodeString)key, (UnicodeString)item_tag);
                    UnicodeString t=tagelement.getString(status);
                    if(!U_FAILURE(status)){
                        string=t;
                    }
                }
                if (index < 0) {
                    CONFIRM_UErrorCode(status,U_MISSING_RESOURCE_ERROR);
                }
                else{
                   if (status != U_MISSING_RESOURCE_ERROR) {
                       count++;
                       expected_string = base;
                       expected_string += buf;
                       CONFIRM_EQ(string,expected_string);
                   }
                }
            }

        }
        CONFIRM_EQ(count, tag_count);

    }
    return (UBool)(failOrig == fail);
}
예제 #26
0
void GMapHome::generate(int dW, int dH)
{
    // Generate home

    // Set

    // Width
    int hWidth = 10 + randi(10);

    // Height
    int hHeight = hWidth/2;

    // Create clear slots
    for(int mX = -hWidth; mX < alignX(dW) + hWidth*2; mX++)
    {
        // X
        int x = cameraX(alignX(dW)) + mX;

        for(int mY = -hHeight; mY < alignY(dH) + hHeight*2; mY++)
        {
            // Y
            int y = cameraY(alignY(dH)) + mY;

            // Create

            slot[x][y] = new GMapSlot();
        }
    }

    // Home coords
    const int homeX = -hWidth/2;
    const int homeY = -hHeight/2;

    // Generate

    // Home
    for(int mX = -hWidth/2; mX < hWidth/2; mX++)
    {
        for(int mY = -hHeight/2; mY < hHeight/2; mY++)
        {
            slot[mX][mY] = generateSlot();
        }
    }

    // Walls

    // Up / Down
    for(int mX = -hWidth/2; mX <= hWidth/2; mX++)
    {
        // Wall

        slot[mX][-hHeight/2] = &gMapSlotWall;
        slot[mX][hHeight/2] = &gMapSlotWall;
    }

    // Left / Right
    for(int mY = -hHeight/2; mY <= hHeight/2; mY++)
    {
        // Wall

        slot[-hWidth/2][mY] = &gMapSlotWall;
        slot[hWidth/2][mY] = &gMapSlotWall;
    }

    // Door

    // Select angle (left up / right down)

    // Left Up
    int angleX = homeX;
    int angleY = homeY;

    bool leftUp = true;

    // Right down
    if(luck(50.0f))
    {
        angleX *= -1;
        angleY *= -1;

        leftUp = false;
    }

    // Get indent
    int indentX = 1+randi(hWidth-2);
    int indentY = 1+randi(hHeight-2);

    if(!leftUp)
    {
        indentX *= -1;
        indentY *= -1;
    }

    // Set
    int doorX = angleX + indentX;
    int doorY = angleY + indentY;

    if(luck(50.0f))
    {
        slot[homeX][doorY] = &gMapSlotDoor;
        doorX = angleX;
    }
    else
    {
        slot[doorX][homeY] = &gMapSlotDoor;
        doorY = angleY;
    }

    // Set player coords

    // Get
    int playerX_ = getPlayerX();
    int playerY_ = getPlayerY();

    if(leftUp)
    {
        if(angleX == doorX)
        {
            playerX_ = doorX+1;
            playerY_ = doorY;
        }
        else if(angleY == doorY)
        {
            playerY_ = doorY+1;
            playerX_ = doorX;
        }
    }
    else
    {
        if(angleX == doorX)
        {
            playerX_ = doorX-1;
            playerY_ = doorY;
        }
        else if(angleY == doorY)
        {
            playerY_ = doorY-1;
            playerX_ = doorX;
        }
    }

    // Set
    setPlayerX(playerX_);
    setPlayerY(playerY_);

    // Set free generated slot of player coords
    GMapSlot *slot_;
    while(!slot[getPlayerX()][getPlayerY()]->is_free())
    {
        // Generate
        slot_ = generateSlot();

        // Set
        slot[playerX_][playerY_] = slot_;
    }

    // Generated
    setGenerated(true);
}
예제 #27
0
mat vqtrain(Array<vec> &DB, int SIZE, int NOITER, double STARTSTEP, bool VERBOSE)
{
  int    DIM = DB(0).length();
  vec    x;
  vec    codebook(DIM*SIZE);
  int    n, MinIndex, i, j;
  double   MinS, S, D, step, *xp, *cp;

  for (i = 0;i < SIZE;i++) {
    codebook.replace_mid(i*DIM, DB(randi(0, DB.length() - 1)));
  }
  if (VERBOSE) std::cout << "Training VQ..." << std::endl ;

res:
  D = 0;
  for (n = 0;n < NOITER;n++) {
    step = STARTSTEP * (1.0 - double(n) / NOITER);
    if (step < 0) step = 0;
    x = DB(randi(0, DB.length() - 1)); // seems unnecessary! Check it up.
    xp = x._data();

    MinS = 1E20;
    MinIndex = 0;
    for (i = 0;i < SIZE;i++) {
      cp = &codebook(i * DIM);
      S = sqr(xp[0] - cp[0]);
      for (j = 1;j < DIM;j++) {
        S += sqr(xp[j] - cp[j]);
        if (S >= MinS) goto sune;
      }
      MinS = S;
      MinIndex = i;
    sune:
      i = i;
    }
    D += MinS;
    cp = &codebook(MinIndex * DIM);
    for (j = 0;j < DIM;j++) {
      cp[j] += step * (xp[j] - cp[j]);
    }
    if ((n % 20000 == 0) && (n > 1)) {
      if (VERBOSE) std::cout << n << ": " << D / 20000 << " ";
      D = 0;
    }
  }

  // checking training result
  vec dist(SIZE), num(SIZE);

  dist.clear();
  num.clear();
  for (n = 0;n < DB.length();n++) {
    x = DB(n);
    xp = x._data();
    MinS = 1E20;
    MinIndex = 0;
    for (i = 0;i < SIZE;i++) {
      cp = &codebook(i * DIM);
      S = sqr(xp[0] - cp[0]);
      for (j = 1;j < DIM;j++) {
        S += sqr(xp[j] - cp[j]);
        if (S >= MinS) goto sune2;
      }
      MinS = S;
      MinIndex = i;
    sune2:
      i = i;
    }
    dist(MinIndex) += MinS;
    num(MinIndex) += 1;
  }
  dist = 10 * log10(dist * dist.length() / sum(dist));
  if (VERBOSE) std::cout << std::endl << "Distortion contribution: " << dist << std::endl ;
  if (VERBOSE) std::cout << "Num spread: " << num / DB.length()*100 << " %" << std::endl << std::endl ;
  if (min(dist) < -30) {
    std::cout << "Points without entries! Retraining" << std::endl ;
    j = min_index(dist);
    i = max_index(num);
    codebook.replace_mid(j*DIM, codebook.mid(i*DIM, DIM));
    goto res;
  }

  mat cb(DIM, SIZE);
  for (i = 0;i < SIZE;i++) {
    cb.set_col(i, codebook.mid(i*DIM, DIM));
  }
  return cb;
}
예제 #28
0
파일: Random.cpp 프로젝트: Daivuk/OakNut
 bool randb()
 {
     return randi(0, 1) ? true : false;
 }
예제 #29
0
파일: Gene.cpp 프로젝트: bog2k3/bugs
Gene Gene::createRandomNeuralParamGene(int nNeurons) {
	GeneNeuralParam g;
	g.targetNeuron.set(randi(nNeurons-1));
	g.value.set(srandf());
	return g;
}
예제 #30
0
파일: Gene.cpp 프로젝트: bog2k3/bugs
Gene Gene::createRandomTransferFuncGene(int nNeurons) {
	GeneTransferFunction g;
	g.functionID.set(randi((int)transferFuncNames::FN_MAXCOUNT-1));
	g.targetNeuron.set(randi(nNeurons-1));
	return g;
}