Ejemplo n.º 1
0
void Event_test::callOnce()
{
  ThreadSafeCounter count("gov.fnal.counter");
  bool wasChanged=false;
  
  AccessTestingProd* at(new AccessTestingProd("access","",demo::kThreadSafeBetweenInstances,count,wasChanged));
  std::vector<std::pair<std::string, std::string> > toGet;
  toGet.push_back(std::pair<std::string,std::string>("access",""));
  SumSyncProd* sum1(new SumSyncProd("sum1","",toGet));
  SumSyncProd* sum2(new SumSyncProd("sum2","",toGet));

  toGet.clear();
  toGet.push_back(std::pair<std::string,std::string>("sum1",""));
  toGet.push_back(std::pair<std::string,std::string>("sum2",""));
  SumSyncProd* sum3(new SumSyncProd("sum3","",toGet));

  demo::Event event;
  event.setIndex(1);
  
  event.addProducer(at);
  event.addProducer(sum1);
  event.addProducer(sum2);
  event.addProducer(sum3);
  
  CPPUNIT_ASSERT(event.get("sum3","")==2);
  CPPUNIT_ASSERT(count.value()==1);
  CPPUNIT_ASSERT(wasChanged==false);
}
Ejemplo n.º 2
0
    bool IntegralAutoTest(int width, int height, bool sqsumEnable, bool tiltedEnable, View::Format sumFormat, View::Format sqsumFormat, const Func & f1, const Func & f2)
    {
        bool result = true;

        TEST_LOG_SS(Info, "Test " << f1.description << " & " << f2.description << " [" << width << ", " << height << "].");

        View src(width, height, View::Gray8, NULL, TEST_ALIGN(width));
        FillRandom(src);

        View sum1(width + 1, height + 1, sumFormat, NULL, TEST_ALIGN(width));
        View sum2(width + 1, height + 1, sumFormat, NULL, TEST_ALIGN(width));
        View sqsum1, sqsum2, tilted1, tilted2;
        if(sqsumEnable)
        {
            sqsum1.Recreate(width + 1, height + 1, sqsumFormat, NULL, TEST_ALIGN(width));
            sqsum2.Recreate(width + 1, height + 1, sqsumFormat, NULL, TEST_ALIGN(width));
        }
        if(tiltedEnable)
        {
            tilted1.Recreate(width + 1, height + 1, sumFormat, NULL, TEST_ALIGN(width));
            tilted2.Recreate(width + 1, height + 1, sumFormat, NULL, TEST_ALIGN(width));
        }

        TEST_EXECUTE_AT_LEAST_MIN_TIME(f1.Call(src, sum1, sqsum1, tilted1));

        TEST_EXECUTE_AT_LEAST_MIN_TIME(f2.Call(src, sum2, sqsum2, tilted2));

        result = result && Compare(sum1, sum2, 0, true, 32, 0, "sum");
        if(sqsumEnable)
            result = result && Compare(sqsum1, sqsum2, 0, true, 32, 0, "sqsum");
        if(tiltedEnable)
            result = result && Compare(tilted1, tilted2, 0, true, 32, 0, "tilted");

        return result;
    }
