"""
* Copyright (c) 2009 Stanford University, School of Medicine All rights reserved. 
* 
* STANFORD ACADEMIC SOFTWARE LICENSE AGREEMENT 
* FOR AngioLocalize SOURCE CODE: 
* 
* 1.  This is a legal agreement between you, RECIPIENT, and STANFORD UNIVERSITY.  
*       By accepting, receiving, and using AngioLocalize.including any accompanying information, materials or 
*       manuals (Program), you are agreeing to be bound by the terms of this Agreement.  
*       If you do not agree to the terms of this Agreement, promptly return the Program to the STANFORD.

* 2.  STANFORD grants to RECIPIENT a royalty-free, nonexclusive, and nontransferable license to use the Program 
*       and accompanying source code furnished hereunder, upon the terms and conditions set out below. 
*       documentation and/or other materials provided with the distribution. 
* 3.  RECIPIENT acknowledges that the Program is a research tool still in the development stage and that 
*       it is being supplied as is, without any accompanying services, support or improvements from STANFORD.
* 4.  RECIPIENT agrees to use the Program solely for internal non-commercial purposes. 
* 5.  RECIPIENT may create derivatives and further transfer the Program under the following terms and conditions: 
*        A) Recipient agrees to not commercially exploit the Program and agrees all uses will be for non-commercial purposes; and,
*        B) Recipient may not mark any derivatives with the title of Program and may not to use iPad mark for any derivatives; and,
*        C) Recipient agrees to mark and acknowledge all derivatives as follows: "This is a derivative work based on AngioLocalize:
*           Frameless AVM localization with 2D Digital Subtraction Angiography (DSA) and 3D Rotational Angiography (DRA) Images developed
*           by Dimitre Hristov, Lina Liu.
*        D) Recipient agrees to make all improvements, enhancements and derivatives available under 
*           similar terms and conditions to the research community. 
* 6.   RECIPIENT warrants that RECIPIENT will not remove or export any part of the software or Program from the United 
*       States except in full compliance with all United States and other applicable laws and regulations.
* 7.  RECIPIENT will use the Program in compliance with all applicable laws, policies and regulations including, but not 
*       limited to, any approvals, informed consent and patient confidentiality principles.
* 8.   RECIPIENT will indemnify, hold harmless, and defend Stanford against any claim of any kind arising out of or
*       related to the exercise of any rights granted under this Agreement or the breach of this Agreement by RECIPIENT.
* 9.  Title and copyright to the Program and any associated documentation shall at all times remain with STANFORD, 
*       and RECIPIENT agrees to preserve same.
""" 
#----------------------------------------------------------------------------------
#! Macro module Registration_3D_2D
#/*!
# \file    Registration_3D_2D.py
# \author  Dimitre Hristov
# \date    2009-12-10
#
# 
#*/
#----------------------------------------------------------------------------------

from mevis import *
from PythonQt import *

## Current Frame global variable
currentFrame=0;

## Picks up image thresholds and ROI from the viewer
## and segments the centerline of the 3D DSA vessels
def segment3DMarkers():
  center=ctx.field("VesselViewer.greyCenter").value;
  width=ctx.field("VesselViewer.greyWidth").value;
  ctx.field("Segment3Dtree.threshMin").value=ctx.field("image3D.input0").minValue()+(ctx.field("image3D.input0").maxValue()-ctx.field("image3D.input0").minValue())*center;
  ctx.field("Segment3Dtree.threshMax").value=ctx.field("image3D.input0").maxValue();
  ctx.field("SelectRoi.apply").touch();
  ctx.field("centerline.clear").touch();
  ctx.field("centerline.update").touch();
  ctx.field("MarkedCenterline.update").touch();

## Shows an MPR view of the 3D image and segmented vessel tree
## additional landmarks can be added by placing markers
def showMPRview():
  ctx.control("Display").selectTabAtIndex(2);

## Displays the projection of the segmented 3D centerline and 
## lets the user select a frame for the 2D segmentation
def reviewDSAframes():
  ctx.field("View2DSelection.drawingOn").value = False ;
  ctx.control("Display").selectTabAtIndex(0);
  ctx.disconnectField("SelectFrame.input0");
  ctx.connectField("View2D.inImage","image2D.output0");
  ctx.connectField("WorldVoxelConvert.input0","image2D.output0");
  ctx.field("SoView2DCSOEditor.self").disconnectOutputs();

## select DSA Frame
def selectDSAframe():
  global currentFrame;
  currentFrame=ctx.field("View2D.startSlice").value;
#  print currentFrame
  
## Set up the data flow by setting the single frame the user set up
## in select DSA frame
def setSingleDSAframe():
  ctx.control("Display").selectTabAtIndex(0);
  ctx.field("CSOManager.removeAllCSOsAndGroups").touch();
  ctx.field("View2DSelection.drawingOn").value = True ;
  ctx.field("Mask.input1").connectFrom(ctx.field("CSOConvertToImage.output0"));
  ctx.field("Mask.mode").value = "Original";
  ctx.connectField("SelectFrame.input0","image2D.output0");
  ctx.field("SelectFrame.fullSize").touch();
  global currentFrame;
  ctx.field("SelectFrame.z").value=currentFrame;
  ctx.field("SelectFrame.sz").value=1;
  ctx.field("SelectFrame.apply").touch();
  ctx.connectField("View2D.inImage","SelectFrame.output0");
  ctx.connectField("WorldVoxelConvert.input0","SelectFrame.output0")

