Beispiel #1
0
        public async Task <TraceMeasures> Trace(TraceLocation location)
        {
            var query = HttpUtility.ParseQueryString(string.Empty);

            query["lat"]                = location.Coordinate.Lat.ToString(CultureInfo.InvariantCulture);
            query["lng"]                = location.Coordinate.Lng.ToString(CultureInfo.InvariantCulture);
            query["accuracyRadius"]     = location.Accuracy.Radius.ToString(CultureInfo.InvariantCulture);
            query["accuracyConfidence"] = location.Accuracy.Confidence.ToString(CultureInfo.InvariantCulture);
            query["timestamp"]          = location.Timestamp.ToString("o");
            var url = $"api/directions/{_directionsKey}/itineraries/{_index}/trace?{query.ToString()}";
            var res = await(await _clientFactory()).GetAsync(url);

            if (res.IsSuccessStatusCode)
            {
                var content = await res.Content.ReadAsStringAsync();

                var traceMeasures = JsonConvert.DeserializeObject <TraceMeasures>(content);
                return(traceMeasures);
            }
            else if (res.StatusCode == System.Net.HttpStatusCode.NotFound)
            {
                return(null);
            }
            throw new TravelServiceException($"Could not trace: {res.StatusCode}");
        }
        public TraceMeasures TraceUserWithParticles(Itinerary itinerary, TraceLocation location)
        {
            var polyLine = itinerary.Legs.Where(d => null != d.Geometry).SelectMany(d => d.Geometry).ToList();

            if (polyLine.Count < 2)
            {
                throw new Exception("Itinerary must have at least two points");
            }
            var    standardDeviation = GetStandardDeviation(location.Accuracy);
            var    z = NormalDistributionTable.ReverseLookUpD(StandardConfidence);
            var    radiusStandardConfidence = z * standardDeviation;
            var    denseLine   = InsertPointsBetween(polyLine).ToList();
            double countOnPath = 0;
            double routeWidth  = Math.Max(AllowedDeviation, (4 * radiusStandardConfidence) / 3.0);

            for (int i = 0; i < NumParticles; i++)
            {
                var distance = CoordinatePolyLineDistance(denseLine,
                                                          GetNormalDistributedParticle(standardDeviation, location.Coordinate));
                if (distance <= routeWidth)
                {
                    countOnPath++;
                }
            }
            return(new TraceMeasures
            {
                ConfidenceOnRoute = countOnPath / NumParticles,
                RouteWidth = routeWidth,
                PositionOnRoute = GetPostitionOnRoute(itinerary, denseLine, location)
            });
        }
        private static int RecBound(string recFunc, Counterexample trace, string traceName)
        {
            var ret = 0;

            if (trace == null)
            {
                return(ret);
            }
            if (recFunc == traceName)
            {
                ret++;
            }

            for (int numBlock = 0; numBlock < trace.Trace.Count; numBlock++)
            {
                Block b = trace.Trace[numBlock];
                for (int numInstr = 0; numInstr < b.Cmds.Count; numInstr++)
                {
                    Cmd c   = b.Cmds[numInstr];
                    var loc = new TraceLocation(numBlock, numInstr);
                    if (trace.calleeCounterexamples.ContainsKey(loc))
                    {
                        ret +=
                            RecBound(recFunc, trace.calleeCounterexamples[loc].counterexample,
                                     (c as CallCmd).Proc.Name);
                    }
                }
            }
            return(ret);
        }
        public TraceMeasures TraceUserOnItinerary(Itinerary itinerary, TraceLocation location)
        {
            var polyLine = itinerary.Legs.Where(d => null != d.Geometry).SelectMany(d => d.Geometry).ToList();

            if (polyLine.Count < 2)
            {
                throw new Exception("Itinerary must have at least two points");
            }
            var denseLine         = InsertPointsBetween(polyLine).ToList();
            var standardDeviation = GetStandardDeviation(location.Accuracy);
            var z = NormalDistributionTable.ReverseLookUpD(StandardConfidence);
            var radiusStandardConfidence = z * standardDeviation;

            var polyPointsInConfidenceRadius =
                GetPolyPointsInConfidenceRadius(denseLine, radiusStandardConfidence, location.Coordinate);

            if (!polyPointsInConfidenceRadius.Any(v => v.InConfidenceRadius))
            {
                return(new TraceMeasures
                {
                    ConfidenceOnRoute = 0,
                    RouteWidth = 0.01
                });
            }
            var circleIntersection = PolyLineLengthInCircle(polyPointsInConfidenceRadius, location.Coordinate, radiusStandardConfidence);

            double confidenceRadius = radiusStandardConfidence;
            double confidence       = StandardConfidence;

            var smallestDistanceToCircle = circleIntersection.InsidePoints.Where(i =>
                                                                                 circleIntersection.EnterPoints.All(e => GetDistance(e, i.Point) > StandardRouteWidth) &&
                                                                                 circleIntersection.ExitPoints.All(e => GetDistance(e, i.Point) > StandardRouteWidth))
                                           .OrderBy(v => v.Distance).FirstOrDefault();

            if (null != smallestDistanceToCircle && smallestDistanceToCircle.Distance < StandardRouteWidth)
            {
                var increaseCircle  = StandardRouteWidth - smallestDistanceToCircle.Distance;
                var increaseClamped = Math.Min(increaseCircle, 3 * standardDeviation - confidenceRadius);
                confidenceRadius          += increaseClamped;
                confidence                 = 2 * NormalDistributionTable.LookupZ(confidenceRadius / standardDeviation) - 1;
                circleIntersection.Length += 2 * increaseClamped; //todo
            }
            var confidenceOnRoute = (circleIntersection.Length * StandardRouteWidth / (Math.PI * Math.Pow(confidenceRadius, 2))) * confidence;

            return(new TraceMeasures
            {
                ConfidenceOnRoute = confidenceOnRoute,
                RouteWidth = StandardRouteWidth
            });
        }
