Beispiel #1
0
int alg(const std::vector<int> & A, int l, int r) {
  
  if(l < 0 || r > A.size()-1) {
    return -1;
  }

  int i = (r+l)/2;

  if(r == l) {
    return l;
  }
  if(r-l == 1) {
    if(A[r] >= A[l])
      return r;
    else
      return l;
  }

  // std::cout << "i : " << i << "\n r : " << r << "\n l : " << l << "\n A.size : " << A.size() << "\n\n\n"; 

  if(A[i] >= A[i-1]) {
    return alg(A, i, r);
  }
  else  {
    return alg(A, l, i);
  }
}
TEST(NumLib, TimeSteppingIterationNumberBased2)
{
    std::vector<std::size_t> iter_times_vector = {0, 3, 5, 7};
    std::vector<double> multiplier_vector = {2.0, 1.0, 0.5, 0.25};
    NumLib::IterationNumberBasedAdaptiveTimeStepping alg(1, 31, 1, 10, 1, iter_times_vector, multiplier_vector);

    std::vector<std::size_t> nr_iterations = {2, 2, 2, 4, 6, 8, 4, 4, 2, 2};
    const std::vector<double> expected_vec_t = {1, 2, 4, 8, 16, 24, 26, 28, 30, 31};

    struct IterationNumberUpdate
    {
        IterationNumberUpdate(const std::vector<std::size_t> &vec, std::size_t& counter)
            : _nr_iterations(vec), i(counter) {}

        std::vector<std::size_t> _nr_iterations;
        std::size_t& i;

        void operator()(NumLib::IterationNumberBasedAdaptiveTimeStepping &obj)
        {
            std::size_t n = (i<_nr_iterations.size()) ? _nr_iterations[i++] : 0;
            //INFO("-> NR-iterations=%d", n);
            obj.setNIterations(n);
        }
    };

    std::size_t counter = 0;
    IterationNumberUpdate update(nr_iterations, counter);

    std::vector<double> vec_t = timeStepping(alg, &update);
    //std::cout << vec_t;

    ASSERT_EQ(expected_vec_t.size(), vec_t.size());
    ASSERT_EQ(1u, alg.getNRepeatedSteps());
    ASSERT_ARRAY_NEAR(expected_vec_t, vec_t, expected_vec_t.size(), std::numeric_limits<double>::epsilon());
}
TEST(ContinuationAlgTest, GetSurfaceCellsOffTopAndRightEdges)
{
	Rectangle bounds(-10.0, 1.0, -10.0, 1.0);
	Grid grid(bounds, 1.0);

	Point2D location(0.0, 0.0);
	double radius = 5.0;
	double isoValue = 0.5;
	PointPrimitive primitive(location, radius, isoValue);

	std::list<Primitive *> primitives;
	primitives.push_back(&primitive);

	SummationBlend blend(primitives, isoValue);

	ContinuationAlgorithm alg(&grid, &primitive, &blend);

	std::list<Cell *> surfaceCells = alg.GetSurfaceCells();

	EXPECT_EQ(12, surfaceCells.size());

	ExpectContainsCell(10, 7, surfaceCells);
	ExpectContainsCell(10, 8, surfaceCells);
	ExpectContainsCell(10, 9, surfaceCells);
	ExpectContainsCell(10, 10, surfaceCells);
	ExpectContainsCell(9, 10, surfaceCells);
	ExpectContainsCell(8, 10, surfaceCells);
	ExpectContainsCell(7, 10, surfaceCells);
	ExpectContainsCell(7, 9, surfaceCells);
	ExpectContainsCell(7, 8, surfaceCells);
	ExpectContainsCell(8, 8, surfaceCells);
	ExpectContainsCell(8, 7, surfaceCells);
	ExpectContainsCell(9, 7, surfaceCells);
}
Beispiel #4
0
int main(int numArgs, char ** args)
{
    bool doOrder = true;
    if (numArgs == 2)
    {
        if (!strcmp(args[1], "order"))
            doOrder = true;
        else if (!strcmp(args[1], "rmse"))
            doOrder = false;
        else
        {
            qDebug() << "Argument" << args[1] << "not recognized" << endl;
            qDebug() << "Defaulting to ordering error" << endl;
            doOrder = true;
        } 
    }

    DataBase db;
    db.load();
    Probe probe(&db);
    SvdOrder alg(&db);
    QFile f("Features.dat");

    if (f.exists())
        alg.loadFeatures("Features.dat");
    else
        alg.calculateFeaturesByOrder();

    if (doOrder)
        probe.runProbeOrdering(&alg, "probe");
    else
        probe.runProbe(&alg, "probe");

    alg.saveFeatures("Features.dat");
}
QVariantMap QgsProcessingAlgorithm::run( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback, bool *ok, const QVariantMap &configuration ) const
{
  std::unique_ptr< QgsProcessingAlgorithm > alg( create( configuration ) );
  if ( ok )
    *ok = false;

  bool res = alg->prepare( parameters, context, feedback );
  if ( !res )
    return QVariantMap();

  QVariantMap runRes;
  try
  {
    runRes = alg->runPrepared( parameters, context, feedback );
  }
  catch ( QgsProcessingException &e )
  {
    QgsMessageLog::logMessage( e.what(), QObject::tr( "Processing" ), Qgis::Critical );
    feedback->reportError( e.what() );
    return QVariantMap();
  }

  if ( ok )
    *ok = true;

  QVariantMap ppRes = alg->postProcess( context, feedback );
  if ( !ppRes.isEmpty() )
    return ppRes;
  else
    return runRes;
}
Beispiel #6
0
void programXCF(Jtag &jtag, IOBase &io, BitFile &file)
{
  ProgAlgXCF alg(jtag,io);
  alg.erase();
  alg.program(file);
  return;
}
Beispiel #7
0
void SigGBAction::performAction() {
  mParams.perform();
  mGBParams.perform();

  // read input file
  const std::string inputBasisFile = mParams.inputFileNameStem(0) + ".ideal";
  std::ifstream inputFile(inputBasisFile.c_str());
  if (inputFile.fail())
    mic::reportError("Could not read input file \"" + inputBasisFile + '\n');


  Scanner in(inputFile);
  auto p = MathicIO<>().readRing(true, in);
  auto& ring = *p.first;
  auto& processor = p.second;
  auto basis = MathicIO<>().readBasis(ring, false, in);
  if (processor.schreyering())
    processor.setSchreyerMultipliers(basis);

  SignatureGB alg(
    std::move(basis),
    std::move(processor),
    Reducer::reducerType(mGBParams.mReducer.value()),
    mGBParams.mMonoLookup.value(),
    mGBParams.mMonomialTable.value(),
    mPostponeKoszul.value(),
    mUseBaseDivisors.value(),
    mGBParams.mPreferSparseReducers.value(),
    mUseSingularCriterionEarly.value(),
    mGBParams.mSPairQueue.value());
  alg.setBreakAfter(mGBParams.mBreakAfter.value());
  alg.setPrintInterval(mGBParams.mPrintInterval.value());
  alg.computeGrobnerBasis();

  // print statistics
  alg.displayStats(std::cout);
  alg.displayPaperStats(std::cout);
  {
    std::ofstream statsOut(mParams.inputFileNameStem(0) + ".stats");
    alg.displayStats(statsOut);
    alg.displayPaperStats(statsOut);
  }

  if (mGBParams.mOutputResult.value()) {
    // print basis
    {
      std::ofstream ogb(mParams.inputFileNameStem(0) + ".gb");
      ogb << "-- gb: ----\n";
      alg.getGB()->display(ogb);
    }
      
    // print syzygy basis
    {
      std::ofstream syzygyOut(mParams.inputFileNameStem(0) + ".syz");
      syzygyOut << "-- syz: ----\n";
      alg.getSyzTable()->display(syzygyOut);
      syzygyOut << std::endl;
    }
  }
}
Beispiel #8
0
//Key
Key* Provider::ImportKey(const BYTE* blob, DWORD size, Key* pubKey)
{
	BLOBHEADER blobHeader;
	if(size < sizeof(blobHeader) || blob==NULL)
		throw ::ErrorInvalidParameter();

	memcpy(&blobHeader, blob, sizeof(blobHeader));
	switch(blobHeader.bType)
	{
		case SIMPLEBLOB: break;
		case PUBLICKEYBLOB: break;
		case PRIVATEKEYBLOB: break;
		case PLAINTEXTKEYBLOB: 
			{
				std::unique_ptr<IAlg> alg(m_cryptoFactory.CreateAlg(blobHeader.aiKeyAlg));
				DWORD keyLen =0;
				BYTE tmpSize[sizeof(DWORD)];
				memcpy(&tmpSize, blob+sizeof(blobHeader), sizeof(DWORD));
				std::reverse(tmpSize, tmpSize+sizeof(DWORD));
				memcpy(&keyLen, tmpSize, sizeof(DWORD));
				if(size < (sizeof(blobHeader)+sizeof(DWORD)+keyLen))
					throw ::ErrorInvalidParameter();
				return alg->ImportKey(blob+sizeof(blobHeader)+sizeof(DWORD), keyLen);
			}
			break;	
		default: throw ::NteBadType(); break;
	}

	UNREFERENCED_PARAMETER(pubKey);
	throw NteNoSupported(); //TODO: написать
}
Beispiel #9
0
bool NormalizeData::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   if (pInArgList == NULL || pOutArgList == NULL)
   {
      return false;
   }
   if (!extractInputArgs(pInArgList))
   {
      return false;
   }

   mProgress.report("Begin normalization conversion.", 1, NORMAL);

   { // scope the lifetime
      RasterElement *pResult = static_cast<RasterElement*>(
         Service<ModelServices>()->getElement(mResultName, TypeConverter::toString<RasterElement>(), NULL));
      if (pResult != NULL)
      {
         Service<ModelServices>()->destroyElement(pResult);
      }
   }
   ModelResource<RasterElement> pResult(RasterUtilities::createRasterElement(mResultName,
      mInput.mpDescriptor->getRowCount(), mInput.mpDescriptor->getColumnCount(), mInput.mpDescriptor->getBandCount(),
      FLT8BYTES, mInput.mpDescriptor->getInterleaveFormat(), mInput.mpDescriptor->getProcessingLocation() == IN_MEMORY));
   mInput.mpResult = pResult.get();
   if (mInput.mpResult == NULL)
   {
      mProgress.report("Unable to create result data set.", 0, ERRORS, true);
      return false;
   }
   mInput.mpResultDescriptor = static_cast<const RasterDataDescriptor*>(mInput.mpResult->getDataDescriptor());
   mInput.mpAbortFlag = &mAbortFlag;
   NormalizeDataThreadOutput outputData;
   mta::ProgressObjectReporter reporter("Normalizing", mProgress.getCurrentProgress());
   mta::MultiThreadedAlgorithm<NormalizeDataThreadInput, NormalizeDataThreadOutput, NormalizeDataThread>     
          alg(Service<ConfigurationSettings>()->getSettingThreadCount(), mInput, outputData, &reporter);
   switch(alg.run())
   {
   case mta::SUCCESS:
      if (!mAbortFlag)
      {
         mProgress.report("Normalization complete.", 100, NORMAL);
         if (!displayResult())
         {
            return false;
         }
         pResult.release();
         mProgress.upALevel();
         return true;
      }
      // fall through
   case mta::ABORT:
      mProgress.report("Normalization aborted.", 0, ABORT, true);
      return false;
   case mta::FAILURE:
      mProgress.report("Normalization failed.", 0, ERRORS, true);
      return false;
   }
   return true; // make the compiler happy
}
Beispiel #10
0
void programXCF(Jtag &jtag, IOBase &io, BitFile &file, int bs)
{
  ProgAlgXCF alg(jtag,io,bs);
  alg.erase();
  alg.program(file);
  alg.reconfig();
  return;
}
Beispiel #11
0
int alg(int m, int n) {
    antal++;

    if (m == 0 && n == 0) {
        v++;
    } else {
        if (m>0) {
            printf("v");
            alg(m-1,n);
        }
        if (n>0) {
            printf("h");
            alg(m,n-1);
        }
        printf("u");
    }
}
Beispiel #12
0
int main() {
  srand(time(0));
  std::vector <int> vec;
  for(int i = 0; i < 100; i++) {
    vec = get_vals(40);
    // print_vec(vec);
    int ind = alg(vec, 0, vec.size()-1);
    std::cout << check_results(vec, ind) << "\n";
  }
}
double CICHWithFurtherPriorityQueue::GetExactGeoDisBetween(const CRichModel& inputModel, int indexOfSource, int indexOfDest)
{
	vector<int> sources;
	sources.push_back(indexOfSource);
	set<int> dests;
	dests.insert(indexOfDest);
	CICHWithFurtherPriorityQueue alg(inputModel, sources, dests);
	alg.Execute();
	return alg.m_InfoAtVertices[indexOfDest].disUptodate;
}
Beispiel #14
0
int main(int argc, char* args[]) {
//    int rad,kol;
//	for (rad=0; rad<10; rad++) {
//		for (kol=0; kol<10; kol++) {
//			printf("Antal vagar(%d,%d): %6d  (antal anrop=%d)\n",rad,kol,alg(rad,kol),antal);
//			antal = 0;
//		}
//	}
    alg(2,3);
    exit(EXIT_SUCCESS);
}
Beispiel #15
0
void ECBCipherMode::Encrypt(IOData &data){
 


    switch (cipher){
	   case AES:   {
			   CryptoPP::AES::Encryption alg(security->key, security->key.size());
               int blockCount=FillAndAlignOutputBuffer(data,alg.BlockSize());
			   for (int block=0; block<blockCount; block++)
				 alg.ProcessBlock(data.out.data+block*alg.BlockSize()); 
	       }
		   break;
	   case GOST_28147_89: {
			   CryptoPP::GOST::Encryption alg(security->key, security->key.size());
               int blockCount=FillAndAlignOutputBuffer(data,alg.BlockSize());
			   for (int block=0; block<blockCount; block++)
				 alg.ProcessBlock(data.out.data+block*alg.BlockSize());
		   }
		   break;
	 }
}
Beispiel #16
0
void ECBCipherMode::Decrypt(IOData &data){

	data.out.fill(data.in);

	//Decrypt input buffer
    switch (cipher){
	   case AES: {  
			   CryptoPP::AES::Decryption alg(security->key, security->key.size());
	           int blockCount=data.in.size()/alg.BlockSize();
			   for (int block=0; block<blockCount; block++)
				 alg.ProcessBlock(data.out.data+block*alg.BlockSize());          
		  }
		   break;
	   case GOST_28147_89: {
             CryptoPP::GOST::Decryption alg(security->key, security->key.size());
	           int blockCount=data.in.size()/alg.BlockSize();
		     for (int block=0; block<blockCount; block++)
               alg.ProcessBlock(data.out.data+block*alg.BlockSize());
		   }
		   break;
	 }  
}
Beispiel #17
0
/** Gets the names and categories of all the currently available algorithms
*
*  @return A vector of pairs of algorithm names and categories
*/
const std::vector<std::pair<std::string,std::string> >
AlgorithmManagerImpl::getNamesAndCategories() const
{
    std::vector<std::pair<std::string,std::string> > retVector;

    for (unsigned int i=0; i < m_managed_algs.size(); ++i)
    {
        std::pair<std::string,std::string> alg(m_managed_algs[i]->name(),m_managed_algs[i]->category());
        retVector.push_back(alg);
    }

    return retVector;
}
TEST(ContinuationAlgTest, GetUnvisitedNeighboursTopRightCorner)
{
	Rectangle bounds(-2.0, 2.0, -2.0, 2.0);
	Grid grid(bounds, 1.0);

	ContinuationAlgorithm alg(&grid, NULL, NULL);
	Cell *targetCell = grid.GetCell(3, 3);

	std::list<Cell *> neighbours = alg.GetUnvisitedNeighbourCells(targetCell);

	EXPECT_EQ(3, neighbours.size());
	ExpectContainsCell(3, 2, neighbours);
	ExpectContainsCell(2, 2, neighbours);
	ExpectContainsCell(2, 3, neighbours);
}
Beispiel #19
0
int main(int argc, char **argv)
{
	CVideoLoader loader;
	std::unique_ptr<CMeasuredData> dataPtr;

	std::unique_ptr<State> state( new MarkState() );

	CTldAlgorithm alg("Tld");
	while (nullptr != state) 
	{
		state = state->handle(loader, alg, dataPtr);	 	
	}

	return 0;
}
Beispiel #20
0
int main(int argc, char **argv)
{
	if(argc != 6 && argc != 8)
	{
		cout << "Error: invalid command!\nPlease use ./vmsim –n <numframes> -a <opt|clock|aging|lru> [-r <refresh>] <tracefile>" << endl;
		return 0;
	}
	
	unsigned int nframes; 	/** # of Frames **/
	if(sscanf(argv[2], "%u", &nframes) == -1 || (nframes & (nframes - 1)) || nframes > 64)		/** x &(x-1) produces 0 if x is of the form 2^n. **/ 
	{														
		cout << "Error: invalid argument for frame numbers!\nPlease use 8, 16, 32, or 64 instead." << endl;
		return 0;
	}
	
	string alg(argv[4]); 	/** Algorithm **/
	
	if(alg == "aging")
	{
		unsigned int period; /** Refreshing Period **/
		sscanf(argv[6], "%u", &period);
		run_aging(argv[7], nframes, period); 	/** will be using a priority deque to simulate the physical memory. **/
	}
	else
	{
		if(alg == "opt")
			run_optimal(argv[5], nframes);		/** will be using an unordered_set to simulate the physical memory. **/
		else if(alg == "clock")
			run_clock(argv[5], nframes); 		/** will be using a doubly-linked list to simulate the physical memory. **/
		else if(alg == "lru")
			run_lru(argv[5], nframes);   		/** will be using a stack to simulate the physical memory. **/
		else
		{
			cout << "Error: unrecognised algorithm.\nPlease use opt, clock, aging, or lru instead." << endl;
			return 0;
		}
	}
	
	cout << "\n\nAlgorithm:\t" << alg << endl;
	cout << "Number of frames:\t" << nframes << endl;
	cout << "Total memory accesses:\t" << total_accesses << endl;
	cout << "Total page faults:\t" << page_fault_count << endl;
	cout << "Total writes to disk:\t" << write_to_disk_count << "\n\n" << endl;
	
	return 0;
}
    std::vector<Solution> HeuristicsSolver::solve_elem_on_generic_graph(bool smart) const {
        // std::vector<Solution> sols;
        auto local_erased = smart ? g->smart_reduce_graph(0, prob->params.p_acceleration_max_arcs_share, erased)
                                  : g->reduce_graph(prob->params.cp_acceleration_arcs_share, erased);        
        //
        // std::vector<Path> optimal_paths;
        // std::vector<ElementaryLabel> optimal_labels;
        //
        // NodeIdFunctor nf(g);
        // ArcIdFunctor af(g);
        //
        // auto vc = g->vessel_class;
        // VisitablePorts pf = prob->data.get_ports_list();
        //
        // try {
        //     boost::r_c_shortest_paths(
        //         g->graph,
        //         make_property_map<Vertex>(nf),
        //         make_property_map<Edge>(af),
        //         g->get_source_vertex().second,
        //         g->get_sink_vertex().second,
        //         optimal_paths,
        //         optimal_labels,
        //         ElementaryLabel(g, vc->capacity, vc->capacity, 0, pf),
        //         LabelExtender(local_erased),
        //         Dominance(),
        //         std::allocator<boost::r_c_shortest_paths_label<BGraph, ElementaryLabel>>(),
        //         boost::default_r_c_shortest_paths_visitor()
        //     );
        // } catch(...) {
        //     g->dump();
        //     throw;
        // }
        //
        // for(auto i = 0u; i < optimal_paths.size(); i++) {
        //     sols.push_back(
        //         Solution(optimal_paths[i], g->calculate_path_cost(optimal_paths[i]), optimal_labels[i].cost, vc, g));
        // }
        //
        // return sols;

        LabelExtender extender(local_erased);
        LabellingAlgorithm<ElementaryLabel, LabelExtender> alg(g);
        return alg.solve(g->get_source_vertex().second, g->get_sink_vertex().second, ElementaryLabel(*g, prob->data.get_ports_list()), extender);
    }
