Exemplo n.º 1
0
 def __init__(self, factor1='0', factor2='0', answer='0', operator='+'):
     #因子1
     self.factor1 = Factors(factor1)
     #因子2
     self.factor2 = Factors(factor2)
     #结果
     self.answer = Factors(answer)
     #符号
     self.operator = Operators(operator)
     #是否为等式
     if self.operator.val() == 1:
         if self.factor1.val() + self.factor2.val() == self.answer.val():
             self.equal = True
         else:
             self.equal = False
     elif self.operator.val() == 2:
         if self.factor1.val() - self.factor2.val() == self.answer.val():
             self.equal = True
         else:
             self.equal = False
     else:
         if self.factor1.val() * self.factor2.val() == self.answer.val():
             self.equal = True
         else:
             self.equal = False
Exemplo n.º 2
0
    def IntermolecularIneffectiveCollision(self, mole, oldMol1, oldMol2,
                                           index1, index2):
        operator = Operators()
        newMol1, newMol2 = operator.Intermolecular(oldMol1, oldMol2)
        pe1 = CRO().CalculatePE(mole, newMol1)
        pe2 = CRO().CalculatePE(mole, newMol2)

        e_inter = 0
        gamma4 = random.uniform(0, 1)

        mole.numHit[index1] = mole.numHit[index1] + 1
        mole.numHit[index2] = mole.numHit[index2] + 1
        e_inter = (mole.PE1[index1] + mole.PE1[index2] + mole.KE1[index1] +
                   mole.KE1[index2]) - (pe1 + pe2)
        if (e_inter >= 0):
            mole.moleculeTable[index1] = newMol1
            mole.moleculeTable[index2] = newMol2
            mole.PE1[index1] = pe1
            mole.PE1[index2] = pe2
            mole.KE1[index1] = e_inter * gamma4
            mole.KE1[index2] = e_inter * (1 - gamma4)

            if (mole.PE1[index1] < mole.minPE[index1]):
                mole.minStruct[index1] = mole.moleculeTable[index1]
                mole.minPE[index1] = mole.PE1[index1]
                mole.minHit[index1] = mole.numHit[index1]
            # endif

            if (mole.PE1[index2] < mole.minPE[index2]):
                mole.minStruct[index2] = mole.moleculeTable[index2]
                mole.minPE[index2] = mole.PE1[index2]
                mole.minHit[index2] = mole.numHit[index2]
Exemplo n.º 3
0
    def __init__(self,param,grid):

        self.list_param=['forcing','noslip','timestepping','diffusion','Kdiff',
                         'forcing_module','gravity','isisland',
                         'customized','custom_module','additional_tracer']
        param.copy(self,self.list_param)

        # for potential energy
        self.list_param=['xr','yr','nh','Lx','msk','area','mpitools']
        grid.copy(self,self.list_param)

        # for variables
        param.varname_list=['vorticity','psi','u','v','buoyancy']
        param.tracer_list=['vorticity','buoyancy']
        param.whosetspsi=('vorticity')

        if hasattr(self,'additional_tracer'):
            for k in range(len(self.additional_tracer)):
                trac=self.additional_tracer[k]
                param.varname_list.append(trac)
                param.tracer_list.append(trac)
                print('Tracers are :',param.tracer_list)

        param.sizevar     =[grid.nyl,grid.nxl]
        self.var = Var(param)
        self.source = zeros(param.sizevar)

        # for operators
        self.ope = Operators(param,grid)

        # for timescheme
        self.tscheme = Timescheme(param,self.var.state)
        self.tscheme.set(self.dynamics, self.timestepping)

        if self.forcing:

            try:
                f = import_module(self.forcing_module)
            except:
                print('module %s for forcing cannot be found'%self.forcing_module)
                print('make sure file **%s.py** exists'%self.forcing_module)
                exit(0)

            self.forc = f.Forcing(param,grid)

        self.diags={}

        if self.customized:
            try:
                f = import_module(self.custom_module)
                print(f)
                self.extrastep = f.Step(param,grid)
            except:
                print('module %s for forcing cannot be found'%self.custom_module)
                print('make sure file **%s.py** exists'%self.custom_module)
                exit(0)
Exemplo n.º 4
0
    def __init__(self, param, grid):

        self.list_param = ['forcing', 'noslip', 'timestepping',
                           'forcing_module', 'additional_tracer',
                           'myrank',
                           'gravity', 'diffusion', 'Kdiff', 'f0']
        param.copy(self, self.list_param)

        # for potential energy
        self.list_param = ['xr', 'yr', 'nh',
                           'Lx', 'msk', 'area', 'mpitools', 'dx']
        grid.copy(self, self.list_param)

        # for variables
        param.varname_list = ['vorticity', 'psi',
                              'u', 'v', 'buoyancy', 'V', 'qE']
        param.tracer_list = ['vorticity', 'buoyancy', 'V']
        param.whosetspsi = ('vorticity')

        if hasattr(self, 'additional_tracer'):
            for k in range(len(self.additional_tracer)):
                trac = self.additional_tracer[k]
                param.varname_list.append(trac)
                param.tracer_list.append(trac)

        param.sizevar = [grid.nyl, grid.nxl]
        self.var = Var(param)

        # for operators
        self.ope = Operators(param, grid)

        # for timescheme
        self.tscheme = Timescheme(param, self.var.state)

        if self.forcing:
            if self.forcing_module == 'embedded':
                print('Warning: check that you have indeed added the forcing to the model')
                print('Right below the line    : model = f2d.model')
                print('you should have the line: model.forc = Forcing(param, grid)')

                pass
            else:
                try:
                    f = import_module(self.forcing_module)

                except ImportError:
                    print('module %s for forcing cannot be found'
                          % self.forcing_module)
                    print('make sure file **%s.py** exists' % self.forcing_module)
                    sys.exit(0)

                self.forc = f.Forcing(param, grid)


        self.diags = {}
