Skip to content

Commit

Permalink
Use math.inf instead of float('inf')
Browse files Browse the repository at this point in the history
  • Loading branch information
renatahodovan committed Feb 23, 2020
1 parent 8655b83 commit 6a3a59b
Show file tree
Hide file tree
Showing 5 changed files with 17 additions and 12 deletions.
5 changes: 3 additions & 2 deletions grammarinator/generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import sys

from argparse import ArgumentParser, ArgumentTypeError
from math import inf
from multiprocessing import Pool
from os.path import abspath, basename, dirname, isdir, join, splitext
from shutil import rmtree
Expand Down Expand Up @@ -47,7 +48,7 @@ def size(self):
class Generator(object):

def __init__(self, generator_path, rule, out_format,
model=None, max_depth=float('inf'), cooldown=1.0,
model=None, max_depth=inf, cooldown=1.0,
population=None, generate=True, mutate=True, recombine=True, keep_trees=False,
tree_transformers=None, test_transformers=None,
cleanup=True, encoding='utf-8'):
Expand Down Expand Up @@ -229,7 +230,7 @@ def restricted_float(value):
help='list of transformers (in package.module.function format) to postprocess the generated tree '
'(the result of these transformers will only affect test serialization but won\'t be saved to the '
'tree representation, e.g., space insertion).')
parser.add_argument('-d', '--max-depth', default=float('inf'), type=int, metavar='NUM',
parser.add_argument('-d', '--max-depth', default=inf, type=int, metavar='NUM',
help='maximum recursion depth during generation (default: %(default)f).')
parser.add_argument('-c', '--cooldown', default=1.0, type=restricted_float, metavar='NUM',
help='cool-down factor defines how much the probability of an alternative should decrease '
Expand Down
9 changes: 5 additions & 4 deletions grammarinator/parse.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Copyright (c) 2018-2019 Renata Hodovan, Akos Kiss.
# Copyright (c) 2018-2020 Renata Hodovan, Akos Kiss.
#
# Licensed under the BSD 3-Clause License
# <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>.
Expand All @@ -13,6 +13,7 @@
import sys

from argparse import ArgumentParser
from math import inf
from multiprocessing import Pool
from os.path import basename, exists, join

Expand Down Expand Up @@ -48,8 +49,8 @@ class ParserFactory(object):
"""

def __init__(self, grammars, parser_dir,
hidden=None, transformers=None, antlr=default_antlr_path, max_depth='inf', cleanup=True):
self.max_depth = max_depth if not isinstance(max_depth, str) else (float('inf') if max_depth == 'inf' else int(max_depth))
hidden=None, transformers=None, antlr=default_antlr_path, max_depth=inf, cleanup=True):
self.max_depth = float(max_depth)
self.cleanup = cleanup in [True, 1, 'True', 'true']
transformers = transformers if isinstance(transformers, list) else json.loads(transformers) if transformers else []
self.transformers = [import_entity(transformer) if isinstance(transformer, str) else transformer for transformer in transformers]
Expand Down Expand Up @@ -177,7 +178,7 @@ def execute():
help='disable the removal of intermediate files.')
parser.add_argument('-j', '--jobs', default=os.cpu_count(), type=int, metavar='NUM',
help='parsing parallelization level (default: number of cpu cores (%(default)d)).')
parser.add_argument('--max-depth', type=int, default=float('inf'),
parser.add_argument('--max-depth', type=int, default=inf,
help='maximum expected tree depth (deeper tests will be discarded (default: %(default)f)).')
parser.add_argument('-o', '--out', metavar='DIR', default=os.getcwd(),
help='directory to save the trees (default: %(default)s).')
Expand Down
7 changes: 4 additions & 3 deletions grammarinator/process.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from argparse import ArgumentParser
from collections import defaultdict
from contextlib import contextmanager
from math import inf
from os import getcwd, makedirs
from os.path import dirname, exists, join
from pkgutil import get_data
Expand Down Expand Up @@ -66,7 +67,7 @@ def add_edge(self, frm, to):
self.vertices[frm].out_neighbours.append(self.vertices[to])

def calc_min_depths(self):
min_depths = defaultdict(lambda: float('inf'))
min_depths = defaultdict(lambda: inf)
changed = True

while changed:
Expand All @@ -83,15 +84,15 @@ def calc_min_depths(self):
# Lift the minimal depths of the alternatives to the alternations, where the decision will happen.
for ident in min_depths:
if isinstance(self.vertices[ident], AlternationNode):
assert all(min_depths[node.id] < float('inf') for node in self.vertices[ident].out_neighbours), '{ident} has an alternative that isn\'t reachable.'.format(ident=ident)
assert all(min_depths[node.id] < inf for node in self.vertices[ident].out_neighbours), '{ident} has an alternative that isn\'t reachable.'.format(ident=ident)
min_depths[ident] = [min_depths[node.id] for node in self.vertices[ident].out_neighbours]

# Remove the lifted Alternatives and check for infinite derivations.
for ident in list(min_depths.keys()):
if isinstance(self.vertices[ident], AlternativeNode):
del min_depths[ident]
else:
assert min_depths[ident] != float('inf'), 'Rule with infinite derivation: %s' % ident
assert min_depths[ident] != inf, 'Rule with infinite derivation: %s' % ident

return min_depths

Expand Down
3 changes: 2 additions & 1 deletion grammarinator/runtime/generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import string

from itertools import chain
from math import inf

from ..model import RandomModel

Expand Down Expand Up @@ -68,7 +69,7 @@ def controlled_fn(obj, *args, **kwargs):

class Generator(object):

def __init__(self, *, model=None, max_depth=float('inf'), weights=None, cooldown=1.0):
def __init__(self, *, model=None, max_depth=inf, weights=None, cooldown=1.0):
self.model = model or RandomModel()
self.max_depth = max_depth
self.weights = weights
Expand Down
5 changes: 3 additions & 2 deletions grammarinator/runtime/tree.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Copyright (c) 2017-2018 Renata Hodovan, Akos Kiss.
# Copyright (c) 2017-2020 Renata Hodovan, Akos Kiss.
#
# Licensed under the BSD 3-Clause License
# <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>.
Expand All @@ -8,6 +8,7 @@
import pickle

from copy import copy, deepcopy
from math import inf


class Tree(object):
Expand Down Expand Up @@ -55,7 +56,7 @@ def load(fn):
with open(fn, 'rb') as f:
return pickle.load(f)

def save(self, fn, max_depth=float('inf')):
def save(self, fn, max_depth=inf):
self.annotate()

if self.root.depth <= max_depth:
Expand Down

0 comments on commit 6a3a59b

Please sign in to comment.