Beispiel #1
0
    def update_parameters(self):

        print "Updating parameters"

        nodefile = self.nodes.get()
        edgefile = self.edges.get()
        debug = self.debugVar.get()
        if debug == 'True':
            debug = True
        else:
            debug = False

        hive = Hive(debug=debug)
        properties = list(hive.get_nodes(nodefile).keys()) + assignmentOptions
        self.assignmentVar = self.reset_option_menu(self.assignmentOpt,
                                                    self.assignmentVar,
                                                    properties,
                                                    index=2)

        properties = list(hive.get_nodes(nodefile).keys()) + positionOptions
        self.positionVar = self.reset_option_menu(self.positionOpt,
                                                  self.positionVar, properties)

        properties = list(hive.get_edges(edgefile)) + edgeStyleOptions
        self.edgeStyleVar = self.reset_option_menu(self.edgeStyleOpt,
                                                   self.edgeStyleVar,
                                                   properties)
Beispiel #2
0
 def build_hives(self):
     self.hives = []
     world_size = self.config['world']['size']
     for i in range(self.config['world']['hives']):
         position = world_size.random_position()
         hive = Hive(self.config, position)
         hive.color = self.config['world']['hive_colors'][i]
         self.hives.append(hive)
     self.children = self.hives
Beispiel #3
0
    def setUp(self):
        #example hive
        self.emptyhive = Hive(debug=False)
        self.friendsHive = Hive(debug=False)
        self.friendsHiveDouble = Hive(debug=False, doubleAxes=True)
        nodefile = _root_dir + '/tests/test_nodes_friends.csv'
        edgefile = _root_dir + '/tests/test_edges_friends.csv'

        self.friendsHive.get_nodes(nodefile)
        self.friendsHive.get_edges(edgefile)
        self.friendsHiveDouble.get_nodes(nodefile)
        self.friendsHiveDouble.get_edges(edgefile)

        self.friendsNodesValuesInt = {
            'Alice': 4,
            'Eric': 2,
            'Daniella': 2,
            'Fatima': 3,
            'Cam': 3,
            'Bob': 4,
            'George': 2
        }
        self.friendsNodesValuesFloat = {
            'Daniella': 0.8,
            'George': 0.9,
            'Fatima': 0,
            'Cam': 0.9,
            'Bob': 0.2,
            'Alice': 1.9,
            'Eric': 1.6
        }
        self.friendsNodesValuesString = {
            'Daniella': 'girl',
            'George': 'alien',
            'Fatima': 'girl',
            'Cam': 'boy',
            'Bob': 'boy',
            'Alice': 'girl',
            'Eric': 'boy'
        }

        self.numAxesOptions = [(True, 2), (True, 3), (False, 5), (False, 4),
                               (False, 3), (False, 2)]
        self.axesOptions = {
            (False, 2): [0, pi],
            (False, 3): [0, pi * 2 / 3, pi * 4 / 3],
            (False, 4): [0, pi / 2, pi, pi * 3 / 2],
            (False, 5): [0, pi * 2 / 5, pi * 4 / 5, pi * 6 / 5, pi * 8 / 5],
            (True, 2): [-pi / 6, pi / 6, pi * 5 / 6, pi * 7 / 6],
            (True, 3): [
                -pi / 9, pi / 9, pi * 5 / 9, pi * 7 / 9, pi * 11 / 9,
                pi * 13 / 9
            ]
        }

        self.rules = [(), 2, 'degree', 'clustering', 'closeness', 'centrality',
                      'betweeness', 'average neighbor degree']
    def test_boundries(self):        
        board = Hive()
        piece = Spider(Color.WHITE)
        board.add(piece, HCP(0,0))

        # Note that these are in the hive coordinate system.
        open_locations = [HCP(1,0), HCP(0,1), HCP(-1,0),
                          HCP(0,-1), HCP(1,-1), HCP(-1,1)]

        self.assertEqual(set(board.edge()),set(open_locations))
Beispiel #5
0
    def test_place(self):
        """ test placement of moves
            
        Test to see if the a player can place a piece
        """
        p1 = Player(Color.WHITE)
        hive = Hive()

        p1.place(Ant, HCP(1, 1), hive)

        self.assertFalse(hive.empty())
    def test_two_piece(self):
        board = Hive()
        piece1 = Spider(Color.WHITE)
        piece2 = Spider(Color.WHITE)
        board.add(piece1, HCP(0,0))
        board.add(piece2, HCP(1,0))

        open_locations = [HCP(1,1), HCP(0,1), HCP(-1,0),
                          HCP(0,-1), HCP(1,-1), HCP(-1,1),
                          HCP(2,0), HCP(2,-1)]

        self.assertEqual(set(board.edge()), set(open_locations))
Beispiel #7
0
    def update_parameters(self):
        nodefile = self.nodes.get()
        edgefile = self.edges.get()
        
        hive = Hive(debug = False)
        properties = list(hive.get_nodes(nodefile).keys()) + assignmentOptions
        self.assignmentVar = self.reset_option_menu(self.assignmentOpt, self.assignmentVar, properties, index = 2) 
        
        properties = list(hive.get_nodes(nodefile).keys()) + positionOptions
        self.positionVar = self.reset_option_menu(self.positionOpt, self.positionVar, properties) 

        properties = list(hive.get_edges(edgefile)) + edgeStyleOptions
        self.edgeStyleVar = self.reset_option_menu(self.edgeStyleOpt, self.edgeStyleVar, properties)
def get_num_colors(edges, style):
    if style == 'uniform':
        colors = [1]
    else:
        edgefile = edges.get()
        hive = Hive(debug = True)
        properties = hive.get_edges(edgefile)[style]
        categories = find_categories(properties)
        if categories:
            colors = [len(categories)]
        else:
            colors = [i for i in range(1,10)]
    return colors
Beispiel #9
0
def get_num_colors(edges, style):
    if style == 'uniform':
        colors = [1]
    else:
        edgefile = edges.get()
        hive = Hive(debug=False)
        properties = hive.get_edges(edgefile)[style]
        categories = find_categories(properties)
        if categories:
            colors = [len(categories)]
        else:
            colors = [i for i in range(1, 10)]
    return colors
Beispiel #10
0
    def __init__(self, playerlist, referee=None):
        # The list of players in our game of hive
        self.players = playerlist
        self.hive = Hive()

        # Make a standard referee
        if referee is None:
            self.ref = HiveRef(HiveRulebook())
Beispiel #11
0
 def get_hive(self):
     hiveTitle = self.title.get()
     nodefile = self.nodes.get()
     edgefile = self.edges.get()
     debug = self.debugVar.get()
     axes = self.axesVar.get()
     double = self.doubleVar.get()
     assignment = self.assignmentVar.get()
     position = self.positionVar.get()
     edgeStyle = self.edgeStyleVar.get()
     nodeColor = self.nodeColorVar.get()
     paletteHue = self.paletteVar.get()
     numColors = self.colorVar.get()
     
     #convert types
     axes = int(axes)
     
     if debug == 'True':
         debug = True
     else: 
         debug = False
     
     if double == 'True':
         double = True
     else:
         double = False
     
     if edgeStyle == 'uniform':
         edgeStyle = None
     
     palette = get_palette(paletteHue,int(numColors))
     
     hive = Hive(debug = debug, 
                 numAxes = axes,
                 doubleAxes = double, 
                 axisAssignRule = assignment, 
                 axisPositRule = position,
                 edgePalette = palette, 
                 edgeStyleRule = edgeStyle,
                 nodeColor = nodeColor
                 )
     hive.make_hive(nodefile, edgefile)
     return hive
