예제 #1
0
bool	CActor::CanMove				()
{
	if( conditions().IsCantWalk() )
	{
		if(mstate_wishful&mcAnyMove)
		{
			HUD().GetUI()->AddInfoMessage("cant_walk");
		}
		return false;
	}else
	if( conditions().IsCantWalkWeight() )
	{
		if(mstate_wishful&mcAnyMove)
		{
			HUD().GetUI()->AddInfoMessage("cant_walk_weight");
		}
		return false;
	
	}

	if(IsTalking())
		return false;
	else
		return true;
}
예제 #2
0
파일: Actor.cpp 프로젝트: OLR-xray/XRay-NEW
void CActor::UpdateArtefactsOnBelt()
{
	static float update_time = 0;

	float f_update_time = 0;

	if(update_time<ARTEFACTS_UPDATE_TIME)
	{
		update_time += conditions().fdelta_time();
		return;
	}
	else
	{
		f_update_time	= update_time;
		update_time		= 0.0f;
	}

	for(TIItemContainer::iterator it = inventory().m_belt.begin(); 
		inventory().m_belt.end() != it; ++it) 
	{
		CArtefact*	artefact = smart_cast<CArtefact*>(*it);
		if(artefact)
		{
			conditions().ChangeBleeding			(artefact->m_fBleedingRestoreSpeed*f_update_time);
			conditions().ChangeHealth			(artefact->m_fHealthRestoreSpeed*f_update_time);
			conditions().ChangePower			(artefact->m_fPowerRestoreSpeed*f_update_time);
//			conditions().ChangeSatiety			(artefact->m_fSatietyRestoreSpeed*f_update_time);
			conditions().ChangeRadiation		(artefact->m_fRadiationRestoreSpeed*f_update_time);
		}
	}
}
예제 #3
0
파일: AtomicModel.cpp 프로젝트: Agilack/vle
void AtomicModel::write(std::ostream& out) const
{
    out << "<model name=\"" << getName().c_str() << "\" "
        << "type=\"atomic\" ";

    if (not conditions().empty()) {
	out << "conditions=\"";

        std::vector < std::string >::const_iterator it =
            conditions().begin();
        while (it != conditions().end()) {
            out << it->c_str();
            ++it;
            if (it != conditions().end()) {
                out << ",";
            }
        }

        out << "\" ";
    }

    out << "dynamics=\"" << dynamics().c_str() << "\" ";

    if (not observables().empty()) {
        out << "observables=\"" << observables().c_str() << "\" ";
    }

    writeGraphics(out);

    out << ">\n";

    writePort(out);

    out << "</model>\n";
}
예제 #4
0
bool CActor::CanMove()
{
	if( conditions().IsCantWalk() )
	{
		if(mstate_wishful&mcAnyMove)
		{
			CurrentGameUI()->AddCustomStatic("cant_walk", true);
		}
		return false;
	}else
	if( conditions().IsCantWalkWeight() )
	{
		if(mstate_wishful&mcAnyMove)
		{
			CurrentGameUI()->AddCustomStatic("cant_walk_weight", true);
		}
		return false;
	
	}

	if(IsTalking())
		return false;
	else
		return true;
}
    arma::Mat<double> GallaghersGaussian101mePeaksFunction::getRandomLocalParameterConditionings() const {
      arma::Col<double> conditions(101);
      conditions(0) = 49.5;
      conditions.tail(conditions.n_elem - 1) = arma::conv_to<arma::Col<double>>::from(getRandomPermutation(conditions.n_elem - 1));

      arma::Mat<double> localParameterConditionings(numberOfDimensions_, conditions.n_elem);
      for (arma::uword n = 0; n < conditions.n_elem; ++n) {
        const double condition = std::pow(10.0, conditions(n) / 33.0);
        localParameterConditionings.col(n) = getParameterConditioning(condition) / std::sqrt(condition);
      }

      return localParameterConditionings;
    }
