void EobListener::infoHandler() {
	DimInfo *curr = getInfo();
	if (curr == &EOB_TS_) {
		std::cout << "EOB has been updated. Writing new file:" << std::endl;
		usleep(Options::GetFloat(OPTION_EOB_TIMEOUT) * 1E6);
		int runNumber = runNumber_.getInt();
		int burst = burstNumber_.getInt();
		int sob = SOB_TS_.getInt();
		int eob = EOB_TS_.getInt();

		/*
		 * Generate the filename and create a ofstream to the file
		 */
		std::string fileName = generateFileName(runNumber, burst, 0);
		std::string filePath = Options::GetString(OPTION_STORAGE_DIR) + "/"
				+ fileName;
		std::cout << "Writing file " << filePath << std::endl;

		if (boost::filesystem::exists(filePath)) {
			std::cerr << "File already exists: " << filePath << std::endl;
			int counter = 2;
			std::string tmpName;
			tmpName = generateFileName(runNumber, burst, counter);
			while (boost::filesystem::exists(
					Options::GetString(OPTION_STORAGE_DIR) + "/" + tmpName)) {
				std::cerr << "File already exists: " << tmpName << std::endl;
				tmpName = generateFileName(runNumber, burst, ++counter);
			}

			std::cerr << "Instead writing file: " << tmpName << std::endl;
			fileName = tmpName;
			filePath = Options::GetString(OPTION_STORAGE_DIR) + "/" + fileName;
		}

		std::ofstream eobFile;
		eobFile.open(filePath.data(), std::ios::out | std::ios::trunc);

		if (!eobFile.good()) {
			std::cerr << "Unable to write to file " << filePath << std::endl;
			// carry on to free the memory. myfile.write will not throw!
		}

		/*
		 * Generate the XML and pipe it into the file
		 */
		eobFile
				<< registryHandler_->generateAllServicesXml(runNumber, burst,
						sob, eob);
		eobFile.close();
		system(std::string("chown na62cdr:vl " + filePath).data());

		std::cout << "Wrote EOB file of run " << runNumber << " and burst "
				<< burst << " to: " << filePath << std::endl;

	}
}
QString BbMediaStorageLocation::generateFileName(const QString &requestedName, QCamera::CaptureMode mode, const QString &prefix, const QString &extension) const
{
    if (requestedName.isEmpty())
        return generateFileName(prefix, defaultDir(mode), extension);

    if (QFileInfo(requestedName).isDir())
        return generateFileName(prefix, QDir(requestedName), extension);

    return requestedName;
}
HeightMapInterface* AbstractHeightMapManager::getHeightMapOfTile(Tile* tile) {
	if (tileMap.find(tile->getId()) != tileMap.end()) {
		return tileMap[tile->getId()]; //cache hit
	}

	//load and save
	std::string fileName = generateFileName(tile);
	HeightMapInterface* h = loadImpl(fileName);
	if(h) {
		PRINTD(INFO, "found saved heightmap at %s\n",fileName.c_str());
	} else {
		PRINTD(INFO, "creating heightmap for tile %s\n",tile->getName().c_str());
		h = createImpl(tile);
		if(h) { //save to disk
			if(!saveImpl(h, fileName))
				PRINTD(WARNING, "can't save heightmap of tile %s to %s\n",tile->getName().c_str(), fileName.c_str());
		}
	}

	if(h) { //save in cache -> TODO what about locks?
		tileMap[tile->getId()] = h;
		return h;
	} else {
		PRINTD(WARNING, "can't neighter load or create heightmap for tile %s\n",tile->getName().c_str());
		return NULL;
	}
}
Beispiel #4
0
//--------------------------------------------------------------
void testApp::keyPressed(int key){
	switch (key) {
		case 's':
			if (isRecording) {
				oniRecorder.stopRecord();
				isRecording = false;
				break;
			} else {
				setupRecording(generateFileName());
				oniRecorder.startRecord(currentFileName);
				isRecording = true;
				break;
			}
			break;
		case 'p':
			if (currentFileName != "" && !isRecording && isLive) {
				setupPlayback(currentFileName);
				isLive = false;
			} else {
				isLive = true;
			}
			break;
		default:
			break;
	}	
}
Beispiel #5
0
/*
 * Generates a image/video file name based on the given parameters:
 *  * Type (image or video)
 *  * Base (either absolute or relative file name of type QString)
 *  * File type
 */
QString S60FileNameGenerator::generateFileNameFromString(const FileNameType nameType,
                                                         const QString base,
                                                         const QString postfix)
{
    QString baseString(base);
    return generateFileName(nameType, baseString, postfix);
}
Beispiel #6
0
/*
 * Generates a image/video file name based on the given parameters:
 *   * Type (image or video)
 *   * Base (either absolute or relative file name of type QUrl)
 *   * File type
 */
