Example #1
0
// Adds sub-pixel resolution EdgeOffsets for the outline using only
// a binary image source.
// Runs a sliding window of 5 edge steps over the outline, maintaining a count
// of the number of steps in each of the 4 directions in the window, and a
// sum of the x or y position of each step (as appropriate to its direction.)
// Ignores single-count steps EXCEPT the sharp U-turn and smoothes out the
// perpendicular direction. Eg
// ___              ___       Chain code from the left:
//    |___    ___   ___|      222122212223221232223000
//        |___|  |_|          Corresponding counts of each direction:
//                          0   00000000000000000123
//                          1   11121111001111100000
//                          2   44434443443333343321
//                          3   00000001111111112111
// Count of direction at center 41434143413313143313
// Step gets used?              YNYYYNYYYNYYNYNYYYyY (y= U-turn exception)
// Path redrawn showing only the used points:
// ___              ___
//     ___    ___   ___|
//         ___    _
// Sub-pixel edge position cannot be shown well with ASCII-art, but each
// horizontal step's y position is the mean of the y positions of the steps
// in the same direction in the sliding window, which makes a much smoother
// outline, without losing important detail.
void C_OUTLINE::ComputeBinaryOffsets() {
  delete [] offsets;
  offsets = new EdgeOffset[stepcount];
  // Count of the number of steps in each direction in the sliding window.
  int dir_counts[4];
  // Sum of the positions (y for a horizontal step, x for vertical) in each
  // direction in the sliding window.
  int pos_totals[4];
  memset(dir_counts, 0, sizeof(dir_counts));
  memset(pos_totals, 0, sizeof(pos_totals));
  ICOORD pos = start;
  ICOORD tail_pos = pos;
  // tail_pos is the trailing position, with the next point to be lost from
  // the window.
  tail_pos -= step(stepcount - 1);
  tail_pos -= step(stepcount - 2);
  // head_pos is the leading position, with the next point to be added to the
  // window.
  ICOORD head_pos = tail_pos;
  // Set up the initial window with 4 points in [-2, 2)
  for (int s = -2; s < 2; ++s) {
    increment_step(s, 1, &head_pos, dir_counts, pos_totals);
  }
  for (int s = 0; s < stepcount; pos += step(s++)) {
    // At step s, s in in the middle of [s-2, s+2].
    increment_step(s + 2, 1, &head_pos, dir_counts, pos_totals);
    int dir_index = chain_code(s);
    ICOORD step_vec = step(s);
    int best_diff = 0;
    int offset = 0;
    // Use only steps that have a count of >=2 OR the strong U-turn with a
    // single d and 2 at d-1 and 2 at d+1 (mod 4).
    if (dir_counts[dir_index] >= 2 || (dir_counts[dir_index] == 1 &&
        dir_counts[Modulo(dir_index - 1, 4)] == 2 &&
        dir_counts[Modulo(dir_index + 1, 4)] == 2)) {
      // Valid step direction.
      best_diff = dir_counts[dir_index];
      int edge_pos = step_vec.x() == 0 ? pos.x() : pos.y();
      // The offset proposes that the actual step should be positioned at
      // the mean position of the steps in the window of the same direction.
      // See ASCII art above.
      offset = pos_totals[dir_index] - best_diff * edge_pos;
    }
    offsets[s].offset_numerator =
        static_cast<inT8>(ClipToRange(offset, -MAX_INT8, MAX_INT8));
    offsets[s].pixel_diff = static_cast<uinT8>(ClipToRange(best_diff, 0 ,
                                                           MAX_UINT8));
    // The direction is just the vector from start to end of the window.
    FCOORD direction(head_pos.x() - tail_pos.x(), head_pos.y() - tail_pos.y());
    offsets[s].direction = direction.to_direction();
    increment_step(s - 2, -1, &tail_pos, dir_counts, pos_totals);
  }
}
Example #2
0
void Hint (void)
{
  /* The next 4 lines must be there. */
  while (gtk_events_pending ())
  {
    gtk_main_iteration ();
  }
  if (ichangestuff == 0)
  {
    Play ("click.mp3", 0);
  }
  if ((((ifilestuff == 0) && ((biscomputer == 0) || (wiscomputer == 0)) &&
    (iyesno == 0)) && (((((Modulo (imoves, 2) == 0) && (iiamblack == 1)) ||
    ((Modulo (imoves, 2) != 0) && (iiamblack == 0))) && (inet == 1)) ||
    (inet == 0))) && (imoving == 0))
  {
    imoving = 1;
    if (Modulo (imoves, 2) == 0)
    {
      if (inet == 1) idohint = 1;
      Computer ('b');
      idohint = 0;
      JudgeBoard ('w');
      if (wiscomputer == 1)
      {
        Computer ('w');
        JudgeBoard ('b');
      }
    }
    else
    {
      if (inet == 1) idohint = 1;
      Computer ('w');
      idohint = 0;
      JudgeBoard ('b');
      if (biscomputer == 1)
      {
        Computer ('b');
        JudgeBoard ('w');
      }
    }
    imoving = 0;
  }
  else
  {
    if (inet == 1)
    {
      Message ("It is not your move.", 3, 0);
    }
  }
}
complex stb_InnerProduct(stabiliser *phi1, stabiliser *phi2)
{
    affine_sp a = afp_Copy(phi1->a); //This won't work. I need to define a copy method
    stabiliser stab;
    stab.a = &a;
    stab.q = phi1->q;
    affine_sp *a1 = phi1->a, *a2 = phi2->a;
    quadratic_fm *q1 = phi1->q, *q2 = phi2->q;
    for (int i = a2->k +1; i < a2->n; i++){
        alpha = InnerProduct(a2->h, a2->GBar[i])
        res = shrink(&stab, a2->HBar[i], alpha);
        if (res == EMPTY){
            return (complex) 0;
        }
    }
    short *y = (short *)calloc(a2->k, sizeof(short));
    short *scratch_space = (short *)calloc(a2->n, sizeof(short));
    short res = 0;
    AddVectors(a2->n, scratch_space, a1->h);
    AddVectors(a2->n, scratch_space, a2->h);
    short **R = (short **)calloc(a2->n, sizeof(short*));
    for (int i=0; i<a2->n; i++){R[i] = (short *)calloc(a2->n, sizeof(short));}
    for (int i = 0; i < a2->k; i++){
        y[i] = InnerProduct(scratch_space, a2->Gbar[i]);
        for (int j = 0; j < a.k; j++){
            R[j][i] = InnerProduct(a.G[j], a2.GBar[i]);
        }

    }
    qfm_BasisChange(q2, R);
    qfm_ShiftChange(q2, y);
    for (int i = 0; i<a2->n; i++){a2->h[i] = a1->h[i];}
    //Cleanup
    for(int i = 0; i<q2->k; i++){free(R[i]);}
    free(scratch_space);
    free (R);
    free(y);
    //Find the final quadratic form q
    q.Q = Modulo(q1->Q - q2->Q, 8);
    for (int i = 0; i < q.K; i++){ 
        q.D[i] = Modulo(q1->D[i]-q2->D[i], 8);
        for (int j = 0; j<q.k; j++){
            q.J[i][j] = Modulo(q1->J[i][j] - q2->J[i][j], 8);
        }
    }
    return pow(2, -1*(a1->k - a2->k)/2)*ExponentialSum(q);
}
Example #4
0
// Returns a pointer to the page with the given index, modulo the total
// number of pages, recaching if needed.
const ImageData* DocumentData::GetPage(int index) {
  index = Modulo(index, total_pages_);
  if (index < pages_offset_ || index >= pages_offset_ + pages_.size()) {
    pages_offset_ = index;
    if (!ReCachePages()) return NULL;
  }
  return pages_[index - pages_offset_];
}
Example #5
0
EXPORT_C TUint TInteger::ModuloL(TUint aOperand) const
	{
	if(!aOperand)
		{
		User::Leave(KErrDivideByZero);
		}
	return Modulo(*this, aOperand);
	}
