static void do_complete(void* owner, operation* base,
      const asio::error_code& result_ec,
      std::size_t /*bytes_transferred*/)
  {
    asio::error_code ec(result_ec);

    // Take ownership of the operation object.
    win_iocp_socket_accept_op* o(static_cast<win_iocp_socket_accept_op*>(base));
    ptr p = { asio::detail::addressof(o->handler_), o, o };
    handler_work<Handler> w(o->handler_);

    if (owner)
    {
      typename Protocol::endpoint peer_endpoint;
      std::size_t addr_len = peer_endpoint.capacity();
      socket_ops::complete_iocp_accept(o->socket_,
          o->output_buffer(), o->address_length(),
          peer_endpoint.data(), &addr_len,
          o->new_socket_.get(), ec);

      // Restart the accept operation if we got the connection_aborted error
      // and the enable_connection_aborted socket option is not set.
      if (ec == asio::error::connection_aborted
          && !o->enable_connection_aborted_)
      {
        o->reset();
        o->socket_service_.restart_accept_op(o->socket_,
            o->new_socket_, o->protocol_.family(),
            o->protocol_.type(), o->protocol_.protocol(),
            o->output_buffer(), o->address_length(), o);
        p.v = p.p = 0;
        return;
      }

      // If the socket was successfully accepted, transfer ownership of the
      // socket to the peer object.
      if (!ec)
      {
        o->peer_.assign(o->protocol_,
            typename Socket::native_handle_type(
              o->new_socket_.get(), peer_endpoint), ec);
        if (!ec)
          o->new_socket_.release();
      }

      // Pass endpoint back to caller.
      if (o->peer_endpoint_)
        *o->peer_endpoint_ = peer_endpoint;
    }

    ASIO_HANDLER_COMPLETION((o));

    // Make a copy of the handler so that the memory can be deallocated before
    // the upcall is made. Even if we're not about to make an upcall, a
    // sub-object of the handler may be the true owner of the memory associated
    // with the handler. Consequently, a local copy of the handler is required
    // to ensure that any owning sub-object remains valid until after we have
    // deallocated the memory here.
    detail::binder1<Handler, asio::error_code>
      handler(o->handler_, ec);
    p.h = asio::detail::addressof(handler.handler_);
    p.reset();

    // Make the upcall if required.
    if (owner)
    {
      fenced_block b(fenced_block::half);
      ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_));
      w.complete(handler, handler.handler_);
      ASIO_HANDLER_INVOCATION_END;
    }
  }
Beispiel #2
0
void Map::CreateMap( vector<vector<Tile*> >& tiles, char* tmxFile, int numSpritesRow )
{
    //Clear out all the tiles
    backTiles.clear();
    backTiles.shrink_to_fit();

	// open the XML map file
	TiXmlDocument xmlFile( tmxFile );
	if(xmlFile.LoadFile()) {
		cout << "Successfully opened the XML map file.\n";
	} else {
		cout << "ERROR: Unable to open the XML map file.\n";
	}

	// parse the XML
	// this code assumes that the layers exist in the XML file in this order: sprites, then collision, then ladders.
	mapWidth = atoi(xmlFile.FirstChildElement("map")->Attribute("width"));
	mapHeight = atoi(xmlFile.FirstChildElement("map")->Attribute("height"));
	int tileSize = atoi(xmlFile.FirstChildElement("map")->Attribute("tilewidth"));
	string tileImageFilename = xmlFile.FirstChildElement("map")->FirstChildElement("tileset")->FirstChildElement("image")->Attribute("source");
	string spriteLayer = xmlFile.FirstChildElement("map")->FirstChildElement("layer")->FirstChildElement("data")->GetText();
	string collisionLayer = xmlFile.FirstChildElement("map")->FirstChildElement("layer")->NextSibling()->FirstChildElement("data")->GetText();
	string ladderLayer = xmlFile.FirstChildElement("map")->FirstChildElement("layer")->NextSibling()->NextSibling()->FirstChildElement("data")->GetText();
	string enemiesLayer = xmlFile.FirstChildElement("map")->FirstChildElement("layer")->NextSibling()->NextSibling()->NextSibling()->FirstChildElement("data")->GetText();

	// convert the CSV strings into vectors of ints
	// these ints are the sprite numbers for each tile. 0 would be the first sprite in the first row, etc.
	replace(spriteLayer.begin(), spriteLayer.end(), ',', ' '); // convert CSV to space-delimited
	stringstream a(spriteLayer);
	vector<int> spriteInts;
	string temp1;
	while(a >> temp1) {
		spriteInts.push_back(atoi(temp1.c_str()));
	}
	replace(collisionLayer.begin(), collisionLayer.end(), ',', ' '); // convert CSV to space-delimited
	stringstream b(collisionLayer);
	vector<int> collisionInts;
	string temp2;
	while(b >> temp2) {
		collisionInts.push_back(atoi(temp2.c_str()));
	}
	replace(ladderLayer.begin(), ladderLayer.end(), ',', ' '); // convert CSV to space-delimited
	stringstream c(ladderLayer);
	vector<int> ladderInts;
	string temp3;
	while(c >> temp3) {
		ladderInts.push_back(atoi(temp3.c_str()));
	}
	replace(enemiesLayer.begin(), enemiesLayer.end(), ',', ' '); // convert CSV to space-delimited
	stringstream d(enemiesLayer);
	vector<int> enemyInts;
	string temp4;
	while(d >> temp4) {
		enemyInts.push_back(atoi(temp4.c_str()));
	}


	// generate the vectors of tiles
	int i = 0;	
	for(int row = 0; row < mapHeight; row++) {
		vector<Tile*> currentRow;
		for(int column = 0; column < mapWidth; column++) {
			int xPosition = (i % mapWidth) * tileSize;
			int yPosition = (i / mapWidth) * tileSize;
			bool collision = collisionInts[i]; // non-zero sprite number indicates collision region
			bool ladder = ladderInts[i]; // non-zero sprite number indicates ladder region
            Game_Enemies enemy;
			if(enemyInts[i] == 377)
				enemy = CORGI;
			else if(enemyInts[i] == 378)
				enemy = HUSKY;
			else if(enemyInts[i] == 379)
				enemy = GREYHOUND;
			else if(enemyInts[i] == 380)
				enemy = SHIBA;
			else if(enemyInts[i] == 381)
				enemy = BULLDOG;
			else
				enemy = NONE;
			string spriteFilePath = tileImageFilename;
			int spritesPerRow = numSpritesRow;
			int spriteXoffset = ((spriteInts[i] - 1) % spritesPerRow) * tileSize;
			int spriteYoffset = ((spriteInts[i] - 1) / spritesPerRow) * tileSize;
			i++;
			currentRow.push_back( new Tile( xPosition, yPosition, collision, ladder, enemy, spriteXoffset, spriteYoffset ) );
		}
		tiles.push_back(currentRow);

	}

	// for debugging: examine the contents of a tile
	cout << "There are " << tiles.size() << " rows, and " << tiles[0].size() << " columns.\n\n";
	int tileToExamine = 1;
	cout << "Details for tile #" << tileToExamine << ":\n\n";
    cout << "xPosition =       " << tiles[tileToExamine / mapWidth][tileToExamine % mapWidth]->GetDestination().x << "\n";
	cout << "yPosition =       " << tiles[tileToExamine / mapWidth][tileToExamine % mapWidth]->GetDestination().y << "\n";
    cout << "collision =       " << tiles[tileToExamine / mapWidth][tileToExamine % mapWidth]->GetCollision() << "\n";
    cout << "ladder =          " << tiles[tileToExamine / mapWidth][tileToExamine % mapWidth]->GetIsLadder() << "\n";
    cout << "enemy =           " << tiles[tileToExamine / mapWidth][tileToExamine % mapWidth]->GetEnemy() << "\n";
	//cout << "spriteFilePath =  " <<  << "\n";
    cout << "spriteXoffset =   " << tiles[tileToExamine / mapWidth][tileToExamine % mapWidth]->GetClip().x << "\n";
    cout << "spriteYoffset =   " << tiles[tileToExamine / mapWidth][tileToExamine % mapWidth]->GetClip().y << "\n";
	cout << "\nDone.\n";

    
    //Get pixels width and height of the map also
    mapPixWidth = mapWidth * TILE_SIZE;
    mapPixHeight = mapHeight * TILE_SIZE;
}
Beispiel #3
0
void StatCounter::record(time_t time, double value, double valueSq, double min, double max, size_t cnt)
{
    if(debugRecord.enabled())
    {
        LogDebug << "record" << value << valueSq << min << max << cnt << time;
    }
    else
    {
        LogSpam << "StatCounter::record thread_id " << boost::this_thread::get_id();
    }
    ++dequeueRecords_;
    --queueLenRecords_;

    time_t nowTime;
    if(isCollated_)
    {
        if(time > istat::istattime(&nowTime) + collationInterval_)
        {
            ++recordsFromTheFuture_;
            if (debugRejectedCounters)
            {
                LogWarning << "StatCounter::record rejected counter from the future: " << time << " > " << nowTime << ": " <<
                    counters_[0].file->header().name;
            }
            return;
        }
        if(time < collations_[0].time)
        {
            ++recordsFromThePast_;
            if (debugRejectedCounters)
            {
                LogWarning << "StatCounter::record rejected counter from the past: " << time
                           << " < " << collations_[0].time
                           << " < " << collations_[1].time
                           << " < " << collations_[2].time
                           << ": " <<  counters_[0].file->header().name;
            }
            return;
        }
    }
    else
    {
        if(time > istat::istattime(&nowTime) + time_t(60))
        {
            if (debugRejectedCounters)
            {
                LogWarning << "StatCounter::record rejected counter from the future: " << time << " > " << nowTime << ": " <<
                    counters_[0].file->header().name;
            }
            ++recordsFromTheFuture_;
            return;
        }
    }

    if(isCollated_)
    {
        time -= time % collationInterval_;

        size_t i = findCollationIndex(time);
        // No matching bucket candidate in time range. Shift ahead!
        if(i == BUCKETS_PER_COLLATION_WINDOW)
        {
            if(collations_[0].time == 0)
            {
                for(size_t i = 0; i != BUCKETS_PER_COLLATION_WINDOW; ++i)
                {
                    collations_[(BUCKETS_PER_COLLATION_WINDOW - 1) - i] = CollationInfo(time - (i * collationInterval_));
                }
            }
            else
            {
               maybeShiftCollated(time);
            }
            i = findCollationIndex(time);
        }

        CollationInfo &collation(collations_[i]);
        istat::Bucket &bucket(collation.bucket);
        bucket.collatedUpdate(value / double(collationInterval_), time);
        ++collation.writes;

        // Only update the statfile on power-of-two updates.
        if((collation.writes & (collation.writes - 1)) == 0)
        {
            counters_.begin()->file->updateBucket(bucket);
        }
    }
    else
    {
        // Don't record zero-sample buckets.
        if(cnt == 0)
        {
            ++recordsRejected_;
            if (debugRejectedCounters)
            {
                LogWarning << "StatCounter::record rejected counter with 0 count: " <<
                    counters_[0].file->header().name;
            }
            return;
        }
        double avg = value / double(cnt);
        // Ensure the value ranges are sensible, or reject them.
        // We allow a small amount of epsilon (0.01%) here before rejecting counters due to double vs. float
        // conversion in Buckets transferred from istatd agents to the master
        if (min > (max + fabs(max) * 0.0001) || (avg + fabs(avg) * 0.0001) < min || avg > (max + fabs(max) * 0.0001))
        {
            if (debugRejectedCounters)
            {
                LogWarning << "StatCounter::record rejected counter with bad min/avg/max: " <<
                    counters_[0].file->header().name << min << avg << "(" << value << "/" << cnt << ")" << max;
            }
            ++recordsRejected_;
            return;
        }

        istat::Bucket b(value, float(valueSq), float(min), float(max), int(cnt), time);
        for(std::vector<OneCounter>::iterator
            ptr(counters_.begin()),
            end(counters_.end());
            ptr != end;
            ++ptr)
        {
            ptr->file->updateBucket(b);
        }
    }
}
Beispiel #4
0
int
main(int argc, char** argv)
{
	{
		// a * b' = C ; a' * b = d
		
		boost::numeric::ublas::vector<double> a(3);
		for (std::size_t i = 0; i < a.size(); ++i) a(i) = i;
		std::cout << "a=" << a << std::endl;
		
		boost::numeric::ublas::vector<double> b(3);
		for (std::size_t i = 0; i < b.size(); ++i) b(i) = i;
		std::cout << "b=" << b << std::endl;
		
		boost::numeric::ublas::matrix<double, boost::numeric::ublas::column_major> c(3, 3);
		boost::numeric::bindings::blas::gemm(
			boost::numeric::bindings::traits::NO_TRANSPOSE,
			boost::numeric::bindings::traits::TRANSPOSE,
			1.0, a, b, 0.0, c
		);
		std::cout << "c=" << c << std::endl;
		
		boost::numeric::ublas::vector<double> d(1);
		boost::numeric::bindings::blas::gemm(
			boost::numeric::bindings::traits::TRANSPOSE,
			boost::numeric::bindings::traits::NO_TRANSPOSE,
			1.0, a, b, 0.0, d
		);
		std::cout << "d=" << d << std::endl;
	}
	
	std::cout << std::endl;
	
	{
		// a * b' = C ; a' * b = d
		
		std::vector<double> a(3);
		for (std::size_t i = 0; i < a.size(); ++i) a[i] = i;
		std::cout << "a=[" << a.size() << "](";
		for (std::size_t i = 0; i < a.size(); ++i) std::cout << (i > 0 ? "," : "") << a[i];
		std::cout << ")" << std::endl;
		
		std::valarray<double> b(3);
		for (std::size_t i = 0; i < b.size(); ++i) b[i] = i;
		std::cout << "b=[" << b.size() << "](";
		for (std::size_t i = 0; i < b.size(); ++i) std::cout << (i > 0 ? "," : "") << b[i];
		std::cout << ")" << std::endl;
		
		boost::numeric::ublas::matrix<double, boost::numeric::ublas::column_major> c(3, 3);
		boost::numeric::bindings::blas::gemm(
			boost::numeric::bindings::traits::NO_TRANSPOSE,
			boost::numeric::bindings::traits::TRANSPOSE,
			1.0, a, b, 0.0, c
		);
		std::cout << "c=" << c << std::endl;
		
		std::vector<double> d(1);
		boost::numeric::bindings::blas::gemm(
			boost::numeric::bindings::traits::TRANSPOSE,
			boost::numeric::bindings::traits::NO_TRANSPOSE,
			1.0, a, b, 0.0, d
		);
		std::cout << "d=[" << d.size() << "](";
		for (std::size_t i = 0; i < d.size(); ++i) std::cout << (i > 0 ? "," : "") << d[i];
		std::cout << ")" << std::endl;
	}
	
	std::cout << std::endl;
	
	{
		// a * b' = C ; a' * b = d
		
		double a[3];
		for (std::size_t i = 0; i < 3; ++i) a[i] = i;
		std::cout << "a=[" << 3 << "](";
		for (std::size_t i = 0; i < 3; ++i) std::cout << (i > 0 ? "," : "") << a[i];
		std::cout << ")" << std::endl;
		
		std::vector<double> b(3);
		for (std::size_t i = 0; i < b.size(); ++i) b[i] = i;
		std::cout << "b=[" << b.size() << "](";
		for (std::size_t i = 0; i < b.size(); ++i) std::cout << (i > 0 ? "," : "") << b[i];
		std::cout << ")" << std::endl;
		
		boost::numeric::ublas::matrix<double, boost::numeric::ublas::column_major> c(3, 3);
		boost::numeric::bindings::blas::gemm(
			boost::numeric::bindings::traits::NO_TRANSPOSE,
			boost::numeric::bindings::traits::TRANSPOSE,
			1.0, a, b, 0.0, c
		);
		std::cout << "c=" << c << std::endl;
		
		std::valarray<double> d(1);
		boost::numeric::bindings::blas::gemm(
			boost::numeric::bindings::traits::TRANSPOSE,
			boost::numeric::bindings::traits::NO_TRANSPOSE,
			1.0, a, b, 0.0, d
		);
		std::cout << "d=[" << d.size() << "](";
		for (std::size_t i = 0; i < d.size(); ++i) std::cout << (i > 0 ? "," : "") << d[i];
		std::cout << ")" << std::endl;
	}
	
	return 0;
}
    void HaystackAccessMethod::searchCommand(OperationContext* txn, Collection* collection,
                                             const BSONObj& nearObj, double maxDistance,
                                             const BSONObj& search, BSONObjBuilder* result,
                                             unsigned limit) {
        Timer t;

        LOG(1) << "SEARCH near:" << nearObj << " maxDistance:" << maxDistance
               << " search: " << search << endl;
        int x, y;
        {
            BSONObjIterator i(nearObj);
            x = ExpressionKeysPrivate::hashHaystackElement(i.next(), _bucketSize);
            y = ExpressionKeysPrivate::hashHaystackElement(i.next(), _bucketSize);
        }
        int scale = static_cast<int>(ceil(maxDistance / _bucketSize));

        GeoHaystackSearchHopper hopper(nearObj, maxDistance, limit, _geoField, collection);

        long long btreeMatches = 0;

        for (int a = -scale; a <= scale && !hopper.limitReached(); ++a) {
            for (int b = -scale; b <= scale && !hopper.limitReached(); ++b) {
                BSONObjBuilder bb;
                bb.append("", ExpressionKeysPrivate::makeHaystackString(x + a, y + b));

                for (unsigned i = 0; i < _otherFields.size(); i++) {
                    // See if the non-geo field we're indexing on is in the provided search term.
                    BSONElement e = search.getFieldDotted(_otherFields[i]);
                    if (e.eoo())
                        bb.appendNull("");
                    else
                        bb.appendAs(e, "");
                }

                BSONObj key = bb.obj();

                unordered_set<DiskLoc, DiskLoc::Hasher> thisPass;


                scoped_ptr<Runner> runner(InternalPlanner::indexScan(txn,  collection,
                                                                     _descriptor, key, key, true));
                Runner::RunnerState state;
                DiskLoc loc;
                while (Runner::RUNNER_ADVANCED == (state = runner->getNext(NULL, &loc))) {
                    if (hopper.limitReached()) { break; }
                    pair<unordered_set<DiskLoc, DiskLoc::Hasher>::iterator, bool> p
                        = thisPass.insert(loc);
                    // If a new element was inserted (haven't seen the DiskLoc before), p.second
                    // is true.
                    if (p.second) {
                        hopper.consider(loc);
                        btreeMatches++;
                    }
                }
            }
        }

        BSONArrayBuilder arr(result->subarrayStart("results"));
        int num = hopper.appendResultsTo(&arr);
        arr.done();

        {
            BSONObjBuilder b(result->subobjStart("stats"));
            b.append("time", t.millis());
            b.appendNumber("btreeMatches", btreeMatches);
            b.append("n", num);
            b.done();
        }
    }
