Example #1
0
def get_new_weights(df_data, df_indicator):
    """
    :does: return weigts after MAI and alpha
    """
    # test data
    a = np.array([[1, 1, 1 / 2, 1 / 5, 1 / 9, 1 / 9],
                  [1, 1, 1 / 2, 1 / 5, 1 / 9, 1 / 9],
                  [2, 2, 1, 1 / 5, 1 / 9, 1 / 9], [5, 5, 5, 1, 1 / 5, 1 / 5],
                  [9, 9, 9, 5, 1, 1 / 2], [9, 9, 9, 3, 2, 1]])

    # relative weights
    weights = mai.mai(a)

    # quality vector
    df_indicator = df_indicator.sort_values(by=df_indicator.columns[0])

    indicators = df_indicator['Rating']

    # judgment matrix
    df_data = df_data.sort_values(by=df_data.columns[0])
    a_matrix = df_data[df_data.columns[1:]].to_numpy()

    # normalize indicators
    indicators_norm = np.copy(indicators)
    print('indicators')
    print(indicators)

    n = indicators_norm.size

    mn = indicators_norm.min()
    mx = indicators_norm.max()
    for i in range(n):
        indicators_norm[i] = (indicators_norm[i] - mn) / (mx - mn)

    print('indicators_norm')
    print(indicators_norm)

    dq = indicators_norm.var(ddof=0)

    print('dq: ' + str(dq))

    print()

    coh = mai.coherence(a, weights)
    print('coh: ' + str(coh))

    alpha_coef = dq / coh
    print('alpha_coef: ' + str(alpha_coef))

    w_new = alpha.alpha(alpha_coef, a_matrix, weights, indicators)
    print('w_new: ' + str(w_new))
    while True in (w_new < 0):
        alpha_coef += 0.1
        w_new = alpha.alpha(alpha_coef, a_matrix, weights, indicators)
    print(alpha_coef)

    return w_new
Example #2
0
def stokes_solver(w, mesh, Vspace, Pspace, Wspace, K_array, n):
	"""
	Solves the Stokes equation
	"""


	u, p = TrialFunctions(Wspace)
	v, q = TestFunctions(Wspace)
		
	K_Func  = interpolate(K_array, Pspace) # Kontroll function
	#plot(K_Func, interactive = False, title = 'Control Domain to be solved over')

	f = Constant([0.0,0.0]) 
 	a = inner(alpha(u, K_Func), v)*dx + inner(grad(u), grad(v))*dx + div(u)*q*dx + div(v)*p*dx
	L = inner(f, v)*dx
	UP = Function(Wspace)


	def u_boundaryBottom(x, on_bnd): 
		return x[1] < DOLFIN_EPS and x[0] > w and x[0] < 1-w and on_bnd
	def p_boundaryRightWall(x, on_bnd): 
		return x[0] > 1- DOLFIN_EPS and x[1] >= 0.5 and x[1] < 0.7 and on_bnd 

	bc_u_B  = DirichletBC(Wspace.sub(0), Constant((0.0,1.0)), u_boundaryBottom)
	velocityFunc = Expression(["0","x[0]-x[0]*x[0]"])
	

	# Project to the function space, plot it and see
	# plot the expression if provide the mesh argument 
	
	# this didnt work 
	#velocity_profile = project(velocityFunc, Pspace)
	#plot(velocity_profile, interactive = True, title = 'velocity parabolic profile')	

	bc_u_B  = DirichletBC(Wspace.sub(0), velocityFunc, u_boundaryBottom)
	bc_p_R  = DirichletBC(Wspace.sub(1), Constant(0.0), p_boundaryRightWall)
	bcs = [bc_u_B, bc_p_R]


	A, b = assemble_system(a, L, bcs)
	solve(A, UP.vector(), b, "lu")
	U, P = UP.split()
	#plot(U, interactive = False, title= "Velocity")
	#plot(P, interactive = True, title= "Pressure")


	#file = File('Stokes_flow.xdmf')
	#file << U 


	return U,P, K_Func
