def get_intermediate_entities(kb, topic_ent, chain):
  """Get all tail entities of a topic entity following a chain of relations.

  Args:
    kb: dictionary to store the KB {subject: {relation: objects}}
    topic_ent: topic entity to start with
    chain: a list of relations to follow

  Returns:
    a set of tail entities
  """
  cur_ents = set([topic_ent])
  intermediate_entities = [cur_ents]
  for rel in chain:
    next_ents = set()
    for ent in cur_ents:
      if ent in kb and rel in kb[ent]:
        objs = kb[ent][rel]
        next_ents.update(objs)
    next_ents.discard(topic_ent)
    cur_ents = next_ents
    intermediate_entities.append(cur_ents)

  return intermediate_entities
Get all tail entities of a topic entity following a chain of relations.

  Args:
    kb: dictionary to store the KB {subject: {relation: objects}}
    topic_ent: topic entity to start with
    chain: a list of relations to follow

  Returns:
    a set of tail entities
  
language/emql/preprocess/metaqa_preprocess.py