Best Python code snippet using PyHamcrest_python
validate.py
Source:validate.py
1 # Copyright 2016-2017 University of Pittsburgh2 # Licensed under the Apache License, Version 2.0 (the "License");3 # you may not use this file except in compliance with the License.4 # You may obtain a copy of the License at5 # http:www.apache.org/licenses/LICENSE-2.06 # Unless required by applicable law or agreed to in writing, software7 # distributed under the License is distributed on an "AS IS" BASIS,8 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.9 # See the License for the specific language governing permissions and10 # limitations under the License.11import sys, csv, json, re, os, uuid12import datetime13from sets import Set14from postgres import connection as pgconn15from postgres import mpEvidenceLoad as pgmp16from postgres import mpEvidenceQry as pgqry17import loadAnnotatorAnnsToRDB as pgload18from elastic import queryMPAnnotation as esmp19from elastic import operations as esop20from model.Micropublication import *21reload(sys) 22sys.setdefaultencoding('utf8')23## VALIDATE TOTAL ANNOTATIONS TRANSLATE AND LOAD #############################24## validate query results and the results from csv25## rttype: boolean26def validateResults(conn, csvD):27 rdbD = queryDocAndDataCnt(conn) 28 # print csvD29 # print "======================================="30 # print rdbD31 return compareTwoDicts(csvD, rdbD)32## query MP claim, rtype: dict with document url and counts of annotation33def queryDocAndDataCnt(conn):34 claimDict = {}35 qry = """36set schema 'ohdsi';37select distinct t.has_source, cann.urn, max(dann.mp_data_index)38from mp_claim_annotation cann join oa_claim_body cbody on cann.has_body = cbody.id39join oa_target t on cann.has_target = t.id40left join mp_data_annotation dann on cann.id = dann.mp_claim_id41group by t.has_source, cann.urn42order by t.has_source, cann.urn """43 cur = conn.cursor()44 cur.execute(qry)45 for row in cur.fetchall():46 document = row[0]; claim_urn = row[1]; cnt = row[2]47 if not cnt or cnt == "":48 cnt = 149 if document in claimDict: 50 claimDict[document] += cnt51 else:52 claimDict[document] = cnt53 return claimDict54## compare two dicts55## rtype: boolean (same: True, different: False)56def compareTwoDicts(dict1, dict2):57 if not dict1 or not dict2:58 print "[ERROR] empty annotation set during validating"59 return False60 if len(dict1) != len(dict2):61 print "[ERROR] the number of annotations from csv not the same as from postgresDB"62 return False63 for k,v in dict1.iteritems():64 if k in dict2 and dict2[k] == v:65 print "[INFO] document (%s) have MP data (%s) validated" % (k, v)66 else:67 print "[ERROR] document (%s) have MP data (%s) from dict1 but data (%s) from dict 2" % (k, v, dict2[k])68 return False69 return True70 71# load json template72def loadTemplateInJson(path):73 json_data=open(path)74 data = json.load(json_data)75 json_data.close()76 return data77 78## VALIDATE INDIVIDUAL ANNOTATION TRANSLATE AND LOAD #############################79def etlAnnForTesting(conn, template, annUrn):80 ## clean test samples in elasticsearch, if exists, then delete81 #esop.deleteById("localhost", "9200", annUrn)82 ## load annotation to elasticsearch83 annTemp = loadTemplateInJson(template)84 esop.createMpAnnotation("localhost", "9200", annTemp, annUrn)85 ## query elasticsearch for the annotation86 annotation = esmp.getMPAnnById("localhost", "9200", annUrn)87 ## load annotation to postgres DB88 pgload.load_annotation(conn, annotation, "dbmi.etl@gmail.com")89 ## qry postgres for the annotation90 annotations = pgqry.getMpAnnotations(conn) 91 for ann in annotations:92 if ann.urn == annUrn:93 return ann94## TESTING FUNCTIONS ######################################################95def testClaim(annotation, urn, label, exact, method, negation, rej_statement, rej_reason, rej_comment):96 print "[INFO] begin validating claim..."97 if isMatched("urn", urn, annotation.urn) and isMatched("label", label, annotation.label) and isMatched("exact text", exact, annotation.exact) and isMatched("user entered method", method, annotation.method) and isMatched("negation", negation, annotation.negation) and isMatched("rejected", rej_statement, annotation.rejected_statement) and isMatched("rejected", rej_reason, annotation.rejected_statement_reason) and isMatched("rejected", rej_comment, annotation.rejected_statement_comment):98 print "[TEST] claim is validated" 99 else:100 print "[ERROR] claim is not correct"101def testQualifier(qualifier, qvalue, subject, predicate, object, enantiomer, metabolite):102 print "[INFO] begin validating claim qualifiers..." 103 if isMatched("qualifier", qvalue, qualifier.qvalue) and isMatched("subject", subject, qualifier.subject) and isMatched("predicate", predicate, qualifier.predicate) and isMatched("object", object, qualifier.object) and isMatched("enantiomer", enantiomer, qualifier.enantiomer) and isMatched("metabolite", metabolite, qualifier.metabolite):104 print "[TEST] claim qualifier is validated"105 else:106 print "[ERROR] claim qualifier are not correct"107def testDataRatio(ratioItem, field, value, type, direction, exact):108 print "[INFO] begin validating %s..." % field109 if isMatched("field", field, ratioItem.field) and isMatched("value", value, ratioItem.value) and isMatched("type", type, ratioItem.type) and isMatched("direction", direction, ratioItem.direction) and isMatched("exact text", exact, ratioItem.exact):110 print "[TEST] %s is validated" % (field)111 else:112 print "[ERROR] %s is incorrect" % (field)113def testMaterialDose(doseItem, field, drugname, value, formulation, duration, regimens, exact):114 print "[INFO] begin validating %s..." % field115 if isMatched("dose type", field, doseItem.field) and isMatched("drugname", drugname, doseItem.drugname) and isMatched("value", value, doseItem.value) and isMatched("duration", duration, doseItem.duration) and isMatched("formulation", formulation, doseItem.formulation) and isMatched("regimens", regimens, doseItem.regimens) and isMatched("exact text", exact, doseItem.exact):116 print "[TEST] %s is validated" % (field)117 else:118 print "[ERROR] %s is incorrect" % (field)119def testParticipants(partItem, value, exact):120 print "[INFO] begin validating participants..."121 if isMatched("participants", value, partItem.value) and isMatched("exact", exact, partItem.exact):122 print "[TEST] participants is validated"123 else:124 print "[ERROR] participants is incorrect"125def testEvRelationship(dmRow, value):126 if isMatched("evidence relationship", value, dmRow.ev_supports):127 print "[TEST] evidence relationship is validated"128 else:129 print "[ERROR] evidence relationship is incorrect" 130def testPhenotype(phenoItem, ptype, value, metabolizer, population, exact):131 print "[INFO] begin validating phenotype..."132 if isMatched("phenotype", ptype, phenoItem.ptype) and isMatched("value", value, phenoItem.value) and isMatched("metabolizer", metabolizer, phenoItem.metabolizer) and isMatched("population", population, phenoItem.population) and isMatched("exact", exact, phenoItem.exact):133 print "[TEST] phenotype is validated"134 else:135 print "[ERROR] phenotype is incorrect"136def testDataReviewer(reviewerItem, reviewer, date, total, lackinfo):137 print "[INFO] begin validating data reviewer..."138 if isMatched("reviewer", reviewer, reviewerItem.reviewer) and isMatched("date", date, reviewerItem.date) and isMatched("total", total, reviewerItem.total) and isMatched("lackinfo", lackinfo, reviewerItem.lackinfo):139 print "[TEST] data reviewer is validated"140 else:141 print "[ERROR] data reviewer is incorrect"142def testDataDipsQs(dipsItem, qsDict):143 print "[INFO] begin validating dips questions..."144 annDipsQsDict = dipsItem.getDipsDict()145 if len(annDipsQsDict) == len(qsDict):146 for k,v in qsDict.iteritems():147 if not isMatched("dips " + k, v, annDipsQsDict[k]):148 return149 print "[TEST] dips questions are validated"150 else:151 print "[ERROR] incorrect number of dips questions"152def testEvTypeQuestion(dmRow, grouprandom, parallelgroup):153 print "[INFO] begin validating evidence type questions..."154 if isMatched("grouprandom", grouprandom, dmRow.grouprandom) and isMatched("parallelgroup", parallelgroup, dmRow.parallelgroup):155 print "[TEST] evidence type related questions are validated"156 else:157 print "[ERROR] evidence type related questions are incorrect"158 159def isMatched(field, val1, val2):160 if type(val1) != type(val2):161 print "[ERROR] %s have an incorrect data type" % field162 return False163 if val1 == val2:164 #print "[TEST] %s is validated" % field165 return True166 print "[ERROR] %s is incorrect: val1 (%s) and val2 (%s)" % (field, val1, val2)167 return False 168## TESTING CASES #############################################################169# Validate clinical trial annotation 170# Two data & material items171def test_clinical_trial_1(conn, template):172 print "[INFO] ===== begin test clinical trial annotation 1 ======================"173 annUrn = "test-clinicaltrial-id-1"174 annotation = etlAnnForTesting(conn, template, annUrn)175 if isinstance(annotation, ClinicalTrial):176 ## claim validation177 print "[INFO] ================= Begin validating MP Claim ======================"178 testClaim(annotation, "test-clinicaltrial-id-1", "telaprevir_inhibits_atorvastatin", "claim-text", "DDI clinical trial", False, True, "rejected-reason", "rejected-comment")179 ## qualifiers180 testQualifier(annotation.csubject, "atorvastatin", True, False, False, False, True)181 testQualifier(annotation.cpredicate, "inhibits", False, True, False, None, None)182 testQualifier(annotation.cobject, "cyp1a1", False, False, True, None, None)183 testQualifier(annotation.cqualifier, "telaprevir", False, False, False, True, False)184 print "[INFO] ================= Begin validating MP data ======================="185 ## data 1 validation186 dmRow1 = annotation.getSpecificDataMaterial(0)187 testEvRelationship(dmRow1, True)188 testEvTypeQuestion(dmRow1, "yes", "no")189 testDataRatio(dmRow1.auc, "auc", "7.88", "Fold", "Increase", "auc-text-1")190 testDataRatio(dmRow1.cmax, "cmax", "10.6", "Fold", "Increase", "cmax-text-1")191 testDataRatio(dmRow1.clearance, "clearance", "87.8", "Percent", "Decrease", "clearance-text-1")192 testDataRatio(dmRow1.halflife, "halflife", "28.5", "Percent", "Decrease", "halflife-text-1")193 ## material 1 validation 194 testParticipants(dmRow1.participants, "21.00", "participants-text-1")195 testMaterialDose(dmRow1.precipitant_dose, "precipitant_dose", "atorvastatin", "30", "Oral", "1", "SD", "drug2Dose-text-1")196 testMaterialDose(dmRow1.object_dose, "object_dose", "telaprevir", "20", "Oral", "16", "Q8", "drug1Dose-text-1")197 ## data 2 validation198 dmRow2 = annotation.getSpecificDataMaterial(1)199 testEvRelationship(dmRow2, False)200 testEvTypeQuestion(dmRow2, "no", "yes")201 testDataRatio(dmRow2.auc, "auc", "17.88", "Percent", "Decrease", "auc-text-2")202 testDataRatio(dmRow2.cmax, "cmax", "10.3", "Percent", "Decrease", "cmax-text-2")203 testDataRatio(dmRow2.clearance, "clearance", "7.8", "Fold", "Increase", "clearance-text-2")204 testDataRatio(dmRow2.halflife, "halflife", "2.5", "Fold", "Increase", "halflife-text-2")205 ## material 2 validation206 testParticipants(dmRow2.participants, "210", "participants-text-2")207 testMaterialDose(dmRow2.precipitant_dose, "precipitant_dose", "atorvastatin", "302", "Oral", "10", "BID", "drug2Dose-text-2")208 testMaterialDose(dmRow2.object_dose, "object_dose", "telaprevir", "201", "Oral", "120", "Q3", "drug1Dose-text-2")209def test_phenotype_clinical_study_1(conn, template):210 print "[INFO] =====begin test phenotype clinical study annotation 1 ============"211 annotationUrn = "test-phenotypeclinicalstudy-id-1"212 annotation = etlAnnForTesting(conn, template, annotationUrn)213 ## claim validation214 print "[INFO] ================= Begin validating MP Claim ======================"215 testClaim(annotation, "test-phenotypeclinicalstudy-id-1", "drugname1_substrate of_enzyme1", "claim-text", "Phenotype clinical study", False, True, "rejected-reason", "rejected-comment")216 ## qualifiers217 testQualifier(annotation.csubject, "drugname1", True, False, False, True, True)218 testQualifier(annotation.cpredicate, "substrate of", False, True, False, None, None)219 testQualifier(annotation.cobject, "enzyme1", False, False, True, None, None)220 ## data 1 validation221 print "[INFO] ================= Begin validating MP data ======================="222 dmRow1 = annotation.getSpecificDataMaterial(0)223 testEvRelationship(dmRow1, False)224 testEvTypeQuestion(dmRow1, "yes", None)225 testDataRatio(dmRow1.auc, "auc", "1.2", "Fold", "Increase", "auc-text-1")226 testDataRatio(dmRow1.cmax, "cmax", "1.6", "Percent", "Increase", "cmax-text-1")227 testDataRatio(dmRow1.clearance, "clearance", "8.8", "Percent", "Increase", "clearance-text-1")228 testDataRatio(dmRow1.halflife, "halflife", "2.5", "Percent", "Decrease", "halflife-text-1")229 ## material 1 validation230 testParticipants(dmRow1.participants, "1.00", "participants-text-1")231 testPhenotype(dmRow1.phenotype, "Genotype", "BRAF", "Poor Metabolizer", "Asian", "phenotype-text-1")232 testMaterialDose(dmRow1.probesubstrate_dose, "probesubstrate_dose", "drugname1", "10", "IV", "23", "Q6", "drug1Dose-text-1")233 234def test_case_report_1(conn, template):235 print "[INFO] =====begin test case report annotation 1 =========================="236 annotationUrn = "test-casereport-id-1"237 annotation = etlAnnForTesting(conn, template, annotationUrn)238 ## claim validation239 print "[INFO] ================= Begin validating MP Claim ======================"240 testClaim(annotation, "test-casereport-id-1", "drugname1_interact with_drugname2", "claim-text", "Case Report", False, True, "test-reason", "test-comment")241 ## qualifiers242 testQualifier(annotation.csubject, "drugname1", True, False, False, False, False)243 testQualifier(annotation.cpredicate, "interact with", False, True, False, None, None)244 testQualifier(annotation.cobject, "drugname2", False, False, True, False, False)245 print "[INFO] ================= Begin validating MP data ======================="246 dmRow1 = annotation.getSpecificDataMaterial(0)247 testDataReviewer(dmRow1.reviewer, "External","02/22/2017", "-1", "false")248 testDataDipsQs(dmRow1.dipsquestion, {"q1":"Yes","q2":"Yes","q10":"No","q3":"No","q4":"No","q5":"NA","q6":"UNK/NA","q7":"UNK/NA","q8":"No","q9":"NA"})249 testMaterialDose(dmRow1.precipitant_dose, "precipitant_dose", "drugname1", "13", "IV", "22", "Q6", "drug1Dose-text-1")250 testMaterialDose(dmRow1.object_dose, "object_dose", "drugname2", "56", "IV", "65", "Q6", "drug2Dose-text-1")251# Validate statement annotation 252def test_statement_1(conn, template):253 print "[INFO] ===== begin test statement annotation 1 ======================"254 annUrn = "test-statement-id-1"255 annotation = etlAnnForTesting(conn, template, annUrn)256 if isinstance(annotation, Statement):257 ## claim validation258 print "[INFO] ================= Begin validating MP Statement ===================="259 testClaim(annotation, "test-statement-id-1", "drugn1_inhibits_enzyme1", "claim-text", "Statement", True, True, "rejected-reason", "")260 ## qualifiers261 testQualifier(annotation.csubject, "drugn1", True, False, False, True, True)262 testQualifier(annotation.cpredicate, "inhibits", False, True, False, None, None)263 testQualifier(annotation.cobject, "enzyme1", False, False, True, None, None)264## MAIN ############################################################################265def test():266 PG_HOST = "localhost"267 PG_USER = "dbmiannotator"268 PG_PASSWORD = "dbmi2016"269 PG_DATABASE = "mpevidence"270 conn = pgconn.connect_postgres(PG_HOST, PG_USER, PG_PASSWORD, PG_DATABASE)271 pgconn.setDbSchema(conn, "ohdsi")272 ## clean postgres273 pgmp.clearAll(conn); conn.commit()274 MP_ANN_1 = "./template/test-clinicaltrial-1.json"275 test_clinical_trial_1(conn, MP_ANN_1)276 MP_ANN_2 = "./template/test-phenotypeclinicalstudy-1.json"277 test_phenotype_clinical_study_1(conn, MP_ANN_2)278 MP_ANN_3 = "./template/test-casereport-1.json"279 test_case_report_1(conn, MP_ANN_3)280 MP_ANN_4 = "./template/test-statement-1.json"281 test_statement_1(conn, MP_ANN_4)282 conn.close()283## MAIN ######################################################284if __name__ == '__main__':...
within10ms.py
Source:within10ms.py
1import os #for accessing and iterating through directories2import statistics #for calculating standard deviation3import matplotlib.pyplot as plt #for generating histogram4from statsmodels.graphics import tsaplots #for autocorrelation function5import numpy as np #for autocorrelation6import scipy7from scipy import signal8from pandas import read_csv9from statsmodels.graphics.tsaplots import plot_acf10import csv11class Event():12 scope = '' #initialized to null string13 timestamp = 0 #initialized to zero14 voltage = 0 #this is the voltage from the ramp. It is initialized to zero15 isMatched = False #initialized to false because the event hasn't been matched to a corrsponding one yet16 def __init__(self, scp, time, volt): #we will include voltage as soon as we figure out how to record from multiple sources in Waveforms 201517 self.scope = scp18 self.timestamp = time19 self.voltage = volt20#anodeDir = 'C:\\Users\\skyfab\\Documents\\Waveforms\\Data Scenario 2\\anode' #folder path to .csv acquisitions for AD1 in scenario 121#pmtDir = 'C:\\Users\\skyfab\\Documents\\Waveforms\\Data Scenario 2\pmt' #folder path to .csv acquisitions for AD2 in scenario 122#anodeDir = 'C:\\Users\\skyfab\\Documents\\Waveforms\\Data Scenario 1\\AD1 run 27' #folder path to .csv acquisitions for AD1 in scenario 123#pmtDir = 'C:\\Users\\skyfab\\Documents\\Waveforms\\Data Scenario 1\\AD2 run 27' #folder path to .csv acquisitions for AD2 in scenario 124anodeDir = 'C:\\Users\\skyfab\Documents\\Waveforms\\Data Scenario 1 with voltages\\AD1' #folder path to .csv acquisitions for AD1 in scenario 125pmtDir = 'C:\\Users\\skyfab\Documents\\Waveforms\\Data Scenario 1 with voltages\\AD2' #folder path to .csv acquisitions for AD2 in scenario 126anode = []27pmt = []28difsXaxis = [] #number of time differences recorded29for filename in os.listdir(anodeDir):30 name = os.path.join(anodeDir, filename) #store the name of the file in 'name'31 index = len(name) - 5 #len(name) is the number of characters in name, and len(name) - 5 is ones place of the milliseconds in the timestamp 32 #example: name = 'C:\Users\skyfab\Documents\Waveforms\Data\anode\anode12.25.43.116.csv' 33 #the character name[index] corresponds to 6. We use the function int() to cast the character to an integer value34 35 timeStampVal = int(name[index - 8]) * 600000 + int(name[index - 7]) * 60000 + int(name[index - 5]) * 10000 + int(name[index - 4]) * 1000 + int(name[index - 2]) * 100 + int(name[index - 1]) * 10 + int(name[index]) #converting the timestamp to milliseconds36 #anodeTimes.append(timeStampVal) #add timestamp value to anodeTimes37 38 volt = 039 40 with open(name) as f:41 rows = list(csv.reader(f))42 volt += float(rows[21][1])43 44 anode.append(Event("AD1", timeStampVal, volt))45 46for filename in os.listdir(pmtDir):47 name = os.path.join(pmtDir, filename) 48 index = len(name) - 549 50 timeStampVal = int(name[index - 8]) * 600000 + int(name[index - 7]) * 60000 + int(name[index - 5]) * 10000 + int(name[index - 4]) * 1000 + int(name[index - 2]) * 100 + int(name[index - 1]) * 10 + int(name[index]) #converting the timestamp to milliseconds51 #pmtTimes.append(timeStampVal) #add timestamp value to pmtTimes52 volt = 053 54 with open(name) as f:55 rows = list(csv.reader(f))56 volt += float(rows[21][1])57 58 pmt.append(Event("AD2", timeStampVal, volt))59#the following section is supposed to get rid of acquisition duplicates60'''61Evan's within dT = 10 milliseconds algorithm62step 1: determine which oscilloscope took more acquisitions. This is the list we are going to pop aquisitions from63step 2: start at the beginning of the larger list and see if the acquisition across is within 10 seconds.64 if it is, move on to the next acquisition in the larger list.65 If not, check if the next acquisition has a smaller time difference66 if it is, check if the acquisition is within 10 seconds. if not check if the next acquisition has a smaller time difference67 if not, move on to the next acquisition in the larger list 68'''69pairedAnode = [] #these lists will contain the paired acquisitions70pairedPmt = []71numTossed = 0 #number of events removed72anodeLen = len(anode) #73pmtLen = len(pmt)74#for when pmt has more acquisitions than anode 75if(pmtLen > anodeLen):76 for i in range(len(anode)):77 wasMatch = False78 if(i == 0): #if you are looking at the first element in the large list, compare it to the next three acquisitions79 for j in range(3):80 if(abs(anode[i].timestamp - pmt[i + j].timestamp) < 10 and not anode[i].isMatched and not pmt[i+j].isMatched):81 pairedAnode.append(anode[i])82 pairedPmt.append(pmt[i + j])83 anode[i].isMatched = True84 pmt[i + j].isMatched = True85 wasMatch = True86 elif(i == len(anode) - 1): #if you are looking at the last element in the large list, compare it to the next three acquisitions87 for j in range(3):88 if(abs(anode[i].timestamp - pmt[i - j].timestamp) < 10 and not anode[i].isMatched and not pmt[i-j].isMatched):89 pairedAnode.append(anode[i])90 pairedPmt.append(pmt[i - j])91 anode[i].isMatched = True92 pmt[i - j].isMatched = True93 wasMatch = True94 else:95 for j in range(3):96 if(abs(anode[i].timestamp - pmt[i - 1 + j].timestamp) < 10 and not anode[i].isMatched and not pmt[i - 1 + j].isMatched):97 pairedAnode.append(anode[i])98 pairedPmt.append(pmt[i - 1 + j])99 anode[i].isMatched = True100 pmt[i - 1 + j].isMatched = True 101 wasMatch = True102 if(not wasMatch):103 numTossed += 1104#for when anode has more acquisitions than pmt105if(anodeLen > pmtLen):106 for i in range(len(pmt)):107 wasMatch = False108 if(i == 0): #if you are looking at the first element in the large list, compare it to the next three acquisitions109 for j in range(3):110 if(abs(pmt[i].timestamp - anode[i + j].timestamp) < 10 and not pmt[i].isMatched and not anode[i+j].isMatched):111 pairedPmt.append(pmt[i])112 pairedAnode.append(anode[i + j])113 pmt[i].isMatched = True114 anode[i + j].isMatched = True115 wasMatch = True116 elif(i == len(pmt) - 1): #if you are looking at the last element in the large list, compare it to the next three acquisitions117 for j in range(3):118 if(abs(pmt[i].timestamp - anode[i - j].timestamp) < 10 and not pmt[i].isMatched and not anode[i-j].isMatched):119 pairedPmt.append(pmt[i])120 pairedAnode.append(anode[i - j])121 pmt[i].isMatched = True122 anode[i - j].isMatched = True123 wasMatch = True124 else:125 for j in range(3):126 if(abs(pmt[i].timestamp - anode[i - 1 + j].timestamp) < 10 and not pmt[i].isMatched and not anode[i - 1 + j].isMatched):127 pairedPmt.append(pmt[i])128 pairedAnode.append(anode[i - 1 + j])129 pmt[i].isMatched = True130 anode[i - 1 + j].isMatched = True 131 wasMatch = True132 133 if(not wasMatch):134 numTossed += 1135'''136if(anodeLen > pmtLen):137 for i in range(len(anode):138 isMatched = False139 for j in range(3):140 if(abs(anode[i].timestamp - pmt[i +j].timestamp) < 10 and not isMatched):141 pairedAnode.append(anode[i])142 pairedPmt.append(pmt[i + j])143 isMatched = True144elif(pmtLen > anodeLen):145 for i in range(len(pmt)):146 isMatched = False147 for j in range(3):148 if(abs(pmt[i].timestamp - anode[i+ j].timestamp) < 10 and not isMatched):149 pairedPmt.append(pmt[i])150 pairedAnode.append(anode[i+j])151 isMatched = True 152''' 153 154 155#The following section can be uncommented to display the timestamp values in anodeTimes and pmtTimes156#This process slows down the program157'''158print("-------------------- now displaying anodeTimes --------------") 159for i in range(len(anodeTimes)): #iterate through and print timestamp values of anodeTimes160 print(anodeTimes[i])161 print('\n')162print("-------------------- now displaying pmtTimes --------------")163 164for i in range(len(pmtTimes)): #iterate through and print timestamp values of pmtTimes165 print(pmtTimes[i])166 print('\n')167'''168timeDifs = [] #difference between timestamps is stored here169voltDifs = [] #difference between voltages is stored here170count = 1 #serves as an index for the time differences171#for a, p in zip(anodeTimes, pmtTimes): 172for a, p in zip(pairedAnode, pairedPmt):173 #timeDifs.append( abs(a - p) )174 timeDifs.append(abs(a.timestamp - p.timestamp))175 voltDifs.append(abs(a.voltage - p.voltage))176 print("%1d %10d %20s %10f %20s %f %20s %10d" % (count, abs(a.timestamp - p.timestamp), "anode voltage: ", a.voltage, "pmt voltage: ", p.voltage, "voltage diff: ", abs(a.voltage - p.voltage)))177 difsXaxis.append(count)178 count += 1179print("\n")180print("The average time difference between the two oscilloscopes is: ")181print(sum(timeDifs) / len(timeDifs)) #print average182print("\n")183print("the standard deviation is:") #print standard deviation184print(statistics.stdev(timeDifs))185print("\n")186print("the median is:")187print(statistics.median(timeDifs)) #print median188print('\n\n')189print("The average voltage difference between the two oscilloscopes is: ") #not sure if I want to plot this yet190print(sum(voltDifs) / len(voltDifs)) #print average191print("\n")192print("the standard deviation is:") #print standard deviation193print(statistics.stdev(voltDifs))194print("\n")195print("the median is:")196print(statistics.median(voltDifs)) 197print('\n\n')198print("the number of acquisitions for AD1 is:") #print number of acquisitions199print(len(pairedAnode))200print("the number of acquisitions for AD2 is:")201print(len(pairedPmt))202print('\n\n')203print("The number of acquisitions tossed is:")204print(numTossed)205#figure something out for bipolar distributions206#The following lines generate a histogram in a popup window207fig, (ax1, ax2, ax3, ax4) = plt.subplots(4) # create figure and axes208ax1.hist(timeDifs, bins = 'auto') #figure out how to make bin width 1 ms209ax1.set_title('Time Differences')210ax1.set_xlabel('Time Difference in Milliseconds')211ax1.set_ylabel('Frequency')212count = 1213anodeXaxis = []214pmtXaxis = []215while(count <= len(pairedAnode)):216 anodeXaxis.append(count)217 count += 1218count = 1219#while(count <= len(pmtTimes)):220while(count <= len(pairedPmt)):221 pmtXaxis.append(count)222 count += 1223#ax2.scatter(anodeXaxis, anodeTimes, color="b")224#ax2.scatter(pmtXaxis, pmtTimes, color="r", marker="P")225anodeTimes = []226pmtTimes = []227for i in range(len(pairedAnode)):228 anodeTimes.append(pairedAnode[i].timestamp)229for i in range(len(pairedPmt)):230 pmtTimes.append(pairedPmt[i].timestamp)231ax2.scatter(anodeXaxis, anodeTimes, color="b")232ax2.scatter(pmtXaxis, pmtTimes, color="r", marker="P")233ax2.set_xlabel('acquisition number')234ax2.set_ylabel('Time in miliseconds') 235ax3.scatter(difsXaxis, timeDifs)236ax3.set_xlabel('acq number')237ax3.set_ylabel('Time difs in miliseconds') 238#corr = signal.correlate(anodeTimes, pmtTimes, mode = 'full', method = 'auto')239corr = signal.correlate(anodeTimes, pmtTimes, mode = 'full', method = 'auto')240ax4.plot(corr)241'''242autocorr = np.correlate(anodeTimes, pmtTimes, mode = 'valid')243print('\n\n')244for i in range(len(autocorr)):245 print(autocorr[i])246'''247plt.show()248#pmt folder usually has one more acquisition than the anode folder. This can cause l#arge discrepancies when 249#multiple acquisitions runs are kept in the same folder as non-corresponding acquisitions are subtracted...
schulte.ts
Source:schulte.ts
1import { defineStore } from 'pinia'2// å®ä¹æ°æ®ä»åº3import axios from 'axios'45export const useSchulteStore = defineStore('schulte', {6 state: () => {7 return {8 numbers5x5: [9 { id: 1, value: 1, isChecked: false, isMatched: false },10 { id: 2, value: 2, isChecked: false, isMatched: false },11 { id: 3, value: 3, isChecked: false, isMatched: false },12 { id: 4, value: 4, isChecked: false, isMatched: false },13 { id: 5, value: 5, isChecked: false, isMatched: false },14 { id: 6, value: 6, isChecked: false, isMatched: false },15 { id: 7, value: 7, isChecked: false, isMatched: false },16 { id: 8, value: 8, isChecked: false, isMatched: false },17 { id: 9, value: 9, isChecked: false, isMatched: false },18 { id: 10, value: 10, isChecked: false, isMatched: false },19 { id: 11, value: 11, isChecked: false, isMatched: false },20 { id: 12, value: 12, isChecked: false, isMatched: false },21 { id: 13, value: 13, isChecked: false, isMatched: false },22 { id: 14, value: 14, isChecked: false, isMatched: false },23 { id: 15, value: 15, isChecked: false, isMatched: false },24 { id: 16, value: 16, isChecked: false, isMatched: false },25 { id: 17, value: 17, isChecked: false, isMatched: false },26 { id: 18, value: 18, isChecked: false, isMatched: false },27 { id: 19, value: 19, isChecked: false, isMatched: false },28 { id: 20, value: 20, isChecked: false, isMatched: false },29 { id: 21, value: 21, isChecked: false, isMatched: false },30 { id: 22, value: 22, isChecked: false, isMatched: false },31 { id: 23, value: 23, isChecked: false, isMatched: false },32 { id: 24, value: 24, isChecked: false, isMatched: false },33 { id: 25, value: 25, isChecked: false, isMatched: false },34 ],35 number3x3: [36 { id: 1, value: 1, isChecked: false, isMatched: false },37 { id: 2, value: 2, isChecked: false, isMatched: false },38 { id: 3, value: 3, isChecked: false, isMatched: false },39 { id: 4, value: 4, isChecked: false, isMatched: false },40 { id: 5, value: 5, isChecked: false, isMatched: false },41 { id: 6, value: 6, isChecked: false, isMatched: false },42 { id: 7, value: 7, isChecked: false, isMatched: false },43 { id: 8, value: 8, isChecked: false, isMatched: false },44 { id: 9, value: 9, isChecked: false, isMatched: false },45 ],46 number4x4: [47 { id: 1, value: 1, isChecked: false, isMatched: false },48 { id: 2, value: 2, isChecked: false, isMatched: false },49 { id: 3, value: 3, isChecked: false, isMatched: false },50 { id: 4, value: 4, isChecked: false, isMatched: false },51 { id: 5, value: 5, isChecked: false, isMatched: false },52 { id: 6, value: 6, isChecked: false, isMatched: false },53 { id: 7, value: 7, isChecked: false, isMatched: false },54 { id: 8, value: 8, isChecked: false, isMatched: false },55 { id: 9, value: 9, isChecked: false, isMatched: false },56 { id: 10, value: 10, isChecked: false, isMatched: false },57 { id: 11, value: 11, isChecked: false, isMatched: false },58 { id: 12, value: 12, isChecked: false, isMatched: false },59 { id: 13, value: 13, isChecked: false, isMatched: false },60 { id: 14, value: 14, isChecked: false, isMatched: false },61 { id: 15, value: 15, isChecked: false, isMatched: false },62 { id: 16, value: 16, isChecked: false, isMatched: false },63 ], 64 letter5x6: [65 { id: 1, value: 'A', isChecked: false, isMatched: false },66 { id: 2, value: 'B', isChecked: false, isMatched: false },67 { id: 3, value: 'C', isChecked: false, isMatched: false },68 { id: 4, value: 'D', isChecked: false, isMatched: false },69 { id: 5, value: 'E', isChecked: false, isMatched: false },70 { id: 6, value: 'F', isChecked: false, isMatched: false },71 { id: 7, value: 'G', isChecked: false, isMatched: false },72 { id: 8, value: 'H', isChecked: false, isMatched: false },73 { id: 9, value: 'I', isChecked: false, isMatched: false },74 { id: 10, value: 'J', isChecked: false, isMatched: false },75 { id: 11, value: 'K', isChecked: false, isMatched: false },76 { id: 12, value: 'L', isChecked: false, isMatched: false },77 { id: 13, value: 'M', isChecked: false, isMatched: false },78 { id: 14, value: 'N', isChecked: false, isMatched: false },79 { id: 15, value: 'O', isChecked: false, isMatched: false },80 { id: 16, value: 'P', isChecked: false, isMatched: false },81 { id: 17, value: 'Q', isChecked: false, isMatched: false },82 { id: 18, value: 'R', isChecked: false, isMatched: false },83 { id: 19, value: 'S', isChecked: false, isMatched: false },84 { id: 20, value: 'T', isChecked: false, isMatched: false },85 { id: 21, value: 'U', isChecked: false, isMatched: false },86 { id: 22, value: 'V', isChecked: false, isMatched: false },87 { id: 23, value: 'W', isChecked: false, isMatched: false },88 { id: 24, value: 'X', isChecked: false, isMatched: false },89 { id: 25, value: 'Y', isChecked: false, isMatched: false },90 { id: 26, value: 'Z', isChecked: false, isMatched: false },91 ], 92 zhcn5x6: [93 { id: 1, value: 'æ¥', isChecked: false, isMatched: false },94 { id: 2, value: 'ç
§', isChecked: false, isMatched: false },95 { id: 3, value: 'é¦', isChecked: false, isMatched: false },96 { id: 4, value: 'ç', isChecked: false, isMatched: false },97 { id: 5, value: 'ç', isChecked: false, isMatched: false },98 { id: 6, value: 'ç´«', isChecked: false, isMatched: false },99 { id: 7, value: 'ç', isChecked: false, isMatched: false },100 { id: 8, value: 'é¥', isChecked: false, isMatched: false },101 { id: 9, value: 'ç', isChecked: false, isMatched: false },102 { id: 10, value: 'ç', isChecked: false, isMatched: false },103 { id: 11, value: 'å¸', isChecked: false, isMatched: false },104 { id: 12, value: 'æ', isChecked: false, isMatched: false },105 { id: 13, value: 'å', isChecked: false, isMatched: false },106 { id: 14, value: 'å·', isChecked: false, isMatched: false },107 { id: 15, value: 'é£', isChecked: false, isMatched: false },108 { id: 16, value: 'æµ', isChecked: false, isMatched: false },109 { id: 17, value: 'ç´', isChecked: false, isMatched: false },110 { id: 18, value: 'ä¸', isChecked: false, isMatched: false },111 { id: 19, value: 'ä¸', isChecked: false, isMatched: false },112 { id: 20, value: 'å', isChecked: false, isMatched: false },113 { id: 21, value: 'å°º', isChecked: false, isMatched: false },114 { id: 22, value: 'ç', isChecked: false, isMatched: false },115 { id: 23, value: 'æ¯', isChecked: false, isMatched: false },116 { id: 24, value: 'é¶', isChecked: false, isMatched: false },117 { id: 25, value: 'æ²³', isChecked: false, isMatched: false },118 { id: 26, value: 'è½', isChecked: false, isMatched: false },119 { id: 27, value: 'ä¹', isChecked: false, isMatched: false },120 { id: 28, value: '天', isChecked: false, isMatched: false },121 ], 122 }123 },124 getters: {125 square3x3: (state) => {126 const shuffle = arr => arr.sort(() => 0.5 - Math.random())127 return shuffle(state.number3x3)128 },129130 square4x4: (state) => {131 const shuffle = arr => arr.sort(() => 0.5 - Math.random())132 return shuffle(state.number4x4)133 },134 square5x5N: (state) => {135 const shuffle = arr => arr.sort(() => 0.5 - Math.random())136 return shuffle(state.numbers5x5)137 },138 square5x6L: (state) => {139 const shuffle = arr => arr.sort(() => 0.5 - Math.random())140 return shuffle(state.letter5x6)141 },142 square5x6CN: (state) => {143 const shuffle = arr => arr.sort(() => 0.5 - Math.random())144 return shuffle(state.zhcn5x6)145 },146147 },148 actions: {149 handleClick() {150 this.isChecked = !this.isChecked151152 },153154 },
...
video-game.functions.spec.ts
Source:video-game.functions.spec.ts
1import { createDefaultVideoGameFilters, IVideoGameFilters } from '../video-game-listing';2import { IVideoGame } from './video-game.interface';3import {4 videoGameMatchesFavoritesFilter,5 videoGameMatchesPlatformFilter,6 videoGameMatchesSearchQuery7} from './video-game.functions';8describe('with Super Mario Odyssey', () => {9 let superMarioOdyssey: IVideoGame;10 beforeEach(() => {11 superMarioOdyssey = {12 id: '1',13 title: 'Super Mario Odyssey',14 description: 'description',15 platform: 'Nintendo Switch',16 youtubeUrl: 'youtube.com',17 favorite: false,18 };19 });20 describe('videoGameMatchesSearchQuery(superMarioOdyssey, "Super")', () => {21 it('returns true', () => {22 const isMatched = videoGameMatchesSearchQuery(superMarioOdyssey, 'Super');23 expect(isMatched).toEqual(true);24 });25 });26 describe('videoGameMatchesSearchQuery(superMarioOdyssey, "Zelda")', () => {27 it('returns false', () => {28 const isMatched = videoGameMatchesSearchQuery(superMarioOdyssey, 'Zelda');29 expect(isMatched).toEqual(false);30 });31 });32 describe('videoGameMatchesSearchQuery(superMarioOdyssey, "")', () => {33 it('returns true', () => {34 const isMatched = videoGameMatchesSearchQuery(superMarioOdyssey, '');35 expect(isMatched).toEqual(true);36 });37 });38 describe('videoGameMatchesSearchQuery(superMarioOdyssey, falsy)', () => {39 it('returns true', () => {40 const isMatched = videoGameMatchesSearchQuery(superMarioOdyssey, null);41 expect(isMatched).toEqual(true);42 });43 });44 describe('videoGameMatchesPlatformFilter(superMarioOdyssey, nintendoSwitch)', () => {45 it('returns true', () => {46 const nintendoSwitch: IVideoGameFilters = {47 ...createDefaultVideoGameFilters(),48 platform: 'Nintendo Switch',49 };50 const isMatched = videoGameMatchesPlatformFilter(superMarioOdyssey, nintendoSwitch);51 expect(isMatched).toEqual(true);52 });53 });54 describe('videoGameMatchesPlatformFilter(superMarioOdyssey, nintendoSwitch)', () => {55 it('returns true', () => {56 const nintendoSwitch: IVideoGameFilters = {57 ...createDefaultVideoGameFilters(),58 platform: 'Nintendo Switch',59 };60 const isMatched = videoGameMatchesPlatformFilter(superMarioOdyssey, nintendoSwitch);61 expect(isMatched).toEqual(true);62 });63 });64 describe('videoGameMatchesPlatformFilter(superMarioOdyssey, pc)', () => {65 it('returns false', () => {66 const pc: IVideoGameFilters = {67 ...createDefaultVideoGameFilters(),68 platform: 'PC',69 };70 const isMatched = videoGameMatchesPlatformFilter(superMarioOdyssey, pc);71 expect(isMatched).toEqual(false);72 });73 });74 describe('videoGameMatchesPlatformFilter(superMarioOdyssey, falsy)', () => {75 it('returns true', () => {76 const isMatched = videoGameMatchesPlatformFilter(superMarioOdyssey, null);77 expect(isMatched).toEqual(true);78 });79 });80 describe('and it is favourited', () => {81 beforeEach(() => {82 superMarioOdyssey = { ...superMarioOdyssey, favorite: true };83 });84 describe('videoGameMatchesFavoritesFilter(superMarioOdyssey, favorites:true)', () => {85 it('returns true', () => {86 const showFavorites: IVideoGameFilters = {87 ...createDefaultVideoGameFilters(),88 favorites: true,89 };90 const isMatched = videoGameMatchesFavoritesFilter(superMarioOdyssey, showFavorites);91 expect(isMatched).toEqual(true);92 });93 });94 describe('videoGameMatchesFavoritesFilter(superMarioOdyssey, favorites:false)', () => {95 it('returns true', () => {96 const showFavorites: IVideoGameFilters = {97 ...createDefaultVideoGameFilters(),98 favorites: false,99 };100 const isMatched = videoGameMatchesFavoritesFilter(superMarioOdyssey, showFavorites);101 expect(isMatched).toEqual(true);102 });103 });104 });105 describe('and it is not favourited', () => {106 beforeEach(() => {107 superMarioOdyssey = { ...superMarioOdyssey, favorite: false };108 });109 describe('videoGameMatchesFavoritesFilter(superMarioOdyssey, favorites:true)', () => {110 it('returns false', () => {111 const filters: IVideoGameFilters = {112 ...createDefaultVideoGameFilters(),113 favorites: true,114 };115 const isMatched = videoGameMatchesFavoritesFilter(superMarioOdyssey, filters);116 expect(isMatched).toEqual(false);117 });118 });119 describe('videoGameMatchesFavoritesFilter(superMarioOdyssey, favorites:false)', () => {120 it('returns true', () => {121 const filters: IVideoGameFilters = {122 ...createDefaultVideoGameFilters(),123 favorites: false,124 };125 const isMatched = videoGameMatchesFavoritesFilter(superMarioOdyssey, filters);126 expect(isMatched).toEqual(true);127 });128 });129 });130});131describe('when the game is falsy', () => {132 describe('videoGameMatchesSearchQuery(falsy, "Super")', () => {133 it('returns false', () => {134 const isMatched = videoGameMatchesSearchQuery(null, 'Super');135 expect(isMatched).toEqual(false);136 });137 });138 describe('videoGameMatchesPlatformFilter(falsy, "Nintendo Switch")', () => {139 const nintendoSwitch: IVideoGameFilters = {140 ...createDefaultVideoGameFilters(),141 platform: 'Nintendo Switch'142 };143 it('returns false', () => {144 const isMatched = videoGameMatchesPlatformFilter(null, nintendoSwitch);145 expect(isMatched).toEqual(false);146 });147 });...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!