Enhanced Data Models: Introduction
to Active, Temporal, Spatial,
Multimedia, and Deductive
Databases
Unit 6
Active Database Concepts and Triggers
Active
Database
Active database system is a database system that supports
reactive behavior through ECA (Event Condition Action)
rules.
An active database is a database that includes an event-
driven architecture which can respond to conditions both
inside and outside the database.
Possible uses include security monitoring, alerting,
statistics gathering and authorization.
Active Database is a database consisting of set of triggers.
Generalized Model for Active Databases
Event-condition-action (ECA) model
Event triggers a rule
Usually, database update operations
For example, addition of new row, deletion of row by DBMS
Condition determines whether rule action should be completed
Optional
Action will complete only if condition evaluates to true
Action to be taken
Sequence of SQL statements, transaction, or external program
Trigger
A trigger defines an action the database should take when some database-related event (such as
inserts, updates, deletes) occurs.
A block of code that is attached to an event. When that event occurs the trigger code is
fired.
Triggers follow an Event-condition-action (ECA) model
• Event:
• Database modification
• E.g., insert, delete, update),
• Condition:
• Any true/false expression
• Optional: If no condition is specified then condition is always true
• Action:
• Sequence of SQL statements that will be automatically executed
Use of
Trigger
1. Auditing
• Write information about (sensitive) data modifications to an audit table
• May include old and new values, user, timestamp
• E.g. new and old salary
2. Data Integrity
• Implement checks on data against business rules
• Can compare with live database values
• NEW and OLD values can be compared
• E.g. prices must not go down
3. Referential integrity
• Allows implementation of a "cascade update"
• E.g. if author ID (aID) is changed, appropriately change authID in
foreign key
4. Derived data
• Update any stored derived data when base data changes
• E.g. if total number of employees is stored, add 1 if new employee added
Use of Trigger…
5. Security
● Logging of database access
● E.g. date and time each user logs on
● E.g. deny access at weekend
6. Maintaining synchronous replicates
● In a distributed database
7. Generating statistics on table access
Types of Oracle Trigger
• Triggers can be
• Row-level
• FOR EACH ROW specifies a row-level trigger
• Statement-level
• Default (when FOR EACH ROW is not specified).
• A statement-level trigger is fired whenever a trigger event occurs on a table regardless of how many
rows are affected. In other words, a statement-level trigger executes once for each transaction.
• For example, if you update 1000 rows in a table, then a statement-level trigger on that table would
only be executed once
• Row level triggers
• Executed separately for each affected row
• Statement-level triggers
• Execute once for the SQL statement,
• It’s typically used to enforce extra security measures on the kind of transaction that may
be performed on a table.
Example of Row Level Trigger
create table Student (id number, name varchar2(100) );
insert into Student values (1,'Ram');
insert into Student values (2,'Sita');
create table Log(id number, old_value varchar2(100),
new_value varchar2(100), updateDate TimeStamp);
create user c##ouser identified by adbms;
grant unlimited tablespace to c##ouser;
grant resource, connect, dba to c##ouser;
Create a trigger
create or replace trigger Tg_Student before update
on Student for each row
begin
insert into Log
values (:old.id,
:old.name, :new.name,
CURRENT_TIMESTAMP);
end;
update student set name='Hari';
Example Statement level trigger
Suppose, you want to restrict users to update credit of customers from 28th to 31st of every month so that you can
close the financial month.
To enforce this rule, you can use this statement-level trigger:
CREATE OR REPLACE TRIGGER customers_credit_trg
BEFORE UPDATE OF credit_limit
ON customers
DECLARE
l_day_of_month NUMBER;
BEGIN
-- determine the transaction type
l_day_of_month := EXTRACT(DAY FROM sysdate);
IF l_day_of_month BETWEEN 28 AND 31 THEN
raise_application_error(-20100,'Cannot update customer credit from 28th to 31st');
END IF;
END;
Note that Oracle automatically rollbacks the update because we call the raise_application_error procedure inside the
trigger.
Example
Events that may cause a change in value of Total_sal attribute
Inserting new employee
Changing salary
Reassigning or deleting employees
Figure 26.1 A simplified COMPANY database used for active rule examples
Example (cont’d.)
Condition to be evaluated
• Check that value of Dno attribute is not NULL
Action to be taken
• Automatically update the value of Total_sal
Figure 26.2 Specifying active rules as triggers in Oracle notation (a) Triggers for
automatically maintaining the consistency of Total_sal of DEPARTMENT
Figure 26.2 (cont’d.) Specifying active rules as triggers in Oracle notation (b)
Trigger for comparing an employee’s salary with that of his or her supervisor
Potential Applications for Active
Databases
Allow notification of certain conditions that occur
Enforce integrity constraints
Automatically maintain derived data
Maintain consistency of materialized views
Enable consistency of replicated tables
Temporal Database Concepts
Temporal
A Database
temporal database is a database with built-in support for handling time sensitive data.
Temporal databases, encompass all DB applications that require some aspect of time
when organizing their information.
Temporal databases can be used for a variety of applications, such as auditing,
compliance, historical analysis, fraud detection, and decision making.
Temporal databases can be more complex to manage than traditional databases. This is
because they need to store additional information about time, and they need to be able to
track changes to data over time.
Temporal databases require some aspect of time when organizing information
Healthcare
Insurance
Reservation systems
Scientific databases
Non-Temporal Database
Store only a single state of the real world, usually the most
recent state
Classified as snapshot databases
No old values
Application developers and database designers need to code
for time varying data requirements eg history tables, forecast
reports etc
Temporal Database Concepts (cont’d.)
SQL2 temporal data types
DATE, TIME, TIMESTAMP, INTERVAL, PERIOD
Point events or facts
Typically associated with a single time point
Time series data
Duration events or facts
Associated with specific time period
Time period represented by start and end points
Valid time
True in the real world
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
Temporal Database Concepts (cont’d.)
Transaction time
Value of the system clock when information is valid in the system
User-defined time
Bitemporal database
Uses valid time and transaction time
Valid time relations
Used to represent history of changes
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
Temporal Database Concept (contd.)
Stores upto two dimensions of time i.e VALID (stated) time
and TRANSACTION (logged) time
Temporal databases have two main types of time: valid time
and transaction time.
Valid time denotes the time period during which a fact is true
with respect to the real world.
Transaction time is the time period during which a fact is
stored in the databases.
Classified as historical, rollback or bi-temporal
No need for application developers or database designers to code for
time varying data requirements i.e time is inherently supported
What are temporal
databases?
Valid (stated) Time
Transaction (logged)
The 2 dimensions of
time
Time
Products Using Temporal Databases:
Oracle Temporal Database,
Microsoft SQL Server Temporal Tables,
IBM DB2 Temporal Database,
PostgreSQL Temporal Data Types
Time Representation..
Temporal databases store and manage data that changes over time.
The temporal aspects usually include valid time and transaction time
dimension.
These attributes can be combined to form bi-temporal data.
• Valid time is the time period during which a fact is true with respect to the real world.
• Transaction time is the time period during which a fact stored in the database is considered to be true.
• Bi-temporal data combines both Valid and Transaction Time
Another important aspect of time representation in temporal databases is the
concept of granularity.
Granularity refers to the smallest unit of time that is meaningful to the
application.
For example, if an application is only interested in tracking time to the nearest
day, then the granularity of the database will be one day.
Exam
ple
• Now let’s see an example of a person, John:
• John was born on April 3, 1992 in Chennai.
• His father registered his birth after three days on April 6, 1992.
• John did his entire schooling and college in Chennai.
• He got a job in Mumbai and shifted to Mumbai on June 21, 2015.
• He registered his change of address only on Jan 10, 2016.
Source: https://www.mytecbits.com/oracle/oracle-database/what-is-temporal-database
Name City Valid From Valid Till
John Chennai April 3, 1992 June 20, 2015
John Mumbai June 21, 2015 ∞
Valid Time and Transaction
Time
Johns father registers his birth on 6th April 1992:
Person(John, Chennai, 3-Apr-1992, ∞, 6-Apr-1992, ∞).
On January 10, 2016 John reports his new address in Mumbai:
Person(John, Mumbai, 21-June-2015, ∞, 10-Jan-2016, ∞).
The original entry is updated.
Person(John, Chennai, 3-Apr-1992, 20-June-2015, 6-Apr-1992, 10-Jan-2016).
Name City Valid From Valid Till Entered Superseded
John Chennai April 3, 1992 June 20, 2015 April 6, 1992 Jan 10, 2016
John Mumbai June 21, 2015 ∞ Jan 10, 2016 ∞
Calendars in temporal
databases
A calendar is a system for dividing time into periods of varying lengths.
Calendars are used to schedule events, track holidays, and calculate
dates and times.
Calendars help manage and represent time-related information in
temporal databases in a structured and meaningful way.
Temporal databases can support a variety of different calendars,
including the Gregorian calendar, the Chinese calendar, and the
Islamic calendar.
The calendar that is used by a temporal database will depend on the
specific needs of the application.
Calendars are a fundamental component of temporal databases,
providing the structure and tools needed to manage and query time-
related data effectively.
They enable the representation of timestamps, time intervals, and
temporal constraints, making it possible to work with data that
Incorporating Time in Relational
Databases Using Tuple Versioning
Tuple versioning is a technique for incorporating time in relational databases. It works by
storing multiple versions of each tuple, each with a timestamp indicating when it was
valid.
This allows users to query the database for the state of the data at any point in time.
Add to every tuple
• Valid start time
• Valid end time
• Transaction Start Time
• Transaction End Time
Tuple versioning has several benefits, including:
• It allows users to track changes to data over time.
• It allows users to query the database for the state of the data at any point in time.
• It can be used to implement undo/redo functionality.
Temporal Relational Database
Example
Temporal Relational Database
Example
Time series data
Time series data is a collection of data points that are
collected over time and arranged in chronological order.
It is a type of sequential data that can be used to track
changes in a variable over time.
Often used in financial, sales, and economics applications
Special type of valid event data
Event’s time points predetermined according to fixed
calendar
Managed using specialized time series management systems
Supported by some commercial DBMS packages
Use of temporal database
Temporal Databases store information about states of the real
world across time.
Temporal Database is a database with built-in support for handling
data involving time.
It stores information relating to past, present and future time of all
events.
Spatial Database Concepts
Spatial Database Concepts
Spatial databases support information about objects in
multidimensional space
Examples: cartographic databases, geographic information systems,
weather information databases
Spatial relationships among the objects are important
Optimized to query data such as points, lines, and polygons
Spatial queries
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
What is Spatial Data?
“Information about the location and shapes of geographic features and
the relationship between them, usually stored as coordinates
and topology” – ESRI (Environmental Systems Research
Institute)
ESRI is an American multinational geographic information
system (GIS) software company. )
https://www.youtube.com/watch?v=uHronVrSSdw
Spatial Database
Spatial Object: Consists of points, lines, surfaces, volumes and higher
dimension objects that are used in applications of computer-aided design,
cartography, geographic information system
Spatial Data: The value of the objects’ spatial attributes: length,
configuration, perimeter, area, volume etc.
Spatial Database: A spatial database is a database that is enhanced to store and
access spatial data or data that defines a geometric space. These data are often
associated with geographic locations and features, or constructed features like cities.
Data on spatial databases are stored as coordinates, points, lines, polygons and
topology.
Spatial Database Concepts (cont’d.)
Measurement operations
Used to measure global properties of single objects
Spatial analysis operations
Uncover spatial relationships within and among mapped data layers
Flow analysis operations
Help determine shortest path between two points
Location analysis
Determine whether given set of points and lines lie within a given polygon
Digital terrain analysis
Used to build three-dimensional models
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
Spatial Database Concepts (cont’d.)
Table 26.1 Common types of analysis for spatial data
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
Spatial Representation
Raster model:
Vector model:
Spatial data types
poin regio
lin n
t
e
Point : 2 real numbers
Line : sequence of points
Region : area included inside n-points
Spatial data types and Models
Spatial data types
Map data
Geographic or spatial features of objects in a map such as an object’s shape and the location of the
object within the map.
The three basic types of features are points, lines, and polygons (or areas).
Attribute data
Descriptive data associated with map features
For example, population, largest city/town, area in square miles, and so on
Image data
Satellite images and aerial photographs, which are typically created by cameras
Models of spatial information
Field models
Used to model spatial data that is continuous in nature, such as terrain elevation, temperature data,
and soil variation characteristics
Object models
Used for applications such as transportation networks, land parcels, buildings, and other objects that
possess both spatial and non-spatial attributes.
Spatial Operators
Spatial operators are used to capture all the relevant geometric properties of objects embedded in the physical
space and the relations between them, as well as to perform spatial analysis .
Spatial operator categories
Topological operators
open, close , and inside, Intersects, Touches, Within, Overlap, Disjoint
Projective operators
Projective operators transform spatial data from one coordinate system to another
Express concavity/convexity of objects
Translate, Rotate, Scale
Metric operators
Metric operators calculate distances, areas, and volumes between and within spatial objects
Specifically describe object’s geometry
Distances, Areas, and Volume
Dynamic spatial operators
Dynamic spatial operators deal with spatial objects that change over time
Create buffer, destroy, and update
Network analysis: Performs network analysis operations, such as finding the shortest path between two
points or the closest facility to a point.
Spatial Queries
Spatial queries
Range queries
finds the objects of particular type that are within a given spatial area or within a particular
distance from given location
Example: find all hospitals with the Metropolitan Atlanta city area
finds all ambulances within five miles of an accident location
Nearest neighbor queries
Finds the objects of particular type that is closed to a given location.
Example: find police car nearest location of a crime
Spatial joins or overlays
Joins the objects of two type based on some spatial conditions, such as the objects intersecting
or overlapping spatially or being within a certain distance of one another.
Example: find all homes within two miles of a lake
finds all cities located on a major highway.
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
Query Examples
Non Spatial Query: “List the municipalities with populations over
500,000 in the Nepal”
Spatial Query: “List crime hot spots within 10 miles of
downtown Patna”
Spatial
Relationships
• Topological relationships:
• adjacent, inside, disjoint, etc
• Direction relationships:
• Above, below, north_of, etc
• Metric relationships:
• “distance < 100”
Spatial data indexing
Grid files
Grid files work by dividing space into a grid of cells. Each cell in the grid contains a list of the spatial objects that intersect with
the cell.
To perform a spatial query on a grid file, the query is first converted into a set of grid cells.
The database then searches the grid cells to find the spatial objects that satisfy the query.
R-trees
The R-tree is a height-balanced tree, which is an extension of the B+-tree for k-dimensions, where k > 1.
R-trees work by grouping spatial objects into bounding boxes. The bounding boxes are then organized into a tree structure, such
that the root node of the tree contains the bounding box for all of the spatial objects in the database. The internal nodes of the
tree contain bounding boxes for smaller groups of spatial objects. The leaf nodes of the tree contain the actual spatial objects.
To perform a spatial query on an R-tree, the query is first converted into a bounding box. The database then searches the R-tree
to find the bounding boxes that intersect with the query bounding box. The database then recursively searches the bounding
boxes until the actual spatial objects are found.
Spatial join index
A spatial join index precomputes a spatial join operation and stores the pointers to the related object in an index structure.
When a spatial join query is performed, the database can use the spatial join index to quickly find the results of the query.
Spatial data mining techniques
Spatial data mining techniques are used to extract knowledge from spatial data.
Spatial classification
Spatial classification is the process of assigning spatial objects to different classes.
Spatial classification can be used to identify different types of land cover, such as forests, urban areas, and agricultural
land.
Hotspots in crime activity is a location prediction problem.
Spatial association
Spatial association rules are defined in terms of spatial predicates rather than items.
A spatial association rule is of the form P1 ∧ P2 ∧ … ∧ Pn ⇒ Q1 ∧ Q2 ∧ … ∧ Qm
where at least one of the Pi ’s or Qj ’s is a spatial predicate.
For example, the rule is_a(x, country) ∧ touches(x, Mediterranean) ⇒ is_a (x, wine-exporter)
(that is, a country that is adjacent to the Mediterranean Sea is typically a wine exporter) is an example of an association
rule, which will have a certain support s and confidence.
Spatial clustering
Spatial clustering is the process of grouping spatial objects together based on their similarity.
Spatial clustering can be used to identify groups of businesses that are located in the same area.
It can also be used to identify groups of spatial objects that are likely to be affected by the same event, such as a flood or
a fire.
An example of a spatial clustering algorithm is density-based clustering, which tries to find clusters based on the density
of data points in a region.
Applications of Spatial Data
Urban planning
Spatial data mining techniques can be used to identify areas that are suitable for
development, to identify areas that are at risk of flooding or other natural disasters, and to
identify areas where there is a need for new schools or hospitals.
Remote sensing or Environmental science
Spatial data mining techniques can be used to monitor environmental changes, such as
deforestation or water pollution, to identify areas that are at risk of environmental hazards,
and to develop environmental management plans.
Public health
Spatial data mining techniques can be used to track the spread of diseases, to identify
areas where there is a high prevalence of chronic diseases, and to develop public health
interventions.
Geographic Information Systems (GIS)
Identify clusters of similar spatial objects, such as areas with high concentrations of crime
or areas with high concentrations of a particular type of vegetation
Natural resource management
Identify areas that are suitable for certain types of development, to identify areas that are
at risk of natural hazards, or to identify areas where there is a high concentration of a
particular natural resource.
This information can then be used to make informed decisions about how to manage
Multimedia Database Concepts
Multimedia Database
Multimedia is a combination of text, graphic, sound, animation, and
video that is delivered interactively to the user by electronic or digitally
manipulated means. In other words, multimedia is a form of
communication that combines different content forms such as text, audio,
images, animations, or video into a single interactive presentation.
Multimedia database is the collection of interrelated multimedia data
that includes text, graphics (sketches, drawings), images, animations,
video, audio etc and have vast amounts of multisource multimedia data.
These data types are broadly categorized into three classes:
Static media (time-independent, i.e. images and handwriting)
Dynamic media (time-dependent, i.e. video and sound bytes)
Dimensional media (i.e. 3D games or computer-aided drafting
programs- CAD)
Data Types of Multimedia in Oracle
Multimedia data types, which are represented in Oracle Database is
Large Objects (LOBs).
There are three SQL data types for defining instances of internal LOBs:
BLOB: A LOB whose value is composed of unstructured binary (raw)
data
CLOB: A LOB whose value is composed of character data that corresponds
to the database character set defined for the Oracle database
NCLOB: A LOB whose value is composed of character data that corresponds
to the national character set defined for the Oracle database
BFILES: are large binary data objects stored in operating system files
outside database table spaces
Types of multimedia data are available in current systems
• Text: Text is the most basic form of multimedia data. It can be stored in a variety of
formats, including plain text, HTML, and XML. The text can have various types of fonts,
sizes and styles. The textual data for multimedia can be developed using any text editors.
• Images: Images are a type of visual data that can be stored in a variety of formats,
including JPEG, PNG, and GIF. There are several graphics packages available to develop
graphics such as MS Paint, Corel Draw, Adobe Photoshop, Adobe Illustrator etc
• Audio : Audio is produced by vibration, as perceived by the sense of hearing. Audio
is a type of auditory data that can be stored in a variety of formats, including WAV,
MP3, and AAC.
Multimedia……
• Video: Video is a type of audiovisual data that can be stored in a variety
of formats, including AVI, MPEG, and MP4. A set of temporally
sequenced photographic data for presentation at specified rates– for
example, 30 frames per second.
• Animations: Temporal sequences of image or graphic data. A computer-
based animation is a sequence of still vector image displayed in rapid
succession to provide visual effect.
Multimedia Database Concepts…
• Multimedia databases allow users to store and query images, video,
audio, and documents
• Automatic Analysis of Images
• extracting meaningful information from images, such as objects, scenes, and
actions, and representing this information in a way that can be efficiently
searched and processed.
• Steps:
• Image Segmentation
• Feature Extraction
• Indexing and Retrieval
• Applications:
• Content-based image retrieval: search for images by using similar images
as queries
• Image classification: classify images into predefined categories, such as
cats, dogs, and cars
• Object detection: identify and locate objects in image
Multimedia Database Concepts (cont’d.)
• Object recognition
• Object recognition is the task of identifying real-world objects in an image or a video sequence.
• It is a key part of many machine learning and deep learning applications, and it has a wide range of
potential applications in fields such as robotics, surveillance, and medical diagnosis.
• Semantic tagging of images
• Assigning descriptive labels or keywords to images based on their content.
• This is done by analyzing the image's pixels and extracting meaningful
information about the objects, scenes, and activities depicted in the image.
• User-supplied tags
• Automated generation of image tags
• Web Ontology Language (OWL) provides concept hierarchy
• Concepts like “sky” and “grass” may be further divided into “clear sky” and “cloudy sky” or
“dry grass” and “green grass” in such a taxonomy
Slide 23- 55
• Analysis of audio data sources
• Audio sources are broadly classified into speech, music, and other audio data.
• Text-based indexing:
• converting audio content into a textual representation that can be efficiently searched and
retrieved. E.g. Voice search, Audio summarization
• Steps:
• Speech-to-text conversion,
• Natural language processing (NLP)
• Indexing
• Retrieval
• Content-based indexing
• Content-based indexing often makes use of the key features of sound: intensity, pitch, timbre,
and rhythm.
• It is possible to compare different pieces of audio data and retrieve information from them
based on the calculation of certain features, as well as application of certain transforms.
Challenges of Multimedia database
Multimedia databases contains data in a large type of formats such as
.txt(text), .jpg(images), .swf(videos), .mp3(audio) etc. It is difficult to
convert one type of data format to another.
The multimedia database requires a large size as the multimedia
data is quite large and needs to be stored successfully in the
database.
It takes a lot of time to process multimedia data so
multimedia database is slow
Deductive Database Concepts;
Deductive Database
What is deductive database?
A deductive database is a database system that makes conclusions about its
data based on a set of well-defined rules and facts stored in the database.
This type of database was developed to combine logic programming with
relational database management systems. Usually, the language used to
define the rules and facts is the logical programming language Datalog.
A deductive database is a finite collection of facts and rules. By applying
the rules of a deductive database to the facts in the database, it is possible to
infer additional facts, i.e. facts that are implicitly true but are not explicitly
represented in the database.
Deductive
Database
A deductive database system is a database system which can make
deductions (i.e.: conclude additional facts) based on rules and facts stored
in the (deductive) database.
Deductive: towards the consequences:
All swans are white.
Tessa is a swan.
Tessa is white.
Given the truth of the assumptions, a valid deduction guarantees the truth
of the conclusion
Prolog/Datalog Notation
Predicate has
a name
a fixed number of arguments
Convention:
Constants are numeric or character strings
Variables start with upper case letters
E.g., SUPERVISE(Supervisor, Supervisee)
States that Supervisor SUPERVISE(s) Supervisee
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 24- 62
Prolog/Datalog Notation
Rule
Is of the form head :- body
where :- is read as if and only iff
E.g., SUPERIOR(X,Y) :- SUPERVISE(X,Y)
E.g., SUBORDINATE(Y,X) :- SUPERVISE(X,Y)
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 24- 63
Prolog/Datalog Notation
Query
Involves a predicate symbol followed by y some variable arguments
to answer the question
where :- is read as if and only iff
E.g., SUPERIOR(james,Y)?
E.g., SUBORDINATE(james,X)?
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 24- 64
Figure 24.11
(a) Prolog notation (b) Supervisory tree
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 24- 65
Syntax in prolog
Variables and Names
Variables begin with an uppercase letter. Predicate names, function names, and the names for objects
must
begin with a lowercase letter. Rules for forming names are the same as for the predicate calculus.
Facts
A fact is a predicate expression that makes a declarative statement about the problem domain. Facts are
statements that are known to be true. Whenever a variable occurs in a Prolog expression, it is assumed to
be universally quantified. Note that all Prolog sentences must end with a period.
likes(john, susie). /* John likes Susie */
likes(X, susie). /* Everyone likes Susie */
likes(john, Y). /* John likes everybody
likes(john, Y), likes(Y, john).*/ /* John likes everybody and everybody likes John
*/ likes(john, susie); likes(john,mary). /* John likes Susie or John likes Mary */
not(likes(john,pizza)). /* John does not like pizza */
likes(john,susie) :- likes(john,mary)./* John likes Susie if John likes Mary.
Rule
A rule is a predicate expression that uses logical implication (:-) to
describe a relationship among facts. Thus a Prolog rule takes the form
left_hand_side :- right_hand_side .
This sentence is interpreted as: left_hand_side if right_hand_side. The
left_hand_side is restricted to a single, positive, literal, which means it
must consist of a positive atomic expression. It cannot be negated and it
cannot contain logical connectives.
Query:
Whenever you run the Prolog interpreter, it will prompt you with ?-.
male(rati).
male(ram). La
male(himanshu).
female(bina). b 1. Who is the father of
female(naru). gunjan?
female(gunjan).
female(smriti). ? – father(X,gunjan)
parent(rati,ram).
parent(naru,ram).
1. Who is the grand mother
parent(ram, himanshu). of smriti?
parent(ram, gunjan).
parent(ram, smriti).
- grandmother(X, smriti)
parent(bina, himanshu).
parent(bina, gunjan).
parent(bina, smriti).
Download SWI-Prolog
father(X,Y):-
male(X),parent(X,Y).
mother(X,Y):-
female(X),parent(X,Y).
grandfather(X,Y):-
male(X),parent(X,Z),
Datalog
• Datalog is a declarative logic programming language that is used for
knowledge representation and inference. This is a variation of Prolog.
• Datalog programs are made up of facts and rules. Facts represent
information about the world, and rules define relationships between
facts.
• Example:
• Fact: capital(Nepal, Kathmandu)
• Rule:has_nepali_passport(person) :- citizen(person, Nepal)
• Inference: Given the following fact and rules:
• capital(Nepal, Kathmandu)
• citizen(Ram, Nepal)
• The following inference can be made:
• has_nepali_passport(Ram)
• Datalog allows you to retrieve information from the database using
queries. Queries consist of predicates and variables that represent
the desired values. The Datalog engine finds matching results based
on the specified conditions.
Example
Facts are statements that are known to be true.
fact: student(john)
Rules are statements that describe how to derive new facts
from existing facts.
Rule: takes(X, C) :- student(X), course(C)
The :- symbol means "if". So, the above rule states that if X is
a student and C is a course, then X must be taking course C.
Queries are statements that ask for information from a Datalog
program.
query: student(X) :- takes(X, C)
Examples
Facts:
course(math)
student(john)
student(mary)
Rules:
takes(X, C) :- student(X), course(C)
teaches(X, C) :- professor(X), course(C)
student(X) :- takes(X, C)
professor(X) :- teaches(X, C)
Queries:
course(C) :- takes(X, C)
professor(X) :- teaches(X, math)
student(X) :- takes(X, math)
student(X) :- student(Y), X != Y
Clausal Form and Horn Clauses
• In deductive database, a clause is a disjunction (OR logical connectives) of literals. Literals
can be positive literals or negative literals.
• The clauses themselves are connected by AND logical connectives only, to form a formula.
• Hence, the clausal form of a formula is a conjunction of clauses.
• NOT(P1) OR NOT(P2) OR … OR NOT(Pn) OR Q1 OR Q2 OR … OR Qm (1)
• This clause has n negative literals and m positive literals. Such a clause can be transformed
into the following equivalent logical formula:
• P1 AND P2 AND … AND Pn ⇒ Q1 OR Q2 OR … OR Qm
• A Horn clause is a clause with at most one positive literal.
• Hence, a Horn clause is either of the form
• NOT (P1) OR NOT(P2) OR … OR NOT(Pn) OR Q (1)
• or of the form NOT (P1) OR NOT(P2) OR … OR NOT(Pn) (2)
• The Horn clause in (1) can be transformed into the clause
• P1 AND P2 AND … AND Pn ⇒ Q
• which is written in Datalog as the following rule: Q :– P1, P2, … , Pn.
• The Horn clause in (2) can be transformed into
• P1 AND P2 AND … AND Pn ⇒
• which is written in Datalog as follows: P1, P2, … , Pn.
• Clauses and Horn clauses are fundamental to deductive databases because they form the
basis for logical reasoning in these systems.
Interpretations of Rules
• Interpretations of rules play a crucial role in deriving new knowledge and making
inferences from existing facts
• Two main alternatives for interpreting the theoretical meaning of rules: Proof-theoretic
and model-theoretic
• Proof-theoretic
• In the proof-theoretic interpretation of rules, we consider the facts and rules to be true statements, or axioms.
• Ground axioms contain no variables. The facts are ground axioms that are given to be true.
• Rules are called deductive axioms, since they can be used to deduce new facts.
• The deductive axioms can be used to construct proofs that derive new facts from existing facts.
• The proof-theoretic interpretation of rules focuses on the derivability of facts from other facts using the
rules.
• This interpretation emphasizes the syntactic properties of the rules and the logical structure of the
proofs.
• Figure 26.12 shows how to prove the fact SUPERIOR(james, ahmad) from the rules and facts given in Figure 26.11.
Interpretations of Rules…
• Model-theoretic
• An interpretation is called a model for a specific set of rules if those rules are
always true under that interpretation; that is, for any values assigned to the
variables in the rules, the head of the rules is true when we substitute the truth
values assigned to the predicates in the body of the rule by that interpretation.
• The model-theoretic interpretation of rules focuses on the truth
preservation properties of rules.
• This interpretation emphasizes the semantic properties of the
rules and the meaning of the formulas in the models.
Example 1: Universal generalization
Rule:
(∀x)(P(x)) → P(a)
Proof-theoretic interpretation:
This rule is meaningful because it can be used to derive the fact P(a) from the fact (∀x)(P(x)). The
elimination rule for this rule is:
(∀x)(P(x)) ⊢ P(a)
Model-theoretic interpretation:
This rule is meaningful because it preserves the truth of the fact P(a) between different models. The
satisfaction condition for this rule is:
M ⊨ (∀x)(P(x)) → P(a)
This means that if a model M satisfies (∀x)(P(x)) for all values of x, then it must also satisfy P(a) for any
particular value of a.
Example 2: Existential instantiation
Rule:
(∃x)(P(x)) → P(a)
Proof-theoretic interpretation:
This rule is meaningful because it can be used to derive the fact P(a) from the fact (∃x)(P(x)). The
elimination rule for this rule is:
(∃x)(P(x)) ⊢ P(a)
Model-theoretic interpretation:
This rule is meaningful because it preserves the truth of the fact P(a) between different models. The
satisfaction condition for this rule is:
M ⊨ (∃x)(P(x)) → P(a)
This means that if a model M satisfies (∃x)(P(x)), then there must exist a value of a such that M also
satisfies P(a).