Beispiel #1
0
                -1, 1, 7, 11, -(2**15), 2**16, 2**30, 2**31, 2**32, 2**33,
                2**61, -(2**62), 2**63, 2**64
        ]:
            val = k * (s + i)
            assert hash(val) == hash(gmpy2.mpz(val)), (val, hash(val),
                                                       hash(gmpy2.mpz(val)))

print("hash tests for integer values passed")

for d in [1, -2, 3, -47, m, m * 2, 324, 797080, -979]:
    for s in [0, m // 2, m, m * 2, m * m]:
        for i in range(-10, 10):
            for k in [
                    -1, 1, 7, 11, -(2**15), 2**16, 2**30, 2**31, 2**32, 2**33,
                    2**61, -(2**62), 2**63, 2**64, 131313164,
                    -4643131646131346460964347
            ]:
                val = k * (s + i)
                if val:
                    assert hash(fractions.Fraction(d, val)) == hash(
                        gmpy2.mpq(d, val)), (d, val,
                                             hash(fractions.Fraction(d, val)),
                                             hash(gmpy.mpq(d, val)))
                if d:
                    assert hash(fractions.Fraction(val, d)) == hash(
                        gmpy2.mpq(val, d)), (val, d,
                                             hash(fractions.Fraction(val, d)),
                                             hash(gmpy.mpq(val, d)))

print("hash tests for rational values passed")
 (ds.integers, {"min_value": -2, "max_value": -1}),
 (ds.decimals, {"min_value": 1.0, "max_value": 1.5}),
 (ds.decimals, {"min_value": "1.0", "max_value": "1.5"}),
 (ds.decimals, {"min_value": decimal.Decimal("1.5")}),
 (ds.decimals, {"max_value": 1.0, "min_value": -1.0, "allow_infinity": False}),
 (ds.decimals, {"min_value": 1.0, "allow_nan": False}),
 (ds.decimals, {"max_value": 1.0, "allow_nan": False}),
 (ds.decimals, {"max_value": 1.0, "min_value": -1.0, "allow_nan": False}),
 (ds.decimals, {"min_value": "-inf"}),
 (ds.decimals, {"max_value": "inf"}),
 (ds.fractions, {"min_value": -1, "max_value": 1, "max_denominator": 1000}),
 (ds.fractions, {"min_value": 1, "max_value": 1}),
 (ds.fractions, {"min_value": 1, "max_value": 1, "max_denominator": 2}),
 (ds.fractions, {"min_value": 1.0}),
 (ds.fractions, {"min_value": decimal.Decimal("1.0")}),
 (ds.fractions, {"min_value": fractions.Fraction(1, 2)}),
 (ds.fractions, {"min_value": "1/2", "max_denominator": 2}),
 (ds.fractions, {"max_value": "1/2", "max_denominator": 3}),
 (ds.lists, {"elements": ds.nothing(), "max_size": 0}),
 (ds.lists, {"elements": ds.integers()}),
 (ds.lists, {"elements": ds.integers(), "max_size": 5}),
 (ds.lists, {"elements": ds.booleans(), "min_size": 5}),
 (ds.lists, {"elements": ds.booleans(), "min_size": 5, "max_size": 10}),
 (ds.sets, {"min_size": 10, "max_size": 10, "elements": ds.integers()}),
 (ds.booleans, {}),
 (ds.just, {"value": "hi"}),
 (ds.integers, {"min_value": 12, "max_value": 12}),
 (ds.floats, {}),
 (ds.floats, {"min_value": 1.0}),
 (ds.floats, {"max_value": 1.0}),
 (ds.floats, {"min_value": math.inf}),
def test_fraction_lt_negative(x):
    assert x <= fractions.Fraction(-1, 2)
Beispiel #4
0
def apply(model, data, overlap_shape=None, verbose=False):
    '''
    Applies a model to an input image. The input image stack is split into
    sub-blocks with model's input size, then the model is applied block by
    block. The sizes of input and output images are assumed to be the same
    while they can have different numbers of channels.

    Parameters
    ----------
    model: keras.Model
        Keras model.
    data: array_like or list of array_like
        Input data. Either an image or a list of images.
    overlap_shape: tuple of int or None
        Overlap size between sub-blocks in each dimension. If not specified,
        a default size ((32, 32) for 2D and (2, 32, 32) for 3D) is used.
        Results at overlapped areas are blended together linearly.

    Returns
    -------
    ndarray
        Result image.
    '''

    model_input_image_shape = tuple(model.input.shape.as_list()[1:-1])
    model_output_image_shape = tuple(model.output.shape.as_list()[1:-1])

    if len(model_input_image_shape) != len(model_output_image_shape):
        raise NotImplementedError

    image_dim = len(model_input_image_shape)
    num_input_channels = model.input.shape[-1].value
    num_output_channels = model.output.shape[-1].value

    scale_factor = tuple(
        fractions.Fraction(o, i)
        for i, o in zip(model_input_image_shape, model_output_image_shape))

    def _scale_tuple(t):
        t = [v * f for v, f in zip(t, scale_factor)]

        if not all([v.denominator == 1 for v in t]):
            raise NotImplementedError

        return tuple(v.numerator for v in t)

    def _scale_roi(roi):
        roi = [
            slice(r.start * f, r.stop * f) for r, f in zip(roi, scale_factor)
        ]

        if not all([
                r.start.denominator == 1 and r.stop.denominator == 1
                for r in roi
        ]):
            raise NotImplementedError

        return tuple(slice(r.start.numerator, r.stop.numerator) for r in roi)

    if overlap_shape is None:
        if image_dim == 2:
            overlap_shape = (32, 32)
        elif image_dim == 3:
            overlap_shape = (2, 32, 32)
        else:
            raise NotImplementedError
    elif len(overlap_shape) != image_dim:
        raise ValueError(f'Overlap shape must be {image_dim}D; '
                         f'Received shape: {overlap_shape}')

    step_shape = tuple(m - o
                       for m, o in zip(model_input_image_shape, overlap_shape))

    block_weight = np.ones([
        m - 2 * o
        for m, o in zip(model_output_image_shape, _scale_tuple(overlap_shape))
    ],
                           dtype=np.float32)

    block_weight = np.pad(block_weight, [(o + 1, o + 1)
                                         for o in _scale_tuple(overlap_shape)],
                          'linear_ramp')[(slice(1, -1), ) * image_dim]

    batch_size = model.gpus if is_multi_gpu_model(model) else 1
    batch = np.zeros(
        (batch_size, *model_input_image_shape, num_input_channels),
        dtype=np.float32)

    if isinstance(data, (list, tuple)):
        input_is_list = True
    else:
        data = [data]
        input_is_list = False

    result = []

    for image in data:
        # add the channel dimension if necessary
        if len(image.shape) == image_dim:
            image = image[..., np.newaxis]

        if (len(image.shape) != image_dim + 1
                or image.shape[-1] != num_input_channels):
            raise ValueError(f'Input image must be {image_dim}D with '
                             f'{num_input_channels} channels; '
                             f'Received image shape: {image.shape}')

        input_image_shape = image.shape[:-1]
        output_image_shape = _scale_tuple(input_image_shape)

        applied = np.zeros((*output_image_shape, num_output_channels),
                           dtype=np.float32)
        sum_weight = np.zeros(output_image_shape, dtype=np.float32)

        num_steps = tuple(i // s + (i % s != 0)
                          for i, s in zip(input_image_shape, step_shape))

        # top-left corner of each block
        blocks = list(
            itertools.product(
                *[np.arange(n) * s for n, s in zip(num_steps, step_shape)]))

        for chunk_index in tqdm.trange(0,
                                       len(blocks),
                                       batch_size,
                                       disable=not verbose,
                                       dynamic_ncols=True,
                                       ascii=tqdm.utils.IS_WIN):
            rois = []
            for batch_index, tl in enumerate(blocks[chunk_index:chunk_index +
                                                    batch_size]):
                br = [
                    min(t + m, i) for t, m, i in zip(
                        tl, model_input_image_shape, input_image_shape)
                ]
                r1, r2 = zip(*[(slice(s, e), slice(0, e - s))
                               for s, e in zip(tl, br)])

                m = image[r1]
                if model_input_image_shape != m.shape[-1]:
                    pad_width = [
                        (0, b - s)
                        for b, s in zip(model_input_image_shape, m.shape[:-1])
                    ]
                    pad_width.append((0, 0))
                    m = np.pad(m, pad_width, 'reflect')

                batch[batch_index] = m
                rois.append((r1, r2))

            p = model.predict(batch, batch_size=batch_size)

            for batch_index in range(len(rois)):
                for channel in range(num_output_channels):
                    p[batch_index, ..., channel] *= block_weight

                r1, r2 = [_scale_roi(roi) for roi in rois[batch_index]]

                applied[r1] += p[batch_index][r2]
                sum_weight[r1] += block_weight[r2]

        for channel in range(num_output_channels):
            applied[..., channel] /= sum_weight

        if applied.shape[-1] == 1:
            applied = applied[..., 0]

        result.append(applied)

    return result if input_is_list else result[0]
Beispiel #5
0
def test_custom_tag():
    import fractions

    class FractionType(asdftypes.AsdfType):
        name = 'fraction'
        organization = 'nowhere.org'
        version = (1, 0, 0)
        standard = 'custom'
        types = [fractions.Fraction]

        @classmethod
        def to_tree(cls, node, ctx):
            return [node.numerator, node.denominator]

        @classmethod
        def from_tree(cls, tree, ctx):
            return fractions.Fraction(tree[0], tree[1])

    class FractionExtension(object):
        @property
        def types(self):
            return [FractionType]

        @property
        def tag_mapping(self):
            return [('tag:nowhere.org:custom',
                     'http://nowhere.org/schemas/custom{tag_suffix}')]

        @property
        def url_mapping(self):
            return [('http://nowhere.org/schemas/custom/',
                     util.filepath_to_url(TEST_DATA_PATH) +
                     '/{url_suffix}.yaml')]

    class FractionCallable(FractionExtension):
        @property
        def tag_mapping(self):
            def check(tag):
                prefix = 'tag:nowhere.org:custom'
                if tag.startswith(prefix):
                    return 'http://nowhere.org/schemas/custom' + tag[len(prefix):]
            return [check]

    yaml = """
a: !<tag:nowhere.org:custom/fraction-1.0.0>
  [2, 3]
b: !core/complex-1.0.0
  0j
    """

    buff = helpers.yaml_to_asdf(yaml)
    with asdf.AsdfFile.open(
        buff, extensions=FractionExtension()) as ff:
        assert ff.tree['a'] == fractions.Fraction(2, 3)

        buff = io.BytesIO()
        ff.write_to(buff)

    buff = helpers.yaml_to_asdf(yaml)
    with asdf.AsdfFile.open(
            buff, extensions=FractionCallable()) as ff:
        assert ff.tree['a'] == fractions.Fraction(2, 3)

        buff = io.BytesIO()
        ff.write_to(buff)
        buff.close()
Beispiel #6
0
	def sqmag(self):
		return frac.Fraction(sum([x**2 for x in self.coords]))
Beispiel #7
0
    passing_params=GREATER_THAN_PARAMS + EQUALITY_PARAMS,
    failing_params=LESS_THAN_PARAMS
)


