/// <summary>
        /// A classification has been requested in processing a query.
        /// This function will run it and attach the result back to the query
        /// event stream when complete.
        /// </summary>
        public static async Task RunClassificationForQuery(
            ClassifierRequestedEventGridEventData classifierRequestData)
        {
            if (classifierRequestData != null)
            {
                // handle the classifier request
                ClassificationResponse response   = null;
                Classification         classifier = new Classification(
                    new ClassificationAttribute(
                        classifierRequestData.ClassifierRequest.DomainName,
                        classifierRequestData.ClassifierRequest.EntityTypeName,
                        classifierRequestData.ClassifierRequest.InstanceKey,
                        classifierRequestData.ClassifierRequest.ClassifierTypeName
                        ));

                if (classifier != null)
                {
                    if (_classificationMap == null)
                    {
                        _classificationMap = ClassificationMaps.CreateDefaultClassificationMaps();
                    }
                    // get the classifier class - must implement TClassification : IClassification, new()
                    IClassification classificationToRun = _classificationMap.CreateClassificationClass(classifier.ClassifierTypeName);
                    if (classificationToRun != null)
                    {
                        response = await classifier.Classify(classificationToRun, null);
                    }
                }

                if (response != null)
                {
                    // and post the result back to the query that asked for it
                    Query qrySource = new Query(classifierRequestData.DomainName,
                                                classifierRequestData.EntityTypeName,
                                                classifierRequestData.InstanceKey);


                    if (qrySource != null)
                    {
                        await qrySource.PostClassifierResponse(classifierRequestData.ClassifierRequest.DomainName,
                                                               classifierRequestData.ClassifierRequest.EntityTypeName,
                                                               classifierRequestData.ClassifierRequest.InstanceKey,
                                                               classifierRequestData.ClassifierRequest.ClassifierTypeName,
                                                               response.AsOfDate,
                                                               classifierRequestData.ClassifierRequest.CorrelationIdentifier,
                                                               response.AsOfSequence,
                                                               response.Result
                                                               );
                    }
                }
            }
        }
예제 #2
0
        public static async Task OnQueryClassificationHandler([EventGridTrigger] EventGridEvent eventGridEvent)
        {
            if (eventGridEvent != null)
            {
                // Get the data from the event that describes what classification is requested
                ClassifierRequestedEventGridEventData classifierRequestData = eventGridEvent.Data as ClassifierRequestedEventGridEventData;
                if (classifierRequestData != null)
                {
                    // handle the classifier request
                    ClassificationResponse response   = null;
                    Classification         classifier = new Classification(
                        new ClassificationAttribute(
                            classifierRequestData.ClassifierRequest.DomainName,
                            classifierRequestData.ClassifierRequest.EntityTypeName,
                            classifierRequestData.ClassifierRequest.InstanceKey,
                            classifierRequestData.ClassifierRequest.ClassifierTypeName
                            ));

                    if (classifier != null)
                    {
                        // get the classifier class - must implement TClassification : IClassification, new()
                        IClassification classificationToRun = Classification.GetClassifierByName(classifier.ClassifierTypeName);
                        if (classificationToRun != null)
                        {
                            response = await classifier.Classify(classificationToRun, null);
                        }
                    }

                    if (response != null)
                    {
                        // and post the result back to the query that asked for it
                        Query qrySource = new Query(classifierRequestData.DomainName,
                                                    classifierRequestData.EntityTypeName,
                                                    classifierRequestData.InstanceKey);


                        if (qrySource != null)
                        {
                            await qrySource.PostClassifierResponse(classifierRequestData.ClassifierRequest.DomainName,
                                                                   classifierRequestData.ClassifierRequest.EntityTypeName,
                                                                   classifierRequestData.ClassifierRequest.InstanceKey,
                                                                   classifierRequestData.ClassifierRequest.ClassifierTypeName,
                                                                   response.AsOfDate,
                                                                   classifierRequestData.ClassifierRequest.CorrelationIdentifier,
                                                                   response.AsOfSequence,
                                                                   response.Result
                                                                   );
                        }
                    }
                }
            }
        }
