コード例 #1
0
QString StringOffsetProvider::string()
{
	QString res = components().join("");
	return res.isNull() ? QString("") : res;
}
コード例 #2
0
 inline
 double
 Quaternion2d::sinAngle() const {
     return components()(1);
 }
コード例 #3
0
ファイル: gmx_anaeig.c プロジェクト: martinhoefling/gromacs
int gmx_anaeig(int argc,char *argv[])
{
  static const char *desc[] = {
    "[TT]g_anaeig[tt] analyzes eigenvectors. The eigenvectors can be of a",
    "covariance matrix ([TT]g_covar[tt]) or of a Normal Modes analysis",
    "([TT]g_nmeig[tt]).[PAR]",
    
    "When a trajectory is projected on eigenvectors, all structures are",
    "fitted to the structure in the eigenvector file, if present, otherwise",
    "to the structure in the structure file. When no run input file is",
    "supplied, periodicity will not be taken into account. Most analyses",
    "are performed on eigenvectors [TT]-first[tt] to [TT]-last[tt], but when",
    "[TT]-first[tt] is set to -1 you will be prompted for a selection.[PAR]",
    
    "[TT]-comp[tt]: plot the vector components per atom of eigenvectors",
    "[TT]-first[tt] to [TT]-last[tt].[PAR]",
    
    "[TT]-rmsf[tt]: plot the RMS fluctuation per atom of eigenvectors",
    "[TT]-first[tt] to [TT]-last[tt] (requires [TT]-eig[tt]).[PAR]",

    "[TT]-proj[tt]: calculate projections of a trajectory on eigenvectors",
    "[TT]-first[tt] to [TT]-last[tt].",
    "The projections of a trajectory on the eigenvectors of its",
    "covariance matrix are called principal components (pc's).",
    "It is often useful to check the cosine content of the pc's,",
    "since the pc's of random diffusion are cosines with the number",
    "of periods equal to half the pc index.",
    "The cosine content of the pc's can be calculated with the program",
    "[TT]g_analyze[tt].[PAR]",
    
    "[TT]-2d[tt]: calculate a 2d projection of a trajectory on eigenvectors",
    "[TT]-first[tt] and [TT]-last[tt].[PAR]",
    
    "[TT]-3d[tt]: calculate a 3d projection of a trajectory on the first",
    "three selected eigenvectors.[PAR]",
    
    "[TT]-filt[tt]: filter the trajectory to show only the motion along",
    "eigenvectors [TT]-first[tt] to [TT]-last[tt].[PAR]",
    
    "[TT]-extr[tt]: calculate the two extreme projections along a trajectory",
    "on the average structure and interpolate [TT]-nframes[tt] frames",
    "between them, or set your own extremes with [TT]-max[tt]. The",
    "eigenvector [TT]-first[tt] will be written unless [TT]-first[tt] and",
    "[TT]-last[tt] have been set explicitly, in which case all eigenvectors",
    "will be written to separate files. Chain identifiers will be added",
    "when writing a [TT].pdb[tt] file with two or three structures (you",
    "can use [TT]rasmol -nmrpdb[tt] to view such a [TT].pdb[tt] file).[PAR]",
    
    "  Overlap calculations between covariance analysis:[BR]",
    "  [BB]Note:[bb] the analysis should use the same fitting structure[PAR]",
    
    "[TT]-over[tt]: calculate the subspace overlap of the eigenvectors in",
    "file [TT]-v2[tt] with eigenvectors [TT]-first[tt] to [TT]-last[tt]",
    "in file [TT]-v[tt].[PAR]",
    
    "[TT]-inpr[tt]: calculate a matrix of inner-products between",
    "eigenvectors in files [TT]-v[tt] and [TT]-v2[tt]. All eigenvectors",
    "of both files will be used unless [TT]-first[tt] and [TT]-last[tt]",
    "have been set explicitly.[PAR]",
    
    "When [TT]-v[tt], [TT]-eig[tt], [TT]-v2[tt] and [TT]-eig2[tt] are given,",
    "a single number for the overlap between the covariance matrices is",
    "generated. The formulas are:[BR]",
    "        difference = sqrt(tr((sqrt(M1) - sqrt(M2))^2))[BR]",
    "normalized overlap = 1 - difference/sqrt(tr(M1) + tr(M2))[BR]",
    "     shape overlap = 1 - sqrt(tr((sqrt(M1/tr(M1)) - sqrt(M2/tr(M2)))^2))[BR]",
    "where M1 and M2 are the two covariance matrices and tr is the trace",
    "of a matrix. The numbers are proportional to the overlap of the square",
    "root of the fluctuations. The normalized overlap is the most useful",
    "number, it is 1 for identical matrices and 0 when the sampled",
    "subspaces are orthogonal.[PAR]",
    "When the [TT]-entropy[tt] flag is given an entropy estimate will be",
    "computed based on the Quasiharmonic approach and based on",
    "Schlitter's formula."
  };
  static int  first=1,last=-1,skip=1,nextr=2,nskip=6;
  static real max=0.0,temp=298.15;
  static gmx_bool bSplit=FALSE,bEntropy=FALSE;
  t_pargs pa[] = {
    { "-first", FALSE, etINT, {&first},     
      "First eigenvector for analysis (-1 is select)" },
    { "-last",  FALSE, etINT, {&last}, 
      "Last eigenvector for analysis (-1 is till the last)" },
    { "-skip",  FALSE, etINT, {&skip},
      "Only analyse every nr-th frame" },
    { "-max",  FALSE, etREAL, {&max}, 
      "Maximum for projection of the eigenvector on the average structure, "
      "max=0 gives the extremes" },
    { "-nframes",  FALSE, etINT, {&nextr}, 
      "Number of frames for the extremes output" },
    { "-split",   FALSE, etBOOL, {&bSplit},
      "Split eigenvector projections where time is zero" },
    { "-entropy", FALSE, etBOOL, {&bEntropy},
      "Compute entropy according to the Quasiharmonic formula or Schlitter's method." },
    { "-temp",    FALSE, etREAL, {&temp},
      "Temperature for entropy calculations" },
    { "-nevskip", FALSE, etINT, {&nskip},
      "Number of eigenvalues to skip when computing the entropy due to the quasi harmonic approximation. When you do a rotational and/or translational fit prior to the covariance analysis, you get 3 or 6 eigenvalues that are very close to zero, and which should not be taken into account when computing the entropy." }
  };
#define NPA asize(pa)
  
  FILE       *out;
  int        status,trjout;
  t_topology top;
  int        ePBC=-1;
  t_atoms    *atoms=NULL;
  rvec       *xtop,*xref1,*xref2,*xrefp=NULL;
  gmx_bool       bDMR1,bDMA1,bDMR2,bDMA2;
  int        nvec1,nvec2,*eignr1=NULL,*eignr2=NULL;
  rvec       *x,*xread,*xav1,*xav2,**eigvec1=NULL,**eigvec2=NULL;
  matrix     topbox;
  real       xid,totmass,*sqrtm,*w_rls,t,lambda;
  int        natoms,step;
  char       *grpname;
  const char *indexfile;
  char       title[STRLEN];
  int        i,j,d;
  int        nout,*iout,noutvec,*outvec,nfit;
  atom_id    *index,*ifit;
  const char *VecFile,*Vec2File,*topfile;
  const char *EigFile,*Eig2File;
  const char *CompFile,*RmsfFile,*ProjOnVecFile;
  const char *TwoDPlotFile,*ThreeDPlotFile;
  const char *FilterFile,*ExtremeFile;
  const char *OverlapFile,*InpMatFile;
  gmx_bool       bFit1,bFit2,bM,bIndex,bTPS,bTop,bVec2,bProj;
  gmx_bool       bFirstToLast,bFirstLastSet,bTraj,bCompare,bPDB3D;
  real       *eigval1=NULL,*eigval2=NULL;
  int        neig1,neig2;
  double     **xvgdata;
  output_env_t oenv;
  gmx_rmpbc_t  gpbc;

  t_filenm fnm[] = { 
    { efTRN, "-v",    "eigenvec",    ffREAD  },
    { efTRN, "-v2",   "eigenvec2",   ffOPTRD },
    { efTRX, "-f",    NULL,          ffOPTRD }, 
    { efTPS, NULL,    NULL,          ffOPTRD },
    { efNDX, NULL,    NULL,          ffOPTRD },
    { efXVG, "-eig", "eigenval",     ffOPTRD },
    { efXVG, "-eig2", "eigenval2",   ffOPTRD },
    { efXVG, "-comp", "eigcomp",     ffOPTWR },
    { efXVG, "-rmsf", "eigrmsf",     ffOPTWR },
    { efXVG, "-proj", "proj",        ffOPTWR },
    { efXVG, "-2d",   "2dproj",      ffOPTWR },
    { efSTO, "-3d",   "3dproj.pdb",  ffOPTWR },
    { efTRX, "-filt", "filtered",    ffOPTWR },
    { efTRX, "-extr", "extreme.pdb", ffOPTWR },
    { efXVG, "-over", "overlap",     ffOPTWR },
    { efXPM, "-inpr", "inprod",      ffOPTWR }
  }; 
#define NFILE asize(fnm) 

  parse_common_args(&argc,argv,
                    PCA_CAN_TIME | PCA_TIME_UNIT | PCA_CAN_VIEW | PCA_BE_NICE ,
		    NFILE,fnm,NPA,pa,asize(desc),desc,0,NULL,&oenv); 

  indexfile=ftp2fn_null(efNDX,NFILE,fnm);

  VecFile         = opt2fn("-v",NFILE,fnm);
  Vec2File        = opt2fn_null("-v2",NFILE,fnm);
  topfile         = ftp2fn(efTPS,NFILE,fnm); 
  EigFile         = opt2fn_null("-eig",NFILE,fnm);
  Eig2File        = opt2fn_null("-eig2",NFILE,fnm);
  CompFile        = opt2fn_null("-comp",NFILE,fnm);
  RmsfFile        = opt2fn_null("-rmsf",NFILE,fnm);
  ProjOnVecFile   = opt2fn_null("-proj",NFILE,fnm);
  TwoDPlotFile    = opt2fn_null("-2d",NFILE,fnm);
  ThreeDPlotFile  = opt2fn_null("-3d",NFILE,fnm);
  FilterFile      = opt2fn_null("-filt",NFILE,fnm);
  ExtremeFile     = opt2fn_null("-extr",NFILE,fnm);
  OverlapFile     = opt2fn_null("-over",NFILE,fnm);
  InpMatFile      = ftp2fn_null(efXPM,NFILE,fnm);
  
  bTop   = fn2bTPX(topfile);
  bProj  = ProjOnVecFile || TwoDPlotFile || ThreeDPlotFile 
    || FilterFile || ExtremeFile;
  bFirstLastSet  = 
    opt2parg_bSet("-first",NPA,pa) && opt2parg_bSet("-last",NPA,pa);
  bFirstToLast = CompFile || RmsfFile || ProjOnVecFile || FilterFile ||
    OverlapFile || ((ExtremeFile || InpMatFile) && bFirstLastSet);
  bVec2  = Vec2File || OverlapFile || InpMatFile;
  bM     = RmsfFile || bProj;
  bTraj  = ProjOnVecFile || FilterFile || (ExtremeFile && (max==0))
    || TwoDPlotFile || ThreeDPlotFile;
  bIndex = bM || bProj;
  bTPS   = ftp2bSet(efTPS,NFILE,fnm) || bM || bTraj ||
    FilterFile  || (bIndex && indexfile);
  bCompare = Vec2File || Eig2File;
  bPDB3D = fn2ftp(ThreeDPlotFile)==efPDB;
  
  read_eigenvectors(VecFile,&natoms,&bFit1,
		    &xref1,&bDMR1,&xav1,&bDMA1,
		    &nvec1,&eignr1,&eigvec1,&eigval1);
  neig1 = DIM*natoms;
  
  /* Overwrite eigenvalues from separate files if the user provides them */
  if (EigFile != NULL) {
    int neig_tmp = read_xvg(EigFile,&xvgdata,&i);
    if (neig_tmp != neig1)
      fprintf(stderr,"Warning: number of eigenvalues in xvg file (%d) does not mtch trr file (%d)\n",neig1,natoms);
    neig1 = neig_tmp;
    srenew(eigval1,neig1);
    for(j=0;j<neig1;j++) {
      real tmp = eigval1[j];
      eigval1[j]=xvgdata[1][j];
      if (debug && (eigval1[j] != tmp))
	fprintf(debug,"Replacing eigenvalue %d. From trr: %10g, from xvg: %10g\n",
		j,tmp,eigval1[j]);
    }
    for(j=0;j<i;j++)
      sfree(xvgdata[j]);
    sfree(xvgdata);
    fprintf(stderr,"Read %d eigenvalues from %s\n",neig1,EigFile);
  }
    
  if (bEntropy) {
    if (bDMA1) {
      gmx_fatal(FARGS,"Can not calculate entropies from mass-weighted eigenvalues, redo the analysis without mass-weighting");
    }
    calc_entropy_qh(stdout,neig1,eigval1,temp,nskip);
    calc_entropy_schlitter(stdout,neig1,nskip,eigval1,temp);
  }
  
  if (bVec2) {
    if (!Vec2File)
      gmx_fatal(FARGS,"Need a second eigenvector file to do this analysis.");
    read_eigenvectors(Vec2File,&neig2,&bFit2,
		      &xref2,&bDMR2,&xav2,&bDMA2,&nvec2,&eignr2,&eigvec2,&eigval2);
    
    neig2 = DIM*neig2;
    if (neig2 != neig1)
      gmx_fatal(FARGS,"Dimensions in the eigenvector files don't match");
  }
  
  if(Eig2File != NULL) {
    neig2 = read_xvg(Eig2File,&xvgdata,&i);
    srenew(eigval2,neig2);
    for(j=0;j<neig2;j++)
      eigval2[j]=xvgdata[1][j];
    for(j=0;j<i;j++)
      sfree(xvgdata[j]);
    sfree(xvgdata);
    fprintf(stderr,"Read %d eigenvalues from %s\n",neig2,Eig2File);      
  }
  
  
  if ((!bFit1 || xref1) && !bDMR1 && !bDMA1) 
    bM=FALSE;
  if ((xref1==NULL) && (bM || bTraj))
    bTPS=TRUE;
  
  xtop=NULL;
  nfit=0;
  ifit=NULL;
  w_rls=NULL;

  if (!bTPS) {
    bTop=FALSE;
  } else {
    bTop=read_tps_conf(ftp2fn(efTPS,NFILE,fnm),
		       title,&top,&ePBC,&xtop,NULL,topbox,bM);
    atoms=&top.atoms;
    gpbc = gmx_rmpbc_init(&top.idef,ePBC,atoms->nr,topbox);
    gmx_rmpbc(gpbc,atoms->nr,topbox,xtop);
    /* Fitting is only required for the projection */ 
    if (bProj && bFit1) {
      if (xref1 == NULL) {
	  printf("\nNote: the structure in %s should be the same\n"
		 "      as the one used for the fit in g_covar\n",topfile);
      }
      printf("\nSelect the index group that was used for the least squares fit in g_covar\n");
      get_index(atoms,indexfile,1,&nfit,&ifit,&grpname);

      snew(w_rls,atoms->nr);
      for(i=0; (i<nfit); i++) {
	if (bDMR1) {
	  w_rls[ifit[i]] = atoms->atom[ifit[i]].m;
	} else {
	  w_rls[ifit[i]] = 1.0;
	}
      }

      snew(xrefp,atoms->nr);
      if (xref1 != NULL) {
	for(i=0; (i<nfit); i++) {
	  copy_rvec(xref1[i],xrefp[ifit[i]]);
	}
      } else {
	/* The top coordinates are the fitting reference */
	for(i=0; (i<nfit); i++) {
	  copy_rvec(xtop[ifit[i]],xrefp[ifit[i]]);
	}
	reset_x(nfit,ifit,atoms->nr,NULL,xrefp,w_rls);
      }
    }
    gmx_rmpbc_done(gpbc);
  }

  if (bIndex) {
    printf("\nSelect an index group of %d elements that corresponds to the eigenvectors\n",natoms);
    get_index(atoms,indexfile,1,&i,&index,&grpname);
    if (i!=natoms)
      gmx_fatal(FARGS,"you selected a group with %d elements instead of %d",i,natoms);
      printf("\n");
  }
  
  snew(sqrtm,natoms);
  if (bM && bDMA1) {
    proj_unit="u\\S1/2\\Nnm";
    for(i=0; (i<natoms); i++)
      sqrtm[i]=sqrt(atoms->atom[index[i]].m);
  }
  else {
    proj_unit="nm";
    for(i=0; (i<natoms); i++)
      sqrtm[i]=1.0;
  }
  
  if (bVec2) {
    t=0;
    totmass=0;
    for(i=0; (i<natoms); i++)
      for(d=0;(d<DIM);d++) {
	t+=sqr((xav1[i][d]-xav2[i][d])*sqrtm[i]);
	totmass+=sqr(sqrtm[i]);
      }
    fprintf(stdout,"RMSD (without fit) between the two average structures:"
	    " %.3f (nm)\n\n",sqrt(t/totmass));
  }
  
  if (last==-1)
    last=natoms*DIM;
  if (first>-1) {
    if (bFirstToLast) {
      /* make an index from first to last */
      nout=last-first+1;
      snew(iout,nout);
      for(i=0; i<nout; i++)
	iout[i]=first-1+i;
    } 
    else if (ThreeDPlotFile) {
      /* make an index of first+(0,1,2) and last */
      nout = bPDB3D ? 4 : 3;
      nout = min(last-first+1, nout);
      snew(iout,nout);
      iout[0]=first-1;
      iout[1]=first;
      if (nout>3)
	iout[2]=first+1;
      iout[nout-1]=last-1;
    }
    else {
      /* make an index of first and last */
      nout=2;
      snew(iout,nout);
      iout[0]=first-1;
      iout[1]=last-1;
    }
  }
  else {
    printf("Select eigenvectors for output, end your selection with 0\n");
    nout=-1;
    iout=NULL;
    
    do {
      nout++;
      srenew(iout,nout+1);
      if(1 != scanf("%d",&iout[nout]))
      {
	  gmx_fatal(FARGS,"Error reading user input");
      }
      iout[nout]--;
    }
    while (iout[nout]>=0);
    
    printf("\n");
  }
  /* make an index of the eigenvectors which are present */
  snew(outvec,nout);
  noutvec=0;
  for(i=0; i<nout; i++) 
    {
      j=0;
      while ((j<nvec1) && (eignr1[j]!=iout[i]))
	j++;
      if ((j<nvec1) && (eignr1[j]==iout[i])) 
	{
	  outvec[noutvec]=j;
	  noutvec++;
	}
    }
  fprintf(stderr,"%d eigenvectors selected for output",noutvec);
  if (noutvec <= 100) 
    {
      fprintf(stderr,":");
      for(j=0; j<noutvec; j++)
	fprintf(stderr," %d",eignr1[outvec[j]]+1);
    }
  fprintf(stderr,"\n");
    
  if (CompFile)
    components(CompFile,natoms,eignr1,eigvec1,noutvec,outvec,oenv);
  
  if (RmsfFile)
    rmsf(RmsfFile,natoms,sqrtm,eignr1,eigvec1,noutvec,outvec,eigval1,
         neig1,oenv);
    
  if (bProj)
    project(bTraj ? opt2fn("-f",NFILE,fnm) : NULL,
	    bTop ? &top : NULL,ePBC,topbox,
	    ProjOnVecFile,TwoDPlotFile,ThreeDPlotFile,FilterFile,skip,
	    ExtremeFile,bFirstLastSet,max,nextr,atoms,natoms,index,
	    bFit1,xrefp,nfit,ifit,w_rls,
	    sqrtm,xav1,eignr1,eigvec1,noutvec,outvec,bSplit,
            oenv);
    
  if (OverlapFile)
    overlap(OverlapFile,natoms,
	    eigvec1,nvec2,eignr2,eigvec2,noutvec,outvec,oenv);
    
  if (InpMatFile)
    inprod_matrix(InpMatFile,natoms,
		  nvec1,eignr1,eigvec1,nvec2,eignr2,eigvec2,
		  bFirstLastSet,noutvec,outvec);
    
  if (bCompare)
    compare(natoms,nvec1,eigvec1,nvec2,eigvec2,eigval1,neig1,eigval2,neig2);
  
  
  if (!CompFile && !bProj && !OverlapFile && !InpMatFile && 
          !bCompare && !bEntropy)
  {
    fprintf(stderr,"\nIf you want some output,"
	    " set one (or two or ...) of the output file options\n");
  }
  
  
  view_all(oenv,NFILE, fnm);
  
  thanx(stdout);
  
  return 0;
}
コード例 #4
0
    // Initialize rendering components and render a frame.
    IRendererController::Status initialize_and_render_frame()
    {
        // Construct an abort switch that will allow to abort initialization or rendering.
        RendererControllerAbortSwitch abort_switch(*m_renderer_controller);

        // Create the texture store.
        TextureStore texture_store(
            *m_project.get_scene(),
            m_params.child("texture_store"));

        // Initialize OSL's shading system.
        if (!initialize_osl_shading_system(texture_store, abort_switch) ||
            abort_switch.is_aborted())
        {
            // If it wasn't an abort, it was a failure.
            return
                abort_switch.is_aborted()
                    ? m_renderer_controller->get_status()
                    : IRendererController::AbortRendering;
        }

        // Let scene entities perform their pre-render actions. Don't proceed if that failed.
        // This is done before creating renderer components because renderer components need
        // to access the scene's render data such as the scene's bounding box.
        OnRenderBeginRecorder recorder;
        if (!m_project.get_scene()->on_render_begin(m_project, nullptr, recorder, &abort_switch) ||
            abort_switch.is_aborted())
        {
            recorder.on_render_end(m_project);
            return m_renderer_controller->get_status();
        }

        // Create renderer components.
        RendererComponents components(
            m_project,
            m_params,
            m_tile_callback_factory,
            texture_store,
            *m_texture_system,
            *m_shading_system);
        if (!components.create())
        {
            recorder.on_render_end(m_project);
            return IRendererController::AbortRendering;
        }

        // Print renderer components settings.
        components.print_settings();

        // Report whether Embree is used or not.
#ifdef APPLESEED_WITH_EMBREE
        const bool use_embree = m_params.get_optional<bool>("use_embree", false);
        m_project.set_use_embree(use_embree);
#else
        const bool use_embree = false;
#endif
        if (use_embree)
             RENDERER_LOG_INFO("using Intel Embree ray tracing kernel.");
        else RENDERER_LOG_INFO("using built-in ray tracing kernel.");

        // Updating the trace context causes ray tracing acceleration structures to be updated or rebuilt.
        m_project.update_trace_context();

        // Load the checkpoint if any.
        Frame& frame = *m_project.get_frame();
        const size_t pass_count = m_params.get_optional<size_t>("passes", 1);
        if (!frame.load_checkpoint(&components.get_shading_result_framebuffer_factory(), pass_count))
        {
            recorder.on_render_end(m_project);
            return IRendererController::AbortRendering;
        }

        // Let renderer components perform their pre-render actions. Don't proceed if that failed.
        if (!components.on_render_begin(recorder, &abort_switch) ||
            abort_switch.is_aborted())
        {
            recorder.on_render_end(m_project);
            return m_renderer_controller->get_status();
        }

        // Execute the main rendering loop.
        const auto status = render_frame(components, abort_switch);

        // Perform post-render actions.
        recorder.on_render_end(m_project);

        // End light path recording.
        const CanvasProperties& props = m_project.get_frame()->image().properties();
        m_project.get_light_path_recorder().finalize(
            props.m_canvas_width,
            props.m_canvas_height);

        // Print texture store performance statistics.
        RENDERER_LOG_DEBUG("%s", texture_store.get_statistics().to_string().c_str());

        return status;
    }
