void Pair::write_file(int narg, char **arg)
{
  if (narg < 8) error->all(FLERR,"Illegal pair_write command");
  if (single_enable == 0)
    error->all(FLERR,"Pair style does not support pair_write");

  // parse arguments

  int itype = atoi(arg[0]);
  int jtype = atoi(arg[1]);
  if (itype < 1 || itype > atom->ntypes || jtype < 1 || jtype > atom->ntypes)
    error->all(FLERR,"Invalid atom types in pair_write command");

  int n = atoi(arg[2]);

  int style;
  if (strcmp(arg[3],"r") == 0) style = RLINEAR;
  else if (strcmp(arg[3],"rsq") == 0) style = RSQ;
  else if (strcmp(arg[3],"bitmap") == 0) style = BMP;
  else error->all(FLERR,"Invalid style in pair_write command");

  double inner = atof(arg[4]);
  double outer = atof(arg[5]);
  if (inner <= 0.0 || inner >= outer)
    error->all(FLERR,"Invalid cutoffs in pair_write command");

  // open file in append mode
  // print header in format used by pair_style table

  int me;
  MPI_Comm_rank(world,&me);
  FILE *fp;
  if (me == 0) {
    fp = fopen(arg[6],"a");
    if (fp == NULL) error->one(FLERR,"Cannot open pair_write file");
    fprintf(fp,"# Pair potential %s for atom types %d %d: i,r,energy,force\n",
            force->pair_style,itype,jtype);
    if (style == RLINEAR)
      fprintf(fp,"\n%s\nN %d R %g %g\n\n",arg[7],n,inner,outer);
    if (style == RSQ)
      fprintf(fp,"\n%s\nN %d RSQ %g %g\n\n",arg[7],n,inner,outer);
  }

  // initialize potentials before evaluating pair potential
  // insures all pair coeffs are set and force constants

  force->init();

  // if pair style = any of EAM, swap in dummy fp vector

  double eamfp[2];
  eamfp[0] = eamfp[1] = 0.0;
  double *eamfp_hold;

  Pair *epair = force->pair_match("eam",0);
  if (epair) epair->swap_eam(eamfp,&eamfp_hold);

  // if atom style defines charge, swap in dummy q vec

  double q[2];
  q[0] = q[1] = 1.0;
  if (narg == 10) {
    q[0] = atof(arg[8]);
    q[1] = atof(arg[9]);
  }
  double *q_hold;

  if (atom->q) {
    q_hold = atom->q;
    atom->q = q;
  }

  // evaluate energy and force at each of N distances

  int masklo,maskhi,nmask,nshiftbits;
  if (style == BMP) {
    init_bitmap(inner,outer,n,masklo,maskhi,nmask,nshiftbits);
    int ntable = 1 << n;
    if (me == 0)
      fprintf(fp,"\n%s\nN %d BITMAP %g %g\n\n",arg[7],ntable,inner,outer);
    n = ntable;
  }

  double r,e,f,rsq;
  union_int_float_t rsq_lookup;

  for (int i = 0; i < n; i++) {
    if (style == RLINEAR) {
      r = inner + (outer-inner) * i/(n-1);
      rsq = r*r;
    } else if (style == RSQ) {
      rsq = inner*inner + (outer*outer - inner*inner) * i/(n-1);
      r = sqrt(rsq);
    } else if (style == BMP) {
      rsq_lookup.i = i << nshiftbits;
      rsq_lookup.i |= masklo;
      if (rsq_lookup.f < inner*inner) {
        rsq_lookup.i = i << nshiftbits;
        rsq_lookup.i |= maskhi;
      }
      rsq = rsq_lookup.f;
      r = sqrt(rsq);
    }

    if (rsq < cutsq[itype][jtype]) {
      e = single(0,1,itype,jtype,rsq,1.0,1.0,f);
      f *= r;
    } else e = f = 0.0;
    if (me == 0) fprintf(fp,"%d %g %g %g\n",i+1,r,e,f);
  }

  // restore original vecs that were swapped in for

  double *tmp;
  if (epair) epair->swap_eam(eamfp_hold,&tmp);
  if (atom->q) atom->q = q_hold;

  if (me == 0) fclose(fp);
}
示例#2
0
文件: DFS_M.hpp 项目: arupa-loka/lrep
void DFS_M::dfs(int iRoot)
{
  Stack2< Pair<int,int> > fringe;
  //Queue< Pair<int,int> > fringe;

  fringe.push(Pair<int,int>(-1,iRoot));
  int precount = 0; // pre-order counter
  int poscount = 0; // post-order counter
  int inocount = 0; // in-order counter
  int P = -1;
  int forest=0;
  int cyclecount = 0; // number of cycles found so far
  
  while (precount < _graph.getVertexSize())
  { 
    while ( !fringe.empty() )
    {
      Pair<int,int> pair = fringe.getTop(); fringe.pop();
      int v0 = pair.first();
      int v1 = pair.second();
      
      if (v0==-2) {
        _postorder[v1]=poscount;
        ++poscount;
        continue;
      }

      if ( !_visited[v1] )
      {
        // first time we see this vertex, push a dummy edge on the fringe
        // before pushing all its children. When the dummy edge will be popped
        // that means all the subtrees rooted under this vertex v1, will have been
        // explored completely, and we can assign the postorder index to the vertex
        fringe.push(Pair<int,int>(-2,v1));
        _preorder[v1]=precount; ++precount;
        _visited[v1]=1;
        _parent[v1]=v0;
        _forest[v1]=forest;
  
        if ( v0 > -1 )
        {
          _matrix[v0][v1]='T';
        }
        //std::cout << "(" << v1 << ")" << std::endl;
    
        for ( GraphEdgeIter it = _graph.getEdgeIter(v1); !it.end(); ++it )
        {
          int v2 = *it;
          
          if (!_visited[v2]) {
            fringe.push(Pair<int,int>(v1,v2));
          } else { // already visited
            char edgeType = tagEdge(v1,v2);
            cycleCheck(edgeType, v1, v2, cyclecount);
          }
        }
      } else { // already visited
        char edgeType = tagEdge(v0,v1);
        cycleCheck(edgeType, v0, v1, cyclecount);
      }

    }

    if (fringe.empty() && precount<_graph.getVertexSize())
    {
      for (int i=0; i<_graph.getVertexSize(); ++i)
      {
          if (!_visited[i])
          {
            fringe.push(Pair<int,int>(-1,i));
            break;
          }
      }
      ++forest;
    }
  }
}
示例#3
0
void ComputeFEP::init()
{
    int i,j;

    if (!fepinitflag)    // avoid init to run entirely when called by write_data
        fepinitflag = 1;
    else return;

    // setup and error checks

    pairflag = 0;

    for (int m = 0; m < npert; m++) {
        Perturb *pert = &perturb[m];

        pert->ivar = input->variable->find(pert->var);
        if (pert->ivar < 0)
            error->all(FLERR,"Variable name for compute fep does not exist");
        if (!input->variable->equalstyle(pert->ivar))
            error->all(FLERR,"Variable for compute fep is of invalid style");

        if (force->pair == NULL)
            error->all(FLERR,"compute fep pair requires pair interactions");

        if (pert->which == PAIR) {
            pairflag = 1;

            Pair *pair = force->pair_match(pert->pstyle,1);
            if (pair == NULL) error->all(FLERR,"compute fep pair style "
                                             "does not exist");
            void *ptr = pair->extract(pert->pparam,pert->pdim);
            if (ptr == NULL)
                error->all(FLERR,"compute fep pair style param not supported");

            pert->array = (double **) ptr;

            // if pair hybrid, test that ilo,ihi,jlo,jhi are valid for sub-style

            if ((strcmp(force->pair_style,"hybrid") == 0 ||
                    strcmp(force->pair_style,"hybrid/overlay") == 0)) {
                PairHybrid *pair = (PairHybrid *) force->pair;
                for (i = pert->ilo; i <= pert->ihi; i++)
                    for (j = MAX(pert->jlo,i); j <= pert->jhi; j++)
                        if (!pair->check_ijtype(i,j,pert->pstyle))
                            error->all(FLERR,"compute fep type pair range is not valid for "
                                       "pair hybrid sub-style");
            }

        } else if (pert->which == ATOM) {
            if (pert->aparam == CHARGE) {
                if (!atom->q_flag)
                    error->all(FLERR,"compute fep requires atom attribute charge");
            }
        }
    }

    if (tailflag) {
        if (force->pair->tail_flag == 0)
            error->all(FLERR,"Compute fep tail when pair style does not "
                       "compute tail corrections");
    }

    // detect if package gpu is present

    int ifixgpu = modify->find_fix("package_gpu");
    if (ifixgpu >= 0) fixgpu = modify->fix[ifixgpu];

    if (comm->me == 0) {
        if (screen) {
            fprintf(screen, "FEP settings ...\n");
            fprintf(screen, "  temperature = %f\n", temp_fep);
            fprintf(screen, "  tail %s\n", (tailflag ? "yes":"no"));
            for (int m = 0; m < npert; m++) {
                Perturb *pert = &perturb[m];
                if (pert->which == PAIR)
                    fprintf(screen, "  %s %s %d-%d %d-%d\n", pert->pstyle, pert->pparam,
                            pert->ilo, pert->ihi, pert->jlo, pert->jhi);
                else if (pert->which == ATOM)
                    fprintf(screen, "  %d-%d charge\n", pert->ilo, pert->ihi);
            }
        }
        if (logfile) {
            fprintf(logfile, "FEP settings ...\n");
            fprintf(logfile, "  temperature = %f\n", temp_fep);
            fprintf(logfile, "  tail %s\n", (tailflag ? "yes":"no"));
            for (int m = 0; m < npert; m++) {
                Perturb *pert = &perturb[m];
                if (pert->which == PAIR)
                    fprintf(logfile, "  %s %s %d-%d %d-%d\n", pert->pstyle, pert->pparam,
                            pert->ilo, pert->ihi, pert->jlo, pert->jhi);
                else if (pert->which == ATOM)
                    fprintf(logfile, "  %d-%d charge\n", pert->ilo, pert->ihi);
            }
        }
    }

}
示例#4
0
void FixAdapt::init()
{
    int i,j;

    // setup and error checks

    anypair = 0;

    for (int m = 0; m < nadapt; m++) {
        Adapt *ad = &adapt[m];

        ad->ivar = input->variable->find(ad->var);
        if (ad->ivar < 0)
            error->all("Variable name for fix adapt does not exist");
        if (!input->variable->equalstyle(ad->ivar))
            error->all("Variable for fix adapt is invalid style");

        if (ad->which == PAIR) {
            anypair = 1;

            Pair *pair = force->pair_match(ad->pstyle,1);
            if (pair == NULL) error->all("Fix adapt pair style does not exist");
            void *ptr = pair->extract(ad->pparam,ad->pdim);
            if (ptr == NULL) error->all("Fix adapt pair style param not supported");

            ad->pdim = 2;
            if (ad->pdim == 0) ad->scalar = (double *) ptr;
            if (ad->pdim == 2) ad->array = (double **) ptr;

            // if pair hybrid, test that ilo,ihi,jlo,jhi are valid for sub-style

            if (ad->pdim == 2 && (strcmp(force->pair_style,"hybrid") == 0 ||
                                  strcmp(force->pair_style,"hybrid/overlay") == 0)) {
                PairHybrid *pair = (PairHybrid *) force->pair;
                for (i = ad->ilo; i <= ad->ihi; i++)
                    for (j = MAX(ad->jlo,i); j <= ad->jhi; j++)
                        if (!pair->check_ijtype(i,j,ad->pstyle))
                            error->all("Fix adapt type pair range is not valid for "
                                       "pair hybrid sub-style");
            }

        } else if (ad->which == KSPACE) {
            if (force->kspace == NULL)
                error->all("Fix adapt is incompatible with KSpace style");
            kspace_scale = (double *) force->kspace->extract("scale");

        } else if (ad->which == ATOM) {
            if (ad->aparam == DIAMETER) {
                if (!atom->radius_flag)
                    error->all("Fix adapt requires atom attribute diameter");
            }
        }
    }

    // make copy of original pair array values

    for (int m = 0; m < nadapt; m++) {
        Adapt *ad = &adapt[m];
        if (ad->which == PAIR && ad->pdim == 2) {
            for (i = ad->ilo; i <= ad->ihi; i++)
                for (j = MAX(ad->jlo,i); j <= ad->jhi; j++)
                    ad->array_orig[i][j] = ad->array[i][j];
        }
    }
}
int NeighborKokkos::init_lists_kokkos()
{
  int i;

  for (i = 0; i < nlist_host; i++) delete lists_host[i];
  delete [] lists_host;
  delete [] pair_build_host;
  delete [] stencil_create_host;
  nlist_host = 0;

  for (i = 0; i < nlist_device; i++) delete lists_device[i];
  delete [] lists_device;
  delete [] pair_build_device;
  delete [] stencil_create_device;
  nlist_device = 0;

  nlist = 0;
  for (i = 0; i < nrequest; i++) {
    if (requests[i]->kokkos_device) nlist_device++;
    else if (requests[i]->kokkos_host) nlist_host++;
    else nlist++;
  }

  lists_host = new NeighListKokkos<LMPHostType>*[nrequest];
  pair_build_host = new PairPtrHost[nrequest];
  stencil_create_host = new StencilPtrHost[nrequest];
  for (i = 0; i < nrequest; i++) {
    lists_host[i] = NULL;
    pair_build_host[i] = NULL;
    stencil_create_host[i] = NULL;
  }

  for (i = 0; i < nrequest; i++) {
    if (!requests[i]->kokkos_host) continue;
    lists_host[i] = new NeighListKokkos<LMPHostType>(lmp);
    lists_host[i]->index = i;
    lists_host[i]->dnum = requests[i]->dnum;
    if (requests[i]->pair) {
      Pair *pair = (Pair *) requests[i]->requestor;
      pair->init_list(requests[i]->id,lists_host[i]);
    }
  }

  lists_device = new NeighListKokkos<LMPDeviceType>*[nrequest];
  pair_build_device = new PairPtrDevice[nrequest];
  stencil_create_device = new StencilPtrDevice[nrequest];
  for (i = 0; i < nrequest; i++) {
    lists_device[i] = NULL;
    pair_build_device[i] = NULL;
    stencil_create_device[i] = NULL;
  }

  for (i = 0; i < nrequest; i++) {
    if (!requests[i]->kokkos_device) continue;
    lists_device[i] = new NeighListKokkos<LMPDeviceType>(lmp);
    lists_device[i]->index = i;
    lists_device[i]->dnum = requests[i]->dnum;
    if (requests[i]->pair) {
      Pair *pair = (Pair *) requests[i]->requestor;
      pair->init_list(requests[i]->id,lists_device[i]);
    }
  }

  // 1st time allocation of xhold

  if (dist_check)
      xhold = DAT::tdual_x_array("neigh:xhold",maxhold);

  // return # of non-Kokkos lists

  return nlist;
}
示例#6
0
void FixAdaptFEP::init()
{
  int i,j;

  // setup and error checks

  anypair = 0;

  for (int m = 0; m < nadapt; m++) {
    Adapt *ad = &adapt[m];

    ad->ivar = input->variable->find(ad->var);
    if (ad->ivar < 0)
      error->all(FLERR,"Variable name for fix adapt/fep does not exist");
    if (!input->variable->equalstyle(ad->ivar))
      error->all(FLERR,"Variable for fix adapt/fep is invalid style");

    if (ad->which == PAIR) {
      anypair = 1;

      Pair *pair = force->pair_match(ad->pstyle,1);
      if (pair == NULL) error->all(FLERR,"Fix adapt/fep pair style does not exist");
      void *ptr = pair->extract(ad->pparam,ad->pdim);
      if (ptr == NULL) 
        error->all(FLERR,"Fix adapt/fep pair style param not supported");

      ad->pdim = 2;
      if (ad->pdim == 0) ad->scalar = (double *) ptr;
      if (ad->pdim == 2) ad->array = (double **) ptr;

      // if pair hybrid, test that ilo,ihi,jlo,jhi are valid for sub-style

      if (ad->pdim == 2 && (strcmp(force->pair_style,"hybrid") == 0 ||
                            strcmp(force->pair_style,"hybrid/overlay") == 0)) {
        PairHybrid *pair = (PairHybrid *) force->pair;
        for (i = ad->ilo; i <= ad->ihi; i++)
          for (j = MAX(ad->jlo,i); j <= ad->jhi; j++)
            if (!pair->check_ijtype(i,j,ad->pstyle))
              error->all(FLERR,"Fix adapt/fep type pair range is not valid for "
                         "pair hybrid sub-style");
      }

    } else if (ad->which == KSPACE) {
      if (force->kspace == NULL)
        error->all(FLERR,"Fix adapt/fep kspace style does not exist");
      kspace_scale = (double *) force->kspace->extract("scale");

    } else if (ad->which == ATOM) {
      if (ad->aparam == DIAMETER) {
        if (!atom->radius_flag)
          error->all(FLERR,"Fix adapt/fep requires atom attribute diameter");
      }
      if (ad->aparam == CHARGE) {
        if (!atom->q_flag)
          error->all(FLERR,"Fix adapt/fep requires atom attribute charge");
      }
    }
  }

  // make copy of original pair array values

  for (int m = 0; m < nadapt; m++) {
    Adapt *ad = &adapt[m];
    if (ad->which == PAIR && ad->pdim == 2) {
      for (i = ad->ilo; i <= ad->ihi; i++)
        for (j = MAX(ad->jlo,i); j <= ad->jhi; j++)
          ad->array_orig[i][j] = ad->array[i][j];
    }
  }

#ifdef ADAPT_DEBUG
  if (comm->me == 0 && screen) {
    for (int m = 0; m < nadapt; m++) {
      Adapt *ad = &adapt[m];
      if (ad->which == PAIR && ad->pdim == 2) {
        fprintf(screen, "###ADAPT original %s %s\n", ad->pstyle, ad->pparam);
        fprintf(screen, "###ADAPT  I  J   old_param\n");
        for (i = ad->ilo; i <= ad->ihi; i++)
          for (j = MAX(ad->jlo,i); j <= ad->jhi; j++)
            fprintf(screen, "###ADAPT %2d %2d %9.5f\n", i, j,
                    ad->array_orig[i][j]);
      }
    }
  }
#endif

}
bool linearInterpolationWeights::integrationWeights
(
    const scalar t1,
    const scalar t2,
    labelList& indices,
    scalarField& weights
) const
{
    if (t2 < t1-VSMALL)
    {
        FatalErrorIn("linearInterpolationWeights::integrationWeights(..)")
            << "Integration should be in positive direction."
            <<  " t1:" << t1 << " t2:" << t2
            << exit(FatalError);
    }

    // Currently no fancy logic on cached index like in value

    //- Find lower or equal index
    label i1 = findLower(samples_, t1, 0, lessEqOp<scalar>());
    //- Find lower index
    label i2 = findLower(samples_, t2);

    // For now just fail if any outside table
    if (i1 == -1 || i2 == samples_.size()-1)
    {
        FatalErrorIn("linearInterpolationWeights::integrationWeights(..)")
            << "Integrating outside table " << samples_[0] << ".."
            << samples_.last() << " not implemented."
            << " t1:" << t1 << " t2:" << t2 << exit(FatalError);
    }

    label nIndices = i2-i1+2;


    // Determine if indices already correct
    bool anyChanged = false;

    if (nIndices != indices.size())
    {
        anyChanged = true;
    }
    else
    {
        // Closer check

        label index = i1;
        forAll(indices, i)
        {
            if (indices[i] != index)
            {
                anyChanged = true;
                break;
            }
            index++;
        }
    }

    indices.setSize(nIndices);
    weights.setSize(nIndices);
    weights = 0.0;

    // Sum from i1+1 to i2+1
    for (label i = i1+1; i <= i2; i++)
    {
        scalar d = samples_[i+1]-samples_[i];
        indices[i-i1] = i;
        weights[i-i1] += 0.5*d;
        indices[i+1-i1] = i+1;
        weights[i+1-i1] += 0.5*d;
    }

    // Add from i1 to t1
    {
        Pair<scalar> i1Tot1 = integrationWeights(i1, t1);
        indices[0] = i1;
        weights[0] += i1Tot1.first();
        indices[1] = i1+1;
        weights[1] += i1Tot1.second();
    }

    // Subtract from t2 to i2+1
    {
        Pair<scalar> wghts = integrationWeights(i2, t2);
        indices[i2-i1] = i2;
        weights[i2-i1] += -wghts.first();
        indices[i2-i1+1] = i2+1;
        weights[i2-i1+1] += -wghts.second();
    }

    return anyChanged;
}
int ComputeGranLocal::compute_pairs(int flag)
{
  int i,j,m,n,ii,jj,inum,jnum,itype,jtype;
  double xtmp,ytmp,ztmp,delx,dely,delz;
  double rsq,eng,fpair,factor_coul,factor_lj;
  int *ilist,*jlist,*numneigh,**firstneigh;
  double *ptr;

  double **x = atom->x;
  int *type = atom->type;
  int *mask = atom->mask;
  int nlocal = atom->nlocal;
  double *special_coul = force->special_coul;
  double *special_lj = force->special_lj;
  int newton_pair = force->newton_pair;

  // invoke half neighbor list (will copy or build if necessary)

  if (flag == 0) neighbor->build_one(list->index);

  inum = list->inum;
  ilist = list->ilist;
  numneigh = list->numneigh;
  firstneigh = list->firstneigh;

  // loop over neighbors of my atoms
  // skip if I or J are not in group
  // for flag = 0, just count pair interactions within force cutoff
  // for flag = 1, calculate requested output fields

  Pair *pair = force->pair;
  double **cutsq = force->pair->cutsq;

  tagint *tag = atom->tag;

  m = 0;
  for (ii = 0; ii < inum; ii++) {
    i = ilist[ii];
    if (!(mask[i] & groupbit)) continue;

    xtmp = x[i][0];
    ytmp = x[i][1];
    ztmp = x[i][2];
    itype = type[i];
    jlist = firstneigh[i];
    jnum = numneigh[i];

    for (jj = 0; jj < jnum; jj++) {
      j = jlist[jj];
      factor_lj = special_lj[sbmask(j)];
      factor_coul = special_coul[sbmask(j)];
      j &= NEIGHMASK;

      if (!(mask[j] & groupbit)) continue;
      if (newton_pair == 0 && j >= nlocal) continue;

      delx = xtmp - x[j][0];
      dely = ytmp - x[j][1];
      delz = ztmp - x[j][2];
      rsq = delx*delx + dely*dely + delz*delz;
      jtype = type[j];
      if (rsq >= cutsq[itype][jtype]) continue;

      if (flag) {
        if (singleflag)
          eng = pair->single(i,j,itype,jtype,rsq,factor_coul,factor_lj,fpair);

        if (nvalues == 1) ptr = &vector[m];
        else ptr = array[m];

        for (n = 0; n < nvalues; n++) {
          switch (pstyle[n]) {
          case DIST:
            ptr[n] = sqrt(rsq);
            break;
          case ENG:
            ptr[n] = eng;
            break;
          case FORCE:
            ptr[n] = sqrt(rsq)*fpair;
            break;
          case FX:
            ptr[n] = delx*fpair;
            break;
          case FY:
            ptr[n] = dely*fpair;
            break;
          case FZ:
            ptr[n] = delz*fpair;
            break;
          case PN:
            ptr[n] = pair->svector[pindex[n]];
            break;
          case TAG1:
            ptr[n] = tag[i];
            break;
          case TAG2:
            ptr[n] = tag[j];
            break;
          }
        }
      }

      m++;
    }
  }

  return m;
}
void PassingChallengePlay::executePlay(VisionData* vision, RobocupStrategyData* rsd) 
{
  RobotIndex r0=ROBOT0;
  RobotIndex r1=ROBOT1;
  
  Pair ballLoc=getBallLocation(*vision);
  ///----
  for(RobotIndex robotID = r0; robotID < ROBOT2; robotID++){
    Pair robotLoc=getLocation(robotID,*vision,rsd->getSystemParams());
    Pair otherPos;
    int side;
    if(robotID == r0){
      otherPos=getLocation(r1,*vision,rsd->getSystemParams());
      side=side0;
    }else{
      otherPos=getLocation(r0,*vision,rsd->getSystemParams());
      side=side1;
    }

    if((ballLoc.getX() > rsd->getSystemParams().field.HALF_LINE &&
        robotID==r0) ||
       (ballLoc.getX() < rsd->getSystemParams().field.HALF_LINE &&
        robotID==r1))
    {
      //ball on our side
      if(friendlyHasPossession(robotID,rsd->getSystemParams())){
        //go kick
        if(-robotLoc.getY()*side > (rsd->getSystemParams().field.SPLIT_LINE + .5f)){
          //we're there, kick
          rsd->getDestination(robotID)->setKick(KICK_PASS);

        }else{
          //not there yet.  
          rsd->getDestination(robotID)->setDribble(DRIBBLE_DEFAULT);
          rsd->getDestination(robotID)->setVerticalDribble(V_DRIBBLE_DEFAULT);
          //head across
          float backup=.3f;
          if(robotID == r1){
            rsd->getDestination(robotID)->setPos(rsd->getSystemParams().field.HALF_LINE - backup,-side*1.0f);
            rsd->getDestination(robotID)->setRotation(0.0f);
          }else{
            rsd->getDestination(robotID)->setPos(rsd->getSystemParams().field.HALF_LINE + backup,-side*1.0f);
            rsd->getDestination(robotID)->setRotation(PI);
          }
        }
      
      }else{
        //go grab ball
        if(!rsd->getStrategyModule().getSkillSet(robotID)->getSkill(AcquirePossessionSkill::skillNum)->isInitialized()){
          rsd->getStrategyModule().getSkillSet(robotID)->getSkill(AcquirePossessionSkill::skillNum)->initialize();
        }
        rsd->getStrategyModule().getSkillSet(robotID)->getSkill(AcquirePossessionSkill::skillNum)->run();
        rsd->getDestination(robotID)->setDribble(DRIBBLE_DEFAULT);
        rsd->getDestination(robotID)->setVerticalDribble(V_DRIBBLE_DEFAULT);
        rsd->getDestination(robotID)->setKick(NO_KICK);
        rsd->getDestination(robotID)->setSpeed(GOALIE_SPEED);

      }


    }else{
        int side;
        if(ballLoc.getY() > rsd->getSystemParams().field.SPLIT_LINE){
          side=1;
        }else{
          side=-1;
        }
        if(robotID == r0){
          side0=side;
        }else{
          side1=side;
        }

        float backup=.5f;
        if(robotID == r1){
          rsd->getDestination(robotID)->setPos(rsd->getSystemParams().field.HALF_LINE - backup,otherPos.getY());
          rsd->getDestination(robotID)->setRotation(0.0f);
        }else{
          rsd->getDestination(robotID)->setPos(rsd->getSystemParams().field.HALF_LINE + backup,otherPos.getY());
          rsd->getDestination(robotID)->setRotation(PI);
        }
    }
  }

/*
  Pair aggressorPos(getLocation(robot1ID,*vision,rsd->getSystemParams()));
  Pair creatorPos(getLocation(robot2ID,*vision,rsd->getSystemParams()));
  Pair ballLoc(getBallLocation(*vision));

  if(ballLoc.getX() > rsd->getSystemParams().field.HALF_LINE)
  { 
     turn = LEFT;
  }
  else
  {
     turn = RIGHT;
  }
  
  
  if(state == KICK_RECEIVE && readTimer() > MAX_ELAPSED_TIME)
  {
    state = MOVE;
    uninitializeSkills();
  }
  if(state == MOVE && dist(getLocation(robot1ID,*vision,rsd->getSystemParams()),dest) < DISTANCE_THRESHOLD &&
     dist(getLocation(robot2ID,*vision,rsd->getSystemParams()),dest1) < DISTANCE_THRESHOLD && 
     (friendlyHasPossession(rsd->getRobotByPosition(AGGRESSOR),rsd->getSystemParams(),*vision, *rsd,true) ||
      friendlyHasPossession(rsd->getRobotByPosition(CREATOR),rsd->getSystemParams(),*vision, *rsd,true)))


  {
    state = ROTATE;
    uninitializeSkills();
  }
  if(state == ROTATE && ABS(getRotation(robot1ID,*vision,rsd->getSystemParams()) - PI  < ROTATION_THRESHOLD &&
     ABS(getRotation(robot2ID,*vision,rsd->getSystemParams()) - 0)  < ROTATION_THRESHOLD) &&
     (friendlyHasPossession(rsd->getRobotByPosition(AGGRESSOR),rsd->getSystemParams(),*vision, *rsd,true) ||
     friendlyHasPossession(rsd->getRobotByPosition(CREATOR),rsd->getSystemParams(),*vision, *rsd,true)))

  {
    state = KICK_RECEIVE;
    uninitializeSkills();
  }


  if(turn == LEFT)
  {
    if(state == KICK_RECEIVE)
    {
      kickSkill1->initialize(KICK_PASS);
      receiveSkill2->initialize(0.5f,dest1,false,true);
      kickSkill1->run();
      receiveSkill2->run();
      turn = RIGHT;
      dest.set(POINT_X,-POINT_Y);
      dest1.set(-POINT_X,-POINT_Y);
      startTimer();
      rsd->setMessage(robot1ID,"Kicking");
      rsd->setMessage(robot2ID,"Receiving");
    }
    if(state == MOVE)
    {
      
      rsd->getDestination(robot1ID)->setDribble(DRIBBLE_DEFAULT);
      rsd->getDestination(robot1ID)->setVerticalDribble(V_DRIBBLE_DEFAULT);
      if(getBallLocation(*vision).getX() < rsd->getSystemParams().field.HALF_LINE)
      {
        rsd->getDestination(robot2ID)->setPos(dest1);
        rsd->setMessage(robot2ID,"Moving to Receive");
      }  
      rsd->setMessage(robot1ID,"Moving with Ball to pass.");
      if(!friendlyHasPossession(rsd->getRobotByPosition(AGGRESSOR),rsd->getSystemParams(),*vision, *rsd,true))
      {
          acquireSkill1->initialize();
          acquireSkill1->run();
      }
      else
      {
          rsd->getDestination(robot1ID)->setPos(dest);
      }
    }

    if(state == ROTATE)
    {
      rsd->getDestination(robot2ID)->setRotation(angleBetween(creatorPos,aggressorPos));
      rsd->setMessage(robot2ID,"Rotating to receive");
      rsd->setMessage(robot1ID,"Rotating to kick");
      if(!friendlyHasPossession(rsd->getRobotByPosition(AGGRESSOR),rsd->getSystemParams(),*vision, *rsd,true))
      {
          acquireSkill1->initialize();
          acquireSkill1->run();
          rsd->getDestination(robot2ID)->setDribble(DRIBBLE_DEFAULT);
          rsd->getDestination(robot2ID)->setVerticalDribble(V_DRIBBLE_DEFAULT);
          rsd->getDestination(robot1ID)->setKick(NO_KICK);
      }
      else
      {
          rotateSkill1->initialize(dest1);
          rotateSkill1->run();
      }
    }
  }
  else
  {

    if(state == KICK_RECEIVE)
    {
      kickSkill2->initialize(KICK_PASS);
      receiveSkill1->initialize(0.5f,dest,false,true);
      kickSkill2->run();
      receiveSkill1->run();
      turn = LEFT;
      dest.set(POINT_X,POINT_Y);
      dest1.set(-POINT_X,POINT_Y);
      startTimer();
      rsd->setMessage(robot2ID,"Kicking");
      rsd->setMessage(robot1ID,"Receiving");
    }
    if(state == MOVE)
    {
      if(getBallLocation(*vision).getX() > rsd->getSystemParams().field.HALF_LINE)
      {
        rsd->getDestination(robot1ID)->setDribble(DRIBBLE_DEFAULT);
        rsd->getDestination(robot1ID)->setVerticalDribble(V_DRIBBLE_DEFAULT);
        rsd->getDestination(robot1ID)->setPos(dest);
        rsd->setMessage(robot1ID,"Moving to Receive");
      }  
      rsd->setMessage(robot2ID,"Moving with Ball to pass.");  
      if(!friendlyHasPossession(rsd->getRobotByPosition(CREATOR),rsd->getSystemParams(),*vision, *rsd,true))
      {
          acquireSkill2->initialize();
          acquireSkill2->run();
          rsd->getDestination(robot2ID)->setDribble(DRIBBLE_DEFAULT);
          rsd->getDestination(robot2ID)->setVerticalDribble(V_DRIBBLE_DEFAULT);
          rsd->getDestination(robot2ID)->setKick(NO_KICK);
      }
      else
      {
          rsd->getDestination(robot2ID)->setPos(dest1);
      }
    }

    if(state == ROTATE)
    {
      rsd->getDestination(robot1ID)->setRotation(angleBetween(creatorPos,aggressorPos));
      rsd->setMessage(robot1ID,"Rotating to receive");
      rsd->setMessage(robot2ID,"Rotating to kick");
      if(!friendlyHasPossession(rsd->getRobotByPosition(CREATOR),rsd->getSystemParams(),*vision, *rsd,true))
      {
          acquireSkill2->initialize();
          acquireSkill2->run();
      }
      else
      {
          rotateSkill2->initialize(dest1);
          rotateSkill2->run();
      }
    }


  }



    
*/
  

}
示例#10
0
inline void ICP::UpdateAndReject(Pair& init_f){
	
	double sigma=0.0;
	double mean=0.0;
	unsigned int N = data_indices.size() + init_f.size();
	
	Eigen::Vector4d point_s(0.0,0.0,0.0,1.0);
	Eigen::Vector4d point_d(0.0,0.0,0.0,1.0);
	
	std::vector<double> dists(N);
		
	//compute mean
	unsigned int k=0;
	for (unsigned int i=0 ; i < N; i++){
		
		if(i<data_indices.size()){
			point_s(0) = cloud_m->points[ model_indices[i] ].x;	
			point_s(1) = cloud_m->points[ model_indices[i] ].y;
			point_s(2) = cloud_m->points[ model_indices[i] ].z;
		
			point_d(0) = cloud_d->points[ data_indices[i] ].x;	
			point_d(1) = cloud_d->points[ data_indices[i] ].y;
			point_d(2) = cloud_d->points[ data_indices[i] ].z;
		}else{
			point_s(0) = cloud_m->points[ init_f[k].first ].x;	
			point_s(1) = cloud_m->points[ init_f[k].first ].y;
			point_s(2) = cloud_m->points[ init_f[k].first ].z;
		
			point_d(0) = cloud_d->points[ init_f[k].second ].x;	
			point_d(1) = cloud_d->points[ init_f[k].second ].y;
			point_d(2) = cloud_d->points[ init_f[k].second ].z;
			k++;
		}
		
		point_d = T*point_d;				
		
		dists[i]= (point_d - point_s).norm();
		mean = mean + dists[i];
	}
	
	mean = mean/N;
	
	//compute standart diviation
	for (unsigned int i=0; i < N; i++){
		sigma = sigma + (dists[i]-mean)*(dists[i]-mean);
	}
	
	sigma = sigma/N;
	sigma = sqrt(sigma);
	
	
	//How good is the registration
	if (mean<D)						//very good
		Dmax = mean + 3*sigma;
	else if (mean<3*D)				//good
		Dmax = mean + 2*sigma;
	else if (mean<6*D)				//bad
		Dmax = mean + sigma;
	else {							//very bad 
		std::vector<double> dists2 = dists;
		sort (dists2.begin(), dists2.end());
	
		if (dists2.size() % 2 == 0) {
			Dmax = (dists2[dists2.size()/2-1] + dists2[dists2.size()/2]) / 2.0;
		}else {
			Dmax = dists2[dists2.size()/2]; 
		}
	}
	
	//Update the maching
	k=0;
	unsigned int i=0;
	for (i=0 ; i <data_indices.size() ; i++){
		if (dists[i] < Dmax){
			model_indices[k] = model_indices[i];
			data_indices[k] = data_indices[i];
			k++;	
		}
	}
	
	model_indices.resize(k);
	data_indices.resize(k);	
		
	k=0;
	unsigned int j,l;
	for (j=i, l=0; j<N ; j++,l++){
		if (dists[j] < Dmax){
			init_f[k]= init_f[l];
			k++;	
		}
	}

	if(k!=init_f.size()) 
		init_f.resize(k);
	
}
示例#11
0
//procustres
inline void ICP::minimize(const Pair& init_f){
	
	Eigen::Vector3d centroide_model(0.0,0.0,0.0), centroide_data(0.0,0.0,0.0);
	Eigen::Matrix3d M;
	
	unsigned int N = data_indices.size() + init_f.size();
	
	Eigen::MatrixXd model(3,N);
	Eigen::MatrixXd  data(3,N);
	
		
	//calcula os centroides
	int k=0;
	for(unsigned int i=0; i<N; i++){
		
		if (i<data_indices.size()){
			model(0,i) = cloud_m->points[ model_indices[i] ].x;
			model(1,i) = cloud_m->points[ model_indices[i] ].y;
			model(2,i) = cloud_m->points[ model_indices[i] ].z;
		
			data(0,i) = cloud_d->points[ data_indices[i] ].x*T(0,0) + cloud_d->points[ data_indices[i] ].y*T(0,1) + cloud_d->points[ data_indices[i] ].z*T(0,2) + T(0,3);
			data(1,i) = cloud_d->points[ data_indices[i] ].x*T(1,0) + cloud_d->points[ data_indices[i] ].y*T(1,1) + cloud_d->points[ data_indices[i] ].z*T(1,2) + T(1,3);
			data(2,i) = cloud_d->points[ data_indices[i] ].x*T(2,0) + cloud_d->points[ data_indices[i] ].y*T(2,1) + cloud_d->points[ data_indices[i] ].z*T(2,2) + T(2,3);
		}else{

			model(0,i) = cloud_m->points[ init_f[k].first ].x;
			model(1,i) = cloud_m->points[ init_f[k].first ].y;
			model(2,i) = cloud_m->points[ init_f[k].first ].z;
		
			data(0,i) = cloud_d->points[ init_f[k].second ].x*T(0,0) + cloud_d->points[ init_f[k].second ].y*T(0,1) + cloud_d->points[ init_f[k].second ].z*T(0,2) + T(0,3);
			data(1,i) = cloud_d->points[ init_f[k].second ].x*T(1,0) + cloud_d->points[ init_f[k].second ].y*T(1,1) + cloud_d->points[ init_f[k].second ].z*T(1,2) + T(1,3);
			data(2,i) = cloud_d->points[ init_f[k].second ].x*T(2,0) + cloud_d->points[ init_f[k].second ].y*T(2,1) + cloud_d->points[ init_f[k].second ].z*T(2,2) + T(2,3);	
			k++;
		}
		
		centroide_model += model.block(0,i,3,1);
		centroide_data  +=  data.block(0,i,3,1);
	}
	
	centroide_data = centroide_data/N;
	centroide_model = centroide_model/N;
	
	
  //subtrai os centroides aos dados
	for (unsigned int i=0; i<N; i++){
		model.block(0,i,3,1) -= centroide_model;
		data.block(0,i,3,1) -= centroide_data;
	}
	
	
	//Determina a transformacao
	M = data*model.transpose();
	
	Eigen::JacobiSVD<Eigen::Matrix3d> svd(M, Eigen::ComputeFullU | Eigen::ComputeFullV);
	
	Eigen::Matrix3d U = svd.matrixU();
	Eigen::Matrix3d V = svd.matrixV();
	
	if (U.determinant()*V.determinant()<0) {
		for (int i=0; i<3; ++i) 
			V(i,2) *=-1;
	}
	
		
	Eigen::Matrix3d r = V * U.transpose();
	Eigen::Vector3d t = centroide_model - r * centroide_data;
	
	//~ T.block<3,3>(0,0) =  r*T.block<3,3>(0,0);
	//~ T.block<3,1>(0,3) += t; 
	T.block<3,1>(0,3) = T.block<3,3>(0,0)*t + T.block<3,1>(0,3); 
	T.block<3,3>(0,0) = T.block<3,3>(0,0)*r;
	
	
} 
示例#12
0
bool frameFieldBackgroundMesh2D::compute_RK_infos(double u,double v, double x, double y, double z, RK_form &infos)
{
    // check if point is in domain
    if (!inDomain(u,v)) return false;

    // get stored angle

    double angle_current = angle(u,v);

    // compute t1,t2: cross field directions

    // get the unit normal at that point
    GFace *face = dynamic_cast<GFace*>(gf);
    if(!face) {
        Msg::Error("Entity is not a face in background mesh");
        return false;
    }

    Pair<SVector3, SVector3> der = face->firstDer(SPoint2(u,v));
    SVector3 s1 = der.first();
    SVector3 s2 = der.second();
    SVector3 n = crossprod(s1,s2);
    n.normalize();
    SVector3 basis_u = s1;
    basis_u.normalize();
    SVector3 basis_v = crossprod(n,basis_u);
    // normalize vector t1 that is tangent to gf at uv
    SVector3 t1 = basis_u * cos(angle_current) + basis_v * sin(angle_current) ;
    t1.normalize();
    // compute the second direction t2 and normalize (t1,t2,n) is the tangent frame
    SVector3 t2 = crossprod(n,t1);
    t2.normalize();

    // get metric

    double L = size(u,v);
    infos.metricField = SMetric3(1./(L*L));
    FieldManager *fields = gf->model()->getFields();
    if(fields->getBackgroundField() > 0) {
        Field *f = fields->get(fields->getBackgroundField());
        if (!f->isotropic()) {
            (*f)(x,y,z, infos.metricField,gf);
        }
        else {
            L = (*f)(x,y,z,gf);
            infos.metricField = SMetric3(1./(L*L));
        }
    }
    double M = dot(s1,s1);
    double N = dot(s2,s2);
    double E = dot(s1,s2);
    // compute the first fundamental form i.e. the metric tensor at the point
    // M_{ij} = s_i \cdot s_j
    double metric[2][2] = {{M,E},{E,N}};

    // get sizes

    double size_1 = sqrt(1. / dot(t1,infos.metricField,t1));
    double size_2 = sqrt(1. / dot(t2,infos.metricField,t2));

    // compute covariant coordinates of t1 and t2 - cross field directions in parametric domain
    double covar1[2],covar2[2];
    // t1 = a s1 + b s2 -->
    // t1 . s1 = a M + b E
    // t1 . s2 = a E + b N --> solve the 2 x 2 system
    // and get covariant coordinates a and b
    double rhs1[2] = {dot(t1,s1),dot(t1,s2)};
    bool singular = false;
    if (!sys2x2(metric,rhs1,covar1)) {
        Msg::Info("Argh surface %d %g %g %g -- %g %g %g -- %g %g",gf->tag(),s1.x(),s1.y(),s1.z(),s2.x(),s2.y(),s2.z(),size_1,size_2);
        covar1[1] = 1.0;
        covar1[0] = 0.0;
        singular = true;
    }
    double rhs2[2] = {dot(t2,s1),dot(t2,s2)};
    if (!sys2x2(metric,rhs2,covar2)) {
        Msg::Info("Argh surface %d %g %g %g -- %g %g %g",gf->tag(),s1.x(),s1.y(),s1.z(),s2.x(),s2.y(),s2.z());
        covar2[0] = 1.0;
        covar2[1] = 0.0;
        singular = true;
    }

    // transform the sizes with respect to the metric
    // consider a vector v of size 1 in the parameter plane
    // its length is sqrt (v^T M v) --> if I want a real size
    // of size1 in direction v, it should be sqrt(v^T M v) * size1
    double l1 = sqrt(covar1[0]*covar1[0]+covar1[1]*covar1[1]);
    double l2 = sqrt(covar2[0]*covar2[0]+covar2[1]*covar2[1]);

    covar1[0] /= l1;
    covar1[1] /= l1;
    covar2[0] /= l2;
    covar2[1] /= l2;

    double size_param_1  = size_1 / sqrt (  M*covar1[0]*covar1[0]+
                                            2*E*covar1[1]*covar1[0]+
                                            N*covar1[1]*covar1[1]);
    double size_param_2  = size_2 / sqrt (  M*covar2[0]*covar2[0]+
                                            2*E*covar2[1]*covar2[0]+
                                            N*covar2[1]*covar2[1]);
    if (singular) {
        size_param_1 = size_param_2 = std::min (size_param_1,size_param_2);
    }


    // filling form...

    infos.t1 = t1;
    infos.h.first  = size_1;
    infos.h.second = size_2;
    infos.paramh.first  = size_param_1;
    infos.paramh.second = size_param_2;
    infos.paramt1 = SPoint2(covar1[0],covar1[1]);
    infos.paramt2 = SPoint2(covar2[0],covar2[1]);
    infos.angle = angle_current;
    infos.localsize = L;
    infos.normal = n;

    return true;
}
示例#13
0
void frameFieldBackgroundMesh2D::computeCrossField(simpleFunction<double> &eval_diffusivity)
{
    angles.clear();

    DoubleStorageType _cosines4,_sines4;

    list<GEdge*> e;
    GFace *face = dynamic_cast<GFace*>(gf);
    if(!face) {
        Msg::Error("Entity is not a face in background mesh");
        return;
    }

    replaceMeshCompound(face, e);

    list<GEdge*>::const_iterator it = e.begin();

    for( ; it != e.end(); ++it ) {
        if (!(*it)->isSeam(face)) {
            for(unsigned int i = 0; i < (*it)->lines.size(); i++ ) {
                MVertex *v[2];
                v[0] = (*it)->lines[i]->getVertex(0);
                v[1] = (*it)->lines[i]->getVertex(1);
                SPoint2 p1,p2;
                reparamMeshEdgeOnFace(v[0],v[1],face,p1,p2);
                Pair<SVector3, SVector3> der = face->firstDer((p1+p2)*.5);
                SVector3 t1 = der.first();
                SVector3 t2 = der.second();
                SVector3 n = crossprod(t1,t2);
                n.normalize();
                SVector3 d1(v[1]->x()-v[0]->x(),v[1]->y()-v[0]->y(),v[1]->z()-v[0]->z());
                t1.normalize();
                d1.normalize();
                double _angle = myAngle (t1,d1,n);
                normalizeAngle (_angle);
                for (int i=0; i<2; i++) {
                    DoubleStorageType::iterator itc = _cosines4.find(v[i]);
                    DoubleStorageType::iterator its = _sines4.find(v[i]);
                    if (itc != _cosines4.end()) {
                        itc->second  = 0.5*(itc->second + cos(4*_angle));
                        its->second  = 0.5*(its->second + sin(4*_angle));
                    }
                    else {
                        _cosines4[v[i]] = cos(4*_angle);
                        _sines4[v[i]] = sin(4*_angle);
                    }
                }
            }
        }
    }

    propagateValues(_cosines4,eval_diffusivity,false);
    propagateValues(_sines4,eval_diffusivity,false);

    std::map<MVertex*,MVertex*>::iterator itv2 = _2Dto3D.begin();
    for ( ; itv2 != _2Dto3D.end(); ++itv2) {
        MVertex *v_2D = itv2->first;
        MVertex *v_3D = itv2->second;
        double angle = atan2(_sines4[v_3D],_cosines4[v_3D]) / 4.0;
        normalizeAngle (angle);
        angles[v_2D] = angle;
    }
}
示例#14
0
TEST(all, all)
{
    srand(time(NULL));
    g_log = new Logger("a.log");
    if (! g_log->Load())
    {
        return ;
    }
    bool b;

    Fmt fmt;
    b = fmt.Load("fmt.xml");
    EXPECT_EQ(b, true);
    if (! b)
    {
        return ;
    }

    Dat dat;
    b = dat.Load("dat.xml", &fmt, "", "");
    EXPECT_EQ(b, true);
    if (! b)
    {
        return ;
    }
    {
        RRMessage r;
        r.m_body = "4abcd3abc";
        QA* qa = dat.Match(&r, true, "");
        RRMessage resp;
        bool res = qa->Answer(&resp, &r);
        EXPECT_EQ(true, res);
    }

    {
        RRMessage r;
        //匹配zhangsan|1
        r.m_body = "zhangsan|1|[email protected]|zzz_HOME,yyy_MOBILE";
        QA* qa = dat.Match(&r, true, "");
        RRMessage resp;
        bool res = qa->Answer(&resp, &r);
        int i = 123;
        char buf[16];
        memcpy(buf, &i, sizeof(int));
        string b(buf, sizeof(int));
        EXPECT_EQ(resp.m_body, b + ",k1=k2;aaa-1");
        EXPECT_EQ(true, res);
    }
    {
        RRMessage r;
        //匹配reg:.*163.COM
        r.m_body = "zhangsan|3|[email protected]|zzz_HOME,yyy_MOBILE";
        QA* qa = dat.Match(&r, true, "");
        RRMessage resp;
        bool res = qa->Answer(&resp, &r);
        int i = 123;
        char buf[16];
        memcpy(buf, &i, sizeof(int));
        string b(buf, sizeof(int));
        EXPECT_EQ(resp.m_body, "k1=k2;aaa-3");
        EXPECT_EQ(true, res);
    }
    {
        RRMessage r;
        //匹配<abd
        r.m_body = "zhangsan|3|[email protected]|abc_HOME,yyy_MOBILE";
        QA* qa = dat.Match(&r, true, "");
        RRMessage resp;
        bool res = qa->Answer(&resp, &r);
        string e1 = "file=aaa;email=zs@f**k.com;a=1;b=";
        string e2 = "a=a1;b=b2|c=c3";
        bool t = false;
        if (e1 == resp.m_body)
        {
            t = true;
        }
        else if (e2 == resp.m_body)
        {
            t = true;
        }
        EXPECT_EQ(t, true);
        EXPECT_EQ(true, res);
    }
    {
        RRMessage r;
        //匹配reg:HOM*
        r.m_body = "zhangsan|3|[email protected]|zzz_HOME,yyy_MOBILE";
        QA* qa = dat.Match(&r, true, "");
        RRMessage resp;
        bool res = qa->Answer(&resp, &r);
        string e1 = "file=aaa;email=zs@f**k.com;a=1;b=";
        string e2 = "a=a1;b=b2|c=c3";
        bool t = false;
        if (e1 == resp.m_body)
        {
            t = true;
        }
        else if (e2 == resp.m_body)
        {
            t = true;
        }
        EXPECT_EQ(t, true);
        EXPECT_EQ(true, res);
    }
    {
        RRMessage r;
        //匹配yyy
        r.m_body = "zhangsan|3|[email protected]|zzz_HME,yyy_MOBILE";
        QA* qa = dat.Match(&r, true, "");
        RRMessage resp;
        bool res = qa->Answer(&resp, &r);
        string e = "b==b2;email==@3-yyy-bxx";
        EXPECT_EQ(e, resp.m_body);
        EXPECT_EQ(true, res);
    }
    {
        RRMessage r;
        //0x03abc4,defgzzz
        string data = "abc";
        string d2 = "defg";
        string tail = "zzz";
        int length = data.size();
        char buf[128];
        char *p = buf;
        memcpy(p, &length, sizeof(int));
        p += sizeof(int);
        strcpy(p, data.c_str());
        p += data.size();
        p += sprintf(p, "%d,", (int)d2.size());
        strcpy(p, d2.c_str());
        p += d2.size();
        strcpy(p, tail.c_str());
        p += tail.size();

        r.m_body = string(buf, p - buf);
        QA* qa = dat.Match(&r, true, "");
        RRMessage resp;
        bool res = qa->Answer(&resp, &r);
        if (! res)
        {
            EXPECT_EQ(0, 1);
            return ;
        }

        AddressBook ab;
        {
            Person* p = ab.add_person();
            p->set_name("zhangsan");
            p->set_id(3);
            p->set_email("*****@*****.**");
            Person::PhoneNumber* pp = p->add_phone();
            pp->set_number("010-11");
            pp->set_type(Person_PhoneType_WORK);
            pp = p->add_phone();
            pp->set_number("123");
            pp->set_type(Person_PhoneType_MOBILE);
        }
        {
            Person* p = ab.add_person();
            p->set_name("lisi");
            p->set_id(4);
        }
        string e;
        ab.SerializeToString(&e);

        EXPECT_EQ("abcd"+e, resp.m_body);
        EXPECT_EQ(true, res);
    }
    {
        RRMessage r;
        //0x03abc4,defgzzz
        string data = "abc";
        string d2 = "defgg";
        string tail = "zzz";
        int length = data.size();
        char buf[128];
        char *p = buf;
        memcpy(p, &length, sizeof(int));
        p += sizeof(int);
        strcpy(p, data.c_str());
        p += data.size();
        p += sprintf(p, "%d,", (int)d2.size());
        strcpy(p, d2.c_str());
        p += d2.size();
        strcpy(p, tail.c_str());
        p += tail.size();

        r.m_body = string(buf, p - buf);
        QA* qa = dat.Match(&r, true, "");
        if (! qa)
        {
            EXPECT_EQ(0, 1);
            return ;
        }
        RRMessage resp;
        bool res = qa->Answer(&resp, &r);
        if (! res)
        {
            EXPECT_EQ(0, 1);
            return ;
        }

        AddressBook ab;
        {
            Person* p = ab.add_person();
            p->set_name("zhangsan");
            p->set_id(3);
            p->set_email("*****@*****.**");
            Person::PhoneNumber* pp = p->add_phone();
            pp->set_number("010-11");
            pp->set_type(Person_PhoneType_WORK);
            pp = p->add_phone();
            pp->set_number("123");
            pp->set_type(Person_PhoneType_MOBILE);
        }
        {
            Person* p = ab.add_person();
            p->set_name("lisi");
            p->set_id(4);
        }
        string e;
        ab.SerializeToString(&e);

        EXPECT_EQ(e, resp.m_body);
        EXPECT_EQ(true, res);
    }
    {
        RRMessage r;
        r.m_body = "100,200;100,300;100,400";
        QA* qa = dat.Match(&r, true, "");
        RRMessage resp;
        bool res = qa->Answer(&resp, &r);
        EXPECT_EQ("a==a1;b==b1-A-", resp.m_body);
        EXPECT_EQ(true, res);
    }
    {
        RRMessage r;
        string b1 = "hello";
        char buf[128];
        char* p = buf;
        p += sprintf(p, "k=key;v=val;a=");
        int len = b1.size();
        memcpy(p, &len, sizeof(int));
        p += sizeof(int);
        p += sprintf(p, ";b=%sb2v;c=cv", b1.c_str());

        r.m_body = string(buf, p - buf);

        QA* qa = dat.Match(&r, true, "");
        RRMessage resp;
        bool res = qa->Answer(&resp, &r);
        AddressBook ab;
        {
            Person* p = ab.add_person();
            p->set_name("len");
            p->set_id(len);
        }
        string e;
        ab.SerializeToString(&e);

        EXPECT_EQ(e, resp.m_body);
        EXPECT_EQ(true, res);
    }
    {
        RRMessage r;
        string s = "b=1;c=2;a=a1:1,a2:2;a=a2:3,a3:4|ddeee";
        r.m_body = s;

        QA* qa = dat.Match(&r, true, "");
        RRMessage resp;
        bool res = qa->Answer(&resp, &r);
        string e;
        string name = "";
        {
            AddressBook ab;
            {
                Person* p = ab.add_person();
                p->set_name("zhangsan");
                p->set_id(3333);
            }
            ab.SerializeToString(&name);
        }
        {
            AddressBook ab;
            {
                Person* p = ab.add_person();
                p->set_name(name);
                p->set_id(123);
            }
            ab.SerializeToString(&e);
        }

        EXPECT_EQ(e, resp.m_body);
        EXPECT_EQ(true, res);
    }
    {
        RRMessage r;
        string s;
        Pair p;
        p.set_key("3;abc12");
        p.set_value(111);
        p.SerializeToString(&s);
        r.m_body = s;

        QA* qa = dat.Match(&r, true, "");
        RRMessage resp;
        bool res = qa->Answer(&resp, &r);
        EXPECT_EQ("a==aa;email==xx-132-100", resp.m_body);
        EXPECT_EQ(true, res);
    }
    {
        RRMessage r;
        string s;
        AddressBook ab;

        Person* p = ab.add_person();
        p->set_name("zhangsan");
        p->set_id(3);
        p->set_email("*****@*****.**");
        Person::PhoneNumber* pn = p->add_phone();
        pn->set_number("010-111");
        pn->set_type(Person::MOBILE);

        ab.SerializeToString(&s);
        r.m_body = s;

        QA* qa = dat.Match(&r, true, "");
        RRMessage resp;
        bool res = qa->Answer(&resp, &r);
        EXPECT_EQ("mytypethis is pb", resp.m_body);
        EXPECT_EQ(true, res);
    }
    {
        RRMessage r;
        string s = "a=1;b=2;url=p.tanx.com%2Fex%3Fi%3D1%26b%3D2";
        r.m_body = s;

        QA* qa = dat.Match(&r, true, "");
        RRMessage resp;
        bool res = qa->Answer(&resp, &r);
        EXPECT_EQ("hello", resp.m_body);
        EXPECT_EQ(true, res);
    }
    {
        RRMessage r;

        string e;
        string name = "";
        {
            AddressBook ab;
            {
                Person* p = ab.add_person();
                p->set_name("zhangsan");
                p->set_id(3333);
                p->set_email("*****@*****.**");
                Person::PhoneNumber* pn = p->add_phone();
                pn->set_number("010");
                pn->set_type(Person::MOBILE);
                pn = p->add_phone();
                pn->set_number("012");
                pn->set_type(Person::HOME);
            }
            ab.SerializeToString(&name);
        }
        {
            AddressBook ab;
            {
                Person* p = ab.add_person();
                p->set_name(name);
                p->set_id(124);
                p->set_email("*****@*****.**");
                Person::PhoneNumber* pn = p->add_phone();
                pn->set_number("010");
                pn->set_type(Person::WORK);
            }
            ab.SerializeToString(&e);
        }
        char buf[16];
        int l = e.size();
        memcpy(buf, &l, sizeof(int));
        e = string(buf, sizeof(int)) + e;
        r.m_body = e + "1234,6,,78";

        QA* qa = dat.Match(&r, true, "");
        RRMessage resp;
        bool res = qa->Answer(&resp, &r);
        EXPECT_EQ("a==a1;b==b1-A-", resp.m_body);
        EXPECT_EQ(true, res);
    }
    {
        RRMessage r;
        string s = "a";
        r.m_body = s;

        QA* qa = dat.Match(&r, true, "");
        RRMessage resp;
        bool res = qa->Answer(&resp, &r);
        EXPECT_EQ("--", resp.m_body);
        EXPECT_EQ(true, res);
    }
    {
        RRMessage r;
        string s = "http%3A%2F%2F#http://www.baidu.com";
        r.m_body = s;

        QA* qa = dat.Match(&r, true, "");
        RRMessage resp;
        bool res = qa->Answer(&resp, &r);
        EXPECT_EQ("http%3A%2F%2F|http%3A%2F%2Fwww.baidu.com", resp.m_body);
        EXPECT_EQ(true, res);
    }
    {
        RRMessage r;
        string s = "http://xxx.com/ex?js-%7B%22a%22%20%3A%20%22av%22%2C%20%22b%22%20%3A%20%22bv_v1_v2%22%2C%20%22c%22%20%3A%20%5B%7B%22c1%22%20%3A%20%22c1v%22%7D%2C%20%7B%22c2%22%20%3A%20%22c2_v1_v2%22%7D%2C%20%7B%22c3%22%20%3A%20%5B%22c31_v1%22%2C%20%22c32_v2%22%2C%20%22c33_v3%22%5D%7D%5D%7D$k-123";
        r.m_body = s;

        QA* qa = dat.Match(&r, true, "");
        RRMessage resp;
        bool res = qa->Answer(&resp, &r);
        EXPECT_EQ("{\"a\":[{\"a1\":[11,111],\"a2\":22,\"b\":{\"b1\":[\"1b\",\"1.1b\"],\"b2\":\"b22\"}},{\"a1\":333,\"a2\":22,\"a3\":33,\"b\":{\"b1\":[\"b-1\",\"1.1-b\"],\"b2\":\"b22\"}}]}", resp.m_body);
        EXPECT_EQ(true, res);
    }
    {
        RRMessage r;

        string eq, ea;
        string name = "";
        {
            Person* p = new Person;
            p->set_name("xxnousex");
            p->set_id(1223456);
            p->set_goodman(true);
            p->SerializeToString(&eq);
        }
        {
            Person* p = new Person();
            p->set_name("xxx");
            p->set_id(9876103);
            p->set_goodman(false);
            p->SerializeToString(&ea);
        }
        r.m_body = eq;

        QA* qa = dat.Match(&r, true, "");
        RRMessage resp;
        bool res = qa->Answer(&resp, &r);
        EXPECT_EQ(ea, resp.m_body);
        EXPECT_EQ(true, res);
    }
}
void pair_Int_Int(){
    Pair<int,int> *pair = new Pair<int,int>(100, 75);
    cout << "Pair < "<< pair->component1() << " , " << pair->component2() <<" >" << endl;
}
//===============================================================================
//Execute the skill.  This is the main part of the skill, where you tell the
//robot how to perform the skill.
void SupplementThreeManSkill::execute()
{    
  ///If not initialized, dont do anything!
  if(!initialized) 
  {
    return;  
  }

  //if the ball is close enough to defenisve players, move next to 
  //the defensive player that is closer to the ball
  //since he'll become the aggresor and move upfield. 
  //this way we can slide in and form the defensive wall immediately.
  Pair ballLoc = getBallLocation(*currentVisionData);
  Pair robotLoc = getLocation(robotID, *currentVisionData, *sp);
  RobotIndex closeDefensiveID = NO_ROBOT;
  float closestDistance;

  RobotIndex tempID;
  float tempDistance;

  tempID = strategy->getCurrentRoboCupFrame()->getRobotByPosition(BLOCKER);
  if(tempID != NO_ROBOT)
  {
    closestDistance = getLocation(tempID, *currentVisionData, *sp).distanceTo(ballLoc);
    closeDefensiveID = tempID;
  }

  tempID = strategy->getCurrentRoboCupFrame()->getRobotByPosition(DEFENDER);
  if(tempID != NO_ROBOT)
  {
    tempDistance = getLocation(tempID, *currentVisionData, *sp).distanceTo(ballLoc);
    if(tempDistance < closestDistance)
    {
      closestDistance = tempDistance;
      closeDefensiveID = tempID;
    }
    if(closeDefensiveID == strategy->getCurrentRoboCupFrame()->getRobotByPosition(BLOCKER))
      closeDefensiveID = strategy->getCurrentRoboCupFrame()->getRobotByPosition(DEFENDER);
  }

  tempID = strategy->getCurrentRoboCupFrame()->getRobotByPosition(SPECIAL_OP_DEFENDER);
  if(tempID != NO_ROBOT)
  {
    tempDistance = getLocation(tempID, *currentVisionData, *sp).distanceTo(ballLoc);
    if(tempDistance < closestDistance)
    {
      closestDistance = tempDistance;
      closeDefensiveID = tempID;
    }
    if(closeDefensiveID == strategy->getCurrentRoboCupFrame()->getRobotByPosition(BLOCKER))
      closeDefensiveID = strategy->getCurrentRoboCupFrame()->getRobotByPosition(SPECIAL_OP_DEFENDER);
  }
  
  //if closest defensive player 
  //a.) exists
  //b.) within tolerance, then go to side of him
  if(closestDistance < 3.0f*sp->general.PLAYER_RADIUS)
  {
    Pair defensivePlayer = getLocation(closeDefensiveID, *currentVisionData, *sp);
    if(defensivePlayer.getY() > sp->field.SPLIT_LINE)
    {
      command->setYPos(defensivePlayer.getY() + sp->general.PLAYER_RADIUS + 0.02f);
    }
    else
    {
      command->setYPos(defensivePlayer.getY() - sp->general.PLAYER_RADIUS - 0.02f);
    }
    command->setXPos(defensivePlayer.getX());
    command->setRotation(angleBetween(robotLoc, ballLoc));

  }
  //else acquire the ball
  else
  {
    Skill* skillHandle = skillSet->getSkill(AcquirePossessionSkill::skillNum);
    if(!skillHandle->isInitialized())
      skillHandle->initialize();
    skillHandle->run();
  }
}
示例#17
0
int ComputePairLocal::compute_pairs(int flag)
{
  int i,j,m,n,ii,jj,inum,jnum,itype,jtype;
  double xtmp,ytmp,ztmp,delx,dely,delz;
  double rsq,eng,fpair,factor_coul,factor_lj;
  int *ilist,*jlist,*numneigh,**firstneigh;
  double *dbuf,*ebuf,*fbuf;

  double **x = atom->x;
  int *type = atom->type;
  int *mask = atom->mask;
  int nlocal = atom->nlocal;
  int nall = nlocal + atom->nghost;
  double *special_coul = force->special_coul;
  double *special_lj = force->special_lj;
  int newton_pair = force->newton_pair;

  // invoke half neighbor list (will copy or build if necessary)

  if (flag == 0) neighbor->build_one(list->index);

  inum = list->inum;
  ilist = list->ilist;
  numneigh = list->numneigh;
  firstneigh = list->firstneigh;

  // loop over neighbors of my atoms
  // skip if I or J are not in group

  if (flag) {
    if (nvalues == 1) {
      if (dflag >= 0) dbuf = vector;
      if (eflag >= 0) ebuf = vector;
      if (fflag >= 0) fbuf = vector;
    } else {
      if (dflag >= 0) dbuf = &array[0][dflag];
      if (eflag >= 0) ebuf = &array[0][eflag];
      if (fflag >= 0) fbuf = &array[0][fflag];
    }
  }

  Pair *pair = force->pair;
  double **cutsq = force->pair->cutsq;

  m = n = 0;
  for (ii = 0; ii < inum; ii++) {
    i = ilist[ii];
    if (!(mask[i] & groupbit)) continue;

    xtmp = x[i][0];
    ytmp = x[i][1];
    ztmp = x[i][2];
    itype = type[i];
    jlist = firstneigh[i];
    jnum = numneigh[i];

    for (jj = 0; jj < jnum; jj++) {
      j = jlist[jj];

      if (j < nall) factor_coul = factor_lj = 1.0;
      else {
	factor_coul = special_coul[j/nall];
	factor_lj = special_lj[j/nall];
	j %= nall;
      }

      if (!(mask[j] & groupbit)) continue;
      if (newton_pair == 0 && j >= nlocal) continue;

      delx = xtmp - x[j][0];
      dely = ytmp - x[j][1];
      delz = ztmp - x[j][2];
      rsq = delx*delx + dely*dely + delz*delz;
      jtype = type[j];
      if (rsq >= cutsq[itype][jtype]) continue;
	
      if (flag) {
	if (dflag >= 0) dbuf[n] = sqrt(rsq);
	if (eflag >= 0 || fflag >= 0) {
	  eng = pair->single(i,j,itype,jtype,rsq,factor_coul,factor_lj,fpair);
	  if (eflag >= 0) ebuf[n] = eng;
	  if (fflag >= 0) fbuf[n] = sqrt(rsq)*fpair;
	}
	n += nvalues;
      }

      m++;
    }
  }

  return m;
}
示例#18
0
//===================================================================================
float laneHalfAngle (Pair passerLoc, // Position of the passing robot.
                     Pair passDestination, // location of the pass destination
                     const VisionData &field, // where everyone else is now
                     const SystemParameters &rp, // contains necessary game parameters  
                     const Pair * extraObstacle, // Check this (optional) location as an obstacle too 
                     bool checkOurRobots) //to see if we check for our robots or not...
{

  float minLaneAngle = PI/2.0f; // Initialize the lane half angle to PI/2 (a clear lane)

  // Lane parameters
  float laneLength = passerLoc.distanceTo (passDestination);
  laneLength = laneLength + rp.general.PLAYER_RADIUS + rp.general.BALL_RADIUS;
  float laneDirection = angleWithXAxis (passerLoc, passDestination);

  // Obstacle parameters
  Pair obstacleLoc;         // Obstacle centre location
  float obstacleDist;       // Distance of the obstacle centre from the passerLoc
  float obstacleDirection;  // Angle made by the segment from passerLoc to obstacle with the x-axis
  float obstacleHalfAngle;  // Half the angle subtended by the obstacle on the passer loc
  float angleWithLane1;     // Angle between the tangents drawn from passerLoc to obstacle with 
  float angleWithLane2;     // the lane direction


  // Check opponent robots first
  RobotIndex i;
  for (i = ROBOT0; i < NUM_ROBOTS; i++) {

    if (theirRobotFound (i, field, rp)) {

      // Get obstacle direction and distance from the passerLoc
      obstacleLoc = getTheirRobotLocation (i, field, rp);
      obstacleDist = passerLoc.distanceTo (obstacleLoc);
  
      // Get the direction of the segment from passerLoc to obstacle with the x-axis
      obstacleDirection = angleWithXAxis (passerLoc, obstacleLoc);
      obstacleHalfAngle = ATAN2 (rp.general.OPPONENT_RADIUS, obstacleDist);

      // Evaluate angles only if the passer loc is closer to the obtacle than the lane length
      if (obstacleDist <= laneLength) {

        // If the difference between the obstacle direction and lane direction is within the half
        // angle subtended by the obstacle on the passer loc, the lane is being blocked
        if (ABS (laneDirection - obstacleDirection) <= obstacleHalfAngle)
          return 0.0f;

        // Get the directions of the tangent to the obstacle from the passer loc and their angular
        // difference from the lane direction
        angleWithLane1 = ABS (angleDifference (obstacleDirection + obstacleHalfAngle, laneDirection));
        angleWithLane2 = ABS (angleDifference (obstacleDirection - obstacleHalfAngle, laneDirection));
      

        // Compare the angle of the tangent closer to the lane diretion
        float smallerAngle = MIN (angleWithLane1, angleWithLane2);
        if (smallerAngle < minLaneAngle)
          minLaneAngle = smallerAngle;

      }
    }

  }

  //IF WE WANT TO TAKE INTO ACCOUNT OUR OWN ROBOTS...
  if (checkOurRobots)
  {
    for (i = ROBOT0; i < NUM_ROBOTS; i++) {

      //If our robot is found, and he is not the passer or receiver => check to see if it is in the way
          if(robotFound(i, field, rp)&&(dist(i,passerLoc,field,rp)>rp.general.PLAYER_RADIUS)&&(dist(i,passDestination,field,rp)>rp.general.PLAYER_RADIUS)) {      

        // Get obstacle direction and distance from the passerLoc
        obstacleLoc = getLocation (i, field, rp);
        obstacleDist = passerLoc.distanceTo (obstacleLoc);
  
        // Get the direction of the segment from passerLoc to obstacle with the x-axis
        obstacleDirection = angleWithXAxis (passerLoc, obstacleLoc);
        obstacleHalfAngle = ATAN2 (rp.general.PLAYER_RADIUS, obstacleDist);

        // Evaluate angles only if the passer loc is closer to the obtacle than the lane length
        if (obstacleDist <= laneLength) {

          // If the difference between the obstacle direction and lane direction is within the half
          // angle subtended by the obstacle on the passer loc, the lane is being blocked
          if (ABS (laneDirection - obstacleDirection) <= obstacleHalfAngle)
            return 0.0f;

          // Get the directions of the tangent to the obstacle from the passer loc and their angular
          // difference from the lane direction
          angleWithLane1 = ABS (angleDifference (obstacleDirection + obstacleHalfAngle, laneDirection));
          angleWithLane2 = ABS (angleDifference (obstacleDirection - obstacleHalfAngle, laneDirection));
      

          // Compare the angle of the tangent closer to the lane diretion
          float smallerAngle = MIN (angleWithLane1, angleWithLane2);
          if (smallerAngle < minLaneAngle)
            minLaneAngle = smallerAngle;

        }
      }

    }
  }


  // Check the passed extra location as an obstacle having the radius the same as our robots
  if (extraObstacle) {

    // Get obstacle direction and distance from the passerLoc
    obstacleLoc = * extraObstacle;
    obstacleDist = passerLoc.distanceTo (obstacleLoc);

    // Get the direction of the segment from passerLoc to obstacle with the x-axis
    obstacleDirection = angleWithXAxis (passerLoc, obstacleLoc);
    obstacleHalfAngle = ATAN2 (rp.general.PLAYER_RADIUS, obstacleDist);

    // Evaluate angles only if the passer loc is closer to the obtacle than the lane length
    if (obstacleDist <= laneLength) {

      // If the difference between the obstacle direction and lane direction is within the half
      // angle subtended by the obstacle on the passer loc, the lane is being blocked
      if (ABS (laneDirection - obstacleDirection) <= obstacleHalfAngle)
        return 0.0f;

      // Get the directions of the tangent to the obstacle from the passer loc and their angular
      // difference from the lane direction
      angleWithLane1 = ABS (angleDifference (obstacleDirection + obstacleHalfAngle, laneDirection));
      angleWithLane2 = ABS (angleDifference (obstacleDirection - obstacleHalfAngle, laneDirection));
      

      // Compare the angle of the tangent closer to the lane diretion
      float smallerAngle = MIN (angleWithLane1, angleWithLane2);
      if (smallerAngle < minLaneAngle)
        minLaneAngle = smallerAngle;

    }
  }

  return minLaneAngle;
}
示例#19
0
文件: Pair.hpp 项目: arupa-loka/lrep
Pair<A,B>::Pair(const Pair<A,B> & iP): _first(iP.first()), _second(iP.second()) {}
void EwaldDisp::init()
{
  nkvec = nkvec_max = nevec = nevec_max = 0;
  nfunctions = nsums = sums = 0;
  nbox = -1;
  bytes = 0.0;

  if (!comm->me) {
    if (screen) fprintf(screen,"EwaldDisp initialization ...\n");
    if (logfile) fprintf(logfile,"EwaldDisp initialization ...\n");
  }

  triclinic_check();
  if (domain->dimension == 2)
    error->all(FLERR,"Cannot use EwaldDisp with 2d simulation");
  if (slabflag == 0 && domain->nonperiodic > 0)
    error->all(FLERR,"Cannot use nonperiodic boundaries with EwaldDisp");
  if (slabflag == 1) {
    if (domain->xperiodic != 1 || domain->yperiodic != 1 ||
        domain->boundary[2][0] != 1 || domain->boundary[2][1] != 1)
      error->all(FLERR,"Incorrect boundaries with slab EwaldDisp");
  }

  scale = 1.0;
  mumurd2e = force->qqrd2e;
  dielectric = force->dielectric;

  int tmp;
  Pair *pair = force->pair;
  int *ptr = pair ? (int *) pair->extract("ewald_order",tmp) : NULL;
  double *cutoff = pair ? (double *) pair->extract("cut_coul",tmp) : NULL;
  if (!(ptr||cutoff))
    error->all(FLERR,"KSpace style is incompatible with Pair style");
  int ewald_order = ptr ? *((int *) ptr) : 1<<1;
  int ewald_mix = ptr ? *((int *) pair->extract("ewald_mix",tmp)) : GEOMETRIC;
  memset(function, 0, EWALD_NFUNCS*sizeof(int));
  for (int i=0; i<=EWALD_NORDER; ++i)                        // transcribe order
    if (ewald_order&(1<<i)) {                                // from pair_style
      int n[] = EWALD_NSUMS, k = 0;
      char str[128];
      switch (i) {
        case 1:
          k = 0; break;
        case 3:
          k = 3; break;
        case 6:
          if (ewald_mix==GEOMETRIC) { k = 1; break; }
          else if (ewald_mix==ARITHMETIC) { k = 2; break; }
          error->all(FLERR,
                     "Unsupported mixing rule in kspace_style ewald/disp");
        default:
          error->all(FLERR,"Unsupported order in kspace_style ewald/disp");
      }
      nfunctions += function[k] = 1;
      nsums += n[k];
    }

  if (!gewaldflag) g_ewald = 0.0;
  pair->init();  // so B is defined
  init_coeffs();
  init_coeff_sums();

  double qsum, qsqsum, bsbsum;
  qsum = qsqsum = bsbsum = 0.0;
  if (function[0]) {
    qsum = sum[0].x;
    qsqsum = sum[0].x2;
  }

  // turn off coulombic if no charge

  if (function[0] && qsqsum == 0.0) {
    function[0] = 0;
    nfunctions -= 1;
    nsums -= 1;
  }

  if (function[1]) bsbsum = sum[1].x2;
  if (function[2]) bsbsum = sum[2].x2;

  if (function[3]) M2 = sum[9].x2;

  if (function[3] && strcmp(update->unit_style,"electron") == 0)
    error->all(FLERR,"Cannot (yet) use 'electron' units with dipoles");

  if (qsqsum == 0.0 && bsbsum == 0.0 && M2 == 0.0)
      error->all(FLERR,"Cannot use Ewald/disp solver "
                 "on system with no charge, dipole, or LJ particles");
  if (fabs(qsum) > SMALL && comm->me == 0) {
      char str[128];
      sprintf(str,"System is not charge neutral, net charge = %g",qsum);
      error->warning(FLERR,str);
  }

  if (!function[1] && !function[2])
    dispersionflag = 0;

  if (!function[3])
    dipoleflag = 0;

  pair_check();

  // set accuracy (force units) from accuracy_relative or accuracy_absolute

  if (accuracy_absolute >= 0.0) accuracy = accuracy_absolute;
  else accuracy = accuracy_relative * two_charge_force;

  // setup K-space resolution

  q2 = qsqsum * force->qqrd2e / force->dielectric;
  M2 *= mumurd2e / force->dielectric;
  b2 = bsbsum; //Are these units right?
  bigint natoms = atom->natoms;

  if (!gewaldflag) {
    if (function[0]) {
      g_ewald = accuracy*sqrt(natoms*(*cutoff)*shape_det(domain->h)) / (2.0*q2);
      if (g_ewald >= 1.0) g_ewald = (1.35 - 0.15*log(accuracy))/(*cutoff);
      else g_ewald = sqrt(-log(g_ewald)) / (*cutoff);
    }
    else if (function[1] || function[2]) {
      //Try Newton Solver
      //Use old method to get guess
      g_ewald = (1.35 - 0.15*log(accuracy))/ *cutoff;
    
      double g_ewald_new = 
        NewtonSolve(g_ewald,(*cutoff),natoms,shape_det(domain->h),b2);
      if (g_ewald_new > 0.0) g_ewald = g_ewald_new;
      else error->warning(FLERR,"Ewald/disp Newton solver failed, "
                          "using old method to estimate g_ewald");
    } else if (function[3]) {
      //Try Newton Solver
      //Use old method to get guess
      g_ewald = (1.35 - 0.15*log(accuracy))/ *cutoff;
      double g_ewald_new = 
        NewtonSolve(g_ewald,(*cutoff),natoms,shape_det(domain->h),M2);
      if (g_ewald_new > 0.0) g_ewald = g_ewald_new;
      else error->warning(FLERR,"Ewald/disp Newton solver failed, "
                          "using old method to estimate g_ewald");
    }
  }

  if (!comm->me) {
      if (screen) fprintf(screen, "  G vector = %g\n", g_ewald);
      if (logfile) fprintf(logfile, "  G vector = %g\n", g_ewald);
  }

  g_ewald_6 = g_ewald;
  deallocate_peratom();
  peratom_allocate_flag = 0;
}
示例#21
0
bool Sequence::has_target(const Pair& other) {
    return this->has_target(other.target_slot());
}
示例#22
0
void fiddle(Pair<string,int> x)
   {
      x.setFirst("Bethesda");
      x.setSecond(202);
      cout<<"In fiddle() pair count: "<<x.getPairCount()<<endl;
   }
