Ejemplo n.º 1
0
  def test_get_population(self):
    my_graph = Graph()
    my_controller = Controller(my_graph)

    my_controller.parse_file("F:/rshan3/Airline/content/map_test_data.json")
    self.assertTrue(my_graph.get_biggest_city().code == 'MEX')
    self.assertTrue(my_graph.get_smallest_city().code == 'SCL')
Ejemplo n.º 2
0
  def test_get_average_distances_of_flight(self):
    my_graph = Graph()
    my_controller = Controller(my_graph)

    my_controller.parse_file("F:/rshan3/Airline/content/map_test_data.json")
    #print(my_graph.list_metros())
    self.assertTrue(my_graph.get_average_distances_of_flight() == (4231+2453)/2.0 )
Ejemplo n.º 3
0
  def test_list_metros(self):
    my_graph = Graph()
    my_controller = Controller(my_graph)

    my_controller.parse_file("F:/rshan3/Airline/content/map_test_data.json")
    #print(my_graph.list_metros())
    self.assertTrue(len(my_graph.list_metros()) == 3 )
Ejemplo n.º 4
0
  def test_get_single_flight(self):
    my_graph = Graph()
    my_controller = Controller(my_graph)

    my_controller.parse_file("F:/rshan3/Airline/content/map_test_data.json")
    #print(my_graph.list_metros())
    self.assertTrue(my_graph.get_longest_single_flight().distance == 4231 )
    self.assertTrue(my_graph.get_shortest_single_flight().distance == 2453)
Ejemplo n.º 5
0
  def test_get_city_info(self):
    my_graph = Graph()
    my_controller = Controller(my_graph)

    my_controller.parse_file("F:/rshan3/Airline/content/map_test_data.json")

    self.assertTrue(my_graph.get_city_info('LIM') is not None)
    self.assertTrue(my_graph.get_city_info('LIMM') is None)
    self.assertTrue(my_graph.get_city_info("Lima") is not None)
Ejemplo n.º 6
0
    def profondeurLimit(self):
        self.base = BaseDeConnaissance(self.path)
        self.tbResolution.setText("")
        etatFinal = self.txEtatFinal.toPlainText()
        EtatInit = self.base.faits[0].predicat
        graphe = Graph(EtatInit)
        nouedFermées = []
        nouedOuverts = [EtatInit]
        i = 0

        # Graph construction
        while nouedOuverts:

            nouedCourant = nouedOuverts.pop(0)
            nouedFermées.append(nouedCourant)
            self.base.faits = nouedCourant
            possibleConclusions = genererConclusionUnifies(
                self.base.regles, nouedCourant)

            for conclusion in possibleConclusions:
                graphe.addEdge(nouedCourant, conclusion)
                if not exist(conclusion, nouedFermées) and not exist(
                        conclusion, nouedOuverts):
                    nouedOuverts.append(conclusion)
            i += 1
        test = Predicat.extractPredicat(etatFinal)
        #test = Predicat("cruchesAetB", ['4', '2'])
        chemin = []
        solution = 'chemin:'
        print(
            graphe.rechercheProfendeurLimiteIteratif(graphe.V, test, 10,
                                                     chemin))
        solution += '\n'
        chemin = algorithmService.prepareChemin(chemin, graphe.V)
        for chem in chemin:
            solution += str(chem) + '\n'
        self.tbResolution.setText("")
        self.tbResolution.setText(solution)
        self.textBrowser.setText("")
        self.textBrowser.setText(str(graphe.trace))
Ejemplo n.º 7
0
    def onStar(self):
        self.base = BaseDeConnaissance(self.path)
        self.tbResolution.setText("")
        EtatInit = self.base.faits[0].predicat
        graphe = Graph(EtatInit)
        nouedFermées = []
        nouedOuverts = [EtatInit]
        i = 0

        # Graph construction
        while nouedOuverts:

            nouedCourant = nouedOuverts.pop(0)
            nouedFermées.append(nouedCourant)
            self.base.faits = nouedCourant
            possibleConclusions = genererConclusionUnifies(
                self.base.regles, nouedCourant)

            for conclusion in possibleConclusions:
                graphe.addEdge(nouedCourant, conclusion)
                if not exist(conclusion, nouedFermées) and not exist(
                        conclusion, nouedOuverts):
                    nouedOuverts.append(conclusion)
            i += 1

        etatFinal = self.txEtatFinal.toPlainText()
        test = Predicat.extractPredicat(etatFinal)
        solution = 'chemin\n'

        result, parcours = graphe.a_star_search(graphe.V, test)
        for chem in parcours:
            print(chem)
            solution += str(chem) + '\n'
        self.tbResolution.setText("")
        self.tbResolution.setText(solution)
        self.textBrowser.setText("")
        self.textBrowser.setText(graphe.trace)
