def delete_sang_song(request): if request.method == 'POST': try: temp = None try: temp = User.objects.get(userid=request.data['userid']) except Exception as e: MM.send(e, "account/delete_sang_song") if temp is not None: idx = 0 for song in temp.sang_songs: if request.data['songid'] == song['songid']: temp.sang_songs.pop(idx) break idx += 1 se = changeSangSongSerializer(temp, data=request.data) if se.is_valid(): se.update(temp, se.validated_data) return JsonResponse({'data': se.data}, status=status.HTTP_200_OK) else: return JsonResponse({'message': 'delete_sang_song'}, status=status.HTTP_400_BAD_REQUEST) except Exception as e: MM.send(e, "account/delete_sang_song") return JsonResponse({'message': 'delete_sang_song error'}, status=status.HTTP_404_NOT_FOUND)
def search(request, Page, Query): if(request.method == 'GET'): try: p = int(Page) ats = Artists.objects.filter(name__istartswith = Query).order_by('name')[p*30:(p*30)+30] artistse = ArtistsSerializer(ats, many=True) ts = Tracks.objects.filter(name__istartswith = Query).order_by('name')[p*30:(p*30)+30] track_name_se = TracksWAlbumSerializer(ts, many=True) track_artist_se = connectdb.get_data_track({'artists': {'$elemMatch' : {'name': {'$regex': '^'+Query, '$options':'i'}}}}, p*30, (p*30)+30) alts = Albums.objects.filter(name__istartswith = Query).order_by('name')[p*30:(p*30)+30] album_name_se = AlbumsSerializer(alts, many=True) album_artist_se = connectdb.get_data_album({'artists': {'$elemMatch' : {'name': {'$regex': '^'+Query, '$options':'i'}}}}, p*30, (p*30)+30) data = { 'artist': artistse.data, 'album' : { 'name' : album_name_se.data, 'artist' : album_artist_se }, 'track' : { 'name' : track_name_se.data, 'artist' : track_artist_se } } return JsonResponse({'data' : data}, status=status.HTTP_200_OK, safe=False) except Exception as e: MM.send(e, "music/search") return JsonResponse({'message': 'search error'}, status=status.HTTP_404_NOT_FOUND)
def add_pi_re_song(request): if request.method == 'POST': try: temp = None try: temp = User.objects.get(userid=request.data['userid']) except Exception as e: MM.send(e, "account/add_pi_re_song") if temp is not None: for req in request.data['pi_re_songs']: check = True for song in temp.pi_re_songs: if req['songid'] == song['songid']: check = False break if check: temp.pi_re_songs.append(req) #temp.re_songs.extend(request.data['pi_re_songs']) se = changePiReSongSerializer(temp, data=request.data) if se.is_valid(): se.update(temp, se.validated_data) return JsonResponse({'data': se.data}, status=status.HTTP_200_OK) else: return JsonResponse({'message': 'add_pi_re_song'}, status=status.HTTP_400_BAD_REQUEST) except Exception as e: MM.send(e, "account/add_pi_re_song") return JsonResponse({'message': 'add_pi_re_song error'}, status=status.HTTP_404_NOT_FOUND)
def Ejecuta(self): self.LastPos = MM.Calcula(self.SerMon, self.N, self.LastPos) if self.N < self.eNd: while self.N <= self.eNd: self.LastPos = MM.Calcula(self.SerMon, self.N, self.LastPos) A = LIA.PromVolt(self.SerAmp, self.NumAprom) self.ws.write(self.j, 0, self.N) self.ws.write(self.j, 1, A) self.N += self.Step self.j += 1 print "EL PASO ACTUAL ES: %f" % self.N print "El Promedio es: %f" % A print "los microspasos totales son: %d" % self.LastPos elif self.N > self.eNd: while self.N >= self.eNd: self.LastPos = MM.Calcula(self.SerMon, self.N, self.LastPos) A = LIA.PromVolt(self.SerAmp, self.NumAprom) self.ws.write(self.j, 0, self.N) self.ws.write(self.j, 1, A) self.N -= self.Step self.j += 1 print "EL PASO ACTUAL ES: %f" % self.N print "El Promedio es: %f" % A print "los microspasos totales son: %d" % self.LastPos else: return self.wb.save('test1.xls') self.N = 0 self.eNd = 0 self.Step = 0 self.NumAprom = 0.0
def get_pitch_file(request): if request.method == 'POST': try: temp = None try: temp = User.objects.get(userid=request.data['userid']) except Exception as e: MM.send(e, "account/get_pitch_file") if temp is not None: wase = WavFileSerializer(data={'file': request.data['file']}) if wase.is_valid(): wase.save() pitch = PitchTracking.get_pitch_file(request.data['file']) temp.pitch = pitch se = changePitchSerializer(temp, data={ 'userid': request.data['userid'], 'pitch': temp.pitch }) if se.is_valid(): se.update(temp, se.validated_data) return JsonResponse({'data': se.data}, status=status.HTTP_200_OK) else: return JsonResponse({'message': 'get_pitch_file'}, status=status.HTTP_400_BAD_REQUEST) except Exception as e: MM.send(e, "account/get_pitch_file") return JsonResponse({'message': 'get_pitch_file error'}, status=status.HTTP_400_BAD_REQUEST) return JsonResponse({'message': 'get_pitch_file error'}, status=status.HTTP_404_NOT_FOUND)
def pvpbattle(self, other): if self.SentChallenge != "": self.send(self.Username+',sendchal,,'+self.pokemons[0].name+","+str(self.pokemons[0].lvl)+","+str(self.pokemons[0].hp)+",") self.addtochat("Your challenge has been cancelled.") self.SentChallenge = "" self.addtochat("Now battling " + other) MM.play_music(MM.pvpbattle_file) self.flashscreen() self.BattlingPlayer = other self.enemypokemon = self.ChallengePokemon for a in xrange(0,4): self.GUIs[1].text["a"+str(a+1)].text = self.pokemons[0].moves[a].name gui.UpdateLabels(self) self.GUIs[1].pics["ppb"].image = GIFImage("sprites/back/"+str(self.pokemons[0].number).zfill(3)+".gif") self.GUIs[1].pics["epb"].image = GIFImage("sprites/front/"+str(self.enemypokemon.number).zfill(3)+".gif") self.GUIs[1].buttons["a2"].visible = False self.GUIs[1].text["a2"].visible = False self.GUIs[1].buttons["a3"].visible = False self.GUIs[1].text["a3"].visible = False self.GUIs[1].buttons["a4"].visible = False self.GUIs[1].text["a4"].visible = False if self.pokemons[0].lvl >= 10: self.GUIs[1].buttons["a2"].visible = True self.GUIs[1].text["a2"].visible = True if self.pokemons[0].lvl >= 20: self.GUIs[1].buttons["a3"].visible = True self.GUIs[1].text["a3"].visible = True if self.pokemons[0].lvl >= 30: self.GUIs[1].buttons["a4"].visible = True self.GUIs[1].text["a4"].visible = True self.CurrentGUI = 1 self.WildBattle = False
def album_one(request, Album_id): if(request.method == 'GET'): try: album = Albums.objects.get(id=Album_id) ser = AlbumsWTracksSerializer(album) return JsonResponse({'data' : ser.data }, status=status.HTTP_200_OK, safe=False) except Exception as e: MM.send(e, "music/album_one") return JsonResponse({'message': 'album_one error'}, status=status.HTTP_404_NOT_FOUND)
def track_one(request, Track_id): if(request.method == 'GET'): try: track = Tracks.objects.get(id=Track_id) ser = TracksWAlbumSerializer(track) return JsonResponse({'data' : ser.data}, status=status.HTTP_200_OK) except Exception as e: MM.send(e, "music/track_one") return JsonResponse({'message': 'track_one error'}, status=status.HTTP_404_NOT_FOUND)
def artist_search(request, Page, Query): if(request.method == 'GET'): try: p = int(Page) ats = Artists.objects.filter(name__istartswith = Query).order_by('name')[p*30:(p*30)+30] se = ArtistsSerializer(ats, many=True) return JsonResponse({'data' : se.data}, status=status.HTTP_200_OK, safe=False) except Exception as e: MM.send(e, "music/artist_search") return JsonResponse({'message': 'artist_search error'}, status=status.HTTP_404_NOT_FOUND)
def track_cluster(request, Page, Cluster): if(request.method == 'GET'): try: p = int(Page) ats = Tracks.objects.filter(cluster=Cluster).order_by('-popularity')[p*15:(p*15)+15] se = TracksWAlbumSerializer(ats, many=True) return JsonResponse({'data' : se.data}, status=status.HTTP_200_OK, safe=False) except Exception as e: MM.send(e, "music/track_cluster") return JsonResponse({'message': 'track_cluster error'}, status=status.HTTP_404_NOT_FOUND)
def artists_album(request, Page, Artist_id): if(request.method == 'GET'): try: p = int(Page) ats = Albums.objects.filter(artists={'id':Artist_id}).order_by('-release_date')[p*30:(p*30)+30] se = AlbumsSerializer(ats, many=True) return JsonResponse({'data' : se.data }, status=status.HTTP_200_OK, safe=False) except Exception as e: MM.send(e, "music/artists_ablum") return JsonResponse({'message': 'artists_album error'}, status=status.HTTP_404_NOT_FOUND)
def artist_popularity(request, Page): if(request.method == 'GET'): try: p = int(Page) ats = Artists.objects.all().order_by('-popularity')[p*30:(p*30)+30] se = ArtistsSerializer(ats, many=True) return JsonResponse({'data' : se.data }, status=status.HTTP_200_OK, safe=False) except Exception as e: MM.send(e, "music/artist_popularity") return JsonResponse({'message': 'artist_popularity error'}, status=status.HTTP_404_NOT_FOUND)
def __init__(self, term_file_path, train_term_file_path): """ :param term_file_path: 所有术语 文件路径 :param train_term_file_path: 训练文本中出现的术语 文件路径 :return: """ self.cw = MM.CutWord(term_file_path) self.terms = set(MM.load_file(term_file_path)) self.train_terms = set(MM.load_file(train_term_file_path)) print "词典中术语个数为:", self.terms.__len__() print "参与训练的术语个数为:", self.train_terms.__len__()
def WinBattle(lp): lp.addtochat(lp.enemypokemon.name + " has fainted.") lp.CurrentGUI = 0 lp.WildBattle = False lp.BattlingPlayer = "" lp.WAITING = False MM.changeMusic(lp.mapname) lp.playingBG = False lp.TrainerWildBattle = False lp.pokemons[0].addexp(lp.enemypokemon.lvl, lp) lp.save() lp.GUIs[1].pics["apb"].visible = False
def pitch_recommend(request): if(request.method == 'POST'): try: user = None try: user = User.objects.get(userid=request.data['userid']) users = User.objects.filter(pitch__range=(user.pitch - 300, user.pitch)) tlist = [] tracks = {} for u in users: if u.userid == request.data['userid']: continue for s in u.sang_songs: try: tracks[s['songid']] += 1 except: tracks[s['songid']] = 1 for t in tracks: ps = True for u in user.sang_songs: if str(t) == u['songid']: ps = False if ps: tlist.append(t) tlist = sorted(tlist, key=tracks.__getitem__, reverse=True) result = [] count = 0 for t in tlist: track = Tracks.objects.get(id=t) if track is not None: ser = TracksWAlbumSerializer(track) result.append(ser.data) count += 1 if count >= 12: break for req in result: check = True for song in user.pi_re_songs: if req['id'] == song['songid']: check = False break if check: user.pi_re_songs.append({'songid' : req['id']}) se = changePiReSongSerializer(user, data = request.data) if se.is_valid(): se.update(user, se.validated_data) return JsonResponse({'data': result}, status=status.HTTP_201_CREATED) except User.DoesNotExist: return JsonResponse({'message': 'pitch_recommend'}, status=status.HTTP_400_BAD_REQUEST) except Exception as e: MM.send(e, "account/pitch_recommend") return JsonResponse({'message': 'pitch_recommend'}, status=status.HTTP_404_NOT_FOUND)
def buttonClickHandleMore(self): self.Step = self.doubleSpinBox.value() self.LastNM += self.Step if self.Step == 0: return if self.LastNM > 1491: MM.init(self.Ser, 0) self.LastNM = 0 self.lcdNumber.display(self.LastNM) self.lineEdit.clear() return self.LastPos = MM.Calcula(self.Ser, self.LastNM, self.LastPos) self.lcdNumber.display(self.LastNM)
def buttonClickHandleMore(self): self.Step = self.doubleSpinBox.value() self.LastNM += self.Step if self.Step == 0: return if self.LastNM > 1491: MM.init(self.Ser, 0) self.LastNM = 0 self.lcdNumber.display(self.LastNM) self.lineEdit.clear() return self.LastPos = MM.Calcula(self.Ser,self.LastNM,self.LastPos); self.lcdNumber.display(self.LastNM)
def LoseBattle(lp): lp.addtochat("Your pokemon has fainted.") lp.x = 10005.0 lp.y = 10005.0 for a in lp.pokemons: a.hp = a.maxhp lp.CurrentGUI = 0 lp.WildBattle = False lp.WAITING = False MM.changeMusic(lp.mapname) lp.TrainerWildBattle = False lp.playingBG = False lp.save() lp.GUIs[1].pics["apb"].visible = False
def FleeBattle(lp): if lp.WildBattle or not lp.TrainerWildBattle: if lp.enemypokemon.lvl > lp.pokemons[0].lvl: lp.addtochat("Couldn't get away!") else: lp.CurrentGUI = 0 lp.WildBattle = False lp.BattlingPlayer = "" MM.changeMusic(lp.mapname) lp.playingBG = False lp.save() lp.GUIs[1].pics["apb"].visible = False else: lp.addtochat("You cannot run from a trainer!")
def get_user_info(request): if request.method == 'POST': try: temp = None try: temp = User.objects.get(userid=request.data['userid']) except Exception as e: MM.send(e, "account/get_user_info") if temp is not None: se = UserSerializer(temp) return JsonResponse({'data': se.data}, status=status.HTTP_200_OK) except Exception as e: MM.send(e, "account/get_user_info") return JsonResponse({'message': 'get_user_info error'}, status=status.HTTP_404_NOT_FOUND)
def id_check(request, Userid): if request.method == 'GET': try: temp = None try: if len(Userid) > 12: return JsonResponse({'message': False}, status=status.HTTP_406_NOT_ACCEPTABLE) temp = User.objects.get(userid=Userid) except User.DoesNotExist: return JsonResponse({'message': True}, status=status.HTTP_201_CREATED) return JsonResponse({'message': False}, status=status.HTTP_400_BAD_REQUEST) except Exception as e: MM.send(e, "account/id_check") return JsonResponse({'message': 'id_check error'}, status=status.HTTP_404_NOT_FOUND)
def login(request): if request.method == 'POST': try: temp = None try: temp = User.objects.get(userid=request.data['userid']) except Exception as e: MM.send(e, "account/login") if temp is not None: if temp.check_password(request.data['password']): return JsonResponse({'message': 'success'}, status=status.HTTP_200_OK) else: return JsonResponse({'message': 'pwd error'}, status=status.HTTP_401_UNAUTHORIZED) except Exception as e: MM.send(e, "account/login") return JsonResponse({'message': 'login error'}, status=status.HTTP_404_NOT_FOUND)
def buttonClickHandle(self): #while type(self.NM)!= float: try: self.NM = self.lineEdit.text() self.NM = float(self.NM); except (ValueError, TypeError): self.NM=0;return; if((self.NM < 1) or (self.NM > 1491)): MM.init(self.Ser, 0) self.lcdNumber.display(0) self.lineEdit.clear() self.NM=0 self.LastNM = self.NM return self.LastPos = MM.Calcula(self.Ser,self.NM,self.LastPos); self.lcdNumber.display(self.NM) self.LastNM = self.NM self.lineEdit.clear() self.NM=0
def mm_sloppy_plot(): """Plots trajectories of 'P' at different parameter values: a visual confirmation of parameter sloppiness""" # set up base system params = OrderedDict((('K',2.0), ('V',1.0), ('St',2.0), ('epsilon',1e-3), ('kappa',10.0))) # from Antonios' writeup true_params = np.array(params.values()) nparams = true_params.shape[0] transform_id = 't2' # set init concentrations S0 = params['St']; C0 = 0.0; P0 = 0.0 # init concentrations Cs0 = np.array((S0, C0, P0)) # set times at which to collect data tscale = (params['St'] + params['K'])/params['V'] # timescale of slow evolution npts = 20 times = tscale*np.linspace(1,npts,npts)/5.0 # use these params, concentrations and times to define the MM system MM_system = MM.MM_System(Cs0, times, true_params, transform_id) # define variables to test param1_name = 'epsilon' # nparam1s = 2 param1s = [0.01, 0.000001]#np.logspace(-1, -0.5, nparam1s) # # nparam2s = 1 param2_name = 'kappa' param2s = [10.0]#np.logspace(-2, 2, nparam2s) # param1_name = 'K' # # nparam1s = 3 # param1s = np.array((100,))#2*np.logspace(0, 3, nparam1s) # param2_name = 'V' # param2s = 3.0*param1s/10.0 + np.array((10, 0)) # set up figure, add true trajectory fig = plt.figure() ax = fig.add_subplot(111) ax.hold(True) ax.plot(times, MM_system.gen_profile(Cs0, times, true_params)[:,2], label='true params') markers = ['.', 'o', 'v', '^', 's', 'p', '*', 'x', '+', '_', 'D'] count = 0 # true_traj_squared_norm = np.power(np.linalg.norm(MM_system.gen_profile(Cs0, times, true_params)[:,2]), 2) # for recording relative as error, scale of_eval by this norm for param1 in param1s: for param2 in param2s: # update values params[param1_name] = param1 params[param2_name] = param2 # params['V'] = params['K']*3.0/10.0 S0 = params['St']; C0 = 0.0; P0 = 0.0 # init concentrations Cs0 = np.array((S0, C0, P0)) ax.plot(times, MM_system.gen_profile(Cs0, times, np.array(params.values()))[:,2], label=param1_name + '=' + str(param1) + ', ' + param2_name + '=' + str(param2) + ',error=' + str("%1.2e" % (np.power(MM_system.of(params.values()), 0.5)/npts)), marker=markers[count]) count = count + 1 ax.set_xlabel('time') ax.set_ylabel('P') # ax.set_title(r'$\frac{K}{V} = \frac{10}{3}$') ax.legend(fontsize=24, loc='lower right') plt.show()
def check_fruit(request, target): # import 학습 model # request에서 들어온 image 변환, 사이즈 input에 맞게 변환 try: img = cv2.imdecode(np.fromstring(request.FILES['image'].read(), np.uint8), cv2.IMREAD_COLOR) except Exception as e: MM.send(e, '\nimage files 확인 필요', "ai-images/predict/") shape = (200, 200) img = cv2.resize(img,shape) img = np.array([img]) # 결과값 바탕으로 T/F 반환 output = { 0:'apple',1:'banana',2:'mixed',3:'orange'} try: predict = reconstructed_model.predict(img) except Exception as e: MM.send(e, '\n AI detection 불가', "ai-images/predict/") return output[np.argmax(predict)] == target
def buttonClickHandle(self): #while type(self.NM)!= float: try: self.NM = self.lineEdit.text() self.NM = float(self.NM) except (ValueError, TypeError): self.NM = 0 return if ((self.NM < 1) or (self.NM > 1491)): MM.init(self.Ser, 0) self.lcdNumber.display(0) self.lineEdit.clear() self.NM = 0 self.LastNM = self.NM return self.LastPos = MM.Calcula(self.Ser, self.NM, self.LastPos) self.lcdNumber.display(self.NM) self.LastNM = self.NM self.lineEdit.clear() self.NM = 0
def get_user_pi_re_songs(request): if request.method == 'POST': try: temp = None try: temp = User.objects.get(userid=request.data['userid']) except Exception as e: MM.send(e, "account/get_user_pi_re_songs") if temp is not None: pi_re_songs = [] p = int(request.data['page']) for song in temp.pi_re_songs[p * 15:(p * 15) + 15]: pi_re_songs.append( TracksWAlbumSerializer( Tracks.objects.get(id=song['songid'])).data) return JsonResponse({'data': pi_re_songs}, status=status.HTTP_200_OK) except Exception as e: MM.send(e, "account/get_user_pi_re_songs") return JsonResponse({'message': 'get_user_pi_re_songs error'}, status=status.HTTP_404_NOT_FOUND)
def check_general(request, target): # import 학습 model # request에서 들어온 image 변환, 사이즈 input에 맞게 변환 try: img = cv2.imdecode(np.fromstring(request.FILES['image'].read(), np.uint8), cv2.IMREAD_COLOR) except Exception as e: MM.send(e, '\nimage files 확인 필요', "ai-images/predict/") shape = (32, 32) img = cv2.resize(img,shape) img = np.array([img]) img = img.astype('float32')/255 # 결과값 바탕으로 T/F 반환 output = { 0:'car', 1:'cat', 2:'dog', 3:'flower', 4:'motorbike', 5:'person'} predict = (reconstructed_model.predict(img) > 0.5).astype("int32") try: result = output[np.argmax(predict[0])] except Exception as e: MM.send(e, '\n AI detection 불가', "ai-images/predict/") return result == target
def wildbattle(self, enemyname, lvl, trainer = False, trainername = ""): if self.SentChallenge != "": self.send(self.Username+',sendchal,,'+self.pokemons[0].name+","+str(self.pokemons[0].lvl)+","+str(self.pokemons[0].hp)+",") self.addtochat("Your challenge has been cancelled.") self.SentChallenge = "" self.TrainerWildBattle = trainer pygame.mixer.music.stop() if self.TrainerWildBattle: self.addtochat("Foe %s sent out %s!" % (trainername,enemyname), True) else: self.addtochat("A wild %s has appeared!" % (enemyname,), True) MM.play_music(MM.battle_file) self.flashscreen() self.enemypokemon = pokelib.getPokemon(enemyname, lvl) for a in xrange(0,4): self.GUIs[1].text["a"+str(a+1)].text = self.pokemons[0].moves[a].name gui.UpdateLabels(self) self.GUIs[1].pics["ppb"].image = GIFImage("sprites/back/"+str(self.pokemons[0].number).zfill(3)+".gif") self.GUIs[1].pics["epb"].image = GIFImage("sprites/front/"+str(self.enemypokemon.number).zfill(3)+".gif") self.GUIs[1].buttons["a2"].visible = False self.GUIs[1].text["a2"].visible = False self.GUIs[1].buttons["a3"].visible = False self.GUIs[1].text["a3"].visible = False self.GUIs[1].buttons["a4"].visible = False self.GUIs[1].text["a4"].visible = False if self.pokemons[0].lvl >= 10: self.GUIs[1].buttons["a2"].visible = True self.GUIs[1].text["a2"].visible = True if self.pokemons[0].lvl >= 20: self.GUIs[1].buttons["a3"].visible = True self.GUIs[1].text["a3"].visible = True if self.pokemons[0].lvl >= 30: self.GUIs[1].buttons["a4"].visible = True self.GUIs[1].text["a4"].visible = True self.CurrentGUI = 1 self.WildBattle = True
def FMM_hit_me(): row_text = insert_text.get("0.0", "end") global on_hit if on_hit == False: # 从 False 状态变成 True 状态 on_hit = True start_time = time.clock() output_text.insert('insert', '(FMM)' + MM.fmm(row_text)) end_time = time.clock() else: # 从 True 状态变成 False 状态 on_hit = False output_text.insert('end','') # 设置 文字为空 seg_time = end_time - start_time Label(root, text='FMM分词所用时间为' + str(seg_time) + 's').pack()
def signup(request): if request.method == 'POST': try: temp = None try: temp = User.objects.get(userid=request.data['userid']) except User.DoesNotExist: if temp is None: se = SignUpSerializer(data=request.data) if se.is_valid(): se.save() return JsonResponse(se.data, status=status.HTTP_201_CREATED) else: return JsonResponse({'message': 'input error'}, status=status.HTTP_400_BAD_REQUEST) return JsonResponse({'message': 'already exist id'}, status=status.HTTP_400_BAD_REQUEST) except Exception as e: MM.send(e, "account/signup") return JsonResponse({'message': 'signup error'}, status=status.HTTP_404_NOT_FOUND)
def recommend(request): if(request.method == 'POST'): try: user = None try: user = User.objects.get(userid=request.data['userid']) results = connectdb.make_audio_feature(request.data['selectmusic']) data = [] for result in results: temp = [] for tid in result['data']: track = Tracks.objects.get(id = tid) if track is not None: se = TracksWAlbumSerializer(track) temp.append(se.data) data.append({'cluster': result['cluster'], 'data':temp}) return JsonResponse({'data': data}, status=status.HTTP_201_CREATED) except Exception as e: return JsonResponse({'message': 'recommend'}, status=status.HTTP_400_BAD_REQUEST) except Exception as e: MM.send(e, "account/recommend") return JsonResponse({'message': 'recommend'}, status=status.HTTP_404_NOT_FOUND)
def predict(request): result = {'ans': False} # category == 물건의 종류, title == 물건의 detail # print(request) # print(request.data) # print(request.FILES) # print(request.FILES['image']) try: keyword = request.data['category'] target = request.data['title'] except Exception as e: MM.send(e, '\nform-data 확인 필요', "ai-images/predict/") # 물건 종류에 따라 if문 model 분기 if keyword == 'fruit': result['ans'] = check_fruit(request, target) elif keyword == 'general': result['ans'] = check_general(request, target) # test용 print문. # qwnkld(request.FILES['image']) return JsonResponse(result)
def check_sloppiness(): """Checks for sloppiness in the model by printing the Hessian's eigenvalues when evaluated at the minimum of least-squares objective fn.""" # set parameters as per suggestions in paper # K = 1.0; V = 1.0; sigma = 1.0; epsilon = 1e-2; kappa = 10.0 # used in first param. transform/ation, now use St instead of sigma # params = np.array((K, V, sigma, epsilon, kappa)) # again, from old transformation # transform_id = 't1' K = 2.0; V = 1.0; St = 2.0; epsilon = 1e-3; kappa = 10.0 # from Antonios' writeup params = np.array((K, V, St, epsilon, kappa)) transform_id = 't2' sigma = St/K # set init concentrations S0 = K*sigma; C0 = 0.0; P0 = 0.0 # init concentrations Cs0 = np.array((S0, C0, P0)) # set times at which to collect data tscale = (sigma + 1)*K/V # timescale of slow evolution npts = 20 times = tscale*np.linspace(1,npts,npts)/5.0 # use these params, concentrations and times to define the MM system MM_system = MM.MM_System(Cs0, times, params, transform_id) # test stepsize's effect on hessian approx as the calculation seems prone to numerical errors nhvals = 20 hvals = np.logspace(-7,-4, nhvals) # numerical delta_h values that will be used in the finite-difference approximations m = 3 # the number of parameters of interest, i.e. '3' if only looking at the effects of K, V and sigma, otherwise '5' to look at effects of all parameters on the obj. fn. eigs = np.empty((nhvals, m)) for i in range(nhvals): hessian_eval = hessian(MM_system.of, params, h=hvals[i]) eigs[i] = np.sort(np.linalg.eigvalsh(hessian_eval[:m,:m])) # plot output fig = plt.figure() ax = fig.add_subplot(111) for i in range(m): ax.cla() ax.plot(hvals, eigs[:,i]) ax.yaxis.get_children()[1].set_size(16) ax.yaxis.get_major_formatter().set_powerlimits((0, 2)) ax.set_xscale('log') ax.set_ylabel('Eigenvalue ' + str(i + 1), fontsize=18) ax.set_xlabel('Finite difference approximation stepsize', fontsize=16) plt.tight_layout() # save in special directory if exists if os.path.isdir('./figs/hessian'): plt.savefig('./figs/hessian/all_eigs' + str(i) + '.png') else: plt.savefig('./all_eigs' + str(i) + '.png')
def RMM_hit_me(): row_text = insert_text.get("0.0", "end") row_text = row_text.replace('\n', '') # text1 = MM.bmm(u"判断当前字符串是否在词典中并不存在,若该字符串从头切割到尾都没有词典中的词则认为无法切割并且") # print text1 global on_hit if on_hit == False: # 从 False 状态变成 True 状态 on_hit = True start_time1 = time.clock() output_text.insert('insert', '(RMM)' + MM.rmm(row_text) + '\n') end_time1 = time.clock() else: # 从 True 状态变成 False 状态 on_hit = False output_text.insert('end', '') # 设置 文字为空 seg_time = end_time1 - start_time1 Label(root, text='RMM分词所用时间为' + str(seg_time) + 's').pack()
def sample_sloppy_params_ii(): """Uses mpi4py to parallelize the collection of sloppy parameter sets. The current, naive method is to sample over a noisy grid of points, discarding those whose objective function evaluation exceeds the set tolerance. The resulting sloppy parameter combinations are saved in './data/input'""" # init MPI comm = MPI.COMM_WORLD rank = comm.Get_rank() nprocs = comm.Get_size() # set up true system, basis for future objective function evaluations K_true = 2.0; V_true = 1.0; St_true = 4.0; epsilon_true = 1e-3; kappa_true = 10.0 # from Antonios' writeup sigma_true = St_true/K_true true_params = np.array((K_true, V_true, sigma_true, epsilon_true, kappa_true)) nparams = true_params.shape[0] transform_id = 't1' # set init concentrations S0_true = St_true; C0_true = 0.0; P0_true = 0.0 # init concentrations concs0_true = np.array((S0_true, C0_true, P0_true)) # set times at which to collect data tscale = (sigma_true + 1)*kappa_true/V_true # timescale of slow evolution print tscale npts = 10 times = np.linspace(tscale, 4*tscale, npts) # use these params, concentrations and times to define the MM system MM_system = MM.MM_System(concs0_true, times, true_params, transform_id) # visualize concentration profiles conc_profiles = MM_system.gen_profile(concs0_true, times, true_params) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(times, conc_profiles[:,0], label='S') ax.plot(times, conc_profiles[:,1], label='C') ax.plot(times, conc_profiles[:,2], label='P') # ax.plot(times, MM_system._data[:,0], label='S') # ax.plot(times, MM_system._data[:,1], label='C') # ax.plot(times, MM_system._data[:,2], label='P') ax.set_xlabel('times') ax.set_ylabel('concentration (potentially dimensionless)') ax.legend(loc=2) plt.show(fig)
color_id = 0 # One for each color redCircleColor = (0, 0, 255) redTextLocation = (10, 25) red_hue_min = 0 red_saturation_min = 80 red_value_min = 23 red_hsv_min = np.array([red_hue_min, red_saturation_min, red_value_min]) red_hue_max = 10 red_saturation_max = 256 red_value_max = 110 red_hsv_max = np.array([red_hue_max, red_saturation_max, red_value_max]) mm.append( MM.M_and_M(color_id, "Red", max_age, redCircleColor, red_hsv_min, red_hsv_max, redTextLocation)) # Create Red Tracking Object # BLUE color_id += 1 blueCircleColor = (255, 0, 0) blueTextLocation = (10, 50) blue_hue_min = 83 blue_saturation_min = 96 blue_value_min = 55 blue_hsv_min = np.array([blue_hue_min, blue_saturation_min, blue_value_min]) blue_hue_max = 143 blue_saturation_max = 251 blue_value_max = 167 blue_hsv_max = np.array([blue_hue_max, blue_saturation_max, blue_value_max])
def move(self): if (self.x % 1) or (self.y % 1): if self.moving == "up": self.y -= .125 elif self.moving == "down": self.y += .125 elif self.moving == "left": self.x -= .125 elif self.moving == "right": self.x += .125 elif self.moving == "": self.x = round(self.x) self.y = round(self.y) #self.send(self.Username+",posi,"+str(self.x)+","+str(self.y)+",") if not((self.x % 1) or (self.y % 1)): color = self.map.get_at((int(self.x),int(self.y))) if color.g > 200: if random.randint(0,10) == 0: self.wildbattle(pokelib.getWildPoke(), color.g-200) elif color.g == 100: self.wildbattle("Charmander", 100, True, "Gary") elif color.g == 101: self.wildbattle("Onyx", 12, True, "Brock") elif color.g == 102: if random.randint(0,5) == 0: self.wildbattle("Zubat", 10) elif color.g == 103: self.wildbattle("Zapdos", 100, True, "Steven") elif color.g == 104: self.wildbattle("Moltres", 100, True, "Matt") elif color.g == 105: self.wildbattle("Articuno", 100, True, "Patrick") elif color.g == 106: self.wildbattle("Togepi", 9999, True, "Mandi") elif color.b == 255: for a in self.pokemons: a.hp = a.maxhp self.addtochat("Your pokemon are back to full health!") elif color.b == 100: if PORTALS.has_key(str(self.x)+","+str(self.y)): self.x,self.y = PORTALS[str(self.x)+","+str(self.y)] self.moving = "down" elif color.r == 100: self.y += .125 if color.b == 101: self.GUIs[0].buttons["cpr"].visible = True self.GUIs[0].buttons["cpl"].visible = True else: self.GUIs[0].buttons["cpr"].visible = False self.GUIs[0].buttons["cpl"].visible = False for a in self.MapList: if a.isInside(self.x,self.y): if a.name != self.mapname: #PATRICKKKKKKKKKKKKK self.mapname = a.name MM.changeMusic(self.mapname) print self.mapname else: if (not self.movepress == "") and self.canmove(self.movepress): self.moving = self.movepress if self.moving == "up": self.y -= .125 elif self.moving == "down": self.y += .125 elif self.moving == "left": self.x -= .125 elif self.moving == "right": self.x += .125 self.send(self.Username+",posi,"+str(self.x)+","+str(self.y)+","+self.moving+",")