Esempio n. 1
0
def vis_detections(im, class_name, dets, thresh=0.5):
    """Draw detected bounding boxes."""
    inds = np.where(dets[:, -1] >= thresh)[0]
    if len(inds) == 0:
        return
    plt.use('Agg')
    im = im[:, :, (2, 1, 0)]
    fig, ax = plt.subplots(figsize=(12, 12))
    ax.imshow(im, aspect='equal')
    for i in inds:
        bbox = dets[i, :4]
        score = dets[i, -1]

        ax.add_patch(
            plt.Rectangle((bbox[0], bbox[1]),
                          bbox[2] - bbox[0],
                          bbox[3] - bbox[1],
                          fill=False,
                          edgecolor='red',
                          linewidth=3.5))
        ax.text(bbox[0],
                bbox[1] - 2,
                '{:s} {:.3f}'.format(class_name, score),
                bbox=dict(facecolor='blue', alpha=0.5),
                fontsize=14,
                color='white')

    ax.set_title(('{} detections with '
                  'p({} | box) >= {:.1f}').format(class_name, class_name,
                                                  thresh),
                 fontsize=14)
    plt.axis('off')
    plt.tight_layout()
    plt.draw()
Esempio n. 2
0
def scatter_graph(purchases):
    # Setting up the scatter graph using matplotlib
    plt.use("ggplot")
    graph_x = []
    graph_y = []
    graph_transactions = 0

    for j in range(len(purchases)):
        # Appending the variables to x and y (matplotlib)
        graph_x.append(j)
        graph_y.append(purchases[j])

    # Plotting the matplotlib scatter plot
    plt.figure(1)
    plt.title("Scatter (All transactions)")
    plt.scatter(graph_x, graph_y, s=5)
Esempio n. 3
0
def find_phase_regression(d, phs_truth=""):

    print(np.mean(d))
    plt.use('Agg')
    plt.plot(d)
    plt.ylabel('some numbers')
    plt.show()
    # Find frequency
    D = np.abs(np.fft.fftshift(np.fft.fft(d * np.hamming(len(d)))))

    f = np.arange(-0.5, 0.5 - 1.0 / len(d), 1.0 / len(d))
    pos = D.argmax()

    # Create x (synthetic sin wave)
    x = np.sin(2 * np.pi * np.arange(-1, len(D)) * np.abs(f[pos]))

    # Compute w
    w = LS_local(np.asarray(d), x, 2)

    # Initialize
    ph0 = 0
    ph1 = -2 * np.pi * np.abs(f[pos])

    # Compute ph
    ph = np.arctan((w[0] * np.sin(ph0) + w[1] * np.sin(ph1)) /
                   (w[0] * np.cos(ph0) + w[1] * np.cos(ph1)))
    if np.sign((w[0] * np.cos(ph0) + w[1] * np.cos(ph1))) < 0:
        ph = ph - np.pi

    ph = modmPitoPi(ph)

    if phs_truth:  # determine Empty String
        phs_truth = modmPitoPi(phs_truth)
        # Check
        print(
            str(phs_truth) + " = " + str(ph) + " ?"
        )  # These should be (approximately) equal or off by an integer multiple of 2*pi
    else:
        #print(str(ph))
        pass
    # Return
    return ph, ErrStd
Esempio n. 4
0
    def __init__(self, dataY, dataFrame, plotType):
        import matplotlib as plt

        plt.use("WXAgg")
        plt.interactive(False)
        self.plotType = plotType
        self.dataFrame = dataFrame
        self.figure = pl.figure()
        self.axis = self.figure.add_subplot(111)
        # create a long tooltip with newline to get around wx bug (in v2.6.3.3)
        # where newlines aren't recognized on subsequent self.tooltip.SetTip() calls
        self.tooltip = wx.ToolTip(tip="tip with a long %s line and a newline\n" % (" " * 100))
        gcfm().canvas.SetToolTip(self.tooltip)
        self.tooltip.Enable(False)
        self.tooltip.SetDelay(0)
        self.figure.canvas.mpl_connect("motion_notify_event", self._onMotion)
        self.dataX = range(len(dataY))
        self.dataY = dataY
        self.xTicks = dataFrame.index
        pl.xticks(self.dataX, self.xTicks)
        self.axis.plot(self.dataX, self.dataY, linestyle="-", marker="o", markersize=15, label="myplot")
