Fix: Black does its job

This commit is contained in:
Bertrand Benjamin 2019-10-13 21:01:31 +02:00
parent 02214b0f82
commit d6bb61dc48
14 changed files with 98 additions and 67 deletions

View File

@ -1,9 +1,9 @@
#!/usr/bin/env python #!/usr/bin/env python
# encoding: utf-8 # encoding: utf-8
from .calculus import Expression#, Polynom, Fraction, random_str, txt, Equation from .calculus import Expression # , Polynom, Fraction, random_str, txt, Equation
#Expression.set_render('tex') # Expression.set_render('tex')
from .stat import Dataset, WeightedDataset from .stat import Dataset, WeightedDataset
from .geometry import random_pythagore from .geometry import random_pythagore

View File

@ -12,7 +12,13 @@ Expression
""" """
from functools import partial from functools import partial
from ..core import AssocialTree, Tree, compute, typing, TypingError from ..core import AssocialTree, Tree, compute, typing, TypingError
from ..core.random import extract_rdleaf, extract_rv, random_generator, compute_leafs, replace_rdleaf from ..core.random import (
extract_rdleaf,
extract_rv,
random_generator,
compute_leafs,
replace_rdleaf,
)
from ..core.MO import moify from ..core.MO import moify
from .tokens import factory from .tokens import factory
from .renders import renders from .renders import renders
@ -75,6 +81,7 @@ class Expression(object):
>>> Expression.set_render('txt') >>> Expression.set_render('txt')
""" """
from .tokens.token import Token from .tokens.token import Token
Token.set_render(render) Token.set_render(render)
cls.RENDER = render cls.RENDER = render
@ -485,6 +492,7 @@ def extract_variable(leaf):
except AttributeError: except AttributeError:
return None return None
def replace(leaf, origin, dest): def replace(leaf, origin, dest):
""" Recursively replace origin to dest in leaf """ """ Recursively replace origin to dest in leaf """
try: try:
@ -497,6 +505,7 @@ def replace(leaf, origin, dest):
replace_var = partial(replace, origin=origin, dest=dest) replace_var = partial(replace, origin=origin, dest=dest)
return leaf.tree.map_on_leaf(replace_var) return leaf.tree.map_on_leaf(replace_var)
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:

View File

@ -69,7 +69,7 @@ class Token(object):
else: else:
raise ValueError(f"Unknow render {self.RENDER}") raise ValueError(f"Unknow render {self.RENDER}")
#return renders[self.RENDER](self._mo) # return renders[self.RENDER](self._mo)
@property @property
def __txt__(self): def __txt__(self):
@ -203,7 +203,6 @@ class Token(object):
return self._get_soul() <= self._get_soul(other) return self._get_soul() <= self._get_soul(other)
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:

View File

@ -26,6 +26,7 @@ def moify(token):
except MOError: except MOError:
return token return token
@coroutine @coroutine
def moify_cor(target): def moify_cor(target):
""" Coroutine which try to convert a parsed token into an MO """ Coroutine which try to convert a parsed token into an MO

View File

@ -101,7 +101,6 @@ class MO(ABC):
raise NotImplementedError raise NotImplementedError
class Atom(MO): class Atom(MO):
""" Base Math Object with only one component. """ Base Math Object with only one component.

View File

@ -110,6 +110,7 @@ class MOstrPower(Molecule):
'monome2' 'monome2'
""" """
return f"monome{self.power}" return f"monome{self.power}"
def differentiate(self): def differentiate(self):
""" differentiate a MOstrPower and get a tree """ differentiate a MOstrPower and get a tree
@ -121,8 +122,10 @@ class MOstrPower(Molecule):
> x^2 > x^2
""" """
if self._power > 2: if self._power > 2:
return Tree('*', self.power, MOstrPower(self.variable, self._power._value-1)) return Tree(
return Tree('*', self.power, MOstr(self.variable)) "*", self.power, MOstrPower(self.variable, self._power._value - 1)
)
return Tree("*", self.power, MOstr(self.variable))
class MOMonomial(Molecule): class MOMonomial(Molecule):

View File

