def build_env(self, env_name: str): self.env_name = env_name self.env_data = db.load_data(env_name) # 載入數據庫 # 建立環境地圖 self.env_map = np.array(self.env_data['floors']['map']) # 禁用(清除)指定事件位置 for pos in self.env_data['floors']['disable']: self.change_map_id(pos, 0) # 建置玩家初始狀態 self.player.reset(self.env_data['player']) # 建立初始觀測值 player_id = None for key, value in self.env_data['maps'].items(): if value['id'] == 'background': self.background_id = key if value['id'] == 'player': if player_id is None: # 只取第一個出現player的ID player_id = key player_pos = np.argwhere(self.env_map==player_id)[0] self.observation = np.append(player_pos, [0,0], axis=0) # 清除主角位置 self.change_map_id(tuple(player_pos), 0) # 複製資料對象,用來快速重置 self._original_env_map = self.env_map.copy() self._original_observation = self.observation.copy()
def build_env(self, env_name: str) -> int: self.env_name = env_name self.env_data = db.load_data(env_name) # 載入數據庫 self.env_map = np.array(self.env_data['floors']['map']) map_ = self.env_data['floors']['map'] disable = self.env_data['floors']['disable'] maps = self.env_data['maps'] enemys = self.env_data['enemys'] items = self.env_data['items'] npcs = self.env_data['npcs'] for z, y, x in self.pos_iter(): pos = (z, y, x) kw = maps[map_[z][y][x]] if kw['id'] == 'background': self.background_id = map_[z][y][x] if kw['cls'] != 'except': # 非事件id不須建立成節點物件 if kw['cls'] == 'enemys': # 敵人類別 node = Enemy(kw) node.reset(enemys[kw['id']]) elif kw['cls'] == 'items': # 道具類別 node = Item(kw, items[kw['id']]) elif kw['cls'] == 'terrains': # 地形類別 node = Terrain(kw) elif kw['cls'] == 'npcs': # 人物類別 if pos not in npcs: node = NPC(kw, []) elif npcs[pos] == 'shop': node = NPC(kw, []) i = 1 # 4維座標 while pos + (i, ) in npcs: snode = NPC(kw, npcs[pos + (i, )]) self.n2p[snode] = pos + (i, ) self.p2n[pos + (i, )] = snode i += 1 else: node = NPC(kw, npcs[pos]) elif kw['id'] == 'player': # 玩家類別 node = Player(kw) node.reset(self.env_data['player']) self.player = node elif kw['id'] == 'end': # 結束標誌類別 node = End_Flag(kw) else: raise TypeError( f'When creating a node, the {kw["cls"]} class is not defined' ) # 事件禁用(無法觸發) if pos in disable: node.disabled = True self.n2p[node] = pos self.p2n[pos] = node # 設置觀測值 self.observation.append(self.player) return len(self.n2p)
def __init__(self, directory, load_file=None): self.img_size = 100 self.n_angles = 6 direc = directory self.pre = preprocess.Preprocess(self.img_size, self.n_angles) self.lookup = [] for subdir, dirs, files in os.walk(direc): for f in files: filename = os.path.join(subdir, f) if filename[-3:] == 'jpg': if not load_file: raw_img = cv2.imread(filename, 0) self.pre.process_img(raw_img) self.lookup.append(filename) print '%i:\t%s' % (len(self.lookup), filename) if load_file: edgel_counts = database.load_data(self.pre.hits, load_file) self.pre.set_edgel_counts(edgel_counts)
def pca_analysis(goes=True): _o, xparams, yparam = db.load_data() components = 6 dates = pd.read_csv("stormlist.csv") dates.dates = pd.to_datetime(dates.dates) if goes: _o, xparams, yparam_clf = db.load_data_RB() else: _o, xparams, yparam_clf = db.load_data() pca = decomposition.PCA(n_components=components) df = _o[xparams] data_scaled = pd.DataFrame(preprocessing.scale(df), columns=df.columns) X_tr = pca.fit_transform(data_scaled) comp_desc = pd.DataFrame(pca.components_, columns=data_scaled.columns, index=['PC-' + str(i) for i in range(components)]) desc_code = [] for i, row in comp_desc.iterrows(): code = "" for r, v in zip(row.tolist(), comp_desc.columns): if r < 0 and len(code) == 0: code = code[:-2] + str(np.round(r, 2)) elif r < 0 and len(code) > 0: code = code[:-2] + str(np.round(r, 2)) elif r > 0: code = code + str(np.round(r, 2)) code = code + " X %s + " % v pass code = code[:-2] desc_code.append("%s=%s" % (i, code)) pass print desc_code print pca.explained_variance_ratio_, data_scaled.columns print np.cumsum(pca.explained_variance_ratio_) XX = np.append(X_tr, _o[yparam_clf].values, axis=1) df = pd.DataFrame( XX, columns=["PC-1", "PC-2", "PC-3", "PC-4", "PC-5", "PC-6", "stormL"]) print df.head() ns = df[df.stormL == 0.] s = df[df.stormL == 1.] fig, axes = plt.subplots(figsize=(9, 6), nrows=2, ncols=3, dpi=120) fig.subplots_adjust(hspace=0.2, wspace=0.3) ax = axes[0, 0] ax.scatter(ns["PC-1"], ns["PC-2"], facecolors='none', edgecolors='b', s=30, alpha=1.) ax.scatter(s["PC-1"], s["PC-2"], facecolors='none', edgecolors='r', s=30, alpha=0.5) ax.tick_params(labelsize=font["size"]) ax.set_xticklabels(ax.get_xticks().astype(np.int), fontdict=font) ax.set_yticklabels(ax.get_yticks().astype(np.int), fontdict=font) ax.set_xlabel("PC-1", fontdict=font) ax.set_ylabel("PC-2", fontdict=font) ax = axes[0, 1] ax.scatter(ns["PC-1"], ns["PC-3"], facecolors='none', edgecolors='b', s=30, alpha=1.) ax.scatter(s["PC-1"], s["PC-3"], facecolors='none', edgecolors='r', s=30, alpha=0.5) ax.tick_params(labelsize=font["size"]) ax.set_xticklabels(ax.get_xticks().astype(np.int), fontdict=font) ax.set_yticklabels(ax.get_yticks().astype(np.int), fontdict=font) ax.set_xlabel("PC-1", fontdict=font) ax.set_ylabel("PC-3", fontdict=font) ax = axes[0, 2] ax.scatter(ns["PC-1"], ns["PC-4"], facecolors='none', edgecolors='b', s=30, alpha=1.) ax.scatter(s["PC-1"], s["PC-4"], facecolors='none', edgecolors='r', s=30, alpha=0.5) ax.tick_params(labelsize=font["size"]) ax.set_xticklabels(ax.get_xticks().astype(np.int), fontdict=font) ax.set_yticklabels(ax.get_yticks().astype(np.int), fontdict=font) ax.set_xlabel("PC-1", fontdict=font) ax.set_ylabel("PC-4", fontdict=font) ax = axes[1, 0] ax.scatter(ns["PC-2"], ns["PC-3"], facecolors='none', edgecolors='b', s=30, alpha=1.) ax.scatter(s["PC-2"], s["PC-3"], facecolors='none', edgecolors='r', s=30, alpha=0.5) ax.tick_params(labelsize=font["size"]) ax.set_xticklabels(ax.get_xticks().astype(np.int), fontdict=font) ax.set_yticklabels(ax.get_yticks().astype(np.int), fontdict=font) ax.set_xlabel("PC-2", fontdict=font) ax.set_ylabel("PC-3", fontdict=font) ax = axes[1, 1] ax.scatter(ns["PC-2"], ns["PC-4"], facecolors='none', edgecolors='b', s=30, alpha=1.) ax.scatter(s["PC-2"], s["PC-4"], facecolors='none', edgecolors='r', s=30, alpha=0.5) ax.tick_params(labelsize=font["size"]) ax.set_xticklabels(ax.get_xticks().astype(np.int), fontdict=font) ax.set_yticklabels(ax.get_yticks().astype(np.int), fontdict=font) ax.set_xlabel("PC-2", fontdict=font) ax.set_ylabel("PC-4", fontdict=font) ax = axes[1, 2] ax.scatter(ns["PC-3"], ns["PC-4"], facecolors='none', edgecolors='b', s=30, alpha=1.) ax.scatter(s["PC-3"], s["PC-4"], facecolors='none', edgecolors='r', s=30, alpha=0.5) ax.tick_params(labelsize=font["size"]) ax.set_xticklabels(ax.get_xticks().astype(np.int), fontdict=font) ax.set_yticklabels(ax.get_yticks().astype(np.int), fontdict=font) ax.set_xlabel("PC-3", fontdict=font) ax.set_ylabel("PC-4", fontdict=font) if goes: plt.savefig("figures/pcag.png", bbox_inches="tight") else: plt.savefig("figures/pca.png", bbox_inches="tight") return
# Check if all fields are available if request.json.get('name') and \ request.json.get('location'): my_persons.append(request.json) else: # Data is missing in the request return jsonify({"error": "Data incomplete"}), 400 save_data('database.json', my_persons) return jsonify(my_persons), 201 @app.route('/persons/<int:number>', methods=['GET']) def person_number(number: int): """ Get the first person """ person: typing.Dict = {} if len(my_persons) > number: person = my_persons[number] return jsonify(person) if __name__ == '__main__': # Load dataset before starting the server my_persons = load_data('database.json') app.run(host='0.0.0.0', port=8080, debug=True)
from __future__ import division from flask import Flask, render_template import database as DB from model import Model import json import numpy as np import simplejson app = Flask(__name__) # Load data from csv file db = DB.load_data("../BASEVENTAS2010A2015.csv") model = Model(db) @app.route("/") def home(): """ Simple analytics graphs """ return render_template("index.html") @app.route("/recommend") def recommend(): """ Recommend products based on other products """ return render_template("recommend.html") @app.route("/forecast", defaults={'product_id': None}) @app.route("/forecast/<product_id>")
import numpy as np import pandas as pd from sklearn import decomposition from sklearn import preprocessing import database as db ########################################################################## ## PCA Analysis and find out the contribution made by individual components ########################################################################## components = 10 dates = pd.read_csv("stormlist.csv") dates.dates = pd.to_datetime(dates.dates) _o, xparams, yparam_clf = db.load_data() pca = decomposition.PCA(n_components=components) df = _o[xparams] data_scaled = pd.DataFrame(preprocessing.scale(df), columns=df.columns) pca.fit_transform(data_scaled) comp_desc = pd.DataFrame(pca.components_, columns=data_scaled.columns, index=['PC-' + str(i) for i in range(components)]) print pca.explained_variance_ratio_, data_scaled.columns print np.cumsum(pca.explained_variance_ratio_) desc_code = [] for i, row in comp_desc.iterrows(): code = "" for r, v in zip(row.tolist(), comp_desc.columns): if r < 0 and len(code) == 0: code = code[:-2] + str(np.round(r, 2)) elif r < 0 and len(code) > 0: code = code[:-2] + str(np.round(r, 2))
from __future__ import division from flask import Flask, render_template import database as DB from model import Model import json import numpy as np import simplejson app = Flask(__name__) # Load data from csv file db = DB.load_data("../BASEVENTAS2010A2015.csv") model = Model(db) @app.route("/") def home(): """ Simple analytics graphs """ return render_template("index.html") @app.route("/recommend") def recommend(): """ Recommend products based on other products """ return render_template("recommend.html") @app.route("/forecast", defaults={'product_id': None})
database.modify_cell(table, **dic) flash('修改成功') return redirect(url_for('ad_everything')) elif op == 'query': info = database.query(table, **dic) flash('查询成功') return render_template('ad_everything.html', info=info) else: raise Exception('非法操作') except Exception as e: info = str(e) if len(str(e)) < 8 or DEBUG else '未知错误' flash('操作失败,' + info) return redirect(url_for('ad_everything')) if __name__ == "__main__": acc = input('mysql account:') pwd = input('mysql password:'******'create table?(y/n)') while create not in ['y', 'Y', 'n', 'N']: create = input('create table?(y/n):') create = True if create in ['y', 'Y'] else False rebuild = input('rebuild data?(y/n)') while rebuild not in ['y', 'Y', 'n', 'N']: rebuild = input('rebuild data?(y/n):') rebuild = True if rebuild in ['y', 'Y'] else False print('init database') database.init_db(ano=acc, apwd=pwd, create=create) if rebuild: database.load_data('./sql/load_data.sql') print('load finished, jiaowu admin account is "a1", and default password is "pwdpwd"') app.run(host='0.0.0.0',port=80)
@app.route('/') def home(): return render_template("home.html") @app.route('/total') def getTotal(): try: date_string = request.args.get("day") return database.read(date_string) except Exception as e: return jsonify({"msg": "Invalid date provided", "err":str(e)}) @app.route('/excelreport/') def get_excel(): try: return send_excel_file() except Exception as e: return str(e) def send_excel_file(): return send_file( database.get_excel_file(), mimetype="application/vnd.ms-excel", as_attachment=True ,attachment_filename="excelreport.xls" , ) if __name__ == "__main__": print("Loading database") database.load_data() print("Starting server") app.run('0.0.0.0')