예제 #3
0
        private void ClassifyButton_Click(object sender, RoutedEventArgs e)
        {
            bool IsError = false;

            //jeżeli nie wybrano klasy decyzyjnej program domyślnie wybierze ostatnią kolumne
            if (ClassifyColumnCombo.SelectedItem == null)
            {
                DecisionColumn = AllRows.GetInstance().HeaderName.ToList().Count - 1;
            }
            else
            {
                DecisionColumn = ClassifyColumnCombo.SelectedIndex;
            }

            if (MetricCombo.SelectedItem == null)
            {
                Metric = MetricName.Euklides;
            }
            else
            {
                Metric = (MetricName)MetricCombo.SelectedItem;
            }
            //MessageBox.Show(Metric.ToString());

            k = Convert.ToInt32(NeighboursText.Text);
            if (k > AllRows.GetInstance().FullFile.Count)
            {
                MessageBox.Show("k nie moze byc wieksze od ilosci obiektow");
                IsError = true;
            }

            for (int i = 0; i < NewObjects[0].Value.Count - 1; i++)
            {
                if (NewObjects[0].Value[i] == "")
                {
                    MessageBox.Show("Uzupelnij wszystkie pola aby kontynuowac");
                    IsError = true;
                    break;
                }
            }

            if (!IsError)
            {
                Classification classificator = new Classification(k, Metric, DecisionColumn);
                string         decision      = classificator.Classify(NewObjects[0]);
                //MessageBox.Show(decision);
                NewObjects[0].Value[NewObjects[0].Value.Count - 1] = decision;
                dataGrid.ItemsSource = null;
                //Thread.Sleep(1000);
                dataGrid.ItemsSource = NewObjects;
            }
        }
        public static async Task <Tuple <string, bool> > AccrueInterestForSpecificAccount
            ([ActivityTrigger] IDurableActivityContext accrueInterestContext)
        {
            const decimal DEBIT_INTEREST_RATE  = 0.001M;
            const decimal CREDIT_INTEREST_RATE = 0.0005M;

            string accountNumber = accrueInterestContext.GetInput <string>();

            #region Tracing telemetry
            Activity.Current.AddTag("Account Number", accountNumber);
            #endregion

            if (!string.IsNullOrEmpty(accountNumber))
            {
                EventStream bankAccountEvents = new EventStream(new EventStreamAttribute("Bank", "Account", accountNumber));
                if (await bankAccountEvents.Exists())
                {
                    // Has the accrual been done today for this account?
                    Classification         clsAccruedToday = new Classification(new ClassificationAttribute("Bank", "Account", accountNumber, nameof(InterestAccruedToday)));
                    ClassificationResponse isAccrued       = await clsAccruedToday.Classify <InterestAccruedToday>();

                    if (isAccrued.Result != ClassificationResponse.ClassificationResults.Include)
                    {
                        // Get the account balance
                        Projection prjBankAccountBalance = new Projection(new ProjectionAttribute("Bank", "Account", accountNumber, nameof(Balance)));

                        // Get the current account balance, as at midnight
                        Balance projectedBalance = await prjBankAccountBalance.Process <Balance>(DateTime.Today);

                        if (null != projectedBalance)
                        {
                            Account.Events.InterestAccrued evAccrued = new Account.Events.InterestAccrued()
                            {
                                Commentary           = $"Daily scheduled interest accrual",
                                AccrualEffectiveDate = DateTime.Today  // set the accrual to midnight today
                            };
                            // calculate the accrual amount
                            if (projectedBalance.CurrentBalance >= 0)
                            {
                                // Using the credit rate
                                evAccrued.AmountAccrued        = CREDIT_INTEREST_RATE * projectedBalance.CurrentBalance;
                                evAccrued.InterestRateInEffect = CREDIT_INTEREST_RATE;
                            }
                            else
                            {
                                // Use the debit rate
                                evAccrued.AmountAccrued        = DEBIT_INTEREST_RATE * projectedBalance.CurrentBalance;
                                evAccrued.InterestRateInEffect = DEBIT_INTEREST_RATE;
                            }

                            try
                            {
                                await bankAccountEvents.AppendEvent(evAccrued, isAccrued.AsOfSequence);
                            }
                            catch (EventSourcingOnAzureFunctions.Common.EventSourcing.Exceptions.EventStreamWriteException)
                            {
                                // We can't be sure this hasn't already run...
                                return(new Tuple <string, bool>(accountNumber, false));
                            }
                        }
                    }
                }
            }
            return(new Tuple <string, bool>(accountNumber, true));
        }
예제 #5
0
 public double Classify(double[] inputValues)
 {
     return(classification.Classify(inputValues));
 }
