コード例 #1
0
ファイル: Font.cpp プロジェクト: ezhangle/AtomicGameEngine
bool Font::BeginLoad(Deserializer& source)
{
    // In headless mode, do not actually load, just return success
    Graphics* graphics = GetSubsystem<Graphics>();
    if (!graphics)
        return true;

    fontType_ = FONT_NONE;
    faces_.Clear();

    fontDataSize_ = source.GetSize();
    if (fontDataSize_)
    {
        fontData_ = new unsigned char[fontDataSize_];
        if (source.Read(&fontData_[0], fontDataSize_) != fontDataSize_)
            return false;
    }
    else
    {
        fontData_.Reset();
        return false;
    }

    String ext = GetExtension(GetName());
    if (ext == ".ttf" || ext == ".otf" || ext == ".woff")
    {
        fontType_ = FONT_FREETYPE;
        LoadParameters();
    }
    else if (ext == ".xml" || ext == ".fnt" || ext == ".sdf")
        fontType_ = FONT_BITMAP;

    sdfFont_ = ext == ".sdf";

    SetMemoryUse(fontDataSize_);
    return true;
}
コード例 #2
0
ファイル: shooter.cpp プロジェクト: TechnoJays/robot2013
/**
 * \brief Initialize the Shooter object.
 *
 * Create member objects, initialize default values, read parameters from the param file.
 *
 * \param parameters shooter parameter file path and name.
 * \param logging_enabled true if logging is enabled.
*/
void Shooter::Initialize(char * parameters, bool logging_enabled) {
	// Initialize public member variables
	encoder_enabled_ = false;
	shooter_enabled_ = false;
	pitch_enabled_ = false;

	// Initialize private member objects
	shooter_controller_ = NULL;
	pitch_controller_ = NULL;
	encoder_ = NULL;
	timer_ = NULL;
	log_ = NULL;
	parameters_ = NULL;

	// Initialize private parameters
	invert_multiplier_ = 0.0;
	shooter_normal_speed_ratio_ = 1.0;
	pitch_normal_speed_ratio_ = 1.0;
	pitch_turbo_speed_ratio_ = 1.0;
	auto_far_speed_ratio_ = 1.0;
	auto_medium_speed_ratio_ = 1.0;
	auto_near_speed_ratio_ = 1.0;	
	auto_medium_encoder_threshold_ = 50;
	auto_far_encoder_threshold_ = 100;
	auto_medium_time_threshold_ = 0.5;
	auto_far_time_threshold_ = 1.0;
	encoder_threshold_ = 10;
	pitch_up_direction_ = 1.0;
	pitch_down_direction_ = -1.0;
	shoot_forward_direction_ = 1.0;
	shoot_backward_direction_ = -1.0;
	time_threshold_ = 0.1;
	encoder_max_limit_ = -1;
	encoder_min_limit_ = -1;
	shooter_min_power_speed_ = 0.4;
	shooter_power_adjustment_ratio_ = 0.006;
	angle_linear_fit_gradient_ = 1.0;
	angle_linear_fit_constant_ = 0.0;
	fulcrum_clear_encoder_count_ = 0;

	// Initialize private member variables
	encoder_count_ = 0;
	log_enabled_ = false;
	robot_state_ = kDisabled;
	ignore_encoder_limits_ = false;

	// Create a new data log object
	log_ = new DataLog("shooter.log");

	// Enable logging if specified
	if (log_ != NULL && log_->file_opened_) {
		log_enabled_ = logging_enabled;
	}
	else {
		log_enabled_ = false;
	}

	// Create a timer object
	timer_ = new Timer();
	
	// Attempt to read the parameters file
	strncpy(parameters_file_, parameters, sizeof(parameters_file_));

	LoadParameters();
}
コード例 #3
0
ファイル: main.c プロジェクト: JosephAtGMEMS/Rochchip_RK31
/*!
 This is main function.
 */
