def add_relationship(self, relationship=None): id = str(len(self.relationships) + 1) if relationship is None: relationship = Relationship(name="Relationship" + id, id=id) elif relationship.id is None: relationship.id = id self.relationships.append(relationship)
def __init__(self, Id=None, name=None, save=True, depth=0): r = redis.StrictRedis(host='localhost', port=6379, db=0) if Id == None and name is not None: Id = r.hget('name2Id:0', name) if Id == None and name is not None: with r.pipeline() as pipe: while 1: try: pipe.watch('numChars:0') self.Id = int(pipe.get('numChars:0')) pipe.incr('numChars:0') pipe.execute() break except WatchError: continue finally: pipe.reset() r.hset('character:0:'+str(self.Id), 'name', name) r.hsetnx('name2Id:0', name, str(self.Id)) elif Id is not None: self.Id = Id else: return Character.chars[self.Id]=self self.traits={} if r.exists('character:0:'+str(self.Id)): traits = r.hgetall('character:0:'+str(self.Id)) for trait in traits.keys(): self.traits[trait.decode('utf-8')] = traits[trait].decode('utf-8') else: raise(Exception()) #Set up traits here self.relationships = {} if r.exists('relationships:0:'+str(self.Id)): rels = r.smembers('relationships:0:'+str(self.Id)) for rel in rels: myRels = {} if r.exists('relationship:0:'+str(self.Id)+':'+str(int(rel))): relMems = r.hgetall('relationship:0:'+str(self.Id)+':'+str(int(rel))) if not r.exists('relVal:0:'+str(self.Id)+':'+str(int(rel))): r.hmset('relVal:0:'+str(self.Id)+':'+str(int(rel)), {key:0 for key in relMems}) relVals = r.hgetall('relVal:0:'+str(self.Id)+':'+str(int(rel))) for rMem in relMems.keys(): myRels[rMem.decode('utf-8')] = (float(relMems[rMem]), float(relVals[rMem])) try: self.relationships[int(rel)] = Relationship(myRels, max(myRels.values(), key=lambda x: x[0])[0], self, getById(int(rel), depth-1)) except: try: Character.danglingRels[int(rel)][self.Id] = dict(myRels) except: Character.danglingRels[int(rel)] = {self.Id: dict(myRels)} if self.Id in Character.danglingRels: for relId in Character.danglingRels[self.Id]: try: rel = getById(relId) rel.relationships[self.Id] = Relationship(Character.danglingRels[self.Id][relId], max(Character.danglingRels[self.Id][relId].values(), key=lambda x: x[0])[0], rel, self) except: pass if save: r.save()
def addNewRelationship(self, sourceId, destId): relationship = Relationship() relationship.sourceSignificantEventId = sourceId relationship.destSignificantEventId = destId relationship.id = 0 if len(self.relationships) == 0 else ( max(list(self.relationships.keys())) + 1) self.relationships[relationship.id] = relationship
def update_relationship(self, other, relationship_type): if other in self.current_relationships.keys(): relationship = self.current_relationships[other] # Don't have a relationship with this person # Creating a new relationship with this person else: relationship = Relationship(self, other) self.current_relationships[other] = relationship relationship.update_relationship(relationship_type, 1)
def addRelationship(self, entityName, relationshipTypeLocal, relationshipTypeForeign, attributes=None): """ Add a binary relationship with a given foreign Entity Parameters ---------- self: object reference entityName: name of foreign Entity relationshipTypeLocal: the cardinality of the relationship on the local side relationshipTypeForeign: the cardinality of the relationship on the foreign side attributes: array of attribute names belonging to the Relationship Returns ------- None """ r = Relationship(entityName, relationshipTypeLocal, relationshipTypeForeign, attributes) self.relationships.append(r)
def findUpdateComponents(self): '''return a dictionary of components used in the updateToOne or updateToMany Methods.''' results = {} rels = Relationship.find(self, Contained=False) for rel in rels: if rel.components[0].id != self.id: component = rel.components[0] Type = rel.Type.split('-')[0] else: component = rel.components[1] Type = rel.Type.split('-')[1] if Type in results: results[Type].append(component) else: results[Type] = [component] imports = [] if '1' in results: imports.append('updateToOne') if 'M' in results: imports.append('updateToMany') if results: self.imports.append('from %s.utils import %s' % (self.zenpack.id, ",".join(sorted(imports)))) self.updateComponents = results
def custompaths(self): '''for non-contained child components return a dict {Type: component, parent component of the parent components} ''' custompaths = {} rels = Relationship.find(self, Contained=False, First=False) for rel in rels: for component in rel.components: if component == self: continue prel = Relationship.find(component, Contained=True, First=False) if prel: prel = prel[0] if not rel.Type in custompaths.keys(): custompaths[rel.Type] = [(component, prel.components[0])] return custompaths """obj = self.context.${first_component}()
def create_relationship(self, parent_id=None, child_id=None, name=""): """Creates a relationship in the selected Vector, the relationship will reference the parent and child nodes.""" if len(self.vectors) == 0: print("No existent vector") return parent = self.vectors[self.selected_vector].nodes[parent_id] child = self.vectors[self.selected_vector].nodes[child_id] relationship = Relationship(name=name, id=None, parent=parent, child=child) self.vectors[self.selected_vector].add_relationship(relationship)
def addRelation(self, other, relation, recip=True): r = redis.StrictRedis(host='localhost', port=6379, db=0) r.sadd('relationships:0:'+str(self.Id), str(other.Id)) relImp = {key:value[0] for (key,value) in relation.items()} relVal = {key:value[1] for (key,value) in relation.items()} r.hmset('relationship:0:'+str(self.Id)+':'+str(other.Id), relImp) r.hmset('relVal:0:'+str(self.Id)+':'+str(other.Id), relVal) if other.Id in self.relationships: for key in relation: self.relationships[other.Id].rels[key] = relation[key] if relation[key][0] > self.relationships[other.Id].importance: self.relationships[other.Id].importance = relation[key][0] else: self.relationships[other.Id] = Relationship(relation, max(relation.values(), key=lambda x: x[0])[0], self, other) if recip: for rel in relation: try: relTypes[rel]['recip'](self, other) except: continue
def get_event_data(self, event_id): """Retrieves the complete event data given an event ID, returns it in a dictionary with the event config and the vectors list""" # Retrieve event config ec_test = self.get_event_config(event_id) if ec_test is None: print("Invalid ID") return event_config = EventConfiguration.create_from_dictionary(ec_test) event_config.set_object_id(event_id) # Get Vector ID list vector_id_list = ec_test.get("vector_obj_ids") vector_list = [] for id in vector_id_list: vdict = self.get_vector(id) vector = Vector.create_from_dictionary(vdict) vector.set_object_id(id) node_id_list = vdict.get("node_obj_ids") relationship_id_list = vdict.get("relationship_obj_ids") nodes_map = {} for n_id in node_id_list: ndict = self.get_node(n_id) node = Node.create_from_dictionary(ndict) node.set_object_id(n_id) nodes_map[node.get_id()] = node vector.add_node(node) for r_id in relationship_id_list: rdict = self.get_relationship(r_id) relationship = Relationship.create_from_dictionary(rdict) relationship.set_object_id(r_id) relationship.child = nodes_map[rdict.get('child id')] relationship.parent = nodes_map[rdict.get('parent id')] vector.add_relationship(relationship) vector_list.append(vector) out_map = {"event_config": event_config, "vectors": vector_list} return out_map
def readEER(entities): ''' Reads in JSON EER file and creates relevant objects as needed Parameters ---------- entities: a JSON file containing the structure of the entities in the ER model Returns ------- toReturn: an array of entity objects ''' toReturn = [] for entity in entities['entities']: attributes = [] for attribute in entity['attributes']: tempAttribute = ERAttribute(attribute['AttributeName'], attribute['isIdentifier'], attribute['isMultiValued'], attribute['composedOf']) attributes.append(tempAttribute) relationships = [] for relationship in entity['relationships']: tempRelationship = Relationship( relationship['Entity'], relationship['RelationTypeLocal'], relationship['RelationTypeForeign'], relationship['relationAttributes']) relationships.append(tempRelationship) tempEntity = Entity(entity['name'], entity['isStrong'], attributes, relationships) toReturn.append(tempEntity) return toReturn
# volume = Quantity("Volume", 1, 1, [0, 1, 2], False) # outflow = Quantity("Outflow", 1, 1, [0, 1, 2], False) """ test scenario2 """ inflow = Quantity("Inflow", 0, 0, [0, 1], True, "G") volume = Quantity("Volume", 0, 0, [0, 1, 2], False, "G") outflow = Quantity("Outflow", 0, 0, [0, 1, 2], False, "G") pressure = Quantity("Pressure", 0, 0, [0, 1, 2], False, "G") height = Quantity("Height", 0, 0, [0, 1, 2], False, "G") quantities = [inflow, volume, outflow] extendedQuantities = [inflow, volume, outflow, pressure, height] initialState = State(0, quantities) extendedInitialState = State(0, extendedQuantities) R1 = Relationship("I", 1, "Inflow", "Volume") R2 = Relationship("I", -1, "Outflow", "Volume") R3 = Relationship("P", 1, "Volume", "Outflow") R4 = Relationship("VC", 2, "Volume", "Outflow") R5 = Relationship("VC", 0, "Volume", "Outflow") E1 = Relationship("P", 1, "Volume", "Pressure") E2 = Relationship("P", 1, "Volume", "Height") E3 = Relationship("VC", 2, "Volume", "Pressure") E4 = Relationship("VC", 0, "Volume", "Pressure") E5 = Relationship("VC", 2, "Volume", "Height") E6 = Relationship("VC", 0, "Volume", "Height") relationships = [R1, R2, R3, R4, R5] extendedRelationships = [R1, R2, R3, R4, R5, E1, E2, E3, E4, E5, E6]
def ManyRelationships(self): """return all of the ManyRelationships related to this component.""" rels = Relationship.find(self, First=True, Types=['1-M', 'M-M']) return rels
def relations(self): '''Find all the relationships that contain this component''' #return self.zenpack.relationshipLookup(self) return Relationship.find(self)