Beispiel #5
0
        private static void printLabels(Counterexample cex, TokenTextWriter ttw, int indent)
        {
            for (int numBlock = 0; numBlock < cex.Trace.Count; numBlock++)
            {
                Block b = cex.Trace[numBlock];

                printIndent(ttw, indent);
                ttw.WriteLine(b.Label);

                for (int numInstr = 0; numInstr < b.Cmds.Count; numInstr++)
                {
                    Cmd c   = b.Cmds[numInstr];
                    var loc = new TraceLocation(numBlock, numInstr);
                    if (cex.calleeCounterexamples.ContainsKey(loc))
                    {
                        printIndent(ttw, indent); ttw.WriteLine("call to {0}:", (c as CallCmd).Proc.Name);
                        printLabels(cex.calleeCounterexamples[loc].counterexample, ttw, indent + 1);
                        printIndent(ttw, indent); ttw.WriteLine("return from {0}.", (c as CallCmd).Proc.Name);
                        printIndent(ttw, indent); ttw.WriteLine(b.Label);
                    }
                }
            }
        }
        public PositionOnRoute GetPostitionOnRoute(Itinerary itinerary, List <Coordinate> denseLine, TraceLocation location)
        {
            var positionOnRoute = denseLine
                                  .Select(v => new { v, Distance = GetDistance(v, location.Coordinate) })
                                  .OrderBy(v => v.Distance)
                                  .Select(v => v.v)
                                  .First();
            var positionIndex = denseLine.IndexOf(positionOnRoute);

            foreach (var leg in itinerary.Legs.Where(l => null != l.Geometry))
            {
                var itStart = denseLine.Where(c => c.Lat == leg.Geometry[0].Lat && c.Lng == leg.Geometry[0].Lng)
                              .First();
                var itStartIndex = denseLine.IndexOf(itStart);
                var itEnd        = denseLine.Where(c => c.Lat == leg.Geometry[leg.Geometry.Length - 1].Lat && c.Lng == leg.Geometry[leg.Geometry.Length - 1].Lng)
                                   .First();
                var itEndIndex = denseLine.IndexOf(itEnd);
                if (itStartIndex <= positionIndex && positionIndex <= itEndIndex)
                {
                    double length    = 0;
                    double wayLength = 0;
                    for (int i = itStartIndex; i < itEndIndex; i++)
                    {
                        var dist = GetDistance(denseLine[i], denseLine[i + 1]);
                        length += dist;
                        if (i < positionIndex)
                        {
                            wayLength += dist;
                        }
                    }
                    TimeSpan delay;
                    if (length > 0)
                    {
                        var pointTime = leg.StartTime + (wayLength) * ((leg.EndTime - leg.StartTime) / (length));
                        delay = location.Timestamp - pointTime;
                    }
                    else
                    {
                        delay = location.Timestamp - leg.EndTime;
                    }
                    return(new PositionOnRoute()
                    {
                        LegIndex = Array.IndexOf(itinerary.Legs, leg),
                        LocationOnRoute = positionOnRoute,
                        Delay = delay
                    });
                }
            }
            throw new Exception("Position on route not found");
        }