コード例 #5
0
 inline
 double
 Quaternion3d::dot(const Quaternion3d& other) const {
     return components().cwiseProduct(other.components()).sum();
 }
コード例 #6
0
/**
 * \brief Create a new Instrument
 */
Instrument::Instrument(Database db, const std::string& name)
	: _database(db), _name(name) {
	debug(LOG_DEBUG, DEBUG_LOG, 0, "instrument '%s' constructed",
		name.c_str());

	// get the information from the instruments table
	InstrumentTable	instruments(_database);

	// find out whether there already is an instrument in the table
	int	instrumentid = -1;
	try {
		instrumentid = instruments.id(name);
		debug(LOG_DEBUG, DEBUG_LOG, 0, "instrument already exists");
	} catch (const std::runtime_error& x) {
		debug(LOG_DEBUG, DEBUG_LOG, 0,
			"instrument does not exist, creating one");
		InstrumentRecord        instrumentrecord;
		instrumentrecord.name = name;
		instrumentid = instruments.add(instrumentrecord);
		debug(LOG_DEBUG, DEBUG_LOG, 0, "id of new instrument: %d",
			instrumentid);
	}

	// retrieve all the matching metadata
	InstrumentComponentTable	components(_database);
	std::string	condition = stringprintf("instrument = %d",
						instrumentid);
	auto l = components.select(condition);
	for (auto ptr = l.begin(); ptr != l.end(); ptr++) {
		// find the type from the string version of the type
		DeviceName::device_type	type
			= InstrumentComponentTableAdapter::type(ptr->type);
		InstrumentComponent::component_t	ctype
			= InstrumentComponentTableAdapter::component_type(
				ptr->componenttype);

		// construct suitable InstrumentComponent objects depending
		// on the mapped field of the component record
		InstrumentComponentPtr	iptr;
		switch (ctype) {
		case InstrumentComponent::mapped:
			// in the case of mapped devices, teh device name is
			// not an actuald evie name, but rather the name of
			// the map entry
			iptr = InstrumentComponentPtr(
				new InstrumentComponentMapped(type, _database,
					ptr->devicename));
			break;
		case InstrumentComponent::direct:
			// for direct components, matters are simplest, so
			// all fields have the meaning the name suggest
			iptr = InstrumentComponentPtr(
				new InstrumentComponentDirect(type,
					DeviceName(ptr->devicename),
					ptr->unit, ptr->servername));
			break;
		case InstrumentComponent::derived:
			// in this case, the devicename is really the component
			// type from which the component should be derived
			iptr = InstrumentComponentPtr(
				new InstrumentComponentDerived(type, *this,
					InstrumentComponentTableAdapter::type(
						ptr->devicename),
					ptr->unit));
			break;
		}

		// add the new component
		add(iptr);
	}

	debug(LOG_DEBUG, DEBUG_LOG, 0, "instrument constructed");
}
コード例 #7
0
ファイル: tarjanhd.cpp プロジェクト: melkebir/htarjan
Node TarjanHD::hd(const Digraph& g,
                  const DoubleArcMap& w,
                  SubDigraph& subG,
                  NodeNodeMap& mapToOrgG,
                  NodeNodeMap& G2T,
                  const ArcList& sortedArcs,
                  int i)
{
  assert(i >= 0);
  
  int m = static_cast<int>(sortedArcs.size());
  assert(m == lemon::countArcs(subG));
  
  int r = m - i;
  if (r == 0 || r == 1)
  {
    // add to _T a subtree rooted at node r,
    // labeled with w(e_m) and having n children labeled with
    // the vertices of subG
    Node root = _T.addNode();
    _label[root] = w[sortedArcs.back()];
    _T2OrgG[root] = lemon::INVALID;
    
    for (SubNodeIt v(subG); v != lemon::INVALID; ++v)
    {
      Node vv = G2T[v];
      if (vv == lemon::INVALID)
      {
        vv = _T.addNode();
        _label[vv] = -1;
        if (mapToOrgG[v] != lemon::INVALID)
        {
          _orgG2T[mapToOrgG[v]] = vv;
          _T2OrgG[vv] = mapToOrgG[v];
        }
      }
      _T.addArc(vv, root);
    }
    
    return root;
  }
  else
  {
    int j = (i + m) % 2 == 0 ? (i + m) / 2 : (i + m) / 2 + 1;
    // remove arcs j+1 .. m
    ArcListIt arcEndIt, arcIt = sortedArcs.begin();
    for (int k = 1; k <= m; ++k)
    {
      if (k == j + 1)
      {
        arcEndIt = arcIt;
      }
      if (k > j)
      {
        subG.disable(*arcIt);
      }
      ++arcIt;
    }
    
    // compute SCCs
    IntNodeMap comp(g, -1);
    int numSCC = lemon::stronglyConnectedComponents(subG, comp);
    if (numSCC == 1)
    {
      ArcList newSortedArcs(sortedArcs.begin(), arcEndIt);
      
      // _subG is strongly connected
      return hd(g, w, subG, mapToOrgG, G2T, newSortedArcs, i);
    }
    else
    {
      // determine strongly connected components
      NodeHasher<Digraph> hasher(g);
      NodeSetVector components(numSCC, NodeSet(42, hasher));
      for (SubNodeIt v(subG); v != lemon::INVALID; ++v)
      {
        components[comp[v]].insert(v);
      }
      
      NodeVector roots(numSCC, lemon::INVALID);
      double w_i = i > 0 ? w[getArcByRank(sortedArcs, i)] : -std::numeric_limits<double>::max();
      for (int k = 0; k < numSCC; ++k)
      {
        const NodeSet& component = components[k];
        if (component.size() > 1)
        {
          // construct new sorted arc list for component: O(m) time
          ArcList newSortedArcs;
          for (ArcListIt arcIt = sortedArcs.begin(); arcIt != arcEndIt; ++arcIt)
          {
            Node u = g.source(*arcIt);
            Node v = g.target(*arcIt);

            bool u_in_comp = component.find(u) != component.end();
            bool v_in_comp = component.find(v) != component.end();
            
            if (u_in_comp && v_in_comp)
            {
              newSortedArcs.push_back(*arcIt);
            }
          }
          
          // remove nodes not in component from the graph
          for (NodeIt v(g); v != lemon::INVALID; ++v)
          {
            subG.status(v, component.find(v) != component.end());
          }
          
          // find new_i, i.e. largest k such that w(e'_k) <= w(e_i)
          // if i == 0 or i > 0 but no such k exists => new_i := 0
          int new_i = get_i(newSortedArcs, w, w_i);
          
          // recurse on strongly connected component
          roots[k] = hd(g, w, subG, mapToOrgG, G2T, newSortedArcs, new_i);
        }
        
        // enable all nodes again
        for (int k = 0; k < numSCC; ++k)
        {
          const NodeSet& component = components[k];
          for (NodeSetIt nodeIt = component.begin(); nodeIt != component.end(); ++nodeIt)
          {
            subG.enable(*nodeIt);
          }
        }
      }
      
      // construct the condensed graph:
      // each strongly connected component is collapsed into a single node, and
      // from the resulting sets of multiple arcs retain only those with minimum weight
      Digraph c;
      DoubleArcMap ww(c);
      NodeNodeMap mapCToOrgG(c);
      NodeNodeMap C2T(c);
      ArcList newSortedArcs;
      
      int new_i = constructCondensedGraph(g, w, mapToOrgG, G2T, sortedArcs,
                                          comp, components, roots, j,
                                          c, ww, mapCToOrgG, C2T, newSortedArcs);
      
      BoolArcMap newArcFilter(c, true);
      BoolNodeMap newNodeFilter(c, true);
      SubDigraph subC(c, newNodeFilter, newArcFilter);
      
      Node root = hd(c, ww, subC, mapCToOrgG, C2T, newSortedArcs, new_i);
      return root;
    }
  }
  
  return lemon::INVALID;
}
int main()
{
	graph_link gl;

	init_graph(&gl);

	insert_vertex(&gl, 'A');
	insert_vertex(&gl, 'B');
	insert_vertex(&gl, 'C');
	insert_vertex(&gl, 'D');
	insert_vertex(&gl, 'E');
	insert_vertex(&gl, 'F');
	insert_vertex(&gl, 'G');
	insert_vertex(&gl, 'H');
	insert_vertex(&gl, 'I');
	insert_vertex(&gl, 'J');
	insert_vertex(&gl, 'K');
	insert_vertex(&gl, 'L');
	insert_vertex(&gl, 'M');

	insert_edge(&gl, 'A', 'B');
	insert_edge(&gl, 'A', 'C');
	insert_edge(&gl, 'A', 'F');
	insert_edge(&gl, 'A', 'L');
	insert_edge(&gl, 'B', 'M');
	insert_edge(&gl, 'L', 'J');
	insert_edge(&gl, 'L', 'M');
	insert_edge(&gl, 'J', 'M');

	insert_edge(&gl, 'D', 'E');

	insert_edge(&gl, 'G', 'H');
	insert_edge(&gl, 'G', 'I');
	insert_edge(&gl, 'G', 'K');
	insert_edge(&gl, 'H', 'K');

	printf("\n");
	show_graph(&gl);

	printf("Depth First Search(DFS) all nodes of the graph: \n");
	depth_first_search(&gl, 'D');
	printf("Nul\n");

	printf("Breadth First Search(BFS) all nodes of the graph: \n");
	breadth_first_search(&gl, 'A');
	printf("Nul\n");

	printf("Non connect graph DFS: \n");
	components(&gl);
	printf("Nul\n");

	//int v = get_first_neighbor(&gl, 'A');
	//printf("The first neighbor node of 'A' is: %d\n", v);

	//int v1 = get_next_neighbor(&gl, 'B', 'E');
	//printf("The next neighbor node of 'B' and 'E' is: %d\n", v1);
	//printf("\n");

	//delete_edge(&gl, 'B', 'C');
	//show_graph(&gl);

	//delete_vertex(&gl, 'C');
	destroy_graph(&gl);
}
コード例 #9
0
ファイル: qt_accessors.cpp プロジェクト: ahinoamp/Research
void KrigingTypeSelector_accessor::clear() {
  std::vector<bool> components( 9, false );
  selector_->setTrendComponents( components );
  selector_->setSkMean( 0.0 );
}
コード例 #10
0
ファイル: DrawMolecule.C プロジェクト: gzoppetti/ExscitechVmd
// return the component corresponding to the pickable
DrawMolItem *DrawMolecule::component_from_pickable(const Pickable *p) {
  for (int i=0; i<components(); i++) 
    if (repList[i] == p) return repList[i];
  return NULL; // no matching component
}
コード例 #11
0
ファイル: Supply.cpp プロジェクト: MatGB/freeorion
void SupplyManager::Update() {
    m_supply_starlane_traversals.clear();
    m_supply_starlane_obstructed_traversals.clear();
    m_fleet_supplyable_system_ids.clear();
    m_resource_supply_groups.clear();
    m_propagated_supply_ranges.clear();

    // for each empire, need to get a set of sets of systems that can exchange
    // resources.  some sets may be just one system, in which resources can be
    // exchanged between UniverseObjects producing or consuming them, but which
    // can't exchange with any other systems.

    // which systems can share resources depends on system supply ranges, which
    // systems have obstructions to supply propagation for reach empire, and
    // the ranges and obstructions of other empires' supply, as only one empire
    // can supply each system or propagate along each starlane. one empire's
    // propagating supply can push back another's, if the pusher's range is
    // larger.

    // map from empire id to map from system id to range (in starlane jumps)
    // that supply can be propagated out of that system by that empire.
    std::map<int, std::map<int, float>> empire_system_supply_ranges;
    // map from empire id to which systems are obstructed for it for supply
    // propagation
    std::map<int, std::set<int>> empire_supply_unobstructed_systems;
    // map from empire id to map from system id to sum of supply source ranges
    // owned by empire in that in system
    std::map<int, std::map<int, float>> empire_system_supply_range_sums;

    for (const std::map<int, Empire*>::value_type& entry : Empires()) {
        const Empire* empire = entry.second;
        empire_system_supply_ranges[entry.first] = empire->SystemSupplyRanges();
        empire_supply_unobstructed_systems[entry.first] = empire->SupplyUnobstructedSystems();

        //std::stringstream ss;
        //for (int system_id : empire_supply_unobstructed_systems[entry.first])
        //{ ss << system_id << ", "; }
        //DebugLogger() << "Empire " << empire->EmpireID() << " unobstructed systems: " << ss.str();
    }
    for (auto empire_id_pair : empire_system_supply_ranges) {
        for (auto sys_id_pair : empire_id_pair.second) {
            empire_system_supply_range_sums[empire_id_pair.first][sys_id_pair.first] =
                EmpireTotalSupplyRangeSumInSystem(empire_id_pair.first, sys_id_pair.first);
        }
    }


    /////
    // probably temporary: additional restriction here for supply propagation
    // but not for general system obstruction as determind within Empire::UpdateSupplyUnobstructedSystems
    /////
    const std::vector<std::shared_ptr<Fleet>> fleets = GetUniverse().Objects().FindObjects<Fleet>();

    for (const std::map<int, Empire*>::value_type& entry : Empires()) {
        int empire_id = entry.first;
        const std::set<int>& known_destroyed_objects = GetUniverse().EmpireKnownDestroyedObjectIDs(empire_id);
        std::set<int> systems_containing_friendly_fleets;

        for (std::shared_ptr<const Fleet> fleet : fleets) {
            int system_id = fleet->SystemID();
            if (system_id == INVALID_OBJECT_ID) {
                continue;   // not in a system, so can't affect system obstruction
            } else if (known_destroyed_objects.find(fleet->ID()) != known_destroyed_objects.end()) {
                continue; //known to be destroyed so can't affect supply, important just in case being updated on client side
            }

            if ((fleet->HasArmedShips() || fleet->HasFighterShips()) && fleet->Aggressive()) {
                if (fleet->OwnedBy(empire_id)) {
                    if (fleet->NextSystemID() == INVALID_OBJECT_ID || fleet->NextSystemID() == fleet->SystemID()) {
                        systems_containing_friendly_fleets.insert(system_id);
                    }
                }
            }
        }

        std::set<int> systems_where_others_have_supply_sources_and_current_empire_doesnt;
        // add all systems where others have supply
        for (std::map<int, std::map<int, float>>::value_type& empire_supply : empire_system_supply_ranges) {
            if (empire_supply.first == empire_id || empire_supply.first == ALL_EMPIRES)
                continue;

            for (const std::map<int, float>::value_type& supply_range : empire_supply.second) {
                if (supply_range.second <= 0.0f)
                    continue;
                systems_where_others_have_supply_sources_and_current_empire_doesnt.insert(supply_range.first);
            }
        }
        // remove systems were this empire has supply
        std::map<int, std::map<int, float>>::const_iterator it = empire_system_supply_ranges.find(empire_id);
        if (it != empire_system_supply_ranges.end()) {
            for (const std::map<int, float>::value_type& supply_range : it->second) {
                if (supply_range.second <= 0.0f)
                    continue;
                systems_where_others_have_supply_sources_and_current_empire_doesnt.erase(supply_range.first);
            }
        }

        // for systems where others have supply sources and this empire doesn't
        // and where this empire has no fleets...
        // supply is obstructed
        for (int system_id : systems_where_others_have_supply_sources_and_current_empire_doesnt) {
            if (systems_containing_friendly_fleets.find(system_id) == systems_containing_friendly_fleets.end())
                empire_supply_unobstructed_systems[empire_id].erase(system_id);
        }
    }
    /////
    // end probably temporary...
    /////


    // system connections each empire can see / use for supply propagation
    std::map<int, std::map<int, std::set<int>>> empire_visible_starlanes;
    for (std::map<int, Empire*>::value_type& entry : Empires()) {
        const Empire* empire = entry.second;
        empire_visible_starlanes[entry.first] = empire->KnownStarlanes();//  VisibleStarlanes();
    }

    std::set<int> systems_with_supply_in_them;

    // store (supply range in jumps, and distance to supply source) of all
    // unobstructed systems before propagation, and add to list of systems
    // to propagate from.
    std::map<int, std::map<int, std::pair<float, float>>> empire_propagating_supply_ranges;
    float max_range = 0.0f;

    for (const auto& empire_supply : empire_system_supply_ranges) {
        int empire_id = empire_supply.first;
        const std::set<int>& unobstructed_systems = empire_supply_unobstructed_systems[empire_id];

        for (const std::map<int, float>::value_type& supply_range : empire_supply.second) {
            int system_id = supply_range.first;
            if (unobstructed_systems.find(system_id) != unobstructed_systems.end()) {
                // stored: first -> source supply range.  second -> distance to source (0 for the source itself)
                empire_propagating_supply_ranges[empire_id][system_id] = {supply_range.second, 0.0f};
                if (supply_range.second > max_range)
                    max_range = supply_range.second;
                systems_with_supply_in_them.insert(system_id);
            }
        }
    }


    // spread supply out from sources by "diffusion" like process, along unobstructed
    // starlanes, until the range is exhausted.
    for (float range_to_spread = max_range; range_to_spread >= 0;
         range_to_spread -= 1.0f)
    {
        //DebugLogger() << "!!!! Reduced spreading range to " << range_to_spread;

        // update systems that have supply in them
        for (const auto& empire_supply : empire_propagating_supply_ranges) {
            for (const std::map<int, std::pair<float, float>>::value_type& supply_range : empire_supply.second)
            { systems_with_supply_in_them.insert(supply_range.first); }
        }


        // resolve supply fights between multiple empires in one system.
        // pass over all empire-supplied systems, removing supply for all
        // but the empire with the highest supply range in each system
        for (int sys_id : systems_with_supply_in_them) {
            // sort empires by range in this system
            std::map<float, std::set<int>> empire_ranges_here;
            for (auto& empire_supply : empire_propagating_supply_ranges) {
                int empire_id = empire_supply.first;
                std::map<int, std::pair<float, float>>::const_iterator empire_supply_it = empire_supply.second.find(sys_id);
                // does this empire have any range in this system? if so, store it
                if (empire_supply_it == empire_supply.second.end())
                    continue;

                // stuff to break ties...
                float bonus = 0.0f;

                // empires with planets in system
                bool has_outpost = false, has_colony = false;
                if (std::shared_ptr<const System> sys = GetSystem(sys_id)) {
                    std::vector<int> obj_ids;
                    std::copy(sys->ContainedObjectIDs().begin(), sys->ContainedObjectIDs().end(), std::back_inserter(obj_ids));
                    for (std::shared_ptr<UniverseObject> obj : Objects().FindObjects(obj_ids)) {
                        if (!obj)
                            continue;
                        if (!obj->OwnedBy(empire_id))
                            continue;
                        if (obj->ObjectType() == OBJ_PLANET) {
                            if (std::shared_ptr<Planet> planet = std::dynamic_pointer_cast<Planet>(obj)) {
                                if (!planet->SpeciesName().empty())
                                    has_colony = true;
                                else
                                    has_outpost = true;
                                continue;
                            }
                        }
                    }
                }
                if (has_colony)
                    bonus += 0.5f;
                else if (has_outpost)
                    bonus += 0.3f;

                // sum of all supply sources in this system
                bonus += empire_system_supply_range_sums[empire_id][sys_id] / 1000.0f;

                // distance to supply source from here
                float propagated_distance_to_supply_source = std::max(1.0f, empire_supply_it->second.second);
                bonus += 0.0001f / propagated_distance_to_supply_source;

                // store ids of empires indexed by adjusted propgated range, in order to sort by range
                float propagated_range = empire_supply_it->second.first;
                empire_ranges_here[propagated_range + bonus].insert(empire_id);
            }

            if (empire_ranges_here.empty())
                continue;   // no empire has supply here?
            if (empire_ranges_here.size() == 1 && empire_ranges_here.begin()->second.size() < 2)
                continue;   // only one empire has supply here

            // at least two empires have supply sources here...
            // check if one is stronger

            // remove supply for all empires except the top-ranged empire here
            // if there is a tie for top-ranged, remove all
            std::map<float, std::set<int>>::reverse_iterator range_empire_it = empire_ranges_here.rbegin();
            int top_range_empire_id = ALL_EMPIRES;
            if (range_empire_it->second.size() == 1) {
                // if just one empire has the most range, it is the top empire
                top_range_empire_id = *(range_empire_it->second.begin());
            }
            //DebugLogger() << "top ranged empire here: " << top_range_empire_id;

            // remove range entries and traversals for all but the top empire
            // (or all empires if there is no single top empire)
            for (auto& empire_supply : empire_propagating_supply_ranges) {
                int empire_id = empire_supply.first;
                if (empire_id == top_range_empire_id)
                    continue;   // this is the top empire, so leave as the sole empire supplying here

                // remove from range entry...
                std::map<int, std::pair<float, float>>& empire_ranges = empire_supply.second;
                empire_ranges.erase(sys_id);

                //DebugLogger() << "... removed empire " << empire_id << " system " << sys_id << " supply.";

                // Remove from unobstructed systems
                empire_supply_unobstructed_systems[empire_id].erase(sys_id);

                std::set<std::pair<int, int>>& lane_traversals = m_supply_starlane_traversals[empire_id];
                std::set<std::pair<int, int>> lane_traversals_initial = lane_traversals;
                std::set<std::pair<int, int>>& obstructed_traversals = m_supply_starlane_obstructed_traversals[empire_id];
                std::set<std::pair<int, int>> obstrcuted_traversals_initial = obstructed_traversals;

                // remove from traversals departing from or going to this system for this empire,
                // and set any traversals going to this system as obstructed
                for (const auto& lane : lane_traversals_initial) {
                    if (lane.first == sys_id) {
                        lane_traversals.erase(std::make_pair(sys_id, lane.second));
                    }
                    if (lane.second == sys_id) {
                        lane_traversals.erase(std::make_pair(lane.first, sys_id));
                        obstructed_traversals.insert(std::make_pair(lane.first, sys_id));
                    }
                }

                // remove obstructed traverals departing from this system
                for (const auto& lane : obstrcuted_traversals_initial) {
                    if (lane.first == sys_id)
                        obstructed_traversals.erase(std::make_pair(lane.first, lane.second));
                }
            }

            //// DEBUG
            //DebugLogger() << "after culling empires ranges at system " << sys_id << ":";
            //for (std::map<int, std::map<int, float>>::value_type& empire_supply : empire_propagating_supply_ranges) {
            //    std::map<int, float>& system_ranges = empire_supply.second;
            //    std::map<int, float>::iterator range_it = system_ranges.find(sys_id);
            //    if (range_it != system_ranges.end())
            //        DebugLogger() << empire_supply.first << " : " << range_it->second;
            //}
            //// END DEBUG
        }

        if (range_to_spread <= 0)
            break;

        // initialize next iteration with current supply distribution
        auto empire_propagating_supply_ranges_next = empire_propagating_supply_ranges;


        // for sources of supply of at least the minimum range for this
        // iteration that are in the current map, give adjacent systems one
        // less supply in the next iteration (unless as much or more is already
        // there)
        for (const auto& empire_supply : empire_propagating_supply_ranges) {
            int empire_id = empire_supply.first;
            //DebugLogger() << ">-< Doing supply propagation for empire " << empire_id << " >-<";
            const std::map<int, std::pair<float, float>>& prev_sys_ranges = empire_supply.second;
            const std::set<int>& unobstructed_systems = empire_supply_unobstructed_systems[empire_id];

            for (const std::map<int, std::pair<float, float>>::value_type& supply_range : empire_supply.second) {
                // does the source system have enough supply range to propagate outwards?
                float range = supply_range.second.first;
                if (range != range_to_spread)
                    continue;
                float range_after_one_more_jump = range - 1.0f; // what to set adjacent systems' ranges to (at least)

                // how far is this system from a source of supply for this empire?
                float distance_to_supply_source = supply_range.second.second;

                // what starlanes can be used to propagate supply?
                int system_id = supply_range.first;

                //DebugLogger() << "propagating from system " << system_id << " which has range: " << range << " and distance: " << distance_to_supply_source;

                // attempt to propagate to all adjacent systems...
                for (int lane_end_sys_id : empire_visible_starlanes[empire_id][system_id]) {
                    // is propagation to the adjacent system obstructed?
                    if (unobstructed_systems.find(lane_end_sys_id) == unobstructed_systems.end()) {
                        // propagation obstructed!
                        //DebugLogger() << "Added obstructed traversal from " << system_id << " to " << lane_end_sys_id << " due to not being on unobstructed systems";
                        m_supply_starlane_obstructed_traversals[empire_id].insert({system_id, lane_end_sys_id});
                        continue;
                    }
                    // propagation not obstructed.


                    // does another empire already have as much or more supply here from a previous iteration?
                    float other_empire_biggest_range = -10000.0f;   // arbitrary big numbeer
                    for (const std::map<int, std::map<int, std::pair<float, float>>>::value_type& other_empire_supply : empire_propagating_supply_ranges) {
                        int other_empire_id = other_empire_supply.first;
                        if (other_empire_id == empire_id)
                            continue;
                        const std::map<int, std::pair<float, float>>& prev_other_empire_sys_ranges = other_empire_supply.second;
                        std::map<int, std::pair<float, float>>::const_iterator prev_other_empire_range_it = prev_other_empire_sys_ranges.find(lane_end_sys_id);
                        if (prev_other_empire_range_it == prev_other_empire_sys_ranges.end())
                            continue;
                        if (prev_other_empire_range_it->second.first > other_empire_biggest_range)
                            other_empire_biggest_range = prev_other_empire_range_it->second.first;
                    }

                    // if so, add a blocked traversal and continue
                    if (range_after_one_more_jump <= other_empire_biggest_range) {
                        m_supply_starlane_obstructed_traversals[empire_id].insert(std::make_pair(system_id, lane_end_sys_id));
                        //DebugLogger() << "Added obstructed traversal from " << system_id << " to " << lane_end_sys_id << " due to other empire biggest range being " << other_empire_biggest_range;
                        continue;
                    }

                    // otherwise, propagate into system...
                    float lane_length = DistanceBetweenObjects(system_id, lane_end_sys_id);
                    float distance_to_supply_source_after_next_lane = lane_length + distance_to_supply_source;

                    //DebugLogger() << "Attempting to propagate into system: " << lane_end_sys_id << " the new range: " << range_after_one_more_jump << " and distance: " << distance_to_supply_source_after_next_lane;

                    // if propagating supply would increase the range of the adjacent system,
                    // or decrease the distance to the adjacent system from a supply source...
                    std::map<int, std::pair<float, float>>::const_iterator prev_range_it = prev_sys_ranges.find(lane_end_sys_id);
                    if (prev_range_it == prev_sys_ranges.end()) {
                        empire_propagating_supply_ranges_next[empire_id][lane_end_sys_id] =
                            {range_after_one_more_jump, distance_to_supply_source_after_next_lane};
                        //DebugLogger() << " ... default case: no previous entry.";

                    } else {
                        //DebugLogger() << " ... previous entry values: " << prev_range_it->second.first << " and " << prev_range_it->second.second;

                        if (range_after_one_more_jump > prev_range_it->second.first) {
                            empire_propagating_supply_ranges_next[empire_id][lane_end_sys_id].first =
                                range_after_one_more_jump;
                            //DebugLogger() << " ... range increased!";
                        }
                        if (distance_to_supply_source_after_next_lane < prev_range_it->second.second) {
                            empire_propagating_supply_ranges_next[empire_id][lane_end_sys_id].second =
                                distance_to_supply_source_after_next_lane;
                            //DebugLogger() << " ... distance decreased!";
                        }
                    }
                    // always record a traversal, so connectivity is calculated properly
                    m_supply_starlane_traversals[empire_id].insert({system_id, lane_end_sys_id});
                    //DebugLogger() << "Added traversal from " << system_id << " to " << lane_end_sys_id;

                    // erase any previous obstructed traversal that just succeeded
                    if (m_supply_starlane_obstructed_traversals[empire_id].find(std::make_pair(system_id, lane_end_sys_id)) !=
                        m_supply_starlane_obstructed_traversals[empire_id].end())
                    {
                        //DebugLogger() << "Removed obstructed traversal from " << system_id << " to " << lane_end_sys_id;
                        m_supply_starlane_obstructed_traversals[empire_id].erase(std::make_pair(system_id, lane_end_sys_id));
                    }
                    if (m_supply_starlane_obstructed_traversals[empire_id].find(std::make_pair(lane_end_sys_id, system_id)) !=
                        m_supply_starlane_obstructed_traversals[empire_id].end())
                    {
                        //DebugLogger() << "Removed obstructed traversal from " << lane_end_sys_id << " to " << system_id;
                        m_supply_starlane_obstructed_traversals[empire_id].erase(std::make_pair(lane_end_sys_id, system_id));
                    }
                }
            }
        }

        // save propagated results for next iteration
        empire_propagating_supply_ranges = empire_propagating_supply_ranges_next;
    }

    //// DEBUG
    //DebugLogger() << "SuppolyManager::Update: after removing conflicts, empires can provide supply to the following system ids:";
    //for (std::map<int, std::map<int, float>>::value_type& empire_supply : empire_propagating_supply_ranges) {
    //    int empire_id = empire_supply.first;
    //    std::stringstream ss;
    //    for (std::map<int, float>::value_type& supply_range : empire_supply.second) {
    //        ss << supply_range.first << " (" << supply_range.second << "),  ";
    //    }
    //    DebugLogger() << "empire: " << empire_id << ":  " << ss.str();
    //}
    //// END DEBUG

    // record which systems are fleet supplyable by each empire (after resolving conflicts in each system)
    for (const auto& empire_supply : empire_propagating_supply_ranges) {
        int empire_id = empire_supply.first;
        for (const auto& supply_range : empire_supply.second) {
            if (supply_range.second.first < 0.0f)
                continue;   // negative supply doesn't count... zero does (it just reaches)
            m_fleet_supplyable_system_ids[empire_id].insert(supply_range.first);

            // should be only one empire per system at this point, but use max just to be safe...
            m_propagated_supply_ranges[supply_range.first] =
                std::max(supply_range.second.first, m_propagated_supply_ranges[supply_range.first]);
            m_empire_propagated_supply_ranges[empire_id][supply_range.first] =
                m_propagated_supply_ranges[supply_range.first];

            // should be only one empire per system at this point, but use max just to be safe...
            m_propagated_supply_distances[supply_range.first] =
                std::max(supply_range.second.second, m_propagated_supply_distances[supply_range.first]);
            m_empire_propagated_supply_distances[empire_id][supply_range.first] =
                m_propagated_supply_distances[supply_range.first];
        }

        //DebugLogger() << "For empire: " << empire_id << " system supply distances: ";
        //for (auto entry : m_empire_propagated_supply_distances[empire_id]) {
        //    DebugLogger() << entry.first << " : " << entry.second;
        //}
    }



    // TEST STUFF FOR INTER-EMPIRE-MERGING
    std::map<int, std::set<std::pair<int, int>>> ally_merged_supply_starlane_traversals = m_supply_starlane_traversals;

    // add connections into allied empire systems when their obstructed lane
    // traversals originate on either end of a starlane
    for (auto& empire_set : m_supply_starlane_obstructed_traversals) {
        // input:
        const std::set<std::pair<int, int>>& empire_obstructed_traversals = empire_set.second;
        // output:
        std::set<std::pair<int, int>>& empire_supply_traversals = ally_merged_supply_starlane_traversals[empire_set.first];


        std::set<int> allies_of_empire = Empires().GetEmpireIDsWithDiplomaticStatusWithEmpire(empire_set.first, DIPLO_ALLIED);
        for (int ally_id : allies_of_empire) {
            // input:
            auto const& ally_obstructed_traversals = m_supply_starlane_obstructed_traversals[ally_id];

            // find cases where outer loop empire has an obstructed traversal from A to B
            // and inner loop empire has an obstructed traversal from B to A
            for (auto const& empire_trav : empire_obstructed_traversals) {
                for (auto const& ally_trav : ally_obstructed_traversals) {
                    if (empire_trav.first == ally_trav.second && empire_trav.second == ally_trav.first) {
                        empire_supply_traversals.insert({empire_trav.first, empire_trav.second});
                        empire_supply_traversals.insert({empire_trav.second, empire_trav.first});
                    }
                }
            }
        }
    }

    // add allied supply starlane traversals to empires' traversals, so that
    // allies can use eachothers' supply networks
    for (auto& empire_set : ally_merged_supply_starlane_traversals) {
        std::set<std::pair<int, int>>& output_empire_traversals = empire_set.second;
        for (int ally_id : Empires().GetEmpireIDsWithDiplomaticStatusWithEmpire(empire_set.first, DIPLO_ALLIED)) {
            // copy ally traversals into the output empire traversals set
            for (const auto& traversal_pair : m_supply_starlane_traversals[ally_id])
                output_empire_traversals.insert(traversal_pair);
        }
    }

    // same for fleet supplyable system ids, as these are added to supplyable
    // groups in following code
    auto ally_merged_fleet_supplyable_system_ids = m_fleet_supplyable_system_ids;
    for (auto& empire_set : ally_merged_fleet_supplyable_system_ids) {
        std::set<int>& output_empire_ids = empire_set.second;
        for (int ally_id : Empires().GetEmpireIDsWithDiplomaticStatusWithEmpire(empire_set.first, DIPLO_ALLIED)) {
            // copy ally traversals into the output empire traversals set
            for (int sys_id : m_fleet_supplyable_system_ids[ally_id])
                output_empire_ids.insert(sys_id);
        }
    }

    // END TEST STUFF FOR INTER-EMPIRE-MERGING



    // determine supply-connected groups of systems for each empire.
    // need to merge interconnected supply groups into as few sets of mutually-
    // supply-exchanging systems as possible.  This requires finding the
    // connected components of an undirected graph, where the node
    // adjacency are the directly-connected systems determined above.
    for (const auto& empire_supply : empire_propagating_supply_ranges) {
        int empire_id = empire_supply.first;

        // assemble all direct connections between systems from remaining traversals
        std::map<int, std::set<int>> supply_groups_map;
        for (auto const& lane : ally_merged_supply_starlane_traversals[empire_id]) {
            supply_groups_map[lane.first].insert(lane.second);
            supply_groups_map[lane.second].insert(lane.first);
        }

        // also add connections from all fleet-supplyable systems to themselves, so that
        // any fleet supply able system with no connection to another system can still
        // have resource sharing within tiself
        for (int system_id : ally_merged_fleet_supplyable_system_ids[empire_id])
            supply_groups_map[system_id].insert(system_id);


        if (supply_groups_map.empty())
            continue;

        //DebugLogger() << "Empire " << empire_id << " supply groups map:";
        //for (auto const& q : supply_groups_map) {
        //    int source_id = q.first;

        //    std::stringstream other_ids;
        //    for (auto const& r : q.second)
        //    { other_ids << r << ", "; }

        //    DebugLogger() << " ... src: " << source_id << " to: " << other_ids.str();
        //}


        // create graph
        boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS> graph;

        // boost expects vertex labels to range from 0 to num vertices - 1, so need
        // to map from system id to graph id and back when accessing vertices
        std::vector<int> graph_id_to_sys_id;
        graph_id_to_sys_id.reserve(supply_groups_map.size());

        std::map<int, int> sys_id_to_graph_id;
        int graph_id = 0;
        for (std::map<int, std::set<int>>::value_type& supply_group : supply_groups_map) {
            int sys_id = supply_group.first;
            boost::add_vertex(graph);   // should add with index = graph_id

            graph_id_to_sys_id.push_back(sys_id);
            sys_id_to_graph_id[sys_id] = graph_id;
            ++graph_id;
        }

        // add edges for all direct connections between systems
        // and add edges from fleet supplyable systems to themselves
        for (std::map<int, std::set<int>>::value_type& supply_group : supply_groups_map) {
            int start_graph_id = sys_id_to_graph_id[supply_group.first];
            for (int system_id : supply_group.second) {
                int end_graph_id = sys_id_to_graph_id[system_id];
                boost::add_edge(start_graph_id, end_graph_id, graph);
            }
        }

        // declare storage and fill with the component id (group id of connected systems)
        // for each graph vertex
        std::vector<int> components(boost::num_vertices(graph));
        boost::connected_components(graph, &components[0]);

        // convert results back from graph id to system id, and into desired output format
        // output: std::map<int, std::set<std::set<int>>>& m_resource_supply_groups

        // first, sort into a map from component id to set of system ids in component
        std::map<int, std::set<int>> component_sets_map;
        for (std::size_t comp_graph_id = 0; comp_graph_id != components.size(); ++comp_graph_id) {
            int label = components[comp_graph_id];
            int sys_id = graph_id_to_sys_id[comp_graph_id];
            component_sets_map[label].insert(sys_id);
        }

        // copy sets in map into set of sets
        for (std::map<int, std::set<int>>::value_type& component_set : component_sets_map)
            m_resource_supply_groups[empire_id].insert(component_set.second);
    }
}
コード例 #12
0
ファイル: DrawMolecule.C プロジェクト: gzoppetti/ExscitechVmd
// return Nth component ... change to proper return type
DrawMolItem *DrawMolecule::component(int n) {
  if(n >= 0 && n < components())
    return repList[n];
  else
    return NULL;
}
コード例 #13
0
ファイル: DrawMolecule.C プロジェクト: gzoppetti/ExscitechVmd
// add or remove a timestep
void DrawMolecule::addremove_ts() {
  int numcomp = components();
  for (int i=0; i<numcomp; i++) 
    component(i)->change_traj();
}
コード例 #14
0
QStringList StringOffsetProvider::components()
{
	if (!vis_) return QStringList();
	return components(vis_->node());
}
コード例 #15
0
ファイル: shortest_path.cpp プロジェクト: ucrbioinfo/MergeMap
    void CG::round_lp_randomized(vector<int> nodes){ 
        // step0 decide if the sub-problem is solved already

        map<int, int> ori_2_new_map;
        for (int ii = 0; ii < nodes.size(); ii++) {
            ori_2_new_map[nodes[ii]] = ii;
        }
        
        double total_probs = 0.0; // care should be taken when dealing with nodes that have been deleted already
        vector<double> probs;
        probs.resize(nodes.size());
        for (int ii = 0; ii < nodes.size(); ii++) {
            if (g_[nodes[ii]].to_delete) {
                probs[ii] = 0.0;
            } else {
                probs[ii] = g_[nodes[ii]].nor_dual_val;
                total_probs = total_probs + probs[ii];
            }
        }
        
        bool exist_none_special_edges = exist_no_special_edge(nodes);
        
        if (not exist_none_special_edges) {
            return;
        }

        // step1: sample one node to delete
        // random_double is a number between 0 and total_probs        
        double random_double = ((rand() + 0.5) / (double(RAND_MAX) + 1)) * total_probs;
        cout << "dbg print:random_double" << random_double / total_probs << endl;
        double accumulated_probs = 0.0;
        int delete_index;
        for (int ii = 0; ii < nodes.size(); ii++) {
            delete_index = ii;
            if (probs[ii] == 0.0) continue;
            accumulated_probs = accumulated_probs + probs[ii];
            if (accumulated_probs > random_double) break;
        }
        
        // step2: delete the vertex
        g_[nodes[delete_index]].to_delete = true;

        
        // step 3: construct a graph. Find out the strongly connected components
        typedef boost::adjacency_list<vecS,vecS,directedS> Graph;
        Graph G(nodes.size());
        for (int ii = 0; ii < nodes.size(); ii++) {
            if (not g_[nodes[ii]].to_delete) {
                for (int jj = 0; jj < g_[nodes[ii]].num_edges; jj++) {
                    int to_id = g_[nodes[ii]].edges[jj].to_id;
                    if ((ori_2_new_map.find(to_id) != ori_2_new_map.end()) and 
                        (not g_[to_id].to_delete)) {
                        add_edge(ii, ori_2_new_map[to_id], G);                    
                    }
                }
            }
        }        
        vector<int> components(nodes.size(),-1);
        int num = strong_components(G,&components[0]);

        // step4: recurse
        vector<vector<int> > sccs;
        sccs.resize(num);
        for (int ii = 0; ii < nodes.size(); ii++){
            assert(components[ii] < num);
            assert(components[ii] >= 0);
            sccs[components[ii]].push_back(nodes[ii]);
        }
        for (int ii = 0; ii < num; ii++) {
            round_lp_randomized(sccs[ii]);
        }
        
    };