예제 #6
0
void
Experiment::setBegin(double begin)
{
    if (not conditions().exist(defaultSimulationEngineCondName()))
        throw utils::ArgError(_("The simulation engine condition"
                                "does not exist"));

    auto& condSim = conditions().get(defaultSimulationEngineCondName());
    auto& dur = condSim.getSetValues("begin");
    dur.clear();
    dur.emplace_back(std::static_pointer_cast<vle::value::Value>(
      std::make_shared<vle::value::Double>(begin)));
}
    arma::Mat<T> GallaghersGaussian21hiPeaksFunction<T>::getRandomLocalParameterConditionings() const noexcept {
      arma::Col<T> conditions(21);
      conditions(0) = static_cast<T>(19.0L);
      conditions.tail(conditions.n_elem - 1) = arma::conv_to<arma::Col<T>>::from(getRandomPermutation(conditions.n_elem - 1));

      arma::Mat<T> localParameterConditionings(this->numberOfDimensions_, conditions.n_elem);
      for (std::size_t n = 0; n < conditions.n_elem; ++n) {
        const T& condition = std::pow(static_cast<T>(1000.0L), conditions(n) / static_cast<T>(19.0L));
        localParameterConditionings.col(n) = this->getParameterConditioning(condition) / std::sqrt(condition);
      }

      return localParameterConditionings;
    }
예제 #8
0
double
Experiment::begin() const
{
    if (not conditions().exist(defaultSimulationEngineCondName()))
        throw utils::ArgError(_("The simulation engine condition"
                                "does not exist"));

    const auto& condSim = conditions().get(defaultSimulationEngineCondName());
    const auto& dur = condSim.getSetValues("begin");

    if (dur.empty())
        throw utils::ArgError(_("The simulation engine condition is empty"));

    return dur[0]->toDouble().value();
}
    void createWall(double x1, double y1, double x2, double y2)
    {
        std::string id = boost::lexical_cast<std::string>(mWallNumbers);

        vp::Condition wall_cond("wall_cond"+id);
        wall_cond.add("x1");
        wall_cond.add("x2");
        wall_cond.add("y1");
        wall_cond.add("y2");
        wall_cond.addValueToPort("x1", vv::Double::create(x1));
        wall_cond.addValueToPort("y1", vv::Double::create(y1));
        wall_cond.addValueToPort("x2", vv::Double::create(x2));
        wall_cond.addValueToPort("y2", vv::Double::create(y2));
        conditions().add(wall_cond);

        createModel("wall" + id,
                    Strings({"agent_input"}),
                    Strings({"agent_output"}),
                    "dyn_wall",
                    Strings({wall_cond.name()}),
                    "");
        connect("wall" + id);
        mModels.push_back("wall" + id);
        ++mWallNumbers;
    }
예제 #10
0
const vpz::AtomicModel*
Executive::createModel(const std::string& name,
                       const std::vector<std::string>& inputs,
                       const std::vector<std::string>& outputs,
                       const std::string& dynamics,
                       const std::vector<std::string>& conds,
                       const std::string& observable,
                       bool debug)
{
    auto model = new vpz::AtomicModel(name, cpled());
    if (debug) {
        model->setDebug();
    }
    std::vector<std::string>::const_iterator it;

    for (it = inputs.begin(); it != inputs.end(); ++it) {
        model->addInputPort(*it);
    }

    for (it = outputs.begin(); it != outputs.end(); ++it) {
        model->addOutputPort(*it);
    }

    m_coordinator.createModel(
      model, conditions(), dynamics, conds, observable);

    return model;
}
예제 #11
0
	void PhysicalWorld::asynchronousQuery(const osg::Vec3d& cameraPos, VirtualDataSceneBase::TransformableActor* currentLayer)
	{
		if (!_physicalWorldEnable || _queryCollisionPlaneList.size() > 0)
			return;
		if (_loadInLayer.get() != currentLayer)
		{
			OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_collisionPlaneListMutex);
			unsigned int viewId = currentLayer->getViewID();
			std::vector< osg::ref_ptr<osg::Referenced> > collisionPlaneActorList;
			std::string conditions(" where ");
			conditions.append(ACTOR_PROPERTY_BELONGLAYERID);
			conditions.append("='");
			conditions.append(currentLayer->getId());
			conditions.append("'");
			bool result = dynamic_cast<VirtualDataSceneData::DataCenter*>(g_SystemContext._dataCenter.get())->selectAndBuildActor(collisionPlaneActorList,
				CLASS_COLLISIONPLANEACTOR, conditions, viewId);
			if (!result)
			{
				osg::notify(osg::NOTICE) << "asynchronousQuery failure!!" << std::endl;
			}
			for (unsigned int i = 0; i < collisionPlaneActorList.size(); ++i)
			{
				VirtualDataSceneGame::CollisionPlaneActor* cActor = static_cast<VirtualDataSceneGame::CollisionPlaneActor*>(collisionPlaneActorList.at(i).get());
				cActor->setActive(0);
				_queryCollisionPlaneList.push_back(cActor);
			}
			_loadInLayer = currentLayer;
		}
	}
