Esempio n. 1
0
XCamReturn
CL3aImageProcessor::apply_3a_result (SmartPtr<X3aResult> &result)
{
    STREAM_LOCK;

    if (result.ptr() == NULL)
        return XCAM_RETURN_BYPASS;

    uint32_t res_type = result->get_type ();

    switch (res_type) {
    case XCAM_3A_RESULT_WHITE_BALANCE: {
        SmartPtr<X3aWhiteBalanceResult> wb_res = result.dynamic_cast_ptr<X3aWhiteBalanceResult> ();
        XCAM_ASSERT (wb_res.ptr ());
        if (_bayer_basic_pipe.ptr ()) {
            _bayer_basic_pipe->set_wb_config (wb_res->get_standard_result ());
            _bayer_basic_pipe->set_3a_result (result);
        }
        break;
    }

    case XCAM_3A_RESULT_BLACK_LEVEL: {
        SmartPtr<X3aBlackLevelResult> bl_res = result.dynamic_cast_ptr<X3aBlackLevelResult> ();
        XCAM_ASSERT (bl_res.ptr ());
        if (_bayer_basic_pipe.ptr ()) {
            _bayer_basic_pipe->set_blc_config (bl_res->get_standard_result ());
            _bayer_basic_pipe->set_3a_result (result);
        }
        break;
    }

    case XCAM_3A_RESULT_DEFECT_PIXEL_CORRECTION: {
        SmartPtr<X3aDefectPixelResult> def_res = result.dynamic_cast_ptr<X3aDefectPixelResult> ();
        XCAM_ASSERT (def_res.ptr ());
        XCAM_UNUSED (def_res);
        break;
    }

    case XCAM_3A_RESULT_RGB2YUV_MATRIX: {
        SmartPtr<X3aColorMatrixResult> csc_res = result.dynamic_cast_ptr<X3aColorMatrixResult> ();
        XCAM_ASSERT (csc_res.ptr ());
        if (_csc.ptr()) {
            _csc->set_rgbtoyuv_matrix (csc_res->get_standard_result ());
            _csc->set_3a_result (result);
        }
        if (_yuv_pipe.ptr()) {
            _yuv_pipe->set_rgbtoyuv_matrix (csc_res->get_standard_result ());
            _yuv_pipe->set_3a_result (result);
        }
        break;
    }

    case XCAM_3A_RESULT_MACC: {
        SmartPtr<X3aMaccMatrixResult> macc_res = result.dynamic_cast_ptr<X3aMaccMatrixResult> ();
        XCAM_ASSERT (macc_res.ptr ());
        if (_yuv_pipe.ptr()) {
            _yuv_pipe->set_macc_table (macc_res->get_standard_result ());
            _yuv_pipe->set_3a_result (result);
        }
        break;
    }
    case XCAM_3A_RESULT_R_GAMMA:
    case XCAM_3A_RESULT_B_GAMMA:
        break;

    case XCAM_3A_RESULT_G_GAMMA:
    case XCAM_3A_RESULT_Y_GAMMA: {
        SmartPtr<X3aGammaTableResult> gamma_res = result.dynamic_cast_ptr<X3aGammaTableResult> ();
        XCAM_ASSERT (gamma_res.ptr ());
        if (_bayer_basic_pipe.ptr ()) {
            _bayer_basic_pipe->set_gamma_table (gamma_res->get_standard_result ());
            _bayer_basic_pipe->set_3a_result (result);
        }
        break;
    }

    case XCAM_3A_RESULT_TEMPORAL_NOISE_REDUCTION_RGB: {
        SmartPtr<X3aTemporalNoiseReduction> tnr_res = result.dynamic_cast_ptr<X3aTemporalNoiseReduction> ();
        XCAM_ASSERT (tnr_res.ptr ());
        XCAM_UNUSED (tnr_res);

        break;
    }

    case XCAM_3A_RESULT_TEMPORAL_NOISE_REDUCTION_YUV: {
        SmartPtr<X3aTemporalNoiseReduction> tnr_res = result.dynamic_cast_ptr<X3aTemporalNoiseReduction> ();
        XCAM_ASSERT (tnr_res.ptr ());
        if (_yuv_pipe.ptr ()) {
            _yuv_pipe->set_tnr_yuv_config(tnr_res->get_standard_result ());
            _yuv_pipe->set_3a_result (result);
        }
        break;
    }

    case XCAM_3A_RESULT_EDGE_ENHANCEMENT: {
        SmartPtr<X3aEdgeEnhancementResult> ee_ee_res = result.dynamic_cast_ptr<X3aEdgeEnhancementResult> ();
        XCAM_ASSERT (ee_ee_res.ptr ());
        if (_bayer_pipe.ptr()) {
            _bayer_pipe->set_ee_config (ee_ee_res->get_standard_result ());
            _bayer_pipe->set_3a_result (result);
        }
#if ENABLE_YEENR_HANDLER
        if (_ee.ptr()) {
            _ee->set_ee_config_ee (ee_ee_res->get_standard_result ());
            _ee->set_3a_result (result);
        }
#endif
        break;
    }

    case XCAM_3A_RESULT_BAYER_NOISE_REDUCTION: {
        SmartPtr<X3aBayerNoiseReduction> bnr_res = result.dynamic_cast_ptr<X3aBayerNoiseReduction> ();
        XCAM_ASSERT (bnr_res.ptr ());
        if (_bayer_pipe.ptr()) {
            _bayer_pipe->set_bnr_config (bnr_res->get_standard_result ());
            _bayer_pipe->set_3a_result (result);
        }

        break;
    }

    case XCAM_3A_RESULT_BRIGHTNESS: {
        SmartPtr<X3aBrightnessResult> brightness_res = result.dynamic_cast_ptr<X3aBrightnessResult> ();
        XCAM_ASSERT (brightness_res.ptr ());
        float brightness_level = ((XCam3aResultBrightness)brightness_res->get_standard_result()).brightness_level;
        XCAM_UNUSED (brightness_level);
        break;
    }

    case XCAM_3A_RESULT_WAVELET_NOISE_REDUCTION: {
        SmartPtr<X3aWaveletNoiseReduction> wavelet_res = result.dynamic_cast_ptr<X3aWaveletNoiseReduction> ();
        XCAM_ASSERT (wavelet_res.ptr ());
        if (_wavelet.ptr()) {
            _wavelet->set_denoise_config (wavelet_res->get_standard_result ());
        }
        if (_newwavelet.ptr()) {
            _newwavelet->set_denoise_config (wavelet_res->get_standard_result ());
        }
        break;
    }

    case XCAM_3A_RESULT_FACE_DETECTION: {
        SmartPtr<X3aFaceDetectionResult> fd_res = result.dynamic_cast_ptr<X3aFaceDetectionResult> ();
        XCAM_ASSERT (fd_res.ptr ());
        if (_wire_frame.ptr ()) {
            _wire_frame->set_wire_frame_config (fd_res->get_standard_result_ptr (), get_scaler_factor ());
        }
        break;
    }

    default:
        XCAM_LOG_WARNING ("CL3aImageProcessor unknow 3a result:%d", res_type);
        break;
    }

    return XCAM_RETURN_NO_ERROR;
}
/*
* Check preconditions
* return PRL_ERR_SUCCESS - no errors
* 	 PRL_ERR_VM_MIGRATE_CHECKING_PRECONDITIONS_FAILED - precondition error
*	 other - internal error
*/
PRL_RESULT Task_MigrateCtSource::CheckVmMigrationPreconditions()
{
	PRL_RESULT nRetCode = PRL_ERR_SUCCESS;

	CDispToDispCommandPtr pRequest =
		CDispToDispProtoSerializer::CreateVmMigrateCheckPreconditionsCommand(
			m_pVmConfig->toString(),
			m_cHostInfo.toString(),
			m_sTargetServerCtHomePath,
			QString(),
			QStringList(),
			QString(),
			0,
			m_nMigrationFlags,
			m_nReservedFlags | PVM_CT_MIGRATE | PVM_FULL_DISP_TASK,
			m_nPrevVmState
		);

	SmartPtr<IOPackage> pPackage =
		DispatcherPackage::createInstance(pRequest->GetCommandId(), pRequest->GetCommand()->toString());
	SmartPtr<IOPackage> pReply;
	IOSendJob::Response pResponse;

	m_hCheckReqJob = m_pIoClient->sendPackage(pPackage);
	if (m_pIoClient->waitForSend(m_hCheckReqJob, m_nTimeout) != IOSendJob::Success) {
		WRITE_TRACE(DBG_FATAL, "Package sending failure");
		return PRL_ERR_CT_MIGRATE_INTERNAL_ERROR;
	}
	if (m_pIoClient->waitForResponse(m_hCheckReqJob, m_nTimeout) != IOSendJob::Success) {
		WRITE_TRACE(DBG_FATAL, "Responce receiving failure");
		return PRL_ERR_CT_MIGRATE_INTERNAL_ERROR;
	}
	pResponse = m_pIoClient->takeResponse(m_hCheckReqJob);
	if (pResponse.responseResult != IOSendJob::Success) {
		WRITE_TRACE(DBG_FATAL, "Job failure: responseResult:%x", pResponse.responseResult);
		return PRL_ERR_CT_MIGRATE_INTERNAL_ERROR;
	}

	pReply = pResponse.responsePackages[0];
	if (!pReply.isValid()) {
		WRITE_TRACE(DBG_FATAL, "Invalid reply");
		return PRL_ERR_CT_MIGRATE_INTERNAL_ERROR;
	}
	if ((pReply->header.type != DispToDispResponseCmd) && (pReply->header.type != VmMigrateCheckPreconditionsReply))
	{
		WRITE_TRACE(DBG_FATAL, "Unexpected response type (%d)", pReply->header.type);
		return PRL_ERR_OPERATION_FAILED;
	}

	CDispToDispCommandPtr pCmd =
		CDispToDispProtoSerializer::ParseCommand(
			DispToDispResponseCmd,
			UTF8_2QSTR(pReply->buffers[0].getImpl())
		);

	if (pReply->header.type == DispToDispResponseCmd) {
		CDispToDispResponseCommand *pResponseCmd =
			CDispToDispProtoSerializer::CastToDispToDispCommand<CDispToDispResponseCommand>(pCmd);
		nRetCode = pResponseCmd->GetRetCode();
		getLastError()->fromString(pResponseCmd->GetErrorInfo()->toString());
		return nRetCode;
	} else {
		CVmMigrateCheckPreconditionsReply *pResponseCmd =
			CDispToDispProtoSerializer::CastToDispToDispCommand<CVmMigrateCheckPreconditionsReply>(pCmd);
		m_lstCheckPrecondsErrors = pResponseCmd->GetCheckPreconditionsResult();
		m_nReservedFlags = pResponseCmd->GetCommandFlags();
		if (!(m_nReservedFlags & PVM_CT_MIGRATE)) {
			/* migration of the containers does not supports */
			WRITE_TRACE(DBG_FATAL, "Remote server does not support migration of the containers");
			return PRL_ERR_UNIMPLEMENTED;
		}
	}
	if (!m_lstCheckPrecondsErrors.isEmpty())
		nRetCode = PRL_ERR_VM_MIGRATE_CHECKING_PRECONDITIONS_FAILED;

	return nRetCode;
}
Esempio n. 3
0
  void Ma86SolverInterface::RegisterOptions(SmartPtr<RegisteredOptions> roptions)
  {
    roptions->AddIntegerOption(
      "ma86_print_level",
      "Debug printing level for the linear solver MA86",
      -1,
      "");
    /*
    "<0 no printing.\n"
    "0  Error and warning messages only.\n"
    "=1 Limited diagnostic printing.\n"
    ">1 Additional diagnostic printing.");
    */
    roptions->AddLowerBoundedIntegerOption(
      "ma86_nemin",
      "Node Amalgamation parameter",
      1, 32,
      "Two nodes in elimination tree are merged if result has fewer than "
      "ma86_nemin variables.");
    roptions->AddLowerBoundedNumberOption(
      "ma86_small",
      "Zero Pivot Threshold",
      0.0, false, 1e-20,
      "Any pivot less than ma86_small is treated as zero.");
    roptions->AddLowerBoundedNumberOption(
      "ma86_static",
      "Static Pivoting Threshold",
      0.0, false, 0.0,
      "See MA86 documentation. Either ma86_static=0.0 or "
      "ma86_static>ma86_small. ma86_static=0.0 disables static pivoting.");
    roptions->AddBoundedNumberOption(
      "ma86_u",
      "Pivoting Threshold",
      0.0, false, 0.5, false, 1e-8,
      "See MA86 documentation.");
    roptions->AddBoundedNumberOption(
      "ma86_umax",
      "Maximum Pivoting Threshold",
      0.0, false, 0.5, false, 1e-4,
      "Maximum value to which u will be increased to improve quality.");
    roptions->AddStringOption3(
      "ma86_scaling",
      "Controls scaling of matrix",
      "mc64",
      "none", "Do not scale the linear system matrix",
      "mc64", "Scale linear system matrix using MC64",
      "mc77", "Scale linear system matrix using MC77 [1,3,0]",
      "This option controls scaling for the solver HSL_MA86.");
    roptions->AddStringOption3(
      "ma86_order",
      "Controls type of ordering used by HSL_MA86",
#ifdef COINHSL_HAS_METIS
      "auto",
#else
      "amd",
#endif
      "auto", "Try both AMD and MeTiS, pick best",
      "amd", "Use the HSL_MC68 approximate minimum degree algorithm",
      "metis", "Use the MeTiS nested dissection algorithm (if available)",
      "This option controls ordering for the solver HSL_MA86.");
  }
