def create_family(self, **kwargs):
"""
A Family is a group of Persons consisting of 2 parents and at least one child. The status of the family is not set.
It starts with the core_age of one parent with that parent's gender determined by a variable.
The core_age should be in the form of days old not years so that a more varied age can be applied to relatives.
The core_age of parent A is determined through a normal distribution of parent ages
The core_age of parent B is determined through a n dist of parent age differences and the core_age of parent A
TODO: Make sim dob time more random and not based on computer time
:param core_age (int that will determine how many days old and then randomizes DateOfBirth based on today
:return:
"""
# Process all the options and set to random lists if none provided.
# Options are there for loops that re-run the function
if not self.basebook:
self.basebook_setup()
if 'core_age' in kwargs:
core_age = kwargs['core_age'] * 365 + (random.randint(-180, 180))
else:
core_age = (int(np.random.normal(loc=self.ParentA_Ages['mean'], scale=self.ParentA_Ages['stdev'])) * 365
+ random.randint(-180, 180))
if 'LastName' in kwargs:
LastName = kwargs['LastName']
else:
LastName = random.choice(self.LastNames)
# Create the first parent
GenderA = random.choices(self.ParentA_Choices, self.ParentA_Weights)[0]
if GenderA == 'F':
FirstName = random.choice(self.FemaleNames)
else:
FirstName = random.choice(self.MaleNames)
# Create the place of birth
POB_A = self.Locations.sample(1)
POB_A = self.create_location(
City=POB_A['city'][int(POB_A.index[0])],
Country=POB_A['country'][int(POB_A.index[0])],
Latitude=float(POB_A['lat'][int(POB_A.index[0])]),
Longitude=float(POB_A['lng'][int(POB_A.index[0])]),
Population=float(POB_A['pop'][int(POB_A.index[0])]),
Type=self.POLE
)
# Create the person record and key
parentA = self.create_person(
DateOfBirth=(datetime.datetime.now() - datetime.timedelta(days=core_age)).strftime('%Y-%m-%d %H:%M:%S'),
PlaceOfBirth=POB_A['City'],
LastName=LastName,
FirstName=FirstName,
Gender=GenderA,
Type=self.POLE,
Category='SIM'
)
# Create the relation to place of birth
self.create_relation(parentA, POB_A, 'BornIn', self.POLE)
# Create the event for birth
DOB_A = self.create_event(
Type=self.POLE,
Category='Birth',
DateTime=parentA['DateOfBirth'],
Description='%s %s born on %s in %s.' % (FirstName,
LastName,
parentA['DateOfBirth'],
POB_A['City']))
self.create_relation(parentA, DOB_A, 'BornOn', self.POLE)
self.create_relation(DOB_A, POB_A, 'OccurredAt', self.POLE)
# Create the second parent based on the first parent and simulation settings
b_core_age = ((core_age + int(np.random.normal(loc=self.Parent_Age_Difference['mean'],
scale=self.Parent_Age_Difference['stdev'])))
+ (random.randint(-180, 180)))
if random.choices(self.Parent_SameGender_Choices, self.Parent_SameGender_Weights)[0]:
GenderB = GenderA
else:
if GenderA == 'F':
GenderB = 'M'
else:
GenderB = 'F'
if GenderB == 'F':
FirstName = random.choice(self.FemaleNames)
else:
FirstName = random.choice(self.MaleNames)
LastNameB = random.choice(self.LastNames)
POB_B = self.Locations.sample(1)
POB_B = self.create_location(
City=POB_B['city'][int(POB_B.index[0])],
Country=POB_B['country'][int(POB_B.index[0])],
Latitude=POB_B['lat'][int(POB_B.index[0])],
Longitude=POB_B['lng'][int(POB_B.index[0])],
Population=POB_B['pop'][int(POB_B.index[0])],
Type=self.POLE,
)
# Create the person record and key
parentB = self.create_person(
DateOfBirth=(datetime.datetime.now() - datetime.timedelta(days=b_core_age)).strftime('%Y-%m-%d %H:%M:%S'),
PlaceOfBirth=POB_B['City'],
LastName=LastNameB,
FirstName=FirstName,
Gender=GenderB,
Type=self.POLE,
)
# Create the relation to place of birth
self.create_relation(parentB, POB_B, 'BornIn', self.POLE)
# Create the event for birth
DOB_B = self.create_event(
DateTime=parentB['DateOfBirth'],
Type=self.POLE,
Category='Birth',
Description='%s %s born on %s in %s.' % (FirstName,
LastName,
parentB['DateOfBirth'],
POB_B['City']))
self.create_relation(parentB, DOB_B, 'BornOn', self.POLE)
self.create_relation(DOB_B, POB_B, 'OccurredAt', self.POLE)
# TODO Create origin based location
# TODO Create beahvior pattern variables for turn based simulation and agent based motivations
# Create the relation between the parents
self.create_relation(parentA, parentB, 'ChildrenWith', self.POLE)
# Create the children starting with the oldest based on an age derived from random parent age and Sim settings
core_age = (random.choice([core_age, b_core_age]) / 365 - int(
np.random.normal(loc=self.Parent_Child_Age_Difference['mean'],
scale=self.Parent_Child_Age_Difference['stdev']))) * 365
i = 0
children = {}
LastName = random.choice([LastName, LastNameB])
childrencount = int(np.random.normal(loc=self.ChildrenCount['mean'], scale=self.ChildrenCount['stdev']))
if childrencount < 2:
childrencount = 2
while i < childrencount:
Gender = random.choices(self.Child_Gender_Choices, self.Child_Gender_Weights)[0]
if Gender == 'M':
FirstName = random.choice(self.MaleNames)
elif Gender == 'F':
FirstName = random.choice(self.FemaleNames)
else:
FirstName = random.choice(self.FemaleNames)
POB = random.choice([POB_A, POB_B])
child = self.create_person(
DateOfBirth=(datetime.datetime.now() - datetime.timedelta(days=core_age)).strftime('%Y-%m-%d %H:%M:%S'),
PlaceOfBirth=POB['City'],
LastName=LastName,
FirstName=FirstName,
Gender=Gender,
Type=self.POLE
)
# Create the relation to place of birth
self.create_relation(child, POB, 'BornIn', self.POLE)
# Create the event for birth
DOB = self.create_event(
Type=self.POLE,
Category='Birth',
DateTime=child['DateOfBirth'],
Description='%s %s born on %s in %s.' % (FirstName,
LastName,
child['DateOfBirth'],
POB['City']))
self.create_relation(child, DOB, 'BornOn', self.POLE)
self.create_relation(DOB, POB, 'OccurredAt', self.POLE)
children[child['key']] = child
# Create the relation between the parents
self.create_relation(parentA, child, 'ParentOf', self.POLE)
self.create_relation(parentB, child, 'ParentOf', self.POLE)
# Increment the age for next kid
core_age = core_age - random.randint(300, 1500)
i += 1
# Create the sibling relationships
for c in children:
for cc in children:
if cc != c:
self.create_relation(children[c], children[cc], 'SiblingOf', self.POLE)
def run_simulation(self, rounds):
if not self.basebook:
self.basebook_setup()
i = 0
sim_time = datetime.datetime.strptime(self.SimStartDate, '%Y-%m-%d %H:%M:%S')
while i < rounds:
'''
1. Choose sims based on an action number range/filter
2. Based on the age create an action.
If child create a school or abuse related event
If parent create a police or employment related event
3. Create a location based on Sim Locations
Choose home as first and add random.
If len of locations is < 3 append, else, random create new based on others or select one
4. Insert the relation of event to person and to locations into the db based on event type
'''
for sim in self.DB['sims']:
if sim['SimClock'] > random.randint(1, 9):
age = self.check_age(sim_time, sim)
if age == 'Not born':
break
action = self.choose_action(age)
EVT = self.create_event(Type=action,
DateTime=sim_time.strftime('%Y-%m-%d %H:%M:%S'),
Description='%s %s, of %s age was involved with an event related to %s at %s'
% (sim['FirstName'], sim['LastName'],
age, action, sim_time.strftime('%Y-%m-%d %H:%M:%S')))
self.create_relation(EVT, sim, 'Involved', action)
# Reset the time to a step in the future based on random time between 1 and max round length
# Set to seconds to allow for more interactions in a round
sim_time = datetime.datetime.strptime(
(sim_time + datetime.timedelta(seconds=random.randint(1, self.SimRoundLengthMax))
).strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S')
# Reset the Sim's clock it's original setting
sim['SimClock'] = sim['SimAction']
else:
sim['SimClock'] += 1
# Reset the time to a step in the future based on random time between 1 and max round length
# Set to minutes to allow for a bigger time jump between each round treating the iteration of sims as "bullet time"
sim_time = datetime.datetime.strptime(
(sim_time + datetime.timedelta(hours=random.randint(1, self.SimRoundLengthMax))
).strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S')
i += 1
def sim_thread():
family_count = 1 # 3 seconds to make 2 families
sim_run_count = 2
click.echo("[%s_View_ThreadSim] Starting simulation with creating %d families" % (get_datetime(), family_count))
i = 0
while i < family_count:
simserver.create_family()
i += 1
click.echo("[%s_View_ThreadSim] Starting %d simulation rounds" % (get_datetime(), sim_run_count))
simserver.run_simulation(sim_run_count)
click.echo("[%s_View_ThreadSim] Exporting snapshot JSON for starter set" % (get_datetime()))
simserver.export_json()
click.echo("[%s_View_ThreadSim] Complete with set up" % (get_datetime()))
def stream_data():
i=0
while stream:
time.sleep(3)
stream['events'].append({'time': get_datetime(), 'message': 'Test %d' % i})
click.echo("[%s_View_ThreadStream] Running %d" % (get_datetime(), i))
i+=1
@orientdb.route('/OrientDB/get_stream', methods=['POST'])
def get_stream():
r = request.form.to_dict(flat=True)
cur_len = len(stream['events'])
cur_index = r['cur_index']
return jsonify(
{'new_index': cur_len,
'old_index': cur_index,
'payload': stream['events'][cur_index:cur_len - 1]
}
)
@orientdb.route('/OrientDB', methods=['GET'])
def home():
sim = Thread(target=sim_thread, )
stm = Thread(target=stream_data, )
sim.start()
click.echo("[%s_View_Home] Getting calc views" % (get_datetime()))
views = load_views()
click.echo("[%s_View_Home] Complete with calc views" % (get_datetime()))
# App tile will always have an index applied to their model when 'GET"
odata = {
'status': 200,
'message': '%s logged in' % get_datetime(),
'd': {
'index': odbserver.get_db_stats(),
'demo_data': odbserver.fill_demo_data(),
'clipboard': {
'keys': [],
'nodes': []
},
'dialogs': {
'nodes': [],
'lines': [],
'groups': []
},
'files': [],
'charts': {
'ChartContainerData1.json': odbserver.get_model('ChartContainerData1.json'),
'ChartContainerData2.json': odbserver.get_model('ChartContainerData2.json'),
'ChartContainerData3.json': odbserver.get_model('ChartContainerData3.json')
},
'views': views,
'network': odbserver.fill_demo_data_small()
}
}
# Get a small net from each db
current_selection = odata['d']['index'][0]
current_selection['network'] = odata['d']['network'][current_selection['name']]
odata['d']['current_selection'] = odata['d']['index'][0]
click.echo("[%s_View_Home] Packaging model for client" % (get_datetime()))
try:
odata = jsonify(odata)
except Exception as e:
if "TypeError: '<' not supported between instances" in str(e):
click.echo("[%s_View_Home] ERROR \n%s Showing oData" % (get_datetime(), odata))
else:
click.echo("[%s_View_Home] UNKNOWN ERROR" % (get_datetime()))
click.echo("[%s_View_Home] Sending model to client" % (get_datetime()))
return odata
getStream: function() {
jQuery.ajax({
url : "/OrientDB/get_stream",
type : "POST",
dataType : "json",
async : true,
success : function(response, jqXHR, textStatus){
var oModel = new JSONModel(response);
sap.ui.getCore().setModel(oModel, 'LaunchpadStats');
window._card1.setModel(oModel);
window._card2.setModel(oModel);
window._card3.setModel(oModel);
window._timeline.setModel(oModel);
sap.ui.core.BusyIndicator.hide(0);
sap.m.MessageToast.show(response.message);
},
error: function(response){
console.log(response);
sap.ui.core.BusyIndicator.hide(0);
}
});
},
window.oGraph = this.byId("graph");
window.oGraph._fZoomLevel = 0.75;
window.oGraphCurIndex = 0;
// Set the Toolbar
var oToolbar = window.oGraph.getToolbar();
/*
* Tool Bar buttons for the Graph
*/
oToolbar.insertContent(new Button("refreshButton", {
type: ButtonType.Transparent,
icon: "sap-icon://refresh",
press: this.refreshGraph.bind(window.oGraph)
}), 0);
oToolbar.insertContent(new Button("goBackGraphButton", {
type: ButtonType.Transparent,
icon: "sap-icon://media-rewind",
press: this.goBackGraph.bind(window.oGraph)
}), 1);
oToolbar.insertContent(new Button("goForwardGraphButton", {
type: ButtonType.Transparent,
icon: "sap-icon://media-forward",
press: this.goForwardGraph.bind(window.oGraph)
}), 2);
oToolbar.insertContent(new Button("addButton", {
type: ButtonType.Transparent,
icon: "sap-icon://add",
press: this.addNode.bind(window.oGraph)
}), 3);
oToolbar.insertContent(new Button("addLine", {
type: ButtonType.Transparent,
icon: "sap-icon://chain-link",
press: this.addLine.bind(window.oGraph)
}), 4);
var newActTraverse = new ActionButton ({
icon: "sap-icon://overview-chart",
title: "Traverse",
position: "Left",
press: function (oEvent) {
var NodeKey = oEvent.getSource().oParent.getKey();
var oData = {
'key': NodeKey,
'db_name': sap.ui.getCore().getModel('OrientDBModel').oData.current_selection.name,
'cur_graph': sap.ui.getCore().getModel('OrientDBModel').oData.current_selection.network
};
var selectedNode = new JSONModel({'key': NodeKey, 'title': NodeTitle});
sap.ui.getCore().setModel(selectedNode, "selectedNode");
jQuery.ajax({
url : "/OrientDB/traverse",
type : "POST",
dataType : "json",
async : true,
data : oData,
success : function(response){
var oData = new JSONModel({
'nodes': response.results.cur_graph.nodes,
'lines': response.results.cur_graph.lines,
'groups': response.results.cur_graph.groups
})
window.oGraph.setModel(oData);
MessageToast.show(response.message);
}
});
}
});
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
User | Count |
---|---|
24 | |
14 | |
11 | |
11 | |
10 | |
9 | |
7 | |
6 | |
5 | |
5 |