Exemplo n.º 5
0
def _infix_to_posfix_part_two(input):
    output = Queue()
    operator_stack = []
    bracket_count = 0
    grouped_operators = ''

    for c in input:
        if represents_int(c) and bracket_count == 0:
            output.put(int(c))
        elif bracket_count > 0 or Operators(c) == Operators.OPEN_BRACKET:
            # push all values grouped together and recursively solve
            grouped_operators += c

            is_number = represents_int(c)

            if not is_number and Operators(c) == Operators.OPEN_BRACKET:
                bracket_count += 1
            elif not is_number and Operators(c) == Operators.CLOSE_BRACKET:
                bracket_count -= 1

                # if last close bracket solve and treat as operator
                if bracket_count == 0:
                    output.put(
                        evaluate_equation_part_two(grouped_operators[1:-1]))
                    grouped_operators = ''

        elif len(operator_stack) > 0:
            # peek at last operator to determine precedence level
            last_operator = operator_stack[-1]
            current_operator = Operators(c)

            # addition is evaluated before multiplication
            _check_operator(output, operator_stack, current_operator,
                            last_operator)

        else:
            operator_stack.append(Operators(c))

    for val in operator_stack[::-1]:
        output.put(val)

    return output
Exemplo n.º 6
0
    def __init__(self, param, grid):
        self.list_param = [
            'forcing', 'diffusion', 'Kdiff', 'noslip', 'timestepping', 'beta',
            'Rd', 'forcing_module'
        ]
        param.copy(self, self.list_param)

        # for diagnostics
        self.list_param = ['yr', 'nh', 'msk', 'area', 'mpitools']
        grid.copy(self, self.list_param)

        # for variables
        param.varname_list = ('pv1', 'psi1', 'u1', 'v1', 'pv2', 'psi2', 'u2',
                              'v2')
        param.sizevar = [grid.nyl, grid.nxl]
        self.var = Var(param)
        self.source = zeros(param.sizevar)

        #        self.ipva = self.var.varname_list.index('pvanom')
        #        self.ipv  = self.var.varname_list.index('pv')
        #        self.ivor = self.var.varname_list.index('vorticity')
        #        self.ipsi = self.var.varname_list.index('psi')

        # background pv
        self.pvback = self.beta * (grid.yr - grid.Ly * .5) * grid.msk

        # for operators
        param.tracer_list = ['pv1', 'pv2']
        param.whosetspsi = ('pvanom')
        param.qgoperator = True
        self.ope = Operators(param, grid)

        # for timescheme
        self.tscheme = Timescheme(param, self.var.state)
        self.dx0 = self.tscheme.dx0

        self.kt = 0

        if self.forcing:

            try:
                f = import_module(self.forcing_module)
            except:
                print('module %s for forcing cannot be found' %
                      self.forcing_module)
                print('make sure file **%s.py** exists' % self.forcing_module)
                exit(0)

            self.forc = f.Forcing(param, grid)

        self.diags = {}

        self.tscheme.set(self.dynamics, self.timestepping)
Exemplo n.º 7
0
Arquivo: de.py Projeto: h3nnn4n/odeen
    def __init__(self, config=None):
        self.config = config
        self.config.de = self

        self.size = self.config.size
        self.dimensions = self.config.dimensions

        self.population = Population(config=config)

        self.operators = Operators(config=config)

        self.config.population = self.population
Exemplo n.º 8
0
def _infix_to_posfix_part_one(input):
    output = Queue()
    operator_stack = []
    bracket_count = 0
    grouped_operators = ''

    for c in input:
        if represents_int(c) and bracket_count == 0:
            output.put(int(c))
        elif bracket_count > 0 or Operators(c) == Operators.OPEN_BRACKET:
            # push all values grouped together and recursively solve
            grouped_operators += c

            is_number = represents_int(c)

            if not is_number and Operators(c) == Operators.OPEN_BRACKET:
                bracket_count += 1
            elif not is_number and Operators(c) == Operators.CLOSE_BRACKET:
                bracket_count -= 1

                # if last close bracket solve and treat as operator
                if bracket_count == 0:
                    output.put(
                        evaluate_equation_part_one(grouped_operators[1:-1]))
                    grouped_operators = ''

        elif len(operator_stack) > 0:
            # equal precedence
            output.put(operator_stack.pop())
            operator_stack.append(Operators(c))

        else:
            operator_stack.append(Operators(c))

    for val in operator_stack[::-1]:
        output.put(val)

    return output
Exemplo n.º 9
0
    def __init__(self, param, grid):

        self.list_param = ['forcing', 'noslip', 'timestepping']
        param.copy(self, self.list_param)

        # for variables
        param.varname_list = ('vorticity', 'psi', 'u', 'v', 'buoyancy', 'V')
        param.sizevar = [grid.nyl, grid.nxl]
        self.var = Var(param)

        # for operators
        param.tracer_list = ['vorticity', 'buoyancy', 'V']
        param.whosetspsi = ('vorticity')
        self.ope = Operators(param, grid)

        # for timescheme
        self.tscheme = Timescheme(param, self.var.state)
