Professional Documents
Culture Documents
Digital Spirometer
Digital Spirometer
Digital Spirometer
DIGITAL SPIROMETER
A Research Submitted in Partial Fulfilment of the Requirements for the Degree of
Bachelor of Science (Honors) in Engineering.
Prepared by:
Mervat Abualqasim BE-2018-053
Supervised by:
Co-Supervised by:
January, 2024
Dedication
the best kind of people are the ones that come into your life, and make you see the sun
where you once saw clouds. The people that believe in you, you start to believe in you
too. The people that love you, simply for being you. The once in a lifetime kind of
people
We extend our deepest gratitude for the endless prayers, support and encouragement that
have illuminated our path throughout this journey. Your presence has been the cornerstone
of our ability to take those critical first steps.
I want to express my heartfelt gratitude to all my friends who have stood by me with
unwavering support. Your presence has been a source of strength and joy, turning
challenges into shared moments of laughter and warmth. I am deeply thankful for the
invaluable bond we share, and I cherish the privilege of having such wonderful friends by
my side. Your friendship has been a true blessing, and I am profoundly grateful for each one
of you.
Our friends don't always come as companions but as a chosen family. We know words
can't fully express our gratitude to you, but we wanted to say thank you from the
bottom of our heart Eng. Marwa Ahmed, Eng. Mohamed Fathiy.
Acknowledgement
First of all, we want to thank ALLAH for his never-ending grace, mercy and provision
which lead us in the right track to fulfill this project.
We wish to express our sincere gratitude to our supervisor Eng. Tasneem Elbashir for
being helpful to us by guiding, supporting, encouraging and providing her valued
comments, the co-supervisor Mr. Mohamed Fathiy for his support and effort.
Abstract
The primary test of lung function is called Spirometry. Spirometry parameters are derived from pressure
and/or flow measurements. The spirometer records exhaled air volume, and produces graphic and numeric
information in the form of spirometric parameters and tracings that can depict and describe the mechanical
properties of the lung. Some possible measurements are like Pressure and gas flows behave during one
respiratory cycle in volume controlled. Patient Spirometry measures airway pressures, flow, volumes,
compliance, and airway resistance breath-by-breath at the patient’s airway. The flow of gas is measured, and
the inspiratory and expiratory concentrations of oxygen and carbon dioxide analyzed. All parameters are
measured through a single, lightweight flow sensor and gas sampler, placed at the patient’s airway. The “close
to the patient” measurement is a sensitive and continuous reflector of patient’s ventilator status, obtained
independently of the ventilator used. The breath-by-breath measurement of pulmonary gas exchange is
technically very demanding and requires sophisticated compensation and data processing algorithms to
achieve the accuracy required in the clinical use. Measurement of respiratory gas flow continuously is
associated with several problems, such as the effects of humidity, alternating gas composition, secretions,
and the dynamic response of the flow sensors. Medical technologies have enabled accurate measurement of
respiratory gas exchange in a wide variety of clinical conditions. The clinical applications range from
assessment of energy requirements to comprehensive analysis of ventilation and oxygen transport in patients
with complex cardio respiratory problems. Obstructive disorders, which are much more common than
restrictive abnormalities include asthma and COPD. Asthmatic bronchitis, chronic bronchitis, and
emphysema are included in COPD. These diseases can be identified by a low FEV / FVC ratio or an FEV
that is lower than predicted. Spirometric data have been presented as exhaled volume over time. These
volume-time curves are easy to visualize and allow physicians to identify FEV, FVC, and expiratory time at
a glance. The flow transducer permits physicians to visualize peak flow and timed peak flow. Which is a
check of patients’ efforts FEV, FVC, and FEV, FVC ratio are expressed in terms of lower limit of normal.
Spirometric measurements can be as fundamental to medicine as are pulse, blood pressure. Temperature,
height and weight measurements and therefore could be considered in the physical examination as important
vital signs.
Figure Page
Figure 2.1: Respiratory System [2] 5
Figure 2.2: The process of breathing in / The process of breathing out [3] 6
Figure 2.3: Spirometry [5] 8
Figure 2.4: Lung Volumes and Lung Capacities [6] 9
Figure 2.5: The spirometry system of claim [8] 15
Figure 3.1: Block diagram of the project system 17
Figure 3.2: Methodology Framework of the project 18
Figure 3.3: Thonny [15] 20
Figure 4.1: Spirometry Simulation input 21
Figure 4.2: Case 1 22
Figure 4.3: Case 2 23
Figure 4.4: Case 3 24
Figure 4.5: Case 4 25
Figure 4.6: Summery of Acceptability, Usability, and Repeatability
Criteria for FEV1 and FVC. [16] 26
Figure 4.7: Grading System for FEV1 and FVC. [16] 26
Figure 4.8: Copely website [17] 27
Figure 4.9: MSD Manual website [18] 27
v
Table of contents
Title Page
List of Figures iii
Chapter One
1.1 Overview 2
1.2 Motivation 2
1.3 Research Questions 2
1.4 Problem Statement 2
1.5 Objectives 3
1.5.1 General Objective 3
1.5.2 Special Objective 3
1.6 Scope 3
1.7 Thesis outlines 4
Chapter Two
2.1 Theoretical Background 5
2.1.5 Spirometry 8
Chapter Three
3.1 Methodology 18
3.2 Block Diagram 18
3.3 Flow Chart 19
3.4 Software Components 20
3.4.1 Thonny 20
vi
4. Chapter Four
4.1 Introduction
21
4.2 Results
21
4.2.1 Case 1
22
4.2.2 Case 2 23
4.2.3 Case 3 24
4.2.4 Case 4 25
5. Chapter Five
5.1 Conclusion 28
5.2 Recommendation and Future Work 28
6. References 29
Appendix 32
vii
Abbreviations
1
Chapter One
Introduction
1.1 Overview
The human body is made up of numerous organs and tissues that work together to carry
out various tasks in a way that ensures life's continuity. If there were a defect, however,
life would be gradually interrupted and eventually end in death for humans. These
devices are intertwined and each is essential to the other, including the digestive,
respiratory, periodic, and nervous systems. One of the most crucial organs, the respiratory
system is responsible for breathing, distributing oxygen to all body parts, and eliminating
carbon dioxide. Our major goal is to create a fully functional, straightforward spirometer by
using Python language. Our goal is to correct or redesign the spirometry to make it more useful,
simple, accurate.
1.2 Motivation
The huge motivation for us is being able to help people with lung diseases and facilitate
their lives and diagnose their normal and abnormal situations.
According to the latest estimates of the World Health Organization (WHO) more than 3
million people die each year from Chronic Obstructive Pulmonary Diseases (COPD) which
is approximately 6% of all deaths worldwide and 90% of COPD deaths occur in low-
income and middle- income countries.
2
1.5 Objectives
To design digital spirometer easy-to-use and carry out the various lung functioning tests.
1.6 Scope
3
1.7 Thesis outlines
The thesis consists of five main chapters and appendices explained in detail within this
thesis.
Chapter one: explains in detail the information about the project background, motivation,
research question, problem statement, objectives, scope and the contribution of research.
In this chapter the reader could find out the overview of this project in addition to the
significance of this project.
Chapter two: the related literature to this project is provided in detail. The topics explained
in this chapter includes approaches, design issues, software programming and basic
hardware.
Chapter three: is about design and implementation step which is explained in details
including the prototype.
Chapter four: all the results and analysis about the system either it achieved the objectives
or not.
Chapter five: summarizes this project with recommendations and future work.
4
Chapter Two
Literature review
2.1 Theoretical Background
The respiratory system is the network of organs and tissues that help the breath. It includes
the airways, lungs and blood vessels. The muscles that power the lungs are also part of the
respiratory system. These parts work together to move oxygen throughout the body and
clean out waste gases like carbon dioxide. [1]
5
2.1.2 Respiratory System Functions
The respiratory system has many functions. Besides helping inhale (breathe in) and exhale
(breathe out), it:
The process of breathing, or respiration, is divided into two distinct phases. The first phase
is called inspiration, or inhaling. When the lungs inhale, the diaphragm contracts and pulls
downward. At the same time, the muscles between the ribs contract and pull upward. This
increases the size of the thoracic cavity and decreases the pressure inside. As a result, air
rushes in and fills the lungs.
The second phase is called expiration, or exhaling. When the lungs exhale, the diaphragm
relaxes, and the volume of the thoracic cavity decreases, while the pressure within it
increases. As a result, the lungs contract and air are forced out. [3]
Figure 2.2: The process of breathing in / The process of breathing out [3]
6
2.1.4 Respiratory System Diseases
Many conditions can affect the organs and tissues that make up the respiratory system.
Some develop due to irritants the breath in from the air, including viruses or bacteria that
cause infection. Others occur as a result of disease or getting older.
Conditions that can cause inflammation (swelling, irritation and pain) or otherwise affect
the respiratory system include:
Allergies: Inhaling proteins, such as dust, mold, and pollen, can cause respiratory
allergies in some people. These proteins can cause inflammation in airways.
Asthma: A chronic (long-term) disorder, asthma causes inflammation in the
airways that can make breathing difficult.
Infection: Infections can lead to pneumonia (inflammation of the lungs) or
bronchitis (inflammation of the bronchial tubes). Common respiratory infections
include the flu (influenza) or a cold.
Disease: Respiratory disorders include lung cancer and chronic obstructive
pulmonary disease (COPD). These illnesses can harm the respiratory system’s
ability to deliver oxygen throughout the body and filter out waste gases.
Aging: Lung capacity decreases as get older.
Damage: Damage to the respiratory system can cause breathing problems. [1]
7
2.1.5 Spirometry
Spirometry (spy-ROM-uh-tree) is a common office test used to assess how well the lungs
work by measuring how much air inhale; how much exhale and how quickly exhale.
If the patient already been diagnosed with a chronic lung disorder, spirometry may be used
periodically to check how well the medications are working and whether breathing
problems are under control. Spirometry may be ordered before a planned surgery to check
if the lung function is adequate for the rigors of an operation. Additionally, spirometry may
be used to screen for occupational-related lung disorders. [4]
8
2.1.6 Lung Volumes
9
2.1.7 Lung Capacities
Vital Capacity
The vital capacity is the total volume of air that can be expired after a maximum
inhalation or maximum air that a person can breathe in after forced expiration. It is
an important measure of a person’s respiratory health. A decreased vital capacity is
an indication of restrictive lung disease where the lungs cannot expand completely.
In the case of normal vital capacity, the improper functioning of lungs indicates
obstructive lung disease where the lungs are blocked in the airways.
VC = TV + ERV + IRV
Inspiratory Capacity
The inspiratory capacity is the total volume of air that can be inspired which is
about 3600 ml.
IC = TV + IRV
FRC = ERV + RV
10
2.1.8 Test the Lung Functions
Lung function tests (also called pulmonary function tests) include a variety of tests that
check how well the lungs work. The most basic test is spirometry. This test measures the
amount of air the lungs can hold. The test also measures how forcefully one can empty air
from the lungs.
Spirometry is used to screen for diseases that affect lung volumes. It also is used to screen
for diseases that affect the airways, such as COPD or asthma.
Lung volume testing is another commonly performed lung function test. It is more precise
than spirometry and measures the volume of air in the lungs, including the air that remains
at the end of a normal breath. In addition, a diffusing capacity test measures how easily
oxygen enters the bloodstream. Exercise testing helps evaluate causes of shortness of
breath. There are also tests to find out if asthma is present when the usual breathing test
results are normal. [7]
Spirometry can be classified on the basis of these major indices into three abnormal
patterns:
3. A mixed obstructive and restrictive pattern with airflow limitation and loss of lung
volume shown by low FVC but low FEV1/FVC ratio.
11
The shape of the flow-volume curve may also vary between an obstructive defect, where
the expiratory curve is convex towards flow and volume axes, and a restrictive disease
where the shape may be concave towards the axes. More complex tests of ventilator
function normally undertaken in a physiology laboratory setting,
such as measurement of total lung capacity and residual volume, are required to confirm
both the restrictive and mixed obstructive/restrictive abnormalities. A particular
confounder can exist where a high residual volume due to air causes the decrease in FVC
giving the false appearance of restriction.
. Forced vital capacity (FVC), the maximum amount of air that can be exhaled when
blowing out as fast as Possible.
.Vital capacity (VC), the maximum amount of air that can be exhaled when blowing out
at a steady rate.
12
2.1.10 Factors affect the spirometry measurements
Digital Spirometry are intricately influenced by four key inputs: age, height, density, and
pipe diameter, each playing a distinct role in the scientific accuracy of the measurements.
13
Density plays a significant role in spirometry by influencing the calculation of lung
volumes. The density of inhaled air varies with changes in atmospheric conditions, and
this variation directly affects the volume measurements recorded during spirometric tests.
As the density of air fluctuates, particularly in response to alterations in temperature,
pressure, and humidity, the accuracy of spirometry results can be impacted. To enhance
precision in interpreting spirometry data, adjustments for density fluctuations may be
necessary, ensuring that the recorded lung volumes are corrected for the specific
conditions under which the test is conducted. Recognizing and accounting for the
influence of air density is crucial in obtaining reliable and standardized spirometric
measurements.
Pipe diameter in spirometry plays a crucial role in determining airflow resistance and,
consequently, affects the accuracy of flow-related parameters. The diameter of the
measurement pipe influences the resistance encountered by the airflow during both
inhalation and exhalation maneuvers. A smaller diameter increases airflow resistance,
potentially leading to higher pressure gradients and affecting parameters like forced
expiratory flow rates. Conversely, a larger diameter reduces resistance, allowing for
smoother airflow. The choice of an appropriate pipe diameter is essential for maintaining
standardized testing conditions and ensuring that spirometric measurements accurately
reflect the dynamics of respiratory function. Adjusting for pipe diameter variations is
vital in interpreting results and comparing data across different spirometric setups to
account for their impact on airflow resistance and associated parameters.
14
2.2 Literature Review
A spirometry system included an imaging device that was configured to capture upper body
movement images of a subject during inhalation and exhalation. The system also had at
least one controller that was configured to receive the captured images from the imaging
device and, based on the received images, determined at least one of an image-based
spirometry flow volume curve for the subject or an image-based spirometry parameter for
the subject. [8]
A portable incentive spirometry monitoring device and method of use were developed. The
device was connected to the base of an incentive spirometer, capable of monitoring
inspiration within the incentive spirometer. It featured a user interface for inputting various
parameters, such as desired air volume and attempt thresholds. Results were stored,
allowing medical personnel to review a patient's attempts, monitor therapeutic use, and
encourage patient compliance. Importantly, the portable incentive spirometry monitoring
device could be reused with different incentive spirometers without requiring extensive
sterilization. [9]
15
A method for identifying and diagnosing pulmonary disease using a classification system
and its kit was disclosed (Kind Code: A1). The invention provided biomarkers and
biomarker combinations for diagnosing lung diseases like non-small cell lung cancer or
reactive airway disease. Measurements of these biomarkers were input into a classification
system, such as support vector machines or Ad boost, to determine the likelihood of an
individual having lung disease. Additionally, kits containing agents for detecting these
biomarkers, combinations, and systems to aid in the diagnosis of lung disease were also
provided. [10]
A diagnostic support program that could display movement of a region whose shape
changed for each respiratory element, encompassing all or part of exhalation or inhalation,
was provided. A process was employed to identify a period of a respiratory element,
including all or part of exhalation or inspiration, based on pixels in a specific region of
each frame image. The program then detected a lung field based on the identified
respiratory element's period, divided the detected lung field into multiple block areas,
calculated changes in the image of these block areas in each frame image, and Fourier-
transformed these changes. Subsequently, within a certain band, which included the
spectrum corresponding to the respiratory element's period, a spectrum was extracted, and
an inverse Fourier transform was performed on it. The resulting inverse transform was
displayed on a display, completing the process. [11]
The invention provided a method for monitoring respiratory frequency and sleep-
disordered breathing based on wearable equipment. The steps included acquiring
physiological characteristic data, such as pulse wave signals and electro cardio signals,
from a monitored user. The pulse wave and electro cardio signals were preprocessed to
remove interference, baseline drift, and motion artifacts, and then uploaded to a big data
center. A respiratory frequency and sleep-disordered breathing learning model were
established based on organ model, disease model, and physiological characteristic data.
This model enabled real-time monitoring of the user's respiratory frequency and sleep-
disordered breathing. The invention, requiring only the user to wear wearable equipment,
offered convenience, strong operability, low cost, and more convenience compared to a
portable breath detector. The wearable device demonstrated robust real-time monitoring
performance, acquiring physiological data in real-time, surpassing the capabilities of a
portable breathing detector. Furthermore, users could make personalized adjustments to
their healthy lifestyle based on the feedback data. [12]
16
A method of imaging a patient's lung involved positioning the patient at a first orientation
relative to an x-ray imaging apparatus and obtaining a volumetric measurement of the
patient's breathing. While the patient was positioned at the first orientation and during the
volumetric measurement of the patient's breathing, the method determined the breathing
phase of the patient based on the volumetric measurement. Upon establishing that the
breathing phase matched a predefined phase, the x-ray imaging apparatus was gated to
produce an x-ray projection of the patient's lung. [13]
The invention provided a CT scanning method for lung respiratory motion detection in the
technical field of lung CT scanning. The steps included a breath pre-training step, where
the patient underwent respiratory training before CT scanning, with a respiratory cycle
denoted as t1. Following this, a CT parameter setting step was carried out with 4-10
scanning periods, each period lasting for a scanning period time (t2) greater than t1 but less
than 2t1. Subsequently, CT scanning commenced, with the patient instructed to start slow
respiration during the scanning period (t2). The respiratory motion process condition of the
lung during a breathing cycle (t1) was recorded by CT scanning. The invention facilitated
continuous chest CT scanning under dynamic respiration, enabling continuous and
dynamic detection and evaluation of lung structure and function. This addressed the
limitation of current lung function assessments and provided complete information on lung
respiratory motion, overcoming clinical challenges associated with single static CT
scanning indices. [14]
17
Chapter Three
Methodology
In this section we will describe the process of the safety system and the software tools that
will be used.
3.1 Methodology
Gather and Analyze respiratory data using the Thonny programming environment.
Participants meeting specified criteria underwent spirometry tests with careful calibration
and adherence to standardized testing conditions. Age, height, density, and pipe diameter
were systematically recorded as key variables influencing the respiratory measurements.
Thonny's scripting capabilities facilitated the implementation of algorithms for data
processing, statistical analysis, and result display. Codes written in Thonny were
meticulously designed to handle data intricacies, ensuring accurate calculations and
meaningful graphical representations. Ethical considerations were paramount, with
adherence to participant privacy and informed consent protocols. The developed Thonny
interface allowed for a user-friendly presentation of spirometric results, enhancing
participant engagement. This streamlined methodology harmonizes traditional spirometry
practices with modern programming techniques, providing a comprehensive framework
for reliable data collection and analysis.
Computer
Data Processing
Input Spirometric Results
and
Parameters Parameters Display
Calculations
18
3.3 Flow chart
19
3.4 Software Components
Thonny
3.4.1 Thonny
An IDE for Python called Thonny was created with science to make Python
programming more accessible and efficient. Its UI is carefully designed to meet the needs
of both inexperienced and experienced developers, following the guidelines of readability
and simplicity. The integrated Python interpreter simplifies the beginning of coding
projects by removing the hassles of third-party installations. A methodical approach to
package installation, updating, and general dependency management is offered by
Thonny's package management system. Robust scientifically, the IDE incorporates
debugging and code execution facilities, allowing for accurate mistake detection and
correction.
20
Chapter Four
Results and discussion
4.1 Introduction
The results of digital spirometry are intricately influenced by four key inputs: age, height,
density, and pipe diameter, each playing a distinct role in the scientific accuracy of the
measurements.
4.2 Results
In the spirometry simulation, this is where crucial data: age, height, pipe diameter, and
density are inserted
21
After the parameter inputs, including age, height, pipe diameter, and density, have been
inserted, the system proceeds to process and calculate the data. This crucial step involves
utilizing algorithms and computations, ensuring accurate and meaningful results in the
context of spirometry simulations.
Here are a few cases with different inputs, demonstrating the flexibility of the spirometry
simulation.
4.2.1 Case 1
The results presented are derived from a digital spirometry simulation, featuring inputs
specifying an age of 6, height of 112.3, and a pipe diameter of 0.025. The simulation
outputs include the Forced Expiratory Volume in one second (FEV1), Forced Vital
Capacity (FVC), and the ratio between them. Additionally, the results provide
information on repeatability grade and mass flow rate.
22
4.2.2 Case 2
The results presented are derived from a digital spirometry simulation, featuring inputs
specifying an age of 16, height of 170, and a pipe diameter of 0.0032. The simulation
outputs include the Forced Expiratory Volume in one second (FEV1), Forced Vital
Capacity (FVC), and the ratio between them. Additionally, the results provide
information on repeatability grade and mass flow rate.
23
4.2.3 Case 3
The results presented are derived from a digital spirometry simulation, featuring inputs
specifying an age of 54, height of 165, and a pipe diameter of 0.0685. The simulation
outputs include the Forced Expiratory Volume in one second (FEV1), Forced Vital
Capacity (FVC), and the ratio between them. Additionally, the results provide
information on repeatability grade and mass flow rate.
24
4.2.4 Case 4
The results presented are derived from a digital spirometry simulation, featuring inputs
specifying an age of 23, height of 176, and a pipe diameter of 0.2002. The simulation
outputs include the Forced Expiratory Volume in one second (FEV1), Forced Vital
Capacity (FVC), and the ratio between them. Additionally, the results provide
information on repeatability grade and mass flow rate.
25
The results presented here are derived from the Standardization of Spirometry as outlined
in the Official American Thoracic Society and European Respiratory Society Technical
Statement. Tables have been incorporated to succinctly illustrate these standards,
providing a clear and straightforward reference for understanding the methodologies
employed in this study.
26
The calculations utilized in the digital spirometer are primarily derived from the Flow
Rate Calculator, a Canadian website known as Copley, and the MSD Manual, an
American website, both esteemed for their authoritative content. To enhance transparency
regarding the sources influencing the computational methodologies employed, snapshots
of these websites will be inserted.
27
Chapter 5
Conclusion and Recommendation
5.1 Conclusion
Due to its prohibitive cost, adequate pulmonary function testing in developing nations
such as Sudan is very limited. Physicians from these areas realize that the quality of
treatment they could provide to patients would increase dramatically if they had access to
spirometers. Unfortunately, such physicians cannot afford to invest in these devices as the
high costs would likely never be regained from the nominal fees they charge for their
services. Thus, essential diagnoses and monitoring are performed with severely limited
information. The progress we have made this semester in the development of a low-cost
spirometer is the first step toward changing this situation. This project exhibits a
profitable yet socially beneficial solution in manufacturing and selling a low-cost
spirometer to practitioners in developing countries. This project also demonstrates the
value of open innovation in the medical device and healthcare sector, and the commercial
viability of addressing situations where the market has failed to deliver necessary
technology at a widely affordable price.
28
6. References
[1] “Respiratory system: Functions, facts, Organs & Anatomy,” Cleveland Clinic.
[Online]. Available: https://my.clevelandclinic.org/health/articles/21205-respiratory-
system. [Accessed: 26-Nov-2022].
[6] Admin, “An overview of lung volumes and capacities (vital capacity),” BYJUS, 03-
Aug-2020. [Online]. Available: https://byjus.com/biology/respiratory-and-lung-volumes/.
[Accessed: 26-Nov-2022].
29
https://patents.google.com/patent/US20200000370A1/en?q=Spirometry&oq=Spiro
metry. [Accessed: 26-Nov-2022].
30
[15] “Thonny download: Get familiar with the python programming language using a
novice-friendly IDE that provides you with several helpful learning tools, all packed into
an intuitive gui,” softpedia, 19-Nov-2023. [Online]. Available:
https://www.softpedia.com/get/Programming/Coding-languages-
Compilers/Thonny.shtml#sgal_0. [Accessed: 14-Jan-2024]
[16] “Thonny download: Get familiar with the python programming language using a
novice-friendly IDE that provides you with several helpful learning tools, all
packed into an intuitive gui,” softpedia, 19-Nov-2023. [Online]. Available:
https://www.softpedia.com/get/Programming/Coding-languages-
Compilers/Thonny.shtml#sgal_0. [Accessed: 14-Jan-2024]
[17] “Flow rate calculator - pressure and diameter,” Copely, 17-Aug-2023. [Online].
Available: https://www.copely.com/tools/flow-rate-calculator/. [Accessed: 15-Jan-
2024]
[18] [“Calculators: PFT adjusted predicted values for men MultiCalc,” MSD Manual
Professional Edition. [Online]. Available:
https://www.msdmanuals.com/professional/multimedia/clinical-calculator/pft-
adjusted-predicted-values-for-men-multicalc. [Accessed: 15-Jan-2024]
31
Appendix
import time
import tkinter as tk
import random
# Constants
volumetric_flow_rate = 0.0
fvc_values = []
fev1_values = []
# Adjustment factors
fev1_adjustment_factor = 1.08
fvc_adjustment_factor = 1.1
# GUI initialization
root = tk.Tk()
32
density_slider = ttk.Scale(root, from_=0, to=100, length=200, orient=tk.HORIZONTAL)
density_slider.set(50)
def calculate_pressure(density):
proportionality_constant = 1.0
def delay(milliseconds):
time.sleep(milliseconds / 1000.0)
race_factor = 1 # Replace with the appropriate value for Race (1 for the first case)
race_factor = 1 # Replace with the appropriate value for Race (1 for the first case)
def calculate_predicted_ratio(age):
def kg_to_lbs(kg):
33
return kg * 2.20462
def calculate_pipe_area(diameter):
def calculate_volumetric_flow_rate(area):
# This is a placeholder
if age >= 6:
return "A"
return "B"
34
return "C"
else:
return "D"
return "A"
return "B"
return "C"
else:
return "D"
def calculate_flow_and_volume():
flow_rate_increment = 0.01
volumetric_flow_rate += flow_rate_increment
volume += volume_increment
fvc_values.append(volume)
fev1_values.append(volume)
35
def repeatability_grade(measured_value, predicted_value, age):
if age >= 6:
return "Excellent"
return "Good"
return "Fair"
else:
return "Poor"
return "Excellent"
return "Good"
return "Fair"
else:
return "Poor"
def perform_quality_control_ATS_ERS_standards_checks():
36
global volume, fvc_values
if fvc_values:
largest_prior_fvc = max(fvc_values)
else:
else:
37
fvc_threshold = max(0.100, 0.10 * max(fvc_values))
else:
def simulate_spirometry(density_slider_value):
time_elapsed = 0
density = density_slider_value
while True:
pressure = calculate_pressure(density)
calculate_flow_and_volume()
print("Pressure:", pressure)
print("Volume:", volume)
delay(volume_update_interval)
38
volume_change_last_second = volume - fvc_values[-int(1 /
(volume_update_interval / 1000))]
else:
break
if variable_name == "age":
age = float(value)
height = float(value)
pipe_diameter = float(value)
simulate_spirometry(density_slider_value)
def start_simulation():
volume = 0
39
fvc_values.clear()
fev1_values.clear()
simulate_spirometry(density_slider.get())
predicted_ratio = calculate_predicted_ratio(age)
print("Grade:", grade)
perform_quality_control_ATS_ERS_standards_checks()
calculate_and_display_flow_rates()
40
def calculate_and_display_flow_rates():
pipe_area = calculate_pipe_area(pipe_diameter)
volumetric_flow_rate = calculate_volumetric_flow_rate(pipe_area)
mass_flow_rate_lbs = kg_to_lbs(mass_flow_rate)
# GUI setup
def gui_setup():
root = tk.Tk()
root.title("Spirometry Simulation")
age_slider.set(age)
41
height_slider = ttk.Scale(root, from_=100, to=200, length=200,
orient=tk.HORIZONTAL, command=lambda value: update_variable(value, "height"))
height_slider.set(height)
# Adjust the minimum and maximum values for the pipe diameter slider
diameter_slider.set(pipe_diameter)
density_slider.set(50)
42
# GUI setup
root.mainloop()
gui_setup()
43