Exemple #1
0
FuncDeclaration *StructDeclaration::buildXopEquals(Scope *sc)
{
    if (!search_function(this, Id::eq))
        return NULL;

    /* static bool__xopEquals(in void* p, in void* q) {
     *     return ( *cast(const S*)(p) ).opEquals( *cast(const S*)(q) );
     * }
     */

    Parameters *parameters = new Parameters;
    parameters->push(new Parameter(STCin, Type::tvoidptr, Id::p, NULL));
    parameters->push(new Parameter(STCin, Type::tvoidptr, Id::q, NULL));
    TypeFunction *tf = new TypeFunction(parameters, Type::tbool, 0, LINKd);
    tf = (TypeFunction *)tf->semantic(loc, sc);

    Identifier *id = Lexer::idPool("__xopEquals");
    FuncDeclaration *fop = new FuncDeclaration(loc, 0, id, STCstatic, tf);

    Expression *e = new CallExp(0,
        new DotIdExp(0,
            new PtrExp(0, new CastExp(0,
                new IdentifierExp(0, Id::p), type->pointerTo()->constOf())),
            Id::eq),
        new PtrExp(0, new CastExp(0,
            new IdentifierExp(0, Id::q), type->pointerTo()->constOf())));

    fop->fbody = new ReturnStatement(loc, e);

    size_t index = members->dim;
    members->push(fop);

    sc = sc->push();
    sc->stc = 0;
    sc->linkage = LINKd;

    unsigned errors = global.startGagging();
    fop->semantic(sc);
    if (errors == global.gaggedErrors)
    {   fop->semantic2(sc);
        if (errors == global.gaggedErrors)
        {   fop->semantic3(sc);
            if (errors == global.gaggedErrors)
                fop->addMember(sc, this, 1);
        }
    }
    if (global.endGagging(errors))    // if errors happened
    {
        members->remove(index);

        if (!xerreq)
        {
            Expression *e = new IdentifierExp(loc, Id::empty);
            e = new DotIdExp(loc, e, Id::object);
            e = new DotIdExp(loc, e, Lexer::idPool("_xopEquals"));
            e = e->semantic(sc);
            Dsymbol *s = getDsymbol(e);
            FuncDeclaration *fd = s->isFuncDeclaration();

            xerreq = fd;
        }
        fop = xerreq;
    }

    sc->pop();

    return fop;
}
  ToneProfile::ToneProfile(tone_profile_t whichProfile, bool majorScale, const Parameters& params){

    float p[12];
    if(whichProfile == TONE_PROFILE_SILENT){
      p[0]=0; p[1]=0;
      p[2]=0; p[3]=0;
      p[4]=0; p[5]=0;
      p[6]=0; p[7]=0;
      p[8]=0; p[9]=0;
      p[10]=0; p[11]=0;
    }else if(whichProfile == TONE_PROFILE_TEMPERLEY){
      if(majorScale){
        p[0]=5.0; p[1]=2.0;
        p[2]=3.5; p[3]=2.0;
        p[4]=4.5;
        p[5]=4.0; p[6]=2.0;
        p[7]=4.5; p[8]=2.0;
        p[9]=3.5; p[10]=1.5;
        p[11]=4.0;
      }else{
        p[0]=5.0; p[1]=2.0;
        p[2]=3.5;
        p[3]=4.5; p[4]=2.0;
        p[5]=4.0; p[6]=2.0;
        p[7]=4.5;
        p[8]=3.5; p[9]=2.0;
        p[10]=1.5; p[11]=4.0;
      }
    }else if(whichProfile == TONE_PROFILE_GOMEZ){
      if(majorScale){
        p[0]=0.82; p[1]=0.00;
        p[2]=0.55; p[3]=0.00;
        p[4]=0.53;
        p[5]=0.30; p[6]=0.08;
        p[7]=1.00; p[8]=0.00;
        p[9]=0.38; p[10]=0.00;
        p[11]=0.47;
      }else{
        p[0]=0.81; p[1]=0.00;
        p[2]=0.53;
        p[3]=0.54; p[4]=0.00;
        p[5]=0.27; p[6]=0.07;
        p[7]=1.00;
        p[8]=0.27; p[9]=0.07;
        p[10]=0.10; p[11]=0.36;
      }
    }else if(whichProfile == TONE_PROFILE_SHAATH){
      if(majorScale){
        p[0]=6.6; p[1]=2.0;
        p[2]=3.5; p[3]=2.3;
        p[4]=4.6;
        p[5]=4.0; p[6]=2.5;
        p[7]=5.2; p[8]=2.4;
        p[9]=3.7; p[10]=2.3;
        p[11]=3.4;
      }else{
        p[0]=6.5; p[1]=2.7;
        p[2]=3.5;
        p[3]=5.4; p[4]=2.6;
        p[5]=3.5; p[6]=2.5;
        p[7]=5.2;
        p[8]=4.0; p[9]=2.7;
        p[10]=4.3; p[11]=3.2;
      }
    }else if(whichProfile == TONE_PROFILE_KRUMHANSL){
      if(majorScale){
        p[0]=6.35; p[1]=2.23;
        p[2]=3.48; p[3]=2.33;
        p[4]=4.38;
        p[5]=4.09; p[6]=2.52;
        p[7]=5.19; p[8]=2.39;
        p[9]=3.66; p[10]=2.29;
        p[11]=2.88;
      }else{
        p[0]=6.33; p[1]=2.68;
        p[2]=3.52;
        p[3]=5.38; p[4]=2.60;
        p[5]=3.53; p[6]=2.54;
        p[7]=4.75;
        p[8]=3.98; p[9]=2.69;
        p[10]=3.34; p[11]=3.17;
      }
    }else{ // Custom
      std::vector<float> ctp = params.getCustomToneProfile();
      if(majorScale){
        for (unsigned int i=0; i<12; i++)
          p[i] = (float)ctp[i];
      }else{
        for (unsigned int i=0; i<12; i++)
          p[i] = (float)ctp[i+12];
      }
    }

    // copy into doubly-linked circular list
    tonic = new Binode<float>(p[0]);
    Binode<float> *q = tonic;
    for (unsigned int i=1; i<12; i++){
      q->r = new Binode<float>(p[i]);
      q->r->l = q;
      q = q->r;
    }
    q->r = tonic;
    tonic->l = q;
    // offset from A to C (3 semitones) if specified in Parameters
    if(params.getOffsetToC()){
      for (unsigned int i=0; i<3; i++)
        tonic = tonic->r;
    }

    // get mean in preparation for correlation
    profileMean = 0.0;
    for (unsigned int i=0; i<12; i++)
      profileMean += (p[i] / 12.0);
  }
