Fits the CBV design matrix to the de-trended flux of a given target. This
    is called internally whenever the user accesses the :py:attr:`fcor`
    attribute.

    :param model: An instance of the :py:obj:`everest` model for the target
761617
def FitCBVs(model):
    '''
    

    '''

    # Get cbvs?
    if model.XCBV is None:
        GetTargetCBVs(model)

    # The number of CBVs to use
    ncbv = model.cbv_num

    # Need to treat short and long cadences differently
    if model.cadence == 'lc':

        # Loop over all the light curve segments
        m = [None for b in range(len(model.breakpoints))]
        weights = [None for b in range(len(model.breakpoints))]
        for b in range(len(model.breakpoints)):

            # Get the indices for this light curve segment
            inds = model.get_chunk(b, pad=False)
            masked_inds = model.get_masked_chunk(b, pad=False)

            # Regress
            mX = model.XCBV[masked_inds, :ncbv + 1]
            A = np.dot(mX.T, mX)
            B = np.dot(mX.T, model.flux[masked_inds])
            try:
                weights[b] = np.linalg.solve(A, B)
            except np.linalg.linalg.LinAlgError:
                # Singular matrix
                log.warn('Singular matrix!')
                weights[b] = np.zeros(mX.shape[1])

            m[b] = np.dot(model.XCBV[inds, :ncbv + 1], weights[b])

            # Vertical alignment
            if b == 0:
                m[b] -= np.nanmedian(m[b])
            else:
                # Match the first finite model point on either side of the
                # break
                # We could consider something more elaborate in the future
                i0 = -1 - np.argmax([np.isfinite(m[b - 1][-i])
                                     for i in range(1, len(m[b - 1]) - 1)])
                i1 = np.argmax([np.isfinite(m[b][i])
                                for i in range(len(m[b]))])
                m[b] += (m[b - 1][i0] - m[b][i1])

        # Join model and normalize
        m = np.concatenate(m)
        m -= np.nanmedian(m)

    else:

        # Interpolate over outliers so we don't have to worry
        # about masking the arrays below
        flux = Interpolate(model.time, model.mask, model.flux)

        # Get downbinned light curve
        newsize = len(model.time) // 30
        time = Downbin(model.time, newsize, operation='mean')
        flux = Downbin(flux, newsize, operation='mean')

        # Get LC breakpoints
        breakpoints = list(Breakpoints(
            model.ID, season=model.season, cadence='lc'))
        breakpoints += [len(time) - 1]

        # Loop over all the light curve segments
        m = [None for b in range(len(breakpoints))]
        weights = [None for b in range(len(breakpoints))]
        for b in range(len(breakpoints)):

            # Get the indices for this light curve segment
            M = np.arange(len(time))
            if b > 0:
                inds = M[(M > breakpoints[b - 1]) & (M <= breakpoints[b])]
            else:
                inds = M[M <= breakpoints[b]]

            # Regress
            A = np.dot(model.XCBV[inds, :ncbv + 1].T,
                       model.XCBV[inds, :ncbv + 1])
            B = np.dot(model.XCBV[inds, :ncbv + 1].T, flux[inds])
            weights[b] = np.linalg.solve(A, B)
            m[b] = np.dot(model.XCBV[inds, :ncbv + 1], weights[b])

            # Vertical alignment
            if b == 0:
                m[b] -= np.nanmedian(m[b])
            else:
                # Match the first finite model point on either side of the
                # break
                # We could consider something more elaborate in the future
                i0 = -1 - np.argmax([np.isfinite(m[b - 1][-i])
                                     for i in range(1, len(m[b - 1]) - 1)])
                i1 = np.argmax([np.isfinite(m[b][i])
                                for i in range(len(m[b]))])
                m[b] += (m[b - 1][i0] - m[b][i1])

        # Join model and normalize
        m = np.concatenate(m)
        m -= np.nanmedian(m)

        # Finally, interpolate back to short cadence
        m = np.interp(model.time, time, m)

    return m
790530
def setModel(self, model):
        
        super(StimulusView, self).setModel(model)
        self.setSelectionModel(ComponentSelectionModel(model))
        # initialize nested list to appropriate size
        self._rects = [[None] * self.model().columnCountForRow(x) for x in range(self.model().rowCount())]

        self._viewIsDirty = True
        self._calculateRects()