Beispiel #12
0
class ConfigEngine(object):
    def __init__(self):
        self.zookeeper = Zookeeper()
        self.hadoop = Hadoop()
        self.hbase = HBase()
        self.hive = Hive()
        self.ignite = Ignite()
        
    def waiting(self):
        while True:
            print('Waiting...')
            time.sleep(5)
    
    def configure(self):
        self.zookeeper.configure()
        self.hadoop.configure()
#         self.hbase.configure()
        self.hive.configure()
        self.ignite.configure()
Beispiel #13
0
    def test_piece_removal(self):
        """ Test to see if pieces are removed from the players
        set of pieces """

        p1 = Player(Color.WHITE)
        hive = Hive()

        p1.place(Queen, HCP(0, 0), hive)

        self.assertFalse(p1.find(Queen))
Beispiel #14
0
class ConfigEngine(object):
    def __init__(self):
        self.zookeeper = Zookeeper()
        self.hadoop = Hadoop()
        self.hbase = HBase()
        self.hive = Hive()
        self.ignite = Ignite()

    def waiting(self):
        while True:
            print('Waiting...')
            time.sleep(5)

    def configure(self):
        self.zookeeper.configure()
        self.hadoop.configure()
        #         self.hbase.configure()
        self.hive.configure()
        self.ignite.configure()
    def test_hivebreak(self):
        board = Hive()

        piece1 = Spider(Color.WHITE)
        board.add(piece1, HCP(0,0))

        piece2 = Spider(Color.BLACK)
        board.add(piece2, HCP(1,0))

        piece3 = Spider(Color.BLACK)
        board.add(piece3, HCP(1,1))

        # These locations will break the hive
        breaker = [piece2, (1,0)]

        self.assertEqual(board.breaker(), breaker)
Beispiel #16
0
    def get_hive(self):
        hiveTitle = self.title.get()
        nodefile = self.nodes.get()
        edgefile = self.edges.get()
        debug = self.debugVar.get()
        axes = self.axesVar.get()
        double = self.doubleVar.get()
        assignment = self.assignmentVar.get()
        position = self.positionVar.get()
        edgeStyle = self.edgeStyleVar.get()
        nodeColor = self.nodeColorVar.get()
        paletteHue = self.paletteVar.get()
        numColors = self.colorVar.get()

        #convert types
        axes = int(axes)

        if debug == 'True':
            debug = True
        else:
            debug = False

        if double == 'True':
            double = True
        else:
            double = False

        if edgeStyle == 'uniform':
            edgeStyle = None

        palette = get_palette(paletteHue, int(numColors))

        hive = Hive(debug=debug,
                    numAxes=axes,
                    doubleAxes=double,
                    axisAssignRule=assignment,
                    axisPositRule=position,
                    edgePalette=palette,
                    edgeStyleRule=edgeStyle,
                    nodeColor=nodeColor)
        hive.make_hive(nodefile, edgefile)
        return hive
Beispiel #17
0
def submit_post(title, tags, body, author):
    hive = Hive(nodes=nodes, keys=[posting_key])
    permlink_title = ''.join(e for e in title if e.isalnum()).lower()
    json_metadata = {
        'community': 'busy',
        'app': 'busy/2.5.7',
        'format': 'markdown',
        'tags': tags
    }

    try:
        hive.post(title=title,
                  body=body,
                  author=author,
                  tags=tags,
                  json_metadata=json_metadata,
                  self_vote=False)
        print("Submitted post")
    except Exception as error:
        print(repr(error))
    def setUp(self):
        #example hive
        self.emptyhive = Hive(debug = False)
        self.friendsHive = Hive(debug = False)
        self.friendsHiveDouble = Hive(debug = False, doubleAxes = True)
        nodefile = _root_dir + '/tests/test_nodes_friends.csv'
        edgefile = _root_dir + '/tests/test_edges_friends.csv'

        self.friendsHive.get_nodes(nodefile)
        self.friendsHive.get_edges(edgefile)
        self.friendsHiveDouble.get_nodes(nodefile)
        self.friendsHiveDouble.get_edges(edgefile)
        
        self.friendsNodesValuesInt = {'Alice': 4, 'Eric': 2, 'Daniella': 2, 'Fatima': 3, 'Cam': 3, 'Bob': 4, 'George': 2}
        self.friendsNodesValuesFloat = {'Daniella': 0.8, 'George': 0.9, 'Fatima': 0, 'Cam': 0.9, 'Bob': 0.2, 'Alice': 1.9, 'Eric': 1.6}
        self.friendsNodesValuesString = {'Daniella': 'girl', 'George': 'alien', 'Fatima': 'girl', 'Cam': 'boy', 'Bob': 'boy', 'Alice': 'girl', 'Eric': 'boy'}
        
        self.numAxesOptions = [(True, 2), (True, 3), (False, 5), (False, 4), (False, 3), (False, 2)]
        self.axesOptions = {(False,2):[0,pi], (False,3):[0, pi*2/3, pi*4/3], (False,4):[0,pi/2,pi,pi*3/2], (False,5):[0,pi*2/5,pi*4/5,pi*6/5,pi*8/5], (True,2):[-pi/6,pi/6,pi*5/6,pi*7/6], (True,3):[-pi/9,pi/9,pi*5/9,pi*7/9,pi*11/9,pi*13/9]}
        
        self.rules = [(),2,'degree', 'clustering', 'closeness', 'centrality', 'betweeness','average neighbor degree']
Beispiel #19
0
    def update_parameters(self):
        
        print "Updating parameters"
        
        nodefile = self.nodes.get()
        edgefile = self.edges.get()
        debug = self.debugVar.get()
        if debug == 'True':
            debug = True
        else: 
            debug = False
        
        hive = Hive(debug = debug)
        properties = list(hive.get_nodes(nodefile).keys()) + assignmentOptions
        self.assignmentVar = self.reset_option_menu(self.assignmentOpt, self.assignmentVar, properties, index = 2) 
        
        properties = list(hive.get_nodes(nodefile).keys()) + positionOptions
        self.positionVar = self.reset_option_menu(self.positionOpt, self.positionVar, properties) 

        properties = list(hive.get_edges(edgefile)) + edgeStyleOptions
        self.edgeStyleVar = self.reset_option_menu(self.edgeStyleOpt, self.edgeStyleVar, properties)
Beispiel #20
0
def inspect_hived_implementation():
    """ Compare implemented methods with current live deployment of hived. """
    _apis = distinct(pluck('api', api_methods))
    _methods = set(pluck('method', api_methods))

    avail_methods = []
    h = Hive(re_raise=False)
    for api in _apis:
        err = h.exec('nonexistentmethodcall', api=api)
        [
            avail_methods.append(x)
            for x in err['data']['stack'][0]['data']['api'].keys()
        ]

    avail_methods = set(avail_methods)

    print("\nMissing Methods:")
    pprint(avail_methods - _methods)

    print("\nLikely Deprecated Methods:")
    pprint(_methods - avail_methods)
