CallSpecifiedMultiProduct::CallSpecifiedMultiProduct(
                         const Clone<MarketModelMultiProduct>& underlying,
                         const Clone<ExerciseStrategy<CurveState> >& strategy,
                         const Clone<MarketModelMultiProduct>& rebate)
                    : underlying_(underlying), 
                    strategy_(strategy), 
                    rebate_(rebate),
                    callable_(true) 
    {

        Size products = underlying_->numberOfProducts();
        EvolutionDescription d1 = underlying->evolution();
        const std::vector<Time>& rateTimes1 = d1.rateTimes();
        const std::vector<Time>& evolutionTimes1 = d1.evolutionTimes();
        const std::vector<Time>& exerciseTimes = strategy->exerciseTimes();

        if (!rebate_.empty()) 
        {
            EvolutionDescription d2 = rebate_->evolution();
            const std::vector<Time>& rateTimes2 = d2.rateTimes();
            QL_REQUIRE(rateTimes1.size() == rateTimes2.size() &&
                       std::equal(rateTimes1.begin(), rateTimes1.end(),
                                  rateTimes2.begin()),
                       "incompatible rate times");
        } 
        else
        {
            EvolutionDescription description(rateTimes1, exerciseTimes);
            Matrix amounts(products, exerciseTimes.size(), 0.0);

            rebate_ = MarketModelCashRebate(description, exerciseTimes,
                                            amounts, products);
        }

        std::vector<Time> mergedEvolutionTimes;
        std::vector<std::vector<Time> > allEvolutionTimes(4);
        allEvolutionTimes[0] = evolutionTimes1;
        allEvolutionTimes[1] = exerciseTimes;
        allEvolutionTimes[2] = rebate_->evolution().evolutionTimes();
        allEvolutionTimes[3] = strategy->relevantTimes();

        mergeTimes(allEvolutionTimes,
                                    mergedEvolutionTimes,
                                    isPresent_);

        // TODO: add relevant rates
        evolution_ = EvolutionDescription(rateTimes1, mergedEvolutionTimes);

        cashFlowTimes_ = underlying_->possibleCashFlowTimes();
        rebateOffset_ = cashFlowTimes_.size();
        const std::vector<Time> rebateTimes = rebate_->possibleCashFlowTimes();
        cashFlowTimes_.insert(cashFlowTimes_.end(),
                                                           rebateTimes.begin(), rebateTimes.end());

        dummyCashFlowsThisStep_ = std::vector<Size>(products, 0);
        Size n = rebate_->maxNumberOfCashFlowsPerProductPerStep();
        dummyCashFlowsGenerated_ =
            std::vector<std::vector<CashFlow> >(products,
                                                std::vector<CashFlow>(n));
    }
