Beispiel #1
0
// Apply the even-odd preconditioned clover-improved Dirac operator
void DiracCloverPC::M(cudaColorSpinorField &out, const cudaColorSpinorField &in) const
{
  double kappa2 = -kappa*kappa;

  // FIXME: For asymmetric, a "DslashCxpay" kernel would improve performance.
  bool reset = newTmp(&tmp1, in);

  if (matpcType == QUDA_MATPC_EVEN_EVEN_ASYMMETRIC) {
    Dslash(*tmp1, in, QUDA_ODD_PARITY);
    Clover(out, in, QUDA_EVEN_PARITY);
#ifdef MULTI_GPU // not safe to alias because of partial updates
    cudaColorSpinorField tmp3(in);
#else // safe since out is not read after writing
    cudaColorSpinorField &tmp3 = out; 
#endif
    DiracWilson::DslashXpay(out, *tmp1, QUDA_EVEN_PARITY, tmp3, kappa2); 
  } else if (matpcType == QUDA_MATPC_ODD_ODD_ASYMMETRIC) {
    Dslash(*tmp1, in, QUDA_EVEN_PARITY);
    Clover(out, in, QUDA_ODD_PARITY);
#ifdef MULTI_GPU // not safe to alias because of partial updates
    cudaColorSpinorField tmp3(in);
#else // safe since out is not read after writing
    cudaColorSpinorField &tmp3 = out; 
#endif
    DiracWilson::DslashXpay(out, *tmp1, QUDA_ODD_PARITY, tmp3, kappa2);
  } else if (!dagger) { // symmetric preconditioning
    if (matpcType == QUDA_MATPC_EVEN_EVEN) {
      Dslash(*tmp1, in, QUDA_ODD_PARITY);
      DslashXpay(out, *tmp1, QUDA_EVEN_PARITY, in, kappa2); 
    } else if (matpcType == QUDA_MATPC_ODD_ODD) {
      Dslash(*tmp1, in, QUDA_EVEN_PARITY);
      DslashXpay(out, *tmp1, QUDA_ODD_PARITY, in, kappa2); 
    } else {
      errorQuda("Invalid matpcType");
    }
  } else { // symmetric preconditioning, dagger
    if (matpcType == QUDA_MATPC_EVEN_EVEN) {
      CloverInv(out, in, QUDA_EVEN_PARITY); 
      Dslash(*tmp1, out, QUDA_ODD_PARITY);
      DiracWilson::DslashXpay(out, *tmp1, QUDA_EVEN_PARITY, in, kappa2); 
    } else if (matpcType == QUDA_MATPC_ODD_ODD) {
      CloverInv(out, in, QUDA_ODD_PARITY); 
      Dslash(*tmp1, out, QUDA_EVEN_PARITY);
      DiracWilson::DslashXpay(out, *tmp1, QUDA_ODD_PARITY, in, kappa2); 
    } else {
      errorQuda("MatPCType %d not valid for DiracCloverPC", matpcType);
    }
  }
  
  deleteTmp(&tmp1, reset);
}
Beispiel #2
0
BoundingBox GlNode::getBoundingBox(GlGraphInputData* data) {
  node n=node(id);

  if(data->getElementRotation()->getNodeValue(n)==0) {
    BoundingBox box;
    box.expand(data->getElementLayout()->getNodeValue(n)-data->getElementSize()->getNodeValue(n)/2.f);
    box.expand(data->getElementLayout()->getNodeValue(n)+data->getElementSize()->getNodeValue(n)/2.f);
    assert(box.isValid());
    return box;
  }
  else {
    float cosAngle=static_cast<float>(cos(data->getElementRotation()->getNodeValue(n)/180.*M_PI));
    float sinAngle=static_cast<float>(sin(data->getElementRotation()->getNodeValue(n)/180.*M_PI));
    Coord tmp1(data->getElementSize()->getNodeValue(n)/2.f);
    Coord tmp2(tmp1[0] ,-tmp1[1], tmp1[2]);
    Coord tmp3(-tmp1[0],-tmp1[1],-tmp1[2]);
    Coord tmp4(-tmp1[0], tmp1[1],-tmp1[2]);
    tmp1=Coord(tmp1[0]*cosAngle-tmp1[1]*sinAngle,tmp1[0]*sinAngle+tmp1[1]*cosAngle,tmp1[2]);
    tmp2=Coord(tmp2[0]*cosAngle-tmp2[1]*sinAngle,tmp2[0]*sinAngle+tmp2[1]*cosAngle,tmp2[2]);
    tmp3=Coord(tmp3[0]*cosAngle-tmp3[1]*sinAngle,tmp3[0]*sinAngle+tmp3[1]*cosAngle,tmp3[2]);
    tmp4=Coord(tmp4[0]*cosAngle-tmp4[1]*sinAngle,tmp4[0]*sinAngle+tmp4[1]*cosAngle,tmp4[2]);
    BoundingBox bb;
    bb.expand(data->getElementLayout()->getNodeValue(n)+tmp1);
    bb.expand(data->getElementLayout()->getNodeValue(n)+tmp2);
    bb.expand(data->getElementLayout()->getNodeValue(n)+tmp3);
    bb.expand(data->getElementLayout()->getNodeValue(n)+tmp4);
    return bb;
  }
}
Beispiel #3
0
vector< vector<double> > Dist::euclid(vector< vector<double> > & dt)
{
    int i, j, k;

    vector< vector<double> > dt0;
    vector<double> miu, sd, tmp;
    double tmp1,tmp2;

    //standardize and transpose
    tmp.resize(dt.size(),0);
    dt0.resize(dt[0].size(), tmp);

    for(i=0; i<dt.size(); i++) {
        meansd(dt[i],tmp1,tmp2);
        miu.push_back(tmp1);
        sd.push_back(tmp2);
        for(j=0; j<dt[i].size(); j++) {
            if(tmp2!=0) dt0[j][i]=(dt[i][j]-tmp1)/tmp2;
            else dt0[j][i]=(dt[i][j]-tmp1);
        }
    }

    vector< vector<double> > ds;
    vector<double> tmp3(dt0.size(),0);
    for(i=0; i<tmp3.size(); i++) ds.push_back(tmp3);

    for(i=0; i<dt0.size(); i++) {
        for(j=i; j<dt0.size(); j++) {
            ds[i][j]=euclid_AB(dt0[i],dt0[j]);
            ds[j][i]=ds[i][j];
        }
    }
    return ds;
}
Beispiel #4
0
void MainWindow::on_pushButton_clicked()
{
    char *SendBuffer=new char[MAX_PATH];
    memset(SendBuffer,0,sizeof(char)*MAX_PATH);

    QString tmp(ReceiveIP);
    QByteArray ba =tmp.toLatin1();
    SendBuffer=ba.data();
    Ret=send(ClientSocket,SendBuffer,(int)strlen(SendBuffer),0);

    if(Ret==SOCKET_ERROR)
    {
        QMessageBox::warning(this,"tzp","send info error!");

    }

    QString tmp2(ui->lineEdit->text());
    QByteArray ba2 =tmp2.toLatin1();
    SendBuffer=ba2.data();


    qDebug()<<SendBuffer;
    Ret=send(ClientSocket,SendBuffer,(int)strlen(SendBuffer),0);

    if(Ret==SOCKET_ERROR)
    {
        QMessageBox::warning(this,"tzp","send info error!");

    }
    QString tmp3("Send information:");
    tmp3.append(SendBuffer);
    ui->textEdit->append(tmp3);
}
int
makeShotPaths_Basler (char *shot, string & shotnum, string & report,
		      string & atoms)
{

  //fisrt argument is the shot number
  int shot_int = atoi (shot);
  char shot_str[4];
  sprintf (shot_str, "%04d", shot_int);
  shotnum = shot_str;

  //creates reportfile path in current directory
  report = "";
  char path[MAXPATHLEN];
  getcwd (path, MAXPATHLEN);
  string tmp3 ("");
  report += path;
  report += "/report";
  report += shot_str;
  report += ".INI";

  //creates fluor file path in the current directory
  atoms = "";
  atoms += path;
  atoms += "/";
  atoms += shot_str;
  atoms += ".fluor";

  return EXIT_SUCCESS;
}
void ProsilicaCapture::run() {
    // main function of the thread
    // read a frame from the Prosilica camera,
    // convert to IplImage and store it to the global pool.

    if( camera != NULL ) {


		//declerations for old code
        //IplImage *cvimg;
        //IplImage *scaled_cvimg, *chn_cvimg;

        do{
            image = (Image*) camera->grabFrame();
            if(image == NULL) {
                readpool->clear();
                continue;
            }
			//this is our original image
			cv::Mat tmp1(cv::Size(image->width(), image->height()),CV_8UC4);
			//copy the data from the frame we just pulled
			tmp1.data = image->data();
			//reshape it to give it 3 channels
			//tmp1.reshape(3);
			cv::Mat tmp2;
			cv::cvtColor(tmp1, tmp2, CV_BGRA2BGR);
			//make a scaled copy of the image
			cv::Mat tmp3(cv::Size(480,360),CV_8UC3);
			cv::resize(tmp2,tmp3,cv::Size(480,360));
			//begin old code
			/*
            cvimg = cvCreateImage( cvSize(image->width(), image->height()), IPL_DEPTH_8U, 4 );
            cvimg->imageData = (char*)image->data();    // share buffers btw/ image and cvimg

            chn_cvimg = cvCreateImage( cvSize(image->width(), image->height()), IPL_DEPTH_8U, 3);
            cvConvertImage(cvimg, chn_cvimg);

            scaled_cvimg = cvCreateImage( cvSize(480, 360), IPL_DEPTH_8U, 3);
            cvResize(chn_cvimg, scaled_cvimg);
			*/
			//end old code
            // put the image to the pool

			/*
                    ID_image *id_image = new ID_image;
                    id_image->image = tmp2;
                    id_image->orig_image = tmp1;
            readpool->storeIDImage(id_image);
			*/
			readpool->storeImage(tmp2);

            //cvReleaseImage(&cvimg);
            //cvReleaseImage(&chn_cvimg);

                    QThread::usleep(1000000 / fps);
        } while (image != NULL && !stopped);

    }
}
Beispiel #7
0
void checkup::checkupfc(vector<vector<Point> > contours_in, std::vector<int> angulo, std::vector<int> *posiciones, vector<vector<Point> > *contours_out )
{

    int n;
    n=angulo.size();
    std::vector<int> tmp2(n,0);
    std::vector<int> tmp3(n,0);
    int tmp1=0;
    tmp1=angulo[0];

//    cout<<endl;
//    cout<<"Angulo original es: ";
//    for(int i=0; i<angulo.size(); i++){
//      // cout<<angulo[i]<<" ";
//    }

    for(int i=0;i<angulo.size();i++){
        if(abs(angulo[i]-tmp1)<=5)
            tmp2[i]=1;
        else
            tmp2[i]=angulo[i];
    }

   // cout<<endl;




 //   cout<<endl;
    for(int i=0;i<angulo.size();i++){
        if(tmp2[i]!=1){
            for(int k=0;k<angulo.size();k++){
                if(abs(angulo[k]-tmp2[i])<=5)
                    tmp3[k]=1;
                else
                    tmp3[k]=tmp2[i];
            }
        }
    }
//    cout<<endl;
//    for(int k=0;k<angulo.size();k++){
//        if(tmp2[k]==1)
//             cout<<"Igual en posicion tmp2: "<<k<<endl;
//    }
//    for(int k=0;k<angulo.size();k++){
//        if(tmp3[k]==1)
//          //   cout<<"Igual en posicion tmp3: "<<k<<endl;
//    }

    // Separar contornos
   // if(tmp)


}
void model_parameters::initialization(void)
{
	NAreaAge.initialize();
 	CatchAreaAge.initialize();
 	CatchNatAge.initialize();
	Nage(1,1) = So*Bo/(1+beta*Bo);
	for(int i=sage+1 ; i <= nage ; i++)
	{
		Nage(1,i) = Nage(1,i-1) * mfexp(-za(i-1));
	}
	VulB(1) = elem_prod(elem_prod(Nage(1),va),wa);
	SB(1) = elem_prod(Nage(1),fa)*wa/2;
	tBo = Nage(1)*wa;
	calcmaxpos(tBo);
	varPos = maxPos*cvPos;
	PosX(1) = minPos + (maxPos - minPos) * (0.5+0.5*sin(indmonth(1)*PI/6 - mo*PI/6)); 
	VBarea(1,sarea) = VulB(1)* (cnorm(areas(sarea)+0.5,PosX(1),varPos));
	for(int r=sarea+1 ; r <= narea-1 ; r++)
	{
		VBarea(1,r) = VulB(1)* (cnorm(areas(r)+0.5,PosX(1),varPos)-cnorm(areas(r)-0.5,PosX(1),varPos));
		NAreaAge(1)(r) = elem_prod(Nage(1)(sage,nage),(cnorm(areas(r)+0.5,PosX(1),varPos)-cnorm(areas(r)-0.5,PosX(1),varPos)));
	}
	//VBarea(1,narea) = VulB(1)* (1.0-cnorm(areas(narea)-0.5,PosX(1),varPos));
	NationVulB(1,1) = sum(VBarea(1)(sarea,sarea+nationareas(1)-1)); 
	NationVulB(1,2) = sum(VBarea(1)(sarea+nationareas(1),narea)); 
	dvar_vector tmp1(sarea,narea);
	dvar_vector tmp2(sarea,narea);
	dvar_vector tmp3(sarea,narea);
	for(int rr= sarea; rr<=narea; rr++)
	{
		tmp1(rr)= VBarea(1)(rr)/ (NationVulB(1)(indnatarea(rr)) + 0.0001);
		tmp2(rr) = tmp1(rr)*TotEffyear(indnatarea(rr))(indyr(1));
		Effarea(1)(rr) = tmp2(rr)*TotEffmonth(indnatarea(rr))(indmonth(1));
	}
	for(int a= sage; a<= nage;a++)
	{
		dvar_vector propVBarea(sarea,narea);
		for(int rr =sarea; rr<=narea; rr++)
		{
			propVBarea(rr) = (cnorm(areas(rr)+0.5,PosX(1),varPos)-cnorm(areas(rr)-0.5,PosX(1),varPos))(a-sage+1);
			CatchAreaAge(1)(rr)(a) = q*Effarea(1)(rr)*va(a)/(q*Effarea(1)(rr)*va(a)+m)*(1-mfexp(-(q*Effarea(1)(rr)*va(a)+m)))*NAreaAge(1)(rr)(a);
			CatchNatAge(1)(indnatarea(rr))(a) += CatchAreaAge(1)(rr)(a);
			EffNatAge(indnatarea(rr))(1)(sage-2) = 1;
			EffNatAge(indnatarea(rr))(1)(sage-1) = indnatarea(rr);
			EffNatAge(indnatarea(rr))(1)(a) += Effarea(1)(rr)*propVBarea(rr);
		}
		//cout<<"propVBarea "<<propVBarea<<endl;
		//cout<<"Effarea(1) "<<Effarea(1)<<endl;
		Effage(1)(a) = Effarea(1)* propVBarea;
	}
}
Beispiel #9
0
//复数类的四则运算
int main()
{
	Fushu a(10);
	Fushu b(20);
	Fushu tmp1(a+b);
	tmp1.Show();
	Fushu tmp2(a-b);
	tmp2.Show();
	Fushu tmp3(a*b);
	tmp3.Show();
	Fushu tmp4(a/b);
	tmp4.Show();
	return 0;
}
int test_rotate90()
{
#ifdef _MSC_VER
	cv::Mat matSrc = cv::imread("E:/GitCode/OpenCV_Test/test_images/1.jpg", 1);
#else	
	cv::Mat matSrc = cv::imread("test_images/1.jpg", 1);
#endif
	if (!matSrc.data) {
		std::cout << "read image fail" << std::endl;
		return -1;
	}

	int width = matSrc.cols;
	int height = matSrc.rows;

	fbc::Mat_<uchar, 3> mat1(height, width, matSrc.data);
	fbc::Mat_<uchar, 3> matTranspose(width, height);
	fbc::transpose(mat1, matTranspose);

	// clockwise rotation  90
	fbc::Mat_<uchar, 3> matRotate90(width, height);
	fbc::flip(matTranspose, matRotate90, 1);
	cv::Mat tmp2(width, height, CV_8UC3, matRotate90.data);
#ifdef _MSC_VER
	cv::imwrite("E:/GitCode/OpenCV_Test/test_images/rotate_90.jpg", tmp2);
#else	
	cv::imwrite("test_images/rotate_90.jpg", tmp2);
#endif

	// clockwise rotation 180
	fbc::Mat_<uchar, 3> matRotate180(height, width);
	fbc::flip(mat1, matRotate180, -1);
	cv::Mat tmp3(height, width, CV_8UC3, matRotate180.data);
#ifdef _MSC_VER
	cv::imwrite("E:/GitCode/OpenCV_Test/test_images/rotate_180.jpg", tmp3);
#else
	cv::imwrite("test_images/rotate_180.jpg", tmp3);
#endif
	// clockwise rotation 270
	fbc::Mat_<uchar, 3> matRotate270(width, height);
	fbc::flip(matTranspose, matRotate270, 0);
	cv::Mat tmp4(matTranspose.rows, matTranspose.cols, CV_8UC3, matRotate270.data);
#ifdef _MSC_VER
	cv::imwrite("E:/GitCode/OpenCV_Test/test_images/rotate_270.jpg", tmp4);
#else
	cv::imwrite("test_images/rotate_270.jpg", tmp4);
#endif
	return 0;
}
Beispiel #11
0
int _tmain(int argc, _TCHAR* argv[])
{
	unordered_set<string> dict;

	string tmp1("hot");
	string tmp2("dot");
	string tmp3("dog");
	string tmp4("lot");
	string tmp5("log");

	dict.insert(tmp1);
	dict.insert(tmp2);
	dict.insert(tmp3);
	dict.insert(tmp4);
	dict.insert(tmp5);

	string start("hit");
	string end("cog");
	Solution instance;
	vector<vector<string> > vvs = instance.findLadders(start, end, dict);

	return 0;
}
Beispiel #12
0
void BlockMatrixTest::testGetSetRowCol()
{
  std::cout << "--> Test: get, set Row and Col." <<std::endl;
  SP::SiconosVector tmp(new SiconosVector(6));
  SP::SiconosVector tmp1(new SiconosVector(6));
  (*tmp1)(0) = 1;
  (*tmp1)(2) = 2;
  SP::SiconosMatrix A(new SimpleMatrix(2, 2));
  SP::SiconosMatrix H(new SimpleMatrix(2, 4));
  SP::SiconosMatrix I(new SimpleMatrix(5, 2));
  SP::SiconosMatrix J(new SimpleMatrix(5, 4));
  std::vector<SP::SiconosMatrix> v(4);
  v[0] = A ;
  v[1] = H ;
  v[2] = I ;
  v[3] = J ;
  SP::SiconosMatrix test(new BlockMatrix(v, 2, 2));

  test->setRow(1, *tmp1);
  test->getRow(1, *tmp);

  CPPUNIT_ASSERT_EQUAL_MESSAGE("testGetSetRowCol : ", *tmp == *tmp1, true);
  CPPUNIT_ASSERT_EQUAL_MESSAGE("testGetSetRowCol : ", (*A)(1, 0) == 1, true);
  CPPUNIT_ASSERT_EQUAL_MESSAGE("testGetSetRowCol : ", (*H)(1, 0) == 2, true);

  SP::SiconosVector tmp2(new SiconosVector(7));
  SP::SiconosVector tmp3(new SiconosVector(7));
  (*tmp3)(0) = 1;
  (*tmp3)(2) = 2;
  test->setCol(1, *tmp3);
  test->getCol(1, *tmp2);
  CPPUNIT_ASSERT_EQUAL_MESSAGE("testGetSetRowCol : ", *tmp2 == *tmp3, true);
  CPPUNIT_ASSERT_EQUAL_MESSAGE("testGetSetRowCol : ", (*A)(0, 1) == 1, true);
  CPPUNIT_ASSERT_EQUAL_MESSAGE("testGetSetRowCol : ", (*I)(0, 1) == 2, true);

  std::cout << "--> get, set Row and Col tests ended with success." <<std::endl;
}
Beispiel #13
0
void RelaxOneHamIntMul(MessRelaxInpPar &RelaxPar,
                    double H,double Qs,double Eta,double Is,double Wid,
                    double *x,double *y)
 {
  CMatrCl Rot3Rgt(4),Rot1Lft(2),Ham(8),Ham3(4),Ham1(2),tmp3(4),tmp1(2);
  Rot1Lft=Rot1Lft*0+1;Rot3Rgt=Rot3Rgt*0+1;
  my_comp *res=NULL;
  double Tstp;  
  Wid=Wid/2;
  int Nit;
//MaxNit=0;
  double CurT,CurItT,t0,t1;
  for (int xi=1;xi<=x[0];xi++) y[xi]=0;
  for (int t=1;t<=RelaxPar.NumHam;t++)
   {
    t1=RelaxPar.Times[t];t0=RelaxPar.Times[t-1];
    QsHMat(Ham,RelaxPar.Teta[t],RelaxPar.Phi[t],H, -Qs, Eta, -Is,&Ham3,&Ham1);

//    GenerateIntVar(Ham3,Rot3Rgt,Ham1,Rot1Lft,t0,t1,0.01,res,Tstp,Nit);
    GenerateInt(Ham3,Rot3Rgt,Ham1,Rot1Lft,t0,t1,0.01,res,Tstp,Nit);
    CurT=t0;
    for (xi=1;xi<=x[0];xi++)
     {
      my_comp freq=my_comp(-Wid,x[xi]);
      CurItT=CurT;
      for (int ti=1;ti<=Nit;ti++)
       {
        y[xi]+=my_real(res[ti]*exp(freq*CurItT))*Tstp;
        CurItT+=Tstp;
       }
      }
     }
  delete []res;
//cout<<MaxNit<<"\n";
//cout<<Ham3<<Ham1<<"\n";
 };
