def parse(self, data, clock):
        if not data:  # nothing received or nothing in the history -> nothing to parse
            return None

        if self.lenNames > len(data):
            raise Exception("CSVParser: not enough data fields")

        result = JOb()
        sd = self.wrapper.getSensorDescription()
        result.fields = sd.fields
        # print data
        for i in range(0, self.lenNames):
            n = self.names[i]
            if n in sd.fields:
                result[n] = JOb()
                result[n].propertyName = sd.field[n].propertyName
                result[n].propertyURI = sd.field[n].propertyURI
                if "unit" in sd.field[n]:
                    result[n].unit = sd.field[n].unit
                result[n].observationSamplingTime = clock.timeAsString()
                result[n].sensorID = sd.fullSensorID
                if self.timestampcell >= 0:
                    result[n].observationResultTime = sd.parseTimestamp(data[self.timestampcell]).strftime(AbstractClock.format)
                else:
                    result[n].observationResultTime = result[n].observationSamplingTime

                if sd.field[n].dataType == "datetime.datetime":
                    result[n].value = dt.datetime.strptime(data[i], sd.field[n].format)
                else:
                    result[n].value = str2Type(u(data[i]), sd.field[n].dataType)

        return result
 def getQualityValues(self, jOb, name, avgQualityType):
     q = JSONObject()
     q.absoluteValues = self.qList.get(avgQualityType).absoluteBuffer.items
     q.ratedValues = self.qList.get(avgQualityType).ratedBuffer.items
     q.name = name
     q.unit = self.unit
     jOb.values.append(q)
 def getAvgQualities(self, jOb, name):
     for key in self.qList:
         q = JSONObject()
         q.absoluteValue = self.qList.get(key).getAbsoluteAverage()
         q.absoluteValueMin = self.qList.get(key).getAbsoluteMin()
         q.absoluteValueMax = self.qList.get(key).getAbsoluteMax()
         q.ratedValue = self.qList.get(key).getRatedAverage()
         q.ratedValueMin = self.qList.get(key).getRatedMin()
         q.ratedValueMax = self.qList.get(key).getRatedMax()
         q.name = name
         q.unit = self.unit
         jOb[key].values.append(q)
 def getLastQoI(self, types=None, avg=None, minimum=None, maximum=None):
     qoiData = JSONObject()
     for metric in self.reputationSystem.metrics:
         q = JSONObject()
         currentValues = JSONObject()
         currentValues.absoluteValue = metric.absoluteValue
         currentValues.ratedValue = metric.ratedValue
         q.unit = metric.unit
         qoiData[metric.name] = q
         q.CURRENT = currentValues
         if types:
             self.reputationSystem.avgQoIManager.getValues(q, metric.name, types, avg, minimum, maximum)
     return qoiData
    def update(self, data):
        self.updateDescription()

        # special case when no fields are in data
        # (fault recovery is not ready yet)
        if len(data.fields) == 0:
            self.rewardAndPunishment.update(False)
            self.absoluteValue = float("inf")
            self.ratedValue = self.rewardAndPunishment.value()
            return

        ts = self.repsys.timestamp


        self.updatecounter += 1

        samplingTime = datetime.datetime.strptime(data[data.fields[0]].observationSamplingTime,
                                                  AbstractClock.parserformat)

        age = (samplingTime - ts).total_seconds()
#         print "age:", age, "ts", ts, "sampling", samplingTime

        if self.lastUpdate == None:
            self.lastUpdate = ts
            self.rewardAndPunishment.update(True)
            self.absoluteValue = age
            self.ratedValue = 1.0
            self.min = age
            self.mean = age
        else:
            # 			delta = ts - self.lastUpdate
            self.lastUpdate = ts
            if data.recovered:
                self.rewardAndPunishment.update(False)
            else:
                self.rewardAndPunishment.update(age <= self.annotatedAge)

            # 			delay = delta.days * 86400 + delta.seconds
            self.absoluteValue = age
            self.ratedValue = self.rewardAndPunishment.value()
            age = float(age)
            self.min = min(self.min, age)
            self.mean = ((self.updatecounter - 1) * self.mean) / self.updatecounter + age / self.updatecounter

        ageReturn = JSONObject()

        ageReturn.absoluteValue = self.absoluteValue
        ageReturn.ratedValue = self.ratedValue
        ageReturn.unit = self.unit
        return (self.name, ageReturn)
    def update(self, data):
        self.updateDescription()

        # special case when no fields are in data
        # (fault recovery is not ready yet)
        if len(data.fields) == 0:
            self.rewardAndPunishment.update(False)
            self.absoluteValue = float("inf")
            self.ratedValue = self.rewardAndPunishment.value()
            return

        ts = self.repsys.timestamp

        self.updatecounter += 1

        latency = data.latency

        annotatedLatency = self.repsys.description.maxLatency

        if self.lastUpdate is None:
            self.lastUpdate = ts
            self.rewardAndPunishment.update(True)
            self.absoluteValue = latency
            self.ratedValue = 1.0
            self.min = latency
            self.mean = latency
        else:
            self.lastUpdate = ts
            
            if data.recovered:
                self.rewardAndPunishment.update(False)
            else:
                self.rewardAndPunishment.update(annotatedLatency > latency)

            self.absoluteValue = latency
            self.ratedValue = self.rewardAndPunishment.value()
            self.min = min(self.min, latency)
            self.mean = ((self.updatecounter - 1) * self.mean) / self.updatecounter + latency / self.updatecounter

        lat = JSONObject()

        lat.absoluteValue = self.absoluteValue
        lat.ratedValue = self.ratedValue
        lat.unit = self.unit
        return (self.name, lat)
    def parse(self, data, clock):
        if not data:  # nothing received or nothing in the history -> nothing to parse
            return None

        if isinstance(data, str) or isinstance(data, unicode):
            data = JOb(u(data))

        result = JOb()
        sd = self.wrapper.getSensorDescription()
        result.fields = sd.fields
        for fieldname in sd.fields:
            result[fieldname] = JOb()
            result[fieldname].propertyName = sd.field[fieldname].propertyName
            result[fieldname].propertyURI = sd.field[fieldname].propertyURI
            if "unit" in sd.field[fieldname]:
                result[fieldname].unit = sd.field[fieldname].unit
            result[fieldname].sensorID = sd.fullSensorID
            result[fieldname].observationSamplingTime = clock.timeAsString()
            if self.timestampfield and self.timestampfield in data:
                result[fieldname].observationResultTime = sd.parseTimestamp(data[self.timestampfield]).strftime(
                    AbstractClock.format
                )
            else:
                result[fieldname].observationResultTime = result[fieldname].observationSamplingTime

            if sd.field[fieldname].dataType == "datetime.datetime":
                if sd.field[fieldname].format.startswith("UNIX"):
                    result[fieldname].value = sd.parseTimestamp(data[fieldname]) if fieldname in data else None
                else:
                    result[fieldname].value = (
                        dt.datetime.strptime(data[fieldname], sd.field[fieldname].format) if fieldname in data else None
                    )
            else:
                result[fieldname].value = (
                    str2Type(u(data[fieldname]), sd.field[fieldname].dataType) if fieldname in data else None
                )

        return result
    def update(self, data):
        self.updatecounter += 1

        # special case when no fields are in data
        # (fault recovery is not ready yet)
        if len(data.fields) == 0:
            self.rewardAndPunishment.update(False)
            self.absoluteValue = float("inf")
            self.ratedValue = self.rewardAndPunishment.value()
            return


        wrongFieldList = []
        for field in data.fields:
            if field not in data:
                wrongFieldList.append(field)
                continue

            dataTypeStr = self.repsys.description.field[field].dataType
            dataType = utils.getType(dataTypeStr)
            minValue, maxValue = self.getMinMaxValue(field, data)

            value = data[field].value
            # print "field:", field, "value:", value, "min:", minValue, "max:", maxValue, "dataType:", dataTypeStr, dataType, "value type:", type(value)

            if minValue and maxValue:
                if dataTypeStr == "datetime.datetime":
                    minValue = datetime.datetime.strptime(minValue, AbstractClock.parserformat)
                    maxValue = datetime.datetime.strptime(maxValue, AbstractClock.parserformat)
                else:
                    maxValue = dataType(maxValue)
                    minValue = dataType(minValue)

            # everything might be a string => first check for type, then try to cast, afterwards check min and max
            wrongValue = False
            if not isinstance(value, dataType): # type(value) is not dataType:
                try:
                    # special handling for datetime as format is needed
                    if dataTypeStr == "datetime.datetime":
                        value = datetime.datetime.strptime(value, self.repsys.description.field[field].format)
                    else:
                        value = dataType(value)
                except ValueError:
                    wrongFieldList.append(field)
                    wrongValue = True

            if not wrongValue:
                # now check if value is within min max interval
                if minValue and minValue is not "":
                    if value < minValue:
                        wrongFieldList.append(field)
                elif maxValue and maxValue is not "":
                    if value > maxValue:
                        wrongFieldList.append(field)