## turn on ROI
def turnROIon():
  ctx.field("SoView2DCSOEditor.self").disconnectOutputs();
  ctx.module("SoGroup").addChild(ctx.module("SoView2DCSOEditor").field("self"));
  ctx.field("View2DItems.i05showItem").value=False ;
  ctx.field("View2DItems.i06showItem").value=True ;
  print "test i5"
  return ;

## turn off ROI
def turnROIoff():
  ctx.field("SoView2DCSOEditor.self").disconnectOutputs();
  ctx.field("View2DItems.i05showItem").value=True;
  ctx.field("View2DItems.i06showItem").value=False;
  return;

## change the display
def changeDisplay():
  selection=ctx.field("View2DSelection.lastSelectedId").value;
  if selection == 'DSAframe':
    ctx.connectField("View2D.inImage","SelectFrame.output0");
  elif selection == 'Skeleton':
    if ctx.field("DtfSkeletonization.output0").isValid():
      ctx.field("View2D.inImage").connectFrom(ctx.field("DtfSkeletonization.output0"));
  elif selection == 'Distance':
    if ctx.field("EuclideanDTF.output0").isValid():
      ctx.field("View2D.inImage").connectFrom(ctx.field("MemCache.output0"));
  elif selection == 'Threshold':
    ctx.field("View2D.inImage").connectFrom(ctx.field("IntervalThresh.output0"));
  elif selection == 'ROI_ON':
    print "ROI on selected"
    turnROIon();
  elif selection == 'ROI_OFF':
    print "ROI off selected"
    turnROIoff();
    
## segment 2D markers  
def segment2DMarkers():
  ctx.field("CSOConvertToImage.apply").touch();
  if ctx.field("CSOConvertToImage.output0").isValid():
    ctx.field("Mask.mode").value = "MaskedOriginal";
  else:
    ctx.field("Mask.mode").value = "Original";
  ctx.field("DtfSkeletonization.clear").touch();
  ctx.field("DtfSkeletonization.update").touch();
  ctx.field("EuclideanDTF.clear").touch();
  ctx.field("EuclideanDTF.update").touch();
  ctx.field("MemCache.clear").touch();
  ctx.field("MemCache.update").touch();
  ctx.field("ChamferMatching.input0").connectFrom(ctx.field("MemCache.output0"));
  print "test";

## automatic registration
def automaticRegistration():
  ctx.control("Display").selectTabAtIndex(0);
  ctx.field("Mask.input1").disconnect();
  ctx.field("CSOManager.removeAllCSOsAndGroups").touch();
  ctx.field("View2DSelection.drawingOn").value = True ;
  if ctx.field("CSOConvertToImage.input0").isValid():
      ctx.field("CSOConvertToImage.apply").touch();

## start the registration      
def startRegistration():
  if ctx.field("CSOConvertToImage.input0").isValid():
      ctx.field("CSOConvertToImage.apply").touch();
      ctx.field("ChamferMatching.input1").connectFrom(ctx.field("CSOConvertToImage.output0"));
  ctx.field("ChamferMatching.start").touch();
  ctx.field("ChamferMatching.input1").disconnect();

## An interactive registration tab
def InteractiveRegistration():
## We have selected the interactive registration tab
  ctx.field("MatrixArithmetic.matrixA").value=ctx.field("ChamferMatching.matrix1").value;
  ctx.field("AngioTransformEdit.reset").touch();
  ctx.control("Display").selectTabAtIndex(0);
  ctx.field("View2DSelection.drawingOn").value = False ;
  ctx.disconnectField("SelectFrame.input0");
  ctx.connectField("View2D.inImage","image2D.output0");
  ctx.connectField("WorldVoxelConvert.input0","image2D.output0");
  global currentFrame;
  print currentFrame
  ctx.field("View2D.startSlice").value=currentFrame;
  ctx.field("SoView2DCSOEditor.self").disconnectOutputs();
 
## trigger the parent callback function when "save" button is clicked. 
def saveOnRegManual():
  ctx.field("saveReg").touch();
  
## trigger the parent callback function when "approve and save" button is clicked  
def approveOnRegManual():
  ctx.field("saveApprove").touch();

## trigger the parent callback function when "cancel" button is clicked 
def cancelonRegManual():
  ctx.field("cancel").touch();  

## show help when "help" button is clicked
def helponRegManual():
  ctx.showHtmlHelp();






#//# MeVis signature v1
#//# key: MFowDQYJKoZIhvcNAQEBBQADSQAwRgJBANEfsmYse2e1dRhkQ9AQbreCq9uxwzWLoGom13MNYmyfwoJqQOEXljLFAgw2eEjaT12G4CdqKWhRxh9ANP6n7GMCARE=:VI/mB8bT4u+mRtf/ru8yUQi8BzpaS3UeL2x62YxsUYnVqCWuLrVNLiukIIjnJMKQXlc8ezmgOIcVAV7pgvgKpQ==
#//# owner: MeVis
#//# date: 2009-06-10T04:12:25
#//# hash: vHSfj+Qt8xrIkDVP4W0Rep0YH6a3+MySa0+Cs+AoqEK/IbB+f5szwmyVTENOjzz/JEgm2t31FtHmUUMFcQg5VQ==
#//# MeVis end