Ejemplo n.º 3
0
int main()
{
	int i = 10, j = 20, k;
	k = sum2(i, j);
	printf("k: %d\n", k);
	return 0;
}
Ejemplo n.º 4
0
void BiorCoefTests()
{
    wave_object obj;
    double epsilon = 1e-10;
    double t1,t2,t3,t4,t5,t6;
    std::vector<std::string > waveletNames;
    waveletNames.push_back("bior1.1");
    waveletNames.push_back("bior1.3");
    waveletNames.push_back("bior1.5");
    waveletNames.push_back("bior2.2");
    waveletNames.push_back("bior2.4");
    waveletNames.push_back("bior2.6");
    waveletNames.push_back("bior2.8");
    waveletNames.push_back("bior3.1");
    waveletNames.push_back("bior3.3");
    waveletNames.push_back("bior3.5");
    waveletNames.push_back("bior3.7");
    waveletNames.push_back("bior3.9");
    waveletNames.push_back("bior4.4");
    waveletNames.push_back("bior5.5");
    waveletNames.push_back("bior6.8");

    for (unsigned int j = 0; j < waveletNames.size(); j++)
    {
        char * name = new char[waveletNames[j].size() + 1];
        memcpy(name, waveletNames[j].c_str(), waveletNames[j].size() + 1);
        obj = wave_init(name);// Initialize the wavelet
        
        t1 = sum1(obj->lpr, obj->lpr_len) - sqrt(2.0);
        t2 = sum1(obj->lpd, obj->lpd_len) - sqrt(2.0);
        
        t3 = sum2(obj->lpr, obj->lpr_len) - 1. / sqrt(2.0);
        t4 = sum2(obj->lpd, obj->lpd_len) - 1. / sqrt(2.0);
        
        t5 = sum3(obj->lpr, obj->lpr_len) - 1. / sqrt(2.0);
        t6 = sum3(obj->lpd, obj->lpd_len) - 1. / sqrt(2.0);
        
        if (fabs(t1) > epsilon || fabs(t2) > epsilon || fabs(t3) > epsilon || fabs(t4) > epsilon || fabs(t5) > epsilon || fabs(t6) > epsilon ) {
			printf("\n ERROR : Bior Coefficients Unit Test Failed. Exiting. \n");
			exit(-1);
		}
        
        
        wave_free(obj);
        delete[] name;
    }
}
Ejemplo n.º 5
0
int main() {
  int a[] = {1, 2, 3, 5, 8};
  printf("%d\n", sum0(a)); // 错误
  printf("%d\n", sum1(a, 5));
  printf("%d\n", sum2(a, a+5));
  printf("%d\n", sum3(a, a+5));
  return 0;
}
Ejemplo n.º 6
0
void CreateStorageBindingConstraint(IloModel model, BoolVar3DMatrix L, BoolVarMatrix M, 
			                              BoolVarMatrix X, BoolVar3DMatrix R, BoolVarMatrix Y, 
                                    IloRangeArray c){

  IloEnv env = model.getEnv();

  //The nested for-loops generate L[p][i][t]
  //that is required to linearize equation 16
  for(int p = 0; p < L.getSize(); p++){
    for(int i = 0; i < n; i++){
      for(int t = 0; t < T_MAX; t++){
	     L[p][i].add(IloBoolVar(env));
	     c.add(L[p][i][t] - M[p][i] - X[i][t] >= -1);
	     c.add(L[p][i][t] - M[p][i] - X[i][t] <=  0);
	     c.add(L[p][i][t] + M[p][i] - X[i][t] <=  1);
	     c.add(L[p][i][t] - M[p][i] + X[i][t] <=  1);
      }
    }
  }

  //Contructing the array R[p][e][t]
  for(int p = 0; p < R.getSize(); p++){
    for(int e = 0; e < E; e++){
      for(int t = 0; t < T_MAX; t++){
	     R[p][e].add(IloBoolVar(env));
      }
    }
  }

  //Encoding the constraint eqn-15
  for(int t = 0; t < T_MAX; t++){
    IloExprArray sum(env);
    for(int e = 0; e < E; e++){
      sum.add(IloExpr(env));
      for(int p = 0; p < n_m; p++){
        sum[e] += R[p][e][t];
      }
      c.add(sum[e] - Y[e][t] == 0);
    }
  }

  //Encoding the constraint eqn-21
  for(int t = 0; t < T_MAX; t++){
    IloExprArray sum1(env);
    IloExprArray sum2(env);
    for(int p = 0; p < n_m; p++){
      sum1.add(IloExpr(env));
      sum2.add(IloExpr(env));
      for(int e = 0; e < E; e++)
        sum1[p] += R[p][e][t];
      for(int i = 0; i < n; i++)
        sum2[p] += L[p][i][t];
      c.add(sum1[p] - n_r*sum2[p] <= 0);
    }
  }

  return;
}
Ejemplo n.º 7
0
int main(){
	int a[] = {1,2,3,4,5};
	int t = sum(a, 5);
	int t1 = sum1(a, 5);
	int t2 = sum2(a, 5);
	int t3 = sum3(a, 5);
	printf("t = %d\nt1 = %d\nt2 = %d\nt3 = %d\n", t, t1, t2, t3);
	return t;
}
Ejemplo n.º 8
0
int main()
{
  SymmetricMatrix a;
  AntiSymmetricMatrix b;
  SingularMatrix c;
  DifferentStrange d;

  sum(a);
  sum(b);
  sum(c);
  //  sum(d); : compile error

  std::cout << "\n";

  sum2(a);
  sum2(b);
  sum2(c);
  sum2(d);
}
Ejemplo n.º 9
0
double mean(const std::vector<double>& v) {
    /*
     * Computes the mean of a vector of doubles
     * args:
     *      v is a double vector passed by ref
     * returns:
     * the mean of the vector as a double
     */
    double result = sum2(v) / (double)v.size();
    return result;
}
Ejemplo n.º 10
0
Archivo: sum.c Proyecto: MiCHiLU/algo
int main()
{
    int i;
    static float a[10001];

    printf("1 + 0.0001 + ... + 0.0001 = 2\n");
    a[0] = 1;
    for (i = 1; i <= 10000; i++) a[i] = 0.0001;
    printf("方法1: %.6f\n", sum1(10001, a));
    printf("方法2: %.6f\n", sum2(10001, a));
    return EXIT_SUCCESS;
}
int main(int argc, char *argv[]) {

  for(int i=0;i<SIZE;i++) {
    for(int j=0;j<SIZE;j++) {
      matrix[i][j]=1;
    }
  }
  printf("%d \n",sum());
  printf("%d \n",sum2());

   return(EXIT_SUCCESS);
}
Ejemplo n.º 12
0
// sum 函式的 interface
static PyObject* mod_sum(PyObject *self, PyObject *args)
{
    int a;
    int b;
    int s;
    // ii 表示兩個輸入變數都是整數
    if (!PyArg_ParseTuple(args,"ii",&a,&b))
       return NULL;
    // 這裡的 sum2 則是內部的函式定義, 與外部呼叫模組或函式名稱沒有直接關係
    s = sum2(a,b);
    // i 表示 s 為整數
    return Py_BuildValue("i",s);
}
Ejemplo n.º 13
0
Archivo: sum_to_n.c Proyecto: ajdan4q/c
int main (int argc, char *argv[])
{
	if (argc != 3)
	{
		fprintf(stderr, "USAGE: %s sum sum\n", argv[0]);
		return EXIT_FAILURE;
	}

	printf("sum  %d\n", sum(atoi(argv[1])));
	printf("sum2 %d\n", sum2(atoi(argv[2])));

	return EXIT_SUCCESS;
}
Ejemplo n.º 14
0
Archivo: va.c Proyecto: minhajksm/code
int main(void)
{
  long va_sum;

  va_sum = sum1(5, -1,3,4,5,3);
  printf("%ld\n", va_sum);
  va_sum = sum1(10, 1,2,3,4,5,6,7,8,9,10);
  printf("%ld\n", va_sum);

  va_sum = sum2(5, -1,3,4,5,3);
	printf("%ld\n", va_sum);

	return 0;
}
Ejemplo n.º 15
0
    bool IntegralDataTest(bool create, int width, int height, const Func & f)
    {
        bool result = true;

        Data data(f.description);

        TEST_LOG_SS(Info, (create ? "Create" : "Verify") << " test " << f.description << " [" << width << ", " << height << "].");

        View src(width, height, View::Gray8, NULL, TEST_ALIGN(width));

        View sum1(width + 1, height + 1, View::Int32, NULL, TEST_ALIGN(width));
        View sum2(width + 1, height + 1, View::Int32, NULL, TEST_ALIGN(width));
        View sqsum1(width + 1, height + 1, View::Int32, NULL, TEST_ALIGN(width));
        View sqsum2(width + 1, height + 1, View::Int32, NULL, TEST_ALIGN(width));
        View tilted1(width + 1, height + 1, View::Int32, NULL, TEST_ALIGN(width));
        View tilted2(width + 1, height + 1, View::Int32, NULL, TEST_ALIGN(width));

        if(create)
        {
            FillRandom(src);

            TEST_SAVE(src);

            f.Call(src, sum1, sqsum1, tilted1);

            TEST_SAVE(sum1);
            TEST_SAVE(sqsum1);
            TEST_SAVE(tilted1);
        }
        else
        {
            TEST_LOAD(src);

            TEST_LOAD(sum1);
            TEST_LOAD(sqsum1);
            TEST_LOAD(tilted1);

            f.Call(src, sum2, sqsum2, tilted2);

            TEST_SAVE(sum2);
            TEST_SAVE(sqsum2);
            TEST_SAVE(tilted2);

            result = result && Compare(sum1, sum2, 0, true, 32, 0, "sum");
            result = result && Compare(sqsum1, sqsum2, 0, true, 32, 0, "sqsum");
            result = result && Compare(tilted1, tilted2, 0, true, 32, 0, "tilted");
        }

        return result;
    }