@ -27,6 +27,7 @@ multiply_doc = """ Multiply MOs
multiply = Dispatcher("multiply", doc=multiply_doc) multiply = Dispatcher("multiply", doc=multiply_doc)
def multiply_filter(left, right): def multiply_filter(left, right):
""" Automatic multiply on MO """ Automatic multiply on MO
@ -56,6 +57,7 @@ def multiply_filter(left, right):
except TypeError: except TypeError:
pass pass
@multiply.register((MOnumber, MOFraction), MOstr) @multiply.register((MOnumber, MOFraction), MOstr)
@special_case(multiply_filter) @special_case(multiply_filter)
def moscalar_mostr(left, right): def moscalar_mostr(left, right):
@ -102,7 +104,7 @@ def moscalar_mostrpower(left, right):
>>> multiply(a, x) >>> multiply(a, x)
<MOstrPower x^4> <MOstrPower x^4>
""" """
#if left == 1: # if left == 1:
# return right # return right
return MOMonomial(left, right) return MOMonomial(left, right)

View File

@ -5,7 +5,7 @@
from random import randint from random import randint
def random_pythagore(v_min = 1, v_max = 10, nbr_format = lambda x : x) : def random_pythagore(v_min=1, v_max=10, nbr_format=lambda x: x):
""" Generate a pythagore triplet """ Generate a pythagore triplet
:returns: (a,b,c) such that a^2 = b^2 + c^2 :returns: (a,b,c) such that a^2 = b^2 + c^2
@ -14,10 +14,11 @@ def random_pythagore(v_min = 1, v_max = 10, nbr_format = lambda x : x) :
while u == v: while u == v:
u, v = randint(v_min, v_max), randint(v_min, v_max) u, v = randint(v_min, v_max), randint(v_min, v_max)
u, v = max(u, v), min(u, v) u, v = max(u, v), min(u, v)
triplet = (u**2+v**2, 2*u*v, u**2-v**2) triplet = (u ** 2 + v ** 2, 2 * u * v, u ** 2 - v ** 2)
formated_triplet = [nbr_format(i) for i in triplet] formated_triplet = [nbr_format(i) for i in triplet]
return formated_triplet return formated_triplet
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:

View File

@ -1,4 +1,4 @@
#/usr/bin/env python # /usr/bin/env python
# -*- coding:Utf-8 -*- # -*- coding:Utf-8 -*-
# #
@ -32,11 +32,17 @@ class Dataset(list):
""" """
@classmethod @classmethod
def random(cls, length, data_name="Valeurs", def random(
distrib="gauss", rd_args=(0, 1), cls,
length,
data_name="Valeurs",
distrib="gauss",
rd_args=(0, 1),
nbr_format=lambda x: round(x, 2), nbr_format=lambda x: round(x, 2),
v_min=None, v_max=None, v_min=None,
exact_mean=None): v_max=None,
exact_mean=None,
):
""" Generate a random list of value """ Generate a random list of value
:param length: length of the dataset :param length: length of the dataset
@ -47,11 +53,9 @@ class Dataset(list):
:param v_max: maximum accepted value :param v_max: maximum accepted value
:param exact_mean: if set, the last generated number will be create in order that the computed mean is exacly equal to "exact_mean" :param exact_mean: if set, the last generated number will be create in order that the computed mean is exacly equal to "exact_mean"
""" """
data = random_generator(length, data = random_generator(
distrib, rd_args, length, distrib, rd_args, nbr_format, v_min, v_max, exact_mean
nbr_format, )
v_min, v_max,
exact_mean)
return cls(data, data_name=data_name) return cls(data, data_name=data_name)
@ -94,7 +98,7 @@ class Dataset(list):
def deviation(self): def deviation(self):
""" Compute the deviation (not normalized) """ """ Compute the deviation (not normalized) """
mean = self.mean() mean = self.mean()
return sum([(x - mean)**2 for x in self]) return sum([(x - mean) ** 2 for x in self])
@number_factory @number_factory
def variance(self): def variance(self):
@ -120,7 +124,8 @@ class Dataset(list):
self.quartile(1), self.quartile(1),
self.quartile(2), self.quartile(2),
self.quartile(3), self.quartile(3),
max(self)) max(self),
)
@number_factory @number_factory
def quartile(self, quartile=1): def quartile(self, quartile=1):
@ -173,18 +178,21 @@ class Dataset(list):
""" Latex code to display dataset as a tabular """ """ Latex code to display dataset as a tabular """
d_per_line = self.effectif_total() // nbr_lines d_per_line = self.effectif_total() // nbr_lines
d_last_line = self.effectif_total() % d_per_line d_last_line = self.effectif_total() % d_per_line
splited_data = [self[x:x + d_per_line] splited_data = [
for x in range(0, self.effectif_total(), d_per_line)] self[x : x + d_per_line]
for x in range(0, self.effectif_total(), d_per_line)
]
# On ajoute les éléments manquant pour la dernière line # On ajoute les éléments manquant pour la dernière line
if d_last_line: if d_last_line:
splited_data[-1] += [' '] * (d_per_line - d_last_line) splited_data[-1] += [" "] * (d_per_line - d_last_line)
# Construction du tableau # Construction du tableau
latex = "\\begin{{tabular}}{{|c|*{{{nbr_col}}}{{c|}}}} \n".format( latex = "\\begin{{tabular}}{{|c|*{{{nbr_col}}}{{c|}}}} \n".format(
nbr_col=d_per_line) nbr_col=d_per_line
)
latex += "\t\t \hline \n" latex += "\t\t \hline \n"
d_lines = [' & '.join(map(str, l)) for l in splited_data] d_lines = [" & ".join(map(str, l)) for l in splited_data]
latex += " \\\\ \n \\hline \n".join(d_lines) latex += " \\\\ \n \\hline \n".join(d_lines)
latex += " \\\\ \n \\hline \n" latex += " \\\\ \n \\hline \n"

View File

@ -1,4 +1,4 @@
#/usr/bin/env python # /usr/bin/env python
# -*- coding:Utf-8 -*- # -*- coding:Utf-8 -*-
from functools import wraps from functools import wraps
@ -6,6 +6,7 @@ from functools import wraps
def number_factory(fun): def number_factory(fun):
""" Decorator which format returned value """ """ Decorator which format returned value """
@wraps(fun) @wraps(fun)
def wrapper(*args, **kwargs): def wrapper(*args, **kwargs):
ans = fun(*args, **kwargs) ans = fun(*args, **kwargs)
@ -16,6 +17,7 @@ def number_factory(fun):
return round(ans, 2) return round(ans, 2)
except AttributeError: except AttributeError:
return ans return ans
return wrapper return wrapper

View File

@ -1,14 +1,18 @@
#/usr/bin/env python # /usr/bin/env python
# -*- coding:Utf-8 -*- # -*- coding:Utf-8 -*-
from random import randint, uniform, gauss, choice from random import randint, uniform, gauss, choice
def random_generator(length, def random_generator(
distrib=gauss, rd_args=(0, 1), length,
distrib=gauss,
rd_args=(0, 1),
nbr_format=lambda x: round(x, 2), nbr_format=lambda x: round(x, 2),
v_min=None, v_max=None, v_min=None,
exact_mean=None): v_max=None,
exact_mean=None,
):
""" Generate a random list of value """ Generate a random list of value
:param length: length of the dataset :param length: length of the dataset
@ -47,7 +51,8 @@ def random_generator(length,
"gauss": gauss, "gauss": gauss,
"uniform": uniform, "uniform": uniform,
"randint": randint, "randint": randint,
"choice": choice} "choice": choice,
}
try: try:
distrib(*rd_args) distrib(*rd_args)
except TypeError: except TypeError:
@ -67,11 +72,13 @@ def random_generator(length,
last_v = nbr_format((length + 1) * exact_mean - sum(data)) last_v = nbr_format((length + 1) * exact_mean - sum(data))
if not validate(last_v): if not validate(last_v):
raise ValueError( raise ValueError(
"Can't build the last value. Conflict between v_min/v_max and exact_mean") "Can't build the last value. Conflict between v_min/v_max and exact_mean"
)
data.append(last_v) data.append(last_v)
return data return data
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:

View File

@ -1,4 +1,4 @@
#/usr/bin/env python # /usr/bin/env python
# -*- coding:Utf-8 -*- # -*- coding:Utf-8 -*-
""" """
@ -12,9 +12,11 @@ from .dataset import Dataset
from itertools import chain from itertools import chain
from .number_tools import number_factory from .number_tools import number_factory
def flatten_list(l): def flatten_list(l):
return list(chain(*l)) return list(chain(*l))
class WeightedDataset(dict): class WeightedDataset(dict):
""" A weighted dataset with statistics and latex rendering methods """ A weighted dataset with statistics and latex rendering methods
@ -37,11 +39,8 @@ class WeightedDataset(dict):
""" """
def __init__( def __init__(
self, self, datas=[], data_name="Valeurs", weights=[], weight_name="Effectifs"
datas=[], ):
data_name="Valeurs",
weights=[],
weight_name="Effectifs"):
""" """
Initiate the WeightedDataset Initiate the WeightedDataset
""" """
@ -84,7 +83,7 @@ class WeightedDataset(dict):
def deviation(self): def deviation(self):
""" Compute the deviation (not normalized) """ """ Compute the deviation (not normalized) """
mean = self.mean() mean = self.mean()
return sum([v * (k - mean)**2 for (k, v) in self.items()]) return sum([v * (k - mean) ** 2 for (k, v) in self.items()])
@number_factory @number_factory
def variance(self): def variance(self):
@ -109,11 +108,13 @@ class WeightedDataset(dict):
(1, 3, 4, 5, 5) (1, 3, 4, 5, 5)
""" """
return (min(self.keys()), return (
min(self.keys()),
self.quartile(1), self.quartile(1),
self.quartile(2), self.quartile(2),
self.quartile(3), self.quartile(3),
max(self.keys())) max(self.keys()),
)
@number_factory @number_factory
def quartile(self, quartile=1): def quartile(self, quartile=1):
@ -146,8 +147,9 @@ class WeightedDataset(dict):
position = self.posi_quartile(quartile) - 1 position = self.posi_quartile(quartile) - 1
expanded_values = flatten_list([v * [k] for (k, v) in self.items()]) expanded_values = flatten_list([v * [k] for (k, v) in self.items()])
if position.is_integer(): if position.is_integer():
return (expanded_values[int(position)] + return (
expanded_values[int(position) + 1]) / 2 expanded_values[int(position)] + expanded_values[int(position) + 1]
) / 2
else: else:
return expanded_values[ceil(position)] return expanded_values[ceil(position)]
@ -167,7 +169,8 @@ class WeightedDataset(dict):
def tabular_latex(self): def tabular_latex(self):
""" Latex code to display dataset as a tabular """ """ Latex code to display dataset as a tabular """
latex = "\\begin{{tabular}}{{|c|*{{{nbr_col}}}{{c|}}}} \n".format( latex = "\\begin{{tabular}}{{|c|*{{{nbr_col}}}{{c|}}}} \n".format(
nbr_col=len(self.keys())) nbr_col=len(self.keys())
)
latex += "\t \hline \n" latex += "\t \hline \n"
data_line = "\t {data_name} ".format(data_name=self.data_name) data_line = "\t {data_name} ".format(data_name=self.data_name)
weight_line = "\t {weight_name} ".format(weight_name=self.weight_name) weight_line = "\t {weight_name} ".format(weight_name=self.weight_name)

View File

@ -6,17 +6,14 @@ except ImportError:
from distutils.core import setup from distutils.core import setup
setup( setup(
name='mapytex', name="mapytex",
version='2.1', version="2.1",
description='Computing like a student', description="Computing like a student",
author='Benjamin Bertrand', author="Benjamin Bertrand",
author_email='programming@opytex.org', author_email="programming@opytex.org",
url='http://git.opytex.org/lafrite/Mapytex', url="http://git.opytex.org/lafrite/Mapytex",
#packages=['mapytex'], # packages=['mapytex'],
packages=find_packages(), packages=find_packages(),
include_package_data = True, include_package_data=True,
install_requires=[ install_requires=["multipledispatch", "tabulate"],
'multipledispatch', )
'tabulate',
],
)