Esempio n. 4
0
UT_sint32 GR_MathManager::getDescent(UT_sint32 uid)
{
	SmartPtr<libxml2_MathView>  pMathView = m_vecMathView.getNthItem(uid);
	BoundingBox box = pMathView->getBoundingBox();
	return m_pAbiContext->toAbiLayoutUnits(box.depth);
}
  bool RestoIterateInitializer::SetInitialIterates()
  {
    DBG_START_METH("RestoIterateInitializer::SetInitialIterates",
                   dbg_verbosity);

    // Get a grip on the restoration phase NLP and obtain the pointers
    // to the original NLP data
    SmartPtr<RestoIpoptNLP> resto_ip_nlp =
      static_cast<RestoIpoptNLP*> (&IpNLP());
    SmartPtr<IpoptNLP> orig_ip_nlp =
      static_cast<IpoptNLP*> (&resto_ip_nlp->OrigIpNLP());
    SmartPtr<IpoptData> orig_ip_data =
      static_cast<IpoptData*> (&resto_ip_nlp->OrigIpData());
    SmartPtr<IpoptCalculatedQuantities> orig_ip_cq =
      static_cast<IpoptCalculatedQuantities*> (&resto_ip_nlp->OrigIpCq());

    // Set the value of the barrier parameter
    Number resto_mu;
    resto_mu = Max(orig_ip_data->curr_mu(),
                   orig_ip_cq->curr_c()->Amax(),
                   orig_ip_cq->curr_d_minus_s()->Amax());
    IpData().Set_mu(resto_mu);
    Jnlst().Printf(J_DETAILED, J_INITIALIZATION,
                   "Initial barrier parameter resto_mu = %e\n", resto_mu);

    /////////////////////////////////////////////////////////////////////
    //                   Initialize primal varialbes                   //
    /////////////////////////////////////////////////////////////////////

    // initialize the data structures in the restoration phase NLP
    IpData().InitializeDataStructures(IpNLP(), false, false, false,
                                      false, false);

    SmartPtr<Vector> new_x = IpData().curr()->x()->MakeNew();
    SmartPtr<CompoundVector> Cnew_x =
      static_cast<CompoundVector*> (GetRawPtr(new_x));

    // Set the trial x variables from the original NLP
    Cnew_x->GetCompNonConst(0)->Copy(*orig_ip_data->curr()->x());

    // Compute the initial values for the n and p variables for the
    // equality constraints
    Number rho = resto_ip_nlp->Rho();
    DBG_PRINT((1,"rho = %e\n", rho));
    SmartPtr<Vector> nc = Cnew_x->GetCompNonConst(1);
    SmartPtr<Vector> pc = Cnew_x->GetCompNonConst(2);
    SmartPtr<const Vector> cvec = orig_ip_cq->curr_c();
    DBG_PRINT_VECTOR(2, "cvec", *cvec);
    SmartPtr<Vector> a = nc->MakeNew();
    SmartPtr<Vector> b = nc->MakeNew();
    a->Set(resto_mu/(2.*rho));
    a->Axpy(-0.5, *cvec);
    b->Copy(*cvec);
    b->Scal(resto_mu/(2.*rho));
    DBG_PRINT_VECTOR(2, "a", *a);
    DBG_PRINT_VECTOR(2, "b", *b);
    solve_quadratic(*a, *b, *nc);
    pc->Copy(*cvec);
    pc->Axpy(1., *nc);
    DBG_PRINT_VECTOR(2, "nc", *nc);
    DBG_PRINT_VECTOR(2, "pc", *pc);

    // initial values for the n and p variables for the inequality
    // constraints
    SmartPtr<Vector> nd = Cnew_x->GetCompNonConst(3);
    SmartPtr<Vector> pd = Cnew_x->GetCompNonConst(4);
    cvec = orig_ip_cq->curr_d_minus_s();
    a = nd->MakeNew();
    b = nd->MakeNew();
    a->Set(resto_mu/(2.*rho));
    a->Axpy(-0.5, *cvec);
    b->Copy(*cvec);
    b->Scal(resto_mu/(2.*rho));
    solve_quadratic(*a, *b, *nd);
    pd->Copy(*cvec);
    pd->Axpy(1., *nd);
    DBG_PRINT_VECTOR(2, "nd", *nd);
    DBG_PRINT_VECTOR(2, "pd", *pd);

    // Leave the slacks unchanged
    SmartPtr<const Vector> new_s = orig_ip_data->curr()->s();

    // Now set the primal trial variables
    DBG_PRINT_VECTOR(2,"new_s",*new_s);
    DBG_PRINT_VECTOR(2,"new_x",*new_x);
    SmartPtr<IteratesVector> trial = IpData().curr()->MakeNewContainer();
    trial->Set_primal(*new_x, *new_s);
    IpData().set_trial(trial);

    DBG_PRINT_VECTOR(2, "resto_c", *IpCq().trial_c());
    DBG_PRINT_VECTOR(2, "resto_d_minus_s", *IpCq().trial_d_minus_s());

    /////////////////////////////////////////////////////////////////////
    //                   Initialize bound multipliers                  //
    /////////////////////////////////////////////////////////////////////

    SmartPtr<Vector> new_z_L = IpData().curr()->z_L()->MakeNew();
    SmartPtr<CompoundVector> Cnew_z_L =
      static_cast<CompoundVector*> (GetRawPtr(new_z_L));
    DBG_ASSERT(IsValid(Cnew_z_L));
    SmartPtr<Vector> new_z_U = IpData().curr()->z_U()->MakeNew();
    SmartPtr<Vector> new_v_L = IpData().curr()->v_L()->MakeNew();
    SmartPtr<Vector> new_v_U = IpData().curr()->v_U()->MakeNew();

    // multipliers for the original bounds are
    SmartPtr<const Vector> orig_z_L = orig_ip_data->curr()->z_L();
    SmartPtr<const Vector> orig_z_U = orig_ip_data->curr()->z_U();
    SmartPtr<const Vector> orig_v_L = orig_ip_data->curr()->v_L();
    SmartPtr<const Vector> orig_v_U = orig_ip_data->curr()->v_U();

    // Set the new multipliers to the min of the penalty parameter Rho
    // and their current value
    SmartPtr<Vector> Cnew_z_L0 = Cnew_z_L->GetCompNonConst(0);
    Cnew_z_L0->Set(rho);
    Cnew_z_L0->ElementWiseMin(*orig_z_L);
    new_z_U->Set(rho);
    new_z_U->ElementWiseMin(*orig_z_U);
    new_v_L->Set(rho);
    new_v_L->ElementWiseMin(*orig_v_L);
    new_v_U->Set(rho);
    new_v_U->ElementWiseMin(*orig_v_U);

    // Set the multipliers for the p and n bounds to the "primal" multipliers
    SmartPtr<Vector> Cnew_z_L1 = Cnew_z_L->GetCompNonConst(1);
    Cnew_z_L1->Set(resto_mu);
    Cnew_z_L1->ElementWiseDivide(*nc);
    SmartPtr<Vector> Cnew_z_L2 = Cnew_z_L->GetCompNonConst(2);
    Cnew_z_L2->Set(resto_mu);
    Cnew_z_L2->ElementWiseDivide(*pc);
    SmartPtr<Vector> Cnew_z_L3 = Cnew_z_L->GetCompNonConst(3);
    Cnew_z_L3->Set(resto_mu);
    Cnew_z_L3->ElementWiseDivide(*nd);
    SmartPtr<Vector> Cnew_z_L4 = Cnew_z_L->GetCompNonConst(4);
    Cnew_z_L4->Set(resto_mu);
    Cnew_z_L4->ElementWiseDivide(*pd);

    // Set those initial values to be the trial values in Data
    trial = IpData().trial()->MakeNewContainer();
    trial->Set_bound_mult(*new_z_L, *new_z_U, *new_v_L, *new_v_U);
    IpData().set_trial(trial);

    /////////////////////////////////////////////////////////////////////
    //           Initialize equality constraint multipliers            //
    /////////////////////////////////////////////////////////////////////

    DefaultIterateInitializer::least_square_mults(
      Jnlst(), IpNLP(), IpData(), IpCq(),
      resto_eq_mult_calculator_, constr_mult_init_max_);

    // upgrade the trial to the current point
    IpData().AcceptTrialPoint();

    DBG_PRINT_VECTOR(2, "y_c", *IpData().curr()->y_c());
    DBG_PRINT_VECTOR(2, "y_d", *IpData().curr()->y_d());

    DBG_PRINT_VECTOR(2, "z_L", *IpData().curr()->z_L());
    DBG_PRINT_VECTOR(2, "z_U", *IpData().curr()->z_U());
    DBG_PRINT_VECTOR(2, "v_L", *IpData().curr()->v_L());
    DBG_PRINT_VECTOR(2, "v_U", *IpData().curr()->v_U());

    return true;
  }
