Friday, August 8, 2025

The story of Pybinding - a python wrapper around C++...

Pybinding isn't a single, monolithic tool, but rather a concept that has been realized by several different libraries. The most prominent and widely used among them is pybind11. The story of pybind11 is a testament to the enduring need for high-performance computing in Python and the elegant solutions that can arise from a desire for simplicity and efficiency.

The story starts with a common problem: Python is a fantastic language for rapid prototyping, data analysis, and orchestrating complex tasks. However, when it comes to raw computational speed, especially for number-crunching or highly parallelized operations, it can fall short. C++ and other compiled languages, on the other hand, excel in these areas. The question was, how do you get the best of both worlds? How do you write the performance-critical parts of your application in C++ while still enjoying the development speed and ecosystem of Python?

The answer was to create a "binding" – a bridge that allows Python to call C++ code as if it were native Python. Early efforts in this space, such as Boost.Python, were powerful but often came with a steep learning curve and significant compilation overhead. They were a bit like using a sledgehammer to crack a nut – effective, but perhaps a bit unwieldy for many use cases.

This is where the next chapter of the story begins, with the emergence of pybind11. The creator of pybind11, Wenzel Jakob, had a vision for a library that would be:

  • Lightweight and Header-Only: No need to link against a large library. You just include the headers, and the magic happens at compile time.

  • Easy to Use: The syntax should feel "Pythonic" and intuitive, allowing developers to create bindings with minimal boilerplate code.

  • Efficient: The generated code should be fast and have a small binary footprint.

  • Modern: It should fully embrace modern C++ standards, like C++11 and beyond, to take advantage of features like move semantics and templates.

Pybind11 was born from this vision, and it quickly gained traction. It told a new story about how C++ and Python could work together. Instead of a cumbersome, complex process, creating a Python wrapper became a straightforward task.

The story of using pybind11 often goes something like this:

The Setup: A scientist or developer has a C++ library with a highly optimized algorithm. Let's say it's a function that performs a complex matrix multiplication. They want to use this function from their Python scripts, where they are handling data loading, visualization, and other tasks.

The Binding: They write a small C++ file that acts as the "wrapper." This file includes the pybind11 headers and uses its simple syntax to expose the C++ function to Python. They define a Python module, give their C++ function a Python-friendly name, and specify the types of arguments it takes. Pybind11 automatically handles the conversion between Python's data types (like NumPy arrays) and C++'s native types (like std::vector or Eigen matrices).

The Compilation: Using a build system like CMake, they compile this wrapper file. The result is a shared library (.so or .dll) that Python can import.

The Payoff: Back in their Python script, they can now simply import the newly created module and call the C++ function directly. The performance-critical work is handled by the blazing-fast C++ code, while the rest of the application remains in the flexible and easy-to-manage world of Python.

So... here we go...

My exploration of Pybinding11 to refactor one of my projects called FactoryDesignPattern.

Here's the source code...

/*

* Food.h

*

* Created on: Mar 10, 2021

* Author: som

*/


#ifndef FOOD_H_

#define FOOD_H_

#include <string>


using namespace std;


class Food {

public:

virtual string getName() = 0;


virtual ~Food(){


}

};



#endif /* FOOD_H_ */



/*

* Biscuit.h

*

* Created on: Mar 10, 2021

* Author: som

*/


#ifndef BISCUIT_H_

#define BISCUIT_H_


#include "Food.h"


class Biscuit: public Food {

public:

Biscuit();

string getName();

~Biscuit();

};


#endif /* BISCUIT_H_ */


/*

* Biscuit.cpp

*

* Created on: Mar 10, 2021

* Author: som

*/

#include <iostream>

#include "Biscuit.h"

using namespace std;



Biscuit::Biscuit() {

// TODO Auto-generated constructor stub

cout<<"Biscuit is made..."<<endl;


}


Biscuit::~Biscuit(){}



string Biscuit::getName(){

return "It's a Biscuit";

}


/*

* Chocolate.h

*

* Created on: Mar 10, 2021

* Author: som

*/


