def test_pivot(): UNPIVOTED = [ dict(state="NSW", party="Pink", votes=10), dict(state="NSW", party="Orange", votes=1), dict(state="VIC", party="Pink", votes=11), dict(state="VIC", party="Orange", votes=2), dict(state="VIC", party="Yellow", votes=5), ] PIVOTED = [ { "state": "NSW", "Pink": 10, "Orange": 1, "Yellow": None }, { "state": "VIC", "Pink": 11, "Orange": 2, "Yellow": 5 }, ] r = results.Results(UNPIVOTED) pivoted = results.Results(PIVOTED) assert r.pivoted() == results.Results(PIVOTED) pivoted.replace_values(None, 0) PIVOTED[0]["Yellow"] = 0 assert pivoted == PIVOTED
def test_badcase(): BAD = [ dict(year=2015, state="NSW", party="Pink", votes=10), dict(year=2015, state="NSW", party="Orange", votes=1), dict(year=2015, state="VIC", party="Magenta", votes=3), dict(year=2018, state="VIC", party="Pink", votes=10), dict(year=2018, state="VIC", party="Magenta", votes=3), dict(year=2018, state="NSW", party="Yellow", votes=1), dict(year=2018, state="NSW", party="Orange", votes=1), ] PIVOTED = [ { "Magenta": None, "Orange": 1, "Pink": 10, "Yellow": None, "state": "NSW", "year": 2015, }, { "Magenta": 3, "Orange": None, "Pink": None, "Yellow": None, "state": "VIC", "year": 2015, }, { "Magenta": 3, "Orange": None, "Pink": 10, "Yellow": None, "state": "VIC", "year": 2018, }, { "Magenta": None, "Orange": 1, "Pink": None, "Yellow": 1, "state": "NSW", "year": 2018, }, ] pivoted = results.Results(BAD).pivoted() EXPECTED = results.Results(PIVOTED) assert pivoted == EXPECTED assert pivoted.keys() == [ "year", "state", "Pink", "Magenta", "Yellow", "Orange" ]
def test_result_object(tmpdir, sample): r = results.Results([]) assert r.keys() == [] EXPECTED_CSV = """first_name,last_name Ice,T Ice,Cube , """ r = results.Results(sample) assert r.keys() == ["First Name ", " Last_Name"] r = r.with_standardized_keys() assert r.keys() == ["first_name", "last_name"] r.strip_all_values() assert r[2] == dict(first_name="", last_name="") assert r.grouped_by("first_name") == { "Ice": results.Results([ dict(first_name="Ice", last_name="T"), dict(first_name="Ice", last_name="Cube"), ]), "": results.Results([dict(first_name="", last_name="")]), } r.set_blanks_to_none() assert r.by_key("last_name", "first_name") == { "T": "Ice", "Cube": "Ice", None: None, } assert r[2] == dict(first_name=None, last_name=None) assert r.csv == EXPECTED_CSV outpath = tmpdir / "test.csv" r.save_csv(outpath) assert Path(outpath).read_text() == EXPECTED_CSV r.delete_key("last_name") assert r.keys() == ["first_name"] r.delete_keys(["first_name"]) assert r.keys() == []
def radiusVsRate(folder="."): temperatures = list(range(120, 221, 5)) plt.title("Average island growth") label = r'Average island radius growth rate $ \sqrt{{ \dot{{r}} }}$' plt.ylabel(label) label = r'Time-averaged total rate $< R >_t }}$' plt.xlabel(label) plt.grid(True) currentResults = results.Results() sqrt = True interval = True print(folder) try: os.chdir(folder) oneResult = mk.getIslandDistribution(temperatures, sqrt, interval) currentResults.append(oneResult) except OSError: print("error changing to {}".format(folder)) a = 0 #do nothing plt.loglog(currentResults.totalRatio(), currentResults.growthSlope(), label="growth" + folder) plt.loglog(currentResults.totalRatio(), currentResults.gyradius(), label="gyradius") plt.loglog(currentResults.totalRatio(), 1000 / currentResults.perimeter(), label="perimeter") plt.legend(loc='upper left', prop={'size': 6})
def report(dir): r = results.Results() r.read_all(dir) print("Hosts with readable shares:") for key in results.sorted_addresses( results.filter_by_shares(r.hosts, readable=True, writable=False)): printhost(r.hosts, key) print("\nHosts with writable shares:") for key in results.sorted_addresses( results.filter_by_shares(r.hosts, readable=False, writable=True)): printhost(r.hosts, key) print("\nHosts vulnerable to Bluekeep:") for key in results.sorted_addresses( results.sorted_addresses( results.filter_by_bluekeep(r.hosts).keys())): printhost(r.hosts, key) print('\nHosts vulnerable to MS17-010:') for key in results.sorted_addresses( results.sorted_addresses( results.filter_by_ms17010(r.hosts).keys())): printhost(r.hosts, key) print("\nHosts vulnerable to MS12-020:") for key in results.sorted_addresses( results.sorted_addresses( results.filter_by_ms12020(r.hosts).keys())): printhost(r.hosts, key) print('\nHosts vulnerable to CVE-2021-1675 (printnightmare):') for key in results.sorted_addresses( results.sorted_addresses( results.filter_by_cve_2021_1675(r.hosts).keys())): printhost(r.hosts, key)
def test_guessing(): assert results.guess_value_type("") is None assert results.guess_value_type(1.1) == float r = results.Results(SAMPLE) guessed = r.guessed_sql_column_types() assert guessed == GUESSED assert results.create_table_statement("ttt", guessed) == CREATE assert r.guessed_create_table_statement("ttt") == CREATE
def test_deterministic_uuids(sample): r = results.Results(sample) r = r.with_standardized_keys() duuid = r[0].deterministic_uuid(["first_name", "last_name"], uuid_domain=SAMPLE_DOMAIN) UUID = "01c6bd2f-a45c-54eb-94f8-43cf01a38efc" assert str(duuid) == UUID assert duuid == uuid.UUID(f"urn:uuid:{UUID}")
def test_table_templating(): templates = nouns.Templates(folders=example_templates_folder, preprocess=x) data = results.Results([dict(a=None, b=2), dict(a=3.5, b="")]) transformed = x(data, style="stylish") transformed["_style"] = x("stylish") rendered = templates.render(transformed) assert rendered == RENDERED_TABLE
def test_pivot_multi_down(): UNPIVOTED = [ dict(year=2015, state="NSW", party="Pink", votes=10), dict(year=2015, state="NSW", party="Orange", votes=1), dict(year=2015, state="VIC", party="Magenta", votes=3), dict(year=2015, state="VIC", party="Pink", votes=11), dict(year=2015, state="VIC", party="Orange", votes=2), dict(year=2018, state="VIC", party="Yellow", votes=5), ] PIVOTED = [ { "state": "NSW", "year": 2015, "Magenta": None, "Pink": 10, "Orange": 1, "Yellow": None, }, { "state": "VIC", "year": 2015, "Magenta": 3, "Pink": 11, "Orange": 2, "Yellow": None, }, { "state": "VIC", "year": 2018, "Magenta": None, "Pink": None, "Orange": None, "Yellow": 5, }, ] r = results.Results(UNPIVOTED) pivoted = results.Results(PIVOTED) assert pivoted.keys() == [ "state", "year", "Magenta", "Pink", "Orange", "Yellow" ] assert r.pivoted() == results.Results(PIVOTED)
def test_pop(sample): r_orig = results.Results(sample) r = results.Results(sample) assert len(r) == 3 popped = r.pop() assert popped == r_orig[-1] assert len(r) == 2 popped = r.pop(0) assert popped == r_orig[0] assert len(r) == 1 assert r.keys() == ["First Name ", " Last_Name"] assert r.pop("First Name ") == ["Ice"]
def test_gm(self): """Process results of a GM run with the Results object.""" results_obj = results.Results( actuals_root=os.path.join(self._input_dir, 'gm-actuals'), expected_root=os.path.join(self._input_dir, 'gm-expectations'), generated_images_root=self._temp_dir) results_obj.get_timestamp = mock_get_timestamp gm_json.WriteToFile( results_obj.get_packaged_results_of_type( results.KEY__HEADER__RESULTS_ALL), os.path.join(self._output_dir_actual, 'gm.json'))
def test_hierarchical(): ORIGINAL = [ dict(state="NSW", party="Pink", candidate="A"), dict(state="NSW", party="Pink", candidate="B"), dict(state="VIC", party="Pink", candidate="C"), dict(state="VIC", party="Pink", candidate="D"), dict(state="VIC", party="Yellow", candidate="E"), ] HIERARCHICAL = [ dict(state="NSW", party="Pink", candidate="A"), dict(state="", party="", candidate="B"), dict(state="VIC", party="Pink", candidate="C"), dict(state="", party="", candidate="D"), dict(state="", party="Yellow", candidate="E"), ] r = results.Results(ORIGINAL) r.make_hierarchical() assert r == results.Results(HIERARCHICAL)
def showResults(self): print self.multiplier print self.score print self.successCounter r = results.Results([ 'Multiplier: ', self.maxMultiplier, 'Score: ', self.score, 'Success: ', self.successCounter, '---------', '--------', 'CpuCycles: <>', self.successCounter * self.maxMultiplier ]) s = cocos.scene.Scene(r) director.replace(TurnOffTilesTransition(s))
def test_joining(): A = [dict(k=1, c=2), dict(k=2, c=3)] B = [dict(k=2, d=4), dict(k=2, d=5), dict(k=3, d=6)] INNER = [dict(k=2, c=3, d=4), dict(k=2, c=3, d=5)] LEFT = [dict(k=1, c=2, d=None), dict(k=2, c=3, d=4), dict(k=2, c=3, d=5)] RIGHT = [dict(k=2, c=3, d=4), dict(k=2, c=3, d=5), dict(k=3, c=None, d=6)] FULL = [ dict(k=1, c=2, d=None), dict(k=2, c=3, d=4), dict(k=2, c=3, d=5), dict(k=3, c=None, d=6), ] a = results.Results(A) b = results.Results(B) joined = a.with_join(b) assert joined == results.Results(INNER) joined = a.with_join(b, left=True) assert joined == results.Results(LEFT) joined = a.with_join(b, right=True) assert joined == results.Results(RIGHT) joined = a.with_join(b, left=True, right=True) assert joined == results.Results(FULL)
def test_results_sort(): FULL = [ dict(k=None, c=3, d=5), dict(k=3, c=None, d=6), dict(k=1, c=2, d=None), dict(k=2, c=3, d=4), dict(k=3, c=3, d=6), dict(k=3, c=3, d=5), ] r = results.Results(FULL) r.ltrsort() SORTED = [ dict(k=1, c=2, d=None), dict(k=2, c=3, d=4), dict(k=3, c=3, d=5), dict(k=3, c=3, d=6), dict(k=3, c=None, d=6), dict(k=None, c=3, d=5), ] assert r == SORTED r.ltrsort(reverse=["c"]) SORTED = [ dict(k=1, c=2, d=None), dict(k=2, c=3, d=4), dict(k=3, c=None, d=6), dict(k=3, c=3, d=5), dict(k=3, c=3, d=6), dict(k=None, c=3, d=5), ] assert r == SORTED r.ltrsort(reverse=["c"], noneslarger=False) SORTED = [ dict(k=None, c=3, d=5), dict(k=1, c=2, d=None), dict(k=2, c=3, d=4), dict(k=3, c=3, d=5), dict(k=3, c=3, d=6), dict(k=3, c=None, d=6), ] assert r == SORTED
def test_empty(tmpdb): db = results.db(tmpdb) empty = db.ss("select 1 as bollocks limit 0") assert empty.keys() == ["bollocks"] empty.delete_key("bollocks") assert empty.keys() == [] empty.delete_keys(["nonexistent"]) assert empty.keys() == [] assert results.Results([]).keys() == [] r = db.ss("select 1 as a, 2 as b union select 3, 4") assert r.values_for("a") == [1, 3] assert r.pop("a") == [1, 3] assert r.keys() == ["b"]
def __init__(self): self.box = Tk() self.frame1 = Frame(self.box) self.frame2 = Frame(self.box) self.toplabel = Label(self.box, text="Complex Calculator", font=("Century Gothic", 24)) self.toplabel.pack(side=TOP) self.inputs = inputs.Inputs(self.frame2) self.inputs.pack(side=LEFT, padx=50) self.evalbutton = Button(self.inputs, text="Evaluate", command=self.calculate) self.evalbutton.pack(side=TOP) self.resultslabels = Frame(self.frame2) self.sum = Label(self.resultslabels, text="Sum", font=("Century Gothic", 12), anchor="w", width=8) self.diff = Label(self.resultslabels, text="Difference", font=("Century Gothic", 12), anchor="w", width=8) self.product = Label(self.resultslabels, text="Product", font=("Century Gothic", 12), anchor="w", width=8) self.sum.pack(side=TOP) self.diff.pack(side=TOP) self.product.pack(side=TOP) self.resultslabels.pack(side=LEFT) self.results = results.Results(self.frame2) self.results.pack(side=LEFT) self.frame1.pack(side=TOP, pady=10) self.frame2.pack(side=TOP, pady=10) self.box.mainloop()
def test_hist(): r = results.Results([ dict(a=1, b=2, c=0, d="yo", e=-1), dict(a=5, b=-1, c=0, d="a", e=None) ]) r.annotate_histogram_amplitudes() def get_annotations(rows): def histos(r): return [getattr(r[k], "histo", None) for k in r.keys()] return [histos(_) for _ in rows] assert get_annotations(r) == [ [(0.0, 20.0), (33.333_333_333_333_33, 100.0), (0.0, 0.0), None, (0.0, 100.0)], [(0.0, 100.0), (0.0, 33.333_333_333_333_33), (0.0, 0.0), None, None], ]
def solve(self, inputdata): """Solve a linear inverse scattering problem. This is the routine in which the method is implemented, i.e., the method receives an instance of an inverse scattering problem containing the scattered and total fields and it returns a solution. Parameters ---------- inputdata : :class:`inputdata.InputData` An object of :class:`InputData` defining the instance of the problem. It must contains scattered and total fields data. Returns ------- :class:`results.Result` """ return rst.Results('')
def update_results(self, invalidate=False): """ Create or update self._results, based on the latest expectations and actuals. We hold self.results_rlock while we do this, to guarantee that no other thread attempts to update either self._results or the underlying files at the same time. Args: invalidate: if True, invalidate self._results immediately upon entry; otherwise, we will let readers see those results until we replace them """ with self.results_rlock: if invalidate: self._results = None logging.info( 'Updating actual GM results in %s to revision %s from repo %s ...' % (self._actuals_dir, self._actuals_repo_revision, self._actuals_repo_url)) self._actuals_repo.Update(path='.', revision=self._actuals_repo_revision) # We only update the expectations dir if the server was run with a # nonzero --reload argument; otherwise, we expect the user to maintain # her own expectations as she sees fit. # # Because the Skia repo is moving from SVN to git, and git does not # support updating a single directory tree, we have to update the entire # repo checkout. # # Because Skia uses depot_tools, we have to update using "gclient sync" # instead of raw git (or SVN) update. Happily, this will work whether # the checkout was created using git or SVN. if self._reload_seconds: logging.info( 'Updating expected GM results in %s by syncing Skia repo ...' % results_mod.DEFAULT_EXPECTATIONS_DIR) _run_command(['gclient', 'sync'], TRUNK_DIRECTORY) self._results = results_mod.Results(actuals_root=self._actuals_dir)
def test_key_renaming(): SAMPLE = dict(a=None, b=None, c=None, d=None) r = results.Results([SAMPLE]) assert r.keys() == "a b c d".split() with raises(ValueError): r.with_renamed_keys({"d": "a"}) # shouldn't raise r2 = r.with_renamed_keys(dict(a="e", d="a")) assert r2.keys() == "e b c a".split() renames = dict( a="a", b="bb", c=None, ) # unchanged # changed # removed r2 = r.with_renamed_keys(renames) assert r2.keys() == "a bb d".split() r2 = r.with_renamed_keys(renames, keep_unmapped_keys=False) assert r2.keys() == "a bb".split() with raises(ValueError): r2 = r.with_renamed_keys(renames, fail_on_unmapped_keys=True) r3 = r.with_reordered_keys("b a".split()) assert r3.keys() == "b a".split() r3 = r.with_reordered_keys("b a".split(), include_unordered=True) assert r3.keys() == "b a c d".split() r3 = r.with_reordered_keys("b a extra".split(), include_nonexistent=True) assert r3.keys() == "b a extra".split() r3 = r.with_reordered_keys("b a extra".split(), include_unordered=True, include_nonexistent=True) assert r3.keys() == "b a extra c d".split()
def __init__(self, parent): Gtk.Box.__init__(self, orientation=Gtk.Orientation.VERTICAL, spacing=6) self.parent = parent try: current_locale, encoding = locale.getdefaultlocale() locale_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'locale') translate = gettext.translation (cn.App.application_shortname, locale_path, [current_locale] ) _ = translate.gettext except FileNotFoundError: _ = str self.stack = Gtk.Stack() self.stack.set_transition_type(Gtk.StackTransitionType.SLIDE_LEFT_RIGHT) self.stack.set_transition_duration(1000) self.results = rs.Results(self) self.stack.add_titled(self.results, "results", _('Results')) self.pack_start(self.stack, True, True, 0)
def update_results(self): """ Create or update self._results, based on the expectations in EXPECTATIONS_DIR and the latest actuals from skia-autogen. We hold self.results_rlock while we do this, to guarantee that no other thread attempts to update either self._results or the underlying files at the same time. """ with self.results_rlock: logging.info( 'Updating actual GM results in %s from SVN repo %s ...' % (self._actuals_dir, ACTUALS_SVN_REPO)) self._actuals_repo.Update('.') # We only update the expectations dir if the server was run with a # nonzero --reload argument; otherwise, we expect the user to maintain # her own expectations as she sees fit. # # Because the Skia repo is moving from SVN to git, and git does not # support updating a single directory tree, we have to update the entire # repo checkout. # # Because Skia uses depot_tools, we have to update using "gclient sync" # instead of raw git (or SVN) update. Happily, this will work whether # the checkout was created using git or SVN. if self._reload_seconds: logging.info( 'Updating expected GM results in %s by syncing Skia repo ...' % EXPECTATIONS_DIR) _run_command(['gclient', 'sync'], TRUNK_DIRECTORY) logging.info( ('Parsing results from actuals in %s and expectations in %s, ' + 'and generating pixel diffs (may take a while) ...') % (self._actuals_dir, EXPECTATIONS_DIR)) self._results = results.Results( actuals_root=self._actuals_dir, expected_root=EXPECTATIONS_DIR, generated_images_root=GENERATED_IMAGES_ROOT)
def format_history_as_table(h): def kformat(vv): if vv is None: return "" def fmt(k, v): if not (isinstance(v, str) and v.startswith("<")): v = repr(v) else: v = v.split(" ")[0][1:] v = v.splitlines()[0] v = trunc(v, 100) return f"{k} = {v}" return ", ".join(fmt(k, v) for k, v in vv.items()) t = [_ for _ in h if _] all_keys = [_.keys() for _ in t] klist = set().union(*all_keys) klist = list(sorted(klist)) largest = max(klist + [0]) tt = [] for i in range(1, largest + 1): # print(i) values = {str(j): kformat(t[j].get(i)) for j in range(len(t))} d = dict(line=str(i), **values) tt.append(d) r = results.Results(tt) for row in r: row.pop("line") return r
def solve(self, inputdata, print_info=True, print_file=sys.stdout): """Solve the inverse scattering problem. This is the model routine for any method implementation. The input may include other arguments. But the output must always be an object of :class:`results.Results`. Parameters ---------- inputdata : :class:`inputdata.InputData` An object of the class which defines an instance. print_info : bool A flag to indicate if information should be displayed or not on the screen. Returns ------- :class:`results.Results` """ if print_info: self._print_title(inputdata, print_file=print_file) return rst.Results(inputdata.name)
replay = sg.Popup('%s does not exist.' % fname) continue mrc = mrcfile.open(fname) nimage = mrc.data.shape[0] if (nimage > len(nv.title[findex])): nimage = len(nv.title[findex]) item = [] r = [] title_index = {} # Load all images of selected file stext.Update(value='Status: Loading images from %s' % fname) for i in range(nimage): title = '%d : %s' % (i, nv.title[findex][i]) title_index[title] = i item.append(title) r.append(results.Results()) r[i].title = nv.title[findex][i] r[i].MapID = nv.MapID[findex][i] r[i].StageXYZ = nv.StageXYZ[findex][i] r[i].load_MRC_data(mrc.data[nv.sliceID[findex][i]], params, window) r[i].xori = 0 r[i].yori = params.ysize r[i].scale = -1 v = math.floor((i + 1) / nimage * 100) window['-PROGRESS-'].UpdateBar(v) vtext = '%3d%%' % v window['-PROGRESS-TEXT-'].Update(value=vtext) window['-SLICE-'].Update(values=item, value=item[index]) opened = True # Display first image index = 0
def solve(self, inputdata): """Solve an instance of linear inverse scattering problem. Parameters ---------- inputdata : :class:`inputdata.InputData` The instance of the problem containing the information on the scattered and total field. Returns ------- :class:`results.Results` """ # Compute the coefficient matrix A = self._compute_A(inputdata) # Compute right-hand-side of system of equations beta = self._compute_beta(inputdata) # Solve according the predefined method if self.linsolver == TIKHONOV_METHOD: if self._choice_strategy == MOZOROV_CHOICE: if inputdata.noise is None or inputdata.noise == 0.: self.parameter = mozorov_choice(A, beta) else: self.parameter = mozorov_choice(A, beta, inputdata.noise) elif self._choice_strategy == LAVARELLO_CHOICE: if self._beta_approximation is None: alpha0 = quick_guess(A, beta) self.parameter = lavarello_choice( A, inputdata.es, np.reshape(A @ alpha0, inputdata.es.shape)) else: self.parameter = lavarello_choice( A, inputdata.es, np.reshape(self._beta_approximation, inputdata.es.shape)) elif self._choice_strategy == LCURVE_CHOICE: if self._bounds is None and self._number_terms is None: self.parameter = lcurve_choice(A, beta) elif self._bounds is None and self._number_terms is not None: self.parameter = lcurve_choice( A, beta, number_terms=self._number_terms) else: self.parameter = lcurve_choice(A, beta, self._bounds, self._number_terms) alpha = tikhonov(A, beta, self.parameter) if self._choice_strategy == LAVARELLO_CHOICE: self._beta_approximation = A @ alpha elif self.linsolver == LANDWEBER_METHOD: x0 = quick_guess(A, beta) alpha = landweber(A, beta, self.parameter[0] / lag.norm(A)**2, x0, self.parameter[1]) elif self.linsolver == CONJUGATED_GRADIENT_METHOD: x0 = quick_guess(A, beta) alpha = conjugated_gradient(A, beta, x0, self.parameter) elif self.linsolver == LEAST_SQUARES_METHOD: alpha = least_squares(A, beta, self.parameter) # Recover the relative permittivity and conductivity maps self._recover_map(inputdata, alpha) aux = rst.Results(inputdata.name + '_' + self.alias_name + '_' + self.discretization_method_alias, method_name=self.name + ' ' + self.discretization_method_name, configuration_filename=self.configuration.name, configuration_filepath=self.configuration.path, input_filename=inputdata.name, input_filepath=inputdata.path, relative_permittivity_map=inputdata.epsilon_r, conductivity_map=inputdata.sigma) return aux
async def on_ready(): await bot.change_presence(status=discord.Status.online, activity=discord.Game('Made by Shep and Peter!')) print(f'Logged in as: {bot.user.name}') print(f'With ID: {bot.user.id}') @bot.event async def on_command_completion(ctx): global command_impact command_impact += 1 def get_impact(): global command_impact return command_impact bot.add_cog(settings.Settings(bot)) bot.add_cog(calculate.Calculate(bot)) bot.add_cog(results.Results(bot)) bot.add_cog(CommandErrorHandler.CommandErrorHandler(bot)) bot.add_cog(info.Info(bot)) bot.add_cog(DataSender.DataSender(bot, guild_id)) bot.add_cog(DataWriter.DataWriter(bot)) bot.add_cog(MatchMaker.MatchMaker(bot)) bot.add_cog(help_functions.Impact(bot)) if "BOT_TOKEN" in os.environ.keys(): print("Starting bot...") bot.run(os.environ['BOT_TOKEN']) else: print(os.environ.keys()) with open('work_bot_token.txt', 'r') as f: bot.run(f.read().strip())
### MAIN random.seed("1683726262826") nList = np.arange(2, MAX_N + 1, MAX_N / 25)[:-1] #nList = np.linspace(1, 5, 50)[1:] qList = np.array([1.0 / 4.0, 1.0 / 3.0, 0.5, 1.0, 2.0, 3.0, 4.0], dtype=float) indexList = np.arange(len(qList)) X, Y = np.meshgrid(nList, qList) XX, YY = np.meshgrid(nList, indexList) zfunc = np.vectorize(runSimulation) #N = np.array(U / nList, dtype=int) #Z = zfunc(nList, U, Y, 5) Z = zfunc(nList, U, Y) names = [ 'error_inserted', 'error_not_inserted', 'gamma', 'beta', 'size', 'width', 'depth', 'fmeasure', 'proba_inserted' ] Zs = [Z[:][:][i] for i in range(len(names))] r = results.Results(output, names, XX, YY, Zs) r.setX("Number of exported keys") r.setY("Priority", indexList, ["F" + str(q)[:4] for q in qList]) with open(output + "data.p", "wb") as f: pickle.dump(r, f)
def __call__(self): suites = [] test_results = { 'framework': { 'name': self.results.results[0].framework, }, 'suites': suites, } for test in self.results.results: # serialize test results tsresult = None if not test.using_xperf: subtests = [] suite = { 'name': test.name(), 'subtests': subtests, } if self.results.extra_options: suite['extraOptions'] = self.results.extra_options suites.append(suite) vals = [] replicates = {} # TODO: counters!!!! we don't have any, but they suffer the # same for result in test.results: # XXX this will not work for manifests which list # the same page name twice. It also ignores cycles for page, val in result.raw_values(): if page == 'NULL': page = test.name() if tsresult is None: tsresult = r = TalosResults.Results() r.results = [{ 'index': 0, 'page': test.name(), 'runs': val }] else: r = tsresult.results[0] if r['page'] == test.name(): r['runs'].extend(val) replicates.setdefault(page, []).extend(val) tresults = [tsresult] if tsresult else test.results for result in tresults: filtered_results = \ result.values(suite['name'], test.test_config['filters']) vals.extend([[i['value'], j] for i, j in filtered_results]) for val, page in filtered_results: if page == 'NULL': # no real subtests page = test.name() subtest = { 'name': page, 'value': val['filtered'], 'replicates': replicates[page], } subtests.append(subtest) if test.test_config.get('lower_is_better') is not None: subtest['lowerIsBetter'] = \ test.test_config['lower_is_better'] if test.test_config.get('alert_threshold') is not None: subtest['alertThreshold'] = \ test.test_config['alert_threshold'] if test.test_config.get('unit'): subtest['unit'] = test.test_config['unit'] # if there is more than one subtest, calculate a summary result if len(subtests) > 1: suite['value'] = self.construct_results( vals, testname=test.name()) if test.test_config.get('lower_is_better') is not None: suite['lowerIsBetter'] = \ test.test_config['lower_is_better'] if test.test_config.get('alert_threshold') is not None: suite['alertThreshold'] = \ test.test_config['alert_threshold'] # counters results_aux data counter_subtests = [] for cd in test.all_counter_results: for name, vals in cd.items(): # We want to add the xperf data as talos_counters # exclude counters whose values are tuples (bad for # graphserver) if len(vals) > 0 and isinstance(vals[0], list): continue # mainthread IO is a list of filenames and accesses, we do # not report this as a counter if 'mainthreadio' in name: continue # responsiveness has it's own metric, not the mean # TODO: consider doing this for all counters if 'responsiveness' is name: subtest = { 'name': name, 'value': filter.responsiveness_Metric(vals) } counter_subtests.append(subtest) continue subtest = { 'name': name, 'value': 0.0, } counter_subtests.append(subtest) if test.using_xperf: if len(vals) > 0: subtest['value'] = vals[0] else: # calculate mean value if len(vals) > 0: varray = [float(v) for v in vals] subtest['value'] = filter.mean(varray) if counter_subtests: suites.append({ 'name': test.name(), 'subtests': counter_subtests }) return test_results