Introduction

The incredible factory 4.0 [1] growing trend, offer to the new and old systems a new opportunity to take advantage of every data produced directly and indirectly.

Due to quantity, quality and availability of these data, specially the family of machine learning and data mining algorithms are able to add a new value to these. Because of this, the companies are using 4.0 tech will have great benefits in the near future.

While investments in artificial intelligence is increasing, the demand for AI developers not as much. The AI industry is shifting rapidly into a technology that is cutting developers and engineers. Many companies choose to use existing products, services and libraries to fulfill their AI needs from the tech giants like Amazon, Google and so on.
But is it always the best choice?

In my opinion, sometimes this is not necessarily the case.
There are many opportunities where the custom development of an AI solution can bring great benefits especially when the use cases targeting different niches. The pre-made tools available on the market are not specialized on very specific problems.

I believe that in all those cases where (artificial) intelligence represents one of the basic and main aspects of a software product or one of its useful features, the custom development of these should be taken into consideration.
Well, there are a lot of examples where this is already in place, since intelligent behaviour is required as heart of the product: cleaning robots, the assembly line robots and many logistics applications are perfect use cases.
Anyway, artificial intelligence can be increasingly grafted to a low level of product development phase in the near future for a growing number of companies. But how do that ?

Event driven domains are widely used and are ideal for incorporating directly AI at model design level.

On this post, I’ll emphasize and illustrate Event Sourcing and Artificial Intelligence algorithms combo in a domain layer example [2].

Event data are used to feed intelligent systems (classifiers) and statistical algorithms. These add some “smart” properties to objects themself.
A transport truck, in addition to the usual properties, has some representations of probabilities or predictions.
Thanks to the integration of intelligent algorithms at domain level, objects will be able to use these smart properties during interactions with business rules.

All the concepts discussed here are based on the codebase available at the following url: https://github.com/sandhaka/SmartDomainsCaseStudy

An import/export company has to manage a fleet of trucks committed to carry the goods through a semplified map.

Working with Event Sourced aggregate

“Capture all changes to an application state as a sequence of events.”
[M.Fowler]

If you aren’t already familiar with this, Event Surcing means refer to an object not by his state but by his collection of changes processed along his whole lifetime [3]. Only these events are going to be stored, the state at desired time will be compute at runtime every time is needed by a special repository.

As a bank account is not a plain table with a balance amount at the current reading time, every truck of the fleet may be seen as a list of events about departures and arrivals.
Besides these events many metrics describes how the truck and the driver have tackled the journey.

Our demo domain

The truck object has some properties like a model code, the current location and some metrics about the current state. For example, the decimal value: AverageFatigueLastWeek describes how much the driver has been stressed in the last week.

On Departure event nothing is updated because metrics are collected at the end of the journey.

Moreover the aggregate can be saved or loaded as a stream of events (implemented in the codebase with a in-memory store).

All the Domain Events represents the truck object. Surprisingly they can feed also a ML algorithm. This can learn by all these metrics about every truck-driver pair behavior.

A Naive Bayes network classifier estimate a probability to have an accident during the next journey.

Smart object properties

Naive Bayes [4] classifiers are a family of simple “probabilistic classifiers” based on applying Bayes’ theorem with strong independence assumptions between the features.

The implementation of IWiseActor interface of the domain layer allow us to exploit these capabilities and predict a future probabilistic incidence to have an accident by current driver fatigue metrics, weather condition, historical statistics and so on.

Wise Actor infrastructure implementation

The Update method, add or update the truck statistical model.

The learner variable is a third party Naive Bayes implementation.

Actually, the proposed code base is a bit huge as example although the domain is just a toy, all the structures needed to implement a tiny versions of event sourcing aggregate with AI capabilities are many.

After fleet creation (a collection of TransportTruck objects), a routine populate the events list of each truck by some data previously defined. These metrics, describes all the past trucks journeys,

I used xUnit to run some example easily, in the unit-test project: TransportFleet.UseCase, the method ChooseTruckCandidateWithLowerAccidentProbability do all the things needed to demonstrate all the above-mentioned.

Adding these events as domain events to initialize the fleet state.
The interesting part is the following, the PredictAccident method is embedded in the domain aggregate as a normal method.

You can run this test from the test project folder with:

And you’ll get the ouptut:

The domain is semplified and the prediction is quite banal, I’m using only some metrics to make the accident prediction, but the code is complete and useful to build much more complex use cases.

More AI, Constraint satisfaction

The ML use case based on Naive Bayes showed above is a very common scenario.

Constraint Satisfaction Problem is another well known mathematical model used in artificial intelligence and operation research to auto-resolve optimization dilemma [5].
Our implementation is based on the “backtracking” concept, where an algorithm abandons candidate values when these cannot fit with a solution for the given problem.

In the example we need to organize three travels for each week day, (monday to saturday) automatically using a six trucks fleet.
This example is more elaborated.
First, a representation of the domain objects is created and then it’s processed directly by a generic resolution algorithm.
The most interesting point is the possibility to insert one or more constraints without worrying too much if a solution exists. The algorithm will find the solution that satisfies the request or one of the closest possible configurations.

To understand completely the code above, you probably need to look at the proposed CSP resolver implementation.

Anyway, CSP problem is another good candidate to be directly included in or close to an enterprise domain layer.

Run test as:

Planning is done with no overlapping between days.

If you want to add a new constrains is straightforward !
For example, I want to ensure that no trucks makes two consecutive trips on monday and tuesday, because is too stressful as example…

Then, adding the following constraint ensure this:

The result will change automatically in this way:

Note that no truck that traveled on Monday did so on Tuesday and vice versa.

It’s a truly useful system to dynamically change a complex scenario when a I need to optimize resources assignment based on properties, constraints and so on.

Software Craftsman @ Blazar Group SA