How to use filtered_strategy method in hypothesis

Best Python code snippet using hypothesis

draw_plots.py

Source:draw_plots.py Github

copy

Full Screen

1#!/usr/bin/env python32import numpy as np3import matplotlib as mpl4import matplotlib.pyplot as plt5import scipy.stats6from math import sqrt7import operator8BASE_PATH = "data/"9PLOTS_PATH = "plots/"10DATA_INDEX = 211DEFAULT_INDEX = 312KNN_INDEX = 413LINEAR_INDEX = 514LOGISTIC_INDEX = 615TREE_INDEX = 716FOREST_INDEX = 817XMEANS_INDEX = 918DEFAULT_PARTITIONS_INDEX = 1119XMEANS_PARTITIONS_INDEX = 1720DELTA_PARTITIONS = DEFAULT_PARTITIONS_INDEX - DEFAULT_INDEX21def select_strategy(data):22 results = []23 for line in data:24 base = line[DATA_INDEX]25 best = None26 best_partitions = 027 besti = 028 for i in range(DEFAULT_PARTITIONS_INDEX,XMEANS_PARTITIONS_INDEX+1):29 current = line[i - DELTA_PARTITIONS]30 current_partitions = line[i]31 if current_partitions > 0:32 if not best or best > current:33 best = current34 best_partitions = current_partitions35 besti = i36 results.append((base, best, besti - DELTA_PARTITIONS, line[0]))37 return results38def stats(filtered_strategy):39 a = [x[0] for x in filtered_strategy]40 b = [x[1] for x in filtered_strategy]41 ab = [x[0]-x[1] for x in filtered_strategy]42 print(scipy.stats.shapiro(a), np.mean(a), np.median(a), np.var(a))43 print(scipy.stats.shapiro(b), np.mean(b), np.median(b), np.var(b))44 print(scipy.stats.wilcoxon(ab))45 print(scipy.stats.norm.isf(5e-8 / 2))46def filter_partitions(data):47 return [x for x in data if sum(x[DEFAULT_PARTITIONS_INDEX:XMEANS_PARTITIONS_INDEX]) > 0]48def count_against_base(data, index=None):49 count = 050 totals = [0,0,0]51 for line in data:52 counts = [0,0,0]53 for idx in range(DEFAULT_INDEX,XMEANS_INDEX+1):54 if index and idx != index:55 continue56 if line[DATA_INDEX] < line[idx]:57 counts[0] = 158 elif line[DATA_INDEX] == line[idx]:59 counts[1] = 160 else:61 counts[2] = 162 break63 if counts[2] != 0:64 totals[2] += 165 elif counts[1] != 0:66 totals[1] += 167 else:68 totals[0] += 169 return totals70def do_line_plot(data):71 mpl.rcParams['figure.figsize'] = (11, 6)72 ab = sorted([(x[0]-x[1], x[-1]) for x in data], key=operator.itemgetter(0))73 closure_ab = ([(x+1,y) for x,(y,z) in enumerate(ab) if z == "Closure"], "o", "0.12", "Closure")74 lang_ab = ([(x+1,y) for x,(y,z) in enumerate(ab) if z == "Lang"], "o", "0.55", "Commons Lang")75 math_ab = ([(x+1,y) for x,(y,z) in enumerate(ab) if z == "Math"], "o", "0.95", "Commons Math")76 chart_ab = ([(x+1,y) for x,(y,z) in enumerate(ab) if z == "Chart"], "^", "0.12", "JFreeChart")77 time_ab = ([(x+1,y) for x,(y,z) in enumerate(ab) if z == "Time"], "^", "0.55", "JodaTime")78 mockito_ab = ([(x+1,y) for x,(y,z) in enumerate(ab) if z == "Mockito"], "^", "0.95", "Mockito")79 fig, ax = plt.subplots()80 ax.set_axisbelow(True)81 plt.grid(True, color='0.75')82 for cat, marker, c, label in [closure_ab, lang_ab, math_ab, chart_ab, time_ab, mockito_ab]:83 plt.scatter([x[0] for x in cat], [x[1] for x in cat], c=c, lw=0.5,s=50, marker=marker, edgecolor="0", label=label, zorder=2)84 ax.set_yscale('symlog')85 ax.set_ylim([-200,1000])86 ax.set_xlim([0,len(ab)+2])87 plt.ylabel("$\Delta{}C_d$")88 plt.xlabel("Subject Number")89 plt.legend(scatterpoints=1,90 loc='lower right',91 fontsize="10")92 ax.axvline(15.5, lw=1.5, color='red',ls='--', zorder=1)93 ax.axvline(77.5, lw=1.5, color='green',ls='--', zorder=1)94 ax.axvspan(0, 15.5, alpha=0.11, color='red', zorder=0)95 ax.axvspan(77.5, len(ab)+2, alpha=0.11, color='green', zorder=0)96 ax.annotate('$\Delta{}C_d \geq 0$', xy=(15.25, 300), xycoords='data',97 xytext=(18, -3), textcoords='offset points',98 arrowprops=dict(arrowstyle="<-"), size=10,99 bbox=dict(boxstyle="square", pad=0, alpha=0)100 )101 ax.annotate('$\Delta{}C_d < 0$', xy=(15.5, 500), xycoords='data',102 xytext=(-55, -3), textcoords='offset points',103 arrowprops=dict(arrowstyle="<-"), size=10,104 bbox=dict(boxstyle="square", pad=0, alpha=0)105 )106 ax.annotate('$\Delta{}C_d > 0$', xy=(77.25, 300), xycoords='data',107 xytext=(18, -3), textcoords='offset points',108 arrowprops=dict(arrowstyle="<-"), size=10,109 bbox=dict(boxstyle="square", pad=0, alpha=0)110 )111 ax.annotate('$\Delta{}C_d \leq 0$', xy=(77.5, 500), xycoords='data',112 xytext=(-55, -3), textcoords='offset points',113 arrowprops=dict(arrowstyle="<-"), size=10,114 bbox=dict(boxstyle="square", pad=0, alpha=0)115 )116 plt.tight_layout()117 plt.savefig(PLOTS_PATH + "delta-cd.pdf", bbox_inches="tight")118def do_plot(results, my_xticks, filename, xlabel='', ylabel='', title=''):119 # data to plot120 n_groups = len(results)121 #results = count_against_base(data)122 results_better = [x[0] for x in results]123 results_same = [x[1] for x in results]124 results_worse = [x[2] for x in results]125 # create plot126 fig, ax = plt.subplots()127 ax.set_axisbelow(True)128 ax.yaxis.grid(True, color="0.85")129 index = np.arange(n_groups)130 bar_width = 0.275131 opacity = 0.8132 rects1 = plt.bar(index, results_better, bar_width,133 color='0.35', lw=1, edgecolor="0",134 label='$\Delta{}C_d$ < 0')135 rects2 = plt.bar(index + bar_width, results_same, bar_width,136 color='0.65', lw=1, edgecolor="0",137 label='$\Delta{}C_d$ = 0')138 rects3 = plt.bar(index + bar_width + bar_width, results_worse, bar_width,139 color='0.95', lw=1, edgecolor="0",140 label='$\Delta{}C_d$ > 0')141 plt.xlabel(xlabel)142 plt.ylabel(ylabel)143 plt.xticks(index + 1.5*bar_width, my_xticks)144 plt.legend(fontsize="12")145 plt.tight_layout()146 plt.savefig(PLOTS_PATH + filename, bbox_inches="tight")147if __name__ == "__main__":148 data = []149 for f in ["Closure.csv", "Lang.csv", "Math.csv", "Chart.csv","Time.csv","Mockito.csv"]:150 with open(BASE_PATH + f) as projectfile:151 for index, line in enumerate(projectfile):152 if index==0:153 continue154 line = line.rstrip().split(",")155 for x in range(2,len(line)):156 line[x] = float(line[x])157 data.append(line)158 data = filter_partitions(data)159 fstrat = select_strategy(data)160 #stats(fstrat)161 results = [count_against_base(data, DEFAULT_INDEX),162 count_against_base(data, XMEANS_INDEX),163 count_against_base(data, KNN_INDEX),164 count_against_base(data, LINEAR_INDEX),165 count_against_base(data, LOGISTIC_INDEX),166 count_against_base(data, TREE_INDEX),167 count_against_base(data, FOREST_INDEX)168 ]169 do_plot(results, ['Sign','X-means', 'k-NN','Linear', 'Logistic', 'Tree', 'Forest'],170 'per-strategy.pdf', xlabel='Strategies',ylabel='# Subjects',171 title='Effort vs Base: All Projects')...

