Call us: +1 (716) 989 6531 or email at:

Forecasting Software for sales, demand and call volumes

RSS RSS

Navigation





Search the wiki
»

PoweredBy

Web Services Tutorial with PHP4 and NuSoap for Time-Series Forecasting

RSS
Developers » Web Services » Here

Web Services Tutorial with PHP4 and NuSoap

Last revision: 2007-01-10


Target audience: developers, system administrators

In this tutorial, we will see how to use Lokad Web Services in a simple application written in PHP and using NuSoap (an open source Web Services toolkit for PHP). Lokad specializes in business time-series forecasting, but this document is neither an introduction to Lokad nor an introduction to Web Services.

Download: source-code for this tutorial

Requirements
(*) The Free subscription plan is sufficient to reproduce this tutorial, with the exception of the last section Retrieving forecasts which requires that the Enterprise plan be selected in your Lokad account.

Introduction

Web Services are an industrial-strength standard currently embraced by most (if not all) major software vendors. Lokad features Web Services: all operations that can be performed from the web application can also be performed programmatically through our Web Services. The Lokad Web Services can be reached at


In this tutorial, we will see how to use Lokad Web Services in a simple PHP application. First, we will see how to configure NuSphere editor to ease and speed up the creation of our web service client script. The NuSphere editor is a convenient tool but it's not a requirement, you can easily reproduce this tutorial with your favorite editor.

Project setup with NuSphere PhpEd 4.6

NuSphere PhpEd is a very convenient tool for creating PHP based applications. To see what methods Lokad Web Services expose, open the PhpEd editor and select the NuSoap Client tab in the bottom-right corner of the editor.

Bild

Right click on "Custom WSDL" as highlighted in the picture and choose "Add Custom WSDL" from the menu. You will see another dialog box as shown in the picture below.

Bild

Put a meaningful title for your web service in the Caption dropdown and the URL of the WSDL in the 2nd dropdown. You should use http://sandbox-ws.lokad.com/TimeSeries.asmx?wsdl as a test WSDL URL. You can replace it with the production version of web service WSDL(just replace sandbox by www). In either case, click on the OK button. You will see TimeSeries appear under Custom WSDL as shown below. Expand TimeSeries to see a list of the methods exposed by the Lokad Web Service.

Bild

Right click on TimeSeries and select "Copy" in the dropdown menu. Open a new PHP file in your editor and paste into it. You will see that this creates basic boilerplate code to access the web service.

require_once('lib/nusoap.php');
$wsdlURL = 'http://sandbox-ws.lokad.com/TimeSeries.asmx?wsdl';
$soap = new soapclient($wsdlURL, 'wsdl');

Web Services Authentication

Lokad Web Services are authenticated, which means that you have to provide the username and password associated with your Lokad Web Account to access our Web Services. Technically, Lokad relies on SOAP headers to authenticate a Web Method call. The code provided below illustrates how you can check that your call is correctly authenticated.

$username = 'mail@example.com';
$password = 'mypassword';