예제 #6
0
        private void UpdateHistogramControl()
        {
            if (!IsFieldToRenderSelected)
            {
                return;
            }

            HistogramLabels = new List <string>();
            HistogramBreaks = new ObservableCollection <Tuple <double, string> >();

            IList <ColumnItem> columnItems = new List <ColumnItem>();

            Tuple <double, int> [] histo = Classification.Histogram(SelectedFieldToRender.Field, Bins);

            var breaks = Classification.Classify(SelectedClassificationMethod, SelectedFieldToRender.Field.Feature.FeatureClass, SelectedFieldToRender.Field.ESRIField, SelectedNumberOfClasses);

            //we have to skip the first one, for detailed information see Classify method
            breaks = breaks.Skip(1).ToArray();

            for (int i = 0; i < histo.Length; i++)
            {
                columnItems.Add(new ColumnItem(histo[i].Item2));

                HistogramLabels.Add(histo[i].Item1.ToString("0.00"));
            }

            for (int i = 0; i < breaks.Length; i++)
            {
                for (int j = 0; j < histo.Length; j++)
                {
                    if (breaks[i] > histo[j].Item1)
                    {
                        continue;
                    }
                    else
                    {
                        var existingBreak = HistogramBreaks.FirstOrDefault(t => t.Item1 == j - 0.5d);

                        if (existingBreak != null)
                        {
                            HistogramBreaks.Remove(existingBreak);
                            HistogramBreaks.Add(Tuple.Create(j - 0.5d,
                                                             existingBreak.Item2 + "  [" + (breaks[i]).ToString("0.0000") + "]"));
                        }
                        else
                        {
                            HistogramBreaks.Add(Tuple.Create(j - 0.5d, "[" + (breaks[i]).ToString("0.0000") + "]"));
                        }

                        break;
                    }
                }
            }

            HistogramData = columnItems;

            PropertyChanged.Notify(() => HistogramLabels);

            PropertyChanged.Notify(() => HistogramData);
            PropertyChanged.Notify(() => HistogramBreaks);
        }
        public static async Task <HttpResponseMessage> AccrueInterestRun(
            [HttpTrigger(AuthorizationLevel.Function, "POST", Route = @"AccrueInterest/{accountnumber}")] HttpRequestMessage req,
            string accountnumber,
            [EventStream("Bank", "Account", "{accountnumber}")]  EventStream bankAccountEvents,
            [Projection("Bank", "Account", "{accountnumber}", nameof(Balance))] Projection prjBankAccountBalance,
            [Classification("Bank", "Account", "{accountnumber}", nameof(InterestAccruedToday))] Classification clsAccruedToday)
        {
            // Set the start time for how long it took to process the message
            DateTime startTime = DateTime.UtcNow;

            if (!await bankAccountEvents.Exists())
            {
                // You cannot accrue interest if the account does not exist
                return(req.CreateResponse <ProjectionFunctionResponse>(System.Net.HttpStatusCode.Forbidden,
                                                                       ProjectionFunctionResponse.CreateResponse(startTime,
                                                                                                                 true,
                                                                                                                 $"Account {accountnumber} does not exist",
                                                                                                                 0)));
            }

            ClassificationResponse isAccrued = await clsAccruedToday.Classify <InterestAccruedToday>();

            if (isAccrued.Result == ClassificationResponse.ClassificationResults.Include)
            {
                // The accrual for today has been performed for this account
                return(req.CreateResponse <ProjectionFunctionResponse>(System.Net.HttpStatusCode.Forbidden,
                                                                       ProjectionFunctionResponse.CreateResponse(startTime,
                                                                                                                 true,
                                                                                                                 $"Interest accrual already done on account {accountnumber} today",
                                                                                                                 isAccrued.AsOfSequence),
                                                                       FunctionResponse.MEDIA_TYPE
                                                                       ));
            }


            // get the request body...
            InterestAccrualData data = await req.Content.ReadAsAsync <InterestAccrualData>();

            // Get the current account balance, as at midnight
            Balance projectedBalance = await prjBankAccountBalance.Process <Balance>(DateTime.Today);

            if (null != projectedBalance)
            {
                Account.Events.InterestAccrued evAccrued = new Account.Events.InterestAccrued()
                {
                    Commentary           = data.Commentary,
                    AccrualEffectiveDate = DateTime.Today  // set the accrual to midnight today
                };

                if (projectedBalance.CurrentBalance >= 0)
                {
                    // Using the credit rate
                    evAccrued.AmountAccrued = data.CreditInterestRate * projectedBalance.CurrentBalance;
                }
                else
                {
                    // Use the debit rate
                    evAccrued.AmountAccrued = data.DebitInterestRate * projectedBalance.CurrentBalance;
                }

                try
                {
                    await bankAccountEvents.AppendEvent(evAccrued, isAccrued.AsOfSequence);
                }
                catch (EventSourcingOnAzureFunctions.Common.EventSourcing.Exceptions.EventStreamWriteException exWrite)
                {
                    return(req.CreateResponse <ProjectionFunctionResponse>(System.Net.HttpStatusCode.Forbidden,
                                                                           ProjectionFunctionResponse.CreateResponse(startTime,
                                                                                                                     true,
                                                                                                                     $"Failed to write interest accrual event {exWrite.Message}",
                                                                                                                     projectedBalance.CurrentSequenceNumber),
                                                                           FunctionResponse.MEDIA_TYPE));
                }

                return(req.CreateResponse <ProjectionFunctionResponse>(System.Net.HttpStatusCode.OK,
                                                                       ProjectionFunctionResponse.CreateResponse(startTime,
                                                                                                                 false,
                                                                                                                 $"Interest accrued for account {accountnumber} is {evAccrued.AmountAccrued}",
                                                                                                                 projectedBalance.CurrentSequenceNumber),
                                                                       FunctionResponse.MEDIA_TYPE));
            }
            else
            {
                return(req.CreateResponse <ProjectionFunctionResponse>(System.Net.HttpStatusCode.Forbidden,
                                                                       ProjectionFunctionResponse.CreateResponse(startTime,
                                                                                                                 true,
                                                                                                                 $"Unable to get current balance for account {accountnumber} for interest accrual",
                                                                                                                 0),
                                                                       FunctionResponse.MEDIA_TYPE
                                                                       ));
            }
        }