Esempio n. 6
0
void init(){

  //  scene.getLight(0).setOn(false);
  scene.getLight(0).setDiffuse(GeomColor(255,255,255,50));

  SceneLight &l = scene.getLight(1);
  static Camera cam(Vec(0,0,600,1),
                    Vec(0,0,-1,1),
                    Vec(0,-1,0,1));
  cam.setResolution(Size(1024,1024));
  scene.setGravity(Vec(0,0,-1000));

  l.setShadowCam(new Camera(cam));
  l.setShadowEnabled(true);
  l.setAnchorToWorld();
  l.setPosition(Vec(0,0,600,1));
  l.setOn(true);
  l.setSpecularEnabled(true);
  l.setDiffuseEnabled(true);
  l.setSpecular(GeomColor(0,100,255,255));
  l.setDiffuse(GeomColor(255,100,0,30));

  scene.setPropertyValue("shadows.use improved shading",true);
  scene.setPropertyValue("shadows.resolution",2048);
  scene.setPropertyValue("shadows.bias",10);


  //static const int W=20,H=13,DIM=W*H;
  static const int W=pa("-paper-dim",0), H=pa("-paper-dim",1);
  static Img8u frontFace = load<icl8u>(*pa("-ff"));
  static Img8u backFace = load<icl8u>(*pa("-bf"));

  const Size s(210,297);
  const Vec corners[4] = {
    Vec(-s.width/2, -s.height/2, 150,1),
    Vec(s.width/2, -s.height/2, 150,1),
    Vec(s.width/2, s.height/2, 150,1),
    Vec(-s.width/2, s.height/2, 150,1),
  };

  paper = new ManipulatablePaper(&scene,&scene,W,H,corners,true,&frontFace,&backFace);
  //scene.removeObject(paper);
  //paper->addShadow(-74.5);


  if(pa("-o")){
    std::vector<Camera> cams;
    for(int i=0;i<3;++i){
      cams.push_back(Camera(*pa("-c",i)));
    }
    capturer = new SceneMultiCamCapturer(scene, cams);
    //    Scene::enableSharedOffscreenRendering();
    scene.setDrawCamerasEnabled(false);
  }

  gui << Draw3D(Size::VGA).minSize(32,24).handle("draw")
      << (VBox().maxSize(12,100).minSize(12,1)
          << ( HBox()
               << Fps(10).handle("fps")
               << Button("add clutter").handle("add")
               )
          << ( HBox()
               << Button("stopped","running",true).out("run")
               << Button("paper ...").handle("props")
               )
          << ( HBox()
               << CheckBox("show cubes").out("showCubes")
               << CheckBox("show texture",false).out("showTexture")
               << CheckBox("show links",false).out("showLinks")
             )
          << FSlider(0,1,0.5).out("vertexMoveFactor").label("manual force")
          << FSlider(1,100,10).out("attractorStreangth").label("attractor force")
          << FSlider(0.0001,0.9999,0.9).handle("globalStiffness").label("global paper stiffness")
          << ( HBox()
               << Button("reset paper").handle("resetPaper")
               << Combo("1,5,10,25,!200,300,500").handle("maxFPS").label("max FPS")
               )
          << FSlider(0.1,20,2).handle("cm").label("collision margin")

          << ( HBox()
               << Button("memorize").handle("mem")
               << CheckBox("soften with mouse",true).handle("soften")
               << Button("test").handle("pct")
             )
          )

      << Show();

  propGUI << Prop("paper").minSize(16,1).maxSize(16,100) << Create();

  gui["pct"].registerCallback(paper_coords_test);
  gui["props"].registerCallback(utils::function((GUI&)propGUI,&GUI::switchVisibility));
  gui["resetPaper"].registerCallback(reset_paper);
  gui["globalStiffness"].registerCallback(change_global_stiffness);

  scene.PhysicsWorld::addObject(&ground);
  scene.Scene::addObject(&groundVis);

  DrawHandle3D draw = gui["draw"];
  draw->install(paper->createMouseHandler(0));
  draw->install(&foldLine);
  draw->link(scene.getGLCallback(0));

  foldLine.cb = utils::function(fold_line_cb);



}
Esempio n. 7
0
void GR_MathManager::initialize(void)
{
	XAP_App *pApp = XAP_App::getApp();

	// load the gtkmathview settings and operator dictionaries from the private user directory, ...
	UT_UTF8String userConfDir(pApp->getUserPrivateDirectory());
	UT_UTF8String userDictDir(pApp->getUserPrivateDirectory());
	UT_UTF8String userCombiningDictDir(pApp->getUserPrivateDirectory());
	UT_UTF8String userLocalDictDir(pApp->getUserPrivateDirectory());
#if defined(WIN32)
	userConfDir += "\\math\\gtkmathview.conf.xml";
	userDictDir += "\\math\\dictionary.xml";
	userCombiningDictDir += "\\math\\dictionary-combining.xml";
	userLocalDictDir += "\\math\\dictionary-local.xml";
#else
	userConfDir += "/math/gtkmathview.conf.xml";
	userDictDir += "/math/dictionary.xml";
	userCombiningDictDir += "/math/dictionary-combining.xml";
	userLocalDictDir += "/math/dictionary-local.xml";
#endif

	// ... or from the (common) AbiSuite directory
	UT_UTF8String libConfDir(pApp->getAbiSuiteLibDir());
	UT_UTF8String libDictDir(pApp->getAbiSuiteLibDir());
	UT_UTF8String libCombiningDictDir(pApp->getAbiSuiteLibDir());
	UT_UTF8String libLocalDictDir(pApp->getAbiSuiteLibDir());
#if defined(WIN32)	 
	libConfDir += "\\math\\gtkmathview.conf.xml";
	libDictDir += "\\math\\dictionary.xml";
	libCombiningDictDir += "\\math\\dictionary-combining.xml";
	libLocalDictDir += "\\math\\dictionary-local.xml";
#else
	libConfDir += "/math/gtkmathview.conf.xml";
	libDictDir += "/math/dictionary.xml";
	libCombiningDictDir += "/math/dictionary-combining.xml";
	libLocalDictDir += "/math/dictionary-local.xml";
#endif

	// add the configuration paths
 
#ifdef TOOLKIT_COCOA
	if (const char * resources = getenv("ABIWORD_COCOA_BUNDLED_RESOURCES"))
	{
		UT_UTF8String bundleConfDir(resources);
		bundleConfDir += "/gtkmathview/gtkmathview.conf.xml";
		Configuration::addConfigurationPath(bundleConfDir.utf8_str());
	}
#endif
	Configuration::addConfigurationPath( libConfDir.utf8_str() );
	Configuration::addConfigurationPath( userConfDir.utf8_str() );

	SmartPtr<AbstractLogger> logger = Logger::create();
	m_pLogger = logger;
	SmartPtr<Configuration> configuration = initConfiguration<libxml2_MathView>(logger, getenv("GTKMATHVIEWCONF"));
	logger->setLogLevel(LOG_INFO);
	 
	// add the dictionary paths

#ifdef TOOLKIT_COCOA
	if (const char * resources = getenv("ABIWORD_COCOA_BUNDLED_RESOURCES"))
	{
		UT_UTF8String bundleDictDir(resources);
		UT_UTF8String bundleCombiningDictDir(resources);
		UT_UTF8String bundleLocalDictDir(resources);

		bundleDictDir += "/gtkmathview/dictionary.xml";
		bundleCombiningDictDir += "/gtkmathview/dictionary-combining.xml";
		bundleLocalDictDir += "/gtkmathview/dictionary-local.xml";

		configuration->add("dictionary/path", bundleDictDir.utf8_str());
		configuration->add("dictionary/path", bundleCombiningDictDir.utf8_str());
		configuration->add("dictionary/path", bundleLocalDictDir.utf8_str());
	}
#endif
	configuration->add("dictionary/path", libDictDir.utf8_str());
	configuration->add("dictionary/path", libCombiningDictDir.utf8_str());
	configuration->add("dictionary/path", libLocalDictDir.utf8_str());

	configuration->add("dictionary/path", userDictDir.utf8_str());
	configuration->add("dictionary/path", userCombiningDictDir.utf8_str());
	configuration->add("dictionary/path", userLocalDictDir.utf8_str());

	SmartPtr<GR_Abi_MathGraphicDevice> mathGraphicDevice 
			= GR_Abi_MathGraphicDevice::create(logger, configuration, getGraphics());
	m_pMathGraphicDevice = mathGraphicDevice;
	m_pAbiContext = new GR_Abi_RenderingContext(getGraphics());
	UT_DEBUGMSG(("MAthView New rendering context %p Graphics %p \n",m_pAbiContext,getGraphics()));
	m_pOperatorDictionary = initOperatorDictionary<libxml2_MathView>(logger, configuration);
}
Esempio n. 8
0
HRESULT 
ISampleCaptureGraphBuilder::ConnectAudioPinToMultiplexer( 
                                            IPin *pPin, 
                                            IBaseFilter *pMultiplexer)
{
    if( !pPin || !pMultiplexer )
    {
        return E_INVALIDARG;
    }

    REGPINMEDIUM pinMedium;
    HRESULT hr = GetMedium( pPin, pinMedium );
    if( FAILED( hr ) )
    {
        return hr;
    }

    SmartPtr<IBaseFilter> pEncoder;
    SmartPtr<IEnumMoniker> pEncoders;

    if( FALSE == ::IsEqualGUID( pinMedium.clsMedium, GUID_NULL ) )
    {
        //
        //  search through encoders category; identify
        //  the encoder using the medium
        //
        hr = GetEncodersByCategory( &pEncoders );
        if( FAILED( hr ) )
        {
            return hr;
        }

        hr = FindEncoder( pEncoders, pinMedium, &pEncoder );
        if( SUCCEEDED( hr ) )
        {
            hr = graph_->AddFilter( pEncoder, L"Audio Encoder" );
            if( SUCCEEDED( hr ) &&
                SUCCEEDED( ConnectPin( pPin, pEncoder ) ) &&
                SUCCEEDED( ConnectFilters( pEncoder, pMultiplexer ) )
            )
            {
                return S_OK;
            }
        }
        
        
        pEncoders = NULL;
        hr = GetEncodersByEnumerating( pPin, pinMedium, &pEncoders );
        if( FAILED( hr ) )
        {
            return hr;
        }

        hr = FindEncoder( pEncoders, pinMedium, &pEncoder );
        if( SUCCEEDED( hr ) )
        {
            hr = graph_->AddFilter( pEncoder, L"Audio Encoder" );
            if( SUCCEEDED( hr ) &&
                SUCCEEDED( ConnectPin( pPin, pEncoder ) ) &&
                SUCCEEDED( ConnectFilters( pEncoder, pMultiplexer ) )
            )
            {
                return S_OK;
            }
        }
        return E_FAIL;
    }


    //
    //  Search throgh the codec category 
    //  
    hr = GetEncodersByCategory( &pEncoders );
    if( FAILED( hr ) )
    {
        return hr;
    }


    SmartPtr<IBaseFilter>    pFilter;
    SmartPtr<IMoniker>       pMoniker;
    ULONG                   fetched;
    while( pFilter.Release(), pMoniker.Release(), S_OK == pEncoders->Next( 1, &pMoniker, &fetched ) )
    {
        hr = pMoniker->BindToObject(
            0, 0, IID_IBaseFilter, reinterpret_cast<void **>( &pFilter ) );
        if( FAILED( hr ) )
        {
            continue;
        }

        hr = graph_->AddFilter( pFilter, L"Audio Encoder" );
        if( FAILED( hr ) )
        {
            continue;
        }

        hr = ConnectPin( pPin, pFilter );
        if( FAILED( hr ) )
        {
            graph_->RemoveFilter( pFilter );
            continue;
        }

        hr = ConnectFilters( pFilter, pMultiplexer );
        if( SUCCEEDED( hr ) )
        {
            return S_OK;
        }
        graph_->RemoveFilter( pFilter );
    }

    return E_FAIL;

}
Esempio n. 9
0
HRESULT 
ISampleCaptureGraphBuilder::CreateVideoPin(
        IMpeg2Demultiplexer *pIMpeg2Demux )
{
    if( !pIMpeg2Demux )
    {
        return E_INVALIDARG;
    }

    AM_MEDIA_TYPE amTypeVideo;
    amTypeVideo.majortype = MEDIATYPE_Video;
    amTypeVideo.subtype = MEDIASUBTYPE_MPEG2_VIDEO;
    amTypeVideo.bFixedSizeSamples = TRUE;
    amTypeVideo.bTemporalCompression = 0;
    amTypeVideo.formattype = FORMAT_MPEG2Video;
    amTypeVideo.pUnk = NULL;
    amTypeVideo.cbFormat = sizeof( Mpeg2ProgramVideo );
    amTypeVideo.pbFormat = Mpeg2ProgramVideo;

    //
    // Create video pin
    //

    SmartPtr<IPin> pVideoOutPin;
    HRESULT hr = pIMpeg2Demux->CreateOutputPin( &amTypeVideo, L"MpegVideo", &pVideoOutPin );
    if( FAILED( hr ) )
    {
        return hr;
    }


    SmartPtr<IMPEG2StreamIdMap> pIVideoPIDMap;
    hr = pVideoOutPin->QueryInterface( &pIVideoPIDMap );
    if( FAILED( hr ) )
    {
        return hr;
    }

    hr = pIVideoPIDMap->MapStreamId(VidPID_, MPEG2_PROGRAM_ELEMENTARY_STREAM , 0, 0);
    if( FAILED( hr ) )
    {
        return hr;
    }


#ifdef USE_VMR
    //
    //  Get the VMR interface and add it to the graph
    //
    SmartPtr<IBaseFilter> pVMR;
    hr = pVMR.CoCreateInstance( CLSID_VideoMixingRenderer );
    if( FAILED( hr ) )
    {
        return hr;
    }

    hr = graph_->AddFilter( pVMR, L"VMR" );
    if( FAILED( hr ) )
    {
        return hr;
    }

    //
    //before rendering the VMR, make the number of streams 1
    //
    SmartPtr<IVMRFilterConfig> pConfig;
    hr = pVMR.QueryInterface( &pConfig );
    if( FAILED( hr ) )
    {
        return hr;
    }
    hr = pConfig->SetNumberOfStreams( 1 );
    if( FAILED( hr ) )
    {
        return hr;
    }


    //
    //  Get the input pin from the VMR
    //
    SmartPtr<IPin> pInputPin;
    hr = graphBuilder2_->FindPin(
            static_cast<IBaseFilter *>( pVMR ),  
            PINDIR_INPUT, 
            NULL, 
            NULL, 
            TRUE, 
            0, 
            &pInputPin
        );
    if( FAILED( hr ) )
    {

        hr = pIMpeg2Demux->DeleteOutputPin(L"MpegVideo");
        graph_->RemoveFilter( pVMR );
        return hr;
    }

    return graph_->Connect( pVideoOutPin, pInputPin );
#endif

    return hr;
}
Esempio n. 10
0
 static pointer get (const SmartPtr &smartptr)
 {  return smartptr.get();}