示例#23
0
void FixAdapt::init()
{
  int i,j;

  // allow a dynamic group only if ATOM attribute not used

  if (group->dynamic[igroup])
    for (int i = 0; i < nadapt; i++)
      if (adapt[i].which == ATOM)
        error->all(FLERR,"Cannot use dynamic group with fix adapt atom");

  // setup and error checks

  anypair = 0;

  for (int m = 0; m < nadapt; m++) {
    Adapt *ad = &adapt[m];

    ad->ivar = input->variable->find(ad->var);
    if (ad->ivar < 0)
      error->all(FLERR,"Variable name for fix adapt does not exist");
    if (!input->variable->equalstyle(ad->ivar))
      error->all(FLERR,"Variable for fix adapt is invalid style");

    if (ad->which == PAIR) {
      anypair = 1;
      Pair *pair = NULL;

      // if ad->pstyle has trailing sub-style annotation ":N",
      //   strip it for pstyle arg to pair_match() and set nsub = N
      // this should work for appended suffixes as well

      int n = strlen(ad->pstyle) + 1;
      char *pstyle = new char[n];
      strcpy(pstyle,ad->pstyle);

      char *cptr;
      int nsub = 0;
      if ((cptr = strchr(pstyle,':'))) {
        *cptr = '\0';
        nsub = force->inumeric(FLERR,cptr+1);
      }

      if (lmp->suffix_enable) {
        int len = 2 + strlen(pstyle) + strlen(lmp->suffix);
        char *psuffix = new char[len];
        strcpy(psuffix,pstyle);
        strcat(psuffix,"/");
        strcat(psuffix,lmp->suffix);
        pair = force->pair_match(psuffix,1,nsub);
        delete[] psuffix;
      }
      if (pair == NULL) pair = force->pair_match(pstyle,1,nsub);
      if (pair == NULL) error->all(FLERR,"Fix adapt pair style does not exist");
      void *ptr = pair->extract(ad->pparam,ad->pdim);
      if (ptr == NULL)
        error->all(FLERR,"Fix adapt pair style param not supported");

      ad->pdim = 2;
      if (ad->pdim == 0) ad->scalar = (double *) ptr;
      if (ad->pdim == 2) ad->array = (double **) ptr;

      // if pair hybrid, test that ilo,ihi,jlo,jhi are valid for sub-style

      if (ad->pdim == 2 && (strcmp(force->pair_style,"hybrid") == 0 ||
                            strcmp(force->pair_style,"hybrid/overlay") == 0)) {
        PairHybrid *pair = (PairHybrid *) force->pair;
        for (i = ad->ilo; i <= ad->ihi; i++)
          for (j = MAX(ad->jlo,i); j <= ad->jhi; j++)
            if (!pair->check_ijtype(i,j,pstyle))
              error->all(FLERR,"Fix adapt type pair range is not valid for "
                         "pair hybrid sub-style");
      }

      delete [] pstyle;

    } else if (ad->which == KSPACE) {
      if (force->kspace == NULL)
        error->all(FLERR,"Fix adapt kspace style does not exist");
      kspace_scale = (double *) force->kspace->extract("scale");

    } else if (ad->which == ATOM) {
      if (ad->aparam == DIAMETER) {
        if (!atom->radius_flag)
          error->all(FLERR,"Fix adapt requires atom attribute diameter");
      }
      if (ad->aparam == CHARGE) {
	if (!atom->q_flag)
	  error->all(FLERR,"Fix adapt requires atom attribute charge");
      }
    }
  }

  // make copy of original pair array values

  for (int m = 0; m < nadapt; m++) {
    Adapt *ad = &adapt[m];
    if (ad->which == PAIR && ad->pdim == 2) {
      for (i = ad->ilo; i <= ad->ihi; i++)
        for (j = MAX(ad->jlo,i); j <= ad->jhi; j++)
          ad->array_orig[i][j] = ad->array[i][j];
    }
  }

  // fixes that store initial per-atom values

  if (id_fix_diam) {
    int ifix = modify->find_fix(id_fix_diam);
    if (ifix < 0) error->all(FLERR,"Could not find fix adapt storage fix ID");
    fix_diam = (FixStore *) modify->fix[ifix];
  }
  if (id_fix_chg) {
    int ifix = modify->find_fix(id_fix_chg);
    if (ifix < 0) error->all(FLERR,"Could not find fix adapt storage fix ID");
    fix_chg = (FixStore *) modify->fix[ifix];
  }

  if (strstr(update->integrate_style,"respa"))
    nlevels_respa = ((Respa *) update->integrate)->nlevels;
}
示例#24
0
//------------------------------------------------------------------------------
// processComponents() -- process our new components list; 
//   -- Add the components from the input list, 'list', to a new list, 'newList'
//      make sure they are all of type Component (or derived from it)
//      tell them that we are their container
//   -- Add an optional component to the end of the new list
//   -- Swap our 'components' list with the new list, newList
//   -- Handle selections.
//------------------------------------------------------------------------------
void Component::processComponents(
      PairStream* const list,
      const std::type_info& filter,
      Pair* const add,
      Component* const remove
   )
{
   PairStream* oldList = components.getRefPtr();

   // ---
   // Our dynamic_cast (see below) already filters on the Component class
   // ---
   bool skipFilter = false;
   if (&filter == 0) skipFilter = true;
   else if (filter == typeid(Component)) skipFilter = true;

   // ---
   // Create a new list, copy (filter) the component pairs and set their container pointers
   // ---
   PairStream* newList = new PairStream();
   if (list != 0) {

      // Add the (filtered) components to the new list and set their container
      List::Item* item = list->getFirstItem();
      while (item != 0) {
         Pair* pair = (Pair*) item->getValue();
         Component* cp = dynamic_cast<Component*>( pair->object() );
         if ( cp != 0 && cp != remove && (skipFilter || cp->isClassType(filter)) ) {
            newList->put(pair);
            cp->container(this);
         }
         else if ( cp != 0 && cp == remove ) {
            cp->container(0);
         }
         item = item->getNext();
      }

   }

   // ---
   // Add the optional component
   // ---
   if (add != 0) {
      Component* cp = dynamic_cast<Component*>( add->object() );
      if ( cp != 0 && (skipFilter || cp->isClassType(filter)) ) {
         newList->put(add);
         cp->container(this);
      }
   }

   // ---
   // Swap lists
   // ---
   components = newList;
   newList->unref();

   // ---
   // Anything selected?
   // ---
   if (selection != 0) {
      if (selection->isClassType(typeid(String))) {
            String str(*((String*)selection));
            select(&str);
      }
      else {
            Integer num(((Number*)selection)->getInt());
            select(&num);
      }
   }

   if (oldList != 0) {
      oldList->unref();
   }
}
示例#25
0
int main(int argc, const char * argv[])
{
    StockCenter* center = new StockCenter();
    //Ask for setting file
    cout<<"Do you need to add a setting file? If no, we will use the default setting. (Y/N)"<<endl;
    string answer;
    getline(cin,answer);
    if(answer.compare("Y")==0){
        cout<<"Please input invalid setting file name"<<endl;
        string fileName;
        getline(cin,fileName);
        center->addSettingFile(fileName);
    }
    
    int getValidInput = 0;
    string validSymbol;
    while (true) {
        
        while (getValidInput == 0) {
            //Input valid stock symbol
            cout<<"Please input the stock symbol or name"<<endl;
            string inputSymbol;
            getline(cin,inputSymbol);
            cout<<"The stock symbol or name you've entered is "<<inputSymbol<<endl;
            
            vector<string> similarSymbols = center->getStockSymbols(inputSymbol);
            if(similarSymbols.size() == 0){
                cout<<"could not find the valid stock symbol that matches your input"<<endl;
            }
            else if(similarSymbols.size() == 1){
                validSymbol = similarSymbols[0];
                cout<<"We find a valid stock symbol " << validSymbol<<endl;
                getValidInput = 1;
            }
            else{
                cout<<"We find more than 1 symbols that matches your input"<<endl;
                for(int i=0; i<similarSymbols.size(); i++){
                    cout<<similarSymbols[i]<<endl;
                }
                cout<<"Please make input again"<<endl;
            }
        }
        getValidInput = 0;
        
        cout<<"What do you want to do with the stock "<<validSymbol<<"? 1. Add it to the database. 2. Remove it from the database."<<endl;
        string option;
        getline(cin,option);
        int opt = atoi(option.c_str());
        
        if(opt == 1){
            //Download file from internet
            string fileName = center->downloadStock(validSymbol);
            cout<<"fileName is "<<fileName<<endl;
            
            //Parse the csv file
            center->createStock(validSymbol, fileName);
            center->printAllStocks();
        }
        else if(opt ==2){
            center->removeStock(validSymbol);
        }
        else{
            cout<<"Invalid command"<<endl;
        }
        
        cout<<"What do you want to process next. 1. Get stock history. 2. Get future prices. 3. Get the future <time,price> pairs. 4. Get suggestions for the current stock"<<endl;
        
        getline(cin,option);
        opt = atoi(option.c_str());
        
        if(opt == 1){
            //Print the stock history
            cout<<"Print the stock history"<<endl;
            vector<Pair*> history = center->getStockHistory(validSymbol);
            for(int i=0; i<history.size(); i++){
                cout<<history[i]->toString()<<endl;
            }
        }
        else if(opt == 2){
            cout<<"How many days in the future do you want to see"<<endl;
            string number;
            getline(cin,number);
            //Get the future prices
            int numberOfDays = atoi(number.c_str());
            
            vector<double> futurePrices = center->getFuturePrices(validSymbol, numberOfDays);
            cout<<"Future price is "<<endl;
            for(int i=0; i<numberOfDays; i++){
                cout<<futurePrices[i]<<endl;
            }
        }
        else if(opt == 3){
            cout<<"How many days in the future do you want to see"<<endl;
            string number;
            getline(cin,number);
            //Get the future <time,price> pairs
            int numberOfDays = atoi(number.c_str());
            vector<Pair*> future = center->getFuturePricesTable(validSymbol, numberOfDays);
            for(int i=0; i<numberOfDays; i++){
                Pair* pair = future[i];
                cout<<pair->getTime()<<" "<<pair->getPrice()<<endl;
            }
        }
        else if(opt == 4){
            //Get the suggestion
            cout<<center->getTradeSuggestion(validSymbol)<<endl;
        }
        else{
            cout<<"Invalid input"<<endl;
        }
    }
    return 0;
}
示例#26
0
void HashTable::remove(Pair pair) {
    int index = hashFunction(pair.getKey());
    // Will throw ListException::ElementNotFound if pair is not found
    data[index].remove(pair);
}