Category Archives: Programiranje

MSNetwork 3: Paralelno i asinhrono programirnje primjeri i prezentacijska datoteka


msnetwork

U ovom postu pobrojani su svi demo primjeri  sa kratkim objašnjenjem koje sam na MSNetwrok 3 predavanju demonstrirao. Ovo ujedno i predstavlja moje aktivnosti zadnjih nekoliko godina vezanih oko ove teme.

Tačno prije 5 godina odnosno u aprilu 2008 godine (22. aprila 2008.) napisao sam prvi članak oko paralelnog programiranja, dok je 5 mjeseci ranije te godine izbačena prva CTP verzija ParallelFx biblioteke.

Ovim MSNetwork predavanjem želio sam ujedno i da sve to objedinim i da široj javnosti prenesem iskustva iz ovog područja programiranja. Ovaj blog post sadrži izvorni kod za sve demo primjere koji su planirani za ovo predavanje. Moguće je, (jer blog post pišem ranije) da neki od primjera nije demonstriran zbog vremena, pa ovom prilikom ih objavljujem sviju sa kratkim pojašnjenjem.

Ukupno za ovo predavanje planirano je 9 demo primjera i to:

1. Power point prezentacija predavanja.

2. Demo primjeri sa predavanja

Primjer manipulacije sa objektom Thread, i kako manipulisati u višenitnom okruženju.
Primjer manipulacije sa Task objektom, kao osnovnim konceptom pralelnog i asinhronog programiranja.
Demo sadrzi 5 različitih primjera korištenja for, foeach, parallelLoopState i primjer koordinacije i razmjene podataka izmedju niti.
PLINQ primjer koristenja paraleliziranih LINQ upita.
Primjer korištenja Partisionera, kojim dijelimo poslove na više taskova.
Primjer koji demonstrira Race Condition fenomen kada dvije niti u isto vrijeme pokusavaju da promjene vrijednost varijable.
Realni primjer primjene ParallelFx u rjesavanju sistema linearnih jednačina sa 1000 nepoznatih.
Primjer asinhronog programiranja na strani klijenta. Kako stari sekvencijalni kod pretvoriti u asinhroni.
Primjer asinhronog programiranja na strani servera. Korištenje asinhronog programiranja u optimizaciji ASP.NET aplikacija i mogućnosti povećavanja performansi i odziva aplikacija.

How to convert your old sequential code in to async


There are plenty of ansyc samples over the internet, and most of them are different and not satisfy your requirements. Actually, async pattern depends of its creator, and can be implement on various ways. It is important to understand the async pattern in order to use it. Only on this way, you can stop searching for exact sample you need, and start coding your own async code.  More that year ago, I wrote simple blog post about async pattern (part 1 and part 2) (Bosnian language), and also wrote how to call Entity Framework with async pattern as well.

Today I am going to show you how old synchronous code block convert in to asynchronous. I think it is interesting because async pattern can improve your existing applications on various ways. First of all async pattern can increase responsiveness of  an application, performance, etc.

First of all, create simple Windows Forms sample and implement synchronous code.This will represent our old application, in which we are going to implement new programming paradigm.

1. Create Windows Forms Project, Name it “WinFormsAsyncSample

2. Design your main form (Form1.cs) exactly as picture shows below, and implement events.

As picture shows we have few labels, one text box, one progress bars, and two buttons.

Note: At the end of the blog you can download both versions (nonasync and async) of this sample.

The sample application calculates how many prime numbers exist in range. You need to enter number, press run button. The program starts counting. The progress bars informs user status of counting.

Lets see the implementation of runBtn_Click event:

private void btnRun_Click(object sender, EventArgs e)
{
    if(!int.TryParse(textBox1.Text,out m_number))
        m_number= 1000000;

    textBox1.Text = m_number.ToString();
    progressBar1.Maximum = m_number;
    progressBar1.Minimum = 0;
    progressBar1.Value = 0;

    //call start calculation
    startCounting();
}

At the beginning of the btnRun_Click we prepare progressBar, and also convert text from textbox in to int type.At the end of the function startConting method is called. Here is the source code of the method:

private void startCounting()
{
    int counter=0;
    for(int i=2;i<m_number; i++)
    {
        bool retVal= IsPrime(i);
        progressBar1.Value++;
        if (retVal)
        {
            counter++;
            label3.Text = "Result is: " + counter.ToString();
        }
    }
}

The method is very simple. It iterates from 2 to specified number by calling helper method IsPrime (see source code of the blog post) to check if certain number is prime. Then the method increased the counter variable and tried to update label about current count value.  If  you run the sample and press run button, you can see that the application is not responsive on user input, and represent classic sequential, synchronous single thread application.