Beispiel #22
0
void encrypt(char *x, int *out, int size)
{
    int buf;
    int ind=0;
    int inc=0;
    int pub=nsqrandr(100,1000);
    keyGen(pub);
    int dex=(pub*private2)-(7*private2);
    out[0]=dex^private2;
    while(ind < size && x[ind] != '\0')
    {
        buf=alg(x[ind],pub,inc);
        out[ind+1]=buf;
        ind++;
        inc++;
        if(inc>=strlen(XKey))
            inc=0;
    }
//    print(out, size);

}
TEST(ContinuationAlgTest, GetSeedCell)
{
	Rectangle bounds(-10.0, 10.0, -10.0, 10.0);
	Grid grid(bounds, 1.0);

	Point2D location(0.0, 0.0);
	double radius = 5.0;
	double isoValue = 0.5;
	PointPrimitive primitive(location, radius, isoValue);

	std::list<Primitive *> primitives;
	primitives.push_back(&primitive);

	SummationBlend blend(primitives, isoValue);

	ContinuationAlgorithm alg(&grid, &primitive, &blend);
	Cell *seedCell = alg.GetSeedCell();

	EXPECT_EQ(10, seedCell->GetRow());
	EXPECT_EQ(7, seedCell->GetColumn());
}
int main(int argc, char *argv[])
{
	size_t i;
	int (*alg)(struct xpath_tree *, struct xpath_tree *);
	clock_t start, end, acc = 0;
	struct xpath_tree *q1, *q2;

	if (argc != 4) {
		fprintf(stderr, "Usage: %s algorithm query1 query2\n", argv[0]);
		exit(EXIT_FAILURE);
	}

	if (strcmp(argv[1], "canonical") == 0) {
		alg = the_canonical_model;
	} else if (strcmp(argv[1], "homomorphism") == 0) {
		alg = the_homomorphism_technique;
	} else {
		fprintf(stderr, "Error: Invalid algorithm \"%s\".\n", argv[1]);
		exit(EXIT_FAILURE);
	}

	q1 = xpath_parser(argv[2]);
	q2 = xpath_parser(argv[3]);

	for (i = 0; i < ITERATIONS; ++i) {
		start = clock();
		alg(q1, q2);
		end = clock();
		acc += end - start;
	}

	delete_xpath_tree(q1);
	delete_xpath_tree(q2);

	printf("%f\n", (double)acc / (double)ITERATIONS);

	return 0;
}
 bool contains(uint item) {
     KDevelop::EmbeddedTreeAlgorithms<TestItem, TestItemHandler> alg(data.data(), data.size(), m_centralFree);
     return alg.indexOf(TestItem(item)) != -1;
 }
