Best Python code snippet using molecule_python
test_interpolate.py
Source:test_interpolate.py  
...16    self.n = 517    self.coefs = list((ra.random((self.n,)) * 0.5 - 1.0) * 2.0)18    self.x = ra.random((1,))[0]19    self.interpolate = interpolate.PolynomialInterpolate(self.coefs)20  def test_interpolate(self):21    self.assertTrue(np.isclose(np.polyval(self.coefs, self.x),22      self.interpolate(self.x)))23class TestPiecewiseLinearInterpolate(unittest.TestCase, BaseInterpolate):24  def setUp(self):25    self.validx = [-10.0, -2.0, 1.0, 2.0, 5.0, 15.0]26    self.invalidx_1 = [-2.0, -10.0, 1.0, 2.0, 5.0, 15.0]27    self.invalidx_2 = [-10.0, -2.0, 1.0, 2.0, 5.0]28    self.points = [50.0, -25.0, 1.0, 0.0, 0.0, 10.0]29    self.x = 17.030    self.valid = interpolate.PiecewiseLinearInterpolate(self.validx, 31        self.points)32    self.invalid1 = interpolate.PiecewiseLinearInterpolate(self.invalidx_1, 33        self.points)34    self.invalid2 = interpolate.PiecewiseLinearInterpolate(self.invalidx_2, 35        self.points)36    self.interpolate = self.valid37  def test_valid(self):38    self.assertTrue(self.valid.valid)39    self.assertFalse(self.invalid1.valid)40    self.assertFalse(self.invalid2.valid)41  def test_interpolate(self):42    testinter = inter.interp1d(self.validx, self.points,43        bounds_error = False)44    xs = np.linspace(-15.0,20.0)45    ys1 = [self.valid(x) for x in xs]46    ys2 = testinter(xs)47    ys2[xs < self.validx[0]] = self.points[0]48    ys2[xs > self.validx[-1]] = self.points[-1]49    self.assertTrue(np.allclose(ys1, ys2))50class TestGenericPiecewiseInterpolate(unittest.TestCase, BaseInterpolate):51  def setUp(self):52    self.xs = [1.0,5.0]53    self.cvs = [-1.0,5.0,-2.0]54    self.fns = [interpolate.ConstantInterpolate(cv) for cv in self.cvs]55    self.interpolate = interpolate.GenericPiecewiseInterpolate(self.xs,56        self.fns)57    self.x = 4.058  def test_interpolate(self):59    self.assertTrue(np.isclose(self.interpolate.value(0.0), self.cvs[0]))60    self.assertTrue(np.isclose(self.interpolate.value(4.0), self.cvs[1]))61    self.assertTrue(np.isclose(self.interpolate.value(10.0), self.cvs[2]))62class TestPiecewiseLogLinearInterpolate(unittest.TestCase, BaseInterpolate):63  def setUp(self):64    self.validx = [-10.0, -2.0, 1.0, 2.0, 5.0, 15.0]65    self.invalidx_1 = [-2.0, -10.0, 1.0, 2.0, 5.0, 15.0]66    self.invalidx_2 = [-10.0, -2.0, 1.0, 2.0, 5.0]67    self.points = [1.0e5, 1.0e0, 1.0e-1, 1.0e-6, 1.0e0, 1.0e2]68    self.invalidpoints = [1.0e5, 1.0e0, -1.0e-1, 1.0e-6, 1.0e0, 1.0e2]69    self.x = 17.070    self.valid = interpolate.PiecewiseLogLinearInterpolate(self.validx, 71        self.points)72    self.invalid1 = interpolate.PiecewiseLogLinearInterpolate(self.invalidx_1, 73        self.points)74    self.invalid2 = interpolate.PiecewiseLogLinearInterpolate(self.invalidx_2, 75        self.points)76    self.invalid3 = interpolate.PiecewiseLogLinearInterpolate(self.validx, 77        self.invalidpoints)78    self.interpolate = self.valid79  def test_valid(self):80    self.assertTrue(self.valid.valid)81    self.assertFalse(self.invalid1.valid)82    self.assertFalse(self.invalid2.valid)83    self.assertFalse(self.invalid3.valid)84  def test_interpolate(self):85    testinter = inter.interp1d(self.validx, np.log(self.points),86        bounds_error = False)87    xs = np.linspace(-15.0,20.0)88    ys1 = [self.valid(x) for x in xs]89    yp = testinter(xs)90    yp[xs < self.validx[0]] = np.log(self.points[0])91    yp[xs > self.validx[-1]] = np.log(self.points[-1])92    ys2 = np.exp(yp)93    self.assertTrue(np.allclose(ys1, ys2))94class TestPiecewiseSemiLogXLinearInterpolate(unittest.TestCase, BaseInterpolate):95  def setUp(self):96    self.validx = [1e-2, 0.5, 1.0, 2.0, 5.0, 15.0]97    self.points = [10,20,30,40,50,60]98    self.x = 7.599    self.interpolate = interpolate.PiecewiseSemiLogXLinearInterpolate(self.validx, 100        self.points)101  def test_interpolate(self):102    testinter = inter.interp1d(np.log10(self.validx), self.points,103        bounds_error = False)104    xs = np.linspace(1e-3,20.0,500)105    ys1 = [self.interpolate(x) for x in xs]106    ys2 = testinter(np.log10(xs))107    ys2[xs < self.validx[0]] = self.points[0]108    ys2[xs > self.validx[-1]] = self.points[-1]109    self.assertTrue(np.allclose(ys1, ys2))110class TestConstantInterpolate(unittest.TestCase, BaseInterpolate):111  def setUp(self):112    self.v = ra.random((1,))[0]113    self.interpolate = interpolate.ConstantInterpolate(self.v)114    self.x = ra.random((1,))[0]115  def test_interpolate(self):116    self.assertTrue(np.isclose(self.v, self.interpolate(self.x)))117class TestExpInterpolate(unittest.TestCase, BaseInterpolate):118  def setUp(self):119    self.A = 1.2120    self.B = 5.1121    self.interpolate = interpolate.ExpInterpolate(self.A, self.B)122    self.x = 0.5123  def test_interpolate(self):124    self.assertTrue(np.isclose(self.A * np.exp(self.B/self.x),125      self.interpolate(self.x)))126class TestPowerLawInterpolate(unittest.TestCase, BaseInterpolate):127  def setUp(self):128    self.A = 5.1129    self.B = 0.3130    self.interpolate = interpolate.PowerLawInterpolate(self.A, self.B)131    self.x = 2.1132  def test_interpolate(self):133    self.assertTrue(np.isclose(self.A * self.x**self.B, 134      self.interpolate(self.x)))135class TestMTSShearInterpolate(unittest.TestCase, BaseInterpolate):136  def setUp(self):137    self.y0 = 100.0138    self.D = 50.0139    self.x0 = 200.0140    self.interpolate = interpolate.MTSShearInterpolate(self.y0, self.D, self.x0)141    self.x = 300.0142  def test_interpolate(self):143    should = self.y0 - self.D / (np.exp(self.x0 / self.x) - 1.0)144    act = self.interpolate(self.x)145    self.assertTrue(np.isclose(should, act))146class TestMTSInterpolate(unittest.TestCase, BaseInterpolate):147  def setUp(self):148    self.tau0 = 300.0149    self.g0 = 0.75150    E_poly = np.array([-3.94833389e-02, -5.20197047e+01, 1.95594836e+05])151    nu = 0.31152    self.mu = interpolate.PolynomialInterpolate(E_poly/(2*(1+nu)))153    self.k = 1.38064e-20154    self.b = 2.02e-7155    self.p = 0.8156    self.q = 0.9157    self.interpolate = interpolate.MTSInterpolate(self.tau0, self.g0, self.q, self.p, self.k, self.b, self.mu)158    self.x = 300.0159  def test_interpolate(self):160    should = self.tau0 * (1.0- (self.k*self.x/(self.mu(self.x)*self.b**3.0*self.g0))**(1.0/self.q))**(1.0/self.p) 161    act = self.interpolate(self.x)...test_utils.py
Source:test_utils.py  
1# -*- coding: utf-8 -*-2import unittest3import os4from advanced_ssh_config.utils import (safe_makedirs, value_interpolate,5                                       construct_proxy_commands, shellquote,6                                       shellquotemultiple)7from advanced_ssh_config.exceptions import ConfigError8from . import PREFIX9class TestContructProxyCommand(unittest.TestCase):10    def test_no_arg(self):11        self.assertRaises(TypeError, construct_proxy_commands)12    def test_empty_arg(self):13        self.assertRaises(ValueError, construct_proxy_commands, {})14    def test_minimal_valid(self):15        command = construct_proxy_commands({16            'hostname': 'aaa',17            'port': 42,18        })19        self.assertEqual(20            command, [['nc', '-w', 180, '-G', 5, 'aaa', 42], ['nc', 'aaa', 42]]21        )22    def test_minimal_nc(self):23        command = construct_proxy_commands({24            'hostname': 'aaa',25            'proxy_type': 'nc',26            'port': 42,27        })28        self.assertEqual(29            command, [['nc', '-w', 180, '-G', 5, 'aaa', 42], ['nc', 'aaa', 42]]30        )31    def test_full_nc(self):32        command = construct_proxy_commands({33            'hostname': 'aaa',34            'port': 42,35            'verbose': True,36            'proxy_type': 'nc',37            'timeout': 45,38        })39        self.assertEqual(40            command, [41                ['nc', '-v', '-w', 45, '-G', 5, 'aaa', 42],42                ['nc', 'aaa', 42]43            ]44        )45    def test_invalid_proxy_type(self):46        args = {47            'hostname': 'aaa',48            'port': 42,49            'proxy_type': 'fake',50            }51        self.assertRaises(ValueError, construct_proxy_commands, args)52    def test_minimal_socat(self):53        command = construct_proxy_commands({54            'hostname': 'aaa',55            'proxy_type': 'socat',56            'port': 42,57        })58        self.assertEqual(command, [['socat', 'STDIN', 'TCP:aaa:42']])59    def test_minimal_socat_http_proxy(self):60        command = construct_proxy_commands({61            'hostname': 'aaa',62            'proxy_type': 'socat_http_proxy',63            'http_proxy_host': 'bbb',64            'http_proxy_port': 43,65            'port': 42,66        })67        self.assertEqual(68            command, [['socat', 'STDIN', 'PROXY:bbb:aaa:42,proxyport=43']]69        )70    def test_minimal_socat_socks(self):71        command = construct_proxy_commands({72            'hostname': 'aaa',73            'proxy_type': 'socat_socks',74            'socks_host': 'bbb',75            'socks_port': 43,76            'port': 42,77        })78        self.assertEqual(79            command, [['socat', 'STDIN', 'SOCKS:bbb:aaa:42,socksport=43']]80        )81    # FIXME: test_custom_handler82class TestSafeMakedirs(unittest.TestCase):83    def setUp(self):84        if os.path.exists(PREFIX):85            os.system('rm -rf {}'.format(PREFIX))86        os.makedirs(PREFIX)87    def test_already_exists(self):88        safe_makedirs('{}/dir'.format(PREFIX))89        safe_makedirs('{}/dir'.format(PREFIX))90    def test_invalid(self):91        for path in ('/dev/null/test',):92            self.assertRaises(OSError, safe_makedirs, path)93    def test_makedirs_on_file(self):94        open('{}/file'.format(PREFIX), 'w').write('hello')95        self.assertRaises(OSError, safe_makedirs, '{}/file/dir'.format(PREFIX))96class TestValueInterpolate(unittest.TestCase):97    def setUp(self):98        if os.environ.get('TEST_INTERPOLATE'):99            del os.environ['TEST_INTERPOLATE']100    def test_interpolate_success(self):101        os.environ['TEST_INTERPOLATE'] = 'titi'102        self.assertEquals(value_interpolate('$TEST_INTERPOLATE'), 'titi')103    def test_interpolate_no_match(self):104        self.assertEquals(105            value_interpolate('$TEST_INTERPOLATE'), '$TEST_INTERPOLATE'106        )107    def test_interpolate_not_interpolable(self):108        os.environ['TEST_INTERPOLATE'] = 'titi'109        self.assertEquals(110            value_interpolate('TEST_INTERPOLATE'), 'TEST_INTERPOLATE'111        )112    def test_interpolate_interpolate_recursive(self):113        os.environ['TEST_INTERPOLATE'] = '$TEST_INTERPOLATE_2'114        os.environ['TEST_INTERPOLATE_2'] = '$TEST_INTERPOLATE_3'115        os.environ['TEST_INTERPOLATE_3'] = '$TEST_INTERPOLATE_4'116        os.environ['TEST_INTERPOLATE_4'] = 'tutu'117        self.assertEquals(value_interpolate('$TEST_INTERPOLATE'), 'tutu')118    def test_interpolate_interpolate_loop(self):119        os.environ['TEST_INTERPOLATE'] = '$TEST_INTERPOLATE'120        self.assertRaises(ConfigError, value_interpolate, '$TEST_INTERPOLATE')121    def test_interpolate_interpolate_loop_complex(self):122        os.environ['TEST_INTERPOLATE'] = '$TEST_INTERPOLATE_2'123        os.environ['TEST_INTERPOLATE_2'] = '$TEST_INTERPOLATE_3'124        os.environ['TEST_INTERPOLATE_3'] = '$TEST_INTERPOLATE'125        self.assertRaises(ConfigError, value_interpolate, '$TEST_INTERPOLATE')126class TestShellQuote(unittest.TestCase):127    def test_shellquote_simple(self):128        self.assertEquals(shellquote(["aaa"]), 'aaa')129        self.assertEquals(shellquote(["aaa", "bbb"]), 'aaa bbb')130        self.assertEquals(shellquote(["aaa", "bbb", 42]), 'aaa bbb 42')131    def test_shellquote_empty(self):132        self.assertEquals(shellquote([]), '')133    def test_shellquote_escape(self):134        self.assertEquals(shellquote(["test'test"]), "'test\\'test'")135        self.assertEquals(shellquote(["test\\test"]), "'test\\\\test'")136        self.assertEquals(shellquote(["test\"test"]), "test\"test")137    def test_shellquote_complex(self):138        self.assertEquals(139            shellquote(["ssh", "manfred's imac", '-p', 4242]),140            "ssh 'manfred\\'s imac' -p 4242"141        )142    def test_shellquote_not_list(self):143        self.assertRaises(ValueError, shellquote, 'aaa')144class TestShellQuoteMultiple(unittest.TestCase):145    def test_shellquote_multiple_simple(self):146        self.assertEquals(147            shellquotemultiple([['aaa', 'bbb', 42], ['ccc', 'ddd', 43]]),148            '(aaa bbb 42 2>/dev/null || ccc ddd 43)'149        )150    def test_shellquote_not_list_of_list(self):151        self.assertRaises(ValueError, shellquotemultiple, [42, 42])152        self.assertRaises(ValueError, shellquotemultiple, 42)...Interpolation.py
Source:Interpolation.py  
...8""" Interpolation holds classes and functions important for interpolating data.9  Examples10--------11    #!python12    >>test_interpolate()13 <h3><a href="../../../Examples/html/Interpolation_Example.html">Interpolation Example</a></h3>14Requirements15------------16+ [sys](https://docs.python.org/2/library/sys.html)17+ [os](https://docs.python.org/2/library/os.html)18+ [types](https://docs.python.org/2/library/types.html)19+ [numpy](https://docs.scipy.org/doc/)20+ [scipy](https://docs.scipy.org/doc/)21Help22---------------23<a href="./index.html">`pyMez.Code.Analysis`</a>24<div>25<a href="../../../pyMez_Documentation.html">Documentation Home</a> |26<a href="../../index.html">API Documentation Home</a> |27<a href="../../../Examples/html/Examples_Home.html">Examples Home</a> |28<a href="../../../Reference_Index.html">Index</a>29</div>30 """31#-----------------------------------------------------------------------------32# Standard Imports33import os34import sys35from types import *36#-----------------------------------------------------------------------------37# Third Party Imports38sys.path.append(os.path.join(os.path.dirname( __file__ ), '..','..'))39try:40    import numpy as np41except:42    print("Numpy was not imported")43    raise44try:45    from scipy.interpolate import interp1d46except:47    print("The function scipy.interpolate.interp1d did not import properly,"48          "please check that scipy is on the python path and that it is not in an error state")49    raise50#-----------------------------------------------------------------------------51# Module Constants52#-----------------------------------------------------------------------------53# Module Functions54def interpolate_data(data_list,**options):55    """interpolate data takes a list of data in [[x,y1,y2,..yn]..] format and56    returns a list of interpolation functions [f1(x),f2(x),f3(x)...fn(x)]"""57    out_list=[]58    # reorganize the list to [[x,..xm],[y,...ym]]59    vector_list=[]60    for index,column in enumerate(data_list[0]):61        vector=[row[index] for row in data_list]62        vector_list.append(vector)63    # now each function is interp1d of64    for vector in vector_list[1:]:65        f=interp1d(vector_list[0],vector,**options)66        out_list.append(f)67    return out_list68def build_interpolated_data_set(x_list,interpolated_function_list):69    """build_interpolated_data_set takes an input independent variable and a list70    of interpolation functions and returns a data set of the form [..[xi,f1(xi),..fn(xi)]]71    it is meant to create a synthetic data set after using interpolate_data"""72    out_data=[]73    for x in x_list:74        new_row=[]75        new_row.append(x)76        for function in interpolated_function_list:77            # to list is needed if the function returns np.array78            if type(function(x)) in [np.ndarray]:79                new_row.append(function(x).tolist())80            else:81                new_row.append(function(x))82        out_data.append(new_row)83    return out_data84def interpolate_table(table,independent_variable_list):85    """Returns a copy of the table interpolated to the independent variable list86    Assumes there is a single independent variable in the first column"""87    functions=interpolate_data(table.data)88    new_data=build_interpolated_data_set(independent_variable_list,functions)89    new_table=table.copy()90    new_table.data=new_data91    return new_table92#-----------------------------------------------------------------------------93# Module Classes94#-----------------------------------------------------------------------------95# Module Scripts96def test_interpolate(data_set=None):97    if data_set is None:98        data_set=[[i,i**2,i**3] for i in range(100)]99    interpolation_functions=interpolate_data(data_set)100    type_of_f=type(interpolation_functions[0](1))101    print(("The types of of the function results are {0}".format(type_of_f)))102    print(("type(f(x)) == numpy.ndarray is {0}".format(type_of_f in [np.ndarray,"<type 'numpy.ndarray'>"])))103    new_x=[i for i in range(100)]104    interpolated_data=build_interpolated_data_set(new_x,interpolation_functions)105    print("Testing interpolation of data set")106    print(("*"*80))107    print(("the old data set is {0} ".format(data_set)))108    print(("*"*80))109    print(("the new data set is {0}".format(interpolated_data)))110#-----------------------------------------------------------------------------111# Module Runner112if __name__ == '__main__':113    test_interpolate()...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!!
