{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "Tirthajyoti Sarkar",
  "title_listed": "\"Digital Twin\" with Python: A hands-on example",
  "keywords": "",
  "domain": "数据处理",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://towardsdatascience.com/digital-twin-with-python-a-hands-on-example-2a3036124b61/",
  "publish_date": "2021-12-15",
  "corpus_stage": "",
  "notes": "",
  "id": "74a3c2a58432",
  "collected_at": "2026-10-02T09:06:02",
  "title": "\"Digital Twin\" with Python: A hands-on example | Towards Data Science",
  "body_markdown": "![Revisit consent button](../images/body-df29beacd7496220cc94.svg)\nWe value your privacy\nWe 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.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](../images/body-2159bb67f3de8ad870eb.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe 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\nNecessaryAlways Active\nNecessary 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.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis 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.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress 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.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis 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.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo 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. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes 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.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe 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.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical 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.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot 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).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot 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.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle 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.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance 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.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement 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.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter 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.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter 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.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube 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.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[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/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\n# \"Digital Twin\" with Python: A hands-on example\nA step-by-step guide to building a digital twin example of an electronic switch (transistor) with Python.\n[Tirthajyoti Sarkar](https://towardsdatascience.com/author/tirthajyoti/)\nDecember 15, 202113 min read\n### A step-by-step guide to building a digital twin example of an electronic switch (transistor) with Python\n![Image source: Created by the author](../images/000.png)\nImage source: Created by the author\nLearn 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.\n## What is a digital twin?\n[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_ \".\nThey 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.\nFurther, IBM says \"_Once informed with such data, the virtual model can be used to_ _**run simulations**_ _,__**study performance**_ _issues and_ _**generate possible improvements**_ \".\nSo, we can draw this mental model, can't we?\n![Image source: Created by the author](../images/001.png)\nImage source: Created by the author\n## Using Python for creating a digital twin\nSo, how do we use our favorite language Python to create a digital twin? Why do we even think it will work?\nThe 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.\n![Image source: Created by the author](../images/002.png)\nImage source: Created by the author\nOnce we accomplish that, we can also hope that the Python object\n  * can be used in suitable simulation programs,\n  * can be probed for data, and\n  * can even be subject to optimization routines for enhancing suitable internal parameters.\n\n\nWe 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.\n> ...main enabling factors for creating a digital twin are the **sensors** that gather data and the **processing system...**\nIn 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.\n## The physical object - a MOSFET device\nThere 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,\n  * internal combustion engine - embodies all mobility\n  * printing press - embodies all knowledge\n  * electrical motor - embodies all industrial motion\n  * a semiconductor-based transistor - embodies all electronics/internet\n\n\nI 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?\n![Image source: Created by the author](../images/003.png)\nImage source: Created by the author\n### So, what's a MOSFET?\nAlthough 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\".\nBasically, 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.\nThis is a historical image of one of the earliest MOSFET patents,\n![Image source: https://www.computerhistory.org/siliconengine/metal-oxide-semiconductor-mos-transistor-demonstrated/](../images/body-b4b81669c212237c782d.jpg)\nImage source: <https://www.computerhistory.org/siliconengine/metal-oxide-semiconductor-mos-transistor-demonstrated/>\nWe can simplify the internal structure by adopting a device model (also called a circuit model) with **three terminals** - _Drain_ , _Source_ , and _Gate_.\n![Image source: Created by the author](../images/004.png)\nImage source: Created by the author\n### Characteristics we want to model\nThis 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.\nFor 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.\n![Image source: Created by the author](../images/005.png)\nImage source: Created by the author\nNow, 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,\n  * <https://www.electronics-tutorials.ws/transistor/tran_6.html>\n\n\nPlease accept cookies to access this content\n### A MOSFET is a digital switch\nThe most succinct way to remember the behavior of a MOSFET is to **imagine it as a digital switch**. Here is how it works,\n  * 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.\n  * 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.\n\n\nSo, 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.\n> What characteristics do we want to model in our digital object? This determines the complexity and data structure choice for the digital twin\n### Parameters to remember\nWith this in mind, the only thing to remember for creating a digital twin, are three important parameters of a generic MOSFET,\n  * **Vth** : It is the threshold voltage (between _Gate_ and _Source_) above which the switch is ON.\n  * **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).\n  * **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.\n\n\n> fundamental utility of a MOSFET is as a **voltage-controlled switch...**\n## Our Python digital twin\nThe 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.\n### The main MOSFET class\nWe 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,\ntext\n\n```\nclass MOSFET:\n    def __init__(self,params=None,terminals=None):\n\n        # Params\n        if params is None:\n            self._params_ = {'BV':20,\n                             'Vth':1.0,\n                             'gm':1e-2}\n        else:\n            self._params_ = params\n\n        # Terminals\n        if terminals is None:\n            self._terminals_ = {'source':0.0,\n                        'drain':0.0,\n                        'gate':0.0}\n        else:\n            self._terminals_ = terminals\n```\n\nIn this code, we can observe the familiar terminals and parameters that we discussed at length before. There are some **default parameters**.\nWe can also have a `__repr__` method to describe the object in one line,\ntext\n\n```\ndef __repr__(self):\n        return \"Digital Twin of a MOSFET\"\n```\n\n### A method for determining the switching state\nWe can easily translate the MOSFET characteristic of a digital switch (ON/OFF) into a programming logic by defining a method within the class.\ntext\n\n```\ndef determine_state(self,vgs=None):\n        \"\"\"\n        \"\"\"\n        if vgs is None:\n            vgs = self._terminals_['gate'] - self._terminals_['source']\n        else:\n            vgs = vgs\n```\n\ntext\n\n```\n        if vgs > self._params_['Vth']:\n            return 'ON'\n        else:\n            return 'OFF'\n```\n\nIn the `__init__` method, we can have the state determined from the instantiation of the object.\ntext\n\n```\n# Determine state\n  self._state_ = self.determine_state()\n```\n\nYou are getting a hang of defining a Digital Twin with its characteristics and behavior, aren't you?\n### Let's see a quick instance\nBefore going deeper into other characteristics, let's see the behavior of this digital twin as defined so far.\ntext\n\n```\nmosfet = MOSFET()\n```\n\nIn [Jupyter notebook](https://github.com/tirthajyoti/Digital-Twin/blob/main/MOSFET-1.ipynb), we type this for testing the one-line description,\ntext\n\n```\nmosfet\n```\n\ntext\n\n```\n>> Digital Twin of a MOSFET\n```\n\nWe test the state of the `mosfet` object.\ntext\n\n```\nmosfet._state_\n```\n\ntext\n\n```\n>> 'OFF'\n```\n\nWe get the default parameters' dictionary back in this way,\ntext\n\n```\nmosfet._params_\n```\n\ntext\n\n```\n>> {'BV': 20, 'Vth': 1.0, 'gm': 0.01}\n```\n\nNow, if we explicitly define an object with some terminal and parameters value,\ntext\n\n```\nmosfet = MOSFET(terminals={'source':0.0,\n            'drain':0.0,\n            'gate':2.0}, \n           params={'BV':20,\n                   'Vth':1.0,\n                   'gm':1e-2})\n```\n\nWhat do you think the state of this object is? Let's check,\ntext\n\n```\nmosfet._state_\n```\n\ntext\n\n```\n>> 'ON'\n```\n\nThe 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,\ntext\n\n```\nterminals={'source':0.0,\n            'drain':0.0,\n            'gate':2.0}\n```\n\nand\ntext\n\n```\nparams={'BV':20,\n        'Vth':1.0,\n        'gm':1e-2})\n```\n\n### A method with an analytical model\nNext, 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,\ntext\n\n```\ndef id_vd(self,vgs=None,vds=None,rounding=True):\n        \"\"\"\n        Calculates drain-source current from \n        terminal voltages and gm\n        \"\"\"\n        <code>\n        if state=='ON':\n            if vds <= vgs - vth:\n                ids = self._params_['gm']*(vgs - vth - (vds/2))*vds\n            else:\n                ids = (self._params_['gm']/2)*(vgs-vth)**2\n\n        <more code...>\n```\n\nWhat 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.\ntext\n\n```\nids = []\nmosfet = MOSFET()\nvds_vals = [0.01*i for i in range(1,501)]\nfor v in vds_vals:\n    ids.append(mosfet.id_vd(vgs=3.0,vds=v,rounding=False))\n```\n\nThe 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.\n![Image source: Created by the author](../images/006.png)\nImage source: Created by the author\nThe 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,\n![Image source: Created by the author](../images/007.png)\nImage source: Created by the author\n## The power of modern digital twin - involving deep learning\nDigital 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.\n**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.\n![Image source: Created by the author](../images/008.png)\nImage source: Created by the author\n> Digital twin modeling does not necessarily need tools from data science or machine learning\n### Model sub-threshold leakage with a neural network\nSo, 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.\nWhat is this \"_Sub-threshold leakage_ \"?\nAs 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).\n### ML models - why and how to choose?\nSo, why did we choose an analytical equation for modeling the Ids-Vds in the ON-state and a DNN for leakage current?\nThere is no right or wrong answer to this question. It depends on a few factors,\n  * the type, and nature of the data you have\n  * the nature and complexity of the physical process that you are trying to model\n  * the trade-off between performance and accuracy of the Digital Twin model\n\n\nIn 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.\nFor 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.\n> you must determine a **balanced mix** of analytical and machine-learning models (or even discrete simulation models), to embed inside the Digital Twin object\n### The model training method\nThe 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.\ntext\n\n```\ndef train_leakage(self,data=None,\n                      batch_size=5,\n                      epochs=20,\n                      learning_rate=2e-5,\n                      verbose=1):\n        \"\"\"\n        Trains the digital twin for leakage current model with experimental data\n        Args:\n            data: The training data, expected as a Pandas DataFrame\n            batch_size (int): Training batch size\n            epochs (int): Number of epochs for training\n            learning_rate (float): Learning rate for training\n            verbose (0 or 1): Verbosity of display while training\n        \"\"\"\n```\n\nNote 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.\nInternally, 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.\ntext\n\n```\n# Deep-learning model\nmodel = build_model(num_layers=3,\n                    architecture=[32,32,32],\n                    input_dim=3)\n# Compile and train\nmodel_trained = compile_train_model(model,\n                                    X_train_scaled,\n                                    y_train_scaled,\n                                    batch_size=batch_size,\n                                    epochs=epochs,\n                                    learning_rate=learning_rate,\n                                    verbose=verbose)\n```\n\ntext\n\n```\nself.leakage_model = model_trained\n```\n\nHyperparameters 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.\n> 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\n### Data source for ML\nFor 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.\n![Image source: Created by the author](../images/009.png)\nImage source: Created by the author\nHowever, **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.\n![Image source: Created by the author](../images/010.png)\nImage source: Created by the author\nWith this arrangement, we just write one line of code to train the model with the training data supplied as `df` DataFrame,\ntext\n\n```\nmosfet.train_leakage(df)\n```\n\nand the familiar training starts,\n![](../images/body-535731d539b452b78ddb.png)\n### The predict method\nWe write a separate leakage method to predict the sub-Vth leakage for any combination of transconductance, Vgs, and Vth as input.\ntext\n\n```\ndef leakage(self,\n                w_l=1e-2,\n                vgs=None,\n                vth=None):\n        \"\"\"\n        Calculates leakage current using the deep learning model\n        \"\"\"\n        if not self._leakage_:\n            return \"Leakage model is not trained yet\"\n        # Vgs\n        if vgs is None:\n            vgs = self._terminals_['gate'] - self._terminals_['source']\n        else:\n            vgs = vgs\n        # Vth\n        if vth is None:\n            vth = self._params_['Vth']\n        else:\n            vth = vth\n\n        # Predict\n        x = np.array([w_l,vgs,vth])\n        ip = x.reshape(-1,3)\n        result = float(10**(-self.leakage_model.predict(ip)))\n\n        return result\n```\n\nThe 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.\n## Expansion of the digital twin\nDigital Twins welcome friends with their open arms. On both sides of the aisle, too.\nBasically, 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.\n**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.\n![Image source: Created by the author. Pixabay image used \\(Free for use\\)](../images/body-7c012b8b050a0bae54f4.png)\nImage source: Created by the author. [Pixabay image](https://pixabay.com/vectors/buildings-factory-business-34906/) used (Free for use)\nIn 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.\nThe 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.\n> **Connection. Communication. Co-work. These are the keys to making a successful and well-liked Digital Twin**\n* * *\n_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**_ _._\n> [**Join Medium with my referral link - Tirthajyoti Sarkar**](https://medium.com/@tirthajyoti/membership)\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](../images/body-662aba1723e2e3d49fcc.jpeg)\nWritten By\n## [Tirthajyoti Sarkar](https://towardsdatascience.com/author/tirthajyoti/)\n[See all from Tirthajyoti Sarkar](https://towardsdatascience.com/author/tirthajyoti/)\n[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/)\nShare This Article\n  * [](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)\n  * [](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)\n  * [](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)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](../images/011.jpeg)](https://towardsdatascience.com/whats-the-current-state-of-data-science-in-healthcare-3b6d8ebc7e0a/)\n## [What's the Current State of Data Science in Healthcare?](https://towardsdatascience.com/whats-the-current-state-of-data-science-in-healthcare-3b6d8ebc7e0a/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nTake a closer look at data science applications in healthcare and learn why the industry still lags behind in embracing data...\n[Andrey Koptelov](https://towardsdatascience.com/author/a.koptelov/)\nSeptember 25, 20205 min read\n  * [![](../images/012.jpg)](https://towardsdatascience.com/are-your-playlists-groovy-enough-7809faaf9c33/)\n## [Are Your Playlists Groovy Enough?](https://towardsdatascience.com/are-your-playlists-groovy-enough-7809faaf9c33/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nLet's find out by using Spotify's public API along with Julia\n[Vikas Negi](https://towardsdatascience.com/author/vikas.negi10/)\nNovember 1, 20217 min read\n  * [![](../images/013.jpeg)](https://towardsdatascience.com/3-simple-outlier-anomaly-detection-algorithms-every-data-scientist-needs-e71b1304a932/)\n## [3 Simple Outlier/Anomaly Detection Algorithms every Data Scientist needs](https://towardsdatascience.com/3-simple-outlier-anomaly-detection-algorithms-every-data-scientist-needs-e71b1304a932/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nGet an in-depth understanding about outlier detection and how you can implement 3 simple, intuitive and powerful outlier detection...\n[Vagif Aliyev](https://towardsdatascience.com/author/vagifaliyev/)\nOctober 24, 202011 min read\n  * [![](../images/014.png)](https://towardsdatascience.com/traffic-intersection-simulation-using-pygame-689d6bd7687a/)\n## [Traffic Intersection Simulation using Pygame](https://towardsdatascience.com/traffic-intersection-simulation-using-pygame-689d6bd7687a/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nThis article contains a step-by-step guide to develop a traffic intersection simulation from scratch using Pygame.\n[Mihir Gandhi](https://towardsdatascience.com/author/mihirgandhi0706/)\nFebruary 26, 202112 min read\n  * [![](../images/015.jpg)](https://towardsdatascience.com/tool-masking-the-layer-mcp-forgot/)\n## [Tool Masking: The Layer MCP Forgot](https://towardsdatascience.com/tool-masking-the-layer-mcp-forgot/)\n[Agentic AI](https://towardsdatascience.com/category/artificial-intelligence/agentic-ai/)\nWhy tool discovery is solved, but tool execution isn’t.\n[Frank Wittkampf](https://towardsdatascience.com/author/frankw_usa/)\nSeptember 5, 202514 min read\n  * [![](../images/016.jpeg)](https://towardsdatascience.com/apache-beam-data-processing-data-pipelines-dataflow-and-flex-templates-2902224aabf3/)\n## [Apache Beam: Data Processing, Data Pipelines, Dataflow and Flex Templates](https://towardsdatascience.com/apache-beam-data-processing-data-pipelines-dataflow-and-flex-templates-2902224aabf3/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nIn this first article, we're exploring Apache Beam, from a simple pipeline to a more complicated one, using GCP Dataflow. Let's learn what...\n[Stefano Bosisio](https://towardsdatascience.com/author/stefanobosisio1/)\nFebruary 12, 202420 min read\n  * [![](../images/017.jpeg)](https://towardsdatascience.com/disappointment-on-the-job-hunt-how-to-handle-rejection-of-a-position-e0eabbb82386/)\n## [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/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nNo one is perfect at handling rejection, and sometimes it can hurt\n[Rose Day](https://towardsdatascience.com/author/rjday/)\nApril 11, 20216 min read\n  * [![](../images/018.jpg)](https://towardsdatascience.com/auk-a-simple-alternative-to-auc-800e61945be5/)\n## [AUK - a simple alternative to AUC](https://towardsdatascience.com/auk-a-simple-alternative-to-auc-800e61945be5/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nA better performance measure than AUC for unbalanced data\n[Emil Rijcken](https://towardsdatascience.com/author/emilrijcken/)\nNovember 8, 20216 min read\n  * [![](../images/019.jpg)](https://towardsdatascience.com/deep-dive-on-ml-techniques-for-feature-selection-in-python-part-3-de2a7593247f/)\n## [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/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nThe final part of a series on ML-based feature selection where we discuss advanced methods like Borutapy and Borutashap. Also, discuss how...\n[Indraneel Dutta Baruah](https://towardsdatascience.com/author/indraneeldb1993ds/)\nJuly 10, 20229 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe 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/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](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\")\n  * [ ![](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\")\n  * [ ![](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?\")\n  * [ ![](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\")\n\n\n",
  "metadata": {
    "title": "\"Digital Twin\" with Python: A hands-on example | Towards Data Science",
    "description": "A step-by-step guide to building a digital twin example of an electronic switch (transistor) with Python.",
    "keywords": null,
    "author": "Tirthajyoti Sarkar",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "\"Digital Twin\" with Python: A hands-on example",
    "og:description": "A step-by-step guide to building a digital twin example of an electronic switch (transistor) with Python.",
    "og:url": "https://towardsdatascience.com/digital-twin-with-python-a-hands-on-example-2a3036124b61/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2021/12/1fUzLf-B6LQ1Y_E35pGZpWQ.png",
    "og:image:width": "3821",
    "og:image:height": "2448",
    "og:image:type": "image/png",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "Tirthajyoti Sarkar",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "13 min read",
    "article:published_time": "2021-12-15T14:04:08.000Z",
    "article:modified_time": "2021-12-15T14:04:08.000Z",
    "article:author": "https://towardsdatascience.com/author/tirthajyoti/"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 202,
    "error": ""
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/74a3c2a58432/code/block_000.txt",
      "chars": 502
    },
    {
      "language": "txt",
      "file": "attachments/74a3c2a58432/code/block_001.txt",
      "chars": 62
    },
    {
      "language": "txt",
      "file": "attachments/74a3c2a58432/code/block_002.txt",
      "chars": 192
    },
    {
      "language": "txt",
      "file": "attachments/74a3c2a58432/code/block_003.txt",
      "chars": 102
    },
    {
      "language": "txt",
      "file": "attachments/74a3c2a58432/code/block_004.txt",
      "chars": 58
    },
    {
      "language": "txt",
      "file": "attachments/74a3c2a58432/code/block_005.txt",
      "chars": 18
    },
    {
      "language": "txt",
      "file": "attachments/74a3c2a58432/code/block_006.txt",
      "chars": 7
    },
    {
      "language": "txt",
      "file": "attachments/74a3c2a58432/code/block_007.txt",
      "chars": 28
    },
    {
      "language": "txt",
      "file": "attachments/74a3c2a58432/code/block_008.txt",
      "chars": 15
    },
    {
      "language": "txt",
      "file": "attachments/74a3c2a58432/code/block_009.txt",
      "chars": 9
    },
    {
      "language": "txt",
      "file": "attachments/74a3c2a58432/code/block_010.txt",
      "chars": 16
    },
    {
      "language": "txt",
      "file": "attachments/74a3c2a58432/code/block_011.txt",
      "chars": 38
    },
    {
      "language": "txt",
      "file": "attachments/74a3c2a58432/code/block_012.txt",
      "chars": 181
    },
    {
      "language": "txt",
      "file": "attachments/74a3c2a58432/code/block_013.txt",
      "chars": 15
    },
    {
      "language": "txt",
      "file": "attachments/74a3c2a58432/code/block_014.txt",
      "chars": 8
    },
    {
      "language": "txt",
      "file": "attachments/74a3c2a58432/code/block_015.txt",
      "chars": 74
    },
    {
      "language": "txt",
      "file": "attachments/74a3c2a58432/code/block_016.txt",
      "chars": 56
    },
    {
      "language": "txt",
      "file": "attachments/74a3c2a58432/code/block_017.txt",
      "chars": 393
    },
    {
      "language": "txt",
      "file": "attachments/74a3c2a58432/code/block_018.txt",
      "chars": 147
    },
    {
      "language": "txt",
      "file": "attachments/74a3c2a58432/code/block_019.txt",
      "chars": 600
    },
    {
      "language": "txt",
      "file": "attachments/74a3c2a58432/code/block_020.txt",
      "chars": 529
    },
    {
      "language": "txt",
      "file": "attachments/74a3c2a58432/code/block_021.txt",
      "chars": 35
    },
    {
      "language": "txt",
      "file": "attachments/74a3c2a58432/code/block_022.txt",
      "chars": 25
    },
    {
      "language": "txt",
      "file": "attachments/74a3c2a58432/code/block_023.txt",
      "chars": 699
    }
  ],
  "images": [
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:40:13Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:40:13Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:40:13Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:40:13Z"
    }
  ],
  "audio": [],
  "videos": [
    {
      "url": "https://www.youtube.com/c/TowardsDataScience",
      "kind": "channel_reference",
      "status": "reference_only"
    }
  ],
  "links": [
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/latest/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/editors-pick/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/the-variable/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/shipai/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/submissions/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/tirthajyoti/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/artificial-intelligence/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/digital-transformation/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/tech/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/technology/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/whats-the-current-state-of-data-science-in-healthcare-3b6d8ebc7e0a/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/a.koptelov/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/are-your-playlists-groovy-enough-7809faaf9c33/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/vikas.negi10/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/3-simple-outlier-anomaly-detection-algorithms-every-data-scientist-needs-e71b1304a932/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/vagifaliyev/"
    },
    {
      "type": "external",
      "href": "https://write.insightmediagroup.io"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/company/towards-data-science/"
    },
    {
      "type": "external",
      "href": "https://x.com/TDataScience"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/ai-engineer"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/ai-data-scientist"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/computer-science"
    },
    {
      "type": "external",
      "href": "https://www.ibm.com/topics/what-is-a-digital-twin"
    },
    {
      "type": "external",
      "href": "https://en.wikipedia.org/wiki/Occam%27s_razor"
    },
    {
      "type": "external",
      "href": "https://www.computerhistory.org/siliconengine/metal-oxide-semiconductor-mos-transistor-demonstrated/"
    },
    {
      "type": "external",
      "href": "https://www.electronics-tutorials.ws/transistor/tran_6.html"
    },
    {
      "type": "external",
      "href": "https://github.com/tirthajyoti/Digital-Twin/blob/main/MOSFET-1.ipynb"
    },
    {
      "type": "external",
      "href": "https://pixabay.com/vectors/buildings-factory-business-34906/"
    },
    {
      "type": "external",
      "href": "https://medium.com/@tirthajyoti/membership"
    },
    {
      "type": "external",
      "href": "https://www.facebook.com/sharer/sharer.php?title=%22Digital+Twin%22+with+Python%3A+A+hands-on+example&u=https%3A%2F%2Ftowardsdatascience.com%2Fdigital-twin-with-python-a-hands-on-example-2a3036124b61%2F"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/shareArticle?mini=true&title=%22Digital+Twin%22+with+Python%3A+A+hands-on+example&url=https%3A%2F%2Ftowardsdatascience.com%2Fdigital-twin-with-python-a-hands-on-example-2a3036124b61%2F"
    },
    {
      "type": "external",
      "href": "https://x.com/share?text=%22Digital+Twin%22+with+Python%3A+A+hands-on+example&url=https%3A%2F%2Ftowardsdatascience.com%2Fdigital-twin-with-python-a-hands-on-example-2a3036124b61%2F"
    },
    {
      "type": "external",
      "href": "https://www.youtube.com/c/TowardsDataScience"
    },
    {
      "type": "external",
      "href": "https://www.threads.net/@towardsdatascience"
    },
    {
      "type": "external",
      "href": "https://bsky.app/profile/towardsdatascience.com"
    },
    {
      "type": "external",
      "href": "https://thenewstack.io"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-20T17:24:45Z",
  "source_url": "https://towardsdatascience.com/digital-twin-with-python-a-hands-on-example-2a3036124b61/",
  "delivery_status": "unverified",
  "discovery_status": "http_403",
  "missing_reason": "源页面未重新核验:http_403；已按保留正文补采图片",
  "repair_error": "",
  "actual_video_files": [],
  "expected_saved_body_images": 4,
  "image_discovery": "saved_markdown",
  "source_body_markdown": "![Revisit consent button](https://cdn-cookieyes.com/assets/images/revisit.svg)\nWe value your privacy\nWe 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.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](https://cdn-cookieyes.com/assets/images/close.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe 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\nNecessaryAlways Active\nNecessary 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.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis 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.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress 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.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis 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.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo 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. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes 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.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe 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.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical 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.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot 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).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot 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.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle 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.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance 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.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement 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.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter 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.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter 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.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube 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.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[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/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\n# \"Digital Twin\" with Python: A hands-on example\nA step-by-step guide to building a digital twin example of an electronic switch (transistor) with Python.\n[Tirthajyoti Sarkar](https://towardsdatascience.com/author/tirthajyoti/)\nDecember 15, 202113 min read\n### A step-by-step guide to building a digital twin example of an electronic switch (transistor) with Python\n![Image source: Created by the author](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/12/1fUzLf-B6LQ1Y_E35pGZpWQ.png)\nImage source: Created by the author\nLearn 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.\n## What is a digital twin?\n[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_ \".\nThey 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.\nFurther, IBM says \"_Once informed with such data, the virtual model can be used to_ _**run simulations**_ _,__**study performance**_ _issues and_ _**generate possible improvements**_ \".\nSo, we can draw this mental model, can't we?\n![Image source: Created by the author](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/12/1WXsxzk7sdShBpdj7vbrDIg.png)\nImage source: Created by the author\n## Using Python for creating a digital twin\nSo, how do we use our favorite language Python to create a digital twin? Why do we even think it will work?\nThe 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.\n![Image source: Created by the author](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/12/12o0FI-q5xoA9NbN8On8qPg.png)\nImage source: Created by the author\nOnce we accomplish that, we can also hope that the Python object\n  * can be used in suitable simulation programs,\n  * can be probed for data, and\n  * can even be subject to optimization routines for enhancing suitable internal parameters.\n\n\nWe 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.\n> ...main enabling factors for creating a digital twin are the **sensors** that gather data and the **processing system...**\nIn 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.\n## The physical object - a MOSFET device\nThere 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,\n  * internal combustion engine - embodies all mobility\n  * printing press - embodies all knowledge\n  * electrical motor - embodies all industrial motion\n  * a semiconductor-based transistor - embodies all electronics/internet\n\n\nI 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?\n![Image source: Created by the author](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/12/1npQjF34vYQS_4-OVd8n9eA.png)\nImage source: Created by the author\n### So, what's a MOSFET?\nAlthough 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\".\nBasically, 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.\nThis is a historical image of one of the earliest MOSFET patents,\n![Image source: https://www.computerhistory.org/siliconengine/metal-oxide-semiconductor-mos-transistor-demonstrated/](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/12/0jrNhsfZ1IBR4YHAw.jpg)\nImage source: <https://www.computerhistory.org/siliconengine/metal-oxide-semiconductor-mos-transistor-demonstrated/>\nWe can simplify the internal structure by adopting a device model (also called a circuit model) with **three terminals** - _Drain_ , _Source_ , and _Gate_.\n![Image source: Created by the author](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/12/1PHQneQaZz49j47wFqrc9xA.png)\nImage source: Created by the author\n### Characteristics we want to model\nThis 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.\nFor 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.\n![Image source: Created by the author](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/12/1o3s2_ADnMZ9vpv2-sYN3zA.png)\nImage source: Created by the author\nNow, 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,\n  * <https://www.electronics-tutorials.ws/transistor/tran_6.html>\n\n\nPlease accept cookies to access this content\n### A MOSFET is a digital switch\nThe most succinct way to remember the behavior of a MOSFET is to **imagine it as a digital switch**. Here is how it works,\n  * 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.\n  * 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.\n\n\nSo, 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.\n> What characteristics do we want to model in our digital object? This determines the complexity and data structure choice for the digital twin\n### Parameters to remember\nWith this in mind, the only thing to remember for creating a digital twin, are three important parameters of a generic MOSFET,\n  * **Vth** : It is the threshold voltage (between _Gate_ and _Source_) above which the switch is ON.\n  * **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).\n  * **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.\n\n\n> fundamental utility of a MOSFET is as a **voltage-controlled switch...**\n## Our Python digital twin\nThe 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.\n### The main MOSFET class\nWe 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,\ntext\n\n```\nclass MOSFET:\n    def __init__(self,params=None,terminals=None):\n\n        # Params\n        if params is None:\n            self._params_ = {'BV':20,\n                             'Vth':1.0,\n                             'gm':1e-2}\n        else:\n            self._params_ = params\n\n        # Terminals\n        if terminals is None:\n            self._terminals_ = {'source':0.0,\n                        'drain':0.0,\n                        'gate':0.0}\n        else:\n            self._terminals_ = terminals\n```\n\nIn this code, we can observe the familiar terminals and parameters that we discussed at length before. There are some **default parameters**.\nWe can also have a `__repr__` method to describe the object in one line,\ntext\n\n```\ndef __repr__(self):\n        return \"Digital Twin of a MOSFET\"\n```\n\n### A method for determining the switching state\nWe can easily translate the MOSFET characteristic of a digital switch (ON/OFF) into a programming logic by defining a method within the class.\ntext\n\n```\ndef determine_state(self,vgs=None):\n        \"\"\"\n        \"\"\"\n        if vgs is None:\n            vgs = self._terminals_['gate'] - self._terminals_['source']\n        else:\n            vgs = vgs\n```\n\ntext\n\n```\n        if vgs > self._params_['Vth']:\n            return 'ON'\n        else:\n            return 'OFF'\n```\n\nIn the `__init__` method, we can have the state determined from the instantiation of the object.\ntext\n\n```\n# Determine state\n  self._state_ = self.determine_state()\n```\n\nYou are getting a hang of defining a Digital Twin with its characteristics and behavior, aren't you?\n### Let's see a quick instance\nBefore going deeper into other characteristics, let's see the behavior of this digital twin as defined so far.\ntext\n\n```\nmosfet = MOSFET()\n```\n\nIn [Jupyter notebook](https://github.com/tirthajyoti/Digital-Twin/blob/main/MOSFET-1.ipynb), we type this for testing the one-line description,\ntext\n\n```\nmosfet\n```\n\ntext\n\n```\n>> Digital Twin of a MOSFET\n```\n\nWe test the state of the `mosfet` object.\ntext\n\n```\nmosfet._state_\n```\n\ntext\n\n```\n>> 'OFF'\n```\n\nWe get the default parameters' dictionary back in this way,\ntext\n\n```\nmosfet._params_\n```\n\ntext\n\n```\n>> {'BV': 20, 'Vth': 1.0, 'gm': 0.01}\n```\n\nNow, if we explicitly define an object with some terminal and parameters value,\ntext\n\n```\nmosfet = MOSFET(terminals={'source':0.0,\n            'drain':0.0,\n            'gate':2.0}, \n           params={'BV':20,\n                   'Vth':1.0,\n                   'gm':1e-2})\n```\n\nWhat do you think the state of this object is? Let's check,\ntext\n\n```\nmosfet._state_\n```\n\ntext\n\n```\n>> 'ON'\n```\n\nThe 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,\ntext\n\n```\nterminals={'source':0.0,\n            'drain':0.0,\n            'gate':2.0}\n```\n\nand\ntext\n\n```\nparams={'BV':20,\n        'Vth':1.0,\n        'gm':1e-2})\n```\n\n### A method with an analytical model\nNext, 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,\ntext\n\n```\ndef id_vd(self,vgs=None,vds=None,rounding=True):\n        \"\"\"\n        Calculates drain-source current from \n        terminal voltages and gm\n        \"\"\"\n        <code>\n        if state=='ON':\n            if vds <= vgs - vth:\n                ids = self._params_['gm']*(vgs - vth - (vds/2))*vds\n            else:\n                ids = (self._params_['gm']/2)*(vgs-vth)**2\n\n        <more code...>\n```\n\nWhat 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.\ntext\n\n```\nids = []\nmosfet = MOSFET()\nvds_vals = [0.01*i for i in range(1,501)]\nfor v in vds_vals:\n    ids.append(mosfet.id_vd(vgs=3.0,vds=v,rounding=False))\n```\n\nThe 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.\n![Image source: Created by the author](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/12/1vNJvyGddQDhpox7nYyaj9A.png)\nImage source: Created by the author\nThe 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,\n![Image source: Created by the author](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/12/159UjjuaTQ7j20Oo-FqEinA.png)\nImage source: Created by the author\n## The power of modern digital twin - involving deep learning\nDigital 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.\n**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.\n![Image source: Created by the author](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/12/1k1DD6vb8NV4wh-nPO587TQ.png)\nImage source: Created by the author\n> Digital twin modeling does not necessarily need tools from data science or machine learning\n### Model sub-threshold leakage with a neural network\nSo, 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.\nWhat is this \"_Sub-threshold leakage_ \"?\nAs 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).\n### ML models - why and how to choose?\nSo, why did we choose an analytical equation for modeling the Ids-Vds in the ON-state and a DNN for leakage current?\nThere is no right or wrong answer to this question. It depends on a few factors,\n  * the type, and nature of the data you have\n  * the nature and complexity of the physical process that you are trying to model\n  * the trade-off between performance and accuracy of the Digital Twin model\n\n\nIn 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.\nFor 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.\n> you must determine a **balanced mix** of analytical and machine-learning models (or even discrete simulation models), to embed inside the Digital Twin object\n### The model training method\nThe 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.\ntext\n\n```\ndef train_leakage(self,data=None,\n                      batch_size=5,\n                      epochs=20,\n                      learning_rate=2e-5,\n                      verbose=1):\n        \"\"\"\n        Trains the digital twin for leakage current model with experimental data\n        Args:\n            data: The training data, expected as a Pandas DataFrame\n            batch_size (int): Training batch size\n            epochs (int): Number of epochs for training\n            learning_rate (float): Learning rate for training\n            verbose (0 or 1): Verbosity of display while training\n        \"\"\"\n```\n\nNote 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.\nInternally, 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.\ntext\n\n```\n# Deep-learning model\nmodel = build_model(num_layers=3,\n                    architecture=[32,32,32],\n                    input_dim=3)\n# Compile and train\nmodel_trained = compile_train_model(model,\n                                    X_train_scaled,\n                                    y_train_scaled,\n                                    batch_size=batch_size,\n                                    epochs=epochs,\n                                    learning_rate=learning_rate,\n                                    verbose=verbose)\n```\n\ntext\n\n```\nself.leakage_model = model_trained\n```\n\nHyperparameters 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.\n> 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\n### Data source for ML\nFor 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.\n![Image source: Created by the author](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/12/1raYYNDlgiHMQUNDP5e7jHg.png)\nImage source: Created by the author\nHowever, **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.\n![Image source: Created by the author](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/12/1RZs4Np0dn4wzZ3E3B_NjOQ.png)\nImage source: Created by the author\nWith this arrangement, we just write one line of code to train the model with the training data supplied as `df` DataFrame,\ntext\n\n```\nmosfet.train_leakage(df)\n```\n\nand the familiar training starts,\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/12/1RELaqtFqWqs9keNFEmg_6g.png)\n### The predict method\nWe write a separate leakage method to predict the sub-Vth leakage for any combination of transconductance, Vgs, and Vth as input.\ntext\n\n```\ndef leakage(self,\n                w_l=1e-2,\n                vgs=None,\n                vth=None):\n        \"\"\"\n        Calculates leakage current using the deep learning model\n        \"\"\"\n        if not self._leakage_:\n            return \"Leakage model is not trained yet\"\n        # Vgs\n        if vgs is None:\n            vgs = self._terminals_['gate'] - self._terminals_['source']\n        else:\n            vgs = vgs\n        # Vth\n        if vth is None:\n            vth = self._params_['Vth']\n        else:\n            vth = vth\n\n        # Predict\n        x = np.array([w_l,vgs,vth])\n        ip = x.reshape(-1,3)\n        result = float(10**(-self.leakage_model.predict(ip)))\n\n        return result\n```\n\nThe 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.\n## Expansion of the digital twin\nDigital Twins welcome friends with their open arms. On both sides of the aisle, too.\nBasically, 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.\n**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.\n![Image source: Created by the author. Pixabay image used \\(Free for use\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/12/1VDPAeuMxclsX2m4BoQmClQ.png)\nImage source: Created by the author. [Pixabay image](https://pixabay.com/vectors/buildings-factory-business-34906/) used (Free for use)\nIn 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.\nThe 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.\n> **Connection. Communication. Co-work. These are the keys to making a successful and well-liked Digital Twin**\n* * *\n_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**_ _._\n> [**Join Medium with my referral link - Tirthajyoti Sarkar**](https://medium.com/@tirthajyoti/membership)\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](https://assets.insightmediagroup.io/media/1787657105381_zw8h6h.jpeg)\nWritten By\n## [Tirthajyoti Sarkar](https://towardsdatascience.com/author/tirthajyoti/)\n[See all from Tirthajyoti Sarkar](https://towardsdatascience.com/author/tirthajyoti/)\n[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/)\nShare This Article\n  * [](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)\n  * [](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)\n  * [](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)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/09/13W0aLSQkYbNxVc4uMfo22Q-scaled.jpeg)](https://towardsdatascience.com/whats-the-current-state-of-data-science-in-healthcare-3b6d8ebc7e0a/)\n## [What's the Current State of Data Science in Healthcare?](https://towardsdatascience.com/whats-the-current-state-of-data-science-in-healthcare-3b6d8ebc7e0a/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nTake a closer look at data science applications in healthcare and learn why the industry still lags behind in embracing data...\n[Andrey Koptelov](https://towardsdatascience.com/author/a.koptelov/)\nSeptember 25, 20205 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/11/0ohmNyeoFIxp3kD0m-scaled.jpg)](https://towardsdatascience.com/are-your-playlists-groovy-enough-7809faaf9c33/)\n## [Are Your Playlists Groovy Enough?](https://towardsdatascience.com/are-your-playlists-groovy-enough-7809faaf9c33/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nLet's find out by using Spotify's public API along with Julia\n[Vikas Negi](https://towardsdatascience.com/author/vikas.negi10/)\nNovember 1, 20217 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/10/1_2lzJN_AOfAvi2kdhQy82w.jpeg)](https://towardsdatascience.com/3-simple-outlier-anomaly-detection-algorithms-every-data-scientist-needs-e71b1304a932/)\n## [3 Simple Outlier/Anomaly Detection Algorithms every Data Scientist needs](https://towardsdatascience.com/3-simple-outlier-anomaly-detection-algorithms-every-data-scientist-needs-e71b1304a932/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nGet an in-depth understanding about outlier detection and how you can implement 3 simple, intuitive and powerful outlier detection...\n[Vagif Aliyev](https://towardsdatascience.com/author/vagifaliyev/)\nOctober 24, 202011 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/02/1sfeqkl-mCPPETdLm5oqI8Q.png)](https://towardsdatascience.com/traffic-intersection-simulation-using-pygame-689d6bd7687a/)\n## [Traffic Intersection Simulation using Pygame](https://towardsdatascience.com/traffic-intersection-simulation-using-pygame-689d6bd7687a/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nThis article contains a step-by-step guide to develop a traffic intersection simulation from scratch using Pygame.\n[Mihir Gandhi](https://towardsdatascience.com/author/mihirgandhi0706/)\nFebruary 26, 202112 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/09/Tool_Mask_Illustration.jpg)](https://towardsdatascience.com/tool-masking-the-layer-mcp-forgot/)\n## [Tool Masking: The Layer MCP Forgot](https://towardsdatascience.com/tool-masking-the-layer-mcp-forgot/)\n[Agentic AI](https://towardsdatascience.com/category/artificial-intelligence/agentic-ai/)\nWhy tool discovery is solved, but tool execution isn’t.\n[Frank Wittkampf](https://towardsdatascience.com/author/frankw_usa/)\nSeptember 5, 202514 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/1qDe_sNC7PPh3fU0KWs04Ug-scaled.jpeg)](https://towardsdatascience.com/apache-beam-data-processing-data-pipelines-dataflow-and-flex-templates-2902224aabf3/)\n## [Apache Beam: Data Processing, Data Pipelines, Dataflow and Flex Templates](https://towardsdatascience.com/apache-beam-data-processing-data-pipelines-dataflow-and-flex-templates-2902224aabf3/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nIn this first article, we're exploring Apache Beam, from a simple pipeline to a more complicated one, using GCP Dataflow. Let's learn what...\n[Stefano Bosisio](https://towardsdatascience.com/author/stefanobosisio1/)\nFebruary 12, 202420 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/1IiFrc3A1dhkou7-fqVn8Mg-scaled.jpeg)](https://towardsdatascience.com/disappointment-on-the-job-hunt-how-to-handle-rejection-of-a-position-e0eabbb82386/)\n## [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/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nNo one is perfect at handling rejection, and sometimes it can hurt\n[Rose Day](https://towardsdatascience.com/author/rjday/)\nApril 11, 20216 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/11/09vNBTqMAtjRlNnjp-scaled.jpg)](https://towardsdatascience.com/auk-a-simple-alternative-to-auc-800e61945be5/)\n## [AUK - a simple alternative to AUC](https://towardsdatascience.com/auk-a-simple-alternative-to-auc-800e61945be5/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nA better performance measure than AUC for unbalanced data\n[Emil Rijcken](https://towardsdatascience.com/author/emilrijcken/)\nNovember 8, 20216 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/07/0ZYbmP6Yj9hRjYcZu.jpg)](https://towardsdatascience.com/deep-dive-on-ml-techniques-for-feature-selection-in-python-part-3-de2a7593247f/)\n## [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/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nThe final part of a series on ML-based feature selection where we discuss advanced methods like Borutapy and Borutashap. Also, discuss how...\n[Indraneel Dutta Baruah](https://towardsdatascience.com/author/indraneeldb1993ds/)\nJuly 10, 20229 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe 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/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](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\")\n  * [ ![](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\")\n  * [ ![](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?\")\n  * [ ![](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\")\n\n\n",
  "body_base_path": "attachments/74a3c2a58432/pages/",
  "body_markdown_path": "attachments/74a3c2a58432/pages/archived-body.md",
  "local_html": "attachments/74a3c2a58432/pages/archived-body.html",
  "body_source": "prior_capture"
}