QString S60FileNameGenerator::generateFileNameFromUrl(const FileNameType nameType,
                                                      const QUrl base,
                                                      const QString postfix)
{

    QString baseString(base.toLocalFile());
    return generateFileName(nameType, baseString, postfix);
}
Beispiel #7
0
void Recorder::initializeRecording()
{
    std::string timestamp = oat::createTimeStamp();

    for (auto &w : writers_) {
        auto fid = generateFileName(timestamp, w->addr());
        w->initialize(fid);
    }
}
QString QAndroidMediaStorageLocation::generateFileName(const QString &requestedName,
                                                       CaptureSource source,
                                                       const QString &prefix,
                                                       const QString &extension) const
{
    if (requestedName.isEmpty())
        return generateFileName(prefix, defaultDir(source), extension);

    QString path = requestedName;

    if (QFileInfo(path).isRelative())
        path = defaultDir(source).absoluteFilePath(path);

    if (QFileInfo(path).isDir())
        return generateFileName(prefix, QDir(path), extension);

    if (!path.endsWith(extension))
        path.append(QString(".%1").arg(extension));

    return path;
}
Beispiel #9
0
/**
* changeOpenFile
* Private method to switch the opened file. Close the old file and open new file.
* @return {void}
*/
void SDWriter::changeOpenFile()
{
	if(cmp >= MAX_LINE_PER_FILE)
	{
		totalfilesize += openFile.size();
		openFile.close();
	}
	
	if (openFile = SD.open(generateFileName(), FILE_WRITE))
	{
		openFile.print("{\"DATA\":[");
		cmp = 0;
	}
	else
	{
		openFile.close();
		state = false;
	}
}
Beispiel #10
0
bool Graph::screenshotGraph() {
    // There isn't any point in creating a file with no data in it
    if (m_dataSets.size() == 0) {
        QMessageBox::critical(&m_window, QObject::tr("Save Data"),
                              QObject::tr("No graphs exist"));
        return false;
    } else {
        bool success = m_window.m_ui.plot->savePng(
            QString::fromStdString("./" + generateFileName() + ".png"));

        if (success) {
            QMessageBox::information(&m_window, QObject::tr("Save Data"),
                                     QObject::tr("Screenshot successful"));
            return true;
        } else {
            QMessageBox::critical(&m_window, QObject::tr("Save Data"),
                                  QObject::tr("Screenshot failed"));
            return false;
        }
    }
}
Beispiel #11
0
//--------------------------------------------------------------
void testApp::guiEvent(ofxUIEventArgs &e)
{
	string name = e.widget->getName(); 
	int kind = e.widget->getKind(); 
	cout << "got event from: " << name << endl; 	
	
	if(name == "RED")
	{
		ofxUISlider *slider = (ofxUISlider *) e.widget; 
		cout << "RED " << slider->getScaledValue() << endl; 
		red = slider->getScaledValue(); 
	}
	else if(name == "GREEN")
	{
		ofxUISlider *slider = (ofxUISlider *) e.widget; 
		cout << "GREEN " << slider->getScaledValue() << endl; 
		green = slider->getScaledValue(); 
	}
	else if(name == "BLUE")
	{
		ofxUISlider *slider = (ofxUISlider *) e.widget; 
		cout << "BLUE " << slider->getScaledValue() << endl; 
		blue = slider->getScaledValue(); 		
	}
    
    else if(name == "Spread Base")
	{
		ofxUISlider *slider = (ofxUISlider *) e.widget; 
		cout << "Spread Base" << slider->getScaledValue() << endl; 
//		spreadbase = slider->getScaledValue(); 		
	}	
    else if(name == "Spread Multiplier")
	{
		ofxUISlider *slider = (ofxUISlider *) e.widget; 
		cout << "Spread Multiplier " << slider->getScaledValue() << endl; 
//		spreadmultiplier = slider->getScaledValue(); 		
	}	
    else if(name == "Boxsize Base")
	{
		ofxUISlider *slider = (ofxUISlider *) e.widget; 
		cout << "Boxsize Base " << slider->getScaledValue() << endl; 
//		boxbase = slider->getScaledValue(); 		
	}	
    else if(name == "Boxsize Multiplier")
	{
		ofxUISlider *slider = (ofxUISlider *) e.widget; 
		cout << "Boxsize Multiplier " << slider->getScaledValue() << endl; 
//		boxmultiplier = slider->getScaledValue(); 		
	}
	else if(name == "isRecording")
	{
		ofxUIToggle *toggle = (ofxUIToggle *) e.widget; 
		isRecording = toggle->getValue(); 
        if (isRecording) {
            oniRecorder.stopRecord();
            isRecording = false;
        } else {
            oniRecorder.startRecord(generateFileName());
            isRecording = true;
        }
	}
    else if(name == "isLive")
	{
		ofxUIToggle *toggle = (ofxUIToggle *) e.widget; 
		isLive = toggle->getValue(); 
        if (isRecording) {
            oniRecorder.stopRecord();
            isRecording = false;
        } else {
            oniRecorder.startRecord(generateFileName());
            isRecording = true;
        }
	}
    
	
	
	
}
//--------------------------------------------------------------
void testApp::keyPressed (int key) {
	switch (key) {
        
        case 'l':
            if(!meshRecorder.readyToPlay) return;
            // Todo: Cuando sepamos detener el Thread que pueda hacerse en cualquier
            // momento durante la carga.
            if(recording) return;
            if(!playing) {
                    playing = true;
                    frameToPlay = 0;
                    meshRecorder.startLoading(_timestamp);
                } else {
                    playing = false;
                }
            break; 
            
        case 'r':
            if(!meshRecorder.readyToPlay) return;
            if(recording) return;
            if(playing) return;
            saveTo = generateFileName();
            frame = 0;
            recording = true;
			break;   
        
        case 's':
            if(!meshRecorder.readyToPlay) return;
            if(!recording) return;
            if(playing) return;
            saveTo = "";
            recording = false;
			break; 
            
		case ' ':
			colorMode = !colorMode;
			break;
			
		case'p':
			bDrawPointCloud = !bDrawPointCloud;
			break;
			
		case '>':
		case '.':
			farThreshold ++;
			if (farThreshold > 255) farThreshold = 255;
			break;
			
		case '<':
		case ',':
			farThreshold --;
			if (farThreshold < 0) farThreshold = 0;
			break;
			
		case '+':
		case '=':
			nearThreshold ++;
			if (nearThreshold > 255) nearThreshold = 255;
			break;
			
		case '-':
			nearThreshold --;
			if (nearThreshold < 0) nearThreshold = 0;
			break;
			
		case 'w':
			kinect.enableDepthNearValueWhite(!kinect.isDepthNearValueWhite());
			break;
			
		case 'o':
			kinect.setCameraTiltAngle(angle); // go back to prev tilt
			kinect.open();
			break;
			
		case 'c':
			kinect.setCameraTiltAngle(0); // zero the tilt
			kinect.close();
			break;
			
		case OF_KEY_UP:
			angle++;
			if(angle>30) angle=30;
			kinect.setCameraTiltAngle(angle);
			break;
			
		case OF_KEY_DOWN:
			angle--;
			if(angle<-30) angle=-30;
			kinect.setCameraTiltAngle(angle);
			break;
    }
}
//--------------------------------------------------------------
void motionDetector::keyPressed(int key) {
    float smooth;
    switch (key) {

    case 's':
    case 'S':
        if (isRecording) {
            oniRecorder.stopRecord();
            isRecording = false;
            break;
        } else {
            oniRecorder.startRecord(generateFileName());
            isRecording = true;
            break;
        }
        break;
    case 'p':
    case 'P':
        if (oniRecorder.getCurrentFileName() != "" && !isRecording && isLive) {
            setupPlayback(oniRecorder.getCurrentFileName());
            isLive = false;
        } else {
            isLive = true;
        }
        break;
    case 't':
    case 'T':
        isTracking = !isTracking;
        break;
    case 'h':
    case 'H':
        isTrackingHands = !isTrackingHands;
        if(isLive) recordHandTracker.toggleTrackHands();
        if(!isLive) playHandTracker.toggleTrackHands();
        break;
    case 'f':
    case 'F':
        isFiltering = !isFiltering;
        recordHandTracker.isFiltering = isFiltering;
        playHandTracker.isFiltering = isFiltering;
        break;
    case '9':
    case '(':
        smooth = recordUser.getSmoothing();
        if (smooth - 0.1f > 0.0f) {
            recordUser.setSmoothing(smooth - 0.1f);
            playUser.setSmoothing(smooth - 0.1f);
        }
        break;
    case '0':
    case ')':
        smooth = recordUser.getSmoothing();
        if (smooth + 0.1f <= 1.0f) {
            recordUser.setSmoothing(smooth + 0.1f);
            playUser.setSmoothing(smooth + 0.1f);
        }
        break;
    case '[':
    case '{':
        if (filterFactor - 0.1f > 0.0f) {
            filterFactor = filterFactor - 0.1f;
            recordHandTracker.setFilterFactors(filterFactor);
            if (oniRecorder.getCurrentFileName() != "") playHandTracker.setFilterFactors(filterFactor);
        }
        break;
    case ']':
    case '}':
        if (filterFactor + 0.1f <= 1.0f) {
            filterFactor = filterFactor + 0.1f;
            recordHandTracker.setFilterFactors(filterFactor);
            if (oniRecorder.getCurrentFileName() != "") playHandTracker.setFilterFactors(filterFactor);
        }
        break;
    case ';':
    case ':':
        smooth = recordHandTracker.getSmoothing();
        if (smooth - 0.1f > 0.0f) {
            recordHandTracker.setSmoothing(smooth -  0.1f);
            playHandTracker.setSmoothing(smooth -  0.1f);
        }
        break;
    case '\'':
    case '\"':
        smooth = recordHandTracker.getSmoothing();
        if (smooth + 0.1f <= 1.0f) {
            recordHandTracker.setSmoothing(smooth +  0.1f);
            playHandTracker.setSmoothing(smooth +  0.1f);
        }
        break;
    case '>':
    case '.':
        farThreshold += 50;
        if (farThreshold > recordDepth.getMaxDepth()) farThreshold = recordDepth.getMaxDepth();
        break;
    case '<':
    case ',':
        farThreshold -= 50;
        if (farThreshold < 0) farThreshold = 0;
        break;
    case '+':
    case '=':
        nearThreshold += 50;
        if (nearThreshold > recordDepth.getMaxDepth()) nearThreshold = recordDepth.getMaxDepth();
        break;
    case '-':
    case '_':
        nearThreshold -= 50;
        if (nearThreshold < 0) nearThreshold = 0;
        break;
    case 'r':
        recordContext.toggleRegisterViewport();
        break;
    case 'Q':
    case 'q':
        myfile.close();
        break;
    default:
        break;
    }
}
Beispiel #14
0
//--------------------------------------------------------------
void testApp::keyPressed(int key){

	float smooth;

	switch (key) {
#ifdef TARGET_OSX // only working on Mac at the moment
		case 357: // up key
			hardware.setTiltAngle(hardware.tilt_angle++);
			break;
		case 359: // down key
			hardware.setTiltAngle(hardware.tilt_angle--);
			break;
#endif
		case 's':
		case 'S':
			if (isRecording) {
				oniRecorder.stopRecord();
				isRecording = false;
				break;
			} else {
				oniRecorder.startRecord(generateFileName());
				isRecording = true;
				break;
			}
			break;
		case 'p':
		case 'P':
			if (oniRecorder.getCurrentFileName() != "" && !isRecording && isLive) {
				setupPlayback(oniRecorder.getCurrentFileName());
				isLive = false;
			} else {
				isLive = true;
			}
			break;
		case 't':
		case 'T':
			isTracking = !isTracking;
			break;
		case 'h':
		case 'H':
			isTrackingHands = !isTrackingHands;
			if(isLive) recordHandTracker.toggleTrackHands();
			if(!isLive) playHandTracker.toggleTrackHands();
			break;
		case 'f':
		case 'F':
			isFiltering = !isFiltering;
			recordHandTracker.isFiltering = isFiltering;
			playHandTracker.isFiltering = isFiltering;
			break;
		case 'm':
		case 'M':
			isMasking = !isMasking;
			recordUser.setUseMaskPixels(isMasking);
			playUser.setUseMaskPixels(isMasking);
			break;
		case 'c':
		case 'C':
			isCloud = !isCloud;
			recordUser.setUseCloudPoints(isCloud);
			playUser.setUseCloudPoints(isCloud);
			break;
		case 'b':
		case 'B':
			isCPBkgnd = !isCPBkgnd;
			break;
		case '9':
		case '(':
			smooth = recordUser.getSmoothing();
			if (smooth - 0.1f > 0.0f) {
				recordUser.setSmoothing(smooth - 0.1f);
				playUser.setSmoothing(smooth - 0.1f);
			}
			break;
		case '0':
		case ')':
			smooth = recordUser.getSmoothing();
			if (smooth + 0.1f <= 1.0f) {
				recordUser.setSmoothing(smooth + 0.1f);
				playUser.setSmoothing(smooth + 0.1f);
			}
			break;
		case '[':
		//case '{':
			if (filterFactor - 0.1f > 0.0f) {
				filterFactor = filterFactor - 0.1f;
				recordHandTracker.setFilterFactors(filterFactor);
				if (oniRecorder.getCurrentFileName() != "") playHandTracker.setFilterFactors(filterFactor);
			}
			break;
		case ']':
		//case '}':
			if (filterFactor + 0.1f <= 1.0f) {
				filterFactor = filterFactor + 0.1f;
				recordHandTracker.setFilterFactors(filterFactor);
				if (oniRecorder.getCurrentFileName() != "") playHandTracker.setFilterFactors(filterFactor);
			}
			break;
		case ';':
		case ':':
			smooth = recordHandTracker.getSmoothing();
			if (smooth - 0.1f > 0.0f) {
				recordHandTracker.setSmoothing(smooth -  0.1f);
				playHandTracker.setSmoothing(smooth -  0.1f);
			}
			break;
		case '\'':
		case '\"':
			smooth = recordHandTracker.getSmoothing();
			if (smooth + 0.1f <= 1.0f) {
				recordHandTracker.setSmoothing(smooth +  0.1f);
				playHandTracker.setSmoothing(smooth +  0.1f);
			}
			break;
		case '>':
		case '.':
			farThreshold += 50;
			if (farThreshold > recordDepth.getMaxDepth()) farThreshold = recordDepth.getMaxDepth();
			break;
		case '<':
		case ',':
			farThreshold -= 50;
			if (farThreshold < 0) farThreshold = 0;
			break;

		case '+':
		case '=':
			nearThreshold += 50;
			if (nearThreshold > recordDepth.getMaxDepth()) nearThreshold = recordDepth.getMaxDepth();
			break;

		case '-':
		case '_':
			nearThreshold -= 50;
			if (nearThreshold < 0) nearThreshold = 0;
			break;
		case 'r':
			recordContext.toggleRegisterViewport();
			break;
            
        case 'z':
        case 'Z':
			ofToggleFullscreen(); 
			break;
            
		case 'x':
        case 'X':
            gui->toggleVisible();            
			break;
            
		default:
			break;
	}
}
Beispiel #15
0
const QString Event::icon() const
{
    return generateFileName(CoreSettings::getEventsIconDir(this->serviceId()));
}
Beispiel #16
0
const QString BaseObject::generateFileName(const QString &path) const
{
    return generateFileName(path, this->iconUrl());
}
void io::VtkWriter::writeTimeStep(
		const Float2D &i_h,
        const Float2D &i_hu,
        const Float2D &i_hv,
        float i_time)
{
	std::ofstream vtkFile(generateFileName().c_str());
	assert(vtkFile.good());

	// VTK HEADER
	vtkFile << "<?xml version=\"1.0\"?>" << std::endl
			<< "<VTKFile type=\"StructuredGrid\">" << std::endl
			<< "<StructuredGrid WholeExtent=\"" << offsetX << " " << offsetX+nX
				<< " " << offsetY << " " << offsetY+nY << " 0 0\">" << std::endl
	        << "<Piece Extent=\"" << offsetX << " " << offsetX+nX
	        	<< " " << offsetY << " " << offsetY+nY << " 0 0\">" << std::endl;

	vtkFile << "<Points>" << std::endl
			<< "<DataArray NumberOfComponents=\"3\" type=\"Float32\" format=\"ascii\">" << std::endl;

	//GITTER PUNKTE
	for (int j=0; j < nX+1; j++)
	      for (int i=0; i < nX+1; i++)
	    	  vtkFile << (offsetX+i)*dX << " " << (offsetY+j)*dY <<" 0" << std::endl;

	vtkFile << "</DataArray>" << std::endl
			<< "</Points>" << std::endl;

	vtkFile << "<CellData>" << std::endl;

	// Water surface height (h+b)
	vtkFile << "<DataArray Name=\"H\" type=\"Float32\" format=\"ascii\">" << std::endl;
	for (int j=1; j < nY+1; j++)
		for (int i=1; i < nX+1; i++)
			vtkFile << i_h[i][j]+b[i][j] << std::endl;
	vtkFile << "</DataArray>" << std::endl;

	// Velocities
	vtkFile << "<DataArray Name=\"U\" type=\"Float32\" format=\"ascii\">" << std::endl;
	for (int j=1; j < nY+1; j++)
		for (int i=1; i < nX+1; i++)
			vtkFile << ((i_h[i][j]>0) ? i_hu[i][j]/i_h[i][j] : 0.0 ) << std::endl;
	vtkFile << "</DataArray>" << std::endl;

	vtkFile << "<DataArray Name=\"V\" type=\"Float32\" format=\"ascii\">" << std::endl;
	for (int j=1; j < nY+1; j++)
		for (int i=1; i<nX+1; i++)
			vtkFile << ((i_h[i][j]>0) ? i_hv[i][j]/i_h[i][j] : 0.0 ) << std::endl;
	vtkFile << "</DataArray>" << std::endl;

	// Bathymetry
	vtkFile << "<DataArray Name=\"B\" type=\"Float32\" format=\"ascii\">" << std::endl;
	for (int j=1; j<nY+1; j++)
		for (int i=1; i<nX+1; i++)
			vtkFile << b[i][j] << std::endl;
	vtkFile << "</DataArray>" << std::endl;

	vtkFile << "</CellData>" << std::endl
			<< "</Piece>" << std::endl;

	vtkFile << "</StructuredGrid>" << std::endl
			<< "</VTKFile>" << std::endl;

	// Increament time step
	timeStep++;
}
Beispiel #18
0
void io::VtkWriter::writeTimeStep(
		const Float2D &i_h,
        const Float2D &i_hu,
        const Float2D &i_hv,
        float i_time)
{
	std::ofstream vtkFile(generateFileName().c_str());
	assert(vtkFile.good());

	//Grid wrapper for each grid
	CoarseGridWrapper gridWrapperH(i_h, boundarySize, nX, nY, coarseness);
	CoarseGridWrapper gridWrapperHu(i_hu, boundarySize, nX, nY, coarseness);
	CoarseGridWrapper gridWrapperHv(i_hv, boundarySize, nX, nY, coarseness);
	CoarseGridWrapper gridWrapperB(b, boundarySize, nX, nY, coarseness);

	// VTK header
	vtkFile << "<?xml version=\"1.0\"?>" << std::endl
			<< "<VTKFile type=\"StructuredGrid\">" << std::endl
			<< "<StructuredGrid WholeExtent=\"" << offsetX << " " << offsetX+coarseX
				<< " " << offsetY << " " << offsetY+coarseY << " 0 0\">" << std::endl
	        << "<Piece Extent=\"" << offsetX << " " << offsetX+coarseX
	        	<< " " << offsetY << " " << offsetY+coarseY << " 0 0\">" << std::endl;

	vtkFile << "<Points>" << std::endl
			<< "<DataArray NumberOfComponents=\"3\" type=\"Float32\" format=\"ascii\">" << std::endl;

	//Grid points
	for (unsigned int j=0; j < coarseX+1; j++)
        for (unsigned int i=0; i < coarseY+1; i++)
            vtkFile << (offsetX+i)*((dX * float(nX)) / float(coarseX))
                << " " << (offsetY+j)*((dY * float(nY)) / float(coarseY))
                << " 0" << std::endl;
    
	vtkFile << "</DataArray>" << std::endl
			<< "</Points>" << std::endl;

	vtkFile << "<CellData>" << std::endl;

	// Water surface height h
	vtkFile << "<DataArray Name=\"h\" type=\"Float32\" format=\"ascii\">" << std::endl;
	for (unsigned int j=0; j < coarseY; j++)
		for (unsigned int i=0; i < coarseX+0; i++)
			vtkFile << gridWrapperH.getElem(i, j) << std::endl;
	vtkFile << "</DataArray>" << std::endl;

	// Momentums
	vtkFile << "<DataArray Name=\"hu\" type=\"Float32\" format=\"ascii\">" << std::endl;
	for (unsigned int j=0; j < coarseY; j++)
		for (unsigned int i=0; i < coarseX; i++)
			vtkFile << gridWrapperHu.getElem(i, j) << std::endl;
	vtkFile << "</DataArray>" << std::endl;

	vtkFile << "<DataArray Name=\"hv\" type=\"Float32\" format=\"ascii\">" << std::endl;
	for (unsigned int j=0; j < coarseY; j++)
		for (unsigned int i=0; i<coarseX; i++)
			vtkFile << gridWrapperHv.getElem(i, j) << std::endl;
	vtkFile << "</DataArray>" << std::endl;

	// Bathymetry
	vtkFile << "<DataArray Name=\"b\" type=\"Float32\" format=\"ascii\">" << std::endl;
	for (unsigned int j=0; j<coarseY; j++)
		for (unsigned int i=0; i<coarseX; i++)
			vtkFile << gridWrapperB.getElem(i, j) << std::endl;
	vtkFile << "</DataArray>" << std::endl;

	vtkFile << "</CellData>" << std::endl
			<< "</Piece>" << std::endl;

	vtkFile << "</StructuredGrid>" << std::endl
			<< "</VTKFile>" << std::endl;

	// Increament time step
	timeStep++;
}
//  projected query vector, length = 50
int medrank::runAlgorithm(float* q){  
    int *vote = new int[60000];
    memset(vote, 0, 60000);        //  初始化为0
    int curLargestVoteNum = 0;   //  记录当前最多票数
    BLeafNode* resultNode = nullptr;//  记录最终结果
    int resultIndex = -1;        //  记录最终结果
    int lowerIndex[50];          //  记录叶子节点中的位置
    int higherIndex[50];         //
    BLeafNode* lower[50];        //  记录叶子节点指针
    BLeafNode* higher[50];       //  
    for (int i = 0; i < 50; ++i) {
        lowerIndex[i] = higherIndex[i] = -1;
        lower[i] = higher[i] = nullptr;
    }

    //  初始化B+树
    BTree* tree;
	char BTreeFname[50];

    //  第一次查询
    for (int i = 0; i < 50; ++i) {
		generateFileName(i, BTreeFname);
		tree = new BTree;
		tree->init_restore(BTreeFname);
		tree->searchLowerAndHigher(q[i],
                                   lower[i], lowerIndex[i],
                                   higher[i], higherIndex[i]);
		printf("search:%d\n", i);
    }

    //  投票过程
    while (curLargestVoteNum <= 25) {
		// printf("current:%d\n", curLargestVoteNum);
        for (int i = 0; i < 50; ++i) {
            bool flag = false;  //  false->left; true->right
            if (higher[i] == nullptr && lower[i] != nullptr) {
                //  lower[lowerIndex] is nearer
                flag = false;
            } else if (higher[i] != nullptr && lower[i] == nullptr) {
                //  higher[higherIndex] is nearer
                flag = true;
            } else if (higher[i] == nullptr && lower[i] == nullptr) {
                //  error
				error("higher == NULL and lower  == NULL", true);
            } else {
                if (q[i] - lower[i]->get_key(lowerIndex[i]) < higher[i]->get_key(higherIndex[i]) - q[i]) {
                    //  lower[lowerIndex] is nearer
                    flag = false;
                } else {
                    //  higher[higherIndex] is nearer
                    flag = true;
                }
            }

            if (flag) {
                //  higher[higherIndex] is nearer
				int index = higher[i]->get_entry_id(higherIndex[i]);
                vote[index]++;
                //  保存curLagerestNum为当前最大票数,更新结果
                if (vote[index] > curLargestVoteNum) {
                    curLargestVoteNum = vote[index];
                    resultNode = higher[i];
                    resultIndex = higherIndex[i];
                }
                ++higherIndex[i];
                if (higherIndex[i] >= higher[i]->get_num_entries()) {
                    higher[i] = higher[i]->get_right_sibling();
                    if (higher[i] != nullptr)
                        higherIndex[i] = 0;
                }
            } else {
                //  lower[lowerIndex] is nearer
				int index = lower[i]->get_entry_id(lowerIndex[i]);
                vote[index]++;
				//  保存curLagerestNum为当前最大票数,更新结果
				if (vote[index] > curLargestVoteNum) {
					curLargestVoteNum = vote[index];
					resultNode = lower[i];
					resultIndex = lowerIndex[i];
				}
                --lowerIndex[i];
                if (lowerIndex[i] < 0) {
                    lower[i] = lower[i]->get_left_sibling();
                    if (lower[i] != nullptr)
                        lowerIndex[i] = lower[i]->get_num_entries() - 1;
                }
            }
        }
    }

//    if (vote != nullptr) {          //  释放内存空间
//        delete [] vote;
//        vote = nullptr;
//    }
	return resultNode->get_entry_id(resultIndex);
}
Beispiel #20
0
	void	CTrainNodeCvKNN::save(const std::string &path, const std::string &name, short idx) const
	{
		std::string fileName = generateFileName(path, name.empty() ? "TrainNodeCvKNN" : name, idx);
		m_pKNN->save(fileName.c_str());
	}