int main (int argc, char *argv[])
{
    const char *file_in_name = NULL;
    const char *file_out_name = NULL;

    bool need_save_output = true;
    bool blind = true;

    const struct option long_opts[] = {
        {"input", required_argument, NULL, 'i'},
        {"output", required_argument, NULL, 'o'},
        {"blind", required_argument, NULL, 'b'},
        {"save", required_argument, NULL, 's'},
        {"help", no_argument, NULL, 'H'},
        {0, 0, 0, 0},
    };

    int opt = -1;
    while ((opt = getopt_long (argc, argv, "", long_opts, NULL)) != -1)
    {
        switch (opt) {
        case 'i':
            file_in_name = optarg;
            break;
        case 'o':
            file_out_name = optarg;
            break;
        case 'b':
            blind = (strcasecmp (optarg, "false") == 0 ? false : true);
            break;
        case 's':
            need_save_output = (strcasecmp (optarg, "false") == 0 ? false : true);
            break;
        case 'H':
            usage (argv[0]);
            return 0;
        default:
            printf ("getopt_long return unknown value:%c\n", opt);
            usage (argv[0]);
            return -1;
        }
    }

    if (optind < argc || argc < 2)
    {
        printf ("unknown option %s\n", argv[optind]);
        usage (argv[0]);
        return -1;
    }

    if (!file_in_name || !file_out_name)
    {
        XCAM_LOG_ERROR ("input/output path is NULL");
        return -1;
    }

    printf ("Description-----------\n");
    printf ("input image file:%s\n", file_in_name);
    printf ("output file :%s\n", file_out_name);
    printf ("blind deblurring:%s\n", blind ? "true" : "false");
    printf ("need save file:%s\n", need_save_output ? "true" : "false");
    printf ("----------------------\n");

    SmartPtr<CVImageSharp> sharp = new CVImageSharp ();
    cv::Mat input_image = cv::imread (file_in_name, cv::IMREAD_COLOR);
    cv::Mat output_image;
    if (input_image.empty ())
    {
        XCAM_LOG_ERROR ("input file read error");
        return -1;
    }
    if (blind)
    {
        blind_deblurring (input_image, output_image);
    }
    else
    {
        non_blind_deblurring (input_image, output_image);
    }
    float input_sharp = sharp->measure_sharp (input_image);
    float output_sharp = sharp->measure_sharp (output_image);
    if (need_save_output)
    {
        cv::imwrite (file_out_name, output_image);
    }
    XCAM_ASSERT (output_sharp > input_sharp);

    return 0;
}
Esempio n. 12
0
  void Ma27TSolverInterface::RegisterOptions(SmartPtr<RegisteredOptions> roptions)
  {
    roptions->AddBoundedNumberOption(
      "ma27_pivtol",
      "Pivot tolerance for the linear solver MA27.",
      0.0, true, 1.0, true, 1e-8,
      "A smaller number pivots for sparsity, a larger number pivots for "
      "stability.  This option is only available if Ipopt has been compiled "
      "with MA27.");
    roptions->AddBoundedNumberOption(
      "ma27_pivtolmax",
      "Maximum pivot tolerance for the linear solver MA27.",
      0.0, true, 1.0, true, 1e-4,
      "Ipopt may increase pivtol as high as pivtolmax to get a more accurate "
      "solution to the linear system.  This option is only available if "
      "Ipopt has been compiled with MA27.");
    roptions->AddLowerBoundedNumberOption(
      "ma27_liw_init_factor",
      "Integer workspace memory for MA27.",
      1.0, false, 5.0,
      "The initial integer workspace memory = liw_init_factor * memory "
      "required by unfactored system. Ipopt will increase the workspace "
      "size by meminc_factor if required.  This option is only available if "
      "Ipopt has been compiled with MA27.");
    roptions->AddLowerBoundedNumberOption(
      "ma27_la_init_factor",
      "Real workspace memory for MA27.",
      1.0, false, 5.0,
      "The initial real workspace memory = la_init_factor * memory "
      "required by unfactored system. Ipopt will increase the workspace"
      " size by meminc_factor if required.  This option is only available if "
      " Ipopt has been compiled with MA27.");
    roptions->AddLowerBoundedNumberOption(
      "ma27_meminc_factor",
      "Increment factor for workspace size for MA27.",
      1.0, false, 2.0,
      "If the integer or real workspace is not large enough, "
      "Ipopt will increase its size by this factor.  This option is only "
      "available if Ipopt has been compiled with MA27.");
    roptions->AddStringOption2(
      "ma27_skip_inertia_check",
      "Always pretend inertia is correct.",
      "no",
      "no", "check inertia",
      "yes", "skip inertia check",
      "Setting this option to \"yes\" essentially disables inertia check. "
      "This option makes the algorithm non-robust and easily fail, but it "
      "might give some insight into the necessity of inertia control.");
    roptions->AddStringOption2(
      "ma27_ignore_singularity",
      "Enables MA27's ability to solve a linear system even if the matrix is singular.",
      "no",
      "no", "Don't have MA27 solve singular systems",
      "yes", "Have MA27 solve singular systems",
      "Setting this option to \"yes\" means that Ipopt will call MA27 to "
      "compute solutions for right hand sides, even if MA27 has detected that "
      "the matrix is singular (but is still able to solve the linear system). "
      "In some cases this might be better than using Ipopt's heuristic of "
      "small perturbation of the lower diagonal of the KKT matrix.");

  }