예제 #12
0
const vpz::BaseModel *
Executive::createModelFromClass(const std::string &classname,
                                const std::string &modelname)
{
    return m_coordinator.createModelFromClass(
        classname, cpled(), modelname, conditions());
}
예제 #13
0
Experiment::Experiment()
{
    Condition cond(defaultSimulationEngineCondName());
    cond.setValueToPort("begin", value::Double::create(0));
    cond.setValueToPort("duration", value::Double::create(100));
    conditions().add(cond);
}
예제 #14
0
const vpz::BaseModel*
Executive::createModelFromClass(const std::string& classname,
                                const std::string& modelname,
                                const std::vector<std::string>& inputs,
                                const std::vector<std::string>& outputs)
{
    return m_coordinator.createModelFromClass(
      classname, cpled(), modelname, conditions(), inputs, outputs);
}
예제 #15
0
bool CActor::CanAccelerate()
{
	bool can_accel = !conditions().IsLimping() &&
		!character_physics_support()->movement()->PHCapture() && 
		(m_time_lock_accel < Device.dwTimeGlobal)
	;		

	return can_accel;
}
예제 #16
0
파일: linco.c 프로젝트: rforge/muste
void muste_linco(char *argv)
        {
        int i;

// RS 5.5.2014 Variable init 
// SURVO_DATA d;
A=NULL;
rlab=NULL;
clab=NULL;
rdim=cdim=lr=lc=type=0;
expr[0]=EOS;
matname[0]=EOS;
pros=0;
var=NULL;
y=NULL;
outvar=NULL;
lag=NULL;
act=0;

  //    if (argc==1) return;
        s_init(argv);

        if (g<3)
            {
            sur_print("\nUsage: LINCO <SURVO_data>,<matrix_of_coefficients>");
            WAIT; return;
            }
        i=data_open2(word[1],&d,1,0,0); if (i<0) return;
                                /* tilaa uusille muuttujille */
        i=spec_init(r1+r-1); if (i<0) return;

        pros=0;

        act='A'; i=spfind("ACT");
        if (i>=0) act=*spb[i];

        i=conditions(&d); if (i<0) return;  /* permitted only once */
        i=matparam(); if (i<0) return;
        i=matrix_load(matname,&A,&rdim,&cdim,&rlab,&clab,&lr,&lc,&type,expr);
        if (i<0) return;

        i=varaa_tilat(); if (i<0) return;
        i=find_variables();
        if (i<0)
            {
            if (etu==2)
                {
                sprintf(tut_info,"___@%d@LINCO@Error in LINCO@",-i);
                s_end(argv[1]); return;
                }
            return;
            }
        linear_combinations();
        data_close(&d);
        s_end(argv);
        }