Beispiel #21
0
def main(*argv):
    '''handles the user input and runs the functions 
        needed to make the hive plot'''
    nodefile = ''
    edgefile = ''
    debug = False
    title = ''
    try:
        opts, args = getopt.getopt(argv,"hn:e:t:d",["nfile=","efile=","title="])
    except getopt.GetoptError:
       print 'main.py -n <nodefile> -e <edgefile> -t <title> -d'
       sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'main.py -n <nodefile> -e <edgefile> -t <title> -d'
            sys.exit()
        elif opt in ("-n", "--nfile"):
            nodefile = arg
        elif opt in ("-e", "--efile"):
            edgefile = arg
        elif opt in ("-d"):
            debug = True
        elif opt in ("-t", "--title"):
            title = arg
    print '\n    Node file is "', nodefile, '"'
    print '    Edge file is "', edgefile, '"'
    
    
    hive = Hive(debug = debug,
            numAxes = numAxes, 
            doubleAxes = doubleAxes, 
            axisAssignRule = axisAssignRule, 
            axisPositRule = axisPositRule, 
            edgePalette = edgeColorPalette, 
            edgeStyleRule = edgeColorRule)
        
    hive.make_hive(nodefile, edgefile)
    make_html(title, hive)
    
    print '\n'
Beispiel #22
0
class RESTAPITestCase(ApplicableTestCase):
    __application__ = Hive()
    __story_directory__ = path.join(DATA_DIRECTORY, 'stories')
    __api_documentation_directory__ = path.join(DATA_DIRECTORY, 'markdown')
    __metadata__ = {
        #r'^/lists.*': List.json_metadata()['fields']
    }

    def login(self, email, password):
        with self.given(
                None,
                '/',
                'LOGIN',
                form=dict(email=email, password=password),
        ) as story:
            response = story.response
            assert response.status == '200 OK'
            self._authentication_token = response.text
def main():
    Log.info('------------------------')
    Log.info('Hive ETL pipeline starts')
    Log.info('------------------------')
    inputArgs = sys.argv
    args = inputArgs[1:]
    drop_earthquakes_tables = Input.getValues(args)
    earthquakes_files = HDFS.getFiles()
    create_DB = Database.CreateDB()
    create_earthquakes_tables = Database.CreateEarthquakesTables()
    upload_static_data = Database.UploadStaticData()
    path = HDFS.getPath()
    if create_DB:
        Hive.createDB(path)
    if create_earthquakes_tables:
        Hive.createEarthquakesTables()
    if upload_static_data:
        Log.info("Uploading cities and seismographic stations to HDFS..")
        HDFS.put('../../data/hive-etl-pipeline/cities.csv', path)
        HDFS.put('../../data/hive-etl-pipeline/seismographic-stations.csv',
                 path)
        Hive.loadCities(path)
        Hive.loadSeismographicStations(path)
        Log.info("Uploading seismograph script to HDFS..")
        HDFS.put('seismograph.py', path)
    Log.info("Files to be proccessed:")
    Log.info("Files to be imported in Hive: {}".format(earthquakes_files))
    if drop_earthquakes_tables:
        Hive.clearEarthquakesTables()
    for file in earthquakes_files:
        Hive.loadEarthquakesData(file)
        Hive.distanceToAllSeismographicStations()
        Hive.distanceAllToCities()
        Hive.distanceToClosestSeismographicStation()
        Hive.distanceToClosestCity()
        Hive.produceOutputSeismographs()
    Log.info('------------------------')
    Log.info('Hive ETL pipeline ends')
    Log.info('------------------------')
Beispiel #24
0
from hive import Hive

app = Hive()
app.configure()
app.initialize_orm()

def render_path(terrain, path):
    x, y = zip(*path)
    plt.plot(x, y, 'r+')
    plt.imshow(terrain)
    plt.show()


if __name__ == '__main__':
    # формируем случайный ландшафт,'низины' выравниваем, оставляем только 'горы'
    terrain = np.random.uniform(0, 1.0, (40, 40))
    terrain = np.where(terrain > 0.7, terrain, 0)
    terrain = scipy.signal.medfilt2d(terrain)

    hive = Hive(n_scouts=30,
                n_points=20,
                n_elite=10,
                n_bees_elite=50,
                n_bees_others=3,
                search_neighborhood=10,
                terrain=terrain,
                pos=(0, 0))

    start = time.time()
    solution = hive.find(target_pos=(39, 39), n_iters=100)

    end = time.time()
    print(end - start)

    render_path(terrain, solution.path)

    def test_starting_pawn(self):
        board = Hive()
        piece = Spider(Color.BLACK)
        board.add(piece, HCP(0,0))

        self.assertFalse(board.empty())
 def test_blankboard(self):
     board = Hive()
     self.assertTrue(board.empty())