Clone makeClone(int pos[], sf::Texture *mctexture){
    Clone clone;
    sf::Sprite sprite;
    sprite.setTexture(*mctexture);
    sprite.setOrigin(TILE/2, TILE/2);
    sprite.setPosition(TILE * (pos[0] + 0.5), TILE * (pos[1] + 0.5));
    sprite.setTextureRect(sf::IntRect(4*TILE, TILE, TILE, TILE));
    clone.setSprite(sprite);
    clone.move_pos = 0;
    return clone;
}
Beispiel #3
0
void FaceOff::updateClone()
{
    gl::ScopedMatrices mvp;
    gl::setMatricesWindow(mRenderedOfflineFaceFbo->getSize());
    gl::ScopedViewport viewport(0, 0, mRenderedOfflineFaceFbo->getWidth(), mRenderedOfflineFaceFbo->getHeight());

    // TODO: merge these two passes w/ MRTs
    {
        gl::ScopedFramebuffer fbo(mRenderedOfflineFaceFbo);
        gl::ScopedGlslProg glsl(gl::getStockShader(gl::ShaderDef().texture()));
        gl::ScopedTextureBind t0(mOfflineFaceTex, 0);
        gl::clear(ColorA::black(), false);
        gl::draw(mFaceMesh);
    }

    if (!MOVIE_MODE)
    {
        {
            gl::ScopedFramebuffer fbo(mFaceMaskFbo);
            gl::clear(ColorA::black(), false);
            gl::draw(mFaceMesh);
        }

        // TODO: add gl::ScopedMatrices in mClone.update()
        mClone.update(mRenderedOfflineFaceFbo->getColorTexture(), mCapture.texture, mFaceMaskFbo->getColorTexture());
        mHasNewRenderedFace = true;
    }
}
Beispiel #4
0
reg_t kDisposeClone(EngineState *s, int argc, reg_t *argv) {
	reg_t obj = argv[0];
	Clone *object = s->_segMan->getObject(obj);

	if (!object) {
		error("Attempt to dispose non-class/object at %04x:%04x",
		         PRINT_REG(obj));
		return s->r_acc;
	}

	// SCI uses this technique to find out, if it's a clone and if it's supposed to get freed
	//  At least kq4early relies on this behavior. The scripts clone "Sound", then set bit 1 manually
	//  and call kDisposeClone later. In that case we may not free it, otherwise we will run into issues
	//  later, because kIsObject would then return false and Sound object wouldn't get checked.
	uint16 infoSelector = object->getInfoSelector().toUint16();
	if ((infoSelector & 3) == kInfoFlagClone)
		object->markAsFreed();

	return s->r_acc;
}
ProxyGreekEngine::ProxyGreekEngine(
    const boost::shared_ptr<MarketModelEvolver>& evolver,
    const std::vector<
    std::vector<boost::shared_ptr<ConstrainedEvolver> > >&
    constrainedEvolvers,
    const std::vector<std::vector<std::vector<Real> > >& diffWeights,
    const std::vector<Size>& startIndexOfConstraint,
    const std::vector<Size>& endIndexOfConstraint,
    const Clone<MarketModelMultiProduct>& product,
    Real initialNumeraireValue)
    : originalEvolver_(evolver), constrainedEvolvers_(constrainedEvolvers),
      diffWeights_(diffWeights),
      startIndexOfConstraint_(startIndexOfConstraint),
      endIndexOfConstraint_(endIndexOfConstraint),
      product_(product),
      initialNumeraireValue_(initialNumeraireValue),
      numberProducts_(product->numberOfProducts()),
      numerairesHeld_(product->numberOfProducts()),
      numberCashFlowsThisStep_(product->numberOfProducts()),
      cashFlowsGenerated_(product->numberOfProducts()) {
    for (Size i=0; i<numberProducts_; ++i)
        cashFlowsGenerated_[i].resize(
            product_->maxNumberOfCashFlowsPerProductPerStep());

    const std::vector<Time>& cashFlowTimes =
        product_->possibleCashFlowTimes();
    const std::vector<Rate>& rateTimes = product_->evolution().rateTimes();
    Size n = cashFlowTimes.size();
    discounters_.reserve(n);
    for (Size j=0; j<n; ++j)
        discounters_.push_back(MarketModelDiscounter(cashFlowTimes[j],
                               rateTimes));
    const std::vector<Rate>& evolutionTimes =
        product_->evolution().evolutionTimes();
    constraints_.resize(evolutionTimes.size());
    constraintsActive_.resize(evolutionTimes.size());
}
Beispiel #6
0
reg_t kClone(EngineState *s, int argc, reg_t *argv) {
	reg_t parentAddr = argv[0];
	const Object *parentObj = s->_segMan->getObject(parentAddr);
	reg_t cloneAddr;
	Clone *cloneObj; // same as Object*

	if (!parentObj) {
		error("Attempt to clone non-object/class at %04x:%04x failed", PRINT_REG(parentAddr));
		return NULL_REG;
	}

	debugC(kDebugLevelMemory, "Attempting to clone from %04x:%04x", PRINT_REG(parentAddr));

	uint16 infoSelector = parentObj->getInfoSelector().toUint16();
	cloneObj = s->_segMan->allocateClone(&cloneAddr);

	if (!cloneObj) {
		error("Cloning %04x:%04x failed-- internal error", PRINT_REG(parentAddr));
		return NULL_REG;
	}

	// In case the parent object is a clone itself we need to refresh our
	// pointer to it here. This is because calling allocateClone might
	// invalidate all pointers, references and iterators to data in the clones
	// segment.
	//
	// The reason why it might invalidate those is, that the segment code
	// (Table) uses Common::Array for internal storage. Common::Array now
	// might invalidate references to its contained data, when it has to
	// extend the internal storage size.
	if (infoSelector & kInfoFlagClone)
		parentObj = s->_segMan->getObject(parentAddr);

	*cloneObj = *parentObj;

	// Mark as clone
	infoSelector &= ~kInfoFlagClass; // remove class bit
	cloneObj->setInfoSelector(make_reg(0, infoSelector | kInfoFlagClone));

	cloneObj->setSpeciesSelector(cloneObj->getPos());
	if (parentObj->isClass())
		cloneObj->setSuperClassSelector(parentObj->getPos());
	s->_segMan->getScript(parentObj->getPos().getSegment())->incrementLockers();
	s->_segMan->getScript(cloneObj->getPos().getSegment())->incrementLockers();

	return cloneAddr;
}
 FByCloneHeap( Clone<A1> a ) // not ambiguous, cost is O(N) here and lifetime of a is whatever.
   : myA1( a.allocate() )
 {
   std::cout << "  FByCloneHeap( Clone<A1> a ) " << myA1 << std::endl;
 }
 inline void ExerciseAdapter::reset() {
     exercise_->reset();
     currentIndex_ = 0;
 }
 inline const EvolutionDescription& ExerciseAdapter::evolution() const {
     return exercise_->evolution();
 }
 inline std::vector<Time>
 ExerciseAdapter::possibleCashFlowTimes() const {
     return exercise_->possibleCashFlowTimes();
 }
 inline DiscountFactor FittedBondDiscountCurve::discountImpl(Time t) const {
     calculate();
     return fittingMethod_->discountFunction(fittingMethod_->solution_, t);
 }