Beispiel #6
0
void ComplexMesh::ComputeConstrainedParameterization()
{
    const float Lambda = 1.0f;

    SparseMatrix<double> M(_Vertices.Length() * 2);
    Vector<double> x(_Vertices.Length() * 2), b(_Vertices.Length() * 2);
    
    for(UINT VertexIndex = 0; VertexIndex < _Vertices.Length(); VertexIndex++)
    {
        Vertex &CurVertex = _Vertices[VertexIndex];
        if(CurVertex.Boundary())
        {
            M.PushDiagonalElement(VertexIndex * 2 + 0, 1.0f);
            M.PushDiagonalElement(VertexIndex * 2 + 1, 1.0f);
        }
        else
        {
            for(UINT EdgeIndex = 0; EdgeIndex < CurVertex.Vertices().Length(); EdgeIndex++)
            {
                Vertex &OtherVertex = *(CurVertex.Vertices()[EdgeIndex]);
                FullEdge &CurEdge = CurVertex.GetSharedEdge(OtherVertex);
                double ConstantFactor = Lambda * CurEdge.GetCotanTerm();
                Assert(ConstantFactor == ConstantFactor, "ConstantFactor invalid");
                M.PushDiagonalElement(VertexIndex * 2 + 0, -ConstantFactor);
                M.PushDiagonalElement(VertexIndex * 2 + 1, -ConstantFactor);
                M.PushElement(VertexIndex * 2 + 0, OtherVertex.Index() * 2 + 0, ConstantFactor);
                M.PushElement(VertexIndex * 2 + 1, OtherVertex.Index() * 2 + 1, ConstantFactor);
            }
        }
    }

    for(UINT VertexIndex = 0; VertexIndex < _Vertices.Length(); VertexIndex++)
    {
        Vertex &CurVertex = _Vertices[VertexIndex];
        if(CurVertex.Boundary())
        {
            x[VertexIndex * 2 + 0] = CurVertex.TexCoords().x;
            x[VertexIndex * 2 + 1] = CurVertex.TexCoords().y;
            b[VertexIndex * 2 + 0] = CurVertex.TexCoords().x;
            b[VertexIndex * 2 + 1] = CurVertex.TexCoords().y;
        }
        else
        {
            //x[VertexIndex * 2 + 0] = CurVertex.Pos().x;
            //x[VertexIndex * 2 + 1] = CurVertex.Pos().y;
            x[VertexIndex * 2 + 0] = pmrnd() * 0.01f;
            x[VertexIndex * 2 + 1] = pmrnd() * 0.01f;
            b[VertexIndex * 2 + 0] = 0.0f;
            b[VertexIndex * 2 + 1] = 0.0f;
        }
    }

    BiCGLinearSolver<double> Solver;
    //TaucsSymmetricLinearSolver Solver;
    Solver.LoadMatrix(&M);
    Solver.Factor();
    Solver.SetParamaters(1000, 1e-6);

    Solver.Solve(x, b);
    Console::WriteLine(Solver.GetOutputString());
    double Error = Solver.ComputeError(x, b);
    Console::WriteLine(String("Parameterization error: ") + String(Error));
    for(UINT VertexIndex = 0; VertexIndex < _Vertices.Length(); VertexIndex++)
    {
        Vertex &CurVertex = _Vertices[VertexIndex];
        if(!CurVertex.Boundary())
        {
            CurVertex.TexCoords().x = float(x[VertexIndex * 2 + 0]);
            CurVertex.TexCoords().y = float(x[VertexIndex * 2 + 1]);
        }
        //Console::WriteLine(String(CurVertex.TexCoords().x));
    }
}
Beispiel #7
0
PointPath CMapSearch::DoSearch(int y1, int x1, int y2, int x2)
{
    PointPath ans;
    CoorType a(y1, x1), b(y2, x2), c, d;

    //如果是直线
    if(a.x == b.x || a.y == b.y)
    {
        if(Abled(a, b, true, true))
        {
            ans.bExist = true;
            ans.Num = 2;
            ans.Points[0] = a, ans.Points[1] = b;
            return ans;
        }
    }

    //如果有一个转折点
    for(int i = 0; i < 2; i++)
    {
        if(i == 0) c.Set(a.y, b.x);
        else c.Set(b.y, a.x);

        //如果转折点合法
        if(Map[c.y][c.x] == -1)
            if(Abled(a, c, true) && Abled(c, b, false, true))
            {
                ans.bExist = true;
                ans.Num = 3;
                ans.Points[0] = a, ans.Points[1] = c, ans.Points[2] = b;
                return ans;
            }
    }

    //如果有两个转折点
    for(int i = 0; i < 4; i++)
    {
        //重置转折点1
        c.Set(y1, x1);
        c += dir[i];

        //如果此转折点合法
        while(c.isIll() && Map[c.y][c.x] == -1)
        {
            if(Abled(a, c, true))
            {
                //设置转折点2
                switch(i) {
                    case 0: 
                    case 1: d.Set(b.y, c.x); break;
                    case 2: 
                    case 3: d.Set(c.y, b.x); break;
                    default: break;
                }

                //如果转折点2合法
                if(Map[d.y][d.x] == -1)
                {
                    if(Abled(c, d) && Abled(d, b, false, true))
                    {
                        ans.bExist = true;
                        ans.Num = 4;
                        ans.Points[0] = a;
                        ans.Points[1] = c;
                        ans.Points[2] = d;
                        ans.Points[3] = b;
                        return ans;
                    }
                }
            }
            else break;

            c += dir[i];
        }
    }

    ans.bExist = false;
    return ans;
}
Beispiel #8
0
/*******************************************************************************
 * For each run, the input filename must be given on the command line.  In all *
 * cases, the command line is:                                                 *
 *                                                                             *
 *    executable <input file name>                                             *
 *                                                                             *
 *******************************************************************************/
