Exemplo n.º 1
0
 def chooserFunction(self,req):
   try:      
     res = testSelectorSrvResponse()
     currentTimestamp = int(time.time())      
     #Load parameters from yaml file
     difficultyModifier1to2,difficultyModifier2to3,historyBasedOnNumOfTestsAndNotTime,pastMonths,pastTests,lookBackTimeStamp=self.loadParamDifficultyModifiersAndHistorySettings()
     #Get user ontology alias
     userOntologyAlias=CognitiveExerciseHelperFunctions.getUserOntologyAlias(req.username)      
     #Get user language
     userLanguage=CognitiveExerciseHelperFunctions.getUserLanguage(req.username)
     res.language=userLanguage      
     #Manual test selection
     if(not req.testDifficulty=="" or not req.testIndex==""): 
       self.selectTestManuallyByGivenParameters(req.testType,req.testSubType,req.testIndex,req.testDifficulty,userLanguage,res)       
     else:
       #Get test types from ontology
       testTypesList=CognitiveExerciseHelperFunctions.getTestTypesFromOntology()
       #Determine the test type of the to be selected test
       testType=self.determineTestType(req.testType,req.testSubType,testTypesList,userOntologyAlias,res.trace)        
       #Get user performance records and determine difficulty of the to be selected test for given test type
       chosenDif,noUserPerformanceRecordsExist,userPerfOrganizedByTimestamp=self.getUserPerformanceRecordsAndDetermineTestDifficultyForTestType(testType,userOntologyAlias,currentTimestamp,lookBackTimeStamp,difficultyModifier1to2,difficultyModifier2to3,historyBasedOnNumOfTestsAndNotTime,pastTests,res.trace)
       #Get all tests of a give type from the ontology
       testsOfTypeOrdered=self.getCognitiveTestsAndFilterByParameters(testType,req.testSubType,userLanguage,chosenDif,res.trace)            
       #Determine the least recently used (LRU) test and retrieve the .xml test file
       testName,testFilePath=self.getLRUtestOfTypeAndXmlPath(testsOfTypeOrdered,noUserPerformanceRecordsExist,userPerfOrganizedByTimestamp)      
       #res.test=testName
       #Parse the .xml test file name and assign the data to the testSelectorSrvResponse response srv           
       self.retrieveDataFromTestXml(testFilePath,userLanguage,res)      
     res.success=True
   except IndexError, e:
     res.trace.append("IndexError: " +str(e))
     res.error="IndexError: "+str(e)
     res.success=False
     CognitiveExerciseHelperFunctions.traceError(res.error,res.trace)
 def assignTestHistoryForTestCategoriesToSrv(self,testTypesList,userOntologyAlias,fromTime,toTime,res):        
  for s in testTypesList:
     userPerformanceResponse=CognitiveExerciseHelperFunctions.getUserPerformanceRecordsForTestType(s,userOntologyAlias)            
     if(userPerformanceResponse.success==True): 
       userPerfOrganizedByTimestamp=CognitiveExerciseHelperFunctions.organizeUserPerformanceByTimestamp(userPerformanceResponse)
       sumCategoryScore=0
       sumCategoryScoreDivideBy=0;
       countValidTests=0;
       arrayCognitiveExercisePerformanceRecords=ArrayCognitiveExercisePerformanceRecordsMsg()
       for k, v in userPerfOrganizedByTimestamp.items():
         if(k<fromTime or k>toTime):
           del userPerfOrganizedByTimestamp[k]
         else:
           tmpRecord=CognitiveExercisePerformanceRecordsMsg()
           tmpRecord.timestamp=k
           tmpList=v[0][0].split('#') 
           if (tmpList[1] is not None):
             tmpRecord.test=tmpList[1]
           tmpRecord.score=long(v[0][1])           
           tmpRecord.difficulty=v[0][2]
           tmpList=v[0][3].split('#')
           if (tmpList[1] is not None):
             tmpRecord.subtype=tmpList[1]
           tmpRecord.type=s
           countValidTests=countValidTests+1
           sumCategoryScore=sumCategoryScore+long(v[0][2])*long(v[0][1])  #[0][2] is difficulty, [0][1] is score         
           sumCategoryScoreDivideBy=sumCategoryScoreDivideBy+long(v[0][2])            
           tmpAverageCategoryScore=float(sumCategoryScore/sumCategoryScoreDivideBy)
           tmpRecord.meanScoreForTypeUpToNow=tmpAverageCategoryScore
           arrayCognitiveExercisePerformanceRecords.records.append(tmpRecord)
       res.recordsPerTestType.append(arrayCognitiveExercisePerformanceRecords)
 def returnTestsFunction(self,req):
   try:      
     res = returnTestsOfTypeSubtypeDifficultySrvResponse()
     if(req.testType==""):
       error="Error, empty testType field"
       raise AppError(error, error)
     supportedLanguages=CognitiveExerciseHelperFunctions.getTestLanguagesFromOntology()      
     keepEntries = dict()
     testCount=0      
     for currentLanguage in supportedLanguages:
       cognitiveTestsOfTypeResponse=CognitiveExerciseHelperFunctions.getCognitiveTestsOfType(req.testType,currentLanguage)        
       tests=CognitiveExerciseHelperFunctions.filterTestsbyDifficultyAndSubtype(cognitiveTestsOfTypeResponse,req.difficulty,req.testSubType)       
       if(req.language=="" or currentLanguage==req.language):
         for k, v in tests.items():
           if(not k in keepEntries):
             currentCognitiveTest =  CognitiveExercisesMsg()
             currentCognitiveTest.testName=k.split('#')[1]
             currentCognitiveTest.testType=req.testType
             currentCognitiveTest.testSubType=(v[0][2]).split('#')[1]
             currentCognitiveTest.testSubType=(v[0][2]).split('#')[1]
             currentCognitiveTest.difficulty=(v[0][1])
             currentCognitiveTest.test_id=(v[0][3])
             currentCognitiveTest.languages.append(currentLanguage)              
             res.cognitiveExercises.append(currentCognitiveTest)
             keepEntries[k]=testCount
             testCount=testCount+1
           else:
             res.cognitiveExercises[keepEntries[k]].languages.append(currentLanguage)
     res.totalNumberOfTestsReturned=testCount
     res.success=True
   except IndexError, e:
     res.trace.append("IndexError: " +str(e))
     res.error="IndexError: "+str(e)
     res.success=False
     CognitiveExerciseHelperFunctions.traceError(res.error,res.trace)
 def recordPerformance(self, req):
     try:
         res = recordUserCognitiveTestPerformanceSrvResponse()
         userOntologyAlias = CognitiveExerciseHelperFunctions.getUserOntologyAlias(
             req.username)
         serv_topic = rospy.get_param(
             'rapp_knowrob_wrapper_record_user_cognitive_tests_performance')
         knowrob_service = rospy.ServiceProxy(
             serv_topic, recordUserPerformanceCognitiveTestsSrv)
         userPerformanceEntry = recordUserPerformanceCognitiveTestsSrvRequest(
         )
         userPerformanceEntry.test = req.test
         userPerformanceEntry.patient_ontology_alias = userOntologyAlias
         userPerformanceEntry.timestamp = int(time.time())
         userPerformanceEntry.score = req.score
         userPerformanceEntryResponse = knowrob_service(
             userPerformanceEntry)
         if (userPerformanceEntryResponse.success != True):
             error = userPerformanceEntryResponse.error + "Submitting query to ontology failed, either test or user ontology alias do not exist or test not of the given type"
             raise AppError(error, error)
         else:
             res.success = True
             res.userCognitiveTestPerformanceEntry = userPerformanceEntryResponse.cognitive_test_performance_entry
     except IndexError, e:
         res.trace.append("IndexError: " + str(e))
         res.error = "IndexError: " + str(e)
         res.success = False
         CognitiveExerciseHelperFunctions.traceError(res.error, res.trace)