Esempio n. 5
0
import networkx as nx
import matplotlib.pyplot as plt
plt.use("Agg")
G = nx.Graph()
G.add_node(1)

nx.draw(G)
G = nx.path_graph(4)
cities = {0: "Toronto", 1: "London", 2: "Berlin", 3: "New York"}

H = nx.relabel_nodes(G, cities)

print("Nodes of graph: ")
print(H.nodes())
print("Edges of graph: ")
print(H.edges())
nx.draw(H)
plt.savefig("path_graph_cities.png")
plt.show()
Esempio n. 6
0
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 16 14:12:33 2019

@author: gynjkm
"""

#imports required packages

import matplotlib.pyplot as plt

plt.use('TkAgg')

import matplotlib.animation
import agentframework_zombies
import csv
import random

#defines our arguments and creating the lists of sheep and zombiesheep

num_of_agents = 100

num_of_iterations = 150

neighbourhood = 15

num_of_zombsheep = 2

agents = []

zombsheep = []
Esempio n. 7
0
parser.add_argument('--confirmexit', '-x', default=False, help='confirm exit')
parser.add_argument('--prompt', '-p', default='>>> ', help='input prompt')
parser.add_argument(
    '--resultprefix',
    '-r',
    default=None,
    help='execution result prefix, include {} for execution count number')
parser.add_argument('--showassign',
                    '-a',
                    default=False,
                    help='display the result of assignments')
args = parser.parse_args()

if args.backend is not None:
    print(f"Using matplotlub backend {args.backend}")
    plt.use(args.backend)

# load some robot models
puma = models.DH.Puma560()
panda = models.DH.Panda()

# print the banner
# https://patorjk.com/software/taag/#p=display&f=Cybermedium&t=Robotics%20Toolbox%0A
print(
    r"""____ ____ ___  ____ ___ _ ____ ____    ___ ____ ____ _    ___  ____ _  _
|__/ |  | |__] |  |  |  | |    [__      |  |  | |  | |    |__] |  |  \/
|  \ |__| |__] |__|  |  | |___ ___]     |  |__| |__| |___ |__] |__| _/\_

for Python

from roboticstoolbox import *
Esempio n. 8
0
Next Steps:
- Plot Data to Graph, Add Styling
- try, catch
- point to audioFiles directory
- make program run faster

audioFiles = ["PTSD_female.wav", "Anxiety_female.wav", "Depression_male.wav", "Depression_male2_JB.wav", "Depression_male3_JB.wav", "Control_male.wav", "Control_Male2.wav", "Depression_female.wav", "Depression_female2.wav", "Depression_female3.wav", "PTSD_male.wav", "Anxiety_male.wav", "Anxiety_male2.wav"]