#ifndef CHOCOLATE_H_

#define CHOCOLATE_H_


#include <iostream>

#include "Food.h"


class Chocolate: public Food {

public:

Chocolate();

virtual ~Chocolate();

string getName();

};



#endif /* CHOCOLATE_H_ */


/*

* Chocolate.cpp

*

* Created on: Mar 10, 2021

* Author: som

*/


#include "Chocolate.h"



Chocolate::Chocolate() {

// TODO Auto-generated constructor stub

cout<<"Chocolate is made..."<<endl;


}


Chocolate::~Chocolate() {

// TODO Auto-generated destructor stub

}


string Chocolate::getName(){

return "It's a Chocolate";

}


/*

* Factory.h

*

* Created on: Mar 10, 2021

* Author: som

*/


#ifndef FACTORY_H_

#define FACTORY_H_


#include <pybind11/pybind11.h>

#include <iostream>

#include <string>


#include "Biscuit.h"

#include "Chocolate.h"


using namespace std;


class Factory{

public:

static Factory* instance;

static Factory* getInstance();


Food* makeFood(const string& type);


private:

Factory(){}


// Delete copy constructor & assignment operator (Singleton pattern)

Factory(const Factory&) = delete;

Factory& operator=(const Factory&) = delete;

};

//Factory* Factory:: instance = NULL;



#endif /* FACTORY_H_ */


/*

* Factory.cpp

*

* Created on: Jan 30, 2025

* Author: som

*/

#include "Factory.h"

Factory* Factory::instance = NULL;


Factory* Factory:: getInstance(){

if(Factory::instance == NULL){

Factory::instance = new Factory();

}

return Factory::instance;

}


Food* Factory::makeFood(const string& type){

if(type.compare("bi") == 0){

return new Biscuit();

}

if(type.compare("ch") == 0){

return new Chocolate();

}


return NULL;

}




//bindings.cpp


#include <pybind11/pybind11.h>

#include <memory>


#include "Food.h"

#include "Factory.h"

#include "Biscuit.h"

#include "Chocolate.h"


namespace py = pybind11;


PYBIND11_MODULE(libfoodfactory, m) {

py::class_<Food, std::shared_ptr<Food>>(m, "Food")

.def("get_name", &Food::getName);


py::class_<Biscuit, Food, std::shared_ptr<Biscuit>>(m, "Biscuit")

.def(py::init<>());


py::class_<Chocolate, Food, std::shared_ptr<Chocolate>>(m, "Chocolate")

.def(py::init<>());


m.def("make_food", [](const std::string& type) -> std::shared_ptr<Food> {

Food* f = Factory::getInstance()->makeFood(type);

if (!f) throw std::runtime_error("Unknown food type");

return std::shared_ptr<Food>(f); // manage memory in Python

});

}


Here's the CMakeLists.txt


cmake_minimum_required(VERSION 3.10)


# Set some basic project attributes

project (FactoryPattern_pybind)


set(CMAKE_CXX_STANDARD 14)


# Set the prefix path to where pybind11 is installed,

# allowing CMake to find its configuration files.

# This assumes pybind11 was installed via pip.

list(APPEND CMAKE_PREFIX_PATH "/home/som/.local/lib/python3.8/site-packages")


# Find the pybind11 package. The REQUIRED keyword ensures

# the build fails if the package isn't found.

find_package(pybind11 REQUIRED)


# Add the shared library (MODULE is for Python extensions)

add_library(foodfactory MODULE

Biscuit.cpp

Chocolate.cpp

Factory.cpp

bindings.cpp

)


# Set include directories for your source files.

# No need to add pybind11's include path here, as it's

# handled by the pybind11::pybind11 target.

target_include_directories(foodfactory PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})


# Link the library to the pybind11 provided target.

# This ensures all necessary compiler flags and include paths

# from pybind11 are used.

target_link_libraries(foodfactory PRIVATE pybind11::pybind11)



The story of pybind11 is not just about a technical tool ; it's about

