How to extract a value of an attribute in Grakn? - vaticle-typedb

I want to use GRAKN to model knowledge about an autonomous car. In one example, I want to derive which velocity I have to propose to the autonomous car. I know the maximum speed of the car, I know the speed limit of the road and if the speed limit on the road is not exceeding the maximum speed of the car, I want to propose the car to drive the allowed speed limit. maximum-speed, speed-limit and proposed-speed are attributes of cars or roads. In my example I want to assign the value of 'speed-limit' as the value of 'proposed-speed'. Is this possible in GRAKN?
The following is what I tried. I know it is incorrect, but I expect the solution to look something like this, but than assigning values instead of the whole attribute.
define
max-speed sub attribute, datatype double;
proposed-speed sub attribute, datatype double;
speed-limit sub attribute, datatype double;
drives-on sub relation,
relates vehicle-role,
relates type-of-road;
vehicle sub entity,
has max-speed,
has proposed-speed,
plays vehicle-role;
car sub vehicle;
road-type sub entity,
has speed-limit,
plays type-of-road;
highway sub road-type;
proposed-speed-by-road-type sub rule,
when {
$x isa vehicle, has max-speed $s;
$y isa road-type, has speed-limit $z;
($x,$y) isa drives-on;
$z <= $s;
}, then {
$x has proposed-speed $z;
};
proposed-speed-by-car-max sub rule,
when {
$x isa vehicle, has max-speed $s;
$y isa road-type, has speed-limit $z;
($x,$y) isa drives-on;
$z > $s;
}, then {
$x has proposed-speed $s;
};
insert
$owncar isa car, has max-speed 190;
$highway isa highway, has speed-limit 130;
(vehicle-role: $owncar, type-of-road: $highway) isa drives-on;`
Now, if I query the following: match $x id V82016, has proposed-speed $z; get;
I get:
grakn.core.server.exception.TransactionException-The type [car] is not allowed to have an attribute of type [speed-limit]. Please check server logs for the stack trace.
I get this, because this is not correct. So what I would like is to extract the value of 'speed-limit' and assign it to proposed-speed. Is this possible?

This is possible. Your example is correct. The only condition at the moment is that the respective attribute data types are the same and the types are allowed to have them. Under the hood a new attribute is created with the value copied. We are planning to expand the use case to cover compatible pairs of data types.
It works as expected on current master branch. In general it should also work with 1.5.7, however 1.5.7 has a problem with computing rule equalities which may lead to incorrect result. The problem should be absent in the 1.5.8 release.
Hope that helps!

Related

Is it bad practice to provide your own setter or should I use setproperty?

Suppose if I had the following Employee struct:
mutable struct Employee
_id::Int64
_first_name::String
_last_name::String
function Employee(_id::Int64,_first_name::String,_last_name::String)
# validation left out.
new(_id,_first_name,_last_name)
end
end
If I wanted to implement my own setproperty!() I can do:
function setproperty!(value::Employee,name::Symbol,x)
if name == :_id
if !isa(x,Int64)
throw(ErrorException("ID type is invalid"))
end
setfield!(value,:_id,x)
end
if name == :_first_name
if is_white_space(x)
throw(ErrorException("First Name cannot be blank!"))
end
setfield!(value,:_first_name,x)
end
if name == :_last_name
if is_white_space(x)
throw(ErrorException("Last Name cannot be blank!"))
end
setfield!(value,:_last_name,x)
end
end
Have I implemented setproperty!() correctly?
The reason why I use setfield!() for _first_name and _last_name, is because if I do:
if name == :_first_name
setproperty!(value,:_first_name,x) # or value._first_name = x
end
it causes a StackOverflowError because it's recursively using setproperty!().
I don't really like the use of setproperty!(), because as the number of parameters grows, so would setproperty!().
It also brings to mind using Enum and if statements (only we've switched Enum with Symbol).
One workaround I like, is to document that the fields are meant to be private and use the provided setter to set the field:
function set_first_name(obj::Employee,first_name::AbstractString)
# Validate first_name before assigning it.
obj._first_name = first_name
end
The function is smaller and has a single purpose.
Of course this doesn't prevent someone from using setproperty!(), setfield!() or value._field_name = x, but if you're going to circumvent the provided setter then you'll have the handle the consequences for doing it.
Of course this doesn't prevent someone from using setproperty!(), setfield!() or value._field_name = x, but if you're going to circumvent the provided setter then you'll have the handle the consequences for doing it.
I would recommend you to do this, defining getter,setter functions, instead of overloading getproperty/setproperty!. on the wild, the main use i saw on overloading getproperty/setproperty! is when fields can be calculated from the data. for a getter/setter pattern, i recommend you to use the ! convention:
getter:
function first_name(value::Employee)
return value._first_name
end
setter:
function first_name!(value::Employee,text::String)
#validate here
value._first_name = text
return value._first_name
end
if your struct is mutable, it could be that some fields are uninitialized. you could add a getter with default, by adding a method:
function first_name(value::Employee,default::String)
value_stored = value._first_name
if is_initialized(value_stored) #define is_initialized function
return value_stored
else
return default
end
end
with a setter/getter with default, the only difference between first_name(val,text) and first_name!(val,text) would be the mutability of val, but the result is the same. useful if you are doing mutable vs immutable functions. as you said it, the getproperty/setproperty! is cumbersome in comparison. If you want to disallow accessing the fields, you could do:
Base.getproperty(val::Employee,key::Symbol) = throw(error("use the getter functions instead!")
Base.setproperty!(val::Employee,key::Symbol,x) = throw(error("use the setter functions instead!")
Disallowing the syntax sugar of val.key and val.key = x. (if someone really want raw access, there is still getfield/setfield!, but they were warned.)
Finally, i found this recomendation in the julia docs, that recommends getter/setter methods over direct field access
https://docs.julialang.org/en/v1/manual/style-guide/#Prefer-exported-methods-over-direct-field-access

Error "rule graph is not stratifiable" in Grakn

I'm trying to insert this rule (data is masked):
when {
$d isa person;
$a isa animal;
$r (role-1: $d, role-2: $a) isa relation-1, has attr $ds;
not {$r1 (role-3: $d, role-4: $a) isa relation-2; };
$ds > 0.5;
}, then {
(role-3: $a, role-4: $d, role-5: $ds) isa relation-2;
};
However I keep getting this structural validation error after I do commit. Please help
INVALID_ARGUMENT: InvalidKBException-A structural validation error has occurred. Please correct the [`1`] errors found.
The rule graph is not stratifiable - it contains following cycles with negation: [[[Base Type [RELATION_TYPE] - Id [V65648] - Label [relation-2] ]]]
. Please check server logs for the stack trace.
All uncommitted data is cleared
Rules that cause loops - for example, where the conclusion is negated in the when clause - are not allowed in Grakn.
Here's an example to demonstrate why.
define
person sub entity, plays employee;
employment sub relation, relates employee;
there-are-no-unemployed sub rule,
when {
$p isa person;
not {
(employee: $p) isa employment;
};
}, then {
(employee: $p) isa employment;
}
If we have a person who is not in an employment relation, then they are in an employment relation. But now, we've contradicted the initial premise of the rule - that they were not in an employment relation. Thus, we have a logical contradiction.

number inside [] after in orderby in XQuery

Following is the query
for $x in $books
where $x/price>=38
order by ($x/price)[l]
return ($x/title, $x/price)
what is denoted by [1] located after order by($x/price)?
It looks to me like a lower-case-L rather than a digit-one.
If it's really a one [1] then it means select the first item in the sequence $x/price. I suspect each book has only one price, in which case it's completely redundant.

Passing strings as task creation discriminants in Ada

I'm moving my first steps with Ada, and I'm finding that I struggle to understand how to do common, even banal, operations that in other languages would be immediate.
In this case, I defined the following task type (and access type so I can create new instances):
task type Passenger(
Name : String_Ref;
Workplace_Station : String_Ref;
Home_Station : String_Ref
);
type Passenger_Ref is access all Passenger;
As you can see, it's a simple task that has 3 discriminants that can be passed to it when creating an instance. String_Ref is defined as:
type String_Ref is access all String;
and I use it because apparently you cannot use "normal" types as task discriminants, only references or primitive types.
So I want to create an instance of such a task, but whatever I do, I get an error. I cannot pass the strings directly by simply doing:
Passenger1 := new Passenger(Name => "foo", Workplace_Station => "man", Home_Station => "bar");
Because those are strings and not references to strings, fair enough.
So I tried:
task body Some_Task_That_Tries_To_Use_Passenger is
Passenger1 : Passenger_Ref;
Name1 : aliased String := "Foo";
Home1 : aliased String := "Man";
Work1 : aliased String := "Bar";
begin
Passenger1 := new Passenger(Name => Name1'Access, Workplace_Station => Work1'Access, Home_Station => Home1'Access);
But this doesn't work either, as, from what I understand, the Home1/Name1/Work1 variables are local to task Some_Task_That_Tries_To_Use_Passenger and so cannot be used by Passenger's "constructor".
I don't understand how I have to do it to be honest. I've used several programming languages in the past, but I never had so much trouble passing a simple String to a constructor, I feel like a total idiot but I don't understand why such a common operation would be so complicated, I'm sure I'm approaching the problem incorrectly, please enlighten me and show me the proper way to do this, because I'm going crazy :D
Yes, I agree it is a serious problem with the language that discriminates of task and record types have to be discrete. Fortunately there is a simple solution for task types -- the data can be passed via an "entry" point.
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
procedure Main is
task type Task_Passenger is
entry Construct(Name, Workplace, Home : in String);
end Passenger;
task body Task_Passenger is
N, W, H : Unbounded_String;
begin
accept Construct(Name, Workplace, Home : in String) do
N := To_Unbounded_String(Name);
W := To_Unbounded_String(Workplace);
H := To_Unbounded_String(Home);
end Construct;
--...
end Passenger;
Passenger : Task_Passenger;
begin
Passenger.Construct("Any", "length", "strings!");
--...
end Main;
Ada doesn't really have constructors. In other languages, a constructor is, in essence, a method that takes parameters and has a body that does stuff with those parameters. Trying to get discriminants to serve as a constructor doesn't work well, since there's no subprogram body to do anything with the discriminants. Maybe it looks like it should, because the syntax involves a type followed by a list of discriminant values in parentheses and separated by commas. But that's a superficial similarity. The purpose of discriminants isn't to emulate constructors.
For a "normal" record type, the best substitute for a constructor is a function that returns an object of the type. (Think of this as similar to using a static "factory method" instead of a constructor in a language like Java.) The function can take String parameters or parameters of any other type.
For a task type, it's a little trickier, but you can write a function that returns an access to a task.
type Passenger_Acc is access all Passenger;
function Make_Passenger (Name : String;
Workplace_Station : String;
Home_Station : String) return Passenger_Acc;
To implement it, you'll need to define an entry in the Passenger task (see Roger Wilco's answer), and then you can use it in the body:
function Make_Passenger (Name : String;
Workplace_Station : String;
Home_Station : String) return Passenger_Acc is
Result : Passenger_Acc;
begin
Result := new Passenger;
Result.Construct (Name, Workplace_Station, Home_Station);
return Result;
end Make_Passenger;
(You have to do this by returning a task access. I don't think you can get the function to return a task itself, because you'd have to use an extended return to set up the task object and the task object isn't activated until after the function returns and thus can't accept an entry.)
You say
"I don't understand how I have to do it to be honest. I've used several programming languages in the past, but I never had so much trouble passing a simple String to a constructor, I feel like a total idiot but I don't understand why such a common operation would be so complicated, I'm sure I'm approaching the problem incorrectly, please enlighten me and show me the proper way to do this, because I'm going crazy :D"
Ada's access types are often a source of confusion. The main issue is that Ada doesn't have automatic garbage collection, and wants to ensure you can't suffer from the problem of returning pointers to local variables. The combination of these two results in a curious set of rules that force you to design your solution carefully.
If you are sure your code is good, then you can always used 'Unrestricted_Access on an aliased String. This puts all the responsibility on you to ensure the accessed variable won't disappear from underneath the task though.
It doesn't have to be all that complicated. You can use an anonymous access type and allocate the strings on demand, but please consider if you really want the strings to be discriminants.
Here is a complete, working example:
with Ada.Text_IO;
procedure String_Discriminants is
task type Demo (Name : not null access String);
task body Demo is
begin
Ada.Text_IO.Put_Line ("Demo task named """ & Name.all & """.");
exception
when others =>
Ada.Text_IO.Put_Line ("Demo task terminated by an exception.");
end Demo;
Run_Demo : Demo (new String'("example 1"));
Second_Demo : Demo (new String'("example 2"));
begin
null;
end String_Discriminants;
Another option is to declare the strings as aliased constants in a library level package, but then you are quite close to just having an enumerated discriminant, and should consider that option carefully before discarding it.
I think another solution would be the following:
task body Some_Task_That_Tries_To_Use_Passenger is
Name1 : aliased String := "Foo";
Home1 : aliased String := "Man";
Work1 : aliased String := "Bar";
Passenger1 : aliased Passenger(
Name => Name1'Access,
Workplace_Station => Work1'Access,
Home_Station => Home1'Access
);
begin
--...

I need some answers for solving these problems.I am stuck in these errors whilw programming in Ada using records

I am new to Ada programming.This is my ADA CODE for a program which gives me a list of things when typed a Football legend name in execution time.But I am getting the following errors.Please help me out:
Some of the Errors found are:
1.Discriminants must have a discrete or Access type
2.components "FBClubs cannot be used before end of record declaration
3.discriminant in a variant part must be of discrete part
4."player" is undefined
5."pos" is undefined.
6.no candidate interpretations match the sctuals : = > in call to inherited operation "to_string" at line "type playernames..."
with Ada.Text_Io; use Ada.Text_Io;
with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
Procedure football_record is
type Position is (Goalkeeper,Midfielder,Forward,Defender);
type playernames is new Unbounded_String;
type FBClubs is (ACMilan,Man_United,Aresnal,ParisSt.Germain,Real_Madrid,Liverpool,Chelsea,Man_City,Lille,
Tottenham,Ajax,Juventus,Dortmund,Roma,Santos,Roma,Bayern_Munich,Inter_Milan);
type countries is (England,Argentina,Brazil,France,Italy,Portugal,Spain,Germany,Iran,Japan);
type fbplayer(player:playernames) is
record
WCAppearances:Integer;
pos:Position;
country:countries;
fbclubs:FBClubs;
case player is
when "David Beckham" =>
country:countries:=England;
WCAppearances:Integer:=3;
pos:Position:=Midfielder;
fbclubs:FBClubs:=ACMilan &"+" & Man_United &"+" & Real_Madrid &"+"& ParisSt.Germain;
when "Lionel Messi" =>
country:countries:=Argentina;
WCAppearances:Integer:=1;
pos:Position:=Forward;
fbclubs:FBClubs:=Barcelona;
.....and some other 12 players(legends)..
when others =>
country:countries:=Nil;
WCAppearances:Integer:=Nil;
pos:Position:=Nil;
fbclubs:FBClubs:=Nil;
end case;
end record;
begin
Get(player);
Put_Line(To_String(Integer'Image(player)));
Put_Line(To_String(Integer'Image(FBClubs'Image(fbclubs)));
Put_Line(To_Unbounded_String(Position'Image(pos)));
end football_record;
The biggest problem is that you're mixing code in with a type declaration.
In Ada, putting a case within a record is only for variant records; these are records where some fields exist in certain cases but not others. For example:
type Employee_Type is (Regular, Manager);
type Employee (Emp_Type : Employee_Type) is record
Name : Unbounded_String;
case Emp_Type is
when Manager =>
Managerial_Level : Integer;
when Regular =>
null;
end case;
end record;
This is a variant record; we're assuming here that there are two kinds of employees, and the Managerial_Level field makes sense only for one of those kinds. Records whose type is Regular will not have a Managerial_Level field at all.
This syntax isn't what you would use to return different values of fields. Instead, you need to do this in statements, usually in a procedure or function (or package initialization, or some other places that allow statements).
And since you're not using the variant record syntax, you don't need to make player a discriminant. It doesn't work, anyway; in Ada, a "discriminant" (like Emp_Type in my example) has to be a discrete type like an integer or an enumeration type (Employee_Type is an enumeration type), or an access (access discriminants are an advanced concept). It can't be an Unbounded_String. So you'd want to make player a regular field:
type fbplayer is record
player : Unbounded_String;
pos : Position;
country : countries;
clubs : FBClubs; -- Note name change!
WCAppearances : Integer;
end record;
and create a procedure to fill in the fields:
procedure Fill_In_Player(P : in out fbplayer; Player : Playernames) is
begin
P.Player := Player;
if Player = "David Beckham" then
P.country := England;
P.WCAppearances := 3;
P.pos = Midfielder;
P.clubs := ??? -- see below
elsif Player = "Lionel Messi" then
------- etc.
elsif ------
end if;
end Fill_In_Player;
and then call Fill_In_Player when you have the Player and want to set up the record fields. You have to write statements to do this; you can't do it inside the declaration of a record.
Note that in Ada, case statements can only be used on integer or enumeration types. You can't use them to test for a string, as some other languages allow.
Ada does not treat lower-case and upper-case letters the same in identifiers or keywords. Therefore, fbclubs is the same name as FBClubs, and you can't declare the field
fbclubs : FBClubs;
because of the name conflict. I changed the name.
Finally, it looks like you want FBClubs to hold more than one club. But FBClubs is an enumeration type, and can therefore hold only one value at a time. If you want each player record to contain a list of clubs, you'll need to do something else, such as using one of Ada's container types (like Ada.Containers.Vectors.Vector) or something like
type Set_Of_Clubs is array(FBClubs) of Boolean;
where each array value is true if the player played for that club.
I'm not sure that will take care of all your errors, but it looks like you have a lot of work to do already.

Resources