Esempio n. 1
0
    def checkandOperate(self):
        #split the userInput with ' " ', and 2 is the largest index of the return list
        inputInfoSplit = self.str.split("\"", 2)
        # #print("cmd:", inputInfoSplit[0])
        #inputInfoSplit contains [cmd, streetname, streetpoints] which is not verified yet
        if len(inputInfoSplit) == 1:
            #g
            stdGraph = re.compile(r'[g][ ]*')
            graphMatchResult = re.match(stdGraph, inputInfoSplit[0])
            if not graphMatchResult:
                raise Exception("Error: Wrong command.")
            else:
                #graph
                graph.build_graph()


#                print("graph")
        elif len(inputInfoSplit) == 0:
            raise Exception("Error: Not enough arguments.")
        elif len(inputInfoSplit) == 3 or len(inputInfoSplit) == 2:
            #verify Command using regular expression
            #(permitting cmd entered with blank(s))
            stdCmds = re.compile(r'[acr][ ]*')
            cmdMatchResult = re.match(stdCmds, inputInfoSplit[0])
            if not cmdMatchResult:
                raise Exception("Error: Wrong command.")
            else:
                self.cmd = inputInfoSplit[0]

                #verify Streetname
                stdStreetName = re.compile(r'^([a-zA-Z ])+$')
                nameMatchResult = re.match(stdStreetName, inputInfoSplit[1])
                if not nameMatchResult:
                    raise Exception(
                        "Error: Wrong name format.(accept letters and blanks)")
                else:
                    self.street.name = inputInfoSplit[1]
                    #add
                    stdAdd = re.compile(r'[a][ ]*')
                    addMatchResult = re.match(stdAdd, self.cmd)
                    #change
                    stdChang = re.compile(r'[c][ ]*')
                    changMatchResult = re.match(stdChang, self.cmd)
                    #remove
                    stdRemove = re.compile(r'[r][ ]*')
                    removeMatchResult = re.match(stdRemove, self.cmd)

                    if addMatchResult:
                        self.checkandAdd(inputInfoSplit)
                    elif changMatchResult:
                        self.checkandChange(inputInfoSplit)
                    elif removeMatchResult:
                        self.checkandRemove(inputInfoSplit)
                    else:
                        pass
        else:
            raise Exception("Error: Wrong command and arguments.")
Esempio n. 2
0
def graphs():
    x1 = [0, 1, 2, 3, 4]
    y1 = [10, 30, 40, 5, 50]
    x2 = [0, 1, 2, 3, 4]
    y2 = [50, 30, 20, 10, 50]

    graph1_url = build_graph(x1, y1)
    graph2_url = build_graph(x2, y2)

    return render_template('graphs.html', graph1=graph1_url, graph2=graph2_url)
Esempio n. 3
0
def graph ():
    x1 = [0, 1, 2, 3, 4]
    y1 = [10, 30, 40, 5, 50]
    x2 = [0, 1, 2, 3, 4]
    y2 = [50, 30, 20, 10, 50]
    x3 = [0, 1, 2, 3, 4]
    y3 = [0, 30, 10, 5, 30]	
    graph1_url = build_graph(x1,y1);
    graph2_url = build_graph(x2,y2);
    graph3_url = build_graph(x3,y3);
 
    return render_template('graph.html', graph1=graph1_url, graph2=graph2_url, graph3=graph3_url)
Esempio n. 4
0
def build_map(array):
    '''
    Builds map with countries in colours.
    '''
    print('')
    with open('locations.json', 'r', encoding='utf-8') as f:
        dicti = json.load(f)

    user_map = folium.Map(max_zoom=7, min_zoom=2)
    country_names = []
    dicti_coor = {}
    for q in array:
        years = []
        users = []
        cur = q._qhead
        while cur is not None:
            years.append(cur.year)
            users.append(cur.item)
            cur = cur.next
        dicti_coor[tuple(dicti[q._name])] = (tuple(users), tuple(years),
                                             q._name)
        country_names.append(q._name)

    fg_psn = folium.FeatureGroup(name="Users")
    fg_psn.add_child(
        folium.GeoJson(
            data=open('world.json', 'r', encoding='utf-8-sig').read(),
            style_function=lambda x: {
                'fillColor':
                'red' if x['properties']['NAME'] in country_names else 'white',
                'color':
                'black',
                'weight':
                2.5
            })).add_to(user_map)

    for loc in dicti_coor:
        location = loc
        (users, years, country) = dicti_coor[loc]
        build_graph(users, years, country)
        encoded = base64.b64encode(
            open('graphs/graph' + country + '.JPG', 'rb').read())
        html = '<img src="data:image/jpeg;base64,{}">'.format
        iframe = folium.IFrame(html(encoded.decode('UTF-8')),
                               width=420,
                               height=308)
        popup = folium.Popup(iframe, max_width=2000)
        folium.Marker(location=[float(location[0]),
                                float(location[1])],
                      popup=popup).add_to(user_map)

    user_map.save('templates/users.html')
