def __init__(self, random=False, width=10, height=13, game='classic'):
   print 'Create a %s game' %game
   self.width = width
   self.height = height
   self.game = game
   for i in range(0, width, 1):
     self.append(column(random, height+1))
Esempio n. 2
0
def measure(line, start = 0):
    """
        returns the column number of the first non-white character on |line|
        assuming that |line| begins at column |start|.
    """
    index = scan_space(line)
    return column(line[:index], start)
Esempio n. 3
0
def Indels(fil):
    BadColum = []
    columns = column.column(fil)
    for k in columns:
        Indel = re.findall('-', columns[k])
        LenIndel = len(Indel)
        LenColumn = len(columns[k])
        if float(LenIndel) / LenColumn > 0.5:
            Pos = int(k)
            BadColum.append(Pos)
        else:
            pass
    return BadColum
Esempio n. 4
0
def Indels(fil):
    seq_dic = column.SeqDic(fil)
    columns = column.column(fil)
    for k in columns:
        Indel = re.findall('-', columns[k])
        LenIndel = len(Indel)
        LenColumn = len(columns[k])
        if float(LenIndel) / LenColumn > 0.5:
            Pos = int(k)
            for key in seq_dic:
                seq_dic[key] = seq_dic[key][:Pos] + seq_dic[key][Pos + 1:]
        else:
            pass

    return seq_dic
def Indels(fil):
    seq_dic=column.SeqDic(fil)
    columns=column.column(fil)
    for k in columns:
        Indel = re.findall('-',columns[k])
        LenIndel = len(Indel)
        LenColumn = len(columns[k])
        if float(LenIndel)/LenColumn > 0.5:
            Pos=int(k)
            for key in seq_dic:
                seq_dic[key]=seq_dic[key][:Pos]+seq_dic[key][Pos+1:]
        else:
            pass

    return seq_dic
Esempio n. 6
0
def MoreThan2(fil):
    seq_dic=50unique(fil)
    columns=column.column(fil)
    for k in columns:
        results=collections.Counter(columns[k])
        number=[]
        for key in results:
            number.append(results[key])
            greater2=[i for i in number if i>2]
            if len(greater2)==0:
                Pos=int(k)
                for keyS in seq_dic:
                    seq_dic[keyS]=seq_dic[keyS][:Pos]+seq_dic[keyS][Pos+1:]
            else:
                pass
    print seq_dic
Esempio n. 7
0
def Unique(fil):
    BadColum = []
    columns = column.column(fil)
    for k in columns:
        results = collections.Counter(columns[k])
        cunter = 0
        for key in results:
            if results[key] == 1:
                cunter = cunter + 1
            else:
                pass
        if float(cunter) / len(columns[k]) >= 0.5:
            Pos = int(k)
            BadColum.append(Pos)
        else:
            pass
    return BadColum
Esempio n. 8
0
def Unique(fil):
    seq_dic = Indels(fil)
    columns = column.column(fil)
    for k in columns:
        results = collections.Counter(columns[k])
        cunter = 0
        for key in results:
            if results[key] == 1:
                cunter = cunter + 1
            else:
                pass
        if float(cunter) / len(results) >= 0.5:
            Pos = int(k)
            for keyS in seq_dic:
                seq_dic[keyS] = seq_dic[keyS][:Pos] + seq_dic[keyS][Pos + 1:]
            else:
                pass
    return seq_dic
def Unique(fil):
    seq_dic=Indels(fil)
    columns=column.column(fil)
    for k in columns:
        results=collections.Counter(columns[k])
        cunter=0
        for key in results:
            if results[key]==1:
                cunter=cunter+1
            else:
                pass
        if float(cunter)/len(results)>=0.5:
            Pos=int(k)
            for keyS in seq_dic:
                seq_dic[keyS]=seq_dic[keyS][:Pos]+seq_dic[keyS][Pos+1:]
            else:
                pass
    return seq_dic