Example #3
0
def weight_graph(matrix_a, weights, q0):
    """
    :param q0: zero-coordinate on alpha
    :return: nothing
    :does: displays a graph of the dependence of weights
    """
    plt.rcParams.update({'font.size': 22})
    w_a = []
    for i in range(len(weights)):
        w_a.append({})
    w_a.append({})

    for i in range(1, 1001):
        a = float(i / 100)
        w_new = alpha.alpha(a, matrix_a, weights, q0)
        """
        w_new = []
        w_mnk = mnk.regularized_ls(matrix_a, q0, a, weights)
        for elem in w_mnk:
            w_new.append(elem[0])
        """
        for j in range(len(w_new)):
            w_a[j][a] = w_new[j]

        w_a[len(weights)][a] = 0
    # figure = plt.figure(dpi=100, figsize=(1980 / 100, 1080 / 100))
    figure, ax = plt.subplots(dpi=100, figsize=(1980 / 100, 1080 / 100))
    plt.xlim(0, 10)
    plt.xticks(range(11))
    ax.grid(which='major', color='k')

    # ax.set_title('W' + str(j))

    ax_colors = ["red", "blue", "green", "orange", "yellow", "pink", "black"]
    ax_labels = ["w1", "w2", "w3", "w4", "w5", "w6", "Ox"]

    for j in range(len(weights) + 1):
        # ax = figure.add_subplot(len(weights) / 2, len(weights) - (len(weights) / 2), j+1)
        # ax.set_title('W' + str(j))

        lists = (w_a[j].items())
        # print(lists)
        x, y = zip(*lists)
        ax.scatter(x, y, c=ax_colors[j], label=ax_labels[j])

    ax.legend(loc='upper right', prop={'size': 20})
    plt.savefig('result.png')
    plt.show()
Example #4
0
    def __init__(self):
        self.tag = ""
        self.win = tk.Tk()
        self.win.title("WallHaven Scrapper")

        inp = tk.Frame(master=self.win,
                       highlightthickness=2,
                       highlightbackground="black")
        tk.Label(master=inp, text="Enter tag to search").grid(row=0, column=0)
        self.btn = tk.Entry(master=inp, width=30)
        self.btn.grid(row=0, column=1)
        tk.Button(master=inp,
                  bg="black",
                  fg="white",
                  text="Get It",
                  command=self.get_tag).grid(row=0, column=2)
        inp.pack()

        self.main = tk.Frame(master=self.win)
        tk.Label(master=self.main, height=20, width=80,
                 image=None).grid(row=0, column=0)
        self.main.pack()
        self.img = ""

        footer = tk.Frame(master=self.win)
        self.nxt = tk.Button(master=footer,
                             bg="black",
                             fg="white",
                             text="Next Image",
                             state="disabled",
                             command=self.randomize_pic)
        self.nxt.grid(row=0, column=0)
        tk.Button(master=footer,
                  bg="black",
                  fg="white",
                  text="Save and Exit",
                  command=self.save_exit).grid(row=0, column=1)
        footer.pack()

        self.Obj = alpha.alpha()

        self.win.mainloop()
