Best Python code snippet using lemoncheesecake
compare.py
Source:compare.py
1import os2import os.path3from typing import Tuple4import bokeh5import bokeh.io6import bokeh.model7import bokeh.plotting8import bokeh.util.platform9import matplotlib.pyplot as plt10import pyproj11from bokeh.models import ColumnDataSource, Circle12from bokeh.tile_providers import STAMEN_TERRAIN13from netCDF4 import Dataset14from numpy import ndarray15from .figurewriter import FigureWriter16from .inspect import L1bProductInspector17# (Plotting) Resources:18# * http://matplotlib.org/api/pyplot_api.html19# * http://matplotlib.org/users/image_tutorial.html20# * http://ipywidgets.readthedocs.io/en/latest/21# * http://bokeh.pydata.org/en/0.11.1/docs/user_guide/geo.html22# * http://bokeh.pydata.org/en/0.11.1/docs/user_guide/notebook.html23def compare_l1b_products(product_file_path_1: str,24 product_file_path_2: str,25 output_path=None, output_format=None) -> 'L1bProductComparator':26 """27 Open two L1B files for comparison.28 If *output_format* is "dir" then a new directory given by *output_path*29 will be created. Each plot figure will will be saved in a new file.30 If *output_format* is "pdf" then a new multi-page PDF document given by *output_path*31 will be created or overwritten if it exists. Each plot figure will will be saved in a new PDF page.32 Format "pdf" does not support all plot types.33 If *output_format* is not given it defaults it is derived from *output_path*.34 Note that both *output_path* and *output_format* arguments are ignored if the inspection is run in an35 Jupyter (IPython) Notebook.36 :param product_file_path_1: The file path of the first L1B product.37 :param product_file_path_2: The file path of the second L1B product.38 :param output_path: The output path where plot figures are written to.39 :param output_format: The output format. Supported formats are "pdf" and "dir".40 """41 if output_path:42 figure_writer = FigureWriter(output_path, output_format)43 else:44 bokeh.io.output_notebook(hide_banner=True)45 figure_writer = None46 return L1bProductComparator(product_file_path_1, product_file_path_2, figure_writer)47class L1bProductComparator:48 """49 The `L1bInspector` class provides access to L1B contents and provides a number of analysis functions.50 """51 def __init__(self,52 product_file_path_1: str,53 product_file_path_2: str,54 figure_writer: FigureWriter):55 if not product_file_path_1:56 raise ValueError('file_path_1 must be given')57 if not product_file_path_2:58 raise ValueError('file_path_2 must be given')59 product_inspector_1 = L1bProductInspector(product_file_path_1, figure_writer)60 product_inspector_2 = L1bProductInspector(product_file_path_2, figure_writer)61 if product_inspector_1.waveform.shape != product_inspector_2.waveform.shape:62 raise ValueError('"%s" and "%s" cannot be compared as they have different waveform dimensions' % (63 product_file_path_1, product_file_path_2))64 self._product_inspector_1 = product_inspector_165 self._product_inspector_2 = product_inspector_266 self._plot = L1bProductComparatorPlots(self, figure_writer)67 self._waveforms_delta = product_inspector_1.waveform - product_inspector_2.waveform68 self._waveforms_delta_range = self._waveforms_delta.min(), self._waveforms_delta.max()69 @property70 def p1(self) -> L1bProductInspector:71 """72 Get the first L1b file inspector.73 """74 return self._product_inspector_175 @property76 def p2(self) -> L1bProductInspector:77 """78 Get the second L1b file inspector.79 """80 return self._product_inspector_281 @property82 def file_paths(self) -> Tuple[str, str]:83 """84 Get the L1b file path.85 """86 return self.p1.file_path, self.p2.file_path87 @property88 def datasets(self) -> Tuple[Dataset, Dataset]:89 """90 Get the underlying netCDF dataset object.91 """92 return self.p1.dataset, self.p2.dataset93 @property94 def waveforms(self) -> Tuple[ndarray, ndarray]:95 """96 Get the underlying netCDF dataset object.97 """98 return self.p1.waveform, self.p2.waveform99 @property100 def waveforms_delta(self) -> ndarray:101 """102 Get the delta waveforms[0] - waveforms[1].103 """104 return self._waveforms_delta105 @property106 def waveforms_delta_range(self) -> Tuple[float, float]:107 """108 Get the range waveforms[0].min(), waveforms[1].max().109 """110 return self._waveforms_delta_range111 @property112 def plot(self) -> 'L1bProductComparatorPlots':113 """114 Get the plotting context.115 """116 return self._plot117 def close(self):118 """Close the underlying dataset's file access."""119 self.p1.close()120 self.p2.close()121 self.plot.close()122class L1bProductComparatorPlots:123 def __init__(self, product_comparator: L1bProductComparator, figure_writer: FigureWriter):124 self._plt = plt125 self._comparator = product_comparator126 self._interactive = figure_writer is None127 self._figure_writer = figure_writer128 def locations(self, color1='blue', color2='red'):129 # Spherical Mercator130 mercator = pyproj.Proj(init='epsg:3857')131 # Equirectangular lat/lon on WGS84132 equirectangular = pyproj.Proj(init='epsg:4326')133 lon1 = self._comparator.p1.lon134 lat1 = self._comparator.p1.lat135 x1, y1 = pyproj.transform(equirectangular, mercator, lon1, lat1)136 lon2 = self._comparator.p2.lon137 lat2 = self._comparator.p2.lat138 x2, y2 = pyproj.transform(equirectangular, mercator, lon2, lat2)139 source1 = ColumnDataSource(data=dict(x=x1, y=y1))140 source2 = ColumnDataSource(data=dict(x=x2, y=y2))141 circle1 = Circle(x='x', y='y', size=6, fill_color=color1, fill_alpha=0.5, line_color=None)142 circle2 = Circle(x='x', y='y', size=6, fill_color=color2, fill_alpha=0.5, line_color=None)143 # map_options = GMapOptions(lat=30.29, lng=-97.73, map_type="roadmap", zoom=11)144 # plot = GMapPlot(x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options)145 # plot.title.text = 'L1B Footprint'146 # plot.add_glyph(source, circle)147 # plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool())148 fig = bokeh.plotting.figure(x_range=(min(x1.min(), x2.min()),149 max(x1.max(), x2.max())),150 y_range=(min(y1.min(), y2.min()),151 max(y1.max(), y2.max())),152 toolbar_location='above')153 fig.axis.visible = False154 # fig.add_tile(STAMEN_TONER)155 fig.add_tile(STAMEN_TERRAIN)156 fig.title.text = "L1B Footprints"157 # fig.title = 'L1B Footprint'158 fig.add_glyph(source1, circle1)159 fig.add_glyph(source2, circle2)160 if self._interactive:161 bokeh.io.show(fig)162 elif self._figure_writer.output_format == "dir":163 os.makedirs(self._figure_writer.output_path, exist_ok=True)164 bokeh.io.save(fig, os.path.join(self._figure_writer.output_path, 'fig-locations.html'),165 title='L1B Locations')166 else:167 print('warning: cannot save locations figure with output format "%s"' % self._figure_writer.output_format)168 def waveforms_delta_im(self, vmin=None, vmax=None, cmap='RdBu_r'):169 vmin = vmin if vmin else self._comparator.waveforms_delta_range[0]170 vmax = vmax if vmax else self._comparator.waveforms_delta_range[1]171 plt.figure(figsize=(10, 10))172 plt.imshow(self._comparator.waveforms_delta, interpolation='nearest', aspect='auto', vmin=vmin, vmax=vmax,173 cmap=cmap)174 plt.xlabel('Echo Sample Index')175 plt.ylabel('Time Index')176 plt.title('Waveform 1, Waveform 2 Delta')177 plt.colorbar(orientation='vertical')178 if self._interactive:179 plt.show()180 else:181 self.savefig("fig-waveform_delta-im.png")182 def waveforms_hist(self, vmin=None, vmax=None, bins=128, log=False, color1='blue', color2='red', alpha=0.5):183 """184 Draw waveform histogram.185 :param vmin: Minimum display value186 :param vmax: Maximum display value187 :param bins: Number of bins188 :param log: Show logarithms of bin counts189 :param color1: Color of the first histogram190 :param color2: Color of the second histogram191 :param alpha: Alpha value for histograms192 """193 vmin = vmin if vmin else self._comparator.waveforms_delta_range[0]194 vmax = vmax if vmax else self._comparator.waveforms_delta_range[1]195 vmax = vmin + 1 if vmin == vmax else vmax196 plt.figure(figsize=(12, 6))197 plt.hist(self._comparator.p1.waveform.flatten(),198 range=(vmin, vmax),199 bins=bins,200 log=log,201 facecolor=color1,202 alpha=alpha,203 normed=True,204 label='Waveform 1')205 plt.hist(self._comparator.p2.waveform.flatten(),206 range=(vmin, vmax),207 bins=bins,208 log=log,209 facecolor=color2,210 alpha=alpha,211 normed=True,212 label='Waveform 2')213 plt.xlabel('Waveform')214 plt.ylabel('Counts')215 plt.title('Waveforms Histogram')216 plt.grid(True)217 if self._interactive:218 plt.show()219 else:220 self.savefig("fig-waveforms-hist.png")221 def waveforms_delta_hist(self, vmin=None, vmax=None, bins=128, log=False, color='green'):222 """223 Draw waveform histogram.224 :param vmin: Minimum display value225 :param vmax: Maximum display value226 :param bins: Number of bins227 :param log: Show logarithms of bin counts228 """229 vmin = vmin if vmin else self._comparator.waveforms_delta_range[0]230 vmax = vmax if vmax else self._comparator.waveforms_delta_range[1]231 vmax = vmin + 1 if vmin == vmax else vmax232 plt.figure(figsize=(12, 6))233 plt.hist(self._comparator.waveforms_delta.flatten(),234 range=(vmin, vmax),235 bins=bins,236 log=log,237 facecolor=color,238 alpha=1,239 normed=True)240 plt.xlabel('Waveforms Delta')241 plt.ylabel('Counts')242 plt.title('Waveforms Delta Histogram')243 plt.grid(True)244 if self._interactive:245 plt.show()246 else:247 self.savefig("fig-waveforms_delta-hist.png")248 def waveforms_scatter(self, vmin=None, vmax=None):249 vmin = vmin if vmin else self._comparator.waveforms_delta_range[0]250 vmax = vmax if vmax else self._comparator.waveforms_delta_range[1]251 vmax = vmin + 1 if vmin == vmax else vmax252 x = self._comparator.p1.waveform253 y = self._comparator.p2.waveform254 plt.figure(figsize=(12, 6))255 plt.axis([vmin, vmax, vmin, vmax])256 plt.scatter(x, y, alpha=0.3, edgecolors='none')257 plt.xlabel('Waveform 1')258 plt.ylabel('Waveform 2')259 plt.title('Waveforms Scatter Plot')260 plt.grid(True)261 if self._interactive:262 plt.show()263 else:264 self.savefig("fig-waveforms-scatter.png")265 def waveforms_hexbin(self, vmin=None, vmax=None, cmap='Blues', log=True):266 vmin = vmin if vmin else self._comparator.waveforms_delta_range[0]267 vmax = vmax if vmax else self._comparator.waveforms_delta_range[1]268 vmax = vmin + 1 if vmin == vmax else vmax269 x = self._comparator.p1.waveform.flatten()270 y = self._comparator.p2.waveform.flatten()271 plt.figure(figsize=(12, 6))272 plt.hexbin(x, y, cmap=cmap, bins='log' if log else None)273 plt.axis([vmin, vmax, vmin, vmax])274 plt.xlabel('Waveform 1')275 plt.ylabel('Waveform 2')276 plt.title('Waveforms Delta Hexagon Binning')277 plt.grid(True)278 cb = plt.colorbar()279 cb.set_label('log10(Counts)' if log else 'Counts')280 if self._interactive:281 plt.show()282 else:283 self.savefig("fig-waveforms-hexbin.png")284 def savefig(self, filename):285 return self._figure_writer.savefig(filename)286 def close(self):287 if self._figure_writer:...
test_action_condition.py
Source:test_action_condition.py
1# -*- coding: utf-8; -*-2# Copyright (C) 2015 - 2022 Lionel Ott3#4# This program is free software: you can redistribute it and/or modify5# it under the terms of the GNU General Public License as published by6# the Free Software Foundation, either version 3 of the License, or7# (at your option) any later version.8#9# This program is distributed in the hope that it will be useful,10# but WITHOUT ANY WARRANTY; without even the implied warranty of11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12# GNU General Public License for more details.13#14# You should have received a copy of the GNU General Public License15# along with this program. If not, see <http://www.gnu.org/licenses/>16import sys17from gremlin import event_handler18sys.path.append(".")19import pytest20import uuid21from xml.etree import ElementTree22import gremlin.error as error23import gremlin.types as types24import gremlin.profile_library as profile_library25import gremlin.util as util26import action_plugins.condition as condition27def test_from_xml():28 c = condition.ConditionModel(29 profile_library.ActionTree(),30 types.InputType.JoystickButton31 )32 c.from_xml(ElementTree.fromstring(open("test/action_condition_simple.xml").read()))33 assert len(c._conditions) == 134 assert c._logical_operator == condition.LogicalOperator.All35 assert c.is_valid()36 assert len(c._conditions[0]._inputs) == 137 cond = c._conditions[0]38 assert isinstance(cond, condition.JoystickCondition)39 assert isinstance(cond._comparator, condition.comparator.PressedComparator)40 assert cond._inputs[0].event_type == types.InputType.JoystickButton41 assert cond._comparator.is_pressed == False42 assert cond.is_valid()43def test_from_xml_complex():44 c = condition.ConditionModel(45 profile_library.ActionTree(),46 types.InputType.JoystickButton47 )48 c.from_xml(ElementTree.fromstring(open("test/action_condition_complex.xml").read()))49 # General information50 assert len(c._conditions) == 451 assert c._logical_operator == condition.LogicalOperator.Any52 assert c.is_valid()53 # Input item data54 assert len(c._conditions[0]._inputs) == 255 in1 = c._conditions[0]._inputs[0]56 assert in1.event_type == types.InputType.JoystickButton57 assert in1.identifier == 258 assert in1.device_guid == util.parse_guid("4DCB3090-97EC-11EB-8003-444553540000")59 in2 = c._conditions[0]._inputs[1]60 assert in2.event_type == types.InputType.JoystickButton61 assert in2.identifier == 4262 assert in2.device_guid == util.parse_guid("4DCB3090-97EC-11EB-8003-444553540024")63 in3 = c._conditions[2]._inputs[0]64 assert in3.event_type == types.InputType.JoystickHat65 assert in3.identifier == 166 assert in3.device_guid == util.parse_guid("4DCB3090-97EC-11EB-8003-444553540000")67 in4 = c._conditions[3]._inputs[0]68 in4.scan_code = 4269 in4.is_extended = True70 # Condition data71 assert len(c._conditions[0]._inputs) == 272 c1 = c._conditions[0]73 assert isinstance(c1, condition.JoystickCondition)74 assert isinstance(c1._comparator, condition.comparator.PressedComparator)75 assert c1._inputs[0].event_type == types.InputType.JoystickButton76 assert c1._comparator.is_pressed == False77 assert c1.is_valid()78 c2 = c._conditions[1]79 assert isinstance(c2, condition.JoystickCondition)80 assert isinstance(c2._comparator, condition.comparator.RangeComparator)81 assert c2._inputs[0].event_type == types.InputType.JoystickAxis82 assert c2._comparator.lower == 0.283 assert c2._comparator.upper == 0.984 assert c2.is_valid()85 c3 = c._conditions[2]86 assert isinstance(c3, condition.JoystickCondition)87 assert isinstance(c3._comparator, condition.comparator.DirectionComparator)88 assert c3._inputs[0].event_type == types.InputType.JoystickHat89 assert len(c3._comparator.directions) == 390 assert c3._comparator.directions[0] == types.HatDirection.North91 assert c3._comparator.directions[1] == types.HatDirection.East92 assert c3._comparator.directions[2] == types.HatDirection.NorthEast93 c4 = c._conditions[3]94 assert isinstance(c4, condition.KeyboardCondition)95 assert isinstance(c4._comparator, condition.comparator.PressedComparator)96 assert c4._comparator.is_pressed == False97def test_to_xml():98 c = condition.ConditionModel(99 profile_library.ActionTree(),100 types.InputType.JoystickButton101 )102 cond = condition.JoystickCondition()103 input_dev = event_handler.Event(104 types.InputType.JoystickButton,105 37,106 util.parse_guid("4DCB3090-97EC-11EB-8003-444553540000")107 )108 cond._inputs.append(input_dev)109 cond._comparator = condition.comparator.PressedComparator(True)110 c._conditions.append(cond)111 node = c.to_xml()112 assert node.find(113 "./property/name[.='logical-operator']/../value"114 ).text == "all"115 assert node.find(116 "./condition/property/name[.='condition-type']/../value"117 ).text == "joystick"118 assert node.find(119 "./condition/input/property/name[.='input-type']/../value"120 ).text == "button"121 assert node.find(122 "./condition/comparator/property/name[.='is-pressed']/../value"123 ).text == "True"124def test_ctor():125 c = condition.ConditionModel(126 profile_library.ActionTree(),127 types.InputType.JoystickButton128 )129 assert len(c._conditions) == 0130 assert c._logical_operator == condition.LogicalOperator.All...
test_attr_comparator.py
Source:test_attr_comparator.py
1from unittest import TestCase2from xmlscomparator.comparators.attr_comparator import AttrComparator3from xmlscomparator.comparators.attr_comparator_policy import AttrComparatorPolicy4from unittest.mock import Mock5from tests import logging_configuration as lc678class TestAttrComparator(TestCase):9 def setUp(self):10 self._comparator = AttrComparator(lc.get_logger('attr'))1112 def test_compare_different_attr_len(self):13 _left_element = Mock(attrib={'a': 1, 'b': 2})14 _right_element = Mock(attrib={'a': 1, 'b': 2, 'c': 3})15 self.assertFalse(self._comparator.compare(16 _left_element, _right_element))1718 def test_compare_different_keys_when_equal_attr_len(self):19 _left_element = Mock(attrib={'a': 1, 'b': 2, 'd': 3})20 _right_element = Mock(attrib={'a': 1, 'b': 2, 'c': 3})21 self.assertFalse(self._comparator.compare(22 _left_element, _right_element))2324 def test_compare_different_values_when_equal_keys_with_no_value_chek(self):25 _left_element = Mock(attrib={'a': 1, 'b': 2, 'c': 3})26 _right_element = Mock(attrib={'a': 1, 'b': 2, 'c': 4})27 self._comparator.set_check_values(False)28 self.assertTrue(self._comparator.compare(29 _left_element, _right_element))3031 def test_compare_different_values_when_equal_keys_with_value_chek(self):32 _left_element = Mock(attrib={'a': 1, 'b': 2, 'c': 3})33 _right_element = Mock(attrib={'a': 1, 'b': 2, 'c': 4})34 self._comparator.set_check_values(True)35 self.assertFalse(self._comparator.compare(36 _left_element, _right_element))3738 def test_compare_the_same_values_when_equal_keys_with_value_chek(self):39 _left_element = Mock(attrib={'a': 1, 'b': 2, 'c': 4})40 _right_element = Mock(attrib={'a': 1, 'b': 2, 'c': 4})41 self._comparator.set_check_values(True)42 self.assertTrue(self._comparator.compare(43 _left_element, _right_element))4445 def test_compare_with_comparator_policy(self):46 _left_element = Mock(attrib={'a': 3, 'b': 2, 'c': 4})47 _right_element = Mock(attrib={'b': 2, 'd': 6, 'c': 4})48 _policy = AttrComparatorPolicy(lc.get_logger('attrPolicy'))49 _policy.add_attribute_name_to_compare('b')50 _policy.add_attribute_name_to_compare('c')51 self._comparator.set_check_values(True)52 self._comparator.set_attr_comparator_policy(_policy)5354 self.assertTrue(self._comparator.compare(
...
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!!