xp1632 / VPE_IP

0 stars 0 forks source link

Ori_VPL_project_doc_summary_with_plan_for_ImageJ_Extension #53

Open xp1632 opened 5 months ago

xp1632 commented 5 months ago

1. To Use ImageJ functions in VP, we need to know:


xp1632 commented 5 months ago

2. VP documemts summary:

Knowledge Graph:

https://github.com/Max-ChenFei/Visual-Programming-Language/blob/main/doc/Knowledge%20Graph.md.md


Image has structure as :

image = {
    'dataType': 'string',  # Replace 'string' with the actual data type
    'value': None,         # Replace None with the actual value
    'metadata': metadata
}
from typing import Literal
metadata = {
    'colorChannel': Literal['rgb', 'gbr', 'grayscale'],
    'channelOrder': Literal['none', 'channelFirst', 'channelLast'],
    'isMiniBatched': bool,
    'intensityRange': Literal['0-255', '0-1'],
    'device': Literal['cpu', 'gpu']
}

xp1632 commented 5 months ago

Conversion Code Generation in Visual Programming

https://github.com/Max-ChenFei/Visual-Programming-Language/blob/main/doc/Knowledge%20Graph.md.md#conversion-code-generation-in-visual-programming


How to add new Image Type and conversion rule:

{
  "description": "image conversion",
  "imageTypeConversion": {
    "imageTypes": [
      {
        "name": "numpy.ndarray",
        "functionName": "numpyndarray2numpyndarray",
        "function": "function numpyndarray2numpyndarray() { #... return 'numpyndarray2numpyndarray'; }"
      },
      {
        "name": "torch.tensor",
        "functionName": "torchtensor2torchtensor",
        "function": "function torchtensor2torchtensor() { #... return 'torchtensor2torchtensor'; }"
      }
    ],
    "ImageTypeConversions": [
      {
        "from": "numpy.ndarray",
        "to": "torch.tensor",
        "functionName": "numpyndarrayToTorchtensor",
        "function": "function numpyndarrayToTorchtensor() { #... return 'numpyndarrayToTorchtensor'; }"
      },
      {
        "from": "torch.tensor",
        "to": "numpy.ndarray",
        "functionName": "torchtensorToNumpyndarray",
        "function": "function torchtensorToNumpyndarray() { #... return 'torchtensorToNumpyndarray'; }"
      }
    ]
  }
}
xp1632 commented 5 months ago

Node Type Specification

——————


export interface NodeConfig {
  category: string;
  title?: string;
  inputs?: Record<string, HandleConfig>;
  outputs?: Record<string, HandleConfig>;
  tooltip?: string;
  [key: string]: any;
  dataType?: string; // the data type for all the handles
  enable?: boolean;
  codeGenerator?: string;
  externalImports?: string;
}

Code Generation:

xp1632 commented 5 months ago

Code Generation:


Example of Desired external Function --> VP Exec Node


export interface NodeConfig {
  category: string;
  title?: string;
  inputs?: Record<string, HandleConfig>;
  outputs?: Record<string, HandleConfig>;
  tooltip?: string;
  [key: string]: any;
  dataType?: string; // the data type for all the handles
  enable?: boolean;
  codeGenerator?: string;
  externalImports?: string;
}

externalImports

codeGenerator

function code(inputs, outputs, node, generator) {  
 // 1. Read an image and assign it to an output variable.
 // 2. Create a metadata dictionary and attach when dealing with image data.
 // 3. Prepare the execution sequence for the subsequent code.
  const code = `${outputs[1]} = io.read_image(${inputs[1]}, ${inputs[2]})
${outputs[1]} = {
  'value': ${outputs[1]},
  'dataType': 'torch.tensor',
  'metadata': {
    'colorChannel': 'rgb',
    'channelOrder': 'channelFirst',
    'isMiniBatched': false,
    'intensityRange': '0-255',
    'device': 'cpu'
  }
}
${outputs[0]}`;
  return code;
}
// Convert the code generation function to a string format for JSON configuration.
const codeGeneratorFunction = code; // Assign the function for conversion
const jsonFormattedString = JSON.stringify(codeGeneratorFunction.toString());
console.log(jsonFormattedString);
{
    "read_image": {
        "type": "read_image",
        "category": "function",
        "title": "read_image",
        "tooltip": "Reads a JPEG or PNG image into a 3 dimensional RGB or grayscale Tensor. Optionally converts the image to the desired format. The values of the output tensor are uint8 in [0, 255].",
        "externalImports": "from torchvision import io\nfrom torchvision.io import ImageReadMode",
        "codeGenerator": "function code(inputs, outputs, node, generator) {\r\n  // Begin Python code generation\r\n  const code = `${outputs[1]} = io.read_image(${inputs[1]}, ${inputs[2]})\r\n${outputs[1]} = {\r\n  'value': ${outputs[1]},\r\n  'dataType': 'torch.tensor',\r\n  'metadata': {\r\n    'colorChannel': 'rgb',\r\n    'channelOrder': 'channelFirst',\r\n    'isMiniBatched': False,\r\n    'intensityRange': '0-255',\r\n    'device': 'cpu'\r\n  }\r\n}\r\n${outputs[0]}`;\r\n  return code;\r\n}",
        "inputs": {
            "execIn": {
                "title": "execIn",
                "tooltip": "execIn",
                "dataType": "exec",
                "showWidget": false,
                "showTitle": false
            },
            "path": {
                "title": "path",
                "dataType": "string",
                "tooltip": "path(str) - path of the JPEG or PNG image."
            },
            "mode": {
                "title": "mode",
                "dataType": "imageio.ImageReadMode",
                "default": "ImageReadMode.UNCHANGED",
                "tooltip": "mode(ImageReadMode) - The read mode used for optionally converting the image. Default: ImageReadMode.UNCHANGED."
            }
        },
        "outputs": {
            "execOut": {
                "title": "execOut",
                "tooltip": "execOut",
                "dataType": "exec",
                "showWidget": false,
                "showTitle": false
            },
            "image": {
                "title": "image",
                "dataType": "image",
                "defaultValue": {
                    "dataType": "torch.tensor"
                },
                "tooltip": "{dataType: torch.tensor, value, layout: [chw], colorMode: [rgb, grayscale], intensityRange: 0-255' device: cpu}"
            }
        }
    }
}
xp1632 commented 5 months ago

