void FFT::backward(VolumeList &volumes) {
    if (volumes.size() > 0 && volumes[0].domain != Domain::Time) {
      fftw_plan plan;
      try {
	plan = backward_plans.at(volumes.data);
      } catch (...) {
	int rank = 3;
	int n[] = { static_cast<int>(volumes[0].width), 
		    static_cast<int>(volumes[0].height),
		    static_cast<int>(volumes[0].depth) };
	int howmany = volumes.size();
	int idist = volumes.volume_size_complex;
	int odist = volumes.volume_size_real;
	int istride = 1, ostride = 1;
	int *inembed = 0, *onembed = 0;
	plan = fftw_plan_many_dft_c2r(rank, n, howmany,
				      reinterpret_cast<fftw_complex *>(volumes.data),
				      inembed, istride, idist,
				      volumes.data,
				      onembed, ostride, odist,
				      FFTW_ESTIMATE);
	backward_plans[volumes.data] = plan;
      }
      fftw_execute(plan);
      for (size_t i = 0; i < volumes.size(); ++i) {
	volumes[i] *= 1.0 / volumes[i].size;
	volumes[i].domain = Domain::Time;
      }
    }
  }
Beispiel #2
0
void VolumePort::loadData(const std::string& path) throw (VoreenException) {
    tgtAssert(!path.empty(), "empty path");

    // append .vvd if no extension specified
    std::string filename = path;
    if (tgt::FileSystem::fileExtension(filename).empty())
        filename += ".vvd";

    VolumeSerializerPopulator serializerPop;
    const VolumeSerializer* serializer = serializerPop.getVolumeSerializer();
    try {
        VolumeList* volumeList = serializer->read(filename);
        tgtAssert(!volumeList->empty(), "empty collection");
        VolumeBase* dataset = volumeList->first();
        setData(dataset, true);
        //we do not need the collection, just the volume:
        delete volumeList;
    }
    catch (VoreenException) {
        throw;
    }
    catch (std::exception& e) {
        throw VoreenException(e.what());
    }
}
Beispiel #3
0
VolumeList* VolumeList::subList(const std::vector<size_t>& indices) const {
    VolumeList* subCollection = new VolumeList();
    for (size_t i=0; i<indices.size(); i++) {
        tgtAssert(indices.at(i) < volumes_.size(), "invalid index");
        subCollection->add(volumes_.at(indices.at(i)));
    }
    return subCollection;
}
Beispiel #4
0
voreen::VolumeList* VolumeList::selectOrigin(const VolumeURL& origin) const {
    VolumeList* collection = new VolumeList();
    for (size_t i=0; i<volumes_.size(); ++i) {
        Volume* vh = dynamic_cast<Volume*>(volumes_[i]);
        if (vh && vh->getOrigin() == origin)
            collection->add(volumes_[i]);
    }
    return collection;
}
Beispiel #5
0
VolumeList* VolumeList::subList(size_t start, size_t end) const {
    VolumeList* subCollection = new VolumeList();
    tgtAssert(start <= end, "invalid indices");
    tgtAssert(start < volumes_.size(), "invalid start index");
    tgtAssert(end < volumes_.size(), "invalid end index");
    for (size_t index = start; index <= end; index++)
        subCollection->add(volumes_.at(index));
    return subCollection;
}
Beispiel #6
0
VolumeList* VolumeList::selectModality(const Modality& modality) const {

    VolumeList* collection = new VolumeList();
    for (size_t i=0; i<volumes_.size(); ++i) {
        if (volumes_[i]->getModality() == modality)
            collection->add(volumes_[i]);
    }
    return collection;
}
VolumeList* VolumeURLListProperty::getVolumes(bool selectedOnly /*= true*/) const {
    VolumeList* collection = new VolumeList();
    std::vector<std::string> urls = get();
    for (size_t i=0; i<urls.size(); i++) {
        std::string url = urls.at(i);
        if (handleMap_.find(url) != handleMap_.end()) {
            if (!selectedOnly || (selectionMap_.find(url) != selectionMap_.end() && selectionMap_.find(url)->second == true) ) {
                VolumeBase* handle = handleMap_.find(url)->second;
                tgtAssert(handle, "handleMap_ contains null pointer");
                collection->add(handle);
            }
        }
    }

    return collection;
}
Beispiel #8
0
int EnumerateVolumes()
{
	HRESULT error;
    WCHAR volname[MAX_PATH+1];
	auto hFind = FindFirstVolume(volname, ARRAYSIZE(volname));
	if (hFind==INVALID_HANDLE_VALUE)
		return Usage(GetLastError(), L"FindFirstVolume() failed");
	while(true)
	{
		auto len = wcslen(volname);
		volname[len] = 0;
		auto v = new Volume();
		v->Init(volname, len);
		g_volumes.push_back(shared_ptr<Volume>(v));
		auto hasNext = FindNextVolume(hFind, volname, ARRAYSIZE(volname));
		if (hasNext)
			continue;
		error = GetLastError();
		if (error==ERROR_NO_MORE_FILES)
			error = 0;
		break;
	}
	FindVolumeClose(hFind);
	if (error!=0)
		return Usage(error, L"ProcessLv failed");
	return 0;
}
Beispiel #9
0
VolumeBase* ECAT7VolumeReader::read(const VolumeURL& origin)
    throw (tgt::FileException, std::bad_alloc)
{
    VolumeBase* result = 0;

    int volumeId = -1;
    std::string tmp = origin.getSearchParameter("volumeId");
    if (! tmp.empty())
        volumeId = stoi(tmp);

    VolumeList* collection = read(origin.getPath(), volumeId);

    if (collection && collection->size() == 1) {
        result = collection->first();
    }
    else if (collection && collection->size() > 1) {
        while(!collection->empty()) {
           VolumeBase* vh = collection->first();
           collection->remove(vh);
           delete vh;
        }
        delete collection;
        throw tgt::FileException("Only one volume expected", origin.getPath());
    }

    delete collection;

    return result;
}
Beispiel #10
0
VolumeBase* VolumeReader::read(const VolumeURL& origin)
    throw (tgt::FileException, std::bad_alloc)
{

    VolumeBase* result = 0;

    VolumeList* collection = read(origin.getPath());

    if (collection && collection->size() == 1) {
        result = collection->first();
    }
    else if (collection && collection->size() > 1) {
        delete collection;
        throw tgt::FileException("Only one volume expected", origin.getPath());
    }

    delete collection;

    return result;
}
Beispiel #11
0
VolumeList* MultiVolumeReader::read(const std::string& url)
    throw (tgt::FileException, std::bad_alloc)
{
    LINFO("Loading multi volume file " << url);
    VolumeURL urlOrigin(url);

    std::vector<VolumeURL> origins = listVolumes(url);
    if (origins.empty())
        throw tgt::FileException("No volumes listed in multi-volume file", url);

    VolumeList* volumeList = new VolumeList();

    std::string refFile = urlOrigin.getSearchParameter("file");
    if (refFile == "") {
        // no particular file specified in URL => load all listed ones
        for (size_t i=0; i<origins.size(); i++) {
            VolumeBase* handle = read(origins.at(i));
            if (handle)
                volumeList->add(handle);
        }
    }
    else {
        // load specified file
        for (size_t i=0; i<origins.size(); i++) {
            if (origins.at(i).getSearchParameter("file") == refFile) {
                VolumeBase* handle = read(origins.at(i));
                if (handle) {
                    volumeList->add(handle);
                    break;
                }
            }
        }

        if (volumeList->empty()) {
            delete volumeList;
            throw tgt::FileException("File '" + refFile + "' not listed in multi-volume file", urlOrigin.getPath());
        }
    }

    return volumeList;
}
  void FFT::convolve(VolumeList &vols, Volume &mask) {
    if (vols.size() > 0 && 
	vols[0].width == mask.width &&
	vols[0].height == mask.height &&
	vols[0].depth == mask.depth) {
      forward(vols);
      forward(mask);
      vols *= mask;
      size_t i = 0;
      for (size_t x = 0; x < vols[0].width; ++x) {
	for (size_t y = 0; y < vols[0].height; ++y) {
	  for (size_t z = 0; z < vols[0].complex_depth; ++z) {
	    if ((x+y+z) % 2) {
	      for (size_t j = 0; j < vols.size(); ++j) {
		vols[j].complex_data[i] *= -1.0;
	      }
	    }
	    ++i;
	  }
	}
      }
      backward(vols);
    }
  }
