Where To Buy? | ||||
---|---|---|---|---|
No. | Components | Distributor | Link To Buy | |
1 | Raspberry Pi 4 | Amazon | Buy Now |
Welcome to the next tutorial in our raspberry pi programming. In the previous tutorial, we learned how we could run Xbox cloud on our pi 4. We found that we can run any game easily without lag or having raspberry pi shut down, proving that pi 4 is quite a powerful minicomputer. However, this tutorial will demonstrate how to use Python on raspberry to monitor websites. This Python program will execute on Pi 4 and watch over a website, alerting you whenever it changes or goes down. This is accomplished by keeping a straightforward webpage duplicate locally and monitoring for updates. This webpage monitor is straightforward, so it should work well on pi Zero. Throughout this tutorial, we will demonstrate how to develop your custom code to monitor a webpage. With this information, you ought to be able to modify the script to meet your unique requirements. However, for email updates to function, a few settings must be made in the core code.
The lack of an interface makes this project ideal for a headless Pi. Even though this tutorial concentrates on Pi 4, the core code can be used on any device that supports Python 3. That implies that, if you'd want, you could even execute this program on a Windows computer.
Raspberry Pi
Micro SD Card
Power Supply
Ethernet Cable or Wi-Fi
Ensure you have all the components you need to execute your website monitoring program before you begin. These actions include installing Python 3 and the necessary Python libraries. Updates to the package registry and any current packages come first. To make these upgrades, we must execute the following lines in the console on our Pi 4.
sudo apt update
sudo apt upgrade -y
We must make sure that Py 3 and its application manager, "pip," are both installed on the mini-computer. To guarantee that the two packages are loaded, use the below command.
sudo apt install python3 python3-pip
Installing the necessary Python libraries is the last step before writing the program to monitor our web pages. Download the packages for queries, beautiful soup4, and lxml with this line.
pip3 install requests beautifulsoup4 lxml
Having completed the installation of the necessary packages, we can begin drafting our elementary website monitoring code. So that you can understand how everything functions, we'll break this down into its parts. Though the nano editor will work, a more capable integrated development environment (IDE) like Visual Studio Code is recommended. Get started on the Python code to keep an eye on a website with your Raspberry Pi. Websitemonitor.py is the name of the script we'll be working with throughout this guide. Launch nano and enter the following command to begin writing the script.
nano websitemonitor.py
Before we get too far into coding a complex website monitoring program for our RPi, let's start with the simplest possible solution. We shall craft a basic script to retrieve a web page, check its contents against a known master copy, and output an appropriate message if any changes have been made. At the beginning of any script, we must import the packages we'll be working with. These scripts' launch requires the "os," "sys," and "requests" packages.
Os: To communicate with the os, you will need to install the package known as os. For our purposes, we'll be using this to store a copy of our most recent website request in a cache. To detect any modifications, we will check this cache.
Sys – For any arguments supplied to the program, we utilize the sys library to retrieve them. We'll allow the user to provide the URL of the website and the name of the cache in this case.
Requests – Python can only send requests thanks to the requests package.
This allows us to take a certain website's content and save them.
import os
import sys
import requests
Most of our logic will be handled by a function we'll write next. Two parameters must be set for this function: "has the website changed." The first input, the website URL, contains the website's address. We will make we obtain a request from this point forward. The website name, the second parameter, contains the website's name. This is a condensed form of the name used for the cached file. This method will have 3 potential return values: -1 if the webpage is "not ok," 0 if the webpage hasn't changed, and One of the webpages is altered.
def has_website_changed(website_url, website_name):
Keep in mind that indentation is crucial when using Python. Please make careful to keep the indentation when you complete this function.
Now that our function is specified, we can move on to implementing it. To initiate a website request, we must first define the headers sent by the request module. We are doing two things with these headers. For starters, there's the "User-Agent" header. Set it to whatever works best for you. For the most part, we are trying to keep things straightforward here.
Second, we instruct the client and the destination server not to store this request in their cache by setting the "Cache-Control" header to "no-cache." There is no guarantee that the requested web server will comply.
headers = {
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; PIWEBMON)',
'Cache-Control': 'no-cache'
}
The queries package is secure enough to retrieve the passed-in URL with the requested headers. This is a vital part of our RPi's website monitoring software, as it returns the site's current status. This is an example of the get function included in the "requests" package. The "headers" and "website URL" variables are passed in. The result of this query will be saved in the "response" parameter.
response = requests.get(website_url, headers=headers)
Once we've retrieved the website's response, we need to double-check that it was an "OK" response. Simply put, we need to ensure the error code is not below 200 or above 299, inclusive.
If the value is outside our allowed range, we will return "-1" to indicate an error on our end.
if (response.status_code < 200 or response.status_code > 299):
return -1
Let's set up two more variables after verifying the response to ensure we get a proper status code. For now, we'll keep the text of the response we received in a variable called "response text." This variable will allow us to tailor the response wording before saving it. Our RPi website monitor will continue to work with the present form of the answer text for the time being.
As a second step, we set up a variable named "cache filename" to hold the location of our cache's data file. This name will be fabricated using the "website name" argument and the suffix "_cache.txt." If our website's name were to be entered as "theengineeringproject," the resulting filename would be "theengineeringproject cache.txt."
response_text = response.text
cache_filename = website_name + "_cache.txt"
It's possible that the current website's URL won't have a cache file when you initially run the program. We use the "path.exists()" function from the "os" package to see if the cache script already exists. If the cache file doesn't already exist, we make one by opening it with the "w" switch. We then append the text of the current response to the file, allowing our Raspberry Pi to check for updates to the website. Given that this is a brand-new request, we will respond with a value of 0 to indicate that the reply has not changed.
If not os.path.exists(cache_filename):
file_handle = open(cache_filename, "w")
file_handle.write(response_text)
file_handle.close()
return 0
If the program reaches this stage, the "previous response text" variable will need to be updated with the contents of the cache file. Now we'll utilize "r+" with the open function. The following command informs open that we want to be able to read and write to our cache file. After Python finishes reading a file, the stream position is reset to the beginning; thus, we need to use the "seek()" function to return to the beginning. If this is a fresh reply, it will be simpler to truncate the file.
file_handle = open(cache_filename, "r+")
previous_response_text = file_handle.read()
file_handle.seek(0)
We may now check for a match between the answer text and the original one.
If the responses are identical in content, we exit the process by closing the file handle and returning 0. Recall that a value of 0 indicates nothing has changed in the responses. This, together with the else statement, completes our RPi's "has website changed" monitoring function.
if response_text == previous_response_text:
file_handle.close()
return 0
If the responses don't match, our RPi has picked up on a change while keeping tabs on the webpage. If the race were being run right now, it would be in position 0. We then append the updated reply to the file once it has been truncated. The file handle can be closed as soon as the writing is done because it is no longer required. Since the answer has shifted, we send back a 1 to show that it has been updated.
else:
file_handle.truncate()
file_handle.write(response_text)
file_handle.close()
return 1
To continue our RPi-based website monitor, we must now create its main method. This method will be invoked anytime the script is executed. In this script section, we'll mostly be concerned with invoking the function we just made, so it should be rather simple. First, we'll identify the primary role. This is where the real magic happens for our RPi-based webpage monitoring.
def main():
At this point, we can access the "has website changed()" method we've created. This method's initial and next parameters will be passed in via the "sys" package. The web address (Uniform resource locator) will be the first argument. As for the second, it will become the cache file's title. The function's output is saved in the "website status" variable we created.
website_status = has_website_changed(sys.argv[1], sys.argv[2])
Our variables now contain the current online status, so we can use that to inform our output. Our basic website monitoring software for the Raspberry Pi is now complete. We can expand upon this feature to make it possible to communicate via email or text message. This is a basic if, Elif clause that prints out various text based on the input.
if website_status == -1:
print("Non 2XX response while fetching")
elif website_status == 0:
print("Website is the same")
elif website_status == 1:
print("Website has changed")
Last, we can wrap up our script by including the call that activates the script's main method. Using an if clause, we can be sure that the program was actually called and not just loaded as a Python package.
if __name__ == "__main__":
main()
The program can be saved and tested at this stage. What we have provided here is how the completed core code should appear. To save your work in the nano editor, use control + X, followed by Y, and finally, the Return key.
import os
import sys
import requests
def has_website_changed(website_url, website_name):
headers = {
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; PIWEBMON)',
'Cache-Control': 'no-cache'
}
response = requests.get(website_url, headers=headers)
if (response.status_code < 200 or response.status_code > 299):
return -1
response_text = response.text
cache_filename = website_name + "_cache.txt"
If not os.path.exists(cache_filename):
file_handle = open(cache_filename, "w")
file_handle.write(response_text)
file_handle.close()
return 0
file_handle = open(cache_filename, "r+")
previous_response_text = file_handle.read()
file_handle.seek(0)
if response_text == previous_response_text:
file_handle.close()
return 0
else:
file_handle.truncate()
file_handle.write(response_text)
file_handle.close()
return 1
def main():
website_status = has_website_changed(sys.argv[1], sys.argv[2])
if website_status == -1:
print("Non 2XX response while fetching")
elif website_status == 0:
print("Website is the same")
elif website_status == 1:
print("Website has changed")
if __name__ == "__main__":
main()
Seeing that our web monitoring software is complete, it can be deployed on the Raspberry Pi. The following procedures will help us test and verify that the script is functioning properly. Our web monitoring script requires elevated permissions before proceeding. By executing the following line on the RPi, we may grant this access to the website monitoring program.
chmod +x websitemonitor.py
Now that the script has the correct permissions, we can run it. When running this script, you will need to know the URL you want to monitor and the name you want to use for its cache. For our example, we will use "https://www.theengineeringprojects.com/” as our URL to monitor and “project” as our cache name.
python3 websitemonitor.py https://www.theengineeringprojects.com/ project
You may check if the website monitor produced the cache file with the ls command in the console. A text document with the extension "_cache.txt" should be present. Take the "theengineeringprojects cache.txt" file as an illustration. If you execute this script, you may find an issue right away. Metadata can be dynamically set on some websites, meaning that even if the content remains unchanged, each request to the site could result in a slightly different response. If you use our website, you'll see that our script will flag the page as modified whenever we update the core code. In the next part, we'll demonstrate how to use Python's lovely soup to tidy up the outcome and remove anything that could falsely flag the webpage as modified.
Here we'll use beautiful soup to enhance Raspberry Pi's web server monitoring. The beautifulsoup Python module is a potent tool for modifying HTML documents. We may eliminate clutter like style and script tags, for instance. You'll need to adjust the script we built in the last step for this one. A new import is added to the script's initialization. This will bring in the bs4 library and its BeautifulSoup module.
from bs4 import BeautifulSoup
Our new mission must now begin. Any HTML obtained from the queries package will be cleaned up using this method. As a result, our RPi's behavior during web monitoring will become more standardized. Including the following code in the file will define the new method. The HTML material to be processed will be supplied as the sole input to this function.
def cleanup_html(HTML):
A fresh instance of BeautifulSoup is instantiated now. The first argument is the HTML string to be cleaned up. We specify the HTML parser we need to utilize in the second argument. XML is used since it is quick and has all the required features. A faster and more efficient program is always welcome in a resource-constrained environment like our RPi, in which we are executing a web monitor.
soup = BeautifulSoup(HTML, features="lxml")
With BeautifulSoup, we can parse HTML and get rid of unwanted tags. We strip off the "script," "style," and "meta" tags with for loops as well as BeautfulSoup's "select" method. You'll see that the ".extract()" method is called on each loop iteration. When an element matching the given criteria is located, this function deletes it.
for s in soup.select('script'):
s.extract()
for s in soup.select('style'):
s.extract()
for s in soup.select('meta'):
s.extract()
After BeautifulSoup has processed the HTML retrieved by our website monitoring software, we can return it. It's not enough to return your soup object to its current state. Alternatively, the "str()" function must be used to transform it into a regular string.
return str(soup)
Our "cleanup html()" function is complete; now, we only need to update some other code to use it. Locate the piece of code below and change it. Instead of storing the reply text without thinking, we first pass it through the new method. The "has website changed()" method is where you'll want to put it.
Substitute the following for the sentence.
response_text = cleanup_html(response.text)
Once you've finished editing the script, the program should resemble what we've displayed below. To save your work when using nano, use control + X, followed by Y, and finally, the Return key.
import os
import sys
import requests
from bs4 import BeautifulSoup
def cleanup_html(HTML):
soup = BeautifulSoup(HTML, features="lxml")
for s in soup.select('script'):
s.extract()
for s in soup.select('style'):
s.extract()
for s in soup.select('meta'):
s.extract()
return str(soup)
def has_website_changed(website_url, website_name):
headers = {
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; PIWEBMON)',
'Cache-Control': 'no-cache'
}
response = requests.get(website_url, headers=headers)
if (response.status_code < 200 or response.status_code > 299):
return -1
response_text = cleanup_html(response.text)
cache_filename = website_name + "_cache.txt"
If not os.path.exists(cache_filename):
file_handle = open(cache_filename, "w")
file_handle.write(response_text)
file_handle.close()
return 0
file_handle = open(cache_filename, "r+")
previous_response_text = file_handle.read()
file_handle.seek(0)
if response_text == previous_response_text:
file_handle.close()
return 0
else:
file_handle.truncate()
file_handle.write(response_text)
file_handle.close()
return 1
def main():
website_status = has_website_changed(sys.argv[1], sys.argv[2])
if website_status == -1:
print("Non 2XX response while fetching")
elif website_status == 0:
print("Website is the same")
elif website_status == 1:
print("Website has changed")
if __name__ == "__main__":
main()
The script is ready for further testing. More stable outcomes are expected this time around. We can decrease the likelihood of a false detection by eliminating the "script," "style," and "meta" tags. For instance, every query on our website must not be recorded as "modified" if you follow this pattern.
Our Raspberry Pi monitoring system is somewhat useless without a way to be alerted when a website has been updated. We'll add to our functionality here by notifying you through email anytime the script notices a shift. Remember that this will necessitate you to have the SMTP information for your email provider at hand. Here, we'll use the SMTP settings for Gmail as an example.
We must import a separate package to make SMTP connections from within Python. Thankfully, Python already has this module built in. Include the following line in your script's imports. This line will make it possible to establish SMTP connections quickly by importing the necessary "smtplib" package.
import smtplib
At the outset of the Python code, we must define certain constants. Below the existing "import" command, add the lines below. The fact that Python doesn't truly support constants doesn't stop us from naming these parameters with all capital letters, though. You shouldn't modify these values while the program is running.
Identity for your outgoing mail server (Simple mail transfer protocol) connection, as defined by this constant. This is the account you'll use to access Gmail.
We refer to the value saved in this constant for the simple mail transfer protocol connection.
SMTP_USER='example@gmail.com'
The SMTP user's password must be set inside this constant. This is the password for your Gmail account. Second-factor authentication (which you should enable) requires a separate app passcode.
SMTP_PASSWORD='PASSWORD'
The address or URL to which the SMTP connection should be established is saved in the "SMTP HOST" constant. Here, we'll use the SMTP server information for Gmail as an example.
SMTP_HOST='smtp.gmail.com'
Using this setting, we tell our RPi web monitor which port to use when it detects a change and needs to notify us through email. Using Gmail's port for implicit SSL, as shown below: (port 465).
SMTP_PORT=465
These days, most email providers offer a secure connection (SSL or TLS). Our software will only be able to utilize HTTPS protocol. Ensure the constant is set to True to activate this support. By setting this to False, SSL will be turned off.
SMTP_SSL=True
At long last, we have the option to designate the sender's email address for this message. It must be an account you have created to use this email. If you're using an Email account, this should be a verified email address. You need to set up that email account and domain in your transaction email provider, such as Mailgun.
SMTP_FROM_EMAIL='example@gmail.com'
The final required setting is the destination email address for the script to use to send the email. Enter the email address at which you would like to be notified of updates to the website.
SMTP_TO_EMAIL='sendto@gmail.com'
Our "email notification()" method can be written when we have declared all necessary constants. This function will take care of the process of connecting to an SMTP server and sending an email. Let's begin by identifying our new role. There will be two inputs for it.
def email_notification(subject, message):
Initiating an SMTP session is the first step of this method. Since we need to accommodate both SSL and non-encrypted connections, we'll have to make two distinct calls separated by an if clause. An SMTP session is established and saved in the "SMTP server" parameter if the "SMTP SSL" flag is set to True. When SSL is not enabled, we also take this action. We include the SMTP HOST and SMTP PORT environment variables when establishing the link.
if (SMTP_SSL):
smtp_server = smtplib.SMTP_SSL(SMTP_HOST, SMTP_PORT)
else:
smtp_server = smtplib.SMTP(SMTP_HOST, SMTP_PORT)
After establishing contact with the SMTP mail server, we can start composing and sending the email. We'll first fire off an "eh" to the server. We won't delve too deeply into what this information conveys to the server. The next step is to send an authentication message to the server. The credentials saved in the variables "SMTP USER" and "SMTP PASSWORD" will be sent along with this login request.
smtp_server.help()
smtp_server.login(SMTP_USER, SMTP_PASSWORD)
The next thing we need to do is compose the message sent via the SMTP connection. This is crucial since it allows our Raspberry Pi to send you an alert if it detects a change to the website you've instructed it to monitor. This structure is adaptable to your needs. To avoid any confusion, please use the "FROM," "Too," and "Subject" lines as shown here. On different lines, please. In addition, one blank line should precede the main body of your email.
email_text = \
"""From: %s
To: %s
Subject: %s
%s
""" % (SMTP_FROM_EMAIL, SMTP_TO_EMAIL, subject, message)
As the final step of this procedure, we transmit the email over our SMTP session. The previously generated email, along with the email address from "SMTP FROM EMAIL" and the destination email address from "SMTP TO EMAIL," are passed into this function call. After the message has been transmitted, we terminate the SMTP session.
smtp_server.sendmail(SMTP_FROM_EMAIL, SMTP_TO_EMAIL, email_text)
smtp_server.close()
Since the necessary method has been written, it must be called from within the program. Here, we'll modify the "main()" procedure. You need to locate the line below in your Python code.
print("Non 2XX response while fetching")
Follow that with the line below. The script will automatically send you an email to notify you every time the RPi web monitor encounters an error connecting to the webpage.
Moreover, we should have a line that alerts us whenever the webpage updates. Check your script for the following line. Ideally, it would be located below the previously discovered line. Try to find the following:
The following line should be added above it. Every time this line is reached, an email will notify you that the web has been updated.
After making the necessary modifications, your script's core code should resemble what we have provided as an example. Before moving forward, make sure to save your code. Your website monitoring service should now send you email alerts if functioning properly. It will send a notification email whenever it is launched and detects a change to the website. This website will, however, notify you by email if it becomes unavailable or produces a status code other than 2XX.
import os
import sys
import requests
from bs4 import BeautifulSoup
import smtplib
SMTP_USER='example@gmail.com'
SMTP_PASSWORD='password'
SMTP_HOST='smtp.gmail.com'
SMTP_PORT='465'
SMTP_SSL=True
SMTP_FROM_EMAIL='example@gmail.com'
SMTP_TO_EMAIL='sendto@gmail.com'
def email_notification(subject, message):
"Send an email notification.
Message - The message to send as the body of the email.
"""
if (SMTP_SSL):
smtp_server = smtplib.SMTP_SSL(SMTP_HOST, SMTP_PORT)
else:
smtp_server = smtplib.SMTP(SMTP_HOST, SMTP_PORT)
smtp_server.ehlo()
smtp_server.login(SMTP_USER, SMTP_PASSWORD)
email_text = \
"""From: %s
To: %s
Subject: %s
%s
""" % (SMTP_FROM_EMAIL, SMTP_TO_EMAIL, subject, message)
smtp_server.sendmail(SMTP_FROM_EMAIL, SMTP_TO_EMAIL, email_text)
smtp_server.close()
def cleanup_html(html):
"""Cleanup the HTML content.
html - A string containg HTML.
"""
soup = BeautifulSoup(html, features="lxml")
for s in soup.select('script'):
s.extract()
for s in soup.select('style'):
s.extract()
for s in soup.select('meta'):
s.extract()
return str(soup)
def has_website_changed(website_url, website_name):
"""Check if a website has changed since the last request.
website_url - URL that you want to monitor for changes.
website_name - Name used for the cache file.
"""
headers = {
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; PIWEBMON)',
'Cache-Control': 'no-cache'
}
response = requests.get(website_url, headers=headers)
if (response.status_code < 200 or response.status_code > 299):
return -1
response_text = cleanup_html(response.text)
cache_filename = website_name + "_cache.txt"
if not os.path.exists(cache_filename):
file_handle = open(cache_filename, "w")
file_handle.write(response_text)
file_handle.close()
return 0
file_handle = open(cache_filename, "r+")
previous_response_text = file_handle.read()
file_handle.seek(0)
if response_text == previous_response_text:
file_handle.close()
return 0
else:
file_handle.truncate()
file_handle.write(response_text)
file_handle.close()
return 1
def main():
"""Check if the passed in website has changed."""
website_status = has_website_changed(sys.argv[1], sys.argv[2])
if website_status == -1:
email_notification("An Error has Occurred", "Error While Fetching " + sys.argv[1])
print("Non 2XX response while fetching")
elif website_status == 0:
print("Website is the same")
elif website_status == 1:
email_notification("A Change has Occurred", sys.argv[1] + " has changed.")
print("Website has changed")
if __name__ == "__main__":
main()
If you've taken the time to write a Python script to keep tabs on many websites, you'll want to set it to run regularly. You may implement an infinite loop to make the script run indefinitely; however, a cronjob will suffice. Our Python program must be installed on the RPi before you continue. You can grab the core code from the Git repo if you'd rather skip the intro. Be careful to complete the SMTP connection information. This instruction section assumes the script is located in the "pi" user's home directory (/home/pi/). After making the necessary changes to the crontab, our program will be run automatically every minute.
Start modifying the active user's crontab with this command.
crontab -e
When requested to choose a text editor, we suggest "nano." Please insert the following line at the end of the document. If you wish to track a certain URL, you'll need to make a small change to the command. In addition, a cache name must be specified. The cache name is optional and can be any string that helps you distinguish this request from others. Insert at the end.
CTRL + X, Y, and ENTER will save your changes to crontab. A new minutely check of the specified website will now be performed by your RPi. The software will notify you if it identifies a modification to a page's content.
Encourages problem-free operation of systems
To maintain optimal performance and satisfy clients, monitoring the website is essential. Customers are in a buying mood and don't want to wait for webpages to open or for controls that don't work. If you own an online store, you should examine key performance indicators such as daily bounce rates and page load time. However, regular usability testing will ensure consistent functionality and keep visitors returning.
Keeps a site running smoothly and efficiently
A growing top line is a sign of a healthy website. However, you will not be able to spot warning signs unless you understand your typical exchange rates and annual peaks. Monitoring your statistics can provide a clear picture of your website's performance.
Detailed user insights are revealed.
One of the essential benefits of web tracking is the ability to uncover hidden user and product possibilities. This may be achieved by setting up quarterly or monthly usability tracking based on your staff's population and your website's structure. One of the most effective strategies to enhance your site and raise customer satisfaction is demonstrating empathy for your customers by performing routine monitoring activities like analyzing comments.
E-commerce transactions can be optimized using customer feedback, for example, by removing an extra photo or description step between the product selection and the shopping basket. There's a chance that another user will vent their annoyance over not being able to access subscriber-only deals. If you take the time to listen to and empathize with your users' complaints, follow up with them to let them know they must sign in to obtain the offer and assure them that the site will be improved soon.
assures usability and boosts return on investment
Users may not be able to access and engage with your website in the event of downtime or page breaks. Prolonged outages can lead to being de-indexed, dropped in search engine rankings, and a dent in your reputation. No one will wait for a down website. Customers are not easily won back, and doing so requires an investment of both time and resources. If your site goes down in Perth but remains accessible in Sydney, you won't realize the difference unless you watch it constantly. In an emergency, tracking can assist you alert consumers and fixing any accessibility problems before they affect users.
In addition to preventing disruptions in the future, automatic downtime monitoring can provide real-time alerts by studying past incidents. Whether you need to check if your SSL certificate has expired or if there is an API problem affecting site speed, automation and control can help.
Facilitates easy interaction
When servers go down, your website becomes inaccessible, and so does all of your correspondence. Because of the prevalence of remote work and international teams, port failures have become increasingly expensive. Unfortunately, there is no viable or efficient way to communicate by text message on a mobile device.
Servers and port monitoring are often included in downtime monitoring software. Systems and tools make it easy to resolve communication issues between teams, offices, and nations. Customers will appreciate the timely alerts, and your employees will appreciate the mental stimulation.
There are, of course, a few drawbacks to keeping an eye on your website. To decide if tracking is the best option for you and the team, consider these drawbacks. Some sites and portals may have a foundation of cybersecurity or automatic monitors; depending on your firm's specifics, you may just need a few more tools and processes. There is a silver lining to every cloud in the website monitoring storm. This article will provide some advice and solutions to help you deal with the drawbacks.
Costly
The cost of a good website monitoring technology might be a significant drain on a company's resources. Though many products provide free tiers of service, these tiers are sometimes not as feature-rich as paid tiers, leaving you vulnerable to security holes or unsupported APIs. Spending on paid monitoring software, if any, might range from $15 per month to $500 per month, depending on the features you require and the size of your firm.
Consumes a lot of time
Time is a necessary component of the organization, approach, and resource for successful web monitoring. How long would it take, for instance, to become an expert in website monitoring if you taught your current team how to do it? Because of the potential lack of workforce in other areas as a result of a single employee's pivot, training may not always be an option. Assume for a moment that your group possesses the necessary expertise to perform monitoring in-house. You should consider how much effort it will take and whether outsourcing is an option.
Blocklists
Checking in on your website regularly is essential. It's important to check in numerous times a day to ensure no outages. Regrettably, excessive monitoring can raise red flags with your hosting service, leading to your IP address being blocklisted. To some, blocklisting might prevent electronic communications and alert consumers that your site is a security threat, a major downside of website monitoring. However, this problem can be easily fixed by contacting your server and having your IP address allowed.
Monitoring errors
Even the most composed teams can quickly become flustered when confronted with novel tools and increased data. Mistakes in tracking can be caused by several factors, including a failure to communicate, inexperience, and hazy objectives. However, when a team is inundated with information, they may become paralyzed and unable to get the answers they need. Since the point of tracking is to swiftly handle problems within all data available instead of getting mired in data analysis, this may be particularly stressful and disheartening.
This tutorial taught you the fundamentals of setting up a web-based monitoring system on a Raspberry Pi 4. This code will retrieve the most recent version of the given URL each time it is used. Then, the cached response is checked again on the new request to determine if any changes were made. This script will notify you via an outside email server if the URL changes or becomes unavailable. In the following tutorial, we will learn how to build a raspberry pi 4 Wi-Fi extender for our home use.
Hi Guys! hope you are doing great today! We come this time with a complete project to work out together starting from the point at which we sit with the client and receive the logical narratives that represent what they want to implement. We are going to start with a simple project this time and continue increasing the scale and complexity of the requirements through the incoming tutorials. The project we are going to implement today is one of the most common tasks that we can find in every place in our real life which is the control of the garage door. That could be found in private property or commercial buildings or public garages. Too many things need to be controlled in garage doors and several scenarios could come to your mind. However, take it as a rule of thumb that we design our program based on the requirements specified by the customer not based on our thoughts.
Figure 1 images the project with details. As you can see, it is a garage door that is required to be controlled to open, and shut down flexibly and safely. Flexible operation means it needs to open and shut down at any time exchangeable showing operation indicators when it is opening and when it is closing. And safe operation means taking care of the motor and system components when the change between open and shut down commands for not make any kind of hazard to the system components.
The control logic philosophy is a common term you will be used to hear when you meet with the clients who are going to discuss with you the control logic and all scenarios which will be interpreted by you to the control narratives. The following control narratives of the project were decided and designed based on the discussion with the customer who requested the control system and it is as follows:
There will be a control panel with a front panel that has push buttons, indicator lamps, and switches that enable the end user of operating the system including all functions of the control system. that includes one push button for commanding the door to open and one other push-button for instructing the system to shut down the door. In addition, one indicator to show the door is opening, one to show the door is closing, and one to show the door is in ajar status or open slightly.
The system needs to have a safety emergency stop switch to stop the operation at any instant
The system also can switch between opening and shutting down at any time when it is allowed to do
The system needs to be safe and secure from any hazards that might occur due to wrong logic design for example requesting one operation which might cause any damage to the system components like motors
Please note that when the customer lists the requirements he or she does not know about the deep technical details like the system components that the system needs including push buttons, indicating lamps, switches, sensors, and actuators because he or she is supposed to talk at a high level while telling you the requirements and you the one who should translate his requirements into logic narratives and deciding for the whole system components.
Guys! now our work has just started by translating the above high-level requirements into detailed logic narratives and also deciding all system components and input-output lists. Figure 2 shows the garage door project with the system components that include actuators, sensors, switches, push buttons and indicator lamps.
Table 1 lists the system components which include the main motor running up and down for opening and shutting down. Limit switches for preventing the door from opening and shutting down. Also, it includes the indicators and operation status while opening and closing and ajar status as well. Also, one emergency stop is utilized to stop the process at any time. The table includes the component name, description, the related IO type, and address. For example, the main motor of the door can be run in two directions to let it open or shut down. Therefore, two coils are connected through two digital outputs at addresses O:02/0 and O:02/01 which are the third output input card and the first and second channels. Also, two limit switches have been utilized to control the limits up and down to which the door can go. They are connected to two digital inputs at addresses I:01/03 and I:01/04 which are connected to the second digital input card at the 4th and 5th channels. In addition, two push buttons to handle the open and shutdown requests of the door have been connected at addresses I:01/00 and I:01/01 which are the first and second channels of the second digital input card. And the E-stop or the emergency stop has been connected to digital input at address I:01/03 which is the 4th channel of the second digital input card. Last but not least, three lamp indicators are connected via three digital outputs which are connected to addresses O:02/02, O:02/03, and O:02/04 which are the third digital output card in the rack and the third, fourth, and fifth channels respectively.
Table 1: Input-output list of the garage door project
Component |
description |
IOs type |
Address |
Motor up |
Door motor in a clockwise direction |
Digital output |
O:02/0 |
Motor Down |
Door motor in Anticlockwise direction |
Digital output |
O:02/01 |
Limit switch |
Limit switch to stop the door from over spinning |
Digital input |
I:01/03 |
Limit switch |
Limit switch to stop door of over shutting down |
Digital input |
I:01/04 |
OPEN pushbutton |
A pushbutton to request opening the door |
Digital input |
I:01/00 |
Shut down pushbutton |
A pushbutton to request shutting the door down |
Digital input |
I:01/01 |
E-stop pushbutton |
A pushbutton to request an emergency stop |
Digital input |
I:01/02 |
Indicator lamp |
Showing ajar door status |
Digital output |
O:02/02 |
Indicator lamp |
Showing open door status |
Digital output |
O:02/03 |
Indicator lamp |
Showing shutdown door status |
Digital output |
O:02/04 |
Despite this is a simple and short project. And it is our first complete project. We are going systematically step by step to show you guys the right sequence to achieve a ladder logic project work. Again, we have to sit with the customer to get his requirements, and then we interpreted his requirements into a logical narrative and decided on the IOs list and all system components. Now we need to work professionally and create a flow chart that represents the program logic graphically as shown in figure 3. It shows when a request of opening the door has been requested, it checks for any emergency stop or a concurrent stop request is in progress, if no then it is clear and all set to energizing the coil of the contactors that drives the motor to run in Up direction for opening the door right away. Similarly, when a request to shut down the door. The emergency stop is checked and if is there an open door request in progress if the answer is no then it is all the settings to run the motor in the down direction to close the door by activating the related contactor to energize the motor in the direction to shut down the door.
Now guys after completing the design stage in which we have to design the logic and decide on the system components and the logic flow. It is time to program so let my friends open our program editor and write down the program rung by rung based on the flowchart we just have drawn in figure 3. Looking into the ladder logic program, the first rung shows the opening handling request by energizing the output coils of the motor to run in the up direction and energizing the lamp indicator in case there is no emergency stop or a shutting down request in progress. Similarly, the second rung shows the shutdown request handling by activating the coils of the motor to run in the down direction and the indicator lamp to show the process of the shutdown of the door is in progress. That is true when there is no emergency stop is hit and no opening request is in progress. Also, you can see in both rungs for opening and shutting down the door of the garage that, the limit switches are used to prevent the door from opening or over closing for protecting the motors. At last, the third rung shows the indicator of ajar status as long as the door is not completely closed or when it is slightly opened.
Now guys! it is time to open our simulator to check if we already have written the correct logic or if there is something missed or wrong. Let me tell you something before testing your program you should hold and sit back and think about the test case scenarios for not to forget any case that might cause a failure to your program. For this very program we simulate, there are two main scenarios which are testing opening the door and testing closing the door. In addition to the main test case scenarios, there are edge test case scenarios which are testing requesting opposite operations like request opening while a shutdown process is in progress or requesting shutdown while an opening the door is in progress. Or testing requesting process while the E-stop is raised to check the safety of the operation. So let’s get started and take the test cases one by one to see if we have coded our program correctly or if there is an issue to fix.
As you can see guys in Figure 5 in rung 2, the process of opening the door started by hitting the open push button, and because there is no emergency stop and there is no shutdown request in progress, the motor keeps spinning in the up direction and the opening lamp indicator keeps switched on. But up till when this operation will go on?
The process of opening the door is continued successfully until the LS1 is contacted at which the door has reached its final point for protecting the motor from overloading failure.
Also figure 7 shows the indicator of the door status on Ajar status whenever it is slightly opened or when it is not closed all the way.
Now let’s test the shutdown command by hitting the shutdown push button and notice the first rung in the program in figure 8. You can notice the door continues closing see the motor is spinning in the down direction and the indicator lamp showing closing is ON. But until when it will be stopped?
Figure 9 shows the end of the shutting down process of the door of the garage by having the limit switch LS2 reached that protects the motor from over spinning until it burned.
Figure 10 shows one of the edge test cases when the door was opening and all of a sudden operator requested to shut down the door. The test was successful and the operation can be reversed thanks at any time thanks to the good design by having the negative of each contact of the open and close in the other rung request as shown in rungs 1 and 2.
Guys! I would like to thank you all for sharing this tutorial up till this point hoping you all have enjoyed learning and practicing. And, be there with a larger project to take for the next time step by step learn, design, coding the ladder logic program, and enjoy simulating them as we are inside the factory.
Hi friends, today we are going to learn one of the most important instructions in the PLC ladder which is MOVE instruction by which we can move data between different memory storage including input, output, marker, and variables. Also, data of different data types and sizes can be transferred from source to destination and source memory locations. For example data types including char, string, integer, floating, time and date can be transferred between source and destination. Memory location like input, output, and marker memory area can be acting as source or destination. Furthermore, a mask can be utilized to customize and control the part of data to be transferred between source and destination. In that move with a mask, the instruction uses a source address, a destination address, and the mask as well. Guys, please do not worry if you are not understanding what is mentioned hundreds percent because you will get it in more detail and practice with the simulator as well. So let’s continue to learn and practice that MOVE and masked MOVE instruction.
Let’s start with the basic MOVE instruction. Figure 1 shows the typical block of a MOVE instruction in Siemens. It shows two sides for the input and output parameters of the block. Simply, the input EN input shows the contact that enables the block and triggers the movement of data between the source specified by the memory address given at input IN and the destination pointed by the memory address given at output OUT1. Also, output ENO denotes the status of the movement process to indicate the completion of the process.
As shown in the function block of the MOVE instruction shown in figure 1, there are source and destination which are an address of a memory area and can be expected to be byte, word, or double word DWORD or of any datatype like integer, character string, float, time, or date datatype. Some examples of memory size and datatype are listed in table 1 below:
Source (IN) |
Destination (OUT1) |
|
---|---|---|
With IEC check |
Without IEC check |
|
BYTE |
BYTE, WORD, DWORD |
BYTE, WORD, DWORD, SINT, USINT, INT, UINT, DINT, UDINT, TIME, DATE ,TOD, CHAR |
WORD |
WORD, DWORD |
BYTE, WORD, DWORD, SINT, USINT, INT, UINT, DINT, UDINT, TIME, DATE, TOD, CHAR |
DWORD |
DWORD |
BYTE, WORD, DWORD, SINT, USINT, INT, UINT, DINT, UDINT, REAL, TIME, DATE, TOD, CHAR |
SINT |
SINT |
BYTE, WORD, DWORD, SINT, USINT, INT, UINT, DINT, UDINT, TIME, DATE, TOD |
USINT |
USINT, UINT, UDINT |
BYTE, WORD, DWORD, SINT, USINT, INT, UINT, DINT, UDINT, TIME, DATE, TOD |
INT |
INT |
BYTE, WORD, DWORD, SINT, USINT, INT, UINT, DINT, UDINT, TIME, DATE, TOD |
UINT |
UINT, UDINT |
BYTE, WORD, DWORD, SINT, USINT, INT, UINT, DINT, UDINT, TIME, DATE, TOD |
DINT |
DINT |
BYTE, WORD, DWORD, SINT, USINT, INT, UINT, DINT, UDINT, TIME, DATE, TOD |
UDINT |
UDINT |
BYTE, WORD, DWORD, SINT, USINT, INT, UINT, DINT, UDINT, TIME, DATE, TOD |
REAL |
REAL |
DWORD, REAL |
LREAL |
LREAL |
LREAL |
TIME |
TIME |
BYTE, WORD, DWORD, SINT, USINT, INT, UINT, DINT, UDINT, TIME |
DATE |
DATE |
BYTE, WORD, DWORD, SINT, USINT, INT, UINT, DINT, UDINT, DATE |
TOD |
TOD |
BYTE, WORD, DWORD, SINT, USINT, INT, UINT, DINT, UDINT, TOD |
DTL |
DTL |
DTL |
CHAR |
CHAR |
BYTE, WORD, DWORD, CHAR, Character of a string1) |
WCHAR |
WCHAR |
BYTE, WORD, DWORD, CHAR, WCHAR, character of a character string1) |
Figure 2 shows one very basic ladder logic rung that demonstrates the usage of a MOVE instruction. It consists of a contact “trigger” to control activation of the move instruction, the MOVE instruction block which has source and destination memory address MW10 and MW12 respectively. The source and destination in this example represent integer data types.
Guys! Let's simulate this rung to learn together how the MOVE instruction works. Figure 3 shows the case when the MOVE instruction is not activated, in that case as shown in figure 3 the data is not transferred from source to destination.
But after activating the MOVE instruction by enabling the EN of the MOVE block using the contact M0.1, the data is moved from the sources to the destination.
It is important to let you guys know, this MOVE function block can be used to move different types of data types as listed above by providing the address of both source and destination.
Friends! Sometimes we need to move arrays of data. So do your think we are going to move one by one? The answer is yes it is possible but that is too boring to code and the program is getting very lengthy. So there is another version of MOVE instruction that enable us to move a massive amount of variables which is MOVE_BLK instruction. Figure 5 shows the function block of the massive move instruction in a very basic example ladder logic rung. As you see friends, similar to basic MOVE instruction, it has EN and ENO for enabling the instruction and returning its status showing the completion status. Also, it has an input source denoted by the address of the memory storage of the source and the address of the memory location of the destination as well. But you notice that time there is an array of variables or datatypes for source and destination. And there are other parameters called count which denotes the number of items to be moved from source to destination. Let’s simulate this MOVE_BLK instruction to see how it works and the virtues of moving many data items in one command.
Figure 6 shows the execution having the block not activated. On the right part the memory of the source and the destination show array of 5 integers for each. You can notice guys there is no data moved.
Figure 7 shows the data is moved from source to destination after activation of the MOVE_BLK instruction. But wait for a second! Why not all the data been moved? Yes, you are correct friends, because we use count parameters to control how many variables or data items are to be transferred. And it has 3. So the first three data items have been moved only.
Figure 8 shows a simple program that demonstrates the ladder logic rung that uses MOVE instruction. It shows the input contact I:3/0 triggers the move instruction block to activate it and enable data transfer from the 16bits input I:1 to the 16bits output O:2. On the left side, you can see guys the inputs are mirrored at the output by using the MOVE instruction. Now let’s see how we can control the data transfer using a mask to allow only selected bits to be transferred and prevent the others.
The idea behind the masked move instruction is that we utilize an array of bits to be used as a mask to filter the data that are being transferred. For example Figure 9 shows a very simple ladder logic rung that uses a masked MOVE instruction to customize the data transfer from source to destination. The MVM instruction has three parameters as shown in figure 9 which are: the source, destination, and mask. All of them are addresses of the memory area. For the very given example here, the source is the 16 bits input at I:1/0 and the output is the 16 bits output at O:2/0 while the mask is the 16bits input at I:3/0. Before we are going to simulate this example, you should expect that the data will be transferred from source to destination based on the status of every bit in the mask data.
In the first test case shown in figure 10, the data to be transferred is ready at the source but nothing is transferred to the destination because the activating contact I:3/0 is not enabled. So let’s switch it on and see what is happening!
Now we enabled the activation switch at I:3/0 but still, data are not transferred from source to destination! Is there a problem in coding or logic? No, that is because the mask bits are set to off that is why bits of the source are not enabled to be transferred to the destination. Now, let us enable the masked bits and see what’s going on?
Yes! Now guys you can see all bits of the source have been transferred to the destination as long as their mates at the masked bits are enabled. But those who have their mates of bits at the mask are disabled and are still prohibited from being transferred. Like this, you can see friends how we can move data without control as when we use the MOVE instruction. In addition, you see how to control that data transfer by using mask bits as a filter. Do not forget, the move instruction can be utilized to move different data types, variables, memory sizes, and data blocks. So, it is a great tool for you as an experienced ladder logic programmer to flexibly move data between your data variables and memory location through long the program you are writing.
Guys! I would like to thank you for being here with me up till this point of our tutorial hoping you are really happy with it and seeing it is useful. Now guess what? I have a gift for you which is our next tutorial. It is not like every time we come up with another aspect in ladder logic to learn and enjoy practicing simulation. Now we come to the point that we should be counted as real ladder logic programmers because we have learned a lot and practiced more topics. So, it is time to practice a complete project string from reading the logic chart, understanding the logic narrative, and interpreting it to a complete successful ladder logic program. So next time will come up with a complete process with a logic diagram and requirements and practice together step by step. You can consider it as a great workshop in which you will apply all your knowledge base and what you have learned so far to take the responsibility as a PLC ladder logic programmer to convert the logic narrative and diagrams into a real ladder logic program. The work will include deciding the required logic components including switches, relays, inputs, outputs, digital and analog. Then will do a flow chart showing the logic flow based on which the program will be written. And lastly, the coded program will be applied to the plc simulator to verify the logic and make sure it is functioning correctly according to what has been requested at the beginning from the customer. So please be ready, make some revisions, and be there when we are going to learn by practicing a real project as in the real life and industry problems.
Matrices are an essential topic in different fields of study, especially in mathematics, where you have a bulk of data and want to organize, relate, transfer, and perform different operations on data in a better manner. We have studied a lot of types and operations on the matrices and have worked on different types with the help of MATLAB. Today, we are here to present the applications of the matrices in different fields of study to clarify the importance of this topic. So, have a look at the list of topics we are going to learn. Yet, first of all, I am going to describe what a matrix is.
In the fields of physics and mathematics, there is the use of different types of numbers in groups of various types. In order to organize the data into a manageable format, matrices are used. A matrix is a rectangular array of numbers that are enclosed by a square matrix (or, in some cases, parentheses).
The information about the numbers of rows and columns is called the order of matrices, and on the basis of this information, we can recognize different types of matrices. The types, in turn, are used in different applications because of their unique behavior. By changing the order of the matrix, the properties and working of the matrices changes according to the changes. Mostly, square matrices are used in different applications.
It is interesting to know that in the early days of matrices, these were considered arrays. With the passage of time, when they were involved more and more in different research and methodologies, matrices gained popularity. Because of the ease of usage, this popularity is not going to end. So, have a look at the different types of fields where matrices are used in different ways but before going into details, you must know, these fields are not only dependent on the matrices but the normal functioning of these fields include the usage of matrices in different ways.
As we have said earlier, matrices are used to deal with massive amounts of data better. The matrices that we have learned and seen till now are of very minimum order, and these are kept simple for the better concepts in easy ways, but in practice, we have seen that there are gigantic matrices with complex data in them, and at that point, it is difficult to solve and save them manually. Have a look at the different fields of practical life where matrices are used in a routine.
Data cryptography is an important department in data communication in which the encryption of the data is an important process. It is done by using different keys and codes to secure the message and communication in a better way. A large amount of data is sent and received by different parties, and the encryption techniques also require some other space as well. Matrixes are used to make sure that all the data and its codes are stored in a better way. These matrices
save the keys of the encrypted data to decrypt them on the receiving end and in this way, matrices play a key role in cryptography.
We all know that in wireless communication, usually air is used as the medium to send and receive messages from one point to the other. In this process, matrices are used to detect, extract, and process the information about the message that is to be delivered. Here are some other uses of matrices in this department:
Signal estimation and the detection of the problem during communication are done with the help of matrices.
Sensor array signal processing involves the matrices.
In the processing and representation of a digital image, matrices have a great role.
Radar signals
Underwater surveillance
With the help of matrices, wireless communication is done efficiently, and understanding the code becomes easy. Think about the case if the data of different queries are not used in the form of a matrix, then finding the data of a simple command would never be organized.
The use of matrices in the field of mathematics is not new to us. We all know that it is a basic concept in mathematics and a great variety of concepts of matrices are used in different ways while solving mathematical problems. One of the major use in mathematics is a solution of linear equations with the help of matrices. The complex and time taking equations can be easily solved with the help of rules of matrices in different ways.
In engineering and other related fields of mathematics, matrices are the basic concepts and it is used in different ways to make the working of the system better manner. We have seen different cases in which the matrix is used as the alternative method to find the unknown value because it is a more organized way and the great number of research resulted in different theorems and laws therefore, the long calculations are minimized to their result by simply using the theorems.
One of the amazing applications of matrices is in the form of computer graphics where the pictures and the graphics comprise pixels and the array of these pixels and points are arranged in the form of matrices for easy transformation and working. Overall, you can say that in computer graphics, each digital image is treated as a matrix. Therefore, different types of operations used in the matrices are applied to the graphics with great ease. Not only in the dimensions and the sizes but also for the colors of the images, matrices are used to store and reuse the values for the images and graphics. For example, in the CNN technique, different types of matrices are used. For the greyscale image, only a 2D image is used and if one wants to get the RBG system image, there is a need for a 3D matrix.
Gaming is one of the most important filed in graphics and when we talk about three-dimensional games, matrices are important there in order to alter the 3D space in different ways. For this purpose, if we use simple words, the conversions between the 2D and 3D matrices are used by different techniques, and therefore, we get the final output. Moreover, the quality of the result depends upon the way you use the data in different ways.
During the seismic survey in geology, matrices are used in a great way. For real-time surveys of different areas of common real problems such as mortality rate, population, the number of people in different areas of the world, and other specific counting related to real-life problems involve the use of matrices because it becomes easy to deal with great data using different operations on the data.
In different Information technology organizations, matrices are used to execute and search the different queries. The IT security system needs to have a secure way to deal with all the information and once saved, data is to be retrieved in an efficient way with the help of minimum commands. If the data is not present in the form of tables, or we should say, in the form of matrices, organizing, storing, retrieving, and dealing with the data will be like a nightmare.
It is one of the procedures in mathematics in which the values of collinear points are found with the help of matrices. If it seems simple at this time then you should think of the case where gigantic collinear points are found with the help of matrics with the help of different software and these points are in return used in different ways.
As we have said, matrices make the working of daily life data and complex calculations easy. We read different types of commands about the matrices when we were learning about their functioning and therefore, we can now use them in a simple program to prepare the code in which the matrix is used for the pre-allocation of the data in a simple way by using limited lines of codes. Trus, have a look at the code given below:
p=zeros(5)
p(1,:)= [ 3 6 2 8 7]
for i=3:4
p(i,:)=p(i-1,:) +1
end
In this code, we have used a simple function of zeros and used a loop to execute the whole instruction. Let us discuss both of them in detail:
Zeros Function
It is a pre-defined function of MATLAB that is used to make a null matrix of the required dimensions by using just a simple signal command. For the null matrices, there is the condition that the square matrix should be used.
For loop in Matrix
There are certain loops used in the MATLAB and with the help of this for loop, we just have to simply follow the syntax given below:
for index = value
statement
end
Here, the index value is the starting point where we want to start the matrix formation and the statement is the condition that we want to be executed while the formation of our matrix. If it is not clear right now in your mind, just have a look at the flow of the program.
First of all, we have used the zeros function to allocate the space in the memory according to the requirement. We have used the square matrix which has the order of 5 by 5.
I wanted to pre-allocate the values in the matrix row after the row therefore, we simply changed the values of the matrix p formed before from 0 to other values defined by us. If you are not familiar with this function, have a look at the notation given below:
p(a,b)
Where,
a=number of row
b=number of column
As we did not want to alter any value in the columns so we have used a colon in its place.
By using the for loops, we have specified that the index value starts from 3 and ends and 4.
In the next step, we are using these index values and specifying to MATLAB that we want to change the values of the 3rd and 4th rows only and the program ends.
MATLAB does this task step by step and changes the null or zero values of the matrix p into the required pre-allocated values in the matrix.
For the best concepts, we have changed the values of just two rows and the other matrix remains the same.
Larger versions of these kinds of procedures are used in diverse ways to recognize, store, and use the data in a better way, and with the help of this short program, we have seen a glimpse of a real-time application in which a matrix can be used to pre-allocate the different values and people can have benefit from it.
Trus, today, we have learned a lot about matrices and their applications. We have read great information about matrices in the past lectures and it was quite interesting to know how can you use these basic pieces of information in a better way and how people are working on the matrices to make their daily tasks easy during their professional life. We have seen different departments where matrices are making the work easy and more efficient. Most of them can not work without using matrices. Moreover, one must have the idea that many times we use matrices in our daily life unintentionally. As we have said earlier, 3D games require the involvement of a matrix. So, when your child is playing the game, he or she is enjoying the application of the matrices without knowing it. In the end, the small program was helpful to understand how little programs and the working of matrices are helpful to perform different tasks automatically.
Hello learners. Welcome to The Engineering Projects. We all know that matrices have been used in the engineering field for a long time, and they have a vital role in the calculation of different data. Therefore, we are learning about some very special kinds of matrices that are usually introduced to engineers at a higher level. Till now, we have seen some general operations on matrices and also examined the special kinds of matrices. Yet, today, we are moving a step forward and learning about some complex types of matrices that require strong basic concepts. So, have a glimpse at the topics that you are going to learn, and then, we’ll start practicing.
What is a matrix?
What are the different types of matrices that are less common?
How can we implement some interesting commands in MATLAB?
What is the procedure for dealing with complex equations in MATLAB?
First of all, it is recommended to learn about the introduction of the matrix. A matrix has different elements in it with different sequences, and we define it as:
“A matrix is a rectangular array in which different types of elements in the different sequences are present, and all the elements are enclosed in a long bracket that is usually a square bracket.”
The sequence and the values of the matrices are important, and the collection of horizontal lines is called a row. On the other hand, the vertical entries are collectively called columns. To find the difference in the types of matrices, it is important to know that the basic kinds of matrices are square matrix and rectangular matrix. Most of the matrices that we are going to discuss here will be square matrices.
Depending upon different parameters in matrices, these are divided into different types and groups. In a square matrix, the numbers of rows and columns are equal to each other, and in a rectangular matrix, the numbers of rows and columns are never equal. You will observe different parameters on the basis of which these matrices are recognized, and then the behavior of each of them is examined. So have a look at these types.
We all know that boolean numbers mean two conditions only, that are, zero and one. So, the boolean matrix is the type of matrix in which only zero and one value are used, and other values are never involved. The order of the matrix may be anything, but the entries must be either zero or one.
One thing that must be kept in mind is that the matrix will surely have these values in a non-specific pattern and it never has only zero or only one. There must be one and zero of each type. We are clearing it because some other types, such as singular matrix, identity matrix, null matrix, and scalar matrix, also involve zero and one, but in a specific manner.
Boolean numbers and conditions are used in almost every field of mathematics, and therefore, this matrix is also used in different ways in such fields. With the help of a matrix, it becomes easy to deal with a large number of data points at once. The example we have shown here has a small size. Yet, when the boolean matrix is used in practical life, we use a bulk of matrices with greater sizes.
In the previous section, we learned that a transpose of the matrix is obtained when the rows and columns, along with the entries, are interchanged with each other. Keeping this concept in mind, we can define this type of matrix as
A matrix A is called an orthogonal matrix if and only if the multiplication of the matrix A with the transpose of itself provides us with the identity matrix.
If you are new to the identity matrix, then you must know that an identity matrix is one that contains only value 1 in its diagonal and all the entries other than the diagonal are zero.
As we have read about the orthogonal matrices, they remind us of the inverse of the matrix. It is interesting to know that there exists the inverse of a matrix that, when multiplied with the original matrix, delivers us the identity matrix. We hope you remember that an identity matrix is a type of matrix that always has the value 1 in the diagonal elements and zero in all the remaining elements. So, if we are taking matrix A, then for the inverse matrix, we can say:
A.AT= I
In this way, if we have the value of A and want to know the inverse of it, we use the following equation:
AT= I/A
So, in this way, we have observed that no matter if the inverse of the matrix is multiplied with the original matrix or vice versa, we get the identity matrix. This condition is somehow special because the multiplication of the matrix is a more complex operation than addition and subtraction, yet here we are using the rules of the dot product. There is another way to find the inverse of a matrix with the help of a formula that states that the inverse of a matrix A is equal to the determinant of matrix A with an adjoint of A.
There are certain conditions for the existence of a square matrix:
A matrix has the inverse only if it is a square matrix.
If the determinant of the matrix is equal to zero, then there is no need to find the adjoint of that matrix because the inverse does not exist for that matrix.
It is not always necessary that in the inverse of a matrix, the values are reciprocal of the original matrix. The values may also be changed, and by dot multiplication, we can get the identity matrix.
Here is another interesting type of matrix in which all the values show the probability values. We know that the probability values are so small that they are less than one and have fractional values or in the form of points less than one. So, the stochastic matrix has all the probability values as its elements.
You can see all the values are less than one because the probability is usually in the form of such small numbers. If any of the values is greater, then it is not a stochastic matrix.
This is a less common type of matrix in which Ak = O, that is, for every power of the matrix, we get a null matrix (the one with all the values equal to zero). There are two conditions that must be fulfilled in this type:
The matrix A must be square.
We get a null matrix every time we apply any power to matrix A, which is a natural number.
For example, when we take the square of each value of A, we get the null matrix. It is a less common type of matrix, but at a higher level of calculations, it has its applications.
It is a type of uncommon matrix that provides us with a matrix equal to itself when any power is applied to it greater than 2. That is, An = A where the value of n is always equal to or greater than 2. Usually, it has been noticed that if the square of the matrix A is equal to itself, then there is no need to check further because the result remains the same for any number greater than 2. You can take it as homework and find examples of such matrices by yourself.
It seems like you have learned a lot about the special kinds of matrices. When we talk about MATLAB, we have observed that there are different MATLAB commands that are not related directly to the matrices yet are used to make the functioning of a group of numbers and matrices easier and more effective in some cases. So, have a look at some of the commands.
sr# |
Command |
Description |
1 |
inv(A) |
This provides us with the inverse of the matrix A. |
2 |
s,t, complex(s,t) |
It is the way to introduce a complex number in MATLAB. It produces a complex equation with s as a real number and t as an imaginary number. |
3 |
real(A) |
With the help of this command, you can find the real part of the equation saved as equation A. |
4 |
imag(A) |
By using this command, you can easily encounter the real part of the equation saved as equation A. |
5 |
abs(A) |
This command will show us the absolute value of the matrix A. |
6 |
angle(A) |
To find the angle of equation A, we use this command. |
We all know about complex numbers and have also used them in the matrices when we were talking about hermitian metrics. A special kind of function in MATLAB is the “complex” function, which is used to make the complex equation. So have a look at the step-by-step procedure to perform the complex equation in MATLAB.
Hit the start button of MATLAB.
Go to the command window.
Start by writing the following command.
a=3
w=3
It will provide us with two numbers that we will use in the complex function. We are naming this equation ComplexEqaution, and the command to perform this is
ComplexEqaution=complex(a,w)
Press the enter button.
Now, using this equation, we can also find the real and imaginary parts of the equation using different commands. For real numbers, we are writing:
real(ComplexEqaution)
It will give us the real part of the equation. Similarly, write the following command for the imaginary number:
imag(ComplexEqaution)
Similarly, to obtain the absolute value of the equation we have just made, we are using the required command.
abs(ComplexEqaution)
Finally, to find the angle of the equation, we are using its command.
angle(ComplexEqaution)
Now, to perform the inverse of a matrix, we are going to introduce the matrix first. So, write the following command:
B=[1 55 2 7; 4 5 2 8; 4 99 1 6; 3 8 4 1]
The command for this purpose is:
InversofMatrix= inv(B)
If you are confused about the absolute value of the complex equation, then you must realize that complex numbers are present in the plane or the coordinates of the system, and the absolute value of the complex numbers is defined as the total distance between the origin of the complex number (where the plane is (0,0)) and the complex plane (a,b). The procedure to do so is a little bit complex if we solve it theoretically, but with the help of MATLAB, this can be done with the help of a simple command and all the control in your hand. You should practice more with all these commands by using your own values in the matrix with a different sequence. Once you have followed all the instructions given above, the output at your MATLAB command window should be like the images given next:
So, in this way, we have gotten rid of the long and error-prone calculations, and by using simple commands, we have simply applied the formula of inverse, and in this way, we have not had to find the adjoint and determinant of the matrix A.
Consequently, we had a little bit of a complex yet interesting lecture today on matrix, in which we defined it first for a solid foundation of the concept. After that, there were different types of matrices that are less common but have interesting patterns of the elements in which the values and positions are important to define the type of matrix. Moreover, we have seen some interesting commands in MATLAB to perform the operations of complex equations and also implement them all practically. In the next lecture, you are going to learn the amazing features and applications of MATLAB in different aspects of the study.
Hey students welcome to another tutorial in The Engineering Projects where we are going to learn a lot about matrices. If you are a beginner to the metrics, then you should go to learn the fundamentals of matrices. Yet, if you know the basic introduction, you are at the right lecture because we are learning about the special kinds of matrices and you are also going to see the matrices in action using MATLAB. So, here is a simple list of today’s topics.
What is a matrix?
How can we identify the matrix with the help of its general form?
What are the different types of matrices?
What is the concept of transpose while dealing with matrices?
How can we implement these types of matrices in MATLAB by different commands?
A matrix is a type of array that stores data of the same kind. It has great importance in the world of technology and it is defined as:
"A matrix takes the form of an ordered rectangular array surrounded by a square bracket and has entries of the same kind in the form of real or complex data."
To perform different operations on the matrices, you just have to apply them to the whole matrix at once; there is no need to apply them to all the entries one after the other. This will make sense when you see the matrices in action.
Till now, we have learned about the basic introduction of the following types of matrices:
Row matrix
Column matric
Square matrix
Rectangular matrix
These are the basic types irrespective of the elements or entries present in them, and now, we are going to discuss some types that have the features of these matrices but the entries in them are in a specific pattern, so they are considered the special kinds of matrices. Before going into the details of each of them, there must be the foundation of a concept of a general form of the matrix.
To examine the location of a specific element, we use the terms "rows” and “columns” where
Rows are the horizontal entries of the matrix.
Columns are the vertical entries of the matrix.
A specific element is the part of a row and column at a time and to mention the location of an element, it is important to know the information about both of them. So, in the general form, a three-by-three matrix is shown as:
Where
Notice that a has two numbers with them in which the first number denotes the rows and the second one is the number of columns. To make it easier, we denote rows with i and columns with j. So we can say,
Keeping this concept in mind, now it is easy to understand the types of matrices in which the value of the elements matters. Have a look at some of these types.
The identity matrix is a special kind of matrix having the arrangement of entries in such a way that all the diagonal entries are one and the remaining ones are all zero. In this way, we get the matrix of the form:
You can observe that for an identity matrix, the elements where i=j are all ones, and all the elements other than this are zero. There are certain applications of the identity matrix and you will know them in the upcoming lectures.
Here is an interesting type of matrix. This matrix has all the entries zero and no other value can be found in this element. So we assume the zero or null matrix as:
Where the sequence of the matrix can be any. No matter whether it square, row, or rectangular matrix.
A singular matrix is the type of square matrix that has the determinant equal to zero. It is possible in the condition when all the entries of the matrix have the value one.
We all know the procedure to find the determinant. So, taking the determinant of this matrix C, we provide ourselves with the following calculations:
|C|=1x[(1x1) - (1x1)] - 1x [(1x1)-(1x1)] + 1x[(1x1)-(1x1)]
=1x(1-1) - 1x(1-1) + 1x(1-1)
=1x(0) - 1x(0) + 1x(0)
= 0 - 0 + 0
=0
So in general, we say, in a singular matrix:
|C| =0
A non-singular matrix, on the other hand, has entries in such a way that the determinant is never zero. So, we can say, most of the matrices are included in a non-singular type of matrix. Here is an example of a non-singular matrix, which we have also mentioned in other categories.
|C|=3x[(-6x7) - (1x-1)] - 0x [(2x7)-(1x4)] + (-5)x[(2x-1)-(-6x4)]
=3x(-42+1) - 0x(14-4) - 5x(-2+24)
=1x(-41) - 0x(-10) + 5x(22)
= -41 - 0 + 110
=69
Hence, we can conclude for the non-singular matrix that if A is a non-singular matrix, then:
|A|≠ 0
The concept of diagonal was used in the identity matrix, but it is a slightly different case. A diagonal matrix is one that has all the entries, other than the diagonal, equal to zero. The values in the diagonal may be anything.
Here, one concept must be clear. In some cases, all the diagonal values except one may be zero, but it will still be called the diagonal matrix. In other words, by changing even one of the values in the null matrix, we can convert it into the diagonal matrix.
A scalar matrix has all the diagonal values the same, no matter what the value is, and all other values are zero. So, in the scaler matrix, three conditions must be satisfied:
The values other than the diagonal are all zero.
The values in the diagonal must be non-zero.
All the values of the diagonal are the same, no matter what the value is.
The matrix is a square matrix.
If one of the conditions is not satisfied, it is not a scalar matrix.
This is an interesting type of matrix. The upper triangular matrix can be recognized when all the entries below the diagonals are zero and the entries above the diagonal are non-zero. So we get the matrix as:
The value in the diagonal must be non-zero for at least one value. And the
As you can guess, the lower triangular matrix has non-zero values in the lower elements than the diagonal. The values presented in the upper portion of the diagonal are all zero. So the lower triangular matrix looks like this:
This is another concept in matrices that is important to discuss here because some types of matrices depend upon it. We know that a matrix has i rows and j columns. Then, the transpose of the matrix is defined as:
The transpose of matrix A, denoted by AT , is obtained when the rows and columns of matrix A are interchanged no matter what the total number of rows and columns.
This concept is used in different ways, and the results obtained are important. To understand well, you must know, that a rectangular matrix of order 2 by 3 will be converted into a matrix of order 2 by 3 when the transpose is applied to it.
It is a special kind of matrix that involves the procedure of transpose. A skew-symmetric matrix is one that has the arrangement of elements in such a way that applying the transposed result in the matrix that has the same entries and same order. In other words:
AT=A
So, the skew-symmetric matrix is always a square.
Here is another kind of square matrix that involves the transpose, and it is slightly different from the one discussed just before. This type of matrix, after taking the transpose, results in a matrix with all the negative values. So we define this in a simple way as
AT=-A
A hermitian matrix involves complex numbers in it. That means some, or all the elements of a matrix A are complex numbers, and the transpose of that matrix A results in the transpose of a conjugate matrix. So, the following conditions are applied to the hermitian matrix:
It is a square matrix.
It involves complex numbers.
A conjugate of the matrix is obtained.
The resultant matrix has the conjugate values.
A skew hermitian matrix, with the complex conjugate, is the one that involves the negative values of the original matrix ( the one before the transpose procedure). It will be crystal clear to you when you examine the case given below:
Are you enjoying the different types of matrices? Matrices are fun in MATLAB, it is good practice if we attempt all these types in MATLAB. Notice that, these types follow a specific sequence. Hence, MATLAB has a special function designed for the user with the help of which, one can have all these types by simply writing some commands. But it would be helpful if you understood the commands first.
Command |
Description |
eye(a,b) |
It creates an identity matrix. Where a=number of rows b=numbers of columns |
triu(A) |
It converts the matrix A into the upper triangle. |
tril(A) |
It converts matrix A into the lower triangle. |
null(a,b) |
It creates a null matrix. Where, a=number of rows b=numbers of columns |
ones(a,b) |
Creates the singular matrix having the rows a and columns b. |
diag(A) |
Used to get only diagonals of the matrix provided by you as A. |
sort(A) |
Sort the elements of the matrix A in the ascending order column-wise. |
A’ |
It takes the hermitian of a complex matrix A. |
Follow the procedure given below to perform the tasks.
Start your MATLAB software.
Go to the command window.
Start typing the codes given below and get your desired matrix.
A=[ 2 7 4; 5 11 5; 3 8 23]
Notice that we have a square matrix now. It will help us in different operations. So let’s start using different operations.
Write your first command.
IdentityMatrix=eye(3,3)
It will create an identity matrix with the name IdentityMatrix with three rows and columns.
Similarly, write the command given below:
UpperTriangularMatrix=triu(A)
It's time to create the lower triangular matrix. So write the command.
LowerTriangularMatrix=tril(A)
For the null matrix, we are going to use:
NullMatrix=null(2,5)
For the singular matrix, we are using the following command:
SingularMatrix=ones(3,4)
If you wish to have a diagonal matrix of A, write the command:
DiagonalOfMatrix=diag(A)
To sort your matrix A, we are using the command given below:
SortMatrix=sort(A)
If you want to find the hermitian of the matrix, first you have to introduce the complex matrix in MATLAB. So we are writing the following matrix:
B = [1+j; 1-j; 2-j; 1+2j]
Now, by simply applying the command, we can get the hermitian of this matrix.
HermitianMatrix=B’
Thus, today’s lecture was full of different types of matrices, and many of them were new to us. We began with the definition of the matrix, then we saw different types of it where the data or the elements of the matrix were important. Many of them have conditions where the order and location of the elements are important. The concept of transport in the matrix was new to us, and by using it, we explored different types. In the end, with the help of different commands in MATLAB and with the help of practice, we sharpened our concepts. There are different and interesting types of matrices, and we are going to explore all of them in our upcoming lectures.
Before starting this important topic there are some of the important terminologies related to the theorem that are frequently used throughout. So let us have a look at them.
Some important key points related to the system are as follows:
In thermodynamics, a system is a quantity of matter of fixed quantity.
The system is mostly closed. system. There is a change in the size and shape of the system but due to the closed system, no mass can cross the boundary.
One of the important points is that the mass of the system remains constant.
Some important key points related to the control volume are as follows:
The control volume is also known as the open system and it is defined as the region that is specified for a case study.
In the case of a control, volume mass can cross and move in and out of the boundary and which is called the control surface.
One of the important key points related to the control volume is that the mass of the control volume decreases during the process but, the volume remains constant.
The important key points related to Reynold’s Transport Theorem are as follows:
In fluid mechanics, control volumes are easy to handle and many of the laws and theorem are based on it.
So Reynold’s Transport theorem is actually a relationship between the rate of change of extensive properties of the system and control volumes.
A system is considered arbitrary when Reynold’s Theorem is being considered. But here the derivation is also being carried away.
Reynold’s Transport Theorem provides a relationship between the system and control volume.
Let us start the theorem with a background of it:
First of all, we will consider the flow that is moving from left to right and that flow is passing through an expanding field.
As the fluid flow the upper and the lower bounds of the fluid flow are considered to be streamlines of flow. Between any two streamlines, it is assumed automatically that the flow will be uniform and so in this situation, it is also considered.
So there is a diagram that is mentioned below that shows the moving system and control volume (shaded region) of the flow field is considered at the times t and ∆t. the streamlines are also shown.
Here one interesting fact is that the system and the control volume are the same as the system seems to be coinciding with the control volume.
With reference to the diagram, in part (1) the system moves with uniform speed V1 and so in part (2) it moves with speed V2 uniformly.
If you look at the diagram, then there is a central region called the hatched region.
The region that is uncovered by the system during the motion is mentioned as section I and this is part of the control volume. but the new region that is covered by the system is said to be section II and this is not part of the control volume.
Now let us start the derivation. For derivation let us suppose B as extensive property and that may be mass, energy or momentum.
Moreover, let us suppose
b= B/m
Now this b=B/m is the intensive property (we are supposing it).
So the extensive property is additive, they can be added easily.
so the extensive property at times t and ∆t are presented as follows:
Bsys,t=BCV,t
Bsys,t+∆t=BCV,t+∆t - BI,t+∆t+BII,t+∆t
Now we will get to the final result by taking two steps. The first step will be subtracting equation 1 with equation 2 and then taking the limit ∆t→ 0. So the final result will be:
dBsysdt=dBCVdt-Bin+Bout
The value Bin and Bout is as follows:
Bin= b11V1A1
Bout= b22V2A2
Here A1 and A2 are the cross-sectional areas.
And the values of BI, t+∆t and BII, t+∆t is as follows:
BI, t+∆t = b11V1∆tA1
BII, t+∆t=b22V2∆tA2
Now we are on the second last step and it is as follows:
Bin=BI=b11V1A1( after taking limit)
Bout=BII=b22V2A2 (after taking the limit)
The important point here is that property is the extensive property and the time rate change of the system is equal to the time rate of change of B of control volume along with the net flux B of control volume by mass.
Now the final result will be:
Bnet=Bout-Bin=∫CS ρbV.n dA (inflow is negative)
So below mentioned is the diagram that shows the whole working of the derivation:
In the case of the control volume, the equation will be as follows
BCV=∫CV ρb dV
Here the following equation presents the time rate of change of property B content of the control volume:
dBCVdt= d/dt∫CV ρb dV
so the system to control volume in the case of the fixed control system will be as follows:
dBCVdt= ddt∫CV ρb dV +∫CS ρbV.n dA
So that is the explanation related to Reynold’s Transport Theorem.
I hope you have learned a lot through this article. Thank you for reading.
Flow visualization widely uses Computational Fluid Dynamics (CFD) and physical experiments. So following are the types of patterns that can be visualized computationally and experimentally. So without wasting any time, let us start.
There are two patterns. I will first explain the streamlines. So the definition of streamlines is as follows:
A streamline is a curve that is tangent everywhere to the instantaneous local velocity vector.
You might not understand the definition by reading it, so just for your ease, let me explain to you in few key points:
A streamline defines fluid’s motion throughout the flow field.
A streamline acts as an indicator of the instantaneous direction of motion of the fluid. To explain this situation, let me exemplify it with an example.
For instance, when we throw water on a solid surface, we observe the fluid flow pattern on the wall. That pattern is a streamlined pan in which the water is separated, moved in recirculating motion, or coming off the wall.
There is an equation of streamline; let me explain the background of the equation to you. Before that, have a look at the diagram.
As you can see, there is an infinitesimal arc along the streamline. Here the infinitesimal arc length is as follows:
dr=dxi+dyj +dzk
Here is a condition that dr should be parallel to the local velocity, whose equation is as follows:
V=ui+vj +wk
By utilising the geometric rules, infinitesimal arc dr is proportional to the local velocity, and the equation of streamline will be like this:
drV=dxu=dyv=dzw
Here, dr is the magnitude of infinitesimal arc length, and V is the magnitude of velocity.
To obtain the equation in an (x, y) plane, we will integrate equation 1 and get the equation of streamline in an (x, y) plane. The equation is as follows:
(dydx)along astreamline=vu
Now I will give a brief explanation about the Streamtubes. So the definition of Streamtubes is as follows:
A Streamtubes is a bundle of streamlines similar to the communication cable with optic fibre cables.
You might not understand the definition by reading it, so just for your ease, let me explain to you in few key points:
As I have discussed earlier, streamlines are parallel to the local velocity, so according to the theoretical information, the fluid cannot cross the streamlines.
A simple diagram elaborates on tee difference between the streamlines and streamtubes.
The definition of Pathlines is as follows:
A Pathline is an actual path travelled by an individual particle (obviously a fluid particle) at some time period.
The following are some essential key points related to the pathlines:
You might have noticed one thing while reading the definition of pathline and Lagrangian are much similar. Both follow a path of an individual particle when the fluid flows.
There is a technique named Particle Image Velocimetry (PIV) that is used to measure the velocity field in one flow of a specific plane.
Let me explain to you the PIV technique briefly. So what happens in PIV is that those small particles are released in fluid, as shown in the diagram.
Then, the flow is observed by a two-flash light to make two spots on a film of every small particle moving. The magnitude and direction of the velocity of each particle location are fixed because the particle size is small. In today’s modern era of science and technology, many modern computers and digital photography have enabled this feature.
In order to trace the location of particles by the following equation:
x=xstart+tstarttV dt
So, the diagram mentioned earlier shows the pathline following the actual path of fluid particles.
There is a condition that if the velocity field is steady, the fluid particles are bound to follow the streamlines.
The definition of a streakline is as follows:
A streakline is the locus of fluid particles passed sequentially through the flow’s specific (prescribed) point.
The following are some important key points related to the streaklines:
The streaklines are one of the most common flow patterns produced through physical experiments. To explain this point more clearly, let me explain to you through an example. If we insert a tube (specifically in small size) in the flow and then add a continuous stream of tracer fluid, the pattern produced due to the addition will be streaklines. The flowing diagram shows the streaklines produced when the constant stream of tracer fluid (colored fluid) is added to the flow. The fact about the diagram is that the streaklines are similar to the pathline and streamlines.
Here is an interesting point to be noted: if the flow is steady, then the pathlines, streamline, and streaklines are all identical.
So you might be confused by the statement that pathlines, streamlines, and streaklines are similar in steady flow. But in the case of unsteady flow, the scenario is entirely different.
There is a difference, i.e., streamlines give an instantons flow pattern (by definition) but in the case of streaklines is an instantons snapshot of time-integrated flow patterns. And the pathlines are the time-exposed flow path of an individual particle at some time.
The equation to find the integrated tracer particle is as follows:
x=xinjection+tinjecttpresentV dt
The definition of timelines is as follows:
A timeline is a set of adjacent fluid particles that were marked at the same time.
The following are some key points related to the timeline:
The fluid flows in which there is uniformity and a steady flow, then timelines are observed.
Practically timelines can be generated in any water channel with the help of hydrogen bubble wire.
As we all know, flow properties vary from time to time, and in space, it is necessary to plot flow data in various ways. In this article, I am going to explain three kinds of plots that are profile plots, vector plots, and contour plots, respectively.
So without wasting any time, let’s start explaining the plots.
The definition of a profile plot is as follows:
A profile plot indicates how the scalar property varies along some desired direction in the flow field.
The following are some essential key points related to profile plots:
It is one of the simplest plots much similar to the XY-plots.
As the definition describe that the profile plots are created for the scalar quantities, but in fluid mechanics, velocity profile plots are used. As velocity is a vector quantity. So, to create a profile plot, we either use magnitude or velocity.
The definition of the vector plots is as follows:
A vector plot is an array of arrows reflecting the magnitude along with the direction of vector quantity at an instant of time.
The following are some essential points related to the vector plots:
Streamlines are used to present the direction of the instantaneous velocity; here, they do not show the velocity magnitude.
A flow pattern is a vector plot for experimental and computational fluid flow. They have an array of arrows that indicate both magnitude and direction of a vector quantity.
The following definition of a contour plot is as follows:
A contour plot shows curves of constant values of scalar property (or magnitude of a vector property) at an instant in time.
The following are some essential key points related to the contour plots:
The contour plot may have curves indicating various properties called Contour Line Plot.
Some of the contours are filled with color of grey are called Filled Contour Plot.
In fluid mechanics, the elements have four fundamental types of motion or deformation in two dimensional as follows. It is interesting to know the fact that all four of these motions can act at the same time. Yes, you heard it right. Isn’t it amazing? In fluid dynamics, the motion and deformation of liquid elements at different times are described. So the deformation rates are expressed in terms of velocity and derivatives of velocity.
Translation
Rotation
Linear Strain (Extensional Strain)
Shear Strain
So let us start explaining one by one.
The translator and rotatory motion are one of the most common motions that are observed in our daily life. For the three dimensions, a vector is used to define the translator rate. In Cartesian coordinates the rate of translation is as follows:
V=ui+vj+wk
The rate of rotation or the angular velocity is defined to be the average rotation rate of two perpendicular lines that intersects at some point.
Example:
In order to exemplify this whole situation, let us explain through some examples.
Let us take an initially square fluid element and consider its bottttttttt.
Technically, the left and the bottom edge of the element intersect at some point. Thus we can say that they are perpendicular to each other.
Now, these two lines tend to rotate in a counterclockwise direction (which is said to be the positive direction).
Toto, show a clearer picture to you let me show you a diagram. So the below-mentioned diagram explains the rotational effect.
One of the main points to observe is that the angle between the two lines remains the same, which is 90 degrees.
So the line rotates at the same rate of rotation.
Here there is also one of the most essential points about the rate of rotation is that when the case is two dimensional then the fluid elements move in translator motion and then rotate. But while rotating, they deform easily.
In order to calculate the rate of rotation, the whole thing is calculated by the scenarios mentioned above, i.e. two lines are taken named a and b respectively. These two lines intersect at a specific point called P ( as mentioned above that this procedure is in two dimensions. Which Means that they are in the XY plane).
These lines are being followed and rotated in an infinitesimal increment of time, and that is:
dt=t2-t1
Line a rotates at some angle aand line b also rotates at a specific angle b. The average rotation angle will be:
a+b2
So the final equation will be as follows:
ω=ddt(a+b2)
ω=12(∂v∂x-∂u∂y)
The definition of linear strain rate is as follows:
Linear strain rate is defined as the rate of increase in length per unit length.
Some of the important key points related to the linear strain rate are as follows:
The linear strain rate depends upon the direction of the line segment and this line segment measures the linear strain.
But here important point should be kept in mind i.e. that the linear strain rate cannot be defined as vector or scalar quantity.
The linear strain rate can be defined in an arbitrary direction.
The linear strain rate can be defined in Cartesian coordinates by the formula as follows:
xx=∂u∂x yy=∂v∂y zz=∂w∂z
The definition of the volumetric strain rate is as follows:
The rate of increase in the volume of fluid element per unit volume is called the volumetric strain rate.
Some of the important critical points related to the volumetric strain rate are as follows:
In an incompressible flow, the volumetric strain rate is zero.
With the increase in volume, the kinematic property is always positive.
The other definition word for the volumetric strain rate is called Rate of Volumetric Dilatation.
The rate of volumetric dilatation is remembered by an example. Let us take an example of the iris of expands enlarging when there is less light.
The formula of volumetric strain rate in Cartesian coordinates is as follows:
1VDVDt=1VdVdt=xx+yy+zz=∂u∂x+∂v∂y+∂w∂z
The definition of the shear strain rate is as follows:
A shear strain rate is defined at the point as half of the rate of decrease of the angle between two initially perpendicular lines that intersects at some points.
Some of the important key points related to the shear strain rate are as follows:
In order to explain the definition, let us explain through some examples. Let us see a diagram first that is mentioned below:
In this diagram, the angle is at first 90 in the lower left corner and upper right corner of the element of fluid the angle decreases so that is a positive shear strain. But the angles at the upper-left and lower-right square fluid element increase so that is negative shear strain.
In the Cartesian coordinates system, the shear strain rate will be:
xy=12∂u∂x+∂v∂x zx=12∂w∂x+∂u∂z yz=12∂v∂z+∂w∂y
I hope you have learned a lot through this article. Thank you for reading.
Hello friend. In this article, I will cover essential points related to fluid kinematics, i.e., what fluid kinematics is and how the motion of the fluids can be explained without describing the forces acting on them. Further, I will explain Lagrangian and Euler about the motion of fluid and a lot more. So buckle up, and let’s start.
The definition of fluid kinematics is as follows:
Fluid kinematics is related to fluid motion without considering the forces responsible for the motion.
The following are some essential key points related to fluid kinematics:
The nature of fluid motion is categorized into two types:
I will extensively explain both types in upcoming topics.
The acceleration, velocity, flow rate, and nature of fluid flow are considered while working on fluid kinematics.
First of all, I will explain the Lagrangian. So the definition of Lagrangian is as follows:
Lagrangian Description of fluid flow deals with individual particles and their nature, and the working trajectory of each particle is calculated separately.
And the definition of Euler is as follows:
Euler’s Description of fluid flow deals with the concentration of the particles, and the number of particles and diffusion are all calculated.
The following are some essential key points related to the Lagrangian Description:
Lagrangian is all about tracking the path of individual particles.
In this regard, Newton’s Laws are beneficial in detecting the pathways. With the help of their kinetic energy, speed, distance velocity, and acceleration.
As we all know, fluid is Continuum in nature. If you are following my fluid mechanic’s articles series, you have forwarded to this word, where I have extensively described the continuum. So it becomes pretty challenging to follow the path of fluids as they deform whenever a direction changes.
In the Lagrangian description, the position and velocity of individual particles must be tracked throughout.
To describe through a simple example the balls on the snooker table. In this case, each ball is responsible for its path.
The following are some essential key points related to the Euler Description:
In the case of Euler’s description, the control volume is defined through which the fluid can move in.
In this description method, there is no need to track the velocity and position of fluid particles.
In this description, space and time are defined within the domain of control volumes.
As I have defined in previous articles, pressure is a scalar quantity. So pressure field in case of three-dimensional fluid flow in Cartesian co-ordinates can be defined as follows:
P = P (x, y, z, t)
The velocity field is mentioned as follows:
V=V(x, y, z, t)
The acceleration field is as follows:
a= a (x, y, z, t)
The interesting fact to know is these three field(along with some others but for now only these three fields) variables define the flow field:
V=(u, v, w)
V=ux,y,z,ti +vx,y, z, tj +w(x, y,z,t)k
I will explain it through a simple example to depict the Lagrangian and Euler description.
The example is as simple as one person standing beside the river. So when he goes through the probe, which will move downstream with water, this situation will be classified as Lagrangian. This will be classified as Euler’s description when he anchors the probe in some fixed location in the water.
The applications of fluid Kinematics are as follows:
The purpose of dealing with Fluid kinematics is that fluid has excellent properties, and they are used almost in every vehicle. So for lubrication purposes and as driving fuel.
Anything that moves has kinetic and potential energy and fluids. They are used in hydroelectric power plants for the generation of electricity.
In refrigerators and air conditioners, refrigerants used are fluids. The primary purpose of refrigerants is to absorb the heat (from the room or, in the case of refrigerators, anything that is kept inside them) and keep them cool, then release the heat into the atmosphere. In the case of air conditioners, heat is absorbed from the room to keep them cool and release that heat into the atmosphere.
Surprisingly fluids can be used as a renewable energy resource. One of the simplest and best examples is the water used in tidal power plants for electricity generation. Moreover, a vegetable oil known as biodiesel is used in many vehicles. Wind and air are also used as renewable energy sources.
One of the essential resources of electricity in thermal power plants. In thermal power plants, water (used as fluids) is heated to form steam, which then turns on the turbine. The turbine then turns on the generator, which generates electricity. So the purpose of explaining this whole procedure is to explain the importance of fluid in electricity generation.
So that are the applications of fluid kinematics in our daily life. Dear friends, I will explain two significant ways to describe motion.
As I have discussed the pressure now I will explain fluid mechanics. The definition of fluid mechanics is as follows:
Fluid mechanics deals with the properties and characteristics of fluid at rest.
Some of the important key points related to the fluid statics are as follows:
Fluid statics has many properties just as hydrostatics when the fluid is in a liquid state and acts as aerostatics when it is in a gaseous state.
The only stress that is in fluid statics is the normal ones other than that there is no shear stress.
The main application of fluid statics is to determine the forces that are acting on the floating or the submerged bodies.
That is a brief introduction to fluid statics further I will explain the forces that are acting on submerged and floating bodies. So without wasting any time let us start.
The structure of the surface and the forces that are acting on the surface is explained as follows:
As the name suggests, there is a plane surface on which liquid flows and the surface is resting.
The fluid pressure is equally distributed onto the surface.
So the set of parallel forces is formed on the surface as a result of hydrostatics forces.
As one side of the surface is facing the fluid pressure whereas the other side is sometimes exposed to the atmosphere and as the result is zero resultant.
The working principle along with all the equations that are acting on the surface are explained as follows:
First of all, as I have discussed earlier that one side of the plate is completely exposed to the atmosphere and has atmospheric pressure whereas the other side of the plate is completely submerged in the fluid as shown in the diagram.
The horizontal surface intersects the plane surface at some angle so that line is considered to be x-axis.
Po is the absolute pressure i.e., the pressure that is above the fluid (liquid) also known to be local atmospheric pressure if the fluid or liquid is exposed to the atmosphere.
The equation of absolute pressure is:
P=P0+ρgh
P=P0+ρg ysinθ (equation 1)
Here h is the vertical distance of a specific point to a surface and y is the distance of a point from the x-axis from the point O as shown in the diagram.
Now the next step is to find the resultant hydrostatics force and for that, the equation is as follows:
FR=∫APdA
Here we will substitute the value of P from equation 1 and equation 2 will look like this:
FR=∫A(P=P0+ρg ysinθ) dA
FR=P=P0A+ρg sinθ∫AydA
∫AydA is the first moment of the area as it is in the y-coordinate and the value is as follows:
yc=1A∫AydA
By substituting the value, we get the final result:
FR=P0A+ρgyc sinθA
FR=P0+ρghcA
FR=PcA
FR=PavgA
The final result will be stated theoretically:
The final resultant force is equal to the pressure at the centroid surface and the area.
The structure of the surface and the forces that are acting on the surface is explained as follows:
As the name shows that the curved surface is submerged in liquid and the hydrostatic forces are determined.
In this part we have applied the integration of pressure forces that fluctuates when the direction of the surfaces changes.
The final force (resultant) is equal and opposite to the force that is acting on the curved surface.
The working principle along with all the equations that are acting on the surface are explained as follows:
Here the weight of the enclosed liquid is as follows:
W=ρgυ
Here V is the volume of fluid and that is in a downward direction as shown in the figure.
the vertical and horizontal forces will be:
the horizontal force component on a curved surface:
FH=FX
the vertical force component on the curved surface
FV=Fy+W
The final result will be:
the horizontal and the vertical component of the hydrostatic force of a curved surface are both equal in case of magnitude and line of action.
The horizontal and vertical component is an equal hydrostatic forces acting on horizontal projection along with the weight of the fluid.
I hope you enjoyed reading the article and have an extensive overview of the pressure and fluid statics. Thanks for reading.