Ejemplo n.º 1
0
METHOD_RETURN_TYPE PDFDictionaryDriver::QueryObject(const ARGS_TYPE& args)
{
    CREATE_ISOLATE_CONTEXT;
	CREATE_ESCAPABLE_SCOPE;
    
    if(args.Length() != 1 || !args[0]->IsString())
    {
		THROW_EXCEPTION("wrong arguments, pass 1 argument which is a string key");
		SET_FUNCTION_RETURN_VALUE(UNDEFINED);
        
    }
    
    std::string key = *String::Utf8Value(args[0]->ToString());

    PDFDictionaryDriver* driver = ObjectWrap::Unwrap<PDFDictionaryDriver>(args.This());
    
    if(!driver->TheObject->Exists(key))
    {
		THROW_EXCEPTION("key not found");
		SET_FUNCTION_RETURN_VALUE(UNDEFINED);
    }
    
    RefCountPtr<PDFObject> anObject = driver->TheObject->QueryDirectObject(key);
    Handle<Value> result = PDFObjectDriver::CreateDriver(anObject.GetPtr());
    
    SET_FUNCTION_RETURN_VALUE(result);
}
Ejemplo n.º 2
0
PDFObject* PDFObjectParser::ParseDictionary(IPDFParserExtender* inParserExtender)
{
	PDFDictionary* aDictionary = new PDFDictionary();
	bool dictionaryEndEncountered = false;
	std::string token;
	EStatusCode status = PDFHummus::eSuccess;

	while(GetNextToken(token) && PDFHummus::eSuccess == status)
	{
		dictionaryEndEncountered = (scDoubleRightAngle == token);
		if(dictionaryEndEncountered)
			break;

		ReturnTokenToBuffer(token);

		// Parse Key
		PDFObjectCastPtr<PDFName> aKey(ParseNewObject(inParserExtender));
		if(!aKey)
		{
			status = PDFHummus::eFailure;
			TRACE_LOG1("PDFObjectParser::ParseDictionary, failure to parse key for a dictionary. token = %s",token.c_str());
			break;
		}

		// i'll consider duplicate keys as failure
		if(aDictionary->Exists(aKey->GetValue()))
		{
			status = PDFHummus::eFailure;
			TRACE_LOG1("PDFObjectParser::ParseDictionary, failure to parse key for a dictionary, key already exists. key = %s",aKey->GetValue().c_str());
			break;
		}

		// Parse Value
		RefCountPtr<PDFObject> aValue = ParseNewObject(inParserExtender);
		if(!aValue)
		{
			status = PDFHummus::eFailure;
			TRACE_LOG1("PDFObjectParser::ParseDictionary, failure to parse value for a dictionary. token = %s",token.c_str());
			break;
		}
	
		// all well, add the two items to the dictionary
		aDictionary->Insert(aKey.GetPtr(),aValue.GetPtr());
	}

	if(dictionaryEndEncountered && PDFHummus::eSuccess == status)
	{
		return aDictionary;
	}
	else
	{
		delete aDictionary;
		TRACE_LOG1("PDFObjectParser::ParseDictionary, failure to parse dictionary, didn't find end of array or failure to parse dictionary member object. token = %s",token.c_str());
		return NULL;
	}
}
Ejemplo n.º 3
0
PDFObject* PDFObjectParser::ParseDictionary()
{
	PDFDictionary* aDictionary = new PDFDictionary();
	bool dictionaryEndEncountered = false;
	std::string token;
	EStatusCode status = PDFHummus::eSuccess;

	while(GetNextToken(token) && PDFHummus::eSuccess == status)
	{
		dictionaryEndEncountered = (scDoubleRightAngle == token);
		if(dictionaryEndEncountered)
			break;

		ReturnTokenToBuffer(token);

		// Parse Key
		PDFObjectCastPtr<PDFName> aKey(ParseNewObject());
		if(!aKey)
		{
			status = PDFHummus::eFailure;
			TRACE_LOG1("PDFObjectParser::ParseDictionary, failure to parse key for a dictionary. token = %s",token.substr(0, MAX_TRACE_SIZE - 200).c_str());
			break;
		}


		// Parse Value
		RefCountPtr<PDFObject> aValue = ParseNewObject();
		if(!aValue)
		{
			status = PDFHummus::eFailure;
			TRACE_LOG1("PDFObjectParser::ParseDictionary, failure to parse value for a dictionary. token = %s",token.substr(0, MAX_TRACE_SIZE - 200).c_str());
			break;
		}
	

		// all good. i'm gonna be forgiving here and allow skipping duplicate keys. cause it happens
		if(!aDictionary->Exists(aKey->GetValue()))
			aDictionary->Insert(aKey.GetPtr(),aValue.GetPtr());
	}

	if(dictionaryEndEncountered && PDFHummus::eSuccess == status)
	{
		return aDictionary;
	}
	else
	{
		delete aDictionary;
		TRACE_LOG1("PDFObjectParser::ParseDictionary, failure to parse dictionary, didn't find end of array or failure to parse dictionary member object. token = %s",token.substr(0, MAX_TRACE_SIZE - 200).c_str());
		return NULL;
	}
}
Ejemplo n.º 4
0
//-----------------------------------------------------------------------------
// Function      : matrixFreeEpetraOperator
// Purpose       : non-member constructor
// Special Notes :
// Scope         : public
// Creator       : Todd Coffey, 1414
// Creation Date : 9/4/08
//-----------------------------------------------------------------------------
RefCountPtr<MatrixFreeEpetraOperator> matrixFreeEpetraOperator(
    RefCountPtr<NonLinearSolver> nonlinearSolver,
    RefCountPtr<N_LAS_Vector> solVector,
    RefCountPtr<N_LAS_Vector> rhsVector,
    RefCountPtr<const Epetra_Map> solutionMap
    )
{
  RefCountPtr<MatrixFreeEpetraOperator> epetraOperator =
    rcp(new MatrixFreeEpetraOperator);
  epetraOperator->initialize(nonlinearSolver,
      solVector,
      rhsVector,
      solutionMap
      );
  return epetraOperator;
}
Ejemplo n.º 5
0
void AuthContext::StaticGetCertCallback(AsyncOpPtr theOp, RefCountPtr theParam)
{
	GetCertOp *anOp = (GetCertOp*)theOp.get();

	AuthContext *aContext = (AuthContext*)theParam.get();
	aContext->GetCertCallback(anOp);
}
Ejemplo n.º 6
0
void ServerConnection::StaticConnectCallback(AsyncOpPtr theOp, RefCountPtr theParam)
{
	PeerAuthOp *anOp = (PeerAuthOp*)theOp.get();
	ServerConnection *thisConnection = (ServerConnection*)theParam.get();

	thisConnection->ConnectCallback(anOp);
}
Ejemplo n.º 7
0
void ServerConnection::StaticMsgCallback(AsyncOpPtr theOp, RefCountPtr theParam)
{
	RecvMsgOp *anOp = (RecvMsgOp*)theOp.get();
	ServerConnection *thisConnection = (ServerConnection*)theParam.get();

	if(anOp->GetStatus()==WS_Success)
		thisConnection->MsgCallback(anOp->GetMsg());
}
Ejemplo n.º 8
0
void showXObjectsPerPageInfo(PDFParser& parser,PDFObjectCastPtr<PDFDictionary> xobjects) 
{
    RefCountPtr<PDFName> key;
    PDFObjectCastPtr<PDFIndirectObjectReference> value;
	MapIterator<PDFNameToPDFObjectMap> it = xobjects->GetIterator();
	while(it.MoveNext())
	{
        key = it.GetKey();
        value = it.GetValue();

        cout << "XObject named " << key->GetValue().c_str() << " is object " << value->mObjectID << " of type ";

        PDFObjectCastPtr<PDFStreamInput> xobject(parser.ParseNewObject(value->mObjectID));
        PDFObjectCastPtr<PDFDictionary> xobjectDictionary(xobject->QueryStreamDictionary());
        PDFObjectCastPtr<PDFName> typeOfXObject = xobjectDictionary->QueryDirectObject("Subtype");

        cout << typeOfXObject->GetValue().c_str() << "\n";
    }
}
Ejemplo n.º 9
0
SymbolTablePtr createSymbTable(size_t size, SymbolTablePtr parentTable) {
    RefCountPtr<SymbolTable> result;
    switch (size) {
        case 0:
            return parentTable;
        case 1:
            result.reset(new SmallTable<1>(parentTable));
            break;
        case 2:
            result.reset(new SmallTable<2>(parentTable));
            break;
        case 3:
            result.reset(new SmallTable<3>(parentTable));
            break;
        default:
            result.reset(new HashTable(parentTable));
    }
    return result;
}
Ejemplo n.º 10
0
void showPageContent(PDFParser& parser, RefCountPtr<PDFObject> contents, InputFile& pdfFile) 
{
    if(contents->GetType() == ePDFObjectArray) 
	{
        PDFObjectCastPtr<PDFIndirectObjectReference> streamReferences;
		SingleValueContainerIterator<PDFObjectVector> itContents = ((PDFArray*)contents.GetPtr())->GetIterator();
		// array of streams
		while(itContents.MoveNext())
		{
            streamReferences = itContents.GetItem();
            PDFObjectCastPtr<PDFStreamInput> stream = parser.ParseNewObject(streamReferences->mObjectID);
            showContentStream(stream.GetPtr(),pdfFile.GetInputStream(),parser);
        }
    } 
	else 
	{
        // stream
        showContentStream((PDFStreamInput*)contents.GetPtr(),pdfFile.GetInputStream(),parser);
    }
}
Ejemplo n.º 11
0
void GameSpySupport::PumpTimerCompletion(AsyncOpPtr theOp, RefCountPtr theParam)
{
	if (theOp.get()	== NULL)
		return;

	if (theOp->Killed())
		return;

	GameSpySupport *pThat = (GameSpySupport*)theParam.get();
	pThat->Pump();
}
/*----------------------------------------------------------------------*
 |  ctor (public)                                             m.gee 3/06|
 *----------------------------------------------------------------------*/