コード例 #16
0
ファイル: qt_accessors.cpp プロジェクト: ahinoamp/Research
void TrendComponents_accessor::clear() {
  std::vector<bool> components( 9, false );
  selector_->setTrendComponents( components );
}
コード例 #17
0
ファイル: shortest_path.cpp プロジェクト: ucrbioinfo/MergeMap
    void CG::round_lp_greedy(vector<int> nodes){ 
        // step0 decide if the sub-problem is solved already

        map<int, int> ori_2_new_map;
        for (int ii = 0; ii < nodes.size(); ii++) {
            ori_2_new_map[nodes[ii]] = ii;
        }
        
        double total_probs = 0.0; // care should be taken when dealing with nodes that have been deleted already
        vector<double> probs;
        probs.resize(nodes.size());
        for (int ii = 0; ii < nodes.size(); ii++) {
            if (g_[nodes[ii]].to_delete) {
                probs[ii] = 0.0;
            } else {
                probs[ii] = g_[nodes[ii]].nor_dual_val;
                total_probs = total_probs + probs[ii];
            }
        }
        
        bool exist_none_special_edges = exist_no_special_edge(nodes);
        
        if (not exist_none_special_edges) {
            return;
        }

        // step1: sample one node to delete
        // use a greedy approach to decide which node to delete
        int delete_index = -1;
        double max_prob = 0.0;
        for (int ii = 0; ii < nodes.size(); ii++) {
            if (probs[ii] > max_prob) {
                delete_index = ii;
                max_prob = probs[ii];
            }
        }
        assert(delete_index != -1);
        
        // step2: delete the vertex
        g_[nodes[delete_index]].to_delete = true;

        
        // step 3: construct a graph. Find out the strongly connected components
        typedef boost::adjacency_list<vecS,vecS,directedS> Graph;
        Graph G(nodes.size());
        for (int ii = 0; ii < nodes.size(); ii++) {
            if (not g_[nodes[ii]].to_delete) {
                for (int jj = 0; jj < g_[nodes[ii]].num_edges; jj++) {
                    int to_id = g_[nodes[ii]].edges[jj].to_id;
                    if ((ori_2_new_map.find(to_id) != ori_2_new_map.end()) and 
                        (not g_[to_id].to_delete)) {
                        add_edge(ii, ori_2_new_map[to_id], G);                    
                    }
                }
            }
        }        
        vector<int> components(nodes.size(),-1);
        int num = strong_components(G,&components[0]);

        // step4: recurse
        vector<vector<int> > sccs;
        sccs.resize(num);
        for (int ii = 0; ii < nodes.size(); ii++){
            assert(components[ii] < num);
            assert(components[ii] >= 0);
            sccs[components[ii]].push_back(nodes[ii]);
        }
        for (int ii = 0; ii < num; ii++) {
            round_lp_greedy(sccs[ii]);
        }
        
    };
