Prepend the constant feature 1 as first feature and return the modified
    feature set.

    Parameters
    ----------
    features : ndarray or DataFrame
197444
def add_const(features):
    
    content = np.empty((features.shape[0], features.shape[1] + 1), dtype='float64')
    content[:, 0] = 1.
    if isinstance(features, np.ndarray):
        content[:, 1:] = features
        return content
    content[:, 1:] = features.iloc[:, :].values
    cols = ['Constant'] + features.columns.tolist()
    return pd.DataFrame(data=content, index=features.index, columns=cols, dtype='float64')
1370169
def _resolve_features(self):
        """"""

        for parentid in self.featsbyparent:
            parent = self.featsbyid[parentid]
            for child in self.featsbyparent[parentid]:
                parent.add_child(child, rangecheck=self.strict)

        # Replace top-level multi-feature reps with a pseudo-feature
        for n, record in enumerate(self.records):
            if not isinstance(record, Feature):
                continue
            if not record.is_multi:
                continue
            assert record.multi_rep == record
            newrep = sorted(record.siblings + [record])[0]
            if newrep != record:
                for sib in sorted(record.siblings + [record]):
                    sib.multi_rep = newrep
                    if sib != newrep:
                        newrep.add_sibling(sib)
                record.siblings = None
            parent = newrep.pseudoify()
            self.records[n] = parent

        if not self.assumesorted:
            for seqid in self.inferred_regions:
                if seqid not in self.declared_regions:
                    seqrange = self.inferred_regions[seqid]
                    srstring = '##sequence-region {:s} {:d} {:d}'.format(
                        seqid, seqrange.start + 1, seqrange.end
                    )
                    seqregion = Directive(srstring)
                    self.records.append(seqregion)

        for record in sorted(self.records):
            yield record
        self._reset()
637946
def prepopulate(self):
        
        if self._prepopulated is False:
            engine = create_engine('sqlite:////' + self.dbpath)
            self._db_base.metadata.create_all(engine)
            self._prepopulated = True
            session_cl = sessionmaker(bind=engine)
            session = session_cl()

            for (dirpath, dirnames, filenames) in walk(self.path_to_set):
                for f_name in filenames:
                    datapoint = self._set_object(real_id=cutoff_filename(self.file_prefix, self.file_suffix, f_name),
                                                 path=f_name, features=None)
                    session.add(datapoint)
                    self.points_amt += 1
            session.commit()
            session.close()
        return None
81911
def prepare_csv_to_dataframe(data_file, config, use_target=True):
    
    names, dtypes = [], []
    model = config.get_data_model()
    for feature in model:
        assert feature.get_name() not in names, "Two features can't have the same name."
        if not use_target and feature.is_target():
            continue
        names.append(feature.get_name())
    data = pd.read_csv(data_file, names=names)

    transform_categorical_features(config, data, use_target)

    return data
511117
def _format_feature(feature, weight, hl_spaces):
    # type: (...) -> str
    
    if isinstance(feature, FormattedFeatureName):
        return feature.format()
    elif (isinstance(feature, list) and
            all('name' in x and 'sign' in x for x in feature)):
        return _format_unhashed_feature(feature, weight, hl_spaces=hl_spaces)
    else:
        return _format_single_feature(feature, weight, hl_spaces=hl_spaces)
236750
def _parse_features(features, new_names=False, rename_function=None, default_feature_type=None,
                        allowed_feature_types=None):
        
        return FeatureParser(features, new_names=new_names, rename_function=rename_function,
                             default_feature_type=default_feature_type, allowed_feature_types=allowed_feature_types)
96811
def has_ndarray_int_columns(features, X):
    
    _, ncols = X.shape
    if not all(d.isdigit() for d in features if isinstance(d, str)) or not isinstance(X, np.ndarray):
        return False
    ndarray_columns = np.arange(0, ncols)
    feature_cols = np.unique([int(d) for d in features])
    return all(np.in1d(feature_cols, ndarray_columns))
999770
def addFixedEffect(self,F=None,A=None, REML=True, index=None):
        
        if F is None:   F = np.ones((self.N,1))
        if A is None:
            A = np.eye(self.P)
            A_identity = True
        elif (A.shape == (self.P,self.P)) & (A==np.eye(self.P)).all():
            A_identity = True
        else:
            A_identity = False

        assert F.shape[0]==self.N, "F dimension mismatch"
        assert A.shape[1]==self.P, "A dimension mismatch"
        if index is None or index==self.n_terms:
            self.F.append(F)
            self.A.append(A)
            self.A_identity.append(A_identity)
            self.REML_term.append(REML)
            # build B matrix and indicator
            self.B.append(np.zeros((F.shape[1],A.shape[0])))
            self._n_terms+=1
            self._update_indicator(F.shape[1],A.shape[0])
        elif index >self.n_terms:
            raise Exception("index exceeds max index of terms")
        else:
            self._n_fixed_effs-=self.F[index].shape[1]*self.A[index].shape[0]
            if self.REML_term[index]:
                self._n_fixed_effs_REML-=self.F[index].shape[1]*self.A[index].shape[0]
            self.F[index] = F
            self.A[index] = A
            self.A_identity[index] = A_identity
            self.REML_term[index]=REML
            self.B[index] = np.zeros((F.shape[1],A.shape[0]))
            self._rebuild_indicator()

        self._n_fixed_effs+=F.shape[1]*A.shape[0]
        if REML:
            self._n_fixed_effs_REML+=F.shape[1]*A.shape[0]
        self.clear_cache('Fstar','Astar','Xstar','Xhat',
                         'Areml','Areml_eigh','Areml_chol','Areml_inv','beta_hat','B_hat',
                         'LRLdiag_Xhat_tens','Areml_grad',
                         'beta_grad','Xstar_beta_grad','Zstar','DLZ')
