<commit_before>'''
NeuroLearn Utilities
====================

handy utilities.

'''
__all__ = ['get_resource_path',
           'get_anatomical',
           'set_algorithm',
           'attempt_to_import',
           'all_same',
           'concatenate',
           '_bootstrap_apply_func',
           'set_decomposition_algorithm'
           ]
__author__ = ["<NAME>"]
__license__ = "MIT"

from os.path import dirname, join, sep as pathsep
import nibabel as nib
import importlib
import os
from sklearn.pipeline import Pipeline
from sklearn.utils import check_random_state
from scipy.spatial.distance import squareform
import numpy as np
import pandas as pd
import collections
from types import GeneratorType

   
def _df_meta_to_arr(df):
    """Check what kind of data exists in pandas columns or index. If string return as numpy array 'S' type, otherwise regular numpy array. Used when saving Brain_Data objects to hdf5.
    """
    
    if len(df.columns):
        if isinstance(df.columns[0], str):
            columns = df.columns.values.astype("S")
        else:
            columns = df.columns.values
    else:
        columns = []
    
    if len(df.index):
        if isinstance(df.index[0], str):
            index = df.index.values.astype("S")
        else:
            index = df.index.values
    else:
        index = []

    return columns, index


def get_resource_path():
    """ Get path to nltools resource directory. """
    return join(dirname(__file__), 'resources') + pathsep


def get_anatomical():
    """ Get nltools default anatomical image.
        DEPRECATED. See MNI_Template and resolve_mni_path from nltools.prefs
    """
    return nib.load(os.path.join(get_resource_path(), 'MNI152_T1_2mm.nii.gz'))


def get_mni_from_img_resolution(brain, img_type='plot'):
    """
    Get the path to the resolution MNI anatomical image that matches the resolution of a Brain_Data instance. Used by Brain_Data.plot() and .iplot() to set backgrounds appropriately.
    
    Args:
        brain: Brain_Data instance
    
    Returns:
        file_path: path to MNI image
    """
    
    if img_type not in ['plot', 'brain']:
        raise ValueError("img_type must be 'plot' or 'brain' ")
    
    res_array = np.diag(brain.nifti_masker.affine_)[:3]
    voxel_dims = np.unique(res_array)
    if len(voxel_dims) != 1:
        raise ValueError("Voxels are not isometric and cannot be visualized in standard space")
    else:
        dim = str(int(voxel_dims[0])) + 'mm'
        if img_type == 'brain':
            mni = f'MNI152_T1_{dim}_brain.nii.gz'
        else:
            mni = f'MNI152_T1_{dim}.nii.gz'
        return os.path.join(get_resource_path(), mni)


def set_algorithm(algorithm, *args, **kwargs):
    """ Setup the algorithm to use in subsequent prediction analyses.

    Args:
        algorithm: The prediction algorithm to use. Either a string or an
                    (uninitialized) scikit-learn prediction object. If string,
                    must be one of 'svm','svr', linear','logistic','lasso',
                    'lassopcr','lassoCV','ridge','ridgeCV','ridgeClassifier',
                    'randomforest', or 'randomforestClassifier'<commit_msg>Quick fix for plotting isometric voxels where the affine involves a rotation.<commit_after>'''
NeuroLearn Utilities
====================

handy utilities.

'''
__all__ = ['get_resource_path',
           'get_anatomical',
           'set_algorithm',
           'attempt_to_import',
           'all_same',
           'concatenate',
           '_bootstrap_apply_func',
           'set_decomposition_algorithm'
           ]
__author__ = ["<NAME>"]
__license__ = "MIT"

from os.path import dirname, join, sep as pathsep
import nibabel as nib
import importlib
import os
from sklearn.pipeline import Pipeline
from sklearn.utils import check_random_state
from scipy.spatial.distance import squareform
import numpy as np
import pandas as pd
import collections
from types import GeneratorType

   
def _df_meta_to_arr(df):
    """Check what kind of data exists in pandas columns or index. If string return as numpy array 'S' type, otherwise regular numpy array. Used when saving Brain_Data objects to hdf5.
    """
    
    if len(df.columns):
        if isinstance(df.columns[0], str):
            columns = df.columns.values.astype("S")
        else:
            columns = df.columns.values
    else:
        columns = []
    
    if len(df.index):
        if isinstance(df.index[0], str):
            index = df.index.values.astype("S")
        else:
            index = df.index.values
    else:
        index = []

    return columns, index


def get_resource_path():
    """ Get path to nltools resource directory. """
    return join(dirname(__file__), 'resources') + pathsep


def get_anatomical():
    """ Get nltools default anatomical image.
        DEPRECATED. See MNI_Template and resolve_mni_path from nltools.prefs
    """
    return nib.load(os.path.join(get_resource_path(), 'MNI152_T1_2mm.nii.gz'))


def get_mni_from_img_resolution(brain, img_type='plot'):
    """
    Get the path to the resolution MNI anatomical image that matches the resolution of a Brain_Data instance. Used by Brain_Data.plot() and .iplot() to set backgrounds appropriately.
    
    Args:
        brain: Brain_Data instance
    
    Returns:
        file_path: path to MNI image
    """
    
    if img_type not in ['plot', 'brain']:
        raise ValueError("img_type must be 'plot' or 'brain' ")
    
    res_array = np.abs(np.diag(brain.nifti_masker.affine_)[:3])
    voxel_dims = np.unique(res_array)
    if len(voxel_dims) != 1:
        raise ValueError("Voxels are not isometric and cannot be visualized in standard space")
    else:
        dim = str(int(voxel_dims[0])) + 'mm'
        if img_type == 'brain':
            mni = f'MNI152_T1_{dim}_brain.nii.gz'
        else:
            mni = f'MNI152_T1_{dim}.nii.gz'
        return os.path.join(get_resource_path(), mni)


def set_algorithm(algorithm, *args, **kwargs):
    """ Setup the algorithm to use in subsequent prediction analyses.

    Args:
        algorithm: The prediction algorithm to use. Either a string or an
                    (uninitialized) scikit-learn prediction object. If string,
                    must be one of 'svm','svr', linear','logistic','lasso',
                    'lassopcr','lassoCV','ridge','ridgeCV','ridgeClassifier',
                    'randomforest', or 'randomforestClassifier'
{'fraction_non_alphanumeric': 0.10663360198388097, 'fraction_numerical': 0.005889646621202728, 'mean_word_length': 2.6874285714285713, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, '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': '716684', 'n_tokens_mistral': 1999, 'n_tokens_neox': 1915, 'n_words': 562}