Beispiel #28
0
class TestHive(unittest.TestCase):
    def setUp(self):
        #example hive
        self.emptyhive = Hive(debug=False)
        self.friendsHive = Hive(debug=False)
        self.friendsHiveDouble = Hive(debug=False, doubleAxes=True)
        nodefile = _root_dir + '/tests/test_nodes_friends.csv'
        edgefile = _root_dir + '/tests/test_edges_friends.csv'

        self.friendsHive.get_nodes(nodefile)
        self.friendsHive.get_edges(edgefile)
        self.friendsHiveDouble.get_nodes(nodefile)
        self.friendsHiveDouble.get_edges(edgefile)

        self.friendsNodesValuesInt = {
            'Alice': 4,
            'Eric': 2,
            'Daniella': 2,
            'Fatima': 3,
            'Cam': 3,
            'Bob': 4,
            'George': 2
        }
        self.friendsNodesValuesFloat = {
            'Daniella': 0.8,
            'George': 0.9,
            'Fatima': 0,
            'Cam': 0.9,
            'Bob': 0.2,
            'Alice': 1.9,
            'Eric': 1.6
        }
        self.friendsNodesValuesString = {
            'Daniella': 'girl',
            'George': 'alien',
            'Fatima': 'girl',
            'Cam': 'boy',
            'Bob': 'boy',
            'Alice': 'girl',
            'Eric': 'boy'
        }

        self.numAxesOptions = [(True, 2), (True, 3), (False, 5), (False, 4),
                               (False, 3), (False, 2)]
        self.axesOptions = {
            (False, 2): [0, pi],
            (False, 3): [0, pi * 2 / 3, pi * 4 / 3],
            (False, 4): [0, pi / 2, pi, pi * 3 / 2],
            (False, 5): [0, pi * 2 / 5, pi * 4 / 5, pi * 6 / 5, pi * 8 / 5],
            (True, 2): [-pi / 6, pi / 6, pi * 5 / 6, pi * 7 / 6],
            (True, 3): [
                -pi / 9, pi / 9, pi * 5 / 9, pi * 7 / 9, pi * 11 / 9,
                pi * 13 / 9
            ]
        }

        self.rules = [(), 2, 'degree', 'clustering', 'closeness', 'centrality',
                      'betweeness', 'average neighbor degree']

    def test_make_axes(self):
        hive = self.emptyhive
        for (doubleAxes, numAxes), angles in self.axesOptions.iteritems():
            hive.doubleAxes = doubleAxes
            hive.numAxes = numAxes
            hive.make_axes()
            angles = [0.0001 if a == 0 else round(a, 2) for a in angles]
            self.assertListEqual(angles, hive.angles)

    def test_get_assignment_values(self):
        hive = self.friendsHive
        values = hive.get_assignment_values(1)
        correctValues = {
            'Daniella': 'girl',
            'George': 'alien',
            'Fatima': 'girl',
            'Cam': 'boy',
            'Bob': 'boy',
            'Alice': 'girl',
            'Eric': 'boy'
        }
        self.assertEqual(values, correctValues)

        hive = self.friendsHiveDouble
        values = hive.get_assignment_values(1)
        correctValues = {
            'Eric.2': 'boy',
            'Cam.2': 'boy',
            'Cam.1': 'boy',
            'Daniella.1': 'girl',
            'Daniella.2': 'girl',
            'George.2': 'alien',
            'Fatima.2': 'girl',
            'Fatima.1': 'girl',
            'Eric.1': 'boy',
            'Alice.1': 'girl',
            'Alice.2': 'girl',
            'Bob.2': 'boy',
            'George.1': 'alien',
            'Bob.1': 'boy'
        }
        self.assertEqual(values, correctValues)

        hive = self.friendsHive
        values = hive.get_assignment_values(2)
        correctValues = {
            'Daniella': 0.8,
            'George': 0.9,
            'Fatima': 0,
            'Cam': 0.9,
            'Bob': 0.2,
            'Alice': 1.9,
            'Eric': 1.6
        }
        self.assertEqual(values, correctValues)

        hive = self.friendsHiveDouble
        values = hive.get_assignment_values(2)
        correctValues = {
            'Eric.2': 1.6,
            'Cam.2': 0.9,
            'Cam.1': 0.9,
            'Daniella.1': 0.8,
            'Daniella.2': 0.8,
            'George.2': 0.9,
            'Fatima.2': 0,
            'Fatima.1': 0,
            'Eric.1': 1.6,
            'Alice.1': 1.9,
            'Alice.2': 1.9,
            'Bob.2': 0.2,
            'George.1': 0.9,
            'Bob.1': 0.2
        }
        self.assertEqual(values, correctValues)

        hive = self.friendsHive
        values = hive.get_assignment_values('degree')
        correctValues = {
            'Alice': 4,
            'Eric': 2,
            'Daniella': 2,
            'Fatima': 3,
            'Cam': 3,
            'Bob': 4,
            'George': 2
        }
        self.assertEqual(values, correctValues)

        hive = self.friendsHiveDouble
        values = hive.get_assignment_values('degree')
        correctValues = {
            'Bob.1': 4,
            'Cam.2': 3,
            'Cam.1': 3,
            'Daniella.1': 2,
            'Daniella.2': 2,
            'George.2': 2,
            'Fatima.2': 3,
            'Fatima.1': 3,
            'Bob.2': 4,
            'Alice.1': 4,
            'Alice.2': 4,
            'Eric.1': 2,
            'George.1': 2,
            'Eric.2': 2
        }
        self.assertEqual(values, correctValues)

    def test_node_assignment(self):
        hive = self.friendsHive
        for (double, numAxes), assignmentValues in zip(
                self.numAxesOptions,
            (self.friendsNodesValuesString, self.friendsNodesValuesInt,
             self.friendsNodesValuesFloat)):
            hive.numAxes = numAxes
            hive.doubleAxes = double
            hive.node_assignment(assignmentValues=assignmentValues)
            assignment = hive.axisAssignment
            #now we check that the axis assignment variable
            #is a dictionary
            self.assertIsInstance(assignment, dict)
            #has an entry for every node
            self.assertEqual(set(assignment.keys()), set(hive.nodes))
            #that the values are integers corresponding to axes numbers
            [self.assertIsInstance(v, int) for v in assignment.values()]
class TestHive(unittest.TestCase):
    def setUp(self):
        #example hive
        self.emptyhive = Hive(debug = False)
        self.friendsHive = Hive(debug = False)
        self.friendsHiveDouble = Hive(debug = False, doubleAxes = True)
        nodefile = _root_dir + '/tests/test_nodes_friends.csv'
        edgefile = _root_dir + '/tests/test_edges_friends.csv'

        self.friendsHive.get_nodes(nodefile)
        self.friendsHive.get_edges(edgefile)
        self.friendsHiveDouble.get_nodes(nodefile)
        self.friendsHiveDouble.get_edges(edgefile)
        
        self.friendsNodesValuesInt = {'Alice': 4, 'Eric': 2, 'Daniella': 2, 'Fatima': 3, 'Cam': 3, 'Bob': 4, 'George': 2}
        self.friendsNodesValuesFloat = {'Daniella': 0.8, 'George': 0.9, 'Fatima': 0, 'Cam': 0.9, 'Bob': 0.2, 'Alice': 1.9, 'Eric': 1.6}
        self.friendsNodesValuesString = {'Daniella': 'girl', 'George': 'alien', 'Fatima': 'girl', 'Cam': 'boy', 'Bob': 'boy', 'Alice': 'girl', 'Eric': 'boy'}
        
        self.numAxesOptions = [(True, 2), (True, 3), (False, 5), (False, 4), (False, 3), (False, 2)]
        self.axesOptions = {(False,2):[0,pi], (False,3):[0, pi*2/3, pi*4/3], (False,4):[0,pi/2,pi,pi*3/2], (False,5):[0,pi*2/5,pi*4/5,pi*6/5,pi*8/5], (True,2):[-pi/6,pi/6,pi*5/6,pi*7/6], (True,3):[-pi/9,pi/9,pi*5/9,pi*7/9,pi*11/9,pi*13/9]}
        
        self.rules = [(),2,'degree', 'clustering', 'closeness', 'centrality', 'betweeness','average neighbor degree']

    def test_make_axes(self):
        hive = self.emptyhive
        for (doubleAxes, numAxes), angles in self.axesOptions.iteritems():
            hive.doubleAxes = doubleAxes
            hive.numAxes = numAxes
            hive.make_axes()
            angles = [0.0001 if a == 0 else round(a,2) for a in angles]
            self.assertListEqual(angles, hive.angles)

    def test_get_assignment_values(self):
        hive = self.friendsHive
        values = hive.get_assignment_values(1)
        correctValues = {'Daniella': 'girl', 'George': 'alien', 'Fatima': 'girl', 'Cam': 'boy', 'Bob': 'boy', 'Alice': 'girl', 'Eric': 'boy'}
        self.assertEqual(values, correctValues)

        hive = self.friendsHiveDouble
        values = hive.get_assignment_values(1)
        correctValues = {'Eric.2': 'boy', 'Cam.2': 'boy', 'Cam.1': 'boy', 'Daniella.1': 'girl', 'Daniella.2': 'girl', 'George.2': 'alien', 'Fatima.2': 'girl', 'Fatima.1': 'girl', 'Eric.1': 'boy', 'Alice.1': 'girl', 'Alice.2': 'girl', 'Bob.2': 'boy', 'George.1': 'alien', 'Bob.1': 'boy'}
        self.assertEqual(values, correctValues)
        
        hive = self.friendsHive
        values = hive.get_assignment_values(2)
        correctValues = {'Daniella': 0.8, 'George': 0.9, 'Fatima': 0, 'Cam': 0.9, 'Bob': 0.2, 'Alice': 1.9, 'Eric': 1.6}
        self.assertEqual(values, correctValues)
        
        hive = self.friendsHiveDouble
        values = hive.get_assignment_values(2)
        correctValues = {'Eric.2': 1.6, 'Cam.2': 0.9, 'Cam.1': 0.9, 'Daniella.1': 0.8, 'Daniella.2': 0.8, 'George.2': 0.9, 'Fatima.2': 0, 'Fatima.1': 0, 'Eric.1': 1.6, 'Alice.1': 1.9, 'Alice.2': 1.9, 'Bob.2': 0.2, 'George.1': 0.9, 'Bob.1': 0.2}
        self.assertEqual(values, correctValues)
        
        hive = self.friendsHive
        values = hive.get_assignment_values('degree')
        correctValues = {'Alice': 4, 'Eric': 2, 'Daniella': 2, 'Fatima': 3, 'Cam': 3, 'Bob': 4, 'George': 2}
        self.assertEqual(values, correctValues)     

        hive = self.friendsHiveDouble
        values = hive.get_assignment_values('degree')
        correctValues = {'Bob.1': 4, 'Cam.2': 3, 'Cam.1': 3, 'Daniella.1': 2, 'Daniella.2': 2, 'George.2': 2, 'Fatima.2': 3, 'Fatima.1': 3, 'Bob.2': 4, 'Alice.1': 4, 'Alice.2': 4, 'Eric.1': 2, 'George.1': 2, 'Eric.2': 2}
        self.assertEqual(values, correctValues)  

    def test_node_assignment(self):
        hive = self.friendsHive
        for (double,numAxes),assignmentValues in zip(self.numAxesOptions,(self.friendsNodesValuesString, self.friendsNodesValuesInt, self.friendsNodesValuesFloat)):
            hive.numAxes = numAxes
            hive.doubleAxes = double
            hive.node_assignment(assignmentValues = assignmentValues)
            assignment = hive.axisAssignment
            #now we check that the axis assignment variable 
            #is a dictionary
            self.assertIsInstance(assignment, dict)
            #has an entry for every node
            self.assertEqual(set(assignment.keys()), set(hive.nodes))
            #that the values are integers corresponding to axes numbers
            [self.assertIsInstance(v,int) for v in assignment.values()]