bool
run_example(int argc, char* argv[])
{
    // Initialize PETSc, MPI, and SAMRAI.
    PetscInitialize(&argc, &argv, NULL, NULL);
    SAMRAI_MPI::setCommunicator(PETSC_COMM_WORLD);
    SAMRAI_MPI::setCallAbortInSerialInsteadOfExit();
    SAMRAIManager::startup();

    { // cleanup dynamically allocated objects prior to shutdown

        // Parse command line options, set some standard options from the input
        // file, and enable file logging.
        Pointer<AppInitializer> app_initializer = new AppInitializer(argc, argv, "cc_poisson.log");
        Pointer<Database> input_db = app_initializer->getInputDatabase();

        // Create major algorithm and data objects that comprise the
        // application.  These objects are configured from the input database.
        Pointer<CartesianGridGeometry<NDIM> > grid_geometry = new CartesianGridGeometry<NDIM>(
            "CartesianGeometry", app_initializer->getComponentDatabase("CartesianGeometry"));
        Pointer<PatchHierarchy<NDIM> > patch_hierarchy = new PatchHierarchy<NDIM>("PatchHierarchy", grid_geometry);
        Pointer<StandardTagAndInitialize<NDIM> > error_detector = new StandardTagAndInitialize<NDIM>(
            "StandardTagAndInitialize", NULL, app_initializer->getComponentDatabase("StandardTagAndInitialize"));
        Pointer<BergerRigoutsos<NDIM> > box_generator = new BergerRigoutsos<NDIM>();
        Pointer<LoadBalancer<NDIM> > load_balancer =
            new LoadBalancer<NDIM>("LoadBalancer", app_initializer->getComponentDatabase("LoadBalancer"));
        Pointer<GriddingAlgorithm<NDIM> > gridding_algorithm =
            new GriddingAlgorithm<NDIM>("GriddingAlgorithm",
                                        app_initializer->getComponentDatabase("GriddingAlgorithm"),
                                        error_detector,
                                        box_generator,
                                        load_balancer);

        // Initialize the AMR patch hierarchy.
        gridding_algorithm->makeCoarsestLevel(patch_hierarchy, 0.0);
        int tag_buffer = 1;
        int level_number = 0;
        bool done = false;
        while (!done && (gridding_algorithm->levelCanBeRefined(level_number)))
        {
            gridding_algorithm->makeFinerLevel(patch_hierarchy, 0.0, 0.0, tag_buffer);
            done = !patch_hierarchy->finerLevelExists(level_number);
            ++level_number;
        }

        // Create cell-centered data and extrapolate that data at physical
        // boundaries to obtain ghost cell values.
        VariableDatabase<NDIM>* var_db = VariableDatabase<NDIM>::getDatabase();
        Pointer<VariableContext> context = var_db->getContext("CONTEXT");
        Pointer<CellVariable<NDIM, double> > var = new CellVariable<NDIM, double>("v");
        const int gcw = 4;
        const int idx = var_db->registerVariableAndContext(var, context, gcw);
        for (int ln = 0; ln <= patch_hierarchy->getFinestLevelNumber(); ++ln)
        {
            Pointer<PatchLevel<NDIM> > level = patch_hierarchy->getPatchLevel(ln);
            level->allocatePatchData(idx);
            for (PatchLevel<NDIM>::Iterator p(level); p; p++)
            {
                Pointer<Patch<NDIM> > patch = level->getPatch(p());
                const Box<NDIM>& patch_box = patch->getBox();
                const Index<NDIM>& patch_lower = patch_box.lower();
                Pointer<CellData<NDIM, double> > data = patch->getPatchData(idx);
                for (Box<NDIM>::Iterator b(patch_box); b; b++)
                {
                    const Index<NDIM>& i = b();
                    (*data)(i) = 0;
                    for (unsigned int d = 0; d < NDIM; ++d)
                    {
                        (*data)(i) += 4 * (d + 1) * (d + 1) * i(d);
                    }
                }

                pout << "level number = " << ln << "\n";
                pout << "patch_box = " << patch_box << "\n";
                pout << "\n";

                plog << "interior data:\n";
                data->print(data->getBox());
                plog << "\n";

                CartExtrapPhysBdryOp constant_fill_op(idx, "CONSTANT");
                constant_fill_op.setPhysicalBoundaryConditions(*patch, 0.0, data->getGhostCellWidth());
                plog << "constant extrapolated ghost data:\n";
                data->print(data->getGhostBox());
                plog << "\n";

                CartExtrapPhysBdryOp linear_fill_op(idx, "LINEAR");
                linear_fill_op.setPhysicalBoundaryConditions(*patch, 0.0, data->getGhostCellWidth());
                plog << "linear extrapolated ghost data:\n";
                data->print(data->getGhostBox());
                plog << "\n";

                bool warning = false;
                for (Box<NDIM>::Iterator b(data->getGhostBox()); b; b++)
                {
                    const Index<NDIM>& i = b();
                    double val = 0;
                    for (int d = 0; d < NDIM; ++d)
                    {
                        val += 4 * (d + 1) * (d + 1) * i(d);
                    }

                    if (!MathUtilities<double>::equalEps(val, (*data)(i)))
                    {
                        warning = true;
                        pout << "warning: value at location " << i << " is not correct\n";
                        pout << "  expected value = " << val << "   computed value = " << (*data)(i) << "\n";
                    }
                }

                if (!warning)
                {
                    pout << "linearly extrapolated boundary data appears to be correct.\n";
                }
                else
                {
                    pout << "possible errors encountered in linearly extrapolated boundary data.\n";
                }

                pout << "checking robin bc handling . . .\n";

                Pointer<CartesianPatchGeometry<NDIM> > pgeom = patch->getPatchGeometry();
                const double* const x_lower = pgeom->getXLower();
                const double* const x_upper = grid_geometry->getXUpper();
                const double* const dx = pgeom->getDx();
                const double shift = 3.14159;
                for (Box<NDIM>::Iterator b(patch_box); b; b++)
                {
                    const Index<NDIM>& i = b();
                    double X[NDIM];
                    for (unsigned int d = 0; d < NDIM; ++d)
                    {
                        X[d] = x_lower[d] + dx[d] * (static_cast<double>(i(d) - patch_lower(d)) + 0.5);
                    }
                    (*data)(i) = 2.0 * X[NDIM - 1] + shift;
                }

                plog << "interior data:\n";
                data->print(data->getBox());
                plog << "\n";

                LocationIndexRobinBcCoefs<NDIM> dirichlet_bc_coef("dirichlet_bc_coef", NULL);
                for (unsigned int d = 0; d < NDIM - 1; ++d)
                {
                    dirichlet_bc_coef.setBoundarySlope(2 * d, 0.0);
                    dirichlet_bc_coef.setBoundarySlope(2 * d + 1, 0.0);
                }
                dirichlet_bc_coef.setBoundaryValue(2 * (NDIM - 1), shift);
                dirichlet_bc_coef.setBoundaryValue(2 * (NDIM - 1) + 1, 2.0 * x_upper[NDIM - 1] + shift);

                CartCellRobinPhysBdryOp dirichlet_bc_fill_op(idx, &dirichlet_bc_coef);
                dirichlet_bc_fill_op.setPhysicalBoundaryConditions(*patch, 0.0, data->getGhostCellWidth());
                plog << "extrapolated ghost data:\n";
                data->print(data->getGhostBox());
                plog << "\n";

                warning = false;
                for (Box<NDIM>::Iterator b(data->getGhostBox()); b; b++)
                {
                    const Index<NDIM>& i = b();
                    double X[NDIM];
                    for (unsigned int d = 0; d < NDIM; ++d)
                    {
                        X[d] = x_lower[d] + dx[d] * (static_cast<double>(i(d) - patch_lower(d)) + 0.5);
                    }
                    double val = 2.0 * X[NDIM - 1] + shift;

                    if (!MathUtilities<double>::equalEps(val, (*data)(i)))
                    {
                        warning = true;
                        pout << "warning: value at location " << i << " is not correct\n";
                        pout << "  expected value = " << val << "   computed value = " << (*data)(i) << "\n";
                    }
                }

                if (!warning)
                {
                    pout << "dirichlet boundary data appears to be correct.\n";
                }
                else
                {
                    pout << "possible errors encountered in extrapolated dirichlet boundary data.\n";
                }

                LocationIndexRobinBcCoefs<NDIM> neumann_bc_coef("neumann_bc_coef", NULL);
                for (unsigned int d = 0; d < NDIM - 1; ++d)
                {
                    neumann_bc_coef.setBoundarySlope(2 * d, 0.0);
                    neumann_bc_coef.setBoundarySlope(2 * d + 1, 0.0);
                }
                neumann_bc_coef.setBoundarySlope(2 * (NDIM - 1), -2.0);
                neumann_bc_coef.setBoundarySlope(2 * (NDIM - 1) + 1, +2.0);

                CartCellRobinPhysBdryOp neumann_bc_fill_op(idx, &neumann_bc_coef);
                neumann_bc_fill_op.setPhysicalBoundaryConditions(*patch, 0.0, data->getGhostCellWidth());
                plog << "extrapolated ghost data:\n";
                data->print(data->getGhostBox());
                plog << "\n";

                warning = false;
                for (Box<NDIM>::Iterator b(data->getGhostBox()); b; b++)
                {
                    const Index<NDIM>& i = b();
                    double X[NDIM];
                    for (unsigned int d = 0; d < NDIM; ++d)
                    {
                        X[d] = x_lower[d] + dx[d] * (static_cast<double>(i(d) - patch_lower(d)) + 0.5);
                    }
                    double val = 2.0 * X[NDIM - 1] + shift;

                    if (!MathUtilities<double>::equalEps(val, (*data)(i)))
                    {
                        warning = true;
                        pout << "warning: value at location " << i << " is not correct\n";
                        pout << "  expected value = " << val << "   computed value = " << (*data)(i) << "\n";
                    }
                }

                if (!warning)
                {
                    pout << "neumann boundary data appears to be correct.\n";
                }
                else
                {
                    pout << "possible errors encountered in extrapolated neumann boundary data.\n";
                }
            }
        }

    } // cleanup dynamically allocated objects prior to shutdown

    SAMRAIManager::shutdown();
    PetscFinalize();
    return true;
} // main
Beispiel #9
0
void main(void)
{
	int		i;

	cout << endl << endl;

	cout << "Memory at start: " << coreleft() << " bytes\n";

	IArray<MyNode>	a(10),b(a),c;

	// Create an array of 10 elements

	for (i = 0; i < 10; i++) {
		a.add(new MyNode(i));
		}

	cout << "Memory after creating array: " << coreleft() << " bytes\n";

	dumpArray(a);
	dumpArray(b);
	cout << "a == b > " << ((a == b) ? "TRUE" : "FALSE") << endl;
	c = a;
	dumpArray(c);
	cout << "c == a > " << ((c == a) ? "TRUE" : "FALSE") << endl;

	// Insert a number of elements into the middle of the array

	a.setDelta(10);
	for (i = 100; i < 120; i++) {
		a.insert(new MyNode(i),5);
		}
	dumpArray(a);
	getch();

	// Insert an element at the start and at the end

	a.insert(new MyNode(-1),0);
	a.insert(new MyNode(-2),a.numberOfItems());
	dumpArray(a);
	getch();

	// Now replace some elements in the array

	a.replace(new MyNode(-3),4);
	a.replace(new MyNode(-3),5);
	delete a[6];	a[6] = new MyNode(-4);
	delete a[7];	a[7] = new MyNode(-5);
	dumpArray(a);
	getch();

	// Now remove some elements from the array

	for (i = 0; i < 7; i++)
		a.destroy(4);
	dumpArray(a);

	a.destroy(10);
	dumpArray(a);
	getch();

	// Display the array using iterators.

	IArrayIterator<MyNode> it1;

	for (it1 = a; it1; it1++)
		cout << *it1.node() << " ";
	cout << endl;

	for (it1.restart(); it1;)
		cout << *it1++ << " ";
	cout << endl;

	for (it1.restart(10,20); it1;)
		cout << *++it1 << " ";
	cout << endl;
	getch();

	a.empty();
	dumpArray(a);

	cout << "Memory at end: " << coreleft() << " bytes\n\n";
}
csEventFlattenerError csEventFlattener::Unflatten (iObjectRegistry *object_reg,
						   iEvent* event, 
						   const char *buffer, 
						   size_t length)
{
  csMemFile b((char *)buffer, length, csMemFile::DISPOSITION_IGNORE);
  uint8 ui8;
  int8 i8;
  uint16 ui16;
  int16 i16;
  uint32 ui32;
  int32 i32;
  uint64 ui64;
  int64 i64;
  double d;
  char *name;
  size_t size;

  b.Read((char *)&ui32, sizeof(ui32));                 // protocol version
  ui32 = csLittleEndian::Convert (ui32);
  if (ui32 != CS_CRYSTAL_PROTOCOL)
  {
    //csPrintf("protocol version invalid: %" PRIX32 "\n", ui32);
    return csEventFlattenerErrorWrongFormat;
  }
  b.Read((char *)&ui64, sizeof(uint64));               // packet size
  size = csLittleEndian::Convert (ui64);
  b.Read((char *)&ui32, sizeof(uint32));               // iEvent.Time
  event->Time = csLittleEndian::Convert (ui32);
  b.Read((char *)&event->Broadcast, sizeof(uint8));    // iEvent.Broadcast flag
  b.Read((char *)&ui16, sizeof(uint16));               // textual name length
  ui16 = csLittleEndian::Convert (ui16);
  char *buf = (char *) cs_malloc(ui16+1);
  b.Read(buf, ui16);                                   // textual name
  buf[ui16] = '\0';
  event->Name = csEventNameRegistry::GetID(object_reg, buf); // EventID
  cs_free(buf);

  while (b.GetPos() < size)
  {
    b.Read((char *)&ui16, sizeof(uint16));
    ui16 = csLittleEndian::Convert (ui16);
    name = new char[ui16+1];
    b.Read(name, ui16);
    name[ui16] = 0;

    b.Read((char *)&ui8, sizeof(uint8));
    switch(ui8)
    {
      case CS_DATATYPE_INT8:
        b.Read((char *)&i8, sizeof(int8));
        event->Add (name, i8);
        break;
      case CS_DATATYPE_UINT8:
        b.Read((char *)&ui8, sizeof(uint8));
        event->Add (name, ui8);
        break;
      case CS_DATATYPE_INT16:
        b.Read((char *)&i16, sizeof(int16));
        i16 = csLittleEndian::Convert (i16);
        event->Add (name, i16);
        break;
      case CS_DATATYPE_UINT16:
        b.Read((char *)&ui16, sizeof(uint16));
        ui16 = csLittleEndian::Convert (ui16);
        event->Add (name, ui16);
        break;
      case CS_DATATYPE_INT32:
        b.Read((char *)&i32, sizeof(int32));
        i32 = csLittleEndian::Convert (i32);
        event->Add (name, i32);
        break;
      case CS_DATATYPE_UINT32:
        b.Read((char *)&ui32, sizeof(uint32));
        ui32 = csLittleEndian::Convert (ui32);
        event->Add (name, ui32);
        break;
      case CS_DATATYPE_INT64:
        b.Read((char *)&i64, sizeof(int64));
        i64 = csLittleEndian::Convert (i64);
        event->Add (name, i64);
        break;
      case CS_DATATYPE_UINT64:
        b.Read((char *)&ui64, sizeof(uint64));
        ui64 = csLittleEndian::Convert (ui64);
        event->Add (name, ui64);
        break;
      case CS_DATATYPE_DOUBLE:
        b.Read((char *)&ui64, sizeof(uint64));
        d = csIEEEfloat::ToNative (csLittleEndian::Convert (ui64));
        event->Add (name, d);
        break;
      case CS_DATATYPE_DATABUFFER:
        {
          b.Read((char *)&ui64, sizeof(uint64));
          ui64 = csLittleEndian::Convert (ui64);
          char* data = new char[ui64];
          b.Read(data, ui64);
          event->Add (name, data, ui64);
	  delete[] data;
        }
        break;
      case CS_DATATYPE_EVENT:
        {
          b.Read((char *)&ui64, sizeof (uint64));
          ui64 = csLittleEndian::Convert (ui64);
	  csRef<iEvent> e;
	  e.AttachNew (new csEvent ());
	  event->Add (name, e);
	  csEventFlattenerError unflattenResult = 
	    Unflatten (object_reg, e, 
		       buffer+b.GetPos(), ui64);
	  if (unflattenResult != csEventFlattenerErrorNone)
	  {
	    delete[] name;
	    return unflattenResult;
	  }
          b.SetPos (b.GetPos() + (size_t)ui64);
        }
        break;
      default:
        break;
    }  
    delete[] name;
  } 
  return csEventFlattenerErrorNone;
}
cps_api_return_code_t cps_api_set_master_node(const char *group,const char * node_name) {
    std::lock_guard<std::recursive_mutex> lg(_mutex);
    (void)load_groups();

    cps_api_node_data_type_t type;
    if(!_nodes->get_group_type(std::string(group),type)) {
        EV_LOGGING(DSAPI,ERR,"SET-MASTER","Failed to get group type for %s",group);
        return cps_api_ret_code_ERR;
    }

    if(type != cps_api_node_data_1_PLUS_1_REDUNDENCY) {
        EV_LOGGING(DSAPI,ERR,"SET-MASTER","Setting master for group type %d not supported",type);
        return cps_api_ret_code_ERR;
    }

    auto it = _nodes->_db_node_map.find(group);
    if( it == _nodes->_db_node_map.end()) {
        EV_LOGGING(DSAPI,ERR,"CPS-DB","No group named %s found",group);
        return cps_api_ret_code_ERR;
    }
    bool found = false;
    std::string master_node;
    for ( auto node_it : it->second) {
        if (strncmp(node_it._name.c_str(),node_name,strlen(node_name))==0) {
            auto master_it = _nodes->_master.find(group);
            if(master_it != _nodes->_master.end()) {
                if(master_it->second.compare(node_it._addr) == 0) {
                    return cps_api_ret_code_OK;
                } else {
                    if(!cps_api_remove_slave(node_it._addr)) {
                        return cps_api_ret_code_ERR;
                    }
                }

            }
            _nodes->_master[group]=node_it._addr;
            _nodes->mark_master_set(std::string(group));
            master_node = node_it._addr;
            if(strncmp(node_it._addr.c_str(),"127.0.0.1",strlen("127.0.0.1"))==0) {
                EV_LOGGING(DSAPI,DEBUG,"SET-MASTER","Setting local node %s master for group %s",node_name,group);
                return cps_api_remove_slave(node_it._addr) ? cps_api_ret_code_OK : cps_api_ret_code_ERR;
            }
            found = true;
            break;
        }
    }

    if(!found) {
        EV_LOGGING(DSAPI,ERR,"CPS-DB","Failed to find a node named %s in group %s",node_name,group);
        return cps_api_ret_code_ERR;
    }

    for ( auto node_it : it->second) {
        if (strncmp(node_it._name.c_str(),node_name,strlen(node_name))) {
            cps_db::connection_request b(cps_db::ProcessDBCache(),node_it._addr.c_str());
            if (!b.valid()) {
                return cps_api_ret_code_ERR;
            }

            if (!cps_db::make_slave(b.get(),master_node)) {
                EV_LOGGING(DSAPI,ERR,"SET-MASTER","Failed to make %s slave of %s",
                           node_it._name.c_str(),master_node.c_str());
                return cps_api_ret_code_ERR;
            }

        }
    }

    return cps_api_ret_code_OK;
}
csEventFlattenerError csEventFlattener::Flatten (iObjectRegistry *object_reg,
						 iEvent* event, 
						 char * buffer)
{
  uint8 ui8;
  int8 i8;
  uint16 ui16;
  int16 i16;
  uint32 ui32;
  int32 i32;
  int64 i64;
  uint64 ui64;
  size_t size;
  csEventFlattenerError flattenResult = FlattenSize (object_reg, event, size);
  if (flattenResult != csEventFlattenerErrorNone)
    return flattenResult;
  csMemFile b (buffer, size, csMemFile::DISPOSITION_IGNORE);
  
  ui32 = CS_CRYSTAL_PROTOCOL;
  ui32 = csLittleEndian::Convert (ui32);
  b.Write((char *)&ui32, sizeof(uint32));           // protocol version
  ui64 = size;
  ui64 = csLittleEndian::Convert (ui64);
  b.Write((char *)&ui64, sizeof(uint64));           // packet size
  ui32 = csLittleEndian::Convert ((uint32)event->Time);
  b.Write((char *)&ui32, sizeof(uint32));           // iEvent.Time
  b.Write((char *)&event->Broadcast, sizeof(uint8));// iEvent.Broadcast flag
  const char *nameStr = csEventNameRegistry::GetString(object_reg,
  	event->GetName());
  ui16 = (uint16)strlen (nameStr);
  ui16 = csLittleEndian::Convert (ui16);
  b.Write((char *)&ui16, sizeof(uint16));           // Event textual name length
  b.Write(nameStr, strlen(nameStr)); // Event textual name

  csRef<iEventAttributeIterator> iter (event->GetAttributeIterator ());

  while (iter->HasNext())
  {
    const char* name;
    name = iter->Next ();

    switch (event->GetAttributeType (name))
    {
      case csEventAttriBase:
	return csEventFlattenerErroriBaseEncountered;
      case csEventAttrEvent:
	{
	  // 2 byte name length (little endian)
	  ui16 = (uint16)strlen(name);
	  ui16 = csLittleEndian::Convert (ui16);
	  b.Write((char *)&ui16, sizeof(int16));
	  // XX byte name
	  b.Write(name, ui16);
	  // 1 byte datatype id
	  ui8 = CS_DATATYPE_EVENT;
	  b.Write((char *)&ui8, sizeof(uint8));

	  csRef<iEvent> ev;
	  if (event->Retrieve (name, ev) != csEventErrNone)
	    return csEventFlattenerErrorAttributeRetrieval;

	  size_t innerSize;
	  csEventFlattenerError innerResult;
	  if ((innerResult = FlattenSize (object_reg, ev, innerSize)) 
	    != csEventFlattenerErrorNone)
	    return innerResult;

	  // 8 byte data length
	  ui64 = csLittleEndian::Convert ((uint64)innerSize);
	  b.Write((char *)&ui64, sizeof(uint64));

	  // XX byte data
	  innerResult = Flatten (object_reg, ev, b.GetPos() + buffer);
	  if (innerResult != csEventFlattenerErrorNone)
	    return innerResult;
	  else
	    b.SetPos(b.GetPos() + innerSize);
	  break;
	}
      case csEventAttrDatabuffer:
	{
	  const void* data;
	  size_t dataSize;
	  if (event->Retrieve (name, data, dataSize) != csEventErrNone)
	    return csEventFlattenerErrorAttributeRetrieval;

	  // 2 byte name length (little endian)
	  ui16 = (uint16)strlen(name);
	  ui16 = csLittleEndian::Convert (ui16);
	  b.Write((char *)&ui16, sizeof(int16));
	  // XX byte name
	  b.Write(name, ui16);
	  // 1 byte datatype id
	  ui8 = CS_DATATYPE_DATABUFFER;
	  b.Write((char *)&ui8, sizeof(uint8));
	  // 4 byte data length
	  ui64 = dataSize;
	  ui64 = csLittleEndian::Convert (ui64);
	  b.Write((char *)&ui64, sizeof(uint64));
	  // XX byte data
	  b.Write ((char*)data, dataSize);
	  break;
	}
      case csEventAttrInt:
	{
	  int64 val;
	  if (event->Retrieve (name, val) != csEventErrNone)
	    return csEventFlattenerErrorAttributeRetrieval;
	  // 2 byte name length (little endian)
	  ui16 = (uint16)strlen(name);
	  ui16 = csLittleEndian::Convert (ui16);
	  b.Write((char *)&ui16, sizeof(int16));
	  // XX byte name
	  b.Write(name, ui16);
	  if ((val > 0x7fffffff) || (val < ((int32)0x80000000)))
	  {
	    // 1 byte datatype id
	    ui8 = CS_DATATYPE_INT64;
	    b.Write((char *)&ui8, sizeof(uint8));
	    // 4 byte data
	    i64 = csLittleEndian::Convert (val);
	    b.Write((char *)&i64, sizeof(int64));
	    break;
	  }
	  else if ((val > 0x7fff) || (val < ((int16)0x8000)))
	  {
	    // 1 byte datatype id
	    ui8 = CS_DATATYPE_INT32;
	    b.Write((char *)&ui8, sizeof(uint8));
	    // 4 byte data
	    i32 = csLittleEndian::Convert ((int32)val);
	    b.Write((char *)&i32, sizeof(int32));
	    break;
	  }
	  else if ((val > 0x7f) || (val < ((int8)0x80)))
	  {
	    // 1 byte datatype id
	    ui8 = CS_DATATYPE_INT16;
	    b.Write((char *)&ui8, sizeof(uint8));
	    // 2 byte data
	    i16 = csLittleEndian::Convert ((int16)val);
	    b.Write((char *)&i16, sizeof(int16));
	    break;
	  }
	  else
	  {
	    // 1 byte datatype id
	    ui8 = CS_DATATYPE_INT8;
	    b.Write((char *)&ui8, sizeof(uint8));
	    // 1 byte data
	    i8 = (int8)val;
	    b.Write((char *)&i8, sizeof(int8));
	    break;
	  }
	}
      case csEventAttrUInt:
	{
	  uint64 val;
	  if (event->Retrieve (name, val) != csEventErrNone)
	    return csEventFlattenerErrorAttributeRetrieval;
	  // 2 byte name length (little endian)
	  ui16 = (uint16)strlen(name);
	  ui16 = csLittleEndian::Convert (ui16);
	  b.Write((char *)&ui16, sizeof(int16));
	  // XX byte name
	  b.Write(name, ui16);
	  if (val > 0xffffffff)
	  {
	    // 1 byte datatype id
	    ui8 = CS_DATATYPE_UINT64;
	    b.Write((char *)&ui8, sizeof(uint8));
	    // 4 byte data
	    ui64 = csLittleEndian::Convert (val);
	    b.Write((char *)&ui64, sizeof(uint64));
	    break;
	  }
	  else if (val > 0xffff)
	  {
	    // 1 byte datatype id
	    ui8 = CS_DATATYPE_UINT32;
	    b.Write((char *)&ui8, sizeof(uint8));
	    // 4 byte data
	    ui32 = csLittleEndian::Convert ((uint32)val);
	    b.Write((char *)&ui32, sizeof(uint32));
	    break;
	  }
	  else if (val > 0xff)
	  {
	    // 1 byte datatype id
	    ui8 = CS_DATATYPE_UINT16;
	    b.Write((char *)&ui8, sizeof(uint8));
	    // 2 byte data
	    ui16 = csLittleEndian::Convert ((uint16)val);
	    b.Write((char *)&ui16, sizeof(uint16));
	    break;
	  }
	  else
	  {
	    // 1 byte datatype id
	    ui8 = CS_DATATYPE_UINT8;
	    b.Write((char *)&ui8, sizeof(uint8));
	    // 1 byte data
	    ui8 = (uint8)val;
	    b.Write((char *)&ui8, sizeof(uint8));
	    break;
	  }
	}
      case csEventAttrFloat:
	{
	  double val;
	  if (event->Retrieve (name, val) != csEventErrNone)
	    return csEventFlattenerErrorAttributeRetrieval;
	  // 2 byte name length (little endian)
	  ui16 = (uint16)strlen(name);
	  ui16 = csLittleEndian::Convert (ui16);
	  b.Write((char *)&ui16, sizeof(int16));
	  // XX byte name
	  b.Write(name, ui16);
	  // 1 byte datatype id
	  ui8 = CS_DATATYPE_DOUBLE;
	  b.Write((char *)&ui8, sizeof(uint8));
	  // 8 byte data (longlong fixed format)
	  ui64 = csLittleEndian::Convert (csIEEEfloat::FromNative (val));
	  b.Write((char *)&ui64, sizeof(uint64));
	  break;
	}
      default: 
        break;
    }
  }
  return csEventFlattenerErrorNone;
}
Beispiel #13
0
	void Run()
	{
		TC parent;
		
		MapBlock b(&parent, v3s16(1,1,1));
		v3s16 relpos(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE);

		assert(b.getPosRelative() == relpos);

		assert(b.getBox().MinEdge.X == MAP_BLOCKSIZE);
		assert(b.getBox().MaxEdge.X == MAP_BLOCKSIZE*2-1);
		assert(b.getBox().MinEdge.Y == MAP_BLOCKSIZE);
		assert(b.getBox().MaxEdge.Y == MAP_BLOCKSIZE*2-1);
		assert(b.getBox().MinEdge.Z == MAP_BLOCKSIZE);
		assert(b.getBox().MaxEdge.Z == MAP_BLOCKSIZE*2-1);
		
		assert(b.isValidPosition(v3s16(0,0,0)) == true);
		assert(b.isValidPosition(v3s16(-1,0,0)) == false);
		assert(b.isValidPosition(v3s16(-1,-142,-2341)) == false);
		assert(b.isValidPosition(v3s16(-124,142,2341)) == false);
		assert(b.isValidPosition(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1)) == true);
		assert(b.isValidPosition(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE,MAP_BLOCKSIZE-1)) == false);

		/*
			TODO: this method should probably be removed
			if the block size isn't going to be set variable
		*/
		/*assert(b.getSizeNodes() == v3s16(MAP_BLOCKSIZE,
				MAP_BLOCKSIZE, MAP_BLOCKSIZE));*/
		
		// Changed flag should be initially set
		assert(b.getChangedFlag() == true);
		b.resetChangedFlag();
		assert(b.getChangedFlag() == false);

		// All nodes should have been set to
		// .d=CONTENT_IGNORE and .getLight() = 0
		for(u16 z=0; z<MAP_BLOCKSIZE; z++)
		for(u16 y=0; y<MAP_BLOCKSIZE; y++)
		for(u16 x=0; x<MAP_BLOCKSIZE; x++)
		{
			//assert(b.getNode(v3s16(x,y,z)).getContent() == CONTENT_AIR);
			assert(b.getNode(v3s16(x,y,z)).getContent() == CONTENT_IGNORE);
			assert(b.getNode(v3s16(x,y,z)).getLight(LIGHTBANK_DAY) == 0);
			assert(b.getNode(v3s16(x,y,z)).getLight(LIGHTBANK_NIGHT) == 0);
		}
		
		{
			MapNode n(CONTENT_AIR);
			for(u16 z=0; z<MAP_BLOCKSIZE; z++)
			for(u16 y=0; y<MAP_BLOCKSIZE; y++)
			for(u16 x=0; x<MAP_BLOCKSIZE; x++)
			{
				b.setNode(v3s16(x,y,z), n);
			}
		}
			
		/*
			Parent fetch functions
		*/
		parent.position_valid = false;
		parent.node.setContent(5);

		MapNode n;
		
		// Positions in the block should still be valid
		assert(b.isValidPositionParent(v3s16(0,0,0)) == true);
		assert(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1)) == true);
		n = b.getNodeParent(v3s16(0,MAP_BLOCKSIZE-1,0));
		assert(n.getContent() == CONTENT_AIR);

		// ...but outside the block they should be invalid
		assert(b.isValidPositionParent(v3s16(-121,2341,0)) == false);
		assert(b.isValidPositionParent(v3s16(-1,0,0)) == false);
		assert(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE)) == false);
		
		{
			bool exception_thrown = false;
			try{
				// This should throw an exception
				MapNode n = b.getNodeParent(v3s16(0,0,-1));
			}
			catch(InvalidPositionException &e)
			{
				exception_thrown = true;
			}
			assert(exception_thrown);
		}

		parent.position_valid = true;
		// Now the positions outside should be valid
		assert(b.isValidPositionParent(v3s16(-121,2341,0)) == true);
		assert(b.isValidPositionParent(v3s16(-1,0,0)) == true);
		assert(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE)) == true);
		n = b.getNodeParent(v3s16(0,0,MAP_BLOCKSIZE));
		assert(n.getContent() == 5);

		/*
			Set a node
		*/
		v3s16 p(1,2,0);
		n.setContent(4);
		b.setNode(p, n);
		assert(b.getNode(p).getContent() == 4);
		//TODO: Update to new system
		/*assert(b.getNodeTile(p) == 4);
		assert(b.getNodeTile(v3s16(-1,-1,0)) == 5);*/
		
		/*
			propagateSunlight()
		*/
		// Set lighting of all nodes to 0
		for(u16 z=0; z<MAP_BLOCKSIZE; z++){
			for(u16 y=0; y<MAP_BLOCKSIZE; y++){
				for(u16 x=0; x<MAP_BLOCKSIZE; x++){
					MapNode n = b.getNode(v3s16(x,y,z));
					n.setLight(LIGHTBANK_DAY, 0);
					n.setLight(LIGHTBANK_NIGHT, 0);
					b.setNode(v3s16(x,y,z), n);
				}
			}
		}
		{
			/*
				Check how the block handles being a lonely sky block
			*/
			parent.position_valid = true;
			b.setIsUnderground(false);
			parent.node.setContent(CONTENT_AIR);
			parent.node.setLight(LIGHTBANK_DAY, LIGHT_SUN);
			parent.node.setLight(LIGHTBANK_NIGHT, 0);
			core::map<v3s16, bool> light_sources;
			// The bottom block is invalid, because we have a shadowing node
			assert(b.propagateSunlight(light_sources) == false);
			assert(b.getNode(v3s16(1,4,0)).getLight(LIGHTBANK_DAY) == LIGHT_SUN);
			assert(b.getNode(v3s16(1,3,0)).getLight(LIGHTBANK_DAY) == LIGHT_SUN);
			assert(b.getNode(v3s16(1,2,0)).getLight(LIGHTBANK_DAY) == 0);
			assert(b.getNode(v3s16(1,1,0)).getLight(LIGHTBANK_DAY) == 0);
			assert(b.getNode(v3s16(1,0,0)).getLight(LIGHTBANK_DAY) == 0);
			assert(b.getNode(v3s16(1,2,3)).getLight(LIGHTBANK_DAY) == LIGHT_SUN);
			assert(b.getFaceLight2(1000, p, v3s16(0,1,0)) == LIGHT_SUN);
			assert(b.getFaceLight2(1000, p, v3s16(0,-1,0)) == 0);
			assert(b.getFaceLight2(0, p, v3s16(0,-1,0)) == 0);
			// According to MapBlock::getFaceLight,
			// The face on the z+ side should have double-diminished light
			//assert(b.getFaceLight(p, v3s16(0,0,1)) == diminish_light(diminish_light(LIGHT_MAX)));
			// The face on the z+ side should have diminished light
			assert(b.getFaceLight2(1000, p, v3s16(0,0,1)) == diminish_light(LIGHT_MAX));
		}
		/*
			Check how the block handles being in between blocks with some non-sunlight
			while being underground
		*/
		{
			// Make neighbours to exist and set some non-sunlight to them
			parent.position_valid = true;
			b.setIsUnderground(true);
			parent.node.setLight(LIGHTBANK_DAY, LIGHT_MAX/2);
			core::map<v3s16, bool> light_sources;
			// The block below should be valid because there shouldn't be
			// sunlight in there either
			assert(b.propagateSunlight(light_sources, true) == true);
			// Should not touch nodes that are not affected (that is, all of them)
			//assert(b.getNode(v3s16(1,2,3)).getLight() == LIGHT_SUN);
			// Should set light of non-sunlighted blocks to 0.
			assert(b.getNode(v3s16(1,2,3)).getLight(LIGHTBANK_DAY) == 0);
		}
		/*
			Set up a situation where:
			- There is only air in this block
			- There is a valid non-sunlighted block at the bottom, and
			- Invalid blocks elsewhere.
			- the block is not underground.

			This should result in bottom block invalidity
		*/
		{
			b.setIsUnderground(false);
			// Clear block
			for(u16 z=0; z<MAP_BLOCKSIZE; z++){
				for(u16 y=0; y<MAP_BLOCKSIZE; y++){
					for(u16 x=0; x<MAP_BLOCKSIZE; x++){
						MapNode n;
						n.setContent(CONTENT_AIR);
						n.setLight(LIGHTBANK_DAY, 0);
						b.setNode(v3s16(x,y,z), n);
					}
				}
			}
			// Make neighbours invalid
			parent.position_valid = false;
			// Add exceptions to the top of the bottom block
			for(u16 x=0; x<MAP_BLOCKSIZE; x++)
			for(u16 z=0; z<MAP_BLOCKSIZE; z++)
			{
				parent.validity_exceptions.push_back(v3s16(MAP_BLOCKSIZE+x, MAP_BLOCKSIZE-1, MAP_BLOCKSIZE+z));
			}
			// Lighting value for the valid nodes
			parent.node.setLight(LIGHTBANK_DAY, LIGHT_MAX/2);
			core::map<v3s16, bool> light_sources;
			// Bottom block is not valid
			assert(b.propagateSunlight(light_sources) == false);
		}
	}