Exemplo n.º 10
0
	def Decomposition(self,mole,oldMol,index,shiftcost,flowcost,N):
		operator = Operators()
		newMol1, newMol2 = operator.Decomposition(oldMol)
		#print('DEcom ',newMol1,'\n',newMol2)
		pe1 = CRO().CalculatePE(newMol1,shiftcost,flowcost,N)
		pe2 = CRO().CalculatePE(newMol2,shiftcost,flowcost,N)
		mole.moleculeTable.append(newMol1)
		mole.moleculeTable.append(newMol2)
		#print(mole.moleculeTable)
		mole.PE.append(pe1)
		mole.PE.append(pe2)

		e_dec = 0
		gamma1 = 0
		gamma2 = 0
		gamma3 = 0
		gamma1 = random.uniform(0,1)
		gamma2 = random.uniform(0,1)

		if ((mole.PE[index] + mole.KE1[index]) >= (pe1+pe2)):
			e_dec = (mole.PE[index] + mole.KE1[index]) - (pe1 + pe2)
		else:
			e_dec = (mole.PE[index] + mole.KE1[index]) + gamma1 * gamma2 * self.buffer - (pe1 + pe2)
		# endif
		mole.KE1.append(e_dec * gamma3)

		if (e_dec>=0):
			self.buffer = self.buffer * (1 -( gamma1*gamma2))
			gamma3 = random.uniform(0,1)

			#mole.moleculeTable[index] = newMol1
			#mole.PE[index] = pe1
			mole.KE1[index] = e_dec * gamma3
			#mole.numHit[index] = 0
			#mole.minHit[index] = 0
			#mole.minStruct[index] = newMol1
			#mole.minPE[index] = pe1

			#mole.moleculeTable.append(newMol1)
			#mole.PE.append(pe1)
			#mole.KE1.append(e_dec * gamma3)
			mole.numHit.append(0)
			mole.minHit.append(0)
			mole.minStruct.append(newMol1)
			mole.minPE.append(pe1)
Exemplo n.º 11
0
 def OnwallIneffectiveCollision(self, mole, oldMol, index):
     operator = Operators()
     newMol = operator.OnWall(oldMol)
     PEnew = CRO().CalculatePE(mole, newMol)
     KEnew = 0.0
     mole.numHit[index] = mole.numHit[index] + 1
     t = mole.PE1[index] + mole.KE1[index]
     if (t >= PEnew):
         a = (random.uniform(0, 1) *
              (1 - self.KELossRate)) + self.KELossRate
         KEnew = (mole.PE1[index] - PEnew + mole.KE1[index]) * a
         mole.moleculeTable[index] = newMol
         mole.PE1[index] = PEnew
         mole.KE1[index] = KEnew
         if (mole.PE1[index] < mole.minPE[index]):
             mole.minStruct[index] = mole
             mole.minPE[index] = mole.PE1[index]
             mole.minHit[index] = mole.numHit[index]
Exemplo n.º 12
0
	def Synthesis (self,mole,oldMol1,oldMol2,index1,index2,shiftcost,flowcost,N):
		operator = Operators()
		newMol = operator.Synthesis(oldMol1, oldMol2)
		#print('EI j ',newMol)
		pe_new = CRO().CalculatePE(newMol,shiftcost,flowcost,N)

		mole.moleculeTable.append(newMol)
		mole.PE.append(pe_new)
		mole.KE1.append(pe_new)
		if((mole.PE[index1]+mole.PE[index2] + mole.KE1[index1]+mole.KE1[index2])>=pe_new):
			
			ke_new = (mole.PE[index1] + mole.PE[index2] + mole.KE1[index1] + mole.KE1[index2]) - pe_new

			mole.KE1.append(ke_new)
			#del mole.moleculeTable[index1]
			#del mole.PE[index1]

			#del mole.KE1[index1]
			#del mole.numHit[index1]
			#del mole.minHit[index1]
			#del mole.minStruct[index1]
			#del mole.minPE[index1]

			if(index2>=index1):
				# position of index2 is decreased by 1
				index2 = index2 -1




			#mole.moleculeTable.append(newMol)
			#mole.PE.append(pe_new)

			mole.KE1.append(ke_new)
			mole.numHit.append(0)
			mole.minHit.append(0)

			mole.minStruct.append(newMol)
			mole.minPE.append(pe_new)
		else:
			mole.numHit[index1] = mole.numHit[index1] + 1
			mole.numHit[index1] = mole.numHit[index1] + 1
Exemplo n.º 13
0
    def Decomposition(self, mole, oldMol, index):
        operator = Operators()
        newMol1, newMol2 = operator.Decomposition(oldMol)
        pe1 = CRO().CalculatePE(mole, newMol1)
        pe2 = CRO().CalculatePE(mole, newMol2)

        e_dec = 0
        gamma1 = 0
        gamma2 = 0
        gamma3 = 0
        gamma1 = random.uniform(0, 1)
        gamma2 = random.uniform(0, 1)

        if ((mole.PE1[index] + mole.KE1[index]) >= (pe1 + pe2)):
            e_dec = (mole.PE1[index] + mole.KE1[index]) - (pe1 + pe2)
        else:
            e_dec = (mole.PE1[index] + mole.KE1[index]
                     ) + gamma1 * gamma2 * self.buffer - (pe1 + pe2)
        # endif

        if (e_dec >= 0):
            self.buffer = self.buffer * (1 - (gamma1 * gamma2))
            gamma3 = random.uniform(0, 1)

            mole.moleculeTable[index] = newMol1
            mole.PE1[index] = pe1
            mole.KE1[index] = e_dec * gamma3
            mole.numHit[index] = 0
            mole.minHit[index] = 0
            mole.minStruct[index] = newMol1
            mole.minPE[index] = pe1

            mole.moleculeTable.append(newMol1)
            mole.PE1.append(pe1)
            mole.KE1.append(e_dec * gamma3)
            mole.numHit.append(0)
            mole.minHit.append(0)
            mole.minStruct.append(newMol1)
            mole.minPE.append(pe1)

        else:
            mole.numHit[index] = mole.numHit[index] + 1