Esempio n. 5
0
def run(session):
    batcher = preprocessing.Batcher(config.SUBSAMPLE_THRESHOLD,
                                    config.TEST_MODE)
    num_batches = batcher.num_batches(config.BATCH_SIZE)
    graph = graph_fns.build_graph(
        vocab_size=batcher.vocab_size(),
        num_embedding_units=config.NUM_EMBEDDING_UNITS,
        num_negative_samples=config.NUM_NEGATIVE_SAMPLES,
    )

    session.run(tf.global_variables_initializer())

    run_info = RunInfo(
        session=session,
        graph=graph,
        saver=tf.train.Saver(),
        batcher=batcher,
        validator=validator.Validator(batcher.vocab_size(),
                                      graph.embedding_matrix),
        batch_size=config.BATCH_SIZE,
        window_size=config.WINDOW_SIZE,
        batches_per_epoch=num_batches,
        batches_per_logging=int(num_batches * config.LOGGING_FREQUENCY),
        batches_per_save=int(num_batches * config.SAVING_FREQUENCY),
        batches_per_validation=int(num_batches * config.VALIDATION_FREQUENCY),
    )

    for epoch_idx in range(1, config.NUM_EPOCHS + 1):
        run_epoch(run_info, epoch_idx)
Esempio n. 6
0
def get_segmented_image(sigma, neighbor, K, min_comp_size, input_file,
                        output_file):
    if neighbor != 4 and neighbor != 8:
        logger.warn(
            'Invalid neighborhood choosed. The acceptable values are 4 or 8.')
        logger.warn('Segmenting with 4-neighborhood...')
    start_time = time.time()
    image_file = Image.open(input_file)

    size = image_file.size  # (width, height) in Pillow/PIL
    logger.info('Параметры изображения: {} | {} | {}'.format(
        image_file.format, size, image_file.mode))

    # Gaussian Filter
    smooth = image_file.filter(ImageFilter.GaussianBlur(sigma))
    smooth = np.array(smooth).astype(int)

    logger.info("Создание графа...")
    graph_edges = build_graph(smooth, size[1], size[0], diff, neighbor == 8)

    logger.info("Вычисление разреза...")
    forest = segment_graph(graph_edges, size[0] * size[1], K, min_comp_size,
                           threshold)

    logger.info("Визуализация: {}".format(output_file))
    image = generate_image(forest, size[1], size[0])
    image.save(output_file)

    logger.info('Количество сегментов: {}'.format(forest.num_sets))
    logger.info('Общее время выполнения: {:0.4}s'.format(time.time() -
                                                         start_time))
Esempio n. 7
0
def main(sigma, neighborhood, K ,min_size ,input_file):
		neighbor = neighborhood
		if neighbor != 4 and neighbor!= 8:
			print('Invalid neighborhood choosed. The acceptable values are 4 or 8.')
			print('Segmenting with 4-neighborhood...')

		image_file = Image.open(input_file)
		image_file = image_file.resize((250,250))

		size = image_file.size
		#print ('Image info: ', image_file.format, size, image_file.mode)

		grid = gaussian_grid(sigma)

		#2print(image_file.mode)
		if image_file.mode == 'RGB':
			image_file.load()
			r, g, b = image_file.split()

			r = filter_image(r, grid)
			g = filter_image(g, grid)
			b = filter_image(b, grid)

			smooth = (r, g, b)
			diff = diff_rgb
		else:
			return 0

		graph = build_graph(smooth, size[1], size[0], diff, neighbor == 8)
		forest = segment_graph(graph, size[0]*size[1], K, min_size, threshold)

		image = generate_image(image_file , forest, size[1], size[0])
		return image

		print ('Number of components: %d' % forest.num_sets)