Example #5
0
    def run(self, freqs=[1.0,10.0,1.0],b=[0.0,0.0], freqUnit='GHz', orientation=None, block=[1,1], verbose=None, plot=None, outputType='frequency'):
        """Runs the model to produce the brightness temperature, weighting functions etc etc
           b = 0.04175 is a good value for Neptune images (don't remember why at the moment...)
           outputType sets whether frequency, wavelength, or both are written
           if outputType is 'batch', it forces the outType to be 'Spectrum' and outputType to be 'frequency'"""

        self.imSize = None
        self.outType = None
        self.bType = None

        ###Set freqs
        reuse = False
        if freqs == None and freqUnit == None:
            freqs = self.freqs
            freqUnit = self.freqUnit
        elif freqs == 'reuse':
            freqs = self.freqs
            reuse = True
        else:
            if freqUnit == None:
                freqUnit = 'GHz'
                self.freqUnit = freqUnit
            if freqs == None:
                freqs = self.freqs
            else:
                freqs = self.__freqRequest__(freqs, freqUnit)
            freqUnit = self.freqUnit
        self.freqs = freqs
        self.freqUnit = freqUnit
        
        ###Set b
        if b == None:
            b = self.b
        else:
            b = self.__bRequest__(b,block)
        if self.outType is None or self.outType == 'Spectrum' or self.outType == 'Profile':
            if len(b) > 5*len(freqs):
                self.outType = 'Profile'
            else:
                self.outType = 'Spectrum'
        if outputType == 'batch':
            self.outType = 'Spectrum'
            outputType = 'frequency'
        self.b = b
        print 'outType = '+self.outType
        if self.outType == 'Image' and len(freqs) > 1:
            print 'Image must be at only one frequency'
            print 'Using %f %s' % (freqs[0],self.freqUnit)
            self.freqs = list(freqs[0])
            freqs = self.freqs

        ###Verbose,plot,start
        if verbose == None:
            verbose = self.verbose
        if plot == None:
            plot = self.plot
        runStart = datetime.datetime.now()

        if not reuse:
            ### Read in absorption modules:  to change absorption, edit files under /constituents'
            self.alpha = alpha.alpha(config=self.config,log=self.log,verbose=verbose,plot=plot)
            #self.alpha.test(f=0,verbose=True,plot=True)
            self.log.flush()

            ### Next compute radiometric properties - initialize bright
            self.bright = bright.brightness(log=self.log,verbose=verbose,plot=plot)
            if not self.config.Doppler:
                self.bright.layerAbsorption(freqs,self.atm,self.alpha)
            
        self.Tb=[]
        hit_b=[]
        btmp = ''
        self.rNorm = None; self.tip = None; self.rotate = None
        if self.outType == 'Image':  ##We now treat it as an image at one frequency
            print 'imgSize = %d x %d' % (self.imSize[0], self.imSize[1])
            self.Tb_img = []
            imtmp = []
            if abs(block[1])>1:
                btmp = '_%02dof%02d'%(block[0],abs(block[1]))
            else:
                btmp = ''
            
        for i,bv in enumerate(b):
            print '%d of %d (view [%.4f, %.4f])  ' % (i+1,len(b),bv[0],bv[1]),
            Tbt = self.bright.single(freqs,self.atm,bv,self.alpha,orientation,plot=not(self.outType=='Image'),discAverage=(self.bType=='disc'))
            if self.bright.path != None and self.rNorm == None:
                self.rNorm = self.bright.path.rNorm
            if self.bright.path != None and self.tip == None:
                self.tip = self.bright.path.tip
            if self.bright.path != None and self.rotate == None:
                self.rotate = self.bright.path.rotate
            if Tbt == None:  #I've now done away with returning None by returning T_cmb in brightness.py (at least I thought so...)
                Tbt = []
                for i in range(len(freqs)):
                    Tbt.append(utils.T_cmb)
            else:            #   ... so should always go to 'else'
                hit_b.append(bv)
            self.Tb.append(Tbt)
            if self.outType == 'Image':
                imtmp.append(Tbt[0])
                if not (i+1)%self.imSize[0]:
                    self.Tb_img.append(imtmp)
                    imtmp = []
        self.log.flush()

        ###Write output files (this needs to be compatible with TBfile  -- eventually should incorporate it in there###
        datFile = 'Output/%s_%s%s_%d%02d%02d_%02d%02d.dat' % (self.planet,self.outType,btmp,runStart.year,runStart.month,runStart.day,runStart.hour,runStart.minute)
        print '\nWriting '+self.outType+' data to ',datFile
        df = open(datFile,'w')
        self.__setHeader__(self.rNorm)
        self.__writeHeader__(df)
        if self.outType == 'Image':
            for data0 in self.Tb_img:
                s = ''
                for data1 in data0:
                    s+= '%7.2f\t' % (data1)
                s+='\n'
                df.write(s)
        elif self.outType == 'Spectrum':
            fp_lineoutput = open('specoutputline.dat','w')
            if outputType == 'frequency':
                s = '# %s  K@b  \t' % (self.freqUnit)
            elif outputType == 'wavelength':
                s = '# cm   K@b  \t'
            else:
                s = '# %s    cm    K@b  \t' % (self.freqUnit)
            for i,bv in enumerate(hit_b):
                s+='(%5.3f,%5.3f)\t' % (bv[0],bv[1])
            s=s.strip('\t')
            s+='\n'
            df.write(s)
            for i,f in enumerate(freqs):
                wlcm = 100.0*utils.speedOfLight / (f*utils.Units[self.freqUnit])
                if outputType == 'frequency':
                    s = '%.2f\t  ' % (f)
                elif outputType == 'wavelength':
                    s = '%.4f\t  ' % (wlcm)
                else:
                    s = '%.2f     %.4f \t ' % (f,wlcm)
                for j in range(len(hit_b)):
                    s+='  %7.2f  \t' % (self.Tb[j][i])
                s=s.strip()
                s+='\n'
                fp_lineoutput.write(s)
                df.write(s)
            fp_lineoutput.close()
        elif self.outType == 'Profile':
            if outputType == 'frequency':
                s = '# b  K@%s \t'  % (self.freqUnit)
            elif outputType == 'wavelength':
                s = '# b  K@cm  \t'
            else:
                s = '# b  K@GHz,cm  \t'
            for i,fv in enumerate(freqs):
                wlcm = 100.0*utils.speedOfLight / (fv*utils.Units[self.freqUnit])
                if outputType == 'frequency':
                    s+='  %9.4f   \t' % (fv)
                elif outputType == 'wavelength':
                    s+='  %.4f   \t' % (wlcm)
                else:
                    s+=' %.2f,%.4f\t' % (fv,wlcm)
            s.strip('\t')
            s+='\n'
            df.write(s)
            bs = []
            for i,bv in enumerate(hit_b):
                s = '%5.3f %5.3f\t' % (bv[0],bv[1])
                bs.append(math.sqrt(bv[0]**2 + bv[1]**2))
                for j in range(len(freqs)):
                    s+=' %7.2f\t ' % (self.Tb[i][j])
                s+='\n'
                df.write(s)
            if plot:
                plt.figure("Profile")
                Tbtr = np.transpose(self.Tb)
                for j in range(len(freqs)):
                    frqs = ('%.2f %s' % (self.freqs[j],self.freqUnit))
                    plt.plot(bs,Tbtr[j],label=frqs)
                plt.legend()
                plt.xlabel('b')
                plt.ylabel('$T_B$ [K]')
        else:
            print 'Invalid outType:  '+self.outType
        df.close()
