Best Python code snippet using hypothesis
food_rs_webservice.py
Source:food_rs_webservice.py
1from flask import Flask, request2from flask_restful import Resource, Api3from json import dumps4import pandas as pd5import numpy as np6app = Flask(__name__)7api = Api(app)8class Mood(Resource):9 def get(self):10 url_dataset_it = 'dataset.csv'11 url_dataset_en = 'dataset_en.csv'12 lang = request.args.get('lang')13 if lang == 'en':14 df = pd.read_csv(url_dataset_en)15 else:16 df = pd.read_csv(url_dataset_it)17 # print('dataset language: ', lang)18 # dfFromIngredient19 def dfFromIngredient(df, searchIngrendient):20 new_rows = []21 returnDf = pd.DataFrame()22 for index, row in df.iterrows():23 listIngredients = row.ingredients.strip("[ ]").split(", ")24 if any(not (ingredient.lower().find(searchIngrendient)) for ingredient in listIngredients):25 new_rows.append(row)26 return returnDf.append(pd.DataFrame(new_rows, columns=df.columns))27 def rescoreOverweight(row):28 new_score = row.score29 if row.calories < 133.35:30 new_score = new_score * 231 if row.calories >= 133.35 and row.calories <= 400.05:32 new_score = new_score * 1.233 if row.calories > 400.05:34 new_score = new_score * 0.135 if row.fat < 4.65:36 new_score = new_score * 237 if row.fat >= 4.65 and row.fat <= 13.95:38 new_score = new_score * 1.239 if row.fat > 13.95:40 new_score = new_score * 0.141 if row.carbohydrates >= 18 and row.carbohydrates <= 54:42 new_score = new_score * 1.243 if row.carbohydrates > 54:44 new_score = new_score * 1.545 if row.fibers < 1.65:46 new_score = new_score * 0.147 if row.fibers >= 1.65 and row.fibers <= 4.95:48 new_score = new_score * 1.249 if row.fibers > 4.95:50 new_score = new_score * 251 return new_score52 def rescoreObesity(row):53 new_score = row.score54 if row.calories < 133.35:55 new_score = new_score * 356 if row.calories >= 133.35 and row.calories <= 400.05:57 new_score = new_score * 1.258 if row.calories > 400.05:59 new_score = new_score * 0.0160 if row.fat < 4.65:61 new_score = new_score * 362 if row.fat >= 4.65 and row.fat <= 13.95:63 new_score = new_score * 164 if row.fat > 13.95:65 new_score = new_score * 0.0166 if row.carbohydrates >= 18 and row.carbohydrates <= 54:67 new_score = new_score * 168 if row.carbohydrates > 54:69 new_score = new_score * 2.570 if row.fibers < 1.65:71 new_score = new_score * 0.0172 if row.fibers >= 1.65 and row.fibers <= 4.95:73 new_score = new_score * 174 if row.fibers > 4.95:75 new_score = new_score * 376 return new_score77 def rescoreObesityPlus(row):78 new_score = row.score79 if row.calories < 133.35:80 new_score = new_score * 481 if row.calories >= 133.35 and row.calories <= 400.05:82 new_score = new_score * 0.983 if row.calories > 400.05:84 new_score = new_score * 0.00185 if row.fat < 4.65:86 new_score = new_score * 487 if row.fat >= 4.65 and row.fat <= 13.95:88 new_score = new_score * 0.989 if row.fat > 13.95:90 new_score = new_score * 0.00191 if row.carbohydrates >= 18 and row.carbohydrates <= 54:92 new_score = new_score * 0.993 if row.carbohydrates > 54:94 new_score = new_score * 3.595 if row.fibers < 1.65:96 new_score = new_score * 0.00197 if row.fibers >= 1.65 and row.fibers <= 4.95:98 new_score = new_score * 0.999 if row.fibers > 4.95:100 new_score = new_score * 4101 return new_score102 def rescoreUnderweight(row):103 new_score = row.score104 if row.calories < 133.35:105 new_score = new_score * 0.1106 if row.calories >= 133.35 and row.calories <= 400.05:107 new_score = new_score * 1.2108 if row.calories > 400.05:109 new_score = new_score * 2110 if row.carbohydrates < 18:111 new_score = new_score * 0.1112 if row.carbohydrates >= 18 and row.carbohydrates <= 54:113 new_score = new_score * 1.2114 if row.carbohydrates > 54:115 new_score = new_score * 2116 if row.proteins < 3.35:117 new_score = new_score * 0.1118 if row.proteins >= 3.35 and row.proteins <= 10.05:119 new_score = new_score * 1.2120 if row.proteins > 10.05:121 new_score = new_score * 2122 return new_score123 def rescoreActivityMedium(row):124 new_score = row.score125 if row.calories > 400.05:126 new_score = new_score * 1.5127 if row.calories >= 133.35 and row.calories <= 400.05:128 new_score = new_score * 1.2129 if row.calories < 133.35:130 new_score = new_score * 0.1131 if row.proteins > 10.05:132 new_score = new_score * 1.5133 if row.proteins >= 3.35 and row.proteins <= 10.05:134 new_score = new_score * 1.2135 if row.proteins < 3.35:136 new_score = new_score * 0.1137 if row.carbohydrates > 54:138 new_score = new_score * 1.5139 if row.carbohydrates >= 18 and row.carbohydrates <= 54:140 new_score = new_score * 1.2141 if row.carbohydrates < 18:142 new_score = new_score * 0.1143 return new_score144 def rescoreActivityHigh(row):145 new_score = row.score146 if row.calories > 400.05:147 new_score = new_score * 2148 if row.calories >= 133.35 and row.calories <= 400.05:149 new_score = new_score * 1.2150 if row.calories < 133.35:151 new_score = new_score * 0.1152 if row.proteins > 10.05:153 new_score = new_score * 2154 if row.proteins >= 3.35 and row.proteins <= 10.05:155 new_score = new_score * 1.2156 if row.proteins < 3.35:157 new_score = new_score * 0.1158 if row.carbohydrates > 54:159 new_score = new_score * 2160 if row.carbohydrates >= 18 and row.carbohydrates <= 54:161 new_score = new_score * 1.2162 if row.carbohydrates < 18:163 new_score = new_score * 0.1164 return new_score165 cibiAntistress = ['latte intero', 'riso', 'pollo', 'cereali integrali', 'manzo', 'fagioli', 'noci',166 'cioccolato', 'formaggio', 'broccoli']167 def isAntistress(ingredients):168 listIngredients = ingredients.strip("[ ]").split(", ")169 antistress = 0170 for elem in cibiAntistress:171 if any(elem in ingredient.lower() for ingredient in listIngredients):172 antistress += 1173 antiS = antistress / len(cibiAntistress)174 return (antiS)175 def rescoreStress(row):176 new_score = row.score177 if row.sodium < sodiumAvg - sodiumStd:178 new_score = new_score * 2179 if row.sodium >= sodiumAvg - sodiumStd and row.sodium <= sodiumAvg + sodiumStd:180 new_score = new_score * 1.2181 if row.sodium > sodiumAvg + sodiumStd:182 new_score = new_score * 0.1183 if row.antistress == 0.1:184 new_score = new_score * 10185 if row.antistress == 0.2:186 new_score = new_score * 20187 if row.antistress >= 0.3:188 new_score = new_score * 30189 return new_score190 def rescoreDepression(row):191 new_score = row.score192 if row.saturatedFat < 1.35:193 new_score = new_score * 2194 if row.saturatedFat >= 1.35 and row.saturatedFat <= 4.05:195 new_score = new_score * 1.2196 if row.saturatedFat > 4.05:197 new_score = new_score * 0.1198 if row.carbohydrates > 54:199 new_score = new_score * 2200 if row.carbohydrates >= 18 and row.carbohydrates <= 54:201 new_score = new_score * 1.2202 if row.carbohydrates < 18:203 new_score = new_score * 0.1204 if row.fibers >= 1.65 and row.fibers <= 4.95:205 new_score = new_score * 1.5206 if row.fibers > 4.95:207 new_score = new_score * 2208 return new_score209 def rescoreMoodBad(row):210 if row.sugars < 6:211 return row.score * 0.1212 if row.sugars >= 6 and row.sugars <= 18:213 return row.score * 1.2214 if row.sugars > 18:215 return row.score * 2216 def rescoreCoffe(row):217 listIngredients = row.ingredients.strip("[ ]").split(", ")218 if 'caffè' in listIngredients:219 return row.score * 0.5220 if 'Caffè' in listIngredients:221 return row.score * 0.5222 else:223 return row.score224 richMagnesium = ['crusca', 'mandorle', 'anacardi', 'cereali integrali', 'piselli', 'fagioli', 'datteri',225 'aneto', 'fichi', 'nocciole']226 def isRichMagnesium(ingredients):227 listIngredients = ingredients.strip("[ ]").split(", ")228 magnesium = 0229 for elem in richMagnesium:230 if any(elem in ingredient.lower() for ingredient in listIngredients):231 magnesium += 1232 mg = magnesium / len(richMagnesium)233 return (mg)234 def rescoreMagnesium(row):235 if row.magnesium == 0.1:236 return row.score * 10237 if row.magnesium == 0.2:238 return row.score * 20239 if row.magnesium == 0.3:240 return row.score * 30241 else:242 return row.score243 def rescoreSleep(row):244 new_score = row.score245 if row.fat > 13.95:246 new_score = new_score * 0.1247 return new_score248 def rescoreDifficulty(row, difficulty):249 new_score = row.score250 if difficulty == 1:251 if row.difficulty == 'Molto facile':252 new_score = new_score * 2253 if difficulty == 2:254 if row.difficulty == 'Facile':255 new_score = new_score * 2256 if row.difficulty == 'Molto facile':257 new_score = new_score * 1.5258 if difficulty == 3:259 if row.difficulty == 'Media':260 new_score = new_score * 2261 if row.difficulty == 'Facile':262 new_score = new_score * 1.5263 if row.difficulty == 'Molto facile':264 new_score = new_score * 1.5265 if difficulty == 4:266 if row.difficulty == 'Difficile':267 new_score = new_score * 2268 if row.difficulty == 'Media':269 new_score = new_score * 1.5270 if row.difficulty == 'Facile':271 new_score = new_score * 1.5272 if row.difficulty == 'Molto facile':273 new_score = new_score * 1.5274 if difficulty == 5:275 if row.difficulty == 'Molto difficile':276 new_score = new_score * 2277 if row.difficulty == 'Difficile':278 new_score = new_score * 1.5279 if row.difficulty == 'Media':280 new_score = new_score * 1.5281 if row.difficulty == 'Facile':282 new_score = new_score * 1.5283 if row.difficulty == 'Molto facile':284 new_score = new_score * 1.5285 return new_score286 def rescoreGoalPlus(row):287 new_score = row.score288 if row.calories < 133.35:289 new_score = new_score * 0.1290 if row.calories >= 133.35 and row.calories <= 400.05:291 new_score = new_score * 1.2292 if row.calories > 400.05:293 new_score = new_score * 2294 if row.carbohydrates > 54:295 new_score = new_score * 2296 if row.carbohydrates >= 18 and row.carbohydrates <= 54:297 new_score = new_score * 1.2298 if row.carbohydrates < 18:299 new_score = new_score * 0.1300 if row.proteins < 3.35:301 new_score = new_score * 0.1302 if row.proteins >= 3.35 and row.proteins <= 10.05:303 new_score = new_score * 1.2304 if row.proteins > 10.05:305 new_score = new_score * 2306 return new_score307 def rescoreGoalMinus(row):308 new_score = row.score309 if row.calories < 133.35:310 new_score = new_score * 2311 if row.calories >= 133.35 and row.calories <= 400.05:312 new_score = new_score * 1.2313 if row.calories > 400.05:314 new_score = new_score * 0.1315 if row.carbohydrates > 54:316 new_score = new_score * 1.4317 if row.carbohydrates >= 18 and row.carbohydrates <= 54:318 new_score = new_score * 1.2319 if row.fat < 4.65:320 new_score = new_score * 2321 if row.fat > 13.95:322 new_score = new_score * 0.1323 return new_score324 def rescoreCost(row, cost):325 new_score = row.score326 if cost == 1:327 if row.cost == 'Molto basso':328 new_score = new_score * 2329 else:330 new_score = new_score * 0.1331 if cost == 2:332 if row.cost == 'Basso':333 new_score = new_score * 2334 elif row.cost == 'Molto basso':335 new_score = new_score * 1.5336 else:337 new_score = new_score * 0.1338 if cost == 3:339 if row.cost == 'Medio':340 new_score = new_score * 2341 elif row.cost == 'Basso':342 new_score = new_score * 1.5343 elif row.cost == 'Molto basso':344 new_score = new_score * 1.5345 else:346 new_score = new_score * 0.1347 if cost == 4:348 if row.cost == 'Elevato':349 new_score = new_score * 2350 elif row.cost == 'Medio':351 new_score = new_score * 1.5352 elif row.cost == 'Basso':353 new_score = new_score * 1.5354 elif row.cost == 'Molto basso':355 new_score = new_score * 1.5356 return new_score357 def rescoreTime(row, time):358 new_score = row.score359 i = len(row.totalTime) - 2360 potenzaDieci = 1361 totalTime = 0362 while i >= 2:363 totalTime = totalTime + int(row.totalTime[i]) * potenzaDieci364 potenzaDieci = potenzaDieci * 10365 i -= 1366 if time == totalTime:367 new_score = new_score * 2368 elif time < totalTime:369 new_score = new_score * 0.1370 elif time > totalTime:371 new_score = new_score * 1.5372 return new_score373 def rescoreU20(row):374 new_score = row.score375 if row.carbohydrates > 54:376 new_score = new_score * 2377 if row.carbohydrates >= 18 and row.carbohydrates <= 54:378 new_score = new_score * 1.2379 if row.carbohydrates < 18:380 new_score = new_score * 0.1381 if row.saturatedFat < 1.35:382 new_score = new_score * 2383 if row.saturatedFat >= 1.35 and row.saturatedFat <= 4.05:384 new_score = new_score * 1.2385 if row.saturatedFat > 4.05:386 new_score = new_score * 0.1387 if row.fibers < 1.65:388 new_score = new_score * 0.1389 if row.fibers >= 1.65 and row.fibers <= 4.95:390 new_score = new_score * 1.2391 if row.fibers > 4.95:392 new_score = new_score * 2393 return new_score394 def rescoreU30(row):395 new_score = row.score396 if row.carbohydrates > 54:397 new_score = new_score * 2398 if row.carbohydrates >= 18 and row.carbohydrates <= 54:399 new_score = new_score * 1.2400 if row.carbohydrates < 18:401 new_score = new_score * 0.1402 if row.proteins < 3.35:403 new_score = new_score * 0.1404 if row.proteins >= 3.35 and row.proteins <= 10.05:405 new_score = new_score * 1.2406 if row.proteins > 10.05:407 new_score = new_score * 2408 if row.fibers < 1.65:409 new_score = new_score * 0.1410 if row.fibers >= 1.65 and row.fibers <= 4.95:411 new_score = new_score * 1.2412 if row.fibers > 4.95:413 new_score = new_score * 2414 return new_score415 def rescoreU40(row):416 new_score = row.score417 if row.proteins < 3.35:418 new_score = new_score * 0.1419 if row.proteins >= 3.35 and row.proteins <= 10.05:420 new_score = new_score * 1.2421 if row.proteins > 10.05:422 new_score = new_score * 2423 if row.fat < 4.65:424 new_score = new_score * 2425 if row.fat >= 4.65 and row.fat <= 13.95:426 new_score = new_score * 1.2427 if row.fat > 13.95:428 new_score = new_score * 0.1429 return new_score430 def rescoreU60(row):431 new_score = row.score432 if row.fibers < 1.65:433 new_score = new_score * 0.1434 if row.fibers >= 1.65 and row.fibers <= 4.95:435 new_score = new_score * 1.2436 if row.fibers > 4.95:437 new_score = new_score * 2438 if row.fat < 4.65:439 new_score = new_score * 2440 if row.fat >= 4.65 and row.fat <= 13.95:441 new_score = new_score * 1.2442 if row.fat > 13.95:443 new_score = new_score * 0.1444 return new_score445 def rescoreO60(row):446 new_score = row.score447 if row.proteins < 3.35:448 new_score = new_score * 0.1449 if row.proteins >= 3.35 and row.proteins <= 10.05:450 new_score = new_score * 1.2451 if row.proteins > 10.05:452 new_score = new_score * 2453 if row.calories < 133.35:454 new_score = new_score * 0.1455 if row.calories >= 133.35 and row.calories <= 400.05:456 new_score = new_score * 1.2457 if row.calories > 400.05:458 new_score = new_score * 2459 return new_score460 def score(row):461 score = row.ratingValue * np.log10(row.ratingCount)462 return score463 df['score'] = df.apply(score, axis=1)464 # calcolo medie prima di 'tagliare' il DataFrame465 #sugarAvg = df.sugars.mean()466 #sugarStd = df.sugars.std()467 #proteinsAvg = df.proteins.mean()468 #proteinsStd = df.proteins.std()469 #caloriesAvg = df.calories.mean()470 #caloriesStd = df.calories.std()471 #fatAvg = df.fat.mean()472 #fatStd = df.fat.std()473 #sFatAvg = df.saturatedFat.mean()474 #sFatStd = df.saturatedFat.std()475 sodiumAvg = df.sodium.mean()476 sodiumStd = df.sodium.std()477 #carbsAvg = df.carbohydrates.mean()478 #carbsStd = df.carbohydrates.std()479 #fiberAvg = df.fibers.mean()480 #fiberStd = df.fibers.std()481 # accorgimenti parametri482 n = int(request.args.get('n')) if (request.args.get('n') != None) else -1483 recipeName = request.args.get('recipeName')484 ingredient = request.args.get('ingredient')485 category = request.args.get('category')486 cost = request.args.get('cost')487 isLowNickel = int(request.args.get('isLowNickel')) if (request.args.get('isLowNickel') != None) else ''488 isVegetarian = int(request.args.get('isVegetarian')) if (request.args.get('isVegetarian') != None) else ''489 isLactoseFree = int(request.args.get('isLactoseFree')) if (request.args.get('isLactoseFree') != None) else ''490 isGlutenFree = int(request.args.get('isGlutenFree')) if (request.args.get('isGlutenFree') != None) else ''491 isLight = int(request.args.get('isLight')) if (request.args.get('isLight') != None) else ''492 user_difficulty = int(request.args.get('difficulty')) if (request.args.get('difficulty') != None) else ''493 goal = int(request.args.get('goal')) if (request.args.get('goal') != None) else ''494 user_cost = int(request.args.get('user_cost')) if (request.args.get('user_cost') != None) else ''495 user_time = int(request.args.get('user_time')) if (request.args.get('user_time') != None) else ''496 # age = int(request.args.get('age')) if (request.args.get('age') != None) else ''497 age = request.args.get('age')498 # orario499 hour = request.args.get('hour')500 # mood501 mood = request.args.get('mood')502 activity = request.args.get('activity')503 stress = request.args.get('stress')504 sleep = request.args.get('sleep')505 depression = request.args.get('depression')506 # overweight = request.args.get('overweight')507 # underweight = request.args.get('underweight')508 #height = request.args.get('height')509 #weight = request.args.get('weight')510 #bmi = weight / (height * height)511 bmi = float(request.args.get('fatclass')) if (request.args.get('fatclass') != None) else ''512 healthy = request.args.get('healthy')513 # filtro il DF sulle ricette salutari514 # https://acmrecsys.github.io/rsss2019/Food-Recommender-ctrattner.pdf515 if healthy == 'high':516 # print("healthy: ", healthy)517 df = df[(df.sugars <= 5) & (df.fat <= 3) & (df.saturatedFat <= 1.5)]518 if healthy == 'medium':519 # print("healthy: ", healthy)520 df = df[(df.sugars >= 5) & (df.sugars <= 15) &521 (df.fat >= 3) & (df.fat <= 20) &522 (df.saturatedFat >= 1.5) & (df.saturatedFat <= 5)523 ]524 if healthy == 'low':525 # print("healthy: ", healthy)526 df = df[(df.sugars >= 15) & (df.fat >= 20) & (df.saturatedFat > 5) & (df.sodium >= 1.5)]527 # filtro il DataFrame su nome della ricetta cercata528 if recipeName:529 # print("recipeName: " + recipeName)530 df = df[df.title.str.contains(recipeName, case=False)]531 # filtro il DataFrame su ingrediente della ricetta cercato532 if ingredient:533 # print("ingredient: " + ingredient)534 df = dfFromIngredient(df, ingredient)535 # categories = df.category.unique()536 # ['Dolci', 'Primi piatti', 'Lievitati', 'Salse e Sughi', 'Piatti Unici', 'Contorni', 'Antipasti', 'Secondi piatti', 'Torte salate', 'Bevande', 'Insalate', 'Marmellate e Conserve']537 if category:538 # print('category: ' + category)539 df = df[df.category == category]540 # cost = df.cost.unique()541 # ['Molto basso', 'Medio', 'Basso', 'None', 'Elevato', 'Molto elevata']542 if cost:543 # print("cost: " + cost)544 df = df[df.cost == cost]545 if isLowNickel:546 # print("isLowNickel: " + str(isLowNickel))547 df = df[df.isLowNickel == isLowNickel]548 if isVegetarian:549 # print("isVegetarian: " + str(isVegetarian))550 df = df[df.isVegetarian == isVegetarian]551 if isLactoseFree:552 # print("isLactoseFree: " + str(isLactoseFree))553 df = df[df.isLactoseFree == isLactoseFree]554 if isGlutenFree:555 # print("isGlutenFree: " + str(isGlutenFree))556 df = df[df.isGlutenFree == isGlutenFree]557 if isLight:558 # print("isLight: " + str(isLight))559 df = df[df.isLight == isLight]560 # if overweight:561 # print('overweight:', overweight)562 # df.score = df.apply(rescoreOverweight, axis=1)563 # df = df.sort_values('score', ascending=False)564 # print(df[['title', 'score']].head(10))565 # if underweight:566 # print('underweight: ', underweight)567 # df.score = df.apply(rescoreUnderweight, axis=1)568 # df = df.sort_values('score', ascending=False)569 # print(df[['title', 'score']].head(10))570 bmiWeight = 'normal'571 if bmi < 19:572 bmiWeight = 'under'573 df.score = df.apply(rescoreUnderweight, axis=1)574 elif bmi >= 25 and bmi < 30:575 bmiWeight = 'over'576 df.score = df.apply(rescoreOverweight, axis=1)577 elif bmi >= 30 and bmi < 35:578 bmiWeight = 'over'579 df.score = df.apply(rescoreObesity, axis=1)580 elif bmi >= 35:581 bmiWeight = 'over'582 df.score = df.apply(rescoreObesityPlus, axis=1)583 df = df.sort_values('score', ascending=False)584 if mood == 'bad':585 # print('mood: bad')586 # print("sugarAvg: " + str(sugarAvg))587 # df = df[df.sugar > sugarAvg]588 df.score = df.apply(rescoreMoodBad, axis=1)589 df = df.sort_values('score', ascending=False)590 # print(df[['title', 'score']].head(10))591 if activity == 'medium':592 df.score = df.apply(rescoreActivityMedium, axis=1)593 df = df.sort_values('score', ascending=False)594 if activity == 'high':595 # print('activity: high')596 # print("caloriesAvg: " + str(caloriesAvg))597 # print("proteinsAvg: " + str(proteinsAvg))598 # df = df[(df.calories > caloriesAvg) & (df.proteins > proteinsAvg)]599 df.score = df.apply(rescoreActivityHigh, axis=1)600 df = df.sort_values('score', ascending=False)601 # print(df[['title', 'score']].head(10))602 # stress => cibo salato (https://www.nutritestesso.it/it/lo-stretto-legame-cibo-ed-emozioni/)603 if stress == 'yes':604 # print('stress : ' + str(stress))605 # print("sodiumAvg: " + str(sodiumAvg))606 # df = df[df.sodium > sodiumAvg]607 df['antistress'] = df.ingredients.apply(isAntistress)608 df.score = df.apply(rescoreStress, axis=1)609 df.score = df.apply(rescoreCoffe, axis=1)610 df = df.sort_values('score', ascending=False)611 # print(df[['title', 'score']].head(10))612 # poco sonno => mangia magnesio613 if sleep == 'low':614 # print("sleep: " + sleep)615 # df = df[df.magnesium > 0]616 df['magnesium'] = df.ingredients.apply(isRichMagnesium)617 df.score = df.apply(rescoreMagnesium, axis=1)618 df.score = df.apply(rescoreCoffe, axis=1)619 df.score = df.apply(rescoreSleep, axis=1)620 # sera => ricalcolo il caffe621 if hour == 'evening':622 # print ("hour: " + hour)623 df.score = df.apply(rescoreCoffe, axis=1)624 # depressione => meno grassi625 if depression == 'yes':626 # print ("depression: " + depression)627 # print("fatAvg: " + str(fatAvg))628 # df = df[df.fat < fatAvg]629 df['magnesium'] = df.ingredients.apply(isRichMagnesium)630 df.score = df.apply(rescoreDepression, axis=1)631 df.score = df.apply(rescoreCoffe, axis=1)632 df.score = df.apply(rescoreMagnesium, axis=1)633 df = df.sort_values('score', ascending=False)634 # print(df[['title', 'score']].head(10))635 if user_difficulty != '':636 # print ('user_difficulty: ', user_difficulty)637 df.score = df.apply(rescoreDifficulty, difficulty=user_difficulty, axis=1)638 df = df.sort_values('score', ascending=False)639 # print(df[['title', 'score']].head(10))640 if goal != '':641 # print ('goal: ', goal)642 # se vuole prendere peso e non è sovrappeso643 if (bmiWeight != 'over' and goal == 1):644 # if((not(overweight)) and goal == 1):645 df.score = df.apply(rescoreGoalPlus, axis=1)646 # se vuole perdere peso e non è sottopeso647 if (bmiWeight != 'under' and goal == -1):648 df.score = df.apply(rescoreGoalMinus, axis=1)649 df = df.sort_values('score', ascending=False)650 if user_cost != '':651 # print ('user_cost: ', user_cost)652 df.score = df.apply(rescoreCost, cost=user_cost, axis=1)653 df = df.sort_values('score', ascending=False)654 if user_time != '':655 # print ('user_time: ', user_time)656 df.score = df.apply(rescoreTime, time=user_time, axis=1)657 df = df.sort_values('score', ascending=False)658 # print ('age: ', age)659 if age == 'U20':660 df.score = df.apply(rescoreU20, axis=1)661 elif age == 'U30':662 df.score = df.apply(rescoreU30, axis=1)663 elif age == 'U40':664 df.score = df.apply(rescoreU40, axis=1)665 elif age == 'U60':666 df.score = df.apply(rescoreU60, axis=1)667 elif age == 'O60':668 df.score = df.apply(rescoreO60, axis=1)669 df = df.sort_values('score', ascending=False)670 # print(len(df))671 return df.head(n).sample(frac=1).to_json(orient='split')672api.add_resource(Mood, '/mood/')673if __name__ == '__main__':...
minmax_play.py
Source:minmax_play.py
1#!/usr/bin/env python2# encoding: utf-83# from evaluate import evaluate_line4from table import TABLE,row,col, black, white,space5from copy import deepcopy6import random7import numpy as np8from value_function import NODE9import value_function10from vv import values11vv={'l2a': 90, 'l2c': 60, 'l2b': 75, 'l3b': 7500, 'd': 0, 'l3a': 8600, 'l4': 200000, 'w': 1000000, 'l1': 3, 'd4': 5000, 'd2': 5, 'd3': 100, 'd1': 1}12values[(1, 0, 0, 0, 1, 1, 0, 0, 1)]='l2a'13values[()]='d'14values[(1, 0, 0, 1, 1, 0, 0, 0, 1)]='l2a'15from newmethod import returnrowvalue16import pygame17count = 018fastScore = [0, 1, 10, 100, 1000, 99999]19def evaluate_line(line):20 status = 121 score = {1:[0, 0], -1:[0, 0]}22 for _ in range(2):23 for i in range(0, len(line)-4):24 tlist = line[i:i+5]25 if -status not in line[i:i+5]:26 tsum = list(tlist).count(status)27 score[status][0] += fastScore[tsum]28 if tsum >= 4:29 score[status][1] += 5030 status = -status31 return score32def evaluate(new_table, status):33 vecs = []34 # 1.1 '---' *1535 for i in xrange(0, row):36 vecs.append(new_table[i])37 # 1.2 '|' * 1538 for j in xrange(0, col):39 vecs.append([new_table[i][j] for i in range(0, row)])40 # 1.3 '\' *2141 vecs.append([new_table[x][x] for x in range(0, row)])42 for i in xrange(1, row - 4):43 vec = [new_table[x][x - i] for x in range(i, row)]44 vecs.append(vec)45 vec = [new_table[y - i][y] for y in range(i, col)]46 vecs.append(vec)47 # print [(y-i,y) for y in range(i, col)]48 # 1.4 '/'*2149 # vecs.append([new_tab;e[x][row-x-1] for x in range(0, row)])50 # print [(x, row-x-1) for x in xrange(0, row)]51 for i in xrange(4, row - 1):52 vec = [new_table[x][i - x] for x in xrange(i, -1, -1)]53 vecs.append(vec)54 vec = [new_table[x][col - x + row - i - 2] for x in xrange(row - i - 1, row)]55 vecs.append(vec)56 # print [(x,i-x) for x in xrange(i,-1,-1)]57 # print [(x,col-x+row-i-2) for x in xrange(row-i-1, row)]58 table_score = 059 for vec in vecs:60 score = evaluate_line(vec)61 if status == black:62 table_score += score[white][0] - score[black][0] - score[black][1]63 else:64 table_score += score[black][0] - score[white][0] - score[white][1]65 return table_score * (random.random() * 0.2 + 0.9)66def get_score2(current_table, status):67 '''68 score = 069 table_list = returnrowvalue(node.table.table, node.status)70 for key in table_list:71 score += vv[key] * table_list[key]72 another_list = returnrowvalue(node.table.table, -node.status)73 # for key in another_list:74 # score -= vv[key] * another_list[key]75 return score76 '''77 return - evaluate(current_table, status)78def get_score(current_table, status):79 score = 080 table_list = returnrowvalue(current_table, status)81 for key in table_list:82 score += vv[key] * table_list[key]83 another_list = returnrowvalue(current_table, status)84 for key in another_list:85 score -= vv[key] * another_list[key]86 return score87def generate_node(table, status, deep, temp, next_node, dist=2):88 # print "origin table", table89 if status == white:90 next_status = black91 else:92 next_status = white93 # print "1:", table[6]94 new_table = table + []95 # print "2:", table[6]96 x = next_node[0]97 y = next_node[1]98 new_table[x][y] = status99 # print "3:", table[6]100 new_deep = deep + 1101 new_temp = temp + []102 for k in range(max(x - dist, 0), min(x + dist + 1, 15)):103 for m in range(max(y - dist, 0), min(y + dist + 1, 15)):104 if new_table[k][m] == space and (k, m) not in new_temp:105 new_temp.append((k, m))106 if (x, y) in new_temp:107 new_temp.remove((x, y))108 # print "new_table1", new_table109 return new_table, new_deep, next_status, new_temp110def alphaBeta(table, status, deep, temp, level_num, game, dist=2, alpha=-1000000, beta=1000000):111 global count112 count += 1113 if deep >= level_num:114 score = get_score2(table, status)115 # print score116 return score117 for next_node in temp:118 Cx = next_node[0]119 Cy = next_node[1]120 xx = game.chessboard.start_x + Cy * game.chessboard.grid_size121 yy = game.chessboard.start_y + Cx * game.chessboard.grid_size122 pygame.draw.circle(game.screen, (255-80*deep, 80*deep, 255-80*deep), [xx, yy], game.chessboard.grid_size // 6)123 pygame.display.update()124 ttable = [x + [] for x in table]125 # print ttable126 new_table, new_deep, new_status, new_temp = generate_node(ttable, status, deep, temp, next_node, dist)127 # print "new_table2", new_table128 new_score = -alphaBeta(new_table, new_status, new_deep, new_temp, level_num, game, dist, -beta, -alpha)129 if new_score > beta:130 return new_score131 if new_score > alpha:132 alpha = new_score133 pos_i = next_node[0]134 pos_j = next_node[1]135 if deep == 0:136 return pos_i, pos_j137 return alpha138def new_alphabeta(table, status, deep, temp, level_num, game, dist=2, alpha=-1000000, beta=1000000):139 global count140 count += 1141 if deep >= level_num:142 score = get_score2(table, status)143 # print score144 return score145 print "deep0:", deep146 if deep == 0:147 num_remain = len(temp) / 2 + 1148 temp_dict = dict()149 small_score = 1000000150 small_index = -1000000151 print "temp0", temp152 for next_node in temp:153 print "next_node", next_node154 print "deep", deep155 Cx = next_node[0]156 Cy = next_node[1]157 xx = game.chessboard.start_x + Cy * game.chessboard.grid_size158 yy = game.chessboard.start_y + Cx * game.chessboard.grid_size159 pygame.draw.circle(game.screen, (255 - 80 * deep, 80 * deep, 255 - 80 * deep), [xx, yy],160 game.chessboard.grid_size // 6)161 pygame.display.update()162 ttable = [x + [] for x in table]163 # print ttable164 new_table, new_deep, new_status, new_temp = generate_node(ttable, status, deep, temp, next_node, dist)165 print "new temp", new_temp166 print "new deep", new_deep167 # print "new_table2", new_table168 new_score = -new_alphabeta(new_table, new_status, new_deep, new_temp, level_num, game, dist, -beta, -alpha)169 if new_score >= beta:170 return new_score171 if deep == 0:172 if len(temp_dict) < num_remain:173 temp_dict[next_node] = new_score174 if new_score < small_score:175 small_score = new_score176 small_index = next_node177 else:178 if new_score > small_score:179 temp_dict[next_node] = new_score180 temp_dict.pop(small_index)181 small_index, small_score = min(temp_dict.items(), key=lambda x: x[1])182 if new_score >= alpha:183 alpha = new_score184 pos_i = next_node[0]185 pos_j = next_node[1]186 print "bingo"187 if deep == 0:188 return list(temp_dict.keys())189 return alpha190def new_alphabeta_final(table, status, deep, temp, level_num, game, dist=2, alpha=-1000000, beta=1000000):191 global count192 count += 1193 if deep >= level_num:194 score = get_score2(table, status)195 # print score196 return score197 print "deep0:", deep198 if deep == 0:199 num_remain = len(temp) / 2 + 1200 temp_dict = dict()201 small_score = 1000000202 small_index = -1000000203 print "temp0", temp204 for next_node in temp:205 print "next_node", next_node206 print "deep", deep207 Cx = next_node[0]208 Cy = next_node[1]209 xx = game.chessboard.start_x + Cy * game.chessboard.grid_size210 yy = game.chessboard.start_y + Cx * game.chessboard.grid_size211 pygame.draw.circle(game.screen, (255 - 80 * deep, 80 * deep, 255 - 80 * deep), [xx, yy],212 game.chessboard.grid_size // 6)213 pygame.display.update()214 ttable = [x + [] for x in table]215 # print ttable216 new_table, new_deep, new_status, new_temp = generate_node(ttable, status, deep, temp, next_node, dist)217 print "new temp", new_temp218 print "new deep", new_deep219 # print "new_table2", new_table220 new_score = -new_alphabeta(new_table, new_status, new_deep, new_temp, level_num, game, dist, -beta, -alpha)221 if new_score >= beta:222 return new_score223 if deep == 0:224 if len(temp_dict) < num_remain:225 temp_dict[next_node] = new_score226 if new_score < small_score:227 small_score = new_score228 small_index = next_node229 else:230 if new_score > small_score:231 temp_dict[next_node] = new_score232 temp_dict.pop(small_index)233 small_index, small_score = min(temp_dict.items(), key=lambda x: x[1])234 if new_score >= alpha:235 alpha = new_score236 pos_i = next_node[0]237 pos_j = next_node[1]238 print "bingo"239 if deep == 0:240 return pos_i, pos_j241 return alpha242def alpha_beta_prunning(table, status, deep, temp, level_num, game, dist=2, alpha=-1000000, beta=1000000):243 '''244 for i in range(1, level_num + 1):245 new_temp = new_alphabeta(table, status, deep, temp, i, game, dist, alpha=-1000000, beta=1000000)246 print "over", i247 temp = new_temp248 print temp249 '''250 new_temp = new_alphabeta(table, status, deep, temp, 2, game, dist, alpha=-1000000, beta=1000000)251 temp = new_temp252 print temp253 pos_i, pos_j = new_alphabeta_final(table, status, deep, temp, level_num, game, dist, alpha=-1000000, beta=1000000)254 return pos_i, pos_j255def new_negaScout(table, status, deep, temp, level_num, game, dist=2, alpha=-1000000, beta=1000000):256 global count257 count += 1258 if deep >= level_num:259 score = get_score2(table, status)260 # print score261 return score262 # print "deep0:", deep263 if deep == 0:264 num_remain = len(temp) / 2 + 1265 temp_dict = dict()266 small_score = 1000000267 small_index = -1000000268 first_next_node = temp[0]269 Cx = first_next_node[0]270 Cy = first_next_node[1]271 xx = game.chessboard.start_x + Cy * game.chessboard.grid_size272 yy = game.chessboard.start_y + Cx * game.chessboard.grid_size273 pygame.draw.circle(game.screen, (100, 100, 100), [xx, yy],274 game.chessboard.grid_size // 6)275 pygame.display.update()276 ttable = [x + [] for x in table]277 first_table, first_deep, first_status, first_temp = generate_node(ttable, status, deep, temp, first_next_node, dist)278 first_value = -negaScout(first_table, first_status, first_deep, first_temp, level_num, game, dist, -beta, -alpha)279 if first_value >= beta:280 return first_value281 if deep == 0:282 temp_dict[first_next_node] = first_value283 if first_value > alpha:284 alpha = first_value285 pos_i = first_next_node[0]286 pos_j = first_next_node[1]287 for i in range(0, len(temp)):288 next_node = temp[i]289 Cx = next_node[0]290 Cy = next_node[1]291 xx = game.chessboard.start_x + Cy * game.chessboard.grid_size292 yy = game.chessboard.start_y + Cx * game.chessboard.grid_size293 pygame.draw.circle(game.screen, (255-80*deep, 80*deep, 255-80*deep), [xx, yy], game.chessboard.grid_size // 6)294 pygame.display.update()295 ttable = [x + [] for x in table]296 # print ttable297 new_table, new_deep, new_status, new_temp = generate_node(ttable, status, deep, temp, next_node, dist)298 # print "new_table2", new_table299 new_score = -negaScout(new_table, new_status, new_deep, new_temp, level_num, game, dist, -alpha - 1, -alpha)300 if new_score > alpha and new_score < beta:301 new_score = -negaScout(new_table, new_status, new_deep, new_temp, level_num, game, dist, -beta, -alpha - 1)302 if new_score >= beta:303 return new_score304 if deep == 0:305 if len(temp_dict) < num_remain:306 temp_dict[next_node] = new_score307 if new_score < small_score:308 small_score = new_score309 small_index = next_node310 else:311 if new_score > small_score:312 temp_dict[next_node] = new_score313 temp_dict.pop(small_index)314 small_index, small_score = min(temp_dict.items(), key=lambda x: x[1])315 if new_score > alpha:316 alpha = new_score317 pos_i = next_node[0]318 pos_j = next_node[1]319 if deep == 0:320 return list(temp_dict.keys())321 return alpha322def negaScout(table, status, deep, temp, level_num, game, dist=2, alpha=-1000000, beta=1000000):323 global count324 count += 1325 if deep >= level_num:326 score = get_score2(table, status)327 # print score328 return score329 first_next_node = temp[0]330 Cx = first_next_node[0]331 Cy = first_next_node[1]332 xx = game.chessboard.start_x + Cy * game.chessboard.grid_size333 yy = game.chessboard.start_y + Cx * game.chessboard.grid_size334 pygame.draw.circle(game.screen, (100, 100, 100), [xx, yy],335 game.chessboard.grid_size // 6)336 pygame.display.update()337 ttable = [x + [] for x in table]338 first_table, first_deep, first_status, first_temp = generate_node(ttable, status, deep, temp, first_next_node, dist)339 first_value = -negaScout(first_table, first_status, first_deep, first_temp, level_num, game, dist, -beta, -alpha)340 if first_value >= beta:341 return first_value342 if first_value > alpha:343 alpha = first_value344 pos_i = first_next_node[0]345 pos_j = first_next_node[1]346 for i in range(0, len(temp)):347 next_node = temp[i]348 Cx = next_node[0]349 Cy = next_node[1]350 xx = game.chessboard.start_x + Cy * game.chessboard.grid_size351 yy = game.chessboard.start_y + Cx * game.chessboard.grid_size352 pygame.draw.circle(game.screen, (255-80*deep, 80*deep, 255-80*deep), [xx, yy], game.chessboard.grid_size // 6)353 pygame.display.update()354 ttable = [x + [] for x in table]355 # print ttable356 new_table, new_deep, new_status, new_temp = generate_node(ttable, status, deep, temp, next_node, dist)357 # print "new_table2", new_table358 new_score = -negaScout(new_table, new_status, new_deep, new_temp, level_num, game, dist, -alpha - 1, -alpha)359 if new_score > alpha and new_score < beta:360 new_score = -negaScout(new_table, new_status, new_deep, new_temp, level_num, game, dist, -beta, -alpha - 1)361 if new_score >= beta:362 return new_score363 if new_score > alpha:364 alpha = new_score365 pos_i = next_node[0]366 pos_j = next_node[1]367 if deep == 0:368 return pos_i, pos_j369 return alpha370def negaScout_prunning(table, status, deep, temp, level_num, game, dist=2):371 new_temp = new_negaScout(table, status, deep, temp, 1, game, dist, alpha=-1000000, beta=1000000)372 temp = new_temp373 # print temp374 pos_i, pos_j = negaScout(table, status, deep, temp, level_num, game, dist, alpha=-1000000, beta=1000000)375 return pos_i, pos_j376def alpha_beta(node, level_num, game, dist=2):377 # print "hahha"378 # print node.table.table379 pos_i, pos_j = negaScout_prunning(node.table.table, node.status, node.deep, node.table.temp, level_num, game, dist)380 # pos_i, pos_j = negaScout(node.table.table, node.status, node.deep, node.table.temp, level_num, game, dist)381 node.pos_i = pos_i382 node.pos_j = pos_j383 # print count...
test_league_rater.py
Source:test_league_rater.py
1import pytest2from service import config3from service.league_service.league_rater import LeagueRater4from service.league_service.typedefs import GameOutcome, LeagueScore5@pytest.fixture6def unplaced_player_score(example_league):7 return LeagueScore(8 division_id=None,9 score=None,10 game_count=example_league.placement_games - 1,11 returning_player=False12 )13def test_new_score_victory_no_boost(example_league):14 current_score = LeagueScore(15 division_id=2, score=5, game_count=30, returning_player=False16 )17 player_rating = (180.0, 0.0)18 new_score = LeagueRater.rate(19 example_league, current_score, GameOutcome.VICTORY, player_rating20 )21 assert new_score.division_id == current_score.division_id22 assert new_score.game_count == current_score.game_count + 123 assert new_score.score == current_score.score + config.SCORE_GAIN24 player_rating = (10.0, 0.0)25 new_score = LeagueRater.rate(26 example_league, current_score, GameOutcome.VICTORY, player_rating27 )28 assert new_score.division_id == current_score.division_id29 assert new_score.game_count == current_score.game_count + 130 assert new_score.score == current_score.score + config.SCORE_GAIN31def test_new_score_victory_boost(example_league):32 current_score = LeagueScore(33 division_id=2, score=5, game_count=30, returning_player=False34 )35 player_rating = (1800.0, 0.0)36 new_score = LeagueRater.rate(37 example_league, current_score, GameOutcome.VICTORY, player_rating38 )39 assert new_score.division_id == current_score.division_id40 assert new_score.game_count == current_score.game_count + 141 assert (42 new_score.score43 == current_score.score + config.SCORE_GAIN + config.POSITIVE_BOOST44 )45def test_new_score_defeat_no_boost(example_league):46 current_score = LeagueScore(47 division_id=2, score=5, game_count=30, returning_player=False48 )49 player_rating = (180.0, 0.0)50 new_score = LeagueRater.rate(51 example_league, current_score, GameOutcome.DEFEAT, player_rating52 )53 assert new_score.division_id == current_score.division_id54 assert new_score.game_count == current_score.game_count + 155 assert new_score.score == current_score.score - config.SCORE_GAIN56 player_rating = (1800.0, 0.0)57 new_score = LeagueRater.rate(58 example_league, current_score, GameOutcome.DEFEAT, player_rating59 )60 assert new_score.division_id == current_score.division_id61 assert new_score.game_count == current_score.game_count + 162 assert new_score.score == current_score.score - config.SCORE_GAIN63def test_new_score_defeat_boost(example_league):64 current_score = LeagueScore(65 division_id=2, score=5, game_count=30, returning_player=False66 )67 player_rating = (60.0, 0.0)68 new_score = LeagueRater.rate(69 example_league, current_score, GameOutcome.DEFEAT, player_rating70 )71 assert new_score.division_id == current_score.division_id72 assert new_score.game_count == current_score.game_count + 173 assert (74 new_score.score75 == current_score.score - config.SCORE_GAIN - config.NEGATIVE_BOOST76 )77def test_new_score_victory_highest_division_no_boost(example_league):78 current_score = LeagueScore(79 division_id=3, score=5, game_count=30, returning_player=False80 )81 player_rating = (240.0, 0.0)82 new_score = LeagueRater.rate(83 example_league, current_score, GameOutcome.VICTORY, player_rating84 )85 assert new_score.division_id == current_score.division_id86 assert new_score.game_count == current_score.game_count + 187 assert new_score.score == current_score.score + config.SCORE_GAIN88def test_new_score_victory_highest_division_boost(example_league):89 current_score = LeagueScore(90 division_id=3, score=5, game_count=30, returning_player=False91 )92 player_rating = (380.0, 0.0)93 new_score = LeagueRater.rate(94 example_league, current_score, GameOutcome.VICTORY, player_rating95 )96 assert new_score.division_id == current_score.division_id97 assert new_score.game_count == current_score.game_count + 198 assert (99 new_score.score100 == current_score.score + config.SCORE_GAIN + config.HIGHEST_DIVISION_BOOST101 )102def test_placement_after_enough_games(example_league, unplaced_player_score):103 # Neutralize the offset in the placement function so we can test the score independently of the config settings104 rating = (150.0 - config.RATING_MODIFIER_FOR_PLACEMENT, 0.0)105 new_score = LeagueRater.rate(106 example_league, unplaced_player_score, GameOutcome.DRAW, rating107 )108 assert new_score.division_id == example_league.divisions[1].id109 assert new_score.game_count == unplaced_player_score.game_count + 1110 assert new_score.score == 5111def test_placement_returning_player(example_league):112 current_score = LeagueScore(113 division_id=None,114 score=None,115 game_count=example_league.placement_games_returning_player - 1,116 returning_player=True117 )118 rating = (150.0 - config.RATING_MODIFIER_FOR_PLACEMENT, 0.0)119 new_score = LeagueRater.rate(120 example_league, current_score, GameOutcome.DRAW, rating121 )122 assert new_score.division_id == example_league.divisions[1].id123 assert new_score.game_count == current_score.game_count + 1124 assert new_score.score == 5125def test_replacement_at_invalid_player_division(example_league):126 current_score = LeagueScore(127 division_id=999,128 score=4,129 game_count=example_league.placement_games,130 returning_player=False131 )132 rating = (150.0 - config.RATING_MODIFIER_FOR_PLACEMENT, 0.0)133 new_score = LeagueRater.rate(134 example_league, current_score, GameOutcome.DRAW, rating135 )136 assert new_score.division_id == example_league.divisions[1].id137 assert new_score.game_count == current_score.game_count + 1138 assert new_score.score == 5139def test_replacement_at_null_division(example_league):140 current_score = LeagueScore(141 division_id=None,142 score=4,143 game_count=example_league.placement_games,144 returning_player=False145 )146 rating = (150.0 - config.RATING_MODIFIER_FOR_PLACEMENT, 0.0)147 new_score = LeagueRater.rate(148 example_league, current_score, GameOutcome.DRAW, rating149 )150 assert new_score.division_id == example_league.divisions[1].id151 assert new_score.game_count == current_score.game_count + 1152 assert new_score.score == 5153def test_replacement_at_null_score(example_league):154 expected_division_id = example_league.divisions[1].id155 current_score = LeagueScore(156 division_id=expected_division_id,157 score=None,158 game_count=example_league.placement_games,159 returning_player=False160 )161 rating = (150.0 - config.RATING_MODIFIER_FOR_PLACEMENT, 0.0)162 new_score = LeagueRater.rate(163 example_league, current_score, GameOutcome.DRAW, rating164 )165 assert new_score.division_id == expected_division_id166 assert new_score.game_count == current_score.game_count + 1167 assert new_score.score == 5168def test_placement(example_league, unplaced_player_score):169 # Neutralize the offset in the placement function so we can test the score independently of the config settings170 rating = 150 - config.RATING_MODIFIER_FOR_PLACEMENT171 new_score = LeagueRater._do_placement(example_league, unplaced_player_score, rating)172 assert new_score.division_id == example_league.divisions[1].id173 assert new_score.game_count == unplaced_player_score.game_count + 1174 assert new_score.score == 5175def test_placement_high_rating(example_league, unplaced_player_score):176 rating = 1500 - config.RATING_MODIFIER_FOR_PLACEMENT177 new_score = LeagueRater._do_placement(example_league, unplaced_player_score, rating)178 assert new_score.division_id == example_league.divisions[-1].id179 assert new_score.game_count == unplaced_player_score.game_count + 1180 assert new_score.score == 10181def test_placement_low_rating(example_league, unplaced_player_score):182 rating = -500 - config.RATING_MODIFIER_FOR_PLACEMENT183 new_score = LeagueRater._do_placement(example_league, unplaced_player_score, rating)184 assert new_score.division_id == example_league.divisions[0].id185 assert new_score.game_count == unplaced_player_score.game_count + 1186 assert new_score.score == 0187def test_new_player(example_league):188 current_score = LeagueScore(189 division_id=None, score=None, game_count=0, returning_player=False190 )191 player_rating = (380.0, 0.0)192 new_score = LeagueRater.rate(193 example_league, current_score, GameOutcome.VICTORY, player_rating194 )195 assert new_score.division_id is None196 assert new_score.game_count == 1197 assert new_score.score is None198def test_placement_games(example_league):199 current_score = LeagueScore(200 division_id=None, score=None, game_count=5, returning_player=False201 )202 player_rating = (380.0, 0.0)203 new_score = LeagueRater.rate(204 example_league, current_score, GameOutcome.VICTORY, player_rating205 )206 assert new_score.division_id is None207 assert new_score.game_count == current_score.game_count + 1208 assert new_score.score is None209def test_promote(example_league):210 current_score = LeagueScore(211 division_id=2, score=10, game_count=30, returning_player=False212 )213 player_rating = (380.0, 0.0)214 new_score = LeagueRater.rate(215 example_league, current_score, GameOutcome.VICTORY, player_rating216 )217 assert new_score.division_id == 3218 assert new_score.game_count == current_score.game_count + 1219 assert new_score.score == config.POINT_BUFFER_AFTER_DIVISION_CHANGE220def test_demote(example_league):221 current_score = LeagueScore(222 division_id=2, score=0, game_count=30, returning_player=False223 )224 player_rating = (380.0, 0.0)225 new_score = LeagueRater.rate(226 example_league, current_score, GameOutcome.DEFEAT, player_rating227 )228 assert new_score.division_id == 1229 assert new_score.game_count == current_score.game_count + 1230 assert new_score.score == 10 - config.POINT_BUFFER_AFTER_DIVISION_CHANGE231def test_promote_in_highest_division(example_league):232 current_score = LeagueScore(233 division_id=3, score=10, game_count=30, returning_player=False234 )235 player_rating = (380.0, 0.0)236 new_score = LeagueRater.rate(237 example_league, current_score, GameOutcome.VICTORY, player_rating238 )239 assert new_score.division_id == current_score.division_id240 assert new_score.game_count == current_score.game_count + 1241 assert new_score.score == 10242def test_demote_in_lowest_division(example_league):243 current_score = LeagueScore(244 division_id=1, score=0, game_count=30, returning_player=False245 )246 player_rating = (380.0, 0.0)247 new_score = LeagueRater.rate(248 example_league, current_score, GameOutcome.DEFEAT, player_rating249 )250 assert new_score.division_id == current_score.division_id251 assert new_score.game_count == current_score.game_count + 1252 assert new_score.score == 0253def test_score_too_high(example_league):254 current_score = LeagueScore(255 division_id=2, score=14, game_count=30, returning_player=False256 )257 player_rating = (380.0, 0.0)258 new_score = LeagueRater.rate(259 example_league, current_score, GameOutcome.VICTORY, player_rating260 )261 assert new_score.division_id == 3262 assert new_score.game_count == current_score.game_count + 1263 assert new_score.score == config.POINT_BUFFER_AFTER_DIVISION_CHANGE264def test_score_too_low(example_league):265 current_score = LeagueScore(266 division_id=2, score=-14, game_count=30, returning_player=False267 )268 player_rating = (380.0, 0.0)269 new_score = LeagueRater.rate(270 example_league, current_score, GameOutcome.VICTORY, player_rating271 )272 assert new_score.division_id == 1273 assert new_score.game_count == current_score.game_count + 1274 assert new_score.score == 10 - config.POINT_BUFFER_AFTER_DIVISION_CHANGE275def test_other_game_outcomes(example_league):276 current_score = LeagueScore(277 division_id=2, score=4, game_count=30, returning_player=False278 )279 player_rating = (180.0, 0.0)280 new_score = LeagueRater.rate(281 example_league, current_score, GameOutcome.DRAW, player_rating282 )283 assert new_score.division_id == current_score.division_id284 assert new_score.game_count == current_score.game_count + 1285 assert new_score.score == current_score.score286 new_score = LeagueRater.rate(287 example_league, current_score, GameOutcome.MUTUAL_DRAW, player_rating288 )289 assert new_score.division_id == current_score.division_id290 assert new_score.game_count == current_score.game_count + 1291 assert new_score.score == current_score.score292 new_score = LeagueRater.rate(293 example_league, current_score, GameOutcome.UNKNOWN, player_rating294 )295 assert new_score.division_id == current_score.division_id296 assert new_score.game_count == current_score.game_count + 1297 assert new_score.score == current_score.score298 new_score = LeagueRater.rate(299 example_league, current_score, GameOutcome.CONFLICTING, player_rating300 )301 assert new_score.division_id == current_score.division_id302 assert new_score.game_count == current_score.game_count + 1...
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!