Example of a VP Value Node without exec handle:

externalImports

- we don't need extra import for `plus` operation 
  - since it's defaultly supporetd

codeGenerator

- we don't need exec handle for this node, so array index starts from 0
function code(inputs, outputs, node, generator) {
 // Perfom plus operation.
 // *NOT NEED deal with execution sequence for the subsequent code, so the index starts   from the 0.
  const code = `${outputs[0]} = ${inputs.filter(s => s.length > 0).join(' + ')}`;
  return code;
}

final JSON node specification for plus operation

{
  "+": {
    "type": "+",
    "category": "math",
    "title": "+",
    "tooltip": "Addition of objects",
    "enableAddNewOne": true,
    "dataType": "anyDataType",
    "codeGenerator": "function code(inputs, outputs, node, generator) {\n  return `${outputs[0]} = ${inputs.filter(s => s.length > 0).join(' + ')}`;\n}",
    "inputs": {
      "in1": {
        "dataType": "anyDataType",
        "title": "in",
        "showTitle": false
      },
      "in2": {
        "dataType": "anyDataType",
        "showTitle": false
      }
    },
    "outputs": {
      "out": {
        "dataType": "anyDataType",
        "title": "out",
        "showTitle": false
      }
    }
  }
}
xp1632 commented 5 months ago

Summary of Automatic Image Transitions via Knowledge graph

Image Data Structure:

Image Metadata:

interface ImageMetadata {
  colorChannel: 'rgb' | 'gbr' | 'grayscale';
  channelOrder: 'none' | 'channelFirst' | 'channelLast';
  isMiniBatched: boolean;
  intensityRange: '0-255' | '0-1';
  device: 'cpu' | 'gpu';
}

SourceImage or DestinationImage

interface ISourceImage {
  dataType: string;
  value: any;
  metadata: ImageMetadata;
}

interface IDestinationImage {
  dataType: string;
  value: any;
  metadata: ImageMetadata[];
}

export type Image = ISourceImage | IDestinationImage;

Example of SourceImage:

output_node_torchvision_read_image = {
    'dataType': 'torch.tensor',
    'value': torch.tensor([3, 20, 20], device='cpu'),
    'metadata': {
        'colorChannel': 'rgb',
        'channelOrder': 'channelFirst',
        'isMiniBatched': False,
        'intensityRange': '0-255',  # Assuming default 8-bit image, modify if different
        'device': 'cpu'  # Default device unless specified otherwise
    }
}

Example of DestinationImage

input_node_matplotlib_imshow = {
    'dataType': 'numpy.ndarray',
    'value': None,
    'metadata': [
        {
            'colorChannel': 'rgb',
            'channelOrder': 'channelLast',
            'isMiniBatched': False,
            'intensityRange': '0-255',
            'device': 'cpu'
        },
        {
            'colorChannel': 'grayscale',
            'channelOrder': 'none',  # No channels for grayscale
            'isMiniBatched': False,
            'intensityRange': '0-255',
            'device': 'cpu'
        }
    ]
}
xp1632 commented 5 months ago

Example of SourceImage:

  • output of the pytorch read_image node is a SourceImage:
output_node_torchvision_read_image = {
    'dataType': 'torch.tensor',
    'value': torch.tensor([3, 20, 20], device='cpu'),
    'metadata': {
        'colorChannel': 'rgb',
        'channelOrder': 'channelFirst',
        'isMiniBatched': False,
        'intensityRange': '0-255',  # Assuming default 8-bit image, modify if different
        'device': 'cpu'  # Default device unless specified otherwise
    }
}

Example of DestinationImage

  • input of matlab imshow node is DestinationImage
  • this node is flexiable in accepting both RGB and grayscale images]
  • thus there're two metadata entries:
input_node_matplotlib_imshow = {
    'dataType': 'numpy.ndarray',
    'value': None,
    'metadata': [
        {
            'colorChannel': 'rgb',
            'channelOrder': 'channelLast',
            'isMiniBatched': False,
            'intensityRange': '0-255',
            'device': 'cpu'
        },
        {
            'colorChannel': 'grayscale',
            'channelOrder': 'none',  # No channels for grayscale
            'isMiniBatched': False,
            'intensityRange': '0-255',
            'device': 'cpu'
        }
    ]
}

Questions:

xp1632 commented 5 months ago

Knowledge Graph Paradigm


Transitions rules (Edges) in Knowledge Graph

Intraconversion

Interconversion