a paradigm shift. It showed that the barrier between C++ and Python

could be lowered significantly, making it easier for developers to

leverage the strengths of both languages. It's a story of how a

well-designed, modern library can solve a long-standing problem

and become the de facto standard in its domain.


Enjoy...

Read my other exploration regarding Python and C++ bindings.

Here we go...

Let's start with SWIG...




And now let's delve into Boost.Python...


Tuesday, August 5, 2025

First What... Then Why... And then How...

 A truly inquisitive and resilient mind doesn't stop at "what" something is or "how" it works—but seeks to understand "why" it exists, why it works that way, and why it matters.

The first and foremost task of a student is to figure out the purpose of why he learns any specific subject. And once he gets the idea - the how follows. The basic purpose of a Guru is to help his disciples find that why.

It's true for every profession that teaches skills. We must not only learn a subject from what’s and how’s point of view, but also why's point of view.

What… How… Why…

Here's a concise breakdown of this triad of understanding:

What → Identification

"What is this concept, object, or phenomenon?"

→ Descriptive knowledge.


How → Mechanism

"How does it function or occur?"

→ Technical/operational knowledge.


Why → Purpose or cause

"Why does this happen? Why was it designed this way? Why should I care?"

→ Philosophical, causal, or ethical understanding.


Nurturing the "why" mindset leads to:


- Original thinking, not just replication.


 - Deeper learning, rooted in curiosity.


- Innovation, since questioning assumptions often sparks breakthroughs.


- Purpose-driven action, not just routine.


It’s the same mindset behind scientific inquiry, design thinking, and even spiritual introspection. So yes—let’s raise thinkers, not just doers.

Now let me tell you about one of my own experiences.

I joined NOKIA, Bharat and got my first taste of Symbian 60 there. There is a concept in Symbian C++ - the two phase constructor which helps avoid memory exceptions while constructing a C++ object.

I was curious about it and asked many employees in NOKIA, but got the standard answer that this is the norm. Then in Japan in 2007, I studied a bit of Boost library, especially the different types of pointers and understood why Symbian people did that - because there was no template concept in the early days of C++ and hence there was no smart pointer - so the Symbian community had no other way to avoid memory exception during construction of C++ object because the destructor works only for a fully constructed object. Note that early mobile phones did not have huge memory… hence even an insignificant memory leak was disastrous.


Read…

Read…

Here's a write up on the Symbian two phase constructor.

Symbian used two-phase construction partly because:

1. Early C++ lacked features like templates (pre-C++98 days).

2. So, smart pointers like std::unique_ptr, std::shared_ptr, or even std::auto_ptr were unavailable or unsafe.

3. This made automatic resource management difficult, especially in the face of exceptions or “leave” behavior.

🔍 The primary reason for two-phase construction was:

> Symbian's custom exception handling mechanism (based on “leave” and “cleanup stack”) and restricted runtime environment

📌 Why Not Use Traditional RAII?

RAII (Resource Acquisition Is Initialization) — the modern C++ idiom using constructors/destructors — was impractical in early Symbian because:

1. No Exceptions → constructors couldn’t safely fail.

2. No Smart Pointers → no automatic cleanup of heap objects.

3. Low-Memory Targets → needed ultra-predictable, minimal-overhead code.

4. Destructors only run on fully constructed objects → Symbian needed a way to clean up partially constructed objects.


📚 Cleanup Stack = Manual Smart Pointer

Symbian’s cleanup stack was a manual alternative to smart pointers, ensuring that dynamically allocated objects or memory could be cleaned up reliably if a “leave” occurred.

🔁 Two-Phase Construction Solved All This By:


Phase                   Role                              Fails?

Constructor Allocates memory only      No

ConstructL() Initializes and may leave  Yes

If ConstructL() failed, the partially constructed object could be safely deleted via cleanup stack.

Engineers by degree is OUT... Engineers by curiosity and skill is IN...

Will AI Kill Engineering Colleges in Bharat?

One of the silent but severe casualties of the Artificial Intelligence (AI) revolution could be engineering colleges in Bharat. With over 3,500 engineering institutions across India, many of which were established during the IT boom, the AI wave is now acting as a stress test — exposing what’s outdated, inefficient, or simply irrelevant.

The Harsh Reality: AI Doesn’t Need Your Degree

AI is not just another “tech trend” — it’s a paradigm shift. It doesn’t ask where you studied. It asks:

  • Can you solve real-world problems?

  • Can you build, deploy, or integrate AI tools?

  • Can you learn, adapt, and innovate?

In this new landscape, a 20-year-old with a laptop, access to ChatGPT, YouTube tutorials, and GitHub can outperform a degree-holder from a Tier 3 college. And companies are taking note.

Why Are Engineering Colleges at Risk?

1. Obsolete Curriculum

Most engineering colleges are still teaching programming as if it’s 2005. AI, prompt engineering, data science, or even modern DevOps tools are nowhere in the syllabus. When AI tools can write boilerplate code or automate testing, students need to learn why and how things work — not just what.

2. Low Employability

Even before AI, a report by Aspiring Minds showed that over 80% of engineering graduates in India were unemployable. AI has only accelerated this crisis by eliminating low-skill jobs that once served as a cushion for average grads.

3. Rise of Skill-Based Hiring

The job market is shifting. Platforms like LinkedIn, GitHub, Kaggle, and HackerRank are becoming more important than your college brand. Startups and even tech giants now hire based on portfolio and problem-solving ability, not campus placements or paper degrees.

4. Self-Learning Has Been Supercharged

Why pay ₹5–10 lakh for a 4-year engineering degree when:

  • You can learn from Stanford or MIT lectures on YouTube?

  • Take Google’s free AI and cloud certifications?

  • Build AI models with help from ChatGPT?
    The Return on Investment (ROI) of many private colleges is rapidly approaching zero.

5. Unsustainable Infrastructure

Many colleges were set up with the assumption:

“Every family wants an engineer.”
But now, families are asking:
“Will this degree get my child a job?”
Expect mass consolidation, closures, or conversions of many colleges into polytechnics or skill development centres.

A Silver Lining: Reinvent or Perish

The crisis is real — but so is the opportunity.

Engineering colleges that accept the disruption and choose to reform boldly may emerge stronger. Here's how:

  • Curriculum overhaul to include AI, ML, robotics, prompt engineering, and ethical tech.

  • Project-based learning over rote exams.

  • Faculty upskilling programs with direct ties to industry.

  • Hackathons, open labs, and AI research cells instead of dusty lecture halls.

  • Start-up incubation centres within colleges.

The Future Belongs to the Makers

The AI wave won’t spare the passive. But it will reward the curious, the creative, and the committed. The age of “engineers by degree” is fading. The age of “engineers by passion, curiosity, and capability” is here.

Let’s not mourn the death of outdated institutions.
Let’s celebrate the birth of a new engineering culture — rooted in inquiry, innovation, and impact. 

Wednesday, July 30, 2025

India’s ITIs Are Getting a Makeover: A New Chapter in Skilling Bharat



In a world where technology changes faster than textbooks, India’s Industrial Training Institutes (ITIs) are undergoing a long-overdue transformation. Once seen as last-resort options for students, these skill hubs are now being turned into modern centers of excellence, ready to power the engines of New Bharat.

🚨 The Problem: Outdated and Undervalued

For decades, ITIs served an important but undervalued role—producing technicians, electricians, welders, and fitters. But the curriculum often lagged behind the times. In many cases, students trained on equipment no longer used in industry. With India eyeing leadership in fields like EV manufacturing, electronics, robotics, and renewable energy, it was clear: the skilling ecosystem needed a revolution.

🔨 The Turning Point: ₹60,000 Crore National Scheme

In May 2025, the Government of India announced the National Scheme for ITI Upgradation, backed by an investment of ₹60,000 crore over five years. This isn’t just a funding exercise—it’s a complete overhaul.