Exemplo n.º 14
0
	def helmholtz(self, u, v, w):
		''' break a vector into solenoidal & dilatational parts '''
		Nx = self.para.Nx
		Ny = self.para.Ny
		Nz = self.para.Nz
		dx = self.para.dx
		dz = self.para.dz.reshape([-1,1])
		dy = self.para.dy.reshape([-1,1,1])
		hx = self.para.hx
		hz = self.para.hz.reshape([-1,1])
		hy = self.para.hy.reshape([-1,1,1])
		dy = self.para.dy.reshape([-1,1,1])
		hy = self.para.hy.reshape([-1,1,1])

		opt = Operators(self.para)
		
		# compute divergence and rotation of the vector field
		phi = opt.divergence(u,v,w)
		xi1, xi2, xi3 = opt.rotation(u,v,w)
		# implement homogeneous BC
		phi[[0,-1]] = 0
		xi1[[0,-1]] = 0
		xi2[[0,-1]] = 0
		xi3[[0,-1]] = 0

		# solve poisson equations with Dirichlet BC for xi2 and Neumann BC for others
		phi = self.poisson(phi)
		xi1 = self.poisson(-xi1)
		xi2 = self.poisson(-xi2, bcoef=1)
		xi3 = self.poisson(-xi3)

		# interpolate xi to staggered grids
		xi1[:,:,1:] = .5/hx[1:] * (xi1[:,:,1:]*dx[:-1] + xi1[:,:,:-1]*dx[1:])
		xi3[:,1:]   = .5/hz[1:] * (xi3[:,1:]  *dz[:-1] + xi3[:,:-1]  *dz[1:])
		xi2[1:]     = .5/hy[1:] * (xi2[1:]    *dy[:-1] + xi2[:-1]    *dy[1:])
		
		xi1[:,:,0] = 0
		xi3[:,0]   = 0
		xi2[0]     = 0

		# return Us (centered), Ud (staggered), xi (staggered), phi (centered)
		return opt.rotation(xi1,xi2,xi3), opt.gradient(phi), (xi1,xi2,xi3), phi
Exemplo n.º 15
0
    def Synthesis(self, mole, oldMol1, oldMol2, index1, index2):
        operator = Operators()
        newMol = operator.Synthesis(oldMol1, oldMol2)
        pe_new = CRO().CalculatePE(mole, newMol)

        if ((mole.PE1[index1] + mole.PE1[index2] + mole.KE1[index1] +
             mole.KE1[index2]) >= pe_new):

            ke_new = (mole.PE1[index1] + mole.PE1[index2] + mole.KE1[index1] +
                      mole.KE1[index2]) - pe_new

            del mole.moleculeTable[index1]
            del mole.PE1[index1]
            del mole.KE1[index1]
            del mole.numHit[index1]
            del mole.minHit[index1]
            del mole.minStruct[index1]
            del mole.minPE[index1]

            if (index2 >= index1):
                # position of index2 is decreased by 1
                index2 = index2 - 1

            del mole.moleculeTable[index2]
            del mole.PE1[index2]
            del mole.KE1[index2]
            del mole.numHit[index2]
            del mole.minHit[index2]
            del mole.minStruct[index2]
            del mole.minPE[index2]

            mole.moleculeTable.append(newMol)
            mole.PE1.append(pe_new)
            mole.KE1.append(ke_new)
            mole.numHit.append(0)
            mole.minHit.append(0)
            mole.minStruct.append(newMol)
            mole.minPE.append(pe_new)
        else:
            mole.numHit[index1] = mole.numHit[index1] + 1
            mole.numHit[index1] = mole.numHit[index1] + 1
Exemplo n.º 16
0
    def __init__(self, param, grid):

        self.list_param = ['timestepping', 'diffusion', 'Kdiff']
        param.copy(self, self.list_param)

        self.list_grid = ['msk', 'nh', 'area', 'mpitools']
        grid.copy(self, self.list_grid)

        # for variables
        param.varname_list = ['tracer', 'psi', 'u', 'v', 'vorticity']
        param.sizevar = [grid.nyl, grid.nxl]
        self.var = Var(param)

        # for operators
        param.tracer_list = ['tracer']
        param.whosetspsi = ('tracer')
        self.ope = Operators(param, grid)

        # for timescheme
        self.tscheme = Timescheme(param, self.var.state)
        self.tscheme.set(self.advection, self.timestepping)

        self.diags = {}
Exemplo n.º 17
0
	def OnwallIneffectiveCollision(self,mole,oldMol, index,shiftcost,flowcost,N):
		operator = Operators()
		newMol = operator.OnWall(oldMol)
		PEnew = CRO().CalculatePE(newMol,shiftcost,flowcost,N)
		KEnew = 0.0
		#mole.numHit[index] = mole.numHit[index] + 1
		t = mole.PE[index] + mole.KE1[index]
		if (t>=PEnew):
			a = (random.uniform(0,1) * (1-self.KELossRate))+self.KELossRate
			#KEnew = (mole.PE[index] - PEnew + mole.KE[index])*a
			'''
			#mole.KE1[index] = KEnew
			if(mole.PE[index]<mole.minPE[index]):
				mole.minStruct.append(mole)
				#mole.minPE[index] = mole.PE[index]
				#mole.minHit[index] = mole.numHit[index]
			#endif
			'''
		mole.moleculeTable.append(newMol)
		mole.KE1.append(KEnew)
		#print(mole.moleculeTable)
		mole.PE.append(PEnew)
		mole.KE1.append(KEnew)
