Factory to choose feature extractor

    :param feature: name of the feature
    :return: Feature extractor function
192117
def factory(feature):
    
    if feature == 'hog':
        return hog
    elif feature == 'deep':
        return deep
    elif feature == 'gray':
        return gray
    elif feature == 'lab':
        return lab
    elif feature == 'luv':
        return luv
    elif feature == 'hsv':
        return hsv
    elif feature == 'hls':
        return hls
    else:
        return rgb
792277
def explain_feature(featurename):
    '''
    '''

    import os
    import featuremonkey
    import importlib
    import subprocess

    def guess_version(feature_module):
        if hasattr(feature_module, '__version__'):
            return feature_module.__version__
        if hasattr(feature_module, 'get_version'):
            return feature_module.get_version()
        return ('unable to determine version:'
                ' please add __version__ or get_version()'
                ' to this feature module!')

    def git_rev(module):
        stdout, stderr = subprocess.Popen(
            ["git", "rev-parse", "HEAD"],
            cwd=os.path.dirname(module.__file__),
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE
        ).communicate()
        if 'Not a git repo' in stderr:
            return '-'
        else:
            return stdout.strip()

    def git_changes(module):
        stdout = subprocess.Popen(
            ["git", "diff", "--name-only"],
            cwd=os.path.dirname(module.__file__),
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE
        ).communicate()[0]
        return stdout.strip() or '-'

    if featurename in featuremonkey.get_features_from_equation_file(os.environ['PRODUCT_EQUATION_FILENAME']):
        print()
        print(featurename)
        print('-' * 60)
        print()
        is_subfeature = '.features.' in featurename
        try:
            feature_module = importlib.import_module(featurename)
        except ImportError:
            print('Error: unable to import feature "%s"' % featurename)

        print('Location: %s' % os.path.dirname(feature_module.__file__))
        print()
        if is_subfeature:
            print('Version: see parent feature')
            print()
        else:
            print('Version: %s' % str(guess_version(feature_module)))
            print()
            print('git: %s' % git_rev(feature_module))
            print()
            print('git changed: %s' % '\n\t\t'.join(git_changes(feature_module).split('\n')))
    else:
        print('No feature named ' + featurename)
841665
public static function extract(Feature $feature)
    {
        $serialized = FeatureSerializer::serialize($feature);

        return self::extractFromArray($serialized);
    }
975462
def calculate_array_feature_extractor_output_shapes(operator):
    '''
    
    '''
    check_input_and_output_numbers(operator, input_count_range=1, output_count_range=1)
    check_input_and_output_types(operator, good_input_types=[FloatTensorType, Int64TensorType, StringTensorType])

    N = operator.inputs[0].type.shape[0]
    extracted_feature_number = len(operator.raw_operator.arrayFeatureExtractor.extractIndex)

    # Save doc_string before over-writing by us
    doc_string = operator.outputs[0].type.doc_string
    operator.outputs[0].type = copy.deepcopy(operator.inputs[0].type)
    operator.outputs[0].type.shape = [N, extracted_feature_number]
    # Assign correct doc_string to the output
    operator.outputs[0].type.doc_string = doc_string
131526
def feature(self, index):
        
        if index < 0 or index >= self.num_features_:
            raise ValueError('Index %d out of range' %(index))
        return self.features_[index]
1166747
def getFeature(self, prop):
        """"""

        f = self.props.get(prop, None)
        if not f:
            return None
        if isinstance(f, Feature):
            return f
        if isinstance(f, tuple):
            if f[0]:
                return f[0]
            elif f[1]:
                return f[1]
            raise Exception("Getting value from a property with a constrain")
        if isinstance(f, list):
            return f
        raise Exception("Getting value from a not simple property.")
380263
def sampleLocationFromFeature(self, feature):
    
    if feature == "surface":
      return self.sampleLocationFromFeature('face') # Temporary workaround for surfaces
    elif feature=="face":
      indx = self.rng.choice(range(self.faces.count))
      rndFace = self.faces[indx]
      return self._sampleLocationOnFace(rndFace)

    elif feature == "edge":
      indx = self.rng.choice(range(self.faces.count))
      rndFace = self.faces[indx]
      rndVertices = self.rng.sample(self.vertices[rndFace],2)
      return self._sampleLocationOnEdge(rndVertices)

    elif feature == "vertex":
      rndVertexIndx = self.rng.choice(range(self.vertices.count))
      return np.array(self.vertices[rndVertexIndx].tolist())

    elif feature == "surface":
      return self.sampleLocationFromFeature("face")      # Temporary workaround for surfaces
    elif feature == "random":
      return self.sampleLocation()
    else:
      raise NameError("No such feature in {}: {}".format(self, feature))
