Passed
Push — dependabot/pip/sphinx-copybutt... ( c72176...cfd31d )
by
unknown
07:42 queued 05:46
created

ConcordanceCalculation.create()   A

Complexity

Conditions 1

Size

Total Lines 12
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 11
nop 6
dl 0
loc 12
rs 9.85
c 0
b 0
f 0
1
"""
2
Calculations of concordance between annotations.
3
"""
4
import abc
5
import enum
6
import math
7
from typing import Collection, Dict, Generator, Sequence, Set, Tuple, Union
0 ignored issues
show
Unused Code introduced by
Unused Collection imported from typing
Loading history...
Unused Code introduced by
Unused Set imported from typing
Loading history...
Unused Code introduced by
Unused Dict imported from typing
Loading history...
Unused Code introduced by
Unused Tuple imported from typing
Loading history...
8
9
import numpy as np
0 ignored issues
show
introduced by
Unable to import 'numpy'
Loading history...
10
import pandas as pd
0 ignored issues
show
introduced by
Unable to import 'pandas'
Loading history...
11
from typeddfs import TypedDfs
0 ignored issues
show
introduced by
Unable to import 'typeddfs'
Loading history...
12
13
from mandos.analysis import AnalysisUtils, SimilarityDf
0 ignored issues
show
Unused Code introduced by
Unused AnalysisUtils imported from mandos.analysis
Loading history...
14
from mandos.model import CleverEnum
15
16
ConcordanceDf = (
17
    TypedDfs.typed("ConcordanceDf")
18
    .require("phi", "psi", dtype=str)
19
    .require("sample", dtype=int)
20
    .require("score", dtype=float)
21
).build()
22
23
24
class ConcordanceCalculator(metaclass=abc.ABCMeta):
0 ignored issues
show
introduced by
Missing class docstring
Loading history...
25
    def __init__(self, n_samples: int, seed: int, phi_name: str, psi_name: str):
26
        self.n_samples = n_samples
27
        self.seed = seed
28
        self.rand = np.random.RandomState(seed)
29
        self.phi_name = phi_name
30
        self.psi_name = psi_name
31
32
    def calc(self, phi: SimilarityDf, psi: SimilarityDf) -> ConcordanceDf:
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
33
        if phi.columns.tolist() != psi.columns.tolist():
34
            raise ValueError(
35
                f"Mismatched compounds: {phi.columns.tolist()} != {psi.columns.tolist()}"
36
            )
37
        df = pd.DataFrame(data=self.generate(phi, psi), columns=["score"])
0 ignored issues
show
Coding Style Naming introduced by
Variable name "df" doesn't conform to snake_case naming style ('([^\\W\\dA-Z][^\\WA-Z]2,|_[^\\WA-Z]*|__[^\\WA-Z\\d_][^\\WA-Z]+__)$' pattern)

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
38
        df = df.reset_index()
0 ignored issues
show
Coding Style Naming introduced by
Variable name "df" doesn't conform to snake_case naming style ('([^\\W\\dA-Z][^\\WA-Z]2,|_[^\\WA-Z]*|__[^\\WA-Z\\d_][^\\WA-Z]+__)$' pattern)

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
39
        df["phi"] = self.phi_name
40
        df["psi"] = self.psi_name
41
        df.columns = ["sample", "score", "phi", "psi"]
42
        return ConcordanceDf(df)
43
44
    def generate(self, phi: SimilarityDf, psi: SimilarityDf) -> Generator[float, None, None]:
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
45
        for b in range(self.n_samples):
0 ignored issues
show
Coding Style Naming introduced by
Variable name "b" doesn't conform to snake_case naming style ('([^\\W\\dA-Z][^\\WA-Z]2,|_[^\\WA-Z]*|__[^\\WA-Z\\d_][^\\WA-Z]+__)$' pattern)

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
Unused Code introduced by
The variable b seems to be unused.
Loading history...
46
            phi_b = self.rand.choice(phi, replace=True)
47
            psi_b = self.rand.choice(psi, replace=True)
48
            yield self._calc(phi_b, psi_b)
49
50
    def _calc(self, phi: SimilarityDf, psi: SimilarityDf) -> float:
0 ignored issues
show
Coding Style introduced by
This method could be written as a function/class method.

If a method does not access any attributes of the class, it could also be implemented as a function or static method. This can help improve readability. For example

class Foo:
    def some_method(self, x, y):
        return x + y;

could be written as

class Foo:
    @classmethod
    def some_method(cls, x, y):
        return x + y;
Loading history...
51
        raise NotImplemented()