Esempio n. 13
0
void
CL3aImageProcessor::set_stats_callback (const SmartPtr<StatsCallback> &callback)
{
    XCAM_ASSERT (callback.ptr ());
    _stats_callback = callback;
}
Esempio n. 14
0
XCamReturn
CL3aImageProcessor::create_handlers ()
{
    SmartPtr<CLImageHandler> image_handler;
    SmartPtr<CLContext> context = get_cl_context ();

    XCAM_ASSERT (context.ptr ());

    /* bayer pipeline */
    image_handler = create_cl_bayer_basic_image_handler (context, _enable_gamma, _3a_stats_bits);
    _bayer_basic_pipe = image_handler.dynamic_cast_ptr<CLBayerBasicImageHandler> ();
    XCAM_FAIL_RETURN (
        WARNING,
        _bayer_basic_pipe.ptr (),
        XCAM_RETURN_ERROR_CL,
        "CL3aImageProcessor create bayer basic pipe handler failed");
    image_handler->set_pool_size (XCAM_CL_3A_IMAGE_MAX_POOL_SIZE);
    _bayer_basic_pipe->set_stats_callback (_stats_callback);
    add_handler (image_handler);

    /* tone mapping */
    switch(_wdr_mode) {
    case Gaussian: {
        image_handler = create_cl_tonemapping_image_handler (context);
        _tonemapping = image_handler.dynamic_cast_ptr<CLTonemappingImageHandler> ();
        XCAM_FAIL_RETURN (
            WARNING,
            _tonemapping.ptr (),
            XCAM_RETURN_ERROR_CL,
            "CL3aImageProcessor create tonemapping handler failed");
        _tonemapping->set_kernels_enable (true);
        image_handler->set_pool_size (XCAM_CL_3A_IMAGE_MAX_POOL_SIZE);
        add_handler (image_handler);
        break;
    }
    case Haleq: {
        image_handler = create_cl_newtonemapping_image_handler (context);
        _newtonemapping = image_handler.dynamic_cast_ptr<CLNewTonemappingImageHandler> ();
        XCAM_FAIL_RETURN (
            WARNING,
            _newtonemapping.ptr (),
            XCAM_RETURN_ERROR_CL,
            "CL3aImageProcessor create tonemapping handler failed");
        _newtonemapping->set_kernels_enable (true);
        image_handler->set_pool_size (XCAM_CL_3A_IMAGE_MAX_POOL_SIZE);
        add_handler (image_handler);
        break;
    }
    default:
        XCAM_LOG_DEBUG ("WDR disabled");
        break;
    }

    /* bayer pipe */
    image_handler = create_cl_bayer_pipe_image_handler (context);
    _bayer_pipe = image_handler.dynamic_cast_ptr<CLBayerPipeImageHandler> ();
    XCAM_FAIL_RETURN (
        WARNING,
        image_handler.ptr (),
        XCAM_RETURN_ERROR_CL,
        "CL3aImageProcessor create bayer pipe handler failed");

    _bayer_pipe->enable_denoise (XCAM_DENOISE_TYPE_BNR & _snr_mode);
    image_handler->set_pool_size (XCAM_CL_3A_IMAGE_MAX_POOL_SIZE * 2);
    //image_handler->set_pool_type (CLImageHandler::DrmBoPoolType);
    add_handler (image_handler);
    if(_capture_stage == BasicbayerStage)
        return XCAM_RETURN_NO_ERROR;

    image_handler = create_cl_yuv_pipe_image_handler (context);
    _yuv_pipe = image_handler.dynamic_cast_ptr<CLYuvPipeImageHandler> ();
    XCAM_FAIL_RETURN (
        WARNING,
        _yuv_pipe.ptr (),
        XCAM_RETURN_ERROR_CL,
        "CL3aImageProcessor create yuv pipe handler failed");
    _yuv_pipe->set_tnr_enable (_tnr_mode & CL_TNR_TYPE_YUV);
    image_handler->set_pool_size (XCAM_CL_3A_IMAGE_MAX_POOL_SIZE * 2);
    add_handler (image_handler);

#if ENABLE_YEENR_HANDLER
    /* ee */
    image_handler = create_cl_ee_image_handler (context);
    _ee = image_handler.dynamic_cast_ptr<CLEeImageHandler> ();
    XCAM_FAIL_RETURN (
        WARNING,
        _ee.ptr (),
        XCAM_RETURN_ERROR_CL,
        "CL3aImageProcessor create ee handler failed");
    _ee->set_kernels_enable (XCAM_DENOISE_TYPE_EE & _snr_mode);
    image_handler->set_pool_type (CLImageHandler::DrmBoPoolType);
    image_handler->set_pool_size (XCAM_CL_3A_IMAGE_MAX_POOL_SIZE);
    add_handler (image_handler);
#endif

    /* wavelet denoise */
    switch (_wavelet_basis) {
    case CL_WAVELET_HAT: {
        image_handler = create_cl_wavelet_denoise_image_handler (context, _wavelet_channel);
        _wavelet = image_handler.dynamic_cast_ptr<CLWaveletDenoiseImageHandler> ();
        XCAM_FAIL_RETURN (
            WARNING,
            _wavelet.ptr (),
            XCAM_RETURN_ERROR_CL,
            "CL3aImageProcessor create wavelet denoise handler failed");
        _wavelet->set_kernels_enable (true);
        image_handler->set_pool_type (CLImageHandler::DrmBoPoolType);
        image_handler->set_pool_size (XCAM_CL_3A_IMAGE_MAX_POOL_SIZE);
        add_handler (image_handler);
        break;
    }
    case CL_WAVELET_HAAR: {
        image_handler = create_cl_newwavelet_denoise_image_handler (context, _wavelet_channel, _wavelet_bayes_shrink);
        _newwavelet = image_handler.dynamic_cast_ptr<CLNewWaveletDenoiseImageHandler> ();
        XCAM_FAIL_RETURN (
            WARNING,
            _newwavelet.ptr (),
            XCAM_RETURN_ERROR_CL,
            "CL3aImageProcessor create new wavelet denoise handler failed");
        _newwavelet->set_kernels_enable (true);
        image_handler->set_pool_type (CLImageHandler::DrmBoPoolType);
        image_handler->set_pool_size (XCAM_CL_3A_IMAGE_MAX_POOL_SIZE);
        add_handler (image_handler);
        break;
    }
    case CL_WAVELET_DISABLED:
    default :
        XCAM_LOG_DEBUG ("unknown or disable wavelet (%d)", _wavelet_basis);
        break;
    }

    /* image scaler */
    image_handler = create_cl_image_scaler_handler (context, V4L2_PIX_FMT_NV12);
    _scaler = image_handler.dynamic_cast_ptr<CLImageScaler> ();
    XCAM_FAIL_RETURN (
        WARNING,
        _scaler.ptr (),
        XCAM_RETURN_ERROR_CL,
        "CL3aImageProcessor create scaler handler failed");
    _scaler->set_scaler_factor (_scaler_factor);
    _scaler->set_buffer_callback (_stats_callback);
    image_handler->set_pool_type (CLImageHandler::DrmBoPoolType);
    image_handler->set_kernels_enable (_enable_scaler);
    add_handler (image_handler);

    /* wire frame */
    image_handler = create_cl_wire_frame_image_handler (context);
    _wire_frame = image_handler.dynamic_cast_ptr<CLWireFrameImageHandler> ();
    XCAM_FAIL_RETURN (
        WARNING,
        _wire_frame.ptr (),
        XCAM_RETURN_ERROR_CL,
        "CL3aImageProcessor create wire frame handler failed");
    _wire_frame->set_kernels_enable (_enable_wireframe);
    image_handler->set_pool_type (CLImageHandler::DrmBoPoolType);
    image_handler->set_pool_size (XCAM_CL_3A_IMAGE_MAX_POOL_SIZE);
    add_handler (image_handler);

    XCAM_FAIL_RETURN (
        WARNING,
        post_config (),
        XCAM_RETURN_ERROR_CL,
        "CL3aImageProcessor post_config failed");

    return XCAM_RETURN_NO_ERROR;
}
Esempio n. 15
0
void reset_paper(){
  //IMPLEMENT LOCK PhysicsWorld::Locker lock(world);
  paper->adaptGlobalStiffness(0.9);
}
Esempio n. 16
0
HRESULT 
ISampleCaptureGraphBuilder::ConnectFilters(IBaseFilter *pUpFilter, IBaseFilter *pDownFilter)
{
    if( !pUpFilter || !pDownFilter )
    {
        return E_INVALIDARG;
    }

    // All the need pin & pin enumerator pointers
    SmartPtr<IEnumPins>  pEnumUpFilterPins , 
                        pEnumDownFilterPins;

    SmartPtr<IPin>   pUpFilterPin , 
                    pDownFilterPin;

    HRESULT hr = S_OK;

    // Get the pin enumerators for both the filtera
    hr = pUpFilter->EnumPins(&pEnumUpFilterPins); 
    if( FAILED( hr ) )
    {
        return hr;
    }

    hr= pDownFilter->EnumPins(&pEnumDownFilterPins); 
    if( FAILED( hr ) )
    {
        return hr;
    }


    // Loop on every pin on the Upstream Filter
    BOOL bConnected = FALSE;
    PIN_DIRECTION pinDir;
    ULONG nFetched = 0;
    while(pUpFilterPin.Release( ), S_OK == pEnumUpFilterPins->Next(1, &pUpFilterPin, &nFetched) )
    {
        // Make sure that we have the output pin of the upstream filter
        hr = pUpFilterPin->QueryDirection( &pinDir );
        if( FAILED( hr ) || PINDIR_INPUT == pinDir )
        {
            continue;
        }

        //
        // I have an output pin; loop on every pin on the Downstream Filter
        //
        while(pDownFilterPin.Release( ), S_OK == pEnumDownFilterPins->Next(1, &pDownFilterPin, &nFetched) )
        {
            hr = pDownFilterPin->QueryDirection( &pinDir );
            if( FAILED( hr ) || PINDIR_OUTPUT == pinDir )
            {
                continue;
            }

            // Try to connect them and exit if u can else loop more until you can
            if(SUCCEEDED(graph_->ConnectDirect(pUpFilterPin, pDownFilterPin, NULL)))
            {
                bConnected = TRUE;
                break;
            }
        }

        hr = pEnumDownFilterPins->Reset();
        if( FAILED( hr ) )
        {
            return hr;
        }
    }

    if( !bConnected )
    {
        return E_FAIL;
    }

    return S_OK;
}
Esempio n. 17
0
void change_global_stiffness(){
  //IMPLEMENT LOCK PhysicsWorld::Locker lock(world);
  paper->adaptGlobalStiffness(gui["globalStiffness"]);
}
Esempio n. 18
0
HRESULT 
ISampleCaptureGraphBuilder::ConnectPin( 
                    IPin *pPin, 
                    IBaseFilter *pDownFilter )
{
    if( !pPin || !pDownFilter )
    {
        return E_INVALIDARG;
    }

    PIN_DIRECTION   pinDirection;
    HRESULT hr = pPin->QueryDirection( &pinDirection );
    if( FAILED( hr ) || PINDIR_INPUT == pinDirection )
    {
        return E_FAIL;
    }

    //
    //  Add the filter to the graph
    //
    BOOL bConnected = FALSE;
    ULONG nFetched = 0;
    SmartPtr<IPin> pDownFilterPin;

    //
    //  Loop through every input pin from downstream filter
    //  and try to connect the pin
    //  
    SmartPtr< IEnumPins > pEnumDownFilterPins;
    hr= pDownFilter->EnumPins( &pEnumDownFilterPins ); 
    if( FAILED( hr ) )
    {
        return hr;
    }

    while(pDownFilterPin.Release( ), S_OK == pEnumDownFilterPins->Next(1, &pDownFilterPin, &nFetched) )
    {
        hr = pDownFilterPin->QueryDirection( &pinDirection );
        if( FAILED( hr ) )
        {
            continue;
        }
        if( PINDIR_OUTPUT == pinDirection )
        {
            continue;
        }

        hr = graph_->ConnectDirect(pPin, pDownFilterPin, NULL);
        if(SUCCEEDED(hr))
        {
            bConnected = TRUE;
            break;
        }
    }

    if( !bConnected )
    {
        graph_->RemoveFilter( pDownFilter );
        return E_FAIL;
    }

    return S_OK;
}
Esempio n. 19
0
 void RegisterOptions_Algorithm(const SmartPtr<RegisteredOptions>& roptions)
 {
   roptions->SetRegisteringCategory("Barrier Parameter Update");
   AdaptiveMuUpdate::RegisterOptions(roptions);
   roptions->SetRegisteringCategory("Initialization");
   DefaultIterateInitializer::RegisterOptions(roptions);
   roptions->SetRegisteringCategory("Main Algorithm");
   AlgorithmBuilder::RegisterOptions(roptions);
   roptions->SetRegisteringCategory("Line Search");
   BacktrackingLineSearch::RegisterOptions(roptions);
   FilterLSAcceptor::RegisterOptions(roptions);
   roptions->SetRegisteringCategory("NLP Scaling");
   StandardScalingBase::RegisterOptions(roptions);
   roptions->SetRegisteringCategory("NLP Scaling");
   GradientScaling::RegisterOptions(roptions);
   roptions->SetRegisteringCategory("Uncategorized");
   IpoptAlgorithm::RegisterOptions(roptions);
   roptions->SetRegisteringCategory("Uncategorized");
   IpoptData::RegisterOptions(roptions);
   roptions->SetRegisteringCategory("Uncategorized");
   IpoptCalculatedQuantities::RegisterOptions(roptions);
   roptions->SetRegisteringCategory("Hessian Approximation");
   LimMemQuasiNewtonUpdater::RegisterOptions(roptions);
   roptions->SetRegisteringCategory("Barrier Parameter Update");
   MonotoneMuUpdate::RegisterOptions(roptions);
   roptions->SetRegisteringCategory("Convergence");
   OptimalityErrorConvergenceCheck::RegisterOptions(roptions);
   roptions->SetRegisteringCategory("NLP");
   OrigIpoptNLP::RegisterOptions(roptions);
   roptions->SetRegisteringCategory("Output");
   OrigIterationOutput::RegisterOptions(roptions);
   roptions->SetRegisteringCategory("Step Calculation");
   PDFullSpaceSolver::RegisterOptions(roptions);
   roptions->SetRegisteringCategory("Step Calculation");
   PDPerturbationHandler::RegisterOptions(roptions);
   roptions->SetRegisteringCategory("Barrier Parameter Update");
   ProbingMuOracle::RegisterOptions(roptions);
   roptions->SetRegisteringCategory("Barrier Parameter Update");
   QualityFunctionMuOracle::RegisterOptions(roptions);
   roptions->SetRegisteringCategory("Restoration Phase");
   RestoFilterConvergenceCheck::RegisterOptions(roptions);
   roptions->SetRegisteringCategory("Restoration Phase");
   RestoIpoptNLP::RegisterOptions(roptions);
   roptions->SetRegisteringCategory("Uncategorized");
   roptions->SetRegisteringCategory("Restoration Phase");
   MinC_1NrmRestorationPhase::RegisterOptions(roptions);
   roptions->SetRegisteringCategory("Warm Start");
   WarmStartIterateInitializer::RegisterOptions(roptions);
 }