Key Goals:

  • Upgrade 1,000 Government ITIs across the country.

  • Create 5 National Centres of Excellence for high-end skilling.

  • Skill 20 lakh youth in emerging sectors like robotics, solar energy, EVs, and advanced manufacturing.

  • Train 50,000 instructors to improve the quality of teaching.

⚙️ What’s Changing on the Ground?

📚 Modern Curriculum

Out goes the outdated syllabus. In comes AI, IoT, 3D printing, drone technology, and mechatronics. Courses are being aligned with the National Skills Qualification Framework (NSQF) to allow seamless transition to higher education or jobs.

🏭 Industry Collaboration

Companies like Tata, Mahindra, Bosch, and Adani are partnering to co-manage ITIs. This ensures what’s taught in the classroom mirrors what’s needed on the factory floor.

🖥️ Digital Classrooms & Smart Labs

Smart boards, VR tools, simulators, and CNC machines are replacing chalk and duster. Many ITIs are now connected to the Skill India Digital portal for blended learning.

🌐 International Alignment

India’s ITIs are being modelled on Germany’s famed dual education system. Students split time between classroom theory and real-world internships.

💼 Beyond Jobs: Creating Entrepreneurs

The new vision isn’t just about making job seekers. It’s about making job creators. With access to modern tools, business mentorship, and startup incubation, ITI graduates are now venturing into entrepreneurship—especially in green technologies and MSME sectors.

🏙️ Rebranding ITIs: From Stigma to Pride

For years, ITIs were stigmatized—considered less "prestigious" than engineering colleges. But today, ITI graduates are commanding respect, landing jobs in global companies, and even migrating abroad with certified skills.

When an ITI graduate works on a solar farm in Rajasthan, repairs drones in Assam, or programs CNC machines in Germany, we know something powerful is happening.

🧭 The Road Ahead

This revamp isn’t just about infrastructure or investment—it’s about trusting the power of skilled hands. It’s about recognizing that an economy cannot thrive on MBAs alone; it needs machinists, coders, welders, and solar technicians just as much.

With the ITI modernization drive, India is not just preparing its youth for jobs. It is preparing Bharat to lead the world in skilled manpower.

Tuesday, July 29, 2025

Nayara Sanctioned: Context and Implication for India’s Digital Sovereignty

The recent U.S. sanctions on Nayara Energy, one of India's private oil refiners, for trading with Russia highlight a critical reality: India’s dependence on foreign systems—economic, technological, and digital—makes it vulnerable to external geopolitical shocks.

Let’s break this down and explore the lesson for Bharat, especially in the realm of digital infrastructure, focusing on homegrown operating systems like Maya OS and BOSS OS.


What Happened with Nayara?

  • Nayara Energy, partly owned by Russia’s Rosneft and other investors, was sanctioned by the U.S. for allegedly helping in Russia’s energy export activities.
  • Even though India hasn't joined the Western sanctions on Russia, secondary sanctions can indirectly cripple Indian companies using U.S.-controlled systems like SWIFT, Visa, Microsoft, or cloud services.


The Lesson for Bharat

1. Digital Sovereignty Is Strategic Sovereignty

  • Windows, Android, iOS, Google, AWS, etc., dominate Indian cyberspace.
  • This gives foreign powers the ability to surveil, pressure, or disrupt Indian operations if they control the software backbone.
  • Just as sanctions cut Nayara off financially, India could be digitally “cut off” if it doesn’t have an independent digital stack.

Enter Maya OS and BOSS OS: India's Defense Against Digital Sanctions

- Maya OS

  • Developed by DRDO and Indian defence establishments.
  • Based on Linux, hardened for military and critical infrastructure.
  • Comes with Sandes (WhatsApp alternative) and Chakshu (anti-phishing tool).
  • Designed to replace Windows in defense networks to ensure cybersecurity and control.

- BOSS (Bharat Operating System Solutions)

  • Developed by CDAC (Centre for Development of Advanced Computing).
  • More civilian/enterprise focused.
  • Based on Debian Linux, supports Indian languages, and can be used in government schools, offices, and research.

