Python math.log10() Examples

The following are 30 code examples of math.log10(). 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 also want to check out all available functions/classes of the module math , or try the search function .
Example #1
Source File: transforms.py    From audio with BSD 2-Clause "Simplified" License 7 votes vote down vote up
def forward(self, waveform: Tensor) -> Tensor:
        r"""
        Args:
            waveform (Tensor): Tensor of audio of dimension (..., time).

        Returns:
            Tensor: Tensor of audio of dimension (..., time).
        """
        if self.gain_type == "amplitude":
            waveform = waveform * self.gain

        if self.gain_type == "db":
            waveform = F.gain(waveform, self.gain)

        if self.gain_type == "power":
            waveform = F.gain(waveform, 10 * math.log10(self.gain))

        return torch.clamp(waveform, -1, 1) 
Example #2
Source File: test_math.py    From ironpython2 with Apache License 2.0 7 votes vote down vote up
def test_math_subclass(self):
        """verify subtypes of float/long work w/ math functions"""
        import math
        class myfloat(float): pass
        class mylong(long): pass

        mf = myfloat(1)
        ml = mylong(1)

        for x in math.log, math.log10, math.log1p, math.asinh, math.acosh, math.atanh, math.factorial, math.trunc, math.isinf:
            try:
                resf = x(mf)
            except ValueError:
                resf = None
            try:
                resl = x(ml)
            except ValueError:
                resl = None
            self.assertEqual(resf, resl) 
Example #3
Source File: utils_image.py    From KAIR with MIT License 6 votes vote down vote up
def calculate_psnr(img1, img2, border=0):
    # img1 and img2 have range [0, 255]
    #img1 = img1.squeeze()
    #img2 = img2.squeeze()
    if not img1.shape == img2.shape:
        raise ValueError('Input images must have the same dimensions.')
    h, w = img1.shape[:2]
    img1 = img1[border:h-border, border:w-border]
    img2 = img2[border:h-border, border:w-border]

    img1 = img1.astype(np.float64)
    img2 = img2.astype(np.float64)
    mse = np.mean((img1 - img2)**2)
    if mse == 0:
        return float('inf')
    return 20 * math.log10(255.0 / math.sqrt(mse))


# --------------------------------------------
# SSIM
# -------------------------------------------- 
Example #4
Source File: python26.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_log():
    import math
    
    zeros = [-1, -1.0, -1L, 0, 0.0, 0L]
    nonzeros = [2, 2.0, 2L]
    ones = [1, 1.0, 1L]
    
    AreNotEqual(type(zeros[0]), type(zeros[2]))
    
    for z0 in zeros:
        AssertError(ValueError, math.log, z0)
        AssertError(ValueError, math.log10, z0)
        for z in zeros:
            AssertError(ValueError, math.log, z0, z)
        for n in nonzeros + ones:
            AssertError(ValueError, math.log, z0, n)
            AssertError(ValueError, math.log, n, z0)
    
    for one in ones:
        for n in nonzeros:
            AssertError(ZeroDivisionError, math.log, n, one) 
Example #5
Source File: transforms.py    From audio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _fade_in(self, waveform_length: int) -> Tensor:
        fade = torch.linspace(0, 1, self.fade_in_len)
        ones = torch.ones(waveform_length - self.fade_in_len)

        if self.fade_shape == "linear":
            fade = fade

        if self.fade_shape == "exponential":
            fade = torch.pow(2, (fade - 1)) * fade

        if self.fade_shape == "logarithmic":
            fade = torch.log10(.1 + fade) + 1

        if self.fade_shape == "quarter_sine":
            fade = torch.sin(fade * math.pi / 2)

        if self.fade_shape == "half_sine":
            fade = torch.sin(fade * math.pi - math.pi / 2) / 2 + 0.5

        return torch.cat((fade, ones)).clamp_(0, 1) 
Example #6
Source File: super_resolution.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def test(ctx):
    val_data.reset()
    avg_psnr = 0
    batches = 0
    for batch in val_data:
        batches += 1
        data = gluon.utils.split_and_load(batch.data[0], ctx_list=ctx, batch_axis=0)
        label = gluon.utils.split_and_load(batch.label[0], ctx_list=ctx, batch_axis=0)
        outputs = []
        for x in data:
            outputs.append(net(x))
        metric.update(label, outputs)
        avg_psnr += 10 * math.log10(1/metric.get()[1])
        metric.reset()
    avg_psnr /= batches
    print('validation avg psnr: %f'%avg_psnr) 