Now I am going to show how this implementation can be converted in to async with minimum code changes.We are going to change only startCounting method, other code will remain the same. Explanation is divided in only 3 steps, which is enough to convert our code in to full async pattern.

  • Put async keyword right after public modifier of startCounting method.

Explanation: Every method which implements async patter needs to be decorated with async.

  • Put sequential implementation in to Task action, and wait.

Explanation: With this, you define a Task object which will run the code without blocking main thread. The simplest implementation is the following:

private async void startCalculation()
{
    var task = new Task(() =>
        {
            int counter = 0;
            for (int i = 2; i < m_number; i++)
            {
                bool retVal = IsPrime(i);

                this.Invoke((Action)(()=>
                {
                    progressBar1.Value++;
                    if (retVal)
                    {
                        counter++;
                        label3.Text = "Result is: " + counter.ToString();
                    }

                }));
            }
        });

    task.Start();
    await task;
}

Now if you run the sample, you have fully asynchronous implementation. Main thread is free and can receive user input. So this is the simplest way how to convert your sync code in to async. This is the case when Task object create another thread in order to execute the code. That’s why we called this.Invoke method in order to set controls properties progressBar.Value and label3.Text. Everything else remain the same as in previous implementation.

  • Create global variable of type CancellationTokenSource and call Cancel method from Cancel Event handler.

Explanation: On this way we can cancel counting at any time.With this case we need to implements extra code in our previous implementation like the following.

private async void RunProces()
{
    if (m_IsRunning)
        return;
    m_IsRunning = true;
    int counter=0;
    if (m_ct != null)
    {
        m_ct.Dispose();
        m_ct = null;
    }
    m_ct = new CancellationTokenSource();

    var task = new Task(() =>
        {
            for (int i = 0; i < m_number; i++)
            {
                bool retVal = IsPrime(i);

                this.Invoke((Action)(()=>
                {
                    progressBar1.Value++;
                    if (retVal)
                    {
                        counter++;
                        label3.Text = "Result is: " + counter.ToString();
                    }

                }));

                if (m_ct.IsCancellationRequested)
                {
                    m_IsRunning = false;
                    return;
                }
            }
        }, m_ct.Token);

    task.Start();
    await task;
}

With the last code implementation you have full of async patter in yur old application.

In this blog post I have tried to explain as simple as possible the way how you can convert you old sync code in to new async programming pattern.

Source code sample used in this blog post:

On this link you can find sequential version of the sample.

On this link you can find the final solution of async pattern.


			

Kako zaokružiti iznos na 5 pfeninga u C#


Kao što je mnogima poznato u Bosni i Hercegovini ne postoji novčanica od 1 pfening, ali kada odete u granap često puta će te dobiti račun koji vam prodavačica ne može naplatiti jer ne postoje novčanice od 1 odnosno 2 pfeninga. Više informacija oko BH novčanica možete pogledati ovdje. Neki ovu pojavu iskorištavaju, a neki se pokušavaju prilagoditi na način da se na računu ne pojavljuju iznosi koji sadrže 1,2,3,4,6,7,8,9 pfeniga kao posljednju cifru računa.

U tu svrhu potrebno je standardno zaokruživanje koje postoji u C# poput Floor, Ceiling, Turncate obogatiti ovim bosanskim fenomenom te zaokruživati na najbliži broj 0 ili 5. U tu svrhu u narednom tekstu se nalazi implementacije metode koja ovu funkcionalnost implementira.

