Fits a non-linear piecewise regression to fixtaion durations for a fixmat.

    Returns corrected fixation durations.
17886
def predict_fixation_duration(
        durations, angles, length_diffs, dataset=None, params=None):
    
    if dataset is None:
        dataset = np.ones(durations.shape)
    corrected_durations = np.nan * np.ones(durations.shape)
    for i, ds in enumerate(np.unique(dataset)):
        e = lambda v, x, y, z: (leastsq_dual_model(x, z, *v) - y)
        v0 = [120, 220.0, -.1, 0.5, .1, .1]
        id_ds = dataset == ds
        idnan = (
            ~np.isnan(angles)) & (
            ~np.isnan(durations)) & (
            ~np.isnan(length_diffs))
        v, s = leastsq(
            e, v0, args=(
                angles[
                    idnan & id_ds], durations[
                    idnan & id_ds], length_diffs[
                    idnan & id_ds]), maxfev=10000)
        corrected_durations[id_ds] = (durations[id_ds] -
                                      (leastsq_dual_model(angles[id_ds], length_diffs[id_ds], *v)))
        if params is not None:
            params['v' + str(i)] = v
            params['s' + str(i)] = s
    return corrected_durations
734844
def _absolute_spike_times_from_labels(self,time_dimension=0,*args,**kwargs):
        
        x = self[time_dimension].copy()
        #x = self.spike_times.get_converted(time_dimension,kwargs.get('units',None))
        factor = self.len(time_dimension,units=kwargs.get('units',None),resolution=kwargs.get('resolution',1.0))
        for a in args:
            if a in self:
                x += factor * self[a]
                factor *= self.len(a)
        for k in kwargs.keys():
            if k in self:
                x += factor * self[k]
                if kwargs[k] is not None:
                    factor *= kwargs[k]
                else:
                    factor *= self.len(k)
        return x,factor
257405
def fixed_parameters(self):
        
        libfn = utils.get_lib_fn('getTransformFixedParameters%s'%self._libsuffix)
        return np.asarray(libfn(self.pointer))
907944
def fit(self, X, y=None):
        
        # default to QuicGraphicalLasso
        estimator = self.estimator or QuicGraphicalLasso()

        if self.penalization != "subsampling" and not hasattr(
            estimator, self.penalty_name
        ):
            raise ValueError(
                (
                    "Must specify valid penalty for "
                    "estimator: {}.".format(self.penalty_name)
                )
            )

        self.proportion_ = None
        self.support_ = None
        self.lam_ = None
        self.lam_scale_ = None
        self.estimators_ = []
        self.lams_ = []
        self.subsets_ = []

        X = check_array(X, ensure_min_features=2, estimator=self)
        X = as_float_array(X, copy=False, force_all_finite=False)

        n_samples_, n_features_ = X.shape
        _, self.lam_scale_ = _init_coefs(X, method=self.init_method)

        fit_fun = partial(
            _fit,
            penalization=self.penalization,
            lam=self.lam,
            lam_perturb=self.lam_perturb,
            lam_scale_=self.lam_scale_,
            estimator=estimator,
            penalty_name=self.penalty_name,
            subsample=self.subsample,
            bootstrap=self.bootstrap,
        )
        indexed_param_grid = [(nn,) for nn in range(self.n_trials)]

        if self.sc is None:
            results = _cpu_map(
                partial(fit_fun, X=X, prng=self.prng),
                indexed_param_grid,
                n_jobs=self.n_jobs,
            )
        else:
            X_bc = self.sc.broadcast(X)
            results = _spark_map(fit_fun, indexed_param_grid, self.sc, self.seed, X_bc)
            X_bc.unpersist()

        self.estimators_ = [e for r, (l, s, e) in results]
        self.subsets_ = [s for r, (l, s, e) in results]
        self.lams_ = [l for r, (l, s, e) in results]

        # reduce
        self.lam_ = 0.0
        self.proportion_ = np.zeros((n_features_, n_features_))
        for new_estimator in self.estimators_:
            # update proportions
            if isinstance(new_estimator.precision_, list):
                for prec in new_estimator.precision_:
                    self.proportion_[np.nonzero(prec)] += 1.

            elif isinstance(new_estimator.precision_, np.ndarray):
                self.proportion_[np.nonzero(new_estimator.precision_)] += 1.

            else:
                raise ValueError("Estimator returned invalid precision_.")

            # currently, dont estimate self.lam_ if penalty_name is different
            if self.penalty_name == "lam":
                self.lam_ += np.mean(new_estimator.lam_.flat)

        # estimate support locations
        threshold = self.support_thresh * self.n_trials
        self.support_ = np.zeros(self.proportion_.shape)
        self.support_[self.proportion_ > threshold] = 1.0

        self.lam_ /= self.n_trials
        if self.normalize:
            self.proportion_ /= self.n_trials

        return self
