Best Python code snippet using avocado_python
test_omni_hro.py
Source:test_omni_hro.py  
1"""Unit tests for OMNI HRO special functions."""2import datetime as dt3import numpy as np4import pandas as pds5import pysat6from pysatNASA.instruments import omni_hro7class TestOMNICustom(object):8    """Unit tests for `pysat.instrument.methods.cdaweb`."""9    def setup(self):10        """Set up the unit test environment for each method."""11        # Load a test instrument12        self.testInst = pysat.Instrument('pysat', 'testing', tag='',13                                         num_samples=12, clean_level='clean')14        self.testInst.load(2009, 1)15        # Recast time in minutes rather than seconds16        self.testInst.data.index = \17            pds.Series([t + dt.timedelta(seconds=(60 - i))18                        + dt.timedelta(minutes=i)19                        for i, t in enumerate(self.testInst.data.index)])20        # Add IMF data21        self.testInst['BX_GSM'] = pds.Series([3.17384966, 5.98685138,22                                              1.78749668, 0.38628409,23                                              2.73080263, 1.58814078,24                                              5.24880448, 3.92347300,25                                              5.59494670, 0.93246592,26                                              5.23676319, 1.14214992],27                                             index=self.testInst.data.index)28        self.testInst['BY_GSM'] = pds.Series([3.93531272, 2.50331246,29                                              0.99765539, 1.07203600,30                                              5.43752734, 5.10629137,31                                              0.59588891, 2.19412638,32                                              0.15550858, 3.75433603,33                                              4.82323932, 3.61784563],34                                             index=self.testInst.data.index)35        self.testInst['BZ_GSM'] = pds.Series([3.94396168, 5.61163579,36                                              4.02930788, 5.47347958,37                                              5.69823962, 0.47219819,38                                              1.47760461, 3.47187188,39                                              4.12581021, 4.40641671,40                                              2.87780562, 0.58539121],41                                             index=self.testInst.data.index)42        self.testInst['flow_speed'] = \43            pds.Series([394.396168, 561.163579,44                        402.930788, 547.347958,45                        569.823962, 47.219819,46                        147.760461, 347.187188,47                        412.581021, 440.641671,48                        287.780562, 58.539121],49                       index=self.testInst.data.index)50        return51    def teardown(self):52        """Clean up the unit test environment after each method."""53        del self.testInst54        return55    def test_clock_angle(self):56        """Test results of calculate_clock_angle."""57        # Run the clock angle routine58        omni_hro.calculate_clock_angle(self.testInst)59        # Set test clock angle60        test_angle = np.array([44.93710732, 24.04132437, 13.90673288,61                               11.08167359, 43.65882745, 84.71666707,62                               21.96325222, 32.29174675, 2.15855047,63                               40.43151704, 59.17741091, 80.80882619])64        # Test the difference.  There may be a 2 pi integer ambiguity65        test_diff = abs(test_angle - self.testInst['clock_angle'])66        assert np.all(test_diff < 1.0e-8)67        return68    def test_yz_plane_mag(self):69        """Test the Byz plane magnitude calculation."""70        # Run the clock angle routine71        omni_hro.calculate_clock_angle(self.testInst)72        # Calculate plane magnitude73        test_mag = np.array([5.57149172, 6.14467489, 4.15098040, 5.57747612,74                             7.87633407, 5.12807787, 1.59323538, 4.10707742,75                             4.12873986, 5.78891590, 5.61652942, 3.66489971])76        # Test the difference77        test_diff = abs(test_mag - self.testInst['BYZ_GSM'])78        assert np.all(test_diff < 1.0e-8)79        return80    def test_yz_plane_cv(self):81        """Test the IMF steadiness CV calculation."""82        # Run the clock angle and steadiness routines83        omni_hro.calculate_clock_angle(self.testInst)84        omni_hro.calculate_imf_steadiness(self.testInst, steady_window=5,85                                          min_window_frac=0.8)86        # Ensure the BYZ coefficient of variation is calculated correctly87        byz_cv = np.array([np.nan, 0.158620, 0.229267, 0.239404, 0.469371,88                           0.470944, 0.495892, 0.384522, 0.396275, 0.208209,89                           0.221267, np.nan])90        # Test the difference91        test_diff = abs(byz_cv - self.testInst['BYZ_CV'])92        assert test_diff[np.isnan(test_diff)].shape[0] == 293        assert np.all(test_diff[~np.isnan(test_diff)] < 1.0e-6)94        assert np.all(np.isnan(self.testInst['BYZ_CV']) == np.isnan(byz_cv))95        return96    def test_clock_angle_std(self):97        """Test the IMF steadiness standard deviation calculation."""98        # Run the clock angle and steadiness routines99        omni_hro.calculate_clock_angle(self.testInst)100        omni_hro.calculate_imf_steadiness(self.testInst, steady_window=5,101                                          min_window_frac=0.8)102        # Ensure the BYZ coefficient of variation is calculated correctly103        ca_std = np.array([np.nan, 13.317200, 14.429278, 27.278579,104                           27.468469, 25.500730, 27.673033, 27.512069,105                           19.043833, 26.616713, 29.250390, np.nan])106        # Test the difference107        test_diff = abs(ca_std - self.testInst['clock_angle_std'])108        assert test_diff[np.isnan(test_diff)].shape[0] == 2109        assert np.all(test_diff[~np.isnan(test_diff)] < 1.0e-6)110        assert np.all(np.isnan(self.testInst['clock_angle_std'])111                      == np.isnan(ca_std))112        return113    def test_dayside_recon(self):114        """Test the IMF steadiness standard deviation calculation."""115        # Run the clock angle and steadiness routines116        omni_hro.calculate_clock_angle(self.testInst)117        omni_hro.calculate_dayside_reconnection(self.testInst)118        # Ensure the BYZ coefficient of variation is calculated correctly119        rcon = np.array([698.297487, 80.233896, 3.033586, 2.216075,120                         1425.310083, 486.460306, 2.350339, 103.843722,121                         0.000720, 534.586320, 1464.596772, 388.974792])122        # Test the difference123        test_diff = abs(rcon - self.testInst['recon_day'])124        assert test_diff.shape[0] == 12125        assert np.all(test_diff < 1.0e-6)...split_pairs_XZ.py
Source:split_pairs_XZ.py  
1#!/usr/bin/env python2import sys3import shutil4import matplotlib.pyplot as plt5import matplotlib.image as mpimg6def format_filename(name, number):7    num_zeros = "0"*(4 - len(number))8    filepath = "../lfw-deepfunneled/"+name+"/"+name+"_"+num_zeros+number+".jpg"9    return filepath10def split(train_file, test_file, train_same, train_diff, vali_same, vali_diff, test_same, test_diff):11    file_handler = open(train_file, "r", encoding="utf-8");12    for row in file_handler:13        temp=row.replace("\n", "");14        string= temp.split("\t"); # split it by whitespace15        converted = [x for x in string]16        if len(converted) ==3:17            train_same.append(converted);18        if len(converted) ==4:19            train_diff.append(converted);20    file_handler.close()21    22        23    file_handler = open( test_file, "r", encoding="utf-8")24    # We must first put the data in a list	25    for row in file_handler:26        temp=row.replace("\n", "");27        string= temp.split("\t") # split it by whitespace28        converted = [x for x in string]29        if len(converted) ==3:30            test_same.append(converted);31        if len(converted) ==4:32            test_diff.append(converted);33    file_handler.close()34    35    for i in range(len(test_same)//2):36        vali_same.append( test_same.pop() );37    38    for i in range( len(test_diff)//2 ):39        vali_diff.append( test_diff.pop() );40    41    print(len(train_same), len(vali_same), len(test_same) );42	43def get_image_plot(train_same, vali_same, test_diff):44	plt.figure();45	plt.subplot(3, 2, 1)46	img=mpimg.imread(format_filename(train_same[0][0], train_same[0][1] )  )47	imgplot = plt.imshow(img)48	plt.title(train_same[0][0]);49	plt.xticks([])50	plt.yticks([])51	52	plt.subplot(3, 2, 2)53	img=mpimg.imread(format_filename(train_same[0][0], train_same[0][2] )  )54	imgplot = plt.imshow(img)55	plt.title(train_same[0][0]);56	plt.xticks([])57	plt.yticks([])58	59	plt.subplot(3, 2, 3)60	img=mpimg.imread(format_filename(vali_same[0][0], vali_same[0][1] )  )61	imgplot = plt.imshow(img)62	plt.title(vali_same[0][0]);63	plt.xticks([])64	plt.yticks([])65	66	plt.subplot(3, 2, 4)67	img=mpimg.imread(format_filename(vali_same[0][0], vali_same[0][2] )  )68	imgplot = plt.imshow(img)69	plt.title(vali_same[0][0]);70	plt.xticks([])71	plt.yticks([])72	73	plt.subplot(3, 2, 5)74	img=mpimg.imread(format_filename(test_diff[0][0], test_diff[0][1] )  )75	imgplot = plt.imshow(img)76	plt.title(test_diff[0][0]);77	plt.xticks([])78	plt.yticks([])79	80	plt.subplot(3, 2, 6)81	img=mpimg.imread(format_filename(test_diff[0][2], test_diff[0][3] )  )82	imgplot = plt.imshow(img)83	plt.title(test_diff[0][2]);84	plt.xticks([])85	plt.yticks([])86	87	plt.tight_layout()88	plt.show()89	90def main():91	train_file="../pairsDevTrain.txt";92	test_file= "../pairsDevTest.txt";93	train_same=[];94	train_diff=[];95	vali_same=[];96	vali_diff=[];97	test_same= [];98	test_diff= [];99	100	split(train_file, test_file, train_same, train_diff, vali_same, vali_diff, test_same, test_diff);101	get_image_plot(train_same, vali_same, test_diff);102	103if __name__ == '__main__':104	main();105	106	...lstm_single_output_forecasts.py
Source:lstm_single_output_forecasts.py  
1from math import sqrt2import numpy as np3from sklearn.metrics import mean_squared_error4from base.base_forecasts import BaseForecasts5class LSTMSingleOutputForecasts(BaseForecasts):6    def __init__(self, model, data_loader, config):7        super(LSTMSingleOutputForecasts, self).__init__(data_loader, config)8        self.model = model9        #       tuple -> self.X_test = self.test_data[0], self.y_test = self.test_data[1]10        self.forecasts_rescaled = []11    def forecast(self, test_raw, test_data, i):12        self.forecasts_scaled = self.model.predict(13            test_data[0],14            batch_size=self.config.trainer.batch_size,15            verbose=self.config.trainer.verbose_training16        )17        test_diff = self.data_loader.data_transformer.reverse_transform(self.forecasts_scaled, test_data[0], i)18        test_raw = test_raw[self.config.data_loader.window_size:]19        # test_calculated = self.calculate_predicted(test_raw, test_diff)20        # test_raw = test_raw[1:]21        test_calculated = test_diff22        rmse = self.evaluate(test_raw, test_calculated)23        return test_raw, test_calculated, rmse24    def calculate_predicted(self, test_raw, test_diff):25        test_calculated = []26        for i in range(0, len(test_diff)):27            forecast = test_raw[i] + test_diff[i]28            test_calculated.append(forecast)29        test_calculated = np.array(test_calculated)30        return test_calculated31    def evaluate(self, test_raw, test_calculated):32        forecasts = test_calculated.flatten()33        rmse = sqrt(mean_squared_error(test_raw, forecasts))34        return rmse35    def forecast_without_model(self, test_raw, i):...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!!
