def _science_calculate(expr): expr = expr.group(0) expr1 = expr.split("(") op = expr1[0] num = expr1[1][:-1] if num == "": raise NameError("wrong calculate for '{}'".format(expr)) else: num = float(num) if op == "sin": result = math.sin(num) elif op == "cos": result = math.cos(num) elif op == "tan": result = math.tan(num) elif op == "log": result = math.log10(num) elif op == "ln": result = math.log(num) elif op == "√": result = math.sqrt(num) elif op == "exp": result = math.exp(num) elif op == "": result = num else: raise NameError("wrong operator for '{}'".format(op)) if result < 0: return wrapper(str(result)) else: return str(result)
def handler(event, context, metrics): client = get_client() metrics.set_namespace('DynamoDB Performance Testing') metrics.put_dimensions({"Operation": f"BatchWriteItem -- {COUNT} items"}) for i in range(10): wrapped = wrapper(client.batch_write_item, **make_batch_items(COUNT)) latency = timeit.timeit(wrapped, number=1) metrics.put_metric("Latency", latency * 1000, "Milliseconds")
def handler(event, context, metrics): client = get_client() metrics.set_namespace('DynamoDB Performance Testing') metrics.put_dimensions({"Operation": "PutItem"}) for i in range(10): wrapped = wrapper(client.put_item, **make_put_item()) latency = timeit.timeit(wrapped, number=1) metrics.put_metric("Latency", latency * 1000, "Milliseconds")
def show(self, figure=None, ax=None): wrap = wrapper(self) color = 'LightYellow' if figure is None: self.figure, self.ax = plt.subplots() self.ax.set_aspect('equal') plt.subplots_adjust(left=0.25, bottom=0.30) self.view.plot(self.figure, self.ax) plt.axis([-1, 1, -1, 1]) self.neg_axes = plt.axes([0.25, 0.1, 0.65, 0.03]) self.sneg = Slider(self.neg_axes, 'Neg Samples', 0.1, 100., valinit=50., valfmt='%4d') self.sneg.on_changed(wrap('update_neg')) self.pos_axes = plt.axes([0.25, 0.15, 0.65, 0.03]) self.spos = Slider(self.pos_axes, 'Pos Samples', 0.1, 100., valinit=50., valfmt='%4d') self.spos.on_changed(wrap('update_pos')) self.resetax = plt.axes([0.8, 0.025, 0.1, 0.04]) self.reset_button = Button(self.resetax, 'Reset', color=color, hovercolor='0.975') self.reset_button.on_clicked(wrap('reset')) self.rax = plt.axes([0.05, 0.5, 0.15, 0.4]) self.rax.text(0., 1.05, r'ratio = neg/pos', fontsize=12, color='black') self.radio_buttons = RadioButtons(self.rax, self.radio_labels, active=6) self.adjust_radio_buttons() self.radio_buttons.on_clicked(wrap('radio')) self.cax = plt.axes([0.05, 0.25, 0.15, 0.2]) self.check_options = CheckButtons(self.cax, self.view_options, self.active_options) self.check_options.on_clicked(wrap('check')) if self.points: phi, delta = self.points phi, delta = phidelta_std2gen(phi, delta, ratio=self.ratio) self.view.scatter2D(phi, delta, ax=self.ax) plt.show()
def _pow(pow_expr): pow_expr = pow_expr.group(0) pow_expr = pow_expr.split("^(") base = pow_expr[0] index = pow_expr[1][:-1] if base == "" or index == "": raise Exception("wrong pow expression:{}".format(pow_expr)) else: base = float(base) index = float(index) result = math.pow(base, index) if result < 0: return wrapper(str(result)) else: return str(result)
lose_prob = 1 - win_prob lose_player_status = copy.deepcopy(player_status) lose_player_status['num_armies'] -= (src['num_armies'] - 1) lose_enemy_status = copy.deepcopy(enemy_status) lose_src = get_territory_by_id(action[0]['territory'], lose_player_status['territories']) lose_src['num_armies'] = 1 # Number of troops remaining on battle loss lose_dest = get_territory_by_id(action[1]['territory'], lose_enemy_status['territories']) lose_dest['num_armies'] = lose_dest['num_armies'] / 2 + 1 # Expected enemy troop loss lose_state = { 'player_status': lose_player_status, 'enemy_status': lose_enemy_status } outcomes[win_prob] = win_state outcomes[lose_prob] = lose_state return outcomes if __name__ == "__main__": import EvaluatorAI b = EvaluatorAI.EvaluatorAI() time.sleep(5) r = Battle_Evaluator() b._refresh_state() possible_action = (b.player_status['territories'][0], b.enemy_status['territories'][0]) import timeit from utils import wrapper wrapped = wrapper(r.evaluate_action, possible_action, b.map_layout, b.player_status, b.get_enemy_status()) print "Waiting... " print "Evaluate (s): " + str(timeit.Timer(wrapped).timeit(number=1)/1)
def main(): # FETCH & PARSE DATA SUNSET_TIMES = [] np.set_printoptions(suppress=True) # DATA_DA = pandas.DataArray representation of data DATA_DA = pd.read_csv(args.infile, # skiprows=1, usecols=range(2, 14), converters=dict(((x, utils.timestampToSeconds) for x in range(0, 14))) ) # Transform DA from rows/cols to cols/rows DATA_DA = DATA_DA.T # flatten 2d array to all be in the same array DATA_FLAT = np.concatenate(tuple( (x[~np.isnan(x)] for x in DATA_DA.to_numpy()) )) XVALS = np.arange(1, 366) data = {} print("Beginning calculations... hold on! (%d generations, %d predictions)" % (args.tries, args.tries*100)) POLYOPT_DATA = utils.generate_report("Opt poly", DATA_FLAT, XVALS, utils.wrapper( gen_opt_poly_model, XVALS, DATA_FLAT, maxDegree=50, ), times=args.tries) POLYFIX_DEGREE = 15 POLYFIX_DATA = utils.generate_report("Fixed poly (δ%d)" % POLYFIX_DEGREE, DATA_FLAT, XVALS, utils.wrapper( gen_poly_model, XVALS, DATA_FLAT, degree=POLYFIX_DEGREE ), times=args.tries) TRIG_DATA_1 = utils.generate_report("Trig1", DATA_FLAT, XVALS, utils.wrapper( gen_trig_model, XVALS, DATA_FLAT ), times=args.tries) TRIG_DATA_2 = utils.generate_report("Trig2", DATA_FLAT, XVALS, utils.wrapper( gen_trig_model, XVALS[:180], DATA_FLAT[:180] ), times=args.tries) TRIG_DATA_2["model"]["predictions"] = TRIG_DATA_2["model"]["model"](XVALS) COMBINED_DATA = utils.generate_report("Combined", DATA_FLAT, XVALS, utils.wrapper( gen_combined_model, XVALS, DATA_FLAT, maxDegree=50, ), times=args.tries) data["Opt poly (δ%d)" % POLYOPT_DATA["model"]["degree"]] = POLYOPT_DATA data["Fix poly (δ%d)" % POLYFIX_DATA["model"]["degree"]] = POLYFIX_DATA data["Cos1"] = TRIG_DATA_1 data["Cos2"] = TRIG_DATA_2 data["Combined (δ%d)" % COMBINED_DATA["model"]["poly"] ["degree"]] = COMBINED_DATA TABLE_ROW = "%s{:>22}%s | " + " | ".join(("%s{:^14}%s",)*len(data.keys())) TRANSLATION_DICT = { "differencesquares": ("Sum of difference^2", int), "incorrectvalues": ("# of incorrect values", len), "generation_time": ("Generation time (ms)", lambda x: "{:.4f}".format(x*1000)), "prediction_time": ("Prediction time (ms)", lambda x: "{:.4f}".format(x*1000)) } print("Calculations complete; final data:\n\n") print(TABLE_ROW.format("", *(k for k in data.keys())) % ((utils.ACCENT_BR, utils.RESET)*(len(data.keys())+1))) for key, translation in TRANSLATION_DICT.items(): values = [value[key] for value in data.values()] # filter passed formatted = TABLE_ROW.format( translation[0], *map(translation[1], values) ) % (utils.ACCENT_BR, utils.RESET, *("",)*(2*len(data.keys()))) print(formatted) # graph results COLOURS = ["firebrick", "royalblue", "darkorchid", "darkslategrey", "forestgreen"] for i, (key, value) in enumerate(data.items()): plt.plot(XVALS, value["model"]["predictions"], color=COLOURS[i], label=key) plt.plot(XVALS, DATA_FLAT, "o", color="black", label="Actual data", ms=0.7) # inspiration from https://stackoverflow.com/questions/26646362/numpy-array-is-not-json-serializable class SafeEncoder(json.JSONEncoder): """JSON encoder for our data so that everything goes swellingly. Don't worry about this. """ def default(self, obj): if isinstance(obj, np.ndarray): return "%^" + str(obj.tolist()) + "%^" elif callable(obj): # if is function return repr(obj) return json.JSONEncoder.default(self, obj) if args.outfile: with open(args.outfile, "w") as f: # recursively delete certain keys i.e. predictions def recursivelyRemove(obj, blacklist=[]): if isinstance(obj, dict): for key in list(obj.keys()): if key in blacklist: del obj[key] else: obj[key] = recursivelyRemove( obj[key], blacklist=blacklist) return obj outputData = recursivelyRemove(data, blacklist=[ "predictions", "trig", "poly" ]) outputJSON = json.dumps(outputData, cls=SafeEncoder, indent=4, sort_keys=True, ensure_ascii=False) outputJSON = outputJSON.replace("\"%^", "").replace("%^\"", "") f.write(outputJSON) print("\n"*2 + Fore.YELLOW + " Equations and data written to `%s`." % args.outfile) if args.graph: plt.legend() plt.show()