예제 #17
0
bool CActor::CanSprint			()
{
	bool can_Sprint = CanAccelerate() && !conditions().IsCantSprint() &&
						Game().PlayerCanSprint(this)
						&& CanRun()
						&& !(mstate_real&mcLStrafe || mstate_real&mcRStrafe)
						&& InventoryAllowSprint()
						;

	return can_Sprint;
}
예제 #18
0
bool CActor::CanAccelerate			()
{
	bool can_accel = !conditions().IsLimping() &&
		!character_physics_support()->movement()->PHCapture() && 
//		&& !m_bZoomAimingMode
//		&& !(mstate_real&mcLookout)
		(m_time_lock_accel < Device.dwTimeGlobal)
	;		

	return can_accel;
}
예제 #19
0
파일: Actor.cpp 프로젝트: OLR-xray/XRay-NEW
void CActor::OnDifficultyChanged	()
{
	// immunities
	VERIFY(g_SingleGameDifficulty>=egdNovice && g_SingleGameDifficulty<=egdMaster); 
	LPCSTR diff_name				= get_token_name(difficulty_type_token, g_SingleGameDifficulty);
	string128						tmp;
	strconcat						(tmp,"actor_immunities_",diff_name);
	conditions().LoadImmunities		(tmp,pSettings);
	// hit probability
	strconcat						(tmp,"hit_probability_",diff_name);
	hit_probability					= pSettings->r_float(*cNameSect(),tmp);
}
예제 #20
0
파일: statmsf.c 프로젝트: rforge/muste
static int pvalues(int ii)
        {
        int i;
        char x[LLENGTH];
        double *freq;
        long l;
        double a;

        strcpy(x,spb[ii]);
        i=load_X(x); if (i<0) return(-1);
/* Rprintf("\ndim=%d,%d",mX,nX); getch(); */
        i=data_open(word[1],&d); if (i<0) return(-1);
        v=(int *)muste_malloc(mX*sizeof(int));
        if (v==NULL) { ei_tilaa(); return(-1); }
        i=nrot();
        mT=mX; nT=2; rlabT=rlabX ;
        i=mat_alloc_lab(&T,mT,nT,NULL,&clabT);
        freq=T+mT;
        for (i=0; i<mX; ++i) freq[i]=0.0;

        i=conditions(&d); if (i<0) return(-1);

        n=0L; sur_print("\n");
        for (l=d.l1; l<=d.l2; ++l)
            {
            if (unsuitable(&d)) continue;
            sprintf(sbuf,"%ld ",l); sur_print(sbuf);
            ++n;
            for (i=0; i<mX; ++i)
                {
                data_load(&d,l,v[i],&a);
                if (a==MISSING8) continue;
                if (a>X[i]) ++freq[i];
                }
            }
        if (n==0L)
            {
            sur_print("\nNo active observations!"); WAIT; return(-1);
            }

        a=1.0/(double)n;
        for (i=0; i<mX; ++i)
            {
            T[i]=X[i];
            freq[i]*=a;
            }
        strncpy(clabT,"Value   P       ",16);
        sprintf(exprT,"Tail_frequencies_in_data_%s_N=%d",word[1],n);
        save_T("TAILFREQ.M");

        return(1);
        }
예제 #21
0
파일: xall.c 프로젝트: rforge/muste
static int xall(void)
{
    int i,j,k;
    double x,y;

    int var1;
    int vartotal;
    int howmany;

    i=data_open(word[1],&d); if (i<0) return -1;
    i=mask(&d); if (i<0) return -1;
    i=conditions(&d); if (i<0) return -1;
    var1=varfind(&d,word[2]); if (var1<0) return -1;
    vartotal=atoi(word[3]);
    if (g>4) howmany=atoi(word[4]); else howmany=1;
    if (howmany<1) return -1;

    muste_kv_s_disp("\nConverting \"X ALL\" responses in %d variables...", vartotal);
    muste_kv_s_disp("\nMoving values of %d variables at a time...", howmany);

    if ((var1+howmany*vartotal) > d.m) {
        muste_kv_s_err("Not enough variables after %s!", word[2]);
        return -1;
    }

    for (j=d.l1; j<=d.l2; j++) {
        if (unsuitable(&d,j)) continue;
        muste_kv_s_disp(" %d",j);
        for (i=(var1+howmany*vartotal-howmany); i>=var1; i-=howmany) {
            data_load(&d,j,i,&x);
            if (x==MISSING8) {
                data_save(&d,j,i,MISSING8); /* (data in edit field) */
                for (k=1; k<howmany; k++) { /* 31.5.97 */
                    data_save(&d,j,i+k,MISSING8);
                }
                continue;
            }
            if (howmany==1 && ((int)x == i)) continue;
            if (((int)x < 1) || ((int)x > vartotal)) continue; /* 20.5.97 */
            data_save(&d,j,i,MISSING8);
            data_save(&d,j,var1+howmany*(int)x-howmany,x);
            for (k=1; k<howmany; k++) { /* 20.5.97 */
                data_load(&d,j,i+k,&y);
                data_save(&d,j,i+k,MISSING8);
                data_save(&d,j,var1+howmany*(int)x-howmany+k,y);
            }
        }
    }
    data_close(&d);
    return 1;
}
예제 #22
0
	void LayersManager::getGuideMapList(const std::string& targetID, std::vector< osg::ref_ptr<osg::Referenced> >& guideMapList)
	{
		SystemViewContext* currentcontext = getSystemViewContext(this);
		guideMapList.clear();
		std::string conditions(" where ");
		conditions.append(ACTOR_PROPERTY_LOOKATTARGET);
		conditions.append("='");
		conditions.append(targetID);
		conditions.append("'");
		bool result = dynamic_cast<VirtualDataSceneData::DataCenter*>(g_SystemContext._dataCenter.get())->selectAndBuildActor(guideMapList,
			CLASS_GUIDEMAPACTOR, conditions, currentcontext->_viewID);
		if (!result)
		{
			osg::notify(osg::NOTICE) << "getGuideMapList failure!!" << std::endl;
		}
	}
