<commit_before># emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
import os
from copy import deepcopy

import numpy as np

from nipype.utils.filemanip import (filename_to_list, list_to_filename)
from nipype.interfaces.base import (traits, TraitedSpec, DynamicTraitedSpec, File,
                                    Undefined, isdefined, OutputMultiPath,
    InputMultiPath)
from nipype.interfaces.io import IOBase, add_traits

    
class IdentityInterface(IOBase):
    """Basic interface class generates identity mappings

    Examples
    --------
    
    >>> from nipype.interfaces.utility import IdentityInterface
    >>> ii = IdentityInterface(fields=['a','b'])
    >>> ii.inputs.a
    <undefined>

    >>> ii.inputs.a = 'foo'
    >>> out = ii._outputs()
    >>> out.a
    <undefined>

    >>> out = ii.run()
    >>> out.outputs.a
    'foo'
    
    """
    input_spec = DynamicTraitedSpec
    output_spec = DynamicTraitedSpec
    
    def __init__(self, fields=None, **inputs):
        super(IdentityInterface, self).__init__(**inputs)
        if fields is None or not fields:
            raise Exception('Identity Interface fields must be a non-empty list')
        self._fields = fields
        add_traits(self.inputs, fields)

    def _add_output_traits(self, base):
        undefined_traits = {}
        for key in self._fields:
            base.add_trait(key, traits.Any)
            undefined_traits[key] = Undefined
        base.trait_set(trait_change_notify=False, **undefined_traits)
        return base

    def _list_outputs(self):
        outputs = self._outputs().get()
        for key in self._fields:
            val = getattr(self.inputs, key)
            if isdefined(val):
                outputs[key] = val
        return outputs

class MergeInputSpec(DynamicTraitedSpec):
    axis = traits.Enum('vstack', 'hstack', usedefault=True,
                desc='direction in which to merge, hstack requires same number of elements in each input')
class MergeOutputSpec(TraitedSpec):
    out = traits.List(desc='Merged output')

class Merge(IOBase):
    """Basic interface class to merge inputs into a single list

    Examples
    --------
    
    >>> from nipype.interfaces.utility import Merge
    >>> mi = Merge(3)
    >>> mi.inputs.in1 = 1
    >>> mi.inputs.in2 = [2,5]
    >>> mi.inputs.in3 = 3
    >>> out = mi.run()
    >>> out.outputs.out
    [1, 2, 5, 3]
    
    """
    input_spec = MergeInputSpec
    output_spec = MergeOutputSpec
    
    def __init__(self, numinputs=0, **inputs):
        super(Merge, self).__init__(**inputs)
        self.numinputs = numinputs
        add_traits(self.inputs, ['in%d'%(i+1) for i in range(numinputs)])
        
    def _list_outputs(self):
        outputs = self._outputs().get()
        out = []
        if self.inputs.axis == 'vstack':
            for idx in range(self.numinputs):
                value = getattr(self.inputs, 'in%d'%(idx+1))
                if isdefined(value):
                    if isinstance(value, list):
                        out.extend(value)
                    else:
                        out.append(value)
        else:
            for i in range(len(filename_to_list(self.inputs.in1))):
                out.insert(i,[])
                for j in range(self.numinputs):
                    out[i].append(filename_to_list(getattr(self.inputs, 'in%d'%(j+1)))[i])
        if out:
            outputs['out'] = out
        return outputs

class RenameInputSpec(DynamicTraitedSpec):

    in_file = File(exists=True, desc="file to rename")
    format_string = traits.String(desc="python string formatting style string to rename a file")

class RenameOutputSpec(TraitedSpec):

    out_file = traits.File(exists=True,desc="softlink to original file with new name")

class Rename(IOBase):

    input_spec = RenameInputSpec
    output_spec = RenameOutputSpec

    def __init__(self, numinputs=0, **inputs):
        super(Rename, self).__init__(**inputs)
        self.numinputs = numinputs
        add_traits(self.inputs, ['in%d'%(i+1) for i in range(numinputs)])

    def _rename(self):
        fmt_list = []
        for idx in range(self.numinputs):
            value = getattr(self.inputs, 'in%d'%(idx+1))
            if isdefined(value):
                fmt_list.append(value) 
        new_name = self.inputs.format_string%tuple(fmt_list)
        return new_name

    def _run_interface(self, runtime):
        runtime.returncode = 0
        os.symlink(self.inputs.in_file, os.path.join(os.getcwd(), self._rename()))
        return runtime
    
    def _list_outputs(self):
        outputs = self._outputs().get()
        outputs["out_file"] = os.path.join(os.getcwd(), self._rename())
        return outputs

class SplitInputSpec(TraitedSpec):
    inlist = traits.List(traits.Any, mandatory=True,
                  desc='list of values to split')
    splits = traits.List(traits.Int, mandatory=True,
                  desc='Number of outputs in each split - should add to number of inputs')

class Split(IOBase):<commit_msg>Changed string formatting to mapped fields<commit_after># emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
import os
import re
import numpy as np

from nipype.utils.filemanip import (filename_to_list, list_to_filename, copyfile)
from nipype.interfaces.base import (traits, TraitedSpec, DynamicTraitedSpec, File,
                                    Undefined, isdefined, OutputMultiPath,
    InputMultiPath)