Example #7
Source File: transforms.py    From audio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _fade_out(self, waveform_length: int) -> Tensor:
        fade = torch.linspace(0, 1, self.fade_out_len)
        ones = torch.ones(waveform_length - self.fade_out_len)

        if self.fade_shape == "linear":
            fade = - fade + 1

        if self.fade_shape == "exponential":
            fade = torch.pow(2, - fade) * (1 - fade)

        if self.fade_shape == "logarithmic":
            fade = torch.log10(1.1 - fade) + 1

        if self.fade_shape == "quarter_sine":
            fade = torch.sin(fade * math.pi / 2 + math.pi / 2)

        if self.fade_shape == "half_sine":
            fade = torch.sin(fade * math.pi + math.pi / 2) / 2 + 0.5

        return torch.cat((ones, fade)).clamp_(0, 1) 
Example #8
Source File: test_long.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_logs(self):
        LOG10E = math.log10(math.e)

        for exp in range(10) + [100, 1000, 10000]:
            value = 10 ** exp
            log10 = math.log10(value)
            self.assertAlmostEqual(log10, exp)

            # log10(value) == exp, so log(value) == log10(value)/log10(e) ==
            # exp/LOG10E
            expected = exp / LOG10E
            log = math.log(value)
            self.assertAlmostEqual(log, expected)

        for bad in -(1L << 10000), -2L, 0L:
            self.assertRaises(ValueError, math.log, bad)
            self.assertRaises(ValueError, math.log10, bad) 
Example #9
Source File: models.py    From oxidizr with GNU General Public License v2.0 6 votes vote down vote up
def get_weight(follower_count=1, following_count=1, status_count=1, listed_in_count=1, is_verified=False):
    """
    (Follower_count / Following_count) + status_count + listed_in_count
    """
    if not follower_count and not following_count and not status_count:
        return 0
    if not follower_count:
        follower_count = 1
    if not following_count:
        following_count = 1
    if not status_count:
        status_count = 1
    if not listed_in_count:
        listed_in_count = 1
    return int((follower_count / following_count) *
               math.log10(follower_count) +
               2 * listed_in_count) + 50 * bool(is_verified) 
Example #10
Source File: config_test.py    From python-control with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_custom_bode_default(self):
        ct.config.defaults['bode.dB'] = True
        ct.config.defaults['bode.deg'] = True
        ct.config.defaults['bode.Hz'] = True

        # Generate a Bode plot
        plt.figure()
        omega = np.logspace(-3, 3, 100)
        ct.bode_plot(self.sys, omega, dB=True)
        mag_x, mag_y = (((plt.gcf().axes[0]).get_lines())[0]).get_data()
        np.testing.assert_almost_equal(mag_y[0], 20*log10(10), decimal=3)

        # Override defaults
        plt.figure()
        ct.bode_plot(self.sys, omega, Hz=True, deg=False, dB=True)
        mag_x, mag_y = (((plt.gcf().axes[0]).get_lines())[0]).get_data()
        phase_x, phase_y = (((plt.gcf().axes[1]).get_lines())[0]).get_data()
        np.testing.assert_almost_equal(mag_x[0], 0.001 / (2*pi), decimal=6)
        np.testing.assert_almost_equal(mag_y[0], 20*log10(10), decimal=3)
        np.testing.assert_almost_equal(phase_y[-1], -pi, decimal=2)

        ct.reset_defaults() 
Example #11
Source File: controls.py    From python-control with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def PlotTimeResp(self, u, t, fig, clear=True, label='model', mysub=111):
        ax = fig.add_subplot(mysub)
        if clear:
            ax.cla()
        try:
            y = self.lsim(u, t)
        except:
            y = self.lsim2(u, t)
        ax.plot(t, y, label=label)
        return ax


##     def BodePlot(self, f, fig, clear=False):
##         mtf = self.FreqResp(
##         ax1 = fig.axes[0]
##         ax1.semilogx(modelf,20*log10(abs(mtf)))
##         mphase = angle(mtf, deg=1)
##         ax2 = fig.axes[1]
##         ax2.semilogx(modelf, mphase) 
Example #12
Source File: stats.py    From OpenBench with GNU General Public License v3.0 6 votes vote down vote up
def ELO(wins, losses, draws):

    def _elo(x):
        if x <= 0 or x >= 1: return 0.0
        return -400*math.log10(1/x-1)

    # win/loss/draw ratio
    N = wins + losses + draws;
    if N == 0: return (0, 0, 0)
    w = float(wins)  / N
    l = float(losses)/ N
    d = float(draws) / N

    # mu is the empirical mean of the variables (Xi), assumed i.i.d.
    mu = w + d/2

    # stdev is the empirical standard deviation of the random variable (X1+...+X_N)/N
    stdev = math.sqrt(w*(1-mu)**2 + l*(0-mu)**2 + d*(0.5-mu)**2) / math.sqrt(N)

    # 95% confidence interval for mu
    mu_min = mu + phi_inv(0.025) * stdev
    mu_max = mu + phi_inv(0.975) * stdev

    return (_elo(mu_min), _elo(mu), _elo(mu_max)) 
