Dataset Viewer
Auto-converted to Parquet
python_code
stringlengths
0
780k
repo_name
stringlengths
7
38
file_path
stringlengths
5
103
# Copyright 2019 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module setuptools script.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from setuptools import find_packages from setuptools import setup description = """A synthetic dataset of school-level mathematics questions. This dataset code generates mathematical question and answer pairs, from a range of question types (such as in arithmetic, algebra, probability, etc), at roughly school-level difficulty. This is designed to test the mathematical learning and reasoning skills of learning models. Original paper: Analysing Mathematical Reasoning Abilities of Neural Models (Saxton, Grefenstette, Hill, Kohli) (https://openreview.net/pdf?id=H1gR5iR5FX). """ setup( name='mathematics_dataset', version='1.0.1', description='A synthetic dataset of school-level mathematics questions', long_description=description, author='DeepMind', author_email='[email protected]', license='Apache License, Version 2.0', keywords='mathematics dataset', url='https://github.com/deepmind/mathematics_dataset', packages=find_packages(), install_requires=[ 'absl-py>=0.1.0', 'numpy>=1.10', 'six', 'sympy>=1.2', ], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: Apache Software License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Topic :: Scientific/Engineering :: Artificial Intelligence', ], )
mathematics_dataset-master
setup.py
# Copyright 2018 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Example of how to write generated questions to text files. Given an output directory, this will create the following subdirectories: * train-easy * train-medium * train-hard * interpolate * extrapolate and populate each of these directories with a text file for each of the module, where the text file contains lines alternating between the question and the answer. Passing --train_split=False will create a single output directory 'train' for training data. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os # Dependency imports from absl import app from absl import flags from absl import logging from mathematics_dataset import generate import six from six.moves import range FLAGS = flags.FLAGS flags.DEFINE_string('output_dir', None, 'Where to write output text') flags.DEFINE_boolean('train_split', True, 'Whether to split training data by difficulty') flags.mark_flag_as_required('output_dir') def main(unused_argv): generate.init_modules(FLAGS.train_split) output_dir = os.path.expanduser(FLAGS.output_dir) if os.path.exists(output_dir): logging.fatal('output dir %s already exists', output_dir) logging.info('Writing to %s', output_dir) os.makedirs(output_dir) for regime, flat_modules in six.iteritems(generate.filtered_modules): regime_dir = os.path.join(output_dir, regime) os.mkdir(regime_dir) per_module = generate.counts[regime] for module_name, module in six.iteritems(flat_modules): path = os.path.join(regime_dir, module_name + '.txt') with open(path, 'w') as text_file: for _ in range(per_module): problem, _ = generate.sample_from_module(module) text_file.write(str(problem.question) + '\n') text_file.write(str(problem.answer) + '\n') logging.info('Written %s', path) if __name__ == '__main__': app.run(main)
mathematics_dataset-master
mathematics_dataset/generate_to_file.py
# Copyright 2018 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for mathematics_dataset.generate.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # Dependency imports from absl.testing import absltest from absl.testing import parameterized from mathematics_dataset import generate import six from six.moves import range class GenerateTest(parameterized.TestCase): def testMakeEntropyFn(self): entropy_full = generate._make_entropy_fn(0, 1) self.assertEqual(entropy_full((2, 3)), (2, 3)) entropy_third = generate._make_entropy_fn(2, 3) self.assertEqual(entropy_third((3, 6)), (5, 6)) @parameterized.parameters('train', 'interpolate', 'extrapolate') def testGenerate(self, regime): generate.init_modules() for module in six.itervalues(generate.filtered_modules[regime]): for _ in range(3): question = module() str(question) if __name__ == '__main__': absltest.main()
mathematics_dataset-master
mathematics_dataset/generate_test.py
# Copyright 2018 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Prints to stdout different curriculum questions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import textwrap # Dependency imports from absl import app from absl import flags from absl import logging from mathematics_dataset import generate_settings from mathematics_dataset.modules import modules import six from six.moves import range FLAGS = flags.FLAGS flags.DEFINE_string('filter', '', 'restrict to matching module names') flags.DEFINE_integer('per_train_module', 10, 'Num of examples per train module') flags.DEFINE_integer('per_test_module', 10, 'Num of examples per test module') flags.DEFINE_bool('show_dropped', False, 'Whether to print dropped questions') filtered_modules = collections.OrderedDict([]) counts = {} def _make_entropy_fn(level, num_levels): """This returns a function that returns a subrange of entropy. E.g., if level=1 (medium) and num_levels=3, then the returned function will map the range [x, x + y] to [x + y/3, x + 2y/3]. Args: level: Integer in range [0, num_levels - 1]. num_levels: Number of difficulty levels. Returns: Function to restrict entropy range. """ lower = level / num_levels upper = (level + 1) / num_levels def modify_entropy(range_): assert len(range_) == 2 length = range_[1] - range_[0] return (range_[0] + lower * length, range_[0] + upper * length) return modify_entropy def _filter_and_flatten(modules_): """Returns flattened dict, filtered according to FLAGS.""" flat = collections.OrderedDict() def add(submodules, prefix=None): for key, module_or_function in six.iteritems(submodules): full_name = prefix + '__' + key if prefix is not None else key if isinstance(module_or_function, dict): add(module_or_function, full_name) else: if FLAGS.filter not in full_name: continue flat[full_name] = module_or_function add(modules_) # Make sure list of modules are in deterministic order. This is important when # generating across multiple machines. flat = collections.OrderedDict( [(key, flat[key]) for key in sorted(six.iterkeys(flat))]) return flat def init_modules(train_split=False): """Inits the dicts containing functions for generating modules.""" if filtered_modules: return # already initialized all_modules = collections.OrderedDict([]) if train_split: all_modules['train-easy'] = modules.train(_make_entropy_fn(0, 3)) all_modules['train-medium'] = modules.train(_make_entropy_fn(1, 3)) all_modules['train-hard'] = modules.train(_make_entropy_fn(2, 3)) else: all_modules['train'] = modules.train(_make_entropy_fn(0, 1)) all_modules['interpolate'] = modules.test() all_modules['extrapolate'] = modules.test_extra() counts['train'] = FLAGS.per_train_module counts['train-easy'] = FLAGS.per_train_module // 3 counts['train-medium'] = FLAGS.per_train_module // 3 counts['train-hard'] = FLAGS.per_train_module // 3 counts['interpolate'] = FLAGS.per_test_module counts['extrapolate'] = FLAGS.per_test_module for regime_, modules_ in six.iteritems(all_modules): filtered_modules[regime_] = _filter_and_flatten(modules_) def sample_from_module(module): """Samples a problem, ignoring samples with overly long questions / answers. Args: module: Callable returning a `Problem`. Returns: Pair `(problem, num_dropped)`, where `problem` is an instance of `Problem` and `num_dropped` is an integer >= 0 indicating the number of samples that were dropped. """ num_dropped = 0 while True: problem = module() question = str(problem.question) if len(question) > generate_settings.MAX_QUESTION_LENGTH: num_dropped += 1 if FLAGS.show_dropped: logging.warning('Dropping question: %s', question) continue answer = str(problem.answer) if len(answer) > generate_settings.MAX_ANSWER_LENGTH: num_dropped += 1 if FLAGS.show_dropped: logging.warning('Dropping question with answer: %s', answer) continue return problem, num_dropped def main(unused_argv): """Prints Q&As from modules according to FLAGS.filter.""" init_modules() text_wrapper = textwrap.TextWrapper( width=80, initial_indent=' ', subsequent_indent=' ') for regime, flat_modules in six.iteritems(filtered_modules): per_module = counts[regime] for module_name, module in six.iteritems(flat_modules): # These magic print constants make the header bold. print('\033[1m{}/{}\033[0m'.format(regime, module_name)) num_dropped = 0 for _ in range(per_module): problem, extra_dropped = sample_from_module(module) num_dropped += extra_dropped text = text_wrapper.fill( '{} \033[92m{}\033[0m'.format(problem.question, problem.answer)) print(text) if num_dropped > 0: logging.warning('Dropped %d examples', num_dropped) if __name__ == '__main__': app.run(main)
mathematics_dataset-master
mathematics_dataset/generate.py
# Copyright 2018 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
mathematics_dataset-master
mathematics_dataset/__init__.py
# Copyright 2018 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Containers for "[example] problems" (i.e., question/answer) pairs.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections from mathematics_dataset.util import composition def question(context, template, **kwargs): """Makes a question, using the given context and template. The format is similar to that for python's `format` function, for example: ``` question(context, 'What is {} plus {p} over {q}?', 2, p=3, q=4) ``` The main difference between this and the standard python formatting is that this understands `Entity`s in the arguments, and will do appropriate expansion of text and prefixing of their descriptions. Arguments: context: Instance of `composition.Context`, for extracting entities needed for describing the problem. template: A string, like "Calculate the value of {exp}.". **kwargs: A dictionary mapping arguments to values, e.g., `{'exp': sympy.Add(2, 3, evaluate=False)}`. Returns: String. """ assert isinstance(context, composition.Context) assert isinstance(template, str) prefix, kwargs = composition.expand_entities(context, **kwargs) if prefix: prefix += ' ' return prefix + template.format(**kwargs) Problem = collections.namedtuple('Problem', ('question', 'answer'))
mathematics_dataset-master
mathematics_dataset/example.py
# Copyright 2018 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Settings for generation.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import string MAX_QUESTION_LENGTH = 160 MAX_ANSWER_LENGTH = 30 QUESTION_CHARS = ( ['', ' '] + list(string.ascii_letters + string.digits + string.punctuation)) EMPTY_INDEX = QUESTION_CHARS.index('') NUM_INDICES = len(QUESTION_CHARS) CHAR_TO_INDEX = {char: index for index, char in enumerate(QUESTION_CHARS)} INDEX_TO_CHAR = {index: char for index, char in enumerate(QUESTION_CHARS)}
mathematics_dataset-master
mathematics_dataset/generate_settings.py
# Copyright 2018 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for mathematics_dataset.util.composition.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # Dependency imports from absl.testing import absltest from mathematics_dataset.util import composition import sympy class FunctionHandleTest(absltest.TestCase): def testApply(self): handle = composition.FunctionHandle('f', 'g') applied = handle.apply(*sympy.symbols('x y')) self.assertEqual(str(applied), 'f(g(x, y))') applied = handle.apply(sympy.symbols('x')) self.assertEqual(str(applied), 'f(g(x))') class ContextTest(absltest.TestCase): def testPeel(self): sample_args = composition.SampleArgs(4, 3.0) entropy, new_sample_args = sample_args.peel() self.assertAlmostEqual(entropy, 0.75) self.assertEqual(new_sample_args.num_modules, 4) self.assertAlmostEqual(new_sample_args.entropy, 2.25) def testSplit(self): sample_args = composition.SampleArgs(4, 5.0) children = sample_args.split(2) self.assertLen(children, 2) self.assertEqual(sum([child.num_modules for child in children]), 3) self.assertAlmostEqual(sum([child.entropy for child in children]), 5.0) class EntityTest(absltest.TestCase): def testInit_valueErrorIfSelfAndHandle(self): with self.assertRaisesRegex(self, ValueError, 'Cannot specify handle'): composition.Entity(context=composition.Context(), value=0, description='Something with {self}. ', handle='additional') if __name__ == '__main__': absltest.main()
mathematics_dataset-master
mathematics_dataset/util/composition_test.py
# Copyright 2018 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
mathematics_dataset-master
mathematics_dataset/util/__init__.py
# Copyright 2018 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests mathematics_dataset.util.combinatorics.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math # Dependency imports from absl.testing import absltest from mathematics_dataset.util import combinatorics class CombinatoricsTest(absltest.TestCase): def testPositiveIntegersWithSum(self): result = combinatorics.uniform_positive_integers_with_sum(1, 1) self.assertEqual(result, [1]) result = combinatorics.uniform_positive_integers_with_sum(2, 2) self.assertEqual(result, [1, 1]) result = combinatorics.uniform_positive_integers_with_sum(1, 10) self.assertEqual(sum(result), 10) result = combinatorics.uniform_positive_integers_with_sum(2, 10) self.assertEqual(sum(result), 10) result = combinatorics.uniform_positive_integers_with_sum(0, 0) self.assertEqual(result, []) def testNonNegativeIntegersWithSum(self): result = combinatorics.uniform_non_negative_integers_with_sum(1, 0) self.assertEqual(result, [0]) result = combinatorics.uniform_non_negative_integers_with_sum(2, 0) self.assertEqual(result, [0, 0]) result = combinatorics.uniform_non_negative_integers_with_sum(3, 10) self.assertEqual(sum(result), 10) def testLogNumberBinaryTrees(self): self.assertAlmostEqual( combinatorics.log_number_binary_trees(0), math.log(1)) self.assertAlmostEqual( combinatorics.log_number_binary_trees(1), math.log(1)) self.assertAlmostEqual( combinatorics.log_number_binary_trees(2), math.log(2)) self.assertAlmostEqual( combinatorics.log_number_binary_trees(3), math.log(5)) self.assertAlmostEqual( combinatorics.log_number_binary_trees(4), math.log(14)) if __name__ == '__main__': absltest.main()
mathematics_dataset-master
mathematics_dataset/util/combinatorics_test.py
# Copyright 2018 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Functionality for displaying expressions. SymPy provides a lot of functionality for displaying expressions, but it's slightly too centered on being a symbolic maths engine to provides all our needs. For example, it's impossible to display an unsimplified fraction like 3/6, or a decimal that isn't internally represented as a float and thus subject to rounding. Also provides some other convenience such as converting numbers to words, and displaying percentages (properly formatted). """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import decimal # Dependency imports import sympy # For converting integers to words: _INTEGER_LOW = [ 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteeen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen' ] _INTEGER_MID = [ '', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety' ] _INTEGER_HIGH = [ (int(1e12), 'trillion'), (int(1e9), 'billion'), (int(1e6), 'million'), (int(1e3), 'thousand'), (100, 'hundred') ] # For converting rationals to words: _SINGULAR_DENOMINATORS = [ '', '', 'half', 'third', 'quarter', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'eleventh', 'twelth', 'thirteenth', 'fourteenth', 'fifteenth', 'sixteenth', 'seventeenth', 'eighteenth', 'nineteenth', 'twentieth' ] _PLURAL_DENOMINATORS = [ '', '', 'halves', 'thirds', 'quarters', 'fifths', 'sixths', 'sevenths', 'eighths', 'ninths', 'tenths', 'elevenths', 'twelths', 'thirteenths', 'fourteenths', 'fifteenths', 'sixteenths', 'seventeenths', 'eighteenths', 'nineteenths', 'twentieths' ] # For converting ordinals to words: _ORDINALS = [ 'zeroth', 'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'eleventh', 'twelth', 'thirteenth', 'fourteenth', 'fifteenth', 'sixteenth', 'seventeenth', 'eighteenth', 'nineteenth', 'twentieth' ] class Decimal(object): """Display a value as a decimal.""" def __init__(self, value): """Initializes a `Decimal`. Args: value: (Sympy) value to display as a decimal. Raises: ValueError: If `value` cannot be represented as a non-terminating decimal. """ self._value = sympy.Rational(value) numer = int(sympy.numer(self._value)) denom = int(sympy.denom(self._value)) denom_factors = list(sympy.factorint(denom).keys()) for factor in denom_factors: if factor not in [2, 5]: raise ValueError('Cannot represent {} as a non-recurring decimal.' .format(value)) self._decimal = decimal.Decimal(numer) / decimal.Decimal(denom) @property def value(self): """Returns the value as a `sympy.Rational` object.""" return self._value def _sympy_(self): return self._value def decimal_places(self): """Returns the number of decimal places, e.g., 32 has 0 and 1.43 has 2.""" if isinstance(self._decimal, int): return 0 elif isinstance(self._decimal, decimal.Decimal): return -self._decimal.as_tuple().exponent def __str__(self): sign, digits, exponent = self._decimal.as_tuple() sign = '' if sign == 0 else '-' num_left_digits = len(digits) + exponent # number digits "before" point if num_left_digits > 0: int_part = ''.join(str(digit) for digit in digits[:num_left_digits]) else: int_part = '0' if exponent < 0: frac_part = '.' if num_left_digits < 0: frac_part += '0' * -num_left_digits frac_part += ''.join(str(digit) for digit in digits[exponent:]) else: frac_part = '' return sign + int_part + frac_part def __add__(self, other): if not isinstance(other, Decimal): raise ValueError('Arithmetic support limited to other `Decimal`s.') return Decimal(self.value + other.value) def __sub__(self, other): if not isinstance(other, Decimal): raise ValueError('Arithmetic support limited to other `Decimal`s.') return Decimal(self.value - other.value) def __mul__(self, other): if not isinstance(other, Decimal): raise ValueError('Arithmetic support limited to other `Decimal`s.') return Decimal(self.value * other.value) def __neg__(self): return Decimal(-self.value) def round(self, ndigits=0): """Returns a new `Decimal` rounded to this many decimal places.""" scale = sympy.Integer(10 ** ndigits) numer = sympy.numer(self.value) * scale denom = sympy.denom(self.value) return Decimal(int(round(numer / denom)) / scale) def __round__(self, ndigits): return self.round(ndigits) def __int__(self): """Returns conversion to integer if possible; TypeError if non-integer.""" if self.decimal_places() == 0: return int(self._decimal) else: raise TypeError('Cannot represent {} as an integer.'.format(str(self))) # NOTE: this is implemented in addition to `__cmp__` because SymPy does not # support inequality comparison between sympy objects and objects that are not # convertible to sympy objects (such as strings). def __eq__(self, other): return self.value == other # Python 2 comparison def __cmp__(self, other): if self.value == other: return 0 if self.value < other: return -1 return 1 # Python 3 comparison: def __lt__(self, other): return self.value < other def __le__(self, other): return self.value <= other def __gt__(self, other): return self.value > other def __ge__(self, other): return self.value >= other class Percentage(object): """Container for a percentage.""" def __init__(self, value): """Initializes a `Percentage`. Args: value: Percentage as a fractional value. E.g., pass in `sympy.Rational(2, 5)` to create the percentage "40%". """ self._value = value def _sympy_(self): return self._value def __str__(self): # Display percentages as decimals (not fractions). value = Decimal(self._value * 100) return str(value) + '%' class NonSimpleRational(object): """Container for rational a / b where allow gcd(a, b) > 1.""" def __init__(self, numer, denom): self._numer = numer self._denom = denom @property def numer(self): return self._numer @property def denom(self): return self._denom def __str__(self): return '{}/{}'.format(self._numer, self._denom) class StringNumber(object): """A string representing a number, that can also be sympified.""" def __init__(self, value, join_number_words_with_hyphens=True): """Initializes a `StringNumber`. Args: value: An integer or rational. join_number_words_with_hyphens: Whether to join the words in integers with hyphens when describing as a string. """ self._join_number_words_with_hyphens = join_number_words_with_hyphens self._sympy_value = sympy.sympify(value) self._string = self._to_string(value) def _integer_to_words(self, integer): """Converts an integer to a list of words.""" if integer < 0: raise ValueError('Cannot handle negative numbers.') if integer < 20: return [_INTEGER_LOW[integer]] words = None if integer < 100: tens, ones = divmod(integer, 10) if ones > 0: return [_INTEGER_MID[tens], _INTEGER_LOW[ones]] else: return [_INTEGER_MID[tens]] for value, word in _INTEGER_HIGH: if integer >= value: den, rem = divmod(integer, value) words = self._integer_to_words(den) + [word] if rem > 0: if rem < 100: words.append('and') words += self._integer_to_words(rem) return words def _rational_to_string(self, rational): """Converts a rational to words, e.g., "two thirds".""" numer = sympy.numer(rational) denom = sympy.denom(rational) numer_words = self._to_string(numer) if denom == 1: return numer_words if denom <= 0 or denom >= len(_PLURAL_DENOMINATORS): raise ValueError('Unsupported denominator {}.'.format(denom)) if numer == 1: denom_word = _SINGULAR_DENOMINATORS[denom] else: denom_word = _PLURAL_DENOMINATORS[denom] return '{} {}'.format(numer_words, denom_word) def _to_string(self, number): """Converts an integer or rational to words.""" if isinstance(number, sympy.Integer) or isinstance(number, int): words = self._integer_to_words(number) join_char = '-' if self._join_number_words_with_hyphens else ' ' return join_char.join(words) elif isinstance(number, sympy.Rational): return self._rational_to_string(number) else: raise ValueError('Unable to handle number {} with type {}.' .format(number, type(number))) def _sympy_(self): return self._sympy_value def __str__(self): return self._string class StringOrdinal(object): """A string representation of an ordinal, e.g., "first".""" def __init__(self, position): """Initializes a `StringOrdinal`. Args: position: An integer >= 0. Raises: ValueError: If `position` is non-positive or out of range. """ if position < 0 or position >= len(_ORDINALS): raise ValueError('Unsupported ordinal {}.'.format(position)) self._string = _ORDINALS[position] def __str__(self): return self._string class NumberList(object): """Contains a list of numbers, intended for display.""" def __init__(self, numbers): self._numbers = numbers def __str__(self): """Converts the list to a string. Returns: Human readable string. Raises: ValueError: if any of the strings contain a comma and thus would lead to an ambigious representation. """ strings = [] for number in self._numbers: string = str(number) if ',' in string: raise ValueError('String representation of the list will be ambigious, ' 'since term "{}" contains a comma.'.format(string)) strings.append(string) return ', '.join(strings) class NumberInBase(object): """Contains value, represented in a given base.""" def __init__(self, value, base): """Initializes a `NumberInBase`. Args: value: Positive or negative integer. base: Integer in the range [2, 36]. Raises: ValueError: If base is not in the range [2, 36] (since this is the limit that can be represented by 10 numbers plus 26 letters). """ if not 2 <= base <= 36: raise ValueError('base={} must be in the range [2, 36]'.format(base)) self._value = value self._base = base chars = [] remainder = abs(value) while True: digit = remainder % base char = str(digit) if digit <= 9 else chr(ord('a') + digit - 10) chars.append(char) remainder = int(remainder / base) if remainder == 0: break if value < 0: chars.append('-') self._str = ''.join(reversed(chars)) def __str__(self): return self._str def _sympy_(self): return self._value
mathematics_dataset-master
mathematics_dataset/util/display.py
# Copyright 2018 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Combinatorics utility functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import random # Dependency imports from six.moves import range from six.moves import zip def uniform_positive_integers_with_sum(count, sum_): """Returns list of size `count` of integers >= 1, summing to `sum_`.""" assert sum_ >= 0 if count > sum_: raise ValueError('Cannot find {} numbers >= 1 with sum {}' .format(count, sum_)) if count == 0: return [] # Select `count - 1` numbers from {1, ..., sum_ - 1} separators = random.sample(list(range(1, sum_)), count - 1) separators = sorted(separators) return [right - left for left, right in zip([0] + separators, separators + [sum_])] def uniform_non_negative_integers_with_sum(count, sum_): """Returns list of size `count` of integers >= 0, summing to `sum_`.""" positive = uniform_positive_integers_with_sum(count, sum_ + count) return [i - 1 for i in positive] def log_number_binary_trees(size): """Returns (nat) log of number of binary trees with `size` internal nodes.""" # This is equal to log of C_size, where C_n is the nth Catalan number. assert isinstance(size, int) assert size >= 0 log = 0.0 for k in range(2, size + 1): log += math.log(size + k) - math.log(k) return log
mathematics_dataset-master
mathematics_dataset/util/combinatorics.py
# Copyright 2018 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for mathematics_dataset.util.probability.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # Dependency imports from absl.testing import absltest from mathematics_dataset.util import probability import sympy class FiniteProductEventTest(absltest.TestCase): def testAllSequences(self): event = probability.FiniteProductEvent([probability.DiscreteEvent({1, 2}), probability.DiscreteEvent({3})]) all_sequences = [i for i in event.all_sequences()] self.assertEqual(all_sequences, [(1, 3), (2, 3)]) class CountLevelSetEventTest(absltest.TestCase): def testAllSequences(self): event = probability.CountLevelSetEvent({'a': 2, 'b': 4, 'c': 1}) all_sequences = event.all_sequences() # Number of sequences should be 7! / (4! * 2! * 1!) = 105. self.assertLen(all_sequences, 105) # They should all be unique. self.assertEqual(len(all_sequences), len(set(all_sequences))) # And check contains one correctly generated tuple. self.assertIn(('a', 'b', 'c', 'b', 'b', 'a', 'b'), all_sequences) class DiscreteProbabilitySpaceTest(absltest.TestCase): def testBasic(self): space = probability.DiscreteProbabilitySpace({0: 1, 1: 2, 2: 3}) p = space.probability(probability.DiscreteEvent([0])) self.assertEqual(p, sympy.Rational(1, 6)) p = space.probability(probability.DiscreteEvent([0, 1])) self.assertEqual(p, sympy.Rational(1, 2)) p = space.probability(probability.DiscreteEvent([0, 1, 2])) self.assertEqual(p, 1) p = space.probability(probability.DiscreteEvent([0, 1, 2, 3])) self.assertEqual(p, 1) p = space.probability(probability.DiscreteEvent([3])) self.assertEqual(p, 0) class FiniteProductSpaceTest(absltest.TestCase): def testProbability_FiniteProductEvent(self): # 5 coin flips of a biased coin with heads prob = 1/3. base_space = probability.DiscreteProbabilitySpace({'h': 1, 't': 2}) space = probability.FiniteProductSpace([base_space] * 5) heads = probability.DiscreteEvent({'h'}) tails = probability.DiscreteEvent({'t'}) event = probability.FiniteProductEvent([heads, heads, tails, tails, heads]) self.assertEqual(space.probability(event), sympy.Rational(4, 3**5)) def testProbability_CountLevelSetEvent(self): base_space = probability.DiscreteProbabilitySpace({'a': 2, 'b': 3, 'c': 5}) space = probability.FiniteProductSpace([base_space] * 12) event = probability.CountLevelSetEvent({'a': 7, 'b': 2, 'c': 3}) # Probability should be (12 choose 7 2 3) * p(a)^7 p(b)^2 p(c)^3 coeff = 7920 p_a = sympy.Rational(1, 5) p_b = sympy.Rational(3, 10) p_c = sympy.Rational(1, 2) self.assertEqual(space.probability(event), coeff * pow(p_a, 7) * pow(p_b, 2) * pow(p_c, 3)) class SampleWithoutReplacementSpaceTest(absltest.TestCase): def testBasic(self): space = probability.SampleWithoutReplacementSpace({0: 1, 1: 1}, 2) event_0_0 = probability.FiniteProductEvent( [probability.DiscreteEvent({0}), probability.DiscreteEvent({0})]) event_0_1 = probability.FiniteProductEvent( [probability.DiscreteEvent({0}), probability.DiscreteEvent({1})]) p_0_0 = space.probability(event_0_0) p_0_1 = space.probability(event_0_1) self.assertEqual(p_0_0, 0) self.assertEqual(p_0_1, sympy.Rational(1, 2)) space = probability.SampleWithoutReplacementSpace({0: 1, 1: 0}, 1) event_0 = probability.FiniteProductEvent([probability.DiscreteEvent({0})]) event_1 = probability.FiniteProductEvent([probability.DiscreteEvent({1})]) event_2 = probability.FiniteProductEvent([probability.DiscreteEvent({2})]) p_0 = space.probability(event_0) p_1 = space.probability(event_1) p_2 = space.probability(event_2) self.assertEqual(p_0, 1) self.assertEqual(p_1, 0) self.assertEqual(p_2, 0) class DiscreteRandomVariableTest(absltest.TestCase): def testCall(self): random_variable = probability.DiscreteRandomVariable({1: 1, 2: 3, 3: 4}) forwards = random_variable(probability.DiscreteEvent({1, 3})) self.assertEqual(forwards.values, {1, 4}) def testInverse(self): random_variable = probability.DiscreteRandomVariable({1: 1, 2: 3, 3: 4}) inverse = random_variable.inverse(probability.DiscreteEvent({1, 3})) self.assertEqual(inverse.values, {1, 2}) random_variable = probability.DiscreteRandomVariable({1: 1, 2: 1}) inverse = random_variable.inverse(probability.DiscreteEvent({1, 5})) self.assertEqual(inverse.values, {1, 2}) class FiniteProductRandomVariableTest(absltest.TestCase): def _random_variable(self): rv1 = probability.DiscreteRandomVariable({1: 'a', 2: 'b', 3: 'c'}) rv2 = probability.DiscreteRandomVariable({1: 'x', 2: 'y', 3: 'x'}) return probability.FiniteProductRandomVariable((rv1, rv2)) def testCall_FiniteProductEvent(self): rv = self._random_variable() event1 = probability.DiscreteEvent({1, 2}) event2 = probability.DiscreteEvent({1, 3}) event = probability.FiniteProductEvent((event1, event2)) result = rv(event) self.assertIsInstance(result, probability.FiniteProductEvent) self.assertLen(result.events, 2) self.assertEqual(result.events[0].values, {'a', 'b'}) self.assertEqual(result.events[1].values, {'x'}) def testInverse_FiniteProductEvent(self): rv = self._random_variable() event1 = probability.DiscreteEvent({'a', 'b'}) event2 = probability.DiscreteEvent({'x'}) event = probability.FiniteProductEvent((event1, event2)) result = rv.inverse(event) self.assertIsInstance(result, probability.FiniteProductEvent) self.assertLen(result.events, 2) self.assertEqual(result.events[0].values, {1, 2}) self.assertEqual(result.events[1].values, {1, 3}) def testInverse_CountLevelSetEvent(self): rv = self._random_variable() event = probability.CountLevelSetEvent({'a': 1, 'x': 1}) result = rv.inverse(event) sequences = result.all_sequences() self.assertLen(sequences, 2) self.assertEqual(set(sequences), {(1, 1), (1, 3)}) if __name__ == '__main__': absltest.main()
mathematics_dataset-master
mathematics_dataset/util/probability_test.py
# Copyright 2018 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Functionality for working with probability spaces and random variables. Basic recap of probability theory, and thus of classes in this file: * A probability space is a (finite or infinite) set Omega with a probability measure defined on this. * A random variable is a mapping from a probability space to another measure space. * An event is a measurable set in a sample space. For example, suppose a bag contains 3 balls: two red balls, and one white ball. This could be represented by a discrete probability space of size 3 with elements {1, 2, 3}, with equal measure assigned to all 3 elements; and a random variable that maps 1->red, 2->red, and 3->white. Then the probability of drawing a red ball is the measure in the probability space of the inverse under the random variable mapping of {red}, i.e., of {1, 2}, which is 2/3. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import itertools # Dependency imports import six from six.moves import zip import sympy @six.add_metaclass(abc.ABCMeta) class Event(object): """Represents an event in a measure space.""" @six.add_metaclass(abc.ABCMeta) class ProbabilitySpace(object): """Represents a probability space.""" @abc.abstractmethod def probability(self, event): """Returns the probability of an event.""" @six.add_metaclass(abc.ABCMeta) class RandomVariable(object): """Random variable; a mapping from a probability space to a measure space.""" @abc.abstractmethod def __call__(self, event): """Maps an `_Event` in the probability space to one in the sample space.""" @abc.abstractmethod def inverse(self, event): """Maps event in the sample space back to the inverse in the prob. space.""" class DiscreteEvent(Event): """Set of discrete values.""" def __init__(self, values): self._values = values @property def values(self): return self._values class FiniteProductEvent(Event): """Event consisting of cartesian product of events.""" def __init__(self, events): """Initializes a `FiniteProductEvent`. Args: events: Tuple of `Event`s; resulting event will be cartesian product of these. """ self._events = events @property def events(self): return self._events def all_sequences(self): """Returns iterator of sequences by selecting a single event in each coord. This assumes that every component event is an instance of `DiscreteEvent`. Returns: Iterator over tuples of values. Raises: ValueError: If one of the component events is not a `DiscreteEvent`. """ if not all(isinstance(event, DiscreteEvent) for event in self._events): raise ValueError('Not all component events are DiscreteEvents') values_list = [event.values for event in self._events] return itertools.product(*values_list) class CountLevelSetEvent(Event): """Event of all sequences with fixed number of different values occurring.""" def __init__(self, counts): """Initializes `CountLevelSetEvent`. E.g., to construct the event of getting two red balls and one green ball, pass `counts = {red: 2, green: 1}`. (Then `all_sequences()` would return `[(red, red, green), (red, green, red), (green, red, red)]`. Args: counts: Dictionary mapping values to the number of times they occur in a sequence. """ self._counts = counts self._all_sequences = None @property def counts(self): return self._counts def all_sequences(self): """Returns all sequences generated by this level set.""" if self._all_sequences is None: # Generate via dynamic programming. cache = {} # dict mapping tuple -> list of tuples labels = list(self._counts.keys()) def generate(counts): """Returns list of tuples for given `counts` of labels.""" if sum(counts) == 0: return [()] counts = tuple(counts) if counts in cache: return cache[counts] generated = [] for i, count in enumerate(counts): if count == 0: continue counts_minus = list(counts) counts_minus[i] -= 1 counts_minus = tuple(counts_minus) extensions = generate(counts_minus) generated += [tuple([labels[i]] + list(extension)) for extension in extensions] cache[counts] = generated return generated self._all_sequences = generate(list(self._counts.values())) return self._all_sequences class SequenceEvent(Event): """Collection of sequences.""" def __init__(self, sequences): self._sequences = sequences def all_sequences(self): return self._sequences def normalize_weights(weights): """Normalizes the weights (as sympy.Rational) in dictionary of weights.""" weight_sum = sum(six.itervalues(weights)) return { i: sympy.Rational(weight, weight_sum) for i, weight in six.iteritems(weights) } class DiscreteProbabilitySpace(ProbabilitySpace): """Discrete probability space.""" def __init__(self, weights=None): """Initializes an `DiscreteProbabilitySpace`. Args: weights: Dictionary mapping values to relative probability of selecting that value. This will be normalized. """ self._weights = normalize_weights(weights) def probability(self, event): if isinstance(event, DiscreteEvent): return sum(self._weights[value] for value in event.values if value in self._weights) else: raise ValueError('Unhandled event type {}'.format(type(event))) @property def weights(self): """Returns dictionary of probability of each element.""" return self._weights class FiniteProductSpace(ProbabilitySpace): """Finite cartesian product of probability spaces.""" def __init__(self, spaces): """Initializes a `FiniteProductSpace`. Args: spaces: List of `ProbabilitySpace`. """ self._spaces = spaces def all_spaces_equal(self): return all([self._spaces[0] == space for space in self._spaces]) def probability(self, event): # Specializations for optimization. if isinstance(event, FiniteProductEvent): assert len(self._spaces) == len(event.events) return sympy.prod([ space.probability(event_slice) for space, event_slice in zip(self._spaces, event.events)]) if isinstance(event, CountLevelSetEvent) and self.all_spaces_equal(): space = self._spaces[0] counts = event.counts probabilities = { value: space.probability(DiscreteEvent({value})) for value in six.iterkeys(counts) } num_events = sum(six.itervalues(counts)) assert num_events == len(self._spaces) # Multinomial coefficient: coeff = ( sympy.factorial(num_events) / sympy.prod( [sympy.factorial(i) for i in six.itervalues(counts)])) return coeff * sympy.prod([ pow(probabilities[value], counts[value]) for value in six.iterkeys(counts) ]) raise ValueError('Unhandled event type {}'.format(type(event))) @property def spaces(self): """Returns list of spaces.""" return self._spaces class SampleWithoutReplacementSpace(ProbabilitySpace): """Probability space formed by sampling discrete space without replacement.""" def __init__(self, weights, n_samples): """Initializes a `SampleWithoutReplacementSpace`. Args: weights: Dictionary mapping values to relative probability of selecting that value. This will be normalized. n_samples: Number of samples to draw. Raises: ValueError: If `n_samples > len(weights)`. """ if n_samples > len(weights): raise ValueError('n_samples is more than number of discrete elements') self._weights = normalize_weights(weights) self._n_samples = n_samples @property def n_samples(self): """Number of samples to draw.""" return self._n_samples def probability(self, event): try: all_sequences = event.all_sequences() except AttributeError: raise ValueError('Unhandled event type {}'.format(type(event))) probability_sum = 0 for sequence in all_sequences: if len(sequence) != len(set(sequence)): continue # not all unique, so not "without replacement". p_sequence = 1 removed_prob = 0 for i in sequence: p = self._weights[i] if i in self._weights else 0 if p == 0: p_sequence = 0 break p_sequence *= p / (1 - removed_prob) removed_prob += p probability_sum += p_sequence return probability_sum class IdentityRandomVariable(RandomVariable): """Identity map of a probability space.""" def __call__(self, event): return event def inverse(self, event): return event class DiscreteRandomVariable(RandomVariable): """Specialization to discrete random variable. This is simply a mapping from a discrete space to a discrete space (dictionary lookup). """ def __init__(self, mapping): """Initializes `DiscreteRandomVariable` from `mapping` dict.""" self._mapping = mapping self._inverse = {} for key, value in six.iteritems(mapping): if value in self._inverse: self._inverse[value].add(key) else: self._inverse[value] = set([key]) def __call__(self, event): if isinstance(event, DiscreteEvent): return DiscreteEvent({self._mapping[value] for value in event.values}) else: raise ValueError('Unhandled event type {}'.format(type(event))) def inverse(self, event): if isinstance(event, DiscreteEvent): set_ = set() for value in event.values: if value in self._inverse: set_.update(self._inverse[value]) return DiscreteEvent(set_) else: raise ValueError('Unhandled event type {}'.format(type(event))) class FiniteProductRandomVariable(RandomVariable): """Product random variable. This has the following semantics. Let this be X = (X_1, ..., X_n). Then X(w) = (X_1(w_1), ..., X_n(w_n)) (the sample space is assumed to be of sequence type). """ def __init__(self, random_variables): """Initializes a `FiniteProductRandomVariable`. Args: random_variables: Tuple of `RandomVariable`. """ self._random_variables = random_variables def __call__(self, event): if isinstance(event, FiniteProductEvent): assert len(event.events) == len(self._random_variables) zipped = list(zip(self._random_variables, event.events)) return FiniteProductEvent( [random_variable(sub_event) for random_variable, sub_event in zipped]) else: raise ValueError('Unhandled event type {}'.format(type(event))) def inverse(self, event): # Specialization for `FiniteProductEvent`; don't need to take all sequences. if isinstance(event, FiniteProductEvent): assert len(event.events) == len(self._random_variables) zipped = list(zip(self._random_variables, event.events)) return FiniteProductEvent(tuple( random_variable.inverse(sub_event) for random_variable, sub_event in zipped)) # Try fallback of mapping each sequence separately. try: all_sequences = event.all_sequences() except AttributeError: raise ValueError('Unhandled event type {}'.format(type(event))) mapped = set() for sequence in all_sequences: assert len(sequence) == len(self._random_variables) zipped = list(zip(self._random_variables, sequence)) mapped_sequence = FiniteProductEvent(tuple( random_variable.inverse(DiscreteEvent({element})) for random_variable, element in zipped)) mapped.update(mapped_sequence.all_sequences()) return SequenceEvent(mapped)
mathematics_dataset-master
mathematics_dataset/util/probability.py
# Copyright 2018 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """For performing module composition.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import random import string # Dependency imports from mathematics_dataset.sample import number from mathematics_dataset.sample import ops from mathematics_dataset.sample import polynomials from mathematics_dataset.util import combinatorics from mathematics_dataset.util import display import numpy as np import six from six.moves import range from six.moves import zip import sympy # Allowed symbols. Don't allow "e", as sympy can hang when printing it as a # function symbol (and it's reserved for exponent). _ALLOWED_SYMBOLS = set(string.ascii_lowercase).difference(set(['e'])) class Polynomial(collections.namedtuple('Polynomial', ('coefficients'))): """Value wrapper for a polynomial function. Attributes: coefficients: Numpy array of coefficients; see `polynomials.py`. """ def __new__(cls, coefficients): coefficients = np.asarray(coefficients) return super(Polynomial, cls).__new__(cls, coefficients) def is_polynomial(value): return isinstance(value, Polynomial) def is_integer_polynomial(value): if not is_polynomial(value): return False coefficients = np.reshape(value.coefficients, [-1]) return all(number.is_integer(coeff) for coeff in coefficients) # List of pairs of `(filter, sampler)`, where `filter` is a function returning # True if the sampler is valid for the given value, and `sampler` returns an # `Entity`. _FILTERS_AND_SAMPLERS = [] def module(filter_): """Returns a Decorator for a module function. The returned decorator adds the function to the library of known modules. Args: filter_: Callable determining whether the module can handle a given value. Returns: Decorator that adds the module function to the library. """ def decorator(module_fn): """Decorates a module function.""" _FILTERS_AND_SAMPLERS.append((filter_, module_fn)) return module_fn return decorator class SampleArgs( collections.namedtuple('SampleArgs', ('num_modules', 'entropy'))): """For sampling mathematical entities / questions.""" def peel(self, frac=1): """Peels one (or `frac`) of a module's entropy. In addition to a portion of the entropy, this returns a new `SampleArgs` (since this object is immutable), which you should use when creating child modules. Args: frac: Float; proportion of module's entropy to take. Returns: Triple `(entropy, new_sample_args)`, where `new_sample_args` is a new `SampleArgs` with the entropy removed. """ entropy = frac * self.entropy / self.num_modules new_sample_args = SampleArgs( num_modules=self.num_modules, entropy=self.entropy - entropy) return entropy, new_sample_args def split(self, count): """Splits the entropy and module counts up. Args: count: Integer >= 1; the split size. Returns: List of `SampleArgs` of length `count`, to be passed to create child entities. Raises: ValueError: If it was not possible to use up all the entropy, for example, all requested types were `WithValue`. """ num_child_modules = self.num_modules - 1 # Sample module counts at random module_counts = combinatorics.uniform_non_negative_integers_with_sum( count, num_child_modules) if num_child_modules == 0: if self.entropy > 0: raise ValueError('Unused entropy') entropies = np.zeros(count) else: entropies = self.entropy * np.random.dirichlet( np.maximum(1e-9, module_counts)) sample_args = [] for i, num_modules in enumerate(module_counts): child_sample_args = SampleArgs( num_modules=num_modules, entropy=entropies[i]) sample_args.append(child_sample_args) return sample_args class PreSampleArgs( collections.namedtuple( 'PreSampleArgs', ('min_modules', 'max_modules', 'min_entropy', 'max_entropy'))): """Sample args before module count and entropy have been sampled.""" def __call__(self): """Samples `SampleArgs`.""" return SampleArgs( num_modules=random.randint(self.min_modules, self.max_modules), entropy=random.uniform(self.min_entropy, self.max_entropy)) def peel(self, *args, **kwargs): sample_args = self() return sample_args.peel(*args, **kwargs) def split(self, *args, **kwargs): sample_args = self() return sample_args.split(*args, **kwargs) class FunctionHandle(object): """Special handle to allow function composition. For example, suppose fn1 = f o g fn2 = h and we want to display fn1(fn2(x)) = f(g(h(x))). This function basically just stores the list of sympy functions. """ def __init__(self, *function_entities): """Initialize a `FunctionHandle`. Args: *function_entities: List of function letters and `Entity`s representing functions, to be composed. """ self._functions = [] for fn in function_entities: if isinstance(fn, str): functions = [sympy.Function(fn)] else: assert isinstance(fn, Entity) assert isinstance(fn.handle, FunctionHandle) functions = fn.handle.functions self._functions += functions def apply(self, *input_): """Returns f(g(...(input)...)) where f, g, ... are the functions.""" result = None for function in reversed(self._functions): if result is None: result = function(*input_) else: result = function(result) return result @property def functions(self): return self._functions def __str__(self): raise ValueError('This should not be directly converted to a string') def _polynomial_entity(value, context): """Create a generic `Entity` describing a polynomial.""" assert isinstance(value, Polynomial) coefficients = np.asarray(value.coefficients) num_variables = coefficients.ndim variables = [sympy.Symbol(context.pop()) for _ in range(num_variables)] function_symbol = context.pop() handle = FunctionHandle(function_symbol) handle_description = sympy.Function(function_symbol)(*variables) polynomial = polynomials.coefficients_to_polynomial(coefficients, variables) polynomial = polynomial.sympy() return Entity( context=context, value=value, expression=polynomial, polynomial_variables=variables, description='Let {function} = {polynomial}.', handle=handle, function=handle_description, polynomial=polynomial) class Context(object): """Keeps track of used symbols, and sampling of children. Each context is associated with an entity. Entities are constructed in a tree-like fashion. """ def __init__(self, relation_symbols=None): """Initializes a `Context`. Args: relation_symbols: Set of symbols used "externally": this means (with reference to the tree in which this context sits) all symbols occurring that aren't in this node or sub-nodes. """ if relation_symbols is None: relation_symbols = set() else: assert isinstance(relation_symbols, set) for symbol in relation_symbols: assert isinstance(symbol, str) self._relation_symbols = relation_symbols self._self_symbols = set() self._child_symbols = set() self._module_count = 1 self._child_entities = [] @property def relation_symbols(self): return self._relation_symbols.copy() @property def self_symbols(self): return self._self_symbols.copy() @property def child_symbols(self): return self._child_symbols.copy() @property def child_entities(self): return self._child_entities[:] def pop(self): """Returns an unused symbol (and keeps track of it being used).""" allowed = (_ALLOWED_SYMBOLS .difference(self._relation_symbols) .difference(self._self_symbols) .difference(self._child_symbols)) if not allowed: raise ValueError('Ran out of symbols') symbol = random.choice(list(allowed)) self._self_symbols.add(symbol) return symbol def mark_used(self, symbol): """Marks a given symbol as used.""" assert isinstance(symbol, str) if (symbol in self._relation_symbols or symbol in self._self_symbols or symbol in self._child_symbols): raise ValueError('Symbol {} already used'.format(symbol)) self._self_symbols.add(symbol) @property def module_count(self): """Returns the number of modules sampled.""" return self._module_count def _sampler(self, value, sample_args): """Returns a sampler appropriate for the given args. Args: value: Target value. sample_args: Instance of `SampleArgs` controlling entropy etc. Returns: A sampler for producing entities. Raises: ValueError: If no valid samplers were found. """ valid = [] for filter_, sampler in _FILTERS_AND_SAMPLERS: if filter_(value): valid.append(sampler) if not valid: raise ValueError('No valid samplers found: value={} sample_args={}' .format(value, sample_args)) return random.choice(valid) def _value_entity(self, value, context): if isinstance(value, (sympy.Integer, sympy.Rational, display.Decimal)): return Entity(context=context, value=value, handle=value) if isinstance(value, Polynomial): return _polynomial_entity(value, context) raise ValueError('Don\'t know how to handle value={} of type {}' .format(value, type(value))) def sample(self, sample_args, values): """Sample multiple entities. Args: sample_args: Instance of `SampleArgs`. The min and max entropy and module count will be split up betwene the various entities sampled. values: List of values to sample. Returns: List of `Entity` of the same length as `types`. Raises: RuntimeError: If one of the modules generates a non-`Entity`. """ # Can only sample children once. assert self._module_count == 1 assert not self._child_symbols assert not self._child_entities if isinstance(sample_args, PreSampleArgs): sample_args = sample_args() sample_args_split = sample_args.split(len(values)) def all_symbols(): return (self._relation_symbols .union(self._self_symbols) .union(self._child_symbols)) for value, child_sample_args in zip(values, sample_args_split): if number.is_integer(value): value = sympy.Integer(value) all_symbols_ = all_symbols() context = Context(all_symbols_) if child_sample_args.num_modules == 0: entity = self._value_entity(value, context) else: sampler = self._sampler(value, child_sample_args) entity = sampler(value, child_sample_args, context) if not isinstance(entity, Entity): raise RuntimeError( 'Expected entity, but got {} instead'.format(entity)) if (not number.is_integer_or_rational_or_decimal(entity.value) and not isinstance(entity.value, Polynomial)): raise RuntimeError('sampler {} returned invalid value of type {}' .format(sampler, type(entity.value))) if ((number.is_integer_or_rational_or_decimal(value) and entity.value != value) or (isinstance(value, Polynomial) and not np.array_equal( entity.value.coefficients, value.coefficients))): raise RuntimeError( 'entity values differ, sampler={} wanted={} got={}' .format(sampler, value, entity.value)) if child_sample_args.num_modules != context.module_count: raise RuntimeError( 'unused modules, value={} sample_args={} context.module_count={},' ' sampler={}' .format(value, child_sample_args, context.module_count, sampler)) self._module_count += context.module_count self._child_entities.append(entity) for symbol in context.self_symbols.union(context.child_symbols): assert symbol not in all_symbols_ self._child_symbols.add(symbol) return self._child_entities def sample_by_replacing_constants(self, sample_args, expressions): """Replaces some of the constants with handles from other modules.""" max_children = sample_args.num_modules - 1 if max_children <= 0: return if isinstance(expressions, ops.Op): expressions = [expressions] constants = ops.number_constants(expressions) if not constants: raise ValueError('No constants to replace in {}' .format([str(expr) for expr in expressions])) sample_count = random.randint(1, min(max_children, len(constants))) constants = random.sample(constants, sample_count) values = [constant.value for constant in constants] entities = self.sample(sample_args, values) for constant, entity in zip(constants, entities): constant.value = entity.handle def expand_entities(context, **kwargs): """Returns prefix description and updated `**kwargs`. Args: context: Instance of `Context` containing all `Entity`s that occur. **kwargs: Dictionary of key/value pairs, some of which are `Entity`s. Returns: Pair `(child_description, new_kwargs)`. `child_description` is a description of the entities contained in `kwargs`, and `new_kwargs` contains handles. """ kwargs = kwargs.copy() entities = set(context.child_entities) for key, maybe_entity in six.iteritems(kwargs): if isinstance(maybe_entity, Entity): entities.add(maybe_entity) kwargs[key] = maybe_entity.handle entities = list(entities) random.shuffle(entities) child_descriptions = [] for entity in entities: child_descriptions.append(entity.child_description) if not entity.expression_used: child_descriptions.append(entity.description) child_description = ' '.join([s for s in child_descriptions if s]) return child_description, kwargs class Entity(object): """An entity (e.g., representing an integer or function). Example usage: ``` new_entity = Entity( context=context, value=17, description='Let {self} be the gcd of {q} and {q}.' p=p, q=q) ``` Above, {self} will be replaced with a new symbol, to be used as the entity handle. """ def __init__(self, context, value, description='', handle=None, expression=None, polynomial_variables=None, **description_kwargs): """Initializes an entity. Args: context: Instance of `Context` keeping track of used symbols and child entities (that may not explicitly occur in `description_kwargs`). value: The value represented by this Entity. description: String, describing this Entity. This can contain '{self}' as a substring, in which case it will be substituted with a new handle (and `context` must be non-None). handle: Optional string/symbol that refers to this Entity. This must always be provided if '{self}' does not occur in `description`. expression: Optional string (or something that can be converted to a string, like ops.Op or sympy.expr) representing the value of this Entity, that can be used directly instead of using `handle`. polynomial_variables: If `expression` provided, then for polynomial entities, the variables used. **description_kwargs: Dict of substitutions (including entities) for use in `description`. Raises: ValueError: If handle specified and '{self}' in description; or neither. """ self._value = value child_description, description_kwargs = expand_entities( context, **description_kwargs) if '{self}' in description: if handle is not None: raise ValueError('Cannot specify handle if {self} in description') handle = context.pop() description_kwargs['self'] = handle handle = sympy.var(handle) else: if handle is None: raise ValueError('Must specify handle if {self} not in description') if isinstance(handle, str): handle = sympy.var(handle) if (isinstance(value, Polynomial) and expression is not None and polynomial_variables is None): raise ValueError('Must provided polynomial_variables') self._child_description = child_description self._description = description.format(**description_kwargs) self._handle = handle self._expression = expression self._polynomial_variables = polynomial_variables # For checking that we don't use both the handle and the expression form of # this entity. self._handle_used = False self._expression_used = False @property def value(self): """The actual value of the entity (e.g., sympy object).""" return self._value @property def child_description(self): """A string describing the entities that this Entity relies on.""" return self._child_description @property def description(self): """A string describing the entity.""" assert not self._expression_used self._handle_used = True return self._description def has_expression(self): """Returns whether there is an expression to use (instead of handle).""" return self._expression is not None @property def handle(self): """A "handle", e.g., SymPy symbol or `function.CompositionHandle`.""" assert not self._expression_used self._handle_used = True return self._handle @property def expression(self): """An expression representing the entity; possibly None. If this is used, then `description` does not need to get used. Returns: String or None. """ assert not self._handle_used self._expression_used = True return self._expression @property def polynomial_variables(self): """For when `expression` is not None, and this entity is a polynomial.""" return self._polynomial_variables @property def expression_used(self): """Returns true if expression instead of handle was used.""" return self._expression_used @property def expression_else_handle(self): """Returns an expression if present, else the handle.""" if self.has_expression(): return self.expression else: return self.handle def __str__(self): """Raises value error - should not attempt to convert to string directly.""" raise ValueError('Should not convert Entity directly to string')
mathematics_dataset-master
mathematics_dataset/util/composition.py
# Copyright 2018 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for mathematics_dataset.util.display.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # Dependency imports from absl.testing import absltest from mathematics_dataset.util import display import sympy class DecimalTest(absltest.TestCase): def testBasic_integer(self): decimal = display.Decimal(123) self.assertEqual(str(decimal), '123') self.assertEqual(sympy.sympify(decimal), sympy.Integer(123)) self.assertEqual(decimal.decimal_places(), 0) def testBasic_ten(self): decimal = display.Decimal(10) self.assertEqual(str(decimal), '10') self.assertEqual(sympy.sympify(decimal), sympy.Integer(10)) self.assertEqual(decimal.decimal_places(), 0) def testBasic(self): decimal = display.Decimal(sympy.Rational(123, 100)) self.assertEqual(str(decimal), '1.23') self.assertEqual(sympy.sympify(decimal), sympy.Rational(123, 100)) self.assertEqual(decimal.decimal_places(), 2) def testStr(self): self.assertEqual(str(display.Decimal(sympy.Rational(0, 10))), '0') self.assertEqual(str(display.Decimal(sympy.Rational(-1, 10))), '-0.1') self.assertEqual(str(display.Decimal(sympy.Rational(-11, 10))), '-1.1') self.assertEqual(str(display.Decimal(sympy.Rational(11, 10))), '1.1') self.assertEqual(str(display.Decimal(sympy.Rational(101, 1))), '101') self.assertEqual( str(display.Decimal(sympy.Rational(20171, 1000000))), '0.020171') def testStr_verySmall(self): # Tests it doesn't display in "scientific" notation 1E-9. decimal = display.Decimal(sympy.Rational(1, 1000000000)) self.assertEqual(str(decimal), '0.000000001') def testAdd(self): self.assertEqual((display.Decimal(2) + display.Decimal(3)).value, 5) def testSub(self): self.assertEqual((display.Decimal(2) - display.Decimal(3)).value, -1) def testMul(self): self.assertEqual((display.Decimal(2) * display.Decimal(3)).value, 6) def testRound(self): decimal = display.Decimal(sympy.Rational(2675, 1000)) # 2.675 self.assertEqual(sympy.sympify(decimal.round()), sympy.Integer(3)) self.assertEqual(sympy.sympify(decimal.round(1)), sympy.Rational(27, 10)) self.assertEqual(sympy.sympify(decimal.round(2)), sympy.Rational(268, 100)) self.assertEqual(sympy.sympify(decimal.round(3)), sympy.Rational(2675, 1000)) def testInt(self): decimal = display.Decimal(123) self.assertEqual(int(decimal), 123) def testInt_errorIfNonInt(self): decimal = display.Decimal(sympy.Rational(1, 2)) with self.assertRaisesRegex(self, TypeError, 'Cannot represent'): int(decimal) def testComparison(self): decimal = display.Decimal(sympy.Rational(-1, 2)) # pylint: disable=g-generic-assert self.assertFalse(decimal != -0.5) self.assertTrue(decimal != 0) self.assertFalse(decimal < -0.5) self.assertTrue(decimal < 0) self.assertTrue(decimal <= -0.5) self.assertTrue(decimal <= 0) self.assertFalse(decimal > -0.5) self.assertTrue(decimal > -1) self.assertTrue(decimal >= -0.5) self.assertFalse(decimal >= 0) self.assertFalse(decimal == 0) self.assertTrue(decimal == -0.5) def testNegation(self): decimal = display.Decimal(sympy.Rational(1, 2)) decimal = -decimal self.assertNotEqual(decimal, 0.5) self.assertEqual(decimal, -0.5) class PercentageTest(absltest.TestCase): def testPercentage(self): percentage = display.Percentage(1.5) self.assertEqual(str(percentage), '150%') percentage = display.Percentage(sympy.Rational(67, 100)) self.assertEqual(str(percentage), '67%') percentage = display.Percentage(sympy.Rational(67, 1000)) self.assertEqual(str(percentage), '6.7%') class NonSimpleRationalTest(absltest.TestCase): def testBasic(self): frac = display.NonSimpleRational(4, 6) self.assertEqual(frac.numer, 4) self.assertEqual(frac.denom, 6) self.assertEqual(str(frac), '4/6') class StringNumberTest(absltest.TestCase): def testIntegerToWords(self): words = display.StringNumber(0) self.assertEqual(str(words), 'zero') self.assertEqual(sympy.sympify(words), 0) words = display.StringNumber(8) self.assertEqual(str(words), 'eight') self.assertEqual(sympy.sympify(words), 8) words = display.StringNumber(12) self.assertEqual(str(words), 'twelve') self.assertEqual(sympy.sympify(words), 12) words = display.StringNumber(30) self.assertEqual(str(words), 'thirty') self.assertEqual(sympy.sympify(words), 30) words = display.StringNumber(100) self.assertEqual(str(words), 'one-hundred') self.assertEqual(sympy.sympify(words), 100) words = display.StringNumber(103) self.assertEqual(str(words), 'one-hundred-and-three') self.assertEqual(sympy.sympify(words), 103) words = display.StringNumber(15439822) self.assertEqual(str(words), 'fifteen-million-four-hundred-and-thirty-nine' '-thousand-eight-hundred-and-twenty-two') self.assertEqual(sympy.sympify(words), 15439822) def testRationalToWords(self): words = display.StringNumber(sympy.Rational(2, 3)) self.assertEqual(str(words), 'two thirds') class StringOrdinalTest(absltest.TestCase): def testBasic(self): ordinal = display.StringOrdinal(0) self.assertEqual(str(ordinal), 'zeroth') ordinal = display.StringOrdinal(10) self.assertEqual(str(ordinal), 'tenth') def testCreate_errorIfNegative(self): with self.assertRaisesRegex(self, ValueError, 'Unsupported ordinal'): display.StringOrdinal(-1) class NumberListTest(absltest.TestCase): def testBasic(self): numbers = [2, 3, 1] number_list = display.NumberList(numbers) string = str(number_list) self.assertEqual(string, '2, 3, 1') class NumberInBaseTest(absltest.TestCase): def testBasic(self): self.assertEqual(str(display.NumberInBase(1, 10)), '1') self.assertEqual(str(display.NumberInBase(-1, 10)), '-1') self.assertEqual(str(display.NumberInBase(1, 2)), '1') self.assertEqual(str(display.NumberInBase(-1, 2)), '-1') self.assertEqual(str(display.NumberInBase(2, 2)), '10') self.assertEqual(str(display.NumberInBase(-2, 2)), '-10') self.assertEqual(str(display.NumberInBase(10, 16)), 'a') self.assertEqual(str(display.NumberInBase(16, 16)), '10') self.assertEqual(str(display.NumberInBase(256, 16)), '100') self.assertEqual(str(display.NumberInBase(-75483, 10)), '-75483') if __name__ == '__main__': absltest.main()
mathematics_dataset-master
mathematics_dataset/util/display_test.py
# Copyright 2018 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for mathematics_dataset.sample.linear_system.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import random # Dependency imports from absl.testing import absltest from absl.testing import parameterized from mathematics_dataset.sample import linear_system from six.moves import range import sympy class ExpressionWithValueTest(parameterized.TestCase): def testIsTrivialIn(self): self.assertEqual(linear_system._is_trivial_in([[1]], 0), False) self.assertEqual(linear_system._is_trivial_in([[1, 2], [3, 4]], 0), False) self.assertEqual(linear_system._is_trivial_in([[1, 2], [3, 0]], 0), True) self.assertEqual(linear_system._is_trivial_in([[1, 2], [3, 0]], 1), False) self.assertEqual(linear_system._is_trivial_in([[1, 2], [0, 3]], 0), False) self.assertEqual(linear_system._is_trivial_in([[1, 2], [0, 3]], 1), True) @parameterized.parameters([1, 2, 3]) def testLinearSystem(self, degree): for _ in range(100): # test a few times target = [random.randint(-100, 100) for _ in range(degree)] variables = [sympy.Symbol(chr(ord('a') + i)) for i in range(degree)] system = linear_system.linear_system( variables=variables, solutions=target, entropy=10.0) solved = sympy.solve(system, variables) solved = [solved[symbol] for symbol in variables] self.assertEqual(target, solved) if __name__ == '__main__': absltest.main()
mathematics_dataset-master
mathematics_dataset/sample/linear_system_test.py
# Copyright 2018 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Sample arithmetic expressions with a given value.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import math import random # Dependency imports from mathematics_dataset.sample import number from mathematics_dataset.sample import ops from mathematics_dataset.util import combinatorics import numpy as np import six from six.moves import zip import sympy class _SampleArgs(collections.namedtuple('SampleArgs', ('count', 'entropy'))): """For sampling mathematical expressions.""" def peel(self, frac=1): """Peels one (or `frac`) of an op's entropy.""" entropy = frac * self.entropy / self.count new_sample_args = _SampleArgs(self.count, self.entropy - entropy) return entropy, new_sample_args def split(self, args): """Splits the entropy and op counts up.""" non_integer_count = sum(not arg.is_Integer for arg in args) assert non_integer_count <= self.count - 1 count_split = combinatorics.uniform_non_negative_integers_with_sum( len(args), (self.count - 1) - non_integer_count) for i, arg in enumerate(args): if not arg.is_Integer: count_split[i] += 1 if all(count == 0 for count in count_split): assert self.entropy == 0 entropies = np.zeros(len(count_split)) else: entropies = ( np.random.dirichlet(np.maximum(1e-9, count_split)) * self.entropy) return [_SampleArgs(op_count, entropy) for op_count, entropy in zip(count_split, entropies)] def _add_sub_filter(value, sample_args): return sample_args.count >= 2 or value.is_Integer def _add_op(value, sample_args, rationals_allowed): """Returns sampled args for `ops.Add`.""" entropy, sample_args = sample_args.peel() if rationals_allowed and sample_args.count >= 3: x = number.integer_or_rational(entropy, True) else: x = number.integer(entropy, True) if random.choice([False, True]): op_args = [x, value - x] else: op_args = [value - x, x] return ops.Add, op_args, sample_args def _sub_op(value, sample_args, rationals_allowed): """Returns sampled args for `ops.Sub`.""" entropy, sample_args = sample_args.peel() if rationals_allowed and sample_args.count >= 3: x = number.integer_or_rational(entropy, True) else: x = number.integer(entropy, True) if random.choice([False, True]): op_args = [x, x - value] else: op_args = [value + x, x] return ops.Sub, op_args, sample_args def _entropy_of_factor_split(integer): """Returns entropy (log base 10) of decomposing: integer = a * b.""" assert integer.is_Integer if integer == 0: return 0 # Gives dict of form {factor: multiplicity} factors = sympy.factorint(integer) return sum(math.log10(mult + 1) for mult in six.itervalues(factors)) def _split_factors(integer): """Randomly factors integer into product of two integers.""" assert integer.is_Integer if integer == 0: return [1, 0] # Gives dict of form {factor: multiplicity} factors = sympy.factorint(integer) left = sympy.Integer(1) right = sympy.Integer(1) for factor, mult in six.iteritems(factors): left_mult = random.randint(0, mult) right_mult = mult - left_mult left *= factor ** left_mult right *= factor ** right_mult return left, right def _mul_filter(value, sample_args): if sample_args.count >= 2: return True if not value.is_Integer: return False return sample_args.entropy <= _entropy_of_factor_split(value) def _mul_op(value, sample_args, rationals_allowed): """Returns sampled args for `ops.Mul`.""" if sample_args.count >= 3: _, op_args, sample_args = _div_op(value, sample_args, rationals_allowed) op_args = [op_args[0], sympy.Integer(1) / op_args[1]] elif sample_args.count == 1: entropy, sample_args = sample_args.peel() assert _entropy_of_factor_split(value) >= entropy op_args = _split_factors(value) else: assert sample_args.count == 2 entropy, sample_args = sample_args.peel() numer = sympy.numer(value) denom = sympy.denom(value) p1, p2 = _split_factors(numer) entropy -= _entropy_of_factor_split(numer) mult = number.integer(entropy, signed=True, min_abs=1, coprime_to=p1) op_args = [p1 / (mult * denom), p2 * mult] if random.choice([False, True]): op_args = list(reversed(op_args)) return ops.Mul, op_args, sample_args def _div_filter(value, sample_args): del value # unused del sample_args # unused return True def _div_op(value, sample_args, rationals_allowed): """Returns sampled args for `ops.Div`.""" assert rationals_allowed # should be True if this function gets invoked entropy, sample_args = sample_args.peel() numer = sympy.numer(value) denom = sympy.denom(value) if sample_args.count == 1: mult = number.integer(entropy, signed=True, min_abs=1) op_args = [numer * mult, denom * mult] elif sample_args.count == 2: if numer == 0 or random.choice([False, True]): x = number.integer(entropy, signed=True, min_abs=1, coprime_to=denom) op_args = [sympy.Rational(x * numer, denom), x] else: x = number.integer(entropy, signed=True, min_abs=1, coprime_to=numer) op_args = [x, sympy.Rational(x * denom, numer)] else: assert sample_args.count >= 3 p2, p1 = _split_factors(numer) q1, q2 = _split_factors(denom) entropy -= _entropy_of_factor_split(numer) + _entropy_of_factor_split(denom) entropy_r = random.uniform(0, entropy) entropy_s = entropy - entropy_r r = number.integer(entropy_r, signed=True, min_abs=1, coprime_to=q1*p2) s = number.integer(entropy_s, signed=False, min_abs=1, coprime_to=p1*q2) op_args = [sympy.Rational(r*p1, s*q1), sympy.Rational(r*q2, s*p2)] return ops.Div, op_args, sample_args def _arithmetic(value, sample_args, add_sub, mul_div): """Internal arithmetic thingy....""" assert sample_args.count >= 0 if sample_args.count == 0: assert sample_args.entropy == 0 return ops.Constant(value) allowed = [] if add_sub and _add_sub_filter(value, sample_args): allowed.append(_add_op) allowed.append(_sub_op) if mul_div and _mul_filter(value, sample_args): allowed.append(_mul_op) if mul_div and _div_filter(value, sample_args): allowed.append(_div_op) if not allowed: raise ValueError( 'No valid ops found, add_sub={} mul_div={} value={} sample_args={}' .format(add_sub, mul_div, value, sample_args)) choice = random.choice(allowed) op, args, sample_args = choice(value, sample_args, rationals_allowed=mul_div) sample_args = sample_args.split(args) child_expressions = [_arithmetic(arg, child_sample_arg, add_sub, mul_div) for arg, child_sample_arg in zip(args, sample_args)] return op(*child_expressions) def length_range_for_entropy(entropy): """Returns length range to sample from for given entropy.""" min_length = 3 max_length = min_length + int(entropy / 2) return min_length, max_length def arithmetic(value, entropy, length=None, add_sub=True, mul_div=True): """Generates an arithmetic expression with a given value. Args: value: Target value (integer or rational). entropy: Amount of randomness to use in generating expression. length: Number of ops to use. If `None` then suitable length will be picked based on entropy by sampling within the range `length_range_for_entropy`. add_sub: Whether to include addition and subtraction operations. mul_div: Whether to include multiplication and division operations. Returns: Instance of `ops.Op` containing expression. """ assert isinstance(entropy, float) if length is None: min_length, max_length = length_range_for_entropy(entropy) length = random.randint(min_length, max_length) # Some entropy used up in sampling the length. entropy -= math.log10(max_length - min_length + 1) else: assert isinstance(length, int) # Entropy adjustment, because different binary trees (from sampling ops) can # lead to the same expression. This is the correct value when we use just # addition as the op, and is otherwise an an upper bound. entropy += combinatorics.log_number_binary_trees(length) / math.log(10) value = sympy.sympify(value) sample_args = _SampleArgs(length, entropy) return _arithmetic(value, sample_args, add_sub, mul_div)
mathematics_dataset-master
mathematics_dataset/sample/arithmetic.py
# Copyright 2018 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Generate linear systems with given set of solutions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import random # Dependency imports from mathematics_dataset.sample import number from mathematics_dataset.sample import ops from mathematics_dataset.sample import polynomials import numpy as np from six.moves import range import sympy def _make_equals_zero_split(monomials): """Returns an `ops.Eq` containing sum of monomials split on left and right.""" left = [] right = [] for monomial in monomials: if random.choice([False, True]): left.append(monomial) else: right.append(ops.Neg(monomial)) if not left: left = [0] if not right: right = [0] left = ops.Add(*left) right = ops.Add(*right) return ops.Eq(left, right) def _is_trivial_in(matrix, variable): """Returns true if matrix_ij == 0 for some i and all j != variable.""" matrix = np.asarray(matrix) assert matrix.ndim == 2 and matrix.shape[0] == matrix.shape[1] size = matrix.shape[0] if size == 1: return False for i in range(size): all_zero = True for j in range(size): if j != variable and matrix[i, j] != 0: all_zero = False break if all_zero: return True return False def _invertible_matrix(degree, entropy, non_trivial_in): """Generates random invertible matrix.""" matrix_entropies = entropy * np.random.dirichlet(np.ones(degree * degree)) matrix_entropies = np.reshape(matrix_entropies, [degree, degree]) matrix_entropies = np.maximum(1, matrix_entropies) while True: def gen(i, j): return number.integer(matrix_entropies[i, j], True) matrix = [[gen(i, j) for i in range(degree)] for j in range(degree)] # pylint: disable=g-complex-comprehension if non_trivial_in is not None and _is_trivial_in(matrix, non_trivial_in): continue if sympy.det(sympy.Matrix(matrix)) != 0: break matrix = np.asarray(matrix).astype(int) return matrix def linear_system(variables, solutions, entropy, non_trivial_in=None, length=None): """Returns a linear system (set of equalities) with the given solutions. Args: variables: List of variables. solutions: List of solutions, of the same length as `variables`. entropy: Float >= 0; the entropy used. non_trivial_in: Optional integer corresponding to a variable for which the solution shouldn't be "trivial". E.g., "solve a + b = 3, a = -2 for a" is disallowed if `variables[non_trivial_in] == 'a'`. length: Total number of terms appearing; if `None` then selected wisely. Returns: List of `ops.Eq`. """ degree = len(variables) assert degree == len(solutions) frac_entropy_matrix = random.uniform(1/3, 2/3) matrix = _invertible_matrix( degree, entropy * frac_entropy_matrix, non_trivial_in) solutions = np.asarray(solutions) constant = np.matmul(matrix, solutions.astype(int)) flattened = np.concatenate([np.reshape(matrix, [degree * degree]), constant]) is_zero = flattened == 0 if length is None: min_length = np.count_nonzero(flattened) + 1 max_length = max(min_length, 1 + int(degree * (1 + entropy / 2))) length = random.randint(min_length, max_length) counts = polynomials.expanded_coefficient_counts( length=length, is_zero=is_zero) entropies = (1 - frac_entropy_matrix) * entropy * np.random.dirichlet( np.maximum(1e-9, counts - 1)) terms = [] for i in range(len(flattened)): coeffs = polynomials.integers_with_sum( value=flattened[i], count=counts[i], entropy=entropies[i]) terms.append(coeffs) matrix = terms[:degree*degree] constant = terms[-degree:] equations = [] for row_index in range(degree): monomials = [] for col_index in range(degree): for term in matrix[row_index * degree + col_index]: monomials.append(polynomials.monomial(term, variables[col_index], 1)) for term in constant[row_index]: monomials.append(polynomials.monomial(-term, None, 0)) equations.append(_make_equals_zero_split(monomials)) return equations
mathematics_dataset-master
mathematics_dataset/sample/linear_system.py
# Copyright 2018 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Generate random integers and rationals with minimum guarantees on entropy.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import random # Dependency imports from mathematics_dataset.util import display import numpy as np import six import sympy def _coprime_density(value): """Returns float > 0; asymptotic density of integers coprime to `value`.""" factors = sympy.factorint(value) density = 1.0 for prime in six.iterkeys(factors): density *= 1 - 1 / prime return density def integer(entropy, signed, min_abs=0, coprime_to=1): """Returns an integer from a set of size ceil(10**entropy). If `signed` is True, then includes negative integers, otherwise includes just positive integers. Args: entropy: Float >= 0. signed: Boolean. Whether to also return negative numbers. min_abs: Integer >= 0. The minimum absolute value. coprime_to: Optional integer >= 1. The returned integer is guaranteed to be coprime to `coprime_to`, with entropy still accounted for. Returns: Integer. """ assert isinstance(min_abs, int) and not isinstance(min_abs, bool) coprime_to = abs(coprime_to) assert min_abs >= 0 max_ = math.pow(10, entropy) max_ += min_abs if coprime_to >= 2: max_ = max_ / _coprime_density(coprime_to) + 1 if signed: max_ = int(math.ceil(max_ / 2)) range_ = [-max_, max_] else: max_ = int(math.ceil(max_)) range_ = [min_abs, max_] while True: value = random.randint(*range_) if abs(value) >= min_abs and sympy.gcd(value, coprime_to) == 1: break return sympy.Integer(value) def non_integer_rational(entropy, signed): """Similar args to `integer`. Entropy split between denom and numer.""" numer_entropy = random.uniform(0, entropy) denom_entropy = entropy - numer_entropy numer = integer(numer_entropy, signed, min_abs=1) denom = integer(denom_entropy, False, min_abs=2, coprime_to=numer) return sympy.Rational(numer, denom) def integer_or_rational(entropy, signed, min_abs=0): """Returns a rational, with 50% probability of it being an integer.""" if random.choice([False, True]): return integer(entropy, signed, min_abs=min_abs) else: return non_integer_rational(entropy, signed) def non_integer_decimal(entropy, signed): """Returns a random decimal; integer divided by random power of ten. Guaranteed to be non-integer (i.e., numbers after the decimal point). Args: entropy: Float. signed: Boolean. Whether to also return negative numbers. Returns: Non-integer decimal. """ while True: base = integer(entropy, signed) shift = random.randint(1, int(math.ceil(entropy))) divisor = 10**shift if base % divisor != 0: return display.Decimal(sympy.Rational(base, divisor)) def integer_or_decimal(entropy, signed): """Returns integer or non-integer decimal; 50% probability of each.""" if random.choice([False, True]): # Represent it as a decimal so that arithmetic operations are supported: return display.Decimal(integer(entropy, signed)) else: return non_integer_decimal(entropy, signed) def entropy_of_value(value): """Returns "min entropy" that would give probability of getting this value.""" if isinstance(value, display.Decimal): return entropy_of_value(sympy.numer(value)) if is_non_integer_rational(value): numer = sympy.numer(value) denom = sympy.denom(value) return entropy_of_value(numer) + entropy_of_value(denom) elif not is_integer(value): raise ValueError('Unhandled value: {}'.format(value)) # Note: we sample integers in a range of size approx 10**entropy about zero, # so assume that `abs(value)` is about half of the upper range. return math.log10(5 * abs(value) + 1) def is_integer(value): return isinstance(value, (int, np.int64, np.int32, sympy.Integer)) def is_positive_integer(value): """Filter for: value is a strictly positive integer.""" return is_integer(value) and value > 0 def is_integer_or_rational(value): return is_integer(value) or isinstance(value, sympy.Rational) def is_integer_or_decimal(value): return is_integer(value) or isinstance(value, display.Decimal) def is_integer_or_rational_or_decimal(value): return is_integer_or_rational(value) or is_integer_or_decimal(value) def is_non_integer_rational(value): return is_integer_or_rational(value) and not is_integer(value)
mathematics_dataset-master
mathematics_dataset/sample/number.py
# Copyright 2018 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
mathematics_dataset-master
mathematics_dataset/sample/__init__.py
# Copyright 2018 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Generate polynomials with given values.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import random # Dependency imports from mathematics_dataset.sample import number from mathematics_dataset.sample import ops from mathematics_dataset.util import combinatorics import numpy as np import six from six.moves import range from six.moves import zip import sympy from sympy.solvers.diophantine import base_solution_linear as diophantine_solve_linear_2d def expanded_coefficient_counts(length, is_zero): """Generates list of integers for number of terms of given power. Args: length: Integer >= `sum(is_zero)`. is_zero: List of booleans. Returns: List of non-negative integers of length `is_zero`, summing to `length`, such that if `is_zero[i]` then `return_value[i] != 1`. Raises: ValueError: If assignment not possible. """ if length == 1 and all(is_zero): raise ValueError('length=1 and all zero') counts = np.asarray([0 if zero else 1 for zero in is_zero]) extra_needed = (length - sum(counts)) if extra_needed < 0: raise ValueError('length={} cannot handle is_zero={}' .format(length, is_zero)) extra = combinatorics.uniform_non_negative_integers_with_sum( count=len(is_zero), sum_=extra_needed) counts += np.asarray(extra) # Tweak so that no zeros get "1". while True: bad_zeros = [ i for i in range(len(is_zero)) if is_zero[i] and counts[i] == 1 ] if not bad_zeros: break take_from = random.choice(bad_zeros) add_to = random.choice( [i for i in range(len(is_zero)) if counts[i] >= 1 and i != take_from]) counts[take_from] -= 1 counts[add_to] += 1 return counts def _split_value_equally(delta, count): """Splits an integer or rational into roughly equal parts.""" numer = sympy.numer(delta) denom = sympy.denom(delta) return [int(math.floor((numer + i) / count)) / denom for i in range(count)] def integers_with_sum(value, count, entropy): """Returns list of integers with a given sum. Args: value: Target value. count: Integer >= 1; the number of integers to use. entropy: Entropy to use (in total). Returns: List of numbers summing to `value`. Raises: ValueError: If `value` is not an integer. """ # Special cases. if count == 0: assert value == 0 assert entropy == 0 return [] if count == 1: assert entropy == 0 return [value] if not number.is_integer(value): raise ValueError('value={} (type={}) is not an integer' .format(value, type(value))) # Because e.g., (1, 1) and (2, 2) will both map to the same set of integers # when we normalize to have sum equal to `value`. entropy *= count / (count - 1) min_term_entropy = max( 1, number.entropy_of_value(int(math.ceil(value/count)))) term_entropies = entropy * np.random.dirichlet(np.ones(count)) term_entropies = np.maximum(min_term_entropy, term_entropies) terms = [number.integer(term_entropy, signed=True) for term_entropy in term_entropies] delta = value - sum(terms) deltas = _split_value_equally(delta, count) terms = [term + delta for term, delta in zip(terms, deltas)] random.shuffle(terms) return terms def monomial(coefficient, variables, powers): """Makes a simple monomial term.""" if not isinstance(variables, (list, tuple)): variables = [variables] if not isinstance(powers, (list, tuple, np.ndarray)): powers = [powers] terms = [] for variable, power in zip(variables, powers): if power == 0: continue elif power == 1: terms.append(variable) else: terms.append(ops.Pow(variable, power)) if (not terms or isinstance(coefficient, sympy.Symbol) or abs(coefficient) != 1): if isinstance(coefficient, sympy.Symbol): terms.insert(0, coefficient) else: terms.insert(0, abs(coefficient)) if len(terms) > 1: term = ops.Mul(*terms) else: term = terms[0] if not isinstance(coefficient, sympy.Symbol) and coefficient < 0: term = ops.Neg(term) return term def sample_coefficients(degrees, entropy, min_non_zero=0, max_non_zero=None): """Generates grid of coefficients with shape `degrees + 1`. This corresponds to univariate if degrees has length 1, otherwise multivariate. Args: degrees: List of integers containing max degrees of variables. entropy: Float >= 0; entropy for generating entries. min_non_zero: Optional integer >= 1; the minimum number of non-zero coeffs. max_non_zero: Optional integer >= 1; the maximum number of non-zero coeffs. Returns: NumPy int array of shape `degrees + 1`. """ if isinstance(degrees, int): degrees = [degrees] degrees = np.asarray(degrees) def random_index(): return [random.randint(0, degrees[i]) for i in range(len(degrees))] indices = set() # Ensure a variable of degree `degrees[i]` occurs for every axis i. for i, degree in enumerate(degrees): if degree > 0: index = random_index() index[i] = degree indices.add(tuple(index)) abs_max_non_zero = np.prod(degrees + 1) min_non_zero = max(min_non_zero, 1, len(indices)) if max_non_zero is None: max_non_zero = min_non_zero + int(entropy/2) min_non_zero = min(min_non_zero, abs_max_non_zero) max_non_zero = min(max_non_zero, abs_max_non_zero) max_non_zero = max(min_non_zero, max_non_zero) num_non_zero = random.randint(min_non_zero, max_non_zero) while len(indices) < num_non_zero: indices.add(tuple(random_index())) coeffs = np.zeros(degrees + 1, dtype=np.int64) entropies = entropy * np.random.dirichlet(np.ones(num_non_zero)) for index, entry_entropy in zip(indices, entropies): value = number.integer(entry_entropy, signed=True, min_abs=1) coeffs.itemset(index, value) return coeffs def expand_coefficients(coefficients, entropy, length=None): """Expands coefficients to multiple terms that sum to each coefficient. Args: coefficients: Array, such that `coefficients[i, j, ..., k]` is the coefficient of x**i * y**j * ... * z**k. entropy: Float >= 0; the entropy to use for generating extra randomness. length: Number of terms that appear, e.g., 2x + 3 has two terms. If `None` then a suitable length will be picked depending on the entropy requested. Returns: Numpy object array with the same shape as `coefficients`, containing lists. """ coefficients = np.asarray(coefficients) shape = coefficients.shape expanded_coefficients = np.empty(shape, dtype=np.object) min_length = np.count_nonzero(coefficients) + 2 if length is None: max_length = min_length + int(math.ceil(entropy) / 2) length = random.randint(min_length, max_length) if length < min_length: length = min_length is_zero_flat = np.reshape(coefficients, [-1]) == 0 counts = expanded_coefficient_counts(length, is_zero=is_zero_flat) coeffs_entropy = entropy * np.random.dirichlet(np.maximum(1e-9, counts - 1)) counts = np.reshape(counts, shape) coeffs_entropy = np.reshape(coeffs_entropy, shape) indices = list(zip(*np.indices(shape).reshape([len(shape), -1]))) for power in indices: coeffs = integers_with_sum( value=coefficients.item(power), count=counts.item(power), entropy=coeffs_entropy.item(power)) expanded_coefficients.itemset(power, coeffs) return expanded_coefficients def sample_expanded_coefficients(degrees, entropy, length=None): """Convenience function: samples and expands coeffs, entropy split equally.""" coefficients = sample_coefficients(degrees, entropy/2, max_non_zero=length) return expand_coefficients(coefficients, entropy/2, length) def coefficients_to_polynomial(coefficients, variables): """Converts array of lists of coefficients to a polynomial.""" coefficients = np.asarray(coefficients) shape = coefficients.shape indices = list(zip(*np.indices(shape).reshape([len(shape), -1]))) monomials = [] for power in indices: coeffs = coefficients.item(power) if (number.is_integer_or_rational(coeffs) or isinstance(coeffs, sympy.Symbol)): coeffs = [coeffs] elif not isinstance(coeffs, list): raise ValueError('Unrecognized coeffs={} type={}' .format(coeffs, type(coeffs))) for coeff in coeffs: monomials.append(monomial(coeff, variables, power)) random.shuffle(monomials) return ops.Add(*monomials) def sample(variables, degrees, entropy, length=None): coefficients = sample_expanded_coefficients(degrees, entropy, length) return coefficients_to_polynomial(coefficients, variables) def add_coefficients(coeffs1, coeffs2): """Adds together two sets of coefficients over same set of variables.""" coeffs1 = np.asarray(coeffs1) coeffs2 = np.asarray(coeffs2) degrees1 = np.array(coeffs1.shape) degrees2 = np.array(coeffs2.shape) assert len(degrees1) == len(degrees2) extra1 = np.maximum(0, degrees2 - degrees1) extra2 = np.maximum(0, degrees1 - degrees2) pad1 = [(0, extra) for extra in extra1] pad2 = [(0, extra) for extra in extra2] coeffs1 = np.pad(coeffs1, pad1, 'constant', constant_values=0) coeffs2 = np.pad(coeffs2, pad2, 'constant', constant_values=0) return coeffs1 + coeffs2 def _random_factor(integer): factors = sympy.factorint(integer) result = 1 for factor, power in six.iteritems(factors): result *= factor ** random.randint(0, power) return result def coefficients_linear_split(coefficients, entropy): """Finds two sets of coefficients and multipliers summing to `coefficients`. Given `coefficients` (an integer vector), will sample integers `a, b`, and two sets of coefficients `coefficients_1, coefficients_2`, such that `a * coefficients_1 + b * coefficients_2 == coefficients`. Args: coefficients: Array of coefficients. entropy: Float >= 0; the amount of randomness used to sample. Returns: Tuple (a, b, coefficients_1, coefficients_2)`. """ coefficients = np.asarray(coefficients) coefficients_shape = coefficients.shape coefficients = np.reshape(coefficients, [-1]) entropy_a = max(1, random.uniform(0, entropy/3)) entropy_b = max(1, random.uniform(0, entropy/3)) entropy -= entropy_a + entropy_b entropy_coefficients = entropy * np.random.dirichlet( np.ones(len(coefficients))) # For each target coefficient z, we are required to solve the linear # Diophantine equation a*x + b*y = c. Bezout's theorem: this has a solution if # and only if gcd(a, b) divides c. # Thus to be solvable for all coefficients, a and b must be chosen such that # gcd(a, b) divides the gcd of the coefficients. coefficients_gcd = sympy.gcd([i for i in coefficients]) coefficients_gcd = max(1, abs(coefficients_gcd)) a = number.integer(entropy_a, signed=True, min_abs=1) b = number.integer(entropy_b, signed=True, min_abs=1, coprime_to=a) b *= _random_factor(coefficients_gcd) if random.choice([False, True]): a, b = b, a coefficients_1 = np.zeros(coefficients.shape, dtype=np.object) coefficients_2 = np.zeros(coefficients.shape, dtype=np.object) for index, coefficient in enumerate(coefficients): entropy_coeff = entropy_coefficients[index] t = number.integer(entropy_coeff, signed=True) x, y = diophantine_solve_linear_2d(c=coefficient, a=a, b=b, t=t) coefficients_1[index] = x coefficients_2[index] = y # Prevent all coefficients from being zero. while np.all(coefficients_1 == 0) or np.all(coefficients_2 == 0): index = random.randint(0, len(coefficients) - 1) scale = random.choice([-1, 1]) coefficients_1[index] += scale * b coefficients_2[index] -= scale * a coefficients_1 = np.reshape(coefficients_1, coefficients_shape) coefficients_2 = np.reshape(coefficients_2, coefficients_shape) return a, b, coefficients_1, coefficients_2 def _degree_of_variable(polynomial, variable): polynomial = sympy.sympify(polynomial).expand() if polynomial.is_constant(): return 0 polynomial = sympy.poly(polynomial) if variable not in polynomial.free_symbols: return 0 return polynomial.degree(variable) def _sample_with_brackets(depth, variables, degrees, entropy, length, force_brackets=True): """Internal recursive function for: constructs a polynomial with brackets.""" # To generate arbitrary polynomial recursively, can do one of: # * add two polynomials, with at least one having brackets. # * multiply two polynomials. # * call `sample` (i.e., polynomial without brackets). if force_brackets: length = max(2, length) if not force_brackets and (random.choice([False, True]) or length < 2): return sample(variables, degrees, entropy, length) length_left = random.randint(1, length - 1) length_right = length - length_left entropy_left, entropy_right = entropy * np.random.dirichlet( [length_left, length_right]) if random.choice([False, True]): # Add two. Force brackets on at least one of the polynomials, and sample # repeatedly until we don't get cancellation. while True: left = _sample_with_brackets( depth + 1, variables, degrees, entropy_left, length_left, True) right = _sample_with_brackets( depth + 1, variables, degrees, entropy_right, length_right, False) if random.choice([False, True]): left, right = right, left result = ops.Add(left, right) all_ok = True for variable, degree in zip(variables, degrees): if _degree_of_variable(result, variable) != degree: all_ok = False break if all_ok: return result else: # Multiply two. def sample_with_zero_check(degrees_, entropy_, length_): while True: result = _sample_with_brackets( depth + 1, variables, degrees_, entropy_, length_, False) if degrees_.sum() > 0 or not result.sympy().is_zero: return result degrees = np.asarray(degrees) def sample_degree(max_degree): """Select in range [0, max_degree], biased away from ends.""" if max_degree <= 1 or random.choice([False, True]): return random.randint(0, max_degree) return random.randint(1, max_degree - 1) degrees_left = np.array([sample_degree(degree) for degree in degrees]) degrees_right = degrees - degrees_left left = sample_with_zero_check(degrees_left, entropy_left, length_left) right = sample_with_zero_check(degrees_right, entropy_right, length_right) return ops.Mul(left, right) def sample_with_brackets(variables, degrees, entropy, length=None): """Constructs a polynomial with brackets. Args: variables: List of variables to use. degrees: Max degrees of variables. This function guarantees that these will be obtained in the returned polynomial. entropy: Float >= 0; the randomness to use in generating the polynomial. length: Optional integer containing number of terms. If `None` then an appropriate one will be generated depending on the entropy. Returns: Instance of `ops.Op` containing the polynomial. """ if isinstance(degrees, int): degrees = [degrees] if not isinstance(variables, (list, tuple)): variables = [variables] if length is None: length = 3 + random.randint(0, int(entropy/2)) # Add on some entropy to compensate for different expressions generating the # same apparent polynomial. entropy += combinatorics.log_number_binary_trees(length) / math.log(10) return _sample_with_brackets(0, variables, degrees, entropy, length, True) def sample_with_small_evaluation(variable, degree, max_abs_input, entropy): """Generates a (canonically ordered) polynomial, with bounded evaluation. The coefficients are chosen to make use of the entropy, with the scaling adjusted so that all give roughly the same contribution to the output of the polynomial when the input is bounded in magnitude by `max_abs_input`. Args: variable: Variable to use in polynomial. degree: Degree of polynomial. max_abs_input: Number >= 1; max absolute value of input. entropy: Float; randomness for generating polynomial. Returns: Instance of `ops.Add`. """ assert max_abs_input >= 1 entropies = entropy * np.random.dirichlet(np.ones(degree + 1)) coeffs = [] for power in range(degree + 1): # This scaling guarantees that the terms give roughly equal contribution # to the typical magnitude of the polynomial when |input| <= max_abs_input. delta = 0.5 * (degree - 2 * power) * math.log10(max_abs_input) power_entropy = entropies[power] + delta min_abs = 1 if power == degree else 0 coeff = number.integer(power_entropy, signed=True, min_abs=min_abs) coeffs.append(coeff) terms = [monomial(coeff, variable, power) for power, coeff in enumerate(coeffs)] return ops.Add(*terms) def sample_messy_power(variable, entropy): """Returns unsimplified power expression like ((x**2)**3/x**4)**2/x**3.""" if entropy <= 0: return variable which = random.choice([1, 2, 3]) if which == 1: exponent_entropy = min(2, entropy) entropy -= exponent_entropy exponent = number.integer_or_rational(exponent_entropy, signed=True) left = sample_messy_power(variable, entropy) return ops.Pow(left, exponent) entropy_left = entropy / 2 if entropy_left < 1: entropy_left = 0 entropy_right = entropy - entropy_left if random.choice([False, True]): entropy_left, entropy_right = entropy_right, entropy_left left = sample_messy_power(variable, entropy_left) right = sample_messy_power(variable, entropy_right) if which == 2: return ops.Mul(left, right) else: return ops.Div(left, right) def trim(coefficients): """Makes non-zero entry in the final slice along each axis.""" coefficients = np.asarray(coefficients) non_zero = np.not_equal(coefficients, 0) ndim = coefficients.ndim for axis in range(ndim): length = coefficients.shape[axis] axis_complement = list(range(0, axis)) + list(range(axis + 1, ndim)) non_zero_along_axis = np.any(non_zero, axis=tuple(axis_complement)) slice_to = 0 for index in range(length - 1, -1, -1): if non_zero_along_axis[index]: slice_to = index + 1 break if slice_to < length: coefficients = coefficients.take(axis=axis, indices=list(range(slice_to))) return coefficients def differentiate(coefficients, axis): """Differentiate coefficients (corresponding to polynomial) along axis.""" coefficients = np.asarray(coefficients) indices = list(range(1, coefficients.shape[axis])) coefficients = coefficients.take(axis=axis, indices=indices) broadcast_shape = np.ones(coefficients.ndim, dtype=np.int32) broadcast_shape[axis] = len(indices) broadcast = np.asarray(indices).reshape(broadcast_shape) result = broadcast * coefficients return trim(result) def integrate(coefficients, axis): """Integrate coefficients (corresponding to polynomial) along axis.""" coefficients = np.asarray(coefficients) length = coefficients.shape[axis] broadcast_shape = np.ones(coefficients.ndim, dtype=np.int32) broadcast_shape[axis] = length powers = np.array([sympy.Integer(i) for i in range(1, length + 1)]) powers = powers.reshape(broadcast_shape) result_unpadded = coefficients / powers pad = [(1 if i == axis else 0, 0) for i in range(coefficients.ndim)] return np.pad(result_unpadded, pad, 'constant', constant_values=0)
mathematics_dataset-master
mathematics_dataset/sample/polynomials.py
# Copyright 2018 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Mathematical operations used to build up expressions for printing. We can't use sympy because sympy will automatically simplify many types of expressions, even with `evaluate=False` passed in. For example: * Mul(-2, -3, evaluate=False) gives -(-6), not (-2) x (-3). * Add(2, 1, evaluate=False) gives 1 + 2, because the terms are sorted. As such, it's easier just to work with our own op classes that display precisely as we created them. This also allows us to use custom symbols for the expressions, such as the multiplication symbol. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc # Dependency imports from absl import logging from mathematics_dataset.sample import number from mathematics_dataset.util import display import numpy as np import six from six.moves import zip import sympy MUL_SYMBOL = '*' DIV_SYMBOL = '/' POW_SYMBOL = '**' GT_SYMBOL = '>' LT_SYMBOL = '<' GE_SYMBOL = '>=' LE_SYMBOL = '<=' EQ_SYMBOL = '=' NE_SYMBOL = '!=' # Operator precedence levels. Used to insert brackets if necessary. _EQ_PRECEDENCE = 0 _CONSTANT_PRECEDENCE = 1 _POW_PRECEDENCE = 2 _SQRT_PRECEDENCE = 3 _MUL_PRECEDENCE = 4 _ADD_PRECEDENCE = 5 def bracketed(child, parent, bracket_if_same_precedence): """Returns string representation of `child`, possibly bracketed. Args: child: Instance of `Op` or a valid value for `ConstantOp`. parent: Instance of `Op`. Used to determine whether `child` needs to be bracketed first before appearing in the parent op's expression. bracket_if_same_precedence: Whether to bracket if the child has the same operator precedence as the parent. Returns: String representation of `child`. """ if not isinstance(child, Op): child = Constant(child) child_precedence = child.precedence parent_precedence = parent.precedence if (parent_precedence > child_precedence or (parent_precedence == child_precedence and not bracket_if_same_precedence)): return str(child) else: return '({})'.format(child) def _flatten(iterable): """Returns list.""" if isinstance(iterable, (list, tuple)): result = list(iterable) else: assert isinstance(iterable, dict) keys = sorted(six.iterkeys(iterable)) result = [iterable[key] for key in keys] # Check we don't have any hierarchy in the structure (otherwise would need # to use something recursive like tf.contrib.framework.nest.flatten). for item in result: assert not isinstance(item, (list, tuple, dict)) return result def _pack_sequence_as(example, flat): if isinstance(example, list) or isinstance(example, tuple): return flat else: assert isinstance(example, dict) keys = sorted(six.iterkeys(example)) return {key: value for key, value in zip(keys, flat)} @six.add_metaclass(abc.ABCMeta) class Op(object): """An operation. This needs to support being transformed into sympy (and possibly in the future other types such as an appropriately formatted string), when given the op arguments. """ def __init__(self, children): """Initialize this `Op` base class. Args: children: Iterable structure containing child ops. """ assert isinstance(children, (list, dict, tuple)) flat_children = _flatten(children) flat_children = [child if isinstance(child, Op) else Constant(child) for child in flat_children] children = _pack_sequence_as(children, flat_children) self._children = children @property def children(self): """Returns iterable or dict over immediate children.""" return self._children def descendants(self): """Returns list of all descendants (self, children, grandchildren, etc).""" descendants = [self] flat_children = _flatten(self._children) for child in flat_children: descendants += child.descendants() return descendants @abc.abstractmethod def __str__(self): """Returns a string format of this op.""" @abc.abstractmethod def sympy(self): """Returns the sympifcation of this op.""" def _sympy_(self): """Convenience method to automatically sympify this object.""" try: return self.sympy() except AttributeError as e: # Note: we print this error here, before raising it again, because sympy # will think `AttributeError` refers to this object not having a `_sympy_` # method, rather than having it, which leads to otherwise confusing error # messages. logging.error( 'Encountered attribute error while trying to sympify: %s', e) raise e @abc.abstractproperty def precedence(self): """Returns the precedence (integer) of this op.""" class Constant(Op): """Returns a constant value; a nullary op.""" def __init__(self, value): super(Constant, self).__init__([]) if isinstance(value, six.integer_types): value = sympy.Integer(value) self._value = value def __str__(self): return str(self._value) def sympy(self): return self._value @property def value(self): return self._value @value.setter def value(self, value): self._value = value def _is_simple(self): """Returns whether it's a simple number, rather than a division or neg.""" if isinstance(self._value, sympy.Symbol): return True elif (isinstance(self._value, int) or isinstance(self._value, sympy.Integer) or isinstance(self._value, display.Decimal) or isinstance(self._value, np.int64) or isinstance(self._value, np.int32)): return self._value >= 0 elif isinstance(self._value, sympy.Rational): return False elif isinstance(self._value, sympy.Function): return True else: raise ValueError('Unknown type {}'.format(type(self._value))) @property def precedence(self): if self._is_simple(): return _CONSTANT_PRECEDENCE else: return _MUL_PRECEDENCE class _SumLikeOp(Op): """Abstract op for sum-like terms which may contain negative entries.""" @abc.abstractmethod def expanded_signs_and_terms(self): """Returns a list of arguments, plus any sub-arguments from sub-adds. E.g., if this op is `Add(Add(2, Neg(3)), Mul(4, 5), 1)`, then will return `[(True, 2), (False, 3), (True, Mul(4, 5)), (True, 1)]` (the arguments of the inner add have been extracted). """ def __str__(self): signs_and_terms = self.expanded_signs_and_terms() if not signs_and_terms: return '0' for i, (sign, term) in enumerate(signs_and_terms): if i == 0: if sign: expression = bracketed(term, self, True) else: expression = '-' + bracketed(term, self, True) else: if sign: expression += ' + ' + bracketed(term, self, True) else: expression += ' - ' + bracketed(term, self, True) return expression class Identity(_SumLikeOp): """The identity op (a unitary op).""" def __init__(self, input_): super(Identity, self).__init__({'input': input_}) def expanded_signs_and_terms(self): if isinstance(self.children['input'], _SumLikeOp): return self.children['input'].expanded_signs_and_terms() else: return [(True, self.children['input'])] def __str__(self): return str(self.children['input']) def sympy(self): return self.children['input'].sympy() @property def precedence(self): return self.children['input'].precedence class Neg(_SumLikeOp): """Negation, a unary op. Also has special display when appearing in a sum.""" def __init__(self, arg): super(Neg, self).__init__({'input': arg}) def expanded_signs_and_terms(self): if isinstance(self.children['input'], _SumLikeOp): inner_signs_and_terms = self.children['input'].expanded_signs_and_terms() return [(not sign, term) for (sign, term) in inner_signs_and_terms] else: return [(False, self.children['input'])] def sympy(self): return -sympy.sympify(self.children['input']) def inner(self): return self.children['input'] @property def precedence(self): return _ADD_PRECEDENCE class Add(_SumLikeOp): """Addition.""" def __init__(self, *args): super(Add, self).__init__(args) def expanded_signs_and_terms(self): """Returns a list of arguments, plus any sub-arguments from sub-adds. E.g., if this op is `Add(Add(2, 3), Mul(4, 5), 1)`, then will return `[2, 3, Mul(4, 5), 1]` (the arguments of the inner add have been extracted). """ expanded = [] for arg in self.children: if isinstance(arg, _SumLikeOp): expanded += arg.expanded_signs_and_terms() else: expanded.append((True, arg)) return expanded def sympy(self): return sympy.Add(*[sympy.sympify(arg) for arg in self.children]) @property def precedence(self): return _ADD_PRECEDENCE class Sub(Op): """Subtraction.""" def __init__(self, left, right): super(Sub, self).__init__({'left': left, 'right': right}) def __str__(self): return (bracketed(self.children['left'], self, False) + ' - ' + bracketed(self.children['right'], self, True)) def sympy(self): return sympy.Add( self.children['left'], sympy.Mul(-1, self.children['right'])) @property def precedence(self): return _ADD_PRECEDENCE class Mul(Op): """Multiplication.""" def __init__(self, *args): super(Mul, self).__init__(args) def __str__(self): if not self.children: return '1' else: args = [bracketed(arg, self, False) for arg in self.children] return MUL_SYMBOL.join(args) def sympy(self): return sympy.Mul(*[sympy.sympify(arg) for arg in self.children]) @property def precedence(self): return _MUL_PRECEDENCE class Div(Op): """Division.""" def __init__(self, numer, denom): super(Div, self).__init__({'numer': numer, 'denom': denom}) def __str__(self): return u'{}{}{}'.format( bracketed(self.children['numer'], self, True), DIV_SYMBOL, bracketed(self.children['denom'], self, True)) def sympy(self): return sympy.Mul( self.children['numer'], sympy.Pow(self.children['denom'], -1)) @property def precedence(self): return _MUL_PRECEDENCE class Pow(Op): """Power a to the power b.""" def __init__(self, a, b): super(Pow, self).__init__({'a': a, 'b': b}) def __str__(self): return u'{}{}{}'.format( bracketed(self.children['a'], self, True), POW_SYMBOL, bracketed(self.children['b'], self, True)) def sympy(self): return sympy.Pow( sympy.sympify(self.children['a']), sympy.sympify(self.children['b'])) @property def precedence(self): return _POW_PRECEDENCE class Sqrt(Op): """Square root of a value.""" def __init__(self, a): super(Sqrt, self).__init__({'a': a}) def __str__(self): return 'sqrt({})'.format(self.children['a']) def sympy(self): return sympy.sqrt(self.children['a']) @property def precedence(self): return _POW_PRECEDENCE class Eq(Op): """Equality.""" def __init__(self, left, right): super(Eq, self).__init__({'left': left, 'right': right}) def __str__(self): return '{} = {}'.format(self.children['left'], self.children['right']) def sympy(self): return sympy.Eq(self.children['left'], self.children['right']) @property def precedence(self): return _EQ_PRECEDENCE def number_constants(expressions): """Returns list of integer, rational, decimal constants in the expressions.""" if isinstance(expressions, Op): expressions = [expressions] descendants = [] for expression in expressions: descendants += expression.descendants() candidate_constants = [op for op in descendants if isinstance(op, Constant)] return [constant for constant in candidate_constants if number.is_integer_or_rational_or_decimal(constant.value)]
mathematics_dataset-master
mathematics_dataset/sample/ops.py
# Copyright 2018 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for mathematics_dataset.sample.number.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import random # Dependency imports from absl.testing import absltest from absl.testing import parameterized from mathematics_dataset.sample import number from six.moves import range import sympy class NumberTest(parameterized.TestCase): def testCoprimeDensity(self): self.assertEqual(number._coprime_density(1), 1.0) self.assertEqual(number._coprime_density(2), 0.5) self.assertLess(abs(number._coprime_density(3) - 2/3), 1e-6) self.assertLess(abs(number._coprime_density(6) - 1/3), 1e-6) @parameterized.parameters(False, True) def testInteger_allowZero(self, signed): saw_zero = False saw_nonzero = False for _ in range(1000): sample = number.integer(1, signed=signed) if sample == 0: saw_zero = True else: saw_nonzero = True if saw_zero and saw_nonzero: break self.assertTrue(saw_zero) self.assertTrue(saw_nonzero) def testNonIntegerRational(self): for _ in range(1000): entropy = random.uniform(0, 10) signed = random.choice([False, True]) sample = number.non_integer_rational(entropy, signed) self.assertNotEqual(sympy.denom(sample), 1) @parameterized.parameters(False, True) def testIntegerOrRational(self, signed): # Tests we can call it. Do it a few times so both code paths get executed. for _ in range(10): number.integer_or_rational(2, signed) def testNonIntegerDecimal(self): for _ in range(1000): sample = number.non_integer_decimal(1, False) self.assertNotEqual(sympy.denom(sample), 1) self.assertLen(str(sample), 3) # should be of form "0.n" self.assertGreater(sample, 0) # positive def testNonIntegerDecimal_size(self): saw_bigger_one = False saw_smaller_one = False for _ in range(1000): sample = number.non_integer_decimal(2, False) if sample > 1: saw_bigger_one = True else: saw_smaller_one = True if saw_bigger_one and saw_smaller_one: break self.assertTrue(saw_bigger_one) self.assertTrue(saw_smaller_one) @parameterized.parameters( lambda: number.integer(0, True), lambda: number.integer(1, True), lambda: number.non_integer_rational(2, True), lambda: number.non_integer_decimal(1, True)) def testGenerate_signed(self, generator): saw_positive = False saw_negative = False for _ in range(1000): sample = generator() saw_positive |= sample > 0 saw_negative |= sample < 0 if saw_positive and saw_negative: break self.assertTrue(saw_positive) self.assertTrue(saw_negative) @parameterized.parameters( lambda: number.integer(2, False), lambda: number.non_integer_rational(2, False)) def testIntegerRational_distinctCount(self, generator): seen = set() for _ in range(3000): seen.add(generator()) self.assertGreaterEqual(len(seen), 10 ** 2) @parameterized.parameters(number.integer, number.non_integer_decimal) def testEntropyOfValue(self, generator): for entropy in [1, 2, 4, 8, 16]: sum_entropy = 0.0 count = 2000 for _ in range(count): value = generator(entropy, signed=True) sum_entropy += number.entropy_of_value(value) avg_entropy = sum_entropy / count error = abs(entropy - avg_entropy) / entropy self.assertLess(error, 0.2) if __name__ == '__main__': absltest.main()
mathematics_dataset-master
mathematics_dataset/sample/number_test.py
# Copyright 2018 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for mathematics_dataset.sample.ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # Dependency imports from absl.testing import absltest from mathematics_dataset.sample import ops from six.moves import range import sympy class OpsTest(absltest.TestCase): def testNeg(self): op = ops.Neg(2) self.assertEqual(str(op), '-2') self.assertEqual(op.sympy(), -2) op = ops.Add(ops.Neg(2), 3) self.assertEqual(str(op), '-2 + 3') self.assertEqual(op.sympy(), 1) op = ops.Add(3, ops.Neg(2)) self.assertEqual(str(op), '3 - 2') self.assertEqual(op.sympy(), 1) op = ops.Add(ops.Add(ops.Neg(2), 5), 3) self.assertEqual(str(op), '-2 + 5 + 3') self.assertEqual(op.sympy(), 6) op = ops.Add(3, ops.Add(ops.Identity(ops.Neg(2)), 5)) self.assertEqual(str(op), '3 - 2 + 5') self.assertEqual(op.sympy(), 6) op = ops.Add(3, ops.Add(2, ops.Neg(5))) self.assertEqual(str(op), '3 + 2 - 5') self.assertEqual(op.sympy(), 0) def testAdd(self): add = ops.Add() self.assertEqual(str(add), '0') self.assertEqual(add.sympy(), 0) add = ops.Add(2, 3) self.assertEqual(str(add), '2 + 3') self.assertEqual(add.sympy(), 5) add = ops.Add(ops.Add(1, 2), 3) self.assertEqual(str(add), '1 + 2 + 3') self.assertEqual(add.sympy(), 6) def testSub(self): sub = ops.Sub(2, 3) self.assertEqual(str(sub), '2 - 3') self.assertEqual(sub.sympy(), -1) sub = ops.Sub(ops.Sub(1, 2), 3) self.assertEqual(str(sub), '1 - 2 - 3') self.assertEqual(sub.sympy(), -4) sub = ops.Sub(1, ops.Sub(2, 3)) self.assertEqual(str(sub), '1 - (2 - 3)') self.assertEqual(sub.sympy(), 2) sub = ops.Sub(ops.Neg(1), 2) self.assertEqual(str(sub), '-1 - 2') self.assertEqual(sub.sympy(), -3) def testMul(self): mul = ops.Mul() self.assertEqual(str(mul), '1') self.assertEqual(mul.sympy(), 1) mul = ops.Mul(2, 3) self.assertEqual(str(mul), '2*3') self.assertEqual(mul.sympy(), 6) mul = ops.Mul(ops.Identity(ops.Constant(-2)), 3) self.assertEqual(str(mul), '-2*3') self.assertEqual(mul.sympy(), -6) mul = ops.Mul(ops.Add(1, 2), 3) self.assertEqual(str(mul), '(1 + 2)*3') self.assertEqual(mul.sympy(), 9) mul = ops.Mul(ops.Mul(2, 3), 5) self.assertEqual(str(mul), '2*3*5') self.assertEqual(mul.sympy(), 30) # TODO(b/124038946): reconsider how we want brackets in these cases: # mul = ops.Mul(ops.Div(2, 3), 5) # self.assertEqual(str(mul), '(2/3)*5') # self.assertEqual(mul.sympy(), sympy.Rational(10, 3)) # # mul = ops.Mul(sympy.Rational(2, 3), 5) # self.assertEqual(str(mul), '(2/3)*5') # self.assertEqual(mul.sympy(), sympy.Rational(10, 3)) def testDiv(self): div = ops.Div(2, 3) self.assertEqual(str(div), '2/3') self.assertEqual(div.sympy(), sympy.Rational(2, 3)) div = ops.Div(2, sympy.Rational(4, 5)) self.assertEqual(str(div), '2/(4/5)') self.assertEqual(div.sympy(), sympy.Rational(5, 2)) div = ops.Div(1, ops.Div(2, 3)) self.assertEqual(str(div), '1/(2/3)') self.assertEqual(div.sympy(), sympy.Rational(3, 2)) div = ops.Div(ops.Div(2, 3), 4) self.assertEqual(str(div), '(2/3)/4') self.assertEqual(div.sympy(), sympy.Rational(1, 6)) div = ops.Div(2, ops.Mul(3, 4)) self.assertEqual(str(div), '2/(3*4)') div = ops.Div(2, sympy.Function('f')(sympy.Symbol('x'))) self.assertEqual(str(div), '2/f(x)') def testPow(self): pow_ = ops.Pow(2, 3) self.assertEqual(str(pow_), '2**3') self.assertEqual(pow_.sympy(), 8) pow_ = ops.Pow(4, sympy.Rational(1, 2)) self.assertEqual(str(pow_), '4**(1/2)') self.assertEqual(pow_.sympy(), 2) pow_ = ops.Pow(sympy.Rational(1, 2), 3) self.assertEqual(str(pow_), '(1/2)**3') self.assertEqual(pow_.sympy(), 1/8) pow_ = ops.Pow(3, ops.Pow(2, 1)) self.assertEqual(str(pow_), '3**(2**1)') self.assertEqual(pow_.sympy(), 9) pow_ = ops.Pow(ops.Pow(2, 3), 4) self.assertEqual(str(pow_), '(2**3)**4') self.assertEqual(pow_.sympy(), 4096) pow_ = ops.Pow(-5, 2) self.assertEqual(str(pow_), '(-5)**2') self.assertEqual(pow_.sympy(), 25) def testEq(self): op = ops.Eq(ops.Add(2, 3), 4) self.assertEqual(str(op), '2 + 3 = 4') self.assertEqual(op.sympy(), False) def testDescendants(self): constants = [ops.Constant(i) for i in range(6)] # (1 + 2*3**4) / 5 - 6 expression = ops.Sub( ops.Div( ops.Add( constants[0], ops.Mul( constants[1], ops.Pow( constants[2], constants[3]))), constants[4]), constants[5]) descendants = expression.descendants() descendants = ops._flatten(descendants) for constant in constants: self.assertIn(constant, descendants) self.assertEqual(descendants.count(constant), 1) # Also test top-level. self.assertEqual(constants[0].descendants(), [constants[0]]) # Also general structure. constant = ops.Constant(3) expression = ops.Neg(constant) self.assertEqual(set(expression.descendants()), set([constant, expression])) def testNumberConstants(self): constant = ops.Constant(3) expression = ops.Neg(constant) constants = ops.number_constants([expression]) self.assertEqual(constants, [constant]) if __name__ == '__main__': absltest.main()
mathematics_dataset-master
mathematics_dataset/sample/ops_test.py
# Copyright 2018 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for mathematics_dataset.sample.polynomials.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import random # Dependency imports from absl.testing import parameterized from mathematics_dataset.sample import polynomials import numpy as np from six.moves import range import sympy import tensorflow as tf class ExpressionWithValueTest(tf.test.TestCase, parameterized.TestCase): def testSplitValueEqually(self): split = polynomials._split_value_equally(3, 2) self.assertEqual(split, [1, 2]) split = polynomials._split_value_equally(sympy.sympify('3/4'), 2) self.assertEqual(split, [sympy.sympify('1/4'), sympy.sympify('1/2')]) def testIntegersWithSum(self): value = 13 count = 10 terms = polynomials.integers_with_sum(value=value, count=count, entropy=4.0) self.assertLen(terms, count) self.assertEqual(sum(terms), value) def testMonomial(self): x, y = sympy.symbols('x y') self.assertEqual(str(polynomials.monomial(1, [x, y], [2, 3])), 'x**2*y**3') # TODO(b/124038530): how handle rational coefficients; are they even used? # self.assertEqual( # str(polynomials.monomial(sympy.Rational(2, 3), [x], [1])), '2*x/3') # self.assertEqual( # str(polynomials.monomial(sympy.Rational(1, 3), [x], [1])), 'x/3') self.assertEqual(str(polynomials.monomial(x, [y], [4])), 'x*y**4') def testExpandCoefficients(self): for _ in range(10): num_variables = np.random.randint(1, 4) degrees = np.random.randint(0, 4, [num_variables]) coefficients = np.random.randint(-3, 3, degrees + 1) entropy = np.random.uniform(0, 10) expanded = polynomials.expand_coefficients(coefficients, entropy) collapsed = np.vectorize(sum)(expanded) self.assertAllEqual(coefficients, collapsed) def testCoefficientsToPolynomial(self): coeffs = [3, 2, 1] x = sympy.Symbol('x') polynomial = polynomials.coefficients_to_polynomial(coeffs, [x]) polynomial = sympy.sympify(polynomial) self.assertEqual(polynomial, x*x + 2*x + 3) def testUnivariate(self): # Test generation for: x**2 + 2*x + 1 x = sympy.Symbol('x') coeffs = [1, 2, 3] for _ in range(10): expanded = polynomials.expand_coefficients(coeffs, 5.0) polynomial = polynomials.coefficients_to_polynomial(expanded, [x]) sympified = sympy.sympify(polynomial) self.assertEqual(sympified, 1 + 2*x + 3*x*x) def testMultivariate(self): # Test generation for: x**2 + 2*x*y + 3*y**2 - x + 5 x, y = sympy.symbols('x y') coeffs = [[5, 0, 3], [-1, 2, 0], [1, 0, 0]] for _ in range(10): expanded = polynomials.expand_coefficients(coeffs, 5.0, length=10) polynomial = polynomials.coefficients_to_polynomial(expanded, [x, y]) sympified = sympy.sympify(polynomial) self.assertEqual(sympified, x*x + 2*x*y + 3*y*y - x + 5) def testAddCoefficients(self): # Add x**2 + 2*y and 3*x + 4*y**3. coeffs1 = [[0, 2], [0, 0], [1, 0]] coeffs2 = [[0, 0, 0, 4], [3, 0, 0, 0]] target = [[0, 2, 0, 4], [3, 0, 0, 0], [1, 0, 0, 0]] actual = polynomials.add_coefficients(coeffs1, coeffs2) self.assertAllEqual(target, actual) def testCoefficientsLinearSplit(self): for degree in range(3): for ndims in range(3): for _ in range(10): coefficients = np.random.randint(-5, 5, [degree + 1] * ndims) entropy = random.uniform(1, 4) c1, c2, coeffs1, coeffs2 = polynomials.coefficients_linear_split( coefficients, entropy) c1 = int(c1) c2 = int(c2) coeffs1 = np.asarray(coeffs1, dtype=np.int32) coeffs2 = np.asarray(coeffs2, dtype=np.int32) sum_ = c1 * coeffs1 + c2 * coeffs2 self.assertAllEqual(sum_, coefficients) def testSampleWithBrackets(self): x, y = sympy.symbols('x y') for _ in range(100): degrees = np.random.randint(1, 4, [2]) entropy = random.uniform(0, 4) polynomial = polynomials.sample_with_brackets( variables=[x, y], degrees=degrees, entropy=entropy) self.assertIn('(', str(polynomial)) poly = sympy.poly(sympy.sympify(polynomial).expand()) self.assertEqual(poly.degree(x), degrees[0]) self.assertEqual(poly.degree(y), degrees[1]) def testTrim(self): self.assertAllEqual(polynomials.trim([1]), [1]) self.assertAllEqual(polynomials.trim([1, 0]), [1]) self.assertAllEqual(polynomials.trim([0, 1]), [0, 1]) self.assertAllEqual(polynomials.trim([0]), []) self.assertAllEqual(polynomials.trim([0, 0]), []) def testDifferentiate_univariate(self): coeffs = [5, 3, 2] expected = [3, 4] actual = polynomials.differentiate(coeffs, 0) self.assertAllEqual(expected, actual) def testDifferentiate_multivariate(self): coeffs = [[0, 3, 1], [5, 0, 0], [0, 2, 0]] expected = [[5, 0], [0, 4]] actual = polynomials.differentiate(coeffs, 0) self.assertAllEqual(expected, actual) def testIntegrate_univariate(self): coeffs = [5, 3, 2] expected = [0, 5, sympy.Rational(3, 2), sympy.Rational(2, 3)] actual = polynomials.integrate(coeffs, 0) self.assertAllEqual(expected, actual) def testIntegrate_multivariate(self): coeffs = [[0, 1], [1, 0]] expected = [[0, 0, sympy.Rational(1, 2)], [0, 1, 0]] actual = polynomials.integrate(coeffs, 1) self.assertAllEqual(expected, actual) if __name__ == '__main__': tf.test.main()
mathematics_dataset-master
mathematics_dataset/sample/polynomials_test.py
# Copyright 2018 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for mathematics_dataset.sample.arithmetic.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import random # Dependency imports from absl.testing import absltest from absl.testing import parameterized from mathematics_dataset.sample import arithmetic from mathematics_dataset.sample import number from mathematics_dataset.sample import ops from six.moves import range import sympy class ArithmeticTest(parameterized.TestCase): def testArithmetic(self): for _ in range(1000): target = number.integer_or_rational(4, signed=True) entropy = 8.0 expression = arithmetic.arithmetic(target, entropy) self.assertEqual(sympy.sympify(expression), target) def testArithmeticLength(self): """Tests that the generated arithmetic expressions have given length.""" for _ in range(1000): target = number.integer_or_rational(4, signed=True) entropy = 8.0 length = random.randint(2, 10) expression = arithmetic.arithmetic(target, entropy, length) # Note: actual length is #ops = #numbers - 1. actual_length = len(ops.number_constants(expression)) - 1 self.assertEqual(actual_length, length) if __name__ == '__main__': absltest.main()
mathematics_dataset-master
mathematics_dataset/sample/arithmetic_test.py
# Copyright 2018 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Arithmetic, e.g., "calculate 2+3".""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools import math import random # Dependency imports from mathematics_dataset import example from mathematics_dataset.sample import arithmetic from mathematics_dataset.sample import number from mathematics_dataset.sample import ops from mathematics_dataset.util import composition from mathematics_dataset.util import display import sympy _ENTROPY_TRAIN = (3, 10) _ENTROPY_INTERPOLATE = (8, 8) _ENTROPY_EXTRAPOLATE = (10, 12) _ADD_SUB_ENTROPY_TRAIN = (4, 16) _ADD_SUB_ENTROPY_INTERPOLATE = (12, 12) _ADD_SUB_ENTROPY_EXTRAPOLATE = (16, 20) # In arithmetic expressions: _EXTRAPOLATE_EXTRA_LENGTH = 3 _INT = 'int' _INT_OR_RATIONAL = 'rational' def _make_modules(entropy, add_sub_entropy): """Returns modules given "difficulty" parameters.""" sample_args_pure = composition.PreSampleArgs(1, 1, *entropy) add_sub_sample_args_pure = composition.PreSampleArgs(1, 1, *add_sub_entropy) # TODO(b/124039105): consider composed modules? return { # Addition and subtraction of integers (and decimals) 'add_or_sub': functools.partial( add_or_sub, None, add_sub_sample_args_pure), 'add_sub_multiple': functools.partial( add_sub_multiple, _INT, sample_args_pure), 'add_or_sub_in_base': functools.partial( add_or_sub_in_base, sample_args_pure), # Multiplication and division 'mul': functools.partial(mul, None, sample_args_pure), 'div': functools.partial(div, None, sample_args_pure), 'mul_div_multiple': functools.partial( mul_div_multiple, _INT_OR_RATIONAL, sample_args_pure), # All together! 'mixed': functools.partial(mixed, _INT_OR_RATIONAL, sample_args_pure), # And some other arithmetic-related stuff. 'nearest_integer_root': functools.partial( nearest_integer_root, sample_args_pure), 'simplify_surd': functools.partial(simplify_surd, None, sample_args_pure), } def train(entropy_fn): """Returns dict of training modules.""" return _make_modules( entropy=entropy_fn(_ENTROPY_TRAIN), add_sub_entropy=entropy_fn(_ADD_SUB_ENTROPY_TRAIN)) def test(): """Returns dict of testing modules.""" return _make_modules( entropy=_ENTROPY_INTERPOLATE, add_sub_entropy=_ADD_SUB_ENTROPY_INTERPOLATE) def test_extra(): """Returns dict of extrapolation testing modules.""" sample_args_pure = composition.PreSampleArgs(1, 1, *_ENTROPY_EXTRAPOLATE) add_sub_sample_args_pure = composition.PreSampleArgs( 1, 1, *_ADD_SUB_ENTROPY_EXTRAPOLATE) train_length = arithmetic.length_range_for_entropy(_ENTROPY_TRAIN[1])[1] def extrapolate_length(): return random.randint( train_length + 1, train_length + _EXTRAPOLATE_EXTRA_LENGTH) def add_sub_multiple_longer(): return add_sub_multiple(_INT, sample_args_pure, length=extrapolate_length()) def mul_div_multiple_longer(): return mul_div_multiple(_INT, sample_args_pure, length=extrapolate_length()) def mixed_longer(): return mixed(_INT, sample_args_pure, length=extrapolate_length()) return { 'add_or_sub_big': functools.partial( add_or_sub, None, add_sub_sample_args_pure), 'mul_big': functools.partial(mul, None, sample_args_pure), 'div_big': functools.partial(div, None, sample_args_pure), 'add_sub_multiple_longer': add_sub_multiple_longer, 'mul_div_multiple_longer': mul_div_multiple_longer, 'mixed_longer': mixed_longer, } def _value_sampler(value): """Returns sampler (e.g., number.integer) appropriate for `value`.""" if value == _INT or number.is_integer(value): return functools.partial(number.integer, signed=True) if value == _INT_OR_RATIONAL or isinstance(value, sympy.Rational): return functools.partial(number.integer_or_rational, signed=True) if isinstance(value, display.Decimal): return functools.partial(number.integer_or_decimal, signed=True) raise ValueError('Unrecognized value {} of type {}' .format(value, type(value))) def _add_question_or_entity(context, p, q, is_question): """Generates entity or question for adding p + q.""" value = p.value + q.value if is_question: template = random.choice([ '{p} + {q}', '{p}+{q}', 'Work out {p} + {q}.', 'Add {p} and {q}.', 'Put together {p} and {q}.', 'Sum {p} and {q}.', 'Total of {p} and {q}.', 'Add together {p} and {q}.', 'What is {p} plus {q}?', 'Calculate {p} + {q}.', 'What is {p} + {q}?', ]) return example.Problem( question=example.question(context, template, p=p, q=q), answer=value) else: return composition.Entity( context=context, value=value, description='Let {self} = {p} + {q}.', p=p, q=q) def _sub_question_or_entity(context, p, q, is_question): """Generates entity or question for subtraction p - q.""" value = p.value - q.value if is_question: templates = [ '{p} - {q}', 'Work out {p} - {q}.', 'What is {p} minus {q}?', 'What is {p} take away {q}?', 'What is {q} less than {p}?', 'Subtract {q} from {p}.', 'Calculate {p} - {q}.', 'What is {p} - {q}?', ] if sympy.Ge(p.value, q.value): # We calculate p - q, so the difference (|p - q|) is the correct answer. for adjective in ['distance', 'difference']: for pair in ['{p} and {q}', '{q} and {p}']: templates.append('What is the {} between {}?'.format(adjective, pair)) template = random.choice(templates) return example.Problem( question=example.question(context, template, p=p, q=q), answer=value) else: return composition.Entity( context=context, value=value, description='Let {self} = {p} - {q}.', p=p, q=q) def _entropy_for_pair(entropy): entropy_1 = max(1, random.uniform(0, entropy)) entropy_2 = max(1, entropy - entropy_1) return entropy_1, entropy_2 @composition.module(number.is_integer_or_rational_or_decimal) def add_or_sub(value, sample_args, context=None): """Module for adding or subtracting two values.""" is_question = context is None if context is None: context = composition.Context() is_addition = random.choice([False, True]) entropy, sample_args = sample_args.peel() if value is None: entropy_p, entropy_q = _entropy_for_pair(entropy) p = number.integer_or_decimal(entropy_p, signed=True) q = number.integer_or_decimal(entropy_q, signed=True) else: entropy = max(entropy, number.entropy_of_value(value)) sampler = _value_sampler(value) p = sampler(entropy) if is_addition: q = value - p # Maybe swap for symmetry. if random.choice([False, True]): p, q = q, p else: q = p - value # Maybe swap for symmetry. if random.choice([False, True]): p, q = -q, -p p, q = context.sample(sample_args, [p, q]) if is_addition: return _add_question_or_entity(context, p, q, is_question) else: return _sub_question_or_entity(context, p, q, is_question) def add_or_sub_in_base(sample_args): """Module for addition and subtraction in another base.""" context = composition.Context() entropy, sample_args = sample_args.peel() entropy_p, entropy_q = _entropy_for_pair(entropy) p = number.integer(entropy_p, signed=True) q = number.integer(entropy_q, signed=True) base = random.randint(2, 16) if random.choice([False, True]): answer = p + q template = 'In base {base}, what is {p} + {q}?' else: answer = p - q template = 'In base {base}, what is {p} - {q}?' return example.Problem( question=example.question( context, template, base=base, p=display.NumberInBase(p, base), q=display.NumberInBase(q, base)), answer=display.NumberInBase(answer, base)) def mul(value, sample_args, context=None): """Returns random question for multiplying two numbers.""" del value # unused is_question = context is None if context is None: context = composition.Context() entropy, sample_args = sample_args.peel() entropy_p, entropy_q = _entropy_for_pair(entropy) p = number.integer_or_decimal(entropy_p, True) q = number.integer_or_decimal(entropy_q, True) p, q = context.sample(sample_args, [p, q]) answer = p.value * q.value if is_question: templates = [ '{p}' + ops.MUL_SYMBOL + '{q}', '{p} ' + ops.MUL_SYMBOL + ' {q}', 'Calculate {p}' + ops.MUL_SYMBOL + '{q}.', 'Work out {p} ' + ops.MUL_SYMBOL + ' {q}.', 'Multiply {p} and {q}.', 'Product of {p} and {q}.', 'What is the product of {p} and {q}?', '{p} times {q}', 'What is {p} times {q}?', ] template = random.choice(templates) return example.Problem( question=example.question(context, template, p=p, q=q), answer=answer ) else: return composition.Entity( context=context, value=answer, description='Let {self} = {p} * {q}.', p=p, q=q) def div(value, sample_args, context=None): """Returns random question for dividing two numbers.""" del value # unused is_question = context is None if context is None: context = composition.Context() entropy, sample_args = sample_args.peel() entropy_1, entropy_q = _entropy_for_pair(entropy) q = number.integer(entropy_q, True, min_abs=1) if random.choice([False, True]): # Pick p/q with nice integer result. answer = number.integer(entropy_1, True) p = answer * q else: p = number.integer(entropy_1, True) answer = p / q p, q = context.sample(sample_args, [p, q]) if is_question: template = random.choice([ 'Divide {p} by {q}.', '{p} divided by {q}', 'What is {p} divided by {q}?', 'Calculate {p} divided by {q}.', ]) return example.Problem( question=example.question(context, template, p=p, q=q), answer=answer ) else: return composition.Entity( context=context, value=answer, description='Let {self} be {p} divided by {q}.', p=p, q=q) def nearest_integer_root(sample_args): """E.g., "Calculate the cube root of 35 to the nearest integer.".""" context = composition.Context() # With at least 50% probability, pick square or cube root (these are most # important roots!). if random.choice([False, True]): one_over_exponent = random.randint(2, 3) else: one_over_exponent = random.randint(2, 10) entropy, sample_args = sample_args.peel() value = number.integer(entropy, signed=False) answer = int(round(value ** (1 / one_over_exponent))) templates = [ 'What is {value} to the power of 1/{one_over_exponent}, to the nearest' ' integer?', ] if one_over_exponent != 2: # "What is the second root of 4?" never used. ordinal = str() templates += [ 'What is the {ordinal} root of {value} to the nearest integer?', ] if one_over_exponent == 2: templates += [ 'What is the square root of {value} to the nearest integer?', ] elif one_over_exponent == 3: templates += [ 'What is the cube root of {value} to the nearest integer?', ] template = random.choice(templates) ordinal = display.StringOrdinal(one_over_exponent) return example.Problem( question=example.question( context, template, value=value, ordinal=ordinal, one_over_exponent=one_over_exponent), answer=answer) def _calculate(value, sample_args, context, add_sub, mul_div, length=None): """Questions for evaluating arithmetic expressions.""" is_question = context is None if context is None: context = composition.Context() entropy, sample_args = sample_args.peel() if value in [_INT, _INT_OR_RATIONAL]: value_entropy = max(1.0, entropy / 4) entropy = max(1.0, entropy - value_entropy) sampler = _value_sampler(value) value = sampler(value_entropy) op = arithmetic.arithmetic( value=value, entropy=entropy, add_sub=add_sub, mul_div=mul_div, length=length) context.sample_by_replacing_constants(sample_args, op) if is_question: template = random.choice([ '{op}', 'What is {op}?', 'Evaluate {op}.', 'Calculate {op}.', 'What is the value of {op}?', ]) return example.Problem( question=example.question(context, template, op=op), answer=value) else: return composition.Entity( context=context, value=value, expression=op, description='Let {self} be {op}.', op=op) def add_sub_multiple(value, sample_args, length=None): return _calculate( value, sample_args, None, add_sub=True, mul_div=False, length=length) def mul_div_multiple(value, sample_args, length=None): return _calculate( value, sample_args, None, add_sub=False, mul_div=True, length=length) @composition.module(number.is_integer_or_rational) def mixed(value, sample_args, context=None, length=None): return _calculate( value, sample_args, context, add_sub=True, mul_div=True, length=length) def _surd_coefficients(sympy_exp): """Extracts coefficients a, b, where sympy_exp = a + b * sqrt(base).""" sympy_exp = sympy.simplify(sympy.expand(sympy_exp)) def extract_b(b_sqrt_base): """Returns b from expression of form b * sqrt(base).""" if isinstance(b_sqrt_base, sympy.Pow): # Just form sqrt(base) return 1 else: assert isinstance(b_sqrt_base, sympy.Mul) assert len(b_sqrt_base.args) == 2 assert b_sqrt_base.args[0].is_rational assert isinstance(b_sqrt_base.args[1], sympy.Pow) # should be sqrt. return b_sqrt_base.args[0] if sympy_exp.is_rational: # Form: a. return sympy_exp, 0 elif isinstance(sympy_exp, sympy.Add): # Form: a + b * sqrt(base) assert len(sympy_exp.args) == 2 assert sympy_exp.args[0].is_rational a = sympy_exp.args[0] b = extract_b(sympy_exp.args[1]) return a, b else: # Form: b * sqrt(base). return 0, extract_b(sympy_exp) def _surd_split_entropy_two(entropy): entropy_left = entropy / 2 if entropy_left < 1: entropy_left = 0 entropy_right = entropy - entropy_left if random.choice([False, True]): entropy_left, entropy_right = entropy_right, entropy_left return entropy_left, entropy_right def _sample_surd(base, entropy, max_power, multiples_only): """An expression that can be reduced to a + b * sqrt(base). For example, if base=3, then the following are valid expressions: * sqrt(12) (reduces to 2 * sqrt(3)) * sqrt(3) - 10 * sqrt(3) (reduces to -9 * sqrt(3)) * sqrt(15) / sqrt(5) (reduces to sqrt(3)). * 4 * sqrt(3) / 2 * 2 + sqrt(3) * 1 / (1 + sqrt(3)) (reduces to -1/2 + (-1/2) sqrt(3)) However, 1 + 2 * sqrt(3) is not valid, as it does not reduce to the form a * sqrt(3). Args: base: The value inside the square root. entropy: Float >= 0; used for randomness. max_power: Integer >= 1; the max power used in expressions. If 1 then disables. multiples_only: Whether the surd should be an integer multiple of sqrt(base). Returns: Instance of `ops.Op`. """ if entropy <= 0: return ops.Sqrt(base) def add_or_sub_(): # Add or subtract two such types. entropy_left, entropy_right = _surd_split_entropy_two(entropy) left = _sample_surd(base, entropy_left, max_power, multiples_only) right = _sample_surd(base, entropy_right, max_power, multiples_only) op = random.choice([ops.Add, ops.Sub]) return op(left, right) def mul_by_integer(): entropy_k = min(1, entropy) left = number.integer(entropy_k, signed=True, min_abs=1) right = _sample_surd(base, entropy - entropy_k, max_power, multiples_only) if random.choice([False, True]): left, right = right, left return ops.Mul(left, right) def div_by_sqrt_k(): """Do sqrt(k * base) / sqrt(k).""" entropy_k = min(1, entropy) k = number.integer(entropy_k, signed=False, min_abs=2) entropy_left, entropy_right = _surd_split_entropy_two(entropy - entropy_k) k_base_expr = _sample_surd(k * base, entropy_left, max_power, True) while True: k_expr = _sample_surd(k, entropy_right, max_power, True) if k_expr.sympy() != 0: break return ops.Div(k_base_expr, k_expr) def square_k(): """Do sqrt(k * k * base).""" entropy_k = min(1, entropy) k = number.integer(entropy_k, signed=False, min_abs=2) return _sample_surd( k * k * base, entropy - entropy_k, max_power, multiples_only) def surd_plus_integer(): """Do surd + integer.""" entropy_k = min(1, entropy) left = number.integer(entropy_k, signed=True) assert not multiples_only right = _sample_surd(base, entropy - entropy_k, max_power, False) if random.choice([True, False]): left, right = right, left return ops.Add(left, right) def power(): """Do surd**2.""" assert not multiples_only surd = _sample_surd(base, entropy, max_power=1, multiples_only=False) return ops.Pow(surd, 2) choices = [add_or_sub_, mul_by_integer] if not multiples_only: choices += [surd_plus_integer] if max_power > 1: choices += [power] if base < 64: # prevent value inside sqrt from getting too big choices += [div_by_sqrt_k, square_k] which = random.choice(choices) return which() def simplify_surd(value, sample_args, context=None): """E.g., "Simplify (2 + 5*sqrt(3))**2.".""" del value # unused if context is None: context = composition.Context() entropy, sample_args = sample_args.peel() while True: base = random.randint(2, 20) if sympy.Integer(base).is_prime: break num_primes_less_than_20 = 8 entropy -= math.log10(num_primes_less_than_20) exp = _sample_surd(base, entropy, max_power=2, multiples_only=False) simplified = sympy.expand(sympy.simplify(exp)) template = random.choice([ 'Simplify {exp}.', ]) return example.Problem( question=example.question(context, template, exp=exp), answer=simplified)
mathematics_dataset-master
mathematics_dataset/modules/arithmetic.py
# Copyright 2018 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Algebra-related questions, e.g., "Solve 1 + x = 2.".""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools import random # Dependency imports from mathematics_dataset import example from mathematics_dataset.sample import linear_system from mathematics_dataset.sample import number from mathematics_dataset.sample import ops from mathematics_dataset.sample import polynomials from mathematics_dataset.util import composition from mathematics_dataset.util import display import numpy as np from six.moves import range import sympy _ENTROPY_TRAIN = (3, 10) _ENTROPY_INTERPOLATE = (8, 8) _ENTROPY_EXTRAPOLATE = (12, 12) # In generating a polynomial with real roots (where the roots are generated # sequentially), this is the probability of taking a previous root, thus giving # at least one repeated root, rather than sampling a new number. The value is # somewhat arbitrary, but gives a "medium probability" of seeing a repeated root # for lowish degree polynomials. _POLY_PROBABILITY_REPEATED_ROOT = 0.2 def _make_modules(entropy): """Returns modules given "difficulty" parameters.""" sample_args_pure = composition.PreSampleArgs(1, 1, *entropy) sample_args_composed = composition.PreSampleArgs(2, 4, *entropy) return { # Solving equations: 'polynomial_roots': functools.partial( polynomial_roots, None, sample_args_pure), 'polynomial_roots_composed': functools.partial( polynomial_roots, None, sample_args_composed), 'linear_1d': functools.partial( solve_linear_1d, None, sample_args_pure), 'linear_1d_composed': functools.partial( solve_linear_1d, None, sample_args_composed), 'linear_2d': functools.partial( solve_linear_2d, None, sample_args_pure), 'linear_2d_composed': functools.partial( solve_linear_2d, None, sample_args_composed), # Sequences: 'sequence_next_term': functools.partial(sequence_next_term, *entropy), 'sequence_nth_term': functools.partial(sequence_nth_term, *entropy), } def train(entropy_fn): """Returns dict of training modules.""" return _make_modules(entropy_fn(_ENTROPY_TRAIN)) def test(): """Returns dict of testing modules.""" return _make_modules(_ENTROPY_INTERPOLATE) def test_extra(): """Returns dict of extrapolation testing modules.""" sample_args_pure = composition.PreSampleArgs(1, 1, *_ENTROPY_EXTRAPOLATE) return { 'polynomial_roots_big': functools.partial( polynomial_roots, None, sample_args_pure), } def _sample_roots(entropy): """Generates `num_distinct + num_repeated` polynomial roots.""" num_roots = random.randint(2, 5) num_repeated = np.random.binomial( num_roots - 1, _POLY_PROBABILITY_REPEATED_ROOT) # Slight hack: don't allow all the roots to be repeated when the entropy is # high, as this can create very large coefficients. if entropy > 4: num_repeated = min(num_repeated, int(num_roots / 2)) num_distinct = num_roots - num_repeated entropies = entropy * np.random.dirichlet(np.ones(num_distinct)) roots = [] for root_entropy in entropies: # Generates a root with small probability of being rational. # (Otherwise when we multiply out the denominators, we get really large # coefficients in our polynomial.) if random.random() < 0.1: root = number.non_integer_rational(root_entropy, True) else: root = number.integer(root_entropy, True) roots.append(root) for _ in range(num_repeated): roots.append(random.choice(roots[:num_distinct])) return roots def _polynomial_coeffs_with_roots(roots, scale_entropy): """Returns a polynomial with the given roots. The polynomial is generated by expanding product_{root in roots} (x - root), and then (1) scaling by the coefficients so they are all integers with lcm 1, and then (2) further scaling the coefficients by a random integer or rational with `scale_entropy` digits. Args: roots: List of values. scale_entropy: Float; entropy of the random coefficient scaling. Returns: List of coefficients `coeffs`, such that `coeffs[i]` is the coefficient of variable ** i. """ variable = sympy.Symbol('x') # doesn't matter, only use coefficients polynomial = sympy.Poly(sympy.prod([variable - root for root in roots])) coeffs_reversed = polynomial.all_coeffs() assert len(coeffs_reversed) == len(roots) + 1 coeffs = list(reversed(coeffs_reversed)) # Multiply terms to change rationals to integers, and then maybe reintroduce. lcm = sympy.lcm([sympy.denom(coeff) for coeff in coeffs]) if scale_entropy > 0: while True: scale = number.integer_or_rational(scale_entropy, signed=True) if scale != 0: break else: scale = 1 return [coeff * scale * lcm for coeff in coeffs] def polynomial_roots(value, sample_args, context=None): """E.g., "Solve 2*x**2 - 18 = 0.".""" del value # not currently used # is_question = context is None if context is None: context = composition.Context() entropy, sample_args = sample_args.peel() scale_entropy = min(entropy / 2, 1) roots = _sample_roots(entropy - scale_entropy) solutions = sorted(list(sympy.FiniteSet(*roots))) coeffs = _polynomial_coeffs_with_roots(roots, scale_entropy) (polynomial_entity,) = context.sample( sample_args, [composition.Polynomial(coeffs)]) if random.choice([False, True]): # Ask for explicit roots. if len(solutions) == 1: answer = solutions[0] else: answer = display.NumberList(solutions) if polynomial_entity.has_expression(): equality = ops.Eq(polynomial_entity.expression, 0) variable = polynomial_entity.polynomial_variables[0] else: variable = sympy.Symbol(context.pop()) equality = ops.Eq(polynomial_entity.handle.apply(variable), 0) template = random.choice([ 'Let {equality}. What is {variable}?', 'Let {equality}. Calculate {variable}.', 'Suppose {equality}. What is {variable}?', 'Suppose {equality}. Calculate {variable}.', 'What is {variable} in {equality}?', 'Solve {equality} for {variable}.', 'Find {variable} such that {equality}.', 'Find {variable}, given that {equality}.', 'Determine {variable} so that {equality}.', 'Determine {variable}, given that {equality}.', 'Solve {equality}.' ]) return example.Problem( question=example.question( context, template, equality=equality, variable=variable), answer=answer) else: if polynomial_entity.has_expression(): expression = polynomial_entity.expression variable = polynomial_entity.polynomial_variables[0] else: variable = sympy.Symbol(context.pop()) expression = polynomial_entity.handle.apply(variable) factored = sympy.factor( polynomials.coefficients_to_polynomial(coeffs, variable)) template = random.choice([ 'Factor {expression}.', ]) return example.Problem( question=example.question(context, template, expression=expression), answer=factored) def _solve_linear_system(degree, value, sample_args, context=None): """Solve linear equations.""" is_question = context is None if context is None: context = composition.Context() entropy, sample_args = sample_args.peel() solutions = [] if value is not None: solutions.append(value) extra_solutions_needed = degree - len(solutions) if extra_solutions_needed > 0: entropies = (entropy / 4) * np.random.dirichlet( np.ones(extra_solutions_needed)) entropies = np.maximum(1, entropies) # min per-solution entropy entropy -= sum(entropies) solutions += [number.integer(solution_entropy, True) for solution_entropy in entropies] entropy = max(1, entropy) variables = [sympy.Symbol(context.pop()) for _ in range(degree)] solution_index = 0 # If we're going to be creating a linear system with constants to replace by # handles from other modules, then we need a linear system with constants # occurring. Very occasionally this can fail to happen, e.g., "x = -x"; # normally this while loop will only see one iteration. while True: equations = linear_system.linear_system( variables=variables, solutions=solutions, entropy=entropy, non_trivial_in=solution_index) constants = ops.number_constants(equations) if sample_args.num_modules <= 1 or constants: break context.sample_by_replacing_constants(sample_args, equations) variable = variables[solution_index] answer = solutions[solution_index] equations = ', '.join([str(equation) for equation in equations]) if is_question: template = random.choice([ 'Solve {equations} for {variable}.', ]) return example.Problem( example.question( context, template, equations=equations, variable=variable), answer) else: return composition.Entity( context=context, value=answer, description='Suppose {equations}.', handle=variable, equations=equations) @composition.module(number.is_integer) def solve_linear_1d(*args, **kwargs): return _solve_linear_system(1, *args, **kwargs) @composition.module(number.is_integer) def solve_linear_2d(*args, **kwargs): return _solve_linear_system(2, *args, **kwargs) class _PolynomialSequence(object): """A sequence given by a polynomial.""" def __init__(self, variable, entropy, min_degree=1, max_degree=3): """Initializes a random polynomial sequence. Args: variable: Variable to use. entropy: Entropy for polynomial coefficients. min_degree: Minimum order of polynomial. max_degree: Maximum order of polynomial. """ self._degree = random.randint(min_degree, max_degree) self._variable = variable polynomial = polynomials.sample_with_small_evaluation( variable=self._variable, degree=self._degree, max_abs_input=self._degree + 2, entropy=entropy) self._sympy = polynomial.sympy() @property def min_num_terms(self): """Returns the minimum number of terms to identify the sequence. This assumes a human-like prior over types of sequences. Returns: Integer >= 1. """ return self._degree + 2 @property def sympy(self): return self._sympy def term(self, n): """Returns the `n`th term of the sequence.""" return self._sympy.subs(self._variable, n) def sequence_next_term(min_entropy, max_entropy): """E.g., "What is the next term in the sequence 1, 2, 3?".""" entropy = random.uniform(min_entropy, max_entropy) context = composition.Context() variable = sympy.Symbol(context.pop()) sequence = _PolynomialSequence(variable, entropy) min_num_terms = sequence.min_num_terms num_terms = random.randint(min_num_terms, min_num_terms + 3) sequence_sample = [sequence.term(n + 1) for n in range(num_terms)] sequence_sample = display.NumberList(sequence_sample) template = random.choice([ 'What is next in {sequence}?', 'What comes next: {sequence}?', 'What is the next term in {sequence}?', ]) answer = sequence.term(num_terms + 1) return example.Problem( question=example.question(context, template, sequence=sequence_sample), answer=answer) def sequence_nth_term(min_entropy, max_entropy): """E.g., "What is the nth term in the sequence 1, 2, 3?".""" entropy = random.uniform(min_entropy, max_entropy) context = composition.Context() variable = sympy.Symbol(context.pop()) sequence = _PolynomialSequence(variable, entropy) min_num_terms = sequence.min_num_terms num_terms = random.randint(min_num_terms, min_num_terms + 3) sequence_sample = [sequence.term(n + 1) for n in range(num_terms)] sequence_sample = display.NumberList(sequence_sample) template = random.choice([ 'What is the {variable}\'th term of {sequence}?', ]) answer = sequence.sympy return example.Problem( question=example.question( context, template, variable=variable, sequence=sequence_sample), answer=answer)
mathematics_dataset-master
mathematics_dataset/modules/algebra.py
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
33