# 			print "Correctness for", self.repsys.description.fullSensorID, len(wrongFieldList), value, minValue, maxValue

        nrWrongFields = len(wrongFieldList)
        if nrWrongFields > 0:
            L.d("Correctness wrong fields:", nrWrongFields, "(", ",".join(wrongFieldList), ")")

        if data.recovered or (nrWrongFields >= 1):
            self.rewardAndPunishment.update(False)
        else:
            self.rewardAndPunishment.update(True)

        self.ratedValue = self.rewardAndPunishment.value()
        self.absoluteValue = 1 - nrWrongFields / len(data.fields)
        self.min = min(self.min, self.absoluteValue)
        self.mean = ((self.updatecounter - 1) * self.mean) / self.updatecounter + float(
            self.absoluteValue) / self.updatecounter

        correctness = JSONObject()
        correctness.wrongFields = wrongFieldList
        correctness.absoluteValue = self.absoluteValue
        correctness.ratedValue = self.ratedValue
        correctness.unit = self.unit
        # 		print "correctness:", self.ratedValue, self.absoluteValue
        return (self.name, correctness)
    def update(self, data):
        # special case when no fields are in data
        # (fault recovery is not ready yet)
        if len(data.fields) == 0:
            self.rewardAndPunishment.update(False)
            self.absoluteValue = float("inf")
            self.ratedValue = self.rewardAndPunishment.value()
            return

        # look for expected fields in sensor description, look only for non optional fields
        fields = self.repsys.description.fields
        fields = [x for x in fields if not self.repsys.description.field[x].optional]
        
        receivedFields = data.fields

        # check if expected and received identical, how to handle received fields with no values?
        nrOfMissingFields = 0
        missingFields = set()
        if set(fields).difference(set(receivedFields)):
            # lists are different
            missingFields = set(fields).difference(set(receivedFields))
            nrOfMissingFields = len(missingFields)

        # now go through all fields and check for NULL, NA,...
        nrOfWrongFields = 0
        wrongFields = set()
        wrongValues = ['None', 'Null', '', 'NA']  #TODO make the list of wrong values configurable
        for field in data.fields:
            if field in data:
                value = data[field].value
                if value is None or value in wrongValues:
                    nrOfWrongFields += 1
                    wrongFields.add(field)
            else:
                nrOfWrongFields += 1
                wrongFields.add(field)

        if nrOfMissingFields > 0:
            L.d("Completeness missing fields:", nrOfMissingFields, "(", ",".join(missingFields), ")")
        if nrOfWrongFields > 0:
            L.d("Completeness wrong fields:", nrOfWrongFields, "(", ",".join(wrongFields), ")")

        length = len(self.repsys.description.fields)
        currentLength = length - nrOfMissingFields - nrOfWrongFields
        self.updatecounter += 1
        if not self.goal:
            self.goal = length
            self.min = float(length)
            self.mean = float(length)
        # 			return (length, self.rewardAndPunishment.value())
        else:
            self.min = min(self.min, currentLength)
            self.mean = ((self.updatecounter - 1) * self.mean) / self.updatecounter + float(
                currentLength) / self.updatecounter
                
        if data.recovered:
            self.rewardAndPunishment.update(False)
        else:
            self.rewardAndPunishment.update(self.goal == currentLength)
        self.absoluteValue = currentLength
        self.ratedValue = self.rewardAndPunishment.value()

        completeness = JSONObject()
        completeness.missingFields = list(missingFields | wrongFields)
        completeness.absoluteValue = self.absoluteValue
        completeness.ratedValue = self.ratedValue
        completeness.unit = self.unit


        # 		print completeness.dumps()

        # 		print "completeness:", self.name, completeness
        # 		print (self.name, missingFields)
        return (self.name, completeness)
    def update(self):
        from virtualisation.resourcemanagement.resourcemanagement import ResourceManagement

        # print "time", self.clock.now()
        latStart = datetime.now()
        L.d("processing:", self.getSensorDescription().sensorID)
        # L.d(self.clock.now())
        if self.replaymode:
            self.stats.startMeasurement("Update_replay")
            #             self.clock.pause()
            if self.historyreader:
                L.d2("abstractwrapper get data")
                self.stats.startMeasurement("Update_replay.Historyreader")
                data_raw = self.historyreader.tick(self.clock)
                self.stats.stopMeasurement("Update_replay.Historyreader")
                L.d2("abstractwrapper received data:", str(data_raw))
                if data_raw:
                    data_list = [data_raw] if not self.historyreader.multiple_observations else data_raw
                    for data in data_list:
                        try:
                            L.d2("abstractwrapper parse data")
                            # print "data to parse", data
                            self.stats.startMeasurement("Update_replay.Historyparser")
                            parsed = self.historyparser.parse(data, self.clock)
                            self.stats.stopMeasurement("Update_replay.Historyparser")
                            L.d2("abstractwrapper parsed data:", str(parsed))
                            del data
                            if parsed:
                                self.stats.startMeasurement("Update_replay.Preparation")
                                ObservationIDGenerator.addObservationIDToFields(parsed)
                                parsed.producedInReplayMode = True
                                parsed.recovered = False
                                parsed.latency = (datetime.now() - latStart).total_seconds()
                                self.stats.stopMeasurement("Update_replay.Preparation")

                                # QoI Start
                                quality = None
                                if self.qoiSystem:
                                    L.d2("abstractwrapper get quality")
                                    self.stats.startMeasurement("Update_replay.Quality")
                                    quality = self.qoiSystem.addData(self.getSensorDescription(), parsed, self.clock)
                                    self.stats.stopMeasurement("Update_replay.Quality")
                                    L.d2("abstractwrapper quality:", quality)
                                if self.faultRecoveryActive:
                                    L.d2("abstractwrapper update fault recovery")
                                    self.stats.startMeasurement("Update_replay.FaultRecoveryUpdate")
                                    self.updateFaultRecoveries(parsed, quality)
                                    self.stats.stopMeasurement("Update_replay.FaultRecoveryUpdate")
                                    L.d2("abstractwrapper fault recovery updated")

                                self.stats.startMeasurement("Update_replay.Receiver")
                                for r in self.receiver:
                                    L.d2("abstractwrapper start receiver", r)
                                    r.receive(parsed, self.getSensorDescription(), self.clock, quality)
                                    L.d2("abstractwrapper receiver", r, "finished")
                                self.stats.stopMeasurement("Update_replay.Receiver")
                        except Exception as e:
                            L.e("Error while updating sensor", self.getSensorDescription().fullSensorID, e)
                        finally:
                            if ResourceManagement.args.gentle:
                                self.clock.sleep()
                else:
                    L.d("there is no data, ask fault recovery1")
                    # L.i(self.getSensorDescription().sensorID)
                    # L.i(self.clock.now())
                    try:
                        self.stats.startMeasurement("Update_replay.Recovery")
                        data = JSONObject()
                        data.latency = 0
                        data.producedInReplayMode = True
                        data.recovered = True

                        data.fields = []
                        for n in self.getSensorDescription().fields:
                            if n in self.faultRecoveries and self.faultRecoveries[n].isReady():
                                data.fields.append(n)
                                data[n] = JSONObject()
                                # at this point the dataType is in FAULT_RECOVERY_SUPPORTED_DATATYPES and we can safely use cast
                                data[n].value = self.faultRecoveryCast(
                                    self.faultRecoveries[n].getEstimation(),
                                    self.getSensorDescription().field[n].dataType,
                                )
                                data[n].propertyName = self.getSensorDescription().field[n].propertyName
                                data[n].propertyURI = self.getSensorDescription().field[n].propertyURI
                                if "unit" in self.getSensorDescription().field[n]:
                                    data[n].unit = self.getSensorDescription().field[n].unit
                                data[n].sensorID = self.getSensorDescription().fullSensorID
                                data[n].observationSamplingTime = self.clock.timeAsString()
                                data[n].observationResultTime = data[n].observationSamplingTime
                        self.stats.stopMeasurement("Update_replay.Recovery")

                        self.stats.startMeasurement("Update_replay.ObservationIDGenerator")
                        ObservationIDGenerator.addObservationIDToFields(data)
                        self.stats.stopMeasurement("Update_replay.ObservationIDGenerator")

                        quality = None
                        if self.qoiSystem:
                            self.stats.startMeasurement("Update_replay.Quality")
                            quality = self.qoiSystem.addData(self.getSensorDescription(), data, self.clock)
                            self.stats.stopMeasurement("Update_replay.Quality")

                        self.stats.startMeasurement("Update_replay.Receiver")
                        for r in self.receiver:
                            r.receive(data, self.getSensorDescription(), self.clock, quality)
                        self.stats.stopMeasurement("Update_replay.Receiver")
                    except Exception as e:
                        L.e("Error while updating sensor", self.getSensorDescription().fullSensorID, e)
                    finally:
                        pass
                        # if ResourceManagement.args.gentle:
                        #     self.clock.sleep()
            else:
                pass  # no history reader - nothing to do
            self.stats.stopMeasurement("Update_replay")
        else:  # no replay mode
            self.stats.startMeasurement("Update_live")
            if self.connection:
                try:
                    self.stats.startMeasurement("Update_live.Connection")
                    data_raw = self.connection.next()
                    self.stats.stopMeasurement("Update_live.Connection")
                    if data_raw:
                        data_list = [data_raw] if not self.connection.multiple_observations else data_raw
                        for data in data_list:
                            self.stats.startMeasurement("Update_live.Parser")
                            parsed = self.parser.parse(data, self.clock)
                            self.stats.stopMeasurement("Update_live.Parser")
                            if parsed:
                                self.stats.startMeasurement("Update_live.Preparation")
                                ObservationIDGenerator.addObservationIDToFields(parsed)
                                parsed.producedInReplayMode = False
                                parsed.recovered = False
                                parsed.latency = (datetime.now() - latStart).total_seconds()
                                self.stats.stopMeasurement("Update_live.Preparation")

                                # QoI Start
                                quality = None
                                if self.qoiSystem:
                                    # TODO update the timestamp
                                    self.stats.startMeasurement("Update_live.Quality")
                                    quality = self.qoiSystem.addData(self.getSensorDescription(), parsed, self.clock)
                                    self.stats.stopMeasurement("Update_live.Quality")
                                if self.faultRecoveryActive:
                                    L.d2("abstractwrapper update fault recovery")
                                    self.stats.startMeasurement("Update_live.FaultRecoveryUpdate")
                                    self.updateFaultRecoveries(parsed, quality)
                                    self.stats.stopMeasurement("Update_live.FaultRecoveryUpdate")
                                    L.d2("abstractwrapper fault recovery updated")

                                self.stats.startMeasurement("Update_live.Receiver")
                                for r in self.receiver:
                                    r.receive(parsed, self.getSensorDescription(), self.clock, quality)
                                self.stats.stopMeasurement("Update_live.Receiver")
                    else:
                        # fault recovery
                        L.i("there is no data, ask fault recovery2")
                        try:
                            self.stats.startMeasurement("Update_live.Recovery")
                            data = JSONObject()
                            data.latency = 0
                            data.recovered = True
                            data.fields = []
                            for n in self.getSensorDescription().fields:
                                if n in self.faultRecoveries and self.faultRecoveries[n].isReady():
                                    data.fields.append(n)
                                    data[n] = JSONObject()
                                    data[n].value = self.faultRecoveryCast(
                                        self.faultRecoveries[n].getEstimation(),
                                        self.getSensorDescription().field[n].dataType,
                                    )
                                    data[n].propertyName = self.getSensorDescription().field[n].propertyName
                                    data[n].propertyURI = self.getSensorDescription().field[n].propertyURI
                                    if "unit" in self.getSensorDescription().field[n]:
                                        data[n].unit = self.getSensorDescription().field[n].unit
                                    data[n].sensorID = self.getSensorDescription().fullSensorID
                                    data[n].observationSamplingTime = self.clock.timeAsString()
                                    data[n].observationResultTime = data[n].observationSamplingTime
                            self.stats.stopMeasurement("Update_live.Recovery")

                            ObservationIDGenerator.addObservationIDToFields(data)
                            quality = None
                            if self.qoiSystem:
                                self.stats.startMeasurement("Update_live.Quality")
                                quality = self.qoiSystem.addData(self.getSensorDescription(), data, self.clock)
                                self.stats.stopMeasurement("Update_live.Quality")

                            self.stats.startMeasurement("Update_live.Receiver")
                            for r in self.receiver:
                                r.receive(data, self.getSensorDescription(), self.clock, quality)
                            self.stats.stopMeasurement("Update_live.Receiver")
                        except Exception as e:
                            L.e(
                                "Error while updating sensor (fault recovery)",
                                self.getSensorDescription().fullSensorID,
                                str(e),
                            )
                        finally:
                            pass
                            # if ResourceManagement.args.gentle:
                            #     self.clock.sleep()
                except Exception as e:
                    L.e(
                        "Error while updating sensor (not fault recovery)",
                        self.getSensorDescription().fullSensorID,
                        str(e),
                    )
            else:
                pass  # no live mode supported
            self.stats.stopMeasurement("Update_live")
	def nonValueUpdate(self):
		jsonOb = JSONObject()
		jsonOb.absoluteValue = self.absoluteValue
		jsonOb.ratedValue = self.ratedValue
		jsonOb.unit = self.unit
		return (self.name, jsonOb)