예제 #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)
예제 #2
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)
예제 #3
0
 def chooserDataHandler(self,req):
   res = testSelectorSrvResponse()
   it = TestSelector()
   res=it.chooserFunction(req)
   return res
예제 #4
0
  def chooserFunction(self,req):

    try:
      res = testSelectorSrvResponse()
      currentTimestamp = int(time.time())       
 
      returnWithError,modifier1,modifier2=self.loadParamDifficultyModifiers(res)
      if(returnWithError):
        return res
        
      returnWithError,userOntologyAlias=self.getUserOntologyAlias(req.username,res)
      if(returnWithError):
        return res

      returnWithError,userLanguage=self.getUserLanguage(req.username,res)
      if(returnWithError):
        return res

      returnWithError,testTypesList=self.getTestTypesFromOntology(res)
      if(returnWithError):
        return res
        
      if(req.testType==""):
        testType=self.determineTestTypeIfNotProvided(res,testTypesList,userOntologyAlias)
      else:
        if (req.testType not in testTypesList):
          res.trace.append("testType provided does not exist")
          res.error="testType provided does not exist"
          res.success=False
          return res
        else:
          testType=req.testType
      
      chosenDif,noUserPerformanceRecordsExist,userPerfOrganizedByTimestamp=self.organizeUserPerformanceByTimestampAndDetermineTestDifficulty(testType,userOntologyAlias,currentTimestamp,self.lookBackTimeStamp,res,modifier1,modifier2)
            
      returnWithError,testsOfTypeOrdered=self.getCognitiveTestsOfType(testType,userLanguage,chosenDif,res)      
      if(returnWithError):
        return res      

      finalTestFilePath,finalTestname=self.getLRUtestOfTypeAndXmlPath(testsOfTypeOrdered,noUserPerformanceRecordsExist,userPerfOrganizedByTimestamp)
      
      #Retrieve the name of the selected test
      tmpList=finalTestname.split('#')
      res.test=tmpList[1]

      #Parse the test xml file and retrieve the desired information
      rospack = rospkg.RosPack()
      localPackagePath=rospack.get_path('rapp_cognitive_exercise')
      finalTestFilePath=localPackagePath+finalTestFilePath
      res.trace.append(finalTestFilePath)
      self.retrieveDataFromTestXml(finalTestFilePath,res,userLanguage)
      res.language=userLanguage
      res.success=True

    except IndexError:
      res.trace.append("Null pointer exception.. some argument was empty")
      res.error="Null pointer exception.. some argument was empty"
      res.success=False
    except IOError:
      res.success=False
      res.trace.append("IO Error, cant open file or read data")
      res.error="IO Error, cant open file or read data"
    return res
예제 #5
0
    def chooserFunction(self, req):

        try:
            res = testSelectorSrvResponse()
            currentTimestamp = int(time.time())

            returnWithError, modifier1, modifier2 = self.loadParamDifficultyModifiers(
                res)
            if (returnWithError):
                return res

            returnWithError, userOntologyAlias = self.getUserOntologyAlias(
                req.username, res)
            if (returnWithError):
                return res

            returnWithError, userLanguage = self.getUserLanguage(
                req.username, res)
            if (returnWithError):
                return res

            returnWithError, testTypesList = self.getTestTypesFromOntology(res)
            if (returnWithError):
                return res

            if (req.testType == ""):
                testType = self.determineTestTypeIfNotProvided(
                    res, testTypesList, userOntologyAlias)
            else:
                if (req.testType not in testTypesList):
                    res.trace.append("testType provided does not exist")
                    res.error = "testType provided does not exist"
                    res.success = False
                    return res
                else:
                    testType = req.testType

            chosenDif, noUserPerformanceRecordsExist, userPerfOrganizedByTimestamp = self.organizeUserPerformanceByTimestampAndDetermineTestDifficulty(
                testType, userOntologyAlias, currentTimestamp,
                self.lookBackTimeStamp, res, modifier1, modifier2)

            returnWithError, testsOfTypeOrdered = self.getCognitiveTestsOfType(
                testType, userLanguage, chosenDif, res)
            if (returnWithError):
                return res

            finalTestFilePath, finalTestname = self.getLRUtestOfTypeAndXmlPath(
                testsOfTypeOrdered, noUserPerformanceRecordsExist,
                userPerfOrganizedByTimestamp)

            #Retrieve the name of the selected test
            tmpList = finalTestname.split('#')
            res.test = tmpList[1]

            #Parse the test xml file and retrieve the desired information
            rospack = rospkg.RosPack()
            localPackagePath = rospack.get_path('rapp_cognitive_exercise')
            finalTestFilePath = localPackagePath + finalTestFilePath
            res.trace.append(finalTestFilePath)
            self.retrieveDataFromTestXml(finalTestFilePath, res, userLanguage)
            res.language = userLanguage
            res.success = True

        except IndexError:
            res.trace.append(
                "Null pointer exception.. some argument was empty")
            res.error = "Null pointer exception.. some argument was empty"
            res.success = False
        except IOError:
            res.success = False
            res.trace.append("IO Error, cant open file or read data")
            res.error = "IO Error, cant open file or read data"
        return res