1313515
def plot_cbv(self, ax, flux, info, show_cbv=False):
        '''
        

        '''

        # Plot the light curve
        bnmask = np.array(
            list(set(np.concatenate([self.badmask, self.nanmask]))), dtype=int)

        def M(x): return np.delete(x, bnmask)
        if self.cadence == 'lc':
            ax.plot(M(self.time), M(flux), ls='none', marker='.',
                    color='k', markersize=2, alpha=0.45)
        else:
            ax.plot(M(self.time), M(flux), ls='none', marker='.',
                    color='k', markersize=2, alpha=0.03, zorder=-1)
            ax.set_rasterization_zorder(0)
        # Hack: Plot invisible first and last points to ensure
        # the x axis limits are the
        # same in the other plots, where we also plot outliers!
        ax.plot(self.time[0], np.nanmedian(M(flux)), marker='.', alpha=0)
        ax.plot(self.time[-1], np.nanmedian(M(flux)), marker='.', alpha=0)

        # Show CBV fit?
        if show_cbv:
            ax.plot(self.time, self._mission.FitCBVs(
                self) + np.nanmedian(flux), 'r-', alpha=0.2)

        # Appearance
        ax.annotate(info, xy=(0.98, 0.025), xycoords='axes fraction',
                    ha='right', va='bottom', fontsize=10, alpha=0.5,
                    fontweight='bold')
        ax.margins(0.01, 0.1)

        # Get y lims that bound 99% of the flux
        flux = np.delete(flux, bnmask)
        N = int(0.995 * len(flux))
        hi, lo = flux[np.argsort(flux)][[N, -N]]
        fsort = flux[np.argsort(flux)]
        pad = (hi - lo) * 0.2
        ylim = (lo - pad, hi + pad)
        ax.set_ylim(ylim)
        ax.get_yaxis().set_major_formatter(Formatter.Flux)
        ax.set_xlabel(r'Time (%s)' % self._mission.TIMEUNITS, fontsize=9)
        for tick in ax.get_xticklabels() + ax.get_yticklabels():
            tick.set_fontsize(7)
188936
def fitlin(imgarr,refarr):
    
    # Initialize variables
    _mat = np.zeros((3,3),dtype=np.float64)
    _xorg = imgarr[0][0]
    _yorg = imgarr[0][1]
    _xoorg = refarr[0][0]
    _yoorg = refarr[0][1]
    _sigxox = 0.
    _sigxoy = 0.
    _sigxo = 0.
    _sigyox = 0.
    _sigyoy = 0.
    _sigyo = 0.

    _npos = len(imgarr)
    # Populate matrices
    for i in range(_npos):
        _mat[0][0] += np.power((imgarr[i][0] - _xorg),2)
        _mat[0][1] += (imgarr[i][0] - _xorg) * (imgarr[i][1] - _yorg)
        _mat[0][2] += (imgarr[i][0] - _xorg)
        _mat[1][1] += np.power((imgarr[i][1] - _yorg),2)
        _mat[1][2] += imgarr[i][1] - _yorg

        _sigxox += (refarr[i][0] - _xoorg)*(imgarr[i][0] - _xorg)
        _sigxoy += (refarr[i][0] - _xoorg)*(imgarr[i][1] - _yorg)
        _sigxo += refarr[i][0] - _xoorg
        _sigyox += (refarr[i][1] - _yoorg)*(imgarr[i][0] -_xorg)
        _sigyoy += (refarr[i][1] - _yoorg)*(imgarr[i][1] - _yorg)
        _sigyo += refarr[i][1] - _yoorg

    _mat[2][2] = _npos
    _mat[1][0] = _mat[0][1]
    _mat[2][0] = _mat[0][2]
    _mat[2][1] = _mat[1][2]

    # Now invert this matrix
    _mat = linalg.inv(_mat)

    _a  = _sigxox*_mat[0][0]+_sigxoy*_mat[0][1]+_sigxo*_mat[0][2]
    _b  = -1*(_sigxox*_mat[1][0]+_sigxoy*_mat[1][1]+_sigxo*_mat[1][2])
    #_x0 = _sigxox*_mat[2][0]+_sigxoy*_mat[2][1]+_sigxo*_mat[2][2]

    _c  = _sigyox*_mat[1][0]+_sigyoy*_mat[1][1]+_sigyo*_mat[1][2]
    _d  = _sigyox*_mat[0][0]+_sigyoy*_mat[0][1]+_sigyo*_mat[0][2]
    #_y0 = _sigyox*_mat[2][0]+_sigyoy*_mat[2][1]+_sigyo*_mat[2][2]

    _xt = _xoorg - _a*_xorg+_b*_yorg
    _yt = _yoorg - _d*_xorg-_c*_yorg

    return [_a,_b,_xt],[_c,_d,_yt]
640085
def setModel(self, model):
        ""
        self._model = model
        self.ui.aofsSpnbx.setValue(model.samplerate())
854500
def reduced_chi2(self, model, error_map=0):
        
        chi2 = self.reduced_residuals(model, error_map)
        return np.sum(chi2**2) / self.num_data_evaluate()
208404
def setModel(self, model):
        """"""
        # disconnect old signals
        try:
            self.ui.parametizer.randomizeCkbx.toggled.disconnect()
            self.ui.parametizer.randomizeCkbx.disconnect()
        except TypeError:
            # disconnecting without any current connections throws error
            pass

        self.ui.trackview.setModel(model)
        self.ui.nrepsSpnbx.setValue(model.repCount())

        self.ui.parametizer.randomizeCkbx.toggled.connect(model.randomToggle)
        self.ui.parametizer.randomizeCkbx.setChecked(bool(model.reorder()))

        # extract the QAutoParameterModel from the QStimulusModel and 
        # set in the AutoParameterView
        autoParamModel = model.autoParams()
        self.ui.parametizer.setModel(autoParamModel)
        # whether the auto parameters are emtpy 
        # affects the enable-ness of the StimlusView
        autoParamModel.emptied.connect(self.ui.trackview.emptySelection)
        autoParamModel.countChanged.connect(self.updateTraceCount)
        self.updateTraceCount()
