code: def query_topn(
      model,
      top_n=10,
      head=None,
      relation=None,
      tail=None,
      ents_to_consider=None,
      rels_to_consider=None,
  ):
      """Queries the model with two elements of a triple and returns the top_n results of
      all possible completions ordered by score predicted by the model.
  
      For example, given a `<subject, predicate>` pair in the arguments, the model will score
      all possible triples `<subject, predicate, ?>`, filling in the missing element with known
      entities, and return the top_n triples ordered by score. If given a `<subject, object>`
      pair it will fill in the missing element with known relations.
  
      Therefore, if we feed the funcion with `<subject, predicate>` or `<predicate, object>`, it
      solves the link prediction task.
  
      .. note::
          This function does not filter out true statements - triples returned can include those
          the model was trained on.
  
      Parameters
      ----------
      model : ScoringBasedEmbeddingModel
          The trained model that will be used to score triple completions.
      top_n : int
          The number of completed triples to returned.
      head : str
          An entity string to query.
      relation : str
          A relation string to query.
      tail : str
          An object string to query.
      ents_to_consider: array-like
          List of entities to use for triple completions. If `None`, will generate completions
          using all distinct entities (default: `None`).
      rels_to_consider: array-like
          List of relations to use for triple completions. If `None`, will generate completions
          using all distinct relations (default: `None`).
  
      Returns
      -------
      X : ndarray of shape (n, 3)
          A list of triples ordered by score.
      S : ndarray, shape (n)
         A list of scores.
  
      Example
      -------
  
      >>> import requests
      >>> from ampligraph.datasets import load_from_csv
      >>> from ampligraph.discovery import discover_facts
      >>> from ampligraph.discovery import query_topn
      >>> from ampligraph.latent_features import ScoringBasedEmbeddingModel
      >>> # Game of Thrones relations dataset
      >>> url = 'https://ampligraph.s3-eu-west-1.amazonaws.com/datasets/GoT.csv'
      >>> open('GoT.csv', 'wb').write(requests.get(url).content)
      >>> X = load_from_csv('.', 'GoT.csv', sep=',')
      >>>
      >>> model = ScoringBasedEmbeddingModel(eta=5,
      >>>                                    k=150,
      >>>                                    scoring_type='TransE')
      >>> model.compile(optimizer='adagrad', loss='pairwise')
      >>> model.fit(X,
      >>>           batch_size=100,
      >>>           epochs=20,
      >>>           verbose=False)
      >>>
      >>> query_topn(model, top_n=5,
      >>>            head='Eddard Stark', relation='ALLIED_WITH', tail=None,
      >>>            ents_to_consider=None, rels_to_consider=None)
      >>>
      (array([['Eddard Stark', 'ALLIED_WITH', 'Smithyton'],
              ['Eddard Stark', 'ALLIED_WITH', 'Eden Risley'],
              ['Eddard Stark', 'ALLIED_WITH', 'House Westbrook'],
              ['Eddard Stark', 'ALLIED_WITH', 'House Leygood'],
              ['Eddard Stark', 'ALLIED_WITH', 'House Bridges']], dtype='<U44'),
       array([9.000417 , 5.272001 , 5.1876183, 5.121145 , 5.0564814],
             dtype=float32))
  
      """
  
      if model.is_backward:
          model = model.model
  
      if not model.is_fitted:
          msg = "Model is not fitted."
          logger.error(msg)
          raise ValueError(msg)
  
      if (
          not np.sum([head is None, relation is None, tail is None])
          == 1
      ):
          msg = "Exactly one of `head`, `relation` or `tail` arguments must be None."
          logger.error(msg)
          raise ValueError(msg)
  
      if head:
          if head not in list(
              model.data_indexer.backend.get_all_entities()
          ):
              msg = "Head entity `{}` not seen by model".format(head)
              logger.error(msg)
              raise ValueError(msg)
  
      if relation:
          if relation not in list(
              model.data_indexer.backend.get_all_relations()
          ):
              msg = "Relation `{}` not seen by model".format(relation)
              logger.error(msg)
              raise ValueError(msg)
  
      if tail:
          if tail not in list(
              model.data_indexer.backend.get_all_entities()
          ):
              msg = "Tail entity `{}` not seen by model".format(tail)
              logger.error(msg)
              raise ValueError(msg)
  
      if ents_to_consider is not None:
          if head and tail:
              msg = "Cannot specify `ents_to_consider` and both `subject` and `object` arguments."
              logger.error(msg)
              raise ValueError(msg)
          if not isinstance(ents_to_consider, (list, np.ndarray)):
              msg = "`ents_to_consider` must be a list or numpy array."
              logger.error(msg)
              raise ValueError(msg)
          if not all(
              x in list(model.data_indexer.backend.get_all_entities())
              for x in ents_to_consider
          ):
              msg = "Entities in `ents_to_consider` have not been seen by the model."
              logger.error(msg)
              raise ValueError(msg)
          if len(ents_to_consider) < top_n:
              msg = "`ents_to_consider` contains less than top_n values, return set will be truncated."
              logger.warning(msg)
  
      if rels_to_consider is not None:
          if relation:
              msg = "Cannot specify both `rels_to_consider` and `relation` arguments."
              logger.error(msg)
              raise ValueError(msg)
          if not isinstance(rels_to_consider, (list, np.ndarray)):
              msg = "`rels_to_consider` must be a list or numpy array."
              logger.error(msg)
              raise ValueError(msg)
          if not all(
              x in list(model.data_indexer.backend.get_all_relations())
              for x in rels_to_consider
          ):
              msg = "Relations in `rels_to_consider` have not been seen by the model."
              logger.error(msg)
              raise ValueError(msg)
          if len(rels_to_consider) < top_n:
              msg = "`rels_to_consider` contains less than top_n values, return set will be truncated."
              logger.warning(msg)
  
      # Complete triples from entity and relation dict
      if relation is None:
          rels = rels_to_consider or list(
              model.data_indexer.backend.get_all_relations()
          )
          triples = np.array([[head, x, tail] for x in rels])
      else:
          ents = ents_to_consider or list(
              model.data_indexer.backend.get_all_entities()
          )
          if head:
              triples = np.array([[head, relation, x] for x in ents])
          else:
              triples = np.array([[x, relation, tail] for x in ents])
  
      # Get scores for completed triples
      scores = model.predict(triples)
  
      # Join triples and scores, sort ascending by scores, then take top_n
      # results
      topn_idx = np.squeeze(np.argsort(scores, axis=0)[::-1][:top_n])
      scores_out = np.array(scores)[topn_idx]
      triples_out = np.copy(triples[topn_idx, :])
  
      return triples_out, scores_out
  
file_path: AmpliGraph/ampligraph/discovery/discovery.py
imports: import logging
  import networkx
  import numpy
  from scipy import optimize, spatial
  from sklearn.cluster import DBSCAN
  from sklearn.neighbors import NearestNeighbors
label_desc: Use image node_id 6 for calling a global function with example usage: query_topn(model, top_n, head, relation, tail, ents_to_consider, rels_to_consider) and returns: triples_out,  scores_out