コード例 #18
0
void
SolutionImageWriter::write(
		const Crag& crag,
		const CragVolumes& volumes,
		const CragSolution& solution,
		const std::string& basename,
		bool boundary) {

	LOG_DEBUG(solutionimagewriterlog) << "storing solution in " << basename << std::endl;

	if (_volumesBB.isZero())
		_volumesBB = volumes.getBoundingBox();

	LOG_DEBUG(solutionimagewriterlog) << "using bounding box of " << _volumesBB << std::endl;

	util::point<float, 3> resolution;
	for (Crag::CragNode n : crag.nodes()) {

		if (!crag.isLeafNode(n))
			continue;
		resolution = volumes[n]->getResolution();
		break;
	}

	LOG_DEBUG(solutionimagewriterlog) << "using resolution of " << resolution << std::endl;

	// create a vigra multi-array large enough to hold all volumes
	vigra::MultiArray<3, float> components(
			vigra::Shape3(
				_volumesBB.width() /resolution.x(),
				_volumesBB.height()/resolution.y(),
				_volumesBB.depth() /resolution.z()),
			std::numeric_limits<int>::max());

	// background for areas without candidates
	if (boundary)
		components = 0.25;
	else
		components = 0;

	for (Crag::CragNode n : crag.nodes()) {

		LOG_ALL(solutionimagewriterlog) << "drawing node " << crag.id(n) << std::endl;

		// draw only selected nodes
		if (!solution.selected(n))
			continue;

		const util::point<float, 3>&      volumeOffset     = volumes[n]->getOffset();
		const util::box<unsigned int, 3>& volumeDiscreteBB = volumes[n]->getDiscreteBoundingBox();

		util::point<unsigned int, 3> begin = (volumeOffset - _volumesBB.min())/resolution;
		util::point<unsigned int, 3> end   = begin +
				util::point<unsigned int, 3>(
						volumeDiscreteBB.width(),
						volumeDiscreteBB.height(),
						volumeDiscreteBB.depth());

		LOG_ALL(solutionimagewriterlog) << "\toffset      : " << volumeOffset << std::endl;
		LOG_ALL(solutionimagewriterlog) << "\tdiscrete bb : " << volumeDiscreteBB << std::endl;
		LOG_ALL(solutionimagewriterlog) << "\ttarget area : " << begin << " -- " << end << std::endl;

		// fill id of connected component
		vigra::combineTwoMultiArrays(
			volumes[n]->data(),
			components.subarray(TinyVector3UInt(&begin[0]),TinyVector3UInt(&end[0])),
			components.subarray(TinyVector3UInt(&begin[0]),TinyVector3UInt(&end[0])),
			vigra::functor::ifThenElse(
					vigra::functor::Arg1() == vigra::functor::Param(1),
					vigra::functor::Param(solution.label(n)),
					vigra::functor::Arg2()
		));
	}

	if (boundary) {

		// gray boundary for all leaf nodes
		for (Crag::CragNode n : crag.nodes())
			if (crag.isLeafNode(n))
				drawBoundary(volumes, n, components, 0.5);

		// black boundary for all selected nodes
		for (Crag::CragNode n : crag.nodes())
			if (solution.selected(n))
				drawBoundary(volumes, n, components, 0);
	}

	if (components.shape(2) > 1) {

		boost::filesystem::create_directory(basename);
		for (unsigned int z = 0; z < components.shape(2); z++) {

			std::stringstream ss;
			ss << std::setw(4) << std::setfill('0') << z;
			vigra::exportImage(
					components.bind<2>(z),
					vigra::ImageExportInfo((basename + "/" + ss.str() + ".tif").c_str()));
		}

	} else {

		vigra::exportImage(
				components.bind<2>(0),
				vigra::ImageExportInfo((basename + ".tif").c_str()));
	}
}
コード例 #19
0
void
v4r::MultiPlaneSegmentation<PointT>::segment(bool force_unorganized)
{
  models_.clear();

  if(input_->isOrganized() && !force_unorganized)
  {
    pcl::PointCloud<pcl::Normal>::Ptr normal_cloud (new pcl::PointCloud<pcl::Normal>);
    if(!normals_set_)
    {
        pcl::IntegralImageNormalEstimation<PointT, pcl::Normal> ne;
        ne.setNormalEstimationMethod (ne.COVARIANCE_MATRIX);
        ne.setMaxDepthChangeFactor (0.02f);
        ne.setNormalSmoothingSize (20.0f);
        ne.setBorderPolicy (pcl::IntegralImageNormalEstimation<PointT, pcl::Normal>::BORDER_POLICY_IGNORE);
        ne.setInputCloud (input_);
        ne.compute (*normal_cloud);
    }
    else
    {
        normal_cloud = normal_cloud_;
    }

    pcl::OrganizedMultiPlaneSegmentation<PointT, pcl::Normal, pcl::Label> mps;
    mps.setMinInliers (min_plane_inliers_);
    mps.setAngularThreshold (0.017453 * 2.f); // 2 degrees
    mps.setDistanceThreshold (0.01); // 1cm
    mps.setMaximumCurvature(0.002);
    mps.setInputNormals (normal_cloud);
    mps.setInputCloud (input_);

    std::vector<pcl::PlanarRegion<PointT>, Eigen::aligned_allocator<pcl::PlanarRegion<PointT> > > regions;
    std::vector<pcl::ModelCoefficients> model_coefficients;
    std::vector<pcl::PointIndices> inlier_indices;
    pcl::PointCloud<pcl::Label>::Ptr labels (new pcl::PointCloud<pcl::Label>);
    std::vector<pcl::PointIndices> label_indices;
    std::vector<pcl::PointIndices> boundary_indices;

    typename pcl::PlaneRefinementComparator<PointT, pcl::Normal, pcl::Label>::Ptr ref_comp (
                                                                                             new pcl::PlaneRefinementComparator<PointT,
                                                                                                 pcl::Normal, pcl::Label> ());
    ref_comp->setDistanceThreshold (0.01f, false);
    ref_comp->setAngularThreshold (0.017453 * 2.f);
    mps.setRefinementComparator (ref_comp);
    mps.segmentAndRefine (regions, model_coefficients, inlier_indices, labels, label_indices, boundary_indices);
    //mps.segment (model_coefficients, inlier_indices);

    //std::cout << model_coefficients.size() << std::endl;

    if(merge_planes_)
    {
      //sort planes by size
      //check if the first plane can be merged against the others, if yes, define a new plane combining both and add it to the cue

      typedef boost::adjacency_matrix<boost::undirectedS, int> GraphPlane;
      GraphPlane mergeable_planes (model_coefficients.size ());
      for(size_t i=0; i < model_coefficients.size(); i++)
      {

        Eigen::Vector3f plane_i = Eigen::Vector3f (model_coefficients[i].values[0], model_coefficients[i].values[1],
                                                   model_coefficients[i].values[2]);

        plane_i.normalize();
        for(size_t j=(i+1); j < model_coefficients.size(); j++)
        {
          Eigen::Vector3f plane_j = Eigen::Vector3f (model_coefficients[j].values[0], model_coefficients[j].values[1],
                                                     model_coefficients[j].values[2]);

          plane_j.normalize();

          //std::cout << "dot product:" << plane_i.dot(plane_j) << " diff:" << std::abs(model_coefficients[i].values[3] - model_coefficients[j].values[3]) << std::endl;
          if(plane_i.dot(plane_j) > 0.95)
          {
            if(std::abs(model_coefficients[i].values[3] - model_coefficients[j].values[3]) < 0.015)
            {
              boost::add_edge (static_cast<int>(i), static_cast<int>(j), mergeable_planes);
            }
          }
        }
      }

      boost::vector_property_map<int> components (boost::num_vertices (mergeable_planes));
      int n_cc = static_cast<int> (boost::connected_components (mergeable_planes, &components[0]));

      std::vector<int> cc_sizes;
      std::vector< std::vector<int> > cc_to_model_coeff;
      cc_sizes.resize (n_cc, 0);
      cc_to_model_coeff.resize(n_cc);

      for (size_t i = 0; i < model_coefficients.size (); i++)
      {
        cc_sizes[components[i]]++;
        cc_to_model_coeff[components[i]].push_back(i);
      }

      std::vector<pcl::ModelCoefficients> new_model_coefficients;
      std::vector<pcl::PointIndices> new_inlier_indices;

      for(size_t i=0; i < cc_sizes.size(); i++)
      {
        if(cc_sizes[i] < 2)
        {
          new_model_coefficients.push_back(model_coefficients[cc_to_model_coeff[i][0]]);
          new_inlier_indices.push_back(inlier_indices[cc_to_model_coeff[i][0]]);
          continue;
        }

        //std::cout << "going to merge CC:" << cc_sizes[i] << std::endl;
        pcl::ModelCoefficients model_coeff;
        model_coeff.values.resize(4);

        for(size_t k=0; k < 4; k++)
          model_coeff.values[k] = 0.f;

        pcl::PointIndices merged_indices;
        for(size_t j=0; j < cc_to_model_coeff[i].size(); j++)
        {
          for(size_t k=0; k < 4; k++)
            model_coeff.values[k] += model_coefficients[cc_to_model_coeff[i][j]].values[k];

          merged_indices.indices.insert(merged_indices.indices.end(), inlier_indices[cc_to_model_coeff[i][j]].indices.begin(),
                                                                      inlier_indices[cc_to_model_coeff[i][j]].indices.end());
        }

        for(size_t k=0; k < 4; k++)
          model_coeff.values[k] /= static_cast<float>(cc_to_model_coeff[i].size());

        new_model_coefficients.push_back(model_coeff);
        new_inlier_indices.push_back(merged_indices);
      }

      model_coefficients = new_model_coefficients;
      inlier_indices = new_inlier_indices;
    }

    for(size_t i=0; i < model_coefficients.size(); i++)
    {
      PlaneModel<PointT> pm;
      pm.coefficients_ = model_coefficients[i];
      pm.cloud_ = input_;
      pm.inliers_ = inlier_indices[i];

      //recompute coefficients based on distance to camera and normal?
      Eigen::Vector4f centroid;
      pcl::compute3DCentroid(*pm.cloud_, pm.inliers_, centroid);
      Eigen::Vector3f c(centroid[0],centroid[1],centroid[2]);

      Eigen::MatrixXf M_w(inlier_indices[i].indices.size(), 3);

      float sum_w = 0.f;
      for(size_t k=0; k < inlier_indices[i].indices.size(); k++)
      {
          const int &idx = inlier_indices[i].indices[k];
          float d_c = (pm.cloud_->points[idx].getVector3fMap()).norm();
          float w_k = std::max(1.f - std::abs(1.f - d_c), 0.f);
          //w_k = 1.f;
          M_w.row(k) = w_k * (pm.cloud_->points[idx].getVector3fMap() - c);
          sum_w += w_k;
      }

      Eigen::Matrix3f scatter;
      scatter.setZero ();
      scatter = M_w.transpose() * M_w;

      Eigen::JacobiSVD<Eigen::MatrixXf> svd(scatter, Eigen::ComputeFullV);
      //std::cout << svd.matrixV() << std::endl;

      Eigen::Vector3f n = svd.matrixV().col(2);
      //flip normal if required
      if(n.dot(c*-1) < 0)
          n = n * -1.f;

      float d = n.dot(c) * -1.f;
      //std::cout << "normal:" << n << std::endl;
      //std::cout << "d:" << d << std::endl;

      pm.coefficients_.values[0] = n[0];
      pm.coefficients_.values[1] = n[1];
      pm.coefficients_.values[2] = n[2];
      pm.coefficients_.values[3] = d;

      pcl::PointIndices clean_inlier_indices;
      float dist_threshold_ = 0.01f;

      for(size_t k=0; k < inlier_indices[i].indices.size(); k++)
      {
          const int &idx = inlier_indices[i].indices[k];
          Eigen::Vector3f p = pm.cloud_->points[idx].getVector3fMap();
          float val = n.dot(p) + d;

          if(std::abs(val) <= dist_threshold_)
              clean_inlier_indices.indices.push_back( idx );
      }

      pm.inliers_ = clean_inlier_indices;
      models_.push_back(pm);
    }
  }
  else
  {
    // Create the filtering object: downsample the dataset using a leaf size of 1cm
    pcl::VoxelGrid<PointT> vg;
    PointTCloudPtr cloud_filtered (new PointTCloud);
    vg.setInputCloud (input_);
    float leaf_size_ = 0.005f;
    float dist_threshold_ = 0.01f;
    vg.setLeafSize (leaf_size_, leaf_size_, leaf_size_);
    vg.filter (*cloud_filtered);

    std::vector<bool> pixel_has_not_been_labelled( cloud_filtered->points.size(), true );

    // Create the segmentation object for the planar model and set all the parameters
    pcl::SACSegmentation<PointT> seg;
    pcl::ModelCoefficients coefficients;
    seg.setOptimizeCoefficients (true);
    seg.setModelType (pcl::SACMODEL_PLANE);
    seg.setMethodType (pcl::SAC_RANSAC);
    seg.setMaxIterations (1000);
    seg.setDistanceThreshold (dist_threshold_);

    PointTCloudPtr cloud_filtered_leftover (new PointTCloud (*cloud_filtered));

    while (1)
    {
      // Segment the largest planar component from the remaining cloud
      seg.setInputCloud (cloud_filtered_leftover);
      pcl::PointIndices inliers_in_leftover;
      seg.segment (inliers_in_leftover, coefficients);

      std::cout << "inliers in left over: " << inliers_in_leftover.indices.size() << " of " << cloud_filtered_leftover->points.size() << std::endl;

      if ( (int)inliers_in_leftover.indices.size () < min_plane_inliers_) // Could not estimate a(nother) planar model big enough for the given cloud.
        break;


      // make indices correspond to complete downsampled cloud
      pcl::PointIndices indices_in_original_cloud;
      size_t current_index_in_leftover = 0;
      size_t px=0;
      indices_in_original_cloud.indices.resize(inliers_in_leftover.indices.size());
      for(size_t inl_id=0; inl_id < inliers_in_leftover.indices.size(); inl_id++) {    // assumes indices are sorted in ascending order
          bool found = false;
          do {
              if( pixel_has_not_been_labelled[px] ) {
                  if( current_index_in_leftover == inliers_in_leftover.indices [inl_id] ) {
                      indices_in_original_cloud.indices[ inl_id ] = px;
                      found = true;
                  }
                  current_index_in_leftover++;
              }
              px++;
          } while( !found );
      }

      for(size_t i=0; i<indices_in_original_cloud.indices.size(); i++)
          pixel_has_not_been_labelled[ indices_in_original_cloud.indices[i] ] = false;


      //save coefficients
        PlaneModel<PointT> pm;
        pm.coefficients_ = coefficients;
        pm.cloud_ = cloud_filtered;
        pm.inliers_ = indices_in_original_cloud;
        models_.push_back(pm);

        pcl::copyPointCloud(*cloud_filtered, pixel_has_not_been_labelled, *cloud_filtered_leftover);
    }

    std::cout << "Number of planes found:" << models_.size() << "organized:" << static_cast<int>(input_->isOrganized() && !force_unorganized) << std::endl;
  }
}
コード例 #20
0
ファイル: HYConsoleWindow.cpp プロジェクト: mdsmith/OCLHYPHY
bool	_HYConsoleWindow::ProcessEvent (_HYEvent* e)
{
	bool	done = false;
	
	_String firstArg;
	long	i,f,k;
	
	if (e->EventClass().Equal(&_hyButtonPushEvent))
	{
		firstArg = e->EventCode().Cut (0,(f=e->EventCode().Find(','))-1);
		k = firstArg.toNum();
		for (i=0;i<components.lLength;i++)
		{
			if (((_HYGuiObject*)components(i))->MatchID(k))
				break;
		}
		if (i==2)
		{
			firstArg 		= e->EventCode().Cut (f+1,-1);
			k 				= firstArg.toNum();
			_HYButtonBar * bb = (_HYButtonBar*)GetObject (2);
			
			switch	(k)
			{
				case 0:
				case 1:
					{

						_List menuChoices;
						if (k==0)
							for (long k=0; k<userHookins.lLength; k++)
							{
								_String *dName =  (_String*)userHookins(k),
										aName (*dName, dName->FindBackwards (
										#ifdef __MAC__
											':'
										#else
											#ifdef __WINDOZE__
											'\\'
											#else
											'/'
											#endif
										#endif
										,0,-1)+1,-1);
										
								menuChoices && & aName;
							}
						else
						{
							firstArg = "Search Commands";
							menuChoices && & firstArg;
							firstArg = "Search Descriptions";
							menuChoices && & firstArg;
							firstArg = "Search Notes";
							menuChoices && & firstArg;
							firstArg = "Export to LaTeX by name";
							menuChoices && & firstArg;
							firstArg = menuSeparator;
							menuChoices && & firstArg;
							firstArg = "Open in a window";
							menuChoices && & firstArg;
						}
						
						int h,v;
						bb->GetButtonLoc(k,h,v,true);
						_String userAction = HandlePullDown (menuChoices,h,v,0);
						bb->_UnpushButton();
						i = menuChoices.Find (&userAction);
						if (i>=0)
						{
							_ExecutionList uxl;
							if (k==0)
							{
								userAction = ((_String*)userHookins(i))->getStr();
							}
							else
								userAction = baseDirectory&"Help"&baseDirectory.sData[baseDirectory.sLength-1]&"Commands"&baseDirectory.sData[baseDirectory.sLength-1]&"query.bf";
							
							h = PushFilePath  (userAction);
							ReadBatchFile (userAction, uxl);
							
							if (k==1)
							{
								_String addin;
								switch (i)
								{
									case 0:
										addin = "Command";
										break;
									case 1:
										addin = "Description";
										break;
									case 2:
										addin = "Notes";
										break;
									case 3:
										addin = "Export";
										break;
									case 5:
										addin = "Window";
										break;
								}
								firstArg = ((_HYTextBox*)GetObject (1))->GetText();
								_FString qf = _FString (addin,false),
										 qt = _FString (firstArg,false);
								
								firstArg = "QUERY_FIELD";
								setParameter (firstArg,&qf);
								firstArg = "QUERY_TERM";
								setParameter (firstArg,&qt);
							}
								
							uxl.Execute();
							terminateExecution = false;
							if (h)
								PopFilePath   ();
							/*}
							else
							{
								userAction = userAction & " could not be found. Perhaps the file was recently moved or deleted.";
								ProblemReport (userAction, (Ptr)this);
							}*/
						}
					}
					break;
					
				case 2: 
					DoEcho();
					break;					

				case 3: 
				{
					_String webUpdate = baseDirectory&"TemplateBatchFiles"&baseDirectory.sData[baseDirectory.sLength-1]&"WebUpdate.bf";
					_ExecutionList wbl;
					k = PushFilePath  (webUpdate);
					ReadBatchFile (webUpdate, wbl);
					wbl.Execute();
					terminateExecution = false;
					if (k)
						PopFilePath   ();

				}
			}
			
			done = true;
		}
	}
	else
		if (e->EventClass().Equal(&_hyTextEditChange))
		{
			firstArg = e->EventCode().Cut (0,(f=e->EventCode().Find(','))-1);
			k = firstArg.toNum();
			for (i=0;i<components.lLength;i++)
			{
				if (((_HYGuiObject*)components(i))->MatchID(k))
					break;
			}
			if (i==0) // out box
			{
				_UpdateEditMenu();
				done = true;
			}		
			else
				if (i==1) // in box
				{
					firstArg 		= e->EventCode().Cut (f+1,-1);
					k 				= firstArg.toNum();
					_HYTextBox * ib = (_HYTextBox*)GetObject (1);
					
					if (k==2)
					{
						if (inputStatus == 1)
							inputStatus = 2;
					}
					else
					{
						if (k==3)
						// down arrow
						{
							if (inputLocation<recentInputs.lLength-1)
								ib->SetText (*(_String*)recentInputs(++inputLocation), false);
						}
						else 
							if (k==4)
							// up arrow
							{
								if (inputLocation>0)
									ib->SetText (*(_String*)recentInputs(--inputLocation), false);
							}
							else
							{	
								if (inputStatus == 1)
									inputLocation = recentInputs.lLength;
									
								_HYButtonBar * bb = (_HYButtonBar*)GetObject (2);
								bool 	onOff = ! ib->_IsEmpty();
								bb->EnableButton   (1,onOff);
							}
					}
					done = true;
				}		
		}
								
	if (done) 
	{
		DeleteObject (e);
		return true;
	}
	return _HYTWindow::ProcessEvent(e);	
}
コード例 #21
0
Vector<Vector<double> >  Detector::EvaluateTemplate(const Matrix<double> &upper_body_template,
                                                        const Matrix<double> &depth_map,
                                                        Vector<Vector<double> > &close_range_BBoxes,
                                                        Vector<Vector<double> > distances)
{
    int stride = Globals::evaluation_stride;
    int nr_scales = Globals::evaluation_nr_scales;
    int inc_cropped_height = Globals::evaluation_inc_cropped_height;

    // performance helper variables: just for avoiding recalculation
    int int_half_template_size = Globals::template_size / 2;
    double double_half_template_size = Globals::template_size / 2.0;

    Vector<Vector<double> > final_result;

    // generate the scales
    Vector<double> all_scales(nr_scales, 1.0);
    all_scales(0) = 1;
    for(int sc = 1; sc < nr_scales; ++sc)
    {
        all_scales(sc) = pow(Globals::evaluation_scale_stride,sc);
    }

//    Matrix<double> roi_img(Globals::dImWidth, Globals::dImHeight, 0);
    if(visualize_roi)
        roi_image = Matrix<int>(Globals::dImWidth, Globals::dImHeight, 0);

    for (int i = 0; i < close_range_BBoxes.getSize(); i++)
    {
        Vector<Vector<double> > result;

        int cropped_height = (int)(close_range_BBoxes(i)(3)/2.0);
        cropped_height += (close_range_BBoxes(i)(3) * Globals::evaluation_inc_height_ratio)/2.0;
        close_range_BBoxes(i)(1) -= (close_range_BBoxes(i)(3) * Globals::evaluation_inc_height_ratio)/2.0;

        if( close_range_BBoxes(i)(1)+cropped_height >= Globals::dImHeight)
            cropped_height = Globals::dImHeight - (int)close_range_BBoxes(i)(1) - 1;

        ROS_DEBUG("(distances(i) %f radius %f", distances(i)(0), distances(i)(1)/2.0);
//        if(Globals::verbose)
//            cout << "(distances(i) " << distances(i)(0) << " radius " << distances(i)(1)/2.0 << endl;

        // Cropped and Filter depth_map with respect to distance from camera
        int start_column = (int)close_range_BBoxes(i)(0);
        int end_column = (int)(close_range_BBoxes(i)(0) + close_range_BBoxes(i)(2));
        int start_row = (int)max(0.0, close_range_BBoxes(i)(1));
        int end_row = (int)close_range_BBoxes(i)(1) + cropped_height;

        Matrix<double> cropped(end_column-start_column+1, end_row-start_row+1);

        double min_distance_threshold = distances(i)(0)- (distances(i)(1)+0.2)/2.0;
        double max_distance_threshold = distances(i)(0)+ (distances(i)(1)+0.2)/2.0;
        for(int ii = 0, ii_depth = start_column; ii < cropped.x_size(); ii++, ii_depth++)
        {
            for(int jj = 0, jj_depth = start_row; jj < cropped.y_size(); jj++, jj_depth++)
            {
                if(depth_map(ii_depth,jj_depth) <= min_distance_threshold || depth_map(ii_depth,jj_depth) >= max_distance_threshold)
                {
                    cropped(ii, jj) = 0;
                }
                else
                {
                    cropped(ii, jj) = depth_map(ii_depth, jj_depth);
                }
            }
        }

//        roi_img.insert(cropped,start_column,start_row);
        ////////////////
        if(visualize_roi)
        {
            for(int tmpx=start_column, tmpxx=0; tmpxx<cropped.x_size(); tmpx++,tmpxx++)
            {
                for(int tmpy=start_row, tmpyy=0; tmpyy<cropped.y_size(); tmpy++,tmpyy++)
                {
                    if(tmpyy==0 || tmpyy==cropped.y_size()-1 || tmpxx==0 || tmpxx==cropped.x_size()-1)
                        roi_image(tmpx,tmpy)=i+1;

                    if(cropped(tmpxx,tmpyy)!=0)
                        roi_image(tmpx,tmpy)=i+1;
                }
            }
        }
        /////////////////////////////////

        // Resize Cropped - with respect to template
        double ratio = close_range_BBoxes(i)(3) / (Globals::template_size * 3.0);
        int new_height = (int)(cropped.y_size() * all_scales(nr_scales-1) / ratio);
        int new_width = (int)(cropped.x_size() * all_scales(nr_scales-1) / ratio);
        if(new_height<=0 || new_width<=0)
            continue;
        if(cropped.y_size() > new_height)
        {
            cropped.DownSample(new_width, new_height);
        }
        else if(cropped.y_size() < new_height)
        {
            cropped.UpSample(new_width, new_height);
        }


        //*******************************************************************************************************
        Matrix<int> b_cropped(cropped.x_size(), cropped.y_size());
        for(int ic = 0; ic<cropped.x_size(); ++ic)
        {
            for(int j=0; j<cropped.y_size(); ++j)
            {
                if(cropped(ic,j)>0)
                    b_cropped(ic,j)=1;
                else
                    b_cropped(ic,j)=0;
            }
        }

        KConnectedComponentLabeler ccl(Globals::region_size_threshold, b_cropped.data(), b_cropped.x_size(), b_cropped.y_size());

        ccl.Process();

        Matrix<double> components(cropped.x_size(),cropped.y_size());
        //*******************************************************************************************************
        for(int cr_com = 0; cr_com < ccl.m_ObjectNumber; ++cr_com)
        {
            for(int x=0; x<cropped.x_size(); ++x)
            {
                for(int y=0; y<cropped.y_size(); ++y)
                {
                    if(b_cropped(x,y)==cr_com+1)
                        components(x,y) = cropped(x,y);
                    else
                        components(x,y) = 0;
                }
            }

            Matrix<double> copy_component = components;

            for(int scale_index = 0; scale_index < all_scales.getSize(); scale_index++)
            {
                copy_component = components;

                // Resize Cropped in loop with different scales
                int xSizeCropped = (int)(copy_component.x_size() / all_scales(scale_index));
                int ySizeCropped = (int)(copy_component.y_size() / all_scales(scale_index));

                if(all_scales(scale_index) != 1)
                    copy_component.DownSample(xSizeCropped , ySizeCropped);

                Matrix<double> extended_cropped(xSizeCropped + Globals::template_size, ySizeCropped+inc_cropped_height, 0.0);
                extended_cropped.insert(copy_component, (int)(double_half_template_size)-1, 0);

                //*Local Max *******************************
                Matrix<double> extended_cropped_open = extended_cropped;
                AncillaryMethods::MorphologyOpen(extended_cropped_open);
                Vector<double> ys ,slopes;
                AncillaryMethods::ExtractSlopsOnBorder(extended_cropped_open, ys, slopes);
                Vector<int> max_xs = AncillaryMethods::FindLocalMax(slopes);
                //******************************************

                int distances_matrix_x_size = max_xs.getSize();

                Vector<double> resulted_distances(distances_matrix_x_size);
                Vector<double> resulted_medians(distances_matrix_x_size);

                Vector<int> rxs(max_xs.getSize()),rys(max_xs.getSize());
                for(int ii = 0; ii<max_xs.getSize(); ++ii)
                {
                    int cx = max(max_xs(ii)-int_half_template_size,0);
                    int cy = max(extended_cropped.y_size()-(int)ys(max_xs(ii))-4, 0);
                    rxs(ii) = cx;
                    rys(ii) = cy;
                    double local_result, local_best=1000;

                    for(int y=cy; y<=cy+1*stride; y+=stride)
                    {
                        if(y>=extended_cropped.y_size() || y>=extended_cropped.y_size()) continue;
                        int y_size = min(extended_cropped.y_size()-1, y+Globals::template_size) - y;

                        int start_row = (int)max(0.0, y + y_size/2.0-5);
                        int end_row = (int)min((double)Globals::dImHeight-1, y + y_size/2.0+5);
                        if(end_row >=extended_cropped.y_size()) continue;

                        for(int x=max(0,cx-5*stride); x<=cx+5*stride; x+=stride)
                        {
                            if(x>=extended_cropped.x_size()) continue;
                            int x_size = min(extended_cropped.x_size()-1, x+Globals::template_size) - x;

                            int start_column = (int)max(0.0, x + x_size/2.0-5);
                            int end_column = (int)min((double)Globals::dImWidth-1, x + x_size/2.0+5);

                            // Normalize the cropped part of the image. regarding the current position of the template;
                            // Crop only some pixels in the middle
                            double median = AncillaryMethods::MedianOfMatrixRejectZero(extended_cropped, start_row, end_row, start_column, end_column);
                            if(median == 0)
                            {
                                resulted_distances(ii) = 1000;
                                continue;
                            }
//                            extended_cropped *= 1.0/median;

                            int x_start_of_temp = max(0, int_half_template_size - x);
                            double x_end_of_temp = Globals::template_size;
                            int evaluating_area = (x_end_of_temp - x_start_of_temp)*Globals::template_size+1;

                            double sum = 0;

                            if(evaluating_area > Globals::template_size * double_half_template_size)
                            {
                                for(int x_of_temp = 0; x_of_temp < x_end_of_temp; x_of_temp++)
                                {
                                    int x_of_extended_cropp = x + x_of_temp;

                                    for(int y_of_temp = 0; y_of_temp < Globals::template_size; y_of_temp++)
                                    {
                                        double difference = upper_body_template(x_of_temp, y_of_temp)-extended_cropped(x_of_extended_cropp, y_of_temp+y)/median;

                                        sum += difference*difference;
                                    }
                                }

                                local_result = sum/(double)evaluating_area;
                                if(local_best>local_result)
                                {
                                    local_best = local_result;
                                    resulted_medians(ii) = median;
                                    rxs(ii)=x;
                                    rys(ii)=y;
                                }
                            }
                        }
                    }
                    resulted_distances(ii) = local_best;
                }

                int n_xSizeTemp = (int)(Globals::template_size*ratio/all_scales(scale_index));

//                double n_threshold = 0.15;
                for(int ii =0; ii<resulted_distances.getSize(); ++ii)
                {
                    if(resulted_distances(ii)<Globals::evaluation_NMS_threshold_LM)
                    {
                        int x = rxs(ii);
                        int y = rys(ii);

                        Vector<double> bbox(6);
                        bbox(0) = (x-double_half_template_size)*ratio/all_scales(scale_index) + close_range_BBoxes(i)(0);
                        bbox(1) = y*ratio/all_scales(scale_index) +close_range_BBoxes(i)(1);
                        bbox(2) = n_xSizeTemp;
                        bbox(3) = n_xSizeTemp;
                        bbox(4) = resulted_distances(ii);
                        bbox(5) = resulted_medians(ii);

                        result.pushBack(bbox);
                    }
                }
            }
        }
        AncillaryMethods::GreedyNonMaxSuppression(result, Globals::evaluation_greedy_NMS_overlap_threshold, Globals::evaluation_greedy_NMS_threshold, upper_body_template, final_result);
    }
//    roi_img.WriteToTXT("roi_img.txt");
    return final_result;
}
コード例 #22
0
 inline
 UnitVector3d
 UnitVector2d::placedOnto(const Plane3d& plane) const {
     return UnitVector3d(plane.basisMatrix() * components());
 }