Beispiel #14
0
void LP02::runProblem()
{
    int numVars = 12;
    std::vector<VariablePtr> variables;
    std::vector<double> costs = {20, 40, 35, 120, 50, 60, 20, 70, 90, 35, 70, 40};
    for (int i = 0; i < numVars; i++)
    {
        auto var = std::make_shared<Variable>(costs.at(i), 0, INF);
        variables.push_back(var);
    }

    ConstraintSetPtr cs = std::make_shared<ConstraintSet>();

    {
        std::vector<VariablePtr> vars = {variables.at(0),
                                         variables.at(1),
                                         variables.at(2),
                                         variables.at(3)};

        DenseMatrix A(1,4); A << 1, 1, 1, 1;
        DenseVector b(1);   b << 100;

        ConstraintPtr lincon = std::make_shared<ConstraintLinear>(vars, A, b, false);
        cs->add(lincon);
    }

    {
        std::vector<VariablePtr> vars = {variables.at(4),
                                         variables.at(5),
                                         variables.at(6),
                                         variables.at(7)};

        DenseMatrix A(1,4); A << 1, 1, 1, 1;
        DenseVector b(1);   b << 75;

        ConstraintPtr lincon = std::make_shared<ConstraintLinear>(vars, A, b, false);
        cs->add(lincon);
    }

    {
        std::vector<VariablePtr> vars = {variables.at(8),
                                         variables.at(9),
                                         variables.at(10),
                                         variables.at(11)};

        DenseMatrix A(1,4); A << 1, 1, 1, 1;
        DenseVector b(1);   b << 90;

        ConstraintPtr lincon = std::make_shared<ConstraintLinear>(vars, A, b, false);
        cs->add(lincon);
    }

    {
        std::vector<VariablePtr> vars = {variables.at(0),
                                         variables.at(4),
                                         variables.at(8)};

        DenseMatrix A(1,3); A << -1, -1, -1;
        DenseVector b(1);   b << -30;

        ConstraintPtr lincon = std::make_shared<ConstraintLinear>(vars, A, b, false);
        cs->add(lincon);
    }

    {
        std::vector<VariablePtr> vars = {variables.at(1),
                                         variables.at(5),
                                         variables.at(9)};

        DenseMatrix A(1,3); A << -1, -1, -1;
        DenseVector b(1);   b << -75;

        ConstraintPtr lincon = std::make_shared<ConstraintLinear>(vars, A, b, false);
        cs->add(lincon);
    }

    {
        std::vector<VariablePtr> vars = {variables.at(2),
                                         variables.at(6),
                                         variables.at(10)};

        DenseMatrix A(1,3); A << -1, -1, -1;
        DenseVector b(1);   b << -90;

        ConstraintPtr lincon = std::make_shared<ConstraintLinear>(vars, A, b, false);
        cs->add(lincon);
    }

    {
        std::vector<VariablePtr> vars = {variables.at(3),
                                         variables.at(7),
                                         variables.at(11)};

        DenseMatrix A(1,3);  A << -1, -1, -1;
        DenseVector b(1);   b << -50;

        ConstraintPtr lincon = std::make_shared<ConstraintLinear>(vars, A, b, false);
        cs->add(lincon);
    }

    //cout << *cs << endl;

    SolverGurobi solver(cs);
    //SolverIpopt solver(cs);
    auto res = solver.optimize();
    cout << res << endl;

    fopt_found = res.objectiveValue;
}
void run_test_cases( BOOST_EXPLICIT_TEMPLATE_TYPE(Block) )
{
  typedef boost::dynamic_bitset<Block> bitset_type;
  typedef bitset_test< bitset_type > Tests;
  const int bits_per_block = bitset_type::bits_per_block;

  std::string long_string = get_long_string();

  //=====================================================================
  // Test operator&=
  {
    boost::dynamic_bitset<Block> lhs, rhs;
    Tests::and_assignment(lhs, rhs);
  }
  {
    boost::dynamic_bitset<Block> lhs(std::string("1")), rhs(std::string("0"));
    Tests::and_assignment(lhs, rhs);
  }
  {
    boost::dynamic_bitset<Block> lhs(long_string.size(), 0), rhs(long_string);
    Tests::and_assignment(lhs, rhs);
  }
  {
    boost::dynamic_bitset<Block> lhs(long_string.size(), 1), rhs(long_string);
    Tests::and_assignment(lhs, rhs);
  }
  //=====================================================================
  // Test operator |=
  {
    boost::dynamic_bitset<Block> lhs, rhs;
    Tests::or_assignment(lhs, rhs);
  }
  {
    boost::dynamic_bitset<Block> lhs(std::string("1")), rhs(std::string("0"));
    Tests::or_assignment(lhs, rhs);
  }
  {
    boost::dynamic_bitset<Block> lhs(long_string.size(), 0), rhs(long_string);
    Tests::or_assignment(lhs, rhs);
  }
  {
    boost::dynamic_bitset<Block> lhs(long_string.size(), 1), rhs(long_string);
    Tests::or_assignment(lhs, rhs);
  }
  //=====================================================================
  // Test operator^=
  {
    boost::dynamic_bitset<Block> lhs, rhs;
    Tests::xor_assignment(lhs, rhs);
  }
  {
    boost::dynamic_bitset<Block> lhs(std::string("1")), rhs(std::string("0"));
    Tests::xor_assignment(lhs, rhs);
  }
  {
    boost::dynamic_bitset<Block> lhs(std::string("0")), rhs(std::string("1"));
    Tests::xor_assignment(lhs, rhs);
  }
  {
    boost::dynamic_bitset<Block> lhs(long_string), rhs(long_string);
    Tests::xor_assignment(lhs, rhs);
  }
  //=====================================================================
  // Test operator-=
  {
    boost::dynamic_bitset<Block> lhs, rhs;
    Tests::sub_assignment(lhs, rhs);
  }
  {
    boost::dynamic_bitset<Block> lhs(std::string("1")), rhs(std::string("0"));
    Tests::sub_assignment(lhs, rhs);
  }
  {
    boost::dynamic_bitset<Block> lhs(std::string("0")), rhs(std::string("1"));
    Tests::sub_assignment(lhs, rhs);
  }
  {
    boost::dynamic_bitset<Block> lhs(long_string), rhs(long_string);
    Tests::sub_assignment(lhs, rhs);
  }
  //=====================================================================
  // Test operator<<=
  { // case pos == 0
    std::size_t pos = 0;
    {
      boost::dynamic_bitset<Block> b;
      Tests::shift_left_assignment(b, pos);
    }
    {
      boost::dynamic_bitset<Block> b(std::string("1010"));
      Tests::shift_left_assignment(b, pos);
    }
    {
      boost::dynamic_bitset<Block> b(long_string);
      Tests::shift_left_assignment(b, pos);
    }
  }
  {
    // test with both multiple and
    // non multiple of bits_per_block
    const int how_many = 10;
    for (int i = 1; i <= how_many; ++i) {
        std::size_t     multiple = i * bits_per_block;
        std::size_t non_multiple = multiple - 1;
        boost::dynamic_bitset<Block> b(long_string);

        Tests::shift_left_assignment(b, multiple);
        Tests::shift_left_assignment(b, non_multiple);
    }
  }
  { // case pos == size()/2
    std::size_t pos = long_string.size() / 2;
    boost::dynamic_bitset<Block> b(long_string);
    Tests::shift_left_assignment(b, pos);
  }
  { // case pos >= n
    std::size_t pos = long_string.size();
    boost::dynamic_bitset<Block> b(long_string);
    Tests::shift_left_assignment(b, pos);
  }
  //=====================================================================
  // Test operator>>=
  { // case pos == 0
    std::size_t pos = 0;
    {
      boost::dynamic_bitset<Block> b;
      Tests::shift_right_assignment(b, pos);
    }
    {
      boost::dynamic_bitset<Block> b(std::string("1010"));
      Tests::shift_right_assignment(b, pos);
    }
    {
      boost::dynamic_bitset<Block> b(long_string);
      Tests::shift_right_assignment(b, pos);
    }
  }
  {
    // test with both multiple and
    // non multiple of bits_per_block
    const int how_many = 10;
    for (int i = 1; i <= how_many; ++i) {
        std::size_t     multiple = i * bits_per_block;
        std::size_t non_multiple = multiple - 1;
        boost::dynamic_bitset<Block> b(long_string);

        Tests::shift_right_assignment(b, multiple);
        Tests::shift_right_assignment(b, non_multiple);
    }

  }
  { // case pos == size()/2
    std::size_t pos = long_string.size() / 2;
    boost::dynamic_bitset<Block> b(long_string);
    Tests::shift_right_assignment(b, pos);
  }
  { // case pos >= n
    std::size_t pos = long_string.size();
    boost::dynamic_bitset<Block> b(long_string);
    Tests::shift_right_assignment(b, pos);
  }
  //=====================================================================
  // test b.set()
  {
    boost::dynamic_bitset<Block> b;
    Tests::set_all(b);
  }
  {
    boost::dynamic_bitset<Block> b(std::string("0"));
    Tests::set_all(b);
  }
  {
    boost::dynamic_bitset<Block> b(long_string);
    Tests::set_all(b);
  }
  //=====================================================================
  // Test b.set(pos)
  { // case pos >= b.size()
    boost::dynamic_bitset<Block> b;
    Tests::set_one(b, 0, true);
  }
  { // case pos < b.size()
    boost::dynamic_bitset<Block> b(std::string("0"));
    Tests::set_one(b, 0, true);
  }
  { // case pos == b.size() / 2
    boost::dynamic_bitset<Block> b(long_string);
    Tests::set_one(b, long_string.size()/2, true);
  }
  //=====================================================================
  // Test b.reset()
  {
    boost::dynamic_bitset<Block> b;
    Tests::reset_all(b);
  }
  {
    boost::dynamic_bitset<Block> b(std::string("0"));
    Tests::reset_all(b);
  }
  {
    boost::dynamic_bitset<Block> b(long_string);
    Tests::reset_all(b);
  }
  //=====================================================================
  // Test b.reset(pos)
  { // case pos >= b.size()
    boost::dynamic_bitset<Block> b;
    Tests::reset_one(b, 0);
  }
  { // case pos < b.size()
    boost::dynamic_bitset<Block> b(std::string("0"));
    Tests::reset_one(b, 0);
  }
  { // case pos == b.size() / 2
    boost::dynamic_bitset<Block> b(long_string);
    Tests::reset_one(b, long_string.size()/2);
  }
  //=====================================================================
  // Test ~b
  {
    boost::dynamic_bitset<Block> b;
    Tests::operator_flip(b);
  }
  {
    boost::dynamic_bitset<Block> b(std::string("1"));
    Tests::operator_flip(b);
  }
  {
    boost::dynamic_bitset<Block> b(long_string);
    Tests::operator_flip(b);
  }
  //=====================================================================
  // Test b.flip()
  {
    boost::dynamic_bitset<Block> b;
    Tests::flip_all(b);
  }
  {
    boost::dynamic_bitset<Block> b(std::string("1"));
    Tests::flip_all(b);
  }
  {
    boost::dynamic_bitset<Block> b(long_string);
    Tests::flip_all(b);
  }
  //=====================================================================
  // Test b.flip(pos)
  { // case pos >= b.size()
    boost::dynamic_bitset<Block> b;
    Tests::flip_one(b, 0);
  }
  { // case pos < b.size()
    boost::dynamic_bitset<Block> b(std::string("0"));
    Tests::flip_one(b, 0);
  }
  { // case pos == b.size() / 2
    boost::dynamic_bitset<Block> b(long_string);
    Tests::flip_one(b, long_string.size()/2);
  }
}
Beispiel #16
0
/*************************************************************************
Returns  nodes/weights  for  Gauss-Jacobi quadrature on [-1,1] with weight
function W(x)=Power(1-x,Alpha)*Power(1+x,Beta).

INPUT PARAMETERS:
    N           -   number of nodes, >=1
    Alpha       -   power-law coefficient, Alpha>-1
    Beta        -   power-law coefficient, Beta>-1

OUTPUT PARAMETERS:
    Info        -   error code:
                    * -4    an  error  was   detected   when   calculating
                            weights/nodes. Alpha or  Beta  are  too  close
                            to -1 to obtain weights/nodes with high enough
                            accuracy, or, may be, N is too large.  Try  to
                            use multiple precision version.
                    * -3    internal eigenproblem solver hasn't converged
                    * -1    incorrect N/Alpha/Beta was passed
                    * +1    OK
    X           -   array[0..N-1] - array of quadrature nodes,
                    in ascending order.
    W           -   array[0..N-1] - array of quadrature weights.


  -- ALGLIB --
     Copyright 12.05.2009 by Bochkanov Sergey
*************************************************************************/
void gqgenerategaussjacobi(int n,
     double alpha,
     double beta,
     int& info,
     ap::real_1d_array& x,
     ap::real_1d_array& w)
{
    ap::real_1d_array a;
    ap::real_1d_array b;
    double alpha2;
    double beta2;
    double apb;
    double t;
    int i;
    double s;

    if( n<1||ap::fp_less_eq(alpha,-1)||ap::fp_less_eq(beta,-1) )
    {
        info = -1;
        return;
    }
    a.setlength(n);
    b.setlength(n);
    apb = alpha+beta;
    a(0) = (beta-alpha)/(apb+2);
    t = (apb+1)*log(double(2))+lngamma(alpha+1, s)+lngamma(beta+1, s)-lngamma(apb+2, s);
    if( ap::fp_greater(t,log(ap::maxrealnumber)) )
    {
        info = -4;
        return;
    }
    b(0) = exp(t);
    if( n>1 )
    {
        alpha2 = ap::sqr(alpha);
        beta2 = ap::sqr(beta);
        a(1) = (beta2-alpha2)/((apb+2)*(apb+4));
        b(1) = 4*(alpha+1)*(beta+1)/((apb+3)*ap::sqr(apb+2));
        for(i = 2; i <= n-1; i++)
        {
            a(i) = 0.25*(beta2-alpha2)/(i*i*(1+0.5*apb/i)*(1+0.5*(apb+2)/i));
            b(i) = 0.25*(1+alpha/i)*(1+beta/i)*(1+apb/i)/((1+0.5*(apb+1)/i)*(1+0.5*(apb-1)/i)*ap::sqr(1+0.5*apb/i));
        }
    }
    gqgeneraterec(a, b, b(0), n, info, x, w);
    
    //
    // test basic properties to detect errors
    //
    if( info>0 )
    {
        if( ap::fp_less(x(0),-1)||ap::fp_greater(x(n-1),+1) )
        {
            info = -4;
        }
        for(i = 0; i <= n-2; i++)
        {
            if( ap::fp_greater_eq(x(i),x(i+1)) )
            {
                info = -4;
            }
        }
    }
}
Beispiel #17
0
bool ComplexMesh::ComputeDiskParameterization(bool Natural)
{
    const float Lambda = 1.0f;

    Vector<FullEdge *> Boundary;
    if(!ComputeDiskBoundary(Boundary))
    {
        return false;
    }

    float TotalBoundaryLength = 0.0f;
    for(UINT i = 0; i < Boundary.Length(); i++)
    {
        TotalBoundaryLength += Boundary[i]->Vector().Length();
        if(i != 0)
        {
            Assert(Boundary[i]->GetVertex(0).Index() == Boundary[i - 1]->GetVertex(1).Index(), "Invalid boundary");
        }
    }
    PersistentAssert(TotalBoundaryLength > 0.0f, "Invalid boundary");

    float CurBoundaryLength = 0.0f;
    for(UINT i = 0; i < Boundary.Length(); i++)
    {
        Vertex &CurVertex = Boundary[i]->GetVertex(0);
        CurVertex.TexCoords() = Vec2f::ConstructFromPolar(0.5f, 2.0f * Math::PIf * CurBoundaryLength / TotalBoundaryLength) + Vec2f(0.5f, 0.5f);
        CurBoundaryLength += Boundary[i]->Vector().Length();
    }
    
    SparseMatrix<double> M(_Vertices.Length() * 2);
    
    const UINT FixedIndexCount = 2;
    UINT FixedIndices[FixedIndexCount];
    FixedIndices[0] = Boundary[0]->GetVertex(0).Index();
    FixedIndices[1] = Boundary[Boundary.Length() / 2]->GetVertex(1).Index();

    for(UINT VertexIndex = 0; VertexIndex < _Vertices.Length(); VertexIndex++)
    {
        Vertex &CurVertex = _Vertices[VertexIndex];
        if(CurVertex.Boundary())
        {
            if(Natural && VertexIndex != FixedIndices[0] && VertexIndex != FixedIndices[1])
            {
                for(UINT TriangleIndex = 0; TriangleIndex < CurVertex.Triangles().Length(); TriangleIndex++)
                {
                    Triangle &CurTriangle = *(CurVertex.Triangles()[TriangleIndex]);
                    UINT IBaseIndex = CurTriangle.GetVertexLocalIndex(CurVertex);
                    UINT IIndex = CurTriangle.GetVertex((IBaseIndex + 0) % 3).Index();
                    UINT JIndex = CurTriangle.GetVertex((IBaseIndex + 1) % 3).Index();
                    UINT KIndex = CurTriangle.GetVertex((IBaseIndex + 2) % 3).Index();

                    double Alpha = CurTriangle.GetCotangent(CurTriangle.GetVertex((IBaseIndex + 2) % 3));
                    double Beta = CurTriangle.GetCotangent(CurTriangle.GetVertex((IBaseIndex + 1) % 3));

                    M.PushElement(2 * VertexIndex + 0, 2 * IIndex + 0, Alpha + Beta);
                    M.PushElement(2 * VertexIndex + 1, 2 * IIndex + 1, Alpha + Beta);

                    M.PushElement(2 * VertexIndex + 0, 2 * JIndex + 0, -Alpha);
                    M.PushElement(2 * VertexIndex + 1, 2 * JIndex + 1, -Alpha);

                    M.PushElement(2 * VertexIndex + 0, 2 * KIndex + 0, -Beta);
                    M.PushElement(2 * VertexIndex + 1, 2 * KIndex + 1, -Beta);

                    M.PushElement(2 * VertexIndex + 0, 2 * JIndex + 1, 1.0);
                    M.PushElement(2 * VertexIndex + 1, 2 * JIndex + 0, -1.0);

                    M.PushElement(2 * VertexIndex + 0, 2 * KIndex + 1, -1.0);
                    M.PushElement(2 * VertexIndex + 1, 2 * KIndex + 0, 1.0);
                }
                /*for(UINT EdgeIndex = 0; EdgeIndex < CurVertex.Vertices().Length(); EdgeIndex++)
                {
                    Vertex &OtherVertex = *(CurVertex.Vertices()[EdgeIndex]);
                    FullEdge &CurEdge = CurVertex.GetSharedEdge(OtherVertex);
                    double ConstantFactor = Lambda * CurEdge.GetCotanTerm();
                    Assert(ConstantFactor == ConstantFactor, "ConstantFactor invalid");
                    M.PushDiagonalElement(VertexIndex * 2 + 0, -ConstantFactor);
                    M.PushDiagonalElement(VertexIndex * 2 + 1, -ConstantFactor);
                    M.PushElement(VertexIndex * 2 + 0, OtherVertex.Index() * 2 + 1, ConstantFactor);
                    M.PushElement(VertexIndex * 2 + 0, OtherVertex.Index() * 2 + 1, ConstantFactor);
                    M.PushElement(VertexIndex * 2 + 1, OtherVertex.Index() * 2 + 0, 1.0f);
                    M.PushElement(VertexIndex * 2 + 0, OtherVertex.Index() * 2 + 1, -1.0f);
                }*/
            }
            else
            {
                M.PushDiagonalElement(VertexIndex * 2 + 0, 1.0f);
                M.PushDiagonalElement(VertexIndex * 2 + 1, 1.0f);
            }
        }
        else
        {
            //M.PushDiagonalElement(VertexIndex * 2 + 0, VertexAreas[VertexIndex]);
            //M.PushDiagonalElement(VertexIndex * 2 + 1, VertexAreas[VertexIndex]);
            for(UINT EdgeIndex = 0; EdgeIndex < CurVertex.Vertices().Length(); EdgeIndex++)
            {
                Vertex &OtherVertex = *(CurVertex.Vertices()[EdgeIndex]);
                FullEdge &CurEdge = CurVertex.GetSharedEdge(OtherVertex);
                double ConstantFactor = Lambda * CurEdge.GetCotanTerm();
                Assert(ConstantFactor == ConstantFactor, "ConstantFactor invalid");
                M.PushDiagonalElement(VertexIndex * 2 + 0, -ConstantFactor);
                M.PushDiagonalElement(VertexIndex * 2 + 1, -ConstantFactor);
                M.PushElement(VertexIndex * 2 + 0, OtherVertex.Index() * 2 + 0, ConstantFactor);
                M.PushElement(VertexIndex * 2 + 1, OtherVertex.Index() * 2 + 1, ConstantFactor);
            }
        }
    }

    BiCGLinearSolver<double> Solver;
    //TaucsSymmetricLinearSolver Solver;
    Solver.LoadMatrix(&M);
    Solver.Factor();
    //ofstream File("Matrix.TexCoord.xt");
    //M.Dump(File, false);
    //File << endl;
    Solver.SetParamaters(1000, 1e-6);

    Vector<double> x(_Vertices.Length() * 2), b(_Vertices.Length() * 2);
    for(UINT VertexIndex = 0; VertexIndex < _Vertices.Length(); VertexIndex++)
    {
        Vertex &CurVertex = _Vertices[VertexIndex];
        if(CurVertex.Boundary())
        {
            if(!Natural || VertexIndex == FixedIndices[0] || VertexIndex == FixedIndices[1])
            {
                x[VertexIndex * 2 + 0] = CurVertex.TexCoords().x;
                x[VertexIndex * 2 + 1] = CurVertex.TexCoords().y;
                b[VertexIndex * 2 + 0] = CurVertex.TexCoords().x;
                b[VertexIndex * 2 + 1] = CurVertex.TexCoords().y;
            }
            else
            {
                x[VertexIndex * 2 + 0] = CurVertex.Pos().x;
                x[VertexIndex * 2 + 1] = CurVertex.Pos().y;
                b[VertexIndex * 2 + 0] = 0.0f;
                b[VertexIndex * 2 + 1] = 0.0f;
            }
        }
        else
        {
            x[VertexIndex * 2 + 0] = CurVertex.Pos().x;
            x[VertexIndex * 2 + 1] = CurVertex.Pos().y;
            b[VertexIndex * 2 + 0] = 0.0f;
            b[VertexIndex * 2 + 1] = 0.0f;
        }
        //File << b[VertexIndex * 2 + 0] << '\t' << b[VertexIndex * 2 + 1] << endl;
    }
    Solver.Solve(x, b);
    Console::WriteLine(Solver.GetOutputString());
    double Error = Solver.ComputeError(x, b);
    Console::WriteLine(String("Parameterization error: ") + String(Error));
    for(UINT VertexIndex = 0; VertexIndex < _Vertices.Length(); VertexIndex++)
    {
        Vertex &CurVertex = _Vertices[VertexIndex];
        if(Natural || !CurVertex.Boundary())
        {
            CurVertex.TexCoords().x = float(x[VertexIndex * 2 + 0]);
            CurVertex.TexCoords().y = float(x[VertexIndex * 2 + 1]);
        }
    }

    return true;
}
Beispiel #18
0
 QPointF operator+(QPointF &p)
 {
     QPointF b(p.x()+m_X,p.y()+m_Y);
     return b;
 }
Beispiel #19
0
void ComplexMesh::ImplicitMeanCurvatureFlow(float TimeStep)
{
    Vector<double> VertexAreas(_Vertices.Length());
    Vector<Vec3f> NewVertexPositions(_Vertices.Length());
    NewVertexPositions.Clear(Vec3f::Origin);

    
    SparseMatrix<double> M(_Vertices.Length());

    for(UINT VertexIndex = 0; VertexIndex < _Vertices.Length(); VertexIndex++)
    {
        Vertex &CurVertex = _Vertices[VertexIndex];
        VertexAreas[VertexIndex] = CurVertex.ComputeTriangleArea();
        M.PushElement(VertexIndex, VertexIndex, VertexAreas[VertexIndex]);
        //M.PushElement(VertexIndex, VertexIndex, 1.0f);
        for(UINT EdgeIndex = 0; EdgeIndex < CurVertex.Vertices().Length(); EdgeIndex++)
        {
            Vertex &OtherVertex = *(CurVertex.Vertices()[EdgeIndex]);
            FullEdge &CurEdge = CurVertex.GetSharedEdge(OtherVertex);
            double ConstantFactor = CurEdge.GetCotanTerm() / 4.0f;
            Assert(ConstantFactor == ConstantFactor, "ConstantFactor invalid");
            M.PushElement(VertexIndex, VertexIndex, TimeStep * ConstantFactor);
            M.PushElement(VertexIndex, OtherVertex.Index(), -TimeStep * ConstantFactor);
        }
    }

    BiCGLinearSolver<double> Solver;
    Solver.LoadMatrix(&M);
    const double ErrorTolerance = 1e-6;
    Solver.SetParamaters(1000, ErrorTolerance);
    Solver.Factor();

    for(UINT ElementIndex = 0; ElementIndex < 3; ElementIndex++)
    {
        Vector<double> x, b(_Vertices.Length());
        for(UINT VertexIndex = 0; VertexIndex < _Vertices.Length(); VertexIndex++)
        {
            b[VertexIndex] = _Vertices[VertexIndex].Pos()[ElementIndex] * VertexAreas[VertexIndex];
            //b[VertexIndex] = _Vertices[VertexIndex].Pos().Element(ElementIndex);
        }
        Solver.Solve(x, b);
        Console::WriteLine(Solver.GetOutputString());
        double Error = Solver.ComputeError(x, b);
        Console::WriteLine(String("Mean curvature error: ") + String(Error));
        if(Error < ErrorTolerance)
        {
            for(UINT VertexIndex = 0; VertexIndex < _Vertices.Length(); VertexIndex++)
            {
                NewVertexPositions[VertexIndex][ElementIndex] = float(x[VertexIndex]);
            }
        }
    }

    float AverageDelta = 0.0f;
    for(UINT VertexIndex = 0; VertexIndex < _Vertices.Length(); VertexIndex++)
    {
        Vec3f Delta = NewVertexPositions[VertexIndex] - _Vertices[VertexIndex].Pos();
        AverageDelta += Delta.Length();
    }
    AverageDelta /= _Vertices.Length();
    for(UINT VertexIndex = 0; VertexIndex < _Vertices.Length(); VertexIndex++)
    {
        Vertex &CurVertex = _Vertices[VertexIndex];
        Vec3f Delta = NewVertexPositions[VertexIndex] - _Vertices[VertexIndex].Pos();
        if(Delta.Length() > 2.0f * AverageDelta)
        {
            Delta.SetLength(2.0f * AverageDelta);
        }
        CurVertex.Pos() += Delta;
    }
}
Beispiel #20
0
int main(int argc, char** argv) {
  int rc = 0;

  try {
    // Initialize runtime
    TiledArray::World& world = TiledArray::initialize(argc, argv);

    // Get command line arguments
    if(argc < 2) {
      std::cout << "Usage: ta_sparse matrix_size block_size [repetitions]\n";
      return 0;
    }
    const long matrix_size = atol(argv[1]);
    const long block_size = atol(argv[2]);
    if(matrix_size <= 0) {
      std::cerr << "Error: matrix size must greater than zero.\n";
      return 1;
    }
    if(block_size <= 0) {
      std::cerr << "Error: block size must greater than zero.\n";
      return 1;
    }
    if((matrix_size % block_size) != 0ul) {
      std::cerr << "Error: matrix size must be evenly divisible by block size.\n";
      return 1;
    }
    const long repeat = (argc >= 4 ? atol(argv[3]) : 4);
    if(repeat <= 0) {
      std::cerr << "Error: number of repetitions must greater than zero.\n";
      return 1;
    }

    // Print information about the test
    const std::size_t num_blocks = matrix_size / block_size;
    const double app_flop = 2.0 * matrix_size * matrix_size * matrix_size;
    std::vector<std::vector<double> > gflops;
    std::vector<std::vector<double> > times;
    std::vector<std::vector<double> > app_gflops;

    if(world.rank() == 0)
      std::cout << "TiledArray: block-sparse matrix multiply test..."
                << "\nGit HASH: " << TILEDARRAY_REVISION
                << "\nNumber of nodes    = " << world.size()
                << "\nMatrix size        = " << matrix_size << "x" << matrix_size
                << "\nBlock size         = " << block_size << "x" << block_size;


    // Construct TiledRange
    std::vector<unsigned int> blocking;
    blocking.reserve(num_blocks + 1);
    for(long i = 0l; i <= matrix_size; i += block_size)
      blocking.push_back(i);

    std::vector<TiledArray::TiledRange1> blocking2(2,
        TiledArray::TiledRange1(blocking.begin(), blocking.end()));

    TiledArray::TiledRange
      trange(blocking2.begin(), blocking2.end());

    for(unsigned int left_sparsity = 10; left_sparsity <= 100; left_sparsity += 10){
      std::vector<double> inner_gflops, inner_times, inner_app_gflops;
      for(unsigned int right_sparsity = 10; right_sparsity <= left_sparsity; right_sparsity += 10){
        const long l_block_count = (double(left_sparsity) / 100.0) * double(num_blocks * num_blocks);
        const long r_block_count = (double(right_sparsity) / 100.0) * double(num_blocks * num_blocks);
        if(world.rank() == 0)
                    std::cout << "\nMemory per left matrix  = " << double(l_block_count * block_size * block_size * sizeof(double)) / 1.0e9 << " GB"
                    << "\nMemory per right matrix  = " << double(r_block_count * block_size * block_size * sizeof(double)) / 1.0e9 << " GB"
                    << "\nNumber of left blocks   = " << l_block_count << "   " << 100.0 * double(l_block_count) / double(num_blocks * num_blocks) << "%"
                    << "\nNumber of right blocks   = " << r_block_count << "   " << 100.0 * double(r_block_count) / double(num_blocks * num_blocks) << "%"
                    << "\nAverage left blocks/node = " << double(l_block_count) / double(world.size())
                    << "\nAverage right blocks/node = " << double(r_block_count) / double(world.size()) << "\n";

        // Construct shape
        TiledArray::Tensor<float>
            a_tile_norms(trange.tiles(), 0.0),
            b_tile_norms(trange.tiles(), 0.0);
        if(world.rank() == 0) {
          world.srand(time(NULL));
          for(long count = 0l; count < l_block_count; ++count) {
            std::size_t index = world.rand() % trange.tiles().volume();

            // Avoid setting the same tile to non-zero.
            while(a_tile_norms[index] > TiledArray::SparseShape<float>::threshold())
              index = world.rand() % trange.tiles().volume();

            a_tile_norms[index] = std::sqrt(float(block_size * block_size));
          }
          for(long count = 0l; count < r_block_count; ++count) {
            std::size_t index = world.rand() % trange.tiles().volume();

            // Avoid setting the same tile to non-zero.
            while(b_tile_norms[index] > TiledArray::SparseShape<float>::threshold())
              index = world.rand() % trange.tiles().volume();

            b_tile_norms[index] = std::sqrt(float(block_size * block_size));
          }

        }
        TiledArray::SparseShape<float>
            a_shape(world, a_tile_norms, trange),
            b_shape(world, b_tile_norms, trange);


        typedef TiledArray::Array<double, 2, TiledArray::Tensor<double>,
            TiledArray::SparsePolicy > SpTArray2;

        // Construct and initialize arrays
        SpTArray2 a(world, trange, a_shape);
        SpTArray2 b(world, trange, b_shape);
        SpTArray2 c;
        a.set_all_local(1.0);
        b.set_all_local(1.0);

        // Start clock
        SpTArray2::wait_for_lazy_cleanup(world);
        world.gop.fence();
        if(world.rank() == 0)
          std::cout << "Starting iterations:\n";

        double total_time = 0.0, flop = 0.0;

        // Do matrix multiplication
        try {
          for(int i = 0; i < repeat; ++i) {
            const double start = madness::wall_time();
            c("m,n") = a("m,k") * b("k,n");
            const double time = madness::wall_time() - start;
            total_time += time;
            if(flop < 1.0)
              flop = 2.0 * c("m,n").sum();
            if(world.rank() == 0)
              std::cout << "Iteration " << i + 1 << "   time=" << time << "   GFLOPS="
                  << flop / time / 1.0e9 << "   apparent GFLOPS=" << app_flop / time / 1.0e9 << "\n";

          }
        } catch(...) {
          if(world.rank() == 0) {
            std::stringstream ss;
            ss << "left shape  = " << a.get_shape().data() << "\n"
               << "right shape = " << b.get_shape().data() << "\n";
            printf(ss.str().c_str());
          }
        }

        // Stop clock
        inner_gflops.push_back(double(repeat) * flop / total_time / 1.0e9);
        inner_times.push_back(total_time / repeat);
        inner_app_gflops.push_back(double(repeat) * app_flop / total_time / 1.0e9);

        // Print results
        if(world.rank() == 0) {
          std::cout << "Average wall time = " << total_time / double(repeat)
              << "\nAverage GFLOPS = " << double(repeat) * double(flop) / total_time / 1.0e9
              << "\nAverage apparent GFLOPS = " << double(repeat) * double(app_flop) / total_time / 1.0e9 << "\n";
        }
      }
      gflops.push_back(inner_gflops);
      times.push_back(inner_times);
      app_gflops.push_back(inner_app_gflops);
    }

    if(world.rank() == 0) {
      std::cout << "\n--------------------------------------------------------------------------------------------------------\nGFLOPS\n";
      print_results(world, gflops);
      std::cout << "\n--------------------------------------------------------------------------------------------------------\nAverage wall times\n";
      print_results(world, times);
      std::cout << "\n--------------------------------------------------------------------------------------------------------\nApparent GFLOPS\n";
      print_results(world, app_gflops);
    }


    TiledArray::finalize();

  } catch(TiledArray::Exception& e) {
    std::cerr << "!! TiledArray exception: " << e.what() << "\n";
    rc = 1;
  } catch(madness::MadnessException& e) {
    std::cerr << "!! MADNESS exception: " << e.what() << "\n";
    rc = 1;
  } catch(SafeMPI::Exception& e) {
    std::cerr << "!! SafeMPI exception: " << e.what() << "\n";
    rc = 1;
  } catch(std::exception& e) {
    std::cerr << "!! std exception: " << e.what() << "\n";
    rc = 1;
  } catch(...) {
    std::cerr << "!! exception: unknown exception\n";
    rc = 1;
  }

  return rc;
}
Beispiel #21
0
void BenchMarkAll(double t)
{
	logtotal = 0;
	logcount = 0;

	cout << "<TABLE border=1><COLGROUP><COL align=left><COL align=right><COL align=right><COL align=right>" << endl;
	cout << "<THEAD><TR><TH>Algorithm<TH>Bytes Processed<TH>Time Taken<TH>Megabytes(2^20 bytes)/Second\n<TBODY>" << endl;

	BenchMarkKeyless<CRC32>("CRC-32", t);
	BenchMarkKeyless<Adler32>("Adler-32", t);
	BenchMarkKeyless<MD2>("MD2", t);
	BenchMarkKeyless<MD5>("MD5", t);
	BenchMarkKeyless<SHA>("SHA-1", t);
	BenchMarkKeyless<SHA256>("SHA-256", t);
	BenchMarkKeyless<SHA512>("SHA-512", t);
	BenchMarkKeyless<HAVAL3>("HAVAL (pass=3)", t);
	BenchMarkKeyless<HAVAL4>("HAVAL (pass=4)", t);
	BenchMarkKeyless<HAVAL5>("HAVAL (pass=5)", t);
#ifdef WORD64_AVAILABLE
	BenchMarkKeyless<Tiger>("Tiger", t);
#endif
	BenchMarkKeyless<RIPEMD160>("RIPE-MD160", t);
	BenchMarkKeyless<PanamaHash<false> >("Panama Hash (little endian)", t);
	BenchMarkKeyless<PanamaHash<true> >("Panama Hash (big endian)", t);
	BenchMarkKeyed<MDC<MD5> >("MDC/MD5", t);
	BenchMarkKeyed<LREncryption<MD5> >("Luby-Rackoff/MD5", t);
	BenchMarkKeyed<DESEncryption>("DES", t);
	BenchMarkKeyed<DES_XEX3_Encryption>("DES-XEX3", t);
	BenchMarkKeyed<DES_EDE3_Encryption>("DES-EDE3", t);
	BenchMarkKeyed<IDEAEncryption>("IDEA", t);
	BenchMarkKeyed<RC2Encryption>("RC2", t);
	BenchMarkKeyed<RC5Encryption>("RC5 (r=16)", t);
	BenchMarkKeyed<BlowfishEncryption>("Blowfish", t);
	BenchMarkKeyed<Diamond2Encryption>("Diamond2", t);
	BenchMarkKeyed<Diamond2LiteEncryption>("Diamond2 Lite", t);
	BenchMarkKeyed<ThreeWayDecryption>("3-WAY", t);
	BenchMarkKeyed<TEAEncryption>("TEA", t);
	BenchMarkKeyed<SAFER_SK64_Encryption>("SAFER (r=8)", t);
	BenchMarkKeyed<GOSTEncryption>("GOST", t);
#ifdef WORD64_AVAILABLE
	BenchMarkKeyed<SHARKEncryption>("SHARK (r=6)", t);
#endif
	BenchMarkKeyed<CAST128Encryption>("CAST-128", t);
	BenchMarkKeyed<CAST256Encryption>("CAST-256", t);
	BenchMarkKeyed<SquareEncryption>("Square", t);
	BenchMarkKeyed<SKIPJACKEncryption>("SKIPJACK", t);
	BenchMarkKeyed<RC6Encryption>("RC6", t);
	BenchMarkKeyed<MARSEncryption>("MARS", t);
	BenchMarkKeyedVariable<RijndaelEncryption>("Rijndael (128-bit key)", t, 16);
	BenchMarkKeyedVariable<RijndaelEncryption>("Rijndael (192-bit key)", t, 24);
	BenchMarkKeyedVariable<RijndaelEncryption>("Rijndael (256-bit key)", t, 32);
	BenchMarkKeyed<TwofishEncryption>("Twofish", t);
	BenchMarkKeyed<SerpentEncryption>("Serpent", t);
	BenchMarkKeyed<ARC4>("ARC4", t);
	BenchMarkKeyed<SEAL>("SEAL", t);
	{
		WAKEEncryption c(key, new BitBucket);
		BenchMark("WAKE", c, t);
	}
	BenchMarkKeyed<PanamaCipher<false> >("Panama Cipher (little endian)", t);
	BenchMarkKeyed<PanamaCipher<true> >("Panama Cipher (big endian)", t);
	BenchMarkKeyed<SapphireEncryption>("Sapphire", t);
	BenchMarkKeyed<MD5MAC>("MD5-MAC", t);
	BenchMarkKeyed<XMACC<MD5> >("XMACC/MD5", t);
	BenchMarkKeyed<HMAC<MD5> >("HMAC/MD5", t);
	BenchMarkKeyed<CBC_MAC<RijndaelEncryption> >("CBC-MAC/Rijndael", t);
	BenchMarkKeyed<DMAC<RijndaelEncryption> >("DMAC/Rijndael", t);

	{
		Integer p("CB6C,B8CE,6351,164F,5D0C,0C9E,9E31,E231,CF4E,D551,CBD0,E671,5D6A,7B06,D8DF,C4A7h");
		Integer q("FD2A,8594,A132,20CC,4E6D,DE77,3AAA,CF15,CD9E,E447,8592,FF46,CC77,87BE,9876,A2AFh");
		Integer s("63239752671357255800299643604761065219897634268887145610573595874544114193025997412441121667211431");
		BlumBlumShub c(p, q, s);
		BenchMark("BlumBlumShub 512", c, t);
	}
	{
		Integer p("FD2A,8594,A132,20CC,4E6D,DE77,3AAA,CF15,CD9E,E447,8592,FF46,CC77,87BE,9876,9E2C,"
				  "8572,64C3,4CF4,188A,44D4,2130,1135,7982,6FF6,EDD3,26F0,5FAA,BAF4,A81E,7ADC,B80Bh");
		Integer q("C8B9,5797,B349,6BA3,FD72,F2C0,A796,8A65,EE0F,B4BA,272F,4FEE,4DB1,06D5,ECEB,7142,"
				  "E8A8,E5A8,6BF9,A32F,BA37,BACC,8A75,8A6B,2DCE,D6EC,B515,980A,4BB1,08FB,6F2C,2383h");
		Integer s("3578,8F00,2965,71A4,4382,699F,45FD,3922,8238,241B,CEBA,0543,3443,E8D9,12FB,AC46,"
				  "7EC4,8505,EC9E,7EE8,5A23,9B2A,B615,D0C4,9448,F23A,ADEE,E850,1A7A,CA30,0B5B,A408,"
				  "D936,21BA,844E,BDD6,7848,3D1E,9137,CC87,DAA5,773B,D45A,C8BB,5392,1393,108B,6992,"
				  "74E3,C5E2,C235,A321,0111,3BA4,BAB4,1A2F,17EE,C371,DE67,01C9,0F3D,907A,B252,9BDDh");
		BlumBlumShub c(p, q, s);
		BenchMark("BlumBlumShub 1024", c, t);
	}
	{
		Integer p("EB56,978A,7BA7,B5D9,1383,4611,94F5,4766,FCEF,CF41,958A,FC41,43D0,839F,C56B,B568,"
				  "4ED3,9E5A,BABB,5ACE,8B11,CEBC,88A2,7C12,FFEE,E6E8,CF0A,E231,5BC2,DEDE,80B7,32F6,"
				  "340E,D8A6,B7DE,C779,7EE5,0E16,9C88,FC9F,2A0E,EE6C,7D47,C5F2,6B06,EB8C,F1C8,2E67,"
				  "5B82,8C28,4FB8,542F,2874,C355,CEEE,7A54,1B06,A8AB,8B66,6A5C,9DB2,72B8,74F3,7BC7h");
		Integer q("EB6B,3645,4591,8343,7331,7CAC,B02E,4BB9,DEF5,8EDC,1772,DB9B,9571,5FAB,1CDD,4FB1,"
				  "7B9A,07CD,E715,D448,F552,CBBD,D387,C037,DE70,6661,F360,D0E8,D42E,292A,9321,DDCB,"
				  "0BF9,C514,BFAC,3F2C,C06E,DF64,A9B8,50D6,AC4F,B9E4,014B,5624,2B40,A0D4,5D0B,6DD4,"
				  "0989,D00E,0268,99AB,21DB,0BB4,DB38,84DA,594F,575F,95AC,1B70,45E4,96C8,C6AD,CE67h");
		Integer s("C75A,8A0D,E231,295F,C08A,1716,8611,D5EC,E9EF,B565,90EC,58C0,57D0,DA7D,C6E6,DB00,"
				  "2282,1CA7,EA31,D64E,768C,0B19,8563,36DF,2226,F4EC,74A4,2844,2E8D,37E8,53DC,0172,"
				  "5F56,8CF9,B444,CA02,78B3,17AF,7C78,D320,16AE,AC3D,B97F,7259,1B8F,9C84,6A16,B878,"
				  "0595,70BB,9C52,18B5,9100,9C1F,E85A,4035,06F3,5F38,7462,F01D,0462,BFBC,A4CD,4A45,"
				  "3A77,E7F8,DED1,D6EF,CEF7,0937,CD3F,3AF1,4F88,932D,6D4B,002C,3735,304C,C5D3,B88A,"
				  "B57B,24B6,5346,9B46,5153,B7ED,B216,C181,B1C6,C52E,CD2B,E0AA,B1BB,0A93,C92E,4F79,"
				  "4931,E303,7C8F,A408,8ACF,56CD,6EC0,76A2,5015,6BA4,4C50,C44D,53B9,E168,5F84,B381,"
				  "2514,10B2,00E5,B4D1,4156,A2FE,0BF6,6F33,0A1B,91C6,31B8,1C90,02F1,FB1F,C494,8B65h");
		BlumBlumShub c(p, q, s);
		BenchMark("BlumBlumShub 2048", c, t);
	}
	cout << "</TABLE>" << endl;

	cout << "<TABLE border=1><COLGROUP><COL align=left><COL align=right><COL align=right><COL align=right>" << endl;
	cout << "<THEAD><TR><TH>Operation<TH>Iterations<TH>Total Time<TH>Milliseconds/Operation" << endl;
	cout << "<TBODY style=\"background: yellow\">" << endl;
	BenchMarkCrypto<RSAES_OAEP_SHA_Decryptor, RSAES_OAEP_SHA_Encryptor>("rsa512.dat", "RSA 512", t);
	BenchMarkCrypto<RabinDecryptor, RabinEncryptor>("rabi512.dat", "Rabin 512", t);
	BenchMarkCrypto<BlumGoldwasserPrivateKey, BlumGoldwasserPublicKey>("blum512.dat", "BlumGoldwasser 512", t);
	BenchMarkCrypto<LUCES_OAEP_SHA_Decryptor, LUCES_OAEP_SHA_Encryptor>("luc512.dat", "LUC 512", t);
	BenchMarkCrypto<ElGamalDecryptor, ElGamalEncryptor>("elgc512.dat", "ElGamal 512", t);

	cout << "<TBODY style=\"background: white\">" << endl;
	BenchMarkCrypto<RSAES_OAEP_SHA_Decryptor, RSAES_OAEP_SHA_Encryptor>("rsa1024.dat", "RSA 1024", t);
	BenchMarkCrypto<RabinDecryptor, RabinEncryptor>("rabi1024.dat", "Rabin 1024", t);
	BenchMarkCrypto<BlumGoldwasserPrivateKey, BlumGoldwasserPublicKey>("blum1024.dat", "BlumGoldwasser 1024", t);
	BenchMarkCrypto<LUCES_OAEP_SHA_Decryptor, LUCES_OAEP_SHA_Encryptor>("luc1024.dat", "LUC 1024", t);
	BenchMarkCrypto<ElGamalDecryptor, ElGamalEncryptor>("elgc1024.dat", "ElGamal 1024", t);
	BenchMarkCrypto<LUCELG_Decryptor, LUCELG_Encryptor>("lucc512.dat", "LUCELG 512", t);

	cout << "<TBODY style=\"background: yellow\">" << endl;
	BenchMarkCrypto<RSAES_OAEP_SHA_Decryptor, RSAES_OAEP_SHA_Encryptor>("rsa2048.dat", "RSA 2048", t);
	BenchMarkCrypto<RabinDecryptor, RabinEncryptor>("rabi2048.dat", "Rabin 2048", t);
	BenchMarkCrypto<BlumGoldwasserPrivateKey, BlumGoldwasserPublicKey>("blum2048.dat", "BlumGoldwasser 2048", t);
	BenchMarkCrypto<LUCES_OAEP_SHA_Decryptor, LUCES_OAEP_SHA_Encryptor>("luc2048.dat", "LUC 2048", t);
	BenchMarkCrypto<ElGamalDecryptor, ElGamalEncryptor>("elgc2048.dat", "ElGamal 2048", t);
	BenchMarkCrypto<LUCELG_Decryptor, LUCELG_Encryptor>("lucc1024.dat", "LUCELG 1024", t);

	cout << "<TBODY style=\"background: white\">" << endl;
	BenchMarkSignature<RSASSA_PKCS1v15_SHA_Signer, RSASSA_PKCS1v15_SHA_Verifier>("rsa512.dat", "RSA 512", t);
	BenchMarkSignature<RabinSignerWith(SHA), RabinVerifierWith(SHA) >("rabi512.dat", "Rabin 512", t);
	BenchMarkSignature<RWSigner<SHA>, RWVerifier<SHA> >("rw512.dat", "RW 512", t);
	BenchMarkSignature<LUCSSA_PKCS1v15_SHA_Signer, LUCSSA_PKCS1v15_SHA_Verifier>("luc512.dat", "LUC 512", t);
	BenchMarkSignature<NRSigner<SHA>, NRVerifier<SHA> >("nr512.dat", "NR 512", t);
	BenchMarkSignature<DSAPrivateKey, DSAPublicKey>("dsa512.dat", "DSA 512", t);

	cout << "<TBODY style=\"background: yellow\">" << endl;
	BenchMarkSignature<RSASSA_PKCS1v15_SHA_Signer, RSASSA_PKCS1v15_SHA_Verifier>("rsa1024.dat", "RSA 1024", t);
	BenchMarkSignature<RabinSignerWith(SHA), RabinVerifierWith(SHA) >("rabi1024.dat", "Rabin 1024", t);
	BenchMarkSignature<RWSigner<SHA>, RWVerifier<SHA> >("rw1024.dat", "RW 1024", t);
	BenchMarkSignature<LUCSSA_PKCS1v15_SHA_Signer, LUCSSA_PKCS1v15_SHA_Verifier>("luc1024.dat", "LUC 1024", t);
	BenchMarkSignature<NRSigner<SHA>, NRVerifier<SHA> >("nr1024.dat", "NR 1024", t);
	BenchMarkSignature<DSAPrivateKey, DSAPublicKey>("dsa1024.dat", "DSA 1024", t);
	BenchMarkSignature<LUCELG_Signer<SHA>, LUCELG_Verifier<SHA> >("lucs512.dat", "LUCELG 512", t);

	cout << "<TBODY style=\"background: white\">" << endl;
	BenchMarkSignature<RSASSA_PKCS1v15_SHA_Signer, RSASSA_PKCS1v15_SHA_Verifier>("rsa2048.dat", "RSA 2048", t);
	BenchMarkSignature<RabinSignerWith(SHA), RabinVerifierWith(SHA) >("rabi2048.dat", "Rabin 2048", t);
	BenchMarkSignature<RWSigner<SHA>, RWVerifier<SHA> >("rw2048.dat", "RW 2048", t);
	BenchMarkSignature<LUCSSA_PKCS1v15_SHA_Signer, LUCSSA_PKCS1v15_SHA_Verifier>("luc2048.dat", "LUC 2048", t);
	BenchMarkSignature<NRSigner<SHA>, NRVerifier<SHA> >("nr2048.dat", "NR 2048", t);
	BenchMarkSignature<LUCELG_Signer<SHA>, LUCELG_Verifier<SHA> >("lucs1024.dat", "LUCELG 1024", t);

	cout << "<TBODY style=\"background: yellow\">" << endl;
	BenchMarkKeyAgreement<XTR_DH>("xtrdh171.dat", "XTR-DH 171", t);
	BenchMarkKeyAgreement<XTR_DH>("xtrdh342.dat", "XTR-DH 342", t);
	BenchMarkKeyAgreement<DH>("dh512.dat", "DH 512", t);
	BenchMarkKeyAgreement<DH>("dh1024.dat", "DH 1024", t);
	BenchMarkKeyAgreement<DH>("dh2048.dat", "DH 2048", t);
	BenchMarkKeyAgreement<LUCDIF>("lucd512.dat", "LUCDIF 512", t);
	BenchMarkKeyAgreement<LUCDIF>("lucd1024.dat", "LUCDIF 1024", t);
	BenchMarkKeyAgreement<MQV>("mqv512.dat", "MQV 512", t);
	BenchMarkKeyAgreement<MQV>("mqv1024.dat", "MQV 1024", t);
	BenchMarkKeyAgreement<MQV>("mqv2048.dat", "MQV 2048", t);

	cout << "<TBODY style=\"background: white\">" << endl;
	{
		Integer modulus("199999999999999999999999980586675243082581144187569");
		Integer a("659942,b7261b,249174,c86bd5,e2a65b,45fe07,37d110h");
		Integer b("3ece7d,09473d,666000,5baef5,d4e00e,30159d,2df49ah");
		Integer x("25dd61,4c0667,81abc0,fe6c84,fefaa3,858ca6,96d0e8h");
		Integer y("4e2477,05aab0,b3497f,d62b5e,78a531,446729,6c3fach");
		Integer r("100000000000000000000000000000000000000000000000151");
		Integer k(2);
		Integer d("76572944925670636209790912427415155085360939712345");

		ECP ec(modulus, a, b);
		ECP::Point P(x, y);
		P = ec.Multiply(k, P);
		ECP::Point Q(ec.Multiply(d, P));
		ECDecryptor<ECP> cpriv(ec, P, r, Q, d);
		ECEncryptor<ECP> cpub(cpriv);
		ECSigner<ECP, SHA> spriv(cpriv);
		ECVerifier<ECP, SHA> spub(spriv);
		ECDHC<ECP> ecdhc(ec, P, r, k);
		ECMQVC<ECP> ecmqvc(ec, P, r, k);

		BenchMarkEncryption("ECIES over GF(p) 168", cpub, t);
		BenchMarkDecryption("ECIES over GF(p) 168", cpriv, cpub, t);
		BenchMarkSigning("ECNR over GF(p) 168", spriv, t);
		BenchMarkVerification("ECNR over GF(p) 168", spriv, spub, t);
		BenchMarkKeyGen("ECDHC over GF(p) 168", ecdhc, t);
		BenchMarkAgreement("ECDHC over GF(p) 168", ecdhc, t);
		BenchMarkKeyGen("ECMQVC over GF(p) 168", ecmqvc, t);
		BenchMarkAgreement("ECMQVC over GF(p) 168", ecmqvc, t);
	}

	cout << "<TBODY style=\"background: yellow\">" << endl;
	{
		Integer r("3805993847215893016155463826195386266397436443");
		Integer k(12);
		Integer d("2065729449256706362097909124274151550853609397");

		GF2NT gf2n(155, 62, 0);
		byte b[]={0x7, 0x33, 0x8f};
		EC2N ec(gf2n, PolynomialMod2::Zero(), PolynomialMod2(b,3));
		EC2N::Point P(0x7B, 0x1C8);
		P = ec.Multiply(k, P);
		EC2N::Point Q(ec.Multiply(d, P));
		ECDecryptor<EC2N> cpriv(ec, P, r, Q, d);
		ECEncryptor<EC2N> cpub(cpriv);
		ECSigner<EC2N, SHA> spriv(cpriv);
		ECVerifier<EC2N, SHA> spub(spriv);
		ECDHC<EC2N> ecdhc(ec, P, r, k);
		ECMQVC<EC2N> ecmqvc(ec, P, r, k);

		BenchMarkEncryption("ECIES over GF(2^n) 155", cpub, t);
		BenchMarkDecryption("ECIES over GF(2^n) 155", cpriv, cpub, t);
		BenchMarkSigning("ECNR over GF(2^n) 155", spriv, t);
		BenchMarkVerification("ECNR over GF(2^n) 155", spriv, spub, t);
		BenchMarkKeyGen("ECDHC over GF(2^n) 155", ecdhc, t);
		BenchMarkAgreement("ECDHC over GF(2^n) 155", ecdhc, t);
		BenchMarkKeyGen("ECMQVC over GF(2^n) 155", ecmqvc, t);
		BenchMarkAgreement("ECMQVC over GF(2^n) 155", ecmqvc, t);
	}
	cout << "</TABLE>" << endl;

	cout << "Throughput Geometric Average: " << setiosflags(ios::fixed) << exp(logtotal/logcount) << endl;
}
int main(int argc, char* argv[])
{
#if 1
	QApplication a(argc, argv);
	MainWindow w;
	w.show();


	// look for image file
	//std::string img_file("data/floor.jpg");
	//QFile file;
	//for (int i = 0; i < 5; ++i)
	//	if (!file.exists(img_file.c_str()))
	//		img_file.insert(0, "../");
	//w.getGLWidget()->setImage(img_file.c_str());

	

	GLLines* gllines = &w.getGLWidget()->glLines();

	
	//gllines->setVertexLine(0, 0, QVector3D(52.3467f, 125.102f, 1.0f));
	//gllines->setVertexLine(0, 1, QVector3D(340.253f, 130.147f, 1.0f));
	//gllines->setVertexLine(1, 0, QVector3D(193.28f, 126.111f, 1.0f));
	//gllines->setVertexLine(1, 1, QVector3D(225.493f, 360.173f, 1.0f));
	//gllines->setVertexLine(2, 0, QVector3D(42.28f, 263.32f, 1.0f));
	//gllines->setVertexLine(2, 1, QVector3D(296.967f, 397.502f, 1.0f));
	//gllines->setVertexLine(3, 0, QVector3D(212.407f, 269.373f, 1.0f));
	//gllines->setVertexLine(3, 1, QVector3D(34.2267f, 391.449f, 1.0f));
	//gllines->setVertexLine(4, 0, QVector3D(294.953f, 318.809f, 1.0f));
	//gllines->setVertexLine(4, 1, QVector3D(456.02f, 322.844f, 1.0f));
	//gllines->setVertexLine(5, 0, QVector3D(492.26f, 208.84f, 1.0f));
	//gllines->setVertexLine(5, 1, QVector3D(429.847f, 400.529f, 1.0f));
	//gllines->setVertexLine(6, 0, QVector3D(299.987f, 31.2756f, 1.0f));
	//gllines->setVertexLine(6, 1, QVector3D(555.68f, 273.409f, 1.0f));
	//gllines->setVertexLine(7, 0, QVector3D(545.613f, 39.3467f, 1.0f));
	//gllines->setVertexLine(7, 1, QVector3D(236.567f, 250.204f, 1.0f));
	//gllines->setVertexLine(8, 0, QVector3D(95.6333f, 264.329f, 1.0f));
	//gllines->setVertexLine(8, 1, QVector3D(501.32f, 273.409f, 1.0f));
	//gllines->setVertexLine(9, 0, QVector3D(302.00f, 29.2578f, 1.0f));
	//gllines->setVertexLine(9, 1, QVector3D(297.973f, 398.511f, 1.0f));
	gllines->computeCanonicalVertices(w.getGLWidget()->width(), w.getGLWidget()->height());
	gllines->onEnable(true);

	return a.exec();

#else
	std::vector<Eigen::Vector3f> vertices;
	vertices.push_back(Eigen::Vector3f(52.3467f, 125.102f, 1.0f));
	vertices.push_back(Eigen::Vector3f(340.253f, 130.147f, 1.0f));
	vertices.push_back(Eigen::Vector3f(193.28f, 126.111f, 1.0f));
	vertices.push_back(Eigen::Vector3f(225.493f, 360.173f, 1.0f));
	vertices.push_back(Eigen::Vector3f(42.28f, 263.32f, 1.0f));
	vertices.push_back(Eigen::Vector3f(296.967f, 397.502f, 1.0f));
	vertices.push_back(Eigen::Vector3f(212.407f, 269.373f, 1.0f));
	vertices.push_back(Eigen::Vector3f(34.2267f, 391.449f, 1.0f));
	vertices.push_back(Eigen::Vector3f(294.953f, 318.809f, 1.0f));
	vertices.push_back(Eigen::Vector3f(456.02f, 322.844f, 1.0f));
	vertices.push_back(Eigen::Vector3f(492.26f, 208.84f, 1.0f));
	vertices.push_back(Eigen::Vector3f(429.847f, 400.529f, 1.0f));
	vertices.push_back(Eigen::Vector3f(299.987f, 31.2756f, 1.0f));
	vertices.push_back(Eigen::Vector3f(555.68f, 273.409f, 1.0f));
	vertices.push_back(Eigen::Vector3f(545.613f, 39.3467f, 1.0f));
	vertices.push_back(Eigen::Vector3f(236.567f, 250.204f, 1.0f));
	vertices.push_back(Eigen::Vector3f(95.6333f, 264.329f, 1.0f));
	vertices.push_back(Eigen::Vector3f(501.32f, 273.409f, 1.0f));
	vertices.push_back(Eigen::Vector3f(302.00f, 29.2578f, 1.0f));
	vertices.push_back(Eigen::Vector3f(297.973f, 398.511f, 1.0f));


	std::cout << vertices.size() << std::endl;

	std::vector<Eigen::Vector3f> lines;
	for (int i = 0; i < vertices.size() - 1; i += 2)
		lines.push_back(lineNormalized(vertices[i], vertices[i + 1]));
	
	for (int i = 0; i < lines.size(); ++i)
		std::cout << "l" << i << " : " << lines[i].x() << ", " << lines[i].y() << ", " << lines[i].z() << std::endl;

	std::cout << std::endl << std::endl;

	//lines[0] = Eigen::Vector3f(-0.000141084, 0.00805224, -0.999968);
	//lines[1] = Eigen::Vector3f(-0.00568419, 0.000782299, 0.999984);
	//lines[2] = Eigen::Vector3f(-0.00218568, 0.00414856, -0.999989);
	//lines[3] = Eigen::Vector3f(-0.0016513, -0.00241022, 0.999996);
	//lines[4] = Eigen::Vector3f(-8.04546e-05, 0.00321109, -0.999995);
	//lines[5] = Eigen::Vector3f(-0.00178489, -0.000581155, 0.999998);
	//lines[6] = Eigen::Vector3f(-0.00374583, 0.0039556, 0.999985);
	//lines[7] = Eigen::Vector3f(-0.00165759, -0.00242947, 0.999996);
	//lines[8] = Eigen::Vector3f(-8.53647e-05, 0.00381402, -0.999993);
	//lines[9] = Eigen::Vector3f(-0.00330775, -3.60706e-05, 0.999995);


	Eigen::MatrixXf A(5, 5);
	Eigen::Vector3f l, m;
	Eigen::VectorXf b(5);

	for (int i = 0; i < 5; ++i)
	{
		l = lines[i * 2 + 0];
		m = lines[i * 2 + 1];

		A(i, 0) = l[0] * m[0];
		A(i, 1) = (l[0] * m[1] + l[1] * m[0]) / 2.0f;
		A(i, 2) = l[1] * m[1];
		A(i, 3) = (l[0] * m[2] + l[2] * m[0]) / 2.0f;
		A(i, 4) = (l[1] * m[2] + l[2] * m[1]) / 2.0f;
		A(i, 5) = l[2] * m[2];

		b[i] = -l[2] * m[2];
	}

	std::cout << "A: \n" << A << std::endl << std::endl;
	std::cout << "b: \n" << b << std::endl << std::endl;

	Eigen::MatrixXf x = A.colPivHouseholderQr().solve(b);
	std::cout << std::fixed << "x: \n" << x << std::endl << std::endl;


	Eigen::MatrixXf conic(3, 3);
	conic(0, 0) = x(0);
	conic(0, 1) = x(1) / 2.0f;
	conic(0, 2) = x(3) / 2.0f;
	conic(1, 0) = x(1) / 2.0f;
	conic(1, 1) = x(2);
	conic(1, 2) = x(4) / 2.0f;
	conic(2, 0) = x(3) / 2.0f;
	conic(2, 1) = x(4) / 2.0f;
	conic(2, 2) = 1.0f;
	std::cout << "Conic : " << std::endl << conic << std::endl << std::endl;

	Eigen::JacobiSVD<Eigen::MatrixXf> svd(conic, Eigen::ComputeFullU);
	Eigen::MatrixXf H = svd.matrixU();
	
	std::cout << "H matrix: " << std::endl 
		<< H << std::endl << std::endl 
		<< "Singular values: " << svd.singularValues()
		<< std::endl << std::endl;

	std::cout << "Rectification transformation: " << std::endl << H.inverse() << std::endl << std::endl;





	QImage input("floor-persp.jpg");
	Eigen::Vector3f img(input.width(), input.height(), 1.0f);

	float xmin = 0;
	float xmax = 0;
	float ymin = 0;
	float ymax = 0;
	computImageSize(H.inverse(), 0, 0, input.width(), input.height(), xmin, xmax, ymin, ymax);


	float aspect = (xmax - xmin) / (ymax - ymin);
	QImage output(input.width(), input.width() / aspect, input.format());
	output.fill(qRgb(0, 0, 0));

	std::cout << "Output size: " << output.width() << ", " << output.height() << std::endl;

	float dx = (xmax - xmin) / float(output.width());
	float dy = (ymax - ymin) / float(output.height());

	std::cout << std::fixed << "dx, dy: " << dx << ", " << dy << std::endl;

	for (int x = 0; x < output.width(); ++x)
	{
		for (int y = 0; y < output.height(); ++y)
		{
			Eigen::Vector3f px(x, y, 1);

			float tx = 0.0f;
			float ty = 0.0f;
			Eigen::Vector2f t = multiplyPointMatrix(H, xmin + x * dx, ymin + y * dy);

			if (t.x() > -1 && t.y() > -1
				&& t.x() < input.width()
				&& t.y() < input.height())
			{
				//if (interpolate)
				//{
				//	QRgb rgb = bilinearInterpol(input, t.x(), t.y(), dx / 2.0, dy / 2.0);
				//	output.setPixel(x, y, rgb);
				//}
				//else
				{
					output.setPixel(x, y, input.pixel(t.x(), t.y()));
				}
			}
		}
	}


	output.save("output_5_floor.jpg");
	
	return EXIT_SUCCESS;
#endif
}
Beispiel #23
0
int
main()
{
    Boo b(0);
    return EXIT_SUCCESS;
}
Beispiel #24
0
int
sc_main( int, char*[] )
{
    // 1) check the existence of the reduce methods

    sc_int<42> a = 42;

    // sc_int_base
    cout << endl;
    cout <<  and_reduce( a ) << endl;
    cout <<   or_reduce( a ) << endl;
    cout <<  xor_reduce( a ) << endl;
    cout << nand_reduce( a ) << endl;
    cout <<  nor_reduce( a ) << endl;
    cout << xnor_reduce( a ) << endl;

    // sc_int_subref
    cout << endl;
    cout <<  and_reduce( a( 7, 0 ) ) << endl;
    cout <<   or_reduce( a( 7, 0 ) ) << endl;
    cout <<  xor_reduce( a( 7, 0 ) ) << endl;
    cout << nand_reduce( a( 7, 0 ) ) << endl;
    cout <<  nor_reduce( a( 7, 0 ) ) << endl;
    cout << xnor_reduce( a( 7, 0 ) ) << endl;

    // sc_int_concref<T1,T2>
    cout << endl;
    cout <<  and_reduce( ( a( 7, 0 ), a( 15, 8 ) ) ) << endl;
    cout <<   or_reduce( ( a( 7, 0 ), a( 15, 8 ) ) ) << endl;
    cout <<  xor_reduce( ( a( 7, 0 ), a( 15, 8 ) ) ) << endl;
    cout << nand_reduce( ( a( 7, 0 ), a( 15, 8 ) ) ) << endl;
    cout <<  nor_reduce( ( a( 7, 0 ), a( 15, 8 ) ) ) << endl;
    cout << xnor_reduce( ( a( 7, 0 ), a( 15, 8 ) ) ) << endl;

    sc_uint<42> b = 42;

    // sc_uint_base
    cout << endl;
    cout <<  and_reduce( b ) << endl;
    cout <<   or_reduce( b ) << endl;
    cout <<  xor_reduce( b ) << endl;
    cout << nand_reduce( b ) << endl;
    cout <<  nor_reduce( b ) << endl;
    cout << xnor_reduce( b ) << endl;

    // sc_uint_subref
    cout << endl;
    cout <<  and_reduce( b( 7, 0 ) ) << endl;
    cout <<   or_reduce( b( 7, 0 ) ) << endl;
    cout <<  xor_reduce( b( 7, 0 ) ) << endl;
    cout << nand_reduce( b( 7, 0 ) ) << endl;
    cout <<  nor_reduce( b( 7, 0 ) ) << endl;
    cout << xnor_reduce( b( 7, 0 ) ) << endl;

    // sc_uint_concref<T1,T2>
    cout << endl;
    cout <<  and_reduce( ( b( 7, 0 ), b( 15, 8 ) ) ) << endl;
    cout <<   or_reduce( ( b( 7, 0 ), b( 15, 8 ) ) ) << endl;
    cout <<  xor_reduce( ( b( 7, 0 ), b( 15, 8 ) ) ) << endl;
    cout << nand_reduce( ( b( 7, 0 ), b( 15, 8 ) ) ) << endl;
    cout <<  nor_reduce( ( b( 7, 0 ), b( 15, 8 ) ) ) << endl;
    cout << xnor_reduce( ( b( 7, 0 ), b( 15, 8 ) ) ) << endl;

    // 2) check the functionality of the reduce methods

    sc_int<2> c2 = -1;
    cout << endl;
    cout << and_reduce( c2 ) << endl;
    cout << xor_reduce( c2 ) << endl;

    sc_int<3> c3 = -1;
    cout << endl;
    cout << and_reduce( c3 ) << endl;
    cout << xor_reduce( c3 ) << endl;

    sc_uint<2> d2 = sc_dt::uint_type( -1 );
    cout << endl;
    cout << and_reduce( d2 ) << endl;
    cout << xor_reduce( d2 ) << endl;

    sc_uint<3> d3 = sc_dt::uint_type( -1 );
    cout << endl;
    cout << and_reduce( d3 ) << endl;
    cout << xor_reduce( d3 ) << endl;

    sc_int<6> e;
    sc_uint<6> f;
    cout << endl;
    for( int i = 0; i >= -10; -- i ) {
        e = i;
        f = i;
        cout << xor_reduce( e ) << endl;
        cout << xor_reduce( f ) << endl;
    }
    
    return 0;
}
Beispiel #25
0
/*************************************************************************************************
* compute_trajectory_from_last_three
* Compute trajectory from last three positions if valid ball pos, otherwise c(0)=0 (no trajectory)
*************************************************************************************************/ 
void CTrajectory::compute_trajectory_from_last_three()
{
  Eigen::Vector3f temp;
  Eigen::Vector3f temporigin;
  
  double coords1[3],coords2[3],coords3[3];
  
  has_trajectory = 0;
  c(0)=0;
  origin(0) = origin(1)=origin(2)=0; 
  
  if (trajecto_pose[HISTORY-3]>=0 && trajecto_pose[HISTORY-2]>=0 && trajecto_pose[HISTORY-1]>=0)
  {
    double d1,d2,d3;
    origin = previous_pose[HISTORY-3];
    temporigin = origin;
    
    // set orgin in ground plane
    temporigin[2]=0;
    d3 = 0;
    
    temp = previous_pose[HISTORY-2];
    temp[2]=0;
    d2 = (temp-temporigin).norm();
    
    temp = previous_pose[HISTORY-1];
    temp[2]=0;
    d1 = (temp-temporigin).norm();
	
    //Eigen::Matrix3f A;
    Eigen::MatrixXf A(3,3);
    //A <<  d1*d1,d1,1,d2*d2,d2,1,d3*d3,d3,1;
    A <<  d3*d3,d3,1,d2*d2,d2,1,d1*d1,d1,1;
    Eigen::VectorXf b(3,1);
    //Eigen::Vector3f b(previous_pose[HISTORY-3][2],previous_pose[HISTORY-2][2],previous_pose[HISTORY-1][2]);
    b << previous_pose[HISTORY-3][2],previous_pose[HISTORY-2][2],previous_pose[HISTORY-1][2];
   
    c = A.colPivHouseholderQr().solve(b);
	
    // check if all three points fits well to curve
    compute_3D_from_1D(d3,coords3);
    compute_3D_from_1D(d2,coords2);
    compute_3D_from_1D(d1,coords1);
    if ( sqrt ( (coords3[0]-previous_pose[HISTORY-3][0]) * (coords3[0]-previous_pose[HISTORY-3][0])
	       +(coords3[1]-previous_pose[HISTORY-3][1]) * (coords3[1]-previous_pose[HISTORY-3][1])
	       +(coords3[2]-previous_pose[HISTORY-3][2]) * (coords3[2]-previous_pose[HISTORY-3][2]) ) > MIN_DISTANCE_TRAJECTORY
      || sqrt ( (coords2[0]-previous_pose[HISTORY-2][0]) * (coords2[0]-previous_pose[HISTORY-2][0])
	       +(coords2[1]-previous_pose[HISTORY-2][1]) * (coords2[1]-previous_pose[HISTORY-2][1])
	       +(coords2[2]-previous_pose[HISTORY-2][2]) * (coords2[2]-previous_pose[HISTORY-2][2]) ) > MIN_DISTANCE_TRAJECTORY
      || sqrt ( (coords1[0]-previous_pose[HISTORY-1][0]) * (coords1[0]-previous_pose[HISTORY-1][0])
	       +(coords1[1]-previous_pose[HISTORY-1][1]) * (coords1[1]-previous_pose[HISTORY-1][1])
	       +(coords1[2]-previous_pose[HISTORY-1][2]) * (coords1[2]-previous_pose[HISTORY-1][2]) ) > MIN_DISTANCE_TRAJECTORY)
/*    if ( fabs(previous_pose[HISTORY-4][2] - (c(0)*d4*d4 +c(1)*d4 +c(2) ) ) > MIN_DISTANCE_TRAJECTORY
      || fabs(previous_pose[HISTORY-3][2] - (c(0)*d3*d3 +c(1)*d3 +c(2) ) ) > MIN_DISTANCE_TRAJECTORY
      || fabs(previous_pose[HISTORY-2][2] - (c(0)*d2*d2 +c(1)*d2 +c(2) ) ) > MIN_DISTANCE_TRAJECTORY
      || fabs(previous_pose[HISTORY-1][2] - (c(0)*d1*d1 +c(1)*d1 +c(2) ) ) > MIN_DISTANCE_TRAJECTORY )*/
    {
      has_trajectory = 0;
      c(0)=0;
      origin(0) = origin(1)=origin(2)=0; 
    }
    else
    {
      has_trajectory = 1;
      trajecto_pose[HISTORY-3]=1;
      trajecto_pose[HISTORY-2]=1;
      trajecto_pose[HISTORY-1]=1;
      origin = previous_pose[HISTORY-3];
    }
  }
}
Beispiel #26
0
 void clearLock()
 {
     SpinBlock b(lock);
     clear();
 }