Beispiel #26
0
void ddm(const Matrix<T>& rays,
    Parameters& params,
    bool intArith,
    const T &zerotol,
    Matrix<T>& ine,
    std::vector<size_t>& ext)
{
    if (params.setRepresentation == SetRepresentation::BitField)
    {
        if (rays.nrows() <= 32)
        {
            Algorithm<T, BitFieldSet<32> > alg(params);
            alg.run(rays, intArith, zerotol, ine, ext);
            return;
        }
        if (rays.nrows() <= 64)
        {
            Algorithm<T, BitFieldSet<64> > alg(params);
            alg.run(rays, intArith, zerotol, ine, ext);
            return;
        }
        if (rays.nrows() <= 96)
        {
            Algorithm<T, BitFieldSet<96> > alg(params);
            alg.run(rays, intArith, zerotol, ine, ext);
            return;
        }
        if (rays.nrows() <= 128)
        {
            Algorithm<T, BitFieldSet<128> > alg(params);
            alg.run(rays, intArith, zerotol, ine, ext);
            return;
        }

        // If impossible to find appropriate bitfield, use vector-based sets.
        params.setRepresentation == SetRepresentation::SortedVector;
    }

    // If vector-based set is used, choose minimal appropriate element type.
    if (rays.nrows() <= (1ULL << (8 * sizeof(unsigned char))))
    {
        Algorithm<T, VectorSet<unsigned char> > alg(params);
        alg.run(rays, intArith, zerotol, ine, ext);
        return;
    }
    if (rays.nrows() <= (1ULL << (8 * sizeof(unsigned short))))
    {
        Algorithm< T, VectorSet<unsigned short> > alg(params);
        alg.run( rays, intArith, zerotol, ine, ext);
        return;
    }
    if (rays.nrows() <= (1ULL << (8 * sizeof(unsigned int))))
    {
        Algorithm<T, VectorSet<unsigned int> > alg(params);
        alg.run(rays, intArith, zerotol, ine, ext);
        return;
    }
    // If nothing else fits, use unsigned long.
    Algorithm<T, VectorSet<unsigned long> > alg(params);
    alg.run(rays, intArith, zerotol, ine, ext);
}
Beispiel #27
0
int main( )
{
    USING_NAMESPACE_ACADO


    // INTRODUCE THE VARIABLES:
    // -------------------------
	DifferentialState xB; //Body Position
	DifferentialState xW; //Wheel Position
	DifferentialState vB; //Body Velocity
	DifferentialState vW; //Wheel Velocity

	Control F;
	Disturbance R;

	double mB = 350.0;
	double mW = 50.0;
	double kS = 20000.0;
	double kT = 200000.0;


    // DEFINE A DIFFERENTIAL EQUATION:
    // -------------------------------
    DifferentialEquation f;

	f << dot(xB) == vB;
	f << dot(xW) == vW;
	f << dot(vB) == ( -kS*xB + kS*xW + F ) / mB;
	f << dot(vW) == (  kS*xB - (kT+kS)*xW + kT*R - F ) / mW;


    // DEFINE LEAST SQUARE FUNCTION:
    // -----------------------------
    Function h;

    h << xB;
    h << xW;
	h << vB;
    h << vW;
	h << F;

    DMatrix Q(5,5); // LSQ coefficient matrix
	Q(0,0) = 10.0;
	Q(1,1) = 10.0;
	Q(2,2) = 1.0;
	Q(3,3) = 1.0;
	Q(4,4) = 1.0e-8;

    DVector r(5); // Reference
    r.setAll( 0.0 );


    // DEFINE AN OPTIMAL CONTROL PROBLEM:
    // ----------------------------------
    const double tStart = 0.0;
    const double tEnd   = 1.0;

    OCP ocp( tStart, tEnd, 20 );

    ocp.minimizeLSQ( Q, h, r );

	ocp.subjectTo( f );

	ocp.subjectTo( -200.0 <= F <= 200.0 );
	ocp.subjectTo( R == 0.0 );


    // SETTING UP THE REAL-TIME ALGORITHM:
    // -----------------------------------
	RealTimeAlgorithm alg( ocp,0.025 );
	alg.set( MAX_NUM_ITERATIONS, 1 );
	alg.set( PLOT_RESOLUTION, MEDIUM );

	GnuplotWindow window;
	  window.addSubplot( xB, "Body Position [m]" );
	  window.addSubplot( xW, "Wheel Position [m]" );
	  window.addSubplot( vB, "Body Velocity [m/s]" );
	  window.addSubplot( vW, "Wheel Velocity [m/s]" );
	  window.addSubplot( F,  "Damping Force [N]" );
	  window.addSubplot( R,  "Road Excitation [m]" );

	alg << window;


    // SETUP CONTROLLER AND PERFORM A STEP:
    // ------------------------------------
	StaticReferenceTrajectory zeroReference( "ref.txt" );

	Controller controller( alg,zeroReference );

	DVector y( 4 );
	y.setZero( );
	y(0) = 0.01;

	if (controller.init( 0.0,y ) != SUCCESSFUL_RETURN)
		exit( 1 );
	if (controller.step( 0.0,y ) != SUCCESSFUL_RETURN)
		exit( 1 );

    return EXIT_SUCCESS;
}
Beispiel #28
0
void svg_precompute(const string& input_obj_name, const int fixed_k, string& svg_file_name) {
  //Step 1. Initialize models
  CRichModel model(input_obj_name);
  model.Preprocess();

  int begin_vertex_index = 0;

  int end_vertex_index = model.GetNumOfVerts() - 1;

  svg_file_name = input_obj_name.substr(0,input_obj_name.length() - 4 ) 
    + "_SVG_k" + to_string(fixed_k) +  ".binary";

  ofstream output_file (svg_file_name.c_str() , ios::out | ios::binary);
  int num_of_vertex = end_vertex_index - begin_vertex_index + 1;
  HeadOfSVG head_of_svg(begin_vertex_index , end_vertex_index , num_of_vertex );     
  output_file.write((char*)&head_of_svg , sizeof(head_of_svg));

  ElapasedTime time_once;

  double dis_time_total(0);
  double past_time(0);
  //#pragma omp parallel for
  for (int tmp_source = begin_vertex_index;tmp_source <= end_vertex_index;++tmp_source) {

    if (time_once.getTime() -  past_time > 5 ) {
      past_time = time_once.getTime();
      char buf[128];
      sprintf(buf, "Computed %.0lf percent", (double) tmp_source  * 100. / (end_vertex_index - begin_vertex_index));
      time_once.printTime(buf );
    }
    ElapasedTime dis_time;
    int source_index = tmp_source;
    double farthest = 0.0;
    //Step 2: Construct a group of source points;
    vector<int> sources;
    sources.push_back(source_index);
    //Step 3: Construct a new algorithm object
    CICHWithFurtherPriorityQueue alg(model, sources);
    //Step 4: Locally propagate wavefronts and stop at the prescribed geodesic distance.
    set<int> fixedDests;
    //The first parameter is the distance threshold, 
    //and the second is to return those vertices where the geodesic distance makes sense.
    double max_radius = 1e10;
    alg.ExecuteLocally_SVG(max_radius, fixedDests,fixed_k);
    dis_time_total += dis_time.getTime();
    //printf("Totally collected: %d\n", fixedDests.size());
    set<int>::iterator itr;
    int cnt = 0;
    vector<pair<int,double>> dests;

    struct node {
      int id;
      double dis;
      int operator<(const node & other) const{
        return dis < other.dis;
      }
    };
    vector<node> covered_points;
    covered_points.resize(fixedDests.size());
    int _index = 0;
    for (itr = fixedDests.begin(); itr != fixedDests.end(); ++itr) {
      int v = *itr;
      map<int, CICHWithFurtherPriorityQueue::InfoAtVertex>::const_iterator it = alg.m_InfoAtVertices.find(v);
      int indexOfParent = it->second.indexOfParent;
      int parent = 0;
      covered_points[_index].id = v;
      covered_points[_index].dis = it->second.disUptodate;
      _index ++;
      if (farthest < it->second.disUptodate){
        farthest = it->second.disUptodate;
      }
      if (it->second.fParentIsPseudoSource) {
        parent = indexOfParent;
      } else {
        parent = it->second.indexOfRootVertOfParent;
      }
      if (parent == sources[0]) {
        dests.push_back(pair<int,double>(v , alg.m_InfoAtVertices[v].disUptodate));
        ++cnt;
      }
    }
    std::sort(covered_points.begin(), covered_points.end());
    std::map<int, int> mp;
    for(int i = 0; i < covered_points.size(); ++i){
      mp[covered_points[i].id] = i;
    }

    BodyHeadOfSVG body_header(source_index , dests.size());
    output_file.write((char*)&body_header , sizeof(body_header));

    vector<BodyPartOfSVGWithK> body_parts(dests.size());
    for(int i = 0; i < dests.size(); ++i) {
      BodyPartOfSVGWithK body_part(dests[i].first , dests[i].second , mp[dests[i].first]);
      body_parts[i] = body_part;
    }
    sort(body_parts.begin() , body_parts.end());
    
    

    for (int i = 0; i < body_parts.size(); ++i) {
      BodyPartOfSVG b = body_parts[i];
      output_file.write( (char*)&b , sizeof(b));
    }
  }

  time_once.printTime("time past ");
  output_file.close();

}
bool ConvolutionFilterShell::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   if (pInArgList == NULL || pOutArgList == NULL)
   {
      return false;
   }
   if (!extractInputArgs(pInArgList))
   {
      return false;
   }
   if (!populateKernel() || mInput.mKernel.Nrows() % 2 == 0 || mInput.mKernel.Ncols() % 2 == 0)
   {
      mProgress.report("Invalid kernel.", 0, ERRORS, true);
      return false;
   }
   BitMaskIterator iterChecker((mpAoi == NULL) ? NULL : mpAoi->getSelectedPoints(), 0, 0,
      mInput.mpDescriptor->getColumnCount() - 1, mInput.mpDescriptor->getRowCount() - 1);
   EncodingType resultType = mInput.mForceFloat ? EncodingType(FLT8BYTES) : mInput.mpDescriptor->getDataType();
   if (resultType == INT4SCOMPLEX)
   {
      resultType = INT4SBYTES;
   }
   else if (resultType == FLT8COMPLEX)
   {
      resultType = FLT8BYTES;
   }
   if (!isBatch())
   {
      RasterElement* pResult = static_cast<RasterElement*>(
         Service<ModelServices>()->getElement(mResultName, TypeConverter::toString<RasterElement>(), NULL));
      if (pResult != NULL)
      {
         if (QMessageBox::question(Service<DesktopServices>()->getMainWidget(), "Result data set exists",
            "The result data set already exists. Would you like to replace it?",
            QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::No)
         {
            return false;
         }
         Service<ModelServices>()->destroyElement(pResult);
      }
   }
   mProgress.report("Begin convolution matrix execution.", 0, NORMAL);

   ModelResource<RasterElement> pResult(RasterUtilities::createRasterElement(
      mResultName, iterChecker.getNumSelectedRows(), iterChecker.getNumSelectedColumns(),
      mInput.mBands.size(), resultType, mInput.mpDescriptor->getInterleaveFormat(),
      mInput.mpDescriptor->getProcessingLocation() == IN_MEMORY));
   pResult->copyClassification(mInput.mpRaster);
   pResult->getMetadata()->merge(mInput.mpDescriptor->getMetadata()); //copy original metadata
   //chip metadata by bands
   vector<DimensionDescriptor> orgBands = mInput.mpDescriptor->getBands();
   vector<DimensionDescriptor> newBands;
   newBands.reserve(mInput.mBands.size());
   for (unsigned int index = 0; index < mInput.mBands.size(); ++index)
   {
      unsigned int selectedBand = mInput.mBands[index];
      if (selectedBand < orgBands.size())
      {
         newBands.push_back(orgBands[selectedBand]);
      }
   }
   RasterUtilities::chipMetadata(pResult->getMetadata(), mInput.mpDescriptor->getRows(),
      mInput.mpDescriptor->getColumns(), newBands);
   mInput.mpResult = pResult.get();
   if (mInput.mpResult == NULL)
   {
      mProgress.report("Unable to create result data set.", 0, ERRORS, true);
      return false;
   }
   mInput.mpAbortFlag = &mAborted;
   mInput.mpIterCheck = &iterChecker;
   ConvolutionFilterThreadOutput outputData;
   mta::ProgressObjectReporter reporter("Convolving", mProgress.getCurrentProgress());
   mta::MultiThreadedAlgorithm<ConvolutionFilterThreadInput,
                               ConvolutionFilterThreadOutput,
                               ConvolutionFilterThread>
          alg(mta::getNumRequiredThreads(iterChecker.getNumSelectedRows()), mInput, outputData, &reporter);
   switch(alg.run())
   {
   case mta::SUCCESS:
      if (!isAborted())
      {
         mProgress.report("Convolution filter complete.", 100, NORMAL);
         SpatialDataView* pView = displayResult();
         if (Service<ApplicationServices>()->isInteractive() && pView == NULL)
         {
            return false;
         }
         pOutArgList->setPlugInArgValue("View", pView);

         pResult.release();
         mProgress.upALevel();
         return true;
      }
      // fall through
   case mta::ABORT:
      mProgress.report("Convolution filter aborted.", 0, ABORT, true);
      return false;
   case mta::FAILURE:
      mProgress.report("Convolution filter failed.", 0, ERRORS, true);
      return false;
   default:
      VERIFY(false); // can't happen
   }
}
Beispiel #30
0
int main(int argc, char *argv[]) 
{
  if (argc<2) {
    cout << "\nUsage: " << argv[0] << " L [c=2 w=64 k=80 d=1]" << endl;
    cout << "  L is the number of levels\n";
    cout << "  optional c is number of columns in the key-switching matrices (default=2)\n";
    cout << "  optional w is Hamming weight of the secret key (default=64)\n";
    cout << "  optional k is the security parameter (default=80)\n";
    cout << "  optional d specifies GF(2^d) arithmetic (default=1, must be <=16)\n";
    //    cout << "  k is the security parameter\n";
    //    cout << "  m determines the ring mod Phi_m(X)" << endl;
    cout << endl;
    exit(0);
  }
  cout.unsetf(ios::floatfield);
  cout.precision(4);

  long L = atoi(argv[1]);
  long c = 2;
  long w = 64;
  long k = 80;
  long d = 1;
  if (argc>2) c = atoi(argv[2]);
  if (argc>3) w = atoi(argv[3]);
  if (argc>4) k = atoi(argv[4]);
  if (argc>5) d = atoi(argv[5]);

  if (d>16) Error("d cannot be larger than 16\n");

  cout << "\nTesting FHE with parameters L="<<L
       << ", c="<<c<<", w="<<w<<", k="<<k<<", d="<<d<< endl;

  // get a lower-bound on the parameter N=phi(m):
  // 1. Empirically, we use ~20-bit small primes in the modulus chain (the main
  //    constraints is that 2m must divide p-1 for every prime p). The first
  //    prime is larger, a 40-bit prime. (If this is a 32-bit machine then we
  //    use two 20-bit primes instead.)
  // 2. With L levels, the largest modulus for "fresh ciphertexts" has size
  //          q0 ~ p0 * p^{L} ~ 2^{40+20L}
  // 3. We break each ciphertext into upto c digits, do each digit is as large
  //    as    D=2^{(40+20L)/c}
  // 4. The added noise variance term from the key-switching operation is
  //    c*N*sigma^2*D^2, and this must be mod-switched down to w*N (so it is
  //    on part with the added noise from modulus-switching). Hence the ratio
  //    P that we use for mod-switching must satisfy c*N*sigma^2*D^2/P^2<w*N,
  //    or    P > sqrt(c/w) * sigma * 2^{(40+20L)/c}
  // 5. With this extra P factor, the key-switching matrices are defined
  //    relative to a modulus of size
  //          Q0 = q0*P ~ sqrt{c/w} sigma 2^{(40+20L)(1+1/c)}
  // 6. To get k-bit security we need N>log(Q0/sigma)(k+110)/7.2, i.e. roughly
  //          N > (40+20L)(1+1/c)(k+110) / 7.2

  long ptxtSpace = 2;
  double cc = 1.0+(1.0/(double)c);
  long N = (long) ceil((pSize*L+p0Size)*cc*(k+110)/7.2);
  cout << "  bounding phi(m) > " << N << endl;

#if 0  // A small m for debugging purposes
  long m = 15;
#else
  // pre-computed values of [phi(m),m,d]
  long ms[][4] = {
    //phi(m)  m  ord(2) c_m*1000
    { 1176,  1247, 28,  3736},
    { 1936,  2047, 11,  3870},
    { 2880,  3133, 24,  3254},
    { 4096,  4369, 16,  3422},
    { 5292,  5461, 14,  4160},
    { 5760,  8435, 24,  8935},
    { 8190,  8191, 13,  1273},
    {10584, 16383, 14,  8358},
    {10752, 11441, 48,  3607},
    {12000, 13981, 20,  2467},
    {11520, 15665, 24, 14916},
    {14112, 18415, 28, 11278},
    {15004, 15709, 22,  3867},
    {15360, 20485, 24, 12767},
 // {16384, 21845, 16, 12798},
    {17208 ,21931, 24, 18387},
    {18000, 18631, 25,  4208},
    {18816, 24295, 28, 16360},
    {19200, 21607, 40, 35633},
    {21168, 27305, 28, 15407},
    {23040, 23377, 48,  5292},
    {24576, 24929, 48,  5612},
    {27000, 32767, 15, 20021},
    {31104, 31609, 71,  5149},
    {42336, 42799, 21,  5952},
    {46080, 53261, 24, 33409},
    {49140, 57337, 39,  2608},
    {51840, 59527, 72, 21128},
    {61680, 61681, 40,  1273},
    {65536, 65537, 32,  1273},
    {75264, 82603, 56, 36484},
    {84672, 92837, 56, 38520}
  };

#if 0

  for (long i = 0; i < 25; i++) {
    long m = ms[i][1];
    PAlgebra alg(m);
    alg.printout();
    cout << "\n";
    // compute phi(m) directly
    long phim = 0;
    for (long j = 0; j < m; j++)
      if (GCD(j, m) == 1) phim++;

    if (phim != alg.phiM()) cout << "ERROR\n";
  }

  exit(0);


#endif



  // find the first m satisfying phi(m)>=N and d | ord(2) in Z_m^*
  long m = 0;
  for (unsigned i=0; i<sizeof(ms)/sizeof(long[3]); i++) 
    if (ms[i][0]>=N && (ms[i][2] % d) == 0) {
      m = ms[i][1];
      c_m = 0.001 * (double) ms[i][3];
      break;
    }
  if (m==0) Error("Cannot support this L,d combination");
#endif
  //  m = 257;
  FHEcontext context(m);
#if 0
  context.stdev = to_xdouble(0.5); // very low error
#endif
  activeContext = &context; // Mark this as the "current" context

  context.zMstar.printout();
  cout << endl;


  // Set the modulus chain

#if 1
  // The first 1-2 primes of total p0size bits
  #if (NTL_SP_NBITS > p0Size)
    AddPrimesByNumber(context, 1, 1UL<<p0Size); // add a single prime
  #else
    AddPrimesByNumber(context, 2, 1UL<<(p0Size/2)); // add two primes
  #endif
#endif

  // The next L primes, as small as possible
  AddPrimesByNumber(context, L);

  ZZ productOfCtxtPrimes = context.productOfPrimes(context.ctxtPrimes);
  double productSize = context.logOfProduct(context.ctxtPrimes);

  // might as well test that the answer is roughly correct
  cout << "  context.logOfProduct(...)-log(context.productOfPrimes(...)) = "
       << productSize-log(productOfCtxtPrimes) << endl;

  // calculate the size of the digits

  context.digits.resize(c);
  IndexSet s1;
#if 0
  for (long i=0; i<c-1; i++) context.digits[i] = IndexSet(i,i);
  context.digits[c-1] = context.ctxtPrimes / IndexSet(0,c-2);
  AddPrimesByNumber(context, 2, 1, true);
#else
  double sizeSoFar = 0.0;
  double maxDigitSize = 0.0;
  if (c>1) {   // break ciphetext into a few digits
    double dsize = productSize/c;  // initial estimate
    double target = dsize-(pSize/3.0);
    long idx = context.ctxtPrimes.first();
    for (long i=0; i<c-1; i++) { // compute next digit
      IndexSet s;
      while (idx <= context.ctxtPrimes.last() && sizeSoFar < target) {
        s.insert(idx);
	sizeSoFar += log((double)context.ithPrime(idx));
	idx = context.ctxtPrimes.next(idx);
      }
      context.digits[i] = s;
      s1.insert(s);
      double thisDigitSize = context.logOfProduct(s);
      if (maxDigitSize < thisDigitSize) maxDigitSize = thisDigitSize;
      cout << "  digit #"<<i+1<< " " <<s << ": size " << thisDigitSize << endl;
      target += dsize;
    }
    IndexSet s = context.ctxtPrimes / s1; // all the remaining primes
    context.digits[c-1] = s;
    double thisDigitSize = context.logOfProduct(s);
    if (maxDigitSize < thisDigitSize) maxDigitSize = thisDigitSize;
    cout << "  digit #"<<c<< " " <<s << ": size " << thisDigitSize << endl;
  }
  else { 
    maxDigitSize = context.logOfProduct(context.ctxtPrimes);
    context.digits[0] = context.ctxtPrimes;
  }

  // Add primes to the chain for the P factor of key-switching
  double sizeOfSpecialPrimes 
    = maxDigitSize + log(c/(double)w)/2 + log(context.stdev *2);

  AddPrimesBySize(context, sizeOfSpecialPrimes, true);
#endif

  cout << "* ctxtPrimes: " << context.ctxtPrimes 
       << ", log(q0)=" << context.logOfProduct(context.ctxtPrimes) << endl;
  cout << "* specialPrimes: " << context.specialPrimes
       << ", log(P)=" << context.logOfProduct(context.specialPrimes) << endl;

  for (long i=0; i<context.numPrimes(); i++) {
    cout << "  modulus #" << i << " " << context.ithPrime(i) << endl;
  }
  cout << endl;

  setTimersOn();
  const ZZX& PhimX = context.zMstar.PhimX(); // The polynomial Phi_m(X)
  long phim = context.zMstar.phiM();         // The integer phi(m)
  FHESecKey secretKey(context);
  const FHEPubKey& publicKey = secretKey;

#if 0 // Debug mode: use sk=1,2
  DoubleCRT newSk(to_ZZX(2), context);
  long id1 = secretKey.ImportSecKey(newSk, 64, ptxtSpace);
  newSk -= 1;
  long id2 = secretKey.ImportSecKey(newSk, 64, ptxtSpace);
#else
  long id1 = secretKey.GenSecKey(w,ptxtSpace); // A Hamming-weight-w secret key
  long id2 = secretKey.GenSecKey(w,ptxtSpace); // A second Hamming-weight-w secret key
#endif

  ZZX zero = to_ZZX(0);
//  Ctxt zeroCtxt(publicKey);

  /******************************************************************/
  /**                      TESTS BEGIN HERE                       ***/
  /******************************************************************/


  cout << "ptxtSpace = " << ptxtSpace << endl;

  GF2X G;          // G is the AES polynomial, G(X)= X^8 +X^4 +X^3 +X +1
  SetCoeff(G,8); SetCoeff(G,4); SetCoeff(G,3); SetCoeff(G,1); SetCoeff(G,0);
  GF2X X;
  SetX(X);
  
#if 1
  // code for rotations...

  {
    GF2X::HexOutput = 1;
    
    const PAlgebra& al = context.zMstar;
    const PAlgebraModTwo& al2 = context.modTwo;

    long ngens = al.numOfGens();
    long nslots = al.NSlots();
    DoubleCRT tmp(context);

    vector< vector< DoubleCRT > > maskTable;

    maskTable.resize(ngens);
    for (long i = 0; i < ngens; i++) {
      if (i==0 && al.SameOrd(i)) continue;
      long ord = al.OrderOf(i);
      maskTable[i].resize(ord+1, tmp);
      for (long j = 0; j <= ord; j++) {
        // initialize the mask that is 1 whenever
        // the ith coordinate is at least j

        vector<GF2X> maps, alphas, betas;

        al2.mapToSlots(maps, G); // Change G to X to get bits in the slots
        alphas.resize(nslots);

        for (long k = 0; k < nslots; k++) 
          if (coordinate(al, i, k) >= j)
               alphas[k] = 1;
          else alphas[k] = 0;

       GF2X ptxt;
       al2.embedInSlots(ptxt, alphas, maps);

       // Sanity-check, make sure that encode/decode works as expected
       al2.decodePlaintext(betas, ptxt, G, maps);
       for (long k = 0; k < nslots; k++) {
	 if (alphas[k] != betas[k]) {
	   cout << " Mask computation failed, i="<<i<<", j="<<j<<"\n";
	   return 0;
	 }
       }
       maskTable[i][j] = to_ZZX(ptxt);
      }
    }

  vector<GF2X> maps;
  al2.mapToSlots(maps, G);

  vector<GF2X> alphas(nslots);
  for (long i=0; i < nslots; i++) 
    random(alphas[i], 8); // random degree-7 polynomial mod 2

  for (long amt = 0; amt < 20; amt++) {

    cout << ".";

     GF2X ptxt;
     al2.embedInSlots(ptxt, alphas, maps);

     DoubleCRT pp(context);
     pp = to_ZZX(ptxt);

     rotate(pp, amt, maskTable);

     GF2X ptxt1 = to_GF2X(to_ZZX(pp));

     vector<GF2X> betas;
     al2.decodePlaintext(betas, ptxt1, G, maps);

     for (long i = 0; i < nslots; i++) {
       if (alphas[i] != betas[(i+amt)%nslots]) {
	 cout << " amt="<<amt<<" oops\n";
          return 0;
       }
     }
   }

   cout << "\n";

#if 0
  long ord0 = al.OrderOf(0);

  for (long i = 0; i < nslots; i++) {
    cout << alphas[i] << " ";
    if ((i+1) % (nslots/ord0) == 0) cout << "\n";
  }
 
  cout << "\n\n";
  cout << betas.size() << "\n";

  for (long i = 0; i < nslots; i++) {
    cout << betas[i] << " ";
    if ((i+1) % (nslots/ord0) == 0) cout << "\n";
  }
#endif


  return 0;
  

  }


#endif

  // an initial sanity check on noise estimates,
  // comparing the estimated variance to the actual average
  cout << "pk:"; checkCiphertext(publicKey.pubEncrKey, zero, secretKey);

  ZZX ptxt[6]; // first four are plaintext, last two are constants
  std::vector<Ctxt> ctxt(4, Ctxt(publicKey));

  // Initialize the plaintext and constants to random 0-1 polynomials
  for (size_t j=0; j<6; j++) {
    ptxt[j].rep.SetLength(phim);
    for (long i = 0; i < phim; i++)
      ptxt[j].rep[i] = RandomBnd(ptxtSpace);
    ptxt[j].normalize();

    if (j<4) { 
      publicKey.Encrypt(ctxt[j], ptxt[j], ptxtSpace);
      cout << "c"<<j<<":"; checkCiphertext(ctxt[j], ptxt[j], secretKey);
    }
  }

  // perform upto 2L levels of computation, each level computing:
  //    1. c0 += c1
  //    2. c1 *= c2            // L1' = max(L1,L2)+1
  //    3. c1.reLinearlize
  //    4. c2 *= p4
  //    5. c2.automorph(k)     // k is the first generator of Zm^* /(2)
  //    6. c2.reLinearlize
  //    7. c3 += p5
  //    8. c3 *= c0            // L3' = max(L3,L0,L1)+1
  //    9. c2 *= c3            // L2' = max(L2,L0+1,L1+1,L3+1)+1
  //   10. c0 *= c0            // L0' = max(L0,L1)+1
  //   11. c0.reLinearlize
  //   12. c2.reLinearlize
  //   13. c3.reLinearlize
  //
  // The levels of the four ciphertexts behave as follows:
  // 0, 0, 0, 0  =>  1, 1, 2, 1  =>  2, 3, 3, 2
  //             =>  4, 4, 5, 4  =>  5, 6, 6, 5
  //             =>  7, 7, 8, 7  =>  8,,9, 9, 10  => [...]
  //
  // We perform the same operations on the plaintext, and after each operation
  // we check that decryption still works, and print the curretn modulus and
  // noise estimate. We stop when we get the first decryption error, or when
  // we reach 2L levels (which really should not happen).

  zz_pContext zzpc;
  zz_p::init(ptxtSpace);
  zzpc.save();
  const zz_pXModulus F = to_zz_pX(PhimX);
  long g = context.zMstar.ZmStarGen(0); // the first generator in Zm*
  zz_pX x2g(g, 1);
  zz_pX p2;

  // generate a key-switching matrix from s(X^g) to s(X)
  secretKey.GenKeySWmatrix(/*powerOfS= */  1,
			   /*powerOfX= */  g,
			   0, 0,
			   /*ptxtSpace=*/  ptxtSpace);

  // generate a key-switching matrix from s^2 to s
  secretKey.GenKeySWmatrix(/*powerOfS= */  2,
			   /*powerOfX= */  1,
			   0, 0,
			   /*ptxtSpace=*/  ptxtSpace);

  // generate a key-switching matrix from s^3 to s
  secretKey.GenKeySWmatrix(/*powerOfS= */  3,
			   /*powerOfX= */  1,
			   0, 0,
			   /*ptxtSpace=*/  ptxtSpace);

  for (long lvl=0; lvl<2*L; lvl++) {
    cout << "=======================================================\n";
    ctxt[0] += ctxt[1];
    ptxt[0] += ptxt[1];
    PolyRed(ptxt[0], ptxtSpace, true);
    cout << "c0+=c1:  "; checkCiphertext(ctxt[0], ptxt[0], secretKey);

    ctxt[1].multiplyBy(ctxt[2]);
    ptxt[1] = (ptxt[1] * ptxt[2]) % PhimX;
    PolyRed(ptxt[1], ptxtSpace, true);
    cout << "c1*=c2:  "; checkCiphertext(ctxt[1], ptxt[1], secretKey);

    ctxt[2].multByConstant(ptxt[4]);
    ptxt[2] = (ptxt[2] * ptxt[4]) % PhimX;
    PolyRed(ptxt[2], ptxtSpace, true);
    cout <<  "c2*=p4:  "; checkCiphertext(ctxt[2], ptxt[2], secretKey);

    ctxt[2] >>= g;
    zzpc.restore();
    p2 = to_zz_pX(ptxt[2]);
    CompMod(p2, p2, x2g, F);
    ptxt[2] = to_ZZX(p2);
    cout << "c2>>="<<g<<":"; checkCiphertext(ctxt[2], ptxt[2], secretKey);

    ctxt[2].reLinearize();
    cout << "c2.relin:"; checkCiphertext(ctxt[2], ptxt[2], secretKey);

    ctxt[3].addConstant(ptxt[5]);
    ptxt[3] += ptxt[5];
    PolyRed(ptxt[3], ptxtSpace, true);
    cout << "c3+=p5:  "; checkCiphertext(ctxt[3], ptxt[3], secretKey);

    ctxt[3].multiplyBy(ctxt[0]);
    ptxt[3] = (ptxt[3] * ptxt[0]) % PhimX;
    PolyRed(ptxt[3], ptxtSpace, true);
    cout << "c3*=c0:  ";    checkCiphertext(ctxt[3], ptxt[3], secretKey);

    ctxt[0].square();
    ptxt[0] = (ptxt[0] * ptxt[0]) % PhimX;
    PolyRed(ptxt[0], ptxtSpace, true);
    cout << "c0*=c0:  ";    checkCiphertext(ctxt[0], ptxt[0], secretKey);

    ctxt[2].multiplyBy(ctxt[3]);
    ptxt[2] = (ptxt[2] * ptxt[3]) % PhimX;
    PolyRed(ptxt[2], ptxtSpace, true);
    cout << "c2*=c3:  ";    checkCiphertext(ctxt[2], ptxt[2], secretKey);
  }
  /******************************************************************/
  /**                       TESTS END HERE                        ***/
  /******************************************************************/
  cout << endl;
  return 0;
}