input
stringlengths
2.65k
237k
output
stringclasses
1 value
frlig.close() countp = countp + 1 else: continue f.close() # make inputfile for foldx4 with mutchain for calculating folding free energy def inputfoldx(): os.chdir(path) f = open(in_file + ".cleaned", 'r') f.next() for line in f: ff = line.split("\t") mut = ff[11][:-1] # GA9A pdb = ff[8] # 1A43 with open('individual_list_' + jobid + '_' + mut + '.txt', 'w') as fic: fic.write('%s' % (mut + ';')) with open('foldx_buildmodel_' + jobid + '_' + mut + '.txt', 'w') as fsc: fsc.write('command=BuildModel\npdb=%s\nmutant-file=%s' % (jobid + '_' + mut + '.pdb', 'individual_list_' + jobid + '_' + mut + '.txt')) os.system("cp %s/%s.pdb %s_%s.pdb" % (pathoutput, pdb, jobid, mut)) f.close() # build model with foldx, produce Dif_1A43_A_Repair_GA9A.fxout def runfoldx_mut(): f = open(in_file + ".cleaned", 'r') f.next() for line in f: ff = line.split("\t") mut = ff[11][:-1] # GA9A pdb = ff[8] # 1A43 os.system('./foldx -f foldx_buildmodel_%s_%s.txt' % (jobid, mut)) os.system("rm WT_%s_%s_1.pdb" % (jobid, mut)) os.system("rm individual_list_%s_%s.txt" % (jobid, mut)) os.system("rm foldx_buildmodel_%s_%s.txt" % (jobid, mut)) os.system("rm Average_%s_%s.fxout" % (jobid, mut)) os.system("rm Raw_%s_%s.fxout" % (jobid, mut)) os.system("rm PdbList_%s_%s.fxout" % (jobid, mut)) os.system("rm %s_%s.fxout" % (jobid, mut)) os.system("mv Dif_%s_%s.fxout %s" % (jobid, mut, pathoutput)) os.system("rm %s_%s.pdb" % (jobid, mut)) os.system("mv %s_%s_1.pdb %s/%s_%s.pdb" % (jobid, mut, pathoutput, pdb, mut)) f.close() def splitchain_mut(): f = open(in_file + ".cleaned", 'r') _unused = f.next() for line in f: ff = line.split("\t") mut = ff[11][:-1] # GA9A pdb = ff[8] # 1A43 partner1 = ff[9] pdb = pdb + '_' + mut countchain = 1 for chains in list(partner1): os.system('grep "^.\{21\}%s" %s/%s.pdb > %s/%s_%s.pdb' % (chains, pathoutput, pdb, pathoutput, pdb, 'CH' + str(countchain))) countchain += 1 f.close() # produce psf and pdb files of mutant with vmd def vmd_mut(): f = open(in_file + ".cleaned", 'r') _unused = f.next() template = open(pathinput + '/vmd.pgn').read() for line in f: ff = line.split("\t") mut = ff[11][:-1] # GA9A pdb = ff[8] # 1A43 partner1 = ff[9] protname = pdb + '_' + mut NumChain = int(len(partner1)) vmd_pdb = template.replace('protname', protname).replace('NumChain', str(NumChain)).replace('pathinput', pathinput).replace('pathoutput', pathoutput) with open(pathoutput + '/vmd_' + protname + '.pgn', 'w') as fw: fw.write(vmd_pdb) os.system('%s -dispdev text -e %s/vmd_%s.pgn' % (pathvmd,pathoutput, protname)) f.close() def wtpdb_all_addh(): pdball = [] with open(in_file + ".cleaned", 'r') as f: f.next() for line in f: ff = line.split("\t") pdb = ff[8].lower() # 1A43 ligand = ff[6].lower() if pdb not in pdball: os.system('cat %s/%s_protein_ch*.pdb %s/%s_%s_ch*.pdb > %s/%s_wt_test.pdb' % (pathoutput, pdb, pathoutput, pdb, ligand, pathoutput, pdb)) fnew = open(pathoutput + '/' + pdb +'_wt.pdb','w') f_old = open(pathoutput + '/' + pdb +'_wt_test.pdb','r') count = 1 for line1 in f_old: if line1[0:6].strip() == 'ATOM': if count < 10: fnew.write('ATOM %s%s' % (str(count),line1[11:])) if count >= 10 and count < 100: fnew.write('ATOM %s%s' % (str(count),line1[11:])) if count >= 100 and count < 1000: fnew.write('ATOM %s%s' % (str(count),line1[11:])) if count >= 1000 and count < 10000: fnew.write('ATOM %s%s' % (str(count),line1[11:])) if count >= 10000 and count < 100000: fnew.write('ATOM %s%s' % (str(count),line1[11:])) count = count + 1 fnew.write("%s\n" % ('END')) fnew.close() f_old.close() pdball.append(pdb) else: continue os.system('rm %s/%s_wt_test.pdb' % (pathoutput, pdb)) def mtpdb_all_addh(): pdball = [] with open(in_file + ".cleaned", 'r') as f: f.next() for line in f: ff = line.split("\t") pdb = ff[8].lower() # 1A43 ligand = ff[6].lower() mut = ff[11][:-1].lower() pdb = pdb + '_' + mut if pdb not in pdball: os.system('cat %s/%s_vmd.pdb %s/%s_%s_ch*.pdb > %s/%s_mt_test.pdb' % (pathoutput, pdb.upper(), pathoutput, pdb.split('_')[0], ligand, pathoutput, pdb)) fnew = open(pathoutput + '/' + pdb +'_mt.pdb','w') f_old = open(pathoutput + '/' + pdb +'_mt_test.pdb','r') count = 1 for line1 in f_old: if line1[0:6].strip() == 'ATOM': if count < 10: fnew.write('ATOM %s%s' % (str(count),line1[11:])) if count >= 10 and count < 100: fnew.write('ATOM %s%s' % (str(count),line1[11:])) if count >= 100 and count < 1000: fnew.write('ATOM %s%s' % (str(count),line1[11:])) if count >= 1000 and count < 10000: fnew.write('ATOM %s%s' % (str(count),line1[11:])) if count >= 10000 and count < 100000: fnew.write('ATOM %s%s' % (str(count),line1[11:])) count = count + 1 fnew.write("%s\n" % ('END')) fnew.close() f_old.close() pdball.append(pdb) else: continue os.system('rm %s/%s_mt_test.pdb' % (pathoutput, pdb)) # Arpeggio def arpeggio(): pdball = [] with open(in_file + ".cleaned", 'r') as f: f.next() for line in f: ff = line.split("\t") pdbid = ff[8].lower() # 1A43 ligand = ff[6].lower() mut = ff[11][:-1].lower() # wild if pdbid not in pdball: pdball.append(pdbid) vmd_temp = open('{}/{}_wt.pdb'.format(pathoutput, pdbid)).read().replace('HSD','HIS') with open('{}/{}_wt_temp.pdb'.format(pathoutput, pdbid),'w') as fw: fw.write(vmd_temp) # run arpeggio os.system('python {} -he {}/{}_wt_temp.pdb'.format(patharpeggio,pathoutput, pdbid)) # mut print(pdbid+'_'+mut) vmd_temp_mut = open('{}/{}_mt.pdb'.format(pathoutput, pdbid+'_'+mut)).read().replace('HSD','HIS') with open('{}/{}_mt_temp.pdb'.format(pathoutput, pdbid+'_'+mut),'w') as fw: fw.write(vmd_temp_mut) # run arpeggio os.system('python {} -he {}/{}_mt_temp.pdb'.format(patharpeggio,pathoutput, pdbid+'_'+mut)) # delete unused files if os.path.exists('{}/{}_wt_temp.contacts'.format(pathoutput,pdbid)) and os.path.exists('{}/{}_mt_temp.contacts'.format(pathoutput,pdbid+'_'+mut)): os.system('rm {}/*_temp.pdb'.format(pathoutput)) os.system('rm {}/*.bs_contacts'.format(pathoutput)) os.system('rm {}/*.specific.sift'.format(pathoutput)) os.system('rm {}/*.sift'.format(pathoutput)) os.system('rm {}/*.specific.siftmatch'.format(pathoutput)) os.system('rm {}/*.siftmatch'.format(pathoutput)) os.system('rm {}/*.specific.polarmatch'.format(pathoutput)) os.system('rm {}/*.polarmatch'.format(pathoutput)) os.system('rm {}/*.ri'.format(pathoutput)) os.system('rm {}/*.rings'.format(pathoutput)) os.system('rm {}/*.ari'.format(pathoutput)) os.system('rm {}/*.amri'.format(pathoutput)) os.system('rm {}/*.amam'.format(pathoutput)) os.system('rm {}/*.residue_sifts'.format(pathoutput)) else: print('arpeggio run error :{}'.format(jobid)) def arpeggio_extract(): first_line = open(in_file + ".cleaned", 'r').readlines()[0][:-1] fclean = pd.read_csv(in_file + ".cleaned",sep='\t',dtype=str) namelist = ['Atom1','Atom2','Clash','Covalent','VdWClash','VdW','Proximal','HydrogenBond','WeakHydrogenBond','HalogenBond','Ionic','MetalComplex','Aromatic','Hydrophobic','Carbonyl','Polar','WeakPolar','InteractingEntities'] allnamelist = ['Arpeggio_'+i+'_sitep2_byAtom_wt' for i in namelist[2:-1]]+['Arpeggio_'+i+'_sitep2_byAtom_mut' for i in namelist[2:-1]] with open(in_file + ".cleaned", 'r') as f, open(pathoutput+'/{}.arpeggio'.format(jobid),'w') as fw: fw.write('{}\t{}\t{}\n'.format('jobid',first_line,'\t'.join(allnamelist))) f.next() for line in f: ff = line.split("\t") pdbfile = ff[0] pdbid = ff[8].lower() # 1A43 mut = ff[11][:-1] partner1 = ff[9] partner2 = ff[10] p1_chain = [i for i in partner1] p2_chain = [j for j in partner2] mutchain = ff[3] col_dict = {i:namelist[i] for i in range(18)} # wild result = pd.read_csv('{}/{}_wt_temp.contacts'.format(pathoutput,pdbid), sep='\t', header=None) result = result.rename(columns = col_dict) result = result[result['Atom1']!='atom_bgn'] for m in namelist[2:-1]: result[m] = result[m].astype(int) contact1 = result['Atom1'].str.split('/', expand=True).rename(columns = {0:'chain1',1:'loc1',2:'atom1'}) contact2 = result['Atom2'].str.split('/', expand=True).rename(columns = {0:'chain2',1:'loc2',2:'atom2'}) allcontacts = pd.concat([contact1, contact2,result], axis=1) allcontacts['chain_loc1'] = allcontacts['chain1']+allcontacts['loc1'] allcontacts['chain_loc2'] = allcontacts['chain2']+allcontacts['loc2'] sitep2 = allcontacts[((allcontacts['chain1'].isin([mut[1]])) & (allcontacts['loc1'].isin([mut[2:-1]])) & (allcontacts['chain2'].isin(p2_chain))) | ((allcontacts['chain2'].isin([mut[1]])) & (allcontacts['loc2'].isin([mut[2:-1]])) & (allcontacts['chain1'].isin(p2_chain)))] ## sitep2 atom_sitep2 = [sum(sitep2[name]) for name in namelist[2:-1]] # mut resultmut = pd.read_csv('{}/{}_mt_temp.contacts'.format(pathoutput,pdbid+'_'+mut.lower()), sep='\t', header=None) resultmut = resultmut.rename(columns = col_dict) resultmut = resultmut[resultmut['Atom1']!='atom_bgn'] for n in namelist[2:-1]: resultmut[n] = resultmut[n].astype(int) contact1mut = resultmut['Atom1'].str.split('/', expand=True).rename(columns = {0:'chain1',1:'loc1',2:'atom1'}) contact2mut = resultmut['Atom2'].str.split('/', expand=True).rename(columns = {0:'chain2',1:'loc2',2:'atom2'}) allcontactsmut = pd.concat([contact1mut, contact2mut,resultmut], axis=1) allcontactsmut['chain_loc1'] = allcontactsmut['chain1']+allcontactsmut['loc1'] allcontactsmut['chain_loc2'] = allcontactsmut['chain2']+allcontactsmut['loc2'] sitep2mut = allcontactsmut[((allcontactsmut['chain1'].isin([mut[1]])) & (allcontactsmut['loc1'].isin([mut[2:-1]])) & (allcontactsmut['chain2'].isin(p2_chain))) | ((allcontactsmut['chain2'].isin([mut[1]])) & (allcontactsmut['loc2'].isin([mut[2:-1]])) & (allcontactsmut['chain1'].isin(p2_chain)))] ## sitep2 atom_sitep2mut = [sum(sitep2mut[name]) for name in namelist[2:-1]] fw.write('{}\t{}\t{}\n'.format(jobid, line[0:-1], '\t'.join([str(i) for i in atom_sitep2+atom_sitep2mut]))) class pdb_network: def __init__(self,pdb,chain=[],uid='0'): self.pdbid = pdb try: file_name = pathoutput+'/'+self.pdbid + ".pdb" print(file_name) f = open(file_name,'r') self.pdb_content = f.read() except: print('no such pdb file') p = PDBParser(PERMISSIVE=1) s = p.get_structure(self.pdbid, file_name)[0] if chain != []: self.chain = chain else: chain_list = Selection.unfold_entities(s, 'C') #C represents chain real_list = [] for i in chain_list: real_list.append(i.id) self.chain = real_list self.res_map = {} for i in self.chain: self.res_map[i] = {} self.get_atom_info() self.build_side_chain_network() self.buid_space_tree() def get_atom_info(self): pdb_text = self.pdb_content chain = self.chain lines = pdb_text.split('\n') all_atom_dict = {} model_count = 0 chain_ass = '' for l in lines: if l[0:5] == 'MODEL': #check model model_count += 1 if model_count ==1: chain_ass = '' else: chain_ass = '_' + str(model_count-1) if l[0:4] == 'ATOM': serial = int(l[7:11].replace(' ','')) #name = l[13:16].replace(' ','') resName = l[17:20].replace(' ','') chain_id = l[20:22].replace(' ','') + chain_ass resSeq = str(l[22:26].replace(' ','')) insider_code = str(l[26]).replace(' ','') if insider_code: resSeq += insider_code x = float(l[31:38].replace(' ','')) y = float(l[39:46].replace(' ','')) z = float(l[47:54].replace(' ','')) element = l[11:17].replace(' ','') element_type = l[11:17].replace(' ','') if chain_id in self.chain: if resSeq not in self.res_map[chain_id]: self.res_map[chain_id][resSeq] = resName resSeq = str(resSeq) + '_' + resName if (chain_id in self.chain) and (element[0] != 'H'): if chain_id in all_atom_dict.keys(): if resSeq in all_atom_dict[chain_id]: all_atom_dict[chain_id][resSeq].append([x,y,z,element_type]) else: all_atom_dict[chain_id][resSeq] = [] all_atom_dict[chain_id][resSeq].append([x,y,z,element_type]) else: all_atom_dict[chain_id] = {} all_atom_dict[chain_id][resSeq] = [] all_atom_dict[chain_id][resSeq].append([x,y,z,element_type]) self.atom_dict = all_atom_dict def build_side_chain_network(self): main_chain = ['C', 'N', 'O', 'OT1', 'OT2', 'CA', 'HA', 'HN', 'HT1', 'HT2', 'HT3'] self.residue_network ={} self.have_no_side_chain = [] for chain_id in self.atom_dict: self.residue_network[chain_id] = {} for res_id in self.atom_dict[chain_id]: res_atom_crood_list = self.atom_dict[chain_id][res_id] x_t = 0 y_t = 0 z_t = 0 x_main = 0 y_main = 0 z_main = 0 atom_count = 0 main_count = 0 for atom_crood in res_atom_crood_list: if atom_crood[3]
backend service is used by a urlMap. response = backends.delete(project=args.project, backendService=name).execute() logging.info("response = %r", response) expired.append(name) except Exception as e: # pylint: disable=broad-except logging.error(e) in_use.append(name) else: unexpired.append(name) if not "nextPageToken" in results: break next_page_token = results["nextPageToken"] logging.info("Unexpired backend services:\n%s", "\n".join(unexpired)) logging.info("Deleted backend services:\n%s", "\n".join(expired)) logging.info("Expired but in-use backend services:\n%s", "\n".join(in_use)) def cleanup_health_checks(args): credentials = GoogleCredentials.get_application_default() compute = discovery.build('compute', 'v1', credentials=credentials) health_checks = compute.healthChecks() next_page_token = None checks = {} while True: results = health_checks.list(project=args.project, pageToken=next_page_token).execute() if not "items" in results: break for d in results["items"]: name = d["name"] checks[name] = d if not "nextPageToken" in results: break next_page_token = results["nextPageToken"] backends = compute.backendServices() services = {} while True: results = backends.list(project=args.project, pageToken=next_page_token).execute() if not "items" in results: break for d in results["items"]: name = d["name"] services[name] = d if not "nextPageToken" in results: break next_page_token = results["nextPageToken"] # Find all health checks not associated with a service. unmatched = [] matched = [] for name in checks.iterkeys(): if not name in services: unmatched.append(name) logging.info("Deleting health check: %s", name) if not args.dryrun: response = health_checks.delete(project=args.project, healthCheck=name).execute() logging.info("response = %s", response) else: matched.append(name) logging.info("Unmatched health checks:\n%s", "\n".join(unmatched)) logging.info("Matched health checks:\n%s", "\n".join(matched)) logging.info("Finished cleanup firewall rules") def get_ssl_certificate_domain(certificate): if "managed" in certificate and "domains" in certificate["managed"]: # We use one domain per certificate. return certificate["managed"]["domains"][0] if "subjectAlternativeNames" in certificate: return certificate["subjectAlternativeNames"][0] return "" def cleanup_certificates(args): credentials = GoogleCredentials.get_application_default() # Using compute beta API other than v1 to get detailed domain information. compute = discovery.build('compute', 'beta', credentials=credentials) certificates = compute.sslCertificates() next_page_token = None unexpired = [] expired = [] while True: results = certificates.list(project=args.project, pageToken=next_page_token).execute() if not "items" in results: break for d in results["items"]: create_time = date_parser.parse(d["creationTimestamp"]) now = datetime.datetime.now(create_time.tzinfo) age = now - create_time name = d["name"] domain = get_ssl_certificate_domain(d) # Expire e2e certs after 4 hours if domain.startswith("kfct"): max_age = datetime.timedelta(hours=4) else: # For autodeployments delete after seven days max_age = datetime.timedelta(days=7) if age > max_age: logging.info("Deleting certifcate: %s for domain %s", d["name"], domain) is_expired = True if not args.dryrun: try: certificates.delete( project=args.project, sslCertificate=d["name"]).execute() except Exception as e: # pylint: disable=broad-except logging.error("There was a problem deleting certifcate %s; " "error: %s", d["name"], e) if is_expired: expired.append("{0} for {1}".format(name, domain)) else: unexpired.append("{0} for {1}".format(name, domain)) if not "nextPageToken" in results: break next_page_token = results["nextPageToken"] logging.info("Unexpired certificates:\n%s", "\n".join(unexpired)) logging.info("expired certificates:\n%s", "\n".join(expired)) logging.info("Finished cleanup certificates") def cleanup_service_accounts(args): logging.info("Cleanup service accounts") credentials = GoogleCredentials.get_application_default() iam = discovery.build('iam', 'v1', credentials=credentials) projects = iam.projects() accounts = [] next_page_token = None while True: service_accounts = iam.projects().serviceAccounts().list( name='projects/' + args.project, pageToken=next_page_token).execute() accounts.extend(service_accounts["accounts"]) if not "nextPageToken" in service_accounts: break next_page_token = service_accounts["nextPageToken"] keys_client = projects.serviceAccounts().keys() unmatched_emails = [] expired_emails = [] unexpired_emails = [] # Service accounts don't specify the creation date time. So we # use the creation time of the key associated with the account. for a in accounts: if not is_match(a["email"]): logging.info("Skipping key %s; it does not match expected names.", a["email"]) unmatched_emails.append(a["email"]) continue keys = keys_client.list(name=a["name"]).execute() is_expired = True for k in keys["keys"]: valid_time = date_parser.parse(k["validAfterTime"]) now = datetime.datetime.now(valid_time.tzinfo) age = now - valid_time if age < datetime.timedelta(hours=args.max_age_hours): is_expired = False break if is_expired: logging.info("Deleting account: %s", a["email"]) if not args.dryrun: iam.projects().serviceAccounts().delete(name=a["name"]).execute() expired_emails.append(a["email"]) else: unexpired_emails.append(a["email"]) logging.info("Unmatched emails:\n%s", "\n".join(unmatched_emails)) logging.info("Unexpired emails:\n%s", "\n".join(unexpired_emails)) logging.info("expired emails:\n%s", "\n".join(expired_emails)) logging.info("Finished cleanup service accounts") def trim_unused_bindings(iamPolicy, accounts): keepBindings = [] for binding in iamPolicy['bindings']: members_to_keep = [] members_to_delete = [] for member in binding['members']: if not member.startswith('serviceAccount:'): members_to_keep.append(member) else: accountEmail = member[15:] if (not is_match(accountEmail)) or (accountEmail in accounts): members_to_keep.append(member) else: members_to_delete.append(member) if members_to_keep: binding['members'] = members_to_keep keepBindings.append(binding) if members_to_delete: logging.info("Delete binding for members:\n%s", "\n".join( members_to_delete)) iamPolicy['bindings'] = keepBindings def cleanup_service_account_bindings(args): logging.info("Cleanup service account bindings") credentials = GoogleCredentials.get_application_default() iam = discovery.build('iam', 'v1', credentials=credentials) accounts = [] next_page_token = None while True: service_accounts = iam.projects().serviceAccounts().list( name='projects/' + args.project, pageToken=next_page_token).execute() for a in service_accounts["accounts"]: accounts.append(a["email"]) if not "nextPageToken" in service_accounts: break next_page_token = service_accounts["nextPageToken"] resourcemanager = discovery.build('cloudresourcemanager', 'v1', credentials=credentials) logging.info("Get IAM policy for project %s", args.project) iamPolicy = resourcemanager.projects().getIamPolicy(resource=args.project, body={}).execute() trim_unused_bindings(iamPolicy, accounts) setBody = {'policy': iamPolicy} if not args.dryrun: resourcemanager.projects().setIamPolicy(resource=args.project, body=setBody).execute() logging.info("Finished cleanup service account bindings") def getAge(tsInRFC3339): # The docs say insert time will be in RFC339 format. # But it looks like it also includes a time zone offset in the form # -HH:MM; which is slightly different from what datetime strftime %z # uses (no colon). # https://cloud.google.com/deployment-manager/docs/reference/latest/deployments/insert # # So we parse out the hours. # # TODO(jlewi): Can we use date_parser like we do in cleanup_service_accounts insert_time_str = tsInRFC3339[:-6] tz_offset = tsInRFC3339[-6:] hours_offset = int(tz_offset.split(":", 1)[0]) RFC3339 = "%Y-%m-%dT%H:%M:%S.%f" insert_time = datetime.datetime.strptime(insert_time_str, RFC3339) # Convert the time to UTC insert_time_utc = insert_time + datetime.timedelta(hours=-1 * hours_offset) age = datetime.datetime.utcnow()- insert_time_utc return age @retrying.retry(stop_max_attempt_number=5, retry_on_exception=is_retryable_exception) def execute_rpc(rpc): """Execute a Google RPC request with retries.""" return rpc.execute() # Wait for 'ops' to finish in 'max_wait_mins' or return the remaining ops. # operation_resource must implement 'get()' method. def wait_ops_max_mins(operation_resource, args, ops, max_wait_mins=15): end_time = datetime.datetime.now() + datetime.timedelta(minutes=max_wait_mins) while datetime.datetime.now() < end_time and ops: not_done = [] for op in ops: op = operation_resource.get(project=args.project, operation=op["name"]).execute() status = op.get("status", "") if status != "DONE": not_done.append(op) ops = not_done if ops: time.sleep(30) return ops def cleanup_deployments(args): # pylint: disable=too-many-statements,too-many-branches logging.info("Cleanup deployments") credentials = GoogleCredentials.get_application_default() dm = discovery.build("deploymentmanager", "v2", credentials=credentials) deployments_client = dm.deployments() deployments = deployments_client.list(project=args.project).execute() unexpired = [] expired = [] delete_ops = [] for d in deployments.get("deployments", []): if not d.get("insertTime", None): logging.warning("Deployment %s doesn't have a deployment time " "skipping it", d["name"]) continue name = d["name"] if not is_match(name): logging.info("Skipping Deployment %s; it does not match expected names.", name) continue full_insert_time = d.get("insertTime") age = getAge(full_insert_time) if "error" in d.get("operation", {}): # Prune failed deployments more aggressively logging.info("Deployment %s is in error state %s", d.get("name"), d.get("operation").get("error")) max_age = datetime.timedelta(minutes=10) else: max_age = datetime.timedelta(hours=args.max_age_hours) if age < max_age: unexpired.append(name) logging.info("Deployment %s has not expired", name) continue logging.info("Deployment %s has expired", name) expired.append(name) logging.info("Deleting deployment %s", name) if not args.dryrun: try: op = deployments_client.delete(project=args.project, deployment=name).execute() delete_ops.append(op) except Exception as e: # pylint: disable=broad-except # Keep going on error because we want to delete the other deployments. # TODO(jlewi): Do we need to handle cases by issuing delete with abandon? logging.error("There was a problem deleting deployment %s; error %s", name, e) delete_ops = wait_ops_max_mins(dm.operations(), args, delete_ops, max_wait_mins=15) not_done_names = [op["name"] for op in delete_ops] logging.info("Delete ops that didn't finish:\n%s", "\n".join(not_done_names)) logging.info("Unexpired deployments:\n%s", "\n".join(unexpired)) logging.info("expired deployments:\n%s", "\n".join(expired)) logging.info("Finished cleanup deployments") def cleanup_clusters(args): logging.info("Cleanup clusters") credentials = GoogleCredentials.get_application_default() gke = discovery.build("container", "v1", credentials=credentials) # Collect clusters for which deployment might no longer exist. clusters_client = gke.projects().zones().clusters() expired = [] unexpired = [] stopping = [] for zone in args.zones.split(","): clusters = clusters_client.list(projectId=args.project, zone=zone).execute() if not clusters: continue for c in clusters["clusters"]: name = c["name"] if not is_match(name): logging.info("Skipping cluster%s; it does not match expected names.", name) continue full_insert_time = c["createTime"] insert_time_str = full_insert_time[:-6] tz_offset = full_insert_time[-6:] hours_offset = int(tz_offset.split(":", 1)[0]) RFC3339 = "%Y-%m-%dT%H:%M:%S" insert_time = datetime.datetime.strptime(insert_time_str, RFC3339) # Convert the time to UTC insert_time_utc = insert_time + datetime.timedelta(hours=-1 * hours_offset) age = datetime.datetime.utcnow()- insert_time_utc # https://cloud.google.com/kubernetes-engine/docs/reference/rest/v1/projects.locations.clusters#Cluster.Status if c.get("status", "") in ["ERROR", "DEGRADED"]: # Prune failed deployments more aggressively logging.info("Cluster %s is in error state; %s", c["name"], c.get("statusMessage", "")) max_age = datetime.timedelta(minutes=10) else: max_age = datetime.timedelta(hours=args.max_age_hours) if age > max_age: if c.get("status", "") == "STOPPING": logging.info("Cluster %s is already stopping; not redeleting", c["name"]) stopping.append(c["name"]) continue expired.append(name) logging.info("Deleting cluster %s in zone %s", name, zone) if not args.dryrun: clusters_client.delete(projectId=args.project, zone=zone, clusterId=name).execute() else: unexpired.append(name) logging.info("Unexpired clusters:\n%s", "\n".join(unexpired)) logging.info("Already stopping clusters:\n%s", "\n".join(stopping)) logging.info("expired clusters:\n%s", "\n".join(expired)) logging.info("Finished cleanup clusters") # The order of cleanup_forwarding_rules, cleanup_target_http_proxies, # cleanup_url_maps, cleanup_backend_services, cleanup_instance_groups makes # sure ingress resources are GCed in one run of this script. See # https://github.com/kubernetes/ingress-gce/issues/136#issuecomment-371254595 def cleanup_all(args): ops = [# Deleting deploymens should be called first because hopefully that will # cleanup all the resources associated with the deployment cleanup_deployments, cleanup_clusters, cleanup_endpoints, cleanup_service_accounts, cleanup_service_account_bindings, cleanup_workflows, cleanup_disks, cleanup_forwarding_rules, cleanup_target_https_proxies, cleanup_target_http_proxies, cleanup_certificates, cleanup_url_maps, cleanup_backend_services, cleanup_firewall_rules, cleanup_health_checks, cleanup_instance_groups] for op in ops: try: op(args) except Exception
"2013-12-11T22:14:00Z", }, { "id": "MnePSAXVEeiR2Ef5_SqrnA", "created": "2013-12-13T00:17:53Z", "updated": "2013-12-13T00:17:53Z", }, { "id": "M2eSpAXVEeimGd_D5lc7_g", "created": "2013-12-13T01:01:20Z", "updated": "2013-12-13T01:01:20Z", }, { "id": "NCbIXgXVEei-YvOb79ehXg", "created": "2013-12-14T03:20:48Z", "updated": "2013-12-14T03:20:48Z", }, { "id": "NNeRjgXVEeifIr-ejOzWEg", "created": "2013-12-14T05:12:46Z", "updated": "2013-12-14T05:12:46Z", }, { "id": "NYf5mAXVEeiTWoe6yIJ08Q", "created": "2013-12-15T10:53:31Z", "updated": "2013-12-15T10:53:31Z", }, { "id": "NjpD0gXVEei8Tk9CmOcbIA", "created": "2013-12-16T20:16:46Z", "updated": "2013-12-16T20:16:46Z", }, { "id": "N0nv6AXVEei7Cq-2DRp7xA", "created": "2013-12-17T04:37:04Z", "updated": "2013-12-17T04:37:04Z", }, { "id": "OBrE4gXVEei5KCsQJ7FMHw", "created": "2013-12-19T17:41:43Z", "updated": "2013-12-19T17:41:43Z", }, { "id": "OOMLFAXVEeiMuWMN33Vmag", "created": "2013-12-21T00:17:40Z", "updated": "2013-12-21T00:17:40Z", }, { "id": "OXbDSgXVEeiu7VNvTKaaSA", "created": "2013-12-21T00:21:06Z", "updated": "2013-12-21T00:21:06Z", }, { "id": "OhC3ygXVEeiTi4djwLbqNA", "created": "2013-12-21T00:25:02Z", "updated": "2013-12-21T00:25:02Z", }, { "id": "Ortm6AXVEeiu7icd8rdu1w", "created": "2013-12-21T01:25:52Z", "updated": "2013-12-21T01:25:52Z", }, { "id": "O4EFiAXVEeiS6UvNA8FXIA", "created": "2013-12-21T01:26:29Z", "updated": "2013-12-21T01:26:29Z", }, { "id": "PF_4BgXVEeiX4ZczIx0X9w", "created": "2013-12-21T01:28:27Z", "updated": "2013-12-21T01:28:27Z", }, { "id": "PSVNrgXVEeimGl9NJcyuUw", "created": "2013-12-21T01:28:30Z", "updated": "2013-12-21T01:28:30Z", }, { "id": "PblCKgXVEeiu7yOabwzbsQ", "created": "2013-12-21T01:35:18Z", "updated": "2013-12-21T01:35:18Z", }, { "id": "PoW4eAXVEeiOsEtdli-uuw", "created": "2013-12-21T01:43:04Z", "updated": "2013-12-21T01:43:04Z", }, { "id": "PzZI3AXVEeiKpIuEuNIjTg", "created": "2013-12-21T02:10:04Z", "updated": "2013-12-21T02:10:04Z", }, { "id": "P_vOVAXVEeiJknvanjO6aA", "created": "2013-12-21T02:19:23Z", "updated": "2013-12-21T02:19:23Z", }, { "id": "QO8iegXVEeiO-KtNJglzaw", "created": "2013-12-21T02:22:53Z", "updated": "2013-12-21T02:22:53Z", }, { "id": "Qel5bgXVEeisnffYqrH_Rw", "created": "2013-12-21T02:24:53Z", "updated": "2013-12-21T02:24:53Z", }, { "id": "Qwk0sAXVEei8T7-BLoi-_A", "created": "2013-12-21T02:27:33Z", "updated": "2013-12-21T02:27:33Z", }, { "id": "RBtsQgXVEeiKw9sQt8ZHeQ", "created": "2013-12-21T02:37:55Z", "updated": "2013-12-21T02:37:55Z", }, { "id": "RRItcAXVEei5KZs7hO4kCQ", "created": "2013-12-21T02:38:14Z", "updated": "2013-12-21T02:38:14Z", }, { "id": "RehFXgXVEei6fe9VZjAzJw", "created": "2013-12-21T02:50:44Z", "updated": "2013-12-21T02:50:44Z", }, { "id": "Rpgq0gXVEeiVhXc8G83gWw", "created": "2013-12-21T03:06:38Z", "updated": "2013-12-21T03:06:38Z", }, { "id": "R1ZwAAXVEeiZ2NORn7-OZQ", "created": "2013-12-21T03:20:03Z", "updated": "2013-12-21T03:20:03Z", }, { "id": "SBxHigXVEeiOsfMQ7HbQTw", "created": "2013-12-21T03:26:36Z", "updated": "2013-12-21T03:26:36Z", }, { "id": "SMVvhgXVEeif5FdSUzxpYQ", "created": "2013-12-21T03:34:58Z", "updated": "2013-12-21T03:34:58Z", }, { "id": "SXrA3gXVEeiSSr9NCnnx5Q", "created": "2013-12-21T03:37:25Z", "updated": "2013-12-21T03:37:25Z", }, { "id": "SiqprgXVEeiR2W8FFU0U8w", "created": "2013-12-21T03:43:51Z", "updated": "2013-12-21T03:43:51Z", }, { "id": "S4i91gXVEeiemDeXaIh-DQ", "created": "2013-12-21T04:12:17Z", "updated": "2013-12-21T04:12:17Z", }, { "id": "TJ8dZAXVEeicnYOWoRVqnw", "created": "2013-12-21T04:14:33Z", "updated": "2013-12-21T04:14:33Z", }, { "id": "TVvF9AXVEei13rej02DrhA", "created": "2013-12-21T04:30:35Z", "updated": "2013-12-21T04:30:35Z", }, { "id": "Thg16gXVEeiKXevLjCFE9Q", "created": "2013-12-21T04:46:17Z", "updated": "2013-12-21T04:46:17Z", }, { "id": "TvuBBgXVEei6fre8uQ39fQ", "created": "2013-12-21T04:47:04Z", "updated": "2013-12-21T04:47:04Z", }, { "id": "T-ea0gXVEeiIO2MqYkt9mg", "created": "2013-12-21T04:48:38Z", "updated": "2013-12-21T04:48:38Z", }, { "id": "UJfwigXVEeiS6ldtwEDwGw", "created": "2013-12-21T05:08:29Z", "updated": "2013-12-21T05:08:29Z", }, { "id": "Ucko_AXVEeirv-P8W1dCkg", "created": "2013-12-21T05:41:44Z", "updated": "2013-12-21T05:41:44Z", }, { "id": "UvDAbgXVEeiS6yfTzm-O8A", "created": "2013-12-21T05:41:52Z", "updated": "2013-12-21T05:41:52Z", }, { "id": "VAH4pgXVEeikw-O0N2_qlw", "created": "2013-12-21T06:54:30Z", "updated": "2013-12-21T06:54:30Z", }, { "id": "VNcLwgXVEeifp3cgcHHDOQ", "created": "2013-12-21T07:49:06Z", "updated": "2013-12-21T07:49:06Z", }, { "id": "Vg95PgXVEei-bduO1vd8FA", "created": "2013-12-21T07:59:14Z", "updated": "2013-12-21T07:59:14Z", }, { "id": "VrLy2gXVEei5PwccjYPEuw", "created": "2013-12-21T08:39:53Z", "updated": "2013-12-21T08:39:53Z", }, { "id": "V2fbbgXVEeiKXrf3himIbQ", "created": "2013-12-21T09:19:59Z", "updated": "2013-12-21T09:19:59Z", }, { "id": "WHe4bAXVEeimIuOYpUm2og", "created": "2013-12-21T21:49:43Z", "updated": "2013-12-21T21:49:43Z", }, { "id": "WV5l0gXVEei-w6unFKV9lQ", "created": "2013-12-21T22:39:53Z", "updated": "2013-12-21T22:39:53Z", }, { "id": "WlFTAAXVEeiSSxf7tkeYLQ", "created": "2013-12-22T04:47:28Z", "updated": "2013-12-22T04:47:28Z", }, { "id": "Www1EgXVEeiCdiNK_lM6YA", "created": "2013-12-22T07:30:45Z", "updated": "2013-12-22T07:30:45Z", }, { "id": "XAJlSgXVEeivFs-XfUxfTg", "created": "2013-12-22T13:07:40Z", "updated": "2013-12-22T13:07:40Z", }, { "id": "XLlyqAXVEeiTW2PRtHyVDA", "created": "2013-12-23T00:04:42Z", "updated": "2013-12-23T00:04:42Z", }, { "id": "XUCXYAXVEeifI7dz4m-5zg", "created": "2013-12-23T03:16:59Z", "updated": "2013-12-23T03:16:59Z", }, { "id": "Xhbg6gXVEei5s4-4x6xrnQ", "created": "2013-12-23T05:40:09Z", "updated": "2013-12-23T05:40:09Z", }, { "id": "XqkzMgXVEeiOsvdzm3DFXw", "created": "2013-12-23T13:19:05Z", "updated": "2013-12-23T13:19:05Z", }, { "id": "X0WmGAXVEei7C5e_1Fxr5A", "created": "2013-12-23T23:07:57Z", "updated": "2013-12-23T23:07:57Z", }, { "id": "X_uINAXVEeiCd7e4s5PDpg", "created": "2013-12-25T05:57:50Z", "updated": "2013-12-25T05:57:50Z", }, { "id": "YJU5ogXVEeikYD8tpIoT8A", "created": "2013-12-25T06:13:36Z", "updated": "2013-12-25T06:13:36Z", }, { "id": "YaqPzAXVEeiTjA-rPKT6gQ", "created": "2013-12-28T02:14:26Z", "updated": "2013-12-28T02:14:26Z", }, { "id": "YlkRWgXVEeiS7Ce_K-XI2g", "created": "2013-12-28T13:16:09Z", "updated": "2013-12-28T13:16:09Z", }, { "id": "YwUn7AXVEeidjuee5K5y_Q", "created": "2013-12-31T23:46:00Z", "updated": "2013-12-31T23:46:00Z", }, { "id": "Y82rrgXVEeid9ke5Vu29pw", "created": "2014-01-01T04:58:40Z", "updated": "2014-01-01T04:58:40Z", }, { "id": "ZJEDTAXVEeivSFcuEl5xMA", "created": "2014-01-03T05:46:38Z", "updated": "2014-01-03T05:46:38Z", }, { "id": "ZaO2HAXVEeivSSvgjbz9rw", "created": "2014-01-03T05:55:40Z", "updated": "2014-01-03T05:55:40Z", }, { "id": "ZjuUlgXVEei_LV_AxKCrcg", "created": "2014-01-07T23:57:50Z", "updated": "2014-01-07T23:57:50Z", }, { "id": "ZrKtsAXVEeifqF9KTsi7cw", "created": "2014-01-08T00:34:21Z", "updated": "2014-01-08T00:34:21Z", }, { "id": "Z3w-HgXVEeidj1v1AjanFA", "created": "2014-01-08T15:41:13Z", "updated": "2014-01-08T15:41:13Z", }, { "id": "aC1NgAXVEeiJk2vRpN1ZkQ", "created": "2014-01-08T18:27:56Z", "updated": "2014-01-08T18:27:56Z", }, { "id": "aTwY-gXVEei13-d9QjKP1w", "created": "2014-01-09T22:37:20Z", "updated": "2014-01-09T22:37:20Z", }, { "id": "abFBIAXVEeiKpduiL9k8QA", "created": "2014-01-10T17:59:34Z", "updated": "2014-01-10T17:59:34Z", }, { "id": "ah9m-gXVEeioiUOSaiqb0g", "created": "2014-01-11T03:04:14Z", "updated": "2014-01-11T03:04:14Z", }, { "id": "atXdpAXVEei5QCs82nHQug", "created": "2014-01-11T03:30:48Z", "updated": "2014-01-11T03:30:48Z", }, { "id": "a1uNvgXVEeioioNlN1-ulQ", "created": "2014-01-11T03:32:50Z", "updated": "2014-01-11T03:32:50Z", }, { "id": "a9U3wgXVEeiu8Ac_sDZZ2g", "created": "2014-01-11T04:12:47Z", "updated": "2014-01-11T04:12:47Z", }, { "id": "bFuZcAXVEeitCwvHQNNpAg", "created": "2014-01-11T20:09:01Z", "updated": "2014-01-11T20:09:01Z", }, { "id": "bUDbwAXVEeiKX9dWc-i70Q", "created": "2014-01-13T23:14:31Z", "updated": "2014-01-13T23:14:31Z", }, { "id": "bfL7PgXVEei8UCNLrA3_pQ", "created": "2014-01-15T05:54:08Z", "updated": "2014-01-15T05:54:08Z", }, { "id": "bqDUSAXVEeimbFsWFazJBg", "created": "2014-01-16T02:22:17Z", "updated": "2014-01-16T02:22:17Z", }, { "id": "b0ZstAXVEei0jtu_cey6Jw", "created": "2014-01-16T02:34:03Z", "updated": "2014-01-16T02:34:03Z", }, { "id": "cCLfMgXVEei3FGuezqc0sQ", "created": "2014-01-17T02:00:01Z", "updated": "2014-01-17T02:00:01Z", }, { "id": "cMeN1AXVEeioiyNJ4sarTg", "created": "2014-01-19T07:08:59Z", "updated": "2014-01-19T07:08:59Z", }, { "id": "cetvPAXVEei-Y49Cxb4FYA", "created": "2014-01-21T20:11:59Z", "updated": "2014-01-21T20:11:59Z", }, { "id": "cwlueAXVEeiY2QefjU-iwA", "created": "2014-01-22T01:27:51Z", "updated": "2014-01-22T01:27:51Z", }, { "id": "c_Pe1gXVEei0j9cgeBDk3g", "created": "2014-01-22T13:04:26Z", "updated": "2014-01-22T13:04:26Z", }, { "id": "dW1BqAXVEeiyf0MlyFuGQw", "created": "2014-01-22T17:46:15Z", "updated": "2014-01-22T17:46:15Z", }, { "id": "dlJ38AXVEeietp-jhxOjlQ", "created": "2014-01-22T20:03:27Z", "updated": "2014-01-22T20:03:27Z", }, { "id": "dutMFAXVEeiYJndJD_ZwDg", "created": "2014-01-24T18:24:07Z", "updated": "2014-01-24T18:24:07Z", }, { "id": "d1biJgXVEeiKpisG2ZL56w", "created": "2014-01-26T03:02:55Z", "updated": "2014-01-26T03:02:55Z", }, { "id": "eAqTjgXVEeiuAJPUljxanQ", "created": "2014-01-27T11:03:05Z", "updated": "2014-01-27T11:03:05Z", }, { "id": "eLyLhAXVEeiTjWPoeozH0Q", "created": "2014-02-05T21:21:39Z", "updated": "2014-02-05T21:21:39Z", }, { "id": "eXquNAXVEeiygNdrk6MFuA", "created": "2014-02-10T17:36:20Z", "updated": "2014-02-10T17:36:20Z", }, { "id": "ekjIoAXVEeiSTEtClgOZkA", "created": "2014-02-15T00:18:33Z", "updated": "2014-02-15T00:18:33Z", }, { "id": "exetvgXVEeiOsztuMCZIjg", "created": "2014-02-16T13:01:17Z", "updated": "2014-02-16T13:01:17Z", }, { "id": "e8yJbgXVEeiet8MfYM1xtA", "created": "2014-02-18T17:06:58Z", "updated": "2014-02-18T17:06:58Z", }, { "id": "fNIxdAXVEei5K6sMYqKCgA", "created": "2014-02-20T15:48:24Z", "updated": "2014-02-20T15:48:24Z", }, { "id": "fXN6mAXVEeiB3PtZQ69UBQ", "created": "2014-02-21T23:16:45Z", "updated": "2014-02-21T23:16:45Z", }, { "id": "fjI_tAXVEeiQR7PH64QgzQ", "created": "2014-02-25T15:54:15Z", "updated": "2014-02-25T15:54:15Z", }, { "id": "fy2yfAXVEeiMugslt49jNw", "created": "2014-03-01T09:56:26Z", "updated": "2014-03-01T09:56:26Z", }, { "id": "gGR8tgXVEeiTXMsaVIimdw", "created": "2014-03-07T23:05:52Z", "updated": "2014-03-07T23:05:52Z", }, { "id": "gUUVeAXVEei-ZNczgafviQ", "created": "2014-03-11T10:20:21Z", "updated": "2014-03-11T10:20:21Z", }, { "id": "giMhnAXVEeimG6eYUo8iIg", "created": "2014-03-27T12:58:01Z", "updated": "2014-03-27T12:58:01Z", }, { "id": "guznmAXVEeiYJ8uT3p7qOA", "created": "2014-03-30T19:06:44Z", "updated": "2014-03-30T19:06:44Z", }, { "id": "g8ASCAXVEeimHE8YISGciA", "created": "2014-04-01T17:08:07Z", "updated": "2014-04-01T17:08:07Z", }, { "id": "hKlgegXVEeiD0nvIVyHEdg", "created": "2014-04-02T00:38:25Z", "updated": "2014-04-02T00:38:25Z", }, { "id": "hVfjXAXVEeiR26_jo8rq0Q", "created": "2014-04-02T02:10:48Z", "updated": "2014-04-02T02:10:48Z", }, { "id": "hrUsKAXVEeiB3VcZMGAQZA", "created": "2014-04-02T08:33:01Z", "updated": "2014-04-02T08:33:01Z", }, { "id": "h7HoAAXVEeiKxNeHKOn7Bg", "created": "2014-04-02T11:21:42Z", "updated": "2014-04-02T11:21:42Z", }, { "id": "iFGQHAXVEeiMuw_115VqJw", "created": "2014-04-02T14:01:49Z", "updated": "2014-04-02T14:01:49Z", }, { "id": "iQhgRAXVEeimHV8o1d3KhQ", "created": "2014-04-02T20:50:17Z", "updated": "2014-04-02T20:50:17Z", }, { "id": "ibj7ZgXVEeirwH-HJfZj_w", "created": "2014-04-03T09:30:04Z", "updated": "2014-04-03T09:30:04Z", }, { "id": "inw5KAXVEei3NyPjHKfbSA", "created": "2014-04-03T09:41:25Z", "updated": "2014-04-03T09:41:25Z", }, { "id": "ixb4FAXVEeiuAW95AlK9UA", "created": "2014-04-03T13:43:09Z", "updated": "2014-04-03T13:43:09Z", }, { "id": "i81tkgXVEeiB3ms1-zJYlw", "created": "2014-04-04T21:52:14Z", "updated": "2014-04-04T21:52:14Z", }, { "id": "jFa9VAXVEeiR3Df1ts5aUg", "created": "2014-04-04T22:55:48Z", "updated": "2014-04-04T22:55:48Z", }, { "id": "jSMAvAXVEei_Lu_7pp7vUw", "created": "2014-04-06T05:22:33Z", "updated": "2014-04-06T05:22:33Z", }, { "id": "jeIDcgXVEeiYKFeUG1YUHg", "created": "2014-04-08T00:01:03Z", "updated": "2014-04-08T00:01:03Z", }, { "id": "jpzgFgXVEeif5Wt0qdVyEQ", "created": "2014-04-08T06:31:58Z", "updated": "2014-04-08T06:31:58Z", }, { "id": "j0vY-gXVEeiO-WcBtvmF-Q", "created": "2014-04-08T22:23:12Z", "updated": "2014-04-08T22:23:12Z", }, { "id": "kCJB4gXVEeimI0_PmBv8HQ", "created": "2014-04-09T04:44:55Z", "updated": "2014-04-09T04:44:55Z", }, { "id": "kSraIgXVEei3OKfsTjfX3Q", "created": "2014-04-09T18:23:42Z", "updated": "2014-04-09T18:23:42Z", }, { "id": "kge7cgXVEeisnzdRrQAw4g", "created": "2014-04-10T13:37:05Z", "updated": "2014-04-10T13:37:05Z", }, { "id": "ktwbagXVEeiKxb_jvZm1_A", "created": "2014-04-11T03:08:12Z", "updated": "2014-04-11T03:08:12Z", }, { "id": "k6KFtgXVEeid99P5VdSVKg", "created": "2014-04-11T20:41:11Z", "updated": "2014-04-11T20:41:11Z", }, { "id": "lKD5ZgXVEeikxIuyCTKdIQ", "created": "2014-04-23T07:14:56Z", "updated": "2014-04-23T07:14:56Z", }, { "id": "lYqTPAXVEeiTjoM3R52wTg", "created": "2014-05-08T19:30:37Z", "updated": "2014-05-08T19:30:37Z", }, { "id": "lkcDAAXVEeisoOcILpUjCA", "created": "2014-05-08T20:00:00Z", "updated": "2014-05-08T20:00:00Z", }, { "id": "lyo_TgXVEei5Kbcs3kL-6Q", "created": "2014-05-09T20:37:52Z", "updated": "2014-05-09T20:37:52Z", }, { "id": "l-9x7AXVEeiMUtM_A1W2gQ", "created": "2014-05-09T20:38:31Z", "updated": "2014-05-09T20:38:31Z", }, { "id": "mJroTAXVEeiyer9UQ1WV7g", "created": "2014-05-12T12:05:53Z", "updated": "2014-05-12T12:05:53Z", }, { "id": "mT_YrAXVEeiye0cy0wwWNg", "created": "2014-05-12T20:36:17Z", "updated": "2014-05-12T20:36:17Z", }, { "id": "mf-lLgXVEei3OctV4Ab7JQ", "created": "2014-05-16T13:54:41Z", "updated": "2014-05-16T13:54:41Z", }, { "id": "mr95TgXVEeiO-mPcDh5dnw", "created": "2014-05-16T14:10:16Z", "updated": "2014-05-16T14:10:16Z", }, { "id": "m12nXgXVEei-ZQ9TJM_STA", "created": "2014-05-22T17:27:32Z", "updated": "2014-05-22T17:27:32Z", }, { "id": "m-SlzgXVEeicMacppm0AVw", "created": "2014-05-28T12:29:33Z", "updated": "2014-05-28T12:29:33Z", }, { "id": "nM7xBgXVEeiojB87o4IP6Q", "created": "2014-06-02T20:15:35Z", "updated": "2014-06-02T20:15:35Z", }, { "id": "nYfG4AXVEeiTj_dAEC1FyA", "created": "2014-06-04T21:32:06Z", "updated": "2014-06-04T21:32:06Z", }, { "id": "nmhhoAXVEeiOtJf60jbzNw", "created": "2014-06-05T03:36:20Z", "updated": "2014-06-05T03:36:20Z", }, { "id": "nz8N4AXVEeiVeIOANa2V8A", "created": "2014-06-11T00:34:54Z", "updated": "2014-06-11T00:34:54Z", }, { "id": "n_gYEgXVEeiojQ9nss3KKQ", "created": "2014-06-19T00:19:31Z", "updated": "2014-06-19T00:19:31Z", }, { "id": "oPIpLgXVEei28DtP66DIVA", "created": "2014-06-23T16:37:00Z", "updated": "2014-06-23T16:37:00Z", }, { "id": "oZtqNAXVEei14fP1v-kVPA", "created": "2014-06-25T13:12:45Z", "updated": "2014-06-25T13:12:45Z", }, { "id": "orov_gXVEeiu8bNzrulgYA", "created": "2014-06-25T13:59:50Z", "updated": "2014-06-25T13:59:50Z", }, { "id": "o1EMJgXVEeiemQM7J1CFhg", "created": "2014-06-26T15:41:20Z", "updated": "2014-06-26T15:41:20Z", }, { "id": "pCBApAXVEeib39O6cMEmbg", "created": "2014-06-26T15:43:38Z", "updated": "2014-06-26T15:43:38Z", }, { "id": "pO2YOAXVEeiIPDec14KJOg", "created": "2014-06-26T15:45:33Z", "updated": "2014-06-26T15:45:33Z", }, { "id": "pdloWAXVEeitDZ_Fdrr-9Q", "created": "2014-06-26T15:47:59Z", "updated": "2014-06-26T15:47:59Z", }, { "id": "puEWJAXVEeitDr-EFgGTxA", "created": "2014-06-26T15:53:58Z", "updated": "2014-06-26T15:53:58Z", }, { "id": "p_cSAgXVEei6fw-x_X1k6w", "created": "2014-06-26T15:55:37Z", "updated": "2014-06-26T15:55:37Z", }, { "id": "qOBmPAXVEeiS7Yt2ZYxm-A", "created": "2014-06-26T16:01:44Z", "updated": "2014-06-26T16:01:44Z", }, { "id": "qcm_bAXVEeiMU0eOABzhYA", "created": "2014-06-26T16:02:31Z", "updated": "2014-06-26T16:02:31Z", }, { "id": "qwzugAXVEeiY2j8o68a3fQ", "created": "2014-06-26T16:04:47Z", "updated": "2014-06-26T16:04:47Z", }, { "id": "q8H1oAXVEeifrDeDnYBBiw", "created": "2014-06-26T19:17:35Z", "updated": "2014-06-26T19:17:35Z", }, { "id": "rJg-OgXVEeikxa9OL7RrvA", "created": "2014-07-01T16:23:38Z", "updated": "2014-07-01T16:23:38Z", }, { "id": "relkdgXVEeiluHtUgvVFOQ", "created": "2014-07-02T20:35:16Z", "updated": "2014-07-02T20:35:16Z", }, { "id": "roP1rgXVEei013cL_XQ7fw", "created": "2014-07-09T00:18:03Z", "updated": "2014-07-09T00:18:03Z", }, { "id": "r5wcAAXVEeifratIoM09ig", "created": "2014-07-17T00:41:14Z", "updated": "2014-07-17T00:41:14Z", }, { "id": "sHldVAXVEeiuAvtOm7QnNg", "created": "2014-07-18T00:02:24Z", "updated": "2014-07-18T00:02:24Z", }, { "id": "sPlMvAXVEeitD59mB5vaUA", "created": "2014-07-18T13:24:25Z", "updated": "2014-07-18T13:24:25Z", }, { "id": "sZ5phgXVEei3Ok8f05GQqw", "created": "2014-07-22T17:12:31Z", "updated": "2014-07-22T17:12:31Z", }, { "id": "slAiegXVEeiOtZ_NKGL3Gg", "created": "2014-07-30T18:00:45Z", "updated": "2014-07-30T18:00:45Z", }, { "id": "sxr9ugXVEeiTkPP_Ltm_1g", "created": "2014-07-31T02:33:39Z", "updated":
storage[ name ] = h info( newline( '=== Added local host', h ) ) return h def add_remote_host( self, name, user, server, **params ): """ Adds a new remote host to the current topology and returns a RemoteHostConfig object representing it. - name : a textual representation of the host - user : the name of the user on the remote server - server: the IP address of the remote server """ if self.built: raise RuntimeError( 'build() method was already called; cannot add any more hosts' ) name = as_str( name ) storage = self.hosts check_duplicate( storage, name ) h = self._new_remote_node( RemoteHostConfig, name, user, server, **params ) storage[ name ] = h info( newline( '=== Added remote host', h ) ) return h def add_local_varanus_collector( self, name, varanus_home, cid, **params ): """ Adds a local VARANUS collector to the current topology and returns a LocalCollectorConfig object representing it, or a NullNodeConfig if VARANUS usage is disabled. - name : a textual representation of the collector - varanus_home: home directory of varanus project - cid : the collector identifier """ if self.enable_varanus: if self.built: raise RuntimeError( 'build() method was already called; cannot add any more collectors' ) name = as_str( name ) storage = self.hosts check_duplicate( storage, name ) c = self._new_node( LocalCollectorConfig, name, \ varanus_home=varanus_home, cid=cid, \ **params ) storage[ name ] = c info( newline( '=== Added local VARANUS collector', c ) ) return c else: return self.add_null_host( name ) def add_remote_varanus_collector( self, name, user, server, varanus_home, cid, **params ): """ Adds a remote VARANUS collector to the current topology and returns a RemoteCollectorConfig object representing it, or a NullNodeConfig if VARANUS usage is disabled. - name : a textual representation of the collector - user : the name of the user on the remote server - server : the IP address of the remote server - varanus_home: home directory of varanus project - cid : the collector identifier """ if self.enable_varanus: if self.built: raise RuntimeError( 'build() method was already called; cannot add any more collectors' ) name = as_str( name ) storage = self.hosts check_duplicate( storage, name ) c = self._new_remote_node( RemoteCollectorConfig, name, user, server, \ varanus_home=varanus_home, cid=cid, \ **params ) storage[ name ] = c info( newline( '=== Added remote VARANUS collector', c ) ) return c else: return self.add_null_host( name ) def add_custom_local_host( self, name, startcmd, stopcmd, morecmds=None, \ **params ): """ Adds a new custom local host to the current topology and returns a CustomLocalHostConfig object representing it. - name : a textual representation of the host - startcmd: a function used to start the host when called - stopcmd : a function used to stop the host when called - morecmds: additional optional commands to define in the Mininet node """ if self.built: raise RuntimeError( 'build() method was already called; cannot add any more hosts' ) name = as_str( name ) storage = self.hosts check_duplicate( storage, name ) h = self._new_node( CustomLocalHostConfig, name, \ startcmd=startcmd, stopcmd=stopcmd, morecmds=morecmds, \ **params ) storage[ name ] = h info( newline( '=== Added custom local host', h ) ) return h def add_custom_remote_host( self, name, user, server, \ startcmd, stopcmd, morecmds=None, \ **params ): """ Adds a custom remote host to the current topology and returns a CustomRemoteHostConfig object representing it. - name : a textual representation of the host - user : the name of the user on the remote server - server : the IP address of the remote server - startcmd: a function used to start the host when called - stopcmd : a function used to stop the host when called - morecmds: additional optional commands to define in the Mininet node """ if self.built: raise RuntimeError( 'build() method was already called; cannot add any more hosts' ) name = as_str( name ) storage = self.hosts check_duplicate( storage, name ) h = self._new_remote_node( CustomRemoteHostConfig, name, user, server, \ startcmd=startcmd, stopcmd=stopcmd, morecmds=morecmds, \ **params ) storage[ name ] = h info( newline( '=== Added custom remote host', h ) ) return h def add_null_host( self, name, **params ): """ Adds a dummy non-existent host to the current topology and returns a NullNodeConfig object representing it. - name: a textual representation of the host """ if self.built: raise RuntimeError( 'build() method was already called; cannot add any more hosts' ) name = as_str( name ) storage = self.hosts check_duplicate( storage, name ) h = self._new_node( NullNodeConfig, name, **params ) storage[ name ] = h info( newline( '=== Added null host', h ) ) return h def add_local_ovs_switch( self, name, **params ): """ Adds a new local OVS switch to the current topology and returns a LocalOVSSwitchConfig object representing it. - name: a textual representation of the switch """ if self.built: raise RuntimeError( 'build() method was already called; cannot add any more switches' ) name = as_str( name ) storage = self.switches check_duplicate( storage, name ) s = self._new_node( LocalOVSSwitchConfig, name, \ protocols=self.of_version, **params ) storage[ name ] = s info( newline( '=== Added local OVS switch', s ) ) return s def add_remote_ovs_switch( self, name, user, server, **params ): """ Adds a new remote OVS switch to the current topology and returns a RemoteOVSSwitchConfig object representing it. - name : a textual representation of the switch - user : the name of the user on the remote server - server: the IP address of the remote server """ if self.built: raise RuntimeError( 'build() method was already called; cannot add any more switches' ) name = as_str( name ) storage = self.switches check_duplicate( storage, name ) s = self._new_remote_node( RemoteOVSSwitchConfig, name, user, server, \ protocols=self.of_version, \ **params ) storage[ name ] = s info( newline( '=== Added remote OVS switch', s ) ) return s def add_pica8_switch( self, name, user, server, **params ): """ Adds a new pica8 switch (remote) to the current topology and returns a Pica8SwitchConfig object representing it. - name : a textual representation of the switch - user : the name of the user on the remote server - server: the IP address of the remote server """ if self.built: raise RuntimeError( 'build() method was already called; cannot add any more switches' ) name = as_str( name ) storage = self.switches check_duplicate( storage, name ) s = self._new_remote_node( Pica8SwitchConfig, name, user, server, \ protocols=self.of_version, \ **params ) storage[ name ] = s info( newline( '=== Added Pica8 switch', s ) ) return s def add_null_switch( self, name, **params ): """ Adds a dummy non-existent switch to the current topology and returns a NullNodeConfig object representing it. - name: a textual representation of the switch """ if self.built: raise RuntimeError( 'build() method was already called; cannot add any more switches' ) name = as_str( name ) storage = self.switches check_duplicate( storage, name ) s = self._new_node( NullNodeConfig, name, **params ) storage[ name ] = s info( newline( '=== Added null switch', s ) ) return s def _new_node( self, node_cls, name, **params ): return node_cls( name, **params ) def _new_remote_node( self, node_cls, name, user, server, **params ): return node_cls( name, user, server, **params ) def add_link( self, port1, port2, **params ): """ Adds a new link to the current topology and returns a LinkConfig object representing it. If any of the ports is a null port then this method returns a NullLinkConfig object. - port1: a PortConfig object representing the port of the 1st node - port2: a PortConfig object representing the port of the 2nd node """ if self.built: raise RuntimeError( 'build() method was already called; cannot add any more links' ) if isinstance( port1, NullPortConfig ) or isinstance( port2, NullPortConfig ): return NullLinkConfig( port1, port2, **params ) if port1.is_virtual() and port2.is_virtual(): link_cls = VirLinkConfig elif not ( port1.is_virtual() or port2.is_virtual() ):
method we need # to call to hide various head parts fix = None # load the appropriate file if (headStyle == "dls"): # dog, long head, short muzzle filePrefix = HeadDict["dls"] headHeight = 0.75 elif (headStyle == "dss"): # dog, short head, short muzzle filePrefix = HeadDict["dss"] headHeight = 0.5 elif (headStyle == "dsl"): # dog, short head, long muzzle filePrefix = HeadDict["dsl"] headHeight = 0.5 elif (headStyle == "dll"): # dog, long head, long muzzle filePrefix = HeadDict["dll"] headHeight = 0.75 elif (headStyle == "cls"): # cat, long head, short muzzle filePrefix = HeadDict["c"] fix = self.__fixHeadLongShort headHeight = 0.75 elif (headStyle == "css"): # cat, short head, short muzzle filePrefix = HeadDict["c"] fix = self.__fixHeadShortShort headHeight = 0.5 elif (headStyle == "csl"): # cat, short head, long muzzle filePrefix = HeadDict["c"] fix = self.__fixHeadShortLong headHeight = 0.5 elif (headStyle == "cll"): # cat, long head, long muzzle filePrefix = HeadDict["c"] fix = self.__fixHeadLongLong headHeight = 0.75 elif (headStyle == "hls"): # horse, long head, short muzzle filePrefix = HeadDict["h"] fix = self.__fixHeadLongShort headHeight = 0.75 elif (headStyle == "hss"): # horse, short head, short muzzle filePrefix = HeadDict["h"] fix = self.__fixHeadShortShort headHeight = 0.5 elif (headStyle == "hsl"): # horse, short head, long muzzle filePrefix = HeadDict["h"] fix = self.__fixHeadShortLong headHeight = 0.5 elif (headStyle == "hll"): # horse, long head, long muzzle filePrefix = HeadDict["h"] fix = self.__fixHeadLongLong headHeight = 0.75 elif (headStyle == "mls"): # mouse, long head, short muzzle filePrefix = HeadDict["m"] fix = self.__fixHeadLongShort headHeight = 0.75 elif (headStyle == "mss"): # mouse, short head, short muzzle filePrefix = HeadDict["m"] fix = self.__fixHeadShortShort headHeight = 0.5 elif (headStyle == "rls"): # rabbit, long head/muzzle, short ears filePrefix = HeadDict["r"] fix = self.__fixHeadLongShort headHeight = 0.75 elif (headStyle == "rss"): # rabbit, short head/muzzle, short ears filePrefix = HeadDict["r"] fix = self.__fixHeadShortShort headHeight = 0.5 elif (headStyle == "rsl"): # rabbit, short head/muzzle, long ears filePrefix = HeadDict["r"] fix = self.__fixHeadShortLong headHeight = 0.5 elif (headStyle == "rll"): # rabbit, long head/muzzle, long ears filePrefix = HeadDict["r"] fix = self.__fixHeadLongLong headHeight = 0.75 elif (headStyle == "fls"): # duck, long head, short bill filePrefix = HeadDict["f"] fix = self.__fixHeadLongShort headHeight = 0.75 elif (headStyle == "fss"): # duck, short head, short bill filePrefix = HeadDict["f"] fix = self.__fixHeadShortShort headHeight = 0.5 elif (headStyle == "fsl"): # duck, short head, long bill filePrefix = HeadDict["f"] fix = self.__fixHeadShortLong headHeight = 0.5 elif (headStyle == "fll"): # duck, long head, long bill filePrefix = HeadDict["f"] fix = self.__fixHeadLongLong headHeight = 0.75 elif (headStyle == "pls"): # monkey, long head, short muzzle filePrefix = HeadDict["p"] fix = self.__fixHeadLongShort headHeight = 0.75 elif (headStyle == "pss"): # monkey, short head, short muzzle filePrefix = HeadDict["p"] fix = self.__fixHeadShortShort headHeight = 0.5 elif (headStyle == "psl"): # monkey, short head, long muzzle filePrefix = HeadDict["p"] fix = self.__fixHeadShortLong headHeight = 0.5 elif (headStyle == "pll"): # monkey, long head, long muzzle filePrefix = HeadDict["p"] fix = self.__fixHeadLongLong headHeight = 0.75 elif (headStyle == "bls"): # bear, long head, short muzzle filePrefix = HeadDict["b"] fix = self.__fixHeadLongShort headHeight = 0.75 elif (headStyle == "bss"): # bear, short head, short muzzle filePrefix = HeadDict["b"] fix = self.__fixHeadShortShort headHeight = 0.5 elif (headStyle == "bsl"): # bear, short head, long muzzle filePrefix = HeadDict["b"] fix = self.__fixHeadShortLong headHeight = 0.5 elif (headStyle == "bll"): # bear, long head, long muzzle filePrefix = HeadDict["b"] fix = self.__fixHeadLongLong headHeight = 0.75 elif (headStyle == "sls"): # pig, long head, short muzzle filePrefix = HeadDict["s"] fix = self.__fixHeadLongShort headHeight = 0.75 elif (headStyle == "sss"): # pig, short head, short muzzle filePrefix = HeadDict["s"] fix = self.__fixHeadShortShort headHeight = 0.5 elif (headStyle == "ssl"): # pig, short head, long muzzle filePrefix = HeadDict["s"] fix = self.__fixHeadShortLong headHeight = 0.5 elif (headStyle == "sll"): # pig, long head, long muzzle filePrefix = HeadDict["s"] fix = self.__fixHeadLongLong headHeight = 0.75 else: ToonHead.notify.error("unknown head style: %s" % headStyle) # load the model and massage the geometry if len(lods) == 1: self.loadModel("phase_3" + filePrefix + lods[0], "head", "lodRoot", copy) if not forGui: pLoaded = self.loadPumpkin(headStyle[1], None, copy) self.loadSnowMan(headStyle[1], None, copy) if not copy: self.showAllParts('head') if fix != None: fix(style, None, copy) if not forGui: if pLoaded: self.__fixPumpkin(style, None, copy) else: self.__lods = lods self.__style = style self.__headStyle = headStyle self.__copy = copy else: for lod in lods: self.loadModel("phase_3" + filePrefix + lod, "head", lod, copy) if not forGui: pLoaded = self.loadPumpkin(headStyle[1], lod, copy) self.loadSnowMan(headStyle[1], lod, copy) if not copy: self.showAllParts('head', lod) if fix != None: fix(style, lod, copy) if not forGui: if pLoaded: self.__fixPumpkin(style, lod, copy) else: self.__lods = lods self.__style = style self.__headStyle = headStyle self.__copy = copy # use the appropriate eye texture self.__fixEyes(style, forGui) self.setupEyelashes(style) self.eyelids.request("closed") self.eyelids.request("open") self.setupMuzzles(style) return headHeight def loadPumpkin(self,headStyle, lod, copy): if (hasattr(base, 'launcher') and ((not base.launcher) or (base.launcher and base.launcher.getPhaseComplete(4)))): if not hasattr(self,'pumpkins'): self.pumpkins = NodePathCollection() ppath = 'phase_4/models/estate/pumpkin_' if headStyle == 'l': if copy: pmodel = loader.loadModel(ppath + 'tall') else: pmodel = loader.loadModel(ppath + 'tall') ptype = 'tall' else: if copy: pmodel = loader.loadModel(ppath + 'short') else: pmodel = loader.loadModel(ppath + 'short') ptype = 'short' if pmodel: p = pmodel.find('**/pumpkin_'+ptype+'*') p.setScale(0.5) p.setZ(-0.5) p.setH(180) if lod: p.reparentTo(self.find('**/' + lod + '/**/__Actor_head')) else: p.reparentTo(self.find('**/__Actor_head')) self.pumpkins.addPath(p) pmodel.remove() return True else: del self.pumpkins return False else: ToonHead.notify.debug("phase_4 not complete yet. Postponing pumpkin head load.") def loadSnowMan(self, headStyle, lod, copy): if hasattr(base, 'launcher') and ((not base.launcher) or (base.launcher and base.launcher.getPhaseComplete(4))): if not hasattr(self, 'snowMen'): self.snowMen = NodePathCollection() snowManPath = 'phase_4/models/props/tt_m_int_snowmanHead_' if headStyle == 'l': snowManPath = snowManPath+'tall' else: snowManPath = snowManPath + 'short' model = loader.loadModel(snowManPath) if model: model.setScale(0.4) model.setZ(-0.5) model.setH(180) if lod: model.reparentTo(self.getPart('head',lod)) else: model.reparentTo(self.find('**/__Actor_head')) self.snowMen.addPath(model) model.stash() return True else: del self.snowMen return False else: ToonHead.notify.debug("phase_4 not loaded yet.") def __fixPumpkin(self, style, lodName = None, copy = 1): if (lodName == None): searchRoot = self else: searchRoot = self.find("**/" + str(lodName)) pumpkin = searchRoot.find( "**/__Actor_head/pumpkin*" ) pumpkin.stash() def enablePumpkins(self, enable): # This is for the case that the head was generated before the pumpkin model was available, due to phase loading. # It uses a few temporary private variables created when the initial pumpkin load attempt failed. # If successful, it should clean those variables up. if not hasattr(self,'pumpkins'): if len(self.__lods) == 1: pLoaded = self.loadPumpkin(self.__headStyle[1], None, self.__copy) if pLoaded: self.__fixPumpkin(self.__style, None, self.__copy) else: for lod in self.__lods: pLoaded = self.loadPumpkin(self.__headStyle[1], lod, self.__copy) if pLoaded: self.__fixPumpkin(self.__style, lod, self.__copy) if hasattr(self,'pumpkins'): for x in ['__lods','__style','__headStyle','__copy']: if hasattr(self,'_ToonHead'+x): delattr(self,'_ToonHead'+x) if hasattr(self,'pumpkins'): if enable: if self.__eyelashOpen: self.__eyelashOpen.stash() if self.__eyelashClosed: self.__eyelashClosed.stash() self.pumpkins.unstash() else: if self.__eyelashOpen: self.__eyelashOpen.unstash() if self.__eyelashClosed: self.__eyelashClosed.unstash() self.pumpkins.stash() def enableSnowMen(self, enable): if not hasattr(self, 'snowMen'): if len(self.__lods) == 1: self.loadSnowMan(self.__headStyle[1], None, self.__copy) else: for lod in self.__lds: self.loadSnowMan(self.__headStyle[1], lod, self.__copy) if hasattr(self, 'snowMen'): if enable: if self.__eyelashOpen: self.__eyelashOpen.stash() if self.__eyelashClosed: self.__eyelashClosed.stash() self.snowMen.unstash() else: if self.__eyelashOpen: self.__eyelashOpen.unstash() if self.__eyelashClosed: self.__eyelashClosed.unstash() self.snowMen.stash() def generateToonColor(self, style): """generateToonColor(self, AvatarDNA style) Color the toon's parts as specified by the dna. Color any LODs by searching for ALL matches. """ # color the head - may have multiple pieces parts = self.findAllMatches("**/head*") parts.setColor(style.getHeadColor()) # color the ears, if they are not black animalType = style.getAnimal() if ((animalType == "cat") or (animalType == "rabbit") or (animalType == 'bear') or (animalType == "mouse") or (animalType == "pig")): parts = self.findAllMatches("**/ear?-*") parts.setColor(style.getHeadColor()) def __fixEyes(self, style, forGui = 0): """__fixEyes(self, AvatarDNA style) Make sure the eyes render in proper order, and don't attempt to animate the pupils via the animation. Instead, we may move them around directly.""" mode = -3 if forGui: mode = -2 if (self.hasLOD()): for lodName in self.getLODNames(): self.drawInFront("eyes*", "head-front*", mode, lodName=lodName) # NOTE: had to change all ref's to "joint-" to "joint_" as Maya # does not support "-" in node names if
from sotd_indicators.indicators import * from arcgis.gis import GIS from arcgis.geometry import Geometry, filters import configparser import time import datetime import shutil import ssl ssl._create_default_https_context = ssl._create_unverified_context class Indicator: def __init__(self): # GIS Resources self.pem = None self.key = None self.username = None self.password = None self.portal = None self.write_to_gdb = None self.temp_gdb_location = None self.temp_gdb = None self.gis_conn = None self.return_all_records = True #None self.fc_prefix = None # Publishing GIS self.pub_pem = None self.pub_key = None self.pub_username = None self.pub_password = <PASSWORD> self.pub_portal = None self.pub_gis_conn = None # Thematic GIS self.them_pem = None self.them_key = None self.them_username = None self.them_password = <PASSWORD> self.them_portal = None self.them_gis_conn = None # Temporal Acuracy self.years = None self.c_features = None self.temp_acc_url = None self.temp_acc_workspace = None self.temp_acc_features = None # Selection Drivers self.grid_url = None self.feat_url = None self.lb_days = None # Positional Accuracy self.poac_sdf = None self.poac_url = None # Completeness self.cmpl_sdf = None self.cmpl_url = None # Logical Consistency self.logc_sdf = None self.logc_url = None # Temporal Currency self.curr_sdf = None self.curr_url = None # Thematic Accuracy self.them_sdf = None self.them_url = None # Source Lineage self.srln_sdf = None self.srln_url = None # Values Derived From Set Functions self.grid_sdf = None self.grid_wkid = None self.features = None self.selected = None # Extra Values self.them_pop = None #Filter Parameters self.aoi_filter_fc = None self.aoi_filter_url = None self.aoi_username = None self.aoi_password = None self.aoi_portal = None self.aoi_key = None self.aoi_pem = None self.timestamp = self.create_datetimestamp() def create_datetimestamp(self): timestamp = '{:%Y_%b_%d_%H_%M_%S}'.format(datetime.datetime.now()) return timestamp def load_config(self, config_file): # Read Incoming Config File config = configparser.ConfigParser() config.read_file(open(config_file)) for section in config.sections(): print('Loading Section: {}'.format(section)) for k, v in dict(config.items(section)).items(): self.__setattr__(k, v) def set_gis(self): # Set GeoEnrichment GIS Object if self.them_key != None and self.them_pem != None: self.them_gis_conn = GIS( url=self.them_portal, key_file=self.them_key, cert_file=self.them_pem, verify_cert=False ) elif self.them_password != None and self.them_username != None: self.them_gis_conn = GIS( url=self.them_portal, username=self.them_username, password=self.them_password ) else: self.them_gis_conn = GIS() if self.key != None and self.pem != None: self.gis_conn = GIS( url=self.portal, key_file=self.key, cert_file=self.pem, verify_cert=False ) elif self.username != None and self.password != None: self.gis_conn = GIS( url=self.portal, username=self.username, password=self.password, ) else: self.gis_conn = GIS() # Setting Publication GIS if self.pub_key != None and self.pub_pem != None: self.pub_gis_conn = GIS( url=self.pub_portal, key_file=self.pub_key, cert_file=self.pub_pem, verify_cert=False ) elif self.pub_username != None and self.pub_password != None: self.pub_gis_conn = GIS( url=self.pub_portal, username=self.pub_username, password=self.pub_password, verify_cert=False ) else: self.pub_gis_conn = GIS() def set_grid_sdf(self, use_sp_query=False): if self.aoi_filter_fc: import arcpy grid_desc = arcpy.Describe(self.aoi_filter_fc) grid_sr = grid_desc.spatialReference grid_extent = grid_desc.extent sp_filter = filters.intersects( grid_extent, grid_sr ) self.geometry_filter = sp_filter elif self.aoi_filter_url: if self.aoi_key != None and self.aoi_pem != None: self.aoi_gis = GIS( url=self.aoi_portal, key_file=self.aoi_key, cert_file=self.aoi_pem, verify_cert=False ) elif self.aoi_username != None and self.aoi_password != None: self.aoi_gis = GIS( self.aoi_portal, self.aoi_username, self.aoi_password ) else: self.aoi_gis = GIS() fl = FeatureLayer( self.aoi_filter_url, gis=self.aoi_gis ) geometry = dict(fl.properties.extent) sp_filter = filters.intersects( geometry, geometry['spatialReference'] ) self.geometry_filter = sp_filter else: self.geometry_filter = None if not self.grid_url: raise Exception('Grid URL Not Set') else: dates = get_dates_in_range(int(self.lb_days)) query_string = form_query_string(dates) print(query_string) if use_sp_query: grid_fl = FeatureLayer(url=self.grid_url, gis=self.gis_conn) print(self.geometry_filter) print("getting grid_sdf") # Potential Bug in 1.4.1 and previous where the query needs to be executed more than once # for it to start working try: print("Running Query - First Attempt") if int(self.lb_days) <= 1000: self.grid_sdf = grid_fl.query( where=query_string, geometry_filter=self.geometry_filter, return_all_records= self.return_all_records, ).df #self.return_all_records, else: print("Getting all features") self.grid_sdf = grid_fl.query( geometry_filter=self.geometry_filter, return_all_records= self.return_all_records, ).df #self.return_all_records, except: print("Running Query - Second Attempt") if int(self.lb_days) <= 1000: self.grid_sdf = grid_fl.query( where=query_string, geometry_filter=self.geometry_filter, return_all_records=self.return_all_records, ).df else: print("Getting all features") self.grid_sdf = grid_fl.query( geometry_filter=self.geometry_filter, return_all_records= self.return_all_records, ).df #self.return_all_records, print(len(self.grid_sdf)) print("Done Querying for Records to Update.") else: print("Using Geometry Filter.") grid_fl = FeatureLayer(url=self.grid_url, gis=self.gis_conn) try: print("Running Query - First Attempt") if int(self.lb_days) <= 1000: self.grid_sdf = grid_fl.query( where=query_string, return_all_records=self.return_all_records, ).df else: print("Getting all features") self.grid_sdf = grid_fl.query( return_all_records=self.return_all_records, ).df except: print("Running Query - Second Attempt") if int(self.lb_days) <= 1000: self.grid_sdf = grid_fl.query( where=query_string, return_all_records=self.return_all_records, ).df else: print("Getting all features") self.grid_sdf = grid_fl.query( return_all_records=self.return_all_records, ).df print(len(self.grid_sdf)) print("Done Querying for Records to Update.") if len(self.grid_sdf)>0: self.temp_gdb = create_temp_gdb(self.temp_gdb_location, self.timestamp) def set_features(self): df_list = [] for idx, row in enumerate(self.grid_sdf.iterrows()):#self.grid_sdf.iterrows()): geom = Geometry(row[1].SHAPE) print(idx) sp_filter = filters.intersects(geom, self.grid_wkid) data_fl = FeatureLayer(url=self.feat_url, gis=self.gis_conn) ## Change return all records to True df_list.append( data_fl.query(geometry_filter=sp_filter, return_all_records=self.return_all_records).df ) self.features = df_list def set_selected(self, indicator): created = False out_sdf = None # Indicator Feature Layer indicator_url = self.__getattribute__(indicator + '_url') print(indicator_url) #data_fl = FeatureLayer(url=indicator_url, gis=self.gis_conn) # Enumerate Used to Leverage the Merge Method on the Data Frame. # Set the First and Merge the Remainder to the First. for idx, row in enumerate(self.grid_sdf.iterrows()): # Negative Buffer Used to Avoid Selecting More Than 1 Cell sp_filter = filters.intersects( Geometry(row[1].SHAPE).buffer(-.1), self.grid_wkid ) if not indicator_url: df_current = SpatialDataFrame( columns=field_schema.get(indicator), geometry=[Geometry(json.loads(row[1].SHAPE.JSON))] ) created = True else: # Negative Buffer to Select a Single Grid Cell sp_filter = filters.intersects( Geometry(row[1].SHAPE).buffer(-.1), self.grid_wkid ) df_current = data_fl.query(geometry_filter=sp_filter, return_all_records=self.return_all_records).df # Set The First Instance if idx == 0: # Check If Cell Found in Target Indicator Layer if df_current.empty: # Use Grid SDF Row Geom to Insert Empty Record for Target Indicator data_fl.edit_features(adds=[ { 'attributes': {}, 'geometry': json.loads(row[1].SHAPE.JSON) } ]) # Select Newly Created Cell As Input out_sdf = data_fl.query(geometry_filter=sp_filter, return_all_records=self.return_all_records).df else: # Use Matched Grid Cell out_sdf = df_current # Append Additional Data else: # Check If Cell Found in Target Indicator Layer if df_current.empty: # Use Grid SDF Row Geom to Insert Empty Record for Target Indicator data_fl.edit_features(adds=[ { 'attributes': {}, 'geometry': json.loads(row[1].SHAPE.JSON) } ]) # Select Newly Created Cell As Input out_sdf.merge(data_fl.query(geometry_filter=sp_filter, return_all_records=self.return_all_records).df) else: # Use Matched Grid Cell out_sdf = out_sdf.merge_datasets(df_current) self.selected = out_sdf.reset_index(drop=False) print("Selected: " + str(len(out_sdf))) return created def create_layer(self, df, title): print('Creating New Hosted Feature Layer: {}'.format(title)) if self.pub_gis_conn==None: new_layer = df.to_featurelayer( title, gis=self.gis_conn ) else: new_layer = df.to_featurelayer( title, gis=self.pub_gis_conn ) return new_layer.id def update_layer(self, df, url): feat_layer = FeatureLayer(url=url, gis=self.gis_conn) res = feat_layer.edit_features(updates=df.to_featureset()) if 'updateResults' not in res: raise Exception('Edit Features Returned Issues: {}'.format(res)) else: return res['updateResults'] def run_poac(self, p1, apply_edits=True): #try: self.set_selected('poac') new_flag = False#self.set_selected('poac') #print(p1) print("positional_accuracy") df = positional_accuracy( self.selected, self.features, p1 ).drop(['index'], axis=1, inplace=False) print('DF Records: {}'.format(len(df))) if self.write_to_gdb: df.to_featureclass(self.temp_gdb, self.fc_prefix + 'poac_' + self.timestamp, overwrite=True) update_insert_features( os.path.join(self.temp_gdb, self.fc_prefix + 'poac_' + self.timestamp), os.path.join(self.write_to_gdb, self.fc_prefix + 'poac '), 'poac' ) return df if new_flag: #print(df.to_featureclass) return [ df, self.create_layer( df, 'Positional Accuracy {}'.format(round(time.time())) ) ] else: if apply_edits: return [ df, self.update_layer( df, self.poac_url ) ] else: return df #except Exception as e: # print('Exception Running Positional Accuracy: {}'.format(str(e))) def run_cmpl(self, comparison_sdf, apply_edits=True): try: self.set_selected('cmpl') new_flag = False#self.set_selected('cmpl') df = completeness( self.selected, self.features, comparison_sdf ).drop(['index'], axis=1, inplace=False) if self.write_to_gdb: df.to_featureclass(self.temp_gdb, 'cmpl_' + self.timestamp, overwrite=True) update_insert_features( os.path.join(self.temp_gdb, 'cmpl_' + self.timestamp), os.path.join(self.write_to_gdb, 'cmpl'), 'cmpl' ) return df if new_flag: return [ df, self.create_layer( df, 'Completeness {}'.format(round(time.time())) ) ] else: if apply_edits: return [ df, self.update_layer( df, self.cmpl_url ) ] else: return df except Exception as e: print('Exception Running Completeness: {}'.format(str(e))) def run_curr(self, p1, date='1901-1-1', apply_edits=True): try: self.set_selected('curr') new_flag = False#self.set_selected('curr') df = temporal_currency( self.selected, self.features, p1, date ).drop(['index'], axis=1, inplace=False) if self.write_to_gdb: df.to_featureclass(self.temp_gdb, self.fc_prefix + 'curr_' + self.timestamp, overwrite=True) update_insert_features( os.path.join(self.temp_gdb, self.fc_prefix + 'curr_' + self.timestamp), os.path.join(self.write_to_gdb, self.fc_prefix + 'curr'), 'curr' ) return df if new_flag: #print(df) return [ df, self.create_layer( df, 'Temporal Currency {}'.format(round(time.time())) ) ] else: if apply_edits: return [ df, self.update_layer( df, self.curr_url ) ] else: return df except Exception as e: print('Exception Running Temporal Currency: {}'.format(str(e))) def run_them(self, p1, apply_edits=False): #try: self.set_selected('them') new_flag = False#self.set_selected('them') df = thematic_accuracy( self.selected, self.features, p1, self.them_gis_conn, self.them_pop ).drop(['index'], axis=1, inplace=False) if self.write_to_gdb: df.to_featureclass(self.temp_gdb, self.fc_prefix + 'them_' + self.timestamp, overwrite=True) update_insert_features( os.path.join(self.temp_gdb, self.fc_prefix + 'them_' + self.timestamp), os.path.join(self.write_to_gdb, self.fc_prefix + 'them'), 'them' ) return df if new_flag: return [ df, self.create_layer( df, 'Thematic Accuracy {}'.format(round(time.time())) ) ] else: if apply_edits: return [ df, self.update_layer( df, self.them_url ) ] else: return df #except Exception as e: # print('Exception Running Thematic Accuracy: {}'.format(str(e)))
= dict() container.update({ "name": f"{key} {datetime.utcnow().strftime(GC_DATE_FORMAT)}", "artifacts": artifacts }) ret_val, message, cid = self.save_container(container) self.debug_print(f"save_container (with artifacts) returns, value: {ret_val}, reason: {message}, id: {cid}") return ret_val, message, cid def _save_artifacts(self, results, run_mode, key): """Ingest all the given artifacts accordingly into the new or existing container. Parameters: :param results: list of artifacts of IoCs or alerts results :param run_mode: current run_mode for which artifacts will be saved :param key: name of the container in which data will be ingested Returns: :return: None """ # Initialize cid = None start = 0 count = None # If not results return if not results: return # Check for existing container only if it's a scheduled/interval poll and not first run if not (self._is_poll_now or self._is_first_run[run_mode]): ret_val, cid, count = self._check_for_existing_container(key) if phantom.is_fail(ret_val): self.debug_print("Failed to check for existing container") if cid and count: ret_val = self._ingest_artifacts(results[:count], key, cid=cid) if phantom.is_fail(ret_val): self.debug_print("Failed to save ingested artifacts in the existing container") return # One part is ingested start = count # Divide artifacts list into chunks which length equals to max_artifacts configured in the asset artifacts = [results[i:i + self._max_artifacts] for i in range(start, len(results), self._max_artifacts)] for artifacts_list in artifacts: ret_val = self._ingest_artifacts(artifacts_list, key) if phantom.is_fail(ret_val): self.debug_print("Failed to save ingested artifacts in the new container") return def _ingest_artifacts(self, artifacts, key, cid=None): """Ingest artifacts into the Phantom server. Parameters: :param artifacts: list of artifacts :param key: name of the container in which data will be ingested :param cid: value of container ID Returns: :return: status(phantom.APP_SUCCESS/phantom.APP_ERROR) """ self.debug_print(f"Ingesting {len(artifacts)} artifacts for {key} results " f"into the {'existing' if cid else 'new'} container") ret_val, message, cid = self._save_ingested(artifacts, key, cid=cid) if phantom.is_fail(ret_val): self.debug_print(f"Failed to save ingested artifacts, error msg: {message}") return ret_val return phantom.APP_SUCCESS def _save_results(self, results): """Parse results and ingest results into the Phantom server. Parameters: :param results: Dictionary of IoCs and alerts results Returns: :return: status(phantom.APP_SUCCESS/phantom.APP_ERROR) """ # Initialize IoCs and alerts results iocs = results.get(GC_RM_IOC_DOMAINS, []) alerts = results.get(GC_RM_ASSET_ALERTS, []) user_alerts = results.get(GC_RM_USER_ALERTS, []) alerting_detections = results.get(GC_RM_ALERTING_DETECTIONS, []) not_alerting_detections = results.get(GC_RM_NOT_ALERTING_DETECTIONS, []) # Create artifacts from the IoCs results try: self.debug_print("Try to create artifacts for the IoC domain matches") iocs = self._create_ioc_artifacts(iocs) self.debug_print(f"Total IoC artifacts created: {len(iocs)}") except Exception as e: self.debug_print(f"Error occurred while creating artifacts for IoCs. Error: {str(e)}") self.save_progress(f"Error occurred while creating artifacts for IoCs. Error: {str(e)}") # Make iocs as empty list iocs = list() # Create artifacts from the alerts results try: self.debug_print("Try to create artifacts for the alerts") alerts = self._create_alert_artifacts(alerts) self.debug_print(f"Total Alert artifacts created: {len(alerts)}") except Exception as e: self.debug_print(f"Error occurred while creating artifacts for alerts. Error: {str(e)}") self.save_progress(f"Error occurred while creating artifacts for alerts. Error: {str(e)}") # Make alerts as empty list alerts = list() # Create artifacts from the user alerts results try: self.debug_print("Try to create artifacts for the user alerts") user_alerts = self._create_user_alert_artifacts(user_alerts) self.debug_print(f"Total User Alerts artifacts created: {len(user_alerts)}") except Exception as e: self.debug_print(f"Error occurred while creating artifacts for user alerts. Error: {str(e)}") self.save_progress(f"Error occurred while creating artifacts for user alerts. Error: {str(e)}") # Make alerts as empty list user_alerts = list() # Create artifacts from the alerting detections results try: self.debug_print("Try to create artifacts for the detections") alerting_detections, not_alerting_detections = self._create_detection_artifacts(alerting_detections, not_alerting_detections) self.debug_print(f"Total Alerting detection artifacts created: {len(alerting_detections)}") self.debug_print(f"Total Not-alerting detection artifacts created: {len(not_alerting_detections)}") except Exception as e: self.debug_print(f"Error occurred while creating artifacts for detections. Error: {str(e)}") self.save_progress(f"Error occurred while creating artifacts for detections. Error: {str(e)}") # Make alerts as empty list alerts = list() # Save artifacts for IoCs try: self.debug_print("Try to ingest artifacts for the IoC domain matches") self._save_artifacts(iocs, run_mode=GC_RM_IOC_DOMAINS, key=GC_IOC_RUN_MODE_KEY) except Exception as e: self.debug_print(f"Error occurred while saving artifacts for IoCs. Error: {str(e)}") # Save artifacts for alerts try: self.debug_print("Try to ingest artifacts for the alerts") self._save_artifacts(alerts, run_mode=GC_RM_ASSET_ALERTS, key=GC_ALERT_RUN_MODE_KEY) except Exception as e: self.debug_print(f"Error occurred while saving artifacts for alerts. Error: {str(e)}") # Save artifacts for user alerts try: self.debug_print("Try to ingest artifacts for the user alerts") self._save_artifacts(user_alerts, run_mode=GC_RM_USER_ALERTS, key=GC_USER_ALERT_RUN_MODE_KEY) except Exception as e: self.debug_print(f"Error occurred while saving artifacts for user alerts. Error: {str(e)}") # Save artifacts for alerting detections try: self.debug_print("Try to ingest artifacts for the alerting detections") self._save_artifacts(alerting_detections, run_mode=GC_RM_ALERTING_DETECTIONS, key=GC_ALERTING_DETECTION_RUN_MODE_KEY) except Exception as e: self.debug_print(f"Error occurred while saving artifacts for alerting detections. Error: {str(e)}") # Save artifacts for not alerting detections try: self.debug_print("Try to ingest artifacts for the not alerting detections") self._save_artifacts(not_alerting_detections, run_mode=GC_RM_NOT_ALERTING_DETECTIONS, key=GC_NOT_ALERTING_DETECTION_RUN_MODE_KEY) except Exception as e: self.debug_print(f"Error occurred while saving artifacts for not alerting detections. Error: {str(e)}") return phantom.APP_SUCCESS def _save_state(self): """Save the last run state as per the given ingestion asset configuration parameters. Returns: :return: status(phantom.APP_SUCCESS/phantom.APP_ERROR) """ # Updating the last run hash digest for scheduled/interval or manual polling self._state["last_run_hash_digests"] = self._last_run_hash_digests # Check for manual poll or not if self._is_poll_now: return phantom.APP_SUCCESS # As end_alert_time has current time, we are saving current time as last run time for both alert and IoCs. for run_mode in self._run_mode: self._state[f"last_run_{run_mode}_time"] = self._time_dict.get(run_mode, {}).get(GC_END_TIME_KEY) return phantom.APP_SUCCESS def _perform_ingest_function(self, action_result, client, config): """Perform the ingest function using supplied asset configuration parameters. Parameters: :param action_result: object of ActionResult class :param client: object of HTTP client :param config: Dictionary of asset configuration parameters Returns: :return: status(phantom.APP_SUCCESS/phantom.APP_ERROR) """ DEFAULT_ALL_MODE_LIST = [ GC_RM_IOC_DOMAINS, GC_RM_ASSET_ALERTS, GC_RM_USER_ALERTS, GC_RM_ALERTING_DETECTIONS, GC_RM_NOT_ALERTING_DETECTIONS ] # Fetch ingestion run mode self._run_mode = GC_RM_ON_POLL_DICT.get(config.get("run_mode", "All"), DEFAULT_ALL_MODE_LIST) # Fetch run_automation flag self._run_automation = config.get("run_automation", False) self.debug_print(f"Ingestion run mode: '{self._run_mode}'") self.save_progress(f"Ingestion run mode: '{self._run_mode}'") self.debug_print(f"Run automation flag: '{self._run_automation}'") self.save_progress(f"Run automation flag: '{self._run_automation}'") # Validate ingestion asset configuration parameters self.debug_print("Validate ingestion asset configuration parameters") self.save_progress("Validate ingestion asset configuration parameters") ret_val = self._validate_on_poll_params(action_result, config) if phantom.is_fail(ret_val): self.debug_print("Asset configuration parameters validation failed") self.save_progress("Asset configuration parameters validation failed") return action_result.get_status() # Fetch results as per the given ingestion run mode self.debug_print("Fetch results as per the given ingestion run mode") self.save_progress("Fetch results as per the given ingestion run mode") ret_val, results = self._fetch_results(action_result, client) if phantom.is_fail(ret_val): self.debug_print("Failed to fetch the results as per the given ingestion run mode") self.save_progress("Failed to fetch the results as per the given ingestion run mode") return action_result.get_status() # Parse results as per the given ingestion run mode self.debug_print("Ingest results as per the given ingestion run mode") self.save_progress("Ingest results as per the given ingestion run mode") ret_val = self._save_results(results) if phantom.is_fail(ret_val): self.debug_print("Failed to ingest the results as per the given ingestion run mode") self.save_progress("Failed to ingest the results as per the given ingestion run mode") return action_result.get_status() # Save state as per the configured ingestion run mode ret_val = self._save_state() if phantom.is_fail(ret_val): self.debug_print("Failed to save the last run state as per the given ingestion run mode") return action_result.get_status() # Return success return phantom.APP_SUCCESS def _handle_on_poll(self, param): """Perform the on poll ingest functionality. Parameters: :param param: Dictionary of input parameters Returns: :return: status(phantom.APP_SUCCESS/phantom.APP_ERROR) """ self.save_progress(f"In action handler for: {self.get_action_identifier()}") # Add an action result object to self (BaseConnector) to represent the action for this param action_result = self.add_action_result(ActionResult(dict(param))) ret_val, client = self._create_client(action_result) if phantom.is_fail(ret_val): self.debug_print(GC_UNABLE_CREATE_CLIENT_ERR) self.save_progress(GC_UNABLE_CREATE_CLIENT_ERR) return ret_val # Get the asset config config = self.get_config() # Check for manual or scheduled poll self._is_poll_now = self.is_poll_now() ret_val = self._perform_ingest_function(action_result, client, config) if phantom.is_fail(ret_val): self.debug_print("Unable to perform ingest function") self.save_progress("Unable to perform ingest function") return action_result.get_status() return action_result.set_status(phantom.APP_SUCCESS) def handle_action(self, param): """Get current action identifier and call member function of its own to handle the action. Parameters: :param param: dictionary which contains information about the actions to be executed Returns: :return: status success/failure """ # Get the action that we are supposed to execute for this App Run action = self.get_action_identifier() ret_val = phantom.APP_SUCCESS self.debug_print("action_id", self.get_action_identifier()) # Dictionary mapping each action with its corresponding actions action_mapping = { "test_connectivity": self._handle_test_connectivity, "list_ioc_details": self._handle_list_ioc_details, "list_assets": self._handle_list_assets, "list_events": self._handle_list_events, "list_iocs": self._handle_list_iocs, "domain_reputation": self._handle_domain_reputation, "ip_reputation": self._handle_ip_reputation, "list_alerts": self._handle_list_alerts, "list_rules": self._handle_list_rules, "list_detections": self._handle_list_detections, "on_poll": self._handle_on_poll } if action in action_mapping.keys(): action_function = action_mapping[action] ret_val = action_function(param) return ret_val def initialize(self): """Initialize the global variables
in view_clades.') messages.error(request, 'Sorry, the server had problems ' 'updating at least on clade: %s' % e) # Updating language clade relations for changed clades: if cladeChanged: updateLanguageCladeRelations() # Adding a new clade: elif 'addClade' in request.POST: cladeCreationForm = CladeCreationForm(request.POST) try: cladeCreationForm.validate() newClade = Clade(**cladeCreationForm.data) with transaction.atomic(): newClade.save(force_insert=True) except Exception as e: logging.exception('Problem creating clade in view_clades.') messages.error(request, 'Sorry, the server had problems ' 'creating the clade: %s' % e) # Deleting an existing clade: elif 'deleteClade' in request.POST: cladeDeletionForm = CladeDeletionForm(request.POST) try: cladeDeletionForm.validate() with transaction.atomic(): # Making sure the clade exists: clade = Clade.objects.get(**cladeDeletionForm.data) # Make sure to update things referencing clade here! # Deleting the clade: Clade.objects.filter(id=clade.id).delete() # Write message about clade deletion: messages.success(request, 'Deleted clade "%s".' % clade.cladeName) except Exception as e: logging.exception('Problem deleting clade in view_clades.') messages.error(request, 'Sorry, the server had problems ' 'deleting the clade: %s' % e) return HttpResponseRedirect('/clades/') # Extra handling for graphs. See #145. if request.method == 'GET': if 'plot' in request.GET: return render_template(request, "distributionPlot.html") form = CladeTableForm() for clade in Clade.objects.all(): clade.idField = clade.id form.elements.append_entry(clade) return render_template(request, "clades.html", {'clades': form}) @csrf_protect @logExceptions def view_sndComp(request): if request.method == 'POST': if 'sndComps' in request.POST: form = SndCompTableForm(request.POST) for entry in form.elements: data = entry.data try: with transaction.atomic(): sndComp = SndComp.objects.get(id=data['idField']) if sndComp.isChanged(**data): try: problem = sndComp.setDelta(**data) if problem is None: sndComp.save() else: messages.error( request, sndComp.deltaReport(**problem)) except Exception: logging.exception('Exception while saving ' 'POST in view_sndComp.') messages.error(request, 'The server had ' 'problems saving the change ' 'to "%s".' % sndComp.lgSetName) except Exception as e: logging.exception('Exception while accessing ' 'entry in view_sndComp.', extra=data) messages.error(request, 'Sorry, the server had problems ' 'saving at least one SndComp entry: %s' % e) # Adding a new SndComp: elif 'addSndComp' in request.POST: sndCompCreationForm = SndCompCreationForm(request.POST) try: sndCompCreationForm.validate() newSndComp = SndComp(**sndCompCreationForm.data) with transaction.atomic(): newSndComp.save(force_insert=True) except Exception as e: logging.exception('Problem creating entry in view_sndComp.') messages.error(request, 'Sorry, the server had problems ' 'creating the SndComp language set: %s' % e) # Deleting an existing SndComp: elif 'deleteSndComp' in request.POST: sndCompDeletionForm = SndCompDeletionForm(request.POST) try: sndCompDeletionForm.validate() with transaction.atomic(): # Making sure the SndComp exists: sndComp = SndComp.objects.get(**sndCompDeletionForm.data) # Make sure to update things referencing SndCom here! # Deleting the SndComp: SndComp.objects.filter(id=sndComp.id).delete() # Write message about SndComp deletion: messages.success(request, 'Deleted set "%s"' % sndComp.lgSetName) except Exception as e: logging.exception('Problem deleting entry in view_sndComp.') messages.error(request, 'Sorry, the server had problems ' 'deleting the SndComp language set: %s' % e) form = SndCompTableForm() sndComps = SndComp.objects.order_by( "lv0", "lv1", "lv2", "lv3").all() for s in sndComps: s.idField = s.id c = s.getClade() if c is not None: s.cladeName = c.cladeName form.elements.append_entry(s) return render_template(request, "sndComp.html", {'sndComps': form}) @logExceptions def reorder_language_list(request, language_list): language_id = getDefaultLanguageId(request) language_list = LanguageList.objects.get(name=language_list) languages = language_list.languages.all().order_by("languagelistorder") ReorderForm = make_reorder_languagelist_form(languages) if request.method == "POST": form = ReorderForm(request.POST, initial={"language": language_id}) if form.is_valid(): language_id = int(form.cleaned_data["language"]) setDefaultLanguageId(request, language_id) language = Language.objects.get(id=language_id) if form.data["submit"] == "Finish": language_list.sequentialize() return HttpResponseRedirect( reverse("view-language-list", args=[language_list.name])) else: if form.data["submit"] == "Move up": move_language(language, language_list, -1) elif form.data["submit"] == "Move down": move_language(language, language_list, 1) else: assert False, "This shouldn't be able to happen" return HttpResponseRedirect( reverse("reorder-language-list", args=[language_list.name])) else: # pressed Finish without submitting changes return HttpResponseRedirect( reverse("view-language-list", args=[language_list.name])) else: # first visit form = ReorderForm(initial={"language": language_id}) return render_template( request, "reorder_language_list.html", {"language_list": language_list, "form": form}) @logExceptions def reorder_meaning_list(request, meaning_list): meaning_id = getDefaultLanguageId(request) meaning_list = MeaningList.objects.get(name=meaning_list) meanings = meaning_list.meanings.all().order_by("meaninglistorder") ReorderForm = make_reorder_meaninglist_form(meanings) if request.method == "POST": form = ReorderForm(request.POST, initial={"meaning": meaning_id}) if form.is_valid(): meaning_id = int(form.cleaned_data["meaning"]) setDefaultMeaningId(request, meaning_id) meaning = Meaning.objects.get(id=meaning_id) if form.data["submit"] == "Finish": meaning_list.sequentialize() return HttpResponseRedirect( reverse("view-wordlist", args=[meaning_list.name])) else: if form.data["submit"] == "Move up": move_meaning(meaning, meaning_list, -1) elif form.data["submit"] == "Move down": move_meaning(meaning, meaning_list, 1) else: assert False, "This shouldn't be able to happen" return HttpResponseRedirect( reverse("reorder-meaning-list", args=[meaning_list.name])) else: # pressed Finish without submitting changes return HttpResponseRedirect( reverse("view-wordlist", args=[meaning_list.name])) else: # first visit form = ReorderForm(initial={"meaning": meaning_id}) return render_template( request, "reorder_meaning_list.html", {"meaning_list": meaning_list, "form": form}) @logExceptions def move_language(language, language_list, direction): assert direction in (-1, 1) languages = list(language_list.languages.order_by("languagelistorder")) index = languages.index(language) if index == 0 and direction == -1: language_list.remove(language) language_list.append(language) else: try: neighbour = languages[index + direction] language_list.swap(language, neighbour) except IndexError: language_list.insert(0, language) @logExceptions def move_meaning(meaning, meaning_list, direction): assert direction in (-1, 1) meanings = list(meaning_list.meanings.order_by("meaninglistorder")) index = meanings.index(meaning) if index == 0 and direction == -1: meaning_list.remove(meaning) meaning_list.append(meaning) else: try: neighbour = meanings[index + direction] meaning_list.swap(meaning, neighbour) except IndexError: meaning_list.insert(0, meaning) @csrf_protect @logExceptions def view_language_wordlist(request, language, wordlist): setDefaultLanguage(request, language) setDefaultWordlist(request, wordlist) try: wordlist = MeaningList.objects.get(name=wordlist) except MeaningList.DoesNotExist: raise Http404("MeaningList '%s' does not exist" % wordlist) # clean language name try: language = Language.objects.get(ascii_name=language) except Language.DoesNotExist: language = get_canonical_language(language, request) return HttpResponseRedirect( reverse("view-language-wordlist", args=[language.ascii_name, wordlist.name])) if request.method == 'POST': # Updating lexeme table data: if 'lex_form' in request.POST: try: form = LexemeTableLanguageWordlistForm(request.POST) form.validate() form.handle(request) except Exception as e: logging.exception('Problem updating lexemes ' 'in view_language_wordlist.') messages.error(request, 'Sorry, the server had problems ' 'updating at least one lexeme: %s' % e) elif 'editCognateClass' in request.POST: try: form = LexemeTableEditCognateClassesForm(request.POST) form.validate() form.handle(request) except Exception: logging.exception('Problem handling editCognateClass.') elif 'addMissingLexemes' in request.POST: try: form = AddMissingLexemsForLanguageForm(request.POST) form.validate() form.handle(request) except Exception as e: logging.exception( 'Problem with AddMissingLexemsForLanguageForm ' 'in view_language_wordlist') messages.error(request, 'Sorry, the server had problems ' 'adding missing lexemes: %s' % e) elif 'removeEmptyLexemes' in request.POST: try: form = RemoveEmptyLexemsForLanguageForm(request.POST) form.validate() form.handle(request) except Exception as e: logging.exception( 'Problem with RemoveEmptyLexemsForLanguageForm ' 'in view_language_wordlist') messages.error(request, 'Sorry, the server had problems ' 'removing empty lexemes: %s' % e) return HttpResponseRedirect( reverse("view-language-wordlist", args=[language.ascii_name, wordlist.name])) # collect data lexemes = Lexeme.objects.filter( language=language, meaning__in=wordlist.meanings.all() ).select_related( "meaning", "language").order_by( "meaning__gloss").prefetch_related( "cognatejudgement_set", "cognatejudgement_set__cognatejudgementcitation_set", "cognate_class", "lexemecitation_set") # Used for #219: cIdCognateClassMap = {} # :: CognateClass.id -> CognateClass notTargetCountPerMeaning = {} for lex in lexemes: if lex.meaning in notTargetCountPerMeaning: if lex.not_swadesh_term: notTargetCountPerMeaning[lex.meaning] += 1 else: if lex.not_swadesh_term: notTargetCountPerMeaning[lex.meaning] = 1 else: notTargetCountPerMeaning[lex.meaning] = 0 lexemes_editabletable_form = LexemeTableLanguageWordlistForm() for lex in lexemes: lex.notTargetCountPerMeaning = notTargetCountPerMeaning[lex.meaning] lexemes_editabletable_form.lexemes.append_entry(lex) ccs = lex.cognate_class.all() for cc in ccs: cIdCognateClassMap[cc.id] = cc otherMeaningLists = MeaningList.objects.exclude(id=wordlist.id).all() languageList = LanguageList.objects.prefetch_related('languages').get( name=getDefaultLanguagelist(request)) typeahead = json.dumps({ l.utf8_name: reverse( "view-language-wordlist", args=[l.ascii_name, wordlist.name]) for l in languageList.languages.all()}) prev_language, next_language = \ get_prev_and_next_languages(request, language, language_list=languageList) cognateClasses = json.dumps([{'id': c.id, 'alias': c.alias, 'placeholder': c.combinedRootPlaceholder} for c in cIdCognateClassMap.values()]) return render_template(request, "language_wordlist.html", {"language": language, "lexemes": lexemes, "prev_language": prev_language, "next_language": next_language, "wordlist": wordlist, "otherMeaningLists": otherMeaningLists, "lex_ed_form": lexemes_editabletable_form, "cognateClasses": cognateClasses, "notTargetCountPerMeaning": notTargetCountPerMeaning, "typeahead": typeahead}) @login_required @logExceptions def view_language_check(request, language=None, wordlist=None): ''' Provides an html snipped that contains some sanity checks for a given language against a given wordlist. If language or wordlist are omitted they are inferred vie defaultModels. This function is a result of #159. @param language :: str | None @param wordlist :: str | None ''' # Infer defaultModels where neccessary: if language is None: language = getDefaultLanguage(request) if wordlist is None: wordlist = getDefaultWordlist(request) # Fetch data to work with: language = Language.objects.get(ascii_name=language) wordlist = MeaningList.objects.get(name=wordlist) meanings = wordlist.meanings.all() # Calculate meaningCounts: meaningCountDict = {m.id: 0 for m in meanings} mIds = Lexeme.objects.filter( language=language, meaning__in=meanings, not_swadesh_term=0).values_list( "meaning_id", flat=True) for mId in mIds: meaningCountDict[mId] += 1 meaningCounts = [{'count': meaningCountDict[m.id], 'meaning': m.gloss} for m in meanings if meaningCountDict[m.id] != 1] meaningCounts.sort(key=lambda x: x['count']) # Render report: return render_template(request, "language_check.html", {"meaningCounts": meaningCounts}) @login_required @logExceptions def add_language_list(request): """Start a new language list by cloning an old one""" if request.method == "POST": form = AddLanguageListForm(request.POST) if "cancel" in form.data: # has to be tested before data is cleaned return HttpResponseRedirect(reverse("view-all-languages")) if form.is_valid(): form.save() new_list = LanguageList.objects.get(name=form.cleaned_data["name"]) other_list = LanguageList.objects.get( name=form.cleaned_data["language_list"]) otherLangs = other_list.languages.all().order_by( "languagelistorder") for language in otherLangs: new_list.append(language) # edit_language_list(request, # language_list=form.cleaned_data["name"]) return HttpResponseRedirect(reverse( "edit-language-list", args=[form.cleaned_data["name"]])) else: form = AddLanguageListForm() return render_template(request, "add_language_list.html", {"form": form}) @login_required @logExceptions def edit_language_list(request, language_list=None): language_list = get_canonical_language_list( language_list, request) # a language list object language_list_all = LanguageList.objects.get(name=LanguageList.ALL) included_languages = language_list.languages.all().order_by( "languagelistorder") excluded_languages = language_list_all.languages.exclude( id__in=language_list.languages.values_list( "id", flat=True)).order_by("languagelistorder") if request.method == "POST": name_form = EditLanguageListForm(request.POST, instance=language_list) if "cancel" in name_form.data: # has to be tested before data is cleaned return HttpResponseRedirect( reverse('view-language-list', args=[language_list.name])) list_form = EditLanguageListMembersForm(request.POST) list_form.fields["included_languages"].queryset = included_languages list_form.fields["excluded_languages"].queryset = excluded_languages if name_form.is_valid() and list_form.is_valid(): changed_members = False exclude = list_form.cleaned_data["excluded_languages"] include =
"""Abstract classes.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import copy import yaml import random import subprocess import numpy as np import tensorflow as tf from tensorflow.contrib.tensorboard.plugins import projector from tensorflow.python.client import device_lib from utils import io_utils from chatbot.components import * from chatbot.globals import DEFAULT_FULL_CONFIG, OPTIMIZERS def gpu_found(): """Returns True if tensorflow finds at least 1 GPU.""" devices = device_lib.list_local_devices() return len([x.name for x in devices if x.device_type == 'GPU']) > 0 class Model(object): """Superclass of all subsequent model classes. """ def __init__(self, logger, dataset, params): """ Args: logger: returned by getLogger & called by subclasses. Passed here so we know what object to use for info/warn/error. dataset: object that inherits from data.Dataset. params: (dict) user-specified params that override those in DEFAULT_FULL_CONFIG above. """ self.log = logger self.__dict__['__params'] = Model.fill_params(dataset, params) # Make particularly useful ckpt directories for website configurations. if 'website_config' in self.ckpt_dir: self.ckpt_dir = Model._build_hparam_path( ckpt_dir=self.ckpt_dir, num_layers=self.num_layers, max_seq_len=self.max_seq_len) self.log.info("New ckpt dir:", self.ckpt_dir) # Configure gpu options if we are using one. if gpu_found(): self.log.info("GPU Found. Setting allow_growth to True.") gpu_config = tf.ConfigProto() gpu_config.gpu_options.allow_growth = True self.sess = tf.Session(config=gpu_config) else: self.log.warning("GPU not found. Not recommended for training.") self.sess = tf.Session() with self.graph.name_scope(tf.GraphKeys.SUMMARIES): self.global_step = tf.Variable(initial_value=0, trainable=False) self.learning_rate = tf.constant(self.learning_rate) # Create ckpt_dir if user hasn't already (if exists, has no effect). subprocess.call(['mkdir', '-p', self.ckpt_dir]) self.projector_config = projector.ProjectorConfig() # Good practice to set as None in constructor. self.loss = None self.file_writer = None self.merged = None self.train_op = None self.saver = None def compile(self): """ Configure training process and initialize model. Inspired by Keras. Either restore model parameters or create fresh ones. - Checks if we can both (1) find a checkpoint state, and (2) a valid V1/V2 checkpoint path. - If we can't, then just re-initialize model with fresh params. """ self.log.info("Checking for checkpoints . . .") checkpoint_state = tf.train.get_checkpoint_state(self.ckpt_dir) if not self.reset_model and checkpoint_state \ and tf.train.checkpoint_exists(checkpoint_state.model_checkpoint_path): print("Reading model parameters from", checkpoint_state.model_checkpoint_path) self.file_writer = tf.summary.FileWriter(self.ckpt_dir) self.saver = tf.train.Saver(tf.global_variables()) self.saver.restore(self.sess, checkpoint_state.model_checkpoint_path) else: print("Created model with fresh parameters:\n\t", self.ckpt_dir) # Recursively delete all files in output but keep directories. subprocess.call([ 'find', self.ckpt_dir, '-type', 'f', '-exec', 'rm', '{}', ';' ]) self.file_writer = tf.summary.FileWriter(self.ckpt_dir) # Add operation for calling all variable initializers. init_op = tf.global_variables_initializer() # Construct saver (adds save/restore ops to all). self.saver = tf.train.Saver(tf.global_variables(), max_to_keep=3) # Add the fully-constructed graph to the event file. self.file_writer.add_graph(self.sess.graph) # Initialize all model variables. self.sess.run(init_op) # Store model config in ckpt dir for easy loading later. with open(os.path.join(self.ckpt_dir, 'config.yml'), 'w') as f: yaml.dump(getattr(self, "params"), f, default_flow_style=False) def save(self, summaries=None): """ Args: summaries: merged summary instance returned by session.run. """ if self.saver is None: raise ValueError("Tried saving model before defining a saver.") ckpt_fname = os.path.join(self.ckpt_dir, "{}.ckpt".format(self.data_name)) # Saves the state of all global variables in a ckpt file. self.saver.save(self.sess, ckpt_fname, global_step=self.global_step) if summaries is not None: self.file_writer.add_summary(summaries, self.global_step.eval(self.sess)) else: self.log.info("Save called without summaries.") def close(self, save_current=True): """Call then when training session is terminated. - Saves the current model/checkpoint state. - Freezes the model into a protobuf file in self.ckpt_dir. - Closes context managers for file_writing and session. """ # First save the checkpoint as usual. if save_current: self.save() # Freeze me, for I am infinite. self.freeze() # Be a responsible bot and close my file writer. self.file_writer.close() # Formally exit the session, farewell to all. self.sess.close() @property def graph(self): return self.sess.graph @staticmethod def fill_params(dataset, params): """For now, essentially just returns (already parsed) params, but placed here in case I want to customize later (likely). """ # Replace (string) specification of dataset with the actual instance. params['dataset'] = dataset params['dataset_params']['data_name'] = dataset.name if params['model_params']['ckpt_dir'] == 'out': params['model_params']['ckpt_dir'] += '/'+dataset.name # Define alias in case older models still use it. params['model_params']['is_chatting'] = params['model_params']['decode'] return params def freeze(self): """Useful for e.g. deploying model on website. Args: directory containing model ckpt files we'd like to freeze. """ if not tf.get_collection('freezer'): self.log.warning('No freezer found. Not saving a frozen model.') return # Note: output_node_names is only used to tell tensorflow what is can # throw away in the frozen graph (e.g. training ops). output_node_names = ",".join( [t.name.rstrip(':0') for t in tf.get_collection('freezer')]) self.log.info('Output node names: %r', output_node_names) # Save a graph with only the bare necessities for chat sessions. output_graph_def = tf.graph_util.convert_variables_to_constants( self.sess, self.graph.as_graph_def(), output_node_names.split(',')) output_fname = os.path.join(self.ckpt_dir, "frozen_model.pb") with tf.gfile.GFile(output_fname, 'wb') as f: f.write(output_graph_def.SerializeToString()) print("%d ops in the final graph." % len(output_graph_def.node)) subprocess.call(['cp', self.dataset.paths['vocab'], self.ckpt_dir]) def __getattr__(self, name): if name == 'params': camel_case = self.data_name.title().replace('_', '') replace_dict = {'dataset': "data."+camel_case} return {**self.__dict__['__params'], **replace_dict} elif name in DEFAULT_FULL_CONFIG: # Requesting a top-level key. return self.__dict__['__params'][name] else: for k in DEFAULT_FULL_CONFIG.keys(): if not isinstance(self.__dict__['__params'][k], dict): continue if name in self.__dict__['__params'][k]: return self.__dict__['__params'][k][name] raise AttributeError(name) @staticmethod def _build_hparam_path(ckpt_dir, **kwargs): """Returns relative path build from args for descriptive checkpointing. The new path becomes ckpt_dir appended with directories named by kwargs: - If a given kwargs[key] is a string, that is set as the appended dir name. - Otherwise, it gets formatted, e.g. for key='learning_rate' it may become 'learning_rate_0_001' Returns: ckpt_dir followed by sequentially appended directories, named by kwargs. """ kwargs = copy.deepcopy(kwargs) new_ckpt_dir = ckpt_dir for key in sorted(kwargs): if not isinstance(kwargs[key], str): dir_name = key + "_" + str(kwargs[key]).replace('.', '_') else: dir_name = kwargs[key] new_ckpt_dir = os.path.join(new_ckpt_dir, dir_name) return new_ckpt_dir class BucketModel(Model): """Abstract class. Any classes that extend BucketModel just need to customize their graph structure in __init__ and implement the step(...) function. The real motivation for making this was to be able to use the true Model abstract class for all classes in this directory, bucketed or not, r1.0 or r0.12. """ def __init__(self, logger, buckets, dataset, params): self.buckets = buckets super(BucketModel, self).__init__( logger=logger, dataset=dataset, params=params) def compile(self): """ Configure training process. Name was inspired by Keras. <3 """ if self.losses is None: raise ValueError("Tried compiling model before defining losses.") print("Configuring training operations. This may take some time . . . ") # Note: variables are trainable=True by default. params = tf.trainable_variables() # train_op will store the parameter (S)GD train_op. self.apply_gradients = [] optimizer = OPTIMIZERS[self.optimizer](self.learning_rate) for b in range(len(self.buckets)): gradients = tf.gradients(self.losses[b], params) # Gradient clipping is actually extremely simple, it basically just # checks if L2Norm(gradients) > max_gradient, and if it is, # it returns (gradients / L2Norm(gradients)) * max_grad. clipped_gradients, _ = tf.clip_by_global_norm( gradients, self.max_gradient) self.apply_gradients.append(optimizer.apply_gradients( zip(clipped_gradients, params),global_step=self.global_step)) super(BucketModel, self).compile() def check_input_lengths(self, inputs, expected_lengths): """ Raises: ValueError: if length of encoder_inputs, decoder_inputs, or target_weights disagrees with bucket size for the specified bucket_id. """ for input, length in zip(inputs, expected_lengths): if len(input) != length: raise ValueError("Input length doesn't match bucket size:" " %d != %d." % (len(input), length)) def get_batch(self, data, bucket_id): """Get a random batch of data from the specified bucket, prepare for step. Args: data: tuple of len(self.buckets). data[bucket_id] == [source_ids, target_ids] bucket_id: integer, which bucket to get the batch for. Returns: The triple (encoder_inputs, decoder_inputs, target_weights) for the constructed batch that has the proper format to call step(...) later. """ encoder_size, decoder_size = self.buckets[bucket_id] encoder_inputs, decoder_inputs = [], [] # Get a random batch of encoder and decoder inputs from data, # pad them if needed, reverse encoder inputs and add GO to decoder. for _ in range(self.batch_size): encoder_input, decoder_input = random.choice(data[bucket_id]) # BasicEncoder inputs are padded and then reversed. encoder_pad = [io_utils.PAD_ID] * (encoder_size - len(encoder_input)) encoder_inputs.append(list(reversed(encoder_input + encoder_pad))) # DynamicDecoder inputs get an extra "GO" symbol, and are padded then. decoder_pad= [io_utils.PAD_ID] * (decoder_size - len(decoder_input) - 1) decoder_inputs.append([io_utils.GO_ID] + decoder_input + decoder_pad) # Define some small helper functions before we re-index & weight. def inputs_to_unit(uid, inputs): """ Return re-indexed version of inputs array. Description in params below. :param uid: index identifier for input timestep/unit/node of interest. :param inputs: single batch of data; inputs[i] is i'th sentence. :return: re-indexed version of inputs as numpy array. """ return np.array([inputs[i][uid] for i in range(self.batch_size)], dtype=np.int32) batch_encoder_inputs = [inputs_to_unit(i, encoder_inputs) for i in range(encoder_size)] batch_decoder_inputs =
= None, transcript_id: Optional[str] = None, transcript_symbol: Optional[str] = None, transcript_type: Optional[Biotype] = None, sequence_guid: Optional[UUID] = None, sequence_name: Optional[str] = None, protein_id: Optional[str] = None, product: Optional[str] = None, guid: Optional[UUID] = None, transcript_guid: Optional[UUID] = None, ) -> "TranscriptInterval": if location.has_ancestor_of_type(SequenceType.SEQUENCE_CHUNK): raise NoSuchAncestorException( "Cannot call from_location with a chunk-relative location. Use from_chunk_relative_location()." ) return TranscriptInterval( exon_starts=[x.start for x in location.blocks], exon_ends=[x.end for x in location.blocks], strand=location.strand, cds_starts=cds._genomic_starts if cds else None, cds_ends=cds._genomic_ends if cds else None, cds_frames=cds.frames if cds else None, guid=guid, transcript_guid=transcript_guid, qualifiers=qualifiers, is_primary_tx=is_primary_tx, transcript_id=transcript_id, transcript_symbol=transcript_symbol, transcript_type=Biotype[transcript_type] if transcript_type else None, sequence_name=sequence_name, sequence_guid=sequence_guid, protein_id=protein_id, product=product, parent_or_seq_chunk_parent=location.parent, ) @staticmethod def from_chunk_relative_location( location: Location, cds: Optional[CDSInterval] = None, qualifiers: Optional[Dict[Hashable, QualifierValue]] = None, is_primary_tx: Optional[bool] = None, transcript_id: Optional[str] = None, transcript_symbol: Optional[str] = None, transcript_type: Optional[Biotype] = None, sequence_guid: Optional[UUID] = None, sequence_name: Optional[str] = None, protein_id: Optional[str] = None, product: Optional[str] = None, guid: Optional[UUID] = None, transcript_guid: Optional[UUID] = None, ) -> "TranscriptInterval": """ Allows construction of a TranscriptInterval from a chunk-relative location. This is a location present on a sequence chunk, which could be a sequence produced This location should be built by something like this: .. code-block:: python from inscripta.biocantor.io.parser import seq_chunk_to_parent parent = seq_chunk_to_parent('AANAAATGGCGAGCACCTAACCCCCNCC', "NC_000913.3", 222213, 222241) loc = SingleInterval(5, 20, Strand.PLUS, parent=parent) And then, this can be lifted back to chromosomal coordinates like such: .. code-block:: python loc.lift_over_to_first_ancestor_of_type("chromosome") """ if not location.has_ancestor_of_type(SequenceType.SEQUENCE_CHUNK): raise NoSuchAncestorException("Must have a sequence chunk in the parent hierarchy.") chromosome_location = location.lift_over_to_first_ancestor_of_type("chromosome") if cds: if not cds.chunk_relative_location.has_ancestor_of_type(SequenceType.SEQUENCE_CHUNK): raise NoSuchAncestorException("Must have a sequence chunk in the parent hierarchy.") cds_chromosome_location = cds.chunk_relative_location.lift_over_to_first_ancestor_of_type("chromosome") return TranscriptInterval( exon_starts=[x.start for x in chromosome_location.blocks], exon_ends=[x.end for x in chromosome_location.blocks], strand=chromosome_location.strand, cds_starts=[x.start for x in cds_chromosome_location.blocks] if cds else None, cds_ends=[x.end for x in cds_chromosome_location.blocks] if cds else None, cds_frames=cds.frames if cds else None, guid=guid, transcript_guid=transcript_guid, qualifiers=qualifiers, is_primary_tx=is_primary_tx, transcript_id=transcript_id, transcript_symbol=transcript_symbol, transcript_type=Biotype[transcript_type] if transcript_type else None, sequence_name=sequence_name, sequence_guid=sequence_guid, protein_id=protein_id, product=product, parent_or_seq_chunk_parent=location.parent, ) def intersect( self, location: Location, new_guid: Optional[UUID] = None, new_qualifiers: Optional[dict] = None, ) -> "TranscriptInterval": """Returns a new TranscriptInterval representing the intersection of this Transcript's location with the other location. Strand of the other location is ignored; returned Transcript is on the same strand as this Transcript. If this Transcript has a CDS, it will be dropped because CDS intersections are not currently supported. """ if not new_qualifiers: new_qualifiers = self.qualifiers location_same_strand = location.reset_strand(self._location.strand) intersection = self.chunk_relative_location.intersection(location_same_strand) if intersection.is_empty: raise EmptyLocationException("Can't intersect disjoint intervals") starts = [x.start for x in intersection.blocks] ends = [x.end for x in intersection.blocks] return TranscriptInterval( starts, ends, strand=intersection.strand, guid=new_guid, qualifiers=new_qualifiers, parent_or_seq_chunk_parent=intersection.parent, ) def sequence_pos_to_transcript(self, pos: int) -> int: """Converts sequence position to relative position along this transcript.""" return self.sequence_pos_to_feature(pos) def chunk_relative_pos_to_transcript(self, pos: int) -> int: """Converts chunk-relative sequence position to relative position along this transcript.""" return self.chunk_relative_pos_to_feature(pos) def sequence_interval_to_transcript(self, chr_start: int, chr_end: int, chr_strand: Strand) -> Location: """Converts a contiguous interval on the sequence to a relative location within this transcript.""" return self.sequence_interval_to_feature(chr_start, chr_end, chr_strand) def chunk_relative_interval_to_transcript(self, chr_start: int, chr_end: int, chr_strand: Strand) -> Location: """ Converts a contiguous interval on the chunk-relative sequence to a relative location within this transcript. """ return self.chunk_relative_interval_to_feature(chr_start, chr_end, chr_strand) def transcript_pos_to_sequence(self, pos: int) -> int: """Converts a relative position along this transcript to sequence coordinate.""" return self.feature_pos_to_sequence(pos) def transcript_pos_to_chunk_relative(self, pos: int) -> int: """Converts a relative position along this transcript to chunk-relative sequence coordinate.""" return self.feature_pos_to_chunk_relative(pos) def transcript_interval_to_sequence(self, rel_start: int, rel_end: int, rel_strand: Strand) -> Location: """Converts a contiguous interval relative to this transcript to a spliced location on the sequence.""" return self.feature_interval_to_sequence(rel_start, rel_end, rel_strand) def transcript_interval_to_chunk_relative(self, rel_start: int, rel_end: int, rel_strand: Strand) -> Location: """ Converts a contiguous interval relative to this transcript to a spliced location on the chunk-relative sequence. """ return self.feature_interval_to_chunk_relative(rel_start, rel_end, rel_strand) def cds_pos_to_sequence(self, pos: int) -> int: """Converts a relative position along the CDS to sequence coordinate.""" if not self.is_coding: raise NoncodingTranscriptError("No CDS positions on non-coding transcript") return self.cds.chromosome_location.relative_to_parent_pos(pos) def cds_pos_to_chunk_relative(self, pos: int) -> int: """Converts a relative position along the CDS to chunk-relative sequence coordinate.""" if not self.is_coding: raise NoncodingTranscriptError("No CDS positions on non-coding transcript") return self.cds.chunk_relative_location.relative_to_parent_pos(pos) def cds_interval_to_sequence(self, rel_start: int, rel_end: int, rel_strand: Strand) -> Location: """Converts a contiguous interval relative to the CDS to a spliced location on the sequence.""" if not self.is_coding: raise NoncodingTranscriptError("No CDS positions on non-coding transcript") return self.cds.chromosome_location.relative_interval_to_parent_location(rel_start, rel_end, rel_strand) def cds_interval_to_chunk_relative(self, rel_start: int, rel_end: int, rel_strand: Strand) -> Location: """Converts a contiguous interval relative to the CDS to a spliced location on the chunk-relative sequence.""" if not self.is_coding: raise NoncodingTranscriptError("No CDS positions on non-coding transcript") return self.cds.chunk_relative_location.relative_interval_to_parent_location(rel_start, rel_end, rel_strand) def sequence_pos_to_cds(self, pos: int) -> int: """Converts sequence position to relative position along the CDS.""" if not self.is_coding: raise NoncodingTranscriptError("No CDS positions on non-coding transcript") return self.cds.chromosome_location.parent_to_relative_pos(pos) def chunk_relative_pos_to_cds(self, pos: int) -> int: """Converts chunk-relative sequence position to relative position along the CDS.""" if not self.is_coding: raise NoncodingTranscriptError("No CDS positions on non-coding transcript") return self.cds.chunk_relative_location.parent_to_relative_pos(pos) def sequence_interval_to_cds(self, chr_start: int, chr_end: int, chr_strand: Strand) -> Location: """Converts a contiguous interval on the sequence to a relative location within the CDS.""" if not self.is_coding: raise NoncodingTranscriptError("No CDS positions on non-coding transcript") i = SingleInterval(chr_start, chr_end, chr_strand, parent=self.cds.chromosome_location.parent) return self.cds.chromosome_location.parent_to_relative_location(i) def chunk_relative_interval_to_cds(self, chr_start: int, chr_end: int, chr_strand: Strand) -> Location: """Converts a contiguous interval on the chunk-relative sequence to a relative location within the CDS.""" if not self.is_coding: raise NoncodingTranscriptError("No CDS positions on non-coding transcript") return self.cds.chunk_relative_location.parent_to_relative_location( SingleInterval(chr_start, chr_end, chr_strand, parent=self.cds.chunk_relative_location.parent) ) def cds_pos_to_transcript(self, pos: int) -> int: """Converts a relative position along the CDS to a relative position along this transcript.""" if not self.is_coding: raise NoncodingTranscriptError("No CDS positions on non-coding transcript") chr_pos = self.cds_pos_to_sequence(pos) return self.sequence_pos_to_transcript(chr_pos) def transcript_pos_to_cds(self, pos: int) -> int: """Converts a relative position along this transcript to a relative position along the CDS.""" if not self.is_coding: raise NoncodingTranscriptError("No CDS positions on non-coding transcript") chr_pos = self.transcript_pos_to_sequence(pos) return self.sequence_pos_to_cds(chr_pos) def get_5p_interval(self) -> Location: """Return the 5' UTR as a Location, if it exists. WARNING: If this is a chunk-relative transcript, the result of this function will also be chunk-relative. """ if not self.is_coding: raise NoncodingTranscriptError("No 5' UTR on a non-coding transcript") # handle the edge case where the CDS is full length if self.cds.chunk_relative_location == self.chunk_relative_location: return EmptyLocation() cds_start_on_transcript = self.cds_pos_to_transcript(0) return self.chunk_relative_location.relative_interval_to_parent_location( 0, cds_start_on_transcript, Strand.PLUS ) def get_3p_interval(self) -> Location: """Returns the 3' UTR as a location, if it exists. WARNING: If this is a chunk-relative transcript, the result of this function will also be chunk-relative. """ if not self.is_coding: raise NoncodingTranscriptError("No 3' UTR on a non-coding transcript") # handle the edge case where the CDS is full length if self.cds.chunk_relative_location == self.chunk_relative_location: return EmptyLocation() cds_inclusive_end_on_transcript = self.cds_pos_to_transcript(len(self.cds.chunk_relative_location) - 1) return self.chunk_relative_location.relative_interval_to_parent_location( cds_inclusive_end_on_transcript + 1, len(self._location), Strand.PLUS ) @lru_cache(maxsize=1) def get_transcript_sequence(self) -> Sequence: """Returns the mRNA sequence.""" return self.get_spliced_sequence() @lru_cache(maxsize=1) def get_cds_sequence(self) -> Sequence: """Returns the in-frame CDS sequence (always multiple of 3).""" if not self.is_coding: raise NoncodingTranscriptError("No CDS sequence on non-coding transcript") return self.cds.extract_sequence() @lru_cache(maxsize=2) def get_protein_sequence( self, truncate_at_in_frame_stop: Optional[bool] = False, translation_table: Optional[TranslationTable] = TranslationTable.DEFAULT, ) -> Sequence: """Return the translation of this transcript, if possible.""" if not self.is_coding: raise NoncodingTranscriptError("No translation on non-coding transcript") return self.cds.translate( truncate_at_in_frame_stop=truncate_at_in_frame_stop, translation_table=translation_table ) def export_qualifiers( self, parent_qualifiers: Optional[Dict[Hashable, Set[str]]] = None ) -> Dict[Hashable, Set[Hashable]]: """Exports qualifiers for GFF3/GenBank export""" qualifiers = self._merge_qualifiers(parent_qualifiers) for key, val in [ [BioCantorQualifiers.TRANSCRIPT_ID.value, self.transcript_id], [BioCantorQualifiers.TRANSCRIPT_NAME.value, self.transcript_symbol], [ BioCantorQualifiers.TRANSCRIPT_TYPE.value, self.transcript_type.name if self.transcript_type else UNKNOWN_BIOTYPE, ], [BioCantorQualifiers.PROTEIN_ID.value, self.protein_id], ]: if not val: continue if key not in qualifiers: qualifiers[key] = set() qualifiers[key].add(val) return qualifiers def to_gff( self, parent: Optional[str] = None, parent_qualifiers: Optional[Dict[Hashable, Set[str]]] = None, chromosome_relative_coordinates: bool = True, raise_on_reserved_attributes: Optional[bool] = True, ) -> Iterable[GFFRow]: """Writes a GFF format list of lists for this transcript. The additional qualifiers are used when writing a hierarchical relationship back to files. GFF files are easier to work
if U.type=='oper': U=Ucorrection*U inner = U.dag()*U_target part_idx = [0, 1, 3, 4] # only computational subspace ptrace = 0 for i in part_idx: ptrace += inner[i, i] dim = 4 # 2 qubits comp subspace return np.real(((np.abs(ptrace))**2+dim*(1-L1))/(dim*(dim+1))) elif U.type=='super': U=qtp.to_super(Ucorrection)*U kraus_form = qtp.to_kraus(U) dim=4 # 2 qubits in the computational subspace part_idx = [0, 1, 3, 4] # only computational subspace psum=0 for A_k in kraus_form: ptrace = 0 inner = U_target_diffdims.dag()*A_k # otherwise dimension mismatch for i in part_idx: ptrace += inner[i, i] psum += (np.abs(ptrace))**2 return np.real((dim*(1-L1) + psum) / (dim*(dim + 1))) def leakage_from_superoperator(U): if U.type=='oper': """ Calculates leakage by summing over all in and output states in the computational subspace. L1 = 1- 1/2^{number computational qubits} sum_i sum_j abs(|<phi_i|U|phi_j>|)**2 """ sump = 0 for i in range(4): for j in range(4): bra_i = qtp.tensor(qtp.ket([i//2], dim=[3]), qtp.ket([i % 2], dim=[3])).dag() ket_j = qtp.tensor(qtp.ket([j//2], dim=[3]), qtp.ket([j % 2], dim=[3])) p = np.abs((bra_i*U*ket_j).data[0, 0])**2 sump += p sump /= 4 # divide by dimension of comp subspace L1 = 1-sump return L1 elif U.type=='super': """ Calculates leakage by summing over all in and output states in the computational subspace. L1 = 1- 1/2^{number computational qubits} sum_i sum_j Tr(rho_{x'y'}C_U(rho_{xy})) where C is U in the channel representation """ sump = 0 for i in range(4): for j in range(4): ket_i = qtp.tensor(qtp.ket([i//2], dim=[3]), qtp.ket([i % 2], dim=[3])) #notice it's a ket rho_i=qtp.operator_to_vector(qtp.ket2dm(ket_i)) ket_j = qtp.tensor(qtp.ket([j//2], dim=[3]), qtp.ket([j % 2], dim=[3])) rho_j=qtp.operator_to_vector(qtp.ket2dm(ket_j)) p = (rho_i.dag()*U*rho_j).data[0, 0] sump += p sump /= 4 # divide by dimension of comp subspace sump=np.real(sump) L1 = 1-sump return L1 def seepage_from_superoperator(U): """ Calculates seepage by summing over all in and output states outside the computational subspace. L1 = 1- 1/2^{number non-computational states} sum_i sum_j abs(|<phi_i|U|phi_j>|)**2 """ if U.type=='oper': sump = 0 for i_list in [[0,2],[1,2],[2,0],[2,1],[2,2]]: for j_list in [[0,2],[1,2],[2,0],[2,1],[2,2]]: bra_i = qtp.tensor(qtp.ket([i_list[0]], dim=[3]), qtp.ket([i_list[1]], dim=[3])).dag() ket_j = qtp.tensor(qtp.ket([j_list[0]], dim=[3]), qtp.ket([j_list[1]], dim=[3])) p = np.abs((bra_i*U*ket_j).data[0, 0])**2 # could be sped up sump += p sump /= 5 # divide by number of non-computational states L1 = 1-sump return L1 elif U.type=='super': sump = 0 for i_list in [[0,2],[1,2],[2,0],[2,1],[2,2]]: for j_list in [[0,2],[1,2],[2,0],[2,1],[2,2]]: ket_i = qtp.tensor(qtp.ket([i_list[0]], dim=[3]), qtp.ket([i_list[1]], dim=[3])) rho_i=qtp.operator_to_vector(qtp.ket2dm(ket_i)) ket_j = qtp.tensor(qtp.ket([j_list[0]], dim=[3]), qtp.ket([j_list[1]], dim=[3])) rho_j=qtp.operator_to_vector(qtp.ket2dm(ket_j)) p = (rho_i.dag()*U*rho_j).data[0, 0] sump += p sump /= 5 # divide by number of non-computational states sump=np.real(sump) L1 = 1-sump return L1 def pro_avfid_superoperator(U): """ Average process (gate) fidelity in the whole space for two qutrits """ if U.type=='oper': ptrace = np.abs((U.dag()*U_target).tr())**2 dim = 9 # dimension of the whole space return np.real((ptrace+dim)/(dim*(dim+1))) elif U.type=='super': return np.real(qtp.average_gate_fidelity(U,target=U_target_diffdims)) def pro_avfid_superoperator_phasecorrected(U,phases): """ Average process (gate) fidelity in the whole space for a qubit and qutrit Qubit Z rotation and qutrit "Z" rotations are applied, taking into account the anharmonicity as well """ Ucorrection = qtp.Qobj([[np.exp(-1j*np.deg2rad(phases[0])), 0, 0, 0, 0, 0, 0, 0, 0], [0, np.exp(-1j*np.deg2rad(phases[1])), 0, 0, 0, 0, 0, 0, 0], [0, 0, np.exp(-1j*np.deg2rad(phases[4]-phases[-1])), 0, 0, 0, 0, 0, 0], [0, 0, 0, np.exp(-1j*np.deg2rad(phases[2])), 0, 0, 0, 0, 0], [0, 0, 0, 0, np.exp(-1j*np.deg2rad(phases[3]-phases[-1])), 0, 0, 0, 0], [0, 0, 0, 0, 0, np.exp(-1j*np.deg2rad(phases[4]-phases[-1]+phases[2]-phases[0])), 0, 0, 0], [0, 0, 0, 0, 0, 0, np.exp(-1j*np.deg2rad(phases[5])), 0, 0], [0, 0, 0, 0, 0, 0, 0, np.exp(-1j*np.deg2rad(phases[5]+phases[1]-phases[0])), 0], [0, 0, 0, 0, 0, 0, 0, 0, np.exp(-1j*np.deg2rad(phases[4]-phases[-1]+phases[5]-phases[0]))]], type='oper', dims=[[3, 3], [3, 3]]) if U.type=='oper': U=Ucorrection*U ptrace = np.abs((U.dag()*U_target).tr())**2 dim = 9 # dimension of the whole space return np.real((ptrace+dim)/(dim*(dim+1))) elif U.type=='super': U=qtp.to_super(Ucorrection)*U return np.real(qtp.average_gate_fidelity(U,target=U_target_diffdims)) #tlist = np.arange(0, 240e-9, 1/2.4e9) def matrix_change_of_variables(H_0): eigs,eigvectors=H_0.eigenstates() eigvectors_ordered_according2basis = [] eigvectors_ordered_according2basis.append(eigvectors[0].full()) # 00 state eigvectors_ordered_according2basis.append(eigvectors[2].full()) # 01 state eigvectors_ordered_according2basis.append(eigvectors[5].full()) # 02 state eigvectors_ordered_according2basis.append(eigvectors[1].full()) # 10 state eigvectors_ordered_according2basis.append(eigvectors[4].full()) # 11 state eigvectors_ordered_according2basis.append(eigvectors[7].full()) # 12 state eigvectors_ordered_according2basis.append(eigvectors[3].full()) # 20 state eigvectors_ordered_according2basis.append(eigvectors[6].full()) # 21 state eigvectors_ordered_according2basis.append(eigvectors[8].full()) # 22 state S=np.hstack(eigvectors_ordered_according2basis) return S def simulate_quantities_of_interest_superoperator(H_0, tlist, c_ops, w_bus, eps_vec, sim_step, verbose: bool=True): """ Calculates the quantities of interest from the propagator U Args: H_0 (Qobj): static hamiltonian, see "coupled_transmons_hamiltonian" for the expected form of the Hamiltonian. tlist (array): times in s, describes the x component of the trajectory to simulate c-ops (list of Qobj): list of jump operators, time-independent at the momennt eps_vec(array): detuning describes the y-component of the trajectory to simulate. Returns phi_cond (float): conditional phase (deg) L1 (float): leakage L2 (float): seepage avgatefid (float): average gate fidelity in full space avgatefid_compsubspace (float): average gate fidelity only in the computational subspace """ # time is multiplied by scalefactor and frequency is divided by it tlist=tlist*scalefactor eps_vec=eps_vec/scalefactor sim_step=sim_step*scalefactor H_0=H_0/scalefactor w_bus=w_bus/scalefactor if c_ops!=[]: # c_ops is a list of either operators or lists where the first element is # an operator and the second one is a list of the (time-dependent) coefficients for c in range(len(c_ops)): if isinstance(c_ops[c],list): c_ops[c][1]=c_ops[c][1]/np.sqrt(scalefactor) else: c_ops[c]=c_ops[c]/np.sqrt(scalefactor) ''' # step of 1/sampling_rate=1/2.4e9=0.4 ns seems good by itself sim_step_new=sim_step*2 eps_interp = interp1d(tlist, eps_vec, fill_value='extrapolate') tlist_new = (np.linspace(0, np.max(tlist), 576/2)) eps_vec_new=eps_interp(tlist_new) c_ops_new=[] for c in range(len(c_ops)): if isinstance(c_ops[c],list): c_ops_interp=interp1d(tlist,c_ops[c][1], fill_value='extrapolate') c_ops_new.append([c_ops[c][0],c_ops_interp(tlist_new)]) else: c_ops_new.append(c_ops[c]) # function only exists to wrap #def eps_t(t, args=None): # return eps_interp(t) print(len(eps_vec),len(eps_vec_new)) t0 = time.time() exp_L_total_new=1 for i in range(len(tlist_new)): H=H_0+eps_vec_new[i]*H_c c_ops_temp=[] for c in range(len(c_ops_new)): if isinstance(c_ops_new[c],list): c_ops_temp.append(c_ops_new[c][0]*c_ops_new[c][1][i]) else: c_ops_temp.append(c_ops_new[c]) liouville_exp_t=(qtp.liouvillian(H,c_ops_temp)*sim_step_new).expm() exp_L_total_new=liouville_exp_t*exp_L_total_new #exp_L_oneway=(qtp.liouvillian(H_0,c_ops)*240e-3).expm() t1 = time.time() print('\n alternative propagator_new',t1-t0) ''' # We change the basis of H to the basis of eigenvectors of H_0 # The columns of S are the eigenvectors of H_0, appropriately ordered S = qtp.Qobj(matrix_change_of_variables(H_0),dims=[[3, 3], [3, 3]]) t0 = time.time() exp_L_total=1 for i in range(len(tlist)): H=hamiltonian_timedependent(H_0,eps_vec[i],w_bus) H=S*H*S.dag() if c_ops != []: c_ops_temp=[] for c in range(len(c_ops)): if isinstance(c_ops[c],list): c_ops_temp.append(c_ops[c][0]*c_ops[c][1][i]) else: c_ops_temp.append(c_ops[c]) liouville_exp_t=(qtp.liouvillian(H,c_ops_temp)*sim_step).expm() else: liouville_exp_t=(-1j*H*sim_step).expm() exp_L_total=liouville_exp_t*exp_L_total #exp_L_oneway=(qtp.liouvillian(H_0,c_ops)*240e-3).expm() t1 = time.time() print('\n alternative propagator',t1-t0) ''' # qutip propagator not used anymore because it takes too much time t0 = time.time() if c_ops==[]: nstepsmax=1000 else: nstepsmax=100000 H_t = [H_0, [H_c, eps_vec]] U_t = qtp.propagator(H_t, tlist, c_ops, parallel=True, options=qtp.Options(nsteps=nstepsmax)) # returns unitary 'oper' if c_ops=[], otherwise 'super' t1 = time.time() print('/n propagator',t1-t0) if verbose: print('simulation took {:.2f}s'.format(t1-t0)) ''' U_final = exp_L_total phases = phases_from_superoperator(U_final) phi_cond = phases[-1] L1 = leakage_from_superoperator(U_final) L2 = seepage_from_superoperator(U_final) avgatefid = pro_avfid_superoperator_phasecorrected(U_final,phases) avgatefid_compsubspace = pro_avfid_superoperator_compsubspace_phasecorrected(U_final,L1,phases) # leakage has to be taken into account, see Woods & Gambetta print('avgatefid_compsubspace',avgatefid_compsubspace) ''' U_final = exp_L_total_new phases2 = phases_from_superoperator(U_final) phi_cond2 = phases2[-1] L12 = leakage_from_superoperator(U_final) L22 = seepage_from_superoperator(U_final) avgatefid2 = pro_avfid_superoperator_phasecorrected(U_final,phases2) avgatefid_compsubspace2 = pro_avfid_superoperator_compsubspace_phasecorrected(U_final,L12,phases2) print(phi_cond-phi_cond2,phi_cond) print(L1-L12,L1) print(L2-L22,L2) print(avgatefid-avgatefid2,avgatefid) print(avgatefid_compsubspace-avgatefid_compsubspace2,avgatefid_compsubspace) ''' return {'phi_cond': phi_cond, 'L1': L1, 'L2': L2, 'avgatefid_pc': avgatefid, 'avgatefid_compsubspace_pc': avgatefid_compsubspace} def spectrum(H_0,eps_vec): eigenvalues=[[],[],[],[],[],[],[],[],[]] for Omega in eps_vec: H=H_0+Omega*H_c eigs=H.eigenenergies() for i in range(len(eigs)): eigenvalues[i].append(eigs[i]) return eigenvalues def fix_theta_f(lambda_3,theta_i): lambda_1target=1 return (theta_i+2*(lambda_1target+lambda_3))*360/(2*np.pi) class CZ_trajectory_superoperator(det.Soft_Detector): def __init__(self, H_0, fluxlutman, noise_parameters_CZ, fitted_stepresponse_ty): """ Detector for simulating a CZ trajectory. Args: fluxlutman (instr): an instrument that contains the parameters required to generate the waveform for the trajectory. noise_parameters_CZ: instrument that contains the noise parameters fitted_stepresponse_ty: list of two elements, corresponding to the time t and the step response in volts along the y axis """ super().__init__() self.value_names = ['Cost func', 'Cond phase', 'L1', 'L2', 'avgatefid_pc', 'avgatefid_compsubspace_pc'] self.value_units = ['a.u.', 'deg', '%', '%', '%', '%'] self.fluxlutman = fluxlutman self.H_0 = H_0 self.noise_parameters_CZ = noise_parameters_CZ self.fitted_stepresponse_ty=fitted_stepresponse_ty # list of 2 elements: stepresponse (=y) # as a function of time (=t) def acquire_data_point(self, **kw): '''# BENCHMARK FOR HOW THE COUPLING IMPACTS THE HAMILTONIAN PARAMETERS eigs,eigvectors = self.H_0.eigenstates() eigs=eigs/(2*np.pi) print('omegaA =',eigs[1]) print('omegaB =',eigs[2]) print(eigs[4]-eigs[1]-eigs[2]) print('etaA =',eigs[3]-2*eigs[1]) print('etaB =',eigs[5]-2*eigs[2]) print(eigvectors[4],'\n fidelity with 1 /otimes 1=',np.abs(eigvectors[4].dag().overlap(qtp.basis(9,4)))**2) print(eigvectors[5],'\n fidelity with 0 /otimes 2=',np.abs(eigvectors[5].dag().overlap(qtp.basis(9,2)))**2) ''' sim_step=1/self.fluxlutman.sampling_rate() subdivisions_of_simstep=4 sim_step_new=sim_step/subdivisions_of_simstep # waveform is generated according to sampling rate of AWG, # but we can use a different step for simulating the time evolution tlist = (np.arange(0, self.fluxlutman.cz_length(), sim_step)) tlist_new = (np.arange(0, self.fluxlutman.cz_length(), sim_step_new)) #theta_i = np.arctan(2*self.fluxlutman.cz_J2() / (self.fluxlutman.cz_freq_01_max() - self.fluxlutman.cz_freq_interaction())) #theta_f=fix_theta_f(self.fluxlutman.cz_lambda_3(),theta_i) #theta_i=theta_i*360/(2*np.pi) #self.fluxlutman.cz_theta_f(theta_f) if not self.fluxlutman.czd_double_sided(): f_pulse = wf.martinis_flux_pulse( length=self.fluxlutman.cz_length(), lambda_2=self.fluxlutman.cz_lambda_2(), lambda_3=self.fluxlutman.cz_lambda_3(), theta_f=self.fluxlutman.cz_theta_f(), f_01_max=self.fluxlutman.cz_freq_01_max(), J2=self.fluxlutman.cz_J2(), f_interaction=self.fluxlutman.cz_freq_interaction(), sampling_rate=self.fluxlutman.sampling_rate(), return_unit='f01') # return in terms of omega amp = self.fluxlutman.detuning_to_amp((self.fluxlutman.cz_freq_01_max()
<filename>file_knowledge/process/knowledge_extraction_sample.py # coding=utf-8 """ @ license: Apache Licence @ github: invoker4zoo @ author: invoker/cc @ wechart: whatshowlove @ software: PyCharm @ file: knowledge_extraction_sample.py @ time: $18-9-21 下午3:23 """ import thulac import os import sys sys.path.append('..') from tool.logger import logger from tool.trans_dic import * from tool.es_connector import esConnector from tool.neo_connector import Neo4jConnector from config.config import * import sys reload(sys) sys.setdefaultencoding('utf-8') # # GOLBAL PARAMS # THUNLP_MODEL_PATH = "/home/showlove/cc/code/THULAC-Python/models" # THUNLP_USER_DIC_PATH = "/home/showlove/PycharmProjects/data_test/nlp/user_dic.txt" # STOP_WORD_DIC_PATH = "/home/showlove/PycharmProjects/data_test/nlp/stop_word_dic.txt" # # MONGODB_SERVER = "127.0.0.1" # # MONGODB_PORT = 27017 # # MONGODB_DB = "gov_finace" # # MONGODB_COLLECTION = "center" # # neo4j config # NEO4J_URL = "bolt://localhost:7687" # NEO4J_AUTH = 'neo4j' # NEO4J_PASSWORD = '<PASSWORD>' # # es config # ES_URL = 'localhost:9200' # ES_INDEX = 'test' # ES_DOC_TYPE = 'finace' """ 文本域 es file format index finace type notice/file { 'publish_time': '', # 发布时间 'publish_location':'', # 发布地点 'publish_org': '', # 发布机构 'publish_org_2': '', # 发布的二级机构 'title': '', # 标题 'category': '', # 文档栏目划分,notice [政策发布, 财经视点, 政策解读, 财政数据] file [文本附件,数据附件, 表格附件] 'classify': '', # 文档类型划分[财政收入,民生支出,税收增长,债务管理,社会保障支出,涉农资金,...] 'content': '', # 文本内容 'identify': '', # 抽取到的文档标示 'content_identify': '', # content中提到的标识,例:财会〔2018〕24号 'content_attach': '', # content的后缀 'quote_title': [], # 标题引用文件 'quote_content':[], # 正文引用文件 'entity_loc': [], # 命名实体,地点 'entity_org': [], # 命名实体,机构 'entity_name': [], # 命名实体,姓名 'attachment_file': [], # 附件列表 'parent_file': '', # 父级文件 'key_word': [], # 关键词 'abstract': [], # 摘要 'data_key': [], # 抽取的数据项目 'data': {}/[], # 抽取的数据对象 } """ """ 节点类型 notice (notice:center/shenzhen/location){id:,title:} file (file:center/shenzhen/location){id,title:} entity (entity:org/loc/name){seg:} data (data:center/shenzhen/location){} 关系抽取 最简版 notice attach file file from notice notice quote file notice quote notice notice explain notice notice transmit notice notice include entity file include entity """ """ relation rule (source_info, #target_info) return match_rule:bool, relation_name:string, params:[{}] """ class buildGraph(object): def __init__(self): # init db self.neo4j_db = Neo4jConnector(NEO4J_URL, NEO4J_AUTH, NEO4J_PASSWORD) self.es_db = esConnector(ES_URL, ES_INDEX, ES_DOC_TYPE) # self.rule_list = [self.rule_notice_attach, self.rule_doc_entity, self.rule_doc_explain,\ # self.rule_doc_quote, self.rule_file_from] self.rule_list = [self.rule_notice_attach, self.rule_doc_explain,\ self.rule_doc_quote, self.rule_file_from, self.rule_doc_trans()] # rule part def rule_notice_attach(self, source_info): """ 提取附件关系的规则 :param source_info: :return: bool, string, list """ try: link_info = list() info = source_info.get('_source', {}) source_id = source_info.get('_id', '') if len(info.get('attachment_file', [])): for attachment_file in info.get('attachment_file'): search_name = attachment_file[: - 1 * (len(attachment_file.split('.')[-1]) + 1)] _id_list, _title_list = self.es_db.search_id_from_title(search_name) for _id, _title in zip(_id_list, _title_list): if _id != source_id and _title == search_name: link_info.append({ 'source': source_id, 'target': _id, 'sourceType': 'id', 'targetType': 'id' }) else: pass if len(link_info): return True, 'attach', link_info else: return False, '', [] else: return False, '', [] except Exception, e: logger.error('searching attach relation attach failed for %s' % str(e)) return False, '', [] def rule_file_from(self, source_info): """ 提取附件从属的规则 :param source_info: :return: bool, string, list """ try: link_info = list() info = source_info.get('_source', {}) source_id = source_info.get('_id', '') if len(info.get('parrent_file', '')): search_name = info.get('parrent_file') _id_list, _title_list = self.es_db.search_id_from_title(search_name) for _id, _title in zip(_id_list, _title_list): if _id != source_id and _title == search_name: link_info.append({ 'source': source_id, 'target': _id, 'sourceType': 'id', 'targetType': 'id' }) if len(link_info): return True, 'from', link_info else: return False, '', [] else: return False, '', [] except Exception, e: logger.error('searching attach relation from failed for %s' % str(e)) return False, '', [] def rule_doc_quote(self, source_info): """ 提取文档的引用关系,包括idendify和文件的引用 :param source_info: :return: """ try: link_info = list() info = source_info.get('_source', {}) source_id = source_info.get('_id', '') source_identify = info.get('identify', '') source_quote = info.get('quote_title', []) + info.get('quote_content', []) source_file = list() source_quote_file = list() # can use counter for item in info.get('quote_title', []): if item not in source_file: source_file.append(item) for item in info.get('quote_content', []): if item not in source_file: source_file.append(item) for item in source_quote: if item not in source_quote_file: source_quote_file.append(item) # seaching if len(source_identify): _id_list = self.es_db.search_id_list_from_identify(source_identify) else: _id_list = [] for _id in _id_list: if _id != source_id: link_info.append({ 'source': source_id, 'target': _id, 'sourceType': 'id', 'targetType': 'id' }) for quote_file in source_quote_file: _id_list = self.es_db.search_id_list_from_filename(quote_file) for _id in _id_list: if _id != source_id: link_info.append({ 'source': source_id, 'target': _id, 'sourceType': 'id', 'targetType': 'id' }) if len(link_info): return True, 'quote', link_info else: return False, '', [] except Exception, e: logger.error('searching attach relation quote failed for %s' % str(e)) return False, '', [] def rule_doc_entity(self, source_info): """ :param source_info: :return: """ try: link_info = list() info = source_info.get('_source', {}) source_id = source_info.get('_id', '') entity_name = info.get('entity_name', []) entity_org = info.get('entity_org', []) entity_loc = info.get('entity_loc', []) entity_list = entity_name + entity_org + entity_loc for seg in entity_list: link_info.append({ 'source': source_id, 'target': seg, 'sourceType': 'id', 'targetType': 'seg' }) if len(link_info): return True, 'include', link_info else: return False, '', [] except Exception, e: logger.error('searching entity relation failed for %s' % str(e)) return False, '', [] def rule_doc_explain(self, source_info): """ 解读文件的关系提取 :param source_info: :return: """ try: link_info = list() info = source_info.get('_source', {}) source_id = source_info.get('_id', '') title = info.get('title', '') if '解读' in title or '答记者问' in title: pass else: return False, '', [] if len(info.get('quote_title', [])): for quote_file in info.get('quote_title'): _id_list = self.es_db.search_id_list_from_filename(quote_file) for _id in _id_list: if _id != source_id: link_info.append({ 'source': source_id, 'target': _id, 'sourceType': 'id', 'targetType': 'id' }) if len(link_info): return True, 'explain', link_info else: return False, '', [] else: return False, '', [] except Exception, e: logger.error('searching doc explain relationship failed for %s' % str(e)) return False, '', [] def rule_doc_trans(self, source_info): """ 转发文件的关系提取 :param source_info: :return: """ try: link_info = list() info = source_info.get('_source', {}) source_id = source_info.get('_id', '') title = info.get('title', '') if '转发' in title: pass else: return False, '', [] if len(info.get('title', [])): search_title = info.get('title').replace('转发', '') _id_list, _ = self.es_db.search_id_from_title(search_title) for _id in _id_list: if _id != source_id: link_info.append({ 'source': source_id, 'target': _id, 'sourceType': 'id', 'targetType': 'id' }) # for quote_file in info.get('quote_title'): # _id_list = self.es_db.search_id_list_from_filename(quote_file) # for _id in _id_list: # if _id != source_id: # link_info.append({ # 'source': _id, # 'target': source_id, # 'sourceType': 'id', # 'targetType': 'id' # }) if len(link_info): return True, 'trans', link_info else: return False, '', [] else: return False, '', [] except Exception, e: logger.error('searching doc explain relationship failed for %s' % str(e)) return False, '', [] # rule part end # ######################################################## def _create_doc_node(self, result_info): """ 建立图中的文档节点 :result_info: es中查询结果 :return: """ try: for doc_info in result_info: doc_analysis = self._doc_info_analysis(doc_info) if doc_analysis: if not self.neo4j_db.check_node_exist(doc_analysis): self.neo4j_db.create_doc_node(doc_analysis) logger.info('create node...') else: logger.info('node is existed, skip') else: logger.warn('analysis doc info failed ,skip...') except Exception, e: logger.error('create doc node failed for %s' %str(e)) def _create_entity_node(self, result_info): """ 建立图中的 :param result_info: :return: """ try: entity_cache_list = list() for doc_info in result_info: info = doc_info['_source'] entity_name = info.get('entity_name', []) entity_org = info.get('entity_org', []) entity_loc = info.get('entity_loc', []) for seg in entity_name: if seg not in entity_cache_list: entity_info = { 'entity_type': 'name', 'seg': seg } self.neo4j_db.create_entity_node(entity_info) logger.info('create name entity node of %s' % seg) entity_cache_list.append(seg) else: continue for seg in entity_org: if seg not in entity_cache_list: entity_info = { 'entity_type': 'org', 'seg': seg } self.neo4j_db.create_entity_node(entity_info) logger.info('create organization entity node of %s' % seg) entity_cache_list.append(seg) else: continue for seg in entity_loc: if seg not in entity_cache_list: entity_info = { 'entity_type': 'loc', 'seg': seg } self.neo4j_db.create_entity_node(entity_info) logger.info('create location entity node of %s' % seg) entity_cache_list.append(seg) else: continue except Exception, e: logger.error('create entity node failed for %s' %str(e)) def _doc_info_analysis(self, doc_info): """ 分析doc_info,提取doc的属性 :param doc_info: :return:node_info node_type:节点的类型 notice,file id:es中id title:文件名 """ try: info = doc_info['_source'] # 存储的doc的类型 if len(info.get('parrent_file',[])): node_type = 'file' else: node_type = 'doc' node_id = doc_info['_id'] title = info.get('title', '') location = info.get('publish_location', '') return { 'node_name': 'notice', 'node_type': node_type, 'id': node_id, 'title': title, 'location': location } except Exception, e: logger.info('analysis doc info failed for %s' % str(e)) return None def _create_node_relationship(self, result_info, rule_list): """ 根据规则建立节点间的链接关系 :param result_info: :return: """ try: for source_info in result_info: # begin match rules logger.info('extract file with id %s' % str(source_info.get('_id',''))) for rule in rule_list: is_match, relationship_type, relationship_info = rule(source_info) if is_match: logger.info('matching rule %s'%rule.__name__) self.neo4j_db.create_relation(relationship_type, relationship_info) else: pass except Exception, e: logger.error('extract relationship between nodes failed for %s' % str(e)) def initial(self): """ 建立图数据库的主运行函数 数据读取来自于es的存储数据 :return: """ try: result = self.es_db.search_all(size=10000) result_info = result['hits']['hits'] self._create_doc_node(result_info) self._create_entity_node(result_info) # self._create_node_relationship(result_info, [self.rule_doc_explain, self.rule_doc_quote]) self._create_node_relationship(result_info, self.rule_list) except Exception, e: logger.error('build graph failed for %s' % str(e)) def build_graph_by_id(self, id): """ 建立固定文档的图连接 :param id: :return: """ try: doc_result = self.es_db.search_doc_by_id(id) doc_result_info = doc_result['hits']['hits'] self._create_doc_node(doc_result_info) self._create_entity_node(doc_result_info) # result = self.es_db.search_all(size=10000) # result_info = result['hits']['hits'] self._create_entity_node(doc_result_info) except Exception, e: logger.error('build graph by id failed for %s' % str(e)) if __name__ == '__main__': # neo4j_db = Neo4jConnector("bolt://localhost:7687", "neo4j", password="<PASSWORD>")
<gh_stars>10-100 #!/user/bin/env python '''interaction_extractor.py This class creates dataset of ligand - macromolecule and macromolecule - macromolecule interaction information. Criteria to select interactions are specified by the InteractionFilter. ''' __author__ = "<NAME>" __version__ = "0.3.0" __status__ = "experimental" from pyspark.sql import SparkSession from pyspark.sql.types import * from mmtfPyspark.utils import ColumnarStructure from pyspark.sql import Row import numpy as np from scipy.spatial import cKDTree class InteractionExtractor(object): @staticmethod def get_ligand_polymer_interactions(structures, interaction_filter, level='group'): '''Returns a dataset of ligand - macromolecule interactions The dataset contains the following columns. When level='chain' or level='group' is specified, only a subset of these columns is returned. - structureChainId - pdbId.chainName of interacting chain - queryGroupId - id of the query group (residue) from the PDB chemical component dictionary - queryChainId - chain name of the query group (residue) - queryGroupNumber - group number of the query group (residue) including insertion code (e.g. 101A) - queryAtomName - atom name of the query atom - targetGroupId - id of the query group (residue) from the PDB chemical component dictionary - targetChainId - chain name of the target group (residue) - targetGroupNumber - group number of the target group (residue) including insertion code (e.g. 101A) - targetAtomName - atom name of the target atom - distance - distance between interaction atoms - sequenceIndex - zero-based index of interacting groups (residues) mapped onto target sequence - sequence - interacting polymer sequence Parameters ---------- structures : PythonRDD a set of PDB structures interaction_filter : InteractionFilter interaction criteria level : 'chain', 'group' or 'atom' to aggregate results Returns ------- dataset dataset with interacting residue and atom information ''' # find all interactions row = structures.flatMap(LigandInteractionFingerprint(interaction_filter, level)) # TODO consider adding parameters # chem: add element, entity_type(LGO, PRO, DNA, etc.) # geom=True -> add distance, order parameters([q3,q4,q5,q6] # seq=True -> add sequence index, sequence # Convert RDD of rows to a dataset using a schema spark = SparkSession.builder.getOrCreate() schema = InteractionExtractor._get_schema(level) return spark.createDataFrame(row, schema) @staticmethod def get_polymer_interactions(structures, interaction_filter, inter=True, intra=False, level='group'): '''Returns a dataset of inter and or intra macromolecule - macromolecule interactions The dataset contains the following columns. When level='chain' or level='group' is specified, only a subset of these columns is returned. - structureChainId - pdbId.chainName of interacting chain - queryGroupId - id of the query group (residue) from the PDB chemical component dictionary - queryChainId - chain name of the query group (residue) - queryGroupNumber - group number of the query group (residue) including insertion code (e.g. 101A) - queryAtomName - atom name of the query atom - targetGroupId - id of the query group (residue) from the PDB chemical component dictionary - targetChainId - chain name of the target group (residue) - targetGroupNumber - group number of the target group (residue) including insertion code (e.g. 101A) - targetAtomName - atom name of the target atom - distance - distance between interaction atoms - sequenceIndex - zero-based index of interacting groups (residues) mapped onto target sequence - sequence - interacting polymer sequence Parameters ---------- structures : PythonRDD a set of PDB structures interaction_filter : InteractionFilter interaction criteria inter : calculate inter-chain interactions (default True) intra : calculate intra-chain interactions (default False) level : 'chain', 'group' or 'atom' to aggregate results Returns ------- dataset dataset with interacting residue and atom information ''' # find all interactions row = structures.flatMap(PolymerInteractionFingerprint(interaction_filter, inter, intra, level)) # Convert RDD of rows to a dataset using a schema spark = SparkSession.builder.getOrCreate() schema = InteractionExtractor._get_schema(level) return spark.createDataFrame(row, schema) @staticmethod def _get_schema(level): fields = [] nullable = False if level == 'chain': fields = [StructField("structureChainId", StringType(), nullable), StructField("queryGroupId", StringType(), nullable), StructField("queryChainId", StringType(), nullable), StructField("queryGroupNumber", StringType(), nullable), StructField("targetChainId", StringType(), nullable) ] elif level == 'group': fields = [StructField("structureChainId", StringType(), nullable), StructField("queryGroupId", StringType(), nullable), StructField("queryChainId", StringType(), nullable), StructField("queryGroupNumber", StringType(), nullable), StructField("targetGroupId", StringType(), nullable), StructField("targetChainId", StringType(), nullable), StructField("targetGroupNumber", StringType(), nullable), StructField("sequenceIndex", IntegerType(), nullable), StructField("sequence", StringType(), nullable) ] elif level == 'atom': fields = [StructField("structureChainId", StringType(), nullable), StructField("queryGroupId", StringType(), nullable), StructField("queryChainId", StringType(), nullable), StructField("queryGroupNumber", StringType(), nullable), StructField("queryAtomName", StringType(), nullable), StructField("targetGroupId", StringType(), nullable), StructField("targetChainId", StringType(), nullable), StructField("targetGroupNumber", StringType(), nullable), StructField("targetAtomName", StringType(), nullable), StructField("distance", FloatType(), nullable), StructField("sequenceIndex", IntegerType(), nullable), StructField("sequence", StringType(), nullable) ] schema = StructType(fields) return schema class LigandInteractionFingerprint: def __init__(self, interaction_filter, level='group'): self.filter = interaction_filter self.level = level def __call__(self, t): structure_id = t[0] structure = t[1] arrays = ColumnarStructure(structure, True) # Apply query (ligand) filter group_names = arrays.get_group_names() qg = self.filter.is_query_group_np(group_names) if np.count_nonzero(qg) == 0: return [] elements = arrays.get_elements() qe = self.filter.is_query_element_np(elements) if np.count_nonzero(qe) == 0: return [] atom_names = arrays.get_atom_names() qa = self.filter.is_query_atom_name_np(atom_names) if np.count_nonzero(qa) == 0: return [] ### filter prohibited groups?? # Create mask for polymer atoms polymer = arrays.is_polymer() # Create mask for ligand atoms lig = ~polymer & qg & qe & qa if np.count_nonzero(lig) == 0: return [] # Apply target (polymer) filter tg = self.filter.is_target_group_np(group_names) te = self.filter.is_target_element_np(elements) ta = self.filter.is_target_atom_name_np(atom_names) poly = polymer & tg & te & ta if np.count_nonzero(poly) == 0: return [] chain_names = arrays.get_chain_names() group_numbers = arrays.get_group_numbers() entity_indices = arrays.get_entity_indices() sequence_positions = arrays.get_sequence_positions() # Stack coordinates into an nx3 array # TODO add this to ColumnarStructure c = np.stack((arrays.get_x_coords(), arrays.get_y_coords(), arrays.get_z_coords()), axis=-1) # Apply ligand mask to ligand data c_ligand = c[lig] lg = group_names[lig] ln = group_numbers[lig] la = atom_names[lig] lc = chain_names[lig] # Apply polymer mask to polymer data c_polymer = c[poly] pg = group_names[poly] pn = group_numbers[poly] pa = atom_names[poly] pc = chain_names[poly] pt = entity_indices[poly] ps = sequence_positions[poly] # Calculate distances between polymer and ligand atoms poly_tree = cKDTree(c_polymer) lig_tree = cKDTree(c_ligand) distance_cutoff = self.filter.get_distance_cutoff() sparse_dm = poly_tree.sparse_distance_matrix(lig_tree, max_distance=distance_cutoff, output_type='dict') # Add interactions to rows. # There are redundant interactions when aggregating the results at the 'group' level, # since multiple atoms in a group may be involved in interactions. # Therefore we use a set of rows to store only unique interactions. rows = set([]) for ind, dis in sparse_dm.items(): i = ind[0] # ligand atom index j = ind[1] # polymer atom index if self.level == 'chain': row = Row(structure_id + "." + pc[i], # structureChainId lg[j], # queryLigandId lc[j], # queryLigandChainId ln[j], # queryLigandNumber pc[i] # targetChainId ) rows.add(row) elif self.level == 'group': row = Row(structure_id + "." + pc[i], # structureChainId lg[j], # queryLigandId lc[j], # queryLigandChainId ln[j], # queryLigandNumber pg[i], # targetGroupId pc[i], # targetChainId pn[i], # targetGroupNumber ps[i].item(), # sequenceIndex structure.entity_list[pt[i]]['sequence'] # sequence ) rows.add(row) elif self.level == 'atom': row = Row(structure_id + "." + pc[i], # structureChainId lg[j], # queryLigandId lc[j], # queryLigandChainId ln[j], # queryLigandNumber la[j], # queryAtomName pg[i], # targetGroupId pc[i], # targetChainId pn[i], # targetGroupNumber pa[i], # targetAtomName dis, # distance ps[i].item(), # sequenceIndex structure.entity_list[pt[i]]['sequence'] # sequence ) rows.add(row) return rows class LigandInteractionFingerprintNew: def __init__(self, interaction_filter, level='group'): self.filter = interaction_filter self.level = level def __call__(self, t): structure_id = t[0] structure = t[1] arrays = ColumnarStructure(structure, True) # Apply query (ligand) filter group_names = arrays.get_group_names() qg = self.filter.is_query_group_np(group_names) if np.count_nonzero(qg) == 0: return [] elements = arrays.get_elements() qe = self.filter.is_query_element_np(elements) if np.count_nonzero(qe) == 0: return [] atom_names = arrays.get_atom_names() qa = self.filter.is_query_atom_name_np(atom_names) if np.count_nonzero(qa) == 0: return [] ### filter prohibited groups?? # Create mask for polymer atoms polymer = arrays.is_polymer() # Create mask for ligand atoms lig = ~polymer & qg & qe & qa if np.count_nonzero(lig) == 0: return [] # Apply target (polymer) filter tg = self.filter.is_target_group_np(group_names) te = self.filter.is_target_element_np(elements) ta = self.filter.is_target_atom_name_np(atom_names) poly = polymer & tg & te & ta if np.count_nonzero(poly) == 0: return [] chain_names = arrays.get_chain_names() group_numbers = arrays.get_group_numbers() entity_indices = arrays.get_entity_indices() sequence_positions = arrays.get_sequence_positions() # Stack coordinates into an nx3 array # TODO add this to ColumnarStructure c = np.stack((arrays.get_x_coords(), arrays.get_y_coords(), arrays.get_z_coords()), axis=-1) # Apply ligand mask to ligand data c_ligand = c[lig] lg = group_names[lig] ln = group_numbers[lig] la = atom_names[lig] lc = chain_names[lig] # Apply polymer mask to polymer data c_polymer = c[poly] pg = group_names[poly] pn = group_numbers[poly] pa = atom_names[poly] pc = chain_names[poly] pt =
_host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously Returns: [IamActor] If the method is called asynchronously, returns the request thread. """ kwargs['async_req'] = kwargs.get( 'async_req', False ) kwargs['_return_http_data_only'] = kwargs.get( '_return_http_data_only', True ) kwargs['_preload_content'] = kwargs.get( '_preload_content', True ) kwargs['_request_timeout'] = kwargs.get( '_request_timeout', None ) kwargs['_check_input_type'] = kwargs.get( '_check_input_type', True ) kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) kwargs['_host_index'] = kwargs.get('_host_index') kwargs['organisation_id'] = \ organisation_id kwargs['policy_id'] = \ policy_id return self.call_with_http_info(**kwargs) self.iam_organisation_policy_actor_list = _Endpoint( settings={ 'response_type': ([IamActor],), 'auth': [ 'BearerAuth' ], 'endpoint_path': '/iam/organisation/{organisationId}/policy/{policyId}/actor', 'operation_id': 'iam_organisation_policy_actor_list', 'http_method': 'GET', 'servers': None, }, params_map={ 'all': [ 'organisation_id', 'policy_id', ], 'required': [ 'organisation_id', 'policy_id', ], 'nullable': [ ], 'enum': [ ], 'validation': [ ] }, root_map={ 'validations': { }, 'allowed_values': { }, 'openapi_types': { 'organisation_id': (str,), 'policy_id': (str,), }, 'attribute_map': { 'organisation_id': 'organisationId', 'policy_id': 'policyId', }, 'location_map': { 'organisation_id': 'path', 'policy_id': 'path', }, 'collection_format_map': { } }, headers_map={ 'accept': [ 'application/json' ], 'content_type': [], }, api_client=api_client, callable=__iam_organisation_policy_actor_list ) def __iam_organisation_policy_create( self, organisation_id, iam_project_policy_create, **kwargs ): """Create iam/policy # noqa: E501 Create policy # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.iam_organisation_policy_create(organisation_id, iam_project_policy_create, async_req=True) >>> result = thread.get() Args: organisation_id (str): Organisation Id iam_project_policy_create (IamProjectPolicyCreate): Keyword Args: x_idempotency_key (str): Idempotency key. [optional] x_dry_run (str): Dry run. [optional] _return_http_data_only (bool): response data without head status code and headers. Default is True. _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. _request_timeout (float/tuple): timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking should be done one the data sent to the server. Default is True. _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously Returns: Policy If the method is called asynchronously, returns the request thread. """ kwargs['async_req'] = kwargs.get( 'async_req', False ) kwargs['_return_http_data_only'] = kwargs.get( '_return_http_data_only', True ) kwargs['_preload_content'] = kwargs.get( '_preload_content', True ) kwargs['_request_timeout'] = kwargs.get( '_request_timeout', None ) kwargs['_check_input_type'] = kwargs.get( '_check_input_type', True ) kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) kwargs['_host_index'] = kwargs.get('_host_index') kwargs['organisation_id'] = \ organisation_id kwargs['iam_project_policy_create'] = \ iam_project_policy_create return self.call_with_http_info(**kwargs) self.iam_organisation_policy_create = _Endpoint( settings={ 'response_type': (Policy,), 'auth': [ 'BearerAuth' ], 'endpoint_path': '/iam/organisation/{organisationId}/policy', 'operation_id': 'iam_organisation_policy_create', 'http_method': 'POST', 'servers': None, }, params_map={ 'all': [ 'organisation_id', 'iam_project_policy_create', 'x_idempotency_key', 'x_dry_run', ], 'required': [ 'organisation_id', 'iam_project_policy_create', ], 'nullable': [ ], 'enum': [ ], 'validation': [ ] }, root_map={ 'validations': { }, 'allowed_values': { }, 'openapi_types': { 'organisation_id': (str,), 'iam_project_policy_create': (IamProjectPolicyCreate,), 'x_idempotency_key': (str,), 'x_dry_run': (str,), }, 'attribute_map': { 'organisation_id': 'organisationId', 'x_idempotency_key': 'x-idempotency-key', 'x_dry_run': 'x-dry-run', }, 'location_map': { 'organisation_id': 'path', 'iam_project_policy_create': 'body', 'x_idempotency_key': 'header', 'x_dry_run': 'header', }, 'collection_format_map': { } }, headers_map={ 'accept': [ 'application/json' ], 'content_type': [ 'application/json' ] }, api_client=api_client, callable=__iam_organisation_policy_create ) def __iam_organisation_policy_delete( self, organisation_id, policy_id, **kwargs ): """Delete iam/policy # noqa: E501 Delete policy # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.iam_organisation_policy_delete(organisation_id, policy_id, async_req=True) >>> result = thread.get() Args: organisation_id (str): Organisation Id policy_id (str): Policy Id Keyword Args: _return_http_data_only (bool): response data without head status code and headers. Default is True. _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. _request_timeout (float/tuple): timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking should be done one the data sent to the server. Default is True. _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously Returns: None If the method is called asynchronously, returns the request thread. """ kwargs['async_req'] = kwargs.get( 'async_req', False ) kwargs['_return_http_data_only'] = kwargs.get( '_return_http_data_only', True ) kwargs['_preload_content'] = kwargs.get( '_preload_content', True ) kwargs['_request_timeout'] = kwargs.get( '_request_timeout', None ) kwargs['_check_input_type'] = kwargs.get( '_check_input_type', True ) kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) kwargs['_host_index'] = kwargs.get('_host_index') kwargs['organisation_id'] = \ organisation_id kwargs['policy_id'] = \ policy_id return self.call_with_http_info(**kwargs) self.iam_organisation_policy_delete = _Endpoint( settings={ 'response_type': None, 'auth': [ 'BearerAuth' ], 'endpoint_path': '/iam/organisation/{organisationId}/policy/{policyId}', 'operation_id': 'iam_organisation_policy_delete', 'http_method': 'DELETE', 'servers': None, }, params_map={ 'all': [ 'organisation_id', 'policy_id', ], 'required': [ 'organisation_id', 'policy_id', ], 'nullable': [ ], 'enum': [ ], 'validation': [ ] }, root_map={ 'validations': { }, 'allowed_values': { }, 'openapi_types': { 'organisation_id': (str,), 'policy_id': (str,), }, 'attribute_map': { 'organisation_id': 'organisationId', 'policy_id': 'policyId', }, 'location_map': { 'organisation_id': 'path', 'policy_id': 'path', }, 'collection_format_map': { } }, headers_map={ 'accept': [ 'application/json' ], 'content_type': [], }, api_client=api_client, callable=__iam_organisation_policy_delete ) def __iam_organisation_policy_event_get( self, organisation_id, policy_id, event_id, **kwargs ): """Get iam/policy.event # noqa: E501 Get iam/policy.event # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.iam_organisation_policy_event_get(organisation_id, policy_id, event_id, async_req=True) >>> result = thread.get() Args: organisation_id (str): Organisation Id policy_id (str): Policy Id event_id (str): eventId Keyword Args: _return_http_data_only (bool): response data without head status code and headers. Default is True. _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. _request_timeout (float/tuple): timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking should be done one the data sent to the server. Default is True. _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously Returns: Event If the method is called asynchronously, returns the request thread. """ kwargs['async_req'] = kwargs.get( 'async_req', False ) kwargs['_return_http_data_only'] = kwargs.get( '_return_http_data_only', True ) kwargs['_preload_content'] = kwargs.get( '_preload_content', True ) kwargs['_request_timeout'] = kwargs.get( '_request_timeout', None ) kwargs['_check_input_type'] = kwargs.get( '_check_input_type', True ) kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) kwargs['_host_index'] = kwargs.get('_host_index') kwargs['organisation_id'] = \ organisation_id kwargs['policy_id'] = \ policy_id kwargs['event_id'] = \ event_id return self.call_with_http_info(**kwargs) self.iam_organisation_policy_event_get = _Endpoint( settings={ 'response_type': (Event,), 'auth': [ 'BearerAuth' ], 'endpoint_path': '/iam/organisation/{organisationId}/policy/{policyId}/event/{eventId}', 'operation_id': 'iam_organisation_policy_event_get', 'http_method': 'GET', 'servers': None, }, params_map={ 'all': [ 'organisation_id', 'policy_id', 'event_id', ], 'required': [ 'organisation_id', 'policy_id', 'event_id', ], 'nullable': [ ], 'enum': [ ], 'validation': [ ] }, root_map={ 'validations': { }, 'allowed_values': { }, 'openapi_types': { 'organisation_id': (str,), 'policy_id': (str,), 'event_id': (str,), }, 'attribute_map': { 'organisation_id': 'organisationId', 'policy_id': 'policyId', 'event_id': 'eventId', }, 'location_map': { 'organisation_id': 'path', 'policy_id': 'path', 'event_id': 'path', }, 'collection_format_map': { } }, headers_map={ 'accept': [ 'application/json' ], 'content_type': [], }, api_client=api_client, callable=__iam_organisation_policy_event_get ) def __iam_organisation_policy_event_list( self, organisation_id, policy_id, **kwargs ): """List iam/policy.event # noqa: E501 List iam/policy.event # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.iam_organisation_policy_event_list(organisation_id, policy_id, async_req=True) >>> result = thread.get() Args: organisation_id (str): Organisation Id policy_id (str): Policy Id Keyword Args: limit (float): $limit. [optional] if omitted the server will use the default value of 100 skip (float): $skip. [optional] _return_http_data_only (bool): response data without head status code and headers. Default is True. _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding
""" Import as: import oms.broker as ombroker """ import abc import collections import logging from typing import Any, Dict, List, Optional, Tuple, cast import pandas as pd import helpers.hasyncio as hasynci import helpers.hdbg as hdbg import helpers.hsql as hsql import market_data as mdata import oms.oms_db as oomsdb import oms.order as omorder _LOG = logging.getLogger(__name__) # ############################################################################# # Fill # ############################################################################# # TODO(gp): Consider moving this in fill.py class Fill: """ Represent an order fill. An order can be filled partially or completely. Each fill can happen at different prices. The simplest case is for an order to be completely filled (e.g., at the end of its VWAP execution window) at a single price. In this case a single `Fill` object can represent the execution. """ _fill_id = 0 def __init__( self, order: omorder.Order, timestamp: pd.Timestamp, num_shares: float, price: float, ): """ Constructor. :param num_shares: it's the number of shares that are filled, with respect to `diff_num_shares` in Order """ self._fill_id = self._get_next_fill_id() # Pointer to the order. self.order = order # TODO(gp): An Order should contain a list of pointers to its fills for # accounting purposes. # We can verify the invariant that no more than the desired quantity # was filled. # Timestamp of when it was completed. self.timestamp = timestamp # Number of shares executed. This has the same meaning as in Order, i.e., it # can be positive and negative depending on long / short. hdbg.dassert_ne(num_shares, 0) self.num_shares = num_shares # Price executed for the given shares. hdbg.dassert_lt(0, price) self.price = price def __str__(self) -> str: txt: List[str] = [] txt.append("Fill:") dict_ = self.to_dict() for k, v in dict_.items(): txt.append(f"{k}={v}") return " ".join(txt) def to_dict(self) -> Dict[str, Any]: dict_: Dict[str, Any] = collections.OrderedDict() dict_["asset_id"] = self.order.asset_id dict_["fill_id"] = self.order.order_id dict_["timestamp"] = self.timestamp dict_["num_shares"] = self.num_shares dict_["price"] = self.price return dict_ @staticmethod def _get_next_fill_id() -> int: fill_id = Fill._fill_id Fill._fill_id += 1 return fill_id # ############################################################################# # AbstractBroker # ############################################################################# class AbstractBroker(abc.ABC): """ Represent a broker to which we can place orders and receive fills back. The broker - keeps an internal book keeping of orders submitted and deadlines when they are supposed to be executed - passes the orders to the actual Order Management System (OMS) through an interface (e.g., a table of a DB, file system) - waits for an acknowledgement of orders being submitted successfully by the OMS """ _submitted_order_id: int = 0 def __init__( self, strategy_id: str, account: str, market_data: mdata.AbstractMarketData, column_remap: Optional[Dict[str, str]] = None, ) -> None: """ Constructor. :param column_remap: (optional) remap columns when accessing a `MarketData` to retrieve execution prices """ self._strategy_id = strategy_id self._account = account # hdbg.dassert_issubclass(market_data, mdata.AbstractMarketData) self.market_data = market_data self._get_wall_clock_time = market_data.get_wall_clock_time self._column_remap = column_remap # Track the orders for internal accounting, mapping wall clock when the # order was submitted to the submitted orders. self._orders: Dict[ pd.Timestamp, List[omorder.Order] ] = collections.OrderedDict() # Map a timestamp to the orders with that execution time deadline. self._deadline_timestamp_to_orders: Dict[ pd.Timestamp, List[omorder.Order] ] = collections.defaultdict(list) # Track the fills for internal accounting. self._fills: List[Fill] = [] async def submit_orders( self, orders: List[omorder.Order], *, dry_run: bool = False, ) -> str: """ Submit a list of orders to the broker. :param dry_run: do not submit orders to the OMS, but keep track of them internally """ wall_clock_timestamp = self._get_wall_clock_time() # Log the order for internal book keeping. self._log_order_submissions(orders) # Enqueue the orders based on their completion deadline time. _LOG.debug("Submitting %d orders", len(orders)) for order in orders: _LOG.debug("Submitting order %s", order.order_id) hdbg.dassert_lte( order.start_timestamp, wall_clock_timestamp, "The order '%s' can only be executed in the future", order, ) self._deadline_timestamp_to_orders[order.end_timestamp].append(order) # Submit the orders to the actual OMS. _LOG.debug("Submitting orders=\n%s", omorder.orders_to_string(orders)) file_name = await self._submit_orders( orders, wall_clock_timestamp, dry_run=dry_run ) _LOG.debug("The receipt is '%s'", file_name) # _LOG.debug("Waiting for the accepted orders") await self._wait_for_accepted_orders(file_name) return file_name @abc.abstractmethod def get_fills(self) -> List[Fill]: """ Get any new fills filled since last execution. """ ... @abc.abstractmethod async def _submit_orders( self, orders: List[omorder.Order], wall_clock_timestamp: pd.Timestamp, *, dry_run: bool, ) -> str: """ Submit orders to the actual OMS and wait for the orders to be accepted. :return: a string representing the receipt of submission / acceptance """ ... @abc.abstractmethod async def _wait_for_accepted_orders( self, file_name: str, ) -> None: """ Wait until orders are accepted. """ ... def _get_fills_helper(self) -> List[Fill]: """ Implement logic simulating orders being filled. """ # We should always get the "next" orders, for this reason one should use # a priority queue. wall_clock_timestamp = self._get_wall_clock_time() timestamps = self._deadline_timestamp_to_orders.keys() _LOG.debug("Timestamps of orders in queue: %s", timestamps) if not timestamps: return [] # In our current execution model, we should ask about the orders that are # terminating. hdbg.dassert_lte(min(timestamps), wall_clock_timestamp) orders_to_execute_timestamps = [] orders_to_execute = [] for timestamp in timestamps: if timestamp <= wall_clock_timestamp: orders_to_execute.extend( self._deadline_timestamp_to_orders[timestamp] ) orders_to_execute_timestamps.append(timestamp) _LOG.debug("Executing %d orders", len(orders_to_execute)) # Ensure that no orders are included with `end_timestamp` greater # than `wall_clock_timestamp`, e.g., assume that in general # orders take their entire allotted window to fill. for order in orders_to_execute: hdbg.dassert_lte(order.end_timestamp, wall_clock_timestamp) # "Execute" the orders. fills = [] for order in orders_to_execute: # TODO(gp): Here there should be a programmable logic that decides # how many shares are filled. fills.extend(self._fully_fill(order.end_timestamp, order)) # NOTE: `self._fills` is not in `init()` in the abstract class. self._fills.extend(fills) # Remove the orders that have been executed. _LOG.debug( "Removing orders from queue with deadline earlier than=`%s`", wall_clock_timestamp, ) for timestamp in orders_to_execute_timestamps: del self._deadline_timestamp_to_orders[timestamp] _LOG.debug("-> Returning fills:\n%s", str(fills)) return fills # TODO(gp): Consider getting the wall clock, instead of passing it. def _fully_fill( self, wall_clock_timestamp: pd.Timestamp, order: omorder.Order ) -> List[Fill]: """ Completely fill an order. :param wall_clock_timestamp: we pass this value instead of getting the since conceptually the timestamp is when the `_submit_orders` was executed. """ num_shares = order.diff_num_shares # TODO(Paul): The function `get_execution_price()` should be # configurable. price = get_execution_price(self.market_data, order, self._column_remap) fill = Fill(order, wall_clock_timestamp, num_shares, price) return [fill] def _log_order_submissions(self, orders: List[omorder.Order]) -> None: """ Add the orders to the internal book keeping. """ hdbg.dassert_container_type(orders, list, omorder.Order) wall_clock_timestamp = self._get_wall_clock_time() _LOG.debug("wall_clock_timestamp=%s", wall_clock_timestamp) if self._orders: last_timestamp = next(reversed(self._orders)) hdbg.dassert_lt(last_timestamp, wall_clock_timestamp) self._orders[wall_clock_timestamp] = orders @staticmethod def _get_next_submitted_order_id() -> int: submitted_order_id = AbstractBroker._submitted_order_id AbstractBroker._submitted_order_id += 1 return submitted_order_id # ############################################################################# # SimulatedBroker # ############################################################################# class SimulatedBroker(AbstractBroker): """ Represent a broker to which we can place orders and receive fills back. """ def __init__( self, *args: Any, ) -> None: super().__init__(*args) def get_fills(self) -> List[Fill]: return self._get_fills_helper() async def _submit_orders( self, orders: List[omorder.Order], wall_clock_timestamp: pd.Timestamp, *, dry_run: bool, ) -> str: """ Same as abstract method. """ # All the simulated behavior is already in the abstract class so there # is nothing to do here. _ = orders, wall_clock_timestamp if dry_run: _LOG.warning("Not submitting orders to OMS because of dry_run") return "dummy_order_receipt" async def _wait_for_accepted_orders( self, file_name: str, ) -> None: """ Same as abstract method. """ # Orders are always immediately accepted in simulation, so there is # nothing to do here. _ = file_name # ############################################################################# # MockedBroker # ############################################################################# class MockedBroker(AbstractBroker): """ An object that mocks a real broker backed by a DB with asynchronous updates to the state representing the placed orders. The DB contains the following tables: - `submitted_orders`: store information about orders placed by strategies - `accepted_orders`: store information about orders accepted by the OMS """ def __init__( self, *args: Any, db_connection: hsql.DbConnection, submitted_orders_table_name: str, accepted_orders_table_name: str, poll_kwargs: Optional[Dict[str, Any]] = None, ): super().__init__(*args) self._db_connection = db_connection self._submitted_orders_table_name = submitted_orders_table_name self._accepted_orders_table_name = accepted_orders_table_name if poll_kwargs is None: poll_kwargs = hasynci.get_poll_kwargs(self._get_wall_clock_time) self._poll_kwargs = poll_kwargs # Store the submitted rows to the DB for internal book keeping. self._submissions: Dict[ pd.Timestamp, pd.Series ] = collections.OrderedDict() def get_fills(self) -> List[Fill]: return self._get_fills_helper() async def _submit_orders( self, orders: List[omorder.Order], wall_clock_timestamp: pd.Timestamp, *, dry_run: bool = False, ) -> str: """ Same as abstract method. :return: a `file_name` representing the id of the submitted order in the DB """ # Add an order in the submitted orders table. submitted_order_id = self._get_next_submitted_order_id() orderlist:
import numpy as np from scipy.linalg import block_diag import math class rJoint: def __init__(self, alpha, a, theta, d, type, inertia, m, r): self.alpha = alpha self.a = a self.theta = theta self.d = d self.type = type self.inertia = inertia self.m = m self.r = r class cartesian: def __init__(self, x, y, z, roll, pitch, yaw): self.x = x self.y = y self.z = z self.roll = roll self.pitch = pitch self.yaw = yaw class fkine: def __init__(self, T, A, Aout, transl, R, rpy): self.T = T self.A = A self.Aout = Aout self.transl = transl self.R = R self.rpy = rpy class impedanceController: def __init__(self): self.Kd = np.diag(np.array([125,125,125,1,1,1])) self.Bd = np.diag(np.array([85,85,85,165,165,165])) self.Md = np.diag(np.array([15, 15, 15, 1, 1, 1])) # Controllers def output(self, x, xd, xdd, xc, xcd, F): Mdinv = np.linalg.inv(self.Md) damper = np.dot(self.Bd,(xcd - xd)) spring = np.dot(self.Kd,(xc - x)) ax = xdd - np.dot(self.Mdinv,(damper + spring + F)) return ax class Robot: def __init__(self, joints, ndof, dh): self.joints = joints self.ndof = ndof self.dh = dh def inverseDynamics(self, qc, qcdot, qcddot, grav): qc = qc.reshape((1,self.ndof)) qcdot = qcdot.reshape((1,self.ndof)) qcddot = qcddot.reshape((1,self.ndof)) if self.dh.lower() == 'mdh': grav = grav.reshape(3) Q = np.ravel(self.mdh_invdyn(qc, qcdot, qcddot, grav)) else: grav = grav.reshape((3,1)) # May need to fix this Q = np.ravel(self.invdyn(qc, qcdot, qcddot, grav)) return Q def forwardKinematics(self, q): if self.dh.lower() == 'mdh': T,A,Aout = self.mdh_Transform(q) else: T,A,Aout = self.Transform(q) transl = self.t2transl(T) R = self.t2rot(T) r,p,y = self.r2rpy(R) rpy = [r,p,y] kinematics = fkine(T, A, Aout, transl, R, rpy) return kinematics def jacobian(self, q): J = self.calcJac(q) return J def jacobianDot(self, q, qd): Jd = self.calcJacDot(q, qd) return Jd # Kinematics def mdh_Transform(rb, q): for j in range(rb.ndof): rb.joints[j].theta = q[j] A = [0 for i in range(rb.ndof)] alp = np.zeros(rb.ndof) a = np.zeros(rb.ndof) th = np.zeros(rb.ndof) d = np.zeros(rb.ndof) for i in range(rb.ndof): alp[i] = rb.joints[i].alpha a[i] = rb.joints[i].a th[i] = rb.joints[i].theta d[i] = rb.joints[i].d T = np.identity(4) Aout = [] for i in range(rb.ndof): ct = np.cos(th[i]) st = np.sin(th[i]) ca = np.cos(alp[i]) sa = np.sin(alp[i]) A[i] = np.array([[ct, -st, 0, a[i]], [(st * ca), (ct * ca), -sa, (-d[i] * sa)], [(st * sa), (ct * sa), ca, (d[i] * ca)], [0, 0, 0, 1]]) Aout.append(np.dot(T, A[i])) T = np.dot(T, A[i]) return T, A, Aout def Transform(rb, q): for j in range(rb.ndof): rb.joints[j].theta = q[j] A = [0 for i in range(rb.ndof)] alp = np.zeros(rb.ndof) a = np.zeros(rb.ndof) th = np.zeros(rb.ndof) d = np.zeros(rb.ndof) # A = np.zeros(2) for i in range(rb.ndof): alp[i] = rb.joints[i].alpha a[i] = rb.joints[i].a th[i] = rb.joints[i].theta d[i] = rb.joints[i].d T = np.identity(4) Aout = [] for i in range(rb.ndof): A[i] = np.array([[np.cos(th[i]), -np.sin(th[i]) * np.cos(alp[i]), np.sin(th[i]) * np.sin(alp[i]), a[i] * np.cos(th[i])], [np.sin(th[i]), np.cos(th[i]) * np.cos(alp[i]), -np.cos(th[i]) * np.sin(alp[i]), a[i] * np.sin(th[i])], [0, np.sin(alp[i]), np.cos(alp[i]), d[i]], [0, 0, 0, 1]]) Aout.append(np.dot(T, A[i])) T = np.dot(T, A[i]) return T, A, Aout def t2transl(self, T): transl = np.ravel(T[:3, 3]) return transl def t2rot(self, T): R = T[:3, :3] return R def r2eul(self, R): if (R[0,2] < np.finfo(float).eps and R[1,2] <np.finfo(float).eps): theta = 0 sp = 0 cp = 1 phi = np.arctan2(cp*R[0,2] + sp*R[1,2], R[2,2]) psi = np.arctan2(-sp*R[0,0] + cp*R[1,0], -sp*R[0,1] + cp*R[1,1]) else: # sin(theta) > 0 #theta = np.arctan2(R[2,2], np.sqrt(1 - (R[2,2]**2))) theta = np.arctan2(R[1,2],R[0,2]) sp = np.sin(theta) cp = np.cos(theta) phi = np.arctan2(cp*R[0,2] + sp*R[1,2], R[2,2]) psi = np.arctan2(-sp*R[0,0] + cp*R[1,0], -sp*R[0,1] + cp*R[1,1]) return theta, phi, psi def isclose(self, x, y, rtol=1.e-5, atol=1.e-8): return abs(x-y) <= atol + rtol * abs(y) def r2rpy(self, R): ''' From a paper by <NAME> (undated), "Computing Euler angles from a rotation matrix ''' phi = 0.0 if self.isclose(R[2,0],-1.0): theta = math.pi/2.0 psi = math.atan2(R[0,1],R[0,2]) elif self.isclose(R[2,0],1.0): theta = -math.pi/2.0 psi = math.atan2(-R[0,1],-R[0,2]) else: theta = -math.asin(R[2,0]) cos_theta = math.cos(theta) psi = math.atan2(R[2,1]/cos_theta, R[2,2]/cos_theta) phi = math.atan2(R[1,0]/cos_theta, R[0,0]/cos_theta) return psi, theta, phi def calcInverseKin(self, X): # Pre solved for the 2-DOF Planar robot. tx = X[0] ty = X[1] tz = X[2] q1 = 2*np.arctan((7*ty + (- 25*tx**4 - 50*tx**2*ty**2 + 49*tx**2 - 25*ty**4 + 49*ty**2)**(1/2))/(5*tx**2 + 7*tx + 5*ty**2)) q2 = -2*np.arctan((- 25*tx**2 - 25*ty**2 + 49)**(1/2)/(5*(tx**2 + ty**2)**(1/2))) if np.isnan(q1): q1 = 0 if np.isnan(q2): q2 = 0 qc = np.array([q1,q2]) return qc def calcQd(rb, Xd, qc, rho): J = rb.calcJac(qc) Jt = np.transpose(J) inner = np.linalg.inv( np.dot(J,Jt) + np.dot(np.identity(6),rho) ) Jinv = np.dot(Jt,inner) TestSingularity = np.linalg.det(J[:2,:2]) if(TestSingularity < (1e-9)) and (TestSingularity > -(1e-9)): qd = np.array([0,0]) print("in here qd") else: qd = np.dot(Jinv[:2,:2],Xd[:2]) return qd def calcQdd(rb, Xdd, qc, qd): J = rb.calcJac(qc) Jd = rb.calcJacDot(qc, qd) Jdq = np.dot(Jd,qd) kine = rb.forwardKinematics(qc) rpy = kine.rpy A = rb.rpy2Ja(rpy[0],rpy[1],rpy[2]) B = block_diag(np.eye(3),np.linalg.inv(A)) # Jadq = np.dot(B,Jdq) Ja = np.dot(B,J) Jpinv = rb.pinv(Ja) Jpinv = rb.pinv(Ja) qdd = np.dot(Jpinv, (Xdd - Jdq)) return qdd def calcQdd3(rb, Xdd, qc, qd): J = rb.calcJac(qc) Jd = rb.calcJacDot(qc, qd) Jdq = np.dot(Jd,qd) kine = rb.forwardKinematics(qc) rpy = kine.rpy A = rb.rpy2Ja(rpy[0],rpy[1],rpy[2]) B = block_diag(np.eye(3),np.linalg.inv(A)) # Jadq = np.dot(B,Jdq) Ja = np.dot(B,J) Jpinv = rb.pinv(Ja) qdd = np.dot(Jpinv[:,:3], (Xdd - Jdq[:3])) return qdd def calcXd(rb, qc, qd): J = rb.calcJac(qc) kine = rb.forwardKinematics(qc) rpy = kine.rpy A = rb.rpy2Ja(rpy[0],rpy[1],rpy[2]) B = block_diag(np.eye(3),np.linalg.inv(A)) # Jadq = np.dot(B,Jdq) Ja = np.dot(B,J) xd = np.dot(Ja,qd) return xd def calcXd3(rb, qc, qd): J = rb.calcJac(qc) # kine = rb.forwardKinematics(qc) # rpy = kine.rpy # A = rb.rpy2Ja(rpy[0],rpy[1],rpy[2]) # B = block_diag(np.eye(3),np.linalg.inv(A)) # # Jadq = np.dot(B,Jdq) # Ja = np.dot(B,J) xd = np.dot(J,qd) xd = xd[:3] return xd def calcJac(rb, q): J = np.zeros((6,7)) kine = rb.forwardKinematics(q) T = kine.T Aout = kine.Aout # To simplify the readability: J1v = np.cross( np.array([0, 0, 1]), T[:3,3]) J1w = np.array([0, 0, 1]) J1 = np.concatenate((J1v,J1w)) J[:,0] = J1 for i in range(1,rb.ndof): Aframe = Aout[i-1] Jv = np.cross( (Aframe[:3, 2]), (T[:3, 3] - Aframe[:3, 3]), axis=0) Jw = Aframe[:3, 2] Jtemp = np.concatenate((Jv, Jw)) J[:,i] = Jtemp return J def calcJacDot(rb, q, qd): J = np.zeros((6,7)) kine = rb.forwardKinematics(q) T = kine.T Aout = kine.Aout # To simplify the readability (Jacobian for the first joint): J1v = np.cross(np.array([0, 0, 1]), T[:3,3]) J1w = np.array([0, 0, 1]) J1 = np.concatenate((J1v,J1w)) J[:,0] = J1 # Jacobian computation # Declaring variables Jvi, Jwi = np.zeros((3,7)), np.zeros((3,7)) Jvi[:,0], Jwi[:,0] = J1v, J1w w, z = [], [] z.append( np.array([0, 0, 1]).reshape((3,1)) ) w.append( np.array([0, 0, 1]).reshape((3,1)) ) for i in range(1,rb.ndof): Aframe = Aout[i-1] z.append( np.array(Aframe[:3, 2]).reshape((3,1)) ) Jv = np.cross( (Aframe[:3, 2]), (T[:3, 3] - Aframe[:3, 3]), axis=0) Jw = Aframe[:3, 2] Jvi[:,i] = Jv Jwi[:,i] = Jw Jtemp = np.concatenate((Jv, Jw)) J[:,i] = Jtemp # w and z (used for Jacobian derivative computation) # Note to self, be aware of indexing. wtemp = w[len(w)-1] + np.dot(z[len(z) - 2], qd[i-1]) w.append(wtemp) # Jacobian derivative computation beta = np.array(np.dot(Jvi, qd)).reshape((3,1)) Jd = np.zeros((6,7)) for i in reversed(range(1, rb.ndof)): Aframe = Aout[i-1] zd = np.cross(w[i-1], z[i-1], axis = 0) alpha = np.array([0, 0, 0]).reshape((3,1)) for j in range(i): alpha = alpha + np.dot( np.cross(z[j+1-1], np.array(T[:3, 3] - Aframe[:3, 3]).reshape((3,1)), axis=0), qd[j]) # print "alpha", (alpha), "\n\n" Jvd = np.cross( zd, (T[:3, 3] - Aframe[:3, 3]), axis=0) + np.cross(z[i-1], (alpha + beta), axis=0) Jwd = zd Jtemp = np.concatenate((Jvd, Jwd)) Jd[:,i] = np.ravel(Jtemp) beta = beta + np.dot(Jvi[:,i-1], qd[i-1]).reshape((3,1)) # cross z0 x beta Jvd = np.cross(np.array([0, 0, 1]).reshape((3,1)), beta, axis=0) Jwd = np.array([0, 0, 0]).reshape((3,1)) Jtemp = np.concatenate((Jvd, Jwd)) Jd[:,0] = np.ravel(Jtemp) return Jd def eul2Ja(self, phi,theta,psi): Ja = np.array([[ 0, -np.sin(phi), np.cos(phi) * np.sin(theta)], [0, np.cos(phi), np.sin(phi) * np.sin(theta)], [1, 0, np.cos(theta) ]]) return Ja def rpy2Ja(self, r,p,y): Ja = np.array([[ 1, 0, np.sin(p)], [0, np.cos(r), -np.cos(p) * np.sin(r)], [0, np.sin(r), np.cos(p) * np.cos(r)]]) return Ja def pinv(self, J): u, s, vh = np.linalg.svd(J.T, full_matrices=True) u.shape, s.shape, vh.shape rho = 4 S2 = np.dot(J.T,0) for i in range(len(s)): S2[i,i] = s[i]
<reponame>chanul13/EDMFTF<filename>src/python/sjoin.py<gh_stars>1-10 #!/usr/bin/env python import utils,indmffile,sys,re,os import optparse from scipy import * import numpy nv = map(int,numpy.__version__.split('.')) if (nv[0],nv[1]) < (1,6): loadtxt = io.read_array def savetxt(filename, data): io.write_array(filename, data, precision=16) def loadtxtE(filename): if (nv[0],nv[1]) < (1,6): return io.read_array(filename)[:,:-2] else: return loadtxt(filename) def SimplifySiginds(siginds): " Takes dictionary of Sigind's and creates list or non-zero columns" def union(data): " Takes a union of array or list" c = [] for d in data: if d not in c: c.append(d) return c cols={} for icix in siginds.keys(): Sigind = siginds[icix] col = sorted(filter(lambda x: x>0, union(array(Sigind).flatten()))) cols[icix] = col return cols if __name__=='__main__': """ Takes the delta files, created by dmft1, and combines them into the input file for the impurity solver. There can be more output delta's from dmft1, then there are impurity problem to be solved. """ usage = """usage: %prog [ options ] The script takes the delta files, created by dmft1, and combines them into the input file for the impurity solver. There can be more output delta's from dmft1, then there are impurity problem to be solved. To give filename, you can use the following expressions: - word 'case', which will be replaced by current case, determined by the presence of struct file. - '?', which will be replaced by icix. """ parser = optparse.OptionParser(usage) parser.add_option("-i", "--delta", dest="indlt", default='case.dlt?', help="filename of the input delta file. Default: 'case.dlt?'") parser.add_option("-o", "--Delta", dest="outdlt", default='imp.?/Delta.imp', help="filename of the output Delta to be used by the impurity solver. Default: 'imp.?/Delta'") parser.add_option("-p", "--pDelta", dest="pdelta", default=None, help="If need to print the intermediate file which contains all deltas in one file") parser.add_option("-e", "--Eimp", dest="inE", default='case.Eimp?', help="filename of the input Eimp file. Default: 'case.Eimp?'") parser.add_option("-u", "--Eout", dest="outE", default='imp.?/Eimp.inp', help="filename of the output Eimp to be used by the impurity solver. Default: 'imp.?/Eimp.inp'") parser.add_option("-a", "--EimpAverage", dest="EimpAverage", default=1, help="By default we average over up/dn impurity levels. With EimpAverage=0, we skip that.") parser.add_option("-d", "--inDC", dest="inDC", default='Edc.dat', help="filename of the input DC-file (Edc.dat)") parser.add_option("-m", "--mix", dest="mix", type=float, default=1.0, help="Mixing parameter for hybridization. Default=1 -- no mixing") parser.add_option("-c", "--cfield", dest="cf", default=None, help="If CF needs to be reduced. Default=1 -- no reduction") parser.add_option("-l", "--lext", dest="m_extn", default='', help="For magnetic calculation, it can be 'dn'.") parser.add_option("-g", "--ginp", dest="ginp", default='case.gc?', help="filename of the input lattice green's function file. Default: 'case.gc?'") parser.add_option("-j", "--gout", dest="gout", default='imp.?/Glatt.imp', help="filename of the output lattice Green's function to be used by the impurity solver. Default: 'imp.?/Glatt.imp'") # Next, parse the arguments (options, args) = parser.parse_args() env = utils.W2kEnvironment() case = env.case options.indlt = re.sub(r'case', case, options.indlt) options.outdlt = re.sub(r'case', case, options.outdlt) options.inE = re.sub(r'case', case, options.inE) options.outE = re.sub(r'case', case, options.outE) options.ginp = re.sub(r'case', case, options.ginp) options.gout = re.sub(r'case', case, options.gout) if options.pdelta is not None: options.pdelta = re.sub(r'case', case, options.pdelta) print 'case=%s, indlt=%s, outdlt=%s, inE=%s, outE=%s, m_extn=%s' % (case, options.indlt, options.outdlt, options.inE, options.outE, options.m_extn) cf_sets=[] if options.cf is not None: cf_sets0 = options.cf.split(';') for c in cf_sets0: wcols = eval(c.split()[0]) wfact = float(c.split()[1]) cf_sets.append([wcols, wfact]) inl = indmffile.Indmfl(case) inl.read() if options.m_extn: inldn = indmffile.Indmfl(case, 'indmfl'+options.m_extn) inldn.read() iSiginds = utils.ParsIndmfi(case) icols = SimplifySiginds(iSiginds) print 'icols=', icols cols = SimplifySiginds(inl.siginds) print 'cols=', cols if options.m_extn: colsdn = SimplifySiginds(inldn.siginds) print 'colsdn=', colsdn allcols_ = cols.values() if options.m_extn: allcols_ += colsdn.values() allcols = sort( reduce(lambda x,y: x+y, allcols_) ) #allcols = sort(array(allcols).flatten()) print 'allcols=', allcols print 'max(allcols)=', max(allcols) noccur = zeros(max(allcols),dtype=int) #print 'len(noccur)=', len(noccur) for c in allcols: noccur[c-1]+=1 print 'noccur=', noccur # to check number of frequency points filename = re.sub(r'\?', str(1), options.indlt) data = loadtxt( filename ).transpose() om = data[0] # Array of all Delta's, after averaging over all columns and over all impurity problems. rDeltas=zeros(( max(allcols)*2+1, len(om) ),dtype=float) rDeltas[0] = om rGlatt=zeros(( max(allcols)*2+1, len(om) ),dtype=float) rGlatt[0] = om rEimps = zeros( max(allcols), dtype=float ) rOlaps = zeros( max(allcols), dtype=float ) # Reading output of dmft1 for icix in cols.keys(): if len(cols[icix])==0: continue filename = re.sub(r'\?', str(icix), options.indlt) data = loadtxt( filename ).transpose() mincol = min(cols[icix]) print ('icix=%d reading from: %s' % (icix, filename)), 'cols=', cols[icix] for c in cols[icix]: #print '%d Taking from col #(%d,%d) and putting into #(%d,%d)' % (c, 2*(c-mincol+1)-1, 2*(c-mincol+1), 2*c-1, 2*c ) rDeltas[2*c-1] += data[2*(c-mincol+1)-1]*(1./noccur[c-1]) rDeltas[2*c] += data[2*(c-mincol+1) ]*(1./noccur[c-1]) filename = re.sub(r'\?', str(icix), options.ginp) data = loadtxt( filename ).transpose() mincol = min(cols[icix]) print ('icix=%d reading from: %s' % (icix, filename)), 'cols=', cols[icix] for c in cols[icix]: #print '%d Taking from col #(%d,%d) and putting into #(%d,%d)' % (c, 2*(c-mincol+1)-1, 2*(c-mincol+1), 2*c-1, 2*c ) rGlatt[2*c-1] += data[2*(c-mincol+1)-1]*(1./noccur[c-1]) rGlatt[2*c] += data[2*(c-mincol+1) ]*(1./noccur[c-1]) # Processing impurity levels Eimpfile = re.sub(r'\?', str(icix), options.inE) execfile(Eimpfile) for c in cols[icix]: #print 'Eimpfile=%s %d Taking from col #(%d) and putting into #(%d)' % (Eimpfile, c, c-mincol, c-1 ) rEimps[c-1] += Ed[c-mincol]*(1./noccur[c-1]) rOlaps[c-1] += Olap[c-mincol]*(1./noccur[c-1]) if options.m_extn: # Reading output of dmft1 for icix in colsdn.keys(): filename = re.sub(r'\?', str(icix), options.indlt) filename += options.m_extn data = loadtxt( filename ).transpose() mincol = min(colsdn[icix]) print ('icix=%d reading from: %s' % (icix, filename)), 'cols=', colsdn[icix] for c in colsdn[icix]: #print '%d Taking from col #(%d,%d) and putting into #(%d,%d)' % (c, 2*(c-mincol+1)-1, 2*(c-mincol+1), 2*c-1, 2*c ) #print 'c=', c, 'mincol=', mincol, 'noccur=', noccur[c-1], 'ind=', 2*(c-mincol+1)-1 #print len(data[2*(c-mincol+1)-1]*(1./noccur[c-1])) #print len(rDeltas[2*c-1]) rDeltas[2*c-1] += data[2*(c-mincol+1)-1]*(1./noccur[c-1]) rDeltas[2*c] += data[2*(c-mincol+1) ]*(1./noccur[c-1]) filename = re.sub(r'\?', str(icix), options.ginp) filename += options.m_extn data = loadtxt( filename ).transpose() print ('icix=%d reading from: %s' % (icix, filename)), 'cols=', colsdn[icix] for c in colsdn[icix]: #print '%d Taking from col #(%d,%d) and putting into #(%d,%d)' % (c, 2*(c-mincol+1)-1, 2*(c-mincol+1), 2*c-1, 2*c ) rGlatt[2*c-1] += data[2*(c-mincol+1)-1]*(1./noccur[c-1]) rGlatt[2*c] += data[2*(c-mincol+1) ]*(1./noccur[c-1]) # Processing impurity levels Eimpfile = re.sub(r'\?', str(icix), options.inE) Eimpfile += options.m_extn execfile(Eimpfile) for c in colsdn[icix]: #print 'Eimpfile=%s %d Taking from col #(%d) and putting into #(%d)' % (Eimpfile, c, c-mincol, c-1 ) rEimps[c-1] += Ed[c-mincol]*(1./noccur[c-1]) rOlaps[c-1] += Olap[c-mincol]*(1./noccur[c-1]) print 'options.EimpAverage=', options.EimpAverage if int(options.EimpAverage): print 'Averaging!' # Averaging impurity leveles between up and down. Should be the same, except for the numerical error for icix in colsdn.keys(): for ic in range(len(cols[icix])): cu = cols[icix][ic] cd = colsdn[icix][ic] Eaver = 0.5*(rEimps[cu-1]+rEimps[cd-1]) Ediff = 0.5*(rEimps[cu-1]-rEimps[cd-1]) #print 'averaging over up and down', ic, cu, cd, rEimps[cu-1], rEimps[cd-1], Eaver, Ediff rEimps[cu-1] = Eaver rEimps[cd-1] = Eaver # Storing intermediate data, if necessary if options.pdelta is not None: savetxt(options.pdelta, rDeltas.transpose()) #if options.hlpE is not None: # fE = open(options.hlpE, 'w') # print >> fE, 'Ed=',rEimps.tolist(), '\n', 'Olap=',rOlaps.tolist() Edc = atleast_1d(loadtxt(options.inDC)) # Reducing CF if necessary for cf in cf_sets: factor = cf[1] mean=zeros((2,len(om)), dtype=float) Emean=0 for c in cf[0]: mean[0] += rDeltas[2*c-1] mean[1] += rDeltas[2*c] Emean += rEimps[c-1] mean *= 1./len(cf[0]) Emean *= 1./len(cf[0]) for c in cf[0]: rDeltas[2*c-1] = mean[0] + (rDeltas[2*c-1]-mean[0])*factor rDeltas[2*c] = mean[1] + (rDeltas[2*c]-mean[1])*factor rEimps[c-1] = Emean + (rEimps[c-1]-Emean)*factor # Arranging the Delta's for the impurity problems. for icix in icols.keys(): # Processing Delta mincol = min(icols[icix]) maxcol = max(icols[icix]) filename = re.sub(r'\?', str(icix), options.outdlt) fileGout = re.sub(r'\?', str(icix), options.gout) print ('icix=%d saving into: %s %s' % (icix, filename,fileGout)), 'cols=', icols[icix] #data=zeros((2*(maxcol-mincol+1)+1,len(om)), dtype=float) data=zeros((2*len(icols[icix])+1, len(om)), dtype=float) data[0] = om #datG=zeros((2*(maxcol-mincol+1)+1,len(om)), dtype=float) datG=zeros((2*len(icols[icix])+1, len(om)), dtype=float) datG[0] = om for ic,c in enumerate(icols[icix]): #data[2*(c-mincol+1)-1] = rDeltas[2*c-1] #data[2*(c-mincol+1)] = rDeltas[2*c] #datG[2*(c-mincol+1)-1] = rGlatt[2*c-1] #datG[2*(c-mincol+1)] = rGlatt[2*c] #print '%d Taking from col #(%d,%d) and putting into #(%d,%d)' % (c, 2*c-1, 2*c, 2*(c-mincol+1)-1, 2*(c-mincol+1) ) data[2*ic+1] = rDeltas[2*c-1] data[2*ic+2] = rDeltas[2*c] datG[2*ic+1] = rGlatt[2*c-1] datG[2*ic+2] = rGlatt[2*c] print '%d Taking from col #(%d,%d) and putting into #(%d,%d)' % (c, 2*c-1, 2*c, 2*ic+1, 2*ic+2 ) cdir = os.path.split(filename)[0] if cdir and not os.path.exists(cdir): print 'Output directory '+cdir+' does not exist! Creating it....!' os.makedirs(cdir) if options.mix!=1.0 and os.path.isfile(filename) and os.path.getsize(filename)>0: print 'Mixing delta with mix=', options.mix data0 = loadtxt(filename).transpose() data = options.mix*data + (1-options.mix)*data0 # Writting Delta savetxt(filename, data.transpose()) # Writting Glatt savetxt(fileGout, datG.transpose()) # Processing Impurity levels Edat=zeros(len(icols[icix]), dtype=float) Odat=zeros(len(icols[icix]), dtype=float) Edca=zeros(len(icols[icix]), dtype=float)
import base64 import os import re import urllib.request import xml.etree.ElementTree as ET from datetime import datetime from io import StringIO, BytesIO import requests from lxml import etree import base.utils as utils_module from base.models import WPS, Task, InputOutput, Artefact, Process, STATUS, Workflow, Edge from base.utils import ns_map, wps_em, ows_em from workflowPSE.settings import wps_log, BASE_DIR def scheduler(): """ Main scheduling function. Schedules Tasks in Workflows according to their execution order, generates execution XML files and sends tasks to their server for execution @return: None @rtype: NoneType """ # TODO: set to changeable by settings & config file wps_log.debug("starting schedule") dir_path = os.path.dirname(os.path.abspath(__file__)) xml_dir = os.path.join(dir_path, 'testfiles/') exec_list = [] for current_workflow in Workflow.objects.all(): all_tasks = Task.objects.filter(workflow=current_workflow, status='1') wps_log.debug( f"found {len(all_tasks)} tasks in workflow{current_workflow.id}") for current_task in all_tasks: previous_tasks_failed = False previous_tasks_finished = True edges_to_current_task = Edge.objects.filter(to_task=current_task) wps_log.debug( f"found {len(edges_to_current_task)} edges to task{current_task.id} in workflow{current_workflow.id}") for current_edge in edges_to_current_task: if current_edge.from_task.status == '4': wps_log.debug( f"task{current_task.id}'s prior task{current_edge.from_task.id} is finished") if not Artefact.objects.filter(task=current_task, role='0'): wps_log.warning(f"something is wrong here, task{current_task.id} has no artefacts," f"but there should at least be input artefacts") previous_tasks_finished = False break else: for current_artefact in Artefact.objects.filter(task=current_task, role='0'): wps_log.debug( f"checking data of artefact{current_artefact.id} of task{current_task.id}") if not current_artefact.data: wps_log.warning( f"task{current_task.id} has artefact{current_artefact.id} which has no data") previous_tasks_finished = False break else: wps_log.debug( f"task{current_task.id}s prior task{current_edge.from_task.id} is not finished") previous_tasks_finished = False if current_edge.from_task.status == '5': wps_log.debug(f"task{current_task.id}'s prior task{current_edge.from_task.id} has failed") previous_tasks_failed = True break if previous_tasks_failed: current_task.status = '5' current_task.save() elif previous_tasks_finished: wps_log.debug( f"previous task is finished, scheduling now following task{current_task.id}") current_task.status = '2' exec_list.append(current_task.id) current_task.save() # generate execute xmls for all tasks with status waiting xml_generator(xml_dir) wps_log.debug(f"xmls generated for tasks: {exec_list}") # send tasks for tid in exec_list: wps_log.debug(f"sending execution request to server for task{tid}") send_task(tid, xml_dir) # sys.stdout = orig_stdout # f.close() def xml_generator(xml_dir): """ Traverses Database and generates execution XML files for every Task set to status WAITING @param xml_dir: Directory where XMLs are generated in @type xml_dir: string @return: None @rtype: NoneType """ wps_log.debug("starting xml generator") try: task_list = list(Task.objects.filter(status='2')) except Task.DoesNotExist: wps_log.debug("no running tasks found") task_list = [] wps_log.debug(f"scheduled tasks: {[task.id for task in task_list]}") for task in task_list: try: process = task.process except Process.DoesNotExist: # process not found wps_log.warning(f"process of task{task.id} not found") return root = wps_em.Execute(ows_em.Identifier(process.identifier)) root.set('service', 'WPS') root.set('version', '1.0.0') inputs_tree = create_data_doc(task) if inputs_tree == 1: # error code, something wrong with task TODO: check for better handling? wps_log.warning(f"Error: missing input artefact for task{task.id}") continue root.append(inputs_tree) wps_log.debug( f"successfully inserted inputs to xml document for task{task.id}") response_doc = wps_em.ResponseDocument() response_doc.set('storeExecuteResponse', 'true') response_doc.set('lineage', 'true') response_doc.set('status', 'true') output_list = list(InputOutput.objects.filter( process=task.process, role='1')) wps_log.debug( f"list of outputs of task{task.id}: {[output.id for output in output_list]}") for output in output_list: response_doc.append(wps_em.Output(ows_em.Identifier(output.identifier), ows_em.Title(output.title), {'asReference': 'true'})) root.append(wps_em.ResponseForm(response_doc)) wps_log.debug(f"successfully created xml for task{task.id}") #f":\n{etree.tostring(root, pretty_print=True).decode()}") # use to print xml to log # write to file, for testing let pretty_print=True for better readability # TODO: rework if file path problem is solved try: with open(f"{xml_dir}/task{task.id}.xml", 'w') as xml_file: xml_file.write(etree.tostring(root, pretty_print=True).decode()) wps_log.debug(f"successfully written xml of task{task.id} to file, ready for sending to server") except: wps_log.warning(f"writing failed for task{task.id}") def create_data_doc(task): """ Creates subtree for execute request for model.Task task. @param task: the task for which the data subtree is created @type task: models.Task @return: subtree on success, error code 1 otherwise @rtype: lxml.etree._Element/int """ # returns [] if no match found wps_log.debug(f"creating data subtree for task{task.id}") inputs = list(InputOutput.objects.filter(process=task.process, role='0')) data_inputs = wps_em.DataInputs() wps_log.debug(f"found inputs: {[input.id for input in data_inputs]}") for input in inputs: # try to get artefact from db try: artefact = Artefact.objects.get(task=task, parameter=input) except: # something is wrong here if artefact has not been created yet # as execute documents for next execution are only started if previous task has finished # and when previous task has finished, the output data is automatically passed to next tasks input wps_log.warning( f"Error: artefact for task{task.id}s input{input.id} has not been created yet") return 1 # create identifier and title as they are used in any case identifier = ows_em.Identifier(input.identifier) title = ows_em.Title(input.title) # first check if it is a file path, as data with length over 490 chars will be stored in a file # if so insert file path in Reference node # TODO: must check if this equals correct url of own server matching to task if artefact.data == utils_module.get_file_path(task): wps_log.debug( f"file path found in task{task.id}s artefact{artefact.id}s data, inserting as data") data_inputs.append(wps_em.Input(identifier, title, wps_em.Reference({"method": "GET"}, {ns_map["href"]: utils_module.get_file_path(artefact)}))) # go to loop header and continue continue wps_log.debug( f"no file path as data in task{task.id}s artefact{artefact.id}, so there must be data") # literal data case, there is either a url or real data in the LiteralData element # in this case just send the data if input.datatype == '0': wps_log.debug(f"literal data found for task{task.id}") literal_data = wps_em.LiteralData(artefact.data) # check for attributes if artefact.format != 'plain': literal_data.set('dataType', artefact.format) # just create subtree with identifier, title and data with nested literaldata containing the artefacts data data_inputs.append(wps_em.Input( identifier, title, wps_em.Data(literal_data))) # complex data case, first try to parse xml, if successfully append to ComplexData element # second check if there is CDATA ?? elif input.datatype == '1': wps_log.debug(f"complex data found for task{task.id}") # append format data as attributes to complex data element # TODO: delete if unneeded, uncommented complex data format handling - complicated stuff # check if there is cdata in format # if artefact.format.split(";")[0] == "CDATA": # wps_log.debug( # f"cdata found in task{task.id} inserting cdata nested in tags into data of artefact{artefact.id}") # complex_data.append(f"<![CDATA[{artefact.data}]]") # # put data nested in cdata tag in complex data element # data_inputs.append(wps_em.Input( # identifier, title, wps_em.Data(complex_data))) # else: # just append it as if it is in xml format, it can also be inserted as text, will then not be in # pretty_print format, but wps server doesn't care about that try: wps_log.debug( f"just inserting complex data for task{task.id} of artefact{artefact.id} in xml") data_inputs.append(wps_em.Input( identifier, title, wps_em.Data(wps_em.ComplexData(artefact.data)))) except: wps_log.debug( f"inserting CDATA for task{task.id} of artefact{artefact.id} in xml") data_inputs.append(wps_em.Input( identifier, title, wps_em.Data(wps_em.ComplexData(etree.CDATA(base64.b64decode(artefact.data)))))) # bounding box case there should just be lowercorner and uppercorner data elif input.datatype == '2': wps_log.debug(f"boundingbox data found for task{task.id}: {artefact.data}") lower_corner = ows_em.LowerCorner() upper_corner = ows_em.UpperCorner() data = artefact.data wps_log.debug(f"{len(data.split('LowerCorner')) == 2 and len(data.split('UpperCorner')) == 2}") if len(data.split("LowerCorner")) == 2 and len(data.split("UpperCorner")) == 2: bbox_corners = data.split(";") lower_corner_data = bbox_corners[1].lstrip('LowerCorner').split(' ') upper_corner_data = bbox_corners[0].lstrip('UpperCorner').split(' ') upper_corner = ows_em.UpperCorner(f"{upper_corner_data[0]} {upper_corner_data[1]}") lower_corner = ows_em.LowerCorner(f"{lower_corner_data[0]} {lower_corner_data[1]}") # quite strange, but this node is called BoundingBoxData for inputs, for outputs it's just BoundingBox # also for inputs it is used with wps namespace, for outputs the ows namespace is used bbox_elem = wps_em.Data(wps_em.BoundingBoxData(lower_corner, upper_corner, {'crs':'EPSG:4326', 'dimensions':'2'})) # finally create subtree data_inputs.append(wps_em.Input(identifier, title, bbox_elem)) # TODO: check if something is missing wps_log.debug(f"finished input xml generation for task{task.id}") return data_inputs def send_task(task_id, xml_dir): """ Sends a Task identified by its Database ID to its WPS Server. @param task_id: ID of Task in Database @type task_id: int @param xml_dir: Directory where XMLs are stored in @type xml_dir: string @return: None @rtype: NoneType """ filepath = str(xml_dir) + 'task' + str(task_id) + '.xml' if not os.path.isfile(filepath): wps_log.warning(f"file for task {task_id} does not exist, aborting...") return try: # This only is outsourced to extra function for better readability execute_url = get_execute_url(Task.objects.get(id=task_id)) except Task.DoesNotExist: wps_log.warning("Error, execute url is empty, but is not allowed to. Aborting...") return # TODO: validate execution url file = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>' + \ str(open(filepath, 'r').read()) # send to url try: # 'http://pse.rudolphrichard.de:5000/wps' response = requests.post(execute_url, data=file) # get response from send xml = ET.fromstring(response.text) except: task = Task.objects.get(id=task_id) task.status = '5' task.save() task_failed_handling(task, "status could not be read, check internet connection or server availability") wps_log.warning(f"request for task{task_id} could not be posted or returned something unexpected, aborting") return err_msg = "" # check for status node in xml if xml.find(ns_map['Status']) is not None: # if there is status node, search for process status if xml.find(ns_map['Status']).find(ns_map['ProcessAccepted']) is not
reader = csv.reader(csvfile, delimiter=self._separator) heads = next(reader) # find index of each target field name idx_cols = field2idx(cols, heads) assert len(idx_cols) == len(cols), \ "one or more field names are not found in {}".format(self._input) cols = idx_cols else: reader = csv.reader(csvfile, delimiter=self._separator) if self._has_head: # skip field name next(reader) # fast path, all rows are used if rows is None: for line in reader: rel_type = line[cols[2]] if rel_type in rel_edges: rel_edges[rel_type][0].append(line[cols[0]]) rel_edges[rel_type][1].append(line[cols[1]]) else: rel_edges[rel_type] = ([line[cols[0]]],[line[cols[1]]]) else: row_idx = 0 for idx, line in enumerate(reader): if len(rows) == row_idx: break if rows[row_idx] == idx: rel_type = line[cols[2]] if rel_type in rel_edges: rel_edges[rel_type][0].append(line[cols[0]]) rel_edges[rel_type][1].append(line[cols[1]]) else: rel_edges[rel_type] = ([line[cols[0]]],[line[cols[1]]]) row_idx += 1 # else skip this line return rel_edges def _load_labels(self, cols, multilabel=False, separator=None, rows=None): src_nodes = [] dst_nodes = [] labels = [] with open(self._input, newline='', encoding=self._encoding) as csvfile: if isinstance(cols[0], str): assert self._has_head, \ "The column name is provided to identify the target column." \ "The input csv should have the head field" reader = csv.reader(csvfile, delimiter=self._separator) heads = next(reader) # find index of each target field name idx_cols = field2idx(cols, heads) assert len(idx_cols) == len(cols), \ "one or more field names are not found in {}".format(self._input) cols = idx_cols else: reader = csv.reader(csvfile, delimiter=self._separator) if self._has_head: # skip field name next(reader) # fast path, all rows are used if rows is None: for line in reader: src_nodes.append(line[cols[0]]) dst_nodes.append(line[cols[1]]) if multilabel: labels.append(line[cols[2]].split(separator)) else: if len(cols) == 3: labels.append(line[cols[2]]) else: row_idx = 0 for idx, line in enumerate(reader): if len(rows) == row_idx: break if rows[row_idx] == idx: src_nodes.append(line[cols[0]]) dst_nodes.append(line[cols[1]]) if multilabel: labels.append(line[cols[2]].split(separator)) else: if len(cols) == 3: labels.append(line[cols[2]]) row_idx += 1 # else skip this line return src_nodes, dst_nodes, labels def process(self, node_dicts, label_map=None): """ Preparing edges and labels for creating dgl graph. Src nodes and dst nodes are converted into consecutive integer ID spaces and its corresponding labels are concatenated together. Parameters ---------- node_dicts: dict of dict {node_type: {node_str : node_id}} label_map: dict of dict Label mapping for each edge type Return ------ dict {edge_type: ((train_snids, train_dnids, train_labels, valid_snids, valid_dnids, valid_labels, test_snids, test_dnids, test_labels)} """ results = {} total_labels = {} for raw_labels in self._labels: edge_type, src_nodes, dst_nodes, labels, split = raw_labels train_split, valid_split, test_split = split if edge_type is None: src_type = None dst_type = None else: src_type, rel_type, dst_type = edge_type # convert src node and dst node if src_type in node_dicts: snid_map = node_dicts[src_type] else: snid_map = {} node_dicts[src_type] = snid_map if dst_type in node_dicts: dnid_map = node_dicts[dst_type] else: dnid_map = {} node_dicts[dst_type] = dnid_map snids = [] dnids = [] for node in src_nodes: nid = get_id(snid_map, node) snids.append(nid) for node in dst_nodes: nid = get_id(dnid_map, node) dnids.append(nid) snids = np.asarray(snids, dtype='long') dnids = np.asarray(dnids, dtype='long') # check if same edge_type already exists if edge_type in results: results[edge_type].append((snids, dnids, split)) total_labels[edge_type] = total_labels[edge_type] + labels \ if self._has_label else None else: results[edge_type] = [] total_labels[edge_type] = labels if self._has_label else None results[edge_type].append((snids, dnids, split)) processed_labels = {} label_offs = {} for edge_type, labels in total_labels.items(): if self._has_label: if label_map is not None: classes = [label_map[edge_type][idx] for idx in range(len(label_map[edge_type]))] else: classes = None if self._is_multilabel: labels, label_map = parse_category_multi_feat(labels, norm=None, classes=classes) else: labels, label_map = parse_category_single_feat(labels, norm=None, classes=classes) self._label_map[edge_type] = label_map else: labels = None processed_labels[edge_type] = labels label_offs[edge_type] = 0 processed_results = {} for edge_type, vals in results.items(): for val in vals: snids, dnids, split = val train_split, valid_split, test_split = split num_edges = snids.shape[0] offset = label_offs[edge_type] labels = None if processed_labels[edge_type] is None \ else processed_labels[edge_type][offset:offset+num_edges] label_offs[edge_type] = offset+num_edges # only train if train_split == 1.: train_snids = snids train_dnids = dnids train_labels = labels valid_snids, valid_dnids, valid_labels = None, None, None test_snids, test_dnids, test_labels = None, None, None # only valid elif valid_split == 1.: train_snids, train_dnids, train_labels = None, None, None valid_snids = snids valid_dnids = dnids valid_labels = labels test_snids, test_dnids, test_labels = None, None, None # only test elif test_split == 1.: train_snids, train_dnids, train_labels = None, None, None valid_snids, valid_dnids, valid_labels = None, None, None test_snids = snids test_dnids = dnids test_labels = labels else: num_nids = snids.shape[0] train_idx, valid_idx, test_idx = \ split_idx(num_nids, train_split, valid_split, test_split) train_snids = snids[train_idx] if len(train_idx) > 0 else None train_dnids = dnids[train_idx] if len(train_idx) > 0 else None valid_snids = snids[valid_idx] if len(valid_idx) > 0 else None valid_dnids = dnids[valid_idx] if len(valid_idx) > 0 else None test_snids = snids[test_idx] if len(test_idx) > 0 else None test_dnids = dnids[test_idx] if len(test_idx) > 0 else None if labels is not None: train_labels = labels[train_idx] valid_labels = labels[valid_idx] test_labels = labels[test_idx] else: train_labels, valid_labels, test_labels = None, None, None # chech if same edge_type already exists # if so concatenate the labels if edge_type in processed_results: last_train_snids, last_train_dnids, last_train_labels, \ last_valid_snids, last_valid_dnids, last_valid_labels, \ last_test_snids, last_test_dnids, last_test_labels = processed_results[edge_type] processed_results[edge_type] = (train_snids if last_train_snids is None else \ last_train_snids if train_snids is None else \ np.concatenate((last_train_snids, train_snids)), train_dnids if last_train_dnids is None else \ last_train_dnids if train_dnids is None else \ np.concatenate((last_train_dnids, train_dnids)), train_labels if last_train_labels is None else \ last_train_labels if train_labels is None else \ np.concatenate((last_train_labels, train_labels)), valid_snids if last_valid_snids is None else \ last_valid_snids if valid_snids is None else \ np.concatenate((last_valid_snids, valid_snids)), valid_dnids if last_valid_dnids is None else \ last_valid_dnids if valid_dnids is None else \ np.concatenate((last_valid_dnids, valid_dnids)), valid_labels if last_valid_labels is None else \ last_valid_labels if valid_labels is None else \ np.concatenate((last_valid_labels, valid_labels)), test_snids if last_test_snids is None else \ last_test_snids if test_snids is None else \ np.concatenate((last_test_snids, test_snids)), test_dnids if last_test_dnids is None else \ last_test_dnids if test_dnids is None else \ np.concatenate((last_test_dnids, test_dnids)), test_labels if last_test_labels is None else \ last_test_labels if test_labels is None else \ np.concatenate((last_test_labels, test_labels))) else: processed_results[edge_type] = (train_snids, train_dnids, train_labels, valid_snids, valid_dnids, valid_labels, test_snids, test_dnids, test_labels) return processed_results def addTrainSet(self, cols, multilabel=False, separator=None, rows=None, edge_type=None): r"""Add Training Set. Two or three columns of the **input** are chosen. If only two columns are provied, they represent the column names of the source nodes and destination nodes. This represents the existance of the edges. If three columns are provided, the first two columns represent the column names of the source nodes and destination nodes while the last column give the labels. Multi-label is supported, but a separator is required to split the labels. Parameters ---------- cols: list of str or list of int Which columns to use. Supported data formats are: (1) [str, str] column names for source node, destination node. (2) [int, int] column numbers for source node, destination node. (3) [str, str, str] column names for source node, destination node and labels. The first column is treated as source node name, the second column is treated as destination node name and the third column is treated as label. (4) [int, int, int] column numbers for node and labels. The first column is treated as source node name, the second column is treated as destination node name and the third column is treated as label. multilabel: bool Whether it is a multi-label task. Default: False separator: str, optional Delimiter(separator) used to split label data. Default: None rows: numpy.array or list of int Which row(s) to load. None to load all. Default: None edge_type: str Canonical edge type. If None, default edge type is chosen. Default: None Examples -------- ** Load train labels ** Example data of label.csv is as follows: ====== ======== ==== name movie rate ====== ======== ==== John StarWar1 5.0 Tim X-Man 3.5 Maggie StarWar1 4.5 ====== ======== ==== >>> label_loader = dgl.data.EdgeLabelLoader(input='label.csv', separator="\t") >>> label_loader.addTrainSet(['name', 'movie', 'rate'], rows=np.arange(start=0, stop=100)) """ if not isinstance(cols, list): raise RuntimeError("The cols should be a list of string or int") if len(cols) != 2 and len(cols) != 3: raise RuntimeError("addTrainSet accepts two columns " \
<reponame>moble/mktheapidocs import inspect, os, pathlib, importlib, black, re, click, enum from numpydoc.docscrape import NumpyDocString, FunctionDoc, ClassDoc from functools import cmp_to_key def get_line(thing): """ Get the line number for something. Parameters ---------- thing : function, class, module Returns ------- int Line number in the source file """ try: return inspect.getsourcelines(thing)[1] except TypeError: # Might be a property return inspect.getsourcelines(thing.fget)[1] except Exception as e: # print(thing) raise e def _sort_modules(mods): """ Always sort `index` or `README` as first filename in list. """ def compare(x, y): x = x[1] y = y[1] if x == y: return 0 if y.stem == "__init__.py": return 1 if x.stem == "__init__.py" or x < y: return -1 return 1 return sorted(mods, key=cmp_to_key(compare)) def get_submodule_files(module, hide=["_version"]): modules = set() module_file = pathlib.Path(module.__file__).parent for root, dirs, files in os.walk(module_file): module_path = pathlib.Path(root).relative_to(module_file.parent) if not module_path.parts[-1].startswith("_"): try: for file in files: module_name = ( "" if "__init__.py" == file else inspect.getmodulename(file) ) if module_name is not None and module_name not in hide: submodule = importlib.import_module( ".".join((module_path / module_name).parts) ) modules.add((submodule, module_path / file)) except ModuleNotFoundError: print(f"Skipping {'.'.join(module_path.parts)} - not a module.") return _sort_modules(modules) def get_all_modules_from_files(module, hide=["__init__", "_version"]): modules = set() module_file = pathlib.Path(module.__file__).parent.parent dir_was = pathlib.Path().absolute() os.chdir(module_file) for root, dirs, files in os.walk(module.__name__): module_path = pathlib.Path(root) if not module_path.parts[-1].startswith("_"): try: module = importlib.import_module(".".join(module_path.parts)) if not module.__name__.startswith("_"): modules.add((module.__name__, module, False, module_path)) for file in files: module_name = inspect.getmodulename(file) if module_name is not None and module_name not in hide: submodule = importlib.import_module( ".".join( (module_path / inspect.getmodulename(file)).parts ) ) if not module.__name__.startswith( "_" ) and not submodule.__name__.startswith("_"): modules.add( ( submodule.__name__, submodule, True, module_path.absolute() / file, ) ) except ModuleNotFoundError: print(f"Skipping {'.'.join(module_path.parts)} - not a module.") os.chdir(dir_was) return modules def get_classes(module): return set( [ x for x in inspect.getmembers(module, inspect.isclass) if (not x[0].startswith("_")) and x[1].__module__ == module.__name__ and not type(x[1]) is enum.EnumMeta ] ) def get_enums(module): return set( [ x for x in inspect.getmembers(module, inspect.isclass) if (not x[0].startswith("_")) and x[1].__module__ == module.__name__ and type(x[1]) is enum.EnumMeta ] ) def get_funcs(module): return set( [ x for x in inspect.getmembers(module, inspect.isfunction) if (not x[0].startswith("_")) and x[1].__module__ == module.__name__ ] ) def get_available_funcs(module): shared_root = module.__name__.split(".")[0] return set( [ x for x in inspect.getmembers(module, inspect.isfunction) if (not x[0].startswith("_")) and x[1].__module__.split(".")[0] == shared_root ] ) def get_available_classes(module): shared_root = module.__name__.split(".")[0] return set( [ x for x in inspect.getmembers(module, inspect.isclass) if (not x[0].startswith("_")) and x[1].__module__.split(".")[0] == shared_root ] ) def deffed_here(thing, holder): return inspect.getfile(thing) == inspect.getfile(holder) def fix_footnotes(s): return re.subn("\[([0-9]+)\]_", r"[^\1]", s)[0] def mangle_types(types): default = re.findall("default .+", types) mangled = [] try: if len(default): default = re.sub("default (.+)", r"default ``\1``", default[0]) mangled.append(default) types = re.sub("default .+", "", types) curlied = re.findall("{.+}", types) no_curls = re.subn("{.+},?", "", types)[0] annotated = re.findall("[a-zA-Z]+\[.+\]", no_curls) no_curls = re.subn("[a-zA-Z]+\[.+\],?", "", no_curls)[0] ts = [t.strip() for t in no_curls.split(",")] ts = [t.split(" or ") for t in ts] ts = [item for sublist in ts for item in sublist if item != ""] types = ts + curlied + annotated for ix, typ in enumerate(types): ts = [f"``{t}``" for t in typ.split(" of ")] mangled.append(" of ".join(ts)) except Exception as e: # print(e) # print(default) # print(types) raise e output = reversed(mangled) return ", ".join(output) def mangle_examples(examples): was_in_python = False in_python = False lines = [] for line in examples: if line.startswith(">>>"): in_python = True if line == "": in_python = False if not in_python and was_in_python: lines.append("\n```\n") elif not in_python: lines.append(f"{line} ") elif in_python and not was_in_python: lines.append("\n```python\n") lines.append(re.sub(">>> ", "", line) + "\n") else: lines.append(re.sub(">>> ", "", line) + "\n") was_in_python = in_python if was_in_python: lines.append("\n```") lines.append("\n\n") return lines def notes_section(doc): lines = [] if "Notes" in doc and len(doc["Notes"]) > 0: lines.append("!!! note\n") lines.append(f" {' '.join(doc['Notes'])}\n\n") return lines def warnings_section(doc): lines = [] if "Warnings" in doc and len(doc["Warnings"]) > 0: lines.append("!!! warning\n") lines.append(f" {' '.join(doc['Warnings'])}\n\n") return lines def refs_section(doc): """ Generate a References section. Parameters ---------- doc : dict Dictionary produced by numpydoc Returns ------- list of str Markdown for references section """ lines = [] if "References" in doc and len(doc["References"]) > 0: # print("Found refs") for ref in doc["References"]: # print(ref) ref_num = re.findall("\[([0-9]+)\]", ref)[0] # print(ref_num) ref_body = " ".join(ref.split(" ")[2:]) # print(f"[^{ref_num}] {ref_body}" + "\n") lines.append(f"[^{ref_num}]: {ref_body}" + "\n\n") # print(lines) return lines def examples_section(doc, header_level): """ Generate markdown for Examples section. Parameters ---------- doc : dict Dict from numpydoc header_level : int Number of `#`s to use for header Returns ------- list of str Markdown for examples section """ lines = [] if "Examples" in doc and len(doc["Examples"]) > 0: lines.append(f"{'#'*(header_level+1)} Examples \n") egs = "\n".join(doc["Examples"]) lines += mangle_examples(doc["Examples"]) return lines def returns_section(thing, doc, header_level): """ Generate markdown for Returns section. Parameters ---------- thing : function Function to produce returns for doc : dict Dict from numpydoc header_level : int Number of `#`s to use for header Returns ------- list of str Markdown for examples section """ lines = [] return_type = None # print(thing) # print(doc) try: return_type = thing.__annotations__["return"] except AttributeError: try: return_type = thing.fget.__annotations__["return"] except: pass except KeyError: pass if return_type is None: return_type = "" else: # print(f"{thing} has annotated return type {return_type}") try: return_type = ( f"{return_type.__name__}" if return_type.__module__ == "builtins" else f"{return_type.__module__}.{return_type.__name__}" ) except AttributeError: return_type = str(return_type) # print(return_type) try: if "Returns" in doc and len(doc["Returns"]) > 0 or return_type != "": # print(doc["Returns"]) lines.append(f"{'#'*(header_level+1)} Returns\n") if return_type != "" and len(doc["Returns"]) == 1: name, typ, desc = doc["Returns"][0] if typ != "" and name != "": lines.append(f"- `{name}`: ``{return_type}``") else: lines.append(f"- ``{return_type}``") lines.append("\n\n") if desc != "": lines.append(f" {' '.join(desc)}\n\n") elif return_type != "": lines.append(f"- ``{return_type}``") lines.append("\n\n") else: for name, typ, desc in doc["Returns"]: if ":" in name: name, typ = name.split(":") if typ != "": if name != "": line = f"- `{name}`: {mangle_types(typ)}" else: line = f"- {mangle_types(typ)}" else: line = f"- {mangle_types(name)}" line += "\n\n" lines.append(line) lines.append(f" {' '.join(desc)}\n\n") except Exception as e: # print(e) # print(doc) pass return lines def summary(doc): """ Generate markdown for summary section. Parameters ---------- doc : dict Output from numpydoc Returns ------- list of str Markdown strings """ lines = [] if "Summary" in doc and len(doc["Summary"]) > 0: lines.append(fix_footnotes(" ".join(doc["Summary"]))) lines.append("\n") if "Extended Summary" in doc and len(doc["Extended Summary"]) > 0: lines.append(fix_footnotes(" ".join(doc["Extended Summary"]))) lines.append("\n") return lines def params_section(thing, doc, header_level): """ Generate markdown for Parameters section. Parameters ---------- thing : function Function to produce parameters from doc : dict Dict from numpydoc header_level : int Number of `#`s to use for header Returns ------- list of str Markdown for examples section """ lines = [] class_doc = doc["Parameters"] return type_list( inspect.signature(thing), class_doc, "#" * (header_level + 1) + " Parameters\n\n", ) def escape(string): """ Escape underscores in markdown. Parameters ---------- string : str String to escape Returns ------- str The string, with `_`s escaped with backslashes """ return string.replace("_", "\\_") def get_source_link(thing, source_location): """ Get a link to the line number a module/class/function is defined at. Parameters ---------- thing : function or class Thing to get the link for source_location : str GitHub url of the source code Returns ------- str String with link to the file & line number, or empty string if it couldn't be found """ try: lineno = get_line(thing) try: owner_module = inspect.getmodule(thing) assert owner_module is not None except (TypeError, AssertionError): owner_module = inspect.getmodule(thing.fget) thing_file = "/".join(owner_module.__name__.split(".")) if owner_module.__file__.endswith("__init__.py"): thing_file += "/__init__.py" else: thing_file += ".py" return ( f"Source: [{escape(thing_file)}]({source_location}/{thing_file}#L{lineno})" + "\n\n" ) except Exception as e: # print("Failed to find source file.") # print(e) # print(lineno) # print(thing) # print(owner_module) # print(thing_file) # print(source_location) pass return "" def get_signature(name, thing): """ Get the signature for a function or class, formatted nicely if possible. Parameters ---------- name : str Name of the thing, used as the first part of the signature thing : class or function Thing to get the signature of """ if inspect.ismodule(thing): return "" if isinstance(thing, property): func_sig = name else: try: sig
self.d1 = self.d_val_lead_aborp[self.energy_count] self.b2 = self.b_val_tun_aborp[self.energy_count] self.c2 = self.c_val_tun_aborp[self.energy_count] self.a2 = self.a_val_tun_aborp[self.energy_count] self.xk2 = self.Xk_val_tun_aborp[self.energy_count] self.d2 = self.d_val_tun_aborp[self.energy_count] self.b = round((self.b1*(log10(self.z2)-log10(self.zeq))+self.b2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.c = round((self.c1*(log10(self.z2)-log10(self.zeq))+self.c2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.a = round((self.a1*(log10(self.z2)-log10(self.zeq))+self.a2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.xk = round((self.xk1*(log10(self.z2)-log10(self.zeq))+self.xk2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.d = round((self.d1*(log10(self.z2)-log10(self.zeq))+self.d2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 10) self.buildup_eabf_func() elif self.z1 == 92 and self.z2 == 82: self.b1 = self.b_val_ura_aborp[self.energy_count] self.c1 = self.c_val_ura_aborp[self.energy_count] self.a1 = self.a_val_ura_aborp[self.energy_count] self.xk1 = self.Xk_val_ura_aborp[self.energy_count] self.d1 = self.d_val_ura_aborp[self.energy_count] self.b2 = self.b_val_lead_aborp[self.energy_count] self.c2 = self.c_val_lead_aborp[self.energy_count] self.a2 = self.a_val_lead_aborp[self.energy_count] self.xk2 = self.Xk_val_lead_aborp[self.energy_count] self.d2 = self.d_val_lead_aborp[self.energy_count] self.b = round((self.b1*(log10(self.z2)-log10(self.zeq))+self.b2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.c = round((self.c1*(log10(self.z2)-log10(self.zeq))+self.c2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.a = round((self.a1*(log10(self.z2)-log10(self.zeq))+self.a2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.xk = round((self.xk1*(log10(self.z2)-log10(self.zeq))+self.xk2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.d = round((self.d1*(log10(self.z2)-log10(self.zeq))+self.d2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 10) self.buildup_eabf_func() else: pass for i in range(25): self.all_gp_result_tableWidget.setItem(i, 0, QtWidgets.QTableWidgetItem(str(self.enrgy_option[i]))) self.all_gp_result_tableWidget.setItem(self.energy_count, 1, QtWidgets.QTableWidgetItem(str(self.b))) self.all_gp_result_tableWidget.setItem(self.energy_count, 2, QtWidgets.QTableWidgetItem(str(self.c))) self.all_gp_result_tableWidget.setItem(self.energy_count, 3, QtWidgets.QTableWidgetItem(str(self.a))) self.all_gp_result_tableWidget.setItem(self.energy_count, 4, QtWidgets.QTableWidgetItem(str(self.xk))) self.all_gp_result_tableWidget.setItem(self.energy_count, 5, QtWidgets.QTableWidgetItem(str(self.d))) self.all_gp_result_tableWidget.setItem(self.energy_count, 6, QtWidgets.QTableWidgetItem(str(self.eabf))) elif self.all_gp_type == "Exposure": if self.z1 == 5 and self.z2 == 4: self.b1 = self.b_val_bor_expo[self.energy_count] self.c1 = self.c_val_bor_expo[self.energy_count] self.a1 = self.a_val_bor_expo[self.energy_count] self.xk1 = self.Xk_val_bor_expo[self.energy_count] self.d1 = self.d_val_bor_expo[self.energy_count] self.b2 = self.b_val_bery_expo[self.energy_count] self.c2 = self.c_val_bery_expo[self.energy_count] self.a2 = self.a_val_bery_expo[self.energy_count] self.xk2 = self.Xk_val_bery_expo[self.energy_count] self.d2 = self.d_val_bery_expo[self.energy_count] self.b = round((self.b1*(log10(self.z2)-log10(self.zeq))+self.b2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.c = round((self.c1*(log10(self.z2)-log10(self.zeq))+self.c2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.a = round((self.a1*(log10(self.z2)-log10(self.zeq))+self.a2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.xk = round((self.xk1*(log10(self.z2)-log10(self.zeq))+self.xk2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.d = round((self.d1*(log10(self.z2)-log10(self.zeq))+self.d2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 10) self.buildup_ebf_func() elif self.z1 == 6 and self.z2 ==5: self.b1 = self.b_val_car_expo[self.energy_count] self.c1 = self.c_val_car_expo[self.energy_count] self.a1 = self.a_val_car_expo[self.energy_count] self.xk1 = self.Xk_val_car_expo[self.energy_count] self.d1 = self.d_val_car_expo[self.energy_count] self.b2 = self.b_val_bor_expo[self.energy_count] self.c2 = self.c_val_bor_expo[self.energy_count] self.a2 = self.a_val_bor_expo[self.energy_count] self.xk2 = self.Xk_val_bor_expo[self.energy_count] self.d2 = self.d_val_bor_expo[self.energy_count] self.b = round((self.b1*(log10(self.z2)-log10(self.zeq))+self.b2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.c = round((self.c1*(log10(self.z2)-log10(self.zeq))+self.c2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.a = round((self.a1*(log10(self.z2)-log10(self.zeq))+self.a2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.xk = round((self.xk1*(log10(self.z2)-log10(self.zeq))+self.xk2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.d = round((self.d1*(log10(self.z2)-log10(self.zeq))+self.d2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 10) self.buildup_ebf_func() elif self.z1 == 7 and self.z2 ==6: self.b1 = self.b_val_nit_expo[self.energy_count] self.c1 = self.c_val_nit_expo[self.energy_count] self.a1 = self.a_val_nit_expo[self.energy_count] self.xk1 = self.Xk_val_nit_expo[self.energy_count] self.d1 = self.d_val_nit_expo[self.energy_count] self.b2 = self.b_val_car_expo[self.energy_count] self.c2 = self.c_val_car_expo[self.energy_count] self.a2 = self.a_val_car_expo[self.energy_count] self.xk2 = self.Xk_val_car_expo[self.energy_count] self.d2 = self.d_val_car_expo[self.energy_count] self.b = round((self.b1*(log10(self.z2)-log10(self.zeq))+self.b2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.c = round((self.c1*(log10(self.z2)-log10(self.zeq))+self.c2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.a = round((self.a1*(log10(self.z2)-log10(self.zeq))+self.a2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.xk = round((self.xk1*(log10(self.z2)-log10(self.zeq))+self.xk2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.d = round((self.d1*(log10(self.z2)-log10(self.zeq))+self.d2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 10) self.buildup_ebf_func() elif self.z1 == 8 and self.z2 ==7: #for i in range(25): self.b1 = self.b_val_oxy_expo[self.energy_count] self.c1 = self.c_val_oxy_expo[self.energy_count] self.a1 = self.a_val_oxy_expo[self.energy_count] self.xk1 = self.Xk_val_oxy_expo[self.energy_count] self.d1 = self.d_val_oxy_expo[self.energy_count] self.b2 = self.b_val_nit_expo[self.energy_count] self.c2 = self.c_val_nit_expo[self.energy_count] self.a2 = self.a_val_nit_expo[self.energy_count] self.xk2 = self.Xk_val_nit_expo[self.energy_count] self.d2 = self.d_val_nit_expo[self.energy_count] self.b = round((self.b1*(log10(self.z2)-log10(self.zeq))+self.b2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.c = round((self.c1*(log10(self.z2)-log10(self.zeq))+self.c2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.a = round((self.a1*(log10(self.z2)-log10(self.zeq))+self.a2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.xk = round((self.xk1*(log10(self.z2)-log10(self.zeq))+self.xk2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.d = round((self.d1*(log10(self.z2)-log10(self.zeq))+self.d2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 10) self.buildup_ebf_func() elif self.z1 == 12 and self.z2 ==11: self.b1 = self.b_val_mag_expo[self.energy_count] self.c1 = self.c_val_mag_expo[self.energy_count] self.a1 = self.a_val_mag_expo[self.energy_count] self.xk1 = self.Xk_val_mag_expo[self.energy_count] self.d1 = self.d_val_mag_expo[self.energy_count] self.b2 = self.b_val_sod_expo[self.energy_count] self.c2 = self.c_val_sod_expo[self.energy_count] self.a2 = self.a_val_sod_expo[self.energy_count] self.xk2 = self.Xk_val_sod_expo[self.energy_count] self.d2 = self.d_val_sod_expo[self.energy_count] self.b = round((self.b1*(log10(self.z2)-log10(self.zeq))+self.b2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.c = round((self.c1*(log10(self.z2)-log10(self.zeq))+self.c2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.a = round((self.a1*(log10(self.z2)-log10(self.zeq))+self.a2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.xk = round((self.xk1*(log10(self.z2)-log10(self.zeq))+self.xk2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.d = round((self.d1*(log10(self.z2)-log10(self.zeq))+self.d2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 10) self.buildup_ebf_func() elif self.z1 == 13 and self.z2 ==12: self.b1 = self.b_val_alu_expo[self.energy_count] self.c1 = self.c_val_alu_expo[self.energy_count] self.a1 = self.a_val_alu_expo[self.energy_count] self.xk1 = self.Xk_val_alu_expo[self.energy_count] self.d1 = self.d_val_alu_expo[self.energy_count] self.b2 = self.b_val_mag_expo[self.energy_count] self.c2 = self.c_val_mag_expo[self.energy_count] self.a2 = self.a_val_mag_expo[self.energy_count] self.xk2 = self.Xk_val_mag_expo[self.energy_count] self.d2 = self.d_val_mag_expo[self.energy_count] self.b = round((self.b1*(log10(self.z2)-log10(self.zeq))+self.b2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.c = round((self.c1*(log10(self.z2)-log10(self.zeq))+self.c2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.a = round((self.a1*(log10(self.z2)-log10(self.zeq))+self.a2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.xk = round((self.xk1*(log10(self.z2)-log10(self.zeq))+self.xk2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.d = round((self.d1*(log10(self.z2)-log10(self.zeq))+self.d2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 10) self.buildup_ebf_func() elif self.z1 == 14 and self.z2 == 13: self.b1 = self.b_val_sil_expo[self.energy_count] self.c1 = self.c_val_sil_expo[self.energy_count] self.a1 = self.a_val_sil_expo[self.energy_count] self.xk1 = self.Xk_val_sil_expo[self.energy_count] self.d1 = self.d_val_sil_expo[self.energy_count] self.b2 = self.b_val_alu_expo[self.energy_count] self.c2 = self.c_val_alu_expo[self.energy_count] self.a2 = self.a_val_alu_expo[self.energy_count] self.xk2 = self.Xk_val_alu_expo[self.energy_count] self.d2 = self.d_val_alu_expo[self.energy_count] self.b = round((self.b1*(log10(self.z2)-log10(self.zeq))+self.b2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.c = round((self.c1*(log10(self.z2)-log10(self.zeq))+self.c2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.a = round((self.a1*(log10(self.z2)-log10(self.zeq))+self.a2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.xk = round((self.xk1*(log10(self.z2)-log10(self.zeq))+self.xk2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.d = round((self.d1*(log10(self.z2)-log10(self.zeq))+self.d2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 10) self.buildup_ebf_func() elif self.z1 == 15 and self.z2 ==14: self.b1 = self.b_val_pho_expo[self.energy_count] self.c1 = self.c_val_pho_expo[self.energy_count] self.a1 = self.a_val_pho_expo[self.energy_count] self.xk1 = self.Xk_val_pho_expo[self.energy_count] self.d1 = self.d_val_pho_expo[self.energy_count] self.b2 = self.b_val_sil_expo[self.energy_count] self.c2 = self.c_val_sil_expo[self.energy_count] self.a2 = self.a_val_sil_expo[self.energy_count] self.xk2 = self.Xk_val_sil_expo[self.energy_count] self.d2 = self.d_val_sil_expo[self.energy_count] self.b = round((self.b1*(log10(self.z2)-log10(self.zeq))+self.b2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.c = round((self.c1*(log10(self.z2)-log10(self.zeq))+self.c2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.a = round((self.a1*(log10(self.z2)-log10(self.zeq))+self.a2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.xk = round((self.xk1*(log10(self.z2)-log10(self.zeq))+self.xk2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.d = round((self.d1*(log10(self.z2)-log10(self.zeq))+self.d2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 10) self.buildup_ebf_func() elif self.z1 == 16 and self.z2 == 15: self.b1 = self.b_val_sul_expo[self.energy_count] self.c1 = self.c_val_sul_expo[self.energy_count] self.a1 = self.a_val_sul_expo[self.energy_count] self.xk1 = self.Xk_val_sul_expo[self.energy_count] self.d1 = self.d_val_sul_expo[self.energy_count] self.b2 = self.b_val_pho_expo[self.energy_count] self.c2 = self.c_val_pho_expo[self.energy_count] self.a2 = self.a_val_pho_expo[self.energy_count] self.xk2 = self.Xk_val_pho_expo[self.energy_count] self.d2 = self.d_val_pho_expo[self.energy_count] self.b = round((self.b1*(log10(self.z2)-log10(self.zeq))+self.b2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.c = round((self.c1*(log10(self.z2)-log10(self.zeq))+self.c2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.a = round((self.a1*(log10(self.z2)-log10(self.zeq))+self.a2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.xk = round((self.xk1*(log10(self.z2)-log10(self.zeq))+self.xk2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.d = round((self.d1*(log10(self.z2)-log10(self.zeq))+self.d2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 10) self.buildup_ebf_func() elif self.z1 == 18 and self.z2 == 16: self.b1 = self.b_val_arg_expo[self.energy_count] self.c1 = self.c_val_arg_expo[self.energy_count] self.a1 = self.a_val_arg_expo[self.energy_count] self.xk1 = self.Xk_val_arg_expo[self.energy_count] self.d1 = self.d_val_arg_expo[self.energy_count] self.b2 = self.b_val_sul_expo[self.energy_count] self.c2 = self.c_val_sul_expo[self.energy_count] self.a2 = self.a_val_sul_expo[self.energy_count] self.xk2 = self.Xk_val_sul_expo[self.energy_count] self.d2 = self.d_val_sul_expo[self.energy_count] self.b = round((self.b1*(log10(self.z2)-log10(self.zeq))+self.b2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.c = round((self.c1*(log10(self.z2)-log10(self.zeq))+self.c2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.a = round((self.a1*(log10(self.z2)-log10(self.zeq))+self.a2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.xk = round((self.xk1*(log10(self.z2)-log10(self.zeq))+self.xk2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.d = round((self.d1*(log10(self.z2)-log10(self.zeq))+self.d2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 10) self.buildup_ebf_func() elif self.z1 == 19 and self.z2 == 18: self.b1 = self.b_val_pot_expo[self.energy_count] self.c1 = self.c_val_pot_expo[self.energy_count] self.a1 = self.a_val_pot_expo[self.energy_count] self.xk1 = self.Xk_val_pot_expo[self.energy_count] self.d1 = self.d_val_pot_expo[self.energy_count] self.b2 = self.b_val_arg_expo[self.energy_count] self.c2 = self.c_val_arg_expo[self.energy_count] self.a2 = self.a_val_arg_expo[self.energy_count] self.xk2 = self.Xk_val_arg_expo[self.energy_count] self.d2 = self.d_val_arg_expo[self.energy_count] self.b = round((self.b1*(log10(self.z2)-log10(self.zeq))+self.b2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.c = round((self.c1*(log10(self.z2)-log10(self.zeq))+self.c2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.a = round((self.a1*(log10(self.z2)-log10(self.zeq))+self.a2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.xk = round((self.xk1*(log10(self.z2)-log10(self.zeq))+self.xk2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.d = round((self.d1*(log10(self.z2)-log10(self.zeq))+self.d2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 10) self.buildup_ebf_func() elif self.z1 == 20 and self.z2 == 19: self.b1 = self.b_val_cal_expo[self.energy_count] self.c1 = self.c_val_cal_expo[self.energy_count] self.a1 = self.a_val_cal_expo[self.energy_count] self.xk1 = self.Xk_val_cal_expo[self.energy_count] self.d1 = self.d_val_cal_expo[self.energy_count] self.b2 = self.b_val_pot_expo[self.energy_count] self.c2 = self.c_val_pot_expo[self.energy_count] self.a2 = self.a_val_pot_expo[self.energy_count] self.xk2 = self.Xk_val_pot_expo[self.energy_count] self.d2 = self.d_val_pot_expo[self.energy_count] self.b = round((self.b1*(log10(self.z2)-log10(self.zeq))+self.b2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.c = round((self.c1*(log10(self.z2)-log10(self.zeq))+self.c2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.a = round((self.a1*(log10(self.z2)-log10(self.zeq))+self.a2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.xk = round((self.xk1*(log10(self.z2)-log10(self.zeq))+self.xk2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.d = round((self.d1*(log10(self.z2)-log10(self.zeq))+self.d2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 10) self.buildup_ebf_func() elif self.z1 == 26 and self.z2 == 20: self.b1 = self.b_val_iron_expo[self.energy_count] self.c1 = self.c_val_iron_expo[self.energy_count] self.a1 = self.a_val_iron_expo[self.energy_count] self.xk1 = self.Xk_val_iron_expo[self.energy_count] self.d1 = self.d_val_iron_expo[self.energy_count] self.b2 = self.b_val_cal_expo[self.energy_count] self.c2 = self.c_val_cal_expo[self.energy_count] self.a2 = self.a_val_cal_expo[self.energy_count] self.xk2 = self.Xk_val_cal_expo[self.energy_count] self.d2 = self.d_val_cal_expo[self.energy_count] self.b = round((self.b1*(log10(self.z2)-log10(self.zeq))+self.b2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.c = round((self.c1*(log10(self.z2)-log10(self.zeq))+self.c2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.a = round((self.a1*(log10(self.z2)-log10(self.zeq))+self.a2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.xk = round((self.xk1*(log10(self.z2)-log10(self.zeq))+self.xk2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.d = round((self.d1*(log10(self.z2)-log10(self.zeq))+self.d2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 10) self.buildup_ebf_func() elif self.z1 == 29 and self.z2 == 26: self.b1 = self.b_val_cop_expo[self.energy_count] self.c1 = self.c_val_cop_expo[self.energy_count] self.a1 = self.a_val_cop_expo[self.energy_count] self.xk1 = self.Xk_val_cop_expo[self.energy_count] self.d1 = self.d_val_cop_expo[self.energy_count] self.b2 = self.b_val_iron_expo[self.energy_count] self.c2 = self.c_val_iron_expo[self.energy_count] self.a2 = self.a_val_iron_expo[self.energy_count] self.xk2 = self.Xk_val_iron_expo[self.energy_count] self.d2 = self.d_val_iron_expo[self.energy_count] self.b = round((self.b1*(log10(self.z2)-log10(self.zeq))+self.b2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.c = round((self.c1*(log10(self.z2)-log10(self.zeq))+self.c2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.a = round((self.a1*(log10(self.z2)-log10(self.zeq))+self.a2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.xk = round((self.xk1*(log10(self.z2)-log10(self.zeq))+self.xk2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.d = round((self.d1*(log10(self.z2)-log10(self.zeq))+self.d2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 10) self.buildup_ebf_func() elif self.z1 == 42 and self.z2 == 29: self.b1 = self.b_val_mol_expo[self.energy_count] self.c1 = self.c_val_mol_expo[self.energy_count] self.a1 = self.a_val_mol_expo[self.energy_count] self.xk1 = self.Xk_val_mol_expo[self.energy_count] self.d1 = self.d_val_mol_expo[self.energy_count] self.b2 = self.b_val_cop_expo[self.energy_count] self.c2 = self.c_val_cop_expo[self.energy_count] self.a2 = self.a_val_cop_expo[self.energy_count] self.xk2 = self.Xk_val_cop_expo[self.energy_count] self.d2 = self.d_val_cop_expo[self.energy_count] self.b = round((self.b1*(log10(self.z2)-log10(self.zeq))+self.b2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.c = round((self.c1*(log10(self.z2)-log10(self.zeq))+self.c2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.a = round((self.a1*(log10(self.z2)-log10(self.zeq))+self.a2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.xk = round((self.xk1*(log10(self.z2)-log10(self.zeq))+self.xk2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.d = round((self.d1*(log10(self.z2)-log10(self.zeq))+self.d2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 10) self.buildup_ebf_func() elif self.z1 == 50 and self.z2 == 42: self.b1 = self.b_val_tin_expo[self.energy_count] self.c1 = self.c_val_tin_expo[self.energy_count] self.a1 = self.a_val_tin_expo[self.energy_count] self.xk1 = self.Xk_val_tin_expo[self.energy_count] self.d1 = self.d_val_tin_expo[self.energy_count] self.b2 = self.b_val_mol_expo[self.energy_count] self.c2 = self.c_val_mol_expo[self.energy_count] self.a2 = self.a_val_mol_expo[self.energy_count] self.xk2 = self.Xk_val_mol_expo[self.energy_count] self.d2 = self.d_val_mol_expo[self.energy_count] self.b = round((self.b1*(log10(self.z2)-log10(self.zeq))+self.b2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.c = round((self.c1*(log10(self.z2)-log10(self.zeq))+self.c2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.a = round((self.a1*(log10(self.z2)-log10(self.zeq))+self.a2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.xk = round((self.xk1*(log10(self.z2)-log10(self.zeq))+self.xk2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.d = round((self.d1*(log10(self.z2)-log10(self.zeq))+self.d2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 10) self.buildup_ebf_func() elif self.z1 == 57 and self.z2 == 50: self.b1 = self.b_val_lan_expo[self.energy_count] self.c1 = self.c_val_lan_expo[self.energy_count] self.a1 = self.a_val_lan_expo[self.energy_count] self.xk1 = self.Xk_val_lan_expo[self.energy_count] self.d1 = self.d_val_lan_expo[self.energy_count] self.b2 = self.b_val_tin_expo[self.energy_count] self.c2 = self.c_val_tin_expo[self.energy_count] self.a2 = self.a_val_tin_expo[self.energy_count] self.xk2 = self.Xk_val_tin_expo[self.energy_count] self.d2 = self.d_val_tin_expo[self.energy_count] self.b = round((self.b1*(log10(self.z2)-log10(self.zeq))+self.b2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.c = round((self.c1*(log10(self.z2)-log10(self.zeq))+self.c2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.a = round((self.a1*(log10(self.z2)-log10(self.zeq))+self.a2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.xk = round((self.xk1*(log10(self.z2)-log10(self.zeq))+self.xk2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.d = round((self.d1*(log10(self.z2)-log10(self.zeq))+self.d2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 10) self.buildup_ebf_func() elif self.z1 == 64 and self.z2 == 57: self.b1 = self.b_val_gad_expo[self.energy_count] self.c1 = self.c_val_gad_expo[self.energy_count] self.a1 = self.a_val_gad_expo[self.energy_count] self.xk1 = self.Xk_val_gad_expo[self.energy_count] self.d1 = self.d_val_gad_expo[self.energy_count] self.b2 = self.b_val_lan_expo[self.energy_count] self.c2 = self.c_val_lan_expo[self.energy_count] self.a2 = self.a_val_lan_expo[self.energy_count] self.xk2 = self.Xk_val_lan_expo[self.energy_count] self.d2 = self.d_val_lan_expo[self.energy_count] self.b = round((self.b1*(log10(self.z2)-log10(self.zeq))+self.b2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.c = round((self.c1*(log10(self.z2)-log10(self.zeq))+self.c2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.a = round((self.a1*(log10(self.z2)-log10(self.zeq))+self.a2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.xk = round((self.xk1*(log10(self.z2)-log10(self.zeq))+self.xk2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.d = round((self.d1*(log10(self.z2)-log10(self.zeq))+self.d2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 10) self.buildup_ebf_func() elif self.z1 == 74 and self.z2 == 64: self.b1 = self.b_val_tun_expo[self.energy_count] self.c1 = self.c_val_tun_expo[self.energy_count] self.a1 = self.a_val_tun_expo[self.energy_count] self.xk1 = self.Xk_val_tun_expo[self.energy_count] self.d1 = self.d_val_tun_expo[self.energy_count] self.b2 = self.b_val_gad_expo[self.energy_count] self.c2 = self.c_val_gad_expo[self.energy_count] self.a2 = self.a_val_gad_expo[self.energy_count] self.xk2 = self.Xk_val_gad_expo[self.energy_count] self.d2 = self.d_val_gad_expo[self.energy_count] self.b = round((self.b1*(log10(self.z2)-log10(self.zeq))+self.b2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.c = round((self.c1*(log10(self.z2)-log10(self.zeq))+self.c2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.a = round((self.a1*(log10(self.z2)-log10(self.zeq))+self.a2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.xk = round((self.xk1*(log10(self.z2)-log10(self.zeq))+self.xk2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 6) self.d = round((self.d1*(log10(self.z2)-log10(self.zeq))+self.d2*(log10(self.zeq)-log10(self.z1)))/(log10(self.z2)-log10(self.z1)), 10) self.buildup_ebf_func() elif self.z1 == 82 and self.z2 == 74: self.b1 = self.b_val_lead_expo[self.energy_count] self.c1 = self.c_val_lead_expo[self.energy_count] self.a1 = self.a_val_lead_expo[self.energy_count] self.xk1 = self.Xk_val_lead_expo[self.energy_count] self.d1 = self.d_val_lead_expo[self.energy_count] self.b2 = self.b_val_tun_expo[self.energy_count] self.c2 = self.c_val_tun_expo[self.energy_count] self.a2
import collections import itertools import json from pathlib import Path import re import sqlite3 import string import attr import nltk import numpy as np def clamp(value, abs_max): value = max(-abs_max, value) value = min(abs_max, value) return value def to_dict_with_sorted_values(d, key=None): return {k: sorted(v, key=key) for k, v in d.items()} @attr.s class SpiderItem: text = attr.ib() code = attr.ib() schema = attr.ib() orig = attr.ib() orig_schema = attr.ib() @attr.s class Column: id = attr.ib() table = attr.ib() name = attr.ib() unsplit_name = attr.ib() orig_name = attr.ib() type = attr.ib() foreign_key_for = attr.ib(default=None) @attr.s class Table: id = attr.ib() name = attr.ib() unsplit_name = attr.ib() orig_name = attr.ib() columns = attr.ib(factory=list) primary_keys = attr.ib(factory=list) @attr.s class Schema: db_id = attr.ib() tables = attr.ib() columns = attr.ib() foreign_key_graph = attr.ib() orig = attr.ib() connection = attr.ib(default=None) @attr.s class PreprocessedSchema: column_names = attr.ib(factory=list) table_names = attr.ib(factory=list) table_bounds = attr.ib(factory=list) column_to_table = attr.ib(factory=dict) table_to_columns = attr.ib(factory=dict) foreign_keys = attr.ib(factory=dict) foreign_keys_tables = attr.ib(factory=lambda: collections.defaultdict(set)) primary_keys = attr.ib(factory=list) STOPWORDS = set(nltk.corpus.stopwords.words("english")) PUNKS = set(a for a in string.punctuation) class EncPreproc: # def __init__(self) -> None: def __init__( self, tables_file, dataset_path, include_table_name_in_column, fix_issue_16_primary_keys, qq_max_dist, cc_max_dist, tt_max_dist, ): self._tables_file = tables_file self._dataset_path = dataset_path self.include_table_name_in_column = include_table_name_in_column self.fix_issue_16_primary_keys = fix_issue_16_primary_keys self.texts = collections.defaultdict(list) self.counted_db_ids = set() self.preprocessed_schemas = {} self.qq_max_dist = qq_max_dist self.cc_max_dist = cc_max_dist self.tt_max_dist = tt_max_dist self.relation_ids = {} def add_relation(name): self.relation_ids[name] = len(self.relation_ids) def add_rel_dist(name, max_dist): for i in range(-max_dist, max_dist + 1): add_relation((name, i)) add_rel_dist("qq_dist", qq_max_dist) add_rel_dist("cc_dist", cc_max_dist) add_rel_dist("tt_dist", tt_max_dist) rel_names = [ "qc_default", "qt_default", "cq_default", "cc_default", "cc_foreign_key_forward", "cc_foreign_key_backward", "cc_table_match", "ct_default", "ct_foreign_key", "ct_primary_key", "ct_table_match", "ct_any_table", "tq_default", "tc_default", "tc_primary_key", "tc_table_match", "tc_any_table", "tc_foreign_key", "tt_default", "tt_foreign_key_forward", "tt_foreign_key_backward", "tt_foreign_key_both", "qcCEM", "cqCEM", "qtTEM", "tqTEM", "qcCPM", "cqCPM", "qtTPM", "tqTPM", "qcNUMBER", "cqNUMBER", "qcTIME", "cqTIME", "qcCELLMATCH", "cqCELLMATCH", ] for rel in rel_names: add_relation(rel) self.schemas = None self.eval_foreign_key_maps = None print("before load_trees") self.schemas, self.eval_foreign_key_maps = self.load_tables([self._tables_file]) print("before connecting") for db_id, schema in self.schemas.items(): sqlite_path = Path(self._dataset_path) / db_id / f"{db_id}.sqlite" source: sqlite3.Connection with sqlite3.connect(sqlite_path) as source: dest = sqlite3.connect(":memory:") dest.row_factory = sqlite3.Row source.backup(dest) schema.connection = dest def get_desc(self, tokenized_utterance, db_id): item = SpiderItem( text=[x.text for x in tokenized_utterance[1:-1]], code=None, schema=self.schemas[db_id], orig=None, orig_schema=self.schemas[db_id].orig, ) return self.preprocess_item(item, "train") def compute_relations( self, desc, enc_length, q_enc_length, c_enc_length, c_boundaries, t_boundaries ): sc_link = desc.get("sc_link", {"q_col_match": {}, "q_tab_match": {}}) cv_link = desc.get("cv_link", {"num_date_match": {}, "cell_match": {}}) # Catalogue which things are where loc_types = {} for i in range(q_enc_length): loc_types[i] = ("question",) c_base = q_enc_length for c_id, (c_start, c_end) in enumerate(zip(c_boundaries, c_boundaries[1:])): for i in range(c_start + c_base, c_end + c_base): loc_types[i] = ("column", c_id) t_base = q_enc_length + c_enc_length for t_id, (t_start, t_end) in enumerate(zip(t_boundaries, t_boundaries[1:])): for i in range(t_start + t_base, t_end + t_base): loc_types[i] = ("table", t_id) relations = np.empty((enc_length, enc_length), dtype=np.int64) for i, j in itertools.product(range(enc_length), repeat=2): def set_relation(name): relations[i, j] = self.relation_ids[name] i_type, j_type = loc_types[i], loc_types[j] if i_type[0] == "question": if j_type[0] == "question": set_relation(("qq_dist", clamp(j - i, self.qq_max_dist))) elif j_type[0] == "column": # set_relation('qc_default') j_real = j - c_base if f"{i},{j_real}" in sc_link["q_col_match"]: set_relation("qc" + sc_link["q_col_match"][f"{i},{j_real}"]) elif f"{i},{j_real}" in cv_link["cell_match"]: set_relation("qc" + cv_link["cell_match"][f"{i},{j_real}"]) elif f"{i},{j_real}" in cv_link["num_date_match"]: set_relation("qc" + cv_link["num_date_match"][f"{i},{j_real}"]) else: set_relation("qc_default") elif j_type[0] == "table": j_real = j - t_base if f"{i},{j_real}" in sc_link["q_tab_match"]: set_relation("qt" + sc_link["q_tab_match"][f"{i},{j_real}"]) else: set_relation("qt_default") elif i_type[0] == "column": if j_type[0] == "question": i_real = i - c_base if f"{j},{i_real}" in sc_link["q_col_match"]: set_relation("cq" + sc_link["q_col_match"][f"{j},{i_real}"]) elif f"{j},{i_real}" in cv_link["cell_match"]: set_relation("cq" + cv_link["cell_match"][f"{j},{i_real}"]) elif f"{j},{i_real}" in cv_link["num_date_match"]: set_relation("cq" + cv_link["num_date_match"][f"{j},{i_real}"]) else: set_relation("cq_default") elif j_type[0] == "column": col1, col2 = i_type[1], j_type[1] if col1 == col2: set_relation(("cc_dist", clamp(j - i, self.cc_max_dist))) else: set_relation("cc_default") if desc["foreign_keys"].get(str(col1)) == col2: set_relation("cc_foreign_key_forward") if desc["foreign_keys"].get(str(col2)) == col1: set_relation("cc_foreign_key_backward") if ( desc["column_to_table"][str(col1)] == desc["column_to_table"][str(col2)] ): set_relation("cc_table_match") elif j_type[0] == "table": col, table = i_type[1], j_type[1] set_relation("ct_default") if self.match_foreign_key(desc, col, table): set_relation("ct_foreign_key") col_table = desc["column_to_table"][str(col)] if col_table == table: if col in desc["primary_keys"]: set_relation("ct_primary_key") else: set_relation("ct_table_match") elif col_table is None: set_relation("ct_any_table") elif i_type[0] == "table": if j_type[0] == "question": i_real = i - t_base if f"{j},{i_real}" in sc_link["q_tab_match"]: set_relation("tq" + sc_link["q_tab_match"][f"{j},{i_real}"]) else: set_relation("tq_default") elif j_type[0] == "column": table, col = i_type[1], j_type[1] set_relation("tc_default") if self.match_foreign_key(desc, col, table): set_relation("tc_foreign_key") col_table = desc["column_to_table"][str(col)] if col_table == table: if col in desc["primary_keys"]: set_relation("tc_primary_key") else: set_relation("tc_table_match") elif col_table is None: set_relation("tc_any_table") elif j_type[0] == "table": table1, table2 = i_type[1], j_type[1] if table1 == table2: set_relation(("tt_dist", clamp(j - i, self.tt_max_dist))) else: set_relation("tt_default") forward = table2 in desc["foreign_keys_tables"].get( str(table1), () ) backward = table1 in desc["foreign_keys_tables"].get( str(table2), () ) if forward and backward: set_relation("tt_foreign_key_both") elif forward: set_relation("tt_foreign_key_forward") elif backward: set_relation("tt_foreign_key_backward") return relations @classmethod def match_foreign_key(cls, desc, col, table): foreign_key_for = desc["foreign_keys"].get(str(col)) if foreign_key_for is None: return False foreign_table = desc["column_to_table"][str(foreign_key_for)] return desc["column_to_table"][str(col)] == foreign_table def validate_item(self, item, section): return True, None def preprocess_item(self, item, validation_info): question, question_for_copying = item.text, item.text question = [x.replace("Ġ", "") for x in question] question_for_copying = [x.replace("Ġ", "") for x in question_for_copying] preproc_schema = self._preprocess_schema(item.schema) assert preproc_schema.column_names[0][0].startswith("<type:") column_names_without_types = [col[1:] for col in preproc_schema.column_names] sc_link = self.compute_schema_linking( question, column_names_without_types, preproc_schema.table_names ) # print(sc_link) cv_link = self.compute_cell_value_linking(question, item.schema) # if cv_link['cell_match']: # print(question) return { "raw_question": question, "question": question, "question_for_copying": question_for_copying, "db_id": item.schema.db_id, "sc_link": sc_link, "cv_link": cv_link, "columns": preproc_schema.column_names, "tables": preproc_schema.table_names, "table_bounds": preproc_schema.table_bounds, "column_to_table": preproc_schema.column_to_table, "table_to_columns": preproc_schema.table_to_columns, "foreign_keys": preproc_schema.foreign_keys, "foreign_keys_tables": preproc_schema.foreign_keys_tables, "primary_keys": preproc_schema.primary_keys, } def _preprocess_schema(self, schema): if schema.db_id in self.preprocessed_schemas: return self.preprocessed_schemas[schema.db_id] result = self.preprocess_schema_uncached( schema, self._tokenize, self.include_table_name_in_column, self.fix_issue_16_primary_keys, ) self.preprocessed_schemas[schema.db_id] = result return result def _tokenize(self, presplit, unsplit): return presplit def _tokenize_for_copying(self, presplit, unsplit): return presplit, presplit # schema linking, similar to IRNet @classmethod def compute_schema_linking(cls, question, column, table): def partial_match(x_list, y_list): x_str = " ".join(x_list) y_str = " ".join(y_list) if x_str in STOPWORDS or x_str in PUNKS: return False if re.match(rf"\b{re.escape(x_str)}\b", y_str): assert x_str in y_str return True else: return False def exact_match(x_list, y_list): x_str = " ".join(x_list) y_str = " ".join(y_list) if x_str == y_str: return True else: return False q_col_match = dict() q_tab_match = dict() col_id2list = dict() for col_id, col_item in enumerate(column): if col_id == 0: continue col_id2list[col_id] = col_item tab_id2list = dict() for tab_id, tab_item in enumerate(table): tab_id2list[tab_id] = tab_item # 5-gram n = 5 while n > 0: for i in range(len(question) - n + 1): n_gram_list = question[i : i + n] n_gram = " ".join(n_gram_list) if len(n_gram.strip()) == 0: continue # exact match case for col_id in col_id2list: if exact_match(n_gram_list, col_id2list[col_id]): for q_id in range(i, i + n): q_col_match[f"{q_id},{col_id}"] = "CEM" for tab_id in tab_id2list: if exact_match(n_gram_list, tab_id2list[tab_id]): for q_id in range(i, i + n): q_tab_match[f"{q_id},{tab_id}"] = "TEM" # partial match case for col_id in col_id2list: if partial_match(n_gram_list, col_id2list[col_id]): for q_id in range(i, i + n): if f"{q_id},{col_id}" not in q_col_match: q_col_match[f"{q_id},{col_id}"] = "CPM" for tab_id in tab_id2list: if partial_match(n_gram_list, tab_id2list[tab_id]): for q_id in range(i, i + n): if f"{q_id},{tab_id}" not in q_tab_match: q_tab_match[f"{q_id},{tab_id}"] = "TPM" n -= 1 return {"q_col_match": q_col_match, "q_tab_match": q_tab_match} @classmethod def load_tables(cls, paths): schemas = {} eval_foreign_key_maps = {} for path in paths: schema_dicts = json.load(open(path)) for schema_dict in schema_dicts: tables = tuple( Table( id=i, name=name.split(), unsplit_name=name, orig_name=orig_name, ) for i, (name, orig_name) in enumerate( zip( schema_dict["table_names"], schema_dict["table_names_original"], ) ) ) columns = tuple( Column( id=i, table=tables[table_id] if table_id >= 0 else None, name=col_name.split(), unsplit_name=col_name, orig_name=orig_col_name, type=col_type, ) for i, ( (table_id, col_name), (_, orig_col_name), col_type, ) in enumerate( zip( schema_dict["column_names"], schema_dict["column_names_original"], schema_dict["column_types"], ) ) ) # Link columns to tables for column in columns: if column.table: column.table.columns.append(column) for column_id in schema_dict["primary_keys"]: # Register primary keys column = columns[column_id] column.table.primary_keys.append(column) foreign_key_graph = None for source_column_id, dest_column_id in schema_dict["foreign_keys"]: # Register foreign keys source_column = columns[source_column_id] dest_column = columns[dest_column_id] source_column.foreign_key_for = dest_column db_id = schema_dict["db_id"] assert db_id not in schemas schemas[db_id] = Schema( db_id, tables, columns, foreign_key_graph, schema_dict ) eval_foreign_key_maps[db_id] = cls.build_foreign_key_map(schema_dict) for db_id, schema_el in schemas.items(): san2orig = {} orig2san = {} for table_el in schema_el.tables: sanitized_name = f"{'_'.join(table_el.name)}".lower() orig_name = f"{table_el.orig_name}".lower() san2orig[sanitized_name] = orig_name orig2san[orig_name] = sanitized_name for col_el in table_el.columns: sanitized_name = ( f"{'_'.join(col_el.table.name)}.{'_'.join(col_el.name)}".lower() ) orig_name = f"{col_el.table.orig_name}.{col_el.orig_name}".lower() san2orig[sanitized_name] = orig_name orig2san[orig_name] = sanitized_name schema_el.san2orig = san2orig
#!/usr/bin/python import time import smbus # =========================================================================== # ST_VL6180x ToF ranger Class # # Originally written by <NAME> # References Arduino library by <NAME> of SparkFun: # https://github.com/sparkfun/ToF_Range_Finder-VL6180_Library\ # =========================================================================== class VL6180X: i2c = None __VL6180X_IDENTIFICATION_MODEL_ID = 0x0000 __VL6180X_IDENTIFICATION_MODEL_REV_MAJOR = 0x0001 __VL6180X_IDENTIFICATION_MODEL_REV_MINOR = 0x0002 __VL6180X_IDENTIFICATION_MODULE_REV_MAJOR = 0x0003 __VL6180X_IDENTIFICATION_MODULE_REV_MINOR = 0x0004 __VL6180X_IDENTIFICATION_DATE = 0x0006 # 16bit value __VL6180X_IDENTIFICATION_TIME = 0x0008 # 16bit value __VL6180X_SYSTEM_MODE_GPIO0 = 0x0010 __VL6180X_SYSTEM_MODE_GPIO1 = 0x0011 __VL6180X_SYSTEM_HISTORY_CTRL = 0x0012 __VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO = 0x0014 __VL6180X_SYSTEM_INTERRUPT_CLEAR = 0x0015 __VL6180X_SYSTEM_FRESH_OUT_OF_RESET = 0x0016 __VL6180X_SYSTEM_GROUPED_PARAMETER_HOLD = 0x0017 __VL6180X_SYSRANGE_START = 0x0018 __VL6180X_SYSRANGE_THRESH_HIGH = 0x0019 __VL6180X_SYSRANGE_THRESH_LOW = 0x001A __VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD = 0x001B __VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME = 0x001C __VL6180X_SYSRANGE_CROSSTALK_COMPENSATION_RATE = 0x001E __VL6180X_SYSRANGE_CROSSTALK_VALID_HEIGHT = 0x0021 __VL6180X_SYSRANGE_EARLY_CONVERGENCE_ESTIMATE = 0x0022 __VL6180X_SYSRANGE_PART_TO_PART_RANGE_OFFSET = 0x0024 __VL6180X_SYSRANGE_RANGE_IGNORE_VALID_HEIGHT = 0x0025 __VL6180X_SYSRANGE_RANGE_IGNORE_THRESHOLD = 0x0026 __VL6180X_SYSRANGE_MAX_AMBIENT_LEVEL_MULT = 0x002C __VL6180X_SYSRANGE_RANGE_CHECK_ENABLES = 0x002D __VL6180X_SYSRANGE_VHV_RECALIBRATE = 0x002E __VL6180X_SYSRANGE_VHV_REPEAT_RATE = 0x0031 __VL6180X_SYSALS_START = 0x0038 __VL6180X_SYSALS_THRESH_HIGH = 0x003A __VL6180X_SYSALS_THRESH_LOW = 0x003C __VL6180X_SYSALS_INTERMEASUREMENT_PERIOD = 0x003E __VL6180X_SYSALS_ANALOGUE_GAIN = 0x003F __VL6180X_SYSALS_INTEGRATION_PERIOD = 0x0040 __VL6180X_RESULT_RANGE_STATUS = 0x004D __VL6180X_RESULT_ALS_STATUS = 0x004E __VL6180X_RESULT_INTERRUPT_STATUS_GPIO = 0x004F __VL6180X_RESULT_ALS_VAL = 0x0050 __VL6180X_RESULT_HISTORY_BUFFER = 0x0052 __VL6180X_RESULT_RANGE_VAL = 0x0062 __VL6180X_RESULT_RANGE_RAW = 0x0064 __VL6180X_RESULT_RANGE_RETURN_RATE = 0x0066 __VL6180X_RESULT_RANGE_REFERENCE_RATE = 0x0068 __VL6180X_RESULT_RANGE_RETURN_SIGNAL_COUNT = 0x006C __VL6180X_RESULT_RANGE_REFERENCE_SIGNAL_COUNT = 0x0070 __VL6180X_RESULT_RANGE_RETURN_AMB_COUNT = 0x0074 __VL6180X_RESULT_RANGE_REFERENCE_AMB_COUNT = 0x0078 __VL6180X_RESULT_RANGE_RETURN_CONV_TIME = 0x007C __VL6180X_RESULT_RANGE_REFERENCE_CONV_TIME = 0x0080 __VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD = 0x010A __VL6180X_FIRMWARE_BOOTUP = 0x0119 __VL6180X_FIRMWARE_RESULT_SCALER = 0x0120 __VL6180X_I2C_SLAVE_DEVICE_ADDRESS = 0x0212 __VL6180X_INTERLEAVED_MODE_ENABLE = 0x02A3 __ALS_GAIN_1 = 0x06 __ALS_GAIN_1_25 = 0x05 __ALS_GAIN_1_67 = 0x04 __ALS_GAIN_2_5 = 0x03 __ALS_GAIN_5 = 0x02 __ALS_GAIN_10 = 0x01 __ALS_GAIN_20 = 0x00 __ALS_GAIN_40 = 0x07 # Dictionaries with the valid ALS gain values # These simplify and clean the code (avoid abuse of if/elif/else clauses) ALS_GAIN_REG = { 1: __ALS_GAIN_1, 1.25: __ALS_GAIN_1_25, 1.67: __ALS_GAIN_1_67, 2.5: __ALS_GAIN_2_5, 5: __ALS_GAIN_5, 10: __ALS_GAIN_10, 20: __ALS_GAIN_20, 40: __ALS_GAIN_40 } ALS_GAIN_ACTUAL = { # Data sheet shows gain values as binary list 1: 1.01, # Nominal gain 1; actual gain 1.01 1.25: 1.28, # Nominal gain 1.25; actual gain 1.28 1.67: 1.72, # Nominal gain 1.67; actual gain 1.72 2.5: 2.60, # Nominal gain 2.5; actual gain 2.60 5: 5.21, # Nominal gain 5; actual gain 5.21 10: 10.32, # Nominal gain 10; actual gain 10.32 20: 20.00, # Nominal gain 20; actual gain 20 40: 40.00, # Nominal gain 40; actual gain 40 } # Range Error Codes class RangeErrorCodes: NO_ERROR = 0b0000 VCSEL_CONTINUITY_TEST = 0b0001 VCSEL_WATCHDOG_TEST = 0b0010 VCSEL_WATCHDOG = 0b0011 PLL1_LOCK = 0b0100 PLL2_LOCK = 0b0101 EARLY_CONVERGENCE_ESTIMATE = 0b0110 MAX_CONVERGENCE = 0b0111 NO_TARGET_IGNORE = 0b1000 MAX_SIGNAL_TO_NOISE_RATIO = 0b1011 RAW_RANGING_ALGO_UNDERFLOW = 0b1100 RAW_RANGING_ALGO_OVERFLOW = 0b1101 RANGING_ALGO_UNDERFLOW = 0b1110 RANGING_ALGO_OVERFLOW = 0b1111 _RANGE_ERROR_CODES_TO_STRINGS = { 0b0000: "No error", 0b0001: "VCSEL Continuity Test", 0b0010: "VCSEL Watchtog Test", 0b0011: "VCSEL Watchdog", 0b0100: "PLL1 Lock", 0b0101: "PLL2 Lock", 0b0110: "Early Convergence Estimate", 0b0111: "Max Convergence Estimate", 0b1000: "No Target Ignore", 0b1001: "Not used", 0b1010: "Not used", 0b1011: "Max Signal to Noise Ratio", 0b1100: "Raw Ranging Underflow", 0b1101: "Raw Ranging Overflow", 0b1110: "Ranging Algo Underflow", 0b1111: "Ranging Algo Overflow" } def __init__(self, address=0x29, debug=False): # Depending on if you have an old or a new Raspberry Pi, you # may need to change the I2C bus. Older Pis use SMBus 0, # whereas new Pis use SMBus 1. If you see an error like: # 'Error accessing 0x29: Check your I2C address ' # change the SMBus number in the initializer below! # setup i2c bus and SFR address self.i2c = smbus.SMBus(1) self.address = address self.debug = debug # Module identification self.idModel = 0x00 self.idModelRevMajor = 0x00 self.idModelRevMinor = 0x00 self.idModuleRevMajor = 0x00 self.idModuleRevMinor = 0x00 self.idDate = 0x00 self.idTime = 0x00 if self.get_register(self.__VL6180X_SYSTEM_FRESH_OUT_OF_RESET) == 1: print("ToF sensor is ready.") self.ready = True else: print("ToF sensor reset failure.") self.ready = False # Required by datasheet # http://www.st.com/st-web-ui/static/active/en/resource/technical/document/application_note/DM00122600.pdf self.set_register(0x0207, 0x01) self.set_register(0x0208, 0x01) self.set_register(0x0096, 0x00) self.set_register(0x0097, 0xfd) self.set_register(0x00e3, 0x00) self.set_register(0x00e4, 0x04) self.set_register(0x00e5, 0x02) self.set_register(0x00e6, 0x01) self.set_register(0x00e7, 0x03) self.set_register(0x00f5, 0x02) self.set_register(0x00d9, 0x05) self.set_register(0x00db, 0xce) self.set_register(0x00dc, 0x03) self.set_register(0x00dd, 0xf8) self.set_register(0x009f, 0x00) self.set_register(0x00a3, 0x3c) self.set_register(0x00b7, 0x00) self.set_register(0x00bb, 0x3c) self.set_register(0x00b2, 0x09) self.set_register(0x00ca, 0x09) self.set_register(0x0198, 0x01) self.set_register(0x01b0, 0x17) self.set_register(0x01ad, 0x00) self.set_register(0x00ff, 0x05) self.set_register(0x0100, 0x05) self.set_register(0x0199, 0x05) self.set_register(0x01a6, 0x1b) self.set_register(0x01ac, 0x3e) self.set_register(0x01a7, 0x1f) self.set_register(0x0030, 0x00) if self.debug: print("Register settings:") print("0x0207 - {:x}".format(self.get_register(0x0207))) print("0x0208 - {:x}".format(self.get_register(0x0208))) print("0x0096 - {:x}".format(self.get_register(0x0096))) print("0x0097 - {:x}".format(self.get_register(0x0097))) print("0x00e3 - {:x}".format(self.get_register(0x00e3))) print("0x00e4 - {:x}".format(self.get_register(0x00e4))) print("0x00e5 - {:x}".format(self.get_register(0x00e5))) print("0x00e6 - {:x}".format(self.get_register(0x00e6))) print("0x00e7 - {:x}".format(self.get_register(0x00e7))) print("0x00f5 - {:x}".format(self.get_register(0x00f5))) print("0x00d9 - {:x}".format(self.get_register(0x00d9))) print("0x00db - {:x}".format(self.get_register(0x00db))) print("0x00dc - {:x}".format(self.get_register(0x00dc))) print("0x00dd - {:x}".format(self.get_register(0x00dd))) print("0x009f - {:x}".format(self.get_register(0x009f))) print("0x00a3 - {:x}".format(self.get_register(0x00a3))) print("0x00b7 - {:x}".format(self.get_register(0x00b7))) print("0x00bb - {:x}".format(self.get_register(0x00bb))) print("0x00b2 - {:x}".format(self.get_register(0x00b2))) print("0x00ca - {:x}".format(self.get_register(0x00ca))) print("0x0198 - {:x}".format(self.get_register(0x0198))) print("0x01b0 - {:x}".format(self.get_register(0x01b0))) print("0x01ad - {:x}".format(self.get_register(0x01ad))) print("0x00ff - {:x}".format(self.get_register(0x00ff))) print("0x0100 - {:x}".format(self.get_register(0x0100))) print("0x0199 - {:x}".format(self.get_register(0x0199))) print("0x01ac - {:x}".format(self.get_register(0x01ac))) print("0x01a6 - {:x}".format(self.get_register(0x01a6))) print("0x01a7 - {:x}".format(self.get_register(0x01a7))) print("0x0030 - {:x}".format(self.get_register(0x0030))) def default_settings(self): # Recommended settings from datasheet # http://www.st.com/st-web-ui/static/active/en/resource/technical/document/application_note/DM00122600.pdf # Set GPIO1 high when sample complete self.set_register(self.__VL6180X_SYSTEM_MODE_GPIO1, 0x10) # Set Avg sample period self.set_register(self.__VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD, 0x30) # Set the ALS gain self.set_register(self.__VL6180X_SYSALS_ANALOGUE_GAIN, 0x46) # Set auto calibration period (Max = 255)/(OFF = 0) self.set_register(self.__VL6180X_SYSRANGE_VHV_REPEAT_RATE, 0xFF) # Set ALS integration time to 100ms self.set_register(self.__VL6180X_SYSALS_INTEGRATION_PERIOD, 0x63) # perform a single temperature calibration self.set_register(self.__VL6180X_SYSRANGE_VHV_RECALIBRATE, 0x01) # Optional settings from datasheet # http://www.st.com/st-web-ui/static/active/en/resource/technical/document/application_note/DM00122600.pdf # Set default ranging inter-measurement period to 100ms self.set_register(self.__VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD, 0x09) # Set default ALS inter-measurement period to 100ms self.set_register(self.__VL6180X_SYSALS_INTERMEASUREMENT_PERIOD, 0x31) # Configures interrupt on 'New Sample Ready threshold event' self.set_register(self.__VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO, 0x24) # Additional settings defaults from community self.set_register(self.__VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME, 0x32) self.set_register( self.__VL6180X_SYSRANGE_RANGE_CHECK_ENABLES, 0x10 | 0x01) self.set_register_16bit( self.__VL6180X_SYSRANGE_EARLY_CONVERGENCE_ESTIMATE, 0x7B) self.set_register_16bit(self.__VL6180X_SYSALS_INTEGRATION_PERIOD, 0x64) self.set_register(self.__VL6180X_SYSALS_ANALOGUE_GAIN, 0x40) self.set_register(self.__VL6180X_FIRMWARE_RESULT_SCALER, 0x01) if self.debug: print("Default settings:") print("SYSTEM_MODE_GPIO1 - {:x}".format(self.get_register(self.__VL6180X_SYSTEM_MODE_GPIO1))) print("READOUT_AVERAGING_SAMPLE_PERIOD - %x", self.get_register( self.__VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD)) print("SYSALS_ANALOGUE_GAIN - %x", self.get_register(self.__VL6180X_SYSALS_ANALOGUE_GAIN)) print("SYSRANGE_VHV_REPEAT_RATE - %x", self.get_register(self.__VL6180X_SYSRANGE_VHV_REPEAT_RATE)) print("SYSALS_INTEGRATION_PERIOD - %x", self.get_register(self.__VL6180X_SYSALS_INTEGRATION_PERIOD)) print("SYSRANGE_VHV_RECALIBRATE - %x", self.get_register(self.__VL6180X_SYSRANGE_VHV_RECALIBRATE)) print("SYSRANGE_INTERMEASUREMENT_PERIOD - %x", self.get_register( self.__VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD)) print("SYSALS_INTERMEASUREMENT_PERIOD - %x", self.get_register( self.__VL6180X_SYSALS_INTERMEASUREMENT_PERIOD)) print("SYSTEM_INTERRUPT_CONFIG_GPIO - %x", self.get_register( self.__VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO)) print("SYSRANGE_MAX_CONVERGENCE_TIME - %x", self.get_register( self.__VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME)) print("SYSRANGE_RANGE_CHECK_ENABLES - %x", self.get_register(self.__VL6180X_SYSRANGE_RANGE_CHECK_ENABLES)) print("SYSRANGE_EARLY_CONVERGENCE_ESTIMATE - %x", self.get_register_16bit( self.__VL6180X_SYSRANGE_EARLY_CONVERGENCE_ESTIMATE)) print("SYSALS_INTEGRATION_PERIOD - %x", self.get_register_16bit( self.__VL6180X_SYSALS_INTEGRATION_PERIOD)) print("SYSALS_ANALOGUE_GAIN - %x", self.get_register(self.__VL6180X_SYSALS_ANALOGUE_GAIN)) print("FIRMWARE_RESULT_SCALER - %x", self.get_register(self.__VL6180X_FIRMWARE_RESULT_SCALER)) def get_identification(self): self.idModel = self.get_register( self.__VL6180X_IDENTIFICATION_MODEL_ID) self.idModelRevMajor = self.get_register( self.__VL6180X_IDENTIFICATION_MODEL_REV_MAJOR) self.idModelRevMinor = self.get_register( self.__VL6180X_IDENTIFICATION_MODEL_REV_MINOR) self.idModuleRevMajor = self.get_register( self.__VL6180X_IDENTIFICATION_MODULE_REV_MAJOR) self.idModuleRevMinor = self.get_register( self.__VL6180X_IDENTIFICATION_MODULE_REV_MINOR) self.idDate = self.get_register_16bit( self.__VL6180X_IDENTIFICATION_DATE) self.idTime = self.get_register_16bit( self.__VL6180X_IDENTIFICATION_TIME) def change_address(self, old_address, new_address): # NOTICE: IT APPEARS THAT CHANGING THE ADDRESS IS NOT STORED IN NON- # VOLATILE MEMORY POWER CYCLING THE DEVICE REVERTS ADDRESS BACK TO 0X29 if old_address == new_address: return old_address if new_address > 127: return old_address self.set_register(self.__VL6180X_I2C_SLAVE_DEVICE_ADDRESS, new_address) self.address = new_address return self.get_register(self.__VL6180X_I2C_SLAVE_DEVICE_ADDRESS) def get_distance(self): # Start Single shot mode self.set_register(self.__VL6180X_SYSRANGE_START, 0x01) time.sleep(0.010) if self.debug: print("Range status: %x", self.get_register(self.__VL6180X_RESULT_RANGE_STATUS) & 0xF1) distance = self.get_register(self.__VL6180X_RESULT_RANGE_VAL) self.set_register(self.__VL6180X_SYSTEM_INTERRUPT_CLEAR, 0x07) return distance def get_distance_with_error_checks(self) -> (int, int): # Check whether the device is ready while bool(self.get_register(self.__VL6180X_RESULT_RANGE_STATUS) & 0x01) is False: time.sleep(0.001) # sleep one millisecond and try again # Start Single shot mode self.set_register(self.__VL6180X_SYSRANGE_START, 0x01) # Wait for range measurement to complete time.sleep(0.010) # measurement will not be finished that fast, so sleep a little while bool(self.get_register(self.__VL6180X_RESULT_INTERRUPT_STATUS_GPIO) & 0x04) is False: time.sleep(0.001) # sleep one millisecond and try again # Read range result distance = self.get_register(self.__VL6180X_RESULT_RANGE_VAL) # Read status code status = self.get_range_status() # Clear interrupt flag self.set_register(self.__VL6180X_SYSTEM_INTERRUPT_CLEAR, 0x07) return distance, status def get_ambient_light(self, als_gain): # First load in Gain we are using, do it every time in case someone # changes it on us. # Note: Upper nibble should be set to 0x4 i.e. for ALS gain # of 1.0 write 0x46 # Set the ALS gain, defaults to 20. # If gain is in the dictionary (defined in init()) it returns the value # of the constant otherwise it returns the value for gain 20. # This saves a lot of if/elif/else code! if als_gain not in self.ALS_GAIN_ACTUAL: print("Invalid gain setting: %d. Setting to 20." % als_gain) als_gain_actual = self.ALS_GAIN_ACTUAL.setdefault(als_gain, 20) self.set_register( self.__VL6180X_SYSALS_ANALOGUE_GAIN, (0x40 | self.ALS_GAIN_REG.setdefault(als_gain, self.__ALS_GAIN_20))) # Start ALS Measurement self.set_register(self.__VL6180X_SYSALS_START, 0x01) time.sleep(0.100) # give it time... # Retrieve the Raw ALS value from the sensor if self.debug: print("ALS status: %x", self.get_register(self.__VL6180X_RESULT_ALS_STATUS) & 0xF1) als_raw = self.get_register_16bit(self.__VL6180X_RESULT_ALS_VAL) self.set_register(self.__VL6180X_SYSTEM_INTERRUPT_CLEAR, 0x07) # Get Integration Period for calculation, we do this every time in case # someone changes it
# Copyright INRIM (https://www.inrim.eu) # See LICENSE file for full licensing details. import sys from typing import Optional from fastapi import FastAPI, Request, Header, HTTPException, Depends, Form from fastapi.responses import RedirectResponse, JSONResponse from .ContentService import ContentService from .main.base.base_class import BaseClass, PluginBase from .main.base.utils_for_service import requote_uri from starlette.status import HTTP_302_FOUND, HTTP_303_SEE_OTHER from fastapi.concurrency import run_in_threadpool import httpx import logging import ujson import re logger = logging.getLogger(__name__) class Gateway(PluginBase): plugins = [] def __init_subclass__(cls, **kwargs): if cls not in cls.plugins: cls.plugins.append(cls()) class GatewayBase(Gateway): @classmethod def create(cls, request: Request, settings, templates): self = GatewayBase() self.init(request, settings, templates) return self def init(self, request: Request, settings, templates): self.request = request self.remote_req_id = "" self.name_allowed = re.compile("^[A-Za-z0-9._~-]*$") self.local_settings = settings self.templates = templates self.session = {} self.token = "" self.is_api = False self.params = self.request.query_params.__dict__['_dict'].copy() self.headers = self.deserialize_header_list() self.cookies = self.request.cookies self.init_headers_and_token() def clean_form(self, form_data): # logger.info(f"before") dat = {} dat = ujson.loads(form_data['formObj']) for k, v in form_data.items(): if not k == 'formObj': dat[k] = v return dat def init_headers_and_token(self): # logger.info(f"before") dat = {} if 'content-length' in self.headers: self.headers.pop("content-length") if "Content-Type" in self.headers: self.headers.pop('Content-Type') if "Cache-control" in self.headers: self.headers.pop('Cache-control') if "cache-control" in self.headers: self.headers.pop('cache-control') if "content-type" in self.headers: self.headers.pop('content-type') if "accept" in self.headers: self.headers.pop('accept') if "token" in self.params: self.token = self.params.get("token", "") base_url = str(self.request.base_url)[:-1] self.headers.update({ "Content-Type": "application/json", "accept": "application/json", "app_code": self.local_settings.app_code, "referer": requote_uri(f"{base_url}{self.request.url.path}"), "base_url_ref": f"{base_url}", "req_id": self.request.headers.get("req_id", "") }) if not self.token: if self.request.headers.get("authtoken"): self.token = self.request.headers.get("authtoken") elif self.request.headers.get("apitoken"): self.token = self.request.headers.get("apitoken") self.is_api = True # TODO move in shibboleth Gateway if "x-remote-user" not in self.request.headers: self.headers['x-remote-user'] = self.request.headers.get('x-remote-user', "") logger.info(f"complete token: {self.token} is Api {self.is_api}") async def load_post_request_data(self): await self.get_session() submitted_data = {} content_service = ContentService.new(gateway=self, remote_data={}) try: submitted_data = await self.request.json() except ValueError as e: try: submit_data = await self.request.form() submitted_data = self.clean_form(submit_data._dict) except ValueError as e: logger.error(f"error {e}") err = { "status": "error", "message": f"Request data must be json or form", "model": "" } return await content_service.form_post_complete_response(err, None) if isinstance(submitted_data, dict): return submitted_data.copy() else: return submitted_data async def compute_datagrid_rows(self, key, model_name, rec_name=""): logger.info("compute_datagrid_rows") await self.get_session() server_response = await self.get_record(model_name, rec_name=rec_name) content_service = ContentService.new(gateway=self, remote_data=server_response.copy()) res = await content_service.compute_datagrid_rows(key) return res async def compute_datagrid_add_row(self, key, num_rows, model_name, rec_name=""): logger.info("compute_datagrid_add_row") await self.get_session() server_response = await self.get_record(model_name, rec_name=rec_name) content_service = ContentService.new(gateway=self, remote_data=server_response.copy()) res = await content_service.compute_datagrid_add_row(key, num_rows) return res async def content_service_from_record(self, model_name, rec_name=""): await self.get_session() server_response = await self.get_record(model_name, rec_name=rec_name) # logger.info(server_response) return ContentService.new(gateway=self, remote_data=server_response.copy()) async def before_submit(self, data, is_create=False): return data.copy() async def middleware_server_post_action(self, content_service, submitted_data) -> dict: """ This middleware method is triggered form Gateway.server_post_action method before create ContentService and post data to server. Is possible to handle three different pathway for data thougt status directive Dict mandatory key "status" possible values --> "done", "content", "error" "data" data dictionary Logic: if status == "error" --> add keys "message" and "model" server_post_action return this error if status == "done" --> server_post_action execute submit of datas conined in key "data" if status == "content" --> server_post_action :param content_service: an instance of content_service with empty data :param submitted_data: data recived from post call :return: structured Dict see above """ content = {} # content_service = ContentService.new(gateway=self, remote_data={}) if "rec_name" in submitted_data: allowed = self.name_allowed.match(submitted_data.get("rec_name")) if not allowed: logger.error(f"name {submitted_data.get('rec_name')}") err = { "status": "error", "message": f"Errore nel campo name {submitted_data.get('rec_name')} caratteri non consentiti", "model": submitted_data.get('data_model'), "data": {} } return err if "/builder_mode" in self.request.url.path: await self.get_session() content = {"status": "done", "data": {}} if "/login" in self.request.url.path: await self.get_session() content = {"status": "done", "data": submitted_data} return content async def server_post_action(self): logger.info(f"server_post_action {self.request.url}") url_path = self.request.scope['path'] # load request data await self.get_session() submitted_data = await self.load_post_request_data() # if submitted_data not dict is error then return if isinstance(submitted_data, JSONResponse): return submitted_data return await self.post_data(submitted_data, url_path=url_path) async def post_data(self, submitted_data, url_path=""): # logger.info("--") cookies = self.cookies params = self.params.copy() builder = params.get('builder') if not url_path: url_path = submitted_data.get("action_url") logger.info(url_path) data = {} content_service = ContentService.new(gateway=self, remote_data={}) mid_data = await self.middleware_server_post_action(content_service, submitted_data) if mid_data.get("status", "") == "error": return await content_service.form_post_complete_response(mid_data, None) elif mid_data.get("status", "") == "done": data = mid_data['data'].copy() elif not mid_data or mid_data.get("status") == 'content': if builder: content_service = ContentService.new(gateway=self, remote_data={}) data = content_service.compute_builder_data(submitted_data) else: if mid_data.get("status") == 'content': content = mid_data['data'].copy() else: content = await self.get_record( submitted_data.get('data_model'), submitted_data.get('rec_name', "") ) # TODO chek use remote data to eval is_create create_datetime remote_data = content.get("content").get("data") content_service = ContentService.new(gateway=self, remote_data=content.copy()) data = await content_service.form_post_handler(submitted_data) logger.info(f"submit on server") data = await self.before_submit(data.copy(), is_create=content_service.is_create) data = await content_service.before_submit(data.copy()) url = f"{self.local_settings.service_url}{url_path}" server_response = await self.post_remote_object(url, data=data, params=params, cookies=cookies) resp = server_response.get("content") # logger.info(resp) if not builder: server_response = await content_service.after_form_post_handler( server_response, data ) # logger.info(f"server_post_action result: {server_response}") return await content_service.form_post_complete_response(resp, server_response) async def server_get_action(self, url_action="", modal=False): logger.info(f"server_get_action {self.request.url} - modal {modal} ") params = self.params.copy() cookies = self.cookies await self.get_session(params=params) if not modal: url = f"{self.local_settings.service_url}{self.request.scope['path']}" server_response = await self.get_remote_object(url, params=params, cookies=cookies) else: url = url_action server_response = {} if ( server_response and ( server_response.get("action") or server_response.get("content", {}).get("action") or server_response.get("content", {}).get("reload")) ): content = server_response if "content" in server_response: content = server_response.get("content") if not modal: if content.get("action") == "redirect" or content.get("link"): url = content.get("url") if content.get("link"): url = content.get("link") headers = self.headers.copy() content_length = str(0) headers["content-length"] = content_length response = RedirectResponse( url, headers=headers, status_code=HTTP_303_SEE_OTHER ) else: return await self.complete_json_response(content) else: if not modal: content_service = ContentService.new(gateway=self, remote_data=server_response.copy()) if self.request.query_params.get("miframe"): response = await content_service.compute_form() else: response = await content_service.make_page() else: content_service = ContentService.new(gateway=self, remote_data={}) resp = await content_service.compute_form(modal=True, url=url) return await self.complete_json_response({"body": resp}) return self.complete_response(response) async def get_session(self, params={}): if not params: params = self.params url = f"{self.local_settings.service_url}/session" res = await self.get_remote_object(url, params=params) self.session = res.copy() return res.copy() async def get_record(self, model, rec_name=""): url = f"{self.local_settings.service_url}/record/{model.strip()}" if rec_name.strip(): url = f"{self.local_settings.service_url}/record/{model.strip()}/{rec_name.strip()}" res = await self.get_remote_object(url) return res async def get_record_data(self, model, rec_name): res = await self.get_record(model, rec_name) return res.get("content", {}).get("data") async def get_schema(self, model): url = f"{self.local_settings.service_url}/schema/{model}" res = await self.get_remote_object(url) return res async def get_param(self, param_name): url = f"{self.local_settings.service_url}/param/{param_name}" res = await self.get_remote_object(url) data = res.get("content").get("data") return data async def get_ext_submission(self, name, params={}): """ name is a model name """ logger.info(f"get_ext_submission -> {name}") url = f"{self.local_settings.service_url}/resource/data/{name}" res = await self.get_remote_object(url, params=params) data = res.get("content").get("data")[:] logger.info(f"get_ext_submission Response -> {len(data)}") return data async def get_list_models(self, domain={}, compute_label="title"): url = f"{self.local_settings.service_url}/models/distinct" res = await self.get_remote_object( url, params={"domain": domain.copy(), "compute_label": compute_label}) data = res.get("content").get("data")[:] logger.info(f"get_remote_object Response -> {len(data)}") return data async def get_remote_data_select( self, url, path_value, header_key, header_value_key): """ name is a model name """ logger.info(f"get_remote_data_select ->for url:{url}") local_url = f"{self.local_settings.service_url}/get_remote_data_select" params = { "url": url, "path_value": path_value, "header_key": header_key, "header_value_key": header_value_key } res = await self.get_remote_object(local_url, params=params) data = res.get("content").get("data") # logger.info(f"get_remote_data_select Response -> {type(data)}") return data async def get_resource_schema_select(self, type, select): """ name is a model name """ logger.info(f"get_resource_schema_select --> params: {type}, {select}") url = f"{self.local_settings.service_url}/resource/schema/select" res = await self.get_remote_object(url, params={"otype": type, "select": select}) data = res.get("content").get("data") logger.info(f"get_resource_schema_select --> {data}") return data async def complete_json_response(self, res, orig_resp=None): response = JSONResponse(res) return self.complete_response(response) def complete_response(self, resp): resp.headers.append("req_id", self.remote_req_id or "") if '/logout/' not in self.request.scope['path']: if not self.is_api: resp.set_cookie('authtoken', value=self.token or "") resp.headers.append("authtoken", self.token or "") else: resp.headers.append("apitoken", self.token or "") if '/logout/' in self.request.scope['path']: resp.set_cookie('authtoken', value="") resp.headers.append("authtoken", "") return resp async def eval_headers(self, headers={}): orig_params = self.request.query_params.__dict__['_dict'].copy() if not self.remote_req_id: req_id = self.request.headers.get("req_id", "") else: req_id = self.remote_req_id headers['req_id'] = req_id if self.is_api: headers['apitoken'] = self.token else: headers['authtoken'] = self.token if "Content-Type" not in headers: headers["Content-Type"] = "application/json" if "accept" not in headers: headers["accept"] = "application/json" # TODO move in shibboleth Gateway return headers.copy() async def get_remote_object(self, url, headers={}, params={}, cookies={}): if self.local_settings.service_url not in url: url = f"{self.local_settings.service_url}{url}" if "token" in params: cookies = {"authtoken": params.get("token")} if not cookies: cookies = self.request.cookies.copy() # logger.info(f" request headers {self.headers}") logger.info(f"get_remote_object --> {url}") async with httpx.AsyncClient(timeout=None) as client: res = await client.get( url=requote_uri(url), params=params, headers=self.headers, cookies=cookies ) if res.status_code == 200: req_id = res.headers.get("req_id") if res.headers.get("apitoken"): self.token = res.headers.get("apitoken") self.is_api = True elif res.headers.get("authtoken", ""): self.token = res.headers.get("authtoken") self.is_api = False self.remote_req_id =
# # BitBake Toaster Implementation # # Copyright (C) 2016 Intel Corporation # # SPDX-License-Identifier: GPL-2.0-only # # Please run flake8 on this file before sending patches import os import re import logging import json import subprocess from collections import Counter from shutil import copyfile from orm.models import Project, ProjectTarget, Build, Layer_Version from orm.models import LayerVersionDependency, LayerSource, ProjectLayer from orm.models import Recipe, CustomImageRecipe, CustomImagePackage from orm.models import Layer, Target, Package, Package_Dependency from orm.models import ProjectVariable from bldcontrol.models import BuildRequest, BuildEnvironment from bldcontrol import bbcontroller from django.http import HttpResponse, JsonResponse from django.views.generic import View from django.core.urlresolvers import reverse from django.db.models import Q, F from django.db import Error from toastergui.templatetags.projecttags import filtered_filesizeformat from django.utils import timezone import pytz # development/debugging support verbose = 2 def _log(msg): if 1 == verbose: print(msg) elif 2 == verbose: f1=open('/tmp/toaster.log', 'a') f1.write("|" + msg + "|\n" ) f1.close() logger = logging.getLogger("toaster") def error_response(error): return JsonResponse({"error": error}) class XhrBuildRequest(View): def get(self, request, *args, **kwargs): return HttpResponse() @staticmethod def cancel_build(br): """Cancel a build request""" try: bbctrl = bbcontroller.BitbakeController(br.environment) bbctrl.forceShutDown() except: # We catch a bunch of exceptions here because # this is where the server has not had time to start up # and the build request or build is in transit between # processes. # We can safely just set the build as cancelled # already as it never got started build = br.build build.outcome = Build.CANCELLED build.save() # We now hand over to the buildinfohelper to update the # build state once we've finished cancelling br.state = BuildRequest.REQ_CANCELLING br.save() def post(self, request, *args, **kwargs): """ Build control Entry point: /xhr_buildrequest/<project_id> Method: POST Args: id: id of build to change buildCancel = build_request_id ... buildDelete = id ... targets = recipe_name ... Returns: {"error": "ok"} or {"error": <error message>} """ project = Project.objects.get(pk=kwargs['pid']) if 'buildCancel' in request.POST: for i in request.POST['buildCancel'].strip().split(" "): try: br = BuildRequest.objects.get(project=project, pk=i) self.cancel_build(br) except BuildRequest.DoesNotExist: return error_response('No such build request id %s' % i) return error_response('ok') if 'buildDelete' in request.POST: for i in request.POST['buildDelete'].strip().split(" "): try: BuildRequest.objects.select_for_update().get( project=project, pk=i, state__lte=BuildRequest.REQ_DELETED).delete() except BuildRequest.DoesNotExist: pass return error_response("ok") if 'targets' in request.POST: ProjectTarget.objects.filter(project=project).delete() s = str(request.POST['targets']) for t in re.sub(r'[;%|"]', '', s).split(" "): if ":" in t: target, task = t.split(":") else: target = t task = "" ProjectTarget.objects.create(project=project, target=target, task=task) project.schedule_build() return error_response('ok') response = HttpResponse() response.status_code = 500 return response class XhrProjectUpdate(View): def get(self, request, *args, **kwargs): return HttpResponse() def post(self, request, *args, **kwargs): """ Project Update Entry point: /xhr_projectupdate/<project_id> Method: POST Args: pid: pid of project to update Returns: {"error": "ok"} or {"error": <error message>} """ project = Project.objects.get(pk=kwargs['pid']) logger.debug("ProjectUpdateCallback:project.pk=%d,project.builddir=%s" % (project.pk,project.builddir)) if 'do_update' in request.POST: # Extract any default image recipe if 'default_image' in request.POST: project.set_variable(Project.PROJECT_SPECIFIC_DEFAULTIMAGE,str(request.POST['default_image'])) else: project.set_variable(Project.PROJECT_SPECIFIC_DEFAULTIMAGE,'') logger.debug("ProjectUpdateCallback:Chain to the build request") # Chain to the build request xhrBuildRequest = XhrBuildRequest() return xhrBuildRequest.post(request, *args, **kwargs) logger.warning("ERROR:XhrProjectUpdate") response = HttpResponse() response.status_code = 500 return response class XhrSetDefaultImageUrl(View): def get(self, request, *args, **kwargs): return HttpResponse() def post(self, request, *args, **kwargs): """ Project Update Entry point: /xhr_setdefaultimage/<project_id> Method: POST Args: pid: pid of project to update default image Returns: {"error": "ok"} or {"error": <error message>} """ project = Project.objects.get(pk=kwargs['pid']) logger.debug("XhrSetDefaultImageUrl:project.pk=%d" % (project.pk)) # set any default image recipe if 'targets' in request.POST: default_target = str(request.POST['targets']) project.set_variable(Project.PROJECT_SPECIFIC_DEFAULTIMAGE,default_target) logger.debug("XhrSetDefaultImageUrl,project.pk=%d,project.builddir=%s" % (project.pk,project.builddir)) return error_response('ok') logger.warning("ERROR:XhrSetDefaultImageUrl") response = HttpResponse() response.status_code = 500 return response # # Layer Management # # Rules for 'local_source_dir' layers # * Layers must have a unique name in the Layers table # * A 'local_source_dir' layer is supposed to be shared # by all projects that use it, so that it can have the # same logical name # * Each project that uses a layer will have its own # LayerVersion and Project Layer for it # * During the Paroject delete process, when the last # LayerVersion for a 'local_source_dir' layer is deleted # then the Layer record is deleted to remove orphans # def scan_layer_content(layer,layer_version): # if this is a local layer directory, we can immediately scan its content if layer.local_source_dir: try: # recipes-*/*/*.bb cmd = '%s %s' % ('ls', os.path.join(layer.local_source_dir,'recipes-*/*/*.bb')) recipes_list = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT).stdout.read() recipes_list = recipes_list.decode("utf-8").strip() if recipes_list and 'No such' not in recipes_list: for recipe in recipes_list.split('\n'): recipe_path = recipe[recipe.rfind('recipes-'):] recipe_name = recipe[recipe.rfind('/')+1:].replace('.bb','') recipe_ver = recipe_name.rfind('_') if recipe_ver > 0: recipe_name = recipe_name[0:recipe_ver] if recipe_name: ro, created = Recipe.objects.get_or_create( layer_version=layer_version, name=recipe_name ) if created: ro.file_path = recipe_path ro.summary = 'Recipe %s from layer %s' % (recipe_name,layer.name) ro.description = ro.summary ro.save() except Exception as e: logger.warning("ERROR:scan_layer_content: %s" % e) class XhrLayer(View): """ Delete, Get, Add and Update Layer information Methods: GET POST DELETE PUT """ def get(self, request, *args, **kwargs): """ Get layer information Method: GET Entry point: /xhr_layer/<project id>/<layerversion_id> """ try: layer_version = Layer_Version.objects.get( pk=kwargs['layerversion_id']) project = Project.objects.get(pk=kwargs['pid']) project_layers = ProjectLayer.objects.filter( project=project).values_list("layercommit_id", flat=True) ret = { 'error': 'ok', 'id': layer_version.pk, 'name': layer_version.layer.name, 'layerdetailurl': layer_version.get_detailspage_url(project.pk), 'vcs_ref': layer_version.get_vcs_reference(), 'vcs_url': layer_version.layer.vcs_url, 'local_source_dir': layer_version.layer.local_source_dir, 'layerdeps': { "list": [ { "id": dep.id, "name": dep.layer.name, "layerdetailurl": dep.get_detailspage_url(project.pk), "vcs_url": dep.layer.vcs_url, "vcs_reference": dep.get_vcs_reference() } for dep in layer_version.get_alldeps(project.id)] }, 'projectlayers': list(project_layers) } return JsonResponse(ret) except Layer_Version.DoesNotExist: error_response("No such layer") def post(self, request, *args, **kwargs): """ Update a layer Method: POST Entry point: /xhr_layer/<layerversion_id> Args: vcs_url, dirpath, commit, up_branch, summary, description, local_source_dir add_dep = append a layerversion_id as a dependency rm_dep = remove a layerversion_id as a depedency Returns: {"error": "ok"} or {"error": <error message>} """ try: # We currently only allow Imported layers to be edited layer_version = Layer_Version.objects.get( id=kwargs['layerversion_id'], project=kwargs['pid'], layer_source=LayerSource.TYPE_IMPORTED) except Layer_Version.DoesNotExist: return error_response("Cannot find imported layer to update") if "vcs_url" in request.POST: layer_version.layer.vcs_url = request.POST["vcs_url"] if "dirpath" in request.POST: layer_version.dirpath = request.POST["dirpath"] if "commit" in request.POST: layer_version.commit = request.POST["commit"] layer_version.branch = request.POST["commit"] if "summary" in request.POST: layer_version.layer.summary = request.POST["summary"] if "description" in request.POST: layer_version.layer.description = request.POST["description"] if "local_source_dir" in request.POST: layer_version.layer.local_source_dir = \ request.POST["local_source_dir"] if "add_dep" in request.POST: lvd = LayerVersionDependency( layer_version=layer_version, depends_on_id=request.POST["add_dep"]) lvd.save() if "rm_dep" in request.POST: rm_dep = LayerVersionDependency.objects.get( layer_version=layer_version, depends_on_id=request.POST["rm_dep"]) rm_dep.delete() try: layer_version.layer.save() layer_version.save() except Exception as e: return error_response("Could not update layer version entry: %s" % e) return error_response("ok") def put(self, request, *args, **kwargs): """ Add a new layer Method: PUT Entry point: /xhr_layer/<project id>/ Args: project_id, name, [vcs_url, dir_path, git_ref], [local_source_dir], [layer_deps (csv)] """ try: project = Project.objects.get(pk=kwargs['pid']) layer_data = json.loads(request.body.decode('utf-8')) # We require a unique layer name as otherwise the lists of layers # becomes very confusing existing_layers = \ project.get_all_compatible_layer_versions().values_list( "layer__name", flat=True) add_to_project = False layer_deps_added = [] if 'add_to_project' in layer_data: add_to_project = True if layer_data['name'] in existing_layers: return JsonResponse({"error": "layer-name-exists"}) if ('local_source_dir' in layer_data): # Local layer can be shared across projects. They have no 'release' # and are not included in get_all_compatible_layer_versions() above layer,created = Layer.objects.get_or_create(name=layer_data['name']) _log("Local Layer created=%s" % created) else: layer = Layer.objects.create(name=layer_data['name']) layer_version = Layer_Version.objects.create( layer=layer, project=project, layer_source=LayerSource.TYPE_IMPORTED) # Local layer if ('local_source_dir' in layer_data): ### and layer.local_source_dir: layer.local_source_dir = layer_data['local_source_dir'] # git layer elif 'vcs_url' in layer_data: layer.vcs_url = layer_data['vcs_url'] layer_version.dirpath = layer_data['dir_path'] layer_version.commit = layer_data['git_ref'] layer_version.branch = layer_data['git_ref'] layer.save() layer_version.save() if add_to_project: ProjectLayer.objects.get_or_create( layercommit=layer_version, project=project) # Add the layer dependencies if 'layer_deps' in layer_data: for layer_dep_id in layer_data['layer_deps'].split(","): layer_dep = Layer_Version.objects.get(pk=layer_dep_id) LayerVersionDependency.objects.get_or_create( layer_version=layer_version, depends_on=layer_dep) # Add layer deps to the project if specified if add_to_project: created, pl = ProjectLayer.objects.get_or_create( layercommit=layer_dep, project=project) layer_deps_added.append( {'name': layer_dep.layer.name, 'layerdetailurl': layer_dep.get_detailspage_url(project.pk)}) # Scan the layer's content and update components scan_layer_content(layer,layer_version) except Layer_Version.DoesNotExist: return error_response("layer-dep-not-found") except Project.DoesNotExist: return error_response("project-not-found") except KeyError: return error_response("incorrect-parameters") return JsonResponse({'error': "ok", 'imported_layer': { 'name': layer.name, 'layerdetailurl': layer_version.get_detailspage_url()}, 'deps_added': layer_deps_added}) def delete(self, request, *args, **kwargs): """ Delete an imported layer Method: DELETE Entry point: /xhr_layer/<projed id>/<layerversion_id> """ try: # We currently only allow Imported layers to be deleted layer_version = Layer_Version.objects.get( id=kwargs['layerversion_id'], project=kwargs['pid'], layer_source=LayerSource.TYPE_IMPORTED) except Layer_Version.DoesNotExist: return error_response("Cannot find imported layer to delete") try: ProjectLayer.objects.get(project=kwargs['pid'], layercommit=layer_version).delete() except ProjectLayer.DoesNotExist: pass layer_version.layer.delete() layer_version.delete() return JsonResponse({ "error": "ok", "gotoUrl": reverse('projectlayers', args=(kwargs['pid'],)) }) class XhrCustomRecipe(View): """ Create a custom image recipe """ def post(self, request, *args, **kwargs): """ Custom image recipe REST API Entry point: /xhr_customrecipe/ Method: POST Args: name: name of custom recipe to create project: target project id of orm.models.Project base: base recipe id of orm.models.Recipe Returns: {"error": "ok", "url": <url of the
<filename>nasws/cnn/policy/cnn_general_search_policies.py<gh_stars>1-10 # ======================================================== # CONFIDENTIAL - Under development # ======================================================== # Author: <NAME> with email <EMAIL> # All Rights Reserved. # Last modified: 2019/11/27 下午12:05 # NOTICE: All information contained herein is, and remains # the property of Kaicheng Yu, if any. The intellectual and # technical concepts contained herein are proprietary to him # and his suppliers and may be covered by U.S. and Foreign Patents, # patents in process, and are protected by trade secret or copyright law. # Dissemination of this information or reproduction of this material # is strictly forbidden unless prior written permission is obtained # from Kaicheng Yu. # ======================================================== # import warnings import logging import shutil from abc import ABC, abstractmethod import utils import os import torch import time import torch.nn as nn from collections import OrderedDict from functools import partial from operator import itemgetter import torch.backends.cudnn as cudnn # from torch.optim.lr_scheduler import CosineAnnealingWarmRestarts from scipy.stats.stats import kendalltau from torch.utils.tensorboard import SummaryWriter # after import torch, add this from nasws.cnn.utils import Rank, compute_percentile, compute_sparse_kendalltau, sort_hash_perfs import nasws.cnn.search_space as search_space from nasws.cnn import procedures as procedure_ops from nasws.cnn.visualization.tool import darts_nds_map_state_dict_keys_from_non_wsbn_to_wsbn from nasws.cnn.operations.loss import CrossEntropyLabelSmooth from nasws.dataset import load_supernet_imagenet, load_supernet_cifar10 from visualization.plot_rank_change import process_rank_data_nasbench from visualization.process_data import * cudnn.benchmark = True class CNNSearchPolicy(ABC): """ Search policy for CNN model. Base method is Oneshot """ trained_model_spec_ids = [] model_spec_id = None model_spec = None _change_model_fn = None _datasets = None @property def change_model_spec_fn(self): if self._change_model_fn: return self._change_model_fn else: self._change_model_fn = self.search_space.change_model_spec return self._change_model_fn @property def criterion(self): return self._loss @property def eval_criterion(self): if self._eval_loss: return self._eval_loss else: return self._loss @property def eval_result(self): """ associate with running_stats. to better save this. Format: dict: Key: model spec ID or architecture spec Val: tuple (acc, obj) """ if 'eval_result' in self.running_stats.keys(): return self.running_stats['eval_result'] else: self.running_stats['eval_result'] = OrderedDict() return self.running_stats['eval_result'] @property def epoch(self): if 'epoch' in self.running_stats.keys(): e = self.running_stats['epoch'] else: e = 0 self.args.current_epoch = e return e @epoch.setter def epoch(self, epoch): self.running_stats['epoch'] = epoch self.args.current_epoch = epoch @property def ranking_per_epoch(self): if 'ranking_per_epoch' in self.running_stats.keys(): return self.running_stats['ranking_per_epoch'] else: logging.info("Initializing one") self.running_stats['ranking_per_epoch'] = OrderedDict() return self.running_stats['ranking_per_epoch'] @property def evaluate_model_spec_ids(self): logging.warning("please remove this, use self.search_space.evaluate_model_spec_ids instead.") raise ValueError("TODO") # return self.search_space.evaluate_model_spec_ids def evaluate_model_spec_id_pool(self): logging.warning("please remove this, use self.search_space.evaluate_model_spec_id_pool instead.") raise ValueError() # return self.search_space.evaluate_model_spec_id_pool() def __init__(self, args, sub_dir_path=None): super(CNNSearchPolicy, self).__init__() self.args = args self._loss = None self._eval_loss = None if self.args.debug: torch.autograd.set_detect_anomaly(True) self.initialize_misc() # Random seed should be set once the Policy is created. logging.info(f"setting random seed as {args.seed}") utils.torch_random_seed(args.seed) logging.info('gpu number = %d' % args.gpus) logging.info("args = %s", args) # metrics to track # self.ranking_per_epoch = OrderedDict() self.search_space = None # store the search space. self.model = None # store the model self.model_fn = None self.amp = None self.running_stats = OrderedDict() # store all running status. # do it here because, Rank loss needs search space self.initialize_search_space() # to log the training results. self.logging_fn = self.logging_at_epoch self.test_fn = procedure_ops.evaluate_procedure.evaluate_normal # load the train methods. if args.supernet_train_method in ['spos']: """ Fundamental baseline training methods sample 1 architecture per batch train supernet Conv op has maximum possible filter channels (== output size of cell) Random a chunk of it. """ train_fn = procedure_ops.darts_train_model self.train_fn = partial(train_fn, args=self.args, architect=None, sampler=self.random_sampler) self.eval_fn = partial(procedure_ops.darts_model_validation, args=self.args) elif args.supernet_train_method == 'fairnas': """ Extend darts training method with FairNas strategy. It is not possible to use directly the FairNAS, but we can extend it into 2 method. """ train_fn = procedure_ops.fairnas_train_model_v1 self.train_fn = partial(train_fn, args=self.args, architect=None, topology_sampler=self.random_sampler, op_sampler=self.op_sampler ) self.eval_fn = partial(procedure_ops.darts_model_validation, args=self.args) elif args.supernet_train_method == 'maml': """ Implement the MAML method, to train the supernet for now. It will support other policy later. """ train_fn = procedure_ops.maml_nas_weight_sharing self.train_fn = partial(train_fn, args=self.args, architect=None, sampler=self.random_sampler) self.eval_fn = partial(procedure_ops.darts_model_validation, args=self.args) self.logging_fn = self.logging_maml torch.autograd.set_detect_anomaly(True) elif args.supernet_train_method == 'spos_rankloss': train_fn = procedure_ops.darts_train_model_with_landmark_regularization logging.info('Enabling Ranking loss function {} and procedure {}.'.format( args.landmark_loss_fn, args.landmark_loss_procedure)) self.train_fn = partial(train_fn, args=self.args, architect=None, sampler=self.random_sampler, landmark_loss_step=procedure_ops.landmark_loss_step_fns[args.landmark_loss_procedure], search_space=self.search_space ) self.eval_fn = partial(procedure_ops.darts_model_validation, args=self.args) logging.info("Landmark archs selected {}".format(self.search_space.landmark_topologies[0])) elif args.supernet_train_method == 'spos_rankloss_maml': train_fn = procedure_ops.maml_ranking_loss_procedure logging.info('Enabling Ranking loss function {} and procedure {}.'.format( args.landmark_loss_fn, args.landmark_loss_procedure)) self.train_fn = partial(train_fn, args=self.args, architect=None, sampler=self.random_sampler, landmark_loss_step=procedure_ops.landmark_loss_step_fns[args.landmark_loss_procedure], search_space=self.search_space ) self.eval_fn = partial(procedure_ops.darts_model_validation, args=self.args) logging.info("Landmark archs selected {}".format(self.search_space.landmark_topologies[0])) self.logging_fn = self.logging_maml else: logging.debug(f'{args.supernet_train_method} is not supported in the base class!') def initialize_misc(self, mode=None): """ initialize path and logger """ args = self.args if not args.continue_train: self.sub_directory_path = mode or '{}_SEED_{}'.format(args.supernet_train_method, args.seed) self.exp_dir = os.path.join(args.main_path, self.sub_directory_path) utils.create_exp_dir(self.exp_dir) utils.save_json(args, self.exp_dir + '/args.json') if args.visualize: self.viz_dir_path = utils.create_viz_dir(self.exp_dir) if args.tensorboard: self.tb_dir = self.exp_dir tboard_dir = os.path.join(args.tboard_dir, self.sub_directory_path) self.writer = SummaryWriter(tboard_dir) # Set logger and directory. self.logger = utils.get_logger( mode or 'train_search', file_handler=utils.get_file_handler(os.path.join(self.exp_dir, 'log.txt')), level=logging.INFO if not args.debug else logging.DEBUG ) """ Procedure of search """ # Search happens here. def run(self): """ Procedure of training. This run describes the entire training procedure Parsed arguments: train_fn : train_queue, valid_queue, model, criterion, optimizer, lr valid_model : model, valid_queue, self.model_spec_id, self.model_spec :return: """ model, optimizer, scheduler = self.initialize_model() train_queue, valid_queue, test_queue, criterion = self.initialize_run() args = self.args fitness_dict = {} logging.info(">> Begin the search with supernet method : {}".format(args.supernet_train_method)) # start from current epoch. if args.debug: self.post_search_phase() for epoch in range(self.epoch, args.epochs): args.current_epoch = epoch lr = scheduler.get_last_lr()[0] train_acc, train_obj = self.train_fn(train_queue, valid_queue, model, criterion, optimizer, lr) self.logging_fn(train_acc, train_obj, epoch, 'Train', display_dict={'lr': lr}) scheduler.step() # validation valid_acc, valid_obj = self.validate_model(model, valid_queue, self.model_spec_id, self.model_spec) self.logging_fn(valid_acc, valid_obj, epoch, 'Valid') self.save_checkpoint(model, optimizer) # save the imagenet results every 10 epochs ... if 'imagenet' in self.args.dataset and epoch % 10 == 0 and epoch > 0: # duplicate for imagenet for easy recovery... self.save_checkpoint(model, optimizer, epoch) if not self.check_should_save(epoch): continue # evaluate process. self.save_duplicate_arch_pool('valid', epoch) fitness_dict = self.evaluate(epoch, test_queue, fitnesses_dict=fitness_dict, train_queue=train_queue) self.save_results(epoch, rank_details=True) logging.info(">> Search phase finished! Evaluate here for better results.") # add later, return the model specs that is evaluated across the time. # Process the ranking in the end, re # turn the best of training. return self.post_search_phase() def validate_model(self, current_model, data_source, current_geno_id, current_genotype, batch_size=10): complete_valid_queue = data_source _valid_queue = [] nb_batch_per_model, nb_models, valid_model_pool = self.\ search_space.validate_model_indices(len(complete_valid_queue)) total_valid_acc = 0. total_valid_obj = 0. valid_accs = OrderedDict() valid_objs = OrderedDict() for step, val_d in enumerate(complete_valid_queue): if self.args.debug: if step > 100: logging.debug("Break after 100 step in validation step.") break _valid_queue.append(val_d) if step % nb_batch_per_model == 0 and step > 0: _id = valid_model_pool[min(int(step / nb_batch_per_model), nb_models - 1)] current_model = self.change_model_spec_fn(current_model, self.search_space.topologies[_id]) current_model.eval() _valid_acc, _valid_obj = self.eval_fn(_valid_queue, current_model, self.eval_criterion) # logging.info(f"model id {valid_model_pool[_id]} acc {_valid_acc} loss {_valid_obj}") # update the metrics total_valid_acc += _valid_acc total_valid_obj += _valid_obj # store the results valid_accs[_id] = _valid_acc valid_objs[_id] = _valid_obj _valid_queue = [] self.save_arch_pool_performance(archs=list(valid_accs.keys()), perfs=list(valid_accs.values()), prefix='valid') return total_valid_acc / nb_models, total_valid_obj/ nb_models def evaluate(self, epoch, data_source, fitnesses_dict=None, train_queue=None, model_spec_id_pool=None): """ Full evaluation of all possible models. :param epoch: :param data_source: :param fitnesses_dict: Store the model_spec_id -> accuracy :return: eval_result {model_spec_id: (acc, obj)} the evaluation results are also returned. """ # Make sure this id pool is not None. model_spec_id_pool = model_spec_id_pool or self.search_space.evaluate_model_spec_id_pool() if 'rankloss' in self.args.supernet_train_method: # add this for evaluate landmark architectures separately. landmark_model_id_pool, landmark_specs = self.search_space.landmark_topologies landmark_rank_gens, landmark_eval_results = procedure_ops.evaluate_procedure.evaluate_normal( self, self.parallel_model, {}, landmark_model_id_pool, data_source, self.change_model_spec_fn, self.eval_criterion ) # save the ranking for landmark architectures. if 'landmark_ranking_per_epoch' not in self.running_stats.keys(): self.running_stats['landmark_ranking_per_epoch'] = OrderedDict({epoch: landmark_rank_gens}) else: self.running_stats['landmark_ranking_per_epoch'][epoch] = landmark_rank_gens logging.info("Rank results for landmark architectures ...") self._save_results( {'ranking_per_epoch': self.running_stats['landmark_ranking_per_epoch']}, epoch, rank_details=True, filename='landmark_rank.json', random_kdt=False, prefix='landmark' ) rank_gens, eval_result = procedure_ops.evaluate_procedure.evaluate_normal( self, self.parallel_model, fitnesses_dict, model_spec_id_pool, data_source, self.change_model_spec_fn, self.eval_criterion ) self.ranking_per_epoch[epoch] = rank_gens self.eval_result[epoch] = eval_result self.logger.info('VALIDATION RANKING OF PARTICLES') for pos, elem in enumerate(rank_gens): self.logger.info(f'particle gen id: {elem[1].geno_id}, acc: {elem[1].valid_acc}, obj {elem[1].valid_obj}, ' f'hash: {elem[0]}, pos {pos}') # save the eval arch pool. archs = [elem[1].geno_id for elem in rank_gens] perfs = [elem[1].valid_acc for elem in rank_gens] self.save_arch_pool_performance(archs, perfs, prefix='eval') self.save_duplicate_arch_pool(prefix='eval', epoch=epoch) self.search_space.eval_model_spec_id_rank(archs, perfs) if self.writer: # process data into list. accs_after, objs_after = zip(*eval_result.values()) tensorboard_summarize_list(accs_after, writer=self.writer, key='neweval_after/acc', step=epoch, ascending=False) tensorboard_summarize_list(objs_after, writer=self.writer, key='neweval_after/obj', step=epoch) return eval_result def post_search_phase(self): """ Running the policy search on a given shared parameters. It should be built from simple use-case, i.e. testing
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== # pylint: disable=g-short-docstring-punctuation """ HashTable Variable. @@SimpleHashTable @@HashTable @@DistributedHashTable """ # pylint: disable=g-bad-name from __future__ import absolute_import from __future__ import division from __future__ import print_function import contextlib from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import function from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import data_flow_ops from tensorflow.python.ops import gen_hash_ops from tensorflow.python.ops import math_ops from tensorflow.python.util import tf_contextlib from tensorflow.python.util.tf_export import tf_export @tf_export("hash_table.SimpleHashTable") class SimpleHashTable(object): """TODO: Add DocString""" def __init__( self, distributed_name, concurrent_read, slicer=None, children=None, name=None): self._distributed_name = distributed_name self._children = [] if children is None else children with ops.name_scope(name, "SimpleHashTable") as name: handle_name = ops.name_from_scope_name(name) self._name = handle_name with ops.control_dependencies(None): self._handle = gen_hash_ops.hash_table_op(shared_name=handle_name, name=name) self._slicer = slicer with ops.colocate_with(self._handle): self._initializer = gen_hash_ops.hash_table_initialize_op( self._handle, True, concurrent_read, self._children, name="Initializer") self._false_initializer = gen_hash_ops.hash_table_initialize_op( self._handle, False, concurrent_read, self._children, name="FalseInitializer") @property def handle(self): return self._handle @property def initializer(self): return self._initializer @property def false_initializer(self): return self._false_initializer @property def slicer(self): return self._slicer @property def name(self): return self._name @property def op(self): return self._handle.op @property def device(self): return self._handle.device @property def graph(self): return self._handle.graph @property def distributed_name(self): return self._distributed_name @distributed_name.setter def distributed_name(self, distributed_name): self._distributed_name = distributed_name @property def children(self): return self._children def to_proto(v, export_scope=None): return None def from_proto(v, import_scope=None): return None def __lt__(self, other): if isinstance(other, SimpleHashTable): other = other._name return self._name < other def lookup(self, keys, admit_strategy=None, frequencies=None, name=None): if admit_strategy is None: with ops.colocate_with(self._handle): return gen_hash_ops.hash_table_lookup_op( self._handle, ops.convert_to_tensor(keys, dtype=dtypes.int64), name=name) else: if frequencies is None: freqs_tensor = constant_op.constant([], dtype=dtypes.int32) else: freqs_tensor = ops.convert_to_tensor(frequencies, dtype=dtypes.int32) with ops.colocate_with(self._handle): return gen_hash_ops.hash_table_lookup_with_admit_op( self._handle, ops.convert_to_tensor(keys, dtype=dtypes.int64), admit_strategy, freqs_tensor, name=name) def size(self, name=None): with ops.colocate_with(self._handle): return gen_hash_ops.hash_table_size_op(self._handle, name=name) @tf_export("hash_table.HashTable") class HashTable(object): """TODO: Add DocString""" DEFAULT_SLICE_SIZE = 4096 def __init__( self, shape, dtype, distributed_name, initializer=None, init_func=None, segment_size=None, collections=None, trainable=True, slicer=None, hash_table=None, concurrent_read=True, children=None, name=None): self._distributed_name = distributed_name self._slots = {} self._concurrent_read = concurrent_read self._children = [] if children is None else children with ops.name_scope(name, "HashTable") as name: handle_name = ops.name_from_scope_name(name) self._name = handle_name if hash_table is None: hash_table = SimpleHashTable( distributed_name, concurrent_read, slicer, self._children) with ops.control_dependencies(None): with ops.colocate_with(hash_table.handle): if initializer == None and init_func == None: raise ValueError("initializer or initial_value must be specified.") if initializer != None and init_func != None: raise ValueError("initializer and initial_value must not be specified both.") if segment_size == None: segment_size = self.DEFAULT_SLICE_SIZE self._shape = tensor_shape.TensorShape(shape) self._dtype = dtypes.as_dtype(dtype) self._segment_shape = tensor_shape.TensorShape.concatenate( tensor_shape.TensorShape([segment_size]), self._shape) if initializer: if isinstance(initializer, type): initializer = initializer(self._dtype) init_func = lambda: initializer(shape=self._segment_shape, dtype=self._dtype, partition_info=None) self._hash_table = hash_table self._factory = function.Defun()(lambda: gen_hash_ops.copy_tensor(init_func())) self._handle = gen_hash_ops.tensible_variable_op( self._dtype, self._segment_shape, shared_name=handle_name, name=name) with ops.control_dependencies([hash_table.initializer]): self._initializer = self.initializer_without_hashtable(True, "Initializer") self._false_initializer = self.initializer_without_hashtable(False, "FalseInitializer") if collections is None: collections = [ops.GraphKeys.GLOBAL_VARIABLES] if not isinstance(collections, (list, tuple, set)): raise ValueError( "collections argument to Variable constructor must be a list, tuple, " "or set. Got %s of type %s" % (collections, type(collections))) trainable = trainable if trainable is not None else True if trainable and ops.GraphKeys.TRAINABLE_VARIABLES not in collections: collections = list(collections) + [ops.GraphKeys.TRAINABLE_VARIABLES] ops.add_to_collections(collections, self) def __repr__(self): return "<tf.hash_table.HashTable '%s' shape=%s dtype=%s" % ( self.name, self.shape, self.dtype.name) @property def handle(self): return self._handle @property def initializer(self): return self._initializer @property def false_initializer(self): return self._false_initializer @property def hash_table(self): return self._hash_table @property def dtype(self): return self._dtype @property def shape(self): return self._shape @property def name(self): return self._name @property def op(self): return self._handle.op @property def device(self): return self._handle.device @property def graph(self): return self._handle.graph @property def slicer(self): return self._hash_table._slicer @slicer.setter def slicer(self, slicer): self._hash_table._slicer = slicer @property def distributed_name(self): return self._distributed_name @property def slots(self): return self._slots @property def children(self): return self._children def get_slot(self, name): return self._slots[name] @property def snapshot(self): return gen_hash_ops.hash_table_snapshot_op(self.hash_table.handle) @distributed_name.setter def distributed_name(self, distributed_name): self._distributed_name = distributed_name def get_shape(self): return self._shape def initializer_without_hashtable(self, initialized=True, name=None): with ops.name_scope(name, "Initializer") as name: init_op = gen_hash_ops.tensible_variable_initialize_op( self._handle, self._hash_table.handle, self._dtype, self._segment_shape, self._factory, initialized, name="Initializer") return init_op def initialize_resource_op(self, name=None): with ops.control_dependencies([self._hash_table.initializer]): return gen_hash_ops.tensible_variable_initialize_op( self._handle, self._hash_table.handle, self._dtype, self._segment_shape, self._factory) def lookup(self, keys, admit_strategy=None, frequencies=None, default_value=0, name=None): with ops.colocate_with(self._handle): with ops.name_scope(name, "tensible_variable_lookup") as name: ids = self.gen_ids(keys, admit_strategy, frequencies) return self.lookup_by_id(ids, default_value, name) def gen_ids(self, keys, admit_strategy=None, frequencies=None, name=None): with ops.colocate_with(self._handle): return self._hash_table.lookup(keys, admit_strategy, frequencies, name) def lookup_by_id(self, ids, default_value=0, name=None): default_value = ops.convert_to_tensor(default_value, dtype=self._dtype) with ops.colocate_with(self._handle): return gen_hash_ops.tensible_variable_gather( self._handle, ids, default_value, name=name) def size(self, name=None): return self._hash_table.size(name) def get_or_create_slot( self, shape, dtype, distributed_name, initializer=None, init_func=None, segment_size=None, collections=None, trainable=False, name=None): if distributed_name in self._slots: return self._slots[distributed_name] return self.create_slot( shape, dtype, distributed_name, initializer, init_func, segment_size, collections, trainable, name) def create_slot( self, shape, dtype, distributed_name, initializer=None, init_func=None, segment_size=None, collections=None, trainable=False, name=None): if distributed_name in self._slots: k = 1 while "{}_{}".format(distributed_name, k) in self._slots: k += 1 distributed_name = "{}_{}".format(distributed_name, k) slot = HashTable( shape, dtype, distributed_name, initializer, init_func, segment_size, collections, trainable, None, self._hash_table, self._concurrent_read, self._children, name) self._slots[distributed_name] = slot return slot def to_proto(v, export_scope=None): return None def from_proto(v, import_scope=None): return None def __lt__(self, other): if isinstance(other, HashTable): other = other._name return self._name < other def scatter_update(self, keys, values, name=None): with ops.colocate_with(self._handle): with ops.name_scope(name, "tensible_scatter_update") as name: return self._scatter_op(keys, values, gen_hash_ops.tensible_variable_scatter_update, name=name) def scatter_add(self, keys, values, name=None): with ops.colocate_with(self._handle): with ops.name_scope(name, "tensible_scatter_add") as name: return self._scatter_op(keys, values, gen_hash_ops.tensible_variable_scatter_add, name=name) def scatter_sub(self, keys, values, name=None): with ops.colocate_with(self._handle): with ops.name_scope(name, "tensible_scatter_sub") as name: return self._scatter_op(keys, values, gen_hash_ops.tensible_variable_scatter_sub) def scatter_mul(self, keys, values, name=None): with ops.colocate_with(self._handle): with ops.name_scope(name, "tensible_scatter_mul") as name: return self._scatter_op(keys, values, gen_hash_ops.tensible_variable_scatter_mul) def scatter_div(self, keys, values, name=None): with ops.colocate_with(self._handle): with ops.name_scope(name, "tensible_scatter_div") as name: return self._scatter_op(keys, values, gen_hash_ops.tensible_variable_scatter_div) def _scatter_op(self, keys, values, scatter_func, name=None): return scatter_func(self, self.gen_ids(keys), values, name=name) @tf_export('hash_table.FixedSizeHashTablePartitioner') class FixedSizeHashTablePartitioner(object): def __init__(self, part_num): self._part_num = part_num def __call__(self, slice_size): slicer = [] x = 0 for i in range(self._part_num): slicer.append(x) x += slice_size // self._part_num if i < slice_size % self._part_num: x += 1 return slicer @tf_export("hash_table.DistributedHashTable") class DistributedHashTable(object): """TODO: Add DocString""" _DEFAULT_SLICER_SIZE = 65536 def __init__( self, shape, dtype, initializer=None, init_func=None, segment_size=None, collections=None, trainable=True, partitioner=None, slice_size=None, slicer=None, hash_tables=None, concurrent_read=True, children=None, name=None): if slice_size is None: slice_size = DistributedHashTable._DEFAULT_SLICER_SIZE if slicer is None and partitioner is None: raise ValueError('must specify slicer or partitioner') if slicer is None: slicer = partitioner(slice_size) self._children = [] if children is None else children if hash_tables is None: with ops.name_scope(name, "DistributedHashTable") as name: distributed_name = ops.name_from_scope_name(name) oslicer = slicer + [slice_size] hash_tables = [] for i in range(len(slicer)): hash_tables.append( HashTable(shape, dtype, distributed_name, initializer, init_func, segment_size, collections, trainable, [oslicer[i], oslicer[i + 1], slice_size], None, concurrent_read, children, "HashTable_" + str(i))) if len(hash_tables) != len(slicer): raise RuntimeError("HashTable size should be equal to slicer size") self._shape = shape self._dtype = dtype self._slice_size = slice_size self._slicer = slicer self._hash_tables = hash_tables self._name = hash_tables[0].distributed_name @property def dtype(self): return self._dtype @property def shape(self): return self._shape @property def partitions(self): return list(self._hash_tables) @property def initializer(self): return [i.initializer for i in self._hash_tables] @property def device(self): return [i.device for i in self._hash_tables] @property def name(self): return self._name @property def snapshot(self): keys = [] ids = [] for partition in self.partitions: key, id = partition.snapshot keys.append(key) ids.append(id) return [array_ops.concat(keys, 0), array_ops.concat(ids, 0)] def initializer_without_hashtable(self, name=None): with ops.name_scope(name, "DistributedHashTable_Initializer") as name: return [i.initializer_without_hashtable() for i in self._hash_tables] def lookup(self, keys, admit_strategy_factory=None, frequencies=None, default_value=0, name=None): with ops.name_scope(name, "DistributedHashTable_Lookup") as name: keys_per_device, gather_ids_per_device, indices_per_device, dense_shape =\ self.gen_ids(keys, admit_strategy_factory, frequencies) return self.lookup_by_id(gather_ids_per_device, indices_per_device, dense_shape, default_value) def gen_ids(self, keys, admit_strategy_factory=None, frequencies=None, name=None): if admit_strategy_factory is None: admit_strategy_factory = lambda ht: None keys = ops.convert_to_tensor(keys, dtype=dtypes.int64) with ops.name_scope(name, "DistributedHashTable_GenIds") as name: flat_keys = array_ops.reshape(keys, [-1]) original_indices = math_ops.range(array_ops.size(flat_keys)) part_id = gen_hash_ops.hash_slice(self._slicer, flat_keys, self._slice_size) keys_per_device = data_flow_ops.dynamic_partition(flat_keys, part_id, len(self._slicer)) if frequencies is None: freqs_per_device = [constant_op.constant([], dtype=dtypes.int32)] * len(self._slicer) else: flat_freqs = array_ops.reshape(frequencies, [-1]) freqs_per_device= data_flow_ops.dynamic_partition(flat_freqs, part_id, len(self._slicer)) indices_per_device =
#!/usr/bin/env python import pygtk pygtk.require('2.0') import gtk import os, sys import time import cairo import igraph from gtk import gdk from util import * import logs from math import * import custom from visual import * import matplotlib.pyplot as plt import numpy as np import micavis.ipython as ipython import micavis.analysis as analysis from event_tree_model import * from trace import * class GraphWindow(object): # graph = igraph instance # node_name_map = map from address_str => vertex id def __init__(self, micavis, graph, node_name_map): window = gtk.Window() self.micavis = micavis vbox = gtk.VBox(False, 0) self.igraph_drawing_area = IGraphDrawingArea(micavis, graph, node_name_map) menubar = self.create_display_menus() vbox.pack_start(menubar, False) vbox.pack_start(self.igraph_drawing_area, True, True, 0) self.micavis.adj = gtk.Adjustment(value = 0, lower = 0, upper = len(self.micavis.events)-1, step_incr = 1, page_incr = 1, page_size = 0) self.micavis.adj.connect("value_changed", self.micavis.event_slider_changed) self.slider = gtk.HScale(self.micavis.adj) self.slider.set_digits(0) vbox.pack_start(self.slider, False, False, 0) window.add(vbox) window.connect("destroy", gtk.main_quit) self.window = window def refresh_graph(self): self.igraph_drawing_area.redraw_canvas() def set_graph(self, graph): self.window.set_graph(graph) def create_menu_item(self, menu, label, callback): item = gtk.MenuItem(label) item.connect("activate",callback) menu.append(item) item.show() def create_display_menus(self): # utility function vis = self.igraph_drawing_area bar = gtk.MenuBar() layers = gtk.MenuItem("Layers") layers.show() bar.append(layers) menu = gtk.Menu() layers.set_submenu(menu) for layer in vis.display_layers: checkitem = gtk.CheckMenuItem(layer.name) checkitem.set_active(layer.active) checkitem.connect("activate", layer.toggle) menu.append(checkitem) checkitem.show() menu.show() projection = gtk.MenuItem("Projection") projection.show() bar.append(projection) menu = gtk.Menu() projection.set_submenu(menu) self.projection_checkitems = {} for p,shortname in self.projection_hierarchy(): checkitem = gtk.CheckMenuItem(shortname) if p == 'root': active = True else: active = False checkitem.set_active(active) checkitem.connect("activate", self.micavis.set_projection_gui, p) self.projection_checkitems[p] = checkitem menu.append(checkitem) checkitem.show() menu.show() analysis = gtk.MenuItem("Analysis") menu = gtk.Menu() menu.show() analysis_menu = menu self.analysis_menu = analysis_menu analysis.set_submenu(menu) analysis.show() bar.append(analysis) def ignore_widget(f): return lambda widget, *args: f(*args) def append_analysis_menuitem(label, callback): self.create_menu_item(analysis_menu, label, callback) append_analysis_menuitem( "State change graph", ignore_widget(self.micavis.plot_state_change_graph)) append_analysis_menuitem( "State change graph (leaves)", ignore_widget(self.micavis.plot_state_change_graph_leaves)) append_analysis_menuitem( "Gossip rate (leaves)", ignore_widget(self.micavis.plot_gossip_rate)) append_analysis_menuitem( "Gossips per node" , ignore_widget(self.micavis.plot_gossip_per_node)) for ne_suffix in self.micavis.notable_event_labels(): append_analysis_menuitem( "Notable events: %s" % ne_suffix, lambda widget,sfx=ne_suffix: self.micavis.plot_notable_events(sfx)) for ne_suffix in self.micavis.notable_event_labels(): append_analysis_menuitem( "Notable event timing histogram: %s" % ne_suffix, lambda widget,sfx=ne_suffix: self.micavis.plot_notable_events_histogram(sfx)) for ne_suffix in self.micavis.notable_event_labels(): append_analysis_menuitem( "Notable event timing histogram (normalized): %s" % ne_suffix, lambda widget,sfx=ne_suffix: self.micavis.plot_notable_events_histogram(sfx,normalize=True)) for label, callback in self.micavis.temp_analysis_menus: append_analysis_menuitem(label, callback) layout = gtk.MenuItem("Layout") menu = gtk.Menu() menu.show() self.layout_menu = menu layout.set_submenu(menu) layout.show() self.create_menu_item(self.layout_menu, "Recompute layout from current view", self.recompute_layout_from_view) bar.append(layout) return bar def projection_hierarchy(self): projs = self.micavis.projections ancestors = [0]*len(projs) ancestors[0] = -1 levels = [1]*len(projs) levels[0] = 0 for i,p in enumerate(projs): for j,r in reversed(list(enumerate(projs[:i]))): if p.startswith(r): ancestors[i] = j levels[i] = levels[j]+1 break for i,p in enumerate(projs): if ancestors[i] <= 0: short = p else: short = p[len(projs[ancestors[i]])+1:] short = ' '*levels[i] + short yield p,short def recompute_layout_from_view(self, widget): ual = self.micavis.unique_addresses namemap = dict((n,i) for i,n in enumerate(ual)) graph = igraph.Graph(directed=True) n = len(ual) graph.add_vertices(n) matrix = [ [0] * n for i in xrange(n) ] for addr in ual: view = self.micavis.current_node_view[addr] for peer, weight in view.iteritems(): matrix[namemap[addr]][namemap[peer]] = weight edges = list(logs.matrix_edge_generator(matrix)) graph.add_edges(edges) self.micavis.set_layout(graph, namemap) class MicaVisMicavis(MicaTrace): def __init__(self, logloc, options): MicaTrace.__init__(self, logloc) self.current = 0 self.options = options self.cursor_listeners = [] # functions that updated cursor ("current") values will be passed to, whenever it changes self.adj = None # initialize custom modules self.create_event_window() self.create_graph_window() # Move cursor to start self.reset_tree_selection() if self.adj is None: print "Warning: micavis.adj is None, graph window creation failed somehow" self.add_cursor_listener(self.current_node_state.set_i) # current_node_state[addr] -> the latest state assigned to node "addr" w.r.t. the cursor self.get_current_i() self.add_cursor_listener(self.current_node_view.set_i) self.exchange_tracker = logs.GossipExchangeTracker2(self.events) self.add_cursor_listener(self.exchange_tracker.set_i) # NOTE: This cursor listener should be last executed! self.add_cursor_listener(lambda i: self.graph_window.refresh_graph()) def notable_event_labels(self): suffixes = set() for (suffix,data),timestamp,address in self.notable_events(): suffixes.add(suffix) return sorted(list(suffixes)) # yields (key,timestamp,address) triples # # if restrict_netype is given, key is simply the "data" value # of the event. If restrict_type is not given, # key is a pair of (ne_type,data) where ne_type is the suffix # from the event_type after notable-event- def notable_events(self,restrict_netype=None): for e in self.events: et = e['event_type'] if not et.startswith('notable-event'): continue temp = et.split('-',2) if len(temp) == 2: ne_type = "" else: ne_type = temp[-1] if restrict_netype is not None and restrict_netype != ne_type: continue ne_name = e.get('data','') if restrict_netype is None: key = (ne_type,ne_name) yield key,e['timestamp'],e['address'] else: key = ne_name yield key,e['timestamp'],e['address'] def add_analysis(self, label, callback): # called by custom protocols before graph window is created # graph window will read this list and use it to build a menu self.temp_analysis_menus += [(label, callback)] def projected_filter(self, data_filter): def pf(e): return logs.state_event_filter(e) and data_filter(e['data']) return pf _inproj = False # set_active triggers set_projection to be called recursively # _inproj is used to make that recursion fizzle out def set_projection_gui(self, widget, p): if self._inproj: return self._inproj = True print "set projection %s" % p # uncheck other projection menu options... for menu_name, checkitem in self.graph_window.projection_checkitems.items(): if p != menu_name: checkitem.set_active(False) else: checkitem.set_active(True) self.set_projection(p) self.graph_window.refresh_graph() self._inproj = False def set_projection(self, p): MicaTrace.set_projection(self,p) if hasattr(self,'graph_window'): self.graph_window.refresh_graph() # return subdata) for current projection def project(self, data): subdata = custom.project(self, self.projection, data) return subdata def add_cursor_listener(self, f): # TODO currently no way to remove cursor listeners self.cursor_listeners.append(f) f(self.get_current_i()) # close the window and quit def delete_event(self, widget, event, data=None): gtk.main_quit() return False def event_slider_changed(self, adj): self.set_current_i(self.get_current_slider_selection()) def get_current_slider_selection(self): return int(self.adj.value) # Set the current event def set_current_i(self, i): if self.current == i: return self.current = i self.update_selection() for l in self.cursor_listeners: l(i) self.dump_event(self.events[i]) # print event info to console when an event is selected def dump_event(self, e): if 'address' not in e: return addr = e['address'] state = self.current_node_state[addr] q = [ (0, ('root',state))] while q: i, (n,s) = q.pop() if s is None: s = {} #print "%s%s: %s" % (' '*i,n,s.get('stateType','(None)')) q += [(i+1,ls) for ls in logs.subprotocols(s)] def update_selection(self): # executed before cursor listeners self.reset_tree_selection() self.reset_slider_selection() def get_current_i(self): return self.current def get_current_event(self): return self.events[self.current] # Aperture is the range of events currently being drawn def get_aperture_events(self): start_event = max(0, self.current - 100) start_event = self.current return self.events[start_event:self.current+1] def reset_slider_selection(self): i = self.get_current_i() j = self.get_current_slider_selection() if i != j: self.adj.set_value(i) def reset_tree_selection(self): i = self.get_current_i() j = self.get_current_tree_selection() if i != j: path = "%s"%i self.tree_selection.select_path(path) # Returns (igraph, namemap) # where igraph is an igraph object with nodes and edges of the comm graph # and namemap maps address_string => graph vertex id def create_default_graph(self): if self.options['novis']: return None, None ual = self.unique_addresses g = igraph.Graph(directed=True) g.add_vertices(len(ual)) namemap = dict((n,i) for i,n in enumerate(ual)) matrix = logs.build_comm_matrix(ual,self.events) if matrix is None: # fall back to initial state view graph matrix = logs.build_final_view_matrix(ual,self.events, self.current_node_view) edges = list(logs.matrix_edge_generator(matrix)) g.add_edges(edges) return g, namemap def create_graph_window(self): graph, namemap = self.create_default_graph() self.graph_window = GraphWindow(self, graph, namemap) self.graph_window.window.show_all() def create_layers_window(self): self.layers_window = create_layers_window() # graph is an igraph instance # name_map is an igraph Layout def set_layout(self, graph, name_map): self.graph_window.igraph_drawing_area.set_graph(graph, name_map) self.graph_window.refresh_graph() def create_event_window(self): # Create a new window self.event_window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.event_window.set_title("Event Browser") self.event_window.set_size_request(500, 600) self.event_window.set_size_request(200, 200) self.event_window.connect("delete_event", self.delete_event) self.event_scrollwindow = gtk.ScrolledWindow() self.event_scrollwindow.set_border_width(10) self.event_scrollwindow.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS) self.event_vbox = gtk.VBox() self.event_vbox.pack_start(self.event_scrollwindow, True) self.treemodel = self.initialize_treemodel() # create the TreeView using treestore self.treeview = gtk.TreeView(self.treemodel) self.tree_selection = self.treeview.get_selection() self.tree_selection.set_mode(gtk.SELECTION_SINGLE) self.tree_selection.connect("changed",self.event_tree_selection_changed) # set up treeview popup menu treeview_popup = gtk.Menu() copy_item = gtk.MenuItem(label="Copy Event") copy_item.connect("activate",self.treeview_menu_copy_data) treeview_popup.append(copy_item) copy_item.show() self.treeview.connect_object("button_press_event", self.tree_button_press, treeview_popup) # create the TreeViewColumn to display the phdata self.timestamp_column = gtk.TreeViewColumn('Timestamp') self.address_column = gtk.TreeViewColumn('Address') self.event_type_column = gtk.TreeViewColumn('Type') self.data_column = gtk.TreeViewColumn('Data') # add columns to treeview self.treeview.append_column(self.timestamp_column) self.treeview.append_column(self.address_column) self.treeview.append_column(self.event_type_column) self.treeview.append_column(self.data_column) # create a CellRendererText to render the data self.cell = gtk.CellRendererText() # add the cell to the tvcolumn and allow it to expand self.timestamp_column.pack_start(self.cell, True) self.address_column.pack_start(self.cell, True) self.event_type_column.pack_start(self.cell, True) self.data_column.pack_start(self.cell, True) # set the cell "text" attribute to column 0 - retrieve text # from that column in treestore self.timestamp_column.add_attribute(self.cell, 'text', 0) self.address_column.add_attribute(self.cell, 'text', 1) self.event_type_column.add_attribute(self.cell, 'text', 2) self.data_column.add_attribute(self.cell, 'text', 3) # make it searchable self.treeview.set_search_column(0) # Allow sorting on the column self.timestamp_column.set_sort_column_id(0) self.address_column.set_sort_column_id(1) self.event_type_column.set_sort_column_id(2) self.data_column.set_sort_column_id(3) # Allow drag and drop reordering of rows self.treeview.set_reorderable(True) self.event_scrollwindow.add(self.treeview)
9, 10, 11, f1_gyro_x, f1_gyro_y, f1_gyro_z, # 12, 13, 14, f2_gyro_x, f2_gyro_y, f2_gyro_z, # 15, 16, 17, f3_gyro_x, f3_gyro_y, f3_gyro_z, # 18, 19, 20, f1_state_position, f1_state_speed, f1_state_effort, # 21, 22, 23, f2_state_position, f2_state_speed, f2_state_effort, # 24, 25, 26, f3_state_position, f3_state_speed, f3_state_effort] # 27, 28, 29, arm_labels = ['forces_x', 'forces_y', 'forces_z', 'net_force', 'torques_x', 'torques_y', 'torques_z', 'net_torque', 'joint_0_pos', 'joint_1_pos', 'joint_2_pos', 'joint_3_pos', 'joint_4_pos', 'joint_5_pos'] hand_labels = ['f1_acc_x', 'f1_acc_y', 'f1_acc_z', 'net_f1_acc', 'f2_acc_x', 'f2_acc_y', 'f2_acc_z', 'net_f2_acc', 'f3_acc_x', 'f3_acc_y', 'f3_acc_z', 'net_f3_acc', 'f1_gyro_x', 'f1_gyro_y', 'f1_gyro_z', 'f2_gyro_x', 'f2_gyro_y', 'f2_gyro_z', 'f3_gyro_x', 'f3_gyro_y', 'f3_gyro_z', 'f1_state_position', 'f1_state_speed', 'f1_state_effort', 'f2_state_position', 'f2_state_speed', 'f2_state_effort', 'f3_state_position', 'f3_state_speed', 'f3_state_effort'] # Apply filter to all the variables arm_variables_filtered = filter_variables(arm_variables, arm_filter_param) hand_variables_filtered = filter_variables(hand_variables, hand_filter_param) # ------------------------------------ Step 5: Plot Results ------------------------------------------------------- # # First select the kind of x-axis time that you want: (a) Original Time Stamps (b) human-readable time stamp # (a) Original Time Stamps # arm_time_ref = arm_time_stamp # arm_joints_time_ref = arm_joints_time_stamp # f1_state_time_ref = f1_state_time_stamp # f1_imu_time_ref = f1_imu_time_stamp # f2_state_time_ref = f2_state_time_stamp # f2_imu_time_ref = f2_imu_time_stamp # f3_state_time_ref = f3_state_time_stamp # f3_imu_time_ref = f3_imu_time_stamp # trial_events_time_ref = trial_events_time_stamp # (b) Human Readable Time Stamps arm_time_ref = arm_elapsed_time arm_joints_time_ref = arm_joints_elapsed_time f1_state_time_ref = f1_state_elapsed_time f1_imu_time_ref = f1_imu_elapsed_time f2_state_time_ref = f2_state_elapsed_time f2_imu_time_ref = f2_imu_elapsed_time f3_state_time_ref = f3_state_elapsed_time f3_imu_time_ref = f3_imu_elapsed_time trial_events_time_ref = trial_events_elapsed_time title = file + ' (Median Filter - Arm = ' + "{:.0f}".format(arm_filter_param) + \ ', Hand = ' + str(hand_filter_param) + ') ' + pdf_variable # ARM figures # Arm's Forces if pdf_variable == '1 - UR5e - (FT) Wrist Forces': broken_axes(plot_number, axrray, arm_time_ref, [arm_variables_filtered[0], arm_variables_filtered[1], arm_variables_filtered[2], arm_variables_filtered[3]], [arm_labels[0], arm_labels[1], arm_labels[2], arm_labels[3]], e, f, g, h, title, 'Force [N]', file_label, -20, 40) # Arm's Torques elif pdf_variable == '2 - UR5e - (FT) Wrist Torques': broken_axes(plot_number, axrray, arm_time_ref, [arm_variables_filtered[4], arm_variables_filtered[5], arm_variables_filtered[6], arm_variables_filtered[7]], [arm_labels[4], arm_labels[5], arm_labels[6], arm_labels[7]], e, f, g, h, title, 'Torque [Nm]', file_label, -2, 2) # Arm's Joints elif pdf_variable == '3 - UR5e - Joint Angular Positions': broken_axes(plot_number, axrray, arm_joints_time_ref, [arm_variables_filtered[8], arm_variables_filtered[9], arm_variables_filtered[10], arm_variables_filtered[11], arm_variables_filtered[12], arm_variables_filtered[13]], [arm_labels[8], arm_labels[9], arm_labels[10], arm_labels[11], arm_labels[12], arm_labels[13]], e, f, g, h, title, 'Angular Positions [rad]', file_label, -6, 6) # Finger 1's Joint States elif pdf_variable == '4 - Finger 1 - Joint States': broken_axes(plot_number, axrray, f1_state_time_ref, [hand_variables_filtered[21], hand_variables_filtered[22], hand_variables_filtered[23]], [hand_labels[21], hand_labels[22], hand_labels[23]], e, f, g, h, title, 'f1 - States', file_label, -500, 500) # Finger 1's accelerometers elif pdf_variable == '5 - Finger 1 - (IMU) Linear Acceleration': broken_axes(plot_number, axrray, f1_imu_time_ref, [hand_variables_filtered[0], hand_variables_filtered[1], hand_variables_filtered[2], hand_variables_filtered[3]], [hand_labels[0], hand_labels[1], hand_labels[2], hand_labels[3]], e, f, g, h, title, 'Linear Acceleration [g]', file_label, -30, 30) # Finger 1's Gyroscopes elif pdf_variable == '6 - Finger 1 - (IMU) Angular Velocity': broken_axes(plot_number, axrray, f1_imu_time_ref, [hand_variables_filtered[12], hand_variables_filtered[13], hand_variables_filtered[14]], [hand_labels[12], hand_labels[13], hand_labels[14]], e, f, g, h, title, 'Angular Velocity [deg/s]', file_label, -300, 300) # Finger 2's Joint States elif pdf_variable == '7 - Finger 2 - Joint States': broken_axes(plot_number, axrray, f2_state_time_ref, [hand_variables_filtered[24], hand_variables_filtered[25], hand_variables_filtered[26]], [hand_labels[24], hand_labels[25], hand_labels[26]], e, f, g, h, title, 'f2 - States', file_label, -500, 500) # Finger 2's Accelerometers elif pdf_variable == '8 - Finger 2 - (IMU) Linear Acceleration': broken_axes(plot_number, axrray, f2_imu_time_ref, [hand_variables_filtered[4], hand_variables_filtered[5], hand_variables_filtered[6], hand_variables_filtered[7]], [hand_labels[4], hand_labels[5], hand_labels[6], hand_labels[7]], e, f, g, h, title, 'Linear Acceleration [g]', file_label, -30, 30) # Finger 2's Gyroscopes elif pdf_variable == '9 - Finger 2 - (IMU) Angular Velocity': broken_axes(plot_number, axrray, f2_imu_time_ref, [hand_variables_filtered[15], hand_variables_filtered[16], hand_variables_filtered[17]], [hand_labels[15], hand_labels[16], hand_labels[17]], e, f, g, h, title, 'Angular Velocity [deg/s]', file_label, -300, 300) # Finger 3's Joint States elif pdf_variable == '10 - Finger 3 - Joint States': broken_axes(plot_number, axrray, f3_state_time_ref, [hand_variables_filtered[27], hand_variables_filtered[28], hand_variables_filtered[29]], [hand_labels[27], hand_labels[28], hand_labels[29]], e, f, g, h, title, 'f3 - States', file_label, -500, 500) # Finger 3's Accelerometers elif pdf_variable == '11 - Finger 3 - (IMU) Linear Acceleration': broken_axes(plot_number, axrray, f3_imu_time_ref, [hand_variables_filtered[8], hand_variables_filtered[9], hand_variables_filtered[10], hand_variables_filtered[11]], [hand_labels[8], hand_labels[9], hand_labels[10], hand_labels[11]], e, f, g, h, title, 'Linear Acceleration [g]', file_label, -30, 30) # Finger 3's Gyroscopes elif pdf_variable == '12 - Finger 3 - (IMU) Angular Velocity': broken_axes(plot_number, axrray, f3_imu_time_ref, [hand_variables_filtered[18], hand_variables_filtered[19], hand_variables_filtered[20]], [hand_labels[18], hand_labels[19], hand_labels[20]], e, f, g, h, title, 'Angular Velocity [deg/s]', file_label, -300, 300) # Experiment Events (e.g. Grasp, Pick) elif pdf_variable == '13 - Events during the experiment': states = [] for i in range(len(trial_events_states)): states.append(trial_events_states[i]) # print(trial_events_time_ref, '\n', states) broken_axes(plot_number, axrray, trial_events_time_ref, [states], 'events', e, f, g, h, title, 'Event', file_label, -1, 8) # plt.show() def look_at_labels(location, filename): """ Looks for the csv file of the bagfile, in order to read the labels from the metadata :param location: :param prefix: the name of the file :return: """ # --- Open the file with open(location + filename) as f: reader = csv.reader(f) data = list(reader) # print('Result of Pick was: ', data[1][10]) # --- Redefine label if data[1][10] == 's': result = '(Successful-Pick)' elif data[1][10] == 'f': result = '(Failed-Pick)' else: result = 'heads up... something is wrong' return result def net_value(var_x, var_y, var_z): """ Obtain the net value of a vector, given the 3 components :param var_x: :param var_y: :param var_z: :return: net value """ net = [None] * len(var_x) for i in range(len(var_x)): net[i] = math.sqrt(var_x[i] ** 2 + var_y[i] ** 2 + var_z[i] ** 2) return net def plot_features(plt, a, b, c, d, e, f, g, h, x_min, x_max, title, label, sigma): """ Add some common features into all the plots in order to ease their analysis, such as shaded areas and dashed lines :param x_max: :param x_min: :param plt: :param a: Time of the Open Hand Event :param b: Time of the Close Hand Event :param c: Time of the Pull Event :param d: Time of the Open Hand Event at the end :param e: Time of the Servos Start :param f: Time of the Servos Stop :param g: Time of the UR5 Start :param h: Time of the UR5 Stop :return: """ plt.legend() plt.xlim(x_min, x_max) xmin, xmax, ymin, ymax = plt.axis() plt.axvspan(a, b, color='y', alpha=0.3, lw=0) plt.annotate('Open hand', (a, 0.95 * ymin)) plt.axvspan(b, c, color='b', alpha=0.3, lw=0) plt.annotate('Close hand', (b, 0.95 * ymin)) plt.axvspan(c, d, color='r', alpha=0.3, lw=0) plt.annotate('Pull', (c, 0.95 * ymin)) plt.axvspan(d, xmax, color='g', alpha=0.3, lw=0) plt.annotate('Open hand', (d, 0.95 * ymin)) plt.axvline(x=e, color='k', linestyle='dashed') plt.annotate('F1 Servo STARTS moving', (e, 0.85 * ymin)) plt.axvline(x=f, color='k', linestyle=(0, (5, 10))) plt.annotate('F1 Servo STOPS moving', (f, 0.80 * ymin)) plt.axvline(x=g, color='k', linestyle='dotted') plt.annotate('UR5e STARTS moving', (g, 0.85 * ymin)) plt.axvline(x=h, color='k', linestyle=(0, (1, 10))) plt.annotate('UR5e STOPS moving', (h, 0.80 * ymin)) plt.annotate('sigma = ' + str(sigma), (xmin, ymax)) plt.xlabel('Elapsed time [sec]') plt.title(title + ' ' + f'$\\bf{label}$') plt.savefig('plots/' + title + '.png') if __name__ == '__main__': # --- List the variables for which you want to generate the pdfs variables = [ '1 - UR5e - (FT) Wrist Forces', '2 - UR5e - (FT) Wrist Torques', '3 - UR5e - Joint Angular Positions', '4 - Finger 1 - Joint States', '5 - Finger 1 - (IMU) Linear Acceleration', '6 - Finger 1 - (IMU) Angular Velocity', '7 - Finger 2 - Joint States', '8 - Finger 2 - (IMU) Linear Acceleration', '9 - Finger 2 - (IMU) Angular Velocity', '10 - Finger 3 - Joint States', '11 - Finger 3 - (IMU) Linear Acceleration', '12 - Finger 3 - (IMU) Angular Velocity', '13 - Events during the experiment' ] # --- Signal Filter parameters # Median Filter hand_filter_window = 3 # Have in mind that the Sampling Rate of the Hand was 70Hz arm_filter_window = int(hand_filter_window * 500 / 70) # Have in mind that the Sampling Rate of the Arm was 500Hz # --- Target label # Note: It has to be same as in function def look_at_labels labels = ['(Successful-Pick)', '(Failed-Pick)'] # labels = ['(Successful-Pick)'] # labels = ['(Failed-Pick)'] for label in labels: for pdf_variable in variables: # --- Step 1: Create PDF pdf_pages = PdfPages(str(pdf_variable) + ' ' + label + ' (Median Filter
temperature sensor", [636]), }, "CartilaginousAndOsseousChange": { "111309": ("Cartilaginous and osseous change", [6030, 6033]), }, "CaseSensitivity": { "111088": ("Case Sensitivity", [6048]), }, "CaseSpecificity": { "111090": ("Case Specificity", [6048]), }, "CassetteBasedProjectionRadiographySystem": { "113959": ("Cassette-based Projection Radiography System", [10032]), }, "Cast": { "130114": ("Cast", [7151, 7157, 7193, 9505, 9513, 9520, 9573]), }, "CathLabProcedureLog": { "121120": ("Cath Lab Procedure Log", [3400]), }, "CatheterCurve": { "122097": ("Catheter Curve", [3423]), }, "CatheterSize": { "122319": ("Catheter Size", []), }, "CatheterizationProcedurePhase": { "109057": ("Catheterization Procedure Phase", []), }, "Caudal10DegreeDistalCranioproximalOblique": { "123019": ("Caudal 10 degree distal-cranioproximal oblique", [7484]), }, "CavityExtentAsPercentOfVolume": { "112017": ("Cavity extent as percent of volume", [6142]), }, "CavityRadiationShield": { "130640": ("Cavity radiation shield", [9572]), }, "Center": { "111010": ("Center", [219]), }, "CenterOfGravity": { "122475": ("Center of Gravity", [3458]), }, "CenterOfMass": { "128138": ("Center of Mass", [1011]), }, "CenterOfRotation": { "130521": ("Center of Rotation", []), }, "CenterOfTableHead": { "128751": ("Center of Table Head", []), }, "Centerline": { "130490": ("Centerline", [219]), }, "CenterlineWallMotionAnalysis": { "122449": ("Centerline Wall Motion Analysis", []), }, "CentralBreathingPosition": { "122612": ("central breathing position", [3823]), }, "CentralLine": { "112174": ("Central line", [6102, 6138, 6404, 7151, 7193]), }, "Centrilobular": { "112156": ("Centrilobular", [6128]), }, "CentrilobularStructures": { "112087": ("Centrilobular structures", [6102, 6109, 6111, 7151, 7192, 9514]), }, "CertaintyOfFeature": { "111011": ("Certainty of Feature", []), }, "CertaintyOfFinding": { "111012": ("Certainty of Finding", [6048]), }, "CertaintyOfImpression": { "111013": ("Certainty of Impression", []), }, "CessationOfExercise": { "125237": ("Cessation of exercise", [12031]), }, "CessationOfStimulation": { "125239": ("Cessation of stimulation", [12031]), }, "Cetuximab89Zr": { "126513": ("Cetuximab ^89^Zr", [4021]), }, "Cg250FAb289Zr": { "126517": ("cG250-F(ab')(2) ^89^Zr", [4021]), }, "ChairOfProtocolCommittee": { "128671": ("Chair of Protocol Committee", [7450, 7452]), }, "ChangMethod": { "122721": ("Chang method", [3117]), }, "ChangeInPatientAnatomy": { "130464": ("Change in Patient Anatomy", [9565]), }, "ChangeOfProcedureForCorrectCharging": { "110509": ("Change of procedure for correct charging", [9300, 9301, 9303]), }, "CheckedInStatus": { "121388": ("Checked-In Status", []), }, "Checkerboard": { "114216": ("Checkerboard", [8202]), }, "ChestCADReport": { "112000": ("Chest CAD Report", []), }, "ChestTube": { "112173": ("Chest tube", [6102, 6138, 6202, 6203, 6404, 7151, 7193]), }, "ChiSquare": { "126221": ("Chi-square", [218, 7180, 7469]), }, "CholineC11": { "126703": ("Choline C^11^", [4021]), }, "CholineCreatineRatio": { "113081": ("Choline/Creatine Ratio", [218, 4032, 4033, 7180, 7186, 7469]), }, "ChoriocapillarisStructuralReflectanceMap": { "128274": ("Choriocapillaris structural reflectance map", [4271]), }, "ChoriocapillarisVasculatureFlow": { "128273": ("Choriocapillaris vasculature flow", [4271]), }, "ChoroidStructuralReflectanceMap": { "128276": ("Choroid structural reflectance map", [4271]), }, "ChoroidVasculatureFlow": { "128275": ("Choroid vasculature flow", [4271]), }, "ChromaticityEvaluation": { "109705": ("Chromaticity evaluation", [8300]), }, "CineFilmDigitized": { "110021": ("Cine Film Digitized", [7008]), }, "Cinefluorography": { "CF": ("Cinefluorography", []), }, "CircadianEffects": { "127050": ("Circadian effects", []), }, "CircleBScanPattern": { "128284": ("Circle B-scan pattern", [4272]), }, "CircleRadialBScanPattern": { "128287": ("Circle-radial B-scan pattern", [4272]), }, "CircleRasterBScanPattern": { "128286": ("Circle-raster B-scan pattern", [4272]), }, "CircularMethod": { "122473": ("Circular method", [3470]), }, "Circulating": { "121100": ("Circulating", []), }, "CirculatorySupport": { "122138": ("Circulatory Support", []), }, "Circumscribed": { "112142": ("Circumscribed", []), }, "ClassActivation": { "130402": ("Class activation", [217, 218, 7180, 7469]), }, "CleanDescriptorsOption": { "113105": ("Clean Descriptors Option", [7050]), }, "CleanGraphicsOption": { "113103": ("Clean Graphics Option", [7050]), }, "CleanPixelDataOption": { "113101": ("Clean Pixel Data Option", [7050]), }, "CleanRecognizableVisualFeaturesOption": { "113102": ("Clean Recognizable Visual Features Option", [7050]), }, "CleanStructuredContentOption": { "113104": ("Clean Structured Content Option", [7050]), }, "ClinicalContext": { "122127": ("Clinical Context", []), }, "ClinicalEvaluation": { "109710": ("Clinical evaluation", [8300]), }, "ClinicalFinding": { "111402": ("Clinical finding", [6051]), }, "ClinicalInterpretation": { "122147": ("Clinical Interpretation", []), }, "ClinicalTrialSubmissionInputUsed": { "128223": ("Clinical Trial Submission Input Used", [7010]), }, "ClockfaceOrRegion": { "111014": ("Clockface or region", []), }, "ClusterAnalysis": { "123107": ("Cluster Analysis", [7162]), }, "ClusterProminenceOfGLCM": { "128797": ("Cluster Prominence of GLCM", []), }, "ClusterShadeOfGLCM": { "128796": ("Cluster Shade of GLCM", []), }, "ClusterTendencyOfGLCM": { "128795": ("Cluster Tendency of GLCM", []), }, "ClusteredMicrocysts": { "111129": ("Clustered microcysts", [6054, 6064]), }, "CmabU3689Zr": { "126746": ("cMAb U36 ^89^Zr", [4021]), }, "CoachingDevice": { "130650": ("Coaching Device", [9573, 9578]), }, "Coalescent": { "112157": ("Coalescent", [6128]), }, "CockroftGaultFormulaEstimationOfGFR": { "113570": ("Cockroft-Gault Formula estimation of GFR", [10047]), }, "CoilMarker": { "129301": ("Coil Marker", [7111, 7112]), }, "CoilPlacementConcern": { "130571": ("Coil placement concern", [6314]), }, "CoilSelectionConcern": { "130572": ("Coil selection concern", [6314]), }, "Coin": { "112178": ("Coin", [6102, 6138, 6202, 6203, 6404, 7151, 7193]), }, "CollectionOfPresentationStates": { "113022": ("Collection of Presentation States", [7010]), }, "CollimatedFieldArea": { "113790": ("Collimated Field Area", []), }, "CollimatedFieldHeight": { "113788": ("Collimated Field Height", []), }, "CollimatedFieldWidth": { "113789": ("Collimated Field Width", []), }, "CollimationTooCloseToBreast": { "111195": ("Collimation too close to breast", [6041]), }, "Collimator": { "111173": ("Collimator", []), }, "CollisionChecks": { "130652": ("Collision Checks", [9577]), }, "ColonCADReport": { "112220": ("Colon CAD Report", []), }, "ColonOverallAssessment": { "112222": ("Colon Overall Assessment", []), }, "ColorFlowDoppler": { "CD": ("Color flow Doppler", []), }, "ColumnAngulation": { "113770": ("Column Angulation", []), }, "CombinationImplant": { "111484": ("Combination implant", [6058, 6059]), }, "CombinedPosteriorEnhancementAndShadowing": { "111370": ("Combined posterior enhancement and shadowing", [6155]), }, "CombinedStructuredLightThermalImager": { "130648": ("Combined Structured Light/Thermal Imager", [9573, 9575]), }, "Comment": { "121106": ("Comment", [12101]), }, "CompactFlash": { "110034": ("Compact Flash", [405]), }, "ComparativeAverage10YearCHDRisk": { "122231": ("Comparative Average10 Year CHD Risk", [3667]), }, "ComparativeLow10YearCHDRisk": { "122232": ("Comparative Low10 Year CHD Risk", [3667]), }, "ComparisonToPreviousExams": { "111424": ("Comparison to previous exams", [6052, 6053]), }, "ComparisonToPreviousFindings": { "111424": ("Comparison to previous findings", []), }, "ComparisonWithPriorExamDone": { "122140": ("Comparison with Prior Exam Done", []), }, "CompleteAcquisitionContent": { "113034": ("Complete Acquisition Content", [7010]), }, "CompleteRenderingForPresentation": { "121332": ("Complete Rendering for Presentation", [7006]), }, "CompleteStudyContent": { "113032": ("Complete Study Content", [7010]), }, "CompletelyEncapsulated": { "130594": ("Completely encapsulated", [6335, 6341, 6342]), }, "Complex": { "111363": ("Complex", [6154]), }, "ComplexCyst": { "111460": ("Complex cyst", [6054, 6064]), }, "ComplicatedCyst": { "111130": ("Complicated cyst", [6054, 6064]), }, "Complications": { "121113": ("Complications", []), }, "ComponentConnection": { "112350": ("Component Connection", []), }, "ComponentID": { "112347": ("Component ID", []), }, "ComponentModel": { "129011": ("Component Model", [7062]), }, "ComponentType": { "112370": ("Component Type", []), }, "ComponentVolume": { "130239": ("Component Volume", []), }, "ComposedFromPriorDoses": { "121370": ("Composed from prior doses", [7220]), }, "ComposedFromPriorDosesAndCurrentPlan": { "121371": ("Composed from prior doses and current plan", [7220]), }, "CompositeFeature": { "111015": ("Composite Feature", []), }, "CompositeFeatureModifier": { "112023": ("Composite Feature Modifier", []), }, "CompositeType": { "111016": ("Composite type", []), }, "CompoundStatement": { "122150": ("Compound Statement", []), }, "CompressionContactArea": { "111649": ("Compression Contact Area", []), }, "CompressionForce": { "111647": ("Compression Force", []), }, "CompressionPressure": { "111648": ("Compression Pressure", []), }, "CompressionThickness": { "111633": ("Compression Thickness", []), }, "ComputationServer": { "COMP": ("Computation Server", [30]), }, "ComputedFromImageAttributes": { "113867": ("Computed From Image Attributes", [10020, 10021]), }, "ComputedRadiography": { "CR": ("Computed Radiography", [29, 30, 33]), }, "ComputedTomography": { "CT": ("Computed Tomography", [29, 30, 33]), }, "ComputerAidedDetection": { "110004": ("Computer Aided Detection", [9231]), }, "ComputerAidedDiagnosis": { "110003": ("Computer Aided Diagnosis", [9231]), }, "ComputerAssistedDetectionDiagnosis": { "CAD": ("Computer Assisted Detection/Diagnosis", [30]), }, "Concentration": { "122093": ("Concentration", [3410]), }, "ConcentricCircleBScanPattern": { "128285": ("Concentric circle B-scan pattern", [4272]), }, "Concern": { "121430": ("Concern", []), }, "Conclusion": { "121077": ("Conclusion", [6053, 7002]), }, "Conclusions": { "121076": ("Conclusions", []), }, "ConditionEffectiveDoseMeasured": { "113816": ("Condition Effective Dose measured", []), }, "ConePresent": { "130457": ("Cone Present", []), }, "Conepresent": { "130457": ("ConePresent", [9564]), }, "ConfirmationOfTarget": { "111442": ("Confirmation of target", []), }, "ConfocalImaging": { "114207": ("Confocal imaging", [8201]), }, "ConformalArcBeam": { "130104": ("Conformal Arc Beam", [9511, 9524]), }, "ConformalityShell": { "130062": ("Conformality Shell", [9535]), }, "ConjunctiveTerm": { "122154": ("Conjunctive Term", []), }, "ConnectedImplantationPlanComponent": { "112374": ("Connected Implantation Plan Component", []), }, "ConsistentWithLabelingOfTheDevice": { "128602": ("Consistent with labeling of the device", [800]), }, "ConstantAngleAcquisition": { "113805": ("Constant Angle Acquisition", [10013]), }, "ConsultationWith": { "122044": ("Consultation With", [3404]), }, "ConsumableCatheterType": { "130257": ("Consumable Catheter Type", []), }, "ConsumableIsNew": { "130224": ("Consumable is New", []), }, "ConsumableReturnedToInventory": { "122077": ("Consumable returned to inventory", [3408]), }, "ConsumableTakenFromInventory": { "122076": ("Consumable taken from inventory", [3408]), }, "ConsumableUnusable": { "122079": ("Consumable unusable", [3408]), }, "ContentAssessmentResult": { "ASMT": ("Content Assessment Result", [32, 33]), }, "ContentDate": { "111018": ("Content Date", []), }, "ContentTime": { "111019": ("Content Time", []),
""" General components. """ # Copyright (c) 2019 <NAME>. All rights reserved. from typing import Tuple, List, Union, Callable import numpy as np import trimesh from modeling import util from modeling.types import Point3, Vec3, Verts2D, Verts, Faces, Mesh, MeshExtended def surface_revolution( xy_points: np.ndarray, angle: float, close_rev: bool, close_fn: bool, subdivisions: int) -> Mesh: """create a surface of revolution by rotating xy points around the y axis""" # TODO: handle zero points properly without duplicating them # pylint: disable=too-many-locals # for now, only the y axis # y axis remains fixed, x is modified and z is added n_points = xy_points.shape[0] # add points for the final subdivision if isn't a full revolution max_sub = subdivisions + 1 if angle < (np.pi * 2.0) else subdivisions # for now, just lay them out in a line points_list = [] for x_val in range(0, max_sub): theta = angle * x_val / subdivisions x_dim = xy_points[:, 0] * np.cos(theta) y_dim = xy_points[:, 1] z_dim = xy_points[:, 0] * np.sin(theta) points_list.append( np.column_stack((x_dim, y_dim, z_dim))) # connect corresponding pairs of points with a face faces_list = [] idxs_sub = list(range(0, max_sub)) if close_rev: idxs_sub.append(0) idxs_vert = list(range(0, n_points)) if close_fn: idxs_vert.append(0) for idx_sub_a, idx_sub_b in zip(idxs_sub[:-1], idxs_sub[1:]): for idx_vert_a, idx_vert_b in zip(idxs_vert[:-1], idxs_vert[1:]): offset_a = idx_sub_a * n_points offset_b = idx_sub_b * n_points faces_list.append( [offset_a + idx_vert_a, offset_a + idx_vert_b, offset_b + idx_vert_a]) faces_list.append( [offset_b + idx_vert_a, offset_a + idx_vert_b, offset_b + idx_vert_b]) # TODO: some degenerate faces are produced here I think return np.vstack(points_list), np.vstack(faces_list) def close_face(idxs_points: List[int], idx_center: int) -> Faces: """generate triangles to link an ordered set of points to a center point""" # TODO: rewrite as "close_face_loop" idxs_vert = list(idxs_points) idxs_vert.append(idxs_vert[0]) faces_list = [] for idx_vert_a, idx_vert_b in zip(idxs_vert[:-1], idxs_vert[1:]): faces_list.append((idx_center, idx_vert_a, idx_vert_b)) return np.vstack(faces_list) def close_face_noloop(idxs_points: List[int], idx_center: int) -> Faces: """generate triangles to link an ordered set of points to a center point""" idxs_vert = list(idxs_points) faces_list = [] for idx_vert_a, idx_vert_b in zip(idxs_vert[:-1], idxs_vert[1:]): faces_list.append((idx_center, idx_vert_a, idx_vert_b)) return np.vstack(faces_list) def verts_quad(idxs: Union[List[int], np.ndarray]) -> Faces: """make a quad (two triangles) from indices""" return np.vstack(( idxs[0:3], (idxs[2], idxs[3], idxs[0]))) def tri_normal(verts: Union[List[Point3], Verts]) -> Vec3: """find the surface normal of a triangle""" seg_0 = verts[1] - verts[0] seg_1 = verts[2] - verts[0] res = np.cross(seg_0, seg_1) return res / np.linalg.norm(res) def tri_area(verts: Union[List[Point3], Verts]) -> Vec3: """find the area of a triangle""" seg_0 = verts[1] - verts[0] seg_1 = verts[2] - verts[0] return 0.5 * np.linalg.norm(np.cross(seg_0, seg_1)) def is_triangle_pair_convex( a: Point3, b: Point3, c: Point3, d: Point3) -> bool: """test whether a pair of triangles (abc, adb) are convex or concave.""" norm_0 = tri_normal([a, b, c]) norm_1 = tri_normal([a, d, b]) rot = np.cross(norm_0, norm_1) shared_edge = b - a return np.dot(rot, shared_edge) > 0 def quad_verts(quad_idxs: Faces) -> List[int]: """convert a quad back to vert indcices""" return [quad_idxs[0, 0], quad_idxs[0, 1], quad_idxs[0, 2], quad_idxs[1, 1]] def cylinder(length: float, radius: float, subdivisions: int) -> Mesh: """cylinder with closed caps""" half_length = length / 2.0 outline = np.array([ [radius, -half_length], [radius, half_length] ]) curve_verts, curve_faces = surface_revolution( outline, np.pi * 2.0, True, False, subdivisions) center_0 = np.array([[0.0, -half_length, 0.0]]) center_1 = np.array([[0.0, half_length, 0.0]]) center_0_idx = curve_verts.shape[0] center_1_idx = curve_verts.shape[0] + 1 cap_0_idxs = range(0, subdivisions * 2, 2) cap_1_idxs = range(1, subdivisions * 2, 2) cap_0_faces = close_face(cap_0_idxs, center_0_idx) cap_1_faces = close_face(cap_1_idxs[::-1], center_1_idx) return ( np.concatenate((curve_verts, center_0, center_1), axis=0), np.concatenate((curve_faces, cap_0_faces, cap_1_faces), axis=0)) def curved_plate( length: float, radius_outer_0: float, radius_inner_0: float, radius_outer_1: float, radius_inner_1: float, angle: float, chamfer_x: float, chamfer_y: float, subdivisions: int) -> Mesh: """create a curved plate""" # pylint: disable=too-many-arguments # pylint: disable=too-many-locals # make a surface of revolution and cap the ends half_length = length / 2.0 outline = np.array([ [radius_inner_0, -half_length], [radius_outer_0, -half_length + chamfer_y], [radius_outer_1, half_length - chamfer_y], [radius_inner_1, half_length] ]) verts, faces = surface_revolution(outline, angle, False, True, subdivisions) # TODO: chamfers could be done more efficiently if chamfer_x > 0: # TODO: it seems like this should still work with double-ended plates # angle_x = 2.0 * chamfer_x / radius_outer_0 angle_x = 2.0 * np.arcsin(chamfer_x / 2.0 / radius_outer_0) print("chamfer angle 0:", angle_x * 180 / np.pi) verts_tightened, _ = surface_revolution( outline, angle - 2.0 * angle_x, False, True, subdivisions) verts_tightened = np.dot(verts_tightened, util.rotation_y(angle_x)) idxs_0 = range(1, verts.shape[0], 4) verts[idxs_0, :] = verts_tightened[idxs_0, :] # angle_x = 2.0 * chamfer_x / radius_outer_1 angle_x = 2.0 * np.arcsin(chamfer_x / 2.0 / radius_outer_1) print("chamfer angle 1:", angle_x * 180 / np.pi) verts_tightened, _ = surface_revolution( outline, angle - 2.0 * angle_x, False, True, subdivisions) verts_tightened = np.dot(verts_tightened, util.rotation_y(angle_x)) idxs_1 = range(2, verts.shape[0], 4) verts[idxs_1, :] = verts_tightened[idxs_1, :] cap_0_idxs = np.array([3, 2, 1, 0]) cap_1_idxs = subdivisions * 4 + np.array([0, 1, 2, 3]) return verts, np.concatenate( (faces, verts_quad(cap_0_idxs), verts_quad(cap_1_idxs))) def compound_radius_plate( length: float, radius_inner_0: float, radius_inner_1: float, thickness: float, angle: float, chamfer_x: float, chamfer_y: float, subdivisions: int) -> Mesh: """create a curved plate with a different radius at each end""" # pylint: disable=too-many-arguments # pylint: disable=too-many-locals # make a surface of revolution and cap the ends half_length = length / 2.0 compound_angle = np.arctan((radius_inner_1 - radius_inner_0) / length) chamfer_y_y = chamfer_y * np.cos(compound_angle) chamfer_y_x = chamfer_y * np.sin(compound_angle) thickness_x = thickness * np.cos(compound_angle) thickness_y = 0.0 - thickness * np.sin(compound_angle) print(thickness_x, thickness_y) outline = np.array([ [radius_inner_0, -half_length], [ radius_inner_0 + thickness_x + chamfer_y_x, -half_length + thickness_y + chamfer_y_y ], [ radius_inner_1 + thickness_x - chamfer_y_x, half_length + thickness_y - chamfer_y_y ], [radius_inner_1, half_length] ]) verts, faces = surface_revolution( outline, angle, False, True, # True subdivisions) # TODO: chamfers could be done more efficiently if chamfer_x > 0: # TODO: it seems like this should still work with double-ended plates # angle_x = 2.0 * chamfer_x / radius_outer_0 angle_x = 2.0 * np.arcsin(chamfer_x / 2.0 / (radius_inner_0 + thickness)) print("chamfer angle 0:", angle_x * 180 / np.pi) verts_tightened, _ = surface_revolution( outline, angle - 2.0 * angle_x, False, True, subdivisions) verts_tightened = np.dot(verts_tightened, util.rotation_y(angle_x)) idxs_0 = range(1, verts.shape[0], 4) verts[idxs_0, :] = verts_tightened[idxs_0, :] # angle_x = 2.0 * chamfer_x / radius_outer_1 angle_x = 2.0 * np.arcsin(chamfer_x / 2.0 / (radius_inner_1 + thickness)) print("chamfer angle 1:", angle_x * 180 / np.pi) verts_tightened, _ = surface_revolution( outline, angle - 2.0 * angle_x, False, True, subdivisions) verts_tightened = np.dot(verts_tightened, util.rotation_y(angle_x)) idxs_1 = range(2, verts.shape[0], 4) verts[idxs_1, :] = verts_tightened[idxs_1, :] cap_0_idxs = np.array([3, 2, 1, 0]) cap_1_idxs = subdivisions * 4 + np.array([0, 1, 2, 3]) return verts, np.concatenate( (faces, verts_quad(cap_0_idxs), verts_quad(cap_1_idxs))) def circular_plating_mesh( plate_mesh_by_angle: Callable, angle_plate_total: float, angle_gap: float, num_plates: int) -> Mesh: """create a mesh for circular plating""" angle_plate = angle_plate_total / num_plates print(angle_plate * 180.0 / np.pi) plate = plate_mesh_by_angle(angle_plate - angle_gap) plates = [] for x_val in range(num_plates): angle = x_val * angle_plate - 0.5 * angle_gap plates.append(util.rotate_mesh(plate, util.rotation_y(angle))) return util.concat(plates) def box_mesh(x_extent: float, y_extent: float, z_extent: float) -> Mesh: """create a box mesh""" # wrapper around trimesh interface # TODO: my own implementation of this would be nice box = trimesh.primitives.Box(extents=(x_extent, y_extent, z_extent)).to_mesh() return box.vertices, box.faces def link(idxs_0: List[int], idxs_1: List[int]) -> Faces: """generate faces that link two corresponding sets of vertices""" assert len(idxs_0) == len(idxs_1) idxs = list(range(len(idxs_0))) faces_list = [] for idx_a, idx_b in zip(idxs[:-1], idxs[1:]): # for now we want to assume that the new faces we are making are convex # so adding some extra logic # we could always make a version that doesn't do this faces_list.append( verts_quad([idxs_0[idx_a], idxs_0[idx_b], idxs_1[idx_b], idxs_1[idx_a]])) return np.concatenate(faces_list, axis=0) def link_map(idxs_0: List[int], idxs_1: List[int], mapping: List[Tuple]) -> Faces: """generate faces that link two corresponding sets of vertices""" faces_list = [] for idx in range(len(mapping)): m_0, m_1 = mapping[idx] if isinstance(m_0, int): one, many = m_0, m_1 v_i_a, v_i_b = idxs_0, idxs_1 elif isinstance(m_1, int): many, one = m_0, m_1 v_i_b, v_i_a = idxs_0, idxs_1 # TODO: the case where we have two single indices later # TODO: this might be backward # create a triangle
<reponame>vsevolodpohvalenko/home-assistant """Click-based interface for Songpal.""" import ast import asyncio import json import logging import sys from functools import update_wrapper import click from songpal import Device, SongpalException from songpal.common import ProtocolType from songpal.containers import Setting from songpal.discovery import Discover from songpal.group import GroupControl class OnOffBoolParamType(click.ParamType): name = "boolean" def convert(self, value, param, ctx): if value == "on": return True elif value == "off": return False else: return click.BOOL.convert(value, param, ctx) ONOFF_BOOL = OnOffBoolParamType() def err(msg): """Pretty-print an error.""" click.echo(click.style(msg, fg="red", bold=True)) def coro(f): """Run a coroutine and handle possible errors for the click cli. Source https://github.com/pallets/click/issues/85#issuecomment-43378930 """ f = asyncio.coroutine(f) def wrapper(*args, **kwargs): loop = asyncio.get_event_loop() try: return loop.run_until_complete(f(*args, **kwargs)) except KeyboardInterrupt: click.echo("Got CTRL+C, quitting..") dev = args[0] loop.run_until_complete(dev.stop_listen_notifications()) except SongpalException as ex: err("Error: %s" % ex) if len(args) > 0 and hasattr(args[0], "debug"): if args[0].debug > 0: raise ex return update_wrapper(wrapper, f) async def traverse_settings(dev, module, settings, depth=0): """Print all available settings.""" for setting in settings: if setting.is_directory: print("%s%s (%s)" % (depth * " ", setting.title, module)) return await traverse_settings(dev, module, setting.settings, depth + 2) else: try: print_settings([await setting.get_value(dev)], depth=depth) except SongpalException as ex: err("Unable to read setting %s: %s" % (setting, ex)) continue def print_settings(settings, depth=0): """Print all available settings of the device.""" # handle the case where a single setting is passed if isinstance(settings, Setting): settings = [settings] for setting in settings: cur = setting.currentValue print( "%s* %s (%s, value: %s, type: %s)" % ( " " * depth, setting.title, setting.target, click.style(cur, bold=True), setting.type, ) ) for opt in setting.candidate: if not opt.isAvailable: logging.debug("Unavailable setting %s", opt) continue click.echo( click.style( "%s - %s (%s)" % (" " * depth, opt.title, opt.value), bold=opt.value == cur, ) ) pass_dev = click.make_pass_decorator(Device) @click.group(invoke_without_command=False) @click.option("--endpoint", envvar="SONGPAL_ENDPOINT", required=False) @click.option("-d", "--debug", default=False, count=True) @click.option("--post", is_flag=True, required=False) @click.option("--websocket", is_flag=True, required=False) @click.pass_context @click.version_option() @coro async def cli(ctx, endpoint, debug, websocket, post): """Songpal CLI.""" lvl = logging.INFO if debug: lvl = logging.DEBUG click.echo("Setting debug level to %s" % debug) logging.basicConfig(level=lvl) if ctx.invoked_subcommand == "discover": ctx.obj = {"debug": debug} return if endpoint is None: err("Endpoint is required except when with 'discover'!") return protocol = None if post and websocket: err("You can force either --post or --websocket") return elif websocket: protocol = ProtocolType.WebSocket elif post: protocol = ProtocolType.XHRPost logging.debug("Using endpoint %s", endpoint) x = Device(endpoint, force_protocol=protocol, debug=debug) try: await x.get_supported_methods() except SongpalException as ex: err("Unable to get supported methods: %s" % ex) sys.exit(-1) ctx.obj = x # this causes RuntimeError: This event loop is already running # if ctx.invoked_subcommand is None: # ctx.invoke(status) @cli.command() @pass_dev @coro async def status(dev: Device): """Display status information.""" power = await dev.get_power() click.echo(click.style("%s" % power, bold=bool(power))) vol = await dev.get_volume_information() click.echo(vol.pop()) play_info = await dev.get_play_info() if not play_info.is_idle: click.echo("Playing %s" % play_info) else: click.echo("Not playing any media") outs = await dev.get_inputs() for out in outs: if out.active: click.echo("Active output: %s" % out) sysinfo = await dev.get_system_info() click.echo("System information: %s" % sysinfo) @cli.command() @coro @click.pass_context async def discover(ctx): """Discover supported devices.""" TIMEOUT = 5 async def print_discovered(dev): pretty_name = "%s - %s" % (dev.name, dev.model_number) click.echo(click.style("\nFound %s" % pretty_name, bold=True)) click.echo("* API version: %s" % dev.version) click.echo("* Endpoint: %s" % dev.endpoint) click.echo(" Services:") for serv in dev.services: click.echo(" - Service: %s" % serv) click.echo("\n[UPnP]") click.echo("* URL: %s" % dev.upnp_location) click.echo("* UDN: %s" % dev.udn) click.echo(" Services:") for serv in dev.upnp_services: click.echo(" - Service: %s" % serv) click.echo("Discovering for %s seconds" % TIMEOUT) await Discover.discover(TIMEOUT, ctx.obj["debug"] or 0, callback=print_discovered) @cli.command() @click.argument("cmd", required=False) @click.argument("target", required=False) @click.argument("value", required=False) @pass_dev @coro async def power(dev: Device, cmd, target, value): """Turn on and off, control power settings. Accepts commands 'on', 'off', and 'settings'. """ async def try_turn(cmd): state = True if cmd == "on" else False try: return await dev.set_power(state) except SongpalException as ex: if ex.code == 3: err("The device is already %s." % cmd) else: raise ex if cmd == "on" or cmd == "off": click.echo(await try_turn(cmd)) elif cmd == "settings": settings = await dev.get_power_settings() print_settings(settings) elif cmd == "set" and target and value: click.echo(await dev.set_power_settings(target, value)) else: power = await dev.get_power() click.echo(click.style(str(power), bold=bool(power))) @cli.command() @click.option("--output", type=str, required=False) @click.argument("input", required=False) @pass_dev @coro async def input(dev: Device, input, output): """Get and change outputs.""" inputs = await dev.get_inputs() if input: click.echo("Activating %s" % input) try: input = next((x for x in inputs if x.title == input)) except StopIteration: click.echo("Unable to find input %s" % input) return zone = None if output: zone = await dev.get_zone(output) if zone.uri not in input.outputs: click.echo("Input %s not valid for zone %s" % (input.title, output)) return await input.activate(zone) else: click.echo("Inputs:") for input in inputs: act = False if input.active: act = True click.echo(" * " + click.style(str(input), bold=act)) for out in input.outputs: click.echo(" - %s" % out) @cli.command() @click.argument("zone", required=False) @click.argument("activate", required=False, type=ONOFF_BOOL) @pass_dev @coro async def zone(dev: Device, zone, activate): """Get and change outputs.""" if zone: zone = await dev.get_zone(zone) click.echo("%s %s" % ("Activating" if activate else "Deactivating", zone)) await zone.activate(activate) else: click.echo("Zones:") for zone in await dev.get_zones(): act = False if zone.active: act = True click.echo(" * " + click.style(str(zone), bold=act)) @cli.command() @click.argument("target", required=False) @click.argument("value", required=False) @pass_dev @coro async def googlecast(dev: Device, target, value): """Return Googlecast settings.""" if target and value: click.echo("Setting %s = %s" % (target, value)) await dev.set_googlecast_settings(target, value) print_settings(await dev.get_googlecast_settings()) @cli.command() @click.argument("scheme", required=False) @pass_dev @coro async def source(dev: Device, scheme: str): """List available sources. If no `scheme` is given, will list sources for all sc hemes. """ if scheme is None: all_schemes = await dev.get_schemes() schemes = [str(scheme.scheme) for scheme in all_schemes] else: schemes = [scheme] for schema in schemes: try: sources = await dev.get_source_list(schema) except SongpalException as ex: click.echo("Unable to get sources for %s: %s" % (schema, ex)) continue for src in sources: click.echo(src) if src.isBrowsable: try: count = await dev.get_content_count(src.source) if count.count > 0: click.echo(" %s" % count) for content in await dev.get_contents(src.source): click.echo(" %s\n\t%s" % (content.title, content.uri)) else: click.echo(" No content to list.") except SongpalException as ex: click.echo(" %s" % ex) @cli.command() @click.option("--output", type=str, required=False) @click.argument("volume", required=False) @pass_dev @coro async def volume(dev: Device, volume, output): """Get and set the volume settings. Passing 'mute' as new volume will mute the volume, 'unmute' removes it. """ vol = None vol_controls = await dev.get_volume_information() if output is not None: click.echo("Using output: %s" % output) output_uri = (await dev.get_zone(output)).uri for v in vol_controls: if v.output == output_uri: vol = v break else: vol = vol_controls[0] if vol is None: err("Unable to find volume controller: %s" % output) return if volume and volume == "mute": click.echo("Muting") await vol.set_mute(True) elif volume and volume == "unmute": click.echo("Unmuting") await vol.set_mute(False) elif volume: click.echo("Setting volume to %s" % volume) await vol.set_volume(volume) if output is not None: click.echo(vol) else: for ctl in vol_controls: click.echo(ctl) @cli.command() @pass_dev @coro async def schemes(dev: Device): """Print supported uri schemes.""" schemes = await dev.get_schemes() for scheme in schemes: click.echo(scheme) @cli.command() @click.option("--internet", is_flag=True, default=True) @click.option("--update", is_flag=True, default=False) @pass_dev @coro async def check_update(dev: Device, internet: bool, update: bool): """Print out update information.""" if internet: print("Checking updates from network") else: print("Not checking updates from internet") update_info = await dev.get_update_info(from_network=internet) if not update_info.isUpdatable: click.echo("No updates available.") return if not update: click.echo("Update available: %s" % update_info) click.echo("Use --update to activate update!") else: click.echo("Activating update, please be seated.") res = await dev.activate_system_update() click.echo("Update result: %s" % res) @cli.command() @click.argument("target", required=False) @click.argument("value", required=False) @pass_dev @coro async def bluetooth(dev: Device, target, value): """Get or set bluetooth settings.""" if target and value: await dev.set_bluetooth_settings(target, value) print_settings(await dev.get_bluetooth_settings()) @cli.command() @pass_dev @coro async def sysinfo(dev: Device): """Print out system information (version, MAC addrs).""" click.echo(await dev.get_system_info()) click.echo(await dev.get_interface_information()) @cli.command() @pass_dev @coro async def misc(dev: Device): """Print miscellaneous settings.""" print_settings(await dev.get_misc_settings()) @cli.command() @pass_dev @coro async def settings(dev: Device): """Print out all possible settings.""" settings_tree = await dev.get_settings() for module in settings_tree: await traverse_settings(dev, module.usage, module.settings) @cli.command() @pass_dev @coro async def storage(dev: Device): """Print storage information.""" storages = await dev.get_storage_list() for storage in storages: click.echo(storage) @cli.command() @click.argument("target", required=False) @click.argument("value", required=False) @pass_dev @coro async def sound(dev: Device, target, value): """Get or set sound settings.""" if target and value: click.echo("Setting %s to %s" % (target, value)) click.echo(await dev.set_sound_settings(target, value)) print_settings(await dev.get_sound_settings()) @cli.command() @pass_dev @click.argument("soundfield", required=False) @coro async def soundfield(dev: Device, soundfield: str): """Get or set sound field.""" if soundfield is not None: await dev.set_sound_settings("soundField", soundfield) soundfields = await dev.get_sound_settings("soundField") print_settings(soundfields) @cli.command() @pass_dev @coro async def eq(dev: Device): """Return EQ information.""" click.echo(await dev.get_custom_eq()) @cli.command() @click.argument("cmd", required=False) @click.argument("target", required=False) @click.argument("value", required=False) @pass_dev @coro async def playback(dev: Device, cmd, target, value): """Get and set playback settings, e.g. repeat and shuffle..""" if target and value: dev.set_playback_settings(target, value) if cmd == "support": click.echo("Supported playback functions:") supported = await dev.get_supported_playback_functions("storage:usb1") for i in
mp.get_hist_n_bins(fh,i) self.hist_list[-1].n_events = mp.get_hist_n_events(fh,i) self.hist_list[-1].fs_per_bin = mp.get_hist_fs_per_bin(fh,i) self.hist_list[-1].s_per_bin = mp.get_hist_sec_per_bin(fh,i) self.hist_list[-1].t0_ps = mp.get_hist_t0_ps(fh,i) self.hist_list[-1].t0_bin = mp.get_hist_t0_bin(fh,i) self.hist_list[-1].good_bin1 = mp.get_hist_good_bin1(fh,i) self.hist_list[-1].good_bin2 = mp.get_hist_good_bin2(fh,i) self.hist_list[-1].background1 = mp.get_hist_background1(fh,i) self.hist_list[-1].background2 = mp.get_hist_background2(fh,i) try: self.hist_list[-1].title = str(mp.get_hist_title(fh,i)) except UnicodeEncodeError: self.hist_list[-1].title = mp.get_hist_title(fh,i) # Read scalers #~ n_scaler = mp.get_scalers(fh)[1] #~ self.scaler_list = [] #~ for i in range(1,n_scaler+1): #~ self.scaler_list.append(bscaler()) #~ self.scaler_list[-1].counts = mp.get_scaler_counts(fh,i) #~ self.scaler_list[-1].id_number = i #~ try: #~ self.scaler_list[-1].title = str(mp.get_scaler_label(fh,i)) #~ except UnicodeEncodeError as e: #~ self.scaler_list[-1].title = repr(e) # Read independent variables n_var = mp.get_ivars(fh)[1] self.var_list = [] for i in range(1,n_var+1): self.var_list.append(bvar()) self.var_list[-1].id_number = i self.var_list[-1].low = mp.get_ivar_low(fh,i) self.var_list[-1].high = mp.get_ivar_high(fh,i) self.var_list[-1].mean = mp.get_ivar_mean(fh,i) self.var_list[-1].std = mp.get_ivar_std(fh,i) self.var_list[-1].skew = mp.get_ivar_skewness(fh,i) try: self.var_list[-1].title = str(mp.get_ivar_name(fh,i)) self.var_list[-1].description = str(\ mp.get_ivar_description(fh,i)) self.var_list[-1].units = str(mp.get_ivar_units(fh,i)) except UnicodeEncodeError: self.var_list[-1].title = mp.get_ivar_name(fh,i) self.var_list[-1].description =mp.get_ivar_description(fh,i) self.var_list[-1].units = mp.get_ivar_units(fh,i) # Close file ---------------------------------------------------------- finally: mp.close_read(fh) # Sort independent variables into dictionaries by title self.ppg = bdict() self.camp = bdict() self.epics = bdict() for v in self.var_list: try: if 'PPG' in v.title: self.ppg[self.dkeys[v.title.split("/")[-1]]] = v elif v.title[0] == "/": self.camp[self.dkeys[v.title]] = v else: self.epics[self.dkeys[v.title]] = v except (KeyError,IndexError): message = '"' + v.title + '" not found in dkeys. '+\ "Data in list, but not sorted to dict." warnings.warn(message,RuntimeWarning,stacklevel=2) # Sort histograms into dictionaries by title and convert to doubles self.hist = bdict() for h in self.hist_list: self.hist[h.title] = h self.hist[h.title].data = self.hist[h.title].data.astype(float) # Sort scalers into dictionaries by title #~ self.sclr = bdict() #~ for s in self.scaler_list: #~ new_key = s.title.split("%")[-1].replace(" ","") #~ self.sclr[new_key] = s # set the date self.start_date = time.ctime(self.start_time) self.end_date = time.ctime(self.end_time) self.year = time.gmtime(self.start_time).tm_year # ======================================================================= # def _get_area_data(self): """Get histogram list based on area type. List pattern: [type1_hel+,type2_hel+,type1_hel-,type2_hel-] where type1/2 = F/B or R/L in that order. """ if self.mode == '1n': data = [self.hist['NBMF+'].data,\ self.hist['NBMF-'].data,\ self.hist['NBMB+'].data,\ self.hist['NBMB-'].data] elif self.area == 'BNMR': data = [self.hist['F+'].data,\ self.hist['F-'].data,\ self.hist['B+'].data,\ self.hist['B-'].data] elif self.area == 'BNQR': data = [self.hist['R+'].data,\ self.hist['R-'].data,\ self.hist['L+'].data,\ self.hist['L-'].data] else: data = [] if self.mode == '2h': data.extend([self.hist['AL1+'].data,self.hist['AL1-'].data, self.hist['AL0+'].data,self.hist['AL0-'].data, self.hist['AL3+'].data,self.hist['AL3-'].data, self.hist['AL2+'].data,self.hist['AL2-'].data]) # copy return [np.copy(d) for d in data] # ======================================================================= # def _get_asym_hel(self,d): """ Find the asymmetry of each helicity. """ # get data 1+ 2+ 1- 2- d0 = d[0]; d1 = d[2]; d2 = d[1]; d3 = d[3] # pre-calcs denom1 = d0+d1; denom2 = d2+d3 # check for div by zero denom1[denom1==0] = np.nan denom2[denom2==0] = np.nan # asymmetries in both helicities asym_hel = [(d0-d1)/denom1, (d2-d3)/denom2] # errors # https://www.wolframalpha.com/input/?i=%E2%88%9A(F*(derivative+of+((F-B)%2F(F%2BB))+with+respect+to+F)%5E2+%2B+B*(derivative+of+((F-B)%2F(F%2BB))+with+respect+to+B)%5E2) asym_hel_err = [2*np.sqrt(d0*d1/np.power(denom1,3)), 2*np.sqrt(d2*d3/np.power(denom2,3))] # remove nan for i in range(2): asym_hel[i][np.isnan(asym_hel[i])] = 0. asym_hel_err[i][np.isnan(asym_hel_err[i])] = 0. # exit return [[asym_hel[1],asym_hel_err[1]], # something wrong with file? [asym_hel[0],asym_hel_err[0]]] # I shouldn't have to switch # ======================================================================= # def _get_asym_comb(self,d): """ Find the combined asymmetry for slr runs. Elegant 4-counter method. """ # get data d0 = d[0]; d1 = d[2]; d2 = d[1]; d3 = d[3] # pre-calcs r_denom = d0*d3 r_denom[r_denom==0] = np.nan r = np.sqrt((d1*d2/r_denom)) r[r==-1] = np.nan # combined asymmetry asym_comb = (r-1)/(r+1) # check for div by zero d0[d0==0] = np.nan d1[d1==0] = np.nan d2[d2==0] = np.nan d3[d3==0] = np.nan # error in combined asymmetry asym_comb_err = r*np.sqrt(1/d1 + 1/d0 + 1/d3 + 1/d2)/np.square(r+1) # replace nan with zero asym_comb[np.isnan(asym_comb)] = 0. asym_comb_err[np.isnan(asym_comb_err)] = 0. return [asym_comb,asym_comb_err] # ======================================================================= # def _get_asym_alpha(self,a,b): """ Find alpha diffusion ratios from cryo oven with alpha detectors. a: list of alpha detector histograms (each helicity) b: list of beta detector histograms (each helicity) """ # just use AL0 try: a = a[2:4] except IndexError: a = a[:2] # sum counts in alpha detectors asum = np.sum(a,axis=0) # sum counts in beta detectors bsum = np.sum(b,axis=0) # check for dividing by zero asum[asum == 0] = np.nan bsum[bsum == 0] = np.nan # asym calcs asym = asum/bsum # errors dasym = asym*np.sqrt(1/asum + 1/bsum) return [asym,dasym] # ======================================================================= # def _get_asym_alpha_tag(self,a,b): """ Find asymmetry from cryo oven with alpha detectors. a: list of alpha detector histograms (each helicity) b: list of beta detector histograms (each helicity) 1+ 1- 2+ 2- """ # beta in coincidence with alpha coin = a[:4] # beta coincidence with no alpha no_coin = a[4:8] # get split helicity asym from hel_coin = self._get_asym_hel(coin) hel_no_coin = self._get_asym_hel(no_coin) hel_reg = self._get_asym_hel(b) # get combined helicities com_coin = self._get_asym_comb(coin) com_no_coin = self._get_asym_comb(no_coin) com_reg = self._get_asym_comb(b) # make output return (hel_coin,hel_no_coin,hel_reg,com_coin,com_no_coin,com_reg) # ======================================================================= # def _get_1f_sum_scans(self,d,freq): """ Sum counts in each frequency bin over 1f scans. """ # combine scans: values with same frequency unique_freq = np.unique(freq) sum_scans = [[] for i in range(len(d))] for f in unique_freq: tag = freq==f for i in range(len(d)): sum_scans[i].append(np.sum(d[i][tag])) return (np.array(unique_freq),np.array(sum_scans)) # ======================================================================= # def _get_2e_asym(self): """ Get asymmetries for 2e random-frequency scan. Based on bnmr_2e.cpp by rmlm (Oct 4, 2017). """ # get needed PPG parameters for splitting 1D histos into 2D histos try: # get frequency vector freq = np.arange(self.ppg['freq_start'].mean,\ self.ppg['freq_stop'].mean+\ self.ppg['freq_incr'].mean,\ self.ppg['freq_incr'].mean) # number of dwelltimes per frequency bin ndwell = 2*int(self.ppg['ndwell_per_f'].mean)-1 # number of RF on delays for the start bin. start_bin = int(self.ppg['rf_on_delay'].mean) # get bin centers in ms time = self.ppg['rf_on_ms'].mean*(np.arange(ndwell)+0.5-ndwell/2.) # get the time and index of the middle time mid_time_i = int(np.floor(ndwell/2.)) mid_time = time[mid_time_i] # beam off time after pulse in ms beam_off = int(self.ppg['beam_off_ms'].mean) except KeyError: raise RuntimeError("Not all dictionary variables read out to "+\ "proper locations") # setup output out = bdict() out['freq'] = freq out['time'] = time # get data data = np.array(self._get_area_data()) # [[fp], [bfm], [bp], [bm]] # discared initial bad bins, and beam-off trailing bins data = data[:,start_bin:len(freq)*ndwell+start_bin] # split data by frequency nsplit = len(data[0])/ndwell fp = np.array(np.split(data[0],nsplit)) fm = np.array(np.split(data[1],nsplit)) bp = np.array(np.split(data[2],nsplit)) bm = np.array(np.split(data[3],nsplit)) # get raw asymmetries asym_p_2cntr = (bp-fp)/(bp+fp) # two counter asym_m_2cntr = (bm-fm)/(bm+fm) # two counter r = np.sqrt(bp*fm/(bm*fp)) asym_4cntr = (r-1)/(r+1) # four counter # get raw asymmetry errors asym_p_2cntr_err = 2*np.sqrt(bp*fp)/((bp+fp)**1.5) asym_m_2cntr_err = 2*np.sqrt(bm*fm)/((bm+fm)**1.5) asym_4cntr_err = r*np.sqrt(1./bp+1./bm+1./fp+1./fm)/((r+1)**2) # save to output out['raw_p'] = np.array([asym_p_2cntr,asym_p_2cntr_err]) out['raw_n'] = np.array([asym_m_2cntr,asym_m_2cntr_err]) out['raw_c'] = np.array([asym_4cntr,asym_4cntr_err]) # wrap asymmetry arrays into one for calculations [p,m,4] # indexing is now [pm4][freq][time bin] asym = np.array([asym_p_2cntr, asym_m_2cntr, asym_4cntr]) asym_err = np.array([asym_p_2cntr_err,asym_m_2cntr_err,asym_4cntr_err]) # compute differenced asymmetries via slopes from weighted least squares # minimization. if ndwell >= 5: # calculate needed components element-wise w = asym_err**-2 x = time y = asym wx = w*x wy = w*y wxy = w*x*y wxx = w*x*x # sum over values i < mid_time_i within each asymmetry and frequency # Indexing: [pm4][freq] w_pre = np.sum(w [:,:,:mid_time_i],2) wx_pre = np.sum(wx [:,:,:mid_time_i],2) wy_pre = np.sum(wy [:,:,:mid_time_i],2) wxy_pre = np.sum(wxy[:,:,:mid_time_i],2) wxx_pre = np.sum(wxx[:,:,:mid_time_i],2) # sum over values i > mid_time_i w_pst = np.sum(w [:,:,-mid_time_i:],2) wx_pst = np.sum(wx [:,:,-mid_time_i:],2) wy_pst = np.sum(wy [:,:,-mid_time_i:],2) wxy_pst = np.sum(wxy[:,:,-mid_time_i:],2) wxx_pst = np.sum(wxx[:,:,-mid_time_i:],2) # calculate slopes and intercepts delta_pre = w_pre*wxx_pre - wx_pre**2 delta_pst = w_pst*wxx_pst - wx_pst**2 sl_pre = (w_pre*wxy_pre - wx_pre*wy_pre)/delta_pre sl_pst = (w_pst*wxy_pst - wx_pst*wy_pst)/delta_pst dsl_pre = np.sqrt(w_pre/delta_pre) dsl_pst = np.sqrt(w_pst/delta_pst) intr_pre = (wy_pre*wxx_pre - wx_pre*wxy_pre)/delta_pre intr_pst = (wy_pst*wxx_pst - wx_pst*wxy_pst)/delta_pst dintr_pre = np.sqrt(wxx_pre/delta_pre) dintr_pst = np.sqrt(wxx_pst/delta_pst) # extrapolate to middle time bin asym_slopes = intr_pst-intr_pre+(sl_pst-sl_pre)*mid_time asym_slopes_err = np.sqrt(dintr_pre**2 + dintr_pst**2 + \ (dsl_pre**2 + dsl_pst**2) * mid_time**2) # save to output out['sl_p'] = np.array([asym_slopes[0],asym_slopes_err[0]]) out['sl_n'] = np.array([asym_slopes[1],asym_slopes_err[1]]) out['sl_c'] =
<gh_stars>1-10 from collections import Counter import getopt import math import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages import numpy as np import os import pandas as pd import scipy.stats import statsmodels.api as sm import statsmodels.formula.api as smf import sys def get_codes(): #same """ Gets the PheWAS codes from a local csv file and load it into a pandas DataFrame. :returns: All of the codes from the resource file. :rtype: pandas DataFrame """ sep = os.sep path = os.path.dirname(os.path.abspath(__file__)) filename = os.sep.join([path,'..','resources','codes.csv']) return pd.read_csv(filename) def get_group_file(path, filename): #same """ Read all of the genotype data from the given file and load it into a pandas DataFrame. :param path: The path to the file that contains the phenotype data :param filename: The name of the file that contains the phenotype data. :type path: string :type filename: string :returns: The data from the genotype file. :rtype: pandas DataFrame """ wholefname = path + filename genotypes = pd.read_csv(wholefname) return genotypes def get_input(path, filename, reg_type): #diff -done - add duration """ Read all of the phenotype data from the given file and load it into a pandas DataFrame. :param path: The path to the file that contains the phenotype data :param filename: The name of the file that contains the phenotype data. :type path: string :type filename: string :returns: The data from the phenotype file. :rtype: pandas DataFrame """ wholefname = path + filename icdfile = pd.read_csv(wholefname) icdfile['icd9'] = icdfile['icd9'].str.strip() if reg_type == 0: phenotypes = pd.merge(icdfile,codes,on='icd9') phenotypes['MaxAgeAtICD'] = 0 phenotypes['MaxAgeAtICD'] = phenotypes.groupby(['id', 'phewas_code'])['AgeAtICD'].transform('max') else: """ This needs to be changed, need to adjust for a variety of different naming conventions in the phenotype file, not simply 'AgeAtICD', 'id', 'icd9', etc. Either we need to adjust for different names in the code, or state explicitly in the documentation that we cannot do things like this. """ phenotypes = pd.merge(icdfile,codes,on='icd9') phenotypes['count']=0 phenotypes['count']=phenotypes.groupby(['id','phewas_code'])['count'].transform('count') phenotypes['duration']=phenotypes.groupby(['id','phewas_code'])['AgeAtICD'].transform('max')-phenotypes.groupby(['id','phewas_code'])['AgeAtICD'].transform('min')+1 phenotypes['MaxAgeAtICD'] = 0 phenotypes['MaxAgeAtICD'] = phenotypes.groupby(['id', 'phewas_code'])['AgeAtICD'].transform('max') return phenotypes def generate_feature_matrix(genotypes,phenotypes, reg_type): #diff - done """ Generates the feature matrix that will be used to run the regressions. :param genotypes: :param phenotypes: :type genotypes: :type phenotypes: :returns: :rtype: """ feature_matrix = np.zeros((genotypes.shape[0],phewas_codes.shape[0]), dtype=int) count = 0; for i in genotypes['id']: if reg_type == 0: temp=pd.DataFrame(phenotypes[phenotypes['id']==i][['phewas_code','MaxAgeAtICD']]).drop_duplicates() match=phewas_codes['phewas_code'].isin(list( phenotypes[phenotypes['id']==i]['phewas_code'])) feature_matrix[0][count,match[match==True].index]=1 age = pd.merge(phewas_codes, temp, on='phewas_code', how='left')['MaxAgeAtICD'] age[np.isnan(age)] = genotypes[genotypes['id'] == i].iloc[0]['MaxAgeBeforeDx'] feature_matrix[1][count, :] = age if phewas_cov: feature_matrix[2][count, :] = int(phewas_cov in list(phenotypes[phenotypes['id'] == i]['phewas_code'])) else: if reg_type == 1: temp=pd.DataFrame(phenotypes[phenotypes['id']==i][['phewas_code','count']]).drop_duplicates() cts = pd.merge(phewas_codes,temp,on='phewas_code',how='left')['count'] cts[np.isnan(cts)]=0 feature_matrix[0][count,:]=cts age = pd.merge(phewas_codes, temp, on='phewas_code', how='left')['MaxAgeAtICD'] age[np.isnan(age)] = genotypes[genotypes['id']==i].iloc[0]['MaxAgeBeforeDx'] feature_matrix[1][count, :] = age if phewas_cov: feature_matrix[2][count, :] = int( phewas_cov in list(phenotypes[phenotypes['id'] == i]['phewas_code'])) elif reg_type==2: temp=pd.DataFrame(phenotypes[phenotypes['id']==i][['phewas_code','count', 'duration']]).drop_duplicates() dura = pd.merge(phewas_codes,temp,on='phewas_code',how='left')['duration'] dura[np.isnan(dura)]=0 feature_matrix[0][count,:]=dura age = pd.merge(phewas_codes, temp, on='phewas_code', how='left')['MaxAgeAtICD'] age[np.isnan(age)] = genotypes[genotypes['id']==i].iloc[0]['MaxAgeBeforeDx'] feature_matrix[1][count, :] = age if phewas_cov: feature_matrix[2][count, :] = int( phewas_cov in list(phenotypes[phenotypes['id'] == i]['phewas_code'])) count+=1 return feature_matrix """ Statistical Modeling """ def get_phewas_info(p_index): #same """ Returns all of the info of the phewas code at the given index. :param p_index: The index of the desired phewas code :type p_index: int :returns: A list including the code, the name, and the rollup of the phewas code. The rollup is a list of all of the ICD-9 codes that are grouped into this phewas code. :rtype: list of strings """ p_code = phewas_codes.loc[p_index].phewas_code corresponding = codes[codes.phewas_code == p_code] p_name = corresponding.iloc[0].phewas_string p_rollup = ','.join(codes[codes.phewas_code == p_code].icd9.tolist()) return [p_code, p_name, p_rollup] def calculate_odds_ratio(genotypes, phen_vector1,phen_vector2,reg_type,covariates,response='',phen_vector3=''): #diff - done """ Runs the regression for a specific phenotype vector relative to the genotype data and covariates. :param genotypes: a DataFrame containing the genotype information :param phen_vector: a array containing the phenotype vector :param covariates: a string containing all desired covariates :type genotypes: pandas DataFrame :type phen_vector: numpy array :type covariates: string .. note:: The covariates must be a string that is delimited by '+', not a list. If you are using a list of covariates and would like to convert it to the pyPhewas format, use the following:: l = ['genotype', 'age'] # a list of your covariates covariates = '+'.join(l) # pyPhewas format The covariates that are listed here *must* be headers to your genotype CSV file. """ data = genotypes data['y']=phen_vector1 data['MaxAgeAtICD'] = phen_vector2 #f='y~'+covariates if response: f = response+'~ y + ' + covariates if phen_vector3.any(): data['phe'] = phen_vector3 f = response + '~ y + phe +' + covariates else: f = 'y ~' + covariates if phen_vector3.any(): data['phe'] = phen_vector3 f = 'y ~ phe +' + covariates try: if reg_type==0: logreg = smf.logit(f,data).fit(method='bfgs',disp=False) p=logreg.pvalues.genotype odds=logreg.deviance conf = logreg.conf_int() od = [-math.log10(p), logreg.params.genotype, '[%s,%s]' % (conf[0]['genotype'],conf[1]['genotype'])] else: linreg = smf.glm(f,data).fit(method='bfgs',disp=False) p=linreg.pvalues.genotype odds=0 conf = linreg.conf_int() od = [-math.log10(p), linreg.params.genotype, '[%s,%s]' % (conf[0]['genotype'],conf[1]['genotype'])] except: odds=0 p=np.nan od = [np.nan,np.nan,np.nan] return (odds,p,od) def run_phewas(fm, genotypes ,covariates, reg_type): #same """ For each phewas code in the feature matrix, run the specified type of regression and save all of the resulting p-values. :param fm: The phewas feature matrix. :param genotypes: A pandas DataFrame of the genotype file. :param covariates: The covariates that the function is to be run on. :returns: A tuple containing indices, p-values, and all the regression data. """ m = len(fm[0,]) p_values = np.zeros(m, dtype=float) icodes=[] # store all of the pertinent data from the regressions regressions = pd.DataFrame(columns=output_columns) for index in range(m): phen_vector = fm[:,index] res=calculate_odds_ratio(genotypes, phen_vector,covariates, reg_type) # save all of the regression data phewas_info = get_phewas_info(index) stat_info = res[2] info = phewas_info[0:2] + stat_info + [phewas_info[2]] regressions.loc[index] = info p_values[index] = res[1] return regressions def get_bon_thresh(normalized,power): #same """ Calculate the bonferroni correction threshold. Divide the power by the sum of all finite values (all non-nan values). :param normalized: an array of all normalized p-values. Normalized p-values are -log10(p) where p is the p-value. :param power: the threshold power being used (usually 0.05) :type normalized: numpy array :type power: float :returns: The bonferroni correction :rtype: float """ return power/sum(np.isfinite(normalized)) def get_fdr_thresh(p_values, power): """ Calculate the false discovery rate threshold. :param p_values: a list of p-values obtained by executing the regression :param power: the thershold power being used (usually 0.05) :type p_values: numpy array :type power: float :returns: the false discovery rate :rtype: float """ sn = np.sort(p_values) sn = sn[np.isfinite(sn)] sn = sn[::-1] for i in range(len(sn)): thresh=0.05*i/len(sn) if sn[i]<=power: break return sn[i] def get_imbalances(regressions): """ Generates a numpy array of the imbalances. For a value *x* where *x* is the beta of a regression: ========= ====== ======================================================= *x* < 0 **-1** The regression had a negative beta value *x* = nan **0** The regression had a nan beta value (and a nan p-value) *x* > 0 **+1** The regression had a positive beta value ========= ====== ======================================================= These values are then used to get the correct colors using the imbalance_colors. :param regressions: DataFrame containing a variety of different output values from the regression performed. The only one used for this function are the 'beta' values. :type regressions: pandas DataFrame :returns: A list that is the length of the number of regressions performed. Each element in the list is either a -1, 0, or +1. These are used as explained above. :rtype: numpy array """ imbalance = np.array(regressions['beta']) imbalance[np.isnan(imbalance)] = 0 imbalance[imbalance > 0] = 1 imbalance[imbalance < 0] = -1 return imbalance def get_x_label_positions(categories, lines=True): #same """ This method is used get the position of the x-labels and the lines between the columns :param categories: list of the categories :param lines: a boolean which determines the locations returned (either the center of each category or the end) :type categories: :type lines: bool :returns: A list of positions :rtype: list of ints """ tt = Counter(categories) s = 0 label_positions = [] for _,v in tt.items(): if lines: inc = v//2 else: inc = v label_positions.append(s + inc) s += v return label_positions def plot_data_points(y, thresh, save='', imbalances=np.array([])): #same """ Plots the data with a variety of different options. This function is the primary plotting function for pyPhewas. :param x: an array of indices :param y: an array of p-values :param thresh: the threshold power :param save: the output file to save to (if empty, display the plot) :param imbalances: a list of imbalances :type x: numpy array :type y: numpy array :type thresh: float :type save: str :type imbalances: numpy array """ # Determine whether or not to show the imbalance. show_imbalance = imbalances.size != 0 # Sort the phewas codes by category. c = codes.loc[phewas_codes['index']] c = c.reset_index() idx = c.sort_values(by='category').index # Get the position of the lines and of the labels linepos = get_x_label_positions(c['category'].tolist(), True) x_label_positions = get_x_label_positions(c['category'].tolist(), False) x_labels = c.sort_values('category').category_string.drop_duplicates().tolist() # Plot each of the points, if necessary, label the points. e = 1 artists = [] for i in idx: if show_imbalance: plt.plot(e,y[i], 'o', color=imbalance_colors[imbalances[i]], fillstyle='full', markeredgewidth=0.0) else: plt.plot(e,y[i],'o', color=plot_colors[c[i:i+1].category_string.values[0]],markersize=10, fillstyle='full', markeredgewidth=0.0) if y[i] > thresh: artists.append(plt.text(e,y[i],c['phewas_string'][i], rotation=40, va='bottom')) e += 1 # If the imbalance is to be shown, draw lines to show the categories. if show_imbalance: for pos in linepos: plt.axvline(x=pos, color='black', ls='dotted') # Plot a blue line at p=0.05 and plot a red line at the line for the threshold type. plt.axhline(y=-math.log10(0.05), color='blue') plt.axhline(y=thresh, color='red') # Set windows and labels plt.xticks(x_label_positions, x_labels,rotation=70, fontsize=10) plt.ylim(ymin=0) plt.xlim(xmin=0, xmax=len(c)) plt.ylabel('-log10(p)') # Determine the type of output desired (saved to a plot or displayed on the screen) if save: pdf = PdfPages(save) pdf.savefig(bbox_extra_artists=artists, bbox_inches='tight') pdf.close() else: plt.subplots_adjust(left=0.05,right=0.85) plt.show() # Clear the plot in case another plot is to be made. plt.clf() def process_args(kwargs,optargs,*args): clean = np.vectorize(lambda x: x[x.rfind('-')+1:] + '=') searchfor = clean(list(optargs.keys())) opts, rem = getopt.getopt(args, '',searchfor) assert len(rem) == 0, 'Unknown arguments included %s' % (str(rem)) for option in opts: k,v = option kwargs[optargs[k]] = v return kwargs def display_kwargs(kwargs): print ("Arguments: ") for k,v in kwargs.items(): left = str(k).ljust(30,'.') right = str(v).rjust(50,'.') print(left + right) output_columns = ['PheWAS Code', 'PheWAS Name', '\"-log(p)\"', 'beta', 'Conf-interval beta',
<gh_stars>10-100 #!/usr/bin/env python3 # -*- coding: utf-8 -*- # # # Copyright © 2018 Dell Inc. or its subsidiaries. All rights reserved. # Dell, EMC, and other trademarks are trademarks of Dell Inc. or its subsidiaries. # Other trademarks may be trademarks of their respective owners. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Authors: <NAME> # import os import sys import re import tempfile import glob import json import logging from enum import Enum from datetime import datetime from omsdk.sdkprint import MyEncoder, PrettyPrint from omsdk.sdkenum import DeviceGroupFilter from omsdk.sdkcenum import EnumWrapper,TypeHelper from omsdk.sdkcunicode import UnicodeHelper import platform PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 logger = logging.getLogger(__name__) # idrac.get_share_type_mapped(): # { ShareType.NFS : 0, ShareType.CIFS : 2, ShareType.VFLASH : 4 } # { IPAddressTypeEnum.IPv4 : 1, IPAddressTypeEnum.IPv6 : 2, } # f10.get_share_type_mapped(): # { ShareType.TFTP : 3, ShareType.FTP : 4, ShareType.SCP : 5 } # { IPAddressTypeEnum.IPv4 : 1, IPAddressTypeEnum.IPv6 : 2, IPAddressTypeEnum.DNS : 16 } class Share(object): ShareType = EnumWrapper('ShareType', {'NFS':0, 'CIFS':2, 'TFTP' : 3, 'FTP' : 4, 'SCP': 5}).enum_type ShareTypeRedfish = EnumWrapper('ShareTypeRedfish', {'NFS': 'NFS', 'CIFS': 'CIFS', 'TFTP': 'TFTP', 'FTP': 'FTP', 'SCP': 'SCP'}).enum_type LocalFolderType = EnumWrapper('LocalFolderType', {'Windows':-1, 'Linux':-2}).enum_type vFlashType = EnumWrapper('vFlashType', {'VFLASH' : 4}).enum_type IPAddressTypeEnum = EnumWrapper('IPAD', { 'Invalid' : 0, 'IPv4' : 1, 'IPv6': 2, 'DNS' : 16}).enum_type _ShareSpec = { ShareType.CIFS : { 'share_file' : re.compile('\\\\\\\\([^\\\\]+)[\\\\](.+)[\\\\]([^\\\\]+)$'), 'share' : re.compile('\\\\\\\\([^\\\\]+)[\\\\](.+)'), 'path_sep' : '\\', 'path_start' : '\\\\', 'ipsep' : '\\', 'type' : ShareType.CIFS, }, ShareType.NFS : { 'share_file' : re.compile("([^/]+):/(.+)/([^/]+)$"), 'share' : re.compile("([^/]+):/(.+)"), 'path_sep' : '/', 'rpath_sep' : '/', 'ipsep' : ':', 'type' : ShareType.NFS, }, ShareType.SCP : { 'share_file' : re.compile("scp:([^/]+):/(.+)/([^/]+)$"), 'share' : re.compile("scp:([^/]+):/(.+)"), 'path_sep' : '/', 'fsep' : ':', 'ipsep' : ':', 'rpath_sep' : '/', 'type' : ShareType.SCP, 'prefix' : 'scp', }, ShareType.FTP : { 'share_file' : re.compile("ftp:([^/]+):/(.+)/([^/]+)$"), 'share' : re.compile("ftp:([^/]+):/(.+)"), 'path_sep' : '/', 'fsep' : ':', 'ipsep' : ':', 'rpath_sep' : '/', 'type' : ShareType.FTP, 'prefix' : 'ftp', }, ShareType.TFTP : { 'share_file' : re.compile("tftp:([^/]+):/(.+)/([^/]+)$"), 'share' : re.compile("tftp:([^/]+):/(.+)"), 'path_sep' : '/', 'fsep' : ':', 'ipsep' : ':', 'rpath_sep' : '/', 'type' : ShareType.TFTP, 'prefix' : 'tftp', }, LocalFolderType.Windows : { 'share' : re.compile('^[A-Za-z]:.+$'), 'path_sep' : '\\', 'type' : LocalFolderType.Windows, }, LocalFolderType.Linux : { 'share' : re.compile("^[^\\\\:]+$"), 'path_sep' : '/', 'type' : LocalFolderType.Linux, }, } IPv4Address = re.compile("^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$") TemplateSpec = re.compile(".*%[A-Za-z].*") class _PathObject(object): def __init__(self, share_type, isFolder, ipaddr, *args): self.share_type = share_type self.ipaddr = ipaddr self.isFolder = isFolder self.iptype = Share.IPAddressTypeEnum.Invalid if ipaddr: if Share.IPv4Address.match(self.ipaddr): self.iptype = Share.IPAddressTypeEnum.IPv4 else: self.iptype = Share.IPAddressTypeEnum.IPv6 self.paths = [path for path in args \ if path is not None and len(path.strip()) > 0] if self.share_type in Share._ShareSpec: psep = Share._ShareSpec[self.share_type]['path_sep'] path_repl_char = '\\' path_repl_regex = '[\\\\]+$' if self.share_type in [Share.ShareType.CIFS, Share.LocalFolderType.Windows]: path_repl_char = '/' path_repl_regex = '/+$' self.paths = [i.replace(path_repl_char, psep) for i in self.paths] self.paths = [re.sub('[\\\\/]+$', '', i) for i in self.paths] self.full_path = self._get_full_path(self.paths) self.mountable_path = self._get_full_path([self.paths[0]]) shpath = self._get_share_path("", self.paths) if self.isFolder: self.share_name = shpath self.file_name = "" self.share_path = self.full_path else: shpatharr = shpath.split(psep) self.share_name = psep.join(shpatharr[0:-1]) self.file_name = shpatharr[-1] self.share_path = psep.join(self.full_path.split(psep)[0:-1]) if self.share_type in [Share.ShareType.CIFS, Share.LocalFolderType.Windows]: self.folder_name = self.share_name else: self.folder_name = self._get_folder_name(self.paths[:-1]) else: if len(args) <= 0: args = [""] self.mountable_path = args[0] self.full_path = args[0] self.share_name = args[0] self.file_name = args[0] self.share_path = args[0] def _get_share_path(self, fname, paths): comma = '' for path_comp in paths: if path_comp and len(path_comp.strip()) > 0: fname += comma + path_comp comma = Share._ShareSpec[self.share_type]['path_sep'] return fname def _get_full_path(self, paths): fname = "" if self.share_type in [Share.vFlashType.VFLASH]: return self.paths[0] # protocol_prefix scp, tftp, ftp if 'prefix' in Share._ShareSpec[self.share_type]: fname += Share._ShareSpec[self.share_type]['prefix'] if 'fsep' in Share._ShareSpec[self.share_type]: fname += Share._ShareSpec[self.share_type]['fsep'] if 'path_start' in Share._ShareSpec[self.share_type]: fname += Share._ShareSpec[self.share_type]['path_start'] if 'ipsep' in Share._ShareSpec[self.share_type]: fname += self.ipaddr + Share._ShareSpec[self.share_type]['ipsep'] if 'rpath_sep' in Share._ShareSpec[self.share_type]: fname += Share._ShareSpec[self.share_type]['rpath_sep'] return self._get_share_path(fname, paths) def _get_folder_name(self, paths): fname = "" if 'rpath_sep' in Share._ShareSpec[self.share_type]: fname += Share._ShareSpec[self.share_type]['rpath_sep'] return self._get_share_path(fname, paths) def get_full_path_with(self, npaths): if not isinstance(npaths, list): npaths = [npaths] return self._get_full_path(self.paths + npaths) def printx(self, sname): print("Share (" + str(self.share_type) + "): " + str(self.share_name)) if self.ipaddr and len(self.ipaddr) > 0: print(" " + sname + " IPAddress " + str(self.ipaddr)) print(" " + sname + " IPType " + str(self.iptype)) if self.file_name and len(self.file_name) > 0: print(" " + sname + " Filename " + str(self.file_name)) print(" " + sname + " Full Path " + str(self.full_path)) print(" " + sname + " Mountable Path " + str(self.mountable_path)) print(" " + sname + " Share Path " + str(self.share_path)) print(" " + sname + " Folder Name " + str(self.folder_name)) class RemotePath(_PathObject): def __init__(self, share_type, isFolder, ipaddr, *args): if PY2: super(RemotePath, self).__init__(share_type, isFolder, ipaddr, *args) else: super().__init__(share_type, isFolder, ipaddr, *args) class LocalPath(_PathObject): def __init__(self, share_type, isFolder, *args): if PY2: super(LocalPath, self).__init__(share_type, isFolder, None, *args) else: super().__init__(share_type, isFolder, None, *args) class vFlash(_PathObject): def __init__(self): if PY2: super(vFlash, self).__init__(Share.vFlashType.VFLASH, False, None, "vFlash") else: super().__init__(Share.vFlashType.VFLASH, False, None, "vFlash") class InvalidPath(_PathObject): def __init__(self): if PY2: super(InvalidPath, self).__init__(None, False, None, "<invalid>") else: super().__init__(None, False, None, "<invalid>") class FileOnShare(Share): def json_encode(self): return { 'share_type': str(self.share_type), 'share_name': str(self.share_name), 'ipaddr': str(self.ipaddr), 'creds.username': str(self.creds.username), 'creds.password': str(self.creds.password), 'full_path': str(self.full_path), } def _get_path_object(self, stype_enum, remote_path, common_path, isFolder): filename = None if remote_path.endswith('/') or remote_path.endswith('\\') or os.path.exists(remote_path): if common_path is None: isFolder = True if not isFolder: for pspec in stype_enum: if pspec not in Share._ShareSpec: continue if 'share_file' not in Share._ShareSpec[pspec]: continue tomatch = remote_path if common_path: if not tomatch.endswith(Share._ShareSpec[pspec]['path_sep']): tomatch += Share._ShareSpec[pspec]['path_sep'] tomatch += common_path cfgtype = Share._ShareSpec[pspec]['share_file'].match(tomatch) if not cfgtype: continue share_type = pspec if len(cfgtype.groups()) > 1: (ipaddr, rshare, filename) = [i for i in cfgtype.groups()] path_list = [ rshare, filename ] if common_path: psp = Share._ShareSpec[pspec]['path_sep'] if psp in common_path: cpath = common_path.replace(psp + filename, '') rshare = rshare.replace(cpath, '') path_list = [ rshare, cpath, filename ] else: rshare = rshare.replace(common_path, '') path_list = [ rshare, filename ] return RemotePath(share_type, isFolder, ipaddr, *path_list) path_list = [ remote_path ] if common_path: path_list.append(common_path) return LocalPath(share_type, isFolder, *path_list) for pspec in stype_enum: if pspec not in Share._ShareSpec: continue tomatch = remote_path if common_path: if not tomatch.endswith(Share._ShareSpec[pspec]['path_sep']): tomatch += Share._ShareSpec[pspec]['path_sep'] tomatch += common_path cfgtype = Share._ShareSpec[pspec]['share'].match(tomatch) if not cfgtype: continue share_type = pspec if len(cfgtype.groups()) > 1: (ipaddr, rshare) = [i for i in cfgtype.groups()] path_list = [ rshare ] if common_path: rshare = rshare.replace(common_path, '') path_list = [ rshare, common_path ] return RemotePath(share_type, isFolder, ipaddr, *path_list) path_list = [ remote_path ] if common_path: path_list.append(common_path) return LocalPath(share_type, isFolder, *path_list) return InvalidPath() def __init__(self, remote, mount_point = None, common_path = None, isFolder=False, creds = None, fd=None): if PY2: super(FileOnShare, self).__init__() else: super().__init__() if creds is not None and creds.username is not None and "@" in creds.username: username_domain = creds.username.split("@") creds.username = username_domain[0] creds.domain = username_domain[1] self.creds = creds self.isFolder = isFolder remote = UnicodeHelper.stringize(remote) mount_point = UnicodeHelper.stringize(mount_point) common_path = UnicodeHelper.stringize(common_path) if remote == "vFlash": self.remote = vFlash() else: self.remote = self._get_path_object(Share.ShareType, remote, common_path, isFolder) if mount_point and mount_point == "vFlash": self.mount_point = vFlash() elif mount_point: self.mount_point = self._get_path_object(Share.LocalFolderType, mount_point, common_path, isFolder) else: self.mount_point = None if remote is not None and self.remote and isinstance(self.remote, InvalidPath): logger.error("Share path is not valid : {}".format(repr(remote))) raise ValueError("Share path is not valid : {}".format(repr(remote))) if mount_point is not None and self.mount_point and isinstance(self.mount_point, InvalidPath): logger.error("Mount point is not valid : {}".format(repr(mount_point))) raise ValueError("Mount point is not valid : {}".format(repr(mount_point))) self.mounted = False self.fd = fd self.valid = False self.is_template = False if Share.TemplateSpec.match(self.remote_full_path) is not None: self.is_template = True def _isConnected(self, drive, remote = None): if platform.system() != "Windows": return True maps = self._mapdetails(drive) status = False if 'Status' in maps: status = (maps['Status']
mod, typ, name, default = match.groups() return mod, typ.strip(), name.strip(), default def get_index_text(self, sig, name, typ): rname = '{} (C# {})->{}'.format(name, _('variable'), typ) return rname def get_obj_name(self, sig): _, typ, name, _ = self.parse_signature(sig) return name, typ class CSharpProperty(CSharpObject): def handle_signature(self, sig, signode): mod, typ, name, getter, setter = self.parse_signature(sig) node = CSNodes.EmptyNode() node += CSNodes.Modificator(text='{}'.format(mod if mod else 'private')) node += CSNodes.TextNode(text=' ') self.append_ref_signature(typ, node) node += CSNodes.TextNode(text=' ') node += CSNodes.MethodName(text='{}'.format(name)) node += CSNodes.TextNode(text=' { ') accessors = [] if getter: accessors.append('get;') if setter: accessors.append(setter.strip()) node += CSNodes.Modificator(text=' '.join(accessors)) node += CSNodes.TextNode(text=' } ') signode += node return self.get_fullname(name) def parse_signature(self, sig): match = PROP_SIG_RE.match(sig.strip()) if not match: raise Exception('Invalid property signature. Got: {}'.format(sig)) mod, typ, name, getter, setter = match.groups() return mod, typ.strip(), name.strip(), getter, setter def get_index_text(self, sig, name, typ): rname = '{} (C# {})->{}'.format(name, _('property'), typ) return rname def get_obj_name(self, sig): _, typ, name, _, _ = self.parse_signature(sig) return name, typ class CSharpMethod(CSharpObject): option_spec = {**CSharpObject.option_spec, 'returns': directives.unchanged, **dict(zip([('param(' + str(i) + ')') for i in range(1, 8)], [directives.unchanged] * 7))} _params_list = () def handle_signature(self, sig, signode): mod, typ, name, generic, params = self.parse_signature(sig) node = CSNodes.EmptyNode() node += CSNodes.Modificator(text='{}'.format(mod if mod else 'private')) node += CSNodes.TextNode(text=' ') self.append_ref_signature(typ if typ else name, node) if typ: node += CSNodes.TextNode(text=' ') node += CSNodes.MethodName(text='{}'.format(name)) if generic: self.append_generic(generic, node) param_node = CSNodes.EmptyNode() param_node += CSNodes.TextNode(text='(') if params: self._params_list = self._get_params(params) i = 1 for (pmod, ptyp, pname, pvalue) in self._params_list: pnode = CSNodes.EmptyNode() if pmod: pnode += CSNodes.Keyword(text='{}'.format(pmod)) pnode += CSNodes.TextNode(text=' ') self.append_ref_signature(ptyp, pnode) pnode += CSNodes.TextNode(text=' ') pnode += CSNodes.TextNode(text='{}'.format(pname)) if pvalue: pnode += CSNodes.TextNode(text=' = ') self.append_ref_signature(pvalue, pnode) param_node += pnode if i < len(self._params_list): param_node += CSNodes.TextNode(text=', ') i += 1 param_node += CSNodes.TextNode(text=')') node += param_node signode += node return self.get_fullname(name) def before_content_node(self, node): if 'returns' in self.options: node += CSNodes.Description(title=_('returns').title(), desc=self.options['returns']) def after_content_node(self, node): options_values = list(value for key, value in self.options.items() if key != 'noindex') i = 0 for (_, _, pname, _) in self._params_list: if i < len(options_values): node += CSNodes.Description(title=pname, desc=options_values[i], lower=True) i += 1 def after_content(self): super().after_content() if self._params_list is not None and len(self._params_list) > 0: del self._params_list def parse_signature(self, sig): match = METHOD_SIG_RE.match(sig.strip()) if not match: raise Exception('Invalid method signature. Got: {}'.format(sig)) mod, typ, name, generic, params = match.groups() return mod, typ, name.strip(), generic, params @staticmethod def parse_param_signature(sig): match = PARAM_SIG_RE.match(sig.strip()) if not match: raise Exception('Invalid parameter signature. Got: {}'.format(sig)) mod, typ, name, value = match.groups() return mod, typ.strip(), name.strip(), value def _get_params(self, params): if not params: return None result = [] params_group = split_sig(params) for param in params_group: pmod, ptyp, pname, pvalue = self.parse_param_signature(param) result.append((pmod, ptyp, pname, pvalue)) return result def get_index_text(self, sig, name, typ): params_text = '' if self._params_list: names = [pname for _, _, pname, _ in self._params_list] params_text = '({})'.format(', '.join(names)) if typ: rname = '{}{} (C# {})->{}'.format(name, params_text, _('method'), typ) else: rname = '{}{} (C# {})->{}'.format(name, params_text, _('constructor'), name) return rname def get_obj_name(self, sig): _, typ, name, _, _ = self.parse_signature(sig) return name, typ class CSharpNamespace(Directive): required_arguments = 1 def run(self): env = self.state.document.settings.env namespace = self.arguments[0].strip() if namespace is None: env.ref_context.pop(CSharpObject.PARENT_ATTR_NAME, None) else: env.ref_context[CSharpObject.PARENT_ATTR_NAME] = namespace return [] class CSharpEndType(Directive): required_arguments = 0 def run(self): env = self.state.document.settings.env if CSharpObject.PARENT_TYPE_NAME in env.ref_context: env.ref_context.pop(CSharpObject.PARENT_TYPE_NAME, None) return [] class CSharpXRefRole(XRefRole): def process_link(self, env, refnode, has_explicit_title, title, target): refnode[CSharpObject.PARENT_ATTR_NAME] = env.ref_context.get( CSharpObject.PARENT_ATTR_NAME) return super(CSharpXRefRole, self).process_link(env, refnode, has_explicit_title, title, target) class CSharpIndex(Index): name = 'csharp' localname = 'CSharp Index' shortname = 'CSharp' def generate(self, docnames=None): content = defaultdict(list) objects = self.domain.get_objects() objects = sorted(objects, key=lambda obj: obj[0]) for name, dispname, objtype, docname, anchor, _ in objects: content[dispname.split('.')[-1][0].lower()].append( (dispname, 0, docname, anchor, docname, '', objtype)) content = sorted(content.items()) return content, True class CSharpDomain(Domain): name = 'sphinxsharp' label = 'C#' roles = { 'type': CSharpXRefRole(), 'var': CSharpXRefRole(), 'prop': CSharpXRefRole(), 'meth': CSharpXRefRole(), 'enum': CSharpXRefRole() } object_types = { 'type': ObjType(_('type'), 'type', 'obj'), 'variable': ObjType(_('variable'), 'var', 'obj'), 'property': ObjType(_('property'), 'prop', 'obj'), 'method': ObjType(_('method'), 'meth', 'obj'), 'enum': ObjType(_('enum'), 'enum', 'obj') } directives = { 'namespace': CSharpNamespace, 'end-type': CSharpEndType, 'type': CSharpType, 'variable': CSharpVariable, 'property': CSharpProperty, 'method': CSharpMethod, 'enum': CSharpEnum } indices = { CSharpIndex } initial_data = { 'objects': {} # (objtype, name) -> (docname, objtype(class, struct etc.)) } def clear_doc(self, docname): for (objtype, name), (doc, _) in self.data['objects'].copy().items(): if doc == docname: del self.data['objects'][(objtype, name)] def get_objects(self): for (objtype, name), (docname, _) in self.data['objects'].items(): yield (name, name, objtype, docname, '{}-{}'.format(objtype, name), 0) def resolve_xref(self, env, fromdocname, builder, typ, target, node, contnode): targets = get_targets(target, node) objects = self.data['objects'] roletypes = self.objtypes_for_role(typ) types = ('type', 'enum', 'method') if typ is None else roletypes for t in targets: for objtyp in types: key = (objtyp, t) if key in objects: obj = objects[key] if typ is not None: role = self.role_for_objtype(objtyp) node['reftype'] = role else: contnode = CSNodes.UnknownType(typ=obj[1], text=target) return make_refnode(builder, fromdocname, obj[0], '{}-{}'.format(objtyp, t), contnode, '{} {}'.format(obj[1], t)) if typ is None: contnode = CSNodes.UnknownType(text=target) return None def merge_domaindata(self, docnames, otherdata): for (objtype, name), (docname, typ) in otherdata['objects'].items(): if docname in docnames: self.data['objects'][(objtype, name)] = (docname, typ) def resolve_any_xref(self, env, fromdocname, builder, target, node, contnode): for typ in self.roles: xref = self.resolve_xref(env, fromdocname, builder, typ, target, node, contnode) if xref: return [('sphinxsharp:{}'.format(typ), xref)] return [] class CSNodes: _TYPES = ('class', 'struct', 'interface', 'enum', 'delegate') class BaseNode(nodes.Element): def __init__(self, rawsource='', *children, **attributes): super().__init__(rawsource, *children, **attributes) @staticmethod def visit_html(self, node): self.body.append(self.starttag(node, 'div')) @staticmethod def depart_html(self, node): self.body.append('</div>') class EmptyNode(BaseNode): def __init__(self, rawsource='', *children, **attributes): super().__init__(rawsource, *children, **attributes) @staticmethod def visit_html(self, node): pass @staticmethod def depart_html(self, node): pass class InlineText(BaseNode): def __init__(self, rawsource, type_class, text, *children, **attributes): super().__init__(rawsource, *children, **attributes) if type_class is None: return self['classes'].append(type_class) if text: self.append(nodes.raw(text=text, format='html')) @staticmethod def visit_html(self, node): self.body.append(self.starttag(node, 'span').replace('\n', '')) @staticmethod def depart_html(self, node): self.body.append('</span>') class Description(BaseNode): def __init__(self, rawsource='', title='', desc='', *children, **attributes): super().__init__(rawsource, *children, **attributes) self['classes'].append('desc') if title and desc: if 'lower' not in attributes: title = title[0].upper() + title[1:] node = nodes.raw( text='<strong class="first">{}:</strong><span class="last">{}</span>'.format(title, desc), format='html') self.append(node) else: raise Exception('Title and description must be assigned.') class Modificator(InlineText): def __init__(self, rawsource='', text='', *children, **attributes): super().__init__(rawsource, 'mod', text, *children, **attributes) class UnknownType(InlineText): def __init__(self, rawsource='', typ='', text='', *children, **attributes): objclass = typ if not text: super().__init__(rawsource, None, text, *children, **attributes) return if typ not in CSNodes._TYPES: objclass = 'kw' if typ not in VALUE_KEYWORDS: objclass = 'unknown' super().__init__(rawsource, objclass, text, *children, **attributes) class TextNode(InlineText): def __init__(self, rawsource='', text='', *children, **attributes): super().__init__(rawsource, 'text', text, *children, **attributes) class MethodName(InlineText): def __init__(self, rawsource='', text='', *children, **attributes): super().__init__(rawsource, 'meth-name', text, *children, **attributes) class VariableName(InlineText): def __init__(self, rawsource='', text='', *children, **attributes): super().__init__(rawsource, 'var-name', text, *children, **attributes) class Keyword(InlineText): def __init__(self, rawsource='', text='', *children, **attributes): super().__init__(rawsource, 'kw', text, *children, **attributes) class Enum(InlineText): def __init__(self, rawsource='', text='', *children, **attributes): super().__init__(rawsource, 'enum', text, *children, **attributes) class Generic(InlineText): def __init__(self, rawsource='', text='', *children, **attributes): super().__init__(rawsource, 'generic', text, *children, **attributes) @staticmethod def add_nodes(app): app.add_node(CSNodes.Description, html=(CSNodes.Description.visit_html, CSNodes.Description.depart_html)) app.add_node(CSNodes.Modificator, html=(CSNodes.Modificator.visit_html, CSNodes.Modificator.depart_html)) app.add_node(CSNodes.UnknownType, html=(CSNodes.UnknownType.visit_html, CSNodes.UnknownType.depart_html)) app.add_node(CSNodes.TextNode, html=(CSNodes.TextNode.visit_html, CSNodes.TextNode.depart_html)) app.add_node(CSNodes.Enum, html=(CSNodes.Enum.visit_html, CSNodes.Enum.depart_html)) app.add_node(CSNodes.Keyword, html=(CSNodes.Keyword.visit_html, CSNodes.Keyword.depart_html)) app.add_node(CSNodes.MethodName, html=(CSNodes.MethodName.visit_html, CSNodes.MethodName.depart_html)) app.add_node(CSNodes.VariableName, html=(CSNodes.VariableName.visit_html, CSNodes.VariableName.depart_html)) app.add_node(CSNodes.BaseNode, html=(CSNodes.BaseNode.visit_html, CSNodes.BaseNode.depart_html)) app.add_node(CSNodes.EmptyNode, html=(CSNodes.EmptyNode.visit_html, CSNodes.EmptyNode.depart_html)) app.add_node(CSNodes.Generic, html=(CSNodes.Generic.visit_html, CSNodes.Generic.depart_html)) def split_sig(params): if not params: return None result = [] current = '' level = 0 for char in params: if char in ('<', '{', '['): level += 1 elif char in ('>', '}', ']'): level -= 1 if char != ',' or level > 0: current += char elif char == ',' and level == 0: result.append(current) current = '' if current.strip() != '': result.append(current) return result def get_targets(target, node): targets = [target] if node[CSharpObject.PARENT_ATTR_NAME] is not None: parts = node[CSharpObject.PARENT_ATTR_NAME].split('.') while parts: targets.append('{}.{}'.format('.'.join(parts), target)) parts = parts[:-1] return targets def copy_asset_files(app, exc): package_dir = path.abspath(path.dirname(__file__)) asset_files = [path.join(package_dir, '_static/css/sphinxsharp.css')] if exc is None: # build succeeded for asset_path in asset_files: copy_asset(asset_path, path.join(app.outdir, '_static')) def setup(app): app.connect('build-finished', copy_asset_files) package_dir = path.abspath(path.dirname(__file__)) app.add_domain(CSharpDomain) app.add_css_file('sphinxsharp.css') override_file = path.join(app.confdir, '_static/sphinxsharp-override.css')
# -*- coding: utf-8 -*- """ Created on Tue May 24 20:20:03 2022 @author: d4kro """ #%%-----------0. loading package----------------------------------------------- import pandas as pd import numpy as np import scipy.sparse import matplotlib.pyplot as plt from sklearn import preprocessing from sklearn.model_selection import train_test_split, GridSearchCV, RandomizedSearchCV from sklearn.ensemble import RandomForestClassifier,ExtraTreesClassifier from sklearn.metrics import accuracy_score, confusion_matrix, plot_confusion_matrix from sklearn.datasets import make_classification from sklearn.tree import DecisionTreeClassifier from matplotlib import pyplot from scipy.stats import randint as randint from sklearn.datasets import make_regression from sklearn.preprocessing import StandardScaler # from keras.models import Sequential # from keras.layers import Dense # from keras.optimizers import SGD label_encoder = preprocessing.LabelEncoder() #%%-----------1. loading data-------------------------------------------------- # import data as dataframe df = pd.read_csv('Master_day6.csv',low_memory=False) #%%-----------2. data processing----------------------------------------------- # drop the raw with concentration value of DMSO (solute test) df = df[df["Nom_Conc"].str.contains("DMSO") == False] # change type string to numeric for "conc_name" column df['Nom_Conc'] = pd.to_numeric(df['Nom_Conc']) df.info() # checking the columns # keeping only the needed columns data = df[['Area','Perimeter','Major','Minor','step_length','step_speed', 'abs_angle','rel_angle','Nom_Conc']].copy() data.info()# checking the new columns #%%-----------3. take 5 random line & export it (no use for the code)---------- #sampleDF = data.sample(n = 5) #sampleDF.to_csv('sampleDF.csv') #%%-----------4. delet infinite and nan values--------------------------------- # turn inf values in nan data.replace([np.inf, -np.inf], np.nan, inplace=True) # check that no raw has NaN values data.isna().values.any() # if true -> deleting all raw containing NaN data_noNAN = data.dropna(axis=0) # check again that no raw has NaN values data_noNAN.isna().values.any() #%%-----------5. represent graphicaly data------------------------------------- # select two variables of interest and the concentration X1 = data_noNAN[['Major']].copy() X2 = data_noNAN[['step_speed']].copy() c = data_noNAN[['Nom_Conc']].copy() #encode the concentration c = label_encoder.fit_transform(c) # plot the points fig = plt.figure() plt.scatter(X1, X2, c=c) # Set figure title and axis labels plt.title('step_speed vs abs_angle for each measurement point') plt.xlabel("Major [pixel]") plt.ylabel("step_speed [pixel]") #%%-----------6. split the data------------------------------------------------ # select the variables X = data_noNAN[['step_speed','Major','Minor','step_length']].copy() Y = data_noNAN[['Nom_Conc']].copy() # split the dataset in train, validation and test set X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.3, train_size=0.7) X_test, X_val, y_test, y_val = train_test_split(X, Y, test_size=0.15, train_size=0.15) # label encoding in order to normalise the target variable label_encoder = preprocessing.LabelEncoder() y_train = label_encoder.fit_transform(y_train) y_test = label_encoder.fit_transform(y_test) #checking the length of each dataset print('length of train set is :') print(len(X_train)) print('length of test set is :') print(len(X_test)) print('length of validation set is :') print(len(X_val)) #%%-----------7. RandomForestClassifier---------------------------------------- #%%--------------7.1 train and test the model (RFC & default HP)--------------- # set the classifier rfc = RandomForestClassifier(n_jobs=-1) # fit the data (training) rfc.fit(X_train, y_train) # predict after training on test set RFC_test = rfc.predict(X_test) # print the matrix and the accuracy print('\nMatrix confusion for RandomForestClassifier (Default HP) :') print(confusion_matrix(y_test, RFC_test)) acc_RFC = accuracy_score(y_test, RFC_test) print(f'\nThe accuracy of the model RandomForestClassifier is (Default HP) {acc_RFC:.1%}') #%%--------------7.2 search HP for RFC----------------------------------------- # define HP for to search params = { 'n_estimators': [80,120], 'max_features': ['sqrt','sqrt',None], 'criterion' :['gini', 'entropy','log_loss'] } #define the Gridsearch gsc = GridSearchCV(rfc, params, cv=5,n_jobs=-1) #fit with the Gridsearch gsc.fit(X_train, y_train) #Results key print('\nResults keys :') sorted(gsc.cv_results_.keys()) # print the best hyperparameters print('\nBest params :') print(gsc.best_params_) # and score print('\nBest score :') print(gsc.best_score_) #Best estimator print('\nBest estimator :') gsc.best_estimator_ #%%--------------7.3 train and test the model (RFC & HP)----------------------- # Since no HP where found to optimize the model (see section 7.2), nothing is # written in this part. Look at the 7.4 confusion matrix section to see the # results. #%%--------------7.4 plot the confusion matrix--------------------------------- plot_confusion_matrix(rfc, X_test, y_test) plt.show() #%%-----------8. DecisionTreesClassifier--------------------------------------- #%%--------------8.2 search HP for DTC----------------------------------------- # define HP to search parameters = { 'criterion' : ['gini','entropy'], 'splitter' : ['best','random'], "max_depth": [25,50,75,100,None], 'min_samples_split':[2,3,4,5], 'min_samples_leaf':[1,2,3,4], 'min_weight_fraction_leaf':[0,0.5], 'max_features':[1,2,'auto','sqrt','log2',None] } #define the Gridsearch gsc1 = GridSearchCV(dtc, parameters,cv=5, n_jobs=3) # fit the data (training) gsc1.fit(X_train,y_train) #Results key print('\nResults keys :') sorted(gsc1.cv_results_.keys()) # print the best hyperparameters print('\nBest params :') print(gsc1.best_params_) # and score print('\nBest score :') print(gsc1.best_score_) #Best estimator print('\nBest estimator :') gsc1.best_estimator_ #%%--------------8.3 search HP for DTC (random)-------------------------------- # define HP to random search param_dist = {"max_depth": [25,50,75,100,None], 'min_samples_split':[2,3,4,5], 'min_samples_leaf':[1,2,3,4], 'min_weight_fraction_leaf':[0,0.5], 'max_features':[1,2,'auto','sqrt','log2',None] } #define the Randomizedsearch gsc_rand = RandomizedSearchCV(dtc, param_dist, cv=5,n_jobs=-1) # fit the data (training) gsc_rand.fit(X_train,y_train) # print the results print(" Results from Random Search " ) print("\n The best estimator across ALL searched params:\n", gsc_rand.best_estimator_) print("\n The best score across ALL searched params:\n", gsc_rand.best_score_) print("\n The best parameters across ALL searched params:\n", gsc_rand.best_params_) #%%--------------8.4 train and test the model (DTC & HP)----------------------- # Since no HP where found to optimize the model (see section 7.2 and 8.3), # nothing is written in this part. #%%-----------9. Softmax regression-------------------------------------------- #https://towardsdatascience.com/softmax-regression-in-python-multi-class-classification-3cb560d90cb2 #https://awjuliani.medium.com/simple-softmax-in-python-tutorial-d6b4c4ed5c16#:~:text=Softmax%20regression%20is%20a%20method,any%20number%20of%20possible%20classes. #https://towardsdatascience.com/multiclass-classification-with-softmax-regression-explained-ea320518ea5d #%%--------------9.1 One-hot encoding------------------------------------------ def one_hot(y, c_length): # y--> y_train/test/val # c--> Number of classes. # A zero matrix of size (m, c) y_hot = np.zeros((len(y), c_length)) # Putting 1 for column where the label is, # Using multidimensional indexing. y_hot[np.arange(len(y)), y] = 1 return y_hot #%%--------------9.2 Softmax function------------------------------------------ def softmax(z): # z--> linear part. # subtracting the max of z for numerical stability. z = z/(np.max(z)/16) exp = np.exp(z) # Calculating softmax for all examples. for i in range(len(z)): exp[i] /= np.sum(exp[i]) return exp #%%--------------9.4 Training-------------------------------------------------- def fit(X, y, lr, c, epochs): # X --> Input. # y --> true/target value. # lr --> Learning rate. # c --> Number of classes. # epochs --> Number of iterations. # m-> number of training examples # n-> number of features m, n = X.shape # Initializing weights and bias randomly. w = np.random.random((n, c)) b = np.random.random(c) # Empty list to store losses. losses = [] # Training loop. for epoch in range(epochs): # Calculating hypothesis/prediction. z = np.dot(X,w) + b y_hat = softmax(z) # One-hot encoding y. y_hot = one_hot(y, c) # Calculating the gradient of loss w.r.t w and b. w_grad = (1/m)*np.dot(X.T, (y_hat - y_hot)) b_grad = (1/m)*np.sum(y_hat - y_hot) # Updating the parameters. w = w - lr*w_grad b = b - lr*b_grad # Calculating loss and appending it in the list. loss = -np.mean(np.log(y_hat[np.arange(len(y)), y])) losses.append(loss) # Printing out the loss at every 100th iteration. #if epoch%100==0: print('Epoch {epoch}==> Loss = {loss}' .format(epoch=epoch, loss=loss)) return w, b, losses #%%--------------9.5 train data------------------------------------------------ w, b, l = fit(X_train, y_train, lr=1.5, c=5, epochs=20) #%%--------------9.6 plot the loss function------------------------------------ plt.plot(l) plt.ylabel('Log Loss') plt.xlabel('Iterations') plt.title('Loss Function Graph') #%%--------------9.7 Predict & measure accuracy-------------------------------- def predict(X, w, b): # X --> Input. # w --> weights. # b --> bias. # Predicting z = np.dot(X,w) + b y_hat = softmax(z) # Returning the class with highest probability. return np.argmax(y_hat, axis=1) def accuracy(y, y_hat): return np.sum(y==y_hat)/len(y) #%%--------------9.8 compute the accuracies------------------------------------ train_p = predict(X_train, w, b) print(accuracy(y_train, train_p)) # Accuracy for test set. # Flattening and normalizing. test_p = predict(X_test, w, b) print(accuracy(y_test, test_p)) #%%----------10. Multi-Class Classification Loss Functions--------------------- #%%-------------10.1 define model---------------------------------------------- model = Sequential() model.add(Dense(50, input_dim=2, activation='relu', kernel_initializer='he_uniform')) model.add(Dense(..., activation='softmax')) #%%-------------10.2 compile model--------------------------------------------- opt = SGD(lr=0.01, momentum=0.9) model.compile(loss='...', optimizer=opt, metrics=['accuracy']) #%%-------------10.3 fit model------------------------------------------------- history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=100, verbose=0) #%%-------------10.4 evaluate the model---------------------------------------- train_acc = model.evaluate(X_train, y_train, verbose=0) test_acc = model.evaluate(X_test, y_test, verbose=0) print('Train: %.3f, Test: %.3f' % (train_acc, test_acc)) #%%-------------10.4 plot the results------------------------------------------ # plot loss during training pyplot.subplot(211) pyplot.title('Loss') pyplot.plot(history.history['loss'], label='train') pyplot.plot(history.history['val_loss'], label='test') pyplot.legend() # plot accuracy during training pyplot.subplot(212) pyplot.title('Accuracy') pyplot.plot(history.history['accuracy'], label='train') pyplot.plot(history.history['val_accuracy'], label='test') pyplot.legend() pyplot.show() #%%----------11. Apply the model selected on day 7----------------------------- #%%-------------11.1 data preprocessing---------------------------------------- # import data as dataframe df7 = pd.read_csv('Master_day7.csv',low_memory=False) # drop the raw with concentration value of DMSO (solute test) df7 = df7[df7["Nom_Conc"].str.contains("DMSO") == False] # change type string to numeric for "conc_name" column df7['Nom_Conc'] = pd.to_numeric(df7['Nom_Conc']) df7.info() # checking the columns # keeping only the needed columns data7 = df7[['Area','Perimeter','Major','Minor','step_length','step_speed', 'abs_angle','rel_angle','Nom_Conc']].copy() data7.info()# checking the new columns # turn inf values in nan data7.replace([np.inf, -np.inf], np.nan, inplace=True) # check that no raw has NaN values data7.isna().values.any() # if true -> deleting all raw containing NaN data_noNAN7 = data.dropna(axis=0) # check again that no raw has NaN values data_noNAN7.isna().values.any() #%%-------------11.2 prepare the data------------------------------------------ # select the variables X7 = data_noNAN7[['step_speed','Major','Minor','step_length']].copy() Y7 = data_noNAN7[['Nom_Conc']].copy() # label encoding in order to normalise the target variable label_encoder = preprocessing.LabelEncoder() Y7 = label_encoder.fit_transform(Y7) #%%-------------12.3 Use the model ont the 7 day data-------------------------- # predict after training on test set RFC7 = rfc.predict(X7) # print the matrix and the accuracy print('\nMatrix confusion for RandomForestClassifier for 7 days data (Default HP) :') print(confusion_matrix(Y7, RFC7)) acc_RFC7 = accuracy_score(Y7, RFC7) print(f'\nThe accuracy of the model RandomForestClassifier for 7 days data is (Default HP) {acc_RFC7:.1%}') #%%----------12. Apply the model selected on day 8----------------------------- #%%-------------11.3 Use the model ont the 7 day data-------------------------- #%%----------12. Apply the model selected on day 8----------------------------- # predict after training on test set RFC_test7 = rfc.predict(X_test7) # print the matrix and the accuracy print('\nMatrix confusion for RandomForestClassifier for 7 days data (Default HP) :') print(confusion_matrix(y_test7, RFC_test7)) acc_RFC = accuracy_score(y_test7, RFC_test7) print(f'\nThe accuracy of the model RandomForestClassifier for 7 days data is (Default HP) {acc_RFC:.1%}') #%%-------------12.1 data preprocessing---------------------------------------- # import data as dataframe df8 = pd.read_csv('Master_day8.csv',low_memory=False) # drop the raw with concentration value of DMSO (solute test) df8 = df8[df8["Nom_Conc"].str.contains("DMSO") == False] # change type string to numeric for "conc_name" column df8['Nom_Conc'] = pd.to_numeric(df8['Nom_Conc']) df8.info() # checking the columns # keeping only the needed columns data8 = df8[['Area','Perimeter','Major','Minor','step_length','step_speed', 'abs_angle','rel_angle','Nom_Conc']].copy() data8.info()# checking the new columns # turn inf values in nan data8.replace([np.inf, -np.inf], np.nan, inplace=True) # check that no raw has NaN values data8.isna().values.any() # if
<filename>ipvs.py # Copyright (c) 2015-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. """IPVS module This module exists as a pure-python replacement for ipvsadm. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import six import socket import struct import gnlpy.netlink as netlink # IPVS forwarding methods IPVS_MASQUERADING = 0 IPVS_LOCAL = 1 IPVS_TUNNELING = 2 IPVS_ROUTING = 3 IPVS_METHODS = set([ IPVS_MASQUERADING, IPVS_LOCAL, IPVS_TUNNELING, IPVS_ROUTING ]) # Virtual Service flags IPVS_SVC_F_ONEPACKET = 0x0004 # These are attr_list_types which are nestable. The command attribute list # is ultimately referenced by the messages which are passed down to the # kernel via netlink. These structures must match the type and ordering # that the kernel expects. IpvsStatsAttrList = netlink.create_attr_list_type( 'IpvsStatsAttrList', ('CONNS', netlink.U32Type), ('INPKTS', netlink.U32Type), ('OUTPKTS', netlink.U32Type), ('INBYTES', netlink.U64Type), ('OUTBYTES', netlink.U64Type), ('CPS', netlink.U32Type), ('INPPS', netlink.U32Type), ('OUTPPS', netlink.U32Type), ('INBPS', netlink.U32Type), ('OUTBPS', netlink.U32Type), ) IpvsStatsAttrList64 = netlink.create_attr_list_type( 'IpvsStatsAttrList64', ('CONNS', netlink.U64Type), ('INPKTS', netlink.U64Type), ('OUTPKTS', netlink.U64Type), ('INBYTES', netlink.U64Type), ('OUTBYTES', netlink.U64Type), ('CPS', netlink.U64Type), ('INPPS', netlink.U64Type), ('OUTPPS', netlink.U64Type), ('INBPS', netlink.U64Type), ('OUTBPS', netlink.U64Type), ) IpvsServiceAttrList = netlink.create_attr_list_type( 'IpvsServiceAttrList', ('AF', netlink.U16Type), ('PROTOCOL', netlink.U16Type), ('ADDR', netlink.BinaryType), ('PORT', netlink.Net16Type), ('FWMARK', netlink.U32Type), ('SCHED_NAME', netlink.NulStringType), ('FLAGS', netlink.BinaryType), ('TIMEOUT', netlink.U32Type), ('NETMASK', netlink.U32Type), ('STATS', IpvsStatsAttrList), ('PE_NAME', netlink.NulStringType), ('STATS64', IpvsStatsAttrList64), ) IpvsDestAttrList = netlink.create_attr_list_type( 'IpvsDestAttrList', ('ADDR', netlink.BinaryType), ('PORT', netlink.Net16Type), ('FWD_METHOD', netlink.U32Type), ('WEIGHT', netlink.I32Type), ('U_THRESH', netlink.U32Type), ('L_THRESH', netlink.U32Type), ('ACTIVE_CONNS', netlink.U32Type), ('INACT_CONNS', netlink.U32Type), ('PERSIST_CONNS', netlink.U32Type), ('STATS', IpvsStatsAttrList), ('ADDR_FAMILY', netlink.U16Type), ('STATS64', IpvsStatsAttrList64), ) IpvsDaemonAttrList = netlink.create_attr_list_type( 'IpvsDaemonAttrList', ('STATE', netlink.U32Type), ('MCAST_IFN', netlink.NulStringType), ('SYNC_ID', netlink.U32Type), ) IpvsInfoAttrList = netlink.create_attr_list_type( 'IpvsInfoAttrList', ('VERSION', netlink.U32Type), ('CONN_TAB_SIZE', netlink.U32Type), ) IpvsCmdAttrList = netlink.create_attr_list_type( 'IpvsCmdAttrList', ('SERVICE', IpvsServiceAttrList), ('DEST', IpvsDestAttrList), ('DAEMON', IpvsDaemonAttrList), ('TIMEOUT_TCP', netlink.U32Type), ('TIMEOUT_TCP_FIN', netlink.U32Type), ('TIMEOUT_UDP', netlink.U32Type), ) IpvsMessage = netlink.create_genl_message_type( 'IpvsMessage', 'IPVS', ('NEW_SERVICE', IpvsCmdAttrList), ('SET_SERVICE', IpvsCmdAttrList), ('DEL_SERVICE', IpvsCmdAttrList), ('GET_SERVICE', IpvsCmdAttrList), ('NEW_DEST', IpvsCmdAttrList), ('SET_DEST', IpvsCmdAttrList), ('DEL_DEST', IpvsCmdAttrList), ('GET_DEST', IpvsCmdAttrList), ('NEW_DAEMON', IpvsCmdAttrList), ('DEL_DAEMON', IpvsCmdAttrList), ('GET_DAEMON', IpvsCmdAttrList), ('SET_CONFIG', IpvsCmdAttrList), ('GET_CONFIG', IpvsCmdAttrList), ('SET_INFO', IpvsCmdAttrList), ('GET_INFO', IpvsCmdAttrList), ('ZERO', IpvsCmdAttrList), ('FLUSH', IpvsCmdAttrList), required_modules=['ip_vs'], ) def verbose(f): def g(self, *args, **kwargs): if self.verbose: s_args = [repr(a) for a in args] s_args.extend(['{0}={1}'.format(k, repr(v)) for k, v in six.iteritems(kwargs)]) print('{0}({1})'.format(f.__name__, ', '.join(s_args))) return f(self, *args, **kwargs) return g def _validate_ip(ip): try: socket.inet_pton(_to_af(ip), ip) return True except socket.error: return False def _to_af(ip): return socket.AF_INET6 if ':' in ip else socket.AF_INET def _to_af_union(ip): af = _to_af(ip) return af, socket.inet_pton(af, ip).ljust(16, b'\0') def _from_af_union(af, addr): n = 4 if af == socket.AF_INET else 16 return socket.inet_ntop(af, addr[:n]) def _to_proto_num(proto): if proto is None: return None if proto.lower() == 'tcp': return socket.IPPROTO_TCP elif proto.lower() == 'udp': return socket.IPPROTO_UDP else: assert False, 'unknown proto %s' % proto def _from_proto_num(n): if n is None: return None if n == socket.IPPROTO_TCP: return 'tcp' elif n == socket.IPPROTO_UDP: return 'udp' else: assert False, 'unknown proto num %d' % n class Dest(object): """Describes a real server to be load balanced to.""" def __init__(self, d={}, validate=False): self.ip_ = d.get('ip', None) self.weight_ = d.get('weight', None) self.port_ = d.get('port', None) self.fwd_method_ = d.get('fwd_method', IPVS_TUNNELING) self.counters_ = d.get('counters', {}) def __repr__(self): return 'Dest(d=dict(ip="%s", weight=%d))' % (self.ip(), self.weight()) def counters(self): return self.counters_ def ip(self): return self.ip_ def weight(self): return self.weight_ def port(self): return self.port_ def fwd_method(self): return self.fwd_method_ def validate(self): assert _validate_ip(self.ip_) assert isinstance(self.weight_, int) assert self.weight_ >= -1 assert self.fwd_method_ in IPVS_METHODS def to_dict(self): return { 'ip': self.ip_, 'weight': self.weight_, } def to_attr_list(self): af, addr = _to_af_union(self.ip_) return IpvsDestAttrList(addr_family=af, addr=addr, port=self.port_, fwd_method=self.fwd_method_) def __eq__(self, other): return isinstance(other, Dest) and self.to_dict() == other.to_dict() def __ne__(self, other): return not self.__eq__(other) @staticmethod def from_attr_list(lst, default_af=None): return Dest( d={ 'ip': _from_af_union(lst.get('addr_family', default_af), lst.get('addr')), 'weight': lst.get('weight'), 'port': lst.get('port'), 'fwd_method': lst.get('fwd_method'), 'counters': { 'active_conns': lst.get('active_conns'), 'inact_conns': lst.get('inact_conns'), 'persist_conns': lst.get('persist_conns'), 'conns': lst.get('stats').get('conns'), 'inpkts': lst.get('stats').get('inpkts'), 'outpkts': lst.get('stats').get('outpkts'), 'inbytes': lst.get('stats').get('inbytes'), 'outbytes': lst.get('stats').get('outbytes'), 'cps': lst.get('stats').get('cps'), 'inpps': lst.get('stats').get('inpps'), 'outpps': lst.get('stats').get('outpps'), 'inbps': lst.get('stats').get('inbps'), 'outbps': lst.get('stats').get('outbps') } }, validate=True, ) class Service(object): """Describes a load balanced service. """ def __init__(self, d={}, validate=False): self.proto_ = d.get('proto', None) self.vip_ = d.get('vip', None) self.port_ = d.get('port', None) self.sched_ = d.get('sched', None) self.fwmark_ = d.get('fwmark', None) default_af = None if self.vip_: default_af = _to_af(self.vip_) self.af_ = d.get('af', default_af) self.counters_ = d.get('counters', {}) if validate: self.validate() def __repr__(self): if self.fwmark_ is not None: return 'Service(d=dict(fwmark=%d, sched="%s", af="%s"))' % ( self.fwmark(), self.sched(), self.af()) return 'Service(d=dict(proto="%s", vip="%s", port=%d, sched="%s"))' % ( self.proto(), self.vip(), self.port(), self.sched()) def counters(self): return self.counters_ def af(self): return self.af_ def fwmark(self): return self.fwmark_ def proto(self): return self.proto_ def proto_num(self): return _to_proto_num(self.proto_) def port(self): return self.port_ def vip(self): return self.vip_ def sched(self): return self.sched_ def validate(self): assert self.af_ in [socket.AF_INET, socket.AF_INET6] if self.vip_ or self.port_ or self.proto_: assert self.proto_.lower() in ['tcp', 'udp'] assert _validate_ip(self.vip_) assert isinstance(self.port_, int) assert self.port_ > 0 and self.port_ < (2 ** 16) assert self.fwmark_ is None else: assert isinstance(self.fwmark_, int) assert self.proto_ is None assert self.port_ is None assert self.vip_ is None assert self.fwmark_ > 0 and self.fwmark_ < (2 ** 32) def to_dict(self): self.validate() if self.fwmark_ is None: return { 'proto': self.proto_, 'vip': self.vip_, 'port': self.port_, 'sched': self.sched_, 'af': self.af_ } else: return { 'fwmark': self.fwmark_, 'sched': self.sched_, 'af': self.af_ } def to_attr_list(self): if self.fwmark_ is None: af, addr = _to_af_union(self.vip_) netmask = ((1 << 32) - 1) if af == socket.AF_INET else 128 proto = self.proto_num() return IpvsServiceAttrList(af=af, addr=addr, protocol=proto, netmask=netmask, port=self.port_, sched_name=self.sched_, flags=struct.pack(str('=II'), 0, 0)) else: netmask = ((1 << 32) - 1) return IpvsServiceAttrList(fwmark=self.fwmark_, af=self.af_, netmask=netmask, sched_name=self.sched_, flags=struct.pack(str('=II'), 0, 0)) def __eq__(self, other): return isinstance(other, Service) and self.to_dict() == other.to_dict() def __ne__(self, other): return not self.__eq__(other) @staticmethod def from_attr_list(lst): if lst.get('addr', None) is not None: d = dict( vip=_from_af_union(lst.get('af'), lst.get('addr')), proto=_from_proto_num(lst.get('protocol')), port=lst.get('port'), sched=lst.get('sched_name'), af=lst.get('af'), counters={ 'conns': lst.get('stats').get('conns'), 'inpkts': lst.get('stats').get('inpkts'), 'outpkts': lst.get('stats').get('outpkts'), 'inbytes': lst.get('stats').get('inbytes'), 'outbytes': lst.get('stats').get('outbytes'), 'cps': lst.get('stats').get('cps'), 'inpps': lst.get('stats').get('inpps'), 'outpps': lst.get('stats').get('outpps'), 'inbps': lst.get('stats').get('inbps'), 'outbps': lst.get('stats').get('outbps') } ) else: d = dict( fwmark=lst.get('fwmark'), sched=lst.get('sched_name'), af=lst.get('af'), ) return Service(d=d, validate=True) class Pool(object): """A tuple of a service and an array of dests for that service """ def __init__(self, d={}, validate=False): self.service_ = Service(d.get('service', {}), validate) self.dests_ = [Dest(x, validate) for x in d.get('dests', [])] def service(self): return self.service_ def dests(self): return self.dests_ def validate(self): self.service_.validate() for dest in self.dests_: dest.validate() def to_dict(self): self.validate() return { 'service': self.service_.to_dict(), 'dests': [d.to_dict() for d in self.dests_], } @staticmethod def from_args(service=None, dests=[]): assert isinstance(service, Service) assert isinstance(dests, list) p = Pool() p.service_ = service p.dests_ = dests return p @staticmethod def load_pools_from_json_list(lst): return [Pool(i, True) for i in lst] class IpvsClient(object): """A python client to use instead of shelling out to ipvsadm """ def __init__(self, verbose=False): self.verbose = verbose self.nlsock = netlink.NetlinkSocket(verbose=verbose) def __modify_service(self, method, vip, port, protocol, ops, **svc_kwargs): if ops: assert protocol == socket.IPPROTO_UDP af, addr = _to_af_union(vip) netmask = ((1 << 32) - 1) if af == socket.AF_INET else 128 flags = 0 if ops: flags |= IPVS_SVC_F_ONEPACKET out_msg = IpvsMessage( method, flags=netlink.MessageFlags.ACK_REQUEST, attr_list=IpvsCmdAttrList( service=IpvsServiceAttrList( af=af, port=port, protocol=protocol, addr=addr, netmask=netmask, flags=struct.pack(str('=II'), flags, flags), **svc_kwargs ) ) ) self.nlsock.execute(out_msg) @verbose def add_service(self, vip, port, protocol=socket.IPPROTO_TCP, sched_name='rr', ops=False): self.__modify_service('new_service', vip, port, protocol, ops, sched_name=sched_name, timeout=0) @verbose def del_service(self, vip, port, protocol=socket.IPPROTO_TCP): self.__modify_service('del_service', vip, port, protocol, False) def __modify_fwm_service(self, method, fwmark, af, **svc_kwargs): netmask = ((1 << 32) - 1) if af == socket.AF_INET else 128 out_msg = IpvsMessage( method, flags=netlink.MessageFlags.ACK_REQUEST, attr_list=IpvsCmdAttrList( service=IpvsServiceAttrList( fwmark=fwmark, flags=struct.pack(str('=II'), 0, 0), af=af, netmask=netmask, **svc_kwargs ) ) ) self.nlsock.execute(out_msg) @verbose def add_fwm_service(self, fwmark, sched_name='rr', af=socket.AF_INET): self.__modify_fwm_service('new_service', fwmark, sched_name=sched_name, timeout=0, af=af) @verbose def del_fwm_service(self, fwmark, af=socket.AF_INET): self.__modify_fwm_service('del_service', fwmark, af=af) def __modify_dest(self, method, vip, port, rip, rport=None, protocol=socket.IPPROTO_TCP, **dest_kwargs): vaf, vaddr = _to_af_union(vip) raf, raddr = _to_af_union(rip) rport = rport or port out_msg = IpvsMessage( method, flags=netlink.MessageFlags.ACK_REQUEST, attr_list=IpvsCmdAttrList( service=IpvsServiceAttrList( af=vaf, port=port, protocol=protocol, addr=vaddr, ), dest=IpvsDestAttrList( addr_family=raf, addr=raddr, port=rport, **dest_kwargs ), ), ) self.nlsock.execute(out_msg) @verbose def add_dest(self, vip, port, rip, rport=None, protocol=socket.IPPROTO_TCP, weight=1, method=IPVS_TUNNELING): self.__modify_dest('new_dest', vip, port, rip, rport, protocol=protocol, weight=weight, fwd_method=method, l_thresh=0, u_thresh=0) @verbose def update_dest(self, vip, port, rip, rport=None, protocol=socket.IPPROTO_TCP, weight=None, method=IPVS_TUNNELING): self.__modify_dest('set_dest', vip, port, rip, rport, protocol, weight=weight, l_thresh=0, u_thresh=0, fwd_method=method) @verbose def del_dest(self, vip, port, rip, rport=None, protocol=socket.IPPROTO_TCP): self.__modify_dest('del_dest', vip, port, rip, rport, protocol) def __modify_fwm_dest(self, method, fwmark, rip, vaf, port, **dest_kwargs): raf, raddr =
<filename>strax/storage/common.py """Base classes for storage backends, frontends, and savers in strax. Please see the developer documentation for more details on strax' storage hierarchy. """ from ast import literal_eval from concurrent.futures import wait import logging from packaging import version import time import typing import warnings import numpy as np import strax export, __all__ = strax.exporter() @export class DataKey: """Request for data to a storage registry Instances of this class uniquely identify a single piece of strax data abstractly -- that is, it describes the full history of algorithms that have to be run to reproduce it. It is used for communication between the main Context class and storage frontends. """ run_id: str data_type: str lineage: dict # Do NOT use directly, use the lineage_hash method _lineage_hash = '' def __init__(self, run_id, data_type, lineage): self.run_id = run_id self.data_type = data_type self.lineage = lineage def __repr__(self): return '-'.join([self.run_id, self.data_type, self.lineage_hash]) @property def lineage_hash(self): """Deterministic hash of the lineage""" # We cache the hash computation to benefit tight loops calling # this property if self._lineage_hash == '': self._lineage_hash = strax.deterministic_hash(self.lineage) return self._lineage_hash @export class DataNotAvailable(Exception): """Raised when requested data is not available""" pass @export class EmptyDataWarning(UserWarning): pass @export class DataExistsError(Exception): """Raised when attempting to write a piece of data that is already written""" def __init__(self, at, message=''): super().__init__(message) self.at = at @export class DataCorrupted(Exception): pass @export class RunMetadataNotAvailable(Exception): pass @export class StorageFrontend: """Interface to something that knows data-locations and run-level metadata. For example, a runs database, or a data directory on the file system. """ backends: list can_define_runs = False provide_run_metadata = False def __init__(self, readonly=False, provide_run_metadata=None, overwrite='if_broken', take_only=tuple(), exclude=tuple()): """ :param readonly: If True, throws CannotWriteData whenever saving is attempted. :param overwrite: When to overwrite data that already exists. - 'never': Never overwrite any data. - 'if_broken': Only overwrites data if it is incomplete or broken. - 'always': Always overwrite data. Use with caution! :param take_only: Provide/accept only these data types. :param exclude: Do NOT provide/accept these data types. :param provide_run_metadata: Whether to provide run-level metadata (run docs). If None, use class-specific default If take_only and exclude are both omitted, provide all data types. If a data type is listed in both, it will not be provided. Attempting to read/write unwanted data types throws DataTypeNotWanted. """ if overwrite not in 'never if_broken always'.split(): raise RuntimeError(f"Invalid 'overwrite' setting {overwrite}. ") self.take_only = strax.to_str_tuple(take_only) self.exclude = strax.to_str_tuple(exclude) self.overwrite = overwrite if provide_run_metadata is not None: self.provide_run_metadata = provide_run_metadata self.readonly = readonly self.log = logging.getLogger(self.__class__.__name__) def loader(self, key: DataKey, time_range=None, allow_incomplete=False, fuzzy_for=tuple(), fuzzy_for_options=tuple(), chunk_number=None, executor=None): """Return loader for data described by DataKey. :param key: DataKey describing data :param time_range: 2-length arraylike of (start, exclusive end) of row numbers to get. Default is None, which means get the entire run. :param allow_incomplete: Allow loading of data which has not been completely written to disk yet. :param fuzzy_for: list/tuple of plugin names for which no plugin name, version, or option check is performed. :param fuzzy_for_options: list/tuple of configuration options for which no check is performed. :param chunk_number: Chunk number to load exclusively. :param executor: Executor for pushing load computation to """ backend, backend_key = self.find(key, write=False, allow_incomplete=allow_incomplete, fuzzy_for=fuzzy_for, fuzzy_for_options=fuzzy_for_options) return self._get_backend(backend).loader( backend_key, time_range=time_range, executor=executor, chunk_number=chunk_number) def saver(self, key, metadata): """Return saver for data described by DataKey.""" backend, backend_key = self.find(key, write=True) return self._get_backend(backend).saver(backend_key, metadata) def get_metadata(self, key, allow_incomplete=False, fuzzy_for=tuple(), fuzzy_for_options=tuple()): """Retrieve data-level metadata for the specified key. Other parameters are the same as for .find """ backend, backend_key = self.find(key, write=False, check_broken=False, allow_incomplete=allow_incomplete, fuzzy_for=fuzzy_for, fuzzy_for_options=fuzzy_for_options) return self._get_backend(backend).get_metadata(backend_key) def _we_take(self, data_type): """Return if data_type can be provided by this frontend""" return not (data_type in self.exclude or self.take_only and data_type not in self.take_only) def find(self, key: DataKey, write=False, check_broken=True, allow_incomplete=False, fuzzy_for=tuple(), fuzzy_for_options=tuple()): """Return (str: backend class name, backend-specific) key to get at / write data, or raise exception. :param key: DataKey of data to load {data_type: (plugin_name, version, {config_option: value, ...}, ...} :param write: Set to True if writing new data. The data is immediately registered, so you must follow up on the write! :param check_broken: If True, raise DataNotAvailable if data has not been complete written, or writing terminated with an exception. """ message = ( f"\nRequested lineage: {key.lineage}." f"\nIgnoring plugin lineage for: {fuzzy_for}." f"\nIgnoring config options: {fuzzy_for}.") if not self._we_take(key.data_type): raise DataNotAvailable( f"{self} does not accept or provide data type {key.data_type}") if write: if self.readonly: raise DataNotAvailable(f"{self} cannot write any-data, " "it's readonly") try: at = self.find(key, write=False, allow_incomplete=allow_incomplete, fuzzy_for=fuzzy_for, fuzzy_for_options=fuzzy_for_options) raise DataExistsError( at=at, message=(f"Data already exists at {at}.\n" + message)) except DataNotAvailable: pass try: backend_name, backend_key = self._find( key=key, write=write, allow_incomplete=allow_incomplete, fuzzy_for=fuzzy_for, fuzzy_for_options=fuzzy_for_options) except DataNotAvailable: raise DataNotAvailable( f"{key.data_type} for {key.run_id} not available." + message) if not write and check_broken: # Get the metadata to check if the data is broken meta = self._get_backend(backend_name).get_metadata(backend_key) if 'exception' in meta: exc = meta['exception'] raise DataNotAvailable( f"Data in {backend_name} {backend_key} corrupted due to " f"exception during writing: {exc}.") if 'writing_ended' not in meta and not allow_incomplete: raise DataNotAvailable( f"Data in {backend_name} {backend_key} corrupted. No " f"writing_ended field present!") return backend_name, backend_key def _get_backend(self, backend): for b in self.backends: if b.__class__.__name__ == backend: return b raise KeyError(f"Unknown storage backend {backend} specified") def _matches(self, lineage: dict, desired_lineage: dict, fuzzy_for: tuple, fuzzy_for_options: tuple): """Return if lineage matches desired_lineage given ignore options """ if not (fuzzy_for or fuzzy_for_options): return lineage == desired_lineage args = [fuzzy_for, fuzzy_for_options] return ( self._filter_lineage(lineage, *args) == self._filter_lineage(desired_lineage, *args)) @staticmethod def _filter_lineage(lineage, fuzzy_for, fuzzy_for_options): """Return lineage without parts to be ignored in matching""" return {data_type: (v[0], v[1], {option_name: b for option_name, b in v[2].items() if option_name not in fuzzy_for_options}) for data_type, v in lineage.items() if data_type not in fuzzy_for} def _can_overwrite(self, key: DataKey): if self.overwrite == 'always': return True if self.overwrite == 'if_broken': metadata = self.get_metadata(key) return not ('writing_ended' in metadata and 'exception' not in metadata) return False def find_several(self, keys, **kwargs): """Return list with backend keys or False for several data keys. Options are as for find() """ # You can override this if the backend has a smarter way # of checking availability (e.g. a single DB query) result = [] for key in keys: try: r = self.find(key, **kwargs) except (strax.DataNotAvailable, strax.DataCorrupted): r = False result.append(r) return result def define_run(self, name, sub_run_spec, **metadata): self.write_run_metadata(name, dict( sub_run_spec=sub_run_spec, **metadata)) ## # Abstract methods (to override in child) ## def _scan_runs(self, store_fields): """Iterable of run document / metadata dictionaries """ yield from tuple() def _find(self, key: DataKey, write, allow_incomplete, fuzzy_for, fuzzy_for_options): """Return backend key (e.g. for filename) for data identified by key, raise DataNotAvailable, or DataExistsError Parameters are as for find. """ # Use the self._matches attribute to compare lineages according to # the fuzzy options raise NotImplementedError def run_metadata(self, run_id, projection=None): """Return run metadata dictionary, or raise RunMetadataNotAvailable""" raise NotImplementedError def write_run_metadata(self, run_id, metadata): """Stores metadata for run_id. Silently overwrites any previously stored run-level metadata.""" raise NotImplementedError def remove(self, key): """Removes a registration. Does not delete any actual data""" raise NotImplementedError @export class StorageBackend: """Storage backend for strax data. This is a 'dumb' interface to data. Each bit of data stored is described by backend-specific keys (e.g. directory names). Finding and assigning backend keys is the responsibility of the StorageFrontend. The backend class name + backend_key must together uniquely identify a piece of data. So don't make __init__ take options like 'path' or 'host', these have to be hardcoded (or made part of the key). """ def loader(self, backend_key, time_range=None, chunk_number=None, executor=None): """Iterates over strax data in backend_key :param time_range: 2-length arraylike of (start, exclusive end) of desired data. Will return all data that partially overlaps with the range. Default is None, which means get the entire :param chunk_number: Chunk number to get exclusively :param executor: Executor to push load/decompress operations to """ metadata = self.get_metadata(backend_key) if 'strax_version' in metadata: v_old = metadata['strax_version'] if version.parse(v_old) < version.parse('0.9.0'): raise strax.DataNotAvailable( f"Cannot load data at {backend_key}: " f"it was created with strax {v_old}, " f"but you have strax {strax.__version__}. ") else: warnings.warn(f"Data
<filename>cnosolar/gui_config.py ############################### # CONFIGURATION GUI # ############################### import json import pytz import pvlib import requests import traitlets import numpy as np import pandas as pd import ipywidgets as widgets from tkinter import Tk, filedialog from IPython.display import display from cnosolar.pvsyst_tools import pvsyst def execute(): ''' Graphical user interface for the configuration of the PV plant and download of the corresponding .JSON file. The JSON file data structure contains the following parameters: 1. latitude : float Latitude based on the location of the PV plant in decimal degrees notation. 2. longitude : float Longitude based on the location of the PV plant in decimal degrees notation. 3. tz : string Time zone of the location of the PV plant. 4. altitude : float Altitude based on the location of the PV plant from sea level in [m]. 5. surface_type : string Surface type to determine the albedo. Optional if albedo is not known. 6. surface_albedo : float Albedo. 7. inverters_database : string Repository of inverters arranged by PVlib. Valid options are: CECInverter, SandiaInverter or ADRInverter. If the configuration method is PVsyst or Manual, the value is set to null. 8. inverter_name : string Inverter name following the according repository format. If the configuration method is PVsyst or Manual, the value is set to null. 9. inverter : dict Set of technical parameters that defines the inverter. - Main Parameters of SNL PVlib Method 1. Paco: Inverter rated AC power in W. 2. Pdco: Inverter rated DC power in W. 3. Vdco: DC voltage at which the nominal AC Power is reached with the DC Power input in V. 4. Pso: DC power required to start the inversion process in W. 5. C0: Parameter that defines the curvature of the relationship between AC Power and DC Power in STC condition in 1/W. 6. C1: Empirical coefficient that allows the Nominal DC Power to vary linearly with the DC Voltage in 1/V. 7. C2: Empirical coefficient that allows the DC Starting Power to vary linearly with the DC Voltage in 1/V. 8. C3: Empirical coefficient that allows $C_0$ to vary linearly with the DC Voltage by 1/V. 9. Pnt: AC power consumed by the inverter during the night in W. - Main Parameters of NREL PVWatts Method 1. Pdco: Inverter rated DC power in W. 2. eta_inv_nom: Dimensionless nominal efficiency of the inverter. 10. ac_model : string Inverter modeling method to be used. Valid options are: sandia or pvwatts. 11. modules_database : string Repository of PV modules arranged by PVlib. Valid options are: pvmodule or cecmodul). If the configuration method is PVFree, PVsyst or Manual, the value is set to null. 12. module_name : string PV module name following the according repository format. If the configuration method is PVFree, PVsyst or Manual, the value is set to null. 13. module : dict Set of technical parameters that defines the PV module. - Main Parameters 1. T_NOCT: Nominal operating cell temperature in ºC. 2. Technology: PV cell technology. Valid options are: monosi, multisi, cigs, cdte, asi or None. 3. N_s: Number of PV cells in series. 4. I_sc_ref: Short circuit current under STC conditions in A. 5. V_oc_ref: Open circuit voltage under STC conditions in V. 6. I_mp_ref: Current at the point of maximum power under STC conditions in A. 7. V_mp_ref: Voltage at the point of maximum power under STC conditions in V. 8. alpha_sc: Temperature coefficient of the short-circuit current in A/ºC. 9. beta_oc: Open circuit voltage temperature coefficient in V/ºC. 10. gamma_r: Temperature coefficient of the power at the maximum point in %/ºC. 11. STC: Nominal power of the PV module under STC conditions in W. 14. bifacial : bool Defines if the PV module is bifacial or not. 15. bifaciality : float Fraction between the efficiency of the front and rear side of the PV module, measured under STC conditions. 16. row_height : float Height of the rows of photovoltaic panels measured at their center in units of meters. 17. row_width : float Width of the rows of photovoltaic panels in the 2D plane considered in units of meters (e.g., 1P, 2P, 4L). 18. with_tracker : bool Parameter that checks if the mounting of the array is either on fixed-tilt racking or horizontal single axis tracker. 19. surface_azimuth : float or list Azimuth angle of the module surface. North = 0, East = 90, South = 180 and West = 270. If with_tracker = true, the value is set to null. 20. surface_tilt : float or list Surface tilt angles. The tilt angle is defined as degrees from horizontal (e.g. surface facing up = 0, surface facing horizon = 90). If with_tracker = true, the value is set to null. 21. axis_tilt : float Tilt of the axis of rotation with respect to horizontal (e.g. a value of 0º indicates that the support axis of the photovoltaic panels is horizontal) in [degrees]. If with_tracker = false, the value is set to null. 22. axis_azimuth : float Perpendicular angle to the axis of rotation by right hand rule (e.g., a value of 180º indicates a rotation from east to west) in [degrees]. If with_tracker = false, the value is set to null. 23. max_angle : float Maximum angle of rotation of the tracker from its horizontal position (e.g., a value of 90º allows the tracker to rotate to and from a vertical position where the panel faces the horizon) in [degrees]. If with_tracker = false, the value is set to null. 24. module_type : string PV module mounting and front and back insolation sheets materials. Valid options are: open_rack_glass_glass, close_mount_glass_glass or insulated_back_glass_polymer. 25. racking_model : string, optional Racking of the PV modules. Valid strings are 'open_rack', 'close_mount', and 'insulated_back'. Used to identify a parameter set for the SAPM cell temperature model. 26. num_arrays : int Set of arrangements connected to an inverter. Each subarray consists of modules in series per string, strings in parallel, and the number of inputs to the inverter (either full inputs per inverter or number of MPPT inputs). 27. modules_per_string : int or list Number of modules in series per string in each subarray. 28. strings_per_inverter : int or list Number of strings in parallel in each subarray. 29. num_inverter : int Number of inverters with electrical configuration exactly equal to the one defined. It allows to scale theproduction calculations. 30. loss : float Overall DC system losses in percentage. Default = 14.6 31. kpc : float Transmission losses up to the common coupling point of the inverters. Default = 0.0 32. kt : float Losses associated with the transformation (voltage rise). Default = 0.0 33. kin : float Interconnection losses, transmission up to the trade border. Default = 0.0 34. name : string Suffix to the name of the configuration file (system_config_suffix). Default = 'system_config' ''' ############################### # DOCUMENTATION TAB # ############################### gui_layout = widgets.Layout(display='flex', flex_flow='row', justify_content='space-between') doc_location = widgets.HTML(''' <h5>Información Geográfica</h5> <ul> <li> <b>Latitud:</b> Utilice la notación de grados decimales.</li> <li> <b>Longitud:</b> Utilice la notación de grados decimales.</li> <li> <b>Altitud:</b> Altitud desde el nivel del mar en metros (m.s.n.m).</li> <li> <b>Huso Horario:</b> Con referencia a UTC. Por defecto: América/Bogotá (UTC-5).</li> <li> <b>Superficie:</b> Tipo de superficie para determinar el albedo. <span style='color:red'>Opcional si desconoce el albedo</span>.</li> <li> <b>Albedo:</b> Utilice un valor porcentual en escala entre 0 y 1.</li> </ul>''', layout=widgets.Layout(height='auto')) doc_inverter = widgets.HTMLMath(''' <h5>Método
<filename>extensions/aria_extension_tosca/simple_v1_0/functions.py # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from cStringIO import StringIO from aria.utils.collections import FrozenList from aria.utils.formatting import as_raw, safe_repr from aria.parser import dsl_specification from aria.parser.exceptions import InvalidValueError from aria.parser.modeling import (Function, CannotEvaluateFunctionException) from aria.parser.validation import Issue # # Intrinsic # @dsl_specification('4.3.1', 'tosca-simple-1.0') class Concat(Function): """ The :code:`concat` function is used to concatenate two or more string values within a TOSCA service template. """ def __init__(self, context, presentation, argument): self.locator = presentation._locator if not isinstance(argument, list): raise InvalidValueError( 'function "concat" argument must be a list of string expressions: %s' % safe_repr(argument), locator=self.locator) string_expressions = [] for index, an_argument in enumerate(argument): string_expressions.append(parse_string_expression(context, presentation, 'concat', index, None, an_argument)) self.string_expressions = FrozenList(string_expressions) @property def as_raw(self): string_expressions = [] for string_expression in self.string_expressions: if hasattr(string_expression, 'as_raw'): string_expression = as_raw(string_expression) string_expressions.append(string_expression) return {'concat': string_expressions} def _evaluate(self, context, container): value = StringIO() for e in self.string_expressions: if hasattr(e, '_evaluate'): e = e._evaluate(context, container) value.write(str(e)) return value.getvalue() @dsl_specification('4.3.2', 'tosca-simple-1.0') class Token(Function): """ The :code:`token` function is used within a TOSCA service template on a string to parse out (tokenize) substrings separated by one or more token characters within a larger string. """ def __init__(self, context, presentation, argument): self.locator = presentation._locator if (not isinstance(argument, list)) or (len(argument) != 3): raise InvalidValueError('function "token" argument must be a list of 3 parameters: %s' % safe_repr(argument), locator=self.locator) self.string_with_tokens = parse_string_expression(context, presentation, 'token', 0, 'the string to tokenize', argument[0]) self.string_of_token_chars = parse_string_expression(context, presentation, 'token', 1, 'the token separator characters', argument[1]) self.substring_index = parse_int(context, presentation, 'token', 2, 'the 0-based index of the token to return', argument[2]) @property def as_raw(self): string_with_tokens = self.string_with_tokens if hasattr(string_with_tokens, 'as_raw'): string_with_tokens = as_raw(string_with_tokens) string_of_token_chars = self.string_with_tokens if hasattr(string_of_token_chars, 'as_raw'): string_of_token_chars = as_raw(string_of_token_chars) return {'token': [string_with_tokens, string_of_token_chars, self.substring_index]} def _evaluate(self, context, container): string_with_tokens = self.string_with_tokens if hasattr(string_with_tokens, '_evaluate'): string_with_tokens = string_with_tokens._evaluate(context, container) # pylint: disable=no-member # # Property # @dsl_specification('4.4.1', 'tosca-simple-1.0') class GetInput(Function): """ The :code:`get_input` function is used to retrieve the values of properties declared within the inputs section of a TOSCA Service Template. """ def __init__(self, context, presentation, argument): self.locator = presentation._locator self.input_property_name = parse_string_expression(context, presentation, 'get_input', None, 'the input property name', argument) if isinstance(self.input_property_name, basestring): the_input = context.presentation.get_from_dict('service_template', 'topology_template', 'inputs', self.input_property_name) if the_input is None: raise InvalidValueError( 'function "get_input" argument is not a valid input name: %s' % safe_repr(argument), locator=self.locator) @property def as_raw(self): return {'get_input': as_raw(self.input_property_name)} def _evaluate(self, context, container): # pylint: disable=unused-argument if not context.modeling.instance: raise CannotEvaluateFunctionException() the_input = context.modeling.instance.inputs.get( self.input_property_name, context.modeling.model.inputs.get(self.input_property_name)) return the_input.value if the_input is not None else None @dsl_specification('4.4.2', 'tosca-simple-1.0') class GetProperty(Function): """ The :code:`get_property` function is used to retrieve property values between modelable entities defined in the same service template. """ def __init__(self, context, presentation, argument): self.locator = presentation._locator if (not isinstance(argument, list)) or (len(argument) < 2): raise InvalidValueError( 'function "get_property" argument must be a list of at least 2 string expressions: ' '%s' % safe_repr(argument), locator=self.locator) self.modelable_entity_name = parse_modelable_entity_name(context, presentation, 'get_property', 0, argument[0]) # The first of these will be tried as a req-or-cap name: self.nested_property_name_or_index = argument[1:] @property def as_raw(self): return {'get_property': [self.modelable_entity_name] + self.nested_property_name_or_index} def _evaluate(self, context, container): modelable_entities = get_modelable_entities(context, container, self.locator, self.modelable_entity_name) req_or_cap_name = self.nested_property_name_or_index[0] for modelable_entity in modelable_entities: if hasattr(modelable_entity, 'requirement_templates') \ and modelable_entity.requirement_templates \ and (req_or_cap_name in modelable_entity.requirement_templates): # First argument refers to a requirement properties = modelable_entity.requirement_templates[req_or_cap_name].properties nested_property_name_or_index = self.nested_property_name_or_index[1:] elif hasattr(modelable_entity, 'capability_templates') \ and modelable_entity.capability_templates \ and (req_or_cap_name in modelable_entity.capability_templates): # First argument refers to a capability properties = modelable_entity.capability_templates[req_or_cap_name].properties nested_property_name_or_index = self.nested_property_name_or_index[1:] else: properties = modelable_entity.properties nested_property_name_or_index = self.nested_property_name_or_index if properties: found = True value = properties for name in nested_property_name_or_index: if (isinstance(value, dict) and (name in value)) \ or (isinstance(value, list) and name < len(list)): value = value[name] if hasattr(value, '_evaluate'): value = value._evaluate(context, modelable_entity) else: found = False break if found: return value raise InvalidValueError( 'function "get_property" could not find "%s" in modelable entity "%s"' \ % ('.'.join(self.nested_property_name_or_index), self.modelable_entity_name), locator=self.locator) # # Attribute # @dsl_specification('4.5.1', 'tosca-simple-1.0') class GetAttribute(Function): """ The :code:`get_attribute` function is used to retrieve the values of named attributes declared by the referenced node or relationship template name. """ def __init__(self, context, presentation, argument): self.locator = presentation._locator if (not isinstance(argument, list)) or (len(argument) < 2): raise InvalidValueError( 'function "get_attribute" argument must be a list of at least 2 string expressions:' ' %s' % safe_repr(argument), locator=self.locator) self.modelable_entity_name = parse_modelable_entity_name(context, presentation, 'get_attribute', 0, argument[0]) # The first of these will be tried as a req-or-cap name: self.nested_property_name_or_index = argument[1:] @property def as_raw(self): return {'get_attribute': [self.modelable_entity_name] + self.nested_property_name_or_index} def _evaluate(self, context, container): # pylint: disable=no-self-use,unused-argument raise CannotEvaluateFunctionException() # # Operation # @dsl_specification('4.6.1', 'tosca-simple-1.0') class GetOperationOutput(Function): """ The :code:`get_operation_output` function is used to retrieve the values of variables exposed / exported from an interface operation. """ def __init__(self, context, presentation, argument): self.locator = presentation._locator if (not isinstance(argument, list)) or (len(argument) != 4): raise InvalidValueError( 'function "get_operation_output" argument must be a list of 4 parameters: %s' % safe_repr(argument), locator=self.locator) self.modelable_entity_name = parse_string_expression(context, presentation, 'get_operation_output', 0, 'modelable entity name', argument[0]) self.interface_name = parse_string_expression(context, presentation, 'get_operation_output', 1, 'the interface name', argument[1]) self.operation_name = parse_string_expression(context, presentation, 'get_operation_output', 2, 'the operation name', argument[2]) self.output_variable_name = parse_string_expression(context, presentation, 'get_operation_output', 3, 'the output name', argument[3]) @property def as_raw(self): interface_name = self.interface_name if hasattr(interface_name, 'as_raw'): interface_name = as_raw(interface_name) operation_name = self.operation_name if hasattr(operation_name, 'as_raw'): operation_name = as_raw(operation_name) output_variable_name = self.output_variable_name if hasattr(output_variable_name, 'as_raw'): output_variable_name = as_raw(output_variable_name) return {'get_operation_output': [self.modelable_entity_name, interface_name, operation_name, output_variable_name]} # # Navigation # @dsl_specification('4.7.1', 'tosca-simple-1.0') class GetNodesOfType(Function): """ The :code:`get_nodes_of_type` function can be used to retrieve a list of all known instances of nodes of the declared Node Type. """ def __init__(self, context, presentation, argument): self.locator = presentation._locator self.node_type_name = parse_string_expression(context, presentation, 'get_nodes_of_type', None, 'the node type name', argument) if isinstance(self.node_type_name, basestring): node_types = context.presentation.get('service_template', 'node_types') if (node_types is None) or (self.node_type_name not in node_types): raise InvalidValueError( 'function "get_nodes_of_type" argument is not a valid node type name: %s' % safe_repr(argument), locator=self.locator) @property def as_raw(self): node_type_name = self.node_type_name if hasattr(node_type_name, 'as_raw'): node_type_name = as_raw(node_type_name) return {'get_nodes_of_type': node_type_name} def _evaluate(self, context, container): pass # # Artifact # @dsl_specification('4.8.1', 'tosca-simple-1.0') class GetArtifact(Function): """ The :code:`get_artifact` function is used to retrieve artifact location between modelable entities defined in the same service template. """ def __init__(self, context, presentation, argument): self.locator = presentation._locator if (not isinstance(argument, list)) or (len(argument) < 2) or (len(argument) > 4): raise InvalidValueError( 'function "get_artifact" argument must be a list of 2 to 4 parameters: %s' % safe_repr(argument), locator=self.locator) self.modelable_entity_name = parse_string_expression(context, presentation, 'get_artifact', 0, 'modelable entity name', argument[0]) self.artifact_name = parse_string_expression(context, presentation, 'get_artifact', 1, 'the artifact name', argument[1]) self.location = parse_string_expression(context, presentation, 'get_artifact', 2, 'the location or "LOCAL_FILE"', argument[2]) self.remove = parse_bool(context, presentation, 'get_artifact', 3, 'the removal flag', argument[3]) @property def as_raw(self): artifact_name = self.artifact_name if hasattr(artifact_name, 'as_raw'): artifact_name = as_raw(artifact_name) location = self.location if hasattr(location, 'as_raw'): location = as_raw(location) return {'get_artifacts': [self.modelable_entity_name, artifact_name, location, self.remove]} # # Utils # def get_function(context, presentation, value): functions = context.presentation.presenter.functions if isinstance(value, dict) and (len(value) == 1): key = value.keys()[0] if key in functions: try: return True, functions[key](context, presentation, value[key]) except InvalidValueError as e: context.validation.report(issue=e.issue) return True, None return False, None def parse_string_expression(context, presentation, name, index, explanation, value): # pylint: disable=unused-argument is_function, func = get_function(context, presentation, value) if is_function: return func else: value = str(value) return value def parse_int(context, presentation, name, index, explanation, value): # pylint: disable=unused-argument if not isinstance(value, int): try: value = int(value) except ValueError: raise invalid_value(name, index, 'an integer', explanation, value, presentation._locator) return value def parse_bool(context, presentation, name, index, explanation, value): # pylint: disable=unused-argument if not isinstance(value, bool): raise
contain a valid structure: {}".format(self.job_name) ) def db_entry(self): """ Generate the initial database entry Returns: (dict): db_dict """ db_dict = super(AtomisticGenericJob, self).db_entry() if self.structure: if isinstance(self.structure, Atoms): parent_structure = self.structure.get_parent_basis() else: parent_structure = self.structure.copy() db_dict["ChemicalFormula"] = parent_structure.get_chemical_formula() return db_dict def restart(self, job_name=None, job_type=None): """ Restart a new job created from an existing calculation. Args: project (pyiron_atomistics.project.Project instance): Project instance at which the new job should be created job_name (str): Job name job_type (str): Job type Returns: new_ham: New job """ new_ham = super(AtomisticGenericJob, self).restart( job_name=job_name, job_type=job_type ) if isinstance(new_ham, GenericMaster) and not isinstance(self, GenericMaster): new_child = self.restart(job_name=None, job_type=None) new_ham.append(new_child) if self.number_of_structures > 0: new_ham.structure = self.get_structure(frame=-1) else: new_ham.structure = self.structure.copy() new_ham._generic_input["structure"] = "atoms" return new_ham def get_workdir_file(self, filename: str) -> None: """ Checks if a given file exists within the job's working directory and returns the absolute path to it. ToDo: Move this to pyiron_base since this is more generic. Args: filename (str): The name of the file Returns: str: The name absolute path of the file in the working directory Raises: FileNotFoundError: Raised if the given file does not exist. """ appended_path = posixpath.join(self.working_directory, filename) if not os.path.isfile(appended_path): raise FileNotFoundError( f"File {filename} not found in working directory: {self.working_directory}" ) return appended_path # Required functions def continue_with_restart_files(self, job_type=None, job_name=None): """ Args: job_type: job_name: Returns: """ if job_name is None: job_name = "{}_continue".format(self.job_name) new_ham = self.restart(job_type=job_type, job_name=job_name) if self.status.initialized: self._job_id = self.save() new_ham.parent_id = self.job_id new_ham._generic_input["structure"] = "continue_final" return new_ham def continue_with_final_structure(self, job_type=None, job_name=None): """ Args: job_type: job_name: Returns: """ if job_name is None: job_name = "{}_continue".format(self.job_name) if job_type is None: job_type = self.__name__ new_ham = self.create_job(job_type, job_name) if self.status.initialized: self._job_id = self.save() new_ham.parent_id = self.job_id if self.status.finished: new_ham.structure = self.get_structure(iteration_step=-1) new_ham._generic_input["structure"] = "atoms" else: new_ham._generic_input["structure"] = "continue_final" return new_ham def trajectory( self, stride=1, center_of_mass=False, atom_indices=None, snapshot_indices=None, overwrite_positions=None, overwrite_cells=None, ): """ Returns a `Trajectory` instance containing the necessary information to describe the evolution of the atomic structure during the atomistic simulation. Args: stride (int): The trajectories are generated with every 'stride' steps center_of_mass (bool): False (default) if the specified positions are w.r.t. the origin atom_indices (list/ndarray): The atom indices for which the trajectory should be generated snapshot_indices (list/ndarray): The snapshots for which the trajectory should be generated overwrite_positions (list/ndarray): List of positions that are meant to overwrite the existing trajectory. Useful to wrap coordinates for example overwrite_cells(list/ndarray): List of cells that are meant to overwrite the existing trajectory. Only used when `overwrite_positions` is defined. This must have the same length of `overwrite_positions` Returns: pyiron_atomistics.atomistics.job.atomistic.Trajectory: Trajectory instance """ cells = self.output.cells if len(self.output.indices) != 0: indices = self.output.indices else: indices = [self.structure.indices] * len( cells ) # Use the same indices throughout if overwrite_positions is not None: positions = np.array(overwrite_positions).copy() if overwrite_cells is not None: if overwrite_cells.shape == (len(positions), 3, 3): cells = np.array(overwrite_cells).copy() else: raise ValueError( "overwrite_cells must be compatible with the positions!" ) else: positions = self.output.positions.copy() conditions = list() if isinstance(cells, (list, np.ndarray)): if len(cells) == 0: conditions.append(True) else: conditions.append(cells[0] is None) conditions.append(cells is None) if any(conditions): max_pos = np.max(np.max(positions, axis=0), axis=0) max_pos[np.abs(max_pos) < 1e-2] = 10 cell = np.eye(3) * max_pos cells = np.array([cell] * len(positions)) if len(positions) != len(cells): raise ValueError("The positions must have the same length as the cells!") if snapshot_indices is not None: positions = positions[snapshot_indices] cells = cells[snapshot_indices] indices = indices[snapshot_indices] if atom_indices is None: return Trajectory( positions[::stride], self.structure.get_parent_basis(), center_of_mass=center_of_mass, cells=cells[::stride], indices=indices[::stride], ) else: sub_struct = self.structure.get_parent_basis()[atom_indices] if len(sub_struct.species) < len(self.structure.species): # Then `sub_struct` has had its indices remapped so they run from 0 to the number of species - 1 # But the `indices` array is unaware of this and needs to be remapped to this new space original_symbols = np.array( [el.Abbreviation for el in self.structure.species] ) sub_symbols = np.array([el.Abbreviation for el in sub_struct.species]) map_ = np.array( [ np.argwhere(original_symbols == symbol)[0, 0] for symbol in sub_symbols ], dtype=int, ) remapped_indices = np.array(indices) for i_sub, i_original in enumerate(map_): np.place(remapped_indices, indices == i_original, i_sub) else: remapped_indices = indices return Trajectory( positions[::stride, atom_indices, :], sub_struct, center_of_mass=center_of_mass, cells=cells[::stride], indices=remapped_indices[::stride, atom_indices], ) def write_traj( self, filename, file_format=None, parallel=True, append=False, stride=1, center_of_mass=False, atom_indices=None, snapshot_indices=None, overwrite_positions=None, overwrite_cells=None, **kwargs, ): """ Writes the trajectory in a given file file_format based on the `ase.io.write`_ function. Args: filename (str): Filename of the output file_format (str): The specific file_format of the output parallel (bool): ase parameter append (bool): ase parameter stride (int): Writes trajectory every `stride` steps center_of_mass (bool): True if the positions are centered on the COM atom_indices (list/numpy.ndarray): The atom indices for which the trajectory should be generated snapshot_indices (list/numpy.ndarray): The snapshots for which the trajectory should be generated overwrite_positions (list/numpy.ndarray): List of positions that are meant to overwrite the existing trajectory. Useful to wrap coordinates for example overwrite_cells(list/numpy.ndarray): List of cells that are meant to overwrite the existing trajectory. Only used when `overwrite_positions` is defined. This must have the same length of `overwrite_positions` **kwargs: Additional ase arguments .. _ase.io.write: https://wiki.fysik.dtu.dk/ase/_modules/ase/io/formats.html#write """ traj = self.trajectory( stride=stride, center_of_mass=center_of_mass, atom_indices=atom_indices, snapshot_indices=snapshot_indices, overwrite_positions=overwrite_positions, overwrite_cells=overwrite_cells, ) # Using thr ASE output writer ase_write( filename=filename, images=traj, format=file_format, parallel=parallel, append=append, **kwargs, ) def get_neighbors_snapshots( self, snapshot_indices=None, num_neighbors=12, **kwargs ): """ Get the neighbors only for the required snapshots from the trajectory Args: snapshot_indices (list/numpy.ndarray): Snapshots for which the the neighbors need to be computed (eg. [1, 5, 10,..., 100] num_neighbors (int): The cutoff for the number of neighbors **kwargs (dict): Additional arguments to be passed to the `get_neighbors()` routine (eg. cutoff_radius, norm_order , etc.) Returns: pyiron_atomistics.atomistics.structure.neighbors.NeighborsTrajectory: `NeighborsTraj` instances containing the neighbor information. """ return self.trajectory().get_neighbors_snapshots( snapshot_indices=snapshot_indices, num_neighbors=num_neighbors, **kwargs ) def get_neighbors(self, start=0, stop=-1, stride=1, num_neighbors=12, **kwargs): """ Get the neighbors for a given section of the trajectory Args: start (int): Start point of the slice of the trajectory to be sampled stop (int): End point of of the slice of the trajectory to be sampled stride (int): Samples the snapshots evert `stride` steps num_neighbors (int): The cutoff for the number of neighbors **kwargs (dict): Additional arguments to be passed to the `get_neighbors()` routine (eg. cutoff_radius, norm_order , etc.) Returns: pyiron_atomistics.atomistics.structure.neighbors.NeighborsTrajectory: `NeighborsTraj` instances containing the neighbor information. """ return self.trajectory().get_neighbors( start=start, stop=stop, stride=stride, num_neighbors=num_neighbors, **kwargs ) # Compatibility functions @deprecate("Use get_structure()") def get_final_structure(self): """ Get the final structure calculated from the job. Returns: :class:`.Atoms` """ return self.get_structure(iteration_step=-1) def _get_structure(self, frame=-1, wrap_atoms=True): if self.structure is None: raise AssertionError("Structure not set") if self.output.cells is not None: try: cell = self.output.cells[frame] except IndexError: if wrap_atoms: raise IndexError("cell at step ", frame, " not found") from None cell = None if self.output.indices is not None: try: indices = self.output.indices[frame] except IndexError: indices = None if indices is not None and len(indices) != len(self.structure): snapshot = Atoms( species=self.structure.species, indices=indices, positions=np.zeros(indices.shape + (3,)), cell=cell, pbc=self.structure.pbc, ) else: snapshot = self.structure.copy() if cell is not None: snapshot.cell = cell if indices is not None: snapshot.indices = indices if self.output.positions is not None: if wrap_atoms: snapshot.positions = self.output.positions[frame] snapshot.center_coordinates_in_unit_cell() elif len(self.output.unwrapped_positions) > max([frame, 0]): snapshot.positions = self.output.unwrapped_positions[frame] else: snapshot.positions += self.output.total_displacements[frame] return snapshot def _number_of_structures(self): return self.output.positions.shape[0] def map(self, function, parameter_lst): """ Create :class:`.MapMaster` with the current job as reference job. The job name is created as 'map_{self.name}' Args: function (callable): passed as `modify_function` to the map master parameter_list (list): passed as `parameter_list` to the map master Returns: :class:`.MapMaster`: newly created master job """ master = self.create_job( job_type=self.project.job_type.MapMaster, job_name="map_" + self.job_name ) master.modify_function = function master.parameter_list = parameter_lst return master def gui(self): """ Returns: """ ProjectGUI(self) def _structure_to_hdf(self): if self.structure is not None and self._generic_input["structure"] == "atoms": with self.project_hdf5.open("input") as hdf5_input: self.structure.to_hdf(hdf5_input) def _structure_from_hdf(self): if ( "structure" in self.project_hdf5["input"].list_groups() and self._generic_input["structure"] == "atoms" ): with self.project_hdf5.open("input") as hdf5_input: self.structure = Atoms().from_hdf(hdf5_input) def _write_chemical_formular_to_database(self): if self.structure: parent_structure = self.structure.get_parent_basis() self.project.db.item_update( {"ChemicalFormula": parent_structure.get_chemical_formula()}, self._job_id, ) def _before_successor_calc(self, ham): if ham._generic_input["structure"] == "continue_final": ham.structure = self.get_structure(iteration_step=-1) ham.to_hdf() def set_structure(job, parameter): job.structure
f: f.write(content) except Exception as e: LOGERR(e) def format_json(resultset, single_record=False, field_filter=0): """Return results in JSON format. Parameters ---------- resultset : list Search results from DB query. single_record : bool, optional If True, indicates only one record. Default is False. field_filter : int, optional Indicates format for displaying bookmarks. Default is 0. Returns ------- json Record(s) in JSON format. """ if single_record: marks = {} for row in resultset: if field_filter == 1: marks["uri"] = row[1] elif field_filter == 2: marks["uri"] = row[1] marks["tags"] = row[3][1:-1] elif field_filter == 3: marks["title"] = row[2] elif field_filter == 4: marks["uri"] = row[1] marks["tags"] = row[3][1:-1] marks["title"] = row[2] else: marks["index"] = row[0] marks["uri"] = row[1] marks["title"] = row[2] marks["description"] = row[4] marks["tags"] = row[3][1:-1] else: marks = [] for row in resultset: if field_filter == 1: record = {"uri": row[1]} elif field_filter == 2: record = {"uri": row[1], "tags": row[3][1:-1]} elif field_filter == 3: record = {"title": row[2]} elif field_filter == 4: record = {"uri": row[1], "title": row[2], "tags": row[3][1:-1]} else: record = { "index": row[0], "uri": row[1], "title": row[2], "description": row[4], "tags": row[3][1:-1], } marks.append(record) return json.dumps(marks, sort_keys=True, indent=4) def print_json_safe(resultset, single_record=False, field_filter=0): """Prints json results and handles IOError Parameters ---------- resultset : list Search results from DB query. single_record : bool, optional If True, indicates only one record. Default is False. field_filter : int, optional Indicates format for displaying bookmarks. Default is 0. Returns ------- None """ try: print(format_json(resultset, single_record, field_filter)) except IOError: try: sys.stdout.close() except IOError: pass try: sys.stderr.close() except IOError: pass def is_int(string): """Check if a string is a digit. string : str Input string to check. Returns ------- bool True on success, False on exception. """ try: int(string) return True except Exception: return False def browse(url): """Duplicate stdin, stdout and open URL in default browser. .. Note:: Duplicates stdin and stdout in order to suppress showing errors on the terminal. Parameters ---------- url : str URL to open in browser. Attributes ---------- suppress_browser_output : bool True if a text based browser is detected. Must be initialized (as applicable) to use the API. override_text_browser : bool If True, tries to open links in a GUI based browser. """ if not parse_url(url).scheme: # Prefix with 'http://' if no scheme # Otherwise, opening in browser fails anyway # We expect http to https redirection # will happen for https-only websites LOGERR("Scheme missing in URI, trying http") url = "http://" + url browser = webbrowser.get() if browse.override_text_browser: browser_output = browse.suppress_browser_output for name in [b for b in webbrowser._tryorder if b not in TEXT_BROWSERS]: browser = webbrowser.get(name) LOGDBG(browser) # Found a GUI browser, suppress browser output browse.suppress_browser_output = True break if browse.suppress_browser_output: _stderr = os.dup(2) os.close(2) _stdout = os.dup(1) if "microsoft" not in platform.uname()[3].lower(): os.close(1) fd = os.open(os.devnull, os.O_RDWR) os.dup2(fd, 2) os.dup2(fd, 1) try: if sys.platform != "win32": browser.open(url, new=2) else: # On Windows, the webbrowser module does not fork. # Use threads instead. def browserthread(): webbrowser.open(url, new=2) t = threading.Thread(target=browserthread) t.start() except Exception as e: LOGERR("browse(): %s", e) finally: if browse.suppress_browser_output: os.close(fd) os.dup2(_stderr, 2) os.dup2(_stdout, 1) if browse.override_text_browser: browse.suppress_browser_output = browser_output def check_upstream_release(): """Check and report the latest upstream release version.""" global MYPROXY if MYPROXY is None: gen_headers() ca_certs = os.getenv("BUKU_CA_CERTS", default=CA_CERTS) if MYPROXY: manager = urllib3.ProxyManager( MYPROXY, num_pools=1, headers=MYHEADERS, cert_reqs="CERT_REQUIRED", ca_certs=ca_certs, ) else: manager = urllib3.PoolManager( num_pools=1, headers={"User-Agent": USER_AGENT}, cert_reqs="CERT_REQUIRED", ca_certs=ca_certs, ) try: r = manager.request( "GET", "https://api.github.com/repos/jarun/buku/releases?per_page=1", headers={"User-Agent": USER_AGENT}, ) except Exception as e: LOGERR(e) return if r.status == 200: latest = json.loads(r.data.decode(errors="replace"))[0]["tag_name"] if latest == "v" + __version__: print("This is the latest release") else: print("Latest upstream release is %s" % latest) else: LOGERR("[%s] %s", r.status, r.reason) manager.clear() def regexp(expr, item): """Perform a regular expression search. Parameters ---------- expr : regex Regular expression to search for. item : str Item on which to perform regex search. Returns ------- bool True if result of search is not None, else False. """ if expr is None or item is None: LOGDBG("expr: [%s], item: [%s]", expr, item) return False return re.search(expr, item, re.IGNORECASE) is not None def delim_wrap(token): """Returns token string wrapped in delimiters. Parameters ---------- token : str String item to wrap with DELIM. Returns ------- str Token string wrapped by DELIM. """ if token is None or token.strip() == "": return DELIM if token[0] != DELIM: token = DELIM + token if token[-1] != DELIM: token = token + DELIM return token def read_in(msg): """A wrapper to handle input() with interrupts disabled. Parameters ---------- msg : str String to pass to to input(). """ disable_sigint_handler() message = None try: message = input(msg) except KeyboardInterrupt: print("Interrupted.") enable_sigint_handler() return message def sigint_handler(signum, frame): """Custom SIGINT handler. .. Note:: Neither signum nor frame are used in this custom handler. However, they are required parameters for signal handlers. Parameters ---------- signum : int Signal number. frame : frame object or None. """ global INTERRUPTED INTERRUPTED = True print("\nInterrupted.", file=sys.stderr) # Do a hard exit from here os._exit(1) DEFAULT_HANDLER = signal.signal(signal.SIGINT, sigint_handler) def disable_sigint_handler(): """Disable signint handler.""" signal.signal(signal.SIGINT, DEFAULT_HANDLER) def enable_sigint_handler(): """Enable sigint handler.""" signal.signal(signal.SIGINT, sigint_handler) # --------------------- # Editor mode functions # --------------------- def get_system_editor(): """Returns default system editor is $EDITOR is set.""" return os.environ.get("EDITOR", "none") def is_editor_valid(editor): """Check if the editor string is valid. Parameters ---------- editor : str Editor string. Returns ------- bool True if string is valid, else False. """ if editor == "none": LOGERR("EDITOR is not set") return False if editor == "0": LOGERR("Cannot edit index 0") return False return True def to_temp_file_content(url, title_in, tags_in, desc): """Generate temporary file content string. Parameters ---------- url : str URL to open. title_in : str Title to add manually. tags_in : str Comma-separated tags to add manually. desc : str String description. Returns ------- str Lines as newline separated string. Raises ------ AttributeError when tags_in is None. """ strings = [ ( '# Lines beginning with "#" will be stripped.\n' "# Add URL in next line (single line)." ), ] # URL if url is not None: strings += (url,) # TITLE strings += ( ( "# Add TITLE in next line (single line). " 'Leave blank to web fetch, "-" for no title.' ), ) if title_in is None: title_in = "" elif title_in == "": title_in = "-" strings += (title_in,) # TAGS strings += ("# Add comma-separated TAGS in next line (single line).",) strings += (tags_in.strip(DELIM),) if not None else "" # DESC strings += ( '# Add COMMENTS in next line(s). Leave blank to web fetch, "-" for no comments.', ) if desc is None: strings += ("\n",) elif desc == "": strings += ("-",) else: strings += (desc,) return "\n".join(strings) def parse_temp_file_content(content): """Parse and return temporary file content. Parameters ---------- content : str String of content. Returns ------- tuple (url, title, tags, comments) url: URL to open title: string title to add manually tags: string of comma-separated tags to add manually comments: string description """ content = content.split("\n") content = [c for c in content if not c or c[0] != "#"] if not content or content[0].strip() == "": print("Edit aborted") return None url = content[0] title = None if len(content) > 1: title = content[1] if title == "": title = None elif title == "-": title = "" tags = DELIM if len(content) > 2: tags = parse_tags([content[2]]) comments = [] if len(content) > 3: comments = list(content[3:]) # need to remove all empty line that are at the end # and not those in the middle of the text for i in range(len(comments) - 1, -1, -1): if comments[i].strip() != "": break if i == -1: comments = [] else: comments = comments[0 : i + 1] comments = "\n".join(comments) if comments == "": comments = None elif comments == "-": comments = "" return url, title, tags, comments def edit_rec(editor, url, title_in, tags_in, desc): """Edit a bookmark record. Parameters ---------- editor : str Editor to
specified axis(es). Equivalent to CAReduce(scalar.and_, axis=axis) """ def __init__(self, axis=None): CAReduce.__init__(self, scalar.and_, axis) def _output_dtype(self, idtype): return "int8" def __str__(self): if self.axis is None: return "All" else: return "All{%s}" % ", ".join(map(str, self.axis)) def make_node(self, input): input = as_tensor_variable(input) if input.dtype not in ["int8", "uint8"]: input = theano.tensor.neq(input, 0) ret = super(All, self).make_node(input) return ret class Any(CAReduce): """ Applies `bitwise or` to all the values of a tensor along the specified axis(es). Equivalent to CAReduce(scalar.or_, axis=axis) """ def __init__(self, axis=None): CAReduce.__init__(self, scalar.or_, axis) def _output_dtype(self, idtype): return "int8" def __str__(self): if self.axis is None: return "Any" else: return "Any{%s}" % ", ".join(map(str, self.axis)) def make_node(self, input): input = as_tensor_variable(input) if input.dtype not in ["int8", "uint8"]: input = theano.tensor.neq(input, 0) ret = super(Any, self).make_node(input) return ret class CAReduceDtype(CAReduce): """ Reduces a scalar operation along the specified axis(es). This subclass of CAReduce accepts an additional "dtype" parameter, that specifies which dtype the output should be. It also accepts an optional "acc_dtype", which specify the dtype that will be used for the accumulation. So, the accumulation will be done into a tensor of dtype "acc_dtype", then it will be casted into "dtype" and returned. If no dtype is provided, one will be inferred so as not to lose too much precision. """ def __init__(self, scalar_op, axis=None, dtype=None, acc_dtype=None): """ Usage: CAReduceDtype(scalar_op, axis=None, dtype=None, acc_dtype=None) :param scalar_op: a binary scalar op with only one output. It must be commutative and associative. :param axis: - the dimension along which we want to reduce - list of dimensions that we want to reduce - if None, all dimensions are reduced :param dtype: The dtype of the returned tensor. If None, then we use the default dtype which is the same as the input tensor's dtype except when: - the input dtype is a signed integer of precision < 64 bit, in which case we use int64 - the input dtype is an unsigned integer of precision < 64 bit, in which case we use uint64 This default dtype does _not_ depend on the value of "acc_dtype". This behavior is similar in spirit to that of numpy (except numpy uses the default machine integer while we always use 64 bit integers to avoid platform-dependent behavior). :param acc_dtype: The dtype of the internal accumulator. If None (default), we use the dtype in the list below, or the input dtype if its precision is higher: - for int dtypes, we use at least int64; - for uint dtypes, we use at least uint64; - for float dtypes, we use at least float64; - for complex dtypes, we use at least complex128. """ CAReduce.__init__(self, scalar_op, axis=axis) self.dtype = dtype self.acc_dtype = acc_dtype def __eq__(self, other): return (CAReduce.__eq__(self, other) and self.dtype == other.dtype and self.acc_dtype == other.acc_dtype) def __hash__(self): return CAReduce.__hash__(self) ^ hash((self.dtype, self.acc_dtype)) def __setstate__(self, d): super(CAReduceDtype, self).__setstate__(d) if not hasattr(self, "dtype"): # This is needed as old pickled will crash otherwise. # We need to keep the old dtype behavior as the op # could be in an apply node with a specified dtype. self.dtype = "OLD" if not hasattr(self, "acc_dtype"): # acc_dtype is not used by any external Op, so we do not # need to keep the previous behaviour here. self.acc_dtype = None def _output_dtype(self, idtype): dtype = self.dtype if dtype == "OLD": return dict( int8='int32', int16='int32', int32='int64', uint8='uint32', uint16='uint32', uint32='uint64', ).get(idtype, idtype) if dtype is None: # If input has a discrete dtype, upcast it to 64 return dict( int8='int64', int16='int64', int32='int64', uint8='uint64', uint16='uint64', uint32='uint64', ).get(idtype, idtype) else: # The important is that the accumulator dtype does not # lose precision. Then, the result can be downcasted. return dtype def _acc_dtype(self, idtype): acc_dtype = self.acc_dtype if acc_dtype is None: return dict( int8='int64', int16='int64', int32='int64', uint8='uint64', uint16='uint64', uint32='uint64', float32='float64', complex64='complex128', ).get(idtype, idtype) elif (acc_dtype in theano.tensor.continuous_dtypes and idtype in theano.tensor.discrete_dtypes): # Specifying a continuous accumulator for discrete input is OK return acc_dtype else: # The conversion has to be considered an upcast. upcasted_dtype = scalar.upcast(idtype, acc_dtype) if acc_dtype != upcasted_dtype: raise TypeError( 'Cannot build %s node with input dtype %s ' 'and acc_dtype %s, as precision would be lost. ' 'To correct this error, you can:\n' ' - not specify acc_dtype, or\n' ' - use an acc_dtype at least as precise as %s.\n' ' - specify "dtype" instead of "acc_dtype", so ' 'the reduction will be precise, but the result will ' 'be casted into "dtype" at the end.\n' 'If you are expecting the precision loss, you can ' 'use tensor.cast(..., dtype="%s"), on your input.' % (self, idtype, acc_dtype, upcasted_dtype, acc_dtype)) return acc_dtype def make_node(self, input): # We need to redefine make_node so that, if self.dtype is None, # we can infer what dtype should be, and create a node from an Op # of the appropriate dtype. input = as_tensor_variable(input) dtype = self._output_dtype(input.dtype) acc_dtype = self._acc_dtype(input.dtype) assert dtype is not None assert acc_dtype is not None if dtype == self.dtype and acc_dtype == self.acc_dtype: # Don't build another instance op = self else: op = copy(self) op.set_ufunc(self.scalar_op) op.dtype = dtype op.acc_dtype = acc_dtype assert op.acc_dtype is not None return CAReduce.make_node(op, input) class Sum(CAReduceDtype): """ Sums all the values of a tensor along the specified axis(es). Equivalent to CAReduceDtype(scalar.add, axis=axis, dtype=dtype), with the difference that this defines the gradient of sum wrt its tensor input. """ def __init__(self, axis=None, dtype=None, acc_dtype=None): """ Constructor. :param axis: Axis(es) along which the tensor should be summed (use None to sum over all axes, and a list or tuple to sum along more than one axis). :param dtype: The dtype of the internal accumulator and returned tensor. If None, then we use the default dtype which is the same as the input tensor's dtype except when: - the input dtype is a signed integer of precision < 64 bit, in which case we use int64 - the input dtype is an unsigned integer of precision < 64 bit, in which case we use uint64 This value does not depend on the value of "acc_dtype". :param acc_dtype: The dtype of the internal accumulator. If None (default), we use the dtype in the list below, or the input dtype if its precision is higher: - for int dtypes, we use at least int64; - for uint dtypes, we use at least uint64; - for float dtypes, we use at least float64; - for complex dtypes, we use at least complex128. """ CAReduceDtype.__init__(self, scalar.add, axis=axis, dtype=dtype, acc_dtype=acc_dtype) def grad(self, inp, grads): x, = inp out = self(*inp) if out.dtype.find('int') != -1: return [x.zeros_like(dtype=theano.config.floatX)] gz, = grads gz = as_tensor_variable(gz) axis = self.axis if axis is None: axis = range(x.type.ndim) if axis == (): return gz, new_dims = [] i = 0 for j, _ in enumerate(x.type.broadcastable): if j in axis: new_dims.append('x') else: new_dims.append(i) i += 1 ds_op = DimShuffle(gz.type.broadcastable, new_dims) gx = Elemwise(scalar.second)(x, ds_op(gz)) return [gx] def R_op(self, inputs, eval_points): # There is just one element in inputs and eval_points, the axis are # part of self if None in eval_points: return [None] return self(*eval_points, **dict(return_list=True)) def __str__(self): if self.axis is None: return "Sum" else: return "Sum{%s}" % ", ".join(map(str, self.axis)) class Prod(CAReduceDtype): """ Multiplies all the values of a tensor along the specified axis(es). Equivalent to CAReduce(scalar.prod, axis = axis), with the difference that this defines the gradient of prod wrt its tensor input. """ def __init__(self, axis=None, dtype=None, acc_dtype=None, no_zeros_in_input=False): CAReduceDtype.__init__(self, scalar.mul, axis=axis, dtype=dtype, acc_dtype=acc_dtype) self.no_zeros_in_input = no_zeros_in_input def __setstate__(self, dct): super(Prod, self).__setstate__(dct) # Add default value to be able to reload old pickled objects. if 'no_zeros_in_input' not in dct: self.no_zeros_in_input = False def __eq__(self, other): return (CAReduceDtype.__eq__(self, other) and self.no_zeros_in_input == other.no_zeros_in_input) def __hash__(self): return (CAReduceDtype.__hash__(self) ^ hash(self.no_zeros_in_input)) def grad(self, inp, grads): ''' The grad of this Op could be very easy, if it is
on channel 2 computed from CAL1. CS_l1b_mds['Data']['R_inst_range'] = np.ma.zeros((n_records,n_blocks),dtype=np.int32) # Instrument Gain Correction: transmit-receive antenna (dB/100) # Calibration correction to gain on channel 1 computed from CAL1 CS_l1b_mds['Data']['TR_inst_gain'] = np.ma.zeros((n_records,n_blocks),dtype=np.int32) # Instrument Gain Correction: receive-only (dB/100) # Calibration correction to gain on channel 2 computed from CAL1 CS_l1b_mds['Data']['R_inst_gain'] = np.ma.zeros((n_records,n_blocks),dtype=np.int32) # Internal Phase Correction (microradians) CS_l1b_mds['Data']['Internal_phase'] = np.ma.zeros((n_records,n_blocks),dtype=np.int32) # External Phase Correction (microradians) CS_l1b_mds['Data']['External_phase'] = np.ma.zeros((n_records,n_blocks),dtype=np.int32) # Noise Power measurement (dB/100) CS_l1b_mds['Data']['Noise_power'] = np.ma.zeros((n_records,n_blocks),dtype=np.int32) # Phase slope correction (microradians) # Computed from the CAL-4 packets during the azimuth impulse response # amplitude (SARIN only). Set from the latest available CAL-4 packet. CS_l1b_mds['Data']['Phase_slope'] = np.ma.zeros((n_records,n_blocks),dtype=np.int32) CS_l1b_mds['Data']['Spares1'] = np.ma.zeros((n_records,n_blocks,4),dtype=np.int8) # CryoSat-2 External Corrections Group CS_l1b_mds['Geometry'] = {} # Dry Tropospheric Correction packed units (mm, 1e-3 m) CS_l1b_mds['Geometry']['dryTrop'] = np.ma.zeros((n_records),dtype=np.int32) # Wet Tropospheric Correction packed units (mm, 1e-3 m) CS_l1b_mds['Geometry']['wetTrop'] = np.ma.zeros((n_records),dtype=np.int32) # Inverse Barometric Correction packed units (mm, 1e-3 m) CS_l1b_mds['Geometry']['InvBar'] = np.ma.zeros((n_records),dtype=np.int32) # Delta Inverse Barometric Correction packed units (mm, 1e-3 m) CS_l1b_mds['Geometry']['DAC'] = np.ma.zeros((n_records),dtype=np.int32) # GIM Ionospheric Correction packed units (mm, 1e-3 m) CS_l1b_mds['Geometry']['Iono_GIM'] = np.ma.zeros((n_records),dtype=np.int32) # Model Ionospheric Correction packed units (mm, 1e-3 m) CS_l1b_mds['Geometry']['Iono_model'] = np.ma.zeros((n_records),dtype=np.int32) # Ocean tide Correction packed units (mm, 1e-3 m) CS_l1b_mds['Geometry']['ocTideElv'] = np.ma.zeros((n_records),dtype=np.int32) # Long period equilibrium ocean tide Correction packed units (mm, 1e-3 m) CS_l1b_mds['Geometry']['lpeTideElv'] = np.ma.zeros((n_records),dtype=np.int32) # Ocean loading tide Correction packed units (mm, 1e-3 m) CS_l1b_mds['Geometry']['olTideElv'] = np.ma.zeros((n_records),dtype=np.int32) # Solid Earth tide Correction packed units (mm, 1e-3 m) CS_l1b_mds['Geometry']['seTideElv'] = np.ma.zeros((n_records),dtype=np.int32) # Geocentric Polar tide Correction packed units (mm, 1e-3 m) CS_l1b_mds['Geometry']['gpTideElv'] = np.ma.zeros((n_records),dtype=np.int32) # Surface Type: enumerated key to classify surface at nadir # 0 = Open Ocean # 1 = Closed Sea # 2 = Continental Ice # 3 = Land CS_l1b_mds['Geometry']['Surf_type'] = np.ma.zeros((n_records),dtype=np.uint32) CS_l1b_mds['Geometry']['Spare1'] = np.ma.zeros((n_records,4),dtype=np.int8) # Corrections Status Flag CS_l1b_mds['Geometry']['Corr_status'] = np.ma.zeros((n_records),dtype=np.uint32) # Correction Error Flag CS_l1b_mds['Geometry']['Corr_error'] = np.ma.zeros((n_records),dtype=np.uint32) CS_l1b_mds['Geometry']['Spare2'] = np.ma.zeros((n_records,4),dtype=np.int8) # CryoSat-2 Average Waveforms Groups CS_l1b_mds['Waveform_1Hz'] = {} if (self.MODE == 'LRM'): # Low-Resolution Mode # Data Record Time (MDSR Time Stamp) CS_l1b_mds['Waveform_1Hz']['Day'] = np.zeros((n_records),dtype=np.int32) CS_l1b_mds['Waveform_1Hz']['Second'] = np.zeros((n_records),dtype=np.uint32) CS_l1b_mds['Waveform_1Hz']['Micsec'] = np.zeros((n_records),dtype=np.uint32) # Lat: packed units (0.1 micro-degree, 1e-7 degrees) CS_l1b_mds['Waveform_1Hz']['Lat'] = np.zeros((n_records),dtype=np.int32) # Lon: packed units (0.1 micro-degree, 1e-7 degrees) CS_l1b_mds['Waveform_1Hz']['Lon'] = np.zeros((n_records),dtype=np.int32) # Alt: packed units (mm, 1e-3 m) # Altitude of COG above reference ellipsoid (interpolated value) CS_l1b_mds['Waveform_1Hz']['Alt'] = np.zeros((n_records),dtype=np.int32) # Window Delay (two-way) corrected for instrument delays CS_l1b_mds['Waveform_1Hz']['TD'] = np.zeros((n_records),dtype=np.int64) # 1 Hz Averaged Power Echo Waveform CS_l1b_mds['Waveform_1Hz']['Waveform'] = np.zeros((n_records,n_LRM_RW),dtype=np.uint16) # Echo Scale Factor (to scale echo to watts) CS_l1b_mds['Waveform_1Hz']['Linear_Wfm_Multiplier'] = np.zeros((n_records),dtype=np.int32) # Echo Scale Power (a power of 2 to scale echo to Watts) CS_l1b_mds['Waveform_1Hz']['Power2_Wfm_Multiplier'] = np.zeros((n_records),dtype=np.int32) # Number of echoes averaged CS_l1b_mds['Waveform_1Hz']['N_avg_echoes'] = np.zeros((n_records),dtype=np.uint16) CS_l1b_mds['Waveform_1Hz']['Flags'] = np.zeros((n_records),dtype=np.uint16) elif (self.MODE == 'SAR'): # SAR Mode # Data Record Time (MDSR Time Stamp) CS_l1b_mds['Waveform_1Hz']['Day'] = np.zeros((n_records),dtype=np.int32) CS_l1b_mds['Waveform_1Hz']['Second'] = np.zeros((n_records),dtype=np.uint32) CS_l1b_mds['Waveform_1Hz']['Micsec'] = np.zeros((n_records),dtype=np.uint32) # Lat: packed units (0.1 micro-degree, 1e-7 degrees) CS_l1b_mds['Waveform_1Hz']['Lat'] = np.zeros((n_records),dtype=np.int32) # Lon: packed units (0.1 micro-degree, 1e-7 degrees) CS_l1b_mds['Waveform_1Hz']['Lon'] = np.zeros((n_records),dtype=np.int32) # Alt: packed units (mm, 1e-3 m) # Altitude of COG above reference ellipsoid (interpolated value) CS_l1b_mds['Waveform_1Hz']['Alt'] = np.zeros((n_records),dtype=np.int32) # Window Delay (two-way) corrected for instrument delays CS_l1b_mds['Waveform_1Hz']['TD'] = np.zeros((n_records),dtype=np.int64) # 1 Hz Averaged Power Echo Waveform CS_l1b_mds['Waveform_1Hz']['Waveform'] = np.zeros((n_records,n_SAR_RW),dtype=np.uint16) # Echo Scale Factor (to scale echo to watts) CS_l1b_mds['Waveform_1Hz']['Linear_Wfm_Multiplier'] = np.zeros((n_records),dtype=np.int32) # Echo Scale Power (a power of 2 to scale echo to Watts) CS_l1b_mds['Waveform_1Hz']['Power2_Wfm_Multiplier'] = np.zeros((n_records),dtype=np.int32) # Number of echoes averaged CS_l1b_mds['Waveform_1Hz']['N_avg_echoes'] = np.zeros((n_records),dtype=np.uint16) CS_l1b_mds['Waveform_1Hz']['Flags'] = np.zeros((n_records),dtype=np.uint16) elif (self.MODE == 'SIN'): # SARIN Mode # Same as the LRM/SAR groups but the waveform array is 512 bins instead of # 128 and the number of echoes averaged is different. # Data Record Time (MDSR Time Stamp) CS_l1b_mds['Waveform_1Hz']['Day'] = np.zeros((n_records),dtype=np.int32) CS_l1b_mds['Waveform_1Hz']['Second'] = np.zeros((n_records),dtype=np.uint32) CS_l1b_mds['Waveform_1Hz']['Micsec'] = np.zeros((n_records),dtype=np.uint32) # Lat: packed units (0.1 micro-degree, 1e-7 degrees) CS_l1b_mds['Waveform_1Hz']['Lat'] = np.zeros((n_records),dtype=np.int32) # Lon: packed units (0.1 micro-degree, 1e-7 degrees) CS_l1b_mds['Waveform_1Hz']['Lon'] = np.zeros((n_records),dtype=np.int32) # Alt: packed units (mm, 1e-3 m) # Altitude of COG above reference ellipsoid (interpolated value) CS_l1b_mds['Waveform_1Hz']['Alt'] = np.zeros((n_records),dtype=np.int32) # Window Delay (two-way) corrected for instrument delays CS_l1b_mds['Waveform_1Hz']['TD'] = np.zeros((n_records),dtype=np.int64) # 1 Hz Averaged Power Echo Waveform CS_l1b_mds['Waveform_1Hz']['Waveform'] = np.zeros((n_records,n_SARIN_RW),dtype=np.uint16) # Echo Scale Factor (to scale echo to watts) CS_l1b_mds['Waveform_1Hz']['Linear_Wfm_Multiplier'] = np.zeros((n_records),dtype=np.int32) # Echo Scale Power (a power of 2 to scale echo to Watts) CS_l1b_mds['Waveform_1Hz']['Power2_Wfm_Multiplier'] = np.zeros((n_records),dtype=np.int32) # Number of echoes averaged CS_l1b_mds['Waveform_1Hz']['N_avg_echoes'] = np.zeros((n_records),dtype=np.uint16) CS_l1b_mds['Waveform_1Hz']['Flags'] = np.zeros((n_records),dtype=np.uint16) # CryoSat-2 Waveforms Groups # Beam Behavior Parameters Beam_Behavior = {} # Standard Deviation of Gaussian fit to range integrated stack power. Beam_Behavior['SD'] = np.zeros((n_records,n_blocks),dtype=np.uint16) # Stack Center: Mean of Gaussian fit to range integrated stack power. Beam_Behavior['Center'] = np.zeros((n_records,n_blocks),dtype=np.uint16) # Stack amplitude parameter scaled in dB/100. Beam_Behavior['Amplitude'] = np.zeros((n_records,n_blocks),dtype=np.uint16) # 3rd moment: providing the degree of asymmetry of the range integrated # stack power distribution. Beam_Behavior['Skewness'] = np.zeros((n_records,n_blocks),dtype=np.int16) # 4th moment: Measure of peakiness of range integrated stack power distribution. Beam_Behavior['Kurtosis'] = np.zeros((n_records,n_blocks),dtype=np.int16) # Standard deviation as a function of boresight angle (microradians) Beam_Behavior['SD_boresight_angle'] = np.zeros((n_records,n_blocks),dtype=np.uint16) # Stack Center angle as a function of boresight angle (microradians) Beam_Behavior['Center_boresight_angle'] = np.zeros((n_records,n_blocks),dtype=np.int16) Beam_Behavior['Spare'] = np.zeros((n_records,n_blocks,n_BeamBehaviourParams-7),dtype=np.int16) # CryoSat-2 mode specific waveform variables CS_l1b_mds['Waveform_20Hz'] = {} if (self.MODE == 'LRM'): # Low-Resolution Mode # Averaged Power Echo Waveform [128] CS_l1b_mds['Waveform_20Hz']['Waveform'] = np.zeros((n_records,n_blocks,n_LRM_RW),dtype=np.uint16) # Echo Scale Factor (to scale echo to watts) CS_l1b_mds['Waveform_20Hz']['Linear_Wfm_Multiplier'] = np.zeros((n_records,n_blocks),dtype=np.int32) # Echo Scale Power (a power of 2) CS_l1b_mds['Waveform_20Hz']['Power2_Wfm_Multiplier'] = np.zeros((n_records,n_blocks),dtype=np.int32) # Number of echoes averaged CS_l1b_mds['Waveform_20Hz']['N_avg_echoes'] = np.zeros((n_records,n_blocks),dtype=np.uint16) CS_l1b_mds['Waveform_20Hz']['Flags'] = np.zeros((n_records,n_blocks),dtype=np.uint16) elif (self.MODE == 'SAR'): # SAR Mode # Averaged Power Echo Waveform [256] CS_l1b_mds['Waveform_20Hz']['Waveform'] = np.zeros((n_records,n_blocks,n_SAR_BC_RW),dtype=np.uint16) # Echo Scale Factor (to scale echo to watts) CS_l1b_mds['Waveform_20Hz']['Linear_Wfm_Multiplier'] = np.zeros((n_records,n_blocks),dtype=np.int32) # Echo Scale Power (a power of 2) CS_l1b_mds['Waveform_20Hz']['Power2_Wfm_Multiplier'] = np.zeros((n_records,n_blocks),dtype=np.int32) # Number of echoes averaged CS_l1b_mds['Waveform_20Hz']['N_avg_echoes'] = np.zeros((n_records,n_blocks),dtype=np.uint16) CS_l1b_mds['Waveform_20Hz']['Flags'] = np.zeros((n_records,n_blocks),dtype=np.uint16) # Beam behaviour parameters CS_l1b_mds['Waveform_20Hz']['Beam'] = Beam_Behavior elif (self.MODE == 'SIN'): # SARIN Mode # Averaged Power Echo Waveform [1024] CS_l1b_mds['Waveform_20Hz']['Waveform'] = np.zeros((n_records,n_blocks,n_SARIN_BC_RW),dtype=np.uint16) # Echo Scale Factor (to scale echo to watts) CS_l1b_mds['Waveform_20Hz']['Linear_Wfm_Multiplier'] = np.zeros((n_records,n_blocks),dtype=np.int32) # Echo Scale Power (a power of 2) CS_l1b_mds['Waveform_20Hz']['Power2_Wfm_Multiplier'] = np.zeros((n_records,n_blocks),dtype=np.int32) # Number of echoes averaged CS_l1b_mds['Waveform_20Hz']['N_avg_echoes'] = np.zeros((n_records,n_blocks),dtype=np.uint16) CS_l1b_mds['Waveform_20Hz']['Flags'] = np.zeros((n_records,n_blocks),dtype=np.uint16) # Beam behaviour parameters CS_l1b_mds['Waveform_20Hz']['Beam'] = Beam_Behavior # Coherence [1024]: packed units (1/1000) CS_l1b_mds['Waveform_20Hz']['Coherence'] = np.zeros((n_records,n_blocks,n_SARIN_BC_RW),dtype=np.int16) # Phase Difference [1024]: packed units (microradians) CS_l1b_mds['Waveform_20Hz']['Phase_diff'] = np.zeros((n_records,n_blocks,n_SARIN_BC_RW),dtype=np.int32) # for each record in the CryoSat file for r in range(n_records): # CryoSat-2 Time and Orbit Group for b in range(n_blocks): CS_l1b_mds['Location']['Day'][r,b] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Location']['Second'][r,b] = np.fromfile(fid,dtype='>u4',count=1) CS_l1b_mds['Location']['Micsec'][r,b] = np.fromfile(fid,dtype='>u4',count=1) CS_l1b_mds['Location']['USO_Corr'][r,b] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Location']['Mode_ID'][r,b] = np.fromfile(fid,dtype='>u2',count=1) CS_l1b_mds['Location']['SSC'][r,b] = np.fromfile(fid,dtype='>u2',count=1) CS_l1b_mds['Location']['Inst_config'][r,b] = np.fromfile(fid,dtype='>u4',count=1) CS_l1b_mds['Location']['Rec_Count'][r,b] = np.fromfile(fid,dtype='>u4',count=1) CS_l1b_mds['Location']['Lat'][r,b] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Location']['Lon'][r,b] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Location']['Alt'][r,b] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Location']['Alt_rate'][r,b] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Location']['Sat_velocity'][r,b,:] = np.fromfile(fid,dtype='>i4',count=3) CS_l1b_mds['Location']['Real_beam'][r,b,:] = np.fromfile(fid,dtype='>i4',count=3) CS_l1b_mds['Location']['Baseline'][r,b,:] = np.fromfile(fid,dtype='>i4',count=3) CS_l1b_mds['Location']['ST_ID'][r,b] = np.fromfile(fid,dtype='>i2',count=1) CS_l1b_mds['Location']['Roll'][r,b] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Location']['Pitch'][r,b] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Location']['Yaw'][r,b] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Location']['MCD'][r,b] = np.fromfile(fid,dtype='>u4',count=1) CS_l1b_mds['Location']['Spares'][r,b,:] = np.fromfile(fid,dtype='>i2',count=2) # CryoSat-2 Measurement Group # Derived from instrument measurement parameters for b in range(n_blocks): CS_l1b_mds['Data']['TD'][r,b] = np.fromfile(fid,dtype='>i8',count=1) CS_l1b_mds['Data']['H_0'][r,b] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Data']['COR2'][r,b] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Data']['LAI'][r,b] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Data']['FAI'][r,b] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Data']['AGC_CH1'][r,b] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Data']['AGC_CH2'][r,b] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Data']['TR_gain_CH1'][r,b] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Data']['TR_gain_CH2'][r,b] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Data']['TX_Power'][r,b] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Data']['Doppler_range'][r,b] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Data']['TR_inst_range'][r,b] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Data']['R_inst_range'][r,b] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Data']['TR_inst_gain'][r,b] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Data']['R_inst_gain'][r,b] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Data']['Internal_phase'][r,b] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Data']['External_phase'][r,b] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Data']['Noise_power'][r,b] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Data']['Phase_slope'][r,b] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Data']['Spares1'][r,b,:] = np.fromfile(fid,dtype='>i1',count=4) # CryoSat-2 External Corrections Group CS_l1b_mds['Geometry']['dryTrop'][r] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Geometry']['wetTrop'][r] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Geometry']['InvBar'][r] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Geometry']['DAC'][r] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Geometry']['Iono_GIM'][r] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Geometry']['Iono_model'][r] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Geometry']['ocTideElv'][r] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Geometry']['lpeTideElv'][r] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Geometry']['olTideElv'][r] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Geometry']['seTideElv'][r] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Geometry']['gpTideElv'][r] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Geometry']['Surf_type'][r] = np.fromfile(fid,dtype='>u4',count=1) CS_l1b_mds['Geometry']['Spare1'][r,:] = np.fromfile(fid,dtype='>i1',count=4) CS_l1b_mds['Geometry']['Corr_status'][r] = np.fromfile(fid,dtype='>u4',count=1) CS_l1b_mds['Geometry']['Corr_error'][r] = np.fromfile(fid,dtype='>u4',count=1) CS_l1b_mds['Geometry']['Spare2'][r,:] = np.fromfile(fid,dtype='>i1',count=4) # CryoSat-2 Average Waveforms Groups if (self.MODE == 'LRM'): # Low-Resolution Mode CS_l1b_mds['Waveform_1Hz']['Day'][r] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Waveform_1Hz']['Second'][r] = np.fromfile(fid,dtype='>u4',count=1) CS_l1b_mds['Waveform_1Hz']['Micsec'][r] = np.fromfile(fid,dtype='>u4',count=1) CS_l1b_mds['Waveform_1Hz']['Lat'][r] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Waveform_1Hz']['Lon'][r] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Waveform_1Hz']['Alt'][r] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Waveform_1Hz']['TD'][r] = np.fromfile(fid,dtype='>i8',count=1) CS_l1b_mds['Waveform_1Hz']['Waveform'][r,:] = np.fromfile(fid,dtype='>u2',count=n_LRM_RW) CS_l1b_mds['Waveform_1Hz']['Linear_Wfm_Multiplier'][r] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Waveform_1Hz']['Power2_Wfm_Multiplier'][r] = np.fromfile(fid,dtype='>i4',count=1) CS_l1b_mds['Waveform_1Hz']['N_avg_echoes'][r] = np.fromfile(fid,dtype='>u2',count=1) CS_l1b_mds['Waveform_1Hz']['Flags'][r] = np.fromfile(fid,dtype='>u2',count=1) elif (self.MODE ==
""" This module module provides functionality to load data from a container into memory in chunks. """ import gc import random import numpy as np import audiomate from audiomate import containers from audiomate.utils import units class PartitioningContainerLoader: """ Load data from one or more containers in partitions. It computes a scheme to load the data of as many utterances as possible in one partition. A scheme is initially computed on creation of the loader. To compute a new one the ``reload()`` method can be used. This only has an effect if ``shuffle == True``, otherwise the utterances are defined always loaded in the same order. With a given scheme, data of a partition can be retrieved via ``load_partition_data()``. It loads all data of the partition with the given index into memory. Args: corpus_or_utt_ids (Corpus, list): Either a corpus or a list of utterances. This defines which utterances are considered for loading. containers (container.Container, list): Either a single or a list of Container objects. From the given containers data is loaded. partition_size (str): Size of the partitions in bytes. The units ``k`` (kibibytes), ``m`` (mebibytes) and ``g`` (gibibytes) are supported, i.e. a ``partition_size`` of ``1g`` equates :math:`2^{30}` bytes. shuffle (bool): Indicates whether the utterances should be returned in random order (``True``) or not (``False``). seed (int): Seed to be used for the random number generator. Example: >>> corpus = audiomate.Corpus.load('/path/to/corpus') >>> container_inputs = containers.FeatureContainer('/path/to/feat.hdf5') >>> container_outputs = containers.Container('/path/to/targets.hdf5') >>> >>> lo = PartitioningContainerLoader( >>> corpus, >>> [container_inputs, container_outputs], >>> '1G', >>> shuffle=True, >>> seed=23 >>> ) >>> len(lo.partitions) # Number of parititions 5 >>> lo.partitions[0].utt_ids # Utterances in the partition with index 0 ['utt-1', 'utt-2', ...] >>> p0 = lo.load_partition_data(0) # Load partition 0 into memory >>> p0.info.utt_ids[0] # First utterance in the partition 'utt-1' >>> p0.utt_data[0] # Data of the first utterance ( array([[0.58843831, 0.18128443, 0.19718328, 0.25284105], ...]), array([[0.0, 1.0], ...]) ) """ def __init__(self, corpus_or_utt_ids, feature_containers, partition_size, shuffle=True, seed=None): if isinstance(corpus_or_utt_ids, audiomate.Corpus): self.utt_ids = list(corpus_or_utt_ids.utterances.keys()) else: self.utt_ids = corpus_or_utt_ids if isinstance(feature_containers, containers.Container): self.containers = [feature_containers] else: self.containers = feature_containers if len(self.containers) == 0: raise ValueError('At least one container has to be provided!') self.partitions = [] self.partition_size = units.parse_storage_size(partition_size) self.shuffle = shuffle # init random state self.rand = random.Random() self.rand.seed(a=seed) # check self._raise_error_if_container_is_missing_an_utterance() # Compute utterance size and length self.utt_sizes = self._scan() self.utt_lengths = self._get_all_lengths() self.reload() def reload(self): """ Create a new partition scheme. A scheme defines which utterances are in which partition. The scheme only changes after every call if ``self.shuffle == True``. Returns: list: List of PartitionInfo objects, defining the new partitions (same as ``self.partitions``). """ # Create the order in which utterances will be loaded utt_ids = sorted(self.utt_ids) if self.shuffle: self.rand.shuffle(utt_ids) partitions = [] current_partition = PartitionInfo() for utt_id in utt_ids: utt_size = self.utt_sizes[utt_id] utt_lengths = self.utt_lengths[utt_id] # We add utterance to the partition as long the partition-size is not exceeded # Otherwise we start with new partition. if current_partition.size + utt_size > self.partition_size: partitions.append(current_partition) current_partition = PartitionInfo() current_partition.utt_ids.append(utt_id) current_partition.utt_lengths.append(utt_lengths) current_partition.size += utt_size if current_partition.size > 0: partitions.append(current_partition) self.partitions = partitions return self.partitions def load_partition_data(self, index): """ Load and return the partition with the given index. Args: index (int): The index of partition, that refers to the index in ``self.partitions``. Returns: PartitionData: A PartitionData object containing the data for the partition with the given index. """ info = self.partitions[index] data = PartitionData(info) for utt_id in info.utt_ids: utt_data = [c._file[utt_id][:] for c in self.containers] # skipcq: PYL-W0212 data.utt_data.append(utt_data) return data def _raise_error_if_container_is_missing_an_utterance(self): """ Check if there is a dataset for every utterance in every container, otherwise raise an error. """ expected_keys = frozenset(self.utt_ids) for cnt in self.containers: keys = set(cnt.keys()) if not keys.issuperset(expected_keys): raise ValueError('Container is missing data for some utterances!') def _scan(self): """ For every utterance, calculate the size it will need in memory. """ utt_sizes = {} for dset_name in self.utt_ids: per_container = [] for cnt in self.containers: dset = cnt._file[dset_name] # skipcq: PYL-W0212 dtype_size = dset.dtype.itemsize record_size = dtype_size * dset.size per_container.append(record_size) utt_size = sum(per_container) if utt_size > self.partition_size: raise ValueError('Records in "{0}" are larger than the partition size'.format(dset_name)) utt_sizes[dset_name] = utt_size return utt_sizes def _get_all_lengths(self): """ For every utterance, get the length of the data in every container. Return a list of tuples. """ utt_lengths = {} for utt_idx in self.utt_ids: per_container = [c._file[utt_idx].shape[0] for c in self.containers] # skipcq: PYL-W0212 utt_lengths[utt_idx] = tuple(per_container) return utt_lengths class PartitionInfo: """ Class for holding the info of a partition. Attributes: utt_ids (list): A list of utterance-ids in the partition. utt_lengths (list): List with lengths of the utterances (Outermost dimension in the dataset of the container). Since there are maybe multiple containers, every item is a tuple of lengths. They correspond to the length of the utterance in every container, in the order of the containers passed to the ParitioningContainerLoader. size (int): The number of bytes the partition will allocate, when loaded. """ def __init__(self): self.utt_ids = [] self.utt_lengths = [] self.size = 0 def total_lengths(self): """ Return the total length of all utterances for every container. """ return tuple(sum(x) for x in zip(*self.utt_lengths)) class PartitionData: """ Class for holding the loaded data of a partition. Args: info (PartitionInfo): The info about the partition. Attributes: utt_data (list): A list holding the data-objects for every utterance in the order of ``info.utt_ids``. The entries are also lists or tuples containing the array for every container. """ def __init__(self, info): self.info = info self.utt_data = [] class PartitioningFeatureIterator: """ Iterates over all features in the given HDF5 file. Before iterating over the features, the iterator slices the file into one or more partitions and loads the data into memory. This leads to significant speed-ups even with moderate partition sizes, regardless of the type of disk (spinning or flash). Pseudo random access is supported with a negligible impact on performance and randomness: The data is randomly sampled (without replacement) within each partition and the partitions are loaded in random order, too. The features are emitted as triplets in the form of ``(utterance name, index of the feature within the utterance, feature)``. When calculating the partition sizes only the size of the features itself is factored in, overhead of data storage is ignored. This overhead is usually negligible even with partition sizes of multiple gigabytes because the data is stored as numpy ndarrays in memory (one per utterance). The overhead of a single ndarray is 96 bytes regardless of its size. Nonetheless the partition size should be chosen to be lower than the total available memory. Args: hdf5file(h5py.File): HDF5 file containing the features partition_size(str): Size of the partitions in bytes. The units ``k`` (kibibytes), ``m`` (mebibytes) and ``g`` (gibibytes) are supported, i.e. a ``partition_size`` of ``1g`` equates :math:`2^{30}` bytes. shuffle(bool): Indicates whether the features should be returned in random order (``True``) or not (``False``). seed(int): Seed to be used for the random number generator. includes(iterable): Iterable of names of data sets that should be included when iterating over the feature container. Mutually exclusive with ``excludes``. If both are specified, only ``includes`` will be considered. excludes(iterable): Iterable of names of data sets to skip when iterating over the feature container. Mutually exclusive with ``includes``. If both are specified, only ``includes`` will be considered. Example: >>> import h5py >>> from audiomate.feeding import PartitioningFeatureIterator >>> hdf5 = h5py.File('features.h5', 'r') >>> iterator = PartitioningFeatureIterator(hdf5, '12g', shuffle=True) >>> next(iterator) ('music-fma-0100', 227, array([ -0.15004082, -0.30246958, -0.38708138, ..., -0.93471956, -0.94194776, -0.90878332 ], dtype=float32)) >>> next(iterator) ('music-fma-0081', 2196, array([ -0.00207647, -0.00101351, -0.00058832, ..., -0.00207647, -0.00292684, -0.00292684], dtype=float32)) >>> next(iterator) ('music-hd-0050', 1026, array([ -0.57352495, -0.63049972, -0.63049972, ..., 0.82490814, 0.84680521, 0.75517786], dtype=float32)) """ def __init__(self, hdf5file, partition_size, shuffle=True, seed=None, includes=None, excludes=None): self._file = hdf5file self._partition_size = units.parse_storage_size(partition_size) self._shuffle = shuffle self._seed = seed data_sets = self._filter_data_sets(hdf5file.keys(), includes=includes, excludes=excludes) if shuffle: _random_state(self._seed).shuffle(data_sets) self._data_sets = tuple(data_sets) self._partitions = [] self._partition_idx = 0 self._partition_data = None self._partition() def
args): """ Enable a host """ host = client.hosts.perform_action(args.id, 'disable') utils.print_dict(host) @utils.arg('id', metavar='<HOST_ID>', help='ID of host to delete') def do_host_delete(client, args): """ Delete a host """ host = client.hosts.delete(args.id) utils.print_dict(host) @utils.arg('id', metavar='<HOST_ID>', help='ID of host to balance') def do_host_cpu_balance(client, args): """ Balance Host cpu """ host = client.hosts.perform_action(args.id, 'cpu-node-balance') utils.print_dict(host) def do_host_dynamic_load_updater(client, args): hosts = client.hosts.list(limit=0, details=False)[0] hosts = [host['id'] for host in hosts] usage_params = {'interval_unit': 'week', 'wire_id': '', 'interval': 1, 'order': 'desc', 'storage_id': '', 'stat_field': '', 'page': 0} for host in hosts: typestr = 'cpu' usage = client.usages.get_host_usage(host, typestr, **usage_params) cpu_percent = usage[0]['percent'] if len(usage) > 0 else None typestr = 'io_stat' usage = client.usages.get_host_usage(host, typestr, **usage_params) disk_io_util = (usage[0]['io_stat_util']) if len(usage) > 0 else None # of 100 percentage meta_data = {} if cpu_percent: meta_data['dynamic_load_cpu_percent'] = cpu_percent if disk_io_util: meta_data['dynamic_load_io_util'] = disk_io_util client.hosts.set_metadata(host, **meta_data) utils.print_dict(client.hosts.get_metadata(host)) @utils.arg('--limit', metavar='<NUMBER>', default=20, help='Page limit') @utils.arg('--offset', metavar='<OFFSET>', help='Page offset') @utils.arg('--order-by', metavar='<ORDER_BY>', help='Name of fields order by') @utils.arg('--order', metavar='<ORDER>', choices=['desc', 'asc'], help='order') @utils.arg('--details', action='store_true', help='More detailed list') @utils.arg('--search', metavar='<KEYWORD>', help='Filter result by simple keyword search') @utils.arg('--filter', metavar='<FILTER>', action='append', help='Filters') @utils.arg('--filter-any', action='store_true', help='If true, match if any of the filters matches; otherwise, match if all of the filters match') @utils.arg('--field', metavar='<FIELD>', action='append', help='Show only specified fields') def do_wire_list(client, args): """ List all network broadcast areas """ page_info = utils.get_paging_info(args) wires = client.wires.list(**page_info) utils.print_list(wires, client.wires.columns) @utils.arg('name', metavar='<WIRE_NAME>', help='Name of wire (broadcast area) to create') @utils.arg('--bw', metavar='<WIRE_BANDWIDTH>', required=True, help='Bandwidth of the wire (broadcast area)') @utils.arg('--desc', metavar='<WIRE_DESCRIPTION>', help='Description') def do_wire_create(client, args): """ Create a wire (broadcast area) """ kwargs = {} kwargs['name'] = args.name kwargs['bandwidth'] = args.bw if args.desc is not None: kwargs['description'] = args.desc sub = client.wires.create(**kwargs) utils.print_dict(sub) @utils.arg('id', metavar='<WIRE_ID>', help='Id of wire (broadcast area) to show') def do_wire_show(client, args): """ Get detail of a wire (broadcast area) """ sub = client.wires.get(args.id) utils.print_dict(sub) @utils.arg('id', metavar='<WIRE_ID>', help='Id of wire to delete') def do_wire_delete(client, args): """ Delete a wire (broadcast area) """ sub = client.wires.delete(args.id) utils.print_dict(sub) @utils.arg('id', metavar='<WIRE_ID>', help='Id of wire (broadcast area) to delete') @utils.arg('--name', metavar='<WIRE_NAME>', help='Name of wire (broadcast area) to create') @utils.arg('--bw', metavar='<WIRE_BANDWIDTH>', help='Bandwidth of the wire (broadcast area)') @utils.arg('--desc', metavar='<WIRE_DESCRIPTION>', help='Description') def do_wire_update(client, args): """ Update a wire (broadcast area) """ kwargs = {} if args.name is not None: kwargs['name'] = args.name if args.bw is not None: kwargs['bandwidth'] = args.bw if args.desc is not None: kwargs['description'] = args.desc if len(kwargs) == 0: raise Exception("Not enough parameters", "NOt enough parameters") sub = client.wires.update(args.id, **kwargs) utils.print_dict(sub) @utils.arg('id', metavar='<HOST_ID>', help='Id of host') @utils.arg('--wire', metavar='<WIRE>', required=True, help='ID of wire') @utils.arg('--bridge', metavar='<BRIDGE>', required=True, help='Name of bridge') @utils.arg('--interface', metavar='<INTERFACE>', required=True, help='Interface associate with bridge') def do_host_wire_attach(client, args): """ Attach a host to a wire (broadcast area) """ kwargs = {} kwargs['bridge'] = args.bridge kwargs['interface'] = args.interface hs = client.hostwires.attach(args.id, args.wire, **kwargs) utils.print_dict(hs) @utils.arg('id', metavar='<HOST_ID>', help='Id of host') @utils.arg('--wire', metavar='<WIRE>', required=True, help='ID of wire') def do_host_wire_detach(client, args): """ Detach a host from a wire """ hs = client.hostwires.detach(args.id, args.wire) utils.print_dict(hs) @utils.arg('id', metavar='<HOST_ID>', help='Id of host') @utils.arg('--wire', metavar='<WIRE>', required=True, help='ID of wire') def do_host_wire_show(client, args): """ Show how a host attach to a wire """ hs = client.hostwires.get(args.id, args.wire) utils.print_dict(hs) @utils.arg('--host', metavar='<HOST_ID>', help='ID of host') @utils.arg('--limit', metavar='<NUMBER>', default=20, help='Page limit') @utils.arg('--offset', metavar='<OFFSET>', help='Page offset') @utils.arg('--order-by', metavar='<ORDER_BY>', help='Name of fields order by') @utils.arg('--order', metavar='<ORDER>', choices=['desc', 'asc'], help='order') @utils.arg('--details', action='store_true', help='More detailed list') @utils.arg('--search', metavar='<KEYWORD>', help='Filter result by simple keyword search') @utils.arg('--filter', metavar='<FILTER>', action='append', help='Filters') @utils.arg('--filter-any', action='store_true', help='If true, match if any of the filters matches; otherwise, match if all of the filters match') @utils.arg('--field', metavar='<FIELD>', action='append', help='Show only specified fields') def do_host_wire_list(client, args): """ List all substrates that a host joins """ page_info = utils.get_paging_info(args) if args.host is None: hslist = client.hostwires.list(**page_info) else: hslist = client.hostwires.list_descendent(args.host, **page_info) utils.print_list(hslist, client.hostwires.columns) @utils.arg('--limit', metavar='<NUMBER>', default=20, help='Page limit') @utils.arg('--offset', metavar='<OFFSET>', help='Page offset') @utils.arg('--order-by', metavar='<ORDER_BY>', help='Name of fields order by') @utils.arg('--order', metavar='<ORDER>', choices=['desc', 'asc'], help='order') @utils.arg('--details', action='store_true', help='More detailed list') @utils.arg('--search', metavar='<KEYWORD>', help='Filter result by simple keyword search') @utils.arg('--filter', metavar='<FILTER>', action='append', help='Filters') @utils.arg('--filter-any', action='store_true', help='If true, match if any of the filters matches; otherwise, match if all of the filters match') @utils.arg('--field', metavar='<FIELD>', action='append', help='Show only specified fields') def do_storage_list(client, args): """ List all storages """ page_info = utils.get_paging_info(args) storages = client.storages.list(**page_info) utils.print_list(storages, client.storages.columns) @utils.arg('name', metavar='<STORAGE_NAME>', help='Name of storage') @utils.arg('--capacity', metavar='<STORAGE_CAPACITY>', required=True, help='Capacity of storage in GB') @utils.arg('--storage-type', metavar='<STORAGE_TYPE>', required=True, choices=['local', 'mebs'], help='Type of storage') @utils.arg('--medium-type', metavar='<MEDIUM_TYPE>', choices=['ssd', 'rotational'], default='rotational', help='Type of storage medium') @utils.arg('--commit-bound', metavar='<COMMIT_BOUND>', type=float, help='Upper bound of storage overcommit rate') @utils.arg('--desc', metavar='<DESCRIPTION>', help='Description') @utils.arg('--mebs-manager-ip', metavar='<IP>', help='MEBS manager IP') @utils.arg('--mebs-manager-port', metavar='<PORT>', type=int, help='MEBS manager port') @utils.arg('--mebs-redis-ip', metavar='<IP>', help='MEBS redis IP') @utils.arg('--mebs-redis-port', metavar='<PORT>', type=int, help='MEBS redis port') @utils.arg('--mebs-sql-connection', metavar='<CONNECTION>', help='MEBS mysql connection') def do_storage_create(client, args): """ Create a storage """ kwargs = {} kwargs['name'] = args.name kwargs['capacity'] = int(args.capacity) * 1024 # convert to MB if args.storage_type is not None: kwargs['storage_type'] = args.storage_type if args.medium_type is not None: kwargs['medium_type'] = args.medium_type if args.commit_bound and args.commit_bound > 0.0: kwargs['cmtbound'] = args.commit_bound if args.desc is not None: kwargs['description'] = args.desc for k in ['mebs_manager_ip', 'mebs_manager_port', 'mebs_redis_ip', 'mebs_redis_port', 'mebs_sql_connection']: if getattr(args, k, None) is not None: kwargs[k] = getattr(args, k) storage = client.storages.create(**kwargs) utils.print_dict(storage) @utils.arg('id', metavar='<STORAGE_ID>', help='ID of storage') @utils.arg('--name', metavar='<STORAGE_NAME>', help='Name of storage') @utils.arg('--capacity', metavar='<STORAGE_CAPACITY>', help='Capacity of storage') @utils.arg('--storage-type', metavar='<STORAGE_TYPE>', choices=['local', 'mebs'], help='Type of storage') @utils.arg('--medium-type', metavar='<MEDIUM_TYPE>', choices=['ssd', 'rotational'], help='Type of storage medium') @utils.arg('--commit-bound', metavar='<COMMIT_BOUND>', type=float, help='Upper bound of storage overcommit rate') @utils.arg('--desc', metavar='<DESCRIPTION>', help='Description') @utils.arg('--mebs-manager-ip', metavar='<IP>', help='MEBS manager IP') @utils.arg('--mebs-manager-port', metavar='<PORT>', type=int, help='MEBS manager port') @utils.arg('--mebs-redis-ip', metavar='<IP>', help='MEBS redis IP') @utils.arg('--mebs-redis-port', metavar='<PORT>', type=int, help='MEBS redis port') @utils.arg('--mebs-sql-connection', metavar='<CONNECTION>', help='MEBS mysql connection') def do_storage_update(client, args): """ Update a storage """ kwargs = {} if args.name is not None: kwargs['name'] = args.name if args.capacity is not None: kwargs['capacity'] = int(args.capacity) * 1024 if args.storage_type is not None: kwargs['storage_type'] = args.storage_type if args.medium_type is not None: kwargs['medium_type'] = args.medium_type if args.commit_bound and args.commit_bound > 0.0: kwargs['cmtbound'] = args.commit_bound if args.desc is not None: kwargs['description'] = args.desc for k in ['mebs_manager_ip', 'mebs_manager_port', 'mebs_redis_ip', 'mebs_redis_port', 'mebs_sql_connection']: if getattr(args, k, None) is not None: kwargs[k] = getattr(args, k) if len(kwargs) == 0: raise Exception("No data", "No data") storage = client.storages.update(args.id, **kwargs) utils.print_dict(storage) @utils.arg('id', metavar='<STORAGE_ID>', help='ID of storage') def do_storage_show(client, args): """ Show details of a storage """ storage = client.storages.get(args.id) utils.print_dict(storage) @utils.arg('id', metavar='<STORAGE_ID>', help='ID of storage') def do_storage_delete(client, args): """ Delete a storage """ storage = client.storages.delete(args.id) utils.print_dict(storage) @utils.arg('--host', metavar='<HOST_ID>', help='ID of host') @utils.arg('--limit', metavar='<NUMBER>', default=20, help='Page limit') @utils.arg('--offset', metavar='<OFFSET>', help='Page offset') @utils.arg('--order-by', metavar='<ORDER_BY>', help='Name of fields order by') @utils.arg('--order', metavar='<ORDER>', choices=['desc', 'asc'], help='order') @utils.arg('--details', action='store_true', help='More detailed list') @utils.arg('--search', metavar='<KEYWORD>', help='Filter result by simple keyword search') @utils.arg('--filter', metavar='<FILTER>', action='append', help='Filters') @utils.arg('--filter-any', action='store_true', help='If true, match if any of the filters matches; otherwise, match if all of the filters match') @utils.arg('--field', metavar='<FIELD>', action='append', help='Show only specified fields') def do_host_storage_list(client, args): """ List storages of a host """ page_info = utils.get_paging_info(args) if args.host is not None: hoststorages = client.hoststorages.list_descendent(args.host, **page_info) else: hoststorages = client.hoststorages.list(**page_info) utils.print_list(hoststorages, client.hoststorages.columns) @utils.arg('id', metavar='<HOST_ID>', help='ID of host') @utils.arg('--storage', metavar='<STORAGE_ID>', required=True, help='ID of storage') @utils.arg('--mount-point', metavar='<STORAGE_MOUNT_POINT>', required=True, help='Mount path of storage on host') def do_host_storage_attach(client, args): """ Atach a host to a storage """ kwargs = {} kwargs['mount_point'] = args.mount_point hoststorage = client.hoststorages.attach(args.id, args.storage, **kwargs) utils.print_dict(hoststorage) @utils.arg('id', metavar='<HOST_ID>', help='ID of host') @utils.arg('--storage', metavar='<STORAGE_ID>', required=True, help='ID of storage') def do_host_storage_detach(client, args): """ Detach a host from a storage """ hoststorage = client.hoststorages.detach(args.id, args.storage) utils.print_dict(hoststorage) @utils.arg('id', metavar='<HOST_ID>', help='ID of host') @utils.arg('--storage', metavar='<STORAGE_ID>', required=True, help='ID of storage') def do_host_storage_show(client, args): """ Show how a host attach to a storage """ hoststorage = client.hoststorages.get(args.id, args.storage) utils.print_dict(hoststorage) @utils.arg('--limit', metavar='<NUMBER>', default=20, help='Page limit') @utils.arg('--offset', metavar='<OFFSET>', help='Page offset') @utils.arg('--order-by', metavar='<ORDER_BY>', help='Name of fields order by') @utils.arg('--order', metavar='<ORDER>', choices=['desc', 'asc'], help='order') @utils.arg('--details', action='store_true', help='More detailed list') @utils.arg('--search', metavar='<KEYWORD>', help='Filter result by simple keyword search') @utils.arg('--filter', metavar='<FILTER>', action='append', help='Filters') @utils.arg('--filter-any', action='store_true', help='If true, match if any of the filters matches; otherwise, match if all of the filters match') @utils.arg('--field', metavar='<FIELD>', action='append', help='Show only specified fields') def do_edge_list(client, args): """ List all edge routers """ page_info = utils.get_paging_info(args) edges = client.edges.list(**page_info) utils.print_list(edges, client.edges.columns) @utils.arg('id', metavar='<ZONE_ID>', help='ID of zone') @utils.arg('--name', metavar='<NAME>', required=True, help='Name of edge router') @utils.arg('--ip', metavar='<IP>', required=True, help='Admininistrative IP address of edge router') @utils.arg('--port', metavar='<PORT>', help='Administrative port of edge router') @utils.arg('--proto', metavar='<PROTOCOL>', required=True, choices=['ssh', 'telnet'], help='Admininistrative protocol (ssh or telnet)') @utils.arg('--user', metavar='<AUTH_USER>', required=True, help='Admininistrative account') @utils.arg('--key-file', metavar='<SSH_PRIVATE_KEY>', help='Authentication private key') @utils.arg('--passwd', metavar='<PASSWORD>', help='Authentication password') @utils.arg('--model', metavar='<MODEL>', choices=['ubuntu', 'debian'], help='Model of edge router') @utils.arg('--egress', metavar='<EGRESS_IF_NAME>', required=True, help='Egress interface name of edge router') @utils.arg('--desc', metavar='<DESCRIPTION>', help='Description') def do_zone_create_edge(client, args): """ Create an edge router """ kwargs = {} kwargs['name'] = args.name kwargs['admin_ip'] = args.ip kwargs['admin_proto'] = args.proto kwargs['auth_user'] = args.user kwargs['egress_if'] = args.egress if args.model:
mod_node = helper.make_node("Mod", inputs=["x", "y"], outputs=["z"], fmod=fmod) onnx_dtype = TensorProto.FLOAT if dtype == "float32" else TensorProto.INT32 graph = helper.make_graph([mod_node], "mod_test", inputs=[helper.make_tensor_value_info("x", onnx_dtype, list(x_shape)), helper.make_tensor_value_info("y", onnx_dtype, list(y_shape))], outputs=[helper.make_tensor_value_info("z", onnx_dtype, list(out_shape))]) model = helper.make_model(graph, producer_name='mod_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output( model, [x_np, y_np], target, ctx, out_shape) tvm.testing.assert_allclose(np_out, tvm_out, rtol=1e-5, atol=1e-5) def test_mod(): # Mod verify_mod(x_shape=[1, 32, 32], y_shape=[1, 32, 32], fmod=0) verify_mod(x_shape=[1, 32, 32], y_shape=[1, 1, 32], fmod=0, dtype="int32") # fmod verify_mod(x_shape=[1, 1, 32], y_shape=[1, 32, 32], fmod=1) verify_mod(x_shape=[1, 32, 32], y_shape=[1, 32, 32], fmod=1, dtype="int32") def verify_xor(x_shape, y_shape): x_np = np.random.choice(a=[False, True], size=x_shape).astype("bool") y_np = np.random.choice(a=[False, True], size=y_shape).astype("bool") np_out = np.logical_xor(x_np, y_np) out_shape = np_out.shape xor_node = helper.make_node("Xor", inputs=["x", "y"], outputs=["z"]) onnx_dtype = TensorProto.BOOL graph = helper.make_graph([xor_node], "xor_test", inputs=[helper.make_tensor_value_info("x", onnx_dtype, list(x_shape)), helper.make_tensor_value_info("y", onnx_dtype, list(y_shape))], outputs=[helper.make_tensor_value_info("z", onnx_dtype, list(out_shape))]) model = helper.make_model(graph, producer_name='xor_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output( model, [x_np, y_np], target, ctx, out_shape) tvm.testing.assert_allclose(np_out, tvm_out, rtol=1e-5, atol=1e-5) def test_xor(): # XOR verify_xor(x_shape=[1, 32, 32], y_shape=[1, 32, 32]) # Xor broadcast verify_xor(x_shape=[1, 32, 32], y_shape=[1, 1, 32]) def verify_max_roi_pool(x_shape, rois_shape, pooled_shape, spatial_scale, out_shape): x_np = np.random.uniform(size=x_shape).astype('float32') rois_np = np.random.uniform(size=rois_shape).astype('float32') if spatial_scale is None: pool_node = helper.make_node("MaxRoiPool", inputs=["x", "rois"], outputs=["y"], pooled_shape=pooled_shape) else: pool_node = helper.make_node("MaxRoiPool", inputs=["x", "rois"], outputs=["y"], pooled_shape=pooled_shape, spatial_scale=spatial_scale) graph = helper.make_graph([pool_node], "pool_test", inputs=[helper.make_tensor_value_info("x", TensorProto.FLOAT, list(x_shape)), helper.make_tensor_value_info("rois", TensorProto.FLOAT, list(rois_shape))], outputs=[helper.make_tensor_value_info("y", TensorProto.FLOAT, list(out_shape))]) model = helper.make_model(graph, producer_name='pool_test') onnx_out = get_onnxruntime_output(model, [x_np, rois_np], 'float32')[0] for target, ctx in ctx_list(): tvm_out = get_tvm_output( model, [x_np, rois_np], target, ctx, out_shape) tvm.testing.assert_allclose(onnx_out, tvm_out, rtol=1e-5, atol=1e-5) def test_max_roi_pool(): verify_max_roi_pool(x_shape=[1, 3, 6, 6], rois_shape=[3, 5], pooled_shape=[1, 1], spatial_scale=None, out_shape=[3, 3, 1, 1]) verify_max_roi_pool(x_shape=[1, 3, 10, 10], rois_shape=[4, 5], pooled_shape=[2, 2], spatial_scale=2.0, out_shape=[4, 3, 2, 2]) def verify_lppool(x_shape, kernel_shape, p, strides, pads, out_shape, auto_pad="NOTSET"): x_np = np.random.uniform(size=x_shape).astype('float32') if pads is None: pool_node = helper.make_node("LpPool", inputs=["x"], outputs=["y"], kernel_shape=kernel_shape, p = p, auto_pad=auto_pad, strides=strides) else: pool_node = helper.make_node("LpPool", inputs=["x"], outputs=["y"], kernel_shape=kernel_shape, p = p, pads=pads, strides=strides) graph = helper.make_graph([pool_node], "lppool_test", inputs=[helper.make_tensor_value_info("x", TensorProto.FLOAT, list(x_shape))], outputs=[helper.make_tensor_value_info("y", TensorProto.FLOAT, list(out_shape))]) model = helper.make_model(graph, producer_name='lppool_test') for target, ctx in ctx_list(): onnx_out = get_onnxruntime_output(model, x_np, 'float32') tvm_out = get_tvm_output( model, [x_np], target, ctx, out_shape) tvm.testing.assert_allclose(onnx_out, tvm_out, rtol=1e-5, atol=1e-5) def test_lppool(): # Pool1D verify_lppool(x_shape=[1, 1, 32], kernel_shape=[3], p=2, strides=[1], pads=[1, 1], out_shape=[1, 1, 32]) # Pool2D verify_lppool(x_shape=[1, 1, 32, 32], kernel_shape=[3, 3], p=2, strides=[1, 1], pads=[1, 1, 1, 1], out_shape=[1, 1, 32, 32]) # Pool1D with stride verify_lppool(x_shape=[1, 1, 32], kernel_shape=[3], p=2, strides=[2], pads=[1, 1], out_shape=[1, 1, 16]) # Pool2D with stride verify_lppool(x_shape=[1, 1, 32, 32], kernel_shape=[3, 3], p=2, strides=[2, 2], pads=[1, 1, 1, 1], out_shape=[1, 1, 16, 16]) # Pool1D with stride and autopadding verify_lppool(x_shape=[1, 1, 32], kernel_shape=[3], p=2, strides=[2], pads=None, out_shape=[1, 1, 16], auto_pad='SAME_UPPER') # Pool2D with stride and autopadding verify_lppool(x_shape=[1, 1, 32, 32], kernel_shape=[3, 3], p=2, strides=[2, 2], pads=None, out_shape=[1, 1, 16, 16], auto_pad='SAME_UPPER') # Pool3D with stride verify_lppool(x_shape=[1, 1, 32, 32, 32], kernel_shape=[3, 3, 3], p=2, strides=[2, 2, 2], pads=[1, 1, 1, 1, 1, 1], out_shape=[1, 1, 16, 16, 16]) # Pool3D with stride and autopadding verify_lppool(x_shape=[1, 1, 32, 32, 32], kernel_shape=[3, 3, 3], p=2, strides=[2, 2, 2], pads=None, out_shape=[1, 1, 16, 16, 16], auto_pad='SAME_UPPER') def verify_lstm(seq_length, batch_size, input_size, hidden_size, use_bias=False, activations=None, alphas=None, betas=None, use_initial_state=False, use_peep=False): x_np = np.random.uniform(size=(seq_length, batch_size, input_size)).astype('float32') w_np = np.random.uniform(size=(1, 4 * hidden_size, input_size)).astype('float32') r_np = np.random.uniform(size=(1, 4 * hidden_size, hidden_size)).astype('float32') input_names = ["X", "W", "R"] input_tensors = [ helper.make_tensor_value_info("X", TensorProto.FLOAT, list(x_np.shape)), helper.make_tensor_value_info("W", TensorProto.FLOAT, list(w_np.shape)), helper.make_tensor_value_info("R", TensorProto.FLOAT, list(r_np.shape)) ] input_values = [x_np, w_np, r_np] if use_bias: b_np = np.random.uniform(size=(1, 8 * hidden_size)).astype('float32') input_names.append("B") input_tensors.append( helper.make_tensor_value_info("B", TensorProto.FLOAT, [1, 8 * hidden_size])) input_values.append(b_np) if use_initial_state: assert use_bias == True, "Initial states must have bias specified." sequence_np = np.repeat(seq_length, batch_size).astype('int32') input_names.append("sequence_lens") input_tensors.append(helper.make_tensor_value_info("sequence_lens", TensorProto.INT32, [batch_size])) input_values.append(sequence_np) initial_h_np = np.random.uniform(size=(1, batch_size, hidden_size)).astype('float32') input_names.append("initial_h") input_tensors.append( helper.make_tensor_value_info("initial_h", TensorProto.FLOAT, [1, batch_size, hidden_size])) input_values.append(initial_h_np) initial_c_np = np.random.uniform(size=(1, batch_size, hidden_size)).astype('float32') input_names.append("initial_c") input_tensors.append( helper.make_tensor_value_info("initial_c", TensorProto.FLOAT, [1, batch_size, hidden_size])) input_values.append(initial_c_np) if use_peep: assert use_initial_state == True, "Peepholes require initial state to be specified." p_np = np.random.uniform(size=(1, 3 * hidden_size)).astype('float32') input_names.append("P") input_tensors.append( helper.make_tensor_value_info("P", TensorProto.FLOAT, [1, 3 * hidden_size])) input_values.append(p_np) Y_shape = [seq_length, 1, batch_size, hidden_size] Y_h_shape = [1, batch_size, hidden_size] Y_c_shape = [1, batch_size, hidden_size] if activations is None: lstm_node = helper.make_node( 'LSTM', inputs=input_names, outputs=["Y", "Y_h", "Y_c"], hidden_size=hidden_size) elif alphas is None: lstm_node = helper.make_node( 'LSTM', inputs=input_names, outputs=["Y", "Y_h", "Y_c"], hidden_size=hidden_size, activations=activations) else: lstm_node = helper.make_node( 'LSTM', inputs=input_names, outputs=["Y", "Y_h", "Y_c"], hidden_size=hidden_size, activations=activations, activation_alpha=alphas, activation_beta=betas) graph = helper.make_graph([lstm_node], "lstm_test", inputs=input_tensors, outputs=[ helper.make_tensor_value_info("Y", TensorProto.FLOAT, list(Y_shape)), helper.make_tensor_value_info("Y_h", TensorProto.FLOAT, list(Y_h_shape)), helper.make_tensor_value_info("Y_c", TensorProto.FLOAT, list(Y_c_shape)) ]) model = helper.make_model(graph, producer_name='lstm_test') for target, ctx in ctx_list(): onnx_out = get_onnxruntime_output(model, input_values, 'float32') tvm_out = get_tvm_output( model, input_values, target, ctx, [Y_shape, Y_h_shape, Y_c_shape], output_dtype=['float32', 'float32', 'float32']) for o_out, t_out in zip(onnx_out, tvm_out): tvm.testing.assert_allclose(o_out, t_out, rtol=5e-3, atol=5e-3) def test_lstm(): # No bias. verify_lstm(seq_length=2, batch_size=1, input_size=16, hidden_size=32, use_bias=False) # large batch. verify_lstm(seq_length=4, batch_size=8, input_size=16, hidden_size=32, use_bias=True) # Non power of two. verify_lstm(seq_length=3, batch_size=3, input_size=16, hidden_size=40, use_bias=True) # Long sequence. verify_lstm(seq_length=8, batch_size=1, input_size=16, hidden_size=32, use_bias=True) # Large hidden. verify_lstm(seq_length=2, batch_size=1, input_size=16, hidden_size=128, use_bias=True) # Large input. verify_lstm(seq_length=2, batch_size=1, input_size=64, hidden_size=32, use_bias=True) # Different activation testing. # Default value hardsigmoid. verify_lstm( seq_length=2, batch_size=1, input_size=16, hidden_size=32, use_bias=False, activations=['HardSigmoid', 'Tanh', 'Tanh']) # Multiple parameterized activations. verify_lstm( seq_length=2, batch_size=1, input_size=16, hidden_size=32, use_bias=False, activations=['HardSigmoid', 'LeakyRelu', 'Tanh'], alphas=[2.0, 0.5], betas=[.3]) # All parameterized with new Affine activation. verify_lstm( seq_length=2, batch_size=1, input_size=16, hidden_size=32, use_bias=False, activations=['HardSigmoid', 'LeakyRelu', 'Affine'], alphas=[2.0, 0.5, 0.8], betas=[.3, 0.1]) # Testing with initial state and peepholes verify_lstm( seq_length=2, batch_size=1, input_size=16, hidden_size=32, use_bias=True, use_initial_state=True) verify_lstm( seq_length=2, batch_size=1, input_size=16, hidden_size=32, use_bias=True, use_initial_state=True, use_peep=True) def test_resize(): def make_constant_node(name, data_type, dims, vals): return helper.make_node('Constant', inputs=[], outputs=[name], value=helper.make_tensor(name=name, data_type=data_type, dims=dims, vals=vals)) def verify(ishape, oshape, scales, mode, coord_trans): nodes = [ make_constant_node('roi', onnx.TensorProto.FLOAT, (0,), []), make_constant_node('scales', onnx.TensorProto.FLOAT, (len(scales),), scales) ] input_names = ['X', 'roi', 'scales'] if oshape != []: nodes.append(make_constant_node('sizes', onnx.TensorProto.INT64, (len(oshape),), oshape)) input_names.append('sizes') nodes.append(helper.make_node( 'Resize', inputs=input_names, outputs=['Y'], mode=mode, coordinate_transformation_mode=coord_trans )) if oshape == []: oshape = [round(dim * scale) for (dim, scale) in zip(ishape, scales)] graph = helper.make_graph(nodes, "resize_test", inputs=[helper.make_tensor_value_info("X", TensorProto.FLOAT, ishape)], outputs=[helper.make_tensor_value_info("Y", TensorProto.FLOAT, oshape)]) model = helper.make_model(graph, producer_name='resize_test') for target, ctx in ctx_list(): x = np.random.uniform(size=ishape).astype('float32') onnx_out = get_onnxruntime_output(model, x, 'float32') tvm_out = get_tvm_output(model, x, target, ctx, oshape, 'float32', opset=11) tvm.testing.assert_allclose(onnx_out, tvm_out, rtol=1e-05, atol=1e-05) # upsampling verify([1, 16, 32, 32], [1, 16, 64, 64], [], "nearest", "asymmetric") verify([1, 16, 32, 32], [1, 16, 64, 64], [], "linear", "align_corners") verify([1, 16, 32, 32], [1, 16, 64, 64], [], "linear", "half_pixel") # downsampling verify([1, 16, 32, 32], [1, 16, 16, 16], [], "nearest", "asymmetric") verify([1, 16, 32, 32], [1, 16, 16, 16], [], "linear", "align_corners") verify([1, 16, 32, 32], [1, 16, 16, 16], [], "linear", "half_pixel") # scales are specified instead of sizes verify([1, 16, 32, 32], [], [1, 1, 2, 2], "nearest", "asymmetric") verify([1, 16, 32, 32], [], [1, 1, 0.5, 0.5], "linear", "half_pixel") def test_nonzero(): def verify_nonzero(indata, outdata, dtype): node = helper.make_node('NonZero', inputs=['X'], outputs=['Y'],) graph = helper.make_graph([node], "nonzero_test", inputs=[helper.make_tensor_value_info("X", TensorProto.INT64, list(indata.shape))], outputs=[helper.make_tensor_value_info("Y", TensorProto.INT64, list(outdata.shape))]) model = helper.make_model(graph, producer_name='nonzero_test') onnx_out = get_onnxruntime_output(model, indata, dtype) for target, ctx in [('llvm', tvm.cpu())]: tvm_out = get_tvm_output_with_vm(model, indata, target, ctx, opset=9) tvm.testing.assert_allclose(onnx_out, tvm_out, rtol=1e-05, atol=1e-05) input_data = np.array([[1, 0], [1, 1]], dtype=np.int64) result = np.array((np.nonzero(input_data))) # expected output [[0, 1, 1], [0, 0, 1]] verify_nonzero(input_data, result, dtype=np.int64) input_data = np.array([[3, 0, 0], [0, 4, 0], [5, 6, 0]], dtype=np.int64) result = np.array((np.nonzero(input_data))) # expected output [[0, 1, 2, 2], [0, 1, 0, 1]] verify_nonzero(input_data, result, dtype=np.int64) def test_topk(): def verify_topk(input_dims, K, axis=-1): output_dims = list(input_dims) output_dims[axis] = K node = helper.make_node('TopK', inputs=['X', 'K'], outputs=['Values', 'Indicies'], axis=axis) graph = helper.make_graph([node], "topk_test", inputs=[helper.make_tensor_value_info("X", TensorProto.FLOAT, list(input_dims)), helper.make_tensor_value_info("K", TensorProto.INT64, [1,])], initializer=[helper.make_tensor("K", TensorProto.INT64, [1], [K])], outputs=[helper.make_tensor_value_info("Values", TensorProto.FLOAT, output_dims), helper.make_tensor_value_info("Indicies", TensorProto.INT64, output_dims)]) model = helper.make_model(graph, producer_name='topk_test') indata = np.random.uniform(-10, 10, input_dims).astype(np.float32) onnx_out = get_onnxruntime_output(model, [indata, k]) for target, ctx in [('llvm', tvm.cpu())]: tvm_out = get_tvm_output(model, indata, target, ctx, [output_dims, output_dims], output_dtype=['float32', 'int64']) tvm.testing.assert_allclose(onnx_out, tvm_out, rtol=1e-05, atol=1e-05) for n in [12, 32]: for shape in [[n], [n, n], [n, n, n]]: for k in [1, 5, 10]: verify_topk(shape, k) verify_topk([n, n, n],
createInstance(clazz, instance_creator) self._pyroInstances[clazz] = instance return instance elif instance_mode == "session": # Create and use one instance for this proxy connection # the instances are kept on the connection object. # (this is the default instance mode when using new style @expose) instance = conn.pyroInstances.get(clazz) if not instance: log.debug("instancemode %s: creating new pyro object for %s", instance_mode, clazz) instance = createInstance(clazz, instance_creator) conn.pyroInstances[clazz] = instance return instance elif instance_mode == "percall": # create and use a new instance just for this call log.debug("instancemode %s: creating new pyro object for %s", instance_mode, clazz) return createInstance(clazz, instance_creator) else: raise errors.DaemonError("invalid instancemode in registered class") def _sendExceptionResponse(self, connection, seq, serializer_id, exc_value, tbinfo, flags=0, annotations=None): """send an exception back including the local traceback info""" exc_value._pyroTraceback = tbinfo serializer = serializers.serializers_by_id[serializer_id] try: data = serializer.dumps(exc_value) except: # the exception object couldn't be serialized, use a generic PyroError instead xt, xv, tb = sys.exc_info() msg = "Error serializing exception: %s. Original exception: %s: %s" % (str(xv), type(exc_value), str(exc_value)) exc_value = errors.PyroError(msg) exc_value._pyroTraceback = tbinfo data = serializer.dumps(exc_value) flags |= protocol.FLAGS_EXCEPTION annotations = dict(annotations or {}) annotations.update(self.annotations()) msg = protocol.SendingMessage(protocol.MSG_RESULT, flags, seq, serializer.serializer_id, data, annotations=annotations) if config.LOGWIRE: protocol.log_wiredata(log, "daemon wiredata sending (error response)", msg) connection.send(msg.data) def register(self, obj_or_class, objectId=None, force=False): """ Register a Pyro object under the given id. Note that this object is now only known inside this daemon, it is not automatically available in a name server. This method returns a URI for the registered object. Pyro checks if an object is already registered, unless you set force=True. You can register a class or an object (instance) directly. For a class, Pyro will create instances of it to handle the remote calls according to the instance_mode (set via @expose on the class). The default there is one object per session (=proxy connection). If you register an object directly, Pyro will use that single object for *all* remote calls. """ if objectId: if not isinstance(objectId, str): raise TypeError("objectId must be a string or None") else: objectId = "obj_" + uuid.uuid4().hex # generate a new objectId if inspect.isclass(obj_or_class): if not hasattr(obj_or_class, "_pyroInstancing"): obj_or_class._pyroInstancing = ("session", None) if not force: if hasattr(obj_or_class, "_pyroId") and obj_or_class._pyroId != "": # check for empty string is needed for Cython raise errors.DaemonError("object or class already has a Pyro id") if objectId in self.objectsById: raise errors.DaemonError("an object or class is already registered with that id") # set some pyro attributes obj_or_class._pyroId = objectId obj_or_class._pyroDaemon = self # register a custom serializer for the type to automatically return proxies # we need to do this for all known serializers for ser in serializers.serializers.values(): if inspect.isclass(obj_or_class): ser.register_type_replacement(obj_or_class, pyro_obj_to_auto_proxy) else: ser.register_type_replacement(type(obj_or_class), pyro_obj_to_auto_proxy) # register the object/class in the mapping self.objectsById[obj_or_class._pyroId] = obj_or_class return self.uriFor(objectId) def unregister(self, objectOrId): """ Remove a class or object from the known objects inside this daemon. You can unregister the class/object directly, or with its id. """ if objectOrId is None: raise ValueError("object or objectid argument expected") if not isinstance(objectOrId, str): objectId = getattr(objectOrId, "_pyroId", None) if objectId is None: raise errors.DaemonError("object isn't registered") else: objectId = objectOrId objectOrId = None if objectId == core.DAEMON_NAME: return if objectId in self.objectsById: del self.objectsById[objectId] if objectOrId is not None: del objectOrId._pyroId del objectOrId._pyroDaemon # Don't remove the custom type serializer because there may be # other registered objects of the same type still depending on it. def uriFor(self, objectOrId, nat=True): """ Get a URI for the given object (or object id) from this daemon. Only a daemon can hand out proper uris because the access location is contained in them. Note that unregistered objects cannot be given an uri, but unregistered object names can (it's just a string we're creating in that case). If nat is set to False, the configured NAT address (if any) is ignored and it will return an URI for the internal address. """ if not isinstance(objectOrId, str): objectOrId = getattr(objectOrId, "_pyroId", None) if objectOrId is None or objectOrId not in self.objectsById: raise errors.DaemonError("object isn't registered in this daemon") if nat: loc = self.natLocationStr or self.locationStr else: loc = self.locationStr return core.URI("PYRO:%s@%s" % (objectOrId, loc)) def resetMetadataCache(self, objectOrId, nat=True): """Reset cache of metadata when a Daemon has available methods/attributes dynamically updated. Clients will have to get a new proxy to see changes""" uri = self.uriFor(objectOrId, nat) # can only be cached if registered, else no-op if uri.object in self.objectsById: registered_object = self.objectsById[uri.object] # Clear cache regardless of how it is accessed reset_exposed_members(registered_object, as_lists=True) reset_exposed_members(registered_object, as_lists=False) def proxyFor(self, objectOrId, nat=True): """ Get a fully initialized Pyro Proxy for the given object (or object id) for this daemon. If nat is False, the configured NAT address (if any) is ignored. The object or id must be registered in this daemon, or you'll get an exception. (you can't get a proxy for an unknown object) """ uri = self.uriFor(objectOrId, nat) proxy = client.Proxy(uri) try: registered_object = self.objectsById[uri.object] except KeyError: raise errors.DaemonError("object isn't registered in this daemon") meta = get_exposed_members(registered_object) proxy._pyroGetMetadata(known_metadata=meta) return proxy def close(self): """Close down the server and release resources""" self.__mustshutdown.set() self.streaming_responses = {} if self.transportServer: log.debug("daemon closing") self.transportServer.close() self.transportServer = None def annotations(self): """Override to return a dict with custom user annotations to be sent with each response message.""" return {} def combine(self, daemon): """ Combines the event loop of the other daemon in the current daemon's loop. You can then simply run the current daemon's requestLoop to serve both daemons. This works fine on the multiplex server type, but doesn't work with the threaded server type. """ log.debug("combining event loop with other daemon") self.transportServer.combine_loop(daemon.transportServer) def __annotations(self): annotations = core.current_context.response_annotations annotations.update(self.annotations()) return annotations def __repr__(self): if hasattr(self, "locationStr"): family = socketutil.family_str(self.sock) return "<%s.%s at 0x%x; %s - %s; %d objects>" % (self.__class__.__module__, self.__class__.__name__, id(self), self.locationStr, family, len(self.objectsById)) else: # daemon objects may come back from serialized form without being properly initialized (by design) return "<%s.%s at 0x%x; unusable>" % (self.__class__.__module__, self.__class__.__name__, id(self)) def __enter__(self): if not self.transportServer: raise errors.PyroError("cannot reuse this object") return self def __exit__(self, exc_type, exc_value, traceback): self.close() def __getstate__(self): # A little hack to make it possible to serialize Pyro objects, because they can reference a daemon, # but it is not meant to be able to properly serialize/deserialize Daemon objects. return tuple() def __setstate__(self, state): assert len(state) == 0 __lazy_dict_iterator_types = (type({}.keys()), type({}.values()), type({}.items())) def _streamResponse(self, data, client): if isinstance(data, collections.Iterator) or inspect.isgenerator(data): if config.ITER_STREAMING: if type(data) in self.__lazy_dict_iterator_types: raise errors.PyroError("won't serialize or stream lazy dict iterators, convert to list yourself") stream_id = str(uuid.uuid4()) self.streaming_responses[stream_id] = (client, time.time(), 0, data) return True, stream_id return True, None return False, data def __deserializeBlobArgs(self, protocolmsg): import marshal blobinfo = protocolmsg.annotations["BLBI"] blobinfo, objId, method = marshal.loads(blobinfo) blob = client.SerializedBlob(blobinfo, protocolmsg, is_blob=True) return objId, method, (blob,), {} # object, method, vargs, kwargs # register the special serializers for the pyro objects serpent.register_class(Daemon, serializers.pyro_class_serpent_serializer) serializers.SerializerBase.register_class_to_dict(Daemon, serializers.serialize_pyro_object_to_dict, serpent_too=False) def pyro_obj_to_auto_proxy(obj): """reduce function that automatically replaces Pyro objects by a Proxy""" daemon = getattr(obj, "_pyroDaemon", None) if daemon: # only return a proxy if the object is a registered pyro object return daemon.proxyFor(obj) return obj def get_attribute(obj, attr): """ Resolves an attribute name to an object. Raises an AttributeError if any attribute in the chain starts with a '``_``'. Doesn't resolve a dotted name, because that is a security vulnerability. It treats it as a single attribute name (and the lookup will likely fail). """ if is_private_attribute(attr): raise AttributeError("attempt to access private attribute '%s'" % attr) else: obj = getattr(obj, attr) if getattr(obj, "_pyroExposed", False): return obj raise AttributeError("attempt to access unexposed attribute '%s'" % attr) __exposed_member_cache = {} def reset_exposed_members(obj, only_exposed=True, as_lists=False): """Delete any cached exposed members forcing recalculation on next request""" if not inspect.isclass(obj): obj = obj.__class__ cache_key = (obj, only_exposed, as_lists) __exposed_member_cache.pop(cache_key, None) def get_exposed_members(obj, only_exposed=True, as_lists=False, use_cache=True): """ Return public and exposed members of the given object's class. You
= 73 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,0,self._ctx) if la_ == 1: self.state = 70 self.declare_note() pass elif la_ == 2: self.state = 71 self.declare_chord() pass elif la_ == 3: self.state = 72 self.declare_melody() pass self.state = 77 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,1,self._ctx) self.state = 80 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 80 self._errHandler.sync(self) token = self._input.LA(1) if token in [MyGrammerParser.STAFF]: self.state = 78 self.declare_staff() pass elif token in [MyGrammerParser.IDENTIFIER]: self.state = 79 self.expr_var() pass else: raise NoViableAltException(self) self.state = 82 self._errHandler.sync(self) _la = self._input.LA(1) if not (_la==MyGrammerParser.STAFF or _la==MyGrammerParser.IDENTIFIER): break self.state = 84 self.match(MyGrammerParser.EOF) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Declare_noteContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def IDENTIFIER(self): return self.getToken(MyGrammerParser.IDENTIFIER, 0) def EQUAL_OPER(self): return self.getToken(MyGrammerParser.EQUAL_OPER, 0) def expr_note(self): return self.getTypedRuleContext(MyGrammerParser.Expr_noteContext,0) def getRuleIndex(self): return MyGrammerParser.RULE_declare_note def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterDeclare_note" ): listener.enterDeclare_note(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitDeclare_note" ): listener.exitDeclare_note(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitDeclare_note" ): return visitor.visitDeclare_note(self) else: return visitor.visitChildren(self) def declare_note(self): localctx = MyGrammerParser.Declare_noteContext(self, self._ctx, self.state) self.enterRule(localctx, 10, self.RULE_declare_note) try: self.enterOuterAlt(localctx, 1) self.state = 86 self.match(MyGrammerParser.IDENTIFIER) self.state = 87 self.match(MyGrammerParser.EQUAL_OPER) self.state = 88 self.expr_note() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Declare_chordContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def IDENTIFIER(self): return self.getToken(MyGrammerParser.IDENTIFIER, 0) def EQUAL_OPER(self): return self.getToken(MyGrammerParser.EQUAL_OPER, 0) def expr_chord(self): return self.getTypedRuleContext(MyGrammerParser.Expr_chordContext,0) def getRuleIndex(self): return MyGrammerParser.RULE_declare_chord def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterDeclare_chord" ): listener.enterDeclare_chord(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitDeclare_chord" ): listener.exitDeclare_chord(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitDeclare_chord" ): return visitor.visitDeclare_chord(self) else: return visitor.visitChildren(self) def declare_chord(self): localctx = MyGrammerParser.Declare_chordContext(self, self._ctx, self.state) self.enterRule(localctx, 12, self.RULE_declare_chord) try: self.enterOuterAlt(localctx, 1) self.state = 90 self.match(MyGrammerParser.IDENTIFIER) self.state = 91 self.match(MyGrammerParser.EQUAL_OPER) self.state = 92 self.expr_chord() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Declare_melodyContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def MELODY(self): return self.getToken(MyGrammerParser.MELODY, 0) def IDENTIFIER(self): return self.getToken(MyGrammerParser.IDENTIFIER, 0) def OPEN_BRACKET(self): return self.getToken(MyGrammerParser.OPEN_BRACKET, 0) def CLOSE_BRACKET(self): return self.getToken(MyGrammerParser.CLOSE_BRACKET, 0) def declare_staff(self, i:int=None): if i is None: return self.getTypedRuleContexts(MyGrammerParser.Declare_staffContext) else: return self.getTypedRuleContext(MyGrammerParser.Declare_staffContext,i) def getRuleIndex(self): return MyGrammerParser.RULE_declare_melody def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterDeclare_melody" ): listener.enterDeclare_melody(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitDeclare_melody" ): listener.exitDeclare_melody(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitDeclare_melody" ): return visitor.visitDeclare_melody(self) else: return visitor.visitChildren(self) def declare_melody(self): localctx = MyGrammerParser.Declare_melodyContext(self, self._ctx, self.state) self.enterRule(localctx, 14, self.RULE_declare_melody) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 94 self.match(MyGrammerParser.MELODY) self.state = 95 self.match(MyGrammerParser.IDENTIFIER) self.state = 96 self.match(MyGrammerParser.OPEN_BRACKET) self.state = 98 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 97 self.declare_staff() self.state = 100 self._errHandler.sync(self) _la = self._input.LA(1) if not (_la==MyGrammerParser.STAFF): break self.state = 102 self.match(MyGrammerParser.CLOSE_BRACKET) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Declare_patternContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def TUPLET(self): return self.getToken(MyGrammerParser.TUPLET, 0) def OPEN_BRACKET(self): return self.getToken(MyGrammerParser.OPEN_BRACKET, 0) def CLOSE_BRACKET(self): return self.getToken(MyGrammerParser.CLOSE_BRACKET, 0) def expr_note(self, i:int=None): if i is None: return self.getTypedRuleContexts(MyGrammerParser.Expr_noteContext) else: return self.getTypedRuleContext(MyGrammerParser.Expr_noteContext,i) def getRuleIndex(self): return MyGrammerParser.RULE_declare_pattern def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterDeclare_pattern" ): listener.enterDeclare_pattern(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitDeclare_pattern" ): listener.exitDeclare_pattern(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitDeclare_pattern" ): return visitor.visitDeclare_pattern(self) else: return visitor.visitChildren(self) def declare_pattern(self): localctx = MyGrammerParser.Declare_patternContext(self, self._ctx, self.state) self.enterRule(localctx, 16, self.RULE_declare_pattern) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 104 self.match(MyGrammerParser.TUPLET) self.state = 105 self.match(MyGrammerParser.OPEN_BRACKET) self.state = 107 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 106 self.expr_note() self.state = 109 self._errHandler.sync(self) _la = self._input.LA(1) if not ((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << MyGrammerParser.DOUBLE) | (1 << MyGrammerParser.FULL) | (1 << MyGrammerParser.HALF) | (1 << MyGrammerParser.QUARTER) | (1 << MyGrammerParser.EIGHTH) | (1 << MyGrammerParser.SIXTEENTH) | (1 << MyGrammerParser.THIRTYSECOND))) != 0)): break self.state = 111 self.match(MyGrammerParser.CLOSE_BRACKET) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Declare_measuresContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def MEASURE(self): return self.getToken(MyGrammerParser.MEASURE, 0) def OPEN_BRACKET(self): return self.getToken(MyGrammerParser.OPEN_BRACKET, 0) def measure_block(self): return self.getTypedRuleContext(MyGrammerParser.Measure_blockContext,0) def CLOSE_BRACKET(self): return self.getToken(MyGrammerParser.CLOSE_BRACKET, 0) def getRuleIndex(self): return MyGrammerParser.RULE_declare_measures def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterDeclare_measures" ): listener.enterDeclare_measures(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitDeclare_measures" ): listener.exitDeclare_measures(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitDeclare_measures" ): return visitor.visitDeclare_measures(self) else: return visitor.visitChildren(self) def declare_measures(self): localctx = MyGrammerParser.Declare_measuresContext(self, self._ctx, self.state) self.enterRule(localctx, 18, self.RULE_declare_measures) try: self.enterOuterAlt(localctx, 1) self.state = 113 self.match(MyGrammerParser.MEASURE) self.state = 114 self.match(MyGrammerParser.OPEN_BRACKET) self.state = 115 self.measure_block() self.state = 116 self.match(MyGrammerParser.CLOSE_BRACKET) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Declare_measures_upContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def MEASUREUP(self): return self.getToken(MyGrammerParser.MEASUREUP, 0) def OPEN_BRACKET(self): return self.getToken(MyGrammerParser.OPEN_BRACKET, 0) def measure_block(self): return self.getTypedRuleContext(MyGrammerParser.Measure_blockContext,0) def CLOSE_BRACKET(self): return self.getToken(MyGrammerParser.CLOSE_BRACKET, 0) def declare_measures_down(self): return self.getTypedRuleContext(MyGrammerParser.Declare_measures_downContext,0) def getRuleIndex(self): return MyGrammerParser.RULE_declare_measures_up def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterDeclare_measures_up" ): listener.enterDeclare_measures_up(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitDeclare_measures_up" ): listener.exitDeclare_measures_up(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitDeclare_measures_up" ): return visitor.visitDeclare_measures_up(self) else: return visitor.visitChildren(self) def declare_measures_up(self): localctx = MyGrammerParser.Declare_measures_upContext(self, self._ctx, self.state) self.enterRule(localctx, 20, self.RULE_declare_measures_up) try: self.enterOuterAlt(localctx, 1) self.state = 118 self.match(MyGrammerParser.MEASUREUP) self.state = 119 self.match(MyGrammerParser.OPEN_BRACKET) self.state = 120 self.measure_block() self.state = 121 self.match(MyGrammerParser.CLOSE_BRACKET) self.state = 122 self.declare_measures_down() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Declare_measures_downContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def MEASUREDOWN(self): return self.getToken(MyGrammerParser.MEASUREDOWN, 0) def OPEN_BRACKET(self): return self.getToken(MyGrammerParser.OPEN_BRACKET, 0) def measure_block(self): return self.getTypedRuleContext(MyGrammerParser.Measure_blockContext,0) def CLOSE_BRACKET(self): return self.getToken(MyGrammerParser.CLOSE_BRACKET, 0) def getRuleIndex(self): return MyGrammerParser.RULE_declare_measures_down def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterDeclare_measures_down" ): listener.enterDeclare_measures_down(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitDeclare_measures_down" ): listener.exitDeclare_measures_down(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitDeclare_measures_down" ): return visitor.visitDeclare_measures_down(self) else: return visitor.visitChildren(self) def declare_measures_down(self): localctx = MyGrammerParser.Declare_measures_downContext(self, self._ctx, self.state) self.enterRule(localctx, 22, self.RULE_declare_measures_down) try: self.enterOuterAlt(localctx, 1) self.state = 124 self.match(MyGrammerParser.MEASUREDOWN) self.state = 125 self.match(MyGrammerParser.OPEN_BRACKET) self.state = 126 self.measure_block() self.state = 127 self.match(MyGrammerParser.CLOSE_BRACKET) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Measure_blockContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def declare_ending(self): return self.getTypedRuleContext(MyGrammerParser.Declare_endingContext,0) def declare_repeat(self): return self.getTypedRuleContext(MyGrammerParser.Declare_repeatContext,0) def expr(self, i:int=None): if i is None: return self.getTypedRuleContexts(MyGrammerParser.ExprContext) else: return self.getTypedRuleContext(MyGrammerParser.ExprContext,i) def declare_pattern(self, i:int=None): if i is None: return self.getTypedRuleContexts(MyGrammerParser.Declare_patternContext) else: return self.getTypedRuleContext(MyGrammerParser.Declare_patternContext,i) def declare_repeat_end(self): return self.getTypedRuleContext(MyGrammerParser.Declare_repeat_endContext,0) def declare_ending_end(self): return self.getTypedRuleContext(MyGrammerParser.Declare_ending_endContext,0) def getRuleIndex(self): return MyGrammerParser.RULE_measure_block def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterMeasure_block" ): listener.enterMeasure_block(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitMeasure_block" ): listener.exitMeasure_block(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitMeasure_block" ): return visitor.visitMeasure_block(self) else: return visitor.visitChildren(self) def measure_block(self): localctx = MyGrammerParser.Measure_blockContext(self, self._ctx, self.state) self.enterRule(localctx, 24, self.RULE_measure_block) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 130 self._errHandler.sync(self) _la = self._input.LA(1) if _la==MyGrammerParser.ENDSTART: self.state = 129 self.declare_ending() self.state = 133 self._errHandler.sync(self) _la = self._input.LA(1) if _la==MyGrammerParser.REPSTART: self.state = 132 self.declare_repeat() self.state = 137 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 137 self._errHandler.sync(self) token = self._input.LA(1) if token in [MyGrammerParser.ACCIDENTAL_KEY, MyGrammerParser.CHORD, MyGrammerParser.DOUBLE, MyGrammerParser.FULL, MyGrammerParser.HALF, MyGrammerParser.QUARTER, MyGrammerParser.EIGHTH, MyGrammerParser.SIXTEENTH, MyGrammerParser.THIRTYSECOND, MyGrammerParser.IDENTIFIER]: self.state = 135 self.expr() pass elif token in [MyGrammerParser.TUPLET]: self.state = 136 self.declare_pattern() pass else: raise NoViableAltException(self) self.state = 139 self._errHandler.sync(self) _la = self._input.LA(1) if not ((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << MyGrammerParser.ACCIDENTAL_KEY) | (1 << MyGrammerParser.CHORD) | (1 << MyGrammerParser.TUPLET) | (1 << MyGrammerParser.DOUBLE) | (1 << MyGrammerParser.FULL) | (1 << MyGrammerParser.HALF) | (1 << MyGrammerParser.QUARTER) | (1 << MyGrammerParser.EIGHTH) | (1 << MyGrammerParser.SIXTEENTH) | (1 << MyGrammerParser.THIRTYSECOND) | (1 << MyGrammerParser.IDENTIFIER))) != 0)): break self.state = 142 self._errHandler.sync(self) _la = self._input.LA(1) if _la==MyGrammerParser.REPEND: self.state = 141 self.declare_repeat_end() self.state = 145 self._errHandler.sync(self) _la = self._input.LA(1)
""" Integration test for a battery+motor example that demonstrates phase branching in trajectories. """ from __future__ import print_function, division, absolute_import import os import unittest from openmdao.api import Problem, pyOptSparseDriver, ScipyOptimizeDriver, DirectSolver from openmdao.utils.assert_utils import assert_rel_error from dymos import Trajectory, Phase, Radau, RungeKutta from dymos.examples.battery_multibranch.battery_multibranch_ode import BatteryODE from dymos.utils.lgl import lgl optimizer = os.environ.get('DYMOS_DEFAULT_OPT', 'SLSQP') class TestBatteryBranchingPhases(unittest.TestCase): def test_optimizer_defects(self): prob = Problem() if optimizer == 'SNOPT': opt = prob.driver = pyOptSparseDriver() opt.options['optimizer'] = optimizer opt.options['dynamic_simul_derivs'] = True opt.opt_settings['Major iterations limit'] = 1000 opt.opt_settings['Major feasibility tolerance'] = 1.0E-6 opt.opt_settings['Major optimality tolerance'] = 1.0E-6 opt.opt_settings["Linesearch tolerance"] = 0.10 opt.opt_settings['iSumm'] = 6 else: opt = prob.driver = ScipyOptimizeDriver() opt.options['dynamic_simul_derivs'] = True num_seg = 5 seg_ends, _ = lgl(num_seg + 1) traj = prob.model.add_subsystem('traj', Trajectory()) # First phase: normal operation. transcription = Radau(num_segments=5, order=5, segment_ends=seg_ends, compressed=False) phase0 = Phase(ode_class=BatteryODE, transcription=transcription) traj_p0 = traj.add_phase('phase0', phase0) traj_p0.set_time_options(fix_initial=True, fix_duration=True) traj_p0.set_state_options('state_of_charge', fix_initial=True, fix_final=False) # Second phase: normal operation. phase1 = Phase(ode_class=BatteryODE, transcription=transcription) traj_p1 = traj.add_phase('phase1', phase1) traj_p1.set_time_options(fix_initial=False, fix_duration=True) traj_p1.set_state_options('state_of_charge', fix_initial=False, fix_final=False) traj_p1.add_objective('time', loc='final') # Second phase, but with battery failure. phase1_bfail = Phase(ode_class=BatteryODE, ode_init_kwargs={'num_battery': 2}, transcription=transcription) traj_p1_bfail = traj.add_phase('phase1_bfail', phase1_bfail) traj_p1_bfail.set_time_options(fix_initial=False, fix_duration=True) traj_p1_bfail.set_state_options('state_of_charge', fix_initial=False, fix_final=False) # Second phase, but with motor failure. phase1_mfail = Phase(ode_class=BatteryODE, ode_init_kwargs={'num_motor': 2}, transcription=transcription) traj_p1_mfail = traj.add_phase('phase1_mfail', phase1_mfail) traj_p1_mfail.set_time_options(fix_initial=False, fix_duration=True) traj_p1_mfail.set_state_options('state_of_charge', fix_initial=False, fix_final=False) traj.link_phases(phases=['phase0', 'phase1'], vars=['state_of_charge', 'time']) traj.link_phases(phases=['phase0', 'phase1_bfail'], vars=['state_of_charge', 'time']) traj.link_phases(phases=['phase0', 'phase1_mfail'], vars=['state_of_charge', 'time']) prob.model.options['assembled_jac_type'] = 'csc' prob.model.linear_solver = DirectSolver(assemble_jac=True) prob.setup() prob['traj.phase0.t_initial'] = 0 prob['traj.phase0.t_duration'] = 1.0*3600 prob['traj.phase1.t_initial'] = 1.0*3600 prob['traj.phase1.t_duration'] = 1.0*3600 prob['traj.phase1_bfail.t_initial'] = 1.0*3600 prob['traj.phase1_bfail.t_duration'] = 1.0*3600 prob['traj.phase1_mfail.t_initial'] = 1.0*3600 prob['traj.phase1_mfail.t_duration'] = 1.0*3600 prob.set_solver_print(level=0) prob.run_driver() soc0 = prob['traj.phase0.states:state_of_charge'] soc1 = prob['traj.phase1.states:state_of_charge'] soc1b = prob['traj.phase1_bfail.states:state_of_charge'] soc1m = prob['traj.phase1_mfail.states:state_of_charge'] # Final value for State of Chrage in each segment should be a good test. assert_rel_error(self, soc0[-1], 0.63464982, 1e-6) assert_rel_error(self, soc1[-1], 0.23794217, 1e-6) assert_rel_error(self, soc1b[-1], 0.0281523, 1e-6) assert_rel_error(self, soc1m[-1], 0.18625395, 1e-6) def test_solver_defects(self): prob = Problem() num_seg = 5 seg_ends, _ = lgl(num_seg + 1) traj = prob.model.add_subsystem('traj', Trajectory()) # First phase: normal operation. transcription = Radau(num_segments=5, order=5, segment_ends=seg_ends, compressed=True) phase0 = Phase(ode_class=BatteryODE, transcription=transcription) traj_p0 = traj.add_phase('phase0', phase0) traj_p0.set_time_options(fix_initial=True, fix_duration=True) traj_p0.set_state_options('state_of_charge', fix_initial=True, fix_final=False, solve_segments=True) # Second phase: normal operation. phase1 = Phase(ode_class=BatteryODE, transcription=transcription) traj_p1 = traj.add_phase('phase1', phase1) traj_p1.set_time_options(fix_initial=False, fix_duration=True) traj_p1.set_state_options('state_of_charge', fix_initial=False, fix_final=False, solve_segments=True) traj_p1.add_objective('time', loc='final') # Second phase, but with battery failure. phase1_bfail = Phase(ode_class=BatteryODE, ode_init_kwargs={'num_battery': 2}, transcription=transcription) traj_p1_bfail = traj.add_phase('phase1_bfail', phase1_bfail) traj_p1_bfail.set_time_options(fix_initial=False, fix_duration=True) traj_p1_bfail.set_state_options('state_of_charge', fix_initial=False, fix_final=False, solve_segments=True) # Second phase, but with motor failure. phase1_mfail = Phase(ode_class=BatteryODE, ode_init_kwargs={'num_motor': 2}, transcription=transcription) traj_p1_mfail = traj.add_phase('phase1_mfail', phase1_mfail) traj_p1_mfail.set_time_options(fix_initial=False, fix_duration=True) traj_p1_mfail.set_state_options('state_of_charge', fix_initial=False, fix_final=False, solve_segments=True) traj.link_phases(phases=['phase0', 'phase1'], vars=['state_of_charge', 'time'], connected=True) traj.link_phases(phases=['phase0', 'phase1_bfail'], vars=['state_of_charge', 'time'], connected=True) traj.link_phases(phases=['phase0', 'phase1_mfail'], vars=['state_of_charge', 'time'], connected=True) prob.setup() prob['traj.phase0.t_initial'] = 0 prob['traj.phase0.t_duration'] = 1.0*3600 prob['traj.phase1.t_initial'] = 1.0*3600 prob['traj.phase1.t_duration'] = 1.0*3600 prob['traj.phase1_bfail.t_initial'] = 1.0*3600 prob['traj.phase1_bfail.t_duration'] = 1.0*3600 prob['traj.phase1_mfail.t_initial'] = 1.0*3600 prob['traj.phase1_mfail.t_duration'] = 1.0*3600 prob['traj.phase0.states:state_of_charge'][:] = 1.0 prob.set_solver_print(level=0) prob.run_model() soc0 = prob['traj.phase0.states:state_of_charge'] soc1 = prob['traj.phase1.states:state_of_charge'] soc1b = prob['traj.phase1_bfail.states:state_of_charge'] soc1m = prob['traj.phase1_mfail.states:state_of_charge'] # Final value for State of Charge in each segment should be a good test. assert_rel_error(self, soc0[-1], 0.63464982, 1e-6) assert_rel_error(self, soc1[-1], 0.23794217, 1e-6) assert_rel_error(self, soc1b[-1], 0.0281523, 1e-6) assert_rel_error(self, soc1m[-1], 0.18625395, 1e-6) def test_solver_defects_single_phase_reverse_propagation(self): prob = Problem() num_seg = 5 seg_ends, _ = lgl(num_seg + 1) # First phase: normal operation. transcription = Radau(num_segments=5, order=5, segment_ends=seg_ends, compressed=True) phase0 = Phase(ode_class=BatteryODE, transcription=transcription) traj_p0 = prob.model.add_subsystem('phase0', phase0) traj_p0.set_time_options(fix_initial=True, fix_duration=True) traj_p0.set_state_options('state_of_charge', fix_initial=True, fix_final=False, solve_segments=True) prob.setup() prob['phase0.t_initial'] = 0 prob['phase0.t_duration'] = -1.0*3600 prob['phase0.states:state_of_charge'][:] = 0.63464982 prob.set_solver_print(level=0) prob.run_model() soc0 = prob['phase0.states:state_of_charge'] assert_rel_error(self, soc0[-1], 1.0, 1e-6) def test_solver_defects_reverse_propagation(self): prob = Problem() num_seg = 5 seg_ends, _ = lgl(num_seg + 1) traj = prob.model.add_subsystem('traj', Trajectory()) # First phase: normal operation. transcription = Radau(num_segments=5, order=5, segment_ends=seg_ends, compressed=True) phase0 = Phase(ode_class=BatteryODE, transcription=transcription) traj_p0 = traj.add_phase('phase0', phase0) traj_p0.set_time_options(fix_initial=True, fix_duration=True) traj_p0.set_state_options('state_of_charge', fix_initial=True, fix_final=False, solve_segments=True) # Second phase: normal operation. phase1 = Phase(ode_class=BatteryODE, transcription=transcription) traj_p1 = traj.add_phase('phase1', phase1) traj_p1.set_time_options(fix_initial=False, fix_duration=True) traj_p1.set_state_options('state_of_charge', fix_initial=False, fix_final=False, solve_segments=True) traj_p1.add_objective('time', loc='final') traj.link_phases(phases=['phase0', 'phase1'], vars=['state_of_charge', 'time'], connected=True) prob.setup() prob['traj.phase0.t_initial'] = 0 prob['traj.phase0.t_duration'] = -1.0*3600 prob['traj.phase0.states:state_of_charge'][:] = 0.23794217 prob['traj.phase1.t_initial'] = 0 prob['traj.phase1.t_duration'] = -1.0*3600 prob.set_solver_print(level=0) prob.run_model() soc1 = prob['traj.phase1.states:state_of_charge'] assert_rel_error(self, soc1[-1], 1.0, 1e-6) def test_optimizer_segments_direct_connections(self): prob = Problem() if optimizer == 'SNOPT': opt = prob.driver = pyOptSparseDriver() opt.options['optimizer'] = optimizer opt.options['dynamic_simul_derivs'] = True opt.opt_settings['Major iterations limit'] = 1000 opt.opt_settings['Major feasibility tolerance'] = 1.0E-6 opt.opt_settings['Major optimality tolerance'] = 1.0E-6 opt.opt_settings["Linesearch tolerance"] = 0.10 opt.opt_settings['iSumm'] = 6 else: opt = prob.driver = ScipyOptimizeDriver() opt.options['dynamic_simul_derivs'] = True num_seg = 5 seg_ends, _ = lgl(num_seg + 1) traj = prob.model.add_subsystem('traj', Trajectory()) # First phase: normal operation. transcription = Radau(num_segments=5, order=5, segment_ends=seg_ends, compressed=True) phase0 = Phase(ode_class=BatteryODE, transcription=transcription) traj_p0 = traj.add_phase('phase0', phase0) traj_p0.set_time_options(fix_initial=True, fix_duration=True) traj_p0.set_state_options('state_of_charge', fix_initial=True, fix_final=False) # Second phase: normal operation. phase1 = Phase(ode_class=BatteryODE, transcription=transcription) traj_p1 = traj.add_phase('phase1', phase1) traj_p1.set_time_options(fix_initial=False, fix_duration=True) traj_p1.set_state_options('state_of_charge', fix_initial=False, fix_final=False) traj_p1.add_objective('time', loc='final') # Second phase, but with battery failure. phase1_bfail = Phase(ode_class=BatteryODE, ode_init_kwargs={'num_battery': 2}, transcription=transcription) traj_p1_bfail = traj.add_phase('phase1_bfail', phase1_bfail) traj_p1_bfail.set_time_options(fix_initial=False, fix_duration=True) traj_p1_bfail.set_state_options('state_of_charge', fix_initial=False, fix_final=False) # Second phase, but with motor failure. phase1_mfail = Phase(ode_class=BatteryODE, ode_init_kwargs={'num_motor': 2}, transcription=transcription) traj_p1_mfail = traj.add_phase('phase1_mfail', phase1_mfail) traj_p1_mfail.set_time_options(fix_initial=False, fix_duration=True) traj_p1_mfail.set_state_options('state_of_charge', fix_initial=False, fix_final=False) traj.link_phases(phases=['phase0', 'phase1'], vars=['state_of_charge', 'time'], connected=True) traj.link_phases(phases=['phase0', 'phase1_bfail'], vars=['state_of_charge', 'time'], connected=True) traj.link_phases(phases=['phase0', 'phase1_mfail'], vars=['state_of_charge', 'time'], connected=True) prob.model.options['assembled_jac_type'] = 'csc' prob.model.linear_solver = DirectSolver(assemble_jac=True) prob.setup() prob['traj.phase0.t_initial'] = 0 prob['traj.phase0.t_duration'] = 1.0*3600 prob['traj.phase1.t_initial'] = 1.0*3600 prob['traj.phase1.t_duration'] = 1.0*3600 prob['traj.phase1_bfail.t_initial'] = 1.0*3600 prob['traj.phase1_bfail.t_duration'] = 1.0*3600 prob['traj.phase1_mfail.t_initial'] = 1.0*3600 prob['traj.phase1_mfail.t_duration'] = 1.0*3600 prob.set_solver_print(level=0) prob.run_driver() soc0 = prob['traj.phase0.states:state_of_charge'] soc1 = prob['traj.phase1.states:state_of_charge'] soc1b = prob['traj.phase1_bfail.states:state_of_charge'] soc1m = prob['traj.phase1_mfail.states:state_of_charge'] # Final value for State of Chrage in each segment should be a good test. assert_rel_error(self, soc0[-1], 0.63464982, 1e-6) assert_rel_error(self, soc1[-1], 0.23794217, 1e-6) assert_rel_error(self, soc1b[-1], 0.0281523, 1e-6) assert_rel_error(self, soc1m[-1], 0.18625395, 1e-6) class TestBatteryBranchingPhasesRungeKutta(unittest.TestCase): def test_constraint_linkages_rk(self): prob = Problem() if optimizer == 'SNOPT': opt = prob.driver = pyOptSparseDriver() opt.options['optimizer'] = optimizer opt.options['dynamic_simul_derivs'] = True opt.opt_settings['Major iterations limit'] = 1000 opt.opt_settings['Major feasibility tolerance'] = 1.0E-6 opt.opt_settings['Major optimality tolerance'] = 1.0E-6 opt.opt_settings["Linesearch tolerance"] = 0.10 opt.opt_settings['iSumm'] = 6 else: opt = prob.driver = ScipyOptimizeDriver() opt.options['dynamic_simul_derivs'] = True num_seg = 20 seg_ends, _ = lgl(num_seg + 1) traj = prob.model.add_subsystem('traj', Trajectory()) # First phase: normal operation. transcription = RungeKutta(num_segments=num_seg) phase0 = Phase(ode_class=BatteryODE, transcription=transcription) traj_p0 = traj.add_phase('phase0', phase0) traj_p0.set_time_options(fix_initial=True, fix_duration=True) traj_p0.set_state_options('state_of_charge', fix_initial=True, fix_final=False) # Second phase: normal operation. phase1 = Phase(ode_class=BatteryODE, transcription=transcription) traj_p1 = traj.add_phase('phase1', phase1) traj_p1.set_time_options(fix_initial=False, fix_duration=True) traj_p1.set_state_options('state_of_charge', fix_initial=False, fix_final=False) traj_p1.add_objective('time', loc='final') # Second phase, but with battery failure. phase1_bfail = Phase(ode_class=BatteryODE, ode_init_kwargs={'num_battery': 2}, transcription=transcription) traj_p1_bfail = traj.add_phase('phase1_bfail', phase1_bfail) traj_p1_bfail.set_time_options(fix_initial=False, fix_duration=True) traj_p1_bfail.set_state_options('state_of_charge', fix_initial=False, fix_final=False) # Second phase, but with motor failure. phase1_mfail = Phase(ode_class=BatteryODE, ode_init_kwargs={'num_motor': 2}, transcription=transcription) traj_p1_mfail = traj.add_phase('phase1_mfail', phase1_mfail) traj_p1_mfail.set_time_options(fix_initial=False, fix_duration=True) traj_p1_mfail.set_state_options('state_of_charge', fix_initial=False, fix_final=False) traj.link_phases(phases=['phase0', 'phase1'], vars=['state_of_charge', 'time']) traj.link_phases(phases=['phase0', 'phase1_bfail'], vars=['state_of_charge', 'time']) traj.link_phases(phases=['phase0', 'phase1_mfail'], vars=['state_of_charge', 'time']) prob.model.options['assembled_jac_type'] = 'csc' prob.model.linear_solver = DirectSolver(assemble_jac=True) prob.setup() prob['traj.phase0.t_initial'] = 0 prob['traj.phase0.t_duration'] = 1.0*3600 prob['traj.phase1.t_initial'] = 1.0*3600 prob['traj.phase1.t_duration'] = 1.0*3600 prob['traj.phase1_bfail.t_initial'] = 1.0*3600 prob['traj.phase1_bfail.t_duration'] = 1.0*3600 prob['traj.phase1_mfail.t_initial'] = 1.0*3600 prob['traj.phase1_mfail.t_duration'] = 1.0*3600 prob.set_solver_print(level=0) prob.run_driver() soc0 = prob['traj.phase0.states:state_of_charge'] soc1 = prob['traj.phase1.states:state_of_charge'] soc1b = prob['traj.phase1_bfail.states:state_of_charge'] soc1m = prob['traj.phase1_mfail.states:state_of_charge'] # Final value for State of Charge in each segment should be a good test. assert_rel_error(self, soc0[-1], 0.63464982, 1e-4) assert_rel_error(self, soc1[-1], 0.23794217, 1e-4) assert_rel_error(self, soc1b[-1], 0.0281523, 1e-4) assert_rel_error(self, soc1m[-1], 0.18625395, 1e-4) def test_single_phase_reverse_propagation_rk(self): prob = Problem() num_seg = 10 seg_ends, _ = lgl(num_seg + 1) # First phase: normal operation. transcription = RungeKutta(num_segments=num_seg) phase0 = Phase(ode_class=BatteryODE, transcription=transcription) traj_p0 = prob.model.add_subsystem('phase0', phase0) traj_p0.set_time_options(fix_initial=True, fix_duration=True) traj_p0.set_state_options('state_of_charge', fix_initial=True, fix_final=False) prob.setup() prob['phase0.t_initial'] = 0 prob['phase0.t_duration'] = -1.0*3600 prob['phase0.states:state_of_charge'][:] = 0.63464982 prob.set_solver_print(level=0) prob.run_model() soc0 = prob['phase0.states:state_of_charge'] assert_rel_error(self, soc0[-1], 1.0, 1e-6) def test_connected_linkages_rk(self): prob = Problem() if optimizer == 'SNOPT': opt = prob.driver = pyOptSparseDriver() opt.options['optimizer'] = optimizer opt.options['dynamic_simul_derivs'] = True opt.opt_settings['Major iterations limit'] = 1000 opt.opt_settings['Major feasibility tolerance'] = 1.0E-6 opt.opt_settings['Major optimality tolerance'] = 1.0E-6 opt.opt_settings["Linesearch tolerance"] = 0.10 opt.opt_settings['iSumm'] = 6 else: opt = prob.driver = ScipyOptimizeDriver() opt.options['dynamic_simul_derivs'] = True num_seg = 20 seg_ends, _ = lgl(num_seg + 1) traj = prob.model.add_subsystem('traj', Trajectory()) # First phase: normal operation. transcription = RungeKutta(num_segments=num_seg) phase0 = Phase(ode_class=BatteryODE, transcription=transcription) traj_p0 = traj.add_phase('phase0', phase0) traj_p0.set_time_options(fix_initial=True, fix_duration=True) traj_p0.set_state_options('state_of_charge', fix_initial=True, fix_final=False) # Second phase: normal operation. phase1 = Phase(ode_class=BatteryODE, transcription=transcription) traj_p1 = traj.add_phase('phase1', phase1) traj_p1.set_time_options(fix_initial=False, fix_duration=True) traj_p1.set_state_options('state_of_charge', fix_initial=False, fix_final=False) traj_p1.add_objective('time', loc='final') # Second phase, but with battery
## ## Name: test_scrubby.py ## Purpose: Unit tests for scrubby.py ## ## Copyright (C) 2009, <NAME>, All Rights Reserved. ## import scrubby as S import unittest, functools # {{ class test_scanner class test_scanner(unittest.TestCase): """Low-level tests for the markup_scanner class. Only tests the internal methods; higher-level methods should be tested by using the results in a markup_parser. """ def test_empty_input(self): """Test correct scan of empty input.""" ts = list(S.markup_scanner('').scan()) self.assertEqual(ts, [('eof', 0, 0, None)]) def test_strings(self): """Test quoted string tokens.""" for tag, src in ( ('str', '"double-quoted string"'), ('ustr', '"incomplete string'), ('str', "'single-quoted string'"), ('ustr', "'incomplete string"), ('str', '""'), # empty double-quoted ('str', "''"), # empty single-quoted ('ustr', '"\x01'), # incomplete double-quoted ('ustr', "'\x01"), # incomplete single-quoted ): s = S.markup_scanner(src) self.assertEqual(s.scan_string(0), (tag, 0, len(s.input))) def test_unquoted(self): """Test unquoted string tokens.""" s = S.markup_scanner('unquoted string') self.assertEqual(s.scan_unquoted(0), ('unq', 0, len('unquoted'))) s = S.markup_scanner(' empty') self.assertEqual(s.scan_unquoted(0, allow_blank=True), ('unq', 0, 0)) self.assertRaises(S.parse_error, lambda: s.scan_unquoted(0, allow_blank=False)) s = S.markup_scanner('NAME<') self.assertEqual(s.scan_name(0), ('name', 0, len('NAME'))) def test_space(self): """Test whitespace consumption.""" s = S.markup_scanner('nospace') self.assertEqual(s.scan_space(0), ('ws', 0, 0)) s = S.markup_scanner(' \t\f\r\n$') self.assertEqual(s.scan_space(0), ('ws', 0, len(s.input) - 1)) def test_literal(self): """Test consumption of literals.""" s = S.markup_scanner('$++OK') self.assertEqual(s.scan_literal(1, '++'), ('lit', 1, 1 + len('++'))) self.assertRaises(S.parse_error, lambda: s.scan_literal(0, 'XXX')) def test_entity(self): """Test consumption of entities.""" for src in ('&ok', '&123', '&a1bx3c'): s = S.markup_scanner(src) self.assertEqual(s.scan_entity(1), ('uent', 1, len(s.input))) s = S.markup_scanner(src + ';') self.assertEqual(s.scan_entity(1), ('ent', 1, len(s.input))) s = S.markup_scanner('&$;') self.assertEqual(s.scan_entity(1), ('uent', 1, 1)) def test_comment(self): """Test comment tokens.""" s = S.markup_scanner('<!---->') self.assertEqual(s.scan_comment(0), ('com', 0, len(s.input))) s = S.markup_scanner('<!-- some random stuff') self.assertEqual(s.scan_comment(0), ('ucom', 0, len(s.input))) s = S.markup_scanner('!<FAIL') self.assertRaises(S.parse_error, lambda: s.scan_comment(0)) def test_directives(self): """Test CDATA and other directives.""" s = S.markup_scanner('<!normal directive>') t = len(s.input) self.assertEqual(s.parse_one(0), ('dir', 0, t, { 'content': (2, t - 1), 'name': (2, 2 + len('normal')) })) s = S.markup_scanner('<!broken directive<') t = len(s.input) self.assertEqual(s.parse_one(0), ('udir', 0, t - 1, { 'content': (2, t - 1), 'name': (2, 2 + len('broken')) })) s = S.markup_scanner('<![CDATA[a[<]]*>+y<]]>') t = len(s.input) self.assertEqual(s.parse_one(0), ('cdata', 0, t, { 'content': (len('<![CDATA['), t - len(']]>')) })) s = S.markup_scanner('<![CDATA[...') t = len(s.input) self.assertEqual(s.parse_one(0), ('udata', 0, t, { 'content': (len('<![CDATA['), t) })) def test_attrib(self): """Test tag-attribute tokens.""" s = S.markup_scanner('novalue/') nlen = len('novalue') self.assertEqual(s.parse_attrib(0), ('attr', 0, nlen, { 'name': (0, nlen), 'value': ('none', nlen, nlen) })) s = S.markup_scanner('name=bare word') nlen = len('name') self.assertEqual(s.parse_attrib(0), ('attr', 0, len(s.input) - 5, { 'name': (0, nlen), 'value': ('unq', 5, 9) })) s = S.markup_scanner('name="bare word') self.assertEqual(s.parse_attrib(0), ('attr', 0, len(s.input), { 'name': (0, nlen), 'value': ('ustr', 5, len(s.input)) })) s = S.markup_scanner(s.input + '"') self.assertEqual(s.parse_attrib(0), ('attr', 0, len(s.input), { 'name': (0, nlen), 'value': ('str', 5, len(s.input)) })) # }} # {{ class test_parser class test_parser(unittest.TestCase): """Unit tests for markup_parser.""" def test_directive(self): """Test markup directives.""" s = S.markup_parser('<!DOCTYPE html public>') self.assertEqual(len(s), 2) self.assertEqual(s[0].type, 'dir') self.assertEqual(s[0].name, 'DOCTYPE') self.assertEqual(s[0].innersource, 'DOCTYPE html public') s = S.markup_parser('<?xml ... ?>') self.assertEqual(len(s), 2) self.assertEqual(s[0].type, 'dir') self.assertEqual(s[0].name, 'xml') self.assertEqual(s[0].innersource, 'xml ... ') for src in ('<!', '<?'): s = S.markup_parser(src + 'incomplete') self.assertEqual(len(s), 2) self.assertEqual(s[0].type, 'udir') self.assertEqual(s[0].name, 'incomplete') self.assertEqual(s[0].innersource, 'incomplete') s = S.markup_parser(src) self.assertEqual(len(s), 2) self.assertEqual(s[0].type, 'text') self.assertEqual(s[0].source, s.input) for src in ('<!>', '<??>'): s = S.markup_parser(src) self.assertEqual(len(s), 2) self.assertEqual(s[0].type, 'text') self.assertEqual(s[0].source, s.input) def test_tags(self): """Test tag formats.""" s = S.markup_parser('<open1><open2 bare name1=val name2="foo">') self.assertEqual(len(s), 3) self.assertTagShape(s[0], 'open', 'open1') self.assertTagShape(s[1], 'open', 'open2', bare='', name1='val', name2='foo') s = S.markup_parser("<self foo=bar baz='quux crunch' zot/></endtag>") self.assertEqual(len(s), 3) self.assertTagShape(s[0], 'self', 'self', foo='bar', baz='quux crunch', zot='') self.assertTagShape(s[1], 'close', 'endtag') def test_basic_nesting(self): """Test basic tag nesting rules.""" # test indices 0 1 2 3 4 5 6 7 8 9 10 s = S.markup_parser('<A> w <B> x <C> y <D></B></C> z </A>') self.assertChildOf(s[0], None) # <A> is at the top level self.assertChildOf(s[1], s[0]) # w is a child of <A> self.assertChildOf(s[2], s[0]) # <B> is a child of <A> self.assertChildOf(s[3], s[2]) # x is a child of <B> self.assertChildOf(s[4], s[0]) # <C> is a child of <A> self.assertChildOf(s[5], s[2]) # y is a child of <B> self.assertChildOf(s[6], s[2]) # <D> is a child of <B> self.assertChildOf(s[7], s[0]) # </B> is a child of </A> self.assertChildOf(s[8], s[0]) # </C> is a child of <A> self.assertChildOf(s[9], s[0]) # z is a child of <A> self.assertChildOf(s[10], None) # </A> is at the top level # Partnership tests self.assertPartners(s[0], s[10]) self.assertPartners(s[2], s[7]) self.assertPartners(s[4], s[8]) # Path tests # <A> ==> <B> ==> <D> self.assertEqual(s[6].path, [s[0], s[2], s[6]]) # <A> ==> <B> ==> y self.assertEqual(s[5].path, [s[0], s[2], s[5]]) # <A> ==> <C> self.assertEqual(s[4].path, [s[0], s[4]]) def test_custom_nesting(self): """Test some simple customized nesting rules.""" class TP(S.markup_parser): CLOSED_BY_CLOSE = {'c': set(('b', ))} CLOSED_BY_OPEN = {'c': set(('c', ))} # 0 1 2 3 4 5 6 7 8 9 10 11 s = TP('<A>aaa<B><C>c1<C>c2<C>c3</B>bbb</A>') self.assertPartners(s[0], s[11]) # <A> ~ </A> self.assertPartners(s[2], s[9]) # <B> ~ </B> self.assertPartner(s[3], s[5]) # <C> ~ <C> self.assertPartner(s[5], s[7]) # ditto self.assertPartner(s[7], s[9]) # ditto self.assertChildOf(s[1], s[0]) # A contains aaa self.assertChildOf(s[2], s[0]) # A contains B self.assertChildOf(s[3], s[2]) # B contains C's self.assertChildOf(s[5], s[2]) self.assertChildOf(s[7], s[2]) self.assertChildOf(s[4], s[3]) # C's contain their c's self.assertChildOf(s[6], s[5]) self.assertChildOf(s[8], s[7]) self.assertChildOf(s[10], s[0]) # A contains bbb def test_simple_queries(self): """Test simple .find() and .first() queries.""" s = S.markup_parser('<doc><!-- comment -->text<?dir?>' '<atag x=y><tag><self/>more&amp;</tag>') # Check that we don't find things we're not supposed to self.assertEqual(list(s.find(name='none')), []) self.assertRaises(KeyError, lambda: s.first(name='none')) self.assertRaises(KeyError, lambda: s.first(name='DOC', case_matters=True)) # Make sure we find the things we are supposed to self.assertEqual(s.first(type='com').source, '<!-- comment -->') self.assertEqual(s.last(name='tag').partner.source, '<tag>') self.assertEqual(list(t.source for t in s.find(type='text')), ['text', 'more&amp;']) self.assertEqual(s.first(value='more&').obj_id, 7) self.assertEqual(s.first(type='self').source, '<self/>') self.assertEqual(s.first(type='dir').source, '<?dir?>') # Check that attribute matching works self.assertRaises(KeyError, lambda: s.first(name='atag', attr=('x', False))) self.assertRaises(TypeError, lambda: s.first(attr=False)) self.assertEqual(s.first(name='atag').keys(), ['x']) self.assertEqual(s.first(attr=('x', True))['x'].value, 'y') def test_query_mapping(self): """Test mapping functions over query results.""" s = S.markup_parser('<a><b/>foobar<c></a></c>') self.assertEqual(s.first(type='text', map='source'), 'foobar') self.assertEqual(s.first(type='self', map='start'), 3) self.assertEqual(s.first(type='close', map=('name', 'obj_id')), ('a', 4)) self.assertEqual(list(s.find(map=len)), [3, 4, 6, 3, 4, 4, 0]) # includes eof marker self.assertEqual(list(s.find(map=lambda t: t.linepos[1])), [0, 3, 7, 13, 16, 20, 24]) #includes eof marker def test_query_candidates(self): """Test queries that stipulate a particular candidate set.""" # 0 1 2 3 4 s = S.markup_parser('<T>a span of text<U/>another span</T>') # If no candidate set is given, search the entire set. self.assertEqual(s.first(type='text').obj_id, 1) # Search on an object queries the contents of the object. self.assertEqual(s[0].first(type='text').obj_id, 1) # Search with an explicit range restricts the span. self.assertEqual(s.first(type='text', search_after=s[2]).obj_id, 3) # Multiple restrictions are allowed. self.assertEqual( s.first(search_after=s[1], search_before=s[3]).obj_id, 2) self.assertEqual( s.first(search_after=s[2], search_inside=s[0]).obj_id, 3) self.assertEqual(s[0].first(search_after=s[2], type='text').obj_id, 3) self.assertEqual(s[0].first(search_before=s[2], type='text').obj_id, 1) # Regression: Searching inside a text field doesn't search everything. self.assertRaises(KeyError, lambda: s.first(search_inside=s[1])) self.assertRaises(KeyError, lambda: s[1].first()) def test_line_numbers(self): """Test line numbering support.""" # Corner cases: Empty string, single line. self.assertEqual(S.markup_parser('').get_linecount(), 1) self.assertEqual(S.markup_parser('a').get_linecount(), 1) self.assertEqual(S.markup_parser('a\n').get_linecount(), 1) s = S.markup_parser('<line num=1>\nline 2\nline 3') self.assertEqual(s.get_linecount(), 3) self.assertEqual(s.get_line(1), '<line num=1>\n') self.assertEqual(s.get_line(2), 'line 2\n') self.assertEqual(s.get_line(3), 'line 3') self.assertRaises(IndexError, lambda: s.get_line(4)) t = s.first(type='text') self.assertEqual(t.source, '\nline 2\nline 3') self.assertEqual(t.linepos, (1, 12)) self.assertEqual(s.locate(t.start + 1), t) self.assertEqual(s.locate(len(s.input)).type, 'eof') t = s.locate(7) self.assertEqual(t.type, 'open') self.assertEqual(t.name, 'num') self.assertEqual(t.value, '1') def test_white_filter(self): """Test whitespace filtering.""" s = S.markup_parser(' <t0> <t1/> t2 <t3 num=3> ', skip_white_text=True) self.assertEqual(len(s), 5) self.assertTagShape(s[0], 'open', 't0') self.assertTagShape(s[1], 'self', 't1') self.assertObjectShape(s[2], 'text', source=' t2 ') self.assertTagShape(s[3], 'open', 't3', num='3') self.assertObjectShape(s[4], 'eof') def test_positions(self): """Test line number, character offset, and column number finding.""" s = S.markup_parser('<a>\n\t<b/>\t<c>d\n</c>\t</a>') s.LINE_NUM_BASE = 1 s.COLUMN_NUM_BASE = 0 s.TAB_WIDTH = 8 # Edge case: First line, first column. self.assertEqual(s[0].linepos, (1, 0)) self.assertEqual(s[0].linecol, (1, 0)) self.assertEqual(s[2].linepos, (2, 1)) self.assertEqual(s[2].linecol, (2, 8)) # Conversion of line/offset and line/column into input offsets. self.assertEqual(s.get_offset(1, 0), 0) # beginning self.assertEqual(s.get_offset(2, 9), 13) # at d self.assertEqual(s.get_offset(2, 0), 4) # start of <b> self.assertEqual(s.get_column_offset(1, 0), 0) # beginning self.assertEqual(s.get_column_offset(2, 19), 13) # at d self.assertEqual(s.get_column_offset(2, 8), 5) # start of <b> def test_entities(self): """Test entity substitution.""" s = S.markup_parser('a&lt;b&gt;c&quot;<x>' # 0 1 '--&testName;--<x>' # 2 3 '--&NoneSuch;--<x>' # 4 5 '&#32;&&&#9;') # 6 <eof> self.assertEqual(len(s), 8) # Check default entities self.assertObjectShape(s[0], 'text', value='a<b>c"') # Check custom entities s.ENTITY_NAME_MAP['testName'] = '[ok]' self.assertObjectShape(s[2], 'text', value='--[ok]--') self.assertObjectShape(s[4], 'text', value='--&NoneSuch;--') # Check numeric entities
""" lipydomics/stats.py <NAME> 2019/02/03 description: A set of functions for performing statistical analyses on the lipidomics data. Generally, these functions should produce one or more columns to associate with the data, as well as a label describing the analysis performed (what groupings are used, normalized or raw data, etc.). This data is added to the Dataset instance into a dictionary called stats, where the key is the label string and the value is a numpy.ndarray containing the desired statistic. WARNING: adding statistics with the same label as ones already added to the Dataset object will overwrite the existing data """ import numpy as np from scipy.stats import f_oneway, pearsonr, ttest_ind, mannwhitneyu from sklearn.decomposition import PCA from sklearn.cross_decomposition import PLSRegression import warnings def add_anova_p(dataset, group_names, normed=False): """ add_anova_p description: adds a column containing ANOVA p-values computed for user-specified groups The p-values (n_features,) are added to Dataset.stats with the label: 'ANOVA_{group_name1}-{group_name2}-{etc.}_{raw/normed}' parameters: dataset (lipydomics.data.Dataset) -- lipidomics dataset group_names (list(str)) -- groups to use to compute the ANOVA p-value [normed (bool)] -- Use normalized data (True) or raw (False) [optional, default=False] """ group_data = np.array([_ for _ in dataset.get_data_bygroup(group_names, normed=normed)]) anova_p = np.array([f_oneway(*feature)[1] for feature in zip(*group_data)]) if normed: normed = "normed" else: normed = "raw" label = "ANOVA_" + '-'.join(group_names) + "_" + normed # add the statistic into the Dataset dataset.stats[label] = anova_p def add_pca3(dataset, group_names, normed=False, random_state=69): """ add_pca3 description: Computes a 3-component PCA from all features in the Dataset (using either raw or normalized intensities) and adds the relevant information (feature loadings, projections) to the Dataset. The fitted PCA object is added as an instance variable (Dataset.pca3_). The feature loadings (3, n_features) and PCA projections (n_samples, 3) are added to Dataset.stats with the labels 'PCA3_{group1}-{group2}-{etc.}_loadings_{raw/normed}' and 'PCA3_{group1}-{group2}-{etc.}_projections_{raw/normed}', respectively. If the Dataset.pca3_ instance variable or either of the Dataset.stats entries are already present, then they will be overridden. parameters: dataset (lipydomics.data.Dataset) -- lipidomics dataset [normed (bool)] -- Use normalized data (True) or raw (False) [optional, default=False] [random_state (int)] -- pRNG seed for deterministic results [optional, default=69] """ # initialize the PCA object, add it to the Dataset dataset.pca3_ = PCA(n_components=3, random_state=random_state) # fit the PCA to the data if normed: nrm = 'normed' else: nrm = 'raw' # get the group data, reshape and concatenate -> X X = np.concatenate([_.T for _ in dataset.get_data_bygroup(group_names, normed=normed)]) dataset.pca3_.fit(X) # add the statistics into the Dataset dataset.stats['PCA3_{}_loadings_{}'.format('-'.join(group_names), nrm)] = dataset.pca3_.components_ dataset.stats['PCA3_{}_projections_{}'.format('-'.join(group_names), nrm)] = dataset.pca3_.transform(X) def add_plsda(dataset, group_names, normed=False, scaled=False): """ add_plsda description: Performs PLS-DA using two specified groups (e.g. groups A and B). Uses the PLSRegression class from sklearn with the target variable being simply 1 for group A or -1 for group B which effectively converts the task from regression to calssification. The fitted PLSRegression object is stored in an instance variable (Dataset.plsda_). The feature loadings (n_features, 2) and projections (n_samples, 2) are added to Dataset.stats with the labels 'PLS-DA_A-B_loadings_{raw/normed}' and 'PLS-DA_A-B_projections_{raw/normed}', respectively. ! the projections and loadings are checked before the statistics are added to the Dataset to ensure that their direction is consistent with the order of the two groups provided, i.e. if groups 'A' and 'B' were provided in that order, then the X projections should be negative for 'A' and positive for 'B', consistent with the direction of the corresponding correlation coefficients. This is to ensure that S-plots that are generated from the two analyses are consistent and interpretable. If this condition is not met, the X component of the projections and loadings are simply flipped ! If the Dataset.plsda_ instance variable or either of the Dataset.stats entries are already present, then they will be overridden. parameters: dataset (lipydomics.data.Dataset) -- lipidomics dataset group_names (list(str)) -- groups to use to compute the PLS-DA, only 2 groups allowed [normed (bool)] -- Use normalized data (True) or raw (False) [optional, default=False] [scaled (bool)] -- whether to let the PLSRegression scale the X data [optional, default=False] """ if len(group_names) != 2: m = 'add_plsda: 2 group names must be specified for PLS-DA, {} group names specified' raise ValueError(m.format(len(group_names))) # get the group data, reshape and concatenate -> X X = np.concatenate([_.T for _ in dataset.get_data_bygroup(group_names, normed=normed)]) # target variable is just 1 for group A and -1 for group B n_A = len(dataset.group_indices[group_names[0]]) n_B = len(dataset.group_indices[group_names[1]]) y = np.array([-1 for _ in range(n_A)] + [1 for _ in range(n_B)]) # initialize the PLSRegression object, add to the Dataset, fit the group data dataset.plsda_ = PLSRegression(scale=scaled) dataset.plsda_.fit(X, y) if normed: nrm = 'normed' else: nrm = 'raw' loadings = dataset.plsda_.x_loadings_ projections = dataset.plsda_.transform(X) # check to see if the X dimension needs to be flipped ordered = True for y_, x_ in zip(y, projections.T[0]): if (y_ < 0 and x_ > 0) or (y_ > 0 and x_ < 0): ordered = False if not ordered: # flip the direction of the X projections and loadings projections *= [-1, 1] loadings *= [-1, 1] # add the statistics into the Dataset dataset.stats['PLS-DA_{}_loadings_{}'.format('-'.join(group_names), nrm)] = loadings dataset.stats['PLS-DA_{}_projections_{}'.format('-'.join(group_names), nrm)] = projections def add_2group_corr(dataset, group_names, normed=False): """ add_2group_corr description: Computes Pearson correlation coefficient between two specified groups (e.g. groups A and B) for all features. The Pearson correlation coefficients (n_features,) are added to Dataset.stats with the label '2-group-corr_A-B_{raw/normed}'. These correlation coefficients can be combined with the loadings from a PLS-DA computed on the same groups in order to generate the familiar S-plot. * To use these data with the loadings from PLS-DA, the same group names must be specified in the same order * If the Dataset.stats entry is already present, then it will be overridden. parameters: dataset (lipydomics.data.Dataset) -- lipidomics dataset group_names (list(str)) -- groups to use to compute the PLS-DA, only 2 groups allowed [normed (bool)] -- Use normalized data (True) or raw (False) [optional, default=False] """ if len(group_names) != 2: m = 'add_2group_corr: 2 group names must be specified for correlation, {} group names specified' raise ValueError(m.format(len(group_names))) # get the group data, reshape and concatenate -> X Y = np.concatenate([_.T for _ in dataset.get_data_bygroup(group_names, normed=normed)]).T # target variable is just 1 for group A and -1 for group B n_A = len(dataset.group_indices[group_names[0]]) n_B = len(dataset.group_indices[group_names[1]]) # set so that the direction is the same as in PLS-DA x = np.array([-1 for _ in range(n_A)] + [1 for _ in range(n_B)]) # compute correlation coefficients for each feature corr = [] for y in Y: c = 0. for _ in y: # if x is all 0s then dont bother computing the correlation coefficient, it just causes a warning if _ > 0: c = pearsonr(x, y)[0] break corr.append(c) # convert corr to a numpy array corr = np.array(corr) if normed: nrm = 'normed' else: nrm = 'raw' # add the statistic into the Dataset dataset.stats['2-group-corr_{}_{}'.format('-'.join(group_names), nrm)] = corr def add_plsra(dataset, group_names, y, normed=False, scaled=False): """ add_plsra description: Performs PLS-RA using the specified groups and a target external continuous variable. Uses the PLSRegression class from sklearn with the target variable being an external continuous variable. The fitted PLSRegression object is stored in an instance variable (Dataset.plsra_). The feature loadings (n_features, 2) and projections (n_samples, 2) are added to Dataset.stats with the labels 'PLS-RA_A-B_loadings_{raw/normed}' and 'PLS-RA_A-B_projections_{raw/normed}', respectively. If the Dataset.plsra_ instance variable or either of the Dataset.stats entries are already present, then they will be overridden. parameters: dataset (lipydomics.data.Dataset) -- lipidomics dataset group_names (list(str)) -- groups to use to compute the PLS-RA y (numpy.array(float)) -- external continuous variable, shape = (n_samples,) [normed (bool)] -- Use normalized data (True) or raw (False) [optional, default=False] [scaled (bool)] -- whether to let the PLSRegression scale the X data [optional, default=False] """ # get the group data, reshape and concatenate -> X X = np.concatenate([_.T for _ in dataset.get_data_bygroup(group_names, normed=normed)]) # make sure y has the proper shape for the selected groups
pool to be deleted. The parameter must be an identifier for the resource type: ``ResourcePool``. :raise: :class:`com.vmware.vapi.std.errors_client.Error` If the system reports an error while responding to the request. :raise: :class:`com.vmware.vapi.std.errors_client.NotFound` If the resource pool is not found. :raise: :class:`com.vmware.vapi.std.errors_client.ServiceUnavailable` If the system is unable to communicate with a service to complete the request. :raise: :class:`com.vmware.vapi.std.errors_client.Unauthenticated` If the user can not be authenticated. :raise: :class:`com.vmware.vapi.std.errors_client.Unauthorized` If the user doesn't have the required privileges. :raise: :class:`com.vmware.vapi.std.errors_client.Unsupported` If the resource pool is a root resource pool. """ return self._invoke('delete', { 'resource_pool': resource_pool, }) def update(self, resource_pool, spec, ): """ Updates the configuration of a resource pool. This method was added in vSphere API 7.0.0. :type resource_pool: :class:`str` :param resource_pool: Identifier of the resource pool. The parameter must be an identifier for the resource type: ``ResourcePool``. :type spec: :class:`ResourcePool.UpdateSpec` :param spec: Specification for updating the configuration of the resource pool. :raise: :class:`com.vmware.vapi.std.errors_client.Error` If the system reports an error while responding to the request. :raise: :class:`com.vmware.vapi.std.errors_client.InvalidArgument` If any of the specified parameters is invalid. :raise: :class:`com.vmware.vapi.std.errors_client.NotFound` If the resource pool is not found. :raise: :class:`com.vmware.vapi.std.errors_client.ServiceUnavailable` If the system is unable to communicate with a service to complete the request. :raise: :class:`com.vmware.vapi.std.errors_client.UnableToAllocateResource` If any of the resources needed to reconfigure the resource pool could not be allocated. :raise: :class:`com.vmware.vapi.std.errors_client.Unauthenticated` If the user can not be authenticated. :raise: :class:`com.vmware.vapi.std.errors_client.Unauthorized` If the user doesn't have the required privileges. :raise: :class:`com.vmware.vapi.std.errors_client.Unauthorized` if you do not have all of the privileges described as follows: * The resource ``ResourcePool`` referenced by the parameter ``resource_pool`` requires ``Resource.EditPool``. """ return self._invoke('update', { 'resource_pool': resource_pool, 'spec': spec, }) class VM(VapiInterface): """ The ``VM`` class provides methods for managing the lifecycle of a virtual machine. """ RESOURCE_TYPE = "VirtualMachine" """ Resource type for virtual machines. """ _VAPI_SERVICE_ID = 'com.vmware.vcenter.VM' """ Identifier of the service in canonical form. """ def __init__(self, config): """ :type config: :class:`vmware.vapi.bindings.stub.StubConfiguration` :param config: Configuration to be used for creating the stub. """ VapiInterface.__init__(self, config, _VMStub) self._VAPI_OPERATION_IDS = {} self._VAPI_OPERATION_IDS.update({'clone_task': 'clone$task'}) self._VAPI_OPERATION_IDS.update({'relocate_task': 'relocate$task'}) class InventoryPlacementSpec(VapiStruct): """ The ``VM.InventoryPlacementSpec`` class contains information used to place a virtual machine in the vCenter inventory. .. tip:: The arguments are used to initialize data attributes with the same names. """ def __init__(self, folder=None, ): """ :type folder: :class:`str` or ``None`` :param folder: Virtual machine folder into which the virtual machine should be placed. When clients pass a value of this class as a parameter, the attribute must be an identifier for the resource type: ``Folder``. When methods return a value of this class as a return value, the attribute will be an identifier for the resource type: ``Folder``. This attribute is currently required. In the future, if this attribute is None, the system will attempt to choose a suitable folder for the virtual machine; if a folder cannot be chosen, the virtual machine creation operation will fail. """ self.folder = folder VapiStruct.__init__(self) InventoryPlacementSpec._set_binding_type(type.StructType( 'com.vmware.vcenter.VM.inventory_placement_spec', { 'folder': type.OptionalType(type.IdType()), }, InventoryPlacementSpec, False, None)) class ComputePlacementSpec(VapiStruct): """ The ``VM.ComputePlacementSpec`` class contains information used to place a virtual machine on compute resources. .. tip:: The arguments are used to initialize data attributes with the same names. """ def __init__(self, resource_pool=None, host=None, cluster=None, ): """ :type resource_pool: :class:`str` or ``None`` :param resource_pool: Resource pool into which the virtual machine should be placed. When clients pass a value of this class as a parameter, the attribute must be an identifier for the resource type: ``ResourcePool``. When methods return a value of this class as a return value, the attribute will be an identifier for the resource type: ``ResourcePool``. This attribute is currently required if both ``host`` and ``cluster`` are None. In the future, if this attribute is None, the system will attempt to choose a suitable resource pool for the virtual machine; if a resource pool cannot be chosen, the virtual machine creation operation will fail. :type host: :class:`str` or ``None`` :param host: Host onto which the virtual machine should be placed. If ``host`` and ``resourcePool`` are both specified, ``resourcePool`` must belong to ``host``. If ``host`` and ``cluster`` are both specified, ``host`` must be a member of ``cluster``. When clients pass a value of this class as a parameter, the attribute must be an identifier for the resource type: ``HostSystem``. When methods return a value of this class as a return value, the attribute will be an identifier for the resource type: ``HostSystem``. This attribute may be None if ``resourcePool`` or ``cluster`` is specified. If None, the system will attempt to choose a suitable host for the virtual machine; if a host cannot be chosen, the virtual machine creation operation will fail. :type cluster: :class:`str` or ``None`` :param cluster: Cluster into which the virtual machine should be placed. If ``cluster`` and ``resourcePool`` are both specified, ``resourcePool`` must belong to ``cluster``. If ``cluster`` and ``host`` are both specified, ``host`` must be a member of ``cluster``. When clients pass a value of this class as a parameter, the attribute must be an identifier for the resource type: ``ClusterComputeResource``. When methods return a value of this class as a return value, the attribute will be an identifier for the resource type: ``ClusterComputeResource``. If ``resourcePool`` or ``host`` is specified, it is recommended that this attribute be None. """ self.resource_pool = resource_pool self.host = host self.cluster = cluster VapiStruct.__init__(self) ComputePlacementSpec._set_binding_type(type.StructType( 'com.vmware.vcenter.VM.compute_placement_spec', { 'resource_pool': type.OptionalType(type.IdType()), 'host': type.OptionalType(type.IdType()), 'cluster': type.OptionalType(type.IdType()), }, ComputePlacementSpec, False, None)) class StoragePlacementSpec(VapiStruct): """ The ``VM.StoragePlacementSpec`` class contains information used to store a virtual machine's files. .. tip:: The arguments are used to initialize data attributes with the same names. """ def __init__(self, datastore=None, ): """ :type datastore: :class:`str` or ``None`` :param datastore: Datastore on which the virtual machine's configuration state should be stored. This datastore will also be used for any virtual disks that are created as part of the virtual machine creation operation. When clients pass a value of this class as a parameter, the attribute must be an identifier for the resource type: ``Datastore``. When methods return a value of this class as a return value, the attribute will be an identifier for the resource type: ``Datastore``. This attribute is currently required. In the future, if this attribute is None, the system will attempt to choose suitable storage for the virtual machine; if storage cannot be chosen, the virtual machine creation operation will fail. """ self.datastore = datastore VapiStruct.__init__(self) StoragePlacementSpec._set_binding_type(type.StructType( 'com.vmware.vcenter.VM.storage_placement_spec', { 'datastore': type.OptionalType(type.IdType()), }, StoragePlacementSpec, False, None)) class PlacementSpec(VapiStruct): """ The ``VM.PlacementSpec`` class contains information used to place a virtual machine onto resources within the vCenter inventory. .. tip:: The arguments are used to initialize data attributes with the same names. """ def __init__(self, folder=None, resource_pool=None, host=None, cluster=None, datastore=None, ): """ :type folder: :class:`str` or ``None`` :param folder: Virtual machine folder into which the virtual machine should be placed. When clients pass a value of this class as a parameter, the attribute must be an identifier for the resource type: ``Folder``. When methods return a value of this class as a return value, the attribute will be an identifier for the resource type: ``Folder``. This attribute is currently required. In the future, if this attribute is None, the system will attempt to choose a suitable folder for the virtual machine; if a folder cannot be chosen, the virtual machine creation operation will fail. :type resource_pool: :class:`str` or ``None`` :param resource_pool: Resource pool into which the virtual machine should be placed. When clients pass a value of this class as a parameter, the attribute must be an identifier for the resource type: ``ResourcePool``. When methods return a value of this class as a return value, the attribute will be an identifier
"http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897419630.htm", "short": "Prefetch Memory (immediate)", }, { "instr": "PRFM", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897420050.htm", "short": "Prefetch Memory (literal)", }, { "instr": "PRFM", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897420470.htm", "short": "Prefetch Memory (register)", }, ], "PRFUM": [ { "instr": "PRFUM", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897421040.htm", "short": "Prefetch Memory (unscaled offset)", } ], "PSB": [ { "instr": "PSB", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_eeb1476202746582.htm", "short": "Profiling Synchronization Barrier", } ], "RADDHN": [ { "instr": "RADDHN", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897544908.htm", "short": "Rounding Add returning High Narrow", } ], "RADDHN2": [ { "instr": "RADDHN2", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897544908.htm", "short": "Rounding Add returning High Narrow", } ], "RBIT": [ { "instr": "RBIT", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897690295.htm", "short": "Reverse Bits", }, { "instr": "RBIT", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897545478.htm", "short": "Reverse Bit order (vector)", }, ], "RET": [ { "instr": "RET", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897690725.htm", "short": "Return from subroutine", } ], "RETAA": [ { "instr": "RETAA", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_osg1476202748462.htm", "short": "Return from subroutine, with pointer authentication", } ], "RETAB": [ { "instr": "RETAB", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_osg1476202748462.htm", "short": "Return from subroutine, with pointer authentication", } ], "REV": [ { "instr": "REV", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897691975.htm", "short": "Reverse Bytes", } ], "REV16": [ { "instr": "REV16", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897691135.htm", "short": "Reverse bytes in 16-bit halfwords", }, { "instr": "REV16", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897546018.htm", "short": "Reverse elements in 16-bit halfwords (vector)", }, ], "REV32": [ { "instr": "REV32", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897691555.htm", "short": "Reverse bytes in 32-bit words", }, { "instr": "REV32", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897546518.htm", "short": "Reverse elements in 32-bit words (vector)", }, ], "REV64": [ { "instr": "REV64", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_lyc1476202750282.htm", "short": "Reverse Bytes", }, { "instr": "REV64", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897547018.htm", "short": "Reverse elements in 64-bit doublewords (vector)", }, ], "ROR": [ { "instr": "ROR", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897695545.htm", "short": "Rotate right (immediate)", }, { "instr": "ROR", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897695925.htm", "short": "Rotate Right (register)", }, ], "RORV": [ { "instr": "RORV", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897696405.htm", "short": "Rotate Right Variable", } ], "RSHRN": [ { "instr": "RSHRN", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897547428.htm", "short": "Rounding Shift Right Narrow (immediate)", } ], "RSHRN2": [ { "instr": "RSHRN2", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897547428.htm", "short": "Rounding Shift Right Narrow (immediate)", } ], "RSUBHN": [ { "instr": "RSUBHN", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897547868.htm", "short": "Rounding Subtract returning High Narrow", } ], "RSUBHN2": [ { "instr": "RSUBHN2", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897547868.htm", "short": "Rounding Subtract returning High Narrow", } ], "SABA": [ { "instr": "SABA", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897548348.htm", "short": "Signed Absolute difference and Accumulate", } ], "SABAL": [ { "instr": "SABAL", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897548828.htm", "short": "Signed Absolute difference and Accumulate Long", } ], "SABAL2": [ { "instr": "SABAL2", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897548828.htm", "short": "Signed Absolute difference and Accumulate Long", } ], "SABD": [ { "instr": "SABD", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897549328.htm", "short": "Signed Absolute Difference", } ], "SABDL": [ { "instr": "SABDL", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897549818.htm", "short": "Signed Absolute Difference Long", } ], "SABDL2": [ { "instr": "SABDL2", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897549818.htm", "short": "Signed Absolute Difference Long", } ], "SADALP": [ { "instr": "SADALP", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897550298.htm", "short": "Signed Add and Accumulate Long Pairwise", } ], "SADDL": [ { "instr": "SADDL", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897550868.htm", "short": "Signed Add Long (vector)", } ], "SADDL2": [ { "instr": "SADDL2", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897550868.htm", "short": "Signed Add Long (vector)", } ], "SADDLP": [ { "instr": "SADDLP", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897551398.htm", "short": "Signed Add Long Pairwise", } ], "SADDLV": [ { "instr": "SADDLV", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897551988.htm", "short": "Signed Add Long across Vector", } ], "SADDW": [ { "instr": "SADDW", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897552518.htm", "short": "Signed Add Wide", } ], "SADDW2": [ { "instr": "SADDW2", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897552518.htm", "short": "Signed Add Wide", } ], "SBC": [ { "instr": "SBC", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897696825.htm", "short": "Subtract with Carry", } ], "SBCS": [ { "instr": "SBCS", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897701701.htm", "short": "Subtract with Carry, setting flags", } ], "SBFIZ": [ { "instr": "SBFIZ", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897703689.htm", "short": "Signed Bitfield Insert in Zero", } ], "SBFM": [ { "instr": "SBFM", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897704099.htm", "short": "Signed Bitfield Move", } ], "SBFX": [ { "instr": "SBFX", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897704549.htm", "short": "Signed Bitfield Extract", } ], "SCVTF": [ { "instr": "SCVTF", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897636223.htm", "short": "Signed fixed-point Convert to Floating-point (scalar)", }, { "instr": "SCVTF", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897636663.htm", "short": "Signed integer Convert to Floating-point (scalar)", }, { "instr": "SCVTF", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897462833.htm", "short": "Signed fixed-point Convert to Floating-point (vector)", }, { "instr": "SCVTF", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897463243.htm", "short": "Signed integer Convert to Floating-point (vector)", }, { "instr": "SCVTF", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897553058.htm", "short": "Signed fixed-point Convert to Floating-point (vector)", }, { "instr": "SCVTF", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897553558.htm", "short": "Signed integer Convert to Floating-point (vector)", }, ], "SDIV": [ { "instr": "SDIV", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897704989.htm", "short": "Signed Divide", } ], "SEV": [ { "instr": "SEV", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_fdo1476202758732.htm", "short": "Send Event", } ], "SEVL": [ { "instr": "SEVL", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_ios1476202759102.htm", "short": "Send Event Local", } ], "SHADD": [ { "instr": "SHADD", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897554008.htm", "short": "Signed Halving Add", } ], "SHL": [ { "instr": "SHL", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897463603.htm", "short": "Shift Left (immediate)", }, { "instr": "SHL", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897554428.htm", "short": "Shift Left (immediate)", }, ], "SHLL": [ { "instr": "SHLL", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897554959.htm", "short": "Shift Left Long (by element size)", } ], "SHLL2": [ { "instr": "SHLL2", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897554959.htm", "short": "Shift Left Long (by element size)", } ], "SHRN": [ { "instr": "SHRN", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897555479.htm", "short": "Shift Right Narrow (immediate)", } ], "SHRN2": [ { "instr": "SHRN2", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897555479.htm", "short": "Shift Right Narrow (immediate)", } ], "SHSUB": [ { "instr": "SHSUB", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897555959.htm", "short": "Signed Halving Subtract", } ], "SLI": [ { "instr": "SLI", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897463983.htm", "short": "Shift Left and Insert (immediate)", }, { "instr": "SLI", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897556429.htm", "short": "Shift Left and Insert (immediate)", }, ], "SMADDL": [ { "instr": "SMADDL", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897706779.htm", "short": "Signed Multiply-Add Long", } ], "SMAX": [ { "instr": "SMAX", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897556919.htm", "short": "Signed Maximum (vector)", } ], "SMAXP": [ { "instr": "SMAXP", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897557419.htm", "short": "Signed Maximum Pairwise", } ], "SMAXV": [ { "instr": "SMAXV", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897557909.htm", "short": "Signed Maximum across Vector", } ], "SMC": [ { "instr": "SMC", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897707179.htm", "short": "Supervisor call to allow OS or Hypervisor code to call the Secure Monitor", } ], "SMIN": [ { "instr": "SMIN", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897558439.htm", "short": "Signed Minimum (vector)", } ], "SMINP": [ { "instr": "SMINP", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897558939.htm", "short": "Signed Minimum Pairwise", } ], "SMINV": [ { "instr": "SMINV", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897559509.htm", "short": "Signed Minimum across Vector", } ], "SMLAL": [ { "instr": "SMLAL", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897560049.htm", "short": "Signed Multiply-Add Long (vector, by element)", }, { "instr": "SMLAL", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897560629.htm", "short": "Signed Multiply-Add Long (vector)", }, ], "SMLAL2": [ { "instr": "SMLAL2", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897560049.htm", "short": "Signed Multiply-Add Long (vector, by element)", }, { "instr": "SMLAL2", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897560629.htm", "short": "Signed Multiply-Add Long (vector)", }, ], "SMLSL": [ { "instr": "SMLSL", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897561089.htm", "short": "Signed Multiply-Subtract Long (vector, by element)", }, { "instr": "SMLSL", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897561559.htm", "short": "Signed Multiply-Subtract Long (vector)", }, ], "SMLSL2": [ { "instr": "SMLSL2", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897561089.htm", "short": "Signed Multiply-Subtract Long (vector, by element)", }, { "instr": "SMLSL2", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897561559.htm", "short": "Signed Multiply-Subtract Long (vector)", }, ], "SMNEGL": [ { "instr": "SMNEGL", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897707739.htm", "short": "Signed Multiply-Negate Long", } ], "SMOV": [ { "instr": "SMOV", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897562019.htm", "short": "Signed Move vector element to general-purpose register", } ], "SMSUBL": [ { "instr": "SMSUBL", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897708159.htm", "short": "Signed Multiply-Subtract Long", } ], "SMULH": [ { "instr": "SMULH", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897708539.htm", "short": "Signed Multiply High", } ], "SMULL": [ { "instr": "SMULL", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897708949.htm", "short": "Signed Multiply Long", }, { "instr": "SMULL", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897562449.htm", "short": "Signed Multiply Long (vector, by element)", }, { "instr": "SMULL", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897562919.htm", "short": "Signed Multiply Long (vector)", }, ], "SMULL2": [ { "instr": "SMULL2", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897562449.htm", "short": "Signed Multiply Long (vector, by element)", }, { "instr": "SMULL2", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897562919.htm", "short": "Signed Multiply Long (vector)", }, ], "SQABS": [ { "instr": "SQABS", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897464403.htm", "short": "Signed saturating Absolute value", }, { "instr": "SQABS", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897563339.htm", "short": "Signed saturating Absolute value", }, ], "SQADD": [ { "instr": "SQADD", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897464823.htm", "short": "Signed saturating Add", }, { "instr": "SQADD", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897563729.htm", "short": "Signed saturating Add", }, ], "SQDMLAL": [ { "instr": "SQDMLAL", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897465243.htm", "short": "Signed saturating Doubling Multiply-Add Long (by element)", }, { "instr": "SQDMLAL", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897465673.htm", "short": "Signed saturating Doubling Multiply-Add Long", }, { "instr": "SQDMLAL", "link": "http://www.keil.com/support/man/docs/armclang_asm/armclang_asm_pge1427897564119.htm", "short": "Signed saturating Doubling
dict2.get(key, default2)) for key in keys3} return dict3 def dict_accum(*dict_list): accumulator = defaultdict(list) for dict_ in dict_list: for key, val in dict_.items(): accumulator[key].append(val) return accumulator dict_isect = dict_intersection def dict_filter_nones(dict_): r""" Removes None values Args: dict_ (dict): a dictionary Returns: dict: CommandLine: python -m utool.util_dict --exec-dict_filter_nones Example: >>> # DISABLE_DOCTEST >>> # UNSTABLE_DOCTEST >>> # fails on python 3 because of dict None order >>> from utool.util_dict import * # NOQA >>> import utool as ut >>> dict_ = {1: None, 2: 'blue', 3: 'four', None: 'fun'} >>> dict2_ = dict_filter_nones(dict_) >>> result = ut.repr4(dict2_, nl=False) >>> print(result) {None: 'fun', 2: 'blue', 3: 'four'} """ dict2_ = { key: val for key, val in six.iteritems(dict_) if val is not None } return dict2_ def groupby_tags(item_list, tags_list): r""" case where an item can belong to multiple groups Args: item_list (list): tags_list (list): Returns: dict: groupid_to_items CommandLine: python -m utool.util_dict --test-groupby_tags Example: >>> # ENABLE_DOCTEST >>> from utool.util_dict import * # NOQA >>> import utool as ut >>> tagged_item_list = { >>> 'spam': ['meat', 'protein', 'food'], >>> 'eggs': ['protein', 'food'], >>> 'cheese': ['dairy', 'protein', 'food'], >>> 'jam': ['fruit', 'food'], >>> 'banana': ['weapon', 'fruit', 'food'], >>> } >>> item_list = list(tagged_item_list.keys()) >>> tags_list = list(tagged_item_list.values()) >>> groupid_to_items = groupby_tags(item_list, tags_list) >>> groupid_to_items = ut.map_vals(sorted, groupid_to_items) >>> result = ('groupid_to_items = %s' % (ut.repr4(groupid_to_items),)) >>> print(result) groupid_to_items = { 'dairy': ['cheese'], 'food': ['banana', 'cheese', 'eggs', 'jam', 'spam'], 'fruit': ['banana', 'jam'], 'meat': ['spam'], 'protein': ['cheese', 'eggs', 'spam'], 'weapon': ['banana'], } """ groupid_to_items = defaultdict(list) for tags, item in zip(tags_list, item_list): for tag in tags: groupid_to_items[tag].append(item) return groupid_to_items def groupby_attr(item_list, attrname): return group_items(item_list, map(op.attrgetter(attrname), item_list)) def group_pairs(pair_list): """ Groups a list of items using the first element in each pair as the item and the second element as the groupid. Args: pair_list (list): list of 2-tuples (item, groupid) Returns: dict: groupid_to_items: maps a groupid to a list of items SeeAlso: group_items """ # Initialize dict of lists groupid_to_items = defaultdict(list) # Insert each item into the correct group for item, groupid in pair_list: groupid_to_items[groupid].append(item) return groupid_to_items def group_items(items, by=None, sorted_=True): """ Groups a list of items by group id. Args: items (list): a list of the values to be grouped. if `by` is None, then each item is assumed to be a (groupid, value) pair. by (list): a corresponding list to group items by. if specified, these are used as the keys to group values in `items` sorted_ (bool): if True preserves the ordering of items within groups (default = True) FIXME. the opposite is true Returns: dict: groupid_to_items: maps a groupid to a list of items SeeAlso: group_indices - first part of a a more fine grained grouping algorithm apply_gropuing - second part of a more fine grained grouping algorithm CommandLine: python -m utool.util_dict --test-group_items Example: >>> # ENABLE_DOCTEST >>> from utool.util_dict import * # NOQA >>> import utool as ut >>> items = ['ham', 'jam', 'spam', 'eggs', 'cheese', 'bannana'] >>> by = ['protein', 'fruit', 'protein', 'protein', 'dairy', 'fruit'] >>> groupid_to_items = ut.group_items(items, iter(by)) >>> result = ut.repr2(groupid_to_items) >>> print(result) {'dairy': ['cheese'], 'fruit': ['jam', 'bannana'], 'protein': ['ham', 'spam', 'eggs']} """ if by is not None: pairs = list(zip(by, items)) if sorted_: # Sort by groupid for cache efficiency (does this even do anything?) # I forgot why this is needed? Determenism? try: pairs = sorted(pairs, key=op.itemgetter(0)) except TypeError: # Python 3 does not allow sorting mixed types pairs = sorted(pairs, key=lambda tup: str(tup[0])) else: pairs = items # Initialize a dict of lists groupid_to_items = defaultdict(list) # Insert each item into the correct group for groupid, item in pairs: groupid_to_items[groupid].append(item) return groupid_to_items def hierarchical_group_items(item_list, groupids_list): """ Generalization of group_item. Convert a flast list of ids into a heirarchical dictionary. TODO: move to util_dict Reference: http://stackoverflow.com/questions/10193235/python-translate-a-table-to-a-hierarchical-dictionary Args: item_list (list): groupids_list (list): CommandLine: python -m utool.util_dict --exec-hierarchical_group_items Example: >>> # ENABLE_DOCTEST >>> from utool.util_dict import * # NOQA >>> import utool as ut >>> item_list = [1, 2, 3, 4] >>> groupids_list = [[1, 1, 2, 2]] >>> tree = hierarchical_group_items(item_list, groupids_list) >>> result = ('tree = ' + ut.repr4(tree, nl=len(groupids_list) - 1)) >>> print(result) tree = {1: [1, 2], 2: [3, 4]} Example: >>> # ENABLE_DOCTEST >>> from utool.util_dict import * # NOQA >>> import utool as ut >>> item_list = [1, 2, 3, 4, 5, 6, 7, 8] >>> groupids_list = [[1, 2, 1, 2, 1, 2, 1, 2], [3, 2, 2, 2, 3, 1, 1, 1]] >>> tree = hierarchical_group_items(item_list, groupids_list) >>> result = ('tree = ' + ut.repr4(tree, nl=len(groupids_list) - 1)) >>> print(result) tree = { 1: {1: [7], 2: [3], 3: [1, 5]}, 2: {1: [6, 8], 2: [2, 4]}, } Example: >>> # ENABLE_DOCTEST >>> from utool.util_dict import * # NOQA >>> import utool as ut >>> item_list = [1, 2, 3, 4] >>> groupids_list = [[1, 1, 1, 2], [1, 2, 2, 2], [1, 3, 1, 1]] >>> tree = hierarchical_group_items(item_list, groupids_list) >>> result = ('tree = ' + ut.repr4(tree, nl=len(groupids_list) - 1)) >>> print(result) tree = { 1: { 1: {1: [1]}, 2: {1: [3], 3: [2]}, }, 2: { 2: {1: [4]}, }, } """ # Construct a defaultdict type with the appropriate number of levels num_groups = len(groupids_list) leaf_type = partial(defaultdict, list) if num_groups > 1: node_type = leaf_type for _ in range(len(groupids_list) - 2): node_type = partial(defaultdict, node_type) root_type = node_type elif num_groups == 1: root_type = list else: raise ValueError('must suply groupids') tree = defaultdict(root_type) # groupid_tuple_list = list(zip(*groupids_list)) for groupid_tuple, item in zip(groupid_tuple_list, item_list): node = tree for groupid in groupid_tuple: node = node[groupid] node.append(item) return tree def iflatten_dict_values(node, depth=0): """ >>> from utool.util_dict import * # NOQA """ if isinstance(node, dict): _iter = (iflatten_dict_values(value) for value in six.itervalues(node)) return util_iter.iflatten(_iter) else: return node #def iflatten_dict_items(node, depth=0): # if isinstance(node, dict): # six.iteritems(node) # _iter = ((key, iflatten_dict_items(value)) for key, value in six.iteritems(node)) # return util_iter.iflatten(_iter) # else: # return node #def iflatten_dict_keys(node, depth=0): # if isinstance(node, dict): # _iter = (iflatten_dict_keys(value) for key, value in six.iteritems(node)) # return util_iter.iflatten(_iter) # else: # return node def hierarchical_map_vals(func, node, max_depth=None, depth=0): """ node is a dict tree like structure with leaves of type list TODO: move to util_dict CommandLine: python -m utool.util_dict --exec-hierarchical_map_vals Example: >>> # ENABLE_DOCTEST >>> from utool.util_dict import * # NOQA >>> import utool as ut >>> item_list = [1, 2, 3, 4, 5, 6, 7, 8] >>> groupids_list = [[1, 2, 1, 2, 1, 2, 1, 2], [3, 2, 2, 2, 3, 1, 1, 1]] >>> tree = ut.hierarchical_group_items(item_list, groupids_list) >>> len_tree = ut.hierarchical_map_vals(len, tree) >>> result = ('len_tree = ' + ut.repr4(len_tree, nl=1)) >>> print(result) len_tree = { 1: {1: 1, 2: 1, 3: 2}, 2: {1: 2, 2: 2}, } Example1: >>> # DISABLE_DOCTEST >>> # UNSTABLE_DOCTEST >>> from utool.util_dict import * # NOQA >>> import utool as ut >>> depth = 4 >>> item_list = list(range(2 ** (depth + 1))) >>> num = len(item_list) // 2 >>> groupids_list = [] >>> total = 0 >>> for level in range(depth): ... num2 = len(item_list) // int((num * 2)) ... #nonflat_levelids = [([total + 2 * x + 1] * num + [total + 2 * x + 2] * num) for x in range(num2)] ... nonflat_levelids = [([1] * num + [2] * num) for x in range(num2)] ... levelids = ut.flatten(nonflat_levelids) ... groupids_list.append(levelids) ... total += num2 * 2 ... num //= 2 >>> print('groupids_list = %s' % (ut.repr4(groupids_list, nl=1),)) >>> print('depth = %r' % (len(groupids_list),)) >>> tree = ut.hierarchical_group_items(item_list, groupids_list) >>> print('tree = ' + ut.repr4(tree, nl=None)) >>> flat_tree_values = list(ut.iflatten_dict_values(tree)) >>> assert sorted(flat_tree_values) == sorted(item_list) >>> print('flat_tree_values = ' + str(flat_tree_values)) >>> #print('flat_tree_keys = ' + str(list(ut.iflatten_dict_keys(tree)))) >>> #print('iflatten_dict_items = ' + str(list(ut.iflatten_dict_items(tree)))) >>> len_tree = ut.hierarchical_map_vals(len, tree, max_depth=4) >>> result = ('len_tree = ' + ut.repr4(len_tree, nl=None)) >>> print(result) """ #if not isinstance(node, dict): if not hasattr(node, 'items'):
<gh_stars>10-100 # -*- coding: utf-8 -*- import mock from mock import call, sentinel, ANY import odooly from ._common import XmlRpcTestCase, OBJ AUTH = sentinel.AUTH ID1, ID2 = 4001, 4002 STABLE = ['uninstallable', 'uninstalled', 'installed'] def _skip_test(test_case): pass def imm(method, *params): return ('object.execute_kw', AUTH, 'ir.module.module', method, params, {'context': ANY}) def bmu(method, *params): return ('object.execute_kw', AUTH, 'base.module.upgrade', method, params, {'context': ANY}) class IdentDict(object): def __init__(self, _id): self._id = _id def __repr__(self): return 'IdentDict(%s)' % (self._id,) def __getitem__(self, key): return (key == 'id') and self._id or ('v_%s_%s' % (key, self._id)) def __eq__(self, other): return self._id == other._id DIC1 = IdentDict(ID1) DIC2 = IdentDict(ID2) class TestService(XmlRpcTestCase): """Test the Service class.""" protocol = 'xmlrpc' def _patch_service(self): return mock.patch('odooly.ServerProxy._ServerProxy__request').start() def _get_client(self): client = mock.Mock() client._server = 'http://127.0.0.1:8069/%s' % self.protocol proxy = getattr(odooly.Client, '_proxy_%s' % self.protocol) client._proxy = proxy.__get__(client, odooly.Client) return client def test_service(self): client = self._get_client() svc_alpha = odooly.Service(client, 'alpha', ['beta']) self.assertIn('alpha', str(svc_alpha.beta)) self.assertRaises(AttributeError, getattr, svc_alpha, 'theta') if self.protocol == 'xmlrpc': self.assertIn('_ServerProxy__request', str(svc_alpha.beta(42))) self.assertCalls(call('beta', (42,)), "().__str__") else: self.assertCalls() self.assertOutput('') def test_service_openerp(self): client = self._get_client() def get_proxy(name, methods=None): if methods is None: methods = odooly._methods.get(name, ()) return odooly.Service(client, name, methods, verbose=False) self.assertIn('common', str(get_proxy('common').login)) login = get_proxy('common').login('aaa') with self.assertRaises(AttributeError): get_proxy('common').non_existent if self.protocol == 'xmlrpc': self.assertIn('_ServerProxy__request', str(login)) self.assertCalls(call('login', ('aaa',)), 'call().__str__') else: self.assertEqual(login, 'JSON_RESULT',) self.assertCalls(ANY) self.assertOutput('') def test_service_openerp_client(self, server_version=11.0): server = 'http://127.0.0.1:8069/%s' % self.protocol return_values = [str(server_version), ['newdb'], 1, {}] if self.protocol == 'jsonrpc': return_values = [{'result': rv} for rv in return_values] self.service.side_effect = return_values client = odooly.Client(server, 'newdb', 'usr', 'pss') self.service.return_value = ANY self.assertIsInstance(client.db, odooly.Service) self.assertIsInstance(client.common, odooly.Service) self.assertIsInstance(client._object, odooly.Service) if server_version >= 11.0: self.assertIs(client._report, None) self.assertIs(client._wizard, None) elif server_version >= 7.0: self.assertIsInstance(client._report, odooly.Service) self.assertIs(client._wizard, None) else: self.assertIsInstance(client._report, odooly.Service) self.assertIsInstance(client._wizard, odooly.Service) self.assertIn('/%s|db' % self.protocol, str(client.db.create_database)) self.assertIn('/%s|db' % self.protocol, str(client.db.db_exist)) if server_version >= 8.0: self.assertRaises(AttributeError, getattr, client.db, 'create') self.assertRaises(AttributeError, getattr, client.db, 'get_progress') else: self.assertIn('/%s|db' % self.protocol, str(client.db.create)) self.assertIn('/%s|db' % self.protocol, str(client.db.get_progress)) self.assertCalls(ANY, ANY, ANY, ANY) self.assertOutput('') def test_service_openerp_61_to_70(self): self.test_service_openerp_client(server_version=7.0) self.test_service_openerp_client(server_version=6.1) def test_service_odoo_80_90(self): self.test_service_openerp_client(server_version=9.0) self.test_service_openerp_client(server_version=8.0) def test_service_odoo_10_11(self): self.test_service_openerp_client(server_version=11.0) self.test_service_openerp_client(server_version=10.0) class TestServiceJsonRpc(TestService): """Test the Service class with JSON-RPC.""" protocol = 'jsonrpc' def _patch_service(self): return mock.patch('odooly.http_post', return_value={'result': 'JSON_RESULT'}).start() class TestCreateClient(XmlRpcTestCase): """Test the Client class.""" server_version = '6.1' startup_calls = ( call(ANY, 'db', ANY, verbose=ANY), 'db.server_version', call(ANY, 'db', ANY, verbose=ANY), call(ANY, 'common', ANY, verbose=ANY), call(ANY, 'object', ANY, verbose=ANY), call(ANY, 'report', ANY, verbose=ANY), call(ANY, 'wizard', ANY, verbose=ANY), 'db.list', ) def test_create(self): self.service.db.list.return_value = ['newdb'] self.service.common.login.return_value = 1 client = odooly.Client('http://127.0.0.1:8069', 'newdb', 'usr', 'pss') expected_calls = self.startup_calls + ( call.common.login('newdb', 'usr', 'pss'), call.object.execute_kw('newdb', 1, 'pss', 'res.users', 'context_get', ()), ) url_xmlrpc = 'http://127.0.0.1:8069/xmlrpc' self.assertIsInstance(client, odooly.Client) self.assertCalls(*expected_calls) self.assertEqual( client.env._cache, {('[1, {}]', 'newdb', url_xmlrpc): client.env(context={}), ('[1, {"lang": "en_US", "tz": "Europe/Zurich"}]', 'newdb', url_xmlrpc): client.env, ('auth', 'newdb', url_xmlrpc): {1: (1, 'pss'), 'usr': (1, 'pss')}, ('model_names', 'newdb', url_xmlrpc): {'res.users'}}) self.assertOutput('') def test_create_getpass(self): getpass = mock.patch('getpass.getpass', return_value='password').start() self.service.db.list.return_value = ['database'] expected_calls = self.startup_calls + ( call.common.login('database', 'usr', 'password'), ) # A: Invalid login self.assertRaises(odooly.Error, odooly.Client, 'http://127.0.0.1:8069', 'database', 'usr') self.assertCalls(*expected_calls) self.assertEqual(getpass.call_count, 1) # B: Valid login self.service.common.login.return_value = 17 getpass.reset_mock() expected_calls = expected_calls + ( call.object.execute_kw('database', 17, 'password', '<PASSWORD>', 'context_get', ()), ) client = odooly.Client('http://127.0.0.1:8069', 'database', 'usr') self.assertIsInstance(client, odooly.Client) self.assertCalls(*expected_calls) self.assertEqual(getpass.call_count, 1) def test_create_with_cache(self): self.service.db.list.return_value = ['database'] self.assertFalse(odooly.Env._cache) url_xmlrpc = 'http://127.0.0.1:8069/xmlrpc' mock.patch.dict(odooly.Env._cache, {('auth', 'database', url_xmlrpc): {'usr': (1, 'password')}}).start() client = odooly.Client('http://127.0.0.1:8069', 'database', 'usr') self.assertIsInstance(client, odooly.Client) self.assertCalls(*(self.startup_calls + ( call.object.execute_kw('database', 1, 'password', '<PASSWORD>', 'context_get', ()), ))) self.assertOutput('') def test_create_from_config(self): env_tuple = ('http://127.0.0.1:8069', 'database', 'usr', None) read_config = mock.patch('odooly.read_config', return_value=env_tuple).start() getpass = mock.patch('getpass.getpass', return_value='password').start() self.service.db.list.return_value = ['database'] expected_calls = self.startup_calls + ( call.common.login('database', 'usr', 'password'), ) # A: Invalid login self.assertRaises(odooly.Error, odooly.Client.from_config, 'test') self.assertCalls(*expected_calls) self.assertEqual(read_config.call_count, 1) self.assertEqual(getpass.call_count, 1) # B: Valid login self.service.common.login.return_value = 17 read_config.reset_mock() getpass.reset_mock() expected_calls = expected_calls + ( call.object.execute_kw('database', 17, 'password', 'res.users', 'context_get', ()), ) client = odooly.Client.from_config('test') self.assertIsInstance(client, odooly.Client) self.assertCalls(*expected_calls) self.assertEqual(read_config.call_count, 1) self.assertEqual(getpass.call_count, 1) def test_create_invalid(self): # Without mock self.service.stop() self.assertRaises(EnvironmentError, odooly.Client, 'dsadas') self.assertOutput('') class TestSampleSession(XmlRpcTestCase): server_version = '6.1' server = 'http://127.0.0.1:8069' database = 'database' user = 'user' password = '<PASSWORD>' uid = 1 def test_simple(self): self.service.object.execute_kw.side_effect = [ 4, 71, [{'model': 'ir.cron'}], sentinel.IDS, sentinel.CRON] res_users = self.env['res.users'] self.assertEqual(res_users.search_count(), 4) self.assertEqual(self.env['ir.cron'].read( ['active = False'], 'active function'), sentinel.CRON) self.assertCalls( OBJ('res.users', 'search_count', []), OBJ('ir.model', 'search', [('model', 'like', 'ir.cron')]), OBJ('ir.model', 'read', 71, ('model',)), OBJ('ir.cron', 'search', [('active', '=', False)]), OBJ('ir.cron', 'read', sentinel.IDS, ['active', 'function']), ) self.assertOutput('') def test_list_modules(self): self.service.object.execute_kw.side_effect = [ ['delivery_a', 'delivery_b'], [{'state': 'not installed', 'name': 'dummy'}]] modules = self.env.modules('delivery') self.assertIsInstance(modules, dict) self.assertIn('not installed', modules) self.assertCalls( imm('search', [('name', 'like', 'delivery')]), imm('read', ['delivery_a', 'delivery_b'], ['name', 'state']), ) self.assertOutput('') def test_module_upgrade(self): self.service.object.execute_kw.side_effect = [ (42, 0), [42], [], ANY, [42], [{'id': 42, 'state': ANY, 'name': ANY}], ANY] result = self.env.upgrade('dummy') self.assertIsNone(result) self.assertCalls( imm('update_list'), imm('search', [('name', 'in', ('dummy',))]), imm('search', [('state', 'not in', STABLE)]), imm('button_upgrade', [42]), imm('search', [('state', 'not in', STABLE)]), imm('read', [42], ['name', 'state']), bmu('upgrade_module', []), ) self.assertOutput(ANY) class TestClientApi(XmlRpcTestCase): """Test the Client API.""" server_version = '6.1' server = 'http://127.0.0.1:8069' database = 'database' user = 'user' password = '<PASSWORD>' uid = 1 def obj_exec(self, *args): if args[4] == 'search': return [ID2, ID1] if args[4] == 'read': return [IdentDict(res_id) for res_id in args[5][::-1]] return sentinel.OTHER def test_create_database(self): create_database = self.client.create_database self.client.db.list.side_effect = [['db1'], ['db2']] create_database('abc', 'db1') create_database('xyz', 'db2', user_password='<PASSWORD>', lang='fr_FR') self.assertCalls( call.db.create_database('abc', 'db1', False, 'en_US', 'admin'), call.db.list(), call.common.login('db1', 'admin', 'admin'), call.object.execute_kw('db1', 1, 'admin', 'res.users', 'context_get', ()), call.db.create_database('xyz', 'db2', False, 'fr_FR', 'secret'), call.db.list(), call.common.login('db2', 'admin', 'secret'), call.object.execute_kw('db2', 1, 'secret', 'res.users', 'context_get', ()), ) self.assertOutput('') if float(self.server_version) < 9.0: self.assertRaises(odooly.Error, create_database, 'xyz', 'db2', user_password='<PASSWORD>', lang='fr_FR', login='other_login', country_code='CA') self.assertRaises(odooly.Error, create_database, 'xyz', 'db2', login='other_login') self.assertRaises(odooly.Error, create_database, 'xyz', 'db2', country_code='CA') self.assertOutput('') return # Odoo 9 self.client.db.list.side_effect = [['db2']] create_database('xyz', 'db2', user_password='<PASSWORD>', lang='fr_FR', login='other_login', country_code='CA') self.assertCalls( call.db.create_database('xyz', 'db2', False, 'fr_FR', 'secret', 'other_login', 'CA'), call.db.list(), call.common.login('db2', 'other_login', 'secret'), call.object.execute_kw('db2', 1, 'secret', 'res.users', 'context_get', ()), ) self.assertOutput('') def test_nonexistent_methods(self): self.assertRaises(AttributeError, getattr, self.client, 'search') self.assertRaises(AttributeError, getattr, self.client, 'count') self.assertRaises(AttributeError, getattr, self.client, 'search_count') self.assertRaises(AttributeError, getattr, self.client, 'search_read') self.assertRaises(AttributeError, getattr, self.client, 'keys') self.assertRaises(AttributeError, getattr, self.client, 'fields') self.assertRaises(AttributeError, getattr, self.client, 'field') self.assertRaises(AttributeError, getattr, self.env, 'search') self.assertRaises(AttributeError, getattr, self.env, 'count') self.assertRaises(AttributeError, getattr, self.env, 'search_count') self.assertRaises(AttributeError, getattr, self.env, 'search_read') self.assertRaises(AttributeError, getattr, self.env, 'keys') self.assertRaises(AttributeError, getattr, self.env, 'fields') self.assertRaises(AttributeError, getattr, self.env, 'field') def test_model(self): self.service.object.execute_kw.side_effect = self.obj_exec self.assertTrue(self.env.models('foo.bar')) self.assertCalls( OBJ('ir.model', 'search', [('model', 'like', 'foo.bar')]), OBJ('ir.model', 'read', [ID2, ID1], ('model',)), ) self.assertOutput('') self.assertRaises(odooly.Error, self.env.__getitem__, 'foo.bar') self.assertCalls( OBJ('ir.model', 'search', [('model', 'like', 'foo.bar')]), OBJ('ir.model', 'read', [ID2, ID1], ('model',)), ) self.assertOutput('') self.service.object.execute_kw.side_effect = [ sentinel.IDS, [{'id': 13, 'model': 'foo.bar'}]] self.assertIsInstance(self.env['foo.bar'], odooly.Model) self.assertIs(self.env['foo.bar'], odooly.Model(self.env, 'foo.bar')) self.assertCalls( OBJ('ir.model', 'search', [('model', 'like', 'foo.bar')]), OBJ('ir.model', 'read', sentinel.IDS, ('model',)), ) self.assertOutput('') def test_access(self): self.assertTrue(self.env.access('foo.bar')) self.assertCalls(OBJ('ir.model.access', 'check', 'foo.bar', 'read')) self.assertOutput('') def test_execute_kw(self): execute_kw = self.env._execute_kw execute_kw('foo.bar', 'any_method', (42,)) execute_kw('foo.bar', 'any_method', ([42],)) execute_kw('foo.bar', 'any_method', ([13, 17],)) self.assertCalls( ('object.execute_kw', AUTH, 'foo.bar', 'any_method', (42,)), ('object.execute_kw', AUTH, 'foo.bar', 'any_method', ([42],)), ('object.execute_kw', AUTH, 'foo.bar', 'any_method', ([13, 17],)), ) self.assertOutput('') def test_exec_workflow(self): exec_workflow = self.env.exec_workflow self.assertTrue(exec_workflow('foo.bar', 'light', 42)) self.assertCalls( ('object.exec_workflow', AUTH, 'foo.bar', 'light', 42), ) self.assertOutput('') def test_wizard(self): wizard_create = self.env.wizard_create wizard_execute = self.env.wizard_execute self.service.wizard.create.return_value = ID1 self.assertTrue(wizard_create('foo.bar')) wiz_id = wizard_create('billy') self.assertTrue(wiz_id) self.assertTrue(wizard_execute(wiz_id, {}, 'shake', None)) self.assertTrue(wizard_execute(42, {}, 'kick', None)) self.assertCalls( ('wizard.create', AUTH, 'foo.bar'), ('wizard.create', AUTH, 'billy'), ('wizard.execute', AUTH, ID1, {}, 'shake', None), ('wizard.execute', AUTH, 42, {}, 'kick', None), ) self.assertOutput('') def test_report(self): self.assertTrue(self.env.report('foo.bar', sentinel.IDS)) self.assertCalls( ('report.report', AUTH, 'foo.bar', sentinel.IDS), ) self.assertOutput('') def test_render_report(self): self.assertTrue(self.env.render_report('foo.bar', sentinel.IDS)) self.assertCalls( ('report.render_report', AUTH, 'foo.bar', sentinel.IDS), ) self.assertOutput('') def test_report_get(self): self.assertTrue(self.env.report_get(ID1)) self.assertCalls( ('report.report_get', AUTH, ID1), ) self.assertOutput('') def _module_upgrade(self, button='upgrade'): execute_return = [ [7, 0], [42], [], {'name': 'Upgrade'}, [4, 42, 5], [{'id': 4, 'state': ANY, 'name': ANY}, {'id': 5, 'state': ANY, 'name': ANY}, {'id': 42, 'state': ANY, 'name': ANY}], ANY] action = getattr(self.env, button) expected_calls = [ imm('update_list'), imm('search', [('name', 'in', ('dummy', 'spam'))]), imm('search', [('state', 'not in', STABLE)]), imm('button_' + button, [42]), imm('search', [('state', 'not in', STABLE)]), imm('read', [4, 42, 5], ['name', 'state']), bmu('upgrade_module', []), ] if button == 'uninstall': execute_return[3:3] = [[], {'state': {'type': 'selection'}}, ANY] expected_calls[3:3] = [ imm('search', [('id', 'in', [42]), ('state', '!=', 'installed'), ('state', '!=', 'to upgrade'), ('state', '!=', 'to remove')]), imm('fields_get'), imm('write', [42], {'state': 'to remove'}), ] self.service.object.execute_kw.side_effect = execute_return result = action('dummy', 'spam') self.assertIsNone(result) self.assertCalls(*expected_calls) self.assertIn('to process', self.stdout.popvalue()) self.service.object.execute_kw.side_effect = [[0, 0], []] self.assertIsNone(action()) self.assertCalls( imm('update_list'), imm('search', [('state', 'not in', STABLE)]), ) self.assertOutput('0 module(s) updated\n') def test_module_upgrade(self):
278222430, 72996, -61288, 278280917, 73004, -1, 278342495, 72966, 278532263, 274501173, -1, 278597798, 278489215, -1, 278663327, 278531857, -1, -61283, 278628503, 73023, -61282, 278675549, 73020, -1, 278728465, 73009, 278925473, 278628503, 73012, -1, 278890647, 73013, 279056547, 278872157, 73010, -1, 279003229, 73011, -61276, 279023751, 73014, -61275, 279142501, 73021, -1, 279194463, 73018, -1, 278546260, 73029, 279449781, 278472697, -1, 279515307, 279413070, -1, -61270, 279483606, 73042, -1, 279527250, 73043, 279711918, 279476258, -1, -61267, 279660925, 73046, -1, 279720502, 73047, 279908529, 279655206, -1, -61264, 279865098, 73044, -1, 279922911, 73045, -61262, 279877895, 73040, -61261, 280060676, 73041, -61260, 280124866, 73049, -1, 280178176, 73048, 280367291, 279411792, -1, -61257, 280334426, 73025, -61256, 280387566, 73026, -61255, 280443733, 73028, -61254, 280501690, 73027, -1, 280564873, 73024, 280821759, 280325964, -1, -61251, 280703015, 73030, -1, 280760142, 73031, 280957212, 274427724, -1, 281022747, 280895440, -1, 281088235, 280983586, -1, 281153768, 281053540, -1, 281219272, 281117006, -1, 281284806, 281180194, -1, -61243, 281230037, 72867, -1, 281284369, 72866, -61241, 281230037, 72859, -1, 281415441, 72858, 281612492, 281172823, -1, -61238, 281581320, 72857, -61237, 281622498, 72853, -1, 281677585, 72861, 281874639, 281581688, -1, -61234, 281819861, 72870, -1, 281874193, 72871, 282071250, 281835554, -1, -61231, 282016469, 72876, -1, 282070801, 72877, 282267861, 282028241, -1, -61228, 282213077, 72863, -1, 282267409, 72862, 282464472, 282217155, -1, -61225, 282409685, 72851, -1, 282464017, 72850, 282661083, 282404191, -1, -61222, 282630266, 72868, -1, 282660625, 72860, 282857694, 282598711, -1, -61219, 282802901, 72855, -1, 282857233, 72854, -61217, 282826504, 72873, -61216, 283021617, 72869, -61215, 283078553, 72874, -61214, 283137630, 72865, -61213, 283200841, 72875, -61212, 283265562, 72856, -61211, 283327189, 72878, -61210, 283391970, 72852, -61209, 283449395, 72864, -1, 283512593, 72879, 283770879, 281101046, -1, -61206, 283647438, 72886, -1, 283710601, 72885, 283906323, 281039273, -1, 283971826, 283869518, -1, 284037360, 283932706, -1, -61201, 283982549, 72835, -1, 284036881, 72834, -61199, 283982549, 72827, -1, 284167953, 72826, 284365046, 283925335, -1, -61196, 284333832, 72825, -61195, 284375010, 72821, -1, 284430097, 72829, 284627193, 284334200, -1, -61192, 284572373, 72838, -1, 284626705, 72839, 284823804, 284588066, -1, -61189, 284768981, 72844, -1, 284823313, 72845, 285020415, 284780753, -1, -61186, 284965589, 72831, -1, 285019921, 72830, 285217026, 284969667, -1, -61183, 285162197, 72819, -1, 285216529, 72818, 285413637, 285156703, -1, -61180, 285382778, 72836, -1, 285413137, 72828, 285610248, 285351223, -1, -61177, 285555413, 72823, -1, 285609745, 72822, -61175, 285579016, 72841, -61174, 285774129, 72837, -61173, 285831065, 72842, -61172, 285890142, 72833, -61171, 285953353, 72843, -61170, 286018074, 72824, -61169, 286079701, 72846, -61168, 286144482, 72820, -61167, 286201907, 72832, -61166, 286265105, 72847, -1, 286328866, 72840, 286527769, 283873528, -1, -61163, 286492823, 72882, -61162, 286548069, 72884, -61161, 286605405, 72881, -61160, 286665567, 72883, -1, 286723943, 72880, -61158, 286480216, 72817, -1, 286866578, 72816, -1, 280986694, 129355, 287117651, 280902439, -1, 287183183, 287067383, -1, 287248718, 287125912, -1, 287314213, 287211854, -1, 287379747, 287277390, -1, -61150, 287324885, 69983, -1, 287379217, 69982, -61148, 287324885, 69988, -1, 287510289, 69987, 287707435, 287253855, -1, 287772969, 287647071, -1, -61144, 287718101, 69985, -1, 287772433, 69984, -61142, 287718101, 69990, -1, 287903505, 69989, 288100655, 287660887, -1, -61139, 288069384, 69981, -61138, 288119728, 69986, -1, 288165649, 69991, 288362802, 288059212, -1, -61135, 288321433, 70002, -1, 288362257, 69997, 288559413, 288319697, -1, -61132, 288504533, 69993, -1, 288558865, 69992, 288756024, 288508611, -1, -61129, 288701141, 69974, -1, 288755473, 69973, 288952635, 288705013, -1, -61126, 288897749, 69980, -1, 288952081, 69979, 289149246, 288896937, -1, -61123, 289094357, 69976, -1, 289148689, 69975, 289345857, 289086775, -1, -61120, 289290965, 69978, -1, 289345297, 69977, 289542468, 289282082, -1, -61117, 289487573, 69995, -1, 289541905, 69994, -61115, 289508935, 69999, -61114, 289704087, 69970, -61113, 289765534, 70000, -61112, 289824869, 69972, -61111, 289887838, 69996, -61110, 289951049, 69998, -61109, 290013277, 69969, -61108, 290077397, 70001, -61107, 290138975, 69971, -1, 290197265, 69968, -1, 287195722, 70006, 290459986, 287143970, -1, -61103, 290407185, 70003, -1, 290466971, 70005, -1, 290394031, 70004, 290722160, 287066975, -1, 290787688, 290673065, -1, 290853209, 290741079, -1, -61097, 290821896, 73451, -61096, 290863074, 73442, -1, 290918161, 73448, -61094, 290821896, 73452, -61093, 291081799, 73455, -61092, 291144150, 73446, -61091, 291207326, 73456, -61090, 291270553, 73453, -61089, 291334411, 73443, -61088, 291395166, 73445, -61087, 291458377, 73454, -61086, 291523354, 73440, -61085, 291588634, 73450, -61084, 291649506, 73441, -61083, 291710443, 73447, -61082, 291773779, 73449, -61081, 291838003, 73444, -1, 291901201, 73457, 292098413, 290754808, -1, -61078, 292063383, 73460, -61077, 292118629, 73462, -61076, 292175965, 73459, -1, 292236127, 73461, -61074, 292055610, 73463, -61073, 292368198, 73464, -1, 292426749, 73458, 292622736, 290672326, -1, 292688256, 292566758, -1, 292753788, 292643592, -1, 292819318, 292716878, -1, -61067, 292786781, 3419, -1, 292827091, 3420, 293015929, 292762406, -1, -61064, 292971974, 3417, -1, 293028339, 3422, -61062, 292977892, 3446, -61061, 293168007, 3416, -1, 293219893, 3447, 293470207, 292717494, -1, -61058, 293373998, 3421, -61057, 293436654, 3448, -1, 293482044, 3418, 293671305, 292639145, -1, 293736837, 293609452, -1, -61053, 293705389, 3413, -61052, 293754388, 3412, -1, 293819424, 3414, -61050, 293701521, 3386, -61049, 293953147, 3369, -61048, 294004905, 3406, -1, 294065430, 3423, 294322175, 293633104, -1, 294326670, 294198583, -1, -61044, 294281829, 3328, -61043, 294340535, 3388, -1, 294392779, 3329, -61041, 294293282, 3387, -1, 294545840, 3407, 294719916, 292591387, -1, 294785433, 294682958, -1, 294850965, 294752537, -1, -61036, 294805605, 119522, -1, 294858428, 119532, 295047576, 294795975, -1, -61033, 295006658, 119523, -1, 295061466, 119533, -1, 294989550, 119530, 295309726, 294746146, -1, 295375260, 295258493, 119526, -1, 295338684, 119536, 295567359, 295318070, 119527, -1, 295469756, 119537, 295637412, 295252774, -1, 295702945, 295593738, 119524, -1, 295666364, 119534, 295895039, 295649373, -1, -61021, 295800429, 119525, -1, 295843726, 119535, 296030632, 295578463, -1, 296096167, 295977566, 119528, -1, 296037722, 119538, -1, 296047185, 119531, 296292778, 295984578, 119529, -1, 296256188, 119539, -61013, 296261895, 119520, -1, 296379140, 119521, 296554927, 294683457, -1, -61010, 296515069, 10187, -1, 296563576, 10189, 296751538, 296499113, -1, -61007, 296705297, 129522, -1, 296758111, 129497, -61005, 296719961, 128470, -1, 296905644, 127809, 297079408, 266682461, -1, 297144929, 297014433, -1, 297210411, 297095593, -1, 297275849, 297173326, -1, 297341376, 297231234, -1, -60998, 297274887, 94105, -60997, 297340257, 94104, -60996, 297405641, 94103, -60995, 297471007, 94102, -60994, 297536387, 94101, -60993, 297601738, 94100, -1, 297667058, 94099, 297865668, 297302050, -1, -60990, 297826462, 93994, -60989, 297876181, 93998, -1, 297930513, 94007, 298127815, 297816727, -1, -60986, 298096392, 93980, -1, 298127121, 93978, -60984, 298090966, 93966, -1, 298258193, 93962, 298455510, 297229143, -1, 298521037, 298423981, -1, -60980, 298466005, 93997, -1, 298520337, 93996, 298717648, 298474327, -1, -60977, 298662613, 93973, -1, 298716945, 93972, 298914259, 298661801, -1, -60974, 298859221, 93988, -1, 298913553, 93987, 299110869, 298848017, 93968, -1, 299071693, 94032, -1, 299055829, 93969, 299307490, 298424440, -1, 299373021, 299276408, -1, 299438555, 299333666, -1, -60966, 299407112, 94017, -1, 299437841, 94014, -60964, 299407112, 94016, -1, 299568913, 94013, 299766240, 299333666, -1, -60961, 299711189, 94006, -1, 299765521, 94012, -60959, 299711189, 94005, -1, 299896593, 94011, 300093933, 299276205, -1, 300159465, 300056910, -1, 300224999, 300120098, -1, -60954, 300169941, 94000, -1, 300224273, 94009, -60952, 300188118, 93964, -1, 300355345, 93965, -60950, 300116235, 93954, -60949, 300506710, 93970, -60948, 300567322, 93984, -1, 300624730, 94001, 300814838, 300052999, -1, 300880373, 300770178, -1, -60944, 300813831, 94111, -60943, 300879049, 94110, -60942, 300944415, 94109, -60941, 301009795, 94108, -60940, 301074930, 94107, -1, 301140310, 94106, -1, 300841703, 94002, 301404672, 300754271, -1, 301470203, 301373560, -1, -60935, 301439098, 93995, -60934, 301480661, 93999, -1, 301534993, 94008, 301732350, 301421207, -1, -60931, 301700872, 93981, -1, 301731601, 93979, -60929, 301671915, 93967, -1, 301862673, 93963, 302060040, 301338385, -1, 302125575, 302018755, -1, 302191109, 302078807, -1, -60924, 302135266, 93989, -1, 302190353, 93971, -60922, 302160196, 94015, -1, 302339678, 93958, -1, 302070471, 94019, 302584334, 302009591, -1, 302649868, 302529223, -1, -60917, 302618376, 93977, -1, 302649105, 93976, -60915, 302618376, 93975, -1, 302780177, 93974, 302977554, 302544930, -1, -60912, 302938270, 94004, -60911, 302987989, 94003, -1, 303042321, 94010, 303239703, 302921641, -1, 303305238, 303184583, -1, -60907, 303250133, 93993, -1, 303304465, 93992, -1, 303238929, 93983, 303567386, 303205941, -1, -60903, 303510346, 93961, -1, 303566609, 93960, 303763997, 303525421, -1, -60900, 303708130, 93986, -1, 303763217, 93985, 303960608, 303720657, -1, -60897, 303910217, 93955, -1, 303959825, 93952, 304157219, 303912468, -1, -60894, 304102101, 93957, -1, 304156433, 93956, 304353830, 304102087, -1, -60891, 304298709, 94020, -1, 304353041, 93990, -60889, 304322085, 93991, -60888, 304517425, 94018, -60887, 304565018, 93982, -60886, 304624458, 93959, -1, 304683059, 93953, 304878167, 297177336, -1, 304943669, 304824413, 94049, 305009200, 304877329, 94050, 305135615, 304962391, 94051, -1, 305018793, 94052, -60879, 304973975, 94056, -60878, 305160293, 94053, -60877, 305225040, 94057, -60876, 305283165, 94055, -1, 305343327, 94054, 305533502, 304877329, 94036, 305599032, 305486679, 94039, -1, 305543081, 94040, 305730106, 305539935, 94067, -1, 305671007, 94068, -60869, 305694871, 94075, -60868, 305807453, 94073, -60867, 305872299, 94038, -1, 305925905, 94037, 306123333, 305498263, 94058, 306188866, 306056977, 94059, 306315263, 306142039, 94060,
self.NextName('log'), shape=[], values=[msg_or_blob]) else: blob = msg_or_blob self.Print(blob, []) def add_attribute(self, name, obj): """ Add `obj` to the list of attributes in this net under the given `name`. Attributes are user-defined objects and have no pre-defined semantics. """ self._attr_dict[name].append(obj) def get_attributes(self, name): """ Returns the list of attributes in this net for a given `name`. Attributes are user-defined objects added with `add_attribute'. """ return self._attr_dict.get(name, []) def set_rand_seed(self, seed=100, sequence_seed=True, seed_on_op_def=False): """ Adds a random seed to each op in the net. If sequence_seed is set, the i-th op has rand_seed=`seed + i` If seed_on_op_def is set, the op rand_seed=hash(str(op)) sequence_seed and seed_on_op_def cannot be both set to True. """ assert not (sequence_seed and seed_on_op_def), ( 'sequence_seed and seed_on_op_def cannot be both set to True.') for i, op in enumerate(self.Proto().op): if sequence_seed: curr_seed = seed + i elif seed_on_op_def: curr_seed = hash(str(op) + str(seed)) % np.iinfo(np.uint32).max else: curr_seed = seed op.device_option.random_seed = curr_seed def Name(self): return self._net.name def __str__(self): return self.Name() def Const(self, array, blob_out=None, dtype=None): if isinstance(array, bool): return self.ConstantFill( [], blob_out or 1, dtype=DataType.BOOL, value=array) if dtype is None: array = np.array(array) else: array = np.array(array, dtype=dtype) def do_set(operator): return operator( [], blob_out or 1, shape=array.shape, values=array.flatten().tolist()) if array.dtype == np.int32: return do_set(self.GivenTensorIntFill) elif array.dtype == np.int64: return do_set(self.GivenTensorInt64Fill) elif array.dtype == np.str: return do_set(self.GivenTensorStringFill) else: return do_set(self.GivenTensorFill) def BlobIsDefined(self, blob): """ Returns true if the given BlobReference is produced as output of an operator in this net, or if it is provided as an external input. """ if self._recreate_lookup_tables: self._RecreateLookupTables() name = str(blob) return (name in self._op_outputs) or (name in self._external_input_map) def UsesBlob(self, blob): """ Returns true iff the given BlobReference is used by any operator or this net, or if it is one of the external inputs of the net. """ blob_name = str(blob) for op in self._net.op: for input in op.input: if input == blob_name: return True return blob_name in self._external_input_map def GetBlobRef(self, blob_name): """ Given the name of a blob produced by this net, return a BlobReference to it. If the blob is not produced by any op in this net, raises KeyError. """ blob_name = str(blob_name) if not self.BlobIsDefined(blob_name): raise KeyError('Net does not define blob %s' % blob_name) return BlobReference(blob_name, self) def Clone( self, name, blob_remap=None, op_id_mask=None, remap_funcs=None, keep_schema=True ): """ Clone this net. Args: name: name of the cloned net blob_remap: optional map with list of blob names to replace op_id_mask: optional list of operator indices to include in the cloned net. If not provided, all ops are included. """ if remap_funcs is None: remap_funcs = {} proto = self._net new_proto = caffe2_pb2.NetDef() new_proto.CopyFrom(proto) new_proto.name = name if blob_remap is None: blob_remap = {} if op_id_mask is None: op_id_mask = list(range(0, len(proto.op))) def get_remapped_str(blob): blob_str = str(blob) return str(blob_remap.get(blob_str, blob_str)) def remap_list(proto_list): new_list = [get_remapped_str(b) for b in proto_list] del proto_list[:] proto_list.extend(new_list) def remap_op(op): new_op = caffe2_pb2.OperatorDef() new_op.CopyFrom(op) remap_list(new_op.input) remap_list(new_op.output) if new_op.type in remap_funcs: remap_funcs[new_op.type](new_op, (name + '/') if name else '') return new_op del new_proto.op[:] new_proto.op.extend([remap_op(proto.op[op_id]) for op_id in op_id_mask]) remap_list(new_proto.external_input) remap_list(new_proto.external_output) new_net = Net(new_proto) if keep_schema: from caffe2.python import schema if self._input_record: new_net._input_record = schema.from_blob_list( self._input_record, [ BlobReference(get_remapped_str(blob), net=new_net) for blob in self._input_record.field_blobs() ], ) if self._output_record: new_net._output_record = schema.from_blob_list( self._output_record, [ BlobReference(get_remapped_str(blob), net=new_net) for blob in self._output_record.field_blobs() ], ) new_net._attr_dict.update(self._attr_dict) return new_net def ClonePartial(self, name, inputs, outputs, remap_funcs=None): """ Clone this net, including only ops that are necessary in order to compute `outputs` given `inputs`. Return references to the cloned outputs. Internal blobs (blobs that are produced and consumed inside the net but not used as outputs) will be remapped to avoid name conflict. Args: name: the name of the cloned net inputs: map where the keys correspond to BlobReferences in the original net, and the values correspond to external inputs in the partially cloned net. If `inputs` is a list, don't remap input names. outputs: outputs to be produced by the cloned net. Returns: Tuple (new_net, new_outputs) new_net: a new Net object. new_outputs: list of BlobReferences corresponding to the outputs produced by new_net. """ input_is_pair_list = isinstance(inputs, list) and all( isinstance(i, tuple) and len(i) == 2 for i in inputs) inputs = ( inputs if isinstance(inputs, (dict, OrderedDict)) else OrderedDict(inputs) if input_is_pair_list else OrderedDict(zip(inputs, inputs))) for output in outputs: assert self.BlobIsDefined(output) input_names = {str(k): str(v) for k, v in viewitems(inputs)} output_names = [str(o) for o in outputs] proto = self._net ssa, blob_versions = get_ssa(proto) used_op_ids = get_op_ids_in_path(ssa, blob_versions, inputs, outputs) disallowed_op_ids = get_op_ids_in_path(ssa, blob_versions, [], inputs) assert len(set(used_op_ids) & set(disallowed_op_ids)) == 0, ( 'Cannot partially clone net: some of the ops required would ' + 'generate the given input.') sub_ssa = [op for i, op in enumerate(ssa) if i in used_op_ids] undef_blobs = get_undefined_blobs(sub_ssa) - set(viewkeys(input_names)) prefix = (name + '/') if name else '' def remap(blob_name): if blob_name in input_names: return input_names[blob_name] elif blob_name in undef_blobs: return blob_name else: return prefix + blob_name blob_mapping = {b: remap(b) for b in viewkeys(blob_versions)} new_net = self.Clone(name, blob_mapping, used_op_ids, remap_funcs) new_in = [ blob_mapping[i] for i in viewkeys(input_names)] + list(undef_blobs) new_out = [blob_mapping[o] for o in output_names] del new_net.Proto().external_input[:] new_net.Proto().external_input.extend(new_in) new_net._external_input_map = set(list(new_in)) del new_net.Proto().external_output[:] new_net.Proto().external_output.extend(new_out) return new_net, [new_net.GetBlobRef(o) for o in new_out] def Proto(self): self._InvalidateLookupTables() return self._net def PopulateProtoWithFileName(self): net_tb = workspace.operator_tracebacks.get(self.Name(), None) if net_tb is not None: for idx, op in enumerate(self.Proto().op): if idx in net_tb: op.name = ':'.join(map(str, net_tb[idx][0])) def NextScopedBlob(self, prefix='unnamed'): """Return the blob that has not been defined or registered in the current net. It returns `ScopedBlobReference(prefix)`, if it's valid, otherwise `ScopedBlobReference(prefix) + '_auto_' + ?`. Different calls is guaranteed to return blob with different names. """ output_blob_base = ScopedName(prefix) return self.NextBlob(output_blob_base) def NextBlob(self, prefix='unnamed'): """Return the blob that has not been defined or registered in the current net. It returns `BlobReference(prefix)`, if it's valid, otherwise `BlobReference(prefix) + '_auto_' + ?`. Different calls is guaranteed to return blob with different names.""" output_blob_base = BlobReference(prefix) output_blob = output_blob_base index = 0 while str(output_blob) in self._registered_blob_names or ( self.BlobIsDefined(output_blob)): output_blob = output_blob_base + '_auto_' + str(index) index += 1 self._registered_blob_names.add(str(output_blob)) return output_blob def NextName(self, prefix=None, output_id=None): """Returns the next name to be used, if you do not want to explicitly name your blob. [Deprecated, use NextBlob, NextScopedBlob instead]""" if prefix: output_name_base = self._net.name + '/' + prefix output_name = output_name_base if output_id is not None: output_name += ':' + str(output_id) index = 2 while self.BlobIsDefined(str(ScopedBlobReference(output_name))): output_name = output_name_base + '_' + str(index) if output_id is not None: output_name += ':' + str(output_id) index += 1 else: output_name = self._net.name + '_blob_' + str(self._next_name_index) self._next_name_index += 1 return str(output_name) def _ExtendOps(self, new_ops): self._net.op.extend(new_ops) for op in new_ops: self._op_outputs.update([text_type(o) for o in op.output]) def _CheckLookupTables(self): ''' Called from unit tests to validate the internal lookup tables match the protobuf contents. ''' test_op_outputs = set() for op in self._net.op: for o in op.output: test_op_outputs.add(o) test_external_inp = set() for inp in self._net.external_input: test_external_inp.add(inp) assert test_op_outputs.difference(self._op_outputs) == set() assert test_external_inp.difference(self._external_input_map) == set() def _InvalidateLookupTables(self): self._recreate_lookup_tables = True def _RecreateLookupTables(self): self._op_outputs = set() for op in self._net.op: for o in op.output: self._op_outputs.add(o) self._external_input_map = set() for inp in self._net.external_input: self._external_input_map.add(inp) self._recreate_lookup_tables = False def AddGradientOperators(self, ys, skip=0): """Add the gradient for operators in the net. Inputs: ys: a list or a dictionary specifying what blobs we want to compute derivatives of. If the input is a list, we will automatically generate their gradients with all-one values; if the input is a dictionary, for any dictionary entries that are not None, we will take the corresponding blobs as their gradients; for all those that are None, we will auto-fill them with 1. skip: skips the first n operators. This is provided mainly because a lot of nets may use the first few operators for data generation like stuff which really do not need to
if data_trend_df.empty: trend_ret_list = [] else: trend_ret_list = score_trend_pandas_groupby(data_trend_df, filter_dataset_dict, score_type) return Response( { "score_trend": trend_ret_list, "level_distribution": { "x": x, "y": bin_result_list, "z": z, "sum_count": sum_count, }, } ) class LevelDistributionView(APIViewSet): @list_route(methods=["post"], url_path=r"(?P<score_type>\w+)") @params_valid(serializer=DataValueSerializer) def level_distribution(self, request, score_type, params): """ @api {post} /datamanage/datastocktake/level_distribution/:score_type/ 价值、重要度等等级分布 @apiVersion 0.1.0 @apiGroup Datastocktake/LevelDistribution @apiName level_distribution @apiParam {String} score_type 生命周期评分指标 importance/heat/range/asset_value/assetvalue_to_cost @apiSuccess (输出) {String} data.x 等级区间 @apiSuccess (输出) {String} data.y 数据个数 @apiSuccess (输出) {String} data.z 数据占比 @apiSuccess (输出) {String} data.sum_count 数据表总数 @apiParamExample {json} 参数样例: HTTP/1.1 http://{domain}/v3/datamanage/datastocktake/level_distribution/importance/ { "bk_biz_id":null, "project_id":null, "tag_ids":[ ], "keyword":"", "tag_code":"virtual_data_mart", "me_type":"tag", "has_standard":1, "cal_type":[ "standard" ], "data_set_type":"all", "page":1, "page_size":10, "platform":"bk_data", } @apiSuccessExample Success-Response: HTTP/1.1 200 OK { "errors": null, "message": "ok", "code": "1500200", "data": { "y": [ 245, 8010, 1887, 1657 ], "x": [ "[0,10]", "(10,50]", "(50,75]", "(75,100]" ], "sum_count": 11799, "z": [ 0.0207645, 0.6788711, 0.1599288, 0.1404356 ] }, "result": true } """ # 从redis拿到热度、广度相关明细数据 metric_list = cache.get("data_value_stocktake") platform = params.get("platform", "all") if (not metric_list) or platform == "tdw": return Response({"x": [], "y": [], "z": [], "sum_count": 0}) has_filter_cond, filter_dataset_dict = dataset_filter(params, request) if has_filter_cond and not filter_dataset_dict: return Response({"x": [], "y": [], "z": [], "sum_count": 0}) x, bin_result_list, z, sum_count = level_distribution(metric_list, filter_dataset_dict, score_type) return Response({"x": x, "y": bin_result_list, "z": z, "sum_count": sum_count}) class CostDistribution(APIViewSet): @list_route(methods=["post"], url_path="storage_capacity") @params_valid(serializer=DataValueSerializer) def storage_capacity(self, request, params): """ @api {post} /datamanage/datastocktake/cost_distribution/storage_capacity/ 存储分布 @apiVersion 0.1.0 @apiGroup Datastocktake/CostDistribution @apiName storage_capacity @apiSuccess (输出) {String} data.capacity_list 不同存储的大小 @apiSuccess (输出) {String} data.label 不同存储的名称 @apiSuccess (输出) {String} data.sum_capacity 总存储大小 @apiSuccess (输出) {String} data.unit 存储单位,自适应单位 @apiSuccessExample Success-Response: HTTP/1.1 200 OK { "errors": null, "message": "ok", "code": "1500200", "data": { "capacity_list": [], "label": [], "sum_capacity": 0, "unit": "TB" }, "result": true } """ metric_list = cache.get("data_value_stocktake") platform = params.get("platform", "all") if (not metric_list) or platform == "tdw": return Response({"capacity_list": [], "label": [], "sum_capacity": 0, "unit": "MB"}) has_filter_cond, filter_dataset_dict = dataset_filter(params, request) if has_filter_cond and not filter_dataset_dict: return Response({"capacity_list": [], "label": [], "sum_capacity": 0, "unit": "MB"}) hdfs_list = [] tspider_list = [] for each in metric_list: if not filter_dataset_dict or each["dataset_id"] in filter_dataset_dict: hdfs_list.append(each["hdfs_capacity"]) tspider_list.append(each["tspider_capacity"]) sum_hdfs = sum(hdfs_list) sum_tspider = sum(tspider_list) sum_capacity = sum_hdfs + sum_tspider format_max_capacity, unit, power = hum_storage_unit(sum_capacity, return_unit=True) sum_hdfs = round(sum_hdfs / float(1024 ** power), 3) sum_tspider = round(sum_tspider / float(1024 ** power), 3) sum_capacity = round(sum_capacity / float(1024 ** power), 3) capacity_list = [sum_hdfs, sum_tspider] label = ["hdfs", "tspider"] return Response( { "capacity_list": capacity_list, "label": label, "sum_capacity": sum_capacity, "unit": unit, } ) @list_route(methods=["post"], url_path="storage_trend") @params_valid(serializer=DataValueSerializer) def storage_trend(self, request, params): """ @api {post} /datamanage/datastocktake/cost_distribution/storage_trend/ 存储成本趋势 @apiVersion 0.1.0 @apiGroup Datastocktake/CostDistribution @apiName storage_trend @apiSuccessExample Success-Response: HTTP/1.1 200 OK { "errors": null, "message": "ok", "code": "1500200", "data": { "tspider_capacity": [ 23, 23, 23, 23, 23, 23 ], "hdfs_capacity": [ 1000, 1000, 1000, 1000, 1000, 1000 ], "total_capacity": [ 1023, 1023, 1023, 1023, 1023, 1023 ], "unit": "TB", "time": [ "08-13", "08-14", "08-15", "08-16", "08-17", "08-18" ] }, "result": true } """ data_trend_df = cache.get("data_trend_df") platform = params.get("platform", "all") if data_trend_df.empty or platform == "tdw": return Response( { "tspider_capacity": [], "hdfs_capacity": [], "total_capacity": [], "time": [], "unit": "B", } ) has_filter_cond, filter_dataset_dict = dataset_filter(params, request) if has_filter_cond and not filter_dataset_dict: return Response( { "tspider_capacity": [], "hdfs_capacity": [], "total_capacity": [], "time": [], "unit": "B", } ) ret_dict = storage_capacity_trend(data_trend_df, filter_dataset_dict) return Response(ret_dict) class ImportanceDistribution(APIViewSet): @list_route(methods=["post"], url_path=r"(?P<metric_type>\w+)") @params_valid(serializer=DataValueSerializer) def importance_metric_distribution(self, request, metric_type, params): """ @api {post} /datamanage/datastocktake/importance_distribution/:metric_type/ 业务重要度、关联BIP、项目运营状态、数据敏感度分布、数据生成类型 @apiVersion 0.1.0 @apiGroup Datastocktake/ImportanceDistribution @apiName importance_metric_distribution @apiParam {String} metric_type 重要度相关指标 app_important_level_name/is_bip/active/sensitivity/generate_type @apiSuccessExample Success-Response: HTTP/1.1 200 OK { "errors":null, "message":"ok", "code":"1500200", "data":{ "dataset_count":[ 10274, 1557 ], "metric":[ false, true ], "dataset_perct":[ 0.8683966, 0.1316034 ], "biz_count":[ 317, 30 ], "biz_perct":[ 0.9135447, 0.0864553 ] }, "result":true } """ metric_list = cache.get("data_value_stocktake") platform = params.get("platform", "all") if (not metric_list) or platform == "tdw": return Response({"metric": [], "dataset_count": [], "dataset_perct": []}) has_filter_cond, filter_dataset_dict = dataset_filter(params, request) if has_filter_cond and not filter_dataset_dict: return Response({"metric": [], "dataset_count": [], "dataset_perct": []}) importance_metric_list = [] for each in metric_list: if not filter_dataset_dict or each["dataset_id"] in filter_dataset_dict: if metric_type not in list(METRIC_DICT.keys()): importance_metric_list.append({"dataset_id": each["dataset_id"], "metric": each[metric_type]}) else: importance_metric_list.append( { "dataset_id": each["dataset_id"], "metric": each[metric_type], METRIC_DICT[metric_type]: each[METRIC_DICT[metric_type]], } ) df1 = DataFrame(importance_metric_list) df2 = df1.groupby("metric", as_index=False).count().sort_values(["metric"], axis=0, ascending=True) metric_count_agg_list = df2.to_dict(orient="records") metric = [each["metric"] for each in metric_count_agg_list] dataset_count = [each["dataset_id"] for each in metric_count_agg_list] metric_sum = len(metric_list) dataset_perct = [ round(each["dataset_id"] / float(metric_sum), 7) if metric_sum else 0 for each in metric_count_agg_list ] if metric_type in list(METRIC_DICT.keys()): df3 = ( df1.groupby(["metric", METRIC_DICT[metric_type]], as_index=False) .count() .sort_values(["metric"], axis=0, ascending=True) ) df4 = df3.groupby("metric", as_index=False).count().sort_values(["metric"], axis=0, ascending=True) count_agg_list = df4.to_dict(orient="records") count = [each["dataset_id"] for each in count_agg_list] count_sum = sum(count) perct = [round(each["dataset_id"] / float(count_sum), 7) if count_sum else 0 for each in count_agg_list] if METRIC_DICT[metric_type] == "bk_biz_id": return Response( { "metric": metric, "dataset_count": dataset_count, "dataset_perct": dataset_perct, "biz_count": count, "biz_perct": perct, } ) else: return Response( { "metric": metric, "dataset_count": dataset_count, "dataset_perct": dataset_perct, "project_count": count, "project_perct": perct, } ) return Response( { "metric": metric, "dataset_count": dataset_count, "dataset_perct": dataset_perct, } ) @list_route(methods=["post"], url_path="biz") @params_valid(serializer=DataValueSerializer) def bip_grade_and_oper_state_distr(self, request, params): """ @api {post} /datamanage/datastocktake/importance_distribution/biz/ 业务星际&运营状态分布 @apiVersion 0.1.0 @apiGroup Datastocktake/ImportanceDistribution @apiName bip_grade_and_oper_state_distribution @apiSuccessExample Success-Response: HTTP/1.1 200 OK { "errors": null, "message": "ok", "code": "1500200", "data": { "dataset_count": [ 148 ], "oper_state_name": [ "不删档" ], "biz_count": [ 6 ], "bip_grade_name": [ "三星" ] }, "result": true } """ metric_list = cache.get("data_value_stocktake") platform = params.get("platform", "all") if (not metric_list) or platform == "tdw": return Response( { "dataset_count": [], "oper_state_name": [], "biz_count": [], "bip_grade_name": [], } ) has_filter_cond, filter_dataset_dict = dataset_filter(params, request) if has_filter_cond and not filter_dataset_dict: return Response( { "dataset_count": [], "oper_state_name": [], "biz_count": [], "bip_grade_name": [], } ) biz_metric_list = [] for each in metric_list: if not filter_dataset_dict or each["dataset_id"] in filter_dataset_dict: bip_grade_name = ( each["bip_grade_name"] if each["bip_grade_name"] not in ABN_BIP_GRADE_NAME_LIST else CORR_BIP_GRADE_NAME ) biz_metric_list.append( { "dataset_id": each["dataset_id"], "oper_state_name": each["oper_state_name"], "bip_grade_name": bip_grade_name, "bk_biz_id": each["bk_biz_id"], } ) df1 = DataFrame(biz_metric_list) # 按照oper_state_name和bip_grade_name聚合,按照bip_grade_name排序 df2 = df1.groupby(["oper_state_name", "bip_grade_name"], as_index=False).count() # 自定义排序顺序,按照bip_grade_name和oper_state_name排序 df2["oper_state_name"] = df2["oper_state_name"].astype("category").cat.set_categories(OPER_STATE_NAME_ORDER) df2["bip_grade_name"] = df2["bip_grade_name"].astype("category").cat.set_categories(BIP_GRADE_NAME_ORDER) df2 = df2.dropna() df2 = df2.sort_values(by=["oper_state_name", "bip_grade_name"], ascending=True) metric_count_agg_list = df2.to_dict(orient="records") oper_state_name = [each["oper_state_name"] for each in metric_count_agg_list] bip_grade_name = [each["bip_grade_name"] for each in metric_count_agg_list] dataset_count = [each["dataset_id"] for each in metric_count_agg_list] df3 = df1.groupby(["oper_state_name", "bip_grade_name", "bk_biz_id"], as_index=False).count() df4 = df3.groupby(["oper_state_name", "bip_grade_name"], as_index=False).count() # 自定义排序顺序,按照bip_grade_name和oper_state_name排序 df4["oper_state_name"] = df4["oper_state_name"].astype("category").cat.set_categories(OPER_STATE_NAME_ORDER) df4["bip_grade_name"] = df4["bip_grade_name"].astype("category").cat.set_categories(BIP_GRADE_NAME_ORDER) df4 = df4.dropna() df4 = df4.sort_values(by=["oper_state_name", "bip_grade_name"], ascending=True) count_agg_list = df4.to_dict(orient="records") biz_count = [each["dataset_id"] for each in count_agg_list] return Response( { "oper_state_name": oper_state_name, "bip_grade_name": bip_grade_name, "dataset_count": dataset_count, "biz_count": biz_count, } ) class QueryCountDistributionView(APIViewSet): @list_route(methods=["post"], url_path="distribution_filter") @params_valid(serializer=DataValueSerializer) def day_query_count_distribution_filter(self, request, params): """ @api {get} /datamanage/datastocktake/day_query_count/distribution_filter/ 每日查询次数分布情况 @apiVersion 0.1.0 @apiGroup QueryCountDistributionView @apiName day_query_count_distribution """ # 从redis拿到热度、广度相关明细数据 metric_list = cache.get("data_value_stocktake") platform = params.get("platform", "all") if (not metric_list) or platform == "tdw": return Response({"x": [], "y": [], "z": []}) has_filter_cond, filter_dataset_dict = dataset_filter(params, request) if has_filter_cond and not filter_dataset_dict: return Response({"x": [], "y": [], "z": []}) num_list = [] for each in metric_list: if not filter_dataset_dict or each["dataset_id"] in filter_dataset_dict: num_list.append(int(each["query_count"] / 7.0)) # num_list = [int(each['query_count']/7.0) for each in metric_list] x = [ "0", "1", "2", "3", "4", "5", "5-10", "10-20", "20-30", "30-40", "40-50", "50-100", "100-500", "500-1000", "1000-5000", ">5000", ] bins = [0, 1, 2, 3, 4, 5, 10, 20, 30, 40, 50, 100, 500, 1000, 5000, np.inf] score_cat = pd.cut(num_list, bins, right=False) bin_result_list = pd.value_counts(score_cat, sort=False).values.tolist() sum_count = len(metric_list) z = [round(each / float(sum_count), 7) for each in bin_result_list] return Response({"x": x, "y": bin_result_list, "z": z}) class ApplicationDistributionView(APIViewSet): @list_route(methods=["post"], url_path="biz_count_distribution_filter") @params_valid(serializer=DataValueSerializer) def biz_count_distribution_filter(self, request, params): """ @api {get} /datamanage/datastocktake/application/biz_count_distribution_filter/ @apiVersion 0.1.0 @apiGroup ApplicationDistributionView @apiName biz_count_distribution """ # 从redis拿到热度、广度相关明细数据 metric_list = cache.get("data_value_stocktake") platform = params.get("platform", "all") if (not metric_list) or platform == "tdw": return Response({"x": [], "y": [], "z": []}) has_filter_cond, filter_dataset_dict = dataset_filter(params, request) if has_filter_cond and not filter_dataset_dict: return Response({"x": [], "y": [], "z": []}) biz_count_tmp_list = [] for each in metric_list: if not filter_dataset_dict or each["dataset_id"] in filter_dataset_dict: biz_count_tmp_list.append( { "dataset_id": each["dataset_id"], "biz_count": each["biz_count"] if each["biz_count"] else 1, } ) df1 = DataFrame(biz_count_tmp_list) df2 = df1.groupby("biz_count", as_index=False).count().sort_values(["biz_count"], axis=0, ascending=True) biz_count_agg_list
"""Command line interface for osxphotos """ import csv import datetime import json import os import os.path import pathlib import pprint import sys import time import unicodedata import click import osxmetadata import yaml import osxphotos from ._constants import ( _EXIF_TOOL_URL, _OSXPHOTOS_NONE_SENTINEL, _PHOTOS_4_VERSION, _UNKNOWN_PLACE, CLI_COLOR_ERROR, CLI_COLOR_WARNING, DEFAULT_EDITED_SUFFIX, DEFAULT_JPEG_QUALITY, DEFAULT_ORIGINAL_SUFFIX, EXTENDED_ATTRIBUTE_NAMES, EXTENDED_ATTRIBUTE_NAMES_QUOTED, OSXPHOTOS_EXPORT_DB, OSXPHOTOS_URL, SIDECAR_EXIFTOOL, SIDECAR_JSON, SIDECAR_XMP, UNICODE_FORMAT, ) from ._version import __version__ from .cli_help import ExportCommand from .configoptions import ( ConfigOptions, ConfigOptionsInvalidError, ConfigOptionsLoadError, ) from .datetime_formatter import DateTimeFormatter from .exiftool import get_exiftool_path from .export_db import ExportDB, ExportDBInMemory from .fileutil import FileUtil, FileUtilNoOp from .path_utils import is_valid_filepath, sanitize_filename, sanitize_filepath from .photoinfo import ExportResults from .photokit import check_photokit_authorization, request_photokit_authorization from .utils import get_preferred_uti_extension # global variable to control verbose output # set via --verbose/-V VERBOSE = False def verbose_(*args, **kwargs): """ print output if verbose flag set """ if VERBOSE: styled_args = [] for arg in args: if type(arg) == str: if "error" in arg.lower(): arg = click.style(arg, fg=CLI_COLOR_ERROR) elif "warning" in arg.lower(): arg = click.style(arg, fg=CLI_COLOR_WARNING) styled_args.append(arg) click.echo(*styled_args, **kwargs) def normalize_unicode(value): """ normalize unicode data """ if value is not None: if isinstance(value, tuple): return tuple(unicodedata.normalize(UNICODE_FORMAT, v) for v in value) elif isinstance(value, str): return unicodedata.normalize(UNICODE_FORMAT, value) else: return value else: return None def get_photos_db(*db_options): """Return path to photos db, select first non-None db_options If no db_options are non-None, try to find library to use in the following order: - last library opened - system library - ~/Pictures/Photos Library.photoslibrary - failing above, returns None """ if db_options: for db in db_options: if db is not None: return db # if get here, no valid database paths passed, so try to figure out which to use db = osxphotos.utils.get_last_library_path() if db is not None: click.echo(f"Using last opened Photos library: {db}", err=True) return db db = osxphotos.utils.get_system_library_path() if db is not None: click.echo(f"Using system Photos library: {db}", err=True) return db db = os.path.expanduser("~/Pictures/Photos Library.photoslibrary") if os.path.isdir(db): click.echo(f"Using Photos library: {db}", err=True) return db else: return None class DateTimeISO8601(click.ParamType): name = "DATETIME" def convert(self, value, param, ctx): try: return datetime.datetime.fromisoformat(value) except Exception: self.fail( f"Invalid value for --{param.name}: invalid datetime format {value}. " "Valid format: YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]]" ) class TimeISO8601(click.ParamType): name = "TIME" def convert(self, value, param, ctx): try: return datetime.time.fromisoformat(value).replace(tzinfo=None) except Exception: self.fail( f"Invalid value for --{param.name}: invalid time format {value}. " "Valid format: HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]] " "however, note that timezone will be ignored." ) # Click CLI object & context settings class CLI_Obj: def __init__(self, db=None, json=False, debug=False): if debug: osxphotos._set_debug(True) self.db = db self.json = json CTX_SETTINGS = dict(help_option_names=["-h", "--help"]) DB_OPTION = click.option( "--db", required=False, metavar="<Photos database path>", default=None, help=( "Specify Photos database path. " "Path to Photos library/database can be specified using either --db " "or directly as PHOTOS_LIBRARY positional argument. " "If neither --db or PHOTOS_LIBRARY provided, will attempt to find the library " "to use in the following order: 1. last opened library, 2. system library, 3. ~/Pictures/Photos Library.photoslibrary" ), type=click.Path(exists=True), ) DB_ARGUMENT = click.argument("photos_library", nargs=-1, type=click.Path(exists=True)) JSON_OPTION = click.option( "--json", "json_", required=False, is_flag=True, default=False, help="Print output in JSON format.", ) def deleted_options(f): o = click.option options = [ o( "--deleted", is_flag=True, help="Include photos from the 'Recently Deleted' folder.", ), o( "--deleted-only", is_flag=True, help="Include only photos from the 'Recently Deleted' folder.", ), ] for o in options[::-1]: f = o(f) return f def query_options(f): o = click.option options = [ o( "--keyword", metavar="KEYWORD", default=None, multiple=True, help="Search for photos with keyword KEYWORD. " 'If more than one keyword, treated as "OR", e.g. find photos matching any keyword', ), o( "--person", metavar="PERSON", default=None, multiple=True, help="Search for photos with person PERSON. " 'If more than one person, treated as "OR", e.g. find photos matching any person', ), o( "--album", metavar="ALBUM", default=None, multiple=True, help="Search for photos in album ALBUM. " 'If more than one album, treated as "OR", e.g. find photos matching any album', ), o( "--folder", metavar="FOLDER", default=None, multiple=True, help="Search for photos in an album in folder FOLDER. " 'If more than one folder, treated as "OR", e.g. find photos in any FOLDER. ' "Only searches top level folders (e.g. does not look at subfolders)", ), o( "--name", metavar="FILENAME", default=None, multiple=True, help="Search for photos with filename matching FILENAME. " 'If more than one --name options is specified, they are treated as "OR", ' "e.g. find photos matching any FILENAME. ", ), o( "--uuid", metavar="UUID", default=None, multiple=True, help="Search for photos with UUID(s).", ), o( "--uuid-from-file", metavar="FILE", default=None, multiple=False, help="Search for photos with UUID(s) loaded from FILE. " "Format is a single UUID per line. Lines preceded with # are ignored.", type=click.Path(exists=True), ), o( "--title", metavar="TITLE", default=None, multiple=True, help="Search for TITLE in title of photo.", ), o("--no-title", is_flag=True, help="Search for photos with no title."), o( "--description", metavar="DESC", default=None, multiple=True, help="Search for DESC in description of photo.", ), o( "--no-description", is_flag=True, help="Search for photos with no description.", ), o( "--place", metavar="PLACE", default=None, multiple=True, help="Search for PLACE in photo's reverse geolocation info", ), o( "--no-place", is_flag=True, help="Search for photos with no associated place name info (no reverse geolocation info)", ), o( "--label", metavar="LABEL", multiple=True, help="Search for photos with image classification label LABEL (Photos 5 only). " 'If more than one label, treated as "OR", e.g. find photos matching any label', ), o( "--uti", metavar="UTI", default=None, multiple=False, help="Search for photos whose uniform type identifier (UTI) matches UTI", ), o( "-i", "--ignore-case", is_flag=True, help="Case insensitive search for title, description, place, keyword, person, or album.", ), o("--edited", is_flag=True, help="Search for photos that have been edited."), o( "--external-edit", is_flag=True, help="Search for photos edited in external editor.", ), o("--favorite", is_flag=True, help="Search for photos marked favorite."), o( "--not-favorite", is_flag=True, help="Search for photos not marked favorite.", ), o("--hidden", is_flag=True, help="Search for photos marked hidden."), o("--not-hidden", is_flag=True, help="Search for photos not marked hidden."), o( "--shared", is_flag=True, help="Search for photos in shared iCloud album (Photos 5 only).", ), o( "--not-shared", is_flag=True, help="Search for photos not in shared iCloud album (Photos 5 only).", ), o( "--burst", is_flag=True, help="Search for photos that were taken in a burst.", ), o( "--not-burst", is_flag=True, help="Search for photos that are not part of a burst.", ), o("--live", is_flag=True, help="Search for Apple live photos"), o( "--not-live", is_flag=True, help="Search for photos that are not Apple live photos.", ), o("--portrait", is_flag=True, help="Search for Apple portrait mode photos."), o( "--not-portrait", is_flag=True, help="Search for photos that are not Apple portrait mode photos.", ), o("--screenshot", is_flag=True, help="Search for screenshot photos."), o( "--not-screenshot", is_flag=True, help="Search for photos that are not screenshot photos.", ), o("--slow-mo", is_flag=True, help="Search for slow motion videos."), o( "--not-slow-mo", is_flag=True, help="Search for photos that are not slow motion videos.", ), o("--time-lapse", is_flag=True, help="Search for time lapse videos."), o( "--not-time-lapse", is_flag=True, help="Search for photos that are not time lapse videos.", ), o("--hdr", is_flag=True, help="Search for high dynamic range (HDR) photos."), o("--not-hdr", is_flag=True, help="Search for photos that are not HDR photos."), o( "--selfie", is_flag=True, help="Search for selfies (photos taken with front-facing cameras).", ), o("--not-selfie", is_flag=True, help="Search for photos that are not selfies."), o("--panorama", is_flag=True, help="Search for panorama photos."), o( "--not-panorama", is_flag=True, help="Search for photos that are not panoramas.", ), o( "--has-raw", is_flag=True, help="Search for photos with both a jpeg and raw version", ), o( "--only-movies", is_flag=True, help="Search only for movies (default searches both images and movies).", ), o( "--only-photos", is_flag=True, help="Search only for photos/images (default searches both images and movies).", ), o( "--from-date", help="Search by item start date, e.g. 2000-01-12T12:00:00, 2001-01-12T12:00:00-07:00, or 2000-12-31 (ISO 8601 with/without timezone).", type=DateTimeISO8601(), ), o( "--to-date", help="Search by item end date, e.g. 2000-01-12T12:00:00, 2001-01-12T12:00:00-07:00, or 2000-12-31 (ISO 8601 with/without timezone).", type=DateTimeISO8601(), ), o( "--from-time", help="Search by item start time of day, e.g. 12:00, or 12:00:00.", type=TimeISO8601(), ), o( "--to-time", help="Search by item end time of day, e.g. 12:00 or 12:00:00.", type=TimeISO8601(), ), o("--has-comment", is_flag=True, help="Search for photos that have comments."), o("--no-comment", is_flag=True, help="Search for photos with no comments."), o("--has-likes", is_flag=True, help="Search for photos that have likes."), o("--no-likes", is_flag=True, help="Search for photos with no likes."), o( "--is-reference", is_flag=True, help="Search for photos that were imported as referenced files (not copied into Photos library).", ), o( "--in-album", is_flag=True, help="Search for photos that are in one or more albums.", ), o( "--not-in-album", is_flag=True, help="Search for photos
from collections import OrderedDict import itertools from typing import Any, Generator, List, Optional, Type from typing import OrderedDict as ODict # Prevent naming conflicts import bpy.types from bpy.props import * from nodeitems_utils import NodeItem from arm.logicnode.arm_sockets import ArmCustomSocket import arm # we cannot import arm.livepatch here or we have a circular import # Pass custom property types and NodeReplacement forward to individual # node modules that import arm_nodes from arm.logicnode.arm_props import * from arm.logicnode.replacement import NodeReplacement import arm.node_utils if arm.is_reload(__name__): arm.logicnode.arm_props = arm.reload_module(arm.logicnode.arm_props) from arm.logicnode.arm_props import * arm.logicnode.replacement = arm.reload_module(arm.logicnode.replacement) from arm.logicnode.replacement import NodeReplacement arm.node_utils = arm.reload_module(arm.node_utils) else: arm.enable_reload(__name__) # When passed as a category to add_node(), this will use the capitalized # name of the package of the node as the category to make renaming # categories easier. PKG_AS_CATEGORY = "__pkgcat__" nodes = [] category_items: ODict[str, List['ArmNodeCategory']] = OrderedDict() array_nodes = dict() # See ArmLogicTreeNode.update() # format: [tree pointer => (num inputs, num input links, num outputs, num output links)] last_node_state: dict[int, tuple[int, int, int, int]] = {} class ArmLogicTreeNode(bpy.types.Node): arm_category = PKG_AS_CATEGORY arm_section = 'default' arm_is_obsolete = False def init(self, context): # make sure a given node knows the version of the NodeClass from when it was created if isinstance(type(self).arm_version, int): self.arm_version = type(self).arm_version else: self.arm_version = 1 if not hasattr(self, 'arm_init'): # Show warning for older node packages arm.log.warn(f'Node {self.bl_idname} has no arm_init function and might not work correctly!') else: self.arm_init(context) arm.live_patch.send_event('ln_create', self) @classmethod def poll(cls, ntree): return ntree.bl_idname == 'ArmLogicTreeType' @classmethod def on_register(cls): """Don't call this method register() as it will be triggered before Blender registers the class, resulting in a double registration.""" add_node(cls, cls.arm_category, cls.arm_section, cls.arm_is_obsolete) @classmethod def on_unregister(cls): pass def get_tree(self): return self.id_data def update(self): """Called if the node was updated in some way, for example if socket connections change. This callback is not called if socket values were changed. """ def num_connected(sockets): return sum([socket.is_linked for socket in sockets]) # If a link between sockets is removed, there is currently no # _reliable_ way in the Blender API to check which connection # was removed (*). # # So instead we just check _if_ the number of links or sockets # has changed (the update function is called before and after # each link removal). Because we listen for those updates in # general, we automatically also listen to link creation events, # which is more stable than using the dedicated callback for # that (`insert_link()`), because adding links can remove other # links and we would need to react to that as well. # # (*) https://devtalk.blender.org/t/how-to-detect-which-link-was-deleted-by-user-in-node-editor self_id = self.as_pointer() current_state = (len(self.inputs), num_connected(self.inputs), len(self.outputs), num_connected(self.outputs)) if self_id not in last_node_state: # Lazily initialize the last_node_state dict to also store # state for nodes that already exist in the tree last_node_state[self_id] = current_state if last_node_state[self_id] != current_state: arm.live_patch.send_event('ln_update_sockets', self) last_node_state[self_id] = current_state def free(self): """Called before the node is deleted.""" arm.live_patch.send_event('ln_delete', self) def copy(self, node): """Called if the node was copied. `self` holds the copied node, `node` the original one. """ arm.live_patch.send_event('ln_copy', (self, node)) def on_prop_update(self, context: bpy.types.Context, prop_name: str): """Called if a property created with a function from the arm_props module is changed. If the property has a custom update function, it is called before `on_prop_update()`. """ arm.live_patch.send_event('ln_update_prop', (self, prop_name)) def on_socket_val_update(self, context: bpy.types.Context, socket: bpy.types.NodeSocket): arm.live_patch.send_event('ln_socket_val', (self, socket)) def insert_link(self, link: bpy.types.NodeLink): """Called on *both* nodes when a link between two nodes is created.""" # arm.live_patch.send_event('ln_insert_link', (self, link)) pass def get_replacement_node(self, node_tree: bpy.types.NodeTree): # needs to be overridden by individual node classes with arm_version>1 """(only called if the node's version is inferior to the node class's version) Help with the node replacement process, by explaining how a node (`self`) should be replaced. This method can either return a NodeReplacement object (see `nodes_logic.py`), or a brand new node. If a new node is returned, then the following needs to be already set: - the node's links to the other nodes - the node's properties - the node inputs's default values If more than one node need to be created (for example, if an input needs a type conversion after update), please return all the nodes in a list. please raise a LookupError specifically when the node's version isn't handled by the function. note that the lowest 'defined' version should be 1. if the node's version is 0, it means that it has been saved before versioning was a thing. NODES OF VERSION 1 AND VERSION 0 SHOULD HAVE THE SAME CONTENTS """ if self.arm_version == 0 and type(self).arm_version == 1: # In case someone doesn't implement this function, but the node has version 0 return NodeReplacement.Identity(self) else: raise LookupError(f"the current node class {repr(type(self)):s} does not implement get_replacement_node() even though it has updated") def add_input(self, socket_type: str, socket_name: str, default_value: Any = None, is_var: bool = False) -> bpy.types.NodeSocket: """Adds a new input socket to the node. If `is_var` is true, a dot is placed inside the socket to denote that this socket can be used for variable access (see SetVariable node). """ socket = self.inputs.new(socket_type, socket_name) if default_value is not None: if isinstance(socket, ArmCustomSocket): if socket.arm_socket_type != 'NONE': socket.default_value_raw = default_value else: raise ValueError('specified a default value for an input node that doesn\'t accept one') else: # should not happen anymore? socket.default_value = default_value if is_var and not socket.display_shape.endswith('_DOT'): socket.display_shape += '_DOT' return socket def add_output(self, socket_type: str, socket_name: str, default_value: Any = None, is_var: bool = False) -> bpy.types.NodeSocket: """Adds a new output socket to the node. If `is_var` is true, a dot is placed inside the socket to denote that this socket can be used for variable access (see SetVariable node). """ socket = self.outputs.new(socket_type, socket_name) # FIXME: …a default_value on an output socket? Why is that a thing? if default_value is not None: if socket.arm_socket_type != 'NONE': socket.default_value_raw = default_value else: raise ValueError('specified a default value for an input node that doesn\'t accept one') if is_var and not socket.display_shape.endswith('_DOT'): socket.display_shape += '_DOT' return socket class ArmNodeAddInputButton(bpy.types.Operator): """Add a new input socket to the node set by node_index.""" bl_idname = 'arm.node_add_input' bl_label = 'Add Input' bl_options = {'UNDO', 'INTERNAL'} node_index: StringProperty(name='Node Index', default='') socket_type: StringProperty(name='Socket Type', default='ArmDynamicSocket') name_format: StringProperty(name='Name Format', default='Input {0}') index_name_offset: IntProperty(name='Index Name Offset', default=0) def execute(self, context): global array_nodes inps = array_nodes[self.node_index].inputs socket_types = self.socket_type.split(';') name_formats = self.name_format.split(';') assert len(socket_types)==len(name_formats) format_index = (len(inps) + self.index_name_offset) //len(socket_types) for socket_type, name_format in zip(socket_types, name_formats): inps.new(socket_type, name_format.format(str(format_index))) # Reset to default again for subsequent calls of this operator self.node_index = '' self.socket_type = 'ArmDynamicSocket' self.name_format = 'Input {0}' self.index_name_offset = 0 return{'FINISHED'} class ArmNodeAddInputValueButton(bpy.types.Operator): """Add new input""" bl_idname = 'arm.node_add_input_value' bl_label = 'Add Input' bl_options = {'UNDO', 'INTERNAL'} node_index: StringProperty(name='Node Index', default='') socket_type: StringProperty(name='Socket Type', default='ArmDynamicSocket') def execute(self, context): global array_nodes inps = array_nodes[self.node_index].inputs inps.new(self.socket_type, 'Value') return{'FINISHED'} class ArmNodeRemoveInputButton(bpy.types.Operator): """Remove last input""" bl_idname = 'arm.node_remove_input' bl_label = 'Remove Input' bl_options = {'UNDO', 'INTERNAL'} node_index: StringProperty(name='Node Index', default='') count: IntProperty(name='Number of inputs to remove', default=1, min=1) min_inputs: IntProperty(name='Number of inputs to keep', default=0, min=0) def execute(self, context): global array_nodes node = array_nodes[self.node_index] inps = node.inputs min_inps = self.min_inputs if not hasattr(node, 'min_inputs') else node.min_inputs if len(inps) >= min_inps + self.count: for _ in range(self.count): inps.remove(inps.values()[-1]) return{'FINISHED'} class ArmNodeRemoveInputValueButton(bpy.types.Operator): """Remove last input""" bl_idname = 'arm.node_remove_input_value' bl_label = 'Remove Input' bl_options = {'UNDO', 'INTERNAL'} node_index: StringProperty(name='Node Index', default='') target_name: StringProperty(name='Name of socket to remove', default='Value') def execute(self, context): global array_nodes node = array_nodes[self.node_index] inps = node.inputs min_inps = 0 if not hasattr(node, 'min_inputs') else node.min_inputs if len(inps) > min_inps and inps[-1].name == self.target_name: inps.remove(inps.values()[-1]) return{'FINISHED'} class ArmNodeAddOutputButton(bpy.types.Operator): """Add a new output socket to the node set by node_index""" bl_idname = 'arm.node_add_output' bl_label = 'Add Output' bl_options = {'UNDO', 'INTERNAL'} node_index: StringProperty(name='Node Index', default='') socket_type: StringProperty(name='Socket Type', default='ArmDynamicSocket') name_format: StringProperty(name='Name Format', default='Output {0}') index_name_offset: IntProperty(name='Index Name Offset', default=0) def execute(self, context): global array_nodes outs = array_nodes[self.node_index].outputs socket_types = self.socket_type.split(';') name_formats = self.name_format.split(';') assert len(socket_types)==len(name_formats) format_index = (len(outs) + self.index_name_offset) //len(socket_types) for socket_type, name_format
then should new joins be allowed. Args: roomNum (int): Index in request[rooms] for target room. seatNum (int): Target seat number. """ roomNum = int(roomNum) # Arg `roomNum` is sent as unicode from browser room = self.getRoomByNumber(roomNum) if room is None: self.emit('err', 'That room does not exist.') return elif room.isFull(): self.emit('err', 'That room is full.') return else: try: self.moveToRoom(roomNum=roomNum, seat=seatNum) except Exception as e: log.debug('err in on_join({1}, {2}): {0}'.format( repr(e), roomNum, seatNum)) self.emit('err', repr(e)) return # If the room is now full, begin or resume the game. if room.isFull(): self.emit_to_room('roomFull', roomNum) self.emit_to_target_room(LOBBY, 'roomFull', roomNum) # Without this Timer, the last person to join will receive # start data before room data and will not have confirmed # their seat/pNum. if room.started: t = Timer(0.5, self.joinInProgress, [room, seatNum, self.session['nickname']]) else: t = Timer(0.5, room.startGame) t.start() log.debug('%s joined room %s.', self.session['nickname'], roomNum) return dict(roomNum=roomNum, seatChart=room.getSeatingChart(), mySeat=seatNum) def joinInProgress(self, room, seatNum, nickname): """Facilitate a player joining a game in progress.""" if not room.started: log.error("joinInProgress fired for a game not yet started") return initData = room.game.join_game_in_progress(seatNum, nickname) self.emit('startData', initData) def on_exit(self): """Handle socket request to leave current room. This method takes an argument to maintain client compatibility. Leaving the room should result in the following outcomes: - If the client is in a game room, they should move to the Lobby. This may affect the visibility of the room in the Lobby. This may affect the continued existence of the room (if empty). Departure will be announced. - If the client is in the Lobby, they should leave the Lobby and go nowhere. Departure will be announced. - If the client is nowhere, they should remain there. This probably marks the end of the socket connection. """ curRoomNum = self.session['roomNum'] if curRoomNum == LOBBY or curRoomNum is None: # Simply leave the room self._leaveRoom() return curRoom = self.getRoomByNumber(curRoomNum) # Client is wanting to leave a game room. If room is full before user # leaves, tell Lobby room is no longer full. if curRoom.isFull(): self.emit_to_room('roomNotFull', curRoomNum) self.emit_to_target_room(LOBBY, 'roomNotFull', curRoomNum) # The Lobby will want to know what seat is becoming available self.emit_to_target_room( LOBBY, 'exit', self.session['nickname'], curRoomNum, self.session['seat']) self._leaveRoom() # If room is now empty, remove the room and notify clients. # NOTE: this doesn't affect the actual room object, only its # availability to clients; this may be a memory leak. TODO investigate. if len(curRoom.getUsers()) == 0 and curRoomNum != LOBBY: self.request['rooms'].remove(curRoom) self.broadcast_event('roomGone', curRoom.num) log.debug('%s left room %s; placing in lobby.', self.session['nickname'], curRoomNum) self.moveToRoom(roomNum=LOBBY, seat=0) def on_room_list(self): """Transmit list of available rooms and their occupants. Exclude the Lobby, because we don't want it in the list of rooms to be joined. Remove `if x.num != LOBBY` if you want the Lobby to be included. """ roomList = [{'name': str(x), 'num': x.num, 'isFull': x.isFull(), 'started': x.started, 'seatChart': x.getSeatingChart()} for x in self.request['rooms'] if x.num != LOBBY] # Not using callback as to support recv_connect # TODO: have all clients send a connection message when they start # instead of relying on recv_connect. self.emit('rooms', roomList) def on_chat(self, message): """Transmit chat message to room, including nickname of sender. If the client desires different formatting for messages that it sent, the client should compare its nickname to that of the chat message. The server sends the same data to all clients in the room. Args: message (string): Chat string from client. """ if 'nickname' in self.session: self.emit_to_room('chat', [self.session['nickname'], message]) else: self.emit('err', 'You must set a nickname first') def on_createRoom(self, args): """Create new room and announce new room's existence to clients. Args: args (dict, optional): {seat: ai_model_id, seat2: ...} """ # 'rooms' is list of Room objects roomNum = self.request['curMaxRoomNum'] + 1 self.request['curMaxRoomNum'] += 1 newRoom = Room(roomNum) self.request['rooms'].append(newRoom) # store new room in Server self.emit_to_target_room( LOBBY, 'newRoom', {'name': str(newRoom), 'num': roomNum, 'started': False, 'isFull': newRoom.isFull(), 'seatChart': []}) # Summon AI players try: for seat in args.keys(): self.emit_to_target_room( LOBBY, 'summonAI', {roomNum: (int(seat), int(args[seat]))}) except AttributeError: pass # No args given return roomNum # Tells user to join room def on_nickname(self, name): """Set nickname for user. The nickname cannot be changed while the user is in a room other than the lobby. This is to protect the integrity of any game logging done. FUTURE: Prevent multiple users from having same nickname. Will need to show error message to client on username entry screen. Args: name (string): Desired nickname. """ if self.session['roomNum'] > LOBBY: self.emit('err', 'You cannot change names while in a game') return None else: self.session['nickname'] = name return name def localhost_only(func): """Decoration function for limiting access to localhost.""" def _localhost_only(self, *args, **kwargs): local_hosts = set(['127.0.0.1', '::ffff:127.0.0.1', '::1']) if self.environ['REMOTE_ADDR'] not in local_hosts: log.warning('Remote address {0} tried to call local-only ' 'method {1}'.format(self.environ['REMOTE_ADDR'], str(func))) return else: return func(self, *args, **kwargs) return _localhost_only @localhost_only def on_killRoom(self, roomNum): """Evict all players from a room. Only works from localhost.""" room = self.getRoomByNumber(int(roomNum)) if room: for x in room.getUsers(): x[SOCKETIO_NS].on_exit() return roomNum else: return None # -------------------- # AI methods # -------------------- def on_aiList(self): """Provide client with list of available AIs and their information.""" return self.request['aiInfo'] def on_aiListData(self, data): """Receive AI identity information from AI manager.""" self.request['aiInfo'] = data def on_summonAI(self, model, roomNum, seat): """Human client has requested an AI agent for a game room.""" log.debug("AI model {0} summoned for Room {1} Seat {2}".format( model, roomNum, seat)) self.emit_to_target_room(LOBBY, 'summonAI', {roomNum: (seat, model)}) @localhost_only def on_aiOnlyGame(self, seatMap): """Run AI-only game (4x AI). Args: seatMap (list): A list of the AI agent models for each game seat. The indexes of the model numbers match the seat numbers. """ seatMap = map(int, seatMap) seats = map(unicode, range(len(seatMap))) args = dict(zip(seats, seatMap)) return self.on_createRoom(args) # -------------------- # Game methods # -------------------- def on_bid(self, bid): """Relay bid to game. Args: bid (str): Bid amount. Must be a number. """ g = self.getRoomByNumber(self.session['roomNum']).game if 'seat' in self.session: pNum = self.session['seat'] else: # Handle clients bidding while not seated. self.emit('err', 'No seat assigned; bidding not allowed.') log.warning('Non-seated client "%s" sent bid %s', self.session['nickname'], bid) return res = g.handle_bid(pNum, int(bid)) # False on bad bid, None for inactive player if res is False: self.emit('err', 'Bad bid: {0}'.format(bid)) elif res is None: self.emit('err', "It's not your turn") else: self.emit_to_room('bid', res) def on_play(self, play): """Relay play to game. Args: play (str): Card code. Must be a number. """ g = self.getRoomByNumber(self.session['roomNum']).game if 'seat' in self.session: pNum = self.session['seat'] else: # Handle clients playing while not seated. self.emit('err', 'No seat assigned; playing not allowed.') log.warning('Non-seated client "%s" sent play %s', self.session['nickname'], play) return res = g.handle_card_played(pNum, int(play)) # False on bad play, None for inactive player if res is False: log.debug("on_play: illegal play attempted in seat " + str(pNum)) self.emit('err', 'Bad play: {0}'.format(play)) elif res is None: self.emit('err', "It's not your turn") else: # Multiple messages == distinct messages; happens at end of hand if type(res) == list: target_sock_map = {s.session['seat']: s[SOCKETIO_NS] for s in self.getRoomByNumber( self.session['roomNum']).getUsers()} for msg in res: target_sock_map[msg['tgt']].emit('play', msg) else: self.emit_to_room('play', res) # -------------------- # Game log methods # -------------------- def on_game_log(self, gameId): """Return parsed game log for game with id=gameId. Args: gameId (int): ID of target game. Returns: dict: Prepared game log data. """ gameData = db(db.Games.id == gameId).select().first() events = db(db.Events.game_id == gameId).select() return parseLog.prepare(gameData, events) def on_log_list(self): """Retrieve list of available game logs. Returns: list: Each list item is a dict with keys (name, id). """ return db(db.Games.id > 0).select().as_list() # -------------------- # Helper methods # -------------------- def emit_to_room(self, event, *args, **kwargs): """Send message to all users in sender's room. Args: event (string): Command name for message (e.g. 'chat', 'users', 'ack'). args (list): Args for command specified by event. kwargs (dict): Keyword args passed to emit_to_target_room. """ self.emit_to_target_room( self.session['roomNum'], event, *args, **kwargs) def emit_to_room_not_me(self, event, *args, **kwargs): """Send message to all users in sender's room except sender itself. This
The protocol returned by `protocol_factory`. Raises ------ ValueError - If `server_host_name` parameter is given, but `ssl` isn't. - If `ssl` parameter is given, but `server_host_name` is not. - If `socket`'s is not an unix domain stream socket. NotImplementedError Not supported on windows by the library. """ ssl, server_host_name = self._create_unix_connection_shared_precheck(ssl, server_host_name) if socket.family not in (module_socket.AF_UNIX, module_socket.SOCK_STREAM): raise ValueError(f'A unix domain stream `socket` was expected, got {socket!r}.') socket.setblocking(False) return await self._create_connection_transport(socket, protocol_factory, ssl, server_host_name, False) async def open_unix_connection_to(self, path, *, ssl=None, server_host_name=None): """ Creates an unix connection. This method is a coroutine. Parameters ---------- path : `str` The path to open connection to. ssl : `None`, `SSLContext` = `None`, Optional (Keyword only) Whether ssl should be enabled. server_host_name : `None`, `str` = `None`, Optional (Keyword only) Overwrites the hostname that the target server’s certificate will be matched against. Should only be passed if `ssl` is not `None`. Returns ------- protocol : ``BaseProtocol`` The connected read and write protocol. Raises ------ ValueError - If `server_host_name` parameter is given, but `ssl` isn't. - If `ssl` parameter is given, but `server_host_name` is not. NotImplementedError Not supported on windows by the library. """ return await self.create_unix_connection_to( partial_func(ReadWriteProtocolBase, self), path, ssl = ssl, server_host_name = server_host_name, ) async def open_unix_connection_with(self, socket, *, ssl=None, server_host_name=None): """ Creates an unix connection. This method is a coroutine. Parameters ---------- socket : `socket.socket` A preexisting socket object to use up. ssl : `None`, `SSLContext` = `None`, Optional (Keyword only) Whether ssl should be enabled. server_host_name : `None`, `str` = `None`, Optional (Keyword only) Overwrites the hostname that the target server’s certificate will be matched against. Should only be passed if `ssl` is not `None`. Returns ------- protocol : ``BaseProtocol`` The connected read and write protocol. Raises ------ ValueError - If `server_host_name` parameter is given, but `ssl` isn't. - If `ssl` parameter is given, but `server_host_name` is not. - If `socket`'s is not an unix domain stream socket. NotImplementedError Not supported on windows by the library. """ return await self.create_unix_connection_with( partial_func(ReadWriteProtocolBase, self), socket, ssl = ssl, server_host_name = server_host_name, ) def _create_unix_server_shared_precheck(self, ssl): """ Shared precheck used by ``.create_unix_server_to`` and ``.create_unix_server_with``. Parameters ---------- ssl : `None`, `SSLContext` Whether ssl should be enabled. Returns ------- ssl : ``None`, `SSLContext` """ if (ssl is not None) and (not isinstance(ssl, SSLContext)): raise TypeError(f'`ssl` can be `None`, `SSLContext`, got {ssl.__class__.__name__}.') return ssl async def create_unix_server_to(self, protocol_factory, path, *, backlog=100, ssl=None): """ Creates an unix server (socket type AF_UNIX) listening on the given path. This method is a coroutine. Parameters ---------- protocol_factory : `callable` Factory function for creating a protocols. path : `str` The path to open connection to. backlog : `int` = `100`, Optional (Keyword only) The maximum number of queued connections passed to `socket.listen()`. ssl : `None`, `SSLContext` = `None`, Optional (Keyword only) Whether and what ssl is enabled for the connections. Returns ------- server : ``Server`` The created server instance. Raises ------ TypeError - If `ssl` is not given neither as `None` nor as `SSLContext`. FileNotFoundError: The given `path` do not exists. OsError - Path already in use. - Error while attempting to connect to `path`. NotImplementedError Not supported on windows by the library. """ ssl = self._create_unix_server_shared_precheck(ssl) path = os.fspath(path) socket = module_socket.socket(module_socket.AF_UNIX, module_socket.SOCK_STREAM) # Check for abstract socket. if not path.startswith('\x00'): try: if S_ISSOCK(os.stat(path).st_mode): os.remove(path) except FileNotFoundError: pass try: socket.bind(path) except OSError as err: socket.close() if err.errno == errno.EADDRINUSE: # Let's improve the error message by adding with what exact address it occurs. raise OSError( errno.EADDRINUSE, f'Address {path!r} is already in use.' ) from None else: raise except: socket.close() raise socket.setblocking(False) return Server(self, [socket], protocol_factory, ssl, backlog) async def create_unix_server_with(self, protocol_factory, socket, *, backlog=100, ssl=None): """ Creates an unix server (socket type AF_UNIX) listening with the given socket. This method is a coroutine. Parameters ---------- protocol_factory : `callable` Factory function for creating a protocols. socket : `socket.socket` Can be specified in order to use a preexisting socket object. backlog : `int` = `100`, Optional (Keyword only) The maximum number of queued connections passed to `socket.listen()`. ssl : `None`, `SSLContext` = `None`, Optional (Keyword only) Whether and what ssl is enabled for the connections. Returns ------- server : ``Server`` The created server instance. Raises ------ TypeError - If `ssl` is not given neither as `None` nor as `SSLContext`. ValueError - If `socket` is given, but it's type is not `module_socket.SOCK_STREAM`. NotImplementedError Not supported on windows by the library. """ ssl = self._create_unix_server_shared_precheck(ssl) if socket.family not in (module_socket.AF_UNIX, module_socket.SOCK_STREAM): raise ValueError(f'A unix domain stream `socket` was expected, got {socket!r}.') socket.setblocking(False) return Server(self, [socket], protocol_factory, ssl, backlog) if not IS_UNIX: @copy_docs(create_unix_connection_to) async def create_unix_connection_to(self, protocol_factory, path, *, ssl=None, server_host_name=None): raise NotImplementedError @copy_docs(create_unix_connection_with) async def create_unix_connection_with(self, protocol_factory, socket, *, ssl=None, server_host_name=None): raise NotImplementedError @copy_docs(open_unix_connection_to) async def open_unix_connection_to(self, path, *, ssl=None, server_host_name=None): raise NotImplementedError @copy_docs(open_unix_connection_with) async def open_unix_connection_with(self, socket, *, ssl=None, server_host_name=None): raise NotImplementedError @copy_docs(create_unix_server_to) async def create_unix_server_to(self, protocol_factory, path, *, socket, backlog=100, ssl=None,): raise NotImplementedError @copy_docs(create_unix_server_with) async def create_unix_server_with(self, protocol_factory, socket, *, backlog=100, ssl=None,): raise NotImplementedError # await it def get_address_info(self, host, port, *, family=0, type=0, protocol=0, flags=0): """ Asynchronous version of `socket.getaddrinfo()`. Parameters ---------- host : `None`, `str` To respective network interface. port : `None`, `int` The port of the `host`. family : `AddressFamily`, `int` = `0`, Optional (Keyword only) The address family. type : `SocketKind`, `int` = `0`, Optional (Keyword only) Socket type. protocol : `int` = `0`, Optional (Keyword only) Protocol type. Can be used to narrow host resolution. flags : `int` = `0`, Optional (Keyword only) Can be used to narrow host resolution. Returns ------- future : ``Future`` An awaitable future, what will yield the lookup's result. Might raise `OSError` or return a `list` of `tuple`-s with the following elements: - `family` : `AddressFamily`, `int`. Address family. - `type` : `SocketKind`, `int`. Socket type. - `protocol` : `int`. Protocol type. - `canonical_name` : `str`. Represents the canonical name of the host. - `socket_address` : `tuple` (`str, `int`). Socket address containing the `host` and the `port`. """ return self.run_in_executor(alchemy_incendiary( module_socket.getaddrinfo, (host, port, family, type, protocol, flags,),)) # await it def get_name_info(self, socket_address, flags=0): """ Asynchronous version of `socket.getnameinfo()`. Parameters ---------- socket_address : `tuple` (`str`, `int`) Socket address as a tuple of `host` and `port`. flags : `int` = `0`, Optional Can be used to narrow host resolution. Returns ------- future : ``Future`` An awaitable future, what will yield the lookup's result. """ return self.run_in_executor(alchemy_incendiary(module_socket.getnameinfo, (socket_address, flags,),)) def _ensure_resolved(self, address, *, family=0, type=module_socket.SOCK_STREAM, protocol=0, flags=0): """ Ensures, that the given address is already a resolved IP. If not, gets it's address. Parameters ---------- address : `tuple` ((`None`, `str`), (`None`, `int`)) Address as a tuple of `host` and `port`. family : `AddressFamily`, `int` = `0`, Optional (Keyword only) The address family. type : `SocketKind`, `int` = `module_socket.SOCK_STREAM`, Optional Socket type. protocol : `int` = `0`, Optional Protocol type. Can be used to narrow host resolution. flags : `int` = `0`, Optional Can be used to narrow host resolution. Returns ------- future : ``Future`` An awaitable future, what returns a `list` of `tuples` with the following elements: - `family` : `AddressFamily`, `int`. Address family. - `type` : `SocketKind`, `int`. Socket type. - `protocol` : `int`. Protocol type. - `canonical_name` : `str`. Represents the canonical name of the host. - `socket_address` : `tuple` (`str, `int`). Socket address containing the `host` and the `port`. Might raise `OSError` as well. """ # Address
], service_endpoint=self.context.settings.get( "default_endpoint") ) ], ) # Create create-did message create_did_message = CreateDIDMessage( from_did=from_did.did, to_did=to_did.did, created_time=round(time.time() * 1000), body=did_doc ) # Sign did doc using local did verkey to prove ownership await create_did_message.sign_field("body", local_did_record.verkey, wallet, timestamp=time.time()) # Create transaction record transaction_record = MyDataDIDRegistryDIDCommTransactionRecord( thread_id=create_did_message._id, message_type=MyDataDIDRegistryDIDCommTransactionRecord.MESSAGE_TYPE_CREATE_DID, messages_list=[create_did_message.to_json()], connection_id=connection_record.connection_id, ) # Save transaction record await transaction_record.save(self.context, reason="Sending create-did message to MyData DID Registry") # Send create-did message to MyData DID Registry responder: BaseResponder = await self.context.inject(BaseResponder, required=False) if responder: await responder.send(create_did_message, connection_id=connection_record.connection_id) return transaction_record async def process_read_did_message(self, read_did_message: ReadDIDMessage, receipt: MessageReceipt): """ Process read-did DIDComm message """ # Storage instance from context storage: IndyStorage = await self.context.inject(BaseStorage) # Wallet instance from context wallet: IndyWallet = await self.context.inject(BaseWallet) # Responder instance from context responder: DispatcherResponder = await self.context.inject(BaseResponder, required=False) # From and To DIDs of the recieved message create_did_message_from_did: DIDMyData = DIDMyData.from_public_key_b58( receipt.sender_verkey, key_type=KeyType.ED25519) create_did_message_to_did: DIDMyData = DIDMyData.from_public_key_b58( receipt.recipient_verkey, key_type=KeyType.ED25519) # From and To DIDs for the response messages response_message_from_did = create_did_message_to_did response_message_to_did = create_did_message_from_did mydata_did_registry_did_info_record = None try: # Fetch DID from wallet mydata_did_registry_did_info_record = await storage.search_records( type_filter=ADAManager.RECORD_TYPE_MYDATA_DID_REGISTRY_DID_INFO, tag_query={"did": read_did_message.body.did} ).fetch_single() except (StorageNotFoundError, StorageDuplicateError) as e: # Send problem-report message. mydata_did_problem_report = MyDataDIDProblemReportMessage( problem_code=MyDataDIDProblemReportMessageReason.DID_NOT_FOUND.value, explain="DID not found.", from_did=response_message_from_did.did, to_did=response_message_to_did.did, created_time=round(time.time() * 1000) ) # Assign thread id mydata_did_problem_report.assign_thread_id( thid=read_did_message._id) if responder: await responder.send_reply(mydata_did_problem_report) return # Send read-did-response message read_did_response_message = ReadDIDResponseMessage( from_did=response_message_from_did.did, to_did=response_message_to_did.did, created_time=round(time.time() * 1000), body=MyDataDIDResponseBody( did_doc=MyDataDIDDoc.from_json( mydata_did_registry_did_info_record.value), version=mydata_did_registry_did_info_record.tags.get( "version"), status=mydata_did_registry_did_info_record.tags.get("status") ) ) # Assign thread id read_did_response_message.assign_thread_id( thid=read_did_message._id) # Create transaction record to keep track of didcomm messages transaction_record = MyDataDIDRegistryDIDCommTransactionRecord( thread_id=read_did_message._id, message_type=MyDataDIDRegistryDIDCommTransactionRecord.MESSAGE_TYPE_READ_DID, messages_list=[read_did_message.to_json( ), read_did_response_message.to_json()], connection_id=self.context.connection_record.connection_id, ) # Save transaction record await transaction_record.save(self.context) if responder: await responder.send_reply(read_did_response_message) async def process_read_did_response_message(self, read_did_response_message: ReadDIDResponseMessage, receipt: MessageReceipt): """ Process read-did-response DIDComm message """ # Thread identifier thread_id = read_did_response_message._thread_id mydata_did_registry_didcomm_transaction_record = None try: # Fetch MyData DID registry didcomm transaction record mydata_did_registry_didcomm_transaction_record: MyDataDIDRegistryDIDCommTransactionRecord = await MyDataDIDRegistryDIDCommTransactionRecord.retrieve_by_tag_filter( context=self.context, tag_filter={"thread_id": thread_id} ) except (StorageNotFoundError, StorageDuplicateError) as e: # No record found self._logger.debug( "Failed to process read-did-response message; " "No MyData DID registry didcomm transaction record found for thread_id: %s", thread_id ) return # Assert transaction record is not None assert mydata_did_registry_didcomm_transaction_record is not None mydata_did_registry_didcomm_transaction_record.messages_list.append( read_did_response_message.to_json() ) # Update transaction record await mydata_did_registry_didcomm_transaction_record.save(self.context) async def send_read_did_message(self, did: str) -> MyDataDIDRegistryDIDCommTransactionRecord: """ Send read-did DIDComm message """ # Wallet instance from context wallet: IndyWallet = await self.context.inject(BaseWallet) # Storage instance from context storage: BaseStorage = await self.context.inject(BaseStorage) connection_record, err = await self.fetch_mydata_did_registry_connection_record() if err: raise ADAManagerError( f"Failed to send read-did message. " f"Reason: {err}" ) # from_did pairwise_local_did_record = await wallet.get_local_did(connection_record.my_did) from_did = DIDMyData.from_public_key_b58( pairwise_local_did_record.verkey, key_type=KeyType.ED25519) # to_did to_did = DIDMyData.from_public_key_b58( connection_record.their_did, key_type=KeyType.ED25519) # Create read-did message read_did_message = ReadDIDMessage( from_did=from_did.did, to_did=to_did.did, created_time=round(time.time() * 1000), body=ReadDIDMessageBody( did=did ) ) # Create transaction record transaction_record = MyDataDIDRegistryDIDCommTransactionRecord( thread_id=read_did_message._id, message_type=MyDataDIDRegistryDIDCommTransactionRecord.MESSAGE_TYPE_READ_DID, messages_list=[read_did_message.to_json()], connection_id=connection_record.connection_id, ) # Save transaction record await transaction_record.save(self.context, reason="Send read-did message") # Send read-did message to MyData DID Registry responder: BaseResponder = await self.context.inject(BaseResponder, required=False) if responder: await responder.send(read_did_message, connection_id=connection_record.connection_id) return transaction_record async def process_delete_did_message(self, delete_did_message: DeleteDIDMessage, receipt: MessageReceipt): """ Process delete-did DIDComm message """ # Storage instance storage: IndyStorage = await self.context.inject(BaseStorage) # Wallet instance wallet: IndyWallet = await self.context.inject(BaseWallet) # Responder instance responder: DispatcherResponder = await self.context.inject(BaseResponder, required=False) # From and To DIDs of the recieved message create_did_message_from_did: DIDMyData = DIDMyData.from_public_key_b58( receipt.sender_verkey, key_type=KeyType.ED25519) create_did_message_to_did: DIDMyData = DIDMyData.from_public_key_b58( receipt.recipient_verkey, key_type=KeyType.ED25519) # From and To DIDs for the response messages response_message_from_did = create_did_message_to_did response_message_to_did = create_did_message_from_did mydata_did_registry_did_info_record = None try: # Fetch DID from wallet mydata_did_registry_did_info_record = await storage.search_records( type_filter=ADAManager.RECORD_TYPE_MYDATA_DID_REGISTRY_DID_INFO, tag_query={"did": delete_did_message.body.did} ).fetch_single() except (StorageNotFoundError, StorageDuplicateError) as e: # Send problem-report message. mydata_did_problem_report = MyDataDIDProblemReportMessage( problem_code=MyDataDIDProblemReportMessageReason.DID_NOT_FOUND.value, explain="DID not found.", from_did=response_message_from_did.did, to_did=response_message_to_did.did, created_time=round(time.time() * 1000) ) # Assign thread id mydata_did_problem_report.assign_thread_id( thid=delete_did_message._id) if responder: await responder.send_reply(mydata_did_problem_report, connection_id=self.context.connection_record.connection_id) return try: # Verify signature await delete_did_message.verify_signed_field( field_name="body", wallet=wallet, signer_verkey=DIDMyData.from_did( delete_did_message.body.did).public_key_b58 ) except BaseModelError as e: # Send problem-report message. mydata_did_problem_report = MyDataDIDProblemReportMessage( problem_code=MyDataDIDProblemReportMessageReason.MESSAGE_BODY_SIGNATURE_VERIFICATION_FAILED.value, explain="Invalid signature.", from_did=response_message_from_did.did, to_did=response_message_to_did.did, created_time=round(time.time() * 1000) ) # Assign thread id mydata_did_problem_report.assign_thread_id( thid=delete_did_message._id) if responder: await responder.send_reply(mydata_did_problem_report, connection_id=self.context.connection_record.connection_id) return # Update MyData DID Registry DID info record with revoked status mydata_did_registry_did_info_record.tags["status"] = "revoked" await storage.update_record_tags( record=mydata_did_registry_did_info_record, tags=mydata_did_registry_did_info_record.tags, ) # Send delete-did-response message delete_did_response_message = DeleteDIDResponseMessage( from_did=response_message_from_did.did, to_did=response_message_to_did.did, created_time=round(time.time() * 1000), body=DeleteDIDResponseMessageBody( did=mydata_did_registry_did_info_record.tags.get("did"), status=mydata_did_registry_did_info_record.tags.get("status"), ) ) # Assign thread id delete_did_response_message.assign_thread_id( thid=delete_did_message._id) # Create transaction record to keep track of didcomm messages transaction_record = MyDataDIDRegistryDIDCommTransactionRecord( thread_id=delete_did_message._id, message_type=MyDataDIDRegistryDIDCommTransactionRecord.MESSAGE_TYPE_DELETE_DID, messages_list=[delete_did_message.to_json( ), delete_did_response_message.to_json()], connection_id=self.context.connection_record.connection_id, ) # Save transaction record await transaction_record.save(self.context) if responder: await responder.send_reply(delete_did_response_message, connection_id=self.context.connection_record.connection_id) async def process_delete_did_response_message(self, delete_did_response_message: DeleteDIDResponseMessage, receipt: MessageReceipt): """ Process delete-did-response DIDComm message """ # Storage instance from context storage: BaseStorage = await self.context.inject(BaseStorage) # Thread identifier thread_id = delete_did_response_message._thread_id mydata_did_registry_didcomm_transaction_record = None try: # Fetch MyData DID registry didcomm transaction record mydata_did_registry_didcomm_transaction_record: MyDataDIDRegistryDIDCommTransactionRecord = await MyDataDIDRegistryDIDCommTransactionRecord.retrieve_by_tag_filter( context=self.context, tag_filter={"thread_id": thread_id} ) except (StorageNotFoundError, StorageDuplicateError) as e: # No record found self._logger.debug( "Failed to process delete-did-response message; " "No MyData DID registry didcomm transaction record found for thread_id: %s", thread_id ) return # Assert transaction record is not None assert mydata_did_registry_didcomm_transaction_record is not None mydata_did_registry_didcomm_transaction_record.messages_list.append( delete_did_response_message.to_json() ) # Update transaction record await mydata_did_registry_didcomm_transaction_record.save(self.context) try: # Mark remote did status as revoked mydata_did_remote_record = await storage.search_records( type_filter=ADAManager.RECORD_TYPE_MYDATA_DID_REMOTE, tag_query={"did": delete_did_response_message.body.did} ).fetch_single() mydata_did_remote_record.tags["status"] = "revoked" await storage.update_record_tags( record=mydata_did_remote_record, tags=mydata_did_remote_record.tags, ) except (StorageNotFoundError, StorageDuplicateError) as e: # No record found self._logger.debug( "Failed to process delete-did-response message; " "No MyData DID remote record found for did: %s", delete_did_response_message.body.did ) return async def send_delete_did_message(self, did: str) -> MyDataDIDRegistryDIDCommTransactionRecord: """ Send delete-did DIDComm message """ # Wallet instance from context wallet: IndyWallet = await self.context.inject(BaseWallet) # Storage instance from context storage: BaseStorage = await self.context.inject(BaseStorage) connection_record, err = await self.fetch_mydata_did_registry_connection_record() if err: raise ADAManagerError( f"Failed to send read-did message. " f"Reason: {err}" ) # from_did pairwise_local_did_record = await wallet.get_local_did(connection_record.my_did) from_did = DIDMyData.from_public_key_b58( pairwise_local_did_record.verkey, key_type=KeyType.ED25519) # to_did to_did = DIDMyData.from_public_key_b58( connection_record.their_did, key_type=KeyType.ED25519) # To be deleted did # Fetch did:sov local did record for to deleted mydata did to_be_deleted_sov_did = await wallet.get_local_did_for_verkey( verkey=DIDMyData.from_did(did).public_key_b58 ) # Create delete-did message delete_did_message = DeleteDIDMessage( from_did=from_did.did, to_did=to_did.did, created_time=round(time.time() * 1000), body=DeleteDIDMessageBody( did=did ) ) # Sign message await delete_did_message.sign_field( field_name="body", signer_verkey=to_be_deleted_sov_did.verkey, wallet=wallet, timestamp=time.time() ) # Create transaction record transaction_record = MyDataDIDRegistryDIDCommTransactionRecord( thread_id=delete_did_message._id, message_type=MyDataDIDRegistryDIDCommTransactionRecord.MESSAGE_TYPE_DELETE_DID, messages_list=[delete_did_message.to_json()], connection_id=connection_record.connection_id, ) # Save transaction record await transaction_record.save(self.context, reason="Send delete-did message") # Send delete-did message to MyData DID Registry responder: BaseResponder = await self.context.inject(BaseResponder, required=False) if responder: await responder.send(delete_did_message, connection_id=connection_record.connection_id) return transaction_record async def send_read_data_agreement_message(self, connection_record: ConnectionRecord, data_agreement_id: str) -> DataAgreementCRUDDIDCommTransaction: """ Send a read-data-agreement message to the remote agent. """ # Fetch context objects # Fetch the wallet instance from the context wallet: IndyWallet = await self.context.inject(BaseWallet) # Fetch the storage instance from the context storage: BaseStorage = await self.context.inject(BaseStorage) try: # from_did pairwise_local_did_record = await wallet.get_local_did(connection_record.my_did) from_did = DIDMyData.from_public_key_b58( pairwise_local_did_record.verkey, key_type=KeyType.ED25519) # to_did to_did = DIDMyData.from_public_key_b58( connection_record.their_did, key_type=KeyType.ED25519) except StorageError as err: raise ADAManagerError( f"Failed to send read-data-agreement message: {err}" ) # Create the read-data-agreement message data_agreement_message = ReadDataAgreement( from_did=from_did.did, to_did=to_did.did, created_time=round(time.time() * 1000), body=ReadDataAgreementBody( data_agreement_id=data_agreement_id, ) ) # Create transaction record to keep track of read-data-agreement message lifecycle transaction_record = DataAgreementCRUDDIDCommTransaction( thread_id=data_agreement_message._id, message_type=DataAgreementCRUDDIDCommTransaction.MESSAGE_TYPE_READ_DATA_AGREEMENT, messages_list=[data_agreement_message.serialize()], connection_id=connection_record.connection_id, ) # Add the transaction record to the storage await transaction_record.save(self.context) responder: BaseResponder = await self.context.inject(BaseResponder, required=False) if responder: await responder.send(data_agreement_message, connection_id=connection_record.connection_id) return transaction_record async def process_data_agreement_problem_report_message(self, *, data_agreement_problem_report_message: DataAgreementProblemReport, receipt: MessageReceipt): """Process data agreement problem report message""" thread_id = data_agreement_problem_report_message._thread_id # Fetch data agreement didcomm crud transaction record transaction_records = await DataAgreementCRUDDIDCommTransaction.query( context=self.context, tag_filter={"thread_id": thread_id}, ) if len(transaction_records) == 1: transaction_record: DataAgreementCRUDDIDCommTransaction = transaction_records[0] # Update transaction record with problem report transaction_record.messages_list.append( data_agreement_problem_report_message.serialize() ) await transaction_record.save(self.context) async def process_read_data_agreement_message(self, *, read_data_agreement_message: ReadDataAgreement, receipt: MessageReceipt): storage: IndyStorage = await self.context.inject(BaseStorage) responder: DispatcherResponder = await self.context.inject(BaseResponder, required=False) # fetch the data agreement record from the wallet # create data agreement didcomm crud transaction record # save request and response messages # send the response message. #
container self.blocks = None def reset(self): """set data to initial form""" # current question id, id is blockname::qname self.question_id = None # current question name within that block self.qname = None # qform the questions get saved in self.qform = None # current concrete question container self.concrete = None # current block container self.blocks = None def visit_question_ast_generator(self, qgen, qform=None): """When visiting an ast generator""" # save qform in self.qform self.qform = qform # set block_name and block_id self.question_id = '' # set concrete and blocks to None self.concrete = None self.blocks = None # start visiting the blocks output = qgen.tree.accept(self) # reset self.reset() # return output def visit_question_container(self, block): """when visiting a question container""" # save qname qname = self.qname # with self.question_block() as qid: for key, question in block.items(): # set qname to current key self.qname = key # set question_id self.question_id = join_keys(qid, key) # visit next item question.accept(self) # create block block = QuestionBlock(qid, self.concrete, self.blocks, self.qform, comment=block.comment) # if in main form, or within subquestions block, return the block if self.blocks is None: return block # else set the block self.blocks[qname] = block def visit_conditional_question(self, question): """visit conditional question form""" # create concrete_question and save it in the concrete_question block concrete_question = ConcreteQuestion(self.question_id, question.main, is_subquestion=True) self.concrete[self.qname] = concrete_question # enter the subquestion_block mode with self.subquestion_block() as (qid, block_name): # create empty cases dictionary cases = {} # for qname, quest in question.items(): # set question_id self.question_id = join_case(qid, qname) # there are no ids for these, so question.id does not need # to be set, here only subblocks can be inside! cases[qname] = quest.accept(self) # save subquestion block self.blocks[block_name] = SubquestionBlock(qid, concrete_question, cases, self.qform) def visit_literal_block(self, question): """block needs to be in a concrete section""" self.concrete[self.qname] = LiteralBlock(self.question_id, question.comment, self.qform) def visit_question(self, question): """question needs to be in concrete section""" self.concrete[self.qname] = ConcreteQuestion(self.question_id, question) @contextmanager def subquestion_block(self): """helper function to set defaults and reset them for SubquestionBlock""" blocks = self.blocks # self.blocks = None # yield self.question_id, self.qname # self.blocks = blocks @contextmanager def question_block(self): """helper function to set defaults and reset them for QuestionBlock""" # save old concrete, and blocks concrete = self.concrete blocks = self.blocks # create empty new ones self.concrete = {} self.blocks = {} # yield self.question_id # restore the old ones self.concrete = concrete self.blocks = blocks class ErrorSettingAnswerFromFile(SystemExit): """errors setting answers from file""" __slots__ = () def __init__(self, filename, msg): super().__init__(f"ErrorSettingAnswerFromFile: file = '{filename}'\n{msg}") class ErrorSettingAnswerFromDict(SystemExit): """Error when trying to read answers from a dict""" __slots__ = () def __init__(self, msg): super().__init__(f"ErrorSettingAnswerFromDict:\n{msg}") class WriteJsonVisitor(QuestionVisitor): """Visitor to write the answers to a string""" __slots__ = () def visit_qform(self, qform, **kwargs): data = qform.form.accept(self) return json.dumps(data, indent=4) def visit_question_block(self, block): # first all normal questions dct = {} for name, question in block.concrete.items(): res = question.accept(self) if res is not None: dct[res] = res # for name, subblock in block.blocks.items(): dct[name] = subblock.accept(self) return dct def visit_concrete_question_select(self, question): return question.get_answer_as_string() def visit_concrete_question_hidden(self, question): pass def visit_concrete_question_input(self, question): return question.get_answer_as_string() def visit_literal_block(self, block): answer = block.answer if answer.is_none is True: return return answer def visit_subquestion_block(self, block): """visit subquestion blocks""" answer = block.main_question.answer dct = {'__answer__': answer} if answer is None: return {} subblock = block.cases.get(answer) if subblock is None: return {} dct[answer] = subblock.accept(self) return dct class WriteConfigVisitor(QuestionVisitor): """Visitor to write the answers to a string""" __slots__ = ('txt',) def __init__(self): self.txt = '' def visit_qform(self, qform, **kwargs): self.txt = '' for blockname in qform.get_blocks(): # normal blocks qform[blockname].accept(self) txt = self.txt self.txt = '' return txt def visit_question_block(self, block): if block.name != '': self.txt += f'\n[{block.name}]\n' # first all normal questions for question in block.concrete.values(): if not isinstance(question, LiteralBlock): question.accept(self) # than literal blocks for question in block.concrete.values(): if isinstance(question, LiteralBlock): question.accept(self) def visit_concrete_question_select(self, question): self.txt += f'{question.short_name} = {question.get_answer_as_string()}\n' def visit_concrete_question_hidden(self, question): pass def visit_concrete_question_input(self, question): self.txt += f'{question.short_name} = {question.get_answer_as_string()}\n' def visit_literal_block(self, block): answer = block.answer if answer.is_none is True: return self.txt += f'[{block.id}]\n{answer}\n' def visit_subquestion_block(self, block): """visit subquestion blocks""" raise Exception("should never arrive in subquestion block!") class QuestionForm(Mapping, Component): """Main interface to the question forms""" # __slots__ = ('blocks', 'literals', 'unset', 'form') # visitor to generate answers answer_visitor = AnswerVisitor() # visitor to write answers to file write_visitor = WriteConfigVisitor() # visitor to generate question forms question_generator_visitor = QuestionGeneratorVisitor() def __init__(self, questions, config=None, presets=None): # self.blocks = {} # literal blocks self.literals = {} # not set variables self.unset = {} # generate Question Forms self.form = self._generate_forms(questions) # self.set_answers_and_presets(config, presets) def _generate_forms(self, questions): questions = QuestionASTGenerator(questions) return self.question_generator_visitor.visit(questions, qform=self) def accept(self, visitor, **kwargs): return visitor.visit_qform(self, **kwargs) @property def is_all_set(self): """check if all questions are answered""" return all(block.is_set for block in self.values()) def set_answer(self, name, answer): """Set the answer of a question""" if answer == "": return False # block, key = self._split_keys(name) # try: block.concrete[key].answer = answer is_set = True except ValueError: is_set = False except ValidatorErrorNotInChoices: is_set = False # return is_set def get_answers(self, check=True): """Get the answers from the forms Parameter --------- check: bool if False, raise no exception in case answers are not set missing answers are given as empty strings Returns ------- AnswersBlock dictionary with the parsed and validated userinput Raises ------ ColtErrorAnswerNotDefined if `check` is True, raises error in case answers are not given """ return self.answer_visitor.visit(self, check=check) def get_blocks(self): """return blocks""" return self.form.get_blocks() def write_config(self, filename): """ get a linear config and write it to the file""" if isinstance(filename, StringIO): return with open(filename, 'w') as fhandle: fhandle.write(self.write_visitor.visit(self)) def set_answers_from_file(self, filename, raise_error=True): error = self._set_answers_from_file(filename) if raise_error is True and error.is_none() is False: raise ErrorSettingAnswerFromDict(str(error)) def set_answers_from_dct(self, dct, raise_error=True): error = self._set_answers_from_dct(dct) if raise_error is True and error.is_none() is False: raise ErrorSettingAnswerFromDict(str(error)) def set_answers_and_presets(self, config=None, presets=None, raise_error=True): """set both presets and answers""" if presets is not None: self.set_presets(presets) if config is not None: if isinstance(config, Mapping): self.set_answers_from_dct(config, raise_error=raise_error) elif isinstance(config, StringIO) or is_existing_file(config): self.set_answers_from_file(config, raise_error=raise_error) def set_presets(self, presets): """reset some of the question possibilites""" presets = PresetGenerator(presets).tree # for blockname, fields in presets.items(): if blockname not in self.blocks: print(f"Unknown block {blockname} in presets, continue") continue block = self.blocks[blockname] for key, preset in fields.items(): if key not in block: print(f"Unknown key {key} in {blockname} in presets, continue") continue try: block[key].preset(preset.default, preset.choices) except ValidatorErrorNotChoicesSubset: print((f"Could not update choices in '{blockname}' entry '{key}' as choices ", "not subset of previous choices, continue")) def __iter__(self): return iter(self.get_blocks()) def __len__(self): return len(self.get_blocks()) def __getitem__(self, key): return self.blocks[key] def _set_literals(self, literals): """set literals from literalblock """ for key, value in literals.items(): if value in (None, ''): continue self.literals[key].answer = value def _set_answers_from_file(self, filename): """Set answers from a given file""" # try: parsed, literals = ConfigParser.read(filename, self.literals) except FileNotFoundError: return ColtErrorMessage(f"File '{filename}' not found!") # self._set_literals(literals) # return self._set_answers_from_dct(parsed) def _set_answers_from_dct(self, dct): """Set the answers from a dictionary""" # error = ColtInputError() # for blockname, answers in dct.items(): if blockname == ConfigParser.base: blockname = "" if blockname not in self.blocks: if blockname in self.literals: self.literals[blockname].answer = answers continue print(f"""Section = {blockname} unknown, maybe typo?""") continue error.append(self._set_block_answers(blockname, answers)) # return error def _set_block_answers(self, blockname, answers): error = ColtBlockError(blockname) block = self.blocks[blockname] for key, answer in answers.items(): if key not in block: print(f"unknown key '{key}' in '[{block}]'") continue question = block[key] if answer == "": if question.is_optional: question.is_set = True question.is_set_to_empty = True continue # try: question.answer = answer except ValueError as e: error[key] = f"{answer}, ValueError: {e}" except ValidatorErrorNotInChoices as err_choices: error[key] = f"{answer}, Wrong Choice: {err_choices}" return error def _split_keys(self, name): block, key = split_keys(name) if block not in self.blocks: raise Exception("block unknown") return self.blocks[block], key class ColtBlockError: """Class to handle error messages for setting a block""" __slots__ = ('_errors', 'name') def __init__(self, name): self._errors = {} self.name = name def is_none(self): return self._errors == {} def __setitem__(self, key, value): self._errors[key] = value def
<gh_stars>0 # -*- coding: utf-8 -*- from __future__ import unicode_literals import os import pdfkit import logging from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.db.models import Q from django import forms from django.forms import ModelForm from entidades.models import Gauser_extra, Subentidad, Cargo from gauss.funciones import usuarios_de_gauss, get_dce from gauss.rutas import * from tutorados.models import Pregunta, Informe_seguimiento, Respuesta, Fichero_tarea, Informe_tareas, Tarea_propuesta from autenticar.control_acceso import permiso_required from django.http import HttpResponse, JsonResponse, FileResponse from datetime import datetime, date, timedelta from django.template.loader import render_to_string from django.core.mail import EmailMessage import simplejson as json from mensajes.views import crear_aviso, encolar_mensaje from mensajes.models import Aviso from zipfile import ZipFile from django.utils.text import slugify logger = logging.getLogger('django') preguntas_base = ['¿Realiza las tareas y ejercicios encomendados con regularidad?', '¿Cómo es su comportamiento en clase?', '¿Cómo es su relación con compañeros y profesores?', '¿Cuál es su forma de actuar con respecto a la puntualidad y asistencia a clase?', 'Aspectos en los que ha tenido más dificultades y le han impedido superar la asignatura', '¿Qué notas va sacando en vuestra asignatura?'] @permiso_required('acceso_informes_usuarios') def informes_seguimiento(request): g_e = request.session['gauser_extra'] informes_solicitados = Informe_seguimiento.objects.filter(solicitante=g_e, usuario__entidad=g_e.ronda.entidad).distinct() informes_a_rellenar = Informe_seguimiento.objects.filter(Q(usuarios_destino__in=[g_e]), Q(deadline__gte=date.today()), ~Q(id__in=informes_solicitados)).distinct() if request.method == 'POST': if request.POST['action'] == 'pdf_informe_seguimiento': informe = Informe_seguimiento.objects.get(usuario__ronda=g_e.ronda, id=request.POST['informe_id']) if informe.solicitante == g_e or g_e.has_permiso('ve_informes_seguimiento'): doc_seg = 'Configuración de informes de seguimiento' dce = get_dce(g_e.ronda.entidad, doc_seg) c = render_to_string('informe_seguimiento2pdf.html', { 'informe': informe, 'MEDIA_ANAGRAMAS': MEDIA_ANAGRAMAS, }) fich = pdfkit.from_string(c, False, dce.get_opciones) logger.info('%s, pdf_informe_seguimiento %s' % (g_e, informe.id)) response = HttpResponse(fich, content_type='application/pdf') usuario = slugify(informe.usuario.gauser.get_full_name()) response['Content-Disposition'] = 'attachment; filename=Informe_Seguimiento_%s.pdf' % usuario return response return render(request, "informes_seguimiento.html", { 'formname': 'informe_seguimiento', 'informes_solicitados': informes_solicitados, 'informes_a_rellenar': informes_a_rellenar, 'g_e': g_e, 'avisos': Aviso.objects.filter(usuario=g_e, aceptado=False) }) @login_required() def ajax_informe_seguimiento(request): g_e = request.session['gauser_extra'] if request.is_ajax(): logger.info('%s, %s' % (g_e, request.POST['action'])) if request.POST['action'] == 'buscar_usuarios_destino': q = request.POST['q'].split() Q_total = Q(gauser__isnull=False) for texto in q: Q_parcial = Q(gauser__first_name__icontains=texto) | Q(gauser__last_name__icontains=texto) Q_total = Q_total & Q_parcial # sub_docentes = Subentidad.objects.get(entidad=g_e.ronda.entidad, clave_ex='docente') # usuarios = usuarios_de_gauss(g_e.ronda.entidad, subentidades=[sub_docentes]) cargo = Cargo.objects.get(entidad=g_e.ronda.entidad, clave_cargo='g_docente') usuarios = Gauser_extra.objects.filter(ronda=g_e.ronda, cargos__in=[cargo]) filtrados = usuarios.filter(Q_total) options = [] for u in filtrados: options.append( {'id': u.id, 'text': u.gauser.get_full_name()}) return JsonResponse(options, safe=False) elif request.POST['action'] == 'buscar_usuario': q = request.POST['q'].split() Q_total = Q(gauser__isnull=False) for texto in q: Q_parcial = Q(gauser__first_name__icontains=texto) | Q(gauser__last_name__icontains=texto) Q_total = Q_total & Q_parcial & ~Q(id__in=request.POST.getlist('ges_informes_abiertos[]')) sub_alumnos = Subentidad.objects.get(entidad=g_e.ronda.entidad, clave_ex='alumnos') usuarios = usuarios_de_gauss(g_e.ronda.entidad, subentidades=[sub_alumnos]) filtrados = usuarios.filter(Q_total) options = [] for u in filtrados: try: grupo_nombre = u.gauser_extra_estudios.grupo.nombre except: grupo_nombre = 'Sin grupo asignado' options.append( {'id': u.id, 'text': u.gauser.get_full_name() + ' (' + grupo_nombre + ')'}) return JsonResponse(options, safe=False) elif request.POST['action'] == 'get_informes_usuario': usuario = Gauser_extra.objects.get(ronda=g_e.ronda, id=request.POST['usuario']) informes = Informe_seguimiento.objects.filter(Q(usuario=usuario), ~Q(id__in=request.POST.getlist('ges_informes_cerrados[]'))) # data = render_to_string('informes_seguimiento_accordion.html', {'informes': informes, 'g_e': g_e}) # return JsonResponse({'html': data, 'ok': True, 'usuario_nombre': usuario.gauser.get_full_name()}) # usuario = Gauser_extra.objects.get(ronda=g_e.ronda, id=request.POST['usuario']) # informes = Informe_tareas.objects.filter(Q(usuario=usuario), # ~Q(id__in=request.POST.getlist('ges_informes_cerrados[]'))) crea_informe = False ge_informes = [] for i in informes: if g_e in i.usuarios_destino.all() or g_e.has_permiso('ve_informes_seguimiento'): ge_informes.append(i) con_crea_informe1 = g_e in usuario.gauser_extra_estudios.grupo.tutores con_crea_informe2 = g_e in usuario.gauser_extra_estudios.grupo.cotutores con_crea_informe3 = g_e.has_permiso('solicita_informes_seguimiento') if con_crea_informe1 or con_crea_informe2 or con_crea_informe3: crea_informe = True if len(ge_informes) > 0: data = render_to_string('informes_seguimiento_accordion.html', {'informes': ge_informes, 'g_e': g_e}) else: data = False return JsonResponse({'html': data, 'ok': True, 'usuario_nombre': usuario.gauser.get_full_name(), 'crea_informe': crea_informe}) elif request.POST['action'] == 'solicitar_informe': usuario = Gauser_extra.objects.get(ronda=g_e.ronda, id=request.POST['usuario_id']) if (g_e in usuario.gauser_extra_estudios.grupo.tutores) or g_e.has_permiso( 'solicita_informes_seguimiento') or (g_e in usuario.gauser_extra_estudios.grupo.cotutores): try: informe = Informe_seguimiento.objects.get(usuario=usuario, deadline__gte=date.today()) html = False except: texto_solicitud = 'Hola, voy a tener una reunión para hablar de {0}. Por favor, responde a ' \ 'las siguientes preguntas'.format(usuario.gauser.get_full_name()) deadline = date.today() + timedelta(days=7) informe = Informe_seguimiento.objects.create(usuario=usuario, solicitante=g_e, deadline=deadline, texto_solicitud=texto_solicitud, fecha=datetime.today()) try: grupo = usuario.gauser_extra_estudios.grupo ges = set(grupo.sesion_set.all().values_list('g_e', flat=True)) informe.usuarios_destino.add(*ges) except: pass html = render_to_string('informes_seguimiento_accordion.html', {'informes': [informe], 'g_e': g_e}) return JsonResponse({'html': html, 'ok': True, 'informe': informe.id}) else: return JsonResponse({'ok': False}) elif request.POST['action'] == 'open_accordion': # sub_docentes = Subentidad.objects.get(entidad=g_e.ronda.entidad, clave_ex='docente') # docentes = usuarios_de_gauss(g_e.ronda.entidad, subentidades=[sub_docentes]) cargo = Cargo.objects.get(entidad=g_e.ronda.entidad, clave_cargo='g_docente') docentes = Gauser_extra.objects.filter(ronda=g_e.ronda, cargos__in=[cargo]) informe = Informe_seguimiento.objects.get(usuario__ronda=g_e.ronda, id=request.POST['informe']) data = render_to_string('informe_seguimiento_accordion_content.html', {'informe': informe, 'g_e': g_e, 'docentes': docentes, 'preguntas': preguntas_base}) return HttpResponse(data) elif request.POST['action'] == 'deadline': try: informe = Informe_seguimiento.objects.get(usuario__ronda=g_e.ronda, id=request.POST['informe']) informe.deadline = datetime.strptime(request.POST['deadline'], '%d/%m/%Y').date() informe.save() estado = 'closed' if informe.deadline < date.today() else 'open' return JsonResponse({'ok': True, 'estado': estado, 'inf': informe.id}) except: return JsonResponse({'ok': False}) elif request.POST['action'] == 'del_informe_seguimiento': try: informe = Informe_seguimiento.objects.get(usuario__ronda=g_e.ronda, id=request.POST['informe']) informe.delete() return JsonResponse({'ok': True}) except: return JsonResponse({'ok': False}) elif request.POST['action'] == 'del_participacion_informe_seguimiento': try: informe = Informe_seguimiento.objects.get(usuario__ronda=g_e.ronda, id=request.POST['informe']) informe.usuarios_destino.remove(g_e) return JsonResponse({'ok': True}) except: return JsonResponse({'ok': False}) elif request.POST['action'] == 'texto_solicitud': try: informe = Informe_seguimiento.objects.get(usuario__ronda=g_e.ronda, id=request.POST['informe']) informe.texto_solicitud = request.POST['texto'] informe.save() return JsonResponse({'ok': True}) except: return JsonResponse({'ok': False}) elif request.POST['action'] == 'mod_usuarios_destino' and g_e.has_permiso('solicita_informes_seguimiento'): informe = Informe_seguimiento.objects.get(usuario__ronda=g_e.ronda, id=request.POST['informe']) usuarios = Gauser_extra.objects.filter(ronda=g_e.ronda, id__in=request.POST.getlist('usuarios[]')) informe.usuarios_destino.clear() informe.usuarios_destino.add(*usuarios) return JsonResponse({'ok': True, 'n': informe.usuarios_destino.all().count()}) elif request.POST['action'] == 'aviso_informe_seguimiento': informe = Informe_seguimiento.objects.get(usuario__ronda=g_e.ronda, id=request.POST['informe']) asunto = render_to_string('informe_seguimiento_mail_asunto.html', {'informe': informe}) texto = render_to_string('informe_seguimiento_mail.html', {'informe': informe}) receptores = [] for ge in informe.usuarios_destino.all(): if ge.respuesta_set.filter(pregunta__informe=informe).count() != informe.pregunta_set.all().count(): Aviso.objects.create(usuario=ge, aviso=texto, fecha=datetime.now(), aceptado=False, link='/informes_seguimiento') receptores.append(ge.gauser) encolar_mensaje(emisor=g_e, receptores=receptores, asunto=asunto, html=texto) return JsonResponse({'ok': True}) elif request.POST['action'] == 'add_pregunta_informe' and g_e.has_permiso('solicita_informes_seguimiento'): informe = Informe_seguimiento.objects.get(usuario__ronda=g_e.ronda, id=request.POST['informe']) n = request.POST['n'] if n == 'nueva': p = Pregunta.objects.create(informe=informe, pregunta='') else: p = Pregunta.objects.create(informe=informe, pregunta=preguntas_base[int(n)]) html = render_to_string('informe_seguimiento_accordion_content_pregunta.html', {'pregunta': p, 'g_e': g_e}) return JsonResponse({'ok': True, 'html': html}) elif request.POST['action'] == 'delete_pregunta': ok = False try: pregunta = Pregunta.objects.get(informe__usuario__ronda=g_e.ronda, id=request.POST['pregunta']) pregunta_id = pregunta.id informe = pregunta.informe if g_e.has_permiso('borra_preguntas_informes_seguimiento') or pregunta.informe.solicitante == g_e: pregunta.delete() ok = True n_preguntas = informe.pregunta_set.all().count() return JsonResponse({'pregunta': pregunta_id, 'n_preguntas': n_preguntas, 'ok': ok}) except: return JsonResponse({'ok': ok}) elif request.POST['action'] == 'pregunta': try: informe = Informe_seguimiento.objects.get(usuario__ronda=g_e.ronda, id=request.POST['informe']) pregunta = Pregunta.objects.get(informe=informe, id=request.POST['pregunta']) pregunta.pregunta = request.POST['texto'] pregunta.save() return JsonResponse({'ok': True}) except: return JsonResponse({'ok': False}) elif request.POST['action'] == 'respuesta_a_pregunta': try: informe = Informe_seguimiento.objects.get(usuario__ronda=g_e.ronda, id=request.POST['informe']) responde = Gauser_extra.objects.get(ronda=g_e.ronda, id=request.POST['ge']) pregunta = Pregunta.objects.get(informe=informe, id=request.POST['pregunta']) try: respuesta, c = Respuesta.objects.get_or_create(informe=informe, usuario=responde, pregunta=pregunta) except: Respuesta.objects.filter(informe=informe, usuario=responde, pregunta=pregunta).delete() respuesta = Respuesta.objects.create(informe=informe, usuario=responde, pregunta=pregunta) respuesta.respuesta = request.POST['respuesta'] respuesta.save() return JsonResponse({'ok': True, 'n': informe.num_usuarios_respondido}) except: return JsonResponse({'ok': False}) else: logger.info(u'%s, acción no permitida' % (g_e)) return HttpResponse(False) else: return HttpResponse(status=400) # ######################################################################## # INFORMES CON TRABAJOS @permiso_required('acceso_informes_tareas') def informes_tareas(request): g_e = request.session['gauser_extra'] informes_solicitados = Informe_tareas.objects.filter(solicitante=g_e, usuario__entidad=g_e.ronda.entidad).distinct() informes_a_rellenar = Informe_tareas.objects.filter(Q(usuario__entidad=g_e.ronda.entidad), Q(usuarios_destino__in=[g_e]), Q(deadline__gte=date.today()), ~Q(id__in=informes_solicitados)).distinct() if request.method == 'POST': if request.POST['action'] == 'pdf_informe_tareas': doc_tar = 'Configuración de informes con tareas' dce = get_dce(g_e.ronda.entidad, doc_tar) informe = Informe_tareas.objects.get(usuario__ronda=g_e.ronda, id=request.POST['informe_id']) ficheros_list = Fichero_tarea.objects.filter(tarea__informe=informe) if informe.solicitante == g_e or g_e.has_permiso('ve_informes_tareas'): fichero = 'informe_informe_tareas_%s_%s.pdf' % (g_e.ronda.entidad.code, informe.id) c = render_to_string('informe_tareas2pdf.html', { 'informe': informe, 'ficheros_list': ficheros_list, }) ruta = MEDIA_INFORMES + '%s/' % g_e.ronda.entidad.code informe_pdf = ruta + '%s' % fichero pdfkit.from_string(c, informe_pdf, dce.get_opciones) if ficheros_list.count() > 0: ruta_zip = ruta + 'informe_informe_tareas_%s_%s.zip' % (g_e.ronda.entidad.code, informe.id) with ZipFile(ruta_zip, 'w') as zipObj: # Añadir varios archivos en un ZIP # Primero incluimos el pdf y después los archivos adjuntos zipObj.write(informe_pdf, os.path.basename(informe_pdf)) for f in ficheros_list: zipObj.write(f.fichero.path, os.path.basename(f.fichero.path)) logger.info('%s, pdf_informe_tareas %s' % (g_e, informe.id)) response = FileResponse(open(ruta_zip, 'rb')) response['Content-Disposition'] = 'attachment; filename=informe_informe_tareas_%s_%s.zip' % ( slugify(informe.usuario.gauser.get_full_name()), str(informe.id)) return response else: logger.info('%s, pdf_informe_tareas %s' % (g_e, informe.id)) response = FileResponse(open(informe_pdf, 'rb')) response['Content-Disposition'] = 'attachment; filename=informe_informe_tareas_%s_%s.pdf' % ( slugify(informe.usuario.gauser.get_full_name()), str(informe.id)) return response return render(request, "informes_tareas.html", { 'formname': 'informe_tareas', 'informes_solicitados': informes_solicitados, 'informes_a_rellenar': informes_a_rellenar, 'g_e': g_e, 'avisos': Aviso.objects.filter(usuario=g_e, aceptado=False) }) # @permiso_required('acceso_informes_tareas') def ajax_informe_tareas(request): g_e = request.session['gauser_extra'] if request.is_ajax(): logger.info('%s, %s' % (g_e, request.POST['action'])) if request.POST['action'] == 'buscar_usuarios_destino': q = request.POST['q'].split() Q_total = Q(gauser__isnull=False) for texto in q: Q_parcial = Q(gauser__first_name__icontains=texto) | Q(gauser__last_name__icontains=texto) Q_total = Q_total & Q_parcial # sub_docentes = Subentidad.objects.get(entidad=g_e.ronda.entidad, clave_ex='docente') # usuarios = usuarios_de_gauss(g_e.ronda.entidad, subentidades=[sub_docentes]) cargo = Cargo.objects.get(entidad=g_e.ronda.entidad, clave_cargo='g_docente') usuarios = Gauser_extra.objects.filter(ronda=g_e.ronda, cargos__in=[cargo]) filtrados = usuarios.filter(Q_total) options = [] for u in filtrados: options.append( {'id': u.id, 'text': u.gauser.get_full_name()}) return JsonResponse(options, safe=False) elif request.POST['action'] == 'buscar_usuario': q = request.POST['q'].split() Q_total = Q(gauser__isnull=False) for texto in q: Q_parcial = Q(gauser__first_name__icontains=texto) | Q(gauser__last_name__icontains=texto) Q_total = Q_total & Q_parcial & ~Q(id__in=request.POST.getlist('ges_informes_abiertos[]')) sub_alumnos = Subentidad.objects.get(entidad=g_e.ronda.entidad, clave_ex='alumnos') usuarios = usuarios_de_gauss(g_e.ronda.entidad, subentidades=[sub_alumnos]) filtrados = usuarios.filter(Q_total) options = [] for u in filtrados: try: grupo_nombre = u.gauser_extra_estudios.grupo.nombre except: grupo_nombre = 'Sin grupo asignado' options.append( {'id': u.id, 'text': u.gauser.get_full_name() + ' (' + grupo_nombre + ')'}) return JsonResponse(options, safe=False) elif request.POST['action'] == 'get_informes_usuario': usuario = Gauser_extra.objects.get(ronda=g_e.ronda, id=request.POST['usuario']) informes = Informe_tareas.objects.filter(Q(usuario=usuario), ~Q(id__in=request.POST.getlist('ges_informes_cerrados[]'))) crea_informe = False ge_informes = [] for i in informes: if g_e in i.usuarios_destino.all() or g_e.has_permiso('ve_informes_tareas'): ge_informes.append(i) if (g_e in usuario.gauser_extra_estudios.grupo.tutores) or ( g_e in usuario.gauser_extra_estudios.grupo.cotutores)
<gh_stars>0 import os import pytest from boltons.dictutils import OMD from boltons.iterutils import (first, remap, research, default_enter, default_exit, get_path) from boltons.namedutils import namedtuple CUR_PATH = os.path.abspath(__file__) isbool = lambda x: isinstance(x, bool) isint = lambda x: isinstance(x, int) odd = lambda x: isint(x) and x % 2 != 0 even = lambda x: isint(x) and x % 2 == 0 is_meaning_of_life = lambda x: x == 42 class TestFirst(object): def test_empty_iterables(self): """ Empty iterables return None. """ s = set() l = [] assert first(s) is None assert first(l) is None def test_default_value(self): """ Empty iterables + a default value return the default value. """ s = set() l = [] assert first(s, default=42) == 42 assert first(l, default=3.14) == 3.14 l = [0, False, []] assert first(l, default=3.14) == 3.14 def test_selection(self): """ Success cases with and without a key function. """ l = [(), 0, False, 3, []] assert first(l, default=42) == 3 assert first(l, key=isint) == 0 assert first(l, key=isbool) is False assert first(l, key=odd) == 3 assert first(l, key=even) == 0 assert first(l, key=is_meaning_of_life) is None class TestRemap(object): # TODO: test namedtuples and other immutable containers def test_basic_clone(self): orig = {"a": "b", "c": [1, 2]} assert orig == remap(orig) orig2 = [{1: 2}, {"a": "b", "c": [1, 2, {"cat": "dog"}]}] assert orig2 == remap(orig2) def test_empty(self): assert [] == remap([]) assert {} == remap({}) assert set() == remap(set()) def test_unremappable(self): obj = object() with pytest.raises(TypeError): remap(obj) def test_basic_upper(self): orig = {'a': 1, 'b': object(), 'c': {'d': set()}} remapped = remap(orig, lambda p, k, v: (k.upper(), v)) assert orig['a'] == remapped['A'] assert orig['b'] == remapped['B'] assert orig['c']['d'] == remapped['C']['D'] def test_item_drop(self): orig = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] even_items = remap(orig, lambda p, k, v: not (v % 2)) assert even_items == [0, 2, 4, 6, 8] def test_noncallables(self): with pytest.raises(TypeError): remap([], visit='test') with pytest.raises(TypeError): remap([], enter='test') with pytest.raises(TypeError): remap([], exit='test') def test_sub_selfref(self): coll = [0, 1, 2, 3] sub = [] sub.append(sub) coll.append(sub) with pytest.raises(RuntimeError): # if equal, should recurse infinitely assert coll == remap(coll) def test_root_selfref(self): selfref = [0, 1, 2, 3] selfref.append(selfref) with pytest.raises(RuntimeError): assert selfref == remap(selfref) selfref2 = {} selfref2['self'] = selfref2 with pytest.raises(RuntimeError): assert selfref2 == remap(selfref2) def test_duperef(self): val = ['hello'] duperef = [val, val] remapped = remap(duperef) assert remapped[0] is remapped[1] assert remapped[0] is not duperef[0] def test_namedtuple(self): """TODO: this fails right now because namedtuples' __new__ is overridden to accept arguments. remap's default_enter tries to create an empty namedtuple and gets a TypeError. Could make it so that immutable types actually don't create a blank new parent and instead use the old_parent as a placeholder, creating a new one at exit-time from the value's __class__ (how default_exit works now). But even then it would have to *args in the values, as namedtuple constructors don't take an iterable. """ Point = namedtuple('Point', 'x y') point_map = {'origin': [Point(0, 0)]} with pytest.raises(TypeError): remapped = remap(point_map) assert isinstance(remapped['origin'][0], Point) def test_path(self): path_map = {} # test visit's path target_str = 'test' orig = [[[target_str]]] ref_path = (0, 0, 0) def visit(path, key, value): if value is target_str: path_map['target_str'] = path + (key,) return key, value remapped = remap(orig, visit=visit) assert remapped == orig assert path_map['target_str'] == ref_path # test enter's path target_obj = object() orig = {'a': {'b': {'c': {'d': ['e', target_obj, 'f']}}}} ref_path = ('a', 'b', 'c', 'd', 1) def enter(path, key, value): if value is target_obj: path_map['target_obj'] = path + (key,) return default_enter(path, key, value) remapped = remap(orig, enter=enter) assert remapped == orig assert path_map['target_obj'] == ref_path # test exit's path target_set = frozenset([1, 7, 3, 8]) orig = [0, 1, 2, [3, 4, [5, target_set]]] ref_path = (3, 2, 1) def exit(path, key, old_parent, new_parent, new_items): if old_parent is target_set: path_map['target_set'] = path + (key,) return default_exit(path, key, old_parent, new_parent, new_items) remapped = remap(orig, exit=exit) assert remapped == orig assert path_map['target_set'] == ref_path def test_reraise_visit(self): root = {'A': 'b', 1: 2} key_to_lower = lambda p, k, v: (k.lower(), v) with pytest.raises(AttributeError): remap(root, key_to_lower) remapped = remap(root, key_to_lower, reraise_visit=False) assert remapped['a'] == 'b' assert remapped[1] == 2 def test_drop_nones(self): orig = {'a': 1, 'b': None, 'c': [3, None, 4, None]} ref = {'a': 1, 'c': [3, 4]} drop_none = lambda p, k, v: v is not None remapped = remap(orig, visit=drop_none) assert remapped == ref orig = [None] * 100 remapped = remap(orig, drop_none) assert not remapped def test_dict_to_omd(self): def enter(path, key, value): if isinstance(value, dict): return OMD(), sorted(value.items()) return default_enter(path, key, value) orig = [{'title': 'Wild Palms', 'ratings': {1: 1, 2: 3, 3: 5, 4: 6, 5: 3}}, {'title': 'Twin Peaks', 'ratings': {1: 3, 2: 2, 3: 8, 4: 12, 5: 15}}] remapped = remap(orig, enter=enter) assert remapped == orig assert isinstance(remapped[0], OMD) assert isinstance(remapped[0]['ratings'], OMD) assert isinstance(remapped[1], OMD) assert isinstance(remapped[1]['ratings'], OMD) def test_sort_all_lists(self): def exit(path, key, old_parent, new_parent, new_items): # NB: in this case, I'd normally use *a, **kw ret = default_exit(path, key, old_parent, new_parent, new_items) if isinstance(ret, list): ret.sort() return ret # NB: Airplane model numbers (Boeing and Airbus) orig = [[[7, 0, 7], [7, 2, 7], [7, 7, 7], [7, 3, 7]], [[3, 8, 0], [3, 2, 0], [3, 1, 9], [3, 5, 0]]] ref = [[[0, 2, 3], [0, 3, 5], [0, 3, 8], [1, 3, 9]], [[0, 7, 7], [2, 7, 7], [3, 7, 7], [7, 7, 7]]] remapped = remap(orig, exit=exit) assert remapped == ref def test_collector_pattern(self): all_interests = set() def enter(path, key, value): try: all_interests.update(value['interests']) except: pass return default_enter(path, key, value) orig = [{'name': 'Kate', 'interests': ['theater', 'manga'], 'dads': [{'name': 'Chris', 'interests': ['biking', 'python']}]}, {'name': 'Avery', 'interests': ['museums', 'pears'], 'dads': [{'name': 'Kurt', 'interests': ['python', 'recursion']}]}] ref = set(['python', 'recursion', 'biking', 'museums', 'pears', 'theater', 'manga']) remap(orig, enter=enter) assert all_interests == ref def test_add_length(self): def exit(path, key, old_parent, new_parent, new_items): ret = default_exit(path, key, old_parent, new_parent, new_items) try: ret['review_length'] = len(ret['review']) except: pass return ret orig = {'Star Trek': {'TNG': {'stars': 10, 'review': "Episodic AND deep. <3 Data."}, 'DS9': {'stars': 8.5, 'review': "Like TNG, but with a story and no Data."}, 'ENT': {'stars': None, 'review': "Can't review what you can't watch."}}, 'Babylon 5': {'stars': 6, 'review': "Sophomoric, like a bitter laugh."}, 'Dr. Who': {'stars': None, 'review': "800 episodes is too many to review."}} remapped = remap(orig, exit=exit) assert (remapped['Star Trek']['TNG']['review_length'] < remapped['Star Trek']['DS9']['review_length']) def test_prepop(self): """Demonstrating normalization and ID addition through prepopulating the objects with an enter callback. """ base_obj = {'name': None, 'rank': None, 'id': 1} def enter(path, key, value): new_parent, new_items = default_enter(path, key, value) try: new_parent.update(base_obj) base_obj['id'] += 1 except: pass return new_parent, new_items orig = [{'name': 'Firefox', 'rank': 1}, {'name': 'Chrome', 'rank': 2}, {'name': 'IE'}] ref = [{'name': 'Firefox', 'rank': 1, 'id': 1}, {'name': 'Chrome', 'rank': 2, 'id': 2}, {'name': 'IE', 'rank': None, 'id': 3}] remapped = remap(orig, enter=enter) assert remapped == ref def test_remap_set(self): # explicit test for sets to make sure #84 is covered s = set([1, 2, 3]) assert remap(s) == s fs = frozenset([1, 2, 3]) assert remap(fs) == fs def test_remap_file(self): with open(CUR_PATH, 'rb') as f: x = {'a': [1, 2, 3], 'f': [f]} assert remap(x) == x f.read() assert remap(x) == x f.close() # see #146 assert remap(x) == x return class TestGetPath(object): def test_depth_one(self): root = ['test'] assert get_path(root, (0,)) == 'test' assert get_path(root, '0') == 'test' root = {'key': 'value'} assert get_path(root, ('key',)) == 'value' assert get_path(root, 'key') == 'value' def test_depth_two(self): root = {'key': ['test']} assert get_path(root, ('key', 0)) == 'test' assert get_path(root, 'key.0') == 'test' def test_research(): root = {} with pytest.raises(TypeError): research(root, query=None) root = {'a': 'a'} res = research(root, query=lambda p, k, v: v == 'a') assert len(res) == 1 assert res[0] == (('a',), 'a') def broken_query(p, k, v): raise RuntimeError() with pytest.raises(RuntimeError): research(root, broken_query, reraise=True) # empty results with default, reraise=False assert research(root, broken_query) == [] def test_backoff_basic(): from
Provide an alternate name for the status code in the response body which can vary between services due to the spec still being in draft. The default is `b"statusCode"`. :type status_code_field: bytes or str :param description_fields: Provide an alternate name for the description in the response body which can vary between services due to the spec still being in draft. The default is `b"statusDescription"`. :type description_fields: bytes or str :rtype: ~uamqp.message.Message """ while not await self.auth_complete_async(): await asyncio.sleep(0.05) response = await asyncio.shield(self._session.mgmt_request_async( message, operation, op_type=op_type, node=node, callback=callback, encoding=self._encoding, debug=self._debug_trace, **kwargs)) return response async def auth_complete_async(self): """Whether the authentication handshake is complete during connection initialization. :rtype: bool """ timeout = False auth_in_progress = False if self._connection.cbs: timeout, auth_in_progress = await self._auth.handle_token_async() if timeout is None and auth_in_progress is None: _logger.debug("No work done.") return False if timeout: _logger.info("CBS authentication timeout on connection: %r.", self._connection.container_id) raise TimeoutException("Authorization timeout.") if auth_in_progress: await self._connection.work_async() return False return True async def client_ready_async(self): """ Whether the handler has completed all start up processes such as establishing the connection, session, link and authentication, and is not ready to process messages. :rtype: bool """ if not await self.auth_complete_async(): return False if not await self._client_ready_async(): await self._connection.work_async() return False return True async def do_work_async(self): """Run a single connection iteration asynchronously. This will return `True` if the connection is still open and ready to be used for further work, or `False` if it needs to be shut down. :rtype: bool :raises: TimeoutError or ~uamqp.errors.ClientTimeout if CBS authentication timeout reached. """ if self._shutdown: return False if not await self.client_ready_async(): return True return await self._client_run_async() class SendClientAsync(client.SendClient, AMQPClientAsync): """An AMQP client for sending messages asynchronously. :param target: The target AMQP service endpoint. This can either be the URI as a string or a ~uamqp.address.Target object. :type target: str, bytes or ~uamqp.address.Target :param auth: Authentication for the connection. This should be one of the subclasses of uamqp.authentication.AMQPAuth. Currently this includes: - uamqp.authentication.SASLAnonymous - uamqp.authentication.SASLPlain - uamqp.authentication.SASTokenAsync If no authentication is supplied, SASLAnnoymous will be used by default. :type auth: ~uamqp.authentication.common.AMQPAuth :param client_name: The name for the client, also known as the Container ID. If no name is provided, a random GUID will be used. :type client_name: str or bytes :param loop: A user specified event loop. :type loop: ~asycnio.AbstractEventLoop :param debug: Whether to turn on network trace logs. If `True`, trace logs will be logged at INFO level. Default is `False`. :type debug: bool :param msg_timeout: A timeout in seconds for messages from when they have been added to the send queue to when the message is actually sent. This prevents potentially expired data from being sent. If set to 0, messages will not expire. Default is 0. :type msg_timeout: int :param error_policy: A policy for parsing errors on link, connection and message disposition to determine whether the error should be retryable. :type error_policy: ~uamqp.errors.ErrorPolicy :param keep_alive_interval: If set, a thread will be started to keep the connection alive during periods of user inactivity. The value will determine how long the thread will sleep (in seconds) between pinging the connection. If 0 or None, no thread will be started. :type keep_alive_interval: int :param send_settle_mode: The mode by which to settle message send operations. If set to `Unsettled`, the client will wait for a confirmation from the service that the message was successfully sent. If set to 'Settled', the client will not wait for confirmation and assume success. :type send_settle_mode: ~uamqp.constants.SenderSettleMode :param receive_settle_mode: The mode by which to settle message receive operations. If set to `PeekLock`, the receiver will lock a message once received until the client accepts or rejects the message. If set to `ReceiveAndDelete`, the service will assume successful receipt of the message and clear it from the queue. The default is `PeekLock`. :type receive_settle_mode: ~uamqp.constants.ReceiverSettleMode :param max_message_size: The maximum allowed message size negotiated for the Link. :type max_message_size: int :param link_properties: Metadata to be sent in the Link ATTACH frame. :type link_properties: dict :param link_credit: The sender Link credit that determines how many messages the Link will attempt to handle per connection iteration. :type link_credit: int :param max_frame_size: Maximum AMQP frame size. Default is 63488 bytes. :type max_frame_size: int :param channel_max: Maximum number of Session channels in the Connection. :type channel_max: int :param idle_timeout: Timeout in milliseconds after which the Connection will close if there is no further activity. :type idle_timeout: int :param properties: Connection properties. :type properties: dict :param remote_idle_timeout_empty_frame_send_ratio: Ratio of empty frames to idle time for Connections with no activity. Value must be between 0.0 and 1.0 inclusive. Default is 0.5. :type remote_idle_timeout_empty_frame_send_ratio: float :param incoming_window: The size of the allowed window for incoming messages. :type incoming_window: int :param outgoing_window: The size of the allowed window for outgoing messages. :type outgoing_window: int :param handle_max: The maximum number of concurrent link handles. :type handle_max: int :param on_attach: A callback function to be run on receipt of an ATTACH frame. The function must take 4 arguments: source, target, properties and error. :type on_attach: func[~uamqp.address.Source, ~uamqp.address.Target, dict, ~uamqp.errors.AMQPConnectionError] :param encoding: The encoding to use for parameters supplied as strings. Default is 'UTF-8' :type encoding: str """ def __init__( self, target, auth=None, client_name=None, loop=None, debug=False, msg_timeout=0, error_policy=None, keep_alive_interval=None, **kwargs): self.loop = loop or get_running_loop() client.SendClient.__init__( self, target, auth=auth, client_name=client_name, debug=debug, msg_timeout=msg_timeout, error_policy=error_policy, keep_alive_interval=keep_alive_interval, **kwargs) # AMQP object settings self.sender_type = MessageSenderAsync self._pending_messages_lock = asyncio.Lock() async def _client_ready_async(self): """Determine whether the client is ready to start sending messages. To be ready, the connection must be open and authentication complete, The Session, Link and MessageSender must be open and in non-errored states. :rtype: bool :raises: ~uamqp.errors.MessageHandlerError if the MessageSender goes into an error state. """ # pylint: disable=protected-access if not self.message_handler: self.message_handler = self.sender_type( self._session, self._name, self._remote_address, name='sender-link-{}'.format(uuid.uuid4()), debug=self._debug_trace, send_settle_mode=self._send_settle_mode, receive_settle_mode=self._receive_settle_mode, max_message_size=self._max_message_size, properties=self._link_properties, error_policy=self._error_policy, encoding=self._encoding, executor=self._connection._executor, loop=self.loop) await asyncio.shield(self.message_handler.open_async()) return False if self.message_handler.get_state() == constants.MessageSenderState.Error: raise errors.MessageHandlerError( "Message Sender Client is in an error state. " "Please confirm credentials and access permissions." "\nSee debug trace for more details.") if self.message_handler.get_state() != constants.MessageSenderState.Open: return False return True async def _transfer_message_async(self, message, timeout): sent = await asyncio.shield(self.message_handler.send_async(message, self._on_message_sent, timeout=timeout)) if not sent: _logger.info("Message not sent, raising RuntimeError.") raise RuntimeError("Message sender failed to add message data to outgoing queue.") async def _filter_pending_async(self): filtered = [] for message in self._pending_messages: if message.state in constants.DONE_STATES: continue elif message.state == constants.MessageState.WaitingForSendAck: self._waiting_messages += 1 elif message.state == constants.MessageState.WaitingToBeSent: message.state = constants.MessageState.WaitingForSendAck try: timeout = self._get_msg_timeout(message) if timeout is None: self._on_message_sent(message, constants.MessageSendResult.Timeout) if message.state != constants.MessageState.WaitingToBeSent: continue else: await self._transfer_message_async(message, timeout) except Exception as exp: # pylint: disable=broad-except self._on_message_sent(message, constants.MessageSendResult.Error, delivery_state=exp) if message.state != constants.MessageState.WaitingToBeSent: continue filtered.append(message) return filtered async def _client_run_async(self): """MessageSender Link is now open - perform message send on all pending messages. Will return True if operation successful and client can remain open for further work. :rtype: bool """ # pylint: disable=protected-access await self.message_handler.work_async() self._waiting_messages = 0 async with self._pending_messages_lock: self._pending_messages = await self._filter_pending_async() if self._backoff and not self._waiting_messages: _logger.info("Client told to backoff - sleeping for %r seconds", self._backoff) await self._connection.sleep_async(self._backoff) self._backoff = 0 await asyncio.shield(self._connection.work_async()) return True async def redirect_async(self, redirect, auth): """Redirect the client endpoint using a Link DETACH redirect response. :param redirect: The Link DETACH redirect details. :type redirect: ~uamqp.errors.LinkRedirect :param auth: Authentication credentials to the redirected endpoint. :type auth: ~uamqp.authentication.common.AMQPAuth """ if self._ext_connection: raise ValueError( "Clients with a shared connection cannot be " "automatically redirected.") if self.message_handler: await self.message_handler.destroy_async() self.message_handler = None async with self._pending_messages_lock: self._pending_messages = [] self._remote_address = address.Target(redirect.address) await self._redirect_async(redirect, auth) async def close_async(self): """Close down the client asynchronously. No further messages can be sent and the client cannot be re-opened. All pending, unsent messages will remain uncleared to allow them to be inspected and queued to a new client. """ await super(SendClientAsync, self).close_async() async def wait_async(self): """Run the client asynchronously until all
instancecreated + [Instance.InstanceName] # # # # Instance.ReadFromFile("01", "Lumpy", 2, 25, e="n", rk=50, leadtimestructure=0, lostsale=20, capacity= 5, longtimehoizon = True ) # Instance.SaveCompleteInstanceInExelFile() # instancecreated = instancecreated + [Instance.InstanceName] # # # # Instance.ReadFromFile("04", "NonStationary", 2, 25, e="n", rk=50, leadtimestructure=0, lostsale=20, capacity= 2, longtimehoizon = True ) # Instance.SaveCompleteInstanceInExelFile() # instancecreated = instancecreated + [Instance.InstanceName] # # # Instance.ReadFromFile("02", "SlowMoving", 2, 25, e="n", rk=50, leadtimestructure=0, lostsale=20, capacity= 2, longtimehoizon = True ) # Instance.SaveCompleteInstanceInExelFile() # instancecreated = instancecreated + [Instance.InstanceName] # # # # Instance.ReadFromFile("01", "Normal", 4, 25, e="n", rk=50, leadtimestructure=0, lostsale=40, capacity= 5, longtimehoizon = True ) # Instance.SaveCompleteInstanceInExelFile() # instancecreated = instancecreated + [Instance.InstanceName] # # # # Instance.ReadFromFile("02", "Lumpy", 4, 25, e="n", rk=50, leadtimestructure=0, lostsale=40, capacity= 2, longtimehoizon = True ) # Instance.SaveCompleteInstanceInExelFile() # instancecreated = instancecreated + [Instance.InstanceName] # # # # Instance.ReadFromFile("04", "NonStationary", 4, 25, e="n", rk=50, leadtimestructure=0, lostsale=40, capacity= 5, longtimehoizon = True ) # Instance.SaveCompleteInstanceInExelFile() # instancecreated = instancecreated + [Instance.InstanceName] # # # Instance.ReadFromFile("04", "SlowMoving", 4, 25, e="n", rk=50, leadtimestructure=0, lostsale=40, capacity= 2, longtimehoizon = True ) # Instance.SaveCompleteInstanceInExelFile() # instancecreated = instancecreated + [Instance.InstanceName] # # # # Instance.ReadFromFile("04", "Normal", 4, 25, e="n", rk=50, leadtimestructure=0, lostsale=40, capacity= 5, longtimehoizon = True ) # Instance.SaveCompleteInstanceInExelFile() # instancecreated = instancecreated + [Instance.InstanceName] # # # def GenerateInstancesUncapacitated(): instancecreated = [] ## Instance.ReadFromFile("K0014111", "Lumpy", 2, 0, e="n", rk=0, leadtimestructure=0, lostsale=20, longtimehoizon=False, capacity=10) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # Instance.ReadFromFile("G0044431", "SlowMoving", 4, 0, e="n", rk=0, leadtimestructure=0, lostsale=40, longtimehoizon=False, capacity=10) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] Instance.ReadFromFile("G5047534", "NonStationary", 4, 25, e="l", rk=50, leadtimestructure=1, lostsale=40, longtimehoizon=False, capacity=10) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # Instance.ReadFromFile("K0011113", "NonStationary", 2, 25, e="n", rk=25, leadtimestructure=0, lostsale=20, longtimehoizon=False, capacity=10) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] csvfile = open("./Instances/InstancesToSolveUncapacitated.csv", 'wb') data_rwriter = csv.writer(csvfile, delimiter=",", skipinitialspace=True) data_rwriter.writerow(instancecreated) def GenerateInstancesPreliminary(): instancecreated = [] ## Instance.ReadFromFile("K0014111", "Lumpy", 2, 0, e="n", rk=0, leadtimestructure=0, lostsale=20, longtimehoizon=False, capacity=10) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # Instance.ReadFromFile("G0041254", "Lumpy", 4, 0, e="n", rk=0, leadtimestructure=0, lostsale=40, longtimehoizon=False) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # Instance.ReadFromFile("K5017331", "Lumpy", 2, 0, e="l", rk=0, leadtimestructure=1, lostsale=20, longtimehoizon=False) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # Instance.ReadFromFile("G5044455", "Lumpy", 4, 0, e="l", rk=0, leadtimestructure=1, lostsale=40, longtimehoizon=False) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # Instance.ReadFromFile("G5041533", "Lumpy", 2, 0, e="n", rk=0, leadtimestructure=0, lostsale=20, longtimehoizon=False) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # Instance.ReadFromFile("K5017512", "SlowMoving", 2, 0, e="n", rk=0, leadtimestructure=0, lostsale=20, longtimehoizon=False) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # Instance.ReadFromFile("G0044431", "SlowMoving", 4, 0, e="n", rk=0, leadtimestructure=0, lostsale=40, longtimehoizon=False, capacity=10) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # Instance.ReadFromFile("K0011313", "SlowMoving", 2, 0, e="n", rk=0, leadtimestructure=1, lostsale=20, longtimehoizon=False) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # Instance.ReadFromFile("G0047254", "SlowMoving", 4, 0, e="l", rk=0, leadtimestructure=1, lostsale=40, longtimehoizon = False) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # Instance.ReadFromFile("K0011112", "SlowMoving", 2, 0, e="n", rk=0, leadtimestructure=0, lostsale=20, longtimehoizon = False) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] ## Instance.ReadFromFile("G5044355", "NonStationary", 2, 25, e="n", rk=50, leadtimestructure=0, lostsale=20, longtimehoizon = False, capacity=10) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # Instance.ReadFromFile("K5017435", "NonStationary", 4, 25, e="n", rk=75, leadtimestructure=0, lostsale=40, longtimehoizon = False) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # Instance.ReadFromFile("K5014255", "NonStationary", 2, 25, e="l", rk=25, leadtimestructure=1, lostsale=20, longtimehoizon = False) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # Instance.ReadFromFile("G5047534", "NonStationary", 4, 25, e="l", rk=50, leadtimestructure=1, lostsale=40, longtimehoizon = False) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # Instance.ReadFromFile("K0011113", "NonStationary", 2, 25, e="n", rk=25, leadtimestructure=0, lostsale=20, longtimehoizon = False) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # Instance.ReadFromFile("G0044432", "NonStationary", 2, 25, e="n", rk=50, leadtimestructure=0, lostsale=20, longtimehoizon = False) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # Instance.ReadFromFile("K0011131", "NonStationary", 4, 25, e="n", rk=75, leadtimestructure=0, lostsale=40, longtimehoizon = False) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # Instance.ReadFromFile("K5017552", "NonStationary", 2, 25, e="n", rk=50, leadtimestructure=1, lostsale=20, longtimehoizon = False, capacity=10) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # Instance.ReadFromFile("G5047313", "NonStationary", 4, 25, e="l", rk=50, leadtimestructure=1, lostsale=40, longtimehoizon = False) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # Instance.ReadFromFile("G0044214", "NonStationary", 2, 25, e="n", rk=25, leadtimestructure=0, lostsale=20, longtimehoizon = False) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] csvfile = open("./Instances/InstancesToSolve.csv", 'wb') data_rwriter = csv.writer(csvfile, delimiter=",", skipinitialspace=True) data_rwriter.writerow(instancecreated) def GenerateInstancesRH(): instancecreated = [] ## Instance.ReadFromFile("K0014111", "Lumpy", 2, 0, e="n", rk=0, leadtimestructure=0, lostsale=20, longtimehoizon=True, capacity=10) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # Instance.ReadFromFile("G0041254", "Lumpy", 4, 0, e="n", rk=0, leadtimestructure=0, lostsale=40, longtimehoizon=True) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # # Instance.ReadFromFile("K5017331", "Lumpy", 2, 0, e="l", rk=0, leadtimestructure=1, lostsale=20, longtimehoizon=True) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # # Instance.ReadFromFile("G5044455", "Lumpy", 4, 0, e="l", rk=0, leadtimestructure=1, lostsale=40, longtimehoizon=True) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # Instance.ReadFromFile("G5041553", "Lumpy", 2, 0, e="n", rk=0, leadtimestructure=0, lostsale=20, longtimehoizon=True) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # Instance.ReadFromFile("K5017512", "SlowMoving", 2, 0, e="n", rk=0, leadtimestructure=0, lostsale=20, longtimehoizon=True) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # Instance.ReadFromFile("G0044431", "SlowMoving", 4, 0, e="n", rk=0, leadtimestructure=0, lostsale=40, longtimehoizon=True, capacity=10) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # # Instance.ReadFromFile("K0011313", "SlowMoving", 2, 0, e="n", rk=0, leadtimestructure=1, lostsale=20, longtimehoizon=True) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # Instance.ReadFromFile("G0047254", "SlowMoving", 4, 0, e="l", rk=0, leadtimestructure=1, lostsale=40, longtimehoizon = True) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # # Instance.ReadFromFile("K0011112", "SlowMoving", 2, 0, e="n", rk=0, leadtimestructure=0, lostsale=20, longtimehoizon = True) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # ## Instance.ReadFromFile("G5044355", "NonStationary", 2, 25, e="n", rk=50, leadtimestructure=0, lostsale=20, longtimehoizon = True, capacity=10) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # Instance.ReadFromFile("K5017435", "NonStationary", 4, 25, e="n", rk=75, leadtimestructure=0, lostsale=40, longtimehoizon = True) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # # Instance.ReadFromFile("K5014255", "NonStationary", 2, 25, e="l", rk=25, leadtimestructure=1, lostsale=20, longtimehoizon = True) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # Instance.ReadFromFile("G5047534", "NonStationary", 4, 25, e="l", rk=50, leadtimestructure=1, lostsale=40, longtimehoizon = True) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # Instance.ReadFromFile("K0011153", "NonStationary", 2, 25, e="n", rk=25, leadtimestructure=0, lostsale=20, longtimehoizon = True) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # Instance.ReadFromFile("G0044432", "NonStationary", 2, 25, e="n", rk=50, leadtimestructure=0, lostsale=20, longtimehoizon = True) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # Instance.ReadFromFile("K0011131", "NonStationary", 4, 25, e="n", rk=75, leadtimestructure=0, lostsale=40, longtimehoizon = True) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # # Instance.ReadFromFile("K5017552", "NonStationary", 2, 25, e="n", rk=50, leadtimestructure=1, lostsale=20, longtimehoizon = True, capacity = 10 ) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # # Instance.ReadFromFile("G5047313", "NonStationary", 4, 25, e="l", rk=50, leadtimestructure=1, lostsale=40, longtimehoizon = True) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # # Instance.ReadFromFile("G0044214", "NonStationary", 2, 25, e="n", rk=25, leadtimestructure=0, lostsale=20, longtimehoizon = True) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] csvfile = open("./Instances/InstancesToSolveRH.csv", 'wb') data_rwriter = csv.writer(csvfile, delimiter=",", skipinitialspace=True) data_rwriter.writerow(instancecreated) def GenerateInstancesRHLargeLeadTime(): instancecreated = [] ## Instance.ReadFromFile("K0014111", "Lumpy", 2, 0, e="n", rk=0, leadtimestructure=2, lostsale=20, longtimehoizon=True, capacity=10) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # Instance.ReadFromFile("G0041254", "Lumpy", 4, 0, e="n", rk=0, leadtimestructure=2, lostsale=40, longtimehoizon=True) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # # Instance.ReadFromFile("K5017331", "Lumpy", 2, 0, e="l", rk=0, leadtimestructure=2, lostsale=20, longtimehoizon=True) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # # Instance.ReadFromFile("G5044455", "Lumpy", 4, 0, e="l", rk=0, leadtimestructure=2, lostsale=40, longtimehoizon=True) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # Instance.ReadFromFile("G5041553", "Lumpy", 2, 0, e="n", rk=0, leadtimestructure=2, lostsale=20, longtimehoizon=True) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # Instance.ReadFromFile("K5017512", "SlowMoving", 2, 0, e="n", rk=0, leadtimestructure=2, lostsale=20, longtimehoizon=True) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # Instance.ReadFromFile("G0044431", "SlowMoving", 4, 0, e="n", rk=0, leadtimestructure=2, lostsale=40, longtimehoizon=True, capacity=10) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # # Instance.ReadFromFile("K0011313", "SlowMoving", 2, 0, e="n", rk=0, leadtimestructure=2, lostsale=20, longtimehoizon=True) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # Instance.ReadFromFile("G0047254", "SlowMoving", 4, 0, e="l", rk=0, leadtimestructure=2, lostsale=40, longtimehoizon = True) Instance.SaveCompleteInstanceInExelFile() instancecreated = instancecreated + [Instance.InstanceName] # # # # Instance.ReadFromFile("K0011112", "SlowMoving", 2, 0, e="n", rk=0, leadtimestructure=2, lostsale=20, longtimehoizon = True) Instance.SaveCompleteInstanceInExelFile()
<gh_stars>0 #!/usr/bin/env python # vim: set fileencoding=utf-8 : # # Check the location of hot pixels in NRES images. This simple test will # help identify readout problems with nres01. # # <NAME> # Created: 2017-08-11 # Last modified: 2017-08-13 #-------------------------------------------------------------------------- #************************************************************************** #-------------------------------------------------------------------------- ## Current version: __version__ = "0.1.5" ## Modules: import getopt import signal import os import sys import time import numpy as np np.set_printoptions(suppress=True) ## FITS I/O: try: import astropy.io.fits as pf except ImportError: try: import pyfits as pf except ImportError: sys.stderr.write("\nError! No FITS I/O module found!\n" "Install either astropy.io.fits or pyfits and try again!\n\n") sys.exit(1) ## Time conversion: #try: # import astropy.time as astt #except ImportError: # sys.stderr.write("\nError: astropy module not installed!\n" # "Please install and try again.\n\n") # sys.exit(1) ##--------------------------------------------------------------------------## ## Colors for fancy terminal output: NRED = '\033[0;31m' ; BRED = '\033[1;31m' NGREEN = '\033[0;32m' ; BGREEN = '\033[1;32m' NYELLOW = '\033[0;33m' ; BYELLOW = '\033[1;33m' NBLUE = '\033[0;34m' ; BBLUE = '\033[1;34m' NMAG = '\033[0;35m' ; BMAG = '\033[1;35m' NCYAN = '\033[0;36m' ; BCYAN = '\033[1;36m' NWHITE = '\033[0;37m' ; BWHITE = '\033[1;37m' ENDC = '\033[0m' ## Suppress colors in cron jobs: if (os.getenv('FUNCDEF') == '--nocolors'): NRED = '' ; BRED = '' NGREEN = '' ; BGREEN = '' NYELLOW = '' ; BYELLOW = '' NBLUE = '' ; BBLUE = '' NMAG = '' ; BMAG = '' NCYAN = '' ; BCYAN = '' NWHITE = '' ; BWHITE = '' ENDC = '' ## Fancy text: degree_sign = u'\N{DEGREE SIGN}' ## Dividers: halfdiv = "----------------------------------------" fulldiv = halfdiv + halfdiv ##--------------------------------------------------------------------------## ## Catch interruption cleanly: def signal_handler(signum, frame): sys.stderr.write("\nInterrupted!\n\n") sys.exit(1) signal.signal(signal.SIGINT, signal_handler) ##--------------------------------------------------------------------------## ## Save FITS image with clobber (astropy / pyfits): #def qsave(iname, idata, header=None, padkeys=1000, **kwargs): # sys.stderr.write("Writing to '%s' ... " % iname) # if header: # while (len(header) < padkeys): # header.append() # pad header # if os.path.isfile(iname): # os.remove(iname) # pf.writeto(iname, idata, header=header, **kwargs) # sys.stderr.write("done.\n") ##--------------------------------------------------------------------------## ## Save FITS image with clobber (fitsio): #def qsave(iname, idata, header=None, **kwargs): # sys.stderr.write("Writing to '%s' ... " % iname) # #if os.path.isfile(iname): # # os.remove(iname) # fitsio.write(iname, idata, clobber=True, header=header, **kwargs) # sys.stderr.write("done.\n") ##--------------------------------------------------------------------------## def argnear(vec, val): return (np.abs(vec - val)).argmin() ## Robust location/scale estimate using median/MAD: def calc_ls_med_MAD(a, axis=None): """Return median and median absolute deviation of *a* (scaled to normal).""" med_val = np.median(a, axis=axis) sig_hat = (1.482602218 * np.median(np.abs(a - med_val), axis=axis)) return (med_val, sig_hat) ## Robust location/scale estimate using median/IQR: def calc_ls_med_IQR(a, axis=None): """Return median and inter-quartile range of *a* (scaled to normal).""" pctiles = np.percentile(a, [25, 50, 75], axis=axis) med_val = pctiles[1] sig_hat = (0.741301109 * (pctiles[2] - pctiles[0])) return (med_val, sig_hat) ## Settings: debug = False timer = False vlevel = 0 prog_name = 'verify-hot-pixels.py' full_prog = sys.argv[0] base_prog = os.path.basename(full_prog) num_todo = 0 ## Options: save_file = None camera_id = None ##--------------------------------------------------------------------------## ## Argument type-checking: def is_integer(asdf): try: int(asdf) return True except ValueError: return False def is_float(asdf): try: float(asdf) return True except ValueError: return False ##--------------------------------------------------------------------------## ##********************* Help and options menu: *********************## ##--------------------------------------------------------------------------## ## Syntax / how to run: def usage(stream): stream.write("\n" + "Usage: %s [options] nres_spectrum.fits\n" % base_prog + "Verify the location of hot pixels in NRES spectra.\n" + "Version: %s\n" % __version__ + "\n" + "Camera choice:\n" + " --nres01 verify nres01 hot pixels\n" + "\n" + "Output file (REQUIRED):\n" + " -o, --output=FILE save results to FILE\n" + "\n" + "Available options:\n" + " --debug extra debugging info\n" + " -h, --help print this page\n" + " -q, --quiet suppress unnecessary output\n" + " -t, --timer report program run-time\n" + " -v, --verbose more status updates\n" + "\n") #+ " -n, --numtodo=N stop after N iterations\n" #+ " -s, --sigcut=N clip data beyond N*sigma\n" ##--------------------------------------------------------------------------## ##********************* Parse command line: *********************## ##--------------------------------------------------------------------------## ## Options: short_opts = 'o:hqtv' # n:s: long_opts = ['nres01', 'output=', 'debug', 'help', 'quiet', 'timer', 'verbose'] # 'numtodo=', 'sigcut=' ## GNU-style parsing (with exception handling): try: options, remainder = getopt.gnu_getopt(sys.argv[1:], short_opts, long_opts) except getopt.GetoptError, err: sys.stderr.write("%s\n" % str(err)) usage(sys.stderr) sys.exit(2) ## Handle selected options: for opt, arg in options: # ------------------------------------------------ if (opt == '--debug'): debug = True sys.stderr.write(BRED + "\nDebugging output enabled!" + ENDC + "\n") # ------------------------------------------------ #elif ((opt == '-n') or (opt == '--numtodo')): # if not is_integer(arg): # sys.stderr.write("Error! Non-integer argument: %s\n\n" % arg) # sys.exit(1) # num_todo = int(arg) # if (vlevel >= 0): # msg = "Stopping after %d items." % num_todo # sys.stderr.write(NYELLOW + msg + ENDC + "\n") # ------------------------------------------------ elif (opt == '--nres01'): camera_id = 'nres01' if (vlevel >= 0): msg = "Selected camera: " + camera_id sys.stderr.write(NYELLOW + msg + ENDC + "\n") # ------------------------------------------------ elif ((opt == '-o') or (opt == '--output')): save_file = arg if (vlevel >= 0): msg = "Saving results to: " + arg sys.stderr.write(NYELLOW + msg + ENDC + "\n") # ------------------------------------------------ #elif ((opt == '-s') or (opt == '--sigcut')): # if not is_float(arg): # sys.stderr.write("Error! Non-numeric argument: %s\n\n" % arg) # sys.exit(1) # sigcut = float(arg) # if (vlevel >= 0): # msg = "Using %.2f-sigma outlier threshold." % sigcut # sys.stderr.write(NYELLOW + msg + ENDC + "\n") # ------------------------------------------------ elif ((opt == '-h') or (opt == '--help')): usage(sys.stdout) sys.exit(0) elif ((opt == '-q') or (opt == '--quiet')): vlevel -= 1 elif ((opt == '-t') or (opt == '--timer')): timer = True elif ((opt == '-v') | (opt == '--verbose')): vlevel += 1 sys.stderr.write(NYELLOW + "Increasing verbosity." + ENDC + "\n") # ------------------------------------------------ else: msg = "Unhandled option: %s" % opt sys.stderr.write(BRED + "\n" + msg + ENDC + "\n\n") sys.exit(1) pass ## Verbosity: if (vlevel >= 1): sys.stderr.write("%sVerbosity level: %d%s\n" % (NYELLOW, vlevel, ENDC)) ## Full command line if highly verbose: if (vlevel >= 2): sys.stderr.write("%s\nFull command line:%s\n" % (NCYAN, ENDC)) sys.stderr.write(" %s\n" % sys.argv) ##--------------------------------------------------------------------------## ## Output file is required: if not save_file: sys.stderr.write(BRED + "\nOutput file required!" + ENDC + "\n") usage(sys.stderr) sys.exit(1) ## Input file is required: if (len(remainder) < 1): sys.stderr.write(BRED + "\nInput file required!" + ENDC + "\n") usage(sys.stderr) sys.exit(1) ## Check for input file: data_file = remainder[0] if not os.path.isfile(data_file): msg = "%s error: file not found: %s" % (prog_name, data_file) sys.stderr.write("\n" + BRED + msg + ENDC + "\n") sys.exit(1) ##--------------------------------------------------------------------------## ## Known hot pixels (PIXEL COORDINATES [1-indexed]). hotpix_coords = {} hotpix_coords['nres01'] = [(3304, 584)] ## Hot pixel detection criterion: min_sigs = 20.0 # hot pixel must be >= N*sigma above median sig_buffer = 10.0 # hot pixel must be >= M*sigma above other pixels ## Make sure camera is specified and recognized: if not camera_id: sys.stderr.write("No camera selected!\n") usage(sys.stderr) sys.exit(1) if not camera_id in hotpix_coords.keys(): sys.stderr.write("Unrecognized camera: %s\n" % camera_id) usage(sys.stderr) sys.exit(1) ##--------------------------------------------------------------------------## ## Shift config: deltas = np.arange(-1, 2) xx, yy = np.meshgrid(deltas, deltas) dx_list = xx.flatten() dy_list = yy.flatten() ##--------------------------------------------------------------------------## ## Quick FITS I/O: #data_file = 'image.fits' #img_vals = pf.getdata(data_file) #hdr_keys = pf.getheader(data_file) #img_vals, hdr_keys = pf.getdata(data_file, header=True) img_vals, hdr_keys = pf.getdata(data_file, header=True, uint=True) # USHORT #img_vals, hdr_keys = fitsio.read(data_file, header=True) ## Bulk stats: img_med, img_iqrn = calc_ls_med_IQR(img_vals) ## Begin results: saving = {} saving['results'] = [ data_file, img_med, img_iqrn] saving['formats'] = [ '%s', '%9.2f', '%9.2f'] saving['columns'] = ['FILENAME', 'PIX_MED', 'PIX_IQRN'] ## Check area around each known hot pixel: shift_list = [] for (xpix, ypix) in hotpix_coords[camera_id]: if (vlevel >= 1): sys.stderr.write("xpix: %s\n" % str(xpix)) sys.stderr.write("ypix: %s\n" % str(ypix)) # select pixels and sort by value: values = img_vals[dy_list + (ypix - 1), dx_list + (xpix - 1)] order = np.argsort(values)[::-1] values = values[order] maxdex = order[0] # check for identical values: if np.unique(values).size == 1: sys.stderr.write("WARNING: identical pixel values!\n") sys.stderr.write(" --> %s\n" % str(values)) continue # stats to ensure confidence: pix_med, pix_iqrn = calc_ls_med_IQR(values) sigmas = (values - pix_med) / pix_iqrn if (vlevel >= 1): sys.stderr.write("pix_med: %9.3f\n" % pix_med) sys.stderr.write("pix_iqrn: %9.3f\n" % pix_iqrn) sys.stderr.write("sigmas: %s\n" % str(sigmas)) if (sigmas[0] > min_sigs) and (sigmas[0] - sigmas[1] > sig_buffer): delta = (dx_list[maxdex], dy_list[maxdex]) shift_list.append(delta) if (vlevel >= 1): sys.stderr.write("delta (x,y): (%d, %d)\n" % delta) ## Typical shift: n_shifts = len(shift_list) if n_shifts > 0: avg_shift = np.average(shift_list, axis=0) else: sys.stderr.write("WARNING: shift measurement inconclusive!\n") avg_shift = np.array([0.0, 0.0]) ## Update results: saving['results'].extend([avg_shift[0], avg_shift[1], n_shifts]) saving['formats'].extend([ '%6.2f', '%6.2f', '%2d']) saving['columns'].extend([ 'XSHIFT', 'YSHIFT', 'NSHIFTS']) ##--------------------------------------------------------------------------## ## Create output file with headers (if not present): if not os.path.isfile(save_file): with open(save_file, 'w') as f: f.write(' '.join(saving['columns']) + '\n') ## Append results to file: linefmt = ' '.join(saving['formats']) + '\n' savetxt = linefmt % tuple(saving['results']) with open(save_file, 'a') as f: f.write(savetxt) if vlevel >= -1: sys.stderr.write(savetxt) #f.write("%s %9.2f %9.2f %6.2f %6.2f %2d\n" % # (data_file, img_med, img_iqrn, avg_shift[0], avg_shift[1], n_shifts)) ###################################################################### # CHANGELOG (verify-hot-pixels.py): #--------------------------------------------------------------------- # # 2017-08-13: # -- Increased __version__ to 0.1.5. # -- Output file is now required. # -- Removed unused matplotlib import. # -- Now also calculate and report median/IQRN pixel value. # -- Increased __version__ to 0.1.1. # -- Added check for
<filename>dash_docs/chapters/dash_datatable/width/index.py<gh_stars>100-1000 from collections import OrderedDict import dash_core_components as dcc import dash_html_components as html import pandas as pd import dash_table from dash_docs import reusable_components as rc from dash_docs import datasets Display = rc.CreateDisplay({ 'dash_table': dash_table, 'html': html, 'df': datasets.df_regions, 'df_regions': datasets.df_regions, 'df_election': datasets.df_election, 'df_long': datasets.df_long, 'df_long_columns': datasets.df_long_columns, 'df_15_columns': datasets.df_15_columns, 'df_moby_dick': datasets.df_moby_dick, 'df_numeric': datasets.df_numeric, 'pd': pd }) layout = html.Div( children=[ html.H1('DataTable Width & Column Width'), html.H2('Default Width'), rc.Markdown( ''' By default, the table will expand to the width of its container. The width of the columns is determined automatically in order to accommodate the content in the cells. ''' ), Display( ''' result = dash_table.DataTable( data=df.to_dict('records'), columns=[{'id': c, 'name': c} for c in df.columns] ) ''' ), html.Hr(), rc.Markdown( ''' The default styles work well for a small number of columns and short text. However, if you are rendering a large number of columns or cells with long contents, then you'll need to employ one of the following overflow strategies to keep the table within its container. ''' ), rc.Markdown( ''' ## Wrapping onto Multiple Lines If your cells contain contain text with spaces, then you can overflow your content into multiple lines. ''' ), Display( ''' dash_table.DataTable( style_cell={ 'whiteSpace': 'normal', 'height': 'auto', }, data=df_election.to_dict('records'), columns=[{'id': c, 'name': c} for c in df_election.columns] ) '''), rc.Markdown( ''' `style_cell` updates the styling for the data cells & the header cells. To specify header styles, use `style_header`. To specify data cell styles, use `style_data`. This example keeps the header on a single line while wrapping the data cells. ''' ), Display( ''' df = df_election # no-display result = dash_table.DataTable( style_data={ 'whiteSpace': 'normal', 'height': 'auto', }, data=df.to_dict('records'), columns=[{'id': c, 'name': c} for c in df.columns] ) '''), rc.Markdown( ''' ### Denser Multi-Line Cells with Line-Height If you are displaying lots of text in your cells, then you may want to make the text appear a little more dense by shortening up the line-height. By default (as above), it's around 22px. Here, it's 15px. ''' ), Display( ''' df = df_election # no-display result = dash_table.DataTable( style_data={ 'whiteSpace': 'normal', 'height': 'auto', 'lineHeight': '15px' }, data=df.to_dict('records'), columns=[{'id': c, 'name': c} for c in df.columns] ) '''), rc.Markdown( ''' ### Wrapping onto Multiple Lines while Constraining the Height of Cells If your text is really long, then you can constrain the height of the cells and display a tooltip when hovering over the cell. ''' ), Display( """ df = df_moby_dick # no-display result = dash_table.DataTable( style_data={ 'whiteSpace': 'normal', }, data=df.to_dict('records'), columns=[{'id': c, 'name': c} for c in df.columns], css=[{ 'selector': '.dash-spreadsheet td div', 'rule': ''' line-height: 15px; max-height: 30px; min-height: 30px; height: 30px; display: block; overflow-y: hidden; ''' }], tooltip_data=[ { column: {'value': str(value), 'type': 'markdown'} for column, value in row.items() } for row in df.to_dict('records') ], tooltip_duration=None, style_cell={'textAlign': 'left'} # left align text in columns for readability ) """), rc.Markdown( ''' Hover over the cells to see the tooltip. Why the `css`? Fixed height cells are tricky because, [by CSS 2.1 rules](https://www.w3.org/TR/CSS21/tables.html#height-layout), the height of a table cell is "the minimum height required by the content". So, here we are setting the height of the cell indirectly by setting the div _within_ the cell. In this example, we display two lines of data by setting the `line-height` to be 15px and the height of each cell to be 30px. The second sentence is cut off. There are a few **limitations** with this method: 1. It is not possible to display ellipses with this method. 2. It is not possible to set a max-height. All of the cells need to be the same height. Subscribe to [plotly/dash-table#737](https://github.com/plotly/dash-table/issues/737) for updates or other workarounds on this issue. ''' ), rc.Markdown( """ ## Overflowing Into Ellipses Alternatively, you can keep the content on a single line but display a set of ellipses if the content is too long to fit into the cell. Here, `max-width` is set to 0. It could be any number, the only important thing is that it is supplied. The behaviour will be the same whether it is 0 or 50. If you want to just hide the content instead of displaying ellipses, then set `textOverflow` to `'clip'` instead of `'ellipsis'`. """ ), Display( ''' df = df_election # no-display result = dash_table.DataTable( data=df.to_dict('records'), columns=[{'id': c, 'name': c} for c in df.columns], style_cell={ 'overflow': 'hidden', 'textOverflow': 'ellipsis', 'maxWidth': 0 } ) '''), rc.Markdown( ''' > In the example above, ellipsis are not displayed for the header. > We consider this a bug, subscribe to [plotly/dash-table#735](https://github.com/plotly/dash-table/issues/735) for updates. '''), rc.Markdown( ''' ### Ellipses & Tooltips If you are display text data that is cut off by ellipses, then you can include tooltips so that the full text appears on hover. By setting `tooltip_duration` to `None`, the tooltip will persist as long as the mouse pointer is above the cell, and it will disappear when the pointer moves away. You can override this by passing in a number in milliseconds (e.g. 2000 if you want it to disappear after two seconds). ''' ), Display( ''' df = df_election # no-display result = dash_table.DataTable( data=df.to_dict('records'), columns=[{'id': c, 'name': c} for c in df.columns], style_cell={ 'overflow': 'hidden', 'textOverflow': 'ellipsis', 'maxWidth': 0, }, tooltip_data=[ { column: {'value': str(value), 'type': 'markdown'} for column, value in row.items() } for row in df.to_dict('records') ], tooltip_duration=None ) '''), rc.Markdown( ''' ## Horizontal Scroll Instead of trying to fit all of the content in the container, you could overflow the entire container into a scrollable container. ''' ), Display( ''' df = df_election # no-display result = dash_table.DataTable( data=df.to_dict('records'), columns=[{'id': c, 'name': c} for c in df.columns], style_table={'overflowX': 'auto'}, ) '''), rc.Markdown( ''' Note how we haven't explicitly set the width of the individual columns yet. The widths of the columns have been computed dynamically depending on the width of the table and the width of the cell's contents. In the example above, by providing a scrollbar, we're effectively giving the table as much width as it needs in order to fit the entire width of the cell contents on a single line. ''' ), rc.Markdown('### Horizontal Scroll with Fixed-Width Columns & Cell Wrapping'), rc.Markdown( ''' Alternatively, you can fix the width of each column by adding `width`. In this case, the column's width will be constant, even if its contents are shorter or wider. ''' ), Display( ''' df = df_election # no-display result = dash_table.DataTable( data=df.to_dict('records'), columns=[{'id': c, 'name': c} for c in df.columns], style_table={'overflowX': 'auto'}, style_cell={ 'height': 'auto', # all three widths are needed 'minWidth': '180px', 'width': '180px', 'maxWidth': '180px', 'whiteSpace': 'normal' } ) '''), rc.Markdown('### Horizontal Scroll with Fixed-Width & Ellipses'), Display( ''' df = df_election # no-display result = dash_table.DataTable( data=df.to_dict('records'), columns=[{'id': c, 'name': c} for c in df.columns], style_table={'overflowX': 'auto'}, style_cell={ # all three widths are needed 'minWidth': '180px', 'width': '180px', 'maxWidth': '180px', 'overflow': 'hidden', 'textOverflow': 'ellipsis', } ) '''), rc.Markdown( ''' ### Horizontal Scrolling via Fixed Columns You can also add a horizontal scrollbar to your table by fixing the leftmost columns with `fixed_columns`. ''' ), Display( ''' df = df_election # no-display result = dash_table.DataTable( data=df.to_dict('records'), columns=[{'id': c, 'name': c} for c in df.columns], fixed_columns={'headers': True, 'data': 1}, style_table={'minWidth': '100%'} ) '''), rc.Markdown( ''' Here is the same example but with *fixed-width cells & ellipses*. ''' ), Display( ''' df = df_election # no-display result = dash_table.DataTable( data=df.to_dict('records'), columns=[{'id': c, 'name': c} for c in df.columns], fixed_columns={ 'headers': True, 'data': 1 }, style_table={'minWidth': '100%'}, style_cell={ # all three widths are needed 'minWidth': '180px', 'width': '180px', 'maxWidth': '180px', 'overflow': 'hidden', 'textOverflow': 'ellipsis', } ) '''), rc.Markdown("## Setting Column Widths"), rc.Markdown( ''' ### Percentage Based Widths The widths of individual columns can be supplied through the `style_cell_conditional` property. These widths can be specified as percentages or fixed pixels.
<reponame>shamimmamun/qosftask4<filename>qosftask4.py #!/usr/bin/env python # coding: utf-8 # In[2]: import numpy as np from qiskit.circuit import QuantumCircuit from qiskit.circuit.library import TGate, HGate, TdgGate,SGate from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit.transpiler.passes.synthesis.solovay_kitaev import SolovayKitaevDecomposition from qiskit.quantum_info import Operator from itertools import tee,islice # In[ ]: def rz(x,circuit,qubit): circuit.rz(x,qubit ) dag = circuit_to_dag(circuit) basis_gates = [TGate(), TdgGate(), HGate()] skd = SolovayKitaevDecomposition(recursion_degree=2, basis_gates=basis_gates) discretized = dag_to_circuit(skd.run(dag)) pp=discretized.qasm() with open('ss1.qasm', 'w') as f: print(pp,file=f) def parse_qasm(qasm): lns = qasm.split(',') n = (lns[0]) #gates = [l.split(" ") for l in lns[4:] if l] gates = [l.split("") for l in lns[3:] if l] return {'n': n, 'gates': gates, 'n_gates': len(gates)} def parse_qasm_file(fname,fname1): a = ['OPENQASM 2.0;','include "qelib1.inc";','qreg q[1];'] with open(fname) as fin, open(fname1 , "w+") as fout: lines=fin.readlines() p=[] l=[] for i in range(4): p.append(lines[i::3]) ll=[''.join(str(twos))+'\n' for twos in zip(*p)] for line in ll: for word in a: line = line.replace(word, "1") line=line.replace(';',"") line=line.replace('q[',"") line=line.replace(']',"") line=line.replace('(',"") line=line.replace(')',"") line=line.replace('n',"") line=line.replace(',',"") line=line.replace("'","") line=line.replace(' \ ',' ' ) line=line.replace('tdg','T') fout.write(line) fin.close() fout.close() #gates = [l.split(" ") for l in lns[4:] if l] return parse_qasm(open(fname1).read()) gg=parse_qasm_file('ss1.qasm','ss567112390.qasm') print(gg) #l=[' '.join(twos) for twos in zip(gates[::2],gates[1::2])] def inverse_parse_file(fname1,qubit): with open(fname1+str(qubit)+'.qasm') as fin ,open(fname1+str(qubit+1)+'.qasm ','w+') as fout : l=fin.read().split(str(qubit)+' ') for line in l: fout.write(line+str(qubit)+' '+'\n') fin.close() fout.close() qc=QuantumCircuit(2) with open(fname1+str(qubit+1)+'.qasm') as fin: l=fin.readlines() count=0 for line in l: if 'cx' in line : ll=[] for i in range(len(line)): if line[i]!= 'c' and line[i]!='x' and line[i]!= ' ' and line[i]!= '\n': ll.append(line[i] ) qc.cx(int(ll[0]),int(ll[1])) count=count+1 if 'T' in line : ll=[] for i in range(len(line)): if line[i]!= 'h' and line[i]!= 't' and line[i]!= 'T' and line[i]!= ' ' and line[i]!= '\n': ll.append(line[i] ) qc.tdg(int(ll[0])) count=count+1 if 't' in line : ll=[] for i in range(len(line)): if line[i]!= 'h' and line[i]!= 't' and line[i]!= 'T' and line[i]!= ' ' and line[i]!= '\n': ll.append(line[i] ) qc.t(int(ll[0])) count=count+1 if 'h' in line : ll=[] for i in range(len(line)): if line[i]!= 'h' and line[i]!= 't' and line[i]!= 'T' and line[i]!= ' ' and line[i]!= '\n': ll.append(line[i] ) qc.h(int(ll[0])) count=count+1 if 'ccx' in line: ll=[] for i in range(len(line)): if line[i] !='c' and line[i] !='x' and line[i] != ' ' and line[i] != '\n': ll.append(line[i]) ccx(int(ll[0]),int(ll[1]),int(ll[2]),qc) print( qc.draw()) gh=inverse_parse_file('ss56711239',0) # In[ ]: def ccx(ii,j,k,qc): qc.h(k) qc.cx(j,k) qc.tdg(k) qc.cx(ii,k) qc.t(k) qc.cx(ii,j) qc.tdg(k) qc.cx(ii,k) qc.t(ii) qc.t(k) qc.cx(ii,j) qc.h(k) qc.t(ii) qc.tdg(j) qc.cx(ii,j) pppp=qc.qasm() with open('ss1.qasm', 'w') as f: print(pppp,file=f) def parse_qasm(qasm): lns = qasm.split(',') n = (lns[0]) gates = [l.split("") for l in lns[3:] if l] return {'n': n, 'gates': gates, 'n_gates': len(gates)} def parse_qasm_file(fname,fname1): a = ['OPENQASM 2.0;','include "qelib1.inc";','qreg q[1];'] with open(fname) as fin, open(fname1 , "w+") as fout: lines=fin.readlines() p=[] l=[] for i in range(4): p.append(lines[i::4]) ll=[''.join(str(twos))+'\n' for twos in zip(*p)] for line in ll: for word in a: line = line.replace(word, "1") line=line.replace(';',"") line=line.replace('q[',"") line=line.replace(']',"") line=line.replace('(',"") line=line.replace(')',"") line=line.replace('n',"") line=line.replace(',',"") line=line.replace("'","") #line=line.replace(" 0\ "," ") #line=line.replace(" 0"," ") line=line.replace('\ ',' ' ) line=line.replace('tdg','T') #line=line.replace('tdg tdg','sdg') fout.write(line) fin.close() fout.close() return parse_qasm(open(fname1).read()) gg=parse_qasm_file('ss1.qasm','ss56711230.qasm') print(gg) #l=[' '.join(twos) for twos in zip(gates[::2],gates[1::2])] gh=inverse_parse_file('ss5671123') print(gh) # In[ ]: import numpy as np from qiskit.circuit import QuantumCircuit from qiskit.circuit.library import TGate, HGate, TdgGate,SGate from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit.transpiler.passes.synthesis.solovay_kitaev import SolovayKitaevDecomposition from qiskit.quantum_info import Operator from itertools import tee,islice circuit = QuantumCircuit(1) circuit.rz(np.pi/5,0 ) dag = circuit_to_dag(circuit) print('Original circuit:') print(circuit.draw()) basis_gates = [TGate(), TdgGate(), HGate()] skd = SolovayKitaevDecomposition(recursion_degree=2, basis_gates=basis_gates) discretized = dag_to_circuit(skd.run(dag)) qc = QuantumCircuit(3) qc.h(0) qc.y(1) qc.h(2) qc.cx(0,1) qc.ccx(0,1,2) qc.z(1) qc.rz(np.pi/5,2) pppp=qc.qasm() #print('Discretized circuit:') ##print(discretized.draw()) #print('Error:', np.linalg.norm(Operator(circuit).data - Operator(discretized).data)) with open('ss1.qasm', 'w') as f: print(pppp,file=f) def parse_qasm(qasm): """Parse qasm from a string. """ lns = qasm.split(',') n = (lns[0]) #gates = [l.split(" ") for l in lns[4:] if l] gates = [l.split("") for l in lns[3:] if l] return {'n': n, 'gates': gates, 'n_gates': len(gates)} def parse_qasm_file(fname,fname1): a = ['OPENQASM 2.0;','include "qelib1.inc";','qreg q[1];'] with open(fname) as fin, open(fname1 , "w+") as fout: lines=fin.readlines() p=[] l=[] for i in range(4): p.append(lines[i::4]) ll=[''.join(str(twos))+'\n' for twos in zip(*p)] for line in ll: for word in a: line = line.replace(word, "1") line=line.replace(';',"") line=line.replace('q[',"") line=line.replace(']',"") line=line.replace('(',"") line=line.replace(')',"") line=line.replace('n',"") line=line.replace(',',"") line=line.replace("'","") #line=line.replace(" 0\ "," ") #line=line.replace(" 0"," ") line=line.replace('\ ',' ' ) #line=line.replace('tdg','T') #line=line.replace('tdg tdg','sdg') fout.write(line) fin.close() fout.close() #gates = [l.split(" ") for l in lns[4:] if l] """Parse a qasm file. """ return parse_qasm(open(fname1).read()) gg=parse_qasm_file('ss1.qasm','ss567112380.qasm') print(gg) #l=[' '.join(twos) for twos in zip(gates[::2],gates[1::2])] def inverse_parse_file(fname1): for i in range(10): with open(fname1+str(i)+'.qasm') as fin ,open(fname1+str(i+1)+'.qasm ','w+') as fout : l=fin.read().split(str(i)+' ') for line in l: fout.write(line+str(i)+' '+'\n') fin.close() fout.close() qc=QuantumCircuit(3) with open(fname1+str(10)+'.qasm') as fin: l=fin.readlines() count=0 for line in l: if 'cx' in line : ll=[] for i in range(len(line)): if line[i]!= 'c' and line[i]!='x' and line[i]!= ' ' and line[i]!= '\n': ll.append(line[i] ) qc.cx(int(ll[0]),int(ll[1])) count=count+1 if 'T' in line : ll=[] for i in range(len(line)): if line[i]!= 'T' and line[i]!= ' ' and line[i]!= '\n': ll.append(line[i] ) qc.tdg(int(ll[0])) count=count+1 if 't' in line : ll=[] for i in range(len(line)): if line[i]!= 't' and line[i]!= ' ' and line[i]!= '\n': ll.append(line[i] ) qc.t(int(ll[0])) count=count+1 if 'h' in line : ll=[] for i in range(len(line)): if line[i]!= 'h' and line[i]!= ' ' and line[i]!= '\n': ll.append(line[i] ) qc.h(int(ll[0])) count=count+1 if 'ccx' in line: ll=[] for i in range(len(line)): if line[i] !='c' and line[i] !='x' and line[i] != ' ' and line[i] != '\n': ll.append(line[i]) ccx(int(ll[0]),int(ll[1]),int(ll[2]),qc) return qc.draw() gh=inverse_parse_file('ss56711238') print(gh) # In[ ]: def cost(fname): for i in range(10): with open(fname+str(i)+'.qasm') as fin ,open(fname+str(i+1)+'.qasm ','w+') as fout : l=fin.read().split(str(i)+' ') for line in l: fout.write(line+str(i)+' '+'\n') fin.close() fout.close() with open(fname+str(10)+'.qasm') as fin: l=fin.readlines() count=0 for line in l: if 'cx' in line : ll=[] for i in range(len(line)): if line[i]!= 'c' and line[i]!='x' and line[i]!= ' ' and line[i]!= '\n': ll.append(line[i] ) qc.cx(int(ll[0]),int(ll[1])) count=count+1 if 'T' in line : ll=[] for i in range(len(line)): if line[i]!= 'T' and line[i]!= ' ' and line[i]!= '\n': ll.append(line[i] ) qc.tdg(int(ll[0])) count=count+1 if 't' in line : ll=[] for i in range(len(line)): if line[i]!= 't' and line[i]!= ' ' and line[i]!= '\n': ll.append(line[i] ) qc.t(int(ll[0])) count=count+1 if 'h' in line : ll=[] for i in range(len(line)): if line[i]!= 'h' and line[i]!= ' ' and line[i]!= '\n': ll.append(line[i] ) qc.h(int(ll[0])) count=count+1 return count # In[ ]: def checking_pattern(x,fname): from itertools import permutations def cxhhcx(fname1,fname2,num_qubits): p=[] for i in range(num_qubits): p.append(i) perm=permutations(p) with open(fname1) as fin, open(fname2,'w+') as fout: lines=fin.readlines() for i in range(x): for line in lines: for item in list(perm): j in list(item) line=line.replace('cx'+' '+str(j[0])+str(j[1])+' '+'h'+" "+str(j[0])+' '+'h'+' '+str(j[1])+' '+ 'cx'+' '+str(j[0])+str(j[1])+' '+'h'+" "+str(j[0])+' '+'h'+' '+str(j[1])+' '+'cx'+' '+str(j[0])+str(j[1])+' '+'h'+" "+str(j[0])+' '+'h'+' '+ str(j[1]),'cx'+' '+str(j[0])+str(j[1])+' '+'cx'+' '+str(j[1])+str(j[0])+' '+'cx'+' '+str(j[0])+str(j[1])) fout.write() fin.close() fout.close() return cost(fname2) def cxcx2to3(fname1,fname2,num_qubits): p=[] for i in range(num_qubits): p.append(i) perm=permutations(p) with open(fname1) as fin, open(fname2,'w+') as fout: lines=fin.readlines() for i in range(x): for line in lines: for item in list(perm): j = list(item) line=line.replace('cx'+' '+str(j[1])+str(j[2])+' '+'cx'+' '+str(j[0])+str(j[1]),'cx'+' '+str(j[0])+str(j[1])+' '+'cx'+' '+str(j[1])+str(j[2])+' '+'cx'+' '+str(j[0])+str(j[2])) fout.write() fin.close() fout.close() return cost(fname2) def cxcxcx(fname1,fname2,num_qubits): p=[] for i in range(num_qubits): p.append(i) perm=permutations(p) with open(fname1) as fin, open(fname2,'w+') as fout: lines=fin.readlines() for i in range(x): for line in lines: for item in list(perm): j = list(item) line=line.replace('cx'+' '+str(j[1])+str(j[0])+' '+'cx'+' '+str(j[0])+str(j[2])+' '+'cx'+' '+str(j[1])+str(j[0]),'cx'+' '+str(j[0])+str(j[1])+' '+'cx'+' '+str(j[1])+str(j[2])+' '+'cx'+' '+str(j[0])+str(j[1])) fout.write() fin.close() fout.close() return cost(fname2) def cx3to2cx(fname1,fname2,num_qubits): p=[] for i in range(num_qubits): p.append(i) perm=permutations(p) with open(fname1) as fin, open(fname2,'w+') as fout: lines=fin.readlines() for i in range(x): for line in lines: for item in list(perm): j = list(item): line=line.replace('cx'+' '+str(j[0])+str(j[1])+' '+'cx'+' '+str(j[1])+str(j[2])+' '+'cx'+' '+str(j[0])+str(j[1]),'cx'+' '+str(j[0])+str(j[2])+' '+'cx'+' '+str(j[1])+str(j[2])) fout.write() fin.close() fout.close() return cost(fname2) def cx3to3cx(fname1,fname2,num_qubits): p=[] for i in range(num_qubits): p.append(i) perm=permutations(p) with open(fname1) as fin, open(fname2,'w+') as fout: lines=fin.readlines() for i in range(x): for line in lines: for item in list(perm): j =list(item) line=line.replace('cx'+' '+str(j[1])+str(j[2])+' '+'cx'+' '+str(j[0])+str(j[1])+' '+'cx'+' '+str(j[1])+str(j[2]),'cx'+' '+str(j[0])+str(j[2])+' '+'cx'+' '+str(j[0])+str(j[1])) fout.write() fin.close() fout.close() return
import copy import os import re import sys if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest import shutil import time import replica_status_test from . import session from . import settings from .. import lib from .. import test from ..configuration import IrodsConfig from .resource_suite import ResourceBase class Test_iPhymv(ResourceBase, unittest.TestCase): def setUp(self): super(Test_iPhymv, self).setUp() irods_config = IrodsConfig() self.resource_1 = 'unix1Resc' self.resource_2 = 'unix2Resc' self.admin.assert_icommand("iadmin mkresc randResc random", 'STDOUT_SINGLELINE', 'random') self.admin.assert_icommand( ['iadmin', 'mkresc', self.resource_1, 'unixfilesystem', ':'.join([ test.settings.HOSTNAME_1, os.path.join(irods_config.irods_directory, 'unix1RescVault') ]) ], 'STDOUT_SINGLELINE', 'unixfilesystem') self.admin.assert_icommand( ['iadmin', 'mkresc', self.resource_2, 'unixfilesystem', ':'.join([ test.settings.HOSTNAME_2, os.path.join(irods_config.irods_directory, 'unix2RescVault') ]) ], 'STDOUT_SINGLELINE', 'unixfilesystem') self.admin.assert_icommand("iadmin addchildtoresc randResc unix1Resc") self.admin.assert_icommand("iadmin addchildtoresc randResc unix2Resc") def tearDown(self): self.admin.assert_icommand("iadmin rmchildfromresc randResc unix2Resc") self.admin.assert_icommand("iadmin rmchildfromresc randResc unix1Resc") self.admin.assert_icommand("iadmin rmresc unix2Resc") self.admin.assert_icommand("iadmin rmresc unix1Resc") self.admin.assert_icommand("iadmin rmresc randResc") super(Test_iPhymv, self).tearDown() def get_source_resource(self, object_path): return self.admin.run_icommand(['iquest', '%s', '''"select RESC_NAME where COLL_NAME = '{0}' and DATA_NAME = '{1}'"'''.format( os.path.dirname(object_path), os.path.basename(object_path))])[0].strip().strip() def get_destination_resource(self, source_resc): return self.resource_2 if source_resc == self.resource_1 else self.resource_1 def get_source_and_destination_resources(self, object_path): source_resource = self.get_source_resource(object_path) destination_resource = self.get_destination_resource(source_resource) return (source_resource, destination_resource) def test_iphymv_to_child_resource__2933(self): filepath = os.path.join(self.admin.local_session_dir, 'file') lib.make_file(filepath, 1) file_name = 'file' dest_path = os.path.join(self.admin.session_collection, file_name) self.admin.assert_icommand('iput -fR randResc ' + filepath + ' ' + dest_path) self.admin.assert_icommand('ils -L ' + dest_path, 'STDOUT_SINGLELINE', 'randResc') source_resc, dest_resc = self.get_source_and_destination_resources(dest_path) self.admin.assert_icommand(['iphymv', '-S', source_resc, '-R', dest_resc, dest_path]) self.admin.assert_icommand('irm -f ' + dest_path) def test_iphymv_to_resc_hier__2933(self): filepath = os.path.join(self.admin.local_session_dir, 'file') lib.make_file(filepath, 1) file_name = 'file' dest_path = os.path.join(self.admin.session_collection, file_name) self.admin.assert_icommand('iput -fR randResc ' + filepath + ' ' + dest_path) self.admin.assert_icommand('ils -l ' + dest_path, 'STDOUT_SINGLELINE', 'randResc') source_resc, dest_resc = self.get_source_and_destination_resources(dest_path) self.admin.assert_icommand(['iphymv', '-S', 'randResc;{}'.format(source_resc), '-R', 'randResc;{}'.format(dest_resc), dest_path]) self.admin.assert_icommand('irm -f ' + dest_path) def test_iphymv_invalid_resource__2821(self): filepath = os.path.join(self.admin.local_session_dir, 'file') lib.make_file(filepath, 1) dest_path = self.admin.session_collection + '/file' self.admin.assert_icommand('iput ' + filepath) self.admin.assert_icommand('iphymv -S invalidResc -R demoResc '+dest_path, 'STDERR_SINGLELINE', 'SYS_RESC_DOES_NOT_EXIST') self.admin.assert_icommand('iphymv -S demoResc -R invalidResc '+dest_path, 'STDERR_SINGLELINE', 'SYS_RESC_DOES_NOT_EXIST') @unittest.skipIf(test.settings.TOPOLOGY_FROM_RESOURCE_SERVER, 'Skip for Topology Testing on Resource Server') def test_iphymv_unable_to_unlink__2820(self): filename = 'test_iphymv_unable_to_unlink__2820' localfile = os.path.join(self.admin.local_session_dir, filename) lib.make_file(localfile, 1) dest_path = os.path.join(self.admin.session_collection, filename) try: # put a data object so that a file appears in the vault self.admin.assert_icommand(['iput', localfile, dest_path]) # modify the permissions on the physical file in the vault to deny unlinking to the service account filepath = os.path.join(self.admin.get_vault_session_path(), filename) self.admin.assert_icommand(['ils', '-L', dest_path], 'STDOUT', filepath) os.chmod(filepath, 0444) # attempt and fail to phymv the replica (due to no permissions for unlink) self.admin.assert_icommand(['iphymv', '-S', 'demoResc', '-R', 'TestResc', dest_path], 'STDERR_SINGLELINE', 'Permission denied') self.admin.assert_icommand(['ils', '-L', dest_path], 'STDOUT', 'demoResc') # ensure that physical file was not unlinked self.assertTrue(os.path.exists(filepath)) # set the permissions on the physical file back to allow unlinking to the service account os.chmod(filepath, 0666) # attempt to phymv the replica (and succeed) self.admin.assert_icommand(['iphymv', '-S', 'demoResc', '-R', 'TestResc', dest_path]) # ensure that file was unlinked self.assertFalse(os.path.exists(filepath)) self.admin.assert_icommand(['ils', '-L', dest_path], 'STDOUT', 'TestResc') finally: os.unlink(localfile) self.admin.assert_icommand(['irm', '-f', dest_path]) def test_iphymv_to_self(self): filename = 'test_iphymv_to_self' filepath = os.path.join(self.admin.local_session_dir, filename) lib.make_file(filepath, 1) try: self.admin.assert_icommand(['iput', filepath, filename]) self.admin.assert_icommand(['ils', '-L'], 'STDOUT', [' 0 ', 'demoResc', ' & ', filename]) self.admin.assert_icommand(['iphymv', '-S', 'demoResc', '-R', 'demoResc', filename], 'STDERR', 'SYS_NOT_ALLOWED') self.admin.assert_icommand(['ils', '-L'], 'STDOUT', [' 0 ', 'demoResc', ' & ', filename]) finally: self.admin.run_icommand(['irm', '-f', filename]) if os.path.exists(filepath): os.unlink(filepath) def test_iphymv_retains_system_metadata(self): file_name = 'test_iphymv_retains_system_metadata' filepath = os.path.join(self.admin.local_session_dir, file_name) lib.make_file(filepath, 1) dest_path = os.path.join(self.admin.session_collection, file_name) source_resource = self.admin.default_resource destination_resource = 'unix1Resc' attributes = [ 'DATA_CHECKSUM', 'DATA_CREATE_TIME', 'DATA_MODIFY_TIME', 'DATA_REPL_NUM', 'DATA_REPL_STATUS', 'DATA_SIZE' ] system_metadata_genquery = '''"select {0} where COLL_NAME = '{1}' and DATA_NAME = '{2}'"'''.format( ','.join(attributes), os.path.dirname(dest_path), os.path.basename(dest_path)) try: # put in a file and get the system metadata self.admin.assert_icommand(['iput', '-K', '-R', source_resource, filepath, dest_path]) self.admin.assert_icommand(['ils', '-l', dest_path], 'STDOUT_SINGLELINE', source_resource) source_system_metadata = self.admin.run_icommand(['iquest', '%s' * len(attributes), system_metadata_genquery])[0].strip().split() # sleep to make sure the modify time would change (but doesn't!) time.sleep(2) # phymv the replica and get the system metadata self.admin.assert_icommand(['iphymv', '-S', source_resource, '-R', destination_resource, dest_path]) self.admin.assert_icommand(['ils', '-l', dest_path], 'STDOUT_SINGLELINE', destination_resource) destination_system_metadata = self.admin.run_icommand(['iquest', '%s' * len(attributes), system_metadata_genquery])[0].strip().split() # assert that everything lines up self.assertEqual(len(source_system_metadata), len(destination_system_metadata)) for i,_ in enumerate(source_system_metadata): self.assertEqual(source_system_metadata[i], destination_system_metadata[i]) finally: self.admin.assert_icommand(['irm', '-f', file_name]) def test_multithreaded_iphymv__issue_5478(self): def do_test(size, threads): file_name = 'test_multithreaded_iphymv__issue_5478' local_file = os.path.join(self.user0.local_session_dir, file_name) dest_path = os.path.join(self.user0.session_collection, file_name) try: lib.make_file(local_file, size) self.user0.assert_icommand(['iput', '-R', 'randResc', local_file, dest_path]) source_resc, dest_resc = self.get_source_and_destination_resources(dest_path) phymv_thread_count = self.user0.run_icommand(['iphymv', '-v', '-S', source_resc, '-R', dest_resc, dest_path])[0].split('|')[2].split()[0] self.assertEqual(int(phymv_thread_count), threads) finally: self.user0.assert_icommand(['irm', '-f', dest_path]) default_buffer_size_in_bytes = 4 * (1024 ** 2) cases = [ { 'size': 0, 'threads': 0 }, { 'size': 34603008, 'threads': (34603008 / default_buffer_size_in_bytes) + 1 } ] for case in cases: do_test(size=case['size'], threads=case['threads']) class test_invalid_parameters(session.make_sessions_mixin([('otherrods', 'rods')], [('alice', 'apass')]), unittest.TestCase): def setUp(self): super(test_invalid_parameters, self).setUp() self.admin = self.admin_sessions[0] self.leaf_rescs = { 'a' : { 'name': 'test_iphymv_repl_status_a', 'vault': os.path.join(self.admin.local_session_dir, 'a'), 'host': test.settings.HOSTNAME_1 }, 'b' : { 'name': 'test_iphymv_repl_status_b', 'vault': os.path.join(self.admin.local_session_dir, 'b'), 'host': test.settings.HOSTNAME_2 }, 'c' : { 'name': 'test_iphymv_repl_status_c', 'vault': os.path.join(self.admin.local_session_dir, 'c'), 'host': test.settings.HOSTNAME_3 }, 'f' : { 'name': 'test_iphymv_repl_status_f', 'vault': os.path.join(self.admin.local_session_dir, 'f'), 'host': test.settings.HOSTNAME_1 } } for resc in self.leaf_rescs.values(): self.admin.assert_icommand(['iadmin', 'mkresc', resc['name'], 'unixfilesystem', ':'.join([resc['host'], resc['vault']])], 'STDOUT', resc['name']) self.parent_rescs = { 'd' : 'test_iphymv_repl_status_d', 'e' : 'test_iphymv_repl_status_e', } for resc in self.parent_rescs.values(): self.admin.assert_icommand(['iadmin', 'mkresc', resc, 'passthru'], 'STDOUT', resc) self.admin.assert_icommand(['iadmin', 'addchildtoresc', self.parent_rescs['d'], self.parent_rescs['e']]) self.admin.assert_icommand(['iadmin', 'addchildtoresc', self.parent_rescs['e'], self.leaf_rescs['f']['name']]) self.admin.environment_file_contents.update({'irods_default_resource': self.leaf_rescs['a']['name']}) self.filename = 'foo' self.local_path = os.path.join(self.admin.local_session_dir, self.filename) self.logical_path = os.path.join(self.admin.session_collection, 'subdir', self.filename) def tearDown(self): self.admin.assert_icommand(['iadmin', 'rmchildfromresc', self.parent_rescs['d'], self.parent_rescs['e']]) self.admin.assert_icommand(['iadmin', 'rmchildfromresc', self.parent_rescs['e'], self.leaf_rescs['f']['name']]) for resc in self.parent_rescs.values(): self.admin.assert_icommand(['iadmin', 'rmresc', resc]) for resc in self.leaf_rescs.values(): self.admin.assert_icommand(['iadmin', 'rmresc', resc['name']]) super(test_invalid_parameters, self).tearDown() def test_invalid_parameters(self): nonexistent_resource_name = 'nope' # does not exist self.admin.assert_icommand(['iphymv', self.logical_path], 'STDERR', 'does not exist') # put a file if not os.path.exists(self.local_path): lib.make_file(self.local_path, 1024) self.admin.assert_icommand(['imkdir', os.path.dirname(self.logical_path)]) self.admin.assert_icommand(['iput', '-R', self.leaf_rescs['a']['name'], self.local_path, self.logical_path]) try: # USER__NULL_INPUT_ERR # iphymv foo self.admin.assert_icommand(['iphymv', self.logical_path], 'STDERR', 'USER__NULL_INPUT_ERR') # iphymv -S a foo self.admin.assert_icommand(['iphymv', '-S', self.leaf_rescs['a']['name'], self.logical_path], 'STDERR', 'USER__NULL_INPUT_ERR') # iphymv -R a foo self.admin.assert_icommand(['iphymv', '-R', self.leaf_rescs['a']['name'], self.logical_path], 'STDERR', 'USER__NULL_INPUT_ERR') # USER_INCOMPATIBLE_PARAMS # iphymv -S a -n 0 foo self.admin.assert_icommand(['iphymv', '-S', self.leaf_rescs['a']['name'], '-n0', self.logical_path], 'STDERR', 'USER_INCOMPATIBLE_PARAMS') # USER_INVALID_RESC_INPUT # iphymv -S d -R a foo self.admin.assert_icommand( ['iphymv', '-S', self.parent_rescs['d'], '-R', self.leaf_rescs['a']['name'], self.logical_path], 'STDERR', 'USER_INVALID_RESC_INPUT') # iphymv -S a -R d foo self.admin.assert_icommand( ['iphymv', '-R', self.leaf_rescs['a']['name'], '-S', self.parent_rescs['d'], self.logical_path], 'STDERR', 'USER_INVALID_RESC_INPUT') # iphymv -S e -R a foo self.admin.assert_icommand( ['iphymv', '-S', self.parent_rescs['e'], '-R', self.leaf_rescs['a']['name'], self.logical_path], 'STDERR', 'USER_INVALID_RESC_INPUT') # iphymv -S a -R e foo self.admin.assert_icommand( ['iphymv', '-S', self.leaf_rescs['a']['name'], '-R', self.parent_rescs['e'], self.logical_path], 'STDERR', 'USER_INVALID_RESC_INPUT') # iphymv -S 'd;e' -R a foo hier = ';'.join([self.parent_rescs['d'], self.parent_rescs['e']]) self.admin.assert_icommand( ['iphymv', '-S', hier, '-R', self.leaf_rescs['a']['name'], self.logical_path], 'STDERR', 'USER_INVALID_RESC_INPUT') # iphymv -S a -R 'd;e' foo self.admin.assert_icommand( ['iphymv', '-S', self.leaf_rescs['a']['name'], '-R', hier, self.logical_path], 'STDERR', 'USER_INVALID_RESC_INPUT') # iphymv -S 'e;f' -R a foo hier = ';'.join([self.parent_rescs['e'], self.leaf_rescs['f']['name']]) self.admin.assert_icommand( ['iphymv', '-S', hier, '-R', self.leaf_rescs['a']['name'], self.logical_path], 'STDERR', 'USER_INVALID_RESC_INPUT') # iphymv -S a -R 'e;f' foo self.admin.assert_icommand( ['iphymv', '-S', self.leaf_rescs['a']['name'], '-R', hier, self.logical_path], 'STDERR', 'USER_INVALID_RESC_INPUT') # SYS_RESC_DOES_NOT_EXIST # iphymv -S nope -R b foo self.admin.assert_icommand(['iphymv', '-S', nonexistent_resource_name, '-R', self.leaf_rescs['b']['name'], self.logical_path], 'STDERR', 'SYS_RESC_DOES_NOT_EXIST') # iphymv -S a -R nope foo self.admin.assert_icommand(['iphymv', '-S', self.leaf_rescs['a']['name'], '-R', nonexistent_resource_name, self.logical_path], 'STDERR', 'SYS_RESC_DOES_NOT_EXIST') # ensure no replications took place out, _, _ = self.admin.run_icommand(['ils', '-l', self.logical_path]) print(out) for resc in self.leaf_rescs.values()[1:]: self.assertNotIn(resc['name'], out, msg='found unwanted replica on [{}]'.format(resc['name'])) for resc in self.parent_rescs.values(): self.assertNotIn(resc, out, msg='found replica on coordinating resc [{}]'.format(resc)) finally: self.admin.assert_icommand(['irm', '-rf', os.path.dirname(self.logical_path)]) class test_iphymv_repl_status(session.make_sessions_mixin([('otherrods', 'rods')], [('alice', 'apass')]), unittest.TestCase): def setUp(self): super(test_iphymv_repl_status, self).setUp() self.admin = self.admin_sessions[0] self.leaf_rescs = { 'a' : { 'name': 'test_iphymv_repl_status_a', 'vault': os.path.join(self.admin.local_session_dir, 'a'), 'host': test.settings.HOSTNAME_1 }, 'b' : { 'name': 'test_iphymv_repl_status_b', 'vault': os.path.join(self.admin.local_session_dir, 'b'), 'host': test.settings.HOSTNAME_2 }, 'c' : { 'name': 'test_iphymv_repl_status_c', 'vault': os.path.join(self.admin.local_session_dir, 'c'), 'host': test.settings.HOSTNAME_3 }, } for resc in self.leaf_rescs.values(): self.admin.assert_icommand(['iadmin', 'mkresc', resc['name'], 'unixfilesystem', ':'.join([resc['host'], resc['vault']])], 'STDOUT', resc['name']) self.admin.environment_file_contents.update({'irods_default_resource': self.leaf_rescs['a']['name']}) self.filename = 'foo' self.local_path = os.path.join(self.admin.local_session_dir, self.filename) self.logical_path = os.path.join(self.admin.session_collection, 'subdir', self.filename) def tearDown(self): for resc in self.leaf_rescs.values(): self.admin.assert_icommand(['iadmin', 'rmresc', resc['name']]) super(test_iphymv_repl_status, self).tearDown() def test_iphymv_Sa_Rb_foo(self): # iphymv -S a -R b foo (source default resource, destination non-default resource) scenarios = [ {'start':{'a':'-', 'b':'-', 'c':'&'}, 'end':{'a':'-', 'b':'-', 'c':'&'}, 'output':{'out':None, 'err':'SYS_REPLICA_DOES_NOT_EXIST', 'rc':None}}, {'start':{'a':'-', 'b':'-', 'c':'X'}, 'end':{'a':'-', 'b':'-', 'c':'X'}, 'output':{'out':None, 'err':'SYS_REPLICA_DOES_NOT_EXIST', 'rc':None}}, {'start':{'a':'-', 'b':'&', 'c':'-'}, 'end':{'a':'-', 'b':'&', 'c':'-'}, 'output':{'out':None, 'err':'SYS_REPLICA_DOES_NOT_EXIST', 'rc':None}}, {'start':{'a':'-', 'b':'&', 'c':'&'}, 'end':{'a':'-', 'b':'&', 'c':'&'}, 'output':{'out':None, 'err':'SYS_REPLICA_DOES_NOT_EXIST', 'rc':None}}, {'start':{'a':'-', 'b':'&', 'c':'X'}, 'end':{'a':'-', 'b':'&', 'c':'X'}, 'output':{'out':None, 'err':'SYS_REPLICA_DOES_NOT_EXIST', 'rc':None}}, {'start':{'a':'-', 'b':'X', 'c':'-'},
<reponame>industrial-optimization-group/offline_data_driven_moea import numpy as np import pickle import os from joblib import Parallel, delayed import matplotlib.pyplot as plt import csv from IGD_calc import igd, igd_plus from non_domx import ndx from pygmo import hypervolume as hv from scipy import stats from mpl_toolkits.mplot3d import Axes3D from statsmodels.stats.multicomp import (pairwise_tukeyhsd, MultiComparison) from statsmodels.stats.multitest import multipletests from scipy.stats import wilcoxon import math from ranking_approaches import calc_rank from scipy.spatial import distance #from pymop.problems.welded_beam import WeldedBeam #from pymop.problems.truss2d import Truss2D from sklearn.cluster import KMeans from sklearn.metrics import pairwise_distances_argmin_min #from matplotlib import rc #rc('font',**{'family':'serif','serif':['Helvetica']}) #rc('text', usetex=True) #plt.rcParams.update({'font.size': 15}) pareto_front_directory = 'True_Pareto_5000' mod_p_val = True metric = 'HV' #metric = 'IGD' save_fig = 'pdf' #dims = [5,8,10] #,8,10] dims = [10] folder_data = 'AM_Samples_109_Final' problem_testbench = 'DTLZ' #problem_testbench = 'DDMOPP' #main_directory = 'Offline_Prob_DDMOPP3' main_directory = 'Tests_Probabilistic_Finalx_new' #main_directory = 'Tests_new_adapt' #main_directory = 'Tests_toys' #objectives = [6] #objectives = [3,5,6] objectives = [2,3,5] #objectives = [2,3,4,5,6,8,10] #problems = ['DTLZ2'] problems = ['DTLZ2','DTLZ4','DTLZ5','DTLZ6','DTLZ7'] #problems = ['P1','P2'] #problems = ['P2'] #problems = ['WELDED_BEAM'] #dims=4 #problems = ['TRUSS2D'] #dims=3 #modes = [1, 2, 3] # 1 = Generic, 2 = Approach 1 , 3 = Approach 2, 7 = Approach_Prob #modes = [0,7,70,71] # 1 = Generic, 2 = Approach 1 , 3 = Approach 2 #modes = [0,1,7,8] #modes = [0,1,7,8] modes = [0,1,9,7,8] #modes = [1,2] mode_length = int(np.size(modes)) #sampling = ['BETA', 'MVNORM'] #sampling = ['LHS'] #sampling = ['BETA','OPTRAND','MVNORM'] #sampling = ['OPTRAND'] #sampling = ['MVNORM'] sampling = ['LHS', 'MVNORM'] #emo_algorithm = ['RVEA','IBEA'] emo_algorithm = ['RVEA'] #emo_algorithm = ['IBEA'] #emo_algorithm = ['NSGAIII'] #emo_algorithm = ['MODEL_CV'] #approaches = ['Generic', 'Approach 1', 'Approach 2', 'Approach 3'] #approaches = ['Generic', 'Approach 1', 'Approach 2', 'Approach X'] #approaches = ['Initial sampling','Generic', 'Approach Prob','Approach Hybrid'] #approaches = ['Initial sampling','Generic_RVEA','Generic_IBEA'] #approaches = ['Initial sampling','Prob Old', 'Prob constant 1','Prob FE/FEmax'] #approaches = ['Generic', 'Approach Prob','Approach Hybrid'] #approaches = ['Generic', 'Probabilistic','Hybrid'] #approaches = ['7', '9', '11'] #approaches = ['Initial sampling','Generic', 'TransferL','Probabilistic','Hybrid'] approaches = ['Init','Gen','TL','Prob','Hyb'] #"DTLZ6": {"2": [10, 10], "3": [10, 10, 10], "5": [10, 10, 10, 10, 10]}, #"DTLZ4": {"2": [4, 4], "3": [4, 4, 4], "5": [4, 4, 4, 4, 4]}, hv_ref = {"DTLZ2": {"2": [3, 3], "3": [3, 3, 3], "5": [3, 3, 3, 3, 3]}, "DTLZ4": {"2": [3, 3.1], "3": [3, 3, 3], "5": [3, 3, 3, 3, 3]}, "DTLZ5": {"2": [2.5, 3], "3": [2.5, 3, 3], "5": [2, 2, 2, 2, 2.5]}, "DTLZ6": {"2": [10, 10], "3": [10, 10, 10], "5": [7, 7, 7, 7, 7]}, "DTLZ7": {"2": [1, 20], "3": [1, 1, 30], "5": [1, 1, 1, 1, 45]}} nruns = 11 pool_size = nruns plot_boxplot = True l = [approaches]*nruns labels = [list(i) for i in zip(*l)] labels = [y for x in labels for y in x] p_vals_all = None index_all = None def arg_median(a): if len(a) % 2 == 1: return np.where(a == np.median(a))[0][0] else: l,r = len(a) // 2 - 1, len(a) // 2 left = np.partition(a, l)[l] right = np.partition(a, r)[r] return [np.where(a == left)[0][0], np.where(a == right)[0][0]] for samp in sampling: for prob in problems: for obj in objectives: for n_vars in dims: fig = plt.figure(1, figsize=(10, 10)) #fig = plt.figure() ax = fig.add_subplot(111) fig.set_size_inches(4, 4) #fig = plt.figure() # ax = fig.add_subplot(111, projection='3d') #ax = fig.add_subplot(111) #fig.set_size_inches(5, 5) #plt.xlim(0, 1) #plt.ylim(0, 1) #if save_fig == 'pdf': # plt.rcParams["text.usetex"] = True #with open(pareto_front_directory + '/True_5000_' + prob + '_' + obj + '.txt') as csv_file: # csv_reader = csv.reader(csv_file, delimiter=',') if problem_testbench == 'DTLZ': pareto_front = np.genfromtxt(pareto_front_directory + '/True_5000_' + prob + '_' + str(obj) + '.txt' , delimiter=',') #path_to_file = pareto_front_directory + '/' + 'Pareto_Weld' #infile = open(path_to_file, 'rb') #pareto_front = pickle.load(infile) #infile.close() #problem_weld = WeldedBeam() #pareto_front = problem_weld.pareto_front() for algo in emo_algorithm: #igd_all = np.zeros([nruns, np.shape(modes)[0]]) igd_all = None solution_ratio_all = None for mode, mode_count in zip(modes,range(np.shape(modes)[0])): if problem_testbench == 'DTLZ': path_to_file = main_directory \ + '/Offline_Mode_' + str(mode) + '_' + algo + \ '/' + samp + '/' + prob + '_' + str(obj) + '_' + str(n_vars) else: path_to_file = main_directory \ + '/Offline_Mode_' + str(mode) + '_' + algo + \ '/' + samp + '/' + prob + '_' + str(obj) + '_' + str(n_vars) print(path_to_file) def igd_calc(): pass def igd_box(): pass def plot_median_run(): pass def plot_convergence_plots(): pass def parallel_execute(run, path_to_file): if metric == 'IGD': path_to_file = path_to_file + '/Run_' + str(run) + '_NDS' infile = open(path_to_file, 'rb') results_data=pickle.load(infile) infile.close() non_dom_front = results_data["actual_objectives_nds"] non_dom_surr = results_data["surrogate_objectives_nds"] #print(np.shape(non_dom_surr)) #print((np.max(non_dom_front,axis=0))) solution_ratio = np.shape(non_dom_front)[0]/np.shape(non_dom_surr)[0] return [igd(pareto_front, non_dom_front), solution_ratio] else: if problem_testbench == 'DDMOPP': if mode == 9: path_to_file = path_to_file + '/Run_' + str(run+1) + '_soln' actual_objectives_nds = [] with open(path_to_file,'r') as f: reader = csv.reader(f) for line in reader: actual_objectives_nds.append(line) else: path_to_file = path_to_file + '/Run_' + str(run) + '_SOLN' infile = open(path_to_file, 'rb') results_data=pickle.load(infile) infile.close() if mode == 0: actual_objectives_nds = results_data["actual_objectives_nds"] else: actual_objectives_nds = results_data["obj_solns"] actual_objectives_nds = np.array(actual_objectives_nds, dtype=np.float32) r0=np.ones(obj) r1=np.ones(obj)*-1 dx=distance.euclidean(r0,r1) ref=np.ones(obj)*dx #ref = [2]*obj else: if mode == 9: path_to_file = path_to_file + '/Run_' + str(run+1) + '_soln' actual_objectives_nds = [] with open(path_to_file,'r') as f: reader = csv.reader(f) for line in reader: actual_objectives_nds.append(line) actual_objectives_nds = np.array(actual_objectives_nds, dtype=np.float32) else: path_to_file = path_to_file + '/Run_' + str(run) + '_NDS' infile = open(path_to_file, 'rb') results_data = pickle.load(infile) infile.close() actual_objectives_nds = results_data["actual_objectives_nds"] #non_dom_surr = results_data["surrogate_objectives_nds"] ref = hv_ref[prob][str(obj)] #print(actual_objectives_nds) if np.shape(actual_objectives_nds)[0] > 1: non_dom_front = ndx(actual_objectives_nds) actual_objectives_nds = actual_objectives_nds[non_dom_front[0][0]] else: actual_objectives_nds = actual_objectives_nds.reshape(1, obj) print(np.shape(actual_objectives_nds)) solution_ratio = 0 hyp = hv(actual_objectives_nds) hv_x = hyp.compute(ref) #print(np.amax(actual_objectives_nds,axis=0)) #ax.scatter(actual_objectives_nds[:, 0], actual_objectives_nds[:, 1],actual_objectives_nds[:, 2]) #ax.scatter(actual_objectives_nds[:, 0], actual_objectives_nds[:, 1]) return [hv_x, solution_ratio] #km = KMeans(n_clusters=100).fit(non_dom_front) #closest, _ = pairwise_distances_argmin_min(km.cluster_centers_, non_dom_front) #non_dom_front = non_dom_front[closest] #print(np.shape(non_dom_surr)) #print(non_dom_front) #plt.scatter(non_dom_front[:,0],non_dom_front[:,1]) #plt.scatter(pareto_front[:, 0], pareto_front[:, 1]) #plt.scatter(non_dom_surr[:, 0], non_dom_surr[:, 1]) #plt.show() #print(solution_ratio) #print(np.shape(non_dom_front)) #print(np.shape(non_dom_surr)) #print(igd(pareto_front, non_dom_front)) #return [igd_plus(pareto_front, non_dom_front), solution_ratio] #zz = np.amax(non_dom_front,axis=0) #return zz temp = Parallel(n_jobs=11)(delayed(parallel_execute)(run, path_to_file) for run in range(nruns)) #temp=None #for run in range(nruns): # temp=np.append(temp,parallel_execute(run, path_to_file)) temp=np.asarray(temp) igd_temp = np.transpose(temp[:, 0]) solution_ratio_temp = np.transpose(temp[:, 1]) if plot_boxplot is True: if igd_all is None: igd_all = igd_temp solution_ratio_all = solution_ratio_temp else: igd_all = np.vstack((igd_all, igd_temp)) solution_ratio_all = np.vstack((solution_ratio_all,solution_ratio_temp)) igd_all = np.transpose(igd_all) solution_ratio_all = np.transpose(solution_ratio_all) #print(np.max(igd_all)) #print(np.max(solution_ratio_all)) #print(igd_all) #mod = MultiComparison(igd_all[:,0], igd_all[:,1], igd_all[:,2], igd_all[:,3]) #dat=igd_all.flatten() #mod = MultiComparison(data=dat, groups=labels) #test=mod.tukeyhsd() #z=mod.getranks() #print(test.summary().data) #print(solution_ratio_all)\ p_value = np.zeros(int(math.factorial(mode_length)/((math.factorial(mode_length-2))*2))) p_cor_temp = p_value count = 0 count_prev = 0 for i in range(mode_length-1): for j in range(i+1,mode_length): if metric == 'HV': #w, p = wilcoxon(x=igd_all[:, i], y=igd_all[:, j], alternative='less') w, p = wilcoxon(x=igd_all[:, i], y=igd_all[:, j]) else: w, p = wilcoxon(x=igd_all[:, i], y=igd_all[:, j], alternative='greater') p_value[count] = p count +=1 if mod_p_val is True: r, p_cor_temp[count_prev:count], alps, alpb = multipletests(p_value[count_prev:count], alpha=0.05, method='bonferroni', is_sorted=False, returnsorted=False) count_prev = count p_cor = p_cor_temp print(p_value) print(p_cor) if mod_p_val is False: r, p_cor, alps, alpb = multipletests(p_value, alpha=0.05, method='bonferroni', is_sorted=False, returnsorted=False) current_index = [samp, n_vars, prob, obj] #adding other indicators mean, median, std dev #p_cor = (np.asarray([p_cor, np.mean(igd_all, axis=0), # np.median(igd_all, axis=0), # np.std(igd_all, axis=0)])).flatten() ranking = calc_rank(p_cor, np.median(igd_all, axis=0),np.shape(modes)[0]) p_cor = np.hstack((p_cor, np.mean(igd_all, axis=0), np.median(igd_all, axis=0), np.std(igd_all, axis=0),ranking)) for medz in range(mode_length): print("Median index:") med_mode = int(arg_median(igd_all[:, medz])) med_mode = np.asarray(med_mode).reshape((1,1)) med_mode = np.tile(med_mode,(2,2)) med_mode = med_mode.astype(int) path_to_file2 = main_directory \ + '/Offline_Mode_' + str(modes[medz]) + '_' + algo + \ '/' + samp + '/' + prob + '_' + str(obj) + '_' + str(n_vars) + '/med_indices.csv' print(path_to_file2) med_mode = med_mode.tolist() print(med_mode) with open(path_to_file2, 'w') as f: writer = csv.writer(f) for line in med_mode: writer.writerow(line) #np.savetxt(path_to_file2, med_mode, delimiter=",") print("File written") p_cor = np.hstack((current_index,p_cor)) if p_vals_all is None: p_vals_all = p_cor else: p_vals_all = np.vstack((p_vals_all, p_cor)) bp = ax.boxplot(igd_all, showfliers=False, widths=0.45) #ax.set_title(metric + '_'+ samp + '_Algo_' + algo + '_' + prob + '_' + str(obj) + '_' + str(n_vars)) ax.set_title('Hypervolume comparison') ax.set_xlabel('Approaches') #ax.set_ylabel(metric) ax.set_ylabel('Hypervolume') ax.set_xticklabels(approaches, rotation=45, fontsize=15) if problem_testbench == 'DTLZ': filename_fig = main_directory + '/' + metric + '_'+ samp + '_' + algo + '_' + prob + '_' + str(obj)\ + '_' + str(n_vars) else: filename_fig = main_directory + '/' + metric + '_' + samp + '_' + algo + '_' + prob + '_' + str( obj) + '_' + str(n_vars) if save_fig == 'png': fig.savefig(filename_fig + '.png', bbox_inches='tight') else: fig.savefig(filename_fig + '.pdf', bbox_inches='tight') ax.clear() """ bp = ax.boxplot(solution_ratio_all, showfliers=False) ax.set_title('SOLR_'+ samp + '_Algo_' + algo + '_' + prob + '_' + str(obj)) ax.set_xlabel('Approaches') ax.set_ylabel('SOLR') ax.set_xticklabels(approaches, rotation=45, fontsize=8) filename_fig = main_directory + '/SOLR_'+ samp + '_' + algo + '_' + prob
open(l, "a+") as f: f.write(vector_information) os.chdir(cwd) def we_analysis(): """ Runs short MD simulation for saved inpcrd files. """ cwd = os.getcwd() os.chdir(cwd + "/" + "westpa_dir") dir_list = [ "dihedral_threshold_lower", "dihedral_threshold_upper", "dual_threshold_lower", "dual_threshold_upper", "total_threshold_lower", "total_threshold_upper", ] we_list = ["1d_c1", "1d_c12", "1d_c123", "2d_c1", "2d_c12", "2d_c123"] for i in dir_list: for j in we_list: os.chdir(cwd + "/" + "westpa_dir" + "/" + str(i)) os.chdir(cwd + "/" + "westpa_dir" + "/" + str(i) + "/" + str(j)) if len(open("BASIS_STATES").readlines()) > 0: df = pd.read_csv("BASIS_STATES", delimiter=" ", header=None) df.columns = [["descriptor", "probability", "file_name"]] df1 = df[["file_name"]] inpcrd_list = df1.values.tolist() inpcrd_list = list(itertools.chain(*inpcrd_list)) os.system("rm -rf md_sims") os.system("mkdir md_sims") os.chdir( cwd + "/" + "westpa_dir" + "/" + str(i) + "/" + str(j) + "/" + "md_sims" ) with open("md.in", "w") as f: f.write( "Run minimization followed by saving rst file" + "\n" ) f.write("&cntrl" + "\n") f.write( " imin = 1, maxcyc = 10000, ntpr = 5, iwrap = 1, ntxo = 1" + "\n" ) f.write("&end" + "\n") for k in inpcrd_list: source_dir = ( cwd + "/" + "westpa_dir" + "/" + str(i) + "/" + str(j) + "/" + "bstates" ) target_dir = ( cwd + "/" + "westpa_dir" + "/" + str(i) + "/" + str(j) + "/" + "md_sims" ) shutil.copy( source_dir + "/" + str(k), target_dir + "/" + str(k) ) source_dir = cwd + "/" + "starting_structures" target_dir = ( cwd + "/" + "westpa_dir" + "/" + str(i) + "/" + str(j) + "/" + "md_sims" ) shutil.copy( source_dir + "/" + "system_final.prmtop", target_dir + "/" + "system_final.prmtop", ) for l in range(len(inpcrd_list)): command = ( "pmemd.cuda -O -i md.in -o " + inpcrd_list[l][:-6] + "out" + " -p system_final.prmtop -c " + inpcrd_list[l] + " -r " + inpcrd_list[l][:-6] + "rst" ) print(command) os.system(command) os.chdir(cwd) def correction_westpa(): """ Eliminates all inpcrd files crashed during the short MD simulation run. Also create folders for .rst files in case it is needed for WE simulations """ cwd = os.getcwd() os.chdir(cwd + "/" + "westpa_dir") dir_list = [ "dihedral_threshold_lower", "dihedral_threshold_upper", "dual_threshold_lower", "dual_threshold_upper", "total_threshold_lower", "total_threshold_upper", ] we_list = ["1d_c1", "1d_c12", "1d_c123", "2d_c1", "2d_c12", "2d_c123"] for i in dir_list: for j in we_list: os.chdir(cwd + "/" + "westpa_dir" + "/" + str(i)) os.chdir(cwd + "/" + "westpa_dir" + "/" + str(i) + "/" + str(j)) if len(open("BASIS_STATES").readlines()) > 0: os.chdir( cwd + "/" + "westpa_dir" + "/" + str(i) + "/" + str(j) + "/" + "md_sims" ) files = os.listdir(".") file_to_find = "*.out" out_list = [] for y in files: if fnmatch.fnmatch(y, file_to_find): out_list.append(y) list_failed_jobs = [] for out_file in out_list: with open(out_file, "r") as f: last_line = f.readlines()[-2] if last_line.startswith("|") == False: list_failed_jobs.append(out_file) for c in range(len(list_failed_jobs)): command = "rm -rf " + list_failed_jobs[c] os.system(command) for d in range(len(list_failed_jobs)): command = "rm -rf " + list_failed_jobs[d][:-3] + "rst" os.system(command) for e in range(len(list_failed_jobs)): command = "rm -rf " + list_failed_jobs[e][:-3] + "inpcrd" os.system(command) for f in range(len(list_failed_jobs)): command = "rm -rf " + list_failed_jobs[f][:-3] + "nc" os.system(command) files = os.listdir(".") file_to_find = "*.rst" rst_list = [] for y in files: if fnmatch.fnmatch(y, file_to_find): rst_list.append(y) rst_failed_jobs = [] for rst_file in rst_list: with open(rst_file, "r") as f: req_line = f.readlines()[2] if "NaN" in req_line: rst_failed_jobs.append(rst_file) for g in range(len(rst_failed_jobs)): command = "rm -rf " + rst_failed_jobs[g] os.system(command) for h in range(len(rst_failed_jobs)): command = "rm -rf " + rst_failed_jobs[h][:-3] + "out" os.system(command) for u in range(len(rst_failed_jobs)): command = "rm -rf " + rst_failed_jobs[u][:-3] + "inpcrd" os.system(command) for v in range(len(rst_failed_jobs)): command = "rm -rf " + rst_failed_jobs[v][:-3] + "nc" os.system(command) files_2 = os.listdir(".") file_to_find_2 = "*.rst" rst_list_2 = [] for y in files_2: if fnmatch.fnmatch(y, file_to_find_2): rst_list_2.append(y) rst_failed_jobs_2 = [] for rst_file_2 in rst_list_2: with open(rst_file_2, "r") as f: lines_file = f.readlines() for req_line in lines_file: if "*" in req_line: rst_failed_jobs_2.append(rst_file_2) for g in range(len(rst_failed_jobs_2)): command = "rm -rf " + rst_failed_jobs_2[g] os.system(command) for h in range(len(rst_failed_jobs_2)): command = "rm -rf " + rst_failed_jobs_2[h][:-3] + "out" os.system(command) for u in range(len(rst_failed_jobs_2)): command = "rm -rf " + rst_failed_jobs_2[u][:-3] + "inpcrd" os.system(command) for v in range(len(rst_failed_jobs_2)): command = "rm -rf " + rst_failed_jobs_2[v][:-3] + "nc" os.system(command) os.system("rm -rf md.in") os.system("rm -rf system_final.prmtop") os.system("rm -rf mdinfo") files = os.listdir(".") inpcrd_file_to_find = "*.inpcrd" rst_file_to_find = "*.rst" inpcrd_file_list = [] for y in files: if fnmatch.fnmatch(y, inpcrd_file_to_find): inpcrd_file_list.append(y) rst_file_list = [] for z in files: if fnmatch.fnmatch(z, rst_file_to_find): rst_file_list.append(z) os.chdir( cwd + "/" + "westpa_dir" + "/" + str(i) + "/" + str(j) ) os.system("rm -rf bstates_corrected_rst") os.system("mkdir bstates_corrected_rst") os.system("rm -rf bstates_corrected_inpcrd") os.system("mkdir bstates_corrected_inpcrd") for x in inpcrd_file_list: shutil.copy( cwd + "/" + "westpa_dir" + "/" + str(i) + "/" + str(j) + "/" + "md_sims" + "/" + str(x), cwd + "/" + "westpa_dir" + "/" + str(i) + "/" + str(j) + "/" + "bstates_corrected_inpcrd" + "/" + str(x), ) for y in rst_file_list: shutil.copy( cwd + "/" + "westpa_dir" + "/" + str(i) + "/" + str(j) + "/" + "md_sims" + "/" + str(y), cwd + "/" + "westpa_dir" + "/" + str(i) + "/" + str(j) + "/" + "bstates_corrected_rst" + "/" + str(y), ) df = pd.read_csv("BASIS_STATES", sep=" ", header=None) df.columns = ["index_df", "probability", "inpcrd"] df = df[["probability", "inpcrd"]] df = df[df.inpcrd.str.contains("|".join(inpcrd_file_list))] index_row_list = [] for n in range(df.shape[0]): index_row_list.append(n) df = df.assign(index_=index_row_list) df = df[["index_", "probability", "inpcrd"]] df.to_csv( "BASIS_STATES_CORRECTED_INPCRD", header=False, index=None, sep=" ", mode="w", ) fin = open("BASIS_STATES_CORRECTED_INPCRD", "rt") fout = open("BASIS_STATES_CORRECTED_RST", "wt") for line in fin: fout.write(line.replace("inpcrd", "rst")) fin.close() fout.close() os.chdir(cwd) def plot_contrib(): """ Plots to review the analysis done. Plot bar graphs for the number of structures obtained for WE simulation for each of the potential boosts during GaMD simulation. """ cwd = os.getcwd() os.chdir(cwd + "/" + "westpa_dir") dir_list = [ "dihedral_threshold_lower", "dihedral_threshold_upper", "dual_threshold_lower", "dual_threshold_upper", "total_threshold_lower", "total_threshold_upper", ] we_list = ["1d_c1", "1d_c12", "1d_c123", "2d_c1", "2d_c12", "2d_c123"] confs = [] for i in dir_list: conf_within = [] for j in we_list: os.chdir(cwd + "/" + "westpa_dir" + "/" + str(i)) os.chdir(cwd + "/" + "westpa_dir" + "/" + str(i) + "/" + str(j)) if len(open("BASIS_STATES").readlines()) > 0: count1 = len(open("BASIS_STATES").readlines()) count2 = len(open("BASIS_STATES_CORRECTED_RST").readlines()) conf = str(i), str(j), count1, count2 conf_within.append(conf) confs.append(conf_within) print(confs) os.chdir(cwd) corrected_list = [] for i in range(len(confs)): corrected_list_1 = [] for j in range(len(confs[i])): corrected_list_1.append(confs[i][j][3]) corrected_list.append(corrected_list_1) print(corrected_list) expanse_list = [] for i in range(len(confs)): expanse_list_1 = [] for j in range(len(confs[i])): expanse_list_1.append(confs[i][j][1]) expanse_list.append(expanse_list_1) print(expanse_list) x0 = expanse_list[0] y0 = corrected_list[0] x1 = expanse_list[1] y1 = corrected_list[1] x2 = expanse_list[2] y2 = corrected_list[2] x3 = expanse_list[3] y3 = corrected_list[3] x4 = expanse_list[4] y4 = corrected_list[4] x5 = expanse_list[5] y5 = corrected_list[5] y = y0 x = x0 title = "Configurations vs Different Expansions" + " for " + dir_list[0] print(title) sns.set(font_scale=1) plt.rcParams["figure.figsize"] = (8, 4) plt.rcParams["font.family"] = "serif" style.use("fivethirtyeight") g = sns.barplot(y, x, palette=("binary")) g.grid(False) g.set_title(title) g.set(xlabel="Configurations", ylabel="Expansion") ax = g for i, v in enumerate(y): ax.text(v + 1, i + 0.25, str(v), color="black", fontweight="bold") fig_name = dir_list[0] plt.savefig(fig_name, bbox_inches="tight") plt.show(block=False) plt.pause(1) plt.close() y = y1 x = x1 title = "Configurations vs Different Expansions" + " for " + dir_list[1] print(title) sns.set(font_scale=1) plt.rcParams["figure.figsize"] = (8, 4) plt.rcParams["font.family"] = "serif" style.use("fivethirtyeight") g = sns.barplot(y, x, palette=("binary")) g.grid(False) g.set_title(title) g.set(xlabel="Configurations", ylabel="Expansion") ax = g for i, v in enumerate(y): ax.text(v + 1, i + 0.25, str(v), color="black", fontweight="bold") fig_name = dir_list[1] plt.savefig(fig_name, bbox_inches="tight") plt.show(block=False) plt.pause(1) plt.close() y = y2 x = x2 title = "Configurations vs Different Expansions" + " for " + dir_list[2] print(title) sns.set(font_scale=1) plt.rcParams["figure.figsize"] = (8, 4) plt.rcParams["font.family"] = "serif" style.use("fivethirtyeight") g = sns.barplot(y, x, palette=("binary")) g.grid(False) g.set_title(title) g.set(xlabel="Configurations", ylabel="Expansion") ax = g for i, v in enumerate(y): ax.text(v + 1, i + 0.25, str(v), color="black", fontweight="bold") fig_name = dir_list[2] plt.savefig(fig_name, bbox_inches="tight") plt.show(block=False) plt.pause(1) plt.close() y = y3 x = x3 title = "Configurations vs
#!/usr/bin/env python # -*- coding: utf-8 -*- from google.appengine.ext import ndb from google.appengine.api import users from google.appengine.api import memcache import datetime import calendar import pickle import json import logging import bulbware_lib import user_model class BulbwareProject(ndb.Model): app_name = ndb.StringProperty() owner = ndb.KeyProperty(user_model.UserInfo) name = ndb.StringProperty() options = ndb.TextProperty() tags = ndb.StringProperty(repeated=True) sorttext = ndb.StringProperty() create_datetime = ndb.DateTimeProperty(auto_now_add=True) update_datetime = ndb.DateTimeProperty(auto_now=True) def get_property(self): return { 'id': self.key.urlsafe(), 'owner_id': self.owner.urlsafe(), 'owner_name': self.owner.get().name, 'name': self.name, 'options': self.options, 'tags': self.tags, 'sorttext': self.sorttext, 'create_datetime': bulbware_lib.jst_date(self.create_datetime).strftime('%Y-%m-%d %H:%M:%S'), 'update_datetime': bulbware_lib.jst_date(self.update_datetime).strftime('%Y-%m-%d %H:%M:%S') } def get_option_values(self): if self.options: return json.loads(self.options) else: return {} def get_owner(self): return self.owner.get() def get_pages(self): return search_pages_project(self.app_name, self) def get_items(self): return search_items_project(self.app_name, self) def check_edit(self, userinfo): return (self.owner.urlsafe() == userinfo.key.urlsafe()) def check_delete(self, userinfo): pages = self.get_pages() items = self.get_items() return (pages.count() == 0) and (items.count() == 0) and (self.owner.urlsafe() == userinfo.key.urlsafe()) def save(self, userinfo, name, options, tags, sorttext=None): self.name = name self.options = options self.tags = tags if sorttext: self.sorttext = sorttext else: self.sorttext = name self.put() def inTag(self, tag): return (tag in self.tags) def get_project(app_name, key_str): if key_str: key = ndb.Key(urlsafe=key_str) if key.kind() == 'BulbwareProject': project = key.get() if project.app_name == app_name: return project def add_project(app_name, userinfo, name, options, tags, sorttext=None): project = BulbwareProject() project.app_name = app_name project.owner = userinfo.key project.save(userinfo, name, options, tags, sorttext) return project def search_projects_owner(app_name, userinfo, tags=None): q = BulbwareProject.query(BulbwareProject.app_name==app_name, BulbwareProject.owner==userinfo.key) # if tags: while tags.count('') > 0: tags.remove('') if tags and (len(tags) > 0): q = q.filter(BulbwareProject.tags.IN(tags)) # return q.order(BulbwareProject.sorttext) def search_projects_name(app_name, name, tags=None): q = BulbwareProject.query(BulbwareProject.app_name==app_name, BulbwareProject.name==name) # if tags: while tags.count('') > 0: tags.remove('') if tags and (len(tags) > 0): q = q.filter(BulbwareProject.tags.IN(tags)) # return q.order(BulbwareProject.sorttext) def search_projects_tags(app_name, tags=None): q = BulbwareProject.query(BulbwareProject.app_name==app_name) # if tags: while tags.count('') > 0: tags.remove('') if tags and (len(tags) > 0): q = q.filter(BulbwareProject.tags.IN(tags)) # return q.order(BulbwareProject.sorttext) class BulbwarePage(ndb.Model): app_name = ndb.StringProperty() project = ndb.KeyProperty(BulbwareProject) owner = ndb.KeyProperty(user_model.UserInfo) name = ndb.StringProperty() options = ndb.TextProperty() tags = ndb.StringProperty(repeated=True) sorttext = ndb.StringProperty() create_datetime = ndb.DateTimeProperty(auto_now_add=True) update_datetime = ndb.DateTimeProperty(auto_now=True) def get_property(self): ret = { 'id': self.key.urlsafe(), 'project': '', 'owner_id': self.owner.urlsafe(), 'owner_name': self.owner.get().name, 'name': self.name, 'options': self.options, 'tags': self.tags, 'sorttext': self.sorttext, 'create_datetime': bulbware_lib.jst_date(self.create_datetime).strftime('%Y-%m-%d %H:%M:%S'), 'update_datetime': bulbware_lib.jst_date(self.update_datetime).strftime('%Y-%m-%d %H:%M:%S') } if self.project: ret['project'] = self.project.get().get_property() return ret def get_option_values(self): if self.options: return json.loads(self.options) else: return {} def get_owner(self): return self.owner.get() def check_edit(self, userinfo): return (self.owner.urlsafe() == userinfo.key.urlsafe()) def check_delete(self, userinfo): return self.check_edit(userinfo) def save(self, name, options, tags, sorttext=None, project_key=None): self.name = name self.options = options self.tags = tags if sorttext: self.sorttext = sorttext else: self.sorttext = name if project_key: self.project = ndb.Key(urlsafe=project_key) self.put() def get_page(app_name, key_str): if key_str: key = ndb.Key(urlsafe=key_str) if key.kind() == 'BulbwarePage': page = key.get() if page.app_name == app_name: return page def add_page(app_name, userinfo, name, options, tags, sorttext=None, project_key=None): page = BulbwarePage() page.app_name = app_name page.owner = userinfo.key page.save(name, options, tags, sorttext, project_key) return page def search_pages(app_name, userinfo=None, project=None, tags=None, order=True): q = BulbwarePage.query(BulbwarePage.app_name==app_name) # if userinfo: q = q.filter(BulbwarePage.owner==bulbware_lib.get_key(userinfo, user_model.UserInfo)) # if project: q = q.filter(BulbwarePage.project==bulbware_lib.get_key(project, BulbwareProject)) # if tags: while tags.count('') > 0: tags.remove('') if tags and (len(tags) > 0): q = q.filter(BulbwarePage.tags.IN(tags)) # if order: return q.order(BulbwarePage.sorttext) else: return q def search_pages_project(app_name, project, tags=None): q = BulbwarePage.query(BulbwarePage.app_name==app_name, BulbwarePage.project==project.key) # if tags: while tags.count('') > 0: tags.remove('') if tags and (len(tags) > 0): q = q.filter(BulbwarePage.tags.IN(tags)) # return q.order(BulbwarePage.sorttext) class BulbwareItem(ndb.Model): app_name = ndb.StringProperty() project = ndb.KeyProperty(BulbwareProject) owner = ndb.KeyProperty(user_model.UserInfo) name = ndb.StringProperty() options = ndb.TextProperty() tags = ndb.StringProperty(repeated=True) sorttext = ndb.StringProperty() create_datetime = ndb.DateTimeProperty(auto_now_add=True) update_datetime = ndb.DateTimeProperty(auto_now=True) def get_property(self): ret = { 'id': self.key.urlsafe(), 'project': '', 'owner_id': self.owner.urlsafe(), 'owner_name': self.owner.get().name, 'name': self.name, 'options': self.options, 'tags': self.tags, 'sorttext': self.sorttext, 'create_datetime': bulbware_lib.jst_date(self.create_datetime).strftime('%Y-%m-%d %H:%M:%S'), 'update_datetime': bulbware_lib.jst_date(self.update_datetime).strftime('%Y-%m-%d %H:%M:%S') } if self.project: ret['project'] = self.project.get().get_property() return ret def get_option_values(self): if self.options: return json.loads(self.options) else: return {} def get_owner(self): return self.owner.get() def check_edit(self, userinfo): return (self.owner.urlsafe() == userinfo.key.urlsafe()) def check_delete(self, userinfo): return self.check_edit(userinfo) def save(self, name, options, tags, sorttext=None, project_key=None): self.name = name self.options = options self.tags = tags if sorttext: self.sorttext = sorttext else: self.sorttext = name if project_key: self.project = ndb.Key(urlsafe=project_key) self.put() def get_item(app_name, key_str): if key_str: key = ndb.Key(urlsafe=key_str) if key.kind() == 'BulbwareItem': item = key.get() if item.app_name == app_name: return item def add_item(app_name, userinfo, name, options, tags, sorttext=None, project_key=None): item = BulbwareItem() item.app_name = app_name item.owner = userinfo.key item.save(name, options, tags, sorttext, project_key) return item def search_items(app_name, userinfo=None, project=None, tags=None, order=True): q = BulbwareItem.query(BulbwareItem.app_name==app_name) # if userinfo: q = q.filter(BulbwareItem.owner==bulbware_lib.get_key(userinfo, user_model.UserInfo)) # if project: q = q.filter(BulbwareItem.project==bulbware_lib.get_key(project, BulbwareProject)) # if tags: while tags.count('') > 0: tags.remove('') if tags and (len(tags) > 0): q = q.filter(BulbwareItem.tags.IN(tags)) # if order: return q.order(BulbwareItem.sorttext) else: return q def search_items_project(app_name, project, tags=None): q = BulbwareItem.query(BulbwareItem.app_name==app_name, BulbwareItem.project==project.key) # if tags: while tags.count('') > 0: tags.remove('') if tags and (len(tags) > 0): q = q.filter(BulbwareItem.tags.IN(tags)) # return q.order(BulbwareItem.sorttext) class BulbwareAttribute(ndb.Model): app_name = ndb.StringProperty() project = ndb.KeyProperty(BulbwareProject) owner = ndb.KeyProperty(user_model.UserInfo) name = ndb.StringProperty() options = ndb.TextProperty() tags = ndb.StringProperty(repeated=True) sorttext = ndb.StringProperty() create_datetime = ndb.DateTimeProperty(auto_now_add=True) update_datetime = ndb.DateTimeProperty(auto_now=True) def get_property(self): ret = { 'id': self.key.urlsafe(), 'project': '', 'owner_id': self.owner.urlsafe(), 'owner_name': self.owner.get().name, 'name': self.name, 'options': self.options, 'tags': self.tags, 'sorttext': self.sorttext, 'create_datetime': bulbware_lib.jst_date(self.create_datetime).strftime('%Y-%m-%d %H:%M:%S'), 'update_datetime': bulbware_lib.jst_date(self.update_datetime).strftime('%Y-%m-%d %H:%M:%S') } if self.project: ret['project'] = self.project.get().get_property() return ret def get_option_values(self): if self.options: return json.loads(self.options) else: return {} def get_owner(self): return self.owner.get() def check_edit(self, userinfo): return (self.owner.urlsafe() == userinfo.key.urlsafe()) def check_delete(self, userinfo): return self.check_edit(userinfo) def save(self, name, options, tags, sorttext=None, project_key=None): self.name = name self.options = options self.tags = tags if sorttext: self.sorttext = sorttext else: self.sorttext = name self.project = bulbware_lib.get_key(project_key, BulbwareProject) self.put() def get_attribute(app_name, key_str): if key_str: key = ndb.Key(urlsafe=key_str) if key.kind() == 'BulbwareAttribute': attribute = key.get() if attribute.app_name == app_name: return attribute def add_attribute(app_name, userinfo, name, options, tags, sorttext=None, project_key=None): attribute = BulbwareAttribute() attribute.app_name = app_name attribute.owner = userinfo.key attribute.save(name, options, tags, sorttext, project_key) return attribute def search_attributes_owner(app_name, userinfo, tags=None): q = BulbwareAttribute.query(BulbwareAttribute.app_name==app_name, BulbwareAttribute.owner==userinfo.key) # if tags: while tags.count('') > 0: tags.remove('') if tags and (len(tags) > 0): q = q.filter(BulbwareAttribute.tags.IN(tags)) # return q.order(BulbwareAttribute.sorttext) def search_attributes_project(app_name, project, tags=None): q = BulbwareAttribute.query(BulbwareAttribute.app_name==app_name, BulbwareAttribute.project==project.key) # if tags: while tags.count('') > 0: tags.remove('') if tags and (len(tags) > 0): q = q.filter(BulbwareAttribute.tags.IN(tags)) # return q.order(BulbwareAttribute.sorttext) class BulbwareElement(ndb.Model): app_name = ndb.StringProperty() project = ndb.KeyProperty(BulbwareProject) owner = ndb.KeyProperty(user_model.UserInfo) page = ndb.KeyProperty(BulbwarePage) item = ndb.KeyProperty(BulbwareItem) attribute = ndb.KeyProperty(BulbwareAttribute) options = ndb.TextProperty() tags = ndb.StringProperty(repeated=True) sorttext = ndb.StringProperty() element_datetime = ndb.DateTimeProperty() create_datetime = ndb.DateTimeProperty(auto_now_add=True) update_datetime = ndb.DateTimeProperty(auto_now=True) def get_property(self): ret = { 'id': self.key.urlsafe(), 'project': '', 'page': '', 'item': '', 'attribute': '', 'options': self.options, 'tags': self.tags, 'sorttext': self.sorttext, 'element_datetime': bulbware_lib.jst_date(self.element_datetime).strftime('%Y-%m-%d %H:%M:%S') if self.element_datetime else '', 'create_datetime': bulbware_lib.jst_date(self.create_datetime).strftime('%Y-%m-%d %H:%M:%S'), 'update_datetime': bulbware_lib.jst_date(self.update_datetime).strftime('%Y-%m-%d %H:%M:%S') } if self.project: ret['project'] = self.project.get().get_property() if self.page: ret['page'] = self.page.get().get_property() if self.item: ret['item'] = self.item.get().get_property() if self.attribute: ret['attribute'] = self.attribute.get().get_property() return ret def get_option_values(self): if self.options: return json.loads(self.options) else: return {} def get_owner(self): return self.owner.get() def check_edit(self, userinfo): return (self.owner.urlsafe() == userinfo.key.urlsafe()) def check_delete(self, userinfo): return (self.owner.urlsafe() == userinfo.key.urlsafe()) def save(self, options, tags, sorttext=None, element_datetime=None, project=None, page=None, item=None, attribute=None): self.options = options self.tags = tags if sorttext: self.sorttext = sorttext else: self.sorttext = element_datetime if element_datetime: self.element_datetime = bulbware_lib.utc_date(bulbware_lib.parse_datetime(element_datetime)) else: self.element_datetime = None self.project = bulbware_lib.get_key(project, BulbwareProject) self.page = bulbware_lib.get_key(page, BulbwarePage) self.item = bulbware_lib.get_key(item, BulbwareItem) self.attribute = bulbware_lib.get_key(attribute, BulbwareAttribute) self.put() def get_element(app_name, key_str): if key_str: key = ndb.Key(urlsafe=key_str) if key.kind() == 'BulbwareElement': element = key.get() if element.app_name == app_name: return element def add_element(app_name, userinfo, options, tags, sorttext=None, element_datetime=None, project=None, page=None, item=None, attribute=None): element = BulbwareElement() element.app_name = app_name element.owner = userinfo.key element.save(options, tags, sorttext, element_datetime, project, page, item, attribute) return element def search_elements(app_name, userinfo=None, project=None, page=None, item=None, attribute=None, tags=None, datetime1=None, datetime2=None, order=True): q = BulbwareElement.query(BulbwareElement.app_name==app_name) # if userinfo: q = q.filter(BulbwareElement.owner==bulbware_lib.get_key(userinfo, user_model.UserInfo)) # if project: q = q.filter(BulbwareElement.project==bulbware_lib.get_key(project, BulbwareProject)) # if page: q = q.filter(BulbwareElement.page==bulbware_lib.get_key(page, BulbwarePage)) # if item: q = q.filter(BulbwareElement.item==bulbware_lib.get_key(item, BulbwareItem)) # if attribute: q = q.filter(BulbwareElement.attribute==bulbware_lib.get_key(attribute, BulbwareAttribute)) # if tags: while tags.count('') > 0: tags.remove('') if tags and (len(tags) > 0): q = q.filter(BulbwareElement.tags.IN(tags)) # if datetime1: q = q.filter(BulbwareElement.element_datetime>=bulbware_lib.get_datetime(datetime1)) if datetime2: q = q.filter(BulbwareElement.element_datetime<=bulbware_lib.get_datetime(datetime2)) # if order: return q.order(BulbwareElement.sorttext) else: return q def search_elements_project(app_name, project, tags=None): q = BulbwareElement.query(BulbwareElement.app_name==app_name, BulbwareElement.project==project.key) # if tags: while
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'variables': { 'verbose_libraries_build%': 0, 'instrumented_libraries_jobs%': 1, 'instrumented_libraries_cc%': '<!(cd <(DEPTH) && pwd -P)/<(make_clang_dir)/bin/clang', 'instrumented_libraries_cxx%': '<!(cd <(DEPTH) && pwd -P)/<(make_clang_dir)/bin/clang++', }, 'libdir': 'lib', 'ubuntu_release': '<!(lsb_release -cs)', 'conditions': [ ['asan==1', { 'sanitizer_type': 'asan', }], ['msan==1', { 'sanitizer_type': 'msan', }], ['tsan==1', { 'sanitizer_type': 'tsan', }], ['use_goma==1', { 'cc': '<(gomadir)/gomacc <(instrumented_libraries_cc)', 'cxx': '<(gomadir)/gomacc <(instrumented_libraries_cxx)', }, { 'cc': '<(instrumented_libraries_cc)', 'cxx': '<(instrumented_libraries_cxx)', }], ], 'target_defaults': { 'build_method': 'destdir', # Every package must have --disable-static in configure flags to avoid # building unnecessary static libs. Ideally we should add it here. # Unfortunately, zlib1g doesn't support that flag and for some reason it # can't be removed with a GYP exclusion list. So instead we add that flag # manually to every package but zlib1g. 'extra_configure_flags': [], 'jobs': '<(instrumented_libraries_jobs)', 'package_cflags': [ '-O2', '-gline-tables-only', '-fPIC', '-w', '-U_FORITFY_SOURCE', '-fno-omit-frame-pointer' ], 'package_ldflags': [ '-Wl,-z,origin', # We set RPATH=XORIGIN when building the package and replace it with # $ORIGIN later. The reason is that this flag goes through configure/make # differently for different packages. Because of this, we can't escape the # $ character in a way that would work for every package. '-Wl,-R,XORIGIN/.' ], 'patch': '', 'pre_build': '', 'asan_blacklist': '', 'msan_blacklist': '', 'tsan_blacklist': '', 'conditions': [ ['asan==1', { 'package_cflags': ['-fsanitize=address'], 'package_ldflags': ['-fsanitize=address'], }], ['msan==1', { 'package_cflags': [ '-fsanitize=memory', '-fsanitize-memory-track-origins=<(msan_track_origins)' ], 'package_ldflags': ['-fsanitize=memory'], }], ['tsan==1', { 'package_cflags': ['-fsanitize=thread'], 'package_ldflags': ['-fsanitize=thread'], }], ], }, 'targets': [ { 'target_name': 'prebuilt_instrumented_libraries', 'type': 'none', 'variables': { 'prune_self_dependency': 1, # Don't add this target to the dependencies of targets with type=none. 'link_dependency': 1, 'conditions': [ ['msan==1', { 'conditions': [ ['msan_track_origins==2', { 'archive_prefix': 'msan-chained-origins', }, { 'conditions': [ ['msan_track_origins==0', { 'archive_prefix': 'msan-no-origins', }, { 'archive_prefix': 'UNSUPPORTED_CONFIGURATION' }], ]}], ]}, { 'archive_prefix': 'UNSUPPORTED_CONFIGURATION' }], ], }, 'actions': [ { 'action_name': 'unpack_<(archive_prefix)-<(_ubuntu_release).tgz', 'inputs': [ 'binaries/<(archive_prefix)-<(_ubuntu_release).tgz', ], 'outputs': [ '<(PRODUCT_DIR)/instrumented_libraries_prebuilt/<(archive_prefix).txt', ], 'action': [ 'scripts/unpack_binaries.py', '<(archive_prefix)', 'binaries', '<(PRODUCT_DIR)/instrumented_libraries_prebuilt/', ], }, ], 'direct_dependent_settings': { 'target_conditions': [ ['_toolset=="target"', { 'ldflags': [ # Add a relative RPATH entry to Chromium binaries. This puts # instrumented DSOs before system-installed versions in library # search path. '-Wl,-R,\$$ORIGIN/instrumented_libraries_prebuilt/<(_sanitizer_type)/<(_libdir)/', '-Wl,-z,origin', ], }], ], }, }, { 'target_name': 'instrumented_libraries', 'type': 'none', 'variables': { 'prune_self_dependency': 1, # Don't add this target to the dependencies of targets with type=none. 'link_dependency': 1, }, # NOTE: Please keep install-build-deps.sh in sync with this list. 'dependencies': [ '<(_sanitizer_type)-freetype', '<(_sanitizer_type)-libcairo2', '<(_sanitizer_type)-libexpat1', '<(_sanitizer_type)-libffi6', '<(_sanitizer_type)-libgcrypt11', '<(_sanitizer_type)-libgpg-error0', '<(_sanitizer_type)-libnspr4', '<(_sanitizer_type)-libp11-kit0', '<(_sanitizer_type)-libpcre3', '<(_sanitizer_type)-libpng12-0', '<(_sanitizer_type)-libx11-6', '<(_sanitizer_type)-libxau6', '<(_sanitizer_type)-libxcb1', '<(_sanitizer_type)-libxcomposite1', '<(_sanitizer_type)-libxcursor1', '<(_sanitizer_type)-libxdamage1', '<(_sanitizer_type)-libxdmcp6', '<(_sanitizer_type)-libxext6', '<(_sanitizer_type)-libxfixes3', '<(_sanitizer_type)-libxi6', '<(_sanitizer_type)-libxinerama1', '<(_sanitizer_type)-libxrandr2', '<(_sanitizer_type)-libxrender1', '<(_sanitizer_type)-libxss1', '<(_sanitizer_type)-libxtst6', '<(_sanitizer_type)-zlib1g', '<(_sanitizer_type)-libglib2.0-0', '<(_sanitizer_type)-libdbus-1-3', '<(_sanitizer_type)-libdbus-glib-1-2', '<(_sanitizer_type)-nss', '<(_sanitizer_type)-libfontconfig1', '<(_sanitizer_type)-pulseaudio', '<(_sanitizer_type)-libasound2', '<(_sanitizer_type)-pango1.0', '<(_sanitizer_type)-libcap2', '<(_sanitizer_type)-udev', '<(_sanitizer_type)-libgnome-keyring0', '<(_sanitizer_type)-libgtk2.0-0', '<(_sanitizer_type)-libgdk-pixbuf2.0-0', '<(_sanitizer_type)-libpci3', '<(_sanitizer_type)-libdbusmenu-glib4', '<(_sanitizer_type)-libgconf-2-4', '<(_sanitizer_type)-libappindicator1', '<(_sanitizer_type)-libdbusmenu', '<(_sanitizer_type)-atk1.0', '<(_sanitizer_type)-libunity9', '<(_sanitizer_type)-dee', '<(_sanitizer_type)-libpixman-1-0', '<(_sanitizer_type)-brltty', '<(_sanitizer_type)-libva1', '<(_sanitizer_type)-libcredentialkit_pkcs11-stub', ], 'conditions': [ ['"<(_ubuntu_release)"=="precise"', { 'dependencies': [ '<(_sanitizer_type)-libtasn1-3', ], }, { 'dependencies': [ # Trusty and above. '<(_sanitizer_type)-libtasn1-6', '<(_sanitizer_type)-harfbuzz', '<(_sanitizer_type)-libsecret', ], }], ['msan==1', { 'dependencies': [ '<(_sanitizer_type)-libcups2', ], }], ['tsan==1', { 'dependencies!': [ '<(_sanitizer_type)-libpng12-0', ], }], ], 'direct_dependent_settings': { 'target_conditions': [ ['_toolset=="target"', { 'ldflags': [ # Add a relative RPATH entry to Chromium binaries. This puts # instrumented DSOs before system-installed versions in library # search path. '-Wl,-R,\$$ORIGIN/instrumented_libraries/<(_sanitizer_type)/<(_libdir)/', '-Wl,-z,origin', ], }], ], }, }, { 'package_name': 'freetype', 'dependencies=': [], 'extra_configure_flags': ['--disable-static'], 'pre_build': 'scripts/pre-build/freetype.sh', 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'libcairo2', 'dependencies=': [], 'extra_configure_flags': [ '--disable-gtk-doc', '--disable-static', ], 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'libdbus-1-3', 'dependencies=': [], 'extra_configure_flags': [ '--disable-static', # From debian/rules. '--disable-libaudit', '--enable-apparmor', '--enable-systemd', '--libexecdir=/lib/dbus-1.0', '--with-systemdsystemunitdir=/lib/systemd/system', '--disable-tests', '--exec-prefix=/', # From dh_auto_configure. '--prefix=/usr', '--localstatedir=/var', ], 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'libdbus-glib-1-2', 'dependencies=': [], 'extra_configure_flags': [ # Use system dbus-binding-tool. The just-built one is instrumented but # doesn't have the correct RPATH, and will crash. '--with-dbus-binding-tool=dbus-binding-tool', '--disable-static', ], 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'libexpat1', 'dependencies=': [], 'extra_configure_flags': ['--disable-static'], 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'libffi6', 'dependencies=': [], 'extra_configure_flags': ['--disable-static'], 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'libfontconfig1', 'dependencies=': [], 'extra_configure_flags': [ '--disable-docs', '--sysconfdir=/etc/', '--disable-static', # From debian/rules. '--with-add-fonts=/usr/X11R6/lib/X11/fonts,/usr/local/share/fonts', ], 'conditions': [ ['"<(_ubuntu_release)"=="precise"', { 'patch': 'patches/libfontconfig.precise.diff', }, { 'patch': 'patches/libfontconfig.trusty.diff', }], ], 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'libgcrypt11', 'dependencies=': [], 'package_ldflags': ['-Wl,-z,muldefs'], 'extra_configure_flags': [ # From debian/rules. '--enable-noexecstack', '--enable-ld-version-script', '--disable-static', # http://crbug.com/344505 '--disable-asm' ], 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'libglib2.0-0', 'dependencies=': [], 'extra_configure_flags': [ '--disable-gtk-doc', '--disable-gtk-doc-html', '--disable-gtk-doc-pdf', '--disable-static', ], 'asan_blacklist': 'blacklists/asan/libglib2.0-0.txt', 'msan_blacklist': 'blacklists/msan/libglib2.0-0.txt', 'pre_build': 'scripts/pre-build/autogen.sh', 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'libgpg-error0', 'dependencies=': [], 'extra_configure_flags': ['--disable-static'], 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'libnspr4', 'dependencies=': [], 'extra_configure_flags': [ '--enable-64bit', '--disable-static', # TSan reports data races on debug variables. '--disable-debug', ], 'pre_build': 'scripts/pre-build/libnspr4.sh', 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'libp11-kit0', 'dependencies=': [], 'extra_configure_flags': ['--disable-static'], # Required on Trusty due to autoconf version mismatch. 'pre_build': 'scripts/pre-build/autoreconf.sh', 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'libpcre3', 'dependencies=': [], 'extra_configure_flags': [ '--enable-utf8', '--enable-unicode-properties', '--disable-static', ], 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'libpixman-1-0', 'dependencies=': [], 'extra_configure_flags': [ '--disable-static', # From debian/rules. '--disable-gtk', '--disable-silent-rules', # Avoid a clang issue. http://crbug.com/449183 '--disable-mmx', ], 'patch': 'patches/libpixman-1-0.diff', 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'libpng12-0', 'dependencies=': [], 'extra_configure_flags': ['--disable-static'], 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'libx11-6', 'dependencies=': [], 'extra_configure_flags': [ '--disable-specs', '--disable-static', ], 'msan_blacklist': 'blacklists/msan/libx11-6.txt', # Required on Trusty due to autoconf version mismatch. 'pre_build': 'scripts/pre-build/autoreconf.sh', 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'libxau6', 'dependencies=': [], 'extra_configure_flags': ['--disable-static'], 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'libxcb1', 'dependencies=': [], 'extra_configure_flags': [ '--disable-build-docs', '--disable-static', ], 'conditions': [ ['"<(_ubuntu_release)"=="precise"', { # Backport fix for https://bugs.freedesktop.org/show_bug.cgi?id=54671 'patch': 'patches/libxcb1.precise.diff', }], ], # Required on Trusty due to autoconf version mismatch. 'pre_build': 'scripts/pre-build/autoreconf.sh', 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'libxcomposite1', 'dependencies=': [], 'extra_configure_flags': ['--disable-static'], 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'libxcursor1', 'dependencies=': [], 'extra_configure_flags': ['--disable-static'], 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'libxdamage1', 'dependencies=': [], 'extra_configure_flags': ['--disable-static'], 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'libxdmcp6', 'dependencies=': [], 'extra_configure_flags': [ '--disable-docs', '--disable-static', ], 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'libxext6', 'dependencies=': [], 'extra_configure_flags': [ '--disable-specs', '--disable-static', ], 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'libxfixes3', 'dependencies=': [], 'extra_configure_flags': ['--disable-static'], 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'libxi6', 'dependencies=': [], 'extra_configure_flags': [ '--disable-specs', '--disable-docs', '--disable-static', ], 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'libxinerama1', 'dependencies=': [], 'extra_configure_flags': ['--disable-static'], 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'libxrandr2', 'dependencies=': [], 'extra_configure_flags': ['--disable-static'], 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'libxrender1', 'dependencies=': [], 'extra_configure_flags': ['--disable-static'], 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'libxss1', 'dependencies=': [], 'extra_configure_flags': ['--disable-static'], 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'libxtst6', 'dependencies=': [], 'extra_configure_flags': [ '--disable-specs', '--disable-static', ], 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'zlib1g', 'dependencies=': [], # --disable-static is not supported 'patch': 'patches/zlib1g.diff', 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'nss', 'dependencies=': [ # TODO(eugenis): get rid of this dependency '<(_sanitizer_type)-libnspr4', ], 'patch': 'patches/nss.diff', 'build_method': 'custom_nss', 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'pulseaudio', 'dependencies=': [], 'conditions': [ ['"<(_ubuntu_release)"=="precise"', { 'patch': 'patches/pulseaudio.precise.diff', 'jobs': 1, }, { # New location of libpulsecommon. 'package_ldflags': [ '-Wl,-R,XORIGIN/pulseaudio/.' ], }], ], 'extra_configure_flags': [ '--disable-static', # From debian/rules. '--enable-x11', '--disable-hal-compat', # Disable some ARM-related code that fails compilation. No idea why # this even impacts x86-64 builds. '--disable-neon-opt' ], 'pre_build': 'scripts/pre-build/pulseaudio.sh', 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'libasound2', 'dependencies=': [], 'extra_configure_flags': ['--disable-static'], 'pre_build': 'scripts/pre-build/libasound2.sh', 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'libcups2', 'dependencies=': [], 'patch': 'patches/libcups2.diff', 'jobs': 1, 'extra_configure_flags': [ '--disable-static', # All from debian/rules. '--localedir=/usr/share/cups/locale', '--enable-slp', '--enable-libpaper', '--enable-ssl', '--enable-gnutls', '--disable-openssl', '--enable-threads', '--enable-debug', '--enable-dbus', '--with-dbusdir=/etc/dbus-1', '--enable-gssapi', '--enable-avahi', '--with-pdftops=/usr/bin/gs', '--disable-launchd', '--with-cups-group=lp', '--with-system-groups=lpadmin', '--with-printcap=/var/run/cups/printcap', '--with-log-file-perm=0640', '--with-local_protocols="CUPS dnssd"', '--with-remote_protocols="CUPS dnssd"', '--enable-libusb', ], 'pre_build': 'scripts/pre-build/libcups2.sh', 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'pango1.0', 'dependencies=': [], 'extra_configure_flags': [ '--disable-static', # Avoid https://bugs.gentoo.org/show_bug.cgi?id=425620 '--enable-introspection=no', # Pango is normally used with dynamically loaded modules. However, # ensuring pango is able to find instrumented versions of those modules # is a huge pain in the neck. Let's link them statically instead, and # hope for the best. '--with-included-modules=yes' ], 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'libcap2', 'dependencies=': [], 'extra_configure_flags': ['--disable-static'], 'build_method': 'custom_libcap', 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'udev', 'dependencies=': [], 'extra_configure_flags': [ '--disable-static', # Without this flag there's a linking step that doesn't honor LDFLAGS # and fails. # TODO(eugenis): find a better fix. '--disable-gudev' ], 'pre_build': 'scripts/pre-build/udev.sh', 'includes': ['standard_instrumented_package_target.gypi'], }, { 'package_name': 'libtasn1-3', 'dependencies=': [], 'extra_configure_flags': [ '--disable-static', # From
per_channel=0.5) seen = [0, 0] for _ in sm.xrange(200): observed = aug.augment_image(np.zeros((1, 1, 100), dtype=np.uint8)) uq = np.unique(observed) if len(uq) == 1: seen[0] += 1 elif len(uq) > 1: seen[1] += 1 else: assert False assert 100 - 50 < seen[0] < 100 + 50 assert 100 - 50 < seen[1] < 100 + 50 def test_bad_datatype_for_per_channel_fails(self): # bad datatype for per_channel got_exception = False try: _ = iaa.BlendAlpha(0.5, iaa.Add(10), None, per_channel="test") except Exception as exc: assert "Expected " in str(exc) got_exception = True assert got_exception def test_hooks_limiting_propagation(self): aug = iaa.BlendAlpha(0.5, iaa.Add(100), iaa.Add(50), name="AlphaTest") def propagator(images, augmenter, parents, default): if "Alpha" in augmenter.name: return False else: return default hooks = ia.HooksImages(propagator=propagator) image = np.zeros((10, 10, 3), dtype=np.uint8) + 1 observed = aug.augment_image(image, hooks=hooks) assert np.array_equal(observed, image) def test_keypoints_factor_is_1(self): self._test_cba_factor_is_1("augment_keypoints", self.kpsoi) def test_keypoints_factor_is_0501(self): self._test_cba_factor_is_0501("augment_keypoints", self.kpsoi) def test_keypoints_factor_is_0(self): self._test_cba_factor_is_0("augment_keypoints", self.kpsoi) def test_keypoints_factor_is_0499(self): self._test_cba_factor_is_0499("augment_keypoints", self.kpsoi) def test_keypoints_factor_is_1_with_per_channel(self): self._test_cba_factor_is_1_and_per_channel( "augment_keypoints", self.kpsoi) def test_keypoints_factor_is_0_with_per_channel(self): self._test_cba_factor_is_0_and_per_channel( "augment_keypoints", self.kpsoi) def test_keypoints_factor_is_choice_of_vals_close_to_050_per_channel(self): self._test_cba_factor_is_choice_around_050_and_per_channel( "augment_keypoints", self.kpsoi) def test_keypoints_are_empty(self): self._test_empty_cba( "augment_keypoints", ia.KeypointsOnImage([], shape=(1, 2, 3))) def test_keypoints_hooks_limit_propagation(self): self._test_cba_hooks_limit_propagation( "augment_keypoints", self.kpsoi) def test_polygons_factor_is_1(self): self._test_cba_factor_is_1("augment_polygons", self.psoi) def test_polygons_factor_is_0501(self): self._test_cba_factor_is_0501("augment_polygons", self.psoi) def test_polygons_factor_is_0(self): self._test_cba_factor_is_0("augment_polygons", self.psoi) def test_polygons_factor_is_0499(self): self._test_cba_factor_is_0499("augment_polygons", self.psoi) def test_polygons_factor_is_1_and_per_channel(self): self._test_cba_factor_is_1_and_per_channel( "augment_polygons", self.psoi) def test_polygons_factor_is_0_and_per_channel(self): self._test_cba_factor_is_0_and_per_channel( "augment_polygons", self.psoi) def test_polygons_factor_is_choice_around_050_and_per_channel(self): self._test_cba_factor_is_choice_around_050_and_per_channel( "augment_polygons", self.psoi ) def test_empty_polygons(self): return self._test_empty_cba( "augment_polygons", ia.PolygonsOnImage([], shape=(1, 2, 3))) def test_polygons_hooks_limit_propagation(self): return self._test_cba_hooks_limit_propagation( "augment_polygons", self.psoi) def test_line_strings_factor_is_1(self): self._test_cba_factor_is_1("augment_line_strings", self.lsoi) def test_line_strings_factor_is_0501(self): self._test_cba_factor_is_0501("augment_line_strings", self.lsoi) def test_line_strings_factor_is_0(self): self._test_cba_factor_is_0("augment_line_strings", self.lsoi) def test_line_strings_factor_is_0499(self): self._test_cba_factor_is_0499("augment_line_strings", self.lsoi) def test_line_strings_factor_is_1_and_per_channel(self): self._test_cba_factor_is_1_and_per_channel( "augment_line_strings", self.lsoi) def test_line_strings_factor_is_0_and_per_channel(self): self._test_cba_factor_is_0_and_per_channel( "augment_line_strings", self.lsoi) def test_line_strings_factor_is_choice_around_050_and_per_channel(self): self._test_cba_factor_is_choice_around_050_and_per_channel( "augment_line_strings", self.lsoi ) def test_empty_line_strings(self): return self._test_empty_cba( "augment_line_strings", ia.LineStringsOnImage([], shape=(1, 2, 3))) def test_line_strings_hooks_limit_propagation(self): return self._test_cba_hooks_limit_propagation( "augment_line_strings", self.lsoi) def test_bounding_boxes_factor_is_1(self): self._test_cba_factor_is_1("augment_bounding_boxes", self.bbsoi) def test_bounding_boxes_factor_is_0501(self): self._test_cba_factor_is_0501("augment_bounding_boxes", self.bbsoi) def test_bounding_boxes_factor_is_0(self): self._test_cba_factor_is_0("augment_bounding_boxes", self.bbsoi) def test_bounding_boxes_factor_is_0499(self): self._test_cba_factor_is_0499("augment_bounding_boxes", self.bbsoi) def test_bounding_boxes_factor_is_1_and_per_channel(self): self._test_cba_factor_is_1_and_per_channel( "augment_bounding_boxes", self.bbsoi) def test_bounding_boxes_factor_is_0_and_per_channel(self): self._test_cba_factor_is_0_and_per_channel( "augment_bounding_boxes", self.bbsoi) def test_bounding_boxes_factor_is_choice_around_050_and_per_channel(self): self._test_cba_factor_is_choice_around_050_and_per_channel( "augment_bounding_boxes", self.bbsoi ) def test_empty_bounding_boxes(self): return self._test_empty_cba( "augment_bounding_boxes", ia.BoundingBoxesOnImage([], shape=(1, 2, 3))) def test_bounding_boxes_hooks_limit_propagation(self): return self._test_cba_hooks_limit_propagation( "augment_bounding_boxes", self.bbsoi) # Tests for CBA (=coordinate based augmentable) below. This currently # covers keypoints, polygons and bounding boxes. @classmethod def _test_cba_factor_is_1(cls, augf_name, cbaoi): aug = iaa.BlendAlpha( 1.0, iaa.Identity(), iaa.Affine(translate_px={"x": 1})) observed = getattr(aug, augf_name)([cbaoi]) assert_cbaois_equal(observed[0], cbaoi) @classmethod def _test_cba_factor_is_0501(cls, augf_name, cbaoi): aug = iaa.BlendAlpha(0.501, iaa.Identity(), iaa.Affine(translate_px={"x": 1})) observed = getattr(aug, augf_name)([cbaoi]) assert_cbaois_equal(observed[0], cbaoi) @classmethod def _test_cba_factor_is_0(cls, augf_name, cbaoi): aug = iaa.BlendAlpha( 0.0, iaa.Identity(), iaa.Affine(translate_px={"x": 1})) observed = getattr(aug, augf_name)([cbaoi]) expected = cbaoi.shift(x=1) assert_cbaois_equal(observed[0], expected) @classmethod def _test_cba_factor_is_0499(cls, augf_name, cbaoi): aug = iaa.BlendAlpha(0.499, iaa.Identity(), iaa.Affine(translate_px={"x": 1})) observed = getattr(aug, augf_name)([cbaoi]) expected = cbaoi.shift(x=1) assert_cbaois_equal(observed[0], expected) @classmethod def _test_cba_factor_is_1_and_per_channel(cls, augf_name, cbaoi): aug = iaa.BlendAlpha( 1.0, iaa.Identity(), iaa.Affine(translate_px={"x": 1}), per_channel=True) observed = getattr(aug, augf_name)([cbaoi]) assert_cbaois_equal(observed[0], cbaoi) @classmethod def _test_cba_factor_is_0_and_per_channel(cls, augf_name, cbaoi): aug = iaa.BlendAlpha( 0.0, iaa.Identity(), iaa.Affine(translate_px={"x": 1}), per_channel=True) observed = getattr(aug, augf_name)([cbaoi]) expected = cbaoi.shift(x=1) assert_cbaois_equal(observed[0], expected) @classmethod def _test_cba_factor_is_choice_around_050_and_per_channel( cls, augf_name, cbaoi): aug = iaa.BlendAlpha( iap.Choice([0.49, 0.51]), iaa.Identity(), iaa.Affine(translate_px={"x": 1}), per_channel=True) expected_same = cbaoi.deepcopy() expected_shifted = cbaoi.shift(x=1) seen = [0, 0, 0] for _ in sm.xrange(200): observed = getattr(aug, augf_name)([cbaoi])[0] assert len(observed.items) == len(expected_same.items) assert len(observed.items) == len(expected_shifted.items) # We use here allclose() instead of coords_almost_equals() # as the latter one is much slower for polygons and we don't have # to deal with tricky geometry changes here, just naive shifting. if np.allclose(observed.items[0].coords, expected_same.items[0].coords, rtol=0, atol=0.1): seen[0] += 1 elif np.allclose(observed.items[0].coords, expected_shifted.items[0].coords, rtol=0, atol=0.1): seen[1] += 1 else: seen[2] += 1 assert 100 - 50 < seen[0] < 100 + 50 assert 100 - 50 < seen[1] < 100 + 50 assert seen[2] == 0 @classmethod def _test_empty_cba(cls, augf_name, cbaoi): # empty CBAs aug = iaa.BlendAlpha(0.501, iaa.Identity(), iaa.Affine(translate_px={"x": 1})) observed = getattr(aug, augf_name)(cbaoi) assert len(observed.items) == 0 assert observed.shape == cbaoi.shape @classmethod def _test_cba_hooks_limit_propagation(cls, augf_name, cbaoi): aug = iaa.BlendAlpha( 0.0, iaa.Affine(translate_px={"x": 1}), iaa.Affine(translate_px={"y": 1}), name="AlphaTest") def propagator(cbaoi_to_aug, augmenter, parents, default): if "Alpha" in augmenter.name: return False else: return default # no hooks for polygons yet, so we use HooksKeypoints hooks = ia.HooksKeypoints(propagator=propagator) observed = getattr(aug, augf_name)([cbaoi], hooks=hooks)[0] assert observed.items[0].coords_almost_equals(cbaoi.items[0]) def test_zero_sized_axes(self): shapes = [ (0, 0), (0, 1), (1, 0), (0, 1, 0), (1, 0, 0), (0, 1, 1), (1, 0, 1) ] for shape in shapes: with self.subTest(shape=shape): image = np.full(shape, 0, dtype=np.uint8) aug = iaa.BlendAlpha(1.0, iaa.Add(1), iaa.Add(100)) image_aug = aug(image=image) assert np.all(image_aug == 1) assert image_aug.dtype.name == "uint8" assert image_aug.shape == shape def test_unusual_channel_numbers(self): shapes = [ (1, 1, 4), (1, 1, 5), (1, 1, 512), (1, 1, 513) ] for shape in shapes: with self.subTest(shape=shape): image = np.full(shape, 0, dtype=np.uint8) aug = iaa.BlendAlpha(1.0, iaa.Add(1), iaa.Add(100)) image_aug = aug(image=image) assert np.all(image_aug == 1) assert image_aug.dtype.name == "uint8" assert image_aug.shape == shape def test_get_parameters(self): fg = iaa.Identity() bg = iaa.Sequential([iaa.Add(1)]) aug = iaa.BlendAlpha(0.65, fg, bg, per_channel=1) params = aug.get_parameters() assert params[0] is aug.factor assert params[1] is aug.per_channel assert 0.65 - 1e-6 < params[0].value < 0.65 + 1e-6 assert params[1].value == 1 def test_get_children_lists(self): fg = iaa.Identity() bg = iaa.Sequential([iaa.Add(1)]) aug = iaa.BlendAlpha(0.65, fg, bg, per_channel=1) children_lsts = aug.get_children_lists() assert len(children_lsts) == 2 assert ia.is_iterable([lst for lst in children_lsts]) assert fg in children_lsts[0] assert bg == children_lsts[1] def test_to_deterministic(self): class _DummyAugmenter(iaa.Identity): def __init__(self, *args, **kwargs): super(_DummyAugmenter, self).__init__(*args, **kwargs) self.deterministic_called = False def _to_deterministic(self): self.deterministic_called = True return self identity1 = _DummyAugmenter() identity2 = _DummyAugmenter() aug = iaa.BlendAlpha(0.5, identity1, identity2) aug_det = aug.to_deterministic() assert aug_det.deterministic assert aug_det.random_state is not aug.random_state assert aug_det.foreground.deterministic assert aug_det.background.deterministic assert identity1.deterministic_called is True assert identity2.deterministic_called is True def test_pickleable(self): aug = iaa.BlendAlpha( (0.1, 0.9), iaa.Add((1, 10), seed=1), iaa.Add((11, 20), seed=2), per_channel=True, seed=3) runtest_pickleable_uint8_img(aug, iterations=10) class _DummyMaskParameter(iap.StochasticParameter): def __init__(self, inverted=False): super(_DummyMaskParameter, self).__init__() self.inverted = inverted def _draw_samples(self, size, random_state): h, w = size[0:2] nb_channels = 1 if len(size) == 2 else size[2] assert nb_channels <= 3 result = [] for i in np.arange(nb_channels): if i == 0: result.append(np.zeros((h, w), dtype=np.float32)) else: result.append(np.ones((h, w), dtype=np.float32)) result = np.stack(result, axis=-1) if len(size) == 2: result = result[:, :, 0] if self.inverted: result = 1.0 - result return result class TestAlphaElementwise(unittest.TestCase): def test_deprecation_warning(self): aug1 = iaa.Sequential([]) aug2 = iaa.Sequential([]) with warnings.catch_warnings(record=True) as caught_warnings: warnings.simplefilter("always") aug = iaa.AlphaElementwise(factor=0.5, first=aug1, second=aug2) assert ( "is deprecated" in str(caught_warnings[-1].message) ) assert isinstance(aug, iaa.BlendAlphaElementwise) assert np.isclose(aug.factor.value, 0.5) assert aug.foreground is aug1 assert aug.background is aug2 # TODO add tests for heatmaps and segmaps that differ from the image size class TestBlendAlphaElementwise(unittest.TestCase): def setUp(self): reseed() @property def image(self): base_img = np.zeros((3, 3, 1), dtype=np.uint8) return base_img @property def heatmaps(self): heatmaps_arr = np.float32([[0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 1.0, 1.0]]) return HeatmapsOnImage(heatmaps_arr, shape=(3, 3, 3)) @property def heatmaps_r1(self): heatmaps_arr_r1 = np.float32([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0]]) return HeatmapsOnImage(heatmaps_arr_r1, shape=(3, 3, 3)) @property def heatmaps_l1(self): heatmaps_arr_l1 = np.float32([[0.0, 1.0, 0.0], [0.0, 1.0, 0.0], [1.0, 1.0, 0.0]]) return HeatmapsOnImage(heatmaps_arr_l1, shape=(3, 3, 3)) @property def segmaps(self): segmaps_arr = np.int32([[0, 0, 1], [0, 0, 1], [0, 1, 1]]) return SegmentationMapsOnImage(segmaps_arr, shape=(3, 3, 3)) @property def segmaps_r1(self): segmaps_arr_r1 = np.int32([[0, 0, 0], [0, 0, 0], [0, 0, 1]]) return SegmentationMapsOnImage(segmaps_arr_r1, shape=(3, 3, 3)) @property def segmaps_l1(self): segmaps_arr_l1 = np.int32([[0, 1, 0], [0, 1, 0], [1, 1, 0]]) return SegmentationMapsOnImage(segmaps_arr_l1, shape=(3, 3, 3)) @property def kpsoi(self): kps = [ia.Keypoint(x=5, y=10), ia.Keypoint(x=6, y=11)] return ia.KeypointsOnImage(kps, shape=(20, 20, 3)) @property def psoi(self): ps = [ia.Polygon([(5, 5), (10, 5), (10, 10)])] return ia.PolygonsOnImage(ps, shape=(20, 20, 3)) @property def lsoi(self): lss = [ia.LineString([(5, 5), (10, 5), (10, 10)])] return ia.LineStringsOnImage(lss, shape=(20, 20, 3)) @property def bbsoi(self): bbs = [ia.BoundingBox(x1=5, y1=6, x2=7, y2=8)] return ia.BoundingBoxesOnImage(bbs, shape=(20, 20, 3)) def test_images_factor_is_1(self): aug = iaa.BlendAlphaElementwise(1, iaa.Add(10), iaa.Add(20)) observed = aug.augment_image(self.image) expected = self.image + 10 assert np.allclose(observed, expected) def test_heatmaps_factor_is_1_with_affines(self): aug = iaa.BlendAlphaElementwise( 1, iaa.Affine(translate_px={"x": 1}), iaa.Affine(translate_px={"x": -1})) observed = aug.augment_heatmaps([self.heatmaps])[0] assert observed.shape == (3, 3, 3) assert 0 - 1e-6 < observed.min_value < 0 + 1e-6 assert 1 - 1e-6 < observed.max_value < 1 + 1e-6 assert np.allclose(observed.get_arr(), self.heatmaps_r1.get_arr()) def test_segmaps_factor_is_1_with_affines(self): aug = iaa.BlendAlphaElementwise( 1, iaa.Affine(translate_px={"x": 1}), iaa.Affine(translate_px={"x": -1})) observed = aug.augment_segmentation_maps([self.segmaps])[0] assert observed.shape == (3, 3, 3) assert np.array_equal(observed.get_arr(),
import ast import logging from re import template import warnings import numpy as np import pandas as pd from idaes.core import FlowsheetBlock from idaes.core.util.model_statistics import degrees_of_freedom import os from pyomo.environ import Var, Expression, NonNegativeReals, Block, ConcreteModel, Constraint, Objective, SolverFactory, TransformationFactory, units as pyunits, value from pyomo.network import SequentialDecomposition, Arc from pyomo.network.port import SimplePort # from pyomo.contrib.mindtpy.MindtPy import MindtPySolver from . import financials from .case_study_trains import * from .post_processing import get_results_table import pyomo.environ from pyomo.gdp import * warnings.filterwarnings('ignore') __all__ = ['watertap_setup', 'run_model', 'run_and_return_model', 'run_model_no_print', 'run_watertap3', 'case_study_constraints', 'get_ix_stash', 'fix_ix_stash', 'print_ro_results', 'print_results', 'set_bounds', 'get_ro_stash', 'fix_ro_stash', 'make_decision', 'connected_units'] def watertap_setup(dynamic=False, case_study=None, reference='nawi', scenario=None, source_reference=None, source_case_study=None, source_scenario=None, new_df_units=None): ''' Initial setup of WaterTAP3 model. Create flowsheet and read in basic information about model (water sources, units in treatment train) ''' def get_source(reference, water_type, case_study, scenario): ''' Read in water source data. ''' input_file = 'data/case_study_water_sources.csv' df = pd.read_csv(input_file, index_col='variable') try: source_df = df[((df.case_study == case_study) & (df.water_type == water_type) & (df.reference == reference) & (df.scenario == scenario))].copy() source_flow = source_df.loc['flow'].value except: source_df = df[((df.case_study == case_study) & (df.water_type == water_type) & (df.reference == reference) & (df.scenario == 'baseline'))].copy() source_flow = source_df.loc['flow'].value source_df.drop(source_df[source_df.index == 'flow'].index, inplace=True) return source_flow, source_df case_study_print = case_study.replace('_', ' ').swapcase() scenario_print = scenario.replace('_', ' ').swapcase() m_name = f'{case_study_print}: {scenario_print}' m = ConcreteModel(name=m_name) m.fs = FlowsheetBlock(default={ 'dynamic': dynamic }) m.fs.train = { 'case_study': case_study, 'reference': reference, 'scenario': scenario } if source_reference is None: source_reference = reference if source_case_study is None: source_case_study = case_study if source_scenario is None: source_scenario = scenario df = pd.read_csv('data/treatment_train_setup.csv') # Read in treatment train input sheet. water_type_list = [] if new_df_units is not None: m.fs.df_units = new_df_units.copy() else: m.fs.df_units = df[((df.Reference == reference) & (df.Scenario == scenario) & (df.CaseStudy == case_study))].copy() print(f'\nCase Study = {case_study_print}' f'\nScenario = {scenario_print}\n') m.fs.has_ro = False m.fs.has_ix = False if 'ion_exchange' in m.fs.df_units.Unit: m.fs.has_ix = True if 'reverse_osmosis' in m.fs.df_units.Unit: m.fs.has_ro = True for i in m.fs.df_units[m.fs.df_units.Type == 'intake'].index: temp_dict = ast.literal_eval(m.fs.df_units[m.fs.df_units.Type == 'intake'].loc[i]['Parameter']) for water_type in temp_dict['water_type']: water_type_list.append(water_type) if len(water_type_list) == 1: water_type_list = water_type_list[0] m.fs.source_water = { 'case_study': source_case_study, 'reference': source_reference, 'scenario': source_scenario, 'water_type': water_type_list } flow_dict = {} if isinstance(m.fs.source_water['water_type'], list): m.fs.source_df = pd.DataFrame() for water_type in m.fs.source_water['water_type']: source_flow, source_df = get_source(m.fs.source_water['reference'], water_type, m.fs.source_water['case_study'], m.fs.source_water['scenario']) flow_dict[water_type] = source_flow m.fs.source_df = m.fs.source_df.append(source_df) else: source_flow, source_df = get_source(m.fs.source_water['reference'], m.fs.source_water['water_type'], m.fs.source_water['case_study'], m.fs.source_water['scenario']) flow_dict[m.fs.source_water['water_type']] = source_flow m.fs.source_df = source_df m.fs.flow_in_dict = flow_dict return m def run_and_return_model(m, solver='ipopt', tolerance=None, tee=False, objective=False, max_attempts=3, print_it=False, initial_run=True, mip_solver='glpk'): ''' Function to attempt model solve and return model object. ''' if initial_run: financials.get_system_costing(m.fs) TransformationFactory('network.expand_arcs').apply_to(m) if objective: m.fs.objective_function = Objective(expr=m.fs.costing.LCOW) model_solver = SolverFactory(solver) if tolerance and solver == 'ipopt': model_solver.options['tol'] = tolerance logging.getLogger('pyomo.core').setLevel(logging.ERROR) print('.................................') print('\nDegrees of Freedom:', degrees_of_freedom(m)) if solver == 'gdpopt': m.fs.results = results = model_solver.solve(m, tee=tee, mip_solver=mip_solver) else: m.fs.results = results = model_solver.solve(m, tee=tee) print(f'\nInitial solve attempt {results.solver.termination_condition.swapcase()}') attempt_number = 1 while ((m.fs.results.solver.termination_condition in ['infeasible', 'maxIterations', 'unbounded', 'other']) & (attempt_number <= max_attempts)): print(f'\nAttempt {attempt_number}:') if solver == 'gdpopt': m.fs.results = results = model_solver.solve(m, tee=tee, mip_solver=mip_solver) else: m.fs.results = results = model_solver.solve(m, tee=tee) print(f'\n\tWaterTAP3 solver returned {results.solver.termination_condition.swapcase()} solution...') attempt_number += 1 print(f'\nWaterTAP3 solution {results.solver.termination_condition.swapcase()}\n') print('.................................') if print_it: print_results(m) return m def run_model(m, solver='ipopt', tolerance=None, tee=False, objective=False, max_attempts=3, print_it=False, initial_run=True, mip_solver='glpk'): ''' Function used to attempt model solve. ''' if initial_run: financials.get_system_costing(m.fs) TransformationFactory('network.expand_arcs').apply_to(m) if objective: m.fs.objective_function = Objective(expr=m.fs.costing.LCOW) model_solver = SolverFactory(solver) if tolerance and solver == 'ipopt': model_solver.options['tol'] = tolerance logging.getLogger('pyomo.core').setLevel(logging.ERROR) print('.................................') print('\nDegrees of Freedom:', degrees_of_freedom(m)) if solver == 'gdpopt': m.fs.results = results = model_solver.solve(m, tee=tee, mip_solver=mip_solver) else: m.fs.results = results = model_solver.solve(m, tee=tee) print(f'\nInitial solve attempt {results.solver.termination_condition.swapcase()}') attempt_number = 1 while ((m.fs.results.solver.termination_condition in ['infeasible', 'maxIterations', 'unbounded', 'other']) & (attempt_number <= max_attempts)): print(f'\nAttempt {attempt_number}:') if solver == 'gdpopt': m.fs.results = results = model_solver.solve(m, tee=tee, mip_solver=mip_solver) else: m.fs.results = results = model_solver.solve(m, tee=tee) print(f'\n\tWaterTAP3 solver returned {results.solver.termination_condition.swapcase()} solution...') attempt_number += 1 print(f'\nWaterTAP3 solution {results.solver.termination_condition.swapcase()}\n') print('.................................') if print_it: print_results(m) def run_model_no_print(m, solver='ipopt', tolerance=None, tee=False, objective=False, max_attempts=3, initial_run=True, mip_solver='glpk', return_model=False): if initial_run: financials.get_system_costing(m.fs) TransformationFactory('network.expand_arcs').apply_to(m) if objective: m.fs.objective_function = Objective(expr=m.fs.costing.LCOW) model_solver = SolverFactory(solver) if tolerance and solver == 'ipopt': model_solver.options['tol'] = tolerance # m.fs.solver = solver = SolverFactory('glpk') logging.getLogger('pyomo.core').setLevel(logging.ERROR) if solver == 'gdpopt': m.fs.results = results = model_solver.solve(m, tee=tee, mip_solver=mip_solver) else: m.fs.results = results = model_solver.solve(m, tee=tee) attempt_number = 1 while ((m.fs.results.solver.termination_condition in ['infeasible', 'maxIterations', 'unbounded']) & (attempt_number <= max_attempts)): if solver == 'gdpopt': m.fs.results = results = model_solver.solve(m, tee=tee, mip_solver=mip_solver) else: m.fs.results = results = model_solver.solve(m, tee=tee) attempt_number += 1 if return_model: return m def run_watertap3(m, desired_recovery=1, ro_bounds='seawater', solver='ipopt', return_df=False, tolerance=None, tee=False): ''' Function to run WaterTAP3 ''' print('\n=========================START WT3 MODEL RUN==========================') scenario = m.fs.train['scenario'] case_study = m.fs.train['case_study'] reference = m.fs.train['reference'] run_model(m, solver=solver, objective=True, tolerance=tolerance, tee=tee) if m.fs.results.solver.termination_condition != 'optimal': raise Exception(f'\n\tMODEL RUN ABORTED:' f'\n\tWT3 solution is {m.fs.results.solver.termination_condition.swapcase()}' f'\n\tModel did not solve optimally after 3 attempts. No results are saved.' f'\n\tCheck model setup and initial conditions and retry.') if m.fs.choose: print(f'********TREATMENT TRAIN CONTAINS DECISION VARIABLE********') print('Removing non-optimal unit processes...\n\n') m = make_decision(m, case_study, scenario) print('The following units were dropped:') for dropped_unit in m.fs.all_dropped_units: print(f"\t{dropped_unit.replace('_', ' ').swapcase()}") print('\n=======================OPTIMIZED TREATMENT TRAIN=======================') run_model(m, solver=solver, objective=True, tolerance=tolerance, tee=tee) if m.fs.results.solver.termination_condition != 'optimal': raise Exception(f'\n\tMODEL RUN ABORTED:' f'\n\tWT3 solution is {m.fs.results.solver.termination_condition.swapcase()}' f'\n\tModel did not solve optimally after 3 attempts. No results are saved.' f'\n\tCheck model setup and initial conditions and retry.') if m.fs.has_ix: m, ix_stash = get_ix_stash(m) print('Initial IX solve OK...\nFixing number IX columns...') # m = fix_ix_stash(m, ix_stash, only_num_cols=True) m = fix_ix_stash(m, ix_stash) run_model(m, solver=solver, objective=True, tolerance=tolerance) # if m.fs.results.solver.termination_condition != 'optimal': # raise Exception(f'\n\tMODEL RUN ABORTED:' # f'\n\tWT3 solution is {m.fs.results.solver.termination_condition.swapcase()}' # f'\n\tIX did not solve after fixing the number of columns.') # print('IX solved!\nFixing other IX variables...') # m, ix_stash = get_ix_stash(m) # m = fix_ix_stash(m, ix_stash) m = case_study_constraints(m, case_study, scenario) if m.fs.has_ro: if case_study == 'upw': m.fs.splitter2.split_fraction_constr = Constraint(expr=sum(m.fs.splitter2.split_fraction_vars) <= 1.001) m.fs.splitter2.split_fraction_constr2 = Constraint(expr=sum(m.fs.splitter2.split_fraction_vars) >= 0.999) m = set_bounds(m, source_water_category=ro_bounds) if m.fs.results.solver.termination_condition != 'optimal': print(f'\n\tMODEL RUN ABORTED AFTER SETTING RO BOUNDS:' f'\n\tWT3 solution is {m.fs.results.solver.termination_condition.swapcase()}' f'\n\tModel did not solve optimally after 3 attempts. No results are saved.' f'\n\tCheck model setup and initial conditions and retry.') return m if desired_recovery < 1: if m.fs.costing.system_recovery() > desired_recovery: print('Running for desired recovery -->', desired_recovery) m.fs.recovery_bound = Constraint(expr=m.fs.costing.system_recovery <= desired_recovery) m.fs.recovery_bound1 = Constraint(expr=m.fs.costing.system_recovery >= desired_recovery - 1.5) run_model(m, objective=True, tolerance=tolerance) if m.fs.results.solver.termination_condition != 'optimal': print(f'\n\tMODEL RUN ABORTED WHILE TARGETING SYSTEM RECOVERY OF {desired_recovery * 100}:' f'\n\tWT3 solution is {m.fs.results.solver.termination_condition.swapcase()}' f'\n\tModel did not solve optimally after 3 attempts. No results are saved.' f'\n\tCheck model setup and initial conditions and retry.') return m else: print('System recovery already lower than desired recovery.' '\n\tDesired:', desired_recovery, '\n\tCurrent:', m.fs.costing.system_recovery()) if case_study == 'uranium': ur_list = [] ur_list.append(m.fs.ion_exchange.removal_fraction[0, 'tds']()) ur_list.append(m.fs.ion_exchange.anion_res_capacity[0]()) ur_list.append(m.fs.ion_exchange.cation_res_capacity[0]()) # change this to set splitters if case_study == 'upw': m.fs.upw_list = upw_list = [] upw_list.append(m.fs.splitter2.split_fraction_outlet_1[0]()) upw_list.append(m.fs.splitter2.split_fraction_outlet_2[0]()) if m.fs.has_ro: m, ro_stash = get_ro_stash(m) ###### RESET BOUNDS AND DOUBLE CHECK RUN IS OK SO CAN GO INTO SENSITIVITY ##### if m.fs.new_case_study: new_df_units = m.fs.df_units.copy() all_dropped_units = m.fs.all_dropped_units m = watertap_setup(dynamic=False, case_study=case_study, scenario=scenario, new_df_units=new_df_units) m.fs.all_dropped_units = all_dropped_units m = get_case_study(m=m, new_df_units=new_df_units) # if m.fs.has_ix: # m = fix_ix_stash(m, ix_stash) else: m = watertap_setup(dynamic=False, case_study=case_study, scenario=scenario) m = get_case_study(m=m) # if m.fs.has_ix: # m = fix_ix_stash(m, ix_stash) if case_study == 'gila_river' and scenario != 'baseline': m.fs.evaporation_pond.water_recovery.fix(0.895) if case_study == 'upw': run_model(m, solver=solver, objective=True, tolerance=tolerance) m.fs.upw_list = upw_list m.fs.media_filtration.water_recovery.fix(0.9) m.fs.splitter2.split_fraction_outlet_1.fix(upw_list[0]) m.fs.splitter2.split_fraction_outlet_2.fix(upw_list[1]) if case_study == 'ocwd': # Facility data in email from <NAME> 7/7/2021 # m.fs.ro_pressure_constr = Constraint(expr=m.fs.reverse_osmosis.feed.pressure[0] <= 15) # Facility data: RO pressure is 140-220 psi (~9.7-15.1 bar) m.fs.microfiltration.water_recovery.fix(0.9) if case_study == 'uranium': m.fs.ion_exchange.removal_fraction[0, 'tds'].fix(ur_list[0]) m.fs.ion_exchange.anion_res_capacity.fix(ur_list[1]) m.fs.ion_exchange.cation_res_capacity.fix(ur_list[2]) if case_study == 'irwin': run_model(m, solver=solver, objective=True, tolerance=tolerance) m.fs.brine_concentrator.water_recovery.fix(0.8) run_model(m, solver=solver, objective=True, tolerance=tolerance) m = fix_ro_stash(m, ro_stash) m.fs.objective_function.deactivate() # m = fix_ro_stash(m, ro_stash) if m.fs.has_ix: # m, ix_stash = get_ix_stash(m) m = fix_ix_stash(m, ix_stash) run_model(m, solver=solver, objective=False, print_it=True, tolerance=tolerance) if m.fs.results.solver.termination_condition != 'optimal': print(f'\nFINAL MODEL RUN ABORTED:' f'\n\tWT3 solution is {m.fs.results.solver.termination_condition.swapcase()}' f'\n\tModel did not solve optimally after 3 attempts. No results are saved.' f'\n\tCheck model setup and initial conditions
from __future__ import print_function from __future__ import division from __future__ import absolute_import import os import json import shutil from crds.bestrefs import BestrefsScript from crds.tests import test_config """ Bestrefs has a number of command line parameters which make it operate in different modes. ----------- NEW CONTEXT ----------- crds.bestrefs always computes best references with respect to a context which can be explicitly specified with the --new-context parameter. If no --new-context is specified, the default operational context is determined by consulting the CRDS server or looking in the local cache as a fallback. ------------------------ LOOKUP PARAMETER SOURCES ------------------------ The two primary modes for bestrefs involve the source of reference file matching parameters. Conceptually lookup parameters are always associated with particular datasets and used to identify the references required to process those datasets. The options --files, --datasets, --instruments, and --all determine the source of lookup parameters: 1. To find best references for a list of files do something like this: % python -m crds.bestrefs --new-context hst.pmap --files j8bt05njq_raw.fits j8bt06o6q_raw.fits j8bt09jcq_raw.fits the first parameter, hst.pmap, is the context with respect to which best references are determined. 2. To find best references for a list of catalog dataset ids do something like this: % python -m crds.bestrefs --new-context hst.pmap --datasets j8bt05njq j8bt06o6q j8bt09jcq 3. To do mass scale testing for all cataloged datasets for a particular instrument(s) do: % python -m crds.bestrefs --new-context hst.pmap --instruments acs 4. To do mass scale testing for all supported instruments for all cataloged datasets do: % python -m crds.bestrefs --new-context hst.pmap --all ---------------- COMPARISON MODES ---------------- The --old-context and --compare-source-bestrefs parameters define the best references comparison mode. Each names the origin of a set of prior recommendations and implicitly requests a comparison to the recommendations from the newly computed bestrefs determined by --new-context. CONTEXT-TO-CONTEXT .................. --old-context can be used to specify a second context for which bestrefs are dynamically computed; --old-context implies that a bestrefs comparison will be made with --new-context. PRIOR SOURCE RECOMMENDATIONS ............................ --compare-source-bestrefs requests that the bestrefs from --new-context be compared to the bestrefs which are recorded with the lookup parameter data, either in the file headers of data files, or in the catalog. In both cases the prior best references are recorded static values, not dynamically computed bestrefs. ------------ UPDATE MODES ------------ Currently there is only one update mode. When --files are specified as the input source, --update-bestrefs can also be specified to update the input data file headers with new bestrefs recommendations. In this case the data files are used as both the source of matching parameters and as the destination for best reference recommendations. ------------ OUTPUT MODES ------------ crds.bestrefs supports several output modes for bestrefs and comparison results. If --print-affected is specified, crds.bestrefs will print out the name of any file (or dataset id) for which at least one update for one reference type was recommended. This is essentially a list of files to be reprocessed with new references. % python -m crds.bestrefs --new-context hst.pmap --files j8bt05njq_raw.fits j8bt06o6q_raw.fits j8bt09jcq_raw.fits --compare-source-bestrefs --print-affected j8bt05njq_raw.fits j8bt06o6q_raw.fits j8bt09jcq_raw.fits """ def dt_bestrefs_3_files(): """ Compute simple bestrefs for 3 files: >>> old_state = test_config.setup() >>> BestrefsScript(argv="bestrefs.py --new-context hst.pmap --files data/j8bt05njq_raw.fits data/j8bt06o6q_raw.fits data/j8bt09jcq_raw.fits")() CRDS - INFO - No comparison context or source comparison requested. CRDS - INFO - No file header updates requested; dry run. CRDS - INFO - ===> Processing data/j8bt05njq_raw.fits CRDS - INFO - ===> Processing data/j8bt06o6q_raw.fits CRDS - INFO - ===> Processing data/j8bt09jcq_raw.fits CRDS - INFO - 0 errors CRDS - INFO - 0 warnings CRDS - INFO - 5 infos 0 >>> test_config.cleanup(old_state) """ def dt_bestrefs_compare_source_files(): """ Compute and print files with at least one reference change: >>> old_state = test_config.setup() >>> BestrefsScript(argv="bestrefs.py --new-context hst.pmap --files data/j8bt05njq_raw.fits data/j8bt06o6q_raw.fits data/j8bt09jcq_raw.fits --print-affected --compare-source-bestrefs")() CRDS - INFO - No file header updates requested; dry run. CRDS - INFO - ===> Processing data/j8bt05njq_raw.fits CRDS - INFO - instrument='ACS' type='ATODTAB' data='data/j8bt05njq_raw.fits' :: New best reference: 'kcb1734ij_a2d.fits' --> 'n/a' :: Would update. CRDS - INFO - instrument='ACS' type='CRREJTAB' data='data/j8bt05njq_raw.fits' :: New best reference: 'n4e12510j_crr.fits' --> 'n/a' :: Would update. CRDS - INFO - instrument='ACS' type='IMPHTTAB' data='data/j8bt05njq_raw.fits' :: New best reference: 'undefined' --> 'w3m1716tj_imp.fits' :: Would update. CRDS - INFO - instrument='ACS' type='NPOLFILE' data='data/j8bt05njq_raw.fits' :: New best reference: 'undefined' --> 'v9718263j_npl.fits' :: Would update. CRDS - INFO - instrument='ACS' type='SHADFILE' data='data/j8bt05njq_raw.fits' :: New best reference: 'kcb1734pj_shd.fits' --> 'n/a' :: Would update. CRDS - INFO - ===> Processing data/j8bt06o6q_raw.fits CRDS - INFO - instrument='ACS' type='ATODTAB' data='data/j8bt06o6q_raw.fits' :: New best reference: 'kcb1734ij_a2d.fits' --> 'n/a' :: Would update. CRDS - INFO - instrument='ACS' type='CRREJTAB' data='data/j8bt06o6q_raw.fits' :: New best reference: 'n4e12510j_crr.fits' --> 'n/a' :: Would update. CRDS - INFO - instrument='ACS' type='IMPHTTAB' data='data/j8bt06o6q_raw.fits' :: New best reference: 'undefined' --> 'w3m1716tj_imp.fits' :: Would update. CRDS - INFO - instrument='ACS' type='NPOLFILE' data='data/j8bt06o6q_raw.fits' :: New best reference: 'undefined' --> 'v9718264j_npl.fits' :: Would update. CRDS - INFO - instrument='ACS' type='SHADFILE' data='data/j8bt06o6q_raw.fits' :: New best reference: 'kcb1734pj_shd.fits' --> 'n/a' :: Would update. CRDS - INFO - ===> Processing data/j8bt09jcq_raw.fits CRDS - INFO - instrument='ACS' type='ATODTAB' data='data/j8bt09jcq_raw.fits' :: New best reference: 'kcb1734ij_a2d.fits' --> 'n/a' :: Would update. CRDS - INFO - instrument='ACS' type='IMPHTTAB' data='data/j8bt09jcq_raw.fits' :: New best reference: 'undefined' --> 'w3m1716tj_imp.fits' :: Would update. CRDS - INFO - instrument='ACS' type='NPOLFILE' data='data/j8bt09jcq_raw.fits' :: New best reference: 'undefined' --> 'v9718260j_npl.fits' :: Would update. CRDS - INFO - instrument='ACS' type='SHADFILE' data='data/j8bt09jcq_raw.fits' :: New best reference: 'kcb1734pj_shd.fits' --> 'n/a' :: Would update. CRDS - INFO - Affected products = 3 data/j8bt05njq_raw.fits data/j8bt06o6q_raw.fits data/j8bt09jcq_raw.fits CRDS - INFO - 0 errors CRDS - INFO - 0 warnings CRDS - INFO - 19 infos 0 >>> test_config.cleanup(old_state) """ def dt_bestrefs_3_files_default_context_from_server(): """ Compute simple bestrefs for 3 files using the default context from the server: >>> old_state = test_config.setup() >>> BestrefsScript(argv="bestrefs.py --new-context=hst.pmap --files data/j8bt05njq_raw.fits data/j8bt06o6q_raw.fits data/j8bt09jcq_raw.fits")() CRDS - INFO - No comparison context or source comparison requested. CRDS - INFO - No file header updates requested; dry run. CRDS - INFO - ===> Processing data/j8bt05njq_raw.fits CRDS - INFO - ===> Processing data/j8bt06o6q_raw.fits CRDS - INFO - ===> Processing data/j8bt09jcq_raw.fits CRDS - INFO - 0 errors CRDS - INFO - 0 warnings CRDS - INFO - 5 infos 0 >>> test_config.cleanup(old_state) """ def dt_bestrefs_broken_dataset_file(): """ Same + one broken file to test shell error status >>> old_state = test_config.setup() >>> BestrefsScript(argv="bestrefs.py --new-context hst.pmap --files data/j8bt05njq_raw.fits data/j8bt05njq_raw_broke.fits data/j8bt06o6q_raw.fits data/j8bt09jcq_raw.fits")() CRDS - INFO - No comparison context or source comparison requested. CRDS - INFO - No file header updates requested; dry run. CRDS - INFO - ===> Processing data/j8bt05njq_raw.fits CRDS - INFO - ===> Processing data/j8bt05njq_raw_broke.fits CRDS - ERROR - instrument='ACS' type='BIASFILE' data='data/j8bt05njq_raw_broke.fits' :: New: Bestref FAILED: parameter='CCDAMP' value='FOOBAR' is not in ['A', 'ABCD', 'AC', 'AD', 'B', 'BC', 'BD', 'C', 'D'] CRDS - INFO - ===> Processing data/j8bt06o6q_raw.fits CRDS - INFO - ===> Processing data/j8bt09jcq_raw.fits CRDS - INFO - 1 errors CRDS - INFO - 0 warnings CRDS - INFO - 6 infos 1 >>> test_config.cleanup(old_state) """ def dt_bestrefs_broken_cache_and_server(): """ >>> old_state = test_config.setup(cache="/nowhere", url="https://server-is-out-of-town") >> BestrefsScript(argv="bestrefs.py --new-context hst.pmap --files data/j8bt05njq_raw.fits")() CRDS - ERROR - (FATAL) CRDS server connection and cache load FAILED. Cannot continue. See https://hst-crds.stsci.edu or https://jwst-crds.stsci.edu for more information on configuring CRDS. Traceback (most recent call last): ... SystemExit: 1 >>> test_config.cleanup(old_state) """ def dt_bestrefs_catalog_dataset(): """ Compute simple bestrefs for 1 catalog datasets using hst.pmap: >>> old_state = test_config.setup() >>> BestrefsScript(argv="bestrefs.py --new-context hst.pmap --datasets LB6M01030")() # doctest: +ELLIPSIS CRDS - INFO - Dumping dataset parameters from CRDS server at '...' for ['LB6M01030'] CRDS - INFO - Dumped 1 of 1 datasets from CRDS server at '...' CRDS - INFO - Computing bestrefs for datasets ['LB6M01030'] CRDS - INFO - No comparison context or source comparison requested. CRDS - INFO - 0 errors CRDS - INFO - 0 warnings CRDS - INFO - 4 infos 0 >>> test_config.cleanup(old_state) MAINTENANCE NOTE: the preceding test is currently an expected error case pending the delivery of a modified WFC3 FLSHFILE rmap located at crds/hst/prototypes/wfc3/hst_wfc3_flshfile_0251.rmap. Once the modified rmap is delivered to operations, the above new-context should be changed to the new OPS context. After that point, all mirrors of OPS
<reponame>alexchartier/digital_rf #!python # ---------------------------------------------------------------------------- # Copyright (c) 2017 Massachusetts Institute of Technology (MIT) # All rights reserved. # # Distributed under the terms of the BSD 3-clause license. # # The full license is in the LICENSE file, distributed with this software. # ---------------------------------------------------------------------------- """ drf_plot.py $Id$ Simple program to load 16 bit IQ data and make some basic plots. Command line options are supported and data frames may be filtered from the output. The program can offset into a data file to limit the memory usage when plotting a subset of a data file. """ import calendar import getopt import os import string import sys import time import traceback import digital_rf import matplotlib import matplotlib.pyplot as plt import numpy as np def voltage_process(data, sfreq, toffset, modulus, integration, log_scale, title): """ Break voltages by modulus and display each block. Integration here acts as a pure average on the voltage level data. """ if modulus: block = 0 block_size = integration * modulus block_toffset = toffset while block < len(data) / (block_size): dblock = data[block * block_size : block * block_size + modulus] # complete integration for idx in range(1, integration): dblock += data[ block * block_size + idx * modulus : block * block_size + idx * modulus + modulus ] dblock /= integration yield voltage_plot(dblock, sfreq, block_toffset, log_scale, title) block += 1 block_toffset += block_size / sfreq else: yield voltage_plot(data, sfreq, toffset, log_scale, title) def voltage_plot(data, sfreq, toffset, log_scale, title): """Plot the real and imaginary voltage from IQ data.""" print("voltage") t_axis = np.arange(0, len(data)) / sfreq + toffset fig = plt.figure() ax0 = fig.add_subplot(2, 1, 1) ax0.plot(t_axis, data.real) ax0.grid(True) maxr = np.max(data.real) minr = np.min(data.real) if minr == 0.0 and maxr == 0.0: minr = -1.0 maxr = 1.0 ax0.axis([t_axis[0], t_axis[len(t_axis) - 1], minr, maxr]) ax0.set_ylabel("I sample value (A/D units)") ax1 = fig.add_subplot(2, 1, 2) ax1.plot(t_axis, data.imag) ax1.grid(True) maxi = np.max(data.imag) mini = np.min(data.imag) if mini == 0.0 and maxi == 0.0: mini = -1.0 maxi = 1.0 ax1.axis([t_axis[0], t_axis[len(t_axis) - 1], mini, maxi]) ax1.set_xlabel("time (seconds)") ax1.set_ylabel("Q sample value (A/D units)") ax1.set_title(title) return fig def power_process(data, sfreq, toffset, modulus, integration, log_scale, zscale, title): """ Break power by modulus and display each block. Integration here acts as a pure average on the power level data. """ if modulus: block = 0 block_size = integration * modulus block_toffset = toffset while block < len(data) / block_size: vblock = data[block * block_size : block * block_size + modulus] pblock = (vblock * np.conjugate(vblock)).real # complete integration for idx in range(1, integration): vblock = data[ block * block_size + idx * modulus : block * block_size + idx * modulus + modulus ] pblock += (vblock * np.conjugate(vblock)).real pblock /= integration yield power_plot(pblock, sfreq, block_toffset, log_scale, zscale, title) block += 1 block_toffset += block_size / sfreq else: pdata = (data * np.conjugate(data)).real yield power_plot(pdata, sfreq, toffset, log_scale, zscale, title) def power_plot(data, sfreq, toffset, log_scale, zscale, title): """Plot the computed power of the iq data.""" print("power") t_axis = np.arange(0, len(data)) / sfreq + toffset if log_scale: lrxpwr = 10 * np.log10(data + 1e-12) else: lrxpwr = data zscale_low, zscale_high = zscale if zscale_low == 0 and zscale_high == 0: if log_scale: zscale_low = np.min(lrxpwr[np.where(lrxpwr.real != -np.Inf)]) zscale_high = np.max(lrxpwr) + 3.0 else: zscale_low = np.min(lrxpwr) zscale_high = np.max(lrxpwr) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.plot(t_axis, lrxpwr.real) ax.grid(True) ax.axis([toffset, t_axis[len(t_axis) - 1], zscale_low, zscale_high]) ax.set_xlabel("time (seconds)") if log_scale: ax.set_ylabel("power (dB)") else: ax.set_ylabel("power") ax.set_title(title) return fig def iq_process(data, sfreq, toffset, modulus, integration, log_scale, title): """ Break voltages by modulus and display each block. Integration here acts as a pure average on the voltage level data prior to iq plotting. """ if modulus: block = 0 block_size = integration * modulus block_toffset = toffset while block < len(data) / block_size: dblock = data[block * block_size : block * block_size + modulus] # complete integration for idx in range(1, integration): dblock += data[ block * block_size + idx * modulus : block * block_size + idx * modulus + modulus ] dblock /= integration yield iq_plot(dblock, block_toffset, log_scale, title) block += 1 block_toffset += block_size / sfreq else: yield iq_plot(data, toffset, log_scale, title) def iq_plot(data, toffset, log_scale, title): """Plot an IQ circle from the data in linear or log scale.""" print("iq") if log_scale: rx_raster_r = ( np.sign(data.real) * np.log10(np.abs(data.real) + 1e-30) / np.log10(2.0) ) rx_raster_i = ( np.sign(data.imag) * np.log10(np.abs(data.imag) + 1e-30) / np.log10(2.0) ) else: data *= 1.0 / 32768.0 rx_raster_r = data.real rx_raster_i = data.imag fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.plot(rx_raster_r, rx_raster_i, ".") axmx = np.max([np.max(rx_raster_r), np.max(rx_raster_i)]) ax.axis([-axmx, axmx, -axmx, axmx]) ax.grid(True) ax.set_xlabel("I") ax.set_ylabel("Q") ax.set_title(title) return fig def phase_process(data, sfreq, toffset, modulus, integration, log_scale, title): """ Break voltages by modulus and display the phase of each block. Integration here acts as a pure average on the voltage level data prior to iq plotting. """ if modulus: block = 0 block_size = integration * modulus block_toffset = toffset while block < len(data) / block_size: dblock = data[block * block_size : block * block_size + modulus] # complete integration for idx in range(1, integration): dblock += data[ block * block_size + idx * modulus : block * block_size + idx * modulus + modulus ] dblock /= integration yield phase_plot(dblock, block_toffset, log_scale, title) block += 1 block_toffset += block_size / sfreq else: yield phase_plot(data, toffset, log_scale, title) def phase_plot(data, toffset, log_scale, title): """Plot the phase of the data in linear or log scale.""" print("phase") phase = np.angle(data) / np.pi fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.plot(phase) # ax.axis([-axmx, axmx, -axmx, axmx]) ax.grid(True) ax.set_xlabel("time") ax.set_ylabel("phase") ax.set_title(title) return fig def spectrum_process( data, sfreq, cfreq, toffset, modulus, integration, bins, log_scale, zscale, detrend, title, clr, ): """ Break spectrum by modulus and display each block. Integration here acts as a pure average on the spectral data. """ if detrend: dfn = matplotlib.mlab.detrend_mean else: dfn = matplotlib.mlab.detrend_none win = np.blackman(bins) if modulus: block = 0 block_size = integration * modulus block_toffset = toffset while block < len(data) / block_size: vblock = data[block * block_size : block * block_size + modulus] pblock, freq = matplotlib.mlab.psd( vblock, NFFT=bins, Fs=sfreq, detrend=dfn, window=win, scale_by_freq=False, ) # complete integration for idx in range(1, integration): vblock = data[ block * block_size + idx * modulus : block * block_size + idx * modulus + modulus ] pblock_n, freq = matplotlib.mlab.psd( vblock, NFFT=bins, Fs=sfreq, detrend=dfn, window=matplotlib.mlab.window_hanning, scale_by_freq=False, ) pblock += pblock_n pblock /= integration yield spectrum_plot( pblock, freq, cfreq, block_toffset, log_scale, zscale, title, clr ) block += 1 block_toffset += block_size / sfreq else: pdata, freq = matplotlib.mlab.psd( data, NFFT=bins, Fs=sfreq, detrend=dfn, window=win, scale_by_freq=False ) yield spectrum_plot(pdata, freq, cfreq, toffset, log_scale, zscale, title, clr) def spectrum_plot(data, freq, cfreq, toffset, log_scale, zscale, title, clr): """Plot a spectrum from the data for a given fft bin size.""" print("spectrum") tail_str = "" if log_scale: # pss = 10.0*np.log10(data / np.max(data)) pss = 10.0 * np.log10(data + 1e-12) tail_str = " (dB)" else: pss = data print(freq) freq_s = freq / 1.0e6 + cfreq / 1.0e6 print(freq_s) zscale_low, zscale_high = zscale if zscale_low == 0 and zscale_high == 0: if log_scale: zscale_low = np.median(np.min(pss[np.where(pss.real != -np.Inf)])) - 3.0 zscale_high = np.median(np.max(pss)) + 3.0 else: zscale_low = np.median(np.min(pss)) zscale_high = np.median(np.max(pss)) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.plot(freq_s, pss, clr) print(freq_s[0], freq_s[-1], zscale_low, zscale_high) ax.axis([freq_s[0], freq_s[-1], zscale_low, zscale_high]) ax.grid(True) ax.set_xlabel("frequency (MHz)") ax.set_ylabel("power spectral density" + tail_str, fontsize=12) ax.set_title(title) return fig def histogram_process( data, sfreq, toffset, modulus, integration, bins, log_scale, title ): """ Break voltages by modulus and display each block. Integration here acts as a pure average on the voltage level data prior to the histogram. """ if modulus: block = 0 block_size = integration * modulus block_toffset = toffset while block < len(data) / block_size: dblock = data[block * block_size : block * block_size + modulus] # complete integration for idx in range(1, integration): dblock += data[ block * block_size + idx * modulus : block * block_size + idx
import pandas as pd import numpy as np import dash import dash_core_components as dcc import dash_html_components as html import dash_table as dt from dash.dependencies import Input, Output, State import plotly.graph_objects as go import plotly.express as px import datetime external_stylesheets = ['https://codepen.io/unicorndy/pen/GRJXrvP.css','https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css'] app = dash.Dash(__name__, external_stylesheets=external_stylesheets) app.title = 'Covid - 19 Dashboard' server = app.server colors = { 'background': '#2D2D2D', 'text': '#E1E2E5', 'figure_text': '#ffffff', 'confirmed_text':'#3CA4FF', 'deaths_text':'#f44336', 'recovered_text':'#81FF33', 'active_text':'#f1f772', 'highest_case_bg':'#393939', } divBorderStyle = { 'backgroundColor' : '#393939', 'borderRadius': '12px', 'lineHeight': 0.9, } boxBorderStyle = { 'borderColor' : '#393939', 'borderStyle': 'solid', 'borderRadius': '10px', 'borderWidth':2, } url_confirmed = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv' url_deaths = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv' url_recovered = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_recovered_global.csv' df_confirmed = pd.read_csv(url_confirmed) df_deaths = pd.read_csv(url_deaths) df_recovered = pd.read_csv(url_recovered) def df_move1st_sg(df_t): df_t["new"] = range(1,len(df_t)+1) df_t.loc[df_t[df_t['Country/Region'] == 'India'].index.values,'new'] = 0 df_t = df_t.sort_values("new").drop('new', axis=1) return df_t ######## Data Pre-processing ############### # Total cases df_confirmed_total = df_confirmed.iloc[:, 4:].sum(axis=0) df_deaths_total = df_deaths.iloc[:, 4:].sum(axis=0) df_recovered_total = df_recovered.iloc[:, 4:].sum(axis=0) # modified deaths dataset for mortality rate calculation df_deaths_confirmed=df_deaths.copy() df_deaths_confirmed['confirmed'] = df_confirmed.iloc[:,-1] #Sorted - df_deaths_confirmed_sorted is different from others, as it is only modified later. Careful of it dataframe structure df_deaths_confirmed_sorted = df_deaths_confirmed.sort_values(by=df_deaths_confirmed.columns[-2], ascending=False)[['Country/Region',df_deaths_confirmed.columns[-2],df_deaths_confirmed.columns[-1]]] df_recovered_sorted = df_recovered.sort_values(by=df_recovered.columns[-1], ascending=False)[['Country/Region',df_recovered.columns[-1]]] df_confirmed_sorted = df_confirmed.sort_values(by=df_confirmed.columns[-1], ascending=False)[['Country/Region',df_confirmed.columns[-1]]] #Single day increase df_deaths_confirmed_sorted['24hr'] = df_deaths_confirmed_sorted.iloc[:,-2] - df_deaths.sort_values(by=df_deaths.columns[-1], ascending=False)[df_deaths.columns[-2]] df_recovered_sorted['24hr'] = df_recovered_sorted.iloc[:,-1] - df_recovered.sort_values(by=df_recovered.columns[-1], ascending=False)[df_recovered.columns[-2]] df_confirmed_sorted['24hr'] = df_confirmed_sorted.iloc[:,-1] - df_confirmed.sort_values(by=df_confirmed.columns[-1], ascending=False)[df_confirmed.columns[-2]] #Aggregate the countries with different province/state together df_deaths_confirmed_sorted_total = df_deaths_confirmed_sorted.groupby('Country/Region').sum() df_deaths_confirmed_sorted_total=df_deaths_confirmed_sorted_total.sort_values(by=df_deaths_confirmed_sorted_total.columns[0], ascending=False).reset_index() df_recovered_sorted_total = df_recovered_sorted.groupby('Country/Region').sum() df_recovered_sorted_total=df_recovered_sorted_total.sort_values(by=df_recovered_sorted_total.columns[0], ascending=False).reset_index() df_confirmed_sorted_total = df_confirmed_sorted.groupby('Country/Region').sum() df_confirmed_sorted_total=df_confirmed_sorted_total.sort_values(by=df_confirmed_sorted_total.columns[0], ascending=False).reset_index() #Modified recovery csv due to difference in number of rows. Recovered will match ['Province/State','Country/Region']column with Confirmed ['Province/State','Country/Region'] df_recovered['Province+Country'] = df_recovered[['Province/State','Country/Region']].fillna('nann').agg('|'.join,axis=1) df_confirmed['Province+Country'] = df_confirmed[['Province/State','Country/Region']].fillna('nann').agg('|'.join,axis=1) df_recovered_fill = df_recovered df_recovered_fill.set_index("Province+Country") df_recovered_fill.set_index("Province+Country").reindex(df_confirmed['Province+Country']) df_recovered_fill = df_recovered_fill.set_index("Province+Country").reindex(df_confirmed['Province+Country']).reset_index() #split Province+Country back into its respective columns new = df_recovered_fill["Province+Country"].str.split("|", n = 1, expand = True) df_recovered_fill['Province/State']=new[0] df_recovered_fill['Country/Region']=new[1] df_recovered_fill['Province/State'].replace('nann','NaN') #drop 'Province+Country' for all dataset df_confirmed.drop('Province+Country',axis=1,inplace=True) df_recovered.drop('Province+Country',axis=1,inplace=True) df_recovered_fill.drop('Province+Country',axis=1,inplace=True) # Data preprocessing for times series countries graph display # create temp to store sorting arrangement for all confirm, deaths and recovered. df_confirmed_sort_temp = df_confirmed.sort_values(by=df_confirmed.columns[-1], ascending=False) df_confirmed_t = df_move1st_sg(df_confirmed_sort_temp) df_confirmed_t['Province+Country'] = df_confirmed_t[['Province/State','Country/Region']].fillna('nann').agg('|'.join,axis=1) df_confirmed_t=df_confirmed_t.drop(['Province/State','Country/Region','Lat','Long'],axis=1).T df_deaths_t = df_deaths.reindex(df_confirmed_sort_temp.index) df_deaths_t = df_move1st_sg(df_deaths_t) df_deaths_t['Province+Country'] = df_deaths_t[['Province/State','Country/Region']].fillna('nann').agg('|'.join,axis=1) df_deaths_t=df_deaths_t.drop(['Province/State','Country/Region','Lat','Long'],axis=1).T # take note use reovered_fill df df_recovered_t = df_recovered_fill.reindex(df_confirmed_sort_temp.index) df_recovered_t = df_move1st_sg(df_recovered_t) df_recovered_t['Province+Country'] = df_recovered_t[['Province/State','Country/Region']].fillna('nann').agg('|'.join,axis=1) df_recovered_t=df_recovered_t.drop(['Province/State','Country/Region','Lat','Long'],axis=1).T df_confirmed_t.columns = df_confirmed_t.iloc[-1] df_confirmed_t = df_confirmed_t.drop('Province+Country') df_deaths_t.columns = df_deaths_t.iloc[-1] df_deaths_t = df_deaths_t.drop('Province+Country') df_recovered_t.columns = df_recovered_t.iloc[-1] df_recovered_t = df_recovered_t.drop('Province+Country') df_confirmed_t.index=pd.to_datetime(df_confirmed_t.index) df_deaths_t.index=pd.to_datetime(df_confirmed_t.index) df_recovered_t.index=pd.to_datetime(df_confirmed_t.index) df_active_t = df_confirmed_t.subtract(df_deaths_t.add(df_recovered_t)) df_active_t.clip(lower=0,inplace=True) # Highest 10 plot data preprocessing # getting highest 10 countries with confirmed case name = df_confirmed_t.columns.str.split("|", 1) df_confirmed_t_namechange=df_confirmed_t.copy() name0 = [x[0] for x in name] name1 = [x[1] for x in name] df_confirmed_t_namechange.columns = name1 df_confirmed_t_namechange=df_confirmed_t_namechange.groupby(df_confirmed_t_namechange.columns,axis=1).sum() df_confirmed_t_namechange10 = df_confirmed_t_namechange.sort_values(by=df_confirmed_t_namechange.index[-1], axis=1, ascending=False).iloc[:,:10] df_confirmed_t_stack = df_confirmed_t_namechange10.stack() df_confirmed_t_stack=df_confirmed_t_stack.reset_index(level=[0,1]) df_confirmed_t_stack.rename(columns={"level_0": "Date",'level_1':'Countries', 0: "Confirmed"}, inplace=True) # getting highest 10 countries with deceased case name = df_deaths_t.columns.str.split("|", 1) df_deaths_t_namechange=df_deaths_t.copy() # name0 = [x[0] for x in name] name1 = [x[1] for x in name] df_deaths_t_namechange.columns = name1 df_deaths_t_namechange=df_deaths_t_namechange.groupby(df_deaths_t_namechange.columns,axis=1).sum() df_deaths_t_namechange10 = df_deaths_t_namechange.sort_values(by=df_deaths_t_namechange.index[-1], axis=1, ascending=False).iloc[:,:10] df_deaths_t_stack = df_deaths_t_namechange10.stack() df_deaths_t_stack=df_deaths_t_stack.reset_index(level=[0,1]) df_deaths_t_stack.rename(columns={"level_0": "Date",'level_1':'Countries', 0: "Deceased"}, inplace=True) # Recreate required columns for map data map_data = df_confirmed[["Province/State", "Country/Region", "Lat", "Long"]] map_data['Confirmed'] = df_confirmed.loc[:, df_confirmed.columns[-1]] map_data['Deaths'] = df_deaths.loc[:, df_deaths.columns[-1]] map_data['Recovered'] = df_recovered_fill.loc[:, df_recovered_fill.columns[-1]] map_data['Recovered']=map_data['Recovered'].fillna(0).astype(int) map_data['Active'] = map_data['Confirmed'] - (map_data['Deaths'] + map_data['Recovered']) map_data['Active'].clip(lower=0,inplace=True) #last 24 hours increase map_data['Deaths_24hr']=df_deaths.iloc[:,-1] - df_deaths.iloc[:,-2] map_data['Recovered_24hr']=df_recovered_fill.iloc[:,-1] - df_recovered_fill.iloc[:,-2] map_data['Confirmed_24hr']=df_confirmed.iloc[:,-1] - df_confirmed.iloc[:,-2] map_data['Active_24hr'] = map_data['Confirmed_24hr'] - (map_data['Deaths_24hr'] + map_data['Recovered_24hr']) map_data['Active_24hr'].clip(lower=0,inplace=True) map_data.sort_values(by='Confirmed', ascending=False,inplace=True) map_data["new"] = range(1,len(map_data)+1) map_data.loc[map_data[map_data['Country/Region'] == 'India'].index.values,'new'] = 0 map_data = map_data.sort_values("new").drop('new', axis=1) ############################################################################# # mapbox_access_token keys, not all mapbox function require token to function. ############################################################################# mapbox_access_token = '' # enter mapbox access token here ########################### # functions to create map ########################### def gen_map(map_data,zoom,lat,lon,map_disp_type="confirmed"): if map_disp_type=="confirmed": return { "data": [{ "type": "scattermapbox", #specify the type of data to generate, in this case, scatter map box is used "lat": list(map_data['Lat']), #for markers location "lon": list(map_data['Long']), # "hoverinfo": "text", "hovertext": [["Country/Region: {} <br>Province/State: {} <br>Active: {} (+ {} past 24hrs)<br>Confirmed: {} (+ {} past 24hrs)<br>Deaths: {} (+ {} past 24hrs)<br>Recovered: {} (+ {} past 24hrs)".format(i, j, k, k24, l, l24, m, m24, n, n24)] for i, j, k, l, m, n, k24, l24, m24, n24 in zip(map_data['Country/Region'], map_data['Province/State'], map_data['Active'], map_data['Confirmed'], map_data['Deaths'], map_data['Recovered'], map_data['Active_24hr'],map_data['Confirmed_24hr'], map_data['Deaths_24hr'], map_data['Recovered_24hr'],)], "mode": "markers", "name": list(map_data['Country/Region']), "marker": { "opacity": 0.5, "size": np.log(map_data['Confirmed']), } }, ], "layout": dict( autosize=True, height=350, font=dict(color=colors['figure_text']), titlefont=dict(color=colors['text'], size='14'), margin=dict( l=0, r=0, b=0, t=0 ), hovermode="closest", plot_bgcolor=colors['background'], paper_bgcolor=colors['background'], legend=dict(font=dict(size=10), orientation='h'), mapbox=dict( accesstoken=mapbox_access_token, style='mapbox://styles/mapbox/dark-v10', center=dict( lon=lon, lat=lat, ), zoom=zoom, ) ), } elif map_disp_type=="active": return { "data": [{ "type": "scattermapbox", #specify the type of data to generate, in this case, scatter map box is used "lat": list(map_data['Lat']), #for markers location "lon": list(map_data['Long']), # "hoverinfo": "text", "hovertext": [["Country/Region: {} <br>Province/State: {} <br>Active: {} (+ {} past 24hrs)<br>Confirmed: {} (+ {} past 24hrs)<br>Deaths: {} (+ {} past 24hrs)<br>Recovered: {} (+ {} past 24hrs)".format(i, j, k, k24, l, l24, m, m24, n, n24)] for i, j, k, l, m, n, k24, l24, m24, n24 in zip(map_data['Country/Region'], map_data['Province/State'], map_data['Active'], map_data['Confirmed'], map_data['Deaths'], map_data['Recovered'], map_data['Active_24hr'],map_data['Confirmed_24hr'], map_data['Deaths_24hr'], map_data['Recovered_24hr'],)], "mode": "markers", "name": list(map_data['Country/Region']), "marker": { "opacity": 0.5, "size": np.log(map_data['Deaths']), "color":"#f1f772", } }, ], "layout": dict( autosize=True, height=350, font=dict(color=colors['figure_text']), titlefont=dict(color=colors['text'], size='14'), margin=dict( l=0, r=0, b=0, t=0 ), hovermode="closest", plot_bgcolor=colors['background'], paper_bgcolor=colors['background'], legend=dict(font=dict(size=10), orientation='h'), mapbox=dict( accesstoken=mapbox_access_token, style='mapbox://styles/mapbox/dark-v10', center=dict( lon=lon, lat=lat, ), zoom=zoom, ) ), } elif map_disp_type=="deaths": return { "data": [{ "type": "scattermapbox", #specify the type of data to generate, in this case, scatter map box is used "lat": list(map_data['Lat']), #for markers location "lon": list(map_data['Long']), # "hoverinfo": "text", "hovertext": [["Country/Region: {} <br>Province/State: {} <br>Active: {} (+ {} past 24hrs)<br>Confirmed: {} (+ {} past 24hrs)<br>Deaths: {} (+ {} past 24hrs)<br>Recovered: {} (+ {} past 24hrs)".format(i, j, k, k24, l, l24, m, m24, n, n24)] for i, j, k, l, m, n, k24, l24, m24, n24 in zip(map_data['Country/Region'], map_data['Province/State'], map_data['Active'], map_data['Confirmed'], map_data['Deaths'], map_data['Recovered'], map_data['Active_24hr'],map_data['Confirmed_24hr'], map_data['Deaths_24hr'], map_data['Recovered_24hr'],)], "mode": "markers", "name": list(map_data['Country/Region']), "marker": { "opacity": 0.5, "size": np.log(map_data['Deaths']), "color":"red", } }, ], "layout": dict( autosize=True, height=350, font=dict(color=colors['figure_text']), titlefont=dict(color=colors['text'], size='14'), margin=dict( l=0, r=0, b=0, t=0 ), hovermode="closest", plot_bgcolor=colors['background'], paper_bgcolor=colors['background'], legend=dict(font=dict(size=10), orientation='h'), mapbox=dict( accesstoken=mapbox_access_token, style='mapbox://styles/mapbox/dark-v10', center=dict( lon=lon, lat=lat, ), zoom=zoom, ) ), } else: return { "data": [{ "type": "scattermapbox", #specify the type of data to generate, in this case, scatter map box is used "lat": list(map_data['Lat']), #for markers location "lon": list(map_data['Long']), # "hoverinfo": "text", "hovertext": [["Country/Region: {} <br>Province/State: {} <br>Active: {} (+ {} past 24hrs)<br>Confirmed: {} (+ {} past 24hrs)<br>Deaths: {} (+ {} past 24hrs)<br>Recovered: {} (+ {} past 24hrs)".format(i, j, k, k24, l, l24, m, m24, n, n24)] for i, j, k, l, m, n, k24, l24, m24, n24 in zip(map_data['Country/Region'], map_data['Province/State'], map_data['Active'], map_data['Confirmed'], map_data['Deaths'], map_data['Recovered'], map_data['Active_24hr'],map_data['Confirmed_24hr'], map_data['Deaths_24hr'], map_data['Recovered_24hr'],)], "mode": "markers", "name": list(map_data['Country/Region']), "marker": { "opacity": 0.5, "size": np.log(map_data['Recovered']), "color":"#81FF33", } }, ], "layout": dict( autosize=True, height=350, font=dict(color=colors['figure_text']), titlefont=dict(color=colors['text'], size='14'), margin=dict( l=0, r=0, b=0, t=0 ), hovermode="closest", plot_bgcolor=colors['background'], paper_bgcolor=colors['background'], legend=dict(font=dict(size=10), orientation='h'), mapbox=dict( accesstoken=mapbox_access_token, style='mapbox://styles/mapbox/dark-v10', center=dict( lon=lon, lat=lat, ), zoom=zoom, ) ), } ############################################## #Functions to create display for highest cases ############################################## def high_cases(countryname,total,single,color_word='#63b6ff',confirmed_total=1,deaths = False,): if deaths: percent = (total/confirmed_total)*100 return html.P([ html.Span(countryname + ' | ' + f"{int(total):,d}", style={'backgroundColor': colors['highest_case_bg'], 'borderRadius': '6px',}), html.Span(' +' + f"{int(single):,d}", style={'color': color_word,'margin':2,'fontWeight': 'bold','fontSize': 14,}), html.Span(f' ({percent:.2f}%)', style={'color': color_word,'margin':2,'fontWeight': 'bold','fontSize': 14,}), ], style={ 'textAlign': 'center', 'color': 'rgb(200,200,200)', 'fontsize':12, } ) return html.P([ html.Span(countryname + ' | ' + f"{int(total):,d}", style={'backgroundColor': colors['highest_case_bg'], 'borderRadius': '6px',}), html.Span(' +' + f"{int(single):,d}", style={'color': color_word,'margin':2,'fontWeight': 'bold','fontSize': 14,}), ], style={ 'textAlign': 'center', 'color': 'rgb(200,200,200)', 'fontsize':12, } ) ######################################################################### #Convert datetime to Display datetime with following format - 06-Apr-2020 ######################################################################### def datatime_convert(date_str,days_to_add=0): format_str = '%m/%d/%y' # The format datetime_obj = datetime.datetime.strptime(date_str, format_str) datetime_obj += datetime.timedelta(days=days_to_add) return datetime_obj.strftime('%d-%b-%Y') def return_outbreakdays(date_str): format_str = '%d-%b-%Y' # The format datetime_obj = datetime.datetime.strptime(date_str, format_str).date() d0 = datetime.date(2020, 1, 22) delta = datetime_obj - d0 return delta.days noToDisplay = 8 confirm_cases = [] for i in range(noToDisplay): confirm_cases.append(high_cases(df_confirmed_sorted_total.iloc[i,0],df_confirmed_sorted_total.iloc[i,1],df_confirmed_sorted_total.iloc[i,2])) deaths_cases = [] for i in range(noToDisplay): deaths_cases.append(high_cases(df_deaths_confirmed_sorted_total.iloc[i,0],df_deaths_confirmed_sorted_total.iloc[i,1],df_deaths_confirmed_sorted_total.iloc[i,3],'#ff3b4a',df_deaths_confirmed_sorted_total.iloc[i,2],True)) confirm_cases_24hrs = [] for i in range(noToDisplay): confirm_cases_24hrs.append(high_cases(df_confirmed_sorted_total.sort_values(by=df_confirmed_sorted_total.columns[-1], ascending=False).iloc[i,0], df_confirmed_sorted_total.sort_values(by=df_confirmed_sorted_total.columns[-1], ascending=False).iloc[i,1], df_confirmed_sorted_total.sort_values(by=df_confirmed_sorted_total.columns[-1], ascending=False).iloc[i,2], )) deaths_cases_24hrs = [] for i in range(noToDisplay): deaths_cases_24hrs.append(high_cases(df_deaths_confirmed_sorted_total.sort_values(by=df_deaths_confirmed_sorted_total.columns[-1], ascending=False).iloc[i,0], df_deaths_confirmed_sorted_total.sort_values(by=df_deaths_confirmed_sorted_total.columns[-1], ascending=False).iloc[i,1], df_deaths_confirmed_sorted_total.sort_values(by=df_deaths_confirmed_sorted_total.columns[-1], ascending=False).iloc[i,3], '#ff3b4a', df_deaths_confirmed_sorted_total.sort_values(by=df_deaths_confirmed_sorted_total.columns[-1], ascending=False).iloc[i,2], True)) #################################################### # Prepare plotly figure to attached to dcc component # Global outbreak Plot #################################################### # Change date index to datetimeindex and share x-axis with all the plot def draw_global_graph(df_confirmed_total,df_deaths_total,df_recovered_total,graph_type='Total Cases'): df_confirmed_total.index = pd.to_datetime(df_confirmed_total.index) if graph_type == 'Daily Cases': df_confirmed_total = (df_confirmed_total - df_confirmed_total.shift(1)).drop(df_confirmed_total.index[0]) df_deaths_total = (df_deaths_total - df_deaths_total.shift(1)).drop(df_deaths_total.index[0]) df_recovered_total = (df_recovered_total - df_recovered_total.shift(1)).drop(df_recovered_total.index[0]) fig = go.Figure() fig.add_trace(go.Scatter(x=df_confirmed_total.index, y=df_confirmed_total, mode='lines+markers', name='Confirmed', line=dict(color='#3372FF', width=2), fill='tozeroy',)) fig.add_trace(go.Scatter(x=df_confirmed_total.index, y=df_recovered_total, mode='lines+markers', name='Recovered', line=dict(color='#33FF51', width=2), fill='tozeroy',)) fig.add_trace(go.Scatter(x=df_confirmed_total.index, y=df_deaths_total, mode='lines+markers', name='Deaths', line=dict(color='#FF3333', width=2), fill='tozeroy',)) fig.update_layout( hovermode='x', font=dict( family="Courier New, monospace", size=14, color=colors['figure_text'], ), legend=dict( x=0.02, y=1, traceorder="normal", font=dict( family="sans-serif", size=12, color=colors['figure_text'] ), bgcolor=colors['background'], borderwidth=5 ), paper_bgcolor=colors['background'], plot_bgcolor=colors['background'], margin=dict(l=0, r=0, t=0, b=0 ), height=300, ) fig.update_xaxes(showgrid=True, gridwidth=1, gridcolor='#3A3A3A') fig.update_yaxes(showgrid=True, gridwidth=1, gridcolor='#3A3A3A') fig.update_yaxes(zeroline=True, zerolinewidth=2, zerolinecolor='#3A3A3A') return fig #################################################### # Function to plot Highest 10 countries cases #################################################### def draw_highest_10(df_confirmed_t_stack, df_deaths_t_stack, graphHigh10_type='Confirmed Cases'): if graphHigh10_type=='Confirmed Cases': fig = px.line(df_confirmed_t_stack, x="Date", y="Confirmed", color='Countries', color_discrete_sequence = px.colors.qualitative.Light24) else: fig =
<filename>evoMPS/tdvp_gen.py # -*- coding: utf-8 -*- """ Created on Thu Oct 13 17:29:27 2011 @author: <NAME> TODO: - Adaptive step size. """ from __future__ import absolute_import, division, print_function import copy as cp import scipy as sp import scipy.linalg as la import scipy.optimize as opti import scipy.sparse.linalg as las from . import matmul as m from . import tdvp_common as tm from .mps_gen import EvoMPS_MPS_Generic import logging log = logging.getLogger(__name__) class Vari_Opt_Single_Site_Op: def __init__(self, tdvp, n, KLnm1, tau=1., HML=None, HMR=None, HMn=None, use_local_ham=True, sanity_checks=False): """ """ self.D = tdvp.D self.q = tdvp.q self.tdvp = tdvp self.n = n self.KLnm1 = KLnm1 self.HML = HML self.HMR = HMR self.HMn = HMn self.sanity_checks = sanity_checks self.sanity_tol = 1E-12 d = self.D[n - 1] * self.D[n] * self.q[n] self.shape = (d, d) self.dtype = sp.dtype(tdvp.typ) self.calls = 0 self.tau = tau self.ham_local = use_local_ham self.ham_MPO = not HMn is None def apply_ham_local(self, An, res): t = self.tdvp n = self.n #Assuming RCF if t.ham_sites == 2: if n > 1: AAnm1 = tm.calc_AA(t.A[n - 1], An) Cnm1 = tm.calc_C_mat_op_AA(t.ham[n - 1], AAnm1) Cnm1 = sp.transpose(Cnm1, axes=(1, 0, 2, 3)).copy() for s in range(t.q[n]): res[s] += tm.eps_l_noop(t.l[n - 2], t.A[n - 1], Cnm1[s, :]) if n < t.N: AAn = tm.calc_AA(An, t.A[n + 1]) Cn = tm.calc_C_mat_op_AA(t.ham[n], AAn) for s in range(t.q[n]): res[s] += tm.eps_r_noop(t.r[n + 1], Cn[s, :], t.A[n + 1]) if t.ham_sites == 3: if n > 2: AAAnm2 = tm.calc_AAA_AA(t.AA[n - 2], An) Cnm2 = tm.calc_C_3s_mat_op_AAA(t.ham[n - 2], AAAnm2) Cnm2 = sp.transpose(Cnm2, axes=(2, 0, 1, 3, 4)).copy() for s in range(t.q[n]): res[s] += tm.eps_l_op_2s_AA12_C34(t.l[n - 3], t.AA[n - 2], Cnm2[s, :, :]) if n > 1 and n < t.N: AAnm1 = tm.calc_AA(t.A[n - 1], An) AAAnm1 = tm.calc_AAA_AA(AAnm1, t.A[n + 1]) Cnm1 = tm.calc_C_3s_mat_op_AAA(t.ham[n - 1], AAAnm1) for s in range(t.q[n]): for u in range(t.q[n - 1]): res[s] += t.A[n - 1][u].conj().T.dot(t.l[n - 2].dot( tm.eps_r_noop(t.r[n + 1], Cnm1[u, s, :], t.A[n + 1]))) if n < t.N - 1: AAn = tm.calc_AA(An, t.A[n + 1]) AAAn = tm.calc_AAA_AA(AAn, t.A[n + 2]) Cn = tm.calc_C_3s_mat_op_AAA(t.ham[n], AAAn) for s in range(t.q[n]): res[s] += tm.eps_r_op_2s_AA12_C34(t.r[n + 2], Cn[s, :, :], t.AA[n + 1]) if n > 1: for s in range(t.q[n]): res[s] += self.KLnm1.dot(An[s]) if n < t.N: for s in range(t.q[n]): res[s] += An[s].dot(t.K[n + 1]) def apply_ham_MPO(self, An, res): t = self.tdvp n = self.n HMAn = tm.apply_MPO_local(self.HMn, An) #print self.HML.shape, HMAn[0].shape, self.HMR.shape, An[0].shape for s in range(t.q[n]): res[s] += self.HML.conj().T.dot(HMAn[s]).dot(self.HMR) def matvec(self, x): self.calls += 1 #print self.calls n = self.n #x = sp.asarray(x, dtype=self.dtype) #ensure the type is right! An = x.reshape((self.q[n], self.D[n - 1], self.D[n])) res = sp.zeros_like(An) if self.ham_local: self.apply_ham_local(An, res) if self.ham_MPO: self.apply_ham_MPO(An, res) #print "en = ", (sp.inner(An.conj().ravel(), res.ravel()) # / sp.inner(An.conj().ravel(), An.ravel())) return res.reshape(x.shape) * self.tau class Vari_Opt_SC_op: def __init__(self, tdvp, n, KLn, tau=1, HML=None, HMR=None, use_local_ham=True, sanity_checks=False): """ """ self.D = tdvp.D self.q = tdvp.q self.tdvp = tdvp self.n = n self.KLn = KLn self.HML = HML self.HMR = HMR self.sanity_checks = sanity_checks self.sanity_tol = 1E-12 d = self.D[n] * self.D[n] self.shape = (d, d) self.dtype = sp.dtype(tdvp.typ) self.calls = 0 self.tau = tau self.ham_local = use_local_ham self.ham_MPO = not HML is None def apply_ham_MPO(self, Gn, res): HMGn = sp.kron(Gn, sp.eye(self.HMR.shape[0] // self.D[self.n])) res += self.HML.conj().T.dot(HMGn).dot(self.HMR) def apply_ham_local(self, Gn, res): t = self.tdvp n = self.n res += self.KLn.dot(Gn) + Gn.dot(t.K[n + 1]) Ap1 = sp.array([Gn.dot(As) for As in t.A[n + 1]]) if t.ham_sites == 2: AAn = tm.calc_AA(t.A[n], Ap1) Cn = tm.calc_C_mat_op_AA(t.ham[n], AAn) for s in range(t.q[n]): sres = tm.eps_r_noop(t.r[n + 1], Cn[s, :], t.A[n + 1]) res += t.A[n][s].conj().T.dot(t.l[n - 1].dot(sres)) elif t.ham_sites == 3: if n < t.N - 1: AAn = tm.calc_AA(t.A[n], Ap1) AAAn = tm.calc_AAA_AA(AAn, t.A[n + 2]) Cn = tm.calc_C_3s_mat_op_AAA(t.ham[n], AAAn) for s in range(t.q[n]): res += t.A[n][s].conj().T.dot( tm.eps_r_op_2s_AA12_C34(t.r[n + 2], Cn[s, :, :], t.AA[n + 1])) if n > 1: AAAm1 = tm.calc_AAA_AA(t.AA[n - 1], Ap1) Cm1 = tm.calc_C_3s_mat_op_AAA(t.ham[n - 1], AAAm1) Cm1 = sp.transpose(Cm1, axes=(2, 0, 1, 3, 4)).copy() for s in range(t.q[n + 1]): res += tm.eps_l_op_2s_AA12_C34(t.l[n - 2], t.AA[n - 1], Cm1[s, :, :]).dot(t.A[n + 1][s].conj().T) def matvec(self, x): self.calls += 1 #print self.calls n = self.n Gn = x.reshape((self.D[n], self.D[n])) res = sp.zeros_like(Gn) if self.ham_local: self.apply_ham_local(Gn, res) if self.ham_MPO: self.apply_ham_MPO(Gn, res) return res.reshape(x.shape) * self.tau class EvoMPS_TDVP_Generic(EvoMPS_MPS_Generic): def __init__(self, N, D, q, ham, ham_sites=None): """Creates a new EvoMPS_TDVP_Generic object. This class implements the time-dependent variational principle (TDVP) for matrix product states (MPS) of a finite spin chain with open boundary conditions. It is derived from EvoMPS_MPS_Generic, which implements basic operations on the state, adding the ability to integrate the TDVP flow equations given a nearest-neighbour Hamiltonian. Performs EvoMPS_MPS_Generic.__init__(). Sites are numbered 1 to N. self.A[n] is the parameter tensor for site n with shape == (q[n], D[n - 1], D[n]). Parameters ---------- N : int The number of lattice sites. D : ndarray A 1d array, length N + 1, of integers indicating the desired bond dimensions. q : ndarray A 1d array, length N + 1, of integers indicating the dimension of the hilbert space for each site. Entry 0 is ignored (there is no site 0). ham : array or callable Hamiltonian term for each site ham(n, *physical_indices) or ham[n][*physical indices] for site n. """ self.ham = ham """The Hamiltonian. Can be changed, for example, to perform a quench. The number of neighbouring sites acted on must be specified in ham_sites.""" if ham_sites is None: if not callable(ham): self.ham_sites = len(ham[1].shape) // 2 else: self.ham_sites = 2 else: self.ham_sites = ham_sites if not (self.ham_sites == 2 or self.ham_sites == 3): raise ValueError("Only 2 or 3 site Hamiltonian terms supported!") super(EvoMPS_TDVP_Generic, self).__init__(N, D, q) self.gauge_fixing = self.canonical_form def _init_arrays(self): super(EvoMPS_TDVP_Generic, self)._init_arrays() #Make indicies correspond to the thesis self.AA = sp.empty((self.N), dtype=sp.ndarray) self.AAA = sp.empty((self.N - 1), dtype=sp.ndarray) self.K = sp.empty((self.N + 1), dtype=sp.ndarray) #Elements 1..N self.C = sp.empty((self.N), dtype=sp.ndarray) #Elements 1..N-1 for n in range(1, self.N + 1): self.K[n] = sp.zeros((self.D[n - 1], self.D[n - 1]), dtype=self.typ, order=self.odr) if n <= self.N - self.ham_sites + 1: ham_shape = [] for i in range(self.ham_sites): ham_shape.append(self.q[n + i]) C_shape = tuple(ham_shape + [self.D[n - 1], self.D[n - 1 + self.ham_sites]]) self.C[n] = sp.empty(C_shape, dtype=self.typ, order=self.odr) self.eta_sq = sp.zeros((self.N + 1), dtype=self.typ) """The per-site contributions to the norm-squared of the TDVP tangent vector (projection of the exact time evolution onto the MPS tangent plane. Only available after calling take_step() or calc_B().""" self.eta_sq.fill(0) """The norm of the TDVP tangent vector. Only available after calling take_step() or calc_B().""" self.eta = sp.NaN self.etaBB_sq = sp.zeros((self.N + 1), dtype=self.typ) """Per-site contributions to the norm-squared of the evolution captured by the two-site tangent plane but not by the one-site tangent plane. Only available after calling take_step() with calc_Y_2s or dynexp.""" self.etaBB_sq.fill(0) """The norm of the evolution captured by the two-site tangent plane. Only available after calling take_step() with calc_Y_2s or dynexp.""" self.etaBB = sp.NaN self.h_expect = sp.zeros((self.N + 1), dtype=self.typ) """The local energy expectation values (of each Hamiltonian term), available after calling update() or calc_K().""" self.h_expect.fill(sp.NaN) self.H_expect = sp.NaN """The energy expectation value, available after calling update() or calc_K().""" def calc_C(self, n_low=-1, n_high=-1, calc_AA=True): """Generates the C tensors used to calculate the K's and ultimately the B's. This is called automatically by self.update(). C[n] contains a contraction of the Hamiltonian self.ham with the parameter tensors over
import datetime import time import csv from operator import attrgetter from django.db.models import Q from django.http import Http404 from django.views.generic import list_detail from django.http import HttpResponseRedirect from django.shortcuts import render_to_response, get_object_or_404 from django.core.urlresolvers import reverse from django.contrib.auth.models import User from django.template import RequestContext from django.http import HttpResponse from django.core import serializers from django.contrib.auth.decorators import login_required from django.core.exceptions import MultipleObjectsReturned from django.core.mail import send_mail from django.utils import simplejson from models import * from forms import * from view_helpers import * from utils import DojoDataJSONResponse, serialize try: from notification import models as notification except ImportError: notification = None # Several of the views here are based on # http://collingrady.com/2008/02/18/editing-multiple-objects-in-django-with-newforms/ # Could now be switched to use formsets. @login_required def send_fresh_list(request): if request.method == "POST": if notification: try: fn = food_network() food_network_name = fn.long_name except FoodNetwork.DoesNotExist: return render_to_response('distribution/network_error.html') if fn: week_of = next_delivery_date() fresh_list = fn.fresh_list() users = list(Customer.objects.all()) users.append(fn) intro = avail_email_intro() notification.send(users, "distribution_fresh_list", { "intro": intro.message, "fresh_list": fresh_list, "week_of": week_of, "food_network_name": food_network_name, }) request.user.message_set.create(message="Fresh List emails have been sent") return HttpResponseRedirect(request.POST["next"]) @login_required def send_pickup_list(request): if request.method == "POST": if notification: try: fn = food_network() food_network_name = fn.long_name except FoodNetwork.DoesNotExist: return render_to_response('distribution/network_error.html') if fn: pickup_date = next_delivery_date() pickup_list = fn.pickup_list() for pickup in pickup_list: dist = pickup_list[pickup] item_list = dist.custodians.values() item_list.sort(lambda x, y: cmp(x.custodian, y.custodian)) users = [dist, fn] notification.send(users, "distribution_pickup_list", { "pickup_list": item_list, "pickup_date": pickup_date, "distributor": dist.distributor}) request.user.message_set.create(message="Pickup List emails have been sent") return HttpResponseRedirect(request.POST["next"]) @login_required def send_delivery_list(request): if request.method == "POST": if notification: try: fn = food_network() food_network_name = fn.long_name except FoodNetwork.DoesNotExist: return render_to_response('distribution/network_error.html') if fn: delivery_date = next_delivery_date() delivery_list = fn.delivery_list() for distributor in delivery_list: dist = delivery_list[distributor] order_list = dist.customers.values() order_list.sort(lambda x, y: cmp(x.customer, y.customer)) users = [dist, fn] notification.send(users, "distribution_order_list", { "order_list": order_list, "order_date": delivery_date, "distributor": dist.distributor}) request.user.message_set.create(message="Order List emails have been sent") return HttpResponseRedirect(request.POST["next"]) @login_required def send_order_notices(request): if request.method == "POST": if notification: try: fn = food_network() food_network_name = fn.long_name except FoodNetwork.DoesNotExist: return render_to_response('distribution/network_error.html') if fn: thisdate = next_delivery_date() weekstart = thisdate - datetime.timedelta(days=datetime.date.weekday(thisdate)) weekend = weekstart + datetime.timedelta(days=5) order_list = Order.objects.filter(delivery_date__range=(weekstart, weekend)) for order in order_list: customer = order.customer users = [customer, fn] for contact in customer.users.all(): if contact.email != customer.email: users.append(contact) users = list(set(users)) notification.send(users, "distribution_order_notice", { "order": order, "order_date": thisdate}) request.user.message_set.create(message="Order Notice emails have been sent") return HttpResponseRedirect(request.POST["next"]) def availability_csv(request, year, month, day): try: fn = food_network() except FoodNetwork.DoesNotExist: return render_to_response('distribution/network_error.html') avail_date = datetime.date(int(year), int(month), int(day)) response = HttpResponse(mimetype='text/csv') response['Content-Disposition'] = 'attachment; filename=availability.csv' writer = csv.writer(response) writer.writerow(["Producer", "Product", "Price", "Quantity", "Notes"]) for item in fn.avail_items_for_customer(avail_date): writer.writerow( [item.producer.long_name, item.product, item.product.formatted_unit_price_for_date(avail_date), item.remaining, item.notes ] ) return response def json_customer_info(request, customer_id): # Note: serializer requires an iterable, not a single object. Thus filter rather than get. data = serializers.serialize("json", Party.objects.filter(pk=customer_id)) return HttpResponse(data, mimetype="text/json-comment-filtered") def json_distributor_info(request, distributor_id): # Note: serializer requires an iterable, not a single object. Thus filter rather than get. qs = Distributor.objects.filter(pk=distributor_id) if not qs.count(): qs = FoodNetwork.objects.filter(pk=distributor_id) data = serializers.serialize("json", qs) return HttpResponse(data, mimetype="text/json-comment-filtered") def json_producer_info(request, producer_id): data = serializers.serialize("json", Party.objects.filter(pk=producer_id)) return HttpResponse(data, mimetype="text/json-comment-filtered") #@login_required def plan_selection(request): #import pdb; pdb.set_trace() from_date = next_delivery_date() # force from_date to Monday, to_date to Sunday from_date = from_date - datetime.timedelta(days=datetime.date.weekday(from_date)) to_date = from_date + datetime.timedelta(weeks=16) to_date = to_date - datetime.timedelta(days=datetime.date.weekday(to_date)+1) to_date = to_date + datetime.timedelta(days=7) plan_init = { 'plan_from_date': from_date, 'plan_to_date': to_date, 'list_type': 'M', } init = { 'from_date': from_date, 'to_date': to_date, } if request.method == "POST": if request.POST.get('submit-supply-demand'): sdform = DateRangeSelectionForm(prefix='sd', data=request.POST) if sdform.is_valid(): data = sdform.cleaned_data from_date = data['from_date'].strftime('%Y_%m_%d') to_date = data['to_date'].strftime('%Y_%m_%d') return HttpResponseRedirect('/%s/%s/%s/' % ('distribution/dojosupplydemand', from_date, to_date)) else: psform = PlanSelectionForm(initial=plan_init) income_form = DateRangeSelectionForm(prefix = 'inc', initial=init) elif request.POST.get('submit-income'): income_form = DateRangeSelectionForm(prefix='inc', data=request.POST) if income_form.is_valid(): data = income_form.cleaned_data from_date = data['from_date'].strftime('%Y_%m_%d') to_date = data['to_date'].strftime('%Y_%m_%d') return HttpResponseRedirect('/%s/%s/%s/' % ('distribution/dojoincome', from_date, to_date)) else: psform = PlanSelectionForm(initial=plan_init) sdform = DateRangeSelectionForm(prefix='sd', initial=init) else: psform = PlanSelectionForm(request.POST) if psform.is_valid(): psdata = psform.cleaned_data member_id = psdata['member'] from_date = psdata['plan_from_date'].strftime('%Y_%m_%d') to_date = psdata['plan_to_date'].strftime('%Y_%m_%d') list_type = psdata['list_type'] return HttpResponseRedirect('/%s/%s/%s/%s/%s/' % ('distribution/dojoplanningtable', member_id, list_type, from_date, to_date)) else: sdform = DateRangeSelectionForm(prefix='sd', initial=init) income_form = DateRangeSelectionForm(prefix = 'inc', initial=init) else: psform = PlanSelectionForm(initial=plan_init) sdform = DateRangeSelectionForm(prefix='sd', initial=init) income_form = DateRangeSelectionForm(prefix = 'inc', initial=init) return render_to_response('distribution/plan_selection.html', {'plan_form': psform, 'sdform': sdform, 'income_form': income_form, }, context_instance=RequestContext(request)) @login_required def planning_table(request, member_id, list_type, from_date, to_date): try: member = Party.objects.get(pk=member_id) except Party.DoesNotExist: raise Http404 role = "producer" plan_type = "Production" if member.is_customer(): role = "consumer" plan_type = "Consumption" try: from_date = datetime.datetime(*time.strptime(from_date, '%Y_%m_%d')[0:5]).date() to_date = datetime.datetime(*time.strptime(to_date, '%Y_%m_%d')[0:5]).date() except ValueError: raise Http404 # force from_date to Monday, to_date to Sunday from_date = from_date - datetime.timedelta(days=datetime.date.weekday(from_date)) to_date = to_date - datetime.timedelta(days=datetime.date.weekday(to_date)+1) to_date = to_date + datetime.timedelta(days=7) products = None if list_type == "M": if role == "consumer": products = CustomerProduct.objects.filter(customer=member, planned=True) else: products = ProducerProduct.objects.filter(producer=member, planned=True) if not products: products = Product.objects.filter(plannable=True) list_type = "A" plan_table = plan_weeks(member, products, from_date, to_date) #import pdb; pdb.set_trace() forms = create_weekly_plan_forms(plan_table.rows, data=request.POST or None) if request.method == "POST": for row in forms: if row.formset.is_valid(): for form in row.formset.forms: data = form.cleaned_data qty = data['quantity'] plan_id = data['plan_id'] from_dt = data['from_date'] to_dt = data['to_date'] product_id = data['product_id'] plan = None if plan_id: # what if plan was changed by prev cell? plan = ProductPlan.objects.get(id=plan_id) if plan.to_date < from_dt or plan.from_date > to_dt: plan = None if qty: if plan: if not qty == plan.quantity: if plan.from_date >= from_dt and plan.to_date <= to_dt: plan.quantity = qty plan.save() else: if plan.from_date < from_dt: new_to_dt = from_dt - datetime.timedelta(days=1) earlier_plan = ProductPlan( member=plan.member, product=plan.product, quantity=plan.quantity, from_date=plan.from_date, to_date=new_to_dt, role=plan.role, inventoried=plan.inventoried, distributor=plan.distributor, ) earlier_plan.save() if plan.to_date > to_dt: new_plan = ProductPlan( member=plan.member, product=plan.product, quantity=qty, from_date=from_dt, to_date=to_dt, role=plan.role, inventoried=plan.inventoried, distributor=plan.distributor, ) new_plan.save() plan.from_date = to_dt + datetime.timedelta(days=1) plan.save() else: plan.from_date=from_dt plan.quantity=qty plan.save() else: product = Product.objects.get(id=product_id) new_plan = ProductPlan( member=member, product=product, quantity=qty, from_date=from_dt, to_date=to_dt, role=role, ) new_plan.save() if role == "producer": listed_product, created = ProducerProduct.objects.get_or_create( product=product, producer=member) elif role == "consumer": listed_product, created = CustomerProduct.objects.get_or_create( product=product, customer=member) else: if plan: if plan.from_date >= from_dt and plan.to_date <= to_dt: plan.delete() else: if plan.to_date > to_dt: early_from_dt = plan.from_date if plan.from_date < from_dt: early_to_dt = from_dt - datetime.timedelta(days=1) earlier_plan = ProductPlan( member=plan.member, product=plan.product, quantity=plan.quantity, from_date=early_from_dt, to_date=early_to_dt, role=plan.role, inventoried=plan.inventoried, distributor=plan.distributor, ) earlier_plan.save() plan.from_date = to_dt + datetime.timedelta(days=1) plan.save() else: plan.to_date= from_dt - datetime.timedelta(days=1) plan.save() from_date = from_date.strftime('%Y_%m_%d') to_date = to_date.strftime('%Y_%m_%d') return HttpResponseRedirect('/%s/%s/%s/%s/' % ('distribution/membersupplydemand', from_date, to_date, member_id)) return render_to_response('distribution/planning_table.html', { 'from_date': from_date, 'to_date': to_date, 'plan_table': plan_table, 'forms': forms, 'plan_type': plan_type, 'member': member, 'list_type': list_type, 'tabnav': "distribution/tabnav.html", }, context_instance=RequestContext(request)) # todo: needs 2 views, this one to present the page, # the other to respond to the JsonRestStore @login_required def dojo_planning_table(request, member_id, list_type, from_date, to_date): try: member = Party.objects.get(pk=member_id) except Party.DoesNotExist: raise Http404 role = "producer" plan_type = "Production" if member.is_customer(): role = "consumer" plan_type = "Consumption" from_datestring = from_date to_datestring = to_date try: from_date = datetime.datetime(*time.strptime(from_date, '%Y_%m_%d')[0:5]).date() to_date = datetime.datetime(*time.strptime(to_date, '%Y_%m_%d')[0:5]).date() except ValueError: raise Http404 # force from_date to Monday, to_date to Sunday from_date = from_date - datetime.timedelta(days=datetime.date.weekday(from_date)) to_date = to_date - datetime.timedelta(days=datetime.date.weekday(to_date)+1) to_date = to_date + datetime.timedelta(days=7) products = None if list_type == "M": if role == "consumer": products = CustomerProduct.objects.filter(customer=member, planned=True) else: products = ProducerProduct.objects.filter(producer=member, planned=True) if not products: products = Product.objects.filter(plannable=True) list_type = "A" columns = plan_columns(from_date, to_date) return render_to_response('distribution/dojo_planning_table.html', { 'from_date': from_date, 'to_date': to_date, 'from_datestring': from_datestring, 'to_datestring': to_datestring, 'columns': columns, 'column_count': len(columns), 'plan_type': plan_type, 'member': member, 'list_type': list_type, 'tabnav': "distribution/tabnav.html", }, context_instance=RequestContext(request)) def json_planning_table(request, member_id, list_type, from_date, to_date, row_id=None): #import pdb; pdb.set_trace() try: member = Party.objects.get(pk=member_id) except Party.DoesNotExist: raise Http404 role = "producer" plan_type = "Production" if member.is_customer(): role = "consumer" plan_type = "Consumption" #import pdb; pdb.set_trace() if row_id: if request.method == "GET": #import pdb; pdb.set_trace() response = HttpResponse(request.raw_post_data, mimetype="text/json-comment-filtered") response['Cache-Control'] = 'no-cache' return response elif request.method == "PUT": #import pdb; pdb.set_trace() product = Product.objects.get(id=row_id) data = simplejson.loads(request.raw_post_data) member = Party.objects.get(id=data['member_id']) fd = data["from_date"] td = data["to_date"] from_date = datetime.datetime(*time.strptime(fd, '%Y-%m-%d')[0:5]).date() to_date = datetime.datetime(*time.strptime(td, '%Y-%m-%d')[0:5]).date() wkdate = from_date while wkdate <= to_date: key = wkdate.strftime('%Y-%m-%d') qty = data[key] if is_number(qty): qty = Decimal(qty) plan_id = data.get(":".join([key, "plan_id"])) from_dt = wkdate to_dt = from_dt + datetime.timedelta(days=6) plan = None if plan_id: plan = ProductPlan.objects.get(id=plan_id)
<filename>poc-hostapd/pub_api.py<gh_stars>10-100 """ pub_api.py """ from lib import * log.setLevel(logging.DEBUG) NC_PT_TYPES = [ # NOTE: encrypted 'eka', 'ewd', 'eha', 'esh', 'esh2', 'ewl', 'pay', 'pay2', # NOTE: not encrypted 'kep1', 'kep2', 'kep3', 'kep4', 'iw', ] class RemoteAdvertiser: """ Used to store data about the remote node """ _version = '1.0.0' def __init__(self, strategy, sid): self.strategy = strategy self.sid = sid self.btaddr = None self.btname = None self.eid = None self.ncname = None self.uuid = None self.sock = None self.ip = None self.tcp_port = None self.essid = None self.password = <PASSWORD> class RemoteDiscoverer: """ Used to store data about the remote node """ _version = '1.0.0' def __init__(self, strategy, sid): self.strategy = strategy self.sid = sid self.btaddr = None self.btname = None self.eid = None self.ncname = None self.sock = None self.ip = None self.tcp_port = None class Advertiser: """ Advertiser """ _version = '1.0.0' def __init__(self, strategy, sid, ncname, eid, wifi_mode, port=5): self.strategy = strategy self.sid = sid self.ncname = ncname self.eid = eid self.wifi_mode = wifi_mode self.port = port self.server_sock = None self.rdsc = RemoteDiscoverer(self.strategy, self.sid) assert self.strategy == self.rdsc.strategy assert self.sid == self.rdsc.sid self.kep1 = None self.kep2 = None self.kep3 = None self.kep4 = None self.r_kep1 = None self.r_kep2 = None self.r_kep3 = None self.r_kep4 = None # self.pri_key = int_to_bytes(randint(2, 3000)) # self.pri_key = b'\x02' self.pri_key = urandom(4) self.pub_key = None self.shared_secret = None self.dsc2adv_key = None self.adv2dsc_key = None self.auth_token = None self.d2a_count = 0 self.a2d_count = 0 self._compute_btname() self._precompute_kep() def _compute_btname(self): """Compute btname according to strategy, eid, ncname and sid.""" # btname = get_adv_btname(P2P_CLUSTER, eid, ncname, sid) if self.strategy == 'P2P_STAR': self.btname = get_adv_btname('!', self.eid, self.ncname, self.sid) elif self.strategy == 'P2P_CLUSTER': self.btname = get_adv_btname('"', self.eid, self.ncname, self.sid) log.debug("Adv btname: {}".format(self.btname)) def _precompute_kep(self): """Pre compute Kep3 r_* packets are created from scapy ones and sent. """ self.kep3 = nc_scapy_pkt('kep3', [self.pri_key, self.pub_key]) log.debug("Adv pri_key: {}".format(self.pri_key)) self.r_kep3 = raw(self.kep3) def advertise(self, max_con=1, prompt=False): """Start RFCOMM and SDP servers""" if prompt: _ = input("Adv bluetoothd -C, {}, {}, {}, {}, {}, {}, start wireshark.".format( self.strategy, self.sid, self.eid, self.ncname, self.btname, self.wifi_mode)) self.server_sock = BluetoothSocket(RFCOMM) self.server_sock.bind(("", self.port)) self.server_sock.listen(max_con) log.info("Adv on port {} and accepts {}".format(self.port, max_con)) # NOTE: uuid depends only on sid # uuid = sid_to_uuid(sid) self.uuid = "b8c1a306-9167-347e-b503-f0daba6c5723" # NOTE: requires bluetoothd -C advertise_service( sock=self.server_sock, name=self.sid, service_id = "", service_classes = [self.uuid], ) def connect(self, auto_accept=True): """Accept BT connection, kep, kdf and AL pre-connection.""" # NOTE: blocking self.rdsc.sock, info = self.server_sock.accept() self.rdsc.btaddr = info[0] log.info("Adv connected with: {}".format(self.rdsc.btaddr)) self._do_kep() self._do_kdf() self._do_pre_connection(auto_accept) def _do_kep(self): """Do the key exchange protocol with the dsc. Recv kep1, kep2, kep4 """ data = self.rdsc.sock.recv(1024) # NOTE: packet contains only Kep1 if data.find(b'AES_256_CBC-HMAC_SHA256') == -1: self.kep1 = Kep1(data) log.info("Adv rcvd Kep1") data = self.rdsc.sock.recv(1024) self.kep2 = Kep2(data) log.info("Adv rcvd Kep2") # NOTE: packet contains Kep1 and Kep2 else: # NOTE: assuming that kep2 is always 140 Bytes self.kep1 = Kep1(data[:len(data)-NC_KEP2_LEN]) log.info("Adv rcvd Kep1") self.kep2 = Kep2(data[-NC_KEP2_LEN:]) log.info("Adv rcvd Kep2") self.rdsc.ncname = self.kep1.ncname self.rdsc.eid = self.kep1.eid log.debug("Adv ncname_remote: {} eid_remote:{}".format( self.rdsc.ncname, self.rdsc.eid)) # log.warning("Adv kep1.str1: {}, {}".format(kep1.str1, b64e(kep1.str1))) self.rdsc.kdf1 = self.kep2.kdf1 self.r_kep2 = raw(self.kep2) # NOTE: Kep3 log.debug("Adv kep3.xA: {}, {}".format(self.kep3.xA.hex(), len(self.kep3.xA.hex()))) log.debug("Adv kep3.yA: {}, {}".format(self.kep3.yA.hex(), len(self.kep3.yA.hex()))) self.rdsc.sock.send(self.r_kep3) log.info("Adv sent (precomputed) Kep3:") data = self.rdsc.sock.recv(1024) log.info("Adv rcvd Kep4:") # NOTE: Kep4 self.r_kep4 = data self.kep4 = Kep4(data) log.debug("Adv kep4.xD: {}, {}".format(self.kep4.xD.hex(), len(self.kep4.xD.hex()))) log.debug("Adv kep4.yD: {}, {}".format(self.kep4.yD.hex(), len(self.kep4.yD.hex()))) # NOTE: commitment test done only by the adv if not nc_kep(self.r_kep2, self.r_kep4): log.error("Adv failed nc_kep check") exit("Adv failed nc_kep check") def _do_kdf(self): """Derives shared shared_secret, session keys and auth token.""" self.shared_secret = nc_ecdh(self.pri_key, self.kep4.xD, self.kep4.yD) rv = nc_kdf(self.shared_secret, self.r_kep2, self.r_kep3) self.dsc2adv_key = rv[6] self.adv2dsc_key = rv[8] self.auth_token = rv[9] log.debug("Adv ss: {} token: {}".format(self.shared_secret, self.auth_token)) def _do_pre_connection(self, auto_accept): """Do the pre-connection phase.""" while True: data = self.rdsc.sock.recv(1024) if data.find(NC_KA_PRE_CON) != -1: log.info("Adv recv a preconn ka.") self.rdsc.sock.send(NC_KA_PRE_CON) log.debug("Adv sent a preconn ka.") elif data.find(NC_ACCEPT_CON) != -1: log.info("Dsc accepted the connection.") if auto_accept: self.rdsc.sock.send(NC_ACCEPT_CON) log.debug("Adv accepted the connection.") else: log.debug("Adv still has to accept the connection.") break elif data.find(NC_REJECT_CON) != -1: log.info("Dsc rejected the connection.") self.rdsc.sock.send(NC_REJECT_CON) log.debug("Adv rejected the connection.") exit("Adv and Dsc rejected the connection.") else: log.warning("Adv don't know how to handle {}.".format(data)) def send(self, ptype, pargs=None, eid=None, blocking=True ): """Send a NCPacket of ptype to eid and returns it. pargs contains parameters to be used by nc_scapy_pkt """ if eid is None: eid = self.rdsc.eid iv = urandom(AES_IV_BYTES) self.a2d_count += 1 if pargs is None: pkt = NCPacket(ptype, self.adv2dsc_key, iv, self.a2d_count) else: pkt = NCPacket(ptype, self.adv2dsc_key, iv, self.a2d_count, *pargs) log.debug("Adv send: {}, a2d_count: {}".format(pkt.ptype, self.a2d_count)) self.rdsc.sock.send(raw(pkt.scapy)) return pkt def recv(self, eid=None, blocking=True): """Recv and returns a NCPacket from eid.""" if eid is None: eid = self.rdsc.eid self.d2a_count += 1 data = self.rdsc.sock.recv(1024) pkt = NCPacket(data, self.dsc2adv_key, None, self.d2a_count) log.debug("Adv rcvd ka: {}, d2a_count: {}".format(pkt.pt, pkt.pt.count)) return pkt def disconnect(self): """disconnect""" if self.rdsc.sock is None: log.info("Adv: no client socket to disconnect from") else: self.rdsc.sock.close() self.rdsc.sock = None if self.server_sock is None: log.info("Adv: no server socket to disconnect from") else: self.server_sock.close() self.server_sock = None def __repr__(self): return 'Adv:' + repr((self.strategy, self.sid, self.eid, self.ncname)) def __str__(self): return 'Adv:' + repr((self.strategy, self.sid, self.eid, self.ncname)) class Discoverer: """ Discoverer """ _version = '1.0.0' def __init__(self, btaddr, btname, strategy, sid, ncname, eid, wifi_mode='hostapd'): self.btaddr = btaddr self.btname = btname self.strategy = strategy self.sid = sid self.ncname = ncname self.eid = eid self.wifi_mode = wifi_mode self.port = None # 5, 10 self.advs = None self.radv = RemoteAdvertiser(self.strategy, self.sid) assert self.strategy == self.radv.strategy assert self.sid == self.radv.sid self.kep1 = None self.kep2 = None self.kep3 = None self.kep4 = None self.r_kep1 = None self.r_kep2 = None self.r_kep3 = None self.r_kep4 = None # self.pri_key = int_to_bytes(randint(2, 3000)) # self.pri_key = b'\x02' self.pri_key = urandom(4) self.pub_key = None self.shared_secret = None self.dsc2adv_key = None self.adv2dsc_key = None self.auth_token = None self.d2a_count = 0 self.a2d_count = 0 self._precompute_kep() def _precompute_kep(self): """Pre compute Kep1, Kep4 and Kep2. Kep4 before Kep2 because of sha512 r_* packets are created from scapy ones and sent. """ self.kep1 = nc_scapy_pkt('kep1', [self.eid, self.ncname, self.strategy, self.wifi_mode]) self.r_kep1 = raw(self.kep1) log.debug("Dsc r_kep1: {}".format(self.r_kep1)) self.kep4 = nc_scapy_pkt('kep4', [self.pri_key, self.pub_key]) log.debug("Dsc pri_key: {}".format(self.pri_key)) log.debug("Dsc pub_key: {}".format(self.pub_key)) self.r_kep4 = raw(self.kep4) log.debug("Dsc r_kep4: {}".format(self.r_kep4)) self.kep2 = nc_scapy_pkt('kep2', [self.r_kep4]) self.r_kep2 = raw(self.kep2) log.debug("Dsc r_kep2: {}".format(self.r_kep2)) def discover(self, duration): advs, others = discover_bt(duration) if not advs: exit("Dsc no devices discovered") else: self.advs = advs log.info("Dsc discovered: {}".format(advs)) def connect(self, btaddr, btname, auto_accept=True): """Connect to an advertiser If auto_accept is False you have to manually accept the connection.""" self.radv.btaddr = btaddr self.radv.btname = btname _, self.radv.eid, _, self.radv.ncname = get_adv_parameters(self.radv.btname) self.radv.uuid = sid_to_uuid(self.sid) # XXX strengthen log.warning('Dsc uuid is hardcoded') self.radv.uuid = "b8c1a306-9167-347e-b503-f0daba6c5723" sdps = find_service(address=self.radv.btaddr, uuid=self.radv.uuid) if not sdps: exit("Dsc no sdp with uuid: {}".format(self.radv.uuid)) self.radv.sdp = sdps[0] log.info("Dsc found sdp_nc: {}".format(self.radv.sdp)) assert self.radv.sdp["host"] == self.radv.btaddr assert self.radv.sdp["name"] == self.radv.sid self.port = self.radv.sdp["port"] try: self.radv.sock = BluetoothSocket(RFCOMM) self.radv.sock.connect((self.radv.btaddr, self.port)) log.info("Dsc connecting to: {} port: {}".format(self.radv.btaddr, self.port)) self._do_kep() self._do_kdf() self._do_pre_connection(auto_accept) except IOError: pass except Exception as e: raise e def _do_kep(self): """Do the key exchange protocol with the adv. Recv kep3 """ self.radv.sock.send(self.r_kep1) log.info("Dsc sent (precomputed) Kep1:") self.radv.sock.send(self.r_kep2) log.info("Dsc sent(precomputed) Kep2:") data = self.radv.sock.recv(1024) log.info("Dsc rcvd Kep3: {}".format(data.hex())) self.r_kep3 = data self.kep3 = Kep3(data) log.debug("Dsc kep3.xA: {}, {}".format(self.kep3.xA.hex(), len(self.kep3.xA.hex()))) log.debug("Dsc kep3.yA: {}, {}".format(self.kep3.yA.hex(), len(self.kep3.yA.hex()))) self.radv.sock.send(self.r_kep4) log.info("Dsc sent(precomputed) Kep4:") log.debug("Dsc kep4.xD: {}, {}".format(self.kep4.xD.hex(), len(self.kep4.xD.hex()))) log.debug("Dsc kep4.yD: {}, {}".format(self.kep4.yD.hex(), len(self.kep4.yD.hex()))) # NOTE: commitment test done only by the adv if not nc_kep(self.r_kep2, self.r_kep4): log.error("Dsc failed nc_kep check") exit("Dsc failed nc_kep check") def _do_kdf(self): """Derives shared shared_secret, session keys and auth token.""" self.shared_secret = nc_ecdh(self.pri_key, self.kep3.xA, self.kep3.yA) rv = nc_kdf(self.shared_secret, self.r_kep2, self.r_kep3) self.dsc2adv_key = rv[6] self.adv2dsc_key = rv[8] self.auth_token = rv[9] def _do_pre_connection(self, auto_accept): """Do the pre-connection phase.""" while True: data = self.radv.sock.recv(1024) if data.find(NC_KA_PRE_CON) != -1: log.info("Adv sent a preconn ka.") self.radv.sock.send(NC_KA_PRE_CON) log.debug("Dsc sent a preconn ka.") elif data.find(NC_ACCEPT_CON) != -1: log.info("Adv accepted the connection.") if auto_accept: self.radv.sock.send(NC_ACCEPT_CON)
vegan.summary_simper(simper_ret) species_stats = self._generate_species_stats(df, simper_ret, grouping_names) report_output = self._generate_simper_report(workspace_id, simper_ret, simper_sum, species_stats, grouping_names) return report_output def perform_rarefy(self, params): logging.info('Start performing rarefying matrix with {}'.format(params)) warnings = [] input_matrix_ref = params.get('input_matrix_ref') workspace_id = params.get('workspace_id') new_matrix_name = params.get('new_matrix_name') seed_number = params.get('seed_number', 'do_not_seed') subsample_size = params.get('subsample_size') dimension = params.get('dimension', 'col') bootstrap = params.get('bootstrap') if bootstrap is not None: num_rare_reps = bootstrap['num_rare_reps'] central_tendency = bootstrap['central_tendency'] input_matrix_obj = self.dfu.get_objects({'object_refs': [input_matrix_ref]})['data'][0] input_matrix_info = input_matrix_obj['info'] input_matrix_name = input_matrix_info[1] input_matrix_data = input_matrix_obj['data'] for key, obj_data in input_matrix_data.items(): if key.endswith('_ref'): subobj_ref = input_matrix_data[key] input_matrix_data[key] = '{};{}'.format(input_matrix_ref, subobj_ref) logging.info('updated {} to {}'.format(key, input_matrix_data[key])) for dim in ['row', 'col']: attribute_mapping = input_matrix_data.get('{}_mapping'.format(dim)) attributemapping_ref = input_matrix_data.get('{}_attributemapping_ref'.format(dim)) if not attribute_mapping and attributemapping_ref: am_data = self.dfu.get_objects({'object_refs': [attributemapping_ref]})[ 'data'][0]['data'] attribute_mapping = {x: x for x in am_data['instances'].keys()} input_matrix_data['{}_mapping'.format(dim)] = attribute_mapping if not new_matrix_name: current_time = time.localtime() new_matrix_name = input_matrix_name + time.strftime('_%H_%M_%S_%Y_%m_%d', current_time) data_matrix = self.data_util.fetch_data({'obj_ref': input_matrix_ref}).get('data_matrix') df = pd.read_json(data_matrix) # original_matrix_df = df.copy(deep=True) if dimension == 'col': df = df.T df.fillna(0, inplace=True) run_seed = (not seed_number == 'do_not_seed') # determining subsample size raremax = int(min(df.sum(axis=1))) # least sample size if subsample_size is None: # default behavior: use least sample size subsample_size = raremax else: # user-specified behavior, find any samples too small unrarefied = df.index[df.sum(axis=1) < subsample_size].tolist() if len(unrarefied) > 0: msg = ( 'At subsampling size %d, samples %s are too small and will not be rarefied. ' 'Smallest sample size is %d' % (subsample_size, str(unrarefied), raremax) ) warnings.append(msg) logging.info(msg) logging.info('Using subsample size %d' % subsample_size) vegan = rpackages.importr('vegan') numpy2ri.activate() # generating rarefied matrix logging.info('Start executing rrarefy(s)') if run_seed: ro.r('set.seed({})'.format(seed_number)) if bootstrap is None: with localconverter(ro.default_converter + pandas2ri.converter): random_rare = vegan.rrarefy(df, subsample_size) else: random_rare_l = [] for rep in range(num_rare_reps): with localconverter(ro.default_converter + pandas2ri.converter): random_rare = vegan.rrarefy(df, subsample_size) # returns np.ndarray random_rare_l.append(random_rare) if central_tendency == 'mean': random_rare = sum(random_rare_l) / num_rare_reps elif central_tendency == 'median': random_rare = np.median(random_rare_l, axis=0) else: raise NotImplementedError('Unknown value for `central_tendency`') random_rare_df = pd.DataFrame(random_rare, index=df.index, columns=df.columns) if dimension == 'col': random_rare_df = random_rare_df.T # generating plots result_directory = os.path.join(self.scratch, str(uuid.uuid4())) self._mkdir_p(result_directory) logging.info('Start generating rarecurve plot') rarecurve_image = os.path.join(result_directory, 'rarecurve.jpg') ro.r("jpeg('{}')".format(rarecurve_image)) if run_seed: ro.r('set.seed({})'.format(seed_number)) with localconverter(ro.default_converter + pandas2ri.converter): vegan.rarecurve(df, sample=subsample_size, step=20, col="blue", cex=0.6) ro.r('dev.off()') logging.info('Start generating expected species richness vs raw abundance plot') with localconverter(ro.default_converter + pandas2ri.converter): Srare = vegan.rarefy(df, subsample_size) specnumber = ro.r['specnumber'] with localconverter(ro.default_converter + pandas2ri.converter): S = specnumber(df) obs_vs_rare_image = os.path.join(result_directory, 'obs_vs_rare.jpg') ro.r("jpeg('{}')".format(obs_vs_rare_image)) plot = ro.r['plot'] plot(S, Srare, xlab="Observed No. of Species", ylab="Rarefied No. of Species") ro.r('dev.off()') new_matrix_data = {'row_ids': random_rare_df.index.tolist(), 'col_ids': random_rare_df.columns.tolist(), 'values': random_rare_df.values.tolist()} input_matrix_data['data'] = new_matrix_data logging.info("Saving new rarefy matrix object") new_matrix_obj_ref = self.data_util.save_object({ 'obj_type': input_matrix_info[2], 'obj_name': new_matrix_name, 'data': input_matrix_data, 'workspace_id': workspace_id})['obj_ref'] returnVal = {'new_matrix_obj_ref': new_matrix_obj_ref} report_output = self._generate_rarefy_report(new_matrix_obj_ref, workspace_id, random_rare_df, rarecurve_image, obs_vs_rare_image, warnings) returnVal.update(report_output) return returnVal def perform_mantel_test(self, params): logging.info('Start performing mantel test with {}'.format(params)) input_matrix_refs = params.get('input_matrix_refs') workspace_id = params.get('workspace_id') dimension = params.get('dimension', 'col') dist_metric = params.get('dist_metric', 'euclidean') correlation_method = params.get('correlation_method', 'pearson') permutations = params.get('permutations', 0) alternative_hypothesis = params.get('alternative_hypothesis', 'two-sided') if dimension not in ['col', 'row']: raise ValueError('Please use "col" or "row" for input dimension') if len(input_matrix_refs) < 2: raise ValueError('Please provide at least 2 matrices to perform mentel test') dms = list() labels = list() for input_matrix_ref in input_matrix_refs: input_matrix_obj = self.dfu.get_objects({'object_refs': [input_matrix_ref]})['data'][0] input_matrix_info = input_matrix_obj['info'] input_matrix_name = input_matrix_info[1] labels.append(input_matrix_name) data_matrix = self.data_util.fetch_data( {'obj_ref': input_matrix_ref}).get('data_matrix') df = pd.read_json(data_matrix) dm = self._create_distance_matrix(df, dist_metric=dist_metric, dimension=dimension) dms.append(dm) pwmantel_res = self._run_mantel_tests(dms, labels, permutations=permutations, correlation_method=correlation_method, alternative_hypothesis=alternative_hypothesis) report_output = self._generate_mantel_test_report(workspace_id, pwmantel_res) return report_output def perform_variable_stats_matrix(self, params): logging.info('Start performing variable statistics with {}'.format(params)) input_matrix_ref = params.get('input_matrix_ref') workspace_id = params.get('workspace_id') dimension = params.get('dimension', 'col') dist_metric = params.get('dist_metric', 'euclidean') permutations = params.get('permutations', 0) grouping = params.get('grouping') perform_anosim = params.get('perform_anosim', True) perform_permanova = params.get('perform_permanova', True) perform_permdisp = params.get('perform_permdisp', True) if not bool(perform_anosim or perform_permanova or perform_permdisp): raise ValueError('Please select at least one algorithm to perform') if dimension not in ['col', 'row']: raise ValueError('Please use "col" or "row" for input dimension') input_matrix_obj = self.dfu.get_objects({'object_refs': [input_matrix_ref]})['data'][0] input_matrix_info = input_matrix_obj['info'] input_matrix_data = input_matrix_obj['data'] matrix_type = input_matrix_info[2] if 'KBaseMatrices' in matrix_type: am_ref = input_matrix_data.get('{}_attributemapping_ref'.format(dimension)) if not am_ref: raise ValueError( 'Missing {} attribute mapping from original matrix'.format(dimension)) elif 'KBaseProfile' in matrix_type: profile_category = input_matrix_data.get('profile_category') if profile_category == 'community' and dimension == 'row': raise ValueError('Please choose column dimension for community profile') if profile_category == 'organism' and dimension == 'col': raise ValueError('Please choose row dimension for organism profile') am_ref = input_matrix_data.get('{}_attributemapping_ref'.format(dimension)) if not am_ref: raise ValueError( 'Missing {} attribute mapping from functional profile'.format(dimension)) else: raise ValueError('Unsupported data type: {}'.format(matrix_type)) data_matrix = self.data_util.fetch_data({'obj_ref': input_matrix_ref}).get('data_matrix') df = pd.read_json(data_matrix) dm = self._create_distance_matrix(df, dist_metric=dist_metric, dimension=dimension) am_ref = '{};{}'.format(input_matrix_ref, am_ref) am_data = self.dfu.get_objects({'object_refs': [am_ref]})['data'][0]['data'] attribute_names = [am.get('attribute') for am in am_data.get('attributes')] if grouping not in attribute_names: raise ValueError('Cannot find {} in {} attribute mapping'.format(grouping, dimension)) attri_pos = attribute_names.index(grouping) instances = am_data.get('instances') if dimension == 'col': items = df.columns else: items = df.index grouping_names = list() for item in items: instance = instances.get(item) if not instance: raise ValueError('Cannot find instance for {} in attribute mapping'.format(item)) attri = instance[attri_pos] grouping_names.append(attri) logging.info('Fetched {} for {} from attributes'.format(grouping_names, grouping)) anosim_res = None if perform_anosim: anosim_res = self._run_anosim(dm, grouping_names, permutations) permanova_res = None if perform_permanova: permanova_res = self._run_permanova(dm, grouping_names, permutations) permdisp_res = None if perform_permdisp: permdisp_res = self._run_permdisp(dm, grouping_names, permutations) report_output = self._generate_variable_stats_report(workspace_id, anosim_res, permanova_res, permdisp_res) return report_output def transform_matrix_variable_specific(self, params): """ Transform a list of variable from a matrix """ OPS = [ 'relative_abundance', 'standardization', 'ratio_transformation', 'log', 'sqrt', 'logit', ] logging.info('Start performing transformation with {}'.format(params)) input_matrix_ref = params.get('input_matrix_ref') workspace_id = params.get('workspace_id') new_matrix_name = params.get('new_matrix_name') operations = params.get('operations') relative_abundance_params = params.get('perform_relative_abundance', {}) standardization_params = params.get('standardization_params', {}) ratio_transformation_params = params.get('ratio_transformation_params', {}) log_params = params.get('log_params', {}) dimension = params.get('dimension', 'row') variables = params.get('variables', list()) if dimension not in ['col', 'row']: raise ValueError('Please use "col" or "row" for input dimension') # validate operations MAX_OPS = 15 if len(operations) > MAX_OPS: raise Exception('Maximum allowed number of operations is %d' % MAX_OPS) for op in operations: if op not in OPS: raise Exception('Operation %s not in allowed %s' % (str(op), OPS)) input_matrix_obj = self.dfu.get_objects({'object_refs': [input_matrix_ref]})['data'][0] input_matrix_info = input_matrix_obj['info'] input_matrix_name = input_matrix_info[1] input_matrix_data = input_matrix_obj['data'] unmatched_var = set(variables) - set(input_matrix_data['data']['{}_ids'.format(dimension)]) if unmatched_var: raise ValueError('variable [{}] is not contained in {} ids from matrix'.format( unmatched_var, dimension)) for key, obj_data in input_matrix_data.items(): if key.endswith('_ref'): subobj_ref = input_matrix_data[key] input_matrix_data[key] = '{};{}'.format(input_matrix_ref, subobj_ref) logging.info('updated {} to {}'.format(key, input_matrix_data[key])) for dim in ['row', 'col']: attribute_mapping = input_matrix_data.get('{}_mapping'.format(dim)) attributemapping_ref = input_matrix_data.get('{}_attributemapping_ref'.format(dim)) if not attribute_mapping and attributemapping_ref: am_data = self.dfu.get_objects({'object_refs': [attributemapping_ref]})[ 'data'][0]['data'] attribute_mapping = {x: x for x in am_data['instances'].keys()} input_matrix_data['{}_mapping'.format(dim)] = attribute_mapping if not new_matrix_name: current_time = time.localtime() new_matrix_name = input_matrix_name + time.strftime('_%H_%M_%S_%Y_%m_%d', current_time) data_matrix = self.data_util.fetch_data({'obj_ref': input_matrix_ref}).get('data_matrix') df = pd.read_json(data_matrix) original_df = df.copy(deep=True) original_row_ids = original_df.index original_col_ids = original_df.columns if dimension == 'row': selected_df = original_df.loc[list(set(variables))] else: selected_df = original_df.loc[:, list(set(variables))] # iterate over operations df_results = [] for op in operations: if op == 'relative_abundance': selected_df = self._relative_abundance( selected_df, dimension=relative_abundance_params.get( 'relative_abundance_dimension', 'col')) elif op == 'standardization': selected_df = self._standardize_df( selected_df, dimension=standardization_params.get( 'standardization_dimension', 'col'), with_mean=standardization_params.get( 'standardization_with_mean', True), with_std=standardization_params.get( 'standardization_with_std', True)) elif op == 'ratio_transformation': selected_df = self._ratio_trans_df( selected_df, method=ratio_transformation_params.get( 'ratio_transformation_method', 'clr'), dimension=ratio_transformation_params.get( 'ratio_transformation_dimension', 'col')) elif op == 'logit': selected_df = self._logit(selected_df) elif op == 'sqrt': selected_df = self._sqrt(selected_df) elif op == 'log': selected_df = self._log(selected_df, base=log_params.get('base', 10), a=log_params.get('offset', 1)) else: raise NotImplementedError('Unknown op `%s`' % op) df_results.append(selected_df.copy(deep=True)) if dimension == 'row': df = selected_df.combine_first(original_df) else: df = selected_df.T.combine_first(original_df.T).T df.index = df.index.astype('str') df.columns = df.columns.astype('str') new_matrix_data = {'row_ids': df.index.tolist(), 'col_ids': df.columns.tolist(), 'values': df.values.tolist()} input_matrix_data['data'] = new_matrix_data removed_row_ids = set(original_row_ids) - set(df.index) removed_col_ids = set(original_col_ids) - set(df.columns) if removed_row_ids and input_matrix_data.get('row_attributemapping_ref'): input_matrix_data = self._sync_attribute_mapping(input_matrix_data, removed_row_ids, new_matrix_name + '_row_attribute_mapping', 'row', workspace_id) if removed_col_ids and input_matrix_data.get('col_attributemapping_ref'): input_matrix_data = self._sync_attribute_mapping(input_matrix_data, removed_col_ids, new_matrix_name + '_col_attribute_mapping', 'col', workspace_id) logging.info("Saving new transformed matrix object") new_matrix_obj_ref = self.data_util.save_object({ 'obj_type': input_matrix_info[2], 'obj_name': new_matrix_name, 'data': input_matrix_data, 'workspace_id': workspace_id})['obj_ref'] returnVal = {'new_matrix_obj_ref': new_matrix_obj_ref} report_output = self._generate_transform_report(new_matrix_obj_ref, workspace_id, operations, df_results, variable_specific=True) returnVal.update(report_output) return returnVal def transform_matrix(self, params): """ Transform a matrix """ OPS =
# not accounting for scr refresh text_10.frameNStop = frameN # exact frame index win.timeOnFlip(text_10, 'tStopRefresh') # time at next scr refresh text_10.setAutoDraw(False) # check for quit (typically the Esc key) if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]): core.quit() # check if all components have finished if not continueRoutine: # a component has requested a forced-end of Routine break continueRoutine = False # will revert to True if at least one component still running for thisComponent in feedback1Components: if hasattr(thisComponent, "status") and thisComponent.status != FINISHED: continueRoutine = True break # at least one component has not yet finished # refresh the screen if continueRoutine: # don't flip if this routine is over or we'll get a blank screen win.flip() # -------Ending Routine "feedback1"------- for thisComponent in feedback1Components: if hasattr(thisComponent, "setAutoDraw"): thisComponent.setAutoDraw(False) loop_formal1.addData('text_3.started', text_3.tStartRefresh) loop_formal1.addData('text_3.stopped', text_3.tStopRefresh) loop_formal1.addData('text_9.started', text_9.tStartRefresh) loop_formal1.addData('text_9.stopped', text_9.tStopRefresh) loop_formal1.addData('text_10.started', text_10.tStartRefresh) loop_formal1.addData('text_10.stopped', text_10.tStopRefresh) thisExp.nextEntry() # completed 1 repeats of 'loop_formal1' # ------Prepare to start Routine "question1"------- continueRoutine = True # update component parameters for each repeat rating.reset() # keep track of which components have finished question1Components = [text_15, rating] for thisComponent in question1Components: thisComponent.tStart = None thisComponent.tStop = None thisComponent.tStartRefresh = None thisComponent.tStopRefresh = None if hasattr(thisComponent, 'status'): thisComponent.status = NOT_STARTED # reset timers t = 0 _timeToFirstFrame = win.getFutureFlipTime(clock="now") question1Clock.reset(-_timeToFirstFrame) # t0 is time of first possible flip frameN = -1 # -------Run Routine "question1"------- while continueRoutine: # get current time t = question1Clock.getTime() tThisFlip = win.getFutureFlipTime(clock=question1Clock) tThisFlipGlobal = win.getFutureFlipTime(clock=None) frameN = frameN + 1 # number of completed frames (so 0 is the first frame) # update/draw components on each frame # *text_15* updates if text_15.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance: # keep track of start time/frame for later text_15.frameNStart = frameN # exact frame index text_15.tStart = t # local t and not account for scr refresh text_15.tStartRefresh = tThisFlipGlobal # on global time win.timeOnFlip(text_15, 'tStartRefresh') # time at next scr refresh text_15.setAutoDraw(True) # *rating* updates if rating.status == NOT_STARTED and t >= 0.0-frameTolerance: # keep track of start time/frame for later rating.frameNStart = frameN # exact frame index rating.tStart = t # local t and not account for scr refresh rating.tStartRefresh = tThisFlipGlobal # on global time win.timeOnFlip(rating, 'tStartRefresh') # time at next scr refresh rating.setAutoDraw(True) continueRoutine &= rating.noResponse # a response ends the trial # check for quit (typically the Esc key) if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]): core.quit() # check if all components have finished if not continueRoutine: # a component has requested a forced-end of Routine break continueRoutine = False # will revert to True if at least one component still running for thisComponent in question1Components: if hasattr(thisComponent, "status") and thisComponent.status != FINISHED: continueRoutine = True break # at least one component has not yet finished # refresh the screen if continueRoutine: # don't flip if this routine is over or we'll get a blank screen win.flip() # -------Ending Routine "question1"------- for thisComponent in question1Components: if hasattr(thisComponent, "setAutoDraw"): thisComponent.setAutoDraw(False) thisExp.addData('text_15.started', text_15.tStartRefresh) thisExp.addData('text_15.stopped', text_15.tStopRefresh) # store data for thisExp (ExperimentHandler) thisExp.addData('rating.response', rating.getRating()) thisExp.addData('rating.rt', rating.getRT()) thisExp.nextEntry() thisExp.addData('rating.started', rating.tStart) thisExp.addData('rating.stopped', rating.tStop) # the Routine "question1" was not non-slip safe, so reset the non-slip timer routineTimer.reset() # ------Prepare to start Routine "rest"------- continueRoutine = True # update component parameters for each repeat key_resp_5.keys = [] key_resp_5.rt = [] _key_resp_5_allKeys = [] # keep track of which components have finished restComponents = [text_16, key_resp_5] for thisComponent in restComponents: thisComponent.tStart = None thisComponent.tStop = None thisComponent.tStartRefresh = None thisComponent.tStopRefresh = None if hasattr(thisComponent, 'status'): thisComponent.status = NOT_STARTED # reset timers t = 0 _timeToFirstFrame = win.getFutureFlipTime(clock="now") restClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip frameN = -1 # -------Run Routine "rest"------- while continueRoutine: # get current time t = restClock.getTime() tThisFlip = win.getFutureFlipTime(clock=restClock) tThisFlipGlobal = win.getFutureFlipTime(clock=None) frameN = frameN + 1 # number of completed frames (so 0 is the first frame) # update/draw components on each frame # *text_16* updates if text_16.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance: # keep track of start time/frame for later text_16.frameNStart = frameN # exact frame index text_16.tStart = t # local t and not account for scr refresh text_16.tStartRefresh = tThisFlipGlobal # on global time win.timeOnFlip(text_16, 'tStartRefresh') # time at next scr refresh text_16.setAutoDraw(True) # *key_resp_5* updates waitOnFlip = False if key_resp_5.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance: # keep track of start time/frame for later key_resp_5.frameNStart = frameN # exact frame index key_resp_5.tStart = t # local t and not account for scr refresh key_resp_5.tStartRefresh = tThisFlipGlobal # on global time win.timeOnFlip(key_resp_5, 'tStartRefresh') # time at next scr refresh key_resp_5.status = STARTED # keyboard checking is just starting waitOnFlip = True win.callOnFlip(key_resp_5.clock.reset) # t=0 on next screen flip win.callOnFlip(key_resp_5.clearEvents, eventType='keyboard') # clear events on next screen flip if key_resp_5.status == STARTED and not waitOnFlip: theseKeys = key_resp_5.getKeys(keyList=['space'], waitRelease=False) _key_resp_5_allKeys.extend(theseKeys) if len(_key_resp_5_allKeys): key_resp_5.keys = _key_resp_5_allKeys[-1].name # just the last key pressed key_resp_5.rt = _key_resp_5_allKeys[-1].rt # a response ends the routine continueRoutine = False # check for quit (typically the Esc key) if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]): core.quit() # check if all components have finished if not continueRoutine: # a component has requested a forced-end of Routine break continueRoutine = False # will revert to True if at least one component still running for thisComponent in restComponents: if hasattr(thisComponent, "status") and thisComponent.status != FINISHED: continueRoutine = True break # at least one component has not yet finished # refresh the screen if continueRoutine: # don't flip if this routine is over or we'll get a blank screen win.flip() # -------Ending Routine "rest"------- for thisComponent in restComponents: if hasattr(thisComponent, "setAutoDraw"): thisComponent.setAutoDraw(False) thisExp.addData('text_16.started', text_16.tStartRefresh) thisExp.addData('text_16.stopped', text_16.tStopRefresh) # the Routine "rest" was not non-slip safe, so reset the non-slip timer routineTimer.reset() # set up handler to look after randomisation of conditions etc loop_formal2 = data.TrialHandler(nReps=1, method='sequential', extraInfo=expInfo, originPath=-1, trialList=data.importConditions('documents\\loop2.xlsx'), seed=None, name='loop_formal2') thisExp.addLoop(loop_formal2) # add the loop to the experiment thisLoop_formal2 = loop_formal2.trialList[0] # so we can initialise stimuli with some values # abbreviate parameter names if possible (e.g. rgb = thisLoop_formal2.rgb) if thisLoop_formal2 != None: for paramName in thisLoop_formal2: exec('{} = thisLoop_formal2[paramName]'.format(paramName)) for thisLoop_formal2 in loop_formal2: currentLoop = loop_formal2 # abbreviate parameter names if possible (e.g. rgb = thisLoop_formal2.rgb) if thisLoop_formal2 != None: for paramName in thisLoop_formal2: exec('{} = thisLoop_formal2[paramName]'.format(paramName)) # ------Prepare to start Routine "formal1"------- continueRoutine = True # update component parameters for each repeat key_resp_formal1.keys = [] key_resp_formal1.rt = [] _key_resp_formal1_allKeys = [] # keep track of which components have finished formal1Components = [text, text_2, key_resp_formal1] for thisComponent in formal1Components: thisComponent.tStart = None thisComponent.tStop = None thisComponent.tStartRefresh = None thisComponent.tStopRefresh = None if hasattr(thisComponent, 'status'): thisComponent.status = NOT_STARTED # reset timers t = 0 _timeToFirstFrame = win.getFutureFlipTime(clock="now") formal1Clock.reset(-_timeToFirstFrame) # t0 is time of first possible flip frameN = -1 # -------Run Routine "formal1"------- while continueRoutine: # get current time t = formal1Clock.getTime() tThisFlip = win.getFutureFlipTime(clock=formal1Clock) tThisFlipGlobal = win.getFutureFlipTime(clock=None) frameN = frameN + 1 # number of completed frames (so 0 is the first frame) # update/draw components on each frame # *text* updates if text.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance: # keep track of start time/frame for later text.frameNStart = frameN # exact frame index text.tStart = t # local t and not account for scr refresh text.tStartRefresh = tThisFlipGlobal # on global time win.timeOnFlip(text, 'tStartRefresh') # time at next scr refresh text.setAutoDraw(True) if text.status == STARTED: # is it time to stop? (based on global clock, using actual start) if tThisFlipGlobal > text.tStartRefresh + 1.0-frameTolerance: # keep track of stop time/frame for later text.tStop = t # not accounting for scr refresh text.frameNStop = frameN # exact frame index win.timeOnFlip(text, 'tStopRefresh') # time at next scr refresh text.setAutoDraw(False) # *text_2* updates if text_2.status == NOT_STARTED and tThisFlip >= 1-frameTolerance: # keep track of start time/frame for later text_2.frameNStart = frameN # exact frame index text_2.tStart = t # local t and not account for scr refresh text_2.tStartRefresh = tThisFlipGlobal # on global time win.timeOnFlip(text_2, 'tStartRefresh') # time at next scr refresh text_2.setAutoDraw(True) # *key_resp_formal1* updates waitOnFlip = False if key_resp_formal1.status == NOT_STARTED
<gh_stars>1-10 import argparse import math import os import pickle import random import sys import numpy as np import torch import torch.backends.cudnn as cudnn from torch import nn from torch.optim import lr_scheduler from torch.utils import data import torchvision.transforms as transforms import transforms as extended_transforms from loss import prediction_stat from main import get_data_path from main.loader import get_loader from main.models import get_model from utils import dotdict, float2str # paths ROOT = '/home/wenlidai/sunets-reproduce/' RESULT = 'results' device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") def main(args): print('='*10, 'Starting', '='*10, '\n') print(device) # Set the seed for reproducing the results random.seed(args.manual_seed) np.random.seed(args.manual_seed) torch.manual_seed(args.manual_seed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(args.manual_seed) cudnn.benchmark = True # Set up results folder if not os.path.exists(os.path.join(ROOT, RESULT, 'saved_val_images')): os.makedirs(os.path.join(ROOT, RESULT, 'saved_val_images')) if not os.path.exists(os.path.join(ROOT, RESULT, 'saved_train_images')): os.makedirs(os.path.join(ROOT, RESULT, 'saved_train_images')) # Setup Dataloader data_loader = get_loader(args.dataset) input_transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) target_transform = extended_transforms.MaskToTensor() traindata = data_loader('train', n_classes=args.n_classes, transform=input_transform, target_transform=target_transform, do_transform=True) trainloader = data.DataLoader(traindata, batch_size=args.batch_size, num_workers=2, shuffle=True) valdata = data_loader('val', n_classes=args.n_classes, transform=input_transform, target_transform=target_transform) valloader = data.DataLoader(valdata, batch_size=args.batch_size, num_workers=2, shuffle=False) n_classes = traindata.n_classes n_trainsamples = len(traindata) n_iters_per_epoch = np.ceil(n_trainsamples / float(args.batch_size * args.iter_size)) # Setup Model model = get_model( name=args.arch, n_classes=n_classes, ignore_index=traindata.ignore_index, output_stride=args.output_stride, pretrained=args.pretrained, momentum_bn=args.momentum_bn, dprob=args.dprob ).to(device) epochs_done=0 X=[] Y1=[] Y1_test=[] Y2=[] Y2_test=[] avg_pixel_acc = 0 mean_class_acc = 0 mIoU = 0 avg_pixel_acc_test = 0 mean_class_acc_test = 0 mIoU_test = 0 best_mIoU = 0 best_epoch = 0 if args.model_path: model_name = args.model_path.split('.') checkpoint_name = model_name[0] + '_optimizer.pkl' checkpoint = torch.load(os.path.join(ROOT, RESULT, checkpoint_name)) optm = checkpoint['optimizer'] model.load_state_dict(checkpoint['state_dict']) split_str = model_name[0].split('_') epochs_done = int(split_str[-1]) saved_loss = pickle.load( open(os.path.join(ROOT, RESULT, "saved_loss.p"), "rb") ) saved_accuracy = pickle.load( open(os.path.join(ROOT, RESULT, "saved_accuracy.p"), "rb") ) X=saved_loss["X"][:epochs_done] Y=saved_loss["Y"][:epochs_done] Y_test=saved_loss["Y_test"][:epochs_done] avg_pixel_acc = saved_accuracy["P"][:epochs_done,:] mean_class_acc = saved_accuracy["M"][:epochs_done,:] mIoU = saved_accuracy["I"][:epochs_done,:] avg_pixel_acc_test = saved_accuracy["P_test"][:epochs_done,:] mean_class_acc_test = saved_accuracy["M_test"][:epochs_done,:] mIoU_test = saved_accuracy["I_test"][:epochs_done,:] if args.best_model_path: best_model_name = args.best_model_path.split('_') best_mIoU = float(best_model_name[-2]) best_epoch = int(best_model_name[-3]) # Learning rates: For new layers (such as final layer), we set lr to be 10x the learning rate of layers already trained bias_10x_params = filter(lambda x: ('bias' in x[0]) and ('final' in x[0]) and ('conv' in x[0]), model.named_parameters()) bias_10x_params = list(map(lambda x: x[1], bias_10x_params)) bias_params = filter(lambda x: ('bias' in x[0]) and ('final' not in x[0]), model.named_parameters()) bias_params = list(map(lambda x: x[1], bias_params)) nonbias_10x_params = filter(lambda x: (('bias' not in x[0]) or ('bn' in x[0])) and ('final' in x[0]), model.named_parameters()) nonbias_10x_params = list(map(lambda x: x[1], nonbias_10x_params)) nonbias_params = filter(lambda x: ('bias' not in x[0]) and ('final' not in x[0]), model.named_parameters()) nonbias_params = list(map(lambda x: x[1], nonbias_params)) optimizer = torch.optim.SGD([{'params': bias_params, 'lr': args.lr}, {'params': bias_10x_params, 'lr': 20 * args.lr if args.pretrained else args.lr}, {'params': nonbias_10x_params, 'lr': 10 * args.lr if args.pretrained else args.lr}, {'params': nonbias_params, 'lr': args.lr},], lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay, nesterov=(args.optim == 'Nesterov')) num_param_groups = 4 # optimizer = torch.optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay) # Setting up scheduler if args.model_path and args.restore: # Here we restore all states of optimizer optimizer.load_state_dict(optm) total_iters = n_iters_per_epoch * args.epochs lambda1 = lambda step: 0.5 + 0.5 * math.cos(np.pi * step / total_iters) scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=[lambda1]*num_param_groups, last_epoch=epochs_done*n_iters_per_epoch) # scheduler = lr_scheduler.StepLR(optimizer, step_size=20, gamma=0.1, last_epoch=epochs_done) else: # scheduler = lr_scheduler.StepLR(optimizer, step_size=20, gamma=0.1) # Here we simply restart the training # if args.T0: # total_iters = args.T0 * n_iters_per_epoch # else: total_iters = ((args.epochs - epochs_done) * n_iters_per_epoch) lambda1 = lambda step: 0.5 + 0.5 * math.cos(np.pi * step / total_iters) scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=[lambda1]*num_param_groups) global l_avg, totalclasswise_pixel_acc, totalclasswise_gtpixels, totalclasswise_predpixels global l_avg_test, totalclasswise_pixel_acc_test, totalclasswise_gtpixels_test, totalclasswise_predpixels_test global steps, steps_test criterion_sbd = nn.CrossEntropyLoss(size_average=False, ignore_index=traindata.ignore_index) criterion_lip = nn.CrossEntropyLoss(size_average=False, ignore_index=traindata.ignore_index) criterions = [criterion_sbd, criterion_lip] for epoch in range(epochs_done, args.epochs): print('='*10, 'Epoch %d' % (epoch + 1), '='*10) l_avg = [0, 0] totalclasswise_pixel_acc = [0, 0] totalclasswise_gtpixels = [0, 0] totalclasswise_predpixels = [0, 0] l_avg_test = [0, 0] totalclasswise_pixel_acc_test = [0, 0] totalclasswise_gtpixels_test = [0, 0] totalclasswise_predpixels_test = [0, 0] steps = [0, 0] steps_test = [0, 0] # scheduler.step() train(model, optimizer, criterions, trainloader, epoch, scheduler, traindata) val(model, criterions, valloader, epoch, valdata) # save the model every 5 epochs if (epoch + 1) % 5 == 0 or epoch == args.epochs - 1: if (epoch + 1) > 5: os.remove(os.path.join(ROOT, RESULT, "{}_{}_{}.pkl".format(args.arch, args.dataset, epoch - 4))) os.remove(os.path.join(ROOT, RESULT, "{}_{}_{}_optimizer.pkl".format(args.arch, args.dataset, epoch - 4))) torch.save(model, os.path.join(ROOT, RESULT, "{}_{}_{}.pkl".format(args.arch, args.dataset, epoch + 1))) torch.save({'state_dict': model.state_dict(), 'optimizer': optimizer.state_dict()}, os.path.join(ROOT, RESULT, "{}_{}_{}_optimizer.pkl".format(args.arch, args.dataset, epoch + 1))) # remove old loss & accuracy files if os.path.isfile(os.path.join(ROOT, RESULT, "saved_loss.p")): os.remove(os.path.join(ROOT, RESULT, "saved_loss.p")) if os.path.isfile(os.path.join(ROOT, RESULT, "saved_accuracy.p")): os.remove(os.path.join(ROOT, RESULT, "saved_accuracy.p")) # save train and validation loss X.append(epoch + 1) Y1.append(l_avg[0] / steps[0]) Y1_test.append(l_avg_test[0] / steps_test[0]) Y2.append(l_avg[1] / steps[1]) Y2_test.append(l_avg_test[1] / steps_test[1]) saved_loss={"X": X, "Y1": Y1, "Y2": Y2, "Y1_test": Y1_test, "Y2_test": Y2_test} pickle.dump(saved_loss, open(os.path.join(ROOT, RESULT, "saved_loss.p"), "wb")) # pixel accuracy totalclasswise_pixel_acc[0] = totalclasswise_pixel_acc[0].reshape((-1, n_classes[0])).astype(np.float32) totalclasswise_gtpixels[0] = totalclasswise_gtpixels[0].reshape((-1, n_classes[0])) totalclasswise_predpixels[0] = totalclasswise_predpixels[0].reshape((-1, n_classes[0])) totalclasswise_pixel_acc_test[0] = totalclasswise_pixel_acc_test[0].reshape((-1, n_classes[0])).astype(np.float32) totalclasswise_gtpixels_test[0] = totalclasswise_gtpixels_test[0].reshape((-1, n_classes[0])) totalclasswise_predpixels_test[0] = totalclasswise_predpixels_test[0].reshape((-1, n_classes[0])) totalclasswise_pixel_acc[1] = totalclasswise_pixel_acc[1].reshape((-1, n_classes[1])).astype(np.float32) totalclasswise_gtpixels[1] = totalclasswise_gtpixels[1].reshape((-1, n_classes[1])) totalclasswise_predpixels[1] = totalclasswise_predpixels[1].reshape((-1, n_classes[1])) totalclasswise_pixel_acc_test[1] = totalclasswise_pixel_acc_test[1].reshape((-1, n_classes[1])).astype(np.float32) totalclasswise_gtpixels_test[1] = totalclasswise_gtpixels_test[1].reshape((-1, n_classes[1])) totalclasswise_predpixels_test[1] = totalclasswise_predpixels_test[1].reshape((-1, n_classes[1])) if isinstance(avg_pixel_acc, list): avg_pixel_acc[0] = np.vstack((avg_pixel_acc[0], np.sum(totalclasswise_pixel_acc[0], axis=1) / np.sum(totalclasswise_gtpixels[0], axis=1))) mean_class_acc[0] = np.vstack((mean_class_acc[0], np.mean(totalclasswise_pixel_acc[0] / totalclasswise_gtpixels[0], axis=1))) mIoU[0] = np.vstack((mIoU[0], np.mean(totalclasswise_pixel_acc[0] / (totalclasswise_gtpixels[0] + totalclasswise_predpixels[0] - totalclasswise_pixel_acc[0]), axis=1))) avg_pixel_acc[1] = np.vstack((avg_pixel_acc[1], np.sum(totalclasswise_pixel_acc[1], axis=1) / np.sum(totalclasswise_gtpixels[1], axis=1))) mean_class_acc[1] = np.vstack((mean_class_acc[1], np.mean(totalclasswise_pixel_acc[1] / totalclasswise_gtpixels[1], axis=1))) mIoU[1] = np.vstack((mIoU[1], np.mean(totalclasswise_pixel_acc[1] / (totalclasswise_gtpixels[1] + totalclasswise_predpixels[1] - totalclasswise_pixel_acc[1]), axis=1))) avg_pixel_acc_test[0] = np.vstack((avg_pixel_acc_test[0], np.sum(totalclasswise_pixel_acc_test[0],axis=1) / np.sum(totalclasswise_gtpixels_test[0], axis=1))) mean_class_acc_test[0] = np.vstack((mean_class_acc_test[0], np.mean(totalclasswise_pixel_acc_test[0] / totalclasswise_gtpixels_test[0], axis=1))) mIoU_test[0] = np.vstack((mIoU_test[0], np.mean(totalclasswise_pixel_acc_test[0] / (totalclasswise_gtpixels_test[0] + totalclasswise_predpixels_test[0] - totalclasswise_pixel_acc_test[0]), axis=1))) avg_pixel_acc_test[1] = np.vstack((avg_pixel_acc_test[1], np.sum(totalclasswise_pixel_acc_test[1],axis=1) / np.sum(totalclasswise_gtpixels_test[1], axis=1))) mean_class_acc_test[1] = np.vstack((mean_class_acc_test[1], np.mean(totalclasswise_pixel_acc_test[1] / totalclasswise_gtpixels_test[1], axis=1))) mIoU_test[1] = np.vstack((mIoU_test[1], np.mean(totalclasswise_pixel_acc_test[1] / (totalclasswise_gtpixels_test[1] + totalclasswise_predpixels_test[1] - totalclasswise_pixel_acc_test[1]), axis=1))) else: avg_pixel_acc = [] mean_class_acc = [] mIoU = [] avg_pixel_acc.append( np.sum(totalclasswise_pixel_acc[0], axis=1) / np.sum(totalclasswise_gtpixels[0], axis=1) ) mean_class_acc.append( np.mean(totalclasswise_pixel_acc[0] / totalclasswise_gtpixels[0], axis=1) ) mIoU.append( np.mean(totalclasswise_pixel_acc[0] / (totalclasswise_gtpixels[0] + totalclasswise_predpixels[0] - totalclasswise_pixel_acc[0]), axis=1) ) avg_pixel_acc.append( np.sum(totalclasswise_pixel_acc[1], axis=1) / np.sum(totalclasswise_gtpixels[1], axis=1) ) mean_class_acc.append( np.mean(totalclasswise_pixel_acc[1] / totalclasswise_gtpixels[1], axis=1) ) mIoU.append( np.mean(totalclasswise_pixel_acc[1] / (totalclasswise_gtpixels[1] + totalclasswise_predpixels[1] - totalclasswise_pixel_acc[1]), axis=1) ) avg_pixel_acc_test = [] mean_class_acc_test = [] mIoU_test = [] avg_pixel_acc_test.append( np.sum(totalclasswise_pixel_acc_test[0], axis=1) / np.sum(totalclasswise_gtpixels_test[0], axis=1) ) mean_class_acc_test.append( np.mean(totalclasswise_pixel_acc_test[0] / totalclasswise_gtpixels_test[0], axis=1) ) mIoU_test.append( np.mean(totalclasswise_pixel_acc_test[0] / (totalclasswise_gtpixels_test[0] + totalclasswise_predpixels_test[0] - totalclasswise_pixel_acc_test[0]), axis=1) ) avg_pixel_acc_test.append( np.sum(totalclasswise_pixel_acc_test[1], axis=1) / np.sum(totalclasswise_gtpixels_test[1], axis=1) ) mean_class_acc_test.append( np.mean(totalclasswise_pixel_acc_test[1] / totalclasswise_gtpixels_test[1], axis=1) ) mIoU_test.append( np.mean(totalclasswise_pixel_acc_test[1] / (totalclasswise_gtpixels_test[1] + totalclasswise_predpixels_test[1] - totalclasswise_pixel_acc_test[1]), axis=1) ) saved_accuracy = { "X": X, "P1": avg_pixel_acc[0], "P2": avg_pixel_acc[1], "M1": mean_class_acc[0], "M2": mean_class_acc[1], "I1": mIoU[0], "I2": mIoU[1], "P1_test": avg_pixel_acc_test[0], "P2_test": avg_pixel_acc_test[1], "M1_test": mean_class_acc_test[0], "M2_test": mean_class_acc_test[1], "I1_test": mIoU_test[0], "I2_test": mIoU_test[1] } pickle.dump(saved_accuracy, open(os.path.join(ROOT, RESULT, "saved_accuracy.p"), "wb")) # print validation mIoU of both tasks this_mIoU1 = np.mean(totalclasswise_pixel_acc_test[0] / (totalclasswise_gtpixels_test[0] + totalclasswise_predpixels_test[0] - totalclasswise_pixel_acc_test[0]), axis=1)[0] this_mIoU2 = np.mean(totalclasswise_pixel_acc_test[1] / (totalclasswise_gtpixels_test[1] + totalclasswise_predpixels_test[1] - totalclasswise_pixel_acc_test[1]), axis=1)[0] print('Val: mIoU_sbd = {}, mIoU_lip = {}'.format(this_mIoU1, this_mIoU2)) def train(model, optimizer, criterions, trainloader, epoch, scheduler, data): global l_avg, totalclasswise_pixel_acc, totalclasswise_gtpixels, totalclasswise_predpixels global steps model.train() for i, (images, sbd_labels, lip_labels) in enumerate(trainloader): sbd_valid_pixel = float( (sbd_labels.data != criterions[0].ignore_index).long().sum() ) lip_valid_pixel = float( (lip_labels.data != criterions[1].ignore_index).long().sum() ) images = images.to(device) sbd_labels = sbd_labels.to(device) lip_labels = lip_labels.to(device) sbd_outputs, lip_outputs = model(images, task=2) sbd_loss = criterions[0](sbd_outputs, sbd_labels) classwise_pixel_acc, classwise_gtpixels, classwise_predpixels = prediction_stat([sbd_outputs], sbd_labels, data.n_classes[0]) classwise_pixel_acc = torch.FloatTensor([classwise_pixel_acc]) classwise_gtpixels = torch.FloatTensor([classwise_gtpixels]) classwise_predpixels = torch.FloatTensor([classwise_predpixels]) totalclasswise_pixel_acc[0] += classwise_pixel_acc.sum(0).data.numpy() totalclasswise_gtpixels[0] += classwise_gtpixels.sum(0).data.numpy() totalclasswise_predpixels[0] += classwise_predpixels.sum(0).data.numpy() sbd_total_loss = sbd_loss.sum() sbd_total_loss = sbd_total_loss / float(sbd_valid_pixel) sbd_total_loss.backward(retain_graph=True) lip_loss = criterions[1](lip_outputs, lip_labels) classwise_pixel_acc, classwise_gtpixels, classwise_predpixels = prediction_stat([lip_outputs], lip_labels, data.n_classes[1]) classwise_pixel_acc = torch.FloatTensor([classwise_pixel_acc]) classwise_gtpixels = torch.FloatTensor([classwise_gtpixels]) classwise_predpixels = torch.FloatTensor([classwise_predpixels]) totalclasswise_pixel_acc[1] += classwise_pixel_acc.sum(0).data.numpy() totalclasswise_gtpixels[1] += classwise_gtpixels.sum(0).data.numpy() totalclasswise_predpixels[1] += classwise_predpixels.sum(0).data.numpy() lip_total_loss = lip_loss.sum() lip_total_loss = lip_total_loss / float(lip_valid_pixel) lip_total_loss.backward() l_avg[0] += sbd_loss.sum().data.cpu().numpy() steps[0] += sbd_valid_pixel l_avg[1] += lip_loss.sum().data.cpu().numpy() steps[1] += lip_valid_pixel optimizer.step() optimizer.zero_grad() scheduler.step() # if (i + 1) % args.log_size == 0: # pickle.dump(images[0].cpu().numpy(), # open(os.path.join(ROOT, RESULT, "saved_train_images/" + str(epoch) + "_" + str(i) + "_input.p"), "wb")) # pickle.dump(np.transpose(data.decode_segmap(outputs[0].data.cpu().numpy().argmax(0)), [2, 0, 1]), # open(os.path.join(ROOT, RESULT, "saved_train_images/" + str(epoch) + "_" + str(i) + "_output.p"), "wb")) # pickle.dump(np.transpose(data.decode_segmap(labels[0].cpu().numpy()), [2, 0, 1]), # open(os.path.join(ROOT, RESULT, "saved_train_images/" + str(epoch) + "_"
Professional Experience found': 'ကြ်မ္းက်င္မႈအေတြ႕အၾကံဳမေတြ႕ရွိေသးပါ', 'No Profiles currently have Configurations for this Layer': 'ဤအလႊာအတြက္သီးသန္႔စီစဥ္ထားသည့္အညႊန္းမရွိေသးပါ', 'No Projections currently defined': 'လက္ရွိသတ္မွတ္ထားသည့္ ခန္႔မွန္းေျခမ်ားမရွိေသးပါ', 'No Ratings for Skill Type': 'ကြ်မ္းက်င္မႈစံနႈန္းအမ်ိဳးအစားမရွိေသးပါ', 'No Records currently available': 'လက္ရွိမွတ္တမ္းမရွိရွိနိုင္ေသးပါ', 'No Red Cross & Red Crescent National Societies currently registered': 'လက္ရွိတြင္ ၾကက္ေျခနီႏွင့္လျခမ္းနီအမ်ဳိးသားအသင္းမ်ား မွတ္ပံုတင္မထားေသးပါ', 'No Regions currently registered': 'လက္ရွိမွတ္ပံုတင္ထားေသာေဒသမ်ားမရွိေသးပါ', 'No Resource Types defined': 'သတ္မွတ္ထားသည့္အရင္းအျမစ္အမ်ိဳးအစားမရွိေသးပါ', 'No Resources in Inventory': 'စစ္တမ္းအရင္းအျမစ္မရွိပါ', 'No Response': 'တုံ႔ျပန္မႈမရွိပါ', 'No Restrictions': 'ကန္႔သတ္ခ်က္မရွိပါ', 'No Roles defined': 'သတ္မွတ္ထားေသာအခန္းက႑မရွိပါ', 'No Rooms currently registered': 'လက္ရွိမွတ္ပံုတင္ထားသည့္အခန္းမရွိပါ', 'No Sectors currently registered': 'လက္ရွိမွတ္ပံုတင္ထားသည့္က႑ဍမ်ားမရွိပါ', 'No Sectors found for this Organization': 'အဖြဲ႕အစည္းအတြက္က႑မ်ားမေတြ႕ရွိေသးပါ', 'No Services currently registered': 'လက္ရွိမွတ္ပံုတင္ထားသည့္ဝန္ေဆာင္မႈမရွိေသးပါ', 'No Services found for this Organization': 'အဖြဲ႕အစည္းအတြက္ဝန္ေဆာင္မႈမ်ားမေတြ႕ရွိေသးပါ', 'No Staff currently registered': 'လက္ရွိမွတ္ပံုတင္ထားေသာဝန္ထမ္းမရွိေသးပါ', 'No Statuses currently defined': 'သတ္မွတ္ထားသည့္အေျခအေနမ်ားမရွိေသးပါ', 'No Teams currently registered': 'လက္ရွိမွတ္ပံုတင္ထားသည့္အသင္းမ်ားမရွိေသးပါ', 'No Users currently registered': 'လက္ရွိမွတ္ပံုတင္ထားသည့္အသံုးျပုသူမ်ားမရွိေသးပါ', 'No Volunteer Cluster Positions': '‌ေစတနာလုပ္အားရွင္အစုအေဝးအဆင့္မရွိေသးပါ', 'No Volunteer Cluster Types': '‌ေစတနာလုပ္အားရွင္အစုအေဝးအမ်ိဳးအစားမ်ားမရွိေသးပါ', 'No Volunteer Clusters': 'ေစတနာလုပ္အားရွင္အစုအေဝးမရွိပါ', 'No Volunteers currently registered': 'လက္ရွိမွတ္ပံုတင္ထားသည့္ေစတနာလုပ္အားရွင္အစုအေဝးမ်ားမရွိေသးပါ', 'No access to this record!': 'ယင္းမွတ္တမ္းအတြက္အသံုးျပဳ၍မရေသးပါ', 'No contact information available': 'ဆက္သြယ္ရန္သတင္းအခ်က္အလက္မ်ား မရရွိႏိုင္ပါ', 'No contact method found': 'ဆက္သြယ္ရန္နည္းလမ္းမ်ား မေတြ႕ရပါ', 'No data available': 'အခ်က္အလက္မ်ား မရရွိနိုင္ပါ', 'No databases in this application': 'ေလွ်ာက္လႊာတင္ရန္အတြက္အေျခခံအခ်က္အလက္မရွိပါ', 'No education details currently registered': 'လက္ရွိမွတ္ပံုတင္ထားသည့္ပညာေရးဆိုင္ရာအခ်က္အလက္မ်ားမရွိပါ', 'No entries currently available': 'လက္ရွိတြင္ျဖည့္သြင္းထားသည့္အရာမ်ားမရွိေသးပါ', 'No entries found': 'ျဖည့္သြင္းထားသည့္အရာမ်ားမေတြ႕ပါ', 'No entry available': 'ဝင္ေရာက္၍ မရပါ', 'No forms to the corresponding resource have been downloaded yet.': 'ကိုက္ညီေသာအရင္းအျမစ္ကူးယူထားေသာ ပံုစံမရွိေသးပါ', 'No further users can be assigned.': 'အလုပ္တာဝန္ခြဲေဝေပးျခင္းခံရေသာေနာက္ထပ္အသံုးျပဳသူမရွိေသးပါ', 'No jobs configured yet': 'ကန္႔သတ္ထားသည့္အလုပ္မ်ားမရွိေသးပါ', 'No jobs configured': 'ကန္႔သတ္ထားသည့္အလုပ္မ်ားမရွိပါ', 'No location information defined!': 'သတ္မွတ္ထားသည့္တည္ေနရာသတင္းအခ်က္အလက္မရွိပါ', 'No match': 'ကိုက္ညီမႈမရွိပါ', 'No matching records found': 'ကိုက္ညီေသာ မွတ္တမ္းမရွိပါ', 'No options available': '‌ေရြးစရာမရွိပါ', 'No options currently available': 'လက္ရွိေရြးစရာမရွိပါ', 'No records found': 'မွတ္တမ္း မေတြ႕ရွိပါ', 'No records in this resource. Add one more records manually and then retry.': 'ဤအရင္းအျမစ္တြင္မွတ္တမ္းမရွိပါ။ မွတ္တမ္းတစ္ခုျဖည္‌့စြက္ျပီးျပန္လည္ျကိုးစားပါ', 'No records to review': 'ျပန္လည္ၾကည့္ရႈရန္ မွတ္တမ္းမရွိပါ', 'No report specified.': 'သတ္မွတ္ထားေသာသတင္းေပးပို႔မႈမရွိပါ', 'No role to delete': 'ဖ်က္ရန္ အခန္းက႑မရွိပါ', 'No roles currently assigned to this user.': 'ဤအသံုးျပဳသူအား လက္ရွိတာဝန္ခြဲေဝေပးထားေသာခန္းက႑မရွိေသးပါ', 'No staff or volunteers currently registered': 'လက္ရွိမွတ္ပံုတင္ထားေသာဝန္ထမ္းမ်ားႏွင့္ေစတနာလုပ္အားရွင္မ်ားမရွိေသးပါ', 'No users with this role at the moment.': 'လက္ရွိအခန္းက႑အားအသံုးျပဳသူမ်ားမရွိေသးပါ', 'No': 'မဟုတ္ပါ', 'None (no such record)': 'မွတ္တမ္းမ်ားတစ္ခုမွမဟုတ္ပါ', 'None of the above': 'အထက္မွအရာမ်ား တစ္ခုမွမဟုတ္ပါ', 'None': 'တစ္ခုမွမဟုတ္ပါ', 'Normal Job': 'သာမန္အလုပ္', 'Normal': 'သာမန္ျဖစ္ေသာ', 'Not installed or incorrectly configured.': 'အင္စေတာလုပ္ထားျခင္းမရွိေသးပါ (သို႔မဟုတ္) မမွန္ကန္စြာေရးသြင္းထားသည္', 'Not yet a Member of any Group': 'အဖြဲ႕တြင္အသင္းဝင္မ်ားမရရွိေသးျခင္း', 'Not yet a Member of any Team': 'အသင္းတြင္အသင္းဝင္မ်ားမရရွိေသးျခင္း', 'Note that when using geowebcache, this can be set in the GWC config.': 'Geowebcache ကိုအသံုးျပဳေသာအခါမွတ္သားထားပါ။ GWC ေရးသြင္းျခင္းျဖင့္လည္း ေဆာင္ရြက္ႏိုင္ပါသည္။', 'Note': 'ထုတ္ျပန္သည့္သတင္းအတြက္ မွတ္ခ်က္', 'Note: Make sure that all the text cells are quoted in the csv file before uploading': 'မွတ္ခ်က္: စာအကြက္မ်ားကိုမတင္မွီ csv ဖိုင္ျဖင့္ေသခ်ာေအာင္ေဆာင္ရြက္ပါ။', 'Number of Children': 'ကေလးအေရအတြက္', 'Number of Countries': 'ႏိုင္ငံအေရတြက္', 'Number of Deployments': 'ေစလႊတ္ထားေသာအေရအတြက္', 'Number of Disaster Types': 'သဘာဝေဘးအႏၱရာယ္အမ်ဳိးအစားအေရအတြက္', 'Number of Facilities': 'အေထာက္အကူျပဳပစၥည္းမ်ားအေရအတြက္', 'Number of Missions': 'အထူးတာဝန္ထမ္းေဆာင္ရသူမ်ားအေရအတြက္', 'Number of Resources': 'အရင္းအျမစ္အေရအတြက္', 'Number of Responses': 'တုံ႔ျပန္မႈအေရအတြက္', 'Number or Label on the identification tag this person is wearing (if any).': '(လုိအပ္ပါ) ဤပုဂၢိဳလ္ဝတ္ဆင္ထားသည့္ အေထာက္အထားအမွတ္အသား သုိ႔မဟုတ္ နံပါတ္', 'Number': 'နံပါတ္', 'Nutrition': 'အာဟာရတိုက္ေကၽြးျခင္း', 'Nutritional Assessments': 'အာဟာရခ်င့္ခ်ိန္မႈ', 'OCR Form Review': 'OCR ပံုစံျပန္လည္သံုးသပ္ျခင္း', 'OCR module is disabled. Ask the Server Administrator to enable it.': 'OCR ေမာ္ဂ်ဴးကိုပိတ္ထားသည္။ ဖြင့္ေပးရန္ Server Administrator ကိုဆက္သြယ္ပါ။', 'OCR review data has been stored into the database successfully.': 'OCR ျပန္လည္သံုးသပ္ျခင္းအခ်က္အလက္မ်ားကို ကြန္ပ်ဴတာအတြင္း၌ စနစ္တက်ေအာင္ျမင္စြာသိုေလွာင္ထားသည္။', 'OD Coordinator': 'OD ညွိႏႈင္းေရးမွဴး', 'OK': 'အိုေက', 'OSM file generation failed!': 'OSM ဖိုင္ေဆာင္ရြက္ျခင္းမေအာင္ျမင္ပါ', 'OSM file generation failed: %s': 'OSM ဖိုင္ေဆာင္ရြက္ျခင္းမေအာင္ျမင္ပါ: %s', 'Object': 'အရာဝတၳဳ', 'Observer': 'ေလ့လာသူ', 'Obsolete': 'အသံုးမဝင္ေတာ့ေသာ/ေခတ္ေနာက္က်ေသာ', 'Office Address': '႐ံုးခန္းတည္ေနရာလိပ္စာ', 'Office Details': '႐ံုးလုပ္ငန္းအခ်က္အလက္', 'Office Phone': '႐ံုးလုပ္ငန္းသံုးဖုန္း', 'Office Type Details': '႐ံုးခန္းအမ်ိဳးအစားေသးစိတ္ခ်က္အလက္', 'Office Type added': 'ေပါင္းထည့္ထားေသာ႐ံုးခန္းအမ်ဳိးအစား', 'Office Type deleted': 'ပယ္ဖ်က္ထားေသာ႐ံုးခန္းအမ်ဳိးအစား', 'Office Type updated': 'ျပင္ဆင္ျဖည့္စြက္ထားေသာ႐ံုးခန္းအမ်ဳိးအစား', 'Office Type': '႐ံုးခန္းအမ်ိဳးအစား', 'Office Types': '႐ံုးခန္းအမ်ဳိးအစားမ်ား', 'Office added': 'ေပါင္းထည့္ထားေသာ႐ံုးခန္း', 'Office deleted': 'ပယ္ဖ်က္ထားေသာ႐ံုးခန္း', 'Office updated': 'ျပင္ဆင္ျဖည့္စြက္ထားေသာ႐ံုးခန္း', 'Office': '႐ံုးခန္း', 'Office/Center': '႐ံုးခန္း/စင္တာ', 'Offices': '႐ံုးခန္းမ်ား', 'Old?': 'အသက္ႀကီးၿပီလား။ အရြယ္ေရာက္ၿပီလား', 'On by default?': 'ပံုေသေပၚေရာက္ရွိေနျခင္းေၾကာင့္လား။', 'Only showing accessible records!': 'နားလည္ရန္လြယ္ေသာမွတ္တမ္းမ်ားသာျပသရန္', 'Opacity': 'အလင္းပိတ္မႈ', 'Open Chart': 'ပံုစံကားခ်ပ္ကိုဖြင့္သည္', 'Open Incidents': 'ထူးျခားျဖစ္စဥ္မ်ားကိုဖြင့္သည္', 'Open Map': '‌ေျမပံုဖြင့္သည္', 'Open Report': 'အစီရင္ခံစာကိုဖြင့္သည္', 'Open Table': 'ဇယားဖြင့္သည္', 'Open recent': 'မၾကာေသးခင္ကအသံုးျပဳထားေသာအရာမ်ားကိုဖြင့္သည္', 'Open': 'ဖြင့္သည္', 'OpenStreetMap Layer': 'လမ္းျပေျမပံုအလႊာကိုဖြင့္သည္', 'OpenStreetMap OAuth Consumer Key': 'လမ္းျပေျမပံု အသံုးျပဳသူအဓိကအခ်က္', 'OpenStreetMap OAuth Consumer Secret': 'လမ္းျပေျမပံု အသံုးျပဳသူလွ်ဳိ႕ဝွက္ခ်က္', 'OpenWeatherMap Layer': 'ရာသီဥတုျပေျမပံုအလႊာကိုဖြင့္သည္', 'Opening Times': 'ဖြင့္သည့္အခ်ိန္', 'Optional password for HTTP Basic Authentication.': 'HTTP Basic Authentication အတြက္ အျခားလွ်ိဳ႕ဝွက္နံပါတ္', 'Optional selection of a MapServer map.': 'MapServer ေျမပံုတစ္ခုအတြက္ အျခားေရြးခ်ယ္မႈ', 'Optional selection of a background color.': '‌ေနာက္ခံအေရာင္အတြက္အျခားေရြးခ်ယ္မႈ', 'Optional selection of an alternate style.': 'ေနာက္ထပ္ပံုစံတစ္မ်ဳိးအတြက္အျခားေရြးခ်ယ္မႈ', 'Optional username for HTTP Basic Authentication.': 'HTTP Basic Authentication အတြက္ အျခား username', 'Optional. In GeoServer, this is the Workspace Namespace URI (not the name!). Within the WFS getCapabilities, the workspace is the FeatureType Name part before the colon(:).': 'အျခားေရြးခ်ယ္မႈ: ဤေနရာသည္ GeoServer ထဲတြင္ အလုပ္အတြက္ေနရာလြတ္ အမည္အတြက္ေနရာလြတ္ျဖစ္သည္ URI (အမည္မဟုတ္ပါ။) WFS စြမ္းေဆာင္ရည္ရရွိမႈအတြင္း အလုပ္အတြက္ေနရာလြတ္သည္ ပံုသ႑ာန္အမ်ဳိးအစားအမည္ အစိတ္အပိုင္း၏ ေကာ္လံ (:) မတိုင္မွီအစိတ္အပိုင္းျဖစ္သည္။', 'Optional. The name of an element whose contents should be a URL of an Image file put into Popups.': 'အျခားေရြးခ်ယ္မႈ: Popups အတြင္းသုိ႔ထည့္သြင္းေသာ ပံုဖိုင္တစ္ခု၏ URL တစ္ခုျဖစ္သင့္သည့္ ပါဝင္သည့္အရာမ်ား ရွိေသာအရာတစ္ခု၏အမည္', 'Optional. The name of an element whose contents should be put into Popups.': 'အျခားေရြးခ်ယ္မႈ: Popups အတြင္းသုိ႔ထည့္သြင္းေသာ ပါဝင္သင့္သည့္အရာမ်ား ရွိေသာအရာတစ္ခု၏အမည္', 'Optional. The name of the schema. In Geoserver this has the form http://host_name/geoserver/wfs/DescribeFeatureType?version=1.1.0&;typename=workspace_name:layer_name.': 'အျခားေရြးခ်ယ္မႈ: ပံုၾကမ္းျဖင့္သ႐ုပ္ေဖာ္မႈအမည္။ Geoserver ထဲတြင္ပံုစံတစ္ခုရွိသည္ http://host_name/geoserver/wfs/DescribeFeatureType?version=1.1.0&;typename=workspace_name:layer_name', 'Options': '‌ေရြးခ်ယ္မႈမ်ား', 'Or add a new language code': 'သို႔မဟုတ္ ဘာသာစကားကုဒ္အသစ္တစ္ခုေပါင္းထည့္ပါ', 'Order No': 'အစီအစဥ္နံပါတ္', 'Organisational Preparedness - NHQ and Branches': 'အဖြဲ႕အစည္းဆုိင္ရာ ႀကိဳတင္ျပင္ဆင္မႈ - NHQ ႏွင့္ ႐ံုးခြဲမ်ား', 'Organization Contact': 'အဖြဲ႕အစည္းအားဆက္သြယ္ရန္', 'Organization Details': 'အဖြဲ႕အစည္းအေသးစိတ္', 'Organization Domain Details': 'အဖြဲ႕အစည္းဒိုမိန္းအေသးစိတ္', 'Organization Domain added': 'ေပါင္းထည့္ထားေသာအဖြဲ႕အစည္းဒိုမိန္း', 'Organization Domain deleted': 'ပယ္ဖ်က္ထားေသာအဖြဲ႕အစည္းဒိုမိန္း', 'Organization Domain updated': 'ျပင္ဆင္ျဖည့္စြက္ထားေသာအဖြဲ႕အစည္းဒိုမိန္း', 'Organization Domains': 'အဖြဲ႕အစည္းဒိုမိန္းမ်ား', 'Organization Type Details': 'အဖြဲ႕အစည္းအမ်ဳိးအစားအေသးစိတ္', 'Organization Type added': 'ေပါင္းထည့္ထားေသာအဖြဲ႕အစည္းအမ်ဳိးအစား', 'Organization Type deleted': 'ပယ္ဖ်က္ထားေသာအဖြဲ႕အစည္းအမ်ဳိးအစား', 'Organization Type updated': 'ျပင္ဆင္ျဖည့္စြက္ထားေသာအဖြဲ႕အစည္းအမ်ဳိးအစား', 'Organization Type': 'အဖြဲ႕အစည္းအမ်ဳိးအစား', 'Organization Types': 'အဖြဲ႕အစည္းအမ်ဳိးအစားမ်ား', 'Organization Units': 'အဖြဲ႕အစည္းယူနစ္မ်ား', 'Organization added': 'ေပါင္းထည့္ထားေသာအဖြဲ႕အစည္း', 'Organization deleted': 'ပယ္ဖ်က္ထားေသာအဖြဲ႕အစည္း', 'Organization group': 'အဖြဲ႕အစည္းအဖြဲ႕', 'Organization updated': 'ျပင္ဆင္ျဖည့္စြက္ထားေသာအဖြဲ႕အစည္း', 'Organization': 'အဖြဲ႕အစည္း', 'Organization/Branch': 'အဖြဲ႕အစည္း/႐ံုးခြဲ', 'Organizational Development': 'အဖြဲ႕အစည္းဆိုင္ရာဖြံ႕ၿဖိဳးတိုးတက္မႈ', 'Organizations / Teams / Facilities': 'အဖြဲ႕အစည္းမ်ား/ အသင္းမ်ား/ အေထာက္အကူျပဳပစၥည္းမ်ား', 'Organizations': 'အဖြဲ႕အစည္းမ်ား', 'Organized By': 'ကဖြဲ႕စည္းထားသည္', 'Origin': 'မူလပထမ/ပင္ရင္း', 'Original': 'မူလပထမျဖစ္ေသာ', 'Other - Other events': 'အျခားျဖစ္စဥ္', 'Other Address': 'အျခားေသာ ေနရပ္လိပ္စာ', 'Other Components': 'အျခားေသာအစိတ္အပိုင္းမ်ား', 'Other Details': 'အျခားေသာ အေသးစိတ္အခ်က္အလက္မ်ား', 'Other Education': 'အျခားေသာ ပညာေရး', 'Other Employments': 'အျခားေသာ အမႈထမ္းမ်ား', 'Other Users': 'အျခားေသာ အသံုးျပဳသူမ်ား', 'Other settings can only be set by editing a file on the server': 'အျခားေသာရႈခင္းမ်ားကိုအင္တာနက္ခ်ိတ္ဆက္ထားေသာဖိုင္တစ္ခုတည္းျဖတ္ျခင္းအားျဖင့္သာျပဳျပင္နိုင္သည္', 'Other': 'အျခားေသာ', 'Others': 'အျခားသူမ်ား', 'Outreach Staff': '‌ေဒသျခားတြင္ တာဝန္ထမ္းေဆာင္ရေသာဝန္ထမ္း', 'Overlays': 'တစ္လႊာေပၚတစ္လႊာထပ္ျခင္း', 'Overview': 'ျခံဳငံုသံုးသပ္ခ်က္', 'Owned Records': 'ပိုင္ဆိုင္ထားေသာမွတ္တမ္းမ်ား', 'Owned Resources': 'ပိုင္ဆိုင္ထားေသာအရင္းအျမစ္မ်ား', 'PDF File': 'PDF ဖိုင္', 'PIL (Python Image Library) not installed': 'PIL (စပါးအံုးပံုမ်ားစာၾကည့္တိုက္) ကိုတပ္ဆင္မထားေသးပါ', 'Page': 'စာမ်က္နွာ', 'Paid': 'ရွင္းၿပီး', 'Pan Map: keep the left mouse button pressed and drag the map': 'Pan ေျမပံု: ေမာက္စ္၏ဘယ္ဘက္ခလုပ္ကိုဖိ၍ေျမပံုကိုဆြဲေရႊ႕ပါ။', 'Paper Size': 'စာရြက္အရြယ္အစား', 'Parameters': 'ကန္႔သတ္ခ်က္ေဘာင္', 'Parent needs to be of the correct level': 'မိဘမ်ားသည္မွန္ကန္ေသာအဆင့္ေရာက္ရွိရန္လိုအပ္သည္', 'Parent needs to be set for locations of level': 'မိဘမ်ားသည္တည္ေနရာအဆင့္မ်ားျပဳျပင္ရန္လိုအပ္သည္', 'Parent needs to be set': 'မိဘမ်ားသည္ျပဳျပင္ရန္လိုအပ္သည္', 'Parent': 'မိဘ', 'Parsers': 'Parser မ်ား', 'Part of the URL to call to access the Features': 'ပံုသ႑ာန္မ်ားကိုအသံုးျပဳရန္ URL အစိတ္အပိုင္း', 'Participant Details': 'ပါဝင္သူ၏အေသးစိတ္အခ်က္အလက္မ်ား', 'Participant added': 'ေပါင္းထည့္ထားေသာပါဝင္တက္ေရာက္သူ', 'Participant deleted': 'ပယ္ဖ်က္ထားေသာပါဝင္တက္ေရာက္သူ', 'Participant updated': 'ျပင္ဆင္ျဖည့္စြက္ထားေသာပါဝင္တက္ေရာက္သူ', 'Participant': 'ပါဝင္တက္ေရာက္သူ', 'Participants': 'ပါဝင္တက္ေရာက္သူမ်ား', 'Participatory Community Assessment': 'လူထုကပါဝင္ေဆာင္ရြက္သည့္ဆန္းစစ္မႈ', 'Participatory Hygiene Promotion': 'ပါဝင္ေဆာင္ရြက္သည့္က်န္းမာသန္႔ရွင္းေရးျမွင့္တင္မႈ', 'Pass': '‌ေအာင္ျမင္သည္', 'Passport Date': 'ႏိုင္ငံကူးလက္မွတ္ထုတ္ေပးသည့္ရက္စြဲ', 'Passport Expires': 'ႏိုင္ငံကူးလက္မွတ္သက္တမ္းကုန္ဆံုးမည့္ရက္စြဲ', 'Passport Issuer': 'ႏိုင္ငံကူးလက္မွတ္ထုတ္ေပးသူ', 'Passport Number': 'ႏိုင္ငံကူးလက္မွတ္နံပါတ္', 'Passport': 'ႏိုင္ငံကူးလက္မွတ္', 'Password': '<PASSWORD>္', 'Peer Support': 'တန္းတူသူမ်ားကေထာက္ပံ့မႈ', 'Pending': 'ဆိုင္းငံ့ျခင္း', 'Performance Rating': 'ေဆာင္ရြက္မႈအဆင့္သတ္မွတ္ျခင္း', 'Permanent Home Address': 'အျမဲတမ္းေနရပ္လိပ္စာ', 'Person Details': 'ကိုယ္ပိုင္အေသးစိတ္အခ်က္အလက္မ်ား', 'Person Registry': 'လူပုဂၢိဳလ္မွတ္ပံုတင္ျခင္း', 'Person added to Group': 'အဖြဲ႕သို႔ေပါင္းထည့္ထားေသာလူပုဂၢိဳလ္', 'Person added to Team': 'အသင္းသို႔ေပါင္းထည့္ထားေသာလူပုဂၢိဳလ္', 'Person added': 'ေပါင္းထည့္ထားေသာလူပုဂၢဳိလ္', 'Person deleted': 'ပယ္ဖ်က္ထားေသာလူပုဂၢဳိလ္', 'Person details updated': 'ျပင္ဆင္ျဖည့္စြက္ထားေသာလူပုဂၢဳိလ္အေသးစိတ္', 'Person must be specified!': 'ကိုယ္ပိုင္အခ်က္အလက္မ်ားကိုခြဲျခားျပသရမည္', 'Person or OU': 'လူပုဂၢိဳလ္ သုိ႔မဟုတ္ OU', 'Person removed from Group': 'လူပုဂၢဳိလ္ကိုအဖြဲ႕မွပယ္ထုတ္သည္', 'Person removed from Team': 'လူပုဂၢဳိလ္ကိုအသင္းမွပယ္ထုတ္သည္', 'Person who has actually seen the person/group.': 'လူတစ္ဦးတစ္ေယာက္/အဖြဲ႕ကို အမွန္တကယ္ျမင္ႏိုင္ေသာပုဂၢိဳလ္', 'Person': 'ပုဂၢိဳလ္', 'Personal Profile': 'ကိုယ္ေရးအက်ဥ္း', 'Personal': 'ကိုယ္ေရးကိုယ္တာ', 'Personnel': 'အမႈထမ္း', 'Persons': 'ပုဂၢိဳလ္မ်ား', 'Philippine Pesos': 'ဖိလစ္ပိုင္ႏိုင္ငံသံုးေငြ (ပီဆို)', 'Phone #': 'ဖုန္း #', 'Phone 1': 'ဖုန္းနံပါတ္ ၁', 'Phone 2': 'ဖုန္းနံပါတ္ ၂', 'Phone number is required': 'ဖုန္းနံပါတ္လိုအပ္ပါသည္', 'Phone': 'ဖုန္း', 'Photograph': 'ဓါတ္ပံု', 'Photos': 'ဓါတ္ပံုမ်ား', 'Place of Birth': '‌ေမြးဖြားသည့္ေနရာ', 'Place on Map': '‌ေျမပံုေပၚရွိေနရာ', 'Planning and Construction of Drainage Systems ': 'စီမံခ်က္နွင့္ေရနုတ္ေျမာင္းစနစ္မ်ားပါဝင္ေသာတည္ေဆာက္ေရးလုပ္ငန္း', 'Please Select a Facility': '‌အေထာက္အပံ့ပစၥည္းတစ္ခုေရြးခ်ယ္ပါ', 'Please choose a type': 'အမ်ိဳးအစားတစ္ခုကို ေရြးခ်ယ္ပါ', 'Please enter a first name': 'ပထမအမည္ကို ျဖည့္ပါ', 'Please enter a last name': '‌ေနာက္ဆံုးအမည္ကို ျဖည္‌့ပါ', 'Please enter a number only': 'နံပါတ္တစ္ခုကိုသာ ျဖည့္ပါ', 'Please enter a valid email address': 'မွန္ကန္ေသာ အီးေမးလ္လိပ္စာကို ျဖည့္ပါ', 'Please select a valid image!': 'မွန္ကန္ေသာ ပံုကို ျဖည့္ပါ', 'Please select exactly two records': 'တိက်ေသာ မွတ္တမ္းနွစ္ခုကို မွတ္သားပါ', 'Please use this field to record any additional information, including a history of the record if it is updated.': 'ေနာက္ဆံုးျဖစ္ေသာ သမိုင္းမွတ္တမ္းအပါအဝင္ ထုတ္ျပန္ထားေသာ သတင္းအခ်က္အလက္မ်ားအားမွတ္တမ္းတင္ရန္ ဤေနရာအား အသံုးျပဳပါ', 'Please use this field to record any additional information, such as Ushahidi instance IDs. Include a history of the record if it is updated.': 'Ushahidi instance IDs ကဲ့သို႔ေသာထည့္ျဖည့္ရန္ရွိသည့္ သတင္းအခ်က္အလက္မ်ားအားမွတ္တမ္းတင္ရန္ ဤေနရာအား အသံုးျပဳပါ။ ထပ္ျဖည့္မည္ဆိုပါက မွတ္တမ္းေဟာင္းမ်ားကိုပါဝင္ေအာင္ေဆာင္ရြက္ပါ။', 'PoI Type Details': 'PoI အမ်ဳိးအစားအေသးစိတ္မ်ား', 'PoI Type added': 'ေပါင္းထည့္္ထားေသာ PoI အမ်ဳိးအစား', 'PoI Type deleted': 'ပယ္ဖ်က္ထားေသာ PoI အမ်ဳိးအစား', 'PoI Type updated': 'ျပင္ဆင္ျဖည့္စြက္ထားေသာ PoI အမ်ဳိးအစား', 'PoI Types': 'PoI အမ်ဳိးအစားမ်ား', 'PoI': 'PoI အက်ဳိးတူပုဂၢိဳလ္မ်ား', 'PoIs successfully imported.': 'PoI မ်ားကိုေအာင္ျမင္စြာျဖည့္သြင္းၿပီးပါၿပီ။', 'PoIs': 'PoI မ်ား', 'Point of Interest Details': 'အက်ဳိးတူပုဂၢဳိလ္မ်ားအေသးစိတ္', 'Point of Interest added': 'ေပါင္းထည့္ထားေသာအက်ဳိးတူပုဂၢဳိလ္မ်ား', 'Point of Interest deleted': 'ပယ္ဖ်က္ထားအက်ဳိးတူပုဂၢဳိလ္မ်ား', 'Point of Interest updated': 'ျပင္ဆင္ျဖည့္စြက္ထားေသာအက်ဳိးတူပုဂၢဳိလ္မ်ား', 'Point of Interest': 'အက်ဳိးတူပုဂၢဳိလ္မ်ား', 'Points of Interest': 'အက်ဳိးတူအမွတ္မ်ား', 'Points': 'အမွတ္မ်ား', 'Policy Development': 'မူဝါဒဖြံ႕ၿဖိဳးတိုးတက္မႈ', 'Political Theory Education': 'ႏိုင္ငံေရးသီအိုရီပညာေရး', 'Polygon': 'ဗဟုဂံ', 'Poor': 'ဆင္းရဲမႈ', 'Popup Format': 'Popup ပံုစံ', 'Portable App': 'သံုးရလြယ္ေသာအပလီေကးရွင္း', 'Position': 'အဆင့္သတ္မွတ္ခ်က္', 'Positions': 'အဆင့္သတ္မွတ္ခ်က္မ်ား', 'Post Harvest Storage and Management': 'ထြန္ယက္ခ်ိန္လြန္သိုေလွာင္ျခင္းႏွင့္စီမံခန္႔ခြဲမႈ', 'Posts': 'ရာထူးမ်ား', 'Power Supply Type': 'စြမ္းအားေထာက္ပံ့မႈအမ်ိဳးအစား', 'Powered by Sahana': 'Sahana ကအာဏာအပ္ႏွင္းသည္', 'Powered by': 'ကအာဏာအပ္ႏွင္းသည္', 'Preferred Name': 'စိတ္ႀကိဳက္အမည္', 'Presence Condition': 'လက္ရွိအေျခအေန', 'Presence Log': 'လက္ရွိမွတ္တမ္း', 'Previous View': 'ယခင္အျမင္', 'Previous': 'ယခင္', 'Print': 'ပံုႏွိပ္သည္', 'Priority from 1 to 9. 1 is most preferred.': 'ဦးစားေပးသတ္မွတ္ခ်က္ ၁ မွ ၉-၁ ကို ပိုနွစ္သက္သည္', 'Priority': 'ဦးစားေပးသတ္မွတ္ခ်က္', 'Privacy': 'အေႏွာက္အယွက္ကင္းမႈ', 'Private - only to specified addresses (mentioned as recipients)': 'ပုဂၢလိက', 'Private Contacts': 'ကိုယ္ပိုင္အဆက္အသြယ္မ်ား', 'Private': 'ပုဂၢလိက', 'Procedure': 'လုပ္ထံုးလုပ္နည္း', 'Processing': 'အစီအစဥ္တက်သြားေနျခင္း', 'Profession': 'ကြ်မ္းက်င္မႈ', 'Professional Experience Details': 'ကၽြမ္းက်င္မႈဆိုင္ရာအေတြ႕အၾကံဳအေသးစိတ္', 'Professional Experience added': 'ေပါင္းထည့္ထားေသာကၽြမ္းက်င္မႈဆိုင္ရာအေတြ႕အၾကံဳ', 'Professional Experience deleted': 'ပယ္ဖ်က္ထားေသာကၽြမ္းက်င္မႈဆိုင္ရာအေတြ႕အၾကံဳ', 'Professional Experience updated': 'ျပင္ဆင္ျဖည့္စြက္ထားေသာကၽြမ္းက်င္မႈဆိုင္ရာအေတြ႕အၾကံဳ', 'Professional Experience': 'ကၽြမ္းက်င္မႈဆိုင္ရာအေတြ႕အၾကံဳ', 'Profile Configuration removed': 'ပယ္ထုတ္ထားေသာကိုယ္ေရးမွတ္တမ္းပံုသ႑ာန္', 'Profile Configuration updated': 'ျပင္ဆင္ျဖည့္စြက္ထားေသာကိုယ္ေရးမွတ္တမ္းပံုသ႑ာန္', 'Profile Configuration': 'ကိုယ္ေရးမွတ္တမ္းပံုသ႑ာန္', 'Profile Configurations': 'ကိုယ္ေရးအက်ဥ္းကိုေရးသြင္းျခင္း', 'Profile Configured': 'ေရးသြင္းထားေသာကိုယ္ေရးအက်ဥ္း', 'Profile Details': 'ကိုယ္ေရးအခ်က္အလက္အေသးစိတ္', 'Profile Page': 'မိမိကိုယ္ေရးစာမ်က္ႏွာ', 'Profile Picture': 'မိမိကိုယ္ေရးစာမ်က္ႏွာအတြက္ေခါင္းစီးဓာတ္ပံု', 'Profile Picture?': 'မိမိကိုယ္ေရးစာမ်က္ႏွာအတြက္ေခါင္းစီးဓာတ္ပံုဟုတ္ပါသလား', 'Profiles': 'ကိုယ္ေရးအက်ဥ္းမ်ား', 'Program Details': 'အစီအစဥ္အေသးစိတ္', 'Program Hours (Month)': 'ပ႐ိုဂရမ္ၾကာခ်ိန္ (လ)', 'Program Hours (Year)': 'ပ႐ိုဂရမ္ၾကာခ်ိန္ (ႏွစ္)', 'Program Volunteer': 'အစီအစဥ္အတြက္ေစတနာလုပ္အားရွင္', 'Program added': 'ျဖည့္စြက္ထားေသာအစီအစဥ္', 'Program deleted': 'ပယ္ဖ်က္ထားေသာအစီအစဥ္', 'Program updated': 'ျပင္ဆင္ျဖည့္စြက္ထားေသာအစီအစဥ္', 'Program': 'အစီအစဥ္', 'Programme Manager': 'ပ႐ိုဂရမ္မန္ေနဂ်ာ', 'Programme Preparation and Action Plan, Budget & Schedule': 'အစီအစဥ္ျပင္ဆင္ျခင္းနွင့္ လႈပ္ရွားမႈအစီအစဥ္၊ ဘတ္ဂ်တ္နွင့္ လုပ္ငန္းစဥ္', 'Programs': 'အစီအစဥ္မ်ား', 'Project Assessments and Planning': 'စီမံကိန္းဆံုးျဖတ္ခ်က္မ်ားနွင့္ အစီအစဥ္မ်ား', 'Project Officer': 'စီမံကိန္း ေရးဆြဲသူ', 'Projection Details': 'စီမံကိန္းေရးဆြဲျခင္းအေသးစိတ္', 'Projection Type': 'စီမံကိန္းေရးဆြဲျခင္းအမ်ဳိးအစား', 'Projection added': 'ေပါင္းထည့္ထားေသာစီမံကိန္းေရးဆြဲျခင္း', 'Projection deleted': 'ပယ္ဖ်က္ထားေသာစီမံကိန္းေရးဆြဲျခင္း', 'Projection updated': 'ျပင္ဆင္ျဖည့္စြက္ထားေသာစီမံကိန္းေရးဆြဲျခင္း', 'Projection': 'စီမံကိန္းေရးဆြဲျခင္း', 'Projections': 'စီမံကိန္းေရးဆြဲျခင္းမ်ား', 'Projects': 'စီမံကိန္းမ်ား', 'Proposed': 'အဆိုျပဳသည္', 'Protection': 'ကာကြယ္ျခင္း', 'Provide a password': '‌လွ်ိုဳ႕ဝွက္နံပါတ္ေပးသည္', 'Provision of Inputs': 'ထည့္သြင္းအခ်က္အလက္မ်ားကိုေစာင့္ၾကည့္ျခင္း', 'Provision of Tools and Equipment': 'ကိရိယာတန္ဆာပလာမ်ား ေထာက္ပံ့ျခင္း', 'Psychosocial Support': 'စိတ္ပိုင္းဆိုင္ရာေထာက္ပံ့မႈ', 'Public - unrestricted audiences': 'အမ်ားျပည္သူ', 'Public Contacts': 'ျပည္သူလူထုအဆက္အသြယ္', 'Public URL':
import six import os import contextlib import eventlet import ConfigParser from collections import OrderedDict import psutil import mysql.connector from simpleutil.log import log as logging from simpleutil.config import cfg from simpleutil.utils import systemutils import goperation from gopdb import common from gopdb import privilegeutils from gopdb.api import exceptions from gopdb.api.rpc.impl import DatabaseConfigBase from gopdb.api.rpc.impl import DatabaseManagerBase from gopdb.api.rpc.impl.mysql import config from goperation.utils import safe_fork if systemutils.POSIX: from simpleutil.utils.systemutils.posix import wait MYSQLSAFE = systemutils.find_executable('mysqld_safe') MYSQLINSTALL = systemutils.find_executable('mysql_install_db') SH = systemutils.find_executable('sh') BASELOG = '/var/log/mysqld.log' else: # just for windows test from simpleutil.utils.systemutils import empty as wait MYSQLSAFE = r'C:\Program Files\mysql\bin\mysqld_safe.exe' MYSQLINSTALL = r'C:\Program Files\mysql\bin\mysql_install_db.exe' SH = r'C:\Program Files\Git\bin\sh.exe' BASELOG = r'C:\temp\mysqld.log' CONF = cfg.CONF LOG = logging.getLogger(__name__) config.register_opts(CONF.find_group(common.DB)) MULTIABLEOPTS = frozenset([ 'replicate-ignore-db', ]) class MultiOrderedDict(OrderedDict): def __setitem__(self, key, value, dict_setitem=dict.__setitem__): if key in MULTIABLEOPTS and key in self: if isinstance(self[key], list): if value not in self[key]: self[key].append(value) return else: value = [self[key], value] OrderedDict.__setitem__(self, key, value, dict_setitem) class MultiConfigParser(ConfigParser.ConfigParser): def __init__(self): ConfigParser.ConfigParser.__init__(self, dict_type=MultiOrderedDict) def write(self, fp): """Write an .ini-format representation of the configuration state.""" if self._defaults: fp.write("[%s]\n" % ConfigParser.DEFAULTSECT) for (key, value) in self._defaults.items(): fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t'))) fp.write("\n") for section in self._sections: fp.write("[%s]\n" % section) for (key, value) in self._sections[section].items(): if key == "__name__": continue if (value is not None) or (self._optcre == self.OPTCRE): if isinstance(value, list): for v in value: line = " = ".join((key, str(v).replace('\n', '\n\t'))) fp.write("%s\n" % line) else: key = " = ".join((key, str(value).replace('\n', '\n\t'))) fp.write("%s\n" % key) fp.write("\n") def default_config(): cf = MultiConfigParser() cf.add_section('mysqld_safe') cf.add_section('mysqld') # mysqld_safe opts cf.set('mysqld_safe', 'log-error', '/var/log/mysqld.log') # base options cf.set('mysqld', 'server-id', 1) cf.set('mysqld', 'symbolic-links', 0) cf.set('mysqld', 'character-set-server', 'utf8') cf.set('mysqld', 'user', 'mysql') cf.set('mysqld', 'pid-file', '/var/run/mysqld/mysqld.pid') cf.set('mysqld', 'log-error', '/var/log/mysqld.log') cf.set('mysqld', 'datadir', '/data/mysql/mysqld') # network config cf.set('mysqld', 'socket', '/var/lib/mysql/mysql.sock') cf.set('mysqld', 'port', 3306) cf.set('mysqld', 'max_connect_errors', 64) cf.set('mysqld', 'back_log', 1024) cf.set('mysqld', 'max_connections', 512) cf.set('mysqld', 'thread_cache_size', 16) cf.set('mysqld', 'max_allowed_packet', 33554432) # table options cf.set('mysqld', 'max_heap_table_size', 268435456) cf.set('mysqld', 'tmp_table_size', 268435456) cf.set('mysqld', 'table_open_cache', 2048) # query options cf.set('mysqld', 'query_cache_size', 134217728) # InnoDB opts cf.set('mysqld', 'innodb_file_per_table', 1) cf.set('mysqld', 'innodb_buffer_pool_size', 4294967296) cf.set('mysqld', 'innodb_data_file_path', 'ibdata:100M:autoextend') cf.set('mysqld', 'innodb_log_buffer_size', 8388608) cf.set('mysqld', 'innodb_log_file_size', 536870912) cf.set('mysqld', 'innodb_log_files_in_group', 2) cf.set('mysqld', 'innodb_flush_log_at_trx_commit', 2) cf.set('mysqld', 'innodb_open_files', 1024) # MyISAM opts cf.set('mysqld', 'concurrent_insert', 2) cf.set('mysqld', 'key_buffer_size', 134217728) cf.set('mysqld', 'read_buffer_size', 4194304) cf.set('mysqld', 'read_rnd_buffer_size', 6291456) return cf def slave_config(cf): # Slave opts cf.set('mysqld', 'read-only', 1) cf.set('mysqld', 'relay-log', 'relay-bin') cf.set('mysqld', 'replicate-ignore-db', 'information_schema') cf.set('mysqld', 'replicate-ignore-db', 'performance_schema') cf.set('mysqld', 'replicate-ignore-db', 'sys') class MysqlConfig(DatabaseConfigBase): def __init__(self, config): # default opts if not isinstance(config, MultiConfigParser): raise TypeError('mysql config not ConfigParser') self.config = config def get(self, key): try: return self.config.get('mysqld', key) except ConfigParser.NoOptionError: return None @classmethod def load(cls, cfgfile): """load config from config file""" config = MultiConfigParser() config.read(cfgfile) return cls(config) @classmethod def loads(cls, **kwargs): """load config from kwargs""" mysql_id = kwargs.pop('entity') datadir = kwargs.pop('datadir') runuser = kwargs.pop('runuser') pidfile = kwargs.pop('pidfile') sockfile = kwargs.pop('sockfile') logfile = kwargs.pop('logfile') # binlog on/off binlog = (kwargs.pop('binlog', False) or kwargs.pop('log-bin', False)) relaylog = (kwargs.pop('relaylog', False) or kwargs.pop('relay-bin', False)) # init mysql default config config = default_config() # set mysqld_safe opts config.set('mysqld_safe', 'log-error', logfile) # read opts from kwargs for k, v in six.iteritems(kwargs): config.set('mysqld', k, v) # set default opts config.set('mysqld', 'server-id', mysql_id) config.set('mysqld', 'datadir', datadir) config.set('mysqld', 'pid-file', pidfile) config.set('mysqld', 'log-error', logfile) config.set('mysqld', 'user', runuser) # set default socket opts config.set('mysqld', 'socket', sockfile) # ste logbin if binlog: conf = CONF[common.DB] config.set('mysqld', 'log-bin', 'binlog') config.set('mysqld', 'expire_logs_days', conf.expire_log_days) config.set('mysqld', 'max_binlog_size', 270532608) if relaylog: slave_config(config) return cls(config) def save(self, cfgfile): """save config""" with open(cfgfile, 'wb') as f: self.config.write(f) def dump(self, cfgfile): """out put config""" output = {} for section in self.config.sections(): output[section] = self.config.items(section) return output def update(self, cfgfile): """update config""" config = MultiConfigParser() config.read(cfgfile) self.config = config def binlog(self): config = self.config if not self.get('log-bin'): conf = CONF[common.DB] config.set('mysqld', 'log-bin', 'binlog') config.set('mysqld', 'expire_logs_days', conf.expire_log_days) config.set('mysqld', 'max_binlog_size', 270532608) class DatabaseManager(DatabaseManagerBase): config_cls = MysqlConfig base_opts = ['--skip-name-resolve'] def _slave_status(self, conn): cursor = conn.cursor(dictionary=True) cursor.execute('SHOW ALL SLAVES STATUS') slaves = cursor.fetchall() cursor.close() return slaves def _master_status(self, conn): cursor = conn.cursor(dictionary=True) cursor.execute('SHOW MASTER STATUS') masters = cursor.fetchall() cursor.close() return masters[0] if masters else None def _schemas(self, conn): schemas = [] cursor = conn.cursor() cursor.execute('SHOW DATABASES') for result in cursor.fetchall(): schema = result[0] if schema not in common.IGNORES['mysql']: schemas.append(schema) cursor.close() return schemas def _binlog_on(self, conn): cursor = conn.cursor(dictionary=True) cursor.execute("SHOW GLOBAL VARIABLES LIKE 'log_bin'") varinfo = cursor.fetchall()[0] cursor.close() if varinfo.get('Value').lower() == 'on': return True return False @contextlib.contextmanager def _lower_conn(self, sockfile, user, passwd, schema=None, raise_on_warnings=True): kwargs = dict(user=user, passwd=<PASSWORD>, unix_socket=sockfile, raise_on_warnings=raise_on_warnings) if schema: kwargs['database'] = schema conn = mysql.connector.connect(**kwargs) try: yield conn except Exception as e: LOG.error('lower mysql connect error %s' % e.__class__.__name__) if LOG.isEnabledFor(logging.DEBUG): LOG.exception('mysql.connector exec error') raise finally: conn.close() def status(self, cfgfile, **kwargs): """status of database intance""" def start(self, cfgfile, postrun=None, timeout=None, **kwargs): """stary database intance""" args = [SH, MYSQLSAFE, '--defaults-file=%s' % cfgfile] args.extend(self.base_opts) if not systemutils.POSIX: # just for test on windows LOG.info('will call %s', ' '.join(args)) return pid = safe_fork() if pid == 0: # fork twice ppid = os.fork() if ppid == 0: os.closerange(3, systemutils.MAXFD) with open(BASELOG, 'ab') as f: os.dup2(f.fileno(), 1) os.dup2(f.fileno(), 2) try: os.execv(SH, args) except OSError: os._exit(1) else: os._exit(0) else: wait(pid) eventlet.sleep(1) def stop(self, cfgfile, postrun=None, timeout=None, **kwargs): """stop database intance""" process = kwargs.pop('process', None) timeout = timeout or 3 config = self.config_cls.load(cfgfile) pidifle = config.get('pid-file') datadir = config.get('datadir') user = config.get('user') with open(pidifle, 'rb') as f: _pid = int(f.read(4096).strip()) if process: if _pid != process.pid: raise ValueError('Process pid not match pid file') else: process = psutil.Process(_pid) cmdlines = process.cmdline() if process.username() == user and '--datadir=%s' % datadir in cmdlines: process.terminate() else: raise ValueError('Process user or cmdline not match') while timeout > 0: eventlet.sleep(1) timeout -= 1 if not process.is_running(): LOG.debug('Stop mysql process success') return raise exceptions.GopdbError('Process is running after stop') def bond(self, cfgfile, postrun, timeout, dbinfo, **kwargs): """slave bond to master database""" conf = CONF[common.DB] master = kwargs.pop('master') schemas = set(master.pop('schemas')) force = kwargs.pop('force', False) config = self.config_cls.load(cfgfile) sockfile = config.get('socket') auth = privilegeutils.mysql_slave_replprivileges(slave_id=dbinfo.get('database_id'), **master) master_name = 'masterdb-%(database_id)s' % auth sql = "CHANGE MASTER 'masterdb-%(database_id)s' TO MASTER_HOST='%(host)s', MASTER_PORT=%(port)d," \ "MASTER_USER='%(user)s',MASTER_PASSWORD='%(<PASSWORD>'," \ "MASTER_LOG_FILE='%(file)s',MASTER_LOG_POS=%(position)s" % auth LOG.info('Replication connect sql %s' % sql) with self._lower_conn(sockfile, conf.localroot, conf.localpass) as conn: LOG.info('Login mysql from unix sock %s success, try bond master' % sockfile) if schemas & set(self._schemas(conn)): raise exceptions.AcceptableSchemaError('Schema with same name exist') LOG.info('Slave channel name %s' % master_name) slaves = self._slave_status(conn) for slave_status in slaves: channel = slave_status.get('Connection_name') host = slave_status.get('Master_Host') port = slave_status.get('Master_Port') iothread = slave_status.get('Slave_IO_Running').lower() epos = slave_status.get('Exec_Master_Log_Pos') rpos = slave_status.get('Read_Master_Log_Pos') bsecond = slave_status.get('Seconds_Behind_Master') if channel != master_name and (host == auth.get('host') and port == auth.get('port')): LOG.info('Bond slave find same host and port with different channel name %s' % channel) if iothread == 'yes': raise exceptions.AcceptableDbError('Slave with channel name %s ' 'is running in same host:port' % channel) if epos != 0 or rpos != 0 or bsecond != 0: if not force: raise exceptions.AcceptableDbError('Channel %s pos not zero, need force' % channel) LOG.warning('Reset slave channel %s' % channel) if LOG.isEnabledFor(logging.DEBUG): for key in slave_status.keys(): LOG.debug('BOND FIND OLD SLAVE %s STATUS ------ %s : %s' % (channel, key, slave_status[key])) cursor = conn.cursor() cursor.execute("RESET SLAVE '%s' ALL" % channel) cursor.close() break elif channel == master_name: LOG.info('Bond slave find same channel') if host != auth.get('host') or port != auth.get('port'): if iothread == 'yes': raise exceptions.AcceptableDbError('Channel %s is running but ' 'connection is not the same' % channel) if epos != 0 or rpos != 0 or bsecond != 0: if not force: raise exceptions.AcceptableDbError('Channel %s pos not zero, need force' % channel) if LOG.isEnabledFor(logging.DEBUG): for key in slave_status.keys(): LOG.debug('BOND FIND OLD SLAVE %s STATUS ------ %s : %s' % (channel, key, slave_status[key])) if iothread == 'yes': cursor = conn.cursor() cursor.execute("STOP SLAVE '%s'" % channel) cursor.close() cursor = conn.cursor() cursor.execute("RESET SLAVE '%s' ALL" % channel) cursor.close() break cursor = conn.cursor() cursor.execute(sql) cursor.close() LOG.info('Connect to master success, try start slave') # master have no schemas auto start slave if not schemas: cursor = conn.cursor() cursor.execute("START SLAVE '%s'" % master_name) cursor.close() LOG.info('START SLAVE %s success' % master_name) if postrun: postrun() def unbond(self, cfgfile, postrun, timeout, **kwargs): """slave unbond master database"""
""" XPath selectors based on lxml """ import sys import six from lxml import etree, html from .utils import flatten, iflatten, extract_regex, shorten from .csstranslator import HTMLTranslator, GenericTranslator class CannotRemoveElementWithoutRoot(Exception): pass class CannotRemoveElementWithoutParent(Exception): pass class SafeXMLParser(etree.XMLParser): def __init__(self, *args, **kwargs): kwargs.setdefault('resolve_entities', False) super(SafeXMLParser, self).__init__(*args, **kwargs) _ctgroup = { 'html': {'_parser': html.HTMLParser, '_csstranslator': HTMLTranslator(), '_tostring_method': 'html'}, 'xml': {'_parser': SafeXMLParser, '_csstranslator': GenericTranslator(), '_tostring_method': 'xml'}, } def _st(st): if st is None: return 'html' elif st in _ctgroup: return st else: raise ValueError('Invalid type: %s' % st) def create_root_node(text, parser_cls, base_url=None): """Create root node for text using given parser class. """ body = text.strip().replace('\x00', '').encode('utf8') or b'<html/>' parser = parser_cls(recover=True, encoding='utf8') root = etree.fromstring(body, parser=parser, base_url=base_url) if root is None: root = etree.fromstring(b'<html/>', parser=parser, base_url=base_url) return root class SelectorList(list): """ The :class:`SelectorList` class is a subclass of the builtin ``list`` class, which provides a few additional methods. """ # __getslice__ is deprecated but `list` builtin implements it only in Py2 def __getslice__(self, i, j): o = super(SelectorList, self).__getslice__(i, j) return self.__class__(o) def __getitem__(self, pos): o = super(SelectorList, self).__getitem__(pos) return self.__class__(o) if isinstance(pos, slice) else o def __getstate__(self): raise TypeError("can't pickle SelectorList objects") def xpath(self, xpath, namespaces=None, **kwargs): """ Call the ``.xpath()`` method for each element in this list and return their results flattened as another :class:`SelectorList`. ``query`` is the same argument as the one in :meth:`Selector.xpath` ``namespaces`` is an optional ``prefix: namespace-uri`` mapping (dict) for additional prefixes to those registered with ``register_namespace(prefix, uri)``. Contrary to ``register_namespace()``, these prefixes are not saved for future calls. Any additional named arguments can be used to pass values for XPath variables in the XPath expression, e.g.:: selector.xpath('//a[href=$url]', url="http://www.example.com") """ return self.__class__(flatten([x.xpath(xpath, namespaces=namespaces, **kwargs) for x in self])) def css(self, query): """ Call the ``.css()`` method for each element in this list and return their results flattened as another :class:`SelectorList`. ``query`` is the same argument as the one in :meth:`Selector.css` """ return self.__class__(flatten([x.css(query) for x in self])) def re(self, regex, replace_entities=True): """ Call the ``.re()`` method for each element in this list and return their results flattened, as a list of unicode strings. By default, character entity references are replaced by their corresponding character (except for ``&amp;`` and ``&lt;``. Passing ``replace_entities`` as ``False`` switches off these replacements. """ return flatten([x.re(regex, replace_entities=replace_entities) for x in self]) def re_first(self, regex, default=None, replace_entities=True): """ Call the ``.re()`` method for the first element in this list and return the result in an unicode string. If the list is empty or the regex doesn't match anything, return the default value (``None`` if the argument is not provided). By default, character entity references are replaced by their corresponding character (except for ``&amp;`` and ``&lt;``. Passing ``replace_entities`` as ``False`` switches off these replacements. """ for el in iflatten(x.re(regex, replace_entities=replace_entities) for x in self): return el else: return default def getall(self): """ Call the ``.get()`` method for each element is this list and return their results flattened, as a list of unicode strings. """ return [x.get() for x in self] extract = getall def get(self, default=None): """ Return the result of ``.get()`` for the first element in this list. If the list is empty, return the default value. """ for x in self: return x.get() else: return default extract_first = get @property def attrib(self): """Return the attributes dictionary for the first element. If the list is empty, return an empty dict. """ for x in self: return x.attrib else: return {} def remove(self): """ Remove matched nodes from the parent for each element in this list. """ for x in self: x.remove() class Selector(object): """ :class:`Selector` allows you to select parts of an XML or HTML text using CSS or XPath expressions and extract data from it. ``text`` is a ``unicode`` object in Python 2 or a ``str`` object in Python 3 ``type`` defines the selector type, it can be ``"html"``, ``"xml"`` or ``None`` (default). If ``type`` is ``None``, the selector defaults to ``"html"``. """ __slots__ = ['text', 'namespaces', 'type', '_expr', 'root', '__weakref__', '_parser', '_csstranslator', '_tostring_method'] _default_type = None _default_namespaces = { "re": "http://exslt.org/regular-expressions", # supported in libxslt: # set:difference # set:has-same-node # set:intersection # set:leading # set:trailing "set": "http://exslt.org/sets" } _lxml_smart_strings = False selectorlist_cls = SelectorList def __init__(self, text=None, type=None, namespaces=None, root=None, base_url=None, _expr=None): self.type = st = _st(type or self._default_type) self._parser = _ctgroup[st]['_parser'] self._csstranslator = _ctgroup[st]['_csstranslator'] self._tostring_method = _ctgroup[st]['_tostring_method'] if text is not None: if not isinstance(text, six.text_type): raise TypeError("text argument should be of type %s" % six.text_type) root = self._get_root(text, base_url) elif root is None: raise ValueError("Selector needs either text or root argument") self.namespaces = dict(self._default_namespaces) if namespaces is not None: self.namespaces.update(namespaces) self.root = root self._expr = _expr def __getstate__(self): raise TypeError("can't pickle Selector objects") def _get_root(self, text, base_url=None): return create_root_node(text, self._parser, base_url=base_url) def xpath(self, query, namespaces=None, **kwargs): """ Find nodes matching the xpath ``query`` and return the result as a :class:`SelectorList` instance with all elements flattened. List elements implement :class:`Selector` interface too. ``query`` is a string containing the XPATH query to apply. ``namespaces`` is an optional ``prefix: namespace-uri`` mapping (dict) for additional prefixes to those registered with ``register_namespace(prefix, uri)``. Contrary to ``register_namespace()``, these prefixes are not saved for future calls. Any additional named arguments can be used to pass values for XPath variables in the XPath expression, e.g.:: selector.xpath('//a[href=$url]', url="http://www.example.com") """ try: xpathev = self.root.xpath except AttributeError: return self.selectorlist_cls([]) nsp = dict(self.namespaces) if namespaces is not None: nsp.update(namespaces) try: result = xpathev(query, namespaces=nsp, smart_strings=self._lxml_smart_strings, **kwargs) except etree.XPathError as exc: msg = u"XPath error: %s in %s" % (exc, query) msg = msg if six.PY3 else msg.encode('unicode_escape') six.reraise(ValueError, ValueError(msg), sys.exc_info()[2]) if type(result) is not list: result = [result] result = [self.__class__(root=x, _expr=query, namespaces=self.namespaces, type=self.type) for x in result] return self.selectorlist_cls(result) def css(self, query): """ Apply the given CSS selector and return a :class:`SelectorList` instance. ``query`` is a string containing the CSS selector to apply. In the background, CSS queries are translated into XPath queries using `cssselect`_ library and run ``.xpath()`` method. .. _cssselect: https://pypi.python.org/pypi/cssselect/ """ return self.xpath(self._css2xpath(query)) def _css2xpath(self, query): return self._csstranslator.css_to_xpath(query) def re(self, regex, replace_entities=True): """ Apply the given regex and return a list of unicode strings with the matches. ``regex`` can be either a compiled regular expression or a string which will be compiled to a regular expression using ``re.compile(regex)``. By default, character entity references are replaced by their corresponding character (except for ``&amp;`` and ``&lt;``). Passing ``replace_entities`` as ``False`` switches off these replacements. """ return extract_regex(regex, self.get(), replace_entities=replace_entities) def re_first(self, regex, default=None, replace_entities=True): """ Apply the given regex and return the first unicode string which matches. If there is no match, return the default value (``None`` if the argument is not provided). By default, character entity references are replaced by their corresponding character (except for ``&amp;`` and ``&lt;``). Passing ``replace_entities`` as ``False`` switches off these replacements. """ return next(iflatten(self.re(regex, replace_entities=replace_entities)), default) def get(self): """ Serialize and return the matched nodes in a single unicode string. Percent encoded content is unquoted. """ try: return etree.tostring(self.root, method=self._tostring_method, encoding='unicode', with_tail=False) except (AttributeError, TypeError): if self.root is True: return u'1' elif self.root is False: return u'0' else: return six.text_type(self.root) extract = get def getall(self): """ Serialize and return the matched node in a 1-element list of unicode strings. """ return [self.get()] def register_namespace(self, prefix, uri): """ Register the given namespace to be used in this :class:`Selector`. Without registering namespaces you can't select or extract data from non-standard namespaces. See :ref:`selector-examples-xml`. """ self.namespaces[prefix] = uri def remove_namespaces(self): """ Remove all namespaces, allowing to traverse the document using namespace-less xpaths. See :ref:`removing-namespaces`. """ for el in self.root.iter('*'): if el.tag.startswith('{'): el.tag = el.tag.split('}', 1)[1] # loop on element attributes also for an in el.attrib.keys(): if an.startswith('{'): el.attrib[an.split('}', 1)[1]] = el.attrib.pop(an) # remove namespace declarations etree.cleanup_namespaces(self.root) def remove(self): """ Remove matched nodes from the parent element. """ try: parent = self.root.getparent() except AttributeError: # 'str' object has no attribute 'getparent' raise CannotRemoveElementWithoutRoot( "The
) > 0: joint_grp = self.am.find_node( char, 'Joint_Grp' ) or [ ] joints = mc.listRelatives( joint_grp, c = True, ad = True, typ = 'joint' ) attrs = [ 'controlSize', 'controlSizeX', 'controlSizeY', 'controlSizeZ', 'controlOffset', 'controlOffsetX', 'controlOffsetY', 'controlOffsetZ' ] for handle in handles: tmp = { } handle_path = self.am.find_node( char, handle ) tmp[ 'data' ] = mc.getAttr( handle_path + '.aniMetaData' ) for attr in attrs: try: tmp[ attr ] = round( mc.getAttr( handle_path + '.' + attr ), 4 ) except: pass char_data[ 'handles' ][ self.am.short_name(handle) ] = tmp for joint in joints: joint_path = self.am.find_node( char, joint ) tmp = { } for attr in [ 'tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'jox', 'joy', 'joz' ]: value = mc.getAttr( joint_path + '.' + attr ) tmp[ attr ] = value if len( tmp ) > 0: char_data[ 'joints' ][ self.am.short_name(joint) ] = tmp sceneDict = self.am.get_scene_info() aniMetaDict = { } aniMetaDict[ 'aniMeta' ] = [ { 'info': sceneDict, 'data_type': 'aniMetaBiped' }, { 'data': char_data } ] pretty_json = json.dumps( aniMetaDict, indent = 4, sort_keys = True ) full_file_path = os.path.join( os.path.abspath( self.rig_path ), rig_name + '.json' ) with open( full_file_path, 'w' ) as write_file: write_file.write( pretty_json ) self.create_icon( kLibRig, rig_name + '.json' ) self.refresh( kLibRig ) print ('aniMeta: Animation written to ', full_file_path) else: print ('aniMeta: Nothing to export, please select or specify nodes.') def rig_export(self, char, fileName): metaData = self.am.get_metaData(char) rigState = None rig = Rig() if 'RigState' in metaData: rigState = metaData['RigState'] else: mc.warning('aniMeta: unable to determine the rig`s status, aborting export process.') return False if rigState != kRigStateControl: mc.warning('aniMeta: To export a rig, please put it in control mode.') else: char_data = {} char_data['root'] = {} char_data['handles'] = {} char_data['joints'] = {} for attr in mc.listAttr(char, k=True) or []: char_data['root'][attr] = mc.getAttr(char + '.' + attr) handles = rig.get_char_handles( char, {'Type': kHandle, 'Side': kAll}) or [] if len(handles) > 0: joint_grp = self.am.find_node(char, 'Joint_Grp') or [] joints = mc.listRelatives(joint_grp, c=True, ad=True, typ='joint') attrs = ['controlSize', 'controlSizeX', 'controlSizeY', 'controlSizeZ', 'controlOffset', 'controlOffsetX', 'controlOffsetY', 'controlOffsetZ'] for handle in handles: tmp = {} tmp['data'] = mc.getAttr(handle + '.aniMetaData') for attr in attrs: try: tmp[attr] = round(mc.getAttr(handle + '.' + attr), 4) except: pass char_data['handles'][handle] = tmp for joint in joints: tmp = {} for attr in ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'jox', 'joy', 'joz']: value = round(mc.getAttr(joint + '.' + attr), 4) tmp[attr] = value if len(tmp) > 0: char_data['joints'][joint] = tmp sceneDict = self.am.get_scene_info() aniMetaDict = {} aniMetaDict['aniMeta'] = [{'info': sceneDict, 'type': 'biped_rig'}, {'data': char_data}] jsonDictData = json.dumps(aniMetaDict, indent=4, sort_keys=True) f = open(fileName, 'w') f.write(jsonDictData) f.close() return True else: print ('aniMeta: Nothing to export, please select or specify nodes.') def rig_import( self, *args ): char = args[ 0 ] dict = args[ 1 ] type = kBiped info = dict[ 'aniMeta' ][ 0 ][ 'info' ] data = dict[ 'aniMeta' ][ 1 ][ 'data' ] _rig_ = Rig() _char_ = Char() _biped_ = Biped() metaData = self.am.get_metaData(char) rigState = None if 'RigState' in metaData: mc.undoInfo( openChunk=True ) mc.progressWindow() rigState = metaData['RigState'] if rigState == kRigStateControl: _char_.toggle_guides() mc.progressWindow( e = True, pr = 10 ) _char_.delete_body_guides( char ) mc.progressWindow( e = True, pr = 20 ) ############################################################################### # # Reset joints to default and apply data from dict if 'joints' in data: for key in sorted(data['joints'].keys()): if not 'Blend' in key and not 'Aux' in key: joint = self.am.find_node(char, key) if joint is not None: for attr in sorted(data['joints'][key].keys()): # Translates need to be set via the multiply node on the parent try: value = data['joints'][key][attr] mc.setAttr(joint + '.' + attr, value ) except: mc.warning('aniMeta: There is a problem setting attribute', attr, 'on joint', joint) pass else: mc.warning('aniMeta: Can not find joint', key) # Reset joints to default and apply data from dict # ############################################################################### mc.progressWindow( e = True, pr = 30 ) # Set Root Attributes if 'root' in data: rootDict = data['root'] for attr in rootDict.keys(): if mc.attributeQuery(attr, node=char, exists=True): try: mc.setAttr(char + '.' + attr, rootDict[attr]) except: pass mc.progressWindow( e = True, pr = 40 ) mm.eval('dgdirty -a;') # Build the guides so they match the joints # The guides are needed for building the control rig _char_.build_body_guides( char, type ) mc.progressWindow( e = True, pr = 60 ) # Build the control rig _biped_.build_control_rig( char ) mc.progressWindow( e = True, pr = 80 ) _biped_.build_mocap( char, type ) if 'handles' in data: handleDict = data['handles'] attrs = ['controlSize', 'controlSizeX', 'controlSizeY', 'controlSizeZ', 'controlOffset', 'controlOffsetX', 'controlOffsetY', 'controlOffsetZ'] for handle in sorted( handleDict ): handle_path = self.am.find_node( char, handle ) if handle_path is None: mc.warning('aniMeta import rig: can not find handle', handle ) continue else: for attr in attrs: if attr in handleDict[handle]: try: if handle is not None: mc.setAttr( handle_path + '.' + attr, handleDict[handle][attr]) except: pass mc.progressWindow( e = True, pr = 90 ) mc.setAttr( char + '.show_Rig', True ) mc.setAttr( char + '.show_Guides', False) self.am.update_ui() om.MGlobal.displayInfo('aniMeta: Rig preset loaded successfully.') mc.progressWindow( ep = True ) mc.undoInfo( closeChunk=True ) # Rig Import/Export # #################################################################################################################### class aniMetaTreeWidget( QTreeWidget): def __init__(self, parent = None): QTreeWidget.__init__(self, parent) def mousePressEvent (self, event): if event.button() == QtCore.Qt.LeftButton: # print( "left click !" ) self.selected() #if event.button() == QtCore.Qt.RightButton: # print( "right click !" ) QTreeWidget.mousePressEvent(self, event) def selected( self ): if self.currentItem() is not None: tree = self.currentItem().treeWidget() iterator = QTreeWidgetItemIterator( self ) # Remove empty lines that keep showing up when selecting an item with children while iterator.value(): item = iterator.value() if item.text(0) == '': parent = item.parent() parent.removeChild( item ) parent.removeChild( item ) iterator += 1 def get_index( self, item ): index = self.indexFromItem( item ) return index class aniMetaLibItem( QPushButton ): def __init__(self, *args): QPushButton.__init__(self, *args) def mouseDoubleClickEvent(self, event): path = mc.optionVar( q= 'aniMeta_lib_pose_path' ) if event.button() == QtCore.Qt.LeftButton: full_path = os.path.join( path, self.text()+'.json' ) if os.path.isfile( full_path ): lib = LibTab() lib.import_doit( kLibPose, full_path ) else: mc.warning('aniMeta pose import: invalid path', full_path ) def mousePressEvent (self, event): pass class AniMetaOptionsUI(): # the UI name for Maya name = 'aniMetaOptionsUI' def __init__( self, *args, **kwargs ): # Offset between items in the layout self.offset = 4 self.__ui__() def __ui__( self ): # Delete window, if exists if mc.window( self.name, exists = True ): mc.deleteUI( self.name ) # Create Window mc.window( self.name, title = 'aniMeta Options', w = 300, h = 400 ) ################################################################################################ # Menu mc.menuBarLayout() self.edit_menu = mc.menu( 'Settings' ) mc.menuItem( 'Save Settings', command = self.save_settings ) mc.menuItem( 'Reset Settings' ) # Menu ################################################################################################ # The main layout to arrange things self.form = mc.formLayout() # Useful for resizable UIs self.scroll = mc.scrollLayout( cr = True ) # Picker section mc.frameLayout( label = 'Picker UI' ) self.picker_btn_size = mc.optionMenuGrp( label = 'Button Size', cc = self.change_picker_button ) main_tab = MainTab() for item in main_tab.get_button_options(): mc.menuItem( label = item ) self.save_button = mc.button( label = 'Save', parent = self.form, command=self.save_settings) self.cancel_button = mc.button( label = 'Cancel', parent = self.form, command=self.delete_ui ) mc.formLayout( self.form, e = True, af = [ (self.save_button, 'bottom', self.offset), (self.save_button, 'left', self.offset) ], ap = [ (self.save_button, 'right', self.offset * 0.5, 50) ] ) mc.formLayout( self.form, e = True, af = [ (self.cancel_button, 'bottom', self.offset), (self.cancel_button, 'right', self.offset) ], ap = [ (self.cancel_button, 'left', self.offset * 0.5, 50) ] ) mc.formLayout( self.form, e = True, af = [ (self.scroll, 'left', self.offset), (self.scroll, 'right', self.offset), (self.scroll, 'top', 0), (self.scroll, 'bottom', 48) ] ) self.refresh_ui() mc.showWindow() def reset_settings( self ): # Picker button size mc.optionVar( sv = [ 'aniMetaUIButtonSize', 'Medium' ] ) def save_settings( self, *args ): value = mc.optionMenuGrp( self.picker_btn_size, query = True, value = True ) mc.optionVar( sv = [ 'aniMetaUIButtonSize', value ] ) def refresh_ui( self ): button_size = 'Medium' if mc.optionVar( exists = 'aniMetaUIButtonSize' ): button_size = mc.optionVar( query = 'aniMetaUIButtonSize' ) else: mc.optionVar( sv=('aniMetaUIButtonSize', button_size)) mc.optionMenuGrp(
import sys import multiprocessing as mp import numpy as np import time import os from rllab.algos.base import RLAlgorithm import rllab.misc.logger as logger import rllab.plotter as plotter from rllab.misc import ext from sandbox.ex2.parallel_trpo.sampler import WorkerBatchSampler from sandbox.ex2.parallel_trpo.simple_container import SimpleContainer from sandbox.ex2.utils.plot_utils import log_paths import psutil class ParallelBatchPolopt(RLAlgorithm): """ Base class for parallelized batch sampling-based policy optimization methods. This includes various parallelized policy gradient methods like vpg, npg, ppo, trpo, etc. Here, parallelized is limited to mean: using multiprocessing package. """ def __init__( self, env, policy, baseline, scope=None, n_itr=500, start_itr=0, batch_size=5000, max_path_length=500, discount=0.99, gae_lambda=1, plot_exemplar=False, plot=False, pause_for_plot=False, center_adv=True, positive_adv=False, store_paths=False, whole_paths=True, n_parallel=1, set_cpu_affinity=False, cpu_assignments=None, serial_compile=True, clip_reward=False, exemplar_cls=None, exemplar_args=None, bonus_coeff=0, path_length_scheduler=None, log_memory_usage=True, avoid_duplicate_paths=False, path_replayer=None, tmax=-1, reset_freq=-1, eval_first=False, **kwargs ): """ :param env: Environment :param policy: Policy :type policy: Policy :param baseline: Baseline :param scope: Scope for identifying the algorithm. Must be specified if running multiple algorithms simultaneously, each using different environments and policies :param n_itr: Number of iterations. :param start_itr: Starting iteration. :param batch_size: Number of samples per iteration. :param max_path_length: Maximum length of a single rollout. :param discount: Discount. :param gae_lambda: Lambda used for generalized advantage estimation. :param plot: Plot evaluation run after each iteration. :param pause_for_plot: Whether to pause before contiuing when plotting. :param center_adv: Whether to rescale the advantages so that they have mean 0 and standard deviation 1. :param positive_adv: Whether to shift the advantages so that they are always positive. When used in conjunction with center_adv the advantages will be standardized before shifting. :param store_paths: Whether to save all paths data to the snapshot. """ self.env = env self.policy = policy self.baseline = baseline self.scope = scope self.n_itr = n_itr self.current_itr = start_itr self.batch_size = batch_size self.max_path_length = max_path_length self.discount = discount self.gae_lambda = gae_lambda self.plot = plot self.pause_for_plot = pause_for_plot self.center_adv = center_adv self.positive_adv = positive_adv self.store_paths = store_paths self.whole_paths = whole_paths self.n_parallel = n_parallel self.set_cpu_affinity = set_cpu_affinity self.cpu_assignments = cpu_assignments self.serial_compile = serial_compile self.worker_batch_size = batch_size // n_parallel self.n_steps_collected = 0 # (set by sampler) self.avoid_duplicate_paths = avoid_duplicate_paths self.sampler = WorkerBatchSampler(self) self.clip_reward = clip_reward self.exemplar = None self.exemplar_cls = exemplar_cls self.exemplar_args = exemplar_args self.bonus_coeff = bonus_coeff self.path_length_scheduler = path_length_scheduler if path_length_scheduler is not None: self.path_length_scheduler.set_algo(self) self.log_memory_usage = log_memory_usage self.path_replayer = path_replayer self.tmax = tmax self.plot_exemplar = plot_exemplar self.reset_freq = reset_freq self.unpicklable_list = ["_par_objs","manager","shared_dict", "exemplar"] self.eval_first = eval_first def __getstate__(self): """ Do not pickle parallel objects. """ return { k: v for k, v in iter(self.__dict__.items()) if k not in self.unpicklable_list } # # Serial methods. # (Either for calling before forking subprocesses, or subprocesses execute # it independently of each other.) # def _init_par_objs_batchpolopt(self): """ Any init_par_objs() method in a derived class must call this method, and, following that, may append() the SimpleContainer objects as needed. """ n = self.n_parallel self.rank = None shareds = SimpleContainer( sum_discounted_return=mp.RawArray('d', n), num_traj=mp.RawArray('i', n), sum_return=mp.RawArray('d', n), max_return=mp.RawArray('d', n), min_return=mp.RawArray('d', n), sum_raw_return=mp.RawArray('d', n), max_raw_return=mp.RawArray('d', n), min_raw_return=mp.RawArray('d', n), max_bonus=mp.RawArray('d', n), min_bonus=mp.RawArray('d', n), sum_bonus=mp.RawArray('d', n), sum_path_len=mp.RawArray('i',n), max_path_len=mp.RawArray('i',n), min_path_len=mp.RawArray('i',n), num_steps=mp.RawArray('i', n), num_valids=mp.RawArray('d', n), sum_ent=mp.RawArray('d', n), ) ##HT: for explained variance (yeah I know it's clumsy) shareds.append( baseline_stats=SimpleContainer( y_sum_vec=mp.RawArray('d',n), y_square_sum_vec=mp.RawArray('d',n), y_pred_error_sum_vec=mp.RawArray('d',n), y_pred_error_square_sum_vec=mp.RawArray('d',n), ) ) barriers = SimpleContainer( dgnstc=mp.Barrier(n), ) self._par_objs = (shareds, barriers) self.baseline.init_par_objs(n_parallel=n) if self.exemplar is not None: self.exemplar.init_par_objs(n_parallel=n) def init_par_objs(self): """ Initialize all objects use for parallelism (called before forking). """ raise NotImplementedError def init_opt(self): """ Initialize the optimization procedure. If using theano / cgt, this may include declaring all the variables and compiling functions """ raise NotImplementedError def get_itr_snapshot(self, itr, samples_data): """ Returns all the data that should be saved in the snapshot for this iteration. """ raise NotImplementedError def update_plot(self): if self.plot: plotter.update_plot(self.policy, self.max_path_length) def prep_samples(self): """ Used to prepare output from sampler.process_samples() for input to optimizer.optimize(), and used in force_compile(). """ raise NotImplementedError def force_compile(self, n_samples=100): """ Serial - compile Theano (e.g. before spawning subprocesses, if desired) """ logger.log("forcing Theano compilations...") paths = self.sampler.obtain_samples(n_samples) self.process_paths(paths) samples_data, _ = self.sampler.process_samples(paths) input_values = self.prep_samples(samples_data) self.optimizer.force_compile(input_values) self.baseline.force_compile() logger.log("all compiling complete") # # Main external method and its target for parallel subprocesses. # def train(self): self.init_opt() if self.serial_compile: self.force_compile() self.init_par_objs() self.manager = mp.Manager() self.shared_dict = self.manager.dict() if self.n_parallel == 1: self._train(0,self.shared_dict) else: processes = [mp.Process(target=self._train, args=(rank,self.shared_dict)) for rank in range(self.n_parallel)] for p in processes: p.start() for p in processes: p.join() def process_paths(self, paths): if self.eval_first: for path in paths: path["raw_rewards"] = np.copy(path["rewards"]) if self.clip_reward: path["rewards"] = np.clip(path["raw_rewards"],-1,1) if self.exemplar is not None: path["bonus_rewards"] = self.exemplar.predict(path) if self.exemplar is not None: if self.reset_freq > 0 and self.current_itr % self.reset_freq == 0: self.exemplar.reset() self.exemplar.fit(paths) self.exemplar.fit(paths) else: if self.exemplar is not None: if self.reset_freq > 0 and self.current_itr % self.reset_freq == 0: self.exemplar.reset() self.exemplar.fit(paths) self.exemplar.fit(paths) for path in paths: path["raw_rewards"] = np.copy(path["rewards"]) if self.clip_reward: path["rewards"] = np.clip(path["raw_rewards"],-1,1) if self.exemplar is not None: path["bonus_rewards"] = self.exemplar.predict(path) if self.exemplar is not None: bonus_rewards = np.concatenate([path["bonus_rewards"].ravel() for path in paths]) median_bonus = np.median(bonus_rewards) mean_discrim = np.mean(1 / (bonus_rewards + 1)) for path in paths: path["bonus_rewards"] -= median_bonus path["rewards"] = path["rewards"] + self.bonus_coeff * path["bonus_rewards"] if self.rank == 0: logger.record_tabular('Median Bonus', median_bonus) logger.record_tabular('Mean Discrim', mean_discrim) def init_shared_dict(self,shared_dict): self.shared_dict = shared_dict if self.exemplar is not None: self.exemplar.init_shared_dict(shared_dict) def _train(self, rank, shared_dict): # Initialize separate exemplar per process if self.exemplar_cls is not None: self.exemplar = self.exemplar_cls(**self.exemplar_args) self.init_rank(rank) self.init_shared_dict(shared_dict) if self.rank == 0: start_time = time.time() for itr in range(self.current_itr, self.n_itr): with logger.prefix('itr #%d | ' % itr): self.update_algo_params(itr) if rank == 0: logger.log("Collecting samples ...") paths = self.sampler.obtain_samples() if rank == 0: logger.log("Processing paths...") self.process_paths(paths) if rank == 0: logger.log("processing samples...") if self.plot_exemplar: if 'bonus_rewards' in paths[0]: log_paths(paths[:20], 'traj_rewards', itr=itr) samples_data, dgnstc_data = self.sampler.process_samples(paths) self.log_diagnostics(itr, samples_data, dgnstc_data) # (parallel) if rank == 0: logger.log("optimizing policy...") if self.path_replayer is not None: replayed_paths = self.path_replayer.replay_paths() if len(replayed_paths) > 0: self.process_paths(replayed_paths) replayed_samples_data,_ = self.sampler.process_samples(replayed_paths) samples_data = self.sampler.combine_samples([ samples_data, replayed_samples_data ]) self.path_replayer.record_paths(paths) self.optimize_policy(itr, samples_data) # (parallel) if rank == 0: logger.log("fitting baseline...") # self.baseline.fit_by_samples_data(samples_data) # (parallel) self.baseline.fit(paths) if rank == 0: logger.log("fitted") logger.log("saving snapshot...") params = self.get_itr_snapshot(itr, samples_data) params["algo"] = self if self.store_paths: # NOTE: Only paths from rank==0 worker will be saved. params["paths"] = samples_data["paths"] logger.save_itr_params(itr, params) logger.log("saved") logger.record_tabular("ElapsedTime",time.time()-start_time) logger.dump_tabular(with_prefix=False) if self.plot: self.update_plot() if self.pause_for_plot: input("Plotting evaluation run: Press Enter to " "continue...") if self.log_memory_usage: process = psutil.Process(os.getpid()) print("Process %d memory usage: %.4f GB"%(rank,process.memory_info().rss / (1024**3))) if self.rank == 0 and sys.platform == "linux": print("Shared memory usage: %.4f GB"%( process.memory_info().shared / (1024**3) )) self.current_itr = itr + 1 def update_algo_params(self,itr): if self.path_length_scheduler is not None: self.path_length_scheduler.update(itr) # # Parallelized methods and related. # def log_diagnostics(self, itr, samples_data, dgnstc_data): shareds, barriers = self._par_objs i = self.rank shareds.sum_discounted_return[i] = \ np.sum([path["returns"][0] for path in samples_data["paths"]]) undiscounted_returns = [sum(path["rewards"]) for path in samples_data["paths"]] undiscounted_raw_returns = [sum(path["raw_rewards"]) for path in samples_data["paths"]] shareds.num_traj[i] = len(undiscounted_returns) shareds.num_steps[i] = self.n_steps_collected # shareds.num_steps[i] = sum([len(path["rewards"]) for path in samples_data["paths"]]) shareds.sum_return[i] = np.sum(undiscounted_returns) shareds.min_return[i] = np.min(undiscounted_returns) shareds.max_return[i] = np.max(undiscounted_returns) shareds.sum_raw_return[i] = np.sum(undiscounted_raw_returns) shareds.min_raw_return[i] = np.min(undiscounted_raw_returns) shareds.max_raw_return[i] = np.max(undiscounted_raw_returns) if self.exemplar is not None: # bonuses bonuses = np.concatenate([path["bonus_rewards"] for path in samples_data["paths"]]) shareds.max_bonus[i] = np.max(bonuses) shareds.min_bonus[i] = np.min(bonuses) shareds.sum_bonus[i] = np.sum(bonuses) if not self.policy.recurrent: shareds.sum_ent[i] = np.sum(self.policy.distribution.entropy( samples_data["agent_infos"])) shareds.num_valids[i] = 0 else: raise NotImplementedError shareds.sum_ent[i] = np.sum(self.policy.distribution.entropy( samples_data["agent_infos"]) * samples_data["valids"]) shareds.num_valids[i] = np.sum(samples_data["valids"]) # explained variance y_pred = np.concatenate(dgnstc_data["baselines"]) y = np.concatenate(dgnstc_data["returns"]) shareds.baseline_stats.y_sum_vec[i] = np.sum(y) shareds.baseline_stats.y_square_sum_vec[i] = np.sum(y**2) shareds.baseline_stats.y_pred_error_sum_vec[i] = np.sum(y-y_pred) shareds.baseline_stats.y_pred_error_square_sum_vec[i] = np.sum((y-y_pred)**2) # path lengths path_lens = [len(path["rewards"]) for path in samples_data["paths"]] shareds.sum_path_len[i] = np.sum(path_lens) shareds.max_path_len[i] = np.amax(path_lens) shareds.min_path_len[i] = np.amin(path_lens) barriers.dgnstc.wait() if self.rank == 0: self.env.log_diagnostics(samples_data["paths"]) num_traj = sum(shareds.num_traj) n_steps = sum(shareds.num_steps) average_discounted_return = \ sum(shareds.sum_discounted_return) / num_traj if self.policy.recurrent: ent = sum(shareds.sum_ent) / sum(shareds.num_valids) else: ent = sum(shareds.sum_ent) / sum(shareds.num_steps) average_return = sum(shareds.sum_return) / num_traj max_return = max(shareds.max_return) min_return = min(shareds.min_return) average_raw_return = sum(shareds.sum_raw_return) / num_traj max_raw_return = max(shareds.max_raw_return) min_raw_return = min(shareds.min_raw_return) if self.exemplar is not None: max_bonus = max(shareds.max_bonus) min_bonus = min(shareds.min_bonus) average_bonus = sum(shareds.sum_bonus) / n_steps # compute explained variance y_mean = sum(shareds.baseline_stats.y_sum_vec) / n_steps y_square_mean = sum(shareds.baseline_stats.y_square_sum_vec) / n_steps y_pred_error_mean =
* ``Vh``: (if ``full == True``) the Arnoldi basis with ``Vh.shape == (N, n+d-k)``. * ``F``: (if ``full == True``) the perturbation matrix :math:`F=-Z\hat{R}\hat{V}_n^* - \hat{V}_n\hat{R}^*Z^*`. """ n = self.n n_ = self.n_ d = self.d k = Wt.shape[1] # get orthonormal basis of Wt and Wt^\perp if k > 0: Wto, _ = scipy.linalg.qr(Wt) Wt = Wto[:, :k] Wto = Wto[:, k:] else: Wto = numpy.eye(Wt.shape[0]) deflated_solver = self._deflated_solver Pt = utils.Projection( self.L.dot(Wt), self.J.T.conj().dot(Wt) ).operator_complement() if d > 0: qt = Pt * ( numpy.vstack( [ [[deflated_solver.MMlr0_norm]], numpy.zeros((self.n_ - 1, 1)), numpy.linalg.solve(deflated_solver.E, deflated_solver.UMlr), ] ) ) else: tmp = numpy.zeros((self.n_, 1)) tmp[0] = deflated_solver.MMlr0_norm qt = Pt * tmp q = Wto.T.conj().dot(self.J.dot(qt)) # TODO: q seems to suffer from round-off errors and thus the first # vector in the computed basis may differ from the exact # projected one more than on the level of unit round-off. # rotate closest vector in [V_n,U] to first column Q = utils.House(q) q_norm = Q.xnorm # Arnoldify WtoQ = Q.apply(Wto.T.conj()).T.conj() from scipy.linalg import hessenberg Hh, T = hessenberg( Q.apply(Wto.T.conj().dot(self.J).dot(Pt * (self.L.dot(WtoQ)))), calc_q=True ) QT = Q.apply(T) # construct residual Rh = self.N.dot(Pt * self.L.dot(Wto.dot(QT))) # norm of difference between initial vectors vdiff = self.N.dot(qt) vdiff_norm = 0 if vdiff.size == 0 else numpy.linalg.norm(vdiff, 2) # compute norm of projection P_{W^\perp,AW} if k > 0: # compute coefficients of orthonormalized AW in the basis [V,Z] Y = numpy.block( [ [numpy.eye(n_), deflated_solver.B_], [numpy.zeros((d, n_)), deflated_solver.E], [numpy.zeros((self.R12.shape[0], n_)), self.R12], ] ) YL_Q, _ = scipy.linalg.qr(Y.dot(self.L.dot(Wt)), mode="economic") # compute <W,X> where X is an orthonormal basis of AW WX = Wt.T.conj().dot(numpy.vstack([YL_Q[:n, :], YL_Q[n_ : n_ + d, :]])) PWAW_norm = 1.0 / numpy.min(scipy.linalg.svdvals(WX)) else: PWAW_norm = 1.0 if full: Vh = numpy.column_stack( [deflated_solver.V[:, :n], deflated_solver.projection.U] ).dot(Wto.dot(QT)) ip_Minv_B = deflated_solver.linear_system.get_ip_Minv_B() def _apply_F(x): """Application of the perturbation.""" return -( self.Z.dot(Rh.dot(utils.inner(Vh, x, ip_B=ip_Minv_B))) + Vh.dot(Rh.T.conj().dot(utils.inner(self.Z, x, ip_B=ip_Minv_B))) ) F = utils.LinearOperator( (Vh.shape[0], Vh.shape[0]), dtype=deflated_solver.dtype, dot=_apply_F ) return Hh, Rh, q_norm, vdiff_norm, PWAW_norm, Vh, F return Hh, Rh, q_norm, vdiff_norm, PWAW_norm def bound_pseudo( arnoldifyer, Wt, g_norm=0.0, G_norm=0.0, GW_norm=0.0, WGW_norm=0.0, tol=1e-6, pseudo_type="auto", pseudo_kwargs=None, delta_n=20, terminate_factor=1.0, ): r"""Bound residual norms of next deflated system. :param arnoldifyer: an instance of :py:class:`~krypy.deflation.Arnoldifyer`. :param Wt: coefficients :math:`\tilde{W}\in\mathbb{C}^{n+d,k}` of the considered deflation vectors :math:`W` for the basis :math:`[V,U]` where ``V=last_solver.V`` and ``U=last_P.U``, i.e., :math:`W=[V,U]\tilde{W}` and :math:`\mathcal{W}=\operatorname{colspan}(W)`. Must fulfill :math:`\tilde{W}^*\tilde{W}=I_k`. :param g_norm: norm :math:`\|g\|` of difference :math:`g=c-b` of right hand sides. Has to fulfill :math:`\|g\|<\|b\|`. :param G_norm: norm :math:`\|G\|` of difference :math:`G=B-A` of operators. :param GW_norm: Norm :math:`\|G|_{\mathcal{W}}\|` of difference :math:`G=B-A` of operators restricted to :math:`\mathcal{W}`. :param WGW_norm: Norm :math:`\|\langle W,GW\rangle\|_2`. :param pseudo_type: One of * ``'auto'``: determines if :math:`\hat{H}` is non-normal, normal or Hermitian and uses the corresponding mode (see other options below). * ``'nonnormal'``: the pseudospectrum of the Hessenberg matrix :math:`\hat{H}` is used (involves one computation of a pseudospectrum) * ``'normal'``: the pseudospectrum of :math:`\hat{H}` is computed efficiently by the union of circles around the eigenvalues. * ``'hermitian'``: the pseudospectrum of :math:`\hat{H}` is computed efficiently by the union of intervals around the eigenvalues. * ``'contain'``: the pseudospectrum of the extended Hessenberg matrix :math:`\begin{bmatrix}\hat{H}\\S_i\end{bmatrix}` is used (pseudospectrum has to be re computed for each iteration). * ``'omit'``: do not compute the pseudospectrum at all and just use the residual bounds from the approximate Krylov subspace. :param pseudo_kwargs: (optional) arguments that are passed to the method that computes the pseudospectrum. :param terminate_factor: (optional) terminate the computation if the ratio of two subsequent residual norms is larger than the provided factor. Defaults to 1. """ if pseudo_kwargs is None: pseudo_kwargs = {} # Arnoldify! Hh, Rh, q_norm, vdiff_norm, PWAW_norm = arnoldifyer.get(Wt) # get original linear system ls_orig = arnoldifyer._deflated_solver.linear_system k = Wt.shape[1] if k > 0: # smallest singular value of W^*AW WAW = Wt.T.conj().dot(arnoldifyer.J.dot(arnoldifyer.L.dot(Wt))) sigma_min = numpy.min(scipy.linalg.svdvals(WAW)) if sigma_min <= WGW_norm: raise utils.AssumptionError("sigma_min(W^*AW) > ||W^*GW|| not satisfied.") eta = GW_norm / (sigma_min - WGW_norm) else: eta = 0.0 b_norm = ls_orig.MMlb_norm beta = PWAW_norm * (eta * (b_norm + g_norm) + g_norm) + vdiff_norm # check assumption on g_norm and b_norm if g_norm >= b_norm: raise utils.AssumptionError("||g_norm|| < ||b_norm|| not satisfied") # compute residual norms of Hh*z=e_1*b_norm ls_small = linsys.LinearSystem( Hh, numpy.eye(Hh.shape[0], 1) * q_norm, normal=ls_orig.normal, self_adjoint=ls_orig.self_adjoint, positive_definite=ls_orig.positive_definite, ) Solver = type(arnoldifyer._deflated_solver) if issubclass(Solver, linsys.Minres) or issubclass(Solver, linsys.Gmres): aresnorms = utils.get_residual_norms(Hh, self_adjoint=ls_orig.self_adjoint) else: # TODO: compute residuals more efficiently for CG try: solver = Solver(ls_small, tol=tol, maxiter=Hh.shape[0]) except utils.ConvergenceError as e: # use all residuals that have been computed # (useful for short recurrences) solver = e.solver aresnorms = numpy.array(solver.resnorms) # absolute residual norm aresnorms = aresnorms * q_norm if pseudo_type == "omit": return aresnorms / (b_norm - g_norm) # spectrum of Hh evals, evecs = scipy.linalg.eig(Hh) if ls_small.self_adjoint: evals = numpy.real(evals) # norm of Hh Hh_norm = numpy.linalg.norm(Hh, 2) def _auto(): """determine pseudo automatically""" # is Hh Hermitian? if numpy.linalg.norm(Hh - Hh.T.conj(), 2) < 1e-14 * Hh_norm: return "hermitian" # is Hh normal? if numpy.linalg.cond(evecs, 2) < 1 + 1e-14: return "normal" return "nonnormal" if pseudo_type == "auto": pseudo_type = _auto() # for delta >= min(|\lambda|), the pseudospectrum will contain zero and # the thus polymax > 1. nevertheless, the bound may provide useful # information in early iterations with large values of delta. # Therefore, the maximal perturbation is chosen as the maximal # eigenvalue of Hh delta_max = 1e2 * numpy.max(numpy.abs(evals)) # minimal delta is defined via Rh # HACK until numpy.linal.svd (and thus numpy.linalg.norm) is fixed from scipy.linalg import svd _, Rhsvd, _ = svd(Rh[:, :1]) delta_min = PWAW_norm * (eta * (Hh_norm + G_norm) + G_norm) + numpy.max(Rhsvd) if delta_min == 0: delta_min = 1e-16 import pseudopy if not ls_small.normal: # construct pseudospectrum for the expected range pseudo = pseudopy.NonnormalAuto( Hh, delta_min * 0.99, delta_max * 1.01, **pseudo_kwargs ) elif not ls_small.self_adjoint: pseudo = pseudopy.NormalEvals(evals) else: pseudo = None bounds = [aresnorms[0]] for i in range(1, len(aresnorms)): # compute roots of polynomial if issubclass(Solver, linsys.Cg): roots = scipy.linalg.eigvalsh(Hh[:i, :i]) else: # TODO: more stable way of computing the roots of the MINRES # poly with exploitation of symmetry? HhQ, HhR = scipy.linalg.qr(Hh[: i + 1, :i], mode="economic") roots_inv = scipy.linalg.eigvals(HhQ[:i, :].T.conj(), HhR) roots = 1.0 / roots_inv[numpy.abs(roots_inv) > 1e-14] if ls_small.self_adjoint: roots = numpy.real(roots) # compute polynomial p = utils.NormalizedRootsPolynomial(roots) if ls_small.self_adjoint: p_minmax_candidates = p.minmax_candidates() # absolute residual aresnorm = aresnorms[i] # perturbation # HACK until numpy.linal.svd (and thus numpy.linalg.norm) is fixed _, Rhsvd, _ = svd(Rh[:, :i]) Rhnrm = numpy.max(Rhsvd) epsilon = PWAW_norm * (eta * (Hh_norm + G_norm) + G_norm) + Rhnrm # + numpy.linalg.norm(Rh[:, :i], 2) if epsilon == 0: epsilon = 1e-16 if pseudo_type == "contain": raise NotImplementedError("contain not yet implemented") # exit if epsilon >= delta_max if epsilon >= delta_max: break delta_log_range = numpy.linspace( numpy.log10(1.01 * epsilon), numpy.log10(delta_max), delta_n + 2 )[0:-1] def compute_pseudo(delta_log): delta = 10 ** delta_log if ls_small.self_adjoint: # pseudospectrum are intervals pseudo_intervals = utils.Intervals( [utils.Interval(ev - delta, ev + delta) for ev in evals] ) # add roots of first derivative of p candidates = [] for candidate in p_minmax_candidates: if pseudo_intervals.contains(candidate): candidates.append(candidate) all_candidates = numpy.hstack( [pseudo_intervals.get_endpoints(), numpy.array(candidates)] ) # evaluate polynomial polymax = numpy.max(numpy.abs(p(all_candidates))) pseudolen = 2 * delta else: # get pseudospectrum paths pseudo_path = pseudo.contour_paths(delta) # length of boundary pseudolen = pseudo_path.length() # evaluate polynomial on points of path if pseudolen > 0: polymax = numpy.max(numpy.abs(p(pseudo_path.vertices()))) else: polymax = numpy.Inf # compute THE bound return ( pseudolen / (2 * numpy.pi * delta) * (epsilon / (delta - epsilon) * (q_norm + beta) + beta) * polymax ) # minimization from scipy.optimize import minimize_scalar opt_res = minimize_scalar( compute_pseudo, bounds=(delta_log_range[0], delta_log_range[-1]), method="bounded", options={"maxiter": delta_n}, ) # the delta with minimal value is min_delta = 10**opt_res.x min_val = opt_res.fun # minimal bound value boundval = aresnorm + min_val # if not increasing: append to
<filename>code_artyom/unet_17_depth_coord.py #!/usr/bin/python3.6 import os, pickle, random, subprocess, sys from typing import Any import numpy as np, pandas as pd from sklearn.model_selection import StratifiedKFold from tqdm import tqdm from skimage.io import imread, imshow from skimage.transform import resize from skimage.morphology import label from keras.models import Model, load_model, save_model from keras.layers import Input, Dropout, BatchNormalization, Activation, Add from keras.layers.core import Lambda from keras.layers.convolutional import Conv2D, Conv2DTranspose from keras.layers.pooling import MaxPooling2D from keras.layers.merge import concatenate from keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau from keras import backend as K from keras import optimizers import tensorflow as tf from keras.preprocessing.image import array_to_img, img_to_array, load_img NpArray = Any basic_name = "../output/unet_17_depth_coord" submission_file = basic_name + '.csv' NUM_FOLDS = 5 PREDICT_ONLY = True img_size_ori = 101 img_size_target = 101 def enable_logging() -> None: """ Sets up logging to a file. """ module_name = os.path.splitext(os.path.basename(__file__))[0] log_file = '../output/' + module_name + ".log" tee = subprocess.Popen(["tee", "-a", log_file], stdin=subprocess.PIPE) os.dup2(tee.stdin.fileno(), sys.stdout.fileno()) # os.dup2(tee.stdin.fileno(), sys.stderr.fileno()) def make_output_path(filename: str) -> str: """ Returns a correct file path to save to. """ module_name = os.path.splitext(os.path.basename(__file__))[0] name_ext = os.path.splitext(filename) return '../output/' + name_ext[0] + '_' + module_name + name_ext[1] def upsample(img):# not used if img_size_ori == img_size_target: return img return resize(img, (img_size_target, img_size_target), mode='constant', preserve_range=True) def downsample(img):# not used if img_size_ori == img_size_target: return img return resize(img, (img_size_ori, img_size_ori), mode='constant', preserve_range=True) def cov_to_class(val): for i in range(0, 11): if val * 10 <= i : return i def BatchActivate(x): x = BatchNormalization()(x) x = Activation('relu')(x) return x def convolution_block(x, filters, size, strides=(1,1), padding='same', activation=True): x = Conv2D(filters, size, strides=strides, padding=padding)(x) if activation==True: x = BatchActivate(x) return x def residual_block(blockInput, num_filters=16, batch_activate=False): x = BatchActivate(blockInput) x = convolution_block(x, num_filters, (3,3)) x = convolution_block(x, num_filters, (3,3), activation=False) x = Add()([x, blockInput]) if batch_activate: x = BatchActivate(x) return x # Build Model def build_model(input_layer, start_neurons, DropoutRatio=0.5): # 101 -> 50 conv1 = Conv2D(start_neurons*1, (3,3), activation=None, padding='same')(input_layer) conv1 = residual_block(conv1, start_neurons*1) conv1 = residual_block(conv1, start_neurons*1, True) pool1 = MaxPooling2D((2,2))(conv1) pool1 = Dropout(DropoutRatio/2)(pool1) # 50 -> 25 conv2 = Conv2D(start_neurons*2, (3,3), activation=None, padding='same')(pool1) conv2 = residual_block(conv2, start_neurons*2) conv2 = residual_block(conv2, start_neurons*2, True) pool2 = MaxPooling2D((2,2))(conv2) pool2 = Dropout(DropoutRatio)(pool2) # 25 -> 12 conv3 = Conv2D(start_neurons*4, (3,3), activation=None, padding='same')(pool2) conv3 = residual_block(conv3, start_neurons*4) conv3 = residual_block(conv3, start_neurons*4, True) pool3 = MaxPooling2D((2,2))(conv3) pool3 = Dropout(DropoutRatio)(pool3) # 12 -> 6 conv4 = Conv2D(start_neurons*8, (3,3), activation=None, padding='same')(pool3) conv4 = residual_block(conv4, start_neurons*8) conv4 = residual_block(conv4, start_neurons*8, True) pool4 = MaxPooling2D((2,2))(conv4) pool4 = Dropout(DropoutRatio)(pool4) # Middle convm = Conv2D(start_neurons*16, (3,3), activation=None, padding='same')(pool4) convm = residual_block(convm, start_neurons*16) convm = residual_block(convm, start_neurons*16, True) # 6 -> 12 deconv4 = Conv2DTranspose(start_neurons*8, (3,3), strides=(2,2), padding='same')(convm) uconv4 = concatenate([deconv4, conv4]) uconv4 = Dropout(DropoutRatio)(uconv4) uconv4 = Conv2D(start_neurons*8, (3,3), activation=None, padding='same')(uconv4) uconv4 = residual_block(uconv4, start_neurons*8) uconv4 = residual_block(uconv4, start_neurons*8, True) # 12 -> 25 deconv3 = Conv2DTranspose(start_neurons*4, (3,3), strides=(2,2), padding='valid')(uconv4) uconv3 = concatenate([deconv3, conv3]) uconv3 = Dropout(DropoutRatio)(uconv3) uconv3 = Conv2D(start_neurons*4, (3,3), activation=None, padding='same')(uconv3) uconv3 = residual_block(uconv3, start_neurons*4) uconv3 = residual_block(uconv3, start_neurons*4, True) # 25 -> 50 deconv2 = Conv2DTranspose(start_neurons*2, (3,3), strides=(2,2), padding='same')(uconv3) uconv2 = concatenate([deconv2, conv2]) uconv2 = Dropout(DropoutRatio)(uconv2) uconv2 = Conv2D(start_neurons*2, (3,3), activation=None, padding='same')(uconv2) uconv2 = residual_block(uconv2, start_neurons*2) uconv2 = residual_block(uconv2, start_neurons*2, True) # 50 -> 101 deconv1 = Conv2DTranspose(start_neurons*1, (3,3), strides=(2,2), padding='valid')(uconv2) uconv1 = concatenate([deconv1, conv1]) uconv1 = Dropout(DropoutRatio)(uconv1) uconv1 = Conv2D(start_neurons*1, (3,3), activation=None, padding='same')(uconv1) uconv1 = residual_block(uconv1, start_neurons*1) uconv1 = residual_block(uconv1, start_neurons*1, True) output_layer_noActi = Conv2D(1, (1,1), padding='same', activation=None)(uconv1) output_layer = Activation('sigmoid')(output_layer_noActi) return output_layer def get_iou_vector(A, B): batch_size = A.shape[0] metric = [] for batch in range(batch_size): t, p = A[batch]>0, B[batch]>0 intersection = np.logical_and(t, p) union = np.logical_or(t, p) iou = (np.sum(intersection > 0) + 1e-10 )/ (np.sum(union > 0) + 1e-10) thresholds = np.arange(0.5, 1, 0.05) s = [] for thresh in thresholds: s.append(iou > thresh) metric.append(np.mean(s)) return np.mean(metric) def my_iou_metric(label, pred): return tf.py_func(get_iou_vector, [label, pred>0.5], tf.float64) def my_iou_metric_2(label, pred): return tf.py_func(get_iou_vector, [label, pred >0], tf.float64) # code download from: https://github.com/bermanmaxim/LovaszSoftmax def lovasz_grad(gt_sorted): """ Computes gradient of the Lovasz extension w.r.t sorted errors See Alg. 1 in paper """ gts = tf.reduce_sum(gt_sorted) intersection = gts - tf.cumsum(gt_sorted) union = gts + tf.cumsum(1. - gt_sorted) jaccard = 1. - intersection / union jaccard = tf.concat((jaccard[0:1], jaccard[1:] - jaccard[:-1]), 0) return jaccard # --------------------------- BINARY LOSSES --------------------------- def lovasz_hinge(logits, labels, per_image=True, ignore=None): """ Binary Lovasz hinge loss logits: [B, H, W] Variable, logits at each pixel (between -\infty and +\infty) labels: [B, H, W] Tensor, binary ground truth masks (0 or 1) per_image: compute the loss per image instead of per batch ignore: void class id """ if per_image: def treat_image(log_lab): log, lab = log_lab log, lab = tf.expand_dims(log, 0), tf.expand_dims(lab, 0) log, lab = flatten_binary_scores(log, lab, ignore) return lovasz_hinge_flat(log, lab) losses = tf.map_fn(treat_image, (logits, labels), dtype=tf.float32) loss = tf.reduce_mean(losses) else: loss = lovasz_hinge_flat(*flatten_binary_scores(logits, labels, ignore)) return loss def lovasz_hinge_flat(logits, labels): """ Binary Lovasz hinge loss logits: [P] Variable, logits at each prediction (between -\infty and +\infty) labels: [P] Tensor, binary ground truth labels (0 or 1) ignore: label to ignore """ def compute_loss(): labelsf = tf.cast(labels, logits.dtype) signs = 2. * labelsf - 1. errors = 1. - logits * tf.stop_gradient(signs) errors_sorted, perm = tf.nn.top_k(errors, k=tf.shape(errors)[0], name="descending_sort") gt_sorted = tf.gather(labelsf, perm) grad = lovasz_grad(gt_sorted) loss = tf.tensordot(tf.nn.elu(errors_sorted), tf.stop_gradient(grad), 1, name="loss_non_void") return loss # deal with the void prediction case (only void pixels) loss = tf.cond(tf.equal(tf.shape(logits)[0], 0), lambda: tf.reduce_sum(logits) * 0., compute_loss, strict=True, name="loss" ) return loss def flatten_binary_scores(scores, labels, ignore=None): """ Flattens predictions in the batch (binary case) Remove labels equal to 'ignore' """ scores = tf.reshape(scores, (-1,)) labels = tf.reshape(labels, (-1,)) if ignore is None: return scores, labels valid = tf.not_equal(labels, ignore) vscores = tf.boolean_mask(scores, valid, name='valid_scores') vlabels = tf.boolean_mask(labels, valid, name='valid_labels') return vscores, vlabels def lovasz_loss(y_true, y_pred): y_true, y_pred = K.cast(K.squeeze(y_true, -1), 'int32'), K.cast(K.squeeze(y_pred, -1), 'float32') logits = y_pred #Jiaxin loss = lovasz_hinge(logits, y_true, per_image = True, ignore = None) return loss def train_and_predict(x_train, y_train, x_valid, y_valid, fold): # data augmentation x_train = np.append(x_train, [np.fliplr(x) for x in x_train], axis=0) y_train = np.append(y_train, [np.fliplr(x) for x in y_train], axis=0) print("x_train after hflip", x_train.shape) print("y_train after hflip", y_valid.shape) # model input_layer = Input((img_size_target, img_size_target, 3)) output_layer = build_model(input_layer, 16,0.5) model1 = Model(input_layer, output_layer) c = optimizers.adam(lr = 0.005) model1.compile(loss="binary_crossentropy", optimizer=c, metrics=[my_iou_metric]) save_model_name = f"{basic_name}_stage1_fold{fold}.hdf5" early_stopping = EarlyStopping(monitor='my_iou_metric', mode = 'max',patience=15, verbose=1) model_checkpoint = ModelCheckpoint(save_model_name, monitor='my_iou_metric', mode='max', save_best_only=True, verbose=1) reduce_lr = ReduceLROnPlateau(monitor='my_iou_metric', mode='max', factor=0.5, patience=5, min_lr=0.0001, verbose=1) epochs = 80 batch_size = 128 if not PREDICT_ONLY: history = model1.fit(x_train, y_train, validation_data = [x_valid, y_valid], epochs = epochs, batch_size = batch_size, callbacks = [early_stopping, model_checkpoint, reduce_lr], verbose = 2) model1 = load_model(save_model_name, custom_objects={'my_iou_metric':my_iou_metric}) # remove activation layer and use lovasz loss input_x = model1.layers[0].input output_layer = model1.layers[-1].input model = Model(input_x, output_layer) c = optimizers.adam(lr=0.01) model.compile(loss=lovasz_loss, optimizer=c, metrics=[my_iou_metric_2]) save_model_name = f"{basic_name}_stage2_fold{fold}.hdf5" early_stopping = EarlyStopping(monitor='val_my_iou_metric_2', mode = 'max',patience=30, verbose=1) model_checkpoint = ModelCheckpoint(save_model_name,monitor='val_my_iou_metric_2', mode = 'max', save_best_only=True, verbose=1) reduce_lr = ReduceLROnPlateau(monitor='val_my_iou_metric_2', mode = 'max',factor=0.5, patience=5, min_lr=0.00005, verbose=1) epochs = 120 batch_size = 128 if not PREDICT_ONLY: history = model.fit(x_train, y_train, validation_data=[x_valid, y_valid], epochs=epochs, batch_size=batch_size, callbacks=[ model_checkpoint,reduce_lr,early_stopping], verbose=2) model = load_model(save_model_name,custom_objects={'my_iou_metric_2': my_iou_metric_2, 'lovasz_loss': lovasz_loss}) def predict_result(model,x_test,img_size_target): # predict both orginal and reflect x x_test_reflect = np.array([np.fliplr(x) for x in x_test]) preds_test = model.predict(x_test).reshape(-1, img_size_target, img_size_target) preds_test2_refect = model.predict(x_test_reflect).reshape(-1, img_size_target, img_size_target) preds_test += np.array([ np.fliplr(x) for x in preds_test2_refect] ) return preds_test/2 preds_valid = predict_result(model,x_valid,img_size_target) preds_test = predict_result(model,x_test,img_size_target) return preds_valid, preds_test #Score the model and do a threshold optimization by the best IoU. # src: https://www.kaggle.com/aglotero/another-iou-metric def iou_metric(y_true_in, y_pred_in, print_table=False): labels = y_true_in y_pred = y_pred_in true_objects = 2 pred_objects = 2 # if all zeros, original code generate wrong bins [-0.5 0 0.5], temp1 = np.histogram2d(labels.flatten(), y_pred.flatten(), bins=([0,0.5,1], [0,0.5, 1])) # temp1 = np.histogram2d(labels.flatten(), y_pred.flatten(), bins=(true_objects, pred_objects)) #print(temp1) intersection = temp1[0] #print("temp2 = ",temp1[1]) #print(intersection.shape) # print(intersection) # Compute areas (needed for finding the union between all objects) #print(np.histogram(labels, bins = true_objects)) area_true = np.histogram(labels,bins=[0,0.5,1])[0] #print("area_true = ",area_true) area_pred = np.histogram(y_pred, bins=[0,0.5,1])[0] area_true = np.expand_dims(area_true, -1) area_pred = np.expand_dims(area_pred, 0) # Compute union union = area_true + area_pred - intersection # Exclude background from the analysis intersection = intersection[1:,1:] intersection[intersection == 0] = 1e-9 union = union[1:,1:] union[union == 0] = 1e-9 # Compute the intersection
load("//ocaml:providers.bzl", "OcamlArchiveProvider", "OcamlImportProvider", "OcamlSignatureProvider", "OcamlLibraryProvider", "OcamlModuleProvider", "OcamlNsArchiveProvider", "OcamlNsLibraryProvider", "OcamlNsResolverProvider", "PpxArchiveProvider", "PpxExecutableProvider", "PpxLibraryProvider", "PpxModuleProvider", "PpxNsArchiveProvider", "PpxNsLibraryProvider") load("//ocaml/_transitions:transitions.bzl", "ocaml_module_deps_out_transition") load("//ocaml/_transitions:ns_transitions.bzl", "ocaml_module_cc_deps_out_transition", "ocaml_nslib_main_out_transition", "ocaml_nslib_submodules_out_transition", # "ocaml_nslib_sublibs_out_transition", "ocaml_nslib_ns_out_transition", ) ## Naming conventions: # # * hidden prefix: '_' (e.g. _rule) # * ns config state prefix: '__' (i.e. label atts) ################ def options(ws): ws = "@" + ws return dict( opts = attr.string_list( doc = "List of OCaml options. Will override configurable default options." ), ## GLOBAL CONFIGURABLE DEFAULTS (all ppx_* rules) _debug = attr.label(default = ws + "//debug"), _cmt = attr.label(default = ws + "//cmt"), _keep_locs = attr.label(default = ws + "//keep-locs"), _noassert = attr.label(default = ws + "//noassert"), _opaque = attr.label(default = ws + "//opaque"), _short_paths = attr.label(default = ws + "//short-paths"), _strict_formats = attr.label(default = ws + "//strict-formats"), _strict_sequence = attr.label(default = ws + "//strict-sequence"), _verbose = attr.label(default = ws + "//verbose"), _mode = attr.label( default = ws + "//mode", ), _sdkpath = attr.label( default = Label("@ocaml//:path") # ppx also uses this ), _cc_toolchain = attr.label( default = Label("@bazel_tools//tools/cpp:current_cc_toolchain"), ), ) ####################### def options_executable(ws): ws = "@" + ws attrs = dict( _linkall = attr.label(default = ws + "//executable/linkall"), _thread = attr.label(default = ws + "//executable/thread"), _warnings = attr.label(default = ws + "//executable:warnings"), _opts = attr.label( doc = "Hidden options.", default = "@ocaml//executable:opts" ), _sdkpath = attr.label( default = Label("@ocaml//:path") ), main = attr.label( doc = "Label of module containing entry point of executable. This module will be placed last in the list of dependencies.", providers = [[OcamlModuleProvider], [PpxModuleProvider]], default = None ), data = attr.label_list( allow_files = True, doc = "Runtime dependencies: list of labels of data files needed by this executable at runtime." ), strip_data_prefixes = attr.bool( doc = "Symlink each data file to the basename part in the runfiles root directory. E.g. test/foo.data -> foo.data.", default = False ), deps = attr.label_list( doc = "List of OCaml dependencies.", providers = [[OcamlArchiveProvider], [OcamlLibraryProvider], [OcamlModuleProvider], [OcamlNsArchiveProvider], [OcamlNsLibraryProvider], [PpxArchiveProvider], [PpxLibraryProvider], [PpxModuleProvider], [PpxNsArchiveProvider], [PpxNsLibraryProvider], [CcInfo]], ), _deps = attr.label( doc = "Dependency to be added last.", default = "@ocaml//executable:deps" ), deps_opam = attr.string_list( doc = "List of OPAM package names" ), deps_adjunct = attr.label_list( doc = """List of non-opam adjunct dependencies (labels).""", # providers = [[DefaultInfo], [PpxModuleProvider]] ), deps_adjunct_opam = attr.string_list( doc = """List of opam adjunct dependencies (pkg name strings).""", ), cc_deps = attr.label_keyed_string_dict( doc = """Dictionary specifying C/C++ library dependencies. Key: a target label; value: a linkmode string, which determines which file to link. Valid linkmodes: 'default', 'static', 'dynamic', 'shared' (synonym for 'dynamic'). For more information see [CC Dependencies: Linkmode](../ug/cc_deps.md#linkmode). """, ## FIXME: cc libs could come from LSPs that do not support CcInfo, e.g. rules_rust # providers = [[CcInfo]] ), _cc_deps = attr.label( doc = "Global C/C++ library dependencies. Apply to all instances of ocaml_executable.", ## FIXME: cc libs could come from LSPs that do not support CcInfo, e.g. rules_rust # providers = [[CcInfo]] default = "@ocaml//executable:cc_deps" ), cc_linkall = attr.label_list( ## equivalent to cc_library's "alwayslink" doc = "True: use `-whole-archive` (GCC toolchain) or `-force_load` (Clang toolchain). Deps in this attribute must also be listed in cc_deps.", # providers = [CcInfo], ), cc_linkopts = attr.string_list( doc = "List of C/C++ link options. E.g. `[\"-lstd++\"]`.", ), _mode = attr.label( default = ws + "//mode" ), # _allowlist_function_transition = attr.label( # default = "@bazel_tools//tools/allowlists/function_transition_allowlist" # ), ) return attrs ####################### def options_library(ws): if ws == "ocaml": _providers = [ [OcamlArchiveProvider], [OcamlImportProvider], [OcamlLibraryProvider], [OcamlModuleProvider], [OcamlNsResolverProvider], [OcamlNsArchiveProvider], [OcamlNsLibraryProvider], [OcamlSignatureProvider], [PpxArchiveProvider] ] else: _providers =[ [PpxLibraryProvider], [PpxModuleProvider], [PpxArchiveProvider] ] return dict( modules = attr.label_list( doc = "List of component modules.", providers = _providers ) ) ####################### def options_module(ws): if ws == "ocaml": providers = [[OcamlArchiveProvider], [OcamlImportProvider], [OcamlSignatureProvider], [OcamlLibraryProvider], [OcamlModuleProvider], [OcamlNsArchiveProvider], [OcamlNsLibraryProvider], # [OcamlNsResolverProvider], [PpxArchiveProvider], [PpxModuleProvider], [PpxNsArchiveProvider], [PpxNsLibraryProvider]] else: ## FIXME: providers for ppx_module providers = [] ws = "@" + ws return dict( _opts = attr.label(default = ws + "//module:opts"), # string list _linkall = attr.label(default = ws + "//module/linkall"), # bool _thread = attr.label(default = ws + "//module/thread"), # bool _warnings = attr.label(default = ws + "//module:warnings"), # string list struct = attr.label( doc = "A single module (struct) source file label.", mandatory = True, allow_single_file = True # no constraints on extension ), sig = attr.label( doc = "Single label of a target producing OcamlSignatureProvider (i.e. rule 'ocaml_signature'). Optional.", # allow_single_file = [".cmi"], providers = [OcamlSignatureProvider], cfg = ocaml_module_deps_out_transition ), implements = attr.label( doc = "Virtual module implementations must specify the interface's library in this if it is namespaced.", providers = [[OcamlNsLibraryProvider], [PpxNsLibraryProvider]], ), ################ deps = attr.label_list( doc = "List of OCaml dependencies.", providers = providers, # transition undoes changes that may have been made by ns_lib cfg = ocaml_module_deps_out_transition ), _allowlist_function_transition = attr.label( default = "@bazel_tools//tools/allowlists/function_transition_allowlist" ), _deps = attr.label( doc = "Global deps, apply to all instances of rule. Added last.", default = ws + "//module:deps" ), deps_opam = attr.string_list( doc = "List of OPAM package names" ), data = attr.label_list( allow_files = True, doc = "Runtime dependencies: list of labels of data files needed by this module at runtime." ), ################ cc_deps = attr.label_keyed_string_dict( doc = """Dictionary specifying C/C++ library dependencies. Key: a target label; value: a linkmode string, which determines which file to link. Valid linkmodes: 'default', 'static', 'dynamic', 'shared' (synonym for 'dynamic'). For more information see [CC Dependencies: Linkmode](../ug/cc_deps.md#linkmode). """, # providers = [[CcInfo]] cfg = ocaml_module_cc_deps_out_transition ), _cc_deps = attr.label( doc = "Global cc-deps, apply to all instances of rule. Added last.", default = ws + "//module:deps" ), ################ # ns = attr.label( # doc = "Label of ocaml_ns target" # ), _ns_resolver = attr.label( doc = "Experimental", providers = [OcamlNsResolverProvider], default = "@ocaml//ns", ), _ns_submodules = attr.label( doc = "Experimental. May be set by ocaml_ns_library containing this module as a submodule.", default = "@ocaml//ns:submodules", # => string_list_setting # allow_files = True, # mandatory = True ), _ns_strategy = attr.label( doc = "Experimental", default = "@ocaml//ns:strategy" ), ) ####################### def options_ns_archive(ws): if ws == "ocaml": _submod_providers = [ [OcamlModuleProvider], [OcamlNsArchiveProvider], [OcamlNsLibraryProvider], [OcamlSignatureProvider] ] else: _submod_providers = [ [OcamlModuleProvider], [OcamlNsArchiveProvider], [OcamlNsLibraryProvider], [OcamlSignatureProvider], [PpxModuleProvider], ] ws = "@" + ws return dict( _linkall = attr.label(default = ws + "//archive/linkall"), # _thread = attr.label(default = ws + "//ns/thread"), _warnings = attr.label(default = ws + "//archive:warnings"), _ns_resolver = attr.label( doc = "Experimental", providers = [OcamlNsResolverProvider], default = "@ocaml//ns", cfg = ocaml_nslib_submodules_out_transition ), submodules = attr.label_list( doc = "List of *_module submodules", allow_files = [".cmo", ".cmx", ".cmi"], providers = _submod_providers, cfg = ocaml_nslib_submodules_out_transition ), ## so we can dump ConfigState _ns_prefixes = attr.label( doc = "Experimental", default = "@ocaml//ns:prefixes" ), _ns_submodules = attr.label( doc = "Experimental. May be set by ocaml_ns_library containing this module as a submodule.", default = "@ocaml//ns:submodules", # => string_list_setting # allow_files = True, # mandatory = True ), _allowlist_function_transition = attr.label( default = "@bazel_tools//tools/allowlists/function_transition_allowlist" ), _mode = attr.label( default = ws + "//mode" ), _projroot = attr.label( default = "@ocaml//:projroot" ) ) ####################### def options_ns_library(ws): if ws == "ocaml": _submod_providers = [ [OcamlModuleProvider], [OcamlNsLibraryProvider], [PpxModuleProvider], [OcamlSignatureProvider] ] _sublib_providers = [ # [OcamlNsArchiveProvider], [OcamlNsLibraryProvider], [PpxNsLibraryProvider], ] else: ## FIXME: ppx providers _submod_providers = [PpxModuleProvider] _sublib_providers = [PpxNsLibraryProvider] ws_prefix = "@ocaml" ## + ws return dict( _opts = attr.label(default = ws_prefix + "//module:opts"), # string list _linkall = attr.label(default = ws_prefix + "//module/linkall"), # bool _thread = attr.label(default = ws_prefix + "//module/thread"), # bool _warnings = attr.label(default = ws_prefix + "//module:warnings"), # string list ## we need this when we have sublibs but no direct submodules _ns_resolver = attr.label( doc = "Experimental", providers = [OcamlNsResolverProvider], default = "@ocaml//ns", cfg = ocaml_nslib_submodules_out_transition ), ## Note: this is for the user; transition fn uses it to populate ns:submodules # submodules = attr.label_keyed_string_dict( submodules = attr.label_list( doc = "List of *_module submodules", allow_files = [".cmo", ".cmx", ".cmi"], providers = _submod_providers, cfg = ocaml_nslib_submodules_out_transition ), ## so we can dump ConfigState _ns_prefixes = attr.label( doc = "Experimental", default = "@ocaml//ns:prefixes"
""" model selection: trains models that classify birdsong syllables, using algorithms and other parameters specified in config file """ # from standard library import os import copy # from dependencies import numpy as np from sklearn.preprocessing import StandardScaler from sklearn.metrics import accuracy_score from sklearn.externals import joblib import yaml # from hvc from .parseconfig import parse_config from .utils import grab_n_samples_by_song, get_acc_by_label, timestamp path = os.path.abspath(__file__) # get the path of this file dir_path = os.path.dirname(path) # but then just take the dir with open(os.path.join(dir_path, 'parse', 'validation.yml')) as val_yaml: validate_dict = yaml.load(val_yaml) model_types = validate_dict['valid_models'] def determine_model_output_folder_name(model_dict): """generates name for folder that holds model files by appending hyperparameter names and values in alphabetical order of hyperparameter name to name of model/algorithm """ model_dict_copy = copy.copy(model_dict) return model_dict_copy.pop( 'model_name' ) + ''.join('_{!s}{!r}'.format(key, val) for (key, val) in sorted( model_dict['hyperparameters'].items()) ) def select(config_file): """main function that runs model selection. Saves model files and summary file, doesn't return anything. Parameters ---------- config_file : string filename of YAML file that configures feature extraction """ select_config = parse_config(config_file, 'select') print('Parsed select config.') todo_list = select_config['todo_list'] for ind, todo in enumerate(todo_list): print('Completing item {} of {} in to-do list'.format(ind+1, len(todo_list))) a_timestamp = timestamp() output_dir = os.path.abspath(todo['output_dir']) output_dir = os.path.join(output_dir, 'select_output_' + a_timestamp) if not os.path.isdir(output_dir): os.makedirs(output_dir) output_filename = os.path.join(output_dir, 'summary_model_select_file_created_' + a_timestamp) if 'models' in todo: model_list = todo['models'] else: model_list = select_config['models'] for model_dict in model_list: # import models objects from sklearn + keras if not imported already if model_dict['model_name'] == 'svm': if 'SVC' not in locals(): from sklearn.svm import SVC elif model_dict['model_name'] == 'knn': if 'neighbors' not in locals(): from sklearn import neighbors elif model_dict['model_name'] == 'flatwindow': if 'flatwindow' not in locals(): from hvc.neuralnet.models.flatwindow import flatwindow from keras.callbacks import ModelCheckpoint, CSVLogger, EarlyStopping if 'num_test_samples' in todo: num_test_samples = todo['num_test_samples'] else: num_test_samples = select_config['num_test_samples'] if 'num_train_samples' in todo: num_train_samples_list = todo['num_train_samples'] else: num_train_samples_list = select_config['num_train_samples'] if 'num_replicates' in todo: num_replicates = todo['num_replicates'] else: num_replicates = select_config['num_replicates'] feature_file = joblib.load(todo['feature_file']) labels = np.asarray(feature_file['labels']) # call grab_n_samples this first time to get indices for test/validation set # and a list of song IDs from which we will draw the training set indices below test_IDs, train_song_ID_list = grab_n_samples_by_song(feature_file['songfile_IDs'], feature_file['labels'], num_test_samples, return_popped_songlist=True) test_labels = labels[test_IDs] score_arr = np.zeros((len(num_train_samples_list), len(range(num_replicates)), len(model_list))) avg_acc_arr = np.zeros((len(num_train_samples_list), len(range(num_replicates)), len(model_list))) pred_labels_arr = np.empty((len(num_train_samples_list), len(range(num_replicates)), len(model_list)), dtype='O') train_IDs_arr = np.empty((len(num_train_samples_list), len(range(num_replicates))), dtype='O') for num_samples_ind, num_train_samples in enumerate(num_train_samples_list): for replicate in range(num_replicates): print('Training models with {0} samples, replicate #{1}' .format(num_train_samples, replicate)) # here we call grab_n_samples again with the train_song_ID_list # from above. currently each fold is a random grab without # anything like k-folds. # For testing on large datasets this is okay but in situations # where we're data-limited it's less than ideal, the whole point # is to not have to hand-label a large data set train_IDs = grab_n_samples_by_song(feature_file['songfile_IDs'], feature_file['labels'], num_train_samples, song_ID_list=train_song_ID_list) train_IDs_arr[num_samples_ind, replicate] = train_IDs train_labels = labels[train_IDs] for model_ind, model_dict in enumerate(model_list): # save info associated with model such as indices of training samples. # Note this is done outside the if/elif list for switching between # models. model_output_dir = os.path.join(output_dir, determine_model_output_folder_name( model_dict)) if not os.path.isdir(model_output_dir): os.makedirs(model_output_dir) model_fname_str = \ '{0}_{1}samples_replicate{2}.model'.format(model_dict['model_name'], num_train_samples, replicate) model_filename = os.path.join(model_output_dir, model_fname_str) # if-elif that switches based on model type, # start with sklearn models if model_dict['model_name'] in model_types['sklearn']: # if model_dict specifies using a certain feature group if 'feature_group' in model_dict: # determine if we already figured out which features belong to that feature group. # Can only do that if model_dict defined for todo_list, not if model_dict defined # at top level of select config file if 'feature_list_indices' in model_dict: feature_inds = np.in1d(feature_file['features_arr_column_IDs'], model_dict['feature_list_indices']) else: # have to figure out feature list indices ftr_grp_ID_dict = feature_file['feature_group_ID_dict'] ftr_list_grp_ID = feature_file['feature_list_group_ID'] # figure out what they are by finding ID # corresponding to feature # group or groups in ID_dict, and then finding all the indices in the # feature list that have that group ID #, using ftr_list_grp_ID, a list # the same length as feature list where each element indicates whether # the element with the same index in the feature list belongs to a # feature group and if so which one, by ID # if type(model_dict['feature_group']) == str: ftr_grp_ID = ftr_grp_ID_dict[model_dict['feature_group']] # now find all the indices of features associated with the # feature group for that model ftr_list_inds = [ind for ind, val in enumerate(ftr_list_grp_ID) if val == ftr_grp_ID] # if user specified more than one feature group elif type(model_dict['feature_group']) == list: ftr_list_inds = [] for ftr_grp in model_dict['feature_group']: ftr_grp_ID = ftr_grp_ID_dict[ftr_grp] # now find all the indices of features associated with the # feature group for that model ftr_list_inds.extend([ind for ind, val in enumerate(ftr_list_grp_ID) if val == ftr_grp_ID]) # finally use ftr_list_inds to get the actual columns we need from the # features array. Need to this because multiple columns might belong to # the same feature, e.g. if the feature is a spectrum feature_inds = np.in1d(feature_file['features_arr_column_IDs'], ftr_list_inds) # put feature list indices in model dict so we have it later when # saving summary file model_dict['feature_list_indices'] = ftr_list_inds elif 'feature_list_indices' in model_dict and\ 'feature_group' not in model_dict: # if no feature group in model dict, use feature list indices # Note that for neuralnet models, there will be neither if model_dict['feature_list_indices'] == 'all': feature_inds = np.ones(( feature_file['features_arr_column_IDs'].shape[-1],)).astype(bool) else: # use 'feature_list_indices' from model_dict to get the actual columns # we need from the features array. Again, need to this because multiple # columns might belong to the same feature, # e.g. if the feature is a spectrum feature_inds = np.in1d(feature_file['features_arr_column_IDs'], model_dict['feature_list_indices']) if model_dict['model_name'] == 'svm': print('training svm. ', end='') clf = SVC(C=model_dict['hyperparameters']['C'], gamma=model_dict['hyperparameters']['gamma'], decision_function_shape='ovr', probability=model_dict['predict_proba']) elif model_dict['model_name'] == 'knn': print('training knn. ', end='') clf = neighbors.KNeighborsClassifier(model_dict['hyperparameters']['k'], 'distance') #use 'advanced indexing' to get only sample rows and only feature models features_train = feature_file['features'][train_IDs[:, np.newaxis], feature_inds] scaler = StandardScaler() features_train = scaler.fit_transform(features_train) features_test = feature_file['features'][test_IDs[:,np.newaxis], feature_inds] features_test = scaler.transform(features_test) print('fitting model. ', end='') clf.fit(features_train, train_labels) score = clf.score(features_test, test_labels) print('score on test set: {:05.4f} '.format(score), end='') score_arr[num_samples_ind, replicate, model_ind] = score pred_labels = clf.predict(features_test) pred_labels_arr[num_samples_ind, replicate, model_ind] = pred_labels acc_by_label, avg_acc = get_acc_by_label(test_labels, pred_labels, feature_file['labelset']) print(', average accuracy on test set: {:05.4f}'.format(avg_acc)) avg_acc_arr[num_samples_ind, replicate, model_ind] = avg_acc joblib.dump(clf, model_filename) # this is the middle of the if-elif that switches based on model type # end sklearn, start keras models elif model_dict['model_name'] in model_types['keras']: if 'neuralnet_input' in model_dict: neuralnet_input = model_dict['neuralnet_input'] spects = feature_file['neuralnet_inputs'][neuralnet_input] else: # if not specified, assume that input should be the one that # corresponds to the neural net model being trained neuralnet_input = model_dict['model_name'] try: spects = feature_file['neuralnet_inputs'][neuralnet_input] except KeyError: raise KeyError('no input specified for model {}, and ' 'input type for that model was not found in ' 'feature file' .format(model_dict['model_name'])) if 'SpectScaler' not in locals(): from hvc.neuralnet.utils import SpectScaler if 'test_labels_onehot' not in locals(): from sklearn.preprocessing import LabelBinarizer label_binarizer = LabelBinarizer() test_labels_onehot = label_binarizer.fit_transform(test_labels) if 'test_spects' not in locals(): # get spects for test set, # also add axis so correct input_shape for keras.conv_2d test_spects = spects[test_IDs, :, :] train_labels_onehot = label_binarizer.transform(train_labels) # get spects for train set, # also add axis so correct input_shape for keras.conv_2d train_spects = spects[train_IDs, :, :] # scale all spects by mean and std of training set spect_scaler = SpectScaler() # concatenate all spects then rotate so # Hz bins are columns, i.e., 'features' spect_scaler.fit(train_spects) train_spects_scaled = spect_scaler.transform(train_spects) test_spects_scaled = spect_scaler.transform(test_spects) # have to add 'channels' axis for keras 2-d convolution # even though these are spectrograms, don't have channels # like an image would. # Decided to leave it explicit here instead of hiding in a function train_spects_scaled = train_spects_scaled[:, :, :, np.newaxis] test_spects_scaled = test_spects_scaled[:, :, :, np.newaxis] num_samples, num_freqbins, num_timebins, num_channels = \ train_spects_scaled.shape num_label_classes = len(feature_file['labelset']) input_shape = (num_freqbins, num_timebins, num_channels) flatwin = flatwindow(input_shape=input_shape, num_label_classes=num_label_classes) csv_str = ''.join(['flatwindow_training_', '{}_samples_'.format(num_train_samples), 'replicate_{}'.format(replicate), '.log']) csv_filename = os.path.join(model_output_dir, csv_str) csv_logger =
# -*- coding: utf-8 -*- """ Created on Mon Sep 17 14:32:52 2018 @author: <NAME> Decision level ensemble classifiers of base GFMM-AGGLO-2 DecisionLevelEnsembleClassifier(numClassifier, numFold, gamma, teta, bthres, simil, sing, oper, isNorm, norm_range) INPUT numClassifier The number of classifiers numFold The number of folds for cross-validation gamma Membership function slope (default: 1) teta Maximum hyperbox size (default: 1) bthres Similarity threshold for hyperbox concatenetion (default: 0.5) simil Similarity measure: 'short', 'long' or 'mid' (default: 'mid') sing Use 'min' or 'max' (default) memberhsip in case of assymetric similarity measure (simil='mid') oper Membership calculation operation: 'min' or 'prod' (default: 'min') isNorm Do normalization of input training samples or not? norm_range New ranging of input data after normalization, for example: [0, 1] ATTRIBUTES baseClassifiers An array of base GFMM AGLLO-2 classifiers numHyperboxes The number of hyperboxes in all base classifiers """ import sys, os sys.path.insert(0, os.path.pardir) import numpy as np import time import ast from GFMM.basebatchlearninggfmm import BaseBatchLearningGFMM from GFMM.accelbatchgfmm import AccelBatchGFMM from GFMM.classification import predict, predictDecisionLevelEnsemble from functionhelper.matrixhelper import delete_const_dims from functionhelper.preprocessinghelper import splitDatasetRndToKPart, splitDatasetRndClassBasedToKPart from functionhelper.preprocessinghelper import loadDataset, string_to_boolean class DecisionLevelEnsembleClassifier(BaseBatchLearningGFMM): def __init__(self, numClassifier = 10, numFold = 10, gamma = 1, teta = 1, bthres = 0.5, simil = 'mid', sing = 'max', oper = 'min', isNorm = True, norm_range = [0, 1]): BaseBatchLearningGFMM.__init__(self, gamma, teta, False, oper, isNorm, norm_range) self.numFold = numFold self.numClassifier = numClassifier self.bthres = bthres self.simil = simil self.sing = sing self.baseClassifiers = np.empty(numClassifier, dtype = BaseBatchLearningGFMM) self.numHyperboxes = 0 def fit(self, X_l, X_u, patClassId, typeOfSplitting = 0): """ Training the ensemble model at decision level. This method is used when the input data are not partitioned into k parts INPUT X_l Input data lower bounds (rows = objects, columns = features) X_u Input data upper bounds (rows = objects, columns = features) patClassId Input data class labels (crisp) typeOfSplitting The way of splitting datasets + 1: random split on whole dataset - do not care the classes + otherwise: random split according to each class label """ X_l, X_u = self.dataPreprocessing(X_l, X_u) self.numHyperboxes = 0 time_start = time.clock() for i in range(self.numClassifier): if typeOfSplitting == 1: partitionedXtr = splitDatasetRndToKPart(X_l, X_u, patClassId, self.numFold) else: partitionedXtr = splitDatasetRndClassBasedToKPart(X_l, X_u, patClassId, self.numFold) self.baseClassifiers[i] = self.training(partitionedXtr) self.numHyperboxes = self.numHyperboxes + len(self.baseClassifiers[i].classId) time_end = time.clock() self.elapsed_training_time = time_end - time_start return self def training(self, partitionedXtr): """ Training a base classifier using K-fold cross-validation. This method is used when the input data are preprocessed and partitioned into k parts INPUT partitionedXtr An numpy array contains k sub-arrays, in which each subarray is Bunch datatype: + lower: lower bounds + upper: upper bounds + label: class labels partitionedXtr should be normalized (if needed) beforehand using this function OUTPUT baseClassifier base classifier was validated using K-fold cross-validation """ baseClassifier = None minEr = 2 for k in range(self.numFold): classifier_tmp = AccelBatchGFMM(self.gamma, self.teta, self.bthres, self.simil, self.sing, False, self.oper, False) classifier_tmp.fit(partitionedXtr[k].lower, partitionedXtr[k].upper, partitionedXtr[k].label) # Create the validation set being the remaining training data for l in range(self.numFold): if l == k: continue else: if (k == 0 and l == 1) or (l == 0 and k != 0): lower_valid = partitionedXtr[l].lower upper_valid = partitionedXtr[l].upper label_valid = partitionedXtr[l].label else: lower_valid = np.concatenate((lower_valid, partitionedXtr[l].lower), axis=0) upper_valid = np.concatenate((upper_valid, partitionedXtr[l].upper), axis=0) label_valid = np.concatenate((label_valid, partitionedXtr[l].label)) # validate the trained model rest = predict(classifier_tmp.V, classifier_tmp.W, classifier_tmp.classId, lower_valid, upper_valid, label_valid, self.gamma, self.oper) er = rest.summis / len(label_valid) if er < minEr: minEr = er baseClassifier = classifier_tmp return baseClassifier def predict(self, Xl_Test, Xu_Test, patClassIdTest): """ Perform classification result = predict(Xl_Test, Xu_Test, patClassIdTest) INPUT: Xl_Test Test data lower bounds (rows = objects, columns = features) Xu_Test Test data upper bounds (rows = objects, columns = features) patClassIdTest Test data class labels (crisp) OUTPUT: result A object with Bunch datatype containing all results as follows: + summis Number of misclassified samples + misclass Binary error map for input samples + out Soft class memberships, rows are testing input patterns, columns are indices of classes + classes Store class labels corresponding column indices of out """ #Xl_Test, Xu_Test = delete_const_dims(Xl_Test, Xu_Test) # Normalize testing dataset if training datasets were normalized if len(self.mins) > 0 and self.isNorm == True: noSamples = Xl_Test.shape[0] Xl_Test = self.loLim + (self.hiLim - self.loLim) * (Xl_Test - np.ones((noSamples, 1)) * self.mins) / (np.ones((noSamples, 1)) * (self.maxs - self.mins)) Xu_Test = self.loLim + (self.hiLim - self.loLim) * (Xu_Test - np.ones((noSamples, 1)) * self.mins) / (np.ones((noSamples, 1)) * (self.maxs - self.mins)) if Xl_Test.min() < self.loLim or Xu_Test.min() < self.loLim or Xl_Test.max() > self.hiLim or Xu_Test.max() > self.hiLim: print('Test sample falls outside', self.loLim, '-', self.hiLim, 'interval') print('Number of original samples = ', noSamples) # only keep samples within the interval loLim-hiLim indXl_good = np.where((Xl_Test >= self.loLim).all(axis = 1) & (Xl_Test <= self.hiLim).all(axis = 1))[0] indXu_good = np.where((Xu_Test >= self.loLim).all(axis = 1) & (Xu_Test <= self.hiLim).all(axis = 1))[0] indKeep = np.intersect1d(indXl_good, indXu_good) Xl_Test = Xl_Test[indKeep, :] Xu_Test = Xu_Test[indKeep, :] print('Number of kept samples =', Xl_Test.shape[0]) # do classification result = None if Xl_Test.shape[0] > 0: result = predictDecisionLevelEnsemble(self.baseClassifiers, Xl_Test, Xu_Test, patClassIdTest, self.gamma, self.oper) return result if __name__ == '__main__': """ INPUT parameters from command line arg1: + 1 - training and testing datasets are located in separated files + 2 - training and testing datasets are located in the same files arg2: path to file containing the training dataset (arg1 = 1) or both training and testing datasets (arg1 = 2) arg3: + path to file containing the testing dataset (arg1 = 1) + percentage of the training dataset in the input file arg4: + Number of base classifiers needs to be combined (default: 5) arg5: + Number of folds for cross-validation (default: 10) arg6: + Maximum size of hyperboxes (teta, default: 1) arg7: + gamma value (default: 1) arg8: + Similarity threshold (default: 0.5) arg9: + Similarity measure: 'short', 'long' or 'mid' (default: 'mid') arg10: + operation used to compute membership value: 'min' or 'prod' (default: 'min') arg11: + do normalization of datasets or not? True: Normilize, False: No normalize (default: True) arg12: + range of input values after normalization (default: [0, 1]) arg13: + Use 'min' or 'max' (default) memberhsip in case of assymetric similarity measure (simil='mid') arg14: Mode to split a dataset into arg5 folds (default: 0): - 1: Randomly split whole dataset - otherwise: Randomly split following each class label """ # Init default parameters if len(sys.argv) < 5: numBaseClassifier = 5 else: numBaseClassifier = int(sys.argv[4]) if len(sys.argv) < 6: numFold = 10 else: numFold = int(sys.argv[5]) if len(sys.argv) < 7: teta = 1 else: teta = float(sys.argv[6]) if len(sys.argv) < 8: gamma = 1 else: gamma = float(sys.argv[7]) if len(sys.argv) < 9: bthres = 0.5 else: bthres = float(sys.argv[8]) if len(sys.argv) < 10: simil = 'mid' else: simil = sys.argv[9] if len(sys.argv) < 11: oper = 'min' else: oper = sys.argv[10] if len(sys.argv) < 12: isNorm = True else: isNorm = string_to_boolean(sys.argv[11]) if len(sys.argv) < 13: norm_range = [0, 1] else: norm_range = ast.literal_eval(sys.argv[12]) if len(sys.argv) < 14: sing = 'max' else: sing = sys.argv[13] if len(sys.argv) < 15: typeOfSplit = 0 else: typeOfSplit = int(sys.argv[14]) if sys.argv[1] == '1': training_file = sys.argv[2] testing_file = sys.argv[3] # Read training file Xtr, X_tmp, patClassIdTr, pat_tmp = loadDataset(training_file, 1, False) # Read testing file X_tmp, Xtest, pat_tmp, patClassIdTest = loadDataset(testing_file, 0, False) else: dataset_file = sys.argv[2] percent_Training = float(sys.argv[3]) Xtr, Xtest, patClassIdTr, patClassIdTest = loadDataset(dataset_file, percent_Training, False) classifier = DecisionLevelEnsembleClassifier(numClassifier = numBaseClassifier, numFold = numFold, gamma = gamma, teta = teta, bthres = bthres, simil = simil, sing = sing, oper = oper, isNorm = isNorm, norm_range =
<filename>matrix_calc_201128.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- # File name: matrix_calc.py """ Created on Thu May 7 20:56:54 2020 @author: Neo(<EMAIL>) Some codes for calculating various matrix & array needed in the LSQ preocess. The normal equation is writtern as A * x = b where A is the normal matrix, x the vector consist of unknowns, and b the right-hand-side array. """ import sys import os import numpy as np from numpy import pi, concatenate # My progs # from .vsh_expension import real_vec_sph_harm_proj from vsh_expension_201128 import real_vec_sph_harm_proj, vec_sph_harm_proj # ----------------------------- FUNCTIONS ----------------------------- def cov_mat_calc(dra_err, ddc_err, ra_dc_cov=None, ra_dc_cor=None): """Calculate the covariance matrix. Parameters ---------- dra_err/ddc_err : array of float formal uncertainty of dRA(*cos(dc_rad))/dDE ra_dc_cov : array of float correlation between dRA and dDE, default is None ra_dc_cor : array of float correlation coefficient between dRA and dDE, default is None Returns ---------- cov_mat : matrix Covariance matrix used in the least squares fitting. """ if len(ddc_err) != len(dra_err): print("The length of dra_err and ddc_err should be equal") sys.exit() # TO-DO # Check the length of correlation array # else: # if ra_dc_cov is None: # Covariance matrix. # err = np.vstack((dra_err, ddc_err)).T.flatten() err = concatenate((dra_err, ddc_err)) cov_mat = np.diag(err**2) # Take the correlation into consideration. # Assume at most one of ra_dc_cov and ra_dc_cor is given if ra_dc_cov is None and ra_dc_cor is None: return cov_mat elif ra_dc_cor is not None: ra_dc_cov = ra_dc_cor * dra_err * ddc_err N = len(dra_err) for i, covi in enumerate(ra_dc_cov): cov_mat[i, i+N] = covi cov_mat[i+N, i] = covi return cov_mat def cov_to_cor(cov_mat): """Convert covariance matrix to sigma and correlation coefficient matrix """ # Formal uncertainty sig = np.sqrt(cov_mat.diagonal()) # Correlation coefficient. cor_mat = np.array([cov_mat[i, j] / sig[i] / sig[j] for j in range(len(sig)) for i in range(len(sig))]) cor_mat.resize((len(sig), len(sig))) return sig, cor_mat def cor_to_cov(sig, cor_mat): """Convert correlation coefficient matrix to sigma and covariance matrix """ # Covariance cov_mat = np.array([cor_mat[i, j] * sig[i] * sig[j] for j in range(len(sig)) for i in range(len(sig))]) cov_mat.resize((len(sig), len(sig))) return cov_mat def wgt_mat_calc(dra_err, ddc_err, ra_dc_cov=None, ra_dc_cor=None): """Calculate the weight matrix. Parameters ---------- dra_err/ddc_err : array of float formal uncertainty of dRA(*cos(dc_rad))/dDE ra_dc_cov : array of float correlation between dRA and dDE, default is None ra_dc_cor : array of float correlation coefficient between dRA and dDE, default is None Returns ---------- wgt_matrix : matrix weighted matrix used in the least squares fitting. """ # Calculate the covariance matrix cov_mat = cov_mat_calc(dra_err, ddc_err, ra_dc_cov, ra_dc_cor) # Inverse it to obtain weight matrix. wgt_mat = np.linalg.inv(cov_mat) return wgt_mat def jac_mat_l_calc(T_ra_mat, T_dc_mat, l, fit_type="full"): """Calculate the Jacobian matrix of lth degree Parameters ---------- ra_rad/dc_rad : array (M,) of float Right ascension/Declination in radian l : int degree of the harmonics fit_type : string flag to determine which parameters to be fitted "full" for T- and S-vectors bot Number of observations """ # Number of source M = T_ra_mat.shape[2] # Usually begins with the first order Tl0_ra, Tl0_dc = real_vec_sph_harm_proj(l, 0, T_ra_mat, T_dc_mat) # Note the relation between Tlm and Slm # S10_ra, S10_dc = -Tl0_dc, Tl0_ra # jac_mat_ra = concatenate( # (Tl0_ra.reshape(M, 1), Sl0_ra.reshape(M, 1)), axis=1) jac_mat_ra = concatenate( (Tl0_ra.reshape(M, 1), -Tl0_dc.reshape(M, 1)), axis=1) jac_mat_dc = concatenate( (Tl0_dc.reshape(M, 1), Tl0_ra.reshape(M, 1)), axis=1) for m in range(1, l+1): Tlmr_ra, Tlmr_dc, Tlmi_ra, Tlmi_dc = real_vec_sph_harm_proj( l, m, T_ra_mat, T_dc_mat) # Just to show the relation # Slmr_ra, Slmi_ra = -Tlmr_dc, -Tlmr_dc # Slmr_dc, Slmr_dc = Tlmr_ra, Tlmr_ra # Concatenate the new array and the existing Jacobian matrix jac_mat_ra = concatenate( (jac_mat_ra, Tlmr_ra.reshape(M, 1), -Tlmr_dc.reshape(M, 1), Tlmi_ra.reshape(M, 1), -Tlmi_dc.reshape(M, 1)), axis=1) jac_mat_dc = concatenate( (jac_mat_dc, Tlmr_dc.reshape(M, 1), Tlmr_ra.reshape(M, 1), Tlmi_dc.reshape(M, 1), Tlmi_ra.reshape(M, 1)), axis=1) # Treat (ra, dc) as two observations(dependent or independent) # Combine the Jacobian matrix projection on RA and Decl. jac_mat = concatenate((jac_mat_ra, jac_mat_dc), axis=0) # Check the shape of the matrix if jac_mat.shape != (2*M, 4*l+2): print("Shape of Jocabian matrix at l={} is ({},{}) " "rather than ({},{})".format(l, jac_mat.shape[0], jac_mat.shape[1], 2*M, 4*l+2)) sys.exit() return jac_mat def jac_mat_calc(ra_rad, dc_rad, l_max, fit_type="full"): """Calculate the Jacobian matrix Parameters ---------- ra_rad/dc_rad : array (m,) of float Right ascension/Declination in radian l_max : int maximum degree fit_type : string flag to determine which parameters to be fitted "full" for T- and S-vectors both "T" for T-vectors only "S" for S-vectors only Returns ---------- jac_mat : array of float Jacobian matrix (M, N) (assume N unknows to determine) """ # Calculate all the VSH terms at one time T_ra_mat, T_dc_mat = vec_sph_harm_proj(l_max, ra_rad, dc_rad) # Usually begins with the first degree jac_mat = jac_mat_l_calc(T_ra_mat, T_dc_mat, 1, fit_type) for l in range(2, l_max+1): new_mat = jac_mat_l_calc(T_ra_mat, T_dc_mat, l, fit_type) jac_mat = concatenate((jac_mat, new_mat), axis=1) # Check the shape of the Jacobian matrix M = len(ra_rad) N = 2 * l_max * (l_max+2) if jac_mat.shape != (2*M, N): print("Shape of Jocabian matrix is ({},{}) " "rather than ({},{})".format(jac_mat.shape[0], jac_mat.shape[1], 2*M, N)) sys.exit() return jac_mat def nor_mat_calc(dra, ddc, dra_err, ddc_err, ra_rad, dc_rad, ra_dc_cov=None, ra_dc_cor=None, l_max=1, fit_type="full", suffix=""): """Cacluate the normal and right-hand-side matrix for LSQ analysis. Parameters ---------- dra_err/ddc_err : array of float formal uncertainty of dRA(*cos(dc_rad))/dDE in dex ra_rad/dc_rad : array of float Right ascension/Declination in radian ra_dc_cov : array of float correlation between dRA and dDE, default is None ra_dc_cor : array of float correlation coefficient between dRA and dDE, default is None l_max : int maximum degree fit_type : string flag to determine which parameters to be fitted "full" for T- and S-vectors both "T" for T-vectors only "S" for S-vectors only suffix : string suffix for output matrix file Returns ---------- nor_mat : array of float normal matrix rhs_mat : array of float right-hand-side matrix """ # Jacobian matrix jac_mat = jac_mat_calc(ra_rad, dc_rad, l_max, fit_type) # Weighted matrix wgt_mat = wgt_mat_calc(dra_err, ddc_err, ra_dc_cov, ra_dc_cor) # Jac_mat_T * Wgt_mat mul_mat = np.dot(np.transpose(jac_mat), wgt_mat) # Calculate normal matrix A nor_mat = np.dot(mul_mat, jac_mat) # Calculate right-hand-side matrix b res_mat = concatenate((dra, ddc), axis=0) rhs_mat = np.dot(mul_mat, res_mat) # Save matrice for later use # np.save("jac_mat_{:s}.npy".format(suffix), jac_mat) return nor_mat, rhs_mat def predict_mat_calc(pmt, suffix): """Calculate the predicted value Parameters ---------- pmt : array estimate of unknowns suffix : string suffix for finding corresponding Jacobian matrix Returns ------- dra_pre : array predicted offset in RA ddc_pre : array predicted offset in Declination """ jac_mat = np.load("jac_mat_{:s}.npy".format(suffix)) dra_ddc = np.dot(jac_mat, pmt) num_sou = int(len(dra_ddc)/2) dra_pre, ddc_pre = dra_ddc[:num_sou], dra_ddc[num_sou:] return dra_pre, ddc_pre def nor_eq_sol(dra, ddc, dra_err, ddc_err, ra_rad, dc_rad, ra_dc_cov=None, ra_dc_cor=None, l_max=1, fit_type="full", num_iter=None): """The 1st degree of VSH function: glide and rotation. Parameters ---------- dra/ddc : array of float R.A.(*cos(Dec.))/Dec. differences in dex dra_err/ddc_err : array of float formal uncertainty of dra(*cos(dc_rad))/ddc in dex ra_rad/dc_rad : array of float Right ascension/Declination in radian ra_dc_cov/ra_dc_cor : array of float covariance/correlation coefficient between dra and ddc in dex^2, default is None fit_type : string flag to determine which parameters to be fitted "full" for T- and S-vectors both "T" for T-vectors only "S" for S-vectors only Returns ---------- pmt : array of float estimation of (d1, d2, d3, r1, r2, r3) in dex sig : array of float uncertainty of x in dex cor_mat : matrix matrix of correlation coefficient. """ # Maxium number of sources processed per time # According to my test, 100 should be a good choice if num_iter is None: num_iter = 100 div = dra.size // num_iter rem = dra.size % num_iter suffix_array = [] A, b = 0, 0 if rem: suffix_array.append("{:05d}".format(0)) if not ra_dc_cov is None: A, b = nor_mat_calc(dra[: rem], ddc[: rem], dra_err[: rem], ddc_err[: rem], ra_rad[: rem], dc_rad[: rem], ra_dc_cov=ra_dc_cov[: rem], l_max=l_max, fit_type=fit_type, suffix=suffix_array[0]) elif not ra_dc_cor is None: A, b = nor_mat_calc(dra[: rem], ddc[: rem], dra_err[: rem], ddc_err[: rem], ra_rad[: rem], dc_rad[: rem], ra_dc_cor=ra_dc_cor[: rem], l_max=l_max, fit_type=fit_type, suffix=suffix_array[0]) else: A, b = nor_mat_calc(dra[: rem], ddc[: rem], dra_err[: rem], ddc_err[: rem], ra_rad[: rem], dc_rad[: rem], l_max=l_max, fit_type=fit_type, suffix=suffix_array[0]) for i in range(div): sta = rem + i * num_iter end = sta +