예제 #6
0
  def chooserFunction(self,req):
    currentTimestamp = int(time.time()) #15552000000 for last 3 months

    try:
      res = testSelectorSrvResponse()
      #obtain user's ontology alias. It will be created if it does not exist in case of invalid username it will be caught
      serv_topic = rospy.get_param('rapp_knowrob_wrapper_create_ontology_alias')
      if(not serv_topic):
        rospy.logerror("rapp_knowrob_wrapper_create_ontology_alias param not found")
        res.trace.append("rapp_knowrob_wrapper_create_ontology_alias param not found")
        res.error="rapp_knowrob_wrapper_create_ontology_alias param not found"
        res.success=False
        return res
      rospy.wait_for_service(serv_topic)
      knowrob_service = rospy.ServiceProxy(serv_topic, createOntologyAliasSrv)
      createOntologyAliasReq = createOntologyAliasSrvRequest()
      createOntologyAliasReq.username=req.username
      createOntologyAliasResponse = knowrob_service(createOntologyAliasReq)
      if(createOntologyAliasResponse.success!=True):
        res.trace.extend(createOntologyAliasResponse.trace)
        res.error=createOntologyAliasResponse.error
        res.success=False
        return res


      #get user language
      serv_topic = rospy.get_param('rapp_mysql_wrapper_user_fetch_data_topic')
      if(not serv_topic):
        rospy.logerror("rapp_mysql_wrapper_user_fetch_data_topic param not found")
        res.trace.append("rapp_mysql_wrapper_user_fetch_data_topic param not found")
        res.error="mysql_wrapper_rapp_read_data topic param not found"
        res.success=False
        return res
      rospy.wait_for_service(serv_topic)
      knowrob_service = rospy.ServiceProxy(serv_topic, fetchDataSrv)
      fetchDataSrvReq = fetchDataSrvRequest()
      fetchDataSrvReq.req_cols=["language"]
      fetchDataSrvReq.where_data=[StringArrayMsg(s=["username",req.username])]
      #print fetchDataSrvReq.where_data
      fetchDataSrvResponse = knowrob_service(fetchDataSrvReq)
      if(fetchDataSrvResponse.success.data!=True):
        #print fetchDataSrvResponse.res_data[0].s[0];
        res.trace.extend(fetchDataSrvResponse.trace)
        res.error=fetchDataSrvResponse.trace[0]
        res.success=False
        return res
      userLanguage=fetchDataSrvResponse.res_data[0].s[0];
      #print userLanguage
      #


      #Check if test type exists (if a test type is provided)
      serv_topic = rospy.get_param('rapp_knowrob_wrapper_subclasses_of_topic')
      if(not serv_topic):
        rospy.logerror("rapp_knowrob_wrapper_subclasses_of_topic topic param not found")
        res.trace.append("rapp_knowrob_wrapper_subclasses_of_topic topic param not found")
        res.error="rapp_knowrob_wrapper_subclasses_of_topic topic param not found"
        res.success=False
        return res
      rospy.wait_for_service(serv_topic)
      knowrob_service = rospy.ServiceProxy(serv_topic, ontologySubSuperClassesOfSrv)
      testTypesReq = ontologySubSuperClassesOfSrvRequest()
      testTypesReq.ontology_class="CognitiveTests"
      testTypesResponse = knowrob_service(testTypesReq)
      if(testTypesResponse.success!=True):
        res.trace.extend(testTypesResponse.trace)
        res.trace.append("cannot load test categories from ontology")
        res.error=testTypesResponse.error+"cannot load test categories from ontology"
        res.success=False
        return res
      testTypesList=[]
      for s in testTypesResponse.results:
        #res.trace.append(s)
        tmpList=s.split('#')
        testTypesList.append(tmpList[1])

      serv_topic = rospy.get_param('rapp_knowrob_wrapper_user_performance_cognitve_tests')
      if(not serv_topic):
        rospy.logerror("rapp_knowrob_wrapper_user_performance_cognitve_tests topic not foud")
        res.trace.append("mysql_wrapper_rapp_read_data topic param not found")
        res.error="mysql_wrapper_rapp_read_data topic param not found"
        res.success=False
        return res

      if(req.testType==""):
        res.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=createOntologyAliasResponse.ontology_alias
          knowrob_service = rospy.ServiceProxy(serv_topic, userPerformanceCognitveTestsSrv)
          userPerformanceResponse = knowrob_service(userPerformanceReq)
          if(userPerformanceResponse.success!=True):
            noRecordsList.append(s)
          else:
            tmpUserPerfOrganizedByTimestamp=self.organizeUserPerformance(userPerformanceResponse)
            t1=tmpUserPerfOrganizedByTimestamp.items()[0][0]
            d1[t1]=[s]

        if(len(noRecordsList)>0):
          req.testType=random.choice(noRecordsList)
          res.trace.append("made random choice from the test types which were never used by the user, choice was: "+ req.testType)
        else:
          d1=OrderedDict(sorted(d1.items(), key=lambda t: t[0]))
          req.testType=d1.values()[0][0]
          res.trace.append("all test types had performance records.. least recently used one was :"+ req.testType)
      else:
        if (req.testType not in testTypesList):
          res.trace.append("testType provided does not exist")
          res.error="testType provided does not exist"
          res.success=False
          return res

      # check if performance records exist for the selected test in order to determine the difficulty setting
      noUserPerformanceRecordsExist=False;
      chosenDif="1"
      userPerformanceReq=userPerformanceCognitveTestsSrvRequest()
      userPerformanceReq.test_type=req.testType
      userPerformanceReq.ontology_alias=createOntologyAliasResponse.ontology_alias
      knowrob_service = rospy.ServiceProxy(serv_topic, userPerformanceCognitveTestsSrv)
      userPerformanceResponse = knowrob_service(userPerformanceReq)
      if(userPerformanceResponse.success!=True):
        res.trace.extend(userPerformanceResponse.trace)
        res.trace.append("KnowRob wrapper returned no performance records for this user.. will start with a a difficulty setting of 1")
        noUserPerformanceRecordsExist=True
      else:
        userPerfOrganizedByTimestamp=self.organizeUserPerformance(userPerformanceResponse)
        for k, v in userPerfOrganizedByTimestamp.items():
          if(currentTimestamp-k>15552000000):
            del userPerfOrganizedByTimestamp[k]
          else:
            break

        userScore=self.calculateUserScore(userPerfOrganizedByTimestamp)
        res.trace.append("user score :"+str(userScore))
        if(userScore==0):
          chosenDif="1"
        elif(userScore<0.75*100):
          chosenDif="1"
        elif(userScore<0.75*2*100):
          chosenDif="2"
        else:   #(userScore>0.75*3*100)
          chosenDif="3"
      res.trace.append("Chosen Diff :"+chosenDif)

      #Get cognitive tests of the selected type.
      serv_topic = rospy.get_param('rapp_knowrob_wrapper_cognitive_tests_of_type')
      if(not serv_topic):
        rospy.logerror("rapp_knowrob_wrapper_cognitive_tests_of_type not found")
        res.trace.append("rapp_knowrob_wrapper_cognitive_tests_of_type not found")
        res.error="rapp_knowrob_wrapper_cognitive_tests_of_type not found"
        res.success=False
        return res
      cognitiveTestsOfTypeSrvReq=cognitiveTestsOfTypeSrvRequest()
      cognitiveTestsOfTypeSrvReq.test_type=req.testType
      cognitiveTestsOfTypeSrvReq.test_language=userLanguage
      knowrob_service = rospy.ServiceProxy(serv_topic, cognitiveTestsOfTypeSrv)
      cognitiveTestsOfTypeResponse = knowrob_service(cognitiveTestsOfTypeSrvReq)

      if(cognitiveTestsOfTypeResponse.success!=True):
        res.trace.extend(cognitiveTestsOfTypeResponse.trace)
        res.error=cognitiveTestsOfTypeResponse.error
        res.success=False
        return res

      #print "after tests........."
      #Filter the tests according to the determined difficulty
      success,testsOfTypeOrdered=self.filterTestsbyDifficulty(cognitiveTestsOfTypeResponse,chosenDif,res)

      #If no test exists
      if(not success): #not len(testsOfTypeOrdered)>0):
        res.trace.append("Error, no tests of type contained in the ontology... cannot proceed")
        res.error="Error, no tests of type contained in the ontology... cannot proceed"
        res.success=False
        return res

      #Choose the least recently used test of the given test type and difficulty and obtain the path to the xml file
      finalTestname=""
      finalTestFilePath=""
      if(noUserPerformanceRecordsExist):
        #print "inside no records"
        finalTestname=random.choice(testsOfTypeOrdered.keys())
        finalTest=testsOfTypeOrdered[finalTestname]
        finalTestFilePath=finalTest[0][0]
      else:
        testsOfTypeOrderedCopy=testsOfTypeOrdered.copy()
        for k, v in userPerfOrganizedByTimestamp.items():
          if(v[0][0] in testsOfTypeOrderedCopy):
            del testsOfTypeOrderedCopy[v[0][0]]

        if(len(testsOfTypeOrderedCopy)>0):
          finalTestname=random.choice(testsOfTypeOrderedCopy.keys())
          finalTest=testsOfTypeOrderedCopy[finalTestname]
          finalTestFilePath=finalTest[0][0]
        else:
          finalTestname=userPerfOrganizedByTimestamp.values()[len(userPerfOrganizedByTimestamp)-1]
          finalTestname=finalTestname[0][0]
          finalTest=testsOfTypeOrdered[finalTestname]
          finalTestFilePath=finalTest[0][0]

      #Retrieve the name of the selected test
      tmpList=finalTestname.split('#')
      res.test=tmpList[1]

      #Parse the test xml file and retrieve the desired information
      rospack = rospkg.RosPack()
      localPackagePath=rospack.get_path('rapp_cognitive_exercise')
      finalTestFilePath=localPackagePath+finalTestFilePath
      res.trace.append(finalTestFilePath)
      self.retrieveDataFromTestXml(finalTestFilePath,res,userLanguage)
      res.language=userLanguage
      res.success=True

    except IndexError:
      res.trace.append("Null pointer exception.. some argument was empty")
      res.error="Null pointer exception.. some argument was empty"
      res.success=False
      #print "Wrong Query Input Format, check for empty required columns list or wrong/incomplete Query data format"
    except IOError:
      res.success=False
      res.trace.append("IO Error, cant open file or read data")
      res.error="IO Error, cant open file or read data"
    return res
