Numerical functions of the model class.
961135
def modelnumericfunctions(self):
        """"""
        lines = Lines()
        lines.extend(self.solve)
        lines.extend(self.calculate_single_terms)
        lines.extend(self.calculate_full_terms)
        lines.extend(self.get_point_states)
        lines.extend(self.set_point_states)
        lines.extend(self.set_result_states)
        lines.extend(self.get_sum_fluxes)
        lines.extend(self.set_point_fluxes)
        lines.extend(self.set_result_fluxes)
        lines.extend(self.integrate_fluxes)
        lines.extend(self.reset_sum_fluxes)
        lines.extend(self.addup_fluxes)
        lines.extend(self.calculate_error)
        lines.extend(self.extrapolate_error)
        return lines
1239871
def linear_model(x, y):
        
        x1, x2 = x
        y1, y2 = y
        m = (y2 - y1) / (x2 - x1)
        b = y1 - (m * x1)
        return lambda x: m * x + b
422598
def infer_dm(self, m, s, ds):
        
        OptimizedInverseModel.infer_dm(self, ds)
        if len(self.fmodel.dataset) == 0:
            return [[0.0]*self.dim_out]
        else:
            _, index = self.fmodel.dataset.nn_dims(m, np.hstack((s, ds)), range(len(m)), range(self.dim_x, self.dim_x + self.dim_y), k=1)
            guesses = [self.fmodel.dataset.get_dims(index[0], dims=range(len(m), self.dim_x))]
            result = []
                    
            for g in guesses:
                res = scipy.optimize.minimize(lambda dm:self._error_dm(m, dm, s), g,
                                              args        = (),
                                              method      = self.algo,
                                              options     = self.conf
                                             )
    
    
    
                d = self._error_dm(m, res.x, s)
                result.append((d, res.x))
            return [xi for fi, xi in sorted(result)][0]
1309049
def get_model(input_dim):
    """"""
    model = Sequential()
    model.add(Dense(100, input_dim=input_dim, activation='sigmoid'))
    model.add(Dense(1))
    model.compile(loss='mean_squared_error', optimizer='SGD')
    return model
903302
def _hammer_function_precompute(self,x0, L, Min, model):
        
        if x0 is None: return None, None
        if len(x0.shape)==1: x0 = x0[None,:]
        m = model.predict(x0)[0]
        pred = model.predict(x0)[1].copy()
        pred[pred<1e-16] = 1e-16
        s = np.sqrt(pred)
        r_x0 = (m-Min)/L
        s_x0 = s/L
        r_x0 = r_x0.flatten()
        s_x0 = s_x0.flatten()
        return r_x0, s_x0
213670
def _calc_inst_pmf(self):
        """"""
        # Easy vars
        t = self.t_
        epsilon = self.epsilon
        alpha = self.alpha
        preds = self._preds_avg_in_strata
        weights = self.strata.weights_[:,np.newaxis]
        p1 = self._BB_model.theta_[:,np.newaxis]
        p0 = 1 - p1
        if t==0:
            F = self._F_guess[self.opt_class]
        else:
            F = self._estimate[t - 1, self.opt_class]
            # Fill in non-finite estimates with the initial guess
            nonfinite = ~np.isfinite(F)
            F[nonfinite] = self._F_guess[self.opt_class][nonfinite]

        # Calculate optimal instrumental pmf
        sqrt_arg = np.sum(preds * (alpha**2 * F**2 * p0 + (1 - F)**2 * p1) + \
                          (1 - preds) * (1 - alpha)**2 * F**2 * p1, \
                          axis=1, keepdims=True) #: sum is over classifiers
        inst_pmf = weights * np.sqrt(sqrt_arg)
        # Normalize
        inst_pmf /= np.sum(inst_pmf)
        # Epsilon-greedy: (1 - epsilon) q + epsilon * p
        inst_pmf *= (1 - epsilon)
        inst_pmf += epsilon * weights

        if self.record_inst_hist:
            self._inst_pmf[:,t] = inst_pmf.ravel()
        else:
            self._inst_pmf = inst_pmf.ravel()
706755
def admm_linearized_simple(x, f, g, L, tau, sigma, niter, **kwargs):
    
    callback = kwargs.pop('callback', None)
    z = L.range.zero()
    u = L.range.zero()
    for _ in range(niter):
        x[:] = f.proximal(tau)(x - tau / sigma * L.adjoint(L(x) + u - z))
        z = g.proximal(sigma)(L(x) + u)
        u = L(x) + u - z
        if callback is not None:
            callback(x)