Exemplo n.º 5
0
 def chooserFunction(self, req):
     try:
         res = testSelectorSrvResponse()
         currentTimestamp = int(time.time())
         #Load parameters from yaml file
         difficultyModifier1to2, difficultyModifier2to3, historyBasedOnNumOfTestsAndNotTime, pastMonths, pastTests, lookBackTimeStamp = self.loadParamDifficultyModifiersAndHistorySettings(
         )
         #Get user ontology alias
         userOntologyAlias = CognitiveExerciseHelperFunctions.getUserOntologyAlias(
             req.username)
         #Get user language
         userLanguage = CognitiveExerciseHelperFunctions.getUserLanguage(
             req.username)
         res.language = userLanguage
         #Manual test selection
         if (not req.testDifficulty == "" or not req.testIndex == ""):
             self.selectTestManuallyByGivenParameters(
                 req.testType, req.testSubType, req.testIndex,
                 req.testDifficulty, userLanguage, res)
         else:
             #Get test types from ontology
             testTypesList = CognitiveExerciseHelperFunctions.getTestTypesFromOntology(
             )
             #Determine the test type of the to be selected test
             testType = self.determineTestType(req.testType,
                                               req.testSubType,
                                               testTypesList,
                                               userOntologyAlias, res.trace)
             #Get user performance records and determine difficulty of the to be selected test for given test type
             chosenDif, noUserPerformanceRecordsExist, userPerfOrganizedByTimestamp = self.getUserPerformanceRecordsAndDetermineTestDifficultyForTestType(
                 testType, userOntologyAlias, currentTimestamp,
                 lookBackTimeStamp, difficultyModifier1to2,
                 difficultyModifier2to3, historyBasedOnNumOfTestsAndNotTime,
                 pastTests, res.trace)
             #Get all tests of a give type from the ontology
             testsOfTypeOrdered = self.getCognitiveTestsAndFilterByParameters(
                 testType, req.testSubType, userLanguage, chosenDif,
                 res.trace)
             #Determine the least recently used (LRU) test and retrieve the .xml test file
             testName, testFilePath = self.getLRUtestOfTypeAndXmlPath(
                 testsOfTypeOrdered, noUserPerformanceRecordsExist,
                 userPerfOrganizedByTimestamp)
             #res.test=testName
             #Parse the .xml test file name and assign the data to the testSelectorSrvResponse response srv
             self.retrieveDataFromTestXml(testFilePath, userLanguage, res)
         res.success = True
     except IndexError, e:
         res.trace.append("IndexError: " + str(e))
         res.error = "IndexError: " + str(e)
         res.success = False
         CognitiveExerciseHelperFunctions.traceError(res.error, res.trace)
Exemplo n.º 6
0
 def selectTestManuallyByGivenParameters(self,testType,testSubtype,testIndex,testDifficulty,userLanguage, res):
   if(not testType=="" and not testDifficulty=="" and not testIndex=="" and not testSubtype==""):
     testIndex=str(int(testIndex)-1)
     tests=CognitiveExerciseHelperFunctions.getCognitiveTestsOfType(testType,userLanguage) 
     tests=CognitiveExerciseHelperFunctions.filterTestsbyDifficultyAndSubtype(tests,testDifficulty,testSubtype)
     filepath=""
     for k, v in tests.items():
       if(testIndex==(v[0][3])):
         filepath=(v[0][0])      
     if(filepath==""):
       error="No such test exists, or not available in user's language"
       raise AppError(error,error) 
     self.retrieveDataFromTestXml(filepath,userLanguage,res)  
   else:
     error="Error, manual test detection detected as testIndex or testDifficulty was defined. One or more of testType, testSubtype, testIndex, testDifficulty were not defined, cannot proceed"
     raise AppError(error,error) 
