I am trying to build a knowledge graph using the OWLReady2 libray for Python. Before, I became very familiar with rdflib, but ontologies are far more complex…
The specific example I am trying to do is:
Define persons
Define photos
Provide facts about which photo depicts which persons
Infere which persons are depicted together with which other persons
My working example provides all the definitions needed:
from owlready2 import *
onto = get_ontology("urn:test")
with onto:
class Person(Thing): pass
class Photo(Thing): pass
class depicts(Photo >> Person): pass
class depiction(Person >> Photo): inverse_property = depicts
class depicted_with(Person >> Person): pass
depicted_with_imp = Imp()
depicted_with_imp.set_as_rule("Person(?a), depiction(?a, ?p), depicts(?p, ?b) -> depicted_with(?a, ?b)")
pe1 = Person(name="Person 1")
pe2 = Person(name="Person 2")
pe3 = Person(name="Person 3")
ph1 = Photo()
ph2 = Photo()
ph1.depicts = [pe1, pe2]
ph2.depicts = [pe2, pe3]
sync_reasoner_pellet(infer_property_values = True, infer_data_property_values = True)
assert pe1.depicted_with == [pe2]
assert pe2.depicted_with == [pe1, pe3]
assert pe3.depicted_with == [pe2]
What I cannot wrap my head around is how to write the depicted_with property, so that the inferred property will be created when reasoning.
Related
class Air:
def __init__(self,supplier,delivery,ensurance):
self.supplier = supplier
self.delivery = delivery
self.ensurance = ensurance
def rate_for_custom(self):
return (self.supplier + self.delivery + self.ensurance)
class Sea:
def __init__(self,supplier,delivery,ensurance,port_tax):
self.supplier = supplier
self.delivery = delivery
self.ensurance = ensurance
self.port_tax = port_tax
def rate_for_custom(self):
return (self.supplier + self.delivery + self.ensurance + self.port_tax)
so i'm trying to write a program that calculates the import taxes in israel.
There are two types: one in the sea and one in the air
they both share the same attributes except Sea needs to be calculated with another attribute.
I'm feeling like my code is not good(i'm new to pragramming started a week ago)
is it fine to use two classes in this case? if not what is the solution (by stil using OOP because I need to practice with it)
You can move common parts to a common parent class:
class Transport:
def __init__(self,supplier,delivery,ensurance):
self.supplier = supplier
self.delivery = delivery
self.ensurance = ensurance
def rate_for_custom(self):
return (self.supplier + self.delivery + self.ensurance)
class Air(Transport):
pass
class Sea(Transport):
def __init__(self,supplier,delivery,ensurance,port_tax):
super().__init__(supplier, delivery, ensurance)
self.port_tax = port_tax
def rate_for_custom(self):
return super().rate_for_custom() + self.port_tax
As you want to learn OOP, then you can start to see the concept of inheritance. Here is an example:
# generic class
class Custom:
def __init__(self,*args):
# collect all given parameters:
self.args = args
def rate_for_custom(self):
# just sum all numbers in given parameter:
return sum(self.args)
class Sea(Custom):
def __init__(self,supplier=0,delivery=0,insurance=0, port_tax = 0):
# Call Custom class and provide all relevant parameters:
super().__init__(supplier, delivery, insurance, port_tax)
class Air(Custom):
def __init__(self,supplier=0, delivery=0, insurance=0):
# Call Custom class and provide all relevant parameters:
super().__init__(supplier, delivery, insurance )
print(Custom(100,50,25).rate_for_custom())
# 175
print(Air(supplier=100,delivery=50,insurance=25).rate_for_custom())
# 175
print(Sea(supplier=100,delivery=50,insurance=25,port_tax=25).rate_for_custom())
# 200
Customclass is doing all the job, by summing all parameters it receives in init(). You can call this class providing the values to sum :Custom(100,50,25).rate_for_custom()
Two other classes Airand Sea are inheriting from the Customclass and are just an interface. Using them allows you to use keyword arguments instead of simple arguments: Sea(supplier=100,delivery=50,insurance=25,port_tax=25) which is more friendly.
I was trying to create a nesting of list() class using Python attrs decoractors, and noticed that the attrs.asdict() did not work at some level of subvariables. Such that:
attrs.asdict(mlle) displays ok
attrs.asdict(mlle.list_of_list_of_elements) # FAILS
attrs.asdict(mlle.list_of_list_of_elements[0]) displays ok
My working example is:
import attr
#attr.s
class MyElement(object):
element = attr.ib(default="mydefault", type=str)
#attr.s(slots=True)
class MyListOfElements(object):
one_element = attr.ib(default=attr.Factory(MyElement))
list_of_elements = attr.ib(default=attr.Factory(list), type=list)
def add(self, le):
self.list_of_elements.append(le)
#attr.s(slots=True)
class MyListOfList(object):
version = attr.ib(default=None, type=str)
list_of_list_of_elements = attr.ib(default=attr.Factory(list)) # Where's the dunder for this list?
e1 = MyElement("1.1.1.1")
e1_1 = MyElement("11.11.11.11")
le1 = MyListOfElements()
le1.add(e1)
le1.add(e1_1)
print("le1:", le1)
e2 = MyElement("2.2.2.2")
le2 = MyListOfElements(e2)
le2.list_of_elements.append(e2)
print("le2:", le2)
mlle = MyListOfList()
print("mlle:", mlle)
mlle.list_of_list_of_elements.append(le1)
mlle.list_of_list_of_elements.append(le2)
print("mlle:", mlle)
Now onward to using the attr.asdict() function...
# attr.Dict
print("asdict(mlle):", attr.asdict(mlle))
print("asdict(mlle.lle):", attr.asdict(mlle.list_of_list_of_elements)) # FAILS
print("asdict(mlle.lle[0]):", attr.asdict(mlle.list_of_list_of_elements[0]))
I am quite sure that I did something simple incorrectly as I thought I decorated ALL the nested variables with attrs.
I was more perplex that the use of attr.asdict() is not smoothly available at each dotted subvariable such that mlle and mlle.list_of_list_of_elements[0] works, but not the mlle.list_of_list_of_elements in between.
attr.asdict takes an instance of an attr.s-decorated class. mlle and mlle.list_of_list_of_elements[0] are both instances of attr.s-decorated classes. mlle.list_of_list_of_elements is not.
I am currently designing a software which needs to manage a certain hardware setup.
The hardware setup is as following :
System - The system contains two identical devices, and has certain functionality relative to the entire system.
Device - Each device contains two identical sub devices, and has certain functionality relative to both sub devices.
Sub device - Each sub device has 4 configurable entities (Controlled via the same hardware command - thus I don't count them as a sub-sub device).
What I want to achieve :
I want to control all configurable entities via the system manager (the entities are counted in a serial way), meaning I would be able to do the following :
system_instance = system_manager_class(some_params)
system_instance.some_func(0) # configure device_manager[0].sub_device_manager[0].entity[0]
system_instance.some_func(5) # configure device_manager[0].sub_device_manager[1].entity[1]
system_instance.some_func(8) # configure device_manager[1].sub_device_manager[1].entity[0]
What I have thought of doing :
I was thinking of creating an abstract class, which contains all sub device functions (with a call to a conversion function) and have the system_manager, device_manager and sub_device_manager inherit it. Thus all classes will have the same function name and I will be able to access them via the system manager.
Something around these lines :
class abs_sub_device():
#staticmethod
def convert_entity(self):
sub_manager = None
sub_entity_num = None
pass
def set_entity_to_2(entity_num):
sub_manager, sub_manager_entity_num = self.convert_entity(entity_num)
sub_manager.some_func(sub_manager_entity_num)
class system_manager(abs_sub_device):
def __init__(self):
self.device_manager_list = [] # Initiliaze device list
self.device_manager_list.append(device_manager())
self.device_manager_list.append(device_manager())
def convert_entity(self, entity_num):
relevant_device_manager = self.device_manager_list[entity_num // 4]
relevant_entity = entity_num % 4
return relevant_device_manage, relevant_entity
class device_manager(abs_sub_device):
def __init__(self):
self.sub_device_manager_list = [] # Initiliaze sub device list
self.sub_device_manager_list.append(sub_device_manager())
self.sub_device_manager_list.append(sub_device_manager())
def convert_entity(self, entity_num):
relevant_sub_device_manager = self.sub_device_manager_list[entity_num // 4]
relevant_entity = entity_num % 4
return relevant_sub_device_manager, relevant_entity
class sub_device_manager(abs_sub_device):
def __init__(self):
self.entity_list = [0] * 4
def set_entity_to_2(self, entity_num):
self.entity_list[entity_num] = 2
The code is for generic understanding of my design, not for actual functionality.
The problem :
It seems to me that the system I am trying to design is really generic and that there must be a built-in python way to do this, or that my entire object oriented look at it is wrong.
I would really like to know if some one has a better way of doing this.
After much thinking, I think I found a pretty generic way to solve the issue, using a combination of decorators, inheritance and dynamic function creation.
The main idea is as following :
1) Each layer dynamically creates all sub layer relevant functions for it self (Inside the init function, using a decorator on the init function)
2) Each function created dynamically converts the entity value according to a convert function (which is a static function of the abs_container_class), and calls the lowers layer function with the same name (see make_convert_function_method).
3) This basically causes all sub layer function to be implemented on the higher level with zero code duplication.
def get_relevant_class_method_list(class_instance):
method_list = [func for func in dir(class_instance) if callable(getattr(class_instance, func)) and not func.startswith("__") and not func.startswith("_")]
return method_list
def make_convert_function_method(name):
def _method(self, entity_num, *args):
sub_manager, sub_manager_entity_num = self._convert_entity(entity_num)
function_to_call = getattr(sub_manager, name)
function_to_call(sub_manager_entity_num, *args)
return _method
def container_class_init_decorator(function_object):
def new_init_function(self, *args):
# Call the init function :
function_object(self, *args)
# Get all relevant methods (Of one sub class is enough)
method_list = get_relevant_class_method_list(self.container_list[0])
# Dynamically create all sub layer functions :
for method_name in method_list:
_method = make_convert_function_method(method_name)
setattr(type(self), method_name, _method)
return new_init_function
class abs_container_class():
#staticmethod
def _convert_entity(self):
sub_manager = None
sub_entity_num = None
pass
class system_manager(abs_container_class):
#container_class_init_decorator
def __init__(self):
self.device_manager_list = [] # Initiliaze device list
self.device_manager_list.append(device_manager())
self.device_manager_list.append(device_manager())
self.container_list = self.device_manager_list
def _convert_entity(self, entity_num):
relevant_device_manager = self.device_manager_list[entity_num // 4]
relevant_entity = entity_num % 4
return relevant_device_manager, relevant_entity
class device_manager(abs_container_class):
#container_class_init_decorator
def __init__(self):
self.sub_device_manager_list = [] # Initiliaze sub device list
self.sub_device_manager_list.append(sub_device_manager())
self.sub_device_manager_list.append(sub_device_manager())
self.container_list = self.sub_device_manager_list
def _convert_entity(self, entity_num):
relevant_sub_device_manager = self.sub_device_manager_list[entity_num // 4]
relevant_entity = entity_num % 4
return relevant_sub_device_manager, relevant_entity
class sub_device_manager():
def __init__(self):
self.entity_list = [0] * 4
def set_entity_to_value(self, entity_num, required_value):
self.entity_list[entity_num] = required_value
print("I set the entity to : {}".format(required_value))
# This is used for auto completion purposes (Using pep convention)
class auto_complete_class(system_manager, device_manager, sub_device_manager):
pass
system_instance = system_manager() # type: auto_complete_class
system_instance.set_entity_to_value(0, 3)
There is still a little issue with this solution, auto-completion would not work since the highest level class has almost no static implemented function.
In order to solve this I cheated a bit, I created an empty class which inherited from all layers and stated to the IDE using pep convention that it is the type of the instance being created (# type: auto_complete_class).
Does this solve your Problem?
class EndDevice:
def __init__(self, entities_num):
self.entities = list(range(entities_num))
#property
def count_entities(self):
return len(self.entities)
def get_entity(self, i):
return str(i)
class Device:
def __init__(self, sub_devices):
self.sub_devices = sub_devices
#property
def count_entities(self):
return sum(sd.count_entities for sd in self.sub_devices)
def get_entity(self, i):
c = 0
for index, sd in enumerate(self.sub_devices):
if c <= i < sd.count_entities + c:
return str(index) + " " + sd.get_entity(i - c)
c += sd.count_entities
raise IndexError(i)
SystemManager = Device # Are the exact same. This also means you can stack that infinite
sub_devices1 = [EndDevice(4) for _ in range(2)]
sub_devices2 = [EndDevice(4) for _ in range(2)]
system_manager = SystemManager([Device(sub_devices1), Device(sub_devices2)])
print(system_manager.get_entity(0))
print(system_manager.get_entity(5))
print(system_manager.get_entity(15))
I can't think of a better way to do this than OOP, but inheritance will only give you one set of low-level functions for the system manager, so it wil be like having one device manager and one sub-device manager. A better thing to do will be, a bit like tkinter widgets, to have one system manager and initialise all the other managers like children in a tree, so:
system = SystemManager()
device1 = DeviceManager(system)
subDevice1 = SubDeviceManager(device1)
device2 = DeviceManager(system)
subDevice2 = SubDeviceManager(device2)
#to execute some_func on subDevice1
system.some_func(0, 0, *someParams)
We can do this by keeping a list of 'children' of the higher-level managers and having functions which reference the children.
class SystemManager:
def __init__(self):
self.children = []
def some_func(self, child, *params):
self.children[child].some_func(*params)
class DeviceManager:
def __init__(self, parent):
parent.children.append(self)
self.children = []
def some_func(self, child, *params):
self.children[child].some_func(*params)
class SubDeviceManager:
def __init__(self, parent):
parent.children.append(self)
#this may or may not have sub-objects, if it does we need to make it its own children list.
def some_func(self, *params):
#do some important stuff
Unfortunately, this does mean that if we want to call a function of a sub-device manager from the system manager without having lots of dots, we will have to define it again again in the system manager. What you can do instead is use the built-in exec() function, which will take in a string input and run it using the Python interpreter:
class SystemManager:
...
def execute(self, child, function, *args):
exec("self.children[child]."+function+"(*args)")
(and keep the device manager the same)
You would then write in the main program:
system.execute(0, "some_func", 0, *someArgs)
Which would call
device1.some_func(0, someArgs)
Here's what I'm thinking:
SystemManager().apply_to_entity(entity_num=7, lambda e: e.value = 2)
class EntitySuperManagerMixin():
"""Mixin to handle logic for managing entity managers."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs) # Supports any kind of __init__ call.
self._entity_manager_list = []
def apply_to_entity(self, entity_num, action):
relevant_entity_manager = self._entity_manager_list[index // 4]
relevant_entity_num = index % 4
return relevant_entity_manager.apply_to_entity(
relevant_entity_num, action)
class SystemManager(EntitySuperManagerMixin):
def __init__(self):
super().__init__()
# An alias for _entity_manager_list to improve readability.
self.device_manager_list = self._entity_manager_list
self.device_manager_list.extend(DeviceManager() for _ in range(4))
class DeviceManager(EntitySuperManagerMixin):
def __init__(self):
super().__init__()
# An alias for _entity_manager_list to improve readability.
self.sub_device_manager_list = self._entity_manager_list
self.sub_device_manager_list.extend(SubDeviceManager() for _ in range(4))
class SubDeviceManager():
"""Manages entities, not entity managers, thus doesn't inherit the mixin."""
def __init__(self):
# Entities need to be classes for this idea to work.
self._entity_list = [Entity() for _ in range(4)]
def apply_to_entity(self, entity_num, action):
return action(self._entity_list[entity_num])
class Entity():
def __init__(self, initial_value=0):
self.value = initial_value
With this structure:
Entity-specific functions can stay bound to the Entity class (where it belongs).
Manager-specific code needs to be updated in two places: EntitySuperManagerMixin and the lowest level manager (which would need custom behavior anyway since it deals with the actual entities, not other managers).
The way i see it if you want to dynamically configure different part of system you need some sort of addressing so if you input an ID or address with some parameter the system will know with address on which sub sistem you are talking about and then configure that system with parameter.
OOP is quite ok for that and then you can easily manipulate such data via bitwise operators.
So basic addressing is done via binary system , so to do that in python you need first to implement an address static attribute to your class with perhaps some basic further detailing if system grows.
Basic implementation of addres systems is as follows:
bin(71)
1010 1011
and if we divide it into nibbles
1010 - device manager 10
1011 - sub device manager 11
So in this example we have system of 15 device managers and 15 sub device menagers, and every device and sub device manager has its integer address.So let's say you want to access device manager no10 with sub device manager no11. You would need their address which is in binary 71 and you would go with:
system.config(address, parameter )
Where system.config funcion would look like this:
def config(self,address, parameter):
device_manager = (address&0xF0)>>4 #10
sub_device_manager = address&0xf # 11
if device_manager not in range(self.devices): raise LookupError("device manager not found")
if sub_device_manager not in range(self.devices[device_manager].device): raise LookupError("sub device manager not found")
self.devices[device_manager].device[sub_device_manager].implement(parameter)
In layman you would tell system that sub_device 11 from device 10 needs configuration with this parameter.
So how would this setup look in python inheritance class of some base class of system that could be then composited/inherited to different classes:
class systems(object):
parent = None #global parent element, defaults to None well for simplicity
def __init__(self):
self.addrMASK = 0xf # address mask for that nibble
self.addr = 0x1 # default address of that element
self.devices = [] # list of instances of device
self.data = { #some arbitrary data
"param1":"param_val",
"param2":"param_val",
"param3":"param_val",
}
def addSubSystem(self,sub_system): # connects elements to eachother
# checks for valiability
if not isinstance(sub_system,systems):
raise TypeError("defined input is not a system type") # to prevent passing an integer or something
# appends a device to system data
self.devices.append(sub_system)
# search parent variables from sub device manager to system
obj = self
while 1:
if obj.parent is not None:
obj.parent.addrMASK<<=4 #bitshifts 4 bits
obj.parent.addr <<=4 #bitshifts 4 bits
obj = obj.parent
else:break
#self management , i am lazy guy so i added this part so i wouldn't have to reset addresses manualy
self.addrMASK <<=4 #bitshifts 4 bits
self.addr <<=4 #bitshifts 4 bits
# this element is added so the obj address is coresponding to place in list, this could be done more eloquently but i didn't know what are your limitations
if not self.devices:
self.devices[ len(self.devices)-1 ].addr +=1
self.devices[ len(self.devices)-1 ].parent = self
# helpful for checking data ... gives the address of system
def __repr__(self):
return "system at {0:X}, {1:0X}".format(self.addr,self.addrMASK)
# extra helpful lists data as well
def __str__(self):
data = [ '{} : {}\n'.format(k,v) for k,v in self.data.items() ]
return " ".join([ repr(self),'\n',*data ])
#checking for data, skips looping over sub systems
def __contains__(self,system_index):
return system_index-1 in range(len(self.data))
# applying parameter change -- just an example
def apply(self,par_dict):
if not isinstance(par_dict,dict):
raise TypeError("parameter must be a dict type")
if any( key in self.data.keys() for key in par_dict.keys() ):
for k,v in par_dict.items():
if k in self.data.keys():
self.data[k]=v
else:pass
else:pass
# implementing parameters trough addresses
def implement(self,address,parameter_dictionary):
if address&self.addrMASK==self.addr:
if address-self.addr!=0:
item = (address-self.addr)>>4
self.devices[item-1].implement( address-self.addr,parameter_dictionary )
else:
self.apply(parameter_dictionary)
a = systems()
b = systems()
a.addSubSystem(b)
c = systems()
b.addSubSystem(c)
print('a')
print(a)
print('')
print('b')
print(b)
print('')
print('c')
print(c)
print('')
a.implement(0x100,{"param1":"a"})
a.implement(0x110,{"param1":"b"})
a.implement(0x111,{"param1":"c"})
print('a')
print(a)
print('')
print('b')
print(b)
print('')
print('c')
print(c)
print('')
I'm defining database-classes for SQLAlchemy, like so:
class People(Base):
__tablename__ = 'people'
id = Column(Integer, primary_key=True, unique=True)
name = Column(Text)
haircolor = Column(Text)
height = Column(Numeric)
def __init__(self, id, name, haircolor, height):
self.id = id
self.name = name
self.haircolor = haircolor
self.height = height
Writing this out manually is tedious repeated work for many tables. Since the structure of the class-definitions is always the same, there must be a way to configure vim to write a part of the definition for you, e.g. when adding the columns the init-function is automagically defined at the same time.
What are the tools vim provides to facilitate automation of somewhat complex code structures?
snippets are like the built-in :abbreviate on steroids, usually with parameter insertions, mirroring, and multiple stops inside them. One of the first, very famous (and still widely used) Vim plugins is snipMate (inspired by the TextMate editor); unfortunately, it's not maintained any more; though there is a fork. A modern alternative (that requires Python though) is UltiSnips. There are more, see this list on the Vim Tips Wiki.
There are three things to evaluate: First, the features of the snippet engine itself, second, the quality and breadth of snippets provided by the author or others; third, how easy it is to add new snippets.
Author's note/solution:
This can be done with UltiSnips together with python.snippets. Additionally to the answers above, here's how I've extended python.snippets to work with the code-example in the question.
To create a SQLAlchemy specific class as in the example above, add the following code to the python.snippets file (Usually located at .vim/UltiSnips/python.snippets):
########################################
# Custom snippets #
########################################
global !p
def write_init_body_sa(args, parents, snip):
parents = [p.strip() for p in parents.split(",")]
parents = [p for p in parents if p != 'object']
for arg in args:
snip += "self.%s = %s" % (arg, arg)
def write_sqlalchemy_columns(args, parents, snip):
parents = [p.strip() for p in parents.split(",")]
parents = [p for p in parents if p != 'object']
for p in parents:
snip += "__tablename__ = '%s'" % (p.lower())
for arg in args:
snip += "%s = Column()" % (arg)
endglobal
snippet saclass "SQLAlchemy class" b
class ${1:MyClass}(${2:Base}):`!p
snip >> 1
snip.rv = ""
args = get_args(t[3])
write_sqlalchemy_columns(args, t[1], snip)
`
def __init__(self$3):`!p
snip.rv = ""
snip >> 2
args = get_args(t[3])
write_init_body_sa(args, t[2], snip)
`
$0
endsnippet
I have the following classes defined that inherits from some other classes. Goblin is a Python dependency package that I am extending from.
class AnnotatedVertexProperty(goblin.VertexProperty):
notes = goblin.Property(goblin.String)
datetime = goblin.Property(DateTime)
class KeyProperty(goblin.Property):
def __init__(self, data_type, *, db_name=None, default=None, db_name_factory=None):
super().__init__(data_type, default=None, db_name=None, db_name_factory=None)
class TypedVertex(goblin.Vertex):
def __init__(self):
self.vertex_type = self.__class__.__name__.lower()
super().__init__()
class TypedEdge(goblin.Edge):
def __init__(self):
self.edge_type = self.__class__.__name__.lower()
super().__init__()
class Airport(TypedVertex):
#label
type = goblin.Property(goblin.String)
airport_code = KeyProperty(goblin.String)
airport_city = KeyProperty(goblin.String)
airport_name = goblin.Property(goblin.String)
airport_region = goblin.Property(goblin.String)
airport_runways = goblin.Property(goblin.Integer)
airport_longest_runway = goblin.Property(goblin.Integer)
airport_elev = goblin.Property(goblin.Integer)
airport_country = goblin.Property(goblin.String)
airport_lat = goblin.Property(goblin.Float)
airport_long = goblin.Property(goblin.Float)
At run time, I need to iterate thrown each one of the properties and be able to determine its class type (keyProperty or goblin.Property) I also need to be able to determine if the value is a string, integer, etc...
During instantiation, I create an airport object and set the values as following:
lhr = Airport()
lhr.airport_code = 'LHR'
print (lhr.airport_code.__class__.mro())
lhr.airport_city = 'London'
lhr.airport_name = 'London Heathrow International Airport'
lhr.airport_region = 'UK-EN'
lhr.airport_runways = 3
lhr.airport_longest_runway = 12395
lhr.airport_elev = 1026
lhr.airport_country = 'UK'
lhr.airport_lat = 33.6366996765137
lhr.airport_long = -84.4281005859375
However when I inspect the object while debugging it, all I get is the property name, defined as string and values, defined as string, integer, etc... How can I check for the object type for each property?
Any help or suggestions on how to handle this ?
I figured out what I was looking for. I had to call element.class.dict.items(): and I can get a dictionary with all the properties, mappings, etc...