912894
def obfn_dfd(self):
        
        """

        Ef = sl.inner(self.Df, self.obfn_fvarf(), axis=self.cri.axisM) - \
            self.Sf
        return sl.rfl2norm2(Ef, self.S.shape, axis=self.cri.axisN) / 2.0
233825
def cublasSgemm(handle, transa, transb, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc):
    

    status = _libcublas.cublasSgemm_v2(handle,
                                       _CUBLAS_OP[transa],
                                       _CUBLAS_OP[transb], m, n, k, 
                                       ctypes.byref(ctypes.c_float(alpha)),
                                       int(A), lda, int(B), ldb,
                                       ctypes.byref(ctypes.c_float(beta)),
                                       int(C), ldc)
    cublasCheckStatus(status)
1332648
def _nominal_kernel(x, y, out):
    """"""
    for i in range(x.shape[0]):
        for j in range(y.shape[0]):
            out[i, j] += (x[i, :] == y[j, :]).sum()

    return out
734600
def predict_size_models(self, model_names,
                            input_columns,
                            metadata_cols,
                            data_mode="forecast"):
        
        groups = self.size_models.keys()
        predictions = {}
        for group in groups:
            group_data = self.data[data_mode]["combo"].loc[self.data[data_mode]["combo"][self.group_col] == group]
            if group_data.shape[0] > 0:
                predictions[group] = {}
                output_values = self.size_models[group]["outputvalues"].astype(int)
                for m, model_name in enumerate(model_names):
                    print("{0} {1}".format(group, model_name))
                    pred_col_names = [model_name.replace(" ", "-") + "_{0:02d}".format(p) for p in output_values]
                    predictions[group][model_name] = group_data[metadata_cols]
                    pred_vals = self.size_models[group][model_name].predict_proba(group_data[input_columns])
                    pred_classes = self.size_models[group][model_name].classes_
                    pred_pdf = np.zeros((pred_vals.shape[0], output_values.size))
                    for pcv, pc in enumerate(pred_classes):
                        idx = np.where(output_values == pc)[0][0]
                        pred_pdf[:, idx] = pred_vals[:, pcv]
                    for pcn, pred_col_name in enumerate(pred_col_names):
                        predictions[group][model_name].loc[:, pred_col_name] = pred_pdf[:, pcn]
        return predictions
1311884
def grad_numerical(self, x, func, epsilon=None):
        """"""
        eps = 1e-8 * (1 + abs(x)) if epsilon is None else epsilon
        grad = np.zeros(len(x))
        ei = np.zeros(len(x))  # float is 1.6 times faster than int
        for i in rglen(x):
            ei[i] = eps[i]
            grad[i] = (func(x + ei) - func(x - ei)) / (2*eps[i])
            ei[i] = 0
        return grad
108202
def obfn_dfd(self):
        
        """

        Ef = sl.inner(self.Zf, self.obfn_fvarf(), axis=self.cri.axisM) \
          - self.Sf
        return (np.linalg.norm(self.W * sl.irfftn(Ef, self.cri.Nv,
                                                  self.cri.axisN))**2) / 2.0
976545
def coefficients(self):
        """"""
        out = numpy.array([self.A[key] for key in self.keys])
        out = numpy.rollaxis(out, -1)
        return out
1289444
def cublasSsymm(handle, side, uplo, m, n, alpha, A, lda, B, ldb, beta, C, ldc):
    
    
    status = _libcublas.cublasSsymm_v2(handle,
                                       _CUBLAS_SIDE_MODE[side], 
                                       _CUBLAS_FILL_MODE[uplo], 
                                       m, n, ctypes.byref(ctypes.c_float(alpha)),
                                       int(A), lda, int(B), ldb, 
                                       ctypes.byref(ctypes.c_float(beta)), 
                                       int(C), ldc)
    cublasCheckStatus(status)
580218
def f_nc(self,x):
        '''
        
        '''
        x = np.atleast_2d(x)
        xx = self.context_manager._expand_vector(x)
        if x.shape[0] == 1:
            return self.f(xx)[0]
        else:
            return self.f(xx)
1133609
def sparse_GP_regression_1D(num_samples=400, num_inducing=5, max_iters=100, optimize=True, plot=True, checkgrad=False):
    """"""
    # sample inputs and outputs
    X = np.random.uniform(-3., 3., (num_samples, 1))
    Y = np.sin(X) + np.random.randn(num_samples, 1) * 0.05
    # construct kernel
    rbf = GPy.kern.RBF(1)
    # create simple GP Model
    m = GPy.models.SparseGPRegression(X, Y, kernel=rbf, num_inducing=num_inducing)

    if checkgrad:
        m.checkgrad()

    if optimize:
        m.optimize('tnc', max_iters=max_iters)

    if plot:
        m.plot()

    return m