Beispiel #14
0
cv::Scalar SSIM::computeSSIM(const cv::Mat& img1, const cv::Mat& img2)
{

	int ht = img1.rows;
	int wt = img1.cols;
	int w = wt - 10;
	int h = ht - 10;

	cv::Mat mu1(h,w,CV_32F), mu2(h,w,CV_32F);
	cv::Mat mu1_sq(h,w,CV_32F), mu2_sq(h,w,CV_32F), mu1_mu2(h,w,CV_32F);
	cv::Mat img1_sq(ht,wt,CV_32F), img2_sq(ht,wt,CV_32F), img1_img2(ht,wt,CV_32F);
	cv::Mat sigma1_sq(h,w,CV_32F), sigma2_sq(h,w,CV_32F), sigma12(h,w,CV_32F);
	cv::Mat tmp1(h,w,CV_32F), tmp2(h,w,CV_32F), tmp3(h,w,CV_32F);
	cv::Mat ssim_map(h,w,CV_32F), cs_map(h,w,CV_32F);

	// mu1 = filter2(window, img1, 'valid');
	applyGaussianBlur(img1, mu1, 11, 1.5);

	// mu2 = filter2(window, img2, 'valid');
	applyGaussianBlur(img2, mu2, 11, 1.5);

	// mu1_sq = mu1.*mu1;
	cv::multiply(mu1, mu1, mu1_sq);
	// mu2_sq = mu2.*mu2;
	cv::multiply(mu2, mu2, mu2_sq);
	// mu1_mu2 = mu1.*mu2;
	cv::multiply(mu1, mu2, mu1_mu2);

	cv::multiply(img1, img1, img1_sq);
	cv::multiply(img2, img2, img2_sq);
	cv::multiply(img1, img2, img1_img2);

	// sigma1_sq = filter2(window, img1.*img1, 'valid') - mu1_sq;
	applyGaussianBlur(img1_sq, sigma1_sq, 11, 1.5);
	sigma1_sq -= mu1_sq;

	// sigma2_sq = filter2(window, img2.*img2, 'valid') - mu2_sq;
	applyGaussianBlur(img2_sq, sigma2_sq, 11, 1.5);
	sigma2_sq -= mu2_sq;

	// sigma12 = filter2(window, img1.*img2, 'valid') - mu1_mu2;
	applyGaussianBlur(img1_img2, sigma12, 11, 1.5);
	sigma12 -= mu1_mu2;

	// cs_map = (2*sigma12 + C2)./(sigma1_sq + sigma2_sq + C2);
	tmp1 = 2*sigma12 + C2;
	tmp2 = sigma1_sq + sigma2_sq + C2;
	cv::divide(tmp1, tmp2, cs_map);
	// ssim_map = ((2*mu1_mu2 + C1).*(2*sigma12 + C2))./((mu1_sq + mu2_sq + C1).*(sigma1_sq + sigma2_sq + C2));
	tmp3 = 2*mu1_mu2 + C1;
	cv::multiply(tmp1, tmp3, tmp1);
	tmp3 = mu1_sq + mu2_sq + C1;
	cv::multiply(tmp2, tmp3, tmp2);
	cv::divide(tmp1, tmp2, ssim_map);

	// mssim = mean2(ssim_map);
	double mssim = cv::mean(ssim_map).val[0];
	// mcs = mean2(cs_map);
	double mcs = cv::mean(cs_map).val[0];

	cv::Scalar res(mssim, mcs);

	return res;
}
Beispiel #15
0
/* SRC: classes/exception.php line 152 */
void c_Exception::t_inittrace() {
  INSTANCE_METHOD_INJECTION_BUILTIN(Exception, Exception::initTrace);
  Variant v_top;
  Variant v_frame;

  ObjectData *obj_tmp UNUSED;
  {
    const CallInfo *cit0 = NULL;
    MethodCallPackage mcp0;
    mcp0.staticMethodCall(NAMSTR(s_sys_ssf08d205d, "static"), NAMSTR(s_sys_ssc453e9e9, "getTraceOptions"));
    mcp0.lateStaticBind(fi.getThreadInfo());
    cit0 = mcp0.ci;
    const Array &tmp1((x_debug_backtrace(toBoolean((cit0->getMeth0Args())(mcp0, 0)))));
    m_trace = tmp1;
  }
  LOOP_COUNTER(1);
  {
    while (!(empty(m_trace))) {
      LOOP_COUNTER_CHECK(1);
      {
        {
          const Variant &tmp0((m_trace.rvalAt(0LL, AccessFlags::Error)));
          v_top.assignVal(tmp0);
        }
        {
          bool tmp0;
          {
            bool tmp1 = ((isset(v_top, NAMSTR(s_sys_ssc82dbd12, "class"), true) && isset(v_top, NAMSTR(s_sys_ss52403931, "function"), true)));
            if (tmp1) {
              const String &tmp2((toString(v_top.rvalAt(NAMSTR(s_sys_ssc82dbd12, "class"), AccessFlags::Error_Key))));
              int64 tmp3((x_strcasecmp(tmp2, NAMSTR(s_sys_ssae8717ad, "exception"))));
              tmp1 = (same(tmp3, 0LL));
            }
            bool tmp4 = (tmp1);
            if (tmp4) {
              const String &tmp5((toString(v_top.rvalAt(NAMSTR(s_sys_ss52403931, "function"), AccessFlags::Error_Key))));
              int64 tmp6((x_strcasecmp(tmp5, NAMSTR(s_sys_ssa26bedd7, "__init__"))));
              tmp4 = (same(tmp6, 0LL));
            }
            tmp0 = (tmp4);
          }
          if (tmp0) {
            {
              {
                const Variant &tmp0((x_array_shift(ref(m_trace))));
                v_frame.assignVal(tmp0);
              }
              if (isset(v_frame, NAMSTR(s_sys_ss8ce7db5b, "file"), true)) {
                {
                  const Variant &tmp0((v_frame.rvalAt(NAMSTR(s_sys_ss8ce7db5b, "file"), AccessFlags::Error_Key)));
                  m_file.assignVal(tmp0);
                }
              }
              if (isset(v_frame, NAMSTR(s_sys_ssddf8728c, "line"), true)) {
                {
                  const Variant &tmp0((v_frame.rvalAt(NAMSTR(s_sys_ssddf8728c, "line"), AccessFlags::Error_Key)));
                  m_line.assignVal(tmp0);
                }
              }
              return;
            }
          }
        }
        x_array_shift(ref(m_trace));
      }
    }
  }
}
int
makeShotPaths (char *shot, string & shotnum, string & report,
	       string & atoms, string & noatoms, string & atomsref,
	       string & noatomsref, const bool andor2)
{

  //fisrt argument is the shot number
  int shot_int = atoi (shot);
  char shot_str[4];
  sprintf (shot_str, "%04d", shot_int);
  shotnum = shot_str;

  //creates reportfile path in current directory
  report = "";
  char path[MAXPATHLEN];
  getcwd (path, MAXPATHLEN);
  string tmp3 ("");
  report += path;
  report += "/report";
  report += shot_str;
  report += ".INI";

  //creates atoms file path in the current directory
  atoms = "";
  atoms += path;
  atoms += "/";
  atoms += shot_str;
  if (andor2)
    atoms += "atoms_andor2.fits";
  else
    atoms += "atoms.fits";

  //creates noatoms file path in the current directory
  noatoms = "";
  noatoms += path;
  noatoms += "/";
  noatoms += shot_str;
  if (andor2)
    noatoms += "noatoms_andor2.fits";
  else
    noatoms += "noatoms.fits";

  //creates atomsref file path in the current directory
  atomsref = "";
  atomsref += path;
  atomsref += "/";
  atomsref += shot_str;
  if (andor2)
    atomsref += "atomsref_andor2.fits";
  else
    atomsref += "atomsref.fits";

  //creates noatomsref file path in the current directory
  noatomsref = "";
  noatomsref += path;
  noatomsref += "/";
  noatomsref += shot_str;
  if (andor2)
    noatomsref += "noatomsref_andor2.fits";
  else
    noatomsref += "noatomsref.fits";

  return EXIT_SUCCESS;
}
Beispiel #17
0
void
sasio::Files::
write_pdb(const std::string &filename, int &frame)
{
    std::ofstream outfile(filename) ;

    std::string time_and_user_string ;
    time_and_user_string = util::time_and_user();
    std::string temp_remark = "REMARK PDB FILE WRITTEN ";
    temp_remark += time_and_user_string ;
    std::string remark(temp_remark,0,80) ;
    std::cout << remark << std::endl ;

    outfile << remark << std::endl;
    //std::string dum1 ="         1         2         3         4         5         6         7         8";
    //std::string dum2 ="12345678901234567890123456789012345678901234567890123456789012345678901234567890";
    //outfile << dum1 << std::endl;
    //outfile << dum2 << std::endl;

    std::stringstream line ;
    std::stringstream my_stringstream;

    for(int i = 0 ; i < _natoms() ; ++i)
    {
        line.str( std::string() );
        line.clear() ;
        std::string tmp(_atom_record()[i],0,6) ;
        line << std::setfill(' ') << std::setw(6) << tmp ;

        if(_atom_index()[i] > 99999)
        {
            std::string tmp2(std::to_string(99999),0,5) ;
            line << std::setfill(' ') << std::setw(5) << std::right << tmp2 ;
        }
        else if(_atom_index()[i] < -9999)
        {
            std::string tmp2(std::to_string(-9999),0,5) ;
            line << std::setfill(' ') << std::setw(5) << std::right << tmp2 ;
        }
        else
        {
            std::string tmp2(std::to_string(_atom_index()[i]),0,5) ;
            line << std::setfill(' ') << std::setw(5) << std::right << tmp2 ;
        }

        std::string tmp0 = " ";
        line << tmp0 ;

        std::string tmp3(_atom_name()[i],0,4) ;
        line << std::setfill(' ') << std::setw(4) << std::left << tmp3 ;

        std::string tmp4(_atom_altloc()[i],0,1) ;
        line << std::setw(1) << tmp4 ;

        std::string tmp5(_atom_resname()[i],0,3) ;
        line << std::setfill(' ') << std::setw(4) << std::left << tmp5 ;

        std::string tmp6(_atom_chain()[i],0,1) ;
        line << std::setfill(' ') << std::setw(1) << std::left << tmp6 ;

        if(_atom_resid()[i] > 9999)
        {
            std::string tmp7(std::to_string(9999),0,4) ;
            line << std::setfill(' ') << std::setw(4) << std::right << tmp7 ;
        }
        else if(_atom_resid()[i] < -999)
        {
            std::string tmp7(std::to_string(-999),0,4) ;
            line << std::setfill(' ') << std::setw(4) << std::right << tmp7 ;
        }
        else
        {
            std::string tmp7(std::to_string(_atom_resid()[i]),0,4) ;
            line << std::setfill(' ') << std::setw(4) << std::right << tmp7 ;
        }

        std::string tmp8(_atom_icode()[i],0,1) ;
        line << std::setw(4) << std::left << tmp8 ;

        //std::string f_str = std::to_string(f);

        //here
        //
        my_stringstream << _x()(i,frame) ;
        //my_stringstream << std::to_string(_x()(i,frame)) ;
        //line << std::setfill(' ') << std::setw(8) << std::right << my_stringstream.str() ;
        line << std::setfill(' ') << std::setw(8) << std::right << my_stringstream.str() ;

        my_stringstream << _y()(i,frame) ;
        line << my_stringstream.str() ;

        my_stringstream << _z()(i,frame) ;
        line << my_stringstream.str() ;

        std::string tmp12(_atom_occupancy()[i],0,6) ;
        line << std::setfill(' ') << std::setw(6) << std::right << tmp12 ;

        std::string tmp13(_atom_beta()[i],0,6) ;
        line << std::setfill(' ') << std::setw(6) << std::right << tmp13 ;

        std::string tmp14(_atom_segname()[i],0,4) ;
        line << std::setfill(' ') << std::setw(10) << std::right << tmp14 ;

        std::string tmp15(_atom_element()[i],0,2) ;
        line << std::setfill(' ') << std::setw(2) << std::right << tmp15 ;

        std::string tmp16(_atom_charge()[i],0,2) ;
        line << std::setfill(' ') << std::setw(2) << std::right << tmp16 ;

        outfile << line.str() << std::endl ;
    }

    outfile << "END" << std::endl;
    outfile.close() ;
}
Beispiel #18
0
        void FilterEnergyBase::v_Update(
            const Array<OneD, const MultiRegions::ExpListSharedPtr> &pFields,
            const NekDouble &time)
        {
            int i, nPoints = pFields[0]->GetNpoints();

            m_index++;

            if (m_index % m_outputFrequency > 0)
            {
                return;
            }

            // Calculate kinetic energy.
            NekDouble Ek = 0.0;
            Array<OneD, NekDouble> tmp(nPoints, 0.0);
            Array<OneD, Array<OneD, NekDouble> > u(3);
            for (i = 0; i < 3; ++i)
            {
                u[i] = Array<OneD, NekDouble>(nPoints);

                v_GetVelocity(pFields, i, u[i]);

                if (m_homogeneous && pFields[i]->GetWaveSpace())
                {
                    pFields[i]->HomogeneousBwdTrans(u[i], u[i]);
                }

                Vmath::Vvtvp(nPoints, u[i], 1, u[i], 1, tmp, 1, tmp, 1);
            }

            if (!m_constDensity)
            {
                Vmath::Vmul(nPoints, v_GetDensity(pFields), 1, tmp, 1, tmp, 1);
            }

            if (m_homogeneous)
            {
                Array<OneD, NekDouble> tmp2(nPoints, 0.0);
                pFields[0]->HomogeneousFwdTrans(tmp, tmp2);
                Ek = pFields[0]->GetPlane(0)->Integral(tmp2) * 2.0 * M_PI;
            }
            else
            {
                Ek = pFields[0]->Integral(tmp);
            }

            Ek /= 2.0 * m_area;

            if (m_comm->GetRank() == 0)
            {
                m_outFile << setw(17) << setprecision(8) << time
                          << setw(22) << setprecision(11) << Ek;
            }

            bool waveSpace[3] = {
                pFields[0]->GetWaveSpace(),
                pFields[1]->GetWaveSpace(),
                pFields[2]->GetWaveSpace()
            };

            if (m_homogeneous)
            {
                for (i = 0; i < 3; ++i)
                {
                    pFields[i]->SetWaveSpace(false);
                }
            }

            // First calculate vorticity field.
            Array<OneD, NekDouble> tmp2(nPoints), tmp3(nPoints);
            Vmath::Zero(nPoints, tmp, 1);
            for (i = 0; i < 3; ++i)
            {
                int f1 = (i+2) % 3, c2 = f1;
                int c1 = (i+1) % 3, f2 = c1;
                pFields[f1]->PhysDeriv(c1, u[f1], tmp2);
                pFields[f2]->PhysDeriv(c2, u[f2], tmp3);
                Vmath::Vsub (nPoints, tmp2, 1, tmp3, 1, tmp2, 1);
                Vmath::Vvtvp(nPoints, tmp2, 1, tmp2, 1, tmp, 1, tmp, 1);
            }

            if (!m_constDensity)
            {
                Vmath::Vmul(nPoints, v_GetDensity(pFields), 1, tmp, 1, tmp, 1);
            }

            if (m_homogeneous)
            {
                for (i = 0; i < 3; ++i)
                {
                    pFields[i]->SetWaveSpace(waveSpace[i]);
                }
                pFields[0]->HomogeneousFwdTrans(tmp, tmp);
                Ek = pFields[0]->GetPlane(0)->Integral(tmp) * 2 * M_PI;
            }
            else
            {
                Ek = pFields[0]->Integral(tmp);
            }

            Ek /= 2.0*m_area;

            if (m_comm->GetRank() == 0)
            {
                m_outFile << setw(22) << setprecision(11) << Ek << endl;
            }
        }