Potrebno je prvo iznos podjeliti sa 10 da se dobije vrijednost iza zareza u pfeninzima, a onda pogodnim ispitivanjima zaokružiti na bliži broj. Pogledajte implementaciju.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ZaokruzivanjeNaPolaPfeninga
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(
                            "Iznos od  {0} KM se zaokruživa na {1}", 
                             17.61, ZaokruziNa5Feninga(17.61m).ToString("N2"));
            Console.WriteLine(
                            "Iznos od  {0} KM se zaokruživa na {1}", 
                            17.62, ZaokruziNa5Feninga(17.62m).ToString("N2"));
            Console.WriteLine(
                            "Iznos od  {0} KM se zaokruživa na {1}", 
                            17.63, ZaokruziNa5Feninga(17.63m).ToString("N2"));
            Console.WriteLine(
                            "Iznos od  {0} KM se zaokruživa na {1}", 
                            17.64, ZaokruziNa5Feninga(17.64m).ToString("N2"));
            Console.WriteLine(
                            "Iznos od  {0} KM se zaokruživa na {1}", 
                            17.65, ZaokruziNa5Feninga(17.65m).ToString("N2"));
            Console.WriteLine(
                            "Iznos od  {0} KM se zaokruživa na {1}", 
                            17.66, ZaokruziNa5Feninga(17.66m).ToString("N2"));
            Console.WriteLine(
                            "Iznos od  {0} KM se zaokruživa na {1}", 
                            17.67, ZaokruziNa5Feninga(17.67m).ToString("N2"));
            Console.WriteLine(
                            "Iznos od  {0} KM se zaokruživa na {1}", 
                            17.68, ZaokruziNa5Feninga(17.68m).ToString("N2"));
            Console.WriteLine(
                            "Iznos od  {0} KM se zaokruživa na {1}", 
                            17.69, ZaokruziNa5Feninga(17.69m).ToString("N2"));
            Console.WriteLine(
                            "Iznos od  {0} KM se zaokruživa na {1}", 
                            17.70, ZaokruziNa5Feninga(17.70m).ToString("N2"));
            ///
            Console.WriteLine("Press any key to continue...");
            Console.Read();
        }

        private static decimal ZaokruziNa5Feninga(decimal iznos)
        {
            iznos *= 10;

            decimal cijelo = Math.Truncate(iznos);
            decimal ostatak = iznos - cijelo;

            if (ostatak < 0.29999999m)
                 ostatak = 0;
            else if (ostatak < 0.8m)
                 ostatak = 0.5m;
            else
               ostatak = 1m;

            return (cijelo + ostatak)/10.0m;
        }
    }
}

Skrgic Selection in GPdotNET


Introduction

This document presents Skrgic Selection Method, the one of several selection methods in GPdotNET. While I was developing GPdotNET I have had several conversation with my friend Fikret Skrgic (master in computer scinence and math) regarding selection in Evolutionary algorithms. He is an incredible man, and in just a few minutes while I was describing to him what I want from a new way of selection, he came out with the basic idea of the new selection method. After that time in just a few mails I had a new selection method ready for implementation in GPdotNET. I gave the name to the new selection method by his surname. It is a little thankfulness to him.

In the flowing text it will be presented the idea behind Skrgic Selection.

Liner Skrgic Selection (LSS)

The Idea behind this selection is based on chromosome fitness. The rule is simple: The bigger chromosome fitness gives bigger chance to select better chromosome. In Population, chromosomes are already sorted from best to worst chromosomes.
The process of selection is the following:

  1. Find the maximum and minimum fitness value from the population.
  2. The best chromosome (maximum fitness) has position 0 in the population (zero based index), and the worst chromosome has index N-1.
  3. Let’s give them name as f_{max} and f_{min} respectively.
  4. Choose random number r between f_{min} and f_{max}.
  5. Choose random chromosome from the Population chrom.
  6. Compare the values of r and f_{chrom}. If the f_{chrom} is greater than r, select chrom.
  7. Repeat steps 3 and 4 until you select one chromosome.
  8. Repeat steps 2,3,4,5 until you select n chromosomes.

The following picture shows graph of linear Skrgic selection:

Linear Skrgic Selection (LSS)

Nonlinear Skrgic Selection (NSS)

In LSS we have linear graph of selection probability. This means that if we have chromosome with f_{chrom} fitness value, and another chromosome with \frac{f_{chrom}}{2} fitness value, the probability of selection of two chromosomes is p and \frac{p}{2} respectively. This means that probability of selection is growing linearly.
If we want to change probability between chromosomes we can define a factor k to be like selection pressure on whole chromosomes in the population. So let the k be a real value, and define the fitness of each chromosome as:

f_{nss}=f_{chrom} (1+k \frac{f_{chrom}}{f_{max}}),

where:

  • f_{chrom} – fitness value of the chromosome,
  • f_{max} – maximum fitness value(fitness of the best chromosome of the population),
  • k – selection pressure,
  • f_{nss} – nonlinear fitness value of the chromosome.

We can conclude that the maximum nonlinear fitness value of the best chromosome is given by:

f_{max(nss)}=f_{max}(1+k).

For various value of parameter k  we can define graph of probability selection like on the following picture:

Graph for various sample of NonLinear Skrgic Selection (NLSS)

On the picture above we can see if k=0 we get the standard Linear Skrgic Selection (LSS). We can also conclude that there is a fitness value when the probability of selection is constant and not depends of parameter k. Very interesting graph is when the k=-1. In this case the selection probability of the worst and the best chromosome are equal.

GPdotNET settings of GP parameters

Follow

Get every new post delivered to your Inbox.

Join 409 other followers

%d bloggers like this: