Wednesday, March 15, 2023

Pi Day and the genius mathematician from Bharat - Ramanujan

 


The genius mathematician who used to dream Maths formulas


Ramajunan lived just 32 years - but created history in Maths which shows the brain power of Bharat.

But again, due to colonialism, we celebrated this genius once he was celebrated abroad - in England - the same way Swami Vivekananda and Rabindranath Tagore were termed genius only after they became iconic figures abroad.

The way Mozart used to visualize the music, this genius from Bharat used to dream of Maths.

The first letter he wrote to a famous British Mathematician G H Hardy, contained 120 Maths formulas but no demonstration of how he got all these formulas.

This forced the British mathematician to almost pooh-pooh Ramanujan, but in the end, even he said, all these formulas must be true - otherwise how one could ever imagine them.

Let me conclude this write-up with only one request to the Humans of Bharat - you have already wasted a very long period of time in hibernation - now it's time for you to wake up and reclaim your true spirit - the Vishwaguru Bharat.

I am really happy to see that Baharat has come up with her own designed railways locomotive - which can make even the technologies of Japan envy us. We have come up with our indigenous Kabach - the shield - to be used in the Railways as safety norms.

The possibilities are infinite.

Only we have to change the mindset - we are here to contribute to the global community as Vishwaguru Bharat.

This is the true nature of Bharat - let us change the global perception of Bharat

From the takers to the givers

we have a lot of stuff to give to the UNIVERSE - just as Vishwaguru Bharat

Jai Hind...

Monday, March 13, 2023

A new journey restarted - the beginner's step - Monte Carlo Methpd

Monte Carlo Simulation, also known as the Monte Carlo Method or a multiple probability simulation, is a mathematical technique, which is used to estimate the possible outcomes of an uncertain event. The Monte Carlo Method was invented by John von Neumann and Stanislaw Ulam during World War II to improve decision-making under uncertain conditions.


Unlike a normal forecasting model, Monte Carlo Simulation predicts a set of outcomes based on an estimated range of values versus a set of fixed input values.

Example 1

Problem: the probability of three heads and two tails for a coin tossed five times (assuming a fair coin)

# Answer (from Maths Probability theory) : binomial(3 + 2, 3) 2^(-(3 + 2)) = ((3 + 2)!)/(3! 2! 2^(3 + 2))= 5/16 ≈ 0.3125

Example 2

Problem: The probability of getting three consecutive Heads at the beginning if a coin is tossed 5 times

# Answer (Using Probability theory): ½ X ½ X 1/2  = ⅛ = 0.125


The Mathematical model of Monte Carlo written in Python

Problem 1

def calculateprobability1(attempts):
success = 0
for i in range(0, attempts):
if (random.randint(0, 1) + random.randint(0, 1) +
random.randint(0, 1) + random.randint(0, 1)
+ random.randint(
0, 1)) != 3:
pass
else:
success += 1
print("Number of attempts = ", attempts)
print("Number of success = ", success)

return success / attempts


Problem 2

def calculateprobability2(attempts):
success = 0
for i in range(0, attempts):
if (random.randint(0, 1) == 1 and random.randint(0, 1) == 1
and random.randint(0, 1) == 1):
success += 1
else:
pass
print("Number of attempts = ", attempts)
print("Number of success = ", success)

return success / attempts



The Monte Carlo examples implemented in Python...

Thursday, March 9, 2023

Factory Pattern in Python...

 I used to get the utmost satisfaction by deciphering framework code. I remember, initially, I used to study the MFC framework code and came to know about observer patterns, about the chain of responsibility design patterns being used there.

Later, I used to study the Symbian S60 framework code - and studied in detail their Active Object design principles and ECom plugins.

Yes, I am talking about 2006-2007 just before the arrival of the iPhone and Android when NOKIA was the undisputed leader in the mobile world.

Please have a look at the following blog post where I deciphered the basic Active Object of the Symbian framework and why a long-running task does not freeze the UI.

So the point is, don't blindly follow anything. Keep your inquisitive mind always ready for new stuff. For example, my inquisition about the two-phase constructor in Symbian led me to study the Boost library in 2007 in Japan which ultimately became part of the C++ standard library in the 2009 release of C++.

Symbian Active Object framework...




Then when i switched over to Android, I started studying the Android framework code.

For example here are two such detailed study analyses on Asynctask and Android Service Framework


Asynstask Framework...




Android Service internals...




This has changed my mindset from looking at code from just a programmer's perspective. I try to find out the design principles and try to join the invisible dots inside the framework code.

For example, when i found the parameterized factory pattern implementation in the Android framework code, my vision becomes clearer than the vision of a programmer.

Please have a look at the following document where i studied that part of the Android media framework where the parameterized factory pattern is used.






So, here we go - an implementation of Factory Pattern in Python.

from abc import ABC,abstractmethod


class Food(ABC):

   pass

class Chocolate(Food):

   def __init__(self):

       print("chocolate is made")

class Biscuit(Food):

   def __init__(self):

       print("biscuit is made")


class Factory:

   def makefood(self,type):

       if(type == "ch"):

           return Chocolate()

       if(type == "bi"):

           return Biscuit()

if __name__ == '__main__':

   fact = Factory()

   chocolate = fact.makefood("ch")

   biscuit = fact.makefood("bi")



Friends... Enjoy...
Just start deciphering a framework code...
And become happy in your endeavor...

Observer Pattern in Python...

The observer design pattern is a very popular design pattern in the Object Oriented world. I must admit, I first saw the utilities of this design pattern while studying the document view architecture of the MFC source code.

Later on, I used this pattern in many places.

There is a lot of similarity between the Observer Pattern, the Callback mechanism, and the Event Handler process in Java. Usually, the callback method is used when there is only one observer who awaits the signal from the observee.

So, let me put it in this fashion.

Suppose, there is a central document that is viewed by a few applications - someone is viewing it in a spreadsheet, someone as a Pie chart, and so on.

Now if the data in the document is updated, all the viewers must be updated and they should synchronize their views with the latest data set. So basically all the viewers were observing the central data. The moment it changes, all the observers get their respective views updated.

Here goes the Python code for this observer pattern

from __future__ import annotations

from abc import ABC,abstractmethod

from typing import List

class Subject(ABC):

   @abstractmethod

   def addObserver(self,observer):

       pass

   @abstractmethod

   def removeObserver(self,observer):

       pass

   @abstractmethod

   def notifyObservers(self):

       pass

class ConcreteSubject(Subject):

   _observers = []

   _state = "my current state"

   def addObserver(self,observer):

       self._observers.append(observer)

   def removeObserver(self,observer):

       self._observers.remove(observer)

   def notifyObservers(self):

       for observer in self._observers:

           observer.update()

   def dosomething(self):

       print("I am doing something which will change my state.Notifying observers")

       self._state = "subject state has been changed"

       self.notifyObservers()

class Observer(ABC):

   @abstractmethod

   def update(self):

       pass

class ConcreteObserver(Observer):

   def __init__(self,subject):

       self._subject = subject

   def update(self):

       print(self._subject._state)

if __name__ == '__main__':

   concretesubject = ConcreteSubject()

   observer1 = ConcreteObserver(concretesubject)

   observer2 = ConcreteObserver(concretesubject)

   concretesubject.addObserver(observer1)

   concretesubject.addObserver(observer2)

   concretesubject.dosomething()


For all other inquisitive student communities, here goes my training on Observer Pattern in Java


And for all the Bengali medium students, here we go


Observer Pattern in Bengali...

Wednesday, March 8, 2023

The Proxy Pattern in Python...

Proxy pattern - as the name suggests - creates a proxy in place of a real heavy-duty object.

Let me give you a real-life example taken from computer science.

In case a document contains many huge-sized images, it does not load all the images when the doc gets loaded into the memory. Because it might take a very long time. 

The proxy pattern comes as a rescue. 

The document, instead of the actual mega images, gets loaded with very lightweight proxies of those images. And then when needed - in actual run time, i.e., when we need to see an image, the images get loaded by the proxy. This kind of proxy is called a virtual proxy.

Now let us talk from our example.

We are a family of three. Now my son does all the lightweight jobs - like, if there is a guest, he opens the door. So, he is the initial interface for the guests. However, in case, a guest wants to have lunch or dinner, my son calls his Mamma - because it's a heavy-duty job that he himself cannot do.

So basically my son gives proxy to his Mom, and if needed - like when he has to perform a heavy-duty job like cooking - he simply delegates the task to his Mom. For all other lightweight jobs, his Mom, who obviously has a lot of significant jobs to perform, remains in the background. She comes in the foreground in case there is a heavy-duty task like cooking for a guest.

Here's the source code of the Proxy Pattern implemented in Python.

Enjoy.


from abc import ABC,abstractmethod
class FamilyMember(ABC):
@abstractmethod
def openTheDoor(self):
pass
def cook(self):
pass

class Mamma(FamilyMember):
def openTheDoor(self):
print("Son will open the door")

def cook(self):
print("Mamma is cooking")

class Son(FamilyMember):
def __init__(self):
self.mamma = Mamma()

def openTheDoor(self):
print("Son opens the door")
def cook(self):
print("Son does not know how to cook He was just giving proxy for mamma")
self.mamma.cook()

class Home():
def __init__(self):
self.son = Son()

def openTheDoor(self):
self.son.openTheDoor()


def preparefood(self):
self.son.cook()
if __name__ == '__main__':
home = Home()
home.openTheDoor()
home.preparefood()


The State Pattern in Python...

 In the State Design Pattern, the same object behaves differently depending on the current state of the object.

For example, take the case of Chicken preparation.

When it is delivered, it remains in an uncleaned state. Hence the first task will be to clean it. 

At that time if you call a specific method of the Chicken State, say, cook, it will behave differently (say maybe flash out a message that the chicken can't be cooked until it is properly cleaned and marinated). But the same cook method will cook the chicken once it is in the Marinated State. This time the "cook" method will properly cook the chicken and will flash out a different message - maybe like the Chicken is getting cooked - so have patience.

In the example, we have a ChickenState interface and then Mamma as the chef. The transition from one state to another is done at the end of the appropriate method of the interface at each state.

Enjoy the State Pattern written in written in Python


from __future__ import annotations
from abc import ABC, abstractmethod
import time

class Mamma():
def __init__(self, state):
self._state = state


def getstate(self):
return self._state


def setstate(self, state):
self._state = state


def startpreparation(self):
self._state.wash()
self._state.marinate()
self._state.cook()
self._state.serve()




class State(ABC):
@abstractmethod
def wash(self):
pass


@abstractmethod
def marinate(self):
pass


@abstractmethod
def cook(self):
pass


@abstractmethod
def serve(self):
pass




class UncleanedState(State):
def __init__(self, mamma):
self._mamma = mamma


def wash(self):
print("chicken is in the uncleaned state and is getting cleaned:next state will be cleaned state")
time.sleep(1)
self._mamma.setstate(CleanedState(self._mamma))


def marinate(self):
print("chicken is in the uncleaned state...first clean it")
pass


def cook(self):
print("chicken is in the uncleaned state...first clean it")
pass


def serve(self):
print("chicken is in the uncleaned state...first clean it")
pass




class CleanedState(State):
def __init__(self, mamma):
self._mamma = mamma


def wash(self):
print("chicken is in the cleaned state...wash already done")
pass


def marinate(self):
print("chicken is in the cleaned state and is marinated. next state will be marinate state")
time.sleep(1)
self._mamma.setstate(MarinateState(self._mamma))


def cook(self):
print("chicken is in the cleaned state...first marinate it")
pass


def serve(self):
print("chicken is in the cleaned state...first marinate it")
pass




class MarinateState(State):
def __init__(self, mamma):
self._mamma = mamma


def wash(self):
print("chicken is in the marinated state...cleaning already done")
pass


def marinate(self):
print("chicken is in the marinated state...marination already done")
pass


def cook(self):
print("chicken is in the marinated state and being cooked. :next state will be cooked state")
time.sleep(1)
self._mamma.setstate(CookedState(self._mamma))


def serve(self):
print("chicken is in the marinated state and being cooked. only after cooking u can serve...")
pass




class CookedState(State):
def __init__(self, mamma):
self._mamma = mamma


def wash(self):
print("chicken has already being cooked")
pass


def marinate(self):
print("chicken has already being cooked")
pass


def cook(self):
print("chicken has already being cooked")
pass


def serve(self):
print("chicken is ready and is served : this is the last state")
time.sleep(1)


print("guest are saying thank you for the meal")


if __name__ == '__main__':
mamma = Mamma(None)
mamma.setstate(UncleanedState(mamma))
mamma.startpreparation()







Tuesday, March 7, 2023

The Command Pattern in Python...

When I taught my son #Ridit and many other students about Python, I had to cover the subject of the Design Patterns implemented in Python.

That was almost 2 years ago.

Now again as my son is planning to delve into Fluid Simulation, there are some software in which the scenes are developed in Python.

Hence, again I am trying to open the PyCharm and practicing Python.

Here is the Command Pattern being implemented in Python.

We have taken the same Restaurant problem which has Chef, Waiter, and Order classes participating in this design pattern.

The idea of Command Pattern is that the decoupling between the invoker of the command and the executor.

The command is kind of a full-fledged object having all knowledge about the executor of the command meaning the command will have a reference to the executor of the command.

The waiter is working as the invoker and the chef is working as the executor of the command.

Here we go.

The Source Code


from abc import ABC , abstractmethod
import time
class Item:
    def __init__(self,name,price):
        self.name = name
        self.price = price
class ItemOrder:
    def __init__(self,item,numberOfPlates):
        self.item = item
        self.numberOfPlates = numberOfPlates
class Order:
    def __init__(self):
    	self.itemorders = []
    def getItemOrder(self):
        return self.itemorders
#executor
class Chef(ABC):
    @abstractmethod
    def prepare(self):
        pass


class ChefTeaCoffe(Chef):
    def prepare(self,order):
        for itemorder in order.itemorders:
            if "Tea" in itemorder.item.name:
                print(str(itemorder.numberOfPlates) + " cups of " + itemorder.item.name + " is being prepared")
                time.sleep(5)
                

class ChefFood(Chef):
    def prepare(self,order):
        for itemorder in order.itemorders:
            if "Food" in itemorder.item.name:
                print(str(itemorder.numberOfPlates) + " plates of " + itemorder.item.name + " is being prepared")
                time.sleep(5)
                
#command
class Command(ABC):
    @abstractmethod
    def execute(self):
        pass
class TeaCoffeeCommand(Command):
    def __init__(self,chef,order):
        self.chef = chef
        self.order = order

    def execute(self):
        self.chef.prepare(self.order)

class FoodCommand(Command):
    def __init__(self,chef,order):
        self.chef = chef
        self.order = order

    def execute(self):
        self.chef.prepare(self.order)
#invoker
class Waiter:
    def setCommand(self,command):
        self.command = command

    def giveCommandToChef(self):
        self.command.execute()


if __name__ == '__main__':
    itemTea = Item("Tea",40)

    itemBread = Item("Food", 20)

    itemOrderTea = ItemOrder(itemTea, 3)

    itemOrderBread = ItemOrder(itemBread, 4)

    orderTea = Order()
    orderFood = Order()

    orderTea.itemorders.append(itemOrderTea)
    orderFood.itemorders.append(itemOrderBread)

    chefTea = ChefTeaCoffe()
    chefFood = ChefFood()

    commandTeaCoffee = TeaCoffeeCommand(chefTea, orderTea)
    commandFood = FoodCommand(chefFood, orderFood)

    waiter = Waiter()
    waiter.setCommand(commandTeaCoffee)
    waiter.giveCommandToChef()

    waiter.setCommand(commandFood)
    waiter.giveCommandToChef()

Here is my son, Ridit, explaining the command design pattern implemented in Python.
I hope you will like it.