477675
def _generate_base_svm_classifier_spec(model):
    
    if not(_HAS_SKLEARN):
        raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.')

    check_fitted(model, lambda m: hasattr(m, 'support_vectors_'))

    spec = _Model_pb2.Model()
    spec.specificationVersion = SPECIFICATION_VERSION
    svm = spec.supportVectorClassifier

    _set_kernel(model, svm)

    for cur_rho in model.intercept_:
        if(len(model.classes_) == 2):
            # For some reason Scikit Learn doesn't negate for binary classification
            svm.rho.append(cur_rho)
        else:
            svm.rho.append(-cur_rho)

    for i in range(len(model._dual_coef_)):
        svm.coefficients.add()
        for cur_alpha in model._dual_coef_[i]:
            svm.coefficients[i].alpha.append(cur_alpha)

    for cur_src_vector in model.support_vectors_:
        cur_dest_vector = svm.denseSupportVectors.vectors.add()
        for i in cur_src_vector:
            cur_dest_vector.values.append(i)
    return spec
605560
def instance_ik_model_receiver(fn):
    
    @wraps(fn)
    def receiver(self, sender, **kwargs):
        # print 'inspect.isclass(sender? %s'%(inspect.isclass(sender))
        if not inspect.isclass(sender):
            return
        for src in self._source_groups:
            if issubclass(sender, src.model_class):
                fn(self, sender=sender, **kwargs)

                # If we find a match, return. We don't want to handle the signal
                # more than once.
                return
    return receiver
508740
public synchronized void replaceModel (MaxentModel model) {
	replacementThread = Thread.currentThread();
	while (!replacementCanProceed) Thread.yield();
	setter.setModel(model);
	replacementThread = null;
    }
864602
def _get_model_fitting(self, mf_id):
        
        for model_fitting in self.model_fittings:
            if model_fitting.activity.id == mf_id:
                return model_fitting

        raise Exception("Model fitting activity with id: " + str(mf_id) +
                        " not found.")
825903
def follow_model(self, model):
        
        if model:
          self.models_by_name[model.__name__.lower()] = model
          signals.post_save.connect(create_or_update, sender=model)
          signals.post_delete.connect(self.remove_orphans, sender=model)
812034
def transform(self, X):
        
        assert np.shape(X)[0] == len(self._weights), (
            'BlendingOptimizer: Number of models to blend its predictions and weights does not match: '
            'n_models={}, weights_len={}'.format(np.shape(X)[0], len(self._weights)))
        blended_predictions = np.average(np.power(X, self._power),
                                         weights=self._weights,
                                         axis=0) ** (1.0 / self._power)

        return {'y_pred': blended_predictions}
600867
def setModel(self, model):
        

        if not model:
            return

        LOGGER.debug("> Setting '{0}' model.".format(model))

        umbra.ui.views.Abstract_QTreeView.setModel(self, model)

        # Signals / Slots.
        self.model().modelAboutToBeReset.connect(self.__model__modelAboutToBeReset)
        self.model().modelReset.connect(self.__model__modelReset)
1271738
private void linkMembersToShapes(IntermediateModel model) {
        for (Map.Entry<String, ShapeModel> entry : model.getShapes().entrySet()) {
            if (entry.getValue().getMembers() != null) {
                for (MemberModel member : entry.getValue().getMembers()) {
                    member.setShape(
                            Utils.findShapeModelByC2jNameIfExists(model, member.getC2jShape()));
                }
            }
        }
    }
1290761
public void setModel( BundleAdjustmentCamera model ) {
		this.model = model;
		numIntrinsic = model.getIntrinsicCount();
		if( numIntrinsic > intrinsic.length ) {
			intrinsic = new double[numIntrinsic];
		}
		model.getIntrinsic(intrinsic,0);

		numericalPoint = createNumericalAlgorithm(funcPoint);
		numericalIntrinsic = createNumericalAlgorithm(funcIntrinsic);
	}
1078578
def _generate_base_svm_regression_spec(model):
    
    if not(_HAS_SKLEARN):
        raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.')

    spec = _Model_pb2.Model()
    spec.specificationVersion = SPECIFICATION_VERSION
    svm = spec.supportVectorRegressor

    _set_kernel(model, svm)

    svm.rho = -model.intercept_[0]
    for i in range(len(model._dual_coef_)):
        for cur_alpha in model._dual_coef_[i]:
            svm.coefficients.alpha.append(cur_alpha)

    for cur_src_vector in model.support_vectors_:
        cur_dest_vector = svm.denseSupportVectors.vectors.add()
        for i in cur_src_vector:
            cur_dest_vector.values.append(i)
    return spec