Exemplo n.º 7
0
 def determineTestTypeIfNotProvided(self,testTypesList,userOntologyAlias,trace):
   serv_topic = rospy.get_param('rapp_knowrob_wrapper_user_performance_cognitve_tests')  
   trace.append("no test type provided, will use least recently used")
   noRecordsList=[]
   d1=OrderedDict()
   for s in testTypesList:
     userPerformanceReq=userPerformanceCognitveTestsSrvRequest()
     userPerformanceReq.test_type=s
     userPerformanceReq.ontology_alias=userOntologyAlias
     knowrob_service = rospy.ServiceProxy(serv_topic, userPerformanceCognitveTestsSrv)
     userPerformanceResponse = knowrob_service(userPerformanceReq)
     if(userPerformanceResponse.success!=True):
       noRecordsList.append(s)
     else:
       tmpUserPerfOrganizedByTimestamp=CognitiveExerciseHelperFunctions.organizeUserPerformanceByTimestamp(userPerformanceResponse)
       t1=tmpUserPerfOrganizedByTimestamp.items()[0][0]
       d1[t1]=[s]
   if(len(noRecordsList)>0):
     testType=random.choice(noRecordsList)
     trace.append("made random choice from the test types which were never used by the user, choice was: "+ testType)
   else:
     d1=OrderedDict(sorted(d1.items(), key=lambda t: t[0]))
     testType=d1.values()[0][0]
     trace.append("all test types had performance records.. least recently used one was :"+ testType)
   return testType 
Exemplo n.º 8
0
 def determineTestTypeIfNotProvided(self, testTypesList, userOntologyAlias,
                                    trace):
     serv_topic = rospy.get_param(
         'rapp_knowrob_wrapper_user_performance_cognitve_tests')
     trace.append("no test type provided, will use least recently used")
     noRecordsList = []
     d1 = OrderedDict()
     for s in testTypesList:
         userPerformanceReq = userPerformanceCognitveTestsSrvRequest()
         userPerformanceReq.test_type = s
         userPerformanceReq.ontology_alias = userOntologyAlias
         knowrob_service = rospy.ServiceProxy(
             serv_topic, userPerformanceCognitveTestsSrv)
         userPerformanceResponse = knowrob_service(userPerformanceReq)
         if (userPerformanceResponse.success != True):
             noRecordsList.append(s)
         else:
             tmpUserPerfOrganizedByTimestamp = CognitiveExerciseHelperFunctions.organizeUserPerformanceByTimestamp(
                 userPerformanceResponse)
             t1 = tmpUserPerfOrganizedByTimestamp.items()[0][0]
             d1[t1] = [s]
     if (len(noRecordsList) > 0):
         testType = random.choice(noRecordsList)
         trace.append(
             "made random choice from the test types which were never used by the user, choice was: "
             + testType)
     else:
         d1 = OrderedDict(sorted(d1.items(), key=lambda t: t[0]))
         testType = d1.values()[0][0]
         trace.append(
             "all test types had performance records.. least recently used one was :"
             + testType)
     return testType
 def calculateUserScoresForCategories(self, testTypesList,
                                      userOntologyAlias, upToTime):
     scoresPerCategory = []
     d1 = OrderedDict()
     for s in testTypesList:
         userPerformanceResponse = CognitiveExerciseHelperFunctions.getUserPerformanceRecordsForTestType(
             s, userOntologyAlias)
         if (userPerformanceResponse.success != True):
             scoresPerCategory.append(0)
         else:
             scoreOfCategory = 0
             scoreOfCategoryDivideBy = 0
             for i in range(len(userPerformanceResponse.tests)):
                 if (int(userPerformanceResponse.timestamps[i]) < upToTime):
                     scoreOfCategory = scoreOfCategory + (
                         int(userPerformanceResponse.scores[i]) *
                         int(userPerformanceResponse.difficulty[i]))
                     scoreOfCategoryDivideBy = scoreOfCategoryDivideBy + int(
                         userPerformanceResponse.difficulty[i])
             #scoresPerCategory.append(long(scoreOfCategory/len(userPerformanceResponse.tests)))
             if (scoreOfCategoryDivideBy == 0):
                 scoresPerCategory.append(0)
             else:
                 scoresPerCategory.append(
                     float(scoreOfCategory / scoreOfCategoryDivideBy))
     return scoresPerCategory
Exemplo n.º 10
0
 def getCognitiveTestsAndFilterByParameters(self, testType, testSubType,
                                            userLanguage, chosenDif, trace):
     cognitiveTestsOfTypeResponse = CognitiveExerciseHelperFunctions.getCognitiveTestsOfType(
         testType, userLanguage)
     testsOfTypeOrdered = self.filterTestsbyDifficultyAndSubtype(
         cognitiveTestsOfTypeResponse, chosenDif, testSubType, trace)
     return testsOfTypeOrdered
 def returnUserHistory(self,req):
   try:
     res = userScoreHistoryForAllCategoriesSrvResponse() 
     #Validate the provided time range     
     fromTime,toTime=self.validateTimeRange(req.fromTime,req.toTime)     
     #Get user ontology alias   
     userOntologyAlias=CognitiveExerciseHelperFunctions.getUserOntologyAlias(req.username)    
     #Get test types from ontology     
     validtestTypesList=CognitiveExerciseHelperFunctions.getTestTypesFromOntology()    
     #Construct the test type list for returning their score history 
     testTypesList=CognitiveExerciseHelperFunctions.determineTestTypeListForReturningScoresOrHistory(req.testType,validtestTypesList)      
     res.testCategories=testTypesList      
     #Retrieve the test history for each test category
     self.assignTestHistoryForTestCategoriesToSrv(testTypesList,userOntologyAlias,fromTime,toTime,res)  
     res.success=True
   except ValueError:
     res.trace.append("ValueError: " +str(e))
     res.error="ValueError: "+str(e)
     res.success=False
     CognitiveExerciseHelperFunctions.traceError(res.error,res.trace)
   except IndexError, e:
     res.trace.append("IndexError: " +str(e))
     res.error="IndexError: "+str(e)
     res.success=False
     CognitiveExerciseHelperFunctions.traceError(res.error,res.trace)
