Fit an ePSF model to a single star.

        The input ``epsf`` will usually be modified by the fitting
        routine in this function.  Make a copy before calling this
        function if the original is needed.
489056
def _fit_star(self, epsf, star, fitter, fitter_kwargs,
                  fitter_has_fit_info, fit_boxsize):
        

        if fit_boxsize is not None:
            try:
                xcenter, ycenter = star.cutout_center
                large_slc, small_slc = overlap_slices(star.shape,
                                                      fit_boxsize,
                                                      (ycenter, xcenter),
                                                      mode='strict')
            except (PartialOverlapError, NoOverlapError):
                warnings.warn('The star at ({0}, {1}) cannot be fit because '
                              'its fitting region extends beyond the star '
                              'cutout image.'.format(star.center[0],
                                                     star.center[1]),
                              AstropyUserWarning)

                star = copy.deepcopy(star)
                star._fit_error_status = 1

                return star

            data = star.data[large_slc]
            weights = star.weights[large_slc]

            # define the origin of the fitting region
            x0 = large_slc[1].start
            y0 = large_slc[0].start
        else:
            # use the entire cutout image
            data = star.data
            weights = star.weights

            # define the origin of the fitting region
            x0 = 0
            y0 = 0

        scaled_data = data / np.prod(epsf._oversampling)

        # define positions in the ePSF oversampled grid
        yy, xx = np.indices(data.shape, dtype=np.float)
        xx = (xx - (star.cutout_center[0] - x0)) * epsf._oversampling[0]
        yy = (yy - (star.cutout_center[1] - y0)) * epsf._oversampling[1]

        # define the initial guesses for fitted flux and shifts
        epsf.flux = star.flux
        epsf.x_0 = 0.0
        epsf.y_0 = 0.0

        # create copy to avoid overwriting original oversampling factor
        _epsf = epsf.copy()
        _epsf._oversampling = np.array([1., 1.])

        try:
            fitted_epsf = fitter(model=_epsf, x=xx, y=yy, z=scaled_data,
                                 weights=weights, **fitter_kwargs)
        except TypeError:
            # fitter doesn't support weights
            fitted_epsf = fitter(model=_epsf, x=xx, y=yy, z=scaled_data,
                                 **fitter_kwargs)

        fit_error_status = 0
        if fitter_has_fit_info:
            fit_info = copy.copy(fitter.fit_info)

            if 'ierr' in fit_info and fit_info['ierr'] not in [1, 2, 3, 4]:
                fit_error_status = 2    # fit solution was not found
        else:
            fit_info = None

        # compute the star's fitted position
        x_center = (star.cutout_center[0] +
                    (fitted_epsf.x_0.value / epsf._oversampling[0]))
        y_center = (star.cutout_center[1] +
                    (fitted_epsf.y_0.value / epsf._oversampling[1]))

        star = copy.deepcopy(star)
        star.cutout_center = (x_center, y_center)

        # set the star's flux to the ePSF-fitted flux
        star.flux = fitted_epsf.flux.value

        star._fit_info = fit_info
        star._fit_error_status = fit_error_status

        return star
398579
def fit(ts, fs=[], all_params=[], fit_vars=None,
        alg='leastsq', make_bounded=True):
    
    if fit_vars is None:
        fit_vars = [f._peakargs for f in fs]
    initc = [min(ts.values)]
    for f, peak_params, to_fit in zip(fs, all_params, fit_vars):
        if 'v' in to_fit:
            to_fit.remove('v')

        if make_bounded and hasattr(f, '_pbounds'):
            new_v = _to_unbnd_p({i: peak_params[i] for i in to_fit},
                                f._pbounds)
            initc += [new_v[i] for i in to_fit]
        else:
            initc += [peak_params[i] for i in to_fit]

    def errfunc_lsq(fit_params, t, y, all_params):
        # first value in fit_params is baseline
        # fit_y = np.ones(len(t)) * fit_params[0]
        fit_y = np.zeros(len(t))
        param_i = 1
        for f, peak_params, to_fit in zip(fs, all_params, fit_vars):
            for k in to_fit:
                peak_params[k] = fit_params[param_i]
                param_i += 1
            if make_bounded and hasattr(f, '_pbounds'):
                fit_y += f(t, **_to_bound_p(peak_params, f._pbounds))
            else:
                fit_y += f(t, **peak_params)
        return fit_y - y

    def errfunc(p, t, y, all_params):
        return np.sum(errfunc_lsq(p, t, y, all_params) ** 2)

    if alg == 'simplex':
        fit_p, _ = fmin(errfunc, initc, args=(ts.index, ts.values,
                                              peak_params))