Esempio n. 8
0
def get_segmented_image(sigma, neighbor, K, min_comp_size, input_file, output_file):
    if neighbor != 4 and neighbor!= 8:
        logger.warn('Invalid neighborhood choosed. The acceptable values are 4 or 8.')
        logger.warn('Segmenting with 4-neighborhood...')
    start_time = time.time()
    image_file = Image.open(input_file)

    size = image_file.size  # (width, height) in Pillow/PIL
    logger.info('Image info: {} | {} | {}'.format(image_file.format, size, image_file.mode))

    # Gaussian Filter
    smooth = image_file.filter(ImageFilter.GaussianBlur(sigma))
    smooth = np.array(smooth)
    
    logger.info("Creating graph...")
    graph_edges = build_graph(smooth, size[1], size[0], diff, neighbor==8)
    
    logger.info("Merging graph...")
    forest = segment_graph(graph_edges, size[0]*size[1], K, min_comp_size, threshold)

    logger.info("Visualizing segmentation and saving into: {}".format(output_file))
    image = generate_image(forest, size[1], size[0])
    image.save(output_file)

    logger.info('Number of components: {}'.format(forest.num_sets))
    logger.info('Total running time: {:0.4}s'.format(time.time() - start_time))
Esempio n. 9
0
def get_segmented_image(sigma, neighbor, K, min_comp_size, input_file,
                        output_file):
    if neighbor != 4 and neighbor != 8:
        logger.warn(
            'Invalid neighborhood choosed. The acceptable values are 4 or 8.')
        logger.warn('Segmenting with 4-neighborhood...')
    start_time = time.time()
    image_file = Image.open(input_file)

    size = image_file.size  # (width, height) in Pillow/PIL
    logger.info('Image info: {} | {} | {}'.format(image_file.format, size,
                                                  image_file.mode))

    # Gaussian Filter
    smooth = image_file.filter(ImageFilter.GaussianBlur(sigma))
    smooth = np.array(smooth)

    logger.info("Creating graph...")
    graph_edges = build_graph(smooth, size[1], size[0], diff,
                              neighbor == 8)  #返回8邻域中任意两个节点间的连接权值

    logger.info("Merging graph...")
    forest = segment_graph(graph_edges, size[0] * size[1], K, min_comp_size,
                           threshold)

    logger.info(
        "Visualizing segmentation and saving into: {}".format(output_file))
    image = generate_image(forest, size[1], size[0])
    image.save(output_file)

    logger.info('Number of components: {}'.format(forest.num_sets))
    logger.info('Total running time: {:0.4}s'.format(time.time() - start_time))
Esempio n. 10
0
def run():
    train_batches, validation_batches = batcher.partition_batches(
        batcher.make_batches(config.file_reader.one_hot_text(),
                             config.BATCH_SIZE, config.STEP_SIZE))

    num_training_batches = len(train_batches)
    num_validation_batches = len(validation_batches)
    batches_per_save = int(config.SAVE_FREQUENCY * num_training_batches)
    batches_per_validation = int(config.VALIDATION_FREQUENCY *
                                 num_training_batches)

    graph = graph_fns.build_graph(config.BATCH_SIZE,
                                  config.file_reader.vocab_size(),
                                  config.NUM_LAYERS, config.STEP_SIZE,
                                  config.NUM_LSTM_UNITS)

    saver = tf.train.Saver()

    run_info = RunInfo(train_batches=train_batches,
                       validation_batches=validation_batches,
                       num_training_batches=num_training_batches,
                       num_validation_batches=num_validation_batches,
                       batches_per_save=batches_per_save,
                       batches_per_validation=batches_per_validation,
                       graph=graph,
                       saver=saver)

    with tf.Session() as session:
        session.run(tf.global_variables_initializer())
        for epoch_idx in range(config.NUM_EPOCHS):
            run_epoch(session, run_info, epoch_idx)