Exemplo n.º 12
0
 def returnUserHistory(self, req):
     try:
         res = userScoreHistoryForAllCategoriesSrvResponse()
         #Validate the provided time range
         fromTime, toTime = self.validateTimeRange(req.fromTime, req.toTime)
         #Get user ontology alias
         userOntologyAlias = CognitiveExerciseHelperFunctions.getUserOntologyAlias(
             req.username)
         #Get test types from ontology
         validtestTypesList = CognitiveExerciseHelperFunctions.getTestTypesFromOntology(
         )
         #Construct the test type list for returning their score history
         testTypesList = CognitiveExerciseHelperFunctions.determineTestTypeListForReturningScoresOrHistory(
             req.testType, validtestTypesList)
         res.testCategories = testTypesList
         #Retrieve the test history for each test category
         self.assignTestHistoryForTestCategoriesToSrv(
             testTypesList, userOntologyAlias, fromTime, toTime, res)
         res.success = True
     except ValueError:
         res.trace.append("ValueError: " + str(e))
         res.error = "ValueError: " + str(e)
         res.success = False
         CognitiveExerciseHelperFunctions.traceError(res.error, res.trace)
     except IndexError, e:
         res.trace.append("IndexError: " + str(e))
         res.error = "IndexError: " + str(e)
         res.success = False
         CognitiveExerciseHelperFunctions.traceError(res.error, res.trace)
 def returnUserScores(self, req):
     try:
         res = userScoresForAllCategoriesSrvResponse()
         #Get user ontology alias
         userOntologyAlias = CognitiveExerciseHelperFunctions.getUserOntologyAlias(
             req.username)
         #Get test types from ontology
         validtestTypesList = CognitiveExerciseHelperFunctions.getTestTypesFromOntology(
         )
         #Construct the test type list for returning their score history
         testTypesList = CognitiveExerciseHelperFunctions.determineTestTypeListForReturningScoresOrHistory(
             req.testType, validtestTypesList)
         res.testCategories = testTypesList
         #Calculate scores for test categories
         res.testScores = self.calculateUserScoresForCategories(
             testTypesList, userOntologyAlias, req.upToTime)
         res.success = True
     except ValueError:
         res.trace.append("ValueError: " + str(e))
         res.error = "ValueError: " + str(e)
         res.success = False
         CognitiveExerciseHelperFunctions.traceError(res.error, res.trace)
     except IndexError, e:
         res.trace.append("IndexError: " + str(e))
         res.error = "IndexError: " + str(e)
         res.success = False
         CognitiveExerciseHelperFunctions.traceError(res.error, res.trace)
Exemplo n.º 14
0
class ReturnTests:

    ## @brief The callback function of the return tests of type cognitive exercise service
    # @param req [rapp_platform_ros_communications::returnTestsOfTypeSubtypeDifficultySrvRequest::Request&] The ROS service request
    # @param res [rapp_platform_ros_communications::returnTestsOfTypeSubtypeDifficultySrvResponse::Response&] The ROS service response
    # @exception Exception IndexError
    # @exception Exception AIOError
    # @exception Exception KeyError
    # @exception Exception AppError
    def returnTestsFunction(self, req):
        try:
            res = returnTestsOfTypeSubtypeDifficultySrvResponse()
            if (req.testType == ""):
                error = "Error, empty testType field"
                raise AppError(error, error)
            supportedLanguages = CognitiveExerciseHelperFunctions.getTestLanguagesFromOntology(
            )
            keepEntries = dict()
            testCount = 0
            for currentLanguage in supportedLanguages:
                cognitiveTestsOfTypeResponse = CognitiveExerciseHelperFunctions.getCognitiveTestsOfType(
                    req.testType, currentLanguage)
                tests = CognitiveExerciseHelperFunctions.filterTestsbyDifficultyAndSubtype(
                    cognitiveTestsOfTypeResponse, req.difficulty,
                    req.testSubType)
                if (req.language == "" or currentLanguage == req.language):
                    for k, v in tests.items():
                        if (not k in keepEntries):
                            currentCognitiveTest = CognitiveExercisesMsg()
                            currentCognitiveTest.testName = k.split('#')[1]
                            currentCognitiveTest.testType = req.testType
                            currentCognitiveTest.testSubType = (
                                v[0][2]).split('#')[1]
                            currentCognitiveTest.testSubType = (
                                v[0][2]).split('#')[1]
                            currentCognitiveTest.difficulty = (v[0][1])
                            currentCognitiveTest.test_id = (v[0][3])
                            currentCognitiveTest.languages.append(
                                currentLanguage)
                            res.cognitiveExercises.append(currentCognitiveTest)
                            keepEntries[k] = testCount
                            testCount = testCount + 1
                        else:
                            res.cognitiveExercises[keepEntries[
                                k]].languages.append(currentLanguage)
            res.totalNumberOfTestsReturned = testCount
            res.success = True
        except IndexError, e:
            res.trace.append("IndexError: " + str(e))
            res.error = "IndexError: " + str(e)
            res.success = False
            CognitiveExerciseHelperFunctions.traceError(res.error, res.trace)
        except IOError, e:
            res.success = False
            res.trace.append("IOError: " + str(e))
            res.error = "IOError: " + str(e)
            CognitiveExerciseHelperFunctions.traceError(res.error, res.trace)
Exemplo n.º 15
0
 def returnTestsFunction(self, req):
     try:
         res = returnTestsOfTypeSubtypeDifficultySrvResponse()
         if (req.testType == ""):
             error = "Error, empty testType field"
             raise AppError(error, error)
         supportedLanguages = CognitiveExerciseHelperFunctions.getTestLanguagesFromOntology(
         )
         keepEntries = dict()
         testCount = 0
         for currentLanguage in supportedLanguages:
             cognitiveTestsOfTypeResponse = CognitiveExerciseHelperFunctions.getCognitiveTestsOfType(
                 req.testType, currentLanguage)
             tests = CognitiveExerciseHelperFunctions.filterTestsbyDifficultyAndSubtype(
                 cognitiveTestsOfTypeResponse, req.difficulty,
                 req.testSubType)
             if (req.language == "" or currentLanguage == req.language):
                 for k, v in tests.items():
                     if (not k in keepEntries):
                         currentCognitiveTest = CognitiveExercisesMsg()
                         currentCognitiveTest.testName = k.split('#')[1]
                         currentCognitiveTest.testType = req.testType
                         currentCognitiveTest.testSubType = (
                             v[0][2]).split('#')[1]
                         currentCognitiveTest.testSubType = (
                             v[0][2]).split('#')[1]
                         currentCognitiveTest.difficulty = (v[0][1])
                         currentCognitiveTest.test_id = (v[0][3])
                         currentCognitiveTest.languages.append(
                             currentLanguage)
                         res.cognitiveExercises.append(currentCognitiveTest)
                         keepEntries[k] = testCount
                         testCount = testCount + 1
                     else:
                         res.cognitiveExercises[keepEntries[
                             k]].languages.append(currentLanguage)
         res.totalNumberOfTestsReturned = testCount
         res.success = True
     except IndexError, e:
         res.trace.append("IndexError: " + str(e))
         res.error = "IndexError: " + str(e)
         res.success = False
         CognitiveExerciseHelperFunctions.traceError(res.error, res.trace)
