From e64d353865337d48ba5123be583a71e08983f7af Mon Sep 17 00:00:00 2001 From: Philip Eisenlohr Date: Wed, 24 Jun 2020 18:37:33 -0400 Subject: [PATCH] condensed scale_to_coprime; added test of scale_to_coprime --- python/damask/util.py | 11 +++++++---- python/tests/test_util.py | 23 ++++++++++++++++++++++- 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/python/damask/util.py b/python/damask/util.py index 471a5069b..cf99dc1b9 100644 --- a/python/damask/util.py +++ b/python/damask/util.py @@ -166,10 +166,13 @@ def scale_to_coprime(v): """Least common multiple.""" return a * b // np.gcd(a, b) - denominators = [int(get_square_denominator(i)) for i in v] - s = reduce(lcm, denominators) ** 0.5 - m = (np.array(v)*s).astype(np.int) - return m//reduce(np.gcd,m) + m = (np.array(v) * reduce(lcm, map(lambda x: int(get_square_denominator(x)),v)) ** 0.5).astype(np.int) + m = m//reduce(np.gcd,m) + + if not np.allclose(v/m,v[0]/m[0]): + raise ValueError(f'Invalid result {m} for input {v}. Insufficient precision?') + + return m #################################################################################################### diff --git a/python/tests/test_util.py b/python/tests/test_util.py index e67478d82..de6926e8c 100644 --- a/python/tests/test_util.py +++ b/python/tests/test_util.py @@ -1,11 +1,32 @@ +import pytest +import numpy as np from damask import util + class TestUtil: def test_execute_direct(self): out,err = util.execute('echo test') assert out=='test\n' and err=='' - + def test_execute_env(self): out,err = util.execute('sh -c "echo $test_for_execute"',env={'test_for_execute':'test'}) assert out=='test\n' and err=='' + + def test_croak(self): + util.croak('Burp!') + + @pytest.mark.parametrize('input,output', + [ + ([0.5,0.5],[1,1]), + ([1./2.,1./3.],[3,2]), + ([2./3.,1./2.,1./3.],[4,3,2]), + ]) + + def test_scale2coprime(self,input,output): + assert np.allclose(util.scale_to_coprime(np.array(input)), + np.array(output).astype(int)) + + def test_lackofprecision(self): + with pytest.raises(ValueError): + util.scale_to_coprime(np.array([0.66,0.5,0.33]))