Example #1
0
def compute_contrasts(contrast_struct, misc, CompletePaths, glms=None,
                     model="default", **kargs):
    """
    Contrast computation utility    
    
    Parameters
    ----------
    contrast_struct, ConfigObj instance or string
               it yields the set of contrasts of the multi-session model
               or the path to a configobj that specifies the contarsts
    misc: misc object instance,
              misc information on the datasets used here
              or path to a configobj file that yields the misc info
    Complete_Paths: dictionary or string,
                    yields all paths, indexed by contrasts,
                    where outputs will be written
                    if it is a string, all the paths are re-generated 
                    based on it as a output directory
    glms, dictionary of nipy.neurospin.glm.glm.glm instances
         indexed by sessions, optional
         if it is not provided, a 'glm_config' instance should be provided
         in kargs
    """
    
    # read the msic info
    if isinstance(misc, basestring):
        misc = ConfigObj(misc)
    if not misc.has_key(model):
        misc[model] = {}
    if not misc[model].has_key("con_dofs"):
        misc[model]["con_dofs"] = {}
    sessions = misc['sessions']
    
    # get the contrasts
    if isinstance(misc, basestring):
        contrast_struct = ConfigObj(contrast_struct) 
    contrasts_names = contrast_struct["contrast"]

    # get the glms
    designs = {}
    if glms is not None:
       designs = glms
    else:             
        if not kargs.has_key('glms_config'):
            raise ValueError, "No glms provided"
        else:
            import nipy.neurospin.glm as GLM
            for s in sessions:
                designs[s] = GLM.load(kargs['glm_config'][s]["GlmDumpFile"])

    # set the output paths
    if isinstance(CompletePaths, basestring) :
        CompletePaths = generate_brainvisa_ouput_paths(CompletePaths, 
                        contrast_struct)
    # compute the contrasts
    for i, contrast in enumerate(contrasts_names):
        contrast_type = contrast_struct[contrast]["Type"]
        contrast_dimension = contrast_struct[contrast]["Dimension"]
        final_contrast = []
        k = i+1
        multicon = dict()

        for key, value in contrast_struct[contrast].items():
            if key != "Type" and key != "Dimension":
                session = "_".join(key.split("_")[:-1])
                bv = [int(j) != 0 for j in value]
                if contrast_type == "t" and sum(bv)>0:
                    _con = designs[session].contrast([int(i) for i in value])
                    final_contrast.append(_con)

                if contrast_type == "F":
                    if not multicon.has_key(session):
                        multicon[session] = np.array(bv)
                    else:
                        multicon[session] = np.vstack((multicon[session], bv))
        if contrast_type == "F":
            for key, value in multicon.items():
                if sum([j != 0 for j in value.reshape(-1)]) != 0:
                    _con = designs[key].contrast(value)
                    final_contrast.append(_con)

        design = designs[session]
        res_contrast = final_contrast[0]
        for c in final_contrast[1:]:
            res_contrast = res_contrast + c
            res_contrast.type = contrast_type
            
        # write misc information
        cpp = CompletePaths[contrast]
        save_all_textures(res_contrast, contrast_dimension, cpp)
        misc[model]["con_dofs"][contrast] = res_contrast.dof
    
    misc.write()
Example #2
0
def ComputeContrasts(contrastFile, miscFile, glms, save_mode="Contrast Name", 
                                   model="default", verbose=0, **kargs):
    """
    Contrast computation utility    
    
    Parameters
    ----------
    contrastFile, string, path of the configobj contrast file
    miscFile, string, path of the configobj miscinfo file
    glms, dictionary indexed by sessions that yields paths to
          nipy.neurospin.glm.glm instances 
          representing the glms of the individual sessions 
          in particular , it should have the key "GlmDumpFile".
    save_mode="Contrast Name", string to be chosen
                        among "Contrast Name" or "Contrast Number"
    model="default", string,
                     name of the contrast model used in miscfile
    """
    import nipy.neurospin.glm as GLM
    misc = ConfigObj(miscFile)
    if not misc.has_key(model):
        misc[model] = {}

    if not misc[model].has_key("con_dofs"):
        misc[model]["con_dofs"] = {}

    contrasts = ConfigObj(contrastFile)
    contrasts_names = contrasts["contrast"]
    designs = {}
    for i, contrast in enumerate(contrasts_names):
        contrast_type = contrasts[contrast]["Type"]
        contrast_dimension = contrasts[contrast]["Dimension"]
        final_contrast = []
        k = i+1
        multicon = dict()
        if save_mode == "Contrast Name":
            ContrastId = contrast
        elif save_mode == "Contrast Number":
            ContrastId = "%04i" % k
        else:
            raise ValueError, "unknown save mode"

        for key, value in contrasts[contrast].items():
            if verbose: print key,value
            if key != "Type" and key != "Dimension":
                session = "_".join(key.split("_")[:-1])
                if not designs.has_key(session):
                    print "Loading session : %s" % session
                designs[session] = GLM.load(glms[session]["GlmDumpFile"])

                bv=[int(j) != 0 for j in value]
                if contrast_type == "t" and sum(bv)>0:
                    _con = designs[session].contrast([int(i) for i in value])
                    final_contrast.append(_con)

                if contrast_type == "F":
                    if not multicon.has_key(session):
                        multicon[session] = np.array(bv)
                    else:
                        multicon[session] = np.vstack((multicon[session], bv))
        if contrast_type == "F":
            for key, value in multicon.items():
                if sum([j != 0 for j in value.reshape(-1)]) != 0:
                    _con = designs[key].contrast(value)
                    final_contrast.append(_con)

        design = designs[session]
        res_contrast = final_contrast[0]
        for c in final_contrast[1:]:
            res_contrast = res_contrast + c
            res_contrast.type = contrast_type

        if contrasts.has_key('mask_url'):
            mask_url = contrasts['mask_url']
        elif misc.has_key('mask_url'):
            mask_url = misc['mask_url']
        else:
            mask_url = None

        if kargs.has_key('CompletePaths'):
            cpp = kargs['CompletePaths']
            print cpp, contrast
            save_all_images(res_contrast, contrast_dimension, mask_url, cpp[contrast])
        else:
            save_all(res_contrast, ContrastId, contrast_dimension, mask_url, kargs)
        misc[model]["con_dofs"][contrast] = res_contrast.dof
    misc["Contrast Save Mode"] = save_mode
    misc.write()