Esempio n. 11
0
def graph_based_segmentation(neighbor_list, num_nodes, K, min_size, threshold):
    xcoor = []
    ycoor = []
    diff = []
    length = 0
    for i in range(len(neighbor_list)):
        xcoor.append(neighbor_list[i][0])
        ycoor.append(neighbor_list[i][1])
        diff.append(neighbor_list[i][2])
    graph = build_graph(length, diff, xcoor, ycoor)
    forest = segment_graph(graph, num_nodes + 1, K, min_size, threshold)

    # output prediction results
    prediction = []
    for x in xrange(num_nodes + 1):
        prediction.append(forest.find(x))

    # prediction clusters rename
    name_set = []
    for name in prediction:
        if name not in name_set:
            name_set.append(name)
    rename = {}
    for i in range(len(name_set)):
        rename[name_set[i]] = i + 1
    for i in range(len(prediction)):
        prediction[i] = rename[prediction[i]]

    # Write results to files and save
    # with open('prediction','w') as f:
    #     for i in prediction:
    #         f.write(str(i) + '\n')

    return [forest, prediction]
Esempio n. 12
0
def seg_a_img(img, img_name, img_mode="remote_sensing"):

    grid = gaussian_grid(SIGMA)

    if img_mode == "remote_sensing":
        c, h, w = img.shape[0], img.shape[1], img.shape[2]
        print("we are working in geo-tif mode, img is read by gdal")
        img_bands = []
        for i in range(c):
            img_bands.append(filter_image(img[i], grid))
        smooth = tuple(img_bands)
        diff = diff_geoTif

    elif img_mode == "BGR":
        print("we are working in BGR mode, the img is read by opencv")
        h, w, c = img.shape[0], img.shape[1], img.shape[2]

        smooth = []
        for i in range(3):
            smooth.append(filter_image(img[:, :, i], grid))
        smooth = tuple(smooth)
        diff = diff_rgb
    else:
        h, w = img.shape[0], img.shape[1]
        smooth = filter_image(img, grid)
        diff = diff_grey

    graph = build_graph(smooth, w, h, diff, neighbor == 8)
    forest = segment_graph(graph, h * w, K, MIN_SIZE, threshold)

    image = generate_image(forest, w, h)
    image.save("seg_res/%s.png" % img_name)
    # image.save(sys.argv[6])
    print 'Number of components: %d' % forest.num_sets
Esempio n. 13
0
def graphs():
    #These coordinates could be stored in DB
    x1 = [0, 1, 2, 3, 4]
    y1 = [10, 30, 40, 5, 50]

    graph1_url = build_graph(x1, y1)

    return render_template('graphs.html', graph1=graph1_url)
Esempio n. 14
0
 def view_graph(self):
     '''
     Open window with graph of progress
     '''        
     if graphok == 0: # This means graph was imported correctly  
         selection = self.lbox.curselection()
         note_select = self.libox.curselection()
         if selection:
             self.lpointer = int(selection[0])
             graph.build_graph(self.goal_list.goals[self.lpointer])
         else:
             if note_select: # if cursor is on a note then a goal must have already been selected and lpointer already set.
                 graph.build_graph(self.goal_list.goals[self.lpointer]) 
             else:
                 messagebox.showwarning("Warning", "No goal selected")
     else: # if graph was not imported
         messagebox.showwarning("Warning", "Matplotlib is not installed please refer to the user installation document.")
Esempio n. 15
0
def graphs():
    #These coordinates could be stored in DB
    x1 = [0, 1, 2, 3, 4]
    y1 = [10, 30, 40, 5, 50]
    x2 = [0, 1, 2, 3, 4]
    y2 = [50, 30, 20, 10, 50]
    x3 = [0, 1, 2, 3, 4]
    y3 = [0, 30, 10, 5, 30]
 
    graph1_url = build_graph(x1,y1);
    graph2_url = build_graph(x2,y2);
    graph3_url = build_graph(x3,y3);
 
    return render_template('graphs.html',
    graph1=graph1_url,
    graph2=graph2_url,
    graph3=graph3_url)
Esempio n. 16
0
    def run_segmentation(self):
        self.graph = build_graph(img=self.image_smooth,
                                 width=self.width,
                                 height=self.height,
                                 diff=self.diff,
                                 neighborhood_8=self.neighbor == 8)

        self.forest = segment_graph(self.graph, self.height * self.width,
                                    self.K, self.min_size, threshold)