1051163
def _calc_damping(mod_reducs, x_2, x_2_mean, x_3, x_3_mean):
        """"""
        # Mean values of the predictors
        x_1_mean = -1.0
        x_1 = np.log(np.log(1 / mod_reducs) + 0.103)

        ones = np.ones_like(mod_reducs)
        x = np.c_[ones, x_1, x_2, x_3, (x_1 - x_1_mean) * (x_2 - x_2_mean), (
            x_2 - x_2_mean) * (x_3 - x_3_mean)]
        c = np.c_[2.86, 0.571, -0.103, -0.141, 0.0419, -0.240]

        ln_damping = (c * x).sum(axis=1)
        return np.exp(ln_damping) / 100.
680802
void adjustOffsets(final double pNorthOrWest, final double pSouthOrEast,
					   final boolean isLatitude, final int pExtraSize) {
		final long min;
		final long max;
		final long deltaX;
		final long deltaY;
		if (isLatitude) {
			min = getLongPixelYFromLatitude(pNorthOrWest);
			max = getLongPixelYFromLatitude(pSouthOrEast);
			deltaX = 0;
			deltaY = getScrollableOffset(min, max, mMercatorMapSize, mIntrinsicScreenRectProjection.height(), pExtraSize);
		} else {
			min = getLongPixelXFromLongitude(pNorthOrWest);
			max = getLongPixelXFromLongitude(pSouthOrEast);
			deltaX = getScrollableOffset(min, max, mMercatorMapSize, mIntrinsicScreenRectProjection.width(), pExtraSize);
			deltaY = 0;
		}
		adjustOffsets(deltaX, deltaY);
	}
755854
def _fixedpoint(D, tol=1e-7, maxiter=None):
    ''''''
    N, K = D.shape
    logp = log(D).mean(axis=0)
    a0 = _init_a(D)

    # Start updating
    if maxiter is None:
        maxiter = MAXINT
    for i in xrange(maxiter):
        a1 = _ipsi(psi(a0.sum()) + logp)
        # if norm(a1-a0) < tol:
        if abs(loglikelihood(D, a1)-loglikelihood(D, a0)) < tol: # much faster
            return a1
        a0 = a1
    raise Exception('Failed to converge after {} iterations, values are {}.'
                    .format(maxiter, a1))
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)
684541
def estimate_sub_second_time(files, interval=0.0):
    '''
    
    '''
    if interval <= 0.0:
        return [exif_time(f) for f in tqdm(files, desc="Reading image capture time")]

    onesecond = datetime.timedelta(seconds=1.0)
    T = datetime.timedelta(seconds=interval)
    for i, f in tqdm(enumerate(files), desc="Estimating subsecond time"):
        m = exif_time(f)
        if not m:
            pass
        if i == 0:
            smin = m
            smax = m + onesecond
        else:
            m0 = m - T * i
            smin = max(smin, m0)
            smax = min(smax, m0 + onesecond)
    if not smin or not smax:
        return None
    if smin > smax:
        # ERROR LOG
        print('Interval not compatible with EXIF times')
        return None
    else:
        s = smin + (smax - smin) / 2
        return [s + T * i for i in range(len(files))]
