![Revisit consent button](../images/body-df29beacd7496220cc94.svg)
We value your privacy
We use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking "Accept All", you consent to our use of cookies.
Customise Reject All Accept All
Customise Consent Preferences ![](../images/body-2159bb67f3de8ad870eb.svg)
We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.
The cookies that are categorised as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more
NecessaryAlways Active
Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.
  * Cookie
BCTempID
  * Duration
10 minutes
  * Description
No description available.


  * Cookie
__cf_bm
  * Duration
1 hour
  * Description
This cookie, set by Cloudflare, is used to support Cloudflare Bot Management. 


  * Cookie
AWSALBCORS
  * Duration
7 days
  * Description
Amazon Web Services set this cookie for load balancing.


  * Cookie
_cfuvid
  * Duration
session
  * Description
Cloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services


  * Cookie
li_gc
  * Duration
6 months
  * Description
Linkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.


  * Cookie
__hssrc
  * Duration
session
  * Description
This cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.


  * Cookie
__hssc
  * Duration
1 hour
  * Description
HubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.


  * Cookie
wpEmojiSettingsSupports
  * Duration
session
  * Description
WordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.


  * Cookie
BCSessionID
  * Duration
1 year 1 month 4 days
  * Description
Blueconic sets this cookie as a unique identifier for the BlueConic profile.


  * Cookie
_octo
  * Duration
1 year
  * Description
No description available.


  * Cookie
logged_in
  * Duration
1 year
  * Description
No description available.


  * Cookie
__Secure-YEC
  * Duration
past
  * Description
YouTube sets this cookie to stores the user's video player preferences using embedded YouTube video


  * Cookie
__eoi
  * Duration
6 months
  * Description
Description is currently not available.


  * Cookie
AWSALBTGCORS
  * Duration
7 days
  * Description
No description available.


  * Cookie
login-status-p
  * Duration
past
  * Description
Description is currently not available.


  * Cookie
AWSALBTG
  * Duration
7 days
  * Description
No description available.


  * Cookie
csrf_token
  * Duration
session
  * Description
No description available.


  * Cookie
token_v2
  * Duration
1 day
  * Description
Description is currently not available.


  * Cookie
D
  * Duration
1 year
  * Description
Description is currently not available.


  * Cookie
PHPSESSID
  * Duration
session
  * Description
This cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.


  * Cookie
VISITOR_PRIVACY_METADATA
  * Duration
6 months
  * Description
YouTube sets this cookie to store the user's cookie consent state for the current domain. 


  * Cookie
cookietest
  * Duration
session
  * Description
The cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.


  * Cookie
__Host-airtable-session
  * Duration
1 year
  * Description
This cookie is used to enable us to integrate the services of Airtable.


  * Cookie
__Host-airtable-session.sig
  * Duration
1 year
  * Description
This cookie is used to enable us to integrate the services of Airtable.


  * Cookie
m
  * Duration
1 year 1 month 4 days
  * Description
Stripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.


  * Cookie
BIGipServer*
  * Duration
session
  * Description
Marketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. 


  * Cookie
__cfruid
  * Duration
session
  * Description
Cloudflare sets this cookie to identify trusted web traffic.


  * Cookie
_GRECAPTCHA
  * Duration
6 months
  * Description
Google Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.


  * Cookie
__Secure-YNID
  * Duration
6 months
  * Description
Google cookie used to protect user security and prevent fraud, especially during the login process.


  * Cookie
cookieyes-consent
  * Duration
1 year
  * Description
CookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.


Functional
Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.
  * Cookie
lidc
  * Duration
1 day
  * Description
LinkedIn sets the lidc cookie to facilitate data center selection.


  * Cookie
brw
  * Duration
1 year
  * Description
No description available.


  * Cookie
brwConsent
  * Duration
5 minutes
  * Description
Description is currently not available.


  * Cookie
WMF-Uniq
  * Duration
1 year
  * Description
Description is currently not available.


  * Cookie
loom_anon_comment
  * Duration
1 year
  * Description
No description available.


  * Cookie
loom_referral_video
  * Duration
session
  * Description
Description is currently not available.


  * Cookie
VISITOR_INFO1_LIVE
  * Duration
6 months
  * Description
A cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.


  * Cookie
yt-remote-connected-devices
  * Duration
Never Expires
  * Description
