def __init__(self): self.ID = None self.DesignParameters = Values() self.Responses = Values() self.Success = False self.Objectives = None self.Constraints = None self.Fitness = None
def __init__(self, unique_id, model, country_of_origin, pos): ''' Initializes Newcomer Class (NC) DQ - documentation quality pos - position in x,y space dq_min - refers to the IND standard decision time - time until IND must make a decision. current_step - refers to what position the agent is in the sequence of actions ''' super().__init__(unique_id, model) self.pos = pos self.coa = None #ls is Legal Status self.ls = 'edp' #externally displaced person self.decision_time = 8 #28 days is the length of the general asylum procedure self.intake_time = 4 #time until transfer out of ter apel self.coo = country_of_origin self.specs = self.model.specs[ self.coo] #specs contains bournoulli distribution params self.ext_time = 90 #duration of extended procedure #draw first decision outcome self.first = bernoulli.rvs(self.specs[0], size=1)[0] #second decision outcome not drawn unless necessary self.second = None # new comer values self.values = Values(10, 70, 30, 70, 50) self.testing_activities = False
# @app.route("/") # def main(): # return render_template('index.html') test = [] print(len(test)) # assistant = Assistant() # # testing sensing devices assistant.addSensingDevice("Light", "home/sensorData", 60) assistant.addSensingDevice("Temperature", "home/sensorData", 60) assistant.getSensingDevices()[0].message = "220" tempSensor = assistant.getSensingDevices()[1] tempSensor.message = "10" print(assistant.getSensingDevices()[0].name) print(Values().getValue("Light")) # #testing acting devices assistant.addActingDevice("Light control relat", "home/actuators") actor = assistant.getActingDevices()[0] print(actor.currentState) actor.performAction(actor.possibleActions.TURN_ON) print(actor.currentState) assistant.addScenario(actor, actor.possibleActions.TURN_OFF) scenario = assistant.getScenarios()[0] valueCond = ValueCondition("Light", "<", 250) scenario.addCondition(valueCond) valueCond2 = ValueCondition("Temperature", ">", 20) scenario.addCondition(valueCond2) print(scenario.checkConditionsSatisfaction()) tempSensor.message = "30"
import math from Values import Values from Uncertainties import * # Universal mass_water = scale(Values(100, 0.5), 0.001) mass_washer = scale(Values(5.56, 0.005), 0.001) heat_capacity_water = Values(4200, 20) # joules per kilogram celsius # Energy absorbed by water (with uncertainties) # trial 1 t_initial_water_1 = Values(21.7, 0.5) t_final_water_1 = Values(22.5, 0.5) delta_t_1 = subtract(t_final_water_1, t_initial_water_1) # print("del t: " + delta_t_1.output_absolute()) mass_test = multiply(mass_water, heat_capacity_water) # print("mc: " + mass_test.output_absolute()) q_water_1 = multiply(mass_test, delta_t_1) # print("Q1: " + q_water_1.output_self()) # trial 2 t_initial_water_2 = Values(22.5, 0.5) t_final_water_2 = Values(23.1, 0.5) delta_t_2 = subtract(t_final_water_2, t_initial_water_2)
def __init__(self, unique_id, model, city): super().__init__(unique_id, model) self.azcs = set([]) self.activity_centers = set([]) self.capacities = dict() self.average_capacities = self.capacities self.model = model self.assessment_frequency = 30 #monthly checks self.projection_time = 180 #6 month construction time self.budget = 300000 #arbitrary and to be replaced self.city = city self.newcomers = set([]) self.shock_assessment_frequency = 10 self.shock_threshold = 5 self.capacity_threshold = .75 self.buildings_under_construction = set([]) self.shock = False # is current influx an anomoly self.crisis = False # is there sufficient housing # for current influx self.problematic = False # is change in policy required self.shock_reference = None self.delta = None #rate of change #ter apel shock check self.sum_ta = 0 self.squared_ta = 0 self.counter_ta = 1 self.variance_ta = None self.var_copy_ta = None #policies self.policy = self.house self.collection_fee = 194 self.IND = None self.ta = False # coa values # self_enhancement actions actions increase available capital, # such as consolidation which involves transferring newcomers # from low capacity AZCs into a few high capacity AZC. Empty AZCs can either be sold off or # operated at minimal cost until required. During shock periods, # COA can satisfy SE by requesting additional government funding. self.self_enhancement = 60 # COA satisfies ST by investing its available capital to improve living # conditions for its residents. Available capital is invested facilities, # which are a generic building which can host activities, aimed at satisfying # newcomer values. During shock periods, providing housing to newcomers over # the current capacity satisfies ST. self.self_transcendence = 70 # COA satisfies C by employing "safe but segregated" policies. That is, # separating newcomers by legal status and targeting service delivery on # those who will likely receive status. During shock-periods, C is satisfied # by building robust facilities. That is, favoring AZC developments with a # degree of redundancy; two 100 capacity AZCs instead of one 200, for example. self.conservatism = 60 # COA satisfies OTC by employing integration policies which are available # to all AS newcomers, regardless of the likelihood of their final status. # During shock periods periods, OTC is satisfied by the construction of # flexible housing. Flexibility, here, means ability to serve multiple functions. # Such housing could serve local populations post shock. self.openness_to_change = 30 self.values = Values(10, self.self_enhancement, self.self_transcendence, self.conservatism, self.openness_to_change) #####ACTIONS###### self.actions = set([]) self.action_names = ['Consolidate', 'Invest', 'Segregate', 'Integrate'] #add actions to action set for action in range(len(self.action_names)): #make action w a name, actor, and index of value to be satisfied if action == 0: current_action = activity.Consolidate( self.action_names[action], self, action) self.actions.add(current_action) elif action == 1: current_action = activity.Invest(self.action_names[action], self, action) self.actions.add(current_action) elif action == 2: current_action = activity.Segregate(self.action_names[action], self, action) self.actions.add(current_action) elif action == 3: current_action = activity.Integrate(self.action_names[action], self, action) self.actions.add(current_action)
class COA(Organization): def __init__(self, unique_id, model, city): super().__init__(unique_id, model) self.azcs = set([]) self.activity_centers = set([]) self.capacities = dict() self.average_capacities = self.capacities self.model = model self.assessment_frequency = 30 #monthly checks self.projection_time = 180 #6 month construction time self.budget = 300000 #arbitrary and to be replaced self.city = city self.newcomers = set([]) self.shock_assessment_frequency = 10 self.shock_threshold = 5 self.capacity_threshold = .75 self.buildings_under_construction = set([]) self.shock = False # is current influx an anomoly self.crisis = False # is there sufficient housing # for current influx self.problematic = False # is change in policy required self.shock_reference = None self.delta = None #rate of change #ter apel shock check self.sum_ta = 0 self.squared_ta = 0 self.counter_ta = 1 self.variance_ta = None self.var_copy_ta = None #policies self.policy = self.house self.collection_fee = 194 self.IND = None self.ta = False # coa values # self_enhancement actions actions increase available capital, # such as consolidation which involves transferring newcomers # from low capacity AZCs into a few high capacity AZC. Empty AZCs can either be sold off or # operated at minimal cost until required. During shock periods, # COA can satisfy SE by requesting additional government funding. self.self_enhancement = 60 # COA satisfies ST by investing its available capital to improve living # conditions for its residents. Available capital is invested facilities, # which are a generic building which can host activities, aimed at satisfying # newcomer values. During shock periods, providing housing to newcomers over # the current capacity satisfies ST. self.self_transcendence = 70 # COA satisfies C by employing "safe but segregated" policies. That is, # separating newcomers by legal status and targeting service delivery on # those who will likely receive status. During shock-periods, C is satisfied # by building robust facilities. That is, favoring AZC developments with a # degree of redundancy; two 100 capacity AZCs instead of one 200, for example. self.conservatism = 60 # COA satisfies OTC by employing integration policies which are available # to all AS newcomers, regardless of the likelihood of their final status. # During shock periods periods, OTC is satisfied by the construction of # flexible housing. Flexibility, here, means ability to serve multiple functions. # Such housing could serve local populations post shock. self.openness_to_change = 30 self.values = Values(10, self.self_enhancement, self.self_transcendence, self.conservatism, self.openness_to_change) #####ACTIONS###### self.actions = set([]) self.action_names = ['Consolidate', 'Invest', 'Segregate', 'Integrate'] #add actions to action set for action in range(len(self.action_names)): #make action w a name, actor, and index of value to be satisfied if action == 0: current_action = activity.Consolidate( self.action_names[action], self, action) self.actions.add(current_action) elif action == 1: current_action = activity.Invest(self.action_names[action], self, action) self.actions.add(current_action) elif action == 2: current_action = activity.Segregate(self.action_names[action], self, action) self.actions.add(current_action) elif action == 3: current_action = activity.Integrate(self.action_names[action], self, action) self.actions.add(current_action) def house(self, newcomer): #candidates candidates = [] #find all coas coas = [coa for coa in self.model.schedule.agents if type(coa) is COA] #not ter appel coas = [coa for coa in coas if not coa.ta] #only relevant azcs for coa in coas: for azc in coa.azcs: if azc.occupant_type == newcomer.ls: candidates.append(azc) destination = min(candidates, key=attrgetter('occupancy')) self.move(newcomer, destination) def social_house(self, newcomer): ''' Add newcomer to TR housing ''' destination = self.city.social_housing self.move(newcomer, destination) def move(self, newcomer, destination): ''' moves newcomer to a destination updates occupancies of previous and new destinations ''' newcomer.loc.occupancy -= 1 if newcomer in newcomer.loc.occupants: newcomer.loc.occupants.remove(newcomer) destination.occupancy += 1 #update occupancy #take first one, in future, evaluate buildings on some criteria house_loc = destination.pos #where is it #add noise so agents don't overlap #x = house_loc[0] #+ np.random.randint(-20,20) #y = house_loc[1] - 10 + int(20*((1+ destination.occupancy) / destination.capacity)) self.model.grid.move_agent(newcomer, house_loc) #place destination.occupants.add(newcomer) #add agent to building roster newcomer.loc = destination #update agent location if type(destination) is Hotel: newcomer.coa = destination.city.coa else: newcomer.coa = destination.coa def min_house(self, newcomer): '''COA policy houses newcomer in the most empty AZC ''' #candidates candidates = [] #find all coas coas = [coa for coa in self.model.schedule.agents if type(coa) is COA] #not ter appel coas = [coa for coa in coas if not coa.ta] #only relevant azcs for coa in coas: for azc in coa.azcs: candidates.append(azc) destination = min(candidates, key=attrgetter('occupancy')) self.move(newcomer, destination) def get_total_cap(self): '''total available room''' return sum([azc.capacity for azc in self.azcs]) def get_total_occupancy(self): '''total occupied space''' return sum([azc.occupancy for azc in self.azcs]) def get_occupancy_pct(self): '''room to space ratio''' return self.get_total_occupancy() / (self.get_total_cap() + 1) def hotel_house(self, newcomer): ''' min-house till near max, then send to hotel ''' #until there's no room, house in azc if self.get_total_occupancy() / self.get_total_cap() < .90: self.min_house(newcomer) #then house in hotel else: destination = [x for x in self.city.buildings if type(x) is Hotel][0] self.move(newcomer, destination) self.budget -= destination.cost_pp def evaluate_need(self, building, projection): ''' How many newcomers need housing ''' return projection - building.capacity def project_dc(self): total = 0 #delta begins as null bc it requires a shock to be activated if not self.delta: total = self.get_total_occupancy() else: for azc in self.azcs: total += self.delta * 180 ''' if self.shock: total += self.project_2(azc)[0] else: total += self.project(azc)[0] ''' return max(0, total / self.get_total_cap()) def project_2(self, building): ''' variation on project function ''' difference = building.occupancy - self.capacities[building] time_diff = self.model.schedule.steps - self.shock_reference delta = difference / self.assessment_frequency #assuming monthly assessment return self.capacities[building] + delta * (time_diff + 50), delta def project(self, building): ''' Calculates difference between current and previous occupancies to get a rate of change, delta, uses that to estimate, project, occupancy in 180 days time if the rate of change were to continue ''' difference = building.occupancy - self.capacities[building] delta = difference / self.assessment_frequency #assuming monthly assessment self.delta = delta return self.capacities[building] + delta * self.projection_time, delta def evaluate_cost(self, need, building): ''' returns hotel cost, per person per month or conversion cost of an empty building ''' if type(building) is Empty: return building.convert_cost elif type(building) is Hotel: return need * building.cost_pp def online_variance_ta(self, building): ''' Calculates online variance for anomoly detection ''' self.counter_ta += 1 sum_ta = self.sum_ta squared_ta = self.squared_ta variance_ta = self.variance_ta sum_ta += building.occupancy squared_ta += building.occupancy**2 variance_ta = np.sqrt( (self.counter_ta * self.squared_ta - self.sum_ta**2) / (self.counter_ta * (self.counter_ta - 1))) return (variance_ta, squared_ta, sum_ta) def shock_check(self, variance_ta): '''checks if current amount of arrivals is abnormal ''' return self.model.ter_apel.occupancy / variance_ta > self.shock_threshold def update_capacities(self): #update monthly rate of change for k, v in self.capacities.items(): self.capacities[k] = k.occupancy def problematic_check(self): problematic = False #look at rate of change for each building for building, occupancy in self.capacities.items(): #project rate of growth project = self.project(building) #update capacities self.capacities[building] = building.occupancy if project[0] > building.capacity * self.capacity_threshold: problematic = True break else: self.project(building) #all must be manageable for normal housing policies return problematic def crisis_check(self): ''' Checks if the projected amount of inflow is greater than the capacity in the city ''' total_need = 0 #takes into account future capacities if building under construction if self.buildings_under_construction: total_need -= sum( [x.capacity for x in self.buildings_under_construction]) for building, occupancy in self.capacities.items(): #how many in 6 months project = self.project(building) #difference between that and occupancy total_need += self.evaluate_need(building, project[0]) return (total_need > 0, total_need) def evaluate_options(self, need): ''' if in crisis, check cost of each hotel v empty building conversion need = amount of people over capacity ''' #placeholder average_duration = 50 #gather candidates hotel = [x for x in self.city.buildings if type(x) is Hotel][0] candidates = [x for x in self.city.buildings if type(x) is Empty] candidates = [x for x in candidates if self.budget > x.convert_cost] candidates.append(hotel) #calculate values for candidate in candidates: candidate.calc_cost(need, average_duration) #find max value, need:cost ratio best = max(candidates, key=attrgetter('calculated_value')) #return policy return best def convert(self, building): #remove new_azc = AZC(building.unique_id, building.model, 'as_ext', building.pos, self) azc_viz = AZC_Viz(self.model, new_azc) self.model.schedule.add(azc_viz) self.model.grid.place_agent(azc_viz, azc_viz.pos) self.model.schedule.add(new_azc) self.model.grid.place_agent(new_azc, building.pos) self.city.buildings.add(new_azc) self.azcs.add(new_azc) self.capacities[new_azc] = new_azc.occupancy self.city.buildings.remove(building) self.buildings_under_construction.remove(building) self.model.schedule.remove(building) self.model.grid.remove_agent(building) # I set this up so we'd have a framework to convert empty buildings into activity centers # but currently it is not being used. def convertToActivityCenter(self, building): #remove new_activity_center = ActivityCenter(building.unique_id, building.model, 'as', building.pos, self) activity_center_viz = ActivityCenter_Viz(self.model, new_activity_center) self.model.schedule.add(activity_center_viz) self.model.grid.place_agent(activity_center_viz, activity_center_viz.pos) self.model.schedule.add(new_activity_center) self.model.grid.place_agent(new_activity_center, building.pos) self.city.buildings.add(new_activity_center) self.activity_centers.add(new_activity_center) self.capacities[new_activity_center] = new_activity_center.participants self.city.buildings.remove(building) self.buildings_under_construction.remove(building) self.model.schedule.remove(building) self.model.grid.remove_agent(building) def construct(self, building): building.under_construction = True self.buildings_under_construction.add(building) self.budget -= building.convert_cost def collect(self): self.budget += self.collection_fee * self.get_total_occupancy() def step(self): ''' COA is essentially checking for anomalies in the 'Ter Apel' If detected, inspects the gravity of the anomoly and acts accordingly ''' ########Actions########### #decay self.values.decay_val() #prioritize priority = self.values.prioritize() #act #find action that corresponds to priority current = None possible_actions = set(filter(lambda x: x.precondition(), self.actions)) for action in possible_actions: if priority == action.v_index: current = action #update v_sat if current != None: #print(current.name) current.do() #gives the model time to build of a distribution of normal flow if self.model.schedule.steps < self.model.shock_period / 2: if self.model.schedule.steps % self.assessment_frequency == 0: self.collect() # start calculting variances self.variance_ta, self.squared_ta, self.sum_ta = self.online_variance_ta( self.model.ter_apel) #starts checking for anamolies else: #only with a certain frequency so as not to slow it down if self.model.schedule.steps % self.assessment_frequency == 0: #also collects from residents self.collect() #check variance of current point variance_ta, squared_ta, sum_ta = self.online_variance_ta( self.model.ter_apel) if self.shock_check(variance_ta): self.shock = True self.shock_reference = self.model.schedule.steps #if no anomoly add to normal flow distribution else: self.variance_ta, self.squared_ta, self.sum_ta = variance_ta, squared_ta, sum_ta self.shock = False self.policy = self.house self.update_capacities() #only during shock periods project if self.shock: if self.model.schedule.steps % self.assessment_frequency == 0: if self.problematic: cc = self.crisis_check() if cc[0]: self.crisis = True if self.ta: pass else: decision = self.evaluate_options(cc[1]) if type(decision) is Hotel: self.policy = self.hotel_house else: self.policy = self.hotel_house #convert decision self.construct(decision) else: self.crisis = False self.problematic = False #forcing reevaluation. else: #check for problematic if self.problematic_check(): self.problematic = True self.policy = self.min_house else: self.policy = self.house self.problematic = False def intake(self, newcomer): '''Adds a newcomer to Ter Apel ''' #take first one, in future, evaluate buildings on some criteria house_loc = self.model.ter_apel.pos #where is it #update occupancy self.model.ter_apel.occupancy += 1 #add noise so agents don't overlap x = house_loc[0] #+ np.random.randint(-20,20) y = house_loc[1] - 10 + int(20 * ((1 + self.model.ter_apel.occupancy) / self.model.ter_apel.capacity)) self.model.grid.move_agent(newcomer, (x, y)) #place self.model.ter_apel.occupants.add( newcomer) #add agent to building roster newcomer.loc = self.model.ter_apel #update agent location
class Newcomer(Agent): def __init__(self, unique_id, model, country_of_origin, pos): ''' Initializes Newcomer Class (NC) DQ - documentation quality pos - position in x,y space dq_min - refers to the IND standard decision time - time until IND must make a decision. current_step - refers to what position the agent is in the sequence of actions ''' super().__init__(unique_id, model) self.pos = pos self.coa = None #ls is Legal Status self.ls = 'edp' #externally displaced person self.decision_time = 8 #28 days is the length of the general asylum procedure self.intake_time = 4 #time until transfer out of ter apel self.coo = country_of_origin self.specs = self.model.specs[ self.coo] #specs contains bournoulli distribution params self.ext_time = 90 #duration of extended procedure #draw first decision outcome self.first = bernoulli.rvs(self.specs[0], size=1)[0] #second decision outcome not drawn unless necessary self.second = None # new comer values self.values = Values(10, 70, 30, 70, 50) self.testing_activities = False def step(self): if self.testing_activities: #decay self.values.decay_val() #check if test activity is occuring today day = self.model.schedule.steps % 7 if self.model.test_activity.frequency == day: print('partaking!') self.model.test_activity.effect(self) #EDP to AZ if self.ls == 'edp': self.intake_time -= 1 if self.intake_time == 0: self.ls = 'as' self.coa.policy(self) self.coa.IND.set_time(self) #AZ to TR elif self.ls == 'as': self.decision_time -= 1 if self.decision_time == 0: if self.coa.IND.decide(True, self): self.ls = 'tr' self.coa.social_house(self) country = self.model.country_list.index(self.coo) self.model.country_success[country] += 1 self.model.Remove(self) else: self.ls = 'as_ext' self.coa.policy(self) self.coa.IND.set_time(self) #draws decision outcome from bernoulli distribution based on attributes self.second = bernoulli.rvs(self.specs[1], size=1)[0] # Extended Procedure to TR or Repatriation elif self.ls == 'as_ext': self.decision_time -= 1 if self.decision_time == 0: if self.second == 0: self.model.Remove(self) else: self.ls = 'tr' self.coa.social_house(self) country = self.model.country_list.index(self.coo) self.model.country_success[country] += 1 self.model.Remove(self) #temporary just to speed things up # Agent Temporary Resident elif self.ls == 'tr': pass
files = vars(args) train_graph_file = files[ 'dataset'] + 'E:/KDD/public-data/public/e/train.data/edge.tsv' train_label_file = files[ 'dataset'] + 'E:/KDD/public-data/public/e/train.data/train_label.txt' train_node_id = files[ 'dataset'] + 'E:/KDD/public-data/public/e/train.data/train_node_id.txt' features = files[ 'dataset'] + 'E:/KDD/public-data/public/e/train.data/feature.tsv' test_label = files['dataset'] + 'E:/KDD/public-data/public/e/test_label.txt' test_node_id = files[ 'dataset'] + 'E:/KDD/public-data/public/e/train.data/test_node_id.txt' files['struct'][0] = 7521 train_graph_data = Values(train_graph_file, files['neg_sample']) print("AAAAA") print(train_graph_data) model = SDNE(files, train_graph_file) model.do_variables_init(train_graph_data) embedding = None feature_embedding = None daata = pd.read_csv('E:/KDD/public-data/public/e/train.data/edge.tsv', delimiter='\t') graph = nx.from_pandas_edgelist(daata, 'src_idx', 'dst_idx', ['edge_weight']) adj = nx.adjacency_matrix(graph).todense() while (True): mini_batch = train_graph_data.sample(files['batch_size'], do_shuffle=False) if embedding is None:
class Individual(object): def __init__(self): self.ID = None self.DesignParameters = Values() self.Responses = Values() self.Success = False self.Objectives = None self.Constraints = None self.Fitness = None def Clone(self): """ Clones self, but the clone has no ID, i.e. ID == None """ indi = copy.deepcopy(self) indi.ID = None indi.Objectives = None indi.Constraints = None indi.Fitness = None return indi def Initialize(self): self.DesignParameters.Initialize() self.Responses.Initialize() self.ID = None self.Objectives = None self.Constraints = None self.Fitness = None def Randomize(self): for v in self.DesignParameters: v.Randomize() self.Success = False def ClipWithinBounds(self): for v in self.DesignParameters: v.Value = min(v.Value, v.MaxValue) v.Value = max(v.Value, v.MinValue) def ParameterSpaceDistanceTo(self, indi2): x1 = self.DesignParameters.AsVector() x2 = indi2.DesignParameters.AsVector() d = x2 - x1 return n.sqrt(n.dot(d, d)) def IsFeasible(self): if not self.Success: return False if self.Constraints == None: return True return self.Constraints.sum() == 0.0 def __str__(self): return str(self.DesignParameters) + str(self.Responses) + str( self.Objectives) + str(self.Constraints) + " " + str( self.Success) + " " + str(self.Fitness)
from Values import Values var1 = Values(10, 1) var2 = Values(30, 6) var3 = Values(3, 0.5) ans = 2 - var2 / (var3**3 + var1) print(ans)