Completed
Push — master ( 643512...2b6b3e )
by Chris
20:40 queued 10:36
created

abydos.distance._pearson_chi_squared   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 245
Duplicated Lines 20 %

Test Coverage

Coverage 97.3%

Importance

Changes 0
Metric Value
wmc 9
eloc 53
dl 49
loc 245
ccs 36
cts 37
cp 0.973
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A PearsonChiSquared.__init__() 0 46 1
A PearsonChiSquared.sim() 0 32 1
A PearsonChiSquared.corr() 0 44 2
A PearsonChiSquared.sim_score() 49 49 5

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
# -*- coding: utf-8 -*-
2
3
# Copyright 2018-2019 by Christopher C. Little.
4
# This file is part of Abydos.
5
#
6
# Abydos is free software: you can redistribute it and/or modify
7
# it under the terms of the GNU General Public License as published by
8
# the Free Software Foundation, either version 3 of the License, or
9
# (at your option) any later version.
10
#
11
# Abydos is distributed in the hope that it will be useful,
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
# GNU General Public License for more details.
15
#
16
# You should have received a copy of the GNU General Public License
17
# along with Abydos. If not, see <http://www.gnu.org/licenses/>.
18
19 1
"""abydos.distance._pearson_chi_squared.
20
21
Pearson's Chi-Squared similarity
22
"""
23
24 1
from __future__ import (
25
    absolute_import,
26
    division,
27
    print_function,
28
    unicode_literals,
29
)
30
31 1
from math import copysign
32
33 1
from ._token_distance import _TokenDistance
34
35 1
__all__ = ['PearsonChiSquared']
36
37
38 1
class PearsonChiSquared(_TokenDistance):
39
    r"""Pearson's Chi-Squared similarity.
40
41
    For two sets X and Y and a population N, the Pearson's :math:`\chi^2`
42
    similarity :cite:`Pearson:1913` is
43
44
        .. math::
45
46
            sim_{PearsonChiSquared}(X, Y) =
47
            \frac{|N| \cdot (|X \cap Y| \cdot |(N \setminus X) \setminus Y| -
48
            |X \setminus Y| \cdot |Y \setminus X|)^2}
49
            {|X| \cdot |Y| \cdot |N \setminus X| \cdot |N \setminus Y|}
50
51
    This is also Pearson I similarity.
52
53
    In :ref:`2x2 confusion table terms <confusion_table>`, where a+b+c+d=n,
54
    this is
55
56
        .. math::
57
58
            sim_{PearsonChiSquared} =
59
            \frac{n(ad-bc)^2}{(a+b)(a+c)(b+d)(c+d)}
60
61
    .. versionadded:: 0.4.0
62
    """
63
64 1
    def __init__(
65
        self,
66
        alphabet=None,
67
        tokenizer=None,
68
        intersection_type='crisp',
69
        **kwargs
70
    ):
71
        """Initialize PearsonChiSquared instance.
72
73
        Parameters
74
        ----------
75
        alphabet : Counter, collection, int, or None
76
            This represents the alphabet of possible tokens.
77
            See :ref:`alphabet <alphabet>` description in
78
            :py:class:`_TokenDistance` for details.
79
        tokenizer : _Tokenizer
80
            A tokenizer instance from the :py:mod:`abydos.tokenizer` package
81
        intersection_type : str
82
            Specifies the intersection type, and set type as a result:
83
            See :ref:`intersection_type <intersection_type>` description in
84
            :py:class:`_TokenDistance` for details.
85
        **kwargs
86
            Arbitrary keyword arguments
87
88
        Other Parameters
89
        ----------------
90
        qval : int
91
            The length of each q-gram. Using this parameter and tokenizer=None
92
            will cause the instance to use the QGram tokenizer with this
93
            q value.
94
        metric : _Distance
95
            A string distance measure class for use in the ``soft`` and
96
            ``fuzzy`` variants.
97
        threshold : float
98
            A threshold value, similarities above which are counted as
99
            members of the intersection for the ``fuzzy`` variant.
100
101
102
        .. versionadded:: 0.4.0
103
104
        """
105 1
        super(PearsonChiSquared, self).__init__(
106
            alphabet=alphabet,
107
            tokenizer=tokenizer,
108
            intersection_type=intersection_type,
109
            **kwargs
110
        )