Beispiel #12
0
void FaceOff::draw()
{
    gl::clear(ColorA::black(), false);

    if (!mCapture.isReady())
        return;

    gl::setMatricesWindow(getWindowSize());

    gl::enableAlphaBlending();

    float camAspect = CAM_W / (float)CAM_H;
    float winAspect = getWindowAspectRatio();
    float adaptiveCamW = 0;
    float adaptiveCamH = 0;
    if (camAspect > winAspect)
    {
        adaptiveCamW = APP_W;
        adaptiveCamH = APP_W / camAspect;
    }
    else
    {
        adaptiveCamH = APP_H;
        adaptiveCamW = APP_H * camAspect;
    }
    Area srcArea = { 0, 0, CAM_W, CAM_H };
    Rectf dstRect =
    {
        APP_W * 0.5f - adaptiveCamW * 0.5f,
        APP_H * 0.5f - adaptiveCamH * 0.5f,
        APP_W * 0.5f + adaptiveCamW * 0.5f,
        APP_H * 0.5f + adaptiveCamH * 0.5f
    };

    if (!mOnlineTracker)
    {
        gl::draw(mCapture.texture, srcArea, dstRect);
        return;
    }

    gl::Texture2dRef fullscreenTex;
    if (VFX_VISIBLE && mHasNewRenderedFace)
    {
        fullscreenTex = mClone.getResultTexture();
    }
    else if (VFX_VISIBLE && MOVIE_MODE)
    {
        fullscreenTex = mRenderedOfflineFaceFbo->getColorTexture();
    }
    else
    {
        fullscreenTex = mCapture.texture;
    }
    gl::draw(fullscreenTex, srcArea, dstRect);

    if (OFFLINE_VISIBLE)
    {
        gl::draw(mOfflineFaceTex);
    }

    FPS = getAverageFps();

    gl::disableAlphaBlending();

    if (WIREFRAME_MODE && (MOVIE_MODE || mHasNewRenderedFace))
    {
        gl::enableWireframe();

        gl::ScopedModelMatrix modelMatrix;
        gl::ScopedColor color(ColorA(0, 1.0f, 0, 1.0f));
        gl::translate(dstRect.x1, dstRect.y1);
        gl::scale(adaptiveCamW / CAM_W, adaptiveCamH / CAM_H);
        gl::draw(mFaceMesh);

        if (OFFLINE_VISIBLE)
        {
            gl::draw(mOfflineTracker->getImageMesh());
        }

        gl::disableWireframe();
    }
    
    updateGui();
}
Beispiel #13
0
void FaceOff::trackerThreadFn()
{
    jing::Option option;
    option.scale = 0.5f;
    mOfflineTracker = jing::BaseFaceTracker::create();
    mOnlineTracker = jing::BaseFaceTracker::create(option);

    bool shouldInitFaceMesh = false;

    while (!mShouldQuit)
    {
        // TODO: more robust with update_signal
        if (!mCapture.checkNewFrame())
        {
            sleep(1.0f);
            continue;
        }
        
        if (mDoesCaptureNeedsInit)
        {
            // TODO: more robust with setup_signal
            mDoesCaptureNeedsInit = false;

            CAM_W = mCapture.size.x;
            CAM_H = mCapture.size.y;

            auto createFboFn = [this]
            {
                gl::Fbo::Format fboFormat;
                fboFormat.enableDepthBuffer(false);
                mRenderedOfflineFaceFbo = gl::Fbo::create(CAM_W, CAM_H, fboFormat);
                mFaceMaskFbo = gl::Fbo::create(CAM_W, CAM_H, fboFormat);

                mClone.setup(CAM_W, CAM_H);
                mClone.setStrength(16);
            };
            dispatchAsync(createFboFn);
        }

        if (mPeopleId != PEOPLE_ID)
        {
            mPeopleId = PEOPLE_ID;

            ImageSourceRef img = loadImage(loadAsset("people/" + mPeopleNames[PEOPLE_ID]));
            updateOfflineImage(img);

            shouldInitFaceMesh = true;
        }

        mOnlineTracker->update(mCapture.surface);

        if (!mOnlineTracker->getFound())
        {
            mHasNewRenderedFace = false;
            continue;
        }

        int nPoints = mOnlineTracker->size();
        if (shouldInitFaceMesh)
        {
            shouldInitFaceMesh = false;
            mFaceMesh.getBufferTexCoords0().clear();

            auto imgSize = mOfflineTracker->getImageSize();
            for (int i = 0; i < nPoints; i++)
            {
                vec3 point = mOfflineTracker->getImagePoint(i);
                mFaceMesh.appendTexCoord({ point.x / imgSize.x, point.y / imgSize.y });
            }
            mOnlineTracker->addTriangleIndices(mFaceMesh);
        }

        mFaceMesh.getBufferPositions().clear();
        for (int i = 0; i < nPoints; i++)
        {
            mFaceMesh.appendPosition(mOnlineTracker->getImagePoint(i));
        }

        if (VFX_VISIBLE && mOfflineFaceTex)
        {
            dispatchAsync(bind(&FaceOff::updateClone, this));
        }
    }
}
Beispiel #14
0
// *** MAIN START***
int main (int argc, const char * argv[]){
  cmdl_opts opts;
  get_opts( argc, argv, opts);
  int nTimes=0, nT=0;
  //*** EMITTED DATA OBJECTS ***
  Emission cnaEmit, bafEmit, snvEmit;
  if (opts.cna_fn != NULL) get_cna_data( &cnaEmit, opts, nTimes);
  if (opts.baf_fn != NULL) get_baf_data( &bafEmit, opts, nTimes, nT);
  if (opts.snv_fn != NULL) get_snv_data( &snvEmit, opts, nTimes, nT);
  //*** ANNOUNCE ***
  printf("\ncloneHD: probabilistic inference of sub-clonality using...\n\n");
  if (cnaEmit.is_set){
    printf("CNA data in %s: %i sites in %i chr across %i samples\n", 
	   opts.cna_fn, cnaEmit.total_loci, cnaEmit.nSamples, nTimes);
  }
  if (bafEmit.is_set){
    printf("BAF data in %s: %i sites in %i chr across %i samples\n", 
	   opts.baf_fn, bafEmit.total_loci, bafEmit.nSamples, nTimes);
  }
  if (snvEmit.is_set){
    printf("SNV data in %s: %i sites in %i chr across %i samples\n", 
	   opts.snv_fn, snvEmit.total_loci, snvEmit.nSamples, nTimes);
  }
  cout<<endl;
  // *** ALLOCATE CLONE ***
  Clone myClone;
  myClone.allocate( &cnaEmit, &bafEmit, &snvEmit, opts.chr_fn);
  myClone.cna_pen_zero = opts.cna_pen_zero;//CNA penalty for zero total copies
  myClone.cna_pen_diff = opts.cna_pen_diff;//CNA penalty for different c.n.
  myClone.cna_pen_norm = opts.cna_pen_norm;//CNA penalty for non-normal c.n.
  myClone.baf_pen_comp = opts.baf_pen_comp;//BAF penalty for complex chr status
  myClone.snv_pen_high = opts.snv_pen_high;//SNV penalty for high SNV genotypes
  myClone.snv_pen_mult = opts.snv_pen_mult;//SNV penalty for multiple hit SNVs
  myClone.snv_fpr  = opts.snv_fpr;//SNV false-positive rate
  myClone.snv_fpf  = opts.snv_fpf;//SNV frequency of false positives
  myClone.bulk_fix = opts.bulk_fix;
  myClone.cnaGrid  = opts.cnaGrid;
  myClone.bafGrid  = opts.bafGrid;
  myClone.snvGrid  = opts.snvGrid;
  myClone.bulkGrid = opts.bulkGrid;
  myClone.learn_priors = (cnaEmit.is_set || snvEmit.connect || opts.avcn_fn != NULL) ? 0 : opts.learn_priors;
  // *** GET MAX-TCN INFO ***
  get_maxtcn_input( opts.maxtcn_fn, opts.maxtcn, &myClone);
  // *** GET SNV BULK PRIOR ***
  if ( snvEmit.is_set && opts.bulk_fn != NULL ){
    printf("Using data in %s as SNV bulk prior...\n", opts.bulk_fn);
    get_snv_bulk_prior( &myClone, opts);
  }
  //*** GET JUMP PROBABILITY TRACKS and COLLAPSE TO EVENTS***
  get_jump_probability( &myClone, opts);
  //...now all segments are fixed and mean_tcn/av_cn allocated.
  if ( snvEmit.is_set && !cnaEmit.is_set ){//for SNV only
    // *** GET TOTAL MEAN COPYNUMBER TRACK ***  
    if( opts.mntcn_fn != NULL ){
      get_mean_tcn( opts.mntcn_fn, &myClone, &snvEmit);
    } 
    // *** GET AVAILABLE COPYNUMBER TRACK ***  
    if ( opts.avcn_fn != NULL ){
      get_avail_cn( opts.avcn_fn, &myClone, &snvEmit);
    }
  }
  //*** GET READ DEPTH BIAS FIELD ***
  if (cnaEmit.is_set && opts.bias_fn != NULL){
    get_bias_field( &myClone, opts);
  }
  //*** PREPARE COARSE-GRAINED DATA ***
  if (cnaEmit.is_set && (opts.cna_jumps_fn != NULL || opts.cna_jump == 0.0)){
    cnaEmit.log_space      = 1;
    cnaEmit.coarse_grained = 1;
    printf( "Collapsed CNA data to %5i segments based on potential jump events.\n", 
	    cnaEmit.total_events);
    cout<<"Precomputing for CNA..."<<flush;
    myClone.get_cnaEmitLog();
    cout<<"done."<<endl;
  }
  if (bafEmit.is_set && ( opts.cna_jumps_fn != NULL || opts.baf_jumps_fn != NULL || opts.baf_jump == 0.0)){
    bafEmit.log_space      = 1;
    bafEmit.coarse_grained = 1;
    printf("Collapsed BAF data to %5i segments based on potential jump events.\n", bafEmit.total_events);
    cout<<"Precomputing for BAF..."<<flush;
    myClone.get_bafEmitLog();
    cout<<"done."<<endl;
  }
  if (snvEmit.is_set && opts.snv_jumps_fn != NULL){
    snvEmit.log_space      = 1;
    snvEmit.coarse_grained = 1;
    printf("Collapsed SNV data to %5i segments based on potential jump events.\n", snvEmit.total_events);
    cout<<"Precomputing for SNV..."<<flush;
    myClone.get_snvEmitLog();
    cout<<"done."<<endl;
  }
  cout<<endl;
  //exit(0);
  // get purities...
  if (opts.purity_fn != NULL){
    get_purity( opts.purity_fn, myClone.min_purity);
  }
  // get user pre-defined clones
  gsl_matrix * clones = NULL;
  gsl_vector * mass   = NULL;
  if (opts.clones_fn != NULL) get_fixed_clones( clones, mass, opts.clones_fn, nTimes);
  int bestn=0, rows=0;
  if (mass != NULL   && (int) mass->size > nTimes)    rows = (int) mass->size;
  if (clones != NULL && (int) clones->size1 > nTimes) rows = (int) clones->size1;
  if (rows > nTimes){//print LLH's for predefined parameter values...
    print_llh_for_set( clones, mass, &myClone, opts);
    return(0);
  }
  else{
    // ****** INFERENCE STARTS HERE ******
    bestn = infer_clones( clones, mass, &myClone, opts);
    printf("cloneHD in ");
    if (cnaEmit.is_set && bafEmit.is_set && snvEmit.is_set) cout<<"cna-baf-snv ";
    if (cnaEmit.is_set && bafEmit.is_set && !snvEmit.is_set) cout<<"cna-baf ";
    if (cnaEmit.is_set && !bafEmit.is_set && snvEmit.is_set) cout<<"cna-snv ";
    if (cnaEmit.is_set && !bafEmit.is_set && !snvEmit.is_set) cout<<"cna ";
    if (!cnaEmit.is_set && !bafEmit.is_set && snvEmit.is_set) cout<<"snv ";
    printf("mode found support for %i sub-clone(s) in the data.\n", bestn);
    // ****** INFERENCE COMPLETED ********
  }
  print_all_results( &myClone, opts);
  // all done...
  return (0);
}