Towards Logic Programming as a Service: Experiments in tuProlog Roberta Calegari, Enrico Denti, Stefano Mariani, Andrea Omicini Dipartimento di Informatica, Scienza e Ingegneria (DISI) A LMA M ATER S TUDIORUM–Università di Bologna Email: {roberta.calegari, enrico.denti, s.mariani, andrea.omicini}@unibo.it Abstract—In this paper we explore the perspective of Logic are known to impact on the modelling of complex, hetero- Programming as a Service (LPaaS), with a broad notion of “ser- geneous systems as multi-agent systems (MAS) [2]—also vice” going beyond the mere handling of the logic engine lifecycle, suggesting that their actual vocation should rightfully include knowledge base management, reasoning queries execution, etc. In supporting scalable, configurable, intelligent infrastructures for particular, we present tuProlog as-a-service, a Prolog engine based Internet-based applications. on the tuProlog core made available as an encapsulated service to effectively support the spreading of intelligence in pervasive The tuProlog [3] engine, deployed as a Java JAR or systems—mainly, Internet-of-Things (IoT) application scenarios. Microsoft .NET DLL, is inherently easily deployable and So, after recalling the main features of tuProlog technology, exploitable by other applications as a library service—that is, we discuss the design and implementation of tuProlog as-a-service, from a software engineering standpoint, a suitably encapsu- focussing in particular on the iOS platform because of the many lated set of related functionalities. However, this might not be supported smart devices (phones, watches, etc.), the URL-based enough in complex IoT scenarios, where the mobility/cloud communication support among apps, and the multi-language ecosystem aims at delivering infrastructure, platforms, and resulting scenarios. software as a service – according to a more Service Oriented Architecture (SOA) interpretation of the term “service” –, I. I NTRODUCTION enabling people to benefit from ubiquitous information access. Emphasis is more and more on on-demand applications, where Today applications are more and more pervasive and intel- the enabling infrastructure – servers, storage, networks, and ligent, calling for situated intelligence—light-weight, effective client devices – moves towards cloud computing. Service- intelligence chunks placed where and when needed to locally oriented computing also promotes the idea of assembling tackle the specific reasoning needs in complex distributed application components into a network of services that can be systems. This is particularly true in the fast-growing field of loosely coupled to create flexible, dynamic business processes the Internet-of-Things (IoT), where connectivity and interoper- and agile applications spanning organisations and computing ability are just the basic steps towards higher-level, customised, platforms. variously-situated services. In the remainder of the paper, after recalling the main The complexity of IoT system engineering calls for suit- features of the tuProlog technology, we outline the general able, easily deployable infrastructures, meant to make the architecture for Logic Programming as a Service (LPaaS) – designers’ and developers’ task easier by providing commonly- without limiting ourselves to the case where “as a service” required services to applications. Such infrastructures should means “as a Web/Cloud Service” – aimed at fully managing the (i) be both statically and dynamically (easily) configurable, Prolog engine lifecycle (either dedicated or not to a given client so as to match the application needs; (ii) govern components application), the knowledge base management, and the query and applications interaction; (iii) encapsulate intelligence in execution. Then, we focus on the tuProlog case, taking iOS suitable forms for applications’ exploitation. as our experimental platform – where the actual instantiation of the as-a-service paradigm is much closer to a SOA-/Cloud- In this scenario, where software engineering, programming oriented interpretation – and discuss some simple application languages, and distributed artificial intelligence meet, logic- examples. based languages have the potential to play a prominent role both as intelligence providers and technology integrators. II. tuP ROLOG IN A NUTSHELL For the former, typical LP features – such as programs as logic theories, computation as deduction, and programming tuProlog [3] is an open-source, light-weight Prolog frame- with relations and inference – make logic languages a natural work for distributed applications and infrastructures, released choice for building intelligent components. In the context of under the LGPL license [4]. Unlike most Prolog programming IoT, this also implies that logic-based technologies should be environments – such as [5], [6], which are typically very implemented taking strongly into account specific engineering efficient but also monolithic and thought to operate as stand- criteria such as deployability, scalability, and interoperability. alone systems –, tuProlog is intentionally designed to be minimal, dynamically configurable, easily deployable, inter- For the latter, logic languages already proved to be effec- operable, but above all multi-paradigm – promoting seamless tive as both communication and coordination languages [1], integration of the logic/declarative paradigm, on the one side, whereas, more generally, declarative models and technologies with the object-oriented imperative paradigm, on the other 79 Fig. 1. Overview of the 2PaaS architecture – and multi-language—enabling Prolog to inter-operate with operability standards such as TCP/IP, RMI, and CORBA, and Java (and viceversa) easily and directly, with no need for is exploited as the enabling technology inside the TuCSoN special pre-declarations, static stub files, etc. [7]. Over the coordination infrastructure [10], [11], which provides logic- years, tuProlog has grown to become also multi-platform, based, programmable tuple spaces – tuple centres [12] – as from Microsoft .NET to Android and Apple iOS [8]. So, coordination media for distributed processes and agents. besides Java, the object-oriented side now covers potentially any language on the .NET platform; other languages, like the III. L OGIC P ROGRAMMING AS A S ERVICE newborn Apple Swift [9], are also being included. Coherently with the view outlined above, this paper looks Minimality means that the tuProlog core contains only the forward to the idea of providing Logic Programming as a Prolog engine essentials – roughly speaking, the reasoning Service (LPaaS), conceptually situated inside the Software as a engine and the required basic mechanisms – whereas any other Service layer of, e.g., a typical Cloud-based environment. Nev- feature is implemented via libraries: users can configure their ertheless, the first step to achieve such a goal is to carefully de- system by dynamically loading/unloading libraries at any time. sign the architecture of a logic programming engine according to the general software engineering principles of modularity, Each library provides a package of related predicates, encapsulation, and reusability. The architecture would provide functors, and operators; new libraries can also be easily the conceptual foundation for the “as a service” paradigm in developed, either in Prolog or in Java/.NET language (or a the context of heterogeneous computational environments— hybrid mix of the two) as a suitable Java/.NET class, extending e.g., as a RESTful Web Service, as a Cloud-hosted app, etc. the tuProlog Library class and following simple naming conventions. Library-defined predicates, functors and operators In the LPaaS context, according to the broad acceptation of are indistinguishable from tuProlog built-ins—actually, most term “service” described in Section I, the basic functionality to of the perceived built-ins are actually provided by some pre- be provided is the ability to reason over logic theories, which loaded library. translates into the ability to submit queries and retrieve results; related functionalities include the creation and configuration of Easy deployability means that, generally speaking, in- the reasoner (the logic engine) with the proper knowledge base. stalling is just a matter of making the JAR archive/.NET The interface is then supposed to define the API to provide assembly available in the desired location: the only exception such functionalities, namely: is when the hosting platform imposes its install procedure, as in the case of Android/iOS app (for which going through the • create engine: to instantiate a dedicated engine; Android/iOS installer is mandatory). • reset engine: to reset the engine to the initial state and In addition, tuProlog is compatible with major inter- possibly the empty knowledge base; 80 Fig. 2. The derivative application scenario: the symbolic derivative query (left) and result (right) on iPhoner and iWatchr . • set theory: to load the knowledge base into the engine; • create engine: for convenience, this functionality is just embedded in the first call to the service; • query: to submit queries and retrieve (possibly multi- ple) results. • reset engine: mapped onto the reset primitive; Further degrees of freedom include whether multiple engines • set theory: mapped onto the theory primitive; could be allowed, whether a given engine should/should not • query: mapped onto a set of primitives, namely be reserved to a given client application, etc. query to issue the query, result and solution If the Prolog language is adopted, such functionalities have to retrieve the query result, and nextSol to explore to be tailored to the Prolog-specific behaviour, assumptions, further solutions. and syntax, and APIs have to be mapped onto suitable Prolog predicates. In the next section we specialise our approach to A nice peculiarity of the iOS platform, which is one of the specific case of the tuProlog system, which provides not the main reasons to choose it in our experiments, is the only a light-weight Prolog engine particularly featured for this built-in URL scheme functionality, which provides a simple kind of applications, but also a multi-paradigm and multi- and effective way for applications’ inter-communication via language working environment, thus paving the way towards a user-defined, URL-based protocol. In short, all is needed further forms of interaction and expressiveness. to communicate with an app is to create an appropriately- formatted URL and ask the system to open it; on the opposite Among the different platforms supported by tuProlog, in side, the custom scheme needs to be declared and properly this paper we take the iOS platform as our reference (a) implemented—see Fig. 1. because of its adoption in pervasive contexts, (b) for the availability of several sorts of smart devices (phones, watches, In the tuProlog case, two custom URL schemes need to etc.) that constitute a challenging testbed, and (c) for its be defined—one for incoming requests, to be processed by the architectural similarity with more specific SOA/Cloud-oriented tuProlog Mobile App and encoding the above API; and another notions of “as a service”. for the query results, to be processed by the client app. The tuProlog app implements the following URL scheme: IV. tuP ROLOG AS A S ERVICE ON I OS tuPrologMobile://?src=srcURL& command=argument& As a challenging application context for LPaaS, here we dst=dstURL focus on the development of the tuProlog service for iOS, for both Objective-C and Swift applications. The service is where: embedded in a tuProlog app, acting as the service provider for all other applications running on the mobile device. Its API • srcURL is the client URL scheme: as a result, a obviously adheres to the above-presented API, tailored to the new Prolog engine is created in tuProlog Mobile and Prolog syntax plus some convenience mechanisms—namely: associated with that client; 81 • command is one of theory, query, nextSol, reset, with argument respectively being theory (the Prolog theory to be set in the engine, or the link where to donwload it1 ), query (the text of the query), nextSol, reset; • dstURL is the URL scheme of the client to which the result must be sent, possibly different from srcURL; if null, the result is shown in tuProlog app console. On the other hand, the query result returned by the tuProlog service is encoded by the following URL scheme: dstURL://command=commandresult where • dstURL is the URL scheme of the client receiving the result; • command is one of the below four (result, solution, nextSol, reset), with the respective commandresult. The specific syntax of commandresult varies with command , namely: dstURL://?result=result& engine=engineVersion& Fig. 3. The multi-language toy example: Swift app using Java entities engineAge=engineAge dstURL://?solution=solution& V. A PPLICATION SCENARIOS engine=engineVersion& Fig. 2 shows one first, typical application scenario: the engineAge=engineAge client is a Swift/Objective-C application that provides a GUI dstURL://?nextSol=nextSolution& for the computation of the symbolic derivative, while the engine=engineVersion symbolic computation is delegated to the tuProlog service. The Apple Watch extension (WatchKit) is also supported, so dstURL://?reset=OK as to replicate the client GUI on the the iWatchr (which, in principle, could also play a more active role). where From the user’s side, the first step is to create a dedicated • result is either Yes or No for success or failure, Prolog engine, loaded with the proper logic theory: respectively; tuPrologMobile://?src=tuPrologMobileClient& theory=dExpr(T,DT) :- dTerm(T,DT). • engineVersion is the version of the tuProlog system; dExpr(E+T,[DE+DT]) :- dExpr(E,DE), dTerm(T,DT). dExpr(E-T,[DE-DT]) :- dExpr(E,DE), dTerm(T,DT). • engineAge can be new or still for a dedicated or dTerm(F,DF) :- dFactor(F,DF). dTerm(T*F,[[DT*F]+[T*DF]]) :- dTerm(T,DT), dFactor(F,DF). cached engine, respectively; dTerm(T/F,[[F*DT]-[T*DF]]/[F*F]) :- dTerm(T,DT), dFactor(F,DF). dFactor(x,1). • solution is the solution of the query; dFactor(N,0) :- number(N). dFactor([E],DE) :- dExpr(E,DE). • nextSolution is the next solution of the query; dFactor(-E,-DE) :- dExpr(E,DE). dFactor(sin(E), [cos(E)*DE] ) :- dExpr(E,DE). • error contains potential errors. dFactor(cos(E), [-sin(E)*DE] ) :- dExpr(E,DE). Such a URL scheme is a first step towards a more SOA/Cloud- The engine can now be queried via the top-level predicate oriented interpretation of the LPaaS paradigm, with respect dExpr(+function, ?derivative). For instance, the request to to the more general notion envisioned for tuProlog—where, derive the cos x · sin x function translates into the URL: essentially, “as a service” is interpreted according to the tuPrologMobile://?src=myTuPrologMobileClient& general software engineering principles of modularity, encap- query=dExpr(cos(x)*sin(x), D).&dst=myTuPrologMobileClient sulation, and reusability. In fact, making LPaaS available on a Web Server, a Cloud infrastructure, or other communication whose answer, − sin2 x + cos2 x, is returned (in a non- protocols adopted in IoT scenarios is just a matter of designing simplified form) as the URL: and deploying a suitable wrapper API, translating e.g. RESTful tuPrologMobileClient://?solution=yes. requests to the appropriate library method calls. D / [’+’([’*’([’*’(’-’(sin(x)),1)],sin(x))], [’*’(cos(x),[’*’(cos(x),1)])])] dExpr(’*’(cos(x),sin(x)), 1 To be supported in the next release. [’+’([’*’([’*’(’-’(sin(x)),1)],sin(x))], 82 [’*’(cos(x),[’*’(cos(x),1)])])]) to the MAS and to perform the required reasoning, yet, in a &errors=&engine=2p Mobile - 3.0 beta &engineAge=still more realistic scenario, some supposedly-smart devices could be not powerful enough to actually hold the computation This URL encodes both the variable binding and the whole locally—or, it could be impractical to do so because of the solution: in particular, the Prolog variable D, which contains complexity of the required configuration. On the other hand, the computed derivative, results when enough computational power is available on the devices, the need for situatedness (along with the software engineering D / [’+’([’*’([’*’(’-’(sin(x)),1)], sin(x))], principles of locality and encapsulation) could instead suggest [’*’(cos(x), [’*’(cos(x),1)])]) ] to compute directly on the Home Manager devices by querying Technically, the client app, written in Objective-C, triggers situated Prolog engines reasoning on locally-available data. the iOS service based on the provided URL, while on the In the overall, Home Manager – and, more generally, the other side the server app, written in Java, parses the command, smart home scenario – clearly shows how LPaaS could be an creates the Prolog engine, performs the required activity and effective way to tackle multiple different aspects – from de- returns the result. ployment to maintenance, cost issues, hardware requirements, More complex scenarios in a multi-language and multi- etc. – while efficiently spreading intelligence where and when platform perspective could exploit tuProlog multi-paradigm needed in pervasive contexts. programming support (OOLibrary) in a broader sense, with Swift or Objective-C apps interacting with Java entities. Fig. 3, VI. R ELATED W ORK for instance, shows a toy Swift app which creates Java objects, calls some methods, and elaborates the (Java) result back in Many Prolog systems offer some form of support for Swift. the HTTP protocol and for the exploitation of Prolog as a service. The (Semantic) Web is one of the most promising More precisely, as detailed in the following code, a Java application areas for SWI-Prolog [15]. Prolog handles the string with the “member(X, [a,d]).” text is first bound to semantic web Resource Description Framework (RDF) model the Prolog variable Q, then a Java Prolog engine is bound to naturally, where RDF provides a stable model for knowledge the Prolog variable P and used to solve the query Q, binding the representation with shared semantics. The PiLLoW library result to the Prolog variable S; this result is finally converted (Programming in Logic Languages on the Web) [16], devel- back to a Java string via toString, binding the final result oped in Ciao Prolog and available for Ciao [17], SWI-Prolog, (yes in this case) to the Prolog variable SOL. SICStus [5] Prolog, and YAP, is one of the most widely known tuprologmobile://?src=null&query= examples: a comparison between PiLLoW and SWI-Prolog for new_object(’java.lang.String’, [’member(X, [a,d]).’], Q), new_object(’alice.tuprolog.Prolog’, [], P), HTML documents handling can be found in [18]. P <- solve(Q) returns S, S toString returns SOL&dst=null Logic programming has also been used for the composition of Semantic Web Services: in [19], for instance, the GOLOG As shown in Fig. 3, the result is exploited by the client Swift language [20] is extended for this purpose through the pro- application for its own purposes–here, trivially, just to print it vision of high-level generic procedures and customising con- in its console. straints. Finally, ProWeb [21] is an ALP-Prolog library aimed at embedded HTTP servers for controlling appliances: there, In a wider perspective, this approach fits particularly well the notion of Request Processing Modules (RPM) supports those pervasive application scenarios where intelligence needs different protocols, including HTTP, to support remote access. to be spread onto a broad set of heterogeneous devices, yet the choice of where logic computation should actually take While PiLLoW is an add-on library, aimed at directly place depends on many conditions—such as the available handling HTTP, CGI and other internet protocols, tuProlog computational power, the available bandwidth, the instability does not provide such services directly: rather, its modular of the connection, the need for situatedness. and Java-based architecture makes it easy both to embed it in other applications, and, more generally, exploit it as a In the IoT context, for instance, the Home Manager project service through its API. Other features, if necessary, could be [13] aims at supporting the construction of Socio-Technical developed in the form of suitable tuProlog libraries and loaded Smart Spaces (STSS), namely in the case of a smart home by need—for instance, as in the case of the RDF library [22]. and the surrounding environment where users live, according to the Butlers architectural vision [14]. There, a variety of smart devices, appliances, sensors, etc. need to be properly integrated VII. C ONCLUSION and coordinated so as to provide advanced services to the home Pervasive and situated systems of any sort are increas- users, immersed in the smart space. To this end, the house ingly demanding intelligence to be scattered throughout the is seen as a multi-agent system (MAS), coordinated via the computational devices populating the physical environment— TuCSoN middleware [11], [10]: smart appliances participate as clearly demonstrated by IoT scenarios like smart homes, to the agent society by means of an agent, which embeds the personal healthcare assistants, energy grids, etc. To meet such device intelligence, while the social intelligence (with related a requirement, light-weight logic programming engines are a policies, global goals, etc.) is implemented on top of TuCSoN crucial need, aimed at providing the reasoning services on- tuple centres [12]. demand to the most heterogeneous client applications. In its While Home Manager devices are supposed to be equipped turn, this requires the logic engine to be modular, multi- with enough computational power to support their participation platform, and multi-language—as tuProlog is. 83 Then, making available such a logic programming ser- [7] E. Denti, A. Omicini, and A. Ricci, “Multi-paradigm Java- vice according to the different application needs, onto het- Prolog integration in tuProlog,” Science of Computer Programming, erogeneous infrastructures, and across different interaction vol. 57, no. 2, pp. 217–250, Aug. 2005. [Online]. Available: http://www.sciencedirect.com/science/article/pii/S0167642305000158 paradigms is a matter of designing suitable wrapper interfaces [8] E. Denti, A. Omicini, and R. Calegari, “tuProlog: Making Prolog around the tuProlog service API—as we have done with the ubiquitous,” ALP Newsletter, Oct. 2013. [Online]. Available: http: iOS platform. Accordingly, future work is devoted to further //www.cs.nmsu.edu/ALP/2013/10/tuprolog-making-prolog-ubiquitous/ extend the reach of the LPaaS paradigm considering both [9] Apple Inc., The Swift Programming Language (Swift 2.2 Edition), Jun. traditional SOA infrastructures – e.g., tuProlog as a RESTful 2014. web service – and pervasive deployment scenarios from the [10] A. Omicini and F. Zambonelli, “Coordination for Internet application IoT landscape—e.g., making tuProlog available over Bluetooth development,” Autonomous Agents and Multi-Agent Systems, vol. 2, Low Energy connections. no. 3, pp. 251–269, Sep. 1999, Special Issue: Coordination Mechanisms for Web Agents. [Online]. Available: http://link.springer.com/10.1023/ Also, building a specialised tuProlog-oriented middleware, A:1010060322135 dealing with heterogeneous platforms, as well as with distri- [11] TuCSoN, “Home page,” http://tucson.unibo.it, A LMA M ATER S TUDIO - RUM –Università di Bologna. bution, life-cycle, interoperation, and coordination of multiple, [12] A. Omicini and E. Denti, “From tuple spaces to tuple centres,” situated Prolog engines – possibly based onto the existing Science of Computer Programming, vol. 41, no. 3, pp. 277–294, TuCSoN middleware – is a goal for our future research, aimed Nov. 2001. [Online]. Available: http://www.sciencedirect.com/science/ at exploring the full potential of logic-based technologies in article/pii/S0167642301000119 the context of IoT scenarios and applications. [13] Home Manager, “Home Page,” https://apice.unibo.it/xwiki/bin/view/ Products/HomeManager, A LMA M ATER S TUDIORUM–Università di Bologna. ACKNOWLEDGEMENTS [14] E. Denti, “Novel pervasive scenarios for home management: the Authors would like to thank Dipl. Eng. Alberto Sita for his butlers architecture,” SpringerPlus, vol. 3, no. 52, pp. 1–30, January contribution to this project and his work to the new prototype 2014. [Online]. Available: http://www.springerplus.com/content/3/1/52/ abstract of the iOS tuProlog app. Also, we would like to thank Asia [15] SWI-Prolog, “Home page,” http://www.swi-prolog.org. Mariani for her help in fixing the last version of the paper. [16] D. Cabeza and M. V. Hermenegildo, “Distributed WWW programming using (Ciao-) Prolog and the PilloW library,” R EFERENCES Theory and Practice of Logic Programming, vol. 1, no. 3, pp. 251–282, May 2001. [Online]. Available: [1] E. Denti and A. Omicini, “Engineering multi-agent systems in LuCe,” http://journals.cambridge.org/action/displayAbstract?aid=77729 in ICLP’99 International Workshop on Multi-Agent Systems in Logic Programming (MAS’99), S. Rochefort, F. Sadri, and F. Toni, Eds., Las [17] Ciao, “Home page,” http://ciao-lang.org. Cruces, NM, USA, 30 Nov. 1999. [18] J. Wielemaker, Z. Huang, and L. Van Der Meij, “SWI-Prolog [2] A. Omicini and F. Zambonelli, “MAS as complex systems: A view on and the Web,” Theory and Practice of Logic Programming, the role of declarative approaches,” in Declarative Agent Languages vol. 8, no. 3, pp. 363–392, May 2008. [Online]. Available: and Technologies, ser. Lecture Notes in Computer Science, J. A. Leite, http://journals.cambridge.org/article S1471068407003237 A. Omicini, L. Sterling, and P. Torroni, Eds. Springer, May 2004, vol. [19] S. Mcilraith and T. C. Son, “Adapting GOLOG for composition of 2990, pp. 1–17, 1st International Workshop (DALT 2003), Melbourne, Semantic Web Services,” in 8th International Conference on Principles Australia, 15 Jul. 2003. Revised Selected and Invited Papers. [Online]. and Knowledge Representation and Reasoning (KR-02), D. Fensel, Available: http://link.springer.com/10.1007/978-3-540-25932-9 1 F. Giunchiglia, D. L. McGuinness, and M.-A. Williams, Eds. Morgan [3] E. Denti, A. Omicini, and A. Ricci, “tuProlog: A light-weight Kaufmann, 22–25 Apr. 2002, pp. 482–493. Prolog for Internet applications and infrastructures,” in Practical [20] H. J. Levesque, R. Reiter, Y. Lespérance, F. Lin, and R. B. Aspects of Declarative Languages, ser. Lecture Notes in Computer Scherl, “GOLOG: A logic programming language for dynamic Science, I. Ramakrishnan, Ed. Springer, 2001, vol. 1990, pp. domains,” The Journal of Logic Programming, vol. 31, no. 1-3, pp. 184–198, 3rd International Symposium (PADL 2001), Las Vegas, 59–83, 1997, special Issue “Reasoning about Action and Change”. NV, USA, 11–12 Mar. 2001. Proceedings. [Online]. Available: [Online]. Available: http://www.sciencedirect.com/science/article/pii/ http://link.springer.com/10.1007/3-540-45241-9 13 S0743106696001215 [4] tuProlog, “Home page,” http://tuprolog.unibo.it, A LMA M ATER S TU - [21] M. Bathelt, U. Gall, B. Hindel, and C. Kurzke, “Accessing embedded DIORUM –Università di Bologna. systems via WWW: The ProWeb toolset,” Computer Networks and [5] SICStus Prolog, “Home page,” http://sicstus.sics.se, SICS Swedish ICT. ISDN Systems, vol. 29, no. 8-13, pp. 1065–1073, Sep. 1997, papers from the 6th International World Wide Web Conference. [Online]. Available: [6] GNU Prolog, “Home page,” http://www.gprolog.org. http://www.sciencedirect.com/science/article/pii/S016975529700024X [22] tuProlog, “RDF library,” http://apice.unibo.it/xwiki/bin/view/Tuprolog/ Libraries, A LMA M ATER S TUDIORUM–Università di Bologna. 84