0 ignored issues
show
Bug introduced by
NotImplemented does not seem to be callable.
Loading history...
Best Practice introduced by
NotImplemented raised - should raise NotImplementedError
Loading history...
52
53
54
class TauConcordanceCalculator(ConcordanceCalculator):
0 ignored issues
show
introduced by
Missing class docstring
Loading history...
55
    def _calc(self, phi: SimilarityDf, psi: SimilarityDf) -> float:
56
        n = len(phi)
0 ignored issues
show
Coding Style Naming introduced by
Variable name "n" doesn't conform to snake_case naming style ('([^\\W\\dA-Z][^\\WA-Z]2,|_[^\\WA-Z]*|__[^\\WA-Z\\d_][^\\WA-Z]+__)$' pattern)

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
57
        numerator = self._n_z(phi, psi, 1) - self._n_z(phi, psi, -1)
58
        denominator = math.factorial(n) / (2 * math.factorial(n - 2))
59
        return numerator / denominator
60
61
    def _n_z(self, a: Sequence[float], b: Sequence[float], z: int) -> int:
0 ignored issues
show
Coding Style Naming introduced by
Argument name "z" doesn't conform to snake_case naming style ('([^\\W\\dA-Z][^\\WA-Z]2,|_[^\\WA-Z]*|__[^\\WA-Z\\d_][^\\WA-Z]+__)$' pattern)

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
Coding Style Naming introduced by
Argument name "b" doesn't conform to snake_case naming style ('([^\\W\\dA-Z][^\\WA-Z]2,|_[^\\WA-Z]*|__[^\\WA-Z\\d_][^\\WA-Z]+__)$' pattern)

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
Coding Style Naming introduced by
Argument name "a" doesn't conform to snake_case naming style ('([^\\W\\dA-Z][^\\WA-Z]2,|_[^\\WA-Z]*|__[^\\WA-Z\\d_][^\\WA-Z]+__)$' pattern)

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
62
        values = [self._i_sum(a, b, i, z) for i in range(len(a))]
63
        return int(np.sum(values))
64
65
    def _i_sum(self, a: np.array, b: np.array, i: int, z: int):
0 ignored issues
show
Coding Style introduced by
This method could be written as a function/class method.

If a method does not access any attributes of the class, it could also be implemented as a function or static method. This can help improve readability. For example

class Foo:
    def some_method(self, x, y):
        return x + y;

could be written as

class Foo:
    @classmethod
    def some_method(cls, x, y):
        return x + y;
Loading history...
Coding Style Naming introduced by
Argument name "z" doesn't conform to snake_case naming style ('([^\\W\\dA-Z][^\\WA-Z]2,|_[^\\WA-Z]*|__[^\\WA-Z\\d_][^\\WA-Z]+__)$' pattern)

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
Coding Style Naming introduced by
Argument name "b" doesn't conform to snake_case naming style ('([^\\W\\dA-Z][^\\WA-Z]2,|_[^\\WA-Z]*|__[^\\WA-Z\\d_][^\\WA-Z]+__)$' pattern)

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
Coding Style Naming introduced by
Argument name "a" doesn't conform to snake_case naming style ('([^\\W\\dA-Z][^\\WA-Z]2,|_[^\\WA-Z]*|__[^\\WA-Z\\d_][^\\WA-Z]+__)$' pattern)

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
66
        values = [int(np.sign(a[i] - a[j]) == z * np.sign(b[i] - b[j]) != 0) for j in range(i)]
67
        return int(np.sum(values))
68
69
70
class ConcordanceAlg(CleverEnum):
0 ignored issues
show
introduced by
Missing class docstring
Loading history...
71
    tau = enum.auto()
72
73
74
class ConcordanceCalculation:
0 ignored issues
show
introduced by
Missing class docstring
Loading history...
75
    @classmethod
76
    def create(
0 ignored issues
show
best-practice introduced by
Too many arguments (6/5)
Loading history...
introduced by
Missing function or method docstring
Loading history...
77
        cls,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
78
        algorithm: Union[str, ConcordanceAlg],
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
79
        phi_name: str,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
80
        psi_name: str,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
81
        n_samples: int,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
82
        seed: int,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
83
    ) -> ConcordanceCalculator:
84
        algorithm = ConcordanceAlg.of(algorithm)
85
        return TauConcordanceCalculator(
86
            n_samples=n_samples, seed=seed, phi_name=phi_name, psi_name=psi_name
87
        )
88
89
90
__all__ = [
91
    "ConcordanceCalculator",
92
    "TauConcordanceCalculator",
93
    "ConcordanceDf",
94
    "ConcordanceCalculation",
95
    "ConcordanceAlg",
96
]
97