Ejemplo n.º 8
0
def simulate(cars_no):
    # env = simpy.rt.RealtimeEnvironment()
    env = simpy.Environment()
    light_groups = [[13, 15], [17, 19], [12, 14], [16, 18]]

    lightManager = TrafficLightManager(env, light_groups, 20)
    graph = Graph(lightManager)

    vehicles = []

    for c in range(cars_no):
        vehicle = Vehicle(env, c, random.choice(graph.start_nodes),
                          random.choice(graph.end_nodes), graph,
                          max(numpy.random.normal(loc=20.0, scale=2.0), 20.0))
        vehicles.append(vehicle)

    env.run(until=60 * 60 * 2)

    return vehicles
Ejemplo n.º 9
0
 def initialize(self):
     graph = Graph()
     graph.parseFile(FILE)
Ejemplo n.º 10
0
'''
Created on Feb 28, 2014

@author: Will
'''
from model.Graph import Graph
import sys

FILE = Graph.FILE
graph = Graph()


class Stats():

    # Creates the underlying graph for
    # which we do statistics by parsing the file
    def initialize(self):
        graph = Graph()
        graph.parseFile(FILE)

    # Prints out a list of all the cities
    # that CSAir flies to.
    def allCities(self):
        for city in graph.nodes:
            print city['name']

    # Gets the average of all the populations
    # of the given graph of cities
    #
    # @return the overall average city population
    def averagePopulation(self):
Ejemplo n.º 11
0
def start_run_task(task):
    try:
        user_uuid = task.model.user.uuid
    except:
        logger.error("no user")
    try:
        success = True
        graph = Graph()
        if not graph.load(task.text):
            pass
        else:
            task.start_time = datetime.datetime.utcnow() - datetime.timedelta(hours=6)

            task.end_time = None
            task.complete_percent = 0
            task.state = 1
            task.save()

            # 文件夹处理
            file_root = setting.UPLOADS_ROOT
            user_root = os.path.join(file_root, str(user_uuid))
            task_path = os.path.join(user_root, str(task.uuid))
            model_id = task.model.uuid
            model_name = task.model.name
            model_root = os.path.join(user_root, model_name)
            #  兼容之前的模式
            if not os.path.exists(model_root):
                os.mkdir(model_root)
            task_path = os.path.join(model_root, task.name)
            if os.path.exists(task_path):
                shutil.rmtree(task_path)
            os.mkdir(task_path)
            info = ("create task folder:{0}".format(task_path))
            logger.info(info)
            #生成执行计划
            flow = graph.plan()
            if flow:

                Process.objects.filter(task=task).delete()

                #生成执行步骤及其状态,记录Process的状态
                processes = []
                for func in flow:
                    process = task.process_set.create(
                        name = func.getName(),
                        node_id = func.getID()
                        #start_time = timezone.now(),
                        #end_time = timezone.now()
                    )
                    process.save()
                    processes.append(process)

                #执行Plan
                count = len(processes)
                for i in range(count):
                    # 先判断是否已经失败了
                    task = Task.objects.get(uuid=task.uuid)
                    if task.state == 3:
                        info = "task[{0}] already fail".format(str(task.uuid))
                        success = False;
                        errmsg = "run task failed:already fail"
                        break;

                    #执行func
                    #更新process的状态为正在执行
                    process = processes[i]
                    process.state = 1
                    process.complete_percent = 0
                    process.start_time = datetime.datetime.utcnow() - datetime.timedelta(hours=6)
                    process.save()


                    ###################################################
                    # 执行计算任务 Begin
                    ###################################################
                    func = flow[i]
                    #processing func

                    success = False
                    errmsg  = ""
                    process_func_name = "process_" + func.getName()
                    #检查是否存在相应的处理函数
                    if hasattr(functions, process_func_name.lower()):
                        #如果存在相应的处理函数,则获取该处理函数
                        f = getattr(functions, process_func_name.lower())
                        #处理计算任务
                        info = "run {0} function".format(process_func_name)
                        try:
                            success = f(func,process,str(user_uuid))
                        except Exception as e:
                            errmsg = "process {0} run failed :{1}".format(process_func_name,str(e))

                            success = False
                    else:
                        errmsg = "方法[{0}]尚未在系统中注册".format(func.getName());

                        success = False

                    # time.sleep(5)
                    ###################################################
                    # 执行计算任务 End
                    ###################################################

                    ###################################################
                    # 设置Process的状态 Begin
                    ###################################################
                    if success == True:
                        # 更新process的状态为结束,并记录结束时间
                        process.end_time = datetime.datetime.utcnow() - datetime.timedelta(hours=6)
                        process.state = 2   #success
                        process.complete_percent = 100
                        process.save()

                        task = Task.objects.get(uuid=task.uuid)
                        if task.state == 3:
                            errmsg = "user stop task already"
                            success = False
                            break;

                        # 更新task的percent
                        task.complete_percent = 100 * (i+1) / count
                        task.save()
                        info = "process[{0}] run success".format(str(process.id))
                        logger.info(info)
                    else:
                        # 更新process的状态为结束,并记录结束时间
                        process.state = 3   #failure
                        process.save()
                        # errmsg = "process[{0}] run failed".format(str(process.id))
                        info = "process[{0}] run failed".format(str(process.id))
                        logger.error(info)
                        break
                    ###################################################
                    # 设置Process的状态 End
                    ###################################################

            ###################################################
            # 设置Task的状态 Begin
            ###################################################
            if success==True:
                task.state = 2
                task.end_time = datetime.datetime.utcnow() - datetime.timedelta(hours=6)

                task.complete_percent = 100
                info = "task[{0}] run success".format(str(task.uuid))
                logger.info(info)
            else:
                task.state =  3  # 设置task的状态
                info = "task[{0}] run fail".format(str(task.uuid))
                logger.error(info)
            task.save()
            ###################################################
            # 设置Task的状态 End
            ###################################################

    except Exception as e:
        task.state = 3
        task.save();
        info = "run task failed:{0}".format(str(e))
        logger.error(info)
    finally:
        connection.close()