VolumeBase* AmiraMeshReader::read(const VolumeURL& origin)
    throw (tgt::FileException, std::bad_alloc)
{
    VolumeBase* result = 0;

    int timeframe = -1;
    std::string tmp = origin.getSearchParameter("timeframe");
    if (! tmp.empty())
        timeframe = stoi(tmp);

    VolumeList* collection = read(origin.getPath(), timeframe);

    if (collection && collection->size() == 1) {
        result = collection->first();
    }
    else if (collection && collection->size() > 1) {
        delete collection;
        throw tgt::FileException("Only one volume expected", origin.getPath());
    }

    delete collection;

    return result;
}
Beispiel #14
0
void VolumeURLProperty::loadVolume() throw (tgt::FileException, std::bad_alloc){

    std::string url = get();
    if (url.empty()) {
        LWARNING("loadVolume(): empty URL");
        return;
    }

    ProgressBar* progressBar = getProgressBar();
    if (progressBar) {
        progressBar->setTitle("Loading volume");
        progressBar->setProgressMessage("Loading volume ...");
    }
    VolumeSerializerPopulator serializerPopulator(progressBar);
    VolumeList* volumeList = serializerPopulator.getVolumeSerializer()->read(url);

    if (progressBar)
        progressBar->hide();

    if (volumeList && !volumeList->empty()) {
        VolumeBase* handle = volumeList->first();
        tgtAssert(handle, "No handle");
        setVolume(static_cast<Volume*>(handle));

        // delete superfluous volumes
        if (volumeList->size() > 1) {
            LWARNING("More than one volume loaded from file: " + url + ". Discarding surplus volumes!");
                for (size_t i=1; i<volumeList->size(); i++)
                    delete volumeList->at(i);
        }

        // property does take ownership of loaded handles
        volumeOwner_ = true;
    }

    delete volumeList;
}
Beispiel #15
0
void VolumeIOHelper::loadRawVolume(const std::string& filenameStd) {

    QString filename = QString::fromStdString(filenameStd);
    if (filename.isEmpty())
        return;

    // query raw parameters via dialog
    std::string objectModel;
    std::string format;
        int numFrames;
    tgt::ivec3 dim;
    tgt::vec3 spacing;
    int headerSkip;
    bool bigEndian;
    tgt::mat4 trafoMat = tgt::mat4::identity;
    RawVolumeWidget* rawVW = new RawVolumeWidget(parent_, tr("Please enter the properties for <br><strong>") + filename + "</strong>",
        objectModel, format, numFrames, dim, spacing, headerSkip, bigEndian, trafoMat);
    if (!rawVW->exec() == QDialog::Accepted)
        return;

    // derive expected file size from provided properties
    uint formatBytes = 1;;
    if (format == "USHORT" || format == "USHORT_12" || format == "SHORT")
        formatBytes = 2;
    else if (format == "FLOAT")
        formatBytes = 4;
    else if (format == "UINT" || format == "INT")
        formatBytes = 4;

    int numChannels = 1;
    if (objectModel == "RGB")
        numChannels = 3;
    else if (objectModel == "RGBA")
        numChannels = 4;
    else if (objectModel.find("TENSOR_") == 0)
        numChannels = 6;

    uint rawSize = headerSkip + formatBytes * numChannels * (dim.x * dim.y * dim.z) * numFrames;

    // inform/query user, if file size does not match
    if (QFile(filename).size() != rawSize) {
        QMessageBox::StandardButton retButton = QMessageBox::Yes;
        if(QFile(filename).size() > rawSize) {
            QString msg = tr("The provided properties result in a size smaller\nthan the actual file size. Do you want to continue?");
            retButton = QMessageBox::question(parent_, tr("Size mismatch"), msg,
                QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Yes);
        }
        else if (QFile(filename).size() < rawSize) {
            QString msg = tr("The provided properties result in a size\ngreater than the actual file size.");
            retButton = QMessageBox::warning(parent_, tr("Size mismatch"), msg,
                QMessageBox::Cancel);
        }
        if (retButton != QMessageBox::Yes && retButton != QMessageBox::Ok)
            return;
    }

    qApp->processEvents();

    // load raw volume
    try {
        for (int frame=0; frame < numFrames; ++frame) {
            RawVolumeReader rawReader(progressBar_);
            rawReader.setReadHints(dim, spacing, objectModel, format, frame, headerSkip, bigEndian);
            VolumeList* collection = rawReader.read(filename.toStdString());
            if (collection && !collection->empty()) {
                tgtAssert(collection->size() == 1, "More than one raw volume returned");
                Volume* volumeHandle = static_cast<Volume*>(collection->first());
                oldVolumePosition(volumeHandle);
                volumeHandle->setPhysicalToWorldMatrix(trafoMat);
                volumeHandle->setTimestep(static_cast<float>(frame));
                emit(volumeLoaded(volumeHandle));
            }
            delete collection;
        }
    }
    catch (const tgt::FileException& e) {
        LERROR(e.what());
        QErrorMessage* errorMessageDialog = new QErrorMessage(VoreenApplicationQt::qtApp()->getMainWindow());
        errorMessageDialog->showMessage(e.what());
    }
    catch (std::bad_alloc&) {
        LERROR("bad allocation while reading file: " << filename.toStdString());
        QErrorMessage* errorMessageDialog = new QErrorMessage(VoreenApplicationQt::qtApp()->getMainWindow());
        errorMessageDialog->showMessage("Bad allocation while reading file: " + filename);
    }
}
Beispiel #16
0
VolumeList* ECAT7VolumeReader::read(const std::string &url, int volumeId)
    throw(tgt::CorruptedFileException, tgt::IOException, std::bad_alloc)
{
    LINFO("Loading dataset " << url << " vid: " << volumeId);

    VolumeURL origin(url);
    std::string fileName = origin.getPath();
    FILE* fin = fopen(fileName.c_str(), "rb");

    if(!fin) {
        throw tgt::FileNotFoundException("ECAT7: File not found", fileName);
    }

    ECAT7VolumeReader::ECAT7Structure s = readStructure(fileName);

    VolumeList* vc = new VolumeList();

    for(size_t i=0; i<s.subVolumes_.size(); i++) {
        fseek(fin, s.subVolumes_[i].de_.startBlock_ * 512, SEEK_SET);
        fseek(fin, 512, SEEK_CUR); //skip past header (already read)

        tgt::svec3 dimensions = s.subVolumes_[i].getDimensions();
        //tgt::mat4 m = s.subVolumes_[i].getTransformation();
        tgt::vec3 spacing = s.subVolumes_[i].getSpacing();
        tgt::vec3 offset  = s.subVolumes_[i].getOffset();

        if(volumeId != -1) {
            if(volumeId != s.subVolumes_[i].getId())
                continue;
        }

        if(s.subVolumes_[i].ih_.num_dimensions != 3)
            continue;

        if (getProgressBar()) {
            getProgressBar()->setTitle("Loading Volume");
            getProgressBar()->setProgressMessage("Loading volume: " + fileName);
        }

        VolumeRAM* vol;
        RealWorldMapping denormalize;
        if(s.h_.file_type == 6) {
            vol = new VolumeRAM_UInt8(dimensions);
            denormalize = RealWorldMapping::createDenormalizingMapping<uint8_t>();
        }
        else if(s.h_.file_type == 7) {
            vol = new VolumeRAM_UInt16(dimensions);
            denormalize = RealWorldMapping::createDenormalizingMapping<uint16_t>();
        }
        else {
            LERROR("Unknown file format detected.");
            return 0;
        }

        float scale = s.subVolumes_[i].ih_.scale_factor * s.h_.ecat_calibration_factor;
        RealWorldMapping rwm(scale, 0.0f, s.h_.data_units);

        VolumeReader::read(vol, fin);

        // Assume that the pixel size values given in the ecat header are in cm.  Multiply spacing and offset
        // with 0.1 to convert to mm.
        Volume* vh = new Volume(vol, spacing * 0.1f, offset * 0.1f);
        vh->setRealWorldMapping(RealWorldMapping::combine(denormalize, rwm));

        if(s.swapEndianness_)
            VolumeOperatorSwapEndianness::APPLY_OP(vh);

        // TODO: This must depend on some parameter in the headers, figure out which and how
        bool mirrorZ = true;
        if(mirrorZ)
        {
            Volume* mirrored = VolumeOperatorMirrorZ::APPLY_OP(vh);
            delete vh;
            vh = mirrored;
        }

        VolumeURL o("ecat7", fileName);
        o.addSearchParameter("volumeId", itos(s.subVolumes_[i].de_.id_));
        vh->setOrigin(o);

        s.transformMetaData(vh->getMetaDataContainer(), static_cast<int>(i));

        if(length(offset) == 0.f)
            centerVolume(vh);

        vc->add(vh);

        if (getProgressBar())
            getProgressBar()->hide();
    }

    fclose(fin);
    return vc;
}
Beispiel #17
0
void VolumePlugin::manageVolumes()
{
	VolumeList *list = new VolumeList(this);
	list->show();
};
VolumeList* AmiraMeshReader::readMetaFile(const std::string &fileName, size_t firstSlice, size_t lastSlice, int timeframe)
    throw (tgt::FileException, std::bad_alloc)
{
	bool error = false;
	const char* FileName = fileName.c_str();
	FILE* fp = fopen(FileName, "rb");
    if (!fp)
    {
        LERROR("Could not find :" << FileName);
        error = true;
		goto K;
    }

    char buffer[2048];
    fread(buffer, sizeof(char), 2047, fp);
    buffer[2047] = '\0'; //The following string routines prefer null-terminated strings

    if (!strstr(buffer, "# AmiraMesh BINARY-LITTLE-ENDIAN 2.1") && !strstr(buffer, "# AmiraMesh 3D BINARY 2.0"))
    {
        LERROR("Not a proper AmiraMesh file.");
        fclose(fp);
        error = true;
		goto K;
    }

    //Find the Lattice definition, i.e., the dimensions of the uniform grid
    int xDim(0), yDim(0), zDim(0);
    sscanf(FindAndJump(buffer, "define Lattice"), "%d %d %d", &xDim, &yDim, &zDim);
	LDEBUG("Grid Dimensions: " << xDim << " " << yDim << " " << zDim);

    //Find the BoundingBox
    float xmin(1.0f), ymin(1.0f), zmin(1.0f);
    float xmax(-1.0f), ymax(-1.0f), zmax(-1.0f);
    sscanf(FindAndJump(buffer, "BoundingBox"), "%g %g %g %g %g %g", &xmin, &xmax, &ymin, &ymax, &zmin, &zmax);
    LDEBUG("BoundingBox in x-Direction: [" << xmin << " " << xmax << "]");
	LDEBUG("BoundingBox in x-Direction: [" << ymin << " " << ymax << "]");
	LDEBUG("BoundingBox in x-Direction: [" << zmin << " " << zmax << "]");
	
    //Is it a uniform grid? We need this only for the sanity check below.
    const bool bIsUniform = (strstr(buffer, "CoordType \"uniform\"") != NULL);
    LDEBUG("GridType: " << bIsUniform ? "uniform" : "UNKNOWN");

    //Type of the field: scalar, vector
    int NumComponents(0);
    if (strstr(buffer, "Lattice { float Data }"))
    {
        //Scalar field
        NumComponents = 1;
    }
    else
    {
        //A field with more than one component, i.e., a vector field
        sscanf(FindAndJump(buffer, "Lattice { float["), "%d", &NumComponents);
    }
    LDEBUG("Number of Components: " << NumComponents);

    //Sanity check
    if (xDim <= 0 || yDim <= 0 || zDim <= 0
        || xmin > xmax || ymin > ymax || zmin > zmax
        || !bIsUniform || NumComponents <= 0)
    {
        printf("Something went wrong\n");
        fclose(fp);
        error = true;
		goto K;
    }


	K : RawVolumeReader::ReadHints h;
	std::string objectFilename = fileName;

	h.headerskip_ = strstr(buffer, "# Data section follows") - buffer;
    //Set the file pointer to the beginning of "# Data section follows"
	fseek(fp, h.headerskip_, SEEK_SET);
    //Consume this line, which is "# Data section follows"
	char buf1[2048];
	fgets(buf1, 2047, fp);
	int l1 = strlen(buf1);

    //Consume the next line, which is "@1"
	char buf2[2048];
    fgets(buf2, 2047, fp);
	int l2 = strlen(buf2);

    vec3 sliceThickness = vec3(1.f, 1.f, 1.f);
    int numFrames = NumComponents;
	
	h.dimensions_.x = xDim;
	h.dimensions_.y = yDim;
	h.dimensions_.z = zDim;
	
	h.format_ = "FLOAT";
	h.objectModel_ = "I";
	h.bigEndianByteOrder_ = false;
	h.headerskip_ += (l1 + l2);
	LDEBUG("Header size : " << h.headerskip_);

    if (hor(lessThanEqual(h.dimensions_, ivec3(0)))) {
        LERROR("Invalid resolution or resolution not specified: " << h.dimensions_);
        error = true;
    }

    h.spacing_ = sliceThickness;
	h.timeStep_ = 0;

	if (!error) {
        RawVolumeReader rawReader(getProgressBar());

        // do we have a relative path?
        if ((objectFilename.substr(0, 1) != "/")  && (objectFilename.substr(0, 1) != "\\") &&
            (objectFilename.substr(1, 2) != ":/") && (objectFilename.substr(1, 2) != ":\\"))
        {
            size_t p = fileName.find_last_of("\\/");
            // construct path relative to dat file
            objectFilename = fileName.substr(0, p + 1) + objectFilename;
        }

        int start = 0;
        int end = numFrames;
        if (timeframe != -1) {
            if (timeframe >= numFrames)
                throw tgt::FileException("Specified time frame not in volume", fileName);

            start = timeframe;
            end = timeframe+1;
        }

        VolumeList* toReturn = new VolumeList();
        for (int frame = start; frame < end; ++frame) {
            h.timeframe_ = frame;
            rawReader.setReadHints(h);

            VolumeList* volumeList = rawReader.readSlices(objectFilename, firstSlice, lastSlice);
            if (!volumeList->empty()) {
                VolumeURL origin(fileName);
                origin.addSearchParameter("timeframe", itos(frame));

                Volume* vh = static_cast<Volume*>(volumeList->first());
                vh->setOrigin(origin);
                vh->setTimestep(static_cast<float>(frame));

                oldVolumePosition(vh);

                if(!h.hash_.empty())
                    vh->setHash(h.hash_);

                toReturn->add(volumeList->first());
            }
            delete volumeList;
        }
        return toReturn;
    }
    else {
        throw tgt::CorruptedFileException("error while reading data", fileName);
    }
}