YouTube sets this cookie to store the user's video preferences using embedded YouTube videos.


  * Cookie
ytidb::LAST_RESULT_ENTRY_KEY
  * Duration
Never Expires
  * Description
The cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.


  * Cookie
yt-remote-device-id
  * Duration
Never Expires
  * Description
YouTube sets this cookie to store the user's video preferences using embedded YouTube videos.


  * Cookie
yt-remote-session-name
  * Duration
session
  * Description
The yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.


  * Cookie
yt-remote-fast-check-period
  * Duration
session
  * Description
The yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.


  * Cookie
yt-remote-session-app
  * Duration
session
  * Description
The yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.


  * Cookie
yt-remote-cast-available
  * Duration
session
  * Description
The yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.


  * Cookie
yt-remote-cast-installed
  * Duration
session
  * Description
The yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.


  * Cookie
cp_session
  * Duration
3 months
  * Description
Codepen sets this cookie for Help systems found in the website.


  * Cookie
loid
  * Duration
1 year 1 month 4 days
  * Description
This cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.


Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.
  * Cookie
__hstc
  * Duration
6 months
  * Description
Hubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).


  * Cookie
hubspotutk
  * Duration
6 months
  * Description
HubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.


  * Cookie
_ga
  * Duration
1 year 1 month 4 days
  * Description
Google Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.


  * Cookie
_ga_*
  * Duration
1 year 1 month 4 days
  * Description
Google Analytics sets this cookie to store and count page views.


  * Cookie
__Host-psifi.analyticsTrace
  * Duration
6 hours
  * Description
Description is currently not available.


  * Cookie
__Host-psifi.analyticsTraceV2
  * Duration
6 hours
  * Description
Description is currently not available.


  * Cookie
_gh_sess
  * Duration
session
  * Description
GitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.


  * Cookie
YSC
  * Duration
session
  * Description
YSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.


  * Cookie
ajs_anonymous_id
  * Duration
1 year
  * Description
This cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.


  * Cookie
vuid
  * Duration
1 year 1 month 4 days
  * Description
Vimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. 


Performance
Performance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.
  * Cookie
AWSALB
  * Duration
7 days
  * Description
AWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.


  * Cookie
acq
  * Duration
past
  * Description
Description is currently not available.


  * Cookie
acq.sig
  * Duration
past
  * Description
Description is currently not available.


  * Cookie
ptc
  * Duration
2 years
  * Description
No description available.


Advertisement
Advertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.
  * Cookie
muc_ads
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to collect user behaviour and interaction data to optimize the website.


  * Cookie
guest_id_marketing
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to identify and track the website visitor.


  * Cookie
guest_id_ads
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to identify and track the website visitor.


  * Cookie
personalization_id
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.


  * Cookie
guest_id
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.


  * Cookie
bcookie
  * Duration
1 year
  * Description
LinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.


  * Cookie
__Secure-ROLLOUT_TOKEN
  * Duration
6 months
  * Description
YouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.


  * Cookie
yt.innertube::nextId
  * Duration
Never Expires
  * Description
YouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.


  * Cookie
yt.innertube::requests
  * Duration
Never Expires
  * Description
YouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.


  * Cookie
session_tracker
  * Duration
session
  * Description
This cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.


  * Cookie
edgebucket
  * Duration
session
  * Description
Reddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.


  * Cookie
did
  * Duration
1 year
  * Description
Arbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.