void HandlePlayer(char input)
{
	int tempx = player.x,
		tempy = player.y;

	if (input == '1')
		tempx--;
	else if (input == 'r')
		tempx++;
	else if (input == 'u')
		tempy--;
	else if (input == 'd')
		tempy++;

	player.x = Modulo(tempx, 6);
	player.y = Modulo(tempy, 6);
}
Example #7
0
void main(void)
{
 char *res;
 char ch1[]="12.2";
 char ch2[]="25.7";
 res=Modulo(ch1,ch2,'\0');
 printf("Resultat :%s:\n",res);
 free(res);
}              
Example #8
0
int main(int argc, char *argv[], char *env[])
{
    int Nbre1 = 3;
    int Nbre2 = 2;
    printf("%d + %d = %d\n", Nbre1, Nbre2, Additionner(Nbre1, Nbre2));
    printf("%d - %d = %d\n", Nbre1, Nbre2, Soustraire(Nbre1, Nbre2));
    printf("%d * %d = %d\n", Nbre1, Nbre2, Multiplier(Nbre1, Nbre2));
    printf("%d / %d = %d\n", Nbre1, Nbre2, Diviser(Nbre1, Nbre2));
    printf("%d %% %d = %d\n", Nbre1, Nbre2, Modulo(Nbre1, Nbre2));
    printf("%d ^ 2 = %d\n", Nbre1, Carre(Nbre1));
}
Example #9
0
// Helper for ComputeBinaryOffsets. Increments pos, dir_counts, pos_totals
// by the step, increment, and vertical step ? x : y position * increment
// at step s Mod stepcount respectively. Used to add or subtract the
// direction and position to/from accumulators of a small neighbourhood.
void C_OUTLINE::increment_step(int s, int increment, ICOORD* pos,
                               int* dir_counts, int* pos_totals) const {
  int step_index = Modulo(s, stepcount);
  int dir_index = chain_code(step_index);
  dir_counts[dir_index] += increment;
  ICOORD step_vec = step(step_index);
  if (step_vec.x() == 0)
    pos_totals[dir_index] += pos->x() * increment;
  else
    pos_totals[dir_index] += pos->y() * increment;
  *pos += step_vec;
}
main(){
	double x[N]=
	{
	1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0,
	1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0,
	1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0,
	1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0
	};// Vetor de entrada, inicializado com amostragem de uma onda quadrada
	double X[N];     // Vetor Saída 
	double pi_N;     // Auxiliar Pi*n
	unsigned int i;  // Indexador de uso geral
	printf("\n * Transformada Discreta de Hartley * ");  
	// Calculo da DHT
	for (int n=0; n<N; n++){
		X[n] = 0;
		pi_N = 2*n*pi;
		for (int k=0; k<N; k++){
			X[n] += x[k]*sqrt(2)*(cos((pi_N*k)/N-pi/4));//+sin((pi_N*k)/N));
		}
		X[n]=2*X[n]/N;
	}
	// Exibe vetor de entrada
	printf("\n\nEntrada:\n");
	for (i=0;i<N/2;i++) printf(" %.4f ", x[i]);
	printf("\n");
	for (;i<N;i++) printf(" %.4f ", x[i]);
    // Exibe resultado
	printf("\n\nResultado DHT:\n");
	for (i=0;i<N/2;i++) printf(" %.4f ", X[i]);
	printf("\n");
	for (;i<N;i++) printf(" %.4f ", X[i]);
	// Valor absoluto
	printf("\n\nEm Modulo:\n");
	for (i=0;i<N/2;i++) printf(" %.4f ", Modulo(X[i]));
	printf("\n");
	for (;i<N;i++) printf(" %.4f ", Modulo(X[i]));
}
Example #11
0
// Gathers outline points and their directions from start_index into dirs by
// stepping along the outline and normalizing the coordinates until the
// required feature_length has been collected or end_index is reached.
// On input pos must point to the position corresponding to start_index and on
// return pos is updated to the current raw position, and pos_normed is set to
// the normed version of pos.
// Since directions wrap-around, they need special treatment to get the mean.
// Provided the cluster of directions doesn't straddle the wrap-around point,
// the simple mean works. If they do, then, unless the directions are wildly
// varying, the cluster rotated by 180 degrees will not straddle the wrap-
// around point, so mean(dir + 180 degrees) - 180 degrees will work. Since
// LLSQ conveniently stores the mean of 2 variables, we use it to store
// dir and dir+128 (128 is 180 degrees) and then use the resulting mean
// with the least variance.
static int GatherPoints(const C_OUTLINE* outline, double feature_length,
                        const DENORM& denorm, const DENORM* root_denorm,
                        int start_index, int end_index,
                        ICOORD* pos, FCOORD* pos_normed,
                        LLSQ* points, LLSQ* dirs) {
  int step_length = outline->pathlength();
  ICOORD step = outline->step(start_index % step_length);
  // Prev_normed is the start point of this collection and will be set on the
  // first iteration, and on later iterations used to determine the length
  // that has been collected.
  FCOORD prev_normed;
  points->clear();
  dirs->clear();
  int num_points = 0;
  int index;
  for (index = start_index; index <= end_index; ++index, *pos += step) {
    step = outline->step(index % step_length);
    int edge_weight = outline->edge_strength_at_index(index % step_length);
    if (edge_weight == 0) {
      // This point has conflicting gradient and step direction, so ignore it.
      continue;
    }
    // Get the sub-pixel precise location and normalize.
    FCOORD f_pos = outline->sub_pixel_pos_at_index(*pos, index % step_length);
    denorm.NormTransform(root_denorm, f_pos, pos_normed);
    if (num_points == 0) {
      // The start of this segment.
      prev_normed = *pos_normed;
    } else {
      FCOORD offset = *pos_normed - prev_normed;
      float length = offset.length();
      if (length > feature_length) {
        // We have gone far enough from the start. We will use this point in
        // the next set so return what we have so far.
        return index;
      }
    }
    points->add(pos_normed->x(), pos_normed->y(), edge_weight);
    int direction = outline->direction_at_index(index % step_length);
    if (direction >= 0) {
      direction = NormalizeDirection(direction, f_pos, denorm, root_denorm);
      // Use both the direction and direction +128 so we are not trying to
      // take the mean of something straddling the wrap-around point.
      dirs->add(direction, Modulo(direction + 128, 256));
    }
    ++num_points;
  }
  return index;
}
Example #12
0
int main(int argc, char** argv) {
    
int opcao;
 float num01,num02;
    
    do {
  
     printf("Entre com o numero da operacao matematica:\n");
     printf("1 - Adição;\n");
     printf("2 - Subtração;\n");
     printf("3 - Multiplicação;\n");
     printf("4 - Divisao;\n");
     printf("5 - Modulo;\n");
     printf("6 - Sair;\n");
     scanf("%d",&opcao);
     
     printf("Entre com um numero: ");
     scanf("%f",&num01);
     
     printf("Entre com um numero: ");
     scanf("%f",&num02);
     
      if(opcao == 1){
          printf("%.0f + %.0f = %.0f\n",num01,num02,Adicao(num01,num02));
       }
      else if(opcao == 2){
          printf("%.0f - %.0f = %.0f\n",num01,num02,Substracao(num01,num02));
      }
      else if(opcao == 3){
          printf("%.0f * %.0f = %.0f\n",num01,num02,Multiplicacao(num01,num02));
      }
      else if(opcao ==4){
          printf("%.0f / %.0f = %.2f \n",num01,num02,Divisao(num01,num02));
      }
      else if(opcao == 5){
      printf("%.0f %% %.0f = %.2f\n",num01,num02,Modulo(num01,num02));
      }
      else if( opcao != 6){
          printf("Operador matematico não encontrado\n");
      }
      else{
      printf("Saindo do sistema.");
      }
        
    }while(opcao != 6);

    return (EXIT_SUCCESS);
}
Example #13
0
// Helper returns the mean direction vector from the given stats. Use the
// mean direction from dirs if there is information available, otherwise, use
// the fit_vector from point_diffs.
static FCOORD MeanDirectionVector(const LLSQ& point_diffs, const LLSQ& dirs,
                                  const FCOORD& start_pt,
                                  const FCOORD& end_pt) {
  FCOORD fit_vector;
  if (dirs.count() > 0) {
    // There were directions, so use them. To avoid wrap-around problems, we
    // have 2 accumulators in dirs: x for normal directions and y for
    // directions offset by 128. We will use the one with the least variance.
    FCOORD mean_pt = dirs.mean_point();
    double mean_dir = 0.0;
    if (dirs.x_variance() <= dirs.y_variance()) {
      mean_dir = mean_pt.x();
    } else {
      mean_dir = mean_pt.y() + 128;
    }
    fit_vector.from_direction(Modulo(IntCastRounded(mean_dir), 256));
  } else {
    // There were no directions, so we rely on the vector_fit to the points.
    // Since the vector_fit is 180 degrees ambiguous, we align with the
    // supplied feature_dir by making the scalar product non-negative.
    FCOORD feature_dir(end_pt - start_pt);
    fit_vector = point_diffs.vector_fit();
    if (fit_vector.x() == 0.0f && fit_vector.y() == 0.0f) {
      // There was only a single point. Use feature_dir directly.
      fit_vector = feature_dir;
    } else {
      // Sometimes the least mean squares fit is wrong, due to the small sample
      // of points and scaling. Use a 90 degree rotated vector if that matches
      // feature_dir better.
      FCOORD fit_vector2 = !fit_vector;
      // The fit_vector is 180 degrees ambiguous, so resolve the ambiguity by
      // insisting that the scalar product with the feature_dir should be +ve.
      if (fit_vector % feature_dir < 0.0)
        fit_vector = -fit_vector;
      if (fit_vector2 % feature_dir < 0.0)
        fit_vector2 = -fit_vector2;
      // Even though fit_vector2 has a higher mean squared error, it might be
      // a better fit, so use it if the dot product with feature_dir is bigger.
      if (fit_vector2 % feature_dir > fit_vector % feature_dir)
        fit_vector = fit_vector2;
    }
  }
  return fit_vector;
}
Example #14
0
// Helper to compute an offset index feature. In this context an offset
// feature with a dir of +/-1 is a feature of a similar direction,
// but shifted perpendicular to the direction of the feature. An offset
// feature with a dir of +/-2 is feature at the same position, but rotated
// by +/- one [compact] quantum. Returns the index of the generated offset
// feature, or -1 if it doesn't exist. Dir should be in
// [-kNumOffsetMaps, kNumOffsetMaps] to indicate the relative direction.
// A dir of 0 is an identity transformation.
// Both input and output are from the index(sparse) feature space, not
// the mapped/compact feature space, but the offset feature is the minimum
// distance moved from the input to guarantee that it maps to the next
// available quantum in the mapped/compact space.
int IntFeatureMap::ComputeOffsetFeature(int index_feature, int dir) const {
  INT_FEATURE_STRUCT f = InverseIndexFeature(index_feature);
  ASSERT_HOST(IndexFeature(f) == index_feature);
  if (dir == 0) {
    return index_feature;
  } else if (dir == 1 || dir == -1) {
    FCOORD feature_dir = FeatureDirection(f.Theta);
    FCOORD rotation90(0.0f, 1.0f);
    feature_dir.rotate(rotation90);
    // Find the nearest existing feature.
    for (int m = 1; m < kMaxOffsetDist; ++m) {
      double x_pos = f.X + feature_dir.x() * (m * dir);
      double y_pos = f.Y + feature_dir.y() * (m * dir);
      int x = IntCastRounded(x_pos);
      int y = IntCastRounded(y_pos);
      if (x >= 0 && x <= MAX_UINT8 && y >= 0 && y <= MAX_UINT8) {
        INT_FEATURE_STRUCT offset_f;
        offset_f.X = x;
        offset_f.Y = y;
        offset_f.Theta = f.Theta;
        int offset_index = IndexFeature(offset_f);
        if (offset_index != index_feature && offset_index >= 0)
          return offset_index;  // Found one.
      } else {
        return -1;  // Hit the edge of feature space.
      }
    }
  } else if (dir == 2 || dir == -2) {
    // Find the nearest existing index_feature.
    for (int m = 1; m < kMaxOffsetDist; ++m) {
      int theta = f.Theta + m * dir / 2;
      INT_FEATURE_STRUCT offset_f;
      offset_f.X = f.X;
      offset_f.Y = f.Y;
      offset_f.Theta = Modulo(theta, 256);
      int offset_index = IndexFeature(offset_f);
      if (offset_index != index_feature && offset_index >= 0)
        return offset_index;  // Found one.
    }
  }
  return -1;  // Nothing within the max distance.
}
Example #15
0
 Integer&  operator%=(word t)  { return *this = Modulo(t); }