// adds authentication to a SOAP client
// returns true if the authentication was successful
function addAuthentication($soap, $username, $password)
{
    // username and password are added in an AuthHeader
    $soap->setHeaders("<AuthHeader xmlns=\"lokad.com/ws\">
                           <UserName>$username</UserName>
                           <Password>$password</Password>
                       </AuthHeader>");

    // we check if the authentication was successful
    $result = $soap->call('IsAuthenticated');
    if ($error = $soap->getError()) die($error);
    return ($result["IsAuthenticatedResult"] == 'true');
}
addAuthentication($soap, $username, $password);

The call to addAuthentication should return true, provided that you have entered a valid username and password.

Time-series management

Lokad specializes in time-series forecasting. Before actually performing a forecast, you first need to upload your data; and this can be easily achieved with our Web Services. Technically, a time-series is simply a named array of time-value pairs. Let's see how a time-series can be generated programmatically.

function makeRandomTimeSerie ($name, $length = 10,
                              $unitName = "", $utcOffset = 0)
{
    $timeValues = array();
    for ($i = 0; $i < $length; $i++)
    {
        $time = mktime(0, 0, 0, date("m"), date("d") + $i, date("Y"));
        $value  = rand();
        $timeValues["TimeValue"][$i] = makeTimeValue($time, $value);
    }

    $timeSerie = array(
        "Name" => $name,
        "UnitName" => $unitName,
        "UtcOffset" => $utcOffset,
        "TimeValues"=> $timeValues
    );
    return $timeSerie;
}

function makeTimeValue ($timestamp, $value)
{
    return array('Time' => date('Y-m-d\TH:i:s', $timestamp),
                 'Value' => $value);
}

The function makeRandomTimeSerie creates a time-series named $name. Note that we specify a UtcOffset in the example above; this value is expressed in hours according to the formula local time = UTC time + offset. Once the time-series is defined, $length time-value pairs are added. In our sample, for simplicity, the values are regularly spaced (one day increment for each value) but this is not a requirement. The intervals between the successive values can vary arbitrarily.

Naming conventions: although the word serie (singular) does not exist in English, we have found it quite convenient to distinguish serie (singular) from series (plural) in the source code . So, when the term serie is used in our examples, it's not a mistake, it's intentional.

The makeRandomTimeSerie method provides a time-series instance. Let's add this time-series to your Lokad account.

$timeSerie = makeRandomTimeSerie('TestSerie');
$parameters = array();
$parameters['parameters']['serie'] = $timeSerie;
$result = $soap->call('AddSerie', $parameters);

To delete a time-series from your account, you just need to specify the name identifier of the time-series in question. You can also retrieve the names of the existing time-series in your account; the following snippet outputs the names of the time-series in your account.

$result = $soap->call('GetAllSerieNames');
if ($error = $soap->getError()) die($error);
// format and display the result
$series = toArray($result['GetAllSerieNamesResult']['string']);
echo "Here is the list of your time-series:\n";
echo "<ul>";
foreach ($series as $key => $name)
    echo "<li>" . $name . "</li>";
echo "</ul>\n";

function toArray ($data)
{
if ($data == "")
    return array();
else if (is_string($data))
    return array($data);
else
    return $data;
}

You will notice that we are forcing $result to be an array. If there are multiple time series in your account, the method call will return an array of names, otherwise it will return a single string. Forecasting task management

Before you can retrieve a time-series forecast, you need to define a forecasting task that will specify how the forecast time-series should be computed. In the Lokad data model, a forecasting task is always associated with a particular time-series; several forecasting tasks can be associated with the same time-series.

function makeTask ($name, $aggregator = "Sum", $period = "Day",
                   $pastPeriods = 10, $futurePeriods = 5,
                   $periodStart = "2001-01-01T00:00:00")
{
    $task = array(
        "Name" => $name,
        "Aggregator" => $aggregator,
        "Period" => $period,
        "PastPeriods" => $pastPeriods,
        "FuturePeriods" => $futurePeriods,
        "PeriodStart" => $periodStart
    );
    return $task;
}

Tip: the time-series names should be unique within the scope of your Lokad account (you cannot have two distinct time-series identified by the same name). However, the names of the forecasting tasks only need to be unique within the scope of their base time-series. In other words, you can have several forecasting tasks identified by the same name but associated with different time-series.

Now we add the task.

$parameters = array();
$parameters['parameters']['serieName'] = $serieName;
$parameters['parameters']['task'] = makeTask('TestTask');
$result = $soap->call('AddTask', $parameters);
if($error = $soap->getError()) die($error);

$result will return true if the task is added successfully and false otherwise.

Retrieving forecasts

To retrieve your forecasts through our Web Services, you need to activate the Enterprise subscription plan in your Lokad account. Note that you won't be charged upfront, but only at the end of each 30-day period (if you decide to continue with your subscription).

The following code will retrieve the forecasts for the task previously created.

$parameters['parameters']['serieName'] = 'TestSerie';
$parameters['parameters']['taskName'] = 'TestTask';
$result = $soap->call('GetForecast', $parameters);
if($error = $soap->getError()){ die($error);}
$forecasts = toArray(
    $result['GetForecastResult']['TimeValues']['TimeValue']);
echo "<p>Here is the forecast for this task:</p>\n";
echo "<table>";
foreach ($forecasts as $key => $timeValue)
    echo "<tr><td>" . $timeValue['!Time'] . "</td>
              <td>" . $timeValue['!Value'] . "</td></tr>";
echo "</table>\n";

$forecastResult=$result["GetForecastResult"]["TimeValue"];
if(is_array($forecastResult))
{
  for($i=0;$i < count($forecastResult);$i++)
  {
      echo("<br>Time: ".$forecastResult[$i]["!Time"]);
      echo("<br>Value: ".$forecastResult[$i]["!Value"]);
  }
}
Google Code

All add-ons developed by Lokad have been released as open source under the BSD license on Google Code.

The BSD license is compatible with closed-source commercial applications. Integrating a forecasting technology has never been easier.

What people say

From a developer standpoint, we found that the Lokad API was very well documented and easy to use. The Lokad team was also extremely responsive to any questions we had. Most importantly, we were able to develop a Lokad plugin for our data browser in very short order. Jeff Engel, Kirix Corporation