Best Python code snippet using assertpy_python
deciles_charts.py
Source:deciles_charts.py
1import argparse2import glob3import json4import logging5import pathlib6import re7import jsonschema8import numpy9import pandas10from ebmdatalab import charts11# replicate cohort-extractor's logging12logger = logging.getLogger(__name__)13logger.setLevel(logging.INFO)14handler = logging.StreamHandler()15handler.setFormatter(16 logging.Formatter(17 fmt="%(asctime)s [%(levelname)-9s] %(message)s [%(module)s]",18 datefmt="%Y-%m-%d %H:%M:%S",19 )20)21logger.addHandler(handler)22DEFAULT_CONFIG = {23 "show_outer_percentiles": False,24 "tables": {25 "output": True,26 },27 "charts": {28 "output": True,29 },30}31CONFIG_SCHEMA = {32 "type": "object",33 "additionalProperties": False,34 "properties": {35 "show_outer_percentiles": {"type": "boolean"},36 "tables": {37 "type": "object",38 "additionalProperties": False,39 "properties": {40 "output": {"type": "boolean"},41 },42 },43 "charts": {44 "type": "object",45 "additionalProperties": False,46 "properties": {47 "output": {"type": "boolean"},48 },49 },50 },51}52MEASURE_FNAME_REGEX = re.compile(r"measure_(?P<id>\w+)\.csv")53def get_measure_tables(input_files):54 for input_file in input_files:55 measure_fname_match = re.match(MEASURE_FNAME_REGEX, input_file.name)56 if measure_fname_match is not None:57 measure_table = pandas.read_csv(input_file, parse_dates=["date"])58 measure_table.attrs["id"] = measure_fname_match.group("id")59 yield measure_table60def drop_zero_denominator_rows(measure_table):61 """62 Zero-denominator rows could cause the deciles to be computed incorrectly, so should63 be dropped beforehand. For example, a practice can have zero registered patients. If64 the measure is computed from the number of registered patients by practice, then65 this practice will have a denominator of zero and, consequently, a value of inf.66 Depending on the implementation, this practice's value may be sorted as greater than67 other practices' values, which may increase the deciles.68 """69 # It's non-trivial to identify the denominator column without the associated Measure70 # instance. It's much easier to test the value column for inf, which is returned by71 # Pandas when the second argument of a division operation is zero.72 is_not_inf = measure_table["value"] != numpy.inf73 num_is_inf = len(is_not_inf) - is_not_inf.sum()74 logger.info(f"Dropping {num_is_inf} zero-denominator rows")75 return measure_table[is_not_inf].reset_index(drop=True)76def get_deciles_table(measure_table, config):77 return charts.add_percentiles(78 measure_table,79 period_column="date",80 column="value",81 show_outer_percentiles=config["show_outer_percentiles"],82 )83def write_deciles_table(deciles_table, path, filename):84 create_dir(path)85 deciles_table.to_csv(path / filename, index=False)86def get_deciles_chart(measure_table, config):87 return charts.deciles_chart(88 measure_table,89 period_column="date",90 column="value",91 show_outer_percentiles=config["show_outer_percentiles"],92 )93def write_deciles_chart(deciles_chart, path, filename):94 create_dir(path)95 deciles_chart.savefig(path / filename, bbox_inches="tight")96def create_dir(path):97 pathlib.Path(path).mkdir(parents=True, exist_ok=True)98def get_path(*args):99 return pathlib.Path(*args).resolve()100def match_paths(pattern):101 return [get_path(x) for x in glob.glob(pattern)]102def parse_config(config_json):103 user_config = json.loads(config_json)104 config = DEFAULT_CONFIG.copy()105 config.update(user_config)106 try:107 jsonschema.validate(config, CONFIG_SCHEMA)108 except jsonschema.ValidationError as e:109 raise argparse.ArgumentTypeError(e.message) from e110 return config111def parse_args():112 parser = argparse.ArgumentParser()113 parser.add_argument(114 "--input-files",115 required=True,116 type=match_paths,117 help="Glob pattern for matching one or more input files",118 )119 parser.add_argument(120 "--output-dir",121 required=True,122 type=get_path,123 help="Path to the output directory",124 )125 parser.add_argument(126 "--config",127 default=DEFAULT_CONFIG.copy(),128 type=parse_config,129 help="JSON-encoded configuration",130 )131 return parser.parse_args()132def main():133 args = parse_args()134 input_files = args.input_files135 output_dir = args.output_dir136 config = args.config137 for measure_table in get_measure_tables(input_files):138 measure_table = drop_zero_denominator_rows(measure_table)139 id_ = measure_table.attrs["id"]140 if config["tables"]["output"]:141 deciles_table = get_deciles_table(measure_table, config)142 fname = f"deciles_table_{id_}.csv"143 write_deciles_table(deciles_table, output_dir, fname)144 if config["charts"]["output"]:145 chart = get_deciles_chart(measure_table, config)146 fname = f"deciles_chart_{id_}.png"147 write_deciles_chart(chart, output_dir, fname)148if __name__ == "__main__":...
numeric.pyi
Source:numeric.pyi
...5 def is_not_zero(self) -> AssertionBuilder: ...6 def is_nan(self) -> AssertionBuilder: ...7 def is_not_nan(self) -> AssertionBuilder: ...8 def is_inf(self) -> AssertionBuilder: ...9 def is_not_inf(self) -> AssertionBuilder: ...10 def is_greater_than(self, other: Any) -> AssertionBuilder: ...11 def is_greater_than_or_equal_to(self, other: Any) -> AssertionBuilder: ...12 def is_less_than(self, other: Any) -> AssertionBuilder: ...13 def is_less_than_or_equal_to(self, other: Any) -> AssertionBuilder: ...14 def is_positive(self) -> AssertionBuilder: ...15 def is_negative(self) -> AssertionBuilder: ...16 def is_between(self, low: Any, high: Any) -> AssertionBuilder: ...17 def is_not_between(self, low: Any, high: Any) -> AssertionBuilder: ...18 def is_close_to(self, other: Any, tolerance: Any) -> AssertionBuilder: ......
assertpy_floats.py
Source:assertpy_floats.py
...13assert_that(123.4).is_close_to(123, 0.5)14assert_that(float('NaN')).is_nan()15assert_that(123.4).is_not_nan()16assert_that(float('Inf')).is_inf()...
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!!