Exemple #3
0
RadCalcer::RadCalcer( Parameters& params_, long opacity_, bool correlated_ )
  : zDist( params_, opacity_ ), qperps( opacity_, correlated_ ), n( opacity_ )
{
  std::vector<double> ReturnedParamsDouble;
  std::vector<long> ReturnedParamsLong;
  std::list<std::string> ReturnedParamsString;
  std::list<std::string>::iterator it;

  // First, we get the parameters of the medium
  // This is: 1st = mu, 2nd = temperature, 3rd = gluon mass, 4th = gluon mean free path
  // Here, we only need the gluon mass
  // the zDist will need the others
  ReturnedParamsDouble = params_.GetParametersDouble( "@mediumParams" );
  _mg = ReturnedParamsDouble[2];

  // Next, get the jet flavour
  ReturnedParamsString = params_.GetParametersString( "@jetFlavour" );
  std::string jetFlavour = ReturnedParamsString.front();
  if ( jetFlavour == "Gluon" )
  {
    _cr = 3.; _mass = _mg;
  }
  else if ( jetFlavour == "Light" )
  {
    _cr = 4./3.; _mass = _mg / sqrt(2);
  }
  else if ( jetFlavour == "Charm" )
  {
    _cr = 4./3.; _mass = 1.2;
  }
  else if ( jetFlavour == "Bottom" )
  {
    _cr = 4./3.; _mass = 4.75;
  }
  else
  {
    std::cerr << "@jetFlavour not understood" << std::endl;
    exit(0);
  }

  // Now, check whether also specifying a jet mass
  ReturnedParamsDouble = params_.GetParametersDouble( "@jetMassDirect" );
  if ( ReturnedParamsDouble.size() > 0 )
    _mass = ReturnedParamsDouble[0];
  
  // Now, the momentum, to give the jet energy
  ReturnedParamsDouble = params_.GetParametersDouble( "@jetMomentum" );
  double jetMomentum = ReturnedParamsDouble[0];
  // Now calculate and set energy, and mass
  _en = sqrt( _mass*_mass + jetMomentum*jetMomentum );

  // The jet path length in the medium
  ReturnedParamsDouble = params_.GetParametersDouble( "@pathLength" );
  _length = ReturnedParamsDouble[0];

  // The setting on the k max
  ReturnedParamsLong = params_.GetParametersLong( "@limitSet" );
  _switchkmax = ReturnedParamsLong[0];

  // The strong coupling, alpha_s
  ReturnedParamsString = params_.GetParametersString( "@alpha" );
  it = ReturnedParamsString.begin();
  if ( *it == "fixed" )
  {
    ++it;
    _alphas = boost::lexical_cast<double>( *it );
  }
  else
  {
    std::cerr << "Radcalcer, @alpha not understood";
    std::cerr << std::endl;
    exit(0);
  }

  ReturnedParamsString = params_.GetParametersString( "@incClassicalDiffusion" );
  if ( ReturnedParamsString.front() == "yes" )
    _diffexclude = false;
  else if ( ReturnedParamsString.front() == "no" )
    _diffexclude = true;
  else
  {
    std::cerr << "Radcalcer, @incClassicalDiffusion not understood as yes or no";
    std::cerr << std::endl;
    exit(0);
  }


  _correlated = correlated_;
}
Exemple #4
0
FuncDeclaration *buildXopCmp(StructDeclaration *sd, Scope *sc)
{
    //printf("StructDeclaration::buildXopCmp() %s\n", toChars());
    if (Dsymbol *cmp = search_function(sd, Id::cmp))
    {
        if (FuncDeclaration *fd = cmp->isFuncDeclaration())
        {
            TypeFunction *tfcmpptr;
            {
                Scope scx;

                /* const int opCmp(ref const S s);
                 */
                Parameters *parameters = new Parameters;
                parameters->push(new Parameter(STCref | STCconst, sd->type, NULL, NULL));
                tfcmpptr = new TypeFunction(parameters, Type::tint32, 0, LINKd);
                tfcmpptr->mod = MODconst;
                tfcmpptr = (TypeFunction *)tfcmpptr->semantic(Loc(), &scx);
            }
            fd = fd->overloadExactMatch(tfcmpptr);
            if (fd)
                return fd;
        }
    }
    else
    {
#if 0   // FIXME: doesn't work for recursive alias this
        /* Check opCmp member exists.
         * Consider 'alias this', but except opDispatch.
         */
        Expression *e = new DsymbolExp(sd->loc, sd);
        e = new DotIdExp(sd->loc, e, Id::cmp);
        Scope *sc2 = sc->push();
        e = e->trySemantic(sc2);
        sc2->pop();
        if (e)
        {
            Dsymbol *s = NULL;
            switch (e->op)
            {
                case TOKoverloadset:    s = ((OverExp *)e)->vars;       break;
                case TOKimport:         s = ((ScopeExp *)e)->sds;       break;
                case TOKvar:            s = ((VarExp *)e)->var;         break;
                default:                break;
            }
            if (!s || s->ident != Id::cmp)
                e = NULL;   // there's no valid member 'opCmp'
        }
        if (!e)
            return NULL;    // bitwise comparison would work
        /* Essentially, a struct which does not define opCmp is not comparable.
         * At this time, typeid(S).compare might be correct that throwing "not implement" Error.
         * But implementing it would break existing code, such as:
         *
         * struct S { int value; }  // no opCmp
         * int[S] aa;   // Currently AA key uses bitwise comparison
         *              // (It's default behavior of TypeInfo_Strust.compare).
         *
         * Not sure we should fix this inconsistency, so just keep current behavior.
         */
#else
        return NULL;
#endif
    }

    if (!sd->xerrcmp)
    {
        // object._xopCmp
        Identifier *id = Lexer::idPool("_xopCmp");
        Expression *e = new IdentifierExp(sd->loc, Id::empty);
        e = new DotIdExp(sd->loc, e, Id::object);
        e = new DotIdExp(sd->loc, e, id);
        e = e->semantic(sc);
        Dsymbol *s = getDsymbol(e);
        if (!s)
        {
            ::error(Loc(), "ICE: %s not found in object module. You must update druntime", id->toChars());
            fatal();
        }
        assert(s);
        sd->xerrcmp = s->isFuncDeclaration();
    }

    Loc declLoc = Loc();    // loc is unnecessary so __xopCmp is never called directly
    Loc loc = Loc();        // loc is unnecessary so errors are gagged

    Parameters *parameters = new Parameters;
    parameters->push(new Parameter(STCref | STCconst, sd->type, Id::p, NULL));
    parameters->push(new Parameter(STCref | STCconst, sd->type, Id::q, NULL));
    TypeFunction *tf = new TypeFunction(parameters, Type::tint32, 0, LINKd);

    Identifier *id = Id::xopCmp;
    FuncDeclaration *fop = new FuncDeclaration(declLoc, Loc(), id, STCstatic, tf);

    Expression *e1 = new IdentifierExp(loc, Id::p);
    Expression *e2 = new IdentifierExp(loc, Id::q);
    Expression *e = new CallExp(loc, new DotIdExp(loc, e2, Id::cmp), e1);

    fop->fbody = new ReturnStatement(loc, e);

    unsigned errors = global.startGagging();    // Do not report errors
    Scope *sc2 = sc->push();
    sc2->stc = 0;
    sc2->linkage = LINKd;

    fop->semantic(sc2);
    fop->semantic2(sc2);

    sc2->pop();
    if (global.endGagging(errors))    // if errors happened
        fop = sd->xerrcmp;

    return fop;
}
Exemple #5
0
void StructDeclaration::semantic(Scope *sc)
{
    Scope *sc2;

    //printf("+StructDeclaration::semantic(this=%p, %s '%s', sizeok = %d)\n", this, parent->toChars(), toChars(), sizeok);

    //static int count; if (++count == 20) halt();

    assert(type);
    if (!members)               // if opaque declaration
    {
        return;
    }

    if (symtab)
    {   if (sizeok == SIZEOKdone || !scope)
        {   //printf("already completed\n");
            scope = NULL;
            return;             // semantic() already completed
        }
    }
    else
        symtab = new DsymbolTable();

    Scope *scx = NULL;
    if (scope)
    {   sc = scope;
        scx = scope;            // save so we don't make redundant copies
        scope = NULL;
    }

    int errors = global.errors;

    unsigned dprogress_save = Module::dprogress;

    parent = sc->parent;
    type = type->semantic(loc, sc);
    handle = type;
    protection = sc->protection;
    alignment = sc->structalign;
    storage_class |= sc->stc;
    if (sc->stc & STCdeprecated)
        isdeprecated = true;
    assert(!isAnonymous());
    if (sc->stc & STCabstract)
        error("structs, unions cannot be abstract");
    userAttributes = sc->userAttributes;

    if (sizeok == SIZEOKnone)            // if not already done the addMember step
    {
        for (size_t i = 0; i < members->dim; i++)
        {
            Dsymbol *s = (*members)[i];
            //printf("adding member '%s' to '%s'\n", s->toChars(), this->toChars());
            s->addMember(sc, this, 1);
        }
    }

    sizeok = SIZEOKnone;
    sc2 = sc->push(this);
    sc2->stc &= STCsafe | STCtrusted | STCsystem;
    sc2->parent = this;
    if (isUnionDeclaration())
        sc2->inunion = 1;
    sc2->protection = PROTpublic;
    sc2->explicitProtection = 0;
    sc2->structalign = STRUCTALIGN_DEFAULT;
    sc2->userAttributes = NULL;

    /* Set scope so if there are forward references, we still might be able to
     * resolve individual members like enums.
     */
    for (size_t i = 0; i < members->dim; i++)
    {   Dsymbol *s = (*members)[i];
        /* There are problems doing this in the general case because
         * Scope keeps track of things like 'offset'
         */
        //if (s->isEnumDeclaration() || (s->isAggregateDeclaration() && s->ident))
        {
            //printf("struct: setScope %s %s\n", s->kind(), s->toChars());
            s->setScope(sc2);
        }
    }

    for (size_t i = 0; i < members->dim; i++)
    {
        Dsymbol *s = (*members)[i];

        /* If this is the last member, see if we can finish setting the size.
         * This could be much better - finish setting the size after the last
         * field was processed. The problem is the chicken-and-egg determination
         * of when that is. See Bugzilla 7426 for more info.
         */
        if (i + 1 == members->dim)
        {
            if (sizeok == SIZEOKnone && s->isAliasDeclaration())
                finalizeSize(sc2);
        }
        // Ungag errors when not speculative
        unsigned oldgag = global.gag;
        if (global.isSpeculativeGagging() && !isSpeculative())
        {
            global.gag = 0;
        }
        s->semantic(sc2);
        global.gag = oldgag;
    }
    finalizeSize(sc2);

    if (sizeok == SIZEOKfwd)
    {   // semantic() failed because of forward references.
        // Unwind what we did, and defer it for later
        for (size_t i = 0; i < fields.dim; i++)
        {   Dsymbol *s = fields[i];
            VarDeclaration *vd = s->isVarDeclaration();
            if (vd)
                vd->offset = 0;
        }
        fields.setDim(0);
        structsize = 0;
        alignsize = 0;
//        structalign = 0;

        scope = scx ? scx : new Scope(*sc);
        scope->setNoFree();
        scope->module->addDeferredSemantic(this);

        Module::dprogress = dprogress_save;
        //printf("\tdeferring %s\n", toChars());
        return;
    }

    Module::dprogress++;

    //printf("-StructDeclaration::semantic(this=%p, '%s')\n", this, toChars());

    // Determine if struct is all zeros or not
    zeroInit = 1;
    for (size_t i = 0; i < fields.dim; i++)
    {
        Dsymbol *s = fields[i];
        VarDeclaration *vd = s->isVarDeclaration();
        if (vd && !vd->isDataseg())
        {
            if (vd->init)
            {
                // Should examine init to see if it is really all 0's
                zeroInit = 0;
                break;
            }
            else
            {
                if (!vd->type->isZeroInit(loc))
                {
                    zeroInit = 0;
                    break;
                }
            }
        }
    }

#if DMDV1
    /* This doesn't work for DMDV2 because (ref S) and (S) parameter
     * lists will overload the same.
     */
    /* The TypeInfo_Struct is expecting an opEquals and opCmp with
     * a parameter that is a pointer to the struct. But if there
     * isn't one, but is an opEquals or opCmp with a value, write
     * another that is a shell around the value:
     *  int opCmp(struct *p) { return opCmp(*p); }
     */

    TypeFunction *tfeqptr;
    {
        Parameters *arguments = new Parameters;
        Parameter *arg = new Parameter(STCin, handle, Id::p, NULL);

        arguments->push(arg);
        tfeqptr = new TypeFunction(arguments, Type::tint32, 0, LINKd);
        tfeqptr = (TypeFunction *)tfeqptr->semantic(Loc(), sc);
    }

    TypeFunction *tfeq;
    {
        Parameters *arguments = new Parameters;
        Parameter *arg = new Parameter(STCin, type, NULL, NULL);

        arguments->push(arg);
        tfeq = new TypeFunction(arguments, Type::tint32, 0, LINKd);
        tfeq = (TypeFunction *)tfeq->semantic(Loc(), sc);
    }

    Identifier *id = Id::eq;
    for (int i = 0; i < 2; i++)
    {
        Dsymbol *s = search_function(this, id);
        FuncDeclaration *fdx = s ? s->isFuncDeclaration() : NULL;
        if (fdx)
        {   FuncDeclaration *fd = fdx->overloadExactMatch(tfeqptr);
            if (!fd)
            {   fd = fdx->overloadExactMatch(tfeq);
                if (fd)
                {   // Create the thunk, fdptr
                    FuncDeclaration *fdptr = new FuncDeclaration(loc, loc, fdx->ident, STCundefined, tfeqptr);
                    Expression *e = new IdentifierExp(loc, Id::p);
                    e = new PtrExp(loc, e);
                    Expressions *args = new Expressions();
                    args->push(e);
                    e = new IdentifierExp(loc, id);
                    e = new CallExp(loc, e, args);
                    fdptr->fbody = new ReturnStatement(loc, e);
                    ScopeDsymbol *s = fdx->parent->isScopeDsymbol();
                    assert(s);
                    s->members->push(fdptr);
                    fdptr->addMember(sc, s, 1);
                    fdptr->semantic(sc2);
                }
            }
        }

        id = Id::cmp;
    }
#endif
#if DMDV2
    dtor = buildDtor(sc2);
    postblit = buildPostBlit(sc2);
    cpctor = buildCpCtor(sc2);

    buildOpAssign(sc2);
    buildOpEquals(sc2);
#endif
    inv = buildInv(sc2);

    sc2->pop();

    /* Look for special member functions.
     */
#if DMDV2
    ctor = search(Loc(), Id::ctor, 0);
#endif
    aggNew =       (NewDeclaration *)search(Loc(), Id::classNew,       0);
    aggDelete = (DeleteDeclaration *)search(Loc(), Id::classDelete,    0);

    TypeTuple *tup = type->toArgTypes();
    size_t dim = tup->arguments->dim;
    if (dim >= 1)
    {   assert(dim <= 2);
        arg1type = (*tup->arguments)[0]->type;
        if (dim == 2)
            arg2type = (*tup->arguments)[1]->type;
    }

    if (sc->func)
    {
        semantic2(sc);
        semantic3(sc);
    }

    if (global.errors != errors)
    {   // The type is no good.
        type = Type::terror;
    }

    if (deferred && !global.gag)
    {
        deferred->semantic2(sc);
        deferred->semantic3(sc);
    }

#if 0
    if (type->ty == Tstruct && ((TypeStruct *)type)->sym != this)
    {
        printf("this = %p %s\n", this, this->toChars());
        printf("type = %d sym = %p\n", type->ty, ((TypeStruct *)type)->sym);
    }
#endif
    assert(type->ty != Tstruct || ((TypeStruct *)type)->sym == this);
}
Exemple #6
0
int main(int argInN, char* argIn[]) {
   
    time(&g_statsAll.timeStart);
   
    Parameters *P = new Parameters; //all parameters
       
    P->inputParameters(argInN, argIn);
    
    *(P->inOut->logStdOut) << timeMonthDayTime(g_statsAll.timeStart) << " ..... Started STAR run\n" <<flush;           
    
    //generate genome
    if (P->runMode=="genomeGenerate") {
        genomeGenerate(P);
        (void) sysRemoveDir (P->outFileTmp);        
        P->inOut->logMain << "DONE: Genome generation, EXITING\n" << flush;
        exit(0);
    } else if (P->runMode!="alignReads") {
        P->inOut->logMain << "EXITING because of INPUT ERROR: unknown value of input parameter runMode=" <<P->runMode<<endl<<flush;
        exit(1);
    };
    
    Genome mainGenome (P);
    mainGenome.genomeLoad();
    if (P->genomeLoad=="LoadAndExit" || P->genomeLoad=="Remove") 
    {
        return 0;
    };
    
    P->twoPass.pass2=false; //this is the 1st pass    
    
    SjdbClass sjdbLoci;

    if (P->sjdbInsert.pass1) 
    {
        Parameters *P1=new Parameters;
        *P1=*P;
        sjdbInsertJunctions(P, P1, mainGenome, sjdbLoci);
    };

    //calculate genome-related parameters
    Transcriptome *mainTranscriptome=NULL;
    
    
/////////////////////////////////////////////////////////////////////////////////////////////////START
    if (P->runThreadN>1) {
        g_threadChunks.threadArray=new pthread_t[P->runThreadN];
        pthread_mutex_init(&g_threadChunks.mutexInRead, NULL);
        pthread_mutex_init(&g_threadChunks.mutexOutSAM, NULL);
        pthread_mutex_init(&g_threadChunks.mutexOutBAM1, NULL);
        pthread_mutex_init(&g_threadChunks.mutexOutUnmappedFastx, NULL);
        pthread_mutex_init(&g_threadChunks.mutexOutFilterBySJout, NULL);
        pthread_mutex_init(&g_threadChunks.mutexStats, NULL);
        pthread_mutex_init(&g_threadChunks.mutexBAMsortBins, NULL);
    };

    g_statsAll.progressReportHeader(P->inOut->logProgress);    
    
    if (P->twoPass.yes) {//2-pass
        //re-define P for the pass1
        
        Parameters *P1=new Parameters;
        *P1=*P;
        //turn off unnecessary calculations
        P1->outSAMtype[0]="None";
        P1->outSAMbool=false;
        P1->outBAMunsorted=false;
        P1->outBAMcoord=false;
    
        P1->chimSegmentMin=0;
        
        P1->quant.yes=false;
        P1->quant.trSAM.yes=false;
        P1->quant.geCount.yes=false;
        
        P1->outFilterBySJoutStage=0;
        
        P1->outReadsUnmapped="None";
        
        P1->outFileNamePrefix=P->twoPass.dir;

        P1->readMapNumber=P->twoPass.pass1readsN;
//         P1->inOut->logMain.open((P1->outFileNamePrefix + "Log.out").c_str());

        g_statsAll.resetN();
        time(&g_statsAll.timeStartMap);
        P->inOut->logProgress << timeMonthDayTime(g_statsAll.timeStartMap) <<"\tStarted 1st pass mapping\n" <<flush;
        *P->inOut->logStdOut << timeMonthDayTime(g_statsAll.timeStartMap) << " ..... Started 1st pass mapping\n" <<flush;

        //run mapping for Pass1
        ReadAlignChunk *RAchunk1[P->runThreadN];        
        for (int ii=0;ii<P1->runThreadN;ii++) {
            RAchunk1[ii]=new ReadAlignChunk(P1, mainGenome, mainTranscriptome, ii);
        };    
        mapThreadsSpawn(P1, RAchunk1);
        outputSJ(RAchunk1,P1); //collapse and output junctions
//         for (int ii=0;ii<P1->runThreadN;ii++) {
//             delete [] RAchunk[ii];
//         };          
        
        time_t rawtime; time (&rawtime);
        P->inOut->logProgress << timeMonthDayTime(rawtime) <<"\tFinished 1st pass mapping\n";
        *P->inOut->logStdOut << timeMonthDayTime(rawtime) << " ..... Finished 1st pass mapping\n" <<flush;
        ofstream logFinal1 ( (P->twoPass.dir + "/Log.final.out").c_str());
        g_statsAll.reportFinal(logFinal1,P1);

        P->twoPass.pass2=true;//starting the 2nd pass
        P->twoPass.pass1sjFile=P->twoPass.dir+"/SJ.out.tab";
        
        sjdbInsertJunctions(P, P1, mainGenome, sjdbLoci);

        //reopen reads files
        P->closeReadsFiles();
        P->openReadsFiles();
    } else {//not 2-pass
        //nothing for now
    };
    
    if ( P->quant.yes ) {//load transcriptome
        mainTranscriptome=new Transcriptome(P);
    };    
    
    //initialize Stats
    g_statsAll.resetN();
    time(&g_statsAll.timeStartMap);
    *P->inOut->logStdOut << timeMonthDayTime(g_statsAll.timeStartMap) << " ..... Started mapping\n" <<flush;
    
    g_statsAll.timeLastReport=g_statsAll.timeStartMap;

    //open SAM/BAM files for output
    if (P->outSAMmode != "None") {//open SAM file and write header
        ostringstream samHeaderStream;
        
        for (uint ii=0;ii<P->nChrReal;ii++) {
            samHeaderStream << "@SQ\tSN:"<< P->chrName.at(ii) <<"\tLN:"<<P->chrLength[ii]<<"\n";
        };

        if (P->outSAMheaderPG.at(0)!="-") {
            samHeaderStream << P->outSAMheaderPG.at(0);
            for (uint ii=1;ii<P->outSAMheaderPG.size(); ii++) {
                samHeaderStream << "\t" << P->outSAMheaderPG.at(ii);
            };
            samHeaderStream << "\n";
        };        
        
        samHeaderStream << "@PG\tID:STAR\tPN:STAR\tVN:" << STAR_VERSION <<"\tCL:" << P->commandLineFull <<"\n";
        
        if (P->outSAMheaderCommentFile!="-") {
            ifstream comstream (P->outSAMheaderCommentFile);
            while (comstream.good()) {
                string line1;
                getline(comstream,line1);
                if (line1.find_first_not_of(" \t\n\v\f\r")!=std::string::npos) {//skip blank lines
                    samHeaderStream << line1 <<"\n";
                };
            };
        };         
        

        for (uint32 ii=0;ii<P->outSAMattrRGlineSplit.size();ii++) {//@RG lines
            samHeaderStream << "@RG\t" << P->outSAMattrRGlineSplit.at(ii) <<"\n";
        };
 
        samHeaderStream <<  "@CO\t" <<"user command line: " << P->commandLine <<"\n";
        
        if (P->outSAMheaderHD.at(0)!="-") {
            P->samHeaderHD = P->outSAMheaderHD.at(0);
            for (uint ii=1;ii<P->outSAMheaderHD.size(); ii++) {
                P->samHeaderHD +="\t" + P->outSAMheaderHD.at(ii);
            };
        } else {
            P->samHeaderHD = "@HD\tVN:1.4";
        };        
        
        
        P->samHeader=P->samHeaderHD+"\n"+samHeaderStream.str();
        //for the sorted BAM, need to add SO:cooridnate to the header line
        P->samHeaderSortedCoord=P->samHeaderHD + (P->outSAMheaderHD.size()==0 ? "" : "\tSO:coordinate") + "\n" + samHeaderStream.str();
        
        if (P->outSAMbool) {//
            *P->inOut->outSAM << P->samHeader;
        };
        if (P->outBAMunsorted){
            outBAMwriteHeader(P->inOut->outBAMfileUnsorted,P->samHeader,P->chrName,P->chrLength);
        };
//             if (P->outBAMcoord){
//                 outBAMwriteHeader(P->inOut->outBAMfileCoord,P->samHeader,P->chrName,P->chrLength);            
//             };
        
        if ( P->quant.trSAM.yes ) {
            samHeaderStream.str("");
            vector <uint> trlength;
            for (uint32 ii=0;ii<mainTranscriptome->trID.size();ii++) {
                uint32 iex1=mainTranscriptome->trExI[ii]+mainTranscriptome->trExN[ii]-1; //last exon of the transcript
                trlength.push_back(mainTranscriptome->exLenCum[iex1]+mainTranscriptome->exSE[2*iex1+1]-mainTranscriptome->exSE[2*iex1]+1);          
                samHeaderStream << "@SQ\tSN:"<< mainTranscriptome->trID.at(ii) <<"\tLN:"<<trlength.back()<<"\n";
            };
            for (uint32 ii=0;ii<P->outSAMattrRGlineSplit.size();ii++) {//@RG lines
                samHeaderStream << "@RG\t" << P->outSAMattrRGlineSplit.at(ii) <<"\n";
            };
            outBAMwriteHeader(P->inOut->outQuantBAMfile,samHeaderStream.str(),mainTranscriptome->trID,trlength);        
        };
        
    };
    
    if (P->chimSegmentMin>0) {
        P->inOut->outChimJunction.open((P->outFileNamePrefix + "Chimeric.out.junction").c_str());
        P->inOut->outChimSAM.open((P->outFileNamePrefix + "Chimeric.out.sam").c_str());
        P->inOut->outChimSAM << P->samHeader;
        pthread_mutex_init(&g_threadChunks.mutexOutChimSAM, NULL);   
        pthread_mutex_init(&g_threadChunks.mutexOutChimJunction, NULL);
    };
         
    // P->inOut->logMain << "mlock value="<<mlockall(MCL_CURRENT|MCL_FUTURE) <<"\n"<<flush;

    // prepare chunks and spawn mapping threads    
    ReadAlignChunk *RAchunk[P->runThreadN];
    for (int ii=0;ii<P->runThreadN;ii++) {
        RAchunk[ii]=new ReadAlignChunk(P, mainGenome, mainTranscriptome, ii);
    };    
    
    mapThreadsSpawn(P, RAchunk);
   
    if (P->outFilterBySJoutStage==1) {//completed stage 1, go to stage 2
        P->inOut->logMain << "Completed stage 1 mapping of outFilterBySJout mapping\n"<<flush;
        outputSJ(RAchunk,P);//collapse novel junctions
        P->readFilesIndex=-1;
        

        P->outFilterBySJoutStage=2;
        if (P->outBAMcoord) {
            for (int it=0; it<P->runThreadN; it++) {//prepare the unmapped bin 
                RAchunk[it]->chunkOutBAMcoord->coordUnmappedPrepareBySJout();
            };
        };

        mapThreadsSpawn(P, RAchunk);
    };
    
    //close some BAM files
    if (P->inOut->outBAMfileUnsorted!=NULL) {
        bgzf_flush(P->inOut->outBAMfileUnsorted);
        bgzf_close(P->inOut->outBAMfileUnsorted);
    };
    if (P->inOut->outQuantBAMfile!=NULL) {
        bgzf_flush(P->inOut->outQuantBAMfile);
        bgzf_close(P->inOut->outQuantBAMfile);
    };      
    
    if (P->outBAMcoord && P->limitBAMsortRAM==0) {//make it equal ot the genome size
        P->limitBAMsortRAM=P->nGenome+mainGenome.SA.lengthByte+mainGenome.SAi.lengthByte;
    };
        
    //no need for genome anymore, free the memory
    mainGenome.freeMemory();
    
    if ( P->quant.geCount.yes )
    {//output gene quantifications
        for (int ichunk=1; ichunk<P->runThreadN; ichunk++)
        {//sum counts from all chunks into 0th chunk
            RAchunk[0]->chunkTr->quants->addQuants(*(RAchunk[ichunk]->chunkTr->quants));
        };
        RAchunk[0]->chunkTr->quantsOutput();
    };
    
    if (P->runThreadN>1 && P->outSAMorder=="PairedKeepInputOrder") {//concatenate Aligned.* files
        RAchunk[0]->chunkFilesCat(P->inOut->outSAM, P->outFileTmp + "/Aligned.out.sam.chunk", g_threadChunks.chunkOutN);
    };    

    
    if (P->outBAMcoord) {//sort BAM if needed
        *P->inOut->logStdOut << timeMonthDayTime() << " ..... Started sorting BAM\n" <<flush;
        P->inOut->logMain << timeMonthDayTime() << " ..... Started sorting BAM\n" <<flush;
        uint32 nBins=P->outBAMcoordNbins;
        
        //check max size needed for sorting
        uint maxMem=0;
        for (uint32 ibin=0; ibin<nBins-1; ibin++) {//check akk bins
            uint binS=0;
            for (int it=0; it<P->runThreadN; it++) {//collect sizes from threads
                binS += RAchunk[it]->chunkOutBAMcoord->binTotalBytes[ibin]+24*RAchunk[it]->chunkOutBAMcoord->binTotalN[ibin];
            };        
            if (binS>maxMem) maxMem=binS;
        };
        P->inOut->logMain << "Max memory needed for sorting = "<<maxMem<<endl;
        if (maxMem>P->limitBAMsortRAM) {
            ostringstream errOut;
            errOut <<"EXITING because of fatal ERROR: not enough memory for BAM sorting: \n";
            errOut <<"SOLUTION: re-run STAR with at least --limitBAMsortRAM " <<maxMem+1000000000;
            exitWithError(errOut.str(), std::cerr, P->inOut->logMain, EXIT_CODE_PARAMETER, *P);                                    
        };
        
        
        uint totalMem=0;
//         P->inOut->logMain << "Started sorting BAM ..." <<endl;
        #pragma omp parallel num_threads(P->outBAMsortingThreadNactual) 
        #pragma omp for schedule (dynamic,1)
        for (uint32 ibin1=0; ibin1<nBins; ibin1++) {
            uint32 ibin=nBins-1-ibin1;//reverse order to start with the last bin - unmapped reads
            
            uint binN=0, binS=0;
            for (int it=0; it<P->runThreadN; it++) {//collect sizes from threads
                binN += RAchunk[it]->chunkOutBAMcoord->binTotalN[ibin];
                binS += RAchunk[it]->chunkOutBAMcoord->binTotalBytes[ibin];
            };
            
            if (binS==0) continue; //empty bin
  
            if (ibin == nBins-1) {//last bin for unmapped reads
                BAMbinSortUnmapped(ibin,P->runThreadN,P->outBAMsortTmpDir,P->inOut->outBAMfileCoord, P);
            } else {
            uint newMem=binS+binN*24;
            bool boolWait=true;
            while (boolWait) {
                #pragma omp critical
                if (totalMem+newMem < P->limitBAMsortRAM) {
                    boolWait=false;
                    totalMem+=newMem;
                };
                sleep(0.1);
            };
            BAMbinSortByCoordinate(ibin,binN,binS,P->runThreadN,P->outBAMsortTmpDir,P->inOut->outBAMfileCoord, P);
            #pragma omp critical
            totalMem-=newMem;//"release" RAM
        };
        };
        //concatenate all BAM files, using bam_cat
        char **bamBinNames = new char* [nBins];
        vector <string> bamBinNamesV;
        for (uint32 ibin=0; ibin<nBins; ibin++) {
            
            bamBinNamesV.push_back(P->outBAMsortTmpDir+"/b"+to_string((uint) ibin));            
            struct stat buffer;
            if (stat (bamBinNamesV.back().c_str(), &buffer) != 0) {//check if file exists
                bamBinNamesV.pop_back();
            };
        };
        for (uint32 ibin=0; ibin<bamBinNamesV.size(); ibin++) {
                bamBinNames[ibin] = (char*) bamBinNamesV.at(ibin).c_str();
        };
        bam_cat(bamBinNamesV.size(), bamBinNames, 0, P->outBAMfileCoordName.c_str());
    };
    //wiggle output
    if (P->outWigFlags.yes) {
        *P->inOut->logStdOut << timeMonthDayTime() << " ..... Started wiggle output\n" <<flush;
        P->inOut->logMain << timeMonthDayTime() << " ..... Started wiggle output\n" <<flush;
        string wigOutFileNamePrefix=P->outFileNamePrefix + "Signal";
        signalFromBAM(P->outBAMfileCoordName, wigOutFileNamePrefix, *P);
    };
    
    //aggregate output junctions
    //collapse splice junctions from different threads/chunks, and output them
    outputSJ(RAchunk,P);
    
    g_statsAll.progressReport(P->inOut->logProgress);
    P->inOut->logProgress  << "ALL DONE!\n"<<flush;
    P->inOut->logFinal.open((P->outFileNamePrefix + "Log.final.out").c_str());
    g_statsAll.reportFinal(P->inOut->logFinal,P);
    *P->inOut->logStdOut << timeMonthDayTime(g_statsAll.timeFinish) << " ..... Finished successfully\n" <<flush;
    
    P->inOut->logMain  << "ALL DONE!\n"<<flush;
    sysRemoveDir (P->outFileTmp);
    
    P->closeReadsFiles();//this will kill the readFilesCommand processes if necessary
    mainGenome.~Genome(); //need explicit call because of the 'delete P->inOut' below, which will destroy P->inOut->logStdOut
    
    delete P->inOut; //to close files
    delete P;
    
    return 0;    
};
Exemple #7
0
FuncDeclaration *buildOpAssign(StructDeclaration *sd, Scope *sc)
{
    if (FuncDeclaration *f = hasIdentityOpAssign(sd, sc))
    {
        sd->hasIdentityAssign = true;
        return f;
    }
    // Even if non-identity opAssign is defined, built-in identity opAssign
    // will be defined.

    if (!needOpAssign(sd))
        return NULL;

    //printf("StructDeclaration::buildOpAssign() %s\n", toChars());
    StorageClass stc = STCsafe | STCnothrow | STCpure | STCnogc;
    Loc declLoc = sd->loc;
    Loc loc = Loc();    // internal code should have no loc to prevent coverage

    if (sd->dtor || sd->postblit)
    {
        if (!sd->type->isAssignable())  // Bugzilla 13044
            return NULL;
        if (sd->dtor)
        {
            stc = mergeFuncAttrs(stc, sd->dtor);
            if (stc & STCsafe)
                stc = (stc & ~STCsafe) | STCtrusted;
        }
    }
    else
    {
        for (size_t i = 0; i < sd->fields.dim; i++)
        {
            VarDeclaration *v = sd->fields[i];
            if (v->storage_class & STCref)
                continue;
            Type *tv = v->type->baseElemOf();
            if (tv->ty == Tstruct)
            {
                TypeStruct *ts = (TypeStruct *)tv;
                if (FuncDeclaration *f = hasIdentityOpAssign(ts->sym, sc))
                    stc = mergeFuncAttrs(stc, f);
            }
        }
    }

    Parameters *fparams = new Parameters;
    fparams->push(new Parameter(STCnodtor, sd->type, Id::p, NULL));
    Type *tf = new TypeFunction(fparams, sd->handleType(), 0, LINKd, stc | STCref);

    FuncDeclaration *fop = new FuncDeclaration(declLoc, Loc(), Id::assign, stc, tf);

    Expression *e = NULL;
    if (stc & STCdisable)
    {
    }
    else if (sd->dtor || sd->postblit)
    {
        /* Do swap this and rhs
         *    tmp = this; this = s; tmp.dtor();
         */
        //printf("\tswap copy\n");
        Identifier *idtmp = Lexer::uniqueId("__tmp");
        VarDeclaration *tmp = NULL;
        AssignExp *ec = NULL;
        if (sd->dtor)
        {
            tmp = new VarDeclaration(loc, sd->type, idtmp, new VoidInitializer(loc));
            tmp->noscope = 1;
            tmp->storage_class |= STCtemp | STCctfe;
            e = new DeclarationExp(loc, tmp);
            ec = new BlitExp(loc, new VarExp(loc, tmp), new ThisExp(loc));
            e = Expression::combine(e, ec);
        }
        ec = new BlitExp(loc, new ThisExp(loc), new IdentifierExp(loc, Id::p));
        e = Expression::combine(e, ec);
        if (sd->dtor)
        {
            /* Instead of running the destructor on s, run it
             * on tmp. This avoids needing to copy tmp back in to s.
             */
            Expression *ec2 = new DotVarExp(loc, new VarExp(loc, tmp), sd->dtor, 0);
            ec2 = new CallExp(loc, ec2);
            e = Expression::combine(e, ec2);
        }
    }
    else
    {
        /* Do memberwise copy
         */
        //printf("\tmemberwise copy\n");
        for (size_t i = 0; i < sd->fields.dim; i++)
        {
            VarDeclaration *v = sd->fields[i];
            // this.v = s.v;
            AssignExp *ec = new AssignExp(loc,
                new DotVarExp(loc, new ThisExp(loc), v, 0),
                new DotVarExp(loc, new IdentifierExp(loc, Id::p), v, 0));
            e = Expression::combine(e, ec);
        }
    }
    if (e)
    {
        Statement *s1 = new ExpStatement(loc, e);

        /* Add:
         *   return this;
         */
        e = new ThisExp(loc);
        Statement *s2 = new ReturnStatement(loc, e);

        fop->fbody = new CompoundStatement(loc, s1, s2);
    }

    sd->members->push(fop);
    fop->addMember(sc, sd, 1);
    sd->hasIdentityAssign = true;        // temporary mark identity assignable

    unsigned errors = global.startGagging();    // Do not report errors, even if the
    Scope *sc2 = sc->push();
    sc2->stc = 0;
    sc2->linkage = LINKd;

    fop->semantic(sc2);
    fop->semantic2(sc2);
    fop->semantic3(sc2);

    sc2->pop();
    if (global.endGagging(errors))    // if errors happened
    {
        // Disable generated opAssign, because some members forbid identity assignment.
        fop->storage_class |= STCdisable;
        fop->fbody = NULL;  // remove fbody which contains the error
    }

    //printf("-StructDeclaration::buildOpAssign() %s, errors = %d\n", sd->toChars(), (fop->storage_class & STCdisable) != 0);

    return fop;
}
Exemple #8
0
FuncDeclaration *StructDeclaration::buildOpAssign(Scope *sc)
{
    if (!needOpAssign())
        return NULL;

    //printf("StructDeclaration::buildOpAssign() %s\n", toChars());

    FuncDeclaration *fop = NULL;

    Parameter *param = new Parameter(STCnodtor, type, Id::p, NULL);
    Parameters *fparams = new Parameters;
    fparams->push(param);
    Type *ftype = new TypeFunction(fparams, handle, FALSE, LINKd);
#if STRUCTTHISREF
    ((TypeFunction *)ftype)->isref = 1;
#endif

    fop = new FuncDeclaration(loc, 0, Id::assign, STCundefined, ftype);

    Expression *e = NULL;
    if (postblit)
    {   /* Swap:
         *    tmp = *this; *this = s; tmp.dtor();
         */
        //printf("\tswap copy\n");
        Identifier *idtmp = Lexer::uniqueId("__tmp");
        VarDeclaration *tmp;
        AssignExp *ec = NULL;
        if (dtor)
        {
            tmp = new VarDeclaration(0, type, idtmp, new VoidInitializer(0));
            tmp->noscope = 1;
            tmp->storage_class |= STCctfe;
            e = new DeclarationExp(0, tmp);
            ec = new AssignExp(0,
                new VarExp(0, tmp),
#if STRUCTTHISREF
                new ThisExp(0)
#else
                new PtrExp(0, new ThisExp(0))
#endif
                );
            ec->op = TOKblit;
            e = Expression::combine(e, ec);
        }
        ec = new AssignExp(0,
#if STRUCTTHISREF
                new ThisExp(0),
#else
                new PtrExp(0, new ThisExp(0)),
#endif
                new IdentifierExp(0, Id::p));
        ec->op = TOKblit;
        e = Expression::combine(e, ec);
        if (dtor)
        {
            /* Instead of running the destructor on s, run it
             * on tmp. This avoids needing to copy tmp back in to s.
             */
            Expression *ec = new DotVarExp(0, new VarExp(0, tmp), dtor, 0);
            ec = new CallExp(0, ec);
            e = Expression::combine(e, ec);
        }
    }
    else
    {   /* Do memberwise copy
         */
        //printf("\tmemberwise copy\n");
        for (size_t i = 0; i < fields.dim; i++)
        {
            Dsymbol *s = fields.tdata()[i];
            VarDeclaration *v = s->isVarDeclaration();
            assert(v && v->storage_class & STCfield);
            // this.v = s.v;
            AssignExp *ec = new AssignExp(0,
                new DotVarExp(0, new ThisExp(0), v, 0),
                new DotVarExp(0, new IdentifierExp(0, Id::p), v, 0));
            ec->op = TOKblit;
            e = Expression::combine(e, ec);
        }
    }
    Statement *s1 = new ExpStatement(0, e);

    /* Add:
     *   return this;
     */
    e = new ThisExp(0);
    Statement *s2 = new ReturnStatement(0, e);

    fop->fbody = new CompoundStatement(0, s1, s2);

    members->push(fop);
    fop->addMember(sc, this, 1);

    sc = sc->push();
    sc->stc = 0;
    sc->linkage = LINKd;

    fop->semantic(sc);

    sc->pop();

    //printf("-StructDeclaration::buildOpAssign() %s\n", toChars());

    return fop;
}
Exemple #9
0
FuncDeclaration *StructDeclaration::buildOpEquals(Scope *sc)
{
    if (!needOpEquals())
        return NULL;
    //printf("StructDeclaration::buildOpEquals() %s\n", toChars());
    Loc loc = this->loc;

    Parameters *parameters = new Parameters;
#if STRUCTTHISREF
    // bool opEquals(ref const T) const;
    Parameter *param = new Parameter(STCref, type->constOf(), Id::p, NULL);
#else
    // bool opEquals(const T*) const;
    Parameter *param = new Parameter(STCin, type->pointerTo(), Id::p, NULL);
#endif

    parameters->push(param);
    TypeFunction *ftype = new TypeFunction(parameters, Type::tbool, 0, LINKd);
    ftype->mod = MODconst;
    ftype = (TypeFunction *)ftype->semantic(loc, sc);

    FuncDeclaration *fop = new FuncDeclaration(loc, 0, Id::eq, STCundefined, ftype);

    Expression *e = NULL;
    /* Do memberwise compare
     */
    //printf("\tmemberwise compare\n");
    for (size_t i = 0; i < fields.dim; i++)
    {
        Dsymbol *s = fields.tdata()[i];
        VarDeclaration *v = s->isVarDeclaration();
        assert(v && v->storage_class & STCfield);
        if (v->storage_class & STCref)
            assert(0);                  // what should we do with this?
        // this.v == s.v;
        EqualExp *ec = new EqualExp(TOKequal, loc,
            new DotVarExp(loc, new ThisExp(loc), v, 0),
            new DotVarExp(loc, new IdentifierExp(loc, Id::p), v, 0));
        if (e)
            e = new AndAndExp(loc, e, ec);
        else
            e = ec;
    }
    if (!e)
        e = new IntegerExp(loc, 1, Type::tbool);
    fop->fbody = new ReturnStatement(loc, e);

    members->push(fop);
    fop->addMember(sc, this, 1);

    sc = sc->push();
    sc->stc = 0;
    sc->linkage = LINKd;

    fop->semantic(sc);

    sc->pop();

    //printf("-StructDeclaration::buildOpEquals() %s\n", toChars());

    return fop;
}
void CppParticleSimulator::updateSimulation(const Parameters &params, float dt_seconds) {

    // Set forces to 0 and calculate densities
    for (int i = 0; i < positions.size(); ++i) {
        forces[i] = {0, 0, 0};
        float density = 0;

        for (int j = 0; j < positions.size(); ++j) {
            glm::vec3 relativePos = positions[i] - positions[j];
            density += params.get_particle_mass() * Wpoly6(relativePos, params.kernel_size);
        }

        densities[i] = density;
    }

    // Calculate forces
    for (int i = 0; i < positions.size(); ++i) {
        float iPressure = (densities[i] - params.rest_density) * params.k_gas;
        float cs = 0;
        glm::vec3 n = {0, 0, 0};
        float laplacianCs = 0;

        glm::vec3 pressureForce = {0, 0, 0};
        glm::vec3 viscosityForce = {0, 0, 0};

        for (int j = 0; j < positions.size(); ++j) {
            glm::vec3 relativePos = positions[i] - positions[j];

            // Particle j's pressure force on i
            float jPressure = (densities[j] - params.rest_density) * params.k_gas;
            pressureForce = pressureForce - params.get_particle_mass() *
                ((iPressure + jPressure) / (2 * densities[j])) *
                gradWspiky(relativePos, params.kernel_size);

            // Particle j's viscosity force in i
            viscosityForce += params.k_viscosity *
                params.get_particle_mass() * ((velocities[j] - velocities[i]) / densities[j]) *
                laplacianWviscosity(relativePos, params.kernel_size);

            // cs for particle j
            cs += params.get_particle_mass() * (1 / densities[j]) * Wpoly6(relativePos, params.kernel_size);

            // Gradient of cs for particle j
            n += params.get_particle_mass() * (1 / densities[j]) * gradWpoly6(relativePos, params.kernel_size);

            // Laplacian of cs for particle j
            laplacianCs += params.get_particle_mass() * (1 /densities[j]) * laplacianWpoly6(relativePos, params.kernel_size);
        }

        glm::vec3 tensionForce;

        if (glm::length(n) < params.k_threshold) {
            tensionForce = {0, 0, 0};
        } else {
            tensionForce = params.sigma * (- laplacianCs / glm::length(n)) * n;
        }

        //glm::vec3 n = {0, 0, 0};
        glm::vec3 boundaryForce = {0, 0, 0};
        boundaryForce = calculateBoundaryForceGlass(params, i);

        // Add external forces on i
        forces[i] = pressureForce + viscosityForce + tensionForce + params.gravity + boundaryForce;

        // Euler time step
        velocities[i] += (forces[i] / densities[i]) * dt_seconds;
        positions[i] += velocities[i] * dt_seconds;

    }

    checkBoundariesGlass(params);

    glBindBuffer (GL_ARRAY_BUFFER, vbo_pos);
    glBufferData (GL_ARRAY_BUFFER, positions.size() * 3 * sizeof (float), positions.data(), GL_STATIC_DRAW);
}
Exemple #11
0
int PLL::Events (realtype t, N_Vector X, realtype * event, void * data) {
#ifndef WITHPHIERR
  realtype x, y, r, w;
  Parameters * parameters = (Parameters *) data;
  
  x = Ith (X, 0);
  y = Ith (X, 1);
  r = Ith (X, 2);
  w = Ith (X, 3);
  
  fREF = parameters->At(0);
  T = 1.0/fREF;
  R1 = parameters->At(1);
  omega0 = 2*pi*parameters->At(2);
  Vdd = parameters->At(3);
  rho0 = parameters->At(4);
  rhoap = parameters->At(5);
  k0 = parameters->At(6);
  Krho = parameters->At(7);
  Kap = parameters->At(8);
  alpha = parameters->At(9);
  KVCOa = parameters->At(10);
  KVCOb = parameters->At(11);
  KVCOc = parameters->At(12);
  tuning_coeff = parameters->At(13);
  
  // rising edge of the clock
  event[0] = t - n*T;
  // extrema of x
  realtype gamma = sqrt(x*x+y*y);
  realtype vtune = w/tuning_coeff;
  event[1] = ((rho0+Krho*vtune)/gamma - 1)*k0*x - ((1-alpha)*Kap*(gamma-rhoap) + 1 + alpha*vtune*(KVCOa + KVCOb*vtune + KVCOc*vtune*vtune))*omega0*y;
  // reset
  event[2] = t - (treset+tau_d+dt);
#endif
  return CV_SUCCESS;
}
Exemple #12
0
void	Room::setParameters(Parameters &params)
{
  _parameter->setDifficulty(params.getDifficulty());
}
Exemple #13
0
// This is the workhorse of the code.
// It takes in the input parameters and an output object, and runs everything from there.
// This modularization is set up so that anybody can call the evolution routines.
//
// Input parameters:
// inifile: the input parameters
// params: class containing cosmological parameters (somewhat degenerate with inifile, but these values won't be read from inifile)
// output: the outputting class
// postprocess: whether or not to perform postprocessing
//
// Return values:
// 0: success
// -1: error in initialization
// 1: Integration error
// 2: NAN error
// 3: Did not get to a = 1 in allotted time
// 4: Model reports invalid state
// 5: Error in postprocessing integration of distance measures
int doEvolution(IniReader& inifile, Parameters& params, Output& output, vector<vector<double> > &SN1adata, bool postprocess) {

    //****************//
    // Initialization //
    //****************//

    // Set up the integrator
    Integrator myIntegrator;

    // Set up the model class
    Model *myModel;
    std::string parsestring = inifile.getiniString("model", "LambdaCDM", "Cosmology");
    if (parsestring == "Quintessence")
        myModel = new Quintessence();
    else if (parsestring == "LinearW")
        myModel = new LinearW();
    else if (parsestring == "Kessence")
        myModel = new Kessence();
    else if (parsestring == "KGB")
        myModel = new KGB();
    else if (parsestring == "Fr")
        myModel = new Fr();
    else
        myModel = new LambdaCDM();    // LambdaCDM is the default

    // Load the model and parameters into a class to pass into the integration routine
    IntParams myIntParams(params, *myModel);

    // Set up the consistency check class
    parsestring = inifile.getiniString("consistencyclass", "None", "Function");
    Consistency *myChecker;
    if (parsestring == "SimpleCheck")
        myChecker = new SimpleCheck();
    else
        myChecker = new Consistency();  // Default option, which has no checking

    // Create vectors for redshift and hubble
    vector<double> redshift;
    vector<double> hubble;

    int result = 0; // For information coming back from functions


    //********************//
    // Initial Conditions //
    //********************//

    // The initial value of a is extracted from the starting redshift
    // The initial values of \phi and \dot{\phi} are read from the input parameters
    double phi0 = inifile.getiniDouble("phi0", 0.0, "Cosmology");
    double phidot0 = inifile.getiniDouble("phidot0", 0.0, "Cosmology");
    double data[4] = { 1.0 / (1.0 + params.z0()), phi0, phidot0, 0.0 };
    // The data array stores a, \phi, \dot{phi} and H through the evolution
    // H is calculated in the initialization of the model

    // Start and end times
    double starttime = inifile.getiniDouble("starttime", 0.0, "Function");
    double endtime = starttime + inifile.getiniDouble("maxtime", 10.0, "Function");

    // Get the output class to write out information on the run
    output.printinfo(data, params);

    // Allow the model to initialize itself
    result = myModel->init(data, starttime, params, inifile, output);
    if (result != 0) {
        delete myChecker;
        delete myModel;
        return -1;
    }

    // Check that the model has an internally consistent state with the initial data (it should have aborted already if so, but be safe)
    if (myModel->isvalidconfig(data) == false) {
        delete myChecker;
        delete myModel;
        return 4;
    }

    // Write the model name to the output log
    output.printvalue("Model", myModel->classname());
    output.printlog(""); // Whitespace for prettiness


    //***********//
    // Evolution //
    //***********//

    // Do the evolution!
    result = BeginEvolution(myIntegrator, myIntParams, data, starttime, endtime, output, *myChecker, hubble, redshift);


    //*********************************//
    // Clean up of Hubble and Redshift //
    //*********************************//

    if (result == 0) { // when the evolution was a success

        // We have H and z starting with high z going to z = 0. We want these reversed.
        reverse(hubble.begin(),hubble.end());
        reverse(redshift.begin(),redshift.end());

        // Update the parameters class with the new hubble value
        params.seth(hubble[0]);

        // Now go and report the actual density fractions and hubble parameter to the logs
        output.printlog("Values from evolution of model are as follows:");
        output.printvalue("modelh", params.geth());
        output.printvalue("modelOmegaR", params.getOmegaR());
        output.printvalue("modelOmegaM", params.getOmegaM());
        output.printvalue("modelOmegaB", params.getOmegaB());
        output.printvalue("modelOmegaK", params.getOmegaK());
        output.printvalue("modelOmegaLambda", 1 - params.getOmegaK() - params.getOmegaR() - params.getOmegaM());
        output.printlog("");

    }


    //*********************************//
    // Post-processing: initialization //
    //*********************************//

    // Construct vectors for distance measures
    int numrows = hubble.size();
    vector<double> DC;
    vector<double> DM;
    vector<double> DA;
    vector<double> DL;
    vector<double> mu;
    // Other distances that are computed
    double rs; // sound horizon at z_CMB
    double rd; // sound horizon at z_drag

    //*******************//
    // Distance measures //
    //*******************//

    if (result == 0 && postprocess) { // when the evolution was a success AND we're doing the postprocessing

        // Get the output class to print any headings for postprocessing
        output.postprintheading();

        // Allocate space for the vectors
        DC.reserve(numrows);
        DM.reserve(numrows);
        DA.reserve(numrows);
        DL.reserve(numrows);
        mu.reserve(numrows);

        // Calculate distance measurements
        result = PostProcessingDist(hubble, redshift, DC, DM, DA, DL, mu, rs, rd, params, output);

        // Flag any errors
        if (result == 1) result = 5;

    }


    //**************//
    // chi^2 values //
    //**************//

    if (result == 0 && postprocess) { // when the distance calculations were a success AND we're doing the postprocessing

        double BAOchi, BAOrchi, WMAPchi, Planckchi, Hubblechi, SNchi;

        // Put in some whitespace!
        output.printlog("");

        // First, do chi^2 of WMAP and Planck distance posteriors
        chi2CMB(redshift, DA, rs, output, params, WMAPchi, Planckchi);

        // Next, do chi^2 of SN1a
        SNchi = chi2SN1a(redshift, mu, output, inifile, SN1adata);

        // Do chi^2 for hubble value
        Hubblechi = chi2hubble(params, inifile.getiniDouble("desiredh", 0.7, "Cosmology"), inifile.getiniDouble("sigmah", 0.03, "Cosmology"), output);

        // Finally, do chi^2 of BAO measurements
        chi2BAO(rd, redshift, hubble, DA, params, output, BAOchi, BAOrchi);

        // Calculate the combination chi^2 from the bitmask
        double combination = 0;
        unsigned int bitmask = params.getbitmask();
        // 1 = SN1a
        // 2 = BAO (using SDSS)
        // 4 = BAO (using SDSSR)
        // 8 = Hubble
        // 16 = WMAP
        // 32 = Planck
        combination += (bitmask & 1) * SNchi;
        combination += ((bitmask & 2) >> 1) * BAOchi;
        combination += ((bitmask & 4) >> 2) * BAOrchi;
        combination += ((bitmask & 8) >> 3) * Hubblechi;
        combination += ((bitmask & 16) >> 4) * WMAPchi;
        combination += ((bitmask & 32) >> 5) * Planckchi;
        output.printvalue("combinationchi", combination);
        output.printvalue("chicombo", (int) bitmask);

    }
Exemple #14
0
FuncDeclaration *StructDeclaration::buildCpCtor(Scope *sc)
{
    //printf("StructDeclaration::buildCpCtor() %s\n", toChars());
    FuncDeclaration *fcp = NULL;

    /* Copy constructor is only necessary if there is a postblit function,
     * otherwise the code generator will just do a bit copy.
     */
    if (postblit)
    {
        //printf("generating cpctor\n");

        StorageClass stc = postblit->storage_class &
                            (STCdisable | STCsafe | STCtrusted | STCsystem | STCpure | STCnothrow);
        if (stc & (STCsafe | STCtrusted))
            stc = stc & ~STCsafe | STCtrusted;

        Parameters *fparams = new Parameters;
        fparams->push(new Parameter(STCref, type->constOf(), Id::p, NULL));
        Type *ftype = new TypeFunction(fparams, Type::tvoid, FALSE, LINKd, stc);
        ftype->mod = MODconst;

        fcp = new FuncDeclaration(loc, 0, Id::cpctor, stc, ftype);

        if (!(fcp->storage_class & STCdisable))
        {
            // Build *this = p;
            Expression *e = new ThisExp(0);
#if !STRUCTTHISREF
            e = new PtrExp(0, e);
#endif
            AssignExp *ea = new AssignExp(0,
                new PtrExp(0, new CastExp(0, new AddrExp(0, e), type->mutableOf()->pointerTo())),
                new PtrExp(0, new CastExp(0, new AddrExp(0, new IdentifierExp(0, Id::p)), type->mutableOf()->pointerTo()))
            );
            ea->op = TOKblit;
            Statement *s = new ExpStatement(0, ea);

            // Build postBlit();
            e = new ThisExp(0);
#if !STRUCTTHISREF
            e = new PtrExp(0, e);
#endif
            e = new PtrExp(0, new CastExp(0, new AddrExp(0, e), type->mutableOf()->pointerTo()));
            e = new DotVarExp(0, e, postblit, 0);
            e = new CallExp(0, e);

            s = new CompoundStatement(0, s, new ExpStatement(0, e));
            fcp->fbody = s;
        }
        else
            fcp->fbody = new ExpStatement(0, (Expression *)NULL);

        members->push(fcp);

        sc = sc->push();
        sc->stc = 0;
        sc->linkage = LINKd;

        fcp->semantic(sc);

        sc->pop();
    }

    return fcp;
}
Exemple #15
0
void createHamiltonian(Geometry const &geometry, DynVars const &dynVars,
                       MyMatrix<std::complex<double> >& matrix,Parameters const &ether,Aux &aux,int type)
// Modified by IS Nov-08-04

{
    int	col, volume, i = 0, p,dir;
    tpem_t hopping,hopping2,bandHop;
    double	 tmp,tmp2;
    int	j,iTmp;
    volume = ether.linSize;
    tpem_t S_ij;
    //static vector<double> phonon_q1(volume);
    //static vector<double> phonon_q2(volume);
    //static vector<double> phonon_q3(volume);


    Phonons<Parameters,Geometry> phonons(ether,geometry);
    for (p = 0; p < matrix.getRank(); p++)
        for (col = 0; col < matrix.getRank(); col++)
            matrix(p,col)=0;

    for (p = 0; p < volume; p++) {
        double phonon_q1=phonons.calcPhonon(p,dynVars,0);
        double phonon_q2=phonons.calcPhonon(p,dynVars,1);
        double phonon_q3=phonons.calcPhonon(p,dynVars,2);
        matrix(p,p) = ether.phononEjt[0]*phonon_q1+ether.phononEjt[2]*phonon_q3+ether.potential[p];
        matrix(p+volume,p+volume) = -ether.phononEjt[2]*phonon_q3+ether.phononEjt[0]*phonon_q1+ether.potential[p];
        matrix(p,p+volume) = (ether.phononEjt[1]*phonon_q2);
        matrix(p+volume,p) = conj(matrix(p,p+volume));

        for (j = 0; j < geometry.z(p); j++) {	/* hopping elements */
            iTmp=geometry.borderId(p,j);;
            if (iTmp>=0) hopping = ether.hoppings[iTmp];
            else hopping= -1.0;
            col = geometry.neighbor(p,j);
            tmp=cos(0.5*dynVars.theta[p])*cos(0.5*dynVars.theta[col]);
            tmp2=sin(0.5*dynVars.theta[p])*sin(0.5*dynVars.theta[col]);
            S_ij=tpem_t(tmp+tmp2*cos(dynVars.phi[p]-dynVars.phi[col]),
                        -tmp2*sin(dynVars.phi[p]-dynVars.phi[col]));

            if (p>col) hopping2 = conj(hopping);
            else hopping2=hopping;
            dir = int(j/2);

            bandHop=ether.bandHoppings[0+0*2+dir*4];
            hopping=hopping2 * bandHop ;
            matrix(p,col) = hopping * S_ij;
            matrix(col,p) = conj(hopping * S_ij);

            bandHop=ether.bandHoppings[0+1*2+dir*4];
            hopping= hopping2 * bandHop;
            matrix(p, col+volume)=hopping * S_ij;
            matrix(col+volume,p)=conj(matrix(p,col+volume));

            //
            bandHop=ether.bandHoppings[1+0*2+dir*4];
            hopping= hopping2 * bandHop;
            matrix(p+volume,col) =  hopping * S_ij;
            matrix(col,p+volume) =  conj(matrix(p+volume,col));

            bandHop=ether.bandHoppings[1+1*2+dir*4];
            hopping=hopping2 * bandHop;
            matrix(p+volume,col+volume) =  hopping * S_ij;
            matrix(col+volume,p+volume) = conj(matrix(p+volume,col+volume));
        }

        if (ether.isSet("tprime")) {
            for (j = 0; j < geometry.z(p,2); j++) {	/* hopping elements */
                iTmp=geometry.borderId(p,j,2);
                hopping= -1.0;
                if (iTmp>=0) hopping = ether.hoppings[iTmp];

                col = geometry.neighbor(p,j,2);
                tmp=cos(0.5*dynVars.theta[p])*cos(0.5*dynVars.theta[col]);
                tmp2=sin(0.5*dynVars.theta[p])*sin(0.5*dynVars.theta[col]);
                S_ij=tpem_t(tmp+tmp2*cos(dynVars.phi[p]-dynVars.phi[col]),
                            -tmp2*sin(dynVars.phi[p]-dynVars.phi[col]));

                if (p>col) hopping2 = conj(hopping);
                else hopping2=hopping;
                dir = int(j/2);

                bandHop=ether.bandHoppings[0+0*2+dir*4]*ether.tprime;
                hopping=hopping2 * bandHop ;
                matrix(p,col) = hopping * S_ij;
                matrix(col,p) = conj(hopping * S_ij);

                bandHop=ether.bandHoppings[0+1*2+dir*4]*ether.tprime;
                hopping= hopping2 * bandHop;
                matrix(p, col+volume)=hopping * S_ij;
                matrix(col+volume,p)=conj(matrix(p,col+volume));

                //
                bandHop=ether.bandHoppings[1+0*2+dir*4]*ether.tprime;
                hopping= hopping2 * bandHop;
                matrix(p+volume,col) =  hopping * S_ij;
                matrix(col,p+volume) =  conj(matrix(p+volume,col));

                bandHop=ether.bandHoppings[1+1*2+dir*4]*ether.tprime;
                hopping=hopping2 * bandHop;
                matrix(p+volume,col+volume) =  hopping * S_ij;
                matrix(col+volume,p+volume) = conj(matrix(p+volume,col+volume));
            }
        }
    }
    //if (!matrix.isHermitian()) throw std::runtime_error("I'm barking\n");


}
int main(int argc, char ** argv) {

	MPI_Init(&argc, &argv);

try {

	// Number of latitudes
	int nLat;

	// Number of longitudes
	int nLon;

	// Zonal wavenumber
	int nK;

	// Meridional power
	int nLpow;

	// Output file
	std::string strOutputFile;

	// Parse the command line
	BeginCommandLine()
		CommandLineInt(nLat, "lat", 40);
		CommandLineInt(nLon, "lon", 80);
		CommandLineString(strOutputFile, "out", "topo.nc");

		ParseCommandLine(argc, argv);
	EndCommandLine(argv)

	// Generate longitude and latitude arrays
	AnnounceBanner();
	AnnounceStartBlock("Generating longitude and latitude arrays");

	DataVector<double> dLon;
	dLon.Initialize(nLon);

	Parameters param;
	param.GenerateLatituteArray(nLat);

	std::vector<double> & dLat = param.vecNode;

	double dDeltaLon = 2.0 * M_PI / static_cast<double>(nLon);
	for (int i = 0; i < nLon; i++) {
		dLon[i] = (static_cast<double>(i) + 0.5) * dDeltaLon;
	}

	AnnounceEndBlock("Done");

	// Open NetCDF output file
	AnnounceStartBlock("Writing to file");

	NcFile ncdf_out(strOutputFile.c_str(), NcFile::Replace);

	// Output coordinates
	NcDim * dimLat = ncdf_out.add_dim("lat", nLat);
	NcDim * dimLon = ncdf_out.add_dim("lon", nLon);

	NcVar * varLat = ncdf_out.add_var("lat", ncDouble, dimLat);
	varLat->set_cur((long)0);
	varLat->put(&(param.vecNode[0]), nLat);

	NcVar * varLon = ncdf_out.add_var("lon", ncDouble, dimLon);
	varLon->set_cur((long)0);
	varLon->put(&(dLon[0]), nLon);

	// Generate topography
	DataMatrix<double> dTopo;
	dTopo.Initialize(nLat, nLon);

	double dK = static_cast<double>(nK);
	double dLpow = static_cast<double>(nLpow);

	double dA = 6.37122e6;
	double dX = 500.0;
	double dLatM = 0.0;
	double dLonM = M_PI / 4.0;
	double dD = 5000.0;
	double dH0 = 1.0;
	double dXiM = 4000.0;

	for (int j = 0; j < nLat; j++) {
	for (int i = 0; i < nLon; i++) {

		// Great circle distance
		double dR = dA / dX * acos(sin(dLatM) * sin(dLat[j])
			+ cos(dLatM) * cos(dLat[j]) * cos(dLon[i] - dLonM));

		double dCosXi = 1.0; //cos(M_PI * dR / dXiM);

		dTopo[j][i] = dH0 * exp(- dR * dR / (dD * dD))
			* dCosXi * dCosXi;
	}
	}

	// Write topography
	NcVar * varZs = ncdf_out.add_var("Zs", ncDouble, dimLat, dimLon);
	varZs->set_cur(0, 0);
	varZs->put(&(dTopo[0][0]), nLat, nLon);

	AnnounceEndBlock("Done");
	Announce("Completed successfully!");
	AnnounceBanner();

} catch(Exception & e) {
	Announce(e.ToString().c_str());
}
	MPI_Finalize();
}
Exemple #17
0
void kTpemHamiltonian (Geometry const &geometry, DynVars const &dynVars,
                       tpem_sparse *matrix,Parameters const &ether,Aux &aux,int type)
// Modified by IS Nov-08-04

{
    int	row, col, volume, i = 0, p,dir;
    tpem_t hopping,hopping2,bandHop;
    double	a=aux.varTpem_a, b=aux.varTpem_b, tmp,tmp2;
    int	j,iTmp;
    volume = ether.linSize;
    tpem_t S_ij;
    vector<double> phonon_q1(volume);
    vector<double> phonon_q2(volume);
    vector<double> phonon_q3(volume);

    if (ether.isSet("adjusttpembounds")) {
        //cerr<<"setting a=1 and b=0\n";
        a=1.0;
        b=0.0;
    }

    Phonons<Parameters,Geometry> phonons(ether,geometry);

    for (p = 0, row = 0; p < volume; p++, row++) {


        phonon_q1[p]=phonons.calcPhonon(p,dynVars,0);
        phonon_q2[p]=phonons.calcPhonon(p,dynVars,1);
        phonon_q3[p]=phonons.calcPhonon(p,dynVars,2);

        matrix->rowptr[row] = i;
        matrix->colind[i] = row;		/* element aa */
        tmp = (ether.phononEjt[0]*phonon_q1[p]+ether.phononEjt[2]*phonon_q3[p]+ether.potential[p]-b)/a;
        matrix->values[i] = tmp;
        i++;

        matrix->colind[i] = row + volume;	/*  element ab */
        tmp = (ether.phononEjt[1]*phonon_q2[p])/a;
        matrix->values[i] = tmp;
        i++;

        //cout<<"p="<<p<<endl;
        for (j = 0; j < geometry.z(p); j++) {	/* hopping elements */
            iTmp=geometry.borderId(p,j);;
            if (iTmp>=0) hopping = ether.hoppings[iTmp]/a;
            else hopping= -1.0/a;
            col = geometry.neighbor(p,j);
            tmp=cos(0.5*dynVars.theta[p])*cos(0.5*dynVars.theta[col]);
            tmp2=sin(0.5*dynVars.theta[p])*sin(0.5*dynVars.theta[col]);
            S_ij=tpem_t(tmp+tmp2*cos(dynVars.phi[p]-dynVars.phi[col]),
                        -tmp2*sin(dynVars.phi[p]-dynVars.phi[col]));

            if (p>col) hopping2 = conj(hopping);
            else hopping2=hopping;
            dir = int(j/2);

            bandHop=ether.bandHoppings[0+0*2+dir*4];
            hopping=hopping2 * bandHop ;
            matrix->colind[i] = col;
            matrix->values[i] = hopping * S_ij;
            i++;

            bandHop=ether.bandHoppings[0+1*2+dir*4];
            hopping= hopping2 * bandHop;
            matrix->colind[i] = col+volume;
            matrix->values[i] = hopping * S_ij;
            i++;
        }
    }
    for (p = 0; p < volume; p++, row++) {

        matrix->rowptr[row] = i;

        matrix->colind[i] = row ;	/* element bb */
        tmp = (-ether.phononEjt[2]*phonon_q3[p]+ether.phononEjt[0]*phonon_q1[p]+ether.potential[p]-b)/a;
        matrix->values[i] = tmp;
        i++;

        matrix->colind[i] = row - volume;		/*  element ba */
        tmp = (ether.phononEjt[1]*phonon_q2[p])/a;
        matrix->values[i] = tmp;
        i++;

        //cout<<"p="<<p<<endl;
        for (j = 0; j < geometry.z(p); j++) {	/* hopping elements */
            iTmp=geometry.borderId(p,j);
            if (iTmp>=0) hopping = ether.hoppings[iTmp]/a;
            else hopping= -1.0/a;
            col = geometry.neighbor(p,j);
            tmp=cos(0.5*dynVars.theta[p])*cos(0.5*dynVars.theta[col]);
            tmp2=sin(0.5*dynVars.theta[p])*sin(0.5*dynVars.theta[col]);
            S_ij=tpem_t(tmp+tmp2*cos(dynVars.phi[p]-dynVars.phi[col]),
                        -tmp2*sin(dynVars.phi[p]-dynVars.phi[col]));

            if (p>col) hopping2 = conj(hopping);
            else hopping2=hopping;
            dir = int(j/2);

            bandHop=ether.bandHoppings[1+0*2+dir*4];
            hopping= hopping2 * bandHop;
            matrix->colind[i] = col;
            matrix->values[i] = hopping * S_ij;
            i++;

            bandHop=ether.bandHoppings[1+1*2+dir*4];
            hopping=hopping2 * bandHop;
            matrix->colind[i] = col+volume;
            matrix->values[i] = hopping * S_ij;
            i++;
        }
    }

}
Exemple #18
0
bool CalibratorKriging::calibrateCore(File& iFile, const ParameterFile* iParameterFile) const {
   int nLat = iFile.getNumLat();
   int nLon = iFile.getNumLon();
   int nEns = iFile.getNumEns();
   int nTime = iFile.getNumTime();
   vec2 lats = iFile.getLats();
   vec2 lons = iFile.getLons();
   vec2 elevs = iFile.getElevs();

   // Check if this method can be applied
   bool hasValidGridpoint = false;
   for(int i = 0; i < nLat; i++) {
      for(int j = 0; j < nLon; j++) {
         if(Util::isValid(lats[i][j]) && Util::isValid(lons[i][j]) && Util::isValid(elevs[i][j])) {
            hasValidGridpoint = true;
         }
      }
   }
   if(!hasValidGridpoint) {
      Util::warning("There are no gridpoints with valid lat/lon/elev values. Skipping kriging...");
      return false;
   }

   // Precompute weights from auxillary variable
   std::vector<std::vector<std::vector<std::vector<float> > > > auxWeights;
   if(mAuxVariable != Variable::None) {
      // Initialize
      auxWeights.resize(nLat);
      for(int i = 0; i < nLat; i++) {
         auxWeights[i].resize(nLon);
         for(int j = 0; j < nLon; j++) {
            auxWeights[i][j].resize(nEns);
            for(int e = 0; e < nEns; e++) {
               auxWeights[i][j][e].resize(nTime, 0);
            }
         }
      }
      // Load auxillarcy variable
      std::vector<FieldPtr> auxFields;
      auxFields.resize(nTime);
      for(int t = 0; t < nTime; t++) {
         auxFields[t] = iFile.getField(mAuxVariable, t);
      }

      // Compute auxillary weights
      for(int t = 0; t < nTime; t++) {
         #pragma omp parallel for
         for(int i = 0; i < nLat; i++) {
            for(int j = 0; j < nLon; j++) {
               for(int e = 0; e < nEns; e++) {
                  float total = 0;
                  int start = std::max(t-mWindow,0);
                  int end   = std::min(nTime-1,t+mWindow);
                  int numValid = 0;
                  for(int tt = start; tt <= end; tt++) {
                     float aux = (*auxFields[tt])(i,j,e);
                     if(Util::isValid(aux)) {
                        if(aux >= mLowerThreshold && aux <= mUpperThreshold) {
                           total++;
                        }
                        numValid++;
                     }
                  }
                  int windowSize = end - start + 1;
                  if(numValid == 0)
                     auxWeights[i][j][e][t] = 1;
                  else
                     auxWeights[i][j][e][t] += total / numValid;
               }
            }
         }
      }
   }

   if(!iParameterFile->isLocationDependent()) {
      std::stringstream ss;
      ss << "Kriging requires a parameter file with spatial information";
      Util::error(ss.str());
   }
   std::vector<Location> obsLocations = iParameterFile->getLocations();

   // General proceedure for a given gridpoint:
   // S              = matrix * weights
   // weights        = (matrix)^-1 * S
   // gridpoint_bias = weights' * bias (scalar)
   // where
   // matrix:  The obs-to-obs covariance matrix (NxN)
   // S:       The obs-to-current_grid_point covariance (Nx1)
   // bias:    The bias at each obs location (Nx1)
   //
   // Note that when computing the weights, we can take a shortcut since most values in
   // S are zero. However, the weights will still have the length of all stations (not the
   // number of nearby stations), since when computing the bias we still need to 
   // weight in far away biases (because they can covary with the nearby stations)

   // Compute obs-obs covariance-matrix once
   vec2 matrix;
   int N = obsLocations.size();
   std::cout << "      Point locations: " << N << std::endl;
   matrix.resize(N);
   for(int ii = 0; ii < N; ii++) {
      matrix[ii].resize(N,0);
   }
   for(int ii = 0; ii < N; ii++) {
      Location iloc = obsLocations[ii];
      // The diagonal is 1, since the distance from a point to itself
      // is 0, therefore its weight is 1.
      matrix[ii][ii] = 1;
      // The matrix is symmetric, so only compute one of the halves
      for(int jj = ii+1; jj < N; jj++) {
         Location jloc = obsLocations[jj];
         // Improve conditioning of matrix when you have two or more stations
         // that are very close
         float factor = 0.414 / 0.5;
         float R = calcCovar(iloc, jloc)*factor;
         // Store the number in both halves
         matrix[ii][jj] = R;
         matrix[jj][ii] = R;
      }
   }

   // Compute (matrix)^-1
   std::cout << "      Precomputing inverse of obs-to-obs covariance matrix: ";
   std::cout.flush();
   double s1 = Util::clock();
   vec2 inverse = Util::inverse(matrix);
   double e1 = Util::clock();
   std::cout << e1 - s1 << " seconds" << std::endl;

   // Compute grid-point to obs-point covariances
   std::cout << "      Precomputing gridpoint-to-obs covariances: ";
   std::cout.flush();
   double s2 = Util::clock();
   // Store the covariances of each gridpoint to every obs-point. To save memory, 
   // only store values that are above 0. Store the index of the obs-point.
   // This means that Sindex does not have the same size for every gridpoint.
   std::vector<std::vector<std::vector<float> > > S; // lat, lon, obspoint
   std::vector<std::vector<std::vector<int> > > Sindex;
   S.resize(nLat);
   Sindex.resize(nLat);
   for(int i = 0; i < nLat; i++) {
      S[i].resize(nLon);
      Sindex[i].resize(nLon);
   }

   #pragma omp parallel for
   for(int i = 0; i < nLat; i++) {
      for(int j = 0; j < nLon; j++) {
         float lat = lats[i][j];
         float lon = lons[i][j];
         float elev = elevs[i][j];
         const Location gridPoint(lat, lon, elev);
         for(int ii = 0; ii < N; ii++) {
            Location obsPoint = obsLocations[ii];
            float covar = calcCovar(obsPoint, gridPoint);
            if(covar > 0) {
               S[i][j].push_back(covar);
               Sindex[i][j].push_back(ii);
            }
         }
      }
   }
   double e2 = Util::clock();
   std::cout << e2 - s2 << " seconds" << std::endl;

   // Loop over offsets
   for(int t = 0; t < nTime; t++) {
      FieldPtr field = iFile.getField(mVariable, t);
      FieldPtr accum = iFile.getEmptyField(0);
      FieldPtr weights = iFile.getEmptyField(0);

      // Arrange all the biases for all stations into one vector
      std::vector<float> bias(N,0);
      for(int k = 0; k < obsLocations.size(); k++) {
         Location loc = obsLocations[k];
         Parameters parameters = iParameterFile->getParameters(t, loc, false);
         if(parameters.size() > 0) {
            float currBias = parameters[0];
            if(Util::isValid(currBias)) {
               // For * and /, operate on the flucuations areound a mean of 1
               if(mOperator == Util::OperatorMultiply) {
                  currBias = currBias - 1;
               }
               else if(mOperator == Util::OperatorDivide) {
                  currBias = currBias - 1;
               }
            }
            bias[k] = currBias;
         }
      }

      #pragma omp parallel for
      for(int i = 0; i < nLat; i++) {
         for(int j = 0; j < nLon; j++) {

            std::vector<float> currS = S[i][j];
            std::vector<int> currI = Sindex[i][j];
            int currN = currS.size();

            // No correction if there are no nearby stations
            if(currN == 0)
               continue;

            // Don't use the nearest station when cross validating
            float maxCovar = Util::MV;
            int ImaxCovar = Util::MV;
            if(mCrossValidate) {
               for(int ii = 0; ii < currS.size(); ii++) {
                  if(!Util::isValid(ImaxCovar) || currS[ii] > maxCovar) {
                     ImaxCovar = ii;
                     maxCovar = currS[ii];
                  }
               }
               currS[ImaxCovar] = 0;
               vec2 cvMatrix = matrix;
               for(int ii = 0; ii < currN; ii++) {
                  cvMatrix[ImaxCovar][ii] = 0;
                  cvMatrix[ii][ImaxCovar] = 0;
               }
               cvMatrix[ImaxCovar][ImaxCovar] = 1;
               inverse = Util::inverse(cvMatrix);
            }

            // Compute weights (matrix-vector product)
            std::vector<float> weights;
            weights.resize(N, 0);
            for(int ii = 0; ii < N; ii++) {
               // Only loop over non-zero values in the vector
               for(int jj = 0; jj < currN; jj++) {
                  int JJ = currI[jj];
                  weights[ii] += inverse[ii][JJ] * currS[jj];
               }
            }
            // Set the weight of the nearest location to 0 when cross-validating
            if(mCrossValidate) {
               weights[ImaxCovar] = 0;
            }

            // Compute final bias (dot product of bias and weights)
            float finalBias = 0;
            for(int ii = 0; ii < N; ii++) {
               float currBias = bias[ii];
               if(!Util::isValid(currBias)) {
                  finalBias = Util::MV;
                  break;
               }
               finalBias += bias[ii]*weights[ii];
            }

            if(Util::isValid(finalBias)) {
               // Reconstruct the factor/divisor by adding the flucuations
               // onto the mean of 1
               if(mOperator == Util::OperatorMultiply)
                  finalBias = finalBias + 1;
               else if(mOperator == Util::OperatorDivide)
                  finalBias = finalBias - 1;

               // Apply bias to each ensemble member
               for(int e = 0; e < nEns; e++) {
                  float rawValue = (*field)(i,j,e);

                  // Adjust bias based on auxillary weight
                  if(mAuxVariable != Variable::None) {
                     float weight = auxWeights[i][j][e][t];
                     if(mOperator == Util::OperatorAdd || mOperator == Util::OperatorSubtract) {
                        finalBias = finalBias * weight;
                     }
                     else {
                        finalBias = pow(finalBias, weight);
                     }
                  }

                  if(mOperator == Util::OperatorAdd) {
                     (*field)(i,j,e) += finalBias;
                  }
                  else if(mOperator == Util::OperatorSubtract) {
                     (*field)(i,j,e) -= finalBias;
                  }
                  else if(mOperator == Util::OperatorMultiply) {
                     // TODO: How do we ensure that the matrix is positive definite in this
                     // case?
                     (*field)(i,j,e) *= finalBias;
                  }
                  else if(mOperator == Util::OperatorDivide) {
                     // TODO: How do we ensure that the matrix is positive definite in this
                     // case?
                     (*field)(i,j,e) /= finalBias;
                  }
                  else {
                     Util::error("Unrecognized operator in CalibratorKriging");
                  }
               }
            }
         }
      }
   }
   return true;
}
Exemple #19
0
Expression *createTypeInfoArray(Scope *sc, Expression *exps[], size_t dim)
{
#if 1
    /*
     * Pass a reference to the TypeInfo_Tuple corresponding to the types of the
     * arguments. Source compatibility is maintained by computing _arguments[]
     * at the start of the called function by offseting into the TypeInfo_Tuple
     * reference.
     */
    Parameters *args = Parameters_create();
    args->setDim(dim);
    for (size_t i = 0; i < dim; i++)
    {   Parameter *arg = Parameter::create(STCin, exps[i]->type, NULL, NULL);
        (*args)[i] = arg;
    }
    TypeTuple *tup = TypeTuple::create(args);
    Expression *e = tup->getTypeInfo(sc);
    e = e->optimize(WANTvalue);
    assert(e->op == TOKsymoff);         // should be SymOffExp

    return e;
#else
    /* Improvements:
     * 1) create an array literal instead,
     * as it would eliminate the extra dereference of loading the
     * static variable.
     */

    ArrayInitializer *ai = new ArrayInitializer(0);
    VarDeclaration *v;
    Type *t;
    Expression *e;
    OutBuffer buf;
    Identifier *id;
    char *name;

    // Generate identifier for _arguments[]
    buf.writestring("_arguments_");
    for (int i = 0; i < dim; i++)
    {   t = exps[i]->type;
        t->toDecoBuffer(&buf);
    }
    buf.writeByte(0);
    id = Lexer::idPool((char *)buf.data);

    Module *m = sc->module;
    Dsymbol *s = m->symtab->lookup(id);

    if (s && s->parent == m)
    {   // Use existing one
        v = s->isVarDeclaration();
        assert(v);
    }
    else
    {   // Generate new one

        for (int i = 0; i < dim; i++)
        {   t = exps[i]->type;
            e = t->getTypeInfo(sc);
            ai->addInit(new IntegerExp(i), new ExpInitializer(Loc(), e));
        }

        t = Type::typeinfo->type->arrayOf();
        ai->type = t;
        v = new VarDeclaration(0, t, id, ai);
        v->storage_class |= STCtemp;
        m->members->push(v);
        m->symtabInsert(v);
        sc = sc->push();
        sc->linkage = LINKc;
        sc->stc = STCstatic | STCcomdat;
        ai->semantic(sc, t);
        v->semantic(sc);
        v->parent = m;
        sc = sc->pop();
    }
    e = VarExp::create(Loc(), v);
    e = e->semantic(sc);
    return e;
#endif
}
int
lineByLineRLCSA(std::string base_name, usint block_size, usint sample_rate, usint buffer_size)
{
  Parameters parameters;
  parameters.set(RLCSA_BLOCK_SIZE.first, block_size);
  parameters.set(SAMPLE_RATE.first, sample_rate);

  if(sample_rate > 0)
  {
    parameters.set(SUPPORT_LOCATE.first, 1);
    parameters.set(SUPPORT_DISPLAY.first, 1);
  }
  else
  {
    parameters.set(SUPPORT_LOCATE.first, 0);
    parameters.set(SUPPORT_DISPLAY.first, 0);
  }

  std::string parameters_name = base_name + PARAMETERS_EXTENSION;
  parameters.print();
  parameters.write(parameters_name);

  std::cout << "Input: " << base_name << std::endl;
  std::ifstream input_file(base_name.c_str(), std::ios_base::binary);
  if(!input_file)
  {
    std::cerr << "Error opening input file!" << std::endl;
    return 2;
  }
  std::cout << "Buffer size: " << buffer_size << " MB" << std::endl;
  std::cout << std::endl;

  double start = readTimer();
  RLCSABuilder builder(parameters.get(RLCSA_BLOCK_SIZE), parameters.get(SAMPLE_RATE), buffer_size * MEGABYTE);

  usint lines = 0, total = 0;
  while(input_file)
  {
    char buffer[16384];  // FIXME What if lines are longer? Probably fails.
    input_file.getline(buffer, 16384);
    usint chars = input_file.gcount();
    lines++; total += chars;
    if(chars >= 16383) { std::cout << lines << ": " << chars << " chars read!" << std::endl; }
    if(chars > 1) { builder.insertSequence(buffer, chars - 1, false); }
  }

  RLCSA* rlcsa = 0;
  if(builder.isOk())
  {
    rlcsa = builder.getRLCSA();
    rlcsa->writeTo(base_name);
  }
  else
  {
    std::cerr << "Error: RLCSA construction failed!" << std::endl;
    return 3;
  }

  double time = readTimer() - start;
  double build_time = builder.getBuildTime();
  double search_time = builder.getSearchTime();
  double sort_time = builder.getSortTime();
  double merge_time = builder.getMergeTime();

  double megabytes = rlcsa->getSize() / (double)MEGABYTE;
  usint sequences = rlcsa->getNumberOfSequences();
  std::cout << sequences << " sequences" << std::endl;
  std::cout << megabytes << " megabytes in " << time << " seconds (" << (megabytes / time) << " MB/s)" << std::endl;
  std::cout << "(build " << build_time << " s, search " << search_time << "s, sort " << sort_time << " s, merge " << merge_time << " s)" << std::endl;
  std::cout << std::endl;

  delete rlcsa;
  return 0;
}
Exemple #21
0
FuncDeclaration *buildXopEquals(StructDeclaration *sd, Scope *sc)
{
    if (!needOpEquals(sd))
        return NULL;        // bitwise comparison would work

    //printf("StructDeclaration::buildXopEquals() %s\n", sd->toChars());
    if (Dsymbol *eq = search_function(sd, Id::eq))
    {
        if (FuncDeclaration *fd = eq->isFuncDeclaration())
        {
            TypeFunction *tfeqptr;
            {
                Scope scx;

                /* const bool opEquals(ref const S s);
                 */
                Parameters *parameters = new Parameters;
                parameters->push(new Parameter(STCref | STCconst, sd->type, NULL, NULL));
                tfeqptr = new TypeFunction(parameters, Type::tbool, 0, LINKd);
                tfeqptr->mod = MODconst;
                tfeqptr = (TypeFunction *)tfeqptr->semantic(Loc(), &scx);
            }
            fd = fd->overloadExactMatch(tfeqptr);
            if (fd)
                return fd;
        }
    }

    if (!sd->xerreq)
    {
        // object._xopEquals
        Identifier *id = Lexer::idPool("_xopEquals");
        Expression *e = new IdentifierExp(sd->loc, Id::empty);
        e = new DotIdExp(sd->loc, e, Id::object);
        e = new DotIdExp(sd->loc, e, id);
        e = e->semantic(sc);
        Dsymbol *s = getDsymbol(e);
        if (!s)
        {
            ::error(Loc(), "ICE: %s not found in object module. You must update druntime", id->toChars());
            fatal();
        }
        assert(s);
        sd->xerreq = s->isFuncDeclaration();
    }

    Loc declLoc = Loc();    // loc is unnecessary so __xopEquals is never called directly
    Loc loc = Loc();        // loc is unnecessary so errors are gagged

    Parameters *parameters = new Parameters;
    parameters->push(new Parameter(STCref | STCconst, sd->type, Id::p, NULL));
    parameters->push(new Parameter(STCref | STCconst, sd->type, Id::q, NULL));
    TypeFunction *tf = new TypeFunction(parameters, Type::tbool, 0, LINKd);

    Identifier *id = Id::xopEquals;
    FuncDeclaration *fop = new FuncDeclaration(declLoc, Loc(), id, STCstatic, tf);

    Expression *e1 = new IdentifierExp(loc, Id::p);
    Expression *e2 = new IdentifierExp(loc, Id::q);
    Expression *e = new EqualExp(TOKequal, loc, e1, e2);

    fop->fbody = new ReturnStatement(loc, e);

    unsigned errors = global.startGagging();    // Do not report errors
    Scope *sc2 = sc->push();
    sc2->stc = 0;
    sc2->linkage = LINKd;

    fop->semantic(sc2);
    fop->semantic2(sc2);

    sc2->pop();
    if (global.endGagging(errors))    // if errors happened
        fop = sd->xerreq;

    return fop;
}
Exemple #22
0
// check the HMM type for a DIRECTED branch without going off the end of the array
int HMM_type_for_branch(const Parameters& P, int b)
{
  return P.branch_HMM_type(P.t().undirected(b));
}
Exemple #23
0
int main(int argc, char **argv)
{
  // Model variables
  uint nFrames = 2;
  uint nStates = 3;
  uint nVars = 3; //Tohid: t, x, y
  uint nDemos = 4;//Tohid: number of Demonstrations, for easier loading from the data files
  std::vector<std::string> varNames;
  varNames.push_back("t");    // time is input (t) and the attractor position (2D vector [x y]) is the output.
  varNames.push_back("x");
  varNames.push_back("y");
  //..................................................................................
  //......... loading the demonstrations and task parameters from the txt files ......
  std::vector<Demonstration> demos;
  Demonstration demo =  Demonstration(3,200,2);  //(3 vars, 200 datapoints, 2 frames of references)

  std::vector<Parameters> Params;


  char filename[256];
  cout<<"Loading the demonstrations and the task parameters ...";
  for (int m=0; m<nDemos; m++){   //Loading demos in the loop
      Parameters param = Parameters(3,2,1);  //nVAR, nPAR, nPOINTS (set to 1 to show that the task parameters are fixed all the time)
      sprintf(filename, "../../data/pgmm/Data0%d.txt",m+1);
      demo.getDatapoints().loadFromFile(filename, true);
      demo.getDatapoints().setVarNames(varNames);
      sprintf(filename, "../../data/pgmm/Param0%d.txt",m+1);
      param.loadFromFile(filename);
      Params.push_back(param);
      demo.setParams(param);
      demos.push_back(demo);
  }
  cout<<endl<<"Demonstrations and task parameters are loaded successfully !!!!"<<endl;
  cout<<"Press any key to continue (learning the PGMM model for the loaded demonstrations)"<<endl;
  getchar();

  //..................................................................................
  //......... Learning the PGMM model parameters using the EM algorithm ......
  cout<<"Learning model parameters using EM ...";
  PGMM_Model *pgmm;
  //pgmm = new PGMM_Model(nVars, nStates, nFrames);
  pgmm = new PGMM_Model(demos, nStates, nFrames);
  //    pgmm->loadPGMMfromMATLAB(priorsName, ZmuName, ZsigmaName);   //Tohid: commented, because we do not have Zmu and ZSigma anymore
  //cout<<"demos.size() =  "<<demos.size()<<endl;
  cout << "\n EM rounds = " << pgmm->EM_TensorLearn()<<endl;
  cout<<"Learning is done and the model is learned for the provided demonstrations!!!"<<endl;
  // saving the learned model parameters
  mat MuTmp = zeros(nVars, nStates*nFrames);
  mat SigmaTmp = zeros(nVars, nVars*nStates*nFrames);
  mat Priors = zeros(1,nStates);
  std::vector<GMM_Model> GMMSresult;
  GMMSresult = pgmm->getGMMS();
  for(uint m=0; m<nFrames; m++){
    for (uint i=0;i<nStates; i++){
      MuTmp.col(m*nStates+i) = GMMSresult.at(m).getCOMPONENTS().at(i).getMU();
      SigmaTmp.cols(m*nVars*nStates+i*nVars, m*nVars*nStates+i*nVars+nVars-1) = GMMSresult.at(m).getCOMPONENTS().at(i).getSIGMA();
    }
  }
  sprintf(filename, "../../data/pgmm/Mu0%d.txt",2);
  MuTmp.save(filename, raw_ascii);
  sprintf(filename, "../../data/pgmm/Sigma0%d.txt",2);
  SigmaTmp.save(filename, raw_ascii);
  sprintf(filename, "../../data/pgmm/Priors0%d.txt",2);
  Priors = pgmm->getPRIORS();
  Priors.save(filename, raw_ascii);
  cout<<"the learned model parameters are written into text files succesfully."<<endl;
  cout<<"Press any key to continue (performing the GMR for the new set of task parameters)"<<endl;
  getchar();
  //..................................................................................

  // Path for model files
  //std::string priorsName = "../../data/pgmm/Priors02.txt";
  //std::string MuName = "../../data/pgmm/Mu02.txt";
  //std::string SigmaName = "../../data/pgmm/Sigma02.txt";

  // Reproduction variables (GMR)
  GMR			*gmr = new GMR();
  Datapoints	*repro = new Datapoints(1,1);				// Only one datapoint passed at each time step
  mat			reproData, auxYgmr;
  std::vector<std::string> reproVarNames;
  reproVarNames.push_back("t");							      // time is the query point
  repro->setVarNames(reproVarNames);
  // loading new parameters for the reproduction from the text file
  // In this case we have considered that the parameters are the same all along the reproduction. They can be varying.
  std::vector<mat> A_tmp;
  mat auxA;
  std::vector<colvec> b_tmp;
  colvec auxb;
  sprintf(filename, "../../data/pgmm/ParamRepro0%d.txt",1);
  mat ParamTmp;
  ParamTmp.load(filename, raw_ascii);
  b_tmp.push_back(trans(ParamTmp.row(0)));
  A_tmp.push_back(ParamTmp.rows(1,nVars));
  b_tmp.push_back(trans(ParamTmp.row(nVars+1)));
  A_tmp.push_back(ParamTmp.rows(nVars+2,2*nVars+1));
  for(uint tn = 1 ; tn <= 200 ; tn++){
      // Computing the resulting gmm given the set of parameters {A,b}
      GMM_Model* gmm;
      gmm = pgmm->getGMM(A_tmp, b_tmp);
      gmm->setVARSNames(varNames);
      // Printing model components
      cout << "Resulting GMM given the set of parameters 'A' and 'b'" << endl;
      for(uint i = 0 ; i < nStates ; i++){
              cout << "State #" << i << ":"<< endl;
              gmm->getCOMPONENTS().at(i).getMU().print("Mu = ");
              gmm->getCOMPONENTS().at(i).getSIGMA().print("Sigma = ");
      }
      // Computing GMR
      gmr->setGMMModel(gmm);
      mat repDataPt;
      repDataPt << (tn * 0.01);	// time step as input
      repDataPt.print("tn = ");
      repro->setData(repDataPt);
      gmr->regression(repro);
      gmr->get_y().print("y = ");

      cout << "Please press [ENTER] to continue or [CTRL+C] to finish" << endl;
      char key;
      std::cin.ignore(1);
  }
  return 0;
}
Exemple #24
0
void TypeInfoStructDeclaration::toDt(dt_t **pdt)
{
    //printf("TypeInfoStructDeclaration::toDt() '%s'\n", toChars());

    unsigned offset = Type::typeinfostruct->structsize;

    dtxoff(pdt, Type::typeinfostruct->toVtblSymbol(), 0, TYnptr); // vtbl for TypeInfo_Struct
    dtsize_t(pdt, 0);                        // monitor

    assert(tinfo->ty == Tstruct);

    TypeStruct *tc = (TypeStruct *)tinfo;
    StructDeclaration *sd = tc->sym;

    /* Put out:
     *  char[] name;
     *  void[] init;
     *  hash_t function(in void*) xtoHash;
     *  bool function(in void*, in void*) xopEquals;
     *  int function(in void*, in void*) xopCmp;
     *  string function(const(void)*) xtoString;
     *  uint m_flags;
     *  xgetMembers;
     *  xdtor;
     *  xpostblit;
     *  uint m_align;
     *  version (X86_64)
     *      TypeInfo m_arg1;
     *      TypeInfo m_arg2;
     *
     *  name[]
     */

    const char *name = sd->toPrettyChars();
    size_t namelen = strlen(name);
    dtsize_t(pdt, namelen);
    //dtabytes(pdt, TYnptr, 0, namelen + 1, name);
    dtxoff(pdt, toSymbol(), offset, TYnptr);
    offset += namelen + 1;

    // void[] init;
    dtsize_t(pdt, sd->structsize);       // init.length
    if (sd->zeroInit)
        dtsize_t(pdt, 0);                // NULL for 0 initialization
    else
        dtxoff(pdt, sd->toInitializer(), 0, TYnptr);    // init.ptr

    FuncDeclaration *fd;
    FuncDeclaration *fdx;
    Dsymbol *s;

    static TypeFunction *tftohash;
    static TypeFunction *tftostring;

    if (!tftohash)
    {
        Scope sc;

        /* const hash_t toHash();
         */
        tftohash = new TypeFunction(NULL, Type::thash_t, 0, LINKd);
        tftohash->mod = MODconst;
        tftohash = (TypeFunction *)tftohash->semantic(0, &sc);

        tftostring = new TypeFunction(NULL, Type::tchar->invariantOf()->arrayOf(), 0, LINKd);
        tftostring = (TypeFunction *)tftostring->semantic(0, &sc);
    }

    TypeFunction *tfcmpptr;
    {
        Scope sc;

        /* const int opCmp(ref const KeyType s);
         */
        Parameters *arguments = new Parameters;
#if STRUCTTHISREF
        // arg type is ref const T
        Parameter *arg = new Parameter(STCref, tc->constOf(), NULL, NULL);
#else
        // arg type is const T*
        Parameter *arg = new Parameter(STCin, tc->pointerTo(), NULL, NULL);
#endif

        arguments->push(arg);
        tfcmpptr = new TypeFunction(arguments, Type::tint32, 0, LINKd);
        tfcmpptr->mod = MODconst;
        tfcmpptr = (TypeFunction *)tfcmpptr->semantic(0, &sc);
    }

    s = search_function(sd, Id::tohash);
    fdx = s ? s->isFuncDeclaration() : NULL;
    if (fdx)
    {   fd = fdx->overloadExactMatch(tftohash);
        if (fd)
        {
            dtxoff(pdt, fd->toSymbol(), 0, TYnptr);
            TypeFunction *tf = (TypeFunction *)fd->type;
            assert(tf->ty == Tfunction);
            if (global.params.warnings)
            {
                /* I'm a little unsure this is the right way to do it. Perhaps a better
                 * way would to automatically add these attributes to any struct member
                 * function with the name "toHash".
                 * So I'm leaving this here as an experiment for the moment.
                 */
                if (!tf->isnothrow || tf->trust == TRUSTsystem /*|| tf->purity == PUREimpure*/)
                {   warning(fd->loc, "toHash() must be declared as extern (D) uint toHash() const nothrow @safe, not %s", tf->toChars());
                    if (global.params.warnings == 1)
                        global.errors++;
                }
            }
        }
        else
        {
            //fdx->error("must be declared as extern (D) uint toHash()");
            dtsize_t(pdt, 0);
        }
    }
    else
        dtsize_t(pdt, 0);

    if (sd->xeq)
        dtxoff(pdt, sd->xeq->toSymbol(), 0, TYnptr);
    else
        dtsize_t(pdt, 0);

    s = search_function(sd, Id::cmp);
    fdx = s ? s->isFuncDeclaration() : NULL;
    if (fdx)
    {
        //printf("test1 %s, %s, %s\n", fdx->toChars(), fdx->type->toChars(), tfeqptr->toChars());
        fd = fdx->overloadExactMatch(tfcmpptr);
        if (fd)
        {   dtxoff(pdt, fd->toSymbol(), 0, TYnptr);
            //printf("test2\n");
        }
        else
            //fdx->error("must be declared as extern (D) int %s(%s*)", fdx->toChars(), sd->toChars());
            dtsize_t(pdt, 0);
    }
    else
        dtsize_t(pdt, 0);

    s = search_function(sd, Id::tostring);
    fdx = s ? s->isFuncDeclaration() : NULL;
    if (fdx)
    {   fd = fdx->overloadExactMatch(tftostring);
        if (fd)
            dtxoff(pdt, fd->toSymbol(), 0, TYnptr);
        else
            //fdx->error("must be declared as extern (D) char[] toString()");
            dtsize_t(pdt, 0);
    }
    else
        dtsize_t(pdt, 0);

    // uint m_flags;
    dtsize_t(pdt, tc->hasPointers());

#if DMDV2
    // xgetMembers
    FuncDeclaration *sgetmembers = sd->findGetMembers();
    if (sgetmembers)
        dtxoff(pdt, sgetmembers->toSymbol(), 0, TYnptr);
    else
        dtsize_t(pdt, 0);                        // xgetMembers

    // xdtor
    FuncDeclaration *sdtor = sd->dtor;
    if (sdtor)
        dtxoff(pdt, sdtor->toSymbol(), 0, TYnptr);
    else
        dtsize_t(pdt, 0);                        // xdtor

    // xpostblit
    FuncDeclaration *spostblit = sd->postblit;
    if (spostblit && !(spostblit->storage_class & STCdisable))
        dtxoff(pdt, spostblit->toSymbol(), 0, TYnptr);
    else
        dtsize_t(pdt, 0);                        // xpostblit
#endif

    // uint m_align;
    dtsize_t(pdt, tc->alignsize());

    if (global.params.is64bit)
    {
        TypeTuple *tup = tc->toArgTypes();
        assert(tup->arguments->dim <= 2);
        for (size_t i = 0; i < 2; i++)
        {
            if (i < tup->arguments->dim)
            {
                Type *targ = (tup->arguments->tdata()[i])->type;
                targ = targ->merge();
                targ->getTypeInfo(NULL);
                dtxoff(pdt, targ->vtinfo->toSymbol(), 0, TYnptr);       // m_argi
            }
            else
                dtsize_t(pdt, 0);                    // m_argi
        }
    }

    // name[]
    dtnbytes(pdt, namelen + 1, name);
}
Exemple #25
0
void Volumetric3D::buildInparam(std::vector<Volumetric3D *> &models, 
    const Parameters &par, const ExodusModel *exModel, 
    double srcLat, double srcLon, double srcDep, int verbose) {
    
    // clear the container
    for (const auto &m: models) {
        delete m;    
    }    
    models.clear();
    
    // check size
    int nmodels = par.getValue<int>("MODEL_3D_VOLUMETRIC_NUM");
    int nsize = par.getSize("MODEL_3D_VOLUMETRIC_LIST");
    if (nmodels > nsize) {
        throw std::runtime_error("Volumetric3D::buildInparam || "
            "Not enough model names provided in MODEL_3D_VOLUMETRIC_LIST, ||"
            "MODEL_3D_VOLUMETRIC_NUM = " + boost::lexical_cast<std::string>(nmodels) + 
            ", but only " + boost::lexical_cast<std::string>(nsize) + " provided.");
    }
    
    for (int imodel = 0; imodel < nmodels; imodel++) {
        
        // split model name and parameters
        std::string mstr = par.getValue<std::string>("MODEL_3D_VOLUMETRIC_LIST", imodel);
        std::vector<std::string> strs = Parameters::splitString(mstr, "$");
        std::string name(strs[0]);
        std::vector<std::string> params(strs.begin() + 1, strs.end());
        
        // create model
        Volumetric3D *m;
        if (boost::iequals(name, "s20rts")) {
            m = new Volumetric3D_s20rts();
        } else if (boost::iequals(name, "s40rts")) {
            m = new Volumetric3D_s40rts();
        } else if (boost::iequals(name, "crust1")) {
            m = new Volumetric3D_crust1();
        } else if (boost::iequals(name, "bubble")) {
            m = new Volumetric3D_bubble(); 
        } else if (boost::iequals(name, "cylinder")) {
            m = new Volumetric3D_cylinder();        
        } else if (boost::iequals(name, "emc")) {
            m = new Volumetric3D_EMC();
            
        /////////////////////////////// 
        // user-defined models here
        /////////////////////////////// 
            
        } else {
            throw std::runtime_error("Volumetric3D::buildInparam || "
                "Unknown volumetric model name " + name + ".");
        }
        
        // initialize
        m->setSourceLocation(srcLat, srcLon, srcDep);
        m->setupExodusModel(exModel);
        m->initialize(params);
        models.push_back(m);
        
        // verbose
        if (verbose) {
            XMPI::cout << m->verbose();
        }
    }
}
Exemple #26
0
Expression *createTypeInfoArray(Scope *sc, Expression *exps[], unsigned dim)
{
#if 1
    /* Get the corresponding TypeInfo_Tuple and
     * point at its elements[].
     */

    /* Create the TypeTuple corresponding to the types of args[]
     */
    Parameters *args = new Parameters;
    args->setDim(dim);
    for (size_t i = 0; i < dim; i++)
    {   Parameter *arg = new Parameter(STCin, exps[i]->type, NULL, NULL);
        args->tdata()[i] = arg;
    }
    TypeTuple *tup = new TypeTuple(args);
    Expression *e = tup->getTypeInfo(sc);
    e = e->optimize(WANTvalue);
    assert(e->op == TOKsymoff);         // should be SymOffExp

#if BREAKABI
    /*
     * Should just pass a reference to TypeInfo_Tuple instead,
     * but that would require existing code to be recompiled.
     * Source compatibility can be maintained by computing _arguments[]
     * at the start of the called function by offseting into the
     * TypeInfo_Tuple reference.
     */

#else
    // Advance to elements[] member of TypeInfo_Tuple
    SymOffExp *se = (SymOffExp *)e;
    se->offset += PTRSIZE + PTRSIZE;

    // Set type to TypeInfo[]*
    se->type = Type::typeinfo->type->arrayOf()->pointerTo();

    // Indirect to get the _arguments[] value
    e = new PtrExp(0, se);
    e->type = se->type->next;
#endif
    return e;
#else
    /* Improvements:
     * 1) create an array literal instead,
     * as it would eliminate the extra dereference of loading the
     * static variable.
     */

    ArrayInitializer *ai = new ArrayInitializer(0);
    VarDeclaration *v;
    Type *t;
    Expression *e;
    OutBuffer buf;
    Identifier *id;
    char *name;

    // Generate identifier for _arguments[]
    buf.writestring("_arguments_");
    for (int i = 0; i < dim; i++)
    {   t = exps[i]->type;
        t->toDecoBuffer(&buf);
    }
    buf.writeByte(0);
    id = Lexer::idPool((char *)buf.data);

    Module *m = sc->module;
    Dsymbol *s = m->symtab->lookup(id);

    if (s && s->parent == m)
    {   // Use existing one
        v = s->isVarDeclaration();
        assert(v);
    }
    else
    {   // Generate new one

        for (int i = 0; i < dim; i++)
        {   t = exps[i]->type;
            e = t->getTypeInfo(sc);
            ai->addInit(new IntegerExp(i), new ExpInitializer(0, e));
        }

        t = Type::typeinfo->type->arrayOf();
        ai->type = t;
        v = new VarDeclaration(0, t, id, ai);
        m->members->push(v);
        m->symtabInsert(v);
        sc = sc->push();
        sc->linkage = LINKc;
        sc->stc = STCstatic | STCcomdat;
        ai->semantic(sc, t);
        v->semantic(sc);
        v->parent = m;
        sc = sc->pop();
    }
    e = new VarExp(0, v);
    e = e->semantic(sc);
    return e;
#endif
}
void  HyperElasticUP3DLaw::CalculateMaterialResponsePK2 (Parameters& rValues)
{

    //-----------------------------//

    //a.-Check if the constitutive parameters are passed correctly to the law calculation
    CheckParameters(rValues);

    //b.- Get Values to compute the constitutive law:
    Flags &Options=rValues.GetOptions();

    const Properties& MaterialProperties  = rValues.GetMaterialProperties();
    const Matrix&   DeformationGradientF  = rValues.GetDeformationGradientF();
    const double&   DeterminantF          = rValues.GetDeterminantF();

    const GeometryType&  DomainGeometry   = rValues.GetElementGeometry ();
    const Vector&        ShapeFunctions   = rValues.GetShapeFunctionsValues ();

    Vector& StrainVector                  = rValues.GetStrainVector();
    Vector& StressVector                  = rValues.GetStressVector();
    Matrix& ConstitutiveMatrix            = rValues.GetConstitutiveMatrix();

    //-----------------------------//

    //0.- Initialize parameters
    MaterialResponseVariables ElasticVariables;
    ElasticVariables.Identity = identity_matrix<double> ( 3 );

    ElasticVariables.SetElementGeometry(DomainGeometry);
    ElasticVariables.SetShapeFunctionsValues(ShapeFunctions);

    // Initialize Splited Parts: Isochoric and Volumetric stresses and constitutive tensors
    double voigtsize = StressVector.size();
    VectorSplit SplitStressVector;
    MatrixSplit SplitConstitutiveMatrix;

    //1.- Lame constants
    const double& YoungModulus          = MaterialProperties[YOUNG_MODULUS];
    const double& PoissonCoefficient    = MaterialProperties[POISSON_RATIO];

    ElasticVariables.LameLambda      = (YoungModulus*PoissonCoefficient)/((1+PoissonCoefficient)*(1-2*PoissonCoefficient));
    ElasticVariables.LameMu          =  YoungModulus/(2*(1+PoissonCoefficient));

    //2.- Thermal constants
    if( MaterialProperties.Has(THERMAL_EXPANSION_COEFFICIENT) )
      ElasticVariables.ThermalExpansionCoefficient = MaterialProperties[THERMAL_EXPANSION_COEFFICIENT];
    else
      ElasticVariables.ThermalExpansionCoefficient = 0;

    if( MaterialProperties.Has(REFERENCE_TEMPERATURE) )
      ElasticVariables.ReferenceTemperature = MaterialProperties[REFERENCE_TEMPERATURE];
    else
      ElasticVariables.ReferenceTemperature = 0;

    //3.-DeformationGradient Tensor 3D
    ElasticVariables.DeformationGradientF = DeformationGradientF;
    ElasticVariables.DeformationGradientF = Transform2DTo3D( ElasticVariables.DeformationGradientF );

    //4.-Determinant of the Total Deformation Gradient
    ElasticVariables.DeterminantF = DeterminantF;

    //5.-Right Cauchy Green tensor C
    Matrix RightCauchyGreen = prod(trans(ElasticVariables.DeformationGradientF),ElasticVariables.DeformationGradientF);

    //6.-Inverse of the Right Cauchy-Green tensor C: (stored in the CauchyGreenMatrix)
    ElasticVariables.traceCG = 0;
    ElasticVariables.CauchyGreenMatrix( 3, 3 );
    MathUtils<double>::InvertMatrix( RightCauchyGreen, ElasticVariables.CauchyGreenMatrix, ElasticVariables.traceCG);


    //8.-Green-Lagrange Strain:
    if(Options.Is( ConstitutiveLaw::COMPUTE_STRAIN ))
      {
	this->CalculateGreenLagrangeStrain(RightCauchyGreen, StrainVector);
      }
    
    //9.-Calculate Total PK2 stress
    SplitStressVector.Isochoric = ZeroVector(voigtsize);

    if( Options.Is(ConstitutiveLaw::COMPUTE_STRESS ) || Options.Is(ConstitutiveLaw::COMPUTE_CONSTITUTIVE_TENSOR ) )
      this->CalculateIsochoricStress( ElasticVariables, StressMeasure_PK2, SplitStressVector.Isochoric );

    Vector IsochoricStressVector = SplitStressVector.Isochoric;

    if( Options.Is( ConstitutiveLaw::COMPUTE_STRESS ) )
      {

	SplitStressVector.Volumetric = ZeroVector(voigtsize);

	this->CalculateVolumetricStress ( ElasticVariables, SplitStressVector.Volumetric );

	//PK2 Stress:
	StressVector = SplitStressVector.Isochoric + SplitStressVector.Volumetric;
	
	if( Options.Is(ConstitutiveLaw::ISOCHORIC_TENSOR_ONLY ) )
	  {
	    StressVector = SplitStressVector.Isochoric;
	  }
	else if( Options.Is(ConstitutiveLaw::VOLUMETRIC_TENSOR_ONLY ) )
	  {
	    StressVector = SplitStressVector.Volumetric;
	  }
	
      }

    //10.-Calculate Constitutive Matrix related to Total PK2 stress    
    if( Options.Is( ConstitutiveLaw::COMPUTE_CONSTITUTIVE_TENSOR ) )
      {

	//initialize constitutive tensors
	ConstitutiveMatrix.clear();
	SplitConstitutiveMatrix.Isochoric  = ConstitutiveMatrix;
	SplitConstitutiveMatrix.Volumetric = ConstitutiveMatrix;
	
	Matrix IsoStressMatrix = MathUtils<double>::StressVectorToTensor( IsochoricStressVector );

	this->CalculateIsochoricConstitutiveMatrix ( ElasticVariables, IsoStressMatrix, SplitConstitutiveMatrix.Isochoric );

	this->CalculateVolumetricConstitutiveMatrix ( ElasticVariables, SplitConstitutiveMatrix.Volumetric );

	//if( Options.Is(ConstitutiveLaw::TOTAL_TENSOR ) )
	ConstitutiveMatrix = SplitConstitutiveMatrix.Isochoric + SplitConstitutiveMatrix.Volumetric;

	if( Options.Is(ConstitutiveLaw::ISOCHORIC_TENSOR_ONLY ) )
	  {
	    ConstitutiveMatrix = SplitConstitutiveMatrix.Isochoric;
	  }
	else if( Options.Is(ConstitutiveLaw::VOLUMETRIC_TENSOR_ONLY ) )
	  {
	    ConstitutiveMatrix = SplitConstitutiveMatrix.Volumetric;
	  }
	
      }
    

    // std::cout<<" Constitutive "<<ConstitutiveMatrix<<std::endl;
    // std::cout<<" Stress "<<StressVector<<std::endl;

    //-----------------------------//
}
Exemple #28
0
/*------------------------------------------*/
int main ( int argc , char ** argv ) {

  // display:
  Display out ( std::cout );
  out.precision ( DISPLAY_PRECISION_STD );

  // NOMAD initializations:
  begin ( argc , argv );

  try {

    // usage:
    if ( argc != 4 ) {
      cerr << "\nusage: multi param.txt nb_circles nb_mads_runs\n\n";
      return 1;
    }

    int NBC = atoi(argv[2] );

    if ( NBC < 4 ) {
      cerr << "\nthe number of circles must be > 3\n\n";
      return 1;
    }

    int   N = 2*NBC-3;
    //int   M = ( NBC * ( NBC + 1 ) - 8 ) / 2;
    int   M = 2;

    // list of x0 points (LH strategy is used):
    // -----------------

    vector<Point *> x0_pts;

    // srand ( static_cast<int> ( time(0) ) );
    srand(0);
    rand();

    int i;
    int nb_mads_runs = atoi ( argv[3] );

    LH_x0 ( N , nb_mads_runs , x0_pts );

    // read best_x.txt:
    ifstream fin ( "best_x.txt");

    if ( !fin.fail() )
      for ( int i = 0 ; i < N ; ++i )
        fin >> (*x0_pts[0])[i];

    fin.close();

    // display all starting points:
    out << endl;
    for ( int j = 0 ; j < nb_mads_runs ; ++j )
      out << "starting point # " << j << ": ( " << *x0_pts[j] << " )" << endl;
    out << endl;

    // parameters creation:
    // --------------------
    Parameters param ( out );

    param.set_DIMENSION (N);
    vector<bb_output_type> bbot (M+1);
    for ( i = 0 ; i < M ; ++i )
      bbot[i] = PB;
    bbot[M] = OBJ;
    param.set_BB_OUTPUT_TYPE ( bbot );

    Point lb ( N , LB );
    Point ub ( N , UB );
    param.set_LOWER_BOUND ( lb );
    param.set_UPPER_BOUND ( ub );

    param.read ( argv[1] );

    param.set_DISPLAY_DEGREE (0);

    param.set_X0 ( *x0_pts[0] );

    // parameters check:
    param.check();

    // out << param << endl;

    // custom evaluator creation:
    My_Evaluator ev ( param , NBC , M );

    const Eval_Point * cur_x;
    Point              best_x (N);
    Double             best_f = INF , worst_f = 0.0 , avg_f = 0.0;

    // MADS runs:
    // ----------
    int bbe = 0;
    i = 0;
    while ( true ) {

      // algorithm creation:
      Mads mads ( param , &ev );
      mads.run();

      bbe += mads.get_cache().size();

      // displays and remember the best point:
      out << "run #" << setw(2) << i << ": ";
      cur_x = mads.get_best_feasible();
      if ( cur_x ) {

	out << "f=" << cur_x->get_f() << endl;

        if ( cur_x->get_f() < best_f ) {

	  best_f = cur_x->get_f();
	  best_x = *cur_x;
	}

	if ( cur_x->get_f() > worst_f )
	  worst_f = cur_x->get_f();

	avg_f += cur_x->get_f();

      }
      else
	out << "NULL" << endl;

      if ( ++i == nb_mads_runs )
	break;

      // preparation of next run:
      mads.reset();
      param.reset_X0();
      param.set_X0 ( *x0_pts[i] );
      param.check();
    }

    // display the solution:
    out << endl << "bb eval : " << bbe << endl
	<< "best    : " << best_f;
    out << endl
	<< "worst   : " << worst_f << endl
	<< "solution: ";
    out << "x = ( ";
    best_x.display ( out , " " , -1 , -1 );
    out << " ) f(x) = " << best_f.value();
    out << endl << endl;

    ofstream fout ( "best_x.txt" );
    fout << setprecision(32);
    best_x.display ( fout , " " , -1 , -1 );
    fout.close();

    // delete x0 points:
    for ( i = 0 ; i < nb_mads_runs ; ++i )
      delete x0_pts[i];
  }
  catch ( exception & e ) {
    cerr << "\nNOMAD has been interrupted (" << e.what() << ")\n\n";
  }

  end();

  return EXIT_SUCCESS;
}
Exemple #29
0
void kTpemHamiltonian (Geometry const &geometry, DynVars const &dynVars,
		 tpem_sparse *matrix,Parameters const &ether,Aux &aux,int type)
{
	int	row, col, volume, i = 0, p;
	double	a=aux.varTpem_a, b=aux.varTpem_b, tmp;
	int	j,k,dir;
	volume = ether.linSize;
	int level,gamma1,gamma2;
	vector<MatType> jmatrix(36,0), ymatrix(36,0);
        
	  if (ether.isSet("adjusttpembounds")) {
                a=1.0; b=0.0;
        }

	row=0;
	for (gamma1=0;gamma1<6;gamma1++) {
			for (p = 0; p < volume; p++, row++) {
			
			auxCreateJmatrix(jmatrix,dynVars,ether,p),auxCreateYmatrix(ymatrix,dynVars,ether,p);

	
			matrix->rowptr[row] = i;
			matrix->colind[i] = row;		
			tmp =real(jmatrix[gamma1+6*gamma1])*double(ether.modulus[p]) + ether.potential[p]+real(ymatrix[gamma1+6*gamma1]);
//                        tmp =real(jmatrix[gamma1+6*gamma1])*double(ether.modulus[p]) + ether.potential[p];
  			
			matrix->values[i] = (tmp-b)/a; /* -b because it's diagonal */
			i++;
			
				
			for (j = 0; j <  geometry.z(p); j++) {	
				k = geometry.neighbor(p,j);
				dir = geometry.scalarDirection(p,k,j);
//                               for (gamma1=0;gamma1<ether.numberOfOrbitals;gamma1++) {
				for (gamma2=0;gamma2<6;gamma2++) {
					matrix->colind[i]=k+gamma2*volume;
					matrix->values[i]=ether.bandHoppings[gamma1+gamma2*6+36*dir]/a;
					i++;
				}
//			}
			
                     }
			
			for (gamma2=0;gamma2<6;gamma2++) {
				if (gamma1==gamma2) continue;
				matrix->colind[i]=p + gamma2*volume;
				matrix->values[i]=jmatrix[gamma1+6*gamma2]*double(ether.modulus[p])/a;
				i++;
			}
			
		}
	}
						
				
			
	if (i!=ether.nonzero) {
		cerr<<"i="<<i<<" but nonzero="<<ether.nonzero<<endl;
		cerr<<"At this point: "<<__FILE__<<" "<<__LINE__<<endl;
		exit(1);
	}
	
		
}
Exemple #30
0
FuncDeclaration *StructDeclaration::buildOpEquals(Scope *sc)
{
    Dsymbol *eq = search_function(this, Id::eq);
    if (eq)
    {
        for (size_t i = 0; i <= 1; i++)
        {
            Expression *e =
                i == 0 ? new NullExp(loc, type->constOf())  // dummy rvalue
                       : type->constOf()->defaultInit();    // dummy lvalue
            Expressions *arguments = new Expressions();
            arguments->push(e);

            // check identity opEquals exists
            FuncDeclaration *fd = eq->isFuncDeclaration();
            if (fd)
            {   fd = fd->overloadResolve(loc, e, arguments, 1);
                if (fd && !(fd->storage_class & STCdisable))
                    return fd;
            }

            TemplateDeclaration *td = eq->isTemplateDeclaration();
            if (td)
            {   fd = td->deduceFunctionTemplate(sc, loc, NULL, e, arguments, 1);
                if (fd && !(fd->storage_class & STCdisable))
                    return fd;
            }
        }
        return NULL;
    }

    if (!needOpEquals())
        return NULL;

    //printf("StructDeclaration::buildOpEquals() %s\n", toChars());

    Parameters *parameters = new Parameters;
    parameters->push(new Parameter(STCin, type, Id::p, NULL));
    TypeFunction *tf = new TypeFunction(parameters, Type::tbool, 0, LINKd);
    tf->mod = MODconst;
    tf = (TypeFunction *)tf->semantic(loc, sc);

    FuncDeclaration *fop = new FuncDeclaration(loc, 0, Id::eq, STCundefined, tf);

    Expression *e = NULL;
    /* Do memberwise compare
     */
    //printf("\tmemberwise compare\n");
    for (size_t i = 0; i < fields.dim; i++)
    {
        Dsymbol *s = fields.tdata()[i];
        VarDeclaration *v = s->isVarDeclaration();
        assert(v && v->storage_class & STCfield);
        if (v->storage_class & STCref)
            assert(0);                  // what should we do with this?
        // this.v == s.v;
        EqualExp *ec = new EqualExp(TOKequal, loc,
            new DotVarExp(loc, new ThisExp(loc), v, 0),
            new DotVarExp(loc, new IdentifierExp(loc, Id::p), v, 0));
        if (e)
            e = new AndAndExp(loc, e, ec);
        else
            e = ec;
    }
    if (!e)
        e = new IntegerExp(loc, 1, Type::tbool);
    fop->fbody = new ReturnStatement(loc, e);

    members->push(fop);
    fop->addMember(sc, this, 1);

    sc = sc->push();
    sc->stc = 0;
    sc->linkage = LINKd;

    fop->semantic(sc);

    sc->pop();

    //printf("-StructDeclaration::buildOpEquals() %s\n", toChars());

    return fop;
}