'''

from pyAudioAnalysis import audioBasicIO
from pyAudioAnalysis import audioFeatureExtraction
import matplotlib.pyplot as plt
import os, sys
import matplotlib.pyplot as style
style.use('ggplot')

#Define Global Variables
path = "/Users/kamilahmitchell/Desktop/C++, Python & Vsts/Neurolex/traumaDemo/Audio Files"
dir = os.listdir(path)
i = 0

def readFiles(dir):
    audioFiles = []
    for file in dir:
        if file.endswith(".wav"):
            audioFiles.append(file)
    print audioFiles #Trace
    return audioFiles

def findFormants(audioFiles, i, dir):
Esempio n. 9
0
    plt.ylabel("E")

    if flag_start == False:
        command = input("Press Enter, then start.")
        flag_start = True

    plt.pause(0.001)
    plt.clf()
    flag_plt = True

#Visualization
"""
E_nx_for_plt=[
E_nx[0,0,0] E_nx[1,0,0] ... E_nx[i,0,0]
E
]
"""
Ex_for_plt = np.zeros([n_meshx, n_meshy, n_meshz])
for i in range(0, n_meshx - 1):
    for j in range(0, n_meshy - 1):
        Ex_for_plt[i, j] = E_nx[i, j, 0]

x_plt = np.arange(-area_x + dx, area_x - dx, dx)
y_plt = np.arange(-area_y + dx, area_y - dx, dy)

X, Y = np.meshgrid(x_plt, y_plt)
plt.use('Agg')
plt.pcolor(X, Y, Ex_for_plt)
plt.colorbar()
plt.show()
Esempio n. 10
0
#                           collocations=False,
#                           font_path='simhei.ttf',
#                           icon_name='fas fa-heart',
#                           size=653,
#                           # palette='matplotlib.Inferno_9',
#                           output_name='./005827.png')
# Image(filename='./005827.png')

# 用更为量化的方法,计算出每个评论的情感评分
senta = hub.Module(name="senta_bilstm")
texts = df['标题'].tolist()
input_data = {'text': texts}
res = senta.sentiment_classify(data=input_data)
df['投资者情绪'] = [x['positive_probs'] for x in res]
# 重采样至15分钟
df['时间'] = pd.to_datetime(df['时间'])
df.index = df['时间']
data = df.resample('15min').mean().reset_index()

# 通过AkShare这一开源API接口获取上证指数分时数据,AkShare是基于Python的财经数据接口库,
# 可以实现对股票、期货、期权、基金、外汇、债券、指数、
# 数字货币等金融产品的基本面数据、历史行情数据的快速采集和清洗。
sz_index = ak.stock_zh_a_minute(symbol='sh000001', period='15', adjust="qfq")
sz_index['日期'] = pd.to_datetime(sz_index['day'])
sz_index['收盘价'] = sz_index['close'].astype('float')
data = data.merge(sz_index, left_on='时间', right_on='日期', how='inner')
plt.use('Qt5Agg')
data.index = data['时间']
data[['投资者情绪', '收盘价']].plot(secondary_y=['close'])
plt.show()
Esempio n. 11
0
im1 = imageio.imread('chelsea.png')
im2 = imageio.imread('chelsea_morph1.png')
#im2 = imageio.imread('https://dl.dropboxusercontent.com/u/1463853/images/chelsea_morph1.png')

# Select one channel (grayscale), and make float
im1 = im1[:,:,1].astype('float32')
im2 = im2[:,:,1].astype('float32')

# Get default params and adjust
params = pyelastix.get_default_params()
params.NumberOfResolutions = 3
print(params)

# Register!
im3, field = pyelastix.register(im1, im2, params)

# Visualize the result
fig = plt.figure(1);
plt.clf()
plt.subplot(231); plt.imshow(im1)
plt.subplot(232); plt.imshow(im2)
plt.subplot(234); plt.imshow(im3)
plt.subplot(235); plt.imshow(field[0])
plt.subplot(236); plt.imshow(field[1])

# Enter mainloop
if hasattr(plt, 'use'):
    plt.use().Run()  # visvis
else:
    plt.show()  # mpl
Esempio n. 12
0
#!/usr/bin/env python
import time
import datetime
import numpy as np
import matplotlib.pyplot as plt
plt.use('GTKAgg')
import matplotlib.ticker as mticker
import matplotlib.dates as mdates

eachStock = 'TSLA', 'AAPL'

def graphData(stock):
     try:
	stockfile = stock+'.txt'

	date, closep, highp, lowp, openp, volume = np.loadtxt(stockFile, delimiter=',',unpack=True,converters={ 0: smdates.strpdate2num('%Y%m%d')})

	fig = plt.figure()
	ax1 = plt.subplot(1,1,1)
	ax1.plot(date, openp)
	ax1.plot(date, highp)
	ax1.plot(date, lowp)
	ax1.plot(date, closep)
 	
	plt.show()

     except Exception, e:
	print 'failed main loop',str(e)

for stock in eachStock:
	graphData(stock)
Esempio n. 13
0
feature_file_path = "F:\Yassien_PhD\Experiment_4\All_Categories_Data_25_Basic_Features_With_10_Time_Intervals\Arts, Crafts & Sewing.txt"
target = []
features = []
with open(feature_file_path, 'r') as filep:
    for item in filep:
        review = item.split(' ')
        target.append(review[0])
        feat_vect = []
        for i in range(2, len(review)):
            feat_vect.append(float(review[i].split(':')[1]))
        features.append(feat_vect)

data = np.array(features)

# clustering
thresh = 0.7
clusters = hcluster.fclusterdata(data, thresh, criterion="distance")
#k_means = cluster.KMeans(n_clusters=30)
#k_means.fit(data)
print(type(clusters))
for clus in clusters:
    print(clus)
# plotting
plt.use("ggplot")
plt.scatter(*numpy.transpose(data), c=clusters)
plt.axis("equal")
title = "threshold: %f, number of clusters: %d" % (thresh, len(set(clusters)))
plt.title(title)
plt.show()