Example #16
0
 Integer&  operator%=(const Integer& t)	{ return *this = Modulo(t); }
Example #17
0
void TInteger::PrimeRandomizeL(TUint aBits, TRandomAttribute aAttr)
	{
	assert(aBits > 1); 
	
	//"this" is "empty" currently.  Consists of Size() words of 0's.  This is just
	//checking that sign flag is positive as we don't set it later.
	assert(NotNegative());

	//Flag for the whole function saying if we've found a prime
	TBool foundProbablePrime = EFalse;

	//Find 2^aBits + 1 -- any prime we find must be less than this.
	RInteger max = RInteger::NewEmptyL(BitsToWords(aBits)+1);
	CleanupStack::PushL(max);
	max.SetBit(aBits);
	assert(max.BitCount()-1 == aBits);

	// aBits 	| approx number of odd numbers you must try to have a 50% 
	//			chance of finding a prime
	//---------------------------------------------------------
	// 512		| 122		
	// 1024		| 245
	// 2048		| 1023
	//Therefore if we are generating larger than 1024 bit numbers we'll use a
	//bigger bit array to have a better chance of avoiding re-generating it.
	TUint sLength = aBits > 1024 ? 1024 : 512;
	RInteger S = RInteger::NewEmptyL(BitsToWords(sLength));
	CleanupStack::PushL(S);

	while(!foundProbablePrime)
		{
		//Randomly choose aBits
		RandomizeL(aBits, aAttr);

		//If the random number chosen is less than KSmallPrimeSquared, we have a
		//special set of routines.
		if(SmallPrimeRandomizeL())
			{
			foundProbablePrime = ETrue;
			}
		else
			{
			//if it was <= KLastSmallPrimeSquared then it would have been
			//handled by SmallPrimeRandomizeL()
			assert(*this > KLastSmallPrimeSquared);

			//Make sure any number we bother testing is at least odd
			SetBit(0);

			//Ensure that this + 2*sLength < max
			RInteger temp = max.MinusL(*this);
			CleanupStack::PushL(temp);
			++temp;
			temp >>=1;
			if(temp < sLength)
				{
				//if this + 2*sLength >= max then we use a smaller sLength to
				//ensure we don't find a number that is outside of our bounds
				//(and bigger than our allocated memory for this)

				//temp must be less than KMaxTUint as sLength is a TUint 
				sLength = temp.ConvertToUnsignedLong();	
				}
			CleanupStack::PopAndDestroy(&temp);

			//Start at 1 as no point in checking against 2 (all odd numbers)
			for(TUint i=1; i<KPrimeTableSize; i++)
				{
				//no need to call ModuloL as we know KPrimeTable[i] is not 0
				TUint remainder = Modulo(*this, KPrimeTable[i]);
				TUint index = FindSmallestIndex(KPrimeTable[i], remainder);
				EliminateComposites(S.Ptr(), KPrimeTable[i], index, sLength);
				}
			TInt j = FindFirstPrimeCandidate(S.Ptr(), sLength);
			TInt prev = 0;
			for(; j>=0; j=FindFirstPrimeCandidate(S.Ptr(), sLength))
				{
				ArraySetBit(S.Ptr(), j);

				//should never carry as we earlier made sure that 2*j + this < max
				//where max is 1 bit more than we asked for.
				IncrementNoCarry(Ptr(), Size(), 2*(j-prev));

				assert(*this < max);
				assert(!HasSmallDivisorL(*this));

				prev = j;

				if( IsStrongProbablePrimeL(*this) )
					{
					foundProbablePrime = ETrue;
					break;
					}
				}
			//This clears the memory
			S.CopyL(0, EFalse);
			}
		}
	CleanupStack::PopAndDestroy(2, &max);
	}
