コード例 #1
0
def feature_grapher(featuredata, path_out, feature_index, feature_num):
    Visualizer.feature_grapher(featuredata=featuredata,
                               feature_index=feature_index,
                               showlegend=True,
                               hide_traces=True,
                               path_out=path_out,
                               feature_num=feature_num)
コード例 #2
0
def _merge(screen, lst, low, mid, high):
    """Helper function for merge sort."""
    merged = []
    i = low
    j = mid + 1
    while i <= mid and j <= high:
        if lst[i] < lst[j]:
            merged.append(lst[i])
            Visualizer.update(screen, lst.copy(), {i, j})
            i += 1
        else:
            merged.append(lst[j])
            Visualizer.update(screen, lst.copy(), {i, j})
            j += 1
    while i <= mid:
        merged.append(lst[i])
        Visualizer.update(screen, lst.copy(), {i})
        i += 1
    while j <= high:
        merged.append(lst[j])
        Visualizer.update(screen, lst.copy(), {j})
        j += 1
    for k in range(len(merged)):
        lst[k + low] = merged[k]
        Visualizer.update(screen, lst.copy(), {k + low})
コード例 #3
0
def _quick_sort(screen, lst, low, high):
    """Quick sort implementation in Python."""
    if low >= high:
        Visualizer.update(screen, lst.copy(), {})
    else:
        pivot = _partition(screen, lst, low, high)
        _quick_sort(screen, lst, low, pivot)
        _quick_sort(screen, lst, pivot + 1, high)
コード例 #4
0
 def bubble(self, array):
     # Flag checks if any swaps happened, if not array is already sorted
     for i in range(len(array)):
         for j in range(0, len(array) - i - 1):
             if array[j] > array[j + 1]:
                 Visualizer.update_screen(array, "Bubble Sort", self.speed,
                                          j, j + 1)
                 array[j], array[j + 1] = array[j + 1], array[j]
コード例 #5
0
def bubble_sort(screen, lst):
    """Bubble sort implementation in Python."""
    for i in range(len(lst)):
        for j in range(len(lst) - i - 1):
            if lst[j] > lst[j + 1]:
                lst[j], lst[j + 1] = lst[j + 1], lst[j]
            Visualizer.update(screen, lst.copy(), {j, j + 1, len(lst) - i})
    Visualizer.update(screen, lst.copy(), {})
コード例 #6
0
def _merge_sort(screen, lst, low, high):
    """Merge sort implementation in Python."""
    if low >= high:
        Visualizer.update(screen, lst.copy(), {})
    else:
        mid = (low + high) // 2
        _merge_sort(screen, lst, low, mid)
        _merge_sort(screen, lst, mid + 1, high)
        _merge(screen, lst, low, mid, high)
コード例 #7
0
def heap_sort(screen, lst):
    """Heap sort implementation in Python."""
    for i in range(len(lst) // 2 - 1, -1, -1):
        _heapify(screen, lst, len(lst), i)
    for i in range(len(lst) - 1, 0, -1):
        lst[i], lst[0] = lst[0], lst[i]
        Visualizer.update(screen, lst.copy(), {0, i})
        _heapify(screen, lst, i, 0)
    Visualizer.update(screen, lst.copy(), {})
コード例 #8
0
def annotation_feature_grapher(annotationdata, featuredata, path_out,
                               non_overlap, title, feature_index, feature_num):
    Visualizer.annotation_feature_grapher(annotationdata=annotationdata,
                                          featuredata=featuredata,
                                          path_out=path_out,
                                          non_overlap=non_overlap,
                                          title=title,
                                          feature_index=feature_index,
                                          feature_num=feature_num)
コード例 #9
0
 def selection(self, array):
     for i in range(len(array)):
         # minimum value at position i
         minimum = i
         for j in range(i + 1, len(array)):
             if array[j] < array[minimum]:
                 minimum = j
         Visualizer.update_screen(array, "Selection sort", self.speed, i,
                                  minimum)
         array[i], array[minimum] = array[minimum], array[i]
コード例 #10
0
def gen_acceleration_graph(count):
    acc_end = len(db.rawdata.index)
    acc_start = int(acc_end - DISPLAY_RANGE*SAMPLING_RATE)

    if acc_start < 0:
        acc_start = 0

    acc_data = db.rawdata[acc_start:acc_end]

    acc_fig = Visualizer.acc_grapher(acc_data,return_fig=True)

    feature_end = len(db.featuredata.index)
    feature_start = int(feature_end - DISPLAY_RANGE/FEATURE_TIME) - 1

    if feature_start < 0:
        feature_start = 0
    if feature_end < 0:
        feature_end = 0

    feature_data = db.featuredata.iloc[feature_start:feature_end,:]
    feature_fig = Visualizer.feature_grapher(feature_data, return_fig=True, feature_index=values)
    
    for label in db.annotationdata.iloc[:,3].unique():
        if label not in annotation_colors:
            annotation_colors[label] = Visualizer.generate_color(1)[0]
    
    annotation_end = len(db.annotationdata.index)
    annotation_start = int(annotation_end - DISPLAY_RANGE/FEATURE_TIME) - 1

    if annotation_start < 0:
        annotation_start = 0
    if annotation_end < 0:
        annotation_end = 0

    annotation_data = db.annotationdata.iloc[annotation_start:annotation_end,:]
    annotation_fig = Visualizer.annotation_feature_grapher(annotation_data.iloc[:,[0,1,3]], colors=annotation_colors, return_fig=True)
    
    
    acc_fig['data'] += feature_fig['data']
    acc_fig['data'] += annotation_fig['data']

    acc_fig['layout'].update(feature_fig['layout'])

    acc_fig['layout'].update(annotation_fig['layout'])
    acc_fig['layout']['yaxis']['domain'] = [0,0.3]
    acc_fig['layout']['yaxis2']['domain'] = [0.31,0.6]
    acc_fig['layout']['yaxis3']['domain'] = [0.61, 1]

    range_end = pd.to_datetime(acc_data.iloc[acc_data.shape[0]-1,0])
    range_start = range_end - datetime.timedelta(seconds=DISPLAY_RANGE)
    acc_fig['layout']['xaxis'].update(dict(fixedrange=True, range=[range_start,range_end]))
    acc_fig['layout']['width'] = 1200

    return acc_fig
コード例 #11
0
 def insertion(self, array):
     for i in range(1, len(array)):
         curr = array[i]
         # Move elements of already sorted portion one element up if greater then curr value
         sPart = i - 1
         while sPart >= 0 and curr < array[sPart]:
             array[sPart + 1] = array[sPart]
             sPart = sPart - 1
         Visualizer.update_screen(array, "Insertion sort", self.speed,
                                  sPart, i)
         array[sPart + 1] = curr
コード例 #12
0
	def refresh(self):
		new_entry = [
			float(self.pelvic_incidence.get()),
			float(self.pelvic_tilt.get()),
			float(self.lumbar_lordosis_angle.get()),
			float(self.sacral_slope.get()),
			float(self.pelvic_radius.get()),
			float(self.degree_spondylolisthesis.get())
		]

		print(self.var.get())

		Visualizer.makeGraph(self.k_slider.get(), self.mesh_slider.get(), new_entry, self.var.get())
コード例 #13
0
 def partition(self, array, low, high):
     # This is the index of the smaller element
     i = (low - 1)
     # Pivot is last element
     pivot = array[high]
     for j in range(low, high):
         # if array element is smaller then pivot
         # then shift low index up
         if array[j] < pivot:
             i += 1
             Visualizer.update_screen(array, "Quick Sort", self.speed, i, j)
             array[i], array[j] = array[j], array[i]
     array[i + 1], array[high] = array[high], array[i + 1]
     return i + 1
コード例 #14
0
def normalizeChecker(data):

    loss = data.mean() - data.median()

    loss2 = loss.mean()

    print("Analysis Result / 분석 결과: ")
    print("While the data's mean is %f, the difference between median and mean is in average %f."%(data.mean().mean(), loss2))
    print("데이터의 평균값은 %f인데 반해, 중앙값과 평균값의 차이는 평균 %f입니다. 이 둘의 값의 차가 클수록 많은 열의 데이터가 대칭적이지 않거나 이상치가 많음을 의미합니다. \n"
          "이상치가 많을 경우, 평균과 표준편차, 혹은 최댓값과 최솟값으로 정규화하는 것은 기계학습의 정확도를 낮출 수 있습니다. 참고하시기 바랍니다." % (
    data.mean().mean(), loss2))

    print("Actual Analysis Result / 실제 분석 결과: ")

    vi.backDoorOneVarPlot(loss)
コード例 #15
0
def GenGrid(size):
    global m
    m = size
    global grid
    grid = np.zeros((size, size))

    rocks = np.random.randint(round(size/2))
    for n in range(rocks):
        placeRock()
        placePad()
    for n in range(round(rocks/2)):
        placeImmovable()
    placeTeleporter()
    placeR2D2()
    v.renderGrid(grid, size, True)
    return grid
コード例 #16
0
ファイル: NNT.py プロジェクト: hastern/NeuronalNetworkToolkit
	def visualize(self, filename, options = {'showHead'}): 
		"""
		Visualizes the net using a specified visualisation tool
		
		@type	filename:	string
		@param	filename:	filename where the graph gets stored
		
		@type	options:	set
		@param	options: 	Set of options for visualisation
			possible options:
				- C{'showHead'}: set this flag,
					if you want to have directed connections
				- C{'showLabel'}: activate to display the connection weights
				- C{'useColor'}: colored HTMl
		"""
		Visualizer.useGraphViz(self, filename, options)
コード例 #17
0
def starter(feature_model, dimension_reduction, k, visualizer):
    path, pos = Config().read_path(), None
    descriptor_type = DescriptorType(feature_model).descriptor_type
    if DescriptorType(feature_model).check_sift():
        x, ids, pos = functions.process_files(path, feature_model,
                                              dimension_reduction)
    else:
        x, ids = functions.process_files(path, feature_model,
                                         dimension_reduction)

    symantics_type = LatentSymanticsType(dimension_reduction).symantics_type
    if visualizer == 1:
        _, latent_symantics = LatentSymantics(
            x, k, dimension_reduction).latent_symantics
        k_th_eigenvector_all = []
        for i in range(k):
            col = latent_symantics[:, i]
            arr = []
            for k, val in enumerate(col):
                arr.append((str(ids[k] + ".jpg"), val))
            arr.sort(key=lambda x: x[1], reverse=True)
            k_th_eigenvector_all.append(arr)
            print(
                "Printing term-weight pair for latent Semantic {}:".format(i +
                                                                           1))
            print(arr)
        k_th_eigenvector_all = pd.DataFrame(k_th_eigenvector_all)
        Visualizer.visualize_data_symantics(k_th_eigenvector_all,
                                            symantics_type, descriptor_type)
    elif visualizer == 2:
        latent_symantics, _ = LatentSymantics(
            x, k, dimension_reduction).latent_symantics
        k_th_eigenvector_all = []
        for j in range(k):
            arr = []
            for i in range(len(ids)):
                arr.append((
                    str(ids[i] + ".jpg"),
                    np.dot(x[i], latent_symantics.components_[j]),
                ))
                # k_th_eigenvector_all[ids[i]] = np.dot(x[i], latent_symantics[j])
            arr.sort(key=lambda x: x[1], reverse=True)
            k_th_eigenvector_all.append(arr[:1])
            print(arr[0])
        k_th_eigenvector_all = pd.DataFrame(k_th_eigenvector_all)
        Visualizer.visualize_feature_symantics(k_th_eigenvector_all,
                                               symantics_type, descriptor_type)
コード例 #18
0
    def plot_feature_and_raw(
            features,
            acc_data,
            path_out='/Users/zhangzhanming/Desktop/mHealth/Test/'):
        acc_fig = Visualizer.acc_grapher(acc_data,
                                         return_fig=True,
                                         showlegend=True)
        feature_fig = Visualizer.feature_grapher(features,
                                                 return_fig=True,
                                                 showlegend=True,
                                                 hide_traces=True)
        acc_fig['data'] += feature_fig['data']
        acc_fig['layout'].update(feature_fig['layout'])
        acc_fig['layout']['yaxis2']['domain'] = [0, 0.5]
        acc_fig['layout']['yaxis2']['fixedrange'] = False
        acc_fig['layout']['height'] = 600
        acc_fig['layout']['yaxis3'] = dict(domain=[0.51, 1])

        py.plot(acc_fig, filename=path_out + 'feature_acc_graph.html')
コード例 #19
0
    def show(self, start, end):
        """
        Runs the visualizer on the net

        [0,1,2,3,4,5,6,7]

        net.show(3,5) shows layers 3,4,5
        
        """
        layer_sizes = []
        nodes = []
        for layer in self.activation_layers[start:end + 1]:
            layer_sizes.append(len(layer))
            for node in layer:
                nodes.append(round(node, 3))
        weights = []
        for layer in self.weight_layers[start:end]:
            layer_t = layer.transpose()
            for output_node in layer_t:
                for connection in output_node:
                    weights.append(connection)
        Visualizer.draw_neural_net(0.1, 1, 0, 1, layer_sizes, nodes, weights)
コード例 #20
0
 def printChart(self, df):
     Visualizer.print_full(df[[
         'date',
         # 'timestamp'
         'close',
         # 'high',
         # 'low',
         'open',
         # 'supportQuote',
         # 'resistanceQuote',
         # 'quoteVolume',
         # 'volume',
         'isUp',
         'quoteGrowth1stPeriod',
         'weightedAverage',
         'buyValue',
         'sellValue',
         'perGain',
         'btc',
         'actualCurrency',
         'Buy',
         'shouldBuy'
     ]])
コード例 #21
0
 def __init__(self, bzrc):
     
     self.bzrc = bzrc
     self.fields = fields.Calculations()
     self.throttle = .15
     self.commands = []
     self.constants = self.bzrc.get_constants()
     self.truePositive = float(self.constants['truepositive'])
     self.falseNegative = 1.0 - float(self.truePositive)
     self.trueNegative = float(self.constants['truenegative'])
     self.falsePositive = 1.0 - self.trueNegative
     self.grid = OccGrid(800, 800, .07125)
     #the .07125 comes from the 4 Ls world where 7.125% of the world was occupied
     self.time = time.time()
     self.locationList = []
     self.oldlocation = []
     vs.init_window(800,800)
     self.grid.draw()
     
     self.mytanks = self.bzrc.get_mytanks()
     
     for i in range(10):
         self.locationList.append(self.getRandomCoordinate(i))
         self.oldlocation.append(Point(self.mytanks[i].x, self.mytanks[i].y))
コード例 #22
0
def _heapify(screen, lst, size, i):
    """Helper function for heap sort."""
    largest = i
    left = 2 * i + 1
    right = 2 * i + 2
    Visualizer.update(screen, lst.copy(), {size, largest})
    if left < size:
        if lst[largest] < lst[left]:
            largest = left
        Visualizer.update(screen, lst.copy(), {size, largest, left})
    if right < size:
        if lst[largest] < lst[right]:
            largest = right
        Visualizer.update(screen, lst.copy(), {size, largest, right})
    if largest != i:
        lst[i], lst[largest] = lst[largest], lst[i]
        Visualizer.update(screen, lst.copy(), {size, largest, i})
        _heapify(screen, lst, size, largest)
コード例 #23
0
def selection_sort(screen, lst):
    """Selection sort implementation in Python."""
    for i in range(len(lst)):
        smallest = i
        for j in range(i + 1, len(lst)):
            if lst[j] < lst[smallest]:
                smallest = j
            Visualizer.update(screen, lst.copy(), {i - 1, j, smallest})
        lst[smallest], lst[i] = lst[i], lst[smallest]
        Visualizer.update(screen, lst.copy(), {i - 1, i, smallest})
    Visualizer.update(screen, lst.copy(), {})
コード例 #24
0
def insertion_sort(screen, lst):
    """Insertion sort implementation in Python."""
    for i in range(1, len(lst)):
        key = lst[i]
        j = i - 1
        while j >= 0 and lst[j] > key:
            lst[j + 1], lst[j] = lst[j], lst[j + 1]
            Visualizer.update(screen, lst.copy(), {i, j, j + 1})
            j -= 1
        lst[j + 1], key = key, lst[j + 1]
        Visualizer.update(screen, lst.copy(), {i, j + 1})
    Visualizer.update(screen, lst.copy(), {})
コード例 #25
0
def visualize_perceptron(base_path, suffix, mean_squared_errors_train,
                         mean_squared_errors_test, avg_acc_errors_train,
                         avg_acc_errors_test, learning_set, learning_answers,
                         epoch_measure_points, testing_set, testing_answers,
                         result, perceptron):

    #v.visualize_classification(perceptron, testing_set, result, True,
    #f"{base_path}_{suffix}_classification.png")
    v.confusion_matrix(testing_answers, result, True,
                       f"{base_path}_{suffix}_confusion_matrix.png")
    v.visualize_accuracy(avg_acc_errors_train, avg_acc_errors_test,
                         epoch_measure_points, True,
                         f"{base_path}_{suffix}_accuracy.png")

    v.visualize_mean_sqrt_errors(
        mean_squared_errors_train, mean_squared_errors_test,
        epoch_measure_points, True,
        f"{base_path}_{suffix}_mean_square_errors.png")
    v.show_edges_weight(perceptron, True, f"{base_path}_{suffix}_weights.png")
コード例 #26
0
def main():
    # Audio processing class
    audio_proc = audio.Audio()

    # Visualizer
    vis = Visualizer.Visualizer()

    # Create and start audio thread
    audio_thread = threading.Thread(target=audio_proc.record_monitor)

    audio_thread.start()

    while True:
        # listen for input keys
        input_handler(vis, audio_proc)

        # render
        vis.render(audio_proc.get_stft)

        time.sleep(0.025)
コード例 #27
0
 def merge(self, array, left_index, right_index, middle):
     # Second param is non-inclusive thus we add 1
     left_copy = array[left_index:middle + 1]
     right_copy = array[middle + 1:right_index + 1]
     # Values to keep track of where we are in each 'sub-array'
     left_copy_index = 0
     right_copy_index = 0
     sorted_index = left_index  #this is where previous problem was, set to left_index of total array passed in, not left_copy_index as that is different value
     # Fill up new array with portions of each sub array
     # until we run out of elements in one array
     while left_copy_index < len(left_copy) and right_copy_index < len(
             right_copy):
         if left_copy[left_copy_index] <= right_copy[right_copy_index]:
             Visualizer.update_screen(array, "Merge sort", self.speed,
                                      sorted_index, left_copy_index)
             array[sorted_index] = left_copy[left_copy_index]
             left_copy_index = left_copy_index + 1
         else:
             Visualizer.update_screen(array, "Merge sort", self.speed,
                                      sorted_index, right_copy_index)
             array[sorted_index] = right_copy[right_copy_index]
             right_copy_index = right_copy_index + 1
         sorted_index = sorted_index + 1
     # Either ran out of elements in left or right array
     # Need to while loops to fill in whichever array has remaining elements
     while left_copy_index < len(left_copy):
         Visualizer.update_screen(array, "Merge sort", self.speed,
                                  sorted_index, left_copy_index)
         array[sorted_index] = left_copy[left_copy_index]
         left_copy_index = left_copy_index + 1
         sorted_index = sorted_index + 1
     while right_copy_index < len(right_copy):
         Visualizer.update_screen(array, "Merge sort", self.speed,
                                  sorted_index, right_copy_index)
         array[sorted_index] = right_copy[right_copy_index]
         right_copy_index = right_copy_index + 1
         sorted_index = sorted_index + 1
コード例 #28
0
def main():
    sudokuSolver = SudokuSolver.SudokuSolver()
    visualizer = Visualizer.Visualizer()
    #creates the board starting message
    currentBoard = [
        "..23....4", ".8..69...", "4592.716.", "145.92.38", "67..1..4.",
        "2.....651", ".17..63..", ".......75", "8.45...1."
    ]
    board = Board.Board(currentBoard)

    visualizer.drawBoard(board)

    solved = False
    while solved == False:
        solved = sudokuSolver.next(board)
        if solved == False:
            visualizer.drawBoard(board)
            print("--------------------------------------------------")
            #time.sleep(0.5)
    print("solved!")
    time.sleep(1)
    exit()
コード例 #29
0
def _partition(screen, lst, low, high):
    """Helper function for quick sort."""
    pivot = lst[low]
    i = low
    j = high
    while True:
        while lst[i] < pivot:
            Visualizer.update(screen, lst.copy(), {i, j, low})
            i += 1
        while lst[j] > pivot:
            Visualizer.update(screen, lst.copy(), {i, j, low})
            j -= 1
        if i >= j:
            return j
        lst[i], lst[j] = lst[j], lst[i]
        Visualizer.update(screen, lst.copy(), {i, j, low})
        i += 1
        j -= 1
コード例 #30
0
    def draw(self):
		vs.update_grid(self.grid)
		vs.draw_grid()
コード例 #31
0
    def open_fretboard(self, widget):
        if not self.project: return

        w = Visualizer.FretboardWindow(self.project.control)
        w.show_all()