Exemplo n.º 16
0
 def getUserPerformanceRecordsAndDetermineTestDifficultyForTestType(
         self, testType, userOntologyAlias, currentTimestamp,
         lookBackTimeStamp, difficultyModifier1to2, difficultyModifier2to3,
         historyBasedOnNumOfTestsAndNotTime, pastTests, trace):
     noUserPerformanceRecordsExist = False
     userPerformanceResponse = CognitiveExerciseHelperFunctions.getUserPerformanceRecordsForTestType(
         testType, userOntologyAlias)
     userPerfOrganizedByTimestamp = []
     if (userPerformanceResponse.success != True):
         trace.extend(userPerformanceResponse.trace)
         trace.append(
             "KnowRob wrapper returned no performance records for this user.. will start with a difficulty setting of 1"
         )
         noUserPerformanceRecordsExist = True
         chosenDif = "1"
     else:
         userPerfOrganizedByTimestamp = CognitiveExerciseHelperFunctions.organizeUserPerformanceByTimestamp(
             userPerformanceResponse)
         if (historyBasedOnNumOfTestsAndNotTime):
             if (len(userPerfOrganizedByTimestamp) > pastTests):
                 counter = 0
                 for k, v in userPerfOrganizedByTimestamp.items():
                     counter = counter + 1
                     if (counter > pastTests):
                         del userPerfOrganizedByTimestamp[k]
         else:
             for k, v in userPerfOrganizedByTimestamp.items():
                 if (currentTimestamp - k > lookBackTimeStamp):
                     del userPerfOrganizedByTimestamp[k]
                 else:
                     break
         userScore = self.calculateUserScore(userPerfOrganizedByTimestamp)
         trace.append("user score :" + str(userScore))
         if (userScore == 0):
             chosenDif = "1"
         elif (userScore < difficultyModifier1to2):
             chosenDif = "1"
         elif (userScore < difficultyModifier2to3):
             chosenDif = "2"
         else:
             chosenDif = "3"
     trace.append("Chosen Diff :" + chosenDif)
     return chosenDif, noUserPerformanceRecordsExist, userPerfOrganizedByTimestamp
Exemplo n.º 17
0
 def assignTestHistoryForTestCategoriesToSrv(self, testTypesList,
                                             userOntologyAlias, fromTime,
                                             toTime, res):
     for s in testTypesList:
         userPerformanceResponse = CognitiveExerciseHelperFunctions.getUserPerformanceRecordsForTestType(
             s, userOntologyAlias)
         if (userPerformanceResponse.success == True):
             userPerfOrganizedByTimestamp = CognitiveExerciseHelperFunctions.organizeUserPerformanceByTimestamp(
                 userPerformanceResponse)
             sumCategoryScore = 0
             sumCategoryScoreDivideBy = 0
             countValidTests = 0
             arrayCognitiveExercisePerformanceRecords = ArrayCognitiveExercisePerformanceRecordsMsg(
             )
             for k, v in userPerfOrganizedByTimestamp.items():
                 if (k < fromTime or k > toTime):
                     del userPerfOrganizedByTimestamp[k]
                 else:
                     tmpRecord = CognitiveExercisePerformanceRecordsMsg()
                     tmpRecord.timestamp = k
                     tmpList = v[0][0].split('#')
                     if (tmpList[1] is not None):
                         tmpRecord.test = tmpList[1]
                     tmpRecord.score = long(v[0][1])
                     tmpRecord.difficulty = v[0][2]
                     tmpList = v[0][3].split('#')
                     if (tmpList[1] is not None):
                         tmpRecord.subtype = tmpList[1]
                     tmpRecord.type = s
                     countValidTests = countValidTests + 1
                     sumCategoryScore = sumCategoryScore + long(
                         v[0][2]) * long(v[0][
                             1])  #[0][2] is difficulty, [0][1] is score
                     sumCategoryScoreDivideBy = sumCategoryScoreDivideBy + long(
                         v[0][2])
                     tmpAverageCategoryScore = float(
                         sumCategoryScore / sumCategoryScoreDivideBy)
                     tmpRecord.meanScoreForTypeUpToNow = tmpAverageCategoryScore
                     arrayCognitiveExercisePerformanceRecords.records.append(
                         tmpRecord)
             res.recordsPerTestType.append(
                 arrayCognitiveExercisePerformanceRecords)