예제 #7
0
    def chooserFunction(self, req):
        currentTimestamp = int(time.time())  #15552000000 for last 3 months

        try:
            res = testSelectorSrvResponse()
            #obtain user's ontology alias. It will be created if it does not exist in case of invalid username it will be caught
            serv_topic = rospy.get_param(
                'rapp_knowrob_wrapper_create_ontology_alias')
            if (not serv_topic):
                rospy.logerror(
                    "rapp_knowrob_wrapper_create_ontology_alias param not found"
                )
                res.trace.append(
                    "rapp_knowrob_wrapper_create_ontology_alias param not found"
                )
                res.error = "rapp_knowrob_wrapper_create_ontology_alias param not found"
                res.success = False
                return res
            rospy.wait_for_service(serv_topic)
            knowrob_service = rospy.ServiceProxy(serv_topic,
                                                 createOntologyAliasSrv)
            createOntologyAliasReq = createOntologyAliasSrvRequest()
            createOntologyAliasReq.username = req.username
            createOntologyAliasResponse = knowrob_service(
                createOntologyAliasReq)
            if (createOntologyAliasResponse.success != True):
                res.trace.extend(createOntologyAliasResponse.trace)
                res.error = createOntologyAliasResponse.error
                res.success = False
                return res

            #get user language
            serv_topic = rospy.get_param(
                'rapp_mysql_wrapper_user_fetch_data_topic')
            if (not serv_topic):
                rospy.logerror(
                    "rapp_mysql_wrapper_user_fetch_data_topic param not found")
                res.trace.append(
                    "rapp_mysql_wrapper_user_fetch_data_topic param not found")
                res.error = "mysql_wrapper_rapp_read_data topic param not found"
                res.success = False
                return res
            rospy.wait_for_service(serv_topic)
            knowrob_service = rospy.ServiceProxy(serv_topic, fetchDataSrv)
            fetchDataSrvReq = fetchDataSrvRequest()
            fetchDataSrvReq.req_cols = ["language"]
            fetchDataSrvReq.where_data = [
                StringArrayMsg(s=["username", req.username])
            ]
            #print fetchDataSrvReq.where_data
            fetchDataSrvResponse = knowrob_service(fetchDataSrvReq)
            if (fetchDataSrvResponse.success.data != True):
                #print fetchDataSrvResponse.res_data[0].s[0];
                res.trace.extend(fetchDataSrvResponse.trace)
                res.error = fetchDataSrvResponse.trace[0]
                res.success = False
                return res
            userLanguage = fetchDataSrvResponse.res_data[0].s[0]
            #print userLanguage
            #

            #Check if test type exists (if a test type is provided)
            serv_topic = rospy.get_param(
                'rapp_knowrob_wrapper_subclasses_of_topic')
            if (not serv_topic):
                rospy.logerror(
                    "rapp_knowrob_wrapper_subclasses_of_topic topic param not found"
                )
                res.trace.append(
                    "rapp_knowrob_wrapper_subclasses_of_topic topic param not found"
                )
                res.error = "rapp_knowrob_wrapper_subclasses_of_topic topic param not found"
                res.success = False
                return res
            rospy.wait_for_service(serv_topic)
            knowrob_service = rospy.ServiceProxy(serv_topic,
                                                 ontologySubSuperClassesOfSrv)
            testTypesReq = ontologySubSuperClassesOfSrvRequest()
            testTypesReq.ontology_class = "CognitiveTests"
            testTypesResponse = knowrob_service(testTypesReq)
            if (testTypesResponse.success != True):
                res.trace.extend(testTypesResponse.trace)
                res.trace.append("cannot load test categories from ontology")
                res.error = testTypesResponse.error + "cannot load test categories from ontology"
                res.success = False
                return res
            testTypesList = []
            for s in testTypesResponse.results:
                #res.trace.append(s)
                tmpList = s.split('#')
                testTypesList.append(tmpList[1])

            serv_topic = rospy.get_param(
                'rapp_knowrob_wrapper_user_performance_cognitve_tests')
            if (not serv_topic):
                rospy.logerror(
                    "rapp_knowrob_wrapper_user_performance_cognitve_tests topic not foud"
                )
                res.trace.append(
                    "mysql_wrapper_rapp_read_data topic param not found")
                res.error = "mysql_wrapper_rapp_read_data topic param not found"
                res.success = False
                return res

            if (req.testType == ""):
                res.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 = createOntologyAliasResponse.ontology_alias
                    knowrob_service = rospy.ServiceProxy(
                        serv_topic, userPerformanceCognitveTestsSrv)
                    userPerformanceResponse = knowrob_service(
                        userPerformanceReq)
                    if (userPerformanceResponse.success != True):
                        noRecordsList.append(s)
                    else:
                        tmpUserPerfOrganizedByTimestamp = self.organizeUserPerformance(
                            userPerformanceResponse)
                        t1 = tmpUserPerfOrganizedByTimestamp.items()[0][0]
                        d1[t1] = [s]

                if (len(noRecordsList) > 0):
                    req.testType = random.choice(noRecordsList)
                    res.trace.append(
                        "made random choice from the test types which were never used by the user, choice was: "
                        + req.testType)
                else:
                    d1 = OrderedDict(sorted(d1.items(), key=lambda t: t[0]))
                    req.testType = d1.values()[0][0]
                    res.trace.append(
                        "all test types had performance records.. least recently used one was :"
                        + req.testType)
            else:
                if (req.testType not in testTypesList):
                    res.trace.append("testType provided does not exist")
                    res.error = "testType provided does not exist"
                    res.success = False
                    return res

            # check if performance records exist for the selected test in order to determine the difficulty setting
            noUserPerformanceRecordsExist = False
            chosenDif = "1"
            userPerformanceReq = userPerformanceCognitveTestsSrvRequest()
            userPerformanceReq.test_type = req.testType
            userPerformanceReq.ontology_alias = createOntologyAliasResponse.ontology_alias
            knowrob_service = rospy.ServiceProxy(
                serv_topic, userPerformanceCognitveTestsSrv)
            userPerformanceResponse = knowrob_service(userPerformanceReq)
            if (userPerformanceResponse.success != True):
                res.trace.extend(userPerformanceResponse.trace)
                res.trace.append(
                    "KnowRob wrapper returned no performance records for this user.. will start with a a difficulty setting of 1"
                )
                noUserPerformanceRecordsExist = True
            else:
                userPerfOrganizedByTimestamp = self.organizeUserPerformance(
                    userPerformanceResponse)
                for k, v in userPerfOrganizedByTimestamp.items():
                    if (currentTimestamp - k > 15552000000):
                        del userPerfOrganizedByTimestamp[k]
                    else:
                        break

                userScore = self.calculateUserScore(
                    userPerfOrganizedByTimestamp)
                res.trace.append("user score :" + str(userScore))
                if (userScore == 0):
                    chosenDif = "1"
                elif (userScore < 0.75 * 100):
                    chosenDif = "1"
                elif (userScore < 0.75 * 2 * 100):
                    chosenDif = "2"
                else:  #(userScore>0.75*3*100)
                    chosenDif = "3"
            res.trace.append("Chosen Diff :" + chosenDif)

            #Get cognitive tests of the selected type.
            serv_topic = rospy.get_param(
                'rapp_knowrob_wrapper_cognitive_tests_of_type')
            if (not serv_topic):
                rospy.logerror(
                    "rapp_knowrob_wrapper_cognitive_tests_of_type not found")
                res.trace.append(
                    "rapp_knowrob_wrapper_cognitive_tests_of_type not found")
                res.error = "rapp_knowrob_wrapper_cognitive_tests_of_type not found"
                res.success = False
                return res
            cognitiveTestsOfTypeSrvReq = cognitiveTestsOfTypeSrvRequest()
            cognitiveTestsOfTypeSrvReq.test_type = req.testType
            cognitiveTestsOfTypeSrvReq.test_language = userLanguage
            knowrob_service = rospy.ServiceProxy(serv_topic,
                                                 cognitiveTestsOfTypeSrv)
            cognitiveTestsOfTypeResponse = knowrob_service(
                cognitiveTestsOfTypeSrvReq)

            if (cognitiveTestsOfTypeResponse.success != True):
                res.trace.extend(cognitiveTestsOfTypeResponse.trace)
                res.error = cognitiveTestsOfTypeResponse.error
                res.success = False
                return res

            #print "after tests........."
            #Filter the tests according to the determined difficulty
            success, testsOfTypeOrdered = self.filterTestsbyDifficulty(
                cognitiveTestsOfTypeResponse, chosenDif, res)

            #If no test exists
            if (not success):  #not len(testsOfTypeOrdered)>0):
                res.trace.append(
                    "Error, no tests of type contained in the ontology... cannot proceed"
                )
                res.error = "Error, no tests of type contained in the ontology... cannot proceed"
                res.success = False
                return res

            #Choose the least recently used test of the given test type and difficulty and obtain the path to the xml file
            finalTestname = ""
            finalTestFilePath = ""
            if (noUserPerformanceRecordsExist):
                #print "inside no records"
                finalTestname = random.choice(testsOfTypeOrdered.keys())
                finalTest = testsOfTypeOrdered[finalTestname]
                finalTestFilePath = finalTest[0][0]
            else:
                testsOfTypeOrderedCopy = testsOfTypeOrdered.copy()
                for k, v in userPerfOrganizedByTimestamp.items():
                    if (v[0][0] in testsOfTypeOrderedCopy):
                        del testsOfTypeOrderedCopy[v[0][0]]

                if (len(testsOfTypeOrderedCopy) > 0):
                    finalTestname = random.choice(
                        testsOfTypeOrderedCopy.keys())
                    finalTest = testsOfTypeOrderedCopy[finalTestname]
                    finalTestFilePath = finalTest[0][0]
                else:
                    finalTestname = userPerfOrganizedByTimestamp.values()[
                        len(userPerfOrganizedByTimestamp) - 1]
                    finalTestname = finalTestname[0][0]
                    finalTest = testsOfTypeOrdered[finalTestname]
                    finalTestFilePath = finalTest[0][0]

            #Retrieve the name of the selected test
            tmpList = finalTestname.split('#')
            res.test = tmpList[1]

            #Parse the test xml file and retrieve the desired information
            rospack = rospkg.RosPack()
            localPackagePath = rospack.get_path('rapp_cognitive_exercise')
            finalTestFilePath = localPackagePath + finalTestFilePath
            res.trace.append(finalTestFilePath)
            self.retrieveDataFromTestXml(finalTestFilePath, res, userLanguage)
            res.language = userLanguage
            res.success = True

        except IndexError:
            res.trace.append(
                "Null pointer exception.. some argument was empty")
            res.error = "Null pointer exception.. some argument was empty"
            res.success = False
            #print "Wrong Query Input Format, check for empty required columns list or wrong/incomplete Query data format"
        except IOError:
            res.success = False
            res.trace.append("IO Error, cant open file or read data")
            res.error = "IO Error, cant open file or read data"
        return res