Ejemplo n.º 16
0
uint_t sum3(const uint_t &n)
{
    uint_t sum = 0;

    if(n <= 0) {
        for(int i = 1; i >= n; i--) {
            sum += i;
        }
    } else {
        sum = sum2(n);
    }

    return sum;
}
Ejemplo n.º 17
0
int main()
{
	int i;
	int n, m;
	scanf("%d",&n);
	int *a = (int *)malloc(n*sizeof(int));
	for (i = 0; i < n; i++)
		scanf("%d",&a[i]);
	printf("%d\n",sum1(a,n));
	scanf("%d",&m);
	float *b = (float *)malloc(m*sizeof(float));
	for (i = 0; i < m; i++)
		scanf("%f",&b[i]);
	printf("%f\n",sum2(b,m));
	return 0;
}
 vector<int> maxSumOfThreeSubarrays(vector<int>& nums, int k) {
     vector<int> sum(nums.size() + 1);
     sum[0] = 0;
     for(int i=0; i<nums.size(); i++)
         sum[i+1] = sum[i] + nums[i];
     
     vector<int> sum1(nums.size(), 0), sum2(nums.size(), 0), sum3(nums.size(), 0);
     vector<vector<int>> result1(nums.size()), result2(nums.size()), result3(nums.size());
     
     for(int i=k-1; i < (nums.size() - (2 * k)); i++) {
         if(sum1[i-1] < sum[i+1] - sum[i-k+1]) {
             sum1[i] = sum[i+1] - sum[i-k+1];
             result1[i].push_back(i-k+1);
         }
         else {
             sum1[i] = sum1[i-1];
             result1[i] = result1[i-1];
         }
         //sum1[i] = max(sum1[i-1], sum[i+1] - sum[i-k+1]);
     }
     for(int i=(2*k)-1; i < (nums.size() - k); i++) {
         if(sum2[i-1] < sum1[i-k] + sum[i+1] - sum[i-k+1]) {
             sum2[i] = sum1[i-k] + sum[i+1] - sum[i-k+1];
             result2[i] = result1[i-k];
             result2[i].push_back(i-k+1);
         }
         else {
             sum2[i] = sum2[i-1];
             result2[i] = result2[i-1];
         }
         //sum2[i] = max(sum2[i-1], sum1[i-k] + sum[i+1] - sum[i-k+1]);
     }
     for(int i=(3*k)-1; i < nums.size(); i++) {
         if(sum3[i-1] < sum2[i-k] + sum[i+1] - sum[i-k+1]) {
             sum3[i] = sum2[i-k] + sum[i+1] - sum[i-k+1];
             result3[i] = result2[i-k];
             result3[i].push_back(i-k+1);
         }
         else {
             sum3[i] = sum3[i-1];
             result3[i] = result3[i-1];
         }
         //sum3[i] = max(sum3[i-1], sum2[i-k] + sum[i+1] - sum[i-k+1]);
     }
     
     return result3[nums.size()-1];
 }
