Best Python code snippet using autotest_python
curvelet.py
Source:curvelet.py
1import numpy as np2# -----------------------------------------------------------------------------3# FUNCTION API4# -----------------------------------------------------------------------------5def curvelet_transform(x, num_bands, num_angles = 8, all_curvelets = True, as_complex = False):6 ndims = len(x.shape)7 # This file requires Curvelab and the PyCurveLab packages be installed on your system.8 try:9 import pyct10 except ImportError:11 raise NotImplementedError("Use of curvelets requires installation of CurveLab and the PyCurveLab package.\nSee: http://curvelet.org/ and https://www.slim.eos.ubc.ca/SoftwareLicensed/")12 if ndims == 2:13 ct = pyct.fdct2( n = x.shape,14 nbs = num_bands, # Number of bands15 nba = num_angles, # Number of discrete angles16 ac = all_curvelets,# Return curvelets at the finest detail level17 vec = False, # Return results as nested python vectors18 cpx = as_complex) # Disable complex-valued curvelets19 elif ndims == 3:20 ct = pyct.fdct3( n = x.shape,21 nbs = num_bands, # Number of bands22 nba = num_angles, # Number of discrete angles23 ac = all_curvelets,# Return curvelets at the finest detail level24 vec = False, # Return results as nested python vectors25 cpx = as_complex) # Disable complex-valued curvelets26 else:27 raise NotImplementedError("%dD Curvelets are not supported." % (ndims))28 result = ct.fwd(x)29 del ct30 return result31def inverse_curvelet_transform(coefs, x_shape, num_bands, num_angles, all_curvelets, as_complex):32 # This file requires Curvelab and the PyCurveLab packages be installed on your system.33 try:34 import pyct35 except ImportError:36 raise NotImplementedError("Use of curvelets requires installation of CurveLab and the PyCurveLab package.\nSee: http://curvelet.org/ and https://www.slim.eos.ubc.ca/SoftwareLicensed/")37 if len(x_shape) == 2:38 ct = pyct.fdct2( n = x_shape,39 nbs = num_bands, # Number of bands40 nba = num_angles,41 ac = all_curvelets,42 vec = False,43 cpx = as_complex)44 else:45 ct = pyct.fdct3( n = x_shape,46 nbs = num_bands, # Number of bands47 nba = num_angles,48 ac = all_curvelets,49 vec = False,50 cpx = as_complex)51 result = ct.inv(coefs)52 del ct53 return result54# -----------------------------------------------------------------------------55# OBJECT-ORIENTED API56# -----------------------------------------------------------------------------57class CurveletTransform(object):58 def __init__(self, x_shape, num_bands = None, num_angles = 8, all_curvelets = True, as_complex = False):59 if num_bands == None:60 self._num_bands = int(np.ceil(np.log2(np.min(x_shape)) - 3))61 else:62 self._num_bands = num_bands63 self.x_shape = x_shape64 self.num_angles = num_angles65 self.all_curvelets = all_curvelets66 self.as_complex = as_complex67 self.example_coefs = self.fwd(np.zeros(x_shape))68 # ------------- Forward and inverse transforms ------------------69 def fwd(self, data, num_bands = None):70 '''71 Curvelets must have the num_bands initialized in the72 constructor, but for uniformity with the API for forward73 transforms, we allow the user to supply a num_bands74 argument. If the supplied num_bands does not match the75 num_bands used in the constructor, an error is generated.76 '''77 if num_bands != None:78 assert self._num_bands == num_bands79 # Check argument80 assert data.shape == self.x_shape81 ndims = len(self.x_shape)82 if ndims == 1:83 raise NotImplementedError("1D curvelet transform not yet implemented.")84 elif ndims == 2:85 return curvelet_transform(data, self._num_bands, self.num_angles, self.all_curvelets, self.as_complex)86 elif ndims == 3:87 return curvelet_transform(data, self._num_bands, self.num_angles, self.all_curvelets, self.as_complex)88 else:89 raise NotImplementedError("Curveletes not supported for %dD data." % (len(data.shape)))90 def inv(self, coefs):91 ndims = len(self.x_shape)92 if ndims == 1:93 raise NotImplementedError("1D Inverse curvelet transform not yet implemented.")94 elif ndims == 2:95 return inverse_curvelet_transform(coefs, self.x_shape, self._num_bands, self.num_angles,96 self.all_curvelets, self.as_complex)97 elif ndims == 3:98 return inverse_curvelet_transform(coefs, self.x_shape, self._num_bands, self.num_angles,99 self.all_curvelets, self.as_complex)100 else:101 raise NotImplementedError("Curvelets not supported for %dD data." % (len(data.shape)))102 # --------------------- Utility methods -------------------------103 def num_bands(self, coefs):104 return self._num_bands105 def num_coefficients(self):106 total = 0107 for band in self.example_coefs:108 total += sum([ np.prod(angle.shape) for angle in band ] )109 return total110 def num_nonzero_coefficients(self, coefs):111 total = 0112 for band in coefs:113 total += sum([ angle.nonzero()[0].shape[0] for angle in band ] )114 return total115 def coefs_to_vec(self, coefs):116 return np.hstack([np.hstack([ angle.ravel(order = 'c') for angle in band ]) for band in coefs])117 def vec_to_coefs(self, coef_vec):118 base_idx = 0119 coefs = []120 for band in self.example_coefs:121 angle_list = []122 for angle in band:123 angle_size = np.prod(angle.shape)124 angle_list.append(np.reshape(coef_vec[base_idx:base_idx+angle_size], angle.shape, order = 'c'))125 base_idx += angle_size126 coefs.append(angle_list)127 return coefs128 def update(self, coefs, update, alpha):129 '''130 Adds the update (multiplied by alpha) to each set of131 coefficients.132 '''133 delta_sqrsum = 0.0134 for band in xrange(len(coefs)):135 for angle in xrange(len(coefs[band])):136 delta = alpha * update[band][angle]137 coefs[band][angle] += delta138 delta_sqrsum += np.square(delta).sum()139 update_norm = np.sqrt(delta_sqrsum)140 return (coefs, update_norm)141 def mean(self, coefs):142 '''143 Compute the average over all wavelet coefficients.144 '''145 accum = []146 for coef in coefs:147 accum.append(np.hstack( [ block.ravel() for block in coef ] ))148 return np.hstack(accum).mean()149 # ------------------ Thresholding methods -----------------------150 def _estimate_noise(self):151 '''152 Helper function for the thresholding function below.153 Adapted from the fdct_osfft_demo_denoise.m file in CurveLab.154 '''155 E_coefs = self.fwd(np.random.randn(*self.x_shape))156 E_thresholds = []157 for band in xrange(len(E_coefs)):158 angle_thresholds = []159 for angle in xrange(len(E_coefs[band])):160 A = E_coefs[band][angle]161 angle_thresholds.append( np.median(np.abs(A - np.median(A)))/0.6745 )162 E_thresholds.append(angle_thresholds)163 return E_thresholds164 def threshold_by_band(self, coefs, threshold_func, skip_bands = [], within_axis = None, scaling_factor = None):165 '''166 Threshold each band individually. The threshold_func() should167 take an array of coefficients (which may be 1d or 2d or 3d),168 and return a tuple: (band_center, band_threshold)169 For the sake of speed and memory efficiency, updates to the coefficients170 are performed in-place.171 '''172 # Skip the lowest frequency band173 for b in xrange(1, len(coefs)):174 num_removed = 0175 num_total = 0176 # Skip band?177 if b in skip_bands:178 continue179 # print num_total - num_removed, num_total180 # Compute the center and threshold.181 tmp = np.hstack( [ angle.ravel() for angle in coefs[b] ] )182 (band_center, band_threshold) = threshold_func(tmp, b, None)183 # print '\t\t****', b, band_center, band_threshold184 #if scaling_factor != None:185 # band_threshold /= scaling_factor186 for a in xrange(len(coefs[b])):187 # Soft threshold the coefficients188 idxs = np.where( coefs[b][a] > band_threshold )189 coefs[b][a][idxs] -= band_threshold190 idxs = np.where( np.abs(coefs[b][a]) <= band_threshold )191 coefs[b][a][idxs] = 0.0192 idxs = np.where( coefs[b][a] < -band_threshold )193 coefs[b][a][idxs] += band_threshold194 #idxs = np.where( np.abs( coefs[b][a] - band_center ) < band_threshold )# * scaling_factor[b][a] / max_scale )195 #num_removed += idxs[0].shape[0]196 #num_total += np.prod(coefs[b][a].shape)197 #coefs[b][a][idxs] = 0.0198 #print 'Retained %0.2f -- ( %g / %g )' % (100.0*(num_total - num_removed)/float(num_total),199 # num_total - num_removed, num_total)...
test_api.py
Source:test_api.py
1#!/usr/bin/env python2# -*- coding: utf-8 -*-3#4# parselglossy -- Generic input parsing library, speaking in tongues5# Copyright (C) 2020 Roberto Di Remigio, Radovan Bast, and contributors.6#7# This file is part of parselglossy.8#9# Permission is hereby granted, free of charge, to any person obtaining a copy10# of this software and associated documentation files (the "Software"), to deal11# in the Software without restriction, including without limitation the rights12# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell13# copies of the Software, and to permit persons to whom the Software is14# furnished to do so, subject to the following conditions:15#16# The above copyright notice and this permission notice shall be included in17# all copies or substantial portions of the Software.18#19# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR20# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,21# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE22# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER23# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,24# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE25# SOFTWARE.26#27# For information on the complete list of contributors to the28# parselglossy library, see: <http://parselglossy.readthedocs.io/>29#30"""Tests for `parselglossy` package."""31import json32from pathlib import Path33from shutil import rmtree34import pytest35from parselglossy import api36from parselglossy.utils import as_complex37@pytest.mark.parametrize(38 "args,out,reference",39 [40 (("tests/api/standard.inp",), None, "tests/ref/standard_ir.json"),41 (42 ("tests/api/scf.inp", "standard", "scf_ir.json"),43 "scf_ir.json",44 "tests/ref/scf_ir.json",45 ),46 (47 ("tests/api/getkw.inp", "getkw", "lex_ir.json"),48 "lex_ir.json",49 "tests/ref/getkw_ir.json",50 ),51 ],52 ids=["lex-default", "lex-standard-w-outfile", "lex-getkw-w-outfile"],53)54def test_api_lex(args, out, reference):55 ir = api.lex(*args)56 # Check intermediate representation matches with reference57 ref_json = Path(reference).resolve()58 if out is None:59 with ref_json.open("r") as f:60 assert ir == json.loads(f.read(), object_hook=as_complex)61 else:62 dumped = Path(out).resolve()63 with ref_json.open("r") as ref, dumped.open("r") as o:64 assert json.loads(o.read(), object_hook=as_complex) == json.loads(65 ref.read(), object_hook=as_complex66 )67 # Clean up JSON file68 dumped.unlink()69@pytest.mark.parametrize(70 "args,out,reference",71 [72 (73 ("tests/ref/scf_ir.json", "tests/validation/overall/template.yml"),74 None,75 "tests/ref/scf_fr.json",76 ),77 (78 (79 "tests/ref/scf_ir.json",80 "tests/validation/overall/template.yml",81 "scf_fr.json",82 ),83 "scf_fr.json",84 "tests/ref/scf_fr.json",85 ),86 ],87 ids=["validate-default", "validate-w-outfile"],88)89def test_api_validate(args, out, reference):90 fr = api.validate(*args)91 # Check final representation matches with reference92 ref_json = Path(reference).resolve()93 if out is None:94 with ref_json.open("r") as f:95 assert fr == json.loads(f.read(), object_hook=as_complex)96 else:97 dumped = Path(out).resolve()98 with ref_json.open("r") as ref, dumped.open("r") as o:99 assert json.loads(o.read(), object_hook=as_complex) == json.loads(100 ref.read(), object_hook=as_complex101 )102 # Clean up JSON file103 dumped.unlink()104@pytest.mark.parametrize(105 "args,out,reference",106 [107 (108 ("tests/api/scf.inp", "tests/validation/overall/template.yml"),109 None,110 "tests/ref/scf_fr.json",111 ),112 (113 (114 "tests/api/scf.inp",115 "tests/validation/overall/template.yml",116 "scf_fr.json",117 ),118 "scf_fr.json",119 "tests/ref/scf_fr.json",120 ),121 (122 (123 "tests/api/scf.inp",124 "tests/validation/overall/template.yml",125 None,126 "standard",127 True,128 ),129 None,130 "tests/ref/scf_fr.json",131 ),132 ],133 ids=["parse-default", "parse-w-outfile", "parse-w-dumpir"],134)135def test_api_parse(args, out, reference):136 fr = api.parse(*args)137 # Check final representation matches with reference138 ref_json = Path(reference).resolve()139 if out is None:140 with ref_json.open("r") as f:141 assert fr == json.loads(f.read(), object_hook=as_complex)142 else:143 dumped = Path(out).resolve()144 with ref_json.open("r") as ref, dumped.open("r") as o:145 assert json.loads(o.read(), object_hook=as_complex) == json.loads(146 ref.read(), object_hook=as_complex147 )148 # Clean up JSON file149 dumped.unlink()150@pytest.mark.parametrize(151 "args,out,reference",152 [153 (("tests/api/docs_template.yml",), None, "tests/ref/input.rst"),154 (155 ("tests/api/docs_template.yml", "input.rst"),156 "input.rst",157 "tests/ref/input.rst",158 ),159 (160 (161 "tests/api/docs_template.yml",162 "input.rst",163 "Dwigt Rortugal's guide to input parameters",164 ),165 "input.rst",166 "tests/ref/dwigt.rst",167 ),168 ],169 ids=["document-default", "document-w-outfile", "document-w-header"],170)171def test_api_document(args, out, reference):172 docs = api.document(*args)173 # Check final representation matches with reference174 ref_rst = Path(reference).resolve()175 if out is None:176 with ref_rst.open("r") as ref:177 assert docs == ref.read()178 else:179 dumped = Path(out).resolve()180 with ref_rst.open("r") as ref, dumped.open("r") as o:181 assert o.read() == ref.read()182 # Clean up .rst file183 dumped.unlink()184@pytest.mark.parametrize(185 "args,inp,references",186 [187 (188 {189 "template": "tests/validation/overall/template.yml",190 "docfile": "foo.rst",191 "grammar": "standard",192 },193 "tests/api/scf.inp",194 ("tests/ref/scf_fr.json", "tests/ref/generated_input.rst"),195 ),196 (197 {198 "template": "tests/validation/overall/template.yml",199 "docfile": "babar.rst",200 "grammar": [201 Path(__file__).parents[1].absolute()202 / f"parselglossy/grammars/{x}.py"203 for x in ["atoms", "getkw"]204 ],205 "tokenize": "from . import getkw; lexer = getkw.grammar(has_complex=True); ir = lexer.parseString(in_str).asDict()",206 },207 "tests/api/scf.inp",208 ("tests/ref/scf_fr.json", "tests/ref/generated_input.rst"),209 ),210 ],211 ids=["generate-default", "generated-custom-grammar"],212)213def test_api_generate(args, inp, references):214 # generate parser215 parser_dir = api.generate(**args)216 # use generated parser to parse inp217 from input_parser import api as generated_api218 fr = generated_api.parse(inp)219 # Check final representation matches with reference220 ref_json = Path(references[0]).resolve()221 with ref_json.open("r") as ref:222 assert fr == json.loads(ref.read(), object_hook=as_complex)223 # Check generated documentation agrees with reference224 ref_rst = Path(references[1]).resolve()225 dumped = parser_dir / f"docs/{args['docfile']}"226 with ref_rst.open("r") as ref, dumped.open("r") as o:227 assert o.read() == ref.read()228 # clean up generated parser...
conversions.py
Source:conversions.py
1def int_to_str(value, width):2 """3 Outputs a string of the binary of the value with4 LSB to the left.5 """6 s = bin(value)[2:]7 assert len(s) <= width8 s = '0' * (width - len(s)) + s9 return s10def signed_to_slv(value, width):11 """12 Takes a value between -1 to 1 inclusive and maps it13 into `width` bits.14 >>> bin(signed_to_slv(1, 8))15 '0b1000000'16 >>> bin(signed_to_slv(-1, 8))17 '0b11000000'18 """19 assert abs(value) <= 120 max_mag = pow(2, width-2)21 scaled = round(value * max_mag)22 if scaled < 0:23 scaled = pow(2, width) + scaled24 assert scaled < pow(2, width)25 assert isinstance(scaled, int)26 return scaled27def slv_to_signed(value, width):28 max_mag = pow(2, width-2)29 if value >= pow(2, width-1):30 value = value - pow(2, width)31 scaled = value / max_mag32 assert scaled <= 133 return scaled34def complex_to_slv(value, width):35 """36 Maps a complex number, `value`, (with mag <= 1) to an integer with37 bit width of width `width`.38 >>> bin(complex_to_slv(1+0j, 12))39 '0b10000000000'40 >>> bin(complex_to_slv(0.5-0.5j, 12))41 '0b1000111000'42 """43 assert width % 2 == 044 assert abs(value) <= 145 mapped_real = signed_to_slv(value.real, width//2)46 mapped_imag = signed_to_slv(value.imag, width//2)47 mapped = mapped_imag + mapped_real * pow(2, width//2)48 return mapped49def complex_from_slv(value, width):50 """51 Maps an integer (with bit-width `width`)52 to a complex number.53 """54 assert value < pow(2, width)55 assert width % 2 == 056 real_part = value >> width//257 imag_part = value % pow(2, width//2)58 imag_float = slv_to_signed(imag_part, width//2)59 real_float = slv_to_signed(real_part, width//2)60 as_complex = real_float + imag_float * (0+1j)61 return as_complex62def list_of_complex_to_slv(values, width):63 slv = 064 f = 165 for value in values:66 slv += complex_to_slv(value, width) * f67 f = f << width68 return slv69def list_of_complex_from_slv(value, width, size):70 assert value < pow(2, width*size)71 bits = ''.join(reversed(bin(value)[2:]))72 assert len(bits) <= width * size73 bits += '0' * (width*size - len(bits))74 lumps = [bits[index*width: (index+1)*width]75 for index in range(size)]76 complexes = []77 for lump in lumps:78 as_int = int(''.join(reversed(lump)), 2)79 as_complex = complex_from_slv(as_int, width)80 complexes.append(as_complex)81 return complexes82def list_of_uints_to_slv(values, width):83 slv = 084 f = 185 step = pow(2, width)86 for value in values:87 slv += value * f88 f *= step89 return slv90def list_of_uints_from_slv(slv, width, size):91 step = pow(2, width)92 values = []93 for i in range(size):94 values.append(slv % step)95 slv = slv >> width96 assert slv == 097 return values98if __name__ == '__main__':99 import doctest...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!