Beispiel #21
0
bool Graph::saveAsCSV() {
    // There isn't any point in creating a file with no data in it
    if (m_dataSets.size() == 0) {
        QMessageBox::critical(&m_window, QObject::tr("Save Data"),
                              QObject::tr("No graphs exist"));
        return false;
    }

    std::ofstream saveFile(generateFileName() + ".csv", std::ios_base::trunc);

    if (saveFile.is_open()) {
        // Tracks positions in each data set; start at 0 for each
        std::vector<size_t> sets(m_dataSets.size(), 0);

        size_t setsOpen = m_dataSets.size();

        // Write axis and data labels to file
        for (size_t j = 0; j < m_dataSets.size(); j++) {
            if (j == 0) {
                // X axis label
                saveFile << "Time (s)"
                         << ",";
            }
            saveFile << m_graphNames[j];

            // If last Y axis label hasn't been written yet
            if (j + 1 < m_dataSets.size()) {
                saveFile << ",";
            } else {
                saveFile << "\n";
            }
        }

        // While there is still data in at least one data set to add to the file
        while (setsOpen > 0) {
            setsOpen = m_dataSets.size();

            for (size_t j = 0; j < m_dataSets.size(); j++) {
                // If there are still points in this data set to add
                if (sets[j] != m_dataSets[j].size()) {
                    /* Only write X values of first data set since X values of
                     * all data sets are identical.
                     */
                    if (j == 0) {
                        saveFile << m_dataSets[j][sets[j]].first << ",";
                    }
                    saveFile << m_dataSets[j][sets[j]].second;

                    // Increment to next point in data set
                    sets[j]++;
                } else {
                    // Data set has reached invalid point after incrementing

                    // Add a filler comma
                    saveFile << ",";

                    setsOpen--;
                }

                // Only add another comma if there is more data to add
                if (j < m_dataSets.size() - 1) {
                    saveFile << ",";
                }
            }

            if (setsOpen > 0) {
                saveFile << '\n';
            }
        }

        saveFile.close();

        QMessageBox::information(&m_window, QObject::tr("Save Data"),
                                 QObject::tr("Export to CSV successful"));
        return true;
    } else {
        QMessageBox::critical(&m_window, QObject::tr("Save Data"),
                              QObject::tr("Open CSV file failed"));
        return false;
    }
}
Beispiel #22
0
	void	CTrainNodeCvKNN::load(const std::string &path, const std::string &name, short idx)
	{
		std::string fileName = generateFileName(path, name.empty() ? "TrainNodeCvKNN" : name, idx);
		m_pKNN = Algorithm::load<ml::KNearest>(fileName.c_str());
	}