Beispiel #30
0
from hive import Hive

user = input("Username / Email:  ")
password = input("Password:  "******"Node id: %s, name: %s"%(node['id'],node['name']))
#    print(node)

# Print all events - useful for recreating a previous webgui action
#h.get_events()
#for event in h.events:
#    print(event)

# Some commands, h.water_node and h.heating_node should be populated during init, if it doesn't or you have more than one Hive
# in your account then you should set the relevant property and then call schedule/boost in the same way.
# This is because the method checks the nodeid against these stored properties to work out if a water or heating
# action needs to be submitted.
#h.set_to_schedule(h.water_node)
#h.set_to_schedule(h.heating_node)
#h.set_boost(h.water_node)
#h.set_boost(h.heating_node)
Beispiel #31
0
 def __init__(self):
     self.zookeeper = Zookeeper()
     self.hadoop = Hadoop()
     self.hbase = HBase()
     self.hive = Hive()
     self.ignite = Ignite()
Beispiel #32
0
class Beewa:
    def __init__(self, username, password):
        # instantiation of Hive
        self.hive = Hive(username, password)

        # and login
        self.hive.login()

    def list(self, params='', args=''):
        # now for a list of devices
        data = self.hive.list()
        for device in data:
            if not device['name'].startswith(("http://", "Fake")):
                if self.hive._classify(device) in ['bulb']:
                    print("{}: {} (presence: {}, state: {})".format(
                        device['id'], device['name'],
                        device['attributes']['presence']['displayValue'],
                        device['attributes']['state']['displayValue']))
                else:
                    print("{}: {}".format(device['id'], device['name']))

    def info(self, params='', args=''):
        # Now for a list of devices
        try:
            data = self.hive.info(params)

            for value in data:
                if value in ['id', 'name']:
                    print("{}: {}".format(value, data[value]))
                elif value in ['attributes']:
                    data = data[value]
                    for value in data:
                        if value in ['state', 'presence', 'brightness']:
                            print("{}: {}".format(
                                value,
                                str(data[value]['displayValue']).lower()))
        except:
            exit("Unable to get information about device: {}".format(
                params[0]))

    def on(self, params='', args=''):
        # Now for a list of devices
        try:
            if self.hive.on(params):
                print("{} is now on".format(params[0]))
        except:
            exit("Unable to login to Hive at this time. Exiting.")

    def off(self, params='', args=''):
        # Now for a list of devices
        try:
            if self.hive.off(params):
                print("{} is now off".format(params[0]))
        except:
            exit("Unable to login to Hive at this time. Exiting.")

    def brightness(self, params='', args=''):
        # Now for a list of devices
        try:
            if self.hive.brightness(params):
                print("Set brightness of {} to {}%".format(
                    params[0], params[1]))
        except:
            exit("Unable to login to Hive at this time. Exiting.")

    def groups(self, params='', args=''):
        try:
            with open(args.groups) as f:
                data = json.loads(f.read())
        except IOError:
            exit("Unable to locate {} file".format(args.groups))

        # if they haven't submitted a subcommand
        if len(params) == 0:
            exit(self.groups_list(args.command[1:], data))

        try:
            method = False
            method = getattr(self, "groups_{}".format(params[0]))
            method(args.command[1:], data)
        except AttributeError:
            exit('groups {} is not a supported action'.format(params[0]))
        if not method:
            exit('groups {} is not a supported action'.format(params[0]))

    def groups_list(self, params='', data=''):
        # print a list of groups
        for group in data['groups']:
            print("===========\n{}\n===========".format(group))
            for device in data['groups'][group]:
                print(device)

    def groups_on(self, params='', data=''):
        # now we iterate through the devices and switch them on
        try:
            for device in data['groups'][params[1]]:
                if self.hive.on([device]):
                    print("{} is now on".format(device))
        except KeyError:
            exit("Unable to find group: {}".format(params[1]))

    def groups_off(self, params='', data=''):
        # now we iterate through the devices and switch them on
        try:
            for device in data['groups'][params[1]]:
                if self.hive.off([device]):
                    print("{} is now off".format(device))
        except KeyError:
            exit("Unable to find group: {}".format(params[1]))
Beispiel #33
0
def simulate(A, C, crit):

    env = None
    hive = None
    queen = None

    env = enviroment.Enviroment(100, 150, 3000, 24)

    queen = QueenBee(SIMUATION_TIME, A, C, crit)
    hive = Hive(SIMUATION_TIME, [0, 310, 207, None, 100, 100, 200])

    out_population = None
    out_honey = None

    average_flights_num = 10
    average_gather_to_weight_ratio = 0.1

    # gathering efficiency
    c1 = 3  # nectar
    c2 = 3  # pollen

    # scout flights loss ratio
    c3 = 0.15

    # nectar demands
    c4 = .2
    c5 = .285
    c6 = .09
    c7 = .14

    # pollen demands (relative to nectar demands)
    c8 = .2
    c9 = .18

    c10 = .08
    c11 = .006
    c12 = 0.5
    c13 = 0.2

    c14 = 0.11
    c15 = 0.3

    # c16 = 1

    c17 = 1
    c18 = 1

    E = 100000

    ########### initial resources
    hive.u11[0] = 4000  #rand.randint(2000, 10000)
    hive.u12[0] = 3000  #rand.randint(2000, 10000)
    hive.u2P[0] = 3000  #rand.randint(2000, 10000)
    ###########

    ###
    famine = None

    ###

    for day in range(SIMUATION_TIME):
        log.info("DAY %d" % day)

        if day > 0:
            if hive.u2P[day -
                        1] == 0 or hive.y1[day - 1] >= 3 * hive.y4[day - 1]:
                if hive.y1[day - 1] >= 3 * hive.y4[day - 1]:
                    log.warning("too many young bees")
                queen.b[day] = 0
            elif day > queen.k_crit:
                queen.b[day] = max(1 - (1 / E) * sum(hive.dy[:day]), 0)
            else:
                queen.b[day] = 1

        hive.dy[day] = int(queen.layEggs(day, hive.x13))

        # do bees growth
        hive.updatePopulation(day)

        log.info("🥚 x %d, 🐛 x %d, 🐜 x %d, 🐝 x %d (%d, %d, %d)" %
                 (hive.y[day], hive.y1[day], hive.y2[day], hive.y3[day],
                  hive.y4[day], hive.y5[day], hive.y6Q[day] + hive.y6V[day]))

        # do supply flights
        hive.u1[
            day] = c1 * average_flights_num * average_gather_to_weight_ratio * hive.y6Q[
                day]
        hive.u2[
            day] = c2 * average_flights_num * average_gather_to_weight_ratio * hive.y6V[
                day]

        log.debug("harvested: u1: %4.4f, u2: %4.4f" %
                  (hive.u1[day], hive.u2[day]))

        # store supplies
        hive.u11[day] = hive.u11[max(day - 1,
                                     0)] + hive.u1[day]  # - human factor
        hive.u12[day] = hive.u12[max(day - 1, 0)]  # - human factor
        hive.u2P[day] = hive.u2P[max(day - 1,
                                     0)] + hive.u2[day]  # - human factor

        # resource used on scout flights
        hive.x10[
            day] = c3 * average_flights_num * average_gather_to_weight_ratio * (
                hive.y6Q[day] + hive.y6V[day])
        hive.u11[day], _ = distribute_resources(hive.u11[day], hive.x10[day])

        # cannot have negative resources
        assert hive.u11[day] >= 0
        assert hive.u12[day] >= 0
        assert hive.u2P[day] >= 0

        log.debug("resources: u11: %4.4f, u12: %4.4f, u2P: %4.4f" %
                  (hive.u11[day], hive.u12[day], hive.u2P[day]))
        """ ----------------------- calculate resource demand -------------------------- """

        n = 4
        # calculate the building related stuff
        if day > 10 + n:
            hive.u3[day] = 0.3 * (
                c15 +
                (c14 / n) * sum(hive.x13[day -
                                         (9 + n):day - 9])) * hive.y5[day]
        log.debug("u3 = %4.4f" % hive.u3[day])

        ## RESOURCE DEMAND:
        # keep vital functions
        hive.x11d[day] = c4 * hive.y3[day]
        # proper larva growth
        hive.x12d[day] = c5 * hive.y1[day]
        # excess intake for feeding and larva care
        hive.x13d[day] = c6 * hive.y4[day] if (hive.y1[day] +
                                               hive.y[day]) > 0 else 0
        # excess intake for cluster building and wax synthesis
        hive.x14d[day] = c7 * hive.y5[day] if (hive.u3[day]) > 0 else 0

        log.debug(
            "demands: x11: %4.4f, x12: %4.4f, x13: %4.4f, x14: %4.4f," %
            (hive.x11d[day], hive.x12d[day], hive.x13d[day], hive.x14d[day]))

        ## CALCULATE ACTUAL NECTAR INTAKE (priority based):
        if hive.u11[day] >= (hive.x11d[day] + hive.x12d[day] + hive.x13d[day] +
                             hive.x14d[day]):
            # all demands can be satisfied
            log.info("all demands can be satisfied")
            hive.x11[day] = hive.x11d[day]
            hive.x12[day] = hive.x12d[day]
            hive.x13[day] = hive.x13d[day]
            hive.x14[day] = hive.x14d[day]

        elif (hive.x11d[day] + hive.x12d[day]) <= hive.u11[day]:
            # basic survival needs can be fully satisfied
            log.warn("basic survival needs can be fully satisfied")
            hive.x11[day] = hive.x11d[day]
            hive.x12[day] = hive.x12d[day]

            # other needs are diminished
            hive.x13[day] = (hive.x13d[day] / (hive.x13d[day] + hive.x14d[day])) * \
                (hive.u11[day] - (hive.x11d[day] + hive.x12d[day]))
            hive.x14[day] = hive.u11[day] - (hive.x11d[day] + hive.x12d[day] +
                                             hive.x13[day])

        elif hive.u11[day] < (hive.x11d[day] + hive.x12d[day]):
            # basic survival needs cannot be fully satisfied
            log.warn("basic survival needs cannot be fully satisfied")
            hive.x11[day] = hive.x11d[day]
            hive.x12[day] = hive.x12d[day]
            hive.x13[day] = 0
            hive.x14[day] = 0
        else:
            log.error("this should never occur")
            assert False

        ## POLLEN INTAKE
        hive.u2P[day], hive.x21[day] = distribute_resources(
            hive.u2P[day], c8 * hive.x11[day])
        hive.u2P[day], hive.x22[day] = distribute_resources(
            hive.u2P[day], c9 * hive.x12[day])
        hive.u2P[day], hive.x23[day] = distribute_resources(
            hive.u2P[day], c9 * hive.x13[day])
        hive.u2P[day], hive.x24[day] = distribute_resources(
            hive.u2P[day], c9 * hive.x14[day])

        # what's left after supply division
        hive.u2P_1[day] = hive.u2P[day]

        hive.u1_1[day] = hive.u11[day] + hive.u12[day] - (
            hive.x11[day] + hive.x12[day] + hive.x13[day] + hive.x14[day])

        if hive.u2P_1[day] <= 0 or hive.u1_1[day] <= 0:
            log.warning("u2P_1 == %4.4f, u1_1 == %4.4f" %
                        (hive.u2P_1[day], hive.u1_1[day]))
            if famine is None:
                famine = {'start_day': day, 'end_day': None}
            elif day - famine.get('start_day') > MAX_FAMINE_PERIOD:
                log.warning(" ☠️ ")
                out_population = 0
                break
        elif famine is not None:
            famine = None

        # calculate resources spent on building
        hive.x15[day] = c10 * hive.u3[day]
        hive.x25[day] = c11 * hive.u3[day]

        log.debug(
            "usage: x11: %4.4f, x12: %4.4f, x13: %4.4f, x14: %4.4f, x15: %4.4f"
            % (hive.x11[day], hive.x12[day], hive.x13[day], hive.x14[day],
               hive.x15[day]))
        log.debug(
            "usage: x21: %4.4f, x22: %4.4f, x23: %4.4f, x24: %4.4f, x25: %4.4f"
            % (hive.x21[day], hive.x22[day], hive.x23[day], hive.x24[day],
               hive.x25[day]))

        #hive.u2P[day], hive.x25[day] = distribute_resources(hive.u2P[day], hive.x15[day])
        hive.u2P[day], hive.x25[day] = distribute_resources(
            hive.u2P[day], hive.x25[day])

        hive.u11_2[day] = hive.u11[day] - (hive.x11[day] + hive.x12[day] +
                                           hive.x13[day] + hive.x14[day] +
                                           hive.x15[day])
        log.debug("liquid nectar after usage %4.4f" % hive.u11_2[day])
        if hive.u11_2[day] >= 0:
            # enough liquid nectar to satisfy needs
            hive.u12d[day] = c12 * hive.u11_2[day]
            hive.x16[day] = c13 * hive.u12d[day]

            assert c12 * (1 + c13) < 1

            hive.u11[day] = hive.u11_2[day] - hive.u12d[day] - hive.x16[day]
            hive.u12[day] += hive.u12d[day]
        else:
            # need to liquify some solid nectar
            hive.u11[day] = 0
            hive.u12[day], _ = distribute_resources(hive.u12[day],
                                                    -hive.u11_2[day])
            # hive.u12[day] += hive.u11_2[day]

        out_population = hive.sy[
            day] = c17 * hive.y[day] + hive.y1[day] + hive.y2[day]
        out_honey = hive.su[day] = c18 * (2 * hive.u11[day] + hive.u12[day] +
                                          hive.u2P[day])

        log.warning("SY = %d, SU = %d" % (hive.sy[day], hive.su[day]))
        """ ---------------------------------------------------------------------------- """

    log.info("queen params: A=%f, C=%d" % (queen.A, queen.C))
    fig, ax = plt.subplots(4, sharex=True)
    ax[0].set_ylabel("Populacja\nrodziny")
    ax[1].set_ylabel("Nośność\nmatki pszczelej")
    ax[2].set_ylabel("Zebrany\nnektar")
    ax[3].set_ylabel("Zebrany\npyłek")
    ax[3].set_xlabel("Dzień symulacji")
    ax[0].plot(hive.sy)
    ax[1].plot(hive.dy)
    ax[2].plot([sum(x) for x in zip(hive.u11, hive.u12)])
    ax[3].plot(hive.u2P)
    plt.show()

    data = {
        'i_queenA': queen.A,
        'i_queenC': queen.C,
        'i_queenKcrit': queen.k_crit,
        "o_population": out_population,
        "o_honey": out_honey,
        "mark": 1 if out_population >= 20000 else 0,
    }

    return data