Exemplo n.º 18
0
    def Mol(self, sequence, popSize, initialKE, minStem):
        self.sequence = sequence
        dotplot = population.Checkerboard(sequence)
        self.stemTable = population.FindDiagonal(sequence, dotplot, minStem)
        self.infoTable = self.stemTable[:]  # Copying the varible to keep original one
        # print(self.infoTable,'before')

        # RepairKHP operator
        Op = Operators()
        self.infoTable = Op.RepairKHP(self.infoTable)
        # print(self.infoTable,'after')

        self.molecules, self.stemPool, self.infoEnergy, self.moleculeEnergy, self.moleculeTable, self.basePairs, self.infoTable, self.moleculeShort, self.elements = population.GenerateMolecule(
            sequence, len(sequence), popSize, self.infoTable)
        #population.PrintInfo(molecule,stemPool,infoEnergy,moleculeEnergy)
        self.PE = self.moleculeEnergy
        self.PE1 = self.moleculeEnergy
        for i in range(len(self.moleculeTable)):
            self.KE.append(initialKE)
            self.KE1.append(initialKE)
            self.numHit.append(0)
            self.minStruct.append(self.moleculeTable[i])
            self.minPE.append(self.moleculeEnergy[i])
            self.minHit.append(0)
        #endfor

    #end


#endclass

#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# IMPORTANT
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

