Example #1
0
    def dumpCorrelationToMatlab(self, correlation, fileName, **analysisOptions):
        results = self._performAnalysis(correlation, **analysisOptions)
        results = self._organizeByGroup(results)

        from mlabwrap import mlab

        groups = []
        for group, correlations in results.iteritems():

            wrapped = []
            for i, data in enumerate(correlations):
                info = _infoToMatlab(data.info, mlab)
                points = np.array(data.points)
                wrapped.append(mlab.struct("info", info, 
                                           "points", points, 
                                           "name", str(data.name)))

            groups.append(mlab.struct("group", group, 
                                      "correlations", _toStructArray(wrapped)))

        mlab._set(correlation, _toStructArray(groups))
        mlab.save(fileName, correlation)
Example #2
0
def cobra_model_object_to_cobra_matlab_struct(cobra_model):
    """This function converts all of the  object values to the
    corresponding model fields to update the mlab model.

    """
    try:
        from mlabwrap import mlab as matlab
    except:
        raise Exception('mlabwrap and MATLAB are required to use these functions. '+\
                        'They only function on Mac OS X and GNU/Linux')
    from cobra.mlab import python_list_to_matlab_cell, scipy_sparse_to_mlab_sparse
    if hasattr(cobra_model, 'to_array_based_model'):
        cobra_model = cobra_model.to_array_based_model()
    else:
        cobra_model.update()
    matlab_struct = matlab.struct()
    #Things that need a conversion:  S, rxnGeneMat,
    matlab_struct.mets = python_list_to_matlab_cell([x.id for x in cobra_model.metabolites],
                                                    transpose = True)
    matlab_struct.metNames =  python_list_to_matlab_cell([x.name for x in cobra_model.metabolites],
                                                         transpose = True)
    matlab_struct.metFormulas = python_list_to_matlab_cell([x.formula
                                                            for x in cobra_model.metabolites],
                                                           transpose = True)
    matlab_struct.genes = python_list_to_matlab_cell(cobra_model.genes, transpose = True)
    matlab_struct.grRules = python_list_to_matlab_cell([x.gene_reaction_rule
                                                        for x in cobra_model.reactions],
                                                       transpose = True)
    matlab_struct.rxns = python_list_to_matlab_cell([x.id for x in cobra_model.reactions],
                                                    transpose = True)
    matlab_struct.rxnNames = python_list_to_matlab_cell([x.name
                                                         for x in cobra_model.reactions],
                                                        transpose = True)
    matlab_struct.subSystems = python_list_to_matlab_cell([x.subsystem
                                                           for x in cobra_model.reactions],
                                                           transpose=True)

    if hasattr(cobra_model, 'constraint_sense'):
        matlab_struct.csense = reduce(lambda x,y: x+y, cobra_model.constraint_sense)
    #matlab_struct.csense = python_list_to_matlab_cell(['E']*len(cobra_model.metabolites), transpose = True)
    #TODO: inefficient conversion but who cares? matlab's on its way out
    matlab_struct.S = scipy_sparse_to_mlab_sparse(cobra_model.S)
    #Things that can be directly copied
    matlab_struct.b = cobra_model.b
    matlab_struct.c = cobra_model.objective_coefficients
    matlab_struct.lb = cobra_model.lower_bounds
    matlab_struct.ub = cobra_model.upper_bounds
    matlab_struct.rev = [x.reversibility for x in cobra_model.reactions]
    matlab_struct.description = cobra_model.description
    return(matlab_struct)
Example #3
0
def trackBacteria(images, debug=False):
    from mlabwrap import mlab
    
    masks = computeForegroundMasks(images)
    
    #simpleImages = SimpleImageSeq(images)
    #blobs = findBlobs(simpleImages, SimpleImageSeq(masks))
    #if debug:
    #    debugBlobs(simpleImages, blobs)
    #ellipses = findEllipses(blobs)
    
    ellipses = findEllipses(masks)
    
    params = mlab.struct("mem", 1, "dim", 2, "good", 2, "quiet", 0)
    matrix = ellipses.selectColumns("x", "y", "angle", "area", "time")
    maxDist = 5
    while maxDist > 0.5:
        try:
            tracks = TracksMatrix(mlab.track(matrix, maxDist, params))
            break
        except:
            maxDist /= 2.0
    
    timeUnits = images.info.dt
    lengthUnits = images.info.pixel
    velocities = [VelocityMatrix(t*timeUnits) for t in range(1, len(images))]
    
    oldId = tracks[0, "id"]
    oldPosition = tracks[0, ("x", "y")]*lengthUnits
    oldTime = 0
    
    for row in range(1, tracks.shape[0]):
        position = tracks[row, ("x", "y")]*lengthUnits
        time = tracks[row, "time"]
        angle = tracks[row, "angle"]
        id_ = tracks[row, "id"]
        
        if oldId != id_:
            oldId = id_
        else:
            dt = (time - oldTime)*timeUnits
            velocity = (position - oldPosition)/dt
            combined = position.tolist() + velocity.tolist()
            velocities[int(time) - 1].append(*(combined + [angle]))
        
        oldPosition = position  
        oldTime = time
    
    for matrix in velocities: matrix.compact()
    return PathData(images.info, velocities)
Example #4
0
    def fit(self, X, y):
        """
        Fits the IVM

        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)
            Set of samples, where n_samples is the number of samples and
            n_features is the number of features.

        Returns
        -------
        self : object
            Returns self
        """

        self.classes_, y = np.unique(y, return_inverse=True)
        y = y + 1 #convert to matlab style indexing

        if self.CV is None:
            param_struct = mlab.struct('sigma', self.sigma, 'lambda', self._lambda, 'Nadd', self.Nadd, 'output', self.output, 
                'maxIter', self.maxIter, 'epsilon', self.epsilon, 'delta_k', self.delta_k, 'tempInt', self.tempInt,
                'epsilon_back', self.epsilon_back, 'flyComputeK', self.flyComputeK, 'deselect', self.deselect)

            self.model = mlab.ivm_learn(X.T, y, param_struct)
        else:
            param_struct = mlab.struct('sigmas', np.array(self.sigmas).reshape((1,-1)), 'lambdas', np.array(self.lambdas).reshape((1,-1)), 'CV', self.CV, 'Nadd', self.Nadd, 'output', self.output, 
            'maxIter', self.maxIter, 'epsilon', self.epsilon, 'delta_k', self.delta_k, 'tempInt', self.tempInt,
            'epsilon_back', self.epsilon_back, 'flyComputeK', self.flyComputeK, 'deselect', self.deselect)

            data_struct = mlab.struct('phi', X.T, 'c', y, 'phit', X.T, 'ct', y)

            result = mlab.ivm(data_struct, param_struct)
            self.model = result.model

        return self
Example #5
0
    def dumpCorrelationToMatlab(self, correlation, fileName,
                                **analysisOptions):
        results = self._performAnalysis(correlation, **analysisOptions)
        results = self._organizeByGroup(results)

        from mlabwrap import mlab

        groups = []
        for group, correlations in results.iteritems():

            wrapped = []
            for i, data in enumerate(correlations):
                info = _infoToMatlab(data.info, mlab)
                points = np.array(data.points)
                wrapped.append(
                    mlab.struct("info", info, "points", points, "name",
                                str(data.name)))

            groups.append(
                mlab.struct("group", group, "correlations",
                            _toStructArray(wrapped)))

        mlab._set(correlation, _toStructArray(groups))
        mlab.save(fileName, correlation)
Example #6
0
    def dumpPathsToMatlab(self, fileName, **trackOptions):
        self.track(**trackOptions)

        from mlabwrap import mlab

        allPaths = []
        for info in self.infos:
            try:
                paths = self._loadPaths(info)
            except:
                continue

            print info.uniqueName

            frames = _makeCells([v.array for v in paths.velocities], mlab)
            allPaths.append(mlab.struct("info", _infoToMatlab(paths.info, mlab),
                                        "frames", _wrapCellValue(frames)))
        
        mlab._set("paths", _toStructArray(allPaths))
        mlab.save(fileName, "paths")
Example #7
0
    def dumpPathsToMatlab(self, fileName, **trackOptions):
        self.track(**trackOptions)

        from mlabwrap import mlab

        allPaths = []
        for info in self.infos:
            try:
                paths = self._loadPaths(info)
            except:
                continue

            print info.uniqueName

            frames = _makeCells([v.array for v in paths.velocities], mlab)
            allPaths.append(
                mlab.struct("info", _infoToMatlab(paths.info, mlab), "frames",
                            _wrapCellValue(frames)))

        mlab._set("paths", _toStructArray(allPaths))
        mlab.save(fileName, "paths")