Returns similarity scores by information content.

    :param sense1: A synset.
    :param sense2: A synset.
    :param option: String, one of ('res', 'jcn', 'lin').
    :return: A float, similarity measurement.
512699
def similarity_by_infocontent(sense1: "wn.Synset", sense2: "wn.Synset", option: str) -> float:
    

    if sense1.pos != sense2.pos: # infocontent sim can't do diff POS.
        return 0

    if option in ['res', 'resnik']:
        if sense1.pos not in wnic_bnc_resnik_add1.ic:
            return 0
        return wn.res_similarity(sense1, sense2, wnic_bnc_resnik_add1)
    #return min(wn.res_similarity(sense1, sense2, wnic.ic(ic)) \
    #             for ic in info_contents)

    elif option in ['jcn', "jiang-conrath"]:
        if sense1.pos not in wnic_bnc_add1.ic:
            return 0
        return wn.jcn_similarity(sense1, sense2, wnic_bnc_add1)

    elif option in ['lin']:
        if sense1.pos not in wnic_bnc_add1.ic:
            return 0
        return wn.lin_similarity(sense1, sense2, wnic_bnc_add1)
145071
def similarity(self, other):
        """"""
        # Select the longer list as the basis for comparison
        if len(self.items) > len(other.items):
            first, second = self, other
        else:
            first, second = other, self
        items = list(first.items)  # backup items list
        length = len(items)
        sim = self.Similarity(0.0 if length else 1.0)

        # Calculate the similarity for each permutation of items
        cname = self.__class__.__name__

        for num, perm in enumerate(permutations(items, length), start=1):
            first.items = perm
            aname = 'items-p{}'.format(num)
            self.log(first, second, '%', cname=cname, aname=aname)
            permutation_sim = super(Group, first).similarity(second)
            self.log(first, second, '%', cname=cname, aname=aname,
                     result=permutation_sim)

            sim = max(sim, permutation_sim)
            logging.debug("highest similarity: %s", sim)

        first.items = items  # restore original items list

        return sim
202332
def _comparable(self):
        
        return self._replace(
            name='' if self.name is None else self.name,
            wavelength=tuple() if self.wavelength is None else self.wavelength,
            resolution=0 if self.resolution is None else self.resolution,
            polarization='' if self.polarization is None else self.polarization,
            calibration='' if self.calibration is None else self.calibration,
        )
660516
def score_xrefs_by_semsim(self, xg, ont=None):
        
        logging.info("scoring xrefs by semantic similarity for {} nodes in {}".format(len(xg.nodes()), ont))
        for (i,j,d) in xg.edges(data=True):
            pfx1 = self._id_to_ontology(i)
            pfx2 = self._id_to_ontology(j)
            ancs1 = self._blanket(i)
            ancs2 = self._blanket(j)
            s1,_,_ = self._sim(xg, ancs1, ancs2, pfx1, pfx2)
            s2,_,_ = self._sim(xg, ancs2, ancs1, pfx2, pfx1)
            s = 1 - ((1-s1) * (1-s2))
            logging.debug("Score {} x {} = {} x {} = {} // {}".format(i,j,s1,s2,s, d))
            xg[i][j][self.SIMSCORES] = (s1,s2)
            xg[i][j][self.SCORE] *= s
970374
public static float compare(final int numOfBits, final String str1,
            final String str2) {
        return compare(numOfBits, BaseEncoding.base64().decode(str1),
                BaseEncoding.base64().decode(str2));
    }
932682
def Similarity(self, value=None):  # pylint: disable=C0103
        """"""
        if value is None:
            value = 0.0
        return Similarity(value, threshold=self.threshold)
391973
def semantic_similarity(go_id1, go_id2, godag, branch_dist=None):
    '''
        
    '''
    dist = semantic_distance(go_id1, go_id2, godag, branch_dist)
    if dist is not None:
        return 1.0 / float(dist)
373596
def semcor_to_offset(sensekey):
    

    synset = wn.lemma_from_key(sensekey).synset
    offset = '%08d-%s' % (synset.offset, synset.pos)
    return offset
544488
def _best_match_syn(self, sx, sys, scope_map):
        
        SUBSTRING_WEIGHT = 0.2
        WBEST = None
        sbest = None
        sxv = self._standardize_label(sx.val)
        sxp = self._id_to_ontology(sx.class_id)
        for sy in sys:
            syv = self._standardize_label(sy.val)
            syp = self._id_to_ontology(sy.class_id)
            W = None
            if sxv == syv:
                confidence = sx.confidence * sy.confidence
                if sx.is_abbreviation() or sy.is_abbreviation:
                    confidence *= self._get_config_val(sxp, 'abbreviation_confidence', 0.5)
                    confidence *= self._get_config_val(syp, 'abbreviation_confidence', 0.5)
                W = scope_map[sx.scope()][sy.scope()] + logit(confidence/2)
            elif sxv in syv:
                W = np.array((-SUBSTRING_WEIGHT, SUBSTRING_WEIGHT, 0, 0))
            elif syv in sxv:
                W = np.array((SUBSTRING_WEIGHT, -SUBSTRING_WEIGHT, 0, 0))
            if W is not None:
                # 
                if WBEST is None or max(abs(W)) > max(abs(WBEST)):
                    WBEST = W
                    sbest = sy
        return WBEST, sbest
714485
def jaccard_similarity(self,s1,s2):
        
        a1 = self.inferred_types(s1)
        a2 = self.inferred_types(s2)
        num_union = len(a1.union(a2))
        if num_union == 0:
            return 0.0
        return len(a1.intersection(a2)) / num_union