#    elif alg == 'anneal':
#        fit_p, _ = anneal(errfunc, initc, args=(ts.index, ts.values,
#                                                peak_params))
    elif alg == 'lbfgsb':
        # TODO: use bounds param
        fitp, _ = fmin_l_bfgs_b(errfunc, fit_p,
                                args=(ts.index, ts.values, peak_params),
                                approx_grad=True)
    elif alg == 'leastsq':
        fit_p, _ = leastsq(errfunc_lsq, initc, args=(ts.index, ts.values,
                                                     all_params))
    # else:
    #     r = minimize(errfunc, initc, \
    #                  args=(ts.index, ts.values, all_params), \
    #                  jac=False, gtol=1e-2)
    #     #if not r['success']:
    #     #    print('Fail:' + str(f))
    #     #    print(r)
    #     #if np.nan in r['x']:  # not r['success']?
    #     #    fit_p = initc
    #     #else:
    #     #    fit_p = r['x']

    fit_pl = fit_p.tolist()
    v = fit_pl.pop(0)  # noqa
    fitted_params = []
    for f, to_fit in zip(fs, fit_vars):
        fit_p_dict = {v: fit_pl.pop(0) for v in to_fit}
        # fit_p_dict['v'] = v
        if make_bounded and hasattr(f, '_pbounds'):
            fitted_params.append(_to_bound_p(fit_p_dict, f._pbounds))
        else:
            fitted_params.append(fit_p_dict)

    # calculate r^2 of the fit
    ss_err = errfunc(fit_p, ts.index, ts.values, fitted_params)
    ss_tot = np.sum((ts.values - np.mean(ts.values)) ** 2)
    r2 = 1 - ss_err / ss_tot
    res = {'r^2': r2}

    return fitted_params, res
535686
def gnuplot_fit(function, data, options, initials, term_options)
      variables = initials.keys
      term = Terminal.new
      term.set(term_options)
      initials.each { |var_name, value| term.stream_puts "#{var_name} = #{value}" }
      command = "fit #{function} #{data.to_s(term, without_options: true)} " \
                "#{options} via #{variables.join(',')}"
      term.stream_puts(command)
      output = wait_for_output(term, variables)
      begin
        term.close
      rescue GnuplotError
        # Nothing interesting here.
        # If we had an error, we never reach this line.
        # Error here may be only additional information
        # such as correlation matrix.
      end
      output
    end
643781
def fit_transform(
        self,
        X,
        projection="sum",
        scaler=preprocessing.MinMaxScaler(),
        distance_matrix=False,
    ):
        

        projections = projection
        scalers = scaler
        distance_matrices = distance_matrix

        # Turn single projection arguments into a pipeline
        if isinstance(projection, list) and isinstance(projection[0], int):
            projections = [projection]

        if not isinstance(projection, list):
            projections = [projection]

        # Turn single scaler arguments into a pipeline
        if not isinstance(scaler, list):
            scalers = [scaler]

        # Turn single distance matrix arguments into a pipeline
        if not isinstance(distance_matrix, list):
            distance_matrices = [distance_matrix]

        # set defaults to first list item, if not (correctly) set by the user
        if len(scalers) != len(projections):
            scalers = [scalers[0]] * len(projections)

        if len(distance_matrices) != len(projections):
            distance_matrices = [distance_matrices[0]] * len(projections)

        if self.verbose > 0:
            print("..Composing projection pipeline of length %s:" % (len(projections)))
            print("\tProjections: %s" % ("\n\t\t".join(map(str, projections))))
            print("\tDistance matrices: %s" % ("\n".join(map(str, distance_matrices))))
            print("\tScalers: %s" % ("\n".join(map(str, scalers))))

        # Pipeline Stack the projection functions
        lens = X
        for projection, scaler, distance_matrix in zip(
            projections, scalers, distance_matrices
        ):
            lens = self.project(
                lens,
                projection=projection,
                scaler=scaler,
                distance_matrix=distance_matrix,
            )

        return lens
195776
def _fit_strel_to_im_2d(im, strel, r, x, y):
    
    """
    elem = strel.copy()
    x_dim, y_dim = im.shape
    x_min = x-r
    x_max = x+r+1
    y_min = y-r
    y_max = y+r+1
    if x_min < 0:
        x_adj = -x_min
        elem = elem[x_adj:, :]
        x_min = 0
    elif x_max > x_dim:
        x_adj = x_max - x_dim
        elem = elem[:-x_adj, :]
    if y_min < 0:
        y_adj = -y_min
        elem = elem[:, y_adj:]
        y_min = 0
    elif y_max > y_dim:
        y_adj = y_max - y_dim
        elem = elem[:, :-y_adj]
    ex, ey = elem.shape
    im[x_min:x_min+ex, y_min:y_min+ey] += elem
    return im
1113095
def _fit_null(self, Y, X_base, scan_onsets=None):
        
        n_V = np.size(Y, axis=1)
        n_T = np.size(Y, axis=0)
        t_start = time.time()

        D, F, run_TRs, n_run = self._prepare_DF(
            n_T, scan_onsets=scan_onsets)
        YTY_diag = np.sum(Y * Y, axis=0)
        YTDY_diag = np.sum(Y * np.dot(D, Y), axis=0)
        YTFY_diag = np.sum(Y * np.dot(F, Y), axis=0)

        tol = self.tol
        n_iter = self.n_iter
        logger.info('Fitting null model'
                    ' for maximum {} times'.format(n_iter))

        # Add DC components capturing run-specific baselines.
        X_DC = self._gen_X_DC(run_TRs)
        X_DC, X_base, idx_DC = self._merge_DC_to_base(
            X_DC, X_base, no_DC=False)
        X_res = None
        param0 = np.zeros(n_V)
        for it in range(0, n_iter):
            if X_res is None:
                X0 = X_base
            else:
                X0 = np.concatenate((X_base, X_res), axis=1)
            n_X0 = X0.shape[1]
            X0TX0, X0TDX0, X0TFX0 = self._make_templates(D, F, X0, X0)
            X0TY, X0TDY, X0TFY = self._make_templates(D, F, X0, Y)
            res_null = scipy.optimize.minimize(
                self._loglike_AR1_null, param0, args=(
                    YTY_diag, YTDY_diag, YTFY_diag,
                    X0TX0, X0TDX0, X0TFX0, X0TY, X0TDY, X0TFY,
                    n_T, n_V, n_run, n_X0),
                method=self.optimizer, jac=True, tol=tol,
                options=self.minimize_options)
            param_change = res_null.x - param0
            param0 = res_null.x.copy()
            est_rho1_AR1_null = 2.0 / np.pi * np.arctan(param0)
            if self.auto_nuisance:
                X0TAX0 = X0TX0[None, :, :] \
                    - est_rho1_AR1_null[:, None, None] \
                    * X0TDX0[None, :, :] \
                    + est_rho1_AR1_null[:, None, None]**2 \
                    * X0TFX0[None, :, :]
                # dimension: space*#baseline*#baseline
                X0TAY = self._make_ar1_quad_form(X0TY, X0TDY, X0TFY,
                                                 est_rho1_AR1_null)
                # dimension: #baseline*space
                beta0s = np.linalg.solve(X0TAX0, X0TAY.T).T
                residuals = Y - np.dot(X_base, beta0s[:np.shape(X_base)[1], :])
                X_res = self.nureg_method(self.n_nureg_).fit_transform(
                    self.preprocess_residual(residuals))
            if np.max(np.abs(param_change)) < self.tol:
                logger.info('The change of parameters is smaller than '
                            'the tolerance value {}. Fitting is finished '
                            'after {} iterations'.format(self.tol, it + 1))
                break
        X0TAX0 = X0TX0[None, :, :] \
            - est_rho1_AR1_null[:, None, None] \
            * X0TDX0[None, :, :] \
            + est_rho1_AR1_null[:, None, None]**2 \
            * X0TFX0[None, :, :]
        # dimension: space*#baseline*#baseline
        X0TAY = self._make_ar1_quad_form(X0TY, X0TDY, X0TFY,
                                         est_rho1_AR1_null)
        # dimension: #baseline*space
        est_beta0_AR1_null = np.linalg.solve(X0TAX0, X0TAY.T).T

        YTAY = self._make_ar1_quad_form(YTY_diag, YTDY_diag, YTFY_diag,
                                        est_rho1_AR1_null)
        # dimension: space,
        YTAcorrY = YTAY - np.sum(X0TAY * est_beta0_AR1_null, axis=0)
        # dimension: space,
        est_sigma_AR1_null = (YTAcorrY / (n_T - n_X0)) ** 0.5
        if idx_DC.size > 1:
            collapsed_DC = np.sum(X0[:, idx_DC], axis=1)
            X0 = np.insert(np.delete(X0, idx_DC, axis=1), 0,
                           collapsed_DC, axis=1)
            collapsed_beta0 = np.mean(est_beta0_AR1_null[idx_DC, :], axis=0)
            est_beta0_AR1_null = np.insert(
                np.delete(est_beta0_AR1_null, idx_DC, axis=0),
                0, collapsed_beta0, axis=0)
        t_finish = time.time()
        logger.info(
            'total time of fitting: {} seconds'.format(t_finish - t_start))
        return est_beta0_AR1_null, est_sigma_AR1_null, est_rho1_AR1_null, X0
383186
def fit_transform(self, X, y=None, **fit_params):
        
        y = column_or_1d(X, warn=True)
        _check_numpy_unicode_bug(X)
        self.classes_, X = np.unique(X, return_inverse=True)
        return X
974866
def partial_fit(self, X, y, classes=None):
        
        return self.fit(X, y, epochs=1)
1103745
def upsample(self, factor):
        
        
        self.checkforpilimage()
        
        if type(factor) != type(0):
            raise RuntimeError, "Upsample factor must be an integer !"
        
        if self.verbose:
            print "Upsampling by a factor of %i" % factor
        self.pilimage = self.pilimage.resize((self.pilimage.size[0] * factor, self.pilimage.size[1] * factor))
        self.upsamplefactor = factor
        
        self.draw = None
114782
def fit(self, data):
        

        _raise_error_if_not_sframe(data, "data")

        fitted_state = {}
        feature_columns = _internal_utils.get_column_names(data, self._exclude, self._features)

        if not feature_columns:
            raise RuntimeError("No valid feature columns specified in transformation.")

        fitted_state['features'] = feature_columns
        fitted_state['fitted'] = True

        self.__proxy__.update(fitted_state)

        return self
591945
def to_fits(self):
        

        max_length_coord = 1
        coord_x = []
        coord_y = []
        shapes = []
        radius = []
        rotangle_deg = []
        components = []

        reg_reverse_mapping = {value: key for key, value in
                               reg_mapping['FITS_REGION'].items()}
        reg_reverse_mapping['rectangle'] = 'ROTBOX'
        reg_reverse_mapping['circleannulus'] = 'ANNULUS'
        reg_reverse_mapping['ellipseannulus'] = 'ELLIPTANNULUS'

        for num, shape in enumerate(self):
            shapes.append(reg_reverse_mapping[shape.region_type])
            if shape.region_type == 'polygon':
                max_length_coord = max(len(shape.coord)/2, max_length_coord)
                coord = [x.value for x in shape.coord]
                coord_x.append(coord[::2])
                coord_y.append(coord[1::2])
                radius.append(0)
                rotangle_deg.append(0)
            else:
                coord_x.append(shape.coord[0].value)
                coord_y.append(shape.coord[1].value)
                if shape.region_type in ['circle', 'circleannulus', 'point']:
                    radius.append([float(val) for val in shape.coord[2:]])
                    rotangle_deg.append(0)
                else:
                    radius.append([float(x) for x in shape.coord[2:-1]])
                    rotangle_deg.append(shape.coord[-1].to('deg').value)

            tag = shape.meta.get('tag', '')
            if tag.isdigit():
                components.append(int(tag))
            else:
                components.append(num + 1)

        # padding every value with zeros at the end to make sure that all values
        # in the column have same length.
        for i in range(len(self)):
            if np.isscalar(coord_x[i]):
                coord_x[i] = np.array([coord_x[i]])
            if np.isscalar(coord_y[i]):
                coord_y[i] = np.array([coord_y[i]])
            if np.isscalar(radius[i]):
                radius[i] = np.array([radius[i]])

            coord_x[i] = np.pad(coord_x[i], (0, int(max_length_coord - len(coord_x[i]))),
                                'constant', constant_values=(0, 0))
            coord_y[i] = np.pad(coord_y[i], (0, int(max_length_coord - len(coord_y[i]))),
                                'constant', constant_values=(0, 0))
            radius[i] = np.pad(radius[i], (0, 4 - len(radius[i])), 'constant',
                               constant_values=(0, 0))

        table = Table([coord_x, coord_y, shapes, radius, rotangle_deg, components],
                       names=('X', 'Y', 'SHAPE', 'R', 'ROTANG', 'COMPONENT'))
        table['X'].unit = 'pix'
        table['Y'].unit = 'pix'
        table['R'].unit = 'pix'
        table['ROTANG'].unit = 'deg'

        return table
942232
def fit_transform(self, X, y):
        
        self.target_encoders = [None] * X.shape[1]
        self.target_mean = y.mean()

        for i, col in enumerate(X.columns):
            self.target_encoders[i] = self._get_target_encoder(X[col], y)

            X.loc[:, col] = X[col].fillna(NAN_INT).map(self.target_encoders[i]).fillna(self.target_mean)

        return X
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]
175818
def fit(self, data):
        
        jmodel = callMLlibFunc("fitPCA", self.k, data)
        return PCAModel(jmodel)
414054
def set_model(self, f0, A, model='trigonometric'):
        
        self.f0 = f0
        self.y_clean, vary = trigonometric_model(self.t, f0, A)
        # y_clean is normalized to have unit standard deviation
        self.y_clean = self.y_clean/np.sqrt(vary)
167683
def fit(self):
        
        # solve for estimator of B
        n,p          = np.shape(self._X)
        self._df     = float(n - p)
        self._Cx     = np.linalg.pinv(np.dot(self._X.T,self._X))
        self._Bhat   = np.dot(np.dot(self._Cx, self._X.T), self._A)
        self._Y_rec  = self._compute_prediction(self._X)
818092
def fit_model(ts, sc=None):
    
    assert sc != None, "Missing SparkContext"
    
    jvm = sc._jvm
    jmodel = jvm.com.cloudera.sparkts.models.GARCH.fitModel(_py2java(sc, Vectors.dense(ts)))
    return GARCHModel(jmodel=jmodel, sc=sc)