<commit_before>'''
Created on 22 Jun 2010

@author: filo
'''
from nipype.interfaces.base import CommandLine, CommandLineInputSpec,\
    DynamicTraitedSpec
import xml.dom.minidom
import enthought.traits.api as traits
import os
from nipype.interfaces.traits import File
from nipype.utils.misc import isdefined
from enthought.traits.trait_base import Undefined


path = "/home/filo/tmp/slicer/Slicer3-build/lib/Slicer3/Plugins"

class SlicerCommandLineInputSpec(DynamicTraitedSpec, CommandLineInputSpec):
    module = traits.Str()

class SlicerCommandLine(CommandLine):
    input_spec = SlicerCommandLineInputSpec
    output_spec = DynamicTraitedSpec
        
    
    def _grab_xml(self):
        cmd = CommandLine(command = self.cmd, args="--xml")
        ret = cmd.run()
        return xml.dom.minidom.parseString(ret.runtime.stdout)
    
    def _outputs(self):
        base = super(SlicerCommandLine, self)._outputs()
        undefined_output_traits = {}
        for key in [node.getElementsByTagName('name')[0].firstChild.nodeValue for node in self._outputs_nodes]:
            base.add_trait(key, File(exists = True))
            undefined_output_traits[key] = Undefined
            
        base.trait_set(trait_change_notify=False, **undefined_output_traits)
        return base
    
    def __init__(self, module, **inputs):
        super(SlicerCommandLine, self).__init__(command= os.path.join(path, module), name= module, **inputs)
        dom = self._grab_xml()
        self._outputs_filenames = {}
        
        self._outputs_nodes = []
        
        undefined_traits = {}
        
        for paramGroup in dom.getElementsByTagName("parameters"):
            for param in paramGroup.childNodes:
                if param.nodeName in ['label', 'description', '#text', '#comment']:
                    continue
                traitsParams = {}
                
                name = param.getElementsByTagName('name')[0].firstChild.nodeValue
                
                longFlagNode = param.getElementsByTagName('longflag')
                if longFlagNode:
                    traitsParams["argstr"] = "--" + longFlagNode[0].firstChild.nodeValue + " " 
                else:
                    traitsParams["argstr"] = "--" + name + " "
                    
                    
                argsDict = {'file': '%s', 'integer': "%d", 'double': "%f", 'float': "%f", 'image': "%s", 'transform': "%s", 'boolean': '', 'string-enumeration': '%s', 'string': "%s"}
                    
                if param.nodeName.endswith('-vector'):
                    traitsParams["argstr"] += argsDict[param.nodeName[:-7]]
                else:
                    traitsParams["argstr"] += argsDict[param.nodeName]
                
                index = param.getElementsByTagName('index')
                if index:
                    traitsParams["position"] = index[0].firstChild.nodeValue
                    
                desc = param.getElementsByTagName('description')
                if index:
                    traitsParams["desc"] = desc[0].firstChild.nodeValue
                
                name = param.getElementsByTagName('name')[0].firstChild.nodeValue
                
                typesDict = {'integer': traits.Int, 'double': traits.Float, 'float': traits.Float, 'image': File, 'transform': File, 'boolean': traits.Bool, 'string': traits.Str, 'file':File}
                            
                if param.nodeName == 'string-enumeration':
                    type = traits.Enum
                    values = [el.firstChild.nodeValue for el in param.getElementsByTagName('element')]
                elif param.nodeName.endswith('-vector'):
                    type = traits.List
                    values = [typesDict[param.nodeName[:-7]]]
                    traitsParams["sep"] = ','
                else:
                    values = []
                    type = typesDict[param.nodeName]
                
                if param.nodeName in ['file', 'directory', 'image', 'transform'] and param.getElementsByTagName('channel')[0].firstChild.nodeValue == 'output':
                    self.inputs.add_trait(name, traits.Either(traits.Bool, File, **traitsParams))
                    undefined_traits[name] = Undefined
                    
                    #traitsParams["exists"] = True
                    self._outputs_filenames[name] = self._gen_filename_from_param(param)
                    #undefined_output_traits[name] = Undefined
                    #self._outputs().add_trait(name, File(*values, **traitsParams))
                    self._outputs_nodes.append(param)
                else:
                    if param.nodeName in ['file', 'directory', 'image', 'transform']:
                        traitsParams["exists"] = True
                    self.inputs.add_trait(name, type(*values, **traitsParams))
                    undefined_traits[name] = Undefined
                
        self.inputs.trait_set(trait_change_notify=False, **undefined_traits)
        for name in undefined_traits.keys():
            value = getattr(self.inputs, name)
        #self._outputs().trait_set(trait_change_notify=False, **undefined_output_traits)
        
    def _gen_filename(self, name):
        if name in self._outputs_filenames:
            return self._outputs_filenames[name]
        return None
    
    def _gen_filename_from_param(self,param):
        base = param.getElementsByTagName('name')[0].firstChild.nodeValue
        fileExtensions = param.getAttribute("fileExtensions")
        if fileExtensions:
            ext = fileExtensions
        else:
            ext = {'image': '.nii', 'transform': '.txt', 'file': ''}[param.nodeName]
        return os.path.abspath(base + ext)
    
    def _list_outputs(self):
        outputs = self.output_spec().get()
        for output_node in self._outputs_nodes:
            name = output_node.getElementsByTagName('name')[0].firstChild.nodeValue
            outputs[name] = getattr(self.inputs, name)
            if isdefined(outputs[name]) and isinstance(outputs[name], bool):
                if outputs[name]:<commit_msg>abs path for outputs, using slicer launch now, exceptions if module not found<commit_after>'''
Created on 22 Jun 2010

@author: filo
'''
from nipype.interfaces.base import CommandLine, CommandLineInputSpec,\
    DynamicTraitedSpec