245036
def get_feature_names(clf, vec=None, bias_name='<BIAS>', feature_names=None,
                      num_features=None, estimator_feature_names=None):
    # type: (Any, Any, Optional[str], Any, int, Any) -> FeatureNames
    
    if not has_intercept(clf):
        bias_name = None

    if feature_names is None:
        if vec and hasattr(vec, 'get_feature_names'):
            return FeatureNames(vec.get_feature_names(), bias_name=bias_name)
        else:
            if estimator_feature_names is None:
                num_features = num_features or get_num_features(clf)
                return FeatureNames(
                    n_features=num_features,
                    unkn_template='x%d',
                    bias_name=bias_name
                )
            return FeatureNames(estimator_feature_names, bias_name=bias_name)

    num_features = num_features or get_num_features(clf)
    if isinstance(feature_names, FeatureNames):
        if feature_names.n_features != num_features:
            raise ValueError("feature_names has a wrong n_features: "
                             "expected=%d, got=%d" % (num_features,
                                                      feature_names.n_features))
        # Make a shallow copy setting proper bias_name
        return FeatureNames(
            feature_names.feature_names,
            n_features=num_features,
            bias_name=bias_name,
            unkn_template=feature_names.unkn_template)
    else:
        if len(feature_names) != num_features:
            raise ValueError("feature_names has a wrong length: "
                             "expected=%d, got=%d" % (num_features,
                                                      len(feature_names)))
        return FeatureNames(feature_names, bias_name=bias_name)
823964
def explain_features():
    '''
    '''
    from ape import tasks
    import featuremonkey
    import os

    featurenames = featuremonkey.get_features_from_equation_file(os.environ['PRODUCT_EQUATION_FILENAME'])

    for featurename in featurenames:
        tasks.explain_feature(featurename)
1339022
def _all_feature_names(name):
    # type: (Union[str, bytes, List[Dict]]) -> List[str]
    
    if isinstance(name, bytes):
        return [name.decode('utf8')]
    elif isinstance(name, list):
        return [x['name'] for x in name]
    else:
        return [name]
100472
def parse_original_feature_from_example(example, feature_name):
  
  feature = get_example_features(example)[feature_name]
  feature_type = feature.WhichOneof('kind')
  original_value = proto_value_for_feature(example, feature_name)

  return OriginalFeatureList(feature_name, original_value, feature_type)
1089346
def getFeatureByIndex(self, index):
        
        feature = self.layer[index]
        if feature is None:
            feature = self.getfeatures()[index]
        return feature
1005798
def getFeatureById(self, featureId):
        
        sql = "SELECT * FROM FEATURE WHERE id = ?"
        query = self._dbconn.execute(sql, (featureId,))
        ret = query.fetchone()
        if ret is None:
            return None
        return sqlite_backend.sqliteRowToDict(ret)
1059030
def get_eval_func(obj, feature, slice=np.s_[...]):
    
    if feature is not None:
        # kernel + feature combination
        if not isinstance(feature, InducingFeature) or not isinstance(obj, kernels.Kernel):
            raise TypeError("If `feature` is supplied, `obj` must be a kernel.")
        return lambda x: tf.transpose(Kuf(feature, obj, x))[slice]
    elif isinstance(obj, mean_functions.MeanFunction):
        return lambda x: obj(x)[slice]
    elif isinstance(obj, kernels.Kernel):
        return lambda x: obj.Kdiag(x)
    else:
        raise NotImplementedError()
392401
def extract(cls, extractor, typ):
        
        schema = {
            "title": typ.__name__,
            "type": "object",
            "properties": {},
            "required": []
        }
        for attribute in attr.fields(typ):
            details = cls._extract_attribute(extractor, attribute)
            if details.is_required:
                schema["required"].append(details.name)
            schema["properties"][details.name] = details.schema
        return schema
502816
def _extract_mod_from_feature(mf):
        """"""
        # ModificationFeature / SequenceModificationVocabulary
        mf_type = mf.getModificationType()
        if mf_type is None:
            return None
        mf_type_terms = mf_type.getTerm().toArray()
        known_mf_type = None
        for t in mf_type_terms:
            if t.startswith('MOD_RES '):
                t = t[8:]
            mf_type_indra = _mftype_dict.get(t)
            if mf_type_indra is not None:
                known_mf_type = mf_type_indra
                break
        if not known_mf_type:
            logger.debug('Skipping modification with unknown terms: %s' %
                        ', '.join(mf_type_terms))
            return None

        mod_type, residue = known_mf_type

        # getFeatureLocation returns SequenceLocation, which is the
        # generic parent class of SequenceSite and SequenceInterval.
        # Here we need to cast to SequenceSite in order to get to
        # the sequence position.
        mf_pos = mf.getFeatureLocation()
        if mf_pos is not None:
            # If it is not a SequenceSite we can't handle it
            if not mf_pos.modelInterface.getName() == \
                'org.biopax.paxtools.model.level3.SequenceSite':
                mod_pos = None
            else:
                mf_site = cast(_bp('SequenceSite'), mf_pos)
                mf_pos_status = mf_site.getPositionStatus()
                if mf_pos_status is None:
                    mod_pos = None
                elif mf_pos_status and mf_pos_status.toString() != 'EQUAL':
                    logger.debug('Modification site position is %s' %
                                mf_pos_status.toString())
                else:
                    mod_pos = mf_site.getSequencePosition()
                    mod_pos = '%s' % mod_pos
        else:
            mod_pos = None
        mc = ModCondition(mod_type, residue, mod_pos, True)
        return mc
433019
def extract_features(self, text):
        
        # Feature extractor may take one or two arguments
        try:
            return self.feature_extractor(text, self.train_set)
        except (TypeError, AttributeError):
            return self.feature_extractor(text)