Beispiel #23
0
/**
 * Main program for the simulation on a single SWE_WavePropagationBlock.
 */
int main( int argc, char** argv ) {
  /**
   * Initialization.
   */
  // check if the necessary command line input parameters are given
  #ifndef READXML
  if(argc != 4) {
    std::cout << "Aborting ... please provide proper input parameters." << std::endl
              << "Example: ./SWE_parallel 200 300 /work/openmp_out" << std::endl
              << "\tfor a single block of size 200 * 300" << std::endl;
    return 1;
  }
  #endif

  //! number of grid cells in x- and y-direction.
  int l_nX, l_nY;

  //! l_baseName of the plots.
  std::string l_baseName;

  // read command line parameters
  #ifndef READXML
  l_nY = l_nX = atoi(argv[1]);
  l_nY = atoi(argv[2]);
  l_baseName = std::string(argv[3]);
  #endif

  // read xml file
  #ifdef READXML
  assert(false); //TODO: not implemented.
  if(argc != 2) {
    s_sweLogger.printString("Aborting. Please provide a proper input file.");
    s_sweLogger.printString("Example: ./SWE_gnu_debug_none_augrie config.xml");
    return 1;
  }
  s_sweLogger.printString("Reading xml-file.");

  std::string l_xmlFile = std::string(argv[1]);
  s_sweLogger.printString(l_xmlFile);

  CXMLConfig l_xmlConfig;
  l_xmlConfig.loadConfig(l_xmlFile.c_str());
  #endif

  #ifdef ASAGI
  /* Information about the example bathymetry grid (tohoku_gebco_ucsb3_500m_hawaii_bath.nc):
   *
   * Pixel node registration used [Cartesian grid]
   * Grid file format: nf = GMT netCDF format (float)  (COARDS-compliant)
   * x_min: -500000 x_max: 6500000 x_inc: 500 name: x nx: 14000
   * y_min: -2500000 y_max: 1500000 y_inc: 500 name: y ny: 8000
   * z_min: -6.48760175705 z_max: 16.1780223846 name: z
   * scale_factor: 1 add_offset: 0
   * mean: 0.00217145586762 stdev: 0.245563641735 rms: 0.245573241263
   */

  //simulation area
  float simulationArea[4];
  simulationArea[0] = -450000;
  simulationArea[1] = 6450000;
  simulationArea[2] = -2450000;
  simulationArea[3] = 1450000;

  SWE_AsagiScenario l_scenario( "/work/breuera/workspace/geo_information/output/tohoku_gebco_ucsb3_500m_hawaii_bath.nc",
                                "/work/breuera/workspace/geo_information/output/tohoku_gebco_ucsb3_500m_hawaii_displ.nc",
                                (float) 28800., simulationArea);
  #else
  // create a simple artificial scenario
  SWE_BathymetryDamBreakScenario l_scenario;
  #endif

  //! number of checkpoints for visualization (at each checkpoint in time, an output file is written).
  int l_numberOfCheckPoints = 20;

  //! size of a single cell in x- and y-direction
  float l_dX, l_dY;

  // compute the size of a single cell
  l_dX = (l_scenario.getBoundaryPos(BND_RIGHT) - l_scenario.getBoundaryPos(BND_LEFT) )/l_nX;
  l_dY = (l_scenario.getBoundaryPos(BND_TOP) - l_scenario.getBoundaryPos(BND_BOTTOM) )/l_nY;

  // initialize the grid data and the corresponding static variables
  SWE_Block::initGridData(l_nX,l_nY,l_dX,l_dY);

  //! origin of the simulation domain in x- and y-direction
  float l_originX, l_originY;

  // get the origin from the scenario
  l_originX = l_scenario.getBoundaryPos(BND_LEFT);
  l_originY = l_scenario.getBoundaryPos(BND_BOTTOM);

  // create a single wave propagation block
  #ifndef CUDA
  SWE_WavePropagationBlock l_wavePropgationBlock(l_originX, l_originY);
  #else
  SWE_WavePropagationBlockCuda l_wavePropgationBlock(l_originX, l_originY);
  #endif

  // initialize the wave propgation block
  l_wavePropgationBlock.initScenario(l_scenario);


  //! time when the simulation ends.
  float l_endSimulation = l_scenario.endSimulation();

  //! checkpoints when output files are written.
  float* l_checkPoints = new float[l_numberOfCheckPoints+1];

  // compute the checkpoints in time
  for(int cp = 0; cp <= l_numberOfCheckPoints; cp++) {
     l_checkPoints[cp] = cp*(l_endSimulation/l_numberOfCheckPoints);
  }


  // write the output at time zero
  s_sweLogger.printOutputTime((float) 0.);
  #ifdef WRITENETCDF
  //boundary size of the ghost layers
  int l_boundarySize[4];
  l_boundarySize[0] = l_boundarySize[1] = l_boundarySize[2] = l_boundarySize[3] = 1;

  //construct a NetCdfWriter
  std::string l_fileName = l_baseName;
  io::NetCdfWriter l_netCdfWriter( l_fileName, l_nX, l_nY );
  //create the netCDF-file
  l_netCdfWriter.createNetCdfFile(l_dX, l_dY, l_originX, l_originY);
  l_netCdfWriter.writeBathymetry(l_wavePropgationBlock.getBathymetry(), l_boundarySize);
  l_netCdfWriter.writeUnknowns( l_wavePropgationBlock.getWaterHeight(),
                                l_wavePropgationBlock.getDischarge_hu(),
                                l_wavePropgationBlock.getDischarge_hv(),
                                l_boundarySize, (float) 0.);
  #else
  l_wavePropgationBlock.writeVTKFileXML(generateFileName(l_baseName,0,0,0), l_nX, l_nY);
  #endif


  /**
   * Simulation.
   */
  // print the start message and reset the wall clock time
  s_sweLogger.printStartMessage();
  s_sweLogger.initWallClockTime(time(NULL));

  //! simulation time.
  float l_t = 0.0;

  // loop over checkpoints
  for(int c=1; c<=l_numberOfCheckPoints; c++) {
    // reset the cpu clock
    s_sweLogger.resetCpuClockToCurrentTime();

    // do time steps until next checkpoint is reached
    while( l_t < l_checkPoints[c] ) {
      // set values in ghost cells:
      l_wavePropgationBlock.setGhostLayer();

      // compute numerical flux on each edge
      l_wavePropgationBlock.computeNumericalFluxes();

      //! maximum allowed time step width.
      float l_maxTimeStepWidth = l_wavePropgationBlock.getMaxTimestep();

      // update the cell values
      l_wavePropgationBlock.updateUnknowns(l_maxTimeStepWidth);

      // update simulation time with time step width.
      l_t += l_maxTimeStepWidth;

      // print the current simulation time
      s_sweLogger.printSimulationTime(l_t);
    }

    // update the cpu time in the logger
    s_sweLogger.updateCpuTime();

    // print current simulation time of the output
    s_sweLogger.printOutputTime(l_t);

    // write output
#ifdef WRITENETCDF
    l_netCdfWriter.writeUnknowns( l_wavePropgationBlock.getWaterHeight(),
                                  l_wavePropgationBlock.getDischarge_hu(),
                                  l_wavePropgationBlock.getDischarge_hv(),
                                  l_boundarySize, l_t);
#else
    l_wavePropgationBlock.writeVTKFileXML(generateFileName(l_baseName,c,0,0), l_nX, l_nY);
#endif
  }

  /**
   * Finalize.
   */
  // write the statistics message
  s_sweLogger.printStatisticsMessage();

  // print the cpu time
  s_sweLogger.printCpuTime();

  // print the wall clock time (includes plotting)
  s_sweLogger.printWallClockTime(time(NULL));

  return 0;
}