Python math.fsum() Examples

The following are 30 code examples for showing how to use math.fsum(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module math , or try the search function .

Example 1
Project: ironpython2   Author: IronLanguages   File: test_random.py    License: Apache License 2.0 6 votes vote down vote up
def gamma(z, sqrt2pi=(2.0*pi)**0.5):
    # Reflection to right half of complex plane
    if z < 0.5:
        return pi / sin(pi*z) / gamma(1.0-z)
    # Lanczos approximation with g=7
    az = z + (7.0 - 0.5)
    return az ** (z-0.5) / exp(az) * sqrt2pi * fsum([
        0.9999999999995183,
        676.5203681218835 / z,
        -1259.139216722289 / (z+1.0),
        771.3234287757674 / (z+2.0),
        -176.6150291498386 / (z+3.0),
        12.50734324009056 / (z+4.0),
        -0.1385710331296526 / (z+5.0),
        0.9934937113930748e-05 / (z+6.0),
        0.1659470187408462e-06 / (z+7.0),
    ]) 
Example 2
Project: BinderFilter   Author: dxwu   File: test_random.py    License: MIT License 6 votes vote down vote up
def gamma(z, sqrt2pi=(2.0*pi)**0.5):
    # Reflection to right half of complex plane
    if z < 0.5:
        return pi / sin(pi*z) / gamma(1.0-z)
    # Lanczos approximation with g=7
    az = z + (7.0 - 0.5)
    return az ** (z-0.5) / exp(az) * sqrt2pi * fsum([
        0.9999999999995183,
        676.5203681218835 / z,
        -1259.139216722289 / (z+1.0),
        771.3234287757674 / (z+2.0),
        -176.6150291498386 / (z+3.0),
        12.50734324009056 / (z+4.0),
        -0.1385710331296526 / (z+5.0),
        0.9934937113930748e-05 / (z+6.0),
        0.1659470187408462e-06 / (z+7.0),
    ]) 
Example 3
Project: oss-ftp   Author: aliyun   File: test_random.py    License: MIT License 6 votes vote down vote up
def gamma(z, sqrt2pi=(2.0*pi)**0.5):
    # Reflection to right half of complex plane
    if z < 0.5:
        return pi / sin(pi*z) / gamma(1.0-z)
    # Lanczos approximation with g=7
    az = z + (7.0 - 0.5)
    return az ** (z-0.5) / exp(az) * sqrt2pi * fsum([
        0.9999999999995183,
        676.5203681218835 / z,
        -1259.139216722289 / (z+1.0),
        771.3234287757674 / (z+2.0),
        -176.6150291498386 / (z+3.0),
        12.50734324009056 / (z+4.0),
        -0.1385710331296526 / (z+5.0),
        0.9934937113930748e-05 / (z+6.0),
        0.1659470187408462e-06 / (z+7.0),
    ]) 
Example 4
Project: PyDDM   Author: mwshinn   File: solution.py    License: MIT License 6 votes vote down vote up
def __init__(self, pdf_corr, pdf_err, model, conditions, pdf_undec=None, pdf_evolution=None):
        """Create a Solution object from the results of a model
        simulation.

        Constructor takes four arguments.

            - `pdf_corr` - a size N numpy ndarray describing the correct portion of the joint pdf
            - `pdf_err` - a size N numpy ndarray describing the error portion of the joint pdf
            - `model` - the Model object used to generate `pdf_corr` and `pdf_err`
            - `conditions` - a dictionary of condition names/values used to generate the solution
            - `pdf_undec` - a size M numpy ndarray describing the final state of the simulation.  None if unavailable.
            - `pdf_evolution` - a size M-by-N numpy ndarray describing the state of the simulation at each time step. None if unavailable.
        """
        self.model = copy.deepcopy(model) # TODO this could cause a memory leak if I forget it is there...
        self.corr = pdf_corr 
        self.err = pdf_err
        self.undec = pdf_undec
        self.evolution = pdf_evolution
        # Correct floating point errors to always get prob <= 1
        if fsum(self.corr.tolist() + self.err.tolist()) > 1:
            self.corr /= 1.00000000001
            self.err /= 1.00000000001
        self.conditions = conditions 
Example 5
Project: Jandroid   Author: FSecureLABS   File: commits.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def main():
  for repository in _REPOSITORIES:
    commit_times = CommitTimes(repository, _REVISION_COUNT)

    commit_durations = []
    for time1, time2 in Pairwise(commit_times):
      #if not (IsWeekday(time1) and IsWeekday(time2)):
      #  continue
      commit_durations.append((time1 - time2).total_seconds() / 60.)
    commit_durations.sort()

    print 'REPOSITORY:', repository
    print 'Start Date:', min(commit_times), 'PDT'
    print '  End Date:', max(commit_times), 'PDT'
    print '  Duration:', max(commit_times) - min(commit_times)
    print '         n:', len(commit_times)

    for p in (0.25, 0.50, 0.90):
      percentile = Percentile(commit_durations, p)
      print '%3d%% commit duration:' % (p * 100), '%6.1fm' % percentile
    mean = math.fsum(commit_durations) / len(commit_durations)
    print 'Mean commit duration:', '%6.1fm' % mean
    print 
Example 6
Project: Jandroid   Author: FSecureLABS   File: commits.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def main():
  for repository in _REPOSITORIES:
    commit_times = CommitTimes(repository, _REVISION_COUNT)

    commit_durations = []
    for time1, time2 in Pairwise(commit_times):
      #if not (IsWeekday(time1) and IsWeekday(time2)):
      #  continue
      commit_durations.append((time1 - time2).total_seconds() / 60.)
    commit_durations.sort()

    print 'REPOSITORY:', repository
    print 'Start Date:', min(commit_times), 'PDT'
    print '  End Date:', max(commit_times), 'PDT'
    print '  Duration:', max(commit_times) - min(commit_times)
    print '         n:', len(commit_times)

    for p in (0.25, 0.50, 0.90):
      percentile = Percentile(commit_durations, p)
      print '%3d%% commit duration:' % (p * 100), '%6.1fm' % percentile
    mean = math.fsum(commit_durations) / len(commit_durations)
    print 'Mean commit duration:', '%6.1fm' % mean
    print 
Example 7
Project: Jandroid   Author: FSecureLABS   File: commits.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def main():
  for repository in _REPOSITORIES:
    commit_times = CommitTimes(repository, _REVISION_COUNT)

    commit_durations = []
    for time1, time2 in Pairwise(commit_times):
      #if not (IsWeekday(time1) and IsWeekday(time2)):
      #  continue
      commit_durations.append((time1 - time2).total_seconds() / 60.)
    commit_durations.sort()

    print 'REPOSITORY:', repository
    print 'Start Date:', min(commit_times), 'PDT'
    print '  End Date:', max(commit_times), 'PDT'
    print '  Duration:', max(commit_times) - min(commit_times)
    print '         n:', len(commit_times)

    for p in (0.25, 0.50, 0.90):
      percentile = Percentile(commit_durations, p)
      print '%3d%% commit duration:' % (p * 100), '%6.1fm' % percentile
    mean = math.fsum(commit_durations) / len(commit_durations)
    print 'Mean commit duration:', '%6.1fm' % mean
    print 
Example 8
Project: Fluid-Designer   Author: Microvellum   File: test_random.py    License: GNU General Public License v3.0 6 votes vote down vote up
def gamma(z, sqrt2pi=(2.0*pi)**0.5):
    # Reflection to right half of complex plane
    if z < 0.5:
        return pi / sin(pi*z) / gamma(1.0-z)
    # Lanczos approximation with g=7
    az = z + (7.0 - 0.5)
    return az ** (z-0.5) / exp(az) * sqrt2pi * fsum([
        0.9999999999995183,
        676.5203681218835 / z,
        -1259.139216722289 / (z+1.0),
        771.3234287757674 / (z+2.0),
        -176.6150291498386 / (z+3.0),
        12.50734324009056 / (z+4.0),
        -0.1385710331296526 / (z+5.0),
        0.9934937113930748e-05 / (z+6.0),
        0.1659470187408462e-06 / (z+7.0),
    ]) 
Example 9
Project: qiskit-aqua   Author: Qiskit   File: quadratic_program.py    License: Apache License 2.0 6 votes vote down vote up
def _quadratic_constraints(self) -> bool:
        feasible = True
        for quad_cst in self._src.quadratic_constraints:
            const1, lin1 = self._linear_expression(quad_cst.linear)
            const2, lin2, quadratic = self._quadratic_expression(quad_cst.quadratic)
            rhs = -fsum([-quad_cst.rhs] + const1 + const2)
            linear = lin1.coefficients + lin2.coefficients

            if quadratic.coefficients.nnz > 0:
                self._dst.quadratic_constraint(name=quad_cst.name, linear=linear,
                                               quadratic=quadratic.coefficients,
                                               sense=quad_cst.sense, rhs=rhs)
            elif linear.nnz > 0:
                name = quad_cst.name
                lin_names = set(lin.name for lin in self._dst.linear_constraints)
                while name in lin_names:
                    name = '_' + name
                self._dst.linear_constraint(name=name, linear=linear, sense=quad_cst.sense, rhs=rhs)
            else:
                if not self._feasible(quad_cst.sense, rhs):
                    logger.warning('constraint %s is infeasible due to substitution', quad_cst.name)
                    feasible = False

        return feasible 
Example 10
Project: ironpython3   Author: IronLanguages   File: test_random.py    License: Apache License 2.0 6 votes vote down vote up
def gamma(z, sqrt2pi=(2.0*pi)**0.5):
    # Reflection to right half of complex plane
    if z < 0.5:
        return pi / sin(pi*z) / gamma(1.0-z)
    # Lanczos approximation with g=7
    az = z + (7.0 - 0.5)
    return az ** (z-0.5) / exp(az) * sqrt2pi * fsum([
        0.9999999999995183,
        676.5203681218835 / z,
        -1259.139216722289 / (z+1.0),
        771.3234287757674 / (z+2.0),
        -176.6150291498386 / (z+3.0),
        12.50734324009056 / (z+4.0),
        -0.1385710331296526 / (z+5.0),
        0.9934937113930748e-05 / (z+6.0),
        0.1659470187408462e-06 / (z+7.0),
    ]) 
Example 11
Project: eduActiv8   Author: imiolek-ireneusz   File: ratio_hq.py    License: GNU General Public License v3.0 6 votes vote down vote up
def draw_minicircles(self):
        ttl = int(fsum(self.numbers))
        angle_step = 2 * pi / ttl
        angle_start = -pi / 2
        r = self.size // 2.5
        r2 = self.size // 17
        # manually draw the arc - the 100% width of the arc does not impress

        for i in range(ttl):
            # angle for line
            angle = angle_start + angle_step * i

            # Calculate the x,y for the end point
            x = r * cos(angle) + self.center[0]
            y = r * sin(angle) + self.center[1]
            if i < self.numbers[0]:
                pygame.draw.circle(self.canvas, self.color1, [int(x), int(y)], r2, 0)
                pygame.draw.circle(self.canvas, self.border_color1, [int(x), int(y)], r2, 2)
            elif i < self.numbers[0] + self.numbers[1]:
                pygame.draw.circle(self.canvas, self.color2, [int(x), int(y)], r2, 0)
                pygame.draw.circle(self.canvas, self.border_color2, [int(x), int(y)], r2, 2)
            else:
                pygame.draw.circle(self.canvas, self.color3, [int(x), int(y)], r2, 0)
                pygame.draw.circle(self.canvas, self.border_color3, [int(x), int(y)], r2, 2)
            # Draw the line from the self.center to the calculated end point 
Example 12
Project: gcblue   Author: gcblue   File: test_random.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def gamma(z, sqrt2pi=(2.0*pi)**0.5):
    # Reflection to right half of complex plane
    if z < 0.5:
        return pi / sin(pi*z) / gamma(1.0-z)
    # Lanczos approximation with g=7
    az = z + (7.0 - 0.5)
    return az ** (z-0.5) / exp(az) * sqrt2pi * fsum([
        0.9999999999995183,
        676.5203681218835 / z,
        -1259.139216722289 / (z+1.0),
        771.3234287757674 / (z+2.0),
        -176.6150291498386 / (z+3.0),
        12.50734324009056 / (z+4.0),
        -0.1385710331296526 / (z+5.0),
        0.9934937113930748e-05 / (z+6.0),
        0.1659470187408462e-06 / (z+7.0),
    ]) 
Example 13
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: test_random.py    License: GNU General Public License v3.0 6 votes vote down vote up
def gamma(z, sqrt2pi=(2.0*pi)**0.5):
    # Reflection to right half of complex plane
    if z < 0.5:
        return pi / sin(pi*z) / gamma(1.0-z)
    # Lanczos approximation with g=7
    az = z + (7.0 - 0.5)
    return az ** (z-0.5) / exp(az) * sqrt2pi * fsum([
        0.9999999999995183,
        676.5203681218835 / z,
        -1259.139216722289 / (z+1.0),
        771.3234287757674 / (z+2.0),
        -176.6150291498386 / (z+3.0),
        12.50734324009056 / (z+4.0),
        -0.1385710331296526 / (z+5.0),
        0.9934937113930748e-05 / (z+6.0),
        0.1659470187408462e-06 / (z+7.0),
    ]) 
Example 14
Project: meshplex   Author: nschloe   File: mesh_tetra_test.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_toy_geometric():
    mesh = meshplex.read(this_dir / "meshes" / "toy.vtk")

    mesh = meshplex.MeshTetra(mesh.node_coords, mesh.cells["nodes"])

    run(
        mesh,
        volume=9.3875504672601107,
        convol_norms=[0.20175742659663737, 0.0093164692200450819],
        ce_ratio_norms=[13.497977312281323, 0.42980191511570004],
        cellvol_norms=[0.091903119589148916, 0.0019959463063558944],
        tol=1.0e-6,
    )

    cc = mesh.cell_circumcenters
    cc_norm_2 = fsum(cc.flat)
    cc_norm_inf = max(cc.flat)
    assert abs(cc_norm_2 - 1103.7038287583791) < 1.0e-12
    assert abs(cc_norm_inf - 3.4234008596539662) < 1.0e-12 
Example 15
Project: ConvLab   Author: ConvLab   File: nlp.py    License: MIT License 5 votes vote down vote up
def sentence_bleu_4(hyp, refs, weights=[0.25, 0.25, 0.25, 0.25]):
    # input : single sentence, multiple references
    count = [0, 0, 0, 0]
    clip_count = [0, 0, 0, 0]
    r = 0
    c = 0

    for i in range(4):
        hypcnts = Counter(ngrams(hyp, i + 1))
        cnt = sum(hypcnts.values())
        count[i] += cnt

        # compute clipped counts
        max_counts = {}
        for ref in refs:
            refcnts = Counter(ngrams(ref, i + 1))
            for ng in hypcnts:
                max_counts[ng] = max(max_counts.get(ng, 0), refcnts[ng])
        clipcnt = dict((ng, min(count, max_counts[ng])) \
                       for ng, count in hypcnts.items())
        clip_count[i] += sum(clipcnt.values())

    bestmatch = [1000, 1000]
    for ref in refs:
        if bestmatch[0] == 0:
            break
        diff = abs(len(ref) - len(hyp))
        if diff < bestmatch[0]:
            bestmatch[0] = diff
            bestmatch[1] = len(ref)
    r = bestmatch[1]
    c = len(hyp)

    p0 = 1e-7
    bp = math.exp(-abs(1.0 - float(r) / float(c + p0)))

    p_ns = [float(clip_count[i]) / float(count[i] + p0) + p0 for i in range(4)]
    s = math.fsum(w * math.log(p_n) for w, p_n in zip(weights, p_ns) if p_n)
    bleu_hyp = bp * math.exp(s)

    return bleu_hyp 
Example 16
Project: emotion_classification   Author: XiaoYee   File: utils.py    License: MIT License 5 votes vote down vote up
def softmax(x):
    y = [math.exp(k) for k in x]
    sum_y = math.fsum(y)
    z = [k/sum_y for k in y]
    return z 
Example 17
Project: emotion_classification   Author: XiaoYee   File: utils.py    License: MIT License 5 votes vote down vote up
def softmax(x):
    y = [math.exp(k) for k in x]
    sum_y = math.fsum(y)
    z = [k/sum_y for k in y]
    return z 
Example 18
Project: optimesh   Author: nschloe   File: helpers.py    License: MIT License 5 votes vote down vote up
def run(mesh, volume, convol_norms, ce_ratio_norms, cellvol_norms, tol=1.0e-12):
    # Check cell volumes.
    total_cellvolume = fsum(mesh.cell_volumes)
    assert abs(volume - total_cellvolume) < tol * volume
    norm2 = numpy.linalg.norm(mesh.cell_volumes, ord=2)
    norm_inf = numpy.linalg.norm(mesh.cell_volumes, ord=numpy.Inf)
    assert near_equal(cellvol_norms, [norm2, norm_inf], tol)

    # If everything is Delaunay and the boundary elements aren't flat, the
    # volume of the domain is given by
    #   1/n * edge_lengths * ce_ratios.
    # Unfortunately, this isn't always the case.
    # ```
    # total_ce_ratio = \
    #     fsum(mesh.edge_lengths**2 * mesh.get_ce_ratios_per_edge() / dim)
    # self.assertAlmostEqual(volume, total_ce_ratio, delta=tol * volume)
    # ```
    # Check ce_ratio norms.
    # TODO reinstate
    alpha2 = fsum((mesh.get_ce_ratios() ** 2).flat)
    alpha_inf = max(abs(mesh.get_ce_ratios()).flat)
    assert near_equal(ce_ratio_norms, [alpha2, alpha_inf], tol)

    # Check the volume by summing over the absolute value of the control
    # volumes.
    vol = fsum(mesh.get_control_volumes())
    assert abs(volume - vol) < tol * volume
    # Check control volume norms.
    norm2 = numpy.linalg.norm(mesh.get_control_volumes(), ord=2)
    norm_inf = numpy.linalg.norm(mesh.get_control_volumes(), ord=numpy.Inf)
    assert near_equal(convol_norms, [norm2, norm_inf], tol)

    return 
Example 19
Project: aumfor   Author: virtualrealitysystems   File: text.py    License: GNU General Public License v3.0 5 votes vote down vote up
def partition_width(self, widths):
        """Determines if the widths are over the maximum available space, and if so shrinks them"""
        if math.fsum(widths) + (len(widths) - 1) > self.max_width:
            remainder = (int(math.fsum(widths)) + (len(widths) - 1)) - self.max_width
            # Take from the largest column first, eventually evening out
            for i in range(remainder):
                col_index = widths.index(max(widths))
                widths[col_index] -= 1
        return widths 
Example 20
Project: PyDDM   Author: mwshinn   File: solution.py    License: MIT License 5 votes vote down vote up
def _test(v):
        # TODO should these be Positive0 instead of Number?
        assert v.corr in NDArray(d=1, t=Number), "Invalid corr histogram"
        assert v.err in NDArray(d=1, t=Number), "Invalid err histogram"
        if v.undec is not None:
            assert v.undec in NDArray(d=1, t=Number), "Invalid err histogram"
            assert len(v.undec) == len(v.model.x_domain(conditions=v.conditions))
        #assert v.model is Generic(Model), "Invalid model" # TODO could cause inf recursion issue
        assert len(v.corr) == len(v.err) == len(v.model.t_domain()), "Histogram lengths must match"
        assert 0 <= fsum(v.corr.tolist() + v.err.tolist()) <= 1, "Histogram does not integrate " \
            " to 1, not to " + str(fsum(v.corr.tolist() + v.err.tolist()))
        assert v.conditions in Conditions() 
Example 21
Project: PyDDM   Author: mwshinn   File: solution.py    License: MIT License 5 votes vote down vote up
def prob_correct(self):
        """Probability of correct response within the time limit."""
        return fsum(self.corr) 
Example 22
Project: PyDDM   Author: mwshinn   File: solution.py    License: MIT License 5 votes vote down vote up
def prob_error(self):
        """Probability of incorrect (error) response within the time limit."""
        return fsum(self.err) 
Example 23
Project: PyDDM   Author: mwshinn   File: solution.py    License: MIT License 5 votes vote down vote up
def prob_undecided(self):
        """The probability of not responding during the time limit."""
        udprob = 1 - fsum(self.corr.tolist() + self.err.tolist())
        if udprob < 0:
            print("Warning, setting undecided probability from %f to 0" % udprob)
            udprob = 0
        return udprob 
Example 24
Project: PyDDM   Author: mwshinn   File: unit_tests.py    License: MIT License 5 votes vote down vote up
def test_pdfs(self):
        """Produce valid distributions which sum to one"""
        dt = .02
        for n,s in self.samps.items():
            if n == "empty": continue
            assert np.isclose(fsum([fsum(s.pdf_corr(T_dur=4, dt=dt))*dt, fsum(s.pdf_err(T_dur=4, dt=dt))*dt, s.prob_undecided()]), 1)
            assert np.isclose(fsum(s.pdf_corr(T_dur=4, dt=dt)*dt), s.prob_correct())
            assert np.isclose(fsum(s.pdf_err(T_dur=4, dt=dt)*dt), s.prob_error())
            assert s.mean_decision_time() > 0
            if s.prob_undecided() == 0:
                assert s.prob_correct() == s.prob_correct_forced()
                assert s.prob_error() == s.prob_error_forced()
            assert len(s.pdf_corr(T_dur=4, dt=dt)) == len(s.t_domain(T_dur=4, dt=dt)) 
Example 25
Project: PyDDM   Author: mwshinn   File: unit_tests.py    License: MIT License 5 votes vote down vote up
def test_pdfs(self):
        """Make sure we produce valid distributions from solutions"""
        # For each test model
        for s in self.all_sols:
            dt = s.model.dt
            # Distribution sums to 1
            assert np.isclose(fsum([fsum(s.pdf_corr())*dt, fsum(s.pdf_err())*dt, s.prob_undecided()]), 1)
            # Correct and error probabilities are sensible
            assert np.isclose(fsum(s.pdf_corr()*dt), s.prob_correct())
            assert np.isclose(fsum(s.pdf_err()*dt), s.prob_error())
            assert s.mean_decision_time() > 0
            if s.prob_undecided() == 0:
                assert s.prob_correct() == s.prob_correct_forced()
                assert s.prob_error() == s.prob_error_forced()
            # Signed probabilities sum to 1
            if s.undec is not None:
                assert np.isclose(np.sum(s.prob_correct_sign()) + np.sum(s.prob_error_sign()), 1, rtol=.005)
                assert np.sum(s.prob_correct_sign()) + np.sum(s.prob_error_sign()) <= 1
            # Correct time domain
            assert len(s.pdf_corr()) == len(s.model.t_domain())
        # pdf_undec with pdf_corr and pdf_err sums to one if pdf_undec exists
        for s in [self.quick_cn, self.quick_imp, self.params_cn, self.params_imp]:
            dx = s.model.dx
            if s.undec is not None:
                # Allow better tolerance since accuracy isn't perfect for undecided pdf
                assert np.isclose(fsum([fsum(s.pdf_corr())*dt, fsum(s.pdf_err())*dt, fsum(s.pdf_undec())*dx]), 1, atol=.001) 
Example 26
Project: multiwoz   Author: budzianowski   File: nlp.py    License: MIT License 5 votes vote down vote up
def sentence_bleu_4(hyp, refs, weights=[0.25, 0.25, 0.25, 0.25]):
    # input : single sentence, multiple references
    count = [0, 0, 0, 0]
    clip_count = [0, 0, 0, 0]
    r = 0
    c = 0

    for i in range(4):
        hypcnts = Counter(ngrams(hyp, i + 1))
        cnt = sum(hypcnts.values())
        count[i] += cnt

        # compute clipped counts
        max_counts = {}
        for ref in refs:
            refcnts = Counter(ngrams(ref, i + 1))
            for ng in hypcnts:
                max_counts[ng] = max(max_counts.get(ng, 0), refcnts[ng])
        clipcnt = dict((ng, min(count, max_counts[ng])) \
                       for ng, count in hypcnts.items())
        clip_count[i] += sum(clipcnt.values())

    bestmatch = [1000, 1000]
    for ref in refs:
        if bestmatch[0] == 0:
            break
        diff = abs(len(ref) - len(hyp))
        if diff < bestmatch[0]:
            bestmatch[0] = diff
            bestmatch[1] = len(ref)
    r = bestmatch[1]
    c = len(hyp)

    p0 = 1e-7
    bp = math.exp(-abs(1.0 - float(r) / float(c + p0)))

    p_ns = [float(clip_count[i]) / float(count[i] + p0) + p0 for i in range(4)]
    s = math.fsum(w * math.log(p_n) for w, p_n in zip(weights, p_ns) if p_n)
    bleu_hyp = bp * math.exp(s)

    return bleu_hyp 
Example 27
Project: Fluid-Designer   Author: Microvellum   File: test_statistics.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_compare_with_math_fsum(self):
        # Compare with the math.fsum function.
        # Ideally we ought to get the exact same result, but sometimes
        # we differ by a very slight amount :-(
        data = [random.uniform(-100, 1000) for _ in range(1000)]
        self.assertApproxEqual(self.func(data), math.fsum(data), rel=2e-16) 
Example 28
Project: qiskit-aqua   Author: Qiskit   File: docplex.py    License: Apache License 2.0 5 votes vote down vote up
def _auto_define_penalty(mdl: Model, default_penalty: float = 1e5) -> float:
    """Automatically define the penalty coefficient.

    This returns object function's (upper bound - lower bound + 1).

    Args:
        mdl: A model of DOcplex for a optimization problem.
        default_penalty: The default value of the penalty coefficient for the constraints.

    Returns:
        The penalty coefficient for the Hamiltonian.
    """

    # if a constraint has float coefficient, return 1e5 for the penalty coefficient.
    terms = []
    for constraint in mdl.iter_constraints():
        terms.append(constraint.cplex_num_rhs())
        terms.extend(term[1] for term in constraint.iter_net_linear_coefs())
    if any(isinstance(term, float) and not term.is_integer() for term in terms):
        logger.warning('Using %f for the penalty coefficient because a float coefficient exists '
                       'in constraints. \nThe value could be too small. '
                       'If so, set the penalty coefficient manually.', default_penalty)
        return default_penalty

    # (upper bound - lower bound) can be calculate as the sum of absolute value of coefficients
    # Firstly, add 1 to guarantee that infeasible answers will be greater than upper bound.
    penalties = [1]
    # add linear terms of the object function.
    penalties.extend(abs(i[1]) for i in mdl.get_objective_expr().iter_terms())
    # add quadratic terms of the object function.
    penalties.extend(abs(i[1]) for i in mdl.get_objective_expr().iter_quads())

    return fsum(penalties) 
Example 29
Project: qiskit-aqua   Author: Qiskit   File: quadratic_program.py    License: Apache License 2.0 5 votes vote down vote up
def _objective(self) -> bool:
        obj = self._src.objective
        const1, lin1 = self._linear_expression(obj.linear)
        const2, lin2, quadratic = self._quadratic_expression(obj.quadratic)

        constant = fsum([obj.constant] + const1 + const2)
        linear = lin1.coefficients + lin2.coefficients
        if obj.sense == obj.sense.MINIMIZE:
            self._dst.minimize(constant=constant, linear=linear, quadratic=quadratic.coefficients)
        else:
            self._dst.maximize(constant=constant, linear=linear, quadratic=quadratic.coefficients)
        return True 
Example 30
Project: qiskit-aqua   Author: Qiskit   File: quadratic_program.py    License: Apache License 2.0 5 votes vote down vote up
def _linear_constraints(self) -> bool:
        feasible = True
        for lin_cst in self._src.linear_constraints:
            constant, linear = self._linear_expression(lin_cst.linear)
            rhs = -fsum([-lin_cst.rhs] + constant)
            if linear.coefficients.nnz > 0:
                self._dst.linear_constraint(name=lin_cst.name, linear=linear.coefficients,
                                            sense=lin_cst.sense, rhs=rhs)
            else:
                if not self._feasible(lin_cst.sense, rhs):
                    logger.warning('constraint %s is infeasible due to substitution', lin_cst.name)
                    feasible = False
        return feasible