Ejemplo n.º 19
0
int main(int argc, const char* argv[])
{
	struct timeval tv1,tv2,tv3;
	
	int ret1=gettimeofday(&tv1,NULL);
	int sumLine=sum();
	int ret2=gettimeofday(&tv2,NULL);
	int sumCol=sum2();
	int ret3=gettimeofday(&tv3,NULL);
	
	int diff1=(tv2.tv_sec-tv1.tv_sec)*1000000+(tv2.tv_usec-tv1.tv_usec);
	int diff2=(tv3.tv_sec-tv2.tv_sec)*1000000+(tv3.tv_usec-tv2.tv_usec);
	printf("Résultat de sum() est %d et la durée d'éxécution est de %2d usec\n",sumLine,diff1);
	printf("Résultat de sum2() est %d et la durée d'éxécution est de %2d usec\n",sumCol,diff2);
	double ratio=(double)diff2/(double)diff1;
	printf("Le calcul colonne par colonne prend %f fois plus de temps que le calcul ligne par ligne -> localité spatiale\n", ratio);
						
}
Ejemplo n.º 20
0
void CoifCoefTests()
{
    wave_object obj;
    double epsilon = 1e-15;
    double t1,t2,t3,t4,t5;
    std::vector<std::string > waveletNames;
    waveletNames.resize(17);
    for (unsigned int i = 0; i < waveletNames.size(); i++)
    {
        waveletNames[i] = std::string("coif") + patch::to_string(i + 1);
    }

    for (unsigned int j = 0; j < waveletNames.size(); j++)
    {
        char * name = new char[waveletNames[j].size() + 1];
        memcpy(name, waveletNames[j].c_str(), waveletNames[j].size() + 1);
        obj = wave_init(name);// Initialize the wavelet
        t1 = sum1(obj->lpr, obj->lpr_len) - sqrt(2.0);
        t2 = sum2(obj->lpr, obj->lpr_len) - 1. / sqrt(2.0);
        t3 = sum3(obj->lpr, obj->lpr_len) - 1. / sqrt(2.0);
        t4 = sum4(obj->lpr, obj->lpr_len) - 1.;
        
        if (fabs(t1) > epsilon || fabs(t2) > epsilon || fabs(t3) > epsilon || fabs(t4) > epsilon) {
			printf("\n ERROR : Coif Coefficients Unit Test Failed. Exiting. \n");
			exit(-1);
		}
        
        for (int m = 1; m < (obj->lpr_len / 2) - 1;m++) {
			t5 = sum5(obj->lpr, obj->lpr_len, m);
            if (fabs(t5) > epsilon) {
				printf("\n ERROR : Coif Coefficients Unit Test Failed. Exiting. \n");
				exit(-1);
			}
		}
        wave_free(obj);
        delete[] name;
    }
}
Ejemplo n.º 21
0
// Calculates v3 for the Prey at index "index". OBSTACLES TO BE ADDED.
Vector Sky::tooNear(int index, float K, float O, Vector* obstacles, int n_obstacles)
{
	Vector v3(0,0);
	Vector sum1(0,0);
	Vector sum2(0,0);
	int i;
	Vector position1 = flock[index].getPosition();
	float contact = flock[index].getContact();
	
	for (i=0; i<flock_size; i++) // For every bird of the flock
	{
		if(i!=index) 
		{
			Vector position2 = flock[i].getPosition();			

			if (position1.isSomeoneTouching(position2,contact) == true)  // Finding birds in radius of perception
				sum1 = sum1 + (position2 - position1);
		}
	}
	for (i=0; i<n_obstacles; i++) // For every obstacle
	{	
		Vector obstacle = obstacles[i];			

		if (position1.isSomeoneTouching(obstacle,contact) == true)
			sum2 = sum2 + (obstacle - position1);

				

			//printf("\nsum1 = (%lg,%lg),  sum2 = (%lg,%lg)\n", sum1.getX(), sum1.getY(), sum2.getX(), sum2.getY());
			
	}
	
	//printf("v3=(%lg,%lg)\n", v3.getX(), v3.getY());
	v3 = sum1/(-K) +sum2/(-O);

	return v3;
}
Ejemplo n.º 22
0
//========================================================================
//========================================================================
//
//	NAME:	complex<double> bessel_2_complex(int n, complex<double> arg)
//
//	DESC:	Calculates the Bessel function of the second kind (Yn) for
//		complex arguments.
//
//	INPUT:
//		int n:: Order of Bessel function
//		complex<double> arg: Bessel function argument
//	
//	OUTPUT:
//		complex<double> Yn:: Bessel function of the second kind of
//			order n
//		
//	NOTES:	1) The Bessel function of the second kind is defined as:
//			Yn(x) = (2.0*Jn(x)/pi)*(ln(x/2) + gamma_e) 
//				+ sum{m=0, m=inf}[(((-1)^(m-1))*(hs(m) + 
//					hs(m+n)) + x^(2*m))/(((2.0^(2*m+n))*m!*(m+n)!)
//				- sum{m=0, m=(n-1)}[((n-m-1)!*x^(2*m))/((2.0^(2*m-n))*m!)
//
//		2) Y-n = ((-1)^n)*Yn
//
//========================================================================
//========================================================================
complex<double> bessel_2_complex(int n, complex<double> arg)
{

  complex<double> Yn(0.0, 0.0);

  // get a tolerance for the "infinite" sum
  double tolerance = 100.0*depsilon();

 
  // make sure we calculate the positive order Bessel function
  int k = abs(n);


  // GET BESSEL FUNCTIONS OF THE FIRST KIND
  complex<double> Jn = bessel_1_complex(k, arg);


  // GET TERM SUM 1
  complex<double> sum1(0.0,0.0), sum11(0.0,0.0);


/*
  for(int i = 0; i <= 20; i++)
  {
    sum1 = sum1 + pow((0.0-1.0), (i-1))*(h_s(i) + h_s(i+k))*pow(arg, (2*i))/(pow(2.0, (2*i+k))*dfactorial(i)*dfactorial(i+k));
  }
*/

  // !!! my concern with this do loop is that if a certain term contributes 0 then the 
  // loop may inappropriately exit
  int mm_max = static_cast<int>(2.0*real(arg)) + 1;

  int mm = 0;

  do
  {
    sum11 = sum1;

    sum1 = sum1 + pow((0.0-1.0), (mm-1))*(h_s(mm) + h_s(mm+k))*pow(arg, (2*mm))/(pow(2.0, (2*mm+k))*dfactorial(mm)*dfactorial(mm+k));

    mm = mm + 1;

  } while((fabs(real(sqrt(sum1*conj(sum1) - sum11*conj(sum11)))) > tolerance) || (mm < mm_max));

  sum1 = pow(arg, k)*sum1/(1.0*PI);


  // GET TERM SUM 2
  complex<double> sum2(0.0,0.0);

  for(int m = 0; m <= (k-1); m++)
  {
    sum2 = sum2 + dfactorial((k-m-1))*pow(arg, (2*m))/(pow(2.0, (2*m-k))*dfactorial(m));
  }
  
  sum2 = pow(arg, (0-k))*sum2/(1.0*PI);


  // NOW GET Yn
  Yn = (2.0*Jn/(1.0*PI))*(log(arg/2.0) + EULERC) + sum1 - sum2;


  // NOW WE WILL MAKE USE OF THE BESSEL FUNCTION RELATION FOR NEGATIVE n:
  // Y(n-1) = (-1)^n*Yn
  if(n < 0)
  {
    Yn = pow((0.0-1.0), k)*Yn;
  }


  return Yn;

}
Ejemplo n.º 23
0
void solve()
{
	printf("%d\n", sum1(N));
	printf("%d\n", sum2(N));
	printf("%d\n", sum1(N) - sum2(N));
}
}