Exemplo n.º 18
0
 def selectTestManuallyByGivenParameters(self, testType, testSubtype,
                                         testIndex, testDifficulty,
                                         userLanguage, res):
     if (not testType == "" and not testDifficulty == ""
             and not testIndex == "" and not testSubtype == ""):
         testIndex = str(int(testIndex) - 1)
         tests = CognitiveExerciseHelperFunctions.getCognitiveTestsOfType(
             testType, userLanguage)
         tests = CognitiveExerciseHelperFunctions.filterTestsbyDifficultyAndSubtype(
             tests, testDifficulty, testSubtype)
         filepath = ""
         for k, v in tests.items():
             if (testIndex == (v[0][3])):
                 filepath = (v[0][0])
         if (filepath == ""):
             error = "No such test exists, or not available in user's language"
             raise AppError(error, error)
         self.retrieveDataFromTestXml(filepath, userLanguage, res)
     else:
         error = "Error, manual test detection detected as testIndex or testDifficulty was defined. One or more of testType, testSubtype, testIndex, testDifficulty were not defined, cannot proceed"
         raise AppError(error, error)
 def recordPerformance(self,req):
   try:
     res = recordUserCognitiveTestPerformanceSrvResponse()
     userOntologyAlias=CognitiveExerciseHelperFunctions.getUserOntologyAlias(req.username)      
     serv_topic = rospy.get_param('rapp_knowrob_wrapper_record_user_cognitive_tests_performance')
     knowrob_service = rospy.ServiceProxy(serv_topic, recordUserPerformanceCognitiveTestsSrv)
     userPerformanceEntry = recordUserPerformanceCognitiveTestsSrvRequest()
     userPerformanceEntry.test=req.test    
     userPerformanceEntry.patient_ontology_alias=userOntologyAlias
     userPerformanceEntry.timestamp=int(time.time())
     userPerformanceEntry.score=req.score
     userPerformanceEntryResponse = knowrob_service(userPerformanceEntry)      
     if(userPerformanceEntryResponse.success!=True):
       error=userPerformanceEntryResponse.error+"Submitting query to ontology failed, either test or user ontology alias do not exist or test not of the given type"        
       raise AppError(error,error)
     else:
       res.success=True
       res.userCognitiveTestPerformanceEntry=userPerformanceEntryResponse.cognitive_test_performance_entry
   except IndexError, e:
     res.trace.append("IndexError: " +str(e))
     res.error="IndexError: "+str(e)
     res.success=False
     CognitiveExerciseHelperFunctions.traceError(res.error,res.trace)
Exemplo n.º 20
0
 def getUserPerformanceRecordsAndDetermineTestDifficultyForTestType(self,testType,userOntologyAlias,currentTimestamp,lookBackTimeStamp,difficultyModifier1to2,difficultyModifier2to3,historyBasedOnNumOfTestsAndNotTime,pastTests,trace):
   noUserPerformanceRecordsExist=False;  
   userPerformanceResponse=CognitiveExerciseHelperFunctions.getUserPerformanceRecordsForTestType(testType,userOntologyAlias)     
   userPerfOrganizedByTimestamp=[]
   if(userPerformanceResponse.success!=True):
     trace.extend(userPerformanceResponse.trace)
     trace.append("KnowRob wrapper returned no performance records for this user.. will start with a difficulty setting of 1")
     noUserPerformanceRecordsExist=True
     chosenDif="1"
   else:
     userPerfOrganizedByTimestamp=CognitiveExerciseHelperFunctions.organizeUserPerformanceByTimestamp(userPerformanceResponse)
     if(historyBasedOnNumOfTestsAndNotTime):
       if(len(userPerfOrganizedByTimestamp)>pastTests):          
         counter=0;
         for k, v in userPerfOrganizedByTimestamp.items():
           counter=counter+1
           if(counter>pastTests):
             del userPerfOrganizedByTimestamp[k]       
     else:
       for k, v in userPerfOrganizedByTimestamp.items():
         if(currentTimestamp-k>lookBackTimeStamp):
           del userPerfOrganizedByTimestamp[k]
         else:
           break
     userScore=self.calculateUserScore(userPerfOrganizedByTimestamp)
     trace.append("user score :"+str(userScore))    
     if(userScore==0):
       chosenDif="1"
     elif(userScore<difficultyModifier1to2):
       chosenDif="1"
     elif(userScore<difficultyModifier2to3):
       chosenDif="2"
     else:
       chosenDif="3"
   trace.append("Chosen Diff :"+chosenDif)
   return chosenDif,noUserPerformanceRecordsExist,userPerfOrganizedByTimestamp
class RecordUserCognitiveTestPerformance:

    ## @brief The callback function of the cognitive exercise record user cognitive test performance service
    # @param req [rapp_platform_ros_communications::recordUserCognitiveTestPerformanceSrvRequest::Request&] The ROS service request
    # @param res [rapp_platform_ros_communications::recordUserCognitiveTestPerformanceSrvResponse::Response&] The ROS service response
    # @exception Exception IndexError
    # @exception Exception IOError
    # @exception Exception KeyError
    # @exception Exception AppError
    def recordPerformance(self, req):
        try:
            res = recordUserCognitiveTestPerformanceSrvResponse()
            userOntologyAlias = CognitiveExerciseHelperFunctions.getUserOntologyAlias(
                req.username)
            serv_topic = rospy.get_param(
                'rapp_knowrob_wrapper_record_user_cognitive_tests_performance')
            knowrob_service = rospy.ServiceProxy(
                serv_topic, recordUserPerformanceCognitiveTestsSrv)
            userPerformanceEntry = recordUserPerformanceCognitiveTestsSrvRequest(
            )
            userPerformanceEntry.test = req.test
            userPerformanceEntry.patient_ontology_alias = userOntologyAlias
            userPerformanceEntry.timestamp = int(time.time())
            userPerformanceEntry.score = req.score
            userPerformanceEntryResponse = knowrob_service(
                userPerformanceEntry)
            if (userPerformanceEntryResponse.success != True):
                error = userPerformanceEntryResponse.error + "Submitting query to ontology failed, either test or user ontology alias do not exist or test not of the given type"
                raise AppError(error, error)
            else:
                res.success = True
                res.userCognitiveTestPerformanceEntry = userPerformanceEntryResponse.cognitive_test_performance_entry
        except IndexError, e:
            res.trace.append("IndexError: " + str(e))
            res.error = "IndexError: " + str(e)
            res.success = False
            CognitiveExerciseHelperFunctions.traceError(res.error, res.trace)
        except IOError, e:
            res.success = False
            res.trace.append("IOError: " + str(e))
            res.error = "IOError: " + str(e)
            CognitiveExerciseHelperFunctions.traceError(res.error, res.trace)
 def calculateUserScoresForCategories(self,testTypesList,userOntologyAlias,upToTime):    
   scoresPerCategory=[]
   d1=OrderedDict()
   for s in testTypesList:
     userPerformanceResponse=CognitiveExerciseHelperFunctions.getUserPerformanceRecordsForTestType(s,userOntologyAlias)      
     if(userPerformanceResponse.success!=True):
       scoresPerCategory.append(0)
     else:
       scoreOfCategory=0
       scoreOfCategoryDivideBy=0
       for i in range(len(userPerformanceResponse.tests)):
         if(int(userPerformanceResponse.timestamps[i])<upToTime):
           scoreOfCategory=scoreOfCategory+(int(userPerformanceResponse.scores[i])*int(userPerformanceResponse.difficulty[i]))            
           scoreOfCategoryDivideBy=scoreOfCategoryDivideBy+int(userPerformanceResponse.difficulty[i])
       #scoresPerCategory.append(long(scoreOfCategory/len(userPerformanceResponse.tests)))
       if(scoreOfCategoryDivideBy==0):
         scoresPerCategory.append(0)
       else:
         scoresPerCategory.append(float(scoreOfCategory/scoreOfCategoryDivideBy))
   return scoresPerCategory    
 def returnUserScores(self,req):
   try:
     res = userScoresForAllCategoriesSrvResponse()      
     #Get user ontology alias
     userOntologyAlias=CognitiveExerciseHelperFunctions.getUserOntologyAlias(req.username)
     #Get test types from ontology       
     validtestTypesList=CognitiveExerciseHelperFunctions.getTestTypesFromOntology()
     #Construct the test type list for returning their score history    
     testTypesList=CognitiveExerciseHelperFunctions.determineTestTypeListForReturningScoresOrHistory(req.testType,validtestTypesList)  
     res.testCategories=testTypesList
     #Calculate scores for test categories
     res.testScores=self.calculateUserScoresForCategories(testTypesList,userOntologyAlias,req.upToTime)   
     res.success=True
   except ValueError:
     res.trace.append("ValueError: " +str(e))
     res.error="ValueError: "+str(e)
     res.success=False
     CognitiveExerciseHelperFunctions.traceError(res.error,res.trace)
   except IndexError, e:
     res.trace.append("IndexError: " +str(e))
     res.error="IndexError: "+str(e)
     res.success=False
     CognitiveExerciseHelperFunctions.traceError(res.error,res.trace)
