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 Project: ironpython2 Author: IronLanguages File: test_math.py License: Apache License 2.0 | 7 votes |
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 #2
Source Project: svviz Author: svviz File: track.py License: MIT License | 6 votes |
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 #3
Source Project: dynamic-training-with-apache-mxnet-on-aws Author: awslabs File: super_resolution.py License: Apache License 2.0 | 6 votes |
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 #4
Source Project: audio Author: pytorch File: transforms.py License: BSD 2-Clause "Simplified" License | 6 votes |
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 #5
Source Project: audio Author: pytorch File: transforms.py License: BSD 2-Clause "Simplified" License | 6 votes |
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 #6
Source Project: audio Author: pytorch File: transforms.py License: BSD 2-Clause "Simplified" License | 6 votes |
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 #7
Source Project: oxidizr Author: pixlie File: models.py License: GNU General Public License v2.0 | 6 votes |
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 #8
Source Project: python-control Author: python-control File: config_test.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #9
Source Project: python-control Author: python-control File: controls.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #10
Source Project: OpenBench Author: AndyGrant File: stats.py License: GNU General Public License v3.0 | 6 votes |
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 #11
Source Project: mathematics_dataset Author: deepmind File: arithmetic.py License: Apache License 2.0 | 6 votes |
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 #12
Source Project: mathematics_dataset Author: deepmind File: numbers.py License: Apache License 2.0 | 6 votes |
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 #13
Source Project: KAIR Author: cszn File: utils_image.py License: MIT License | 6 votes |
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 #14
Source Project: OISR-PyTorch Author: HolmesShuan File: utility.py License: BSD 2-Clause "Simplified" License | 6 votes |
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 #15
Source Project: OISR-PyTorch Author: HolmesShuan File: utility.py License: BSD 2-Clause "Simplified" License | 6 votes |
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 Project: OISR-PyTorch Author: HolmesShuan File: utility.py License: BSD 2-Clause "Simplified" License | 6 votes |
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 Project: OISR-PyTorch Author: HolmesShuan File: utility.py License: BSD 2-Clause "Simplified" License | 6 votes |
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 Project: OISR-PyTorch Author: HolmesShuan File: utility.py License: BSD 2-Clause "Simplified" License | 6 votes |
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 Project: kano-toolset Author: KanoComputing File: audio.py License: GNU General Public License v2.0 | 6 votes |
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 #20
Source Project: rattlesnake Author: loehnertz File: rattlesnake.py License: MIT License | 6 votes |
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 #21
Source Project: ironpython2 Author: IronLanguages File: test_long.py License: Apache License 2.0 | 6 votes |
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 #22
Source Project: ironpython2 Author: IronLanguages File: python26.py License: Apache License 2.0 | 6 votes |
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 #23
Source Project: AboveTustin Author: kevinabrandon File: flightdata.py License: MIT License | 5 votes |
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 #24
Source Project: CAMISIM Author: CAMI-challenge File: mothurcluster.py License: Apache License 2.0 | 5 votes |
def __init__( self, precision, otu_separator="\t", element_separator=",", iid_gid_mapping=None, logfile=None, verbose=False, debug=False): """ Constructor @param precision: Cluster are made in steps: 10: 0.1, 100: 0.01, 1000: 0.001 @type precision: int | long @param otu_separator: Character separating otu cluster from another @type otu_separator: str | unicode @param element_separator: Character separating elements within otu cluster from another @type element_separator: str | unicode @param iid_gid_mapping: Map of internal ids to genome ids @type iid_gid_mapping: dict[str|unicode, str|unicode] @param logfile: File handler or file path to a log file @type logfile: file | FileIO | StringIO | basestring @param verbose: Not verbose means that only warnings and errors will be past to stream @type verbose: bool @param debug: Display debug messages @type debug: bool """ assert isinstance(precision, int) assert self.validate_number(precision, minimum=0) assert isinstance(otu_separator, basestring) assert isinstance(element_separator, basestring) assert iid_gid_mapping is None or isinstance(iid_gid_mapping, dict) super(MothurCluster, self).__init__(logfile=logfile, verbose=verbose, debug=debug) self._precision = int(math.log10(precision)) self._cluster_separator = otu_separator self._element_separator = element_separator self._cutoff_to_cluster = {} self._gid_to_cluster_index_list = {} self._unique_threshold = "unique" self._iid_gid = {} if iid_gid_mapping is not None: self._iid_gid = iid_gid_mapping
Example #25
Source Project: SecPi Author: SecPi File: alarmdata.py License: GNU General Public License v3.0 | 5 votes |
def human_size(self, nbytes): rank = int((math.log10(nbytes)) / 3) rank = min(rank, len(self.suffixes) - 1) human = nbytes / (1024.0 ** rank) f = ('%.2f' % human).rstrip('0').rstrip('.') return '%s %s' % (f, self.suffixes[rank])
Example #26
Source Project: audio Author: pytorch File: transforms.py License: BSD 2-Clause "Simplified" License | 5 votes |
def __init__(self, stype: str = 'power', top_db: Optional[float] = None) -> None: super(AmplitudeToDB, self).__init__() self.stype = stype if top_db is not None and top_db < 0: raise ValueError('top_db must be positive value') self.top_db = top_db self.multiplier = 10.0 if stype == 'power' else 20.0 self.amin = 1e-10 self.ref_value = 1.0 self.db_multiplier = math.log10(max(self.amin, self.ref_value))
Example #27
Source Project: audio Author: pytorch File: functional.py License: BSD 2-Clause "Simplified" License | 5 votes |
def amplitude_to_DB( x: Tensor, multiplier: float, amin: float, db_multiplier: float, top_db: Optional[float] = None ) -> Tensor: r"""Turn a tensor from the power/amplitude scale to the decibel scale. This output depends on the maximum value in the input tensor, and so may return different values for an audio clip split into snippets vs. a a full clip. Args: x (Tensor): Input tensor before being converted to decibel scale multiplier (float): Use 10. for power and 20. for amplitude amin (float): Number to clamp ``x`` db_multiplier (float): Log10(max(reference value and amin)) top_db (float or None, optional): Minimum negative cut-off in decibels. A reasonable number is 80. (Default: ``None``) Returns: Tensor: Output tensor in decibel scale """ x_db = multiplier * torch.log10(torch.clamp(x, min=amin)) x_db -= multiplier * db_multiplier if top_db is not None: x_db = x_db.clamp(min=x_db.max().item() - top_db) return x_db
Example #28
Source Project: audio Author: pytorch File: functional_cpu_test.py License: BSD 2-Clause "Simplified" License | 5 votes |
def test_DB_to_amplitude(self): # Make some noise x = torch.rand(1000) spectrogram = torchaudio.transforms.Spectrogram() spec = spectrogram(x) amin = 1e-10 ref = 1.0 db_multiplier = math.log10(max(amin, ref)) # Waveform amplitude -> DB -> amplitude multiplier = 20. power = 0.5 db = F.amplitude_to_DB(torch.abs(x), multiplier, amin, db_multiplier, top_db=None) x2 = F.DB_to_amplitude(db, ref, power) torch.testing.assert_allclose(x2, torch.abs(x), atol=5e-5, rtol=1e-5) # Spectrogram amplitude -> DB -> amplitude db = F.amplitude_to_DB(spec, multiplier, amin, db_multiplier, top_db=None) x2 = F.DB_to_amplitude(db, ref, power) torch.testing.assert_allclose(x2, spec, atol=5e-5, rtol=1e-5) # Waveform power -> DB -> power multiplier = 10. power = 1. db = F.amplitude_to_DB(x, multiplier, amin, db_multiplier, top_db=None) x2 = F.DB_to_amplitude(db, ref, power) torch.testing.assert_allclose(x2, torch.abs(x), atol=5e-5, rtol=1e-5) # Spectrogram power -> DB -> power db = F.amplitude_to_DB(spec, multiplier, amin, db_multiplier, top_db=None) x2 = F.DB_to_amplitude(db, ref, power) torch.testing.assert_allclose(x2, spec, atol=5e-5, rtol=1e-5)
Example #29
Source Project: razzy-spinner Author: rafasashi File: plot.py License: GNU General Public License v3.0 | 5 votes |
def config_axes(self, xlog, ylog): if hasattr(self, '_rng'): (i1, j1, i2, j2) = self.visible_area() zoomed=1 else: zoomed=0 self._xlog = xlog self._ylog = ylog if xlog: self._rng = [log10(x) for x in self._original_rng] else: self._rng = self._original_rng if ylog: self._vals = [log10(x) for x in self._original_vals] else: self._vals = self._original_vals self._imin = min(self._rng) self._imax = max(self._rng) if self._imax == self._imin: self._imin -= 1 self._imax += 1 self._jmin = min(self._vals) self._jmax = max(self._vals) if self._jmax == self._jmin: self._jmin -= 1 self._jmax += 1 if zoomed: self.zoom(i1, j1, i2, j2) else: self.zoom(self._imin, self._jmin, self._imax, self._jmax)
Example #30
Source Project: PlayStoreLinks_Bot Author: crisbal File: utils.py License: MIT License | 5 votes |
def human_readable_download_number(download_number_string): download_number_string = download_number_string.split("-")[0].replace(',','').replace('+','').strip() n = float(download_number_string) millidx = max(0,min(len(millnames)-1, int(math.floor(0 if n == 0 else math.log10(abs(n))/3)))) return '{:.0f}{}'.format(n / 10**(3 * millidx), millnames[millidx])