int main(void) {
    struct node n1[] = {
        {.value = 0},
        {.value = 5},
        {.value = 1},
        {.value = 3},
    };

    struct node n2[] = {
        {.value = 0},
        {.value = 2},
        {.value = 9},
        {.value = 5},
    };

    #define setup(x) do {                               \
    for (int i = 1; i < sizeof((x))/sizeof((x)[0]);i++) \
        insert(&(x)[0],&(x)[i]);                        \
    } while(0)

    setup(n1);
    setup(n2);

    #undef setup
    printf("%d\n",sum(&n1[0],&n2[0]));
    printf("%d\n",sum2(&n1[0],&n2[0]));
}
Ejemplo n.º 25
0
void scan3d::reconstruct_model_patch_center(Pointcloud & pointcloud, CalibrationData const& calib, 
                                cv::Mat const& pattern_image, cv::Mat const& min_max_image, cv::Mat const& color_image,
                                cv::Size const& projector_size, int threshold, double max_dist, QWidget * parent_widget)
{
    if (!pattern_image.data || pattern_image.type()!=CV_32FC2)
    {   //pattern not correctly decoded
        std::cerr << "[reconstruct_model] ERROR invalid pattern_image\n";
        return;
    }
    if (!min_max_image.data || min_max_image.type()!=CV_8UC2)
    {   //pattern not correctly decoded
        std::cerr << "[reconstruct_model] ERROR invalid min_max_image\n";
        return;
    }
    if (color_image.data && color_image.type()!=CV_8UC3)
    {   //not standard RGB image
        std::cerr << "[reconstruct_model] ERROR invalid color_image\n";
        return;
    }
    if (!calib.is_valid())
    {   //invalid calibration
        return;
    }

    //parameters
    //const unsigned threshold = config.value("main/shadow_threshold", 70).toUInt();
    //const double   max_dist  = config.value("main/max_dist_threshold", 40).toDouble();
    //const bool     remove_background = config.value("main/remove_background", true).toBool();
    //const double   plane_dist = config.value("main/plane_dist", 100.0).toDouble();
    double plane_dist = 100.0;

    /* background removal
    cv::Point2i plane_coord[3];
    plane_coord[0] = cv::Point2i(config.value("background_plane/x1").toUInt(), config.value("background_plane/y1").toUInt());
    plane_coord[1] = cv::Point2i(config.value("background_plane/x2").toUInt(), config.value("background_plane/y2").toUInt());
    plane_coord[2] = cv::Point2i(config.value("background_plane/x3").toUInt(), config.value("background_plane/y3").toUInt());

    if (plane_coord[0].x<=0 || plane_coord[0].x>=pattern_local.cols
        || plane_coord[0].y<=0 || plane_coord[0].y>=pattern_local.rows)
    {
        plane_coord[0] = cv::Point2i(50, 50);
        config.setValue("background_plane/x1", plane_coord[0].x);
        config.setValue("background_plane/y1", plane_coord[0].y);
    }
    if (plane_coord[1].x<=0 || plane_coord[1].x>=pattern_local.cols
        || plane_coord[1].y<=0 || plane_coord[1].y>=pattern_local.rows)
    {
        plane_coord[1] = cv::Point2i(50, pattern_local.rows-50);
        config.setValue("background_plane/x2", plane_coord[1].x);
        config.setValue("background_plane/y2", plane_coord[1].y);
    }
    if (plane_coord[2].x<=0 || plane_coord[2].x>=pattern_local.cols
        || plane_coord[2].y<=0 || plane_coord[2].y>=pattern_local.rows)
    {
        plane_coord[2] = cv::Point2i(pattern_local.cols-50, 50);
        config.setValue("background_plane/x3", plane_coord[2].x);
        config.setValue("background_plane/y3", plane_coord[2].y);
    }
    */

    //init point cloud
    //初始化点云数据为NAN,大小是经过缩放的
    int scale_factor_x = 1;
    int scale_factor_y = (projector_size.width>projector_size.height ? 1 : 2); //XXX HACK: preserve regular aspect ratio XXX HACK
    int out_cols = projector_size.width/scale_factor_x;
    int out_rows = projector_size.height/scale_factor_y;
    pointcloud.clear();
    pointcloud.init_points(out_rows, out_cols);//NAN点:point初始化(pointcloud成员变量)
    pointcloud.init_color(out_rows, out_cols);//白色图像:color初始化(pointcloud成员变量)

    //progress


    //take 3 points in back plane
    /*cv::Mat plane;
    if (remove_background)
    {
        cv::Point3d p[3];
        for (unsigned i=0; i<3;i++)
        {
            for (unsigned j=0; 
                j<10 && (
                    INVALID(pattern_local.at<cv::Vec2f>(plane_coord[i].y, plane_coord[i].x)[0])
                    || INVALID(pattern_local.at<cv::Vec2f>(plane_coord[i].y, plane_coord[i].x)[1])); j++)
            {
                plane_coord[i].x += 1.f;
            }
            const cv::Vec2f & pattern = pattern_local.at<cv::Vec2f>(plane_coord[i].y, plane_coord[i].x);

            const float col = pattern[0];
            const float row = pattern[1];

            if (projector_size.width<=static_cast<int>(col) || projector_size.height<=static_cast<int>(row))
            {   //abort
                continue;
            }

            //shoot a ray through the image: u=\lambda*v + q
            cv::Point3d u1 = camera.to_world_coord(plane_coord[i].x, plane_coord[i].y);
            cv::Point3d v1 = camera.world_ray(plane_coord[i].x, plane_coord[i].y);

            //shoot a ray through the projector: u=\lambda*v + q
            cv::Point3d u2 = projector.to_world_coord(col, row);
            cv::Point3d v2 = projector.world_ray(col, row);

            //compute ray-ray approximate intersection
            double distance = 0.0;
            p[i] = geometry::approximate_ray_intersection(v1, u1, v2, u2, &distance);
            std::cout << "Plane point " << i << " distance " << distance << std::endl;
        }
        plane = geometry::get_plane(p[0], p[1], p[2]);
        if (cv::Mat(plane.rowRange(0,3).t()*cv::Mat(cv::Point3d(p[0].x, p[0].y, p[0].z-1.0)) + plane.at<double>(3,0)).at<double>(0,0)
                <0.0)
        {
            plane = -1.0*plane;
        }
        std::cout << "Background plane: " << plane << std::endl;
    }
    */

    //candidate points
    QMap<unsigned, cv::Point2f> proj_points;
    QMap<unsigned, std::vector<cv::Point2f> > cam_points;

    //cv::Mat proj_image = cv::Mat::zeros(out_rows, out_cols, CV_8UC3);

    unsigned good = 0;
    unsigned bad  = 0;
    unsigned invalid = 0;
    unsigned repeated = 0;
    for (int h=0; h<pattern_image.rows; h++)
    {

        register const cv::Vec2f * curr_pattern_row = pattern_image.ptr<cv::Vec2f>(h);
        register const cv::Vec2b * min_max_row = min_max_image.ptr<cv::Vec2b>(h);
        for (register int w=0; w<pattern_image.cols; w++)
        {
            const cv::Vec2f & pattern = curr_pattern_row[w];
            const cv::Vec2b & min_max = min_max_row[w];

            if (sl::INVALID(pattern) 
                || pattern[0]<0.f || pattern[0]>=projector_size.width || pattern[1]<0.f || pattern[1]>=projector_size.height
                || (min_max[1]-min_max[0])<static_cast<int>(threshold))
            {   //skip
                continue;
            }

            //ok
            cv::Point2f proj_point(pattern[0]/scale_factor_x, pattern[1]/scale_factor_y);

            unsigned index = static_cast<unsigned>(proj_point.y)*out_cols + static_cast<unsigned>(proj_point.x);//索引是投影图像上所有的点(uncertain)

            proj_points.insert(index, proj_point);

             //std::cout<<"index:  "<<index<<std::endl;
            cam_points[index].push_back(cv::Point2f(w, h));

            //std::cout<<"cam_point:  "<<cam_points[index]<<std::endl;

            //proj_image.at<cv::Vec3b>(static_cast<unsigned>(proj_point.y), static_cast<unsigned>(proj_point.x)) = color_image.at<cv::Vec3b>(h, w);
        }

    }


    //cv::imwrite("proj_image.png", proj_image);
    


    cv::Mat Rt = calib.R.t();


    QMapIterator<unsigned, cv::Point2f> iter1(proj_points);
    unsigned n = 0;
    while (iter1.hasNext()) 
    {
        n++;



        iter1.next();
        unsigned index = iter1.key();
        const cv::Point2f & proj_point = iter1.value();
        const std::vector<cv::Point2f> & cam_point_list = cam_points.value(index);
        const unsigned count = static_cast<int>(cam_point_list.size());

        if (!count)
        {   //empty list
            continue;
        }

        //center average
        cv::Point2d sum(0.0, 0.0), sum2(0.0, 0.0);
        for (std::vector<cv::Point2f>::const_iterator iter2=cam_point_list.begin(); iter2!=cam_point_list.end(); iter2++)
        {
            sum.x += iter2->x;
            sum.y += iter2->y;
            sum2.x += (iter2->x)*(iter2->x);
            sum2.y += (iter2->y)*(iter2->y);
        }
        cv::Point2d cam(sum.x/count, sum.y/count);//
        cv::Point2d proj(proj_point.x*scale_factor_x, proj_point.y*scale_factor_y);

        //triangulate
        double distance = max_dist;  //quality meassure
        cv::Point3d p;          //reconstructed point
        triangulate_stereo(calib.cam_K, calib.cam_kc, calib.proj_K, calib.proj_kc, Rt, calib.T, cam, proj, p, &distance);

        if (distance < max_dist)
        {   //good point

            //evaluate the plane
            double d = plane_dist+1;
            /*if (remove_background)
            {
                d = cv::Mat(plane.rowRange(0,3).t()*cv::Mat(p) + plane.at<double>(3,0)).at<double>(0,0);
            }*/
            if (d>plane_dist)
            {   //object point, keep
                good++;

                cv::Vec3f & cloud_point = pointcloud.points.at<cv::Vec3f>(proj_point.y, proj_point.x);
                cloud_point[0] = p.x;
                cloud_point[1] = p.y;
                cloud_point[2] = p.z;
                //std::cout << " pointcloud.points= " <<cloud_point << std::endl;

                if (color_image.data)//每個像素點對應的彩色值,存入
                {
                    const cv::Vec3b & vec = color_image.at<cv::Vec3b>(static_cast<unsigned>(cam.y), static_cast<unsigned>(cam.x));
                    cv::Vec3b & cloud_color = pointcloud.colors.at<cv::Vec3b>(proj_point.y, proj_point.x);
                    cloud_color[0] = vec[0];
                    cloud_color[1] = vec[1];
                    cloud_color[2] = vec[2];
                }
            }

        }
        else
        {   //skip
            bad++;
            //std::cout << " d = " << distance << std::endl;
        }
    }   //while



    std::cout << "Reconstructed points [patch center]: " << good << " (" << bad << " skipped, " << invalid << " invalid) " << std::endl
                << " - repeated points: " << repeated << " (ignored) " << std::endl;
}
Ejemplo n.º 26
0
Archivo: sum_to_n.c Proyecto: ajdan4q/c
int sum2 (int n)
{
	if (n < 1)
		return 0;
	return n + sum2(n - 1); /* non tail-recurisve, may be call stack overflow */
}
Ejemplo n.º 27
0
int
main (int argc, char **argv)
{
	int 	nt,nzt,nxt,nz,nxo,nxs,ns,nx,nr,is,ixo,ixs;
	int 	ls,jtr,mtr,tracl,mzmax;
	off_t nseek;
	float   ft,fzt,fxt,fz,fx,fxo,fs,fxs,dt,dzt,dxt,dz,dx,dxo,ds,dxs,
		ext,ezt,es,ex,ez,xo,s,xs,xg,fpeak;	
	float 	v0,dvz;
	float 	fmax,angmax,offmax,rmax,aperx;
	float **mig,**migi,***ttab,**tb,**pb,**cosb,**sigb,**tsum,**tt;
	
	char *infile="stdin",*outfile="stdout",*ttfile,*jpfile;
	FILE *infp,*outfp,*ttfp,*jpfp;
	Wavelet *w;


	/* hook up getpar to handle the parameters */
	initargs(argc, argv);
	requestdoc(1);

	/* open input and output files	*/
	if( !getparstring("infile",&infile)) {
		infp = stdin;
	} else  
		if ((infp=fopen(infile,"r"))==NULL)
			err("cannot open infile=%s\n",infile);
	if( !getparstring("outfile",&outfile)) {
		outfp = stdout;
	} else { 
		outfp = fopen(outfile,"w");
	}
	efseeko(infp,(off_t) 0,SEEK_CUR);
	warn("Got A");
	efseeko(outfp,(off_t) 0,SEEK_CUR);
	if( !getparstring("ttfile",&ttfile))
		err("must specify ttfile!\n");
	if ((ttfp=fopen(ttfile,"r"))==NULL)
		err("cannot open ttfile=%s\n",ttfile);
	if( !getparstring("jpfile",&jpfile)) {
		jpfp = stderr;
	} else  
		jpfp = fopen(jpfile,"w");

	/* get information for seismogram traces */
	if (!getparint("nt",&nt)) nt = 501;
	if (!getparfloat("dt",&dt)) dt = 0.004;
	if (!getparfloat("ft",&ft)) ft = 0.0;
	if (!getparfloat("fmax",&fmax)) fmax = 1.0/(4*dt);
	fpeak = 0.2/dt;
	if (!getparint("nxs",&nxs)) nxs = 101;
	if (!getparfloat("dxs",&dxs)) dxs = 15;
	if (!getparfloat("fxs",&fxs)) fxs = 0.0;
	if (!getparint("nxo",&nxo)) nxo = 1;
	if (!getparfloat("dxo",&dxo)) dxo = 50;
	if (!getparfloat("fxo",&fxo)) fxo = 0.0;
	
	/* get traveltime table parameters	*/
	if (!getparint("nxt",&nxt)) err("must specify nxt!\n");
	if (!getparfloat("fxt",&fxt)) err("must specify fxt!\n");
	if (!getparfloat("dxt",&dxt)) err("must specify dxt!\n");
	if (!getparint("nzt",&nzt)) err("must specify nzt!\n");
	if (!getparfloat("fzt",&fzt)) err("must specify fzt!\n");
	if (!getparfloat("dzt",&dzt)) err("must specify dzt!\n");
	if (!getparint("ns",&ns)) err("must specify ns!\n");
	if (!getparfloat("fs",&fs)) err("must specify fs!\n");
	if (!getparfloat("ds",&ds)) err("must specify ds!\n");
	ext = fxt+(nxt-1)*dxt;
	ezt = fzt+(nzt-1)*dzt;
	es = fs+(ns-1)*ds;

	/* check source and receiver coordinates */
 	for (ixs=0; ixs<nxs; ++ixs) {
		xs = fxs+ixs*dxs;
		for (ixo=0; ixo<nxo; ++ixo) {
			xg = xs+fxo+ixo*dxo;
			if (fs>xs || es<xs || fs>xg || es<xg) 
		err("shot or receiver lie outside of specified (x,z) grid\n");
		}
	} 

	/* get migration section parameters	*/
	if (!getparint("nx",&nx)) err("must specify nx!\n");
	if (!getparfloat("fx",&fx)) err("must specify fx!\n");
	if (!getparfloat("dx",&dx)) err("must specify dx!\n");
	if (!getparint("nz",&nz)) err("must specify nz!\n");
	if (!getparfloat("fz",&fz)) err("must specify fz!\n");
	if (!getparfloat("dz",&dz)) err("must specify dz!\n");
	ex = fx+(nx-1)*dx;
	ez = fz+(nz-1)*dz;
	if(fxt>fx || ext<ex || fzt>fz || ezt<ez) 
		err(" migration section is out of traveltime table!\n");

	if (!getparfloat("v0",&v0)) v0 = 1500;
	if (!getparfloat("dvz",&dvz)) dvz = 0;
	if (!getparfloat("angmax",&angmax)) angmax = 60.;
	if  (angmax<0.00001) err("angmax must be positive!\n");
	mzmax = dx*sin(angmax*PI/180.)/dz;
	if(mzmax<1) mzmax = 1;
	if (!getparfloat("aperx",&aperx)) aperx = 0.5*nxt*dxt;

	if (!getparint("ls",&ls))	ls = 1;
	if (!getparint("mtr",&mtr))	mtr = 100;

	fprintf(jpfp,"\n");
	fprintf(jpfp," Modeling parameters\n");
	fprintf(jpfp," ================\n");
	fprintf(jpfp," infile=%s \n",infile);
	fprintf(jpfp," outfile=%s \n",outfile);
	fprintf(jpfp," ttfile=%s \n",ttfile);
	fprintf(jpfp," \n");
	fprintf(jpfp," nzt=%d fzt=%g dzt=%g\n",nzt,fzt,dzt);
	fprintf(jpfp," nxt=%d fxt=%g dxt=%g\n",nxt,fxt,dxt);
 	fprintf(jpfp," ns=%d fs=%g ds=%g\n",ns,fs,ds);
	fprintf(jpfp," \n");
	fprintf(jpfp," nz=%d fz=%g dz=%g\n",nz,fz,dz);
	fprintf(jpfp," nx=%d fx=%g dx=%g\n",nx,fx,dx);
	fprintf(jpfp," \n");
	fprintf(jpfp," nxs=%d fxs=%g dxs=%g\n",nxs,fxs,dxs);
	fprintf(jpfp," nxo=%d fxo=%g dxo=%g\n",nxo,fxo,dxo);
	fprintf(jpfp," \n");
	
	/* compute reference traveltime and slowness  */
	offmax = MAX(ABS(fxo),ABS(fxo+(nxo-1)*dxo));
	rmax = MAX(es-fxt,ext-fs);
	rmax = MIN(rmax,0.5*offmax+aperx);
	nr = 2+(int)(rmax/dx);
	tb = ealloc2float(nzt,nr);
	pb = ealloc2float(nzt,nr);
	sigb = ealloc2float(nzt,nr);
	cosb = ealloc2float(nzt,nr);
	timeb(nr,nzt,dx,dzt,fzt,dvz,v0,tb,pb,sigb,cosb);

	fprintf(jpfp," nt=%d ft=%g dt=%g fpeak=%g \n",nt,ft,dt,fpeak);
	fprintf(jpfp," v0=%g dvz=%g \n",v0,dvz);
 	fprintf(jpfp," aperx=%g angmax=%g offmax=%g\n",aperx,angmax,offmax);
 	fprintf(jpfp," mtr=%d ls=%d\n",mtr,ls);
	fprintf(jpfp," ================\n");
	fflush(jpfp);

	/* allocate space */
	mig = ealloc2float(nz,nx);
	migi = ealloc2float(nz+2*mzmax,nx);
	ttab = ealloc3float(nzt,nxt,ns);
	tt = ealloc2float(nzt,nxt);
	tsum = ealloc2float(nzt,nxt);


	/* make wavelet */
	makericker(fpeak,dt,&w);

	/* set constant segy trace header parameters */
	memset((void *) &tr, 0, sizeof(segy));
	tr.trid = 1;
	tr.counit = 1;
	tr.ns = nt;
	tr.dt = 1.0e6*dt;
	tr.delrt = 1.0e3*ft;

	fprintf(jpfp," read traveltime tables \n");
	fflush(jpfp);

	/* compute traveltime residual	*/
	for(is=0; is<ns; ++is){
		nseek = (off_t) nxt*nzt*is;
		efseeko(ttfp,nseek*((off_t) sizeof(float)),SEEK_SET);
		fread(ttab[is][0],sizeof(float),nxt*nzt,ttfp);
		s = fs+is*ds;
		resit(nxt,fxt,dxt,nzt,nr,dx,tb,ttab[is],s);		
	}

	fprintf(jpfp," read migration section \n");
	fflush(jpfp);

	/* read migration section	*/
	fread(mig[0],sizeof(float),nx*nz,infp);

	/* integrate migration section for constructing anti-aliasing 
		filter	*/
	integ(mig,nz,dz,nx,mzmax,migi);
                       
	fprintf(jpfp," start synthesis ... \n");
	fprintf(jpfp," \n");
	fflush(jpfp);
	
	jtr = 0;
	/* loop over shots  */
	for (ixs=0,xs=fxs,tracl=0; ixs<nxs; ++ixs,xs+=dxs) {
		/* loop over offsets */
		for (ixo=0,xo=fxo; ixo<nxo; ++ixo,xo+=dxo) {
	    		float as,res;
	    		int is;
			xg = xs+xo; 
			/* set segy trace header parameters */
			tr.tracl = tr.tracr = ++tracl;
			tr.fldr = 1+ixs;
			tr.tracf = 1+ixo;
			tr.offset = NINT(xo);
			tr.sx = NINT(xs);
			tr.gx = NINT(xg);

	    		as = (xs-fs)/ds;
	    		is = (int)as;
			if(is==ns-1) is=ns-2;
			res = as-is;
			if(res<=0.01) res = 0.0;
			if(res>=0.99) res = 1.0;
			sum2(nxt,nzt,1-res,res,ttab[is],ttab[is+1],tsum);

	    		as = (xg-fs)/ds;
	    		is = (int)as;
			if(is==ns-1) is=ns-2;
			res = as-is;
			if(res<=0.01) res = 0.0;
			if(res>=0.99) res = 1.0;
			sum2(nxt,nzt,1-res,res,ttab[is],ttab[is+1],tt);
			sum2(nxt,nzt,1,1,tt,tsum,tsum);
				fflush(jpfp);

			/* make one trace */
			maketrace(tr.data,nt,ft,dt,xs,xg,mig,migi,aperx,
			  nx,fx,dx,nz,fz,dz,mzmax,ls,angmax,v0,fmax,w,
			  tb,pb,sigb,cosb,nr,tsum,nxt,fxt,dxt,nzt,fzt,dzt);
			
			/* write trace */
			fputtr(outfp,&tr);

	        	jtr++;
	        	if((jtr-1)%mtr ==0 ){
				fprintf(jpfp," generated trace %d\n",jtr);
				fflush(jpfp);
	    		}
		}
	}


	fprintf(jpfp," generated %d traces in total\n",jtr);


	fprintf(jpfp," \n");
	fprintf(jpfp," output done\n");
	fflush(jpfp);

	efclose(jpfp);
	efclose(outfp);

	    
	free2float(tsum);
	free2float(tt);
	free2float(pb);
	free2float(tb);
	free2float(cosb);
	free2float(sigb);
	free3float(ttab);
	free2float(mig);
	free2float(migi);

	return(CWP_Exit());
}