コード例 #1
0
void Raster::CSVWriteVectorValues(OGRLayer * poLayer, const char * psFieldName, const char * sRasterOutputPath){

    // use the filename with CSV added onto the end.
    QFileInfo sOutputFileInfo(sRasterOutputPath);
    QDir sNewDir = QDir(sOutputFileInfo.absolutePath());
    QString sCSVFullPath = sNewDir.filePath(sOutputFileInfo.completeBaseName() + ".csv");

    QFile csvFile(sCSVFullPath);

    if (csvFile.open(QFile::WriteOnly|QFile::Truncate))
    {
      QTextStream stream(&csvFile);

      // Write CSV file header
      stream << "\"index\", " << "\""<< psFieldName << "\""<< "\n"; // this writes first line with two columns

      OGRFeature *poFeature;
      poLayer->ResetReading();
      poLayer->SetSpatialFilter(NULL);
      while( (poFeature = poLayer->GetNextFeature()) != NULL){
          const char * sFieldVal = poFeature->GetFieldAsString(psFieldName);
          //  write line to file
          stream << poFeature->GetFID() << ", " << "\"" << sFieldVal << "\"" << "\n"; // this writes first line with two columns
          OGRFeature::DestroyFeature( poFeature );
      }

      csvFile.close();
    }
    return;

}
コード例 #2
0
QString ImportAnnotationsFromCSVDialog::checkInputGroup(bool silent) {
    QString inputFile = readFileName->text();
    if (inputFile.isEmpty()) {
        if (!silent) {
            QMessageBox::critical(this, L10N::errorTitle(), tr("Enter input CSV file name"));
            readFileName->setFocus();
        }
        return QString();
    }
    QFileInfo csvFile(inputFile);
    if (!csvFile.exists() || !csvFile.isFile()) {
        if (!silent) {
            QMessageBox::critical(this, L10N::errorTitle(), L10N::errorFileNotFound(inputFile));
            readFileName->setFocus();
        }
        return QString();
    }

    if (!csvFile.isReadable()) {
        if (!silent) {
            QMessageBox::critical(this, L10N::errorTitle(), L10N::errorOpeningFileRead(inputFile));
            readFileName->setFocus();
        }
        return QString();
    }
    return csvFile.canonicalFilePath();
}
コード例 #3
0
ファイル: mitkTransform.cpp プロジェクト: zomboir/MITK
  void Transform::FromCSVFile(const std::string& file)
  {
    std::ifstream csvFile (file.c_str());
    endoAssert ( csvFile.fail() == false );

    mitk::Transform::Pointer transform = mitk::Transform::New();
    vnl_matrix_fixed<mitk::ScalarType, 4, 4> mat;
    std::string line;
    mitk::ScalarType d = 0.0f;
    int row=0,column = 0;

    while (std::getline (csvFile, line))
    {
      std::istringstream linestream(line);
      std::string item;
      column = 0;
      while (std::getline (linestream, item, ','))
      {
        std::istringstream number;
        number.str(item);
        number >> d;
        mat(row, column) = d;
        ++column;
      }
      ++row;
    }
    endoAssert( row == 4 && column == 4 );
    transform->SetMatrix( mat );

    this->SetNavigationData( transform->GetNavigationData() );
    // modified is called in SetNavigationData
  }
コード例 #4
0
int main(int argc, char **argv)
{

  std::string csvFile (argv[1]);


  CSVGrainDataReader reader;
  reader.setFileName(csvFile);
  int err = reader.readFile();
  if (err < 0)
  {
    std::cout << "Error occurred reading the CSV Grain Data file" << std::endl;
    return EXIT_FAILURE;
  }

  // If the 'reader' object goes out of scope then all the pointers are going
  // to be invalid as the CSVGrainDataReader manages the memory for you.
  int* grain_ids = reader.getGrainIdPointer();
  if (grain_ids > 0) {

  }
  std::cout << "Success Reading the Grain Data File" << std::endl;


  return EXIT_SUCCESS;
}
コード例 #5
0
QString ItemsList::setPath()
{
    QString csvWritePath = "";
    csvWritePath = QFileDialog::getExistingDirectory( 0 , tr("Wybierz folder"), QDir::homePath() );

    QFile csvFile( QDir::homePath()+"/schedule.csv" );
    if ( !csvFile.open(QIODevice::WriteOnly | QIODevice::Append) )
        {
            runMsg("Nie można otworzyć pliku pomocniczego schedule.csv.");
            return QString("");
        }

    QTextStream out( &csvFile );
    out << csvWritePath;
    csvFile.close();

    return csvWritePath;
}
コード例 #6
0
bool appReportCsv::WriteCurveCsv(QString FileName,sFrqValues *FrqValues, QVector<double> *DataFrq, QVector<double> *DatadBm)
{
 bool done = false;
 QString frqValue;
 QString dBmValue;

 if(DataFrq && DatadBm && !FileName.isEmpty())
 {
  // Open File
  QFile       csvFile(FileName);
  QTextStream csvStream(&csvFile);

  csvStream.setRealNumberPrecision(15);

  if(csvFile.open(QIODevice::WriteOnly))
  {
   //Generate and write Header
   csvStream << "Date           " << "," << QDateTime::currentDateTime().toString()  << "\r\n";
   csvStream << "FStart    [MHz]" << "," << (double)FrqValues->FrqStart              << "\r\n";
   csvStream << "FStop     [MHz]" << "," << (double)FrqValues->FrqStop               << "\r\n";
   csvStream << "FStepWidth[kHz]" << "," << (double)FrqValues->FrqStepWidth          << "\r\n";
   csvStream << "   MHz         " << ","  << "    dBm        "                       << "\r\n";
   csvStream << "---------------" << ","  << "---------------"                       << "\r\n";
   if(DataFrq->count() == DatadBm->count())
   {
    for(int index=0;index<DataFrq->count();index++)
    {
     csvStream << (double)DataFrq->at(index) << ","  << (double)DatadBm->at(index) << "\r\n";
    };

    done = true;
   };
  };
 };

 return(done);
}
コード例 #7
0
ファイル: exporter.cpp プロジェクト: braselectron/openhantek
/// \brief Print the document (May be a file too)
bool Exporter::doExport() {
	if(this->format < EXPORT_FORMAT_CSV) {
		// Choose the color values we need
		DsoSettingsColorValues *colorValues;
		if(this->format == EXPORT_FORMAT_IMAGE && this->settings->view.screenColorImages)
			colorValues = &(this->settings->view.color.screen);
		else
			colorValues = &(this->settings->view.color.print);
		
		QPaintDevice *paintDevice;
		
		if(this->format < EXPORT_FORMAT_IMAGE) {
			// We need a QPrinter for printing, pdf- and ps-export
			paintDevice = new QPrinter(QPrinter::HighResolution);
			static_cast<QPrinter *>(paintDevice)->setOrientation(this->settings->view.zoom ? QPrinter::Portrait : QPrinter::Landscape);
			static_cast<QPrinter *>(paintDevice)->setPageMargins(20, 20, 20, 20, QPrinter::Millimeter);
			
			if(this->format == EXPORT_FORMAT_PRINTER) {
				// Show the printing dialog
				QPrintDialog dialog(static_cast<QPrinter *>(paintDevice), static_cast<QWidget *>(this->parent()));
				dialog.setWindowTitle(tr("Print oscillograph"));
				if(dialog.exec() != QDialog::Accepted) {
					delete paintDevice;
					return false;
				}
			}
			else {
				// Configure the QPrinter
				static_cast<QPrinter *>(paintDevice)->setOutputFileName(this->filename);
				static_cast<QPrinter *>(paintDevice)->setOutputFormat((this->format == EXPORT_FORMAT_PDF) ? QPrinter::PdfFormat : QPrinter::PostScriptFormat);
			}
		}
		else {
			// We need a QPixmap for image-export
			paintDevice = new QPixmap(this->settings->options.imageSize);
			static_cast<QPixmap *>(paintDevice)->fill(colorValues->background);
		}
		
		// Create a painter for our device
		QPainter painter(paintDevice);
		
		// Get line height
		QFont font;
		QFontMetrics fontMetrics(font, paintDevice);
		double lineHeight = fontMetrics.height();
		
		painter.setBrush(Qt::SolidPattern);
		
		this->dataAnalyzer->mutex()->lock();
		
		// Draw the settings table
		double stretchBase = (double) (paintDevice->width() - lineHeight * 10) / 4;
		
		// Print trigger details
		painter.setPen(colorValues->voltage[this->settings->scope.trigger.source]);
		QString levelString = Helper::valueToString(this->settings->scope.voltage[this->settings->scope.trigger.source].trigger, Helper::UNIT_VOLTS, 3);
		QString pretriggerString = tr("%L1%").arg((int) (this->settings->scope.trigger.position * 100 + 0.5));
		painter.drawText(QRectF(0, 0, lineHeight * 10, lineHeight), tr("%1  %2  %3  %4").arg(this->settings->scope.voltage[this->settings->scope.trigger.source].name, Dso::slopeString(this->settings->scope.trigger.slope), levelString, pretriggerString));
		
		// Print sample count
		painter.setPen(colorValues->text);
		painter.drawText(QRectF(lineHeight * 10, 0, stretchBase, lineHeight), tr("%1 S").arg(this->dataAnalyzer->sampleCount()), QTextOption(Qt::AlignRight));
		// Print samplerate
		painter.drawText(QRectF(lineHeight * 10 + stretchBase, 0, stretchBase, lineHeight), Helper::valueToString(this->settings->scope.horizontal.samplerate, Helper::UNIT_SAMPLES) + tr("/s"), QTextOption(Qt::AlignRight));
		// Print timebase
		painter.drawText(QRectF(lineHeight * 10 + stretchBase * 2, 0, stretchBase, lineHeight), Helper::valueToString(this->settings->scope.horizontal.timebase, Helper::UNIT_SECONDS, 0) + tr("/div"), QTextOption(Qt::AlignRight));
		// Print frequencybase
		painter.drawText(QRectF(lineHeight * 10 + stretchBase * 3, 0, stretchBase, lineHeight), Helper::valueToString(this->settings->scope.horizontal.frequencybase, Helper::UNIT_HERTZ, 0) + tr("/div"), QTextOption(Qt::AlignRight));
		
		// Draw the measurement table
		stretchBase = (double) (paintDevice->width() - lineHeight * 6) / 10;
		int channelCount = 0;
		for(int channel = this->settings->scope.voltage.count() - 1; channel >= 0; channel--) {
			if((this->settings->scope.voltage[channel].used || this->settings->scope.spectrum[channel].used) && this->dataAnalyzer->data(channel)) {
				++channelCount;
				double top = (double) paintDevice->height() - channelCount * lineHeight;
				
				// Print label
				painter.setPen(colorValues->voltage[channel]);
				painter.drawText(QRectF(0, top, lineHeight * 4, lineHeight), this->settings->scope.voltage[channel].name);
				// Print coupling/math mode
				if((unsigned int) channel < this->settings->scope.physicalChannels)
					painter.drawText(QRectF(lineHeight * 4, top, lineHeight * 2, lineHeight), Dso::couplingString((Dso::Coupling) this->settings->scope.voltage[channel].misc));
				else
					painter.drawText(QRectF(lineHeight * 4, top, lineHeight * 2, lineHeight), Dso::mathModeString((Dso::MathMode) this->settings->scope.voltage[channel].misc));
				
				// Print voltage gain
				painter.drawText(QRectF(lineHeight * 6, top, stretchBase * 2, lineHeight), Helper::valueToString(this->settings->scope.voltage[channel].gain, Helper::UNIT_VOLTS, 0) + tr("/div"), QTextOption(Qt::AlignRight));
				// Print spectrum magnitude
				painter.setPen(colorValues->spectrum[channel]);
				painter.drawText(QRectF(lineHeight * 6 + stretchBase * 2, top, stretchBase * 2, lineHeight), Helper::valueToString(this->settings->scope.spectrum[channel].magnitude, Helper::UNIT_DECIBEL, 0) + tr("/div"), QTextOption(Qt::AlignRight));
				
				// Amplitude string representation (4 significant digits)
				painter.setPen(colorValues->text);
				painter.drawText(QRectF(lineHeight * 6 + stretchBase * 4, top, stretchBase * 3, lineHeight), Helper::valueToString(this->dataAnalyzer->data(channel)->amplitude, Helper::UNIT_VOLTS, 4), QTextOption(Qt::AlignRight));
				// Frequency string representation (5 significant digits)
				painter.drawText(QRectF(lineHeight * 6 + stretchBase * 7, top, stretchBase * 3, lineHeight), Helper::valueToString(this->dataAnalyzer->data(channel)->frequency, Helper::UNIT_HERTZ, 5), QTextOption(Qt::AlignRight));
			}
		}
		
		// Draw the marker table
		double scopeHeight;
		stretchBase = (double) (paintDevice->width() - lineHeight * 10) / 4;
		painter.setPen(colorValues->text);
		
		// Calculate variables needed for zoomed scope
		double divs = fabs(this->settings->scope.horizontal.marker[1] - this->settings->scope.horizontal.marker[0]);
		double time = divs * this->settings->scope.horizontal.timebase;
		double zoomFactor = DIVS_TIME / divs;
		double zoomOffset = (this->settings->scope.horizontal.marker[0] + this->settings->scope.horizontal.marker[1]) / 2;
		
		if(this->settings->view.zoom) {
			scopeHeight = (double) (paintDevice->height() - (channelCount + 5) * lineHeight) / 2;
			double top = 2.5 * lineHeight + scopeHeight;
			
			painter.drawText(QRectF(0, top, stretchBase, lineHeight), tr("Zoom x%L1").arg(DIVS_TIME / divs, -1, 'g', 3));
			
			painter.drawText(QRectF(lineHeight * 10, top, stretchBase, lineHeight), Helper::valueToString(time, Helper::UNIT_SECONDS, 4), QTextOption(Qt::AlignRight));
			painter.drawText(QRectF(lineHeight * 10 + stretchBase, top, stretchBase, lineHeight), Helper::valueToString(1.0 / time, Helper::UNIT_HERTZ, 4), QTextOption(Qt::AlignRight));
			
			painter.drawText(QRectF(lineHeight * 10 + stretchBase * 2, top, stretchBase, lineHeight), Helper::valueToString(time / DIVS_TIME, Helper::UNIT_SECONDS, 3) + tr("/div"), QTextOption(Qt::AlignRight));
			painter.drawText(QRectF(lineHeight * 10 + stretchBase * 3, top, stretchBase, lineHeight), Helper::valueToString(divs  * this->settings->scope.horizontal.frequencybase / DIVS_TIME, Helper::UNIT_HERTZ, 3) + tr("/div"), QTextOption(Qt::AlignRight));
		}
		else {
			scopeHeight = (double) paintDevice->height() - (channelCount + 4) * lineHeight;
			double top = 2.5 * lineHeight + scopeHeight;
			
			painter.drawText(QRectF(0, top, stretchBase, lineHeight), tr("Marker 1/2"));
			
			painter.drawText(QRectF(lineHeight * 10, top, stretchBase * 2, lineHeight), Helper::valueToString(time, Helper::UNIT_SECONDS, 4), QTextOption(Qt::AlignRight));
			painter.drawText(QRectF(lineHeight * 10 + stretchBase * 2, top, stretchBase * 2, lineHeight), Helper::valueToString(1.0 / time, Helper::UNIT_HERTZ, 4), QTextOption(Qt::AlignRight));
		}
		
		// Set DIVS_TIME x DIVS_VOLTAGE matrix for oscillograph
		painter.setMatrix(QMatrix((paintDevice->width() - 1) / DIVS_TIME, 0, 0, -(scopeHeight - 1) / DIVS_VOLTAGE, (double) (paintDevice->width() - 1) / 2, (scopeHeight - 1) / 2 + lineHeight * 1.5), false);
		
		// Draw the graphs
		painter.setRenderHint(QPainter::Antialiasing);
		painter.setBrush(Qt::NoBrush);
		
		for(int zoomed = 0; zoomed < (this->settings->view.zoom ? 2 : 1); ++zoomed) {
			switch(this->settings->scope.horizontal.format) {
				case Dso::GRAPHFORMAT_TY:
					// Add graphs for channels
					for(int channel = 0 ; channel < this->settings->scope.voltage.count(); ++channel) {
						if(this->settings->scope.voltage[channel].used && this->dataAnalyzer->data(channel)) {
							painter.setPen(colorValues->voltage[channel]);
							
							// What's the horizontal distance between sampling points?
							double horizontalFactor = this->dataAnalyzer->data(channel)->samples.voltage.interval / this->settings->scope.horizontal.timebase;
							// How many samples are visible?
							double centerPosition, centerOffset;
							if(zoomed) {
								centerPosition = (zoomOffset + DIVS_TIME / 2) / horizontalFactor;
								centerOffset = DIVS_TIME / horizontalFactor / zoomFactor / 2;
							}
							else {
								centerPosition = DIVS_TIME / 2 / horizontalFactor;
								centerOffset = DIVS_TIME / horizontalFactor / 2;
							}
							unsigned int firstPosition = qMax((int) (centerPosition - centerOffset), 0);
							unsigned int lastPosition = qMin((int) (centerPosition + centerOffset), (int) this->dataAnalyzer->data(channel)->samples.voltage.sample.size() - 1);
							
							// Draw graph
							QPointF *graph = new QPointF[lastPosition - firstPosition + 1];
							
							for(unsigned int position = firstPosition; position <= lastPosition; ++position)
								graph[position - firstPosition] = QPointF(position * horizontalFactor - DIVS_TIME / 2, this->dataAnalyzer->data(channel)->samples.voltage.sample[position] / this->settings->scope.voltage[channel].gain + this->settings->scope.voltage[channel].offset);
							
							painter.drawPolyline(graph, lastPosition - firstPosition + 1);
							delete[] graph;
						}
					}
				
					// Add spectrum graphs
					for (int channel = 0; channel < this->settings->scope.spectrum.count(); ++channel) {
						if(this->settings->scope.spectrum[channel].used && this->dataAnalyzer->data(channel)) {
							painter.setPen(colorValues->spectrum[channel]);
							
							// What's the horizontal distance between sampling points?
							double horizontalFactor = this->dataAnalyzer->data(channel)->samples.spectrum.interval / this->settings->scope.horizontal.frequencybase;
							// How many samples are visible?
							double centerPosition, centerOffset;
							if(zoomed) {
								centerPosition = (zoomOffset + DIVS_TIME / 2) / horizontalFactor;
								centerOffset = DIVS_TIME / horizontalFactor / zoomFactor / 2;
							}
							else {
								centerPosition = DIVS_TIME / 2 / horizontalFactor;
								centerOffset = DIVS_TIME / horizontalFactor / 2;
							}
							unsigned int firstPosition = qMax((int) (centerPosition - centerOffset), 0);
							unsigned int lastPosition = qMin((int) (centerPosition + centerOffset), (int) this->dataAnalyzer->data(channel)->samples.spectrum.sample.size() - 1);
							
							// Draw graph
							QPointF *graph = new QPointF[lastPosition - firstPosition + 1];
							
							for(unsigned int position = firstPosition; position <= lastPosition; ++position)
								graph[position - firstPosition] = QPointF(position * horizontalFactor - DIVS_TIME / 2, this->dataAnalyzer->data(channel)->samples.spectrum.sample[position] / this->settings->scope.spectrum[channel].magnitude + this->settings->scope.spectrum[channel].offset);
							
							painter.drawPolyline(graph, lastPosition - firstPosition + 1);
							delete[] graph;
						}
					}
					break;
					
				case Dso::GRAPHFORMAT_XY:
					break;
				
				default:
					break;
			}
			
			// Set DIVS_TIME / zoomFactor x DIVS_VOLTAGE matrix for zoomed oscillograph
			painter.setMatrix(QMatrix((paintDevice->width() - 1) / DIVS_TIME * zoomFactor, 0, 0, -(scopeHeight - 1) / DIVS_VOLTAGE, (double) (paintDevice->width() - 1) / 2 - zoomOffset * zoomFactor * (paintDevice->width() - 1) / DIVS_TIME, (scopeHeight - 1) * 1.5 + lineHeight * 4), false);
		}
		
		this->dataAnalyzer->mutex()->unlock();
		
		// Draw grids
		painter.setRenderHint(QPainter::Antialiasing, false);
		for(int zoomed = 0; zoomed < (this->settings->view.zoom ? 2 : 1); ++zoomed) {
			// Set DIVS_TIME x DIVS_VOLTAGE matrix for oscillograph
			painter.setMatrix(QMatrix((paintDevice->width() - 1) / DIVS_TIME, 0, 0, -(scopeHeight - 1) / DIVS_VOLTAGE, (double) (paintDevice->width() - 1) / 2, (scopeHeight - 1) * (zoomed + 0.5) + lineHeight * 1.5 + lineHeight * 2.5 * zoomed), false);
			
			// Grid lines
			painter.setPen(colorValues->grid);
			
			if(this->format < EXPORT_FORMAT_IMAGE) {
				// Draw vertical lines
				for(int div = 1; div < DIVS_TIME / 2; ++div) {
					for(int dot = 1; dot < DIVS_VOLTAGE / 2 * 5; ++dot) {
						painter.drawLine(QPointF((double) -div - 0.02, (double) -dot / 5), QPointF((double) -div + 0.02, (double) -dot / 5));
						painter.drawLine(QPointF((double) -div - 0.02, (double) dot / 5), QPointF((double) -div + 0.02, (double) dot / 5));
						painter.drawLine(QPointF((double) div - 0.02, (double) -dot / 5), QPointF((double) div + 0.02, (double) -dot / 5));
						painter.drawLine(QPointF((double) div - 0.02, (double) dot / 5), QPointF((double) div + 0.02, (double) dot / 5));
					}
				}
				// Draw horizontal lines
				for(int div = 1; div < DIVS_VOLTAGE / 2; ++div) {
					for(int dot = 1; dot < DIVS_TIME / 2 * 5; ++dot) {
						painter.drawLine(QPointF((double) -dot / 5, (double) -div - 0.02), QPointF((double) -dot / 5, (double) -div + 0.02));
						painter.drawLine(QPointF((double) dot / 5, (double) -div - 0.02), QPointF((double) dot / 5, (double) -div + 0.02));
						painter.drawLine(QPointF((double) -dot / 5, (double) div - 0.02), QPointF((double) -dot / 5, (double) div + 0.02));
						painter.drawLine(QPointF((double) dot / 5, (double) div - 0.02), QPointF((double) dot / 5, (double) div + 0.02));
					}
				}
			}
			else {
				// Draw vertical lines
				for(int div = 1; div < DIVS_TIME / 2; ++div) {
					for(int dot = 1; dot < DIVS_VOLTAGE / 2 * 5; ++dot) {
						painter.drawPoint(QPointF(-div, (double) -dot / 5));
						painter.drawPoint(QPointF(-div, (double) dot / 5));
						painter.drawPoint(QPointF(div, (double) -dot / 5));
						painter.drawPoint(QPointF(div, (double) dot / 5));
					}
				}
				// Draw horizontal lines
				for(int div = 1; div < DIVS_VOLTAGE / 2; ++div) {
					for(int dot = 1; dot < DIVS_TIME / 2 * 5; ++dot) {
						if(dot % 5 == 0)
							continue;                       // Already done by vertical lines
						painter.drawPoint(QPointF((double) -dot / 5, -div));
						painter.drawPoint(QPointF((double) dot / 5, -div));
						painter.drawPoint(QPointF((double) -dot / 5, div));
						painter.drawPoint(QPointF((double) dot / 5, div));
					}
				}
			}
				
			// Axes
			painter.setPen(colorValues->axes);
			painter.drawLine(QPointF(-DIVS_TIME / 2, 0), QPointF(DIVS_TIME / 2, 0));
			painter.drawLine(QPointF(0, -DIVS_VOLTAGE / 2), QPointF(0, DIVS_VOLTAGE / 2));
			for(double div = 0.2; div <= DIVS_TIME / 2; div += 0.2) {
				painter.drawLine(QPointF(div, -0.05), QPointF(div, 0.05));
				painter.drawLine(QPointF(-div, -0.05), QPointF(-div, 0.05));
			}
			for(double div = 0.2; div <= DIVS_VOLTAGE / 2; div += 0.2) {
				painter.drawLine(QPointF(-0.05, div), QPointF(0.05, div));
				painter.drawLine(QPointF(-0.05, -div), QPointF(0.05, -div));
			}
			
			// Borders
			painter.setPen(colorValues->border);
			painter.drawRect(QRectF(-DIVS_TIME / 2, -DIVS_VOLTAGE / 2, DIVS_TIME, DIVS_VOLTAGE));
		}
		
		painter.end();
		
		if(this->format == EXPORT_FORMAT_IMAGE)
			static_cast<QPixmap *>(paintDevice)->save(this->filename);
		
		delete paintDevice;
		
		return true;
	}
	else {
		QFile csvFile(this->filename);
		if(!csvFile.open(QIODevice::WriteOnly | QIODevice::Text))
			return false;
		
		QTextStream csvStream(&csvFile);
		
		for(int channel = 0 ; channel < this->settings->scope.voltage.count(); ++channel) {
			if(this->dataAnalyzer->data(channel)) {
				if(this->settings->scope.voltage[channel].used) {
					// Start with channel name and the sample interval
					csvStream << "\"" << this->settings->scope.voltage[channel].name << "\"," << this->dataAnalyzer->data(channel)->samples.voltage.interval;
					
					// And now all sample values in volts
					for(unsigned int position = 0; position < this->dataAnalyzer->data(channel)->samples.voltage.sample.size(); ++position)
						csvStream << "," << this->dataAnalyzer->data(channel)->samples.voltage.sample[position];
					
					// Finally a newline
					csvStream << '\n';
				}
				
				if(this->settings->scope.spectrum[channel].used) {
					// Start with channel name and the sample interval
					csvStream << "\"" << this->settings->scope.spectrum[channel].name << "\"," << this->dataAnalyzer->data(channel)->samples.spectrum.interval;
					
					// And now all magnitudes in dB
					for(unsigned int position = 0; position < this->dataAnalyzer->data(channel)->samples.spectrum.sample.size(); ++position)
						csvStream << "," << this->dataAnalyzer->data(channel)->samples.spectrum.sample[position];
					
					// Finally a newline
					csvStream << '\n';
				}
			}
		}
		
		csvFile.close();
		
		return true;
	}
}
コード例 #8
0
ファイル: main.cpp プロジェクト: BonnieBBS/TrainStation
int main()
{
    readInAllCSVs();
    checkAllVectors();
    std::cout << "All vectors with ID numbers are checked." << std::endl;
    //showVector(allTrainsVec);
    std::ofstream csvFile ("auto_solution.csv");
    //std::cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << std::endl;
    //Departure d1 = allDeparturesVec[0];
    //d1.print();
    //Departure de = allDeparturesVec[allDeparturesVec.size()-1];
    //de.print();
    //std::cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << std::endl;
    if(csvFile.is_open())
    {
        csvFile << "Train;Time;Event type;Resource;Gate;Complement;\n";
        
        /* The GENERAL IDEA !!!!!!!!!!!!!
        while(wholeTime.ticksAway())
        {
        for(int i=0; i<allTrainsVec.size(); i++)
        {
            Train& train = allTrainsVec[i];
            for each train.currentResource.neightResource
                if( train.check(Resource resource) )
                    train.transmitTo(resource);
        }
        allTrainsVec.sort();
        }*/

        for(int i=0; i<allArrivalsVec.size(); i++)
        {
            Arrival &tempArr = allArrivalsVec[i];

            Train &tempTrain = allTrainsVec[i];

            printArrival2Platform(tempArr, i, csvFile);

            //Train& tempTrain = allTrainsVec[i];

            for(int j=0; j<allDeparturesVec.size(); j++)
            {
                Departure& tempDep = allDeparturesVec[j];
                if(tempDep.assignedTrainID) continue;
                if(tempArr.category != tempDep.compatibleCategory) continue;
                if(!tempArr.time.isEarlierThan(tempDep.time)) continue;////
                if(tempArr.remDBM<tempDep.reqDBM && tempDep.reqTBM.isEarlierThan(tempArr.remTBM) ) continue;
                tempDep.assignedTrainID = tempArr.id;
                tempTrain.departureID = tempDep.id;
                break;
            }  
            if(tempTrain.departureID != -1)
            {
                Departure& theAssignedDep = allDeparturesVec[tempTrain.departureID];
                printPlatform2Departure(tempTrain, theAssignedDep, csvFile);
            }
            else
            {
                for(int j=0; j<allDeparturesVec.size(); j++)
                {
                    Departure& tempDep = allDeparturesVec[j];
                    if(tempDep.assignedTrainID) continue;
                    tempDep.assignedTrainID = tempArr.id;
                    tempTrain.departureID = tempDep.id;
                    break;
                }
                Departure& theAssignedDep = allDeparturesVec[tempTrain.departureID-1];
                //if(tempTrain.id==1234) 
                //{
                //    std::cout << tempTrain.id << std::endl;
                //    std::cout << tempTrain.departureID << std::endl;
                //    theAssignedDep.print();
                //    printPlatform2Departure(tempTrain, theAssignedDep, std::cout);
                //}
                //if(tempTrain.id==1235) 
                //{
                //    std::cout << tempTrain.id << std::endl;
                //    std::cout << tempTrain.departureID << std::endl;
                //    theAssignedDep.print();
                //    printPlatform2Departure(tempTrain, theAssignedDep, std::cout);
                //}
                printPlatform2Departure(tempTrain, theAssignedDep, csvFile);
                /*
                   std::cout << i << std::endl;
                   csvFile << "Train" << i+1 << ";d7 23:59:59;EnterResource;TrackGroup7;;;" << std::endl;
                   csvFile << "Train" << i+1 << ";d7 23:59:59;Departure;TrackGroup7;;Dep1906;" << std::endl;
                   csvFile << "Train" << i+1 << ";d7 23:59:59;ExitResource;TrackGroup7;;;" << std::endl;
                   csvFile << "Train" << i+1 << ";d7 23:59:59;ExitSystem;TrackGroup7;;;" << std::endl;
                   */
            }
        }
        for(int i=allArrivalsVec.size(); i<allTrainsVec.size(); i++)
        {
            Train &temp = allTrainsVec[i];

            printInitialInTrain2Platform(temp, csvFile);

            csvFile << "Train" << i+1 << ";d7 23:59:59;EnterResource;TrackGroup7;;;" << std::endl;
            csvFile << "Train" << i+1 << ";d7 23:59:59;ExitResource;TrackGroup7;;;" << std::endl;
            csvFile << "Train" << i+1 << ";d7 23:59:59;ExitSystem;TrackGroup7;;;" << std::endl;
        }
    }

    return 0;
}
コード例 #9
0
int main(int argc, const char** argv) {
    
    boost::program_options::options_description desc("Allowed options");
    desc.add_options()
        ("help", "produce help message")
        ("input", boost::program_options::value<std::string>(), "the folder to process")
        ("lambda", boost::program_options::value<double>()->default_value(0.5), "lambda")
        ("sigma", boost::program_options::value<double>()->default_value(5.0), "sigma")
        ("four-connected", "use 4-connected")
        ("superpixels", boost::program_options::value<int>()->default_value(400), "number of superpixels")
        ("time", boost::program_options::value<std::string>(), "time the algorithm and save results to the given directory")
        ("process", "show additional information while processing")
        ("csv", "save segmentation as CSV file")
        ("contour", "save contour image of segmentation")
        ("mean", "save mean colored image of segmentation")
        ("output", boost::program_options::value<std::string>()->default_value("output"), "specify the output directory (default is ./output)");

    boost::program_options::positional_options_description positionals;
    positionals.add("input", 1);
    
    boost::program_options::variables_map parameters;
    boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(desc).positional(positionals).run(), parameters);
    boost::program_options::notify(parameters);

    if (parameters.find("help") != parameters.end()) {
        std::cout << desc << std::endl;
        return 1;
    }
    
    boost::filesystem::path outputDir(parameters["output"].as<std::string>());
    if (!boost::filesystem::is_directory(outputDir)) {
        boost::filesystem::create_directory(outputDir);
    }
    
    boost::filesystem::path inputDir(parameters["input"].as<std::string>());
    if (!boost::filesystem::is_directory(inputDir)) {
        std::cout << "Image directory not found ..." << std::endl;
        return 1;
    }
    
    bool process = false;
    if (parameters.find("process") != parameters.end()) {
        process = true;
    }
    
    std::vector<boost::filesystem::path> pathVector;
    std::vector<boost::filesystem::path> images;
    
    std::copy(boost::filesystem::directory_iterator(inputDir), boost::filesystem::directory_iterator(), std::back_inserter(pathVector));

    std::sort(pathVector.begin(), pathVector.end());
    
    std::string extension;
    int count = 0;
    
    for (std::vector<boost::filesystem::path>::const_iterator iterator (pathVector.begin()); iterator != pathVector.end(); ++iterator) {
        if (boost::filesystem::is_regular_file(*iterator)) {
            
            // Check supported file extensions.
            extension = iterator->extension().string();
            std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower);
            
            if (extension == ".png" || extension == ".jpg" || extension == ".jpeg") {
                images.push_back(*iterator);
                
                if (process == true) {
                    std::cout << "Found " << iterator->string() << " ..." << std::endl;
                }
                
                ++count;
            }
        }
    }
    
    std::cout << count << " images total ..." << std::endl;
    
    boost::timer timer;
    double totalTime = 0;
    
    int eightConnected = 1;
    if (parameters.find("four-connected") != parameters.end()) {
        eightConnected = 0;
    }
    
    int superpixels = parameters["superpixels"].as<int>();
    int kernel = 0;
    double lambda = parameters["lambda"].as<double>();
    double sigma = parameters["sigma"].as<double>();
    MERCLazyGreedy merc;
    
    cv::Mat time(images.size(), 2, cv::DataType<double>::type);
    for(std::vector<boost::filesystem::path>::iterator iterator = images.begin(); iterator != images.end(); ++iterator) {
        cv::Mat mat = cv::imread(iterator->string());
        
        Image<RGBMap> inputImage;
        MERCInputImage<RGBMap> input;

        inputImage.Resize(mat.cols, mat.rows, false);

        for (int i = 0; i < mat.rows; ++i) {
            for (int j = 0; j < mat.cols; ++j) {
                RGBMap color((int) mat.at<cv::Vec3b>(i, j)[2], (int) mat.at<cv::Vec3b>(i, j)[1], (int) mat.at<cv::Vec3b>(i, j)[0]);
                inputImage.Access(j, i) = color;
            }
        }

        input.ReadImage(&inputImage, eightConnected);
		
        timer.restart();
        int index = std::distance(images.begin(), iterator);
        
        merc.ClusteringTreeIF(input.nNodes_, input, kernel, sigma*mat.channels(), lambda*1.0*superpixels, superpixels);
        
        time.at<double>(index, 1) = timer.elapsed();
        time.at<double>(index, 0) = index + 1;
        totalTime += time.at<double>(index, 1);
        
	vector<int> label = MERCOutputImage::DisjointSetToLabel(merc.disjointSet_);
        
        int** labels = new int*[mat.rows];
        for (int i = 0; i < mat.rows; ++i) {
            labels[i] = new int[mat.cols];
            
            for (int j = 0; j < mat.cols; ++j) {
                labels[i][j] = label[j + i*mat.cols];
            }
        }
        
        Integrity::relabel(labels, mat.rows, mat.cols);
        
        boost::filesystem::path extension = iterator->filename().extension();
        int position = iterator->filename().string().find(extension.string());
        
        if (parameters.find("contour") != parameters.end()) {
            
            std::string store = outputDir.string() + DIRECTORY_SEPARATOR + iterator->filename().string().substr(0, position) + "_contours.png";
            
            int bgr[] = {0, 0, 204};
            cv::Mat contourImage = Draw::contourImage(labels, mat, bgr);
            cv::imwrite(store, contourImage);
            
            if (process == true) {
                std::cout << "Image " << iterator->string() << " with contours saved to " << store << " ..." << std::endl;
            }
        }

        if (parameters.find("mean") != parameters.end()) {
            
            std::string store = outputDir.string() + DIRECTORY_SEPARATOR + iterator->filename().string().substr(0, position) + "_mean.png";

            cv::Mat meanImage = Draw::meanImage(labels, mat);
            cv::imwrite(store, meanImage);

            if (process == true) {
                std::cout << "Image " << iterator->string() << " with mean colors saved to " << store << " ..." << std::endl;
            }
        }

        if (parameters.find("csv") != parameters.end()) {
            
            boost::filesystem::path csvFile(outputDir.string() + DIRECTORY_SEPARATOR + iterator->filename().string().substr(0, position) + ".csv");
            Export::CSV(labels, mat.rows, mat.cols, csvFile);

            if (process == true) {
                std::cout << "Labels for image " << iterator->string() << " saved in " << csvFile.string() << " ..." << std::endl;
            }
        }
        
        for (int i = 0; i < mat.rows; ++i) {
            delete[] labels[i];
        }
        
        delete[] labels;
    }
    
    if (parameters.find("time") != parameters.end()) {
        
        boost::filesystem::path timeDir(parameters["time"].as<std::string>());
        if (!boost::filesystem::is_directory(timeDir)) {
            boost::filesystem::create_directories(timeDir);
        }
        
        boost::filesystem::path timeImgFile(timeDir.string() + DIRECTORY_SEPARATOR + "eval_time_img.txt");
        boost::filesystem::path timeFile(timeDir.string() + DIRECTORY_SEPARATOR + "eval_time.txt");
        
        Export::BSDEvaluationFile<double>(time, 4, timeImgFile);
        
        cv::Mat avgTime(1, 1, cv::DataType<double>::type);
        avgTime.at<double>(0, 0) = totalTime/((double) images.size());
        Export::BSDEvaluationFile<double>(avgTime, 6, timeFile);
    }
    
    std::cout << "On average, " << totalTime/images.size() << " seconds needed ..." << std::endl;
    
    return 0;
}
コード例 #10
0
ElevatorLabWindow::ElevatorLabWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::ElevatorLabWindow)
{
    ui->setupUi(this);

    //Set up constants
    //Positive means up for everything

    /// Mass of the mass, kilograms
    const double mass = 0.5;

    /// Floor height, meters
    const double floorHeight = 4.1;

    /// Initial height above the ground, meters
    //TODO when the algorithm is working: Change this to the
    const double initialHeight = floorHeight * 6;

    /// Time elapsed between lines in the CSV file, seconds
    const double lineTime = 0.1;

    //Set up loop variables

    /// Velocity, meters/second
    double velocity = 0;

    /// Height, meters
    double height = initialHeight;

    //Hard-coded file path. Change this if running on another computer.
    QFile csvFile("/Users/samcrow/Downloads/elevator_lab.csv");
    csvFile.open(QIODevice::Text | QIODevice::ReadOnly);

    //Read and ignore the first line (headers)
    csvFile.readLine();

    //Open the output file in the same directory as the input file
    QFileInfo csvInfo(csvFile);
    QString outPath = csvInfo.absoluteDir().path() + "/elevator_out.csv";
    qDebug() << outPath;
    QFile outFile(outPath);
    outFile.open(QIODevice::Text | QIODevice::Truncate | QIODevice::WriteOnly);
    outFile.write("Time, Acceleration, Velocity, Corrected Velocity, Height, Floor\n");

    //Iterate through every line
    while(true) {

        QString line = csvFile.readLine();
        //Exit condition: Leave the loop if the end of file is reached
        if(line.isEmpty()) {
            break;
        }

        QStringList parts = line.split(',');

        double time = parts.at(0).trimmed().toDouble();

        //The downward force, in newtons, excluding the force of gravity, that the 0.5 kg mass applies to the elevator
        //If this force is negative, the elevator is accelerating upwards and applying an equal and opposite force to the mass
        double forceOnElevator = parts.at(2).trimmed().toDouble();

        //The equal and opposite force that the elevator applies to the mass to accelerate it
        double forceOnMass = -forceOnElevator;

        //f = m a
        //a = f / m
        double acceleration = forceOnMass / mass;

        velocity += acceleration * lineTime;

        /// The velocity, corrected to reduce accumulated error
        double correctedVelocity = velocity - getError(time);

        //Try to correct for any additional error in the corrected velocity by setting values with very small magnitudes to zero
        if(qAbs<double>(correctedVelocity) < 0.1) {
            correctedVelocity = 0;
        }

        height += correctedVelocity * lineTime;

        //Calculate which floor the elevator is on
        int floor = qRound(height / floorHeight);

        qDebug() << "Time" << time << "\tVelocity" << velocity << "\tCorrected velocity" << correctedVelocity << "\tError" << getError(time) << "\tHeight" << height;

        //Write data to the CSV file
        outFile.write(QByteArray::number(time));
        outFile.write(",");
        outFile.write(QByteArray::number(acceleration));
        outFile.write(",");
        outFile.write(QByteArray::number(velocity));
        outFile.write(",");
        outFile.write(QByteArray::number(correctedVelocity));
        outFile.write(",");
        outFile.write(QByteArray::number(height));
        outFile.write(",");
        outFile.write(QByteArray::number(floor));
        outFile.write("\n");

    }


    outFile.close();
    csvFile.close();
}
コード例 #11
0
ファイル: RelayGameLayer.cpp プロジェクト: jg-maon/Atelier
/**
	@brief		メンバ変数初期化
	@param[in]	なし
	@return		なし
*/
void RelayGameLayer::_SetDefaultValues()
{

	// アニメーションフラグ折る
	m_isAnimation = false;

	// 順番表示へ
	m_flowPhase = FlowPhase::CHECK;

	// 時間計測停止
	m_isCounting = false;

	m_oneDrawTime = 0.f;

	// 描きはじめ
	m_nowDrawer = 0;
	m_nowPage = 0;
	m_nowLine = 0;

	//-----------------------------------------------------
	// ペン色
	m_colors.push_back(Color4F(0xff / 255.f, 0x0f / 255.f, 0x0f / 255.f, 1.f)); // ff0f0f
	m_colors.push_back(Color4F(0x0f / 255.f, 0xa3 / 255.f, 0xff / 255.f, 1.f));	// 0fa3ff
	m_colors.push_back(Color4F(0x00 / 255.f, 0x74 / 255.f, 0x16 / 255.f, 1.f));	// 007416
	m_colors.push_back(Color4F(0xf5 / 255.f, 0xb8 / 255.f, 0x00 / 255.f, 1.f));	// f5b800
	m_colors.push_back(Color4F(0x20 / 255.f, 0x0f / 255.f, 0xff / 255.f, 1.f));	// 200fff
	m_colors.push_back(Color4F(0x9c / 255.f, 0x0f / 255.f, 0xff / 255.f, 1.f));	// 9c0fff
	m_colors.push_back(Color4F(0x0f / 255.f, 0xff / 255.f, 0x36 / 255.f, 1.f));	// 0fff36
	m_colors.push_back(Color4F(0xff / 255.f, 0x30 / 255.f, 0xe6 / 255.f, 1.f));	// ff30e6
	m_colors.push_back(Color4F(0xff / 255.f, 0xff / 255.f, 0x2d / 255.f, 1.f));	// ffff2d

	
	//-----------------------------------------------------
	// テーマ読み込み
#pragma region テーマ読み込み
	//std::string csvName("theme_numeric.csv");
	std::string csvName("ThemeRelay.csv");
	std::string fullpath = FileUtils::getInstance()->fullPathForFilename(csvName);
	ssize_t fs = 0;

#if CC_PLATFORM_WIN32 == CC_TARGET_PLATFORM
	std::ifstream csvFile(fullpath);
	CCASSERT(csvFile.is_open(), "csvFile open error.");
#else
	std::string str = FileUtils::getInstance()->getStringFromFile(csvName);
	std::istringstream csvFile(str);
#endif	

	std::string buf;

	while (std::getline(csvFile, buf))
	{
		// インプットチェック(空白の場合終了)
		if (buf.empty())
			break;

		// カンマ区切りで読み込む
		std::istringstream ss(buf);

		// 書式は "テーマ,よみがな"
		Theme theme;
		std::getline(ss, theme.theme, ',');
		ss >> theme.kana;

		// UTF-8のEOF検知用
		if (theme.kana.empty())
			break;

		// 配列に追加
		m_themes.push_back(theme);
	}
#pragma endregion	// テーマ読み込み


	
}