Wednesday, May 29, 2019

Simple Regression using SQL

A.  Calculating for the Slope

Given the following data in the MariaDB database table named "simreg":

XY
11234
21768
32234
42555
52800

Where X is the independent variable and Y is the dependent variable, the slope can be calculated using the following SQL command:

SELECT (sum((x - (select avg(x) from simreg)) * (y - (select avg(y) from simreg)))) / sum(power(x - (select avg(x) from simreg),2)) AS 'Slope' FROM simreg;

This query produces the following output:

Slope
391.9

The slope value of 391.9 is correct.  We can convert the query into an SQL function as follows:

DELIMITER |
CREATE FUNCTION c_slope() RETURNS DOUBLE
BEGIN
    DECLARE myres DOUBLE;
    SELECT (sum((x - (select avg(x) from simreg)) * (y - (select avg(y) from simreg)))) / sum(power(x - (select avg(x) from simreg),2)) INTO myres FROM simreg;
    RETURN myres;
END |
DELIMITER ;

Such will create the function c_slope() and can be queried using the command:

SELECT c_slope() AS 'Slope';


B.  Calculating for the Intercept

The Intercept can be calculated by issuing the following SQL command:

SELECT avg(y) - (sum((x - (select avg(x) from simreg)) * (y - (select avg(y) from simreg)))) / (sum((x - (select avg(x) from simreg))* (x - (select avg(x) from simreg)))) * avg(x) AS 'Intercept' FROM simreg;

This query produces the following output:

Intercept
942.5

The Intercept value of 942.5 is correct.  Such query can be converted into an SQL function as follows:

DELIMITER |
CREATE FUNCTION c_intercept() RETURNS DOUBLE
BEGIN
     DECLARE myres DOUBLE;
     SELECT avg(y) - (sum((x - (select avg(x) from simreg)) * (y - (select avg(y) from simreg)))) / (sum((x - (select avg(x) from simreg))* (x - (select avg(x) from simreg)))) * avg(x) INTO myres FROM simreg;
     RETURN myres;
END |
DELIMITER ;

Likewise, such will create the function c_intercept() and can be queried using the command:

SELECT c_intercept() AS 'Intercept';


C.  Forecasting

Given the Slope (b) and Intercept (a), the equation of the straight line is "Y = a + b X".  We can use this equation to forecast the value of Y by supplying the value of X.  To execute this in SQL, the command is:

SELECT c_intercept()+c_slope()*x AS 'Y Forecast' FROM simreg;

This query produces the following output:

Y Forecast
1334.4
1726.3
2118.2
2510.1
2902

If we want to have the forecast side by side with the original Y, we can just add the Y into the query as:

SELECT c_intercept()+c_slope()*x AS 'Y Forecast', y AS 'Y Original' FROM simreg;

This will produce the following output:

Y ForecastY Original
1334.41234
1726.31768
2118.22234
2510.12555
29022800

Likewise, if we want to get the forecast error, we can just modify the query a bit to deduct the 'Y Original' with the 'Y Forecast' as follows:

SELECT c_intercept()+c_slope()*x AS 'Y Forecast', y AS 'Y Original', (c_intercept()+c_slope()*x) - y AS 'Y Error' FROM simreg;

This will produce the following output:

Y ForecastY OriginalY Error
1334.41234100.40000000000009
1726.31768-41.700000000000045
2118.22234-115.80000000000018
2510.12555-44.90000000000009
29022800102


D.  Calculating the Mean Absolute Difference

We can calculate the Mean Absolute Difference (MAD) as a means to compare the "Simple Regression Method" with other forecasting methods.  The SQL command to get the MAD is:

SELECT avg(abs((c_intercept()+c_slope()*x) - y)) AS 'MAD' FROM simreg;

Which produces the output:

MAD
80.96000000000008


E.  Calculating the Root Mean Square Error

As an alternative the MAD, we can also get the Root Mean Square Error (RMSE) of the method.  The SQL command is:

SELECT SQRT(AVG(POWER((c_intercept()+c_slope()*x - y),2))) AS 'RMSE' FROM simreg;

Which produces the output:

RMSE
86.77407446927921


F.  Coefficient of Determination

