示例#1
0
def cvRun(gridLength, alloyFraction, dimensions, eList, T, localEam,
          nIterationsPerSim):
    grid = srf.initializeGrid(gridLength, alloyFraction, dimensions)
    grid, eList = srf.runSim(grid, eList, T, localEam, nIterationsPerSim,
                             gridLength, dimensions)
    currentOrderValue, actualList, binList = sref.getOrder(
        grid, alloyFraction, dimensions)
    return currentOrderValue
def cValidateTest(dimensions=2):
    gridLength, alloyFraction = 50, 50
    grid = srf.initializeGrid(gridLength, alloyFraction, dimensions)
    # xCase (+1)
    result = srf.cValidate(gridLength + 1, grid, gridLength, 'x', dimensions)
    if result != 0:
        print("cValidate does NOT work for x case")
    # xCase (-1)
    result = srf.cValidate(-1, grid, gridLength, 'x', dimensions)
    if result == 0:
        print(
            "ERROR: xCase - 1 doesn't work")  # i.e. would produce index error
示例#3
0
def createBarDistribution(gridLength=40,
                          alloyFraction=50,
                          nIterations=3000000,
                          Eam=0.1,
                          T=300,
                          dimensions=2):
    alloyGrid = srf.initializeGrid(gridLength, alloyFraction, dimensions)
    # Sets up list to take current system energy as simulation progresses
    energyList = [0] * (nIterations + 1)
    energyList[0] = sref.getTotalEnergy(alloyGrid, Eam, dimensions)

    alloyGrid, energyList = srf.runSim(alloyGrid, energyList, T, Eam,
                                       nIterations, gridLength, dimensions)

    randomMeasure2, actualList, binList = sref.getOrder(
        alloyGrid, alloyFraction, dimensions)

    trace1 = plotly.graph_objs.Bar(
        x=[str(i) for i in range(dimensions * 2 + 1)],
        y=actualList,
        name='actualDistribution')

    trace2 = plotly.graph_objs.Bar(
        x=[str(i) for i in range(dimensions * 2 + 1)],
        y=binList,
        name='binomialDistribution')

    data = [trace1, trace2]
    layout = plotly.graph_objs.Layout(
        barmode='group',
        xaxis=dict(title='No. of unlike neighbours',
                   titlefont=dict(family='Courier New, monospace',
                                  size=18,
                                  color='#7f7f7f')),
        yaxis=dict(title='Frequency',
                   titlefont=dict(family='Courier New, monospace',
                                  size=18,
                                  color='#7f7f7f')))

    fig = plotly.graph_objs.Figure(data=data, layout=layout)
    plotly.offline.plot(
        fig,
        filename="""barDistribution [gL={}, n={}, comp={}, Eam={},
		T={}, dimensions={}].html""".format(str(gridLength), str(nIterations),
                                      str(alloyFraction / 100.0), str(Eam),
                                      str(T), str(dimensions)).replace(
                                          '\n', '').replace('\t', ''))
示例#4
0
def orderVsCompVaryingEam(gridLength=40,
                          T=300,
                          nIterations=3000000,
                          eOptions=[-0.1, 0.0, 0.1],
                          compList=range(0, 101, 5),
                          dimensions=2,
                          numTimesToAvg=3,
                          multiProcess=True):
    """Plotting order vs composition, with varying Eam. Eam values are taken from
	eOptions, while composition values are taken from compList"""
    alloyGrid = srf.initializeGrid(gridLength, 50, dimensions)
    # Sets up list to take current system energy as simulation progresses
    energyList = [0] * (nIterations + 1)
    energyList[0] = sref.getTotalEnergy(alloyGrid, 0.1, dimensions)
    dataSet = []
    for i, j in enumerate(eOptions):
        rList = sif.compVary(energyList, compList, j, gridLength, T,
                             dimensions, numTimesToAvg, nIterations,
                             multiProcess)
        dataSet.append(rList)

    colourOptions = ['b', 'g', 'r', 'c', 'm', 'y', 'k'] * ceil(
        len(eOptions) / 7)
    fig, ax = pyplot.subplots()
    for i, j in enumerate(dataSet):
        ax.plot(compList,
                j,
                colourOptions[i],
                label='Eam = {} eV'.format(str(eOptions[i])))

    # Now add the legend with some customizations
    legend = ax.legend(loc='upper right', shadow=False)
    # The frame is matplotlib.patches.Rectangle instance surrounding the legend
    frame = legend.get_frame()
    frame.set_facecolor('white')
    # Set the fontsize
    for label in legend.get_texts():
        label.set_fontsize('large')
    for label in legend.get_lines():
        label.set_linewidth(1.5)  # the legend line width

    pyplot.xlabel('Composition (%% foreign atoms)')
    pyplot.ylabel('orderValue')
    pyplot.show()
