本文整理汇总了Python中math.isclose函数的典型用法代码示例。如果您正苦于以下问题:Python isclose函数的具体用法?Python isclose怎么用?Python isclose使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了isclose函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_convert_to_square_resolution
def test_convert_to_square_resolution(renderer, spoof_tesseract_cache,
resources, outpdf):
from math import isclose
# Confirm input image is non-square resolution
in_pageinfo = PdfInfo(resources / 'aspect.pdf')
assert in_pageinfo[0].xres != in_pageinfo[0].yres
# --force-ocr requires means forced conversion to square resolution
check_ocrmypdf(
resources / 'aspect.pdf', outpdf,
'--force-ocr',
'--pdf-renderer', renderer, env=spoof_tesseract_cache)
out_pageinfo = PdfInfo(outpdf)
in_p0, out_p0 = in_pageinfo[0], out_pageinfo[0]
# Resolution show now be equal
assert out_p0.xres == out_p0.yres
# Page size should match input page size
assert isclose(in_p0.width_inches,
out_p0.width_inches)
assert isclose(in_p0.height_inches,
out_p0.height_inches)
# Because we rasterized the page to produce a new image, it should occupy
# the entire page
out_im_w = out_p0.images[0]['width'] / out_p0.images[0]['dpi_w']
out_im_h = out_p0.images[0]['height'] / out_p0.images[0]['dpi_h']
assert isclose(out_p0.width_inches, out_im_w)
assert isclose(out_p0.height_inches, out_im_h)
示例2: test_rgbled_pulse_background
def test_rgbled_pulse_background():
r, g, b = (Device.pin_factory.pin(i) for i in (4, 5, 6))
with RGBLED(1, 2, 3) as led:
start = time()
led.pulse(0.2, 0.2, n=2)
assert isclose(time() - start, 0, abs_tol=0.05)
led._blink_thread.join()
assert isclose(time() - start, 0.8, abs_tol=0.05)
expected = [
(0.0, 0),
(0.04, 0.2),
(0.04, 0.4),
(0.04, 0.6),
(0.04, 0.8),
(0.04, 1),
(0.04, 0.8),
(0.04, 0.6),
(0.04, 0.4),
(0.04, 0.2),
(0.04, 0),
(0.04, 0.2),
(0.04, 0.4),
(0.04, 0.6),
(0.04, 0.8),
(0.04, 1),
(0.04, 0.8),
(0.04, 0.6),
(0.04, 0.4),
(0.04, 0.2),
(0.04, 0),
]
r.assert_states_and_times(expected)
g.assert_states_and_times(expected)
b.assert_states_and_times(expected)
示例3: list_to_monolists_concat
def list_to_monolists_concat(lis, key=lambda x: x):
"""
list_to_monolists and concatenates at stationary key.
>>> pairs = [(0, 0), (1, 1),
... (1, 2), (0, 3), (0, 4), (-1, 5),
... (-1, 6), (0, 7),
... (0, 8), (10, 9)]
>>> list_to_monolists(pairs, key=lambda x: x[0])
... # doctest: +NORMALIZE_WHITESPACE
([[(0, 0), (1, 1)],
[(1, 2), (0, 3)],
[(0, 4), (-1, 5)],
[(-1, 6), (0, 7)],
[(0, 8), (10, 9)]],
[1, -1, -1, 1, 10])
>>> list_to_monolists_concat(pairs, key=lambda x: x[0])
... # doctest: +NORMALIZE_WHITESPACE
([[(0, 0), (1, 1)],
[(1, 2), (0, 3), (-1, 5)],
[(-1, 6), (0, 7)],
[(0, 8), (10, 9)]],
[1, -1, 1, 10])
"""
lists, diffs = list_to_monolists(lis, key)
for i in range(len(diffs) - 2, -1, -1): # Second from last --> 0
key1 = key(lists[i][-1])
key2 = key(lists[i + 1][0])
if math.isclose(diffs[i], diffs[i + 1]) and math.isclose(key1, key2):
del diffs[i + 1]
del lists[i + 1][0]
lists[i] += lists[i + 1]
del lists[i + 1]
return lists, diffs
示例4: request
def request(self, layer, crs, style, dotiming=False, checkimg=False,
saveimg=False, profiler=None):
"""Requests WMS image from server and returns image"""
env = self.base_env.copy()
query = self.base_query_map.copy()
bounds = list(self.wms[layer].boundingBoxWGS84)
if crs != 'EPSG:4326':
delta = 1.0 # We move 1 degrees away from the poles
if math.isclose(bounds[1], -90.0):
bounds[1] += delta
if math.isclose(bounds[3], 90.0):
bounds[3] -= delta
bbox = wms_utils.get_bounding_box(bounds, crs)
if bbox != '':
query['BBOX'] = bbox
query['CRS'] = crs
t = self.wms[layer].timepositions
if t is not None:
t = [tv.strip() for tv in t]
query['TIME'] = t[int(len(t)/2)]
elevations = self.wms[layer].elevations
if elevations is not None:
elevations = [ev.strip() for ev in elevations]
query['ELEVATION'] = elevations[int(len(elevations)/2)]
query['LAYERS'] = layer
query['STYLES'] = style
t = None
if dotiming:
t1 = time.clock()
if profiler is not None:
profiler.enable()
response = self.get(params=query,
extra_environ=self.base_env, status=200)
result = response.body[:]
if profiler is not None:
profiler.disable()
if dotiming:
t2 = time.clock()
t = (t2-t1)*1000
if saveimg:
with open('tmp/png_%s_%s.png' % (layer, crs), 'wb') as f:
f.write(result)
if checkimg:
is_blank = wms_utils.check_blank(result)
if is_blank:
# Construct URL for easy testing in browser
url = self.path_info + '?' + urllib.parse.urlencode(query)
msg = "Error: Blank image returned for layer=%s; crs=%s" % (layer, crs)
msg += "\nQuery: " + url
raise SystemExit(msg)
"""
else:
print('Image data seems OK')
"""
return result, t
示例5: test_output_pwm_fade_background
def test_output_pwm_fade_background():
pin = Device.pin_factory.pin(4)
with PWMOutputDevice(4) as device:
start = time()
device.blink(0, 0, 0.2, 0.2, n=2)
assert isclose(time() - start, 0, abs_tol=0.05)
device._blink_thread.join()
assert isclose(time() - start, 0.8, abs_tol=0.05)
pin.assert_states_and_times([
(0.0, 0),
(0.04, 0.2),
(0.04, 0.4),
(0.04, 0.6),
(0.04, 0.8),
(0.04, 1),
(0.04, 0.8),
(0.04, 0.6),
(0.04, 0.4),
(0.04, 0.2),
(0.04, 0),
(0.04, 0.2),
(0.04, 0.4),
(0.04, 0.6),
(0.04, 0.8),
(0.04, 1),
(0.04, 0.8),
(0.04, 0.6),
(0.04, 0.4),
(0.04, 0.2),
(0.04, 0),
])
示例6: test_single_page_image
def test_single_page_image(outdir):
filename = outdir / 'image-mono.pdf'
im_tmp = outdir / 'tmp.png'
im = Image.new('1', (8, 8), 0)
for n in range(8):
im.putpixel((n, n), 1)
im.save(str(im_tmp), format='PNG')
imgsize = ((img2pdf.ImgSize.dpi, 8), (img2pdf.ImgSize.dpi, 8))
layout_fun = img2pdf.get_layout_fun(None, imgsize, None, None, None)
im_bytes = im_tmp.read_bytes()
pdf_bytes = img2pdf.convert(
im_bytes, producer="img2pdf", with_pdfrw=False,
layout_fun=layout_fun)
filename.write_bytes(pdf_bytes)
info = pdfinfo.PdfInfo(filename)
assert len(info) == 1
page = info[0]
assert not page.has_text
assert len(page.images) == 1
pdfimage = page.images[0]
assert pdfimage.width == 8
assert pdfimage.color == Colorspace.gray
# DPI in a 1"x1" is the image width
assert isclose(pdfimage.xres, 8)
assert isclose(pdfimage.yres, 8)
示例7: set_fp_gpio_voltage
def set_fp_gpio_voltage(self, value):
""" Set Front Panel GPIO voltage (in volts)
3V3 2V5 | Voltage
-----------------
0 0 | 1.8 V
0 1 | 2.5 V
1 0 | 3.3 V
Arguments:
value : 3.3
"""
assert any([math.isclose(value, nn, abs_tol=0.1) for nn in (3.3,)]),\
"FP GPIO currently only supports 3.3V"
if math.isclose(value, 1.8, abs_tol=0.1):
voltage_reg = 0
elif math.isclose(value, 2.5, abs_tol=0.1):
voltage_reg = 1
elif math.isclose(value, 3.3, abs_tol=0.1):
voltage_reg = 2
mask = 0xFFFFFFFF ^ ((0b1 << self.MB_GPIO_CTRL_EN_3V3) | \
(0b1 << self.MB_GPIO_CTRL_EN_2V5))
with self.regs:
reg_val = self.peek32(self.MB_GPIO_CTRL) & mask
reg_val = reg_val | (voltage_reg << self.MB_GPIO_CTRL_EN_2V5)
self.log.trace("Writing MB_GPIO_CTRL to 0x{:08X}".format(reg_val))
return self.poke32(self.MB_GPIO_CTRL, reg_val)
示例8: test_query
def test_query(self):
l1, u1 = queryweightedmodel(self.q_access_alice_f1, self.ws, self.As,
self.IC, wf=self.wf)
l2, u2 = queryweightedmodel(self.q_access_alice_f2, self.ws, self.As,
self.IC, wf=self.wf)
l3, u3 = queryweightedmodel(self.q_access_bob_f1, self.ws, self.As,
self.IC, wf=self.wf)
l4, u4 = queryweightedmodel(self.q_access_bob_f2, self.ws, self.As,
self.IC, wf=self.wf)
l5, u5 = queryweightedmodel(self.q_blacklisted_alice, self.ws, self.As,
self.IC, wf=self.wf)
l6, u6 = queryweightedmodel(self.q_blacklisted_bob, self.ws, self.As,
self.IC, wf=self.wf)
self.assertTrue(math.isclose(l1, 0.44, abs_tol=1e-2))
self.assertTrue(math.isclose(u1, 0.44, abs_tol=1e-2))
self.assertTrue(math.isclose(l2, 0.6, abs_tol=1e-1))
self.assertTrue(math.isclose(u2, 0.6, abs_tol=1e-1))
# too much deviation: 0.14 to 0.04
# self.assertTrue(math.isclose(l3, 0.14, abs_tol=1e-2))
# self.assertTrue(math.isclose(u3, 0.14, abs_tol=1e-2))
self.assertTrue(math.isclose(l4, 0.4, abs_tol=1e-1))
self.assertTrue(math.isclose(u4, 0.4, abs_tol=1e-1))
self.assertTrue(math.isclose(l5, 0.005, abs_tol=5e-3))
self.assertTrue(math.isclose(u5, 0.005, abs_tol=5e-3))
self.assertTrue(math.isclose(l6, 0.017, abs_tol=1e-2))
self.assertTrue(math.isclose(u6, 0.017, abs_tol=1e-2))
示例9: plot_reference_data
def plot_reference_data(ax, atomic_number, ion_stage, estimators_celltimestep, dfpopthision, args, annotatelines):
nne, Te, TR, W = [estimators_celltimestep[s] for s in ['nne', 'Te', 'TR', 'W']]
# comparison to Chianti file
elsym = at.elsymbols[atomic_number]
elsymlower = elsym.lower()
if Path('data', f'{elsymlower}_{ion_stage}-levelmap.txt').exists():
# ax.set_ylim(bottom=2e-3)
# ax.set_ylim(top=4)
levelmapfile = Path('data', f'{elsymlower}_{ion_stage}-levelmap.txt').open('r')
levelnumofconfigterm = {}
for line in levelmapfile:
row = line.split()
levelnumofconfigterm[(row[0], row[1])] = int(row[2]) - 1
# ax.set_ylim(bottom=5e-4)
for depfilepath in sorted(Path('data').rglob(f'chianti_{elsym}_{ion_stage}_*.txt')):
with depfilepath.open('r') as depfile:
firstline = depfile.readline()
file_nne = float(firstline[firstline.find('ne = ') + 5:].split(',')[0])
file_Te = float(firstline[firstline.find('Te = ') + 5:].split(',')[0])
file_TR = float(firstline[firstline.find('TR = ') + 5:].split(',')[0])
file_W = float(firstline[firstline.find('W = ') + 5:].split(',')[0])
# print(depfilepath, file_nne, nne, file_Te, Te, file_TR, TR, file_W, W)
if (math.isclose(file_nne, nne, rel_tol=0.01) and
math.isclose(file_Te, Te, abs_tol=10)):
if file_W > 0:
continue
bbstr = ' with dilute blackbody'
color = 'C2'
marker = '+'
else:
bbstr = ''
color = 'C1'
marker = '^'
print(f'Plotting reference data from {depfilepath},')
print(f'nne = {file_nne} (ARTIS {nne}) cm^-3, Te = {file_Te} (ARTIS {Te}) K, '
f'TR = {file_TR} (ARTIS {TR}) K, W = {file_W} (ARTIS {W})')
levelnums = []
depcoeffs = []
firstdep = -1
for line in depfile:
row = line.split()
try:
levelnum = levelnumofconfigterm[(row[1], row[2])]
if levelnum in dfpopthision['level'].values:
levelnums.append(levelnum)
if firstdep < 0:
firstdep = float(row[0])
depcoeffs.append(float(row[0]) / firstdep)
except (KeyError, IndexError, ValueError):
pass
ionstr = at.get_ionstring(atomic_number, ion_stage, spectral=False)
ax.plot(levelnums, depcoeffs, linewidth=1.5, color=color,
label=f'{ionstr} CHIANTI NLTE{bbstr}', linestyle='None', marker=marker, zorder=-1)
if annotatelines and atomic_number == 28 and ion_stage == 2:
annotate_emission_line(ax=ax, y=0.04, upperlevel=6, lowerlevel=0, label=r'$\lambda$7378')
annotate_emission_line(ax=ax, y=0.15, upperlevel=6, lowerlevel=2, label=r'1.939 $\mu$m')
annotate_emission_line(ax=ax, y=0.26, upperlevel=7, lowerlevel=1, label=r'$\lambda$7412')
示例10: test_jpg
def test_jpg(self, directory, file_name, tolerance):
source_file_path = os.path.join(BASE, 'files', file_name)
output_file_path = os.path.join(directory, 'test.{}'.format(settings.EXPORT_TYPE))
format = '{}.{}'.format(settings.EXPORT_MAXIMUM_SIZE, settings.EXPORT_TYPE)
exporter = ImageExporter(source_file_path=source_file_path, ext='.jpg',
output_file_path=output_file_path, format=format,
metadata={})
assert not os.path.exists(output_file_path)
exporter.export()
assert os.path.exists(output_file_path)
output_image = Image.open(output_file_path)
source_image = Image.open(source_file_path)
source_pixels = list(source_image.getdata())
output_pixels = list(output_image.getdata())
assert source_image.size == output_image.size
assert output_image.mode == 'RGB'
assert output_image.palette == source_image.palette
assert output_image.format.lower() == settings.EXPORT_TYPE
for i in range(100):
# PIL conversions change some pixels, but first 100 are the same on this one
assert isclose(source_pixels[i][0], output_pixels[i][0], abs_tol=tolerance)
assert isclose(source_pixels[i][1], output_pixels[i][1], abs_tol=tolerance)
assert isclose(source_pixels[i][2], output_pixels[i][2], abs_tol=tolerance)
示例11: calc_coverage_threshold
def calc_coverage_threshold(cov_dict):
'''
calculate minimum coverage threshold for each key in cov_dict.
see end of 'alternative parameterization' section of Negative binomial page
and scipy negative binomial documentation for details of calculation.
'''
threshold_dict = {}
for g in cov_dict:
mean = float(cov_dict[g]['mean'])
var = float(cov_dict[g]['variance'])
q = (var-mean)/var
n = mean**2/(var-mean)
p = 1 - q
## assert that I did the math correctly.
assert(isclose(nbinom.mean(n,p), mean))
assert(isclose(nbinom.var(n,p), var))
## find the integer threshold that includes ~95% of REL606 distribution,
## excluding 5% on the left hand side.
my_threshold = nbinom.ppf(0.05,n,p)
my_threshold_p = nbinom.cdf(my_threshold,n,p)
threshold_dict[g] = {'threshold':str(my_threshold),
'threshold_p':str(my_threshold_p)}
return threshold_dict
示例12: get_hkl_indices_from_streamfile
def get_hkl_indices_from_streamfile(self, crystal_index, peak_x, peak_y):
"""
This method returns the hkl indices of the predicted bragg peaks of
the crystal with the given index at the position (peak_x, peak_y)
Args:
crystal_index (int): Index of the crystal from which the unit cell
is returned.
peak_x (float): The x coordinate of the peak position
peak_y (float): The y coordinate of the peak position
Returns:
list: The hkl indices
"""
try:
crystal = self.crystals[crystal_index]
self.stream_file.seek(crystal.begin_predicted_peaks_pointer)
while(self.stream_file.tell() !=
crystal.end_predicted_peaks_pointer):
line = self.stream_file.readline()
matches = re.findall(self._float_matching_regex, line)
if(math.isclose(peak_x, float(matches[7]))
and math.isclose(peak_y, float(matches[8]))):
return [int(matches[0]), int(matches[1]), int(matches[2])]
except IOError:
print("Cannot read the peak information from streamfile: ",
self.filename)
return []
示例13: shear_force
def shear_force(self, factor=None, figsize=None, verbosity=0, scale=1, offset=(0, 0), show=True, gridplot=False):
self.plot_structure(figsize, 1, scale=scale, offset=offset, gridplot=gridplot)
if factor is None:
max_force = max(map(lambda el: np.max(np.abs(el.shear_force)), self.system.element_map.values()))
factor = det_scaling_factor(max_force, self.max_val_structure)
for el in self.system.element_map.values():
if math.isclose(el.node_1.Ty, 0, rel_tol=1e-5, abs_tol=1e-9) and \
math.isclose(el.node_2.Ty, 0, rel_tol=1e-5, abs_tol=1e-9) and el.q_load is None:
# If True there is no bending moment and no shear, thus no shear force, so no need for plotting.
continue
axis_values = plot_values_shear_force(el, factor)
shear_1 = el.shear_force[0]
shear_2 = el.shear_force[-1]
if verbosity == 0:
node_results = True
else:
node_results = False
self.plot_result(axis_values, shear_1, shear_2, node_results=node_results)
if show:
self.plot()
else:
return self.fig
示例14: test_dynamic_trapz
def test_dynamic_trapz():
same_grid = dynamic_trapz(a_curve, 1, 6, 100)
assert isclose(7.4512822710374, same_grid)
big_grids = dynamic_trapz(a_curve, 1, 6, 5)
assert isclose(big_grids, 7.2642983586919)
small_grids = dynamic_trapz(a_curve, 1, 6, 500)
assert isclose(small_grids, 7.4533539021642)
示例15: test_model_load_mem_leak
def test_model_load_mem_leak():
"testing memory leak on load"
pytest.xfail("memory leak in learn.load()")
path = untar_data(URLs.MNIST_TINY)
data = ImageDataBunch.from_folder(path, ds_tfms=([], []), bs=2)
learn = cnn_learner(data, models.resnet18, metrics=accuracy)
this_tests(learn.load)
gpu_mem_reclaim() # baseline
used_before = gpu_mem_get_used()
name = 'mnist-tiny-test-load-mem-leak'
model_path = learn.save(name, return_path=True)
_ = learn.load(name)
if os.path.exists(model_path): os.remove(model_path)
used_after = gpu_mem_get_used()
# models.resnet18 loaded in GPU RAM is about 50MB
# calling learn.load() of a saved and then instantly re-loaded model shouldn't require more GPU RAM
# XXX: currently w/o running gc.collect() this temporarily leaks memory and causes fragmentation - the fragmentation can't be tested from here, but it'll get automatically fixed once load is fixed. load() must unload first the previous model, gc.collect() and only then load the new one onto cuda.
assert isclose(used_before, used_after, abs_tol=6), f"load() and used GPU RAM: before load(): {used_before}, after: {used_after}"
# this shows how it should have been
gc.collect()
gpu_cache_clear()
used_after_reclaimed = gpu_mem_get_used()
# XXX: not sure where 6MB get lost still but for now it's a small leak - need to test with a bigger model
assert isclose(used_before, used_after_reclaimed, abs_tol=6),f"load() and used GPU RAM: before load(): {used_before}, after: {used_after}, after gc.collect() {used_after_reclaimed} used"