Example #6
0
        print >> sys.stderr, "Corpora have different lengths"
        sys.exit(1)

    corpora = [corpusA, corpusB]
else:
    corpora = aggregate(*[os.path.normpath(dir) for dir in args])

if '--acc' in options:
    if '--tree' in options:
        cmp = pairwise_jaccard(*corpora)
    else:
        cmp = conll.pairwise_compare(*corpora)

if metric == 'all':
    for name, d in metrics.items():
        print "\\alpha_%s=%f" % (name, alpha(corpora, metric=d, convert_items=lambda s: s))

    if '--acc' in options:
        print "UAS: ", cmp['UAS']
        print "LAS: ", cmp['LAS']
        print "lbl: ", cmp['lbl']
        if cmp.get('ignored', 0) > 0:
            print "Ignored %d sentences in accuracy computation" % cmp['ignored']
else:
    print alpha(corpora, metric=metrics[metric], convert_items=lambda s: s),

    if '--acc' in options:
        print cmp['UAS'], cmp['LAS'], cmp['lbl'],

    print ''
Example #7
0
def stokes_solver(w, mesh, Vspace, Pspace, Wspace,DG1, K_array, n):
	"""
	Solves the Stokes equation
	"""

	u, p = TrialFunctions(Wspace)
	v, q = TestFunctions(Wspace)
		
	K_Func  = interpolate(K_array, DG1) # Kontroll function
	#plot(K_Func, interactive = False, title = 'Control Domain to be solved over')

	f = Constant([0.0,0.0]) 
 	a = inner(alpha(u, K_Func), v)*dx + inner(grad(u), grad(v))*dx + div(u)*q*dx + div(v)*p*dx
	L = inner(f, v)*dx
	UP = Function(Wspace)

	velocityFunc = Expression(["0","-(x[0]-0.45)*(x[0]-0.55)"])
	
	
	def u_boundaryBottom(x, on_bnd): 
		return x[1] < DOLFIN_EPS and x[0] > w and x[0] < 1-w and on_bnd
		
	def restBottom(x, on_bnd):
		return x[1] < DOLFIN_EPS and  not (x[0]> w) and not (x[0] < 1-w) and on_bnd
	
    	def leftWall(x, on_boundary):
        	return near(x[0], 0.0)
	
	def rightWall(x, on_boundary):
        	return near(x[0], 1.0)
	
	def outlet(x, on_bnd):
		return x[1] < 1 - DOLFIN_EPS and x[0] > w and x[0] < 1-w and on_bnd
	
	
	# SIMON: 
	# Project to the function space, plot it and see
	# plot the expression if provide the mesh argument 
	# this didnt work 
	# velocity_profile = project(velocityFunc, Pspace)
	# plot(velocity_profile, interactive = True, title = 'velocity parabolic profile')	

	inlet  = DirichletBC(Wspace.sub(0), velocityFunc, u_boundaryBottom)
	restBottom = DirichletBC(Wspace.sub(0), Constant((0.0,0.0)), restBottom)		
	right = DirichletBC(Wspace.sub(0), Constant((0.0,0.0)), rightWall)	
	left = DirichletBC(Wspace.sub(0), Constant((0.0,0.0)), leftWall)	
	
	#top = DirichletBC(Wspace.sub(0), Constant((0.0,0.0)), outlet)	


	# Make dirichlet bcs overalt unntatt outletene 
	#rightOutlet  = DirichletBC(Wspace.sub(1), Constant(0.0), p_boundaryRightWall)
	#leftOutlet   = DirichletBC(Wspace.sub(1), Constant(0.0), p_boundaryLeftWall)	
		
	bcs = [inlet, restBottom, right, left] # right, left, top] #, rightOutlet, leftOutlet]


	A, b = assemble_system(a, L, bcs)
	solve(A, UP.vector(), b, "lu")
	U, P = UP.split()
	n = FacetNormal(mesh)
	print "Mass conservation: ", assemble(inner(U, n)*ds)
	plot(U, interactive = True, title= "Velocity")
	#plot(P, interactive = True, title= "Pressure")


	#file = File('Stokes_flow.xdmf')
	#file << U 


	return U,P, K_Func