示例#5
0
def orderVsComp(gridLength=40,
                T=300,
                nIterations=3000000,
                Eam=0.1,
                compList=range(0, 101, 5),
                dimensions=2,
                numTimesToAvg=3,
                multiProcess=True):
    """Plotting order vs composition"""
    alloyGrid = srf.initializeGrid(gridLength, 50, dimensions)
    # Sets up list to take current system energy as simulation progresses
    energyList = [0] * (nIterations + 1)
    energyList[0] = sref.getTotalEnergy(alloyGrid, Eam, dimensions)
    rList = sif.compVary(energyList, compList, Eam, gridLength, T, dimensions,
                         numTimesToAvg, nIterations, multiProcess)
    pyplot.plot(compList, rList)
    pyplot.xlabel('Composition (%% foreign atoms)')
    pyplot.ylabel('orderValue')
    pyplot.show()
示例#6
0
def orderVsTemp(gridLength=40,
                alloyFraction=50,
                nIterations=3000000,
                Eam=0.1,
                tempList=range(300, 4100, 500),
                dimensions=2,
                numTimesToAvg=3,
                multiProcess=True):
    """Plotting order vs temperature"""
    alloyGrid = srf.initializeGrid(gridLength, alloyFraction, dimensions)
    # Sets up list to take current system energy as simulation progresses
    energyList = [0] * (nIterations + 1)
    energyList[0] = sref.getTotalEnergy(alloyGrid, Eam, dimensions)
    rList = sif.tempVary(energyList, tempList, Eam, gridLength, alloyFraction,
                         dimensions, numTimesToAvg, nIterations, multiProcess)
    pyplot.plot(tempList, rList)
    pyplot.xlabel('Temperature (K)')
    pyplot.ylabel('orderValue')
    pyplot.show()
示例#7
0
def plotEnergyConvergence(gridLength=40,
                          alloyFraction=50,
                          nIterations=3000000,
                          Eam=0.1,
                          T=300,
                          dimensions=2):
    """Produces graph of system energy vs no of iterations"""
    alloyGrid = srf.initializeGrid(gridLength, alloyFraction, dimensions)
    # Sets up list to take current system energy as simulation progresses
    energyList = [0] * (nIterations + 1)
    energyList[0] = sref.getTotalEnergy(alloyGrid, Eam, dimensions)
    alloyGrid, energyList = srf.runSim(alloyGrid, energyList, T, Eam,
                                       nIterations, gridLength, dimensions)

    iterationList = range(nIterations + 1)
    pyplot.plot(iterationList, energyList)
    pyplot.xlabel('No. of iterations')
    pyplot.ylabel('System Energy (eV')
    pyplot.show()
def initializeGridTest(dimensions):
    """tests if intial grid is random and displays intial grid"""
    gridLength, alloyFraction = 20, 50
    grid = srf.initializeGrid(gridLength, alloyFraction, dimensions)
    # checks order of inital grid
    result, actualList, binList = sref.getOrder(grid, alloyFraction,
                                                dimensions)
    if result > gridLength * 0.1:
        print("CORRECT: initializeGrid produces random grid")
    else:
        print(
            """ERROR: initializeGrid most likely does NOT produce a random grid. Run 1
			more time to make sure.""")
    if dimensions == 2:
        # displays intial grid, if 2D
        pyplot.figure(num="Initial Grid Test")
        img = pyplot.imshow(grid, interpolation='nearest')
        pyplot.colorbar(img)
        pyplot.show()
