bool OperationHelperRaster::resample(IRasterCoverage& raster1, IRasterCoverage& raster2, ExecutionContext *ctx) {
    if ( !raster1.isValid())
        return false;

    IGeoReference commonGeoref = raster1->georeference();
    if ( ctx->_masterGeoref != sUNDEF) {
        if(!commonGeoref.prepare(ctx->_masterGeoref))
            return false;
    }
    if (raster1->georeference()!= commonGeoref ){
        Resource res;
        res.prepare();
        QString expr = QString("%3=resample(%1,%2,bicubic)").arg(raster1->source().url().toString()).arg(commonGeoref->source().url().toString()).arg(res.name());
        ExecutionContext ctxLocal;
        SymbolTable symtabLocal;
        if(!commandhandler()->execute(expr,&ctxLocal,symtabLocal))
            return false;
        QVariant var = symtabLocal.getValue(res.name());
        raster1 = var.value<IRasterCoverage>();
    }
    if ( raster2.isValid() && raster2->georeference()!= commonGeoref ){
        Resource res;
        res.prepare();
        QString expr = QString("%3=resample(%1,%2,bicubic)").arg(raster2->source().url().toString()).arg(commonGeoref->source().url().toString()).arg(res.name());
        ExecutionContext ctxLocal;
        SymbolTable symtabLocal;
        if(!commandhandler()->execute(expr,&ctxLocal,symtabLocal))
            return false;
        QVariant var = symtabLocal.getValue(res.name());
        IRasterCoverage outRaster = var.value<IRasterCoverage>();
        raster2.assign(outRaster);
    }
    return true;
}
bool RasterCoverageConnector::loadMetaData(IlwisObject *data) {
    if(!CoverageConnector::loadMetaData(data))
        return false;

    auto *gcoverage = static_cast<RasterCoverage *>(data);

    IGeoReference grf;
    if(!grf.prepare(_resource.url().toLocalFile()))
        return ERROR2(ERR_COULDNT_CREATE_OBJECT_FOR_2,"Georeference",gcoverage->name() );

    gcoverage->georeference(grf);

    Size sz(gdal()->xsize(_dataSet), gdal()->ysize(_dataSet), gdal()->layerCount(_dataSet));
    gcoverage->size(sz);

    int layerIndex = 1;
    auto index = _internalPath.indexOf("layerindex=");
    if ( index == 0) {
        bool ok = true;
        layerIndex = _internalPath.mid(11).toInt(&ok);
        if (!ok)
            return ERROR2(ERR_COULD_NOT_LOAD_2,gcoverage->name(),"layer");
    }
    auto layerHandle = gdal()->getRasterBand(_dataSet, layerIndex);
    if (!layerHandle) {
        return ERROR2(ERR_COULD_NOT_LOAD_2, gcoverage->name(),"layer");
    }

    int ok;

    auto vmin = gdal()->minValue(layerHandle, &ok);
    auto vmax = gdal()->maxValue(layerHandle, &ok);
    gcoverage->datadef().range(new NumericRange(vmin, vmax));

    _gdalValueType = gdal()->rasterDataType(layerHandle);
    _typeSize = gdal()->getDataTypeSize(_gdalValueType) / 8;

    return true;
}
Example #3
0
Ilwis::OperationImplementation::State SelectionRaster::prepare(ExecutionContext *ctx, const SymbolTable &st)
{
    OperationImplementation::prepare(ctx,st);
    if ( _expression.parameterCount() != 2) {
        ERROR3(ERR_ILLEGAL_NUM_PARM3,"rasvalue","1",QString::number(_expression.parameterCount()));
        return sPREPAREFAILED;
    }
    IlwisTypes inputType = itRASTER;
    QString raster = _expression.parm(0).value();
    if (!_inputObj.prepare(raster, inputType)) {
        ERROR2(ERR_COULD_NOT_LOAD_2,raster,"");
        return sPREPAREFAILED;
    }
    IRasterCoverage inputRaster = _inputObj.as<RasterCoverage>();
    _inputAttributeTable = inputRaster->attributeTable();
    quint64 copylist = itCOORDSYSTEM ;


    QString selector = _expression.parm(1).value();
    parseSelector(selector, inputRaster);

    std::vector<QString> selectionBands = bands(inputRaster);
     _box = boundingBox(_inputObj.as<RasterCoverage>());
    bool useOldGrf ;
    if ( _box.isNull() || !_box.isValid()){
        _box = inputRaster->size();
        useOldGrf = true;
    } else
        useOldGrf = false;

    if ( useOldGrf){
        copylist |= itGEOREF | itRASTERSIZE | itENVELOPE;
    }


    int selectedAttributes = attributeNames().size();
    if (selectedAttributes != 1)
        copylist |= itDOMAIN;

     _outputObj = OperationHelperRaster::initialize(_inputObj,inputType, copylist);
     if ( !_outputObj.isValid()) {
         ERROR1(ERR_NO_INITIALIZED_1, "output coverage");
         return sPREPAREFAILED;
     }
     IRasterCoverage outputRaster = _outputObj.as<RasterCoverage>();

     QString outputName = _expression.parm(0,false).value();
     if ( outputName != sUNDEF)
         _outputObj->name(outputName);

     if ( selectedAttributes > 1) {
         QString url = INTERNAL_CATALOG + "/" + outputName;
         Resource resource(url, itFLATTABLE);
         _attTable.prepare(resource);
     }
     if ( selectedAttributes == 1 && _inputAttributeTable.isValid()){
        QStringList names = attributeNames();
        //outputRaster->datadefRef().domain(_inputAttributeTable->columndefinition(names[0]).datadef().domain());
        outputRaster->setDataDefintions(_inputAttributeTable->columndefinition(names[0]).datadef().domain(), selectionBands, inputRaster->stackDefinition().domain());
     }else
         outputRaster->setDataDefintions(inputRaster->datadef().domain(), selectionBands, inputRaster->stackDefinition().domain());



     if ( (copylist & itGEOREF) == 0) {
         Resource resource(QUrl(INTERNAL_CATALOG + "/" + outputRaster->name() + "_grf_" + QString::number(outputRaster->id())),itGEOREF);
         resource.addProperty("size", IVARIANT(_box.size()));
         auto envelope = inputRaster->georeference()->pixel2Coord(_box);
         resource.addProperty("envelope", IVARIANT(envelope));
         resource.addProperty("coordinatesystem", IVARIANT(inputRaster->coordinateSystem()));
         resource.addProperty("name", _outputObj->name());
         resource.addProperty("centerofpixel",inputRaster->georeference()->centerOfPixel());
         IGeoReference  grf;
         grf.prepare(resource);
         outputRaster->georeference(grf);
         outputRaster->envelope(envelope);
    }


    return sPREPARED;
}
Example #4
0
Ilwis::OperationImplementation::State Selection::prepare(ExecutionContext *, const SymbolTable &)
{
    if ( _expression.parameterCount() != 2) {
        ERROR3(ERR_ILLEGAL_NUM_PARM3,"rasvalue","1",QString::number(_expression.parameterCount()));
        return sPREPAREFAILED;
    }
    IlwisTypes inputType = itRASTER;
    QString raster = _expression.parm(0).value();
    if (!_inputObj.prepare(raster, inputType)) {
        ERROR2(ERR_COULD_NOT_LOAD_2,raster,"");
        return sPREPAREFAILED;
    }
    IRasterCoverage inputRaster = _inputObj.as<RasterCoverage>();
    quint64 copylist = itCOORDSYSTEM;


    QString selector = _expression.parm(1).value();
    selector = selector.remove('"');

    int index = selector.indexOf("box=");
    Envelope box;
    if ( index != -1) {
        QString crdlist = "box(" + selector.mid(index+4) + ")";
        _box = BoundingBox(crdlist);
        box = inputRaster->georeference()->pixel2Coord(_box);
        copylist |= itDOMAIN | itTABLE;
        std::vector<qint32> vec{_box.min_corner().x, _box.min_corner().y,_box.min_corner().z};
        _base = vec;

    }
    index = selector.indexOf("polygon=");
    if ( index != -1)
    {
        //TODO:
        copylist |= itDOMAIN | itTABLE;
    }
    index = selector.indexOf("attribute=");
    if ( index != -1 ) {
        if (! inputRaster->attributeTable().isValid()) {
            ERROR2(ERR_NO_FOUND2,"attribute-table", "coverage");
            return sPREPAREFAILED;
        }
        _attribColumn =  selector.mid(index+10);
        copylist |= itRASTERSIZE | itGEOREF | itENVELOPE;
    }
    int indexindex = selector.indexOf("index=");
    if ( indexindex != -1) {
        copylist |= itDOMAIN | itGEOREF | itENVELOPE | itTABLE;
        _box = BoundingBox(inputRaster->size());
        QString zvalues = selector.mid(6);
        bool ok;
        _zvalue = zvalues.toInt(&ok);
        if ( !ok || _zvalue < 0) {
            ERROR3(ERR_ILLEGAL_PARM_3, TR("layer index"), zvalues,"Selection");
            return sPREPAREFAILED;
        }
        _box.min_corner().z = _zvalue;
        _box.max_corner().z = _zvalue;
        std::vector<qint32> vec{_box.min_corner().x, _box.min_corner().y,_box.min_corner().z};
        _base = vec;
    }

     _outputObj = OperationHelperRaster::initialize(_inputObj,inputType, copylist);
     if ( !_outputObj.isValid()) {
         ERROR1(ERR_NO_INITIALIZED_1, "output coverage");
         return sPREPAREFAILED;
     }
     IRasterCoverage outputRaster = _outputObj.as<RasterCoverage>();
     if ( (copylist & itDOMAIN) == 0) {
         outputRaster->datadefRef() = _attribColumn != "" ? inputRaster->attributeTable()->columndefinition(_attribColumn).datadef()
                                                   : outputRaster->datadefRef() = inputRaster->datadef();
     }
     QString outputName = _expression.parm(0,false).value();
     if ( outputName != sUNDEF)
         _outputObj->name(outputName);
     if ( (copylist & itGEOREF) == 0) {
        Resource resource(QUrl("ilwis://internalcatalog/georeference"),itGEOREF);
        resource.addProperty("size", IVARIANT(_box.size()));
        resource.addProperty("envelope", IVARIANT(box));
        resource.addProperty("coordinatesystem", IVARIANT(inputRaster->coordinateSystem()));
        resource.addProperty("name", _outputObj->name());
        resource.addProperty("centerofpixel",inputRaster->georeference()->centerOfPixel());
        IGeoReference  grf;
        grf.prepare(resource);
        outputRaster->georeference(grf);
        outputRaster->envelope(box);
    }
     if(indexindex != -1)  {
         Size<> sz(outputRaster->size().xsize(),outputRaster->size().xsize(), 1);
         outputRaster->size(sz);
     }

    return sPREPARED;
}
IlwisObject *InternalIlwisObjectFactory::createRasterCoverage(const Resource& resource, const IOOptions &options) const {
    if ( !resource.isValid()) {
        ERROR1(ERR_NO_INITIALIZED_1,"resource");
        return 0;
    }
    RasterCoverage *gcoverage = createFromResource<RasterCoverage>(resource, options);
    if (!createCoverage(resource, gcoverage, options))
        return 0;

    Size<> sz;
    QString typenm = resource["size"].typeName();
    if ( typenm == "Ilwis::Size<quint32>"){
        sz = resource["size"].value<Size<>>();
    } else if (typenm == "QSize") {
        sz = resource["size"].toSize();
    } else if (typenm == "QString") {
        QStringList parts = resource["size"].toString().split(" ");
        if ( parts.size() >= 2)
            sz = Size<>(parts[0].toInt(), parts[1].toInt(), 1);
        if ( parts.size() == 3)
            sz.zsize(parts[2].toInt());
    }

    gcoverage->gridRef()->prepare(gcoverage, sz);

    IGeoReference grf;
    QString tpnam = resource["georeference"].typeName();
    if (tpnam == "Ilwis::IGeoReference")
        grf = resource["georeference"].value<Ilwis::IGeoReference>();
    else if( tpnam == "QString"  && resource["georeference"].toString() != sUNDEF) {
        Resource newresource = resource.property2Resource("georeference", itGEOREF);
        if ( newresource.isValid()) {
            if (!grf.prepare(newresource))
                return 0;
        }
    } else if ( tpnam == "qulonglong"){
        if(!grf.prepare(resource["georeference"].value<quint64>()))
                return 0;

    } else{
        Envelope bounds = gcoverage->envelope();
        if ( bounds.isValid() && !bounds.isNull()){
            grf = new GeoReference();
            grf->create("corners");
            grf->name("subset_" + gcoverage->name());
            grf->coordinateSystem(gcoverage->coordinateSystem());
			QSharedPointer< CornersGeoReference> spGrf = grf->as< CornersGeoReference>();
			spGrf->internalEnvelope(bounds);
            grf->size(sz);
            if (!grf->compute()){
                ERROR1(ERR_COULDNT_CREATE_OBJECT_FOR_1, "Georeference");
                return 0;
            }

        }

    }
    if ( grf.isValid())
        gcoverage->georeference(grf);
    if ( sz.isValid())
        gcoverage->size(sz);

    return gcoverage;
}
Ilwis::OperationImplementation::State AggregateRaster::prepare(ExecutionContext *, const SymbolTable & )
{
    QString raster = _expression.parm(0).value();
    QString outputName = _expression.parm(0,false).value();
    int copylist = itDOMAIN | itCOORDSYSTEM;

    if (!_inputObj.prepare(raster, itRASTER)) {
        ERROR2(ERR_COULD_NOT_LOAD_2,raster,"");
        return sPREPAREFAILED;
    }
    _method = toMethod(_expression.parm(1).value());
    if ( _method == NumericStatistics::pLAST) {
        ERROR2(ERR_ILLEGAL_VALUE_2, "parameter value", " aggregation method");
        return sPREPAREFAILED;
    }
    bool ok;
    quint32 groupSz = _expression.parm(2).value().toInt(&ok);
    if (!ok) {
        QString blist = _expression.parm(2).value();
        blist.remove("{");
        blist.remove("}");
        QStringList dims = blist.split(" ");
        if ( dims.size() > 0) {
            for(int i=0; i < dims.size(); ++i)     {
                quint32 val = dims[i].toInt(&ok);
                if ( ok) {
                    _groupSize[i] = val;
                }else
                    break;
            }
        }

    }else {
        _groupSize[0] = groupSz;
        _groupSize[1] = groupSz;

    }
    if ( !ok || groupSize() < 2) {
        ERROR2(ERR_ILLEGAL_VALUE_2, "aggregation group size", QString::number(groupSize()));
        return sPREPAREFAILED;
    }

    _grouped = _expression.parm(3).value().toLower() == "true";
    if ( !_grouped)
        copylist |= itGEOREF;

    _outputObj = OperationHelperRaster::initialize(_inputObj,itRASTER, copylist);
    if ( !_outputObj.isValid()) {
        ERROR1(ERR_NO_INITIALIZED_1, "output rastercoverage");
        return sPREPAREFAILED;
    }
    QString outputBaseName = outputName;
    int index = 0;
    if ( (index = outputName.lastIndexOf(".")) != -1) {
        outputBaseName = outputName.left(index);
    }
    IRasterCoverage inputRaster = _inputObj.as<RasterCoverage>();
    IRasterCoverage outputRaster = _outputObj.as<RasterCoverage>();
    if ( outputName != sUNDEF)
        _outputObj->name(outputName);
    outputRaster->coordinateSystem(inputRaster->coordinateSystem());

    BoundingBox box(inputRaster->size());
    if ( _grouped) {
        int xs = box.xlength();
        int ys = box.ylength();
        int zs = box.zlength();
        int newxs = xs / groupSize(0);
        int newys = ys / groupSize(1);
        int newzs = zs / groupSize(2);
        box = BoundingBox(Size<>(newxs, newys, newzs));

    }
    if ( _expression.parameterCount() == 5 || _grouped) {
        Envelope envlope = inputRaster->envelope();
        Resource resource(QUrl("ilwis://internalcatalog/georeference"),itGEOREF);
        resource.addProperty("size", IVARIANT(box.size()));
        resource.addProperty("envelope", IVARIANT(envlope));
        resource.addProperty("coordinatesystem", inputRaster->coordinateSystem()->id());
        resource.addProperty("name", outputBaseName);
        resource.addProperty("centerofpixel",inputRaster->georeference()->centerOfPixel());
        IGeoReference  grf;
        if (grf.prepare(resource)) {
            mastercatalog()->addItems({resource});
            outputRaster->georeference(grf);
        }
        outputRaster->envelope(envlope);
        outputRaster->size(box.size());
    }

    initialize(outputRaster->size().linearSize());

    return sPREPARED;
}
bool RasterCoverageConnector::loadMetaData(IlwisObject *data, const IOOptions &options){

    if(!CoverageConnector::loadMetaData(data, options))
        return false;

    auto *raster = static_cast<RasterCoverage *>(data);

    if (_handle->type() == GdalHandle::etGDALDatasetH){
        Coordinate cMin, cMax;
        quint32 layer = sourceRef().hasProperty("bandindex")? sourceRef()["bandindex"].toUInt(): iUNDEF;
        Size<> rastersize(gdal()->xsize(_handle->handle()), gdal()->ysize(_handle->handle()), layer != iUNDEF ? 1 : gdal()->layerCount(_handle->handle()));

        _offsetScales.resize(rastersize.zsize());

        std::vector<double> bands(layer != iUNDEF  ? 1 : rastersize.zsize());
        for(int i =0; i < rastersize.zsize(); ++i){
            bands[i] = i;
        }
        raster->stackDefinitionRef().setSubDefinition(IDomain("count"),bands);

        auto layerHandle = gdal()->getRasterBand(_handle->handle(), layer != iUNDEF  ? layer + 1 : 1);
        GDALColorInterp colorType = gdal()->colorInterpretation(layerHandle);
        bool ok = false;
        if ( layer != iUNDEF){
            raster->size(rastersize);

            if (sourceRef().hasProperty("scale") && sourceRef().hasProperty("offset")) {
                _offsetScales[layer].offset = sourceRef()["offset"].toDouble();
                _offsetScales[layer].scale = sourceRef()["scale"].toDouble();
            }

            ok = handleNumericLayerCase(layer, raster);
        }else if( colorType <=1 || layer != iUNDEF){ // no colors + grayscale which equals image domain
                    raster->size(rastersize);
                    ok = handleNumericCase(raster->size(), raster);
        } else if ( colorType >= 3 && colorType <= 12){
            raster->size(Size<>(rastersize.xsize(), rastersize.ysize(), layer != iUNDEF  ? 1 : rastersize.zsize() / 3));
            ok = handleColorCase(raster->size(), raster,colorType);
        }else if (colorType == 2){ // color palette
            ok = handlePaletteCase(rastersize, raster);
        }

        if (!ok)
            return false;

        IGeoReference georeference;
        double geosys[6];
        CPLErr err = gdal()->getGeotransform(_handle->handle(), geosys) ;
        if ( err == CE_None) {
            double a1 = geosys[0];
            double b1 = geosys[3];
            double a2 = geosys[1];
            double b2 = geosys[5];
            Coordinate crdLeftup( a1 , b1);
            Coordinate crdRightDown(a1 + rastersize.xsize() * a2, b1 + rastersize.ysize() * b2 ) ;
            cMin = Coordinate( min(crdLeftup.x, crdRightDown.x), min(crdLeftup.y, crdRightDown.y));
            cMax = Coordinate( max(crdLeftup.x, crdRightDown.x), max(crdLeftup.y, crdRightDown.y));

            if(!georeference.prepare(_resource.url().toString()))
                return ERROR2(ERR_COULDNT_CREATE_OBJECT_FOR_2,"Georeference",raster->name() );
        } else {
            int iNrTiePoints = gdal()->getGCPCount(_handle->handle());
            if (iNrTiePoints > 0) {
                const GDAL_GCP* amtp = gdal()->getGCPs(_handle->handle());
                Envelope envTieLimits;
                for (int i = 0; i < iNrTiePoints; i++) {
                    Coordinate crdtiep(amtp[i].dfGCPX,amtp[i].dfGCPY,0);
                    envTieLimits += crdtiep;
                }
                cMin = envTieLimits.min_corner();
                cMax = envTieLimits.max_corner();
                if(!georeference.prepare(_resource.url().toString()))
                    return ERROR2(ERR_COULDNT_CREATE_OBJECT_FOR_2,"Georeference",raster->name() );
            } else {
                cMin = Coordinate( 0, 0 );
                cMax = Coordinate( rastersize.xsize() - 1, rastersize.ysize() - 1);
                if(!georeference.prepare("code=georef:undetermined"))
                    return ERROR2(ERR_COULDNT_CREATE_OBJECT_FOR_2,"Georeference",raster->name() );
                georeference->coordinateSystem(raster->coordinateSystem()); // the grf.prepare() for internal ilwis georeferences (among others "undetermined") does not autmatically set its csy
                georeference->envelope(Envelope(cMin, cMax));
            }
        }

        georeference->size(rastersize);
        georeference->compute();

        raster->envelope(Envelope(cMin, cMax));
        raster->coordinateSystem()->envelope(raster->envelope());
        raster->georeference(georeference);
        //if (!raster->gridRef()->prepare(raster,rastersize))
        //    return false;

        return true;

    }else{
        return ERROR2(ERR_INVALID_PROPERTY_FOR_2,"non-RasterCoverage",_fileUrl.toLocalFile());
    }
}