Example #13
Source File: audio.py    From kano-toolset with GNU General Public License v2.0 6 votes vote down vote up
def percent_to_millibel(percent, raspberry_mod=False):
    if not raspberry_mod:
        from math import log10

        multiplier = 2.5

        percent *= multiplier
        percent = min(percent, 100. * multiplier)
        percent = max(percent, 0.000001)

        millibel = 1000 * log10(percent / 100.)

    else:
        # special case for mute
        if percent == 0:
            return -11000

        min_allowed = -4000
        max_allowed = 400
        percent = percent / 100.
        millibel = min_allowed + (max_allowed - min_allowed) * percent

    return int(millibel) 
Example #14
Source File: track.py    From svviz with MIT License 6 votes vote down vote up
def getTicks(self, regionID):
        ticks = []
        start = 0
        width = self.scale.partsToLengths[regionID]
        end = start + width

        res = (10 ** round(math.log10(end - start))) / 10.0
        if width / res > 15:
            res *= 2.5
        elif width / res < 5:
            res /= 2.0

        roundStart = start - (start%res)

        for i in range(int(roundStart), end, int(res)):
            ticks.append(i)

        return ticks 
Example #15
Source File: utility.py    From OISR-PyTorch with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def calc_psnr(sr, hr, scale, rgb_range, dataset=None):
    if hr.nelement() == 1: return 0

    diff = (sr - hr) / rgb_range
    if dataset and dataset.dataset.benchmark:
        shave = scale
        # print('Ycbcr PSNR.')
        if diff.size(1) > 1:
            gray_coeffs = [65.738, 129.057, 25.064]
            convert = diff.new_tensor(gray_coeffs).view(1, 3, 1, 1) / 256
            diff = diff.mul(convert).sum(dim=1)
    else:
        shave = scale + 6

    valid = diff[..., shave:-shave, shave:-shave]
    mse = valid.pow(2).mean()

    return -10 * math.log10(mse) 
Example #16
Source File: utility.py    From OISR-PyTorch with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def calc_psnr(sr, hr, scale, rgb_range, dataset=None):
    if hr.nelement() == 1: return 0

    diff = (sr - hr) / rgb_range
    if dataset and dataset.dataset.benchmark:
        shave = scale
        # print('Ycbcr PSNR.')
        if diff.size(1) > 1:
            gray_coeffs = [65.738, 129.057, 25.064]
            convert = diff.new_tensor(gray_coeffs).view(1, 3, 1, 1) / 256
            diff = diff.mul(convert).sum(dim=1)
    else:
        shave = scale + 6

    valid = diff[..., shave:-shave, shave:-shave]
    mse = valid.pow(2).mean()

    return -10 * math.log10(mse) 
Example #17
Source File: utility.py    From OISR-PyTorch with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def calc_psnr(sr, hr, scale, rgb_range, dataset=None):
    if hr.nelement() == 1: return 0

    diff = (sr - hr) / rgb_range
    if dataset and dataset.dataset.benchmark:
        shave = scale
        # print('Ycbcr PSNR.')
        if diff.size(1) > 1:
            gray_coeffs = [65.738, 129.057, 25.064]
            convert = diff.new_tensor(gray_coeffs).view(1, 3, 1, 1) / 256
            diff = diff.mul(convert).sum(dim=1)
    else:
        shave = scale + 6

    valid = diff[..., shave:-shave, shave:-shave]
    mse = valid.pow(2).mean()

    return -10 * math.log10(mse) 
Example #18
Source File: utility.py    From OISR-PyTorch with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def calc_psnr(sr, hr, scale, rgb_range, dataset=None):
    if hr.nelement() == 1: return 0

    diff = (sr - hr) / rgb_range
    if dataset and dataset.dataset.benchmark:
        shave = scale
        # print('Ycbcr PSNR.')
        if diff.size(1) > 1:
            gray_coeffs = [65.738, 129.057, 25.064]
            convert = diff.new_tensor(gray_coeffs).view(1, 3, 1, 1) / 256
            diff = diff.mul(convert).sum(dim=1)
    else:
        shave = scale + 6

    valid = diff[..., shave:-shave, shave:-shave]
    mse = valid.pow(2).mean()

    return -10 * math.log10(mse) 