示例#9
0
def orderVsTempVaryingComp(gridLength=40,
                           compList=range(0, 101, 10),
                           nIterations=3000000,
                           Eam=0.1,
                           tempList=range(300, 4100, 500),
                           dimensions=2,
                           numTimesToAvg=3,
                           multiProcess=True):
    alloyGrid = srf.initializeGrid(gridLength, 50, dimensions)
    # Sets up list to take current system energy as simulation progresses
    energyList = [0] * (nIterations + 1)
    energyList[0] = sref.getTotalEnergy(alloyGrid, Eam, dimensions)
    dataSet = []
    for i, j in enumerate(compList):
        rList = sif.tempVary(energyList, tempList, Eam, gridLength, j,
                             dimensions, numTimesToAvg, nIterations,
                             multiProcess)
        dataSet.append(rList)

    colourOptions = ['b', 'g', 'r', 'c', 'm', 'y', 'k'] * ceil(
        len(compList) / 7)
    fig, ax = pyplot.subplots()
    for i, j in enumerate(dataSet):
        ax.plot(tempList,
                j,
                colourOptions[i],
                label='f={} %%'.format(str(compList[i])))

    # Now add the legend with some customizations
    legend = ax.legend(loc='upper right', shadow=False)
    # The frame is matplotlib.patches.Rectangle instance surrounding the legend
    frame = legend.get_frame()
    frame.set_facecolor('white')
    # Set the fontsize
    for label in legend.get_texts():
        label.set_fontsize('large')
    for label in legend.get_lines():
        label.set_linewidth(1.5)  # the legend line width

    pyplot.xlabel('Temperature (K)')
    pyplot.ylabel('orderValue')
    pyplot.show()
def standardRun(nIterations=3000000,
                gridLength=40,
                alloyFraction=50,
                Eam=0.1,
                T=300,
                dimensions=2,
                showMatrixImages=True):
    """Runs through simulation for one set of parameters"""
    alloyGrid = srf.initializeGrid(gridLength, alloyFraction, dimensions)
    # Sets up list list to take current system energy as simulation progresses
    energyList = [0] * (nIterations + 1)
    energyList[0] = sref.getTotalEnergy(alloyGrid, Eam, dimensions)

    if showMatrixImages and dimensions == 2:
        # Display initial matrix
        pyplot.figure(num="Initial config")
        img1 = pyplot.imshow(alloyGrid, interpolation='nearest')
        pyplot.colorbar(img1)

    orderMeasure1, actualList, binList = sref.getOrder(alloyGrid,
                                                       alloyFraction,
                                                       dimensions)
    print("Initial order is: {}".format(str(orderMeasure1)))
    alloyGrid, energyList = srf.runSim(alloyGrid, energyList, T, Eam,
                                       nIterations, gridLength, dimensions)

    if showMatrixImages and dimensions == 2:
        # Display matrix in prettier form, as a coloured graph
        pyplot.figure(num="Final config")
        img2 = pyplot.imshow(alloyGrid, interpolation='nearest')
        pyplot.colorbar(img2)
        pyplot.show()

    orderMeasure2, actualList, binList = sref.getOrder(alloyGrid,
                                                       alloyFraction,
                                                       dimensions)
    print("Final order is: {}".format(str(orderMeasure2)))
def getOrderTest(dimensions):
    gridLength = 20
    comp = 40
    ranGrid = srf.initializeGrid(gridLength, comp, dimensions)
    nForeignAtoms = int(comp * 0.01 * gridLength**dimensions)
    orderedGrid = np.zeros([gridLength] * dimensions)
    numAdded = 0
    try:  # try, except statement creates ordered grid (2 blocks)
        for i in range(gridLength):
            for j in range(gridLength):
                if dimensions == 2:
                    orderedGrid[i, j] = 1
                    numAdded += 1
                elif dimensions == 3:
                    for k in range(gridLength):
                        orderedGrid[i, j, k] = 1
                        numAdded += 1
                assert (numAdded < nForeignAtoms)
    except (AssertionError
            ):  # exception raised simply means we should stop adding
        # atoms, not that there is a problem
        pass

    if dimensions == 2:
        # shows ordered grid to show that we are testing an ordered grid
        pyplot.figure(num="orderedGrid")
        tempImg = pyplot.imshow(orderedGrid, interpolation='nearest')
        pyplot.colorbar(tempImg)
        pyplot.show()
    ranRan, actualList, binList = sref.getOrder(ranGrid, comp, dimensions)
    ranOrd, actualList, binList = sref.getOrder(orderedGrid, comp, dimensions)
    # ranRan should be much lower than ranOrd
    if ranRan < 0.2 * ranOrd:
        print(
            "CORRECT: random and ordered grids produces correct orderValues.")
    print("The order value for the random grid is: {}".format(str(ranRan)))
    print("The order value for the random grid is: {}".format(str(ranOrd)))