예제 #23
0
	void LayersManager::getViewPointAnimationList(const std::string& targetID, ActorRefPtrList& viewPointAnimationList)
	{
		SystemViewContext* currentcontext = getSystemViewContext(this);
		viewPointAnimationList.clear();
		std::string conditions(" where ");
		conditions.append(ACTOR_PROPERTY_LOOKATTARGET);
		conditions.append("='");
		conditions.append(targetID);
		conditions.append("'");
		bool result = dynamic_cast<VirtualDataSceneData::DataCenter*>(g_SystemContext._dataCenter.get())->selectAndBuildActor(viewPointAnimationList,
			CLASS_VIEWPOINTANIMATION, conditions, currentcontext->_viewID);
		if (!result)
		{
			osg::notify(osg::NOTICE) << "getViewPointAnimationList failure!!" << std::endl;
		}
	}
예제 #24
0
void WeatherPlugin::updateButton()
{
    if ((getTime() == 0) || (m_bar == NULL))
        return;
    const char **xpm = NULL;
    QString conditions(getConditions());
    if (conditions == "Overcast"){
        xpm = overcast;
    }else if (conditions == "Fog"){
        xpm = fog;
    }else if (conditions == "Storm"){
        xpm = storm;
    }else if (conditions == "Rain"){
        xpm = rain;
    }else if (conditions == "Snow"){
        xpm = snow;
    }else if (conditions == "Cloudy"){
        xpm = snow;
    }else if (conditions == "Clear"){
        xpm = isDay() ? day : night;
    }else if (conditions == "Partial cloudy"){
        xpm = isDay() ? day_cloudy : night_cloudy;
    }
    if (xpm){
        IconDef icon;
        icon.name = "weather";
        icon.xpm  = xpm;
        Event eIcon(EventAddIcon, &icon);
        eIcon.process();
    }
    QString text = unquoteText(getButtonText());
    QString tip = getTipText();
    text = replace(text);
    tip  = replace(tip);
    Command cmd;
    cmd->id		= CmdWeather;
    cmd->param	= m_bar;
    Event e(EventCommandWidget, cmd);
    CToolButton *btn = (CToolButton*)e.process();
    if (btn == NULL)
        return;
    btn->setTextLabel(text);
    btn->repaint();
    QToolTip::add(btn, tip);
}
    void createBall(double x, double y, double dx, double dy, double radius)
    {
        std::string id = boost::lexical_cast<std::string>(mBallNumbers);
        std::string obs_ports[] = {"coordinates"};
        std::map<std::string,vv::Value*> cond_map =
        {{"x",vv::Double::create(x)},
         {"y",vv::Double::create(y)},
         {"dx",vv::Double::create(dx)},
         {"dy",vv::Double::create(dy)},
         {"radius",vv::Double::create(radius)}};
        //Create experimental conditions
        vp::Condition ball_cond("ball_cond"+id);
    for(const auto& it : cond_map) {
        ball_cond.add(it.first);
            ball_cond.addValueToPort(it.first,it.second);
    }
        conditions().add(ball_cond);

        //Create observables
        vp::Observable ball_obs("ball"+id+"_position");
        for(const auto& it : obs_ports)
        ball_obs.add(it);
        observables().add(ball_obs);

        //Create vle model
        createModel("ball" + id,
                    Strings({"agent_input"}),
                    Strings({"agent_output"}),
                    "dyn_ball",
                    Strings({ball_cond.name()}),
                    ball_obs.name());

        //Attach observables
        for(const auto& it : obs_ports)
            addObservableToView("ball" + id, it, mView);

        //Connect to others
        connect("ball" + id);
        mModels.push_back("ball" + id);

        ++mBallNumbers;
    }
