How to use all_filtered method in hypothesis

Best Python code snippet using hypothesis

business_logic.py

Source:business_logic.py Github

copy

Full Screen

1import pandas as pd2import numpy as np3import datetime4import helper_methods as helpers5from dateutil import relativedelta6from custom_exceptions import NoLeftOperandInPercentage7from chatbot.models import MONTH_NAMES8# class for storing all complex business logic9# All methods should be class method and a data frame as parameter10class BusinessLogic:11 def __init__(self, dimensions, fact_condition, date_condition, dim_filters):12 self.dimensions = dimensions13 self.fact_condition = fact_condition14 self.agg = fact_condition['aggregation']15 self.dim_filters = dim_filters16 self.date_condition = date_condition17 self.start_date = datetime.datetime.today()18 self.end_date = datetime.datetime.strptime('2000-01-01', '%Y-%m-%d')19 for cond in date_condition:20 # Use max date in date_condition for end date and min for start date21 date = datetime.datetime.strptime(cond['CalendarDate'], '%Y-%m-%d')22 if date < self.start_date:23 self.start_date = date24 if date > self.end_date:25 self.end_date = date26 # self.curr_month = self.date.month27 # self.curr_year = self.date.year28 # self.curr_quarter = (self.curr_month - 1) // 3 + 129 # self.last_month = 12 if self.curr_month - 1 == 0 else self.curr_month - 130 # self.last_quarter = 4 if self.curr_quarter - 1 == 0 else self.curr_quarter - 131 # self.last_year = self.curr_year - 132 # self.last_month_year = self.last_year if self.curr_month - 1 == 0 else self.curr_year33 # self.last_qtr_year = self.last_year if self.curr_quarter - 1 == 0 else self.curr_year34 # # Append Q to quarter after creating last qtr and last qtr year35 # self.curr_quarter = "Q" + str(self.curr_quarter)36 # self.last_quarter = "Q" + str(self.last_quarter)37 def mom_facts(self, df):38 if self.dim_filters:39 df = helpers.apply_dim_filters(df, dim_filters=self.dim_filters)40 final_df = pd.DataFrame()41 s_date = self.start_date42 e_date = self.end_date43 if e_date.strftime('%Y-%m-%d') > df['CalendarDate'].max():44 e_date = datetime.datetime.strptime(df['CalendarDate'].max(), '%Y-%m-%d')45 r = relativedelta.relativedelta(e_date, s_date)46 n_months = r.years * 12 + r.months47 # if there is no date or same date then make mom for last 6 months48 if n_months < 1:49 n_months = 650 e_date = datetime.datetime.now()51 s_date = e_date - relativedelta.relativedelta(months=6)52 # show 1 extra month for current month53 for month in range(n_months + 1):54 curr_month_year = MONTH_NAMES[s_date.month]['ShortMonthName'] + '-' + str(s_date.year)55 prev_month_year = helpers.get_prev_month_year(curr_month_year)56 curr_month_facts = helpers.safe_groupby(df[df['MonthYear'] == curr_month_year], self.dimensions + [57 'MonthYear'], self.agg)58 last_month_facts = helpers.safe_groupby(df[df['MonthYear'] == prev_month_year], self.dimensions + [59 'MonthYear'], self.agg)60 if not last_month_facts.empty:61 last_month_facts.index = curr_month_facts.index62 mom_facts = (curr_month_facts / last_month_facts).fillna(63 0) if last_month_facts.empty else 100 * curr_month_facts / last_month_facts64 mom_facts = mom_facts.add_prefix("% MOM ")65 final_df = final_df.append(pd.concat([curr_month_facts, mom_facts], axis=1, sort=False))66 s_date = s_date + relativedelta.relativedelta(months=1)67 # curr_month_facts = curr_month_facts.add_prefix(MONTH_NAMES[self.curr_month] + '-' + str(self.curr_year) + " ")68 # last_month_facts = last_month_facts.add_prefix(MONTH_NAMES[self.last_month] + '-' + str(self.last_month_year) + " ")69 # return pd.concat([curr_month_facts, last_month_facts, mom_facts], axis=1, sort=False)70 return final_df71 def qoq_facts(self, df):72 if self.dim_filters:73 df = helpers.apply_dim_filters(df, dim_filters=self.dim_filters)74 final_df = pd.DataFrame()75 s_date = self.start_date76 e_date = self.end_date77 n_qtr = helpers.get_n_quarters(e_date, s_date)78 # if there is no date or same date then make qoq for last 4 quarters79 if n_qtr < 1:80 n_qtr = 481 e_date = datetime.datetime.now()82 s_date = e_date - relativedelta.relativedelta(months=n_qtr * 3)83 # use 1 extra quarter to show current quarter facts alse84 for qtr in range(n_qtr + 1):85 curr_qtr_year = MONTH_NAMES[s_date.month]['QtrName'] + '-' + str(s_date.year)86 prev_qtr_year = helpers.get_prev_qtr_year(curr_qtr_year)87 curr_qtr_facts = helpers.safe_groupby(df[df['QuarterYear'] == curr_qtr_year], self.dimensions + [88 'QuarterYear'], self.agg)89 last_qtr_facts = helpers.safe_groupby(df[df['QuarterYear'] == prev_qtr_year], self.dimensions + [90 'QuarterYear'], self.agg)91 if not last_qtr_facts.empty:92 last_qtr_facts.index = curr_qtr_facts.index93 qoq_facts = (curr_qtr_facts / last_qtr_facts).fillna(94 0) if last_qtr_facts.empty else 100 * curr_qtr_facts / last_qtr_facts95 qoq_facts = qoq_facts.add_prefix("% QOQ ")96 final_df = final_df.append(pd.concat([curr_qtr_facts, qoq_facts], axis=1, sort=False))97 s_date = s_date + relativedelta.relativedelta(months=3)98 return final_df99 def yoy_fact(self, df):100 if self.dim_filters:101 df = helpers.apply_dim_filters(df, dim_filters=self.dim_filters)102 final_df = pd.DataFrame()103 s_date = self.start_date104 e_date = self.end_date105 n_year = relativedelta.relativedelta(e_date, s_date).years106 # if there is no date or same date then make yoy for last 3 years107 if n_year < 1:108 n_year = 3109 e_date = datetime.datetime.now()110 s_date = e_date - relativedelta.relativedelta(years=3)111 # add 1 to show current year sales also112 for year in range(n_year + 1):113 curr_year = s_date.year114 prev_year = curr_year - 1115 curr_year_facts = helpers.safe_groupby(df[df['Year'] == curr_year], self.dimensions + [116 'Year'], self.agg)117 last_year_facts = helpers.safe_groupby(df[df['Year'] == prev_year], self.dimensions + [118 'Year'], self.agg)119 if not last_year_facts.empty:120 last_year_facts.index = curr_year_facts.index121 yoy_facts = (curr_year_facts / last_year_facts).fillna(122 0) if last_year_facts.empty else 100 * curr_year_facts / last_year_facts123 yoy_facts = yoy_facts.add_prefix("% YoY ")124 final_df = final_df.append(pd.concat([curr_year_facts, yoy_facts], axis=1, sort=False))125 s_date = s_date + relativedelta.relativedelta(years=1)126 return final_df127 def mtd(self, df):128 if self.dim_filters:129 df = helpers.apply_dim_filters(df, dim_filters=self.dim_filters)130 # get max date from the user query for mtd131 date = self.end_date if self.end_date > self.start_date else self.start_date132 curr_month_year = MONTH_NAMES[date.month]['ShortMonthName'] + '-' + str(date.year)133 mtd_facts = helpers.safe_groupby(df[(df['MonthYear'] == curr_month_year) & (134 df['CalendarDate'] <= date.strftime("%Y-%m-%d"))], self.dimensions, self.agg)135 mtd_facts = mtd_facts.add_prefix(136 date.replace(day=1).strftime("%Y-%m-%d") + ' to ' + date.strftime("%Y-%m-%d") + " ")137 return mtd_facts138 def qtd(self, df):139 if self.dim_filters:140 df = helpers.apply_dim_filters(df, dim_filters=self.dim_filters)141 # get max date from the user query for qtd142 date = self.end_date if self.end_date > self.start_date else self.start_date143 curr_qtr_year = MONTH_NAMES[date.month]['QtrName'] + '-' + str(date.year)144 qtd_facts = helpers.safe_groupby(df[(df['QuarterYear'] == curr_qtr_year) & (145 df['CalendarDate'] <= date.strftime("%Y-%m-%d"))], self.dimensions, self.agg)146 qtr_first_date = datetime.datetime(date.year, (3 * int(MONTH_NAMES[date.month]['QtrName'][1:]) - 2), 1)147 qtd_facts = qtd_facts.add_prefix(148 qtr_first_date.strftime("%Y-%m-%d") + ' to ' + date.strftime("%Y-%m-%d") + " ")149 return qtd_facts150 def ytd(self, df):151 if self.dim_filters:152 df = helpers.apply_dim_filters(df, dim_filters=self.dim_filters)153 # get max date from the user query for ytd154 date = self.end_date if self.end_date > self.start_date else self.start_date155 ytd_facts = helpers.safe_groupby(df[(df['Year'] == date.year) & (156 df['CalendarDate'] <= date.strftime("%Y-%m-%d"))], self.dimensions, self.agg)157 ytd_facts = ytd_facts.add_prefix(158 date.replace(day=1, month=1).strftime("%Y-%m-%d") + ' to ' + date.strftime("%Y-%m-%d") + " ")159 return ytd_facts160 def target_achievement(self, df):161 fact_condition = self.fact_condition.copy()162 if self.dim_filters:163 df = helpers.apply_dim_filters(df, dim_filters=self.dim_filters)164 if self.date_condition:165 df = helpers.apply_date_condition(df, self.date_condition)166 # add Sales in Aggregation167 if 'SalesAmount' not in fact_condition['aggregation']:168 fact_condition['aggregation']['SalesAmount'] = ['sum']169 fact_condition['conditions'] += [170 {'fact_name': 'SalesAmount sum', 'conditions': np.nan, 'fact_value': np.nan}]171 # add Target Amount in Aggregation172 if 'TargetAmount' not in fact_condition['aggregation']:173 fact_condition['aggregation']['TargetAmount'] = fact_condition['aggregation']['SalesAmount']174 fact_condition['conditions'] += [175 {'fact_name': 'TargetAmount sum', 'conditions': np.nan, 'fact_value': np.nan}]176 # add sum to sales Amount177 if 'sum' not in fact_condition['aggregation']['SalesAmount']:178 fact_condition['aggregation']['SalesAmount'] += ['sum']179 fact_condition['conditions'] += [180 {'fact_name': 'SalesAmount sum', 'conditions': np.nan, 'fact_value': np.nan}]181 # Apply fact condition182 df = helpers.apply_fact_condition(df, self.dimensions + list(self.dim_filters.keys()), fact_condition)183 sale_fact_names = [c['fact_name'] for c in fact_condition['conditions'] if c['fact_name'][0:5] == 'Sales']184 target_fact_names = [c['fact_name'] for c in fact_condition['conditions'] if c['fact_name'][0:6] == 'Target']185 # target facts for 0th name186 target_facts = pd.DataFrame(100 * df[sale_fact_names[0]] / df[target_fact_names[0]])187 target_facts.columns = ["% Target Achievement"]188 # return pd.concat([df, target_facts], axis=1, sort=False)189 return target_facts190 # TODO Need to implement again for more dynamic191 def contribution(self, df):192 # Raise Error if there is no filters193 if not self.dim_filters and not self.date_condition and not self.dimensions:194 raise NoLeftOperandInPercentage(195 "Could not apply percentage without a filter! Either apply filter in dimension or date")196 all_filtered = df.copy()197 less_filtered = df.copy()198 contribution = pd.DataFrame({'Error': ["Could not applied percentage"]})199 if (self.dim_filters or self.dimensions) and self.date_condition:200 # Do not filter lowest level dimension201 all_filtered = helpers.apply_dim_filters(all_filtered, dim_filters=self.dim_filters)202 all_filtered = helpers.apply_date_condition(all_filtered, self.date_condition)203 less_filtered = helpers.apply_date_condition(less_filtered, self.date_condition)204 all_filtered = helpers.apply_fact_condition(all_filtered, self.dimensions, self.fact_condition)205 less_filtered = helpers.apply_fact_condition(less_filtered, self.dimensions[1:], self.fact_condition)206 contribution = 100 * all_filtered / less_filtered.iloc[0]207 contribution = contribution.add_prefix("% ")208 elif len(self.dim_filters.keys()) == 1 or self.dimensions:209 # Do not filter lowest level dimension210 less_dim_filters = {k: v for k, v in self.dim_filters.items() if k != list(self.dim_filters.keys())[0]}211 all_filtered = helpers.apply_dim_filters(all_filtered, dim_filters=self.dim_filters)212 less_filtered = helpers.apply_dim_filters(less_filtered, dim_filters=less_dim_filters)213 all_filtered = helpers.apply_fact_condition(all_filtered, self.dimensions, self.fact_condition)214 less_filtered = helpers.apply_fact_condition(less_filtered, self.dimensions[1:], self.fact_condition)215 contribution = 100 * all_filtered / less_filtered.iloc[0]216 contribution = contribution.add_prefix("% ")217 elif len(self.dim_filters.keys()) > 1:218 # Do not filter lowest level dimension219 less_dim_filters = {k: v for k, v in self.dim_filters.items() if k != list(self.dim_filters.keys())[0]}220 all_filtered = helpers.apply_dim_filters(all_filtered, dim_filters=self.dim_filters)221 less_filtered = helpers.apply_dim_filters(less_filtered, dim_filters=less_dim_filters)222 all_filtered = helpers.apply_fact_condition(all_filtered, self.dimensions, self.fact_condition)223 less_filtered = helpers.apply_fact_condition(less_filtered, self.dimensions[1:], self.fact_condition)224 contribution = 100 * all_filtered / less_filtered225 contribution = contribution.add_prefix("% ")226 elif self.date_condition:227 # Do not filter first level date228 less_date_filters = self.date_condition[1:]229 more_date_filters = self.date_condition[0:1]230 if not len(self.date_condition) % 2:231 less_date_filters = self.date_condition[2:]232 more_date_filters = self.date_condition[0:2]233 all_filtered = helpers.apply_date_condition(all_filtered, more_date_filters)234 less_filtered = helpers.apply_date_condition(less_filtered, less_date_filters)235 all_filtered = helpers.apply_fact_condition(all_filtered, self.dimensions, self.fact_condition)236 less_filtered = helpers.apply_fact_condition(less_filtered, self.dimensions[1:], self.fact_condition)237 contribution = 100 * all_filtered / less_filtered238 contribution = contribution.add_prefix("% ")...