Esempio n. 17
0
def test():
    graph_text = '''source1,dest1,dest2
source2,dest1,abc,dest2,abc'''
    graph = build_graph(graph_text)
    print_graph(graph)
    
    print lookup ('source')
    print lookup ('source1')
    print lookup ('source2')
Esempio n. 18
0
def start_search(state):
    graph = g.build_graph()  # Create an instance of the graph class
    dt_travel = dt.Stack()
    if state.breadth_search:  # If Breadth First Search was Specified
        breadth_first_search(
            state, graph, state.starting_url)  # Initiate Breadth First Search
    if state.depth_search:  # If Depth First Search was Specified
        depth_first_search(state, graph, dt_travel,
                           state.starting_url)  # Initiate Depth First Search
Esempio n. 19
0
def run():
    dataset = TextDataSet(f'../datasets/{config.DATASET_FILENAME}')
    g = graph.build_graph(BATCH_SIZE, dataset.num_chars, config.NUM_LAYERS,
                          STEP_SIZE, config.NUM_LSTM_UNITS)
    with tf.Session() as session:
        session.run(tf.global_variables_initializer())
        load_model(session)
        states = graph.make_initial_sampling_states(config.NUM_LAYERS,
                                                    config.NUM_LSTM_UNITS)
        return create_sample(session, g, dataset, states)
Esempio n. 20
0
def eulerian(filename):
    """ Return wheter or not the graph built from the given file contains a eulerian cycle """

    # read from a file to grab graph properties
    graph, vertices, edges = read_file(filename)
    # builded graph object
    graph = build_graph(graph, vertices, edges)

    eulerian = graph.is_eulerian()

    print("This graph is Eulerian: {}".format(eulerian))
Esempio n. 21
0
def graphs():
    #These coordinates could be stored in DB
    x1 = [0, 1, 2, 3, 4]
    y1 = [10, 30, 40, 5, 50]
    x2 = [0, 1, 2, 3, 4]
    y2 = [50, 30, 20, 10, 50]
    x3 = [0, 1, 2, 3, 4]
    y3 = [0, 30, 10, 5, 30]

    plt.plot([0, 0.1, 0.2, 0.3])
    plt.ylabel('Stenosis Trend')
    axis([0,750,25,100])
    plt.show()
 
    graph0_url = build_graph([x1,y1],[x2,y2]);

    graph1_url = build_graph(x1,y1);
    graph2_url = build_graph(x2,y2);
    graph3_url = build_graph(x3,y3);
 
    return render_template('graphs.html', graph12=graph12_url, graph1=graph1_url, graph2=graph2_url, graph3=graph3_url)
Esempio n. 22
0
def graph1():
    checkSession()

    source_biases = weightranking.source_user_biases(session["srcdict"])
    x1 = []
    y1 = []
    for x in source_biases:
        x1.append(x[0])
        y1.append(x[1])
    graph1_url = graph.build_graph(x1, y1)

    if request.method == "GET":
        return render_template('graph.html', graph1=graph1_url)
Esempio n. 23
0
File: app.py Progetto: ivanmir/fuzzy
def graphs():

    #Clears all previously plotted graphs
    plt.close('all')

    #Regenerate random numbers
    xpts, ypts, labels = generateTestData()

    graph1_url = g.build_graph(g.build_x0(xpts, ypts, labels, colors))
    g1, fpcs = g.build_x1(xpts, ypts, labels, colors, np)
    graph2_url = g.build_graph(g1)
    graph3_url = g.build_graph(g.build_x2(xpts, ypts, labels, colors, np,
                                          fpcs))
    graph4_url = g.build_graph(g.build_x3(xpts, ypts, labels, colors, np))

    return render_template(
        'graphs.html',
        graph1=graph1_url,
        graph2=graph2_url,
        graph3=graph3_url,
        graph4=graph4_url,
    )
Esempio n. 24
0
def graphs():
    test_gender, test_class, df_test_processed = process_test_data()
    df_bar = pd.DataFrame({
        'Emotion':
        lgbm_model_class.classes_,
        'Percentage': [
            np.round(x * 100, 1)
            for x in lgbm_model_class.predict_proba(test_class)[0]
        ]
    })
    df_bar = df_bar.sort_values(by='Percentage', ascending=False)
    graph1_url = build_graph(df_bar['Emotion'].values,
                             df_bar['Percentage'].values)
    return render_template('graphs.html', graph1=graph1_url)