Exemplo n.º 24
0
  def testCreator(self,req):
    res=cognitiveTestCreatorSrvResponse()
    fname=req.inputFile
    d=dict()
    questions=dict()
    answers=dict()
    correctAnswers=dict()
    listQuestions=[]
    listAnswers=[]
    listCorrectAnswers=[]
    supportedLanguages=[]
    flag=False
    questionsStart=False
    count=0    
    
    try:
      with open(fname) as f:
        content = f.readlines()
      for s in content:
        if (":" in s):
          s=s.strip()
          tmp=s.split(":")
          if(tmp[0] == "Difficulty" or tmp[0]=="variationID"):
            if (not self.is_int(tmp[1])):
              res.trace.append("error, difficulty or variation ID is not an integer")
              flag=False
          if(tmp[0] == "language"):
            if(not len(questions)==len(answers)==len(correctAnswers)):
              flag=False
              res.trace.append("error, test is broken, questions-answers-correctAnswers not equal in size")
              break
            supportedLanguages.append(tmp[1])
            listQuestions.append(questions.copy())
            questions.clear()
            listAnswers.append(answers.copy())
            answers.clear()
            listCorrectAnswers.append(correctAnswers.copy())
            correctAnswers.clear()
            questionsStart=True
            flag=True
            count=0
          elif(questionsStart):
            if(tmp[0] == "question"):
              count=count+1;
              tmp[0]=tmp[0]+str(count)
              #print tmp[1]
              questions[tmp[0]]=tmp[1]
            elif(tmp[0]=="answers"):
              tmp[0]=tmp[0]+str(count)
              answers[tmp[0]]=tmp[1]
            elif(tmp[0]=="correctAnswer"):
              tmp[0]=tmp[0]+str(count)
              if(tmp[1] not in answers["answers"+str(count)]):
                flag=False
                res.trace.append("Correct Answer not in answers in Question "+str(count) +" in test "+fname )
                break
              correctAnswers[tmp[0]]=tmp[1]
            else:
              flag=False
              res.trace.append("field other than questions,answers,correctAnswer found")
              break
          else:
            d[tmp[0]]=[tmp[1]]

      if(not len(questions)==len(answers)==len(correctAnswers)):
        flag=False
        res.trace.append("error, test is broken, questions-answers-correctAnswers not equal in size")
      else:
        listQuestions.append(questions.copy())
        questions.clear()
        listAnswers.append(answers.copy())
        answers.clear()
        listCorrectAnswers.append(correctAnswers.copy())
        correctAnswers.clear()
      xmlFileName=""
      if(flag):
        #xmlFileName=d["testType"][0]+"_"+d["testSubType"][0]+"_"+"diff"+d["difficulty"][0]
        root = ET.Element("cognitiveTest")
        ET.SubElement(root, "testType").text = d["testType"][0] 
        ET.SubElement(root, "testSubType").text = d["testSubType"][0]
        Languages=ET.SubElement(root,"Languages")
        
        for l in range(1,len(listQuestions)):
          questions=listQuestions[l] 
          answers=listAnswers[l]    
          correctAnswers=listCorrectAnswers[l] 
          currentLanguage=ET.SubElement(Languages, supportedLanguages[l-1])
          for i in range(1,count+1):
            nm="Q"+str(i)
            Q=ET.SubElement(currentLanguage, "Question", name=nm)
            nm="question"+str(i)
            ET.SubElement(Q, "body").text = questions[nm].decode('UTF-8')
            nm="answers"+str(i)
            answs=answers[nm].split(",")
            for j in answs:
              A=ET.SubElement(Q, "answer")
              ET.SubElement(A, "body").text = j.decode('UTF-8')
            nm="correctAnswer"+str(i)
            corrAnswer=correctAnswers[nm]
            ET.SubElement(Q, "correctAnswer").text = corrAnswer.decode('UTF-8')

        tree = ET.ElementTree(root)
        rospack = rospkg.RosPack()

        localPackagePath=rospack.get_path('rapp_cognitive_exercise')
        test_id=self.determineCognitiveTestId(d["testType"][0], d["testSubType"][0], d["difficulty"][0])
        xmlFileName=d["testType"][0]+"_"+d["testSubType"][0]+"_"+"diff"+d["difficulty"][0]+"_id_"+str(test_id)
        inNodeName="/cognitiveTests/"+xmlFileName+".xml"
        localPackagePath=localPackagePath+inNodeName
        tree.write(localPackagePath,encoding="UTF-8",xml_declaration=True)

        serv_topic = rospy.get_param('rapp_knowrob_wrapper_create_cognitve_tests')          
        createTestReq=createCognitiveExerciseTestSrvRequest()
        createTestReq.test_type=d["testType"][0]
        createTestReq.test_difficulty=int(d["difficulty"][0])
        createTestReq.test_subtype=d["testSubType"][0]
        createTestReq.test_path=inNodeName
        createTestReq.supported_languages=supportedLanguages        
        createTestReq.test_id=supportedLanguages=test_id
        
        knowrob_service = rospy.ServiceProxy(serv_topic, createCognitiveExerciseTestSrv)
        createCognitiveTestResponse = knowrob_service(createTestReq)
        if(createCognitiveTestResponse.success!=True):
          res.trace.extend(createCognitiveTestResponse.trace)
          res.error=createCognitiveTestResponse.error
          res.success=False
          os.remove(localPackagePath)
          return res
          
        ontologyName=createCognitiveTestResponse.test_name
        tmp=ontologyName.split("#")
        ontologyName=tmp[1]

        tree = ET.parse(localPackagePath)
        root = tree.getroot()
        ET.SubElement(root, "name").text = ontologyName
        self.indent(root)
        os.remove(localPackagePath)
        tree.write(localPackagePath,encoding="UTF-8",xml_declaration=True)
        res.success=True
        
      else:
        res.error="test "+fname +" is broken"
        res.success=False

    except IndexError:
      #print "test "+fname +" is broken"
      res.error="IndexError.. test "+fname +" is broken"
      CognitiveExerciseHelperFunctions.traceError(res.error,res.trace)
      res.success=False
    except IOError:
      #print "IO Error, cannot open test file or write xml file"
      res.error="IO Error, cannot open test file or write xml file"
      CognitiveExerciseHelperFunctions.traceError(res.error,res.trace)
      res.success=False
    except AppError as e:
      AppError.passErrorToRosSrv(e,res) 
    return res