Uncategorised
Other uncategorised cookies are those that are being analysed and have not been classified into a category as yet.
No cookies to display.
Reject All Save My Preferences Accept All
Toggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation
[](https://towardsdatascience.com/)
Publish AI, ML & data-science insights to a global community of data professionals.
Sign in[Submit an Article](https://write.insightmediagroup.io)
[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)
* * *
[Write For TDS](https://towardsdatascience.com/submissions/)
[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search
[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)
# "Digital Twin" with Python: A hands-on example
A step-by-step guide to building a digital twin example of an electronic switch (transistor) with Python.
[Tirthajyoti Sarkar](https://towardsdatascience.com/author/tirthajyoti/)
December 15, 202113 min read
### A step-by-step guide to building a digital twin example of an electronic switch (transistor) with Python
![Image source: Created by the author](../images/000.png)
Image source: Created by the author
Learn this step by step with the interactive [AI Engineer](https://roadmap.sh/ai-engineer), [AI and Data Scientist](https://roadmap.sh/ai-data-scientist) and [Computer Science](https://roadmap.sh/computer-science) roadmaps.
## What is a digital twin?
[IBM defines](https://www.ibm.com/topics/what-is-a-digital-twin) a digital twin as follows "_A digital twin is a virtual model designed to accurately reflect a physical object_ ".
They go on to describe how the main enabling factors for creating a digital twin are the **sensors** that gather data and the **processing system** that inserts the data in some particular format/**model** into the digital copy of the object.
Further, IBM says "_Once informed with such data, the virtual model can be used to_ _**run simulations**_ _,__**study performance**_ _issues and_ _**generate possible improvements**_ ".
So, we can draw this mental model, can't we?
![Image source: Created by the author](../images/001.png)
Image source: Created by the author
## Using Python for creating a digital twin
So, how do we use our favorite language Python to create a digital twin? Why do we even think it will work?
The answer is deceptively simple. Just look at the figure above and then at the one below to see the equivalency between a Digital Twin model and a classic Python object. We can _emulate_ the sensors and data processors with suitable methods/functions, store the gathered data in a database or internal variables, and _encapsulate_ everything into a Python class.
![Image source: Created by the author](../images/002.png)
Image source: Created by the author
Once we accomplish that, we can also hope that the Python object
  * can be used in suitable simulation programs,
  * can be probed for data, and
  * can even be subject to optimization routines for enhancing suitable internal parameters.


We can, of course, add virtually infinite layers of complexity to this scheme and make the object a truly complex digital construct. But, following [Occam's Razor principle](https://en.wikipedia.org/wiki/Occam%27s_razor), we should start simple, and add sophistication as we go along.
> ...main enabling factors for creating a digital twin are the **sensors** that gather data and the **processing system...**
In this article, we will take a simple step-by-step approach to **creating a digital twin object out of a single semiconductor device** (the _physical object_). For the sake of simplicity, we will not even get into modeling sensors, but emulate them as simple terminal voltages on the semiconductor device.
## The physical object - a MOSFET device
There are a select few physical objects around us that define and embody the march of modern civilization quite spectacularly. An incomplete list may look like the following,
  * internal combustion engine - embodies all mobility
  * printing press - embodies all knowledge
  * electrical motor - embodies all industrial motion
  * a semiconductor-based transistor - embodies all electronics/internet


I have worked in the semiconductor industry for more than a decade before joining the world of data science. Naturally, I would be attracted towards using a related example for this digital twin demo, won't I?
![Image source: Created by the author](../images/003.png)
Image source: Created by the author
### So, what's a MOSFET?
Although the first semiconductor transistors were so-called 'Bipolar Junction Device", almost all modern transistors are of the form called MOSFET. It is an acronym that stands for "**M** etal-**O** xide-**S** emiconductor **F** ield-**E** ffect-**T** ransistor".
Basically, it is a device made of metal and semiconductor (e.g., silicon or germanium) layers that sandwich a thin oxide (or another electrical insulator) material layer in between.
This is a historical image of one of the earliest MOSFET patents,
![Image source: https://www.computerhistory.org/siliconengine/metal-oxide-semiconductor-mos-transistor-demonstrated/](../images/body-b4b81669c212237c782d.jpg)
Image source: <https://www.computerhistory.org/siliconengine/metal-oxide-semiconductor-mos-transistor-demonstrated/>
We can simplify the internal structure by adopting a device model (also called a circuit model) with **three terminals** - _Drain_ , _Source_ , and _Gate_.
![Image source: Created by the author](../images/004.png)
Image source: Created by the author
### Characteristics we want to model
This is one of the first considerations while building a digital twin - what characteristics we want to model in our digital object. This determines the complexity and data structure choice for the twin.
For instance, although we can model all kinds of complex physics phenomena with the MOSFET structure, we may choose to restrict ourselves to modeling only the most basic characteristic viz. the drain-source current and voltage relationships in their simplest form.
![Image source: Created by the author](../images/005.png)
Image source: Created by the author
Now, we don't have the bandwidth to explain all these characteristics (and their underlying physics) in detail in this article. Interested readers can refer to excellent online materials,
  * <https://www.electronics-tutorials.ws/transistor/tran_6.html>


Please accept cookies to access this content
### A MOSFET is a digital switch
The most succinct way to remember the behavior of a MOSFET is to **imagine it as a digital switch**. Here is how it works,
  * If the voltage between _Gate_ and _Source_ is below a certain threshold, then the switch is OFF and no current (or information) flows between the _Drain_ and _Source_. This is shown in the bottom-right image of the figure above.
  * When the Gate to Source voltage is above this threshold, the switch is ON. The Drain to Source current is also determined by the voltage between them. This is shown in the top-right image of the figure above.


So, the fundamental utility of a MOSFET is as a **voltage-controlled switch** i.e. we can control the amount of current (or information) between two of its terminals by controlling the voltage on the third terminal.
> What characteristics do we want to model in our digital object? This determines the complexity and data structure choice for the digital twin
### Parameters to remember
With this in mind, the only thing to remember for creating a digital twin, are three important parameters of a generic MOSFET,
  * **Vth** : It is the threshold voltage (between _Gate_ and _Source_) above which the switch is ON.
  * **gm** : It is the 'ease' with which a MOSFET can carry current between _Drain_ and _Source_ once it is ON. The higher this number is, the more is the current. It can be thought of as an inverse quantity to resistance (which represents the resistance to the flow of current for a given voltage).
  * **BV** : This is called the "_Breakdown voltage_ ". This was not discussed in the ideal switch description and will not be modeled in the digital twin. This represents a limit on how much voltage the MOSFET can hold between its _Drain_ and _Source_ while it is in the OFF state. Above this limit, the MOSFET starts conducting again but not in a controlled manner i.e. we cannot control the current flow and it is essentially useless. However, this parameter is important to design and model as it limits the choice of a particular device in a particular application.


> fundamental utility of a MOSFET is as a **voltage-controlled switch...**
## Our Python digital twin
The boilerplate code for this demo is [here in my Github repo](https://github.com/tirthajyoti/Digital-Twin/blob/main/MOSFET-1.ipynb). For brevity, I will only show partial code snippets in this article.
### The main MOSFET class
We define the main MOSFET class with a choice for the user to also define some parameters and the terminal voltages. Partial code is shown below,
text

```
class MOSFET:
    def __init__(self,params=None,terminals=None):

        # Params
        if params is None:
            self._params_ = {'BV':20,
                             'Vth':1.0,
                             'gm':1e-2}
        else:
            self._params_ = params

        # Terminals
        if terminals is None:
            self._terminals_ = {'source':0.0,
                        'drain':0.0,
                        'gate':0.0}
        else:
            self._terminals_ = terminals
```

In this code, we can observe the familiar terminals and parameters that we discussed at length before. There are some **default parameters**.
We can also have a `__repr__` method to describe the object in one line,
text

```
def __repr__(self):
        return "Digital Twin of a MOSFET"
```

### A method for determining the switching state
We can easily translate the MOSFET characteristic of a digital switch (ON/OFF) into a programming logic by defining a method within the class.
text

```
def determine_state(self,vgs=None):
        """
        """
        if vgs is None:
            vgs = self._terminals_['gate'] - self._terminals_['source']
        else:
            vgs = vgs
```

text

```
        if vgs > self._params_['Vth']:
            return 'ON'
        else:
            return 'OFF'
```

In the `__init__` method, we can have the state determined from the instantiation of the object.
text

```
# Determine state
  self._state_ = self.determine_state()
```

You are getting a hang of defining a Digital Twin with its characteristics and behavior, aren't you?
### Let's see a quick instance
Before going deeper into other characteristics, let's see the behavior of this digital twin as defined so far.
text

```
mosfet = MOSFET()
```

In [Jupyter notebook](https://github.com/tirthajyoti/Digital-Twin/blob/main/MOSFET-1.ipynb), we type this for testing the one-line description,
text

```
mosfet
```

text

```
>> Digital Twin of a MOSFET
```

We test the state of the `mosfet` object.
text

```
mosfet._state_
```

text

```
>> 'OFF'
```

We get the default parameters' dictionary back in this way,
text

```
mosfet._params_
```

text

```
>> {'BV': 20, 'Vth': 1.0, 'gm': 0.01}
```

Now, if we explicitly define an object with some terminal and parameters value,
text

```
mosfet = MOSFET(terminals={'source':0.0,
            'drain':0.0,
            'gate':2.0}, 
           params={'BV':20,
                   'Vth':1.0,
                   'gm':1e-2})
```

What do you think the state of this object is? Let's check,
text

```
mosfet._state_
```

text

```
>> 'ON'
```

The MOSFET (or its Digital Twin) is ON because the voltage between _Gate_ and _Source_ is larger than the parameter _Vth_ as defined in the instance. I repeat the code snippet again with highlighted portion of interest,
text

```
terminals={'source':0.0,
            'drain':0.0,
            'gate':2.0}
```

and
text

```
params={'BV':20,
        'Vth':1.0,
        'gm':1e-2})
```

### A method with an analytical model
Next, we define a method to calculate the Drain-to-Source current for the ON-state MOSFET using a simple, first-order analytical model. The code and equation are contained in the [Notebook](https://github.com/tirthajyoti/Digital-Twin/blob/main/MOSFET-1.ipynb), and I only show a partial code snippet here,
text

```
def id_vd(self,vgs=None,vds=None,rounding=True):
        """
        Calculates drain-source current from 
        terminal voltages and gm
        """
        <code>
        if state=='ON':
            if vds <= vgs - vth:
                ids = self._params_['gm']*(vgs - vth - (vds/2))*vds
            else:
                ids = (self._params_['gm']/2)*(vgs-vth)**2

        <more code...>
```

What will be more interesting is that checking if the Digital Twin can generate current-voltage characteristics similar to a physical device. We can calculate a series of _Drain_ -_Source_ currents for a range of _Drain_ -_Source_ voltage.
text

```
ids = []
mosfet = MOSFET()
vds_vals = [0.01*i for i in range(1,501)]
for v in vds_vals:
    ids.append(mosfet.id_vd(vgs=3.0,vds=v,rounding=False))
```

The result looks beautifully matched to a generic, ideal MOSFET characteristic. Here Vds (_x_ -axis) represents _Drain_ -_Source_ voltage and Ids (_y_ -axis) represent _Drain_ -_Source_ current.
![Image source: Created by the author](../images/006.png)
Image source: Created by the author
The analytical model involves _Gate_ -_Source_ voltage (Vgs) too, and therefore, we can calculate Ids vs. Vds curves for a range of Vgs. That result looks like,
![Image source: Created by the author](../images/007.png)
Image source: Created by the author
## The power of modern digital twin - involving deep learning
Digital twin modeling does not necessarily need tools from data science or machine learning. However, in the modern world, dominated by data-driven models, it is prudent to use such modeling techniques wherever applicable and suitable.
**This does not mean that you should eliminate all analytical models from your digital twins** and start throwing deep learning models at every characteristic. As a domain expert (or with the help of one if you are not the domain expert), you must determine a **balanced mix** of analytical and machine-learning models (or even discrete simulation models), to embed inside the Digital Twin object for representing the real-world characteristics of the physical asset.
![Image source: Created by the author](../images/008.png)
Image source: Created by the author
> Digital twin modeling does not necessarily need tools from data science or machine learning
### Model sub-threshold leakage with a neural network
So, where should we apply a suitable ML technique in our digital twin object? It turns out that calculating (or predicting with an ML estimator) the so-called "_Sub-threshold leakage_ " will be a good candidate.
What is this "_Sub-threshold leakage_ "?
As we discussed earlier, the MOSFET is in the OFF state when the Vgs is below Vth. So, the ideal behavior for it is to carry zero current between _Drain_ and _Source_. However, due to the **wonderful whimsical nature of quantum mechanics (the details of which we don't need to know), a real MOSFET carries a small amount of 'leakage' current even in the OFF state**. We can attempt to calculate this using an ML model - specifically a deep neural network (DNN).
### ML models - why and how to choose?
So, why did we choose an analytical equation for modeling the Ids-Vds in the ON-state and a DNN for leakage current?
There is no right or wrong answer to this question. It depends on a few factors,
  * the type, and nature of the data you have
  * the nature and complexity of the physical process that you are trying to model
  * the trade-off between performance and accuracy of the Digital Twin model


In this case, the measurement of the leakage current is often noisy. The actual value is also somewhat stochastic, being a strong function of the natural variability in the material properties and manufacturing processes that created the physical MOSFET. The physics also dictates that it is a nonlinear function of the terminal voltage and a few other internal parameters. All of these make an ML approach suitable for modeling this characteristic.
For every digital twin you create, you have to investigate deeply and make the choice based on your judgment. However, the beauty of a digital twin is that it allows you to swap out an analytical model with an ML model (and vice versa) anytime you fancy.
> you must determine a **balanced mix** of analytical and machine-learning models (or even discrete simulation models), to embed inside the Digital Twin object
### The model training method
The choice of the model training and prediction interface is entirely flexible. In this example, we have separate training and prediction methods. The code snippet for the training method looks like the following.
text

```
def train_leakage(self,data=None,
                      batch_size=5,
                      epochs=20,
                      learning_rate=2e-5,
                      verbose=1):
        """
        Trains the digital twin for leakage current model with experimental data
        Args:
            data: The training data, expected as a Pandas DataFrame
            batch_size (int): Training batch size
            epochs (int): Number of epochs for training
            learning_rate (float): Learning rate for training
            verbose (0 or 1): Verbosity of display while training
        """
```

Note the inclusion of parameters like `batch_size`, `epochs`, and `learning_rate` - familiar to anybody knowledgeable about building a deep learning model. As the main input, all you have to supply is the `data` which is expected to be a Pandas DataFrame.
Internally, the code builds a Tensorflow Keras model, compiles and trains it, and saves the trained model as an internal property (`self.leakage_model`) of the Digital Twin.
text

```
# Deep-learning model
model = build_model(num_layers=3,
                    architecture=[32,32,32],
                    input_dim=3)
# Compile and train
model_trained = compile_train_model(model,
                                    X_train_scaled,
                                    y_train_scaled,
                                    batch_size=batch_size,
                                    epochs=epochs,
                                    learning_rate=learning_rate,
                                    verbose=verbose)
```

text

```
self.leakage_model = model_trained
```

Hyperparameters like the number of hidden layers and the activation function are pre-fixed in this implementation, but they can be exposed easily to the developer who is using the Digital Twin in the real-world application.
> beauty of a digital twin is that it allows you to swap out an analytical model with an ML model (and vice versa) anytime you fancy
### Data source for ML
For this demo, **we created some synthetic data** using a special helper function (included in the [Notebook](https://github.com/tirthajyoti/Digital-Twin/blob/main/MOSFET-1.ipynb)) to train the DNN. This helper included random variables to mimic the variability and noise in the manufacturing and measurement, mentioned earlier.
![Image source: Created by the author](../images/009.png)
Image source: Created by the author
However, **in real life, the semiconductor plant/ fab will run physical test suites** (using other machines) on millions of MOSFETs and record their leakage current for various Vgs bias voltages. It will also record the Vth of those MOSFETs in the test. All these data will flow into the Digital Twin and the model will be continuously trained and updated.
![Image source: Created by the author](../images/010.png)
Image source: Created by the author
With this arrangement, we just write one line of code to train the model with the training data supplied as `df` DataFrame,
text

```
mosfet.train_leakage(df)
```

and the familiar training starts,
![](../images/body-535731d539b452b78ddb.png)
### The predict method
We write a separate leakage method to predict the sub-Vth leakage for any combination of transconductance, Vgs, and Vth as input.
text

```
def leakage(self,
                w_l=1e-2,
                vgs=None,
                vth=None):
        """
        Calculates leakage current using the deep learning model
        """
        if not self._leakage_:
            return "Leakage model is not trained yet"
        # Vgs
        if vgs is None:
            vgs = self._terminals_['gate'] - self._terminals_['source']
        else:
            vgs = vgs
        # Vth
        if vth is None:
            vth = self._params_['Vth']
        else:
            vth = vth

        # Predict
        x = np.array([w_l,vgs,vth])
        ip = x.reshape(-1,3)
        result = float(10**(-self.leakage_model.predict(ip)))

        return result
```

The exponentiation in the code (raising to the power of 10) is due to the fact that we supplied the negative 10-logarithm of actual leakage values as training targets to the DNN model. This was done to achieve faster convergence and higher accuracy.
## Expansion of the digital twin
Digital Twins welcome friends with their open arms. On both sides of the aisle, too.
Basically, they are particularly amenable to connecting to industrial systems - upstream and downstream - and exploit that connection for the optimal behavior of the whole plant/industrial system. This is important to keep in mind while designing Digital Twin with a programming language, or any other modern data-oriented tool for that matter.
**Connection. Communication. Co-work. These are the keys to making a successful and well-liked Digital Twin**. So, the designer must carefully evaluate the choice of data structures, programming platforms, and AI/ML methods to make sure they play well with that design philosophy.
![Image source: Created by the author. Pixabay image used \(Free for use\)](../images/body-7c012b8b050a0bae54f4.png)
Image source: Created by the author. [Pixabay image](https://pixabay.com/vectors/buildings-factory-business-34906/) used (Free for use)
In this article, we just peeled the upper layers of a Digital Twin design by showing you some simple steps with Python programmatic framework. It is up to you - the readers - to take the concepts forward and add more sophisticated layers of programming, logic, and data science layers to the system/asset of your choice and design powerful digital twins.
The Industry 4.0/ Smart factory is already here and ready to take advantage of all the progress in Digital Transformation, Artificial Intelligence, and Machine Learning. Digital twins are a vital co-component of that journey.
> **Connection. Communication. Co-work. These are the keys to making a successful and well-liked Digital Twin**
* * *
_Loved the article? Become a_[ _**Medium member**_](https://medium.com/@tirthajyoti/membership) _to continue_ _**learning without limits**_ _. I'll receive a portion of your membership fee if you use the following link,__**with no extra cost to you**_ _._
> [**Join Medium with my referral link - Tirthajyoti Sarkar**](https://medium.com/@tirthajyoti/membership)
## Register Now to Continue Reading
### Unlock Towards Data Science with a Free Account
All articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.
Register for freeSign in to your account
* * *
![](../images/body-662aba1723e2e3d49fcc.jpeg)
Written By
## [Tirthajyoti Sarkar](https://towardsdatascience.com/author/tirthajyoti/)
[See all from Tirthajyoti Sarkar](https://towardsdatascience.com/author/tirthajyoti/)
[Artificial Intelligence](https://towardsdatascience.com/tag/artificial-intelligence/)[Data Science](https://towardsdatascience.com/tag/data-science/)[Digital Transformation](https://towardsdatascience.com/tag/digital-transformation/)[Tech](https://towardsdatascience.com/tag/tech/)[Technology](https://towardsdatascience.com/tag/technology/)
Share This Article
  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fdigital-twin-with-python-a-hands-on-example-2a3036124b61%2F&title=%22Digital%20Twin%22%20with%20Python%3A%20A%20hands-on%20example)
  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fdigital-twin-with-python-a-hands-on-example-2a3036124b61%2F&title=%22Digital%20Twin%22%20with%20Python%3A%20A%20hands-on%20example)
  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fdigital-twin-with-python-a-hands-on-example-2a3036124b61%2F&text=%22Digital%20Twin%22%20with%20Python%3A%20A%20hands-on%20example)


Towards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.
[Write for TDS](https://towardsdatascience.com/submissions/)
## Related Articles
  * [![](../images/011.jpeg)](https://towardsdatascience.com/whats-the-current-state-of-data-science-in-healthcare-3b6d8ebc7e0a/)
## [What's the Current State of Data Science in Healthcare?](https://towardsdatascience.com/whats-the-current-state-of-data-science-in-healthcare-3b6d8ebc7e0a/)
[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)
Take a closer look at data science applications in healthcare and learn why the industry still lags behind in embracing data...
[Andrey Koptelov](https://towardsdatascience.com/author/a.koptelov/)
September 25, 20205 min read
  * [![](../images/012.jpg)](https://towardsdatascience.com/are-your-playlists-groovy-enough-7809faaf9c33/)
## [Are Your Playlists Groovy Enough?](https://towardsdatascience.com/are-your-playlists-groovy-enough-7809faaf9c33/)
[Data Science](https://towardsdatascience.com/category/data-science/)
Let's find out by using Spotify's public API along with Julia
[Vikas Negi](https://towardsdatascience.com/author/vikas.negi10/)
November 1, 20217 min read
  * [![](../images/013.jpeg)](https://towardsdatascience.com/3-simple-outlier-anomaly-detection-algorithms-every-data-scientist-needs-e71b1304a932/)
## [3 Simple Outlier/Anomaly Detection Algorithms every Data Scientist needs](https://towardsdatascience.com/3-simple-outlier-anomaly-detection-algorithms-every-data-scientist-needs-e71b1304a932/)
[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)
Get an in-depth understanding about outlier detection and how you can implement 3 simple, intuitive and powerful outlier detection...
[Vagif Aliyev](https://towardsdatascience.com/author/vagifaliyev/)
October 24, 202011 min read
  * [![](../images/014.png)](https://towardsdatascience.com/traffic-intersection-simulation-using-pygame-689d6bd7687a/)
## [Traffic Intersection Simulation using Pygame](https://towardsdatascience.com/traffic-intersection-simulation-using-pygame-689d6bd7687a/)
[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)
This article contains a step-by-step guide to develop a traffic intersection simulation from scratch using Pygame.
[Mihir Gandhi](https://towardsdatascience.com/author/mihirgandhi0706/)
February 26, 202112 min read
  * [![](../images/015.jpg)](https://towardsdatascience.com/tool-masking-the-layer-mcp-forgot/)
## [Tool Masking: The Layer MCP Forgot](https://towardsdatascience.com/tool-masking-the-layer-mcp-forgot/)
[Agentic AI](https://towardsdatascience.com/category/artificial-intelligence/agentic-ai/)
Why tool discovery is solved, but tool execution isn’t.
[Frank Wittkampf](https://towardsdatascience.com/author/frankw_usa/)
September 5, 202514 min read
  * [![](../images/016.jpeg)](https://towardsdatascience.com/apache-beam-data-processing-data-pipelines-dataflow-and-flex-templates-2902224aabf3/)
## [Apache Beam: Data Processing, Data Pipelines, Dataflow and Flex Templates](https://towardsdatascience.com/apache-beam-data-processing-data-pipelines-dataflow-and-flex-templates-2902224aabf3/)
[Data Science](https://towardsdatascience.com/category/data-science/)
In this first article, we're exploring Apache Beam, from a simple pipeline to a more complicated one, using GCP Dataflow. Let's learn what...
[Stefano Bosisio](https://towardsdatascience.com/author/stefanobosisio1/)
February 12, 202420 min read
  * [![](../images/017.jpeg)](https://towardsdatascience.com/disappointment-on-the-job-hunt-how-to-handle-rejection-of-a-position-e0eabbb82386/)
## [Disappointment on the Job Hunt - How to Handle Rejection of a Position](https://towardsdatascience.com/disappointment-on-the-job-hunt-how-to-handle-rejection-of-a-position-e0eabbb82386/)
[Data Science](https://towardsdatascience.com/category/data-science/)
No one is perfect at handling rejection, and sometimes it can hurt
[Rose Day](https://towardsdatascience.com/author/rjday/)
April 11, 20216 min read
  * [![](../images/018.jpg)](https://towardsdatascience.com/auk-a-simple-alternative-to-auc-800e61945be5/)
## [AUK - a simple alternative to AUC](https://towardsdatascience.com/auk-a-simple-alternative-to-auc-800e61945be5/)
[Data Science](https://towardsdatascience.com/category/data-science/)
A better performance measure than AUC for unbalanced data
[Emil Rijcken](https://towardsdatascience.com/author/emilrijcken/)
November 8, 20216 min read
  * [![](../images/019.jpg)](https://towardsdatascience.com/deep-dive-on-ml-techniques-for-feature-selection-in-python-part-3-de2a7593247f/)
## [Deep-dive on ML techniques for feature selection in Python - Part 3](https://towardsdatascience.com/deep-dive-on-ml-techniques-for-feature-selection-in-python-part-3-de2a7593247f/)
[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)
The final part of a series on ML-based feature selection where we discuss advanced methods like Borutapy and Borutashap. Also, discuss how...
[Indraneel Dutta Baruah](https://towardsdatascience.com/author/indraneeldb1993ds/)
July 10, 20229 min read


  * [YouTube](https://www.youtube.com/c/TowardsDataScience)
  * [X](https://x.com/TDataScience)
  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)
  * [Threads](https://www.threads.net/@towardsdatascience)
  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)


[](https://towardsdatascience.com/)
Your home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.
Subscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)
© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)
####  Recommended Articles 
Close
  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ "Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1")
  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ "The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs")
  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ "Does Your Company Have a Data Strategy?")
  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500) Productivity Tips, Data Career Insights, and Other Recent Must-Reads ](https://towardsdatascience.com/productivity-tips-data-career-insights-and-other-recent-must-reads-5c47eb7a2fe0/ "Productivity Tips, Data Career Insights, and Other Recent Must-Reads")