Esempio n. 25
0
def index():
    masters = Master.query.all()
    slaves_list = []

    if len(masters) is 0:
        return render_template('device/master_enroll_check.html')

    for master in masters:
        slaves = Slave.query.filter_by(master_id=master.id).all()

        if len(slaves) is 0:
            return render_template('device/master_enroll_check.html')

        for slave in slaves:
            graph_url_list = []
            text = ''
            route = 'slaves/'
            slave_RXAddr = slave.RXAddr
            csv = '.txt'

            route += slave_RXAddr
            route += csv

            f = open(route, "r")
            texts = f.readlines()
            f.close()

            text_list = []

            for text in texts:
                text = text.replace('\n', '')
                text_list.append(text.split('|'))

            # x = KW, y = 시간
            x = []
            y = []

            for text in text_list[1:]:
                x.append(int(text[4]))
                y.append(
                    int(text[1]) * 3600 + int(text[2]) * 60 + int(text[3]))

            graph_url = build_graph(y, x)
            graph_url_list.append(graph_url)

            slave.graph_url = graph_url

            slaves_list.append(slave)

    return render_template('index.html', slaves=slaves_list)
Esempio n. 26
0
def display_sensors():
    sensor_list = User.get_sensors(current_user.id)
    humidity_sensors = []
    temperature_sensors = []
    for sensor in sensor_list:
        sensor_dict = dict(zip(sensor.keys(), sensor))
        if sensor_dict["sensor_type"] == "Humidity":
            humidity_sensors.append(sensor_dict["sensor_name"])
        elif sensor_dict["sensor_type"] == "Temperature":
            temperature_sensors.append(sensor_dict["sensor_name"])

    plot_url = build_graph(humidity_sensors, temperature_sensors)

    return render_template('display_sensors.html', graph=plot_url)
Esempio n. 27
0
def vs_graph(term, radius, fpath, trim_leaves=False):
    """Build a neighborhood graph of the search term

    \b
    Args:
        term: Word to search for
        radius: Maximum distance away from the central node to keep in the graph
        fpath: Where to save the html output.
    """

    if not fpath:
        fpath = get_valid_filename(term) + ".html"
    g = build_graph(term, radius=radius, trim_leaves=trim_leaves)
    build_plot(term, g, fpath)
Esempio n. 28
0
def main(_):
    ps_hosts = FLAGS.ps_hosts.split(",")
    worker_hosts = FLAGS.worker_hosts.split(",")

    # 使用参数服务器和工作节点创建集群
    cluster = tf.train.ClusterSpec({"ps": ps_hosts, "worker": worker_hosts})

    # 创建并启动服务
    server = tf.train.Server(cluster,
                             job_name=FLAGS.job_name,
                             task_index=FLAGS.task_index)

    if FLAGS.job_name == "ps":
        server.join()

    elif FLAGS.job_name == "worker":

        with tf.device(
                tf.train.replica_device_setter(
                    worker_device="/job:worker/task:%d" % FLAGS.task_index,
                    cluster=cluster)):
            x, y_, train_step, accuracy = build_graph()

        hooks = [
            tf.train.StopAtStepHook(last_step=TRAINING_STEPS),
            tf.train.CheckpointSaverHook(checkpoint_dir=MODEL_PATH,
                                         save_secs=600,
                                         saver=tf.train.Saver(sharded=True))
        ]
        is_chief = (FLAGS.task_index == 0)
        i = 1
        validate_feed = {
            x: mnist.validation.images,
            y_: mnist.validation.labels
        }

        with tf.train.MonitoredTrainingSession(master=server.target,
                                               is_chief=is_chief,
                                               checkpoint_dir=MODEL_PATH,
                                               hooks=hooks) as mon_sess:
            while not mon_sess.should_stop():
                xs, ys = mnist.train.next_batch(BATCH_SIZE)
                mon_sess.run(train_step, feed_dict={x: xs, y_: ys})
                i += 1
                if i % 100 == 0:
                    validate_acc = mon_sess.run(accuracy,
                                                feed_dict=validate_feed)
                    print("After %d training step(s), validation accuracy "
                          "using average model is %g" % (i, validate_acc))