import xml.dom.minidom
import enthought.traits.api as traits
import os
from nipype.interfaces.traits import File
from nipype.utils.misc import isdefined
from enthought.traits.trait_base import Undefined


class SlicerCommandLineInputSpec(DynamicTraitedSpec, CommandLineInputSpec):
    module = traits.Str()

class SlicerCommandLine(CommandLine):
    input_spec = SlicerCommandLineInputSpec
    output_spec = DynamicTraitedSpec
        
    
    def _grab_xml(self, module):
        cmd = CommandLine(command = "Slicer3", args="--launch %s --xml"%module)
        ret = cmd.run()
        if ret.runtime.returncode == 0:
            return xml.dom.minidom.parseString(ret.runtime.stdout)
        else:
            raise Exception(cmd.cmdline + " failed:\n%s"%ret.runtime.stderr)
    
    def _outputs(self):
        base = super(SlicerCommandLine, self)._outputs()
        undefined_output_traits = {}
        for key in [node.getElementsByTagName('name')[0].firstChild.nodeValue for node in self._outputs_nodes]:
            base.add_trait(key, File(exists = True))
            undefined_output_traits[key] = Undefined
            
        base.trait_set(trait_change_notify=False, **undefined_output_traits)
        return base
    
    def __init__(self, module, **inputs):
        super(SlicerCommandLine, self).__init__(command= "Slicer3 --launch %s "%module, name= module, **inputs)
        dom = self._grab_xml(module)
        self._outputs_filenames = {}
        
        self._outputs_nodes = []
        
        undefined_traits = {}
        
        for paramGroup in dom.getElementsByTagName("parameters"):
            for param in paramGroup.childNodes:
                if param.nodeName in ['label', 'description', '#text', '#comment']:
                    continue
                traitsParams = {}
                
                name = param.getElementsByTagName('name')[0].firstChild.nodeValue
                
                longFlagNode = param.getElementsByTagName('longflag')
                if longFlagNode:
                    traitsParams["argstr"] = "--" + longFlagNode[0].firstChild.nodeValue + " " 
                else:
                    traitsParams["argstr"] = "--" + name + " "
                    
                    
                argsDict = {'file': '%s', 'integer': "%d", 'double': "%f", 'float': "%f", 'image': "%s", 'transform': "%s", 'boolean': '', 'string-enumeration': '%s', 'string': "%s"}
                    
                if param.nodeName.endswith('-vector'):
                    traitsParams["argstr"] += argsDict[param.nodeName[:-7]]
                else:
                    traitsParams["argstr"] += argsDict[param.nodeName]
                
                index = param.getElementsByTagName('index')
                if index:
                    traitsParams["position"] = index[0].firstChild.nodeValue
                    
                desc = param.getElementsByTagName('description')
                if index:
                    traitsParams["desc"] = desc[0].firstChild.nodeValue
                
                name = param.getElementsByTagName('name')[0].firstChild.nodeValue
                
                typesDict = {'integer': traits.Int, 'double': traits.Float, 'float': traits.Float, 'image': File, 'transform': File, 'boolean': traits.Bool, 'string': traits.Str, 'file':File}
                            
                if param.nodeName == 'string-enumeration':
                    type = traits.Enum
                    values = [el.firstChild.nodeValue for el in param.getElementsByTagName('element')]
                elif param.nodeName.endswith('-vector'):
                    type = traits.List
                    values = [typesDict[param.nodeName[:-7]]]
                    traitsParams["sep"] = ','
                else:
                    values = []
                    type = typesDict[param.nodeName]
                
                if param.nodeName in ['file', 'directory', 'image', 'transform'] and param.getElementsByTagName('channel')[0].firstChild.nodeValue == 'output':
                    self.inputs.add_trait(name, traits.Either(traits.Bool, File, **traitsParams))
                    undefined_traits[name] = Undefined
                    
                    #traitsParams["exists"] = True
                    self._outputs_filenames[name] = self._gen_filename_from_param(param)
                    #undefined_output_traits[name] = Undefined
                    #self._outputs().add_trait(name, File(*values, **traitsParams))
                    self._outputs_nodes.append(param)
                else:
                    if param.nodeName in ['file', 'directory', 'image', 'transform']:
                        traitsParams["exists"] = True
                    self.inputs.add_trait(name, type(*values, **traitsParams))
                    undefined_traits[name] = Undefined
                
        self.inputs.trait_set(trait_change_notify=False, **undefined_traits)
        for name in undefined_traits.keys():
            value = getattr(self.inputs, name)
        #self._outputs().trait_set(trait_change_notify=False, **undefined_output_traits)

        
    def _gen_filename(self, name):
        if name in self._outputs_filenames:
            return os.path.join(os.getcwd(), self._outputs_filenames[name])
        return None
    
    def _gen_filename_from_param(self,param):
        base = param.getElementsByTagName('name')[0].firstChild.nodeValue
        fileExtensions = param.getAttribute("fileExtensions")
        if fileExtensions:
            ext = fileExtensions
        else:
            ext = {'image': '.nii', 'transform': '.txt', 'file': ''}[param.nodeName]
        return base + ext
    
    def _list_outputs(self):
        outputs = self.output_spec().get()
        for output_node in self._outputs_nodes:
            name = output_node.getElementsByTagName('name')[0].firstChild.nodeValue
            outputs[name] = getattr(self.inputs, name)
            if isdefined(outputs[name]) and isinstance(outputs[name], bool):
                if outputs[name]:
{'fraction_non_alphanumeric': 0.11583848438628884, 'fraction_numerical': 0.0031307698482780765, 'mean_word_length': 1.9839520958083832, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 10}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '745793', 'n_tokens_mistral': 3415, 'n_tokens_neox': 3268, 'n_words': 632}