# Need to uniquify: moleculeTable
Exemplo n.º 19
0
	def IntermolecularIneffectiveCollision(self,mole,oldMol1,oldMol2,index1,index2,shiftcost,flowcost,N):
		operator = Operators()
		newMol1, newMol2 = operator.Intermolecular(oldMol1, oldMol2)
		pe1 = CRO().CalculatePE(newMol1,shiftcost,flowcost,N)
		pe2 = CRO().CalculatePE(newMol2,shiftcost,flowcost,N)
		
		e_inter = 0
		gamma4 = random.uniform(0,1)
		#print ('Intermoleculer newMoll', newMol1)

		mole.moleculeTable.append(newMol1)
		mole.moleculeTable.append(newMol2)
		mole.PE.append(pe1)
		mole.PE.append(pe2)
		#print('PE Check',mole.PE)
		#print ('Intermoleculer Table', mole.moleculeTable)
		#mole.numHit[index1] = mole.numHit[index1] + 1
		#mole.numHit[index2] = mole.numHit[index2] + 1
		e_inter = (mole.PE[index1] + mole.PE[index2] + mole.KE1[index1] + mole.KE1[index2]) - (pe1 + pe2)
		mole.KE1.append(e_inter * gamma4)
		mole.KE1.append(e_inter * (1-gamma4))
		if (e_inter>=0):
			#mole.moleculeTable[index1] = newMol1
			#mole.moleculeTable[index2] = newMol2

			#mole.moleculeTable.append(newMol1)
			#mole.moleculeTable.append(newMol2)



			#mole.PE[index1] = pe1
			#mole.PE[index2] = pe2

			#mole.KE1[index1] = e_inter * gamma4
			#mole.KE1[index2] = e_inter * (1 - gamma4)
			'''
Exemplo n.º 20
0
MEANING = [{"low": 0., "high": 0.}, {"none": 0., "some": 0., "every": 0.}]

FUZZY_VARS = [
    FuzzyVar(["low", "high"], {
        "low": lambda x: 20 - x**3 / 2,
        "high": lambda x: x**3 / 5.
    }),
    FuzzyVar(
        ["none", "some", "every"], {
            "none": lambda x: 1. if x <= 0. else 0.,
            "some": lambda x: cos(x * pi) * sin(x * pi),
            "every": lambda x: 1. if x == 1. else 0.
        })
]

OP = Operators(0.5, 0.5, 0.5)


def calculate_base_meaning(meaning_list: List[Dict[str, float]]) -> NoReturn:
    for idx, var in enumerate(FUZZY_VARS):
        for name in var.values:
            meaning_list[idx][name] = var.get_meaning(name, BASE_VALUES[idx])


calculate_base_meaning(MEANING)
# print(MEANING)

A = VAR_DICT["A"]
B = VAR_DICT["B"]

FUZZY_RULES = [
Exemplo n.º 21
0
    def __init__(self, param, grid):

        self.list_param = [
            'forcing', 'noslip', 'timestepping', 'alphaT', 'betaS',
            'diffusion', 'Kdiff', 'myrank', 'forcing_module', 'gravity',
            'isisland', 'customized', 'custom_module', 'additional_tracer'
        ]
        param.copy(self, self.list_param)

        # for potential energy
        self.list_param = ['xr', 'yr', 'nh', 'Lx', 'msk', 'area', 'mpitools']
        grid.copy(self, self.list_param)

        # for variables
        param.varname_list = [
            'vorticity', 'psi', 'u', 'v', 'density', 'danom', 'T', 'S'
        ]
        param.tracer_list = ['vorticity', 'T', 'S']
        param.whosetspsi = ('vorticity')

        if hasattr(self, 'additional_tracer'):
            for k in range(len(self.additional_tracer)):
                trac = self.additional_tracer[k]
                param.varname_list.append(trac)
                param.tracer_list.append(trac)

        self.varname_list = param.varname_list

        param.sizevar = [grid.nyl, grid.nxl]
        self.var = Var(param)
        dref = self.var.get('density').copy()
        self.dref = dref
        self.source = np.zeros(param.sizevar)

        # for operators
        self.ope = Operators(param, grid)

        # for timescheme
        self.tscheme = Timescheme(param, self.var.state)
        self.tscheme.set(self.dynamics, self.timestepping)

        if self.forcing:
            if self.forcing_module == 'embedded':
                print(
                    'Warning: check that you have indeed added the forcing to the model'
                )
                print('Right below the line    : model = f2d.model')
                print(
                    'you should have the line: model.forc = Forcing(param, grid)'
                )

                pass
            else:
                try:
                    f = import_module(self.forcing_module)

                except ImportError:
                    print('module %s for forcing cannot be found' %
                          self.forcing_module)
                    print('make sure file **%s.py** exists' %
                          self.forcing_module)
                    sys.exit(0)

                self.forc = f.Forcing(param, grid)

        self.diags = {}

        if self.customized:
            try:
                f = import_module(self.custom_module)
                print(f)
                self.extrastep = f.Step(param, grid)
            except ImportError:
                print('module %s for forcing cannot be found' %
                      self.custom_module)
                print('make sure file **%s.py** exists' % self.custom_module)
                exit(0)
Exemplo n.º 22
0
    def __init__(self, param, grid):

        self.list_param = [
            'forcing', 'noslip', 'timestepping', 'diffusion', 'Kdiff',
            'myrank', 'forcing_module', 'gravity', 'isisland', 'customized',
            'custom_module', 'additional_tracer'
        ]
        param.copy(self, self.list_param)

        # for potential energy
        self.list_param = ['xr', 'yr', 'nh', 'Lx', 'msk', 'area', 'mpitools']
        grid.copy(self, self.list_param)

        # for variables
        param.varname_list = [
            'vorticity', 'psi', 'u', 'v', 'buoyancy', 'banom'
        ]
        param.tracer_list = ['vorticity', 'buoyancy']
        param.whosetspsi = ('vorticity')

        if hasattr(self, 'additional_tracer'):
            for k in range(len(self.additional_tracer)):
                trac = self.additional_tracer[k]
                param.varname_list.append(trac)
                param.tracer_list.append(trac)

        param.sizevar = [grid.nyl, grid.nxl]
        self.var = Var(param)
        bref = self.var.get('buoyancy').copy()
        self.bref = bref
        self.source = np.zeros(param.sizevar)

        # for operators
        self.ope = Operators(param, grid)

        # for timescheme
        self.tscheme = Timescheme(param, self.var.state)
        self.tscheme.set(self.dynamics, self.timestepping)

        if self.forcing:
            if self.forcing_module == 'embedded':
                self.msg_forcing = (
                    'To make Fluid2d aware of your embedded forcing\n' +
                    'you need to add in the user script \n' +
                    'model.forc = Forcing(param, grid)\n' +
                    'right below the line: model = f2d.model')

                pass
            else:
                try:
                    f = import_module(self.forcing_module)
                except ImportError:
                    print('module %s for forcing cannot be found' %
                          self.forcing_module)
                    print('make sure file **%s.py** exists' %
                          self.forcing_module)
                    exit(0)
                self.forc = f.Forcing(param, grid)

        self.diags = {}

        if self.customized:
            try:
                f = import_module(self.custom_module)
                print(f)
                self.extrastep = f.Step(param, grid)
            except ImportError:
                print('module %s for forcing cannot be found' %
                      self.custom_module)
                print('make sure file **%s.py** exists' % self.custom_module)
                exit(0)
Exemplo n.º 23
0
    def __init__(self, param, grid):
        self.list_param = [
            'forcing', 'diffusion', 'Kdiff', 'timestepping', 'ageostrophic',
            'forcing_module', 'geometry'
        ]
        param.copy(self, self.list_param)

        # for diagnostics
        self.list_param = ['yr', 'nh', 'msk', 'area', 'mpitools']
        grid.copy(self, self.list_param)
        assert grid.geometry == "perio", "SQG imposes a biperiodic domain"

        assert param.ageostrophic == False, "Ageostrophic velocity not yet tested"

        # for variables
        param.varname_list = ['pv', 'psi', 'u', 'v', 'vorticity']

        if param.ageostrophic:
            # TODO: not yet tested for SQG
            param.varname_list += ['ua', 'va']

        param.sizevar = [grid.nyl, grid.nxl]
        self.var = Var(param)
        self.source = np.zeros(param.sizevar)

        self.ipv = self.var.varname_list.index('pv')
        self.ivor = self.var.varname_list.index('vorticity')
        self.ipsi = self.var.varname_list.index('psi')

        # for operators
        param.tracer_list = ['pv']

        if param.ageostrophic:
            param.tracer_list += ['ua', 'va']

        param.whosetspsi = ('pv')
        param.sqgoperator = True
        self.ope = Operators(param, grid)

        # for timescheme
        self.tscheme = Timescheme(param, self.var.state)
        self.dx0 = self.tscheme.dx0

        self.kt = 0

        if self.forcing:
            if self.forcing_module == 'embedded':
                print(
                    'Warning: check that you have indeed added the forcing to the model'
                )
                print('Right below the line    : model = f2d.model')
                print(
                    'you should have the line: model.forc = Forcing(param, grid)'
                )

                pass
            else:
                try:
                    f = import_module(self.forcing_module)

                except ImportError:
                    print('module %s for forcing cannot be found' %
                          self.forcing_module)
                    print('make sure file **%s.py** exists' %
                          self.forcing_module)
                    sys.exit(0)

                self.forc = f.Forcing(param, grid)

        self.diags = {}

        self.tscheme.set(self.dynamics, self.timestepping)
Exemplo n.º 24
0
    def __init__(self, param, grid):

        self.list_param = [
            'forcing', 'noslip', 'timestepping', 'diffusion', 'Kdiff',
            'forcing_module', 'additional_tracer', 'enforce_momentum',
            'var_to_save', 'customized', 'custom_module', 'spongelayer'
        ]
        param.copy(self, self.list_param)

        # for diagnostics
        self.list_param = [
            'yr', 'nh', 'msk', 'area', 'mpitools', 'dx', 'xr', 'yr', 'r2',
            'x0', 'y0', 'x2', 'y2', 'isisland', 'Lx', 'ny'
        ]
        grid.copy(self, self.list_param)

        # for variables
        param.varname_list = ['vorticity', 'psi', 'u', 'v',
                              'source']  # ,'tauw','wshear']
        param.tracer_list = ['vorticity']
        param.whosetspsi = ('vorticity')

        if 'tauw' in self.var_to_save:
            param.varname_list.append('tauw')

        if 'wshear' in self.var_to_save:
            param.varname_list.append('wshear')

        if hasattr(self, 'additional_tracer'):
            for k in range(len(self.additional_tracer)):
                trac = self.additional_tracer[k]
                param.varname_list.append(trac)
                param.tracer_list.append(trac)

        param.sizevar = [grid.nyl, grid.nxl]
        self.var = Var(param)
        self.work = np.zeros(param.sizevar)

        # for timing the code
        self.timers = Timers(param)

        # for operators
        self.ope = Operators(param, grid)

        # for timescheme
        self.tscheme = Timescheme(param, self.var.state)
        self.tscheme.set(self.dynamics, self.timestepping)

        if self.forcing:
            if self.forcing_module == 'embedded':
                print(
                    'Warning: check that you have indeed added the forcing to the model'
                )
                print('Right below the line    : model = f2d.model')
                print(
                    'you should have the line: model.forc = Forcing(param, grid)'
                )

                pass
            else:
                try:
                    f = import_module(self.forcing_module)
                except ImportError:
                    print('module %s for forcing cannot be found' %
                          self.forcing_module)
                    print('make sure file **%s.py** exists' %
                          self.forcing_module)
                    exit(0)
                self.forc = f.Forcing(param, grid)

        if self.spongelayer:
            # sponge layer zone [0 = full sponge, 1 = no sponge]
            self.spongemsk = (1 - (1 + np.tanh(
                (self.xr - self.Lx) / 0.1)) * 0.5)

        self.diags = {}

        if self.customized:
            try:
                f = import_module(self.custom_module)
                self.extrastep = f.Step(param, grid)
            except ImportError:
                print('module %s for forcing cannot be found' %
                      self.custom_module)
                print('make sure file **%s.py** exists' % self.custom_module)
                exit(0)
Exemplo n.º 25
0
    def __init__(self, param, grid):
        self.list_param = ['forcing', 'diffusion', 'Kdiff', 'noslip',
                           'timestepping', 'beta', 'Rd', 'ageostrophic',
                           'bottom_torque',
                           'forcing_module']
        param.copy(self, self.list_param)

        # for diagnostics
        self.list_param = ['yr', 'nh', 'msk', 'area', 'mpitools',  'isisland']
        grid.copy(self, self.list_param)

        # for variables
        param.varname_list = ['pv', 'psi', 'u', 'v', 'pvanom', 'vorticity']

        if param.bottom_torque:
            param.varname_list += ['btorque']

        if param.ageostrophic:
            param.varname_list += ['ua', 'va']

        param.sizevar = [grid.nyl, grid.nxl]
        self.var = Var(param)
        self.source = np.zeros(param.sizevar)

        self.ipva = self.var.varname_list.index('pvanom')
        self.ipv = self.var.varname_list.index('pv')
        self.ivor = self.var.varname_list.index('vorticity')
        self.ipsi = self.var.varname_list.index('psi')

        # background pv
        self.pvback = self.beta*(grid.yr-grid.Ly*.5)*grid.msk

        # for operators
        param.tracer_list = ['pv']
        if param.bottom_torque:
            param.tracer_list += ['btorque']

        if param.ageostrophic:
            param.tracer_list += ['ua', 'va']

        param.whosetspsi = ('pvanom')
        param.qgoperator = True
        self.ope = Operators(param, grid)

        # for timescheme
        self.tscheme = Timescheme(param, self.var.state)
        self.dx0 = self.tscheme.dx0

        self.kt = 0

        if self.forcing:
            if self.forcing_module == 'embedded':
                print('Warning: check that you have indeed added the forcing to the model')
                print('Right below the line    : model = f2d.model')
                print('you should have the line: model.forc = Forcing(param, grid)')

                pass
            else:
                try:
                    f = import_module(self.forcing_module)

                except ImportError:
                    print('module %s for forcing cannot be found'
                          % self.forcing_module)
                    print('make sure file **%s.py** exists' % self.forcing_module)
                    sys.exit(0)

                self.forc = f.Forcing(param, grid)

        self.diags = {}

        self.tscheme.set(self.dynamics, self.timestepping)
Exemplo n.º 26
0
	def get_Q(self, u, v, w):
		''' compute Q = -1/2 * \nabla \dot N where N(u) = \nabla \dot (uu) '''
		Nx = self.para.Nx
		Ny = self.para.Ny
		Nz = self.para.Nz
		dx = self.para.dx
		dz = self.para.dz.reshape([-1,1])
		dy = self.para.dy.reshape([-1,1,1])
		hx = self.para.hx
		hz = self.para.hz.reshape([-1,1])
		hy = self.para.hy.reshape([-1,1,1])

		uu, vv, ww = (np.empty([Ny+1, Nz+1, Nx+1]) for _ in range(3))
		uv, vw, wu = (np.empty([Ny+1, Nz+1, Nx+1]) for _ in range(3))
		N1, N2, N3 = (np.zeros([Ny+1, Nz+1, Nx+1]) for _ in range(3))

		im, ic, ip = np.arange(Nx-1), np.arange(1,Nx), np.arange(2,Nx+1)
		km, kc, kp = np.arange(Nz-1), np.arange(1,Nz), np.arange(2,Nz+1)
		jm, jc, jp = np.arange(Ny-1), np.arange(1,Ny), np.arange(2,Ny+1)

		## compute 2nd order terms

		# normal terms on cell centers
		uu[:,:,ic]  = .25 * (u[:,:,ic] + u[:,:,ip])**2 # on cell centers
		ww[:,kc]    = .25 * (w[:,kc]   + w[:,kp]  )**2 # on cell centers
		vv[jc]      = .25 * (v[jc]     + v[jp]    )**2 # on cell centers
		# boundaries of normal terms
		uu[:,:,[0,-1]] = uu[:,:,[-2,1]] # periodic u boundary
		ww[:,[0,-1]]   = ww[:,[-2,1]]   # periodic w boundary
		vv[[0,-1]]     = (hy[1]/dy[1] * (v[1]-v[2]) + .5 * (v[1]+v[2]))**2, \
					 (hy[-1]/dy[-2] * (v[-1]-v[-2]) + .5 * (v[-1]+v[-2]))**2 # linear extrapolation of v
		# cross terms on edges
		uv[1:]      = .5/hy[1:] * (u[1:]    *dy[:-1] + u[:-1]    *dy[1:]) # on z-edges
		uv[:,:,1:] *= .5/hx[1:] * (v[:,:,1:]*dx[:-1] + v[:,:,:-1]*dx[1:])
		vw[:,1:]    = .5/hz[1:] * (v[:,1:]  *dz[:-1] + v[:,:-1]  *dz[1:]) # on x-edges
		vw[1:]     *= .5/hy[1:] * (w[1:]    *dy[:-1] + w[:-1]    *dy[1:])
		wu[:,:,1:]  = .5/hx[1:] * (w[:,:,1:]*dx[:-1] + w[:,:,:-1]*dx[1:]) # on y-edges
		wu[:,1:]   *= .5/hz[1:] * (u[:,1:]  *dz[:-1] + u[:,:-1]  *dz[1:])

		## compute the convection operator N(u) = \nabla \dot (uu)

		# 3 components of N on staggered grids
		N1[:,:,1:] += (uu[:,:,1:] - uu[:,:,:-1]) / hx[1:]
		N1[:,kc]   += (wu[:,kp]   - wu[:,kc]   ) / dz[kc]
		N1[jc]     += (uv[jp]     - uv[jc]     ) / dy[jc]

		N2[:,:,ic] += (uv[:,:,ip] - uv[:,:,ic]) / dx[ic]
		N2[:,kc]   += (vw[:,kp]   - vw[:,kc]  ) / dz[kc]
		N2[1:]     += (vv[1:]     - vv[:-1]   ) / hy[1:]

		N3[:,:,ic] += (wu[:,:,ip] - wu[:,:,ic]) / dx[ic]
		N3[:,1:]   += (ww[:,1:]   - ww[:,:-1] ) / hz[1:]
		N3[jc]     += (vw[jp]     - vw[jc]    ) / dy[jc]
		# boundaries of N
		# N1, N3 on yc[0] are automatically zero
		N1[:,[0,-1]]   = N1[:,[-2,1]]
		N2[:,[0,-1]]   = N2[:,[-2,1]]
		N2[:,:,[0,-1]] = N2[:,:,[-2,1]]
		N3[:,:,[0,-1]] = N3[:,:,[-2,1]]

		## Q = -1/2 * \nabla \dot N, the returned result's boundary not handled
		return -.5 * Operators(self.para).divergence(N1,N2,N3)
Exemplo n.º 27
0
    def __init__(self, param, grid):

        self.list_param = [
            'forcing', 'noslip', 'timestepping', 'diffusion', 'Kdiff',
            'myrank', 'forcing_module', 'gravity', 'isisland', 'customized',
            'custom_module', 'additional_tracer'
        ]
        param.copy(self, self.list_param)

        # for potential energy
        self.list_param = ['xr', 'yr', 'nh', 'Lx', 'msk', 'area', 'mpitools']
        grid.copy(self, self.list_param)

        # for variables
        param.varname_list = [
            'vorticity', 'psi', 'u', 'v', 'buoyancy', 'banom'
        ]
        param.tracer_list = ['vorticity', 'buoyancy']
        param.whosetspsi = ('vorticity')

        if hasattr(self, 'additional_tracer'):
            for k in range(len(self.additional_tracer)):
                trac = self.additional_tracer[k]
                param.varname_list.append(trac)
                param.tracer_list.append(trac)

        param.sizevar = [grid.nyl, grid.nxl]
        self.var = Var(param)
        bref = self.var.get('buoyancy').copy()
        self.bref = bref
        self.source = np.zeros(param.sizevar)

        # for operators
        self.ope = Operators(param, grid)

        # for timescheme
        self.tscheme = Timescheme(param, self.var.state)
        self.tscheme.set(self.dynamics, self.timestepping)

        if self.forcing:
            if hasattr(self, 'forcing_module'):
                f = import_module(self.forcing_module)
                self.forc = f.Forcing(param, grid)
            else:
                if self.myrank == 0:
                    print('-' * 50)
                    print('did not find an external forcing module')
                    print(
                        'make sure file you define a class Forcing() in your script'
                    )
                    print('and that you attach it.')
                    print(
                        'You should have the following line before f2d.loop()')
                    print('model.forc = Forcing(param, grid)')

        self.diags = {}

        if self.customized:
            try:
                f = import_module(self.custom_module)
                print(f)
                self.extrastep = f.Step(param, grid)
            except ImportError:
                print('module %s for forcing cannot be found' %
                      self.custom_module)
                print('make sure file **%s.py** exists' % self.custom_module)
                exit(0)