예제 #26
0
/** a very fast growing prime number set */
void growingPrimeSet(std::list<long>& primes,long mp, long np)
{
	std::vector<long> conditions(np*np-mp*mp-1,true);
	for(auto iter= primes.begin();iter!=primes.end();++iter)
	{
		if((*iter)>=np)
			break;
		long bi = (mp*mp/(*iter)+1)*(*iter);
		for(long k = bi ; k < np*np ; k+=(*iter))
		{
			conditions[k-mp*mp-1] = false;
		}
	}
	for(long k = mp*mp+1; k < np*np ; ++k)
	{
		if(conditions[k-mp*mp-1]){
			primes.emplace_back(k);
		}
	}
}
예제 #27
0
파일: cluster.c 프로젝트: rforge/muste
void muste_cluster(char *argv)
        {
        int i,k;
        double a;
        char ch;

//      if (argc==1) return;
        s_init(argv);

        if (g<2)
            {
            sur_print("\nUsage: CLUSTER <SURVO_data>,<output_line>");
            WAIT; return;
            }
        tulosrivi=0;
        if (g>2)
            {
            tulosrivi=edline2(word[2],1,1);
            if (tulosrivi==0) return;
            }

        strcpy(aineisto,word[1]);
        i=data_open(aineisto,&d); if (i<0) return;
        i=sp_init(r1+r-1); if (i<0) return;
        i=mask(&d); if (i<0) return;
        scales(&d);
        i=conditions(&d); if (i<0) return;

        gvar=activated(&d,'G');
        if (gvar<0)
            {
            sur_print("\nNo grouping variable (activated by 'G') given!");
            WAIT; return;
            }

        ivar=-1; ivar=activated(&d,'I');

        i=spfind("TRIALS");
        if (i>=0) maxiter=atoi(spb[i]);

        i=rand_init(); if (i<0) return;   /* 30.4.1994 */

        i=spfind("TEMPFILE");
        if (i>=0) strcpy(tempfile,spb[i]);
        else { strcpy(tempfile,etmpd); strcat(tempfile,"SURVO.CLU"); }

        i=spfind("PRIND");
        if (i>=0 && atoi(spb[i])>0) prind=1;

        data_load(&d,1L,gvar,&a);
        i=data_save(&d,1L,gvar,a);
        if (i<0) return;

        gvar2=(int *)muste_malloc(d.m_act*sizeof(int));
        if (gvar2==NULL) { not_enough_memory(); return; }

        k=0; n_saved=0; m=0;
        for (i=0; i<d.m_act; ++i)
            {
            ch=d.vartype[d.v[i]][1];
            if (ch=='G')
                {
                ++k;
                gvar2[n_saved]=d.v[i];    /* gvar=gvar2[0] */
                ++n_saved; continue;
                }
            if (ch=='I') { ++k; continue; }
            d.v[m++]=d.v[i];
            }
/*
printf("\nivar=%d gvar=%d m=%d\n",ivar,gvar,m); getch();
for (i=0; i<m; ++i) Rprintf(" %d",d.v[i]); getch();
printf("\n"); for (i=0; i<n_saved; ++i) Rprintf(" %d",gvar2[i]); getch();
*/

        i=spfind("GROUPS");
        if (i<0) ng=2; else ng=atoi(spb[i]);
        if (ng<2) ng=2;
        ng2=ng+2;
        mn=m; if (mn<ng) mn=ng;

        first_line=r+1; if (r+n_saved>r3) first_line=1;
        n_show=n_saved; if (n_show>r3) n_show=r3;

        i=varaa_tilat(); if (i<0) return;

        i=lue_havainnot(); if (i<0) return;
        hav_muistissa=havainnot_muistiin();
        ortogonalisoi();
        if (ivar_init) alustava_luokittelu();
        LOCATE(first_line,1);
        SCROLL_UP(first_line,r3+1,r3);
        sur_print("\nCluster analysis: Iteration 1:");
        while (sur_kbhit()) sur_getch();
        it=0;
        while (1)
            {
            while (1)
                {
                if (it) init_gr();
                i=init_tilat();
                if (i>=0) break;
                if (maxiter==1) return;
                }
            iteroi();
            ++it;
            if (maxiter>1) vertaa_muihin();
            if (it==maxiter) break;
            LOCATE(first_line,1);
            sprintf(sbuf,"\nIteration %d (Cluster analysis)",it);
            sur_print(sbuf);
            for (i=0; i<n_show; ++i)
               {
               if (freq[i]==0) break;
               sprintf(sbuf,"\n%d %g %d        ",i+1,lambda2[i],freq[i]); sur_print(sbuf);
               }
            if (sur_kbhit())
                {
                i=sur_getch(); if (i=='.') break;
                }
            }
        tulosta();

        data_close(&d);
        sur_delete(tempfile);
        s_end(argv);
        }
    void FdSimpleExtOUStorageEngine::calculate() const {

        // 1. Exercise
        QL_REQUIRE(arguments_.exercise->type() == Exercise::Bermudan,
                   "Bermudan exercise supported only");

        // 2. Mesher
        const Time maturity
            = rTS_->dayCounter().yearFraction(rTS_->referenceDate(),
                                              arguments_.exercise->lastDate());

        const ext::shared_ptr<Fdm1dMesher> xMesher(
                     new FdmSimpleProcess1dMesher(xGrid_, process_, maturity));

        ext::shared_ptr<Fdm1dMesher> storageMesher;

        if(yGrid_ == Null<Size>()){
            //elevator mesher
            std::vector<Real> storageValues(1, arguments_.capacity);
            storageValues.reserve(
                Size(arguments_.capacity/arguments_.changeRate)+1);

            for (Real level=0; level <= arguments_.capacity;
                    level+=arguments_.changeRate) {
                    storageValues.push_back(level);
                    storageValues.push_back(arguments_.capacity - level);
            }

            const std::set<Real, LessButNotCloseEnough>    orderedValues(
                storageValues.begin(), storageValues.end());
            storageValues.assign(orderedValues.begin(), orderedValues.end());

            storageMesher =    ext::shared_ptr<Fdm1dMesher>(
                new Predefined1dMesher(storageValues));
        }
        else {
            // uniform mesher
            storageMesher = ext::shared_ptr<Fdm1dMesher>(
                new Uniform1dMesher(0, arguments_.capacity, yGrid_));
        }

        const ext::shared_ptr<FdmMesher> mesher (
            new FdmMesherComposite(xMesher, storageMesher));

        // 3. Calculator
        ext::shared_ptr<FdmInnerValueCalculator> storageCalculator(
                                                  new FdmStorageValue(mesher));

        // 4. Step conditions
        std::list<ext::shared_ptr<StepCondition<Array> > > stepConditions;
        std::list<std::vector<Time> > stoppingTimes;

        // 4.1 Bermudan step conditions
        std::vector<Time> exerciseTimes;
        for (Size i=0; i<arguments_.exercise->dates().size(); ++i) {
            const Time t = rTS_->dayCounter()
                           .yearFraction(rTS_->referenceDate(),
                                         arguments_.exercise->dates()[i]);

            QL_REQUIRE(t >= 0, "exercise dates must not contain past date");
            exerciseTimes.push_back(t);
        }
        stoppingTimes.push_back(exerciseTimes);

        ext::shared_ptr<Payoff> payoff(
                                    new PlainVanillaPayoff(Option::Call, 0.0));

        ext::shared_ptr<FdmInnerValueCalculator> underlyingCalculator(
            new FdmExpExtOUInnerValueCalculator(payoff, mesher, shape_));

        stepConditions.push_back(ext::shared_ptr<StepCondition<Array> >(
            new FdmSimpleStorageCondition(exerciseTimes,
                                          mesher, underlyingCalculator,
                                          arguments_.changeRate)));

        ext::shared_ptr<FdmStepConditionComposite> conditions(
                new FdmStepConditionComposite(stoppingTimes, stepConditions));

        // 5. Boundary conditions
        const FdmBoundaryConditionSet boundaries;

        // 6. Solver
        FdmSolverDesc solverDesc = { mesher, boundaries, conditions,
                                     storageCalculator, maturity, tGrid_, 0 };

        ext::shared_ptr<FdmSimple2dExtOUSolver> solver(
                new FdmSimple2dExtOUSolver(
                           Handle<ExtendedOrnsteinUhlenbeckProcess>(process_),
                           rTS_, solverDesc, schemeDesc_));

        const Real x = process_->x0();
        const Real y = arguments_.load;

        results_.value = solver->valueAt(x, y);
    }
    void FdBlackScholesRebateEngine::calculate() const {

        // 1. Layout
        std::vector<Size> dim;
        dim.push_back(xGrid_);
        const boost::shared_ptr<FdmLinearOpLayout> layout(
                                              new FdmLinearOpLayout(dim));

        // 2. Mesher
        const boost::shared_ptr<StrikedTypePayoff> payoff =
            boost::dynamic_pointer_cast<StrikedTypePayoff>(arguments_.payoff);
        const Time maturity = process_->time(arguments_.exercise->lastDate());

        Real xMin=Null<Real>();
        Real xMax=Null<Real>();
        if (   arguments_.barrierType == Barrier::DownIn
            || arguments_.barrierType == Barrier::DownOut) {
            xMin = std::log(arguments_.barrier);
        }
        if (   arguments_.barrierType == Barrier::UpIn
            || arguments_.barrierType == Barrier::UpOut) {
            xMax = std::log(arguments_.barrier);
        }

        const boost::shared_ptr<Fdm1dMesher> equityMesher(
            new FdmBlackScholesMesher(xGrid_, process_, maturity,
                                      payoff->strike(), xMin, xMax));
        
        std::vector<boost::shared_ptr<Fdm1dMesher> > meshers;
        meshers.push_back(equityMesher);
        boost::shared_ptr<FdmMesher> mesher (
                                     new FdmMesherComposite(layout, meshers));
        
        // 3. Calculator
        boost::shared_ptr<StrikedTypePayoff> rebatePayoff(
                new CashOrNothingPayoff(Option::Call, 0.0, arguments_.rebate));
        boost::shared_ptr<FdmInnerValueCalculator> calculator(
                                new FdmLogInnerValue(rebatePayoff, mesher, 0));

        // 4. Step conditions
        std::list<boost::shared_ptr<StepCondition<Array> > > stepConditions;
        std::list<std::vector<Time> > stoppingTimes;

        // 4.1 Step condition if discrete dividends
        boost::shared_ptr<FdmDividendHandler> dividendCondition(
            new FdmDividendHandler(arguments_.cashFlow, mesher,
                                   process_->riskFreeRate()->referenceDate(),
                                   process_->riskFreeRate()->dayCounter(), 0));

        if(!arguments_.cashFlow.empty()) {
            stepConditions.push_back(dividendCondition);
            stoppingTimes.push_back(dividendCondition->dividendTimes());
        }

        QL_REQUIRE(arguments_.exercise->type() == Exercise::European,
                   "only european style option are supported");

        boost::shared_ptr<FdmStepConditionComposite> conditions(
                new FdmStepConditionComposite(stoppingTimes, stepConditions));

        // 5. Boundary conditions
        std::vector<boost::shared_ptr<FdmDirichletBoundary> > boundaries;
        if (   arguments_.barrierType == Barrier::DownIn
            || arguments_.barrierType == Barrier::DownOut) {
            boundaries.push_back(boost::shared_ptr<FdmDirichletBoundary>(
                new FdmDirichletBoundary(layout, arguments_.rebate, 0,
                                         FdmDirichletBoundary::Lower)));

        }
        if (   arguments_.barrierType == Barrier::UpIn
            || arguments_.barrierType == Barrier::UpOut) {
            boundaries.push_back(boost::shared_ptr<FdmDirichletBoundary>(
                new FdmDirichletBoundary(layout, arguments_.rebate, 0,
                                         FdmDirichletBoundary::Upper)));
        }

        // 6. Solver
        boost::shared_ptr<FdmBlackScholesSolver> solver(
                new FdmBlackScholesSolver(
                                Handle<GeneralizedBlackScholesProcess>(process_),
                                mesher, boundaries, conditions, calculator,
                                payoff->strike(), maturity, tGrid_,
                                dampingSteps_,
                                theta_, localVol_, illegalLocalVolOverwrite_));

        const Real spot = process_->x0();
        results_.value = solver->valueAt(spot);
        results_.delta = solver->deltaAt(spot);
        results_.gamma = solver->gammaAt(spot);
        results_.theta = solver->thetaAt(spot);
    }
예제 #30
0
/*
 * @brief
 * 本函数实现向数据库中更新MemberLevel的信息
 * @name Update
 * @arg
 * pObj QObject* :@class MemberLevel*, 需要更新到数据库的信息
 * @return bool
 * true 执行成功
 * false 执行失败
 * @author
 * QiumingLu Email:[email protected]
 * @test
 * no
 */
bool DaoMemberLevel::Update(MemberLevel *pObj)
{
    Q_ASSERT(pObj != NULL);
    QStringList conditions("LEVEL_ID"); //primary key
    return BaseDao::Update(pObj, "MEMBER_LEVEL", conditions);
}