Why They Matter Now More Than Ever

Concern Without Maya/BOSS With Maya/BOSS
Cybersecurity Reliant on U.S. companies Code owned & audited by India
Sanction Vulnerability U.S. can deny access (MS, Apple) India controls the stack
Data Sovereignty Data flows through U.S. clouds Data stays in Bharat
Defense Safety Military uses Windows! Hardened OS for military
Innovation Dependent on Big Tech Boost to Indian tech ecosystem

The Way Forward

  • Mandate Maya OS in critical infra: defense, power grid, ISRO, PSUs.
  • Push BOSS OS in schools and govt offices—just like China dumped Windows.
  • Build a native software ecosystem: office suite, browsers, AI tools.
  • Invest in open-source hardware, not just software.

Final Thought

The Nayara sanction is a warning shot. Tomorrow, Google may revoke Play Store access, or Microsoft could suspend Indian servers, or NVIDIA might deny AI chips—all at the whim of foreign policy.

Bharat must not just be Atmanirbhar in slogans. It must be sovereign in code.

Bharat will have to upgrade her digital infrastructure to tackle not only official blackout created by the foreign tech giants, but also  to tackle the various threats from hackers worldwide. There's no scope for wilful blindness in the technology field. Here's my write-up on USA's Baltimore bridge collapse.

Read ON...

O my Bharatwasi... Read ON...

Monday, July 28, 2025

The journey of Ridit through Code...

🌱 From Blocks to Buffers: My Son’s Journey Through Code

Not all journeys begin with a map.
Some begin with curiosity, a spark in a child's eyes when something moves on the screen—not because he clicked a button, but because he made it happen.

That’s how it began for my son, Ridit.


👶 From Drag-and-Drop to Lines of Logic

It all started with a simple platform: Code.org. A playground of visual blocks and puzzles that teach logic without words.

Then came Scratch—bright, colorful, and fun. He’d spend hours animating characters, setting conditions, building logic trees with a child’s imagination and a budding developer’s precision. I still remember the moment he showed me a working game he had made at the age when most kids were still figuring out which app to click.

That was the first sign: he didn’t just want to use software—he wanted to build it.


🧠 The Leap to Real Code: Java, Python, and C++

As his mind outgrew the blocky charm of Scratch, we introduced him to Java—his first experience writing logic in words, not pictures. Java gave him structure. Then came Python, where he found beauty in simplicity. And finally, the mighty C++, where he learned memory, control, and the raw power of thinking like a machine.

From loops to classes, from functions to recursion—he tackled them all with an energy that came not from obligation, but from genuine fascination.


🧩 The Architect’s Eye: UML & Design Patterns

But Ridit didn’t stop at syntax. He grew curious about how software is structured, not just written.

That’s when I introduced him to UML diagrams and design patterns—the architecture behind the application. To my surprise, he embraced them eagerly. MVC, Factory, Singleton—concepts even professionals sometimes struggle with—became tools in his thinking, not just terms in a book.

He wasn’t just coding now. He was designing.


🎨 The Creative Leap: Blender and Beyond

Every engineer has a little artist hidden inside. In Ridit, that artist woke up through Blender.

He began building 3D models, animating them, understanding meshes and textures—not just how software behaves, but how it looks and feels.

Now, he was combining code and creativity, logic and beauty.


🧱 Now: OpenGL and the World of Graphics

Today, Ridit is experimenting with OpenGL. Low-level graphics APIs that professionals use to render complex visualizations and simulations.

What once began as blocky instructions in Scratch has now evolved into buffer objects, shaders, and 3D transformations.

He’s not just a student of code anymore.
He’s a creator of systems, a designer of virtual worlds.


👨‍👦 From a Father to Fellow Learners

As a computer science teacher myself, I have had the privilege of guiding hundreds of students—but watching my own son evolve, guiding him from his first block of logic to rendering real-time 3D, has been one of the greatest joys of my life.

More importantly, it has reaffirmed something I wish every parent and teacher would embrace:

Let curiosity lead. Let them play, explore, break things. Then show them how to build.


🚀 Let’s Create Professionals, Not Just Consumers

In a world where screens are used mostly to consume content, let’s teach our children to create it.

Start with play.
Move to logic.
Then to structure.
Then to creation.

Not every child will become a software engineer. But every child deserves the power to build.

And sometimes, like in my case, they’ll end up building things you never imagined.


🙌 To Parents, Teachers, and Mentors

If you're raising or teaching an inquisitive child:

  • Start early. Use tools like Code.org, Scratch, Tynker.

  • Expose them to real languages when ready—Python, Java, C++.

  • Encourage structure: UML, design thinking.

  • Let them explore creativity: Blender, Unity, web design.

  • And when the time is right, show them OpenGL or low-level power—not as a challenge, but as a gift.


My son, Ridit, is still learning. But so am I. And I hope we never stop.

Let’s raise creators.
Let’s raise thinkers.
Let’s raise the next generation of doers.

Here we go...

Ridit's latest exploration of OpenGL...


Here's Ridit's tech youtube channel especially made for OpenGL.

Please subscribe to encourage this inquisitive boy of Bharat.


And here's his old YouTube tech channel...


Tuesday, July 22, 2025

Engineers of Bharat - Wake up and embrace Sanskrit - part III - we knew the value of Pi centuries before the European - Kaṭapayādi system of ancient Bharat......

 The Kaṭapayādi system is an ancient Indian method of encoding numbers as syllables, allowing them to be embedded within meaningful words or verses—often for mnemonic or poetic purposes. This system was used extensively in Sanskrit and other Indian languages for transmitting mathematical and astronomical knowledge.

What is the Kaṭapayādi System?

In this system, consonants are assigned numerical values from 0 to 9. Vowels do not carry value but are used to form pronounceable words.

Basic Encoding Table:

Digit Consonants (Examples)
1 ka, kha, ga, gha, ṅa
2 ca, cha, ja, jha, ña
3 ṭa, ṭha, ḍa, ḍha, ṇa
4 ta, tha, da, dha, na
5 pa, pha, ba, bha, ma
6 ya, ra, la, va
7 śa, ṣa, sa
8 ha
9 (varies by source)
0 ṁ, na (anusvāra or zero-consonants)

Note: There are multiple minor variations across regions.

Use in Encoding the Value of Pi (π)

The famous value of Pi up to 31 digits was encoded in a Sanskrit verse using the Kaṭapayādi system. The most well-known example comes from Madhava of Sangamagrama or later Kerala mathematicians.

The verse (in Malayalam tradition):

"गोपीभाग्यमधुव्रात-श्रुंगिशोदधिसंधिगः।
खलजीवितखाताव गलहाला रसंधरः॥"

Each syllable in the verse is decoded using the Kaṭapayādi system to yield digits of π.

Decoded Digits of π

Applying the Kaṭapayādi values to this verse yields:

3.1415926535897932384626433832792

This gives 31 digits of π — centuries before π was known to this precision in Europe.

Significance of the Kaṭapayādi-Pi Verse

  1. Mnemonic Tool: Easily remembered and recited by students and scholars.

  2. Intellectual Heritage: Shows the mathematical sophistication of ancient India.

  3. Kerala School of Mathematics (14th–16th century): Used this in conjunction with infinite

Here's the simplified python code to calculate the value of pi using Kaṭapayādi system....

import re
from indic_transliteration import sanscript
from indic_transliteration.sanscript import transliterate

# Kaṭapayādi consonant → digit map (Kaṭādi system for Pi verse)
# This specific mapping is used for the Pi verse mnemonic.
# Note: Vowels are ignored in this system.
katapayadi_map = {
1: ['k', 'ṭ', 'p', 'y'], # क, ट, प, य
2: ['kh', 'ṭh', 'ph', 'r'], # ख, ठ, फ, र
3: ['g', 'ḍ', 'b', 'l'], # ग, ड, ब, ल
4: ['gh', 'ḍh', 'bh', 'v'], # घ, ढ, भ, व
5: ['ṅ', 'ṇ', 'm', 'ś'], # ङ, ण, म, श
6: ['c', 't', 'ṣ'], # च, त, ष
7: ['ch', 'th', 's'], # छ, थ, स
8: ['j', 'd', 'h'], # ज, द, ह
9: ['jh', 'dh'], # झ, ध
0: ['ñ', 'n'] # ञ, न
}