155863
def time_ephem(b, component, dataset, solve_for=None, **kwargs):
    
    hier = b.get_hierarchy()
    if not len(hier.get_value()):
        # TODO: change to custom error type to catch in bundle.add_component
        # TODO: check whether the problem is 0 hierarchies or more than 1
        raise NotImplementedError("constraint for time_ecl requires hierarchy")

    if component=='_default':
        # need to do this so that the constraint won't fail before being copied
        parentorbit = hier.get_top()
    else:
        parentorbit = hier.get_parent_of(component)

    parentorbit_ps = _get_system_ps(b, parentorbit)

    filterwargs = {}
    if component is not None:
        filterwargs['component'] = component
    if dataset is not None:
        filterwargs['dataset'] = dataset

    time_ephem = b.get_parameter(qualifier='time_ephems', **filterwargs)
    t0 = parentorbit_ps.get_parameter(qualifier='t0_supconj')  # TODO: make sure t0_supconj makes sense here
    period = parentorbit_ps.get_parameter(qualifier='period')
    phshift = parentorbit_ps.get_parameter(qualifier='phshift')
    dpdt = parentorbit_ps.get_parameter(qualifier='dpdt')
    esinw_ = parentorbit_ps.get_parameter(qualifier='esinw')

    N = b.get_parameter(qualifier='Ns', **filterwargs)

    if solve_for in [None, time_ephem]:

        # TODO: N is always an int, but we want to include the expected phase of eclipse (ie N+ph_ecl) based on which component and esinw/ecosw
        # then we can have bundle.add_component automatically default to add all components instead of just the primary

        # same as Bundle.to_time except phase can be > 1
        lhs = time_ephem
        # we have to do a trick here since dpdt is in sec/yr and floats are
        # assumed to have the same unit during subtraction or addition.
        one = 1.0*(u.s/u.s)
        if component!='_default' and hier.get_primary_or_secondary(component)=='secondary':
            # TODO: make sure this constraint updates if the hierarchy changes?
            N = N + 0.5 + esinw_  # TODO: check this
        rhs = t0 + ((N - phshift) * period) / (-1 * (N - phshift) * dpdt + one)
        #rhs = (N-phshift)*period
    else:
        raise NotImplementedError

    return lhs, rhs, {'component': component, 'dataset': dataset}
27707
def regress_fit(fqdn, result, *argl, **argd):
    
    if len(argl) > 2:
        yP = argl[2]
    out = _generic_fit(fqdn, result, regress_predict, yP, *argl, **argd)
    return out
713432
def nss(prediction, fix):
    

    prediction = prediction - np.mean(prediction)
    prediction = prediction / np.std(prediction)
    return np.mean(prediction[fix[0], fix[1]])
936097
def fitPlaneLSQ(XYZ):
    
    [rows,cols] = XYZ.shape
    G = np.ones((rows,3))
    G[:,0] = XYZ[:,0]  #X
    G[:,1] = XYZ[:,1]  #Y
    Z = XYZ[:,2]
    coeff,resid,rank,s = np.linalg.lstsq(G,Z,rcond=None)
    return coeff
1055341
def _analytical_fit_adjacent(self, ref_dists):
        
        dists = ref_dists**2
        rot_dists = self._rotate_rows(dists)
        b = dists - rot_dists + self._partial_b
        self._b = b
        return self._pinvA.dot(b)
1107568
def plot_fit(self,**kwargs):
        
        import matplotlib.pyplot as plt
        import seaborn as sns

        figsize = kwargs.get('figsize',(10,7))

        if self.latent_variables.estimated is False:
            raise Exception("No latent variables estimated!")
        else:
            date_index = self.index[self.lags:self.data[0].shape[0]]
            mu, Y = self._model(self.latent_variables.get_z_values())
            for series in range(0,Y.shape[0]):
                plt.figure(figsize=figsize)
                plt.plot(date_index,Y[series],label='Data ' + str(series))
                plt.plot(date_index,mu[series],label='Filter' + str(series),c='black')  
                plt.title(self.data_name[series])
                plt.legend(loc=2)   
            plt.show()
1121721
def fit_trace_polynomial(trace, deg, axis=0):
    '''
    
    '''

    dispaxis = axis_to_dispaxis(axis)

    # FIT to a polynomial
    pfit = numpy.polyfit(trace[:,0], trace[:,1], deg)
    start = trace[0,0]
    stop = trace[-1,0],
    return PolyTrace(start, stop, axis, pfit)
1309185
def regress_poly(degree, data, remove_mean=True, axis=-1):
    
    timepoints = data.shape[0]
    # Generate design matrix
    X = np.ones((timepoints, 1))  # quick way to calc degree 0
    for i in range(degree):
        polynomial_func = Legendre.basis(i + 1)
        value_array = np.linspace(-1, 1, timepoints)
        X = np.hstack((X, polynomial_func(value_array)[:, np.newaxis]))
    non_constant_regressors = X[:, :-1] if X.shape[1] > 1 else np.array([])
    betas = np.linalg.pinv(X).dot(data)
    if remove_mean:
        datahat = X.dot(betas)
    else:  # disregard the first layer of X, which is degree 0
        datahat = X[:, 1:].dot(betas[1:, ...])
    regressed_data = data - datahat
    return regressed_data, non_constant_regressors