697952
def retrieve_with_score(self, s):
        
        all_sim = []
        use_max_n = self.max_n is not None
        for comparison_string in self._get_comparison_strings(s):
            score = self.comparison_func(s, comparison_string)
            if score >= self.cutoff:
                all_sim.append((comparison_string, score))
                if use_max_n and len(all_sim) >= self.max_n:
                    return all_sim
        return all_sim
651891
def zset_score_pairs(response, **options):
    
    if not response or not options.get('withscores'):
        return response
    score_cast_func = options.get('score_cast_func', float)
    it = iter(response)
    return list(izip(it, imap(score_cast_func, it)))
639494
public Pair<List<SuggestedReplacement>, SortedMap<String, Float>> computeFeatures(List<String> suggestions, String word, AnalyzedSentence sentence, int startPos) {
    if (suggestions.isEmpty()) {
      return Pair.of(Collections.emptyList(), Collections.emptySortedMap());
    }
    if (topN <= 0) {
      topN = suggestions.size();
    }
    List<String> topSuggestions = suggestions.subList(0, Math.min(suggestions.size(), topN));
    //EditDistance<Integer> levenshteinDistance = new LevenshteinDistance(4);
    EditDistance levenstheinDistance = new EditDistance(word, EditDistance.DistanceAlgorithm.Damerau);
    SimilarityScore<Double> jaroWrinklerDistance = new JaroWinklerDistance();
    List<Feature> features = new ArrayList<>(topSuggestions.size());

    for (String candidate : topSuggestions) {
      double prob1 = languageModel.getPseudoProbability(Collections.singletonList(candidate)).getProb();
      double prob3 = LanguageModelUtils.get3gramProbabilityFor(language, languageModel, startPos, sentence, candidate);
      //double prob4 = LanguageModelUtils.get4gramProbabilityFor(language, languageModel, startPos, sentence, candidate);
      long wordCount = ((BaseLanguageModel) languageModel).getCount(candidate);
      int levenstheinDist = levenstheinDistance.compare(candidate, 3);
      double jaroWrinklerDist = jaroWrinklerDistance.apply(word, candidate);
      DetailedDamerauLevenstheinDistance.Distance detailedDistance = DetailedDamerauLevenstheinDistance.compare(word, candidate);

      features.add(new Feature(prob1, prob3, wordCount, levenstheinDist, detailedDistance, jaroWrinklerDist, candidate));
    }
    if (!"noop".equals(score)) {
      features.sort(Feature::compareTo);
    }
    //logger.trace("Features for '%s' in '%s': %n", word, sentence.getText());
    //features.stream().map(Feature::toString).forEach(logger::trace);
    List<String> words = features.stream().map(Feature::getWord).collect(Collectors.toList());

    // compute general features, not tied to candidates
    SortedMap<String, Float> matchData = new TreeMap<>();
    matchData.put("candidateCount", (float) words.size());

    List<SuggestedReplacement> suggestionsData = features.stream().map(f -> {
      SuggestedReplacement s = new SuggestedReplacement(f.getWord());
      s.setFeatures(f.getData());
      return s;
    }).collect(Collectors.toList());
    return Pair.of(suggestionsData, matchData);
  }
640727
def similarity(word1: str, word2: str) -> float:
    
    return _MODEL.similarity(word1, word2)
644437
def similarity(other)
      overlap = (wordset & other.wordset).size
      total = wordset.size + other.wordset.size
      100.0 * (overlap * 2.0 / total)
    end
889064
def senses(self, bestonly=False):
        """"""
        l = []
        for word_id, senses,distance in self:
            for sense, confidence in senses:
                if not sense in l: l.append(sense)
                if bestonly:
                    break
        return l
656956
def evaluate_similarity(args, token_embedding, ctx, logfile=None,
                        global_step=0):
    """"""

    results = []
    for similarity_function in args.similarity_functions:
        evaluator = nlp.embedding.evaluation.WordEmbeddingSimilarity(
            idx_to_vec=token_embedding.idx_to_vec,
            similarity_function=similarity_function)
        evaluator.initialize(ctx=ctx)
        if not args.no_hybridize:
            evaluator.hybridize()

        # Evaluate all datasets
        for (dataset_name, dataset_kwargs,
             dataset) in iterate_similarity_datasets(args):
            initial_length = len(dataset)
            dataset_coded = [[
                token_embedding.token_to_idx[d[0]],
                token_embedding.token_to_idx[d[1]], d[2]
            ] for d in dataset if d[0] in token_embedding.token_to_idx
                             and d[1] in token_embedding.token_to_idx]
            num_dropped = initial_length - len(dataset_coded)

            # All words are unknown
            if not len(dataset_coded):
                correlation = 0
            else:
                words1, words2, scores = zip(*dataset_coded)
                pred_similarity = evaluator(
                    mx.nd.array(words1, ctx=ctx), mx.nd.array(words2, ctx=ctx))
                sr = stats.spearmanr(pred_similarity.asnumpy(),
                                     np.array(scores))
                correlation = sr.correlation

            logging.info(
                'Spearman rank correlation on %s (%s pairs) %s with %s:\t%s',
                dataset.__class__.__name__, len(dataset_coded),
                str(dataset_kwargs), similarity_function, correlation)

            result = dict(
                task='similarity',
                dataset_name=dataset_name,
                dataset_kwargs=dataset_kwargs,
                similarity_function=similarity_function,
                spearmanr=correlation,
                num_dropped=num_dropped,
                global_step=global_step,
            )
            log_similarity_result(logfile, result)
            results.append(result)

    return results