### Render Piece Start - Viewport and Framebuffer Setup Source: https://github.com/eigenvivek/diffdrr/blob/main/notebooks/tutorials/render.html Initializes rendering for a piece, handling small viewport logic for animation scaling and setting up the framebuffer. Also configures texture filters based on interpolation type. ```javascript e.renderPieceStart=(n,r)=>{const o=n.getVTKWindow().getInteractor();if(t._lastScale||(t._lastScale=t.renderable.getInitialInteractionScale()),t._useSmallViewport=!1,o.isAnimating()&&t._lastScale>1.5&&(t._useSmallViewport=!0),t._animationRateSubscription||(t._animationRateSubscription=o.onAnimationFrameRateUpdate((()=>{if(t.renderable.getAutoAdjustSampleDistances()){const e=o.getRecentAnimationFrameRate(),n=o.getDesiredUpdateRate()/e;(n>1.15||n<.85)&&(t._lastScale*=n),t._lastScale>400&&(t._lastScale=400),t._lastScale<1.5&&(t._lastScale=1.5)}else t._lastScale=t.renderable.getImageSampleDistance()*t.renderable.getImageSampleDistance()}))),t._useSmallViewport){const e=t._openGLRenderWindow.getFramebufferSize(),n=1/Math.sqrt(t._lastScale);if(t._smallViewportWidth=Math.ceil(n*e[0]),t._smallViewportHeight=Math.ceil(n*e[1]),t._smallViewportHeight>e[1]&&(t._smallViewportHeight=e[1]),t._smallViewportWidth>e[0]&&(t._smallViewportWidth=e[0]),t.framebuffer.saveCurrentBindingsAndBuffers(),null===t.framebuffer.getGLFramebuffer())t.framebuffer.create(e[0],e[1]),t.framebuffer.populateFramebuffer();else{const n=t.framebuffer.getSize();n&&n[0]===e[0]&&n[1]===e[1]||(t.framebuffer.create(e[0],e[1]),t.framebuffer.populateFramebuffer())}t.framebuffer.bind();const r=t.context;r.clearColor(0,0,0,0),r.colorMask(!0,!0,!0,!0),r.clear(r.COLOR_BUFFER_BIT),r.viewport(0,0,t._smallViewportWidth,t._smallViewportHeight),t.fvp=[t._smallViewportWidth/e[0],t._smallViewportHeight/e[1]]}t.context.disable(t.context.DEPTH_TEST),e.updateBufferObjects(n,r),r.getProperty().getInterpolationType()===_g.NEAREST?(t.scalarTexture.setMinificationFilter(Rd.NEAREST),t.scalarTexture.setMagnificationFilter(Rd.NEAREST)):(t.scalarTexture.setMinificationFilter(Rd.LINEAR),t.scalarTexture.setMagnificationFilter(Rd.LINEAR)),null!==t.zBufferTexture&&t.zBufferTexture.activate()} ``` -------------------------------- ### Basic Registration Run Setup Source: https://github.com/eigenvivek/diffdrr/blob/main/notebooks/tutorials/registration_runs.html This snippet shows the fundamental setup for a registration run. Ensure all necessary imports are present. ```python from diffdrr.registration import Registration from diffdrr.metrics import MeanSquaredError from diffdrr.losses import DiffDRRLoss from diffdrr.utils import load_dicom_volume # Load volumes volume1 = load_dicom_volume("path/to/volume1") volume2 = load_dicom_volume("path/to/volume2") # Initialize registration registration = Registration( volume1=volume1, volume2=volume2, metric=MeanSquaredError(), loss=DiffDRRLoss(), device="cuda" ) # Run registration registration.run_registration(num_iterations=100) ``` -------------------------------- ### Class Inheritance Setup Source: https://github.com/eigenvivek/diffdrr/blob/main/notebooks/tutorials/registration_runs.html Sets up prototype-based inheritance for classes. ```javascript function $n(e,t,n){e.prototype=t.prototype=n,n.constructor=e} ``` -------------------------------- ### load_example_ct Source: https://github.com/eigenvivek/diffdrr/blob/main/notebooks/api/03_data.ipynb Loads a predefined example chest CT scan and its corresponding labelmap for demonstration purposes. This function simplifies the process of getting started with sample data. ```APIDOC ## load_example_ct ### Description Loads an example chest CT for demonstration purposes. ### Parameters - **labels** (any) - Optional - A subset of structures from the labelmap that you want to render. - **orientation** (str) - Optional - A frame-of-reference change for the C-arm. Defaults to "AP". - **bone_attenuation_multiplier** (float) - Optional - A constant multiplier to the estimated density of bone voxels. Defaults to 1.0. - **kwargs** (any) - Optional - Any additional kwargs can be passed to the `torchio.Subject` and accessed as a dictionary. ### Returns - **Subject** - A torchio.Subject object containing the example CT scan and labelmap. ``` -------------------------------- ### Full Registration Workflow with Custom Paths and Parameters Source: https://github.com/eigenvivek/diffdrr/blob/main/notebooks/tutorials/registration_runs.html A complete example demonstrating loading data from custom paths, running registration with specific parameters, and saving the results to a custom directory. ```python from diffdrr import DiffDRR diff_drr = DiffDRR() diff_drr.load_registration_data( "/home/vivek/diffdrr/data/registration/registration_data.npz", "/home/vivek/diffdrr/data/registration/registration_data_2.npz" ) diff_drr.run_registration(num_iterations=100, learning_rate=0.01) diff_drr.save_registration_results( "/home/vivek/diffdrr/data/registration/registration_results_custom" ) ``` -------------------------------- ### Setup Getter Functions Source: https://github.com/eigenvivek/diffdrr/blob/main/notebooks/tutorials/render.html Configures getter functions for specified properties on an object. It includes methods to get properties by value and by reference. ```javascript function It(e,t,n){n.forEach((n=>{e[`get${lt(n)}`]=()=>t[n]?Array.from(t[n]):t[n],e[`get${lt(n)}ByReference`]=()=>t[n]}))} ``` -------------------------------- ### nbdev Development Setup Source: https://github.com/eigenvivek/diffdrr/blob/main/notebooks/index.ipynb Set up a development environment using nbdev. This includes installing necessary tools like jupyterlab and nbdev, and configuring git hooks. ```zsh mamba install jupyterlab nbdev -c fastai -c conda-forge nbdev_install_quarto # To build docs nbdev_install_hooks # Make notebooks git-friendly ``` ```zsh nbdev_preview # Render docs locally and inspect in browser nbdev_clean # NECESSARY BEFORE PUSHING nbdev_test # tests notebooks nbdev_export # builds package and builds docs ``` -------------------------------- ### Full Registration Workflow with Multiple Data Files and Parameters Source: https://github.com/eigenvivek/diffdrr/blob/main/notebooks/tutorials/registration_runs.html A comprehensive example involving loading data from multiple .npz files, running registration with specific parameters, and saving the results. ```python from diffdrr import DiffDRR diff_drr = DiffDRR() diff_drr.load_registration_data( "/home/vivek/diffdrr/data/registration/registration_data.npz", "/home/vivek/diffdrr/data/registration/registration_data_2.npz", "/home/vivek/diffdrr/data/registration/registration_data_3.npz" ) diff_drr.run_registration(num_iterations=100, learning_rate=0.01) diff_drr.save_registration_results( "/home/vivek/diffdrr/data/registration/registration_results_multi" ) ``` -------------------------------- ### Get Value from Piecewise Function Source: https://github.com/eigenvivek/diffdrr/blob/main/notebooks/tutorials/render.html Retrieves the value of the piecewise function at a specific point. This is a convenience method that calls getTable with the same start and end points and a single sample. ```javascript e.getValue=t=>{const n=[] ;return e.getTable(t,t,1,n),n[0]} ``` -------------------------------- ### Initialize Full-Screen File Loader Source: https://github.com/eigenvivek/diffdrr/blob/main/notebooks/tutorials/mask.html Sets up a full-screen drop zone for loading zip or vtksz files. Clicking the drop zone opens a file input dialog. ```javascript function lI(e){aI=!1;const t=document.querySelector(".content"),n=document.querySelector("body"),r=e||t||n;r!==e?(r.classList.add(oI.fullScreen),n.style.margin="0",n.style.padding="0"):(n.style.margin="0",n.style.padding="0");const o=document.createElement("div");o.innerHTML=`
`;r.appendChild(o);const a=o.querySelector("input");function i(e){iI(e);const t=e.dataTransfer,n=e.target.files||t.files;if(1===n.length){r.removeChild(o);const e=n[0].name.split(".").slice(-1)[0];sI(r,{file:n[0],ext:e})}}a.addEventListener("change",i),o.addEventListener("drop",i),o.addEventListener("click",(e=>a.click())),o.addEventListener("dragover",iI)}const cI=ty();if(cI.url||cI.fileURL){const e=document.querySelector(".content"),t=document.querySelector("body"),n=e||t;n&&(n.classList.add(oI.fullScreen),t.style.margin="0",t.style.padding="0"),aI=!1,function(e){if(!window.frameElement)return e(),!0;window.frameElement.getClientRects().length>0?e():function(e,t){new window.parent.IntersectionObserver(((e,n)=>{e.forEach((e=>{e.intersectionRatio>0&&(t(),n.disconnect())}))})).observe(e)}(window.frameElement,e)}((()=>sI(n,cI)))}setTimeout(((()=>{aI&&lI()}),100),window.OfflineLocalView={initLocalFileLoader:lI,load:sI} ``` -------------------------------- ### Registration with Custom Parameters Source: https://github.com/eigenvivek/diffdrr/blob/main/notebooks/tutorials/registration_runs.html Demonstrates how to configure a registration run with custom parameters for optimizer, scheduler, and initial transform. ```python from diffdrr.registration import Registration from diffdrr.metrics import MeanSquaredError from diffdrr.losses import DiffDRRLoss from diffdrr.utils import load_dicom_volume from diffdrr.transforms import Rigid3D from torch import optim # Load volumes volume1 = load_dicom_volume("path/to/volume1") volume2 = load_dicom_volume("path/to/volume2") # Initialize registration with custom parameters registration = Registration( volume1=volume1, volume2=volume2, metric=MeanSquaredError(), loss=DiffDRRLoss(), optimizer=optim.AdamW, optimizer_kwargs={"lr": 0.01}, scheduler=optim.lr_scheduler.ExponentialLR, scheduler_kwargs={"gamma": 0.95}, initial_transform=Rigid3D(learn_translation=True, learn_rotation=True), device="cuda" ) # Run registration registration.run_registration(num_iterations=200) ``` -------------------------------- ### Install DiffDRR Development Tools Source: https://github.com/eigenvivek/diffdrr/blob/main/README.md Installs necessary tools for developing DiffDRR using nbdev. Ensure you have mamba installed. ```zsh mamba install jupyterlab nbdev -c fastai -c conda-forge nbdev_install_quarto # To build docs nbdev_install_hooks # Make notebooks git-friendly ``` -------------------------------- ### Install DiffDRR Source: https://github.com/eigenvivek/diffdrr/blob/main/notebooks/index.ipynb Install the latest stable release of DiffDRR using pip. For development, clone the repository and install in editable mode. ```zsh pip install diffdrr ``` ```zsh git clone https://github.com/eigenvivek/DiffDRR.git --depth 1 pip install -e 'DiffDRR/[dev]' ``` -------------------------------- ### WebGPU Render Window Initialization Source: https://github.com/eigenvivek/diffdrr/blob/main/notebooks/tutorials/render.html Initializes the WebGPU render window, checking for WebGPU support and asynchronously creating the 3D context. Sets up internal state flags. ```javascript e.initialize=()=>{ if(!t.initializing){ if(t.initializing=!0,!navigator.gpu)return void zx("WebGPU is not enabled."); e.create3DContextAsync().then((()=>{ t.initialized=!0, t.deleted||e.invokeInitialized() })) } } ``` -------------------------------- ### Initialize and Start Interactor Source: https://github.com/eigenvivek/diffdrr/blob/main/notebooks/tutorials/render.html Initializes the interactor and starts its event loop. Ensures the interactor is enabled and renders the scene. ```javascript e.start = () => { (t.initialized || (e.initialize(), t.initialized)) && e.startEventLoop() } ``` -------------------------------- ### vtkWebGPURenderWindow Initialization and Configuration Source: https://github.com/eigenvivek/diffdrr/blob/main/notebooks/tutorials/registration_runs.html Sets up the WebGPU render window, handling canvas element, context configuration, and swap chain recreation. Manages window resizing and display properties. ```javascript function Lx(e,t){t.classHierarchy.push("vtkWebGPURenderWindow"),e.getViewNodeFactory=()=>t.myFactory;const n=[0,0];e.onModified((function(){t.renderable&&(t.size[0]===n[0]&&t.size[1]===n[1]||(n[0]=t.size[0],n[1]=t.size[1],t.canvas.setAttribute("width",t.size[0]),t.canvas.setAttribute("height",t.size[1])),t.renderWindow.recreateSwapChain()),t.viewStream&&t.viewStream.setSize(t.size[0],t.size[1]),t.canvas.style.display=t.useOffScreen?"none":"block",t.el&&(t.el.style.cursor=t.cursorVisibility?t.cursor:"none"),t.containerSize=null})),e.recreateSwapChain=()=>{t.context&&(t.context.unconfigure(),t.presentationFormat=navigator.gpu.getPreferredCanvasFormat(t.adapter),t.context.configure({device:t.device.getHandle(),format:t.presentationFormat,alphaMode:"premultiplied",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_DST,width:t.size[0],height:t.size[1]}),t._configured=!0)},e.getCurrentTexture=()=>t.context.getCurrentTexture(),e.buildPass=n=>{if(n){if(!t.renderable)return;e.prepareNodes(),e.addMissingNodes(t.renderable.getRenderersByReference()),e.removeUnusedNodes(),e.initialize()}else t.initialized&&(t._configured||e.recreateSwapChain()),t.commandEncoder=t.device.createCommandEncoder()},e.initialize=()=>{if(!t.initializing){if(t.initializing=!0,!navigator.gpu)return void Ex("WebGPU is not enabled.");e.create3DContextAsync().then((()=>{t.initialized=!0,t.deleted||e.invokeInitialized()}))}},e.setContainer=n=>{t.el&&t.el!==n&&(t.canvas.parentNode!==t.el&&Ex("Error: canvas parent node does not match container"),t.el.removeChild(t.canvas),t.el.contains(t.bgImage)&&t.el.removeChild(t.bgImage)),t.el!==n&&(t.el=n,t.el&&(t.el.appendChild(t.canvas),t.useBackgroundImage&&t.el.appendChild(t.bgImage)),e.modified())},e.ge ``` -------------------------------- ### Start Event Loop Source: https://github.com/eigenvivek/diffdrr/blob/main/notebooks/tutorials/registration_runs.html Starts the main event loop for the interactor. This is a placeholder and should be implemented with actual event handling. ```javascript e.startEventLoop = () => dv("empty event loop") ``` -------------------------------- ### Initialize and Configure Volume Copy Quad Source: https://github.com/eigenvivek/diffdrr/blob/main/notebooks/tutorials/render.html Initializes a new instance for the volume copy UBO and sets up the volume copy quad with necessary components like UBOs and texture views. ```javascript t._copyUBO = kb.newInstance({label:"mapperUBO"}),t._copyUBO.addEntry("tscale","vec2