コード例 #23
0
ファイル: formats.cpp プロジェクト: Ojaswi/inviwo
DataFormatBase::DataFormatBase() : formatId_(id()), components_(components()), size_(size()), formatStr_("") {}
コード例 #24
0
ファイル: control.cpp プロジェクト: yongwangCPH/peat
void Control::do_script(vector<string> words)
{
  
  //check if scripting is initiated
  if (!script_initiated)
    initiate_scripting();
  
  printf("\n");
  printf("  Script mode - Note that absolute stability values do not make sense!\n");
 
  string method = "",sign="";
  Soup this_soup,this_soup2;
  float result = 0, this_result = 0;
  int no_soups = 1;
  bool name_is_set = 0;
  vector<double> components(Stability.get_no_components(),0); //this line could be problematic if binding is included in scripting


  for(unsigned int i=1; i<words.size();i++)
    {
      //cout<<">"<<words.at(i)<<endl;
      // find out what the sign of the term is
      if (words.at(i) =="+" or words.at(i) =="-")
	{
	  if (method == "") // if method is set it means that we are adding soups not energy terms
	    sign = words.at(i);
	}
      // check which method to use for this term
      else if (words.at(i) =="stability" or words.at(i) =="binding" or words.at(i) =="binding_just_PL")
	{
	  method = words.at(i);
	  //printf("Got method %s\n",method.c_str());
	}

      // calculate the term
      else if(words.at(i) =="}")
	{
	  vector<double> these_components(8,0);
	  if (method == "stability")
	    {
	      this_result = Stability.calculate_stability(&this_soup);
	      printf("  Stability: %-40s       %1s %8.2f kJ/mol\n",this_soup.name.c_str(),sign.c_str(), this_result);
	      these_components = Stability.get_components();
	    }
	  else if (method == "binding_just_PL")
	    {
	      if (no_soups == 1)
		{
		  no_soups = 2;
		  //cout<<"Starting second soup"<<endl;
		  continue;
		}
	      
	      this_result = Binding.calculate_binding(&this_soup, &this_soup2);
	      printf("  Binding:   %-20s and %-20s  %1s %8.2f kJ/mol\n",this_soup.name.c_str(),this_soup2.name.c_str(),sign.c_str(), this_result);
	      these_components = Binding.get_components();
	    }
	  else if (method == "binding")
	    {
	      if (no_soups == 1)
		{
		  no_soups = 2;
		  //cout<<"Starting second soup"<<endl;
		  continue;
		}
	      
	      Soup holo, apo;
	      apo = this_soup;
	      holo = this_soup + this_soup2;
	      
	      float stab_apo, stab_holo, ligand_entropy;
	      vector<double> components_apo, components_holo;
	      stab_apo = Stability.calculate_stability(&apo);
	      components_apo  = Stability.get_components();
	      stab_holo = Stability.calculate_stability(&holo);
	      components_holo = Stability.get_components();

	      ligand_entropy = Ligand_entropy.calculate_using_desolvation(&apo, &this_soup2);

	      this_result = stab_holo - stab_apo + ligand_entropy;

	      printf("  Binding_ds:%-20s and %-20s  %1s %8.2f kJ/mol\n",this_soup.name.c_str(),this_soup2.name.c_str(),sign.c_str(), this_result);
	      

	      for (int k =0; k<components_holo.size(); k++)
		these_components[k] = components_holo[k] - components_apo[k];
	      these_components[6] = ligand_entropy; //include ligand entropy
	    }

	  
	  

	  

	  if (sign=="+" or sign =="")
	    {
	      result += this_result;
	      for(unsigned int c=0;c<components.size();c++)
		components[c] += these_components[c];
	    }
	  else if (sign=="-")
	    {
	      result -= this_result;
	      for(unsigned int c=0;c<components.size();c++)
		components[c] -= these_components[c];

	    }

	  this_soup.clearSoup();
	  this_soup.name = "";
	  this_soup2.clearSoup();
	  this_soup2.name = "";
	  method = "";
	  no_soups = 1;

	}
      // set target value
      else if(words.at(i) =="target")
	{
	  // printf("got target: %s\n",words.at(i+1).c_str());
	  b.push_back(atof(words.at(i+1).c_str()));
	  i++;//jump
	}
      // set calculation name
      else if(words.at(i) =="name")
	{
	  // printf("got name: %s\n",words.at(i+1).c_str());
	  names.push_back(words.at(i+1));
	  i++;//jump
	  name_is_set = 1;
	}

      // find soups to use for this term
      else if(words.at(i) !="{" and words.at(i) !="}")
	{
	  //      	  cout<<"Looking for "<<words.at(i)<<endl;
	  bool found = false;
	  for(unsigned int s=0; s<soups.size(); s++)
	    if(soups[s].name == words.at(i))
	      {
		//cout<<"adding to soup "<<no_soups<<endl;
		if (no_soups == 1)
		  this_soup = this_soup + soups[s];
		else if(no_soups == 2)
		  this_soup2 = this_soup2 + soups[s];
		found = true;
	      }
	  if (!found)
	    {
	      printf("Script error: invalid soup name: %s\n",words.at(i).c_str());
	      exit(0);
	    }
	}



    }

  if (name_is_set != 1)
    names.push_back("");

  printf("  ---------------------------------------------------------------------------\n");
  printf("  Result for %-30s                   %8.2f kJ/mol\n",names.at(names.size()-1).c_str(),result);
  printf("  ===========================================================================\n");
  A.push_back(components);

  
}
コード例 #25
0
 inline
 double
 Quaternion2d::cosAngle() const {
     return components()(0);
 }
コード例 #26
0
void MSC::test()
{

  vector<Soup*>::iterator 
    wt = wts.begin(), 
    mt = mts.begin();
  
  vector<vector<float> > wt_distances, mut_distances;
  cout<<setprecision(2)<<setw(8)<<fixed;
  while(wt != wts.end())
    {
      cout<<"******* Now doing no "<<count+1<<" of "<<wts.size()<<": "<<(*mt)->name<<endl;

      if(include_ff_components)
	{

	  A.resize(A.size1()+1,A.size2(),true);
	  /*** Insert mutant values in matrices ***/
	  calculate_stability(*mt);
	  for(int i=0; i<components.size();i++)
	    A(count,i) = components(i);

	  /*** Insert wild type values in matrices ***/
	  calculate_stability(*wt);
	  for(int i=0; i<components.size();i++)
	      A(count,i) = A(count,i) - components(i);


	  wt_comps.resize(wt_comps.size1()+1,wt_comps.size2(),true);
	  mut_comps.resize(mut_comps.size1()+1,mut_comps.size2(),true);
	  
	  wt_comps(count, 0) = 0.0;
	  wt_comps(count, 1) = 0.0;
	  wt_comps(count, 2) = 0.0;
	  wt_comps(count, 3) = 0.0;
	  wt_comps(count, 4) = 0.0;
	  
	  mut_comps(count, 0) = 0.0;
	  mut_comps(count, 1) = 0.0;
	  mut_comps(count, 2) = 0.0;
	  mut_comps(count, 3) = 0.0;
	  mut_comps(count, 4) = 0.0;
	  
	}
      if(include_aa_components)
	{
	  /*** insert unfolded terms ***/
	  for(int i=0;i<20;i++)
	    A(count,no_components-20+i) = 0.0;

	  A(count,no_components-21+aa_map[(*mt)->name[5]]) = -1.0;
	  A(count,no_components-21+aa_map[(*mt)->name[(*mt)->name.size()-1]]) =  1.0;
	}

      names.push_back((*mt)->name);
      
      count++;
      
      /*** iterate iterators ***/
      wt++;
      mt++;
    }
}
コード例 #27
0
	inline typename genType::value_type * end(genType& v)
	{
		return begin(v) + components(v);
	}
コード例 #28
0
double MSC::calculate_stability(Soup * soup)
{
  if(include_ff_components)
    simple_parameters.prepare(soup);
  
  cout<<soup->name<<flush;
  
  de_component  = de.calculate(soup);//Desolvation_Factor must be calculated first, as desolvation_factor is needed in hb, vdw, es, wb
    cout<<" de:"<<de_component <<flush;

  hb_component  = hb.calculate(soup); //Hydrogen bonds must be calculated before es and vdw, as info on hydrogen bonds is needed in es and vdw 
    cout<<" hb:"<<hb_component <<flush;

  vdw_component = vdw_line.calculate(soup, 10);
    cout<<" vdw:"<<vdw_component<<flush;

  es_component  = es.calculate(soup, 0);
    cout<<" es:"<<es_component <<flush;

  bb_component = bb.calculate(soup);
    cout<<" bb:"<<bb_component <<flush;

  pe_component  = 0.0;//pe.calculate(soup);
    cout<<" pe:"<<pe_component <<flush;	  

  le_component  = 0.0;//le.calculate(soup);
    cout<<" le:"<<le_component <<flush;
  
  wb_component = wb.calculate(soup);
    cout<<endl;
  
  cout << "calc is done" <<flush;
  // Insert in matrices 
  components(0) = vdw_component;
  components(1) = es_component;
  components(2) = hb_component;
  components(3) = de_component;
  components(4) = bb_component;
  components(5) = pe_component;
  components(6) = le_component;
  components(7) = wb_component;

  /*
  A.resize(A.size1()+1,A.size2(),true);
  for(int i=0; i<components.size();i++)
    A(A.size1()-1,i) = components(i);

  names.push_back(soup->name);
      
 
  count++;
  */

  if(coefficients_are_set)
    {
      calculate_result();
      return total_stability;
    }

  return 0.0;
}
コード例 #29
0
ファイル: logger.c プロジェクト: Allen-smith/ctf-tools
void log_guess(char *login, char *uid, char *ciphertext, char *rep_plain,
               char *store_plain, char field_sep, int index)
{
	int count1, count2;
	int len;
	char spacer[] = "                ";
	char *secret = "";
	char uid_sep[2] = { 0 };
	char *uid_out = "";

/* This is because printf("%-16s") does not line up multibyte UTF-8.
   We need to count characters, not octets. */
	if (pers_opts.target_enc == UTF_8 || pers_opts.report_utf8)
		len = strlen8((UTF8*)rep_plain);
	else
		len = strlen(rep_plain);

	if (options.show_uid_on_crack && uid && *uid) {
		uid_sep[0] = field_sep;
		uid_out = uid;
	}

	if (options.verbosity > 1) {
		if (options.secure) {
			secret = components(rep_plain, len);
			printf("%-16s (%s%s%s)\n",
			       secret, login, uid_sep, uid_out);
		} else {
			spacer[len > 16 ? 0 : 16 - len] = 0;

			printf("%s%s (%s%s%s)\n",
			       rep_plain, spacer, login, uid_sep, uid_out);

			if (options.fork)
				fflush(stdout);
		}
	}

	in_logger = 1;

	if (pot.fd >= 0 && ciphertext ) {
#ifndef DYNAMIC_DISABLED
		if (!strncmp(ciphertext, "$dynamic_", 9))
			ciphertext = dynamic_FIX_SALT_TO_HEX(ciphertext);
#endif
		if (strlen(ciphertext) + strlen(store_plain) <= LINE_BUFFER_SIZE - 3) {
			if (options.secure) {
				secret = components(store_plain, len);
				count1 = (int)sprintf(pot.ptr,
				                      "%s%c%s\n",
				                      ciphertext,
				                      field_sep,
				                      secret);
			} else
				count1 = (int)sprintf(pot.ptr,
				                      "%s%c%s\n", ciphertext,
				                      field_sep, store_plain);
			if (count1 > 0) pot.ptr += count1;
		}
	}

	if (log.fd >= 0 &&
	    strlen(login) < LINE_BUFFER_SIZE - 64) {
		count1 = log_time();
		if (count1 > 0) {
			log.ptr += count1;
			count2 = (int)sprintf(log.ptr, "+ Cracked %s%s%s", login, uid_sep, uid_out);

			if (options.secure) {
				secret = components(rep_plain, len);
				count2 += (int)sprintf(log.ptr + count2,
				                       ": %s", secret);
			} else
			if (cfg_log_passwords)
				count2 += (int)sprintf(log.ptr + count2,
				                       ": %s", rep_plain);
			if (cfg_showcand)
				count2 += (int)sprintf(log.ptr + count2,
				                       " as candidate #"LLu"",
				                       ((unsigned long long)
				                       status.cands.hi << 32) +
				                       status.cands.lo + index + 1);
			count2 += (int)sprintf(log.ptr + count2, "\n");

			if (count2 > 0)
				log.ptr += count2;
			else
				log.ptr -= count1;
		}
	}

/* Try to keep the two files in sync */
	if (log_file_write(&pot))
		log_file_flush(&log);
	else
	if (log_file_write(&log))
		log_file_flush(&pot);

	in_logger = 0;

	if (cfg_beep)
		write_loop(fileno(stderr), "\007", 1);
}
コード例 #30
0
bool    _HYObjectInspector::ProcessEvent (_HYEvent* e)
{
    _String firstArg;
    long    k,i,f;
    bool    done = false;
    if (e->EventClass()==_hyMenuSelChangeEvent) {
        firstArg = e->EventCode().Cut (0,(f=e->EventCode().Find(','))-1);
        k = firstArg.toNum();
        for (i=0; i<components.lLength; i++) {
            if (((_HYGuiObject*)components(i))->MatchID(k)) {
                break;
            }
        }
        firstArg = e->EventCode().Cut (f+1,-1);
        k = firstArg.toNum();
        BuildListOfObjects (k);
        done = true;

    } else {
        if (e->EventClass()==_hyTableChangeSelEvent) {
            k = e->EventCode().toNum();
            for (i=0; i<components.lLength; i++)
                if (((_HYGuiObject*)components(i))->MatchID(k)) {
                    break;
                }
            if (i==1) {
                UpdateButtonsAndInfo ();
            }
            done = true;
        } else {
            if (e->EventClass()==_hyButtonPushEvent) {
                firstArg = e->EventCode().Cut (0,(f=e->EventCode().Find(','))-1);
                k = firstArg.toNum();
                for (i=0; i<components.lLength; i++)
                    if (((_HYGuiObject*)components(i))->MatchID(k)) {
                        break;
                    }

                firstArg = e->EventCode().Cut (f+1,-1);
                k = firstArg.toNum();
                if (i==4) { // button bar
                    _HYButtonBar* bb = (_HYButtonBar*)GetCellObject (0,0);
                    switch (k) {
                    case 0:
                        OpenObjectWindow();
                        break;
                    case 1:
                        KillObject ();
                        break;
                    case 2:
                        OpenObject ();
                        break;
                    case 3:
                        NewObject ();
                        break;
                    }
                    bb->_UnpushButton();
                    UpdateButtonsAndInfo();
                }

                done = true;
            } else {
                if (e->EventClass()==_hyTableDblClickEvent) {
                    k = e->EventCode().toNum();
                    for (i=0; i<components.lLength; i++)
                        if (((_HYGuiObject*)components(i))->MatchID(k)) {
                            break;
                        }
                    if (i==1) {
                        OpenObjectWindow();
                    }
                    done = true;
                } else if (e->EventClass()==_hyTablePullDownEvent) {
                    firstArg = e->EventCode().Cut (0,(f=e->EventCode().Find(','))-1);
                    k = firstArg.toNum();
                    for (i=0; i<components.lLength; i++) {
                        if (((_HYGuiObject*)components(i))->MatchID(k)) {
                            break;
                        }
                    }
                    k               = e->EventCode().Find(',',f+1,-1);
                    firstArg        = e->EventCode().Cut (k+1,-1);
                    if (i==2) {
                        SortObjectsByName (firstArg.toNum());
                    }

                    done = true;
                }

            }
        }
    }
    if (done) {
        DeleteObject (e);
        return true;
    }
    return _HYTWindow::ProcessEvent(e);
}