def mouseReleaseEvent(self, event): self.clear() self.inputting = False self.fourier = Fourier(self.view, self.path, path_offset=self.start_at, closed=False) self.addItem(self.fourier) self.go()
def fourier(): if request.args.get('function') is None: return render_template('fourier.html') else: fourier_in = cv2.imread('web/lena.jpg', 0) fourier_out = Fourier(fourier_in) cv2.imwrite('web/static/fourier.jpg', fourier_out) return send_file('static/fourier.jpg', mimetype='image/jpeg')
def initScene(self): self.scene = QGraphicsScene(self) self.setScene(self.scene) self.setSceneRect(-self.WIDTH/2, -self.HEIGHT/2, self.WIDTH, self.HEIGHT) # Pick a random .svg file in svg folder. self.fileName = 'svg/' + random.choice(os.listdir('svg/')) # Get QPainterPath from said file. path, closed = svgToPath(self.fileName) scale = getScale(path, 1000, 600, 500, 300) self.fourier = Fourier(self, path, scale=scale, closed=closed) self.scene.addItem(self.fourier)
def rankFeaturesFourier(self, X, y, d=1): compare = lambda x, y: cmp(abs(x), abs(y)) sorted_coeffs = sorted(Fourier(X, y, self.logger).coeff(d).items(), key=operator.itemgetter(1), reverse=True, cmp=compare) featureIndices = [] for ranking in sorted_coeffs: for index in ranking[0]: if index not in featureIndices: featureIndices.append(index) return featureIndices
def run(Ns, save_anim=False): # --- user input --- fig, ax = plt.subplots() ax.set_xlim([0, 1]) ax.set_ylim([0, 1]) draw = Drawer(fig, ax) plt.show() # --- find Fourier series for drawn shape --- fouriers = [Fourier(draw.points, N) for N in Ns] # --- plot drawn shape against Fourier approximation --- fig, axs = plt.subplots(1, len(Ns)) ps = draw.points t_start, t_end = ps[0, 0].real, ps[-1, 0].real ts = np.linspace(t_start, t_end, 100) fs = [f(ts) for f in fouriers] for ax, f in zip(axs, fs): ax.plot(ps[:, 1].real, ps[:, 1].imag) ax.plot(f.real, f.imag) plt.legend(("User Input", "Fourier Approximation")) plt.show() # --- animate Fourier drawing --- anim_fig, anim_axs = plt.subplots(1, len(Ns)) anim_fig.suptitle(f"Fourier approximations of orders {Ns}") anims = [] for anim_ax, fourier in zip(anim_axs, fouriers): anim_ax.set_xlim([0, 1]) anim_ax.set_ylim([0, 1]) anim_ax.set_title(f"N = {len(fourier.n) // 2}") anims.append(Animator(anim_ax, fourier)) group_anim = GroupAnimator(anim_fig, anims, ts[-1]) if save_anim: fig.savefig('images\comparison.png') group_anim.save('images\drawing.gif', writer='imagemagick', fps=30) plt.show()
def create_arrows(ax, fourier): """Create arrows from the coefficients of a Fourier series""" p = 0 + 0j arrows = [] for c, n in zip(fourier.c, fourier.n): arrow = Arrow(ax, p.real, p.imag, n, c, fourier.L) arrows.append(arrow) p += c return arrows if __name__ == "__main__": fig, axes = plt.subplots(1, 2) fig.set_size_inches(14, 7) ts = np.linspace(0, 6.28, 100) xs = 0.5 * np.cos(ts) + 0.5 * np.cos(2 * ts) ys = np.sin(ts) + 0.25 points = np.array([ts, xs + 1j * ys]).T anims = [] for n, ax in enumerate(axes): f = Fourier(points, N=n+1) anims.append(Animator(ax, f)) ax.set_xlim((-2, 2)) ax.set_ylim((-2, 2)) group_anims = GroupAnimator(fig, anims, 6.28) plt.show()
mytimes, mygroups = run.getTimeGroups(time) # ds = float(run.dl) dt = float(mytimes[1] - mytimes[0]) # numoftimes = mytimes.__len__() numofcells = int(run.ncells) + 1 # data = np.empty([numoftimes, numofcells], dtype=complex, order='C') # # then fill the data for input fft for it in range(mytimes.__len__()): data[it, :].real = run.GetB(mytimes[it])[..., 2] data[it, :].imag = 0.0 # f = Fourier(data, field=field, domain=domain) # # # .. draw the plot plo = Colp(colordata=[ f.xdata / float(run.dl), f.ydata / float(mytimes[1] - mytimes[0]), f.zdata ], bounds=bounds, colormap=colormap, contourdata=None, flines=None, arrowdata=None, labels=['$k$', '$\omega$'], ticks=ticks, subticks=subticks, figsize=figsize,
if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--embed_dir', type=str, help="directory to embeddings") parser.add_argument('--results_dir', type=str, help="directory to results") parser.add_argument('--periods', type=int, nargs='+', help="list of periods") parser.add_argument('--mean', action='store_true', help="use mean descriptor or not") parser.add_argument('--events', type=int, nargs='+', default=range(1, 14), help="list of events") args = parser.parse_args() use_mean = args.mean if not os.path.exists(args.results_dir): os.makedirs(args.results_dir) if not use_mean: periods = args.periods fourier = Fourier(periods) fourier_coefs = fourier.get_fourier_coefs() offset_mat_dicts = fourier.get_offset_mats() retrieve = Retrieve(args.embed_dir, args.results_dir) retrieve()
def __init__(self, param, grid): self.list_param = [ 'varname_list', 'tracer_list', 'whosetspsi', 'mpi', 'npx', 'npy', 'nh', 'gravity', 'f0', 'beta', 'Rd', 'qgoperator', 'order', 'Kdiff', 'diffusion', 'enforce_momentum', 'isisland', 'aparab', 'flux_splitting_method', 'hydroepsilon', 'myrank', 'geometry', 'sqgoperator' ] param.copy(self, self.list_param) self.list_grid = [ 'msk', 'nxl', 'nyl', 'dx', 'dy', 'bcarea', 'mpitools', 'msknoslip', 'mskbc', 'domain_integration', 'nh', 'xr0', 'yr0', 'i0', 'j0', 'area' ] grid.copy(self, self.list_grid) self.first_time = True # internal work array for the inversion self.work = zeros((self.nyl, self.nxl)) self.work2 = zeros((self.nyl, self.nxl)) pp = { 'np': param.npx, 'mp': param.npy, 'nh': param.nh, 'n': param.nx // param.npx, 'm': param.ny // param.npy, 'omega': 8. / 9., 'npmpmax': 1, 'verbose': False, 'dx': grid.dx, 'dy': grid.dy, 'n1': 32, 'n0': 4, 'method': 'deep', 'nagglo': 2, 'hydroepsilon': param.hydroepsilon, 'relaxation': param.relaxation } # load the multigrid solver # # WARNING: the multigrid needs the mask at cell corners!!! # not at cell centers mskr = self.msk * 1. # this piece is a bit awkward: to initialize gmg, we need # a mask with a halo properly filled but the fill_halo method # belongs to gmg. We have a circular definition. # the trick: define a dummy gmg first a msk=1 everywhere # then grab the fill_halo method and redefine once again the # multigrid, this time with the proper mask # self.gmg = Gmg(pp,mskr) # borrow the fill_halo from the multigrid # self.fill_halo = self.gmg.grid[0].halo.fill fo.celltocorner(mskr, self.work) # self.fill_halo(self.work) # del self.gmg # del self.fill_halo self.work[self.work < 1.] = 0. self.mskp = self.msk * 0 self.mskp[self.work == 1.] = 1 pp['verbose'] = True if self.myrank == 0: print('-' * 50) print(' Multigrid hierarchy') print('-' * 50) if hasattr(self, 'qgoperator'): pp['qgoperator'] = True pp['Rd'] = self.Rd self.gmg = Gmg(pp, self.work) else: self.gmg = Gmg(pp, self.work) if hasattr(self, 'sqgoperator'): self.fourier = Fourier(param, grid) # borrow the fill_halo from the multigrid self.fill_halo = self.gmg.grid[0].halo.fill grid.fill_halo = self.gmg.grid[0].halo.fill self.blwidth = param.Lx * 0.05 # tentative for a regularized no-slip source term coef = 0. * zeros_like(self.mskp) coef[1:, 1:] = (self.mskp[:-1, 1:] + self.mskp[:-1, :-1] + self.mskp[1:, 1:] + self.mskp[1:, :-1]) # nbpsibc is the number of land psi-points surrounding a fluid cell self.nbpsibc = (4. - coef) * self.msk self.nbpsibc[self.nbpsibc > 0] = 1. self.set_boundary_msk() self.cst = zeros(5, ) # select the proper flux discretization if self.order % 2 == 0: self.fortran_adv = fa.adv_centered self.cst[0] = grid.dx self.cst[1] = grid.dy self.cst[2] = 0.05 self.cst[3] = 0 # umax self.cst[4] = 0 # unused # should be updated at each timestep # self.cst[3]=param.umax else: self.fortran_adv = fa.adv_upwind self.cst[0] = grid.dx self.cst[1] = grid.dy self.cst[2] = 0.05 self.cst[3] = 0 # umax self.cst[4] = self.aparab # should be updated at each timestep # self.cst[3]=param.umax # controls the flux splitting method # 0 = min/max # 1 = parabolic list_fs_method = ['minmax', 'parabolic'] if self.flux_splitting_method in list_fs_method: self.fs_method = list_fs_method.index(self.flux_splitting_method) else: print('Warning: %s does not exist' % self.flux_splitting_method) print('replaced with the default: parabolic') self.fs_method = list_fs_method.index('parabolic') # these coefficients below are used for the thermalwind model coef = 0. * zeros_like(self.msk) coef[1:-1, 1:-1] = self.msk[1:-1, 2:] + self.msk[1:-1, 0:-2] coef[coef < 2] = 0. coef[coef == 2] = 0.5 self.fill_halo(coef) self.coefb = coef * 1. coef = 0. * zeros_like(self.msk) coef[1:-1, 1:-1] = self.msk[2:, 1:-1] + self.msk[0:-2, 1:-1] coef[coef < 2] = 0. coef[coef == 2] = 0.5 self.fill_halo(coef) self.coefV = coef * 1. if type(self.Kdiff) != dict: K = self.Kdiff self.Kdiff = {} for trac in self.tracer_list: self.Kdiff[trac] = K if self.diffusion: print('diffusion coefficients') print(' => ', self.Kdiff)
from image import Image from fourier import Fourier from plot import Plot im = Image("house.jpg", (200, 200)) path = im.sort() period, tup_circle_rads, tup_circle_locs = Fourier(n_approx=1000, coord_1=path).get_circles() Plot(period, tup_circle_rads, tup_circle_locs, speed=80).plot()
mydate = df['Dates'] nd = len(mydate) print "%d crimes in total" % nd tw = np.zeros(nd) # array of times in weeks for i in range(0, nd): tw[i] = (mydate[i]-t0).total_seconds() tw[i] /= swk tw = tw[tw <= 1.0] # only times in the first week tw = tw * 7 nc = len(tw) # Now get Fourier curve nw = 336 nb = 84 t = np.linspace(0.0, 1.0, nw) MyF = Fourier(645.0, 16, 52.1775, 12, 1.0, 6, 1.0/7.0, 8, df, t0) MyF.compute() fv = np.empty(nw) #fv.fill(2700.0) for i in range(0, nw): fv[i] = MyF.fa(t[i]) fv[i] *= nc + 0.0 fv[i] /= nb + 0.0 # Got Fourier curve t = t * 7 plt.hist(tw, bins=nb) # 645 weeks but we only have alternating weeks plt.plot(t, fv, linewidth=2.5) plt.title("Crimes History") plt.xlabel("Days") plt.ylabel("Crimes per 2 hours")
import csv import math from datetime import datetime from fourier import Fourier twopi = 2.0 * math.pi t0 = np.datetime64("2003-01-01") ## read training file z = zipfile.ZipFile('../train.csv.zip') dateparse = lambda x: pd.datetime.strptime(x, '%Y-%m-%d %H:%M:%S') df = pd.read_csv(z.open('train.csv'), parse_dates=['Dates'], date_parser=dateparse) #crime_category = df['Category'] # list of crime types #group = df.groupby('Category') #freq = group.size() # histogram of crime types #cr_index = freq.index.values #Nc = len(cr_index) # number of crime types #cr_a_index = pd.DataFrame(data = np.arange(Nc, dtype=np.int), index = cr_index) #cr_a_index = cr_a_index[0] # this now holds the index for each crime type MyF = Fourier(645.0, 20, 52.1775, 12, 1.0, 6, 1.0 / 7.0, 6, df) MyF.compute() MyF.graph() ## read testing file #z = zipfile.ZipFile('../test.csv.zip') #df = pd.read_csv(z.open('train.csv'), parse_dates=['Dates'], date_parser=dateparse)
import matplotlib.pyplot as pt from fourier import Fourier import numpy as np t = np.arange(0.0, 8, 0.01) print(t.shape[0]) s1 = np.sin(2 * np.pi * t) s2 = np.cos(4 * np.pi * t) + s1 s3 = np.random.random(128) jf = Fourier() #f_s1 = jf.Fast(s1) #f_s2 = jf.Fast(s2) #f_s3 = jf.Fast(s3) f_s1 = np.fft.fft(s1) #f_s2 = np.fft.fft(s2) f_s2 = jf.Fast(s2, vect=False) f_s3 = np.fft.fft(s3) m_s1 = jf.complex_to_linear(f_s1) m_s2 = jf.complex_to_linear(f_s2) m_s3 = jf.complex_to_linear(f_s3) fig, ax = pt.subplots(3, 3) ax[0, 0].plot(t, s1) ax[0, 1].plot(t, s2)