コード例 #1
0
def LocalRelaxation(adatoms, substrate_bins, around):
	'''
	Relaxes the deposited adatoms into the lowest energy position using a conjugate gradient algorithm.
	Performs an additional global relaxation is global forces are too large.
	
	adatoms: np.array(np.array[x, y]) - position of adatoms
	substrate_bins: list(list(np.array[x, y])) - bin'd position of substrate atoms
	around: np.array[x, y] - position around which to perform the relaxation
	
	returns: np.array(np.array[x, y]) - positions of relaxed adatoms
	'''
	
	nearby_indices = []
	relaxing_adatoms = []
	adatom_bins = Bins.PutInBins(adatoms)
	nearby_adatoms = Bins.NearbyAtoms(around[0], around[1], adatom_bins)
	nearby_indices = [list(Ds).index(0) for Ds in Periodic.Distances(nearby_adatoms, adatoms)]
	nearby_indices = sorted(nearby_indices, reverse=True)
	for i in nearby_indices:
		relaxing_adatoms.append(adatoms[2*i])
		relaxing_adatoms.append(adatoms[2*i+1])
		adatoms = np.delete(adatoms, 2*i)
		adatoms = np.delete(adatoms, 2*i)
	relaxing_adatoms = np.array(relaxing_adatoms)
	relaxing_adatoms = Relaxation(relaxing_adatoms, substrate_bins, scale=4)
	adatoms = np.append(adatoms, relaxing_adatoms)
	forces = Energy.AdatomAdatomForces(adatoms) + Energy.AdatomSubstrateForces(adatoms, substrate_bins)
	maxF = max([np.dot(forces[2*i:2*i+2], forces[2*i:2*i+2]) for i in range(len(forces))])
	if maxF > 1e-3:
		print 'global required'
		adatoms = Relaxation(adatoms, substrate_bins, scale=4, threshold=1e-4)
	return adatoms
コード例 #2
0
def PlotStresses(adatoms, substrate, substrate_bins):
	PlotAtoms(substrate, 'blue')
	Fs = Energy.AdatomAdatomForces(adatoms) + Energy.AdatomSubstrateForces(adatoms, substrate_bins)
	Fs = [np.sqrt(Fs[2*i]**2 + Fs[2*i+1]**2) for i in range(len(Fs)/2)]
	Fs = [np.log(f*1e4) for f in Fs]
	Fs = ['#e7%.2x%.2x'%(max(0, min(255, f*8+79)), max(0, min(255, f*8+53))) for f in Fs]
	
	for i in range(len(Fs)):
		PlotAtoms(adatoms[2*i:2*i+2], Fs[i])
	plt.axis([-gv.L/2, gv.L/2, gv.Dmin, gv.Dmax])
コード例 #3
0
def dotest(query, bufferingFactor, measurementsActiveAgendaLoops,
           measurementsIgnoreIn, measurementsRemoveOperators,
           measurementsThinOperators, measurementsMultiAcquire,
           removeUnrequiredOperators):
    global outputPath

    testName = runDir(bufferingFactor, measurementsActiveAgendaLoops,
                      measurementsIgnoreIn, measurementsRemoveOperators,
                      measurementsThinOperators, measurementsMultiAcquire,
                      removeUnrequiredOperators)
    outputPath = optOutputRoot + testName + "/"
    report("DoTest to: " + outputPath)

    if optCompileQuery:
        queryDir = outputPath + "/" + str(query)
        report("Running: " + queryDir)
        if os.path.isdir(queryDir):
            if not (SneeqlLib.optDeleteOldFiles):
                report("Reusing " + queryDir)
                copyFiles(queryDir, measurementsActiveAgendaLoops)
                return
        outputPath = compileInput(
            outputPath, query, bufferingFactor, measurementsActiveAgendaLoops,
            measurementsIgnoreIn, measurementsRemoveOperators,
            measurementsThinOperators, measurementsMultiAcquire,
            removeUnrequiredOperators)
    else:
        copyInput(outputPath)

    report("Outpath = " + outputPath)

    if (optCompileNesc):
        exitVal = AvroraLib.compileNesCCode(outputPath)
        if (exitVal != 0):
            return
        AvroraLib.generateODs(outputPath)
        print "complied"
    else:
        print 'reusing existing Nesc and od files'

    numNodes = getMaxMote(outputPath)
    desc = "test"
    #run avrora simulation
    (avroraOutputFile, traceFilePath) = AvroraLib.runSimulation(
        outputPath,
        outputPath,
        desc,
        numNodes,
        simulationDuration=optSimulationDuration,
        networkFilePath=optAvroraNetworkFile)

    getLedTimes(avroraOutputFile, numNodes)
    getLedStates(avroraOutputFile, numNodes)
    Energy.getEnergy(outputPath)
    copyFiles(queryDir, measurementsActiveAgendaLoops)