Example #19
Source File: utility.py    From OISR-PyTorch with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def calc_psnr(sr, hr, scale, rgb_range, dataset=None):
    if hr.nelement() == 1: return 0

    diff = (sr - hr) / rgb_range
    if dataset and dataset.dataset.benchmark:
        shave = scale
        # print('Ycbcr PSNR.')
        if diff.size(1) > 1:
            gray_coeffs = [65.738, 129.057, 25.064]
            convert = diff.new_tensor(gray_coeffs).view(1, 3, 1, 1) / 256
            diff = diff.mul(convert).sum(dim=1)
    else:
        shave = scale + 6

    valid = diff[..., shave:-shave, shave:-shave]
    mse = valid.pow(2).mean()

    return -10 * math.log10(mse) 
Example #20
Source File: numbers.py    From mathematics_dataset with Apache License 2.0 6 votes vote down vote up
def _semi_prime(entropy):
  """Generates a semi-prime with the given entropy."""
  # Add on extra entropy to account for the sparsity of the primes; we don't
  # actually use the integers sampled, but rather a random prime close to them;
  # thus some entropy is lost, which we must account for
  entropy += math.log10(max(1, entropy * math.log(10)))

  # We intentionally uniformy sample the "entropy" (i.e., approx number digits)
  # of the two factors.
  entropy_1, entropy_2 = entropy * np.random.dirichlet([1, 1])

  # Need >= 2 for randprime to always work (Betrand's postulate).
  approx_1 = number.integer(entropy_1, signed=False, min_abs=2)
  approx_2 = number.integer(entropy_2, signed=False, min_abs=2)

  factor_1 = sympy.ntheory.generate.randprime(approx_1 / 2, approx_1 * 2)
  factor_2 = sympy.ntheory.generate.randprime(approx_2 / 2, approx_2 * 2)

  return factor_1 * factor_2 
Example #21
Source File: arithmetic.py    From mathematics_dataset with Apache License 2.0 6 votes vote down vote up
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) 
Example #22
Source File: rattlesnake.py    From rattlesnake with MIT License 6 votes vote down vote up
def calculate_decibel(data):
    """
    Calculates the volume level in decibel of the given data

    :param data: A bytestring used to calculate the decibel level
    :return db: The calculated volume level in decibel
    """

    count = len(data) / 2
    form = "%dh" % count
    shorts = struct.unpack(form, data)
    sum_squares = 0.0
    for sample in shorts:
        n = sample * (1.0 / 32768)
        sum_squares += n * n
    rms = math.sqrt(sum_squares / count) + 0.0001
    db = 20 * math.log10(rms)
    return db 
Example #23
Source File: test_math.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def testLog10(self):
        self.assertRaises(TypeError, math.log10)
        self.ftest('log10(0.1)', math.log10(0.1), -1)
        self.ftest('log10(1)', math.log10(1), 0)
        self.ftest('log10(10)', math.log10(10), 1)
        self.assertEqual(math.log(INF), INF)
        self.assertRaises(ValueError, math.log10, NINF)
        self.assertTrue(math.isnan(math.log10(NAN)))
        # Log values should match for int and long (issue #18739).
        for n in range(1, 1000):
            self.assertEqual(math.log10(n), math.log10(long(n))) 
Example #24
Source File: iSeeBetterTest.py    From iSeeBetter with MIT License 5 votes vote down vote up
def PSNR(pred, gt, shave_border=0):
    height, width = pred.shape[1:3]
    pred = pred[:, 1+shave_border:height - shave_border, 1+shave_border:width - shave_border]
    gt = gt[:, 1+shave_border:height - shave_border, 1+shave_border:width - shave_border]
    imdff = pred - gt
    rmse = math.sqrt(np.mean(imdff ** 2))
    if rmse == 0:
        return 100
    return 20 * math.log10(255.0 / rmse) 
Example #25
Source File: test_math.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_long_log(self):
        """logon big ints should work"""
        self.assertEqual(round(math.log10(10 ** 1000), 5), 1000.0)
        self.assertEqual(round(math.log(10 ** 1000), 5), 2302.58509)

        self.assertEqual(round(math.log10(18446744073709551615), 5),  19.26592)
        self.assertEqual(round(math.log(18446744073709551615), 5), 44.36142)

        self.assertEqual(round(math.log10(18446744073709551616), 5),  19.26592)
        self.assertEqual(round(math.log(18446744073709551616), 5), 44.36142)

        self.assertEqual(round(math.log10(18446744073709551614), 5),  19.26592)
        self.assertEqual(round(math.log(18446744073709551614), 5), 44.36142)

        # log in a new base
        self.assertEqual(round(math.log(2 ** 1000, 2), 5), 1000.0)

        self.assertRaises(ValueError, math.log, long(0))
        self.assertRaises(ValueError, math.log, long(-1))
        self.assertEqual(math.log(long(2), 1e666), 0.0)
        self.assertRaises(ValueError, math.log, long(2), -1e666)
        self.assertRaises(ZeroDivisionError, math.log, long(2), 1.0)

        #Make sure that an object is converted to float before being passed into log funcs
        class N(object):
            def __float__(self):
                return 10.0
            def __long__(self):
                return 100

        self.assertEqual(round(math.log10(N()), 5),1.0)
        self.assertEqual(round(math.log(N()), 5),2.30259) 