Esempio n. 10
0
def MoreThan2(fil):
    BadColum = []
    columns = column.column(fil)
    for k in columns:
        results = collections.Counter(columns[k])
        number = []
        for key in results:
            number.append(results[key])
            greater2 = []
            for i in range(len(number)):
                if int(number[i]) > 2:
                    greater2.append(number[i])
                else:
                    pass

        if len(greater2) == 0:
            Pos = int(k)
            BadColum.append(Pos)
        else:
            pass
    return BadColum
Esempio n. 11
0
 def __add_columns(self):
     self.columns = np.array([[column(self.input_shape, self.size)
                               for x in range(self.size)]
                               for y in range(self.size)])
Esempio n. 12
0
            for key in seq_dic:
                seq_dic[key]=seq_dic[key][:Pos]+seq_dic[key][Pos+1:]
        else:
            pass

    return seq_dic

##
# Takes a FASTA file. Takes away the columns where at least 50% of amino acids
# are unique.
# Call Indels and column, Caled by MoreThan2.
##

def 50unique(fil)
    seq_dic=Indels(fil)
    columns=column.column(fil)
    for k in columns:
        results=collections.Counter(columns[k])
        cunter=0
        for key in results:
            if results[key]==1:
                cunter=cunter+1
            else:
                pass
        if float(cunter)/len(results)>=0.5:
            Pos=int(k)
                for keyS in seq_dic:
                    seq_dic[keyS]=seq_dic[keyS][:Pos]+seq_dic[keyS][Pos+1:]
            else:
                pass
    return seq_dic
Esempio n. 13
0
def run_sim():
    # constants
    doctrine = Doctrine()
    killVehicle = KillVehicle()
    nKVs = 6
    minThreats = 3
    maxThreats = 16
    nRuns = 2500
    nAlgorithms = 2

    # statistic for metrics
    numThreats = np.zeros((nRuns, 1))
    numMissiles = np.zeros((nRuns, 1))
    invExpended = np.zeros((nRuns, nAlgorithms))
    runTime = np.zeros((nRuns, nAlgorithms))
    fracLethNegated = np.zeros((nRuns, nAlgorithms))
    fracThrtsEngd = np.zeros((nRuns, nAlgorithms))
    divertUsed = np.zeros((nRuns, nAlgorithms))

    for iRun in range(0, nRuns):
        print('Run = ', iRun)
        algoId = 0

        # generate the scenario
        [nThreats, coverageMat, divertMat, pkMat, inventory, threatValues] = \
            sim_scenario(nKVs, minThreats, maxThreats, killVehicle)
        origPkMat = np.copy(pkMat)
        numThreats[iRun] = nThreats
        numMissiles[iRun] = nKVs

        # Munkres' Optimal Assignment algorithm
        lethality = matlib.repmat(threatValues.transpose(), nKVs, 1)
        costMat = np.multiply(lethality, pkMat)
        onesMat = np.ones(costMat.shape)
        costMat = np.subtract(onesMat, costMat)
        costMat = np.multiply(costMat, coverageMat)
        ndx = np.where(costMat <= 0)
        costMat[ndx] = 1
        #         print("Cost Matrix:")
        #         print(costMat)
        t0 = time.time()
        planMat = munkres_wrapper(costMat, doctrine.valueCutoff, divertMat,
                                  threatValues, killVehicle.avePk,
                                  doctrine.maxShotsPerThreat)
        t1 = time.time()
        runTime[iRun, algoId] = t1 - t0
        divertUsed[iRun, algoId] = np.sum(np.multiply(planMat, divertMat))
        fracLethNegated[iRun, algoId] = 1.0 - lethality_leakage(
            origPkMat, planMat, threatValues)
        fracThrtsEngd[iRun, algoId] = fraction_threats_engaged(planMat)
        invExpended[iRun, algoId] = inventory_expended(planMat)
        #         print("MOA assignments:")
        #         print(planMat)
        algoId = algoId + 1

        # Greedy Assignment algorithm
        t0 = time.time()
        planMat = greedy(doctrine, nKVs, nThreats, pkMat, divertMat, inventory,
                         threatValues)
        t1 = time.time()
        runTime[iRun, algoId] = t1 - t0
        divertUsed[iRun, algoId] = np.sum(np.multiply(planMat, divertMat))
        fracLethNegated[iRun, algoId] = 1.0 - lethality_leakage(
            origPkMat, planMat, threatValues)
        fracThrtsEngd[iRun, algoId] = fraction_threats_engaged(planMat)
        invExpended[iRun, algoId] = inventory_expended(planMat)
        #         print("Greedy assignments:")
        #         print(planMat)
        algoId = algoId + 1

        # Brute Force Assignment algorithm
        planMat = np.zeros(coverageMat.shape, dtype=bool)
        wAvailable = np.where(np.sum(coverageMat, axis=1) > 0)
        tValAdj = np.fabs(threatValues -
                          (np.ones(threatValues.shape) * doctrine.valueCutoff))
        tIgnore = np.where(np.logical_not(np.floor(tValAdj)) > 0)
        redPkMatTmp = origPkMat[~np.all(origPkMat == 0,
                                        axis=1)]  # remove rows with all zeros
        redPkMat = redPkMatTmp[:, ~np.all(
            redPkMatTmp == 0, axis=0)]  # remove cols with all zeros
        redCovTmp = coverageMat[~np.all(coverageMat == 0,
                                        axis=1)]  # remove rows with all zeros
        redCov = redCovTmp[:, ~np.all(redCovTmp == 0,
                                      axis=0)]  # remove cols with all zeros
        nT = np.sum(redCov, axis=1)
        assmt = np.zeros(redPkMat.shape, dtype=bool)
        nShot = doctrine.maxShotsPerThreat
        tVals = threatValues.copy()
        cvr = np.copy(redCov.T)
        poss = np.nonzero(cvr)
        [assign, best] = assign_opt(assmt.T, nT, nShot, poss, redPkMat, tVals)
        planMat[wAvailable, tIgnore] = assign.T
        algoId = algoId + 1

    # compute final metrics
    meanRT = np.zeros((maxThreats, nAlgorithms))
    sigmaRT = np.zeros((maxThreats, nAlgorithms))
    meanFracEng = np.zeros((maxThreats, nAlgorithms))
    sigmaFracEng = np.zeros((maxThreats, nAlgorithms))
    meanFracLethNeg = np.zeros((maxThreats, nAlgorithms))
    sigmaFracLethNeg = np.zeros((maxThreats, nAlgorithms))
    meanInvExp = np.zeros((maxThreats, nAlgorithms))
    sigmaInvExp = np.zeros((maxThreats, nAlgorithms))
    meanDU = np.zeros((maxThreats, nAlgorithms))
    sigmaDU = np.zeros((maxThreats, nAlgorithms))
    nObjs = np.zeros((maxThreats, nAlgorithms))
    for i in range(minThreats, maxThreats):
        # find all runs with "i" threats
        ndx = np.where(numThreats == i)
        nRunsI = np.size(ndx)
        if nRunsI > 1:
            rt = runTime[ndx, :]
            invExp = invExpended[ndx, :]
            fracEng = fracThrtsEngd[ndx, :]
            fracLethNeg = fracLethNegated[ndx, :]
            divUsd = divertUsed[ndx, :]
            for j in range(0, nAlgorithms):
                meanRT[i, j] = np.mean(column(rt, j))
                sigmaRT[i, j] = math.sqrt(np.var(column(rt, j)))
                meanFracEng[i, j] = np.mean(column(fracEng, j))
                sigmaFracEng[i, j] = math.sqrt(np.var(column(fracEng, j)))
                meanFracLethNeg[i, j] = np.mean(column(fracLethNeg, j))
                sigmaFracLethNeg[i,
                                 j] = math.sqrt(np.var(column(fracLethNeg, j)))
                meanInvExp[i, j] = np.mean(column(invExp, j))
                sigmaInvExp[i, j] = math.sqrt(np.var(column(invExp, j)))
                meanDU[i, j] = np.mean(column(divUsd, j))
                sigmaDU[i, j] = math.sqrt(np.var(column(divUsd, j)))
                nObjs[i, j] = i

    # plot metrics
    linestyles = ['_', '-', '--', ':']
    algorithms = ['MOA', 'Greedy']
    markers = []
    for m in Line2D.markers:
        try:
            if len(m) == 1 and m != ' ':
                markers.append(m)
        except TypeError:
            pass
    styles = markers + [
        r'$\lambda$', r'$\bowtie$', r'$\circlearrowleft$', r'$\clubsuit$',
        r'$\checkmark$'
    ]
    colors = ('b', 'g', 'r', 'c', 'm', 'y', 'k')

    dx = np.zeros((1, 2))
    dx[0, 0] = -0.1
    dx[0, 1] = 0.1
    # run time
    figNum = 1
    plt.figure(figNum)
    for i in range(0, nAlgorithms):
        color = colors[i % len(colors)]
        style = styles[(i - len(linestyles)) % len(styles)]
        x = column(nObjs, i)
        delX = dx[0, i]
        x[0:np.size(x)] += delX
        y = column(meanRT, i)
        for j in range(0, len(y)):
            y[j] = y[j] * 1000
        err = column(sigmaRT, i)
        for j in range(0, len(err)):
            err[j] = err[j] * 1000
        plt.errorbar(x,
                     y,
                     yerr=err,
                     linestyle='None',
                     marker=style,
                     color=color,
                     markersize=8,
                     label=algorithms[i])
        plt.xlabel('# Threat Objects')
        plt.ylabel('Run Time, ms')
        plt.grid(True)
        plt.show()
        plt.hold(True)
    plt.legend()

    # fraction threats engaged
    figNum = figNum + 1
    plt.figure(figNum)
    for i in range(0, nAlgorithms):
        color = colors[i % len(colors)]
        style = styles[(i - len(linestyles)) % len(styles)]
        x = column(nObjs, i)
        delX = dx[0, i]
        x[0:np.size(x)] += delX
        y = column(meanFracEng, i)
        err = column(sigmaFracEng, i)
        plt.errorbar(x,
                     y,
                     yerr=err,
                     linestyle='None',
                     marker=style,
                     color=color,
                     markersize=8,
                     label=algorithms[i])
        plt.xlabel('# Threat Objects')
        plt.ylabel('Fraction Threats Engaged')
        plt.grid(True)
        plt.show()
        plt.hold(True)
    plt.legend()

    # fraction lethality negated
    figNum = figNum + 1
    plt.figure(figNum)
    for i in range(0, nAlgorithms):
        color = colors[i % len(colors)]
        style = styles[(i - len(linestyles)) % len(styles)]
        x = column(nObjs, i)
        delX = dx[0, i]
        x[0:np.size(x)] += delX
        y = column(meanFracLethNeg, i)
        err = column(sigmaFracLethNeg, i)
        plt.errorbar(x,
                     y,
                     yerr=err,
                     linestyle='None',
                     marker=style,
                     color=color,
                     markersize=8,
                     label=algorithms[i])
        plt.xlabel('# Threat Objects')
        plt.ylabel('Fraction Lethality Negated')
        plt.grid(True)
        plt.show()
        plt.hold(True)
    plt.legend()

    # divert used
    figNum = figNum + 1
    plt.figure(figNum)
    for i in range(0, nAlgorithms):
        color = colors[i % len(colors)]
        style = styles[(i - len(linestyles)) % len(styles)]
        x = column(nObjs, i)
        delX = dx[0, i]
        x[0:np.size(x)] += delX
        y = column(meanDU, i)
        err = column(sigmaDU, i)
        plt.errorbar(x,
                     y,
                     yerr=err,
                     linestyle='None',
                     marker=style,
                     color=color,
                     markersize=8,
                     label=algorithms[i])
        plt.xlabel('# Threat Objects')
        plt.ylabel('Divert Expended, m/s')
        plt.grid(True)
        plt.show()
        plt.hold(True)
    plt.legend()
Esempio n. 14
0
 def __add_columns(self):
     self.columns = np.array(
         [[column(self.input_shape, self.size) for x in range(self.size)]
          for y in range(self.size)])