1056656
def Prepend(self, **kw):
        
        kw = copy_non_reserved_keywords(kw)
        for key, val in kw.items():
            # It would be easier on the eyes to write this using
            # "continue" statements whenever we finish processing an item,
            # but Python 1.5.2 apparently doesn't let you use "continue"
            # within try:-except: blocks, so we have to nest our code.
            try:
                orig = self._dict[key]
            except KeyError:
                # No existing variable in the environment, so just set
                # it to the new value.
                self._dict[key] = val
            else:
                try:
                    # Check if the original looks like a dictionary.
                    # If it is, we can't just try adding the value because
                    # dictionaries don't have __add__() methods, and
                    # things like UserList will incorrectly coerce the
                    # original dict to a list (which we don't want).
                    update_dict = orig.update
                except AttributeError:
                    try:
                        # Most straightforward:  just try to add them
                        # together.  This will work in most cases, when the
                        # original and new values are of compatible types.
                        self._dict[key] = val + orig
                    except (KeyError, TypeError):
                        try:
                            # Check if the added value is a list.
                            add_to_val = val.append
                        except AttributeError:
                            # The added value isn't a list, but the
                            # original is (by process of elimination),
                            # so insert the the new value in the original
                            # (if there's one to insert).
                            if val:
                                orig.insert(0, val)
                        else:
                            # The added value is a list, so append
                            # the original to it (if there's a value
                            # to append).
                            if orig:
                                add_to_val(orig)
                            self._dict[key] = val
                else:
                    # The original looks like a dictionary, so update it
                    # based on what we think the value looks like.
                    if SCons.Util.is_List(val):
                        for v in val:
                            orig[v] = None
                    else:
                        try:
                            update_dict(val)
                        except (AttributeError, TypeError, ValueError):
                            if SCons.Util.is_Dict(val):
                                for k, v in val.items():
                                    orig[k] = v
                            else:
                                orig[val] = None
        self.scanner_map_delete(kw)
582333
def include_feature(self, name):
        """'"""

        if self.feature_is_included(name) == 0:
            descr = self.features[name].description
            raise DistutilsOptionError(
                descr + " is required, but was excluded or is not available"
            )
        self.features[name].include_in(self)
        self._set_feature(name, 1)
600366
def _extract_features(self, sequence1, sequence2):
        

        array1 = np.array(tuple(sequence1), ndmin=2).T
        array2 = np.array(tuple(sequence2), ndmin=2)

        K = (len(self._binary_features) 
             + sum(num_feats for _, num_feats in self._sparse_features))

        feature_array = np.zeros((array1.size, array2.size, K), dtype='float64')

        for k, feature_function in enumerate(self._binary_features):
            feature_array[..., k] = feature_function(array1, array2)

        if self._sparse_features:
            n_binary_features = len(self._binary_features)

            for i, j in np.ndindex(len(sequence1), len(sequence2)):
                k = n_binary_features

                for feature_function, num_features in self._sparse_features:
                    
                    feature_array[i, j, k + feature_function(i, j, sequence1, sequence2)] = 1.0
                    k += num_features

        return feature_array
551395
def prepare(self, data_source):
        
        dataframe = self.__get_dataframe(data_source, use_target=True)
        self.__config.get_data_model().set_features_types_from_dataframe(dataframe)
        dataframe = self.__cleaner.prepare(dataframe)
        return self.__transformer.prepare(dataframe)
1006774
def feature_names(self, names):
        ""

        if len(names) != self.num_features:
            raise ValueError("Number of names do not match the number of features!")
        if not isinstance(names, (Sequence, np.ndarray, np.generic)):
            raise ValueError("Input is not a sequence. "
                             "Ensure names are in the same order "
                             "and length as features.")

        self.__feature_names = np.array(names)
113801
def provide(self, feature_name, provider, *args, **kwargs):
        
        if not self.allow_replace:
            assert feature_name not in self.providers, "Duplicate feature: {!r}".format(
                feature_name
            )
        if callable(provider) and not isinstance(provider, type):
            self.providers[feature_name] = lambda: provider(*args, **kwargs)
        else:
            self.providers[feature_name] = lambda: provider
179483
def _impute_values(self, features):
        
        if self.verbosity > 1:
            print('Imputing missing values in feature set')

        if self._fitted_imputer is None:
            self._fitted_imputer = Imputer(strategy="median")
            self._fitted_imputer.fit(features)

        return self._fitted_imputer.transform(features)
143486
def _flip_feature(self, feature, parent_len):
    '''

    '''
    copy = feature.copy()
    # Put on the other strand
    if copy.strand == 0:
        copy.strand = 1
    else:
        copy.strand = 0
    # Adjust locations - guarantee that start is always less than end
    copy.start = parent_len - copy.start
    copy.stop = parent_len - copy.stop
    copy.start, copy.stop = copy.stop, copy.start
    return copy
802719
def _normalize_features(feature_list, prepared, is_traindata):
    
    if is_traindata:
        _calculate_feature_stats(feature_list,
                                 prepared,
                                 "featurenormalization.csv")

    start = 0
    for feature in feature_list:
        end = start + feature.get_dimension()
        # For every instance in the dataset: Normalize!
        for i in range(len(prepared)):
            # The 0 is necessary as every element is (x, y)
            feature_range = (feature.max - feature.min)
            if feature_range == 0:
                feature_range = 1
            prepared[i][0][start:end] = (prepared[i][0][start:end] -
                                         feature.mean) / feature_range
        start = end
    return prepared