HRESULT StartGraph(HWND window)
{
    HRESULT hr = S_OK;

    const DWORD BUFFER_SIZE = MAX_PATH * MAX_VIDEO_STREAMS;

    MultiSelectFileList<BUFFER_SIZE> selectList;

    OPENFILENAME ofn;
    ZeroMemory(&ofn, sizeof(ofn));

    ofn.lStructSize         = sizeof(OPENFILENAME);
    ofn.hwndOwner           = g_hWnd;
    ofn.lpstrFilter         = TEXT("Video Files (.AVI, .MPG, .MPEG, .VOB, .WMV)\0*.AVI;*.MPG;*.MPEG;*.VOB;*.WMV\0") 
                              TEXT("All Files (*.*)\0*.*\0\0");
    ofn.nFilterIndex        = 1;
    ofn.lpstrFile           = selectList.BufferPtr();
    ofn.nMaxFile            = selectList.BufferSizeCch();
    ofn.lpstrTitle          = TEXT("Select a video file to play...");
    ofn.Flags               = OFN_HIDEREADONLY | OFN_ALLOWMULTISELECT | OFN_FILEMUSTEXIST | OFN_EXPLORER;
    ofn.lpstrDefExt         = TEXT("AVI");
    
    // Launch the Open File dialog.
	DWORD result = GetOpenFileName(&ofn);

    // Check for errors.
    if (CommDlgExtendedError() != 0)
    {

        // NOTE: For mult-selection, CommDlgExtendedError can return FNERR_BUFFERTOOSMALL even when
        // GetOpenFileName returns TRUE.

        MessageBox(NULL, TEXT( "Could not open files." ), NULL, MB_OK | MB_ICONERROR);
        return E_FAIL;
    }
    else if (!result)
    {
        // The user cancelled. (No error occurred.)
        return S_OK;
    }

    FAIL_RET(hr = selectList.ParseBuffer());

    // Clear all DirectShow interfaces (COM smart pointers)
    g_compositor            = NULL;
    g_windowlessControl     = NULL;
    g_mediaControl          = NULL;
    g_filter                = NULL;
    g_graph                 = NULL;

    // Create the Filter Graph Manager.
    FAIL_RET( CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER, IID_IGraphBuilder, (void**)&g_graph) );

    // Configure the VMR-9.
    FAIL_RET( ConfigureVMR9(window) );

    // Render every file that the user selected.
    for (DWORD i = 0; i < MAX_VIDEO_STREAMS; i++)
    {
        TCHAR *pFileName = NULL;

        FAIL_RET(hr = selectList.Next(&pFileName));
        if (hr == S_FALSE)
        {
            hr = S_OK;
            break;
        }

		hr = g_graph->RenderFile( pFileName, NULL );

        CoTaskMemFree(pFileName);

        FAIL_RET(hr);

	}

    // Run the graph.

    FAIL_RET( g_graph->QueryInterface(IID_IMediaControl, reinterpret_cast<void**>(&g_mediaControl)) );

    FAIL_RET( g_mediaControl->Run() );

    return hr;
}
Esempio n. 21
0
void GR_MathManager::setDefaultFontSize(UT_sint32 uid, UT_sint32 iSize)
{
	SmartPtr<libxml2_MathView>  pMathView = m_vecMathView.getNthItem(uid);
	UT_return_if_fail(pMathView);
	pMathView->setDefaultFontSize(iSize);
}
Esempio n. 22
0
ConvergenceCheck::ConvergenceStatus
RestoConvergenceCheck::CheckConvergence(bool call_intermediate_callback /*= true*/)
{
    // Get pointers to the Original NLP objects
    const RestoIpoptNLP* resto_ipopt_nlp =
        static_cast<const RestoIpoptNLP*>(&IpNLP());
    DBG_ASSERT(dynamic_cast<const RestoIpoptNLP*>(&IpNLP()));

    SmartPtr<IpoptData> orig_ip_data = &resto_ipopt_nlp->OrigIpData();
    SmartPtr<IpoptCalculatedQuantities> orig_ip_cq =
        &resto_ipopt_nlp->OrigIpCq();

    // set the trial point for the original problem
    SmartPtr<const Vector> x = IpData().curr()->x();
    const CompoundVector* cx =
        static_cast<const CompoundVector*>(GetRawPtr(x));
    DBG_ASSERT(dynamic_cast<const CompoundVector*>(GetRawPtr(x)));
    SmartPtr<const Vector> s = IpData().curr()->s();
    const CompoundVector* cs =
        static_cast<const CompoundVector*>(GetRawPtr(s));
    DBG_ASSERT(dynamic_cast<const CompoundVector*>(GetRawPtr(s)));
    DBG_ASSERT(cs->NComps() == 1);

    SmartPtr<IteratesVector> trial = orig_ip_data->curr()->MakeNewContainer();
    trial->Set_x(*cx->GetComp(0));
    trial->Set_s(*cs->GetComp(0));
    orig_ip_data->set_trial(trial);

    if (call_intermediate_callback) {
        // Check if user requested termination by calling the intermediate
        // user callback function
        AlgorithmMode mode = RestorationPhaseMode;
        // Gather the information also used in the iteration output
        Index iter = IpData().iter_count();
        Number inf_pr = orig_ip_cq->trial_primal_infeasibility(NORM_MAX);
        Number inf_du = IpCq().curr_dual_infeasibility(NORM_MAX);
        Number mu = IpData().curr_mu();
        Number dnrm;
        if (IsValid(IpData().delta()) && IsValid(IpData().delta()->x()) && IsValid(IpData().delta()->s())) {
            dnrm = Max(IpData().delta()->x()->Amax(), IpData().delta()->s()->Amax());
        }
        else {
            // This is the first iteration - no search direction has been
            // computed yet.
            dnrm = 0.;
        }
        Number alpha_primal = IpData().info_alpha_primal();
        Number alpha_dual = IpData().info_alpha_dual();
        Number regu_x = IpData().info_regu_x();
        Number unscaled_f = orig_ip_cq->unscaled_trial_f();
        Index ls_count = IpData().info_ls_count();
        bool request_stop =
            !IpNLP().IntermediateCallBack(mode, iter, unscaled_f, inf_pr, inf_du,
                                          mu, dnrm, regu_x, alpha_dual,
                                          alpha_primal, ls_count,
                                          &IpData(), &IpCq());

        if (request_stop) {
            return ConvergenceCheck::USER_STOP;
        }
    }

    if (IpData().iter_count() >= maximum_iters_) {
        return ConvergenceCheck::MAXITER_EXCEEDED;
    }

    if (successive_resto_iter_ > maximum_resto_iters_) {
        Jnlst().Printf(J_WARNING, J_MAIN,
                       "More than %d successive iterations taken in restoration phase.\n",
                       maximum_resto_iters_);
        return ConvergenceCheck::MAXITER_EXCEEDED;
    }
    successive_resto_iter_++;

    // First check if the point is now acceptable for the outer filter
    ConvergenceStatus status;

    // Calculate the f and theta for the original problem
    Number orig_trial_theta = orig_ip_cq->trial_constraint_violation();
    Number orig_curr_theta = orig_ip_cq->curr_constraint_violation();

    // check acceptability to the filter
    Jnlst().Printf(J_DETAILED, J_MAIN,
                   "orig_curr_theta = %8.2e, orig_trial_theta = %8.2e\n",
                   orig_curr_theta, orig_trial_theta);

    // ToDo: In the following we might want to be more careful with the lower bound

    Number orig_curr_inf_pr = orig_ip_cq->curr_primal_infeasibility(NORM_MAX);
    Number orig_trial_inf_pr = orig_ip_cq->trial_primal_infeasibility(NORM_MAX);
    Jnlst().Printf(J_DETAILED, J_MAIN,
                   "orig_curr_inf_pr = %8.2e, orig_trial_inf_pr = %8.2e\n",
                   orig_curr_inf_pr, orig_trial_inf_pr);


    Number orig_inf_pr_max = Max(kappa_resto_*orig_curr_inf_pr,
                                 Min(orig_ip_data->tol(),
                                     orig_constr_viol_tol_));
    if (kappa_resto_ == 0.) {
        orig_inf_pr_max = 0.;
    }

    if (first_resto_iter_) {
        Jnlst().Printf(J_DETAILED, J_MAIN,
                       "This is the first iteration - continue to take at least one step.\n");
        status = CONTINUE;
    }
    else if (orig_ip_cq->IsSquareProblem() &&
             orig_trial_inf_pr <=
             Min(orig_ip_data->tol(), orig_constr_viol_tol_)) {
        Jnlst().Printf(J_DETAILED, J_MAIN,
                       "Restoration phase found points satisfying feasibility tolerance in square problem.\n");
        status = CONVERGED;
    }
    else if (orig_trial_inf_pr > orig_inf_pr_max) {
        Jnlst().Printf(J_DETAILED, J_MAIN,
                       "Point does not provide sufficient reduction w.r.t the original constraint violation (orig_inf_pr_max=%e).\n", orig_inf_pr_max);
        status = CONTINUE;
    }
    else {
        Number orig_trial_barr = orig_ip_cq->trial_barrier_obj();

        Jnlst().Printf(J_DETAILED, J_MAIN,
                       "orig_trial_barr = %8.2e\n", orig_trial_barr);
        status = TestOrigProgress(orig_trial_barr, orig_trial_theta);
    }

    // If the point is not yet acceptable to the filter, check if the problem
    // is maybe locally infeasible

    if (status==CONTINUE) {
        Jnlst().Printf(J_DETAILED, J_MAIN,
                       "Checking convergence for restoration phase problem...\n");
        status = OptimalityErrorConvergenceCheck::CheckConvergence(false);
        if (status == CONVERGED || status == CONVERGED_TO_ACCEPTABLE_POINT) {
            Number orig_trial_primal_inf =
                orig_ip_cq->trial_primal_infeasibility(NORM_MAX);
            // ToDo make the factor in following line an option
            if (orig_trial_primal_inf <= 1e2*IpData().tol()) {
                //        if (orig_trial_primal_inf <= 1e2*orig_ip_data->tol()) {
                if (IpData().tol() > 1e-1*orig_ip_data->tol()) {
                    // For once, we tighten the convergence tolerance for the
                    // restoration phase problem in case the problem is only
                    // very slightly infeasible.
                    IpData().Set_tol(1e-2*IpData().tol());
                    status = CONTINUE;
                    Jnlst().Printf(J_DETAILED, J_LINE_SEARCH,
                                   "Tightening restoration phase tolerance to %e.\n",
                                   IpData().tol());
                    IpData().Append_info_string("!");
                }
                else {
                    Jnlst().Printf(J_WARNING, J_LINE_SEARCH,
                                   "Restoration phase converged to a feasible point that is\n"
                                   "unacceptable to the filter for the original problem.\n");
                    THROW_EXCEPTION(RESTORATION_CONVERGED_TO_FEASIBLE_POINT,
                                    "Restoration phase converged to a feasible point that is "
                                    "unacceptable to the filter for the original problem.");
                }
            }
            else {
                THROW_EXCEPTION(LOCALLY_INFEASIBLE,
                                "Restoration phase converged to a point of local infeasibility");
            }
        }
    }

    first_resto_iter_ = false;

    return status;
}
Esempio n. 23
0
void GR_MathManager::releaseEmbedView(UT_sint32 uid)
{
	SmartPtr<libxml2_MathView>  pMathView = m_vecMathView.getNthItem(uid);
	UT_return_if_fail(pMathView);
	pMathView->resetRootElement();
}
Esempio n. 24
0
void run(){
  bool c_arg = pa("-c");
  
  static FPSLimiter fpsLimit(30);
  fpsLimit.wait();

  const ImgBase *image = grabber.grab();
  DrawHandle draw = gui["draw"];
  ImageHandle cropped = gui["cropped"];

  draw = image;

  static RotateOp rot;
  if(c_arg){
    rot.setAngle(0);
  }else{
    rot.setAngle(parse<int>(gui["rot"]));
  }

  const ImgBase *cro = 0;
  if(c_arg || gui["rect"].as<bool>()){
    static Img8u roi;
    std::vector<utils::Rect> rs = mouse_2->getRects();
    ICLASSERT_THROW(rs.size() == 1, ICLException("expected exactly one rectangle"));
    lastRect = rs[0];
    mouse_2->visualize(**draw);
    SmartPtr<const ImgBase> tmp = image->shallowCopy(rs[0] & image->getImageRect());
    roi.setChannels(tmp->getChannels());
    roi.setFormat(tmp->getFormat());
    roi.setSize(tmp->getROISize());
    tmp->convertROI(&roi);
    cro = rot.apply(&roi);

    draw->color(0,255,0,255);
    draw->text(str(rs[0]), rs[0].x, rs[0].y);

  }else{
    draw->draw(mouse_1->vis());
    Size32f s(gui["s1"],gui["s2"]);
    Point32f ps[4] = { mouse_1->ps[0],  mouse_1->ps[1],  mouse_1->ps[2],  mouse_1->ps[3] };
    switch(image->getDepth()){
#define ICL_INSTANTIATE_DEPTH(D)                                \
      case depth##D:{                                           \
        static ImageRectification<icl##D> ir;                   \
        try{                                                    \
          cro = rot.apply(&ir.apply(ps,*image->as##D(),s));     \
        }catch(...){}                                           \
        break;                                                  \
      }
      ICL_INSTANTIATE_ALL_DEPTHS;
#undef ICL_INSTANTIATE_DEPTH
    }
  }
  if(cro){
    cropped = cro;
    currMutex.lock();
    cro->convert(&curr);
    currMutex.unlock();
  }

  gui["draw"].render();
  gui["fps"].render();
}
PRL_RESULT Task_MigrateCtSource::run_body()
{
	SmartPtr<CVmEvent> pEvent;
	SmartPtr<IOPackage> pPackage;
	IOSendJob::Response pResponse;
	CDispToDispCommandPtr pCmd;
	CDispToDispResponseCommand *pRespCmd;

	//https://bugzilla.sw.ru/show_bug.cgi?id=267152
	CAuthHelperImpersonateWrapper _impersonate( &getClient()->getAuthHelper() );

	if (operationIsCancelled())
		setLastErrorCode(PRL_ERR_OPERATION_WAS_CANCELED);

	PRL_RESULT nRetCode = PRL_ERR_SUCCESS;

	if (PRL_FAILED(nRetCode = CheckVmMigrationPreconditions()))
		goto exit;

	/* set migration mode */
	switch (m_nPrevVmState) {
	case VMS_RUNNING:
	case VMS_PAUSED:
		nRetCode = PRL_ERR_VM_MIGRATE_WARM_MODE_NOT_SUPPORTED;
		goto exit;
	default:
		m_nMigrationFlags |= PVMT_COLD_MIGRATION;
	}

	if (operationIsCancelled())
		setLastErrorCode(PRL_ERR_OPERATION_WAS_CANCELED);

	pEvent = SmartPtr<CVmEvent>(new CVmEvent(PET_DSP_EVT_VM_MIGRATE_STARTED, m_sVmUuid, PIE_DISPATCHER));
	pEvent->addEventParameter(new CVmEventParameter(PVE::Boolean, "true", EVT_PARAM_MIGRATE_IS_SOURCE));
	pPackage = DispatcherPackage::createInstance(PVE::DspVmEvent, pEvent->toString());

	m_nSteps |= MIGRATE_VM_STATE_CHANGED;
	/* and notify clients about VM migration start event */
	CDspService::instance()->getClientManager().sendPackageToVmClients(pPackage, m_sVzDirUuid, m_sVmUuid);

	/* remove target Vm config from watcher (#448235) */
	CDspService::instance()->getVmConfigWatcher().unregisterVmToWatch(m_sVmConfigPath);
	m_nSteps |= MIGRATE_UNREGISTER_VM_WATCH;

	nRetCode = migrateStoppedCt();
	if (PRL_FAILED(nRetCode))
		goto exit;

	/* wait finish reply from target (https://jira.sw.ru/browse/PSBM-9596) */
	quint32 nTimeout = m_nTimeout;

	/* wait target task finish */
	if (PVMT_CHANGE_SID & getRequestFlags())
		/* wait reply during changeSID task timeout (https://jira.sw.ru/browse/PSBM-9733) */
		nTimeout = CHANGESID_TIMEOUT;
	if (m_pIoClient->waitForResponse(m_hCheckReqJob, nTimeout) != IOSendJob::Success) {
		WRITE_TRACE(DBG_FATAL, "Finish acknowledgement receiving failure");
		nRetCode = PRL_ERR_CT_MIGRATE_INTERNAL_ERROR;
		goto exit;
	}
	pResponse = m_pIoClient->takeResponse(m_hCheckReqJob);
	if (pResponse.responseResult != IOSendJob::Success) {
		WRITE_TRACE(DBG_FATAL, "Finish acknowledgement receiving failure");
		nRetCode = PRL_ERR_CT_MIGRATE_INTERNAL_ERROR;
		goto exit;
	}
	pPackage  = pResponse.responsePackages[0];
	if (pPackage->header.type != DispToDispResponseCmd) {
		WRITE_TRACE(DBG_FATAL, "Invalid package type : %d", pPackage->header.type);
		nRetCode = PRL_ERR_CT_MIGRATE_INTERNAL_ERROR;
		goto exit;
	}

	pCmd = CDispToDispProtoSerializer::ParseCommand(
		DispToDispResponseCmd, UTF8_2QSTR(pPackage->buffers[0].getImpl()));
	pRespCmd = CDispToDispProtoSerializer::CastToDispToDispCommand<CDispToDispResponseCommand>(pCmd);
	nRetCode = pRespCmd->GetRetCode();
	if (PRL_FAILED(nRetCode))
		getLastError()->fromString(pRespCmd->GetErrorInfo()->toString());

exit:
	setLastErrorCode(nRetCode);
	return nRetCode;
}
Esempio n. 26
0
int library_geostat_init::init_lib() {
  references_++;
  if( references_ != 1 ) {
    GsTLlog << "geostat library already registered" << "\n";
    return 2;
  }
     
  GsTLlog << "\n\n registering geostat library" << "\n"; 
  
  SmartPtr<Named_interface> ni = 
    Root::instance()->new_interface("directory://Geostat",
				     geostatAlgo_manager );
      
  Manager* dir = dynamic_cast<Manager*>( ni.raw_ptr() );
    
  if( !dir ) {
    GsTLlog << "could not create directory " 
	      << geostatAlgo_manager << "\n";
    return 1;
  }
  
  bind_geostat_factories( dir );

  // Get or create directory for geostat utilities
  SmartPtr<Named_interface> ni_utils = 
    Root::instance()->interface( geostatParamUtils_manager );
  
  if( ni_utils.raw_ptr() == 0 ) {
    ni_utils = 
      Root::instance()->new_interface("directory",
				      geostatParamUtils_manager);

    dir = dynamic_cast<Manager*>( ni_utils.raw_ptr() );
    if( !dir ) {
      GsTLlog << "could not create directory " 
	      << geostatParamUtils_manager << "\n";
      return 1;
    }

    dir->factory("directory", create_directory);
  }
    
  // Now create subdirectory "xmlGeostatParamUtils_manager" of directory
  // "geostatParamUtils_manager" if it does not already exist
  SmartPtr<Named_interface> ni_xml_utils = 
    Root::instance()->interface( xmlGeostatParamUtils_manager );

  if( ni_xml_utils.raw_ptr() == 0 )
    ni_xml_utils = 
      Root::instance()->new_interface("directory://QTaccessors/xml",
				      xmlGeostatParamUtils_manager );

  dir = dynamic_cast<Manager*>( ni_xml_utils.raw_ptr() );
  if( !dir ) {
    GsTLlog << "could not get nor create directory " 
	      << xmlGeostatParamUtils_manager << "\n";
    return 1;
  }
  bind_geostat_utilities( dir );


  GsTLlog << "Registration done" << "\n\n";

  Root::instance()->list_all( GsTLlog );
  return 0;
}
void Ma57TSolverInterface::RegisterOptions(SmartPtr<RegisteredOptions> roptions)
{
    roptions->AddBoundedNumberOption(
        "ma57_pivtol",
        "Pivot tolerance for the linear solver MA57.",
        0.0, true, 1.0, true, 1e-8,
        "A smaller number pivots for sparsity, a larger number pivots for "
        "stability. This option is only available if Ipopt has been compiled "
        "with MA57.");
    roptions->AddBoundedNumberOption(
        "ma57_pivtolmax",
        "Maximum pivot tolerance for the linear solver MA57.",
        0.0, true, 1.0, true, 1e-4,
        "Ipopt may increase pivtol as high as ma57_pivtolmax to get a more "
        "accurate solution to the linear system.  This option is only available "
        "if Ipopt has been compiled with MA57.");
    roptions->AddLowerBoundedNumberOption(
        "ma57_pre_alloc",
        "Safety factor for work space memory allocation for the linear solver MA57.",
        1., false, 1.05,
        "If 1 is chosen, the suggested amount of work space is used.  However, "
        "choosing a larger number might avoid reallocation if the suggest values "
        "do not suffice.  This option is only available if Ipopt has been "
        "compiled with MA57.");
    roptions->AddBoundedIntegerOption(
        "ma57_pivot_order",
        "Controls pivot order in MA57",
        0, 5, 5,
        "This is ICNTL(6) in MA57.");
    roptions->AddStringOption2(
        "ma57_automatic_scaling",
        "Controls MA57 automatic scaling",
        "yes",
        "no", "Do not scale the linear system matrix",
        "yes", "Scale the linear system matrix",
        "This option controls the internal scaling option of MA57."
        "This is ICNTL(15) in MA57.");

    // CET: 04-29-2010
    roptions->AddLowerBoundedIntegerOption(
        "ma57_block_size",
        "Controls block size used by Level 3 BLAS in MA57BD",
        1, 16,
        "This is ICNTL(11) in MA57.");

    roptions->AddLowerBoundedIntegerOption(
        "ma57_node_amalgamation",
        "Node amalgamation parameter",
        1, 16,
        "This is ICNTL(12) in MA57.");

    roptions->AddBoundedIntegerOption(
        "ma57_small_pivot_flag",
        "If set to 1, then when small entries defined by CNTL(2) are detected "
        "they are removed and the corresponding pivots placed at the end of the "
        "factorization.  This can be particularly efficient if the matrix is "
        "highly rank deficient.",
        0, 1, 0,
        "This is ICNTL(16) in MA57.");
    // CET 04-29-2010

}
Esempio n. 28
0
void fold_line_cb(const Point32f &a, const Point32f &b){
  //TODO IMPLEMENt LOCK PhysicsWorld::Locker lock(world);
  paper->adaptStiffnessAlongLine(a,b,gui["soften"].as<bool>() ? 0.001 : 0.9);
}
Esempio n. 29
0
int main(int argc, char**args)
{
  using namespace Ipopt;

  SmartPtr<IpoptApplication> app = IpoptApplicationFactory();
  app->RethrowNonIpoptException(false);

  // Check if executable is run only to print out options documentation
  if (argc == 2) {
    bool print_options = false;
    bool print_latex_options = false;
    if (!strcmp(args[1],"--print-options")) {
      print_options = true;
    }
    else if (!strcmp(args[1],"--print-latex-options")) {
      print_options = true;
      print_latex_options = true;
    }
    if (print_options) {
      SmartPtr<OptionsList> options = app->Options();
      options->SetStringValue("print_options_documentation", "yes");
      if (print_latex_options) {
        options->SetStringValue("print_options_latex_mode", "yes");
      }
      app->Initialize("");
      return 0;
    }
  }

  // Call Initialize the first time to create a journalist, but ignore
  // any options file
  ApplicationReturnStatus retval;
  retval = app->Initialize("");
  if (retval != Solve_Succeeded) {
    printf("ampl_ipopt.cpp: Error in first Initialize!!!!\n");
    exit(-100);
  }

  // Add the suffix handler for scaling
  SmartPtr<AmplSuffixHandler> suffix_handler = new AmplSuffixHandler();
  suffix_handler->AddAvailableSuffix("scaling_factor", AmplSuffixHandler::Variable_Source, AmplSuffixHandler::Number_Type);
  suffix_handler->AddAvailableSuffix("scaling_factor", AmplSuffixHandler::Constraint_Source, AmplSuffixHandler::Number_Type);
  suffix_handler->AddAvailableSuffix("scaling_factor", AmplSuffixHandler::Objective_Source, AmplSuffixHandler::Number_Type);
  // Modified for warm-start from AMPL
  suffix_handler->AddAvailableSuffix("ipopt_zL_out", AmplSuffixHandler::Variable_Source, AmplSuffixHandler::Number_Type);
  suffix_handler->AddAvailableSuffix("ipopt_zU_out", AmplSuffixHandler::Variable_Source, AmplSuffixHandler::Number_Type);
  suffix_handler->AddAvailableSuffix("ipopt_zL_in", AmplSuffixHandler::Variable_Source, AmplSuffixHandler::Number_Type);
  suffix_handler->AddAvailableSuffix("ipopt_zU_in", AmplSuffixHandler::Variable_Source, AmplSuffixHandler::Number_Type);

  SmartPtr<TNLP> ampl_tnlp = new AmplTNLP(ConstPtr(app->Jnlst()),
                                          app->Options(),
                                          args, suffix_handler);

  // Call Initialize again to process output related options
  retval = app->Initialize();
  if (retval != Solve_Succeeded) {
    printf("ampl_ipopt.cpp: Error in second Initialize!!!!\n");
    exit(-101);
  }

  const int n_loops = 1; // make larger for profiling
  for (Index i=0; i<n_loops; i++) {
    retval = app->OptimizeTNLP(ampl_tnlp);
  }

  // finalize_solution method in AmplTNLP writes the solution file

  return 0;
}
Esempio n. 30
0
void Cosisim::init_neighborhoods( Geostat_grid* hard_grid, Geostat_grid* soft_grid, 
                                  const GsTLTripletTmpl<double>& hard_ranges, 
                                  const GsTLTripletTmpl<double>& hard_angles,
                                  const GsTLTripletTmpl<double>& soft_ranges, 
                                  const GsTLTripletTmpl<double>& soft_angles,
                                  int hard_max_neighbors, int soft_max_neighbors,
                                  std::vector< CovarianceType >& covariances, 
                                  Search_filter* prim_filter, Search_filter* soft_filter) {

  int nb_indicators = indicators_.size();

  // get the neighborhoods on the primary variable
  for( int i = 0 ; i < nb_indicators ; i++ ) {


   SmartPtr<Neighborhood> neighborhood;
    if( dynamic_cast<Point_set*>(hard_grid) ) {
      neighborhood = SmartPtr<Neighborhood>(
        hard_grid->neighborhood( hard_ranges, hard_angles,
                                 &covariances[i])  );
    } 
    else {
      neighborhood = SmartPtr<Neighborhood>(
        hard_grid->neighborhood( hard_ranges, hard_angles,
                                 &covariances[i] )  );
    }


    neighborhood->select_property( indicators_[i]->name() );
    neighborhood->max_size( hard_max_neighbors );
    if(prim_filter) neighborhood->search_neighborhood_filter(prim_filter->clone());

    hard_neighborhoods_.push_back( NeighorhoodType( neighborhood ) );
  }

  // get the neighborhoods on the secondary variable
  if( soft_grid ) {
    for( int j = 0 ; j < nb_indicators ; j++ ) {
      appli_assert( nb_indicators == secondary_indicators_.size() );


     SmartPtr<Neighborhood> neighborhood;
      if( dynamic_cast<Point_set*>(hard_grid) ) {
        neighborhood = SmartPtr<Neighborhood>(
          soft_grid->neighborhood( soft_ranges, soft_angles,
                                   &covariances[j], true )  );
      } 
      else {
        neighborhood = SmartPtr<Neighborhood>(
          soft_grid->neighborhood( soft_ranges, soft_angles,
                                   &covariances[j] )  );
      }

       neighborhood->select_property( secondary_indicators_[j]->name() );
      neighborhood->max_size( soft_max_neighbors );
      if(soft_filter) neighborhood->search_neighborhood_filter(soft_filter->clone());
      soft_neighborhoods_.push_back( NeighorhoodType( neighborhood ) );
    }
  }
  else {
    // there are no soft data. Use DummyNeighborhoods
    for( int j = 0 ; j < nb_indicators ; j++ ) {
      SmartPtr<Neighborhood> neighborhood( new DummyNeighborhood );
      soft_neighborhoods_.push_back( NeighorhoodType( neighborhood ) );
    }
  }
}