void LoadParameters() { std::wifstream infile(SettingsFileName); if (infile.fail()) { SetDefaultParameters(); SaveParameters(); } else { TCHAR paramName[MAX_DATASTRING]; infile >> paramName; infile >> PhysicalDrive; int mode; infile >> paramName; infile >> mode; switch (mode) { case LowPower: case Standby: case NoStandby: case HighPerf: PMode = (PowerMode) mode; break; default: ErrorLog(L"Input file settings is bad!"); SetDefaultParameters(); SaveParameters(); } infile.close(); } }
bool celHNavStruct::SaveToFile (iVFS* vfs, const char* directory) { csRef<iDocumentSystem> docsys = csLoadPluginCheck<iDocumentSystem>(objectRegistry, "crystalspace.documentsystem.tinyxml"); if (!docsys) { return false; } csString workingDir(vfs->GetCwd()); vfs->ChDir(directory); // Create XML file csRef<iDocument> doc = docsys->CreateDocument(); csRef<iDocumentNode> root = doc->CreateRoot(); csRef<iDocumentNode> mainNode = root->CreateNodeBefore(CS_NODE_ELEMENT); mainNode->SetValue("iCelHNavStruct"); // Create parameters subtree csRef<iDocumentNode> params = mainNode->CreateNodeBefore(CS_NODE_ELEMENT); params->SetValue("parameters"); SaveParameters(params); // Create navmeshes subtree csRef<iDocumentNode> navmeshes = mainNode->CreateNodeBefore(CS_NODE_ELEMENT); navmeshes->SetValue("navmeshes"); SaveNavMeshes(navmeshes, vfs); // Create highlevelgraph subtree csRef<iDocumentNode> hlgraph = mainNode->CreateNodeBefore(CS_NODE_ELEMENT); hlgraph->SetValue("highlevelgraph"); csRef<iDocumentNode> nodes = hlgraph->CreateNodeBefore(CS_NODE_ELEMENT); nodes->SetValue("nodes"); csRef<iDocumentNode> edges = hlgraph->CreateNodeBefore(CS_NODE_ELEMENT); edges->SetValue("edges"); SaveHighLevelGraph(nodes, edges); // Write xml file const char* log = doc->Write(vfs, "navstruct.xml"); vfs->ChDir(workingDir.GetDataSafe()); vfs->Sync(); if (log) { return false; } return true; }
int main(int argc, char *argv[]) { int nDataVals, nStoredDataVals, nSavedRows; int nPixels_psf; int startDataRow, endDataRow; int nParamsTot, nFreeParams; int nDegFreedom; double *xVals, *yVals, *yWeights, *maskVals; double *xVals_psf, *yVals_psf; int weightMode = WEIGHTS_ARE_SIGMAS; FILE *outputFile_ptr; ModelObject *theModel; double *paramsVect; double *paramErrs; vector<mp_par> paramLimits; vector<int> FunctionBlockIndices; bool maskAllocated = false; bool paramLimitsExist = false; vector<mp_par> parameterInfo; int status, fitStatus; vector<string> functionList; vector<double> parameterList; commandOptions options; configOptions userConfigOptions; SolverResults resultsFromSolver; string nloptSolverName; vector<string> programHeader; string progNameVersion = "profilefit "; /* PROCESS COMMAND-LINE: */ /* First, set up the options structure: */ options.configFileName = DEFAULT_CONFIG_FILE; options.dataFileName = ""; options.modelOutputFileName = DEFAULT_MODEL_OUTPUT_FILE; options.noDataFile = true; options.noConfigFile = true; options.psfPresent = false; options.dataAreMagnitudes = true; // default: assumes we usually fit mu(R) profiles options.zeroPoint = 0.0; options.startDataRow = 0; options.endDataRow = -1; // default value indicating "last row in data file" options.noErrors = true; options.noMask = true; options.maskFormat = MASK_ZERO_IS_GOOD; options.ftol = DEFAULT_FTOL; options.ftolSet = false; options.printChiSquaredOnly = false; options.solver = MPFIT_SOLVER; options.nloptSolverName = "NM"; // default value = Nelder-Mead Simplex options.doBootstrap = false; options.bootstrapIterations = 0; options.subsamplingFlag = false; options.saveBestProfile = false; options.saveBestFitParams = true; options.outputParameterFileName = DEFAULT_1D_OUTPUT_PARAMETER_FILE; options.verbose = 1; options.nloptSolverName = ""; options.rngSeed = 0; progNameVersion += VERSION_STRING; MakeOutputHeader(&programHeader, progNameVersion, argc, argv); ProcessInput(argc, argv, &options); if (options.noDataFile) { printf("*** WARNING: No data to fit!\n\n"); return -1; } /* Read configuration file */ if (! FileExists(options.configFileName.c_str())) { printf("\n*** WARNING: Unable to find or open configuration file \"%s\"!\n\n", options.configFileName.c_str()); return -1; } status = ReadConfigFile(options.configFileName, false, functionList, parameterList, paramLimits, FunctionBlockIndices, paramLimitsExist, userConfigOptions); if (status < 0) { printf("\n*** WARNING: Problem in processing config file!\n\n"); return -1; } /* GET THE DATA: */ nDataVals = CountDataLines(options.dataFileName); if ((nDataVals < 1) || (nDataVals > MAX_N_DATA_VALS)) { /* file has no data *or* too much data (or an integer overflow occured in CountDataLines) */ printf("Something wrong: input file %s has too few or too many data points\n", options.dataFileName.c_str()); printf("(nDataVals = %d)\n", nDataVals); exit(1); } printf("Data file \"%s\": %d data points\n", options.dataFileName.c_str(), nDataVals); /* Set default end data row (if not specified) and check for reasonable values: */ startDataRow = options.startDataRow; endDataRow = options.endDataRow; if (endDataRow == -1) endDataRow = nDataVals - 1; if ( (startDataRow < 0) || (startDataRow >= nDataVals) ) { printf("Starting data row (\"--x1\") must be >= 1 and <= number of rows in data file (%d)!\n", nDataVals); exit(-1); } if ( (endDataRow <= startDataRow) || (endDataRow >= nDataVals) ) { printf("Ending data row (\"--x2\") must be >= starting data row and <= number of rows in data file (%d)!\n", nDataVals); exit(-1); } /* Allocate data vectors: */ nStoredDataVals = endDataRow - startDataRow + 1; xVals = (double *)calloc( (size_t)nStoredDataVals, sizeof(double) ); yVals = (double *)calloc( (size_t)nStoredDataVals, sizeof(double) ); if ( (xVals == NULL) || (yVals == NULL) ) { fprintf(stderr, "\nFailure to allocate memory for input data!\n"); exit(-1); } if (options.noErrors) yWeights = NULL; else yWeights = (double *)calloc( (size_t)nStoredDataVals, sizeof(double) ); if (options.noMask) maskVals = NULL; else { maskVals = (double *)calloc( (size_t)nStoredDataVals, sizeof(double) ); maskAllocated = true; } /* Read in data */ nSavedRows = ReadDataFile(options.dataFileName, startDataRow, endDataRow, xVals, yVals, yWeights, maskVals); if (nSavedRows > nStoredDataVals) { fprintf(stderr, "\nMore data rows saved (%d) than we allocated space for (%d)!\n", nSavedRows, nStoredDataVals); exit(-1); } if (options.noErrors) { // OK, we previously had yWeights = NULL to tell ReadDataFile() to skip // the third column (if any); now we need to have a yWeights vector with // all weights = 1.0 yWeights = (double *)calloc( (size_t)nStoredDataVals, sizeof(double) ); for (int i = 0; i < nStoredDataVals; i++) yWeights[i] = 1.0; } /* Read in PSF profile, if supplied */ if (options.psfPresent) { nPixels_psf = CountDataLines(options.psfFileName); if ((nPixels_psf < 1) || (nPixels_psf > MAX_N_DATA_VALS)) { /* file has no data *or* too much data (or an integer overflow occured in CountDataLines) */ printf("Something wrong: input PSF file %s has too few or too many data points\n", options.psfFileName.c_str()); printf("(nPixels_psf (# of PSF points) = %d)\n", nPixels_psf); exit(1); } printf("PSF file \"%s\": %d data points\n", options.psfFileName.c_str(), nPixels_psf); /* Set default end data row (if not specified) and check for reasonable values: */ startDataRow = 0; endDataRow = nPixels_psf - 1; xVals_psf = (double *)calloc( (size_t)nPixels_psf, sizeof(double) ); yVals_psf = (double *)calloc( (size_t)nPixels_psf, sizeof(double) ); if ( (xVals_psf == NULL) || (yVals_psf == NULL) ) { fprintf(stderr, "\nFailure to allocate memory for PSF data!\n"); exit(-1); } nSavedRows = ReadDataFile(options.psfFileName, startDataRow, endDataRow, xVals_psf, yVals_psf, NULL, NULL); if (nSavedRows > nStoredDataVals) { fprintf(stderr, "\nMore PSF rows saved (%d) than we allocated space for (%d)!\n", nSavedRows, nPixels_psf); exit(-1); } } /* Set up the model object */ theModel = new ModelObject1d(); /* Add functions to the model object */ printf("Adding functions to model object...\n"); status = AddFunctions1d(theModel, functionList, FunctionBlockIndices); if (status < 0) { printf("*** WARNING: Failure in AddFunctions!\n\n"); exit(-1); } theModel->SetZeroPoint(options.zeroPoint); // Set up parameter vector(s), now that we know how many total parameters // there will be nParamsTot = nFreeParams = theModel->GetNParams(); printf("\t%d total parameters\n", nParamsTot); paramsVect = (double *) malloc(nParamsTot * sizeof(double)); for (int i = 0; i < nParamsTot; i++) paramsVect[i] = parameterList[i]; paramErrs = (double *) malloc(nParamsTot * sizeof(double)); /* Add image data, errors, and mask to the model object */ // "true" = input yVals data are magnitudes, not intensities theModel->AddDataVectors(nStoredDataVals, xVals, yVals, options.dataAreMagnitudes); theModel->AddErrorVector1D(nStoredDataVals, yWeights, WEIGHTS_ARE_SIGMAS); if (maskAllocated) { status = theModel->AddMaskVector1D(nStoredDataVals, maskVals, options.maskFormat); if (status < 0) { fprintf(stderr, "*** ERROR: Failure in ModelObject::AddMaskVector1D!\n\n"); exit(-1); } } // Add PSF vector, if present, and thereby enable convolution if (options.psfPresent) { status = theModel->AddPSFVector1D(nPixels_psf, xVals_psf, yVals_psf); if (status < 0) { fprintf(stderr, "*** ERROR: Failure in ModelObject::AddPSFVector1D!\n\n"); exit(-1); } } theModel->FinalSetupForFitting(); // calls ApplyMask(), VetDataVector() theModel->PrintDescription(); // Parameter limits and other info: printf("Setting up parameter information vector ...\n"); mp_par newParamLimit; for (int i = 0; i < nParamsTot; i++) { memset(&newParamLimit, 0, sizeof(mp_par)); newParamLimit.fixed = paramLimits[i].fixed; if (paramLimits[i].fixed == 1) { printf("Fixed parameter detected (i = %d)\n", i); nFreeParams--; } newParamLimit.limited[0] = paramLimits[i].limited[0]; newParamLimit.limited[1] = paramLimits[i].limited[1]; newParamLimit.limits[0] = paramLimits[i].limits[0]; newParamLimit.limits[1] = paramLimits[i].limits[1]; parameterInfo.push_back(newParamLimit); } nDegFreedom = theModel->GetNValidPixels() - nFreeParams; printf("%d free parameters (%d degrees of freedom)\n", nFreeParams, nDegFreedom); // tell ModelObject about parameterInfo (mainly useful for printing-related methods) theModel->AddParameterInfo(parameterInfo); // OK, now we either print chi^2 value for the input parameters and quit, or // else call one of the solvers! if (options.printChiSquaredOnly) { printf("\n"); fitStatus = 1; PrintFitStatistic(paramsVect, theModel, nFreeParams); printf("\n"); // turn off saveing of parameter file options.saveBestFitParams = false; } else { // DO THE FIT! fitStatus = DispatchToSolver(options.solver, nParamsTot, nFreeParams, nStoredDataVals, paramsVect, parameterInfo, theModel, options.ftol, paramLimitsExist, options.verbose, &resultsFromSolver, options.nloptSolverName, options.rngSeed); PrintResults(paramsVect, theModel, nFreeParams, fitStatus, resultsFromSolver); } // OPTIONAL HANDLING OF BOOTSTRAP RESAMPLING HERE if ((options.doBootstrap) && (options.bootstrapIterations > 0)) { printf("\nNow doing bootstrap resampling (%d iterations) to estimate errors...\n", options.bootstrapIterations); printf("[NOT YET PROPERLY IMPLEMENTED!]\n"); BootstrapErrors(paramsVect, parameterInfo, paramLimitsExist, theModel, options.ftol, options.bootstrapIterations, nFreeParams); } if (options.saveBestFitParams) { printf("Saving best-fit parameters in file \"%s\"\n", options.outputParameterFileName.c_str()); string progNameVer = "profilefit "; progNameVer += VERSION_STRING; SaveParameters(paramsVect, theModel, options.outputParameterFileName, programHeader, nFreeParams, options.solver, fitStatus, resultsFromSolver); } if (options.saveBestProfile) { theModel->CreateModelImage(paramsVect); double *modelProfile = (double *) calloc((size_t)nStoredDataVals, sizeof(double)); int nPts = theModel->GetModelVector(modelProfile); if (nPts == nStoredDataVals) { printf("Saving model profile to %s...\n", options.modelOutputFileName.c_str()); outputFile_ptr = fopen(options.modelOutputFileName.c_str(), "w"); for (int i = 0; i < nPts; i++) { fprintf(outputFile_ptr, "\t%f\t%f\n", xVals[i], modelProfile[i]); } fclose(outputFile_ptr); printf("Done.\n"); } else { printf("WARNING -- MISMATCH BETWEEN nStoredDataVals (main) and nDataVals (ModelObject1d)!\n"); printf("NO PROFILE SAVED!\n"); } free(modelProfile); } // Free up memory free(xVals); free(yVals); free(yWeights); if (maskAllocated) free(maskVals); if (options.psfPresent) { free(xVals_psf); free(yVals_psf); } free(paramsVect); free(paramErrs); delete theModel; printf("All done!\n\n"); return 0; }
/*! 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; }
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(); }
/* .! : 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; }
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; }
void LadspaEffect::SaveUserPreset(const wxString & name) { SaveParameters(name); }
/*! 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; }