Beispiel #34
0
    def __init__(self, username, password):
        # instantiation of Hive
        self.hive = Hive(username, password)

        # and login
        self.hive.login()
def main(*argv):
    '''handles user input and runs plsa'''
    parser = argparse.ArgumentParser(
        description=
        'This scripts produces hive plots given user data without the use of the gui.'
    )
    parser.add_argument('-t', help='Title of hive plot', default=gui.TITLE)
    parser.add_argument('-n', help='The node file', default=gui.NODES)
    parser.add_argument('-e', help='The edge file', default=gui.EDGES)
    parser.add_argument('-path',
                        help='Path where hive plot will be saved',
                        default=TEMP_FOLDER)
    parser.add_argument('-axes', help='Number of axes', type=int)
    parser.add_argument('-double',
                        help='Doubles the number of axes',
                        action='store_true')
    parser.add_argument('-assignment', help=assignmentHelp)
    parser.add_argument('-position', help=positionHelp)
    parser.add_argument('-size',
                        help='Size of hive plot: big or small',
                        default='small')
    parser.add_argument('-nodecolor', help='Color of nodes', default='purple')
    parser.add_argument('-edgestyle', help=edgeStyleHelp)
    parser.add_argument('-palette', help=paletteHelp, default='purple')
    parser.add_argument('-numcolors',
                        help='The number of colors to use to style edges',
                        default=1)
    parser.add_argument('-open',
                        help='Open the hive plot in the browser',
                        action='store_true')
    parser.add_argument('-debug',
                        help='Print verbatim to debug',
                        action='store_true')
    parser.add_argument('-properties',
                        help='Shows properties that can be used to plot hives',
                        action='store_true')
    args = parser.parse_args()

    if (args.n == '' and args.e != '') or (args.n != '' and args.e == ''):
        print "\n***You must specify both a node and an edge file if specifying either.***\n"
        parser.print_help()
        sys.exit()

    title = args.t
    nodeFile = args.n
    edgeFile = args.e
    axes = args.axes
    double = args.double
    assignment = args.assignment
    position = args.position
    size = gui_options.sizes[args.size]
    nodeColor = args.nodecolor
    edgeStyle = args.edgestyle
    numColors = args.numcolors
    palette = gui_utilities.get_palette(args.palette, int(numColors))
    open = args.open
    debug = args.debug
    folder = args.path

    if args.properties:
        hive = Hive(debug=debug)
        properties = list(
            hive.get_nodes(nodeFile).keys()) + gui_options.assignmentOptions
        print '\nNode properties:\n\t"' + '", "'.join(properties) + '"\n'
        properties = list(
            hive.get_edges(edgeFile)) + gui_options.edgeStyleOptions
        print 'Edge properties:\n\t"' + '", "'.join(properties) + '"\n'
        sys.exit()
    else:
        if not axes:
            print "You must specify a number of axes"
            sys.exit()
        if not assignment:
            print "You must specify a node assignment rule"
            sys.exit()
        if not position:
            print "You must specify a node position rule"
            sys.exit()

    hive = Hive(debug=debug,
                numAxes=axes,
                doubleAxes=double,
                axisAssignRule=assignment,
                axisPositRule=position,
                edgePalette=palette,
                edgeStyleRule=edgeStyle,
                nodeColor=nodeColor)
    hive.make_hive(nodeFile, edgeFile)

    rules = {}
    rules['assignment'] = assignment
    rules['position'] = position
    rules['edges'] = edgeStyle

    url = make_html(title, hive, size, rules=rules, folder=folder)

    if open:
        webbrowser.open("file://" + url, new=1)
Beispiel #36
0
 def __init__(self):
     self.zookeeper = Zookeeper()
     self.hadoop = Hadoop()
     self.hbase = HBase()
     self.hive = Hive()
     self.ignite = Ignite()
Beispiel #37
0
    if len(sys.argv) == 1:
        print "Type python %s -h or --help for options help." % sys.argv[0]
    else:
        if options.command == "":
            print "Must given -c option\"s value"
        else:
            if options.command == "requireInstall":
                Infra.install(ClusterOptions(True))

            if options.command == "deployAll":
                cluster_options = ClusterOptions(True)
                Zookeeper.install(cluster_options)
                Hadoop.install(cluster_options)
                Storm.install(cluster_options)
                Hive.install(cluster_options)
                HBase.install(cluster_options)

            if options.command == "startZookeeper":
                Zookeeper.start(ClusterOptions())

            if options.command == "stopZookeeper":
                Zookeeper.stop(ClusterOptions())

            if options.command == "startStorm":
                Storm.start(ClusterOptions())

            if options.command == "initCluster":
                Hadoop.init(ClusterOptions())

            if options.command == "startHadoop":