from nipype.interfaces.io import IOBase, add_traits

    
class IdentityInterface(IOBase):
    """Basic interface class generates identity mappings

    Examples
    --------
    
    >>> from nipype.interfaces.utility import IdentityInterface
    >>> ii = IdentityInterface(fields=['a','b'])
    >>> ii.inputs.a
    <undefined>

    >>> ii.inputs.a = 'foo'
    >>> out = ii._outputs()
    >>> out.a
    <undefined>

    >>> out = ii.run()
    >>> out.outputs.a
    'foo'
    
    """
    input_spec = DynamicTraitedSpec
    output_spec = DynamicTraitedSpec
    
    def __init__(self, fields=None, **inputs):
        super(IdentityInterface, self).__init__(**inputs)
        if fields is None or not fields:
            raise Exception('Identity Interface fields must be a non-empty list')
        self._fields = fields
        add_traits(self.inputs, fields)

    def _add_output_traits(self, base):
        undefined_traits = {}
        for key in self._fields:
            base.add_trait(key, traits.Any)
            undefined_traits[key] = Undefined
        base.trait_set(trait_change_notify=False, **undefined_traits)
        return base

    def _list_outputs(self):
        outputs = self._outputs().get()
        for key in self._fields:
            val = getattr(self.inputs, key)
            if isdefined(val):
                outputs[key] = val
        return outputs

class MergeInputSpec(DynamicTraitedSpec):
    axis = traits.Enum('vstack', 'hstack', usedefault=True,
                desc='direction in which to merge, hstack requires same number of elements in each input')
class MergeOutputSpec(TraitedSpec):
    out = traits.List(desc='Merged output')

class Merge(IOBase):
    """Basic interface class to merge inputs into a single list

    Examples
    --------
    
    >>> from nipype.interfaces.utility import Merge
    >>> mi = Merge(3)
    >>> mi.inputs.in1 = 1
    >>> mi.inputs.in2 = [2,5]
    >>> mi.inputs.in3 = 3
    >>> out = mi.run()
    >>> out.outputs.out
    [1, 2, 5, 3]
    
    """
    input_spec = MergeInputSpec
    output_spec = MergeOutputSpec
    
    def __init__(self, numinputs=0, **inputs):
        super(Merge, self).__init__(**inputs)
        self.numinputs = numinputs
        add_traits(self.inputs, ['in%d'%(i+1) for i in range(numinputs)])
        
    def _list_outputs(self):
        outputs = self._outputs().get()
        out = []
        if self.inputs.axis == 'vstack':
            for idx in range(self.numinputs):
                value = getattr(self.inputs, 'in%d'%(idx+1))
                if isdefined(value):
                    if isinstance(value, list):
                        out.extend(value)
                    else:
                        out.append(value)
        else:
            for i in range(len(filename_to_list(self.inputs.in1))):
                out.insert(i,[])
                for j in range(self.numinputs):
                    out[i].append(filename_to_list(getattr(self.inputs, 'in%d'%(j+1)))[i])
        if out:
            outputs['out'] = out
        return outputs

class RenameInputSpec(DynamicTraitedSpec):

    in_file = File(exists=True, mandatory=True, desc="file to rename")
    format_string = traits.String(desc="Python formatting string for output template")

class RenameOutputSpec(TraitedSpec):

    out_file = traits.File(exists=True,desc="softlink to original file with new name")

class Rename(IOBase):
    """Change the name of a file based on a mapped format string.

    The class constructor must be called with the format template, and the
    fields identified will become inputs to the interface.

    Examples
    --------
    >>> from nipype.interfaces.utility import Rename
    >>> rename = Rename(format_string="%(subject_id)s_func_run%(run)02d.nii")

    >>> rename.inputs.in_file "func.nii"
    >>> rename.inputs.subject_id = "subj_201"
    >>> rename.inputs.run = 2
    >>> res = rename.run()          # doctest: +SKIP
    >>> print res.outputs.out_file  # doctest: +SKIP
    'subj_201_func_run02.nii'       # doctest: +SKIP

    """
    input_spec = RenameInputSpec
    output_spec = RenameOutputSpec

    def __init__(self, format_string, **inputs):
        super(Rename, self).__init__(**inputs)
        self.inputs.format_string = format_string
        self.fmt_fields = re.findall(r"%\((.+?)\)", format_string)
        add_traits(self.inputs, self.fmt_fields)

    def _rename(self):
        fmt_dict = dict()
        for field in self.fmt_fields:
            fmt_dict[field] = getattr(self.inputs, field)
        return self.inputs.format_string%fmt_dict

    def _run_interface(self, runtime):
        runtime.returncode = 0
        _ = copyfile(self.inputs.in_file, os.path.join(os.getcwd(), self._rename()))
        return runtime
    
    def _list_outputs(self):
        outputs = self._outputs().get()
        outputs["out_file"] = os.path.join(os.getcwd(), self._rename())
        return outputs

class SplitInputSpec(TraitedSpec):
    inlist = traits.List(traits.Any, mandatory=True,
                  desc='list of values to split')
    splits = traits.List(traits.Int, mandatory=True,
                  desc='Number of outputs in each split - should add to number of inputs')

class Split(IOBase):
{'fraction_non_alphanumeric': 0.11989985163204747, 'fraction_numerical': 0.005378338278931751, 'mean_word_length': 2.455623197693047, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 118, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4094368', 'n_tokens_mistral': 3323, 'n_tokens_neox': 3194, 'n_words': 776}