Skip to content

Commit

Permalink
Merge pull request #117 from sertansenturk/linting
Browse files Browse the repository at this point in the history
Linting
  • Loading branch information
sertansenturk authored Dec 27, 2019
2 parents fc945d0 + f84b25f commit 24c4690
Show file tree
Hide file tree
Showing 41 changed files with 1,012 additions and 458 deletions.
595 changes: 592 additions & 3 deletions .pylintrc

Large diffs are not rendered by default.

22 changes: 20 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
language: python
matrix:
include:
- name: "Docker build"
- name: "docker build"
services: docker
python: 3.6
env: TOX_ENV=docker
Expand All @@ -12,6 +12,24 @@ matrix:
install: # installed by tox
script: tox -e $TOX_ENV
after_success: # do nothing
- name: "pylint"
python: 3.6
env: TOX_ENV=pylint
before_install:
- pip install -U pip
- pip install tox-travis
install: # installed by tox
script: tox -e $TOX_ENV
after_success: # do nothing
- name: "flake8"
python: 3.6
env: TOX_ENV=flake8
before_install:
- pip install -U pip
- pip install tox-travis
install: # installed by tox
script: tox -e $TOX_ENV
after_success: # do nothing
- name: "Python 3.5"
python: 3.5
env: TOX_PYTHON_ENV=py35
Expand All @@ -30,6 +48,6 @@ install:
- python setup.py install
- pip show tomato
script:
- tox -e $TOX_PYTHON_ENV, flake8, pylint
- tox -e $TOX_PYTHON_ENV
after_success:
- codecov # submit coverage to https://codecov.io/gh/sertansenturk/tomato/
4 changes: 2 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,14 +133,14 @@ def _download_binary(fpath, bin_url, sys_os):
"computational-analysis"),
packages=find_packages(exclude=['docs', 'tests']),
include_package_data=True,
python_requires='>=3.5, <3.8',
python_requires='>=3.5,<3.8',
install_requires=[
"numpy>=1.9.0", # numerical operations
"scipy>=0.17.0", # temporary mat file saving for MCR binary inputs
"pandas>=0.18.0,<=0.24.2", # tabular data processing
"matplotlib>=1.5.1,<=3.0.3", # plotting
"json_tricks>=3.12.1", # saving json files with classes and numpy
"eyeD3>=0.7.5,<=0.8.11", # reading metadata embedded in the audio recordings
"eyeD3>=0.7.5,<=0.8.11", # reading metadata embedded in recordings
"python-Levenshtein>=0.12.0", # semiotic structure labeling
"networkx>=1.11", # semiotic structure labeling clique computation
"lxml>=3.6.0", # musicxml conversion
Expand Down
3 changes: 2 additions & 1 deletion tomato/analyzer.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@

from .io import IO

logger = logging.Logger(__name__, level=logging.INFO)
logger = logging.Logger( # pylint: disable-msg=C0103
__name__, level=logging.INFO)


class Analyzer:
Expand Down
7 changes: 5 additions & 2 deletions tomato/audio/ahenk.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,9 @@ class Ahenk:

@classmethod
def identify(cls, tonic_freq, symbol_in):
assert 20.0 <= tonic_freq <= 20000.0, "The input tonic frequency " \
"must be between and 20000 Hz"
if (tonic_freq < 20) or (tonic_freq > 20000):
raise ValueError("The input tonic frequency must be between "
"and 20000 Hz.")

tonic_dict = IO.load_music_data('tonic')
ahenks = IO.load_music_data('ahenk')
Expand Down Expand Up @@ -74,6 +75,8 @@ def identify(cls, tonic_freq, symbol_in):
ahenk_dict['slug'] = ahenk_slug
return ahenk_dict

raise ValueError("Unknown error: could not identify the ahenk.")

@classmethod
def _get_tonic_symbol(cls, symbol_in, tonic_dict):
if symbol_in in tonic_dict.keys(): # tonic symbol given
Expand Down
4 changes: 2 additions & 2 deletions tomato/audio/audioanalyzer.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@
from .predominantmelody import PredominantMelody
from .seyir import Seyir

logger = logging.Logger(__name__, level=logging.INFO)
logger = logging.Logger( # pylint: disable-msg=C0103
__name__, level=logging.INFO)


class AudioAnalyzer(Analyzer):
Expand Down Expand Up @@ -348,7 +349,6 @@ def set_melody_progression_params(self, **kwargs):
def set_note_modeler_params(self, **kwargs):
self._set_params('_note_modeler', **kwargs)

# plot
@staticmethod
def plot(audio_features):
pitch = audio_features['pitch_filtered']['pitch']
Expand Down
3 changes: 2 additions & 1 deletion tomato/audio/makamtonic/inputparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@
from ..pitchdistribution import PitchDistribution
from ...converter import Converter

logger = logging.Logger(__name__, level=logging.INFO)
logger = logging.Logger( # pylint: disable-msg=C0103
__name__, level=logging.INFO)


class InputParser:
Expand Down
2 changes: 1 addition & 1 deletion tomato/audio/makamtonic/knn.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,4 +165,4 @@ def classify(cand_pairs, sorted_pair):
sorted_pair = [pp for pp in sorted_pair if pp[0] != p[0]]
return estimated_pair, sorted_pair

assert False, 'No pair selected, this should be impossible!'
raise ValueError('No pair selected, this should be impossible!')
15 changes: 8 additions & 7 deletions tomato/audio/makamtonic/knnclassifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,12 @@ def train(self, pitches, tonics, modes, sources=None, model_type='multi'):
if model_type == 'single':
return self._train_single_distrib_per_mode(
pitches, tonics, modes, sources=sources)
elif model_type == 'multi':

if model_type == 'multi':
return self._train_multi_distrib_per_mode(
pitches, tonics, modes, sources=sources)
else:
raise ValueError("Unknown training model")

raise ValueError("Unknown training model")

def _train_single_distrib_per_mode(self, pitches, tonics, modes,
sources=None):
Expand Down Expand Up @@ -346,8 +347,8 @@ def model_from_pickle(self, input_str):
def model_to_pickle(model, file_name=None):
if file_name is None:
return pickle.dumps(model)
else:
pickle.dump(model, open(file_name, 'wb'))

return pickle.dump(model, open(file_name, 'wb'))

def model_from_json(self, file_name):
"""--------------------------------------------------------------------
Expand Down Expand Up @@ -387,5 +388,5 @@ def model_to_json(model, file_name=None):

if file_name is None:
return json.dumps(temp_model, indent=4)
else:
json.dump(temp_model, open(file_name, 'w'), indent=4)

return json.dump(temp_model, open(file_name, 'w'), indent=4)
7 changes: 3 additions & 4 deletions tomato/audio/makamtonic/toniclastnote.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,13 @@

from copy import deepcopy

import matplotlib.pyplot as plt
import matplotlib.ticker
import numpy as np

from ...converter import Converter
from ..pitchdistribution import PitchDistribution
from ..pitchfilter import PitchFilter
from ...converter import Converter


class TonicLastNote:
Expand Down Expand Up @@ -156,9 +158,6 @@ def check_tonic_w_octave_cor(self, tonic, distribution):

@staticmethod
def plot(pitch, tonic, pitch_chunks, distribution):
import matplotlib.pyplot as plt
import matplotlib.ticker

_, (ax1, ax2, ax3) = plt.subplots(3, num=None, figsize=(18, 8), dpi=80)
plt.subplots_adjust(left=None, bottom=None, right=None, top=None,
wspace=0, hspace=0.4)
Expand Down
9 changes: 4 additions & 5 deletions tomato/audio/notemodel.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@

from copy import deepcopy

import matplotlib.pyplot as plt
import matplotlib.ticker
import numpy as np

from ..converter import Converter
Expand Down Expand Up @@ -53,7 +55,7 @@ def calculate_notes(self, pitch_distribution, tonic_hz, makam,
pass

# Calculate stable pitches
peak_idx, peak_heights = pd_copy.detect_peaks(
peak_idx, _ = pd_copy.detect_peaks(
min_peak_ratio=min_peak_ratio)

stable_pitches_hz = pd_copy.bins[peak_idx]
Expand Down Expand Up @@ -187,10 +189,7 @@ def _get_extended_key_signature(self, key_sig_in, note_dict):

@staticmethod
def plot(pitch_distribution, stable_notes):
import matplotlib.pyplot as plt
import matplotlib.ticker

fig, ax = plt.subplots()
_, ax = plt.subplots()
plt.subplots_adjust(left=None, bottom=None, right=None, top=None,
wspace=0, hspace=0.4)

Expand Down
39 changes: 17 additions & 22 deletions tomato/audio/pitchdistribution.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,16 @@

import essentia
import essentia.standard as std
import matplotlib.pyplot as plt
import numpy as np
import scipy.integrate
import scipy.stats

from ..converter import Converter
from ..io import IO

logger = logging.Logger(__name__, level=logging.INFO)
logger = logging.Logger( # pylint: disable-msg=C0103
__name__, level=logging.INFO)


class PitchDistribution:
Expand Down Expand Up @@ -84,11 +86,12 @@ def bin_unit(self):
'(bin unit is Hz) or a number greater than 0.'
if self.ref_freq is None:
return 'Hz'
elif isinstance(self.ref_freq, (numbers.Number, np.ndarray)):

if isinstance(self.ref_freq, (numbers.Number, np.ndarray)):
assert self.ref_freq > 0, err_str
return 'cent'
else:
return ValueError(err_str)

return ValueError(err_str)

@staticmethod
def from_cent_pitch(cent_track, ref_freq=440.0, kernel_width=7.5,
Expand Down Expand Up @@ -227,13 +230,11 @@ def is_pcd(self):
if self.has_cent_bin(): # cent bins; compare directly
return np.isclose(max(self.bins) - min(self.bins),
1200 - self.step_size)
else:
dummy_d = copy.deepcopy(self)

dummy_d.hz_to_cent(dummy_d.bins[0])

return np.isclose(max(dummy_d.bins) - min(dummy_d.bins),
1200 - dummy_d.step_size)
dummy_d = copy.deepcopy(self)
dummy_d.hz_to_cent(dummy_d.bins[0])
return np.isclose(max(dummy_d.bins) - min(dummy_d.bins),
1200 - dummy_d.step_size)

def is_pdf(self):
return np.isclose(np.sum(self.vals), 1)
Expand Down Expand Up @@ -273,7 +274,7 @@ def detect_peaks(self, min_peak_ratio=0.15):
'1 (keep only the highest peak)'

# Peak detection is handled by Essentia
detector = std.PeakDetection()
detector = std.PeakDetection() # pylint: disable-msg=E1101
peak_bins, peak_vals = detector(essentia.array(self.vals))

# Essentia normalizes the positions to 1, they are converted here
Expand Down Expand Up @@ -413,23 +414,17 @@ def merge(self, distrib):
self.normalize()

def plot(self):
import matplotlib.pyplot as plt

plt.plot(self.bins, self.vals)
self._label_figure()

def bar(self):
import matplotlib.pyplot as plt

def bar(self): # pylint: disable-msg=C0102
bars = plt.bar(self.bins, self.vals, width=self.step_size,
align='center')
self._label_figure()

return bars

def _label_figure(self):
import matplotlib.pyplot as plt

if self.is_pcd():
plt.title('Pitch class distribution')
ref_freq_str = 'Hz x 2^n'
Expand Down Expand Up @@ -477,8 +472,8 @@ def to_json(self, file_name=None):

if file_name is None:
return json.dumps(dist_json, indent=4)
else:
json.dump(dist_json, open(file_name, 'w'), indent=4)

return json.dump(dist_json, open(file_name, 'w'), indent=4)

@staticmethod
def from_dict(distrib_dict):
Expand All @@ -488,10 +483,10 @@ def from_dict(distrib_dict):

def to_dict(self):
pdict = self.__dict__
for key in pdict.keys():
for key, val in pdict.items():
try:
# convert to list from np array
pdict[key] = pdict[key].tolist()
pdict[key] = val.tolist()
except AttributeError:
pass

Expand Down
Loading

0 comments on commit 24c4690

Please sign in to comment.