Beispiel #27
0
Boundary
GUIInductLoop::MyWrapper::getCenteringBoundary() const throw() {
    Boundary b(myBoundary);
    b.grow(20);
    return b;
}
Beispiel #28
0
//---------------------------------------------------------
int main(int argc, char **argv)
{
   TPS<double>         rbf;
   Polinomio<double>   pol;
   Matrix<double>      A,B;
   Vector<double>      x,y,f;
   Vector<double>      lambda,b;
   Vector<double>      xnew,ynew,fnew; 
   double              c=0.01;
   int                 n,ni,m;
 
//make the data in the square [0,1] x [0,1]   
   make_data(0,1,0,1, 21, 21, x, y, ni, n);

//stablish the exponent in: r^beta log(r)
   rbf.set_beta(4);
   
//configure the associate polynomial
// pol.make( data_dimension, degree_pol)
   pol.make(2 , rbf.get_degree_pol());
   
//show the rbf and pol info
   cout<<rbf;
   cout<<pol;
   
//show the number of nodes   
   cout<<endl;
   cout<<"total nodes    N  = "<<n<<endl;
   cout<<"interior nodes ni = "<<ni<<endl;
   cout<<"boundary nodes nf = "<<n-ni<<endl;
   cout<<endl;
   

//get the number of elements in the polynomial base
   m = pol.get_M();
    
//resize the matrices to store the partial derivatives
   A.Resize(n+m,n+m);  A = 0.0;
   B.Resize(n+m,n+m);  B = 0.0;
   
//Recall that this problem has the general form
//   (Uxx+Uyy)   (Pxx+Pyy)   =  f     interior nodes  0..ni 
//     U           P_b       =  g     boundary nodes  ni..n 
//   P^transpose   0         =  0     momentun conditions in P  
//
// P is the polynomial wit size n x m
// P_b is the polynomial working in the boundary nodes, size   nf x m
// Pxx+Pyy  has size  ni x m   
   
//make the matriz derivatives   
   fill_matrix(   "dxx"     , rbf , pol , c , x , y, 0 ,  ni ,  A);
   fill_matrix(   "dyy"     , rbf , pol , c , x , y, 0 ,  ni ,  B);
      
   A = A + B;   //  A <-  Uxx + Uyy
    
//Add the submatriz for the boundary nodes:   U , P_b           boundary nodes  ni..n        
   fill_matrix(   "normal"  , rbf , pol , c , x , y, ni,   n ,  A);
   
//Add the submatriz P^transpose at the end:    P^transpose   
   fill_matrix( "pol_trans" , rbf , pol , c , x , y, n ,  n+m,  A);
     
//resize the vector to store the right_size of the PDE      
   b.Resize(n+m); b = 0.0;
    
//fill with   f  
   for(int i=0;i<ni;i++)
      b(i) = right_side(x(i), y(i));
      
//fill with the boundary condition      
   for(int i=ni;i<n;i++)
      b(i) = boundary_condition(x(i),y(i));
      
//solve the linear system of equations 
   lambda =  gauss(A,b);
    
//make the new data grid    
   int ni2,n2;
   make_data(0,1,0,1, 41, 41, xnew, ynew, ni2, n2);
    
//interpolate on this new data grid (xnew,ynew)     
   fnew = interpolate(rbf,pol,c,lambda,x,y,xnew,ynew);
     
//determine the maximum error
   double e=0.0;
   for(int i=0;i<ni2;i++)
   {
     e = max(e, fabs(fnew(i) - sin(2*M_PI*xnew(i))*cos(2*M_PI*ynew(i)))  );
   }
     
//show the error     
   cout<<endl;
   cout<<"The maximum error: e_max = "<<e<<endl<<endl;
   
//store the interpolated data   
   save_gnu_data("data",xnew,ynew,fnew);
     
  return 0;
}
void ReturnStatusTest::basic()
{
   // default constructor test
   vpr::ReturnStatus s;
   CPPUNIT_ASSERT( s == vpr::ReturnStatus::Succeed );
   CPPUNIT_ASSERT( s.code() == vpr::ReturnStatus::Succeed );

   // ReturnStatus::Code constructor test
   vpr::ReturnStatus a( vpr::ReturnStatus::WouldBlock );
   CPPUNIT_ASSERT( a == vpr::ReturnStatus::WouldBlock );
   CPPUNIT_ASSERT( a.code() == vpr::ReturnStatus::WouldBlock );

   // copy constructor test
   vpr::ReturnStatus b( a );
   CPPUNIT_ASSERT( b == vpr::ReturnStatus::WouldBlock );
   CPPUNIT_ASSERT( b.code() == vpr::ReturnStatus::WouldBlock );

   // setCode test
   a.setCode( vpr::ReturnStatus::Fail );
   CPPUNIT_ASSERT( a == vpr::ReturnStatus::Fail );
   CPPUNIT_ASSERT( a.code() == vpr::ReturnStatus::Fail );

   // status = status test
   s.setCode( vpr::ReturnStatus::Succeed );
   a.setCode( vpr::ReturnStatus::Fail );
   a = s;
   CPPUNIT_ASSERT( a == vpr::ReturnStatus::Succeed );
   CPPUNIT_ASSERT( a.code() == vpr::ReturnStatus::Succeed );

   // status = code test
   a.setCode( vpr::ReturnStatus::Fail );
   a = vpr::ReturnStatus::Succeed;
   CPPUNIT_ASSERT( a == vpr::ReturnStatus::Succeed );
   CPPUNIT_ASSERT( a.code() == vpr::ReturnStatus::Succeed );

   // code() test
   vpr::ReturnStatus c;
   a.setCode( vpr::ReturnStatus::Fail );
   c.setCode( a.code() );
   CPPUNIT_ASSERT( c == vpr::ReturnStatus::Fail );
   CPPUNIT_ASSERT( c.code() == vpr::ReturnStatus::Fail );



   // setup some stuff....
   a.setCode( vpr::ReturnStatus::Succeed );
   b.setCode( vpr::ReturnStatus::Succeed );

   // ReturnStatus == ReturnStatus test
   CPPUNIT_ASSERT( a == b );

   // Code == Code test
   CPPUNIT_ASSERT( a.code() == b.code() );

   // ReturnStatus == Code test
   CPPUNIT_ASSERT( a == b.code() );
   CPPUNIT_ASSERT( b == a.code() );


   // setup some stuff....
   a.setCode( vpr::ReturnStatus::Succeed );
   b.setCode( vpr::ReturnStatus::Fail );

   // ReturnStatus != ReturnStatus test
   CPPUNIT_ASSERT( a != b );

   // Code != Code test
   CPPUNIT_ASSERT( a.code() != b.code() );

   // ReturnStatus != Code test
   CPPUNIT_ASSERT( a != b.code() );
   CPPUNIT_ASSERT( b != a.code() );
}
Beispiel #30
0
int main()
{
	{
		A::Enum a;
		B::Enum b;
		int n;
	
		A::init();
		a=A::ONE;
		b=B::ONE;
		//a=B::ONE; //nok
		n=a;
	
		assert(n==1);
		n=b;
		assert(n==1);
		assert(A::str[A::ONE]=="one");
		assert(A::str[1]=="one");
	}
	m[ZERO_]="zero";
	m[ONE_]="one";
	m[TWO_]="two";
	{
		N n=ZERO_;
		int m=ZERO_;
	
		assert(n==m);
	
		//n=m;  //nok
		n=static_cast<N>(m);
	
		m=n;
		assert(m==n);
	
		assert(ZERO_==0);
	}
	{
		N n;
		N *p, *q;
		int* r;
	
		n=ZERO_;
		p=&n;
		//p=new ZERO_; //nok
		//p=&ZERO_; //nok
		q=reinterpret_cast<N*>(new int(2));
		r=reinterpret_cast<int*>(p);
	
		assert(*p==n);
		assert(*p==ZERO_);
	
		assert(str_enum(n)=="zero");
		assert(str_enum(*p)=="zero");
		assert(str_enum(static_cast<N>(0))=="zero");
		assert(str_enum(*q)=="two");
	
		assert(str_int(ZERO_)=="0");
		assert(str_int(*q)=="2");
		assert(str_int(*r)=="0");
	
		// TODO enum =>int*
//		assert(str_int_ptr(ZERO_)=="0");
		//assert(str_int_ptr(&n)=="0"); //nok
		//assert(str_int_ptr(static_cast<int>(n))=="0");
		assert(str_int_ptr(reinterpret_cast<int*>(q))=="2");
		assert(str_int_ptr(r)=="0");
	
		delete q;
	}
	{
		N n=ZERO_;
		//Base b(ZERO_); //nok
		Base b(n);
	}
	{
		const int x=5;
		int y=2;
		//enum temp { x, y }; //nok compile error ''x/y' redeclared as different kind of symbol'
	}
	return 0;
}