def vector(feature_key2idsfuncs, example, event_sequence,
           always_keys=set()):
    """
    Create a feature vector by applying the given feature functions to
    the given example and event sequence and return it.

    Runs quickly by applying only those feature functions whose keys
    match the fact keys or event types of the event sequence.

    Creates a sparse feature vector by storing only those feature values
    that evaluate to `True`.

    feature_key2idsfuncs:
        Mapping of feature keys to lists of (feature-ID,
        feature-function) pairs as created by `map_to_functions`.
    example:
        Example record.  Only needed if feature functions will access
        it.
    event_sequence: esal.EventSequence
        Only needed if feature functions will access it.
    always_keys:
        Set of keys whose feature functions should always be applied.
        Useful for computing features whose keys do not appear in the
        facts or events of the event sequence, such as features of the
        example.
    """
    # Sparse mapping of feature IDs to values
    fv = {}
    # Use each fact and event key to look up the corresponding feature
    for key in (event_sequence.fact_keys() |
                event_sequence.types() | always_keys):
        ids_funcs = feature_key2idsfuncs.get(key)
        if ids_funcs is not None:
            for feat_id, feat_func in ids_funcs:
                value = feat_func(example, event_sequence)
                if value:
                    fv[feat_id] = value
    return fv