<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[COMPREDICT - Medium]]></title>
        <description><![CDATA[AI-based Virtual Sensors and Analytics for Mobility - Medium]]></description>
        <link>https://medium.com/compredict?source=rss----f20477687d0d---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>COMPREDICT - Medium</title>
            <link>https://medium.com/compredict?source=rss----f20477687d0d---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 20:33:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/compredict" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Hands-on Day 1 and Day 2 Operations in Kubernetes using Django and AKS — Part 4]]></title>
            <link>https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-4-31988816cab1?source=rss----f20477687d0d---4</link>
            <guid isPermaLink="false">https://medium.com/p/31988816cab1</guid>
            <category><![CDATA[azure-kubernetes-service]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[Ousama Esbel]]></dc:creator>
            <pubDate>Tue, 20 Apr 2021 09:33:13 GMT</pubDate>
            <atom:updated>2021-08-26T19:21:27.038Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://medium.com/p/1bf09984b6ee?source=post_stats_page-------------------------------------">Hands-on Day 1 and Day 2 Operations in Kubernetes using Django and AKS — Part </a>4</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*UbtvCPSuGn0xkfjqyFphUQ.jpeg" /></figure><p>Kubernetes has become the de facto container orchestrator due to its various functionalities and flexibility. Although Kubernetes documentation is thorough and provides many examples, it is not straight forward to combine all these tutorials and use it to deploy a real-life application with several services from end-to-end. With that, I will demonstrate how to deploy a real-life scenario application on Azure Kubernetes Cluster (AKS) as the production platform. Moreover, I will be discussing day 1 and day 2 operations of the application life cycle in Kubernetes in series of articles. Here are the main headlines:</p><ul><li>Discuss the application and set up the cluster, container registry and the production namespace. (<a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-1-2c5aa7e683ef">part 1</a>)</li><li>Deploy Config Maps, Secrets and Persistent Volumes. (<a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-2-970f1d82b65f">part 2</a>)</li><li>Deploy, monitor and define update strategies for the services including setting up Traefik as Ingress Controller. (<a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-3-1bf09984b6ee">part 3</a>)</li><li>DevOps and Auto deployment using Github Action. (part 4)</li></ul><p>You don’t have to use Azure Kubernetes Service per say, you can easily re-configure the manifests to be compatible to any Kubernetes installation, such as AWS EKS or Linode. However, as a prerequisite, you need to have a basic knowledge of Kubernetes, Docker, yaml, shell scripting and Github Actions. In addition, if you want to run the application along with the tutorial, you need to:</p><ul><li>Clone the <a href="https://github.com/uzi0espil/cookiecutter-django-k8s">Cookiecutter-django-k8s</a> repository.</li><li>Install Docker and Docker-compose.</li><li>Enable or install <a href="https://kubernetes.io/docs/tasks/tools/install-kubectl/">Kubectl</a>.</li><li>Install <a href="https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest">Azure cli</a>.</li></ul><p>In this article, best practices for continuously deploying an application in Kubernetes cluster is discussed. Then, a demonstration is provided on how to implement a Continuous Deployment pipeline for the presented application in <a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-1-2c5aa7e683ef">part 1</a> using Github and Azure Actions.</p><h3>Continuous Deployment</h3><p>A key benefit of implementing a Continuous Deployment (CD) pipeline is to automate the release of the software in an efficient, fast and trackable way. In theory, Kubernetes makes CD easy to implement due to its declarative nature. Moreover, you describe the state that you want the applications to be. Then, Kubernetes attempts to reach that state. However, as we saw from the previous articles, Kubernetes takes care of the complete infrastructure; starting from setting up the applications’ configurations, jobs and disks to deploying the applications themselves. Monitoring the changes of these different components and automate the CD become very challenging. In other words, the more different Kubernetes resources you use, the harder it is to automate the complete pipeline.</p><p>Let’s briefly describe how ideally we can implement CD pipeline for the main Kubernetes resources used in the previous articles:</p><h4>ConfigMaps and Secrets</h4><p>In some cases, you end up updating only the application’s configurations, i.e. ConfigMaps and Secrets, without updating the microservices themselves. When CD is ran, the configuration changes are not reflected in the microservices unless you restart the microservices that are using them. This happens because microservices and configurations have different lifecycles and constraints.</p><p>One way to solve this issue is within the logic of CD pipeline. Moreover, we look for changed configuration manifests: if there is any, we will force restart the microservices that are using these configurations unless these microservices are modified anyway. You can simply check whether a configuration is modified or not by using the option --dry-run that will inform you the output of the command without actually applying the changes. Another method is to check if the last changed files in the repository contains any ConfigMaps/Secrets manifests using for example <a href="https://github.com/tj-actions/verify-changed-files">verify-changed-files</a> Action in your Github Actions workflow.</p><p>Although the idea is simple, the implementation is complicated and error-prone especially when a configuration is used by multiple applications across multiple teams. A better practice is to treat each configuration file as immutable file where you need to create a new version of the ConfigMap/Secret if you want to change its values. With that, you will need to modify the microservices manifests to load or mount the configurations of the newer versions. This gives you the possibility to let other applications that depend on the same configuration to use the current version of the configurations. This approach is followed by <a href="https://spinnaker.io/guides/user/kubernetes-v2/best-practices/#version-your-configmaps-and-secrets">Spinnaker.io</a>.</p><h4>Persistent Volumes</h4><p>In Persistent Volumes, one normally wants to expand the size of an already created volume. This can be easily achieved by modifying the Persistent Volume Claim (PVC). Specifically, the resources.requests.storage attribute. Unlike ConfigMaps/Secrets, updating the PVC will be reflected directly without requiring us to restart the related microservices.</p><p>However, if any of the volume type or class storage are required to be changed, then it is very difficult to handle. In this case, a good practice is to re-create the related microservices again with the new version of the PVC, this approach can be better managed using Infrastructure as Code (IaC) tools such as <a href="https://registry.terraform.io/providers/hashicorp/kubernetes/latest/docs/resources/persistent_volume">Terraform</a>. IaC tools require different handling in CD that is out of the scope of this article.</p><h4>Microservices</h4><p>The microservices that define the applications are the most common resources to be updated. Essentially, we would like to reflect the changes and the new features in production whenever we make a release. This can be easily done by compiling new docker images that contain the latest code and push these images to a container registry. These images are usually tagged with the release version. Then in CD pipeline, the services are forced to be updated by pulling the images from the container registry with the correct tag. Normally, the services are updated along with their correspondent Kubernetes Service.</p><p>The update strategy is defined using rolling update configurations and health check probes that have been explained in <a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-3-1bf09984b6ee">part 3</a>. Additionally, we can define further update strategies in the CD pipeline such as Canary strategy or Blue-Green Strategy which I will demonstrate how later. If you are unfamiliar with these mentioned strategies and you would like to learn more, then please refer to this thorough <a href="https://harness.io/blog/continuous-verification/blue-green-canary-deployment-strategies/#:~:text=A%20canary%20deployment%20is%20a,%2C%2075%25%2C%20100%25).">tutorial</a>.</p><h3>Demonstration</h3><p>Let’s demonstrate the CD pipeline using the same example repository and Kubernetes cluster from the previous articles. The repository’s complete CI/CD pipeline is split into three different stages:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*NMtjPC_Q26ABRAchI0cs9Q.png" /><figcaption>Three Stages of CI/CD</figcaption></figure><p>In a nutshell, the pipeline starts when a pull-request is submitted, the code style will be linted and tests will be ran. Once merged to master, docker images will be compiled and pushed to the specified container registry. Finally, upon release, we tag the compiled images from the last step with the release version and update the Kubernetes production cluster. Each stage is split into different Github Action scripts in the <a href="https://github.com/uzi0espil/cookiecutter-django-k8s/tree/master/.github/workflows">repository</a>. In this article, I will only discuss the last two stages that are related to CD as the CI stage was already provided by <a href="https://cookiecutter-django.readthedocs.io/en/latest/index.html">Django Cookiecutter</a>.</p><h4>Environment Variables and Secrets</h4><p>Before we start with Github Action scripts, we need to provide Github the necessary environment variables and secrets that are required to run the pipeline. Mainly we need to set:</p><ul><li>Azure’s access information.</li><li>AKS cluster and Resource-Group names.</li><li>Azure Container Registry (ACR) credentials.</li></ul><p>In Github, we can set the environment variables as secrets in settings -&gt; secrets. However, it is good practice to group secrets that are related to an <a href="https://docs.github.com/en/actions/reference/environments">environment</a> in Github, this helps us in the following:</p><ul><li>Assigning different people in the team for different stage of the application’s lifecycle. For example, allow specific members to create a release.</li><li>Re-use the jobs in Github Actions and only change the environment. In most cases, deploying Kubernetes to staging cluster is the same for production cluster. the difference resides in the access and credentials information. With that, we can make the job general and specify to run it on different environments.</li></ul><p>With that, first we create an environment called productionand assign the following keys to it:</p><ul><li>AZURE_ACCESS_INFO</li><li>CLUSTER_NAME</li><li>RESOURCE_GROUP</li></ul><p>AZURE_ACCESS_INFO can be retrieved by running the following command in Azure cli (you only need to run this command once):</p><pre>az ad sp create-for-rbac --name &quot;aksaccess&quot; --role contributor --scopes /subscriptions/&lt;SUBSCRIPTION_ID&gt;/resourceGroups/&lt;RESOURCE_GROUP&gt; --sdk-auth</pre><p>The command will return a JSON object that you can copy and store as the value of the AZURE_ACCESS_INFO variable. The other two secrets are self-explanatory and you should have obtained them when you created the cluster (for further information check <a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-1-2c5aa7e683ef">part 1</a>).</p><p>Environment variables and secrets that are unrelated to any environment can be stored in the general Github Secrets. For example, the container registry information are mostly shared between production and staging environments and therefore unrelated to a specific environment. With that, navigate to settings -&gt; secrets and add the following variables:</p><ul><li>CR_URL</li><li>REGISTRY_USERNAME</li><li>REGISTRY_PASSWORD</li></ul><p>You can find these information in ACR dashboard in Azure’s portal under Access Keys tab. (For further information refer to <a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-1-2c5aa7e683ef">part 1</a>).</p><h4>Github Action Workflow</h4><p>Let’s start first by compiling and pushing the images to ACR. Here are the main steps to be followed:</p><ol><li>Checkout the code.</li><li>Login to Azure docker.</li><li>Build the docker images locally.</li><li>Iterate through all images in docker-compose file and push each image.</li></ol><p>The following snippet shows how to implement the steps in Github Actions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e086748f15f8fce3b52cfee8afe6ba78/href">https://medium.com/media/e086748f15f8fce3b52cfee8afe6ba78/href</a></iframe><p>First of all, The job, push, is only triggered when a commit is pushed to the master branch as stated in line 1 to 4. The steps are straightforward. However, the final step in line 18, is ran within shell script named push-images.sh. The following snippet shows the shell script’s implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78ad3bb21318ce6ef66495cb223b330c/href">https://medium.com/media/78ad3bb21318ce6ef66495cb223b330c/href</a></iframe><p>Basically, the shell script accepts an argument to set the images tag, if no argument is passed, then latest is chosen. Afterwards, it gets the configuration from the docker-compose file, production.yml, and only tries to find image attribute. Finally, it loops through all images and for each image, it tags the image and pushes it to the container registry.</p><p>Once we have a stable version of our application, we create a release. Beside production release, a release can be alpha, beta or a release candidate (rc*). Normally, you would like to trigger different environment for each release type. In this simple example, only production release is considered which normally starts with v*. like for example, v1.0.0. With that, we trigger the CD pipeline when a release is made that starts with v* as shown in the snippet below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5028ea57e2bb7c145fc31ee3ffe5e81c/href">https://medium.com/media/5028ea57e2bb7c145fc31ee3ffe5e81c/href</a></iframe><p>Then, we need to tag the compiled images with the release version. The following snippet illustrates Github Action script for tagging and versioning the docker images:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1bbf35ddc6ec316b6a1c46fd8a6cfca/href">https://medium.com/media/e1bbf35ddc6ec316b6a1c46fd8a6cfca/href</a></iframe><p>The steps are very similar to the previous job, push , the only difference is that we pass a parameter to push-images.sh script. The parameter is defined in the Get Release Version in line 16, where we retrieve the release version from Github’s internal environment variable, GITHUB_REF . Finally, for performance purposes, we pull the latest images that are built from the previous stage instead of re-building them again.</p><p>Once the job is done, we can deploy the changes to AKS’s Cluster. Here are the steps that are required to deploy to AKS:</p><ol><li>Checkout the new code.</li><li>Login to AKS.</li><li>Get release version</li><li>Get list of Kubernetes manifests.</li><li>Get list of images.</li><li>Deploy to cluster.</li></ol><p>The following snippet illustrates how the steps are implemented:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3118318a1b3c8f7cb9f2d19422ca3bef/href">https://medium.com/media/3118318a1b3c8f7cb9f2d19422ca3bef/href</a></iframe><p>First of all, in line 3, we define that this job runs with respect to production environment that we created earlier. In step 2, Azure’s action <a href="https://github.com/Azure/k8s-set-context/tree/releases/v1">aks-set-context</a> is used to programmatically<strong> </strong>login to AKS, the action depends on the secrets we defined in production environment. In addition, Azure action <a href="https://github.com/Azure/k8s-deploy/">k8s-deploy</a> in line 33 is used to deploy to cluster. It expects list of manifests to run, the new compiled images’ URLs and the targeted Kubernetes Namespace within our cluster. The list of manifests are retrieved in step 4 using shell script list-manifests.sh . The script simply loops through the Kubernetes folders and gets the path to each manifest. Here is the how list-manifests.sh is implemented:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7b3203895c7bc75d0cae40aa4b20a40/href">https://medium.com/media/a7b3203895c7bc75d0cae40aa4b20a40/href</a></iframe><p>The order of the manifests is important, as you want to apply changes of ConfigMaps and Secrets first before you update the microservices.</p><p>Finally, the list of images are retrieved using list-images.sh that is very similar to push-images.sh except it only gets the images URLs without pushing them to ACR.</p><p><a href="https://github.com/Azure/k8s-deploy/">k8s-deploy</a> can take further argument to define the deployment strategy, it accepts both Canary and Blue-Green strategies. For that, you are required to provide additional variables for Canary strategy such as the percentage of replicas of baseline and canary variants. However, you don’t need to modify your Kubernetes infrastructure or introduce additional resources.</p><p>Finally, if you didn’t link the AKS cluster with ACR when you created the AKS cluster (as we did in <a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-1-2c5aa7e683ef">part 1</a>), then you will be required to provide the access to ACR through parameter in k8s-deploy action. Further information can be found in this <a href="https://docs.microsoft.com/en-us/azure/container-registry/container-registry-auth-kubernetes">tutorial</a>.</p><p>With that, we have a CD pipeline using Github Actions to roll updates of the newly released features to the production Kubernetes cluster.</p><h3>Things To Consider</h3><ul><li>Use <a href="https://helm.sh/">Helm</a> to automate the deployment of Kubernetes and make the manifests more customizable.</li><li>Use <a href="https://www.terraform.io/">Terraform </a>to automate the infrastructure changes.</li></ul><h3>Clean Up</h3><p>If you ran the tutorial, please go ahead and delete the resource group, Azure then will delete every resource in that group. Additionally, delete the service principal that has been created along with the resource group.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31988816cab1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-4-31988816cab1">Hands-on Day 1 and Day 2 Operations in Kubernetes using Django and AKS — Part 4</a> was originally published in <a href="https://medium.com/compredict">COMPREDICT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hands-on Day 1 and Day 2 Operations in Kubernetes using Django and AKS — Part 3]]></title>
            <link>https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-3-1bf09984b6ee?source=rss----f20477687d0d---4</link>
            <guid isPermaLink="false">https://medium.com/p/1bf09984b6ee</guid>
            <category><![CDATA[azure-kubernetes-service]]></category>
            <category><![CDATA[traefik]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Ousama Esbel]]></dc:creator>
            <pubDate>Thu, 18 Mar 2021 07:33:37 GMT</pubDate>
            <atom:updated>2021-08-26T19:20:59.988Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hands-on Day 1 and Day 2 Operations in Kubernetes using Django and AKS — Part 3</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*UbtvCPSuGn0xkfjqyFphUQ.jpeg" /></figure><p>Kubernetes has become the de facto container orchestrator due to its various functionalities and flexibility. Although Kubernetes documentation is thorough and provides many examples, it is not straight forward to combine all these tutorials and use it to deploy a real-life application with several services from end-to-end. With that, I will demonstrate how to deploy a real-scenario application on Azure Kubernetes Cluster (AKS) as the production platform. Moreover, I will be discussing day 1 and day 2 operations of the application lifecycle in Kubernetes in series of articles. Here are the main headlines:</p><ul><li>Discuss the application and set up the cluster, container registry and the production namespace. (<a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-1-2c5aa7e683ef">part 1</a>)</li><li>Deploy Config Maps, Secrets and Persistent Volumes. (<a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-2-970f1d82b65f">part 2</a>)</li><li>Deploy, monitor and define update strategies for the services including setting up Traefik as Ingress Controller. (part 3)</li><li>DevOps and Auto deployment using Github Action. (<a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-4-31988816cab1">part 4</a>)</li></ul><p>You don’t have to use Azure Kubernetes Service per say, you can easily re-configure the manifests to be compatible to any Kubernetes installation, such as AWS EKS or Linode. However, as a prerequisite, you need to have a basic knowledge of Kubernetes, Docker, yaml and shell scripting. In addition, if you want to run the application along with the tutorial, you need to:</p><ul><li>Follow the previous tutorials (<a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-1-2c5aa7e683ef">part 1</a> and <a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-2-970f1d82b65f">part 2</a>)</li><li>Clone the <a href="https://github.com/uzi0espil/cookiecutter-django-k8s">Cookiecutter-django-k8s</a> repository.</li><li>Install Docker and Docker-compose.</li><li>Enable or install <a href="https://kubernetes.io/docs/tasks/tools/install-kubectl/">Kubectl</a>.</li><li>Install <a href="https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest">Azure cli</a>.</li></ul><p>In this article, the application is launched, where Django and Flower will be exposed to external traffic using LoadBalancer and Traefik Controller. Moreover, both endpoints are secured using TLS certificates that are automatically generated from Traefik. To conclude, day 2 operations are discussed, mainly rolling updates and health checks.</p><h3>Deploy Services</h3><p>In this application, there are five different services. All these services are interconnected together through internal network. Hence, each should have an internal IP address. However, two of them should be also accessible from outside, namely Django and Flower services.</p><p>All services will be created as Deployments except Postgres where it will be created as a StatefulSet. The Kubernetes manifests of these services look really similar, the manifests should address the following points:</p><ul><li>Path to the image that we pushed to ACR.</li><li>Ports that the application is using.</li><li>The environment variables and secrets.</li><li>Attached volumes and where to mount.</li><li>Kubernetes Service to define the policy on how to access the Pod whether internally or externally.</li></ul><p>Let’s see how the above points are defined for Django service:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c65b13354405c85d8356f55a0fddfad/href">https://medium.com/media/5c65b13354405c85d8356f55a0fddfad/href</a></iframe><p>Django’s container image is defined in line 21. Unlike Docker, you cannot use environment variables within the manifests. Therefore, you need to go to each manifest in compose/kubernetes/*.yaml and change the image URL to match with your ACR. This shortcoming can be addressed by Helm. However, this is a topic for a different day.</p><p>Regarding the port, Django is served using Gunicorn where the port is defined in compose/production/django/start. With that, we need to expose port 5000.</p><p>Then, we define the environment variables and secrets. In the manifests, we refer to the ConfigMaps and Secrets that we created in the earlier section. Additionally, we add two environment variables that expand on the variables defined in the ConfigMaps.</p><p>Next is the volumes’ section, at line 61, where we define what Volume Persistent Claims (VPCs) the pod needs to use (VPCs are created in <a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-2-970f1d82b65f">part 2</a>) and, on line 41, we define where the attached volume should be mounted in the Pod. In our case, we want to mount it as Django’s media folder.</p><p>Finally, we configure the service policy which should be defined as a different Kubernetes resource. In Django’s case, we want to expose it to the other services and map port 5000 in the pod to port 80 of the Service. Of course, this is not ideal for production as we want to use TLS for our application. But let’s make this work as a first step and, later, we will modify it, replace the service with Ingress Resource and use TLS.</p><p>To deploy the services, run the following commands:</p><pre>kubectl apply -f compose/kubernetes/.</pre><p>In our examples, the workers are doing the heavy lifting, so it is purposeful to scale the workers. Accordingly, I sat the replicas in celeryworker.yaml to 3. There are additional sections in the celeryworker and Django that I will address in the upcoming section.</p><p>In the first run, the cluster will take some time to pull the images from the ACR. After some time, you should have the following results when running kubectl get pods -n production -o wide</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uc7CMQymc1MH3zs26ztfEg.png" /><figcaption>Deployed services.</figcaption></figure><h3>Traefik as Ingress Controller</h3><p>One of the main strength of Kubernetes is that it is flexible allowing you to choose any framework for your resources. To connect your cluster to external network, we usually tend to create an Ingress Controller. In AKS, an Ingress Controller can be integrated upon creating the cluster by enabling HTTP external Connection. Azure then will create a Nginx Ingress Controller. Nginx is a very reliable reverse-proxy framework. However, it falls short in several aspects:</p><ul><li>Difficult to integrate it in Kubernetes cluster.</li><li>Static configuration for each service in the cluster which makes it hard to manage in a cluster that is frequently changing.</li><li>Doesn’t support assigning TLS certificates out of the box. It requires another resource to manage certification like <a href="https://cert-manager.io/docs/">Cert-Manager</a>.</li></ul><p>Although Azure takes all the heavy lifting integrating Nginx in our cluster, it still doesn’t solve the other shortcomings. That is why I propose using Traefik. Traefik is a modern reverse-proxy that has been first released in the age of containers. Furthermore, it is easier to integrate as it speaks to Kubernetes natively and doesn’t need an extra wrapper to speak with Kubernetes. In addition, Traefik has built-in Let’s Encrypt and fully supports TCP.</p><p>There are three different strategies to integrate Traefik:</p><ul><li>Use Kubernetes Ingress resource to define the paths. This requires Traefik controller to have the correct permissions to watch ingress API and cannot automatically generate TLS certificates for your services. It requires handing over TLS certificates manually or by using another service like Cert-Manager [<a href="https://doc.traefik.io/traefik/v1.7/user-guide/kubernetes/">tutorial</a>].</li><li>Use Traefik custom Kubernetes resources that allow us to specify Ingresses with Traefik configuration and establish TLS certificates from Let’s Encrypt. In addition, it also requires Traefik controller to have the permissions to watch the new resources [<a href="https://doc.traefik.io/traefik/providers/kubernetes-crd/">tutorial</a>].</li><li>Provide Traefik the complete configuration from a ConfigMap without the need to define Kubernetes Ingress resource. In the configuration, you can define any middleware and you can establish TLS certificates.</li></ul><p>The first two strategies are complicated to integrate. However, they provide the needed flexibility. For applications that have few access points for which the Ingresses are not frequently changed such as in our case, then it is easier and less error-prone to go for the third option.</p><p>Without further ado, first, we need to create a LoadBalancer service for the Traefik controller. The service manifest can be described as the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/440d5f42a45760aeabeffbe7247ad470/href">https://medium.com/media/440d5f42a45760aeabeffbe7247ad470/href</a></iframe><p>In a nutshell, we are asking AKS for an external IP address and accept connections on ports 80, 443 and 5555.</p><p>To create the service, run the following command:</p><pre>kubectl create -f ingress/traefik-svc.yaml</pre><p>To retrieve the external IP address, find traefik when running the following command:</p><pre>kubectl get services -n production</pre><p>Then, map the external IP address to a domain. If you don’t already have a domain, you can use Azure’s <a href="https://docs.microsoft.com/en-us/azure/app-service/manage-custom-dns-buy-domain">App Service Domain</a> to create a domain name. It takes some time for the DNS to be updated. Meanwhile, let’s work on Traefik configurations. Traefik requires two configurations:</p><ul><li><strong>acme.json</strong>: required for automatic certificate generation.</li><li><strong>traefik.yml</strong>: contains all the configurations such as entrypoints, middleware, services and routes.</li></ul><p>Here is the manifest for both ConfigMaps:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/781df88879610fbc5a684ef70ba8550d/href">https://medium.com/media/781df88879610fbc5a684ef70ba8550d/href</a></iframe><p>First of all, replace&lt;your-URL&gt; with the domain name you mapped to the external IP address and replace &lt;your-email&gt; with your email. In the manifest, we are creating two ConfigMaps. The first one is acme.json which is simply an empty string. It is really crucial for Traefik to have this file available in order to generate the certificates, even if it is empty. The second ConfigMap is traefik.yml In line 31, we are specifying that we are using Let’s Encrypt for generating TLS certificates and store the needed information in the acme.json file that we should create. In line 41, the routes to the application are defined. Moreover, services, entrypoints and middlewares are specified. For example, Django service requires Traefik to redirect any requests to HTTPs and allow CSRF headers. The following commands create Traefik’s ConfigMaps:</p><pre>kubectl create -f configmaps/traefik-acme.yaml<br>kubectl create -f configmaps/traefik-config.yaml</pre><p>Now, it is time to create Traefik controller. There are two recommended ways to deploy Traefik pod, either as Kubernetes Deployment or DaemonSet. This official <a href="https://doc.traefik.io/traefik/v1.7/user-guide/kubernetes/#deploy-traefik-using-a-deployment-or-daemonset">article</a> by Traefik explains the difference between them and when to use each. In any case, Deployment is used in this tutorial, however it is fairly easy to swap back and forth between them. Here is the Traefik Deployment manifest:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc40fa3b35225f2e0c044e03d14a46f5/href">https://medium.com/media/bc40fa3b35225f2e0c044e03d14a46f5/href</a></iframe><p>In the manifest, we are starting the pod by running traefik command with arguments specified in line 25. What is important to note is that Traefik will look at the configuration file in path /etc/traefik/traefik.yml. So we need to mount the configuration file there.</p><p>At line 30, several ConfigMaps are projected into the same directory to be passed to the pod as a volume. Moreover, traefik.yml configuration is added to the top of the directory specified in the mounted path. However, acme.json is mounted on acme folder with access mode 0600. The complete directory is then mounted within the pod in the specified path in volumeMounts.mountPath as shown at line 23. And that’s it!</p><p>To create Traefik controller, run the following command:</p><pre>kubectl create -f compose/kubernetes/ingress/traefik-controller.yaml</pre><p>Once Traefik is up, you can navigate to your domain, you will be redirected to HTTPs and can access the website normally.</p><h3>Rolling Update and Health Checks</h3><p>The ability to update your application with zero-downtime is a key feature that Kubernetes offers. The update happens progressively. For example, in deployments, a new ReplicaSet is created where it contains the updated version. At the same time, the old ReplicaSet still exists. Then, a new pod is created in the new ReplicaSet to replace a pod from the old ReplicaSet. This is done incrementally until all pods in the old ReplicaSet are replaced. The update strategy is controlled by the following settings:</p><ul><li><strong>maxUnavailable</strong>: How many resources we can maximum take out from current replicas.</li><li><strong>maxSurge</strong>: How many additional resources we can add to the existing replicas.</li></ul><p>In our application, we need to make sure that we have at least three workers up and running at all times, even during updates. In that case, we can set maxUnavailable and maxSurge to 0 and 1 respectively. With that, one pod is added at a time, and that there will always be 3 pods ready to service in the deployment. The following figure illustrates what happens on every step:</p><figure><a href="https://www.bluematador.com/blog/kubernetes-deployments-rolling-update-configuration"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qlew6fhK_HAiCIsMKocMaQ.gif" /></a><figcaption>Rolling Update one pod at a time. Image is taken from <a href="https://www.bluematador.com/blog/kubernetes-deployments-rolling-update-configuration">here</a></figcaption></figure><p>As illustrated, once the new version is in “Ready” state, a pod from the old ReplicaSet is terminated. But isn’t “Ready” different from one service to another? For instance, in case of a web server, the service is ready when it can receive HTTP requests, on the other hand, databases are said to be ready when they can accept TCP connection to their open port. Therefore, Kubernetes allows us to define how each service is ready.</p><p>In Celery, we can identify the health of its worker and check if it is ready by running the following command:</p><pre>celery inspect ping -A config.celery_app -d celery@$HOSTNAME</pre><p>With the above command, we need the pod to warm up for 30 seconds and then try to run the command every minute until it gets at least 1 successful result (i.e., exit with code 0). With this configuration, ideally, the worker will need 30 seconds to be ready and with 90 seconds we would have replaced the three workers. Even if it is good enough for our application, it might be too long for some other cases. We can translate the above requirements in Kubernetes as the following:</p><pre>readinessProbe:<br>  exec:<br>    command: <br>      - bash<br>      - -c<br>      - celery inspect ping -A config.celery_app -d celery@$HOSTNAME<br>  initialDelaySeconds: 30<br>  periodSeconds: 20<br>  successThreshold: 10</pre><p>What about the terminated Celeryworker? What happens if the worker is performing a task when the Kubernetes decided to terminate it? Shouldn’t it wait until the worker finishes its task and then shut it down? To deal with this, Kubernetes sends a SIGTERM signal to the container and waits a period of time (default 30 seconds) until the container gracefully shuts down. If the container doesn’t terminate within the specified period, Kubernetes will force it to shut down using SIGKILL signal.</p><p>Luckily, Celery provides the <a href="https://docs.celeryproject.org/en/stable/userguide/workers.html#stopping-the-worker">desired functionality</a> out of the box. Furthermore, it will make sure that Celeryworker finishes all currently executed tasks once it receives SIGTERM. However, we still need to increase the waiting period to a suitable time that would let the worker finish its task. We control the time by configuring spec.termplate.spec.terminationGracePeriodSeconds in the deployment’s manifest.</p><p>Finally, to complete the lifecycle of our app, we need to continuously monitor our app to make sure that it is running correctly at all times. In Kubernetes, this is done by defining health checks <em>probes </em>that act on containers<em>. </em>Moreover, Kubernetes can take actions on containers that fail the health check.</p><p>The Readiness probe that we used above is one kind of Health check probes. It informs kubelet agent in the node when a container is “ready” to serve a traffic. If it fails, it will be taken out of service. Another crucial probe is the liveness probe which periodically checks if a container is dead or still alive. If the liveness probe fails, the container will be killed and what happens next depends on the restart policy we specified in the service’s manifest.</p><p>For a web server that has to talk to a database, such the case for Django service, we need to separate the readiness and liveness probes. The convention is that if the website is up but the database is down or unreachable, the liveness should pass but the readiness fails. The reason behind this design is that we don’t want to keep restarting the website for another service’s fault. What we need is to take the website out of service until the problem is resolved.</p><p>With that, a middleware has been implemented in Django to expose two endpoints, one for liveness and another for readiness, the liveness endpoint will check the status of Django before getting to the point where Django checks the database connection. In this present case, the readiness endpoint checks every external connection that Django makes. For more details check out this <a href="https://www.ianlewis.org/en/kubernetes-health-checks-django">article</a>. The liveness and readiness specifications for Django service are listed below:</p><pre>restartPolicy: always<br>...<br>livenessProbe:<br>  httpGet:<br>    path: /healthy<br>    port: 5000  # Gunicorn port<br>  initialDelaySeconds: 30<br>  periodSeconds: 31<br>  timeoutSeconds: 2<br>  failureThreshold: 2<br>readinessProbe:<br>  httpGet:<br>    path: /readiness<br>    port: 5000  # Gunicorn port <br>  initialDelaySeconds: 30<br>  periodSeconds: 37<br>  timeoutSeconds: 5<br>  failureThreshold: 2</pre><p>Django service will be given 30 seconds to start up. Then, every 31 seconds a http GET request will be sent to the healthy endpoint. If it failed in two consecutive times, Django will be marked as failure. In return, it will be terminated and a new service will be created. It is done similarly for the readiness probe but with different endpoint and configuration.</p><h3>Things To Consider</h3><ul><li>Use <a href="https://helm.sh/">Helm</a> to automate the deployment of Kubernetes and make the manifests more customizable.</li><li>Affinity settings should be specified in Traefik’s Deployment to ensure that two pods don’t end up on the same node.</li><li>Use <a href="https://azure.microsoft.com/en-us/services/postgresql/">Azure Postgres Service</a> instead of hosting your PostgresDB in your Cluster.</li><li>Use Traefik Custom Ingress Resources instead of specifying the configuration using ConfigMaps.</li></ul><h3>Next</h3><p>In the next tutorial, I will discuss how Kubernetes cluster lifecycle is managed using Continuous Deployment pipeline in Github Actions.</p><h3>Clean Up</h3><p>If you ran the tutorial, please go ahead and delete the resource group, Azure then will delete every resource in that group. Additionally, delete the service principal that has been created along with the resource group.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bf09984b6ee" width="1" height="1" alt=""><hr><p><a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-3-1bf09984b6ee">Hands-on Day 1 and Day 2 Operations in Kubernetes using Django and AKS — Part 3</a> was originally published in <a href="https://medium.com/compredict">COMPREDICT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hands-on Day 1 and Day 2 Operations in Kubernetes using Django and AKS — Part 2]]></title>
            <link>https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-2-970f1d82b65f?source=rss----f20477687d0d---4</link>
            <guid isPermaLink="false">https://medium.com/p/970f1d82b65f</guid>
            <category><![CDATA[configmap]]></category>
            <category><![CDATA[persistent-volume]]></category>
            <category><![CDATA[azure-kubernetes-service]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Ousama Esbel]]></dc:creator>
            <pubDate>Mon, 08 Mar 2021 08:26:19 GMT</pubDate>
            <atom:updated>2021-08-26T19:19:39.262Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hands-on Day 1 and Day 2 Operations in Kubernetes using Django and AKS — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*UbtvCPSuGn0xkfjqyFphUQ.jpeg" /></figure><p>Kubernetes has become the de facto container orchestrator due to its various functionalities and flexibility. Although Kubernetes documentation is thorough and provides many examples, it is not straight forward to combine all these tutorials and use it to deploy a real-life application with several services from end-to-end. With that, I will demonstrate how to deploy a real-scenario application on Azure Kubernetes Cluster (AKS) as the production platform. Moreover, I will be discussing day 1 and day 2 operations of the application lifecycle in Kubernetes in series of articles. Here are the main headlines:</p><ul><li>Discuss the application and set up the cluster, container registry and the production namespace. (<a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-1-2c5aa7e683ef">part 1</a>)</li><li>Deploy Config Maps, Secrets and Persistent Volumes. (part 2)</li><li>Deploy, monitor and define update strategies for the services including setting up Traefik as Ingress Controller. (<a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-3-1bf09984b6ee">part 3</a>)</li><li>DevOps and Auto deployment using Github Action. (<a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-4-31988816cab1">part 4</a>)</li></ul><p>You don’t have to use Azure Kubernetes Service per say, You can easily re-configure the manifests to be compatible to any Kubernetes installation, such as, AWS EKS or Linode. However, as a prerequisite, you need to have a basic knowledge of Kubernetes, docker, yaml and shell scripting. In addition, if you want to run the application along with the tutorial, you need to:</p><ul><li><a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-1-2c5aa7e683ef">Follow the previous tutorial</a>.</li><li>Clone the <a href="https://github.com/uzi0espil/cookiecutter-django-k8s">Cookiecutter-django-k8s</a> repository.</li><li>Install Docker and Docker-compose.</li><li>Enable or install <a href="https://kubernetes.io/docs/tasks/tools/install-kubectl/">Kubectl</a>.</li><li>Install <a href="https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest">Azure cli</a>.</li></ul><p>This article discusses how to manage the application’s environment variables and configurations as well as how to set up the volume profiles that will be mounted onto the containers.</p><h3>ConfigMaps and Secrets</h3><p>Before we start deploying our services, we need to configure the environment variables and secrets that the services need to function properly. So, I have translated all cookiecutter .envs files into ConfigMaps and Secrets. You can add ConfigMaps and Secrets manually to your cluster through Configuration tab in your Azure cluster dashboard. However, it is better to automate these steps through manifests.</p><p>You can find the configuration files in compose/kubernetes/configmaps and secrets . To deploy them in your cluster, run the following commands:</p><pre>kubectl create -f compose/kubernetes/configmaps/.<br>kubectl create -f compose/kubernetes/secrets/.</pre><p>Kubernetes Secret resource is not the best way to store sensitive data as the values are stored as an encoded base64. Instead, we can use Azure’s <a href="https://azure.microsoft.com/en-us/services/key-vault/">Key Vault</a> resource to securely save these configuration and provide them to the services. However, it is more complicated to configure and integrate than Secrets.</p><h3>Persistent Volumes</h3><p>Persistent Volumes (PV) are very crucial resources to make an application stateful. For our application, we need three different volumes:</p><ul><li>Volume for Postgres data.</li><li>Volume for backing up Postgres.</li><li>Shared volume for media directory that contains the uploaded images.</li></ul><p>Kubernetes provides two methods to create and attach PVs, either dynamically or statically. As a developer using Kubernetes, you are only allowed to create volumes based on profiles determined by the cluster administrator. These profiles are called Storage Classes. Out of the box, Azure provides four different types of Storage Classes. However, all these storage classes will not retain your data if the volume is gone. Moreover, you will lose all your data. To tackle this issue, you can do one of the following approaches:</p><ul><li>Create a custom Storage Class and set the reclaim policy to retain the data. Then, you can dynamically create volumes with this class.</li><li>Create a static persistent volume from the default storage class and override the reclaim policy.</li><li>Dynamically create a Persistent Volume and then patch the created volume to retain the data.</li></ul><p>In this tutorial, I will go through all of the above approaches, although the last option is the least favorable because you cannot reproduce it from manifests. Furthermore, here are the different strategies that will be used:</p><ul><li>For the shared media, a static Persistent Volume will be created from <a href="https://kubernetes.io/docs/concepts/storage/storage-classes/#azure-disk">azurefile</a> Storage Class.</li><li>For Postgres data, I will create a custom Storage Class to define Azure disk that can retain information, then create a dynamic Persistent Volume.</li><li>For Postgres backups, I will create a dynamic Persistent Volume from Azure’s default Storage Class and manually modify the Persistent Volume to retain the information.</li></ul><h4>Media Shared Volume</h4><p>In Static Volume Provisioning, we need to create a Persistent Volume that describes the volume characteristics, like resources, access mode, resource size, etc. Then, we need to create a Persistent Volume Claim (PVC) that can be used to attach the service to the PV.</p><p>Being that, we have to create a Azure Storage Account first. So, head to your resource group, click “add” and search for storage account. The form is straight forward, just make sure to remember the storage account name, to set the location the same as the cluster’s location and to keep everything as default (for real production, you might need to enable soft-delete for restoration purposes).</p><p>Once created, click on the storage account and, on the left menu, click on File shares. Click on add “+ File share” and set the name and Quota as you see fit (in my code I named the File shares <em>aksshare</em>).</p><p>Now, we need to create a Persistent Volume manifest that will attach the newly created File storage to our services (namely Django, Celeryworker and Celerybeat). The following snippet shows how to create the resource:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed6d9fe9856abd97211468f008d41918/href">https://medium.com/media/ed6d9fe9856abd97211468f008d41918/href</a></iframe><p>What you need to bear in mind is that the storage class used is <strong>azureFile</strong>. This type requires credentials in order to mount. The credentials are passed to the volume using Secret. In the cloned repository, I have provided an example manifest of the Secret manifest in compose/kubernetes/secrets/pm.yaml.exmaple, where you have to rename it to pm.yaml and fill in the values inside. You can find the values in the dashboard of Azure Storage Account you created. Head to the dashboard, then go to <em>Access Keys</em> on the right menu and click on <em>show keys</em>. You need to copy the <em>storage account name</em> and any of the provided <em>keys</em>.</p><p>Additionally, the volume will be mounted with permission 0777 for owner with ID 200. In the dockerfile of each service, I created a user for running that service and assigned the user an ID of 200.</p><p>To deploy the volume, run the following commands:</p><pre>kubectl create -f compose/kubernetes/secrets/pm.yaml<br>kubectl create -f compose/kubernetes/persistent_volumes/media.yaml</pre><p>To verify if PV and PVC is created, run the following:</p><pre>kubectl get pv -n production<br>kubectl get pvc -n production</pre><p>You should be able to see that PV has been created and the PVC is bounded to it as the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*hhILT7mG-9Hgg_waziiMHw.png" /></figure><h4>Postgres Data Volume</h4><p>First of all, we need to create a custom Storage Class that can retain the data. The following snippet shows the configuration needed to create the Storage Class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3c9f87a83da40ad75d233a42acdb1a9/href">https://medium.com/media/f3c9f87a83da40ad75d233a42acdb1a9/href</a></iframe><p>What is important, is to set the reclaim policy to retain. Additionally, allowVolumeExpansion is very useful to expand the volumes on fly. To create the custom Storage Class, we need to run the following command in the persistent_volumes folder:</p><pre>kubectl create -f storage_classes/retain_azure_disk.yaml</pre><p>In dynamic volume provisioning, we don’t need to create PV, we only need to create a PVC that uses the custom storage class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09a57d18112a845f4085bc58a3380e1f/href">https://medium.com/media/09a57d18112a845f4085bc58a3380e1f/href</a></iframe><p>As before, we deploy the PVC using kubectl apply -f postgres-data.yaml</p><h4>Postgres Backups Volume</h4><p>For Postgres Backups, we will dynamically create Persistent Volume. However, we will not use the custom Class Storage created earlier. As mentioned before, in Dynamic Volume Provision, we only create the claim. The PVC is very similar to the PVC we used for Postgres data, the only difference is that we need to set storageClassName to default to use the default Storage Class provided by Azure. When you create the PVC, you will notice that the reclaim policy is <em>delete</em> as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bcGvhmyg5zJOOEhgP5gH0g.png" /></figure><p>We can update the reclaim policy for this resource by using Kubernetes API as following:</p><pre>kubectl patch pv &lt;pv-name&gt; -p &#39;{&quot;spec&quot;:{&quot;persistentVolumeReclaimPolicy&quot;:&quot;Retain&quot;}}&#39;</pre><p>where &lt;pv-name&gt; in the above case is: pvc-65e37164-058b-4698-bd6a-908a953e1e27 . As much convenient this is, it is hard to trace and document. It would therefore be advisable to use manifests over patching.</p><h3>Next</h3><p><a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-3-1bf09984b6ee">In the next tutorial</a>, the microservices will be launched and exposed to outside using Traefik and LoadBalancer. Both Django and Flower will be secured by TLS. In addition, I will discuss day 2 operations, specifically monitoring the services using health checks and strategies to update the application.</p><h3>Further Improvements</h3><ul><li>Use <a href="https://helm.sh/">Helm</a> to automate the deployment of Kubernetes and make the manifests more customizable.</li><li>Integrate <a href="https://azure.microsoft.com/en-us/services/key-vault/">Key Vault</a> instead of Kubernetes Secret resource.</li><li>Use same Virtual Network for Azure Storage Account and Kubernetes Cluster, and enable soft-delete.</li></ul><h3>Clean Up</h3><p>If you ran the tutorial, please go ahead and delete the resource group, Azure then will delete every resource in that group. Additionally, delete the service principal that has been created along with the resource group.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=970f1d82b65f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-2-970f1d82b65f">Hands-on Day 1 and Day 2 Operations in Kubernetes using Django and AKS — Part 2</a> was originally published in <a href="https://medium.com/compredict">COMPREDICT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hands-on Day 1 and Day 2 Operations in Kubernetes using Django and AKS — Part 1]]></title>
            <link>https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-1-2c5aa7e683ef?source=rss----f20477687d0d---4</link>
            <guid isPermaLink="false">https://medium.com/p/2c5aa7e683ef</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[azure-kubernetes-service]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Ousama Esbel]]></dc:creator>
            <pubDate>Fri, 26 Feb 2021 17:17:33 GMT</pubDate>
            <atom:updated>2021-08-26T19:16:13.395Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hands-on Day 1 and Day 2 Operations in Kubernetes using Django and AKS — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*UbtvCPSuGn0xkfjqyFphUQ.jpeg" /></figure><p>Kubernetes has become the de facto container orchestrator due to its various functionalities and flexibility. Although Kubernetes documentation is thorough and provides many examples, it is not straight forward to combine all these tutorials and use it to deploy a real-life application with several services from end-to-end. With that, I will demonstrate how to deploy a real-scenario application on Azure Kubernetes Cluster (AKS) as the production platform. Moreover, I will be discussing day 1 and day 2 operations of the application life cycle in Kubernetes in series of articles. Here are the main headlines:</p><ul><li>Discuss the application and set up the cluster, container registry and the production namespace. (part 1)</li><li>Deploy Config Maps, Secrets and Persistent Volumes. (<a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-2-970f1d82b65f">part 2</a>)</li><li>Deploy, monitor and define update strategies for the services including setting up Traefik as Ingress Controller. (<a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-3-1bf09984b6ee">part 3</a>)</li><li>DevOps and Auto deployment using Github Action. (<a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-4-31988816cab1">part 4</a>)</li></ul><p>You don’t have to use Azure Kubernetes Service per say, you can easily re-configure the manifests to be compatible to any Kubernetes installation, such as, AWS EKS or Linode. However, as a prerequisite, you need to have a basic knowledge of Kubernetes, docker, yaml and shell scripting. In addition, if you want to run the application along with the tutorial, you need to:</p><ul><li>Clone the <a href="https://github.com/uzi0espil/cookiecutter-django-k8s">Cookiecutter-django-k8s</a> repository.</li><li>Install Docker and Docker-compose.</li><li>Enable or install <a href="https://kubernetes.io/docs/tasks/tools/install-kubectl/">Kubectl</a>.</li><li>Install <a href="https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest">Azure cli</a>.</li></ul><p>In this article, the application will be explained. Then, I will setup the production cluster and private container repository.</p><h3>Application Overview</h3><p>The application is a web service developed using Python, specifically using Django framework. Whenever you start a new project, there are many boilerplate integrations need to be done before you start developing the actual application or translate your business model, for instance, you need to prepare the development environment, docker integration, install python libraries, create database, build the continuous integration pipeline, etc... In order to quickly jump-start the development and directly start on developing the application’s logic, I used <a href="https://github.com/pydanny/cookiecutter-django">Cookiecutter Django</a>. If you use Django framework but never heard of Cookiecutter Django then I encourage you to give it a look as it provides various functionalities for all stages out of the box.</p><p>At the time of writing this tutorial, Cookiecutter Django does not provide Kubernetes integration so I extended it and added the necessary Kubernetes manifests to deploy to Azure Kubernetes cluster.</p><p>The web application consists of the following services:</p><ul><li><strong>Django</strong>: Web framework.</li><li><strong>Redis</strong>: Queue Broker for escalating heavy tasks to workers.</li><li><strong>Celeryworker</strong>: Process background tasks.</li><li><strong>Celerybeat</strong>: Process scheduled tasks.</li><li><strong>Postgres</strong>: Database.</li><li><a href="https://flower.readthedocs.io/en/latest/"><strong>Flower</strong></a>: Task monitoring tool for Celery</li></ul><p>I have implemented a simple use case in the application for the purpose of demonstrating the communication and deployment of the services in the cluster. Basically, the Django web app provides a form in the admin panel where a user can upload an image and specify its title and caption. Then, the application will escalate a task to the queue to resize the image. If any of the workers is free, then it will overtake the task, resize the image and store it.</p><p>With that, <strong>Django</strong>, <strong>Postgres</strong>, <strong>Redis </strong>and <strong>celeryworker </strong>need to communicate with each other to save and resize the image. The communication is done as following:</p><ol><li>Upon form submission, <strong>Django </strong>stores the record in the database.</li><li><strong>Django </strong>uploads the image to a shared volume.</li><li><strong>Django </strong>notifies the queue that a new record has been stored in the database with a given ID.</li><li>An unoccupied <strong>celeryworker </strong>check the queue and overtake the task.</li><li><strong>celeryworker </strong>queries the record from database.</li><li><strong>celeryworker </strong>gets the image from the shared volume, resize it and overwrite the image in the shared volume.</li><li><strong>Celeryworker </strong>notifies <strong>Redis </strong>about the result of the task.</li></ol><p>The following graph illustrates the previous steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*TauXCq0_WUjQPJ790o-_8A.png" /><figcaption>Step by step on how resize image task is carried in the application.</figcaption></figure><p>With the aforementioned scenario, we need to use three different communication medium in Kubernetes to perform the task:</p><ul><li>Kubernetes LoadBalancer resource to access the admin panel.</li><li>ClusterIP to communicate between the services and pass the record’s ID.</li><li>Kubernetes shared Persistent Volume to access and process the image.</li></ul><p>We could convert the image to base64 string and pass it through the internal network without the need to use persistent volume. However, this will decrease the performance and add communication overhead. Also, for the sake of learning, it would be great to utilize different Kubernetes resources.</p><p>In development phase, I prefer to develop using docker-compose since Kubernetes is mainly used for production and manages services in multiple nodes, while we develop locally in a single node. However, you still can develop with Kubernetes locally with one node using Docker Desktop or Minikube.</p><p>The specification of the services can be found in local.yml . With that, you can run the application using:</p><pre>docker-compose -f local.yml up --build</pre><h3>Azure Kubernetes Cluster</h3><p>If you don’t have already an Azure account, you can <a href="https://azure.microsoft.com/en-us/free/">create one for free</a>. You will have free credits that should be more than sufficient to run this tutorial.</p><p>In Azure portal, it is better to group the resources of your app in a logical group, this is called Resource Group. Then, within your created group, click add, and search for Kubernetes service. The form is straight forward, just make sure to remember the resource group and cluster name and enable the following:</p><ul><li>In Authentication tab, enable AKS-managed Azure Active Directory, this will enable you to connect to cluster from your azure cli in your device (or in your CI runner) and control the cluster locally using kubectl commands.</li><li>In Networking tab: set network configuration to Azure CNI. This will create an Azure VPC instead of using default Kubernetes network, kubenet.</li><li>Create new container registry and enable admin user. You can use external private registry, like dockerhub or harbor.io. However, in this tutorial, I will use Azure Container Registry (ACR).</li></ul><p>Once cluster is created, open your local terminal and run the following commands:</p><pre>SUBSCRIPTION_ID=  # your subscription id when you created your acc.<br>RESOURCE_GROUP=  # The resource group you created.<br>CLUSTER_NAME=  # name of the kubernetes service.</pre><pre>az account set --subscription ${SUBSCRIPTION_ID}<br>az aks get-credentials --resource-group ${RESOURCE_GROUP} --name ${CLUSTER_NAME}</pre><p>Then, a command will prompt asking you to login by providing you a login URL and a code that you need to copy to a browser. Once authenticated, you can then apply any changes to the cluster from your command line. To test it, run the following command:</p><pre>kubectl get all --all-namespaces</pre><p>With that, you are actually getting all the information from your Azure cluster.</p><h3>Azure Container Registry</h3><p>If you went to your resource group in the portal, you would find two additional resources that have been created along with your cluster, namely Virtual Network and Container Registry. So now we need to build the production images and push them to ACR in order for the cluster to find them and pull them.</p><p>For starters, click on the container registry and navigate to <em>Access Keys</em>. There you can find the login server and the credentials that you need to login. In the cloned repository, modify .env file and set CR_URL to the value correspond to <em>login server</em>.</p><p>Then, docker-login to the registry by running the following command in your terminal:</p><pre>docker login -u ${ACR_USERNAME} -p ${ACR_Pass} <a href="https://${acr_url}/">https://${ACR_URL}</a></pre><p>Once successfully logged in, you can then build your production images and push them to the Container Registry using the following commands:</p><pre>docker-compose -f production.yml build<br>docker-compose -f production.yml push</pre><p>You can verify that they are pushed by navigating to <em>Repositories </em>tab in your Container Registry dashboard.</p><h3>Production Namespace</h3><p>Namespaces in Kubernetes is a way to logically isolate services or applications from each other. It is not always necessary to have but it offers several advantages and it is recommended per <a href="https://cloud.google.com/blog/products/containers-kubernetes/kubernetes-best-practices-organizing-with-namespaces">Kubernetes Best Practices</a>. Namespaces help:</p><ul><li>Enforcing roles and responsibilities between the teams, specifying who can access what in the cluster.</li><li>Partitioning landscapes, for example, logically separate staging and production services or app1 and app2.</li></ul><p>In almost every Kubernetes distribution, the cluster comes with several Virtual clusters. An important namespace namedKube-system, contains the Kubernetes system controllers and API. There are few cases where you need to modify the services inside it but it is not always necessary. Another namespace that Kubernetes distributors usually provide is a default namespace for you to create your services. It is called, well, default namespace.</p><p>As per best practices, it is better to organize your application using a namespace and assign the correct roles and responsibility for a team to access and modify it. For our use case, I will create a namespace called production. The following snippet shows how to create a namespace:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ccf3359a1184cf668e20368ba5a02ed5/href">https://medium.com/media/ccf3359a1184cf668e20368ba5a02ed5/href</a></iframe><p>To deploy it, run the following command:</p><pre>kubectl apply -f compose/kubernetes/namespaces/production.yml</pre><h3>Next</h3><p><a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-2-970f1d82b65f">In the next article</a>, I will cover setting up all the requirements prior to release and lunch the application. Moreover, I will cover configurations, secrets and shared volumes.</p><h3>Clean Up</h3><p>If you ran the tutorial, please go ahead and delete the resource group, Azure then will delete every resource in that group. Additionally, delete the service principal that has been created along with the resource group.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c5aa7e683ef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-1-2c5aa7e683ef">Hands-on Day 1 and Day 2 Operations in Kubernetes using Django and AKS — Part 1</a> was originally published in <a href="https://medium.com/compredict">COMPREDICT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[COMPREDICT Platform Architecture — Part 2: in-car logging software]]></title>
            <link>https://medium.com/compredict/compredict-platform-architecture-part-2-in-car-logging-software-35a67ae5f2e5?source=rss----f20477687d0d---4</link>
            <guid isPermaLink="false">https://medium.com/p/35a67ae5f2e5</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[automotive]]></category>
            <category><![CDATA[predictive-maintenance]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[platform]]></category>
            <dc:creator><![CDATA[Vitalij Funk]]></dc:creator>
            <pubDate>Thu, 20 Aug 2020 09:56:25 GMT</pubDate>
            <atom:updated>2020-09-08T14:52:25.879Z</atom:updated>
            <content:encoded><![CDATA[<h3>COMPREDICT Platform Architecture — Part 2: in-car logging software</h3><p><strong>Co-written by </strong><a href="https://medium.com/u/ea582669b6c1"><strong>Simon Sander</strong></a></p><p>Nowadays, collecting data from every kind of components and systems has already moved in the focus of several industry areas. The automotive industry is one of the pushing sectors accelerating the data logging of millions of cars. This data can contain information about the electrical, mechanical or thermal state of several different vehicle components. The challenge is to not only log and store this data but rather to log the big amount of information over a car’s life without information loss and with high sampling rate. Further challenge is to extract the right information from this large amount of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*i9fqe0PlOqO4_6IGGdBplQ.png" /><figcaption>in-car logging hardware</figcaption></figure><p>We at COMPREDICT are able to not only collect data from vehicles in an accurate way but also to pre- and post-process, stream, save, analyze and visualize it. To demonstrate our real-time algorithms to our customers, we applied our Tesla Model 3 with our in-car logging hardware and some additional analog sensors. In the following, we will give an overview of the software parts which are running on our in-car logging hardware. Starting with the overview of the software services, a short introduction to our engineering capabilities like virtual sensors, load spectra computation and damage prediction follows. Then, we will explain the real-time visualization and analytics interface which is used to showcase our proprietary algorithms. Finally, we will introduce the connection to our datalake and analytics platform.</p><h3>Pipeline</h3><p>Our in-car logging software distributes the measurements of physical conditions in a vehicle over an inter-process communication mechanism to process the data, visualize the outputs of our algorithms in real-time and upload the data to our datalake. The following picture describes the basic flow of our in-car logging software.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vjwpiYq4l8IQERCNII9TEA.png" /><figcaption>in-car logging software overview</figcaption></figure><p>At the beginning of the logging process, physical conditions of the car are recorded from different sources, in our case the Control Area Network (CAN bus) and some additional analog sensors. Therefore we built small software packages (logging services) which collect these data and distribute them over an inter-process communication.</p><p>We went for an inter-process communication to have a clear interface for further program parts on the one hand and not to suffer any loss of speed on the other hand. Here we use the <a href="https://zeromq.org/">ZeroMQ</a> messaging library due to its high distribution and third-party bindings for many popular programming languages. Furthermore, we standardized the data structure of our distributed data with <a href="https://developers.google.com/protocol-buffers">Protocol Buffers</a> to achieve a simple and high-performance serialization and deserialization of the data records.</p><p>Since the data of the CAN bus and the analog sensors are sent at different sampling rates, the data is synchronized centrally in the logging services. This synchronization is implemented with a zero-order holding block, so that all data records belonging to a sample interval are broadcasted in an atomic step. All other services that want to process this data can subscribe to the data via the <a href="https://rfc.zeromq.org/spec/29/">Publisher/Subscriber pattern</a> and always receive the most current data at an evenly spaced exact interval.</p><p>The collected data is currently subscribed by three data-processing services, which are discussed in detail in the following sections.</p><h3><strong>Virtual sensors, load spectra computation and damage prediction</strong></h3><p>In the Algorithm-Module Service, we pre- and postprocess the available signals with precompiled models. These models represent the basis for our virtual sensors, load spectra computation and damage prediction. As described in detail in the <a href="https://medium.com/compredict/compredicts-purely-can-based-virtual-sensors-4c9f37a3a6ae">previous article</a>, we at COMPREDICT develop virtual sensors. That means that we are fusioning already available signals in order to generate additional information, which is either non-measured or non-measurable. The reason why we are doing this is simple.</p><p>Let us take an example. Cars are very complex systems, full of electronic and mechanic devices. In order to perfectly control or assess the current status of the entire system, sensors are required that measure physical quantities such as torque, force, temperature, pressure, friction, wear etc. However, due to high costs, space limitation or reliability issues, dedicated physical sensors are not implemented for every component and system in series-production cars. In most passenger cars, the signal transmission and communication between control units, sensors or actuators takes place via CAN bus. To close the gap of limited physical sensor application and to be able to have sensing capabilities on all damage-relevant vehicle components without running in above-mentioned aspects, we have developed a strong expertise in the AI-based virtual sensor technology over the last years (see an example of virtual sensor in the following figure).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RU2cuu-DfS9hso7qNLmruw.png" /><figcaption>Comparison between hardware sensor and virtual sensor</figcaption></figure><p>In a nutshell, a COMPREDICT virtual sensor is a small software package that uses only the existing signals from the CAN bus of a vehicle and generates new additional information to better understand the health state of car components and systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UbD6rzaMb8S5sQ8f6wsORQ.png" /><figcaption>COMPREDICTs virtual sensors, in scopes: example of used CAN signals, in red: target signal</figcaption></figure><p>The development of such virtual sensors varies and depends on the problem complexity and available signals. This process begins with feature selection and extraction, continues with mathematical modelling and system identification, and ends with the combination of approaches of optimization and machine learning. The picture shows some examples of virtual sensors for which we already have solutions.</p><p>Besides the virtual sensors, we generate multidimensional load spectra and predict damage status of several vehicle components. Why are we doing that? Durability science tells us that nothing is endless, and this also applies to the service life of car parts. Everyone of us drives a car differently, one can be a sporty driver, the other only drives on bad roads. Depending on the driving style and behavior, the lifetime of the components is impacted in the same way. To know when and why a component fails, we record the loads that affect each component and calculate the current damage status. This is very helpful not only for the car manufacturers to analyze and improve cars but for fleet managers as well to optimize maintenance plans.</p><h3><strong>Real-time visualization</strong></h3><p>The AnalyticsRT Service processes the live data from our in-car logging system so that it can be displayed on a mobile device in real-time. This real-time visualization is implemented in a WebApp, so that a simple web browser can be used to call the interface.</p><p>For this purpose, both the measurement data (CAN, analog sensors) and the processed data (Algorithm Module) are received by ZeroMQ via the predefined interfaces. To be able to smoothly display the large amount of information on mobile devices, various optimization measures have been taken with regard to transmission speed and data volume.</p><p>First of all, we send the data to the respective client via <a href="https://tools.ietf.org/html/rfc6455">Websockets</a>, which offer full duplex communication channels over a single TCP connection. This reduces the HTTP header overhead and allows a response channel to request specific data sets. Secondly, we can use the response channel to specifically request the necessary signals for the visualization of the sub-page. The amount of data to be transmitted can also be reduced by adjusting the transmission rate and by bundling several time steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ciVhAOM6Z3ccV1pm7Oxn7w.gif" /><figcaption>Cut-out from a realtime damage visualization</figcaption></figure><p>For example, we analyze the driving behavior and usage, and translate it to an indicator for the current load status of the individual components. In the animation, this is depicted by the change of color of a particular component. Green means that the load is low, while red symbolizes a high loading condition. For example, a strong braking request from high speed will partcularly heat up and wear the brakes, which results in a red color for the brake system.</p><p>In parallel, we predict the total damage or wear of given components and systems based on the usage history and the outputs of our virtual sensors. Let us explain it in more detail for a tire.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nN1elqqqQDlO3rcceqrTuA.gif" /><figcaption>Example of damage and remaining service life calculation for tire rear left, and the virtual sensor of longitudinal force</figcaption></figure><p>In the animation, we can see that the prediction of the current health status says that 30% have been reached. This means that the tire profile has diminished by 30% comparing a new tire with a tire which has to be replaced. Besides this, we are also capable to forecast the remaining service life of the tire. Here, the forecast says that the remaining service life is about 64.000km. Forecasting the end-of-life of a tire means that the probability that the tire has to be replaced after the computed remaining driving distance in km is very high. Furthermore, through the WebApp, we are able to visualize the performance of our virtual sensors and thus the loading conditions of the tire like longitudinal, lateral and vertical dynamic forces in real-time.</p><p>As one of the result of our analysis, we compute the load profile of the tire on basis of our virtual sensors, like depicted hereunder. This shows the complete and accurate usage history of the tire. This information is of relevance for design or durability engineers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M7PZ3pMto-Kp4gWegb470g.png" /><figcaption>Rear left tire — Load spectrum</figcaption></figure><h3><strong>Datalake and Analytics</strong></h3><p>Finally, the Upload Service bundles the data from the various services, compresses it and uploads it to our datalake via a mobile data connection. In our datalake, we store all our data<em> </em>generated from our own vehicles, project-related data, data streamed or sent to us, etc. There we apply ETL jobs to extract the useful information from the data or to trigger our AI-based analytics tools, and convert it, if necessary, in order to display it on our analytics platform, COMPREDICT Analytics.</p><p>COMPREDICT Analytics offers a user interface to visualize and manage data. Furthermore, it allows the user to execute our proprietary algorithms hosted in the <a href="https://medium.com/compredict/compredict-platform-architecture-part-1-ai-core-ml-framework-648bc2e1b841">AI Core</a>, for example with the data from our logging platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lFiibL01xPoP2h0embXGNg.png" /><figcaption><em>COMPREDICT Analytics — left: trips and damage overview, right: time series analysing</em></figcaption></figure><p>In the next article, COMPREDICT Platform Architecture –Part 3, we will discuss our <em>COMPREDICT Analytics </em>platform into more detail. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35a67ae5f2e5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/compredict/compredict-platform-architecture-part-2-in-car-logging-software-35a67ae5f2e5">COMPREDICT Platform Architecture — Part 2: in-car logging software</a> was originally published in <a href="https://medium.com/compredict">COMPREDICT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting and Forecasting Fatigue Damage of Automotive Components]]></title>
            <link>https://medium.com/compredict/predicting-and-forecasting-fatigue-damage-of-automotive-components-f6bf5f6bb9e2?source=rss----f20477687d0d---4</link>
            <guid isPermaLink="false">https://medium.com/p/f6bf5f6bb9e2</guid>
            <category><![CDATA[predictive-maintenance]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[automotive-engineering]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Ousama Esbel]]></dc:creator>
            <pubDate>Fri, 26 Jun 2020 13:45:25 GMT</pubDate>
            <atom:updated>2020-09-14T07:50:31.295Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>This article is a continuation work on previous publication¹: Predicting and Forecasting the Lifetime of Automotive Vehicle Components.</blockquote><p>Nowadays, vehicle reliability is becoming an ever more important core aspect of automotive engineering to anticipate the trends towards car sharing and autonomous driving. The flawless operation of vehicles for a defined mileage under given loading and environmental conditions is crucial for cost and safety reasons. There are well-established methodologies in durability engineering to assess component reliability under certain constraints such as mileage or load, in order to retrieve a <strong>Remaining Useful Lifetime</strong> (RUL) estimation. These methods are based on damage accumulation, which are mostly semi-empirical approaches, consider only a limited number of variables and do not always capture real-life usage patterns and the actual environmental conditions a component is exposed to. Consequentially, automotive manufacturers and suppliers are forced to consider safety factors during dimensioning in order to minimize the impact of these uncertainties, which leads to over-design.</p><p>The objective of this research is to propose an approach to better estimate the fatigue damage by incorporating yet unconsidered factors and making use of fleet data. We trained a neural network model to leverage typical unconsidered factors such as temperature, road condition and individual usage patterns, and provide an improved RUL estimation for a vehicle component. Then, we use the output of the model to better forecast at which mileage the component will fail by training another neural network model.</p><p>Without further ado, I will illustrate how we generated the reality-like data to train the models of this study. Then, I will explain each model independently including their pre/post processing, model architecture and the final results. Eventually, I will demonstrate the flow on how we serve and online-train the models in production.</p><h3>Dataset</h3><p>Acquiring enough history of vehicles that failed for a specific component can take years to collect. Besides, fatigue damage is an unknown phenomenon, we can’t quantify the damage at any point in the vehicle’s history except when it fails.</p><p>So what we did is that we used real data generated from our Tesla Model3 and ran it in a simulation environment until a component failed, for the experiment, we monitored the rear side-shaft component of the vehicle. In the simulation environment, we control how this component is affected by the unconsidered factors, so we assumed that temperature, humidity and road condition have different and high nonlinear influences on the component lifetime based on the realtime behavior of the given factor. In order to not make the behavior deterministic, we also add some random noise amplifying or reducing the influence of the given factor at each time step. The following steps illustrate how we generate artificial vehicles in a nutshell:</p><ol><li>We collected the time series data generated from our Tesla Model 3 over 30,000 km.</li><li>We generated many trips with different mileage and time using the <a href="https://medium.com/compredict/generate-an-artificial-car-fleet-to-train-and-test-algorithms-a-concrete-use-case-of-drivereal-d7937bf5e9b3?source=collection_home---4------1-----------------------"><strong>driveREAL</strong></a><strong> </strong>algorithm.</li><li>We combined the trips together to build a car history.</li><li>For each trip, we compute two damages on the component: the damage computed based on the state-of-the-art formulas² (damage accumulation based on the Miner rule) that considers the load (torque) and the number of revolutions of the shaft for the given load. This damage value is denoted as <strong>Simple Damage </strong>and represents our baseline model. The other damage is the real damage that we configured in our simulation environment and that incorporates additional factors, nonlinearities and an undeterministic part. We denote it as <strong>Effective Damage.</strong></li></ol><p>The aforementioned process generated thousands of vehicles, where each vehicle has plenty of trips with the following feature space:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*nV2kkEr6Zw786GrUROY4Vw.png" /></figure><p>After understanding the nature of the dataset and where it came from, let me re-phrase the objective of this research:</p><p><em>Given history of driving profiles generated by the driveREAL algorithm in the simulation environment using real driving profiles from our Tesla Model3, can we predict a damage information closer to the effective damage than the damage given by the state-of-the-art formula, i.e. the simple damage, by incorporating unconsidered but relevant factors along with the stress classes? This, noting that the effective damage can only be used for evaluation and never for training because it is unknown in reality. Then, can we use the improved estimation to forecast at what mileage this component will fail?</em></p><h3>Fatigue Prediction Model</h3><p>Due to the fact that in reality we usually only know the true damage value of a component when that component fails (i.e. the damage value is 1), this limits us to train the model solely on moment of failure which reduces the number of training instances drastically. This raises also another issue: we can’t train the model in supervised settings because the target will always be 1 given different histories of driving profiles.</p><p>To tackle the aforementioned problems, we build a model that learns the real damage using a proxy value, such as the ratio of the domain-expert damage value, i.e. the Simple Damage, to the damage at point of failure, i.e. at 1. We denote this ratio as <strong>Calibration Factor.</strong></p><p>After we identified the target, let’s discuss the feature space. The question resides in how can we incorporate the unconsidered factors with stress classes. We followed the method proposed by Bergmeir et al³ to aggregate the stress loads recorded at certain values. However the shortcomings of this preprocessing approach is that the number of features can grow huge by increasing the number of:</p><ul><li>Unconsidered factors.</li><li>Granularity / number of classes of each factor.</li></ul><p>Another problem is that it might generate a sparse matrix which could be harder to train. From a physical point of view, this means that we will have zeros in the matrix, since certain combinations of the factors are impossible. However, both problems can be solved by assuming in-dependency between the factors. Of course, this assumption can be costly as, in reality, the factors could be inter-dependent.</p><p>With data prepared, we trained a Deep MLP model on damaged vehicles to predict the Calibration Factor and predicted the damage at each trip for unseen testing vehicles. In order to assess the uncertainty of the model, we used Monte-Carlo Dropout layers to produce prediction intervals. Based on the results on unseen vehicles, the model is more confident on its predictions the more history a vehicle has. The following figure shows an example of two test vehicles. As a reminder, the Effective Damage of the test vehicles is only depicted for comparison reason. In the reality, this information is not available and accessible at all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q1Asa2uK1ltph6qX3oZEKA.png" /><figcaption>Dropout predictions for a MLP network, the solid green line is the mean of the prediction intervals with shaded area presenting one standard deviation.</figcaption></figure><h3>Fatigue Forecasting Model</h3><p>Once we have a better estimation of the damage, we can then forecast when a component will fail more accurately. So the first step for forecasting is to predict the fatigue damage for all trips of a given vehicle using our previous model. Since the damage predicted occurred in different dissimilar trips, i.e. trips with different distances which make the distance of the anticipated damage unknown, we had to make the distances between all trips constant using <strong>interpolation</strong> to compose damage values at certain distances within the range of the known given damage values.</p><p>Afterwards, we have <strong>de-seasonalized</strong> the damage because the lifespan damage is accumulative and has temporal dependencies, and Machine Learning models tend to perform better when we remove trend and seasonality components from time series.</p><p>Finally, a <strong>sliding window transformation</strong> is applied to extract features from a window of constant size. The features within the window will be split into <em>&lt;features, targets&gt;</em> subsets. The target space in the sliding window might not be enough to predict failure, especially if the interpolation value is small. For example, if the time interval between observations is one hour, then the forecasting horizon is also one hour, which is inconvenient in some cases. There are many different strategies to forecast multiple steps ahead⁴. However, none of these strategies is suitable for our case. Therefore, we developed a new strategy which combines the recursive multi-step forecast and multiple outputs approach in order to recursively predict a failure that will happen in the far future. In this hybrid approach, maximum number of multiple targets will be used in a sense that the dataset will still be big enough to train the model. Afterwards, we use the anticipated multiple outputs to forecast the next damage values recursively. The following figure shows the flow of the hybrid strategy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*YNgr4D0QVxStPcEqAV6Sfw.png" /><figcaption>Hybrid Multi Output and Recursive multi-step strategy to recursively forecast far future damages.</figcaption></figure><p>With that, the data is ready for training the forecast model, the model used is a Deep MLP that takes into account a history of 100 points that are interpolated at interval of 200km and outputs 50 points in the future, this allows us to predict 10,000km at one-shot, i.e., 200 * 50 = 10,000km.</p><p>The following figure shows the complete flow for training and forecasting damage model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*tFL_AU2-W73K0Fd8_DT9uw.png" /><figcaption>Steps for training and serving the forecasting model.</figcaption></figure><h3>End-to-End model</h3><p>At the end, we want to produce a system that can improve the estimation of the fatigue damage by incorporating unconsidered factors in its calculation and hence identify the lifetime of a component. Then, extend what has been learned to forecast the remaining mileage of a vehicle until failure. The artificial but realistic data we trained the models on are just to demonstrate that if the model worked in simulation environment, then it can perform in reality. However, in reality we don’t have enough broken vehicles in our fleet to train the model, so we first train the models to predict the damage computed by the state-of-the-art formula and with every <em>X</em> new trips or <em>N </em>broken vehicles we online train the models to improve the prediction.</p><p>Both models are trained in our ML Framework and hosted in AI Core, our Machine Learning-as-a-service platform. AI Core provides a capability to automatically join multiple models to create a hybrid model. Simply, it just creates a semantic pipeline that defines how and in which order the models it consists of, are run. The pipeline steps can run sequentially, in parallel or both (you can read further about ML Framework and AI Core in this <a href="https://medium.com/compredict/compredict-platform-architecture-part-1-ai-core-ml-framework-648bc2e1b841">article</a>). At the moment, each model is trained individually but the client can request the result of each model separately or jointly using the hybrid model.</p><p>Additionally, we run an offline job in a certain interval to check if there are new data in our fleet to online-train our models. For fatigue prediction model, we check if any vehicles have recently damaged the component we are monitoring, whereas for the forecasting model, we check if the vehicles in our fleet have X new trips.</p><p>The following figure shows the end-to-end flow for training and serving the models:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*gTinYiXGDvsYWR_L3cTO3w.png" /><figcaption>Training, serving and improving the models and ensemble them to a hybrid model</figcaption></figure><h3>References</h3><p>[1] Ousama Esbel, Sebastian Kauschke and Stephan Rinderknecht, <strong>Predicting and Forecasting the Lifetime of Automotive Vehicle Components</strong>, in: 29. VDI-Fachtagung Technische Zuverlässigkeit 2019, Düsseldorf, pages 321–336, VDI Wissensforum GmbH, 2019</p><p>[2] Haibach, Erwin. <strong>Betriebsfestigkeit</strong>. Springer-Verlag Berlin Heidelberg, 2006.</p><p>[3] Philipp Bergmeir. <strong>Enhanced Machine Learning and Data Mining Methods for Analysing Large Hybrid Electric Vehicle Fleets based on Load Spectrum Data</strong>. Wissenschaftliche Reihe Fahrzeugtechnik Universität Stuttgart. Springer Vieweg, 2018.</p><p>[4] Souhaib Ben Taieb, Rob J Hyndman, et al. <strong>Recursive and direct multi-step forecasting: the best of both worlds</strong>. Working paper, 2012.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6bf5f6bb9e2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/compredict/predicting-and-forecasting-fatigue-damage-of-automotive-components-f6bf5f6bb9e2">Predicting and Forecasting Fatigue Damage of Automotive Components</a> was originally published in <a href="https://medium.com/compredict">COMPREDICT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[COMPREDICTs purely CAN-based Virtual Sensors]]></title>
            <link>https://medium.com/compredict/compredicts-purely-can-based-virtual-sensors-4c9f37a3a6ae?source=rss----f20477687d0d---4</link>
            <guid isPermaLink="false">https://medium.com/p/4c9f37a3a6ae</guid>
            <category><![CDATA[automotive]]></category>
            <category><![CDATA[virtual-sensor]]></category>
            <category><![CDATA[tesla]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Rudolf Kraft]]></dc:creator>
            <pubDate>Wed, 08 Apr 2020 19:35:20 GMT</pubDate>
            <atom:updated>2021-11-02T12:11:53.604Z</atom:updated>
            <content:encoded><![CDATA[<h3>Virtual Sensors based on CAN-bus signals</h3><h3>Virtual sensors</h3><p>Sensors are units, that measure physical quantities and transform them into — mostly electrical — signals. Nowadays, sensors are omnipresent in nearly every electronic or mechatronic device we use, from smartphones to TVs going through cars. Sensor signals are used to monitor system states, detect changes in systems and/or control them (like a temperature regulation for an air conditioning system).</p><p>Sensors are physical hardware devices that make use of physical or chemical effects like electric resistance, temperature, pressure or capacity. Very often, the usage of sensors is restricted due to following aspects:</p><ul><li>High costs</li><li>Limited installation space</li><li>Unsuitable environment conditions (temperature, chemical conditions, etc.)</li><li>Wear and/or non-reliability of the sensor</li></ul><p>When physical sensors cannot be installed or are too expensive for a use in series-production devices, one possible alternative is the usage of so-called virtual sensors. Virtual sensors are software-based sensors, which do not directly make use of physical effects, but calculate an estimation of the targeted physical quantity by using other but measurable physical quantities. In a nutshell, virtual sensors deal with data extraction and fusion. The extraction consists of identifying the indirect physical quantities, which contain at least a part of the targeted quantity. The fusion aspect is about recombining the indirect signals by use of physical modeling or artificial intelligence in order to get access to the targeted quantity. Figure 1 demonstrates the difference between a hardware sensor and a virtual sensor: On the left side two physical quantities are measured using one hardware sensor per quantity. On the right the hardware sensor B is replaced by a virtual sensor. The sensor signal B is estimated based on the sensor signal of A and a model of the dependencies between A and B. Of course, in more complex systems an estimation of a quantity might require the fusion of multiple sensors and thus a more complex modeling of the dependencies between all quantities (like time-dependency). As well, approaches to re-calibrate the virtual sensors can be introduced according to the use case and the quality to be reached (e.g. closed-loop virtual sensors).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9V8vZxAR7VqZI4Bpfejp_A.png" /><figcaption>Figure 1: Left: Classic hardware sensors for two physical quantities, Right: hardware sensor B is replaced with a virtual sensor</figcaption></figure><p>Virtual sensors have many advantages over hardware sensors:</p><ul><li>They are much cheaper in TCO (total cost of ownership), from the initial hardware cost, to installation and calibration.</li><li>They do not suffer damage under rough conditions like vibrations or extreme temperatures.</li><li>Via API/SDK, they can be interfaced with existing telematics solutions.</li><li>Their durability and reliability are only limited by the lifetime of the vehicle’s standard components and of the datalogger/telematics solution.</li><li>They do not alter the system under test, adding no additional mass, strain or effort like e.g. a wheel torque sensor would do.</li></ul><h3>Purely CAN-based sensor fusion</h3><p>As you have probably already understood, to build a virtual sensor you also need hardware sensors, which are at other places measuring other quantities than the one you need. The good news is that, in most of the cases, you have hardware sensors anyway. Let’s take a look at the situation in the automotive field, which is our core competence area: a modern vehicle is similar to a driving computer. It contains electronic control units (ECUs) for engine, steering, brakes and much more. All these control units require sensor signals to monitor the current state of the vehicle components and take appropriate actions. This means, that there are standardly available sensors in a vehicle, which are installed by default, i.e. independently from the usage of virtual sensors. All these sensor signals are usually transmitted on the so-called CAN bus. CAN is the abbreviation for <strong>C</strong>ontroller <strong>A</strong>rea <strong>N</strong>etwork and describes the most widespread communication protocol, that is used for signal transmission and communication between control units in a vehicle. Our virtual sensors take part of these signals as inputs to calculate physical quantities for almost all vehicle components (see Figure 2). For our customers this results in minimum effort: no additional sensors, no additional hardware, no specific space requirements, only lines of code. Comparison data coming from a dedicated sensor is only needed during the training phase of the virtual sensors, which are usually measured during development in test vehicles (i.e. measurements of the target signal to calibrate and validate the virtual sensor). We are also currently working intensively on limiting the need for comparison data and are leading research on topics like transfer learning. In any case, the most important thing is that, in operation, no additional physical sensor is required anymore: once the virtual sensor is trained, it is robust and accurate enough to be implemented in every single vehicle from the same type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HIEetT1kXsIZVSWyKfZYvw.png" /><figcaption>Figure 2: COMPREDICTs virtual sensors, in scopes: example of used CAN signals, in red: target signal</figcaption></figure><p>Given the signals on the CAN bus, we apply our sensor fusion algorithms for the estimation of the desired target. This process includes two main steps, which are:</p><ol><li>selecting the best CAN signals and signal contents.</li><li>modeling of the dependencies between these CAN signals and the target signal</li></ol><p>1. Feature selection and extraction: The first step is to find the CAN signals that are most suitable for estimating the target. Considering more signals may improve the estimation, but also make the training more difficult, and increase the required computation power and the memory footprint. If the dependencies between the CAN signals and the target are obvious, you may imagine that the process of selecting the signals is easy. However, when the dependencies are non-trivial or if only a specific part of a given feature is relevant, you must consider other approaches. These can be based on system knowledge, on frequency analysis or on statistics and probability theory. Feature selection and extraction are very wide fields that are still extensively investigated in the context of Machine Learning. For a bit more insight in our approaches, you can have a look at this previous article: <a href="https://medium.com/compredict/time-series-causality-for-machine-learning-interpretability-97fdb9fd979">Time series causality</a>. We will publish some new articles about this topic soon.</p><p>2. Modeling of the dependencies: The features that have been chosen in the first step are then used to estimate the target signal. We use different approaches to handle this challenge. Besides mathematical modeling, we use various approaches of system identification, optimization algorithms and Machine Learning, all included in the more general area of the artificial intelligence. Depending on the complexity of the system, a virtual sensor can rely on only one of these approaches or on a combination of them. Analogous to the number of features, the efficiency of the algorithms directly affects the performance and memory consumption of the virtual sensor.</p><h3>Implementation</h3><p>The virtual sensor can be used both offline and online (see Figure 3). Offline means, that the CAN signals are gathered and saved in a database on a server, and then these data are used to calculate the target signals for further analysis. Online means, that the estimation of the target signal is performed embedded, on a vehicle’s Electronic Control Unit (ECU) and in real-time. The advantage of this approach is that the signal can directly be used to take actions during the vehicle operation or share on the CAN bus to other ECUs. On the other side, running the virtual sensor directly on the ECU requires a particular attention to memory and efficiency, and thus limits the use of certain modeling approaches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R4Xo7_74UcyoAI_3fSSiEQ.png" /><figcaption>Figure 3: Offline vs online virtual sensor</figcaption></figure><h3>Example how data science can be used in automotive industry</h3><p>Let’s take a look at an application example. One interesting physical quantity in automotive vehicles is the dynamic side shaft torque. It can be used not only to estimate the damage and thus the remaining service life of the side shafts and its subcomponents like the joints, but also of drivetrain systems like the gearbox or the tires. Furthermore, it is a useful information for traction and stability control. Unfortunately, measuring the side shaft torque with a dedicated sensor is not that easy. Usually, adhesive strain gauges are applied on the surface of the shafts, but since the shafts rotate during operation, special methods for signal transmission must be considered. Moreover, side shafts can easily come into contact with water, snow, dirt and particles which can damage the strain gauges. This results in expensive, sensitive and unreliable measuring systems that are not suited for series production.</p><p>In contrast, a purely CAN-based virtual sensor does not require any additional hardware sensors in series application. Figure 4 shows signals for a hardware sensor and a virtual sensor for the side shaft torque of our demonstration vehicle, a Tesla Model 3. In this particular case, for development reasons, the virtual sensor is implemented on a data logger connected to the CAN bus and not directly on a ECU (more info about our own developed data-logger incl. web server in a next post). The virtual sensor gives a real-time signal for the side shaft torque. As you can see, the signals match very good (almost perfectly) over the whole amplitude range.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hORN7kQj0WIlLZOTjS3MEw.png" /><figcaption>Figure 4: Comparison of a hardware sensor and a virtual sensor for the side shaft torque of a Tesla Model 3</figcaption></figure><p>Of course, virtual sensors can be applied not only in automotive vehicles, but in every mechatronic device. We continuously expand our scope of activity, so if you have an interesting field of application, just contact us.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c9f37a3a6ae" width="1" height="1" alt=""><hr><p><a href="https://medium.com/compredict/compredicts-purely-can-based-virtual-sensors-4c9f37a3a6ae">COMPREDICTs purely CAN-based Virtual Sensors</a> was originally published in <a href="https://medium.com/compredict">COMPREDICT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generate an artificial car fleet to train and test algorithms: a concrete use case of driveREAL…]]></title>
            <link>https://medium.com/compredict/generate-an-artificial-car-fleet-to-train-and-test-algorithms-a-concrete-use-case-of-drivereal-d7937bf5e9b3?source=rss----f20477687d0d---4</link>
            <guid isPermaLink="false">https://medium.com/p/d7937bf5e9b3</guid>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[vehicle-fleet]]></category>
            <category><![CDATA[automotive]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Martin Zeller]]></dc:creator>
            <pubDate>Tue, 10 Mar 2020 11:23:02 GMT</pubDate>
            <atom:updated>2020-09-08T12:52:16.545Z</atom:updated>
            <content:encoded><![CDATA[<h3>Generate an artificial car fleet to train and test algorithms: a concrete use case of driveREAL</h3><p>In order to develop, train, test or at least investigate data-driven algorithms, a large amount of conclusive data is required. For an automotive application, this means continuous monitoring from thousands of cars from day one to end-of-life, representing millions of driven kilometers. Such a data scientist dream is still economically as well as, most of the time, technically not manageable. Indeed, besides the colossal time required to gather such a dataset, car manufacturers only have at their disposal very few development cars gathering data for a couple of thousands kilometers at different car development stages.</p><p>This situation is a vicious loop since the only way to gather conclusive and valuable data would be to collect end-user data. This data collection will only be possible with the car owner’s or fleet operator’s acceptance, which can be won by providing them with a new service like a personalized and reliable forecasting of the maintenance work or an estimation of the remaining value when the used car will be sold. These services are mainly based on the computation of key indicators related to durability and fatigue assessment which require non-available data to be developed and tested. This makes closing the loop difficult…</p><p>But <a href="https://compredict.de/">COMPREDICT </a>has the solution for you! And you will learn how an artificial, but reliable and conclusive <strong>car fleet</strong> can be generated from the few already available data, in order to develop new predictive maintenance approaches. This use case is a concrete application of the patented <strong><em>driveREAL</em></strong> method, which covers, however, a broader field of application like the generation of driving cycles and test scenarios for test rigs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*62SP7wGG0trEJLBtFr06PA.png" /></figure><p>In order to generate a fleet of thousands of cars, a database of single <strong>trips </strong>— defined as a driving period between power on and power off events — is generated based on an <strong>aggregated usage profile</strong>. Aggregated usage profile is to be understood as anonymized and compressed, for which no time information is available anymore. Vehicles can then be generated through a recombination of these trips.</p><h3>Trip Generation</h3><p>Trips are generated in a two-step method from an aggregated usage profile. Each trip is composed of timeseries corresponding to different signals representing the behavior or internal states of the vehicle and having physical dependencies between them. Such signals may contain for example vehicle speed, steering angle, wheel torque, but also more complex information like the ratio between combustion engine and electric motor torque for a hybrid car.</p><p>A <strong>usage profile</strong> is used as an input for the trip generation. A usage profile is a matrix, in which the time spent in each driving situation is gathered (one situation = 1 cell in the matrix). The main advantages of such an aggregated usage profile are on the one hand the privacy, which will be discussed later, and on the other hand the extreme compression of the data.</p><p>Such a usage profile is then converted into a so-called transition probability matrix, which represents the probability, given a current driving situation, to reach another driving situation or, rather, state (see picture below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-sLpKFWMU4mDSDaeGJG3uw.png" /><figcaption>Transition probability matrix</figcaption></figure><p>In a first step, <strong>timeseries are stochastically generated</strong> based on the previously described aggregated transition probability matrix and the Markov chain theory. As mentioned before, multiple synchronous timeseries are generated simultaneously in order to catch and reflect physical dependencies.</p><p>In a second step, these timeseries are split into shorter driving events, or rather patterns, in order to build a database of driving segments. This process is called <strong>trip segmenting</strong>.</p><p>Next, driving cycles or rather trips can be very efficiently generated through a <strong>recombination of the trip segments</strong> (see figure 2). The computed trips are built to match specific profiles or distribution of profiles, which are evaluated according to target values for validation parameters (such as damage, consumption, mean velocity, etc.). These driving cycles are finally saved in a database used later for the vehicle generation.</p><p>In order to be able to generate millions of trips within a short period of time, GPU-powered computation and task parallelization are used as a standard by <a href="https://compredict.de/">COMPREDICT</a>.</p><p>For more technical insights about the <strong><em>driveREAL </em></strong>method, please refer to <a href="https://saemobilus.sae.org/content/2018-01-0095/">this publication</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2RzRrcg21OJ29ncB8Zj28Q.png" /><figcaption>Trip generation</figcaption></figure><h3>Car generation</h3><p>The goal of this whole process is to generate a complete vehicle history from day one to end-of-life. Such a history is composed of a succession of trips, where a trip represents the driving period between power on and power off events.</p><p>In order to build a realistic history, environment variables — like temperature or air humidity — are added for each trip as well as charging events for electric vehicles or a rest time between two consecutive trips. As well, regional specificities can be considered, so that usage groups can be generated. This <strong>additional information</strong> is extracted from weather services or third-party databases. This enables to reproduce complex behavior patterns, for example to reflect battery ageing processes.</p><p>Furthermore, the trips can also be <strong>extended with additional timeseries </strong>of state variables, for which no information is usually available. For instance, this can be about high-precision load information like a stress or a strain in a given component. Such additional timeseries are generated thanks to our <strong>virtual sensors</strong>, a proprietary software-based sensing technology of <a href="https://compredict.de/">COMPREDICT</a>, which will be presented in a later blog post.</p><p>At the end, once the vehicles are generated, the corresponding timeseries are finally aggregated into <strong>load spectra </strong>— a compact representation used in durability engineering — in order to perform fatigue or wear assessments and compute durability key indicators for different components — like the drive shafts, the tire or the steering system. These key indicators are later used as a baseline for more complex durability approaches for prediction and forecasting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hoXZ8U8GxiwEqCH_KoO3-w.png" /><figcaption>Car generation</figcaption></figure><h3><strong>Algorithm training and testing</strong></h3><p>Having data from a vehicle fleet is the start point for the development and/or testing of a wide range of <strong>analytics algorithms</strong>. Based on the <strong><em>driveREAL</em></strong> approach, we can generate damage values and load spectra over the complete lifecycle of a given vehicle as well as for many different driving patterns, so that generating a realistic vehicle fleet becomes possible. For example, the artificial vehicle fleet can be used for following use cases:</p><p>· <strong>Vehicles can be compared and sorted </strong>in order to select the most damaging driving patterns and perform a knowledge-based optimization as explained in <a href="https://medium.com/compredict/ecolife%C2%B3-knowledge-and-data-based-approach-for-automotive-design-e3efce91e3b5">this previous post</a>.</p><p>· <strong>Forecast the damage </strong>for the oncoming kilometers for several components by considering the individual driving pattern and external variables, like the environment temperature or humidity, in combination with a confidence interval.</p><p>· Increase the precision of <strong>car health monitoring</strong> by setting up training pipelines while considering strong non-linear effects.</p><h3>Advantages of this workflow</h3><p>This workflow, besides being an end-to-end solution to generate an artificial car fleet, presents many advantages:</p><p>· <strong>Privacy</strong>: No timeseries relying on any real or private data is saved. The driving cycles are generated stochastically with aggregated and anonymized usage profiles.</p><p>· <strong>Multi-dimensionality</strong>: Many signals with physical dependencies are simultaneously generated. For instance, with this pipeline, we are able to generate a fleet of 100.000 electric cars with information about the front and rear electric motor torques and speeds, the wheel speeds, the brake pressures, the suspension displacements, the steering angle, the vehicle speed and accelerations as well as the battery current, voltage, temperature and state of charge.</p><p>· <strong>Efficiency and Representativity</strong>: Compared to an approach based on a simulation model, this method is more representative since only real driving states are used, avoiding the generation of impossible or non-realistic states, without having to explicitly model them. Additionally, the time and expenses to develop and validate such a complete car simulation model can be saved.</p><p>· <strong>Low input data requirement</strong>: This workflow needs a very low input data amount to generate a complete car fleet with millions of driven kilometers. Good results can be achieved with data coming from a single car driven for a couple of thousands of kilometers in mixed conditions. But, as usual in data-driven approach: the more data available, the better the results!</p><p>· <strong>Diversity of data</strong>: The data generation process contains a stochastic part, so the generated vehicle profiles are diverse. Moreover, through simple levers different driving profiles implying diverse ageing and wear processes can be generated, like a mild driver charging the vehicle battery very often or a sporty driver always deeply discharging the battery.</p><p>In a nutshell, <a href="https://compredict.de/">COMPREDICT </a>proposes with the patented method <strong><em>driveREAL </em></strong>a workflow allowing to generate a realistic and realistic-distributed vehicle fleet with few input data, better than a standard simulation would ever do. This dataset will be the start point for the development of innovative AI based predictive maintenance algorithms.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7937bf5e9b3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/compredict/generate-an-artificial-car-fleet-to-train-and-test-algorithms-a-concrete-use-case-of-drivereal-d7937bf5e9b3">Generate an artificial car fleet to train and test algorithms: a concrete use case of driveREAL…</a> was originally published in <a href="https://medium.com/compredict">COMPREDICT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[COMPREDICT Platform Architecture — Part 1: AI Core & ML Framework]]></title>
            <link>https://medium.com/compredict/compredict-platform-architecture-part-1-ai-core-ml-framework-648bc2e1b841?source=rss----f20477687d0d---4</link>
            <guid isPermaLink="false">https://medium.com/p/648bc2e1b841</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[platform]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ousama Esbel]]></dc:creator>
            <pubDate>Wed, 05 Feb 2020 12:53:47 GMT</pubDate>
            <atom:updated>2020-09-14T07:54:05.093Z</atom:updated>
            <content:encoded><![CDATA[<h3>COMPREDICT Platform Architecture —Part 1: AI Core &amp; ML Framework</h3><p>We at COMPREDICT, provide many services to our partners in the Automotive Industry. These services range from in-car software, through managing data lake, to developing and serving AI models in the cloud. This series of posts will discuss the architecture and technology stack that allow us to accept streamed data, train models and serve them inside a car or in our cloud.</p><h3>Overview</h3><p>Our software-based approach, the <strong><em>COMPREDICT Platform</em></strong>, predicts component failure, personalizes maintenance plans, enables lightweight design and optimizes the development process for automotive components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KvxwGD36akd6wOVDPkTPQg.png" /><figcaption>COMPREDICT Platform</figcaption></figure><p>The picture above describes our complete tech stack and the basic flow of our software, called <strong><em>COMPREDICT Platform</em></strong><em>.</em></p><p>In <a href="https://www.youtube.com/watch?v=Irqm-xIuFjw"><em>in-car software</em></a>, we provide embedded load and lifetime monitoring models to compute usage profiles and assess the lifetime of the components by using virtual sensors relying on sensor fusion and Neural Networks. In a nutshell, our embedded algorithms process and enhance the standard data available in every series-production car (e.g. CAN signals), in order to get access to durability-related information of the components. Once processed, we gather the data generated from the <em>in-car software</em> in an aggregated way by sending the data on a regular discrete schedule (preferred way for now), or in a real-time way by streaming time series. All steps of the <em>in-car software</em> are purely software-based, no additional hardware is required.</p><p>In <em>data lake</em>, we store all data we have (generated from our own vehicles, project-related data, data streamed or sent to us by our partners). Then, we apply ETL jobs on these data to transform them into useful information and use them for inference, training or simply store them in our data warehouse.</p><p>The intelligence unit in our platform is <em>AI Core</em> our algorithm hub, where we develop and serve all our models and expose them by a universal API. The <em>AI Core</em> administrates our algorithms and models, executes training processes when new data is available, and manages tasks, queue and priority.</p><p>Finally, to relieve the customer from the hustle of connecting to the <em>AI Core</em>, we provide an user interface that enables data visualization and stores the algorithms’ results on our web server along with several additional features tailored specifically for automotive engineers, fleet managers or drivers. We call it <em>COMPREDICT Analytics.</em></p><p>Each block will be discussed in depth in different blogs. For this post, I will introduce our Machine Learning Platform that we use to develop our models and how it interacts with our ML-as-a-Service platform, <em>AI Core</em>, where we will walk through in depth about its architecture and workflow.</p><h3>AI Core</h3><p>Our main assets are the state-of-the-art, patented and patent pending models that tackle different engineering domains in the automotive industry (software sensing, design optimization, monitoring and predictive maintenance, simulation tools, testing programs). These models are developed using various tools (Tensorflow, C++, Matlab, pyTorch, etc.). <em>AI Core</em> gathers all our developed algorithms in a single centralized hub and securely exposes these models to our internal team and external customers.</p><p>Additionally, <em>AI Core</em> is capable to run algorithms synchronously and asynchronously by dispatching long term jobs to a background queue system.</p><h4>Technology Stack</h4><p><em>AI Core</em> uses the following technologies:</p><ul><li><strong>Docker </strong>for local and production environment.</li><li>Python <strong>Django </strong>as web framework and <strong>Django Rest Framework</strong> as an API engine.</li><li><strong>Celery </strong>for asynchronous tasks that uses <strong>RabbitMQ </strong>as a queue system.</li><li><strong>Flower </strong>for queue monitoring.</li><li><strong>Postgres </strong>database.</li><li><strong>Dask </strong>to offer distributed training for heavy machine learning related algorithms.</li><li><strong>Python Boost</strong> and <strong>Matlab Runtime</strong> to run C++ and Matlab models respectively in python.</li></ul><h4><strong>Applications</strong></h4><p>Django hosts two applications:</p><ul><li><em>Algorithms: </em>Deals with serving and hosting Machine Learning &amp; Analytics Models.</li><li><em>Users</em>: Manages organizations, users, activities and permissions.</li></ul><p>Each application has its own API for connecting and requesting. For each API, we provide <a href="https://github.com/COMPREDICT-GmbH">SDKs</a> in different languages for fast integration.</p><p><em>Algorithms </em>application offers a base class abstract Model that provides convenient methods for serving models. These methods are overrode by sub-classes that are specialized for a specific model type. Moreover, there are five different types we support:</p><ul><li>C++ Model.</li><li>Fit/Unfit ML and NN models.</li><li>Matlab Model.</li><li>Hybrid Model (An ensemble of the above models).</li></ul><p>For each served model, you can specify the <em>evaluations </em>that you would like to apply to the the predicted values. This can be directly done in the API request by including the parameters of the evaluation method. For instance, most of our virtual sensor models for mechanical components are evaluated by using a <a href="https://en.wikipedia.org/wiki/Rainflow-counting_algorithm">Rainflow-counting method</a>, which is standardly implemented in our platform. Similarly, each served model is versioned, a client can request earlier versions as desired.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/1*5X02uHFhUs7pN8lkv_jsAQ.gif" /><figcaption>API Quick response.</figcaption></figure><p>The API’s response solely depends on the type and the task of the model; it might require short amount of time to process. In this case, the response is sent directly to the client, as shown in the figure on the left.</p><p>On the other hand, the model may require plenty of time to process, hence, the request will be dispatched to the queue and a job id will be given to the requester to query the results later. Conversely, the requester can specify a callback endpoint where <em>AI Core</em> will send the results to once processed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*uK7VJyVfb9NPcCqpLzvgtQ.gif" /><figcaption>API Request dispatched to the queue and response is queried later or POSTed to callback URL.</figcaption></figure><p>Each model has different inputs, outputs and evaluations. Upon listing the algorithms or getting a specific one, you can identify the following:</p><ul><li>The features that are mandatory for the algorithm and the expected output.</li><li>The file formats allowed (JSON, CSV, Parquet, tfrecords).</li><li>Whether it will be processed directly or dispatched to the queue.</li><li>List of the <em>evaluations </em>that the user can use to evaluate the predictions.</li></ul><h4>Privacy and Security</h4><p>At COMPREDICT, we value the privacy of the users. Therefore, <em>AI Core</em> doesn’t store any data sent by the user. However, when the request is escalated to the queue, the results will be locally stored for maximum of three days which gives the user the benefit to query the results at later point. This might cause an issue for certain users that have strict requirements to share the input/output to any 3rd party organization. In order to overcome this issue, we allow the users to configure the API to encrypt the results prior to storing them. The results can then only be decrypted by a key held by them. Likewise, we allow the users to send us encrypted input data, so that the data transit is secure in both directions.</p><p>The encryption mechanism used is the widely implemented RSA algorithm. RSA is a symmetric cryptographic algorithm that requires two different keys; a public key that anyone can hold and use to encrypt the data, and a private key to decrypt the data and should always be kept private. In addition, we use PKCS1 OAEP padding scheme which semantically secure under <em>chosen plaintext attack.</em></p><p>However, once received, we need to decrypt the data in order to run training or inference tasks. After the task is done, the data are then re-encrypted before transfer. To overcome this decryption and re-encryption steps, we are conducting many researches, in collaboration with TU Darmstadt, in the area of developing end-to-end private machine learning models, like using Partial Homomorphic Encryption for training and inference. However, this comes at a cost of jeopardizing the performance of the model.</p><p>In another note, the requests are authenticated using Bearer Authentication. Furthermore, not all algorithms are exposed to the users, each user is configured to access limited list of algorithms. In addition, we use throttling to control the number of requests per user. Based on their subscription option, we can increase the amount of requests they can send per minute and per day.</p><h4><strong>Deployment</strong></h4><p><strong><em>COMPREDICT Platform</em></strong> in general, and specifically <em>AI Core,</em> follow the design principles of microservices architecture. These services are managed and orchestrated by Kubernetes. The reason behind this choice is that it allows us to distribute the application load and ensure stability with replicable and scalable services interacting with each other. For instance, this helps us to separate the loads between different <em>organizations </em>by creating different queues for each one. Hence, for each newly created <em>organization </em>in the dashboard (Managed by <em>Users</em> app), Django will trigger RabbitMQ to create a new queue, and workers are spawned to specifically serve this queue. This helps us to track how much resources each <em>organization </em>consumes. Consequently, we can then adapt the subscription service, if the customer requires more loads and and wants us to scale up the workers of this queue.</p><p>Each queue is prioritized. Moreover, a request can be processed according to a given priority, based on the requester and the requested algorithm. Being that, a user with more permissions can have his/her requests processed faster than a normal user in the same instance.</p><p>Depending on the requested training or inference tasks, our customers may send us huge files for processing (i.e. GBytes of data). Moving these files back and forth between the services is costly. This is mitigated by sharing a scalable, on demand space between the containers. Furthermore, once the data is uploaded, the file will be temporarily stored in the shared space until a worker finish processing it.</p><p>Currently, <em>AI Core</em> is deployed in AWS using the following services EKS, RDS and EFS. However, we recently became partners with Open Telekom Cloud and Microsoft Azure, and we are assessing their capabilities to finally choose which one is best for hosting the solution or parts of it.</p><h3>Machine Learning Platform</h3><p>The motivation behind building a standard tool for building and developing ML and NN models is that there was no reliable, uniform and reproducible pipelines among the data science team.</p><p>Additionally, as we have been working in the last years with different OEMs for various tasks, we were able to identify the best models and architectures that work for specific cases in Automotive Industry. Therefore, we have centralized and built different libraries to:</p><ul><li>Optimize the best models for the task and ease the ability to do transfer learning for similar tasks,</li><li>Analyze and process signals and time series.</li><li>Analyze fatigue of materials.</li></ul><p>This platform is connected to our <em>Feature Store</em> to help our team query the necessary data for the specified task.</p><h4>Technology Stack</h4><p>The platform is a combination of containerized open-sourced frameworks that are further extended to meet our needs:</p><ul><li><a href="https://mlflow.org/"><strong>MLFlow </strong></a>for tracking experiments and storing model’s artefacts.</li><li><strong>Postgres </strong>to store the results of the experiments’ details.</li><li><a href="https://github.com/ml-tooling/ml-workspace"><strong>ML-workspace</strong></a> for managing and standardizing the libraries and tools that a data scientist would need.</li><li><a href="https://github.com/ml-tooling/ml-hub"><strong>ML-hub</strong></a> for spawning and managing the data science team environment.</li></ul><p>ML-workspace is extended to spawn our specified image that includes our built-in libraries.</p><h4>Application</h4><p>Beside managing the environment and libraries, we standardized the project structure. For instance, we extended ML-workspace so that, whenever a new project is created, a certain project skeleton is built and pulled from our Git in order to quickly kick-start the core tasks.</p><p>A project is solely controlled by a JSON configuration file, where the data scientist can set the path to the features and targets, and tweak the feature selection, preprocessing, model parameters, cross-validation, etc... Besides, the user has full control of the project and can further modify it to meet the specific project’s needs.</p><p>Once the model is trained, evaluated and compared with other experimented models, the model along with its preprocessing statistics can be pushed to <em>AI Core</em> through the <em>Algorithms </em>API and is then ready for serving customers. Alternatively, it can be exported and deployed somewhere else, like in a vehicle ECU.</p><h4>Deployment</h4><p>The main server is currently deployed on-premises equipped with various high-performance GPUs from Nvidia. As well, and especially for cross-research, we use AWS EC2 equipped with GPUs or AWS Sagemaker.</p><h3>Conclusion</h3><p>In this post, I have briefly talked about the overview of the <strong><em>COMPREDICT Platform</em></strong>. Then, I explained in details two aspects: <em>AI Core </em>and <em>ML Framework</em>. The following figure shows the current version:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UU0ZRffAm7DTkFHbQyIr9g.png" /><figcaption>COMPREDICT Platform: Unpack AI Core and <em>ML Framework</em></figcaption></figure><p>In the next post, we will discuss the<em> in-car software</em> along with our <em>COMPREDICT Analytics </em>platform.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=648bc2e1b841" width="1" height="1" alt=""><hr><p><a href="https://medium.com/compredict/compredict-platform-architecture-part-1-ai-core-ml-framework-648bc2e1b841">COMPREDICT Platform Architecture — Part 1: AI Core &amp; ML Framework</a> was originally published in <a href="https://medium.com/compredict">COMPREDICT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ecoLIFE³: Knowledge- and Data-based Approach for Automotive Design]]></title>
            <link>https://medium.com/compredict/ecolife%C2%B3-knowledge-and-data-based-approach-for-automotive-design-e3efce91e3b5?source=rss----f20477687d0d---4</link>
            <guid isPermaLink="false">https://medium.com/p/e3efce91e3b5</guid>
            <category><![CDATA[automotive-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[genetic-algorithm]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[automotive]]></category>
            <dc:creator><![CDATA[C. Loytved]]></dc:creator>
            <pubDate>Mon, 23 Dec 2019 11:21:18 GMT</pubDate>
            <atom:updated>2020-09-10T14:16:32.041Z</atom:updated>
            <content:encoded><![CDATA[<p>Today cars “made in Germany” are well known for their robustness and quality standards. But have you ever thought of the fact, that German cars may be overdesigned?</p><p>In this short article, we want to address the problem of overdesign and a possible solution to the problem.</p><p>The first step understanding the problem of overdesign is to look at how design in automotive industry typically works nowadays. Let’s just jump right into the simplified break-down of the process:</p><ul><li>Initially, a broad assumption about the later usage of the component of a car is made. The specifications for the design of the component are derived from the previous experience and assumption on what can be the most damaging usage.</li><li>Next, test drives and simulations refine the specifications of the load onto the component.</li><li>With this information the component design can be optimized, and design details can be added.</li><li>Ensuring that the specifications made in the first step are fulfilled, the component can be released into series-production.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6JBp-lN0UQuoyacY-Nfo4g.png" /><figcaption>Simplified break-down of the component design process in automotive industry</figcaption></figure><p>So far so good, right? Let’s assume the design engineers did their work “well”. Not a single component broke due to the lifetime of the product. Well, the component is perfect, right?</p><p>Let’s look a bit closer. Why did no component fail during the lifetime of the car? To make sure that no design assumption was underestimated, engineers add safety factors based on the motto “Better being safe than sorry”. If done at every small decision, the safety factors add up to a very heavy design called “overdesign”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*35NdYXY8h1nX3I4OFLxCjg.png" /><figcaption>Design assumptions vs reality</figcaption></figure><p>This does not only apply to design decisions themselves, but also to the assumption about usage of the car. The customer might think to have a sportive driving style, asking for a sportive design. But in order to cover all situations engineers will rather consider the worst case, a rally-like car usage. But in the end the reality might rather be a low load profile use like city driving. This is the point where we want to jump in with our patent pending ecoLIFE³ approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WQqxArZ69obhRCwrZRixIg.png" /><figcaption>Feedback loop with ecoLIFE³</figcaption></figure><p>Our approach at COMPREDICT is to give a direct feedback from cars in use to the design engineers using the ecoLIFE³ approach. With the massive amount of data from car usage, a combination of the current knowledge-based and the innovative data-based processes is needed and thus given.</p><p>As you will see our approach enables a paradigm change from overdesign (let no component ever fail) to design only what is needed (accept to replace components for extreme drivers, while saving money and material for the extreme majority of the regular drivers). This change in design strategy saves not only money, but also reduces CO₂ emissions within the given lifetime of the product.</p><p>To realize this, the ecoLIFE³ approach consists of mainly three steps:</p><p>1. extrapolate usage profiles to a reference usage</p><p>2. find best potential for design optimization</p><p>3. choose design depending on criteria like costs, weight, CO₂ footprint, etc.</p><p>To understand this approach, you need to know that the car data is aggregated into usage profiles, so-called load collectives, before the data is transfered from the cars. Load collectives are a typical format in durability engineering, ensuring small data sizes and data privacy, but keeping all the relevant information for the engineer’s work. A general problem with load collectives is, that load collectives from different cars are not directly comparable, since the cars are usually driven for a different time span and mileage.</p><p>Therefore, the first step of the ecoLIFE³ approach is to extrapolate all load collectives to a reference usage. This let alone is a difficult task. The length of the lifetime doesn’t only affect the scaling of the load collectives. There is always a probability of rare events with high load peaks, which have to be considered as well, when extrapolating load collectives… So that you may also refer to data-driven approaches to solve this. But let’s keep this for a different post.</p><p>In the second step — the heart of the approach— all components are being compared and the best potentials for lightweight are being found. To break the problem down, let’s pick a gearbox with two gears as an example. Here, 2 components from 10 different cars (referring to a driver) with their load collectives and damages are given. For this example, the goal could be to make the new component cover 70 % of the drivers (so to say for 30 % it would fail).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dKRLenNTfkpp-zGUDudJyQ.png" /><figcaption>Example of the optimization problem for the profile classification of two different gears</figcaption></figure><p>In this case, there are three solutions to reach this goal. The first solution would be to optimize the design for gear 1 only. In this approach, the design of the second gear would not change. Vice versa, you could only change the design of the gear 2. But in both solutions the design of only one gear will be reduced. So the optimal design would be to reduce both designs, saving weight for gear 1 and gear 2, while still covering 70% of the drivers.</p><p>Now imagine this approach with eight degrees of freedom (e.g. 6 gears and 2 bearings). This is where the complexity grows huge and our genetic algorithm kicks in. It optimizes the driver profile iteratively (from generation to generation) to reduce the design, while still covering the pre-set value of drivers.</p><p>Last but not least the third step is to choose the optimal design, depending on different possible criteria. The two main criteria are cost savings, due to the lighter design (including the cost for replacing the failed components), and CO₂ savings in production and during use, due to lighter design and less used material. Such a design strategy combined with a predictive maintenance method allows to forecast failure and plan required workshop maintenance in advance, while avoiding dangerous failures on the streets. This means that the design would cover less usage profiles but that no additional failures would happen by customers: through our continuous monitoring, prediction and forecasting alsgorithms, critical health states are identified and cars get replacement components before a failure happens (more about it also in a future post).</p><p>In a field study (linked below) it was found out, that this approach can save 5.4% of the overall costs for a transverse 6 gear gearbox. At the same time, the weight was reduced by approximately 18% and savings of 16% CO₂ footprint during production and 56 kg CO₂ emissions per 100 000 km driven were achieved. Therefore, we see a great potential for improvement for the future development process for not only transmissions, but general car components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*4V7eaKA8LLaIQkzTgh-aMQ.png" /><figcaption>Results from the ecoLIFE³ optimization process</figcaption></figure><p>For more information see <strong>Foulard, S. et. al. </strong>(2019):<strong><br> <em>An Approach for a Resource-Efficient Dimensioning of Vehicle Components based on a Holistic Optimization with Real Life Load Data</em><br> </strong>In: 19th International VDI Congress Dritev — Drivetrain for Vehicles, Bonn, Germany, 10.-11. July 2019</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3efce91e3b5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/compredict/ecolife%C2%B3-knowledge-and-data-based-approach-for-automotive-design-e3efce91e3b5">ecoLIFE³: Knowledge- and Data-based Approach for Automotive Design</a> was originally published in <a href="https://medium.com/compredict">COMPREDICT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>