The Coefficient of Determination, also commonly referred to as R-Squared, is the percentage of the variation in the dependent variable (Y) that can be explained by the independent variable (X).  The higher percentage and closer the value to 1, the better.  To be precise, R-Squared is the Regression Sum of Squares (RSS) over the Total Sum of Squares (TSS).

To calculate R-Squared, the following SQL functions needs to be created to facilitate the query.

a) Mean of X function

DELIMITER |
CREATE FUNCTION c_avex() RETURNS DOUBLE
BEGIN
DECLARE myres DOUBLE;
SELECT avg(x) INTO myres FROM simreg;
return myres;
END |
DELIMITER ;

b) Mean of Y function

DELIMITER |
CREATE FUNCTION c_avey() RETURNS DOUBLE
BEGIN
DECLARE myres DOUBLE;
SELECT avg(y) INTO myres FROM simreg;
return myres;
END |
DELIMITER ;

c)  Regression Sum of Squares (RSS) function

DELIMITER |
CREATE FUNCTION c_rss() RETURNS DOUBLE
BEGIN
DECLARE myres DOUBLE;
SELECT sum(power(((c_intercept()+c_slope()*x) - c_avey()),2)) INTO myres FROM simreg;
return myres;
END |
DELIMITER ;

d)  Total Sum of Squares (TSS) function

DELIMITER |
CREATE FUNCTION c_tss() RETURNS DOUBLE
BEGIN
DECLARE myres DOUBLE;
SELECT  sum(power(y-c_avey(),2)) INTO myres FROM simreg;
return myres;
END |
DELIMITER ;


e)  R-Squared function

DELIMITER |
CREATE FUNCTION c_r_squared() RETURNS DOUBLE
BEGIN
DECLARE myres DOUBLE;
SELECT c_rss()/c_tss() INTO myres; 
return myres;
END |
DELIMITER ;

After creating all these SQL functions, R-Squared can be calculated by issuing the following command:

SELECT c_r_squared() AS 'R-Squared';

This produces the following output:

R-Squared
0.9760733246803284


G.  Correlation Coefficient

The Correlation Coefficient is designated in Statistics by the symbol R and this is for a good reason.  It means that if we have already the Coefficient of Determination, which is designated by R-Squared, we can readily derive R by just squaring the value of the R-Squared.  Thus, we can create the following function in SQL to get R:

DELIMITER |
CREATE FUNCTION c_r() RETURNS DOUBLE
BEGIN
DECLARE myres DOUBLE;
SELECT sqrt( c_r_squared() ) INTO myres; 
return myres;
END |
DELIMITER ;


After creating the c_r() function, we can get the Correlation Coefficient by issuing the command:

SELECT c_r() AS 'Correlation';

This produces the output:

Correlation
0.9879642448615398


H.  Calculating the F Statistic

The F Statistic is the difference between the regression mean square (RMS) and the error mean square (EMS).  Since the RMS is equal to the regression sum of square (RSS), we just need to create a function to derive the EMS as follows:

DELIMITER |
CREATE FUNCTION c_ems() RETURNS DOUBLE
BEGIN
DECLARE myres DOUBLE;
SELECT sum(power(y-(c_intercept()+c_slope()*x),2)) / (count(x)-2) INTO myres FROM simreg; 
return myres;
END |
DELIMITER ;

After this, the function that will create the F Statistic can be created as:


DELIMITER |
CREATE FUNCTION c_f_stat() RETURNS DOUBLE
BEGIN
DECLARE myres DOUBLE;
SELECT c_rss()/c_ems() INTO myres; 
return myres;
END |
DELIMITER ;

Then, the following command to calculate the F Statistic can be invoke:

SELECT c_f_stat() AS 'F Statistic';

This produces the following output;

F Statistic
122.38319782621953


I.  The Student's t Statistic

In a simple regression equation, the relation between t and F statistic is that the square of the t Statistic is equal to the F Statistic.  Therefore, if we got the F, the t can be derived by just getting the square root of F.  This is undertaken by the following function:

DELIMITER |
CREATE FUNCTION c_t_stat() RETURNS DOUBLE
BEGIN
DECLARE myres DOUBLE;
SELECT sqrt(c_rss()/c_ems()) INTO myres; 
return myres;
END |
DELIMITER ;