Exemplo n.º 25
0
            res.error = "IndexError: " + str(e)
            res.success = False
            CognitiveExerciseHelperFunctions.traceError(res.error, res.trace)
        except IOError, e:
            res.success = False
            res.trace.append("IOError: " + str(e))
            res.error = "IOError: " + str(e)
            CognitiveExerciseHelperFunctions.traceError(res.error, res.trace)
        except KeyError, e:
            res.success = False
            res.trace.append(
                '"KeyError (probably invalid cfg/.yaml parameter) "%s"' %
                str(e))
            res.error = '"KeyError (probably invalid cfg/.yaml parameter) "%s"' % str(
                e)
            CognitiveExerciseHelperFunctions.traceError(res.error, res.trace)
        except AppError as e:
            AppError.passErrorToRosSrv(e, res)
        return res

    ## @brief Selects a cognitive test manually by the given parameters
    # @param testType [string] The test type (category)
    # @param testSubtype [string] The test subtype
    # @param testIndex [int] The id (index) of the test
    # @param testDifficulty [string] The difficulty of the test (1,2 or 3)
    # @param userLanguage [string] The user's language
    # @param res [rapp_platform_ros_communications::testSelectorSrvResponse::Response&] The ROS service response
    #
    # @return res [rapp_platform_ros_communications::testSelectorSrvResponse::Response&] The ROS service response
    # @exception Exception AppError
    def selectTestManuallyByGivenParameters(self, testType, testSubtype,
Exemplo n.º 26
0
 def getCognitiveTestsAndFilterByParameters(self,testType,testSubType,userLanguage,chosenDif,trace):
   cognitiveTestsOfTypeResponse=CognitiveExerciseHelperFunctions.getCognitiveTestsOfType(testType,userLanguage)
   testsOfTypeOrdered=self.filterTestsbyDifficultyAndSubtype(cognitiveTestsOfTypeResponse,chosenDif,testSubType,trace)    
   return testsOfTypeOrdered
Exemplo n.º 27
0
      res.success=True
    except IndexError, e:
      res.trace.append("IndexError: " +str(e))
      res.error="IndexError: "+str(e)
      res.success=False
      CognitiveExerciseHelperFunctions.traceError(res.error,res.trace)
    except IOError, e:
      res.success=False
      res.trace.append("IOError: "+str(e))
      res.error="IOError: "+str(e)
      CognitiveExerciseHelperFunctions.traceError(res.error,res.trace)
    except KeyError, e:
      res.success=False
      res.trace.append('"KeyError (probably invalid cfg/.yaml parameter) "%s"' % str(e))
      res.error='"KeyError (probably invalid cfg/.yaml parameter) "%s"' % str(e)
      CognitiveExerciseHelperFunctions.traceError(res.error,res.trace)
    except AppError as e:
      AppError.passErrorToRosSrv(e,res) 
    return res

  ## @brief Selects a cognitive test manually by the given parameters
  # @param testType [string] The test type (category)
  # @param testSubtype [string] The test subtype
  # @param testIndex [int] The id (index) of the test
  # @param testDifficulty [string] The difficulty of the test (1,2 or 3)
  # @param userLanguage [string] The user's language
  # @param res [rapp_platform_ros_communications::testSelectorSrvResponse::Response&] The ROS service response 
  #
  # @return res [rapp_platform_ros_communications::testSelectorSrvResponse::Response&] The ROS service response 
  # @exception Exception AppError
  def selectTestManuallyByGivenParameters(self,testType,testSubtype,testIndex,testDifficulty,userLanguage, res):