Example #18
0
int CheckSides (int icsbutton, char csccolor, int csitype)
{
  if ((csitype > 0) && (csitype < 4))
  {
    iyeah = 0;
    ichecked = 0;
    if (Board[icsbutton][2] != csccolor)
    {
      if (Board[icsbutton][2] == 'e')
      {
        iyeah = 1;
      }
      else
      {
        iyeah = 2;
      }
      sprintf (Board[icsbutton], "%c%c%c", Board[icsbutton][0],
        Board[icsbutton][1], csccolor);
    }
    for (iclear = 1; iclear <= 361; iclear++)
    {
      ireturn[iclear] = 0;
      Checked[iclear] = 0;
    }
  }

  if (Checked[icsbutton] == 1)
  {
    return (15);
  }
  Checked[icsbutton] = 1;
  ichecked++;

  if (csccolor == 'w')
  {
    csnotccolor = 'b';
  }
  else
  {
    csnotccolor = 'w';
  }

  if ((Modulo ((icsbutton - 1), 19) == 0)
    || (Checked[icsbutton - 1] == 2)
    || ((Modulo ((icsbutton - 1), 19) != 0)
      && (Board[icsbutton - 1][2] == csnotccolor))
    || ((Modulo ((icsbutton - 1), 19) != 0)
      && (Board[icsbutton - 1][2] == csccolor)
      && (CheckSides ((icsbutton - 1), csccolor, 0) == 15)))
  {
    ireturn[icsbutton] += 1;
  }
  else
    Checked[icsbutton - 1] = 2;
  if ((Modulo ((icsbutton), 19) == 0)
    || (Checked[icsbutton + 1] == 2)
    || ((Modulo ((icsbutton), 19) != 0)
      && (Board[icsbutton + 1][2] == csnotccolor))
    || ((Modulo ((icsbutton), 19) != 0)
      && (Board[icsbutton + 1][2] == csccolor)
      && (CheckSides ((icsbutton + 1), csccolor, 0) == 15)))
  {
    ireturn[icsbutton] += 2;
  }
  else
    Checked[icsbutton + 1] = 2;
  if (((icsbutton >= 1) && (icsbutton <= 19))
    || (Checked[icsbutton - 19] == 2)
    || ((icsbutton > 19)
      && (Board[icsbutton - 19][2] == csnotccolor))
    || ((icsbutton > 19)
      && (Board[icsbutton - 19][2] == csccolor)
      && (CheckSides ((icsbutton - 19), csccolor, 0) == 15)))
  {
    ireturn[icsbutton] += 4;
  }
  else
    Checked[icsbutton - 19] = 2;
  if (((icsbutton >= 343) && (icsbutton <= 361))
    || (Checked[icsbutton + 19] == 2)
    || ((icsbutton < 343)
      && (Board[icsbutton + 19][2] == csnotccolor))
    || ((icsbutton < 343)
      && (Board[icsbutton + 19][2] == csccolor)
      && (CheckSides ((icsbutton + 19), csccolor, 0) == 15)))
  {
    ireturn[icsbutton] += 8;
  }
  else
    Checked[icsbutton + 19] = 2;
  if ((csitype == 1) || (csitype == 2))
  {
    if (iyeah == 1)
    {
      sprintf (Board[icsbutton], "%c%c%c", Board[icsbutton][0],
        Board[icsbutton][1], 'e');
    }
    if (iyeah == 2)
    {
      sprintf (Board[icsbutton], "%c%c%c", Board[icsbutton][0],
        Board[icsbutton][1], 's');
    }
  }
  if (csitype == 3)
  {
    return (ichecked);
  }
  else
  {
    return (ireturn[icsbutton]);
  }
}
Example #19
0
// Runs backward propagation of errors on the deltas line.
// See NetworkCpp for a detailed discussion of the arguments.
bool LSTM::Backward(bool debug, const NetworkIO& fwd_deltas,
                    NetworkScratch* scratch,
                    NetworkIO* back_deltas) {
  if (debug) DisplayBackward(fwd_deltas);
  back_deltas->ResizeToMap(fwd_deltas.int_mode(), input_map_, ni_);
  // ======Scratch space.======
  // Output errors from deltas with recurrence from sourceerr.
  NetworkScratch::FloatVec outputerr;
  outputerr.Init(ns_, scratch);
  // Recurrent error in the state/source.
  NetworkScratch::FloatVec curr_stateerr, curr_sourceerr;
  curr_stateerr.Init(ns_, scratch);
  curr_sourceerr.Init(na_, scratch);
  ZeroVector<double>(ns_, curr_stateerr);
  ZeroVector<double>(na_, curr_sourceerr);
  // Errors in the gates.
  NetworkScratch::FloatVec gate_errors[WT_COUNT];
  for (int g = 0; g < WT_COUNT; ++g) gate_errors[g].Init(ns_, scratch);
  // Rotating buffers of width buf_width allow storage of the recurrent time-
  // steps used only for true 2-D. Stores one full strip of the major direction.
  int buf_width = Is2D() ? input_map_.Size(FD_WIDTH) : 1;
  GenericVector<NetworkScratch::FloatVec> stateerr, sourceerr;
  if (Is2D()) {
    stateerr.init_to_size(buf_width, NetworkScratch::FloatVec());
    sourceerr.init_to_size(buf_width, NetworkScratch::FloatVec());
    for (int t = 0; t < buf_width; ++t) {
      stateerr[t].Init(ns_, scratch);
      sourceerr[t].Init(na_, scratch);
      ZeroVector<double>(ns_, stateerr[t]);
      ZeroVector<double>(na_, sourceerr[t]);
    }
  }
  // Parallel-generated sourceerr from each of the gates.
  NetworkScratch::FloatVec sourceerr_temps[WT_COUNT];
  for (int w = 0; w < WT_COUNT; ++w)
    sourceerr_temps[w].Init(na_, scratch);
  int width = input_width_;
  // Transposed gate errors stored over all timesteps for sum outer.
  NetworkScratch::GradientStore gate_errors_t[WT_COUNT];
  for (int w = 0; w < WT_COUNT; ++w) {
    gate_errors_t[w].Init(ns_, width, scratch);
  }
  // Used only if softmax_ != NULL.
  NetworkScratch::FloatVec softmax_errors;
  NetworkScratch::GradientStore softmax_errors_t;
  if (softmax_ != NULL) {
    softmax_errors.Init(no_, scratch);
    softmax_errors_t.Init(no_, width, scratch);
  }
  double state_clip = Is2D() ? 9.0 : 4.0;
#if DEBUG_DETAIL > 1
  tprintf("fwd_deltas:%s\n", name_.string());
  fwd_deltas.Print(10);
#endif
  StrideMap::Index dest_index(input_map_);
  dest_index.InitToLast();
  // Used only by NT_LSTM_SUMMARY.
  StrideMap::Index src_index(fwd_deltas.stride_map());
  src_index.InitToLast();
  do {
    int t = dest_index.t();
    bool at_last_x = dest_index.IsLast(FD_WIDTH);
    // up_pos is the 2-D back step, down_pos is the 2-D fwd step, and are only
    // valid if >= 0, which is true if 2d and not on the top/bottom.
    int up_pos = -1;
    int down_pos = -1;
    if (Is2D()) {
      if (dest_index.index(FD_HEIGHT) > 0) {
        StrideMap::Index up_index(dest_index);
        if (up_index.AddOffset(-1, FD_HEIGHT)) up_pos = up_index.t();
      }
      if (!dest_index.IsLast(FD_HEIGHT)) {
        StrideMap::Index down_index(dest_index);
        if (down_index.AddOffset(1, FD_HEIGHT)) down_pos = down_index.t();
      }
    }
    // Index of the 2-D revolving buffers (sourceerr, stateerr).
    int mod_t = Modulo(t, buf_width);      // Current timestep.
    // Zero the state in the major direction only at the end of every row.
    if (at_last_x) {
      ZeroVector<double>(na_, curr_sourceerr);
      ZeroVector<double>(ns_, curr_stateerr);
    }
    // Setup the outputerr.
    if (type_ == NT_LSTM_SUMMARY) {
      if (dest_index.IsLast(FD_WIDTH)) {
        fwd_deltas.ReadTimeStep(src_index.t(), outputerr);
        src_index.Decrement();
      } else {
        ZeroVector<double>(ns_, outputerr);
      }
    } else if (softmax_ == NULL) {
      fwd_deltas.ReadTimeStep(t, outputerr);
    } else {
      softmax_->BackwardTimeStep(fwd_deltas, t, softmax_errors,
                                 softmax_errors_t.get(), outputerr);
    }
    if (!at_last_x)
      AccumulateVector(ns_, curr_sourceerr + ni_ + nf_, outputerr);
    if (down_pos >= 0)
      AccumulateVector(ns_, sourceerr[mod_t] + ni_ + nf_ + ns_, outputerr);
    // Apply the 1-d forget gates.
    if (!at_last_x) {
      const float* next_node_gf1 = node_values_[GF1].f(t + 1);
      for (int i = 0; i < ns_; ++i) {
        curr_stateerr[i] *= next_node_gf1[i];
      }
    }
    if (Is2D() && t + 1 < width) {
      for (int i = 0; i < ns_; ++i) {
        if (which_fg_[t + 1][i] != 1) curr_stateerr[i] = 0.0;
      }
      if (down_pos >= 0) {
        const float* right_node_gfs = node_values_[GFS].f(down_pos);
        const double* right_stateerr = stateerr[mod_t];
        for (int i = 0; i < ns_; ++i) {
          if (which_fg_[down_pos][i] == 2) {
            curr_stateerr[i] += right_stateerr[i] * right_node_gfs[i];
          }
        }
      }
    }
    state_.FuncMultiply3Add<HPrime>(node_values_[GO], t, outputerr,
                                    curr_stateerr);
    // Clip stateerr_ to a sane range.
    ClipVector<double>(ns_, -state_clip, state_clip, curr_stateerr);
#if DEBUG_DETAIL > 1
    if (t + 10 > width) {
      tprintf("t=%d, stateerr=", t);
      for (int i = 0; i < ns_; ++i)
        tprintf(" %g,%g,%g", curr_stateerr[i], outputerr[i],
                curr_sourceerr[ni_ + nf_ + i]);
      tprintf("\n");
    }
#endif
    // Matrix multiply to get the source errors.
    PARALLEL_IF_OPENMP(GFS)

    // Cell inputs.
    node_values_[CI].FuncMultiply3<GPrime>(t, node_values_[GI], t,
                                           curr_stateerr, gate_errors[CI]);
    ClipVector(ns_, -kErrClip, kErrClip, gate_errors[CI].get());
    gate_weights_[CI].VectorDotMatrix(gate_errors[CI], sourceerr_temps[CI]);
    gate_errors_t[CI].get()->WriteStrided(t, gate_errors[CI]);

    SECTION_IF_OPENMP
    // Input Gates.
    node_values_[GI].FuncMultiply3<FPrime>(t, node_values_[CI], t,
                                           curr_stateerr, gate_errors[GI]);
    ClipVector(ns_, -kErrClip, kErrClip, gate_errors[GI].get());
    gate_weights_[GI].VectorDotMatrix(gate_errors[GI], sourceerr_temps[GI]);
    gate_errors_t[GI].get()->WriteStrided(t, gate_errors[GI]);

    SECTION_IF_OPENMP
    // 1-D forget Gates.
    if (t > 0) {
      node_values_[GF1].FuncMultiply3<FPrime>(t, state_, t - 1, curr_stateerr,
                                              gate_errors[GF1]);
      ClipVector(ns_, -kErrClip, kErrClip, gate_errors[GF1].get());
      gate_weights_[GF1].VectorDotMatrix(gate_errors[GF1],
                                         sourceerr_temps[GF1]);
    } else {
      memset(gate_errors[GF1], 0, ns_ * sizeof(gate_errors[GF1][0]));
      memset(sourceerr_temps[GF1], 0, na_ * sizeof(*sourceerr_temps[GF1]));
    }
    gate_errors_t[GF1].get()->WriteStrided(t, gate_errors[GF1]);

    // 2-D forget Gates.
    if (up_pos >= 0) {
      node_values_[GFS].FuncMultiply3<FPrime>(t, state_, up_pos, curr_stateerr,
                                              gate_errors[GFS]);
      ClipVector(ns_, -kErrClip, kErrClip, gate_errors[GFS].get());
      gate_weights_[GFS].VectorDotMatrix(gate_errors[GFS],
                                         sourceerr_temps[GFS]);
    } else {
      memset(gate_errors[GFS], 0, ns_ * sizeof(gate_errors[GFS][0]));
      memset(sourceerr_temps[GFS], 0, na_ * sizeof(*sourceerr_temps[GFS]));
    }
    if (Is2D()) gate_errors_t[GFS].get()->WriteStrided(t, gate_errors[GFS]);

    SECTION_IF_OPENMP
    // Output gates.
    state_.Func2Multiply3<HFunc, FPrime>(node_values_[GO], t, outputerr,
                                         gate_errors[GO]);
    ClipVector(ns_, -kErrClip, kErrClip, gate_errors[GO].get());
    gate_weights_[GO].VectorDotMatrix(gate_errors[GO], sourceerr_temps[GO]);
    gate_errors_t[GO].get()->WriteStrided(t, gate_errors[GO]);
    END_PARALLEL_IF_OPENMP

    SumVectors(na_, sourceerr_temps[CI], sourceerr_temps[GI],
               sourceerr_temps[GF1], sourceerr_temps[GO], sourceerr_temps[GFS],
               curr_sourceerr);
    back_deltas->WriteTimeStep(t, curr_sourceerr);
    // Save states for use by the 2nd dimension only if needed.
    if (Is2D()) {
      CopyVector(ns_, curr_stateerr, stateerr[mod_t]);
      CopyVector(na_, curr_sourceerr, sourceerr[mod_t]);
    }
  } while (dest_index.Decrement());
#if DEBUG_DETAIL > 2
  for (int w = 0; w < WT_COUNT; ++w) {
    tprintf("%s gate errors[%d]\n", name_.string(), w);
    gate_errors_t[w].get()->PrintUnTransposed(10);
  }
#endif
  // Transposed source_ used to speed-up SumOuter.
  NetworkScratch::GradientStore source_t, state_t;
  source_t.Init(na_, width, scratch);
  source_.Transpose(source_t.get());
  state_t.Init(ns_, width, scratch);
  state_.Transpose(state_t.get());
#ifdef _OPENMP
#pragma omp parallel for num_threads(GFS) if (!Is2D())
#endif
  for (int w = 0; w < WT_COUNT; ++w) {
    if (w == GFS && !Is2D()) continue;
    gate_weights_[w].SumOuterTransposed(*gate_errors_t[w], *source_t, false);
  }
  if (softmax_ != NULL) {
    softmax_->FinishBackward(*softmax_errors_t);
  }
  return needs_to_backprop_;
}
 void CFootBotLightRotZOnlySensor::Update() {
    /* Erase readings */
    for(size_t i = 0; i < m_tReadings.size(); ++i) {
       m_tReadings[i].Value = 0.0f;
    }
    /* Get foot-bot orientation */
    CRadians cTmp1, cTmp2, cOrientationZ;
    m_pcEmbodiedEntity->GetOriginAnchor().Orientation.ToEulerAngles(cOrientationZ, cTmp1, cTmp2);
    /* Ray used for scanning the environment for obstacles */
    CRay3 cOcclusionCheckRay;
    cOcclusionCheckRay.SetStart(m_pcEmbodiedEntity->GetOriginAnchor().Position);
    CVector3 cRobotToLight;
    /* Buffer for the angle of the light wrt to the foot-bot */
    CRadians cAngleLightWrtFootbot;
    /* Buffers to contain data about the intersection */
    SEmbodiedEntityIntersectionItem sIntersection;
    /* List of light entities */
    CSpace::TMapPerTypePerId::iterator itLights = m_cSpace.GetEntityMapPerTypePerId().find("light");
    if (itLights != m_cSpace.GetEntityMapPerTypePerId().end()) {
       CSpace::TMapPerType& mapLights = itLights->second;
       /*
     * 1. go through the list of light entities in the scene
     * 2. check if a light is occluded
     * 3. if it isn't, distribute the reading across the sensors
     *    NOTE: the readings are additive
     * 4. go through the sensors and clamp their values
     */
       for(CSpace::TMapPerType::iterator it = mapLights.begin();
           it != mapLights.end();
           ++it) {
          /* Get a reference to the light */
          CLightEntity& cLight = *(any_cast<CLightEntity*>(it->second));
          /* Consider the light only if it has non zero intensity */
          if(cLight.GetIntensity() > 0.0f) {
             /* Set the ray end */
             cOcclusionCheckRay.SetEnd(cLight.GetPosition());
             /* Check occlusion between the foot-bot and the light */
             if(! GetClosestEmbodiedEntityIntersectedByRay(sIntersection,
                                                           cOcclusionCheckRay,
                                                           *m_pcEmbodiedEntity)) {
                /* The light is not occluded */
                if(m_bShowRays) {
                   m_pcControllableEntity->AddCheckedRay(false, cOcclusionCheckRay);
                }
                /* Get the distance between the light and the foot-bot */
                cOcclusionCheckRay.ToVector(cRobotToLight);
                /*
                 * Linearly scale the distance with the light intensity
                 * The greater the intensity, the smaller the distance
                 */
                cRobotToLight /= cLight.GetIntensity();
                /* Get the angle wrt to foot-bot rotation */
                cAngleLightWrtFootbot = cRobotToLight.GetZAngle();
                cAngleLightWrtFootbot -= cOrientationZ;
                /*
                 * Find closest sensor index to point at which ray hits footbot body
                 * Rotate whole body by half a sensor spacing (corresponding to placement of first sensor)
                 * Division says how many sensor spacings there are between first sensor and point at which ray hits footbot body
                 * Increase magnitude of result of division to ensure correct rounding
                 */
                Real fIdx = (cAngleLightWrtFootbot - SENSOR_HALF_SPACING) / SENSOR_SPACING;
                SInt32 nReadingIdx = (fIdx > 0) ? fIdx + 0.5f : fIdx - 0.5f;
                /* Set the actual readings */
                Real fReading = cRobotToLight.Length();
                /*
                 * Take 6 readings before closest sensor and 6 readings after - thus we
                 * process sensors that are with 180 degrees of intersection of light
                 * ray with robot body
                 */
                for(SInt32 nIndexOffset = -6; nIndexOffset < 7; ++nIndexOffset) {
                   UInt32 unIdx = Modulo(nReadingIdx + nIndexOffset, 24);
                   CRadians cAngularDistanceFromOptimalLightReceptionPoint = Abs((cAngleLightWrtFootbot - m_tReadings[unIdx].Angle).SignedNormalize());
                   /*
                    * ComputeReading gives value as if sensor was perfectly in line with
                    * light ray. We then linearly decrease actual reading from 1 (dist
                    * 0) to 0 (dist PI/2)
                    */
                   m_tReadings[unIdx].Value += ComputeReading(fReading) * ScaleReading(cAngularDistanceFromOptimalLightReceptionPoint);
                }
             }
             else {
                /* The ray is occluded */
                if(m_bShowRays) {
                   m_pcControllableEntity->AddCheckedRay(true, cOcclusionCheckRay);
                   m_pcControllableEntity->AddIntersectionPoint(cOcclusionCheckRay, sIntersection.TOnRay);
                }
             }
          }
       }
       /* Apply noise to the sensors */
       if(m_bAddNoise) {
          for(size_t i = 0; i < 24; ++i) {
             m_tReadings[i].Value += m_pcRNG->Uniform(m_cNoiseRange);
          }
       }
       /* Trunc the reading between 0 and 1 */
       for(size_t i = 0; i < 24; ++i) {
          SENSOR_RANGE.TruncValue(m_tReadings[i].Value);
       }
    }
    else {
       /* There are no lights in the environment */
       if(m_bAddNoise) {
          /* Go through the sensors */
          for(UInt32 i = 0; i < m_tReadings.size(); ++i) {
             /* Apply noise to the sensor */
             m_tReadings[i].Value += m_pcRNG->Uniform(m_cNoiseRange);
             /* Trunc the reading between 0 and 1 */
             SENSOR_RANGE.TruncValue(m_tReadings[i].Value);
          }
       }
    }
 }