Example #26
Source File: numa_allocator.py    From workload-collocation-agent with Apache License 2.0 5 votes vote down vote up
def _get_most_free_memory_nodes(
        memory_limit: MemoryLimit, node_memory_free: Dict[int, int]) -> Set[NumaNodeId]:
    d = {}
    for node in node_memory_free:
        if memory_limit >= node_memory_free[node]:
            # if we can't fit into free memory, don't consider that node at all
            continue
        d[node] = round(math.log10(node_memory_free[node] - memory_limit), 1)
    print(d)
    free_nodes = sorted(d.items(), reverse=True, key=lambda x: x[1])
    best_free_nodes = set()
    if len(free_nodes) > 0:
        z = free_nodes[0][1]
        best_free_nodes = {x[0] for x in free_nodes if x[1] == z}
    return best_free_nodes 
Example #27
Source File: flightdata.py    From AboveTustin with MIT License 5 votes vote down vote up
def _parse_aircraft_data(self, a, time):
        alt = a.get('Alt', 0)
        dist = -1
        az = 0
        el = 0
        if 'Lat' in a and 'Long' in a:
            rec_pos = (receiver_latitude, receiver_longitude)
            ac_pos = (a['Lat'], a['Long'])
            dist = geomath.distance(rec_pos, ac_pos)
            az = geomath.bearing(rec_pos, ac_pos)
            el = math.degrees(math.atan(alt / (dist * 5280)))
        speed = 0
        if 'Spd' in a:
            speed = geomath.knot2mph(a['Spd'])
        if 'PosTime' in a:
            last_seen_time = datetime.fromtimestamp(a['PosTime'] / 1000.0)
            seen = (time - last_seen_time).total_seconds()
        else:
            seen = 0
        ac_data = AirCraftData(
            a.get('Icao', None).upper(),
            a.get('Sqk', None),
            a.get('Call', None),
            a.get('Reg', None),
            a.get('Lat', None),
            a.get('Long', None),
            alt,
            a.get('Vsi', 0),
            a.get('Trak', None),
            speed,
            a.get('CMsgs', None),
            seen,
            a.get('Mlat', False),
            None,  # NUCP
            None,  # Seen pos
            10.0 * math.log10(a.get('Sig', 0) / 255.0 + 1e-5),
            dist,
            az,
            el,
            time)
        return ac_data 
Example #28
Source File: numa_allocator.py    From workload-collocation-agent with Apache License 2.0 5 votes vote down vote up
def _get_best_memory_nodes(
        memory_limit: MemoryLimit, balanced_memory: BalancedMemory) -> Set[NumaNodeId]:
    d = {}
    for node in balanced_memory:
        d[node] = round(math.log10((sum([k[1] for k in balanced_memory[node]]) + memory_limit)), 1)
    best = sorted(d.items(), key=lambda x: x[1])
    z = best[0][1]
    best_nodes = {x[0] for x in best if x[1] == z}
    return best_nodes 
Example #29
Source File: slicing.py    From lidar with MIT License 5 votes vote down vote up
def get_min_max_nodata(image):
    max_elev = np.max(image)
    nodata = pow(10, math.floor(math.log10(np.max(image))) + 2) - 1  # assign no data value
    image[image <= 0] = nodata  # change no data value
    min_elev = np.min(image)
    return min_elev, max_elev, nodata


# set input image parameters for level set method 
Example #30
Source File: badge_service.py    From pepy with MIT License 5 votes vote down vote up
def format(self, downloads: Downloads) -> str:
        if downloads.value == 0:
            return "0"
        digits = int(math.log10(abs(downloads.value)) if downloads else 0)
        millidx = max(0, min(len(self._METRIC_PREFIX) - 1, digits // 3))
        rounded_value = downloads.value // (10 ** (3 * millidx))
        return "{}{}".format(rounded_value, self._METRIC_PREFIX[millidx])