示例#12
0
def tempVary(eList, tList, localEam, gridLength, alloyFraction, dimensions,
             numTimesToAvg, nIterationsPerSim, multiProcess):
    """Runs simulation at every temperature in specfied list"""
    initialGrid = srf.initializeGrid(gridLength, alloyFraction, dimensions)
    if multiProcess:
        p = MyPool(processes=10)
        mainPartial = partial(tvAvgRun, initialGrid, eList, localEam,
                              nIterationsPerSim, gridLength, dimensions,
                              alloyFraction, numTimesToAvg)
        orderList = p.map(mainPartial, tList)
        p.close()
    else:
        orderList = [0] * len(tList)
        for i, j in enumerate(tList):
            avgList = [0] * numTimesToAvg
            for k, l in enumerate(avgList):
                currentOrderValue = tvRun(initialGrid, eList, j, localEam,
                                          nIterationsPerSim, gridLength,
                                          dimensions, alloyFraction, 1)
                avgList[k] = currentOrderValue

            orderList[i] = sum(avgList) / float(len(avgList))
            print(j)
    return orderList
示例#13
0
def createTempVaryingBarDistribution(gridLength=40,
                                     alloyFraction=50,
                                     nIterations=3000000,
                                     Eam=0.1,
                                     tempList=[300, 1000, 3000, 5000],
                                     dimensions=2,
                                     multiProcess=True):
    initialGrid = srf.initializeGrid(gridLength, alloyFraction, dimensions)
    # Sets up list to take current system energy as simulation progresses
    energyList = [0] * (nIterations + 1)
    energyList[0] = sref.getTotalEnergy(initialGrid, Eam, dimensions)

    if multiProcess:
        p = Pool(processes=10)
        mainPartial = partial(tvbdRun, initialGrid, energyList, Eam,
                              nIterations, gridLength, dimensions,
                              alloyFraction)
        combined_lists = p.map(mainPartial, tempList)
        traceList = [i[0] for i in combined_lists]
        binList = combined_lists[-1][1]
    else:
        traceList = [0] * len(tempList)
        for i, j in enumerate(tempList):
            alloyGrid, energyList = srf.runSim(initialGrid, energyList, j, Eam,
                                               nIterations, gridLength,
                                               dimensions)
            randomMeasure2, actualList, binList = sref.getOrder(
                alloyGrid, alloyFraction, dimensions)
            traceList[i] = actualList

    xTraceList = str([str(i) for i in range(dimensions * 2 + 1)])
    traceObjs = []
    for i, j in enumerate(traceList):
        traceObjs.append(
            plotly.graph_objs.Bar(x=eval(xTraceList),
                                  y=j,
                                  name=str(tempList[i]) + " K"))
    traceObjs.append(
        plotly.graph_objs.Bar(x=xTraceList,
                              y=binList,
                              name='Binomial Distribution'))

    layout = plotly.graph_objs.Layout(
        barmode='group',
        xaxis=dict(title='No. of unlike neighbours',
                   titlefont=dict(family='Courier New, monospace',
                                  size=18,
                                  color='#7f7f7f')),
        yaxis=dict(title='Frequency',
                   titlefont=dict(family='Courier New, monospace',
                                  size=18,
                                  color='#7f7f7f')))

    fig = plotly.graph_objs.Figure(data=traceObjs, layout=layout)
    plotly.offline.plot(
        fig,
        filename="""tempVaryingBarDistribution [gL={}, n={}, comp={},Eam={},
		dimensions={}].html""".format(str(gridLength), str(nIterations),
                                str(alloyFraction / 100.0), str(Eam),
                                str(dimensions)).replace('\n',
                                                         '').replace('\t', ''))