Beispiel #38
0
    def __init__(self,
                 width=GRID_WIDTH,
                 height=GRID_HEIGHT,
                 obstacle_density=15,
                 food_density=15,
                 nr_hives=3,
                 VIZUALISATION=False):
        super().__init__()
        self.height = height
        self.width = width
        self.nr_hives = nr_hives
        self.death_count = 0
        self.birth_count = 0
        self.death_age = []
        self.obstacle_density = obstacle_density
        self.food_density = food_density
        self.nr_hives = nr_hives
        self.load_count = 0

        self.user_error = None
        if self.obstacle_density + self.food_density > FOOD_OBSTACLE_RATIO:
            raise Exception("Food and obstacles do not fit in the grid.")

        hive_locations, food_locations, self.obstacle_locations = self.init_grid(
            height, width, self.obstacle_density, self.food_density,
            self.nr_hives)

        self.grid = MultiGridWithObstacles(self.width,
                                           self.height,
                                           torus=False,
                                           obstacle_positions=set(
                                               self.obstacle_locations),
                                           VIZUALISATION=VIZUALISATION)

        self.schedule = RandomActivationBeeWorld(self)

        self.hives = {}

        for hive_location in hive_locations:

            # Init Hives
            r = lambda: rd.randint(0, 255)
            color = '#{:02x}{:02x}{:02x}'.format(r(), r(), r())
            hive = Hive(self, hive_location, color=color, bee_color=color)

            self.hives[hive.unique_id] = hive
            self.add_agent(hive, hive_location)

            # Init Bees
            # TODO TAG BEES FOR WARM-UP PERIOD
            # TODO DEFINE THE AMOUNT OF STARTING BEES BABIES AS WELL
            for _ in range(0, 20):
                self.add_bee(hive=hive,
                             type_bee="scout",
                             color=hive.bee_color,
                             age=BABYTIME)

                self.add_bee(hive=hive,
                             type_bee="rester",
                             color=hive.bee_color,
                             age=BABYTIME)

        # TODO ADD MORE ROBUST RANDOMNESS TO FOOD UTILITY
        # DONE?
        for f_loc in food_locations:
            food = Food(self, f_loc)
            self.add_agent(food, f_loc)

        self.datacollector = DataCollector({
            "n_bees":
            lambda m: m.schedule.get_breed_count(Bee),
            "hive_food":
            lambda m: sum([h.get_food_stat() for h in m.hives.values()]),
            "scout_bees":
            lambda m: m.schedule.get_bee_count("scout"),
            "forage_bees":
            lambda m: m.schedule.get_bee_count("foraging"),
            "rest_bees":
            lambda m: m.schedule.get_bee_count("rester"),
            "baby_bees":
            lambda m: m.schedule.get_bee_count("babee"),
            "death_age":
            lambda m: m.get_death_age(),
            "n_births":
            lambda m: m.get_birth_count(),
            "n_deaths":
            lambda m: m.get_death_count(),
            "load_count":
            lambda m: m.load_count
        })

        self.running = True

        self.datacollector.collect(self)
        self.grid.warmup()
Beispiel #39
0
    def initialize_forest(self):
        """Adds initial organisms to the map."""

        directions = list(Direction)
        # Water map
        for pool_size in WATER_POOLS:
            rand_x = random.randint(0, self.width - 1)
            rand_y = random.randint(0, self.height - 1)
            while self.water_map[rand_x][rand_y]:
                rand_x = random.randint(0, self.width - 1)
                rand_y = random.randint(0, self.height - 1)
            water_pools_added = 0
            positions = [(rand_x, rand_y)]
            WATER_POOLS_POSITIONS.append((rand_x, rand_y))
            while water_pools_added < pool_size and positions:
                # Breadth first add water pools around
                x, y = positions.pop(0)
                if not self.water_map[x][y]:
                    water = Water(self, x, y)
                    self.water_map[x][y] = water
                    water_pools_added += 1
                    # Insert all neighbors
                    random.shuffle(
                        directions)  # shuffle for a bit random shapes
                    for dir in directions:
                        new_x = x + dir.value[0]
                        new_y = y + dir.value[1]
                        # Check if out of bounds
                        if new_x < 0 or new_x >= self.width or new_y < 0 or new_y >= self.height:
                            continue
                        if self.water_map[new_x][new_y]:
                            continue
                        positions.append((new_x, new_y))

        # Plant map
        for x in range(self.width):
            for y in range(self.height):
                # check if water
                if self.water_map[x][y]:
                    continue
                if random.random() <= TREE_PERCENTAGE:
                    tree = Tree(self, x, y)
                    self.plant_map[x][y] = tree
                    if random.random() <= HIVES_PER_TREE:
                        hive = Hive(self, x, y)
                        self.animal_map[x][y].append(hive)
                        bee_amount = random.randint(HIVE_BEE_MIN_AMOUNT,
                                                    HIVE_BEE_MAX_AMOUNT)
                        bee = Bee(self,
                                  x,
                                  y,
                                  hive=hive,
                                  scout=True,
                                  age=random.randint(0, 24 * 150))
                        hive.bees.append(bee)
                        self.animal_map[x][y].append(bee)
                        for _ in range(bee_amount):
                            bee = Bee(self,
                                      x,
                                      y,
                                      hive=hive,
                                      scout=False,
                                      age=random.randint(0, 24 * 150))
                            self.animal_map[x][y].append(bee)
                            hive.bees.append(bee)
                elif random.random() <= GRASS_INIT_PERCENTAGE:
                    grass = Grass(self, x, y, random.randint(-80, 100), None,
                                  self.get_initial_water_level(x, y))
                    self.plant_map[x][y] = grass
                else:
                    earth = Earth(self, x, y,
                                  self.get_initial_water_level(x, y))
                    self.plant_map[x][y] = earth

        # Flower map
        from organisms import Type
        for x in range(self.width):
            for y in range(self.height):
                if self.water_map[x][y]:
                    continue
                if random.random() <= FLOWER_PERCENTAGE:
                    if self.plant_map[x][y] and self.plant_map[x][
                            y].type == Type.TREE:
                        continue
                    for _ in range(random.randint(1, 4)):
                        flower = Flower(self,
                                        x,
                                        y,
                                        random.randint(-50, 100),
                                        nectar=random.randint(0, 100),
                                        has_seed=random.choice([True, False]))
                        self.flower_map[x][y].append(flower)

        # Animal map
        import numpy as np
        # Rabbits
        for _ in range(BURROW_AMOUNT):
            x = random.randint(0, self.width - 1)
            y = random.randint(0, self.height - 1)
            while self.water_map[x][y]:
                x = random.randint(0, self.width - 1)
                y = random.randint(0, self.height - 1)
            burrow = Burrow(self, x, y)
            self.animal_map[x][y].append(burrow)
            rabbit_amount = random.randint(BURROW_RABBIT_MIN_AMOUNT,
                                           BURROW_RABBIT_MAX_AMOUNT)
            for _ in range(rabbit_amount):
                dx = random.randint(-3, 3)
                dy = random.randint(-3, 3)

                if x + dx < 0 or x + dx >= self.width or y + dy < 0 or y + dy >= self.height:
                    continue

                if self.water_map[x + dx][y + dy]:
                    continue

                rabbit = Rabbit(self,
                                x + dx,
                                y + dy,
                                random.choice([True, False]),
                                adult=True,
                                burrow=burrow,
                                age=random.randint(24 * 30, 24 * 30 * 3),
                                reproduction_timer=random.randint(0, 24 * 6),
                                genetics_factor=np.random.normal(1, 0.1))
                self.animal_map[x + dx][y + dy].append(rabbit)

        # Foxes
        for _ in range(FOX_AMOUNT):
            x = random.randint(0, self.width - 1)
            y = random.randint(0, self.height - 1)
            while self.water_map[x][y]:
                x = random.randint(0, self.width - 1)
                y = random.randint(0, self.height - 1)
            fox = Fox(self,
                      x,
                      y,
                      random.choice([True, False]),
                      adult=True,
                      age=random.randint(24 * 30 * 2, 24 * 30 * 6),
                      genetics_factor=np.random.normal(1, 0.1))
            self.animal_map[x][y].append(fox)