The Student's t Statistic can be calculated by issuing the following command:

SELECT c_t_stat() AS 't Statistic';

This produces the following output:

t Statistic
11.062693967846148


J.  Putting it all together

To put it all together, we can create the procedure:

DELIMITER |
CREATE PROCEDURE c_simple_regression()
BEGIN
SELECT c_intercept() as 'Intercept',c_slope() as 'Slope',c_t_stat() as 't Stat',c_r_squared() as 'R Squared',c_r() as 'Correlation', c_f_stat() as 'F Stat';
END |
DELIMITER ;

and the simple regression statistics can be calculated by issuing the command:

CALL c_simple_regression();

which produces the output:

InterceptSlopet StatR SquaredCorrelationF Stat
942.5391.911.0626930.9760730.987964122.383197


Note:

The above-mentioned procedure has been tested in MariaDB 10.3 database.  My guess is, it should also work with MySQL, PostgreSQL and other SQL databases with little modification and with some differences in precision mathematics.



Friday, February 22, 2019

Creating Self-Signed Certificates for the Apache Web Server

Use the OpenSSL package.  Issue the following commands in the Linux terminal:

# openssl req -new > ca.csr

# openssl rsa -in privkey.pem -out ca.key

# openssl x509 -in ca.csr -out ca.crt -req -signkey ca.key -days 720

These commands creates the SSL certificates good for 720 days with the files ca.csr, ca.crt, and ca.key.  Copy these files to the SSL directory of your Apache web server.  In my Linux system, this is located in /etc/apache2/ssl

# cp ca.* /etc/apache2/ssl

Then, restart the Apache webserver for the new certificates to take effect.

# service apache2 restart

Thursday, February 21, 2019

Mounting Remote SSH Filesystem

This is how to mount remote SSH (Secure Sockets Host) filesystem on your local directory (e.g., /home/clemrasul/remoteserv) on Linux.  Mounting remote directories in this way allows you to do server side programming with ease since source code can be edited using your favorite GUI text editor.  The text editor need not have the feature of being able to log on to an SSH server.  Here are the steps:

Step 1:  Install the sshfs software

On Ubuntu, this is done using the command apt-get.

# apt-get install sshfs


Step 2:  Place it in the Linux module and give permissions

# modprobe fuse
# adduser clemrasul fuse
# chown root:fuse /dev/fuse
# chmod +x /dev/fuse

This assumes a username of "clemrasul" that is added to the "fuse" group.


Step 3:  Create the directory where the remove SSH filesystem will be mounted

# cd /home/clemrasul
# mkdir ~/remoteserv

This assumes a remove directory name of "remoteserv".


Step 4:  Mount the remote SSH directory as follows:

# sshfs {fully qualified SSH username}:{default directory}  {local directory mount point}

Example:

# sshfs clemrasul@taocoven.com:/home/clemrasul/html ~/remoteserv

You will be prompted by the remote SSH server for password.  Once authenticated, the remote directory can be seen in the local directory as:

# cd /home/clemrasul/remoteserv/





Tuesday, November 28, 2017

Simple Sample Size Formula

I have often been asked how to determine sample size in Statistics, while I always referred to Cochran [1963:1] for a complete explanation and Yamane [1967:2] for a simpler version of the formula, I discovered (an eureka moment!) that the existing published formula for sample size can still be further simplified.  Here is my simple sample size formula (Rasul Formula):

          Sample Size (n) = 1 / e^2

          where e is the margin of error (sampling error)

This simplified formula assumes an infinite population (or universe) and slightly greater than 95% confidence level.  The input requirement is only the margin of error expressed as a percentage.  If we assume further a 5% (.05) margin of error, the formula will give us a magic value of 400 (Rasul Sample), which can be interpreted as the sample size given infinite population at slightly more than 95% confidence level with 5% margin of error.

If you do not want to compute and was asked as to what sample size of proportion, the answer is 400 samples.

This simple formula also yields a simpler way of calculating the margin of error (e) given an actual sample number as follows (Rasul Margin of Error Formula):

          Margin of Error (e) = (1/n)^(1/2)

          or

          Margin of Error (e) is the square root of 1/n.

Let us say, you were able to get only 300 samples and you want to know what is your margin of error (e), applying the derived formula above will give you:

          e = (1/300)^(0.5)

          e = (0.003333)^(0.5)

          e = 0.057773 (or 6% rounded off to the nearest integer percent)

This tells us that even if we plan for a 5% margin of error, in real life situation, actual field condition (like peace and order situation) may not allow us to get the required sample size.  This particular formula can easily aid us in calculating the margin of error given the actual sample gathered.



Derivation

For those interested on how the formula was derived, here it is:

a)  Cochran's sample formula for proportions given infinite population (universe) is stated as,

          Sample Size (n) = ( Z^2 * p *q ) / e^2

          where:

                   Z is the abscissa of area of the normal curve
                   p is estimated proportion of an attribute that is present in the population
                   q is (1 - p )
                   e is the margin of error

b)  Remember that the Z score is the number of standard deviations a given proportion is away from the mean.  Given that, the desired confidence level and Z score relationship are as follows:

          Confidence Level          Z score

                     90%                         1.65
                     95%                         1.96
                     99%                         2.58


c)  Assuming the more widely acceptable confidence level of 95% and borrowing from the idea of Taro Yamane of approximating the Z score of 95% confidence by rounding it off to 2 instead of using 1.96, and

d)  Assuming further a more conservative proportion (p) of 50% (This is often the assumed value if we do not know the given proportion, which is most likely).  Therefore, p * (1 - p ) = 0.5 * (1-0.5) yields the value of 0.25,

e)  The formula can now can be stated as:

          n = [ 2^2 * (0.25) ]/e^2

          n = [ 4 * 0.25 ]/e^2


     Thereby producing the more simpler formula of:

          n = 1/ e^2

       








--------------------
References

[1]  Cochran, W.G. 1963. Sampling Techniques, 2nd Edition, New York.  John Wiley and Sons, Inc.

[2]  Yamane, Taro. 1967.  Statistics: An Introductory Analysis, 2nd Edition,  New York.  Harper and Row.


Wednesday, September 16, 2015

How to extract the monthly report of an Apache log file

To extract the monthly report of an Apache log file, use the Linux sed command.  For example, to get the logs from July 1, 2015 to July 31, 2015, issue the command:

# sed -n '/1\/Jul\/2015/,/31\/Jul\/2015/ p' /opt/lamp/logs/access.log > Jul2015_log


Installing Webalizer on Ubuntu 14.04

Webalizer is a web-based log file viewer.  To install the software on Ubuntu 14.04, type:

# apt-get install webalizer 

This will install the software in default location. The configuration file is in /etc/webalizer and the default web pages will be created in /var/www/webalizer directory.

The command of the webalizer is:

#/usr/bin/webalizer

Edit the webalizer.conf in the /etc/webalizer directory to point to the Apache log file location (e.g., /var/log/apache2/access_log) and issue the command #/usr/bin/webalizer to create the log file HTML in /var/www/webalizer directory.

To execute the webalizer command at regular intervals, use the Linux's crontab command.

Friday, October 18, 2013

Authentication System Design Pattern

The following are PHP scripts that can serve as design pattern for an application authentication system.

This is the "login.php" file that serves as the HTML login form.


<?php
echo "
<center>
<form method='post' action='authenticate.php'>
<fieldset>
<legend> Login </legend>
<table border='0'>
<tr>
<td rowspan='3'><img src='../img/emblem-keys.png'></td>
<td>Username</td><td><input type='text' name='username'></td>
</tr>
<tr>
<td>Password</td><td><input type='password' name='wordpass'></td>
</tr>
<tr>
<td>   </td><td><input type='submit' value='Login'><input type='reset' value='Reset'</td>
</tr>
</table>
</fieldset>
</form>
";
?>


This is the "authenticate.php" file that is executed after the HTML login form.


<?php
session_start();
include_once('db_postgresql.inc.php');

$sql1 = "SELECT COUNT(*) AS numfound FROM webappuser WHERE username='{$_POST['username']}' AND wordpass='{$_POST['wordpass']}' AND access_level='1' AND record_state='1'";
$result1 = $con->query(''.$sql1.'');