int main(int argc, char **argv)
{
	AK8963PRMS prms;
	int retValue = 0;
	AKMD_PATNO pat;
	int16 outbit;

	/* Show the version info of this software. */
	Disp_StartMessage();

#if ENABLE_AKMDEBUG
	/* Register signal handler */
	signal(SIGINT, signal_handler);
#endif

#if ENABLE_FORMATION
	RegisterFormClass(&s_formClass);
#endif

	/* Open device driver. */
	if (AKD_InitDevice() != AKD_SUCCESS) {
		retValue = ERROR_INITDEVICE;
		goto THE_END_OF_MAIN_FUNCTION;
	}

	/* Parse command-line options */
	if (OptParse(argc, argv, &pat, &outbit) == 0) {
		retValue = ERROR_OPTPARSE;
		goto THE_END_OF_MAIN_FUNCTION;
	}

	/* Initialize parameters structure. */
	InitAK8963PRMS(&prms);

	/* Put argument to PRMS. */
	prms.m_layout = pat;
	prms.m_outbit = outbit;

	/* Read Fuse ROM */
	if (ReadAK8963FUSEROM(&prms) != AKRET_PROC_SUCCEED) {
		retValue = ERROR_FUSEROM;
		goto THE_END_OF_MAIN_FUNCTION;
	}

	/* Here is the Main Loop */
	if (g_opmode) {
		/*** Console Mode *********************************************/
		while (AKD_TRUE) {
			/* Select operation */
			switch (Menu_Main()) {
				case MODE_FctShipmntTestBody:
					FctShipmntTest_Body(&prms);
					break;

				case MODE_MeasureSNG:
					/* Read Parameters from file. */
					if (LoadParameters(&prms) == 0) {
						SetDefaultPRMS(&prms);
					}
					/* Reset flag */
					g_stopRequest = 0;
					/* Measurement routine */
					MeasureSNGLoop(&prms);

					/* Write Parameters to file. */
					SaveParameters(&prms);
					break;

				case MODE_Quit:
					goto THE_END_OF_MAIN_FUNCTION;
					break;

				default:
					AKMDEBUG(DBG_LEVEL0, "Unknown operation mode.\n");
					break;
			}
		}
	} else {
		/*** Daemon Mode *********************************************/
		while (g_mainQuit == AKD_FALSE) {
			int st = 0;
			/* Wait until device driver is opened. */
			if (AKD_GetOpenStatus(&st) != AKD_SUCCESS) {
				retValue = ERROR_GETOPEN_STAT;
				goto THE_END_OF_MAIN_FUNCTION;
			}
			if (st == 0) {
				ALOGI("Suspended.");
			} else {
				ALOGI("Compass Opened.");
				/* Read Parameters from file. */
				if (LoadParameters(&prms) == 0) {
					SetDefaultPRMS(&prms);
				}
				/* Reset flag */
				g_stopRequest = 0;
				/* Start measurement thread. */
				if (startClone(&prms) == 0) {
					retValue = ERROR_STARTCLONE;
					goto THE_END_OF_MAIN_FUNCTION;
				}

				/* Wait until device driver is closed. */
				if (AKD_GetCloseStatus(&st) != AKD_SUCCESS) {
					retValue = ERROR_GETCLOSE_STAT;
					g_mainQuit = AKD_TRUE;
				}
				/* Wait thread completion. */
				g_stopRequest = 1;
				pthread_join(s_thread, NULL);
				ALOGI("Compass Closed.");

				/* Write Parameters to file. */
				SaveParameters(&prms);
			}
		}
	}

THE_END_OF_MAIN_FUNCTION:

	/* Close device driver. */
	AKD_DeinitDevice();

	/* Show the last message. */
	Disp_EndMessage(retValue);

	return retValue;
}
コード例 #4
0
ファイル: OGLTexture3D.cpp プロジェクト: codeman001/Urho3D
bool Texture3D::Load(Deserializer& source)
{
    PROFILE(LoadTexture3D);
    
    // In headless mode, do not actually load the texture, just return success
    if (!graphics_)
        return true;
    
    // If device is lost, retry later
    if (graphics_->IsDeviceLost())
    {
        LOGWARNING("Texture load while device is lost");
        dataPending_ = true;
        return true;
    }
    
    // If over the texture budget, see if materials can be freed to allow textures to be freed
    CheckTextureBudget(GetTypeStatic());

    // Before actually loading the texture, get optional parameters from an XML description file
    LoadParameters();

    String texPath, texName, texExt;
    SplitPath(GetName(), texPath, texName, texExt);
    
    SharedPtr<XMLFile> xml(new XMLFile(context_));
    if (!xml->Load(source))
        return false;

    XMLElement textureElem = xml->GetRoot();
    XMLElement volumeElem = textureElem.GetChild("volume");
    XMLElement colorlutElem = textureElem.GetChild("colorlut");

    if (volumeElem)
    {
        String name = volumeElem.GetAttribute("name");
        
        String volumeTexPath, volumeTexName, volumeTexExt;
        SplitPath(name, volumeTexPath, volumeTexName, volumeTexExt);
        // If path is empty, add the XML file path
        if (volumeTexPath.Empty())
            name = texPath + name;

        SharedPtr<Image> image(GetSubsystem<ResourceCache>()->GetResource<Image>(name));
        return Load(image);
    }
    else if (colorlutElem)
    {
        String name = colorlutElem.GetAttribute("name");
        
        String colorlutTexPath, colorlutTexName, colorlutTexExt;
        SplitPath(name, colorlutTexPath, colorlutTexName, colorlutTexExt);
        // If path is empty, add the XML file path
        if (colorlutTexPath.Empty())
            name = texPath + name;

        SharedPtr<File> file = GetSubsystem<ResourceCache>()->GetFile(name);
        SharedPtr<Image> image(new Image(context_));
        if (!image->LoadColorLUT(*(file.Get())))
            return false;

        return Load(image);
    }

    return false;
}
コード例 #5
0
void GibbsTrackingFilter< ItkQBallImageType >::GenerateData()
{
    TimeProbe preClock; preClock.Start();
    // check if input is qball or tensor image and generate qball if necessary
    if (m_QBallImage.IsNull() && m_TensorImage.IsNotNull())
    {
        TensorImageToQBallImageFilter<float,float>::Pointer filter = TensorImageToQBallImageFilter<float,float>::New();
        filter->SetInput( m_TensorImage );
        filter->Update();
        m_QBallImage = filter->GetOutput();
    }
    else if (m_DuplicateImage) // generate local working copy of QBall image (if not disabled)
    {
        typedef itk::ImageDuplicator< ItkQBallImageType > DuplicateFilterType;
        typename DuplicateFilterType::Pointer duplicator = DuplicateFilterType::New();
        duplicator->SetInputImage( m_QBallImage );
        duplicator->Update();
        m_QBallImage = duplicator->GetOutput();
    }

    // perform mean subtraction on odfs
    typedef ImageRegionIterator< ItkQBallImageType > InputIteratorType;
    InputIteratorType it(m_QBallImage, m_QBallImage->GetLargestPossibleRegion() );
    it.GoToBegin();
    while (!it.IsAtEnd())
    {
        itk::OrientationDistributionFunction<float, QBALL_ODFSIZE> odf(it.Get().GetDataPointer());
        float mean = odf.GetMeanValue();
        odf -= mean;
        it.Set(odf.GetDataPointer());
        ++it;
    }

    // check if mask image is given if it needs resampling
    PrepareMaskImage();

    // load parameter file
    LoadParameters();

    // prepare parameters
    float minSpacing;
    if(m_QBallImage->GetSpacing()[0]<m_QBallImage->GetSpacing()[1] && m_QBallImage->GetSpacing()[0]<m_QBallImage->GetSpacing()[2])
        minSpacing = m_QBallImage->GetSpacing()[0];
    else if (m_QBallImage->GetSpacing()[1] < m_QBallImage->GetSpacing()[2])
        minSpacing = m_QBallImage->GetSpacing()[1];
    else
        minSpacing = m_QBallImage->GetSpacing()[2];

    if(m_ParticleLength == 0)
        m_ParticleLength = 1.5*minSpacing;
    if(m_ParticleWidth == 0)
        m_ParticleWidth = 0.5*minSpacing;

    if(m_ParticleWeight == 0)
        EstimateParticleWeight();

    float alpha = log(m_EndTemperature/m_StartTemperature);
    m_Steps = m_Iterations/10000;
    if (m_Steps<10)
        m_Steps = 10;
    if (m_Steps>m_Iterations)
    {
        MITK_INFO << "GibbsTrackingFilter: not enough iterations!";
        m_AbortTracking = true;
    }
    if (m_CurvatureThreshold < mitk::eps)
        m_CurvatureThreshold = 0;
    unsigned long singleIts = (unsigned long)((1.0*m_Iterations) / (1.0*m_Steps));

    // seed random generators
    Statistics::MersenneTwisterRandomVariateGenerator::Pointer randGen = Statistics::MersenneTwisterRandomVariateGenerator::New();
    if (m_RandomSeed>-1)
        randGen->SetSeed(m_RandomSeed);
    else
        randGen->SetSeed();

    // load sphere interpolator to evaluate the ODFs
    SphereInterpolator* interpolator = new SphereInterpolator(m_LutPath);

    // handle lookup table not found cases
    if( !interpolator->IsInValidState() )
    {
      m_IsInValidState = false;
      m_AbortTracking = true;
      m_BuildFibers = false;
      mitkThrow() << "Unable to load lookup tables.";
    }
    // initialize the actual tracking components (ParticleGrid, Metropolis Hastings Sampler and Energy Computer)
    ParticleGrid* particleGrid;
    GibbsEnergyComputer* encomp;
    MetropolisHastingsSampler* sampler;
    try{
        particleGrid = new ParticleGrid(m_MaskImage, m_ParticleLength, m_ParticleGridCellCapacity);
        encomp = new GibbsEnergyComputer(m_QBallImage, m_MaskImage, particleGrid, interpolator, randGen);
        encomp->SetParameters(m_ParticleWeight,m_ParticleWidth,m_ConnectionPotential*m_ParticleLength*m_ParticleLength,m_CurvatureThreshold,m_InexBalance,m_ParticlePotential);
        sampler = new MetropolisHastingsSampler(particleGrid, encomp, randGen, m_CurvatureThreshold);
    }
    catch(...)
    {
        MITK_ERROR  << "Particle grid allocation failed. Not enough memory? Try to increase the particle length.";
        m_IsInValidState = false;
        m_AbortTracking = true;
        m_BuildFibers = false;
        return;
    }

    MITK_INFO << "----------------------------------------";
    MITK_INFO << "Iterations: " << m_Iterations;
    MITK_INFO << "Steps: " << m_Steps;
    MITK_INFO << "Particle length: " << m_ParticleLength;
    MITK_INFO << "Particle width: " << m_ParticleWidth;
    MITK_INFO << "Particle weight: " << m_ParticleWeight;
    MITK_INFO << "Start temperature: " << m_StartTemperature;
    MITK_INFO << "End temperature: " << m_EndTemperature;
    MITK_INFO << "In/Ex balance: " << m_InexBalance;
    MITK_INFO << "Min. fiber length: " << m_MinFiberLength;
    MITK_INFO << "Curvature threshold: " << m_CurvatureThreshold;
    MITK_INFO << "Random seed: " << m_RandomSeed;
    MITK_INFO << "----------------------------------------";

    // main loop
    preClock.Stop();
    TimeProbe clock; clock.Start();
    m_NumAcceptedFibers = 0;
    unsigned long counter = 1;

    boost::progress_display disp(m_Steps*singleIts);
    if (!m_AbortTracking)
    for( m_CurrentStep = 1; m_CurrentStep <= m_Steps; m_CurrentStep++ )
    {
        // update temperatur for simulated annealing process
        float temperature = m_StartTemperature * exp(alpha*(((1.0)*m_CurrentStep)/((1.0)*m_Steps)));
        sampler->SetTemperature(temperature);

        for (unsigned long i=0; i<singleIts; i++)
        {
            ++disp;
            if (m_AbortTracking)
                break;

            sampler->MakeProposal();

            if (m_BuildFibers || (i==singleIts-1 && m_CurrentStep==m_Steps))
            {
                m_ProposalAcceptance = (float)sampler->GetNumAcceptedProposals()/counter;
                m_NumParticles = particleGrid->m_NumParticles;
                m_NumConnections = particleGrid->m_NumConnections;

                FiberBuilder fiberBuilder(particleGrid, m_MaskImage);
                m_FiberPolyData = fiberBuilder.iterate(m_MinFiberLength);
                m_NumAcceptedFibers = m_FiberPolyData->GetNumberOfLines();
                m_BuildFibers = false;
            }
            counter++;
        }

        m_ProposalAcceptance = (float)sampler->GetNumAcceptedProposals()/counter;
        m_NumParticles = particleGrid->m_NumParticles;
        m_NumConnections = particleGrid->m_NumConnections;

        if (m_AbortTracking)
            break;
    }
    if (m_AbortTracking)
    {
        FiberBuilder fiberBuilder(particleGrid, m_MaskImage);
        m_FiberPolyData = fiberBuilder.iterate(m_MinFiberLength);
        m_NumAcceptedFibers = m_FiberPolyData->GetNumberOfLines();
    }
    clock.Stop();

    delete sampler;
    delete encomp;
    delete interpolator;
    delete particleGrid;
    m_AbortTracking = true;
    m_BuildFibers = false;

    int h = clock.GetTotal()/3600;
    int m = ((int)clock.GetTotal()%3600)/60;
    int s = (int)clock.GetTotal()%60;
    MITK_INFO << "GibbsTrackingFilter: finished gibbs tracking in " << h << "h, " << m << "m and " << s << "s";
    m = (int)preClock.GetTotal()/60;
    s = (int)preClock.GetTotal()%60;
    MITK_INFO << "GibbsTrackingFilter: preparation of the data took " << m << "m and " << s << "s";
    MITK_INFO << "GibbsTrackingFilter: " << m_NumAcceptedFibers << " fibers accepted";

//    sampler->PrintProposalTimes();

    SaveParameters();
}
コード例 #6
0
int main(int argc, char const *argv[]) {
  Eigen::setNbThreads(NumCores);
#ifdef MKL
  mkl_set_num_threads(NumCores);
#endif
  INFO("Eigen3 uses " << Eigen::nbThreads() << " threads.");
  int L;
  RealType J12ratio;
  int OBC;
  int N;
  RealType Uin, phi;
  std::vector<RealType> Vin;
  LoadParameters( "conf.h5", L, J12ratio, OBC, N, Uin, Vin, phi);
  HDF5IO file("BSSH.h5");
  // const int L = 5;
  // const bool OBC = true;
  // const RealType J12ratio = 0.010e0;
  INFO("Build Lattice - ");
  std::vector<ComplexType> J;
  if ( OBC ){
    J = std::vector<ComplexType>(L - 1, ComplexType(1.0, 0.0));
    for (size_t cnt = 0; cnt < L-1; cnt+=2) {
      J.at(cnt) *= J12ratio;
    }
  } else{
    J = std::vector<ComplexType>(L, ComplexType(1.0, 0.0));
    for (size_t cnt = 0; cnt < L; cnt+=2) {
      J.at(cnt) *= J12ratio;
    }
    if ( std::abs(phi) > 1.0e-10 ){
      J.at(L-1) *= exp( ComplexType(0.0e0, 1.0e0) * phi );
      // INFO(exp( ComplexType(0.0e0, 1.0e0) * phi ));
    }
  }
  for ( auto &val : J ){
    INFO_NONEWLINE(val << " ");
  }
  INFO("");
  const std::vector< Node<ComplexType>* > lattice = NN_1D_Chain(L, J, OBC);
  file.saveNumber("1DChain", "L", L);
  file.saveNumber("1DChain", "U", Uin);
  file.saveStdVector("1DChain", "J", J);
  for ( auto &lt : lattice ){
    if ( !(lt->VerifySite()) ) RUNTIME_ERROR("Wrong lattice setup!");
  }
  INFO("DONE!");
  INFO("Build Basis - ");
  // int N1 = (L+1)/2;
  Basis B1(L, N);
  B1.Boson();
  // std::vector< std::vector<int> > st = B1.getBStates();
  // std::vector< RealType > tg = B1.getBTags();
  // for (size_t cnt = 0; cnt < tg.size(); cnt++) {
  //   INFO_NONEWLINE( std::setw(3) << cnt << " - ");
  //   for (auto &j : st.at(cnt)){
  //     INFO_NONEWLINE(j << " ");
  //   }
  //   INFO("- " << tg.at(cnt));
  // }
  file.saveNumber("1DChain", "N", N);
  // file.saveStdVector("Basis", "States", st);
  // file.saveStdVector("Basis", "Tags", tg);
  INFO("DONE!");
  INFO_NONEWLINE("Build Hamiltonian - ");
  std::vector<Basis> Bases;
  Bases.push_back(B1);
  Hamiltonian<ComplexType> ham( Bases );
  std::vector< std::vector<ComplexType> > Vloc;
  std::vector<ComplexType> Vtmp;//(L, 1.0);
  for ( RealType &val : Vin ){
    Vtmp.push_back((ComplexType)val);
  }
  Vloc.push_back(Vtmp);
  std::vector< std::vector<ComplexType> > Uloc;
  // std::vector<ComplexType> Utmp(L, ComplexType(10.0e0, 0.0e0) );
  std::vector<ComplexType> Utmp(L, (ComplexType)Uin);
  Uloc.push_back(Utmp);
  ham.BuildLocalHamiltonian(Vloc, Uloc, Bases);
  ham.BuildHoppingHamiltonian(Bases, lattice);
  ham.BuildTotalHamiltonian();
  INFO("DONE!");
  INFO_NONEWLINE("Diagonalize Hamiltonian - ");
  std::vector<RealType> Val;
  Hamiltonian<ComplexType>::VectorType Vec;
  ham.eigh(Val, Vec);
  INFO("GS energy = " << Val.at(0));
  file.saveVector("GS", "EVec", Vec);
  file.saveStdVector("GS", "EVal", Val);
  INFO("DONE!");
  std::vector<ComplexType> Nbi = Ni( Bases, Vec );
  for (auto &n : Nbi ){
    INFO( n << " " );
  }
  ComplexMatrixType Nij = NiNj( Bases, Vec );
  INFO(Nij);
  INFO(Nij.diagonal());
  file.saveStdVector("Obs", "Nb", Nbi);
  file.saveMatrix("Obs", "Nij", Nij);
  return 0;
}
コード例 #7
0
void CommandlineInterface(vector<string> Arguments) {
	bool InputArgument = false;	
	vector<string> ParameterFiles;
	for (int i=0; i < int(Arguments.size()); i++) {
		if (Arguments[i].compare("inputfilelist") == 0) {
			if (int(Arguments.size()) >= i+2) {
				InputArgument = true;
				SetInputParametersFile(Arguments[i+1].data());
			}
		} if (Arguments[i].compare("parameterfile") == 0) {
			if (int(Arguments.size()) >= i+2) {
				ParameterFiles.push_back(Arguments[i+1].data());
				i++;
			}
		} 
	}
	if (!InputArgument) {
		SetInputParametersFile(COMMANDLINE_INPUT_FILE);
	}
	LoadParameters();
	for(int i=0; i < int(ParameterFiles.size()); i++) {
		LoadParameterFile(ParameterFiles[i]);
	}
	for (int i=0; i < int(Arguments.size()); i++) {
		if (Arguments[i].compare("resetparameter") == 0) {
			if (int(Arguments.size()) >= i+3) {
				string ParameterName = Arguments[i+1];
				findandreplace(ParameterName,"_"," ");
				SetParameter(ParameterName.data(),Arguments[i+2].data());		
			}
		} 
	}
	ClearParameterDependance("CLEAR ALL PARAMETER DEPENDANCE");
	if (Initialize() != SUCCESS) {
		return;
	}
	LoadFIGMODELParameters();
	ClearParameterDependance("CLEAR ALL PARAMETER DEPENDANCE");
	for (int i=0; i < int(Arguments.size()); i++) {
		if (Arguments[i].compare("stringcode") == 0) {
			if (int(Arguments.size()) < i+3) {
				cout << "Insufficient arguments" << endl;
				FErrorFile() << "Insufficient arguments" << endl;
				FlushErrorFile();
			} else {
				CreateStringCode(Arguments[i+1],Arguments[i+2]);
				i += 2;
			}
		} else if (Arguments[i].compare("LoadCentralSystem") == 0 || Arguments[i].compare("LoadDecentralSystem") == 0) {
			if (int(Arguments.size()) < i+2) {
				cout << "Insufficient arguments" << endl;
				FErrorFile() << "Insufficient arguments" << endl;
				FlushErrorFile();
			} else {
				LoadDatabaseFile(Arguments[i+1].data());		
			}
		} else if (Arguments[i].compare("ProcessDatabase") == 0) {
			ProcessDatabase();
		} else if (Arguments[i].compare("metabolites") == 0) {
			if (int(Arguments.size()) < i+2) {
				cout << "Insufficient arguments" << endl;
				FErrorFile() << "Insufficient arguments" << endl;
				FlushErrorFile();
			} else {
				SetParameter("metabolites to optimize",Arguments[i+1].data());		
			}
		} else if (Arguments[i].compare("WebGCM") == 0) {
			if (int(Arguments.size()) < i+3) {
				cout << "Insufficient arguments" << endl;
				FErrorFile() << "Insufficient arguments" << endl;
				FlushErrorFile();
			} else {
				RunWebGCM(Arguments[i+1].data(),Arguments[i+2].data());		
			}
		} else if (Arguments[i].compare("ProcessMolfiles") == 0) {
			if (int(Arguments.size()) < i+3) {
				cout << "Insufficient arguments" << endl;
				FErrorFile() << "Insufficient arguments" << endl;
				FlushErrorFile();
			} else {
				ProcessMolfileDirectory(Arguments[i+1].data(),Arguments[i+2].data());		
			}
		} else if (Arguments[i].compare("ProcessMolfileList") == 0) {
			ProcessMolfiles();
		}
	}
}
コード例 #8
0
ファイル: drivetrain.cpp プロジェクト: TechnoJays/robot2013
/**
 * \brief Initialize the DriveTrain object.
 *
 * Create member objects, initialize default values, read parameters from the param file.
 *
 * \param parameters drive train parameter file path and name.
 * \param logging_enabled true if logging is enabled.
*/
void DriveTrain::Initialize(const char * parameters, bool logging_enabled) {
	// Initialize public member variables
	gyro_enabled_ = false;
	accelerometer_enabled_ = false;

	// Initialize private member objects
	robot_drive_ = NULL;
	left_controller_ = NULL;
	right_controller_ = NULL;
	gyro_ = NULL;
	accelerometer_ = NULL;
	timer_ = NULL;
	acceleration_timer_ = NULL;
	log_ = NULL;
	parameters_ = NULL;

	
	// Initialize private parameters
	invert_multiplier_ = 0.0;
	normal_linear_speed_ratio_ = 1.0;
	turbo_linear_speed_ratio_ = 1.0;
	normal_turning_speed_ratio_ = 1.0;
	turbo_turning_speed_ratio_ = 1.0;
	auto_far_linear_speed_ratio_ = 1.0;
	auto_medium_linear_speed_ratio_ = 1.0;
	auto_near_linear_speed_ratio_ = 1.0;
	auto_far_turning_speed_ratio_ = 1.0;
	auto_medium_turning_speed_ratio_ = 1.0;
	auto_near_turning_speed_ratio_ = 1.0;
	auto_medium_time_threshold_ = 0.5;
	auto_far_time_threshold_ = 1.0;
	auto_medium_distance_threshold_ = 2.0;
	auto_far_distance_threshold_ = 5.0;
	auto_medium_heading_threshold_ = 15.0;
	auto_far_heading_threshold_ = 25.0;
	distance_threshold_ = 0.5;
	heading_threshold_ = 3.0;
	time_threshold_ = 0.1;
	forward_direction_ = 1.0;
	backward_direction_ = -1.0;
	left_direction_ = -1.0;
	right_direction_ = 1.0;
	left_motor_inverted_ = 0;
	right_motor_inverted_ = 0;
	accelerometer_axis_ = 0;
	maximum_linear_speed_change_ = 0.0;
	maximum_turn_speed_change_ = 0.0;
	linear_filter_constant_ = 0.0;
	turn_filter_constant_ = 0.0;
	
	// Initialize private member variables
	acceleration_ = 0.0;
	gyro_angle_ = 0.0;
	initial_heading_ = 0.0;
	adjustment_in_progress_ = false;
	distance_traveled_ = 0.0;
	log_enabled_ = false;
	robot_state_ = kDisabled;
	previous_linear_speed_ = 0.0;
	previous_turn_speed_ = 0.0;

		
	// Create a new data log object
	log_ = new DataLog("drivetrain.log");

	// Enable logging if specified
	if (log_ != NULL && log_->file_opened_) {
		log_enabled_ = logging_enabled;
	}
	else {
		log_enabled_ = false;
	}
	
	// Create a timer object
	timer_ = new Timer();

	// Attempt to read the parameters file
	strncpy(parameters_file_, parameters, sizeof(parameters_file_));

	LoadParameters();
}
コード例 #9
0
ファイル: main.c プロジェクト: JosephAtGMEMS/Rochchip_RK31
/* .! :
 This is main function.
 */
int main(int argc, char **argv)
{
	AK8975PRMS prms;
	int retValue = 0;
	int mainQuit = FALSE;
	int i;
	
	for (i = 1; i < argc; i++) {
		if (0 == strncmp("-s", argv[i], 2)) {
			s_opmode = 1;
		}
	}
	
#ifdef COMIF
	//// Initialize Library
	//// AKSC_Version functions are called in Disp_StartMessage().
	//// Therefore, AKSC_ActivateLibrary function has to be called previously.
	//retValue = AKSC_ActivateLibrary(GUID_AKSC);
	//if (retValue < 0) {
	//	LOGE("akmd2 : Failed to activate library (%d).\n", retValue);
	//	goto THE_END_OF_MAIN_FUNCTION;
	//}
	//LOGI("akmd2 : Activation succeeded (%d).\n", retValue);
#endif
	
	// Show the version info of this software.
	Disp_StartMessage();
	
	// Open device driver.
	if (AKD_InitDevice() != AKD_SUCCESS) {
		LOGE("akmd2 : Device initialization failed.\n");
		retValue = -1;
		goto THE_END_OF_MAIN_FUNCTION;
	}
	
	// Initialize parameters structure.
	InitAK8975PRMS(&prms);
	
	// Read Fuse ROM
	if (ReadAK8975FUSEROM(&prms) == 0) {
		LOGE("akmd2 : Fuse ROM read failed.\n");
		retValue = -2;
		goto THE_END_OF_MAIN_FUNCTION;
	}

	// Here is the Main Loop
	if (s_opmode) {
		//*** Console Mode *********************************************
		while (mainQuit == FALSE) {
			// Select operation
			switch (Menu_Main()) {
				case MODE_FctShipmntTestBody:
					FctShipmntTest_Body(&prms);
					break;
					
				case MODE_MeasureSNG:
					// Read Parameters from file.
					if (LoadParameters(&prms) == 0) {
						LOGE("akmd2 : Setting file can't be read.\n");
						SetDefaultPRMS(&prms);
					}
					
#ifdef COMIF
					//// Activation
					//retValue = AKSC_ActivateLibrary(GUID_AKSC);
					//if (retValue < 0) {
					//	LOGE("akmd2 : Failed to activate library (%d).\n", retValue);
					//	goto THE_END_OF_MAIN_FUNCTION;
					//}
					//LOGI("akmd2 : Activation succeeded (%d).\n", retValue);
#endif
					// Measurement routine
					MeasureSNGLoop(&prms);
					
					// Write Parameters to file.
					if (SaveParameters(&prms) == 0) {
						LOGE("akmd2 : Setting file can't be saved.\n");
					}
					break;
					
				case MODE_Quit:
					mainQuit = TRUE;
					break;
					
				default:
					DBGPRINT(DBG_LEVEL1, "Unknown operation mode.\n");
					break;
			}
		}
	} else {
		//*** Daemon Mode *********************************************
        I("AKMD runs in daemon mode.");
		while (mainQuit == FALSE) {
			int st = 0;
            // .! : 
			// Wait until device driver is opened.
			if (ioctl(g_file, ECS_IOCTL_GET_OPEN_STATUS, &st) < 0) {
				retValue = -3;
				goto THE_END_OF_MAIN_FUNCTION;
			}
			if (st == 0) {
				LOGI("akmd2 : Suspended.\n");
			} else {
				LOGI("akmd2 : Compass Opened.\n");
                V("m_hs : [%d, %d, %d].", (prms.m_hs).v[0], (prms.m_hs).v[1], (prms.m_hs).v[2] );
				// Read Parameters from file.
				if (LoadParameters(&prms) == 0) {
					LOGE("akmd2 : Setting file can't be read.\n");
					SetDefaultPRMS(&prms);
				}
                V("m_hs : [%d, %d, %d].", (prms.m_hs).v[0], (prms.m_hs).v[1], (prms.m_hs).v[2] );
				
#ifdef COMIF
				//// Activation
				//retValue = AKSC_ActivateLibrary(GUID_AKSC);
				//if (retValue < 0) {
				//	LOGE("akmd2 : Failed to activate library (%d).\n", retValue);
				//	retValue = -4;
				//	goto THE_END_OF_MAIN_FUNCTION;
				//}
				//LOGI("akmd2 : Activation succeeded (%d).\n", retValue);
#endif
				
                // .! : 
				// Start measurement thread.
				if (startClone(&prms) == 0) {
					retValue = -5;
					goto THE_END_OF_MAIN_FUNCTION;
				}
				
				// Wait until device driver is closed.
				if (ioctl(g_file, ECS_IOCTL_GET_CLOSE_STATUS, &st) < 0) {
					retValue = -6;
					goto THE_END_OF_MAIN_FUNCTION;
				}
				// Wait thread completion.
				s_stopRequest = 1;
				pthread_join(s_thread, NULL);
				LOGI("akmd2 : Compass Closed.\n");
				// Write Parameters to file.
				if (SaveParameters(&prms) == 0) {
					LOGE("akmd2 : Setting file can't be saved.\n");
				}
			}
		}
	}
	
THE_END_OF_MAIN_FUNCTION:
	
#ifdef COMIF
	//// Close library
	//AKSC_ReleaseLibrary(); 
	//LOGI("akmd2 : Library released.\n");
#endif
	
	// Close device driver.
	AKD_DeinitDevice();
	
	// Show the last message.
	Disp_EndMessage();
	
	return retValue;
}
コード例 #10
0
int main(int argc, char const *argv[]) {
  Eigen::setNbThreads(NumCores);
#ifdef MKL
  mkl_set_num_threads(NumCores);
#endif
  INFO("Eigen3 uses " << Eigen::nbThreads() << " threads.");
  int L;
  RealType J12ratio;
  int OBC;
  int N1, N2;
  int dynamics, Tsteps;
  RealType Uin, phi, dt;
  std::vector<RealType> Vin;
  LoadParameters( "conf.h5", L, J12ratio, OBC, N1, N2, Uin, Vin, phi, dynamics, Tsteps, dt);
  HDF5IO *file = new HDF5IO("FSSH.h5");
  // const int L = 5;
  // const bool OBC = true;
  // const RealType J12ratio = 0.010e0;
  INFO("Build Lattice - ");
  std::vector<DT> J;
  if ( OBC ){
    // J = std::vector<DT>(L - 1, 0.0);// NOTE: Atomic limit testing
    J = std::vector<DT>(L - 1, 1.0);
    if ( J12ratio > 1.0e0 ) {
      for (size_t cnt = 1; cnt < L-1; cnt+=2) {
        J.at(cnt) /= J12ratio;
      }
    } else{
      for (size_t cnt = 0; cnt < L-1; cnt+=2) {
        J.at(cnt) *= J12ratio;
      }
    }
  } else{
    J = std::vector<DT>(L, 1.0);
    if ( J12ratio > 1.0e0 ) {
      for (size_t cnt = 1; cnt < L; cnt+=2) {
        J.at(cnt) /= J12ratio;
      }
    } else{
      for (size_t cnt = 0; cnt < L; cnt+=2) {
        J.at(cnt) *= J12ratio;
      }
    }
#ifndef DTYPE
    if ( std::abs(phi) > 1.0e-10 ){
      J.at(L-1) *= exp( DT(0.0, 1.0) * phi );
    }
#endif
  }
  for ( auto &val : J ){
    INFO_NONEWLINE(val << " ");
  }
  INFO("");
  const std::vector< Node<DT>* > lattice = NN_1D_Chain(L, J, OBC);
  file->saveNumber("1DChain", "L", L);
  file->saveStdVector("1DChain", "J", J);
  for ( auto &lt : lattice ){
    if ( !(lt->VerifySite()) ) RUNTIME_ERROR("Wrong lattice setup!");
  }
  INFO("DONE!");
  INFO("Build Basis - ");
  // int N1 = (L+1)/2;
  Basis F1(L, N1, true);
  F1.Fermion();
  std::vector<int> st1 = F1.getFStates();
  std::vector<size_t> tg1 = F1.getFTags();
  // for (size_t cnt = 0; cnt < st1.size(); cnt++) {
  //   INFO_NONEWLINE( std::setw(3) << st1.at(cnt) << " - ");
  //   F1.printFermionBasis(st1.at(cnt));
  //   INFO("- " << tg1.at(st1.at(cnt)));
  // }
  // int N2 = (L-1)/2;
  Basis F2(L, N2, true);
  F2.Fermion();
  std::vector<int> st2 = F2.getFStates();
  std::vector<size_t> tg2 = F2.getFTags();
  // for (size_t cnt = 0; cnt < st2.size(); cnt++) {
  //   INFO_NONEWLINE( std::setw(3) << st2.at(cnt) << " - ");
  //   F2.printFermionBasis(st2.at(cnt));
  //   INFO("- " << tg2.at(st2.at(cnt)));
  // }
  file->saveNumber("Basis", "N1", N1);
  file->saveStdVector("Basis", "F1States", st1);
  file->saveStdVector("Basis", "F1Tags", tg1);
  file->saveNumber("Basis", "N2", N2);
  file->saveStdVector("Basis", "F2States", st2);
  file->saveStdVector("Basis", "F2Tags", tg2);
  INFO("DONE!");
  INFO_NONEWLINE("Build Hamiltonian - ");
  std::vector<Basis> Bases;
  Bases.push_back(F1);
  Bases.push_back(F2);
  Hamiltonian<DT> ham( Bases );
  std::vector< std::vector<DT> > Vloc;
  std::vector<DT> Vtmp;//(L, 1.0);
  for ( RealType &val : Vin ){
    Vtmp.push_back((DT)val);
  }
  Vloc.push_back(Vtmp);
  Vloc.push_back(Vtmp);
  std::vector< std::vector<DT> > Uloc;
  // std::vector<DT> Utmp(L, DT(10.0e0, 0.0e0) );
  std::vector<DT> Utmp(L, (DT)Uin);
  Uloc.push_back(Utmp);
  Uloc.push_back(Utmp);
  ham.BuildLocalHamiltonian(Vloc, Uloc, Bases);
  INFO(" - BuildLocalHamiltonian DONE!");
  ham.BuildHoppingHamiltonian(Bases, lattice);
  INFO(" - BuildHoppingHamiltonian DONE!");
  ham.BuildTotalHamiltonian();
  INFO("DONE!");
  INFO_NONEWLINE("Diagonalize Hamiltonian - ");
  std::vector<RealType> Val;
  Hamiltonian<DT>::VectorType Vec;
  ham.eigh(Val, Vec);
  INFO("GS energy = " << Val.at(0));
  file->saveVector("GS", "EVec", Vec);
  file->saveStdVector("GS", "EVal", Val);
  INFO("DONE!");
  std::vector< DTV > Nfi = Ni( Bases, Vec, ham );
  INFO(" Up Spin - ");
  INFO(Nfi.at(0));
  INFO(" Down Spin - ");
  INFO(Nfi.at(1));
  INFO(" N_i - ");
  DTV Niall = Nfi.at(0) + Nfi.at(1);
  INFO(Niall);
  DTM Nud = NupNdn( Bases, Vec, ham );
  INFO(" Correlation NupNdn");
  INFO(Nud);
  DTM Nuu = NupNup( Bases, Vec, ham );
  INFO(" Correlation NupNup");
  INFO(Nuu);
  DTM Ndd = NdnNdn( Bases, Vec, ham );
  INFO(" Correlation NdnNdn");
  INFO(Ndd);
  INFO(" N_i^2 - ");
  DTM Ni2 = Nuu.diagonal() + Ndd.diagonal() + 2.0e0 * Nud.diagonal();
  INFO(Ni2);
  file->saveVector("Obs", "Nup", Nfi.at(0));
  file->saveVector("Obs", "Ndn", Nfi.at(1));
  file->saveMatrix("Obs", "NupNdn", Nud);
  file->saveMatrix("Obs", "NupNup", Nuu);
  file->saveMatrix("Obs", "NdnNdn", Ndd);
  delete file;
  if ( dynamics ){
    ComplexType Prefactor = ComplexType(0.0, -1.0e0*dt);/* NOTE: hbar = 1 */
    std::cout << "Begin dynamics......" << std::endl;
    std::cout << "Cut the boundary." << std::endl;
    J.pop_back();
    std::vector< Node<DT>* > lattice2 = NN_1D_Chain(L, J, true);// cut to open
    ham.BuildHoppingHamiltonian(Bases, lattice2);
    INFO(" - Update Hopping Hamiltonian DONE!");
    ham.BuildTotalHamiltonian();
    INFO(" - Update Total Hamiltonian DONE!");
    for (size_t cntT = 1; cntT <= Tsteps; cntT++) {
      ham.expH(Prefactor, Vec);
      if ( cntT % 2 == 0 ){
        HDF5IO file2("DYN.h5");
        std::string gname = "Obs-";
        gname.append(std::to_string((unsigned long long)cntT));
        gname.append("/");
        Nfi = Ni( Bases, Vec, ham );
        Nud = NupNdn( Bases, Vec, ham );
        Nuu = NupNup( Bases, Vec, ham );
        Ndd = NdnNdn( Bases, Vec, ham );
        file2.saveVector(gname, "Nup", Nfi.at(0));
        file2.saveVector(gname, "Ndn", Nfi.at(1));
        file2.saveMatrix(gname, "NupNdn", Nud);
        file2.saveMatrix(gname, "NupNup", Nuu);
        file2.saveMatrix(gname, "NdnNdn", Ndd);
      }
    }
  }
  return 0;
}
コード例 #11
0
ファイル: LadspaEffect.cpp プロジェクト: dot-Sean/audio
bool LadspaEffect::SetHost(EffectHostInterface *host)
{
   mHost = host;

   if (!Load())
   {
      return false;
   }

   mInputPorts = new unsigned long [mData->PortCount];
   mOutputPorts = new unsigned long [mData->PortCount];
   mInputControls = new float [mData->PortCount];
   mOutputControls = new float [mData->PortCount];

   for (unsigned long p = 0; p < mData->PortCount; p++)
   {
      LADSPA_PortDescriptor d = mData->PortDescriptors[p];

      // Collect the audio ports
      if (LADSPA_IS_PORT_AUDIO(d))
      {
         if (LADSPA_IS_PORT_INPUT(d)) 
         {
            mInputPorts[mAudioIns++] = p;
         }
         else if (LADSPA_IS_PORT_OUTPUT(d))
         {
            mOutputPorts[mAudioOuts++] = p;
         }
      }
      // Determine the port's default value
      else if (LADSPA_IS_PORT_CONTROL(d) && LADSPA_IS_PORT_INPUT(d))
      {
         mInteractive = true;

         LADSPA_PortRangeHint hint = mData->PortRangeHints[p];
         float val = float(1.0);
         float lower = hint.LowerBound;
         float upper = hint.UpperBound;

         if (LADSPA_IS_HINT_SAMPLE_RATE(hint.HintDescriptor))
         {
            lower *= mSampleRate;
            upper *= mSampleRate;
         }

         if (LADSPA_IS_HINT_BOUNDED_BELOW(hint.HintDescriptor) && val < lower)
         {
            val = lower;
         }

         if (LADSPA_IS_HINT_BOUNDED_ABOVE(hint.HintDescriptor) && val > upper)
         {
            val = upper;
         }

         if (LADSPA_IS_HINT_DEFAULT_MINIMUM(hint.HintDescriptor))
         {
            val = lower;
         }

         if (LADSPA_IS_HINT_DEFAULT_MAXIMUM(hint.HintDescriptor))
         {
            val = upper;
         }

         if (LADSPA_IS_HINT_DEFAULT_LOW(hint.HintDescriptor))
         {
            if (LADSPA_IS_HINT_LOGARITHMIC(hint.HintDescriptor))
            {
               val = exp(log(lower)) * 0.75f + log(upper) * 0.25f;
            }
            else
            {
               val = lower * 0.75f + upper * 0.25f;
            }
         }

         if (LADSPA_IS_HINT_DEFAULT_MIDDLE(hint.HintDescriptor))
         {
            if (LADSPA_IS_HINT_LOGARITHMIC(hint.HintDescriptor))
            {
               val = exp(log(lower)) * 0.5f + log(upper) * 0.5f;
            }
            else
            {
               val = lower * 0.5f + upper * 0.5f;
            }
         }

         if (LADSPA_IS_HINT_DEFAULT_HIGH(hint.HintDescriptor))
         {
            if (LADSPA_IS_HINT_LOGARITHMIC(hint.HintDescriptor))
            {
               val = exp(log(lower)) * 0.25f + log(upper) * 0.75f;
            }
            else
            {
               val = lower * 0.25f + upper * 0.75f;
            }
         }

         if (LADSPA_IS_HINT_DEFAULT_0(hint.HintDescriptor))
         {
            val = 0.0f;
         }

         if (LADSPA_IS_HINT_DEFAULT_1(hint.HintDescriptor))
         {
            val = 1.0f;
         }

         if (LADSPA_IS_HINT_DEFAULT_100(hint.HintDescriptor))
         {
            val = 100.0f;
         }

         if (LADSPA_IS_HINT_DEFAULT_440(hint.HintDescriptor))
         {
            val = 440.0f;
         }

         mNumInputControls++;
         mInputControls[p] = val;
      }
      else if (LADSPA_IS_PORT_CONTROL(d) && LADSPA_IS_PORT_OUTPUT(d))
      {
         mInteractive = true;

         mNumOutputControls++;
         mOutputControls[p] = 0.0;
 
         // Ladspa effects have a convention of providing latency on an output
         // control port whose name is "latency".
         if (strcmp(mData->PortNames[p], "latency") == 0)
         {
            mLatencyPort = p;
         }
      }
   }

   // mHost will be null during registration
   if (mHost)
   {
      mHost->GetSharedConfig(wxT("Settings"), wxT("BufferSize"), mUserBlockSize, 8192);
      mBlockSize = mUserBlockSize;

      bool haveDefaults;
      mHost->GetPrivateConfig(wxT("Default"), wxT("Initialized"), haveDefaults, false);
      if (!haveDefaults)
      {
         SaveParameters(wxT("Default"));
         mHost->SetPrivateConfig(wxT("Default"), wxT("Initialized"), true);
      }

      LoadParameters(wxT("Current"));
   }

   return true;
}
コード例 #12
0
ファイル: LadspaEffect.cpp プロジェクト: dot-Sean/audio
void LadspaEffect::LoadFactoryDefaults()
{
   LoadParameters(mHost->GetFactoryDefaultsGroup());
}
コード例 #13
0
ファイル: LadspaEffect.cpp プロジェクト: dot-Sean/audio
void LadspaEffect::LoadUserPreset(const wxString & name)
{
   LoadParameters(name);
}
コード例 #14
0
ファイル: Experiment.cpp プロジェクト: AlexandreCampo/FaMouS
Experiment::Experiment (Simulator* simulator, bool graphics, string outputFilename, int replications, int replicationShift, string paramsFilename) :
    Service (simulator)
{
    // read params from file if available
    paramsExp = new ExperimentParameters;
    paramsCtrl = new ControllerDiscriminationParameters;
    if (!paramsFilename.empty()) LoadParameters (paramsFilename);

    // record replications count
    if (replications > 0) paramsExp->replications = replications;
    if (replicationShift > 0) paramsExp->replicationShift = replicationShift;
    currentReplication = replicationShift;

    // output file 
    if (!outputFilename.empty()) paramsExp->outputFilename = outputFilename;

    // random number generation
    init_rng(&rng);        

    // add services 
    physics = new PhysicsBullet(simulator, 10.0);
    simulator->Add (physics);
    
    render = NULL;
    if (graphics)
    {
	render = new RenderOpenGL(simulator);
	simulator->Add (render);

	float lookat[3] = {0,0,0.7 * physics->scalingFactor};
	float dab[3] = {4.0 * physics->scalingFactor, 90.0, 20.0};
	render->dsSetViewpoint2 (lookat, dab);
    }

    // add the experiment so that we can step regularly
    simulator->Add (this);
    

    // add robots
    for (int i = 0; i < paramsExp->robotsCount; i++)
    {
	RobotLily* r = new RobotLily ();
	r->Register(physics);
	if (render) r->Register(render);
	ControllerDiscrimination* c = new ControllerDiscrimination (r);
	c->SetParameters(paramsCtrl);
	robots.push_back(r);
	simulator->Add(r);   	
	
	// position is set in reset
    }

    // add base stations
    float a = 0.0;
    for (int i = 0; i < paramsExp->basestationsCount; i++)
    {
	BaseStation* b = new BaseStation ();
	b->Register (physics);
	if (render) b->Register (render);
	ControllerBaseStation* c = new ControllerBaseStation (b, i);	
	basestations.push_back(b);
	simulator->Add (b);
	
	float distance =  1.0 * physics->scalingFactor;
	float angle = a;
	float x = cos(angle) * distance;
	float y = sin(angle) * distance;
	float z = 1.0 * physics->scalingFactor + b->height / 2.0;
	b->SetPosition(x, y, z);

	a += 2.0 * M_PI / float (paramsExp->basestationsCount);
    }

    AquariumCircular* aquarium = new AquariumCircular(paramsExp->aquariumRadius * physics->scalingFactor,  1.0 * physics->scalingFactor, 1.0 * physics->scalingFactor, 40.0);
    aquarium->Register(physics);
    if (render) aquarium->Register(render);
    simulator->Add(aquarium);

    // set last stuff, position of robots mainly
    Reset();
}
コード例 #15
0
ファイル: main.c プロジェクト: JosephAtGMEMS/Rochchip_RK31
/*!
 This is main function.
 */
int main(int argc, char **argv)
{
	AKSCPRMS prms;
	int retValue = 0;

	/* Show the version info of this software. */
	Disp_StartMessage();

#if ENABLE_AKMDEBUG
	/* Register signal handler */
	signal(SIGINT, signal_handler);
#endif

#if ENABLE_FORMATION
	RegisterFormClass(&s_formClass);
#endif

	/* Initialize parameters structure. */
	InitAKSCPRMS(&prms);

	/* Parse command-line options */
	if (OptParse(argc, argv, &prms.m_hlayout) == 0) {
		retValue = ERROR_OPTPARSE;
		goto THE_END_OF_MAIN_FUNCTION;
	}

	/* Open device driver. */
	if (AKD_InitDevice() != AKD_SUCCESS) {
		retValue = ERROR_INITDEVICE;
		goto THE_END_OF_MAIN_FUNCTION;
	}

	/* If layout is not specified with argument, get parameter from driver */
	if (prms.m_hlayout == PAT_INVALID) {
		int16_t n;
		if (AKD_GetLayout(&n) == AKD_SUCCESS) {
			if ((PAT1 <= n) && (n <= PAT8)) {
				prms.m_hlayout = (AKMD_PATNO)n;
			}
		}
		/* Error */
		if (prms.m_hlayout == PAT_INVALID) {
			ALOGE("Magnetic sensor's layout is specified.");
			retValue = ERROR_HLAYOUT;
			goto THE_END_OF_MAIN_FUNCTION;
		}
	}

	/* Read Fuse ROM */
	if (ReadFUSEROM(&prms) != AKRET_PROC_SUCCEED) {
		retValue = ERROR_FUSEROM;
		goto THE_END_OF_MAIN_FUNCTION;
	}

	/* PDC */
	LoadPDC(&prms);

	/* Here is the Main Loop */
	if (g_opmode & OPMODE_CONSOLE) {
		/*** Console Mode *********************************************/
		while (AKD_TRUE) {
			/* Select operation */
			switch (Menu_Main()) {
				case MODE_FST:
					FST_Body();
					break;

				case MODE_MeasureSNG:
					/* Read Parameters from file. */
					if (LoadParameters(&prms) == 0) {
						SetDefaultPRMS(&prms);
					}
					/* Reset flag */
					g_stopRequest = 0;
					/* Measurement routine */
					MeasureSNGLoop(&prms);

					/* Write Parameters to file. */
					SaveParameters(&prms);
					break;

				case MODE_OffsetCalibration:
					/* Read Parameters from file. */
					if (LoadParameters(&prms) == 0) {
						SetDefaultPRMS(&prms);
					}
					/* measure offset (NOT sensitivity) */
					if (SimpleCalibration(&prms) == AKRET_PROC_SUCCEED) {
						SaveParameters(&prms);
					}
					break;

				case MODE_Quit:
					goto THE_END_OF_MAIN_FUNCTION;
					break;

				default:
					AKMDEBUG(AKMDBG_DEBUG, "Unknown operation mode.\n");
					break;
			}
		}
	} else {
		/*** Daemon Mode *********************************************/
		while (g_mainQuit == AKD_FALSE) {
			int st = 0;
			/* Wait until device driver is opened. */
			if (AKD_GetOpenStatus(&st) != AKD_SUCCESS) {
				retValue = ERROR_GETOPEN_STAT;
				goto THE_END_OF_MAIN_FUNCTION;
			}
			if (st == 0) {
				AKMDEBUG(AKMDBG_DEBUG, "Suspended.");
			} else {
				AKMDEBUG(AKMDBG_DEBUG, "Compass Opened.");
				/* Read Parameters from file. */
				if (LoadParameters(&prms) == 0) {
					SetDefaultPRMS(&prms);
				}
				/* Reset flag */
				g_stopRequest = 0;
				/* Start measurement thread. */
				if (startClone(&prms) == 0) {
					retValue = ERROR_STARTCLONE;
					goto THE_END_OF_MAIN_FUNCTION;
				}

				/* Wait until device driver is closed. */
				if (AKD_GetCloseStatus(&st) != AKD_SUCCESS) {
					retValue = ERROR_GETCLOSE_STAT;
					g_mainQuit = AKD_TRUE;
				}
				/* Wait thread completion. */
				g_stopRequest = 1;
				pthread_join(s_thread, NULL);
				AKMDEBUG(AKMDBG_DEBUG, "Compass Closed.");

				/* Write Parameters to file. */
				SaveParameters(&prms);
			}
		}
	}

THE_END_OF_MAIN_FUNCTION:

	/* Close device driver. */
	AKD_DeinitDevice();

	/* Show the last message. */
	Disp_EndMessage(retValue);

	return retValue;
}
コード例 #16
0
void performFit(string inputDir, string inputParameterFile, string label,
                string PassInputDataFilename, string FailInputDataFilename, 
                string PassSignalTemplateHistName, string FailSignalTemplateHistName)
{

  gBenchmark->Start("fitZCat");

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================
  
  const Double_t mlow  = 60;
  const Double_t mhigh = 120;
  const Int_t    nbins = 24;

  TString effType = inputDir;

  // The fit variable - lepton invariant mass
  RooRealVar* rooMass_ = new RooRealVar("Mass","m_{ee}",mlow, mhigh, "GeV/c^{2}");
  RooRealVar Mass = *rooMass_;
  Mass.setBins(nbins);

  // Make the category variable that defines the two fits,
  // namely whether the probe passes or fails the eff criteria.
  RooCategory sample("sample","") ;
  sample.defineType("Pass", 1) ;
  sample.defineType("Fail", 2) ; 


  RooDataSet *dataPass  = RooDataSet::read((inputDir+PassInputDataFilename).c_str(),RooArgList(Mass));
  RooDataSet *dataFail  = RooDataSet::read((inputDir+FailInputDataFilename).c_str(),RooArgList(Mass));

  RooDataSet *dataCombined = new RooDataSet("dataCombined","dataCombined", RooArgList(Mass), RooFit::Index(sample), 
                                            RooFit::Import("Pass",*dataPass),
                                            RooFit::Import("Fail",*dataFail));



  //*********************************************************************************************
  //Define Free Parameters
  //*********************************************************************************************
  RooRealVar* ParNumSignal =  LoadParameters(inputParameterFile, label,"ParNumSignal");
  RooRealVar* ParNumBkgPass =  LoadParameters(inputParameterFile, label,"ParNumBkgPass");
  RooRealVar* ParNumBkgFail =  LoadParameters(inputParameterFile, label, "ParNumBkgFail");
  RooRealVar* ParEfficiency  = LoadParameters(inputParameterFile, label, "ParEfficiency");
  RooRealVar* ParPassBackgroundExpCoefficient = LoadParameters(inputParameterFile, label, "ParPassBackgroundExpCoefficient");
  RooRealVar* ParFailBackgroundExpCoefficient = LoadParameters(inputParameterFile, label, "ParFailBackgroundExpCoefficient");
  RooRealVar* ParPassSignalMassShift = LoadParameters(inputParameterFile, label, "ParPassSignalMassShift");
  RooRealVar* ParFailSignalMassShift = LoadParameters(inputParameterFile, label, "ParFailSignalMassShift");
  RooRealVar* ParPassSignalResolution = LoadParameters(inputParameterFile, label, "ParPassSignalResolution");
  RooRealVar* ParFailSignalResolution = LoadParameters(inputParameterFile, label, "ParFailSignalResolution");



// new RooRealVar  ("ParPassSignalMassShift","ParPassSignalMassShift",-2.6079e-02,-10.0, 10.0);   //ParPassSignalMassShift->setConstant(kTRUE);  
//   RooRealVar* ParFailSignalMassShift = new RooRealVar  ("ParFailSignalMassShift","ParFailSignalMassShift",7.2230e-01,-10.0, 10.0);   //ParFailSignalMassShift->setConstant(kTRUE);  
//   RooRealVar* ParPassSignalResolution = new RooRealVar ("ParPassSignalResolution","ParPassSignalResolution",6.9723e-01,0.0, 10.0);     ParPassSignalResolution->setConstant(kTRUE);  
//   RooRealVar* ParFailSignalResolution = new RooRealVar ("ParFailSignalResolution","ParFailSignalResolution",1.6412e+00,0.0, 10.0);     ParFailSignalResolution->setConstant(kTRUE);  

  //*********************************************************************************************
  //
  //Load Signal PDFs
  //
  //*********************************************************************************************

  TFile *Zeelineshape_file =  new TFile("res/photonEfffromZee.dflag1.eT1.2.gT40.mt15.root", "READ");
  TH1* histTemplatePass = (TH1D*) Zeelineshape_file->Get(PassSignalTemplateHistName.c_str());
  TH1* histTemplateFail = (TH1D*) Zeelineshape_file->Get(FailSignalTemplateHistName.c_str());

  //Introduce mass shift coordinate transformation 
//   RooFormulaVar PassShiftedMass("PassShiftedMass","@0-@1",RooArgList(Mass,*ParPassSignalMassShift));
//   RooFormulaVar FailShiftedMass("FailShiftedMass","@0-@1",RooArgList(Mass,*ParFailSignalMassShift));

  RooGaussian  *PassSignalResolutionFunction =  new RooGaussian("PassSignalResolutionFunction","PassSignalResolutionFunction",Mass,*ParPassSignalMassShift,*ParPassSignalResolution);
  RooGaussian  *FailSignalResolutionFunction =  new RooGaussian("FailSignalResolutionFunction","FailSignalResolutionFunction",Mass,*ParFailSignalMassShift,*ParFailSignalResolution);


  RooDataHist* dataHistPass = new RooDataHist("dataHistPass","dataHistPass", RooArgSet(Mass), histTemplatePass);
  RooDataHist* dataHistFail = new RooDataHist("dataHistFail","dataHistFail", RooArgSet(Mass), histTemplateFail);
  RooHistPdf* signalShapePassTemplatePdf = new RooHistPdf("signalShapePassTemplatePdf", "signalShapePassTemplatePdf", Mass, *dataHistPass, 1);
  RooHistPdf* signalShapeFailTemplatePdf = new RooHistPdf("signalShapeFailTemplatePdf", "signalShapeFailTemplatePdf", Mass, *dataHistFail, 1);

  RooFFTConvPdf* signalShapePassPdf = new RooFFTConvPdf("signalShapePassPdf","signalShapePassPdf"  , Mass, *signalShapePassTemplatePdf,*PassSignalResolutionFunction,2);
  RooFFTConvPdf* signalShapeFailPdf = new RooFFTConvPdf("signalShapeFailPdf","signalShapeFailPdf"  , Mass, *signalShapeFailTemplatePdf,*FailSignalResolutionFunction,2);


  // Now define some efficiency/yield variables  
  RooFormulaVar* NumSignalPass = new RooFormulaVar("NumSignalPass", "ParEfficiency*ParNumSignal", RooArgList(*ParEfficiency,*ParNumSignal));
  RooFormulaVar* NumSignalFail = new RooFormulaVar("NumSignalFail", "(1.0-ParEfficiency)*ParNumSignal", RooArgList(*ParEfficiency,*ParNumSignal));


  //*********************************************************************************************
  //
  // Create Background PDFs
  //
  //*********************************************************************************************
  RooExponential* bkgPassPdf = new RooExponential("bkgPassPdf","bkgPassPdf",Mass, *ParPassBackgroundExpCoefficient);
  RooExponential* bkgFailPdf = new RooExponential("bkgFailPdf","bkgFailPdf",Mass, *ParFailBackgroundExpCoefficient);


 //*********************************************************************************************
  //
  // Create Total PDFs
  //
  //*********************************************************************************************
  RooAddPdf pdfPass("pdfPass","pdfPass",RooArgList(*signalShapePassPdf,*bkgPassPdf), RooArgList(*NumSignalPass,*ParNumBkgPass));
  RooAddPdf pdfFail("pdfFail","pdfFail",RooArgList(*signalShapeFailPdf,*bkgFailPdf), RooArgList(*NumSignalFail,*ParNumBkgFail));

  // PDF for simultaneous fit
   RooSimultaneous totalPdf("totalPdf","totalPdf", sample);
   totalPdf.addPdf(pdfPass,"Pass");
//    totalPdf.Print();
   totalPdf.addPdf(pdfFail,"Fail");
   totalPdf.Print();


   //*********************************************************************************************
  //
  // Perform Fit
  //
  //*********************************************************************************************
   RooFitResult *fitResult = 0;

  // ********* Fix with Migrad first ********** //  
   fitResult = totalPdf.fitTo(*dataCombined, RooFit::Save(true), 
                              RooFit::Extended(true), RooFit::PrintLevel(-1));
   fitResult->Print("v");


//   // ********* Fit With Minos ********** //  
//    fitResult = totalPdf.fitTo(*dataCombined, RooFit::Save(true), 
//                               RooFit::Extended(true), RooFit::PrintLevel(-1), RooFit::Minos());
//    fitResult->Print("v");




//   // ********* Fix Mass Shift and Fit For Resolution ********** //  
//    ParPassSignalMassShift->setConstant(kTRUE); 
//    ParFailSignalMassShift->setConstant(kTRUE); 
//    ParPassSignalResolution->setConstant(kFALSE); 
//    ParFailSignalResolution->setConstant(kFALSE); 
//    fitResult = totalPdf.fitTo(*dataCombined, RooFit::Save(true), 
//    RooFit::Extended(true), RooFit::PrintLevel(-1));
//    fitResult->Print("v");


//   // ********* Do Final Fit ********** //  
//    ParPassSignalMassShift->setConstant(kFALSE); 
//    ParFailSignalMassShift->setConstant(kFALSE); 
//    ParPassSignalResolution->setConstant(kTRUE); 
//    ParFailSignalResolution->setConstant(kTRUE); 
//    fitResult = totalPdf.fitTo(*dataCombined, RooFit::Save(true), 
//                                             RooFit::Extended(true), RooFit::PrintLevel(-1));
//    fitResult->Print("v");





  double nSignalPass = NumSignalPass->getVal();
  double nSignalFail    = NumSignalFail->getVal();
  double denominator = nSignalPass + nSignalFail;

  printf("\nFit results:\n");
  if( fitResult->status() != 0 ){
    std::cout<<"ERROR: BAD FIT STATUS"<<std::endl;
  }

  printf("    Efficiency = %.4f +- %.4f\n", 
	 ParEfficiency->getVal(), ParEfficiency->getPropagatedError(*fitResult));  
  cout << "Signal Pass: "******"Signal Fail: " << nSignalFail << endl;

  cout << "*********************************************************************\n";
  cout << "Final Parameters\n";
  cout << "*********************************************************************\n";
  PrintParameter(ParNumSignal, label,"ParNumSignal");
  PrintParameter(ParNumBkgPass, label,"ParNumBkgPass");
  PrintParameter(ParNumBkgFail, label, "ParNumBkgFail");
  PrintParameter(ParEfficiency  , label, "ParEfficiency");
  PrintParameter(ParPassBackgroundExpCoefficient , label, "ParPassBackgroundExpCoefficient");
  PrintParameter(ParFailBackgroundExpCoefficient , label, "ParFailBackgroundExpCoefficient");
  PrintParameter(ParPassSignalMassShift , label, "ParPassSignalMassShift");
  PrintParameter(ParFailSignalMassShift , label, "ParFailSignalMassShift");
  PrintParameter(ParPassSignalResolution , label, "ParPassSignalResolution");
  PrintParameter(ParFailSignalResolution , label, "ParFailSignalResolution");
  cout << endl << endl;


  //--------------------------------------------------------------------------------------------------------------
  // Make plots 
  //==============================================================================================================  
  TFile *canvasFile = new TFile("Efficiency_FitResults.root", "UPDATE");


  RooAbsData::ErrorType errorType = RooAbsData::Poisson;

  Mass.setBins(NBINSPASS);
  TString cname = TString((label+"_Pass").c_str());
  TCanvas *c = new TCanvas(cname,cname,800,600);
  RooPlot* frame1 = Mass.frame();
  frame1->SetMinimum(0);
  dataPass->plotOn(frame1,RooFit::DataError(errorType));
  pdfPass.plotOn(frame1,RooFit::ProjWData(*dataPass), 
  RooFit::Components(*bkgPassPdf),RooFit::LineColor(kRed));
  pdfPass.plotOn(frame1,RooFit::ProjWData(*dataPass));
  frame1->Draw("e0");
  
  TPaveText *plotlabel = new TPaveText(0.23,0.87,0.43,0.92,"NDC");
   plotlabel->SetTextColor(kBlack);
   plotlabel->SetFillColor(kWhite);
   plotlabel->SetBorderSize(0);
   plotlabel->SetTextAlign(12);
   plotlabel->SetTextSize(0.03);
   plotlabel->AddText("CMS Preliminary 2010");
  TPaveText *plotlabel2 = new TPaveText(0.23,0.82,0.43,0.87,"NDC");
   plotlabel2->SetTextColor(kBlack);
   plotlabel2->SetFillColor(kWhite);
   plotlabel2->SetBorderSize(0);
   plotlabel2->SetTextAlign(12);
   plotlabel2->SetTextSize(0.03);
   plotlabel2->AddText("#sqrt{s} = 7 TeV");
  TPaveText *plotlabel3 = new TPaveText(0.23,0.75,0.43,0.80,"NDC");
   plotlabel3->SetTextColor(kBlack);
   plotlabel3->SetFillColor(kWhite);
   plotlabel3->SetBorderSize(0);
   plotlabel3->SetTextAlign(12);
   plotlabel3->SetTextSize(0.03);
  char temp[100];
  sprintf(temp, "%.4f", LUMINOSITY);
  plotlabel3->AddText((string("#int#font[12]{L}dt = ") + 
  temp + string(" pb^{ -1}")).c_str());
  TPaveText *plotlabel4 = new TPaveText(0.6,0.82,0.8,0.87,"NDC");
   plotlabel4->SetTextColor(kBlack);
   plotlabel4->SetFillColor(kWhite);
   plotlabel4->SetBorderSize(0);
   plotlabel4->SetTextAlign(12);
   plotlabel4->SetTextSize(0.03);
   double nsig = ParNumSignal->getVal();
   double nErr = ParNumSignal->getError();
   double e = ParEfficiency->getVal();
   double eErr = ParEfficiency->getError();
   double corr = fitResult->correlation(*ParEfficiency, *ParNumSignal);
   double err = ErrorInProduct(nsig, nErr, e, eErr, corr);
   sprintf(temp, "Signal = %.2f #pm %.2f", NumSignalPass->getVal(), err);
   plotlabel4->AddText(temp);
   TPaveText *plotlabel5 = new TPaveText(0.6,0.77,0.8,0.82,"NDC");
   plotlabel5->SetTextColor(kBlack);
   plotlabel5->SetFillColor(kWhite);
   plotlabel5->SetBorderSize(0);
   plotlabel5->SetTextAlign(12);
   plotlabel5->SetTextSize(0.03);
   sprintf(temp, "Bkg = %.2f #pm %.2f", ParNumBkgPass->getVal(), ParNumBkgPass->getError());
   plotlabel5->AddText(temp);
   TPaveText *plotlabel6 = new TPaveText(0.6,0.87,0.8,0.92,"NDC");
   plotlabel6->SetTextColor(kBlack);
   plotlabel6->SetFillColor(kWhite);
   plotlabel6->SetBorderSize(0);
   plotlabel6->SetTextAlign(12);
   plotlabel6->SetTextSize(0.03);
   plotlabel6->AddText("Passing probes");
   TPaveText *plotlabel7 = new TPaveText(0.6,0.72,0.8,0.77,"NDC");
   plotlabel7->SetTextColor(kBlack);
   plotlabel7->SetFillColor(kWhite);
   plotlabel7->SetBorderSize(0);
   plotlabel7->SetTextAlign(12);
   plotlabel7->SetTextSize(0.03); 
   sprintf(temp, "Eff = %.3f #pm %.3f", ParEfficiency->getVal(), ParEfficiency->getErrorHi());
   plotlabel7->AddText(temp);
   TPaveText *plotlabel8 = new TPaveText(0.6,0.72,0.8,0.66,"NDC");
   plotlabel8->SetTextColor(kBlack);
   plotlabel8->SetFillColor(kWhite);
   plotlabel8->SetBorderSize(0);
   plotlabel8->SetTextAlign(12);
   plotlabel8->SetTextSize(0.03);
   sprintf(temp, "#chi^{2}/DOF = %.3f", frame1->chiSquare());
   plotlabel8->AddText(temp);

  plotlabel4->Draw();
  plotlabel5->Draw();
  plotlabel6->Draw();
  plotlabel7->Draw();
  plotlabel8->Draw();

//   c->SaveAs( cname + TString(".eps"));
  c->SaveAs( cname + TString(".gif"));
  canvasFile->WriteTObject(c, c->GetName(), "WriteDelete");

 
  Mass.setBins(NBINSFAIL);
  cname = TString((label+"_Fail").c_str());
  TCanvas* c2 = new TCanvas(cname,cname,800,600);
  RooPlot* frame2 = Mass.frame();
  frame2->SetMinimum(0);
  dataFail->plotOn(frame2,RooFit::DataError(errorType));
  pdfFail.plotOn(frame2,RooFit::ProjWData(*dataFail), 
  RooFit::Components(*bkgFailPdf),RooFit::LineColor(kRed));
  pdfFail.plotOn(frame2,RooFit::ProjWData(*dataFail));
  frame2->Draw("e0");

  plotlabel = new TPaveText(0.23,0.87,0.43,0.92,"NDC");
   plotlabel->SetTextColor(kBlack);
   plotlabel->SetFillColor(kWhite);
   plotlabel->SetBorderSize(0);
   plotlabel->SetTextAlign(12);
   plotlabel->SetTextSize(0.03);
   plotlabel->AddText("CMS Preliminary 2010");
 plotlabel2 = new TPaveText(0.23,0.82,0.43,0.87,"NDC");
   plotlabel2->SetTextColor(kBlack);
   plotlabel2->SetFillColor(kWhite);
   plotlabel2->SetBorderSize(0);
   plotlabel2->SetTextAlign(12);
   plotlabel2->SetTextSize(0.03);
   plotlabel2->AddText("#sqrt{s} = 7 TeV");
  plotlabel3 = new TPaveText(0.23,0.75,0.43,0.80,"NDC");
   plotlabel3->SetTextColor(kBlack);
   plotlabel3->SetFillColor(kWhite);
   plotlabel3->SetBorderSize(0);
   plotlabel3->SetTextAlign(12);
   plotlabel3->SetTextSize(0.03);
   sprintf(temp, "%.4f", LUMINOSITY);
   plotlabel3->AddText((string("#int#font[12]{L}dt = ") + 
                        temp + string(" pb^{ -1}")).c_str());
   plotlabel4 = new TPaveText(0.6,0.82,0.8,0.87,"NDC");
   plotlabel4->SetTextColor(kBlack);
   plotlabel4->SetFillColor(kWhite);
   plotlabel4->SetBorderSize(0);
   plotlabel4->SetTextAlign(12);
   plotlabel4->SetTextSize(0.03);
   err = ErrorInProduct(nsig, nErr, 1.0-e, eErr, corr);
   sprintf(temp, "Signal = %.2f #pm %.2f", NumSignalFail->getVal(), err);
   plotlabel4->AddText(temp);
   plotlabel5 = new TPaveText(0.6,0.77,0.8,0.82,"NDC");
   plotlabel5->SetTextColor(kBlack);
   plotlabel5->SetFillColor(kWhite);
   plotlabel5->SetBorderSize(0);
   plotlabel5->SetTextAlign(12);
   plotlabel5->SetTextSize(0.03);
   sprintf(temp, "Bkg = %.2f #pm %.2f", ParNumBkgFail->getVal(), ParNumBkgFail->getError());
   plotlabel5->AddText(temp);
   plotlabel6 = new TPaveText(0.6,0.87,0.8,0.92,"NDC");
   plotlabel6->SetTextColor(kBlack);
   plotlabel6->SetFillColor(kWhite);
   plotlabel6->SetBorderSize(0);
   plotlabel6->SetTextAlign(12);
   plotlabel6->SetTextSize(0.03);
   plotlabel6->AddText("Failing probes");
   plotlabel7 = new TPaveText(0.6,0.72,0.8,0.77,"NDC");
   plotlabel7->SetTextColor(kBlack);
   plotlabel7->SetFillColor(kWhite);
   plotlabel7->SetBorderSize(0);
   plotlabel7->SetTextAlign(12);
   plotlabel7->SetTextSize(0.03);
   sprintf(temp, "Eff = %.3f #pm %.3f", ParEfficiency->getVal(), ParEfficiency->getErrorHi(), ParEfficiency->getErrorLo());
   plotlabel7->AddText(temp);
   plotlabel8 = new TPaveText(0.6,0.72,0.8,0.66,"NDC");
   plotlabel8->SetTextColor(kBlack);
   plotlabel8->SetFillColor(kWhite);
   plotlabel8->SetBorderSize(0);
   plotlabel8->SetTextAlign(12);
   plotlabel8->SetTextSize(0.03);
   sprintf(temp, "#chi^{2}/DOF = %.3f", frame2->chiSquare());
   plotlabel8->AddText(temp);

//   plotlabel->Draw();
//   plotlabel2->Draw();
//   plotlabel3->Draw();
  plotlabel4->Draw();
  plotlabel5->Draw();
  plotlabel6->Draw();
  plotlabel7->Draw();
  plotlabel8->Draw();

  c2->SaveAs( cname + TString(".gif"));
//   c2->SaveAs( cname + TString(".eps"));
//   c2->SaveAs( cname + TString(".root"));
  canvasFile->WriteTObject(c2, c2->GetName(), "WriteDelete");

  canvasFile->Close();

  
  effTextFile.width(40);
  effTextFile << label;
  effTextFile.width(20);
  effTextFile  << setiosflags(ios::fixed) << setprecision(4) << left << ParEfficiency->getVal() ;
  effTextFile.width(20);
  effTextFile  << left << ParEfficiency->getErrorHi();
  effTextFile.width(20);
  effTextFile  << left << ParEfficiency->getErrorLo();
  effTextFile.width(14);
  effTextFile  << setiosflags(ios::fixed) << setprecision(2) << left << nSignalPass ;
  effTextFile.width(14);
  effTextFile << left << nSignalFail << endl;

}