コード例 #4
0
def doTest():
    mainPath = optOutputRoot + "/" + optMeasurementDir + "/"

    if SneeqlLib.optQuery != None:
        SneeqlLib.compileQuery("AvroraSim",
                               targets="Avrora1",
                               outputRootDir=mainPath)
        queryParts = SneeqlLib.optQuery.split("/")
        query = queryParts[len(queryParts) - 1]
        codePath = mainPath + "/" + query + "/avrora1/"
    else:
        copyInput(mainPath)
        codePath = mainPath + "/avrora1/"
    #Use this to get many durations in one run.
    #multiplyNCFiles(codePath, range(0, 1))

    report("codePath = " + codePath)

    exitVal = AvroraLib.compileNesCCode(codePath)
    if (exitVal != 0):
        return
    AvroraLib.generateODs(codePath)
    print "complied"

    numNodes = getMaxMote(codePath)
    desc = "test"

    #Multiple loops of same code
    openSummarises()
    for i in range(0, 2):
        outputDir = mainPath + "/run" + str(i)
        if not os.path.isdir(outputDir):
            os.makedirs(outputDir)

        #run avrora simulation
        (avroraOutputFile, traceFilePath) = AvroraLib.runSimulation(
            codePath,
            outputDir,
            desc,
            numNodes,
            simulationDuration=optSimulationDuration,
            networkFilePath=optAvroraNetworkFile)

        getLedTimes(avroraOutputFile, numNodes)
        getLedStates(avroraOutputFile, numNodes)
        Energy.getEnergy(outputDir)
        copyFiles(outputDir, i)
    closeFiles()
コード例 #5
0
ファイル: Ammonia.py プロジェクト: julenAlbi/Morphokinetics
 def __init__(self):
     self.aPlot = AmmoniaPlot.AmmoniaPlot()
     self.energy = Energy.Energy()
     self.info = inf.Info()
     self.total = False
     self.sp = False
     self.rAndM = False
     self.omegas = False
     self.sensibility = False
     self.tofSensibility = False
     self.kindOfSensibility = False
     self.lmbdas = False
     self.one = False
     self.ext = ""
     self.labelAlfa = [
         r"P1  $V \rightarrow NH_3$",  # P1
         r"P2  $NH_3 \rightarrow V$",  # P2
         r"P3  $2V + O_2(g) \rightarrow 2O$",  # P3
         r"P4  $2O \rightarrow 2V + O_2(g)$",  # P4
         r"P5  $NH_3 + O \rightarrow NH_2 + OH$",  # P5
         r"P6  $NH_2 + OH \rightarrow NH + H_2O(g)$",  # P6
         r"P7  $NH + OH \rightarrow N + H_2O(g)$",  # P7
         r"P8  $NH + O \rightarrow N + OH$",  # P8
         r"P9  $N + O \rightarrow NO + V$",  # P9   TOF
         r"P10$N + N \rightarrow N_2(g)$",  # P10  TOF
         r"P11$NO \rightarrow V$",  # P11
         r"P12$N \rightarrow N$",  # P12
         r"P13$O \rightarrow O$",  # P13
         r"P14$OH \rightarrow OH$",  # P14
         r"P15$NH_2 + O \rightarrow NH + OH$",  # P15
         r"P16$NH + OH \rightarrow NH_2 + O$",  # P16
         r"P17$NH_2 + OH \rightarrow NH_3 + O$",  # P17
         r"P18$N + OH \rightarrow NH + O$"
     ]  # P18
コード例 #6
0
    async def server(self, websocket, path):
        req = await websocket.recv()

        req = json.loads(req)

        if req['msg'] == 'method':
            if req['method'] == 'getHistory':
                h = History.History('/home/pi/OS/HistoryDB.json')
                res = {'msg': 'result', 'result': h.get()}
                await websocket.send(json.dumps(res))
            if req['method'] == 'getEnergy':
                e = Energy.Energy('/home/pi/OS/EnergyDB.json')
                if not req['params']:
                    res = {'msg': 'result', 'result': e.get()}
                else:
                    resultArray = []
                    params = req['params']
                    if len(params) > 0:
                        for p in params:
                            resultArray.append(e.get(p))
                    res = {'msg': 'result', 'result': resultArray}
                await websocket.send(json.dumps(res))
            else:
                res = {
                    'msg': 'error',
                    'error': 'unrecognized request',
                    'code': 501
                }
                await websocket.send(json.dumps(res))
        print("sent response")