# Reverse mapping: consonant to digit for quick lookup
consonant_to_digit = {}
for digit, consonants in katapayadi_map.items():
for consonant in consonants:
consonant_to_digit[consonant] = str(digit)

# Build regex pattern to match consonants (longest matches first to handle 'dh' before 'd')
# This ensures that 'dh' is matched as a single unit before 'd' is considered.
pattern = '|'.join(sorted(consonant_to_digit.keys(), key=len, reverse=True))

def decode_katapayadi(devanagari_text):
"""
Decodes a Devanagari text using the Kaṭapayādi system.
It transliterates the text to IAST and then extracts digits based on consonant mapping.
"""
# Step 1: Transliterate Devanagari to IAST (International Alphabet of Sanskrit Transliteration)
# Convert to lowercase to match the keys in our map.
iast = transliterate(devanagari_text, sanscript.DEVANAGARI, sanscript.IAST).lower()
print(f"IAST Transliteration: {iast}") # For debugging/verification

# Step 2: Extract consonant roots using the pre-built regex pattern
# re.findall finds all non-overlapping matches of the pattern in the string.
matches = re.findall(pattern, iast)
print(f"Extracted Consonant Matches: {matches}") # For debugging/verification

# Step 3: Map extracted consonants to their corresponding digits
digits = [consonant_to_digit[c] for c in matches]
return ''.join(digits)

# ✅ Your input verse (the famous Pi mnemonic)
devanagari_verse = "गोपीभाग्यमधुव्रातश्रुंगिशोदधिसंधिगःखलजीवितखातावगलहालारसंधरः"

# Decode the verse
decoded_digits = decode_katapayadi(devanagari_verse)

# Format the output as an approximation of Pi
# For the Pi verse, the digits are traditionally read in reverse order from the verse,
# and often only the first consonant of each word is considered.
# This code extracts all mapped consonants in order.
# The actual Pi value (3.141592653589793238462643383279...)
# will be obtained if the specific rules for this mnemonic are applied (e.g., word segmentation and reversal).
# Here, we present the directly decoded sequence.
pi_approx = f"{decoded_digits[0]}.{decoded_digits[1:]}" if decoded_digits else "N/A"

# 🖨️ Output
print("\nDecoded Digits (using Kaṭādi map and all consonant extraction):", decoded_digits)
print("Approx Pi (based on direct decoding):", pi_approx)
print("\nNote: For the exact Pi sequence from this verse, traditional methods often involve splitting the verse into words and reversing the final digit sequence. This script applies the Kaṭādi map to all found consonants in order.")

And here's the result...

IAST Transliteration: gopībhāgyamadhuvrātaśruṃgiśodadhisaṃdhigaḥkhalajīvitakhātāvagalahālārasaṃdharaḥ
Extracted Consonant Matches: ['g', 'p', 'bh', 'g', 'y', 'm', 'dh', 'v', 'r', 't', 'ś', 'r', 'g', 'ś', 'd', 'dh', 's', 'dh', 'g', 'kh', 'l', 'j', 'v', 't', 'kh', 't', 'v', 'g', 'l', 'h', 'l', 'r', 's', 'dh', 'r']

Decoded Digits (using Kaṭādi map and all consonant extraction): 31431594265235897932384626433832792
Approx Pi (based on direct decoding): 3.1431594265235897932384626433832792

Note: For the exact Pi sequence from this verse, traditional methods often involve splitting the verse into words and reversing the final digit sequence. This script applies the Kaṭādi map to all found consonants in order.

Wake up... O my Hindus of Bharat... You are the progenies of a great civilisation...

Read...
Read...