// Login Logic
$my_array1 = $result1->fetch(PDO::FETCH_ASSOC);
if ( $my_array1 ['numfound'] < 1 ) // Login Failed
	{
	$delay = 0;
	$url = "unauthorized.php";
	echo "<meta http-equiv='REFRESH' content='$delay;url=$url'>";
	exit;
	}

// Get the login information from the user	
$sql2 = "SELECT username, wordpass, access_leve, record_state FROM webappuser WHERE username='{$_POST['username']}' AND wordpass='{$_POST['wordpass']}' AND access_level='1' AND record_state='1'";
$result2 = $con->query(''.$sql2.'');
$my_array2 = $result2->fetch(PDO::FETCH_ASSOC);

// Register authentication information in the session
$username = $my_array2['username'];
$wordpass = $my_array2['wordpass'];
$access_level = $my_array2['access_level'];
$_SESSION["u_id"] = $u_id;
$_SESSION["username"] = $username;
$_SESSION["wordpass"] = $wordpass; 
$_SESSION["access_level"] = $access_level;

// Go to the welcome page
$delay = 0;
$url = "welcome.php";
echo "<meta http-equiv='REFRESH' content='$delay;url=$url'>";
?>


This is the "unauthorized.php" file that is called by the authentication system if username and password does not match.


<?php
session_destroy();
echo "
<center>
<form method='post' action='authenticate.php'>
<fieldset>
<legend> Login </legend>
<table border='0'>
<tr>
<td rowspan='3'><img src='../img/emblem-keys.png'></td>
<td>Username</td><td><input type='text' name='username'></td>
</tr>
<tr>
<td>Password</td><td><input type='password' name='wordpass'></td>
</tr>
<tr>
<td>   </td><td><input type='submit' value='Login'><input type='reset' value='Reset'</td>
</tr>
</table>
</fieldset>
</form>
<br>
<font color='red'><blink><b>Unauthorized ...</b></blink></font>
</center>
";
?>


This is the "logout.php" file that is called when the user clicks on a logout button.


<?php
session_destroy();
echo "
<center>
<form method='post' action='authenticate.php'>
<fieldset>
<legend> Login </legend>
<table border='0'>
<tr>
<td rowspan='3'><img src='../img/emblem-keys.png'></td>
<td>Username</td><td><input type='text' name='username'></td>
</tr>
<tr>
<td>Password</td><td><input type='password' name='wordpass'></td>
</tr>
<tr>
<td>   </td><td><input type='submit' value='Login'><input type='reset' value='Reset'</td>
</tr>
</table>
</fieldset>
</form>
<br>
<font color='red'><blink><b>You have been logged out...</b></blink></font>
</center>
";
?>


This is the "db_postgresql.inc.php" database connection file that is included in PHP page whenever it needs to connect to the database. The assumption here is the application is connected to a PostgreSQL database system. You can change this to whatever database brands you prefer. Furthermore, the database named "mydb" will have a table named "webappuser" with a minimum of four fields, namely: (i) username, (ii) wordpass, (iii) access_level, (iv) record_state. In like manner, you can modify this to suit your needs.


<?php
$host = "localhost";
$user = "postgres";
$pw = "wordpass123";
$db = "mydb";
# Using pg PDO
# Connection Check
try {
    $con = new PDO('pgsql:host='.$host.';dbname='.$db.'', $user, $pw );
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    #echo "Database Status:  <font color='green'><blink><b>Connected...</b></blink></font><hr />";
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}
?>



This is the "secure.php" file that can be added at the top of any of the PHP file that you want protected from unauthorized users.


<?php
ini_set( "display_errors", 0);
session_start();
include_once( 'db_postgresql.inc.php' );
$username = $_SESSION["username"];
$wordpass = $_SESSION["wordpass"];

$sql1 = "SELECT COUNT(*) AS numfound FROM webappuser WHERE username='$username' AND wordpass='$wordpass' AND access_level='1' AND record_state='1'";
$result1 = $con->query(''.$sql1.'');
$my_array1 = $result1->fetch(PDO::FETCH_ASSOC);

// Login Logic
if ( $my_array1 ['numfound'] < 1 ) // Login Failed
	{
	$delay = 0;
	$url = "unauthorized.php";
	echo "<meta http-equiv='REFRESH' content='$delay;url=$url'>";	
	exit;
	}
?>