void testInputFiles(int numFilenames, char* filename[]) { inputFilenames = (const char**)malloc((numFilenames+1)*sizeof(char*)); int i; char achar; for (i = 0; i < numFilenames; i++) { if (!isRecognizedSource(filename[i])) { USR_FATAL(astr("file '", filename[i], "' does not have a recognized suffix")); } // WE SHOULDN"T TRY TO OPEN .h files, just .c and .chpl and .o if (!isCHeader(filename[i])) { FILE* testfile = openInputFile(filename[i]); if (fscanf(testfile, "%c", &achar) != 1) { USR_FATAL(astr("source file '", filename[i], "' is either empty or a directory")); } closeInputFile(testfile); } inputFilenames[i] = astr(filename[i]); } inputFilenames[i] = NULL; if (!foundChplSource) USR_FATAL("Command line contains no .chpl source files"); }
void readBigHouseCDF(vector<double> &CDF_Sample, vector<double> &CDF_Prob, const string fileName, ifstream &handle){ openInputFile(fileName, handle); string line = ""; try{ while (getline(handle, line)){ istringstream record(line); string last; record >> last; // BigHouse stores Google search CDF in "second" unit. Need to scale by 1000. if (fileName.compare("search.service.cdf") == 0){ CDF_Sample.push_back(1000 * stod(last)); } else if (fileName.compare("search.arrival.cdf") == 0){ // Multiply by 16 because there are 16 servers. CDF_Sample.push_back(1000 * 16 * stod(last)); } else{ CDF_Sample.push_back(stod(last)); } record >> last; CDF_Prob.push_back(stod(last)); } } catch (const ifstream::failure &e){ assert(CDF_Prob.size() == CDF_Sample.size()); handle.close(); } }
void ModelInput::readInputFile(){ // Unwrap the reference: auto &domain = domainRef.get(); auto &solver = domain.getSolver(); if (not ifs.is_open()){ openInputFile(); } std::string dummy = ""; // header readParams(ifs, dummy); // gravitational acceleration readParams(ifs, solver->g); // total number of timesteps readParams(ifs, solver->tnts); // one timestep in seconds readParams(ifs, solver->dt); // output parameters: readParams(ifs, dummy, domain.qOutput->qts, domain.pts); closeInputFile(); }
int main(){ char allStar = '\0', regularMVP = '\0', worldMVP = '\0', goldGlove = '\0', silverSlug = '\0', homeRun = '\0', battingAve = '\0', gender = '\0'; int bonus = 0, num1 = 0, num2 = 0, num3 = 0, num4 = 0, num5 = 0, activityLevel = 0, menuChoice = 0, i = 0; double weight = 0, height = 0, age = 0, bmr = 0, calories = 0, result = 0; FILE *inputFile = NULL; //PROBLEM 1 inputFile = openInputFile(); /* gender = readCharacter(inputFile); age = readNumber(inputFile); weight = readNumber(inputFile); height = readNumber(inputFile); bmr = computeBMR(gender, weight, height, age); activityLevel = determineActivityLevel(); calories = computeCalories(bmr, activityLevel); printf("Calories needed per day are: %.0lf\n", calories); //PROBLEM 2 allStar = getBaseballAchievements("All-Star Game appearance"); bonus += determineBonus(allStar, 25000); regularMVP = getBaseballAchievements("Regular Season MVP"); bonus += determineBonus(regularMVP, 75000); worldMVP = getBaseballAchievements("World Series MVP"); bonus += determineBonus(worldMVP, 100000); goldGlove = getBaseballAchievements("Gold Glove award"); bonus += determineBonus(goldGlove, 50000); silverSlug = getBaseballAchievements("Silver Slugger award"); bonus += determineBonus(silverSlug, 35000); homeRun = getBaseballAchievements("Home run champ"); bonus += determineBonus(homeRun, 25000); battingAve = getBaseballAchievements("Batting average champ"); bonus += determineBonus(battingAve, 25000); printf("Total player bonus is %d\n", bonus); int i = 0;*/ //PROBLEM 3 num1 = readInteger(inputFile); num2 = readInteger(inputFile); num3 = readInteger(inputFile); num4 = readInteger(inputFile); num5 = readInteger(inputFile); while (i < 3){ menuChoice = displayMenu(); result = calculateResult(menuChoice, num1, num2, num3, num4, num5); displayResult(menuChoice, result); i++; } return 0; }
int main(int argc, char* argv[]) { parseArgs(argc, argv); openInputFile(); openOutputFiles(); skipLines(); splitFile(); fprintf(stdout, "Lines Skipped: %ld / Lines Processed: %llu\n", _linesSkipped, _linesProcessed); closeOutputFiles(); closeInputFile(); exit(EXIT_SUCCESS); }
boost::shared_ptr<IqTexInputFile> IqTexInputFile::open(const boostfs::path& fileName) { boost::shared_ptr<IqTexInputFile> file = openInputFile(guessFileType(fileName), fileName); if(file) return file; else AQSIS_THROW_XQERROR(XqInvalidFile, EqE_BadFile, "Unknown file type for \"" << fileName << "\""); assert(0); return boost::shared_ptr<IqTexInputFile>(); }
void addSourceFiles(int numNewFilenames, const char* filename[]) { static int numInputFiles = 0; int cursor = numInputFiles; char achar; numInputFiles += numNewFilenames; inputFilenames = (const char**)realloc(inputFilenames, (numInputFiles+1)*sizeof(char*)); for (int i = 0; i < numNewFilenames; i++) { if (!isRecognizedSource(filename[i])) { USR_FATAL(astr("file '", filename[i], "' does not have a recognized suffix")); } // WE SHOULDN"T TRY TO OPEN .h files, just .c and .chpl and .o if (!isCHeader(filename[i])) { FILE* testfile = openInputFile(filename[i]); if (fscanf(testfile, "%c", &achar) != 1) { USR_FATAL(astr("source file '", filename[i], "' is either empty or a directory")); } closeInputFile(testfile); } // // Don't add the same file twice -- it's unnecessary and can mess // up things like unprotected headers // bool duplicate = false; const char* newFilename = astr(filename[i]); for (int j = 0; j < cursor; j++) { if (inputFilenames[j] == newFilename) { // legal due to astr() duplicate = true; break; } } if (duplicate) { numInputFiles--; } else { inputFilenames[cursor++] = newFilename; } } inputFilenames[cursor] = NULL; if (!foundChplSource && fUseIPE == false) USR_FATAL("Command line contains no .chpl source files"); }
int main() { printf("start of program: "); heapReport(); FILE *inputFile = openInputFile("input.txt"); FILE *outputFile = openOutputFile("output.txt"); LinkedList list; // Read 10 integers from the input file, adding them // alternately to the beginning and end of the list. // After each change to the list, write the contents of the // list to the output file. fprintf(outputFile, "CREATING LIST:\n"); int count; for (count = 1; count <= 5; count++) { list = readAndAddToStart(list, inputFile); printList(list, outputFile); list = readAndAddToEnd(list, inputFile); printList(list, outputFile); } // end for // Show heap space used on standard input printf("after creating list: "); heapReport(); fprintf(outputFile, "\nWHILE DELETING FROM LIST:\n"); int start = 1; // 1 (true) means addint to start while (list != NULL) { if (start) list = deleteFirst(list); else list = deleteLast(list); start = !start; printList(list, outputFile); } // end for // Show heap space again; if delete functions have freed space // it should be zero. printf("after emptying list: "); heapReport(); fclose(inputFile); fclose(outputFile); printf("after closing files: "); heapReport(); return 0; } // end main
/*! * \brief MainWindow::MainWindow * \param parent */ MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->stopButton->hide(); ui->qwtPlot->setTitle("Error"); ui->qwtPlot->setAxisTitle(ui->qwtPlot->xBottom, "Epoch"); ui->qwtPlot->setAxisTitle(ui->qwtPlot->yLeft,"Error"); ui->qwtPlot->setAxisAutoScale( ui->qwtPlot->xBottom, true ); ui->qwtPlot->setAxisAutoScale( ui->qwtPlot->yLeft, true ); ui->stopButton->setVisible( false ); ui->saveButton->setVisible( false ); zoom = new QwtPlotZoomer(ui->qwtPlot->canvas()); zoom->setRubberBandPen(QPen(Qt::white)); QPen pen = QPen( Qt::red ); curve.setRenderHint( QwtPlotItem::RenderAntialiased ); curve.setPen( pen ); curve.attach( ui->qwtPlot ); sendAlpha(); // INFO connect ui to mainwindow { QObject::connect( ui->saveImageButton, SIGNAL( clicked() ), this, SLOT( saveImage() ) ); QObject::connect( ui->inputOpenButton, SIGNAL( clicked() ), this, SLOT( openInputFile() ) ); QObject::connect( ui->saveButton, SIGNAL( clicked() ), this, SLOT( openOutputFile() ) ); QObject::connect( ui->startButton, SIGNAL( clicked() ), this, SLOT( start() ) ); QObject::connect( ui->startButton, SIGNAL( clicked( bool ) ), ui->stopButton, SLOT( setVisible(bool) ) ); QObject::connect( ui->alphaMantiss, SIGNAL( valueChanged( double ) ), this, SLOT( sendAlpha() ) ); QObject::connect( ui->alphaDegree, SIGNAL( valueChanged( int ) ), this, SLOT( sendAlpha() ) ); } // INFO connectio ui to ui { QObject::connect(ui->startButton,SIGNAL(clicked()),ui->stopButton,SLOT(show())); } // /* INFO connection ui to facade { QObject::connect( ui->stopButton, SIGNAL( clicked() ), &Facade::getInstance(), SLOT( stopProcess() ) ); QObject::connect( ui->maxEpoch, SIGNAL( valueChanged(int) ), &Facade::getInstance(), SLOT( setMaxNumberOfEpoh(int) ) ); QObject::connect( ui->numberOfNeurons, SIGNAL( valueChanged(int) ), &Facade::getInstance(), SLOT( setNumberOfNeurons(int) ) ); } // */ // /* INFO connection facade to ui { QObject::connect( &Facade::getInstance(), SIGNAL( processEnd() ), ui->startButton, SLOT( show() ) ); QObject::connect( &Facade::getInstance(), SIGNAL( processEnd() ), ui->saveButton, SLOT( show() ) ); QObject::connect( &Facade::getInstance(), SIGNAL( processEnd() ), ui->stopButton, SLOT( hide() ) ); } // */ // /* INFO connection facade to main window { // QObject::connect( &Facade::getInstance(), SIGNAL( sendInitialLayerInfo(LayerDescription)), // this, SLOT( setInitialLayerInfo( LayerDescription ) ) ); QObject::connect( &Facade::getInstance(), SIGNAL( processEnd() ), this, SLOT( displayResults() ) ); } // */ // /* INFO connection main window to facade { QObject::connect( this, SIGNAL( setInputFileName(QString) ), &Facade::getInstance(), SLOT( setInputFileName(QString) ) ); QObject::connect( this, SIGNAL( setOutputFileName(QString) ), &Facade::getInstance(), SLOT( setOutputFileName(QString) ) ); QObject::connect( this, SIGNAL( setAlpha( double ) ), &Facade::getInstance(), SLOT( setAlhpa( double ) ) ); } // */ }
void Server::run(const string rho_in, const string cdf_ser, const string cdf_arr){ /* rho_in is the utilization log. cdf_ser and cdf_arr are cdf distributions used to generate workload. SleepScale is called every T mins and only when job log has accumulated JOB_LOG_LENGTH = 10,000 jobs. */ // Open those files! this->logOut << "[SLEEPSCALE] Preparing SleepScale..." << endl; ifstream rhoIn; openInputFile(rho_in, rhoIn); #ifdef DO_OFFLINE ifstream rhoInOffline; openInputFile(rho_in, rhoInOffline); #endif // arr_sample and arr_prob stores the histogram of inter-arrival time. The probability of each entry in arr_sample is stored in arr_prob vector<double> CDF_arrSample; vector<double> CDF_arrProb; vector<double> CDF_serSample; vector<double> CDF_serProb; ifstream arrCdfFile; readBigHouseCDF(CDF_arrSample, CDF_arrProb, cdf_arr, arrCdfFile); ifstream serCdfFile; readBigHouseCDF(CDF_serSample, CDF_serProb, cdf_ser, serCdfFile); this->logOut << "[SLEEPSCALE] All files are open. CDFs are read!" << endl; this->logOut << "[SLEEPSCALE] Constructing the estimator..." << endl; // Construct the estimator this->estimator = make_shared<Estimator>(EST_LOOKBACK, rhoIn, this->logOut); this->logOut << "[SlEEPSCALE] Ensuring the clock is reset -- current minute # is " << this->minute << endl; this->logOut << "[SLEEPSCALE] SleepScale is ready!" << endl; this->logOut << "[SLEEPSCALE] Starting SleepScale..." << endl; // Initialize the first policy shared_ptr<PowerState> lastBestPolicy = this->allPolicy.at(0); while (this->estimator->estimatorStatus && this->estimator->observorStatus){ this->logOut << endl; // cout << "====== MINUTE # " << this->minute << endl; this->logOut << "====== STARTING MINUTE # " << this->minute << endl; // Estimate rho this->logOut << "[SLEEPSCALE] Estimating the utilization for minute # " << this->minute << endl; #ifndef DO_OFFLINE this->estimator->estimateRho(this->logOut); #else this->estimator->estimateRho(this->logOut, rhoInOffline); #endif // Run SleepScale only after job log size reaches JOB_LOG_LENGTH and every UPDATE_INTERVAL minutes if (this->minute > 0 && this->minute % UPDATE_INTERVAL == 0 && this->jobLog.readyForSleepScale()){ assert(this->jobLog.getSize() == this->jobLog.size); this->logOut << "+++++++++++++++ Time to adjust policy at minute # " << this->minute << endl; /* Run the server in SleepScale. The server is ran at the end of every UPDATE_INTERVAL minutes, before calling SleepScale. The policy it uses to run is calculated by the previous SleepScale process. */ this->logOut << "[SLEEPSCALE] Run the server" << endl; this->doQueue(lastBestPolicy, this->jobQueue); // Run the server using baseline. this->logOut << "[SLEEPSCALE] Run the baseline" << endl; this->doQueueBaseline(this->allPolicy.at(0), this->jobQueue); // Workload queue is cleared. this->jobQueue.clear(); // Clear job queue // Then do SleepScale. SleepScale only has access to the job log. It has to adjust their // inter-arrival time to match the predicted utilization. this->logOut << "++++++++++++++++++++++++++++++ Now do SleepScale!" << endl; // Do SleepScale lastBestPolicy = this->doSleepScale(); // Observe a new rho for the next minute. this->logOut << "[SLEEPSCALE] Observe the utilization of minute # " << this->minute << endl; double newRho = this->estimator->observeRho(rhoIn, this->logOut); if (newRho >= 0){ // Generate workload by sampling CDFs. this->logOut << "[SLEEPSCALE] Generate workload for minute # " << this->minute << " under utilization " << newRho << "." << endl; generateWorkloadCDF(CDF_serProb, CDF_serSample, CDF_arrProb, CDF_arrSample, this->minute, newRho); ++this->minute; } else { this->logOut << "[SLEEPSCALE] Observer reached the EoF. Preparing to terminate!" << endl; showReport(); } } else{ // If SleepScale is not done in this minute, observe a new rho for the next minute. this->logOut << "[SLEEPSCALE] Observe the utilization of minute # " << this->minute << endl; double newRho = this->estimator->observeRho(rhoIn, this->logOut); if (newRho >= 0){ // Generate workload by sampling CDFs. Remember to keep track of the utilization this->logOut << "[SLEEPSCALE] Generate workload for minute # " << this->minute << " under utilization " << newRho << "." << endl; generateWorkloadCDF(CDF_serProb, CDF_serSample, CDF_arrProb, CDF_arrSample, this->minute, newRho); ++this->minute; } else { // If reaches the EoF, then run the server and terminate. this->logOut << "[SLEEPSCALE] Observer reached the EoF. Preparing to terminate!" << endl; this->logOut << "[SLEEPSCALE] Run the server" << endl; this->doQueue(lastBestPolicy, this->jobQueue); this->bestFreqUsed.push_back(lastBestPolicy->freq); this->bestLowpowerUsed.push_back(lastBestPolicy->idle); // Run the server using baseline. this->logOut << "[SLEEPSCALE] Run the baseline" << endl; this->doQueueBaseline(this->allPolicy.at(0), this->jobQueue); showReport(); } } } rhoIn.close(); return; }
//Opens user specified file, compares data, and prints results void printStockValue() { int fdIn = openInputFile();//Stores file descriptor char temp[4096] = "NULL";//Stores input data int res = read(fdIn,&temp[0],1); int count = 1;//Array index char symbol[50] = "NULL"; double price; Node * cur; double CV;//Current value double PV;//Purchase value double PL;//Profit/Loss int count2 = 0;//Line feeds in file while(res != 0) { res = read(fdIn,&temp[count],1); if(temp[count] == 10)//Line feed { count2++; } count++; } close(fdIn); printf("\n\n"); //Begin parse char * t = strtok(temp," "); strcpy(symbol,t); int j; for(j=0; j < count2;j++)//Go until count reaches number of lines read { t = strtok(NULL,"\n"); price = atof(t); for(cur=head;cur!=NULL;cur = cur->next) { if(strcmp(((Stock*)(cur->data))->c.symbol,symbol) == 0)//Same symbol { //Compare and print results CV = (price)*((Stock*)(cur->data))->shares; PV = (((Stock*)(cur->data))->shares)*(((Stock*)(cur->data))->price); PL = CV-PV; printf("%s current price: %.2lf\n",((Stock*)(cur->data))->c.name,price); printf(" Current Value: $%.2lf\n",CV); printf(" Puchase Value: $%.2lf\n",PV); if(PL < 0)//Lost value { PL = (PL)*(-1); printf(" Profit/Loss: $(%.2lf)\n",PL); } else { printf(" Profit/Loss: $%.2lf\n",PL); } printf("\n\n"); } } t = strtok(NULL," "); if(t != NULL) { strcpy(symbol,t); } } }
void SFVGridInput::readInputFile(){ // Unwrap the reference: auto &domain = domainRef.get(); auto &grid = domain.getSolver()->getGrid(); if (not ifs.is_open()){ openInputFile(); } if (fileFormat=="asmfv-1D"){ std::string dummy = ""; // Boundary layer thickness (hard-coded) grid->nbt = 1; // header readParams(ifs, dummy); // domain type readParams(ifs, dummy); // ni: number of columns (x-direction) readParams(ifs, grid->ni); // nj: number of rows (y-direction) grid->nj = 1; // x0: x-coordinate of the lower left cell readParams(ifs, grid->x0); // dx: x-coordinate of the lower left cell readParams(ifs, grid->dx); // lbtype, rbtype readParams(ifs, grid->lbtype, grid->rbtype); // zd: default z value readParams(ifs, grid->zd); // generate the cell instances: for (unsigned int id=0; id<grid->get_ninj(); ++id){ grid->insertUnit(Cell(id,std::ref(grid->cells))); grid->cells.back().z = grid->zd; } // Read in non-default z values std::string line; std::vector<std::string> sline; auto cellTypeIndex = std::type_index(typeid(Cell)); while (getline( ifs, line)){ sline = splitLine(line); int id = atoi((sline[0]).c_str()); grid->cells[grid->id2pos[cellTypeIndex][id]].z = atof((sline[1]).c_str()); } // Construct the adjacency for (unsigned int pos=1; pos<grid->get_ninj(); ++pos){ grid->cells[pos].left = &(grid->cells[pos-1]); grid->cells[pos-1].right = &(grid->cells[pos]); } } else if (fileFormat=="esri"){ Report::error("SFVGridInput!","esri format not implemented yet"); } else{ Report::error("SFVGridInput!","Invalid grid format: "+fileFormat); } }
bool EfmProcess::process(QString inputEfmFilename, QString outputAudioFilename, QString outputDataFilename, bool verboseDebug) { // Open the input file if (!openInputFile(inputEfmFilename)) { qCritical("Could not open input file!"); return false; } bool processAudio = false; bool processData = false; if (!outputAudioFilename.isEmpty()) processAudio = true; if (!outputDataFilename.isEmpty()) processData = true; qint64 inputFileSize = inputFileHandle->size(); qint64 inputBytesProcessed = 0; qint32 lastPercent = 0; // Open the audio output file if (processAudio) f2FramesToAudio.openOutputFile(outputAudioFilename); // Open the data decode output file if (processData) sectorsToData.openOutputFile(outputDataFilename); // Open the metadata JSON file if (processAudio) sectionToMeta.openOutputFile(outputAudioFilename + ".subcode.json"); if (processData) sectorsToMeta.openOutputFile(outputDataFilename + ".data.json"); // Turn on verbose debug if required if (verboseDebug) efmToF3Frames.setVerboseDebug(true); QByteArray efmBuffer; while ((efmBuffer = readEfmData()).size() != 0) { inputBytesProcessed += efmBuffer.size(); // Convert the EFM buffer data into F3 frames QVector<F3Frame> f3Frames = efmToF3Frames.convert(efmBuffer); // Convert the F3 frames into F2 frames QVector<F2Frame> f2Frames = f3ToF2Frames.convert(f3Frames); // Convert the F2 frames into F1 frames QVector<F1Frame> f1Frames = f2ToF1Frames.convert(f2Frames); if (processData) { // Convert the F1 frames to data sectors QVector<Sector> sectors = f1ToSectors.convert(f1Frames); // Write the sectors as data sectorsToData.convert(sectors); // Process the sector meta data sectorsToMeta.process(sectors); } // Convert the F2 frames into audio if (processAudio) f2FramesToAudio.convert(f2Frames); // Convert the F3 frames into subcode sections QVector<Section> sections = f3ToSections.convert(f3Frames); // Process the sections to audio metadata if (processAudio) sectionToMeta.process(sections); // Show EFM processing progress update to user qreal percent = (100.0 / static_cast<qreal>(inputFileSize)) * static_cast<qreal>(inputBytesProcessed); if (static_cast<qint32>(percent) > lastPercent) qInfo().nospace() << "Processed " << static_cast<qint32>(percent) << "% of the input EFM"; lastPercent = static_cast<qint32>(percent); } // Report on the status of the various processes reportStatus(processAudio, processData); // Close the input file closeInputFile(); // Close the output files if (processAudio) f2FramesToAudio.closeOutputFile(); if (processAudio) sectionToMeta.closeOutputFile(); if (processData) sectorsToData.closeOutputFile(); if (processData) sectorsToMeta.closeOutputFile(); return true; }
int QgsRelief::processRaster( QgsFeedback *feedback ) { //open input file int xSize, ySize; GDALDatasetH inputDataset = openInputFile( xSize, ySize ); if ( !inputDataset ) { return 1; //opening of input file failed } //output driver GDALDriverH outputDriver = openOutputDriver(); if ( !outputDriver ) { return 2; } GDALDatasetH outputDataset = openOutputFile( inputDataset, outputDriver ); if ( !outputDataset ) { return 3; //create operation on output file failed } //initialize dependency filters with cell sizes mHillshadeFilter285->setCellSizeX( mCellSizeX ); mHillshadeFilter285->setCellSizeY( mCellSizeY ); mHillshadeFilter285->setZFactor( mZFactor ); mHillshadeFilter300->setCellSizeX( mCellSizeX ); mHillshadeFilter300->setCellSizeY( mCellSizeY ); mHillshadeFilter300->setZFactor( mZFactor ); mHillshadeFilter315->setCellSizeX( mCellSizeX ); mHillshadeFilter315->setCellSizeY( mCellSizeY ); mHillshadeFilter315->setZFactor( mZFactor ); mSlopeFilter->setCellSizeX( mCellSizeX ); mSlopeFilter->setCellSizeY( mCellSizeY ); mSlopeFilter->setZFactor( mZFactor ); mAspectFilter->setCellSizeX( mCellSizeX ); mAspectFilter->setCellSizeY( mCellSizeY ); mAspectFilter->setZFactor( mZFactor ); //open first raster band for reading (operation is only for single band raster) GDALRasterBandH rasterBand = GDALGetRasterBand( inputDataset, 1 ); if ( !rasterBand ) { GDALClose( inputDataset ); GDALClose( outputDataset ); return 4; } mInputNodataValue = GDALGetRasterNoDataValue( rasterBand, nullptr ); mSlopeFilter->setInputNodataValue( mInputNodataValue ); mAspectFilter->setInputNodataValue( mInputNodataValue ); mHillshadeFilter285->setInputNodataValue( mInputNodataValue ); mHillshadeFilter300->setInputNodataValue( mInputNodataValue ); mHillshadeFilter315->setInputNodataValue( mInputNodataValue ); GDALRasterBandH outputRedBand = GDALGetRasterBand( outputDataset, 1 ); GDALRasterBandH outputGreenBand = GDALGetRasterBand( outputDataset, 2 ); GDALRasterBandH outputBlueBand = GDALGetRasterBand( outputDataset, 3 ); if ( !outputRedBand || !outputGreenBand || !outputBlueBand ) { GDALClose( inputDataset ); GDALClose( outputDataset ); return 5; } //try to set -9999 as nodata value GDALSetRasterNoDataValue( outputRedBand, -9999 ); GDALSetRasterNoDataValue( outputGreenBand, -9999 ); GDALSetRasterNoDataValue( outputBlueBand, -9999 ); mOutputNodataValue = GDALGetRasterNoDataValue( outputRedBand, nullptr ); mSlopeFilter->setOutputNodataValue( mOutputNodataValue ); mAspectFilter->setOutputNodataValue( mOutputNodataValue ); mHillshadeFilter285->setOutputNodataValue( mOutputNodataValue ); mHillshadeFilter300->setOutputNodataValue( mOutputNodataValue ); mHillshadeFilter315->setOutputNodataValue( mOutputNodataValue ); if ( ySize < 3 ) //we require at least three rows (should be true for most datasets) { GDALClose( inputDataset ); GDALClose( outputDataset ); return 6; } //keep only three scanlines in memory at a time float *scanLine1 = ( float * ) CPLMalloc( sizeof( float ) * xSize ); float *scanLine2 = ( float * ) CPLMalloc( sizeof( float ) * xSize ); float *scanLine3 = ( float * ) CPLMalloc( sizeof( float ) * xSize ); unsigned char *resultRedLine = ( unsigned char * ) CPLMalloc( sizeof( unsigned char ) * xSize ); unsigned char *resultGreenLine = ( unsigned char * ) CPLMalloc( sizeof( unsigned char ) * xSize ); unsigned char *resultBlueLine = ( unsigned char * ) CPLMalloc( sizeof( unsigned char ) * xSize ); bool resultOk; //values outside the layer extent (if the 3x3 window is on the border) are sent to the processing method as (input) nodata values for ( int i = 0; i < ySize; ++i ) { if ( feedback ) { feedback->setProgress( 100.0 * i / static_cast< double >( ySize ) ); } if ( feedback && feedback->isCanceled() ) { break; } if ( i == 0 ) { //fill scanline 1 with (input) nodata for the values above the first row and feed scanline2 with the first row for ( int a = 0; a < xSize; ++a ) { scanLine1[a] = mInputNodataValue; } if ( GDALRasterIO( rasterBand, GF_Read, 0, 0, xSize, 1, scanLine2, xSize, 1, GDT_Float32, 0, 0 ) != CE_None ) { QgsDebugMsg( "Raster IO Error" ); } } else { //normally fetch only scanLine3 and release scanline 1 if we move forward one row CPLFree( scanLine1 ); scanLine1 = scanLine2; scanLine2 = scanLine3; scanLine3 = ( float * ) CPLMalloc( sizeof( float ) * xSize ); } if ( i == ySize - 1 ) //fill the row below the bottom with nodata values { for ( int a = 0; a < xSize; ++a ) { scanLine3[a] = mInputNodataValue; } } else { if ( GDALRasterIO( rasterBand, GF_Read, 0, i + 1, xSize, 1, scanLine3, xSize, 1, GDT_Float32, 0, 0 ) != CE_None ) { QgsDebugMsg( "Raster IO Error" ); } } for ( int j = 0; j < xSize; ++j ) { if ( j == 0 ) { resultOk = processNineCellWindow( &mInputNodataValue, &scanLine1[j], &scanLine1[j + 1], &mInputNodataValue, &scanLine2[j], \ &scanLine2[j + 1], &mInputNodataValue, &scanLine3[j], &scanLine3[j + 1], \ &resultRedLine[j], &resultGreenLine[j], &resultBlueLine[j] ); } else if ( j == xSize - 1 ) { resultOk = processNineCellWindow( &scanLine1[j - 1], &scanLine1[j], &mInputNodataValue, &scanLine2[j - 1], &scanLine2[j], \ &mInputNodataValue, &scanLine3[j - 1], &scanLine3[j], &mInputNodataValue, \ &resultRedLine[j], &resultGreenLine[j], &resultBlueLine[j] ); } else { resultOk = processNineCellWindow( &scanLine1[j - 1], &scanLine1[j], &scanLine1[j + 1], &scanLine2[j - 1], &scanLine2[j], \ &scanLine2[j + 1], &scanLine3[j - 1], &scanLine3[j], &scanLine3[j + 1], \ &resultRedLine[j], &resultGreenLine[j], &resultBlueLine[j] ); } if ( !resultOk ) { resultRedLine[j] = mOutputNodataValue; resultGreenLine[j] = mOutputNodataValue; resultBlueLine[j] = mOutputNodataValue; } } if ( GDALRasterIO( outputRedBand, GF_Write, 0, i, xSize, 1, resultRedLine, xSize, 1, GDT_Byte, 0, 0 ) != CE_None ) { QgsDebugMsg( "Raster IO Error" ); } if ( GDALRasterIO( outputGreenBand, GF_Write, 0, i, xSize, 1, resultGreenLine, xSize, 1, GDT_Byte, 0, 0 ) != CE_None ) { QgsDebugMsg( "Raster IO Error" ); } if ( GDALRasterIO( outputBlueBand, GF_Write, 0, i, xSize, 1, resultBlueLine, xSize, 1, GDT_Byte, 0, 0 ) != CE_None ) { QgsDebugMsg( "Raster IO Error" ); } } if ( feedback ) { feedback->setProgress( 100 ); } CPLFree( resultRedLine ); CPLFree( resultBlueLine ); CPLFree( resultGreenLine ); CPLFree( scanLine1 ); CPLFree( scanLine2 ); CPLFree( scanLine3 ); GDALClose( inputDataset ); if ( feedback && feedback->isCanceled() ) { //delete the dataset without closing (because it is faster) GDALDeleteDataset( outputDriver, mOutputFile.toUtf8().constData() ); return 7; } GDALClose( outputDataset ); return 0; }
QList< QgsRelief::ReliefColor > QgsRelief::calculateOptimizedReliefClasses() { QList< QgsRelief::ReliefColor > resultList; int nCellsX, nCellsY; GDALDatasetH inputDataset = openInputFile( nCellsX, nCellsY ); if ( !inputDataset ) { return resultList; } //open first raster band for reading (elevation raster is always single band) GDALRasterBandH elevationBand = GDALGetRasterBand( inputDataset, 1 ); if ( !elevationBand ) { GDALClose( inputDataset ); return resultList; } //1. get minimum and maximum of elevation raster -> 252 elevation classes int minOk, maxOk; double minMax[2]; minMax[0] = GDALGetRasterMinimum( elevationBand, &minOk ); minMax[1] = GDALGetRasterMaximum( elevationBand, &maxOk ); if ( !minOk || !maxOk ) { GDALComputeRasterMinMax( elevationBand, true, minMax ); } //2. go through raster cells and get frequency of classes //store elevation frequency in 256 elevation classes double frequency[252]; double frequencyClassRange = ( minMax[1] - minMax[0] ) / 252.0; //initialize to zero for ( int i = 0; i < 252; ++i ) { frequency[i] = 0; } float *scanLine = ( float * ) CPLMalloc( sizeof( float ) * nCellsX ); int elevationClass = -1; for ( int i = 0; i < nCellsY; ++i ) { if ( GDALRasterIO( elevationBand, GF_Read, 0, i, nCellsX, 1, scanLine, nCellsX, 1, GDT_Float32, 0, 0 ) != CE_None ) { QgsDebugMsg( "Raster IO Error" ); } for ( int j = 0; j < nCellsX; ++j ) { elevationClass = frequencyClassForElevation( scanLine[j], minMax[0], frequencyClassRange ); if ( elevationClass < 0 ) { elevationClass = 0; } else if ( elevationClass >= 252 ) { elevationClass = 251; } frequency[elevationClass] += 1.0; } } CPLFree( scanLine ); //log10 transformation for all frequency values for ( int i = 0; i < 252; ++i ) { frequency[i] = std::log10( frequency[i] ); } //start with 9 uniformly distributed classes QList<int> classBreaks; classBreaks.append( 0 ); classBreaks.append( 28 ); classBreaks.append( 56 ); classBreaks.append( 84 ); classBreaks.append( 112 ); classBreaks.append( 140 ); classBreaks.append( 168 ); classBreaks.append( 196 ); classBreaks.append( 224 ); classBreaks.append( 252 ); for ( int i = 0; i < 10; ++i ) { optimiseClassBreaks( classBreaks, frequency ); } //debug, print out all the classbreaks for ( int i = 0; i < classBreaks.size(); ++i ) { qWarning( "%d", classBreaks[i] ); } //set colors according to optimised class breaks QVector<QColor> colorList; colorList.push_back( QColor( 7, 165, 144 ) ); colorList.push_back( QColor( 12, 221, 162 ) ); colorList.push_back( QColor( 33, 252, 183 ) ); colorList.push_back( QColor( 247, 252, 152 ) ); colorList.push_back( QColor( 252, 196, 8 ) ); colorList.push_back( QColor( 252, 166, 15 ) ); colorList.push_back( QColor( 175, 101, 15 ) ); colorList.push_back( QColor( 255, 133, 92 ) ); colorList.push_back( QColor( 204, 204, 204 ) ); resultList.reserve( classBreaks.size() ); for ( int i = 1; i < classBreaks.size(); ++i ) { double minElevation = minMax[0] + classBreaks[i - 1] * frequencyClassRange; double maxElevation = minMax[0] + classBreaks[i] * frequencyClassRange; resultList.push_back( QgsRelief::ReliefColor( colorList.at( i - 1 ), minElevation, maxElevation ) ); } return resultList; }
//this function is mainly there for debugging bool QgsRelief::exportFrequencyDistributionToCsv( const QString &file ) { int nCellsX, nCellsY; GDALDatasetH inputDataset = openInputFile( nCellsX, nCellsY ); if ( !inputDataset ) { return false; } //open first raster band for reading (elevation raster is always single band) GDALRasterBandH elevationBand = GDALGetRasterBand( inputDataset, 1 ); if ( !elevationBand ) { GDALClose( inputDataset ); return false; } //1. get minimum and maximum of elevation raster -> 252 elevation classes int minOk, maxOk; double minMax[2]; minMax[0] = GDALGetRasterMinimum( elevationBand, &minOk ); minMax[1] = GDALGetRasterMaximum( elevationBand, &maxOk ); if ( !minOk || !maxOk ) { GDALComputeRasterMinMax( elevationBand, true, minMax ); } //2. go through raster cells and get frequency of classes //store elevation frequency in 256 elevation classes double frequency[252]; double frequencyClassRange = ( minMax[1] - minMax[0] ) / 252.0; //initialize to zero for ( int i = 0; i < 252; ++i ) { frequency[i] = 0; } float *scanLine = ( float * ) CPLMalloc( sizeof( float ) * nCellsX ); int elevationClass = -1; for ( int i = 0; i < nCellsY; ++i ) { if ( GDALRasterIO( elevationBand, GF_Read, 0, i, nCellsX, 1, scanLine, nCellsX, 1, GDT_Float32, 0, 0 ) != CE_None ) { QgsDebugMsg( "Raster IO Error" ); } for ( int j = 0; j < nCellsX; ++j ) { elevationClass = frequencyClassForElevation( scanLine[j], minMax[0], frequencyClassRange ); if ( elevationClass >= 0 ) { frequency[elevationClass] += 1.0; } } } CPLFree( scanLine ); //log10 transformation for all frequency values for ( int i = 0; i < 252; ++i ) { frequency[i] = std::log10( frequency[i] ); } //write out frequency values to csv file for debugging QFile outFile( file ); if ( !outFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) ) { return false; } QTextStream outstream( &outFile ); for ( int i = 0; i < 252; ++i ) { outstream << QString::number( i ) + ',' + QString::number( frequency[i] ) << endl; } outFile.close(); return true; }
int main(void){ FILE *inputFile = NULL, *outputFileStats = NULL, *outputFileAscii = NULL; char c1 = '\0', c2 = '\0', c3 = '\0', c4 = '\0', c5 = '\0', c6 = '\0', c7 = '\0', c8 = '\0', c9 = '\0', c10 = '\0'; int num1 = 0, num2 = 0, num3 = 0, num4 = 0, num5 = 0, num6 = 0, num7 = 0, num8 = 0, num9 = 0, num10 = 0, numLines = 0, numVowels = 0, numDigits = 0, numAlpha = 0, numLower = 0, numUpper = 0, numSpace = 0, numAlnum = 0, numPunct = 0; inputFile = openInputFile(); outputFileStats = fopen("output_stats.dat", "w"); outputFileAscii = fopen("output_ascii.dat", "w"); if (inputFile != NULL && outputFileStats != NULL && outputFileAscii != NULL){ c1 = readCharacter(inputFile); c2 = readCharacter(inputFile); c3 = readCharacter(inputFile); c4 = readCharacter(inputFile); c5 = readCharacter(inputFile); c6 = readCharacter(inputFile); c7 = readCharacter(inputFile); c8 = readCharacter(inputFile); c9 = readCharacter(inputFile); c10 = readCharacter(inputFile); num1 = determineAsciiValue(c1); num2 = determineAsciiValue(c2); num3 = determineAsciiValue(c3); num4 = determineAsciiValue(c4); num5 = determineAsciiValue(c5); num6 = determineAsciiValue(c6); num7 = determineAsciiValue(c7); num8 = determineAsciiValue(c8); num9 = determineAsciiValue(c9); num10 = determineAsciiValue(c10); printInt(outputFileAscii, num1); printInt(outputFileAscii, num2); printInt(outputFileAscii, num3); printInt(outputFileAscii, num4); printInt(outputFileAscii, num5); printInt(outputFileAscii, num6); printInt(outputFileAscii, num7); printInt(outputFileAscii, num8); printInt(outputFileAscii, num9); printInt(outputFileAscii, num10); numLines = numberLines(c1, numLines); numLines = numberLines(c2, numLines); numLines = numberLines(c3, numLines); numLines = numberLines(c4, numLines); numLines = numberLines(c5, numLines); numLines = numberLines(c6, numLines); numLines = numberLines(c7, numLines); numLines = numberLines(c8, numLines); numLines = numberLines(c9, numLines); numLines = numberLines(c10, numLines); printStats(outputFileStats, "Number Lines: ", numLines); numVowels = numberVowels(c1, numVowels); numVowels = numberVowels(c2, numVowels); numVowels = numberVowels(c3, numVowels); numVowels = numberVowels(c4, numVowels); numVowels = numberVowels(c5, numVowels); numVowels = numberVowels(c6, numVowels); numVowels = numberVowels(c7, numVowels); numVowels = numberVowels(c8, numVowels); numVowels = numberVowels(c9, numVowels); numVowels = numberVowels(c10, numVowels); printStats(outputFileStats, "Number Vowels: ", numVowels); numDigits = numberDigits(c1, numDigits); numDigits = numberDigits(c2, numDigits); numDigits = numberDigits(c3, numDigits); numDigits = numberDigits(c4, numDigits); numDigits = numberDigits(c5, numDigits); numDigits = numberDigits(c6, numDigits); numDigits = numberDigits(c7, numDigits); numDigits = numberDigits(c8, numDigits); numDigits = numberDigits(c9, numDigits); numDigits = numberDigits(c10, numDigits); printStats(outputFileStats, "Number Digits: ", numDigits); numAlpha = numberAlphas(c1, numAlpha); numAlpha = numberAlphas(c2, numAlpha); numAlpha = numberAlphas(c3, numAlpha); numAlpha = numberAlphas(c4, numAlpha); numAlpha = numberAlphas(c5, numAlpha); numAlpha = numberAlphas(c6, numAlpha); numAlpha = numberAlphas(c7, numAlpha); numAlpha = numberAlphas(c8, numAlpha); numAlpha = numberAlphas(c9, numAlpha); numAlpha = numberAlphas(c10, numAlpha); printStats(outputFileStats, "Number Alpha Characters: ", numAlpha); numLower = numberLowers(c1, numLower); numLower = numberLowers(c2, numLower); numLower = numberLowers(c3, numLower); numLower = numberLowers(c4, numLower); numLower = numberLowers(c5, numLower); numLower = numberLowers(c6, numLower); numLower = numberLowers(c7, numLower); numLower = numberLowers(c8, numLower); numLower = numberLowers(c9, numLower); numLower = numberLowers(c10, numLower); printStats(outputFileStats, "Number Lowercase Characters: ", numLower); numUpper = numberUppers(c1, numUpper); numUpper = numberUppers(c2, numUpper); numUpper = numberUppers(c3, numUpper); numUpper = numberUppers(c4, numUpper); numUpper = numberUppers(c5, numUpper); numUpper = numberUppers(c6, numUpper); numUpper = numberUppers(c7, numUpper); numUpper = numberUppers(c8, numUpper); numUpper = numberUppers(c9, numUpper); numUpper = numberUppers(c10, numUpper); printStats(outputFileStats, "Number Uppercase Characters: ", numUpper); numSpace = numberSpaces(c1, numSpace); numSpace = numberSpaces(c2, numSpace); numSpace = numberSpaces(c3, numSpace); numSpace = numberSpaces(c4, numSpace); numSpace = numberSpaces(c5, numSpace); numSpace = numberSpaces(c6, numSpace); numSpace = numberSpaces(c7, numSpace); numSpace = numberSpaces(c8, numSpace); numSpace = numberSpaces(c9, numSpace); numSpace = numberSpaces(c10, numSpace); printStats(outputFileStats, "Number Whitespaces: ", numSpace); numAlnum = numberAlnums(c1, numAlnum); numAlnum = numberAlnums(c2, numAlnum); numAlnum = numberAlnums(c3, numAlnum); numAlnum = numberAlnums(c4, numAlnum); numAlnum = numberAlnums(c5, numAlnum); numAlnum = numberAlnums(c6, numAlnum); numAlnum = numberAlnums(c7, numAlnum); numAlnum = numberAlnums(c8, numAlnum); numAlnum = numberAlnums(c9, numAlnum); numAlnum = numberAlnums(c10, numAlnum); printStats(outputFileStats, "Number Alphanumeric Characters: ", numAlnum); numPunct = numberPuncts(c1, numPunct); numPunct = numberPuncts(c2, numPunct); numPunct = numberPuncts(c3, numPunct); numPunct = numberPuncts(c4, numPunct); numPunct = numberPuncts(c5, numPunct); numPunct = numberPuncts(c6, numPunct); numPunct = numberPuncts(c7, numPunct); numPunct = numberPuncts(c8, numPunct); numPunct = numberPuncts(c9, numPunct); numPunct = numberPuncts(c10, numPunct); printStats(outputFileStats, "Number Punctuation Characters: ", numPunct); fclose(inputFile); fclose(outputFileAscii); fclose(outputFileStats); } return 0; }
int QgsNineCellFilter::processRaster( QProgressDialog* p ) { GDALAllRegister(); //open input file int xSize, ySize; GDALDatasetH inputDataset = openInputFile( xSize, ySize ); if ( inputDataset == NULL ) { return 1; //opening of input file failed } //output driver GDALDriverH outputDriver = openOutputDriver(); if ( outputDriver == 0 ) { return 2; } GDALDatasetH outputDataset = openOutputFile( inputDataset, outputDriver ); if ( outputDataset == NULL ) { return 3; //create operation on output file failed } //open first raster band for reading (operation is only for single band raster) GDALRasterBandH rasterBand = GDALGetRasterBand( inputDataset, 1 ); if ( rasterBand == NULL ) { GDALClose( inputDataset ); GDALClose( outputDataset ); return 4; } mInputNodataValue = GDALGetRasterNoDataValue( rasterBand, NULL ); GDALRasterBandH outputRasterBand = GDALGetRasterBand( outputDataset, 1 ); if ( outputRasterBand == NULL ) { GDALClose( inputDataset ); GDALClose( outputDataset ); return 5; } //try to set -9999 as nodata value GDALSetRasterNoDataValue( outputRasterBand, -9999 ); mOutputNodataValue = GDALGetRasterNoDataValue( outputRasterBand, NULL ); if ( ySize < 3 ) //we require at least three rows (should be true for most datasets) { GDALClose( inputDataset ); GDALClose( outputDataset ); return 6; } //keep only three scanlines in memory at a time float* scanLine1 = ( float * ) CPLMalloc( sizeof( float ) * xSize ); float* scanLine2 = ( float * ) CPLMalloc( sizeof( float ) * xSize ); float* scanLine3 = ( float * ) CPLMalloc( sizeof( float ) * xSize ); float* resultLine = ( float * ) CPLMalloc( sizeof( float ) * xSize ); if ( p ) { p->setMaximum( ySize ); } //values outside the layer extent (if the 3x3 window is on the border) are sent to the processing method as (input) nodata values for ( int i = 0; i < ySize; ++i ) { if ( p ) { p->setValue( i ); } if ( p && p->wasCanceled() ) { break; } if ( i == 0 ) { //fill scanline 1 with (input) nodata for the values above the first row and feed scanline2 with the first row for ( int a = 0; a < xSize; ++a ) { scanLine1[a] = mInputNodataValue; } GDALRasterIO( rasterBand, GF_Read, 0, 0, xSize, 1, scanLine2, xSize, 1, GDT_Float32, 0, 0 ); } else { //normally fetch only scanLine3 and release scanline 1 if we move forward one row CPLFree( scanLine1 ); scanLine1 = scanLine2; scanLine2 = scanLine3; scanLine3 = ( float * ) CPLMalloc( sizeof( float ) * xSize ); } if ( i == ySize - 1 ) //fill the row below the bottom with nodata values { for ( int a = 0; a < xSize; ++a ) { scanLine3[a] = mInputNodataValue; } } else { GDALRasterIO( rasterBand, GF_Read, 0, i + 1, xSize, 1, scanLine3, xSize, 1, GDT_Float32, 0, 0 ); } for ( int j = 0; j < xSize; ++j ) { if ( j == 0 ) { resultLine[j] = processNineCellWindow( &mInputNodataValue, &scanLine1[j], &scanLine1[j+1], &mInputNodataValue, &scanLine2[j], \ &scanLine2[j+1], &mInputNodataValue, &scanLine3[j], &scanLine3[j+1] ); } else if ( j == xSize - 1 ) { resultLine[j] = processNineCellWindow( &scanLine1[j-1], &scanLine1[j], &mInputNodataValue, &scanLine2[j-1], &scanLine2[j], \ &mInputNodataValue, &scanLine3[j-1], &scanLine3[j], &mInputNodataValue ); } else { resultLine[j] = processNineCellWindow( &scanLine1[j-1], &scanLine1[j], &scanLine1[j+1], &scanLine2[j-1], &scanLine2[j], \ &scanLine2[j+1], &scanLine3[j-1], &scanLine3[j], &scanLine3[j+1] ); } } GDALRasterIO( outputRasterBand, GF_Write, 0, i, xSize, 1, resultLine, xSize, 1, GDT_Float32, 0, 0 ); } if ( p ) { p->setValue( ySize ); } CPLFree( resultLine ); CPLFree( scanLine1 ); CPLFree( scanLine2 ); CPLFree( scanLine3 ); GDALClose( inputDataset ); if ( p && p->wasCanceled() ) { //delete the dataset without closing (because it is faster) GDALDeleteDataset( outputDriver, mOutputFile.toLocal8Bit().data() ); return 7; } GDALClose( outputDataset ); return 0; }