Full Screen

Full Screen

gc_spyu.py

Source:gc_spyu.py Github

copy

Full Screen

1#!/usr/bin/env python32from gc_spyu import spyu3from gc_spyu import utils4from gc_spyu.view.on_run_conclusion import on_run_conclusion5import debug6import pprint7if __name__ == "__main__":8 debug.dlog("starting")9 spyu_ctx = spyu.spyuCTX()10 utils.run_golem_example(spyu_ctx())11 mySummaryLogger, nodeInfoIds, myModel = spyu_ctx.get_results()12 merged_list = mySummaryLogger.providersFailed13 merged_list.extend(mySummaryLogger.skipped)14 debug.dlog(f"merged_list: {merged_list}")15 if len(merged_list) > 0:16 msg = (17 "The following providers were skipped because they were"18 " unreachable or otherwise uncooperative:"19 )20 print(f"\n{msg}")21 print("-" * (len(msg) - 1))22 merged_pairs = set()23 for dict_ in merged_list:24 merged_pairs.add(25 (26 dict_["name"],27 dict_["address"],28 )29 )30 for name, address in merged_pairs:31 print(f"{name}@{address}")32 print("-" * (len(msg) - 1))33 if len(spyu_ctx.filtered_strategy.lowscored) > 0:34 msg = (35 "The following providers were skipped because they failed"36 " the scoring criteria:"37 )38 print(f"\n{msg}")39 print("-" * (len(msg) - 1))40 for low in spyu_ctx.filtered_strategy.lowscored:41 print(f"{low}")42 print("-" * (len(msg) - 1))43 if len(spyu_ctx.filtered_strategy.whitelist) > 0:44 msg = (45 "The following providers were skipped because they were not"46 " seen on the network:"47 )48 print(f"\n{msg}")49 print("-" * (len(msg) - 1))50 for unseen in spyu_ctx.filtered_strategy.whitelist:51 print(f"{unseen}")52 print("-" * (len(msg) - 1))53 print(54 "\n\033[0;32mTotal glm spent from all engine runs: \033[1m"55 + str(mySummaryLogger.sum_invoices())56 + "\033[0m"57 )58 if isinstance(nodeInfoIds, list) and (59 len(nodeInfoIds) > 0 or len(spyu_ctx.filtered_strategy.dupIds) > 060 ):61 try:62 on_run_conclusion(63 mySummaryLogger, nodeInfoIds, myModel, spyu_ctx.filtered_strategy.dupIds64 )65 except KeyboardInterrupt:...

Full Screen

Full Screen

Strategy.py

Source:Strategy.py Github

copy

Full Screen

1import numpy as np2from numpy import ndarray3class Strategy:4 @classmethod5 def random(cls, size: int):6 return np.ones(size)7 @classmethod8 def normalize(cls, strategy: ndarray, _filter: ndarray = None, frequencies: ndarray = None):9 if _filter is None:10 _filter = np.ones(len(strategy))11 filtered_strategy = strategy * _filter12 normalizing_sum = sum(filtered_strategy)13 if normalizing_sum == 0:14 return np.zeros(len(strategy))15 return filtered_strategy / normalizing_sum16 @classmethod17 def from_utility(cls, strategy: ndarray, utilities: ndarray):18 return np.array([s_val if r_val <= 019 else r_val if s_val == 120 else (r_val + s_val) / 221 for idx, (s_val, r_val) in enumerate(zip(strategy, utilities))])22 # @classmethod23 # def from_regrets(cls, strategy: ndarray, regrets: ndarray):24 # return np.array([s_val if r_val <= 025 # else r_val if s_val == 126 # else (r_val + s_val) / 2...

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