Beispiel #7
0
        // Note: this does not reconstruct the failing assert in trace
        public static void ReconstructImperativeTrace(Counterexample trace, string currProc, Dictionary <string, Implementation> origProg)
        {
            if (trace == null)
            {
                return;
            }

            var originalBlocks = BoogieUtil.labelBlockMapping(origProg[currProc]);

            var newBlocks       = new List <Block>();
            var newCalleeTraces = new Dictionary <TraceLocation, CalleeCounterexampleInfo>();

            for (int numBlock = 0; numBlock < trace.Trace.Count; numBlock++)
            {
                Block b = trace.Trace[numBlock];

                Block ib;
                originalBlocks.TryGetValue(b.Label, out ib);
                if (ib == null)
                {
                    // Such blocks correspond to "itermediate" blocks inserted
                    // by Boogie. We can ignore them. (But note that we should
                    // still check that the counterexample is a valid path in impl
                    // to guard against vagaries of Boogie.)

                    //Log.Out(Log.Normal, "Could not find block " + b.Label);
                    //b.Emit(new TokenTextWriter(Console.Out), 0);
                    for (int numInstr = 0; numInstr < b.Cmds.Count; numInstr++)
                    {
                        if (trace.calleeCounterexamples.ContainsKey(new TraceLocation(numBlock, numInstr)))
                        {
                            throw new InternalError("BoogieVerify: An intermediate block has a procedure call");
                        }
                    }
                }
                else
                {
                    // We have a corresponding block. The number of Commands in b and ib won't match. We
                    // simply use all of the Cmds of ib -- and match the calls manually
                    // TODO: Fix this! It doesn't work when the failing assert is not the last statement
                    // of the block
                    newBlocks.Add(ib);
                    var calleeTraces = new List <Duple <string, CalleeCounterexampleInfo> >();
                    for (int numInstr = 0; numInstr < b.Cmds.Count; numInstr++)
                    {
                        var loc = new TraceLocation(numBlock, numInstr);
                        if (trace.calleeCounterexamples.ContainsKey(loc))
                        {
                            Cmd c           = b.Cmds[numInstr];
                            var calleeName  = trace.getCalledProcName(c);
                            var calleeTrace = trace.calleeCounterexamples[loc].counterexample;
                            ReconstructImperativeTrace(calleeTrace, calleeName, origProg);
                            calleeTraces.Add(
                                new Duple <string, CalleeCounterexampleInfo>(
                                    calleeName,
                                    new CalleeCounterexampleInfo(calleeTrace,
                                                                 trace.calleeCounterexamples[loc].args)
                                    ));
                        }
                    }

                    // Check consistency and map calleeTraces to the actual call instructions
                    var currCount = 0;
                    for (int numInstr = 0; numInstr < ib.Cmds.Count; numInstr++)
                    {
                        Cmd c = ib.Cmds[numInstr];

                        if (!(c is CallCmd))
                        {
                            continue;
                        }

                        var cc = c as CallCmd;

                        // No more calls left to process
                        if (calleeTraces.Count <= currCount)
                        {
                            break;
                        }

                        if (cc.Proc.Name != calleeTraces[currCount].fst)
                        {
                            continue;
                        }

                        // Check if this proc has an implementation
                        //if (!origProg.ContainsKey(cc.Proc.Name))
                        //    continue;

                        // Check if the proc is inlined
                        //if (QKeyValue.FindExprAttribute(cc.Proc.Attributes, "inline") == null)
                        //    continue;

                        // Some thing wrong about the interprocedural trace returned by Boogie if the
                        // following don't match
                        // TODO: Fix when the failing assert is not the last statement of the block
                        //Debug.Assert(cc.Proc.Name == calleeTraces[currCount].fst);

                        newCalleeTraces.Add(new TraceLocation(newBlocks.Count - 1, numInstr), calleeTraces[currCount].snd);
                        currCount++;
                    }
                }
            }
            trace.Trace = newBlocks;
            // reset other info. Safe thing to do unless we know what it is
            trace.calleeCounterexamples = newCalleeTraces;
        }
