<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Andrew Yong Zheng Dao on Medium]]></title>
        <description><![CDATA[Stories by Andrew Yong Zheng Dao on Medium]]></description>
        <link>https://medium.com/@andrewyong7338?source=rss-d9f82700d5c6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WwBZ5STp_yxt4SghqsY5XQ.jpeg</url>
            <title>Stories by Andrew Yong Zheng Dao on Medium</title>
            <link>https://medium.com/@andrewyong7338?source=rss-d9f82700d5c6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 12:11:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andrewyong7338/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[SAP ABAP: Internal table]]></title>
            <link>https://andrewyong7338.medium.com/sap-abap-internal-table-d130578cf74f?source=rss-d9f82700d5c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d130578cf74f</guid>
            <category><![CDATA[sap-abap-training]]></category>
            <category><![CDATA[abap]]></category>
            <category><![CDATA[internal-table]]></category>
            <category><![CDATA[sap-abap]]></category>
            <category><![CDATA[sap]]></category>
            <dc:creator><![CDATA[Andrew Yong Zheng Dao]]></dc:creator>
            <pubDate>Sun, 23 Apr 2023 03:38:06 GMT</pubDate>
            <atom:updated>2023-04-23T03:38:06.239Z</atom:updated>
            <content:encoded><![CDATA[<p>This post will illustrate the method to declare and implement an internal table in the SAP ABAP program.</p><h3>What is the internal table?</h3><p>In ABAP, internal tables are dynamic data and they fulfill the function of arrays. Internal tables provide a form of fixed structure and store it in working memory which is used to process a dataset from a database table with a fixed structure within a program. The data is stored and formatted line by line in memory, and each line has the same structure.</p><h3>Declare the structure of an internal table.</h3><pre>TYPES: BEGIN OF i_tab,<br>        EBELN TYPE EKKO-EBEL,<br>        BUKRS TYPE EKKO-BURKS,<br>        BSTYP TYPE EKKO-BSTYP,<br>        BSART TYPE EKKO-BASRT,<br>        LOEKZ TYPE EKKO-LOEKZ,<br>        LIFNR TYPE EKKO-LIFNR,<br>       END OF i_tab.</pre><p><em>TYPES </em>statement declares the structure lines as defined above. The <em>TYPE </em>keyword is used to refer to the datatype of the field in a database table<em>. </em>Use the commands below to create an internal table and work area of the internal table.</p><pre>DATA: it_tab TYPE TABLE OF i_tab,<br>      wa_tab TYPE it_tab.</pre><p><em>TYPE TABLE OF</em> is used for defining the variable of the internal table whereas <em>TYPE </em>is used for the work area of the internal table.</p><h3><strong>Populating internal table.</strong></h3><p>Write to internal table</p><pre>SELECT EBELN BUKRS BSTYP BSART LOEKZ LIFNR<br>  FROM EKKO INTO TABLE it_tab<br>  WHERE EBELN EQ &quot;&lt;THE PURCHASE ORDER NUMBER&gt;&quot;.</pre><p>Append to internal table</p><pre>APPEND wa_tab TO it_tab. </pre><p>Insert to internal table</p><pre>INSERT wa_tab INTO it_tab [index &lt;idx&gt;].</pre><p>Collect to internal table</p><pre>COLLECT wa_tab INTO it_tab.</pre><p>Read internal table</p><pre>LOOP AT it_tab INTO wa_tab.<br>ENDLOOP.<br><br>.<br>.<br>.<br><br>OR<br><br>.<br>.<br>.<br><br>READ it_tab INTO wa_tab WITH KEY ebeln = &quot;&lt;THE PURCHASE ORDER NUMBER&gt;&quot; .</pre><p>Delete internal table</p><pre>DELETE it_tab.</pre><p>Delete internal table by index</p><pre>DELETE it_tab INDEX &lt;IDX&gt;.</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d130578cf74f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object-oriented Programming (OOP)]]></title>
            <link>https://andrewyong7338.medium.com/object-oriented-programming-in-java-practical-approach-cd7c2c51c46f?source=rss-d9f82700d5c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd7c2c51c46f</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[object-oriented-design]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[oop-concepts]]></category>
            <dc:creator><![CDATA[Andrew Yong Zheng Dao]]></dc:creator>
            <pubDate>Tue, 21 Feb 2023 15:55:24 GMT</pubDate>
            <atom:updated>2023-04-09T13:25:31.722Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>What is object-oriented programming?</strong></h3><p>Object-oriented programming (OOP) focuses on some aspects which are classes, objects, methods, and attributes. An example is given below to structure an OOP program using Java programming.</p><h3><strong>Building a class…</strong></h3><pre>public class Student{<br><br>}</pre><h3><strong>Providing attributes</strong></h3><pre>public class Student{<br>    private String name;<br>    private String id;<br>    public String country;<br>    public String contact_num;<br>    public int date_birth;<br>    public String course_name;<br>    public double cgpa;<br>}</pre><h3><strong>Providing constructors with &amp; without parameters</strong></h3><p>A constructor without parameter initializes the value of attributes but a constructor with parameters assigns the value that is passed by parameters to attributes.</p><pre>public class Student{<br>    private String name;<br>    private String id;<br>    public String country;<br>    public String contact_num;<br>    public int date_birth;<br>    public String course_name;<br>    public double cgpa;<br><br>/*constructor without parameter*/<br>public Student(){<br>    this.name = &quot;Patrick Anderson&quot;;<br>    this.id = &quot;4856749356733454&quot;;<br>    this.country = &quot;Malaysia&quot;;<br>    this.contact_num = &quot;14256175832&quot;;<br>    this.date_birth = 99991201;<br>    this.course_name = &quot;Computer Science&quot;;<br>    this.cgpa = 3.96;<br>}<br>/*constructor with parameter*/<br>public Student(String name, String id, String country, <br>               String contact_num, int date_birth,<br>               String course_name, double cgpa){<br>        this.name = name;<br>        this.id = id;<br>        this.country = country;<br>        this.contact_num = contact_num;<br>        this.date_birth = date_birth;<br>        this.course_name = course_name;<br>        this.cgpa = cgpa;<br>    }<br>}</pre><h3><strong>Providing Setters and Getters methods</strong></h3><p>Setters method is to write the value of the attribute whereas the Getters method is to read the value of the attribute. Normally, the Setters method is named starting with <em>set</em> but the Getters method is named starting with <em>get</em>.</p><pre>public class Student{<br>    private String name;<br>    private String id;<br>    public String country;<br>    public String contact_num;<br>    public int date_birth;<br>    public String course_name;<br>    public double cgpa;<br><br>/*constructor without parameter*/<br>public Student(){<br>    this.name = &quot;Patrick Anderson&quot;;<br>    this.id = &quot;4856749356733454&quot;;<br>    this.country = &quot;Malaysia&quot;;<br>    this.contact_num = &quot;0123456789&quot;;<br>    this.date_birth = 99991201;<br>    this.course_name = &quot;Computer Science&quot;;<br>    this.cgpa = 3.96;<br>}<br>/*constructor with parameter*/<br>public Student(String name, String id, String country, <br>               String contact_num, int date_birth,<br>               String course_name, double cgpa){<br>        this.name = name;<br>        this.id = id;<br>        this.country = country;<br>        this.contact_num = contact_num;<br>        this.date_birth = date_birth;<br>        this.course_name = course_name;<br>        this.cgpa = cgpa;<br>    }<br><br>/*Getters and Setters methods*/   <br>   public String getName() {<br>        return this.name;<br>    }<br><br>    public void setName(String name) {<br>        this.name = name;<br>    }<br><br>    public String getId() {<br>        return id;<br>    }<br><br>    public void setId(String id) {<br>        this.id = id;<br>    }<br><br>    public String getCountry() {<br>        return country;<br>    }<br><br>    public void setCountry(String country) {<br>        this.country = country;<br>    }<br><br>    public String getContact_num() {<br>        return contact_num;<br>    }<br><br>    public void setContact_num(String contact_num) {<br>        this.contact_num = contact_num;<br>    }<br><br>    public int getDate_birth() {<br>        return date_birth;<br>    }<br><br>    public void setDate_birth(int date_birth) {<br>        this.date_birth = date_birth;<br>    }<br><br>    public String getCourse_name() {<br>        return course_name;<br>    }<br><br>    public void setCourse_name(String course_name) {<br>        this.course_name = course_name;<br>    }<br><br>    public double getCgpa() {<br>        return cgpa;<br>    }<br><br>    public void setCgpa(double cgpa) {<br>        this.cgpa = cgpa;<br>    }<br>}</pre><h3><strong>Creating an object for a class</strong></h3><p>An object is an instance of a class. The object is created with specifically defined data and called methods to perform the relevant operations.</p><pre>public class MainActivity{<br><br>  public static void main(String[] args){<br>    /*Create an object for the Student class without parameters*/<br>    Student student1 = new Student();  <br>  }<br><br>}</pre><p>An object named <em>student1</em> is created for the Student class. The attributes of the object hold the value as defined in the constructor without parameters.</p><p>Now, let&#39;s create an object with parameters</p><pre>public class MainActivity{<br><br>  public static void main(String[] args){<br>    /*Create an object for the Student class without parameters*/<br>    Student student1 = new Student();<br>    <br>   /*Create an object for the Student class with parameters*/<br>    Student student2 = new Student(&quot;Chris James&quot;, &quot;2354546312686958&quot;,<br>    &quot;United State&quot;, &quot;14256175832&quot;, 99991201, &quot;Criminal Science&quot;, 3.55);<br>  }<br><br>}</pre><p>An object named <em>student2</em> is created by passing parameters to the constructor. The values that are passed through parameters will be assigned to attributes respectively.</p><h3><strong>Calling methods from class</strong></h3><pre>public class MainActivity{<br><br>  public static void main(String[] args){<br>    /*Create an object for the Student class without parameters*/<br>    Student student1 = new Student();<br>    <br>   /*Create an object for the Student class with parameters*/<br>    Student student2 = new Student(&quot;Chris James&quot;, &quot;2354546312686958&quot;,<br>    &quot;United State&quot;, &quot;14256175832&quot;, 99991201, &quot;Criminal Science&quot;, 3.55);<br>  <br>   /*Call getters method*/<br>   System.out.println(&quot;The first student.&quot;);<br>   System.out.println(&quot;Name: &quot; + student1.getName());<br>   System.out.println(&quot;Course name: &quot; + student1.getCourse_name());<br>   System.out.println(&quot;Result: &quot; + student1.getCgpa());<br><br>   System.out.println(&quot;The second student.&quot;);<br>   System.out.println(&quot;Name: &quot; + student2.getName());<br>   System.out.println(&quot;Course name: &quot; + student2.getCourse_name());<br>   System.out.println(&quot;Result: &quot; + student2.getCgpa());<br>  }<br><br>}</pre><p>The output will be as follows,</p><pre>The first student.<br>Name: Patrick Anderson<br>Course name: Computer Science<br>Result: 3.96<br><br>The second student.<br>Name: Chris James<br>Course name: Criminal Science<br>Result: 3.55</pre><p>The value of the attribute can be changed by using the setters method.</p><pre>public class MainActivity{<br><br>  public static void main(String[] args){<br>    /*Create an object for the Student class without parameters*/<br>    Student student1 = new Student();<br>    <br>   /*Create an object for the Student class with parameters*/<br>    Student student2 = new Student(&quot;Chris James&quot;, &quot;2354546312686958&quot;,<br>    &quot;United State&quot;, &quot;14256175832&quot;, 99991201, &quot;Criminal Science&quot;, 3.55);<br>    <br>   /*Call setters method*/<br>   student1.setName(&quot;Patrick Leon&quot;);<br>   student1.setCgpa( 4.00 );<br><br>   /*Call getters method*/<br>   System.out.println(&quot;The first student.&quot;);<br>   System.out.println(&quot;Name: &quot; + student1.getName());<br>   System.out.println(&quot;Course name: &quot; + student1.getCourse_name());<br>   System.out.println(&quot;Result: &quot; + student1.getCgpa());<br><br>   System.out.println(&quot;The second student.&quot;);<br>   System.out.println(&quot;Name: &quot; + student2.getName());<br>   System.out.println(&quot;Course name: &quot; + student2.getCourse_name());<br>   System.out.println(&quot;Result: &quot; + student2.getCgpa());<br>  }<br><br>}</pre><p>The output will be changed as follows,</p><pre>The first student.<br>Name: Patrick Leon<br>Course name: Computer Science<br>Result: 4.00<br><br>The second student.<br>Name: Chris James<br>Course name: Criminal Science<br>Result: 3.55</pre><p>Apart from setters and getters methods, any method can be defined to perform relevant and desired operations. Let’s add new methods in Student class to calculate and display CGPA%.</p><pre>public class Student{<br>    private String name;<br>    private String id;<br>    public String country;<br>    public String contact_num;<br>    public int date_birth;<br>    public String course_name;<br>    public double cgpa;<br><br>/*constructor without parameter*/<br>public Student(){<br>    this.name = &quot;Patrick Anderson&quot;;<br>    this.id = &quot;4856749356733454&quot;;<br>    this.country = &quot;Malaysia&quot;;<br>    this.contact_num = &quot;0123456789&quot;;<br>    this.date_birth = 99991201;<br>    this.course_name = &quot;Computer Science&quot;;<br>    this.cgpa = 3.96;<br>}<br>/*constructor with parameter*/<br>public Student(String name, String id, String country, <br>               String contact_num, int date_birth,<br>               String course_name, double cgpa){<br>        this.name = name;<br>        this.id = id;<br>        this.country = country;<br>        this.contact_num = contact_num;<br>        this.date_birth = date_birth;<br>        this.course_name = course_name;<br>        this.cgpa = cgpa;<br>    }<br><br>/*Getters and Setters methods*/   <br>   public String getName() {<br>        return this.name;<br>    }<br><br>    public void setName(String name) {<br>        this.name = name;<br>    }<br><br>    public String getId() {<br>        return id;<br>    }<br><br>    public void setId(String id) {<br>        this.id = id;<br>    }<br><br>    public String getCountry() {<br>        return country;<br>    }<br><br>    public void setCountry(String country) {<br>        this.country = country;<br>    }<br><br>    public String getContact_num() {<br>        return contact_num;<br>    }<br><br>    public void setContact_num(String contact_num) {<br>        this.contact_num = contact_num;<br>    }<br><br>    public int getDate_birth() {<br>        return date_birth;<br>    }<br><br>    public void setDate_birth(int date_birth) {<br>        this.date_birth = date_birth;<br>    }<br><br>    public String getCourse_name() {<br>        return course_name;<br>    }<br><br>    public void setCourse_name(String course_name) {<br>        this.course_name = course_name;<br>    }<br><br>    public double getCgpa() {<br>        return cgpa;<br>    }<br><br>    public void setCgpa(double cgpa) {<br>        this.cgpa = cgpa;<br>    }<br>    <br>    /*Method to calculate CGPA%*/<br>    public double cal_CgpaPercent(){<br>      return (this.cgpa * 9.5); <br>    }<br><br>    /*Method to display CGPA%*/<br>    public void dis_CgpaPercent(double cgpa_percentage){<br>      System.out.println(&quot;CGPA%: &quot; + cgpa_percentage + &quot;%&quot;); <br>    }<br>}</pre><p>Implementing it…</p><pre>public class MainActivity{<br><br>  public static void main(String[] args){<br>    /*Create an object for the Student class without parameters*/<br>    Student student1 = new Student();<br>    <br>   /*Create an object for the Student class with parameters*/<br>    Student student2 = new Student(&quot;Chris James&quot;, &quot;2354546312686958&quot;,<br>    &quot;United State&quot;, &quot;14256175832&quot;, 99991201, &quot;Criminal Science&quot;, 3.55);<br>    <br>   /*Call method*/<br>   double cgpa_Percentage = student1.cal_CgpaPercent();<br>   System.out.println(&quot;The first student.&quot;);<br>   student1.dis_CgpaPercent(cgpa_Percentage);<br>  <br>   cgpa_Percentage = student2.cal_CgpaPercent();<br>   System.out.println(&quot;The second student.&quot;);<br>   student2.dis_CgpaPercent(cgpa_Percentage);<br>  }<br><br>}</pre><p>The variable <em>cgpa_Percentage</em> is declared to receive the value <strong>returns</strong> by method <em>cal_CgpaPercent()</em>, and is passed to method <em>dis_CgpaPercent(double)</em> as a parameter to be displayed.</p><p>The output will be as follows,</p><pre>The first student.<br>CGPA%: 37.62%<br><br>The second student.<br>CGPA%: 33.73%<br></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd7c2c51c46f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Identify heart sound using 2D convolutional neural network model (2D CNN)]]></title>
            <link>https://andrewyong7338.medium.com/identify-heart-sound-using-2d-convolutional-neural-network-model-2d-cnn-1ad12284e34e?source=rss-d9f82700d5c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ad12284e34e</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ecg]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Andrew Yong Zheng Dao]]></dc:creator>
            <pubDate>Sat, 31 Jul 2021 15:18:10 GMT</pubDate>
            <atom:updated>2023-07-15T03:46:02.965Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Youtube Link for system demo</em></blockquote><p><a href="https://www.youtube.com/watch?v=KOdiLGD8BZc&amp;t=2s">https://www.youtube.com/watch?v=KOdiLGD8BZc&amp;t=2s</a></p><h3><strong>Sound Identification</strong></h3><p>Listen to understand the prospect of human-like sound or the sound present in the natural environment can be performed by machines with the use of AI techniques. Supervised learning is one of the AI techniques that is commonly applied in classification and regression. In the classification and regression process, a model is built before training and learning from a huge amount of labeled training datasets which can either consist of the feature vector that describes the object of the event or the ground-truth output represented by the label.</p><p>Signal processing has been deployed in the medical field for the diagnosis process to achieve a more accurate and informative result from the system. The bio-signals such as the electrocardiogram (ECG) or phonocardiogram (PCG) do provide the signal features that can be extracted and fed into machine learning or supervised learning algorithms to classify heart valve diseases. The signal features that vary with respect to the time domain, amplitude domain, frequency content, and intensity can be used to differentiate between normal and abnormal heart sound.</p><p>Automated heart sound classification with machine learning is generally to improve the adaptation of the algorithm of the machine learning model to the changes of the heart sounds like the heart sound from the recorded audio data is very subtle. To improve the accuracy of classification, some fundamental procedures or techniques used in signal processing need to be taken into account. The procedures of heart sound classification using a machine learning model are described in the following sections.</p><h3><strong>Denoising / Cleaning</strong></h3><p>Fast Fourier transform (FFT) is calculated over the noise audio clip and signal audio clip to transform the signal into its frequency domain. The mask is then smoothed with a filter over frequency and time before applying it to the FFT of the signal audio clip.</p><pre>import noisereduce as nr<br>#remove the noise of the signal<br>reduced_noise = nr.reduce_noise(audio_clip=signal,noise_clip=signal, verbose=False)<br>#change the output to ndarray<br>reduced_signal_noise = np.array(reduced_noise)<br>np.set_printoptions(threshold=np.inf)</pre><h3>Normalization</h3><p>The de-noised signal is then normalized with the maximum value of the signal as shown below,</p><pre>import numpy as np<br>#extract the maximum signal<br>maximum_signal = max(np.abs(reduced_signal_noise))<br>#normalize the signal<br>normalized_signal = np.array([(abs(signal) / maximum_signal) for signal in reduced_signal_noise])</pre><h3>Segmentation</h3><p>In the segmentation process, Shannon energy is then calculated over the normalized signal. This energy is a square of the input signal because the square of signal is proximity to signal energy.</p><pre>#iterate through the normalized signal<br>for x in range(0, len(normalized_signal)):<br>    #power the signal by 2 <br>    signal_sample = abs(normalized_signal[x]) ** 2 <br>    if signal_sample &lt;= 0: #set the signal to 1 if it is empty<br>       signal_sample = 1.0<br>    <br>    #calculate Shannon energy<br>    shannon_energy = signal_sample * math.log(signal_sample)<br>    <br>    #replace the normalized signal with Shannon energy       <br>    normalized_signal[x] = shannon_energy</pre><p>After this, the vector of Shannon energies is then passed for averaging. Shannon energies are averaged in continuous signals with 0.01 seconds intervals.</p><pre>import numpy as np<br>#obtain the length of signal<br>length_of_signal = len(shannon_energy_signal)<br>#Initialize the signal<br>segment_signal = 0 <br>#Set the segmented signal to 0.0002 seconds for realtime analysis, otherwise 0.02 seconds for audio recorder<br>if realtime:<br>   #set the segment of 0.0002 seconds<br>   segment_signal = int(sample_rate * 0.0002)<br>else:<br>   #set the segment of 0.02 seconds<br>   segment_signal = int(sample_rate * 0.02)<br>segment_energy = [] #initialize the array<br>for x in range(0, len(shannon_energy_signal), segment_signal):<br>    sum_signal = 0 <br>    #retrieve the signal in a segment of 0.02 seconds<br>    current_segment_energy=shannon_energy_signal[x:x+segment_signal]<br>    for i in range(0, len(current_segment_energy)):<br>        #sum up the Shannon energy<br>        sum_signal += current_segment_energy[i]<br>    #assign the average Shannon energy to array    <br>    segment_energy.append(-(sum_signal/segment_signal))<br>#convert to numpy array<br>segment_energy_signal = np.array(segment_energy)</pre><p>The average Shannon energy is then normalized to convert into an energy package, which is also known as the Shannon energy envelope using the mean and the standard deviation. The envelope decreases the signal base and places the signal below the baseline.</p><pre>import numpy as np<br>import librosa, librosa.display<br>#calculate mean<br>mean_SE = np.mean(segment_energy_signal)<br>#calculate standard deviation<br>std_SE = np.std(segment_energy_signal)<br>#calculate Shannon Envelope<br>for x in range(0, len(segment_energy_signal)):<br>    envelope = 0<br>    envelope = (segment_energy_signal[x] - mean_SE) / std_SE<br>    segment_energy_signal[x] = envelope<br>shannon_envelope = segment_energy_signal<br>#calculate envelope size<br>envelope_size = range(0, shannon_envelope.size)<br>#calculate envelope time<br>envelope_time = librosa.frames_to_time(envelope_size,hop_length=442)</pre><p>A threshold value is a definition to determine peaks (QRS complex location) with the fact that the sample with greater amplitude than the threshold is chosen as output. The threshold value is defined using the mean, standard deviation, and a constant.</p><pre>import numpy as np<br>segment_signal = [0] * len(clean_signal)<br>threshold = 0<br>k = 0.001<br>#calculate threshold<br>if std_SE &lt; mean_SE:<br>   threshold = abs(k * mean_SE * (1 - std_SE ** 2))<br>elif std_SE &gt; mean_SE:<br>     threshold = abs(k * std_SE * (1 -  mean_SE ** 2))<br>#extract the signal that is greater than threshold   <br>for x in range(0, len(clean_signal)):<br>    if np.abs(clean_signal[x]) &gt; threshold:<br>       segment_signal[x] = clean_signal[x]<br>segmented_signal = np.array(segment_signal)<br>#remove 0 <br>clean_segmented_signal = np.delete(segmented_signal, np.where(segmented_signal == 0))</pre><h3>Feature Extraction</h3><p>A total of seven features are extracted from different domains. The features are processed using “librosa” and “pyAudioAnalysis” libraries. The extracted features included zero-crossing rate, Mel-frequency cepstral coefficients (MFCCs), spectral centroid, spectral roll-off, spectral flux, frequency, and energy entropy. The zero-crossing rate and the energy entropy are the time domain features, whereas the other five features belong to the frequency domain features.</p><p>Zero-crossing rate</p><pre>from pyAudioAnalysis import ShortTermFeatures as stf<br>zero_crossing_rate = stf.zero_crossing_rate(clean_segmented_signal)</pre><p>Mel-frequency cepstral coefficients (MFCCs)</p><pre>import librosa, librosa.display<br>import numpy as np<br>mfcc =librosa.feature.mfcc(clean_segmented_signal.astype(&#39;float32&#39;), sr=sample_rate)<br>mean_mfcc = np.mean(mfcc)<br>std_mfcc = np.std(mfcc)</pre><p>Spectral centroid</p><pre>import librosa, librosa.display<br>spectral_centroid = librosa.feature.spectral_centroid(clean_segmented_signal, sr=sample_rate)</pre><p>Spectral roll-off</p><pre>import librosa, librosa.display<br>spectral_rolloff = librosa.feature.spectral_rolloff(clean_segmented_signal, sr=sample_rate)</pre><p>Spectral flux</p><pre>from pyAudioAnalysis import ShortTermFeatures as stf<br>import numpy as np<br>#divide the segmented signal length by half<br>fft_frame_length = len(clean_segmented_signal) / 2<br>#extract the signal by half<br>first_frame = clean_segmented_signal[:int(fft_frame_length)]<br>second_frame = clean_segmented_signal[int(fft_frame_length):]<br>frame_step = 1<br>while(first_frame.shape != second_frame.shape):<br>      first_frame = clean_segmented_signal[:frame_step+int(fft_frame_length)]<br>      second_frame = clean_segmented_signal[int(fft_frame_length):]<br>            frame_step = frame_step + 1<br>#calculate the fft of the signal<br>fft_first_frame = np.array([np.fft.fft(first_frame)])<br>fft_second_frame = np.array([np.fft.fft(second_frame)])<br>#extract the spectral flux features<br>spectral_flux = np.array(stf.spectral_flux(np.abs(fft_first_frame), np.abs(fft_second_frame)))</pre><p>Frequency</p><pre>import numpy as np<br>frequency_domain = np.array([np.fft.fft(clean_segmented_signal)])<br>#calculate mean<br>mean_frequency_domain = np.mean(frequency_domain)<br>#calculate standard deviation<br>std_frequency_domain = np.std(frequency_domain)<br>#extract the real and the imaginary number from complex number<br>mean_frequency_domain_real = mean_frequency_domain.real<br>mean_frequency_domain_imaginary = mean_frequency_domain.imag</pre><p>Energy entropy</p><pre>from pyAudioAnalysis import ShortTermFeatures as stf<br>import numpy as np<br>#Extract the energy entropy<br>energy_entropy = np.array(stf.energy_entropy(clean_segmented_signal))</pre><p>The features are used as the characteristics of each sample of the heart sound. The values are then saved in a comma-separated value (CSV) file according to the respective column. Indeed, a new column is added to label the types of heart sounds. For instance, 1 represents normal heart sound, 2 represents murmur heart sound, 3 represents extrasystole heart sound, and 4 represents extra heart sound respectively.</p><h3>2D Convolutional Neural Network (CNN) Model</h3><p>The structure of the 2D CNN model resembles a multi-layer perceptron (MLP) and each neuron in the MLP is associated with an activation function that maps the weighted inputs to the output. There are some basic layers in CNN model, which are convolutional layer, max-pooling layer, dropout, batch normalization, and a fully connected layer or a dense layer, with a rectified linear activation function in CNN architecture. In addition, the design of the structure of the model is shown below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*bPrkZX2bPV6_SEQQmxY3hA.jpeg" /><figcaption>Model Summary</figcaption></figure><p>The proposed two-dimensional (2D) convolutional neural network (CNN) model is trained and tested using the datasets saved in the CSV file. The dataset is then split into 80% of the training set, 10% of the validation set, and 10% of the testing set.</p><h3>Results</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*68s4G45oc52JWnNQTKqfYQ.png" /><figcaption>Performance Graphs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*Gra62AbBFPRW0c2byfuGMA.png" /><figcaption>Confusion Matrix</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*oFUVqUDX0kQJYumI6aFGLw.png" /><figcaption>Receiver Operating Characteristic (ROC) curve</figcaption></figure><h3>Reference</h3><blockquote>Beyramienanlou H, Lotfivand N (2017) Shannon’s energy-based algorithm in ECG signal processing. Computational and mathematical methods in medicine 2017:1–16. <a href="https://doi.org/10.1155/2017/8081361">https://doi.org/10.1155/2017/8081361</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ad12284e34e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Maze Escape with Wall-Following Algorithm.]]></title>
            <link>https://andrewyong7338.medium.com/maze-escape-with-wall-following-algorithm-170c35b88e00?source=rss-d9f82700d5c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/170c35b88e00</guid>
            <category><![CDATA[robot-operating-system]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Andrew Yong Zheng Dao]]></dc:creator>
            <pubDate>Fri, 05 Feb 2021 13:02:32 GMT</pubDate>
            <atom:updated>2023-07-15T03:50:44.858Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*XtGe6UK4G_vocQ1H0Oz4xw.png" /></figure><h3>Maze Solving Problem</h3><p>Maze solving is an imperative section that leads to the development of the decision-making algorithms. The development of the decision-making algorithms is to enable the robot to navigate and solve the problem. Undoubtedly, the maze provides the conditions that allow the robot to navigate and solve the maze problem through the decision making that leads an entrance to a goal.</p><h3><strong>Wall-Following Algorithms</strong></h3><p>The wall follower algorithm contains two rules which are the right-hand rule and the left-hand rule. Regarding the rules, both rules can be applied to solve the maze in a fast and without any extra memory to solve maze. The rules are based on the simple logic of movements whereby either following along the left side or the right side of the enclosure wall. Following one side of the enclosure wall will form a pathway that leads to the exit.</p><h3><strong>Maze Structure</strong></h3><p>This section will show the structure of the maze. The maze is constructed using the gazebo virtual environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hVGDpFToOYOmW1ve-aoLIQ.png" /><figcaption>Top View</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aydrSb36BQb9ssXofDPPFQ.png" /><figcaption>Front View</figcaption></figure><h3><strong>Structure of the Robot</strong></h3><p>The application of the wall follower algorithm indicates that there is only one side of the sensor is required to detect the wall. The functionality of the sensor is to receive or sense the input and the information from the external environment.</p><p>When implies the sensor with the human begin, the eyes, nose, ears, and skin can be considered as the sensor of the human because these body features help the human to receive information from the real world. The same concept is applied to the robot.</p><p>The robot requires the sensor devices to accept the input from the external environment to process and respond accordingly. The sensor of the turtlebot3 burger is the LiDAR which is a 2D laser scanner sensor. This sensor receives the reading from a different angle.</p><p>The view of the angle of obtaining the value from a different direction with the LiDAR scanner is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*BEmoZvN1E33hZLEti1RKfw.png" /></figure><h3>Implement Wall-Following Algorithm in Maze</h3><p>The wall follower algorithm is highly dependent on the enclosure wall to generate a solution path. The turtlebot3 burger can only detect either one side of the enclosure wall using a single side of the direction.</p><p>Throughout the finding, both the left-hand rule and the right-hand rule must detect the front wall and either the left side or the right side of the wall based on the rule selected. For instance, the left-hand rule must detect the existence of the left wall and the front wall whereas the right-hand rule is required to detect the right wall and the front wall during execution. The abstract view of the concept of the algorithm is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*M_PVImuRHfmaRUEiW3Yijw.png" /></figure><p>The right-hand rule wall follower algorithm is selected as the method to solve the maze problem. Based on the determination of entrance and exit on the maze in the picture above, it can realize that the path for the right-hand rule is less complex than that of using the left-hand rule. Indeed, the less complex of the path will result in less consumption of the amount of time in escaping the maze.</p><p>From the perspective of the turtlebot3 burger, the yellow color line and the purple color line represent the pathway for the right-hand rule and the left-hand rule respectively.</p><h3><strong>Truth Table of the right-hand rule</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*Bz0AXvSzIiVujfTGGA7fmg.png" /></figure><p>The concept of the right-hand rule is based on the table above, and vice versa.</p><h3><strong>Python Code Implementation</strong></h3><p>Stops all movement</p><pre>def stop(vel_msg, velocity_publisher):  <br>vel_msg.linear.x = 0 #set linear x to zero  <br>vel_msg.angular.z = 0 #set angular z to zero  <br># Publish the velocity to stop the robot<br>velocity_publisher.publish(vel_msg) <br>time.sleep(1) #stop for 1 second</pre><p>Moves Forward</p><pre>def movingForward(vel_msg, velocity_publisher, t0, current_distance, distance, speed, forwardSpeed, front):  <br>vel_msg.linear.x = forwardSpeed  <br>vel_msg.angular.z = 0 #initialize angular z to zero   <br>print(&#39;Is moving&#39;)  <br>while(current_distance &lt; distance):<br>    velocity_publisher.publish(vel_msg)#Publish the velocity  <br>    #Take actual time to velocity calculation<br>    t1 = rospy.Time.now().to_sec()<br>    current_distance = speed*(t1-t0)#calculates distance<br>#Stop the robot when the front distance from obstacle is smaller than 1.0  <br>if (front &lt; 1.0):<br>    stop(vel_msg, velocity_publisher)<br>time.sleep(1) # stop for 1 second</pre><p>Move Backward</p><pre>def movingBackward(vel_msg, velocity_publisher, t0, current_distance, distance, speed, backwardSpeed, front):<br>   <br>  vel_msg.linear.x = backwardSpeed<br>  vel_msg.angular.z = 0 #initialize angular z to zero<br>  print(&#39;Is backing&#39;)  <br>  while(current_distance &lt; (distance/2)):<br>    velocity_publisher.publish(vel_msg)#Publish the velocity<br>    #Take actual time to vel calculation  <br>    t1 = rospy.Time.now().to_sec()<br>    current_distance = speed*(t1-t0)#calculates distance<br>  if (front &lt; 1.0):<br>    stop(vel_msg, velocity_publisher)<br>  time.sleep(1) # stop for 1 second</pre><p>Turn 90 degrees Clockwise</p><pre>def turnCW(vel_msg, velocity_publisher, t0, current_angle, turningSpeed, angle):<br>   #converting from angle to radian<br>   angular_speed = round(turningSpeed*2*PI/360, 1)<br>   #converting from angle to radian<br>   relative_angle = round(angle*2*PI/360, 1)<br>   vel_msg.linear.x = 0 #initialize linear x to zero<br>   #initialize angular z with angular_speed  <br>   vel_msg.angular.z = -abs(angular_speed)<br>   print(&#39;Turning&#39;)<br>   while(current_angle &lt; relative_angle):<br>      velocity_publisher.publish(vel_msg)#Publish the velocity  <br>      #Take actual time to vel calculation<br>      t1 = rospy.Time.now().to_sec()<br>      current_angle = angular_speed*(t1-t0)#calculates distance<br>   <br>   time.sleep(1)#stop the robot for 1 second</pre><p>Turn 90 degrees Counter-clockwise</p><pre>def turnCCW(vel_msg, velocity_publisher, t0, current_angle, turningSpeed, angle):<br>   #converting from angle to radian<br>   angular_speed = round(turningSpeed*2*PI/360, 1)<br>   #converting from angle to radian<br>   relative_angle = round(angle*2*PI/360, 1)<br>   vel_msg.linear.x = 0 #initialize linear x to zero<br>   #initialize angular z with angular_speed  <br>   vel_msg.angular.z = abs(angular_speed)<br>   print(&#39;Turning&#39;)<br>   while(current_angle &lt; relative_angle):<br>      velocity_publisher.publish(vel_msg)#Publish the velocity  <br>      #Take actual time to vel calculation<br>      t1 = rospy.Time.now().to_sec()<br>      current_angle = angular_speed*(t1-t0)#calculates distance<br>   <br>   time.sleep(1)#stop the robot for 1 second</pre><p>Right-rule algorithm</p><pre>def escapeMaze():<br>   #initialize the node   <br>   rospy.init_node(&#39;robot_cleaner&#39;, anonymous=True)<br>   #set topic for publisher<br>   velocity_publisher = rospy.Publisher(&#39;cmd_vel&#39;, Twist,queue_size=10)<br> <br>   vel_msg = Twist()  <br>   print(&quot;Let&#39;s move the robot&quot;)  <br>   #define the local speed <br>   speed = 0.2<br>   #define the distance<br>   distance = [0.10, 0.20, 0.29]<br>   #set all the linear and angular motion of each dimension to zero        <br>   vel_msg.linear.x = 0  <br>   vel_msg.linear.y = 0  <br>   vel_msg.linear.z = 0  <br>   vel_msg.angular.x = 0  <br>   vel_msg.angular.y = 0  <br>   vel_msg.angular.z = 0  <br>   #Execute the movement when the robot is active<br>   while not rospy.is_shutdown():<br>   #define the variable to determine the existance of the right wall<br>   no_right_wall = None<br>   #define the variable to determine the existance of the front wall<br>   no_front_wall = None<br>   #set current time for distance calculate  <br>   t0 = rospy.Time.now().to_sec()<br>   #define the variable for current distance<br>   current_distance = 0<br>   #read the input from lazer scan<br>   scan_msg = rospy.wait_for_message(&quot;scan&quot;, LaserScan)<br>   #read the input distance between robot and obstacles in the   <br>   #front, left, right, top left, and top right direction<br>   front = scan_msg.ranges[1]  <br>   left = scan_msg.ranges[90]  <br>   top_left = scan_msg.ranges[45]  <br>   right = scan_msg.ranges[270]  <br>   top_right = scan_msg.ranges[315]<br>   #No right wall if the distance between the robot and obstacles if <br>   the distance in right and top_right  <br>   #direction is smaller than 2.0, else right wall is detected<br>   if (right&lt; 2.0) or (top_right &lt; 2.0):<br>      no_right_wall = False #False becuase right wall is detected   <br>      print(&#39;Right wall is detected&#39;)#display message<br>   else:<br>      no_right_wall = True #True becuase right wall is not detected       <br>      print(&#39;Right wall is not detected&#39;) #display message<br>   #Turn clockwise and move forward when no right wall is detected<br>   if no_right_wall == True:<br>      if front &lt; 1.0:<br>      print(&#39;Move backward&#39;)#display message  <br>      #move backward if the distance in front direction is smaller <br>      #than 1.0  <br>      movingBackward(vel_msg, velocity_publisher, t0, <br>      current_distance, <br>      distance[1], speed, -0.36, front)  <br>      <br>      print(&#39;Turn clockwise because no right wall&#39;) #display message      <br>      #Turn 90 degree clockwise<br>      <br>      turnCW(vel_msg, velocity_publisher, t0, 0, 3, 90) <br>      print(&#39;Move forward because no right wall&#39;)<br>     if front &lt; 0.5:<br>         #Move forward with distance of 0.1 when distance from front    <br>         #wall is smaller than 0.5<br>         movingForward(vel_msg, velocity_publisher, t0,  <br>         current_distance, distance[0], speed, 0.36, front)<br>     else:<br>        #Move forward with distance of 0.29 when distance from front  <br>        #wall is greater than 0.5<br>        movingForward(vel_msg, velocity_publisher, t0,<br>        current_distance, distance[2], speed, 0.36, front)<br>#Detect distance from front wall when no right wall is detected<br>  else:<br>   #No front wall if the distance between the robot and obstacles if <br>   #the distance in front and top left<br>   #direction is smaller than 1.0, else front wall is detected<br>   if (front &gt; 1.0) or (top_left &gt; 1.0):<br>     #True because no front wall is detected<br>     no_front_wall = True<br>     print(&#39;Front wall is not detected&#39;)#display message<br>   else:<br>     #False because front wall is detected<br>     no_front_wall = False<br>     print(&#39;Front wall is detected&#39;)#display message<br> <br>   #Move forward if there is no front wall<br>   if (no_front_wall == True) and (front &gt; 1.0):<br>     if (front &lt; 0.5):<br>       print(&#39;Move forward because no front wall&#39;)#display message<br>       #Move forward with distance of 0.1 when distance from front   <br>       #wall is smaller than 0.5<br>       movingForward(vel_msg, velocity_publisher, t0,   <br>       current_distance,distance[0], speed, 0.36, front)<br>    <br>     else:<br>     #Move forward with distance of 0.1 when distance from front  <br>     #wall is greater than 0.5<br>     movingForward(vel_msg, velocity_publisher, t0,current_distance,    <br>     distance[2], speed, 0.36, front)<br> <br>  #Turn clockwise if neither front wall, left, and right wall are  <br>  #detected. Indeed, turn counter-clockwise if both front wall and <br>  #right wall are detected<br>  else:<br>    if (left &gt; 0.5) and ((right &gt; 3.0) or (top_right &gt; 3.0)):<br>     if front &lt; 1.0:<br>     print(&#39;Move backward&#39;)#display message<br>     #move backward if the distance in front direction is smaller <br>     #than 1.0<br>     movingBackward(vel_msg, velocity_publisher,    <br>     t0,current_distance,distance[1], speed, -0.36, front)<br>     print(&#39;Turn clockwise because no right wall&#39;)#display message    <br>     #turn 90 degree clockwise<br>     turnCW(vel_msg, velocity_publisher, t0, 0, 3, 90)<br>   <br>   else:<br>     if front &lt; 1.0:<br>       print(&#39;Move backward&#39;)#display message<br>       #move backward if the distance in front direction is smaller  <br>       #than 1.0<br>       movingBackward(vel_msg, velocity_publisher,  <br>       t0,current_distance,distance[1], speed, -0.36, front)<br>       #display message<br>       print(&#39;Turn counter-clockwise because have front wall&#39;)<br>       #turn 90 degree counter-clockwise<br>       turnCCW(vel_msg, velocity_publisher, t0, 0, 3, 90)<br># The node will stop when press control + C<br> rospy.spin()</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=170c35b88e00" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Fuzzy Logic Algorithms to Obtain Plant’s Health Conditions.]]></title>
            <link>https://andrewyong7338.medium.com/using-fuzzy-logic-algorithms-to-obtain-plants-health-conditions-fb175092960?source=rss-d9f82700d5c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb175092960</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[fuzzy-logic]]></category>
            <category><![CDATA[fuzzy-matching]]></category>
            <dc:creator><![CDATA[Andrew Yong Zheng Dao]]></dc:creator>
            <pubDate>Sat, 11 Jul 2020 15:54:47 GMT</pubDate>
            <atom:updated>2023-07-15T03:54:22.869Z</atom:updated>
            <content:encoded><![CDATA[<h3>Obtain Plant’s Health Conditions with Fuzzy Logic Algorithm</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*_BfqL2Lf5yg2HEwp49a5cw.png" /></figure><h3><strong>What is fuzzy logic?</strong></h3><p>Fuzzy logic is a way of reasoning that simulates human reasoning. The logic imitates how human makes decisions that involve all intermediate possibilities between the answer of YES and NO. The reasoning process involves the use of a mathematical formula which is known as the membership function.</p><h3><strong>Membership Function</strong></h3><p>The membership function is a mathematical function that use in fuzzy logic to calculate the interval value and determine the possible outcomes accordingly. The interval value will modify the consequences, THEN part after evaluating the antecedents, IF part.</p><h3><strong>Fuzzification and defuzzification</strong></h3><p>Fuzzification is a process that converts the input value into linguistic qualifiers and the input will then map and generate output based on fuzzy rules. Moreover, the defuzzification process is to obtain an average result from all the fuzzification results.</p><h3><strong>Fuzzy Logic and Plant Condition</strong></h3><p>Fuzzy Logic is designed to determine the plant’s condition. The algorithm represents a plant to illustrate or simulate the speaking style of humans to express its conditions based on measurable data. The data include temperature value, light intensity value, soil moisture value, and ambient humidity value. These data are passed as input and being processed by the algorithm to obtain the current level of each measurement in terms of linguistic variables respectively. The linguistic variables are set as the antecedents (in the IF clause) and the plant’s health condition is set as the consequences (in the ELSE clause).</p><p>This application helps to specify the plant’s condition and clarify the requirements of the plant in detail in order to improve the current health status of the plant.</p><h3>The input data that are required from a plant</h3><ol><li>Light Intensity (lux)</li><li>Temperature (%)</li><li>Soil Moisture (%)</li><li>Ambient Humidity (%)</li></ol><h3><strong>Triangular Membership Function</strong></h3><p>The triangular membership function is used to characterize the input data and the linguistic variable used for fuzzy reasoning. The mathematical function of the triangular membership function is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*M8c_Hy7RUdsQkAXy8gAw6Q.png" /></figure><h3><strong>The suggested properties of each measurement variable</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*-TQbjnRj9eR8wZG7Km4K9w.png" /></figure><h3>The suggested properties of the overall plant’s health condition</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*0-0yFrC6mhe4lSq6zTSk_w.png" /></figure><h3><strong>Some suggested fuzzy rules</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*d0hOEDY9NFr5Ri9eoGBOeQ.png" /></figure><h3><strong>The defuzzification</strong></h3><p>The weighted average method is applied in the defuzzification process. The formula of the weighted average method is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*IMzj7ONrWxPI47nx8OEljA.png" /></figure><h3><strong>Fuzzy Logic Algorithm (In Javascript)</strong></h3><p>Step 1: Initialise a fuzzy set</p><pre>//Initialize each fuzzy set with input variable name, the name of //membership function, and the range of each membership function.<br>let fuzzyset = {<br> variables_input:[<br>   // Fuzzify light intensity level<br>  {<br>   name: &#39;LightIntensity&#39;,<br>   setsName: [&#39;Dark&#39;, &#39;Normal&#39;, &#39;Bright&#39;],<br>   sets:[[0,5000,10000],[9000,17000,25000],[24000,67500,111000],]<br>  },<br>  //Fuzzify temperature level<br>  {<br>   name: &#39;Temperature&#39;,<br>   setsName: [&#39;Cool&#39;, &#39;Normal&#39;, &#39;Hot&#39;],<br>   sets:[[0,23,46],[44,60,76],[74,87,100],]<br>  },<br>   // Fuzzify Soil Moisture level<br>  {<br>   name: &#39;SoilMoisture&#39;,<br>   setsName: [&#39;Dry&#39;, &#39;Normal&#39;, &#39;Wet&#39;],<br>   sets:[[0,20,40],[30,50,70],[60,80,100],]<br>  },<br> //Fuzzify ambient humidity level<br> {<br>   name: &#39;AmbientHumidity&#39;,<br>   setsName: [&#39;Low&#39;, &#39;Normal&#39;, &#39;High&#39;],<br>   sets: [[0,20,40],[30,50,70],[60,80,100],]<br> }<br> ],<br> };</pre><pre>//fuzzify tips output<br>let tips_output=<br>{<br>    name: &#39;Plant Condition&#39;,<br>    setsName: [&#39;Unhealthy&#39;, &#39;Healthy&#39;, &#39;Very Healthy&#39;],<br>    sets:[[0,20,40],[30,50,70],[60,80,100],]<br>};</pre><p>Step 2: Initialize the Fuzzy Rules</p><pre>/*Define some IF-ELSE rules set whereby condition array store the variable names for <br>light intensity, temperature, soil moisture and ambient humidity respectively and associated with<br>message which displayed later*/</pre><pre>let fuzzysetRulesBase = [{condition :[&#39;Dark&#39;, &#39;Cool&#39;, &#39;Dry&#39;,&#39;High&#39;],<br>message: &quot;I am in extremely unhealthy condition. Rest in Peace~&quot;<br>},<br>{condition :[&#39;Normal&#39;, &#39;Cool&#39;, &#39;Dry&#39;, &#39;Normal&#39;],<br>message: &quot;I am in fairly healthy condition because the soil is dry! I need water!&quot;<br>},<br>{condition :[&#39;Normal&#39;, &#39;Normal&#39;, &#39;Dry&#39;, &#39;Normal&#39;],<br>message: &quot;I need water to recover to normal condition.&quot;<br>},<br>{condition :[&#39;Dark&#39;, &#39;Normal&#39;, &#39;Dry&#39;, &#39;Normal&#39;],<br>message: &quot;The condition is not suitable for me. I need sunlight and water!&quot;<br>},<br>{condition :[&#39;Dark&#39;, &#39;Normal&#39;, &#39;Normal&#39;, &#39;Normal&#39;],<br>message: &quot;The condition is not suitable for me. I need sunlight to produce foods!&quot;<br>},<br>{condition :[&#39;Dark&#39;, &#39;Cool&#39;, &#39;Normal&#39;, &#39;High&#39;],<br>message: &quot;I am not in an ideal condition! The surrounding is too cool and my transpiration rate is low!&quot;<br>},<br>{condition :[&#39;Dark&#39;, &#39;Cool&#39;, &#39;Wet&#39;, &#39;High&#39;],<br>message: &quot;I am not in an ideal condition! The surrounding is too cool and my transpiration rate is low!&quot;<br>},<br>{condition :[&#39;Bright&#39;,&#39;Normal&#39;,&#39;Wet&#39;,&#39;High&#39;],<br>message: &quot;I am healthy but the surrounding humidity is too wet.&quot;<br>},<br>{condition :[&#39;Bright&#39;, &#39;Hot&#39;, &#39;Dry&#39;, &#39;Low&#39;],<br>message: &quot;I feel extremely hot and my soil is very dry! This is not the good condition although the water is provided&quot;<br>},<br>{condition :[&#39;Normal&#39;, &#39;Normal&#39;, &#39;Normal&#39;, &#39;Normal&#39;],<br>message: &quot;I am healthy. Thanks for your concern~&quot;<br>}, <br>{condition :[&#39;Bright&#39;, &#39;Normal&#39;, &#39;Wet&#39;, &#39;Low&#39;],<br>message: &quot;I am very healthy right now. I growth smoothly.&quot;<br>},<br>{condition :[&#39;Normal&#39;, &#39;Cool&#39;, &#39;Wet&#39;, &#39;High&#39;],<br>message: &quot;It is too wet in here, I can&#39;t get rid of the excess water!&quot;<br>},<br>{condition :[&#39;Normal&#39;, &#39;Hot&#39;, &#39;Dry&#39;, &#39;Normal&#39;],<br>message: &quot;It is too hot and dry, I am dehydrated!&quot;<br>}<br>];</pre><p>Step 3: Array for factors and the trigger’s values</p><pre>/*Initiallise the factor array to store the linguistic variable from light intensity, temperature, <br>soil moisture and humidity level factor to check the plants&#39; health condition*/</pre><pre>let factor = [&#39;undefine&#39;,&#39;undefine&#39;,&#39;undefine&#39;,&#39;undefine&#39;];</pre><pre>/*Initiallise the trigger to compare the input for each factor if the range overlapping. 0 will store the calculated value from membership function and &#39;unknown&#39; will store the linguistic<br>variable<br>*/</pre><pre>let trigger = [0,&#39;unknown&#39;,0,&#39;unknown&#39;];</pre><p>Step 4: Declare Membership Function</p><pre>/* Triangular membership function*/<br>function mf_triangle(input, left, max, right)<br>{<br>  if (input &lt; left || input &gt; right) return 0;<br>  if (left &lt;= input &amp;&amp; input &lt;= max) return (input - left) / (max - left);<br>  <br>  return (right - input) / (right - max);<br>}</pre><p>Step 5: Declare Inference Function</p><pre>/*Inference Function for calculate input membership*/<br>function inference(){<br> if(trigger[0] &gt; trigger[2]){<br>      return trigger[1];<br>}if(trigger[0] == trigger[2]){<br>      return trigger[1];<br>}else{<br>      return trigger[3];<br>}}</pre><p>Step 6: Declare Fuzzification Function</p><pre>//Passing the value to membership function<br>function fuzzification(index, input_value){<br>   var left, max,right,linguistic, output, counter = 0;<br>//loop to pass the range of each fuzzified factor to the membership function<br>  for(let i = 0; i&lt;3; i++){<br>  //if index is not equal four then calculate input variable     respectively<br>   if(index !== 4){<br>         left = fuzzyset.variables_input[index].sets[i][0];<br>         max = fuzzyset.variables_input[index].sets[i][1];<br>         right = fuzzyset.variables_input[index].sets[i][2];<br>         linguistic = fuzzyset.variables_input[index].setsName[i];<br>         output = mf_triangle(input_value,left,max,right);<br>   }else{// else calculate the output variable<br>            left = tips_output.sets[i][0];<br>         max = tips_output.sets[i][1];<br>         right = tips_output.sets[i][2];<br>         linguistic = tips_output.setsName[i];<br>         output = mf_triangle(input_value,left,max,right);<br>   }<br>   if(output !== 0){ // if the condition is triggered save it to trigger array<br>   if(counter == 0){<br>       trigger[0] = output;<br>       trigger[1] = linguistic;  <br>       counter++;//increase counter by one<br>   }else{<br>         trigger[2] = output;<br>         trigger[3] = linguistic;}<br>   }<br>   }<br>   counter = 0;//reset counter to zero<br>}</pre><p>Step 7: Declare Defuzzification Function</p><pre>//Defuzzification by appling weight-average method <br>function defuzzification(light_input,temperature_input,soilMoisture_input,ambientHumidity_input){<br>  var left, max, right, output, sumOfmidpointMultiplyoutput = 0,   sumOfoutput = 0, counter = 0;<br>do{<br>   for(let i = 0; i&lt;3; i++){<br>   //counter is zero calculate light intensity input<br>    if(counter === 0){<br>    left = ((fuzzyset.variables_input[counter].sets[i][0] / 111000) *100);//normalized the left boundary over 111000 lux<br>    max = ((fuzzyset.variables_input[counter].sets[i][1] / 111000)*100);//normalized the maximum over 111000 lux<br>    right = ((fuzzyset.variables_input[counter].sets[i][2] / 111000)*100);//normalized the right boundary over 111000 lux<br>    var convertLightToPercentage = ((light_input / 111000) * 100);//normalized the light intensity input over 111000 lux<br>    output = mf_triangle(convertLightToPercentage,left,max,right);<br>    }<br>    //if counter is one calculate temperature input<br>    else if(counter === 1){<br>    left = fuzzyset.variables_input[counter].sets[i][0];<br>     max = fuzzyset.variables_input[counter].sets[i][1];<br>    right = fuzzyset.variables_input[counter].sets[i][2];<br>    output = mf_triangle(temperature_input,left,max,right);<br>     }<br>    //if counter is two calculate soil moisture input<br>    else if(counter === 2){<br>     left = fuzzyset.variables_input[counter].sets[i][0];<br>     max = fuzzyset.variables_input[counter].sets[i][1];<br>     right = fuzzyset.variables_input[counter].sets[i][2];<br>      output = mf_triangle(soilMoisture_input,left,max,right);<br>      }<br>   // if counter is three calculate ambient humidity input     <br>    else if(counter === 3){<br>      left = fuzzyset.variables_input[counter].sets[i][0];<br>       max = fuzzyset.variables_input[counter].sets[i][1];<br>      right = fuzzyset.variables_input[counter].sets[i][2];<br>      output = mf_triangle(ambientHumidity_input,left,max,right);<br>      }<br>   if(output !== 0){//if return 1<br>  /*sum the multiplication between output and the midpoint of the range*/<br>  sumOfmidpointMultiplyoutput = sumOfmidpointMultiplyoutput + (output*((left + right) / 2));<br>   //sum up the output<br>    sumOfoutput = sumOfoutput + output;<br>   }<br>   }<br>   counter++;//increase counter by one<br>  }while(counter &lt; 4);//repeat when counter smaller that four<br>  /*return the defuzzification value*/<br>  return (sumOfmidpointMultiplyoutput / sumOfoutput);<br>}</pre><p>Step 8: Declare function to obtain the plant’s health condition</p><pre>//Appriopriate plant condition reply<br>  function condition(light_input, temperature_input, soilMoisture_input, ambientHumidity_input){<br> //normalized the temperature over 40 celcius<br> var convertTempToPercentage = ((temperature_input / 40) * 100); <br>    let defuzzify,match; <br> //fuzzification function call to pass light intensity input<br> //and save the linguistic variable to factor[0] <br>    fuzzification(0, light_input);<br>    factor[0] = inference();<br> //fuzzification function call to pass temperature input<br> //and save the linguistic variable to factor[1]<br>    fuzzification(1, convertTempToPercentage);<br>    factor[1] = inference();<br> //fuzzification function call to pass soil moisture input<br> //and save the linguistic variable to factor[2]<br>    fuzzification(2, soilMoisture_input);<br>    factor[2] = inference();<br> //fuzzification function call to pass humidity input<br> //save the linguistic variable to factor[3]<br>    fuzzification(3, ambientHumidity_input);<br>    factor[3] = inference();<br> //defuzzify the input varibles<br>    defuzzify = defuzzification(light_input,convertTempToPercentage,soilMoisture_input,ambientHumidity_input);<br>    trigger = [0,&#39;unknown&#39;,0,&#39;unknown&#39;];//reset trigger to default<br>    fuzzification(4, defuzzify); //fuzzification the centroid to get the health condition of plant<br>    //loop to match with the rules base in fuzzysetRules<br>    for(let i = 0; i &lt; fuzzysetRulesBase.length; i++){<br>        //IF the rules batch match<br>    if(JSON.stringify(fuzzysetRulesBase[i].condition) == JSON.stringify(factor)){<br>    console.log(fuzzysetRulesBase[i].message);<br>    match = true; break;<br>   }else{<br>      match = false;<br>    }<br>    }<br>    if(!match)//If not match the rules base<br>    {<br>     if(trigger[1] === &#39;Unhealthy&#39;){<br>       if(trigger[2] &gt;= trigger[0]){<br>        console.log(&quot;I feel better now as I am recovery from aging.&quot;);<br>       }else{<br>          console.log(&quot;I feel very sad and unenergized. My leaves are lost and perhaps in permature aging condition.&quot;);}<br>          }<br>  else if(trigger[1] === &#39;Healthy&#39;){<br>            if(trigger[2] &gt;= trigger[0]){<br>              if(factor[2] == &quot;Dry&quot;){<br>                console.log(&quot;I feel better and getting healthier, and I need some water&quot;);<br>              }else{<br>                console.log(&quot;I feel better as all my photosynthesis and transpiration processes run smoothly and I am getting healthier&quot;);<br>              }<br>            }else{<br>            console.log(&quot;I am healthy and feel comfortable with current condition.&quot;);<br>            }<br>          }<br>  else if(trigger[1] === &#39;Very Healthy&#39; || trigger[3] === &#39;Very Healthy&#39;){<br>         if(trigger[1] === &#39;High&#39;){<br>            console.log(&quot;I feel extremely delightful as all my features look gorgeous.&quot;);<br>         }else if(trigger[2] &gt;= trigger[0]){<br>            console.log(&quot;I growth smoothly and getting stronger.&quot;);<br>         }else{<br>            console.log(&quot;I am in a healthy condition and will grow better than now.&quot;);<br>           }<br>        }       <br>      }<br>        console.log(&quot;My healthy level is about&quot; + defuzzify + &quot;%.&quot;);<br>       //reset trigger array to default<br>       trigger = [0,&#39;unknown&#39;,0,&#39;unknown&#39;];<br>   }</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb175092960" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>