示例#1
0
/*
 * Main program.
 */
int main() {
    if (RANDOM_USE_SEED) {
        setRandomSeed(106);
    }
    
    intro();

    // create GUI window and position the console to its right
    setConsoleLocation(WorldGrid::WINDOW_WIDTH + 6 * WorldAbstract::WINDOW_MARGIN, 20);   // temporary
    // setConsoleSize(CONSOLE_WIDTH, CONSOLE_HEIGHT);
    setConsoleEventOnClose(true);
    
    TrailblazerGUI gui(WINDOW_TITLE);
    gui.snapConsoleLocation();

    // main event loop to process events as they happen
    while (true) {
        GEvent e = waitForEvent(ACTION_EVENT | MOUSE_EVENT | WINDOW_EVENT);
        if (e.getEventType() == MOUSE_CLICKED || e.getEventType() == MOUSE_MOVED) {
            gui.processMouseEvent(GMouseEvent(e));
        } else if (e.getEventClass() == ACTION_EVENT) {
            gui.processActionEvent(GActionEvent(e));
        } else if (e.getEventClass() == WINDOW_EVENT) {
            gui.processWindowEvent(GWindowEvent(e));
        }
    }
    return 0;
}
示例#2
0
文件: main.cpp 项目: Ole-x/musicbox
	void process() {
		activateSound();

		currentSel = 0;

		play();
		while (!terminate) {
			if (isPlaying) {
				midiWriter.setStop(false);

				SongCreator *songCreator = new SongCreator();
				songCreator->createSong(seed, tempo, structureScript, arrangementScript, &midiWriter);
//				osSignalWait(0x1, osWaitForever);
				while (midiWriter.getQueueSize() > 0) {
					wait_ms(100);
				}
				delete songCreator;

				setRandomSeed();

			} else {
				wait_ms(100);
			}
		}
	}
示例#3
0
文件: main.cpp 项目: Ole-x/musicbox
	CcgProgram() : Program() {
		structureScript = "Classical Structure Big";
		arrangementScript = "Piano Advanced Classical";
		tempo = 120;

		setRandomSeed();
		isPlaying = true;

		currentSel = 0;

	}
void ClusteringLayouterNode::processParameters()
{
	if (!updateInputGraph())
		return;
	
	setRandomSeed();
	setMaxNumberOfIterations();
	setIterationsPerLayout();
	setInitialTemperature();
	setCoolDownRate();
	setRestDistance();

	refreshOutput();
}
示例#5
0
/**
 * @internal
 * @brief Initializes the class so it becomes valid.
 *
 * @param userApp if received, this is the pointer to the user application. If not recive, the user is using global functions (processing style)
 * for the application flow
 * @return true if the initialization was ok | false otherwise
 */
bool Application::initApp( UserApplicationBase* userApp /*= NULL*/ )
{
	// Check if the class is already initialized
	if ( isValid() )
		return true;

    // Store pointer to the user app
    m_userApp = userApp;
    
	// Init random number generator seed
	setRandomSeed( time(NULL) );

	// First, init the subsystems needed by any user call (the rest will be init in the initSubSystems method
	// called when the user calls the size function

	// Init the resource manager
	ResourceManager::getSingleton().init();

	// Init the log manager
	// Note: If the log manager is initalized before the Resource Manager, Ogre.log file won't be created
	LogManager::getSingleton().init();
	
    // TODO: this is a temporary 2d renderer (opencv) until Cing's core has the necessary features to not need it
    enableOpenCVRenderer2D();
    
	// Init user application
    if ( m_userApp )
        m_userApp->setup();
    else
        setup();

	// Check subsystems init ok
	checkSubsystemsInit();

	// Reset timer
	m_timer.reset();
	m_absTimer.reset();

	// Set frameCount to zero
	m_frameCount = 0;

	return true;

}
示例#6
0
void HWMapContainer::setRandomMap()
{
    if (!m_master) return;

    setRandomSeed();
    switch(m_mapInfo.type)
    {
        case MapModel::GeneratedMap:
        case MapModel::GeneratedMaze:
        case MapModel::GeneratedPerlin:
            setRandomTheme();
            break;
        case MapModel::MissionMap:
            missionMapChanged(m_missionMapModel->index(rand() % m_missionMapModel->rowCount(), 0));
            break;
        case MapModel::StaticMap:
            staticMapChanged(m_staticMapModel->index(rand() % m_staticMapModel->rowCount(), 0));
            break;
        default:
            break;
    }
}
示例#7
0
   void MultiPeak::setProjectBField(
      FsGrid< std::array<Real, fsgrids::bfield::N_BFIELD>, 2> & perBGrid,
      FsGrid< std::array<Real, fsgrids::bgbfield::N_BGB>, 2>& BgBGrid,
      FsGrid< fsgrids::technical, 2>& technicalGrid
   ) {
      ConstantField bgField;
      bgField.initialize(this->Bx,
                         this->By,
                         this->Bz);
      
      setBackgroundField(bgField, BgBGrid);
      
      if(!P::isRestart) {
         auto localSize = perBGrid.getLocalSize();
         
#pragma omp parallel for collapse(3)
         for (int x = 0; x < localSize[0]; ++x) {
            for (int y = 0; y < localSize[1]; ++y) {
               for (int z = 0; z < localSize[2]; ++z) {
                  const std::array<Real, 3> xyz = perBGrid.getPhysicalCoords(x, y, z);
                  std::array<Real, fsgrids::bfield::N_BFIELD>* cell = perBGrid.get(x, y, z);
                  const int64_t cellid = perBGrid.GlobalIDForCoords(x, y, z);
                  setRandomSeed(cellid);
                  
                  if (this->lambda != 0.0) {
                     cell->at(fsgrids::bfield::PERBX) = this->dBx*cos(2.0 * M_PI * xyz[0] / this->lambda);
                     cell->at(fsgrids::bfield::PERBY) = this->dBy*sin(2.0 * M_PI * xyz[0] / this->lambda);
                     cell->at(fsgrids::bfield::PERBZ) = this->dBz*cos(2.0 * M_PI * xyz[0] / this->lambda);
                  }
                  
                  cell->at(fsgrids::bfield::PERBX) += this->magXPertAbsAmp * (0.5 - getRandomNumber());
                  cell->at(fsgrids::bfield::PERBY) += this->magYPertAbsAmp * (0.5 - getRandomNumber());
                  cell->at(fsgrids::bfield::PERBZ) += this->magZPertAbsAmp * (0.5 - getRandomNumber());
               }
            }
         }
      }
   }
示例#8
0
PsoSolver::PsoSolver(const int dim, 
			      const double *rangeL, const double *rangeU, 
				  double (*getFitness)(const Particle &p, void *obj), 
				  void *obj,
				  int maxIteration, int particleNum,
				  double convergenceThreshold, 
				  double iw, double pw, double gw, double lw, double nw,
				  int localK) {
	this->dim            = dim;
	this->maxIteration   = maxIteration;
	this->getFitness     = getFitness;
	this->obj            = obj;
	this->particleNum    = particleNum;
	this->convergenceThreshold = convergenceThreshold;
	this->iw = iw;
	this->pw = pw;
	this->gw = gw;
	this->lw = lw;
	this->nw = nw;
	this->localK = min(particleNum, localK);

	this->rangeL         = new double[dim];
	this->rangeU         = new double[dim];
	this->rangeInter     = new double[dim];
	this->gBest          = NULL;
	this->gBestFitness   = DBL_MAX;
	this->gBestIteration = -1;

	for (int i = 0; i < dim; i++) {
		this->rangeL[i]     = rangeL[i];
		this->rangeU[i]     = rangeU[i];
		this->rangeInter[i] = rangeU[i] - rangeL[i];
	}

	setRandomSeed();
	initParticles();
}
示例#9
0
/*----------------------------------------------------------------------
  Parameters:

  Description:
  ----------------------------------------------------------------------*/
static int
get_option(int argc, char *argv[])
{
  int  nargs = 0 ;
  char *option ;

  option = argv[1] + 1 ;            /* past '-' */
  if (!stricmp(option, "-help")||!stricmp(option, "-usage"))
  {
    print_help() ;
  }
  else if (!stricmp(option, "-version"))
  {
    print_version() ;
  }
  else if (!stricmp(option, "nbrs"))
  {
    nbrs = atoi(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "using neighborhood size = %d\n", nbrs) ;
  }
  else if (!stricmp(option, "normalize"))
  {
    normalize_flag = 1 ;
  }
  else if (!stricmp(option, "nw"))
  {
    no_write = 1 ;
  }
  else if (!stricmp(option, "seed"))
  {
    setRandomSeed(atol(argv[2])) ;
    fprintf(stderr,"setting seed for random number generator to %d\n",
            atoi(argv[2])) ;
    nargs = 1 ;
  }
  else if (!stricmp(option, "area"))
  {
    normalize_area = 1 ;
    printf("normalizing area after smoothing\n") ;
  }
  else switch (toupper(*option))
    {
    case 'M':
      momentum = atof(argv[2]) ;
      printf("using momentum = %2.2f\n", momentum) ;
      nargs = 1 ;
      break ;
    case 'G':
      gaussian_norm = atof(argv[2]) ;
      gaussian_avgs = atoi(argv[3]) ;
      printf("using Gaussian curvature smoothing with norm %2.2f with %d smooth steps\n",
             gaussian_norm, gaussian_avgs) ;
      nargs = 2 ;
      break ;
    case 'V':
      Gdiag_no = atoi(argv[2]) ;
      printf("debugging vertex %d\n", Gdiag_no) ;
      nargs = 1 ;
      break ;
    case 'W':
      Gdiag |= DIAG_WRITE ;
      write_iterations = atoi(argv[2]) ;
      printf("writing out snapshots every %d iterations\n", write_iterations) ;
      nargs = 1 ;
      break ;
    case '?':
    case 'H':
    case 'U':
      print_usage() ;
      exit(1) ;
      break ;
    case 'R':
      rescale = 1 ;
      fprintf(stderr, "rescaling brain area after smoothing...\n") ;
      break ;
    case 'B':
      strcpy(area_fname, argv[2]) ;
      nargs = 1 ;
      break ;
    case 'C':
      strcpy(curvature_fname, argv[2]) ;
      nargs = 1 ;
      break ;
    case 'N':
      niterations = atoi(argv[2]) ;
      fprintf(stderr, "smoothing for %d iterations\n", niterations) ;
      nargs = 1 ;
      break ;
    case 'A':
      navgs = atoi(argv[2]) ;
      nargs = 1 ;
      fprintf(stderr, "averaging curvature for %d iterations\n", navgs) ;
      break ;
    default:
      fprintf(stderr, "unknown option %s\n", argv[1]) ;
      exit(1) ;
      break ;
    }

  return(nargs) ;
}
示例#10
0
InputDeviceAdapterPlayback::InputDeviceAdapterPlayback(InputDeviceManager* sInputDeviceManager,const Misc::ConfigurationFileSection& configFileSection)
	:InputDeviceAdapter(sInputDeviceManager),
	 inputDeviceDataFile(configFileSection.retrieveString("./inputDeviceDataFileName").c_str(),"rb",Misc::File::LittleEndian),
	 mouseCursorFaker(0),
	 synchronizePlayback(configFileSection.retrieveValue<bool>("./synchronizePlayback",false)),
	 quitWhenDone(configFileSection.retrieveValue<bool>("./quitWhenDone",false)),
	 soundPlayer(0),
	 saveMovie(configFileSection.retrieveValue<bool>("./saveMovie",false)),
	 movieWindowIndex(0),movieWindow(0),
	 firstFrame(true),timeStamp(0.0),
	 done(false)
	{
	/* Read file header: */
	static const char* fileHeader="Vrui Input Device Data File v2.0\n";
	char header[34];
	inputDeviceDataFile.read<char>(header,34);
	bool haveFeatureNames=strncmp(header,fileHeader,34)==0;
	if(!haveFeatureNames)
		{
		/* Old file format doesn't have the header text: */
		inputDeviceDataFile.rewind();
		}
	
	/* Read random seed value: */
	unsigned int randomSeed=inputDeviceDataFile.read<unsigned int>();
	setRandomSeed(randomSeed);
	
	/* Read number of saved input devices: */
	numInputDevices=inputDeviceDataFile.read<int>();
	inputDevices=new InputDevice*[numInputDevices];
	deviceFeatureBaseIndices=new int[numInputDevices];
	
	/* Initialize devices: */
	for(int i=0;i<numInputDevices;++i)
		{
		/* Read device's name and layout from file: */
		std::string name=Misc::readCppString(inputDeviceDataFile);
		int trackType=inputDeviceDataFile.read<int>();
		int numButtons=inputDeviceDataFile.read<int>();
		int numValuators=inputDeviceDataFile.read<int>();
		Vector deviceRayDirection;
		inputDeviceDataFile.read<Scalar>(deviceRayDirection.getComponents(),3);
		
		/* Create new input device: */
		InputDevice* newDevice=inputDeviceManager->createInputDevice(name.c_str(),trackType,numButtons,numValuators,true);
		newDevice->setDeviceRayDirection(deviceRayDirection);
		
		/* Initialize the new device's glyph from the current configuration file section: */
		Glyph& deviceGlyph=inputDeviceManager->getInputGraphManager()->getInputDeviceGlyph(newDevice);
		char deviceGlyphTypeTag[20];
		snprintf(deviceGlyphTypeTag,sizeof(deviceGlyphTypeTag),"./device%dGlyphType",i);
		char deviceGlyphMaterialTag[20];
		snprintf(deviceGlyphMaterialTag,sizeof(deviceGlyphMaterialTag),"./device%dGlyphMaterial",i);
		deviceGlyph.configure(configFileSection,deviceGlyphTypeTag,deviceGlyphMaterialTag);
		
		/* Store the input device: */
		inputDevices[i]=newDevice;
		
		/* Read or create the device's feature names: */
		deviceFeatureBaseIndices[i]=int(deviceFeatureNames.size());
		if(haveFeatureNames)
			{
			/* Read feature names from file: */
			for(int j=0;j<newDevice->getNumFeatures();++j)
				deviceFeatureNames.push_back(Misc::readCppString(inputDeviceDataFile));
			}
		else
			{
			/* Create default feature names: */
			for(int j=0;j<newDevice->getNumFeatures();++j)
				deviceFeatureNames.push_back(getDefaultFeatureName(InputDeviceFeature(newDevice,j)));
			}
		}
	
	/* Check if the user wants to use a fake mouse cursor: */
	int fakeMouseCursorDevice=configFileSection.retrieveValue<int>("./fakeMouseCursorDevice",-1);
	if(fakeMouseCursorDevice>=0)
		{
		/* Read the cursor file name and nominal size: */
		std::string mouseCursorImageFileName=configFileSection.retrieveString("./mouseCursorImageFileName",DEFAULTMOUSECURSORIMAGEFILENAME);
		unsigned int mouseCursorNominalSize=configFileSection.retrieveValue<unsigned int>("./mouseCursorNominalSize",24);
		
		/* Create the mouse cursor faker: */
		mouseCursorFaker=new MouseCursorFaker(inputDevices[fakeMouseCursorDevice],mouseCursorImageFileName.c_str(),mouseCursorNominalSize);
		mouseCursorFaker->setCursorSize(configFileSection.retrieveValue<Size>("./mouseCursorSize",mouseCursorFaker->getCursorSize()));
		mouseCursorFaker->setCursorHotspot(configFileSection.retrieveValue<Vector>("./mouseCursorHotspot",mouseCursorFaker->getCursorHotspot()));
		}
	
	/* Read time stamp of first data frame: */
	try
		{
		nextTimeStamp=inputDeviceDataFile.read<double>();
		
		/* Request an update for the next frame: */
		requestUpdate();
		}
	catch(Misc::File::ReadError)
		{
		done=true;
		nextTimeStamp=Math::Constants<double>::max;
		
		if(quitWhenDone)
			{
			/* Request exiting the program: */
			shutdown();
			}
		}
	
	/* Check if the user wants to play back a commentary sound track: */
	std::string soundFileName=configFileSection.retrieveString("./soundFileName","");
	if(soundFileName!="")
		{
		try
			{
			/* Create a sound player for the given sound file name: */
			soundPlayer=new Sound::SoundPlayer(soundFileName.c_str());
			}
		catch(std::runtime_error error)
			{
			/* Print a message, but carry on: */
			std::cerr<<"InputDeviceAdapterPlayback: Disabling sound playback due to exception "<<error.what()<<std::endl;
			}
		}
	
	/* Check if the user wants to save a movie: */
	if(saveMovie)
		{
		/* Read the movie image file name template: */
		movieFileNameTemplate=configFileSection.retrieveString("./movieFileNameTemplate");
		
		/* Check if the name template has the correct format: */
		int numConversions=0;
		bool hasIntConversion=false;
		for(std::string::const_iterator mfntIt=movieFileNameTemplate.begin();mfntIt!=movieFileNameTemplate.end();++mfntIt)
			{
			if(*mfntIt=='%')
				{
				++mfntIt;
				if(*mfntIt!='%')
					{
					++numConversions;
					
					/* Skip width modifiers: */
					while(isdigit(*mfntIt))
						++mfntIt;
					
					/* Check for integer conversion: */
					if(*mfntIt=='d')
						hasIntConversion=true;
					}
				}
			else if(*mfntIt=='/') // Only accept conversions in the file name part
				hasIntConversion=false;
			}
		if(numConversions!=1||!hasIntConversion)
			Misc::throwStdErr("InputDeviceAdapterPlayback::InputDeviceAdapterPlayback: movie file name template \"%s\" does not have exactly one %%d conversion",movieFileNameTemplate.c_str());
		
		/* Get the index of the window from which to save the frames: */
		movieWindowIndex=configFileSection.retrieveValue<int>("./movieWindowIndex",movieWindowIndex);
		
		/* Get the intended frame rate for the movie: */
		double frameRate=configFileSection.retrieveValue<double>("./movieFrameRate",30.0);
		movieFrameTimeInterval=1.0/frameRate;
		
		/* Calculate the first time at which to save a frame: */
		nextMovieFrameTime=nextTimeStamp+movieFrameTimeInterval*0.5;
		nextMovieFrameCounter=0;
		}
	}