Beispiel #8
0
        public static Counterexample ReconstructTrace(Counterexample trace, string currProc, TraceLocation currLocation, Dictionary <string, Tuple <Block, Implementation> > origProg)
        {
            // we cannot be starting in the last block
            Debug.Assert(currLocation.numBlock != trace.Trace.Count - 1);
            // we cannot be starting in the middle of a block
            Debug.Assert(currLocation.numInstr == 0);

            var newTrace        = new List <Block>();
            var newTraceCallees = new Dictionary <TraceLocation, CalleeCounterexampleInfo>();

            Block          currOrigBlock = null;
            Implementation currOrigImpl  = null;
            int            currOrigInstr = 0;

            while (true)
            {
                if (currLocation.numInstr == 0 && origProg.ContainsKey(trace.Trace[currLocation.numBlock].Label))
                {
                    var origPlace = origProg[trace.Trace[currLocation.numBlock].Label];
                    if (currOrigImpl != null && currOrigImpl.Name != origPlace.Item2.Name)
                    {
                        // change of proc

                        // First, recurse
                        var calleeTrace = ReconstructTrace(trace, origPlace.Item2.Name, currLocation, origProg);
                        // Find the call to this guy in currOrigBlock
                        while (currOrigInstr < currOrigBlock.Cmds.Count)
                        {
                            var cmd = currOrigBlock.Cmds[currOrigInstr] as CallCmd;
                            if (cmd != null && cmd.callee == origPlace.Item2.Name)
                            {
                                break;
                            }
                            currOrigInstr++;
                        }
                        Debug.Assert(currOrigInstr != currOrigBlock.Cmds.Count);
                        newTraceCallees.Add(new TraceLocation(newTrace.Count - 1, currOrigInstr), new CalleeCounterexampleInfo(calleeTrace, new List <object>()));
                        // we're done
                        break;
                    }

                    currOrigBlock = origPlace.Item1;
                    currOrigImpl  = origProg[trace.Trace[currLocation.numBlock].Label].Item2;
                    currOrigInstr = 0;

                    newTrace.Add(currOrigBlock);
                }

                if (trace.calleeCounterexamples.ContainsKey(currLocation))
                {
                    // find the corresponding call in origBlock
                    var calleeInfo = trace.calleeCounterexamples[currLocation];
                    var calleeName = trace.getCalledProcName(trace.Trace[currLocation.numBlock].Cmds[currLocation.numInstr]);
                    while (currOrigInstr < currOrigBlock.Cmds.Count)
                    {
                        var cmd = currOrigBlock.Cmds[currOrigInstr] as CallCmd;
                        if (cmd != null && cmd.callee == calleeName)
                        {
                            break;
                        }
                        currOrigInstr++;
                    }
                    Debug.Assert(currOrigInstr != currOrigBlock.Cmds.Count);
                    newTraceCallees.Add(new TraceLocation(newTrace.Count - 1, currOrigInstr), calleeInfo);
                }

                // increment location
                currLocation.numInstr++;
                if (currLocation.numInstr >= trace.Trace[currLocation.numBlock].Cmds.Count)
                {
                    currLocation.numBlock++;
                    currLocation.numInstr = 0;
                }
                if (currLocation.numBlock == trace.Trace.Count)
                {
                    break;
                }
            }

            var ret = new AssertCounterexample(newTrace, null, null, trace.Model, trace.MvInfo, trace.Context);

            ret.calleeCounterexamples = newTraceCallees;

            return(ret);
        }
Beispiel #9
0
        internal void AddOstTraces(CIContainer aContainer)
        {
            CITraceData traceData = aContainer.Traces;

            //
            if (traceData != null && traceData.Lines.Length > 0)
            {
                foreach (CITrace ciTrace in traceData)
                {
                    System.Text.StringBuilder line = new System.Text.StringBuilder();

                    TraceLine trace = ciTrace;

                    // Type
                    string type = string.Empty;
                    switch (trace.Type)
                    {
                    case TraceLine.TType.ETypeBinary:
                        type = "Bin";
                        break;

                    case TraceLine.TType.ETypeRaw:
                        type = "Raw";
                        break;

                    case TraceLine.TType.ETypeText:
                        type = "Text";
                        break;

                    default:
                        type = "Unknown";
                        break;
                    }
                    if (string.IsNullOrEmpty(type) == false)
                    {
                        line.Append(type);
                    }

                    // Context id
                    if (trace.ContextId != 0)
                    {
                        line.Append(" " + "0x" + trace.ContextId.ToString("x8"));
                    }

                    // Time stamp
                    line.Append(" " + trace.TimeStamp.ToString());

                    // Prefix
                    string prefix = trace.Prefix;
                    if (string.IsNullOrEmpty(prefix) == false)
                    {
                        line.Append(" " + prefix);
                    }

                    // Suffix
                    string suffix = trace.Suffix;
                    if (string.IsNullOrEmpty(suffix) == false)
                    {
                        line.Append(" " + suffix);
                    }

                    if (trace.HasIdentifier)
                    {
                        // Component/group/id triplet
                        TraceIdentifier identifier = trace.Identifier;
                        line.Append(" C:" + "0x" + identifier.Component.ToString("x8"));
                        line.Append(" G:" + identifier.Group.ToString());
                        line.Append(" I:" + identifier.Id.ToString());
                        // File & line
                        TraceLocation location = identifier.Location;
                        //
                        string file       = location.File;
                        string lineNumber = location.Line.ToString();
                        //
                        if (string.IsNullOrEmpty(file) == false && string.IsNullOrEmpty(lineNumber) == false)
                        {
                            line.Append(" " + file);
                            line.Append(":" + lineNumber);
                        }
                    }

                    // Payload
                    string payload = trace.Payload;
                    line.Append(" " + payload);
                    iOstTraces.Add(line.ToString());
                }
            }
        }
Beispiel #10
0
        protected override void XmlSerializeChildren(CrashXmlPlugin.FileFormat.Document.CXmlDocumentSerializationParameters aParameters)
        {
            System.Diagnostics.Debug.Assert(iTraceData != null);
            foreach (CITrace ciTrace in iTraceData)
            {
                aParameters.Writer.WriteStartElement(SegConstants.Traces_Line);
                //
                TraceLine trace = ciTrace;

                // Type
                string type = string.Empty;
                switch (trace.Type)
                {
                case TraceLine.TType.ETypeBinary:
                    type = SegConstants.Traces_Type_Binary;
                    break;

                case TraceLine.TType.ETypeRaw:
                    type = SegConstants.Traces_Type_Raw;
                    break;

                case TraceLine.TType.ETypeText:
                    type = SegConstants.Traces_Type_Text;
                    break;

                default:
                    type = SegConstants.Traces_Type_Unknown;
                    break;
                }
                if (string.IsNullOrEmpty(type) == false)
                {
                    aParameters.Writer.WriteAttributeString(SegConstants.CmnType, type);
                }

                // Context id
                if (trace.ContextId != 0)
                {
                    aParameters.Writer.WriteAttributeString(SegConstants.Traces_ContextId, "0x" + trace.ContextId.ToString("x8"));
                }

                // Time stamp
                aParameters.Writer.WriteAttributeString(SegConstants.Traces_TimeStamp, trace.TimeStamp.ToString());

                // Prefix
                string prefix = trace.Prefix;
                if (string.IsNullOrEmpty(prefix) == false)
                {
                    aParameters.Writer.WriteAttributeString(SegConstants.Traces_Prefix, prefix);
                }

                // Suffix
                string suffix = trace.Suffix;
                if (string.IsNullOrEmpty(suffix) == false)
                {
                    aParameters.Writer.WriteAttributeString(SegConstants.Traces_Suffix, suffix);
                }

                if (trace.HasIdentifier)
                {
                    // Component/group/id triplet
                    TraceIdentifier identifier = trace.Identifier;
                    aParameters.Writer.WriteAttributeString(SegConstants.Traces_ComponentId, "0x" + identifier.Component.ToString("x8"));
                    aParameters.Writer.WriteAttributeString(SegConstants.Traces_GroupId, identifier.Group.ToString());
                    aParameters.Writer.WriteAttributeString(SegConstants.Traces_InstanceId, identifier.Id.ToString());

                    // File & line
                    TraceLocation location = identifier.Location;
                    //
                    string file       = location.File;
                    string lineNumber = location.Line.ToString();
                    //
                    if (string.IsNullOrEmpty(file) == false && string.IsNullOrEmpty(lineNumber) == false)
                    {
                        aParameters.Writer.WriteAttributeString(SegConstants.Traces_File, file);
                        aParameters.Writer.WriteAttributeString(SegConstants.Traces_LineNumber, lineNumber);
                    }
                }

                // Payload
                string payload = trace.Payload;
                aParameters.Writer.WriteValue(payload);

                aParameters.Writer.WriteEndElement();
            }
        }