APPROXIMATE_EQUALITY_ASSERTION_PARAM_NAMES = 'first,second,rel_tol,abs_tol'
IS_CLOSE_PARAMS = [
    (0, 0, 0.0, 0.0),
    (499, 500, 0.003, 0.0),
    (1000, 1001.001, 0.001, 0.0),
    (-500, -555.5, 0.1, 55.0),
    (1e9, 9e8, 0.099, 1.0001e8),
    (True, True, 1e-09, 0.0),
    (False, False, 1e-09, 0.0),
    (decimal.Decimal('0.999'), decimal.Decimal('0.9999'), 0, 0.001),
    (fractions.Fraction(99, 100), fractions.Fraction(100, 101),
     0.00010001, 0.0),
    (3 + 4j, 3 + 5j, 0.18, 0.0),
    (3 + 4j, 4 + 3j, 0.0, 1.42),
    (0, 1e+100, 0.0, float('inf')),
    (float('inf'), float('inf'), 0.0, 0.0),
    (float('-inf'), float('-inf'), 0.0, 0.0),
]

IS_NOT_CLOSE_PARAMS = [
    (0, 0.0001, 0.0, 0.0),
    (499, 500, 0.001, 0.0),
    (1000, 1001.01, 0.001, 0.0),
    (-500, -555.5, 0.0999, 55.0),
    (1e9, 9e8, 0.099, 0.9999e8),
    (True, False, 1e-09, 0.5),
Beispiel #8
0
import re

# _tc_regex is the regex pattern for parsing a timecode string (ex: '01:00:00:00').
_tc_regex: re.Pattern = re.compile(
    r"(?P<negative>-)?"
    r"((?P<section1>[0-9]+)[:|;])?((?P<section2>[0-9]+)[:|;])?"
    r"((?P<section3>[0-9]+)[:|;])?(?P<frames>[0-9]+)$")

# _runtime_regex is the regex pattern for parsing a runtime string (ex: '01:00:00.0')
_runtime_regex: re.Pattern = re.compile(
    r"(?P<negative>-)?"
    r"((?P<section1>[0-9]+)[:|;])?((?P<section2>[0-9]+)[:|;])?"
    r"(?P<seconds>[0-9]+(\.[0-9]+)?)$")

# _feet_and_frames_regex is the regex patter for matching a feet and frames string
# (ex: 5400+13)
_feet_and_frames_regex: re.Pattern = re.compile(
    r"(?P<negative>-)?(?P<feet>[0-9]+)\+(?P<frames>[0-9]+)", )

# Cache the number of seconds in a minute and hour.
_SECONDS_PER_MINUTE: int = 60
_SECONDS_PER_HOUR: int = 3600

# _PPRO_TICKS_PER_SECOND is the number of Adobe Premiere Pro ticks in a second. This
# value is constant regardless of framerate.
_PPRO_TICKS_PER_SECOND: fractions.Fraction = fractions.Fraction(
    254016000000, 1)

# _FRAMES_PER_FOOT is the number of frames in a foot of 35mm, 4-perf film.
_FRAMES_PER_FOOT: int = 16
Beispiel #9
0
 def get_pay_fraction_display(self):
     try:
         frac = fractions.Fraction(self.get_config('pay_fraction'))
     except TypeError:
         frac = 0
     return '%.0f%%' % (frac * 100)
Beispiel #10
0
def plots(plot, p, n, steps, parray):
    N = np.arange(0, steps)
    t = N / n

    px = parray[p - 2][0]
    py = parray[p - 2][1]

    x = 1 / (steps) * np.cos((px + t * 2) * np.pi)
    x = np.append(x, x[0])

    y = 1 / (steps) * np.sin((py + t * 2) * np.pi)
    y = np.append(y, y[0])

    xc = np.cumsum(x)
    yc = np.cumsum(y)

    xd = np.diff(xc[:-1])
    yd = np.diff(yc[:-1])
    dr = np.sqrt(xd**2 + yd**2)
    circum = np.sum(dr)

    minx = np.min(xc[:n])
    miny = np.min(yc[:n])
    maxx = np.max(xc[:n])
    maxy = np.max(yc[:n])

    start = int(steps * 1 / 8)

    ax_list[4 * plot + 0].plot(xc[:n], yc[:n], linewidth=0.15, color='black')

    arrowdic = dict(arrowstyle="-",
                    lw=0.5,
                    color="black",
                    shrinkA=10,
                    shrinkB=5)

    ax_list[4 * plot + 0].annotate('A',
                                   xy=(xc[n], yc[n]),
                                   xycoords='data',
                                   fontsize=16,
                                   xytext=(0.0, -0.3),
                                   textcoords='axes fraction',
                                   color='black',
                                   arrowprops=arrowdic)

    ax_list[4 * plot + 1].plot(xc[:steps],
                               yc[:steps],
                               linewidth=0.15,
                               color='black')

    start = int(1 / 8 * steps - 200)
    stop = int(1 / 8 * steps)

    minsqrx = np.min(xc[start:stop])
    minsqry = np.min(yc[start:stop])
    maxsqrx = np.max(xc[start:stop])
    maxsqry = np.max(yc[start:stop])

    rect = patches.Rectangle((minsqrx, minsqry),
                             maxsqrx - minsqrx,
                             maxsqry - minsqry,
                             linewidth=0.5,
                             edgecolor='red',
                             facecolor='none')

    # Add the patch to the Axes
    ax_list[4 * plot + 1].add_patch(rect)

    arrowdic = dict(arrowstyle="-", lw=0.5, color="red", shrinkA=10, shrinkB=5)

    ax_list[4 * plot + 1].annotate('B',
                                   xy=(maxsqrx, minsqry),
                                   xycoords='data',
                                   fontsize=16,
                                   xytext=(1.2, 0.05),
                                   textcoords='axes fraction',
                                   color='red',
                                   arrowprops=arrowdic)

    text = ('200 steps, 1/8 total')
    ax_list[4 * plot + 2].text(0,
                               0,
                               text,
                               fontsize=12,
                               horizontalalignment='left',
                               verticalalignment='top',
                               transform=ax_list[4 * plot + 2].transAxes,
                               bbox=dict(facecolor='none',
                                         alpha=1,
                                         edgecolor='none'))

    ax_list[4 * plot + 2].plot(xc[start:stop],
                               yc[start:stop],
                               linewidth=0.5,
                               color='black')

    text = (str(steps) + ' steps')

    ax_list[4 * plot + 1].text(0,
                               0,
                               text,
                               fontsize=12,
                               horizontalalignment='left',
                               verticalalignment='top',
                               transform=ax_list[4 * plot + 1].transAxes,
                               bbox=dict(facecolor='none',
                                         alpha=1,
                                         edgecolor='none'))

    text = (
        'N=' + str(steps) + '\n' + 'p=' + str(p) + '\n' + '1/p=' +
        str(np.round(1 / (p), 3)) + '\n' +
        #str(np.array2string(np.arange(p+1)/p*2, formatter={'float_kind':lambda x: "%.1f" % x}, separator=', '))+ '$\pi$ \n\n' +
        'X, Y $\in$ ' + str(
            np.array2string(
                np.arange(p) / (p - 1) * 2,
                formatter={
                    'all':
                    lambda x: str(fractions.Fraction(x).limit_denominator())
                },
                separator=', ')) + '\n\n' + 'measured:\n' + 'walked path=' +
        str(np.round(circum, 3)) + '\n' + 'diameter=' +
        str(np.round(maxy, 3)) + '\n' + 'circumference=' +
        str(np.round(maxy * np.pi, 3)))

    ax_list[4 * plot + 3].text(-0.12,
                               0.98,
                               text,
                               fontsize=12,
                               horizontalalignment='left',
                               verticalalignment='top',
                               transform=ax_list[4 * plot + 3].transAxes)

    text = ('n=' + str(n) + '\n' + str(np.round(100 * n / steps, 4)) + '%')
    ax_list[4 * plot + 0].text(0.02,
                               0.98,
                               text,
                               fontsize=12,
                               horizontalalignment='left',
                               verticalalignment='top',
                               transform=ax_list[4 * plot + 0].transAxes)
Beispiel #11
0
import fractions
num_rings = int(input())
rings = input().strip().split()
first_number = int(rings.pop(0))
for val in rings:
    if first_number % int(val) != 0:
        print(fractions.Fraction(first_number, int(val)))
    else:
        print(str(int(first_number / int(val))) + '/1')
#!/usr/bin/python

# Modul math
import fractions

x = 1.84953
print "Zahl", x

# als fraction
b3 = fractions.Fraction(x)
print "Fraction:", b3

# approximiert
b4 = b3.limit_denominator(100)
print "Approx auf Nenner max. 100:", b4

# Genauigkeit
wert = 1.0 * b4.numerator / b4.denominator
print "Wert:", wert
print "relativer Fehler:", abs((x - wert)/x)

Beispiel #13
0
import fractions
import math

print('PI =', math.pi)

f_pi = fractions.Fraction(str(math.pi))
print('No limit =', f_pi)

for i in [1, 6, 11, 60, 70, 90, 100]:
    limited = f_pi.limit_denominator(i)
    print('{0:8} = {1}'.format(i, limited))
Beispiel #14
0
#!/usr/bin/env python3
# encoding: utf-8
#
# Copyright (c) 2009 Doug Hellmann All rights reserved.
#
"""
"""

#end_pymotw_header
import fractions

for v in [0.1, 0.5, 1.5, 2.0]:
    print('{} = {}'.format(v, fractions.Fraction(v)))
Beispiel #15
0
	def __init__(self, l):
		self.coeff = [frac.Fraction(x) for x in l]
		self.converter = Converter(coeff=self.coeff)
Beispiel #16
0
 def teaching_adjust_per_semester(self):
     credits = self.get_config('teaching_decrease')
     return TeachingAdjust(fractions.Fraction(0), credits)
Beispiel #17
0
	def __init__(self, m, b):
		self.m = frac.Fraction(m)
		self.b = frac.Fraction(b)
		self.converter = Converter(m=m, b=b)
Beispiel #18
0
def test_fraction_converted():
    assert validators.int_validator(fractions.Fraction(2, 1), {}) == 2
Beispiel #19
0

print "Computing Q matrices..."

Qs = []

for ti, _type in enumerate(types):

    if certificate["qdash_matrices"][ti] is None:
        Qs.append(None)
        continue

    if using_sage:
        QD = [[sage_eval(str(s), locals={'x': x}) for s in row] for row in certificate["qdash_matrices"][ti]]
    else:
        QD = [[fractions.Fraction(s) for s in row] for row in certificate["qdash_matrices"][ti]]

    if certificate["r_matrices"][ti] is None:
        Qs.append(QD)
        continue

    if using_sage:
        R = [[sage_eval(str(s), locals={'x': x}) for s in row] for row in certificate["r_matrices"][ti]]
    else:
        R = [[fractions.Fraction(s) for s in row] for row in certificate["r_matrices"][ti]]

    nq = len(QD)
    nf = len(flags[ti])

    Q = [[0 for j in range(i, nf)] for i in range(nf)]
    for l in range(nq):
Beispiel #20
0
def test_non_whole_fraction_raises_Invalid():
    raises_Invalid(validators.int_validator)(fractions.Fraction(3, 2), {})
In particular, ``scripts/compensated-newton/newton_de_casteljau.py``.

This takes a painfully long time (i.e. 5-6 minutes) to run.
"""

import fractions

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

import de_casteljau
import plot_utils


U = fractions.Fraction(1, 2 ** 53)
RHS = 2.0 ** 30
ALPHA = 0.25


def get_coeffs(n):
    r"""Get the coefficients of a specific polynomial.

    When :math:`p(s) = (1 - 5s)^n + 2^{30} (1 - 3s)^n`, the coefficients
    are :math:`b_j = (-4)^j + 2^{30} (-2)^j` since
    :math:`1 - 5s = (1 - s) - 4s` and :math:`1 - 2s = (1 - s) - 2s`.

    It's worth noting that these terms can be represented exactly in
    floating point when :math:`|j - 30| <= 52`.
    """
    coeffs = []
Beispiel #22
0
def get_exif_tags(data):
    """Make a simplified version with common tags from raw EXIF data."""

    logger = logging.getLogger(__name__)
    simple = {}

    for tag in ('Model', 'Make', 'LensModel'):
        if tag in data:
            if isinstance(data[tag], tuple):
                simple[tag] = data[tag][0].strip()
            else:
                simple[tag] = data[tag].strip()

    if 'FNumber' in data:
        fnumber = data['FNumber']
        try:
            simple['fstop'] = float(fnumber[0]) / fnumber[1]
        except IndexError:
            # Pillow == 3.0
            simple['fstop'] = float(fnumber[0])
        except Exception:
            logger.debug('Skipped invalid FNumber: %r', fnumber, exc_info=True)

    if 'FocalLength' in data:
        focal = data['FocalLength']
        try:
            simple['focal'] = round(float(focal[0]) / focal[1])
        except IndexError:
            # Pillow == 3.0
            simple['focal'] = round(focal[0])
        except Exception:
            logger.debug('Skipped invalid FocalLength: %r',
                         focal,
                         exc_info=True)

    if 'ExposureTime' in data:
        exptime = data['ExposureTime']
        if isinstance(exptime, tuple):
            try:
                simple['exposure'] = str(
                    fractions.Fraction(exptime[0], exptime[1]))
            except IndexError:
                # Pillow == 3.0
                simple['exposure'] = exptime[0]
            except ZeroDivisionError:
                logger.info('Invalid ExposureTime: %r', exptime)
        elif isinstance(exptime, int):
            simple['exposure'] = str(exptime)
        else:
            logger.info('Unknown format for ExposureTime: %r', exptime)

    if 'ISOSpeedRatings' in data:
        if isinstance(data['ISOSpeedRatings'], tuple):
            # Pillow == 3.0
            simple['iso'] = data['ISOSpeedRatings'][0]
        else:
            simple['iso'] = data['ISOSpeedRatings']

    if 'DateTimeOriginal' in data:
        try:
            # Remove null bytes at the end if necessary
            date = data['DateTimeOriginal'].rsplit('\x00')[0]
        except AttributeError:
            # Pillow == 3.0
            date = data['DateTimeOriginal'][0]

        try:
            simple['dateobj'] = datetime.strptime(date, '%Y:%m:%d %H:%M:%S')
            dt = simple['dateobj'].strftime('%A, %d. %B %Y')
            simple['datetime'] = dt.decode('utf8') if compat.PY2 else dt
        except (ValueError, TypeError) as e:
            logger.info(u'Could not parse DateTimeOriginal: %s', e)

    if 'GPSInfo' in data:
        info = data['GPSInfo']
        lat_info = info.get('GPSLatitude')
        lon_info = info.get('GPSLongitude')
        lat_ref_info = info.get('GPSLatitudeRef')
        lon_ref_info = info.get('GPSLongitudeRef')

        if lat_info and lon_info and lat_ref_info and lon_ref_info:
            try:
                lat = dms_to_degrees(lat_info)
                lon = dms_to_degrees(lon_info)
            except (ZeroDivisionError, ValueError):
                logger.info('Failed to read GPS info')
            else:
                simple['gps'] = {
                    'lat': -lat if lat_ref_info != 'N' else lat,
                    'lon': -lon if lon_ref_info != 'E' else lon,
                }

    return simple
Beispiel #23
0
# Contributors:
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT

"""NIST score implementation."""
from __future__ import division

import math
import fractions
from collections import Counter

from nltk.util import ngrams
from nltk.translate.bleu_score import modified_precision, closest_ref_length

try:
    fractions.Fraction(0, 1000, _normalize=False)
    from fractions import Fraction
except TypeError:
    from nltk.compat import Fraction


def sentence_nist(references, hypothesis, n=5):
    """
    Calculate NIST score from
    George Doddington. 2002. "Automatic evaluation of machine translation quality
    using n-gram co-occurrence statistics." Proceedings of HLT.
    Morgan Kaufmann Publishers Inc. http://dl.acm.org/citation.cfm?id=1289189.1289273

    DARPA commissioned NIST to develop an MT evaluation facility based on the BLEU
    score. The official script used by NIST to compute BLEU and NIST score is
    mteval-14.pl. The main differences are:
Beispiel #24
0
def compute_irasa(sig,
                  fs,
                  f_range=None,
                  hset=None,
                  thresh=None,
                  **spectrum_kwargs):
    """Separate aperiodic and periodic components using IRASA.

    Parameters
    ----------
    sig : 1d array
        Time series.
    fs : float
        The sampling frequency of sig.
    f_range : tuple, optional
        Frequency range to restrict the analysis to.
    hset : 1d array, optional
        Resampling factors used in IRASA calculation.
        If not provided, defaults to values from 1.1 to 1.9 with an increment of 0.05.
    thresh : float, optional
        A relative threshold to apply when separating out periodic components.
        The threshold is defined in terms of standard deviations of the original spectrum.
    spectrum_kwargs : dict
        Optional keywords arguments that are passed to `compute_spectrum`.

    Returns
    -------
    freqs : 1d array
        Frequency vector.
    psd_aperiodic : 1d array
        The aperiodic component of the power spectrum.
    psd_periodic : 1d array
        The periodic component of the power spectrum.

    Notes
    -----
    Irregular-Resampling Auto-Spectral Analysis (IRASA) is an algorithm ([1]_) that aims to
    separate 1/f and periodic components by resampling time series and computing power spectra,
    averaging away any activity that is frequency specific to isolate the aperiodic component.

    References
    ----------
    .. [1] Wen, H., & Liu, Z. (2016). Separating Fractal and Oscillatory Components in
           the Power Spectrum of Neurophysiological Signal. Brain Topography, 29(1), 13–26.
           DOI: https://doi.org/10.1007/s10548-015-0448-0
    """

    # Check & get the resampling factors, with rounding to avoid floating point precision errors
    hset = np.arange(1.1, 1.95, 0.05) if hset is None else hset
    hset = np.round(hset, 4)

    # The `nperseg` input needs to be set to lock in the size of the FFT's
    if 'nperseg' not in spectrum_kwargs:
        spectrum_kwargs['nperseg'] = int(4 * fs)

    # Calculate the original spectrum across the whole signal
    freqs, psd = compute_spectrum(sig, fs, **spectrum_kwargs)

    # Do the IRASA resampling procedure
    psds = np.zeros((len(hset), *psd.shape))
    for ind, h_val in enumerate(hset):

        # Get the up-sampling / down-sampling (h, 1/h) factors as integers
        rat = fractions.Fraction(str(h_val))
        up, dn = rat.numerator, rat.denominator

        # Resample signal
        sig_up = signal.resample_poly(sig, up, dn, axis=-1)
        sig_dn = signal.resample_poly(sig, dn, up, axis=-1)

        # Calculate the power spectrum, using the same params as original
        freqs_up, psd_up = compute_spectrum(sig_up, h_val * fs,
                                            **spectrum_kwargs)
        freqs_dn, psd_dn = compute_spectrum(sig_dn, fs / h_val,
                                            **spectrum_kwargs)

        # Calculate the geometric mean of h and 1/h
        psds[ind, :] = np.sqrt(psd_up * psd_dn)

    # Take the median resampled spectra, as an estimate of the aperiodic component
    psd_aperiodic = np.median(psds, axis=0)

    # Subtract aperiodic from original, to get the periodic component
    psd_periodic = psd - psd_aperiodic

    # Apply a relative threshold for tuning which activity is labeled as periodic
    if thresh is not None:
        sub_thresh = np.where(
            psd_periodic - psd_aperiodic < thresh * np.std(psd))[0]
        psd_periodic[sub_thresh] = 0
        psd_aperiodic[sub_thresh] = psd[sub_thresh]

    # Restrict spectrum to requested range
    if f_range:
        psds = np.array([psd_aperiodic, psd_periodic])
        freqs, (psd_aperiodic,
                psd_periodic) = trim_spectrum(freqs, psds, f_range)

    return freqs, psd_aperiodic, psd_periodic
Beispiel #25
0
 def from_tree(cls, tree, ctx):
     return fractions.Fraction(tree[0], tree[1])
Beispiel #26
0
        repositionPart(participants)
    elif cmd == "c":
        break


def lcm(a, b):
    if a == 0 and b == 0:
        return 0
    return abs(a * b) / fractions.gcd(a, b)


if len(participants) == 0:
    print "No participants"
    sys.exit(1)

total = fractions.Fraction()
for p in participants:
    total += p[1]
den = 1
for p in participants:
    p[2] = p[1] / total
    den = lcm(den, p[2].denominator)

prev = 0
print "Ticket numbers (inclusive):"
for p in participants:
    tickets = p[2].numerator * (den / p[2].denominator)
    p[2] = prev + tickets
    print str(prev + 1) + " - " + str(p[2]) + ':', p[0]
    prev = p[2]
def test_fraction_gt_positive(x):
    assert fractions.Fraction(1, 2) <= x
Beispiel #28
0
	def __init__(self, coords):
		self.coords = [frac.Fraction(x) for x in coords]
Beispiel #29
0
 def __init__(self):
     self.fps = fractions.Fraction(25, 1)
     self.layers = {}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""a docstring"""
import decimal
import fractions

INTVAL = 1
FLOATVAL = 0.1
DECVAL = decimal.Decimal('0.1')
FRACVAL = fractions.Fraction(1,10)

FRAC_DEC_EQUAL = DECVAL == FRACVAL
DEC_FLOAT_INEQUAL = DECVAL != FLOATVAL