Esempio n. 29
0
async def play_learned_ai(callback):
    import config
    import graph as g
    import main
    import play
    import tensorflow as tf
    with tf.Session() as session:
        graph = g.build_graph()
        saver = tf.train.Saver()
        saver.restore(session, config.CHECKPOINT_FILENAME)
        await play.async_evaluate_performance(
            session,
            graph,
            training_mode = False,
            callback = callback
        )
Esempio n. 30
0
    def compute_features(self, tsv_file):
        graph = helper.build_graph(tsv_file)
        self.graph = graph
        self.undirected_graph = graph.to_undirected()
        self.embeddedness_matrix = helper.get_embeddedbess_matrix(graph)
        features_df = self.build_features_df(graph)
        self.matrix = nx.to_numpy_matrix(graph, weight="weight")

        # Parallel calculation of the features, each thread calculates a different chunk
        features_df_split = np.array_split(features_df, NUMBER_OF_CORES)
        pool = mp.Pool(NUMBER_OF_CORES)
        parts = pool.map(self.process_frame, features_df_split)
        df = pd.concat(parts)
        pool.close()
        pool.join()
        return df
Esempio n. 31
0
def test_min_cost_flow_pixel():
    input_signal_U = np.asfortranarray(np.array([[1.0, 2.0, 3.0, 4.0, 5.0],
                                                 [2.0, 3.0, 2.0, 1.0, 4.0],
                                                 [5.0, 2.0, 2.0, 4.0, 3.0],
                                                 [8.0, 8.0, 3.0, 2.0, 5.0],
                                                 [2.0, 3.0, 2.0, 1.0, 4.0],
                                                 [5.0, 2.0, 2.0, 4.0, 3.0]]),
                                       dtype=project_float)
    graph = build_graph([3, 2], [2, 2])
    prox = lsd.min_cost_flow(input_signal_U, graph, 0.1)
    eq(
        prox,
        np.array([[1.0, 2.0, 2.9, 3.95, 4.9], [2.0, 3.0, 2.0, 1.0, 4.0],
                  [5.0, 2.0, 2.0, 3.95, 3.0], [7.8, 7.8, 2.9, 1.9, 4.9],
                  [2.0, 3.0, 2.0, 1.0, 4.0], [5.0, 2.0, 2.0, 4.0, 3.0]],
                 dtype=project_float))
Esempio n. 32
0
def graphs():
    """
    Plot a graph of historic data and model predictions.
    """
    # Get historic data used to train a model and model predictions
    x = model.data
    y = model.predict(output=1, denormalized=True, return_dict=True)
    # Pre-process predictions
    y = pd.DataFrame(y)
    # Rename the column 'prediction' into 'close' in order to conform with
    # column naming of the original data
    y.rename(columns={'prediction': 'close'}, inplace=True)
    # Select only two columns that both historic observations and predictions share in common
    # Sort observations from the earliest date to the latest in order to conform with predictions format
    x = x[['date', 'close']].sort_values(by=['date'], ascending=True)
    graph_url = build_graph(x, y)
    return render_template('graphs.html', graph=graph_url)
Esempio n. 33
0
        sigma = float(sys.argv[1])
        K = float(sys.argv[3])
        min_size = int(sys.argv[4])

        size = image_file.size
        print 'Image info: ', image_file.format, size, image_file.mode

        grid = gaussian_grid(sigma)
        
        if image_file.mode == 'RGB':
            # image_file.load() # Useless
            r, g, b = image_file.split()

            r = filter_image(r, grid)
            g = filter_image(g, grid)
            b = filter_image(b, grid)

            smooth = (r, g, b)
            diff = diff_rgb # function pointer
        else:
            smooth = filter_image(image_file, grid)
            diff = diff_grey # function pointer

        graph = build_graph(smooth, size[0], size[1], diff, neighbor == 8)
        forest = segment_graph(graph, size[0]*size[1], K, min_size, threshold)

        image = generate_image(forest, size[0], size[1])
        image.save(sys.argv[6])

        print 'Number of components: %d' % forest.num_sets