Beispiel #1
0
 public override void Add(T newVal)
 {
     Total += Datapoint.From <T>(newVal).Magnitude();
 }
    const float threshold  = 1f;  //Threshold for cluster similarity, you may want to use this and alter it if so

    //TODO; fix this function
    public Dictionary <Datapoint, List <Datapoint> > Cluster(Datapoint[] datapoints)
    {
        //This datastructure will hold the clusters as lists by their centers.
        Dictionary <Datapoint, List <Datapoint> > clustersByCenters = new Dictionary <Datapoint, List <Datapoint> > ();

        //Select K random centers to start
        List <Datapoint> centers = new List <Datapoint>();

        //Choose K random points to be centers
        while (centers.Count < K)
        {
            // Generate a random index less than the size of the array.
            int       randomIndex  = Random.Range(0, datapoints.Length);
            Datapoint randomCenter = datapoints[randomIndex];

            if (!centers.Contains(randomCenter))
            {
                centers.Add(randomCenter);
            }
        }

        List <Datapoint> oldCenters = new List <Datapoint>();
        int i   = 0;
        var set = new HashSet <Datapoint>(centers);

        while (!set.SetEquals(oldCenters) && i < MAX_ATTEMPTS)
        {
            i                 = i + 1;
            oldCenters        = new List <Datapoint>(centers);
            clustersByCenters = new Dictionary <Datapoint, List <Datapoint> >();

            //Instantiate clusters by these centers
            foreach (Datapoint center in centers)
            {
                clustersByCenters.Add(center, new List <Datapoint>());
            }

            //Map each datapoint to its closest center
            foreach (Datapoint pnt in datapoints)
            {
                Datapoint closestCenter = null;
                float     minDistance   = float.PositiveInfinity;

                foreach (Datapoint center in centers)
                {
                    float thisDistance = Distance(pnt, center);
                    if (thisDistance < minDistance)
                    {
                        closestCenter = center;
                        minDistance   = thisDistance;
                    }
                }

                clustersByCenters[closestCenter].Add(pnt);
            }

            centers = new List <Datapoint>();

            foreach (Datapoint center in oldCenters)
            {
                Datapoint newCenter = GetAverage(clustersByCenters[center].ToArray());
                centers.Add(newCenter);
            }
            set = new HashSet <Datapoint>(centers);
        }



        return(clustersByCenters);
    }
Beispiel #3
0
        /// <summary>
        /// Partitions the Visibility data into subgrids.
        ///
        /// In the original implementation, this is called "Plan"
        /// </summary>
        /// <param name="c"></param>
        /// <param name="uvw"></param>
        /// <param name="frequencies"></param>
        /// <returns></returns>
        public static List <List <ImageDomainGridder.Subgrid> > CreatePartition(GriddingConstants c, double[,,] uvw, double[] frequencies)
        {
            var imagesize = c.ScaleArcSec * c.GridSize;
            List <List <ImageDomainGridder.Subgrid> > outputGrids = new List <List <ImageDomainGridder.Subgrid> >(uvw.GetLength(0));

            for (int baseline = 0; baseline < uvw.GetLength(0); baseline++)
            {
                var baselineOutput = new List <ImageDomainGridder.Subgrid>(uvw.GetLength(1));
                outputGrids.Add(baselineOutput);
                //idg checks a-terms bins we ignore the a-term correction here, so we can simplify and only iterate over

                Datapoint[,] datapoints = new Datapoint[uvw.GetLength(1), frequencies.Length]; //timeSamplesCount  channelsCount
                int time = 0;
                for (time = 0; time < uvw.GetLength(1); time++)
                {
                    //convert visibilities
                    for (int channel = 0; channel < frequencies.Length; channel++)
                    {
                        var dp = new Datapoint
                        {
                            timestep = time,
                            channel  = channel,
                            uPixel   = MetersToPixels(uvw[baseline, time, 0], imagesize, frequencies[channel]),
                            vPixel   = MetersToPixels(uvw[baseline, time, 1], imagesize, frequencies[channel]),
                            wLambda  = MetersToLambda(uvw[baseline, time, 2], frequencies[channel])
                        };
                        datapoints[time, channel] = dp;
                    }
                }

                time = 0;
                Subgrid subgrid = new Subgrid(c);
                while (time < uvw.GetLength(1))
                {
                    subgrid.Reset();
                    int timeSamplePerSubgrid = 0;

                    //this is taken from the original IDG implementation. Here may be room for simplification
                    for (; time < uvw.GetLength(1); time++)
                    {
                        var dpChannel0   = datapoints[time, 0];
                        var dpChannelMax = datapoints[time, frequencies.Length - 1];
                        var hack         = dpChannelMax.Copy();
                        hack.wLambda = dpChannel0.wLambda;  // hack taken over from IDG reference implementation

                        if (subgrid.AddVisibility(dpChannel0) && subgrid.AddVisibility(hack))
                        {
                            timeSamplePerSubgrid++;
                            if (timeSamplePerSubgrid == c.MaxTimestepsPerSubgrid)
                            {
                                time++;
                                break;
                            }
                        }
                        else
                        {
                            break;
                        }
                    }

                    //Handle empty subgrids
                    if (timeSamplePerSubgrid == 0)
                    {
                        var dp = datapoints[time, 0];

                        if (Double.IsInfinity(dp.uPixel) && Double.IsInfinity(dp.vPixel))
                        {
                            throw new Exception("could not place (all) visibilities on subgrid (too many channnels, kernel size too large)");
                        }
                        else if (Double.IsInfinity(dp.uPixel) || Double.IsInfinity(dp.vPixel))
                        {
                            //added by me
                            throw new Exception("could not place (all) visibilities on subgrid (too many channnels, kernel size too large)");
                        }
                        else
                        {
                            // Advance to next timeslot when visibilities for current timeslot had infinite coordinates
                            time++;
                            continue;
                        }
                    }

                    subgrid.Finish();
                    if (subgrid.InRange())
                    {
                        //TODO: Fix hack and hand over data properly
                        var data = new ImageDomainGridder.Subgrid();
                        data.timeSampleCount = timeSamplePerSubgrid;
                        data.timeSampleStart = time - timeSamplePerSubgrid;
                        data.baselineIdx     = baseline;
                        data.UPixel          = subgrid.UPixel;
                        data.VPixel          = subgrid.VPixel;
                        data.WLambda         = subgrid.WIndex;

                        baselineOutput.Add(data);
                    }
                    else
                    {
                        subgrid.InRange();
                        throw new Exception("subgrid falls not within grid");
                    }
                }
            }//baseline

            return(outputGrids);
        }
Beispiel #4
0
        //internal static Bitmap ToBitmap<Tgraphical>(Datapoint<T>[] sequence) where Tgraphical : struct
        internal static Bitmap ToBitmap(T[] seq)
        {
            if (seq.Length == 0)
            {
                return(null);
            }
            var sequence = seq
                           .Select(s => Datapoint.From(s))
                           .ToArray();

            //List<Tgraphical> Displacements = new List<Tgraphical>(); // Tgraphical is a vector with one dimension per axis we wish to plot.
            //List<float> DistancesTraveled = new List<float>();

            //if (Datapoint<T>.Dimensions <= 2)
            //{
            //    Vector2 V = new Vector2(0, 0);
            //    Vector2 D = new Vector2(0, 0);
            //    // Note - this uses the special convert-to-Vector2 overload of Datapoint<T>.
            //    foreach (Vector2 pt in sequence)
            //    {
            //        //V.X += pt.X;
            //        //V.Y += pt.Y;
            //        //D.X += V.X;
            //        //D.Y += V.Y;
            //        V += pt;
            //        D += V;
            //        Displacements.Add(Operator.Convert<Vector2, Tgraphical>(D));
            //        DistancesTraveled.Add(D.Length());
            //    }
            //}
            //else if (Datapoint<T>.Dimensions >= 3)
            //{
            //    Vector3 V = new Vector3(0, 0, 0);
            //    Vector3 D = new Vector3(0, 0, 0);
            //    // Note - this uses the special convert-to-Vector3 overload of Datapoint<T>.
            //    foreach (Vector3 pt in sequence)
            //    {
            //        V += pt;
            //        D += V;
            //        Displacements.Add(Operator.Convert<Vector3, Tgraphical>(D));
            //        DistancesTraveled.Add(D.Length());
            //    }
            //}

            //// Trim off the first and last 10% *by distance traveled*
            //var TotalDistance = DistancesTraveled.Last();
            //Displacements = Displacements.Where((v, i) => DistancesTraveled[i] > TotalDistance * 0.1 && DistancesTraveled[i] < TotalDistance * 0.9).ToList();

            //int xmax = (int)Displacements.Max(x => x.X);
            //int xmin = (int)Displacements.Min(x => x.X);

            //int ymax = (int)Displacements.Max(x => x.Y);
            //int ymin = (int)Displacements.Min(x => x.Y);

            //int width = xmax - xmin;
            //int height = ymax - ymin;

            //float xmax = sequence.Max(x => x.X);
            //float xmin = sequence.Min(x => x.X);
            //float ymax = sequence.Max(x => x.Y);
            //float ymin = sequence.Min(x => x.Y);
            //// Tweak so that they share the same x-axis and scaling
            //xmax = ymax = Math.Max(xmax, ymax);
            //xmin = ymin = Math.Min(xmin, ymin);

            var   DisplayedDimensions = Enumerable.Range(0, Datapoint.From(default(T)).Dimensions);
            float maxCoord            = float.NegativeInfinity;
            float minCoord            = float.PositiveInfinity;

            foreach (int i in DisplayedDimensions)
            {
                minCoord = Math.Min(minCoord, sequence.Min(v => v.AsArray()[i]));
                maxCoord = Math.Max(maxCoord, sequence.Max(v => v.AsArray()[i]));
            }

            //float width = xmax - xmin;
            //float height = ymax - ymin;

            var    bmp    = Bitmap.CreateBitmap(bmpSize, bmpSize, Bitmap.Config.Argb8888);
            Canvas canvas = new Canvas(bmp);
            Paint  paintX = new Paint();

            paintX.StrokeCap = Paint.Cap.Round;
            Paint paintY = new Paint();

            paintY.StrokeCap = Paint.Cap.Round;

            List <Paint> paints = new List <Paint>();

            #region Paint spectrum functions (mostly just makes things pretty)
            List <Action <int, Paint> > getColorFuncs = new List <Action <int, Paint> > // Colour spectra which can easily be told apart onscreen
            {
                (p, paint) => paint.SetARGB(255, 255 - p / 3, 0, p / 3),
                (p, paint) => paint.SetARGB(255, p / 3, 255 - p / 3, p / 3),
                (p, paint) => paint.SetARGB(255, 255 - p / 3, p / 3, 0),
                (p, paint) => paint.SetARGB(255, p / 3, p / 3, 255 - p / 3),
                (p, paint) => paint.SetARGB(255, p / 3, 255 - p / 3, 177 - p / 6),
                (p, paint) => paint.SetARGB(255, 255 - p / 3, 177 - p / 6, 50 + p / 2)
            };
            // If even that isn't enough, create new ones until we have enough such paint functions.
            //while (Datapoint<Tgraphical>.Dimensions > getColorFuncs.Count)
            while (DisplayedDimensions.Count() > getColorFuncs.Count)
            {
                List <Func <int, int> > converters = new List <Func <int, int> >()
                {
                    p => 0,
                    p => 128,
                    p => 255,
                    p => p,
                    p => p / 2,
                    p => p / 3,
                    p => 255 - p,
                    p => 255 - p / 2,
                    p => 255 - p / 3,
                    p => 50 + p / 2,
                    p => 200 - p / 2,
                    p => 100 + p / 2,
                    p => 150 - p / 2,
                    p => Math.Abs(p * 2 - 128).Clamp(0, 255),
                    p => Math.Abs(128 - p * 2).Clamp(0, 255)
                };
                var f1 = converters.GetRandom();
                var f2 = converters.GetRandom();
                var f3 = converters.GetRandom();
                getColorFuncs.Add((p, paint) => paint.SetARGB(255, f1(p), f2(p), f3(p)));
            }
            #endregion

            foreach (int i in DisplayedDimensions)
            {
                var newPaint = new Paint
                {
                    StrokeCap   = Paint.Cap.Round,
                    StrokeWidth = 1.5f
                };
                paints.Add(newPaint);
            }

            Paint paintAxis = new Paint();
            paintAxis.SetARGB(127, 127, 127, 127);
            var zeroLine = 0f.Scale(minCoord, maxCoord, 0, bmpSize);
            canvas.DrawLine(0, zeroLine, bmpSize, zeroLine, paintAxis);

            int   prev_x = 0.Scale(0, sequence.Length - 1, 0, bmpSize); // ??? Not sure why I'm not just saying "zero" here.
            int[] prev_ys = sequence[0].AsArray().Select(d => d.Scale(minCoord, maxCoord, 0, bmpSize)).ToArray();
            int   x, i255;
            int[] ys;

            for (int i = 1; i < sequence.Length; i++)
            {
                ////int x = (int)Displacements[i].X - xmin;
                ////int y = (int)Displacements[i].Y - ymin;
                //int x = i.Scale(0, sequence.Length - 1, 0, 128);
                //int yX = sequence[i].X.Scale(xmin, xmax, 0, 128);
                //int yY = sequence[i].Y.Scale(ymin, ymax, 0, 128);
                x  = i.Scale(1, sequence.Length, 0, bmpSize);
                ys = sequence[i].AsArray().Select(d => d.Scale(minCoord, maxCoord, 0, bmpSize)).ToArray();

                i255 = i.Scale(0, sequence.Length, 0, 255);

                ////int prevX = (int)Displacements[i - 1].X - xmin;
                ////int prevY = (int)Displacements[i - 1].Y - ymin;
                //int prev_X = (i-1).Scale(0, sequence.Length - 1, 0, 128);
                //int prev_yX = sequence[i-1].X.Scale(xmin, xmax, 0, 128);
                //int prev_yY = sequence[i-1].Y.Scale(ymin, ymax, 0, 128);

                //paintX.SetARGB(255, 255 - p, 0, p);
                //paintY.SetARGB(255, p/2, 255 - p, p);
                //canvas.DrawLine(prev_X, prev_yX, x, yX, paintX);
                //canvas.DrawLine(prev_X, prev_yY, x, yY, paintY);

                foreach (int j in DisplayedDimensions)
                {
                    getColorFuncs[j].Invoke(i255, paints[j]);
                    canvas.DrawLine(prev_x, prev_ys[j], x, ys[j], paints[j]);
                }

                prev_x  = x;
                prev_ys = ys;
            }

            return(bmp);
            // Note - use myImageView.setImageBitmap(bmp) to display.
        }
        public void ReportWatsonEvents(UserContext userContext, IList <ClientLogEvent> watsonEvents, Datapoint contextHeader, Datapoint[] context)
        {
            Stopwatch stopwatch = Stopwatch.StartNew();
            int       num       = 0;
            int       num2      = 0;
            List <ClientWatsonDatapointHandler.ClientWatsonReportLogEvent> list = new List <ClientWatsonDatapointHandler.ClientWatsonReportLogEvent>(watsonEvents.Count);
            List <WatsonClientReport> list2 = new List <WatsonClientReport>(watsonEvents.Count);

            foreach (ClientLogEvent clientLogEvent in watsonEvents)
            {
                string ctqName;
                clientLogEvent.TryGetValue <string>("ctq", out ctqName);
                ClientWatsonReportData reportData;
                ProcessingResult       errorResult = this.TryExtractClientWatsonData(clientLogEvent, out reportData);
                if (errorResult.Code != ResultCode.Success)
                {
                    list.Add(new ClientWatsonDatapointHandler.ClientWatsonReportLogEvent(clientLogEvent.Time, userContext, ctqName, reportData.IsUnhandledException, errorResult));
                    num2++;
                }
                else
                {
                    int  hashCode = reportData.OriginalCallStack.GetHashCode();
                    bool flag     = this.parameters.IsErrorOverReportQuota(hashCode);
                    if (flag)
                    {
                        string[] watsonParameters;
                        if (ClientWatsonDatapointHandler.cachedFlavor == null)
                        {
                            ClientWatsonDatapointHandler.CreateClientWatsonReportAndUpdateCache(reportData, out watsonParameters);
                        }
                        else
                        {
                            watsonParameters = WatsonClientReport.BuildWatsonParameters(ClientWatsonDatapointHandler.cachedFlavor, ClientWatsonDatapointHandler.cachedVersion, reportData.TraceComponent, reportData.FunctionName, reportData.ExceptionType, reportData.NormalizedCallStack, reportData.CallStackHash);
                        }
                        list.Add(new ClientWatsonDatapointHandler.ClientWatsonReportLogEvent(clientLogEvent.Time, userContext, ctqName, watsonParameters, reportData.IsUnhandledException, false));
                        num++;
                    }
                    else
                    {
                        string[]           watsonParameters;
                        WatsonClientReport item = ClientWatsonDatapointHandler.CreateClientWatsonReportAndUpdateCache(reportData, out watsonParameters);
                        list2.Add(item);
                        list.Add(new ClientWatsonDatapointHandler.ClientWatsonReportLogEvent(clientLogEvent.Time, userContext, ctqName, watsonParameters, reportData.IsUnhandledException, true));
                    }
                }
            }
            string extraData = ClientWatsonDatapointHandler.BuildExtraDataString(userContext, contextHeader, context, list);

            foreach (WatsonClientReport report in list2)
            {
                this.parameters.ReportAction(report, extraData);
            }
            this.logger.Set(LogDatapointMetadata.WatsonDatapointSkipped, num);
            this.logger.Set(LogDatapointMetadata.WatsonDatapointFailed, num2);
            this.logger.Set(LogDatapointMetadata.WatsonReportingElapsed, stopwatch.ElapsedMilliseconds);
        }
    // Start is called before the first frame update
    void Start()
    {
        dayData             = gameObject.GetComponentInParent <MonthData>().GetDayData(day);
        firstDatapointOfDay = dayData[0];

        TextMeshProUGUI[] textMeshes = gameObject.GetComponentsInChildren <TextMeshProUGUI>();
        foreach (TextMeshProUGUI textMesh in textMeshes)
        {
            if (textMesh.name == "TempText")
            {
                tempText = textMesh;
            }
            else if (textMesh.name == "FosfaatText")
            {
                fosfaatText = textMesh;
            }
            else
            {
                neerslagText = textMesh;
            }
        }
        MeshRenderer[] meshRenderers = gameObject.GetComponentsInChildren <MeshRenderer>();
        foreach (MeshRenderer meshRenderer in meshRenderers)
        {
            if (meshRenderer.name == "Temp")
            {
                tempMesh = meshRenderer;
                if (firstDatapointOfDay.T < 0)
                {
                    actualTempColor = tempBinColors[4];;
                }
                else if (firstDatapointOfDay.T < 100)
                {
                    actualTempColor = tempBinColors[3];
                }
                else if (firstDatapointOfDay.T < 200)
                {
                    actualTempColor = tempBinColors[2];
                }
                else if (firstDatapointOfDay.T < 300)
                {
                    actualTempColor = tempBinColors[1];
                }
                else
                {
                    actualTempColor = tempBinColors[0];
                }
                tempMesh.material.color = actualTempColor;
            }
            else if (meshRenderer.name == "Fosfaat")
            {
                fosfaatMesh = meshRenderer;
                if (firstDatapointOfDay.fosfaatMetingAT1 < 0.5)
                {
                    actualFosfaatColor = fosfaatBinColors[0];;
                }
                else if (firstDatapointOfDay.fosfaatMetingAT1 < 1)
                {
                    actualFosfaatColor = fosfaatBinColors[1];
                }
                else if (firstDatapointOfDay.fosfaatMetingAT1 < 1.5)
                {
                    actualFosfaatColor = fosfaatBinColors[2];
                }
                else if (firstDatapointOfDay.fosfaatMetingAT1 < 2)
                {
                    actualFosfaatColor = fosfaatBinColors[3];
                }
                else if (firstDatapointOfDay.fosfaatMetingAT1 < 2.5)
                {
                    actualFosfaatColor = fosfaatBinColors[4];
                }
                else if (firstDatapointOfDay.fosfaatMetingAT1 < 3)
                {
                    actualFosfaatColor = fosfaatBinColors[5];
                }
                else
                {
                    actualNeerslagColor = fosfaatBinColors[6];
                }

                fosfaatMesh.material.color = actualFosfaatColor;
            }
            else if (meshRenderer.name == "Neerslag")
            {
                neerslagMesh = meshRenderer;
                if (firstDatapointOfDay.DR < 2)
                {
                    actualNeerslagColor = neerslagBinColors[0];;
                }
                else if (firstDatapointOfDay.DR < 4)
                {
                    Debug.Log(firstDatapointOfDay.DR);
                    actualNeerslagColor = Color.white;
                    actualNeerslagColor = neerslagBinColors[1];
                }
                else if (firstDatapointOfDay.DR < 6)
                {
                    actualNeerslagColor = neerslagBinColors[2];
                }
                else if (firstDatapointOfDay.DR < 8)
                {
                    actualNeerslagColor = neerslagBinColors[3];
                }
                else
                {
                    actualNeerslagColor = neerslagBinColors[4];
                }
                neerslagMesh.material.color = actualNeerslagColor;
            }
            else
            {
            }
        }

        tempText.color = Color.white;
        tempText.SetText((firstDatapointOfDay.T / 10) + " Celcius");
        fosfaatText.SetText(firstDatapointOfDay.fosfaatMetingAT1.ToString("0.00") + " mg/l");
        neerslagText.SetText((firstDatapointOfDay.DR / 10) + " mm");
    }
Beispiel #7
0
    public void  VisGraph(int sliderData)
    {
        for (int i = sliderData; i < sliderData + maxRange; i++)
        {
            startTimeSec = (int)(sliderData * 0.03f);
            endTimeSec   = (int)((sliderData + maxRange) * 0.03f);

            dataStartTimeInSeconds.text = startTimeSec.ToString();
            dataEndTimeInSeconds.text   = endTimeSec.ToString();

            xval = float.Parse(data[i]["xval"].ToString());
            yval = float.Parse(data[i]["yval"].ToString());
            nspk = float.Parse(data[i]["nspk"].ToString());

            if (nspk == 1)
            {
                ntime = float.Parse(data [i] ["ntime"].ToString());
            }
            if (nspk == 2)
            {
                ntime  = float.Parse(data [i] ["ntime"].ToString());
                ntime2 = float.Parse(data [i] ["ntime2"].ToString());
            }
            if (nspk == 3)
            {
                ntime  = float.Parse(data [i] ["ntime"].ToString());
                ntime2 = float.Parse(data [i] ["ntime2"].ToString());
                ntime3 = float.Parse(data [i] ["ntime3"].ToString());
            }

            xval = xval * condensevalue;
            yval = yval * condensevalue;

            Vector3 vect3xy = new Vector3(xval, 0, yval);
            Datapoint.setDataPointColor();
            Instantiate(staticPointPrefab, vect3xy, Quaternion.identity);


            if (nspk == 1)
            {
                noOfSpikes++;
                lowSpikes++;
                timeSec = ntime / 10000;
                timeOfSpikeLow.Add(timeSec);
                nspikeVal = nspk * nspikeCondenseValue;
                Vector3 vect3intensity = new Vector3(xval, nspikeVal, yval);
                Spike.setColor(0.1f);
                Instantiate(pointOneSpkiePrefab, vect3intensity, Quaternion.identity);
                CreateSpike(xval, yval, nspikeVal);
            }
            if (nspk == 2)
            {
                noOfSpikes += 2;
                mediumSpikes++;
                timeOfSpikeMedium.Add(((ntime + ntime2) / 2) / 10000);
                nspikeVal = nspk * nspikeCondenseValue;
                Vector3 vect3intensity = new Vector3(xval, nspikeVal, yval);
                Spike.setColor(0.1f);
                Instantiate(pointTwoSpkiePrefab, vect3intensity, Quaternion.identity);
                CreateSpike(xval, yval, nspikeVal);
            }

            if (nspk == 3)
            {
                noOfSpikes += 3;
                highSpikes++;
                timeOfSpikeHigh.Add(((ntime + ntime2 + ntime3) / 3) / 10000);
                nspikeVal = nspk * nspikeCondenseValue;
                Vector3 vect3intensity = new Vector3(xval, nspikeVal, yval);
                Spike.setColor(0.1f);
                Instantiate(pointThreeSpkiePrefab, vect3intensity, Quaternion.identity);
                CreateSpike(xval, yval, nspikeVal);
            }
        }

        string timesLow    = CreateStringOfTime(timeOfSpikeLow);
        string timesMedium = CreateStringOfTime(timeOfSpikeMedium);
        string timesHigh   = CreateStringOfTime(timeOfSpikeHigh);

        int tillRange = sliderData + maxRange - 1;

        showRange(sliderData, tillRange, noOfSpikes, lowSpikes, highSpikes, mediumSpikes, timesLow, timesMedium, timesHigh);

        DestroyTimeList(timeOfSpikeLow);
        DestroyTimeList(timeOfSpikeMedium);
        DestroyTimeList(timeOfSpikeHigh);
        noOfSpikes   = 0;
        lowSpikes    = 0;
        mediumSpikes = 0;
        highSpikes   = 0;
    }
Beispiel #8
0
        static void Main(string[] args)
        {
            AccessPort accessPort = null;

            try
            {
                Logger.SetConsoleChannel();
                Logger.SetLevels(Logger.Level.Information);

                accessPort = new AccessPort();
                accessPort.TelegramEvent     += new AccessPort.TelegramEventHandler(ShowTelegram);
                accessPort.NotificationEvent += new AccessPort.NotificationEventHandler(ShowNotification);

                // IP
                if (usingIP)
                {
                    accessPort.OpenIp("192.168.1.204");
                }

                // USB (first available USB port)
                if (usingUSB)
                {
                    accessPort.EnumerateUsb();
                    accessPort.OpenUsb(0);
                }

                // Tiny Serial
                if (usingTinySerial)
                {
                    accessPort.OpenTinySerial("COM14");
                }

                // show the KNX packets to/from the bus
                //accessPort.ConnectPacketTrace();

                // DPT-1 (1 bit)
                byte dataByte = Datapoint.Encode_DPT1(true);
                int  bits     = (int)Datapoint.Bits.DPT1;
                accessPort.GroupValueWrite((int)GA.DPT1, dataByte, bits);

                // DPT-2: 1 bit controlled
                dataByte = Datapoint.Encode_DPT2(true, true);
                bits     = (int)Datapoint.Bits.DPT2;
                accessPort.GroupValueWrite((int)GA.DPT2, dataByte, bits);

                // DPT-3: 3 bit controlled
                dataByte = Datapoint.Encode_DPT3(true, 0x05);
                bits     = (int)Datapoint.Bits.DPT3;
                accessPort.GroupValueWrite((int)GA.DPT3, dataByte, bits);

                // DPT-4: Character
                byte[] data = Datapoint.Encode_DPT4((byte)'A');
                accessPort.GroupValueWrite((int)GA.DPT4, data);

                // DPT-5: 8 bit unsigned value
                data = Datapoint.Encode_DPT5(0xAA);
                accessPort.GroupValueWrite((int)GA.DPT5, data);

                // DPT-6: 8 bit signed value
                data = Datapoint.Encode_DPT6(-10);
                accessPort.GroupValueWrite((int)GA.DPT6, data);

                // DPT-7: 2 byte unsigned value
                data = Datapoint.Encode_DPT7(0xAFFE);
                accessPort.GroupValueWrite((int)GA.DPT7, data);

                // DPT-8: 2 byte signed value
                data = Datapoint.Encode_DPT8(-30000);
                accessPort.GroupValueWrite((int)GA.DPT8, data);

                // DPT-9: 2 byte float value
                data = Datapoint.Encode_DPT9(12.25f);
                accessPort.GroupValueWrite((int)GA.DPT9, data);

                // DPT-10: local time
                data = Datapoint.Encode_DPT10_Local();
                accessPort.GroupValueWrite((int)GA.DPT10_LOCAL, data);

                // DPT-10: UTC time
                data = Datapoint.Encode_DPT10_UTC();
                accessPort.GroupValueWrite((int)GA.DPT10_UTC, data);

                // DPT-10: time
                data = Datapoint.Encode_DPT10(1, 11, 11, 11);
                accessPort.GroupValueWrite((int)GA.DPT10, data);

                // DPT-11: local date
                data = Datapoint.Encode_DPT11_Local();
                accessPort.GroupValueWrite((int)GA.DPT11_LOCAL, data);

                // DPT-11: UTC date
                data = Datapoint.Encode_DPT11_UTC();
                accessPort.GroupValueWrite((int)GA.DPT11_UTC, data);

                // DPT-11: date
                data = Datapoint.Encode_DPT11(2012, 3, 12);
                accessPort.GroupValueWrite((int)GA.DPT11, data);

                // DPT-12: 4 byte unsigned value
                data = Datapoint.Encode_DPT12(0xDEADBEEF);
                accessPort.GroupValueWrite((int)GA.DPT12, data);

                // DPT-13: 4 byte signed value
                data = Datapoint.Encode_DPT13(-30000);
                accessPort.GroupValueWrite((int)GA.DPT13, data);

                // DPT-14: 4 byte float value
                data = Datapoint.Encode_DPT14(2025.12345f);
                accessPort.GroupValueWrite((int)GA.DPT14, data);

                // DPT-15: Entrance access
                data = Datapoint.Encode_DPT15(1234, false, true, true, false, 10);
                accessPort.GroupValueWrite((int)GA.DPT15, data);

                // DPT-16: Character string, 14 bytes
                data = Datapoint.Encode_DPT16("Weinzierl Eng ");
                accessPort.GroupValueWrite((int)GA.DPT16, data);

                // Read the value of a Group Object
                ReadGroupObject(accessPort, 0x902);

                // trace receive telegrams (in event handler)
                Logger.Log(Logger.Level.Information, "Press any key to close");
                Console.ReadKey(true);

                accessPort.Close();
            }
            catch (kdrive.KdriveException exception)
            {
                Console.WriteLine(exception.Message);
            }
            finally
            {
                if (accessPort != null)
                {
                    accessPort.Dispose();
                }
                Logger.Shutdown();
            }
        }
Beispiel #9
0
 public ItemDetailViewModel(Datapoint datapoint = null)
 {
     Title     = datapoint?.Category;
     Datapoint = datapoint;
 }
        public void DataPointConversion()
        {
            var data = new Datapoint("test", 0, 1451338593);

            Assert.Equal(1451338593, data.UnixTimestamp);
        }
Beispiel #11
0
        static void OnGroupData(byte[] buffer)
        {
            int address = AccessPort.GetDestAddress(buffer);

            byte[] data         = AccessPort.GetGroupData(buffer);
            GA     groupAddress = (GA)address;
            String value        = "";

            switch (groupAddress)
            {
            case GA.DPT1:
                value = String.Format("[1 Bit] {0}", Datapoint.Decode_DPT1(data));
                break;

            case GA.DPT2:
                bool dpt2_c = false;
                bool dpt2_v = false;
                Datapoint.Decode_DPT2(data, ref dpt2_c, ref dpt2_v);
                value = String.Format("[1 Bit Controlled] Control: {0} Value: {1}", dpt2_c, dpt2_v);
                break;

            case GA.DPT3:
                bool dpt3_c = false;
                byte dpt3_v = 0;
                Datapoint.Decode_DPT3(data, ref dpt3_c, ref dpt3_v);
                value = String.Format("[3 Bit Controlled] Control: {0} Value: {1}", dpt3_c, dpt3_v);
                break;

            case GA.DPT4:
                value = String.Format("[character] {0}", Datapoint.Decode_DPT4(data));
                break;

            case GA.DPT5:
                value = String.Format("[8 bit unsigned] {0}", Datapoint.Decode_DPT5(data));
                break;

            case GA.DPT6:
                value = String.Format("[8 bit signed] {0}", Datapoint.Decode_DPT6(data));
                break;

            case GA.DPT7:
                value = String.Format("[2 byte unsigned] {0}", Datapoint.Decode_DPT7(data));
                break;

            case GA.DPT8:
                value = String.Format("[2 byte signed] {0}", Datapoint.Decode_DPT8(data));
                break;

            case GA.DPT9:
                value = String.Format("[float] {0}", Datapoint.Decode_DPT9(data));
                break;

            case GA.DPT10_LOCAL:
            case GA.DPT10_UTC:
            case GA.DPT10:
                int day    = 0;
                int hour   = 0;
                int minute = 0;
                int second = 0;
                Datapoint.Decode_DPT10(data, ref day, ref hour, ref minute, ref second);
                value = String.Format("[time] {0} {1} {2} {3}", day, hour, minute, second);
                break;

            case GA.DPT11:
                int year  = 0;
                int month = 0;
                int d     = 0;
                Datapoint.Decode_DPT11(data, ref year, ref month, ref d);
                value = String.Format("[date] {0} {1} {2}", year, month, d);
                break;

            case GA.DPT12:
                value = String.Format("[4 byte unsigned] {0}", Datapoint.Decode_DPT12(data));
                break;

            case GA.DPT13:
                value = String.Format("[4 byte signed] {0}", Datapoint.Decode_DPT13(data));
                break;

            case GA.DPT14:
                value = String.Format("[4 byte float] {0}", Datapoint.Decode_DPT14(data));
                break;

            case GA.DPT15:
                int  accessCode = 0;
                bool error      = false;
                bool permission = false;
                bool direction  = false;
                bool encrypted  = false;
                int  index      = 0;
                Datapoint.Decode_DPT15(data, ref accessCode, ref error, ref permission,
                                       ref direction, ref encrypted, ref index);
                value = String.Format("[entrance access] {0} {1} {2} {3} {4} {5}",
                                      accessCode, error, permission,
                                      direction, encrypted, index);
                break;

            case GA.DPT16:
                value = String.Format("[character string] {0}", Datapoint.Decode_DPT16(data));
                break;

            default:
                Logger.Log(Logger.Level.Information, String.Format("Group Value for address: {0:x4}", address));
                Logger.Dump(Logger.Level.Information, "Value of GroupObject", data);
                break;
            }

            if (value != "")
            {
                String message = String.Format("{0} {1}", groupAddress, value);
                Logger.Log(Logger.Level.Information, message);
            }
        }
        protected override void Seed(DeviceContext context)
        {
            ControllerType ct1 = new ControllerType()
            {
                Category         = 1,
                HardwareIndex    = 10,
                SoftwareIndexMin = 0,
                SoftwareIndexMax = 20
            };

            ControllerType ct2 = new ControllerType()
            {
                Category         = 2,
                HardwareIndex    = 10,
                SoftwareIndexMin = 20,
                SoftwareIndexMax = 30
            };

            context.ControllerTypes.AddOrUpdate(x => x.Id, ct1);
            context.ControllerTypes.AddOrUpdate(x => x.Id, ct2);

            Gateway gateway = new Gateway()
            {
                Address = "Some address",
                Name    = "GatewayName",
                Serial  = "433338771000"
            };

            context.Gateways.AddOrUpdate(x => x.GatewayId, gateway);

            Controller controller1 = new Controller()
            {
                Gateway        = gateway,
                Serial         = "9998877",
                ControllerType = ct1,
                Status         = ControllerStatus.Operating
            };

            context.Controllers.AddOrUpdate(x => x.ControllerKey, controller1);

            Controller controller2 = new Controller()
            {
                Gateway        = gateway,
                ControllerType = ct2,
                Status         = ControllerStatus.Invalid,
                Serial         = "999113"
            };

            context.Controllers.AddOrUpdate(x => x.ControllerKey, controller2);

            Datapoint dp1 = new Datapoint()
            {
                Name       = "temp_outside",
                HexAddress = "2300"
            };

            context.Datapoints.AddOrUpdate(x => x.Id, dp1);

            Datapoint dp2 = new Datapoint()
            {
                Name       = "temp_inside",
                HexAddress = "2330"
            };

            context.Datapoints.AddOrUpdate(x => x.Id, dp2);

            Datapoint dp3 = new Datapoint()
            {
                Name       = "set_program",
                HexAddress = "4020"
            };

            context.Datapoints.AddOrUpdate(x => x.Id, dp3);

            ct1.Datapoints.Add(dp1);
            ct1.Datapoints.Add(dp2);

            ct2.Datapoints.Add(dp1);
            ct2.Datapoints.Add(dp3);

            context.SaveChanges();
        }
Beispiel #13
0
        // Token: 0x06002543 RID: 9539 RVA: 0x000869C8 File Offset: 0x00084BC8
        internal static void LogHttpContextData(HttpContext httpContext, RequestDetailsLogger logger)
        {
            if (OwaServerLogger.instance == null || !OwaServerLogger.instance.Configuration.IsLoggingEnabled)
            {
                return;
            }
            if (logger.Get(ExtensibleLoggerMetadata.EventId) == null)
            {
                if (!logger.ActivityScope.Statistics.Any <KeyValuePair <OperationKey, OperationStatistics> >())
                {
                    return;
                }
                OwaServerLogger.SetEventId(httpContext, logger);
            }
            logger.Set(OwaServerLogger.LoggerData.ContentLength, httpContext.Request.ContentLength);
            logger.Set(ServiceLatencyMetadata.HttpPipelineLatency, httpContext.Items[ServiceLatencyMetadata.HttpPipelineLatency]);
            NameValueCollection headers = httpContext.Request.Headers;
            string value = headers["X-OWA-ActionId"];

            if (!string.IsNullOrEmpty(value))
            {
                logger.Set(OwaServerLogger.LoggerData.ClientActionId, value);
            }
            string value2 = headers["X-OWA-ActionName"];

            if (!string.IsNullOrEmpty(value2))
            {
                logger.Set(OwaServerLogger.LoggerData.ClientActionName, value2);
            }
            string value3 = headers["X-EXT-ClientName"];

            if (!string.IsNullOrEmpty(value3))
            {
                logger.Set(OwaServerLogger.LoggerData.ExternalClientName, value3);
            }
            string value4 = headers["X-EXT-CorrelationId"];

            if (!string.IsNullOrEmpty(value4))
            {
                logger.Set(OwaServerLogger.LoggerData.ExternalCorrelationId, value4);
            }
            string sourceCafeServer = CafeHelper.GetSourceCafeServer(httpContext.Request);

            if (!string.IsNullOrEmpty(sourceCafeServer))
            {
                logger.Set(OwaServerLogger.LoggerData.FrontEndServer, sourceCafeServer);
            }
            string value5 = headers["X-OWA-OfflineRejectCode"];

            if (!string.IsNullOrEmpty(value5))
            {
                logger.Set(OwaServerLogger.LoggerData.OfflineRejectCode, value5);
            }
            string text = headers["logonLatency"];
            bool   flag = UserContextUtilities.IsDifferentMailbox(httpContext);

            if (!string.IsNullOrEmpty(text) || flag)
            {
                IMailboxContext mailboxContext = UserContextManager.GetMailboxContext(httpContext, null, false);
                if (!string.IsNullOrEmpty(text))
                {
                    logger.Set(OwaServerLogger.LoggerData.LogonLatencyName, text);
                    string userContext = string.Empty;
                    if (mailboxContext != null)
                    {
                        userContext = mailboxContext.Key.UserContextId.ToString(CultureInfo.InvariantCulture);
                    }
                    string[] keys = new string[]
                    {
                        "LGN.L"
                    };
                    string[] values = new string[]
                    {
                        text
                    };
                    Datapoint      datapoint = new Datapoint(DatapointConsumer.Analytics, "LogonLatency", DateTime.UtcNow.ToString("o"), keys, values);
                    ClientLogEvent logEvent  = new ClientLogEvent(datapoint, userContext);
                    OwaClientLogger.AppendToLog(logEvent);
                }
                if (flag && mailboxContext is SharedContext && httpContext.Items.Contains("CallContext"))
                {
                    CallContext callContext = httpContext.Items["CallContext"] as CallContext;
                    logger.Set(OwaServerLogger.LoggerData.User, callContext.GetEffectiveAccessingSmtpAddress());
                }
            }
            string value6 = httpContext.Items["BackEndAuthenticator"] as string;

            if (!string.IsNullOrEmpty(value6))
            {
                logger.Set(OwaServerLogger.LoggerData.BackendAuthenticator, value6);
            }
            object obj = httpContext.Items["TotalBERehydrationModuleLatency"];

            if (obj != null)
            {
                logger.Set(OwaServerLogger.LoggerData.RehydrationModuleLatency, obj);
            }
            string value7 = headers["X-OWA-Test-PassThruProxy"];

            if (!string.IsNullOrEmpty(value7))
            {
                logger.Set(OwaServerLogger.LoggerData.PassThroughProxy, value7);
            }
            string value8 = headers["X-SuiteServiceProxyOrigin"];

            if (!string.IsNullOrEmpty(value8))
            {
                logger.Set(OwaServerLogger.LoggerData.SuiteServiceProxyOrigin, value8);
            }
            HttpCookie httpCookie = httpContext.Request.Cookies["ClientId"];

            if (httpCookie != null)
            {
                logger.Set(OwaServerLogger.LoggerData.ClientId, httpCookie.Value);
            }
        }
    // Update is called once per frame
    void Update()
    {
        OpenMenu = camera.GetComponent <CameraControl>().OpenMenu;
        if (!OpenMenu)
        {
            if (frames != 0)
            {
                Instruction.GetComponent <TextMeshPro>().text = "";
                done    = false;
                frames -= 1;
            }
            if (frames == 0)
            {
                if (testFlag == 0)
                {
                    target = (int)Random.Range(0, n);
                    Instruction.GetComponent <TextMeshPro>().text = $"FIND THE {colors[target].ToUpper()} AGENT";
                    nClicks  = 0;
                    clicks   = new List <int>();
                    testFlag = 1;
                    trial++;
                }
                if (testFlag == 2)
                {
                    if (clicked)
                    {
                        Datapoint point = new Datapoint();

                        string click_data = "";
                        foreach (var click in clicks)
                        {
                            click_data += click + ",";
                        }
                        click_data = click_data.Substring(0, click_data.Length - 1);

                        string agent_data = "";
                        foreach (var iteragent in agents)
                        {
                            agent_data += iteragent.transform.position.x + "," + iteragent.transform.position.z + ",";
                        }
                        agent_data = agent_data.Substring(0, agent_data.Length - 1);

                        point.experimentID = PlayerPrefs.GetString("ExperimentID").Trim();
                        point.experimentID = point.experimentID.Substring(0, point.experimentID.Length - 1);
                        point.clicks       = click_data;
                        point.question     = trial.ToString().Trim();
                        point.key          = PlayerPrefs.GetString("Key").Trim();
                        point.type         = ((trial > prac) ? "1" : "0");
                        point.worker       = PlayerPrefs.GetString("Worker").Trim();
                        point.pos          = (player.transform.position.x + "," + player.transform.position.y);
                        point.agents       = agent_data;
                        point.testpoint    = false;

                        UnityWebRequest www = UnityWebRequest.Put("https://searchbwh.herokuapp.com/data/submit", JsonUtility.ToJson(point));

                        www.SetRequestHeader("Content-type", "application/json");
                        UnityWebRequestAsyncOperation request = www.SendWebRequest();

                        frames   = 30 * Random.Range(MinTime, MaxTime);
                        testFlag = 0;
                        clicked  = false;
                        if (trial == trials)
                        {
                            testFlag = 4;
                            writer.Close();
                        }
                    }
                    else
                    {
                        if (trial != trials)
                        {
                            Instruction.GetComponent <TextMeshPro>().text = $"Trial {trial}/{trials} complete in {nClicks} " + ((nClicks > 1) ? "clicks" : "click") + "! Right Click to Continue...";
                            if (Input.GetMouseButton(1))
                            {
                                clicked = true;
                            }
                        }
                        else
                        {
                            Instruction.GetComponent <TextMeshPro>().text = $"Trial {trial}/{trials} complete in {nClicks} " + ((nClicks > 1) ? "clicks" : "click") + "! Thank you for completing the 3D MOA Experiment, you may now quit.";
                        }
                        done = true;
                    }
                }
            }
        }
    }
Beispiel #15
0
 public override void Add(T newVal)
 {
     Total = Math.Min(Total, Datapoint.From <T>(newVal).Magnitude());
 }
Beispiel #16
0
        public async Task <PlotModel> Generate()
        {
            var responses = metrics.ToDictionary(x => x, x => cloudWatch.GetMetricStatisticsAsync(new GetMetricStatisticsRequest
            {
                Namespace          = x.Namespace,
                MetricName         = x.Name,
                Period             = (int)x.Period.TotalSeconds,
                StartTime          = metricStartTime,
                Dimensions         = x.Dimensions,
                EndTime            = metricEndTime,
                Statistics         = x.StatisticType.GetRequestStatistics(),
                ExtendedStatistics = x.StatisticType.GetRequestExtendedStatistics()
            }));

            await Task.WhenAll(responses.Select(x => x.Value));

            var model = new PlotModel
            {
                Title                   = title,
                Subtitle                = subtitle,
                Padding                 = new OxyThickness(20d),
                LegendPlacement         = LegendPlacement.Outside,
                LegendPosition          = LegendPosition.BottomLeft,
                LegendOrientation       = LegendOrientation.Horizontal,
                DefaultColors           = GraphConstants.Colors,
                PlotAreaBorderThickness = new OxyThickness(0d, 0d, 0d, 1d),
                PlotAreaBorderColor     = OxyColor.FromRgb(204, 204, 204)
            };

            var dataRanges = new List <Tuple <StandardUnit, double> >();

            foreach (var response in responses.Where(x => x.Value.Result.Datapoints.Any()))
            {
                IEnumerable <Datapoint> orderedData = response.Value.Result.Datapoints.OrderByDescending(i => i.StatisticTypeValue(response.Key.StatisticType));

                Datapoint highestDataPoint = orderedData.First();
                Datapoint lowestDataPoint  = orderedData.Last();

                dataRanges.Add(Tuple.Create(highestDataPoint.Unit, highestDataPoint.StatisticTypeValue(response.Key.StatisticType)));
                dataRanges.Add(Tuple.Create(lowestDataPoint.Unit, lowestDataPoint.StatisticTypeValue(response.Key.StatisticType)));

                Series series = seriesBuilder.BuildSeries(response.Key, response.Value.Result.Datapoints);
                model.Series.Add(series);
            }

            var aAxis = new DateTimeAxis
            {
                Position      = AxisPosition.Bottom,
                TicklineColor = OxyColor.FromRgb(238, 238, 238),
                Minimum       = DateTimeAxis.ToDouble(metricStartTime),
                Maximum       = DateTimeAxis.ToDouble(metricEndTime)
            };

            if (metrics.All(x => x.GraphType != GraphType.Total))
            {
                model.Axes.Add(InferYAxis(dataRanges));
                model.Axes.Add(aAxis);
            }

            return(model);
        }
Beispiel #17
0
 public override void Reset()
 {
     Total = Datapoint.DefaultOrIdentity <T2>();
 }
Beispiel #18
0
        public static void Scenario(string Endpoint, string[] Metadata)
        {
            //  Validate input
            if (Metadata.Length < 1)
            {
                throw new System.ArgumentException("Missing parameters");
            }

            //  Initialize variables
            FilterDefinition <BsonDocument> Filter;
            BsonDocument Owner     = null;
            BsonValue    Ownership = null;
            BsonArray    Entities  = new BsonArray();
            Int32        Node      = 0;
            BsonValue    Location  = null;
            BsonValue    Range     = null;
            String       URL       = "http://localhost/Client.php?action=scenario&realtime=false&people=" + Metadata[0];
            //  Connect database
            var Client   = new MongoClient("mongodb://" + ConfigurationManager.AppSettings["MongoDB.Username"] + ":" + ConfigurationManager.AppSettings["MongoDB.Password"] + "@" + ConfigurationManager.AppSettings["MongoDB.Server"] + ":" + ConfigurationManager.AppSettings["MongoDB.Port"]);
            var Database = Client.GetDatabase(ConfigurationManager.AppSettings["MongoDB.Database"]);

            //  Retrieve datapoints
            Filter = new BsonDocument();
            var Datapoints = Database.GetCollection <BsonDocument>("Datapoint").Find(Filter).ToList();

            //  Retrieve people
            Filter = Builders <BsonDocument> .Filter.Eq("IdNumber", Metadata[0]);

            var People = Database.GetCollection <BsonDocument>("People").Find(Filter).ToList();

            //  Retrieve owner
            if (People.Count != 0)
            {
                Owner = People.First();
            }
            //  Handle exeptions
            else if (People.Count == 0)
            {
                throw new System.ArgumentException("Invalid ID");
            }
            //  Retrieve objects
            Filter = new BsonDocument();
            var Objects = Database.GetCollection <BsonDocument>("Object").Find(Filter).ToList();

            //  Filter objects
            if (Objects.Count != 0)
            {
                foreach (BsonDocument Object in Objects)
                {
                    Ownership = Object["Ownership"].AsBsonArray.Last();
                    if (Ownership["ObjectId"] == Owner["_id"])
                    {
                        //  Append object
                        Entities.Add(Object);
                    }
                }
            }

            //  Validate elements
            if (Datapoints.Count == 0 && Entities.Count == 0)
            {
                throw new System.ArgumentException("Empty scenario");
            }
            //  Build URL
            else if (Datapoints.Count != 0 || Entities.Count == 0)
            {
                //  Append datapoints
                if (Datapoints.Count != 0)
                {
                    //  Retrieve datapoint
                    foreach (BsonDocument Datapoint in Datapoints)
                    {
                        Node++;
                        Location = Datapoint["Location"].AsBsonArray.Last();
                        //  Assign range
                        if (Datapoint.Contains("Range") == true)
                        {
                            Range = Datapoint["Range"];
                        }
                        else if (Datapoint.Contains("Range") == false)
                        {
                            Range = "0";
                        }
                        //  Append metadata
                        URL = URL + "&datapoint[" + Node + "][identifier]=" + System.Uri.EscapeDataString(Datapoint["IdNumber"].ToString()) + "&datapoint[" + Node + "][latitude]=" + Location["Coordinates"][0] + "&datapoint[" + Node + "][longitude]=" + Location["Coordinates"][1] + "&datapoint[" + Node + "][range]=" + Range;
                    }
                    //  Count again
                    Node = 0;
                }
                //  Append objects
                if (Entities.Count != 0)
                {
                    foreach (BsonDocument Entity in Entities)
                    {
                        Node++;
                        URL = URL + "&object[" + Node + "][identifier]=" + System.Uri.EscapeDataString(Entity["IdNumber"].ToString());
                    }
                }
            }
            //  Return URL
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine();
            Console.WriteLine(URL);
            Console.WriteLine();
            Console.ResetColor();
            //  Return menu
            Program.Main(new string[0]);
        }
Beispiel #19
0
 public static string ToJson(this Datapoint datapoint)
 {
     return($"{{\"Id\":\"{datapoint.Id}\",\"CustomerId\":\"{datapoint.CustomerId}\",\"ContainerId\":\"{datapoint.ContainerId}\",\"Name\":\"{datapoint.Name}\",\"NumericValue\":{datapoint.NumericValue.ToString("#0'.'0")},\"StringValue\":\"{datapoint.StringValue}\",\"CollectedTimestamp\":\"{datapoint.CollectedTimestamp.ToString(DateFormat)}\",\"ReceivedTimestamp\":\"{datapoint.ReceivedTimestamp.ToString(DateFormat)}\",\"Tags\":[{ToJson(datapoint.Tags)}]}}");
 }
 /// <summary>
 /// Creates a new instance of the DDatapoint class
 /// </summary>
 /// <param name="parent">DMeasurement hosting this DDatapoint</param>
 /// <param name="model">Model providng data for this DDatapoint</param>
 public DDatapoint(DMeasurement parent, Datapoint model)
 {
     this.Parent = parent;
     this.db = parent.db;
     this.Model = model;
     ViewModel = new DataPointViewModel();
     ViewModel.MeasurementID = Parent.Model.Measurement_ID;
     ViewModel.NameMeasurement = Parent.Model.NM;
     ViewModel.YTDCalc = Parent.Model.YTD_Calc;
     ViewModel.DataPointID = model.Datapoint_ID;
     ViewModel.Applicable = model.Applicable_DT;
     ViewModel.Value = model.Value_AMT;
     ViewModel.NumType = Parent.Model.Type_ID;
     ViewModel.IsCalculated = Parent.Model.Is_Calculated;
     ViewModel.HasSubmitted = model.HasSubmitted_IN;
     string roundingString = "";
     var decimalPlaces = (from m in db.Measurements
                          where Parent.Model.Measurement_ID == m.Measurement_ID
                          select m.Decimal_Points_SZ).ToList();
     var roundingInt = (int)(decimalPlaces.Count > 0 ? decimalPlaces.First() : 0);
     if (roundingInt != 0)
     {
         roundingString = ".";
         for (var i = 0; i < roundingInt; i++)
             roundingString += "0";
     }
     ViewModel.RoudingString = roundingString;
 }
Beispiel #21
0
    public void  VisGraph(int minTime, int maxtime)
    {
        float alpha = 0.0f;
        bool  flag  = false;
        int   midP  = (maxtime - minTime) / 2;
        int   mid   = minTime + midP;
        int   d     = 0;

        float[] arr = new float[mid + 1];
        int     l   = 0;



        for (int i = minTime; i < maxtime; i++)
        {
            d++;
            xval = float.Parse(data[i]["xval"].ToString());
            yval = float.Parse(data[i]["yval"].ToString());
            nspk = float.Parse(data[i]["nspk"].ToString());

            if (nspk == 1)
            {
                ntime = float.Parse(data [i] ["ntime"].ToString());
            }
            if (nspk == 2)
            {
                ntime  = float.Parse(data [i] ["ntime"].ToString());
                ntime2 = float.Parse(data [i] ["ntime2"].ToString());
            }
            if (nspk == 3)
            {
                ntime  = float.Parse(data [i] ["ntime"].ToString());
                ntime2 = float.Parse(data [i] ["ntime2"].ToString());
                ntime3 = float.Parse(data [i] ["ntime3"].ToString());
            }


            xval = xval * condensevalue;
            yval = yval * condensevalue;

            Vector3 vect3xy = new Vector3(xval, 0, yval);

            Datapoint.setDataPointColor();

            if (alpha < 1 && flag == false)
            {
                alpha   = (float)d / (float)midP;
                arr [l] = alpha;
                //	Debug.Log (alpha);
                l++;
            }

            else
            {
                flag  = true;
                alpha = arr [l];
                l--;
                //	Debug.Log (alpha);
            }

            Datapoint.setDataPointColor(alpha);

            Instantiate(staticPointPrefab, vect3xy, Quaternion.identity);

            if (nspk == 1)
            {
                noOfSpikes++;
                lowSpikes++;
                timeSec = ntime / 10000;
                timeOfSpikeLow.Add(timeSec);
                nspikeVal = nspk * nspikeCondenseValue;
                Vector3 vect3intensity = new Vector3(xval, nspikeVal, yval);
                Spike.setColor(alpha);
                Instantiate(pointOneSpkiePrefab, vect3intensity, Quaternion.identity);
                CreateSpike(xval, yval, nspikeVal);
            }
            if (nspk == 2)
            {
                noOfSpikes += 2;
                mediumSpikes++;
                timeOfSpikeMedium.Add(((ntime + ntime2) / 2) / 10000);
                nspikeVal = nspk * nspikeCondenseValue;
                Vector3 vect3intensity = new Vector3(xval, nspikeVal, yval);
                Spike.setColor(alpha);
                Instantiate(pointTwoSpkiePrefab, vect3intensity, Quaternion.identity);
                CreateSpike(xval, yval, nspikeVal);
            }

            if (nspk == 3)
            {
                noOfSpikes += 3;
                highSpikes++;
                timeOfSpikeHigh.Add(((ntime + ntime2 + ntime3) / 3) / 10000);
                nspikeVal = nspk * nspikeCondenseValue;
                Vector3 vect3intensity = new Vector3(xval, nspikeVal, yval);
                Spike.setColor(alpha);
                Instantiate(pointThreeSpkiePrefab, vect3intensity, Quaternion.identity);
                CreateSpike(xval, yval, nspikeVal);
            }
        }

        string timesLow    = CreateStringOfTime(timeOfSpikeLow);
        string timesMedium = CreateStringOfTime(timeOfSpikeMedium);
        string timesHigh   = CreateStringOfTime(timeOfSpikeHigh);


        showRange(minTime, maxtime, noOfSpikes, lowSpikes, highSpikes, mediumSpikes, timesLow, timesMedium, timesHigh);



        DestroyTimeList(timeOfSpikeLow);
        DestroyTimeList(timeOfSpikeMedium);
        DestroyTimeList(timeOfSpikeHigh);
        noOfSpikes   = 0;
        lowSpikes    = 0;
        mediumSpikes = 0;
        highSpikes   = 0;
    }
Beispiel #22
0
 static FeatureListExtractor()
 {
     DefineExtractor("LinAccelMag", new FeatureExtractor <DatapointKitchenSink, double>(v => new double[] { v.LinAccel.Length() }));
     DefineExtractor("LinAccelVec", new FeatureExtractor <DatapointKitchenSink, Vector3>(v => Datapoint.AsDblArrayFrom(v.LinAccel)));
     DefineExtractor("GravityVec", new FeatureExtractor <DatapointKitchenSink, Vector3>(v => Datapoint.AsDblArrayFrom(v.Gravity)));
     DefineExtractor("GyroMag", new FeatureExtractor <DatapointKitchenSink, double>(v => new double[] { v.Gyro.Length() }));
     DefineExtractor("GyroVec", new FeatureExtractor <DatapointKitchenSink, Vector3>(v => Datapoint.AsDblArrayFrom(v.Gyro)));
     DefineExtractor("RotAngle", new FeatureExtractor <DatapointKitchenSink, double>(v => new double[] { v.Orientation.AsAngle() }));
     DefineExtractor("RotAxis", new FeatureExtractor <DatapointKitchenSink, Vector3>(v =>
     {
         //var axis = ;
         //if (axis.LengthSquared() < 1e-8) return new double[] { 0, 0, 0 };
         return(Datapoint.AsDblArrayFrom(v.Orientation.XYZ().Normalize()));
     }));
     DefineExtractor("RotQuat", new FeatureExtractor <DatapointKitchenSink, Quaternion>(v => Datapoint.AsDblArrayFrom(v.Orientation)));
     DefineExtractor("AccelXRot", new FeatureExtractor <DatapointKitchenSink, Vector3>(v =>
                                                                                       Datapoint.AsDblArrayFrom(v.LinAccel.RotatedBy(v.Orientation))));
     DefineExtractor("AccelXRotInv", new FeatureExtractor <DatapointKitchenSink, Vector3>(v =>
                                                                                          Datapoint.AsDblArrayFrom(v.LinAccel.RotatedBy(v.Orientation.Inverse()))));
     DefineExtractor("AccelParallelToG", new FeatureExtractor <DatapointKitchenSink, double>(v => new double[] { v.LinAccel.Dot(v.Gravity.Normalize()) }));
     DefineExtractor("AccelPerpToG", new FeatureExtractor <DatapointKitchenSink, double>(v =>
     {
         if (v.Gravity.LengthSquared() < 1e-8)
         {
             return new double[] { 0 }
         }
         ;
         var gHat = v.Gravity.Normalize();
         return(new double[]
         {
             (double)(v.LinAccel - gHat * (v.LinAccel.Dot(gHat))).Length()
         });
     }));
     DefineExtractor("AccelXandParallelToG", new FeatureExtractor <DatapointKitchenSink>(2, v =>
     {
         return(new double[] { v.LinAccel.X, v.LinAccel.Dot(v.Gravity.Normalize()) });
     }));
     DefineExtractor("AccelPhoneXandWorldYZ", new FeatureExtractor <DatapointKitchenSink>(3, v =>
     {
         if (v.Gravity.LengthSquared() < 1e-8)
         {
             return new double[] { 0, 0, 0 }
         }
         ;
         var gHat = v.Gravity.Normalize();
         var yHat = Vector3.Cross(gHat, Vector3.UnitX);
         return(new double[] { v.LinAccel.X, v.LinAccel.Dot(gHat), v.LinAccel.Dot(yHat) });
     }));
     DefineExtractor("AngleBetweenAccelAndG", new FeatureExtractor <DatapointKitchenSink, double>(v => new double[] { v.LinAccel.AngleTo(v.Gravity) }));
     DefineExtractor("AccelParallelToGyroAxis", new FeatureExtractor <DatapointKitchenSink, double>(v => new double[] { v.LinAccel.Dot(v.Gyro.Normalize()) }));
     DefineExtractor("AccelPerpToGyroAxis", new FeatureExtractor <DatapointKitchenSink, double>(v =>
     {
         if (v.Gyro.LengthSquared() < 1e-8)
         {
             return new double[] { 0 }
         }
         ;
         var gHat = v.Gyro.Normalize();
         return(new double[]
         {
             (double)(v.LinAccel - gHat * (v.LinAccel.Dot(gHat))).Length()
         });
     }));
     DefineExtractor("AngleBetweenAccelAndGyroAxis", new FeatureExtractor <DatapointKitchenSink, double>(v => new double[] { v.LinAccel.AngleTo(v.Gyro) }));
     DefineExtractor("GyroParallelToGravity", new FeatureExtractor <DatapointKitchenSink, double>(v => new double[] { v.Gyro.Dot(v.Gravity.Normalize()) }));
     DefineExtractor("GyroPerpToGravity", new FeatureExtractor <DatapointKitchenSink, double>(v =>
     {
         if (v.Gravity.LengthSquared() < 1e-8)
         {
             return new double[] { 0 }
         }
         ;
         var gHat = v.Gravity.Normalize();
         return(new double[]
         {
             (double)(v.Gyro - gHat * (v.Gyro.Dot(gHat))).Length()
         });
     }));
     DefineExtractor("AngleBetweenGravAndGyroAxis", new FeatureExtractor <DatapointKitchenSink, double>(v => new double[] { v.Gravity.AngleTo(v.Gyro) }));
 }
Beispiel #23
0
 public static double GetOverallMagnitude <T>(T datum) where T : struct
 {
     return(Datapoint.From(datum).Magnitude());
 }
Beispiel #24
0
 public FeatureAbsoluteAxisSelector(int selectedAxis) : base(1, v => new double[] { Datapoint.AsDblArrayFrom(v)[selectedAxis] })
 {
     Name = axisNames[selectedAxis];
 }
Beispiel #25
0
 public AssessByAggregator(Func <T, Tdata, T> aggregator, [CallerMemberName] string name = "")
 {
     Startvalue     = Datapoint.DefaultOrIdentity <T>();
     aggregatorFunc = aggregator;
     Name           = name;
 }
Beispiel #26
0
        //// Methodically search through valid operations to get a way to do (Total - Target) / Sigma => double.
        //private static void ThrowIfNotLegit(IDatapoint D)
        //{
        //    try
        //    {
        //        var dMag = D.Magnitude();
        //        if (float.IsNaN(dMag) || float.IsInfinity(dMag)) throw new InvalidOperationException();
        //    }
        //    catch { throw new InvalidOperationException(); }
        //}
        //private static void ThrowIfNotLegit(T2 D, bool thisIsLessPreferable = true) // Tricksy! Disambiguates in favour of the other one, for the compiler, even though we never ever actually use it.
        //{
        //    ThrowIfNotLegit(Datapoint.From(D));
        //}

        static FoMComponent()
        {
            //bool CanCreateNonzeroExample = false,
            //     CanCastToDatapoint = false,
            //     CanConvertToDatapoint = false,
            //     CanSubtract = false,
            //     CanSubtractAfterCasting = false,
            //     CanDivideAndGetDouble = false,
            //     CanDivideAndTakeMagnitude = false,
            //     CanDivideMagnitudes = false;
            //T2 defaultExample, nonzeroExample;

            //defaultExample = Datapoint.DefaultOrIdentity<T2>(); // This *ought* to be always safe, since it only differs from default(T2) in specific case(s).

            //try
            //{
            //    var nonzero = Datapoint
            //                        .From(default(T2)) // *Should* yield an example Datapoint<T2> (exact contents are irrelevant here, it's like a template)
            //                        .FromArray(Enumerable.Repeat(1.0f, Datapoint<T2>.Dimensions).ToArray()); // This will presumably always yield a nonzero value - it might not make sense but it's a good start.
            //    ThrowIfNotLegit(nonzero);
            //    nonzeroExample = (T2)nonzero;
            //    CanCreateNonzeroExample = true;
            //}
            //catch (InvalidOperationException) { }

            //try
            //{

            //    var verifyCast = (Datapoint<T2>)defaultExample;
            //    ThrowIfNotLegit(verifyCast);
            //    CanCastToDatapoint = true;
            //}
            //catch (InvalidCastException) { }
            //catch (InvalidOperationException) { }

            //if (!CanCastToDatapoint)
            //    try
            //    {
            //        var verifyConvert = Operator.Convert<T2, Datapoint<T2>>(Datapoint.DefaultOrIdentity<T2>());
            //        ThrowIfNotLegit(verifyConvert);
            //        CanConvertToDatapoint = true;
            //    }
            //    catch (InvalidCastException) { }
            //    catch (InvalidOperationException) { }

            //try
            //{
            //    var verifySubtraction = Operator.Subtract(default(T2), default(T2));
            //    ThrowIfNotLegit(verifySubtraction);
            //    CanSubtract = true;
            //}
            //catch (InvalidOperationException) { }

            // Etc., etc., etc.

            //if (CanSubtract && CanDivideMagnitudes)
            //{
            _getZscore = (Total, Target, Sigma) =>
            {
                var numerator   = Datapoint.From(Operator.Subtract(Total, Target)).Magnitude();
                var denominator = Datapoint.From(Sigma).Magnitude();
                return((double)numerator / denominator);
            };
            //}
        }
Beispiel #27
0
        private void Initialize(string fileDir) //初始化
        {
            try
            {
                var connstr = @"Provider=Microsoft.ACE.OLEDB.12.0; Data Source = " + fileDir + "; " + "Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
                Conn = new OleDbConnection(connstr);
                Conn.Open();
                DataTable dtTemp;
                string    datatype;
                datatype = finddatatype(Path.GetFileName(fileDir));

                if (datatype == null)
                {
                    throw new Exception("无法确认表格检测种类!");
                }

                dtTemp = Conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

                if (dtTemp == null)
                {
                    return;
                }

                String[] excelSheets = new string[dtTemp.Rows.Count];
                int      i           = 0;

                foreach (DataRow row in dtTemp.Rows)
                {
                    if (!row["TABLE_NAME"].ToString().Contains("FilterDatabase"))
                    {
                        excelSheets[i] = row["TABLE_NAME"].ToString();
                        i++;
                    }
                }

                dtTemp.Dispose();

                // Loop through all of the sheets
                for (int j = 0; j < i; j++)
                {
                    try
                    {
                        Command = new OleDbCommand("Select * from [" + excelSheets[j] + "]", Conn);
                        Adapter = new OleDbDataAdapter();
                        Table   = new DataTable();
                        Adapter.SelectCommand = Command;
                        Adapter.Fill(Table);
                        string columnTimeName = null;
                        string columnConcName = null;


                        DataTable dtColomn = Conn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[]
                                                                      { null, null, excelSheets[j], null });

                        List <string> listColumn = new List <string>();
                        foreach (DataRow row in dtColomn.Rows)
                        {
                            listColumn.Add(row["Column_name"].ToString());
                        }

                        dtColomn.Dispose();
                        bool timefound = false, concfound = false;
                        foreach (string column in listColumn)
                        {
                            var result = findColumnbelong(column);
                            switch (result)
                            {
                            case "Time_Found":
                                columnTimeName = column;
                                timefound      = true;
                                break;

                            case "Conc_Found":
                                columnConcName = column;
                                concfound      = true;
                                break;

                            default:
                                break;
                            }
                        }

                        if (timefound == false || concfound == false)
                        {
                            throw new Exception("查找时间或者浓度失败!");
                        }

                        if (Table.Rows.Count < 2)
                        {
                            throw new Exception("没有足够数据以查找时间间隔!");
                        }

                        TimeSpan time_interval = new TimeSpan(0, 0, 0);
                        long     intervalcount_thatmakesupaday;
                        long     intervalcount_thatmakesup8hrs = 1;

                        try
                        {
                            DateTime Value1, Value2;
                            if (DateTime.TryParse(Table.Rows[0][columnTimeName].ToString(), out Value1) && DateTime.TryParse(Table.Rows[1][columnTimeName].ToString(), out Value2))
                            {
                                time_interval = Value2 - Value1;
                            }

                            if (time_interval > TimeSpan.FromDays(1) || time_interval == TimeSpan.FromDays(0))
                            {
                                throw new Exception("时间间隔有误!");
                            }

                            if (TimeSpan.FromDays(1).Ticks % time_interval.Ticks != 0)
                            {
                                throw new Exception("时间间隔不能以24小时进行区分!");
                            }

                            if (datatype == "O3")
                            {
                                if (TimeSpan.FromHours(8).Ticks % time_interval.Ticks != 0)
                                {
                                    throw new Exception("时间间隔不能以8小时进行区分!");
                                }
                                intervalcount_thatmakesup8hrs = TimeSpan.FromHours(8).Ticks / time_interval.Ticks;
                            }

                            intervalcount_thatmakesupaday = TimeSpan.FromDays(1).Ticks / time_interval.Ticks;
                        }
                        catch (Exception)
                        {
                            throw;
                        }

                        if (Table.Rows.Count < intervalcount_thatmakesupaday)
                        {
                            throw new Exception("数据不足以求出日均!");
                        }

                        int       rowCount = 1;
                        double    day_sum  = 0;
                        Datapoint prev     = new Datapoint()
                        {
                            Concentration   = 0,
                            Continued_time  = new TimeSpan(0),
                            IsHighPollution = false,
                            IsMonitorError  = false,
                            Time            = new DateTime(0),
                            Monitor_Error   = "",
                            Pollution_Level = ""
                        };
                        Datapoint current = new Datapoint()
                        {
                            Concentration   = 0,
                            Continued_time  = new TimeSpan(0),
                            IsHighPollution = false,
                            IsMonitorError  = false,
                            Time            = new DateTime(0),
                            Monitor_Error   = "",
                            Pollution_Level = ""
                        };

                        List <double> day_elements = new List <double>();

                        foreach (DataRow row in Table.Rows)
                        {
                            string problems_found  = "";
                            string pollution_level = "";
                            current.Concentration = (double)row[columnConcName];
                            DateTime result = new DateTime();

                            if (row[columnTimeName].GetType() == typeof(DateTime))
                            {
                                result = (DateTime)row[columnTimeName];
                            }
                            else
                            {
                                if (!DateTime.TryParse((string)row[columnTimeName], out result))
                                {
                                    throw new Exception(string.Format("无法分析第{0}行的时间数据", rowCount));
                                }
                            }
                            current.Time = result;

                            if (rowCount < intervalcount_thatmakesupaday)
                            {
                                day_sum += (double)row[columnConcName];
                                if (datatype == "O3")
                                {
                                    day_elements.Add((double)row[columnConcName]);
                                }
                            }
                            else if (rowCount > intervalcount_thatmakesupaday)
                            {
                                day_sum -= (double)Table.Rows[rowCount - 1 - (int)intervalcount_thatmakesupaday][columnConcName];
                                day_sum += (double)row[columnConcName];

                                if (datatype == "O3")
                                {
                                    day_elements.RemoveAt(0);
                                    day_elements.Add((double)row[columnConcName]);
                                    pollution_level = O3avg_results(day_elements.OrderByDescending(item => item).Take((int)intervalcount_thatmakesup8hrs).Sum() / intervalcount_thatmakesup8hrs, (double)row[columnConcName]);
                                }
                                else
                                {
                                    pollution_level = calculateAvgandPollutionlvl((double)row[columnConcName], day_sum, intervalcount_thatmakesupaday, datatype);
                                }
                            }
                            else
                            {
                                if (datatype == "O3")
                                {
                                    pollution_level = O3avg_results(day_elements.OrderByDescending(item => item).Take((int)intervalcount_thatmakesup8hrs).Sum() / intervalcount_thatmakesup8hrs, (double)row[columnConcName]);
                                }
                                else
                                {
                                    pollution_level = calculateAvgandPollutionlvl((double)row[columnConcName], day_sum, intervalcount_thatmakesupaday, datatype);
                                }
                            }

                            var monitorinfo = examineMonitorErrors((double)row[columnConcName], datatype);
                            if (monitorinfo != null)
                            {
                                problems_found += monitorinfo;
                            }

                            if (problems_found == "")
                            {
                                current.IsMonitorError = false;
                                current.Monitor_Error  = "";
                            }
                            else
                            {
                                current.IsMonitorError = true;
                                current.Monitor_Error  = problems_found;
                            }
                            current.Pollution_Level = pollution_level;
                            if (pollution_level == "Intermidiate Pollution" || pollution_level == "Heavy Pollution" || pollution_level == "Severe Pollution")
                            {
                                current.IsHighPollution = true;
                            }

                            else
                            {
                                current.IsHighPollution = false;
                                current.Pollution_Level = "";
                            }

                            //Console.WriteLine(string.Format("{0},{1},{2},{3},{4}", prev.Concentration, prev.Time, prev.Continued_time, prev.Pollution_Level, prev.Monitor_Error));
                            current.Field = datatype;

                            if (current.Equals(prev))
                            {
                                current.Mergewith(prev, time_interval);
                            }
                            else if (!current.Equals(prev) && prev.isProblematic())
                            {
                                ReportSQL(prev);

                                //Console.WriteLine(string.Format("{0},{1},{2},{3},{4}", prev.Concentration, prev.Time, prev.Continued_time, prev.Pollution_Level, prev.Monitor_Error));
                            }

                            else
                            {
                            }
                            prev.Copy(current);
                            current.Reset();
                            rowCount++;
                        }


                        //Disposeof();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(String.Format("在表格{0}内的{1}表单,{2}", fileDir, excelSheets[j], ex.Message), "分析文件错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    Command.Dispose();
                    Adapter.Dispose();
                    Table.Dispose();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(String.Format("在表格{0}内,{1}", fileDir, ex.Message), "分析文件错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                throw;
            }
            Conn.Close();
            Conn.Dispose();
        }
Beispiel #28
0
            static CrosslinkAxesImpl()
            {
                Type typeT       = typeof(T);
                Type wrappedType = Datapoint.From(default(T)).GetType();

                // First (and lowest-level of recursion) case: if T is not something which implements IDatapoint at all,
                // hopefully it's a basic type like a scalar or a vector; for all such, return the highest single scaling value, in all slots.
                if (!typeT.Implements <IDatapoint>())
                {
                    //var dimensions = wrappedType.GetStaticProperty<int>("Dimensions");
                    var dimensions = Datapoint.From(default(T)).Dimensions;
                    _apply = (double[] inputs) =>
                    {
                        try
                        {
                            return(Enumerable
                                   .Repeat(inputs.Max(), dimensions)
                                   .ToList().ToArray()); // Stupid frickin' portable Accord.Math with busted ToArray...
                        }
                        catch (Exception)
                        {
                            Android.Util.Log.Debug("Crosslinker", $"Issue with type {typeT.Name} (wrapped type {wrappedType.FullName}) and _apply.");
                            throw;
                        }
                    };
                    return;
                }

                // If it does implement IDatapoint, then (by construction) it has at least one generic argument, possibly several, though we need to use the static Datapoint.GetGenericArguments to allow for proxied types (see DatapointKitchenSink).
                var _applyFuncs  = new List <Func <double[], double[]> >();
                var numberToTake = new List <int>();
                var numberToSkip = new List <int>()
                {
                    0
                };

                foreach (Type t in Datapoint.GetGenericArguments <T>())
                {
                    // How many dimensions does this one have?
                    int nToTake;
                    if (t.Implements <IDatapoint>())
                    {
                        nToTake = t.GetStaticProperty <int>("Dimensions");
                    }
                    else
                    {
                        var wrapped_t = typeof(Datapoint <>).MakeGenericType(t);
                        nToTake = wrapped_t.GetStaticProperty <int>("Dimensions");
                    }
                    numberToTake.Add(nToTake);
                    numberToSkip.Add(numberToSkip.Last() + nToTake);

                    // And what is *its* Apply() function?
                    var crosslinker = typeof(CrosslinkAxesImpl <>).MakeGenericType(t);
                    //_applyFuncs.Add((double[] inputs) =>
                    //{
                    //    return crosslinker.InvokeStaticMethod<double[]>("Apply", inputs);
                    //});
                    var cFunc = (Func <double[], double[]>)crosslinker.GetField("_apply").GetValue(null);
                    _applyFuncs.Add(cFunc);
                }

                _apply = (inputs) =>
                {
                    var outputs = new List <double>();
                    foreach (int i in Enumerable.Range(0, Datapoint.GetGenericArguments <T>().Length))
                    {
                        var inputsSubset = inputs
                                           .Skip(numberToSkip[i])
                                           .Take(numberToTake[i])
                                           .ToList().ToArray(); // Stupid Accord.Math issues again...


                        var _func = _applyFuncs[i];
                        outputs.AddRange(_func.Invoke(inputsSubset));
                    }
                    return(outputs.ToArray());
                };
            }