保留正文与补采附件。源页面当前未重新核验;具体限制见交付清单。

Revisit consent button 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 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.

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.

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.

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.

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.

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 SearchToggle Mobile Navigation Publish AI, ML & data-science insights to a global community of data professionals. Sign inSubmit an Article LatestEditor's PicksNewsletterShipAI


Write For TDS LinkedInXToggle Search 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 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 Image source: Created by the author Learn this step by step with the interactive AI Engineer, AI and Data Scientist and Computer Science roadmaps.

What is a digital twin?

IBM defines 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 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 Image source: Created by the author Once we accomplish that, we can also hope that the Python object

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, 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,

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 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/ 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 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 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,

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,

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,

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. 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, 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, 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 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 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 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,

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) 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 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 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,

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 Image source: Created by the author. Pixabay image 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 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

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


Written By

Tirthajyoti Sarkar

See all from Tirthajyoti Sarkar Artificial IntelligenceData ScienceDigital TransformationTechTechnology Share This Article

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

Related Articles

What's the Current State of Data Science in Healthcare?

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 September 25, 20205 min read

Are Your Playlists Groovy Enough?

Data Science Let's find out by using Spotify's public API along with Julia Vikas Negi November 1, 20217 min read

3 Simple Outlier/Anomaly Detection Algorithms every Data Scientist needs

Artificial Intelligence Get an in-depth understanding about outlier detection and how you can implement 3 simple, intuitive and powerful outlier detection... Vagif Aliyev October 24, 202011 min read

Traffic Intersection Simulation using Pygame

Artificial Intelligence This article contains a step-by-step guide to develop a traffic intersection simulation from scratch using Pygame. Mihir Gandhi February 26, 202112 min read

Tool Masking: The Layer MCP Forgot

Agentic AI Why tool discovery is solved, but tool execution isn’t. Frank Wittkampf September 5, 202514 min read

Apache Beam: Data Processing, Data Pipelines, Dataflow and Flex Templates

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 February 12, 202420 min read

Disappointment on the Job Hunt - How to Handle Rejection of a Position

Data Science No one is perfect at handling rejection, and sometimes it can hurt Rose Day April 11, 20216 min read

AUK - a simple alternative to AUC

Data Science A better performance measure than AUC for unbalanced data Emil Rijcken November 8, 20216 min read

Deep-dive on ML techniques for feature selection in Python - Part 3

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 July 10, 20229 min read

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 NewsletterWrite For TDS•About•Advertise•Privacy Policy•Terms of Use © Insight Media Group, LLC 2026•The New Stack•roadmap.sh•Creator Network

Recommended Articles

Close