コード例 #7
0
def HopAtom(i, adatoms, substrate_bins):
	'''
	Moves a surface adatom and to a nearby spot. Performs a local relaxation around the new position.
	
	i: int - index of adatom to hop
	adatoms: np.array(np.array[x, y]) - position of adatoms
	substrate_bins: list(list(np.array[x, y])) - bin'd position of substrate atoms
	
	returns: np.array(np.array[x, y]) - positions of relaxed adatoms after hop
	'''
	surf = SurfaceAtoms(adatoms, substrate_bins)
	jumper = np.array(adatoms[2*i:2*i+2])
	adatoms = np.delete(adatoms, 2*i); adatoms = np.delete(adatoms, 2*i)
	Ds = Periodic.Distances(jumper, surf)[0]
	potential_jump_to = []
	for i in range(len(Ds)):
		if Ds[i] < 3*gv.r_a:
			potential_jump_to.append(surf[2*i:2*i+2])
	
	jump_to_surf = potential_jump_to[random.randint(0, len(potential_jump_to)-1)]
	jump_directions = [i*np.pi/3 for i in range(6)]
	jump_vectors = [np.array([np.cos(t), np.sin(t)])*gv.r_a for t in jump_directions]
	jump_positions = [jump_to_surf + v for v in jump_vectors]
	jump_energies = [Energy.HoppingEnergy(p, adatoms, substrate_bins) for p in jump_positions]
	jump_to_pos = jump_positions[jump_energies.index(min(jump_energies))]
	jump_to_pos = Periodic.PutAllInBox(jump_to_pos)
	adatoms = np.append(adatoms, jump_to_pos)
	adatoms = Relaxation(adatoms, substrate_bins)
	return adatoms
コード例 #8
0
def fit_grafico(ind, ob, angle_in, nk):
    global Masa
    distancia = np.sqrt(fitDistance(ind[-1, :], ob))
    Energia = Energy.fitness(ind)
    #res+=np.sum(np.abs(angle_in-ind[0,:]))
    #print("funcion de diferencia final {}".format(res))
    #print("Suma de errores {}".format(res2))
    return distancia, Energia
コード例 #9
0
def HoppingRates(adatoms, substrate_bins):
	'''
	Calculates the hopping rate of each surface adatom.
	
	adatoms: np.array(np.array[x, y]) - position of adatoms
	substrate_bins: list(list(np.array[x, y])) - bin'd position of substrate atoms
	
	returns: list(float) - hopping rate of each surface atom
	'''
	omega = 1.0e12
	surf = SurfaceAtoms(adatoms, substrate_bins)
	if len(surf) < 1:
		return []
	surf_indices = [list(Ds).index(0) for Ds in Periodic.Distances(surf, adatoms)]
	return [omega*np.exp(Energy.DeltaU(i, adatoms, substrate_bins)*gv.beta) for i in surf_indices]
コード例 #10
0
def fitPar(pop, ob, angle_in, nk, fit, fDistancia, fEnergia):
    global Masa, phi, sigma
    popsize = pop.shape[0]
    distancia = np.zeros(popsize)
    energia = np.zeros(popsize)
    for j in range(popsize):
        energia[j] = Energy.fitness(pop[j])
        #print(energia[j])
        distancia[j] = fitDistance(pop[j][-1, :], ob)
    Emin = np.min(energia)
    Emean = np.mean(energia)
    logPhi = np.log(phi)
    fEnergia[:] = np.exp((logPhi / (Emean - Emin)) * (energia - Emin))
    fDistancia[:] = np.exp(sigma * distancia)
    fit[:] = fDistancia * (1 + fEnergia)
コード例 #11
0
ファイル: Info.py プロジェクト: julenAlbi/Morphokinetics
 def setParams(self):##, fileName=self.refFile):
     data = self.getInformationFromFile(self.refFile)
     self.r_tt = data[0] # terrace to terrace rate
     self.temp = data[1] # temperature
     self.flux = data[2] # flux
     self.calc = data[3] # calculation mode: basic, AgUc ..
     self.rLib = data[4]
     self.sizI = data[5] # simulation size I
     self.sizJ = data[6] # simulation size J
     self.maxN = 4       # max number of neighbour or atom types
     self.maxA = 18      # max alfa: possible transition types (i.e. different energies)
     self.maxC = data[7] # max simulated coverage
     self.nCo2 = data[8] # created CO2 molecules. For catalysis
     self.prCO = data[9] # pressure. For catalysis
     self.prO2 = data[10] # pressure. For catalysis
     self.mCov = -1       # max coverage to analyse, similar to nCo2.
     self.mMsr = -1       # place to gather p.mCov and p.nCo2
     self.minA = 0 # min alfa: possible transition types (i.e. different energies)
     self.corr = 1 # corrections for rates
     self.energies = Energy.Energy(self)
コード例 #12
0
ファイル: main.py プロジェクト: mjankowski-dev/svvproject
### Access to important results
"""" If you desire, you can manually overwrite these values. """
_ = crosssection.ysc  # y-coordinate of the centroid
_ = crosssection.zsc  # z-coordinate of the centroid
_ = crosssection.J  # torsional constant

######################## Part IV - Deflection calculations #######################################
### Definition of additional parameters
N = 20  # Number of basis functions to use in Rayleigh-Ritz method (total number of coefficients is 3*N)
E = 72.9 * 10**9  # E-modulus (Pa)
G = 27.1 * 10**9  # G-modulus (Pa)

### Create the aileron object
""" Merges the cross-sectional properties with the spanwise properties (length and material properties)"""
aileron = Energy.Beam(la, crosssection, N, E, G)
"""Define your boundary conditions; see manual for explanations. The shown boundary conditions are the boundary
conditions for the aileron as described in the assignment."""
aileron.addbcss(x1, 0., -ha / 2., -theta, d1)
aileron.addbcss(x1, 0., -ha / 2., m.pi / 2 - theta, 0)
aileron.addbcss(x2, 0., -ha / 2., 0, 0)
aileron.addbcss(x2, 0., -ha / 2., m.pi / 2, 0.)
aileron.addbcss(x3, 0., -ha / 2., -theta, d3)
aileron.addbcss(x3, 0., -ha / 2., m.pi / 2 - theta, 0)
aileron.addbcss(x2 - xa / 2., ha / 2., 0, m.pi / 2. - theta, 0)
""""Define your applied loading; see manual for explanations."""
aileron.addfpl(x2 + xa / 2., ha / 2., 0, m.pi / 2. - theta, P)

### Primary functions
""" The following line computes the deflections. If you do not want to include the aerodynamic loading, simply write
aileron.compute_deflections(). Note that the aerodynamic loading significantly slows down the program.
コード例 #13
0
    def run(self):
        #train_op = tf.train.MomentumOptimizer(.01,.001,use_nesterov=True).minimize(self.loss)
        start = time.time()
        if self.method is not None:
            optimizer = tf.contrib.opt.ScipyOptimizerInterface(
                loss=self.loss, method=self.method, options={'gtol': 1e-08})
            tf.global_variables_initializer().run(session=self.sess)
            optimizer.minimize(self.sess,
                               feed_dict={
                                   self.inputx: self.xx,
                                   self.inputy: self.yy
                               })
        else:
            lr = .01
            learning_rate_placeholder = tf.placeholder(tf.float32, [],
                                                       name='learning_rate')

            train_op = tf.train.AdamOptimizer(
                learning_rate=learning_rate_placeholder).minimize(self.loss)
            tf.global_variables_initializer().run(session=self.sess)
            E0 = 1
            E1 = 999999
            itr = 0
            switched = False

            while abs(E0 - E1) / abs(E0) > self.cutoff and itr < self.maxitr:

                print('Iteration: ', itr)
                self.sess.run(train_op,
                              feed_dict={
                                  self.inputx: self.xx,
                                  self.inputy: self.yy,
                                  learning_rate_placeholder: lr
                              })
                #loss = self.sess.run(self.loss,feed_dict={self.inputx: self.xx,self.inputy: self.yy})
                E = self.sess.run(self.E,
                                  feed_dict={
                                      self.inputx: self.xx,
                                      self.inputy: self.yy
                                  })

                self.Elist.append(E[0][0])
                #print('E',E[0][0])
                #print('loss: ', loss[0][0])
                E0 = E1
                E1 = E[0][0]

                if E1 > E0 and itr > 300:
                    lr = lr * .99
                itr += 1
                if E1 < 0:
                    break
        print('LR_final: ', lr)
        end = time.time()
        print('time: ', str(end - start))
        psiL = []
        centers = []
        thetas = []
        psiL.append(
            self.sess.run(en.nnOut(self.inputx, self.inputy, self.W0, self.C0,
                                   self.T0, self.A0, self.activation,
                                   self.Nstates, self.HLS),
                          feed_dict={
                              self.inputx: self.xx,
                              self.inputy: self.yy
                          }))
        psiL.append(
            self.sess.run(en.nnOut(self.inputx, self.inputy, self.W1, self.C1,
                                   self.T1, self.A1, self.activation,
                                   self.Nstates, self.HLS),
                          feed_dict={
                              self.inputx: self.xx,
                              self.inputy: self.yy
                          }))
        centers = [
            self.C0.eval(session=self.sess),
            self.C1.eval(session=self.sess)
        ]
        thetas = [
            self.T0.eval(session=self.sess),
            self.T1.eval(session=self.sess)
        ]
        print('Loss final: ', self.Elist[-1])
        w = [self.W0.eval(session=self.sess), self.W1.eval(session=self.sess)]
        Vxy = self.Vfun(self.xo, self.yo)
        print(self.Vfun(1, 1))
        np.savez('Tests/' + self.testname + '/' + self.subtestname + '/' +
                 self.subtestname,
                 dim=self.plotdim,
                 x=self.xo,
                 y=self.yo,
                 w=w,
                 centers=centers,
                 thetas=thetas,
                 psiL=psiL,
                 V=Vxy,
                 Elist=self.Elist,
                 Efinal=self.Elist[-1],
                 dx=self.d,
                 params=self.params)
        self.sess.close()
コード例 #14
0
 def energy(self):
     return en.energy(self.inputx, self.inputy, self.inputkx, self.inputky,
                      self.V, self.d, self.P1, self.P2, self.gamma,
                      self.VintMap, self.RFW, self.IFW, self.params,
                      self.ydim, self.plotdim)
コード例 #15
0
    def __init__(self,
                 V,
                 VintMap,
                 gamma=.5,
                 params=[],
                 dim=256,
                 xlim=5,
                 maxitr=400,
                 cutoff=10**(-6),
                 hiddenlayersize=100,
                 activation=tf.nn.tanh,
                 method=None,
                 layers=((2048, 10), (10, 1024), (1024, 1024), (1024, 1)),
                 testname='test',
                 subtestname='subtest',
                 Nstates=1):
        self.cutoff = cutoff
        self.Elist = []
        self.HLS = hiddenlayersize
        self.testname = testname
        self.subtestname = subtestname
        print('Name: ' + subtestname)
        self.path = os.getcwd() + '/' + 'Tests' + '/' + self.testname
        if not os.path.exists(self.path):
            os.makedirs(self.path)
        self.path = self.path + '/' + self.subtestname
        if os.path.exists(self.path):
            sh.rmtree(self.path)
            os.makedirs(self.path)
        else:
            os.makedirs(self.path)
        self.activation = activation
        tf.set_random_seed(np.random.randint(1000))
        self.maxitr = maxitr
        self.method = method
        self.config = tf.ConfigProto(log_device_placement=False)

        self.config.intra_op_parallelism_threads = 16
        self.config.inter_op_parallelism_threads = 16
        self.sess = tf.Session(config=self.config)
        self.plotdim = dim
        self.ydim = int(np.square(dim))
        self.Vfun = V
        self.xlim = xlim
        self.x = np.linspace(-xlim, xlim, self.plotdim)
        self.d = self.x[1] - self.x[0]
        self.dk = 1 / self.x.shape[0] / self.d
        self.y = np.linspace(-xlim, xlim, self.plotdim)
        self.kx = np.linspace(-self.x.shape[0] / 2, self.x.shape[0] / 2 - 1,
                              self.plotdim) * 2 * np.pi * self.dk
        self.ky = np.linspace(-self.y.shape[0] / 2, self.y.shape[0] / 2 - 1,
                              self.plotdim) * 2 * np.pi * self.dk
        self.xx, self.yy = np.meshgrid(self.x, self.y)
        self.kxx, self.kyy = np.meshgrid(self.kx, self.ky)
        self.Nstates = Nstates
        self.V = V(self.xx, self.yy)
        self.VintMap = {}
        for Vkey in VintMap.keys():
            tmp = VintMap[Vkey](self.xx, self.yy) * en.G(
                np.sqrt((self.kxx**2 + self.kyy**2) / 2.0))

            self.VintMap[Vkey] = [
                tf.constant(np.real(tmp.reshape(self.ydim, 1)),
                            dtype=tf.float32),
                tf.constant(np.imag(tmp.reshape(self.ydim, 1)),
                            dtype=tf.float32)
            ]

        self.xo = 1 * self.xx
        self.yo = 1 * self.yy
        self.xx = np.tile(self.xx.reshape(self.ydim, 1), (self.HLS, 1, 1))
        self.yy = np.tile(self.yy.reshape(self.ydim, 1), (self.HLS, 1, 1))
        #self.xx = self.xx.reshape(self.ydim,1)
        #self.yy = self.yy.reshape(self.ydim,1)
        self.V = tf.constant(self.V.reshape(self.ydim, 1), dtype=tf.float32)
        self.V = [self.V, tf.zeros([self.ydim, 1], tf.float32)]

        self.inputkx = tf.constant(self.kxx.reshape(self.ydim, 1),
                                   dtype=tf.float32)

        self.inputky = tf.constant(self.kyy.reshape(self.ydim, 1),
                                   dtype=tf.float32)

        self.RFW, self.IFW = en.makeFourierMatrices(dim)
        self.RFW = [
            tf.constant(np.real(self.RFW), dtype=tf.float32),
            tf.constant(np.imag(self.RFW), dtype=tf.float32)
        ]

        self.IFW = [
            tf.constant(np.real(self.IFW), dtype=tf.float32),
            tf.constant(np.imag(self.IFW), dtype=tf.float32)
        ]

        self.inputx = tf.placeholder(tf.float32,
                                     shape=[self.HLS, self.ydim, 1])
        self.inputy = tf.placeholder(tf.float32,
                                     shape=[self.HLS, self.ydim, 1])
        self.gamma = gamma
        initializer = tf.random_uniform_initializer
        self.C0 = tf.get_variable(subtestname + 'C0',
                                  shape=[self.HLS, 1, 2],
                                  initializer=initializer())
        self.C1 = tf.get_variable(subtestname + 'C1',
                                  shape=[self.HLS, 1, 2],
                                  initializer=initializer())
        self.T0 = tf.get_variable(subtestname + 'T0',
                                  shape=[self.HLS, 1],
                                  initializer=initializer())
        self.T1 = tf.get_variable(subtestname + 'T1',
                                  shape=[self.HLS, 1],
                                  initializer=initializer())
        self.A0 = tf.get_variable(subtestname + 'A0',
                                  shape=[self.HLS, 1, 2],
                                  initializer=initializer())
        self.A1 = tf.get_variable(subtestname + 'A1',
                                  shape=[self.HLS, 1, 2],
                                  initializer=initializer())
        self.W0 = tf.get_variable(subtestname + 'W0',
                                  shape=[self.HLS, 2, 2],
                                  initializer=initializer())
        self.W1 = tf.get_variable(subtestname + 'W1',
                                  shape=[self.HLS, 2, 2],
                                  initializer=initializer())
        self.activtion = activation
        self.P1 = [
            self.W0, self.C0, self.T0, self.A0, self.activation, self.Nstates,
            self.HLS
        ]
        self.P2 = [
            self.W1, self.C1, self.T1, self.A1, self.activation, self.Nstates,
            self.HLS
        ]
        self.params = params
        self.E = self.energy()

        self.loss = self.E[0]
コード例 #16
0
def Relaxation(adatoms, substrate_bins, scale=16, threshold=1e-4):
	'''
	Relaxes the deposited adatoms into the lowest energy position using a conjugate gradient algorithm.
	Runs recursively if the step size is too small.
	Uses a multiprocessing pool for extra speed.
	
	adatoms: np.array(np.array[x, y]) - position of adatoms
	substrate_bins: list(list(np.array[x, y])) - bin'd position of substrate atoms
	scale: int - How much to scale the step size down by
	
	returns: np.array(np.array[x, y]) - position of adatoms with additional adatom
	'''
	global pool
	
	if scale > 1024:
		print 'scale exceeded, reducing threshold'
		return Relaxation(adatoms, substrate_bins, scale=16, threshold=threshold*10)
	
	# If the energy of a proposed relaxed arrangement exceeds this Ui, then halve the stepsize and start over.
	Ui = Energy.TotalEnergy(adatoms, substrate_bins)
	N = len(adatoms)/2
	xn = adatoms.copy()
	# Initial forces on each atom
	dx0 = Energy.AdatomAdatomForces(xn) + Energy.AdatomSubstrateForces(xn, substrate_bins)
	xs = [(adatoms + a*dx0/20/scale, substrate_bins) for a in range(20)]
	ys = pool.map(Energy.RelaxEnergy, xs)
	(xnp, a) = xs[ys.index(min(ys))]
	
	sn = dx0[:]
	snp = dx0[:]
	# Force on each atom in the lowest energy position
	dxnp = Energy.AdatomAdatomForces(xnp) + Energy.AdatomSubstrateForces(xnp, substrate_bins)
	maxF = max([np.dot(dxnp[2*i:2*i+2], dxnp[2*i:2*i+2]) for i in range(len(dxnp))])
	lastmaxF = maxF
	while maxF > threshold:
		# U = Energy.TotalEnergy(adatoms, substrate_bins)
		# if U > Ui:
			# print 'changing scale', scale*2, maxF
			# return Relaxation(adatoms, substrate_bins, scale=scale*2, threshold=threshold)
		
		max_y = min([xnp[2*i+1] for i in range(len(xnp)/2)])
		if max_y > gv.Dmax:
			print 'atom out of bounds', scale*2
			return Relaxation(adatoms, substrate_bins, scale=scale*2, threshold=threshold)
		
		# Calculate the conjugate direction step size, beta
		top = np.dot(xnp, (xnp - xn))
		bot = np.dot(xn, xn)
		beta = top/bot
		# Update conjugate direction
		snp = dxnp + beta*sn
		
		xn = xnp.copy()
		sn = snp.copy()
		
		xs = [(xn + a*sn/20/scale, substrate_bins) for a in range(20)]
		ys = pool.map(Energy.RelaxEnergy, xs)
		# plt.plot(ys); plt.show()
		(xmin, a) = xs[ys.index(min(ys))]
		xnp = xmin.copy()
		
		# Calculate forces at new lowest energy position
		dxnp = Energy.AdatomAdatomForces(xmin) + Energy.AdatomSubstrateForces(xmin, substrate_bins)
		maxF = max([np.dot(dxnp[2*i:2*i+2], dxnp[2*i:2*i+2]) for i in range(len(dxnp))])
		print maxF
		if abs(lastmaxF - maxF) < 1e-8:
			print 'relaxation stalled, changing scale', scale*2, maxF
			return Relaxation(adatoms, substrate_bins, scale=scale*2, threshold=threshold)
		lastmaxF = maxF
	return Periodic.PutAllInBox(xnp)
コード例 #17
0
	Kpts=np.linspace(-np.pi,0)

	#Kgamma_X2=np.array([ [np.linspace(0,0)], [np.linspace(4*np.pi,2*np.pi)],[np.linspace(0,0) ]])
	#Kgamma_X2pts=np.linspace(0, 2*np.pi)


	#Kgamma_L= np.array([ [np.linspace(-1*np.pi,0)], [np.linspace(-1*np.pi,0)],[np.linspace(-(1)*np.pi,0)] ])
	#Kgamma_Lpts=np.linspace(-np.pi,0)

	#Kgamma_L2=np.array([ [np.linspace(-2*np.pi,-np.pi)], [np.linspace(-2*np.pi,-np.pi)],[np.linspace(-2*np.pi,-np.pi) ]])
	#Kgamma_L2pts=np.linspace(0, -np.pi)

	#Kgamma_U= np.array([ [np.linspace(0,0.5*np.pi)], [np.linspace(2*np.pi,2*np.pi)],[np.linspace(0,0.5*np.pi)] ])
	#Kgamma_Upts=np.linspace(2*np.pi,3*np.pi)

	Energy=np.array(nrg.nrg(plv,K,i[0][0],i[0][1],i[0][2]))
	#	nrg.nrg(plv,Kgamma_X2,i[0],i[1],i[2]) \
	#	, nrg.nrg(plv,Kgamma_L,i[0],i[1],i[2]),nrg.nrg(plv,Kgamma_L2,i[0],i[1],i[2]) \
	#	, nrg.nrg(plv,Kgamma_U,i[0],i[1],i[2])]) 
	

	plotWidget.plot(Kpts, Energy,pen=(1,1))
	#plotWidget.plot(Kgamma_X2pts, Energy[1],pen=(1,3))
	#plotWidget.plot(Kgamma_Lpts, Energy[2],pen=(2,3))
	#plotWidget.plot(Kgamma_L2pts, Energy[3],pen=(2,3))
	#plotWidget.plot(Kgamma_Upts, Energy[4],pen=(3,3))




pg.QtGui.QApplication.exec_()
コード例 #18
0
    point = sys.argv[1].split(',')
    angle = sys.argv[2].split(',')
    ob = np.array([float(i) for i in point])
    angle_in = np.array([float(i) for i in angle])
    angle_in = np.deg2rad(angle_in)
    print(ob)
    print(angle_in)
    nk = 50
    min_b, max_b = np.array(bounds).T
    l = list(
        cga(fitPar, ob, min_b, max_b, angle_in, nk=nk, its=10000,
            popsize=1000))
    print(l[-1])
    for i in range(100):
        energia = Energy.fitness(l[i][0])
        #print(energia)
    print(np.sqrt(fitDistance(l[-1][0][-1, :], ob)))

    plt.figure(1)
    plt.subplot(2, 2, 1)
    plt.plot(best_error_np)
    #plt.ylim([0,0.01])
    plt.ylim([0, 1.1])
    plt.title("Error")
    plt.ylabel("Error")

    plt.subplot(2, 2, 2)
    plt.plot(best_E_np)
    plt.ylim([-0.1, 300])
    plt.xlabel("pasos")
コード例 #19
0
def doTest(measurementsRemoveOperators):
    mainPath = optOutputRoot + "/" + SneeqlLib.optQuery + "/" + measurementsRemoveOperators + "/"
    if SneeqlLib.optQuery != None:
        SneeqlLib.compileQuery(
            "AvroraSim",
            targets="Avrora1",
            outputRootDir=mainPath,
            measurementsRemoveOperators=measurementsRemoveOperators)
        queryParts = SneeqlLib.optQuery.split("/")
        query = queryParts[len(queryParts) - 1]
        codePath = mainPath + "/" + query + "/avrora1/"
    else:
        copyInput(mainPath)
        codePath = mainPath + "/avrora1/"
    #Use this to get many durations in one run.
    #multiplyNCFiles(codePath, range(0, 1))

    report("codePath = " + codePath)

    exitVal = AvroraLib.compileNesCCode(codePath)
    if (exitVal != 0):
        return
    AvroraLib.generateODs(codePath)
    print "complied"

    numNodes = getMaxMote(codePath)
    desc = "test"

    #Multiple loops of same code
    openSummarises(mainPath)
    if optSimulationDurationList != None:
        queryEnergyFile.write(measurementsRemoveOperators + ",")
        queryYellowFile.write(measurementsRemoveOperators + ",")
        queryYellowMinFile.write(measurementsRemoveOperators + ",")
        queryGreenFile.write(measurementsRemoveOperators + ",")
        queryRedFile.write(measurementsRemoveOperators + ",")
        querySizeFile.write(measurementsRemoveOperators + "," +
                            str(AvroraLib.ram) + "," + str(AvroraLib.rom) +
                            "\n")
        for i in range(0, len(optSimulationDurationList)):
            outputDir = mainPath + "/duration" + str(
                optSimulationDurationList[i])
            if not os.path.isdir(outputDir):
                os.makedirs(outputDir)

            #run avrora simulation
            (avroraOutputFile, traceFilePath) = AvroraLib.runSimulation(
                codePath,
                outputDir,
                desc,
                numNodes,
                simulationDuration=optSimulationDurationList[i],
                networkFilePath=optAvroraNetworkFile)

            getLedTimes(avroraOutputFile, numNodes)
            getLedStates(avroraOutputFile, numNodes)
            Energy.getEnergy(outputDir)
            copyFiles(outputDir, i, "dur" + str(optSimulationDurationList[i]))
        queryEnergyFile.write("\n")
        queryRedFile.write("\n")
        queryYellowFile.write("\n")
        queryYellowMinFile.write("\n")
        queryGreenFile.write("\n")
    else:
        for i in range(0, 1):
            outputDir = mainPath + "/run" + str(i)
            if not os.path.isdir(outputDir):
                os.makedirs(outputDir)

            #run avrora simulation
            (avroraOutputFile, traceFilePath) = AvroraLib.runSimulation(
                codePath,
                outputDir,
                desc,
                numNodes,
                simulationDuration=optSimulationDuration,
                networkFilePath=optAvroraNetworkFile)

            getLedTimes(avroraOutputFile, numNodes)
            getLedStates(avroraOutputFile, numNodes)
            Energy.getEnergy(outputDir)
            copyFiles(outputDir, i, "Run " + str(i))
    closeFiles()