Skip to content

Processing: Rasterize a vector layer #567

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
140 changes: 139 additions & 1 deletion packages/base/src/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,11 @@ import keybindings from './keybindings.json';
import { JupyterGISTracker } from './types';
import { JupyterGISDocumentWidget } from './widget';
import { getGdal } from './gdal';
import { getGeoJSONDataFromLayerSource, downloadFile } from './tools';
import {
getGeoJSONDataFromLayerSource,
downloadFile,
uint8ArrayToBase64
} from './tools';
import { ProcessingFormDialog } from './dialogs/ProcessingFormDialog';

interface ICreateEntry {
Expand Down Expand Up @@ -1405,6 +1409,140 @@ export function addCommands(
}
});

commands.addCommand(CommandIDs.rasterize, {
label: trans.__('Rasterize'),
isEnabled: () => {
const selectedLayer = getSingleSelectedLayer(tracker);
return selectedLayer
? ['VectorLayer', 'ShapefileLayer'].includes(selectedLayer.type)
: false;
},
execute: async () => {
const selectedLayer = getSingleSelectedLayer(tracker);
if (!selectedLayer) {
return;
}

const model = tracker.currentWidget?.model as IJupyterGISModel;
const sources = model.sharedModel.sources ?? {};

const exportSchema = {
...(formSchemaRegistry.getSchemas().get('Rasterize') as IDict)
};
console.log(exportSchema);

const formValues = await new Promise<IDict>(resolve => {
const dialog = new ProcessingFormDialog({
title: 'Rasterize Layer',
schema: exportSchema,
model,
formContext: 'create',
processingType: 'export',
sourceData: {
resolutionX: 1200,
resolutionY: 1200,
outputLayerName: selectedLayer.name + ' Rasterized'
},
syncData: (props: IDict) => {
resolve(props);
dialog.dispose();
}
});

dialog.launch();
});

if (!formValues || !selectedLayer.parameters) {
return;
}

const outputFileName = formValues.outputLayerName;
const resolutionX = formValues.resolutionX ?? 1200;
const resolutionY = formValues.resolutionY ?? 1200;
const sourceId = selectedLayer.parameters.source;
const source = sources[sourceId];

const geojsonString = await getGeoJSONDataFromLayerSource(source, model);
if (!geojsonString) {
return;
}

const Gdal = await getGdal();
const datasetList = await Gdal.open(
new File([geojsonString], 'data.geojson', {
type: 'application/geo+json'
})
);
const dataset = datasetList.datasets[0];

if (!dataset) {
console.error('Dataset could not be opened.');
return;
}

const options = [
'-of',
'GTiff',
'-ot',
'Float32',
'-a_nodata',
'-1.0',
'-burn',
'0.0',
'-ts',
resolutionX.toString(),
resolutionY.toString(),
'-l',
'data',
'data.geojson',
'output.tif'
];

const outputFilePath = await Gdal.gdal_rasterize(dataset, options);
const exportedBytes = await Gdal.getFileBytes(outputFilePath);

const base64String = uint8ArrayToBase64(exportedBytes);

const jgisFilePath = tracker.currentWidget?.model.filePath;
const jgisDir = jgisFilePath
? jgisFilePath.substring(0, jgisFilePath.lastIndexOf('/'))
: '';

// Ensure the path is valid and construct the save path
const savePath = jgisDir
? `${jgisDir}/${outputFileName}.tif`
: `${outputFileName}.tif`;

await app.serviceManager.contents.save(savePath, {
type: 'file',
format: 'base64',
content: base64String
});

Gdal.close(dataset);

// Store in shared model
const newSourceId = UUID.uuid4();
const sourceModel: IJGISSource = {
type: 'GeoTiffSource',
name: outputFileName,
parameters: {
urls: [{ url: `${outputFileName}.tif`, min: 0, max: 1000 }]
}
};

const layerModel: IJGISLayer = {
type: 'WebGlLayer',
parameters: { source: newSourceId },
visible: true,
name: outputFileName
};

model.sharedModel.addSource(newSourceId, sourceModel);
model.addLayer(UUID.uuid4(), layerModel);
}
});

loadKeybindings(commands, keybindings);
}

Expand Down
1 change: 1 addition & 0 deletions packages/base/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export namespace CommandIDs {
// Processing commands
export const buffer = 'jupytergis:buffer';
export const dissolve = 'jupytergis:dissolve';
export const rasterize = 'jupytergis:rasterize';

// Sources only commands
export const newRasterSource = 'jupytergis:newRasterSource';
Expand Down
2 changes: 0 additions & 2 deletions packages/base/src/dialogs/ProcessingFormDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,6 @@ export class ProcessingFormDialog extends Dialog<IDict> {

// Modify schema to include layer options and layer name field
if (options.schema) {
console.log(options.schema.properties?.inputLayer);

if (options.schema.properties?.inputLayer) {
options.schema.properties.inputLayer.enum = layerOptions.map(
option => option.value
Expand Down
8 changes: 8 additions & 0 deletions packages/base/src/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -922,3 +922,11 @@ export async function getGeoJSONDataFromLayerSource(
console.error("Source is missing both 'path' and 'data' parameters.");
return null;
}

export const uint8ArrayToBase64 = (uint8Array: Uint8Array): string => {
let binaryString = '';
for (let i = 0; i < uint8Array.length; i++) {
binaryString += String.fromCharCode(uint8Array[i]);
}
return btoa(binaryString);
};
10 changes: 2 additions & 8 deletions packages/schema/src/schema/export/exportGeotiff.json
Original file line number Diff line number Diff line change
@@ -1,16 +1,10 @@
{
"type": "object",
"description": "ExportGeoTIFFSchema",
"description": "Rasterize",
"title": "IExportGeoTIFF",
"required": ["exportFileName", "resolutionX", "resolutionY"],
"required": ["resolutionX", "resolutionY"],
"additionalProperties": false,
"properties": {
"exportFileName": {
"type": "string",
"title": "GeoTiFF File Name",
"default": "exported_layer",
"description": "The name of the exported GeoTIFF file."
},
"resolutionX": {
"type": "number",
"title": "Resolution (Width)",
Expand Down
4 changes: 4 additions & 0 deletions python/jupytergis_lab/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,10 @@ const plugin: JupyterFrontEndPlugin<void> = {
command: CommandIDs.dissolve
});

processingSubmenu.addItem({
command: CommandIDs.rasterize
});

app.contextMenu.addItem({
type: 'submenu',
selector: '.jp-gis-layerItem',
Expand Down
Loading