def test_pack_size(self): pack = Pack() stickers = pack.open() pack_size = len(stickers) self.assertEqual(pack_size, 5)
def main(argv): input_dir = argv[1] output_dir = argv[2] for file_name in os.listdir(input_dir): input_path = os.path.join(input_dir, file_name) with open(input_path, 'r', encoding='utf-8', errors='ignore') as f: message_str = f.read() pack = Pack(message_str, output_path=output_dir) pack.run()
def forward(self, pack: Pack): rev = pack.get_rev() data = pack.get_pack(self.embedding, torch_var=True) if self.cuda: rev.cuda() states_packed, _ = self.encoder( data) # (packed_sequence, hidden_state) states, _ = torch.nn.utils.rnn.pad_packed_sequence(states_packed) states = torch.cat( [states[-1, :, :self.hidden_dim], states[0, :, self.hidden_dim:]], dim=1) return states[rev, :]
def forward(self, pack: Pack): lengths = pack.get_lengths_var() rev = pack.get_rev() data = pack.get_pack(self.embedding) if self.cuda: lengths.cuda() rev.cuda() states_packed, _ = self.encoder( data) # (packed_sequence, hidden_state) states, _ = torch.nn.utils.rnn.pad_packed_sequence(states_packed) if self.bidirectional: states = states[:, :, :self.hidden_dim] + states[:, :, self.hidden_dim:] states_mean = torch.sum(states, dim=0) / lengths.unsqueeze(1) return states_mean[rev, :]
def move_in_thin_pack(self, path): """Move a specific file containing a pack into the pack directory. :note: The file should be on the same file system as the packs directory. :param path: Path to the pack file. """ data = PackData(path) # Write index for the thin pack (do we really need this?) temppath = os.path.join(self.pack_dir, sha_to_hex(urllib2.randombytes(20))+".tempidx") data.create_index_v2(temppath, self.get_raw) p = Pack.from_objects(data, load_pack_index(temppath)) # Write a full pack version temppath = os.path.join(self.pack_dir, sha_to_hex(urllib2.randombytes(20))+".temppack") write_pack(temppath, ((o, None) for o in p.iterobjects(self.get_raw)), len(p)) pack_sha = load_pack_index(temppath+".idx").objects_sha1() newbasename = os.path.join(self.pack_dir, "pack-%s" % pack_sha) os.rename(temppath+".pack", newbasename+".pack") os.rename(temppath+".idx", newbasename+".idx") self._add_known_pack(newbasename)
def get_event(self): ''' bit位 开关名称 0 出水开关 1 电源开关 2 加热开关 3 制冷开关 4 臭氧开关 # 汇报设备动态 A3-B3 :return: ''' self.boby_A3 = collections.OrderedDict() self.boby_A3['evc'] = 101 # 事件类型编码 self.boby_A3['val'] = 1 # 事件参数 self.boby_A3['evt'] = '' # 事件详情 self.boby_A3['now'] = standard_time() # 当前时间 self.boby_A3['sw'] = 1 << 0 # 开关位,int self.boby_A3['fpA'] = random.randrange(30, 90) # 滤芯A状态(滤芯百分比) self.boby_A3['fpB'] = random.randrange(30, 90) # 滤芯B状态(滤芯百分比) self.boby_A3['fpC'] = random.randrange(30, 90) # 滤芯C状态(滤芯百分比) self.boby_A3['td2'] = random.randrange(50, 254) # TDS2 self.boby_A3['td1'] = random.randrange(50, 254) # TDS1 self.boby_A3['wsr'] = random.randrange(30, 40) # 节水比率 self.boby_A3['ect'] = random.randrange(5, 15) # 错误数量 self.boby_A3['flg'] = 1 << 1 # 错误旗标 self.boby_A3['dnt'] = random.randrange(60, 254) # 断网时长(秒) self.boby_A3['int'] = random.randrange(5, 15) # 进水次数(Inlet Counter) self.boby_A3['tnt'] = random.randrange(5, 15) # 累计用水量(##单位:公升) self.boby_A3['sgt'] = random.randrange(20, 60) # 基站信号数量,信号强度 head_A3 = self.get_head(msg_id='A3') return Pack(head_A3, self.boby_A3).get_msg()
def _is_invalid_pack(self, recv_bytes): _checksum = b''.join(Pack.unpack(recv_bytes)[2]) _check_info = recv_bytes.strip(b'[]')[:-1] _checksum_calc = to_bytes(checksum(_check_info)) _msg_id = Pack.unpack_head(recv_bytes)['msg_id'] log.debug('[{0}] 接收==验证报文==消息类型={1}({2}) 待校验信息=({3})'.format(self.device.dev_id, _msg_id, MSG_TYPE[_msg_id], _check_info)) if _checksum == _checksum_calc: log.debug('[{0}] 接收==验证报文==消息类型={1}({2}) 报文校验码正确(checksum={3} checksum_calc={4})'.format( self.device.dev_id, _msg_id, MSG_TYPE[_msg_id], _checksum, _checksum_calc)) return True else: log.error('[{0}] 接收==验证报文==消息类型={1}({2}) 报文长度验证失败(checksum={3} checksum_calc={4})'.format( self.device.dev_id, _msg_id, MSG_TYPE[_msg_id], _checksum, _checksum_calc)) return True
def predict(self, batches, batch_i): texts = batches.get_data(self.texts, batch_i) text_pack = Pack(texts, cuda=True) images = batches.get_data(self.posters, batch_i) images = torch.autograd.Variable(torch.from_numpy(images)).cuda() encodings = self.encoder(text_pack, images) encodings = torch.cat(encodings, dim=1) return self.classifier(encodings)
def get_register(self): boby = { 'phone': '15989453055', 'password': '******', 'model': self.model, 'mainFirm': self.mainFirm, 'ctrlFirm': self.ctrlFirm, 'gsmFirm': self.gsmFirm, 'proVer': self.proVer } head_A101 = self.get_head(msg_id='A101') return Pack(head_A101, boby).get_msg()
class TestPack(unittest.TestCase): def setUp(self): self.pack = Pack() def test_get_card(self): self.assertIsNotNone(self.pack.get_card()) def test_get_card_twice(self): self.assertNotEqual(self.pack.get_card(), self.pack.get_card()) def test_shuffle(self): card1 = self.pack.get_card() self.pack.shuffle() for i in range(0, 52): self.assertIsNotNone(self.pack.get_card())
def main(argv): input_dir = argv[1] output_dir = argv[2] for file_name in os.listdir(input_dir): print("The order ", file_name, " is processing...") input_path = os.path.join(input_dir, file_name) with open(input_path, 'r', encoding='utf-8', errors='ignore') as f: message_str = f.read() order = Order(message_str) mypack_obj = mypack.Pack(order) hwpack_obj = Pack(message_str, mypack_obj=mypack_obj) route = Routing(order, pack_obj=hwpack_obj) nondominated_sol_listlist = route.population_global_search2(1400, 7) for sol_list in nondominated_sol_listlist: route.res["solutionArray"].append(route.sol_2_trucklist_Dict[''.join([str(x) for x in sol_list])]) route.save_sols(output_dir) print("The order ", file_name, " is done.")
def get_devdynamic(self): # 汇报设备动态 A5-B5 self.boby_A5 = collections.OrderedDict() self.boby_A5['now'] = standard_time() # 当前时间 self.boby_A5['sw'] = 1 << 0 # 开关位,int self.boby_A5['fpA'] = random.randrange(30, 50) # 滤芯A状态(滤芯百分比) self.boby_A5['fpB'] = random.randrange(30, 50) # 滤芯B状态(滤芯百分比) self.boby_A5['fpC'] = random.randrange(30, 50) # 滤芯C状态(滤芯百分比) self.boby_A5['td2'] = random.randrange(10, 20) # TDS2 self.boby_A5['td1'] = random.randrange(80, 100) # TDS1 self.boby_A5['wsr'] = random.randrange(30, 40) # 节水比率 self.boby_A5['ect'] = random.randrange(5, 15) # 错误数量 self.boby_A5['flg'] = 1 << 1 # 错误旗标 self.boby_A5['dnt'] = random.randrange(60, 254) # 断网时长(秒) self.boby_A5['int'] = random.randrange(5, 15) # 进水次数(Inlet Counter) self.boby_A5['tnt'] = random.randrange(5, 15) # 累计用水量(##单位:公升) self.boby_A5['sgt'] = random.randrange(1, 31) # 基站信号数量,信号强度 head_A5 = self.get_head(msg_id='A5') print('boby_A5 = {0}'.format(self.boby_A5)) return Pack(head_A5, self.boby_A5).get_msg()
def get_gsm_update_reponse(self, res_boby): # 获取gsm响应平台固件更新 C21-D21 boby = res_boby head_D21 = self.get_head(msg_id='D21') return Pack(head_D21, boby).get_msg()
def pack_source(cmode, tag, force_update, component): result = Cache.check_consistency() if result == False: return result return Pack.pack_source(cmode, tag, force_update, component)
def pack_upload(opts): return Pack.pack_upload(opts)
def split_pack(p): len_new_pack = ceil(len(p.wolves)/2) new_packs = [Pack(p.wolves[0:len_new_pack]), Pack(p.wolves[len_new_pack:len(p.wolves)])] return new_packs
def get_gsmpara_reponse(self, res_boby): # 获取gsm参数设置响应 C11-D11 boby = res_boby head_D11 = self.get_head(msg_id='D11') return Pack(head_D11, boby).get_msg()
def get_hat(self): boby = {'hatMsg': 'hello'} head_A7 = self.get_head(msg_id='A7') return Pack(head_A7, boby).get_msg()
def get_WaterMachine_update_reponse(self, res_boby): # 获取水机响应平台固件更新 C22-D22 boby = res_boby head_D22 = self.get_head(msg_id='D22') return Pack(head_D22, boby).get_msg()
def pack_clean(): return Pack.pack_clean()
def pack_build(cmode, tag, force_update): result = Cache.check_consistency() if result == False: return result return Pack.pack_build(cmode, tag, force_update)
def pack_create(project_path): return Pack.pack_create(project_path)
def _handle_pack(self, recv_bytes): _msg_id = Pack.unpack_head(recv_bytes)['msg_id'] if _msg_id == 'B7': # 响应心跳指令 self.hat_cumulative_time = time.time() # 收到心跳响应的时间 elif _msg_id == 'B101': # 处理收到的注册响应 if not self.is_register: self.register_cumulative_time = time.time() # 收到登陆响应的时间 error = Pack.unpack_boby(recv_bytes)['Error'] if error == '0': self.device.authCode = Pack.unpack_boby(recv_bytes)['authCode'] self.is_register = True log.info('[{0}] 注册成功'.format(self.device.dev_id)) else: self.is_register = False log.info('[{0}] 注册失败,原因={1}'.format(self.device.dev_id, error)) else: log.info('[{0}] 已经注册,收到无效的注册响应'.format(self.device.dev_id)) elif _msg_id == 'B2': # 响应签权 if self.is_register: self.sign_cumulative_time = time.time() # 收到签权响应的时间 error = Pack.unpack_boby(recv_bytes)['Error'] if error == '0': self.is_logined = True log.info('[{0}] 签权登录成功'.format(self.device.dev_id)) else: self.is_logined = False log.info('[{0}] 签权登录失败,原因={1}'.format(self.device.dev_id, error)) elif _msg_id == 'C17': # 响应套餐指令 log.info('[{0}] 接受套餐信息成功'.format(self.device.dev_id)) # 构造响应信息,发送 res_boby = {} res_boby['OriMsgNO'] = Pack.unpack_head(recv_bytes)['msg_no'] res_boby['OriMsgID'] = Pack.unpack_head(recv_bytes)['msg_id'] res_boby['Error'] = '0' res_boby['stTime'] = Pack.unpack_boby(recv_bytes)['stTime'] res_boby['edTime'] = Pack.unpack_boby(recv_bytes)['edTime'] res_setmeal_msg = self.device.get_setmeal_reponse(res_boby) self.push(res_setmeal_msg) log.info('[{0}] 响应套餐 ( {1} )'.format(self.device.dev_id, DEV_ERROR[int(res_boby['Error'])])) log.debug('[{0}] 生成套餐响应报文D17:{1}'.format(self.device.dev_id, res_setmeal_msg)) log.debug('[{0}] 响应==套餐D17:{1}'.format(self.device.dev_id, bytes_to_hexstr(res_setmeal_msg))) elif _msg_id == 'B5': # 处理收到的动态汇报响应 error = Pack.unpack_boby(recv_bytes)['Error'] log.info('[{0}] 接收平台响应设备状态,应答码= ( {1}, {2} )'.format(self.device.dev_id, error, PLATFORM_ERROR[int(error)])) elif _msg_id == 'B3': # 处理收到的事件响应 error = Pack.unpack_boby(recv_bytes)['Error'] log.info('[{0}] 接收平台事件响应,应答码= ( {1}, {2} )'.format(self.device.dev_id, error, PLATFORM_ERROR[int(error)])) elif _msg_id == 'C11': # 收到的终端参数设置指令,返回相应 # 构造响应信息,发送 res_boby = {} res_boby['OriMsgNO'] = Pack.unpack_head(recv_bytes)['msg_no'] res_boby['OriMsgID'] = Pack.unpack_head(recv_bytes)['msg_id'] res_boby['Error'] = '0' res_gsmpara_msg = self.device.get_gsmpara_reponse(res_boby) self.push(res_gsmpara_msg) log.info('[{0}] 响应GSM参数设置 ( {1} )'.format(self.device.dev_id, DEV_ERROR[int(res_boby['Error'])])) # log.debug('[{0}] 生成GSM参数响应报文D17:{1}'.format(self.device.dev_id, res_gsmpara_msg)) log.debug('[{0}] 响应==套餐D11:{1}'.format(self.device.dev_id, bytes_to_hexstr(res_gsmpara_msg))) elif _msg_id == 'C21': # 收到平台下发的GSM固件更新通知,返回D21响应 # 构造响应信息,发送 res_boby = {} res_boby['OriMsgNO'] = Pack.unpack_head(recv_bytes)['msg_no'] res_boby['OriMsgID'] = Pack.unpack_head(recv_bytes)['msg_id'] res_boby['Error'] = '0' res_gsm_update_msg = self.device.get_gsm_update_reponse(res_boby) self.push(res_gsm_update_msg) log.info('[{0}] 响应平台GSM固件更新 ( {1} )'.format(self.device.dev_id, DEV_ERROR[int(res_boby['Error'])])) # log.debug('[{0}] 生成响应平台GSM固件更新报文D21:{1}'.format(self.device.dev_id, res_gsm_update_msg)) log.debug('[{0}] 响应==套餐D21:{1}'.format(self.device.dev_id, bytes_to_hexstr(res_gsm_update_msg))) elif _msg_id == 'C22': # 收到水机升级指令,放D22响应 # 构造响应信息,发送 res_boby = {} res_boby['OriMsgNO'] = Pack.unpack_head(recv_bytes)['msg_no'] res_boby['OriMsgID'] = Pack.unpack_head(recv_bytes)['msg_id'] res_boby['Error'] = '0' res_WaterMachine_update_msg = self.device.get_WaterMachine_update_reponse(res_boby) self.push(res_WaterMachine_update_msg) log.info('[{0}] 响应平台水机固件更新 ( {1} )'.format(self.device.dev_id, DEV_ERROR[int(res_boby['Error'])])) # log.debug('[{0}] 生成响应平台GSM固件更新报文D21:{1}'.format(self.device.dev_id, res_WaterMachine_update_msg)) log.debug('[{0}] 响应==套餐D22:{1}'.format(self.device.dev_id, bytes_to_hexstr(res_WaterMachine_update_msg))) else: log.info('[{0}] 未知报文,不处理丢弃'.format(self.device.dev_id))
def setUp(self): self.pack = Pack()
def get_setmeal_reponse(self, res_boby): # 获取套餐响应 C17-D17 boby = res_boby head_D17 = self.get_head(msg_id='D17') return Pack(head_D17, boby).get_msg()
def main(argv): # input_dir = argv[1] input_dir = 'data/inputs' # output_dir = argv[2] output_dir = 'data/outputs' antNum = 20 #蚂蚁数量,有多少只蚂蚁就会返回多少个路径 # iterTime = 30 for file_name in os.listdir(input_dir): pack_time = 0 #调用pack的次数 #代表一个实例 begin_time = time() end_time = time() solution = [] #存放所有非支配解 resultArray = [] #存放所有解的目标值 gen = 0 #迭代次数 input_path = os.path.join(input_dir, file_name) with open(input_path, 'r', encoding='utf-8', errors='ignore') as f: message_str = f.read() pack = Pack(message_str, output_path=output_dir) pack_time += 1 #数据中的节点数量 numOfNode = len(pack.data['algorithmBaseParamDto']['platformDtoList']) #数据中的卡车 truck = pack.data['algorithmBaseParamDto']['truckTypeDtoList'] truckOfNum = len(truck) distanceInfo = handleDist( pack.data['algorithmBaseParamDto']['distanceMap'], numOfNode) distanceMat = distanceInfo['distanceMat'] platformOrder = distanceInfo['platformOrder'] allBox = copy.deepcopy(pack.box_list) #获取需要装箱的盒子 #track1 # while pack_time<2000 and (end_time - begin_time)<420: #track2 while (end_time - begin_time) < 130: #确认是否有需要优先的平台,不确定是否有几个 needFirst = [] for item in pack.data['algorithmBaseParamDto']['platformDtoList']: if item['mustFirst'] == True: needFirst.append( platformOrder.index( int(re.findall("\d+", item['platformCode'])[0]))) updataPath = 0 #每隔10代重新求一次路径,返回的是platformOrder的索引节点 if gen < 30 and gen % 5 == 0: bestPath = antLoad(numOfNode + 2, distanceMat, antNum, gen % 5 + 1, needFirst) updataPath = 1 elif gen % 20 == 0: #返回多条路径,但是很可能包含相同,path表示路径,length表示长度 bestPath = antLoad(numOfNode + 2, distanceMat, antNum, random.randint(10, 30), needFirst) updataPath = 1 if updataPath == 1: #将path组转成参数所需要的格式 ['platform04','platform05'] routes = [] for k in range(len(bestPath['path'])): oneAnt = [] for j in range(len(bestPath['path'][k]) - 1): if j != 0: if platformOrder[bestPath['path'][k, j]] < 10: platform = 'platform0' + str( platformOrder[bestPath['path'][k, j]]) else: platform = 'platform' + str( platformOrder[bestPath['path'][k, j]]) oneAnt.append(platform) routes.append(oneAnt) #还未装载的盒子,这里需要使用深度拷贝 restBox = copy.deepcopy(allBox) res = [] while len(restBox) != 0: #所有能使用的车辆编号,range不包括最后truckOfNum canUseTruck = list(range(truckOfNum)) #随机选择一种类型的卡车 chose_truck = random.randint(0, truckOfNum - 1) #随机选择一条路径 chose_path = random.randint(0, len(routes) - 1) old_path = copy.deepcopy(routes[chose_path]) #如果货物中已经有盒子超过了货车的大小,则不能再选择此种货车 box_id = [] for box in restBox: box_id.append(box.box_id) onePack = Pack(message_str, spu_ids=box_id, truck_code=truck[chose_truck]['truckTypeCode'], route=[routes[chose_path]], output_path=output_dir) one = onePack.run() pack_time += 1 #如果打包成功 if one: #检查一下路径是否符合要求 if needFirst: for node in range(len(one['platformArray'])): if node != 0: if platformOrder.index( int( re.findall( "\d+", one['platformArray'] [node])[0])) in needFirst: #去掉不符合规则的那个平台,然后重新计算 old_path.remove(one['platformArray'][node]) onePack = Pack( message_str, spu_ids=box_id, truck_code=truck[chose_truck] ['truckTypeCode'], route=[old_path], output_path=output_dir) one = onePack.run() pack_time += 1 break res.append(one) #去掉已经装载的箱子 for loadBox in one['spuArray']: for box in restBox: if box.box_id == loadBox['spuId']: restBox.remove(box) #计算这个方案的装载率和运输距离 result = calResult(res, distanceMat, numOfNode + 2, platformOrder) resultArray.append(result) solution.append(res) gen += 1 end_time = time() print('result:', result) #迭代完成之后去掉一些重复解 new_resultArr = [] new_solution = [] for no_repeat in resultArray: if no_repeat not in new_resultArr: new_resultArr.append(no_repeat) new_solution.append(solution[resultArray.index(no_repeat)]) #迭代完成之后去掉一些支配解 obj_arr = np.array(new_resultArr) paretoIndex = NDSort(obj_arr.shape[0], obj_arr) paretoIndex.fast_non_dominate_sort() paretoIndex.crowd_distance() #保存第一层的解 temp_solution = [] temp_obj = [] for i in paretoIndex.f[0]: temp_solution.append(new_solution[i]) temp_obj.append(obj_arr[i]) print('finally result:', temp_obj) estimateCode = pack.data['estimateCode'] reserveResult(output_dir, estimateCode, temp_solution, file_name)
from album import Album from pack import Pack opened_number = [] for number_of_test in range(10): album = Album() pack = Pack() opened_packs = 0 album_report = album.get_report() missing = album_report['missing'] while missing > 50: album.insert_sticker(pack.open()) album_report = album.get_report() missing = album_report['missing'] opened_packs += 1 report = album.get_report() opened_number.append(opened_packs) print('album processed {}'.format(number_of_test + 1)) print('min number of packs {}'.format(min(opened_number))) print('max number of packs {}'.format(max(opened_number))) print('mean of packs {}'.format(sum(opened_number) / 10))
from sys import exit, argv from PyQt5.QtWidgets import QApplication from ui import UI from pack import Pack pack = Pack(512, 512, False) pack.insert(256, 256) pack.insert(128, 128) pack.insert(64, 64) pack.insert(32, 32) pack.insert(16, 16) pack.insert(8, 8) pack.insert(4, 4) pack.insert(2, 2) pack.insert(100, 100) pack.insert(200, 50) pack.insert(400, 25) pack.insert(50, 200) pack.insert(25, 400) pack.insert(100, 100) pack.insert(200, 50) pack.insert(400, 25) pack.insert(50, 200) pack.insert(25, 400) app = QApplication(argv) ui = UI(pack) ui.show() exit(app.exec_())
def predict(self, batches, batch_i): texts = batches.get_data(self.texts, batch_i) text_pack = Pack(texts, cuda=True) return self.classifier(self.encoder(text_pack))
def get_sign(self): boby = {'authCode': self.authCode} head_A2 = self.get_head(msg_id='A2') return Pack(head_A2, boby).get_msg()