Ejemplo n.º 12
0
FILE = Graph.FILE


class CircleMap():
    # A function to create a URL leading to
    # the Great Circle Mapper website which
    # will display the image for us.
    #
    # E.g. "http://www.gcmap.com/mapui?P=LIM-MEX,+LIM-BOG,+MEX-LAX"
    #
    # @input graph the given graph representation
    #              for our input
    def createURL(self, graph):
        url = "http://www.gcmap.com/mapui?P="

        routes = ""
        for start in graph.nodes:
            for end in graph.nodes[start]['rels'].keys():
                routes += start + "-" + end + ",+"

        url += routes[:-2]
        return url


if __name__ == '__main__':
    map = CircleMap()
    graph = Graph()
    graph.parseFile(FILE)
    url = map.createURL(graph)
    webbrowser.open(url, new=2)
Ejemplo n.º 13
0
from model.BaseDeConnaissance import BaseDeConnaissance
from model.Graph import Graph
from model.Predicat import Predicat
from service import algorithmService
from service.algorithmService import *

base = BaseDeConnaissance("E:/GL4/AI/TPs/TP2-AI/cruches.txt")

for regle in (genererConclusionUnifies(
        base.regles, Predicat.extractPredicat('cruchesAetB(4,0)'))):
    pass

EtatInit = base.faits[0].predicat
graphe = Graph(EtatInit)
nouedFermées = []
nouedOuverts = [EtatInit]
i = 0

# Graph construction
while nouedOuverts:

    nouedCourant = nouedOuverts.pop(0)
    nouedFermées.append(nouedCourant)
    base.faits = nouedCourant
    possibleConclusions = genererConclusionUnifies(base.regles, nouedCourant)

    for conclusion in possibleConclusions:
        graphe.addEdge(nouedCourant, conclusion)
        if not exist(conclusion, nouedFermées) and not exist(
                conclusion, nouedOuverts):
            nouedOuverts.append(conclusion)
Ejemplo n.º 14
0
 def setUp(self):
     self.graph = Graph()
     self.graph.nodes = []
     self.graph.nodes = []
Ejemplo n.º 15
0
 def testGraphDistances(self):
     graph = Graph()
     graph.parseFile(TESTFILE)
     self.assertEqual(graph.nodes['LIM']['rels']['SCL'], 2453)
Ejemplo n.º 16
0
 def initialize(self):
     graph = Graph()
     graph.parseFile(FILE);
Ejemplo n.º 17
0
 def testGraphNode(self):
     graph = Graph()
     graph.parseFile(TESTFILE)
     self.assertEqual(graph.nodes['SCL']['code'], 'SCL')
     self.assertEqual(graph.nodes['SCL']['continent'], 'South America')
Ejemplo n.º 18
0
 def testGraphRelations(self):
     graph = Graph()
     graph.parseFile(TESTFILE)
     self.assertEqual(graph.nodes['LIM']['rels'].keys(),[u'SCL',u'MEX',u'BOG'])
Ejemplo n.º 19
0
 def testGraphNode(self):
     graph = Graph()
     graph.parseFile(TESTFILE)
     self.assertEqual(graph.nodes['SCL']['code'],'SCL')
     self.assertEqual(graph.nodes['SCL']['continent'],'South America')
Ejemplo n.º 20
0
FILE = Graph.FILE

class CircleMap():
    # A function to create a URL leading to 
    # the Great Circle Mapper website which
    # will display the image for us.
    #
    # E.g. "http://www.gcmap.com/mapui?P=LIM-MEX,+LIM-BOG,+MEX-LAX"
    #
    # @input graph the given graph representation 
    #              for our input
    def createURL(self,graph):
        url = "http://www.gcmap.com/mapui?P="
        
        routes = ""
        for start in graph.nodes:
            for end in graph.nodes[start]['rels'].keys():
                routes += start + "-" + end + ",+"
                
        
        url += routes[:-2]
        return url 
            

if __name__ == '__main__':
    map = CircleMap()
    graph = Graph()
    graph.parseFile(FILE)
    url = map.createURL(graph)
    webbrowser.open(url,new=2)
    
Ejemplo n.º 21
0
  def test_get_hub(self):
    my_graph = Graph()
    my_controller = Controller(my_graph)

    my_controller.parse_file("F:/rshan3/Airline/content/map_test_data.json")
    self.assertTrue(my_graph.get_hub()[0] == 'Lima')
Ejemplo n.º 22
0
class AirGraphTest(unittest.TestCase):
    global graph
    def setUp(self):
        self.graph = Graph()
        self.graph.nodes = []
        self.graph.nodes = []
    
    def testAddNode(self):
        data = "BLARGH"
        self.graph.add_node(data)
        node = self.graph.nodes[0]
        self.assertEquals(node.get_data(),"BLARGH")
    
    def testAddEdge(self):
        source = Node()
        source.set_data("BLECH")
        target = Node()
        target.set_data("ARGHH")
        self.graph.add_edge(source,target,1000)
        edge = self.graph.edges[0]
        self.assertEquals(edge.get_source().get_data(),"BLECH")
        self.assertEquals(edge.get_target().get_data(),"ARGHH")
    
    def testFindEdge(self):
        source = Node()
        source.set_data("BLACK")
        target = Node()
        target.set_data("WHITE")
        self.graph.add_edge(source,target,1)
        
        edge = self.graph.find_edge(source,target)
        sourcedata = edge.get_source().get_data()
        targetdata = edge.get_target().get_data()
        
        self.assertEquals(sourcedata,"BLACK")
        self.assertEquals(targetdata,"WHITE")
        
    '''
    This test is performed on a representation of the 
    graph in "CSAir/examples/dijikstra_example.png", where
    the nodes are labeled with red numbers. The result should 
    be 0->2->3->2->4, which is of length 2+1+1+4=8.
    '''
    def testDijikstra(self):
        nodes = self.graph.nodes
        edges = self.graph.edges
        for i in range (0,7):
            node = Node()
            node.set_data(str(i))
            self.graph.nodes.append(node)
        for i in range (1,7):
            edge = Edge()
            self.graph.edges.append(edge)
            
        edges[0].set_info(nodes[0],nodes[3],2)
        edges[1].set_info(nodes[0],nodes[2],6)
        edges[2].set_info(nodes[1],nodes[2],3)
        edges[3].set_info(nodes[1],nodes[3],1)
        edges[4].set_info(nodes[2],nodes[3],1)
        edges[5].set_info(nodes[2],nodes[4],4)
        edges[6].set_info(nodes[3],nodes[4],6)
        
        edgelist = self.graph.dijikstra(nodes[0],nodes[4])
        correct_edgelist = [edges[0],edges[3],edges[4],edges[5]]
        #self.assertEquals(edgelist,correct_edgelist)
        
        
    def testValidPath(self):
        for i in range(0,10):
            node = Node()
            node.set_data(str(i))
            self.graph.nodes.append(node)

        for i in range(0,8):
            edge = Edge()
            edge.set_info(self.graph.nodes[i],self.graph.nodes[i+1],i)
            self.graph.edges.append(edge)
            
        valid_path = self.graph.is_valid_path(self.graph.nodes[:-1])
        self.assertTrue(valid_path)
        
    def testInvalidPath(self):
        self.graph.nodes = []
        self.graph.edges = []
        for i in range(1,10):
            node = Node()
            self.graph.nodes.append(node)
        for i in range(1,8):
            edge = Edge()
            edge.set_info(self.graph.nodes[i],self.graph.nodes[i+1],i)
            self.graph.edges.append(edge)
            
        self.graph.edges.remove(self.graph.edges[5])
        valid_path = self.graph.is_valid_path(self.graph.nodes)
        self.assertFalse(valid_path)
Ejemplo n.º 23
0
 def testGraphDistances(self):
     graph = Graph()
     graph.parseFile(TESTFILE)
     self.assertEqual(graph.nodes['LIM']['rels']['SCL'],2453)
Ejemplo n.º 24
0
 def testGraphRelations(self):
     graph = Graph()
     graph.parseFile(TESTFILE)
     self.assertEqual(graph.nodes['LIM']['rels'].keys(),
                      [u'SCL', u'MEX', u'BOG'])