NLNML::NLNML_ConstrainedMultiLevelOperator::NLNML_ConstrainedMultiLevelOperator(
              RefCountPtr<ML_Epetra::MultiLevelOperator> ml_operator,
              RefCountPtr<NLNML::NLNML_CoarseLevelNoxInterface> coarseinterface,
              bool applyconstraints) :
comm_(ml_operator->Comm()),
coarseinterface_(coarseinterface),
ml_operator_(ml_operator),
applyconstraints_(applyconstraints)
{
  label_ = "NLNML_ConstrainedMultiLevelOperator";
  return;
}
Ejemplo n.º 13
0
void JPEGSaver::EmbedProfile(RefCountPtr<CMSProfile> profile)
{
	if(!profile)
		return;
	if(!cinfo)
		throw "JPEGSaver: cinfo already freed!";
	BinaryBlob *blob=profile->GetBlob();
	size_t EmbedLen=blob->GetSize();
	JOCTET *EmbedBuffer=(JOCTET *)blob->GetPointer();
	
	write_icc_profile(cinfo,EmbedBuffer,EmbedLen);
	delete blob;
}
Ejemplo n.º 14
0
Handle<Value> PDFArrayDriver::QueryObject(const Arguments& args)
{
    HandleScope scope;
    
    if(args.Length() != 1 || !args[0]->IsNumber())
    {
		ThrowException(Exception::TypeError(String::New("wrong arguments, pass 1 argument which is an index in the array")));
		return scope.Close(Undefined());
        
    }
    
    PDFArrayDriver* arrayDriver = ObjectWrap::Unwrap<PDFArrayDriver>(args.This());
    if(args[0]->ToNumber()->Uint32Value() >= arrayDriver->TheObject->GetLength())
    {
		ThrowException(Exception::Error(String::New("wrong arguments, pass 1 argument which is a valid index in the array")));
		return scope.Close(Undefined());
    }
    
    RefCountPtr<PDFObject> anObject = arrayDriver->TheObject->QueryObject(args[0]->ToNumber()->Uint32Value());
    Handle<Value> result = PDFObjectDriver::CreateDriver(anObject.GetPtr());
    
    return scope.Close(result);
}
Ejemplo n.º 15
0
METHOD_RETURN_TYPE PDFArrayDriver::QueryObject(const ARGS_TYPE& args)
{
    CREATE_ISOLATE_CONTEXT;
	CREATE_ESCAPABLE_SCOPE;
    
    if(args.Length() != 1 || !args[0]->IsNumber())
    {
		THROW_EXCEPTION("wrong arguments, pass 1 argument which is an index in the array");
		SET_FUNCTION_RETURN_VALUE(UNDEFINED);
        
    }
    
    PDFArrayDriver* arrayDriver = ObjectWrap::Unwrap<PDFArrayDriver>(args.This());
    if(args[0]->ToNumber()->Uint32Value() >= arrayDriver->TheObject->GetLength())
    {
		THROW_EXCEPTION("wrong arguments, pass 1 argument which is a valid index in the array");
		SET_FUNCTION_RETURN_VALUE(UNDEFINED);
    }
    
    RefCountPtr<PDFObject> anObject = arrayDriver->TheObject->QueryObject(args[0]->ToNumber()->Uint32Value());
    Handle<Value> result = PDFObjectDriver::CreateDriver(anObject.GetPtr());
    
    SET_FUNCTION_RETURN_VALUE(result);
}
Ejemplo n.º 16
0
void checkXObjectRef(PDFParser& parser,RefCountPtr<PDFDictionary> page) 
{
    PDFObjectCastPtr<PDFDictionary> resources(parser.QueryDictionaryObject(page.GetPtr(),"Resources"));
    if(!resources) 
	{
        wcout << "No XObject in this page\n";
        return;
    }

    PDFObjectCastPtr<PDFDictionary> xobjects(parser.QueryDictionaryObject(resources.GetPtr(),"XObject"));
    if(!xobjects) 
	{
		wcout << "No XObject in this page\n";
		return;
    }

    cout << "Displaying XObjects information for this page:\n";
    showXObjectsPerPageInfo(parser,xobjects);
}
Ejemplo n.º 17
0
void GameSpySupport::StaticGetServiceOpCompletion(AsyncOpPtr theOp, RefCountPtr theGameSpy)
{
	GameSpySupport *aGameSpy = (GameSpySupport*)theGameSpy.get();
	GetServiceOp *anOp = (GetServiceOp*)theOp.get();
	aGameSpy->GetServiceOpCompletion(anOp);
}
Ejemplo n.º 18
0
JPEGSaver::JPEGSaver(const char *filename,RefCountPtr<ImageSource> is,int compression)
	: ImageSaver(is), cinfo(NULL), tmpbuffer(NULL)
{
	if(STRIP_ALPHA(is->type)==IS_TYPE_BW)
		throw _("JPEG Saver only supports greyscale and colour images!");

//	if(STRIP_ALPHA(is->type)==IS_TYPE_CMYK)
//		throw _("Saving CMYK JPEGs not (yet) supported");

// Can't do this directly with a refcounted source!
	if(HAS_ALPHA(is->type))
		source=new ImageSource_Flatten(new ImageSource_Ref(is));

	this->width=is->width;
	this->height=is->height;

	cinfo=new jpeg_compress_struct;
	err=new JPEGSaver_ErrManager;
	memset(cinfo,0,sizeof(jpeg_compress_struct));
	memset(err,0,sizeof(JPEGSaver_ErrManager));
	cinfo->err = jpeg_std_error(&err->std);
	err->std.error_exit = isjpeg_error_exit;

	if(filename)
	{
		if((err->file = FOpenUTF8(filename,"wb")) == NULL)
		{
			delete cinfo;
			delete err;
			cinfo=NULL;
			throw _("Can't open file for saving");
		}
		Debug[TRACE] << "File " << filename << " opened" << endl;
	}
	else
		err->file=stdout;

	jpeg_create_compress(cinfo);
	jpeg_stdio_dest(cinfo, err->file);

	cinfo->image_width=is->width;
	cinfo->image_height=is->height;

	switch(is->type)
	{
		case IS_TYPE_RGB:
			cinfo->input_components=3;
			cinfo->in_color_space = JCS_RGB;
			jpeg_set_defaults(cinfo);
			break;
		case IS_TYPE_GREY:
			cinfo->input_components=1;
			cinfo->in_color_space = JCS_GRAYSCALE;
			jpeg_set_defaults(cinfo);
			break;
		case IS_TYPE_CMYK:
			cinfo->input_components=4;
			cinfo->in_color_space = JCS_CMYK;
			cinfo->jpeg_color_space = JCS_YCCK;
			jpeg_set_defaults(cinfo);
		    jpeg_set_colorspace(cinfo, JCS_YCCK);
			cinfo->write_JFIF_header=TRUE;	// HACK to force resolution to be saved.
											// Not strictly correct, since JFIF files can't be CMYK.
											// LCMS's jpegicc does this too (though probably not deliberately!)
			break;
		default:
			throw _("JPEG Saver can currently only save RGB, CMYK or Greyscale images.");
			break;
	}

	jpeg_set_quality(cinfo,compression,TRUE);

	cinfo->density_unit=1;
	cinfo->X_density=is->xres;
	cinfo->Y_density=is->yres;

	Debug[TRACE] << "JPEGSaver: Set xres to " << cinfo->X_density << endl;
	Debug[TRACE] << "JPEGSaver: Set yres to " << cinfo->Y_density << endl;

	jpeg_start_compress(cinfo,TRUE);

	if(is->GetEmbeddedProfile())
		EmbedProfile(is->GetEmbeddedProfile());

	bytesperrow = width*is->samplesperpixel;

	if(!(tmpbuffer=(unsigned char *)malloc(bytesperrow)))
		throw "No memory for tmpbuffer";
}
Ejemplo n.º 19
0
void MultiPingOp::StaticRecvCallback(AsyncOpPtr theOp, RefCountPtr theParam)
{
	MultiPingOp *thisOp = (MultiPingOp*)theParam.get();
	RecvBytesFromOp *aRecvOp = (RecvBytesFromOp*)theOp.get();
	thisOp->RecvCallback(aRecvOp);
}
Ejemplo n.º 20
0
void AuthContext::StaticAutoRefreshCallback(AsyncOpPtr theOp, RefCountPtr theParam)
{
	AuthContext *aContext = (AuthContext*)theParam.get();
	aContext->AutoRefreshCallback(theOp);
}
Ejemplo n.º 21
0
ObjectIDType DCTDecodeFilterTest::FindDCTDecodedImageObject(PDFParser* inParser)
{
    ObjectIDType imageObject = 0;
    
    do
    {
        // find image by looking for the first image in the first page
        
        RefCountPtr<PDFDictionary> firstPage = inParser->ParsePage(0);
        if(!firstPage)
            break;
        
        PDFObjectCastPtr<PDFDictionary> resourceDictionary(inParser->QueryDictionaryObject(firstPage.GetPtr(),"Resources"));
        
        if(!resourceDictionary)
            break;
        
        PDFObjectCastPtr<PDFDictionary> xobjectDictionary(inParser->QueryDictionaryObject(resourceDictionary.GetPtr(), "XObject"));
        
        if(!xobjectDictionary)
            break;
        
        MapIterator<PDFNameToPDFObjectMap> it = xobjectDictionary->GetIterator();

        while(it.MoveNext())
        {
            if(it.GetValue()->GetType() == PDFObject::ePDFObjectIndirectObjectReference)
            {
                PDFObjectCastPtr<PDFStreamInput> image(
                                                       inParser->ParseNewObject(((PDFIndirectObjectReference*)it.GetValue())->mObjectID));
                RefCountPtr<PDFDictionary> imageDictionary = image->QueryStreamDictionary();
                
                PDFObjectCastPtr<PDFName> objectType = imageDictionary->QueryDirectObject("Subtype");
                if(!objectType || objectType->GetValue() != "Image")
                    continue;
                
                RefCountPtr<PDFObject> filters = imageDictionary->QueryDirectObject("Filter");
                if(!filters)
                    break;
                
                if(filters->GetType() == PDFObject::ePDFObjectName &&
                   ((PDFName*)filters.GetPtr())->GetValue() == "DCTDecode")
                {
                    imageObject = ((PDFIndirectObjectReference*)it.GetValue())->mObjectID;
                    break;
                }
                
                PDFArray* filtersArray = (PDFArray*)filters.GetPtr();
                
                if(filtersArray->GetLength() == 1)
                {
                    PDFObjectCastPtr<PDFName> firstDecoder(filtersArray->QueryObject(0));
                    
                    if(firstDecoder->GetValue() == "DCTDecode")
                    {
                        imageObject = ((PDFIndirectObjectReference*)it.GetValue())->mObjectID;
                        break;
                    }
                }
            }
        }
        
    }
    while (false);
    
    return imageObject;
}
Ejemplo n.º 22
0
void MultiPingOp::StaticTimeoutCallback(AsyncOpPtr theOp, RefCountPtr theParam)
{
	MultiPingOp *thisOp = (MultiPingOp*)theParam.get();
	thisOp->TimeoutCallback((AsyncOp*)theOp.get());
}
// ============================================================================ 
int ML_Epetra::MatrixFreePreconditioner::
Compute(const Epetra_CrsGraph& Graph, Epetra_MultiVector& NullSpace)
{
  Epetra_Time TotalTime(Comm());

  const int NullSpaceDim = NullSpace.NumVectors();
  // get parameters from the list
  std::string PrecType = List_.get("prec: type", "hybrid");
  std::string SmootherType = List_.get("smoother: type", "Jacobi");
  std::string ColoringType = List_.get("coloring: type", "JONES_PLASSMAN");
  int PolynomialDegree = List_.get("smoother: degree", 3);
  std::string DiagonalColoringType = List_.get("diagonal coloring: type", "JONES_PLASSMAN");
  int MaximumIterations = List_.get("eigen-analysis: max iters", 10);
  std::string EigenType_ = List_.get("eigen-analysis: type", "cg");
  double boost = List_.get("eigen-analysis: boost for lambda max", 1.0);
  int OutputLevel = List_.get("ML output", -47);
  if (OutputLevel == -47) OutputLevel =  List_.get("output", 10);
  omega_ = List_.get("smoother: damping", omega_);
  ML_Set_PrintLevel(OutputLevel);
  bool LowMemory = List_.get("low memory", true);
  double AllocationFactor = List_.get("AP allocation factor", 0.5);

  verbose_ = (MyPID() == 0 && ML_Get_PrintLevel() > 5);

  // ================ //
  // check parameters //
  // ================ //

  if (PrecType == "presmoother only")
    PrecType_ = ML_MFP_PRESMOOTHER_ONLY;
  else if (PrecType == "hybrid")
    PrecType_ = ML_MFP_HYBRID;
  else if (PrecType == "additive")
    PrecType_ = ML_MFP_ADDITIVE;
  else
    ML_CHK_ERR(-3); // not recognized

  if (SmootherType == "none")
    SmootherType_ = ML_MFP_NONE;
  else if (SmootherType == "Jacobi")
    SmootherType_ = ML_MFP_JACOBI;
  else if (SmootherType == "block Jacobi")
    SmootherType_ = ML_MFP_BLOCK_JACOBI;
  else if (SmootherType == "Chebyshev")
    SmootherType_ = ML_MFP_CHEBY;
  else
    ML_CHK_ERR(-4); // not recognized

  if (AllocationFactor <= 0.0)
    ML_CHK_ERR(-1); // should be positive

  // =============================== //
  // basic checkings and some output //
  // =============================== //
  
  int OperatorDomainPoints =  Operator_.OperatorDomainMap().NumGlobalPoints();
  int OperatorRangePoints =  Operator_.OperatorRangeMap().NumGlobalPoints();
  int GraphBlockRows = Graph.NumGlobalBlockRows();
  int GraphNnz = Graph.NumGlobalNonzeros();
  NumPDEEqns_ = OperatorRangePoints / GraphBlockRows;
  NumMyBlockRows_ = Graph.NumMyBlockRows();

  if (OperatorDomainPoints != OperatorRangePoints)
    ML_CHK_ERR(-1); // only square matrices

  if (OperatorRangePoints % NumPDEEqns_ != 0)
    ML_CHK_ERR(-2); // num PDEs seems not constant

  if (verbose_)
  {
    ML_print_line("=",78);
    std::cout << "*** " << std::endl;
    std::cout << "*** ML_Epetra::MatrixFreePreconditioner" << std::endl;
    std::cout << "***" << std::endl;
    std::cout << "Number of rows and columns      = " << OperatorDomainPoints << std::endl;
    std::cout << "Number of rows per processor    = " << OperatorDomainPoints / Comm().NumProc()
         << " (on average)" << std::endl;
    std::cout << "Number of rows in the graph     = " << GraphBlockRows << std::endl;
    std::cout << "Number of nonzeros in the graph = " << GraphNnz << std::endl;
    std::cout << "Processors used in computation  = " << Comm().NumProc() << std::endl;
    std::cout << "Number of PDE equations         = " << NumPDEEqns_ << std::endl;
    std::cout << "Null space dimension            = " << NullSpaceDim << std::endl;
    std::cout << "Preconditioner type             = " << PrecType << std::endl;
    std::cout << "Smoother type                   = " << SmootherType << std::endl;
    std::cout << "Coloring type                   = " << ColoringType << std::endl;
    std::cout << "Allocation factor               = " << AllocationFactor << std::endl;
    std::cout << "Number of V-cycles for C        = " << List_.sublist("ML list").get("cycle applications", 1) << std::endl;
    std::cout << std::endl;
  }

  ResetStartTime();

  // ==================================== //
  // compute the inverse of the diagonal, //
  // control that no elements are zero.   //
  // ==================================== //
  
  for (int i = 0; i < InvPointDiagonal_->MyLength(); ++i)
    if ((*InvPointDiagonal_)[i] != 0.0)
      (*InvPointDiagonal_)[i] = 1.0 / (*InvPointDiagonal_)[i];

  // ========================================================= //
  // Setup the smoother. I need to extract the block diagonal  //
  // only if block Jacobi is used. For Chebyshev, I scale with //
  // the point diagonal only. In this latter case, I need to   //
  // compute lambda_max of the scaled operator.                //
  // ========================================================= //
  
  // probes for the block diagonal of the matrix.
  if (SmootherType_ == ML_MFP_JACOBI ||
      SmootherType_ == ML_MFP_NONE)
  {
    // do-nothing here
  }
  else if (SmootherType_ == ML_MFP_BLOCK_JACOBI)
  {
    if (verbose_);
      std::cout << "Diagonal coloring type         = " << DiagonalColoringType << std::endl;
    ML_CHK_ERR(GetBlockDiagonal(Graph, DiagonalColoringType));

    AddAndResetStartTime("block diagonal construction", true);
  }
  else if (SmootherType_ == ML_MFP_CHEBY)
  {
    double lambda_min = 0.0;
    double lambda_max = 0.0;
    Teuchos::ParameterList IFPACKList;

    if (EigenType_ == "power-method")
    {
      ML_CHK_ERR(Ifpack_Chebyshev::PowerMethod(Operator_, *InvPointDiagonal_,
                                               MaximumIterations, lambda_max));
    }
    else if(EigenType_ == "cg")
    {
      ML_CHK_ERR(Ifpack_Chebyshev::CG(Operator_, *InvPointDiagonal_,
                                      MaximumIterations, lambda_min, 
                                      lambda_max));
    }
    else
      ML_CHK_ERR(-1); // not recognized

    if (verbose_)
    {
      std::cout << "Using Chebyshev smoother of degree " << PolynomialDegree << std::endl;
      std::cout << "Estimating eigenvalues using " <<  EigenType_ << std::endl;
      std::cout << "lambda_min = " << lambda_min << ", ";
      std::cout << "lambda_max = " << lambda_max << std::endl;
    }

    IFPACKList.set("chebyshev: min eigenvalue", lambda_min);
    IFPACKList.set("chebyshev: max eigenvalue", boost * lambda_max);
    // FIXME: this allocates a new std::vector inside
    IFPACKList.set("chebyshev: operator inv diagonal", InvPointDiagonal_.get());
    IFPACKList.set("chebyshev: degree", PolynomialDegree);

    PreSmoother_ = rcp(new Ifpack_Chebyshev((Epetra_Operator*)(&Operator_)));
    if (PreSmoother_.get() == 0) ML_CHK_ERR(-1); // memory error?

    IFPACKList.set("chebyshev: zero starting solution", true);
    ML_CHK_ERR(PreSmoother_->SetParameters(IFPACKList));
    ML_CHK_ERR(PreSmoother_->Initialize());
    ML_CHK_ERR(PreSmoother_->Compute());

    PostSmoother_ = rcp(new Ifpack_Chebyshev((Epetra_Operator*)(&Operator_)));
    if (PostSmoother_.get() == 0) ML_CHK_ERR(-1); // memory error?

    IFPACKList.set("chebyshev: zero starting solution", false);
    ML_CHK_ERR(PostSmoother_->SetParameters(IFPACKList));
    ML_CHK_ERR(PostSmoother_->Initialize());
    ML_CHK_ERR(PostSmoother_->Compute());
  }

  // ========================================================= //
  // building P and R for block graph. This is done by working //
  // on the Graph_ object. Support is provided for local       //
  // aggregation schemes only so that all is basically local.  //
  // Then, build the block graph coarse problem.               //
  // ========================================================= //
  
  // ML wrapper for Graph_
  ML_Operator* Graph_ML = ML_Operator_Create(Comm_ML());
  ML_Operator_WrapEpetraCrsGraph(const_cast<Epetra_CrsGraph*>(&Graph), Graph_ML);

  ML_Aggregate* BlockAggr_ML = 0;
  ML_Operator* BlockPtent_ML = 0, *BlockRtent_ML = 0,* CoarseGraph_ML = 0;

  if (verbose_) std::cout << std::endl;

  ML_CHK_ERR(Coarsen(Graph_ML, &BlockAggr_ML, &BlockPtent_ML, &BlockRtent_ML, 
                     &CoarseGraph_ML));

  if (verbose_) std::cout << std::endl;

  Epetra_CrsMatrix* GraphCoarse;
  ML_CHK_ERR(ML_Operator2EpetraCrsMatrix(CoarseGraph_ML, GraphCoarse));

  // used later to estimate the entries in AP
  ML_Operator* CoarseAP_ML = ML_Operator_Create(Comm_ML());
  ML_2matmult(Graph_ML, BlockPtent_ML, CoarseAP_ML, ML_CSR_MATRIX);

  int AP_MaxNnzRow, itmp = CoarseAP_ML->max_nz_per_row;
  Comm().MaxAll(&itmp, &AP_MaxNnzRow, 1);
  ML_Operator_Destroy(&CoarseAP_ML);

  int NumAggregates = BlockPtent_ML->invec_leng;
  ML_Operator_Destroy(&BlockRtent_ML);
  ML_Operator_Destroy(&CoarseGraph_ML);

  AddAndResetStartTime("construction of block C, R, and P", true);
  if (verbose_) std::cout << std::endl;

  // ================================================== //
  // coloring of block graph:                           //
  // - color of block row `i' is given by `ColorMap[i]' //
  // - number of colors is ColorMap.NumColors().        //
  // ================================================== //
  
  ResetStartTime();

  CrsGraph_MapColoring* MapColoringTransform;
  
  if (ColoringType == "JONES_PLASSMAN")
    MapColoringTransform = new CrsGraph_MapColoring (CrsGraph_MapColoring::JONES_PLASSMAN,
                                                     0, false, 0);
  else if (ColoringType == "PSEUDO_PARALLEL")
    MapColoringTransform = new CrsGraph_MapColoring (CrsGraph_MapColoring::PSEUDO_PARALLEL,
                                                     0, false, 0);
  else if (ColoringType == "GREEDY")
    MapColoringTransform = new CrsGraph_MapColoring (CrsGraph_MapColoring::GREEDY,
                                                     0, false, 0);
  else if (ColoringType == "LUBY")
    MapColoringTransform = new CrsGraph_MapColoring (CrsGraph_MapColoring::LUBY,
                                                     0, false, 0);
  else 
    ML_CHK_ERR(-1);

  Epetra_MapColoring* ColorMap = &(*MapColoringTransform)(const_cast<Epetra_CrsGraph&>(GraphCoarse->Graph()));

  // move the information from ColorMap to std::vector Colors
  const int NumColors = ColorMap->MaxNumColors();
  RefCountPtr<Epetra_IntSerialDenseVector> Colors = rcp(new Epetra_IntSerialDenseVector(GraphCoarse->Graph().NumMyRows()));
  for (int i = 0; i < GraphCoarse->Graph().NumMyRows(); ++i)
    (*Colors)[i] = (*ColorMap)[i];

  delete MapColoringTransform;
  delete ColorMap; ColorMap = 0;
  delete GraphCoarse;

  AddAndResetStartTime("coarse graph coloring", true);
  if (verbose_) std::cout << std::endl;

  // get some other information about the aggregates, to be used
  // in the QR factorization of the null space. NodesOfAggregate
  // contains the local ID of block rows contained in each aggregate.

  // FIXME: make it faster
  std::vector< std::vector<int> > NodesOfAggregate(NumAggregates);

  for (int i = 0; i < Graph.NumMyBlockRows(); ++i)
  {
    int AID = BlockAggr_ML->aggr_info[0][i];
    NodesOfAggregate[AID].push_back(i);
  }

  int MaxAggrSize = 0;
  for (int i = 0; i < NumAggregates; ++i)
  {
    const int& MySize = NodesOfAggregate[i].size();
    if (MySize > MaxAggrSize) MaxAggrSize = MySize;
  }

  // collect aggregate information, and mark all nodes that are
  // connected with each aggregate. These nodes will have a possible
  // nonzero entry after the matrix-matrix product between the Operator_
  // and the tentative prolongator.

  std::vector<vector<int> > aggregates(NumAggregates);
  std::vector<int>::iterator iter;

  for (int i = 0; i < NumAggregates; ++i)
    aggregates[i].reserve(MaxAggrSize);

  for (int i = 0; i < Graph.NumMyBlockRows(); ++i)
  {
    int AID = BlockAggr_ML->aggr_info[0][i];

    int NumEntries;
    int* Indices;

    Graph.ExtractMyRowView(i, NumEntries, Indices);

    for (int k = 0; k < NumEntries; ++k)
    {
      // FIXME: use hash??
      const int& GCID = Graph.ColMap().GID(Indices[k]);

      iter = find(aggregates[AID].begin(), aggregates[AID].end(), GCID);
      if (iter == aggregates[AID].end())
        aggregates[AID].push_back(GCID);
    }
  }
  
  int* BlockNodeList = Graph.ColMap().MyGlobalElements();

  // finally get rid of the ML_Aggregate structure.
  ML_Aggregate_Destroy(&BlockAggr_ML);

  const Epetra_Map& FineMap = Operator_.OperatorDomainMap();
  Epetra_Map CoarseMap(-1, NumAggregates * NullSpaceDim, 0, Comm());
  RefCountPtr<Epetra_Map> BlockNodeListMap = 
    rcp(new Epetra_Map(-1, Graph.ColMap().NumMyElements(),
                       BlockNodeList, 0, Comm()));

  std::vector<int> NodeList(Graph.ColMap().NumMyElements() * NumPDEEqns_);
  for (int i = 0; i < Graph.ColMap().NumMyElements(); ++i)
    for (int m = 0; m < NumPDEEqns_; ++m)
      NodeList[i * NumPDEEqns_ + m] = BlockNodeList[i] * NumPDEEqns_ + m;
  RefCountPtr<Epetra_Map> NodeListMap = 
    rcp(new Epetra_Map(-1, NodeList.size(), &NodeList[0], 0, Comm()));

  AddAndResetStartTime("data structures", true);

  // ====================== //
  // process the null space //
  // ====================== //

  // CHECKME
  Epetra_MultiVector NewNullSpace(CoarseMap, NullSpaceDim);
  NewNullSpace.PutScalar(0.0);

  if (NullSpaceDim == 1)
  {
    double* ns_ptr = NullSpace.Values();

    for (int AID = 0; AID < NumAggregates; ++AID)
    {
      double dtemp = 0.0;
      for (int j = 0; j < (int) (NodesOfAggregate[AID].size()); j++)
        for (int m = 0; m < NumPDEEqns_; ++m)
        {
          const int& pos = NodesOfAggregate[AID][j] * NumPDEEqns_ + m;
          dtemp += (ns_ptr[pos] * ns_ptr[pos]);
        }
      dtemp = std::sqrt(dtemp);

      NewNullSpace[0][AID] = dtemp;

      dtemp = 1.0 / dtemp;

      for (int j = 0; j < (int) (NodesOfAggregate[AID].size()); j++)
        for (int m = 0; m < NumPDEEqns_; ++m)
          ns_ptr[NodesOfAggregate[AID][j] * NumPDEEqns_ + m] *= dtemp;
    }
  }
  else
  {
    // FIXME
    std::vector<double> qr_ptr(MaxAggrSize * NumPDEEqns_ * MaxAggrSize * NumPDEEqns_);
    std::vector<double> tmp_ptr(MaxAggrSize * NumPDEEqns_ * NullSpaceDim);

    std::vector<double> work(NullSpaceDim);
    int info;

    for (int AID = 0; AID < NumAggregates; ++AID)
    {
      int MySize = NodesOfAggregate[AID].size();
      int MyFullSize = NodesOfAggregate[AID].size() * NumPDEEqns_;
      int lwork = NullSpaceDim;

      for (int k = 0; k < NullSpaceDim; ++k)
        for (int j = 0; j < MySize; ++j)
          for (int m = 0; m < NumPDEEqns_; ++m)
            qr_ptr[k * MyFullSize + j * NumPDEEqns_ + m] = 
              NullSpace[k][NodesOfAggregate[AID][j] * NumPDEEqns_ + m];

      DGEQRF_F77(&MyFullSize, (int*)&NullSpaceDim, &qr_ptr[0], 
                 &MyFullSize, &tmp_ptr[0], &work[0], &lwork, &info);

      ML_CHK_ERR(info);

      if (work[0] > lwork) work.resize((int) work[0]);

      // the upper triangle of qr_tmp is now R, so copy that into the 
      //  new nullspace

      for (int j = 0; j < NullSpaceDim; j++)
        for (int k = j; k < NullSpaceDim; k++)
          NewNullSpace[k][AID * NullSpaceDim + j] = qr_ptr[j + MyFullSize * k];
		 
      // to get this block of P, need to run qr_tmp through another LAPACK 
      // function:

      DORGQR_F77(&MyFullSize, (int*)&NullSpaceDim, (int*)&NullSpaceDim, 
                 &qr_ptr[0], &MyFullSize, &tmp_ptr[0], &work[0], &lwork, &info);
      ML_CHK_ERR(info); // dgeqtr returned a non-zero

      if (work[0] > lwork) work.resize((int) work[0]);

      // insert the Q block into the null space

      for (int k = 0; k < NullSpaceDim; ++k)
        for (int j = 0; j < MySize; ++j)
          for (int m = 0; m < NumPDEEqns_; ++m)
          {
            int LRID = NodesOfAggregate[AID][j] * NumPDEEqns_ + m;
            double& val = qr_ptr[k * MyFullSize + j * NumPDEEqns_ + m];
            NullSpace[k][LRID] = val;
          }
    }
  }

  AddAndResetStartTime("null space setup", true);

  if (verbose_)
    std::cout << "Number of colors on processor " << Comm().MyPID() << " = "
        << NumColors << std::endl;
  if (verbose_)
    std::cout << "Maximum number of colors = " << NumColors << std::endl;

  RefCountPtr<Epetra_FECrsMatrix> AP;
  
  // try to get a good estimate of the nonzeros per row.
  // This is a compromize between efficiency -- that is, reduce
  // the memory allocation processes, and memory usage -- that, is
  // overestimating can actually kill the code. Basically, this is
  // all junk due to our dear friend, the Cray XT3.
  
  AP = rcp(new Epetra_FECrsMatrix(Copy, FineMap, (int)
                                  (AllocationFactor * AP_MaxNnzRow * NullSpaceDim)));
  if (AP.get() == 0) throw(-1);

  if (!LowMemory)
  {
    // ================================================= //
    // allocate one big chunk of memory, and use View    //             
    // to create Epetra_MultiVectors. Note that          //
    // NumColors * NullSpace can indeed be a quite large //
    // value. To reduce the memory consumption, both     //
    // ColoredAP and ExtColoredAP use the same memory    //
    // array.                                            //
    // ================================================= //
    
    Epetra_MultiVector* ColoredP;
    std::vector<double> ColoredAP_ptr;

    try
    {
      ColoredP = new Epetra_MultiVector(FineMap, NumColors * NullSpaceDim);
      ColoredAP_ptr.resize(NumColors * NullSpaceDim * NodeListMap->NumMyPoints());
    }
    catch (std::exception& rhs)
    {
      catch_message("the allocation of ColoredP", rhs.what(), __FILE__, __LINE__);
      ML_CHK_ERR(-1);
    }
    catch (...)
    {
      catch_message("the allocation of ColoredP", "", __FILE__, __LINE__);
      ML_CHK_ERR(-1);
    }

    int ColoredAP_LDA = NodeListMap->NumMyPoints();

    ColoredP->PutScalar(0.0);

    for (int i = 0; i < BlockPtent_ML->outvec_leng; ++i)
    {
      int allocated = 1;
      int NumEntries;
      int Indices;
      double Values;
      int ierr = ML_Operator_Getrow(BlockPtent_ML, 1 ,&i, allocated,
                                    &Indices,&Values,&NumEntries);
      if (ierr < 0)
        ML_CHK_ERR(-1);

      assert (NumEntries == 1); // this is the block P
      const int& Color = (*Colors)[Indices] - 1;
      for (int k = 0; k < NumPDEEqns_; ++k)
        for (int j = 0; j < NullSpaceDim; ++j)
          (*ColoredP)[(Color * NullSpaceDim + j)][i * NumPDEEqns_ + k] = 
            NullSpace[j][i * NumPDEEqns_ + k];
    }

    ML_Operator_Destroy(&BlockPtent_ML);

    Epetra_MultiVector ColoredAP(View, Operator_.OperatorRangeMap(), 
                                 &ColoredAP_ptr[0], ColoredAP_LDA, 
                                 NumColors * NullSpaceDim);
    // move ColoredAP into ColoredP. This should not be required.
    // but I prefer to skip strange games with View pointers
    Operator_.Apply(*ColoredP, ColoredAP);
    *ColoredP = ColoredAP;

    // FIXME: only if NumProc > 1
    Epetra_MultiVector ExtColoredAP(View, *NodeListMap, 
                                 &ColoredAP_ptr[0], ColoredAP_LDA, 
                                 NumColors * NullSpaceDim);

    try 
    {
      Epetra_Import Importer(*NodeListMap, Operator_.OperatorRangeMap());
      ExtColoredAP.Import(*ColoredP, Importer, Insert);
    }
    catch (std::exception& rhs)
    {
      catch_message("importing of ExtColoredAP", rhs.what(), __FILE__, __LINE__);
      ML_CHK_ERR(-1);
    }
    catch (...)
    {
      catch_message("importing of ExtColoredAP", "", __FILE__, __LINE__);
      ML_CHK_ERR(-1);
    }

    delete ColoredP;

    AddAndResetStartTime("computation of AP", true); 

    // populate the actual AP operator, skip some controls to make it faster

    for (int i = 0; i < NumAggregates; ++i)
    {
      for (int j = 0; j < (int) (aggregates[i].size()); ++j)
      {
        int GRID = aggregates[i][j];
        int LRID = BlockNodeListMap->LID(GRID); // this is the block ID
        //assert (LRID != -1);
        int GCID = CoarseMap.GID(i * NullSpaceDim);
        //assert (GCID != -1); 
        int color = (*Colors)[i] - 1;
        for (int k = 0; k < NumPDEEqns_; ++k)
          for (int j = 0; j < NullSpaceDim; ++j)
          {
            double val = ExtColoredAP[color * NullSpaceDim + j][LRID * NumPDEEqns_ + k];
            if (val != 0.0)
            {
              int GRID2 = GRID * NumPDEEqns_ + k;
              int GCID2 = GCID + j;
              AP->InsertGlobalValues(1, &GRID2, 1, &GCID2, &val);
              //if (ierr < 0) ML_CHK_ERR(ierr);
            }
          }
      }
    }
  }
  else
  {
    // =============================================================== //
    // apply the operator one color at-a-time. This requires NumColors //
    // cycles over BlockPtent. However, the memory requirements are    //
    // drastically reduced. As for low-memory == false, both ColoredAP //
    // and ExtColoredAP point to the same memory location.             //
    // =============================================================== //
    
    if (verbose_)
      std::cout << "Using low-memory computation for AP" << std::endl;

    Epetra_MultiVector ColoredP(FineMap, NullSpaceDim);
    std::vector<double> ColoredAP_ptr;
    try
    {
      ColoredAP_ptr.resize(NullSpaceDim * NodeListMap->NumMyPoints());
    }
    catch (std::exception& rhs)
    {
      catch_message("resizing of ColoredAP_pt", rhs.what(), __FILE__, __LINE__);
      ML_CHK_ERR(-1);
    }
    catch (...)
    {
      catch_message("resizing of ColoredAP_pt", "", __FILE__, __LINE__);
      ML_CHK_ERR(-1);
    }

    Epetra_MultiVector ColoredAP(View, Operator_.OperatorRangeMap(), 
                                 &ColoredAP_ptr[0], NodeListMap->NumMyPoints(), 
                                 NullSpaceDim);
    Epetra_MultiVector ExtColoredAP(View, *NodeListMap, 
                                 &ColoredAP_ptr[0], NodeListMap->NumMyPoints(), 
                                 NullSpaceDim);
    Epetra_Import Importer(*NodeListMap, Operator_.OperatorRangeMap());

    for (int ic = 0; ic < NumColors; ++ic)
    {
      if (ML_Get_PrintLevel() > 8 && Comm().MyPID() == 0)
      {
        if (ic % 20 == 0)
          std::cout << "Processing color " << flush;

        std::cout << ic << " " << flush;
        if (ic % 20 == 19 || ic == NumColors - 1)
          std::cout << std::endl;
        if (ic == NumColors - 1) std::cout << std::endl;
      }

      ColoredP.PutScalar(0.0);

      for (int i = 0; i < BlockPtent_ML->outvec_leng; ++i)
      {
        int allocated = 1;
        int NumEntries;
        int Indices;
        double Values;
        int ierr = ML_Operator_Getrow(BlockPtent_ML, 1 ,&i, allocated,
                                      &Indices,&Values,&NumEntries);
        if (ierr < 0 ||  // something strange in getrow
            NumEntries != 1) // this is the block P
          ML_CHK_ERR(-1);

        const int& Color = (*Colors)[Indices] - 1;
        if (Color != ic)
          continue; // skip this color for this cycle

        for (int k = 0; k < NumPDEEqns_; ++k)
          for (int j = 0; j < NullSpaceDim; ++j)
            ColoredP[j][i * NumPDEEqns_ + k] = 
              NullSpace[j][i * NumPDEEqns_ + k];
      }

      Operator_.Apply(ColoredP, ColoredAP);
      ColoredP = ColoredAP; // just to be safe

      ExtColoredAP.Import(ColoredP, Importer, Insert);

      // populate the actual AP operator, skip some controls to make it faster

      std::vector<int> InsertCols(NullSpaceDim * NumPDEEqns_);
      std::vector<double> InsertValues(NullSpaceDim * NumPDEEqns_);

      for (int i = 0; i < NumAggregates; ++i)
      {
        for (int j = 0; j < (int) (aggregates[i].size()); ++j)
        {
          int GRID = aggregates[i][j];
          int LRID = BlockNodeListMap->LID(GRID); // this is the block ID
          //assert (LRID != -1);
          int GCID = CoarseMap.GID(i * NullSpaceDim);
          //assert (GCID != -1); 
          int color = (*Colors)[i] - 1;
          if (color != ic) continue;

          for (int k = 0; k < NumPDEEqns_; ++k)
          {
            int count = 0;
            int GRID2 = GRID * NumPDEEqns_ + k;
            for (int j = 0; j < NullSpaceDim; ++j)
            {
              double val = ExtColoredAP[j][LRID * NumPDEEqns_ + k];
              if (val != 0.0)
              {
                InsertCols[count] = GCID + j;
                InsertValues[count] = val;
                ++count;
              }
            }
            AP->InsertGlobalValues(1, &GRID2, count, &InsertCols[0], 
                                   &InsertValues[0]);
          }
        }
      }
    }

    ML_Operator_Destroy(&BlockPtent_ML);
  }

  aggregates.resize(0);
  BlockNodeListMap = Teuchos::null;
  NodeListMap = Teuchos::null;

  Colors = Teuchos::null;

  AP->GlobalAssemble(false);
  AP->FillComplete(CoarseMap, FineMap);

#if 0
  try
  {
    AP->OptimizeStorage();
  }
  catch(...)
  {
    // a memory error was reported, typically ReportError.
    // We just continue with fingers crossed.
  }
#endif

  AddAndResetStartTime("computation of the final AP", true); 

  ML_Operator* AP_ML = ML_Operator_Create(Comm_ML());
  ML_Operator_WrapEpetraMatrix(AP.get(), AP_ML);

  // ======== //
  // create R //
  // ======== //
  
  std::vector<int> REntries(NumAggregates * NullSpaceDim);
  for (int AID = 0; AID < NumAggregates; ++AID)
  {
    for (int m = 0; m < NullSpaceDim; ++m)
      REntries[AID * NullSpaceDim + m] = NodesOfAggregate[AID].size() * NumPDEEqns_;
  }

  R_ = rcp(new Epetra_CrsMatrix(Copy, CoarseMap, &REntries[0], true));
  REntries.resize(0);

  for (int AID = 0; AID < NumAggregates; ++AID)
  {
    const int& MySize = NodesOfAggregate[AID].size();

    // FIXME: make it faster
    for (int j = 0; j < MySize; ++j)
      for (int m = 0; m < NumPDEEqns_; ++m)
        for (int k = 0; k < NullSpaceDim; ++k)
        {
          int LCID = NodesOfAggregate[AID][j] * NumPDEEqns_ + m;
          int GCID = FineMap.GID(LCID);
          assert (GCID != -1);

          double& val = NullSpace[k][LCID];

          int GRID = CoarseMap.GID(AID * NullSpaceDim + k);
          int ierr = R_->InsertGlobalValues(GRID, 1, &val, &GCID);
          if (ierr < 0)
            ML_CHK_ERR(-1);
        }
  }

  NodesOfAggregate.resize(0);

  R_->FillComplete(FineMap, CoarseMap);
#if 0
  try
  {
    R_->OptimizeStorage();
  }
  catch(...)
  {
    // a memory error was reported, typically ReportError.
    // We just continue with fingers crossed.
  }
#endif

  ML_Operator* R_ML = ML_Operator_Create(Comm_ML());
  ML_Operator_WrapEpetraMatrix(R_.get(), R_ML);

  AddAndResetStartTime("computation of R", true); 

  // ======== //
  // Create C //
  // ======== //

  C_ML_ = ML_Operator_Create(Comm_ML());
  ML_2matmult(R_ML, AP_ML, C_ML_, ML_MSR_MATRIX);

  ML_Operator_Destroy(&AP_ML);
  ML_Operator_Destroy(&R_ML);
  AP = Teuchos::null;

  C_ = rcp(new ML_Epetra::RowMatrix(C_ML_, &Comm(), false));
  assert (R_->OperatorRangeMap().SameAs(C_->OperatorDomainMap()));

  TotalTime.ResetStartTime();

  AddAndResetStartTime("computation of C", true); 

  if (verbose_)
  {
    std::cout << "Matrix-free preconditioner built. Now building solver for C..." << std::endl; 
  }

  Teuchos::ParameterList& sublist = List_.sublist("ML list");
  sublist.set("PDE equations", NullSpaceDim);
  sublist.set("null space: type", "pre-computed");
  sublist.set("null space: dimension", NewNullSpace.NumVectors());
  sublist.set("null space: vectors", NewNullSpace.Values());

  MLP_ = rcp(new MultiLevelPreconditioner(*C_, sublist, true));

  assert (MLP_.get() != 0);

  IsComputed_ = true;

  AddAndResetStartTime("computation of the preconditioner for C", true); 

  if (verbose_)
  {
    std::cout << std::endl;
    std::cout << "Total CPU time for construction (all included) = ";
    std::cout << TotalCPUTime() << std::endl;
    ML_print_line("=",78);
  }

  return(0);
}
Ejemplo n.º 24
0
ImageSource *Layout_Carousel::GetImageSource(int page,CMColourDevice target,CMTransformFactory *factory,int res,bool completepage)
{
	ImageSource *result=NULL;
	try
	{
		enum IS_TYPE colourspace=GetColourSpace(target);

		IS_ScalingQuality qual=IS_ScalingQuality(state.FindInt("ScalingQuality"));
		if(!res)
			res=state.FindInt("RenderingResolution");

		ImageSource_Montage *mon=new ImageSource_Montage(colourspace,res);

		GetImageableArea();
		int w=(imageablewidth*res)/72;
		int h=(imageableheight*res)/72;
		int ir=(innerradius*res)/72;

		CircleMontage c(w,h);
		c.SetSegments(segments,angleoffset,overlap);
		c.SetInnerRadius(ir);

		ImageSource *source=NULL;
		ImageSource *mask=NULL;
		CMSegment *targetseg=NULL;

		Debug[TRACE] << "Layout_carousel: Left margin: " << leftmargin << endl;

		for(int s=0;s<segments;s+=2)
		{
			Layout_ImageInfo *img=GetNthImage(page,s);

			if(img)
			{
				source=img->GetImageSource(target,factory);
				LayoutRectangle r(source->width,source->height);

				targetseg=c.GetSegmentExtent(s);
		
				RectFit *fit=r.Fit(*targetseg,true,PP_ROTATION_NONE,img->crop_hpan,img->crop_vpan);
		
				source=ISScaleImageBySize(source,fit->width,fit->height,qual);

				mask=new ImageSource_SegmentMask(targetseg,true);
				source=new ImageSource_Crop(source,fit->xoffset,fit->yoffset,mask->width,mask->height);

				source=new ImageSource_Mask(source,mask);
				mon->Add(source,(leftmargin*res)/72+targetseg->x,(topmargin*res)/72+targetseg->y);

				delete fit;
			}
		}

		for(int s=1;s<segments;s+=2)
		{
			Layout_ImageInfo *img=GetNthImage(page,s);

			if(img)
			{
				source=img->GetImageSource(target,factory);
				LayoutRectangle r(source->width,source->height);

				targetseg=c.GetSegmentExtent(s);
		
				RectFit *fit=r.Fit(*targetseg,true,PP_ROTATION_NONE,img->crop_hpan,img->crop_vpan);
		
				source=ISScaleImageBySize(source,fit->width,fit->height,qual);
		
				mask=new ImageSource_SegmentMask(targetseg,false);
				source=new ImageSource_Crop(source,fit->xoffset,fit->yoffset,mask->width,mask->height);
		
				source=new ImageSource_Mask(source,mask);
				mon->Add(source,(leftmargin*res)/72+targetseg->x,(topmargin*res)/72+targetseg->y);
		
				delete fit;
			}
		}

		result=mon;

		if(completepage)
		{
			// If the completepage flag is set we need to render a solid background.
			// This will be used for print preview and TIFF/JPEG export.

			IS_TYPE colourspace=GetColourSpace(target);
			ISDataType white[5]={0,0,0,0,0};
			if(STRIP_ALPHA(colourspace)==IS_TYPE_RGB)
				white[0]=white[1]=white[2]=IS_SAMPLEMAX;

			if(factory)
			{
				RefCountPtr<CMSTransform> transform;
				transform=factory->GetTransform(target,colourspace);
				if(transform)
					transform->Transform(white,white,1);
			}
			mon->Add(new ImageSource_Solid(colourspace,(pagewidth*res)/72,(pageheight*res)/72,white),0,0);
		}
	}
	catch (const char *msg)
	{
		ErrorDialogs.AddMessage(msg);
//		ErrorMessage_Dialog(msg);
	}
	return(result);
}
Ejemplo n.º 25
0
void ServerConnection::StaticKeepAliveCallback(AsyncOpPtr theOp, RefCountPtr theParam)
{
	ServerConnection *thisConnection = (ServerConnection*)theParam.get();
	thisConnection->KeepAliveCallback(theOp);

}
Ejemplo n.º 26
0
//==============================================================================
Ifpack2_NodeFilter::Ifpack2_NodeFilter(const RefCountPtr<const Tpetra_RowMatrix>& Matrix,int nodeID) :
  Matrix_(Matrix),
  NumMyRows_(0),
  NumGlobalRows_(0),
  NumMyNonzeros_(0),
  MaxNumEntries_(0),
  MaxNumEntriesA_(0)
{
  sprintf(Label_,"%s","Ifpack2_NodeFilter");

  //ImportVector_=null;
  //ExportVector_=null;
  ImportVector_=0;
  ExportVector_=0;

  ovA_ = dynamic_cast<const Ifpack2_OverlappingRowMatrix*>(&*Matrix_);
  assert(ovA_ != 0);

  Acrs_=dynamic_cast<const Tpetra_CrsMatrix*>(&ovA_->A());

  NumMyRowsA_ = ovA_->A().NumMyRows();
  NumMyRowsB_ = ovA_->B().NumMyRows();
  
#ifdef HAVE_MPI
  const Tpetra_MpiComm *pComm = dynamic_cast<const Tpetra_MpiComm*>( &(Matrix->Comm()) );
  assert(pComm != NULL);
  MPI_Comm_split(pComm->Comm(),nodeID,pComm->MyPID(),&nodeMPIComm_);
  SubComm_ = rcp( new Tpetra_MpiComm(nodeMPIComm_) );
#else
  SubComm_ = rcp( new Tpetra_SerialComm );
#endif

  NumMyRows_ = Matrix->NumMyRows();
  SubComm_->SumAll(&NumMyRows_,&NumGlobalRows_,1);
  NumMyCols_ = Matrix->NumMyCols();

  // build row map, based on the local communicator
  try {
    const Tpetra_Map &globRowMap = Matrix->RowMatrixRowMap();
    int *myGlobalElts =  globRowMap.MyGlobalElements();
    int numMyElts = globRowMap.NumMyElements();
    Map_ = rcp( new Tpetra_Map(-1,numMyElts,myGlobalElts,globRowMap.IndexBase(),*SubComm_) );
  }
  catch(...) {
    printf("** * Ifpack2_NodeFilter ctor: problem creating row map * **\n\n");
  }


  // build the column map, but don't use a copy constructor, b/c local communicator SubComm_ is
  // different from that of Matrix.
  try {
    const Tpetra_Map &globColMap = Matrix->RowMatrixColMap();
    int *myGlobalElts =  globColMap.MyGlobalElements();
    int numMyElts = globColMap.NumMyElements();
    colMap_ = rcp( new Tpetra_Map(-1,numMyElts,myGlobalElts,globColMap.IndexBase(),*SubComm_) );
  }
  catch(...) {
    printf("** * Ifpack2_NodeFilter ctor: problem creating col map * **\n\n");
  }

  // NumEntries_ will contain the actual number of nonzeros
  // for each localized row (that is, without external nodes,
  // and always with the diagonal entry)
  NumEntries_.resize(NumMyRows_);

  // want to store the diagonal vector. FIXME: am I really useful?
  Diagonal_ = rcp( new Tpetra_Vector(*Map_) );
  if (Diagonal_ == Teuchos::null) IFPACK2_CHK_ERRV(-5);

  // store this for future access to ExtractMyRowCopy().
  // This is the # of nonzeros in the non-local matrix
  MaxNumEntriesA_ = Matrix->MaxNumEntries();
  // tentative value for MaxNumEntries. This is the number of
  // nonzeros in the local matrix
  MaxNumEntries_ = Matrix->MaxNumEntries();

  // ExtractMyRowCopy() will use these vectors
  Indices_.resize(MaxNumEntries_);
  Values_.resize(MaxNumEntries_);

  // now compute:
  // - the number of nonzero per row
  // - the total number of nonzeros
  // - the diagonal entries


  // CMS: [A|B]-Local to Overlap-Local Column Indices
  if(ovA_){
    Ac_LIDMap_=new int[ovA_->A().NumMyCols()+1];
    for(int i=0;i<ovA_->A().NumMyCols();i++) Ac_LIDMap_[i]=colMap_->LID(ovA_->A().RowMatrixColMap().GID(i));    
    Bc_LIDMap_=new int[ovA_->B().NumMyCols()+1];
    for(int i=0;i<ovA_->B().NumMyCols();i++) Bc_LIDMap_[i]=colMap_->LID(ovA_->B().RowMatrixColMap().GID(i));

    Ar_LIDMap_=new int[ovA_->A().NumMyRows()+1];
    for(int i=0;i<ovA_->A().NumMyRows();i++) Ar_LIDMap_[i]=Map_->LID(ovA_->A().RowMatrixRowMap().GID(i));    
    Br_LIDMap_=new int[ovA_->B().NumMyRows()+1];
    for(int i=0;i<ovA_->B().NumMyRows();i++) Br_LIDMap_[i]=Map_->LID(ovA_->B().RowMatrixRowMap().GID(i));

  }
  // end CMS


  // compute nonzeros (total and per-row), and store the
  // diagonal entries (already modified)
  int ActualMaxNumEntries = 0;

  for (int i = 0 ; i < NumMyRows_ ; ++i) {
    
    NumEntries_[i] = 0;
    int Nnz, NewNnz = 0;
    IFPACK2_CHK_ERRV(ExtractMyRowCopy(i,MaxNumEntries_,Nnz,&Values_[0],&Indices_[0]));

    for (int j = 0 ; j < Nnz ; ++j) {
      NewNnz++;
      if (Indices_[j] == i) (*Diagonal_)[i] = Values_[j];
    }

    if (NewNnz > ActualMaxNumEntries)
      ActualMaxNumEntries = NewNnz;

    NumMyNonzeros_ += NewNnz;
    NumEntries_[i] = NewNnz;

  }

  SubComm_->SumAll(&NumMyNonzeros_,&NumGlobalNonzeros_,1);
  MaxNumEntries_ = ActualMaxNumEntries;

  int gpid = Matrix->Comm().MyPID();
  int lpid = SubComm_->MyPID();

  Exporter_ = null;
  Importer_ = null;
  // Check if non-trivial import/export operators
  if (!(RowMatrixRowMap().SameAs(OperatorRangeMap()))) {
    try{Exporter_ = rcp(new Tpetra_Export(RowMatrixRowMap(), OperatorRangeMap()));}
    catch(...) {
      printf("** * gpid %d: Ifpack2_NodeFilter ctor: problem creating Exporter_ * **\n\n",gpid);
    }
  }
  //if (gpid > 1) sleep(8);
/*
  if (gpid == 0)
    printf(">>> node 0 <<<\n");
  if (gpid == 2)
    printf(">>> node 1 <<<\n");
  if (lpid == 0) 
    printf("=======================================\ntarget: RowMatrixColMap()\n====================================\n");
  cout << RowMatrixColMap() << endl;
  sleep(1);
  if (gpid == 0)
    printf("=======================================\nsource: OperatorDomainMap()\n=======================================\n");
  cout << OperatorDomainMap() << endl;
  sleep(1);
*/
/*
  if (!(RowMatrixColMap().SameAs(OperatorDomainMap()))) {
    //TODO change this to RCP
    try{Importer_ = new Tpetra_Import(RowMatrixColMap(), OperatorDomainMap());}
    catch(...) {
      printf("** * gpid %d: Ifpack2_NodeFilter ctor: problem creating Importer_ * **\n\n",gpid);
    }
*/



  if (!(*colMap_).SameAs(*Map_)) {
    //TODO change this to RCP
    try{Importer_ = rcp(new Tpetra_Import(*colMap_, *Map_));}
    catch(...) {
      printf("** * gpid %d: Ifpack2_NodeFilter ctor: problem creating Importer_ * **\n\n",gpid);
    }
/*
    if (lpid == 0)
    printf("=======================================\nIfpack2_NodeFilter Importer_ on node %d\n=======================================\n",(gpid == 0 ? 0: 1)); fflush(stdout);
    cout << *Importer_ << endl;
    if (lpid == 0)
    printf("=======================================\nIfpack2_NodeFilter colmap on node %d\n=======================================\n",(gpid == 0 ? 0: 1)); fflush(stdout);
    cout << *colMap_ << endl;
*/
  }

} //Ifpack2_NodeFilter() ctor