Example #21
0
void Pass (void)
{
  /* The next 4 lines must be there. */
  while (gtk_events_pending ())
  {
    gtk_main_iteration ();
  }
  if (ichangestuff == 0)
  {
    Play ("click.mp3", 0);
  }
  if ((((ifilestuff == 0) && ((biscomputer == 0) || (wiscomputer == 0))
    && (iyesno == 0)) && (((((Modulo (imoves, 2) == 0) && (iiamblack == 1)) ||
    ((Modulo (imoves, 2) != 0) && (iiamblack == 0))) && (inet == 1)) ||
    (inet == 0))) && (imoving == 0))
  {
    imoving = 1;
    if (inet == 1)
    {
      SendData (1, "pass");
    }
    if (Modulo (imoves, 2) == 0)
    {
      JudgeBoard ('w');
    }
    else
    {
      JudgeBoard ('b');
    }
    pass[ihistory] = 1;
    iscorewhite = ScoreWhite ();
    iscoreblack = ScoreBlack ();
    if (Modulo (imoves, 2) != 0)
    {
      if ((iscorewhite > iscoreblack) || (pass[ihistory - 1] == 1))
      {
        if (iscorewhite > iscoreblack)
        {
          iduh = 1;
        }
        EndGame ();
      }
      else
      {
        if (wiscomputer == 1)
        {
          Computer ('w');
          JudgeBoard ('b');
        }
      }
    }
    else
    {
      if ((iscoreblack > iscorewhite) || (pass[ihistory - 1] == 1))
      {
        if (iscoreblack > iscorewhite)
        {
          iduh = 1;
        }
        EndGame ();
      }
      else
      {
        if (biscomputer == 1)
        {
          Computer ('b');
          JudgeBoard ('w');
        }
      }
    }
    imoving = 0;
  }
  else
  {
    if (inet == 1)
    {
      Message ("It is not your move.", 3, 0);
    }
  }
}
Example #22
0
// Converts an angle in radians (from ICOORD::angle or FCOORD::angle) to a
// standard feature direction as an unsigned angle in 256ths of a circle
// measured anticlockwise from (-1, 0).
uint8_t FCOORD::binary_angle_plus_pi(double radians) {
  return Modulo(IntCastRounded((radians + M_PI) * 128.0 / M_PI), 256);
}
Example #23
0
// Adds sub-pixel resolution EdgeOffsets for the outline if the supplied
// pix is 8-bit. Does nothing otherwise.
// Operation: Consider the following near-horizontal line:
// _________
//          |________
//                   |________
// At *every* position along this line, the gradient direction will be close
// to vertical. Extrapoaltion/interpolation of the position of the threshold
// that was used to binarize the image gives a more precise vertical position
// for each horizontal step, and the conflict in step direction and gradient
// direction can be used to ignore the vertical steps.
void C_OUTLINE::ComputeEdgeOffsets(int threshold, Pix* pix) {
  if (pixGetDepth(pix) != 8) return;
  const l_uint32* data = pixGetData(pix);
  int wpl = pixGetWpl(pix);
  int width = pixGetWidth(pix);
  int height = pixGetHeight(pix);
  bool negative = flag(COUT_INVERSE);
  delete [] offsets;
  offsets = new EdgeOffset[stepcount];
  ICOORD pos = start;
  ICOORD prev_gradient;
  ComputeGradient(data, wpl, pos.x(), height - pos.y(), width, height,
                  &prev_gradient);
  for (int s = 0; s < stepcount; ++s) {
    ICOORD step_vec = step(s);
    TPOINT pt1(pos);
    pos += step_vec;
    TPOINT pt2(pos);
    ICOORD next_gradient;
    ComputeGradient(data, wpl, pos.x(), height - pos.y(), width, height,
                    &next_gradient);
    // Use the sum of the prev and next as the working gradient.
    ICOORD gradient = prev_gradient + next_gradient;
    // best_diff will be manipulated to be always positive.
    int best_diff = 0;
    // offset will be the extrapolation of the location of the greyscale
    // threshold from the edge with the largest difference, relative to the
    // location of the binary edge.
    int offset = 0;
    if (pt1.y == pt2.y && abs(gradient.y()) * 2 >= abs(gradient.x())) {
      // Horizontal step. diff_sign == 1 indicates black above.
      int diff_sign = (pt1.x > pt2.x) == negative ? 1 : -1;
      int x = MIN(pt1.x, pt2.x);
      int y = height - pt1.y;
      int best_sum = 0;
      int best_y = y;
      EvaluateVerticalDiff(data, wpl, diff_sign, x, y, height,
                           &best_diff, &best_sum, &best_y);
      // Find the strongest edge.
      int test_y = y;
      do {
        ++test_y;
      } while (EvaluateVerticalDiff(data, wpl, diff_sign, x, test_y, height,
                                    &best_diff, &best_sum, &best_y));
      test_y = y;
      do {
        --test_y;
      } while (EvaluateVerticalDiff(data, wpl, diff_sign, x, test_y, height,
                                    &best_diff, &best_sum, &best_y));
      offset = diff_sign * (best_sum / 2 - threshold) +
          (y - best_y) * best_diff;
    } else if (pt1.x == pt2.x && abs(gradient.x()) * 2 >= abs(gradient.y())) {
      // Vertical step. diff_sign == 1 indicates black on the left.
      int diff_sign = (pt1.y > pt2.y) == negative ? 1 : -1;
      int x = pt1.x;
      int y = height - MAX(pt1.y, pt2.y);
      const l_uint32* line = pixGetData(pix) + y * wpl;
      int best_sum = 0;
      int best_x = x;
      EvaluateHorizontalDiff(line, diff_sign, x, width,
                             &best_diff, &best_sum, &best_x);
      // Find the strongest edge.
      int test_x = x;
      do {
        ++test_x;
      } while (EvaluateHorizontalDiff(line, diff_sign, test_x, width,
                                      &best_diff, &best_sum, &best_x));
      test_x = x;
      do {
        --test_x;
      } while (EvaluateHorizontalDiff(line, diff_sign, test_x, width,
                                      &best_diff, &best_sum, &best_x));
      offset = diff_sign * (threshold - best_sum / 2) +
          (best_x - x) * best_diff;
    }
    offsets[s].offset_numerator =
        static_cast<inT8>(ClipToRange(offset, -MAX_INT8, MAX_INT8));
    offsets[s].pixel_diff = static_cast<uinT8>(ClipToRange(best_diff, 0 ,
                                                           MAX_UINT8));
    if (negative) gradient = -gradient;
    // Compute gradient angle quantized to 256 directions, rotated by 64 (pi/2)
    // to convert from gradient direction to edge direction.
    offsets[s].direction =
        Modulo(FCOORD::binary_angle_plus_pi(gradient.angle()) + 64, 256);
    prev_gradient = next_gradient;
  }
}
Example #24
0
// Runs forward propagation of activations on the input line.
// See NetworkCpp for a detailed discussion of the arguments.
void LSTM::Forward(bool debug, const NetworkIO& input,
                   const TransposedArray* input_transpose,
                   NetworkScratch* scratch, NetworkIO* output) {
  input_map_ = input.stride_map();
  input_width_ = input.Width();
  if (softmax_ != NULL)
    output->ResizeFloat(input, no_);
  else if (type_ == NT_LSTM_SUMMARY)
    output->ResizeXTo1(input, no_);
  else
    output->Resize(input, no_);
  ResizeForward(input);
  // Temporary storage of forward computation for each gate.
  NetworkScratch::FloatVec temp_lines[WT_COUNT];
  for (int i = 0; i < WT_COUNT; ++i) temp_lines[i].Init(ns_, scratch);
  // Single timestep buffers for the current/recurrent output and state.
  NetworkScratch::FloatVec curr_state, curr_output;
  curr_state.Init(ns_, scratch);
  ZeroVector<double>(ns_, curr_state);
  curr_output.Init(ns_, scratch);
  ZeroVector<double>(ns_, curr_output);
  // Rotating buffers of width buf_width allow storage of the state and output
  // for the other dimension, used only when working in true 2D mode. The width
  // is enough to hold an entire strip of the major direction.
  int buf_width = Is2D() ? input_map_.Size(FD_WIDTH) : 1;
  GenericVector<NetworkScratch::FloatVec> states, outputs;
  if (Is2D()) {
    states.init_to_size(buf_width, NetworkScratch::FloatVec());
    outputs.init_to_size(buf_width, NetworkScratch::FloatVec());
    for (int i = 0; i < buf_width; ++i) {
      states[i].Init(ns_, scratch);
      ZeroVector<double>(ns_, states[i]);
      outputs[i].Init(ns_, scratch);
      ZeroVector<double>(ns_, outputs[i]);
    }
  }
  // Used only if a softmax LSTM.
  NetworkScratch::FloatVec softmax_output;
  NetworkScratch::IO int_output;
  if (softmax_ != NULL) {
    softmax_output.Init(no_, scratch);
    ZeroVector<double>(no_, softmax_output);
    int rounded_softmax_inputs = gate_weights_[CI].RoundInputs(ns_);
    if (input.int_mode())
      int_output.Resize2d(true, 1, rounded_softmax_inputs, scratch);
    softmax_->SetupForward(input, NULL);
  }
  NetworkScratch::FloatVec curr_input;
  curr_input.Init(na_, scratch);
  StrideMap::Index src_index(input_map_);
  // Used only by NT_LSTM_SUMMARY.
  StrideMap::Index dest_index(output->stride_map());
  do {
    int t = src_index.t();
    // True if there is a valid old state for the 2nd dimension.
    bool valid_2d = Is2D();
    if (valid_2d) {
      StrideMap::Index dim_index(src_index);
      if (!dim_index.AddOffset(-1, FD_HEIGHT)) valid_2d = false;
    }
    // Index of the 2-D revolving buffers (outputs, states).
    int mod_t = Modulo(t, buf_width);      // Current timestep.
    // Setup the padded input in source.
    source_.CopyTimeStepGeneral(t, 0, ni_, input, t, 0);
    if (softmax_ != NULL) {
      source_.WriteTimeStepPart(t, ni_, nf_, softmax_output);
    }
    source_.WriteTimeStepPart(t, ni_ + nf_, ns_, curr_output);
    if (Is2D())
      source_.WriteTimeStepPart(t, ni_ + nf_ + ns_, ns_, outputs[mod_t]);
    if (!source_.int_mode()) source_.ReadTimeStep(t, curr_input);
    // Matrix multiply the inputs with the source.
    PARALLEL_IF_OPENMP(GFS)
    // It looks inefficient to create the threads on each t iteration, but the
    // alternative of putting the parallel outside the t loop, a single around
    // the t-loop and then tasks in place of the sections is a *lot* slower.
    // Cell inputs.
    if (source_.int_mode())
      gate_weights_[CI].MatrixDotVector(source_.i(t), temp_lines[CI]);
    else
      gate_weights_[CI].MatrixDotVector(curr_input, temp_lines[CI]);
    FuncInplace<GFunc>(ns_, temp_lines[CI]);

    SECTION_IF_OPENMP
    // Input Gates.
    if (source_.int_mode())
      gate_weights_[GI].MatrixDotVector(source_.i(t), temp_lines[GI]);
    else
      gate_weights_[GI].MatrixDotVector(curr_input, temp_lines[GI]);
    FuncInplace<FFunc>(ns_, temp_lines[GI]);

    SECTION_IF_OPENMP
    // 1-D forget gates.
    if (source_.int_mode())
      gate_weights_[GF1].MatrixDotVector(source_.i(t), temp_lines[GF1]);
    else
      gate_weights_[GF1].MatrixDotVector(curr_input, temp_lines[GF1]);
    FuncInplace<FFunc>(ns_, temp_lines[GF1]);

    // 2-D forget gates.
    if (Is2D()) {
      if (source_.int_mode())
        gate_weights_[GFS].MatrixDotVector(source_.i(t), temp_lines[GFS]);
      else
        gate_weights_[GFS].MatrixDotVector(curr_input, temp_lines[GFS]);
      FuncInplace<FFunc>(ns_, temp_lines[GFS]);
    }

    SECTION_IF_OPENMP
    // Output gates.
    if (source_.int_mode())
      gate_weights_[GO].MatrixDotVector(source_.i(t), temp_lines[GO]);
    else
      gate_weights_[GO].MatrixDotVector(curr_input, temp_lines[GO]);
    FuncInplace<FFunc>(ns_, temp_lines[GO]);
    END_PARALLEL_IF_OPENMP

    // Apply forget gate to state.
    MultiplyVectorsInPlace(ns_, temp_lines[GF1], curr_state);
    if (Is2D()) {
      // Max-pool the forget gates (in 2-d) instead of blindly adding.
      inT8* which_fg_col = which_fg_[t];
      memset(which_fg_col, 1, ns_ * sizeof(which_fg_col[0]));
      if (valid_2d) {
        const double* stepped_state = states[mod_t];
        for (int i = 0; i < ns_; ++i) {
          if (temp_lines[GF1][i] < temp_lines[GFS][i]) {
            curr_state[i] = temp_lines[GFS][i] * stepped_state[i];
            which_fg_col[i] = 2;
          }
        }
      }
    }
    MultiplyAccumulate(ns_, temp_lines[CI], temp_lines[GI], curr_state);
    // Clip curr_state to a sane range.
    ClipVector<double>(ns_, -kStateClip, kStateClip, curr_state);
    if (IsTraining()) {
      // Save the gate node values.
      node_values_[CI].WriteTimeStep(t, temp_lines[CI]);
      node_values_[GI].WriteTimeStep(t, temp_lines[GI]);
      node_values_[GF1].WriteTimeStep(t, temp_lines[GF1]);
      node_values_[GO].WriteTimeStep(t, temp_lines[GO]);
      if (Is2D()) node_values_[GFS].WriteTimeStep(t, temp_lines[GFS]);
    }
    FuncMultiply<HFunc>(curr_state, temp_lines[GO], ns_, curr_output);
    if (IsTraining()) state_.WriteTimeStep(t, curr_state);
    if (softmax_ != NULL) {
      if (input.int_mode()) {
        int_output->WriteTimeStepPart(0, 0, ns_, curr_output);
        softmax_->ForwardTimeStep(NULL, int_output->i(0), t, softmax_output);
      } else {
        softmax_->ForwardTimeStep(curr_output, NULL, t, softmax_output);
      }
      output->WriteTimeStep(t, softmax_output);
      if (type_ == NT_LSTM_SOFTMAX_ENCODED) {
        CodeInBinary(no_, nf_, softmax_output);
      }
    } else if (type_ == NT_LSTM_SUMMARY) {
      // Output only at the end of a row.
      if (src_index.IsLast(FD_WIDTH)) {
        output->WriteTimeStep(dest_index.t(), curr_output);
        dest_index.Increment();
      }
    } else {
      output->WriteTimeStep(t, curr_output);
    }
    // Save states for use by the 2nd dimension only if needed.
    if (Is2D()) {
      CopyVector(ns_, curr_state, states[mod_t]);
      CopyVector(ns_, curr_output, outputs[mod_t]);
    }
    // Always zero the states at the end of every row, but only for the major
    // direction. The 2-D state remains intact.
    if (src_index.IsLast(FD_WIDTH)) {
      ZeroVector<double>(ns_, curr_state);
      ZeroVector<double>(ns_, curr_output);
    }
  } while (src_index.Increment());
#if DEBUG_DETAIL > 0
  tprintf("Source:%s\n", name_.string());
  source_.Print(10);
  tprintf("State:%s\n", name_.string());
  state_.Print(10);
  tprintf("Output:%s\n", name_.string());
  output->Print(10);
#endif
  if (debug) DisplayForward(*output);
}
Example #25
0
Vector SDKGradientClass::Output(BaseShader *sh, ChannelData *sd)
{
	Vector p=sd->p;
	Real	 r=0.0,angle,xx,yy;

	if (gdata.turbulence>0.0)
	{
		Vector	res;
		Real		scl=5.0*gdata.scale,tt=sd->t*gdata.freq*0.3;

		res = Vector(Turbulence(p*scl,tt,gdata.octaves,TRUE),Turbulence((p+Vector(0.34,13.0,2.43))*scl,tt,gdata.octaves,TRUE),0.0);

		if (gdata.absolute)
		{
			p.x  = Mix(p.x,res.x,gdata.turbulence);
			p.y  = Mix(p.y,res.y,gdata.turbulence);
		}
		else
		{
			p.x += (res.x-0.5)*gdata.turbulence;
			p.y += (res.y-0.5)*gdata.turbulence;
		}
	}

	// rotation
	p.x -= 0.5;
	p.y -= 0.5;

	xx = gdata.ca*p.x-gdata.sa*p.y + 0.5;
	yy = gdata.sa*p.x+gdata.ca*p.y + 0.5;

	p.x = xx;
	p.y = yy;

	if (gdata.mode<=SDKGRADIENTSHADER_MODE_CORNER && gdata.cycle && (sd->texflag&TEX_TILE))
	{
		if (sd->texflag & TEX_MIRROR)
		{
			p.x = Modulo(p.x,RCO 2.0);
			if (p.x>=1.0) p.x=2.0-p.x;

			p.y = Modulo(p.y,RCO 2.0);
			if (p.y>= 1.0) p.y=2.0-p.y;
		}
		else
		{
			p.x = Modulo(p.x, RCO 1.0);
			p.y = Modulo(p.y, RCO 1.0);
		}
	}

	switch (gdata.mode)
	{
		case SDKGRADIENTSHADER_MODE_U:
			r = p.x; 
			break;

		case SDKGRADIENTSHADER_MODE_V:
			r = 1.0-p.y; 
			break;

		case SDKGRADIENTSHADER_MODE_DIAGONAL:
			r = (p.x+p.y)*0.5; 
			break;

		case SDKGRADIENTSHADER_MODE_RADIAL:
			p.x-=0.5;
			p.y-=0.5;
			if (p.x==0.0) p.x=0.00001;

			angle = ATan(p.y/p.x);
			if (p.x<0.0) angle+=pi;
			if (angle<0.0) angle+=pi2;
			r = angle/pi2;
			break;

		case SDKGRADIENTSHADER_MODE_CIRCULAR:
			p.x-=0.5;
			p.y-=0.5;
			r = Sqrt(p.x*p.x+p.y*p.y)*2.0;
			break;

		case SDKGRADIENTSHADER_MODE_BOX:
			p.x = Abs(p.x - 0.5);
			p.y = Abs(p.y - 0.5);
			r   = FMax(p.x,p.y)*2.0;
			break;

		case SDKGRADIENTSHADER_MODE_STAR:
			p.x = Abs(p.x - 0.5)-0.5;
			p.y = Abs(p.y - 0.5)-0.5;
			r   = Sqrt(p.x*p.x+p.y*p.y) * 1.4142;
			break;

		case SDKGRADIENTSHADER_MODE_CORNER:
		{
			Real		cx;
			Vector	ca,cb;

			cx = FCut01(p.x);
			ca = Mix(gdata.c[0],gdata.c[1],cx);
			cb = Mix(gdata.c[2],gdata.c[3],cx);

			return Mix(ca,cb,FCut01(p.y));
			break;
		}
	}

	return gdata.gradient->CalcGradientPixel(FCut01(r));
}
Example #26
0
   void CEPuckLightSensor::Update() {
      /* Here we assume that the e-puck is rotated only wrt to the Z axis */

      /* Erase readings */
      for(size_t i = 0; i < m_tReadings.size(); ++i) {
         m_tReadings[i].Value = 0.0f;
      }
      /* Get e-puck position */
      const CVector3& cEPuckPosition = GetEntity().GetEmbodiedEntity().GetPosition();
      /* Get e-puck orientation */
      CRadians cTmp1, cTmp2, cOrientationZ;
      GetEntity().GetEmbodiedEntity().GetOrientation().ToEulerAngles(cOrientationZ, cTmp1, cTmp2);
      /* Buffer for calculating the light--e-puck distance */
      CVector3 cLightDistance;
      /* Buffer for the angle of the sensor wrt to the e-puck */
      CRadians cLightAngle;
      /* Initialize the occlusion check ray start to the baseline of the e-puck */
      CRay cOcclusionCheckRay;
      cOcclusionCheckRay.SetStart(cEPuckPosition);
      /* Buffer to store the intersection data */
      CSpace::SEntityIntersectionItem<CEmbodiedEntity> sIntersectionData;
      /* Ignore the sensing ropuck when checking for occlusions */
      TEmbodiedEntitySet tIgnoreEntities;
      tIgnoreEntities.insert(&GetEntity().GetEmbodiedEntity());
      /*
       * 1. go through the list of light entities in the scene
       * 2. check if a light is occluded
       * 3. if it isn't, distribute the reading across the sensors
       *    NOTE: the readings are additive
       * 4. go through the sensors and clamp their values
       */
      try{
         CSpace::TAnyEntityMap& tEntityMap = m_cSpace.GetEntitiesByType("light_entity");
         for(CSpace::TAnyEntityMap::iterator it = tEntityMap.begin();
             it != tEntityMap.end();
             ++it) {
            /* Get a reference to the light */
            CLightEntity& cLight = *(any_cast<CLightEntity*>(it->second));
            /* Consider the light only if it has non zero intensity */
            if(cLight.GetIntensity() > 0.0f) {
               /* Get the light position */
               const CVector3& cLightPosition = cLight.GetPosition();
               /* Set the ray end */
               cOcclusionCheckRay.SetEnd(cLightPosition);
               /* Check occlusion between the e-puck and the light */
               if(! m_cSpace.GetClosestEmbodiedEntityIntersectedByRay(sIntersectionData,
                                                                      cOcclusionCheckRay,
                                                                      tIgnoreEntities)) {
                  /* The light is not occluded */
                  if(m_bShowRays) GetEntity().GetControllableEntity().AddCheckedRay(false, cOcclusionCheckRay);
                  /* Get the distance between the light and the e-puck */
                  cOcclusionCheckRay.ToVector(cLightDistance);
                  /* Linearly scale the distance with the light intensity
                     The greater the intensity, the smaller the distance */
                  cLightDistance /= cLight.GetIntensity();
                  /* Get the angle wrt to e-puck rotation */
                  cLightAngle = cLightDistance.GetZAngle();
                  cLightAngle -= cOrientationZ;
                  /* Transform it into counter-clockwise rotation */
                  cLightAngle.Negate().UnsignedNormalize();
                  /* Find reading corresponding to the sensor */
                  SInt16 nMin = 0;
                  for(SInt16 i = 1; i < NUM_READINGS; ++i){
                     if((cLightAngle - m_tReadings[i].Angle).GetAbsoluteValue() < (cLightAngle - m_tReadings[nMin].Angle).GetAbsoluteValue())
                        nMin = i;
                  }
                  /* Set the actual readings */
                  Real fReading = cLightDistance.Length();
                  m_tReadings[Modulo((SInt16)(nMin-1), NUM_READINGS)].Value += ComputeReading(fReading * Cos(cLightAngle - m_tReadings[Modulo(nMin-1, NUM_READINGS)].Angle));
                  m_tReadings[  nMin                                ].Value += ComputeReading(fReading);
                  m_tReadings[Modulo((SInt16)(nMin+1), NUM_READINGS)].Value += ComputeReading(fReading * Cos(cLightAngle - m_tReadings[Modulo(nMin+1, NUM_READINGS)].Angle));
               }
               else {
                  /* The ray is occluded */
                  if(m_bShowRays) {
                     GetEntity().GetControllableEntity().AddCheckedRay(true, cOcclusionCheckRay);
                     GetEntity().GetControllableEntity().AddIntersectionPoint(cOcclusionCheckRay, sIntersectionData.TOnRay);
                  }
               }
            }
         }
      }
      catch(argos::CARGoSException& e){

      }

      /* Now go through the sensors, add noise and clamp their values if above 1024 or under 1024 */
      for(size_t i = 0; i < m_tReadings.size(); ++i) {
         if(m_fNoiseLevel>0.0f)
            AddNoise(i);
         if(m_tReadings[i].Value > 1024.0f)
            m_tReadings[i].Value = 1024.0f;
         if(m_tReadings[i].Value < 0.0f)
            m_tReadings[i].Value = 0.0f;
      }
   }