Beispiel #19
0
///
/// @par Detailed description
/// ...
/// @param [in, out] (param1) ...
/// @return ...
/// @note ...
void
sasio::Files::
read_pdb(const std::string &filename)
{
    std::string line, word ;

    std::string element_string ;

    std::ifstream infile(filename) ;

    int count = 0 ;
    int frame = 0 ;

    //string s(line, index, number_characters) ;

    std::vector<float> vector_x;
    std::vector<float> vector_y;
    std::vector<float> vector_z;

    while(getline(infile,line))
    {
        std::istringstream record(line) ;
        record >> word ;

        std::string temp1(word,0,5) ;

        if(temp1 != "ATOM" && temp1 != "HETAT")
        {
            std::cout << "excluding: " << word << std::endl ;
        }
        else
        {
            std::string tmp(line,0,6) ;
            _atom_record().push_back(tmp) ;

            std::string tmp2(line,6,5) ;
            _atom_index().push_back(stoi(tmp2)) ;

            std::string tmp3(line,12,4) ;
            _atom_name().push_back(tmp3) ;

            std::string tmp4(line,16,1) ;
            _atom_altloc().push_back(tmp4) ;

            std::string tmp5(line,17,3) ;
            _atom_resname().push_back(tmp5) ;

            std::string tmp6(line,21,1) ;
            _atom_chain().push_back(tmp6) ;

            std::string tmp7(line,22,4) ;
            _atom_resid().push_back(stoi(tmp7)) ;

            std::string tmp8(line,26,1) ;
            _atom_icode().push_back(tmp8) ;

            std::string tmp9(line,30,8) ;
            vector_x.push_back(stof(tmp9)) ;

            std::string tmp10(line,38,8) ;
            vector_y.push_back(stof(tmp10)) ;

            std::string tmp11(line,46,8) ;
            vector_z.push_back(stof(tmp11)) ;

            try
            {
                std::string tmp12(line,54,6) ;
                if(util::has_only_spaces(tmp12))
                {
                    _atom_occupancy().push_back("0.00") ;
                }
                else
                {
                    _atom_occupancy().push_back(tmp12) ;
                }
            }
            catch(const std::out_of_range& oor)
            {
                _atom_occupancy().push_back("0.00") ;
                std::cerr<<"Occupancy: Out of range error: "<< oor.what() <<std::endl ;
            }

            try
            {
                std::string tmp13(line,60,6) ;
                if(util::has_only_spaces(tmp13))
                {
                    _atom_beta().push_back("0.00") ;
                }
                else
                {
                    _atom_beta().push_back(tmp13) ;
                }
            }
            catch(const std::out_of_range& oor)
            {
                _atom_beta().push_back("0.00") ;
                std::cerr<<"Beta: Out of range error: "<< oor.what() <<std::endl ;
            }

            try
            {
                std::string tmp14(line,72,4) ;
                if(util::has_only_spaces(tmp14))
                {
                    _atom_segname().push_back("SEGN") ;
                }
                else
                {
                    _atom_segname().push_back(tmp14) ;
                }
            }
            catch(const std::out_of_range& oor)
            {
                _atom_segname().push_back("SEGN") ;
                std::cerr<<"Segname: Out of range error: "<< oor.what() <<std::endl ;
            }

            try
            {
                std::string tmp15(line,76,2) ;
                if(util::has_only_spaces(tmp15))
                {
                    std::cout << "Element not found" << std::endl;
                    element_string = element_from_name(tmp3) ;
                    _atom_element().push_back(element_string) ;
                }
                else
                {
                    _atom_element().push_back(tmp15) ;
                }
            }
            catch(const std::out_of_range& oor)
            {
                element_string = element_from_name(tmp3) ;
                _atom_element().push_back(element_string) ;
                std::cerr<<"Element: Out of range error: "<< oor.what() <<std::endl ;
            }

            try
            {
                std::string tmp16(line,78,2) ;
                if(util::has_only_spaces(tmp16))
                {
                    _atom_charge().push_back(" ") ;
                }
                else
                {
                    _atom_charge().push_back(tmp16) ;
                }
            }
            catch(const std::out_of_range& oor)
            {
                _atom_charge().push_back(" ") ;
                std::cerr<<"Charge: Out of range error: "<< oor.what() <<std::endl ;
            }

            count++ ;
        }
    }

    _natoms() = count ;
    infile.close() ;

    int nf = _number_of_frames() ;

    if(_number_of_frames() == 0)
    {
        _x().setZero(_natoms(), 1);
        _y().setZero(_natoms(), 1);
        _z().setZero(_natoms(), 1);
    }
    else
    {
        resize_array() ;
    }

    for(int i = 0 ; i < _natoms() ; ++i)
    {
        _x()(i,_number_of_frames()) = vector_x[i] ;
        _y()(i,_number_of_frames()) = vector_y[i] ;
        _z()(i,_number_of_frames()) = vector_z[i] ;
    }

    std::vector<std::string> s_element ;
    s_element = util::strip_white_space(_atom_element()) ;
    _atom_selement() = s_element ;

    dynamic_cast<sasmol::SasMol*>(this)->calc_mass() ;
    _atom_com() = dynamic_cast<sasmol::SasMol*>(this)->calc_com(frame) ;

    _number_of_frames() += 1 ;

    _set_unique_attributes();

    /*
              1         2         3         4         5         6         7         8
    012345678901234567890123456789012345678901234567890123456789012345678901234567890
             1         2         3         4         5         6         7         8
    12345678901234567890123456789012345678901234567890123456789012345678901234567890
    0    6    1 2   7
    ATOM      1  N   GLY X   1     -21.525 -67.562  86.759  1.00  0.00      GAG  N
    ATOM      2  HT1 GLY X   1     -22.003 -68.460  86.892  1.00  0.00      GAG  H
    ATOM      3  HT2 GLY X   1     -21.905 -66.929  87.525  1.00  0.00      GAG  H

    */
}
returnValue MultiObjectiveAlgorithm::formulateOCP( double *idx, OCP *ocp_, Expression **arg ){

    int run1, run2;
    int paretoGeneration;
    double factor;

    get( PARETO_FRONT_GENERATION, paretoGeneration );
    if( paretoGeneration == PFG_UNKNOWN ) paretoGeneration = PFG_WEIGHTED_SUM;

    Grid tmp_grid;
    ocp_->getGrid( tmp_grid );
    Objective  tmp(tmp_grid);


    // WEIGTHED SUM:
    // -----------------------------------------------------------------------------

    if( paretoGeneration == PFG_WEIGHTED_SUM ){

        Expression sum(1);

        for( run1 = 0; run1 < m; run1++ ){   // loop over the number of objectives
             factor = idx[run1];             // determines the weight factor
             sum = sum + arg[run1][0]*factor;
        }
        tmp.addMayerTerm(sum);               // add the new objective as a Meyer Term
        ocp_->setObjective(tmp);             // replace (overwrite) the objective in the ocp
        return SUCCESSFUL_RETURN;
    }


    // NORMALIZED NORMAL CONSTRAINT:
    // -----------------------------------------------------------------------------

    if( paretoGeneration == PFG_NORMALIZED_NORMAL_CONSTRAINT ){ 
	// Normalization based on Messac et al 2004

        //tmp.addMayerTerm( *arg[m-1] );			// Select last (i.e., m-th) objective function
        //ocp_->setObjective( tmp );			// replace (overwrite) the objective in the ocp

        Matrix P  = getNormalizedPayOffMatrix();
        Matrix NK = getUtopiaPlaneVectors    ();

        Vector W(m);
        for( run1 = 0; run1 < m; run1++ )
            W(run1) = idx[run1];

        Vector PW = P*W;

        Vector U = getUtopiaVector();
        Vector L = getNormalizationVector();

        Expression *Fnorm;
        Fnorm = new Expression[m];

        for( run2 = 0; run2 < m; run2++ ){

             Fnorm[run2] = ( *arg[run2] - U(run2) ) / L(run2);
        }

        tmp.addMayerTerm( Fnorm[m-1] );
        ocp_->setObjective( tmp );

        for( run1 = 0; run1 < m-1; run1++ ){
            Expression sum(1);
            for( run2 = 0; run2 < m; run2++ ){

                sum = sum + NK(run2,run1)*( Fnorm[run2] - PW(run2) );
            }
            ocp_->subjectTo( AT_END, sum <= 0.0 );
        }
        delete[] Fnorm;

        return SUCCESSFUL_RETURN;
    }


    // ENHANCED NORMALIZED NORMAL CONSTRAINT:
    // -----------------------------------------------------------------------------

    if( paretoGeneration == PFG_ENHANCED_NORMALIZED_NORMAL_CONSTRAINT ){
	// Normalization based on Sanchis et al 2008

        Matrix P  = getPayOffMatrix();
        Matrix PHI_N(m,m);

        int run3, run4;
        for( run3 = 0; run3 < m; run3++ ){
            for( run4 = 0; run4 < m; run4++ ){
                PHI_N(run3,run4) = 1.0;
            }
        }
        for( run3 = 0; run3 < m; run3++ )
            PHI_N(run3,run3) = 0.0;

        Matrix T;
        T = PHI_N*P.getInverse();

        Matrix NK(m,m-1);
        NK.setZero();

        for( run3 = 0; run3 < m-1; run3++ )
             NK(run3,run3) = 1.0;

        for( run3 = 0; run3 < m-1; run3++ )
             NK(m-1,run3) = -1.0;


        Vector W(m);
        for( run1 = 0; run1 < m; run1++ )
            W(run1) = idx[run1];

        Vector PW = PHI_N*W;

        Vector U = getUtopiaVector();

        Expression *Fnorm;
        Fnorm = new Expression[m];

        for( run2 = 0; run2 < m; run2++ ){
            Expression tmp3(1);
            for( run3 = 0; run3 < m; run3++ ){
                tmp3 = tmp3 + T(run2,run3)*( *arg[run3]- U(run3) );
            }
            Fnorm[run2] = tmp3;
        }

        tmp.addMayerTerm( Fnorm[m-1] );
        ocp_->setObjective( tmp );

        for( run1 = 0; run1 < m-1; run1++ ){

            Expression sum(1);

            for( run2 = 0; run2 < m; run2++ ){

                sum =  sum + NK(run2,run1)*( Fnorm[run2] - PW(run2) );
            }
            ocp_->subjectTo( AT_END, sum <= 0.0 );
        }
        delete[] Fnorm;

        return SUCCESSFUL_RETURN;
    }


    // NORMAL BOUNDARY INTERSECTION:
    // -----------------------------------------------------------------------------

    if( paretoGeneration == PFG_NORMAL_BOUNDARY_INTERSECTION ){

        Vector W(m);
        for( run1 = 0; run1 < m; run1++ )
            W(run1) = idx[run1];

        Matrix P  = getPayOffMatrix();
        Vector U  = getUtopiaVector();
        Vector V  = P*W + U;
        W.setAll( 1.0 );
        Vector X  = P*W;

        Expression lambda;

        lambda = ( *arg[m-1] - V(m-1) )/ X(m-1);

        tmp.addMayerTerm( *arg[m-1] );
        ocp_->setObjective( tmp );

        for( run1 = 0; run1 < m-1; run1++ )
             ocp->subjectTo( AT_END, *arg[run1] - lambda*X(run1) == V(run1) );

        return SUCCESSFUL_RETURN;
    }
    return SUCCESSFUL_RETURN;
}
Beispiel #21
0
gaussian_model EMclustering::maximization(MatrixXf x, MatrixXf r)
{
	int d = x.rows();
	int n = x.cols();
	int k = r.cols();
	//cerr<<x<<endl;
	VectorXf nk(r.rows());
	nk = r.colwise().sum();
	VectorXf w(nk.size());
	w = nk/n;
	MatrixXf tmp1(x.rows(),r.cols());
	tmp1 = x * r;
	VectorXf tmp2(nk.size());
	tmp2 = nk.array().inverse();
	//cerr<<tmp2<<endl<<endl;
	MatrixXf mu(x.rows(),r.cols());
	mu = tmp1 * tmp2.asDiagonal() ;
	MatrixXf *sigma = new MatrixXf[k];
	for(int i=0;i<k;i++)
		sigma[i].setZero(d,d);
	MatrixXf sqrtr(r.rows(),r.cols());
	sqrtr = r.cwiseSqrt();
	MatrixXf xo(d,n);
	MatrixXf tmp3(d,d);
	tmp3.setIdentity(d,d);
	
	for(int i=0;i<k;i++)
	{
		xo = x.colwise() - mu.col(i);
		VectorXf tmp4(sqrtr.rows());
		tmp4 = sqrtr.col(i);
		tmp4 = tmp4.adjoint();
		xo = xo* tmp4.asDiagonal();
		sigma[i] = xo*xo.adjoint()/nk(i);
		sigma[i] = sigma[i] + tmp3*1e-6; 
		//cerr<<sigma[i]<<endl<<endl;
	}

	gaussian_model model;
	model.mu = mu;
	model.sigma = new MatrixXf[k];
	for(int i=0;i<k;i++)
		model.sigma[i] = sigma[i];
	
	model.weight = w;
	
	nk.resize(0);
	w.resize(0);
	tmp1.resize(0,0);
	tmp2.resize(0);
	tmp3.resize(0,0);
	mu.resize(0,0);
	for(int i=0;i<k;i++)
		sigma[i].resize(0,0);
	delete [] sigma;
	sqrtr.resize(0,0);
	xo.resize(0,0);
	tmp3.resize(0,0);

	//cerr<<"---"<<endl;
	model.weight = model.weight.adjoint();
	//cerr<<model.weight<<endl<<endl;
	//cerr<<model.mu<<endl<<endl;
	//for(int i=0;i<k;i++)
	//{
	//	cerr<<model.sigma[i]<<endl<<endl;
	//}
	return model;
}
Beispiel #22
0
MatrixXf EMclustering::initialization(MatrixXf x, int k)
{
  srand (1);

	int n = x.cols();
	int d = x.rows();
	//cerr<<n<<"d "<<d<<endl;

	VectorXi idx(k);
	//idx.setRandom(k);
	//cerr<<idx<<endl;
	idx(0) = rand()%n;
	for(int i=1;i<k;i++)
	{
		int random;// = rand()%n;
		//cerr<<random<<endl;
		bool flag2 = true;
		while(flag2)
		{
			random = rand()%n;
			flag2 = false;
			for(int j=0;j<i;j++)
			{
				if(idx(j)==random)
				{	
				
					flag2 = true;
					break;
				}
			}
		}
		idx(i) = random;
	}
	//cerr<<"idx"<<idx<<endl<<endl;

	int tmpsize = idx.size();
	MatrixXf m(d,tmpsize);
	for(int i=0;i<tmpsize;i++)
		m.col(i) = x.col(idx(i));
	//cerr<<m<<endl<<endl;

	VectorXf tmp1(m.cols());
	tmp1 = m.cwiseProduct(m).colwise().sum();
	//cerr<<tmp1<<endl<<endl;
	tmp1 = tmp1.adjoint()/2;
	//cerr<<tmp1<<endl<<endl;
	MatrixXf tmp2(m.adjoint().rows(),x.cols());
	tmp2 = m.adjoint() * x;
	//cerr<<tmp2<<endl<<endl;
	MatrixXf tmp3(tmp2.rows(),tmp2.cols());
	tmp3 = tmp2.colwise() - tmp1;
	//cerr<<tmp3<<endl<<endl;
	double tmp4;
	int tmp5;
	int tmpd = tmp3.cols();
	VectorXi label(tmpd);
	for(int i=0;i<tmpd;i++)
	{
		tmp4 = tmp3.col(i).maxCoeff(&tmp5);
		label(i) = tmp5;
	}
	//cerr<<label<<endl<<endl;

	VectorXi tmp6(label.size());
	VectorXi u = unique(label, tmp6);
	//cerr<<u<<endl<<endl;
	//cerr<<tmp6<<endl<<endl;

	int max = 100;
	int t=0;
	while(k!=u.size()&&t<max)
	{
		t++;
		//cerr<<"-----------"<<endl;
		
		//idx.setRandom(k);
		idx(0) = rand()%n;//cerr<<k<<" "<<u.size()<<" "<<idx(0)<<endl;
		for(int i=1;i<k;i++)
		{
			int random;// = rand()%n;
			bool flag2 = true;
			while(flag2)
			{random = rand()%n;
				flag2 = false;
				for(int j=0;j<i;j++)
				{
					if(idx(j)==random||x.col(idx(j))==x.col(random))
					{
						flag2 = true;
						break;
					}
				}
			}
			idx(i) = random;//cerr<<idx(i)<<" ";
		}//cerr<<endl;
		//cerr<<"idx"<<idx<<endl<<endl;;
		//cerr<<"u"<<u<<endl<<endl;
		for(int i=0;i<tmpsize;i++)
			m.col(i) = x.col(idx(i));
		//cerr<<m<<endl<<endl;

		tmp1 = m.cwiseProduct(m).colwise().sum();
		//cerr<<tmp1<<endl<<endl;
		tmp1 = tmp1.adjoint()/2;
		//cerr<<tmp1<<endl<<endl;
		tmp2 = m.adjoint() * x;
		//cerr<<tmp2<<endl<<endl;
		tmp3 = tmp2.colwise() - tmp1;
		//cerr<<tmp3<<endl<<endl;
		tmpd = tmp3.cols();
		for(int i=0;i<tmpd;i++)
		{
			tmp4 = tmp3.col(i).maxCoeff(&tmp5);
			label(i) = tmp5;
		}
		//cerr<<"label"<<label.size()<<endl<<endl;
		//cerr<<"end"<<endl;
		u = unique(label, tmp6);
		label = tmp6;
		//cerr<<"u"<<u<<endl<<endl;
		//cerr<<tmp6<<endl<<endl;
	}//cerr<<k<<" "<<u.size()<<endl;

	//cerr<<t<<endl;
	//cerr<<u.size()<<endl;

	MatrixXf r(n,k);
	r.setZero(n,k);
	int j=0;
	int tmplabel[k];

	for(int i=0;i<k;i++)
		tmplabel[i] = 0;
	for(int i=0;i<n;i++)
	{
		r(i,label(j)) = 1;
		tmplabel[label(j)] = 1;
		j++;
	}

	//for(int i=0;i<n;i++)
	//{
	//	if(tmplabel[i]==0)
	//	{
	//		r(i,0) = 1;
	//	}
	//}
	j = 0;
	for(int i=0;i<k;i++)
	{
		if(tmplabel[i]==0)
		{
			//cerr<<i<<endl;
			for(int ii=0;ii<n/k;ii++)
			{
				int ttt = rand()%n;
				//for(int jj=0;jj<k;jj++)
				//	r(ttt,jj)=0;
				r(ttt,i) = 1;
			}
			//j ++;//cerr<<j<<endl;
		}
	}

	//cerr<<r.cols()<<endl;


	//cerr<<r<<endl;
	//delete [] tmplabel;

	idx.resize(0);
	m.resize(0,0);
	tmp1.resize(0);
	tmp2.resize(0,0);
	tmp3.resize(0,0);
	tmp6.resize(0);
	u.resize(0);
	label.resize(0);

	return r;
}
Beispiel #23
0
void bidiag_gkl_restart(
    int locked, int l, int n,
    CAX && Ax, CATX && Atx, CD && D, CE && E, CRho && rho, CP && P, CQ && Q, int s_indx, int t_s_indx) {
  // enhancements version from SLEPc
  const double eta = 1.e-10;
  double t_start = 0.0, t_end = 0.0;
  double local_start = 0.0, local_end = 0.0; 
  double t_total3 = 0.0, t_total4 = 0.0, t_total5 = 0.0, t_total6 = 0.0, t_total7 = 0.0;
  
  int rank, nprocs;
  MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
  
  // Step 1
  int recv_len = (int)P.dim0() * nprocs;
  vec_container<double> tmp(Ax.dim0());
  vec_container<double> recv_tmp(recv_len);
  
  auto m_Ax = make_gemv_ax(&Ax);
  auto m_Atx = make_gemv_ax(&Atx);
  
  m_Ax(Q.col(l), tmp, P.dim0() > 1000);

  vec_container<double> send_data(P.dim0(),0);
  for(size_t i = s_indx; i < s_indx + Ax.dim0(); ++i)
    send_data[i] = tmp.get(i-s_indx);
  MPI_Gather(&send_data[0], P.dim0(), MPI_DOUBLE, &recv_tmp[0], P.dim0(), MPI_DOUBLE, 0, MPI_COMM_WORLD);

  P.col(l) = 0;
  // Generate truly P.col(l)
  if(rank == 0) {
    local_union(P, recv_tmp, l, nprocs);
    // Step 2 & also in rank 0
    for (int j = locked; j < l; ++j) {
      P.col(l) += -rho(j) * P.col(j);
    }
  }
  
  MPI_Bcast(&(P.col(0)[0]), P.size(), MPI_DOUBLE, 0, MPI_COMM_WORLD); 
  //MPI_Bcast(&(P.col(l)[0]), P.size(), MPI_DOUBLE, 0, MPI_COMM_WORLD); 
  // Main loop
  vec_container<double> T(n);
  int recv_l = Q.dim0() * nprocs;
  vec_container<double> recv_t(recv_l);
  for (int j = l; j < n; ++j) {
    // Step 3   
    vec_container<double> tmp2(Atx.dim0());
    
    /* for print */
    if(rank == 0)
    	t_start = currenttime();
   
    local_start = currenttime();
    m_Atx(P.col(j), tmp2, Q.dim0() > 1000);
    local_end = currenttime();
    std::cout << "parallel mv time cost is " << (local_end - local_start) / 1.0e6 << std::endl;
     
    vec_container<double> s_data(Q.dim0(), 0); 
    for(size_t i = t_s_indx; i < t_s_indx + Atx.dim0(); ++i)
      s_data[i] = tmp2[i-t_s_indx];
    MPI_Gather(&s_data[0], Q.dim0(), MPI_DOUBLE, &recv_t[0], Q.dim0(), MPI_DOUBLE, 0, MPI_COMM_WORLD);
    local_start = currenttime();
    std::cout << "parallel mv time cost2 is " << (local_start - local_end) / 1.0e6 << std::endl;
    
    //Q.col(j+1) = 0;
    if(rank == 0) {
      // Generate truly Q.col(j+1) 
      local_union(Q, recv_t, j + 1, nprocs);
      local_end = currenttime();
      t_end = currenttime();
      std::cout << "parallel mv time cost3 is " << (local_end - local_start) / 1.0e6 << std::endl;
      std::cout << "time of step 3 is : " << (t_end - t_start) / 1.0e6 << std::endl;
      t_total3 += (t_end - t_start) / 1.0e6;
    }
      
    // Step 4
    for(size_t aa = 0; aa < Q.dim0(); ++aa) // row
      MPI_Bcast(&(Q.row(aa)[0]), j + 2, MPI_DOUBLE, 0, MPI_COMM_WORLD); 
    // MPI_Bcast(&(Q.col(0)[0]), Q.size(), MPI_DOUBLE, 0, MPI_COMM_WORLD); 
    
    if(rank == 0)
      t_end = currenttime();
    auto Qj = mat_cols(Q, 0, j + 1);
    auto Tj = make_vec(&T, j + 1);
    
    //Tj.assign(gemv(Qj.trans(), Q.col(j + 1)), j >= 3);
    parallel_gemv_task(Qj.trans(), Q.col(j+1), Tj);
    
    if(rank == 0) {
      t_start = currenttime();
      t_total4 += (t_start - t_end) / 1.0e6;
      std::cout << "time of step 4 is : " << (t_start - t_end) / 1.0e6 << std::endl;
    }

    // Step 5
    if(rank == 0) {
      double r = Q.col(j + 1).norm2();
      D[j] = vec_unit(P.col(j));
      Q.col(j + 1).scale(1. / D[j]);
      Tj = Tj / D[j];
      r /= D[j];
      Q.col(j + 1).plus_assign(- gemv(Qj, Tj), Q.dim0() > 1000);
      
      t_end = currenttime();
      t_total5 += (t_end - t_start) / 1.0e6;
      std::cout << "time of step 5 is : " << (t_end - t_start) / 1.0e6 << std::endl;

      // Step 6
      double beta = r * r - Tj.square_sum();
      if (beta < eta * r * r) {
        Tj.assign(gemv(Qj.trans(), Q.col(j + 1)), Q.dim0() > 1000);
        r = Q.col(j + 1).square_sum();
        Q.col(j + 1).plus_assign(-gemv(Qj, Tj), Q.dim0() > 1000);
        beta = r * r - Tj.square_sum();
      }
      beta = std::sqrt(beta);
      E[j] = beta;
      Q.col(j + 1).scale(1. / E[j]);
      
      t_start = currenttime();
      t_total6 += (t_start - t_end) / 1.0e6;
      std::cout << "time of step 6 is : " << (t_start - t_end) / 1.0e6 << std::endl;
    } 
    
    // Step 7
    // MPI_Bcast(&(Q.col(j+1)[0]), Q.size(), MPI_DOUBLE, 0, MPI_COMM_WORLD);
    // MPI_Bcast(&(Q.col(0)[0]), Q.size(), MPI_DOUBLE, 0, MPI_COMM_WORLD);
    for(size_t aa = 0; aa < Q.dim0(); ++aa)
      MPI_Bcast(&(Q.col(j+1)[aa]), 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);

    if (j + 1 < n) {
      if(rank == 0) 
        t_start = currenttime();
      vec_container<double> tmp3(Ax.dim0());
      vec_container<double> se_data(P.dim0(), 0);
      
      m_Ax(Q.col(j + 1), tmp3, P.dim0() > 1000);
      
      for(size_t k1 = s_indx; k1 < s_indx + Ax.dim0(); ++k1)
        se_data[k1] = tmp3[k1-s_indx];
      MPI_Gather(&se_data[0], P.dim0(), MPI_DOUBLE, &recv_tmp[0], P.dim0(), MPI_DOUBLE, 0, MPI_COMM_WORLD);
      
      // P.col(j+1) = 0;
      if(rank == 0) {
	local_union(P, recv_tmp, j + 1, nprocs);
	P.col(j + 1).plus_assign(- E[j] * P.col(j), P.dim0() > 1000);
      }
      
      /* for print */
      if(rank == 0) {
        t_end = currenttime();
        t_total7 += (t_end - t_start) / 1.0e6;
	std::cout << "time of step 7 is : " << (t_end - t_start) / 1.0e6 << std::endl;
      }

      // MPI_Bcast(&(P.col(l)[0]), P.size(), MPI_DOUBLE, 0, MPI_COMM_WORLD);
      // MPI_Bcast(&(P.col(0)[0]), P.size(), MPI_DOUBLE, 0, MPI_COMM_WORLD);
      for(size_t aa = 0; aa < P.dim0(); ++aa)
        MPI_Bcast(&(P.col(j+1)[aa]), 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);

    }  // end if
  }    // end while
  
  /* for print time of each step. */
  if(rank == 0) {
    std::cout << "total step 3 time is : " << t_total3 << std::endl; 
    std::cout << "total step 4 time is : " << t_total4 << std::endl; 
    std::cout << "total step 5 time is : " << t_total5 << std::endl; 
    std::cout << "total step 6 time is : " << t_total6 << std::endl; 
    std::cout << "total step 7 time is : " << t_total7 << std::endl; 
  }
  
  return ;
}
bool CellPointcloud::init()
{
    std::cout << "Initing" << std::endl;
    newCloud0 = false;
    newCloud1 = false;
    newCloud2 = false;
    Eigen::Matrix4f cam0 = Eigen::Matrix4f::Identity();
    cameraPositions.push_back(cam0);
    Eigen::Matrix4f cam1 = Eigen::Matrix4f::Identity();
    // This is the matrix from NUC2 to table
//    cam1 << 0.0078076 ,-0.659096 , 0.752018  ,-1.76514,
//            0.71265 , 0.531222 , 0.458191, -0.757404,
//          -0.701487 , 0.532347 , 0.473851,  0.634337,
//                  0 ,        0     ,    0  ,      1;

    cam1 << -0.0369295,   -0.99916 , 0.0177825,   0.174928,
            -0.592998, 0.00758757 , -0.805168  , 0.016518,
             0.804357, -0.0402794 ,  -0.59278  , 0.945164,
                    0,          0 ,         0   ,       1;
    cameraPositions.push_back(cam1);


    Eigen::Matrix4f cam2 = Eigen::Matrix4f::Identity();
    // This is the matrix from PC to table
//    cam2 << 0.00652725 , 0.488565 ,-0.872509  , 1.71032,
//            -0.705839 , 0.620315 ,  0.34207 ,-0.721961,
//              0.70836 , 0.613619 , 0.348893 , 0.808552,
//                    0  ,       0  ,       0  ,       1;
    cam2 <<   -0.999718 , -0.0224201 ,-0.00776418 ,   0.604796,
              -0.00404688 ,   0.483571  , -0.875296 ,  -0.256756,
                0.0233787 ,  -0.875018  , -0.483525  ,   2.14104,
                        0 ,          0    ,       0     ,      1;

    cameraPositions.push_back(cam2);



    // This is the matrix from NUC1 to table
    Eigen::Matrix4f cam3 = Eigen::Matrix4f::Identity();
//    cam3 <<    0.99921, 0.00555718 , 0.0393607  , 0.019021,
//               0.0316395  ,-0.710612 , -0.702872  ,  0.14354,
//               0.0240642 ,  0.703562 , -0.710226  ,  1.12045,
//                       0  ,        0 ,         0   ,       1;
    cam3 << 0.0139678,  0.998862, 0.0456047, -0.299209,
            0.707306, 0.0223681, -0.706554, -0.578648,
            -0.70677, 0.0421254, -0.706188,   1.80034,
                   0 ,        0,         0,         1;

    cameraPositions.push_back(cam3);

    ros::init(init_argc,init_argv,"cellPointCloud");
    if ( ! ros::master::check() ) {
        return false;
    }

    pcl::PointCloud<pcl::PointXYZRGB>::Ptr tmp1(new pcl::PointCloud<pcl::PointXYZRGB>);
    pcl::PointCloud<pcl::PointXYZRGB>::Ptr tmp2(new pcl::PointCloud<pcl::PointXYZRGB>);
    pcl::PointCloud<pcl::PointXYZRGB>::Ptr tmp3(new pcl::PointCloud<pcl::PointXYZRGB>);
    cloud0 = tmp1;
    cloud1 = tmp2;
    cloud2 = tmp3;

    ros::start();

    ros::NodeHandle n;
    subPointCloud1 = n.subscribe<sensor_msgs::PointCloud2, CellPointcloud>("/NUC1/sd/points", 1, &CellPointcloud::cloudCallback1,this);
    subPointCloud2 = n.subscribe<sensor_msgs::PointCloud2, CellPointcloud>("/NUC2/sd/points", 1, &CellPointcloud::cloudCallback2, this);
    subPointCloud0 = n.subscribe<sensor_msgs::PointCloud2, CellPointcloud>("/PC/sd/points", 1, &CellPointcloud::cloudCallback0, this);
    pubPointCloud = n.advertise<sensor_msgs::PointCloud2>("PointCloudMerged", 500);

    return true;
}