void dgApi dgRayToRayDistance (const dgVector& ray_p0, const dgVector& ray_p1, const dgVector& ray_q0, const dgVector& ray_q1, dgVector& pOut, dgVector& qOut)
{
	dgFloat32 sN;
	dgFloat32 tN;

	dgVector u (ray_p1 - ray_p0);
	dgVector v (ray_q1 - ray_q0);
	dgVector w (ray_p0 - ray_q0);

	dgFloat32 a = u.DotProduct3(u);        
	dgFloat32 b = u.DotProduct3(v);
	dgFloat32 c = v.DotProduct3(v);        
	dgFloat32 d = u.DotProduct3(w);
	dgFloat32 e = v.DotProduct3(w);
	dgFloat32 D = a*c - b*b;   
	dgFloat32 sD = D;			
	dgFloat32 tD = D;			

	// compute the line parameters of the two closest points
	if (D < dgFloat32 (1.0e-8f)) { 
		sN = dgFloat32 (0.0f);        
		sD = dgFloat32 (1.0f);        
		tN = e;
		tD = c;
	} else {                
		// get the closest points on the infinite lines
		sN = (b*e - c*d);
		tN = (a*e - b*d);
		if (sN < dgFloat32 (0.0f)) {       
			// sc < 0 => the s=0 edge is visible
			sN = dgFloat32 (0.0f);
			tN = e;
			tD = c;
		} else if (sN > sD) {  
			// sc > 1 => the s=1 edge is visible
			sN = sD;
			tN = e + b;
			tD = c;
		}
	}


	if (tN < dgFloat32 (0.0f)) {           
		// tc < 0 => the t=0 edge is visible
		tN = dgFloat32 (0.0f);
		// recompute sc for this edge
		if (-d < dgFloat32 (0.0f)) {
			sN = dgFloat32 (0.0f);
		} else if (-d > a) {
			sN = sD;
		} else {
			sN = -d;
			sD = a;
		}
	} else if (tN > tD) {      
		// tc > 1 => the t=1 edge is visible
		tN = tD;
		// recompute sc for this edge
		if ((-d + b) < dgFloat32 (0.0f)) {
			sN = dgFloat32 (0.0f);
		} else if ((-d + b) > a) {
			sN = sD;
		} else {
			sN = (-d + b);
			sD = a;
		}
	}

	// finally do the division to get sc and tc
	dgFloat32 sc = (dgAbs(sN) < dgFloat32(1.0e-8f) ? dgFloat32 (0.0f) : sN / sD);
	dgFloat32 tc = (dgAbs(tN) < dgFloat32(1.0e-8f) ? dgFloat32 (0.0f) : tN / tD);

	dgAssert (u.m_w == dgFloat32 (0.0f));
	dgAssert (v.m_w == dgFloat32 (0.0f));
	pOut = ray_p0 + u.Scale (sc);
	qOut = ray_q0 + v.Scale (tc);
}
Esempio n. 2
0
//get new Ori and Pos arrays for the child after recombination
void AnimalClass::sampleMyPosOri(AnimalClass& father,
                               AnimalClass& mother)
{
    sireId  = father.myId;
    damId   = mother.myId;
	
	chromosome *currentFatherChrom;
	chromosome *currentMotherChrom;
	
	unsigned numChromosomePair = G.get_num_chrom();
    
    //construct paternal chromosome for myId
    ArrayXf tempPos;
    ArrayXi tempOri;
    tempPos.resize(100000);
    tempOri.resize(100000);
    
    for(unsigned i=0;i<numChromosomePair;i++){
        double chrLength = G[i].chr_length;
        unsigned binomialN = chrLength*3 + 1;
        vector<float> rPos;
        binomial_distribution<int> Binom(binomialN,chrLength/binomialN);
        int numCrossover    =   Binom(randGen);
        
        uniform_real_distribution<float> u(0,1);
        for (unsigned k=0; k<numCrossover; k++) {
            rPos.push_back(chrLength*u(randGen));
        }
        rPos.push_back(chrLength);
        sort(rPos.begin(),rPos.end());
        

        unsigned   startPosParent=0;
        unsigned   startPosMe=0;
        
        currentFatherChrom = (u(randGen)<0.5)?&father.GenomePat[i]:&father.GenomeMat[i];

        for(unsigned j=0;j<rPos.size();j++){

            unsigned numCopy=(currentFatherChrom->pos < rPos[j]).count()-startPosParent;
            tempPos.block(startPosMe,0,numCopy,1)=currentFatherChrom->pos.block(startPosParent,0,numCopy,1);
            tempOri.block(startPosMe,0,numCopy,1)=currentFatherChrom->ori.block(startPosParent,0,numCopy,1);
            
            currentFatherChrom= (currentFatherChrom==&father.GenomePat[i])?&father.GenomeMat[i]:&father.GenomePat[i];
            
            startPosParent=(currentFatherChrom->pos < rPos[j]).count();
            startPosMe+=numCopy;
            tempPos(startPosMe)=rPos[j];
            tempOri(startPosMe)=currentFatherChrom->ori(startPosParent-1);
            startPosMe++;
        } //the length of tempPos should be startPosMe now. Tricky here.
        
//        unsigned posLengthMinusOne=startPosMe-1;
//        unsigned nonzero=(tempPos.block(1,0,posLengthMinusOne,1)-tempPos.block(0,0,posLengthMinusOne,1)).count()+1;
//        GenomePat[i].pos.resize(nonzero-1);
//        GenomePat[i].ori.resize(nonzero-1);
       
        unsigned keep=0;
        GenomePat[i].pos.resize(startPosMe);
        GenomePat[i].ori.resize(startPosMe);
        GenomePat[i].pos[0]=tempPos[0];
        GenomePat[i].ori[0]=tempOri[0];

        for(unsigned m=1;m < startPosMe-1; m++){

            if(tempOri[m]!=tempOri[m-1]){
            keep=keep+1;
            GenomePat[i].pos[keep]=tempPos[m];
            GenomePat[i].ori[keep]=tempOri[m];
            }
        }
        
        unsigned PosOriSize=keep+1;
        GenomePat[i].pos.conservativeResize(PosOriSize);
        GenomePat[i].ori.conservativeResize(PosOriSize);

    }
    ///
    ///construct maternal chromosome for myId
    for(unsigned i=0;i<numChromosomePair;i++){
        double chrLength = G[i].chr_length;
        unsigned binomialN = chrLength*3 + 1;
        vector<float> rPos;
        binomial_distribution<int> Binom(binomialN,chrLength/binomialN);
        int numCrossover    =   Binom(randGen);
        
        uniform_real_distribution<float> u(0,1);
        for (unsigned k=0; k<numCrossover; k++) {
            float rPos_Hao=chrLength*u(randGen);
                rPos.push_back(rPos_Hao);
        }

        rPos.push_back(chrLength);
        sort(rPos.begin(),rPos.end());
        
        unsigned   startPosParent=0;
        unsigned   startPosMe=0;
   
        currentMotherChrom = (u(randGen)<0.5)?&mother.GenomePat[i]:&mother.GenomeMat[i];
        
        for(unsigned j=0;j<rPos.size();j++){
            
            unsigned numCopy=(currentMotherChrom->pos < rPos[j]).count()-startPosParent;
            tempPos.block(startPosMe,0,numCopy,1)=currentMotherChrom->pos.block(startPosParent,0,numCopy,1);
            tempOri.block(startPosMe,0,numCopy,1)=currentMotherChrom->ori.block(startPosParent,0,numCopy,1);
            
            currentMotherChrom= (currentMotherChrom==&mother.GenomePat[i])?&mother.GenomeMat[i]:&mother.GenomePat[i];
            
            startPosParent=(currentMotherChrom->pos < rPos[j]).count();
            startPosMe+=numCopy;
            tempPos(startPosMe)=rPos[j];
            tempOri(startPosMe)=currentMotherChrom->ori(startPosParent-1);
            startPosMe++;
            
        }
        
//        unsigned posLengthMinusOne=startPosMe-1;
//        unsigned nonzero=(tempPos.block(1,0,posLengthMinusOne,1)-tempPos.block(0,0,posLengthMinusOne,1)).count()+1;
//        GenomeMat[i].pos.resize(nonzero-1);
//        GenomeMat[i].ori.resize(nonzero-1);

        unsigned keep=0;
        GenomeMat[i].pos.resize(startPosMe);
        GenomeMat[i].ori.resize(startPosMe);
        GenomeMat[i].pos[0]=tempPos[0];
        GenomeMat[i].ori[0]=tempOri[0];
        
        
        for(unsigned m=1;m < startPosMe-1; m++){
            
            if(tempOri[m]!=tempOri[m-1]){
                keep=keep+1;
                GenomeMat[i].pos[keep]=tempPos[m];
                GenomeMat[i].ori[keep]=tempOri[m];
            }
            
        }
        
        unsigned PosOriSize=keep+1;
        GenomeMat[i].pos.conservativeResize(PosOriSize);
        GenomeMat[i].ori.conservativeResize(PosOriSize);

    }
}
Esempio n. 3
0
	void AddressBookSubscription::Request ()
	{
		// must be run in separate thread	
		LogPrint (eLogInfo, "Downloading hosts from ", m_Link, " ETag: ", m_Etag, " Last-Modified: ", m_LastModified);
		bool success = false;	
		i2p::util::http::url u (m_Link);
		i2p::data::IdentHash ident;
		if (m_Book.GetIdentHash (u.host_, ident))
		{
			std::condition_variable newDataReceived;
			std::mutex newDataReceivedMutex;
			auto leaseSet = i2p::client::context.GetSharedLocalDestination ()->FindLeaseSet (ident);
			if (!leaseSet)
			{
				std::unique_lock<std::mutex> l(newDataReceivedMutex);
				i2p::client::context.GetSharedLocalDestination ()->RequestDestination (ident,
					[&newDataReceived, &leaseSet](std::shared_ptr<i2p::data::LeaseSet> ls)
				    {
						leaseSet = ls;
						newDataReceived.notify_all ();
					});
				if (newDataReceived.wait_for (l, std::chrono::seconds (SUBSCRIPTION_REQUEST_TIMEOUT)) == std::cv_status::timeout)
					LogPrint (eLogError, "Subscription LeseseSet request timeout expired");
			}
			if (leaseSet)
			{
				std::stringstream request, response;
				// standard header
				request << "GET " << u.path_ << " HTTP/1.1\r\nHost: " << u.host_
				<< "\r\nAccept: */*\r\n" << "User-Agent: Wget/1.11.4\r\n" << "Connection: close\r\n";
				if (m_Etag.length () > 0) // etag
					request << i2p::util::http::IF_NONE_MATCH << ": \"" << m_Etag << "\"\r\n";
				if (m_LastModified.length () > 0) // if-modfief-since
					request << i2p::util::http::IF_MODIFIED_SINCE << ": " << m_LastModified << "\r\n";
				request << "\r\n"; // end of header
				auto stream = i2p::client::context.GetSharedLocalDestination ()->CreateStream (leaseSet, u.port_);
				stream->Send ((uint8_t *)request.str ().c_str (), request.str ().length ());
				
				uint8_t buf[4096];
				bool end = false;
				while (!end)
				{
					stream->AsyncReceive (boost::asio::buffer (buf, 4096), 
						[&](const boost::system::error_code& ecode, std::size_t bytes_transferred)
						{
							if (bytes_transferred)
								response.write ((char *)buf, bytes_transferred);
							if (ecode == boost::asio::error::timed_out || !stream->IsOpen ())
								end = true;	
							newDataReceived.notify_all ();
						},
						30); // wait for 30 seconds
					std::unique_lock<std::mutex> l(newDataReceivedMutex);
					if (newDataReceived.wait_for (l, std::chrono::seconds (SUBSCRIPTION_REQUEST_TIMEOUT)) == std::cv_status::timeout)
						LogPrint (eLogError, "Subscription timeout expired");
				}
				// process remaining buffer
				while (size_t len = stream->ReadSome (buf, 4096))
					response.write ((char *)buf, len);
				
				// parse response
				std::string version;
				response >> version; // HTTP version
				int status = 0;
				response >> status; // status
				if (status == 200) // OK
				{
					bool isChunked = false;
					std::string header, statusMessage;
					std::getline (response, statusMessage);
					// read until new line meaning end of header
					while (!response.eof () && header != "\r")
					{
						std::getline (response, header);
						auto colon = header.find (':');
						if (colon != std::string::npos)
						{
							std::string field = header.substr (0, colon);
							header.resize (header.length () - 1); // delete \r	
							if (field == i2p::util::http::ETAG)
								m_Etag = header.substr (colon + 1);
							else if (field == i2p::util::http::LAST_MODIFIED)
								m_LastModified = header.substr (colon + 1);
							else if (field == i2p::util::http::TRANSFER_ENCODING)
								isChunked = !header.compare (colon + 1, std::string::npos, "chunked");
						}	
					}
					LogPrint (eLogInfo, m_Link, " ETag: ", m_Etag, " Last-Modified: ", m_LastModified);
					if (!response.eof ())	
					{
						success = true;
						if (!isChunked)
							m_Book.LoadHostsFromStream (response);
						else
						{
							// merge chunks
							std::stringstream merged;
							i2p::util::http::MergeChunkedResponse (response, merged);
							m_Book.LoadHostsFromStream (merged);
						}	
					}	
				}
				else if (status == 304)
				{	
					success = true;
					LogPrint (eLogInfo, "No updates from ", m_Link);
				}	
				else
					LogPrint (eLogWarning, "Adressbook HTTP response ", status);
			}
			else
Esempio n. 4
0
//std::vector <osg::Vec3> LeafGrower::grow_planes(osg::Vec3 origin, double height, int angle, bool maya)
std::vector <osg::Vec3> LeafGrower::grow_planes()
{
    std::vector <osg::Vec3> ret;
    if(!_root)
        return ret;

    //copy to avoid modification
    //BDLSkeletonNode *root = BDLSkeletonNode::copy_tree(_root);
    //BDLSkeletonNode::rectify_skeleton_tree(root, origin, height, angle, maya);
	BDLSkeletonNode *root = _root;

    //set the expected leaf size be 0.35 of the trunk's radius
    float leaf_size_hint = root->_radius * 0.35;

    //store for billboard data
    _all_pos.clear();

    //bfs
    std::queue <BDLSkeletonNode *> Queue;
    Queue.push(root);

    int ball_cnt = 0;
    float outgrow = 1.3f;

    //grow leaves only at tips or small radius nodes
    while(!Queue.empty())
    {
        BDLSkeletonNode *front = Queue.front();
        Queue.pop();

        for(unsigned int i=0; i<front->_children.size(); i++)
            Queue.push(front->_children[i]);

        //skip the root
        if(!front->_prev)
            continue;

        //graph's leafs only
        if(front->_children.size() == 0)
        {
            osg::Vec3 pos(front->_sx, front->_sy, front->_sz);
            osg::Vec3 pre(front->_prev->_sx, front->_prev->_sy, front->_prev->_sz); 
            osg::Vec3 mid = (pos+pre) / 2.0f;
            osg::Vec3 tangent = pos - pre;

            float cloud_width = tangent.length() * 0.50 * outgrow;
            tangent.normalize();

            //consider a plane with tangent as the normal and contains point pos
            //find basis u, v of this plane
            osg::Vec3 u(tangent.y(), -tangent.x(), 0.0);
            osg::Vec3 v = tangent ^ u;

            //consider another plane with u as normal and contains point pos
            //the basis of this plane is chosen as tangent and v
            //div_angle is the angle angle spanned by tangent and the root of the leaf
            double div_angle = (rand()%30-15+70)/180.0*M_PI;

            //number of ball of this node
            int no_leaf = 1;
            for(int i=1; i<=no_leaf; i++)
            {
                double angle = 360.0/no_leaf*i/180.0*M_PI;
                osg::Vec3 div = u*cos(angle) + v*sin(angle);
                div = tangent * cos(div_angle) + div * sin(div_angle);

                //frame: fu, fv, div, at pos
                osg::Vec3 fu(div.y(), -div.x(), 0.0f);
                fu.normalize();
                osg::Vec3 fv = div ^ fu;

                //cloud around this node
                std::vector <osg::Vec3> b_cloud;
                std::vector <float> weights;
                Transformer::sphere_points_transformed(b_cloud, weights, mid, cloud_width, tangent, 10-rand()%20, leaf_size_hint);
                //Transformer::sphere_points_transformed(b_cloud, weights, mid, cloud_width, tangent, -89, leaf_size_hint);

                //from points to leaf vertices
                for(unsigned j=0; j<b_cloud.size(); j++)
                {
                    osg::Vec3 b_p = b_cloud[j];

                    osg::Vec3 normal = b_p - mid;
                    normal.normalize();

                    osg::Vec3 normal2 = b_p - pos;
                    normal2.normalize();

                    //displace
                    float d_ratio = weights[j] > 0.5 ? 0.40 : 1.0f/outgrow;
                    b_p += normal2 * cloud_width * d_ratio * (weights[j]-0.5f);
                    float leaf_s = leaf_size_hint * (1.0-0.8*std::max(0.0f, weights[j]-0.5f));

                    //cloud pt inside segmentation?
                    if(false || _pruner.is_inside_ortho(b_p))
                    {
                        Transformer::points_to_leafs(ret, b_p, normal, leaf_s, true);

                        //for billboard data
                        _all_pos.push_back(b_p);
                    }
                }
            }

            ball_cnt++;
        }
        if(false)
            if(ball_cnt > 5)
                break;
    }
    if(false)
        printf("ball_cnt(%d)\n", ball_cnt);

    //delete copy
    //BDLSkeletonNode::delete_this(root);

    return ret;
}
void FluidSim::solve_viscosity(float dt) {
   int ni = liquid_phi.ni;
   int nj = liquid_phi.nj;
   
   //static obstacles for simplicity - for moving objects, 
   //use a spatially varying 2d array, and modify the linear system appropriately
   float u_obj = 0;
   float v_obj = 0;

   Array2c u_state(ni+1,nj,(const char&)0);
   Array2c v_state(ni,nj+1,(const char&)0);
   const int SOLID = 1;
   const int FLUID = 0;

   printf("Determining states\n");
   //just determine if the face position is inside the wall! That's it.
   for(int j = 0; j < nj; ++j) {
      for(int i = 0; i < ni+1; ++i) {
         if(i - 1 < 0 || i >= ni || (nodal_solid_phi(i,j+1) + nodal_solid_phi(i,j))/2 <= 0)
            u_state(i,j) = SOLID;
         else
            u_state(i,j) = FLUID;
      }
   }


   for(int j = 0; j < nj+1; ++j)  {
      for(int i = 0; i < ni; ++i) {
         if(j - 1 < 0 || j >= nj || (nodal_solid_phi(i+1,j) + nodal_solid_phi(i,j))/2 <= 0)
            v_state(i,j) = SOLID;
         else 
            v_state(i,j) = FLUID;
      }
   }
   
   printf("Building matrix\n");
   int elts = (ni+1)*nj + ni*(nj+1);
   if(vrhs.size() != elts) {
      vrhs.resize(elts);
      velocities.resize(elts);
      vmatrix.resize(elts);
   }
   vmatrix.zero();
   
   float factor = dt/sqr(dx);
   for(int j = 1; j < nj-1; ++j) for(int i = 1; i < ni-1; ++i) {
      if(u_state(i,j) == FLUID ) {
         int index = u_ind(i,j);      
         
         vrhs[index] = u_vol(i,j) * u(i,j);
         vmatrix.set_element(index,index,u_vol(i,j));
         
         //uxx terms
         float visc_right = viscosity(i,j);
         float visc_left = viscosity(i-1,j);
         float vol_right = c_vol(i,j);
         float vol_left = c_vol(i-1,j);

        //u_x_right
         vmatrix.add_to_element(index,index, 2*factor*visc_right*vol_right);
         if(u_state(i+1,j) == FLUID)
            vmatrix.add_to_element(index,u_ind(i+1,j), -2*factor*visc_right*vol_right);
         else if(u_state(i+1,j) == SOLID)
            vrhs[index] -= -2*factor*visc_right*vol_right*u_obj;

         //u_x_left
         vmatrix.add_to_element(index,index, 2*factor*visc_left*vol_left);
         if(u_state(i-1,j) == FLUID)
            vmatrix.add_to_element(index,u_ind(i-1,j), -2*factor*visc_left*vol_left);
         else if(u_state(i-1,j) == SOLID)
            vrhs[index] -= -2*factor*visc_left*vol_left*u_obj;
         
         //uyy terms
         float visc_top = 0.25f*(viscosity(i-1,j+1) + viscosity(i-1,j) + viscosity(i,j+1) + viscosity(i,j));
         float visc_bottom = 0.25f*(viscosity(i-1,j) + viscosity(i-1,j-1) + viscosity(i,j) + viscosity(i,j-1));
         float vol_top = n_vol(i,j+1);
         float vol_bottom = n_vol(i,j);

         //u_y_top
         vmatrix.add_to_element(index,index, +factor*visc_top*vol_top);
         if(u_state(i,j+1) == FLUID)
            vmatrix.add_to_element(index,u_ind(i,j+1), -factor*visc_top*vol_top);
         else if(u_state(i,j+1) == SOLID)
            vrhs[index] -= -u_obj*factor*visc_top*vol_top;
      
         //u_y_bottom
         vmatrix.add_to_element(index,index, +factor*visc_bottom*vol_bottom);
         if(u_state(i,j-1) == FLUID)
            vmatrix.add_to_element(index,u_ind(i,j-1), -factor*visc_bottom*vol_bottom);
         else if(u_state(i,j-1) == SOLID)
            vrhs[index] -= -u_obj*factor*visc_bottom*vol_bottom;
      
         //vxy terms
         //v_x_top
         if(v_state(i,j+1) == FLUID)
            vmatrix.add_to_element(index,v_ind(i,j+1), -factor*visc_top*vol_top);
         else if(v_state(i,j+1) == SOLID)
            vrhs[index] -= -v_obj*factor*visc_top*vol_top;
         
         if(v_state(i-1,j+1) == FLUID)
            vmatrix.add_to_element(index,v_ind(i-1,j+1), factor*visc_top*vol_top);
         else if(v_state(i-1,j+1) == SOLID)
            vrhs[index] -= v_obj*factor*visc_top*vol_top;
     
         //v_x_bottom
         if(v_state(i,j) == FLUID)
            vmatrix.add_to_element(index,v_ind(i,j), +factor*visc_bottom*vol_bottom);
         else if(v_state(i,j) == SOLID)
            vrhs[index] -= v_obj*factor*visc_bottom*vol_bottom;
         
         if(v_state(i-1,j) == FLUID)
            vmatrix.add_to_element(index,v_ind(i-1,j), -factor*visc_bottom*vol_bottom);
         else if(v_state(i-1,j) == SOLID)
            vrhs[index] -= -v_obj*factor*visc_bottom*vol_bottom;
      

      }
   }
   
   for(int j = 1; j < nj; ++j) for(int i = 1; i < ni-1; ++i) {
      if(v_state(i,j) == FLUID) {
         int index = v_ind(i,j);      
         
         vrhs[index] = v_vol(i,j)*v(i,j);
         vmatrix.set_element(index, index, v_vol(i,j));

         //vyy
         float visc_top = viscosity(i,j);
         float visc_bottom = viscosity(i,j-1);
         float vol_top = c_vol(i,j);
         float vol_bottom = c_vol(i,j-1);

         //vy_top
         vmatrix.add_to_element(index,index, +2*factor*visc_top*vol_top);
         if(v_state(i,j+1) == FLUID)
            vmatrix.add_to_element(index,v_ind(i,j+1), -2*factor*visc_top*vol_top);
         else if (v_state(i,j+1) == SOLID)
            vrhs[index] -= -2*factor*visc_top*vol_top*v_obj;
         
         //vy_bottom
         vmatrix.add_to_element(index,index, +2*factor*visc_bottom*vol_bottom);
         if(v_state(i,j-1) == FLUID)
            vmatrix.add_to_element(index,v_ind(i,j-1), -2*factor*visc_bottom*vol_bottom);
         else if(v_state(i,j-1) == SOLID)
            vrhs[index] -= -2*factor*visc_bottom*vol_bottom*v_obj;
         
         //vxx terms
         float visc_right = 0.25f*(viscosity(i,j-1) + viscosity(i+1,j-1) + viscosity(i,j) + viscosity(i+1,j));
         float visc_left = 0.25f*(viscosity(i,j-1) + viscosity(i-1,j-1) + viscosity(i,j) + viscosity(i-1,j));
         float vol_right = n_vol(i+1,j);
         float vol_left = n_vol(i,j);

         //v_x_right
         vmatrix.add_to_element(index,index, +factor*visc_right*vol_right);
         if(v_state(i+1,j) == FLUID)
            vmatrix.add_to_element(index,v_ind(i+1,j), -factor*visc_right*vol_right);
         else if(v_state(i+1,j) == SOLID)
            vrhs[index] -= -v_obj*factor*visc_right*vol_right;
      
         //v_x_left
         vmatrix.add_to_element(index,index, +factor*visc_left*vol_left);
         if(v_state(i-1,j) == FLUID)
            vmatrix.add_to_element(index,v_ind(i-1,j), -factor*visc_left*vol_left);
         else if(v_state(i-1,j) == SOLID)
            vrhs[index] -= -v_obj*factor*visc_left*vol_left;

         //uyx

         //u_y_right
         if(u_state(i+1,j) == FLUID)
            vmatrix.add_to_element(index,u_ind(i+1,j), -factor*visc_right*vol_right);
         else if(u_state(i+1,j) == SOLID)
            vrhs[index] -= -u_obj*factor*visc_right*vol_right;
         
         if(u_state(i+1,j-1) == FLUID)
            vmatrix.add_to_element(index,u_ind(i+1,j-1), factor*visc_right*vol_right);
         else if(u_state(i+1,j-1) == SOLID)
            vrhs[index] -= u_obj*factor*visc_right*vol_right;
      
         //u_y_left
         if(u_state(i,j) == FLUID)
            vmatrix.add_to_element(index,u_ind(i,j), factor*visc_left*vol_left);
         else if(u_state(i,j) == SOLID)
            vrhs[index] -= u_obj*factor*visc_left*vol_left;
          
         if(u_state(i,j-1) == FLUID)
            vmatrix.add_to_element(index,u_ind(i,j-1), -factor*visc_left*vol_left);
         else if(u_state(i,j-1) == SOLID)
            vrhs[index] -= -u_obj*factor*visc_left*vol_left;
      
      }
   }

   
   double res_out;
   int iter_out;
   
   solver.solve(vmatrix, vrhs, velocities, res_out, iter_out);
   
   for(int j = 0; j < nj; ++j)
      for(int i = 0; i < ni+1; ++i)
         if(u_state(i,j) == FLUID)
            u(i,j) = (float)velocities[u_ind(i,j)];
         else if(u_state(i,j) == SOLID) 
            u(i,j) = u_obj;
         

   
   for(int j = 0; j < nj+1; ++j)
      for(int i = 0; i < ni; ++i)
         if(v_state(i,j) == FLUID)
            v(i,j) = (float)velocities[v_ind(i,j)];
         else if(v_state(i,j) == SOLID) 
            v(i,j) = v_obj;
}
Esempio n. 6
0
int main(int argc, char* argv[]) {

  Teuchos::GlobalMPISession mpiSession(&argc, &argv);
  Teuchos::RCP<const Teuchos::Comm<int> > comm
    = Teuchos::DefaultComm<int>::getComm();

  // This little trick lets us print to std::cout only if a (dummy) command-line argument is provided.
  int iprint = argc - 1;
  Teuchos::RCP<std::ostream> outStream;
  Teuchos::oblackholestream bhs; // outputs nothing
  if (iprint > 0 && Teuchos::rank<int>(*comm)==0)
    outStream = Teuchos::rcp(&std::cout, false);
  else
    outStream = Teuchos::rcp(&bhs, false);

  int errorFlag  = 0;

  try {
    /**********************************************************************************************/
    /************************* CONSTRUCT ROL ALGORITHM ********************************************/
    /**********************************************************************************************/
    // Get ROL parameterlist
    std::string filename = "input.xml";
    Teuchos::RCP<Teuchos::ParameterList> parlist = Teuchos::rcp( new Teuchos::ParameterList() );
    Teuchos::updateParametersFromXmlFile( filename, parlist.ptr() );
    // Build ROL algorithm
    parlist->sublist("Status Test").set("Gradient Tolerance",1.e-8);
    parlist->sublist("Status Test").set("Step Tolerance",1.e-14);
    parlist->sublist("Status Test").set("Iteration Limit",100);
    /**********************************************************************************************/
    /************************* CONSTRUCT VECTORS **************************************************/
    /**********************************************************************************************/
    // Build control vectors
    int nx = 256;
    Teuchos::RCP<std::vector<RealT> > x_rcp  = Teuchos::rcp( new std::vector<RealT>(nx+2,0.0) );
    ROL::StdVector<RealT> x(x_rcp);
    Teuchos::RCP<std::vector<RealT> > d_rcp  = Teuchos::rcp( new std::vector<RealT>(nx+2,0.0) );
    ROL::StdVector<RealT> d(d_rcp);
    for ( int i = 0; i < nx+2; i++ ) {
      (*x_rcp)[i] = random<RealT>(comm);
      (*d_rcp)[i] = random<RealT>(comm);
    }
    Teuchos::RCP<ROL::Vector<RealT> > xp = Teuchos::rcp(&x,false);
    // Build state and adjoint vectors
    Teuchos::RCP<std::vector<RealT> > u_rcp  = Teuchos::rcp( new std::vector<RealT>(nx,1.0) );
    ROL::StdVector<RealT> u(u_rcp);
    Teuchos::RCP<std::vector<RealT> > p_rcp  = Teuchos::rcp( new std::vector<RealT>(nx,0.0) );
    ROL::StdVector<RealT> p(p_rcp);
    Teuchos::RCP<ROL::Vector<RealT> > up = Teuchos::rcp(&u,false);
    Teuchos::RCP<ROL::Vector<RealT> > pp = Teuchos::rcp(&p,false);
    /**********************************************************************************************/
    /************************* CONSTRUCT SOL COMPONENTS *******************************************/
    /**********************************************************************************************/
    // Build samplers
//    int dim = 4;
//    int nSamp = 100;
//    std::vector<RealT> tmp(2,0.0); tmp[0] = -1.0; tmp[1] = 1.0;
//    std::vector<std::vector<RealT> > bounds(dim,tmp);
//    Teuchos::RCP<ROL::BatchManager<RealT> > bman
//      = Teuchos::rcp(new ROL::StdTeuchosBatchManager<RealT,int>(comm));
//    Teuchos::RCP<ROL::SampleGenerator<RealT> > sampler
//      = Teuchos::rcp(new ROL::MonteCarloGenerator<RealT>(nSamp,bounds,bman,false,false,100));
    ROL::QuadratureInfo info;
    info.dim = 4;
    info.maxLevel = 7;
    info.rule1D.clear(); info.rule1D.resize(info.dim,ROL::QUAD_CLENSHAWCURTIS);    
    info.growth1D.clear(); info.growth1D.resize(info.dim,ROL::GROWTH_DEFAULT);
    info.normalized = true;
    info.adaptive = false;
    Teuchos::RCP<ROL::BatchManager<RealT> > bman
      = Teuchos::rcp(new ROL::StdTeuchosBatchManager<RealT,int>(comm));
    Teuchos::RCP<ROL::SampleGenerator<RealT> > sampler
      = Teuchos::rcp(new ROL::SparseGridGenerator<RealT>(bman,info));
    // Print samples
    int width = 21;
    std::stringstream name;
    name << "samples_" << sampler->batchID() << ".txt";
    std::ofstream file(name.str().c_str());
    if (file.is_open()) {
      file << std::scientific << std::setprecision(12);
      for (int i = 0; i < sampler->numMySamples(); ++i) {
        std::vector<RealT> pt = sampler->getMyPoint(i);
        RealT wt = sampler->getMyWeight(i);
        for (int j = 0; j < static_cast<int>(pt.size()); ++j) {
          file << std::setw(width) << std::left << pt[j];
        }
        file << std::setw(width) << std::left << wt << std::endl;
      }
      file.close();
    }
    else {
      TEUCHOS_TEST_FOR_EXCEPTION(true, std::invalid_argument,
        ">>> (adapters/trikota/sol/test/test_01): Unable to open file!");
    }

    /**********************************************************************************************/
    /************************* CONSTRUCT OBJECTIVE FUNCTION ***************************************/
    /**********************************************************************************************/
    // Build risk-averse objective function
    RealT alpha = 1.e-3;
    Teuchos::RCP<ROL::Objective_SimOpt<RealT> > pobjSimOpt
      = Teuchos::rcp(new Objective_BurgersControl<RealT>(alpha,nx));
    Teuchos::RCP<ROL::EqualityConstraint_SimOpt<RealT> > pconSimOpt
      = Teuchos::rcp(new EqualityConstraint_BurgersControl<RealT>(nx));
    Teuchos::RCP<ROL::Objective<RealT> > pObj
      = Teuchos::rcp(new ROL::Reduced_Objective_SimOpt<RealT>(pobjSimOpt,pconSimOpt,up,xp,pp));
    Teuchos::RCP<ROL::Objective<RealT> > obj;
    // Test parametrized objective functions
    *outStream << "Check Derivatives of Parametrized Objective Function\n";
    pObj->setParameter(sampler->getMyPoint(0));
    pObj->checkGradient(x,d,true,*outStream);
    pObj->checkHessVec(x,d,true,*outStream);
    /**********************************************************************************************/
    /************************* RISK NEUTRAL *******************************************************/
    /**********************************************************************************************/
    *outStream << "\nSOLVE RISK NEUTRAL OPTIMAL CONTROL PROBLEM WITH TRUST REGION\n";
    // Build CVaR objective function
    Teuchos::ParameterList list;
    list.sublist("SOL").set("Stochastic Optimization Type","Risk Neutral");
    list.sublist("SOL").set("Store Sampled Value and Gradient",true);
    // Build stochastic problem
    ROL::StochasticProblem<RealT> optProb(list,pObj,sampler,xp);
    optProb.checkObjectiveGradient(d,true,*outStream);
    optProb.checkObjectiveHessVec(d,true,*outStream);
    // Run ROL algorithm
    ROL::Algorithm<RealT> algo("Trust Region",*parlist,false);
    clock_t start = clock();
    xp->zero();
    algo.run(optProb,true,*outStream);
    *outStream << "Optimization time: " << (RealT)(clock()-start)/(RealT)CLOCKS_PER_SEC << " seconds.\n";
  }
  catch (std::logic_error err) {
    *outStream << err.what() << "\n";
    errorFlag = -1000;
  }; // end try

  if (errorFlag != 0)
    std::cout << "End Result: TEST FAILED\n";
  else
    std::cout << "End Result: TEST PASSED\n";

  return 0;
}
Esempio n. 7
0
bool QUrl::operator==( const QString& url ) const
{
    QUrl u( url );
    return ( *this == u );
}
Esempio n. 8
0
typename CRBTrilinear<TruthModelType>::convergence_type
CRBTrilinear<TruthModelType>::offline()
{

    int proc_number = this->worldComm().globalRank();

    bool rebuild_database = boption(_name="crb.rebuild-database") ;
    bool orthonormalize_primal = boption(_name="crb.orthonormalize-primal") ;

    boost::timer ti;
    if( this->worldComm().isMasterRank() )
        std::cout << "Offline CRBTrilinear starts, this may take a while until Database is computed..."<<std::endl;
    LOG(INFO) << "[CRBTrilinear::offline] Starting offline for output " << this->M_output_index << "\n";
    LOG(INFO) << "[CRBTrilinear::offline] initialize underlying finite element model\n";
    //M_model->initModel();
    LOG( INFO )<< " -- model init done in " << ti.elapsed() << "s";

    parameter_type mu( this->M_Dmu );

    double delta_pr;
    double delta_du;
    size_type index;
    //if M_N == 0 then there is not an already existing database
    if ( rebuild_database || this->M_N == 0)
    {

        ti.restart();

        LOG(INFO) << "[CRBTrilinear::offline] compute random sampling\n";

        int total_proc = this->worldComm().globalSize();
        std::string sampling_mode = soption("crb.sampling-mode");
        bool all_proc_same_sampling=boption("crb.all-procs-have-same-sampling");
        int sampling_size = ioption("crb.sampling-size");
        std::string file_name = ( boost::format("M_Xi_%1%_"+sampling_mode+"-proc%2%on%3%") % sampling_size %proc_number %total_proc ).str();
        if( all_proc_same_sampling )
            file_name+="-all-proc-have-same-sampling";

        std::ifstream file ( file_name );

        if( ! file )
        {

            // random sampling
            std::string supersamplingname =(boost::format("Dmu-%1%-generated-by-master-proc") %sampling_size ).str();

            if( sampling_mode == "log-random" )
                this->M_Xi->randomize( sampling_size , all_proc_same_sampling , supersamplingname );
            else if( sampling_mode == "log-equidistribute" )
                this->M_Xi->logEquidistribute( sampling_size , all_proc_same_sampling , supersamplingname );
            else if( sampling_mode == "equidistribute" )
                this->M_Xi->equidistribute( sampling_size , all_proc_same_sampling , supersamplingname );
            else
                throw std::logic_error( "[CRBTrilinear::offline] ERROR invalid option crb.sampling-mode, please select between log-random, log-equidistribute or equidistribute" );
            //M_Xi->equidistribute( this->vm()["crb.sampling-size"].template as<int>() );

            this->M_Xi->writeOnFile(file_name);

        }
        else
        {
            this->M_Xi->clear();
            this->M_Xi->readFromFile(file_name);
        }

        this->M_WNmu->setSuperSampling( this->M_Xi );


        LOG( INFO )<<"[CRBTrilinear offline] M_error_type = "<<this->M_error_type<<std::endl;

        LOG(INFO) << " -- sampling init done in " << ti.elapsed() << "s";
        ti.restart();

        // empty sets
        this->M_WNmu->clear();
        if( this->M_error_type == CRB_NO_RESIDUAL )
            mu = this->M_Dmu->element();
        else
        {
            // start with M_C = { arg min mu, mu \in Xi }
            boost::tie( mu, index ) = this->M_Xi->min();
        }


        int size = mu.size();
        //std::cout << " -- WN size :  " << M_WNmu->size() << "\n";

        // dimension of reduced basis space
        this->M_N = 0;

        this->M_maxerror = 1e10;
        delta_pr = 0;
        delta_du = 0;
        //boost::tie( M_maxerror, mu, index ) = maxErrorBounds( N );

        LOG(INFO) << "[CRBTrilinear::offline] allocate reduced basis data structures\n";

        this->M_Aqm_pr.resize( this->M_model->Qa() );
        for(int q=0; q<this->M_model->Qa(); q++)
        {
            this->M_Aqm_pr[q].resize( 1 );
        }

        M_Aqm_tril_pr.resize( this->M_model->QaTri() );

        //for(int q=0; q<this->M_model->QaTri(); q++)
        this->M_Fqm_pr.resize( this->M_model->Ql( 0 ) );

        for(int q=0; q<this->M_model->Ql( 0 ); q++)
        {
            this->M_Fqm_pr[q].resize( 1 );
        }

        this->M_Lqm_pr.resize( this->M_model->Ql( this->M_output_index ) );
        for(int q=0; q<this->M_model->Ql( this->M_output_index ); q++)
            this->M_Lqm_pr[q].resize( 1 );

    }//end of if( rebuild_database )
#if 1
    else
    {
        mu = this->M_current_mu;
        if( proc_number == 0 )
        {
            std::cout<<"we are going to enrich the reduced basis"<<std::endl;
            std::cout<<"there are "<<this->M_N<<" elements in the database"<<std::endl;
        }
        LOG(INFO) <<"we are going to enrich the reduced basis"<<std::endl;
        LOG(INFO) <<"there are "<<this->M_N<<" elements in the database"<<std::endl;
    }//end of else associated to if ( rebuild_databse )
#endif

    LOG(INFO) << "[CRBTrilinear::offline] compute affine decomposition\n";

    std::vector< std::vector<sparse_matrix_ptrtype> > Aqm;
    std::vector< std::vector<sparse_matrix_ptrtype> > Aqm_tril;
    std::vector< std::vector<std::vector<vector_ptrtype> > > Fqm;

    boost::tie( boost::tuples::ignore, Aqm, Fqm ) = this->M_model->computeAffineDecomposition();

    element_ptrtype u( new element_type( this->M_model->functionSpace() ) );

    LOG(INFO) << "[CRBTrilinear::offline] starting offline adaptive loop\n";

    bool reuse_prec = this->vm()["crb.reuse-prec"].template as<bool>() ;

    bool use_predefined_WNmu = this->vm()["crb.use-predefined-WNmu"].template as<bool>() ;
    int N_log_equi = this->vm()["crb.use-logEquidistributed-WNmu"].template as<int>() ;
    int N_equi = this->vm()["crb.use-equidistributed-WNmu"].template as<int>() ;
    int N_random = ioption( "crb.use-random-WNmu" );

    /*    if( N_log_equi > 0 || N_equi > 0 )
     use_predefined_WNmu = true;*/

    // file where the sampling is savec
    std::string file_name = ( boost::format("SamplingWNmu") ).str();
    std::ifstream file ( file_name );

    this->M_WNmu->clear();

    if ( use_predefined_WNmu ) // In this case we want to read the sampling
    {
        if( ! file ) // The user forgot to give the sampling file
            throw std::logic_error( "[CRB::offline] ERROR the file SamplingWNmu doesn't exist so it's impossible to known which parameters you want to use to build the database" );
        else
        {
            int sampling_size = this->M_WNmu->readFromFile(file_name);
            if( Environment::isMasterRank() )
                std::cout<<"[CRB::offline] Read WNmu ( sampling size : "
                         << sampling_size <<" )"<<std::endl;
            LOG( INFO )<<"[CRB::offline] Read WNmu ( sampling size : "
                       << sampling_size <<" )";
        }
    }
    else // We generate the sampling with choosen strategy
    {
        if ( N_log_equi>0 )
        {
            this->M_WNmu->logEquidistribute( N_log_equi , true );
            if( Environment::isMasterRank() )
                std::cout<<"[CRB::offline] Log-Equidistribute WNmu ( sampling size : "
                         <<N_log_equi<<" )"<<std::endl;
            LOG( INFO )<<"[CRB::offline] Log-Equidistribute WNmu ( sampling size : "
                       <<N_log_equi<<" )";
        }
        else if ( N_equi>0 )
        {
            this->M_WNmu->equidistribute( N_equi , true );
            if( Environment::isMasterRank() )
                std::cout<<"[CRB::offline] Equidistribute WNmu ( sampling size : "
                         <<N_equi<<" )"<<std::endl;
            LOG( INFO )<<"[CRB::offline] Equidistribute WNmu ( sampling size : "
                       <<N_equi<<" )";
        }
        else if ( N_random>0 )
        {
            this->M_WNmu->randomize( N_random , true );
            if( Environment::isMasterRank() )
                std::cout<<"[CRB::offline] Randomize WNmu ( sampling size : "
                         <<N_random<<" )"<<std::endl;
            LOG( INFO )<<"[CRB::offline] Randomize WNmu ( sampling size : "
                       <<N_random<<" )";
        }
        else // In this case we don't know what sampling to use
            throw std::logic_error( "[CRB::offline] ERROR : You have to choose an appropriate strategy for the offline sampling : random, equi, logequi or predefined" );

        this->M_WNmu->writeOnFile(file_name);

        /*        if( ! file )
        {
            this->M_WNmu->clear();
            std::vector< parameter_type > V;
            parameter_type __mu;
            __mu = this->M_Dmu->element();
            __mu(0)= 1      ; __mu(1)= 1  ; V.push_back( __mu );
            __mu(0)= 111112 ; __mu(1)= 1  ; V.push_back( __mu );
            __mu(0)= 222223 ; __mu(1)= 1  ; V.push_back( __mu );
            __mu(0)= 333334 ; __mu(1)= 1  ; V.push_back( __mu );
            __mu(0)= 444445 , __mu(1)= 1  ; V.push_back( __mu );
            __mu(0)= 555556 ; __mu(1)= 1  ; V.push_back( __mu );
            __mu(0)= 666667 ; __mu(1)= 1  ; V.push_back( __mu );
            __mu(0)= 777778 ; __mu(1)= 1  ; V.push_back( __mu );
            __mu(0)= 888889 ; __mu(1)= 1  ; V.push_back( __mu );
            __mu(0)= 1e+06  ; __mu(1)= 1  ; V.push_back( __mu );
            __mu(0)= 8123   ; __mu(1)= 1  ; V.push_back( __mu );
            __mu(0)= 9123   ; __mu(1)= 1  ; V.push_back( __mu );
            __mu(0)=1.123e4 ; __mu(1)= 1  ; V.push_back( __mu );
            __mu(0)=2.123e4 ; __mu(1)= 1  ; V.push_back( __mu );
            __mu(0)=4.123e4 ; __mu(1)= 1  ; V.push_back( __mu );
            __mu(0)=912     ; __mu(1)= 1  ; V.push_back( __mu );
            __mu(0)=1.123e3 ; __mu(1)= 1  ; V.push_back( __mu );
            __mu(0)=4.123e3 ; __mu(1)= 1  ; V.push_back( __mu );
         __mu(0)=7.123e4 ; __mu(1)= 1  ; V.push_back( __mu );
            __mu(0)=2123    ; __mu(1)= 1  ; V.push_back( __mu );
            __mu(0)=6.123e3 ; __mu(1)= 1  ; V.push_back( __mu );
            __mu(0)=3.123e3 ; __mu(1)= 1  ; V.push_back( __mu );
            __mu(0)=3.123e4 ; __mu(1)= 1  ; V.push_back( __mu );
            __mu(0)=5.123e4 ; __mu(1)= 1  ; V.push_back( __mu );
            __mu(0)=9.123e4 ; __mu(1)= 1  ; V.push_back( __mu );
            __mu(0)=812     ; __mu(1)= 1  ; V.push_back( __mu );
            __mu(0)=5.111e3 ; __mu(1)= 1  ; V.push_back( __mu );
            __mu(0)=5.124e2 ; __mu(1)= 1  ; V.push_back( __mu );
            this->M_WNmu->setElements( V );
            this->M_iter_max = this->M_WNmu->size();
            this->M_WNmu->writeOnFile(file_name);
         }*/
        use_predefined_WNmu=true;
    } //build sampling

    this->M_iter_max = this->M_WNmu->size();
    mu = this->M_WNmu->at( this->M_N ); // first element


    if( this->M_error_type == CRB_NO_RESIDUAL || use_predefined_WNmu )
    {
        //in this case it makes no sens to check the estimated error
        this->M_maxerror = 1e10;
    }


    LOG(INFO) << "[CRBTrilinear::offline] strategy "<< this->M_error_type <<"\n";

    while ( this->M_maxerror > this->M_tolerance && this->M_N < this->M_iter_max )
    {

        boost::timer timer, timer2;
        LOG(INFO) <<"========================================"<<"\n";
        if( proc_number == this->worldComm().masterRank() )
            std::cout<<"construction of "<<this->M_N<<"/"<<this->M_iter_max<<" basis "<<std::endl;
        LOG(INFO) << "N=" << this->M_N << "/"  << this->M_iter_max << "( nb proc : "<<worldComm().globalSize()<<")";

        // for a given parameter \p mu assemble the left and right hand side
        u->setName( ( boost::format( "fem-primal-N%1%-proc%2%" ) % (this->M_N)  % proc_number ).str() );

        mu.check();
        u->zero();

        timer2.restart();

        LOG(INFO) << "[CRB::offline] solving primal" << "\n";
        *u = this->M_model->solve( mu );

        //if( proc_number == this->worldComm().masterRank() ) std::cout << "  -- primal problem solved in " << timer2.elapsed() << "s\n";
        timer2.restart();


        if( ! use_predefined_WNmu )
            this->M_WNmu->push_back( mu, index );

        this->M_WNmu_complement = this->M_WNmu->complement();

        this->M_model->rBFunctionSpace()->addPrimalBasisElement( *u );
        //WARNING : the dual element is not the real dual solution !
        //no dual problem was solved
        this->M_model->rBFunctionSpace()->addDualBasisElement( *u );

        int number_of_added_elements=1;
        this->M_N+=number_of_added_elements;

        if ( orthonormalize_primal )
        {
            this->orthonormalize( this->M_N, this->M_model->rBFunctionSpace()->primalRB() , number_of_added_elements );
            this->orthonormalize( this->M_N, this->M_model->rBFunctionSpace()->primalRB() , number_of_added_elements );
            this->orthonormalize( this->M_N, this->M_model->rBFunctionSpace()->primalRB() , number_of_added_elements );
        }

        LOG(INFO) << "[CRB::offline] compute Aq_pr, Aq_du, Aq_pr_du" << "\n";
        for  (size_type q = 0; q < this->M_model->Qa(); ++q )
        {
            this->M_Aqm_pr[q][0].conservativeResize( this->M_N, this->M_N );

            // only compute the last line and last column of reduced matrices
            for ( size_type i = this->M_N-number_of_added_elements; i < this->M_N; i++ )
            {
                for ( size_type j = 0; j < this->M_N; ++j )
                {
                    this->M_Aqm_pr[q][0]( i, j ) = Aqm[q][0]->energy( this->M_model->rBFunctionSpace()->primalBasisElement(i) , this->M_model->rBFunctionSpace()->primalBasisElement(j) );
                }
            }

            for ( size_type j=this->M_N-number_of_added_elements; j < this->M_N; j++ )
            {
                for ( size_type i = 0; i < this->M_N; ++i )
                {
                    this->M_Aqm_pr[q][0]( i, j ) = Aqm[q][0]->energy( this->M_model->rBFunctionSpace()->primalBasisElement(i), this->M_model->rBFunctionSpace()->primalBasisElement(j) );
                }
            }
        }//loop over q


        LOG(INFO) << "[CRBTrilinear::offline] compute Fq_pr" << "\n";

        for ( size_type q = 0; q < this->M_model->Ql( 0 ); ++q )
        {
            this->M_Fqm_pr[q][0].conservativeResize( this->M_N );

            for ( size_type l = 1; l <= number_of_added_elements; ++l )
            {
                int index = this->M_N-l;
                this->M_Fqm_pr[q][0]( index ) = this->M_model->Fqm( 0, q, 0, this->M_model->rBFunctionSpace()->primalBasisElement(index) );
            }
        }//loop over q

        LOG(INFO) << "[CRB::offline] compute Lq_pr" << "\n";

        for ( size_type q = 0; q < this->M_model->Ql( this->M_output_index ); ++q )
        {
            this->M_Lqm_pr[q][0].conservativeResize( this->M_N );

            for ( size_type l = 1; l <= number_of_added_elements; ++l )
            {
                int index = this->M_N-l;
                this->M_Lqm_pr[q][0]( index ) = this->M_model->Fqm( this->M_output_index, q, 0, this->M_model->rBFunctionSpace()->primalBasisElement(index) );
            }
        }//loop over q

        sparse_matrix_ptrtype trilinear_form;
        for  (size_type q = 0; q < this->M_model->QaTri(); ++q )
        {
            M_Aqm_tril_pr[q].resize( this->M_N );
            for (int k=0 ; k<this->M_N; k++)
            {
                //bring back the matrix associated to the trilinear form for a given basis function
                //we do this here to use only one matrix
                trilinear_form  = this->M_model->computeTrilinearForm( this->M_model->rBFunctionSpace()->primalBasisElement(k) );

                M_Aqm_tril_pr[q][k].conservativeResize( this->M_N, this->M_N );
                for ( int i = 0; i < this->M_N; ++i )
                {
                    for ( int j = 0; j < this->M_N; ++j )
                    {
                        M_Aqm_tril_pr[q][k]( i, j ) = trilinear_form->energy( this->M_model->rBFunctionSpace()->primalBasisElement(j), this->M_model->rBFunctionSpace()->primalBasisElement(i) );
                    }//j
                }//i
            }//k
        }// q

        timer2.restart();

        if ( ! use_predefined_WNmu )
        {
            bool already_exist;
            do
            {
                //initialization
                already_exist=false;
                //pick randomly an element
                mu = this->M_Dmu->element();
                //make sure that the new mu is not already is M_WNmu
                BOOST_FOREACH( auto _mu, *this->M_WNmu )
                {
                    if( mu == _mu )
                        already_exist=true;
                }
            }
            while( already_exist );
            this->M_current_mu = mu;
        }
        else
        {
            //remmber that in this case M_iter_max = sampling size
            if( this->M_N < this->M_iter_max )
Esempio n. 9
0
    void tsp_vrplc::compute_constraints_impl(constraint_vector &c, const decision_vector& x) const 
    {
        decision_vector::size_type n_cities = get_n_cities();

        switch( get_encoding() ) 
        {
            case FULL:
            {
                // 1 - We set the equality constraints
                for (size_t i = 0; i < n_cities; i++) {
                    c[i] = 0;
                    c[i+n_cities] = 0;
                    for (size_t j = 0; j < n_cities; j++) 
                    {
                        if(i==j) continue; // ignoring main diagonal
                        decision_vector::size_type rows = compute_idx(i, j, n_cities);
                        decision_vector::size_type cols = compute_idx(j, i, n_cities);
                        c[i] += x[rows];
                        c[i+n_cities] += x[cols];
                    }
                    c[i] = c[i]-1;
                    c[i+n_cities] = c[i+n_cities]-1;
                }

                //2 - We set the inequality constraints
                //2.1 - First we compute the uj (see http://en.wikipedia.org/wiki/Travelling_salesman_problem#Integer_linear_programming_formulation)
                //      we start always out tour from the first city, without loosing generality
                size_t next_city = 0,current_city = 0;
                std::vector<int> u(n_cities);
                for (size_t i = 0; i < n_cities; i++) 
                {
                    u[current_city] = i+1;
                    for (size_t j = 0; j < n_cities; j++) 
                    {
                        if (current_city==j) continue;
                        if (x[compute_idx(current_city, j, n_cities)] == 1) 
                        {
                            next_city = j;
                            break;
                        }
                    }
                    current_city = next_city;
                }
                int count=0;
                for (size_t i = 1; i < n_cities; i++) {
                    for (size_t j = 1; j < n_cities; j++) 
                    {
                        if (i==j) continue;
                        c[2*n_cities+count] = u[i]-u[j] + (n_cities+1) * x[compute_idx(i, j, n_cities)] - n_cities;
                        count++;
                    }
                }
                break;
            }
            case RANDOMKEYS:
                break;
            case CITIES:
            {
                std::vector<population::size_type> range(n_cities);
                for (std::vector<population::size_type>::size_type i=0; i<range.size(); ++i) 
                {
                    range[i]=i;
                }
                c[0] = !std::is_permutation(x.begin(),x.end(),range.begin());
                break;
            }
        }
        return;
    }
Esempio n. 10
0
double m1(double t) { return u(0.0, t); }
Esempio n. 11
0
double m2(double t) { return u(1.0, t); }
Esempio n. 12
0
double fi(double x) { return u(x, 0.0) ; }
Esempio n. 13
0
double U(double x) { return u(x, 1.0); }
Esempio n. 14
0
static void tst9() {
    params_ref      ps;
    reslimit        rlim;
    nlsat::solver s(rlim, ps);
    anum_manager & am     = s.am();
    nlsat::pmanager & pm  = s.pm();
    nlsat::assignment as(am);
    nlsat::explain& ex    = s.get_explain();
    int num_lo = 4;
    int num_hi = 5;
    svector<nlsat::var> los, his;
    for (int i = 0; i < num_lo; ++i) {
        los.push_back(s.mk_var(false));
        scoped_anum num(am);
        am.set(num, - i - 1);
        as.set(i, num);
    }
    for (int i = 0; i < num_hi; ++i) {
        his.push_back(s.mk_var(false));
        scoped_anum num(am);
        am.set(num, i + 1);
        as.set(num_lo + i, num);
    }
    nlsat::var _z = s.mk_var(false);
    nlsat::var _x = s.mk_var(false);
    polynomial_ref x(pm), z(pm);
    x = pm.mk_polynomial(_x);
    scoped_anum val(am);
    am.set(val, 0);
    as.set(num_lo + num_hi, val);
    as.set(num_lo + num_hi + 1, val);
    s.set_rvalues(as);
    nlsat::scoped_literal_vector lits(s);

    for (int i = 0; i < num_lo; ++i) {
        polynomial_ref y(pm);
        y = pm.mk_polynomial(los[i]);
        lits.push_back(mk_gt(s, x - y));
    }
    for (int i = 0; i < num_hi; ++i) {
        polynomial_ref y(pm);
        y = pm.mk_polynomial(his[i]);
        lits.push_back(mk_gt(s, y - x));
    }
    z = pm.mk_polynomial(_z);
    lits.push_back(mk_eq(s, x - z));

#define TEST_ON_OFF()                                   \
    std::cout << "Off ";                                \
    ex.set_signed_project(false);                       \
    project(s, ex, _x, lits.size()-1, lits.c_ptr());    \
    std::cout << "On ";                                 \
    ex.set_signed_project(true);                        \
    project(s, ex, _x, lits.size()-1, lits.c_ptr());    \
    std::cout << "Off ";                                \
    ex.set_signed_project(false);                       \
    project(s, ex, _x, lits.size(), lits.c_ptr());      \
    std::cout << "On ";                                 \
    ex.set_signed_project(true);                        \
    project(s, ex, _x, lits.size(), lits.c_ptr())       \

    TEST_ON_OFF();

    lits.reset();
    polynomial_ref u(pm);
    u = pm.mk_polynomial(his[1]);
    for (int i = 0; i < num_lo; ++i) {
        polynomial_ref y(pm);
        y = pm.mk_polynomial(los[i]);
        lits.push_back(mk_gt(s, u*x - y));
    }
    for (int i = 0; i < num_hi; ++i) {
        polynomial_ref y(pm);
        y = pm.mk_polynomial(his[i]);
        lits.push_back(mk_gt(s, y - u*x));
    }
    z = pm.mk_polynomial(_z);
    lits.push_back(mk_eq(s, u*x - z));

    TEST_ON_OFF();

    lits.reset();
    u = pm.mk_polynomial(los[1]);
    for (int i = 0; i < num_lo; ++i) {
        polynomial_ref y(pm);
        y = pm.mk_polynomial(los[i]);
        lits.push_back(mk_gt(s, u*x - y));
    }
    for (int i = 0; i < num_hi; ++i) {
        polynomial_ref y(pm);
        y = pm.mk_polynomial(his[i]);
        lits.push_back(mk_gt(s, y - u*x));
    }
    z = pm.mk_polynomial(_z);
    lits.push_back(mk_eq(s, x - z));

    TEST_ON_OFF();
}
Esempio n. 15
0
/*!

  Compute and return the interaction matrix \f$ L \f$ from
  a subset (\f$ \theta u_x, \theta u_y, \theta u_z\f$) of the possible
  \f$ \theta u \f$ features that represent the 3D rotation
  \f$^{c^*}R_c\f$ or \f$^{c}R_{c^*}\f$, with

  \f[ L = [ 0_3 \; L_{\theta u}] \f] 

  See the vpFeatureThetaU class description for the equations of
  \f$L_{\theta u}\f$.

  \param select : Selection of a subset of the possible \f$ \theta u \f$
  features. 
  - To compute the interaction matrix for all the three \f$ \theta u \f$ 
    features use vpBasicFeature::FEATURE_ALL. In that case the dimension of the
    interaction matrix is \f$ [3 \times 6] \f$
  - To compute the interaction matrix for only one of the \f$ \theta u \f$ 
    component feature (\f$\theta u_x, \theta u_y, \theta u_z\f$) use one of the
    corresponding function selectTUx(), selectTUy() or selectTUz(). In
    that case the returned interaction matrix is \f$ [1 \times 6] \f$
    dimension.

  \return The interaction matrix computed from the \f$ \theta u \f$
  features that represent either the rotation \f$^{c^*}R_c\f$ or the
  rotation \f$^{c}R_{c^*}\f$.

  The code below shows how to compute the interaction matrix
  associated to the visual feature \f$s = \theta u_x \f$. 

  \code
  vpRotationMatrix cdMc;

  // Creation of the current feature s
  vpFeatureThetaU s(vpFeatureThetaU::cdRc);
  s.buildFrom(cdMc);

  vpMatrix L_x = s.interaction( vpFeatureThetaU::selectTUx() );
  \endcode

  The code below shows how to compute the interaction matrix
  associated to the \f$s = (\theta u_x, \theta u_y) \f$
  subset visual feature:

  \code
  vpMatrix L_xy = s.interaction( vpFeatureThetaU::selectTUx() | vpFeatureThetaU::selectTUy() );
  \endcode

  L_xy is here now a 2 by 6 matrix. The first line corresponds to
  the \f$ \theta u_x \f$ visual feature while the second one to the \f$
  \theta u_y \f$ visual feature.

  It is also possible to build the interaction matrix from all the \f$
  \theta u \f$ components by:

  \code
  vpMatrix L_xyz = s.interaction( vpBasicFeature::FEATURE_ALL );
  \endcode

  In that case, L_xyz is a 3 by 6 interaction matrix where the last
  line corresponds to the \f$ \theta u_z \f$ visual feature.

*/
vpMatrix
vpFeatureThetaU::interaction(const unsigned int select)
{

  vpMatrix L ;
  L.resize(0,6) ;

  if (deallocate == vpBasicFeature::user)
  {
    for (unsigned int i = 0; i < nbParameters; i++)
    {
      if (flags[i] == false)
      {
        switch(i){
        case 0:
          vpTRACE("Warning !!!  The interaction matrix is computed but Tu_x was not set yet");
        break;
        case 1:
          vpTRACE("Warning !!!  The interaction matrix is computed but Tu_y was not set yet");
        break;
        case 2:
          vpTRACE("Warning !!!  The interaction matrix is computed but Tu_z was not set yet");
        break;
        default:
          vpTRACE("Problem during the reading of the variable flags");
        }
      }
    }
    resetFlags();
  }

  // Lw computed using Lw = [theta/2 u]_x +/- (I + alpha [u]_x [u]_x)
  vpColVector u(3)  ;
  for (unsigned int i=0 ; i < 3 ; i++) {
    u[i] = s[i]/2.0 ; 
  }
  
  vpMatrix Lw(3,3) ;
  Lw = vpColVector::skew(u) ;  /* [theta/2  u]_x */

  vpMatrix U2(3,3) ;
  U2.eye() ;
  
  double  theta = sqrt(s.sumSquare()) ;
  if (theta >= 1e-6) {
    for (unsigned int i=0 ; i < 3 ; i++) 
      u[i] = s[i]/theta ;

    vpMatrix skew_u ;
    skew_u = vpColVector::skew(u) ; 
    U2 += (1-vpMath::sinc(theta)/vpMath::sqr(vpMath::sinc(theta/2.0)))*skew_u*skew_u ;
  }
 
  if (rotation == cdRc) {
    Lw += U2; 
  }
  else { 
    Lw -=  U2; 
  }

  //This version is a simplification
  if (vpFeatureThetaU::selectTUx() & select )
    {
      vpMatrix Lx(1,6) ;

      Lx[0][0] = 0 ;    Lx[0][1] = 0 ;    Lx[0][2] = 0 ;
      for (int i=0 ; i < 3 ; i++) Lx[0][i+3] = Lw[0][i] ;


      L = vpMatrix::stack(L,Lx) ;
    }

  if (vpFeatureThetaU::selectTUy() & select )
    {
      vpMatrix Ly(1,6) ;

      Ly[0][0] = 0 ;    Ly[0][1] = 0 ;    Ly[0][2] = 0 ;
      for (int i=0 ; i < 3 ; i++) Ly[0][i+3] = Lw[1][i] ;

      L = vpMatrix::stack(L,Ly) ;
    }

  if (vpFeatureThetaU::selectTUz() & select )
    {
      vpMatrix Lz(1,6) ;

      Lz[0][0] = 0 ;    Lz[0][1] = 0 ;    Lz[0][2] = 0 ;
      for (int i=0 ; i < 3 ; i++) Lz[0][i+3] = Lw[2][i] ;

      L = vpMatrix::stack(L,Lz) ;
    }

  return L ;
}
Esempio n. 16
0
void
UrlWrapper::ArgvReceived(int32 argc, char** argv)
{
    if (argc <= 1)
        return;

    const char* failc = " || read -p 'Press any key'";
    const char* pausec = " ; read -p 'Press any key'";
    char* args[] = { (char *)"/bin/sh", (char *)"-c", NULL, NULL};
    status_t err;

    BUrl url(argv[1]);

    BString full = BUrl(url).SetProtocol(BString()).UrlString();
    BString proto = url.Protocol();
    BString host = url.Host();
    BString port = BString() << url.Port();
    BString user = url.UserInfo();
    BString pass = url.Password();
    BString path = url.Path();

    if (!url.IsValid()) {
        fprintf(stderr, "malformed url: '%s'\n", url.UrlString().String());
        return;
    }

    // XXX: debug
    PRINT(("PROTO='%s'\n", proto.String()));
    PRINT(("HOST='%s'\n", host.String()));
    PRINT(("PORT='%s'\n", port.String()));
    PRINT(("USER='%s'\n", user.String()));
    PRINT(("PASS='%s'\n", pass.String()));
    PRINT(("PATH='%s'\n", path.String()));

    if (proto == "about") {
        app_info info;
        BString sig;
        // BUrl could get an accessor for the full - proto part...
        sig = host << "/" << path;
        BMessage msg(B_ABOUT_REQUESTED);
        if (be_roster->GetAppInfo(sig.String(), &info) == B_OK) {
            BMessenger msgr(sig.String());
            msgr.SendMessage(&msg);
            return;
        }
        if (be_roster->Launch(sig.String(), &msg) == B_OK)
            return;
        be_roster->Launch("application/x-vnd.Haiku-About");
        return;
    }

    if (proto == "telnet") {
        BString cmd("telnet ");
        if (url.HasUserInfo())
            cmd << "-l " << user << " ";
        cmd << host;
        if (url.HasPort())
            cmd << " " << port;
        PRINT(("CMD='%s'\n", cmd.String()));
        cmd << failc;
        args[2] = (char*)cmd.String();
        be_roster->Launch(kTerminalSig, 3, args);
        return;
    }

    // see draft:
    // http://tools.ietf.org/wg/secsh/draft-ietf-secsh-scp-sftp-ssh-uri/
    if (proto == "ssh") {
        BString cmd("ssh ");

        if (url.HasUserInfo())
            cmd << "-l " << user << " ";
        if (url.HasPort())
            cmd << "-oPort=" << port << " ";
        cmd << host;
        PRINT(("CMD='%s'\n", cmd.String()));
        cmd << failc;
        args[2] = (char*)cmd.String();
        be_roster->Launch(kTerminalSig, 3, args);
        // TODO: handle errors
        return;
    }

    if (proto == "ftp") {
        BString cmd("ftp ");

        cmd << proto << "://";
        /*
        if (user.Length())
        	cmd << "-l " << user << " ";
        cmd << host;
        */
        cmd << full;
        PRINT(("CMD='%s'\n", cmd.String()));
        cmd << failc;
        args[2] = (char*)cmd.String();
        be_roster->Launch(kTerminalSig, 3, args);
        // TODO: handle errors
        return;
    }

    if (proto == "sftp") {
        BString cmd("sftp ");

        //cmd << url;
        if (url.HasPort())
            cmd << "-oPort=" << port << " ";
        if (url.HasUserInfo())
            cmd << user << "@";
        cmd << host;
        if (url.HasPath())
            cmd << ":" << path;
        PRINT(("CMD='%s'\n", cmd.String()));
        cmd << failc;
        args[2] = (char*)cmd.String();
        be_roster->Launch(kTerminalSig, 3, args);
        // TODO: handle errors
        return;
    }

    if (proto == "finger") {
        BString cmd("/bin/finger ");

        if (url.HasUserInfo())
            cmd << user;
        if (url.HasHost() == 0)
            host = "127.0.0.1";
        cmd << "@" << host;
        PRINT(("CMD='%s'\n", cmd.String()));
        cmd << pausec;
        args[2] = (char*)cmd.String();
        be_roster->Launch(kTerminalSig, 3, args);
        // TODO: handle errors
        return;
    }

    if (proto == "http" || proto == "https" /*|| proto == "ftp"*/) {
        BString cmd("/bin/wget ");

        //cmd << url;
        cmd << proto << "://";
        if (url.HasUserInfo())
            cmd << user << "@";
        cmd << full;
        PRINT(("CMD='%s'\n", cmd.String()));
        cmd << pausec;
        args[2] = (char*)cmd.String();
        be_roster->Launch(kTerminalSig, 3, args);
        // TODO: handle errors
        return;
    }

    if (proto == "file") {
        BMessage m(B_REFS_RECEIVED);
        entry_ref ref;
        _DecodeUrlString(path);
        if (get_ref_for_path(path.String(), &ref) < B_OK)
            return;
        m.AddRef("refs", &ref);
        be_roster->Launch(kTrackerSig, &m);
        return;
    }

    // XXX:TODO: split options
    if (proto == "query") {
        // mktemp ?
        BString qname("/tmp/query-url-temp-");
        qname << getpid() << "-" << system_time();
        BFile query(qname.String(), O_CREAT|O_EXCL);
        // XXX: should check for failure

        BString s;
        int32 v;

        _DecodeUrlString(full);
        // TODO: handle options (list of attrs in the column, ...)

        v = 'qybF'; // QuerY By Formula XXX: any #define for that ?
        query.WriteAttr("_trk/qryinitmode", B_INT32_TYPE, 0LL, &v, sizeof(v));
        s = "TextControl";
        query.WriteAttr("_trk/focusedView", B_STRING_TYPE, 0LL, s.String(),
                        s.Length()+1);
        s = full;
        PRINT(("QUERY='%s'\n", s.String()));
        query.WriteAttr("_trk/qryinitstr", B_STRING_TYPE, 0LL, s.String(),
                        s.Length()+1);
        query.WriteAttr("_trk/qrystr", B_STRING_TYPE, 0LL, s.String(),
                        s.Length()+1);
        s = "application/x-vnd.Be-query";
        query.WriteAttr("BEOS:TYPE", 'MIMS', 0LL, s.String(), s.Length()+1);


        BEntry e(qname.String());
        entry_ref er;
        if (e.GetRef(&er) >= B_OK)
            be_roster->Launch(&er);
        return;
    }

    if (proto == "sh") {
        BString cmd(full);
        if (_Warn(url.UrlString()) != B_OK)
            return;
        PRINT(("CMD='%s'\n", cmd.String()));
        cmd << pausec;
        args[2] = (char*)cmd.String();
        be_roster->Launch(kTerminalSig, 3, args);
        // TODO: handle errors
        return;
    }

    if (proto == "beshare") {
        team_id team;
        BMessenger msgr(kBeShareSig);
        // if no instance is running, or we want a specific server, start it.
        if (!msgr.IsValid() || url.HasHost()) {
            be_roster->Launch(kBeShareSig, (BMessage*)NULL, &team);
            msgr = BMessenger(NULL, team);
        }
        if (url.HasHost()) {
            BMessage mserver('serv');
            mserver.AddString("server", host);
            msgr.SendMessage(&mserver);

        }
        if (url.HasPath()) {
            BMessage mquery('quer');
            mquery.AddString("query", path);
            msgr.SendMessage(&mquery);
        }
        // TODO: handle errors
        return;
    }

    if (proto == "icq" || proto == "msn") {
        // TODO
        team_id team;
        be_roster->Launch(kIMSig, (BMessage*)NULL, &team);
        BMessenger msgr(NULL, team);
        if (url.HasHost()) {
            BMessage mserver(B_REFS_RECEIVED);
            mserver.AddString("server", host);
            msgr.SendMessage(&mserver);

        }
        // TODO: handle errors
        return;
    }

    if (proto == "mms" || proto == "rtp" || proto == "rtsp") {
        args[0] = (char*)url.UrlString().String();
        be_roster->Launch(kVLCSig, 1, args);
        return;
    }

    if (proto == "nfs") {
        BString parameter(host);
        _DecodeUrlString(path);
        if (url.HasPort())
            parameter << ":" << port;
        //XXX: should not always be absolute! FIXME
        parameter << ":/" << path;
        BString prettyPath(path);
        prettyPath.Remove(0, prettyPath.FindLast("/") + 1);
        if (path == "" || path == "/")
            prettyPath = "root";
        prettyPath << " on " << host;
        prettyPath.Prepend("/");
        if (mkdir(prettyPath.String(), 0755) < 0) {
            perror("mkdir");
            return;
        }
        dev_t volume;
        uint32 flags = 0;
        fprintf(stderr, "parms:'%s'\n", parameter.String());
        volume = fs_mount_volume(prettyPath.String(), NULL, "nfs4", flags,
                                 parameter.String());
        if (volume < B_OK) {
            fprintf(stderr, "fs_mount_volume: %s\n", strerror(volume));
            return;
        }

        BMessage m(B_REFS_RECEIVED);
        entry_ref ref;
        if (get_ref_for_path(prettyPath.String(), &ref) < B_OK)
            return;
        m.AddRef("refs", &ref);
        be_roster->Launch(kTrackerSig, &m);
        return;
    }

    if (proto == "doi") {
        BString url("http://dx.doi.org/");
        BString mimetype;

        url << full;
        BUrl u(url.String());
        args[0] = const_cast<char*>("urlwrapper"); //XXX
        args[1] = (char*)u.UrlString().String();
        args[2] = NULL;
        mimetype = kURLHandlerSigBase;
        mimetype += u.Protocol();

        err = be_roster->Launch(mimetype.String(), 1, args + 1);
        if (err != B_OK && err != B_ALREADY_RUNNING)
            err = be_roster->Launch(kAppSig, 1, args + 1);
        // TODO: handle errors
        return;
    }

    /*

    More ?
    cf. http://en.wikipedia.org/wiki/URI_scheme
    cf. http://www.iana.org/assignments/uri-schemes.html

    Audio: (SoundPlay specific, identical to http:// to a shoutcast server)

    vnc: ?
    irc: ?
    im: http://tools.ietf.org/html/rfc3860

    svn: handled by checkitout
    cvs: handled by checkitout
    git: handled by checkitout
    rsync: handled by checkitout - http://tools.ietf.org/html/rfc5781

    smb: cifsmount ?
    nfs: mount_nfs ? http://tools.ietf.org/html/rfc2224
    ipp: http://tools.ietf.org/html/rfc3510

    mailto: ? Mail & Beam both handle it already (not fully though).
    imap: to describe mail accounts ? http://tools.ietf.org/html/rfc5092
    pop: http://tools.ietf.org/html/rfc2384
    mid: cid: as per RFC 2392
    http://www.rfc-editor.org/rfc/rfc2392.txt query MAIL:cid
    message:<MID> http://daringfireball.net/2007/12/message_urls_leopard_mail

    itps: pcast: podcast: s//http/ + parse xml to get url to mp3 stream...
    audio: s//http:/ + default MediaPlayer
    -- see http://forums.winamp.com/showthread.php?threadid=233130

    gps: ? I should submit an RFC for that one :)

    webcal: (is http: to .ics file)

    data: (but it's dangerous)

    */


}
void ribi::tictactoe::Board::Test() noexcept
{
  {
    static bool is_tested{false};
    if (is_tested) return;
    is_tested = true;
  }
  const TestTimer test_timer(__func__,__FILE__,1.0);
  {
    //Check empty board state
    {
      Board t;
      const int s = t.GetSummarizedState();
      Board u(s);
      assert(u == t);
    }
    //Check one-move states
    for (int i=0; i!=9; ++i)
    {
      Board t;
      t.DoMove(i/3,i%3,Player::player1);
      const int s = t.GetSummarizedState();
      Board u(s);
      assert(u == t);
    }
    //Check two-move states
    for (int i=0; i!=8; ++i)
    {
      Board t;
      t.DoMove(i/3,i%3,Player::player1);
      t.DoMove(i/3,(i+1)%3,Player::player2);
      const int s = t.GetSummarizedState();
      Board u(s);
      assert(u == t);
    }
    //Check draw detection
    {
      Board t;
      t.DoMove(1,1,Player::player1);
      t.DoMove(0,0,Player::player2);
      t.DoMove(1,2,Player::player1);
      t.DoMove(1,0,Player::player2);
      t.DoMove(2,0,Player::player1);
      t.DoMove(0,2,Player::player2);
      t.DoMove(0,1,Player::player1);
      t.DoMove(2,1,Player::player2);
      t.DoMove(2,2,Player::player1);
      assert(t.GetWinner() == Winner::draw);
    }
    //Check player1 wins horizontally detection
    {
      Board t;
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(0,0,Player::player1);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(1,0,Player::player2);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(0,1,Player::player1);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(1,1,Player::player2);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(0,2,Player::player1);
      assert(t.GetWinner() == Winner::player1);
    }
    //Check player2 wins vertically detection
    {
      Board t;
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(0,0,Player::player1);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(1,0,Player::player2);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(0,1,Player::player1);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(1,1,Player::player2);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(2,2,Player::player1);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(1,2,Player::player2);
      assert(t.GetWinner() == Winner::player2);
    }
    //Check player1 wins diagonally detection
    {
      Board t;
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(0,0,Player::player1);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(1,0,Player::player2);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(1,1,Player::player1);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(1,2,Player::player2);
      assert(t.GetWinner() == Winner::no_winner);
      t.DoMove(2,2,Player::player1);
      assert(t.GetWinner() == Winner::player1);
    }
    //Check no-winner detection
    {
      Board t;
      t.DoMove(1,1,Player::player1);
      t.DoMove(0,0,Player::player2);
      t.DoMove(1,2,Player::player1);
      t.DoMove(1,0,Player::player2);
      t.DoMove(2,0,Player::player1);
      t.DoMove(0,2,Player::player2);
      t.DoMove(0,1,Player::player1);
      t.DoMove(2,1,Player::player2);
      //t.DoMove(2,2); //Final move to make a draw
      assert(t.GetWinner() == Winner::no_winner);
    }
    //Check CanDoMove
    for (int i=0; i!=9; ++i)
    {
      Board t;
      t.DoMove(i/3,i%3,Player::player1);
      assert(!t.CanDoMove(i/3,i%3));
    }
    //Check all states
    for (int i=0; i!=Helper().IntPower(3,9); ++i)
    {
      try
      {
        Board t(i);
        assert(t.GetSummarizedState() == i);
      }
      catch (std::exception&)
      {
        //No problem
      }
    }
  }
}
Esempio n. 18
0
void
UrlWrapper::RefsReceived(BMessage* msg)
{
    char buff[B_PATH_NAME_LENGTH];
    int32 index = 0;
    entry_ref ref;
    char* args[] = { const_cast<char*>("urlwrapper"), buff, NULL };
    status_t err;

    while (msg->FindRef("refs", index++, &ref) == B_OK) {
        BFile f(&ref, B_READ_ONLY);
        BNodeInfo ni(&f);
        BString mimetype;
        BString extension(ref.name);
        extension.Remove(0, extension.FindLast('.') + 1);
        if (f.InitCheck() == B_OK && ni.InitCheck() == B_OK) {
            ni.GetType(mimetype.LockBuffer(B_MIME_TYPE_LENGTH));
            mimetype.UnlockBuffer();

            // Internet Explorer Shortcut
            if (mimetype == "text/x-url" || extension == "url") {
                // http://filext.com/file-extension/URL
                // http://www.cyanwerks.com/file-format-url.html
                off_t size;
                if (f.GetSize(&size) < B_OK)
                    continue;
                BString contents;
                BString url;
                if (f.ReadAt(0LL, contents.LockBuffer(size), size) < B_OK)
                    continue;
                contents.UnlockBuffer();
                while (contents.Length()) {
                    BString line;
                    int32 cr = contents.FindFirst('\n');
                    if (cr < 0)
                        cr = contents.Length();
                    //contents.MoveInto(line, 0, cr);
                    contents.CopyInto(line, 0, cr);
                    contents.Remove(0, cr+1);
                    line.RemoveAll("\r");
                    if (!line.Length())
                        continue;
                    if (!line.ICompare("URL=", 4)) {
                        line.MoveInto(url, 4, line.Length());
                        break;
                    }
                }
                if (url.Length()) {
                    BUrl u(url.String());
                    args[1] = (char*)u.UrlString().String();
                    mimetype = kURLHandlerSigBase;
                    mimetype += u.Protocol();
                    err = be_roster->Launch(mimetype.String(), 1, args + 1);
                    if (err != B_OK && err != B_ALREADY_RUNNING)
                        err = be_roster->Launch(kAppSig, 1, args + 1);
                    continue;
                }
            }
            if (mimetype == "text/x-webloc" || extension == "webloc") {
                // OSX url shortcuts
                // XML file + resource fork
                off_t size;
                if (f.GetSize(&size) < B_OK)
                    continue;
                BString contents;
                BString url;
                if (f.ReadAt(0LL, contents.LockBuffer(size), size) < B_OK)
                    continue;
                contents.UnlockBuffer();
                int state = 0;
                while (contents.Length()) {
                    BString line;
                    int32 cr = contents.FindFirst('\n');
                    if (cr < 0)
                        cr = contents.Length();
                    contents.CopyInto(line, 0, cr);
                    contents.Remove(0, cr+1);
                    line.RemoveAll("\r");
                    if (!line.Length())
                        continue;
                    int32 s, e;
                    switch (state) {
                    case 0:
                        if (!line.ICompare("<?xml", 5))
                            state = 1;
                        break;
                    case 1:
                        if (!line.ICompare("<plist", 6))
                            state = 2;
                        break;
                    case 2:
                        if (!line.ICompare("<dict>", 6))
                            state = 3;
                        break;
                    case 3:
                        if (line.IFindFirst("<key>URL</key>") > -1)
                            state = 4;
                        break;
                    case 4:
                        if ((s = line.IFindFirst("<string>")) > -1
                                && (e = line.IFindFirst("</string>")) > s) {
                            state = 5;
                            s += 8;
                            line.MoveInto(url, s, e - s);
                            break;
                        } else
                            state = 3;
                        break;
                    default:
                        break;
                    }
                    if (state == 5) {
                        break;
                    }
                }
                if (url.Length()) {
                    BUrl u(url.String());
                    args[1] = (char*)u.UrlString().String();
                    mimetype = kURLHandlerSigBase;
                    mimetype += u.Protocol();
                    err = be_roster->Launch(mimetype.String(), 1, args + 1);
                    if (err != B_OK && err != B_ALREADY_RUNNING)
                        err = be_roster->Launch(kAppSig, 1, args + 1);
                    continue;
                }
            }

            // NetPositive Bookmark or any file with a META:url attribute
            if (f.ReadAttr("META:url", B_STRING_TYPE, 0LL, buff,
                           B_PATH_NAME_LENGTH) > 0) {
                BUrl u(buff);
                args[1] = (char*)u.UrlString().String();
                mimetype = kURLHandlerSigBase;
                mimetype += u.Protocol();
                err = be_roster->Launch(mimetype.String(), 1, args + 1);
                if (err != B_OK && err != B_ALREADY_RUNNING)
                    err = be_roster->Launch(kAppSig, 1, args + 1);
                continue;
            }
        }
    }
}
Esempio n. 19
0
  bool is_kuratowski_subgraph(const Graph& g,
                              ForwardIterator begin, 
                              ForwardIterator end, 
                              VertexIndexMap vm
                              )
  {

    typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;
    typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator_t;
    typedef typename graph_traits<Graph>::edge_descriptor edge_t;
    typedef typename graph_traits<Graph>::edges_size_type e_size_t;
    typedef typename graph_traits<Graph>::vertices_size_type v_size_t;
    typedef typename std::vector<vertex_t> v_list_t;
    typedef typename v_list_t::iterator v_list_iterator_t;
    typedef iterator_property_map
      <typename std::vector<v_list_t>::iterator, VertexIndexMap> 
      vertex_to_v_list_map_t;

    typedef adjacency_list<vecS, vecS, undirectedS> small_graph_t;

    detail::target_graph_t target_graph = detail::tg_k_3_3; //unless we decide otherwise later

    static small_graph_t K_5(detail::make_K_5<small_graph_t>());

    static small_graph_t K_3_3(detail::make_K_3_3<small_graph_t>());

    v_size_t n_vertices(num_vertices(g));
    v_size_t max_num_edges(3*n_vertices - 5);

    std::vector<v_list_t> neighbors_vector(n_vertices);
    vertex_to_v_list_map_t neighbors(neighbors_vector.begin(), vm);

    e_size_t count = 0;
    for(ForwardIterator itr = begin; itr != end; ++itr)
      {

        if (count++ > max_num_edges)
          return false;

        edge_t e(*itr);
        vertex_t u(source(e,g));
        vertex_t v(target(e,g));

        neighbors[u].push_back(v);
        neighbors[v].push_back(u);

      }


    for(v_size_t max_size = 2; max_size < 5; ++max_size)
      {

        vertex_iterator_t vi, vi_end;
        for(tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)
          {
            vertex_t v(*vi);

            //a hack to make sure we don't contract the middle edge of a path
            //of four degree-3 vertices
            if (max_size == 4 && neighbors[v].size() == 3)
              {
                if (neighbors[neighbors[v][0]].size() +
                    neighbors[neighbors[v][1]].size() +
                    neighbors[neighbors[v][2]].size()
                    < 11 // so, it has two degree-3 neighbors
                    )
                  continue;
              }

            while (neighbors[v].size() > 0 && neighbors[v].size() < max_size)
              {
                // Find one of v's neighbors u such that that v and u
                // have no neighbors in common. We'll look for such a 
                // neighbor with a naive cubic-time algorithm since the 
                // max size of any of the neighbor sets we'll consider 
                // merging is 3
                
                bool neighbor_sets_intersect = false;
                
                vertex_t min_u = graph_traits<Graph>::null_vertex();
                vertex_t u;
                v_list_iterator_t v_neighbor_end = neighbors[v].end();
                for(v_list_iterator_t v_neighbor_itr = neighbors[v].begin();
                    v_neighbor_itr != v_neighbor_end; 
                    ++v_neighbor_itr
                    )
                  {
                    neighbor_sets_intersect = false;
                    u = *v_neighbor_itr;
                    v_list_iterator_t u_neighbor_end = neighbors[u].end();
                    for(v_list_iterator_t u_neighbor_itr = 
                          neighbors[u].begin();
                        u_neighbor_itr != u_neighbor_end && 
                          !neighbor_sets_intersect; 
                        ++u_neighbor_itr
                        )
                      {
                        for(v_list_iterator_t inner_v_neighbor_itr = 
                              neighbors[v].begin();
                            inner_v_neighbor_itr != v_neighbor_end; 
                            ++inner_v_neighbor_itr
                            )
                          {
                            if (*u_neighbor_itr == *inner_v_neighbor_itr)
                              {
                                neighbor_sets_intersect = true;
                                break;
                              }
                          }
                        
                      }
                    if (!neighbor_sets_intersect &&
                        (min_u == graph_traits<Graph>::null_vertex() || 
                         neighbors[u].size() < neighbors[min_u].size())
                        )
                      {
                        min_u = u;
                      }
                        
                  }

                if (min_u == graph_traits<Graph>::null_vertex())
                  // Exited the loop without finding an appropriate neighbor of
                  // v, so v must be a lost cause. Move on to other vertices.
                  break;
                else
                  u = min_u;

                detail::contract_edge(neighbors, u, v);

              }//end iteration over v's neighbors

          }//end iteration through vertices v

        if (max_size == 3)
          {
            // check to see whether we should go on to find a K_5
            for(tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)
              if (neighbors[*vi].size() == 4)
                {
                  target_graph = detail::tg_k_5;
                  break;
                }

            if (target_graph == detail::tg_k_3_3)
              break;
          }
        
      }//end iteration through max degree 2,3, and 4

    
    //Now, there should only be 5 or 6 vertices with any neighbors. Find them.
    
    v_list_t main_vertices;
    vertex_iterator_t vi, vi_end;
    
    for(tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)
      {
        if (!neighbors[*vi].empty())
          main_vertices.push_back(*vi);
      }
    
    // create a graph isomorphic to the contracted graph to test 
    // against K_5 and K_3_3
    small_graph_t contracted_graph(main_vertices.size());
    std::map<vertex_t,typename graph_traits<small_graph_t>::vertex_descriptor> 
      contracted_vertex_map;
    
    typename v_list_t::iterator itr, itr_end;
    itr_end = main_vertices.end();
    typename graph_traits<small_graph_t>::vertex_iterator 
      si = vertices(contracted_graph).first;
    
    for(itr = main_vertices.begin(); itr != itr_end; ++itr, ++si)
      {
        contracted_vertex_map[*itr] = *si;
      }

    typename v_list_t::iterator jtr, jtr_end;
    for(itr = main_vertices.begin(); itr != itr_end; ++itr)
      {
        jtr_end = neighbors[*itr].end();
        for(jtr = neighbors[*itr].begin(); jtr != jtr_end; ++jtr)
          {
            if (get(vm,*itr) < get(vm,*jtr))
              {
                add_edge(contracted_vertex_map[*itr],
                         contracted_vertex_map[*jtr],
                         contracted_graph
                         );
              }
          }
      }
    
    if (target_graph == detail::tg_k_5)
      {
        return isomorphism(K_5,contracted_graph);
      }
    else //target_graph == tg_k_3_3
      {
        return isomorphism(K_3_3,contracted_graph);
      }
    
    
  }
Esempio n. 20
0
bool 
PelletTransport::evaluate(NOX::Epetra::Interface::Required::FillType fType, 
				    const Epetra_Vector* soln, 
				    Epetra_Vector* tmp_rhs, 
				    Epetra_RowMatrix* tmp_matrix)
{

  if( fType == NOX::Epetra::Interface::Required::Jac ) 
  {
    cout << "This problem only works for Finite-Difference or Matrix-Free Based Jacobians." 
         << " No analytic Jacobian fill available !!" << endl;
    throw "Problem ERROR";
  }
  else 
    rhs = new Epetra_Vector(*OverlapMap);

  // Create the overlapped solution and position vectors
  Epetra_Vector u(*OverlapMap);
  Epetra_Vector uold(*OverlapMap);
  Epetra_Vector xvec(*OverlapNodeMap);

  // Export Solution to Overlap vector
  uold.Import(*oldSolution, *Importer, Insert);
  xvec.Import(*xptr, *nodeImporter, Insert);
  u.Import(*soln, *Importer, Insert);

  // Declare required variables
  int i;
  int OverlapNumMyNodes = OverlapNodeMap->NumMyElements();

  MaterialPropBase::PropData materialProps;
  // Hard-code use of UO2 for now - RWH 5/14/2007
  string fixedType = "UO2";
  
  int OverlapMinMyNodeGID;
  if (MyPID==0) OverlapMinMyNodeGID = StandardNodeMap->MinMyGID();
  else OverlapMinMyNodeGID = StandardNodeMap->MinMyGID()-1;

  int row1, row2;
  double term1, term2;
  double flux1, flux2;
  double xx[2];
  double uu[2*NUMSPECIES]; // Use of the anonymous enum is needed for SGI builds
  double uuold[2*NUMSPECIES];
  Basis basis(NumSpecies);

  
  // Zero out the objects that will be filled
  rhs->PutScalar(0.0);

  ACTIVE_REGIONS propType;

  // Loop Over # of Finite Elements on Processor
  for( int ne = 0; ne < OverlapNumMyNodes - 1; ++ne )
  {
    propType = (ACTIVE_REGIONS) (*elemTypes)[ne];

    // Loop Over Gauss Points
    for( int gp = 0; gp < 2; ++gp )
    {
      // Get the solution and coordinates at the nodes 
      xx[0] = xvec[ne];
      xx[1] = xvec[ne+1];
      for (int k=0; k<NumSpecies; k++) {
        uu[NumSpecies * 0 + k] = u[NumSpecies * ne + k];
        uu[NumSpecies * 1 + k] = u[NumSpecies * (ne+1) + k];
        uuold[NumSpecies * 0 + k] = uold[NumSpecies * ne + k];
        uuold[NumSpecies * 1 + k] = uold[NumSpecies * (ne+1) + k];
      }
      // Calculate the basis function at the gauss point
      basis.getBasis(gp, xx, uu, uuold);
      MaterialPropFactory::computeProps( propType, basis.uu[0], basis.uu[1], materialProps );
      double & rho1    = materialProps.density  ;
      double & k1      = materialProps.k_thermal;
      double & Cp1     = materialProps.Cp       ;
      double & Qstar1  = materialProps.Qstar    ;
      double & Qdot1   = materialProps.Qdot     ;
      double & Ffunc   = materialProps.thermoF  ;
      double & D_diff1 = materialProps.D_diff   ;

	            
      // Loop over Nodes in Element
      for( i = 0; i < 2; ++i ) 
      {
	row1=OverlapMap->GID(NumSpecies * (ne+i));
	row2=OverlapMap->GID(NumSpecies * (ne+i) + 1);
        flux1 = -k1*basis.duu[0]/basis.dx;
        flux2 = -0.5*D_diff1*(basis.duu[1]/basis.dx 
              + basis.uu[1]*Qstar1/(Ffunc*8.3142*basis.uu[0]*basis.uu[0])*basis.duu[0]/basis.dx);
        term1 = basis.wt*basis.dx*basis.xx*( 
                    rho1*Cp1*(basis.uu[0] - basis.uuold[0])/dt * basis.phi[i] 
                  - flux1*basis.dphide[i]/basis.dx
                  - Qdot1*basis.phi[i]
                );
        term2 = basis.wt*basis.dx*basis.xx*(
                    0.5*(basis.uu[1] - basis.uuold[1])/dt * basis.phi[i] 
                  - flux2*basis.dphide[i]/basis.dx 
                );
        (*rhs)[NumSpecies*(ne+i)]   += term1;
        (*rhs)[NumSpecies*(ne+i)+1] += term2;
      }
    }
  }

  // Insert Boundary Conditions and modify Jacobian and function (F)
  // Dirichlet BCs at xminUO2
  const double xB = dynamic_cast<const MaterialProp_UO2 &>(MaterialPropFactory::factory().get_model(PelletTransport::UO2)).get_xB();
  if (MyPID==0) 
  {
    // Use no-flux BCs
    //(*rhs)[0]= (*soln)[0] - 0.6;
    //(*rhs)[1]= (*soln)[1] - 10.0/3.0;
  }
  // Dirichlet BCs at xmaxUO2
  if( StandardMap->LID(NumSpecies*(NumGlobalElementsUO2)) >= 0 ) 
  {
    int lastUO2Dof = StandardMap->LID(NumSpecies*(NumGlobalElementsUO2) + 1);
    //(*rhs)[lastDof - 1] = (*soln)[lastDof - 1] - 840.0;
    (*rhs)[lastUO2Dof] = (*soln)[lastUO2Dof] - xB;
  }
  // Dirichlet BCs at all He and Clad species variables
  int lastUO2DofGID = NumSpecies*NumGlobalElementsUO2 + 1;
  int lastGID = StandardMap->MaxAllGID();
  for( int i = lastUO2DofGID; i < lastGID; i+=2 )
    if( StandardMap->LID(i) >= 0 ) 
      (*rhs)[StandardMap->LID(i)] = (*soln)[StandardMap->LID(i)] - xB;
    
  // Dirichlet BCs at xmaxClad
  if( StandardMap->LID(StandardMap->MaxAllGID()) >= 0 ) 
  {
    int lastDof = StandardMap->LID(StandardMap->MaxAllGID());
    (*rhs)[lastDof - 1] = (*soln)[lastDof - 1] - 750.0;
    (*rhs)[lastDof] = (*soln)[lastDof] - xB;
  }

  // Sync up processors to be safe
  Comm->Barrier();
 
  // Do an assemble for overlap nodes
  tmp_rhs->Export(*rhs, *Importer, Add);

  delete rhs;

  return true;
}
Esempio n. 21
0
// Matrix and Residual Fills
bool Interface::evaluate(NOX::Epetra::Interface::Required::FillType flag,
             const Epetra_Vector* soln,
             Epetra_Vector* tmp_rhs,
             Epetra_RowMatrix* tmp_matrix)
{
  //Determine what to fill (F or Jacobian)
  bool fillF = false;
  bool fillMatrix = false;
  if (tmp_rhs != 0) {
    fillF = true;
    rhs = tmp_rhs;
  }
  else {
    fillMatrix = true;
  }

  // "flag" can be used to determine how accurate your fill of F should be
  // depending on why we are calling evaluate (Could be using computeF to
  // populate a Jacobian or Preconditioner).
  if (flag == NOX::Epetra::Interface::Required::Residual) {
    // Do nothing for now
  }
  else if (flag == NOX::Epetra::Interface::Required::Jac) {
    // Do nothing for now
  }
  else if (flag == NOX::Epetra::Interface::Required::Prec) {
    // Do nothing for now
  }
  else if (flag == NOX::Epetra::Interface::Required::User) {
    // Do nothing for now
  }


  // Create the overlapped solution and position vectors
  Epetra_Vector u(*OverlapMap);
  Epetra_Vector x(*OverlapMap);

  // Export Solution to Overlap vector
  u.Import(*soln, *Importer, Insert);
  x.Import(*xptr, *Importer, Insert);

  // Declare required variables
  int ierr;
  int OverlapNumMyElements = OverlapMap->NumMyElements();

  int OverlapMinMyGID;
  if (MyPID == 0) OverlapMinMyGID = StandardMap->MinMyGID();
  else OverlapMinMyGID = StandardMap->MinMyGID()-1;

  int row, column;
  double jac;
  double xx[2];
  double uu[2];
  Basis basis;

  // Zero out the objects that will be filled
  if (fillF)
    rhs->PutScalar(0.0);
  if (fillMatrix)
    jacobian->PutScalar(0.0);

  // Loop Over # of Finite Elements on Processor
  for (int ne=0; ne < OverlapNumMyElements-1; ne++) {

    // Loop Over Gauss Points
    for(int gp=0; gp < 2; gp++) {
      // Get the solution and coordinates at the nodes
      xx[0]=x[ne];
      xx[1]=x[ne+1];
      uu[0]=u[ne];
      uu[1]=u[ne+1];
      // Calculate the basis function at the gauss point
      basis.computeBasis(gp, xx, uu);

      // Loop over Nodes in Element
      for (int i=0; i< 2; i++) {
    row=OverlapMap->GID(ne+i);
    //printf("Proc=%d GlobalRow=%d LocalRow=%d Owned=%d\n",
    //     MyPID, row, ne+i,StandardMap.MyGID(row));
    if (StandardMap->MyGID(row)) {
      if (fillF) {
        (*rhs)[StandardMap->LID(OverlapMap->GID(ne+i))]+=
          +basis.wt*basis.dx
          *((1.0/(basis.dx*basis.dx))*basis.duu*
        basis.dphide[i]+factor*basis.uu*basis.uu*basis.phi[i]);
      }
    }
    // Loop over Trial Functions
    if (fillMatrix) {
      for(int j=0;j < 2; j++) {
        if (StandardMap->MyGID(row)) {
          column=OverlapMap->GID(ne+j);
          jac=basis.wt*basis.dx*((1.0/(basis.dx*basis.dx))*
                     basis.dphide[j]*basis.dphide[i]
                     +2.0*factor*basis.uu*basis.phi[j]*
                     basis.phi[i]);
          ierr=jacobian->SumIntoGlobalValues(row, 1, &jac, &column);
        }
      }
    }
      }
    }
  }

  // Insert Boundary Conditions and modify Jacobian and function (F)
  // U(0)=1
  if (MyPID==0) {
    if (fillF)
      (*rhs)[0]= (*soln)[0] - 1.0;
    if (fillMatrix) {
      column=0;
      jac=1.0;
      jacobian->ReplaceGlobalValues(0, 1, &jac, &column);
      column=1;
      jac=0.0;
      jacobian->ReplaceGlobalValues(0, 1, &jac, &column);
    }
  }

  // Sync up processors to be safe
  Comm->Barrier();

  jacobian->FillComplete();

  return true;
}
Esempio n. 22
0
void test_comp() {
	// signed gt
	assert(i(10)>i(5)==1);
	assert(i(5)>i(10)==0);
	assert(i(5)>i(5)==0);
	assert(i(-10)>i(5)==0);
	assert(i(-5)>i(10)==0);
	assert(i(-5)>i(5)==0);
	assert(i(10)>i(-5)==1);
	assert(i(5)>i(-10)==1);
	assert(i(5)>i(-5)==1);
	assert(i(-10)>i(-5)==0);
	assert(i(-5)>i(-10)==1);
	assert(i(-5)>i(-5)==0);

	// signed ge
	assert(i(10)>=i(5)==1);
	assert(i(5)>=i(10)==0);
	assert(i(5)>=i(5)==1);
	assert(i(-10)>=i(5)==0);
	assert(i(-5)>=i(10)==0);
	assert(i(-5)>=i(5)==0);
	assert(i(10)>=i(-5)==1);
	assert(i(5)>=i(-10)==1);
	assert(i(5)>=i(-5)==1);
	assert(i(-10)>=i(-5)==0);
	assert(i(-5)>=i(-10)==1);
	assert(i(-5)>=i(-5)==1);

	// signed lt
	assert(i(10)<i(5)==0);
	assert(i(5)<i(10)==1);
	assert(i(5)<i(5)==0);
	assert(i(-10)<i(5)==1);
	assert(i(-5)<i(10)==1);
	assert(i(-5)<i(5)==1);
	assert(i(10)<i(-5)==0);
	assert(i(5)<i(-10)==0);
	assert(i(5)<i(-5)==0);
	assert(i(-10)<i(-5)==1);
	assert(i(-5)<i(-10)==0);
	assert(i(-5)<i(-5)==0);

	// signed le
	assert(i(10)<=i(5)==0);
	assert(i(5)<=i(10)==1);
	assert(i(5)<=i(5)==1);
	assert(i(-10)<=i(5)==1);
	assert(i(-5)<=i(10)==1);
	assert(i(-5)<=i(5)==1);
	assert(i(10)<=i(-5)==0);
	assert(i(5)<=i(-10)==0);
	assert(i(5)<=i(-5)==0);
	assert(i(-10)<=i(-5)==1);
	assert(i(-5)<=i(-10)==0);
	assert(i(-5)<=i(-5)==1);

	// signed eq
	assert(i(10)==i(5)==0);
	assert(i(5)==i(10)==0);
	assert(i(5)==i(5)==1);
	assert(i(-10)==i(5)==0);
	assert(i(-5)==i(10)==0);
	assert(i(-5)==i(5)==0);
	assert(i(10)==i(-5)==0);
	assert(i(5)==i(-10)==0);
	assert(i(5)==i(-5)==0);
	assert(i(-10)==i(-5)==0);
	assert(i(-5)==i(-10)==0);
	assert(i(-5)==i(-5)==1);

	// signed ne
	assert(i(10)!=i(5)==1);
	assert(i(5)!=i(10)==1);
	assert(i(5)!=i(5)==0);
	assert(i(-10)!=i(5)==1);
	assert(i(-5)!=i(10)==1);
	assert(i(-5)!=i(5)==1);
	assert(i(10)!=i(-5)==1);
	assert(i(5)!=i(-10)==1);
	assert(i(5)!=i(-5)==1);
	assert(i(-10)!=i(-5)==1);
	assert(i(-5)!=i(-10)==1);
	assert(i(-5)!=i(-5)==0);

	// unsigned gt
	assert(u(10)>u(5)==1);
	assert(u(5)>u(10)==0);
	assert(u(5)>u(5)==0);

	// unsigned ge
	assert(u(10)>=u(5)==1);
	assert(u(5)>=u(10)==0);
	assert(u(5)>=u(5)==1);

	// unsigned lt
	assert(u(10)<u(5)==0);
	assert(u(5)<u(10)==1);
	assert(u(5)<u(5)==0);

	// unsigned le
	assert(u(10)<=u(5)==0);
	assert(u(5)<=u(10)==1);
	assert(u(5)<=u(5)==1);

	// unsigned eq
	assert(u(10)==u(5)==0);
	assert(u(5)==u(10)==0);
	assert(u(5)==u(5)==1);

	// unsigned ne
	assert(u(10)!=u(5)==1);
	assert(u(5)!=u(10)==1);
	assert(u(5)!=u(5)==0);

}
//An implementation of the variational pressure projection solve for static geometry
void FluidSim::solve_pressure(float dt) {
   
   //This linear system could be simplified, but I've left it as is for clarity 
   //and consistency with the standard naive discretization
   
   int ni = v.ni;
   int nj = u.nj;
   int system_size = ni*nj;
   if(rhs.size() != system_size) {
      rhs.resize(system_size);
      pressure.resize(system_size);
      matrix.resize(system_size);
   }
   matrix.zero();
   
   //Build the linear system for pressure
   for(int j = 1; j < nj-1; ++j) {
      for(int i = 1; i < ni-1; ++i) {
         int index = i + ni*j;
         rhs[index] = 0;
         pressure[index] = 0;
         float centre_phi = liquid_phi(i,j);
         if(centre_phi < 0) {

            //right neighbour
            float term = u_weights(i+1,j) * dt / sqr(dx);
            float right_phi = liquid_phi(i+1,j);
            if(right_phi < 0) {
               matrix.add_to_element(index, index, term);
               matrix.add_to_element(index, index + 1, -term);
            }
            else {
               float theta = fraction_inside(centre_phi, right_phi);
               if(theta < 0.01f) theta = 0.01f;
               matrix.add_to_element(index, index, term/theta);
            }
            rhs[index] -= u_weights(i+1,j)*u(i+1,j) / dx;
            
            //left neighbour
            term = u_weights(i,j) * dt / sqr(dx);
            float left_phi = liquid_phi(i-1,j);
            if(left_phi < 0) {
               matrix.add_to_element(index, index, term);
               matrix.add_to_element(index, index - 1, -term);
            }
            else {
               float theta = fraction_inside(centre_phi, left_phi);
               if(theta < 0.01f) theta = 0.01f;
               matrix.add_to_element(index, index, term/theta);
            }
            rhs[index] += u_weights(i,j)*u(i,j) / dx;
            
            //top neighbour
            term = v_weights(i,j+1) * dt / sqr(dx);
            float top_phi = liquid_phi(i,j+1);
            if(top_phi < 0) {
               matrix.add_to_element(index, index, term);
               matrix.add_to_element(index, index + ni, -term);
            }
            else {
               float theta = fraction_inside(centre_phi, top_phi);
               if(theta < 0.01f) theta = 0.01f;
               matrix.add_to_element(index, index, term/theta);
            }
            rhs[index] -= v_weights(i,j+1)*v(i,j+1) / dx;
            
            //bottom neighbour
            term = v_weights(i,j) * dt / sqr(dx);
            float bot_phi = liquid_phi(i,j-1);
            if(bot_phi < 0) {
               matrix.add_to_element(index, index, term);
               matrix.add_to_element(index, index - ni, -term);
            }
            else {
               float theta = fraction_inside(centre_phi, bot_phi);
               if(theta < 0.01f) theta = 0.01f;
               matrix.add_to_element(index, index, term/theta);
            }
            rhs[index] += v_weights(i,j)*v(i,j) / dx;
         }
      }
   }

   //Solve the system using Robert Bridson's incomplete Cholesky PCG solver
   
   double tolerance;
   int iterations;
   bool success = solver.solve(matrix, rhs, pressure, tolerance, iterations);
   if(!success) {
      printf("WARNING: Pressure solve failed!************************************************\n");
   }
   
   //Apply the velocity update
   u_valid.assign(0);
   for(int j = 0; j < u.nj; ++j) for(int i = 1; i < u.ni-1; ++i) {
      int index = i + j*ni;
      if(u_weights(i,j) > 0 && (liquid_phi(i,j) < 0 || liquid_phi(i-1,j) < 0)) {
         float theta = 1;
         if(liquid_phi(i,j) >= 0 || liquid_phi(i-1,j) >= 0)
            theta = fraction_inside(liquid_phi(i-1,j), liquid_phi(i,j));
         if(theta < 0.01f) theta = 0.01f;
         u(i,j) -= dt  * (float)(pressure[index] - pressure[index-1]) / dx / theta; 
         u_valid(i,j) = 1;
      }
      else
         u(i,j) = 0;
   }
   v_valid.assign(0);
   for(int j = 1; j < v.nj-1; ++j) for(int i = 0; i < v.ni; ++i) {
      int index = i + j*ni;
      if(v_weights(i,j) > 0 && (liquid_phi(i,j) < 0 || liquid_phi(i,j-1) < 0)) {
         float theta = 1;
         if(liquid_phi(i,j) >= 0 || liquid_phi(i,j-1) >= 0)
            theta = fraction_inside(liquid_phi(i,j-1), liquid_phi(i,j));
         if(theta < 0.01f) theta = 0.01f;
         v(i,j) -= dt  * (float)(pressure[index] - pressure[index-ni]) / dx / theta; 
         v_valid(i,j) = 1;
      }
      else
         v(i,j) = 0;
   }

}
Esempio n. 24
0
inline double initialPosition(Node& p) {
	return u(p, 0.);
}
Esempio n. 25
0
Vetor produto_vetorial(Vetor v, Vetor w){
	Vetor u(v[1]*w[2] - v[2]*w[1], v[0]*w[2] - v[2]*w[0], v[0]*w[1] - v[1]*w[0]);
	return u;
}
Esempio n. 26
0
inline double G1_D(Node& p, double t) {
	return u(p, t);
}
Esempio n. 27
0
//get and save mutation loci for this individual
void AnimalClass::sampleMyMutation()
{
    if(!G.mapPosDone) G.mkMapPos();

    unsigned numChromosomePair = G.get_num_chrom();

    ///paternal chromsome
    for(unsigned i=0;i<numChromosomePair;i++){
        
        vector<float> mutPos;
        
        unsigned nLoci=G[i].get_num_loci();//num of loci is euqal to num of mapPos
        binomial_distribution<int> Binom(nLoci,G.mutRate);
        int nMut=Binom(randGen);
        
        if(nMut){
            
            uniform_real_distribution<float> u(0,1);
            for (unsigned k=0; k<nMut; k++) {
                unsigned which  = unsigned(nLoci*u(randGen));
                if(which!=nLoci){
                    mutPos.push_back(G[i].MapPos(which));     //get map position of mutation loci
                }
            }
            
            for(unsigned j=0;j<nMut;j++){
            
                if(mutPos[j]!=G[i].chr_length){
                    //unsigned count   =(GenomePat[i].pos < mutPos[j]).count();
                    unsigned count    =(GenomePat[i].pos <= mutPos[j]).count();

                    float   startPos  =GenomePat[i].pos(count-1);

                    float   endPos;

                    if(count!=GenomePat[i].pos.size()){
                        endPos =GenomePat[i].pos(count);

                    }else{
                        endPos =G[i].chr_length;
                    }
                
                    int myOri=GenomePat[i].ori(count-1);

                    GenomePat[i].ori(count-1)=countChromosome;
                
                    countChromosome++;
                
                    mutantInfo *mutant = new mutantInfo();//'new' return the address
                    mutant->whichOri        =myOri;
                    mutant->whichStartPos   =startPos;
                    mutant->whichEndPos     =endPos;
                    mutant->mutPos          =mutPos[j];
                
                    AnimalClass::mutants.push_back(mutant);
                
                }
            }
        }
        
    }
    
    ///maternal
    for(unsigned i=0;i<numChromosomePair;i++){
        
        vector<float> mutPos;
        
        unsigned nLoci=G[i].get_num_loci();
        binomial_distribution<int> Binom(nLoci,G.mutRate);
        int nMut=Binom(randGen);
        
        if(nMut){

            uniform_real_distribution<float> u(0,1);
            for (unsigned k=0; k<nMut; k++) {
                unsigned which  = unsigned(nLoci*u(randGen));
                if(which!=nLoci){
                mutPos.push_back(G[i].MapPos(which));     //get map position of mutation loci
                }
            }
            
            for(unsigned j=0;j<nMut;j++){
                
                if(mutPos[j]!=G[i].chr_length){

                    unsigned count    =(GenomeMat[i].pos <= mutPos[j]).count();

                    float   startPos    =GenomeMat[i].pos(count-1);
                    float   endPos;
                
                    if(count!=GenomeMat[i].pos.size()){
                        endPos =GenomeMat[i].pos(count);
                    }else{
                        endPos =G[i].chr_length;
                    
                    }

                
                    int myOri=GenomeMat[i].ori(count-1);
                
                    GenomeMat[i].ori(count-1)=countChromosome; //change this mutated ori to a new one after previous 2*nFounders ori

                    countChromosome++;

                    mutantInfo *mutant = new mutantInfo();//'new' return the address
                    mutant->whichOri        =myOri;
                    mutant->whichStartPos   =startPos;
                    mutant->whichEndPos     =endPos;
                    mutant->mutPos          =mutPos[j];
                
                    AnimalClass::mutants.push_back(mutant);
                
                }
            }
        }
    }


}
Esempio n. 28
0
//-----------------------------------------------------------------------------------------//
int main()
	{
	hash_table_t *t = CreateHashTable();

	{
	Set( t, u("abc"), 3, u("ABC"), 3 );
	uint8_t tmp[4];
	size_t rs = 0;
	Get( t, u("abc"), 3, tmp, sizeof( tmp ), &rs );
	tmp[rs] = '\0';
	assert( rs == 3 );
	assert( memcmp( tmp, "ABC", rs ) == 0 );
	}
	
	{
	for( size_t i = 0 ; i < 0xffff; ++i )
		{
		assert( Set( t, u( &i ), sizeof( i ), u( &i ), sizeof( i ) ) );
		}
	
	for( size_t i = 0 ; i < 0xffff; ++i )
		{
		size_t n = 0;
		size_t s = 0;
		assert( Get( t, u( &i ), sizeof( i ), u( &n ), sizeof( n ), &s ) == true );
		assert( s == sizeof( i ) );
		assert( memcmp( &i, &n, s ) == 0 );
		}
	}

	{
	for( size_t i = 0 ; i < 0xffff; ++i )
		{
		Set( t, u( &i ), sizeof( i ), u( &i ), sizeof( i ) );
		}
	for( size_t i = 0 ; i < 0xffff; ++i )
		{
		assert( Remove( t, u( &i ), sizeof( i ) ) );
		}
	for( size_t i = 0 ; i < 0xffff; ++i )
		{
		size_t n = 0;
		assert( Get( t, u( &i ), sizeof( i ), u( &n ), sizeof( n ), NULL ) == false );
		}
	}

	{
	assert( Set( t, u( "abc" ), 3, u( "ABC" ), 3 ) );
	assert( Append( t, u( "abc" ), 3, u( "DEF" ), 3 ) );
	uint8_t tmp[6];
	size_t n = 0;
	assert( Get( t, u( "abc" ), 3, tmp, 6, &n ) == true );
	assert( n == 6 );
	assert( memcmp( "ABCDEF", tmp, 6 ) == 0 );
	}

	DeleteHashTable( t );
	
	return 0;
	}
Esempio n. 29
0
void
rollback( const unsigned g, PrivGlobs& globs ) {
    unsigned numX = globs.myX.size(),
             numY = globs.myY.size();

    unsigned numZ = max(numX,numY);

    unsigned i, j;

    REAL dtInv = 1.0/(globs.myTimeline[g+1]-globs.myTimeline[g]);

    vector<vector<REAL> > u(numY, vector<REAL>(numX));   // [numY][numX]
    vector<vector<REAL> > v(numX, vector<REAL>(numY));   // [numX][numY]
    vector<REAL> a(numZ), b(numZ), c(numZ), y(numZ);     // [max(numX,numY)]
    vector<REAL> yy(numZ);  // temporary used in tridag  // [max(numX,numY)]

    //	explicit x
    // parallelizable directly since all reads and writes are independent.
    // Degree of parallelism: numX*numY.
    // TODO: Examine how tiling/shared memory can be used on globs (.myResult).
    for(i=0;i<numX;i++) { //par
        for(j=0;j<numY;j++) { //par
            u[j][i] = dtInv*globs.myResult[i][j];

            if(i > 0) {
              u[j][i] += 0.5*( 0.5*globs.myVarX[i][j]*globs.myDxx[i][0] )
                            * globs.myResult[i-1][j];
            }
            u[j][i]  +=  0.5*( 0.5*globs.myVarX[i][j]*globs.myDxx[i][1] )
                            * globs.myResult[i][j];
            if(i < numX-1) {
              u[j][i] += 0.5*( 0.5*globs.myVarX[i][j]*globs.myDxx[i][2] )
                            * globs.myResult[i+1][j];
            }
        }
    }

    //	explicit y
    // parallelizable directly since all reads and writes are independent.
    // Degree of parallelism: numY*numX.
    // TODO: Examine how tiling/shared memory can be used on globs (.myResult).
    // and u.?
    for(j=0;j<numY;j++) { //par
        for(i=0;i<numX;i++) { //par
            v[i][j] = 0.0;

            if(j > 0) {
              v[i][j] +=  ( 0.5*globs.myVarY[i][j]*globs.myDyy[j][0] )
                         *  globs.myResult[i][j-1];
            }
            v[i][j]  +=   ( 0.5*globs.myVarY[i][j]*globs.myDyy[j][1] )
                         *  globs.myResult[i][j];
            if(j < numY-1) {
              v[i][j] +=  ( 0.5*globs.myVarY[i][j]*globs.myDyy[j][2] )
                         *  globs.myResult[i][j+1];
            }
            u[j][i] += v[i][j];
        }
    }

    //	implicit x
    // ASSUMING tridag is independent.
    // parallelizable directly since all reads and writes are independent.
    // Degree of parallelism: numY*numX.
    // TODO: Examine tridag
    for(j=0;j<numY;j++) { // par
        // parallelizable via loop distribution / array expansion.
        for(i=0;i<numX;i++) {  // par // here a, b,c should have size [numX]
            a[i] =		 - 0.5*(0.5*globs.myVarX[i][j]*globs.myDxx[i][0]);
            b[i] = dtInv - 0.5*(0.5*globs.myVarX[i][j]*globs.myDxx[i][1]);
            c[i] =		 - 0.5*(0.5*globs.myVarX[i][j]*globs.myDxx[i][2]);
        }
        // here yy should have size [numX]
        tridag(a,b,c,u[j],numX,u[j],yy);
    }

    //	implicit y
    // ASSUMING tridag is independent.
    // parallelizable directly since all reads and writes are independent.
    // Degree of parallelism: numY*numX.
    // TODO: Examine tridag
    for(i=0;i<numX;i++) { // par
        // parallelizable via loop distribution / array expansion.
        for(j=0;j<numY;j++) { // par  // here a, b, c should have size [numY]
            a[j] =		 - 0.5*(0.5*globs.myVarY[i][j]*globs.myDyy[j][0]);
            b[j] = dtInv - 0.5*(0.5*globs.myVarY[i][j]*globs.myDyy[j][1]);
            c[j] =		 - 0.5*(0.5*globs.myVarY[i][j]*globs.myDyy[j][2]);
        }

        for(j=0;j<numY;j++)
            y[j] = dtInv*u[j][i] - 0.5*v[i][j];

        // here yy should have size [numY]
        tridag(a,b,c,y,numY,globs.myResult[i],yy);
    }
}
Esempio n. 30
0
unsigned int cubicSolver(double * ce, double *roots)
//cubic equation solver
// x^3 + ce[0] x^2 + ce[1] x + ce[2] = 0
{
    // depressed cubic, Tschirnhaus transformation, x= t - b/(3a)
    // t^3 + p t +q =0
    unsigned int ret=0;
    double shift=(1./3)*ce[0];
    double p=ce[1] -shift*ce[0];
    double q=ce[0]*( (2./27)*ce[0]*ce[0]-(1./3)*ce[1])+ce[2];
    //Cardano's method,
    //	t=u+v
    //	u^3 + v^3 + ( 3 uv + p ) (u+v) + q =0
    //	select 3uv + p =0, then,
    //	u^3 + v^3 = -q
    //	u^3 v^3 = - p^3/27
    //	so, u^3 and v^3 are roots of equation,
    //	z^2 + q z - p^3/27 = 0
    //	and u^3,v^3 are,
    //		-q/2 \pm sqrt(q^2/4 + p^3/27)
    //	discriminant= q^2/4 + p^3/27
    std::cout<<"cubicSolver:: p="<<p<<"\tq="<<q<<std::endl;
    double discriminant= (1./27)*p*p*p+(1./4)*q*q;
    if ( fabs(p)< 1.0e-75) {
        ret=1;
        *roots=(q>0)?-pow(q,(1./3)):pow(-q,(1./3));
        *roots -= shift;
        return ret;
    }
    std::cout<<"cubicSolver:: discriminant="<<discriminant<<std::endl;
    if(discriminant>0) {
        double ce2[2]= {q, -1./27*p*p*p},u3[2];
        ret=quadraticSolver(ce2,u3);
        if (! ret ) { //should not happen
            std::cerr<<"cubicSolver::Error cubicSolver("<<ce[0]<<' '<<ce[1]<<' '<<ce[2]<<")\n";
        }
        ret=1;
        double u,v;
        u= (q<=0) ? pow(u3[0], 1./3): -pow(-u3[1],1./3);
        //u=(q<=0)?pow(-0.5*q+sqrt(discriminant),1./3):-pow(0.5*q+sqrt(discriminant),1./3);
        v=(-1./3)*p/u;
        std::cout<<"cubicSolver:: u="<<u<<"\tv="<<v<<std::endl;
        std::cout<<"cubicSolver:: u^3="<<u*u*u<<"\tv^3="<<v*v*v<<std::endl;
        *roots=u+v - shift;
        return ret;
    }
    ret=3;
    std::complex<double> u(q,0),rt[3];
    u=pow(-0.5*u-sqrt(0.25*u*u+p*p*p/27),1./3);
    rt[0]=u-p/(3.*u)-shift;
    std::complex<double> w(-0.5,sqrt(3.)/2);
    rt[1]=u*w-p/(3.*u*w)-shift;
    rt[2]=u/w-p*w/(3.*u)-shift;
//	std::cout<<"Roots:\n";
//	std::cout<<rt[0]<<std::endl;
//	std::cout<<rt[1]<<std::endl;
//	std::cout<<rt[2]<<std::endl;

    roots[0]=rt[0].real();
    roots[1]=rt[1].real();
    roots[2]=rt[2].real();
    return ret;
}