111
112 1 View Code Duplication
    def sim_score(self, src, tar):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
113
        """Return Pearson's Chi-Squared similarity of two strings.
114
115
        Parameters
116
        ----------
117
        src : str
118
            Source string (or QGrams/Counter objects) for comparison
119
        tar : str
120
            Target string (or QGrams/Counter objects) for comparison
121
122
        Returns
123
        -------
124
        float
125
            Pearson's Chi-Squared similarity
126
127
        Examples
128
        --------
129
        >>> cmp = PearsonChiSquared()
130
        >>> cmp.sim_score('cat', 'hat')
131
        193.99489809335964
132
        >>> cmp.sim_score('Niall', 'Neil')
133
        101.99771068526542
134
        >>> cmp.sim_score('aluminum', 'Catalan')
135
        9.19249664336649
136
        >>> cmp.sim_score('ATCG', 'TAGC')
137
        0.032298410951138765
138
139
140
        .. versionadded:: 0.4.0
141
142
        """
143 1
        self._tokenize(src, tar)
144
145 1
        a = self._intersection_card()
146 1
        b = self._src_only_card()
147 1
        c = self._tar_only_card()
148 1
        d = self._total_complement_card()
149 1
        n = self._population_unique_card()
150 1
        ab = self._src_card()
151 1
        ac = self._tar_card()
152
153 1
        if src == tar:
154 1
            return float(n)
155 1
        if not src or not tar:
156 1
            return 0.0
157 1
        num = n * (a * d - b * c) ** 2
158 1
        if num:
159 1
            return num / (ab * ac * (b + d) * (c + d))
160
        return 0.0
161
162 1
    def corr(self, src, tar):
163
        """Return Pearson's Chi-Squared correlation of two strings.
164
165
        Parameters
166
        ----------
167
        src : str
168
            Source string (or QGrams/Counter objects) for comparison
169
        tar : str
170
            Target string (or QGrams/Counter objects) for comparison
171
172
        Returns
173
        -------
174
        float
175
            Pearson's Chi-Squared correlation
176
177
        Examples
178
        --------
179
        >>> cmp = PearsonChiSquared()
180
        >>> cmp.corr('cat', 'hat')
181
        0.2474424720578567
182
        >>> cmp.corr('Niall', 'Neil')
183
        0.1300991207720222
184
        >>> cmp.corr('aluminum', 'Catalan')
185
        0.011710186806836291
186
        >>> cmp.corr('ATCG', 'TAGC')
187
        -4.1196952743799446e-05
188
189
190
        .. versionadded:: 0.4.0
191
192
        """
193 1
        if src == tar:
194 1
            return 1.0
195
196 1
        score = self.sim_score(src, tar)
197
198 1
        a = self._intersection_card()
199 1
        b = self._src_only_card()
200 1
        c = self._tar_only_card()
201 1
        d = self._total_complement_card()
202
203 1
        score /= a + b + c + d
204
205 1
        return copysign(score, a * d - b * c)
206
207 1
    def sim(self, src, tar):
208
        """Return Pearson's normalized Chi-Squared similarity of two strings.
209
210
        Parameters
211
        ----------
212
        src : str
213
            Source string (or QGrams/Counter objects) for comparison
214
        tar : str
215
            Target string (or QGrams/Counter objects) for comparison
216
217
        Returns
218
        -------
219
        float
220
            Normalized Pearson's Chi-Squared similarity
221
222
        Examples
223
        --------
224
        >>> cmp = PearsonChiSquared()
225
        >>> cmp.corr('cat', 'hat')
226
        0.2474424720578567
227
        >>> cmp.corr('Niall', 'Neil')
228
        0.1300991207720222
229
        >>> cmp.corr('aluminum', 'Catalan')
230
        0.011710186806836291
231
        >>> cmp.corr('ATCG', 'TAGC')
232
        -4.1196952743799446e-05
233
234
235
        .. versionadded:: 0.4.0
236
237
        """
238 1
        return (1.0 + self.corr(src, tar)) / 2.0
239
240
241
if __name__ == '__main__':
242
    import doctest
243
244
    doctest.testmod()
245