Full Screen

Full Screen

gaussian_filter_factory.py

Source:gaussian_filter_factory.py Github

copy

Full Screen

1'''2Created on Jun 19, 20133@author: Simon4'''5from algorithms.AbstractAlgorithmFactory import AbstractAlgorithmFactory6from algorithms.image.gaussian_filter import GaussianFilter7class GaussianFilterFactory(AbstractAlgorithmFactory):8 '''9 Factory class for Linear Regression.10 Provides the functionalities specified by the AbstractAlgorithmClass.11 '''12 def __init__(self, sigma):13 '''14 Constructor15 '''16 self.sigma = sigma17 18 def get_instance(self):19 '''20 Create a Gaussian filter21 :return: Object implementing AbstractAlgorithm22 '''23 gaussian_filter = GaussianFilter(self.sigma)24 return gaussian_filter25 def aggregate(self, algs):26 '''27 Aggregates a list of GaussianFilter instances.28 :param algs list of algorithm instances29 :return same as input30 '''31 all_filtered = []32 for f in algs:33 all_filtered.extend(f.filtered)34 gaussian_filter = GaussianFilter(self.sigma)35 gaussian_filter.filtered = all_filtered36 return gaussian_filter37 38 def encode(self, alg_instance):39 return alg_instance.filtered40 41 def decode(self, encoded):42 deserialized = []43 for f in encoded:44 # create new algorithm object45 gauss_filter = GaussianFilter(self.sigma)46 gauss_filter.set_params(f)47 # append to list of algorithm objetcs48 deserialized.append(gauss_filter)...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run hypothesis automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful