Exemplo n.º 1
0
 public IAmRequest(ObjectId iAmDeviceIdentifier, uint maxAPDULengthAccepted, Segmentation segmentationSupported, uint vendorID)
 {
     this.IAmDeviceIdentifier = iAmDeviceIdentifier;
     this.MaxAPDULengthAccepted = maxAPDULengthAccepted;
     this.SegmentationSupported = segmentationSupported;
     this.VendorID = vendorID;
 }
Exemplo n.º 2
0
 /// <summary>
 /// Constructs a new DeviceTableEntry instance
 /// </summary>
 /// <param name="instance">The device instance</param>
 /// <param name="address">The address of the device</param>
 /// <param name="maxAppgramLength">The maximum appgram length that this device can receive</param>
 /// <param name="segmentationSupport">The segmentation support of the device</param>
 /// <param name="vendorId">The vendor id of the device</param>
 public DeviceTableEntry(uint instance, Address address, uint maxAppgramLength, Segmentation segmentationSupport, ushort vendorId)
 {
     this.Instance = instance;
     this.Address = address;
     this.MaxAppgramLength = maxAppgramLength;
     this.SegmentationSupport = segmentationSupport;
     this.VendorId = vendorId;
 }
Exemplo n.º 3
0
        /// <summary>
        /// Create Countly event with provided values
        /// </summary>
        /// <param name="Key">Key attribute, must be non-empty</param>
        /// <param name="Count">Count parameter, must me positive number</param>
        /// <param name="Sum">Sum parameter, can be null</param>
        /// <param name="Segmentation">Segmentation parameter</param>
        public CountlyEvent(string Key, int Count, double? Sum, Segmentation Segmentation)
        {
            if (String.IsNullOrEmpty(Key))
            {
                throw new ArgumentException("Event Key must be non-empty string");
            }

            if (Count <= 0)
            {
                throw new ArgumentException("Event Count must be positive number");
            }

            this.Key = Key;
            this.Count = Count;
            this.Sum = Sum;
            this.Segmentation = Segmentation;
        }
Exemplo n.º 4
0
 public Segmentation GetSegmentBuffer(BacnetMaxSegments max_segments)
 {
     if (max_segments == BacnetMaxSegments.MAX_SEG0) return null;
     Segmentation ret = new Segmentation();
     ret.buffer = GetEncodeBuffer(m_client.HeaderLength);
     ret.max_segments = GetSegmentsCount(max_segments);
     ret.window_size = m_proposed_window_size;
     return ret;
 }
Exemplo n.º 5
0
 public void ReadPropertyMultipleResponse(BacnetAddress adr, byte invoke_id, Segmentation segmentation, IList<BacnetReadAccessResult> values)
 {
     SendComplexAck(adr, invoke_id, segmentation, BacnetConfirmedServices.SERVICE_CONFIRMED_READ_PROP_MULTIPLE, (b) =>
     {
         Services.EncodeReadPropertyMultipleAcknowledge(b, values);
     });
 }
Exemplo n.º 6
0
        internal static async Task RecordMenuItemTelemetryAsync(string?openPath, MorphicMenuItem.MenuType parentMenuType, MorphicMenuItemTelemetryType?telemetryType, string?telemetryCategory)
        {
            string?eventSource = null;

            switch (parentMenuType)
            {
            case MenuType.mainMenu:
                eventSource = "iconMenu";
                break;

            case MenuType.contextMenu:
                eventSource = "contextMenu";
                break;
            }


            switch (telemetryType)
            {
            case MorphicMenuItemTelemetryType.Settings:
            {
                var segmentation        = new Segmentation();
                var settingCategoryName = telemetryCategory;
                if (settingCategoryName is not null)
                {
                    segmentation.Add("category", settingCategoryName);
                }
                //
                segmentation.Add("eventSource", eventSource);
                //
                await App.Current.Countly_RecordEventAsync("systemSettings", 1, segmentation);

                //await App.Current.Countly_RecordEventAsync("systemSettings" + settingCategoryName);
            }
            break;

            case MorphicMenuItemTelemetryType.LearnMore:
            {
                var segmentation        = new Segmentation();
                var settingCategoryName = telemetryCategory;
                if (settingCategoryName is not null)
                {
                    segmentation.Add("category", settingCategoryName);
                }
                //
                segmentation.Add("eventSource", eventSource);
                //
                await App.Current.Countly_RecordEventAsync("learnMore", 1, segmentation);
            }
            break;

            case MorphicMenuItemTelemetryType.QuickDemoVideo:
            {
                var segmentation        = new Segmentation();
                var settingCategoryName = telemetryCategory;
                if (settingCategoryName is not null)
                {
                    segmentation.Add("category", settingCategoryName);
                }
                //
                segmentation.Add("eventSource", eventSource);
                //
                await App.Current.Countly_RecordEventAsync("quickDemoVideo", 1, segmentation);
            }
            break;

            default:
                // handle menu "open settings" items
                // NOTE: we may want to create a separate "telemetry type" and embed it in the menu xaml itself (so that we don't have to compare against open paths here)
            {
                string?settingCategoryName = null;
                switch (openPath)
                {
                case "ms-settings:colors":
                    settingCategoryName = "darkMode";
                    break;

                case "ms-settings:display":
                    settingCategoryName = "textSize";
                    break;

                case "ms-settings:easeofaccess":
                case "ms-settings:easeofaccess-display":
                    settingCategoryName = "allAccessibility";
                    break;

                case "ms-settings:easeofaccess-colorfilter":
                    settingCategoryName = "colorFilter";
                    break;

                case "ms-settings:easeofaccess-cursorandpointersize":
                case "ms-settings:easeofaccess-MousePointer":
                    settingCategoryName = "pointerSize";
                    break;

                case "ms-settings:easeofaccess-highcontrast":
                    settingCategoryName = "highContrast";
                    break;

                case "ms-settings:easeofaccess-keyboard":
                    settingCategoryName = "keyboard";
                    break;

                case "ms-settings:easeofaccess-magnifier":
                    settingCategoryName = "magnifier";
                    break;

                case "ms-settings:mousetouchpad":
                    settingCategoryName = "mouse";
                    break;

                case "ms-settings:nightlight":
                    settingCategoryName = "nightMode";
                    break;

                case "ms-settings:regionlanguage":
                    settingCategoryName = "language";
                    break;

                case "ms-settings:speech":
                    settingCategoryName = "readAloud";
                    break;

                case null:
                    // unknown (i.e. no data)
                    break;

                default:
                    Debug.Assert(false, "Unknown menu item (i.e. no telemetry)");
                    break;
                }
                if (settingCategoryName is not null)
                {
                    var segmentation = new Segmentation();
                    segmentation.Add("category", settingCategoryName);
                    segmentation.Add("eventSource", eventSource);
                    //
                    await App.Current.Countly_RecordEventAsync("systemSettings", 1, segmentation);

                    //await App.Current.Countly_RecordEventAsync("systemSettings" + settingCategoryName);
                }
            }
            break;
            }
        }
Exemplo n.º 7
0
        public static SCalcRegionTask calcRegions(CancellationToken cToken, SCalcRegionTask data)
        {
            Rectangle roiRect = data.roiRect;

            // Flatten RGA to 1 byte pixel buffer with 1 indicating segment
//			if(!FlattenImage(cToken, roiRect, data.pixelData)) {
//				return data;
//			}

            // ********************************************************
            // DETECT REGIONS
            // ********************************************************


            // Allocate stuff
            List <Point>       points  = new List <Point>(128 * 128);
            SCalcRegionBuffers buffers = new SCalcRegionBuffers();

            buffers.Prepare(256 * 256);
            bool isEDM = true;


            // Get regions at tags
            bool propertiesSet = false;
            int  test          = 0;

            foreach (Tag tag in data.tags)
            {
                Point posROI = new Point((int)tag.Pos.X - roiRect.Location.X, (int)tag.Pos.Y - roiRect.Location.Y);
                int   index  = posROI.Y * roiRect.Size.Width + posROI.X;
                uint  val    = data.pixelData[index];
                if (val == 0x00FFFFFF)
                {
                    points.Clear();
                    QuickFill <uint> .FloodFill(posROI, data.pixelData, roiRect.Size, val, 0, points);

                    if (!propertiesSet)
                    {
                        propertiesSet = true;

                        // Get bounds
                        Rectangle regionBounds;
                        Region.Transform(points, Point.Empty, out regionBounds);

                        if (cToken.IsCancellationRequested)
                        {
                            return(data);
                        }

                        // Prepare buffers
                        int regionsize = regionBounds.Width * regionBounds.Height;
                        buffers.Prepare(regionsize);

                        // Load binary map
                        Region.loadBinaryMap(points, new Point(-regionBounds.X, -regionBounds.Y), buffers.EDMMap, regionBounds.Width);

                        if (cToken.IsCancellationRequested)
                        {
                            return(data);
                        }

                        // Create EDM
                        EDM.createEDM(buffers.EDMMap, regionBounds.Width, regionBounds.Height);

                        int[] globalMinMax;
                        Segmentation.FindGlobalMinMax(buffers.EDMMap, regionBounds.Width, regionBounds.Height, out globalMinMax);

                        test = globalMinMax[1];
                    }
                }

                if (cToken.IsCancellationRequested)
                {
                    return(data);
                }
            }



            // Create regions from segmentation map
            int   height   = roiRect.Size.Height;
            int   width    = roiRect.Size.Width;
            int   count    = height * width;
            float invWidth = 1.0f / (float)width;

            for (int index = 0; index < count; index++)
            {
                uint val = data.pixelData[index];
                if (val == 0x00FFFFFF)
                {
                    int   x2  = index % width - 1;
                    int   y2  = (int)((float)(index - x2) * invWidth);
                    Point pos = new Point(x2, y2);

                    points.Clear();
//					QuickFill<uint>.FloodFill(pos, data.pixelData, roiRect.Size, val, 0, points);
                    QuickFillUint.FloodFill(pos, data.pixelData, roiRect.Size, val, 0, points);

                    if (cToken.IsCancellationRequested)
                    {
                        return(data);
                    }

                    // Transform region points to image space
                    Rectangle regionBounds;
                    Region.Transform(points, roiRect.Location, out regionBounds);

                    // Prepare buffers
                    int regionsize = regionBounds.Width * regionBounds.Height;
                    buffers.Prepare(regionsize);

                    // Load binary map
                    Region.loadBinaryMap(points, new Point(-regionBounds.X, -regionBounds.Y), buffers.EDMMap, regionBounds.Width);

                    if (cToken.IsCancellationRequested)
                    {
                        return(data);
                    }

                    // Create EDM
                    EDM.createEDM(buffers.EDMMap, regionBounds.Width, regionBounds.Height);

                    if (cToken.IsCancellationRequested)
                    {
                        return(data);
                    }

                    // Debug render EDM
                    if (data.bDebugDrawEDM)
                    {
                        DebugDragEDM(regionBounds, buffers, data);
                    }

                    if (cToken.IsCancellationRequested)
                    {
                        return(data);
                    }

                    // Find maxima
                    int    minSize   = Math.Min(regionBounds.Width, regionBounds.Height);
                    double tolerance = 20;

//					double findMaxThreshold = 4*EDM.ONE;
                    double findMaxThreshold = (float)test * 0.5f;

                    Segmentation.MaxPoint[] maxPoints;
                    int[] globalMinMax;
                    Segmentation.FindGlobalMinMax(buffers.EDMMap, regionBounds.Width, regionBounds.Height, out globalMinMax);
                    Segmentation.findMaxima(buffers.EDMMap, regionBounds.Width, regionBounds.Height, tolerance,
                                            findMaxThreshold, buffers.maxMap, isEDM, globalMinMax, out maxPoints);

                    // Count max points
                    int iMaxPointCount = 0;
                    foreach (Segmentation.MaxPoint maxPoint in maxPoints)
                    {
                        int ri   = maxPoint.y * regionBounds.Width + maxPoint.x;
                        int iVal = buffers.maxMap[ri];
                        if ((iVal & Segmentation.MAX_POINT) > 0)
                        {
                            iMaxPointCount++;
                        }
                    }


                    // Skip all regions with no max
                    if (iMaxPointCount == 0)
                    {
                        continue;
                    }

                    // Debug Render maxima
                    if (data.bDebugDrawEDM)
                    {
                        DebugDragMaxima(regionBounds, buffers, data, maxPoints, iMaxPointCount);
                    }


                    if (cToken.IsCancellationRequested)
                    {
                        return(data);
                    }

                    if (iMaxPointCount == 1)
                    {
                        Region region = new Region(points, regionBounds);
                        data.regions.Add(region);
                        data.SendRegionAdded(region);
                    }
                    else
                    {
                        // TODO: could watershed write region map in different colors (so we dont have to quickfill)
                        double watershedThreshold = 1;
                        Segmentation.performWatershed(buffers.EDMMap, regionBounds.Width, regionBounds.Height, watershedThreshold,
                                                      buffers.maxMap, isEDM, buffers.regionMap, maxPoints, globalMinMax);

                        // Debug render region map
                        if (data.bDebugDrawRegions)
                        {
                            int offsetX = regionBounds.X - roiRect.X;
                            int offsetY = regionBounds.Y - roiRect.Y;
                            int ri      = 0;
                            for (int ry = 0; ry < regionBounds.Height; ry++)
                            {
                                for (int rx = 0; rx < regionBounds.Width; rx++)
                                {
                                    int iVal = buffers.regionMap[ri];
                                    data.debugTexture.SetPixel(rx + offsetX, ry + offsetY, iVal, 0, 0, 1);
                                    ri++;
                                }
                            }
                        }

                        if (cToken.IsCancellationRequested)
                        {
                            return(data);
                        }

                        for (int ry = 0; ry < regionBounds.Height; ry++)
                        {
                            for (int rx = 0; rx < regionBounds.Width; rx++)
                            {
                                int  ri   = (regionBounds.Width * ry) + rx;
                                uint iVal = (uint)(buffers.regionMap[ri] & 0xFF);

                                if (iVal == 255)
                                {
                                    points.Clear();
//									QuickFill<byte>.FloodFill(new Point(rx, ry), buffers.regionMap, regionBounds.Size, (byte)iVal, 0, points);
                                    QuickFillByte.FloodFill(new Point(rx, ry), buffers.regionMap, regionBounds.Size, (byte)iVal, 0, points);

                                    if (cToken.IsCancellationRequested)
                                    {
                                        return(data);
                                    }

                                    Rectangle bounds;
                                    Region.Transform(points, regionBounds.Location, out bounds);

                                    Region region = new Region(points, bounds);
                                    data.regions.Add(region);
                                    data.SendRegionAdded(region);
                                }
                            }
                        }
                    }

                    if (cToken.IsCancellationRequested)
                    {
                        return(data);
                    }
                }
            }
            return(data);
        }
Exemplo n.º 8
0
    private void Update()
    {
        Time.timeScale = 0;
        currentTimeBetweenAnnotations += Time.deltaTime; //Add current delta time -> Could be higher than capture

        if (exportFinished && currentTimeBetweenAnnotations >= timeBetweenAnnotations)
        {
            if (segmentationDone)
            {
                Segmentation.Camera.Render();
                segmentationDone = false;
            }

            //Check if segmentation camera is still rendering
            if (Segmentation.Camera.FinishedRender)
            {
                segmentationDone = true;
            }
            else
            {
                return;
            }

            //Segmentation rendered all objects visible
            EditableObjects = new HashSet <AnnotationObject>(RenderedObjects); //COPY

            //Count pixels or optional export
            Segmentation.Run();

            //Annotations for each profile
            foreach (AnnotationProfile profile in profiles)
            {
                OutputCamera = profile.Camera;

                Logger.Log("[CONDITIONING]");
                if (profile.Conditioning())
                {
                    Logger.Log("[PRE-ANNOTATE]");
                    profile.PreAnnotate();

                    Logger.Log("[ANNOTATE]");
                    OutputCamera.Render();

                    Logger.Log("[VALIDATE]");
                    bool validated = profile.Validation();

                    Logger.Log("[POST-ANNOTATE]");
                    profile.PostAnnotate();

                    if (validated)
                    {
                        //Logger.Log("POST-CONDITIONING");

                        StartCoroutine(AwaitExport());
                        exportFinished = false;

                        currentTimeBetweenAnnotations = 0.0f;
                    }
                }
            }
        }

        EditableObjects = null;
        Time.timeScale  = timeScale;
    }
 /// <summary>
 /// Records a custom event with the specified segmentation values, count and a sum
 /// </summary>
 /// <param name="Key">Name of the custom event, required, must not be the empty string</param>
 /// <param name="Count">Count to associate with the event, should be more than zero</param>
 /// <param name="Sum">Sum to associate with the event</param>
 /// /// <param name="Sum">Event duration</param>
 /// <param name="Segmentation">Segmentation object to associate with the event, can be null</param>
 /// <returns>True if event is uploaded successfully, False - queued for delayed upload</returns>
 public static Task <bool> RecordEvent(string Key, int Count, double?Sum, double?Duration, Segmentation Segmentation)
 {
     if (!Countly.Instance.IsInitialized())
     {
         throw new InvalidOperationException("SDK must initialized before calling 'RecordEvent'");
     }
     return(Countly.Instance.RecordEventInternal(Key, Count, Sum, Duration, Segmentation));
 }
 private double ComputeNorm(Segmentation s)
 {
     double norm = 0;
     foreach (int str in s.Clusters.Keys)
         norm += similarity(s.Clusters[str].Count, s.Clusters[str].Count, s.Clusters[str].Count);
     return norm;
 }
Exemplo n.º 11
0
        private EncodeBuffer EncodeSegmentHeader(BacnetAddress adr, byte invoke_id, Segmentation segmentation, BacnetConfirmedServices service, bool more_follows)
        {
            EncodeBuffer buffer;
            bool is_segmented = false;
            if (segmentation == null)
                buffer = GetEncodeBuffer(m_client.HeaderLength);
            else
            {
                buffer = segmentation.buffer;
                is_segmented = segmentation.sequence_number > 0 | more_follows;
            }
            buffer.Reset(m_client.HeaderLength);

            //encode
            NPDU.Encode(buffer, BacnetNpduControls.PriorityNormalMessage, adr.RoutedSource, null, DEFAULT_HOP_COUNT, BacnetNetworkMessageTypes.NETWORK_MESSAGE_WHO_IS_ROUTER_TO_NETWORK, 0);

            //set segments limits
            buffer.max_offset = buffer.offset + GetMaxApdu();
            int apdu_header = APDU.EncodeComplexAck(buffer, BacnetPduTypes.PDU_TYPE_COMPLEX_ACK | (is_segmented ? BacnetPduTypes.SEGMENTED_MESSAGE | BacnetPduTypes.SERVER : 0) | (more_follows ? BacnetPduTypes.MORE_FOLLOWS : 0), service, invoke_id, segmentation != null ? segmentation.sequence_number : (byte)0, segmentation != null ? segmentation.window_size : (byte)0);
            buffer.min_limit = (GetMaxApdu() - apdu_header) * (segmentation != null ? segmentation.sequence_number : 0);

            return buffer;
        }
Exemplo n.º 12
0
 public void MultipleModelMethodfromStringTest(string val, MultipleModelMethod res)
 {
     Assert.AreEqual(res, Segmentation.MultipleModelMethodfromString(val));
 }
        public override double Process(Segmentation s1, Segmentation s2)
        {
            if (s1 == null || s2 == null)
                return 0;
            if (s1 == s2)
                return 1;
            double result = 0;
            //En cls van a estar los subconjuntos comunes en las dos particiones concatenados los nombres de los clusters por un &, ademas se guarda la cantidad de elementos del subconjunto.
            Dictionary<string, long> cls = new Dictionary<string, long>();
            for (int i = 0; i < s1.Labels.Length; i++)
            {
                if (cls.ContainsKey(s1.Labels[i] + "&" + s2.Labels[i]))
                    cls[s1.Labels[i] + "&" + s2.Labels[i]] += 1;
                else
                    cls.Add(s1.Labels[i] + "&" + s2.Labels[i], 1);
            }

            string[] aux;
            //Tamanno de los cluster que contienen al subconjunto en P1 y P2 respectivamente.
            int c1 = 0, c2 = 0;
            //Calcular para cada subconjunto el valor de similaridad asociado.
            foreach (string str in cls.Keys)
            {
                aux = str.Split('&');
                c1 = s1.Clusters[int.Parse(aux[0])].Count;
                c2 = s2.Clusters[int.Parse(aux[1])].Count;
                result += similarity(cls[str], c1, c2);
            }

            return result / Math.Sqrt(ComputeNorm(s1) * ComputeNorm(s2));
        }
Exemplo n.º 14
0
 public AcknowledgementService send(Address address, OctetString linkService, uint maxApduLengthAccepted, Segmentation segmentationSupported, ConfirmedRequestService serviceRequest)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 15
0
 protected ConsoleHelper(PlayerStats playerStats)
 {
     this.playerStats = playerStats;
     segmentation     = Segmentation.Instance();
 }
Exemplo n.º 16
0
        /// <summary>
        /// Records a custom event with the specified values
        /// </summary>
        /// <param name="Key">Name of the custom event, required, must not be the empty string</param>
        /// <param name="Count">Count to associate with the event, should be more than zero</param>
        /// <param name="Sum">Sum to associate with the event</param>
        /// <param name="Segmentation">Segmentation object to associate with the event, can be null</param>
        /// <returns>True if event is uploaded successfully, False - queued for delayed upload</returns>
        protected async Task <bool> RecordEventInternal(string Key, int Count, double?Sum, double?Duration, Segmentation Segmentation)
        {
            if (!Countly.Instance.IsServerURLCorrect(ServerUrl))
            {
                return(false);
            }
            if (!IsConsentGiven(ConsentFeatures.Events))
            {
                return(true);
            }

            CountlyEvent cEvent = new CountlyEvent(Key, Count, Sum, Duration, Segmentation);

            bool saveSuccess = false;

            lock (sync)
            {
                Events.Add(cEvent);
                saveSuccess = SaveEvents();
            }

            if (saveSuccess)
            {
                saveSuccess = await Upload();
            }

            return(saveSuccess);
        }
Exemplo n.º 17
0
 public void ReadRangeResponse(BacnetAddress adr, byte invoke_id, Segmentation segmentation, BacnetObjectId object_id, BacnetPropertyReference property, BacnetResultFlags status, uint item_count, byte[] application_data, BacnetReadRangeRequestTypes request_type, uint first_sequence_no)
 {
     SendComplexAck(adr, invoke_id, segmentation, BacnetConfirmedServices.SERVICE_CONFIRMED_READ_RANGE, (b) =>
     {
         Services.EncodeReadRangeAcknowledge(b, object_id, property.propertyIdentifier, property.propertyArrayIndex, BacnetBitString.ConvertFromInt((uint)status), item_count, application_data, request_type, first_sequence_no);
     });
 }
 public override double Process(Segmentation s1, Segmentation s2)
 {
     double ents = Entropy(s1) * Entropy(s2);
     if (ents != 0)
         return MI(s1, s2) / Math.Sqrt(ents);
     else
         return 1;
 }
Exemplo n.º 19
0
 public void WriteFileResponse(BacnetAddress adr, byte invoke_id, Segmentation segmentation, int position)
 {
     SendComplexAck(adr, invoke_id, segmentation, BacnetConfirmedServices.SERVICE_CONFIRMED_ATOMIC_WRITE_FILE, (b) =>
     {
         Services.EncodeAtomicWriteFileAcknowledge(b, true, position);
     });
 }
        //Rand es (n00 + n11) / (n(n-1)/2), pero n00+n01+n10+n11 = n(n-1)/2. Por tanto n00+n11 = n(n-1)/2 - ((n11+n10) + (n11+n01) -2*n11).
        //Hay una forma muy facil de calcular (n11+n10) + (n11+n01) y n11 se calcula en O(n).
        public override double Process(Segmentation s1, Segmentation s2)
        {
            double rand = 0;
            double t = 0;
            double n11_n01 = 0, n11_n10 = 0, n11=0;
            foreach (List<int> cluster in s1.Clusters.Values)
            {
                t = cluster.Count;
                n11_n10 += t * (t-1) / 2;
            }

            foreach (List<int> cluster in s2.Clusters.Values)
            {
                t = cluster.Count;
                n11_n01 += t * (t - 1) / 2;
            }

            Dictionary<string, int> cls = new Dictionary<string, int>();
            for (int i = 0; i < s1.Labels.Length; i++)
            {
                if (cls.ContainsKey(s1.Labels[i] + "&" + s2.Labels[i]))
                    cls[s1.Labels[i] + "&" + s2.Labels[i]] += 1;
                else
                    cls.Add(s1.Labels[i] + "&" + s2.Labels[i], 1);
            }

            foreach (int cluster in cls.Values)
                if (cluster >= 2)
                {
                    t = cluster;
                    n11 += t * (t - 1) / 2;
                }

                t = s1.Labels.Length;
                double pc = t * (t - 1) / 2;

            rand = ((double)(pc - n11_n10 - n11_n01 + 2*n11)) / ((double)pc);
            return rand;
        }
Exemplo n.º 21
0
        private void UpdateCanvas()
        {
            Bitmap         dstImage = new Bitmap(srcImage.Width, srcImage.Height);
            GrayProcessing gp       = new GrayProcessing();
            Adjustment     a        = new Adjustment();
            Effect         e        = new Effect();
            Segmentation   s        = new Segmentation();
            EdgeDetect     ed       = new EdgeDetect();

            switch (support)
            {
            case SupportMethod.Brightness:
                dstImage = a.Brightness((Bitmap)srcImage.Clone(), this.Degree);
                break;

            case SupportMethod.Contrast:
                dstImage = a.Contrast((Bitmap)srcImage.Clone(), this.Degree);
                break;

            case SupportMethod.Thresholding:
                dstImage = gp.Thresholding((Bitmap)srcImage.Clone(), (byte)(255 - this.Degree));
                break;

            case SupportMethod.Sharpen:
                dstImage = e.Sharpen((Bitmap)srcImage.Clone(), (byte)this.Degree);
                break;

            case SupportMethod.UnsharpMask:
                dstImage = e.UnsharpMask((Bitmap)srcImage.Clone(), (byte)this.Degree);
                break;

            case SupportMethod.AddNoise:
                dstImage = e.AddNoise((Bitmap)srcImage.Clone(), this.Degree);
                break;

            case SupportMethod.Sprinkle:
                dstImage = e.Sprinkle((Bitmap)srcImage.Clone(), this.Degree);
                break;

            case SupportMethod.Pinch:
                dstImage = e.Pinch((Bitmap)srcImage.Clone(), this.Degree);
                break;

            case SupportMethod.Swirl:
                dstImage = e.Swirl((Bitmap)srcImage.Clone(), this.Degree);
                break;

            case SupportMethod.Wave:
                dstImage = e.Wave((Bitmap)srcImage.Clone(), this.Degree);
                break;

            case SupportMethod.MoireFringe:
                dstImage = e.MoireFringe((Bitmap)srcImage.Clone(), this.Degree);
                break;

            case SupportMethod.Diffuse:
                dstImage = e.Diffuse((Bitmap)srcImage.Clone(), this.Degree);
                break;

            case SupportMethod.Lighting:
                dstImage = e.Lighting((Bitmap)srcImage.Clone(), this.Degree);
                break;

            case SupportMethod.Mosaic:
                dstImage = e.Mosaic((Bitmap)srcImage.Clone(), this.Degree);
                break;

            case SupportMethod.ClearSmallArea:
                dstImage = s.ClearSmallArea((Bitmap)srcImage.Clone(), this.Degree);
                break;

            case SupportMethod.EdgeEnhance:
                dstImage = ed.EdgeEnhance((Bitmap)srcImage.Clone(), this.Degree);
                break;

            case SupportMethod.EdgeHomogenize:
                dstImage = ed.EdgeHomogenize((Bitmap)srcImage.Clone(), this.Degree);
                break;

            default:
                break;
            }

            this.panel1.BackgroundImage = dstImage;
            this.FinalImage             = (Bitmap)dstImage.Clone();
        }
 public abstract double Process(Segmentation s1, Segmentation s2);
Exemplo n.º 23
0
    //加载XML
    void LoadXml(string url, string password, string xmlName)
    {
        vesal_log.vesal_write_log("开始从DB库中读取XML文件");
        ConnectionString connect1 = new ConnectionString();

        connect1.Filename  = url;
        connect1.LimitSize = 10000000000;
        connect1.Journal   = false;
        connect1.Mode      = LiteDB.FileMode.ReadOnly;
        using (var db = new LiteDatabase(connect1))
        {
            bool isHavScene = db.CollectionExists(xmlName + ".xml");
            if (!isHavScene)
            {
                var         stream = db.FileStorage.OpenRead(xmlName + ".xml");
                XmlDocument doc    = new XmlDocument();
                doc.Load(stream);
                XmlElement root      = doc.DocumentElement;
                XmlElement animation = (XmlElement)root.FirstChild;
                total     = float.Parse(animation.GetAttribute("total"));
                effective = float.Parse(animation.GetAttribute("effective"));
                abObjName = animation.GetAttribute("object");
                try
                {
                    Animation_MouseFollowRotation tmpAMF = this.GetComponent <Animation_MouseFollowRotation>();
                    tmpAMF.minDis = float.Parse(animation.GetAttribute("minDis"));
                    //tmpAMF.maxDis = float.Parse(animation.GetAttribute("maxDis"));
                    Interaction.instance.maxDistance = float.Parse(animation.GetAttribute("maxDis"));
                    Interaction.instance.minDistance = tmpAMF.minDis;
                    tmpAMF.distance = float.Parse(animation.GetAttribute("distance"));
                    Debug.Log("float.Parse(animation.GetAttribute:" + tmpAMF.distance);
                    Camera.main.GetComponent <Interaction>().RotateOpera(transform.parent.rotation.eulerAngles);
                    if (xmlName == "SA0607004" || xmlName == "SA0607005" || xmlName == "SA0607006" || xmlName == "SA0607007")
                    {
                        Camera.main.GetComponent <Interaction>().SetTarget(new Vector3(0, 0, 0), 1);
                    }
                    else
                    {
                        Camera.main.GetComponent <Interaction>().SetTarget(transform.parent.position, tmpAMF.distance);
                    }
                    Camera.main.GetComponent <Interaction>().distance = tmpAMF.distance;
                    try
                    {
                        thisCamera.farClipPlane = float.Parse(animation.GetAttribute("farClipPlane"));
                        thisCamera.fieldOfView  = float.Parse(animation.GetAttribute("fieldOfView"));
                    }
                    catch (Exception e)
                    {
                        Debug.Log(e.Message);
                    }
                    string color = animation.GetAttribute("color");
                    //主题颜色切换
                    switch (color)
                    {
                    case "白色":
                        thisCamera.backgroundColor = Color.white;
                        uiChange(0);
                        tmpAMF.sprite = tmpAMF.sprite0;
                        break;

                    case "灰色":
                        thisCamera.backgroundColor = new Color(50 / 255f, 50 / 255f, 50 / 255f, 1);
                        uiChange(1);
                        tmpAMF.sprite = tmpAMF.sprite1;
                        break;

                    case "黑色":
                        thisCamera.backgroundColor = Color.black;
                        uiChange(1);
                        tmpAMF.sprite = tmpAMF.sprite1;
                        break;

                    default:
                        break;
                    }
                }
                catch (Exception E)
                {
                    Debug.Log(E.Message);
                    throw E;
                }
                XmlNodeList Segmentations = animation.ChildNodes;
                if (Segmentations.Count == 0)
                {
                    vesal_log.vesal_write_log("无分段信息");
                }
                else
                {
                    //分段信息记录
                    for (int se = 0; se < Segmentations.Count; se++)
                    {
                        Segmentation seg = new Segmentation();
                        seg.start       = float.Parse(((XmlElement)Segmentations[se]).GetAttribute("start"));
                        seg.end         = float.Parse(((XmlElement)Segmentations[se]).GetAttribute("end"));
                        seg.count       = float.Parse(((XmlElement)Segmentations[se]).GetAttribute("count"));
                        seg.name        = ((XmlElement)Segmentations[se]).GetAttribute("name");
                        seg.countString = ((XmlElement)Segmentations[se]).GetAttribute("countString");
                        list.Add(seg);
                    }
                    //bool color = true;
                    //分段按钮及进度条生成
                    for (int s = 0; s < list.Count; s++)
                    {
                        GameObject game1 = Instantiate(Resources.Load <GameObject>("Prefab/PPTProgress"));
                        GameObject game2 = Instantiate(Resources.Load <GameObject>("Prefab/Segmented"));
                        game1.transform.SetParent(progressParent);
                        game2.transform.SetParent(segmentedParent);
                        game1.transform.localPosition = Vector3.zero;
                        game2.transform.localPosition = Vector3.zero;
                        game1.transform.localScale    = Vector3.one;
                        game2.transform.localScale    = Vector3.one;
                        game1.GetComponent <LayoutElement>().preferredWidth    = (int)(1000 * list[s].count / effective) + 1;
                        game1.transform.GetChild(3).GetComponent <Text>().text = list[s].countString;
                        game1.GetComponent <Slider>().minValue = list[s].start / total;
                        game1.GetComponent <Slider>().maxValue = list[s].end / total;
                        game2.transform.GetChild(0).GetComponent <Text>().text = (s + 1).ToString() + "." + list[s].name;
                        game2.GetComponent <SegmentedButton>().index           = s;
                        progress.Add(game1.GetComponent <Slider>());
                    }
                }
                LoadModels(url, pwd, aniNo);
            }
            else
            {
                vesal_log.vesal_write_log(string.Format("库中不存在此模型场景:{0}", xmlName));
            }
        }
    }
 public override double Process(Segmentation s1, Segmentation s2)
 {
     return Entropy(s1) + Entropy(s2) - 2 * MI(s1, s2);
 }
        private Segmentation SimulatedAnnealing(double[] normWeights, Segmentation s0, int maxIter)
        {
            Segmentation current = s0;
            Segmentation next = s0;
            Segmentation best = s0;
            double e0 = DistConsensus(normWeights, s0);
            double eCurrent = e0;
            double eNext = e0;
            double eBest = e0;
            int r = 0;
            double temp = 0.0001428;
            Random random = new Random();

            //int[] l0 = new int[s0.Labels.Length];
            //int[] l1 = new int[s0.Labels.Length];
            //for (int i = 0; i < l0.Length; i++)
            //    l0[i] = i;

            //Segmentation seg0 = new Segmentation(l0);
            //Segmentation seg1 = new Segmentation(l1);
            //double au0 = DistConsensus(normWeights, seg0);
            //double au1 = DistConsensus(normWeights, seg1);

            while (r < maxIter)
            {
                next = current.GetNeighbor(Set.SPGraph);
                eNext = DistConsensus(normWeights, next);
                if (eNext < eBest)
                {
                    best = next;
                    eBest = eNext;
                }
                if (Math.Exp(-1 * (eNext - eBest) / temp) > random.NextDouble())
                {
                    current = next;
                    eCurrent = eNext;
                }

                if (r > (maxIter * 4) / 5 && r < (maxIter * 9) / 10)
                   temp = temp * 1.002;
                r++;

            }

            this.Set.DistToConsensus = eBest;
            return best;
        }
 private double Entropy(Segmentation s)
 {
     double entropy = 0;
     double aux = 0;
     foreach (int i in s.Clusters.Keys)
     {
         aux = (((double)s.Clusters[i].Count) / ((double)s.Labels.Length));
         entropy += aux * Math.Log(aux, 2);
     }
     return -1 * entropy;
 }
Exemplo n.º 27
0
        private static void DebugDragMaxima(Rectangle regionBounds, SCalcRegionBuffers buffers, SCalcRegionTask data,
                                            Segmentation.MaxPoint[] maxPoints, int iMaxPointCount)
        {
            Rectangle roiRect = data.roiRect;

            int regionROIOffsetX = regionBounds.X - roiRect.X;
            int regionROIOffsetY = regionBounds.Y - roiRect.Y;

            if (iMaxPointCount > 1)
            {
                Console.WriteLine(" ----- Max debug -----");
                Console.WriteLine(" roi: pos({0},{1}) size({2},{3})", regionBounds.X, regionBounds.Y, regionBounds.Width, regionBounds.Height);
                Console.WriteLine(" max count:" + iMaxPointCount);
            }
            int ri = 0;

            for (int ry = 0; ry < regionBounds.Height; ry++)
            {
                for (int rx = 0; rx < regionBounds.Width; rx++)
                {
                    int iVal = buffers.maxMap[ri];
                    if (iVal > 0)
                    {
                        if ((iVal & Segmentation.MAX_POINT) > 0)
                        {
                            data.debugTexture.SetPixel(rx + regionROIOffsetX, ry + regionROIOffsetY, 0, 255, 0, 1);
                        }
                        else
                        {
                            data.debugTexture.SetPixel(rx + regionROIOffsetX, ry + regionROIOffsetY, 255, 0, 0, 1);
                        }
                        if (iMaxPointCount > 1)
                        {
                            Console.WriteLine("maxMap({0},{1})={2}", rx, ry, Segmentation.GetMaxMapString(iVal));
                        }
                    }
                    ri++;
                }
            }
            if (iMaxPointCount > 1)
            {
                foreach (Segmentation.MaxPoint maxPoint in maxPoints)
                {
                    ri = maxPoint.y * regionBounds.Width + maxPoint.x;
                    int iVal = buffers.maxMap[ri];
                    Console.WriteLine("maxPoint({0},{1})={2} : {3}", maxPoint.x, maxPoint.y, maxPoint.value, Segmentation.GetMaxMapString(iVal));
                }
            }
        }
        private double MI(Segmentation s1, Segmentation s2)
        {
            double mi = 0;
            double aux = 0;
            Dictionary<string, long> cls = new Dictionary<string, long>();
            for (int i = 0; i < s1.Labels.Length; i++)
            {
                if (cls.ContainsKey(s1.Labels[i] + "&" + s2.Labels[i]))
                    cls[s1.Labels[i] + "&" + s2.Labels[i]] += 1;
                else
                    cls.Add(s1.Labels[i] + "&" + s2.Labels[i], 1);
            }

            //foreach (int cluster in cls.Values)
            //{
            //    aux = (((double)cluster) / ((double)s1.Labels.Length));
            //    if (aux != 0)
            //        mi += aux * Math.Log(aux, 2);
            //}

            foreach (int cS1 in s1.Clusters.Keys)
            {
                foreach (int cS2 in s2.Clusters.Keys)
                {
                    if (cls.ContainsKey(cS1.ToString() + "&" + cS2.ToString()))
                    {
                        aux = (((double)cls[cS1.ToString() + "&" + cS2.ToString()]) / ((double)s1.Labels.Length));
                        if (aux != 0)
                            mi += aux * Math.Log((aux * s1.Labels.Length * s1.Labels.Length) / ((double)(s1.Clusters[cS1].Count) * ((double)s2.Clusters[cS2].Count)), 2);
                    }
                }
            }
            return mi;
        }
 public void TearDownFixture()
 {
     _segmentation.Dispose();
     _segmentation = null;
 }
Exemplo n.º 30
0
 public AcknowledgementService send(Address address, OctetString linkService, MaxApduLength maxAPDULength,
                                    Segmentation segmentationSupported, ConfirmedRequestService serviceRequest)
 {
     return(applicationLayer.send(address, linkService, (uint)maxAPDULength.GetMaxApduLength(), segmentationSupported, serviceRequest));
 }
Exemplo n.º 31
0
 public void ReadFileResponse(BacnetAddress adr, byte invoke_id, Segmentation segmentation, int position, uint count, bool end_of_file, byte[] file_buffer)
 {
     SendComplexAck(adr, invoke_id, segmentation, BacnetConfirmedServices.SERVICE_CONFIRMED_ATOMIC_READ_FILE, (b) =>
     {
         Services.EncodeAtomicReadFileAcknowledge(b, true, end_of_file, position, 1, new byte[][] { file_buffer }, new int[] { (int)count });
     });
 }
Exemplo n.º 32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DivikResultLoader"/> class.
 /// </summary>
 public DivikResultLoader()
 {
     _segmentationContext = new Segmentation();
 }
Exemplo n.º 33
0
 public void ReadPropertyResponse(BacnetAddress adr, byte invoke_id, Segmentation segmentation, BacnetObjectId object_id, BacnetPropertyReference property, IEnumerable<BacnetValue> value)
 {
     SendComplexAck(adr, invoke_id, segmentation, BacnetConfirmedServices.SERVICE_CONFIRMED_READ_PROPERTY, (b) =>
     {
         Services.EncodeReadPropertyAcknowledge(b, object_id, property.propertyIdentifier, property.propertyArrayIndex, value);
     });
 }
Exemplo n.º 34
0
 /// <summary>
 /// Constructs a new DeviceTableEntry instance
 /// </summary>
 /// <param name="instance">The device instance</param>
 /// <param name="address">The address of the device</param>
 /// <param name="maxAppgramLength">The maximum appgram length that this device can receive</param>
 /// <param name="segmentationSupport">The segmentation support of the device</param>
 /// <param name="vendorId">The vendor id of the device</param>
 public DeviceTableEntry(uint instance, Address address, uint maxAppgramLength, Segmentation segmentationSupport, ushort vendorId)
 {
     this.Instance            = instance;
     this.Address             = address;
     this.MaxAppgramLength    = maxAppgramLength;
     this.SegmentationSupport = segmentationSupport;
     this.VendorId            = vendorId;
 }
Exemplo n.º 35
0
 public bool WaitForSegmentAck(BacnetAddress adr, byte invoke_id, Segmentation segmentation, int timeout)
 {
     bool signaled = m_last_segment_ack.Wait(adr, invoke_id, timeout);
     if (signaled)
     {
         segmentation.sequence_number = (byte)((m_last_segment_ack.sequence_number + 1) % 256);
         segmentation.window_size = m_last_segment_ack.window_size;
     }
     return signaled;
 }
Exemplo n.º 36
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="DivikService" /> class.
 ///     Creates <see cref="Segmentation" /> (MCR) instance for the service.
 /// </summary>
 public DivikService()
 {
     _segmentation = new Segmentation();
 }
Exemplo n.º 37
0
        private bool EncodeSegment(BacnetAddress adr, byte invoke_id, Segmentation segmentation, BacnetConfirmedServices service, out EncodeBuffer buffer, Action<EncodeBuffer> apdu_content_encode)
        {
            //encode (regular)
            buffer = EncodeSegmentHeader(adr, invoke_id, segmentation, service, false);
            apdu_content_encode(buffer);

            bool more_follows = (buffer.result & EncodeResult.NotEnoughBuffer) > 0;
            if (segmentation != null && more_follows)
            {
                //reencode in segmented
                EncodeSegmentHeader(adr, invoke_id, segmentation, service, true);
                apdu_content_encode(buffer);
                return true;
            }
            else if (more_follows)
                return true;
            else
            {
                return segmentation != null ? segmentation.sequence_number > 0 : false;
            }
        }
 private double DistConsensus(double[] normWeights, Segmentation seg)
 {
     //Sumo 1 del primer termino y 1 del tercero..solo falta restar el 2do termino de la ecuacion (10) en el paper PR.
     double result = 2;
     for (int i = 0; i < Set.Segmentations.Count; i++)
     {
         result -= 2 * normWeights[i] * rand.Process(seg, Set.Segmentations[i]);
     }
     return result;
 }
Exemplo n.º 39
0
        private void SendComplexAck(BacnetAddress adr, byte invoke_id, Segmentation segmentation, BacnetConfirmedServices service, Action<EncodeBuffer> apdu_content_encode)
        {
            Trace.WriteLine("Sending " + System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(service.ToString().ToLower()) + " ... ", null);

            //encode
            EncodeBuffer buffer;
            if (EncodeSegment(adr, invoke_id, segmentation, service, out buffer, apdu_content_encode))
            {
                //client doesn't support segments
                if (segmentation == null)
                {
                    Trace.TraceInformation("Segmenation denied");
                    ErrorResponse(adr, service, invoke_id, BacnetErrorClasses.ERROR_CLASS_SERVICES, BacnetErrorCodes.ERROR_CODE_ABORT_APDU_TOO_LONG);
                    buffer.result = EncodeResult.Good;     //don't continue the segmentation
                    return;
                }

                //first segment? validate max segments
                if (segmentation.sequence_number == 0)  //only validate first segment
                {
                    if (segmentation.max_segments != 0xFF && segmentation.buffer.offset > (segmentation.max_segments * (GetMaxApdu() - 5)))      //5 is adpu header
                    {
                        Trace.TraceInformation("Too much segmenation");
                        ErrorResponse(adr, service, invoke_id, BacnetErrorClasses.ERROR_CLASS_SERVICES, BacnetErrorCodes.ERROR_CODE_ABORT_APDU_TOO_LONG);
                        buffer.result = EncodeResult.Good;     //don't continue the segmentation
                        return;
                    }
                    else
                        Trace.WriteLine("Segmentation required", null);
                }

                //increment before ack can do so (race condition)
                unchecked { segmentation.sequence_number++; };
            }

            //send
            m_client.Send(buffer.buffer, m_client.HeaderLength, buffer.GetLength() - m_client.HeaderLength, adr, false, 0);
        }
        //Evaluo la segmentacion con las medidas RandIndex, VI and NMI y dejo los resultados en el set. Evaluo contra el mejor ground-truth y el promedio contra todos.
        private void EvaluateMatrixSegmentation(Segmentation segm)
        {
            RandIndexSegSim rand = new RandIndexSegSim();
            NMISegSim nmi = new NMISegSim();
            VISegSim vi = new VISegSim();

            //Calcular el rand
            double min = double.MaxValue;
            double ave = 0;
            double aux = 0;
            for (int i = 0; i < this.Set.GroundTruths.Count; i++)
            {
                aux = 1 - rand.Process(segm, this.Set.GroundTruths[i]);
                if (aux < min)
                    min = aux;
                ave += aux;
            }
            ave = ave / this.Set.GroundTruths.Count;
            this.Set.Best_RandEvaluation = min;
            this.Set.Ave_RandEvaluation = ave;

            //Calcular NMI
            min = double.MaxValue;
            ave = 0;
            aux = 0;
            for (int i = 0; i < this.Set.GroundTruths.Count; i++)
            {
                aux = 1- nmi.Process(segm, this.Set.GroundTruths[i]);
                if (aux < min)
                    min = aux;
                ave += aux;
            }
            ave = ave / this.Set.GroundTruths.Count;
            this.Set.Best_NMIEvaluation = min;
            this.Set.Ave_NMIEvaluation = ave;

            //Calcular VI
            min = double.MaxValue;
            ave = 0;
            aux = 0;
            for (int i = 0; i < this.Set.GroundTruths.Count; i++)
            {
                aux = vi.Process(segm, this.Set.GroundTruths[i]);
                if (aux < min)
                    min = aux;
                ave += aux;
            }
            ave = ave / this.Set.GroundTruths.Count;
            this.Set.Best_VIEvaluation = min;
            this.Set.Ave_VIEvaluation = ave;
        }
Exemplo n.º 41
0
 public void SetUpClass()
 {
     _segmentation = new Segmentation();
 }
Exemplo n.º 42
0
 public BulletInfo(double guessFactor, double power, Segmentation segments)
 {
     GuessFactor        = guessFactor;
     Power              = power;
     ApplicableSegments = segments;
 }
        public async Task <bool> SetZoom(Setting setting, object?newValue)
        {
            if (newValue is int index)
            {
                // method 1: get/set zoom level based on resolution
                //Size[] all = this.GetResolutions();
                //if (index >= 0 && index < all.Length)
                //{
                //    this.display.SetResolution(all[index]);
                //}

                // method 2: get/set zoom level based on scale percentage
                var    all         = Display.GetDPIScales();
                double?newDpiScale = null;
                if (all is not null && index >= 0 && index < all.Count)
                {
                    newDpiScale = all[index];
                }
                //
                // NOTE: due to current architectural limitations, Morphic v1.x uses the mouse cursor to determine which display to zoom (instead of finding the display the MorphicBar is on)
                var getCurrentPositionResult = Morphic.WindowsNative.Mouse.Mouse.GetCurrentPosition();
                if (getCurrentPositionResult.IsError == true)
                {
                    return(false);
                }
                var currentMousePosition = getCurrentPositionResult.Value !;
                //
                var getDisplayForPointResult = Morphic.WindowsNative.Display.Display.GetDisplayForPoint(currentMousePosition);
                if (getDisplayForPointResult.IsError == true)
                {
                    return(false);
                }
                var targetDisplay = getDisplayForPointResult.Value !;
                //
                if (newDpiScale is not null)
                {
                    // capture the current scale
                    var oldDpiScale = targetDisplay.GetMonitorScalePercentage();
                    //
                    // capture the recommended scale
                    Display.GetDpiOffsetResult?currentDpiOffsetAndRange;
                    double?recommendedDpiScale;
                    var    getCurrentDpiOffsetAndRangeResult = targetDisplay.GetCurrentDpiOffsetAndRange();
                    if (getCurrentDpiOffsetAndRangeResult.IsSuccess == true)
                    {
                        currentDpiOffsetAndRange = getCurrentDpiOffsetAndRangeResult.Value !;
                        var translateDpiOffsetToScalePercentageResult = Display.TranslateDpiOffsetToScalePercentage(0, currentDpiOffsetAndRange.Value.MinimumDpiOffset, currentDpiOffsetAndRange.Value.MaximumDpiOffset);
                        if (translateDpiOffsetToScalePercentageResult.IsError == true)
                        {
                            recommendedDpiScale = null;
                        }
                        else
                        {
                            recommendedDpiScale = translateDpiOffsetToScalePercentageResult.Value !;
                        }
                    }
                    else
                    {
                        currentDpiOffsetAndRange = null;
                        recommendedDpiScale      = null;
                    }
                    //
                    // set the new percentage
                    _ = await targetDisplay.SetDpiScaleAsync(newDpiScale.Value);

                    // report the display scale (percentage) change
                    if (oldDpiScale is not null)
                    {
                        var segmentation = new Segmentation();
                        if (recommendedDpiScale is not null)
                        {
                            var relativePercent = newDpiScale / recommendedDpiScale;
                            segmentation.Add("scalePercent", ((int)(relativePercent * 100)).ToString());

                            var recommendedDpiIndex = -currentDpiOffsetAndRange !.Value.MinimumDpiOffset;
                            var relativeDotOffset   = index - recommendedDpiIndex;
                            segmentation.Add("dotOffset", relativeDotOffset.ToString());
                        }
                        //
                        if (newDpiScale > oldDpiScale)
                        {
                            // NOTE: we can't call our main Countly logic from here (which skips Countly event recording if it's not enabled), so we just swallow any "not init'd" errors here
                            try
                            {
                                await Countly.RecordEvent("textSizeIncrease", 1, segmentation);
                            }
                            catch (InvalidOperationException)
                            {
                            }
                        }
                        else
                        {
                            // NOTE: we can't call our main Countly logic from here (which skips Countly event recording if it's not enabled), so we just swallow any "not init'd" errors here
                            try
                            {
                                await Countly.RecordEvent("textSizeDecrease", 1, segmentation);
                            }
                            catch (InvalidOperationException)
                            {
                            }
                        }
                    }
                }
            }

            return(true);
        }
Exemplo n.º 44
0
 public SegmentationTests()
 {
     segmentation = Segmentation.Instance();
 }
        //Devuelve la matriz del tamanno de la imagen final con los valores de los pixeles.
        private Bitmap GetFinalSegImage(Segmentation segm)
        {
            int[,] result = new int[this.Set.Image.Height, this.Set.Image.Width];
            for (int i = 0; i < result.GetLength(0); i++)
            {
                for (int j = 0; j < result.GetLength(1); j++)
                {
                    result[i, j] = segm.Labels[i * result.GetLength(1) + j];
                }
            }

            Bitmap image = new Bitmap(this.Set.Image.Width, this.Set.Image.Height,this.Set.Image.PixelFormat);
            BitmapData data = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadWrite, image.PixelFormat);
            unsafe
            {
                byte* imgPtr = (byte*)(data.Scan0);

                for (int i = 0; i < data.Height; i++)
                {
                    for (int j = 0; j < data.Width; j++)
                    {
                        imgPtr[0] = colors[Math.Min(67, result[i, j])].R;
                        imgPtr[1] = colors[Math.Min(67, result[i, j])].G;
                        imgPtr[2] = colors[Math.Min(67, result[i, j])].B;

                        imgPtr += 3;
                    }
                    imgPtr += data.Stride - data.Width * 3;
                }

                image.UnlockBits(data);

            }
            return image;
        }
 public void CreateObjectResponse(BacnetAddress adr, byte invoke_id, Segmentation segmentation, BacnetObjectId object_id)
 {
     SendComplexAck(adr, invoke_id, segmentation, BacnetConfirmedServices.SERVICE_CONFIRMED_CREATE_OBJECT, (b) =>
     {
         Services.EncodeCreateObjectAcknowledge(b, object_id);
     });
 }
 //Esto convierte el objeto segmentacion en la real segmantacion haciendo el proceso contrario al calculo de los superpixels.
 //El nuevo objeto segmentacion es mucho mas grande....la cardinalidad es la cantidad de pixels y no la cantidad de superpixels.
 private Segmentation GetSegmentationResult(Segmentation best)
 {
     int[] result = new int[this.Set.SuperPixelMatrix.Length];
     for (int i = 0; i < this.Set.SuperPixelMatrix.GetLength(0); i++)
     {
         for (int j = 0; j < this.Set.SuperPixelMatrix.GetLength(1); j++)
         {
             int sp = this.Set.SuperPixelMatrix[i, j];
             result[i* this.Set.SuperPixelMatrix.GetLength(1) + j] = best.Labels[sp];
         }
     }
     return new Segmentation(result);
 }
Exemplo n.º 48
0
        public static Tuple <bool, List <List <string> > > Optimize(List <List <double[, ]> > choppedContours, List <double[]>
                                                                    planes, ref ExternalPlanSetup plan, ref StructureSet ss, HNPlan hnPlan, ScriptContext context, List <List <Structure> > optimizedStructures, List <List <Structure> > matchingStructures, string contraName, int numIterations, List <Tuple <bool, double[], string> > features, Tuple <string, string, bool> beamParams)
        //return a list of strings which is the log of constraint updates during optimization.
        {
            //Only make parotid structures if that feature has been selected

            if (features[0].Item1 == true)
            {
                double priorityRatio = features[0].Item2[0];
                Segmentation.MakeParotidStructures(choppedContours, planes, ref plan, ref ss, hnPlan, context, matchingStructures, contraName, priorityRatio);
            }
            else
            {
                //remove previously segmented structures if there
                foreach (Structure structure in ss.Structures.ToList())
                {
                    if (structure.Name.ToLower().Contains("cpg_subseg"))
                    {
                        ss.RemoveStructure(structure);
                    }
                }
            }

            //Now run the first VMAT optimization.
            plan.SetCalculationModel(CalculationType.PhotonVMATOptimization, "PO_13623");
            plan.SetCalculationModel(CalculationType.DVHEstimation, "DVH Estimation Algorithm [15.6.06]");
            plan.SetCalculationModel(CalculationType.PhotonVolumeDose, "AAA_13623");
            plan.OptimizationSetup.AddNormalTissueObjective(100, 3, 95, 50, 0.2);
            bool jawTracking = beamParams.Item3;

            //use jaw tracking
            if (jawTracking)
            {
                try
                {
                    plan.OptimizationSetup.UseJawTracking = true;
                } catch
                {
                    System.Windows.MessageBox.Show("Could not use jaw tracking. Proceeding without.");
                }
            }

            // plan.OptimizeVMAT();
            plan.CalculateDose();
            string treatmentCenter = beamParams.Item1;
            string treatmentArea   = beamParams.Item2;
            string mlcId           = "";
            int    areaNum         = Int32.Parse(Regex.Match(treatmentArea, @"\d+").Value);

            if (treatmentCenter == "BC Cancer - Surrey")
            {
                switch (areaNum)
                {
                case 2:
                    mlcId = "";
                    break;

                case 3:
                    mlcId = "";
                    break;

                case 4:
                    mlcId = "";
                    break;

                case 5:
                    mlcId = "";
                    break;

                case 6:
                    mlcId = "";
                    break;
                }
            }
            else if (treatmentCenter == "BC Cancer - Vancouver")
            {
                switch (areaNum)
                {
                case 1:
                    mlcId = "1";
                    break;

                case 2:
                    mlcId = "HHM0767";
                    break;

                case 3:
                    mlcId = "";
                    break;

                case 4:
                    mlcId = "";
                    break;

                case 5:
                    mlcId = "";
                    break;

                case 6:
                    mlcId = "HML0990";
                    break;

                case 7:
                    mlcId = "MLC0987";
                    break;
                }
            }
            string mlcID     = "HML0990";
            int    numCycles = 1;
            OptimizationOptionsVMAT oov;

            ;
            bool isPassed = false;
            List <List <string> > updateLog = new List <List <string> >();

            for (int iter = 0; iter < numIterations; iter++)
            {
                //mlcID = plan.Beams.FirstOrDefault<Beam>().MLC.Id;
                oov = new OptimizationOptionsVMAT(numCycles, mlcID);
                plan.OptimizeVMAT(oov);
                plan.CalculateDose();

                //Now need to perform a plan check and iteratively adjust constraints based on whether they passed or failed, and whether they passed with flying colours or failed miserably.
                //Going to find the percentage by which the constraint failed or passed, and adjust both the priority and dose constraint based on this.
                updateLog.Add(OptObjectivesEditing.UpdateConstraints(ref plan, ref ss, ref hnPlan, context, optimizedStructures, matchingStructures, numCycles));
                if (features[0].Item1 == true)
                {
                    Segmentation.MakeParotidStructures(choppedContours, planes, ref plan, ref ss, hnPlan, context, matchingStructures, contraName, features[0].Item2[0]);
                }
            }
            numCycles = 4;
            oov       = new OptimizationOptionsVMAT(numCycles, mlcID);
            //Now for a maximum of 3 tries, perform 4-cycle vmat optimization followed by constraint updating until a plan is passed
            for (int i = 0; i < 3; i++)
            {
                plan.OptimizeVMAT(oov);
                plan.CalculateDose();
                updateLog.Add(OptObjectivesEditing.UpdateConstraints(ref plan, ref ss, ref hnPlan, context, optimizedStructures, matchingStructures, numCycles));
                if (features[0].Item1 == true)
                {
                    Segmentation.MakeParotidStructures(choppedContours, planes, ref plan, ref ss, hnPlan, context, matchingStructures, contraName, features[0].Item2[0]);
                }
                isPassed = Check.EvaluatePlan(context, hnPlan, matchingStructures, optimizedStructures).Item1;
                if (isPassed)
                {
                    break;
                }
            }


            return(Tuple.Create(isPassed, updateLog));
        }