示例#11
0
int
main(int argc, char *argv[])
{
  char         **av, *source_fname, *target_fname, *out_fname, fname[STRLEN] ;
  int          ac, nargs, new_transform = 0, pad ;
  MRI          *mri_target, *mri_source, *mri_orig_source ;
  MRI_REGION   box ;
  struct timeb start ;
  int          msec, minutes, seconds ;
  GCA_MORPH    *gcam ;
  MATRIX       *m_L/*, *m_I*/ ;
  LTA          *lta ;


  /* initialize the morph params */
  memset(&mp, 0, sizeof(GCA_MORPH_PARMS));
  /* for nonlinear morph */
  mp.l_jacobian = 1 ;
  mp.min_sigma = 0.4 ;
  mp.l_distance = 0 ;
  mp.l_log_likelihood = .025 ;
  mp.dt = 0.005 ;
  mp.noneg = True ;
  mp.exp_k = 20 ;
  mp.diag_write_snapshots = 1 ;
  mp.momentum = 0.9 ;
  if (FZERO(mp.l_smoothness))
    mp.l_smoothness = 2 ;
  mp.sigma = 8 ;
  mp.relabel_avgs = -1 ;
  mp.navgs = 256 ;
  mp.levels = 6 ;
  mp.integration_type = GCAM_INTEGRATE_BOTH ;
  mp.nsmall = 1 ;
  mp.reset_avgs = -1 ;
  mp.npasses = 3 ;
  mp.regrid = regrid? True : False ;
  mp.tol = 0.1 ;
  mp.niterations = 1000 ;
	
  TimerStart(&start) ;
  setRandomSeed(-1L) ;
  DiagInit(NULL, NULL, NULL) ;
  ErrorInit(NULL, NULL, NULL) ;

  Progname = argv[0] ;
  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++)
    {
      nargs = get_option(argc, argv) ;
      argc -= nargs ;
      argv += nargs ;
    }

  if (argc < 4)
    usage_exit(1) ;

  source_fname = argv[1] ;
  target_fname = argv[2] ;
  out_fname = argv[3] ;
  FileNameOnly(out_fname, fname) ;
  FileNameRemoveExtension(fname, fname) ;
  strcpy(mp.base_name, fname) ;
  mri_source = MRIread(source_fname) ;
  if (!mri_source)
    ErrorExit(ERROR_NOFILE, "%s: could not read source label volume %s",
	      Progname, source_fname) ;

  if (mri_source->type == MRI_INT)
    {
      MRI *mri_tmp = MRIchangeType(mri_source, MRI_FLOAT, 0, 1, 1) ;
      MRIfree(&mri_source); mri_source = mri_tmp ;
    }
  mri_target = MRIread(target_fname) ;
  if (!mri_target)
    ErrorExit(ERROR_NOFILE, "%s: could not read target label volume %s",
	      Progname, target_fname) ;
  if (mri_target->type == MRI_INT)
    {
      MRI *mri_tmp = MRIchangeType(mri_target, MRI_FLOAT, 0, 1, 1) ;
      MRIfree(&mri_target); mri_target = mri_tmp ;
    }
  if (erosions > 0)
    {
      int n ;
      for (n = 0 ; n < erosions ; n++)
	{
	  MRIerodeZero(mri_target, mri_target) ;
	  MRIerodeZero(mri_source, mri_source) ;
	}
    }
  if (scale_values > 0)
    {
      MRIscalarMul(mri_source, mri_source, scale_values) ;
      MRIscalarMul(mri_target, mri_target, scale_values) ;
    }
  if (transform && transform->type == MORPH_3D_TYPE)
    TransformRas2Vox(transform, mri_source,NULL) ;
  if (use_aseg == 0)
    {
      if (match_peak_intensity_ratio)
	MRImatchIntensityRatio(mri_source, mri_target, mri_source, .8, 1.2, 
			       100, 125) ;
      else if (match_mean_intensity)
	MRImatchMeanIntensity(mri_source, mri_target, mri_source) ;
      MRIboundingBox(mri_source, 0, &box) ;
      pad = (int)ceil(PADVOX * 
		      MAX(mri_target->xsize,MAX(mri_target->ysize,mri_target->zsize)) / 
		      MIN(mri_source->xsize,MIN(mri_source->ysize,mri_source->zsize))); 
#if 0
      { MRI *mri_tmp ;
	if (pad < 1)
	  pad = 1 ;
	printf("padding source with %d voxels...\n", pad) ;
	mri_tmp = MRIextractRegionAndPad(mri_source, NULL, &box, pad) ;
	if ((Gdiag & DIAG_WRITE) && DIAG_VERBOSE_ON)
	  MRIwrite(mri_tmp, "t.mgz") ;
	MRIfree(&mri_source) ;
	mri_source = mri_tmp ;
      }
#endif
    }
  mri_orig_source = MRIcopy(mri_source, NULL) ;

  mp.max_grad = 0.3*mri_source->xsize ;

  if (transform == NULL)
    transform = TransformAlloc(LINEAR_VOXEL_TO_VOXEL, NULL) ;

  if (transform->type != MORPH_3D_TYPE)  // initializing m3d from a linear transform
    {
      new_transform = 1 ;
      lta = ((LTA *)(transform->xform)) ;
      if (lta->type != LINEAR_VOX_TO_VOX)
	{
	  printf("converting ras xform to voxel xform\n") ;
	  m_L = MRIrasXformToVoxelXform(mri_source, mri_target, lta->xforms[0].m_L, NULL) ;
	  MatrixFree(&lta->xforms[0].m_L) ;
	  lta->type = LINEAR_VOX_TO_VOX ;
	}
      else
	{
	  printf("using voxel xform\n") ;
	  m_L = lta->xforms[0].m_L ;
	}
#if 0
      if (Gsx >= 0)   // update debugging coords
	{
	  VECTOR *v1, *v2 ;

	  v1 = VectorAlloc(4, MATRIX_REAL) ;
	  Gsx -= (box.x-pad) ;
	  Gsy -= (box.y-pad) ;
	  Gsz -= (box.z-pad) ;
	  V3_X(v1) = Gsx ; V3_Y(v1) = Gsy ; V3_Z(v1) = Gsz ;
	  VECTOR_ELT(v1,4) = 1.0 ;
	  v2 = MatrixMultiply(m_L, v1, NULL) ;
      
	  Gsx = nint(V3_X(v2)) ; Gsy = nint(V3_Y(v2)) ; Gsz = nint(V3_Z(v2)) ;
	  MatrixFree(&v2) ; MatrixFree(&v1) ;
	  printf("mapping by transform (%d, %d, %d) --> (%d, %d, %d) for rgb writing\n",
		 Gx, Gy, Gz, Gsx, Gsy, Gsz) ;
	}
#endif
      if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
	write_snapshot(mri_target, mri_source, m_L, &mp, 0, 1, "linear_init");

      lta->xforms[0].m_L = m_L ;
      printf("initializing GCAM with vox->vox matrix:\n") ;
      MatrixPrint(stdout, m_L) ;
      gcam = GCAMcreateFromIntensityImage(mri_source, mri_target, transform) ;
#if 0
      gcam->gca = gcaAllocMax(1, 1, 1, 
			      mri_target->width, mri_target->height, 
			      mri_target->depth,
			      0, 0) ;
#endif
      GCAMinitVolGeom(gcam, mri_source, mri_target) ;
      if (use_aseg)
	{
	  if (ribbon_name)
	    {
	      char fname[STRLEN], path[STRLEN], *str, *hemi ;
	      int  h, s, label ;
	      MRI_SURFACE *mris_white, *mris_pial ;
	      MRI         *mri ;

	      for (s = 0 ; s <= 1 ; s++) // source and target
		{
		  if (s == 0)
		    {
		      str = source_surf ;
		      mri = mri_source ;
		      FileNamePath(mri->fname, path) ;
		      strcat(path, "/../surf") ;
		    }
		  else
		    {
		      mri = mri_target ;
		      FileNamePath(mri->fname, path) ;
		      strcat(path, "/../elastic") ;
		      str = target_surf ;
		    }
		  // sorry - these values come from FreeSurferColorLUT.txt
		  MRIreplaceValueRange(mri, mri, 1000, 1034, Left_Cerebral_Cortex) ;
		  MRIreplaceValueRange(mri, mri, 1100, 1180, Left_Cerebral_Cortex) ;
		  MRIreplaceValueRange(mri, mri, 2000, 2034, Right_Cerebral_Cortex) ;
		  MRIreplaceValueRange(mri, mri, 2100, 2180, Right_Cerebral_Cortex) ;
		  for (h = LEFT_HEMISPHERE ; h <= RIGHT_HEMISPHERE ; h++)  
		    {
		      if (h == LEFT_HEMISPHERE)
			{
			  hemi = "lh" ;
			  label = Left_Cerebral_Cortex ;
			}
		      else
			{
			  label = Right_Cerebral_Cortex ;
			  hemi = "rh" ;
			}
		      sprintf(fname, "%s/%s%s.white", path, hemi, str) ;
		      mris_white = MRISread(fname) ;
		      if (mris_white == NULL)
			ErrorExit(ERROR_NOFILE, "%s: could not read surface %s", Progname, fname) ;
		      MRISsaveVertexPositions(mris_white, WHITE_VERTICES) ;
		      sprintf(fname, "%s/%s%s.pial", path, hemi, str) ;
		      mris_pial = MRISread(fname) ;
		      if (mris_pial == NULL)
			ErrorExit(ERROR_NOFILE, "%s: could not read surface %s", Progname, fname) ;
		      MRISsaveVertexPositions(mris_pial, PIAL_VERTICES) ;
		      if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
			{
			  sprintf(fname, "sb.mgz") ;
			  MRIwrite(mri_source, fname) ; 
			  sprintf(fname, "tb.mgz") ;
			  MRIwrite(mri_target, fname) ;
			}

		      insert_ribbon_into_aseg(mri, mri, mris_white, mris_pial, h) ;
		      if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
			{
			  sprintf(fname, "sa.mgz") ;
			  MRIwrite(mri_source, fname) ; 
			  sprintf(fname, "ta.mgz") ;
			  MRIwrite(mri_target, fname) ;
			}
		      MRISfree(&mris_white) ; MRISfree(&mris_pial) ;
		    }
		}
	      if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
		{
		  sprintf(fname, "s.mgz") ;
		  MRIwrite(mri_source, fname) ; 
		  sprintf(fname, "t.mgz") ;
		  MRIwrite(mri_target, fname) ;
		}
	    }
	  GCAMinitLabels(gcam, mri_target) ;
	  GCAMsetVariances(gcam, 1.0) ;
	  mp.mri_dist_map = create_distance_transforms(mri_source, mri_target, NULL, 40.0, gcam) ;
	}
    }
  else  /* use a previously create morph and integrate it some more */
    {
      printf("using previously create gcam...\n") ;
      gcam = (GCA_MORPH *)(transform->xform) ;
      GCAMrasToVox(gcam, mri_source) ;
      if (use_aseg)
	{
	  GCAMinitLabels(gcam, mri_target) ;
	  GCAMsetVariances(gcam, 1.0) ;
	  mp.mri_dist_map = create_distance_transforms(mri_source, mri_target, NULL, 40.0, gcam) ;
	}
      else
	GCAMaddIntensitiesFromImage(gcam, mri_target) ;
    }
  if (gcam->width != mri_source->width ||
      gcam->height != mri_source->height ||
      gcam->depth != mri_source->depth)
    ErrorExit(ERROR_BADPARM, "%s: warning gcam (%d, %d, %d), doesn't match source vol (%d, %d, %d)",
	      Progname, gcam->width, gcam->height, gcam->depth,
	      mri_source->width, mri_source->height, mri_source->depth) ;
	
  mp.mri_diag = mri_source ;
  mp.diag_morph_from_atlas = 0 ;
  mp.diag_write_snapshots = 1 ;
  mp.diag_sample_type = use_aseg ? SAMPLE_NEAREST : SAMPLE_TRILINEAR ;
  mp.diag_volume = use_aseg ? GCAM_LABEL : GCAM_MEANS ;

  if (renormalize)
    GCAMnormalizeIntensities(gcam, mri_target) ;
  if (mp.write_iterations != 0)
    {
      char fname[STRLEN] ;
      MRI  *mri_gca ;
		
      if (getenv("DONT_COMPRESS"))
        sprintf(fname, "%s_target.mgh", mp.base_name) ;
      else
        sprintf(fname, "%s_target.mgz", mp.base_name) ;
      if (mp.diag_morph_from_atlas == 0)
      {
        printf("writing target volume to %s...\n", fname) ;
        MRIwrite(mri_target, fname) ;
        sprintf(fname, "%s_target", mp.base_name) ;
        MRIwriteImageViews(mri_target, fname, IMAGE_SIZE) ;
      }
      else
      {
        if (use_aseg)
          mri_gca = GCAMwriteMRI(gcam, NULL, GCAM_LABEL) ;
        else
        {
          mri_gca = MRIclone(mri_source, NULL) ;
          GCAMbuildMostLikelyVolume(gcam, mri_gca) ;
        }
	  printf("writing target volume to %s...\n", fname) ;
	  MRIwrite(mri_gca, fname) ;
	  sprintf(fname, "%s_target", mp.base_name) ;
	  MRIwriteImageViews(mri_gca, fname, IMAGE_SIZE) ;
	  MRIfree(&mri_gca) ;
	}
    }

  if (nozero)
    {
      printf("disabling zero nodes\n") ;
      GCAMignoreZero(gcam, mri_target) ;
    }
  mp.mri = mri_target ;
  if (mp.regrid == True && new_transform == 0)
    GCAMregrid(gcam, mri_target, PAD, &mp, &mri_source) ;

  mp.write_fname = out_fname ;
  GCAMregister(gcam, mri_source, &mp) ; // atlas is target, morph target into register with it
  if (apply_transform)
    {
      MRI *mri_aligned ;
      char   fname[STRLEN] ;
		
      FileNameRemoveExtension(out_fname, fname) ;
      strcat(fname, ".mgz") ;
      mri_aligned = GCAMmorphToAtlas(mp.mri, gcam, NULL, -1, mp.diag_sample_type) ;
      printf("writing transformed output volume to %s...\n", fname) ;
      MRIwrite(mri_aligned, fname) ;
      MRIfree(&mri_aligned) ;
    }
  printf("writing warp vector field to %s\n", out_fname) ;
  GCAMvoxToRas(gcam) ;
  GCAMwrite(gcam, out_fname) ;
  GCAMrasToVox(gcam, mri_source) ;

  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("registration took %d minutes and %d seconds.\n", 
	 minutes, seconds) ;
  exit(0) ;
  return(0) ;
}
示例#12
0
int
main(int argc, char *argv[]) {
  char         *gca_fname, *in_fname, **av, *xform_fname ;
  MRI          *mri_in, *mri_tmp, *mri_orig = NULL ;
  GCA          *gca ;
  int          ac, nargs, input, ninputs ;
  TRANSFORM    *transform = NULL ;
  char         cmdline[CMD_LINE_LEN] ;
  double       ll ;

  make_cmd_version_string
  (argc, argv,
   "$Id: mri_log_likelihood.c,v 1.4 2011/03/02 00:04:22 nicks Exp $",
   "$Name: stable5 $", cmdline);

  /* rkt: check for and handle version tag */
  nargs = handle_version_option
          (argc, argv,
           "$Id: mri_log_likelihood.c,v 1.4 2011/03/02 00:04:22 nicks Exp $",
           "$Name: stable5 $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  setRandomSeed(-1L) ;
  Progname = argv[0] ;

  DiagInit(NULL, NULL, NULL) ;
  ErrorInit(NULL, NULL, NULL) ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (argc < 3)
    ErrorExit
    (ERROR_BADPARM,
     "usage: %s [<options>] <inbrain1> <inbrain2> ... "
     "<atlas> <transform file> ...\n",
     Progname) ;

  ninputs = (argc - 1) / 2 ;
  if (DIAG_VERBOSE_ON)
    printf("reading %d input volume%ss\n", ninputs, ninputs > 1 ? "s" : "") ;
  in_fname = argv[1] ;
  gca_fname = argv[1+ninputs] ;
  xform_fname = argv[2+ninputs] ;
  transform = TransformRead(xform_fname) ;
  if (!transform)
    ErrorExit(ERROR_NOFILE, "%s: could not read input transform from %s",
              Progname, xform_fname) ;

  if (DIAG_VERBOSE_ON)
    printf("reading atlas from '%s'...\n", gca_fname) ;
  gca = GCAread(gca_fname) ;
  if (!gca)
    ErrorExit(ERROR_NOFILE, "%s: could not read input atlas from %s",
              Progname, gca_fname) ;

  fflush(stdout) ;
  for (input = 0 ; input < ninputs ; input++) {
    in_fname = argv[1+input] ;
    if (DIAG_VERBOSE_ON)
      printf("reading input volume from %s...\n", in_fname) ;
    mri_tmp = MRIread(in_fname) ;
    if (!mri_tmp)
      ErrorExit(ERROR_NOFILE, "%s: could not read input MR volume from %s",
                Progname, in_fname) ;
    MRImakePositive(mri_tmp, mri_tmp) ;
    if (input == 0) {
      mri_in =
        MRIallocSequence(mri_tmp->width, mri_tmp->height, mri_tmp->depth,
                         mri_tmp->type, ninputs) ;
      if (!mri_in)
        ErrorExit(ERROR_NOMEMORY,
                  "%s: could not allocate input volume %dx%dx%dx%d",
                  mri_tmp->width,mri_tmp->height,mri_tmp->depth,ninputs) ;
      MRIcopyHeader(mri_tmp, mri_in) ;
    }

    MRIcopyFrame(mri_tmp, mri_in, 0, input) ;
    MRIfree(&mri_tmp) ;
  }
  MRIaddCommandLine(mri_in, cmdline) ;

  TransformInvert(transform, mri_in) ;

  if (orig_fname) {
    mri_orig = MRIread(orig_fname) ;
    if (mri_orig == NULL)
      ErrorExit(ERROR_NOFILE, "%s: could not read orig volume from %s", Progname, orig_fname) ;
  }
  ll = GCAimageLogLikelihood(gca, mri_in, transform, 1, mri_orig) ;
  printf("%2.0f\n", 10000*ll) ;

  MRIfree(&mri_in) ;

  if (gca)
    GCAfree(&gca) ;
  if (mri_in)
    MRIfree(&mri_in) ;
  exit(0) ;
  return(0) ;
}
示例#13
0
/*----------------------------------------------------------------------
  Parameters:

  Description:
  ----------------------------------------------------------------------*/
static int
get_option(int argc, char *argv[])
{
  int  nargs = 0 ;
  char *option ;
  float f ;

  option = argv[1] + 1 ;            /* past '-' */
  if (!stricmp(option, "-help")||!stricmp(option, "-usage"))
  {
    print_help() ;
  }
  else if (!stricmp(option, "-version"))
  {
    print_version() ;
  }
  else if (!stricmp(option, "dist"))
  {
    sscanf(argv[2], "%f", &parms.l_dist) ;
    nargs = 1 ;
    fprintf(stderr, "l_dist = %2.3f\n", parms.l_dist) ;
  }
  else if (!stricmp(option, "lm"))
  {
    parms.integration_type = INTEGRATE_LM_SEARCH ;
    fprintf(stderr, "integrating using binary search line minimization\n") ;
  }
  else if (!stricmp(option, "avgs"))
  {
    smooth_avgs = atoi(argv[2]) ;
    fprintf
    (stderr,
     "smoothing original positions %d times before computing metrics\n",
     smooth_avgs) ;
    nargs = 1 ;
  }
  else if (!stricmp(option, "rotate"))
  {
    ralpha = atof(argv[2]) ;
    rbeta = atof(argv[3]) ;
    rgamma = atof(argv[4]) ;
    nargs = 3 ;
    fprintf(stderr, "rotating brain by (%2.1f, %2.1f, %2.1f)\n",
            ralpha, rbeta, rgamma) ;
  }
  else if (!stricmp(option, "talairach"))
  {
    talairach = 1 ;
    fprintf(stderr, "transforming surface into Talairach space.\n") ;
  }
  else if (!stricmp(option, "remove_negative"))
  {
    remove_negative = atoi(argv[2]) ;
    nargs = 1 ;
    fprintf
    (stderr,
     "%sremoving negative triangles with iterative smoothing\n",
     remove_negative ? "" : "not ") ;
  }
  else if (!stricmp(option, "notal"))
  {
    talairach = 0 ;
    fprintf(stderr, "transforming surface into Talairach space.\n") ;
  }
  else if (!stricmp(option, "dt"))
  {
    parms.dt = atof(argv[2]) ;
    parms.base_dt = base_dt_scale*parms.dt ;
    nargs = 1 ;
    fprintf(stderr, "momentum with dt = %2.2f\n", parms.dt) ;
  }
  else if (!stricmp(option, "curv"))
  {
    sscanf(argv[2], "%f", &parms.l_curv) ;
    nargs = 1 ;
    fprintf(stderr, "using l_curv = %2.3f\n", parms.l_curv) ;
  }
  else if (!stricmp(option, "area"))
  {
    sscanf(argv[2], "%f", &parms.l_area) ;
    nargs = 1 ;
    fprintf(stderr, "using l_area = %2.3f\n", parms.l_area) ;
  }
  else if (!stricmp(option, "iarea"))
  {
    inflate_area = atof(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "inflation l_area = %2.3f\n", inflate_area) ;
  }
  else if (!stricmp(option, "itol"))
  {
    inflate_tol = atof(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "inflation tol = %2.3f\n", inflate_tol) ;
  }
  else if (!stricmp(option, "in"))
  {
    inflate_iterations = atoi(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "inflation iterations = %d\n", inflate_iterations) ;
  }
  else if (!stricmp(option, "idt"))
  {
    inflate_dt = atof(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "inflation dt = %f\n", inflate_dt) ;
  }
  else if (!stricmp(option, "iavgs"))
  {
    inflate_avgs = atoi(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "inflation averages = %d\n", inflate_avgs) ;
  }
  else if (!stricmp(option, "inlarea"))
  {
    inflate_nlarea = atof(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "inflation l_nlarea = %2.3f\n", inflate_nlarea) ;
  }
  else if (!stricmp(option, "ispring"))
  {
    inflate_spring = atof(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "inflation l_spring = %2.3f\n", inflate_spring) ;
  }
  else if (!stricmp(option, "adaptive"))
  {
    parms.integration_type = INTEGRATE_ADAPTIVE ;
    fprintf(stderr, "using adaptive time step integration\n") ;
  }
  else if (!stricmp(option, "nbrs"))
  {
    nbrs = atoi(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "using neighborhood size=%d\n", nbrs) ;
  }
  else if (!stricmp(option, "spring"))
  {
    sscanf(argv[2], "%f", &parms.l_spring) ;
    nargs = 1 ;
    fprintf(stderr, "using l_spring = %2.3f\n", parms.l_spring) ;
  }
  else if (!stricmp(option, "tspring"))
  {
    sscanf(argv[2], "%f", &parms.l_tspring) ;
    nargs = 1 ;
    fprintf(stderr, "using l_tspring = %2.3f\n", parms.l_tspring) ;
  }
  else if (!stricmp(option, "itspring"))
  {
    sscanf(argv[2], "%f", &inflate_tspring) ;
    nargs = 1 ;
    fprintf(stderr, "using inflation l_tspring = %2.3f\n", inflate_tspring) ;
  }
  else if (!stricmp(option, "convex"))
  {
    sscanf(argv[2], "%f", &l_convex) ;
    nargs = 1 ;
    fprintf(stderr, "using l_convex = %2.3f\n", l_convex) ;
  }
  else if (!stricmp(option, "expand"))
  {
    sscanf(argv[2], "%f", &l_expand) ;
    nargs = 1 ;
    fprintf(stderr, "using l_expand = %2.3f\n", l_expand) ;
  }
  else if (!stricmp(option, "spring_norm"))
  {
    sscanf(argv[2], "%f", &l_spring_norm) ;
    nargs = 1 ;
    fprintf(stderr, "using l_spring_norm = %2.3f\n", l_spring_norm) ;
  }
  else if (!stricmp(option, "sphere"))
  {
    sscanf(argv[2], "%f", &l_sphere) ;
    nargs = 1 ;
    fprintf(stderr, "using l_sphere = %2.3f\n", l_sphere) ;
  }
  else if (!stricmp(option, "name"))
  {
    strcpy(parms.base_name, argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "using base name = %s\n", parms.base_name) ;
  }
  else if (!stricmp(option, "angle"))
  {
    sscanf(argv[2], "%f", &parms.l_angle) ;
    nargs = 1 ;
    fprintf(stderr, "using l_angle = %2.3f\n", parms.l_angle) ;
  }
  else if (!stricmp(option, "area"))
  {
    sscanf(argv[2], "%f", &parms.l_area) ;
    nargs = 1 ;
    fprintf(stderr, "using l_area = %2.3f\n", parms.l_area) ;
  }
  else if (!stricmp(option, "tol"))
  {
    if (sscanf(argv[2], "%e", &f) < 1)
      ErrorExit(ERROR_BADPARM, "%s: could not scan tol from %s",
                Progname, argv[2]) ;
    parms.tol = (double)f ;
    nargs = 1 ;
    fprintf(stderr, "using tol = %2.2e\n", (float)parms.tol) ;
  }
  else if (!stricmp(option, "error_ratio"))
  {
    parms.error_ratio = atof(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "error_ratio=%2.3f\n", parms.error_ratio) ;
  }
  else if (!stricmp(option, "dt_inc"))
  {
    parms.dt_increase = atof(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "dt_increase=%2.3f\n", parms.dt_increase) ;
  }
  else if (!stricmp(option, "NLAREA"))
  {
    parms.l_nlarea = atof(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "nlarea = %2.3f\n", parms.l_nlarea) ;
  }
  else if (!stricmp(option, "PAREA"))
  {
    parms.l_parea = atof(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "parea = %2.3f\n", parms.l_parea) ;
  }
  else if (!stricmp(option, "RADIUS"))
  {
    target_radius = atof(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "target radius = %2.3f\n", target_radius) ;
  }
  else if (!stricmp(option, "RA"))
  {
    target_radius = -1 ;
    fprintf(stderr, "computing area-matching target radius\n") ;
  }
  else if (!stricmp(option, "debug"))
  {
    Gdiag = DIAG_SHOW ;
    fprintf(stderr, "enabling DIAG_SHOW for debug\n") ;
  }
  else if (!stricmp(option, "NLDIST"))
  {
    parms.l_nldist = atof(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "nldist = %2.3f\n", parms.l_nldist) ;
  }
  else if (!stricmp(option, "vnum") || !stricmp(option, "distances"))
  {
    parms.nbhd_size = atof(argv[2]) ;
    parms.max_nbrs = atof(argv[3]) ;
    nargs = 2 ;
    fprintf(stderr, "nbr size = %d, max neighbors = %d\n",
            parms.nbhd_size, parms.max_nbrs) ;
  }
  else if (!stricmp(option, "dt_dec"))
  {
    parms.dt_decrease = atof(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "dt_decrease=%2.3f\n", parms.dt_decrease) ;
  }
  else if (!stricmp(option, "seed"))
  {
    setRandomSeed(atol(argv[2])) ;
    fprintf(stderr,"setting seed for random number genererator to %d\n",
            atoi(argv[2])) ;
    nargs = 1 ;
  }
  else switch (toupper(*option))
    {
    case 'T':
      xform_fname = argv[2] ;
      vol_fname = argv[3] ;
      nargs = 2 ;
      break ;
    case 'O':
      orig_name = argv[2] ;
      fprintf(stderr, "using %s as original surface...\n", orig_name) ;
      nargs = 1 ;
      break ;
    case 'P':
      max_passes = atoi(argv[2]) ;
      fprintf(stderr, "limitting unfolding to %d passes\n", max_passes) ;
      nargs = 1 ;
      break ;
    case 'Q':
      remove_negative = 0 ;
      quick = 1 ;
      inflate = 1 ;
      inflate_iterations = 300 ;
      max_passes = 3 ;
      fprintf(stderr, "doing quick spherical unfolding.\n") ;
      nbrs = 1 ;
      parms.l_spring = parms.l_dist = parms.l_parea = parms.l_area = 0.0 ;
      parms.l_nlarea = 1.0 ;
      parms.tol = 1e-1 ;
      parms.n_averages = 32 ;
      /*    parms.tol = 10.0f / (sqrt(33.0/1024.0)) ;*/
      break ;
    case 'L':
      load = 1 ;
      break ;
    case 'B':
      base_dt_scale = atof(argv[2]) ;
      parms.base_dt = base_dt_scale*parms.dt ;
      nargs = 1;
      break ;
    case 'S':
      scale = atof(argv[2]) ;
      fprintf(stderr, "scaling brain by = %2.3f\n", (float)scale) ;
      nargs = 1 ;
      break ;
    case 'V':
      Gdiag_no = atoi(argv[2]) ;
      nargs = 1 ;
      break ;
    case 'D':
      disturb = atof(argv[2]) ;
      nargs = 1 ;
      fprintf
      (stderr, "disturbing vertex positions by %2.3f\n",(float)disturb) ;
      break ;
    case 'R':
      randomly_project = !randomly_project ;
      fprintf(stderr, "using random placement for projection.\n") ;
      break ;
    case 'M':
      parms.integration_type = INTEGRATE_MOMENTUM ;
      parms.momentum = atof(argv[2]) ;
      nargs = 1 ;
      fprintf(stderr, "momentum = %2.2f\n", (float)parms.momentum) ;
      break ;
    case 'W':
      Gdiag |= DIAG_WRITE ;
      sscanf(argv[2], "%d", &parms.write_iterations) ;
      nargs = 1 ;
      fprintf
      (stderr, "using write iterations = %d\n", parms.write_iterations) ;
      break ;
    case 'I':
      inflate = 1 ;
      fprintf(stderr, "inflating brain...\n") ;
      break ;
    case 'A':
      sscanf(argv[2], "%d", &parms.n_averages) ;
      nargs = 1 ;
      fprintf(stderr, "using n_averages = %d\n", parms.n_averages) ;
      break ;
    case '?':
    case 'H':
    case 'U':
      print_usage() ;
      exit(1) ;
      break ;
    case 'N':
      sscanf(argv[2], "%d", &parms.niterations) ;
      nargs = 1 ;
      fprintf(stderr, "using niterations = %d\n", parms.niterations) ;
      break ;
    default:
      fprintf(stderr, "unknown option %s\n", argv[1]) ;
      exit(1) ;
      break ;
    }

  return(nargs) ;
}
示例#14
0
int
main(int argc, char *argv[]) {
  char          **av, *cp, fname[STRLEN], *subject, *out_fname ;
  int           ac, nargs, msec, minutes, n, seconds, nsubjects, i, sno, nfeatures, correct ;
  struct timeb  start ;
  LABEL         *cortex_label, *training_label ;
  RANDOM_FOREST *rf ;
  double        **training_data ;
  int           *training_classes, ntraining ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mris_rf_train.c,v 1.1 2012/06/07 12:09:47 fischl Exp $", "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ; setRandomSeed(0L);
  DiagInit(NULL, NULL, NULL) ;

  TimerStart(&start) ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (argc < 3)
    usage_exit(1) ;


  if (strlen(sdir) == 0) {
    cp = getenv("SUBJECTS_DIR") ;
    if (!cp)
      ErrorExit(ERROR_BADPARM, "%s: SUBJECTS_DIR not defined in env or cmd line",Progname) ;
    strcpy(sdir, cp) ;
  }

  nsubjects = argc-(ARGC_OFFSET+1) ;
  printf("training random forest classifier using %d subjects\n", nsubjects) ;
  for (n = ARGC_OFFSET ; n < argc-1 ; n++)
  {
    subject = argv[n] ;
    sno = n-ARGC_OFFSET ;
    printf("processing subject %s: %d of %d\n", subject, sno+1, nsubjects) ;


    sprintf(fname, "%s/%s/label/lh.%s.label", sdir, subject, label_name) ;
    if (FileExists(fname) == 0)
    {
      sprintf(fname, "%s/%s/label/rh.%s.label", sdir, subject, label_name) ;
    if (FileExists(fname) == 0)
      ErrorExit(ERROR_NOFILE, "%s: subject %s has no training label for either hemisphere", Progname, subject) ;
      hemi = "rh" ;
    }
    else
      hemi = "lh" ;

    training_label = LabelRead(NULL, fname) ;
    if (training_label == NULL)
      ErrorExit(ERROR_NOFILE, "%s: could not read training label %s\n", Progname, fname) ;

    sprintf(fname, "%s/%s/surf/%s.%s", sdir, subject, hemi, surf_name) ;
    mris[sno] = MRISread(fname) ;
    if (!mris[sno])
      ErrorExit(ERROR_NOFILE, "%s: could not read surface from %s",Progname, fname) ;
    
    MRIScomputeMetricProperties(mris[sno]) ;
    if (nbhd_size > mris[sno]->nsize)
      MRISsetNeighborhoodSize(mris[sno], nbhd_size) ;
    sprintf(fname, "%s/%s/label/%s.%s", sdir, subject, hemi, cortex_label_name) ;
    cortex_label = LabelRead(NULL, fname) ;
    if (cortex_label == NULL)
      ErrorExit(ERROR_NOFILE, "%s: could not read cortex label %s\n", Progname, fname) ;
    LabelRipRestOfSurface(cortex_label, mris[sno]) ;

    MRISclearMarks(mris[sno]) ;
    LabelFillUnassignedVertices(mris[sno], training_label, CURRENT_VERTICES);
    LabelDilate(training_label, mris[sno], ndilates) ;
    LabelMark(training_label, mris[sno]) ;
    LabelFree(&training_label) ;

    for (i = 0 ; i < noverlays ; i++)
    {
      sprintf(fname, "%s/%s/surf/%s.%s", sdir, subject, hemi, overlay_names[i]) ;
      mri_overlays[sno][i] = MRIread(fname) ;
      if (mri_overlays[sno][i] == NULL)
	ErrorExit(ERROR_NOFILE, "%s: could not read overlay %s (%d)\n", Progname, fname, i) ;
    }
    LabelFree(&cortex_label) ;
  }

  nfeatures = noverlays*(nbhd_size+1) ;
  rf = RFalloc(ntrees, nfeatures, 2, max_depth, class_names, 100) ;
  rf->feature_names = (char **)calloc(nfeatures, sizeof(char *)) ;
  for (i = 0 ; i < noverlays ; i++)
  {
    rf->feature_names[i] = (char *)calloc(strlen(overlay_names[i])+1, sizeof(char)) ;
    strcpy(rf->feature_names[i], overlay_names[i]) ;
  }
  assemble_training_data_and_free_mris(mris, mri_overlays, nsubjects, noverlays, &training_classes, &training_data, &ntraining) ;
  RFtrain(rf, 1.0, training_fraction, training_classes, training_data, ntraining);
  correct = RFcomputeOutOfBagCorrect(rf, training_classes, training_data, ntraining);
  printf("out of bag accuracy = %2.1f (%d of %d)\n", (float)correct*100.0f/ntraining, correct, ntraining) ;

  RFevaluateFeatures(rf, stdout) ;

  out_fname = argv[argc-1] ;
  printf("writing output to %s\n", out_fname) ;
  RFwrite(rf, out_fname) ;
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;

  printf("random forest training took %d minutes and %d seconds.\n", minutes, seconds) ;

  exit(0) ;
  return(0) ;
}
示例#15
0
HWMapContainer::HWMapContainer(QWidget * parent) :
    QWidget(parent),
    mainLayout(this),
    pMap(0),
    mapgen(MAPGEN_REGULAR),
    m_previewSize(256, 128)
{
    // don't show preview anything until first show event
    m_previewEnabled = false;
    m_missionsViewSetup = false;
    m_staticViewSetup = false;
    m_script = QString();

    hhSmall.load(":/res/hh_small.png");
    hhLimit = 18;
    templateFilter = 0;
    m_master = true;

    linearGrad = QLinearGradient(QPoint(128, 0), QPoint(128, 128));
    linearGrad.setColorAt(1, QColor(0, 0, 192));
    linearGrad.setColorAt(0, QColor(66, 115, 225));

    mainLayout.setContentsMargins(HWApplication::style()->pixelMetric(QStyle::PM_LayoutLeftMargin),
                                  10,
                                  HWApplication::style()->pixelMetric(QStyle::PM_LayoutRightMargin),
                                  HWApplication::style()->pixelMetric(QStyle::PM_LayoutBottomMargin));

    m_staticMapModel = DataManager::instance().staticMapModel();
    m_missionMapModel = DataManager::instance().missionMapModel();
    m_themeModel = DataManager::instance().themeModel();

    /* Layouts */

    QWidget * topWidget = new QWidget();
    QHBoxLayout * topLayout = new QHBoxLayout(topWidget);
    topWidget->setContentsMargins(0, 0, 0, 0);
    topLayout->setContentsMargins(0, 0, 0, 0);

    QHBoxLayout * twoColumnLayout = new QHBoxLayout();
    QVBoxLayout * leftLayout = new QVBoxLayout();
    QVBoxLayout * rightLayout = new QVBoxLayout();
    twoColumnLayout->addLayout(leftLayout, 0);
    twoColumnLayout->addStretch(1);
    twoColumnLayout->addLayout(rightLayout, 0);
    QVBoxLayout * drawnControls = new QVBoxLayout();

    /* Map type combobox */

    topLayout->setSpacing(10);
    topLayout->addWidget(new QLabel(tr("Map type:")), 0);
    cType = new QComboBox(this);
    topLayout->addWidget(cType, 1);
    cType->insertItem(0, tr("Image map"), MapModel::StaticMap);
    cType->insertItem(1, tr("Mission map"), MapModel::MissionMap);
    cType->insertItem(2, tr("Hand-drawn"), MapModel::HandDrawnMap);
    cType->insertItem(3, tr("Randomly generated"), MapModel::GeneratedMap);
    cType->insertItem(4, tr("Random maze"), MapModel::GeneratedMaze);
    cType->insertItem(5, tr("Random perlin"), MapModel::GeneratedPerlin);
    connect(cType, SIGNAL(currentIndexChanged(int)), this, SLOT(mapTypeChanged(int)));
    m_childWidgets << cType;

    /* Randomize button */

    topLayout->addStretch(1);
    const QIcon& lp = QIcon(":/res/dice.png");
    QSize sz = lp.actualSize(QSize(65535, 65535));
    btnRandomize = new QPushButton();
    btnRandomize->setText(tr("Random"));
    btnRandomize->setIcon(lp);
    btnRandomize->setFixedHeight(30);
    btnRandomize->setIconSize(sz);
    btnRandomize->setFlat(true);
    btnRandomize->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    connect(btnRandomize, SIGNAL(clicked()), this, SLOT(setRandomMap()));
    m_childWidgets << btnRandomize;
    btnRandomize->setStyleSheet("padding: 5px;");
    btnRandomize->setFixedHeight(cType->height());
    topLayout->addWidget(btnRandomize, 1);

    /* Seed button */

    btnSeed = new QPushButton(parentWidget()->parentWidget());
    btnSeed->setText(tr("Seed"));
    btnSeed->setStyleSheet("padding: 5px;");
    btnSeed->setFixedHeight(cType->height());
    connect(btnSeed, SIGNAL(clicked()), this, SLOT(showSeedPrompt()));
    topLayout->addWidget(btnSeed, 0);

    /* Map preview label */

    QLabel * lblMapPreviewText = new QLabel(this);
    lblMapPreviewText->setText(tr("Map preview:"));
    leftLayout->addWidget(lblMapPreviewText, 0);

    /* Map Preview */

    mapPreview = new QPushButton(this);
    mapPreview->setObjectName("mapPreview");
    mapPreview->setFlat(true);
    mapPreview->setFixedSize(256 + 6, 128 + 6);
    mapPreview->setContentsMargins(0, 0, 0, 0);
    leftLayout->addWidget(mapPreview, 0);
    connect(mapPreview, SIGNAL(clicked()), this, SLOT(previewClicked()));

    /* Bottom-Left layout */

    QVBoxLayout * bottomLeftLayout = new QVBoxLayout();
    leftLayout->addLayout(bottomLeftLayout, 1);

    /* Map list label */

    lblMapList = new QLabel(this);
    rightLayout->addWidget(lblMapList, 0);

    /* Static maps list */

    staticMapList = new QListView(this);
    rightLayout->addWidget(staticMapList, 1);
    m_childWidgets << staticMapList;

    /* Mission maps list */

    missionMapList = new QListView(this);
    rightLayout->addWidget(missionMapList, 1);
    m_childWidgets << missionMapList;

    /* Map load and edit buttons */

    drawnControls->addStretch(1);

    btnLoadMap = new QPushButton(tr("Load map drawing"));
    btnLoadMap->setStyleSheet("padding: 20px;");
    drawnControls->addWidget(btnLoadMap, 0);
    m_childWidgets << btnLoadMap;
    connect(btnLoadMap, SIGNAL(clicked()), this, SLOT(loadDrawing()));

    btnEditMap = new QPushButton(tr("Edit map drawing"));
    btnEditMap->setStyleSheet("padding: 20px;");
    drawnControls->addWidget(btnEditMap, 0);
    m_childWidgets << btnEditMap;
    connect(btnEditMap, SIGNAL(clicked()), this, SIGNAL(drawMapRequested()));

    drawnControls->addStretch(1);

    rightLayout->addLayout(drawnControls);

    /* Generator style list */

    generationStyles = new QListWidget(this);
    new QListWidgetItem(tr("All"), generationStyles);
    new QListWidgetItem(tr("Small"), generationStyles);
    new QListWidgetItem(tr("Medium"), generationStyles);
    new QListWidgetItem(tr("Large"), generationStyles);
    new QListWidgetItem(tr("Cavern"), generationStyles);
    new QListWidgetItem(tr("Wacky"), generationStyles);
    connect(generationStyles, SIGNAL(currentRowChanged(int)), this, SLOT(setTemplateFilter(int)));
    m_childWidgets << generationStyles;
    rightLayout->addWidget(generationStyles, 1);

    /* Maze style list */

    mazeStyles = new QListWidget(this);
    new QListWidgetItem(tr("Small tunnels"), mazeStyles);
    new QListWidgetItem(tr("Medium tunnels"), mazeStyles);
    new QListWidgetItem(tr("Large tunnels"), mazeStyles);
    new QListWidgetItem(tr("Small islands"), mazeStyles);
    new QListWidgetItem(tr("Medium islands"), mazeStyles);
    new QListWidgetItem(tr("Large islands"), mazeStyles);
    connect(mazeStyles, SIGNAL(currentRowChanged(int)), this, SLOT(setMazeSize(int)));
    m_childWidgets << mazeStyles;
    rightLayout->addWidget(mazeStyles, 1);

    /* Mission description */

    lblDesc = new QLabel();
    lblDesc->setWordWrap(true);
    lblDesc->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    lblDesc->setAlignment(Qt::AlignTop | Qt::AlignLeft);
    lblDesc->setStyleSheet("font: 10px;");
    bottomLeftLayout->addWidget(lblDesc, 100);

    /* Add stretch above theme button */

    bottomLeftLayout->addStretch(1);

    /* Theme chooser */

    btnTheme = new QPushButton(this);
    btnTheme->setFlat(true);
    connect(btnTheme, SIGNAL(clicked()), this, SLOT(showThemePrompt()));
    m_childWidgets << btnTheme;
    bottomLeftLayout->addWidget(btnTheme, 0);

    /* Add everything to main layout */

    mainLayout.addWidget(topWidget, 0);
    mainLayout.addLayout(twoColumnLayout, 1);

    /* Set defaults */

    setRandomSeed();
    setMazeSize(0);
    setTemplateFilter(0);
    staticMapChanged(m_staticMapModel->index(0, 0));
    missionMapChanged(m_missionMapModel->index(0, 0));
    changeMapType(MapModel::GeneratedMap);
}
示例#16
0
/*----------------------------------------------------------------------
            Parameters:

           Description:
----------------------------------------------------------------------*/
static int
get_option(int argc, char *argv[])
{
  int  nargs = 0 ;
  char *option ;
  float f ;

  option = argv[1] + 1 ;            /* past '-' */
  if (!stricmp(option, "-help"))
  {
    print_help() ;
  }
  else if (!stricmp(option, "-version"))
  {
    print_version() ;
  }
  else if (!stricmp(option, "synth"))
  {
    synth_name = argv[2] ;
    nargs = 1 ;
  }
  else if (!stricmp(option, "overlay"))
  {
    mri_overlay = MRIread(argv[2]) ;
    nargs = 1 ;
    if (mri_overlay == NULL)
      ErrorExit(ERROR_NOFILE, "%s: could not read overlay from %s", argv[2]) ;
    parms.niterations = 0 ;   // this will disable the actual flattening
  }
  else if (!stricmp(option, "label_overlay") || !stricmp(option, "overlay_label"))
  {
    label_overlay = LabelRead(NULL, argv[2]) ;
    nargs = 1 ;
    if (label_overlay == NULL)
      ErrorExit(ERROR_NOFILE, "%s: could not read label overlay from %s", Progname,argv[2]) ;
  }
  else if (!stricmp(option, "norand"))
  {
    setRandomSeed(0L) ;
  }
  else if (!stricmp(option, "sphere"))
  {
    sphere_flag = 1 ;
  }
  else if (!stricmp(option, "plane"))
  {
    plane_flag = 1 ;
  }
  else if (!stricmp(option, "rescale"))
  {
    rescale = atof(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "rescaling brain by %2.3f\n", rescale) ;
  }
  else if (!stricmp(option, "dilate"))
  {
    dilate = atoi(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "dilating cuts %d times\n", dilate) ;
  }
  else if (!stricmp(option, "dist"))
  {
    sscanf(argv[2], "%f", &parms.l_dist) ;
    nargs = 1 ;
    fprintf(stderr, "l_dist = %2.3f\n", parms.l_dist) ;
  }
  else if (!stricmp(option, "expand"))
  {
    sscanf(argv[2], "%f", &parms.l_expand) ;
    nargs = 1 ;
    printf("setting l_expand = %2.3f\n", parms.l_expand) ;
  }
  else if (!stricmp(option, "unfold"))
  {
    MRI *mri_kernel, *mri_tmp ;

    sscanf(argv[2], "%f", &parms.l_unfold) ;
    mri_tmp = MRIread(argv[3]) ;
    if (!mri_tmp)
      ErrorExit(ERROR_NOFILE, "%s: could not read distance map %s...\n",
                Progname, argv[3]) ;

    mri_kernel = MRIgaussian1d(1.0, -1) ;
    parms.mri_dist = MRIconvolveGaussian(mri_tmp, NULL, mri_kernel) ;
    MRIfree(&mri_kernel) ;
    MRIfree(&mri_tmp) ;
    nargs = 2 ;
    fprintf(stderr, "l_unfold = %2.3f\n", parms.l_unfold) ;
  }
  else if (!stricmp(option, "boundary"))
  {
    sscanf(argv[2], "%f", &parms.l_boundary) ;
    nargs = 1 ;
    fprintf(stderr, "l_boundary = %2.3f\n", parms.l_boundary) ;
  }
  else if (!stricmp(option, "lm"))
  {
    parms.integration_type = INTEGRATE_LINE_MINIMIZE ;
    fprintf(stderr, "integrating with line minimization\n") ;
  }
  else if (!stricmp(option, "dt"))
  {
    parms.dt = atof(argv[2]) ;
    parms.base_dt = base_dt_scale*parms.dt ;
    nargs = 1 ;
    fprintf(stderr, "momentum with dt = %2.2f\n", parms.dt) ;
  }
  else if (!stricmp(option, "curv"))
  {
    sscanf(argv[2], "%f", &parms.l_curv) ;
    nargs = 1 ;
    fprintf(stderr, "using l_curv = %2.3f\n", parms.l_curv) ;
  }
  else if (!stricmp(option, "nospring"))
  {
    nospring = 1 ;
  }
  else if (!stricmp(option, "area"))
  {
    sscanf(argv[2], "%f", &parms.l_area) ;
    nargs = 1 ;
    fprintf(stderr, "using l_area = %2.3f\n", parms.l_area) ;
  }
  else if (!stricmp(option, "nlarea"))
  {
    sscanf(argv[2], "%f", &parms.l_nlarea) ;
    nargs = 1 ;
    fprintf(stderr, "using l_nlarea = %2.3f\n", parms.l_nlarea) ;
  }
  else if (!stricmp(option, "boundary"))
  {
    sscanf(argv[2], "%f", &parms.l_boundary) ;
    nargs = 1 ;
    fprintf(stderr, "using l_boundary = %2.3f\n", parms.l_boundary) ;
  }
  else if (!stricmp(option, "adaptive"))
  {
    parms.integration_type = INTEGRATE_ADAPTIVE ;
    fprintf(stderr, "using adaptive time step integration\n") ;
  }
  else if (!stricmp(option, "nbrs"))
  {
    nbrs = atoi(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "using neighborhood size=%d\n", nbrs) ;
  }
  else if (!stricmp(option, "spring"))
  {
    sscanf(argv[2], "%f", &parms.l_spring) ;
    nargs = 1 ;
    fprintf(stderr, "using l_spring = %2.3f\n", parms.l_spring) ;
  }
  else if (!stricmp(option, "name"))
  {
    strcpy(parms.base_name, argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "using base name = %s\n", parms.base_name) ;
  }
  else if (!stricmp(option, "angle"))
  {
    sscanf(argv[2], "%f", &parms.l_angle) ;
    nargs = 1 ;
    fprintf(stderr, "using l_angle = %2.3f\n", parms.l_angle) ;
  }
  else if (!stricmp(option, "area"))
  {
    sscanf(argv[2], "%f", &parms.l_area) ;
    nargs = 1 ;
    fprintf(stderr, "using l_area = %2.3f\n", parms.l_area) ;
  }
  else if (!stricmp(option, "tol"))
  {
    if (sscanf(argv[2], "%e", &f) < 1)
      ErrorExit(ERROR_BADPARM, "%s: could not scan tol from %s",
                Progname, argv[2]) ;
    parms.tol = (double)f ;
    nargs = 1 ;
    fprintf(stderr, "using tol = %2.2e\n", (float)parms.tol) ;
  }
  else if (!stricmp(option, "error_ratio"))
  {
    parms.error_ratio = atof(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "error_ratio=%2.3f\n", parms.error_ratio) ;
  }
  else if (!stricmp(option, "dt_inc"))
  {
    parms.dt_increase = atof(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "dt_increase=%2.3f\n", parms.dt_increase) ;
  }
  else if (!stricmp(option, "complete"))
  {
    parms.complete_dist_mat = 1 ;
    fprintf(stderr, "using complete distance matrix\n") ;
  }
  else if (!stricmp(option, "vnum") || (!stricmp(option, "distances")))
  {
    parms.nbhd_size = atof(argv[2]) ;
    parms.max_nbrs = atof(argv[3]) ;
    nargs = 2 ;
    fprintf(stderr, "sampling %d neighbors out to a distance of %d mm\n",
            parms.max_nbrs, parms.nbhd_size) ;
  }
  else if (!stricmp(option, "dt_dec"))
  {
    parms.dt_decrease = atof(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "dt_decrease=%2.3f\n", parms.dt_decrease) ;
  }
  else if (!stricmp(option, "ou"))
  {
    original_unfold_surf_name = argv[2] ;
    nargs = 1 ;
    fprintf(stderr,"reading original unfolding surface from %s...\n",
            original_unfold_surf_name);
  }
  else if (!stricmp(option, "as"))
  {
    parms.area_coef_scale = atof(argv[2]) ;
    printf("setting area coef scale to %2.3f\n",
           parms.area_coef_scale) ;
    nargs = 1 ;
  }
  else switch (toupper(*option))
    {
    case 'P':
      max_passes = atoi(argv[2]) ;
      fprintf(stderr, "limitting unfolding to %d passes\n", max_passes) ;
      nargs = 1 ;
      break ;
    case '1':
      one_surf_flag = 1 ;  /* patch is only surface file */
      break ;
    case 'O':
      original_surf_name = argv[2] ;
      nargs = 1 ;
      fprintf(stderr,"reading original surface from %s...\n",
              original_surf_name);
      break ;
    case 'B':
      base_dt_scale = atof(argv[2]) ;
      parms.base_dt = base_dt_scale*parms.dt ;
      nargs = 1;
      break ;
    case 'V':
      Gdiag_no = atoi(argv[2]) ;
      nargs = 1 ;
      break ;
    case 'L':
      label_fname = argv[2] ;
      dilate_label = atof(argv[3]) ;
      nargs = 2;
      printf("loading label %s and dilating it %d times before flattening\n",
             label_fname, dilate_label) ;
      break ;
    case 'D':
      disturb = atof(argv[2]) ;
      nargs = 1 ;
      fprintf(stderr, "disturbing vertex positions by %2.3f\n",
              (float)disturb) ;
      break ;
    case 'R':
      randomly_flatten = !randomly_flatten ;
      fprintf(stderr, "using random placement for flattening.\n") ;
      break ;
    case 'M':
      parms.integration_type = INTEGRATE_MOMENTUM ;
      parms.momentum = atof(argv[2]) ;
      nargs = 1 ;
      fprintf(stderr, "momentum = %2.2f\n", (float)parms.momentum) ;
      break ;
    case 'S':
      scale = atof(argv[2]) ;
      fprintf(stderr, "scaling brain by = %2.3f\n", (float)scale) ;
      nargs = 1 ;
      break ;
    case 'W':
      Gdiag |= DIAG_WRITE ;
      sscanf(argv[2], "%d", &parms.write_iterations) ;
      nargs = 1 ;
      fprintf(stderr, "using write iterations = %d\n",
              parms.write_iterations) ;
      break ;
    case 'I':
      inflate = 1 ;
      fprintf(stderr, "inflating brain...\n") ;
      break ;
    case 'A':
      sscanf(argv[2], "%d", &parms.n_averages) ;
      nargs = 1 ;
      fprintf(stderr, "using n_averages = %d\n", parms.n_averages) ;
      break ;
    case 'N':
      sscanf(argv[2], "%d", &parms.niterations) ;
      nargs = 1 ;
      fprintf(stderr, "using niterations = %d\n", parms.niterations) ;
      break ;
    default:
    case 'H':
    case '?':
    case 'U':
      print_help() ;
      break ;
    }

  return(nargs) ;
}
示例#17
0
/*---------------------------------------------------------------*/
int main(int argc, char *argv[]) {
  int nargs, nthvtx, nnbrs1, nnbrs2, nthnbr, nbrvtxno1, nbrvtxno2;
  int nthface, annot1, annot2;
  VERTEX *vtx1, *vtx2;
  FACE *face1, *face2;
  float diff, maxdiff;

  nargs = handle_version_option (argc, argv, vcid, "$Name: stable5 $");
  if (nargs && argc - nargs == 1) exit (0);
  argc -= nargs;
  cmdline = argv2cmdline(argc,argv);
  uname(&uts);
  getcwd(cwd,2000);

  Progname = argv[0] ;
  argc --;
  argv++;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;
  if (argc == 0) usage_exit();
  parse_commandline(argc, argv);
  check_options();
  if (checkoptsonly) return(0);

  SUBJECTS_DIR = getenv("SUBJECTS_DIR");
  if (SUBJECTS_DIR == NULL) {
    printf("INFO: SUBJECTS_DIR not defined in environment\n");
    //exit(1);
  }
  if (SUBJECTS_DIR1 == NULL) SUBJECTS_DIR1 = SUBJECTS_DIR;
  if (SUBJECTS_DIR2 == NULL) SUBJECTS_DIR2 = SUBJECTS_DIR;

  if (surf1path == NULL && surfname == NULL) surfname = "orig";

  if (surf1path == NULL) {
    sprintf(tmpstr,"%s/%s/surf/%s.%s",SUBJECTS_DIR1,subject1,hemi,surfname);
    surf1path = strcpyalloc(tmpstr);
  }
  if (surf2path == NULL) {
    sprintf(tmpstr,"%s/%s/surf/%s.%s",SUBJECTS_DIR2,subject2,hemi,surfname);
    surf2path = strcpyalloc(tmpstr);
  }
  dump_options(stdout);

  //read-in each surface.  notice that the random number generator is
  //seeded with the same value prior to each read.  this is because in
  //the routine MRIScomputeNormals, if it finds a zero-length vertex
  //normal, is adds a random value to the x,y,z and recomputes the normal.
  //so if comparing identical surfaces, the seed must be the same so that
  //any zero-length vertex normals appear the same.
  setRandomSeed(seed) ;
  surf1 = MRISread(surf1path);
  if (surf1 == NULL) {
    printf("ERROR: could not read %s\n",surf1path);
    exit(1);
  }
  setRandomSeed(seed) ;
  surf2 = MRISread(surf2path);
  if (surf2 == NULL) {
    printf("ERROR: could not read %s\n",surf2path);
    exit(1);
  }
  printf("Number of vertices %d %d\n",surf1->nvertices,surf2->nvertices);
  printf("Number of faces    %d %d\n",surf1->nfaces,surf2->nfaces);

  //Number of Vertices ----------------------------------------
  if (surf1->nvertices != surf2->nvertices) {
    printf("Surfaces differ in number of vertices %d %d\n",
           surf1->nvertices,surf2->nvertices);
    exit(101);
  }
  //Number of Faces ------------------------------------------
  if (surf1->nfaces != surf2->nfaces) {
    printf("Surfaces differ in number of faces %d %d\n",
           surf1->nfaces,surf2->nfaces);
    exit(101);
  }

  //surf1->faces[10000].area = 100;
  //surf1->vertices[10000].x = 100;

  if (ComputeNormalDist) {
    double dist, dx, dy, dz, dot ;
    MRI    *mri_dist ;

    mri_dist = MRIalloc(surf1->nvertices,1,1,MRI_FLOAT) ;
    MRIScomputeMetricProperties(surf1) ;
    MRIScomputeMetricProperties(surf2) ;
    for (nthvtx=0; nthvtx < surf1->nvertices; nthvtx++) {
      vtx1 = &(surf1->vertices[nthvtx]);
      vtx2 = &(surf2->vertices[nthvtx]);
      dx = vtx2->x-vtx1->x ;
      dy = vtx2->y-vtx1->y ;
      dz = vtx2->z-vtx1->z ;
      dist = sqrt(dx*dx + dy*dy + dz*dz) ;
      dot = dx*vtx1->nx + dy*vtx1->ny + dz*vtx1->nz ;
      dist = dist * dot / fabs(dot) ;
      MRIsetVoxVal(mri_dist, nthvtx, 0, 0, 0, dist) ;
    }
    MRIwrite(mri_dist, out_fname) ;
    MRIfree(&mri_dist) ;
    exit(0);
  }

  maxdiff=0;

  //------------------------------------------------------------
  if (CheckSurf) {
    printf("Comparing surfaces\n");

    // Loop over vertices ---------------------------------------
    error_count=0;
    for (nthvtx=0; nthvtx < surf1->nvertices; nthvtx++) {
      vtx1 = &(surf1->vertices[nthvtx]);
      vtx2 = &(surf2->vertices[nthvtx]);
      if (vtx1->ripflag != vtx2->ripflag) {
        printf("Vertex %d differs in ripflag %c %c\n",
               nthvtx,vtx1->ripflag,vtx2->ripflag);
        if (++error_count>=MAX_NUM_ERRORS) break;
      }
      if (CheckXYZ) {
        diff=fabs(vtx1->x - vtx2->x);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Vertex %d differs in x %g %g\t(%g)\n",
                 nthvtx,vtx1->x,vtx2->x,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
        diff=fabs(vtx1->y - vtx2->y);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Vertex %d differs in y %g %g\t(%g)\n",
                 nthvtx,vtx1->y,vtx2->y,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
        diff=fabs(vtx1->z - vtx2->z);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Vertex %d differs in z %g %g\t(%g)\n",
                 nthvtx,vtx1->z,vtx2->z,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
      }
      if (CheckNXYZ) {
        diff=fabs(vtx1->nx - vtx2->nx);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Vertex %d differs in nx %g %g\t(%g)\n",
                 nthvtx,vtx1->nx,vtx2->nx,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
        diff=fabs(vtx1->ny - vtx2->ny);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Vertex %d differs in ny %g %g\t(%g)\n",
                 nthvtx,vtx1->ny,vtx2->ny,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
        diff=fabs(vtx1->nz - vtx2->nz);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Vertex %d differs in nz %g %g\t(%g)\n",
                 nthvtx,vtx1->nz,vtx2->nz,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
      }
      nnbrs1 = surf1->vertices[nthvtx].vnum;
      nnbrs2 = surf2->vertices[nthvtx].vnum;
      if (nnbrs1 != nnbrs2) {
        printf("Vertex %d has a different number of neighbors %d %d\n",
               nthvtx,nnbrs1,nnbrs2);
        if (++error_count>=MAX_NUM_ERRORS) break;
      }
      for (nthnbr=0; nthnbr < nnbrs1; nthnbr++) {
        nbrvtxno1 = surf1->vertices[nthvtx].v[nthnbr];
        nbrvtxno2 = surf2->vertices[nthvtx].v[nthnbr];
        if (nbrvtxno1 != nbrvtxno2) {
          printf("Vertex %d differs in the identity of the "
                 "%dth neighbor %d %d\n",nthvtx,nthnbr,nbrvtxno1,nbrvtxno2);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
      }
      if (error_count>=MAX_NUM_ERRORS) break;
    }// loop over vertices
    if (maxdiff>0) printf("maxdiff=%g\n",maxdiff);
    if (error_count > 0) {
      printf("Exiting after finding %d errors\n",error_count);
      if (error_count>=MAX_NUM_ERRORS) {
        printf("Exceeded MAX_NUM_ERRORS loop guard\n");
      }
      exit(103);
    }

    // Loop over faces ----------------------------------------
    error_count=0;
    for (nthface=0; nthface < surf1->nfaces; nthface++) {
      face1 = &(surf1->faces[nthface]);
      face2 = &(surf2->faces[nthface]);
      if (CheckNXYZ) {
        diff=fabs(face1->nx - face2->nx);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Face %d differs in nx %g %g\t(%g)\n",
                 nthface,face1->nx,face2->nx,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
        diff=fabs(face1->ny - face2->ny);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Face %d differs in ny %g %g\t(%g)\n",
                 nthface,face1->ny,face2->ny,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
        diff=fabs(face1->nz - face2->nz);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Face %d differs in nz %g %g\t(%g)\n",
                 nthface,face1->nz,face2->nz,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
      }
      diff=fabs(face1->area - face2->area);
      if (diff>maxdiff) maxdiff=diff;
      if (diff>thresh) {
        printf("Face %d differs in area %g %g\t(%g)\n",
               nthface,face1->area,face2->area,diff);
        if (++error_count>=MAX_NUM_ERRORS) break;
      }
      if (face1->ripflag != face2->ripflag) {
        printf("Face %d differs in ripflag %c %c\n",
               nthface,face1->ripflag,face2->ripflag);
        if (++error_count>=MAX_NUM_ERRORS) break;
      }
      for (nthvtx = 0; nthvtx < 3; nthvtx++) {
        if (face1->v[nthvtx] != face2->v[nthvtx]) {
          printf("Face %d differs in identity of %dth vertex %d %d\n",
                 nthface,nthvtx,face1->ripflag,face2->ripflag);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
      } // end loop over nthface vertex
      if (error_count>=MAX_NUM_ERRORS) break;
    } // end loop over faces
    if (maxdiff>0) printf("maxdiff=%g\n",maxdiff);
    if (error_count > 0) {
      printf("Exiting after finding %d errors\n",error_count);
      if (error_count>=MAX_NUM_ERRORS) {
        printf("Exceeded MAX_NUM_ERRORS loop guard\n");
      }
      exit(103);
    }

    printf("Surfaces are the same\n");
    exit(0);
  } // end check surf

  // -----------------------------------------------------------------
  if (CheckCurv) {
    printf("Checking curv file %s\n",curvname);
    sprintf(tmpstr,"%s/%s/surf/%s.%s",SUBJECTS_DIR1,subject1,hemi,curvname);
    printf("Loading curv file %s\n",tmpstr);
    if (MRISreadCurvatureFile(surf1, tmpstr) != 0) {
      printf("ERROR: reading curvature file %s\n",tmpstr);
      exit(1);
    }
    sprintf(tmpstr,"%s/%s/surf/%s.%s",SUBJECTS_DIR2,subject2,hemi,curvname);
    printf("Loading curv file %s\n",tmpstr);
    if (MRISreadCurvatureFile(surf2, tmpstr) != 0) {
      printf("ERROR: reading curvature file %s\n",tmpstr);
      exit(1);
    }
    error_count=0;
    for (nthvtx=0; nthvtx < surf1->nvertices; nthvtx++) {
      vtx1 = &(surf1->vertices[nthvtx]);
      vtx2 = &(surf2->vertices[nthvtx]);
      diff=fabs(vtx1->curv - vtx2->curv);
      if (diff>maxdiff) maxdiff=diff;
      if (diff > thresh) {
        printf("curv files differ at vertex %d %g %g\t(%g)\n",
               nthvtx,vtx1->curv,vtx2->curv,diff);
        if (++error_count>=MAX_NUM_ERRORS) break;
      }
    } // end loop over vertices
    if (maxdiff>0) printf("maxdiff=%g\n",maxdiff);
    if (error_count > 0) {
      printf("Exiting after finding %d errors\n",error_count);
      if (error_count>=MAX_NUM_ERRORS) {
        printf("Exceeded MAX_NUM_ERRORS loop guard\n");
      }
      exit(103);
    }
    printf("Curv files are the same\n");
    exit(0);
  } // end check curv

  // ---------------------------------------------------------
  if (CheckAParc) {
    printf("Checking AParc %s\n",aparcname);
    sprintf(tmpstr,"%s/%s/label/%s.%s.annot",
            SUBJECTS_DIR1,subject1,hemi,aparcname);
    printf("Loading aparc file %s\n",tmpstr);
    fflush(stdout);
    if (MRISreadAnnotation(surf1, tmpstr)) {
      printf("ERROR: MRISreadAnnotation() failed %s\n",tmpstr);
      exit(1);
    }
    if (aparc2name) aparcname = aparc2name;
    sprintf(tmpstr,"%s/%s/label/%s.%s.annot",
            SUBJECTS_DIR2,subject2,hemi,aparcname);
    printf("Loading aparc file %s\n",tmpstr);
    fflush(stdout);
    if (MRISreadAnnotation(surf2, tmpstr)) {
      printf("ERROR: MRISreadAnnotation() failed %s\n",tmpstr);
      exit(1);
    }
    error_count=0;
    for (nthvtx=0; nthvtx < surf1->nvertices; nthvtx++) {
      annot1 = surf1->vertices[nthvtx].annotation;
      annot2 = surf2->vertices[nthvtx].annotation;
      if (annot1 != annot2) {
        printf("aparc files differ at vertex %d: 1:%s 2:%s\n",
               nthvtx,
               CTABgetAnnotationName(surf1->ct,annot1),
               CTABgetAnnotationName(surf2->ct,annot2));
        if (++error_count>=MAX_NUM_ERRORS) break;
      }
    } // end loop over vertices
    if (error_count > 0) {
      printf("Exiting after finding %d errors\n",error_count);
      if (error_count>=MAX_NUM_ERRORS) {
        printf("Exceeded MAX_NUM_ERRORS loop guard\n");
      }
      exit(103);
    }
    printf("\n"
           "AParc files are the same\n"
           "------------------------\n");
    exit(0);
  }

  return 0;
}
示例#18
0
int
main(int argc, char *argv[])
{
  char         *gca_fname, *in_fname, *out_fname, **av, *xform_fname, fname[STRLEN] ;
  MRI          *mri_in, *mri_norm = NULL, *mri_tmp, *mri_ctrl = NULL ;
  GCA          *gca ;
  int          ac, nargs, nsamples, msec, minutes, seconds;
  int          i, struct_samples, norm_samples = 0, n, input, ninputs ;
  struct timeb start ;
  GCA_SAMPLE   *gcas, *gcas_norm = NULL, *gcas_struct ;
  TRANSFORM    *transform = NULL ;
  char         cmdline[CMD_LINE_LEN], line[STRLEN], *cp, subject[STRLEN], sdir[STRLEN], base_name[STRLEN] ;
  FILE         *fp ;

  make_cmd_version_string
    (argc, argv,
     "$Id: mri_cal_normalize.c,v 1.2.2.1 2011/08/31 00:32:41 nicks Exp $",
     "$Name: stable5 $", cmdline);

  /* rkt: check for and handle version tag */
  nargs = handle_version_option
    (argc, argv,
     "$Id: mri_cal_normalize.c,v 1.2.2.1 2011/08/31 00:32:41 nicks Exp $",
     "$Name: stable5 $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  setRandomSeed(-1L) ;
  Progname = argv[0] ;

  DiagInit(NULL, NULL, NULL) ;
  ErrorInit(NULL, NULL, NULL) ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++)
  {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (argc < 6)
    ErrorExit
      (ERROR_BADPARM,
       "usage: %s [<options>] <longitudinal time point file> <in vol> <atlas> <transform file> <out vol> \n",
       Progname) ;
  in_fname = argv[2] ;
  gca_fname = argv[3] ;
  xform_fname = argv[4] ;
  out_fname = argv[5] ;

  transform = TransformRead(xform_fname) ;
  if (transform == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read transform from %s", Progname, xform_fname) ;
  if (read_ctrl_point_fname)
  {
    mri_ctrl = MRIread(read_ctrl_point_fname) ;
    if (mri_ctrl == NULL)
      ErrorExit(ERROR_NOFILE, "%s: could not read precomputed control points from %s", 
                Progname, read_ctrl_point_fname) ;
  }
  TimerStart(&start) ;
  printf("reading atlas from '%s'...\n", gca_fname) ;
  fflush(stdout) ;

  gca = GCAread(gca_fname) ;
  if (gca == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not open GCA %s.\n",Progname, gca_fname) ;
  GCAregularizeConditionalDensities(gca, .5) ;

  FileNamePath(argv[1], sdir) ;
  cp = strrchr(sdir, '/') ; 
  if (cp)
  {
    strcpy(base_name, cp+1) ;
    *cp = 0 ;  // remove last component of path, which is base subject name
  }
  ninputs = 0 ;
  fp = fopen(argv[1], "r") ;
  if (fp == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read time point file %s", argv[1]) ;

  do
  {
    cp = fgetl(line, STRLEN-1, fp) ;
    if (cp != NULL && strlen(cp) > 0)
    {
      subjects[ninputs] = (char *)calloc(strlen(cp)+1, sizeof(char)) ;
      strcpy(subjects[ninputs], cp) ;
      ninputs++ ;
    }
  } while (cp != NULL && strlen(cp) > 0) ;
  fclose(fp) ;
  printf("processing %d timepoints in SUBJECTS_DIR %s...\n", ninputs, sdir) ;
  for (input = 0 ; input < ninputs ; input++)
  {
    sprintf(subject, "%s.long.%s", subjects[input], base_name) ;
    printf("reading subject %s - %d of %d\n", subject, input+1, ninputs) ;
    sprintf(fname, "%s/%s/mri/%s", sdir, subject, in_fname) ;
    mri_tmp = MRIread(fname) ;
    if (!mri_tmp)
      ErrorExit(ERROR_NOFILE, "%s: could not read input MR volume from %s",
                Progname, fname) ;
    MRImakePositive(mri_tmp, mri_tmp) ;
    if (mri_tmp && ctrl_point_fname && !mri_ctrl)
    {
      mri_ctrl = MRIallocSequence(mri_tmp->width, mri_tmp->height, 
                                  mri_tmp->depth,MRI_FLOAT, nregions*2) ; // labels and means
      MRIcopyHeader(mri_tmp, mri_ctrl) ;
    }
    if (input == 0)
    {
      mri_in =
        MRIallocSequence(mri_tmp->width, mri_tmp->height, mri_tmp->depth,
                         mri_tmp->type, ninputs) ;
      if (!mri_in)
        ErrorExit(ERROR_NOMEMORY,
                  "%s: could not allocate input volume %dx%dx%dx%d",
                  mri_tmp->width,mri_tmp->height,mri_tmp->depth,ninputs) ;
      MRIcopyHeader(mri_tmp, mri_in) ;
    }

    if (mask_fname)
    {
      int i ;
      MRI *mri_mask ;

      mri_mask = MRIread(mask_fname) ;
      if (!mri_mask)
        ErrorExit(ERROR_NOFILE, "%s: could not open mask volume %s.\n",
                  Progname, mask_fname) ;

      for (i = 1 ; i < WM_MIN_VAL ; i++)
        MRIreplaceValues(mri_mask, mri_mask, i, 0) ;
      MRImask(mri_tmp, mri_mask, mri_tmp, 0, 0) ;
      MRIfree(&mri_mask) ;
    }
    MRIcopyFrame(mri_tmp, mri_in, 0, input) ;
    MRIfree(&mri_tmp) ;
  }
  MRIaddCommandLine(mri_in, cmdline) ;

  GCAhistoScaleImageIntensitiesLongitudinal(gca, mri_in, 1) ;

  {
    int j ;

    gcas = GCAfindAllSamples(gca, &nsamples, NULL, 1) ;
    printf("using %d sample points...\n", nsamples) ;
    GCAcomputeSampleCoords(gca, mri_in, gcas, nsamples, transform) ;
    if (sample_fname)
      GCAtransformAndWriteSamples
        (gca, mri_in, gcas, nsamples, sample_fname, transform) ;

    for (j = 0 ; j < 1 ; j++)
    {
      for (n = 1 ; n <= nregions ; n++)
      {
        for (norm_samples = i = 0 ; i < NSTRUCTURES ; i++)
        {
          if (normalization_structures[i] == Gdiag_no)
            DiagBreak() ;
          printf("finding control points in %s....\n",
                 cma_label_to_name(normalization_structures[i])) ;
          gcas_struct = find_control_points(gca, gcas, nsamples, &struct_samples, n,
                                            normalization_structures[i], mri_in, transform, min_prior,
                                            ctl_point_pct) ;
          discard_unlikely_control_points(gca, gcas_struct, struct_samples, mri_in, transform,
                                          cma_label_to_name(normalization_structures[i])) ;
          if (mri_ctrl && ctrl_point_fname) // store the samples
            copy_ctrl_points_to_volume(gcas_struct, struct_samples, mri_ctrl, n-1) ;
          if (i)
          {
            GCA_SAMPLE *gcas_tmp ;
            gcas_tmp = gcas_concatenate(gcas_norm, gcas_struct, norm_samples, struct_samples) ;
            free(gcas_norm) ;
            norm_samples += struct_samples ;
            gcas_norm = gcas_tmp ;
          }
          else
          {
            gcas_norm = gcas_struct ; norm_samples = struct_samples ;
          }
        }
        
        printf("using %d total control points "
                 "for intensity normalization...\n", norm_samples) ;
        if (normalized_transformed_sample_fname)
          GCAtransformAndWriteSamples(gca, mri_in, gcas_norm, norm_samples,
                                      normalized_transformed_sample_fname,
                                      transform) ;
        mri_norm = GCAnormalizeSamplesAllChannels(mri_in, gca, gcas_norm, file_only ? 0 :norm_samples,
                                                  transform, ctl_point_fname, bias_sigma) ;
        if (Gdiag & DIAG_WRITE)
        {
          char fname[STRLEN] ;
          sprintf(fname, "norm%d.mgz", n) ;
          printf("writing normalized volume to %s...\n", fname) ;
          MRIwrite(mri_norm, fname) ;
          sprintf(fname, "norm_samples%d.mgz", n) ;
          GCAtransformAndWriteSamples(gca, mri_in, gcas_norm, norm_samples,
                                      fname, transform) ;
          
        }
        MRIcopy(mri_norm, mri_in) ;  /* for next pass through */
        MRIfree(&mri_norm) ;
      }
    }
  }

  // now do cross-time normalization to bring each timepoint closer to the mean at each location
  {
    MRI   *mri_frame1, *mri_frame2, *mri_tmp ;
    double rms_before, rms_after ;
    int    i ;

    mri_tmp = MRIcopy(mri_in, NULL) ;
    mri_frame1 = MRIcopyFrame(mri_in, NULL, 0, 0) ;
    mri_frame2 = MRIcopyFrame(mri_in, NULL, 1, 0) ;
    rms_before = MRIrmsDiff(mri_frame1, mri_frame2) ;
    printf("RMS before = %2.2f\n", rms_before) ;
    MRIfree(&mri_frame1) ; MRIfree(&mri_frame2) ;
    for (i = 50 ; i <= 50 ; i += 25)
    {
      MRIcopy(mri_tmp, mri_in) ;
      normalize_timepoints_with_samples(mri_in, gcas_norm, norm_samples, i) ;
      mri_frame1 = MRIcopyFrame(mri_in, NULL, 0, 0) ;
      mri_frame2 = MRIcopyFrame(mri_in, NULL, 1, 0) ;
      rms_after = MRIrmsDiff(mri_frame1, mri_frame2) ;
      MRIfree(&mri_frame1) ; MRIfree(&mri_frame2) ;
      printf("RMS after (%d) = %2.2f\n", i, rms_after) ;
    }
  }
  {
    MRI   *mri_frame1, *mri_frame2 ;
    double rms_after ;
    int    i ;

    mri_tmp = MRIcopy(mri_in, NULL) ;
    for (i = 10 ; i <= 10 ; i += 10)
    {
      MRIcopy(mri_tmp, mri_in) ;
      normalize_timepoints(mri_in, 2.0, i) ;
      mri_frame1 = MRIcopyFrame(mri_in, NULL, 0, 0) ;
      mri_frame2 = MRIcopyFrame(mri_in, NULL, 1, 0) ;
      rms_after = MRIrmsDiff(mri_frame1, mri_frame2) ;
      MRIfree(&mri_frame1) ; MRIfree(&mri_frame2) ;
      printf("RMS after intensity cohering = %2.2f\n", rms_after) ;
    }
  }

  for (input = 0 ; input < ninputs ; input++)
  {
    sprintf(fname, "%s/%s.long.%s/mri/%s", sdir, subjects[input], base_name, out_fname) ;
    printf("writing normalized volume to %s...\n", fname) ;
    if (MRIwriteFrame(mri_in, fname, input)  != NO_ERROR)
      ErrorExit(ERROR_BADFILE, "%s: could not write normalized volume to %s",Progname, fname);
  }

  if (ctrl_point_fname)
  {
    printf("writing control points to %s\n", ctrl_point_fname) ;
    MRIwrite(mri_ctrl, ctrl_point_fname) ;
    MRIfree(&mri_ctrl) ;
  }
  MRIfree(&mri_in) ;

  printf("freeing GCA...") ;
  if (gca)
    GCAfree(&gca) ;
  printf("done.\n") ;
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("normalization took %d minutes and %d seconds.\n",
         minutes, seconds) ;
  if (diag_fp)
    fclose(diag_fp) ;
  exit(0) ;
  return(0) ;
}
int
main(int argc, char *argv[])
{
  char         *in_fname, *out_fname, **av, *xform_fname, fname[STRLEN] ;
  MRI          *mri_in, *mri_tmp ;
  int          ac, nargs, msec, minutes, seconds;
  int          input, ninputs ;
  struct timeb start ;
  TRANSFORM    *transform = NULL ;
  char         cmdline[CMD_LINE_LEN], line[STRLEN], *cp, subject[STRLEN], sdir[STRLEN], base_name[STRLEN] ;
  FILE         *fp ;

  make_cmd_version_string
    (argc, argv,
     "$Id: mri_fuse_intensity_images.c,v 1.2 2011/06/02 14:05:10 fischl Exp $",
     "$Name:  $", cmdline);

  /* rkt: check for and handle version tag */
  nargs = handle_version_option
    (argc, argv,
     "$Id: mri_fuse_intensity_images.c,v 1.2 2011/06/02 14:05:10 fischl Exp $",
     "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  setRandomSeed(-1L) ;
  Progname = argv[0] ;

  DiagInit(NULL, NULL, NULL) ;
  ErrorInit(NULL, NULL, NULL) ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++)
  {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (argc < 5)
    ErrorExit
      (ERROR_BADPARM,
       "usage: %s [<options>] <longitudinal time point file> <in vol> <transform file> <out vol> \n",
       Progname) ;
  in_fname = argv[2] ;
  xform_fname = argv[3] ;
  out_fname = argv[4] ;

  transform = TransformRead(xform_fname) ;
  if (transform == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read transform from %s", Progname, xform_fname) ;
  TimerStart(&start) ;

  FileNamePath(argv[1], sdir) ;
  cp = strrchr(sdir, '/') ; 
  if (cp)
  {
    strcpy(base_name, cp+1) ;
    *cp = 0 ;  // remove last component of path, which is base subject name
  }
  ninputs = 0 ;
  fp = fopen(argv[1], "r") ;
  if (fp == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read time point file %s", Progname, argv[1]) ;

  do
  {
    cp = fgetl(line, STRLEN-1, fp) ;
    if (cp != NULL && strlen(cp) > 0)
    {
      subjects[ninputs] = (char *)calloc(strlen(cp)+1, sizeof(char)) ;
      strcpy(subjects[ninputs], cp) ;
      ninputs++ ;
    }
  } while (cp != NULL && strlen(cp) > 0) ;
  fclose(fp) ;
  printf("processing %d timepoints in SUBJECTS_DIR %s...\n", ninputs, sdir) ;
  for (input = 0 ; input < ninputs ; input++)
  {
    sprintf(subject, "%s.long.%s", subjects[input], base_name) ;
    printf("reading subject %s - %d of %d\n", subject, input+1, ninputs) ;
    sprintf(fname, "%s/%s/mri/%s", sdir, subject, in_fname) ;
    mri_tmp = MRIread(fname) ;
    if (!mri_tmp)
      ErrorExit(ERROR_NOFILE, "%s: could not read input MR volume from %s",
                Progname, fname) ;
    MRImakePositive(mri_tmp, mri_tmp) ;
    if (input == 0)
    {
      mri_in =
        MRIallocSequence(mri_tmp->width, mri_tmp->height, mri_tmp->depth,
                         mri_tmp->type, ninputs) ;
      if (!mri_in)
        ErrorExit(ERROR_NOMEMORY,
                  "%s: could not allocate input volume %dx%dx%dx%d",
                  mri_tmp->width,mri_tmp->height,mri_tmp->depth,ninputs) ;
      MRIcopyHeader(mri_tmp, mri_in) ;
    }

    if (mask_fname)
    {
      int i ;
      MRI *mri_mask ;

      mri_mask = MRIread(mask_fname) ;
      if (!mri_mask)
        ErrorExit(ERROR_NOFILE, "%s: could not open mask volume %s.\n",
                  Progname, mask_fname) ;

      for (i = 1 ; i < WM_MIN_VAL ; i++)
        MRIreplaceValues(mri_mask, mri_mask, i, 0) ;
      MRImask(mri_tmp, mri_mask, mri_tmp, 0, 0) ;
      MRIfree(&mri_mask) ;
    }
    MRIcopyFrame(mri_tmp, mri_in, 0, input) ;
    MRIfree(&mri_tmp) ;
  }
  MRIaddCommandLine(mri_in, cmdline) ;

  // try to bring the images closer to each other at each voxel where they seem to come from the same distribution
  {
    MRI   *mri_frame1, *mri_frame2 ;
    double rms_after ;

    mri_frame1 = MRIcopyFrame(mri_in, NULL, 0, 0) ;
    mri_frame2 = MRIcopyFrame(mri_in, NULL, 1, 0) ;
    rms_after = MRIrmsDiff(mri_frame1, mri_frame2) ;
    printf("RMS before intensity cohering  = %2.2f\n", rms_after) ;
    MRIfree(&mri_frame1) ; MRIfree(&mri_frame2) ; 
    if (0)
      normalize_timepoints(mri_in, 2.0, cross_time_sigma) ;
    else
      normalize_timepoints_with_parzen_window(mri_in, cross_time_sigma) ;
      
    mri_frame1 = MRIcopyFrame(mri_in, NULL, 0, 0) ;
    mri_frame2 = MRIcopyFrame(mri_in, NULL, 1, 0) ;
    rms_after = MRIrmsDiff(mri_frame1, mri_frame2) ;
    MRIfree(&mri_frame1) ; MRIfree(&mri_frame2) ;
    printf("RMS after intensity cohering  = %2.2f (sigma=%2.2f)\n", rms_after, cross_time_sigma) ;
  }

  for (input = 0 ; input < ninputs ; input++)
  {
    sprintf(fname, "%s/%s.long.%s/mri/%s", sdir, subjects[input], base_name, out_fname) ;
    printf("writing normalized volume to %s...\n", fname) ;
    if (MRIwriteFrame(mri_in, fname, input)  != NO_ERROR)
      ErrorExit(ERROR_BADFILE, "%s: could not write normalized volume to %s",Progname, fname);
  }

  MRIfree(&mri_in) ;

  printf("done.\n") ;
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("normalization took %d minutes and %d seconds.\n",
         minutes, seconds) ;
  if (diag_fp)
    fclose(diag_fp) ;
  exit(0) ;
  return(0) ;
}
示例#20
0
int
main(int argc, char *argv[]) {
  char          **av, *surf_fname, *profile_fname, *seg_fname ;
  int           ac, nargs ;
  MRI_SURFACE   *mris, *mris_ico = NULL ;
  // LABEL         *label = NULL ;
  MRI           *mri_profiles ;
  CLUSTER       *ct ;

  setRandomSeed(10L) ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mris_cluster_profiles.c,v 1.4 2011/03/02 00:04:34 nicks Exp $", "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (argc < 4)
    usage_exit() ;

  profile_fname = argv[1] ;
  surf_fname = argv[2] ;
  seg_fname = argv[3] ;
  mris = MRISread(surf_fname) ;
  if (!mris)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
              Progname, surf_fname) ;
  MRISsetNeighborhoodSize(mris, 2) ;

  if (MRISreadAnnotation(mris, "ad_aparc") != NO_ERROR) {
    if (MRISreadAnnotation(mris, "aparc") != NO_ERROR)
      ErrorExit(ERROR_NOFILE, "%s: could not read annotation file ad_aparc", Progname) ;
  }

  printf("reading intensity profile volume from %s...\n", profile_fname) ;
  mri_profiles = MRIread(profile_fname) ;
  if (!mri_profiles)
    ErrorExit(ERROR_NOFILE, "%s: could not read intensity volume %s",
              Progname, profile_fname) ;
  rip_vertices_out_of_fov(mris, mri_profiles) ;
  rip_bad_vertices(mris, mri_profiles) ;
  MRISclearAnnotations(mris) ;

#if 0
  if (nlabels > 0) {
    int l ;
    char label_name[STRLEN] ;
    LABEL *ltotal = NULL ;

    for (l = 0 ; l < nlabels ; l++) {
      sprintf(label_name, "%s/%s/label/%s.%s.label", sdir, sname, hemi,label_names[l]) ;

      label = LabelRead(NULL, label_name) ;
      if (!label)
        ErrorExit(ERROR_NOFILE, "%s: could not read label file %s...\n", Progname,
                  label_name) ;
      if (num_erode > 0) {
        printf("eroding label %d times, npoints went from %d ", num_erode,label->n_points) ;
        LabelErode(label, mris, num_erode) ;
        printf("to %d ", label->n_points) ;
      }
      ltotal = LabelCombine(label, ltotal) ;
    }
    if (nlabels == 0)
      ltotal = LabelInFOV(mris, mri, MIN_BORDER_DIST) ;

    LabelRipRestOfSurfaceWithThreshold(ltotal, mris, thresh) ;
  }
#endif

  if (navgs > 0) {
    printf("smoothing profiles %d times\n", navgs) ;
    MRISsmoothFrames(mris, mri_profiles, navgs) ;
  }
  if (ico_fname) {
    mris_ico = MRISread(ico_fname) ;
    if (mris_ico == NULL)
      ErrorExit(ERROR_BADPARM, "%s: could not read icosahedron from %s...\n", Progname, ico_fname) ;
  }
  ct = MRIScluster(mris, mri_profiles, cluster_type, k, start_fname, mris_ico) ;
  printf("writing cortical intensity clusters to %s...\n", seg_fname) ;
  MRISwriteAnnotation(mris, seg_fname) ;
  {
    int    vno ;
    VERTEX *v ;
    int    c, i ;
    char   fname[STRLEN], ext[STRLEN] ;

    // write average profiles into mri_profiles and write it out
    for (vno = 0 ; vno < mris->nvertices ; vno++) {
      v = &mris->vertices[vno] ;
      if (v->ripflag)
        continue ;
      c = v->curv ;
      if (c < 0)
        continue ;
      for (i = 0 ; i < mri_profiles->nframes ; i++)
        MRIsetVoxVal(mri_profiles, vno, 0, 0, i, VECTOR_ELT(ct[c].v_mean,i+1)) ;
    }
    FileNameExtension(seg_fname, ext) ;
    FileNameRemoveExtension(seg_fname, fname) ;
    strcat(fname, "_cluster_avg.mgz") ;
    printf("writing average cluster profiles to %s...\n", fname) ;
    MRIwrite(mri_profiles, fname) ;
  }

  MRIfree(&mri_profiles) ;

  exit(0) ;
  return(0) ;  /* for ansi */
}