def _5train(f1out, eachfile, train, dirout_feature, f2resultOut, fin_model=None): ''' training the model ''' print('training on the model') dir_in = dirout_feature dirout = os.path.join(f2resultOut, eachfile) check_path(dirout) validate = {} validate['fin_pair'] = os.path.join(f1out, eachfile, 'validate.txt') validate['dir_in'] = dir_in onehot = True entry( dirout, train, dir_in, model_type=Param.CNN1D_OH, limit=0, onehot=onehot, kernel_size=90, epochs=80, # epochs=30, filters=300, batch_size=500, validate=validate, fin_model=fin_model)
def cvtrain(cv): modelreuse = True f2out = 'file/4train/5CV/elem' dirout_feature = '/home/jjhnenu/Data/SeqTMPPI2W/feature/129878/' f2resultOut = '/home/jjhnenu/Data/SeqTMPPI2W/result/5CV' # f2out = 'file/10humanTrain/4train/cross/group' # dirout_feature = '/home/jjhnenu/Data/SeqTMPPI2W/feature/129878/' # f2resultOut = '/home/jjhnenu/Data/SeqTMPPI2W/result/10humanTrain_80epoch/group_reusemodel_5CV' ''' cross train ''' oldfile = '-1' for elem in range(5): if elem == cv: continue f2dirout = os.path.join(f2resultOut, str(cv)) f3dirout = os.path.join(f2dirout, str(elem)) fin_model = os.path.join(f2dirout, oldfile, '_my_model.h5') if not os.access(fin_model, os.F_OK) or not modelreuse: fin_model = None train = os.path.join(f2out, '%d.txt' % elem) validate = {} validate['fin_pair'] = os.path.join(f2out, '%d.txt' % cv) validate['dir_in'] = dirout_feature onehot = True entry(f3dirout, train, dirout_feature, model_type=Param.CNN1D_OH, limit=0, onehot=onehot, kernel_size=90, epochs=80, # epochs=2, filters=300, batch_size=500, validate=validate, fin_model=fin_model) oldfile = str(elem)
def _7trainAndTest(dirout_feature, fin_train, fin_validate, dirout): # time 664909.4274818897 ~ 7.6 day ''' training the model ''' print('training on the model') check_path(dirout) validate = {} validate['fin_pair'] = fin_validate validate['dir_in'] = dirout_feature onehot = True entry( dirout, fin_train, dirout_feature, model_type=Param.CNN1D_OH, limit=0, onehot=onehot, kernel_size=90, epochs=80, # epochs=30, filters=300, batch_size=50, validate=validate) ''' testing on the model ''' print('testing the model')
def merchant_pick_name(self, resource, give_length_warning=False): """ Function to get the name of the merchant give_length_warning If true, this will specify the max text size as part of the title. """ self.menu_position = "pick name" self.selections["resource"] = resource #check that this does not already exist exists = False for firm_instance in self.solar_system_object_link.current_player.owned_firms.values( ): if isinstance(firm_instance, company.merchant): if firm_instance.from_location == self.selections[ "from_location"]: if firm_instance.to_location == self.selections[ "to_location"]: if firm_instance.resource == resource: exists = True if exists: print_dict = { "text": "A merchant from " + str(self.selections["from_location"].name) + " to " + str(self.selections["to_location"].name) + " trading " + str(resource) + " does already exist", "type": "general gameplay info" } self.solar_system_object_link.messages.append(print_dict) else: pygame.draw.rect(self.action_surface, (212, 212, 212), self.rect) pygame.draw.rect(self.action_surface, (0, 0, 0), self.rect, 2) pygame.draw.line(self.action_surface, (255, 255, 255), (self.rect[0], self.rect[1]), (self.rect[0] + self.rect[2], self.rect[1])) pygame.draw.line(self.action_surface, (255, 255, 255), (self.rect[0], self.rect[1]), (self.rect[0], self.rect[1] + self.rect[3])) text = global_variables.standard_font.render( "Choose name for merchant:", True, (0, 0, 0)) self.action_surface.blit(text, (self.rect[0] + 10, self.rect[1] + 10)) if give_length_warning: warning = global_variables.standard_font.render( "Name must be unique", True, (0, 0, 0)) self.action_surface.blit( warning, (self.rect[0] + 10, self.rect[1] + 50)) self.text_receiver = entry.entry( self.action_surface, topleft=(self.rect[0] + 10, self.rect[1] + 90), width=self.rect[3] - 20, max_letters=global_variables.max_letters_in_company_names) self.text_receiver.active = True self.ok_button = button.button("ok", self.action_surface, fixed_size=(100, 35), topleft=(self.rect[0] + 10, self.rect[1] + 150)) signaller.connect(self.ok_button, "signal__clicked", self.merchant_build)
def ask_company_name(self,give_warning=False): pygame.draw.rect(self.window, (212,212,212), self.gui_rect) title = global_variables.standard_font.render("Name of company:",True,(0,0,0)) self.window.blit(title, (self.gui_rect[0] + 10, self.gui_rect[1] + 10)) self.text_receiver = entry.entry(self.window, (self.gui_rect[0] + 10, self.gui_rect[1] + 45), self.gui_rect[2] - 20, global_variables.max_letters_in_company_names) self.buttons = {} self.buttons["ok"] = button.button( "ok", self.window, topleft = (self.gui_rect[0] + self.gui_rect[2] - 100,self.gui_rect[1] + self.gui_rect[3] - 40), fixed_size = None) signaller.connect(self.buttons["ok"],"signal__clicked",self.ask_company_capital) self.buttons["cancel"] = button.button( "cancel", self.window, topleft = (self.gui_rect[0] + self.gui_rect[2] - 65,self.gui_rect[1] + self.gui_rect[3] - 40), fixed_size = None) signaller.connect(self.buttons["cancel"],"signal__clicked",self.create_intro_gui); if give_warning: warning_label = global_variables.standard_font_small.render("No double space, no blanks",True,(0,0,0)) self.window.blit(warning_label, (self.gui_rect[0] + 10, self.gui_rect[1] + 90)) pygame.display.flip()
def iphoto_entries(): APPLE_BASE = 978307200 existingentries=[x.strip() for x in open(os.path.expanduser("~/bin/archive/iphotoguids")).readlines()] photos=plistlib.readPlist(os.path.expanduser("~/Pictures/iPhoto Library/AlbumData.xml")) eventsDict=dict([(x['RollID'], x['RollName']) for x in photos['List of Rolls']]) flaggedPhotoIds=[x for x in photos['List of Albums'] if x['AlbumName'] == 'Flagged'][0]['KeyList'] flaggedPhotos=[photos['Master Image List'][x] for x in flaggedPhotoIds] for p in flaggedPhotos: if p['GUID'] in existingentries: continue comment=p['Comment']+"\n" caption=p['Caption']+"\n" event=eventsDict[p['Roll']] text = "%s%sfrom %s" % (caption, comment, event) date = datetime.fromtimestamp(APPLE_BASE+p['DateAsTimerInterval']) path = p['ImagePath'] existingentries.append(p['GUID']) yield entry(text, date, picture=path, copy=True) guidfile=open(os.path.expanduser("~/bin/archive/iphotoguids"), "w") for guid in existingentries: guidfile.write(guid+"\n") guidfile.close()
def select_save_name(self, function_parameter=[]): """ Prompts the player to input the name of the savegame file """ pygame.draw.rect(self.action_surface, (150,150,150), self.rect) description = global_variables.standard_font.render("Enter savegame name:",True,(0,0,0)) self.action_surface.blit(description, (10 + self.rect[0], 10 + self.rect[1])) self.button_list_now = ["Empty space","Name box","Ok"] self.button_instances_now = {} self.button_instances_now["Name box"] = entry.entry(self.action_surface, topleft = (10 + self.rect[0], 10 + 40 + self.rect[1]), width = self.rect[2] - 20, max_letters = global_variables.max_letters_in_company_names) self.text_receiver = self.button_instances_now["Name box"] self.button_instances_now["Name box"].active = True self.button_instances_now["Ok"] = button.button( "Ok", self.action_surface, self.effectuate_save, function_parameter = None, fixed_size = (self.rect[2] - 20, 35), topleft = (10 + self.rect[0], 80 + 10 + self.rect[1]) ) pygame.display.flip()
def main(): if len(sys.argv) != 5: logging.info('please input args: car_path, road_path, cross_path, answerPath') exit(1) car_path = sys.argv[1] road_path = sys.argv[2] cross_path = sys.argv[3] answer_path = sys.argv[4] logging.info("car_path is %s" % (car_path)) logging.info("road_path is %s" % (road_path)) logging.info("cross_path is %s" % (cross_path)) logging.info("answer_path is %s" % (answer_path)) entry(car_path, road_path, cross_path, answer_path)
def tweet_entries(startdate, enddate): tweets_url="http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=joanna_m&count=200&exclude_replies=true&include_entities=true" tweet_xml=urllib.urlopen(tweets_url).read() tree=ET.fromstring(tweet_xml) entries=[] for status in tree: d=status.find('created_at').text tweet_datetime=datetime.strptime(d, '%a %b %d %H:%M:%S +0000 %Y') if tweet_datetime > enddate or tweet_datetime < startdate: continue tweet_text=status.find("text").text tweet_id=status.find("id").text for url in status.findall('entities/urls/url'): tweet_text.replace(url.find('url').text, "[%s](%s)" % (url.find('display_url').text, url.find('expanded_url').text)) try: pic=status.find('entities/media/creative') tweet_pic_url=pic.find('media_url').text tweet_text.replace(pic.find('url').text, "") (tweet_pic_file, info)=urllib.urlretrieve(tweet_pic_url) except: tweet_pic_file=None entries.append(entry(tweet_text, tweet_datetime, picture=tweet_pic_file)) return entries
def write(self): ordering = list(self._deletionNumbers) ordering.sort() ordering.reverse() for num in ordering: internal.CDFlib( internal.SELECT_, internal.ATTR_, num, internal.DELETE_, internal.ATTR_) self._deletionNumbers = [] for key in self._creationKeys: # Verify that the attribute values are coherent. # Unlike the special treatment for vAttributes, gAttributes # provide the list interface and thus the entry coercion works # natively. TODO Attribute/entry code is very confusing and # should be cleaned up. value = entry.entry(self[key]) # Assign a number. (attrNum, ) = internal.CDFlib( internal.CREATE_, internal.ATTR_, key, internal.GLOBAL_SCOPE) # Write it. if attrNum is not None: value.write( internal.gENTRY_, internal.gENTRY_DATA_, attrNum) self._globalScopeNamesToNumbers[key] = attrNum self._creationKeys = set()
def entries(cursor): for row in cursor: try: e = entry.entry(row["yaml"]) for key in ["id", "ash"]: if key in row: e[key] = row[key] yield e except Exception as ex: pass
def createCanvas(): newWindow = Toplevel() newWindow.geometry("500x500") newCanvas = canvas(newWindow, values_json["canvas"][0], values_json["canvas"][1]) entry1 = entry(newWindow, values_json["entry1"][0], newCanvas) entry1.render(values_json["entry1"][1]) buttonCanvas = button(newWindow, entry1.getTextVal, values_json["buttonCanvas"][0], values_json["buttonCanvas"][1])
def add_csv_to_database(csv_data): global TS entrylist = list() for line in csv_data[1:]: if (len(line) <= 0): continue entrylist.append(entry(line)) sht = sheet(entrylist, request.files['file'].filename) if (TS == None): TS = db.timesheet(DATABASE_NAME) TS.add_timesheet(sht)
def Value(self, j): o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) if o != 0: x = self._tab.Vector(o) x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 x = self._tab.Indirect(x) from entry import entry obj = entry() obj.Init(self._tab.Bytes, x) return obj return None
def old_twitter_entries(startdate, enddate): for file in glob("tweets/statuses/*"): tweet=json.load(open(file)) datestring=tweet['created_at'] date=datetime.strptime(datestring, '%a %b %d %H:%M:%S +0000 %Y') if date > enddate or date < startdate: continue if tweet['in_reply_to_status_id']: continue if tweet['in_reply_to_user_id']: continue text=tweet['text'] if re.search('^RT', text): continue if re.search(' RT', text): continue if re.search('\B@', text): continue for url in tweet['entities']['urls']: text.replace(url['url'], "[%s](%s)" % (url['display_url'], url['expanded_url'])) try: pic=[x for x in tweet['entities']['media'] if x['type'] == 'photo'][0] tweet_pic_url=pic['media_url'] if tweet_pic_url.find('campl.us') > -1: tweet_pic_url+=":800px" if tweet_pic_url.find('yfrog') > -1: tweet_pic_url+=":medium" text=text.replace(pic['url'], "") (pic_file, info)=urllib.urlretrieve(tweet_pic_url) except KeyError: try: if text.find('yfrog') > -1: url=re.search(r'(http:\/\/yfrog.com\/.*\b)', text).groups()[0] text=text.replace(url, "") (pic_file, info)=urllib.urlretrieve(url+":medium") elif text.find('campl.us') > -1: url=re.search(r'(http:\/\/campl.us\/.*\b)', text).groups()[0] text=text.replace(url, "") (pic_file, info)=urllib.urlretrieve(url+":800px") else: pic_file=None except AttributeError: print tweet yield entry(text, date, picture=pic_file)
def add_block(self, drivers, driver_private_keys, miner_public_key, miner_private_key): prev_hash = self.get_latest_block().get_block_hash() new_entry = entry(drivers) new_block = block(new_entry, len(self.chain), prev_hash, miner_public_key, driver_private_keys) new_block.mine_block(self.difficulty) new_block.generate_miner_signature(miner_private_key) self.chain.append(new_block)
def write(self): archive = self._variable._archive() if archive is not None: for key in self.keys(): # Verify that the attribute values are coherent. value = self[key] if isinstance(value, vAttribute): value = value._value value = entry.entry(value, simple = True) num = archive.attributes._number(key) if num is not None: value.write( self._variable._tokens['SELECT_ENTRY'], self._variable._tokens['GET_ENTRY'], num, self._variable._num)
def lt_reviews(startdate, enddate): lt_url="http://www.librarything.com/api_getdata.php?userid=Yarrow&key=2863435035&resultsets=books&booksort=entry_REV&max=100&reviewmax=10000&responseType=json&reviewsOnly=1&showReviews=1" lt_json_file=urllib.urlopen(lt_url) #lt_json_file=open("../../all_books") lt_file=json.load(lt_json_file) for review in lt_file['books'].values(): review_date=datetime.strptime(review['bookreview_date'], "%b %d, %Y") if review_date < startdate or review_date > enddate: continue review_text="Book review: %s by %s\n%s" % (review['title'], review['author_fl'], review['bookreview']) yield entry(review_text, review_date)
def create_genesis_block(self): if len(self.chain) == 0: genesis_key = "0" * 128 gen_driver = driver(genesis_key, "", "", "", datetime.now()) genesis_entry = entry([gen_driver]) prev_hash = "0" * 32 genesis_block = block(genesis_entry, 0, prev_hash, genesis_key, genesis_key, genesis=True) self.chain.append(genesis_block) else: raise Exception("chain already initialized")
def ask_company_capital(self,give_warning=False): if "country_window" in self.buttons and self.is_country: company_name = self.buttons["country_window"].selected elif self.text_receiver is not None and not self.is_country: company_name = self.text_receiver.text else: raise Exception("Could not figure out whether country or private company was selected") all_ok = True if not (0 < len(company_name) <= global_variables.max_letters_in_company_names): all_ok = False if company_name.find(" ") != -1: #somewhere it is used that there are two double spaces, so we can't allow that in a companyname all_ok = False if company_name in self.countries and not self.is_country: all_ok = False if all_ok: pygame.draw.rect(self.window, (212,212,212), self.gui_rect) title = global_variables.standard_font.render("Starting capital:",True,(0,0,0)) self.window.blit(title, (self.gui_rect[0] + 10, self.gui_rect[1] + 10)) self.text_receiver = entry.entry(self.window, (self.gui_rect[0] + 10, self.gui_rect[1] + 45), self.gui_rect[2] - 20, global_variables.max_letters_in_company_names, starting_text = "10000000") self.buttons = {} self.buttons["ok"] = button.button( "ok", self.window, topleft = (self.gui_rect[0] + self.gui_rect[2] - 100,self.gui_rect[1] + self.gui_rect[3] - 40), fixed_size = None) signaller.connect(self.buttons["ok"],"signal__clicked",self.start_new_game) self.buttons["cancel"] = button.button( "cancel", self.window, topleft = (self.gui_rect[0] + self.gui_rect[2] - 65,self.gui_rect[1] + self.gui_rect[3] - 40), fixed_size = None) signaller.connect(self.buttons["cancel"],"signal__clicked",self.create_intro_gui); self.company_name = company_name if give_warning: warning_label = global_variables.standard_font_small.render("Starting capital must be an",True,(0,0,0)) self.window.blit(warning_label, (self.gui_rect[0] + 10, self.gui_rect[1] + 90)) warning_label2 = global_variables.standard_font_small.render("integer above zero",True,(0,0,0)) self.window.blit(warning_label2, (self.gui_rect[0] + 10, self.gui_rect[1] + 100)) pygame.display.flip() else: self.ask_company_name(give_warning=True)
def lt_entries(startdate, enddate): lt_url=("http://www.librarything.com/api_getdata.php?userid=Yarrow&key=2863435035&booksort=entry_REV&max=1000&responseType=json") lt_json_file=urllib.urlopen(lt_url) #lt_json_file=open("../../all_books") lt_file=json.load(lt_json_file) books_by_date={} for book in lt_file['books'].values(): lt_date=datetime.strptime(book['entry_date'], "%b %d, %Y") try: books_by_date[lt_date].append(book) except KeyError: books_by_date[lt_date]=[book] entries=[] for date in books_by_date.keys(): if date < startdate or date > enddate: continue books=[] covers=[] for book in books_by_date[date]: try: covers.append(book['cover']) except KeyError: pass books.append("* %s by %s" % (book['title'], book['author_fl'])) book_text="Books entered on LibraryThing today:"+"\n"+"\n".join(books) if len(covers) > 0: covers_image=combine_covers(covers) else: covers_image=None #entries.append(entry(book_text, date, picture=covers_image)) yield entry(book_text, date, picture=covers_image)
def upload_timesheetv1(): ''' The upload route accepts a posted csv file with employee timesheet info ''' global DATABASE_NAME global TS try: csv_data = request.files['file'].read().decode( encoding='utf-8').split('\r\n') entrylist = list() for line in csv_data[1:]: if (len(line) <= 0): continue entrylist.append(entry(line)) sht = sheet(entrylist, request.files['file'].filename) if (TS == None): TS = db.timesheet(DATABASE_NAME) TS.add_timesheet(sht) except Exception as e: abort(400, "{}".format(e)) return "200"
def search(self, query, params, page, pageSize=100): limits = " limit %d, %d" % ((page - 1) * pageSize, pageSize) c, matches = database.cursor(), [] for p in params: logging.debug(str(p) + ", " + str(type(params[0]))) c.execute(query + limits, params) lastExecuted = c._last_executed for row in c: try: e = entry.entry(row["yaml"]) e["id"] = row['problem_id'] e["ash"] = row['ash'] matches.append(e) except Exception as ex: logging.error("Bad YAML: %d" % row['problem_id']) c.execute("select FOUND_ROWS() fr") return { 'entries': matches, 'count': c.fetchone()["fr"], # 'q':lastExecuted }
def search(self, query, params, page, pageSize=100): limits = " limit %d, %d" % ((page-1)*pageSize, pageSize) c, matches = database.cursor(), [] for p in params: logging.debug(str(p) + ", " + str(type(params[0]))) c.execute(query + limits, params) lastExecuted = c._last_executed for row in c: try: e = entry.entry(row["yaml"]) e["id"] = row['problem_id'] e["ash"] = row['ash'] matches.append(e) except Exception as ex: logging.error("Bad YAML: %d" % row['problem_id']) c.execute("select FOUND_ROWS() fr") return { 'entries':matches, 'count': c.fetchone()["fr"], # 'q':lastExecuted }
def flickr_entries(startdate, enddate): flickr_url = "http://api.flickr.com/services/rest/?method=flickr.people.getPublicPhotos&api_key=382c1ef794af3d4fb4fa57380307d8a4&user_id=40259880%40N00&per_page=200&format=json&nojsoncallback=1" flickr_json_file = urllib.urlopen(flickr_url) flickr_file = json.load(flickr_json_file) for photo in flickr_file["photos"]["photo"]: id = photo["id"] details = json.load( urllib.urlopen( "http://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=382c1ef794af3d4fb4fa57380307d8a4&photo_id=%s&format=json&nojsoncallback=1" % id ) ) date = datetime.strptime(details["photo"]["dates"]["taken"], "%Y-%m-%d %H:%M:%S") if date < startdate or date > enddate: continue title = details["photo"]["title"]["_content"] description = details["photo"]["description"]["_content"] text = "%s\n%s" % (title, description) photo_url = "http://farm%s.static.flickr.com/%s/%s_%s_b.jpg" % ( photo["farm"], photo["server"], photo["id"], photo["secret"], ) (photo_location, info) = urllib.urlretrieve(photo_url) yield entry(text, date, picture=photo_location)
def crossTrain(dirout_feature,f2resultOut,modelreuse=True): ''' cross train and test ''' f1out = 'file/4train/' f2outdir = os.path.join(f1out, str(0)) fin_pair = os.path.join(f2outdir, 'all.txt') f2outdir = os.path.join(f1out, '5CV','data') check_path(f2outdir) train = os.path.join(f2outdir, 'train_vali.txt') test = os.path.join(f2outdir, 'test.txt') ratios_tvt = [5,1] f3outs = [train, test] # PairDealer().part(fin_pair,ratios_tvt,f3outs) ''' train model ''' f2outdir = os.path.join(f1out, '5CV','data') check_path(f2outdir) train = os.path.join(f2outdir, 'train_vali.txt') f2out = 'file/4train/5CV/elem' ratios_tvt = [1] * 5 f3outs = [os.path.join(f2out,'%d.txt'%x) for x in range(5)] # PairDealer().part(train,ratios_tvt,f3outs) limit = 0 # eachdir = 'benchmark' # dirout_feature = '/mnt/data/sunshiwei/Phsi_Blos/feature/%s/' % eachdir # f2resultOut = '/mnt/data/sunshiwei/SeqTMPPI2W/result/5CV_1' ''' cross train ''' for cv in range(5): oldfile = '-1' f2dirout = os.path.join(f2resultOut, str(cv)) fin_model = '' f3dirout='' for elem in range(5): if cv == elem:continue f3dirout = os.path.join(f2dirout,str(elem)) fin_model = os.path.join(f2dirout,oldfile,'_my_model.h5') if not os.access(fin_model,os.F_OK) or not modelreuse:fin_model=None train = os.path.join(f2out, '%d.txt'%elem) validate = {} validate['fin_pair'] = os.path.join(f2out, '%d.txt'%cv) validate['dir_in'] = dirout_feature onehot = False entry(f3dirout, train, dirout_feature, model_type=Param.CNN1D_OH, limit=0, onehot=onehot, kernel_size=90, epochs=80, # epochs=2, filters=300, batch_size=500, validate=validate, fin_model=fin_model) # entry(f3dirout, train, dirout_feature, model_type=Param.TRANSFORMER, limit=10, onehot=onehot, kernel_size=90, # # epochs=80, # epochs=2, # filters=300, batch_size=500, validate=validate, # fin_model=fin_model) # # oldfile = str(elem) # # print(f3dirout) calculateResults(f2dirout, f2dirout, resultfilename='result.csv') # eachdir = 'benchmark' # dirout_feature = '/mnt/data/sunshiwei/Phsi_Blos/feature/%s/' % eachdir # print('testing the model on test dataset') # fin_model = os.path.join(f2dirout, oldfile, '_my_model.h5') # fin_test = 'file/4train/5CV/data/test.txt' # dirout_result_test = '/mnt/data/sunshiwei/Phsi_Blos/result/5CV_1_test/%d'%cv # check_path(dirout_result_test) # savepredict(fin_test, dirout_feature, fin_model, dirout_result_test,batch_size=500,limit=2000,onehot = onehot) ''' testing on DIP all.txt in DIP/predict ''' # fin_test = 'file/8DIPPredict/predict/all.txt' # dirout_feature = '/mnt/data/sunshiwei/Phsi_Blos/feature/%s/' % 'DIP' # fin_model = os.path.join(f2dirout, oldfile, '_my_model.h5') # dirout_result_test = '/mnt/data/sunshiwei/Phsi_Blos/result/5CV_1_DIP/%d' % cv # check_path(dirout_result_test) # savepredict(fin_test, dirout_feature, fin_model, dirout_result_test, batch_size=500,onehot = onehot) ''' testing on DIP all.txt in DIP/data ''' # fin_test = 'file/8DIPPredict/data/all.txt' # dirout_feature = '/mnt/data/sunshiwei/Phsi_Blos/feature/%s/' % 'DIP' # fin_model = os.path.join(f2dirout, oldfile, '_my_model.h5') # dirout_result_test = '/mnt/data/sunshiwei/Phsi_Blos/result/5CV_1_DIP_posi/%d' % cv # check_path(dirout_result_test) # savepredict(fin_test, dirout_feature, fin_model, dirout_result_test, batch_size=500,onehot = onehot) ''' testing on all.txt in Imex ''' # fin_test = 'file/8ImexPredict/4pair.tsv' # dirout_feature = '/mnt/data/sunshiwei/Phsi_Blos/feature/%s/' % 'IMEx' # fin_model = os.path.join(f2dirout, oldfile, '_my_model.h5') # dirout_result_test = '/mnt/data/sunshiwei/Phsi_Blos/result/5CV_1_IMEx_posi/%d' % cv # check_path(dirout_result_test) # savepredict(fin_test, dirout_feature, fin_model, dirout_result_test, batch_size=500,onehot = onehot) ''' IMEx + - ''' # fin_test = 'file/8ImexPredict/predict/0/all.txt' # dirout_feature = '/mnt/data/sunshiwei/Phsi_Blos/feature/%s/' % 'IMEx' # fin_model = os.path.join(f2dirout, oldfile, '_my_model.h5') # dirout_result_test = '/mnt/data/sunshiwei/Phsi_Blos/result/5CV_1_IMEx/%d' % cv # check_path(dirout_result_test) # savepredict(fin_test, dirout_feature, fin_model, dirout_result_test, batch_size=500,onehot = onehot) ''' testing on DIP all.txt in DIP/data/Human ''' # for eachfile in ['Ecoli', 'Human', 'Mus', 'SC']: # fin_test = 'file/8DIPPredict/data/%s/2pair.tsv'%eachfile # dirout_feature = '/mnt/data/sunshiwei/Phsi_Blos/feature/%s/' % 'DIP' # fin_model = os.path.join(f2dirout, oldfile, '_my_model.h5') # dirout_result_test = '/mnt/data/sunshiwei/Phsi_Blos/result/5CV_1_DIP_%s/%d' % (eachfile,cv) # check_path(dirout_result_test) # savepredict(fin_test, dirout_feature, fin_model, dirout_result_test, batch_size=500,onehot = onehot) '''
print('training on the model') dirout_feature = '/home/19jjhnenu/Data/SeqTMPPI2W/feature/129878/' dirout = '/home/19jjhnenu/Data/SeqTMPPI2W/result/changemodel/lstm' fin_model = None train = 'file/10humanTrain/4train/group/0/train.txt' validate = {} validate['fin_pair'] = 'file/10humanTrain/4train/group/0/validate.txt' validate['dir_in'] = dirout_feature onehot = True entry( dirout, train, dirout_feature, model_type=Param.LSTM, limit=0, onehot=onehot, kernel_size=90, epochs=80, # epochs=30, filters=300, batch_size=500, validate=validate, fin_model=fin_model) pass print('stop', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())) print('time', time.time() - start)
def randomize(self): rnd = randomizer.randint(self.min_list_size, self.max_list_size) for x in range(0, rnd): _entry = entry() _entry.randomize() self.entry_list.append(_entry)
def do_entry(self): if not 'entry' in self.children: self.validate_metadata() from entry import entry return entry()
def crosshumanTrain(modelreuse=False): f2all = 'file/10humanTrain/3cluster/4pair.tsv' # 正负样本非1:1了 f1out = 'file/10humanTrain/4train/group' f2out = 'file/10humanTrain/4train/cross/group' f3out = 'file/10humanTrain/4train/cross' # dirout_feature = '/home/19jjhnenu/Data/SeqTMPPI2W/feature/129878/' # f2resultOut = '/home/19jjhnenu/Data/SeqTMPPI2W/result/10humanTrain_80epoch/group_reusemodel_5CV' dirout_feature = '/root/19jjhnenu/Data/SeqTMPPI2W/feature/129878/' f2resultOut = '/root/19jjhnenu/Data/SeqTMPPI2W/result/10humanTrain_80epoch/group_reusemodel_5CV' check_path(f2resultOut) check_path(f2out) # flist = [os.path.join(f1out,x,'all.txt') for x in os.listdir(f1out)] # concatFile(flist,f2all) ''' train:test = 5:1 ''' train = os.path.join(f3out, 'train_vali.txt') test = os.path.join(f3out, 'test.txt') ratios_tvt = [5, 1] f3outs = [train, test] # PairDealer().part(os.path.join(f3out,'all.txt'),ratios_tvt,f3outs) # PairDealer().part(f2all,ratios_tvt,f3outs) ''' 5cv ''' ratios_tvt = [1] * 5 f3outs = [os.path.join(f2out, '%d.txt' % x) for x in range(5)] # PairDealer().part(os.path.join(f3out,'all.txt'),ratios_tvt,f3outs) # PairDealer().part(os.path.join(f3out,'train_vali.txt'),ratios_tvt,f3outs) ''' cross train ''' for cv in range(5): # oldfile = '-1' oldfile = '2' for elem in range(5): if elem == cv: continue f2dirout = os.path.join(f2resultOut, str(cv)) f3dirout = os.path.join(f2dirout, str(elem)) fin_model = os.path.join(f2dirout, oldfile, '_my_model.h5') if not os.access(fin_model, os.F_OK) or not modelreuse: fin_model = None train = os.path.join(f2out, '%d.txt' % elem) validate = {} validate['fin_pair'] = os.path.join(f2out, '%d.txt' % cv) validate['dir_in'] = dirout_feature onehot = True entry( f3dirout, train, dirout_feature, model_type=Param.CNN1D_OH, limit=0, onehot=onehot, kernel_size=90, epochs=80, # epochs=2, filters=300, batch_size=500, validate=validate, fin_model=fin_model) oldfile = str(elem)
def commodity_size_selection(self, firm_type): """ This function creates a dialog asking the size of the firm to be built The range of the size is from "1" where the it is just the input_output_dict to the integer at which the sum of the inputs are equal to 10% the population of the city (FIXME this rule is not implemented for AI - also note that it is more like 101% of the sum at present) """ self.menu_position = "commodity size" self.selections = {} self.selections["firm_type"] = firm_type if firm_type in ["population transfer", "merchant"]: raise Exception( "This should have been distributed correctly already at the select_button_callback step" ) elif firm_type == "research": technology = {} technology["input_output_dict"] = {} technology["input_output_dict"]["input"] = {"labor": 1} technology["input_output_dict"]["output"] = {"research:": 1} technology["technology_name"] = "research" else: technology = self.solar_system_object_link.current_player.known_technologies[ firm_type] input_size = 0 #calculate the range allowed for input in technology["input_output_dict"]["input"].values(): input_size = input_size + input if input_size < 2: input_size = 2 if self.solar_system_object_link.current_planet.current_base is None: raise Exception("very weird - there was no base selected") population = self.solar_system_object_link.current_planet.current_base.population max_size = max(int(population * 0.05 / float(input_size)), 1) #check if the current_player already owns a company of that technology in the current base existing_firm = None for firm_instance in self.solar_system_object_link.current_player.owned_firms.values( ): if firm_instance.location == self.solar_system_object_link.current_planet.current_base: if firm_instance.technology_name == firm_type: existing_firm = firm_instance break #clean up the act pygame.draw.rect(self.action_surface, (212, 212, 212), self.rect) pygame.draw.rect(self.action_surface, (0, 0, 0), self.rect, 2) pygame.draw.line(self.action_surface, (255, 255, 255), (self.rect[0], self.rect[1]), (self.rect[0] + self.rect[2], self.rect[1])) pygame.draw.line(self.action_surface, (255, 255, 255), (self.rect[0], self.rect[1]), (self.rect[0], self.rect[1] + self.rect[3])) if existing_firm is None: start_value = 1 existing_firm_rendered_text = global_variables.standard_font.render( "Choose name of firm:", True, (0, 0, 0)) self.action_surface.blit(existing_firm_rendered_text, (self.rect[0] + 90, self.rect[1] + 70)) self.text_receiver = entry.entry( self.action_surface, topleft=(self.rect[0] + 100, self.rect[1] + 90, self.rect[2] - 100, self.rect[3] - 150), width=300, max_letters=global_variables.max_letters_in_company_names) self.text_receiver.active = True else: start_value = existing_firm.size existing_firm_rendered_text = global_variables.standard_font.render( "An existing size " + str(existing_firm.size) + " firm of this type already owned here.", True, (0, 0, 0)) self.action_surface.blit(existing_firm_rendered_text, (self.rect[0] + 130, self.rect[1] + 70)) existing_firm_rendered_text = global_variables.standard_font.render( "Select new size and press ok if new size is required.", True, (0, 0, 0)) self.action_surface.blit(existing_firm_rendered_text, (self.rect[0] + 130, self.rect[1] + 85)) text = global_variables.standard_font.render("Choose size of firm:", True, (0, 0, 0)) self.action_surface.blit(text, (self.rect[0] + 90, self.rect[1] + 150)) fastest = global_variables.standard_font.render( "Smallest", True, (0, 0, 0)) self.action_surface.blit(fastest, (self.rect[0] + 40, self.rect[1] + 40)) slowest = global_variables.standard_font.render( "Largest", True, (0, 0, 0)) self.action_surface.blit( slowest, (self.rect[0] + 40, self.rect[1] + self.rect[3] - 50)) def execute(label, technology): """ This function is activated on scrollbar value change on the size selection box, and updates the input_ output_dict """ update_rect = pygame.Rect(self.rect[0] + 50, self.rect[1] + 170, self.rect[2] - 100, self.rect[3] - 250) pygame.draw.rect(self.action_surface, (212, 212, 212), update_rect) size_info = global_variables.standard_font_small.render( "size: " + str(self.slider.position), True, (0, 0, 0)) self.action_surface.blit(size_info, (self.rect[0] + 130, self.rect[1] + 170)) lineno = 0 for put in ["input", "output"]: lineno = lineno + 1 direction_info = global_variables.standard_font_small.render( put + ":", True, (0, 0, 0)) self.action_surface.blit( direction_info, (self.rect[0] + 130, self.rect[1] + 170 + lineno * 20)) # print technology.keys() for resource in technology["input_output_dict"][put].keys(): lineno = lineno + 1 if resource in self.solar_system_object_link.mineral_resources + [ "food" ] and put == "output": mining_opportunity = self.solar_system_object_link.current_planet.current_base.get_mining_opportunities( self.solar_system_object_link.current_planet, resource) unmodified_output = technology["input_output_dict"][ "output"][resource] value = (mining_opportunity / 10) * unmodified_output value = int(value * self.slider.position) value_info = global_variables.standard_font_small.render( resource + ": " + str(value) + " (location modifier: " + str(round(mining_opportunity, 2)) + ")", True, (0, 0, 0)) else: value = technology["input_output_dict"][put][resource] value = value * self.slider.position value_info = global_variables.standard_font_small.render( resource + ": " + str(value), True, (0, 0, 0)) self.action_surface.blit( value_info, (self.rect[0] + 150, self.rect[1] + 170 + lineno * 20)) self.ok_button = button.button( "ok", self.action_surface, fixed_size=(100, 35), topleft=(self.rect[0] + self.rect[2] - 110, self.rect[1] + self.rect[3] - 40)) signaller.connect(self.ok_button, "signal__clicked", lambda: self.commodity_build_firm(existing_firm)) pygame.display.flip() if 1 > start_value or max_size < start_value: print start_value print max_size print firm_type raise Exception("This has been observed before. See printout") self.slider = vscrollbar.vscrollbar( self.action_surface, execute, topleft=(self.rect[0] + 10, self.rect[1] + 30), length_of_bar_in_pixel=self.rect[3] - 60, range_of_values=(1, max_size), start_position=start_value, function_parameter=technology) execute(None, technology) self.selections["technology"] = technology
def crossTrain(f2out, dirout_feature, f2resultOut, fold=5, filename='.txt'): ''' cross train ''' for cv in range(fold): oldfile = '-1' f2dirout = os.path.join(f2resultOut, str(cv)) f3dirout = '' for elem in range(fold): if cv == elem: continue f3dirout = os.path.join(f2dirout, str(elem)) fin_model = os.path.join(f2dirout, oldfile, '_my_model.h5') train = os.path.join(f2out, '%d%s' % (elem, filename)) validate = {} validate['fin_pair'] = os.path.join(f2out, '%d%s' % (cv, filename)) validate['dir_in'] = dirout_feature onehot = False entry( f3dirout, train, dirout_feature, model_type=Param.CNN1D_OH, limit=0, onehot=onehot, kernel_size=90, epochs=80, # epochs=2, filters=300, batch_size=500, validate=validate, ) # # oldfile = str(elem) print(f3dirout) calculateResults(f2dirout, f2dirout, resultfilename='result.csv') # eachdir = 'benchmark_human/train' # dirout_feature = '/mnt/data/sunshiwei/Phsi_Blos/feature/%s/' % eachdir # print('testing the model on test dataset') # fin_model = os.path.join(f2dirout, oldfile, '_my_model.h5') # fin_test = 'file/4train/5CV/data/test.txt' # dirout_result_test = '/mnt/data/sunshiwei/Phsi_Blos/result/5CV_1_test/%d'%cv # check_path(dirout_result_test) # savepredict(fin_test, dirout_feature, fin_model, dirout_result_test,batch_size=500,limit=2000,onehot = onehot) ''' testing on DIP all.txt in DIP/predict ''' # fin_test = 'file/8DIPPredict/predict/all.txt' # dirout_feature = '/mnt/data/sunshiwei/Phsi_Blos/feature/%s/' % 'DIP' # fin_model = os.path.join(f2dirout, oldfile, '_my_model.h5') # dirout_result_test = '/mnt/data/sunshiwei/Phsi_Blos/result/benchmark_human/test/5CV_1_DIP/%d' % cv # check_path(dirout_result_test) # savepredict(fin_test, dirout_feature, fin_model, dirout_result_test, batch_size=500,onehot = onehot) ''' testing on DIP all.txt in DIP/data ''' # fin_test = 'file/8DIPPredict/data/all.txt' # dirout_feature = '/mnt/data/sunshiwei/Phsi_Blos/feature/%s/' % 'DIP' # fin_model = os.path.join(f2dirout, oldfile, '_my_model.h5') # dirout_result_test = '/mnt/data/sunshiwei/Phsi_Blos/result/benchmark_human/test/5CV_1_DIP_posi/%d' % cv # check_path(dirout_result_test) # savepredict(fin_test, dirout_feature, fin_model, dirout_result_test, batch_size=500,onehot = onehot) ''' testing on all.txt in Imex ''' # fin_test = 'file/8ImexPredict/4pair.tsv' # dirout_feature = '/mnt/data/sunshiwei/Phsi_Blos/feature/%s/' % 'IMEx' # fin_model = os.path.join(f2dirout, oldfile, '_my_model.h5') # dirout_result_test = '/mnt/data/sunshiwei/Phsi_Blos/result/benchmark_human/test/5CV_1_IMEx_posi/%d' % cv # check_path(dirout_result_test) # savepredict(fin_test, dirout_feature, fin_model, dirout_result_test, batch_size=500,onehot = onehot) ''' IMEx + - ''' # fin_test = 'file/8ImexPredict/predict/0/all.txt' # dirout_feature = '/mnt/data/sunshiwei/Phsi_Blos/feature/%s/' % 'IMEx' # fin_model = os.path.join(f2dirout, oldfile, '_my_model.h5') # dirout_result_test = '/mnt/data/sunshiwei/Phsi_Blos/result/benchmark_human/test/5CV_1_IMEx/%d' % cv # check_path(dirout_result_test) # savepredict(fin_test, dirout_feature, fin_model, dirout_result_test, batch_size=500,onehot = onehot) ''' testing on DIP all.txt in DIP/data/Human ''' # for eachfile in ['Ecoli', 'Human', 'Mus', 'SC']: # fin_test = 'file/8DIPPredict/data/%s/2pair.tsv'%eachfile # dirout_feature = '/mnt/data/sunshiwei/Phsi_Blos/feature/%s/' % 'DIP' # fin_model = os.path.join(f2dirout, oldfile, '_my_model.h5') # dirout_result_test = '/mnt/data/sunshiwei/Phsi_Blos/result/benchmark_human/test/5CV_1_DIP_%s/%d' % (eachfile,cv) # check_path(dirout_result_test) # savepredict(fin_test, dirout_feature, fin_model, dirout_result_test, batch_size=500,onehot = onehot) '''
def new_base_ask_for_name(self, sphere_coordinates, give_length_warning=False): """ Function that prompts the user for a name of the new base Optional argument give_length_warning includes a label that specifies max " + str(global_variables.max_letters_in_company_names) + " characters """ #first we calculate the distance building_base = self.solar_system_object_link.building_base if self.solar_system_object_link.current_player != building_base.owner: print_dict = { "text": "Could not transfer population from " + str(building_base.name) + " because it is not owned by you.", "type": "general gameplay info" } self.solar_system_object_link.messages.append(print_dict) pygame.mouse.set_cursor(*pygame.cursors.arrow) return if sphere_coordinates[0:19] == "transfer population": if sphere_coordinates[ 23:] in self.solar_system_object_link.current_planet.bases.keys( ): destination_base = self.solar_system_object_link.current_planet.bases[ sphere_coordinates[23:]] sphere_coordinates = destination_base.position_coordinate if self.solar_system_object_link.current_player != destination_base.owner: print_dict = { "text": "Could not transfer population to " + str(destination_base.name) + " because it is not owned by you.", "type": "general gameplay info" } self.solar_system_object_link.messages.append(print_dict) self.solar_system_object_link.build_base_mode = True pygame.mouse.set_cursor(*pygame.cursors.diamond) return else: raise Exception( "The destination base " + str(sphere_coordinates[23:]) + "was not found in base dict of " + str(self.solar_system_object_link.current_planet.name)) else: destination_base = None if sphere_coordinates == (None, None): # sphere_coordinates = "space base" gravitational_constant = 40 if building_base.home_planet == self.solar_system_object_link.current_planet: #intraplanetary if building_base.terrain_type != "Space" and sphere_coordinates != "space base": #ground based transport_type = "ground transport" distance = int( building_base.home_planet.calculate_distance( sphere_coordinates, building_base.position_coordinate)[0]) / 100 else: #space based intraplanetary if building_base.terrain_type != "Space" and sphere_coordinates == "space base": #ground to space building - mostly depends on escape velocity transport_type = "space transport" distance = (self.solar_system_object_link.current_planet. gravity_at_surface * gravitational_constant)**2 else: #space-to-ground or space-to-space (cheap) transport_type = "space transport" distance = 10.0 else: #inter-planetary -- one fixed part and one part ground escape velocity transport_type = "space transport" distance = 100.0 #adding an extra for travels between far-away planets endpoint_distances = [] for endpoint in [ building_base.home_planet, self.solar_system_object_link.current_planet ]: while endpoint.planet_data["satellite_of"] != "sun": endpoint = self.solar_system_object_link.planets[ endpoint.planet_data["satellite_of"]] endpoint_distances.append( endpoint.planet_data["semi_major_axis"]) distance = distance + int( abs(endpoint_distances[0] - endpoint_distances[1])**0.5) / 50 if building_base.terrain_type != "Space": distance = distance + int( (building_base.home_planet.gravity_at_surface * gravitational_constant)**2) distance = distance * 2 #because it is generally more difficult to have to launch from surface of planet # print "distance is " + str(distance) + " using " + transport_type self.pricing = { "steel_cost_per_person": 0.51 + distance / 100, "power_cost_per_person": 0.5 + distance / 100, "transport_cost_per_person": distance, "electronics_cost_per_person": 0.01 + distance / 2000, "transport_type": transport_type, "distance": distance } pygame.draw.rect(self.action_surface, (212, 212, 212), self.rect) pygame.draw.rect(self.action_surface, (0, 0, 0), self.rect, 2) pygame.draw.line(self.action_surface, (255, 255, 255), (self.rect[0], self.rect[1]), (self.rect[0] + self.rect[2], self.rect[1])) pygame.draw.line(self.action_surface, (255, 255, 255), (self.rect[0], self.rect[1]), (self.rect[0], self.rect[1] + self.rect[3])) if destination_base is not None: location_description = "Transfering population to " + destination_base.name else: if sphere_coordinates == "space base": location_description = "Building a base in orbit around " + self.solar_system_object_link.current_planet.name else: location_description = "Building a base at (" + str( round(sphere_coordinates[0]) ) + "," + str( round(sphere_coordinates[1]) ) + ") on " + self.solar_system_object_link.current_planet.name description = global_variables.standard_font.render( location_description, True, (0, 0, 0)) self.action_surface.blit(description, (self.rect[0] + 20, self.rect[1] + 20)) if destination_base is None: description = global_variables.standard_font.render( "Enter name", True, (0, 0, 0)) self.action_surface.blit(description, (self.rect[0] + 20, self.rect[1] + 40)) if give_length_warning: warning = global_variables.standard_font.render( "Name must be unique", True, (0, 0, 0)) self.action_surface.blit( warning, (self.rect[0] + 20, self.rect[1] + 50)) self.text_receiver = entry.entry( self.action_surface, topleft=(self.rect[0] + self.rect[2] / 2 - 100, self.rect[1] + 70), width=200, max_letters=global_variables.max_letters_in_company_names) self.text_receiver.active = True else: assert self.text_receiver == None description = global_variables.standard_font.render( "Population to transfer:", True, (0, 0, 0)) self.action_surface.blit(description, (self.rect[0] + 20, self.rect[1] + 120)) price_rect = pygame.Rect(self.rect[0] + 10, self.rect[1] + 210, self.rect[2] - 20, 80) def population_execute(label, price_rect): pygame.draw.rect(self.action_surface, (212, 212, 212), price_rect) text = primitives.nicefy_numbers(int( self.population_bar.position)) + " people" rendered_text = global_variables.standard_font.render( text, True, (0, 0, 0)) self.action_surface.blit(rendered_text, (price_rect[0], price_rect[1])) text = primitives.nicefy_numbers( int(self.population_bar.position * self.pricing["steel_cost_per_person"])) + " steel" rendered_text = global_variables.standard_font.render( text, True, (0, 0, 0)) self.action_surface.blit(rendered_text, (price_rect[0], price_rect[1] + 15)) text = primitives.nicefy_numbers( int(self.population_bar.position * self.pricing["power_cost_per_person"])) + " power" rendered_text = global_variables.standard_font.render( text, True, (0, 0, 0)) self.action_surface.blit(rendered_text, (price_rect[0], price_rect[1] + 30)) text = primitives.nicefy_numbers( int(self.population_bar.position * self.pricing["transport_cost_per_person"]) ) + " " + transport_type rendered_text = global_variables.standard_font.render( text, True, (0, 0, 0)) self.action_surface.blit(rendered_text, (price_rect[0], price_rect[1] + 45)) text = primitives.nicefy_numbers( int(self.population_bar.position * self. pricing["electronics_cost_per_person"])) + " electronics" rendered_text = global_variables.standard_font.render( text, True, (0, 0, 0)) self.action_surface.blit(rendered_text, (price_rect[0], price_rect[1] + 60)) pygame.display.update(price_rect) max_size = min(10000, building_base.population) min_size = min(max_size / 2, 100) self.population_bar = hscrollbar.hscrollbar( self.action_surface, population_execute, (self.rect[0] + 10, self.rect[1] + 140), self.rect[2] - 20, (min_size, max_size), start_position=100, function_parameter=price_rect) description = global_variables.standard_font.render( "Price of transfer:", True, (0, 0, 0)) self.action_surface.blit(description, (self.rect[0] + 20, self.rect[1] + 170)) description = global_variables.standard_font.render( "Calculated on a cost-distance of " + str(int(distance)), True, (0, 0, 0)) self.action_surface.blit(description, (self.rect[0] + 20, self.rect[1] + 185)) population_execute(None, price_rect) if destination_base is None: self.ok_button = button.button( "ok", self.action_surface, fixed_size=(100, 35), topleft=(self.rect[0] + self.rect[2] - 110, self.rect[1] + self.rect[3] - 40)) signaller.connect(self.ok_button, "signal__clicked", lambda: self.new_base_build(sphere_coordinates)) else: self.ok_button = button.button( "ok", self.action_surface, fixed_size=(100, 35), topleft=(self.rect[0] + self.rect[2] - 110, self.rect[1] + self.rect[3] - 40)) signaller.connect(self.ok_button, "signal__clicked", lambda: self.new_base_build(destination_base)) self.cancel_button = button.button( "cancel", self.action_surface, fixed_size=(100, 35), topleft=(self.rect[0] + self.rect[2] - 220, self.rect[1] + self.rect[3] - 40)) signaller.connect(self.cancel_button, "signal__clicked", self.exit)
def do_entry(self): from entry import entry return entry()
def perform_bid(self, chosen_seller_name): """ Function that allows the player to bid on an asset or technology """ if chosen_seller_name not in self.solar_system_object_link.companies.keys( ): print_dict = { "text": str(chosen_seller_name) + " was not found - perhaps it was shut down recently.", "type": "general gameplay info" } self.solar_system_object_link.messages.append(print_dict) # print "We had an instance of an unknown name: " + str(chosen_seller_name) else: chosen_seller = self.solar_system_object_link.companies[ chosen_seller_name] current_player = self.solar_system_object_link.current_player if self.selections["type"] == "base": self.menu_position = "base bidding" pygame.draw.rect(self.action_surface, (224, 218, 213), self.rect) pygame.draw.rect(self.action_surface, (0, 0, 0), self.rect, 2) pygame.draw.line(self.action_surface, (255, 255, 255), (self.rect[0], self.rect[1]), (self.rect[0] + self.rect[2], self.rect[1])) pygame.draw.line(self.action_surface, (255, 255, 255), (self.rect[0], self.rect[1]), (self.rect[0], self.rect[1] + self.rect[3])) instruction = global_variables.standard_font.render( "Enter bid for " + self.selections["bid_on"] + " (pop:" + str(self.selections["sale_object"].population) + ") with deadline " + str(self.selections["sale_object"].for_sale_deadline), True, (0, 0, 0)) self.action_surface.blit( instruction, (self.rect[0] + 10, self.rect[1] + 10)) # estimating a value of the base potential_base = self.selections["sale_object"] if potential_base.is_on_dry_land == "Yes": dry_term = 1 else: dry_term = 0.01 mining_values = [] for resource in potential_base.mining_opportunities: mining_opportunity = potential_base.mining_opportunities[ resource] price_of_resource = [] for trade_route in potential_base.trade_routes.values(): if trade_route["endpoint_links"].index( potential_base) == 1: neighbour = trade_route["endpoint_links"][0] else: neighbour = trade_route["endpoint_links"][1] try: neighbour.market["buy_offers"][resource] except: if self.solar_system_object_link.message_printing[ "debugging"]: print_dict = { "text": "DEBUGGING: When calculating bid, we did not find a market in neighbour " + str(neighbour.name), "type": "debugging" } self.solar_system_object_link.messages.append( print_dict) else: if len(neighbour.market["buy_offers"] [resource]) > 0: price_of_resource.append( neighbour.market["buy_offers"][resource][0] ["price"]) if len(price_of_resource) > 0: mean_price_of_resource = sum(price_of_resource) / len( price_of_resource) value = mining_opportunity * mean_price_of_resource mining_values.append(value) mining_value_term = sum(mining_values) population_term = potential_base.population company_term = current_player.company_database[ "buy_out_tendency"] base_value = int(dry_term * mining_value_term * population_term * company_term * 0.00000001) #start the entry box self.text_receiver = entry.entry( self.action_surface, (self.rect[0] + 10, self.rect[1] + 40), 300, 32, starting_text=str(base_value)) self.bid_button = button.button("Bid", self.action_surface, topleft=(self.rect[0] + 10, self.rect[1] + 100)) signaller.connect(self.bid_button, "signal__clicked", self.effectuate_base_bid) return None if current_player.capital > self.selections["price"]: if self.selections["type"] in ["technology", "advanced tech."]: self.solar_system_object_link.current_player.known_technologies[ self. selections["bid_on"]] = self.selections["sale_object"] current_player.capital = current_player.capital - self.selections[ "price"] chosen_seller.capital = chosen_seller.capital + self.selections[ "price"] print_dict = { "text": str(self.selections["bid_on"]) + " was bought for " + str(self.selections["price"]) + " from " + str(chosen_seller.name), "type": "general gameplay info" } self.solar_system_object_link.messages.append(print_dict) elif self.selections["type"] == "base": print_dict = { "text": "base buying not implemented yet", "type": "general gameplay info" } self.solar_system_object_link.messages.append(print_dict) else: raise Exception("Unknown type: " + str(self.selections["type"]) + " asked for in the asset sales GUI") else: print_dict = { "text": current_player.name + " has a capital of " + str(current_player.capital) + " and can't bid " + str(self.selections["price"]), "type": "general gameplay info" } self.solar_system_object_link.messages.append(print_dict) return "clear"