def extract_top10(self, tags=[], source=None):
     self.top_10.clear()
     sort = Sorting(self.shots, tags=tags, source=source)
     listing = sort.get_result()
     for tup in listing:
         self.top_10.append(tup[0])
     self.logger.info("Top 10 is extracted.")
Example #2
0
 def test():
     fs = FacetedSearch()
     num = Numbers()
     srt = Sorting()
     prb = Probability()
     print("Тест первого задания: ")
     fs.start_search()
     print("----------------------")
     print("Тест второго задания: ")
     num.perform_distribution()
     print("----------------------")
     print("Тест третьего задания: ")
     srt.fill_array()
     print("Пузырьковая сортировка:")
     srt.bubble_sort()
     print("Гномья сортировка:")
     srt.gnome_sort()
     print("Блочная сортировка:")
     srt.bucket_sort()
     print("Пирамидальная сортировка:")
     srt.pyramid_sort()
     print("----------------------")
     print("Тест четвертого задания: ")
     prb.count_probability()
Example #3
0
# -------------------
# 22/4/2018
# Test Delmas2013
# -------------------

from Sorting import * #@UnusedWildImport
from time import * #@UnusedWildImport

Person = DeclareSort('Person')
Information = DeclareSort('Information')
Topic = DeclareSort('Topic')

table = Sorting()
# Variables
table.add_variable("s", Person)
table.add_variable("r", Person)
table.add_variable("i", Information)
table.add_variable("t", Topic)
s = table.get_variable(0)
r = table.get_variable(1)
i = table.get_variable(2)
t = table.get_variable(3)

#  predicates 
Psend = Function('Psend', Person, Person, Information, BoolSort()) 
Fsend = Function('Fsend', Person, Person, Information, BoolSort()) 
Osend = Function('Osend', Person, Person, Information, BoolSort())
topic = Function('topic', Information, Topic, BoolSort())     
know = Function('know', Person, Information, BoolSort())

# Constants
Example #4
0
# -------------------
# 24/4/2018
# Test simple chaining propositionnal
# -------------------

from Sorting import *  #@UnusedWildImport
from time import *  #@UnusedWildImport

# --------------------------
Type = DeclareSort('Type')

table = Sorting()
# # Variables
table.add_variable("X", Type)
X = table.get_variable(0)

P0 = Const('P0', BoolSort())
D1 = Const('D1', BoolSort())
C1 = Const('C1', BoolSort())
D2 = Const('D2', BoolSort())
C2 = Const('C2', BoolSort())
#
# table.add_rule(D1, C1)
# table.add_rule(C1, C2)
# table.add_rule(C2, Not(D1))

#### ===============
#  ----------- Safe --------------
# SAFE [0, 1, 1] <[Not(D1), C1, C2] => [C2, Not(D1)]>
# SAFE [0, 0, 1] <[Not(D1), Not(C1), C2] => [Not(D1)]>
#  ----------- Unsafe --------------
def RunTest(problem_type, Algorithm_name, num_runs=2, maxTime=60):

    Algorithm = Algorithms[Algorithm_name]
    findIdentity = True
    res_fitness_evals = {}
    res_time = {}
    prob_size = 10

    distance_names = ["Hamming", "Kendall", "Cayley", "RUN", "LAS"]
    # distance_names = ["Cayley", "RUN", "LAS"]

    for dist_name in distance_names:
        res_fitness_evals[dist_name] = [None] * num_runs
        res_time[dist_name] = [None] * num_runs

    for dist_name in distance_names:
        DistanceMeasure = distances[dist_name]

        ProblemInstance = Sorting.Sorting(prob_size)

        if Algorithm_name == "EHBSA_wt" or Algorithm_name == "UMDA":
            pop_size = math.ceil(math.sqrt(ProblemInstance.dim))
        elif Algorithm_name == "GeneralizedMallowsModel":
            pop_size = 10 * ProblemInstance.dim

        # print("Test",problem_type, Algorithm_name, instance)

        for test_num in range(num_runs):
            print(dist_name, "test", test_num)

            try:
                (val1, val2) = Algorithm.Run(problem_type,
                                             ProblemInstance,
                                             pop_size,
                                             maxTime=maxTime,
                                             NumberOfTemplateCuts=4,
                                             findIdentity=findIdentity,
                                             DistanceMeasure=DistanceMeasure)

                res_fitness_evals[dist_name][test_num] = val1
                res_time[dist_name][test_num] = val2

                # print(val1,val2)
            except RuntimeError:
                print("runtime error", problem_type, Algorithm_name)
            except OverflowError as e:
                print("overflow error", problem_type, Algorithm_name, str(e))
            except Exception as e:
                print("Other error",
                      sys.exc_info()[0], problem_type, Algorithm_name, str(e))

            ProblemInstance.ResetFitnessCount()

    path = "C:/Users/gustavfjorder/OneDrive - QVARTZ/Documents/02_DTU/08 Estimation of distribution/EDAs_for_TSP/Testing/"
    path += "DMs/"
    path += Algorithm_name + "_"
    path += str(maxTime) + "s_"
    path += time.strftime("%Y%m%d-%H%M%S")

    df_res_fitness_evals = pd.DataFrame(data=res_fitness_evals)
    df_res_time = pd.DataFrame(data=res_time)

    df_res_fitness_evals.to_excel(path + "_fitnessEvaluations.xlsx")
    df_res_time.to_excel(path + "_timeUsed.xlsx")
    print("Exported to Excel")

    print("Finished", Algorithm_name, problem_type, Algorithm_name)


# RunTest("Sorting", "GeneralizedMallowsModel", num_runs = 2, maxTime = 30)
Example #6
0
# -------------------
# 17/5/2018
# Test tautology
# -------------------

#from Improve import * #@UnusedWildImport
from Sorting import *  #@UnusedWildImport
#from Iterative import * #@UnusedWildImport
from time import *  #@UnusedWildImport

# --------------------------
#table = Iterative()
table = Sorting()
# Variables
table.add_variable("X", IntSort())  ## TODO fix it
A = Const('A', BoolSort())
B = Const('B', BoolSort())
C = Const('C', BoolSort())
D = Const('D', BoolSort())
E = Const('E', BoolSort())
F = Const('F', BoolSort())
G = Const('G', BoolSort())
H = Const('H', BoolSort())

# removed before
###table.add_rule(A, A)

# #### cas <= sat 1 tauto 2 unsafe may be pb lastNot
# table.add_rule(A, B)
# table.add_rule(B, A)
# table.add_rule(C, D)
Example #7
0
import Sorting

read_filename = "/home/vampy/data/test1"
write_filename = "/home/vampy/data/test2"

fp = open(filename, "r")
N = int(fp.readline())
names = []
for i in range(N):
    names.append(fp.readline().strip())

fp.close()

Sorting.mergesort(names)

fp = open(write_filename, "w")
fp.write("{0}\n".format(N))
for i in range(N):
    fp.write("{0}\n".format(names[i]))

fp.close()
Example #8
0
def Run(ProblemType,
        ProblemInstance,
        N,
        maxTime=60,
        epsilon=0.05,
        NumberOfTemplateCuts=0,
        findIdentity=False,
        DistanceMeasure=None):
    # seed = 12
    # random.seed(seed)
    # np.random.seed(seed)
    startTime = time.time()

    # Permutation size
    n = ProblemInstance.dim

    if ProblemType == "TSP" and DistanceMeasure != None:
        DistanceMeasure = None
    elif ProblemType == "Sorting" and DistanceMeasure == None:
        DistanceMeasure = SwapDistance

    if N is None:
        N = ProblemInstance.dim

    # Population size
    population_size = N

    # Sample size
    sample_size = 8 * population_size

    # Epsilon
    # epsilon = 0.1

    t = 0
    # Generate N points randomly
    population = [None] * population_size
    new_sample = [None] * sample_size

    # Probabilities
    P = [[1 / n] * n for _ in range(n)]

    best_permutation = None
    best_fitness = None

    canContinue = True
    while canContinue:

        for j in range(sample_size):
            individual = SampleOffspring(P)
            fitness = ProblemInstance.Fitness(DistanceMeasure, individual)
            new_sample[j] = (fitness, individual)

            if best_fitness is None:
                best_permutation = [i for i in individual]
                best_fitness = fitness

            if time.time() - startTime >= 1.5 * maxTime:
                if any(e is None for e in new_sample):
                    new_sample = [e for e in new_sample if e is not None]
                break

        new_sample = sorted(new_sample,
                            key=lambda t: (t[0], random.random()),
                            reverse=True)
        population = new_sample[:population_size]

        if population[0][0] > best_fitness:
            best_permutation = [i for i in population[0][1]]
            best_fitness = population[0][0]

        # Update probabilities
        for i in range(n):
            P[i] = [epsilon] * n

            for s in population:
                P[i][s[1][i]] += 1

            P[i] = normalize(P[i])

        # Check if we can continue
        if time.time() - startTime >= maxTime:
            canContinue = False
        if findIdentity and Sorting.IsIdentity(population[0][1]):
            canContinue = False

    # If we are solving the sorting problem, return the number of fitness evals and the time it took
    if findIdentity:
        return ProblemInstance.fitness_evaluations, time.time() - startTime

    # Return best permutation and its fitness
    return best_permutation, best_fitness
Example #9
0
import time
import plotly
from plotly.graph_objs import Scatter, Figure, Layout
from Sorting import *
from Movie import *

sorting = Sorting()
sorting_algorithms = [('mergesort', sorting.mergesort), ('quicksort', sorting.quicksort),
                      ('bubblesort', sorting.bubblesort), ('selectionsort', sorting.selectionsort),
                      ('insertionsort', sorting.insertionsort)]

file = open('movie_titles2.txt', 'r')
movies = []
for line in file:
    line = line.split(',', 2)
    movies += [Movie(line[0], line[1], line[2][0:len(line[2])-1])]


def run_sorting_algorithms(arr, namePlot):
    x_axis = [10, 100, 1000, 2000, 5000, 10000, 12000, 15000, 17000]
    data_time = []
    data_comparisons = []

    for algorithm in sorting_algorithms:
        time_complexity = []
        number_comparisons = []
        for x in x_axis:
            data = arr[:x]
            initial_time = time.clock()
            number_comparisons += [algorithm[1](data)]
            time_complexity += [time.clock() - initial_time]
Example #10
0
        # learns the ensembles in original data and generates pictures
        learn.convolution(args.dataset, nfolder, args.dataset_name,\
                        file_name, args.swap_axes,\
                        args.ensembles,args.iterations,args.length,\
                        args.ensemble_penalty,\
                        args.limit,args.start,args.remove,\
                        args.initializations,args.store_iterations,\
                        args.warm_start_file,args.warm_start_group,args.quiet)

        print('learning ensembles on real data is done                 \n')

        # searching for random ensembles if stated so
        if args.initializations > 1:

            if not os.path.exists(args.dataset + '_random.h5'):
                sort.mix_matrix(args.dataset, args.dataset_name)

            # learns the ensembles in randomly mixed data and generated pictures
            nfolder = os.path.join(folder, 'Ensembles_random')
            learn.convolution(args.dataset+'_random', nfolder,\
                            args.dataset_name, file_name+'_random',\
                            args.swap_axes,\
                            args.ensembles,args.iterations,args.length,\
                            args.ensemble_penalty,\
                            args.limit,args.start,args.remove,\
                            args.initializations,args.store_iterations,\
                            None,None,args.quiet)

            print('learning ensembles on random data is done            \n')

    # will store the final motifs in destination
Example #11
0
def Run(ProblemType,
        ProblemInstance,
        N,
        NumberOfTemplateCuts=0,
        maxTime=-1,
        findIdentity=False,
        DistanceMeasure=None):
    """Optimizes using EHBSA
    
    Arguments:
        ProblemType {string} -- "TSP" or "Sorting"
        ProblemInstance -- The instance of TSP or Sorting
        maxIterations {int} -- Number of iterations to run algorithm
        N {int} -- Number of individuals in population
    
    Keyword Arguments:
        NumberOfTemplateCuts {int} -- Number of cuts when running algorithm. Use 0 to get EHBSA/WO (default: {0})
    
    Returns:
        Solution -- The best permutation found
        Distance -- The length of the best tour found 
    """
    if ProblemType == "TSP" and DistanceMeasure != None:
        DistanceMeasure = None
    elif ProblemType == "Sorting" and DistanceMeasure == None:
        DistanceMeasure = Sorting.SwapDistance

    # Start timer
    startTime = time.time()

    # If no population size is given
    if N is None:
        N = ProblemInstance.dim

    # Length of solutions
    L = ProblemInstance.dim

    # Define B_ratio that controls pressure towards random permutations and calculate epsilon
    B_ratio = 0.04
    epsilon = (2 * N) / (L - 1) * B_ratio

    # Create N individuals at random
    individuals = [[i for i in np.random.permutation(L)] for _ in range(N)]
    individuals_fitness = [
        ProblemInstance.Fitness(DistanceMeasure, individual)
        for individual in individuals
    ]

    # Generate initial EHM
    EHM = [[0 for _ in range(L)] for _ in range(L)]

    # Fill EHM
    for i in range(L):
        for j in range(L):
            EHM[i][j] = e(i, j, epsilon, N, L, individuals)

    canContinue = True
    while canContinue:
        # Sample new individual
        if NumberOfTemplateCuts <= 1:
            newIndividual = sampleNewIndividual(N, L, EHM)
        else:
            randomIndividual = random.choice(individuals)
            newIndividual = sampleNewIndividualWithTemplate(
                N, L, EHM, randomIndividual, NumberOfTemplateCuts)

        # Compare new individual to a random exisiting individual
        randomExisitingIndividual = random.randint(0, N - 1)
        randomExisitingIndividual_fitness = individuals_fitness[
            randomExisitingIndividual]

        new_individual_fitness = ProblemInstance.Fitness(
            DistanceMeasure, newIndividual)
        if new_individual_fitness > randomExisitingIndividual_fitness:
            individuals[randomExisitingIndividual] = newIndividual.copy()
            individuals_fitness[
                randomExisitingIndividual] = new_individual_fitness

            # Recalculate EHM
            for i in range(L):
                for j in range(L):
                    EHM[i][j] = e(i, j, epsilon, N, L, individuals)

        if time.time() - startTime >= maxTime:
            canContinue = False
        if findIdentity and Sorting.IsIdentity(newIndividual):
            canContinue = False

    bestSolution_index = 0
    bestFitness = ProblemInstance.Fitness(DistanceMeasure, individuals[0])
    for individual_index in range(1, N):
        fitness = ProblemInstance.Fitness(DistanceMeasure,
                                          individuals[individual_index])
        if fitness > bestFitness:
            bestFitness = fitness
            bestSolution_index = individual_index

    if findIdentity:
        # print(individuals[bestSolution_index], bestFitness)
        return ProblemInstance.fitness_evaluations, time.time() - startTime

    return individuals[bestSolution_index], bestFitness
Example #12
0
# -------------------
# 22/4/2018
# Test Karimi2009
# -------------------

from Sorting import *  #@UnusedWildImport
from time import *  #@UnusedWildImport

Resource = DeclareSort('Resource')
Agent = DeclareSort('Agent')

table = Sorting()
# Variables
table.add_variable("cre", Agent)
table.add_variable("cu", Agent)
table.add_variable("m", Resource)
table.add_variable("c", Resource)
cre = table.get_variable(0)
cu = table.get_variable(1)
m = table.get_variable(2)
c = table.get_variable(3)

#  predicates
resource = Function('resource', Resource, BoolSort())
agent = Function('agent', Agent, BoolSort())
money = Function('money', Resource, BoolSort())
car = Function('car', Resource, BoolSort())
employee = Function('employee', Agent, BoolSort())
customer = Function('customer', Agent, BoolSort())
gold = Function('gold', Agent, BoolSort())
rent = Function('rent', Agent, Agent, Resource, BoolSort())
Example #13
0
# -------------------
# 3/5/2018
# Test simple computation
# -------------------

from Sorting import *  #@UnusedWildImport
from time import *  #@UnusedWildImport

# --------------------------
#Type = DeclareSort('Type')

table = Sorting()
# Variables
table.add_variable("I", IntSort())
table.add_variable("J", IntSort())
#table.add_variable("K", IntSort())
I = table.get_variable(0)
J = table.get_variable(1)
#K = table.get_variable(2)

### predicates
fun = Function('fun', IntSort(), IntSort())
H = Function('H', IntSort(), IntSort(), IntSort())
G = Function('G', IntSort(), IntSort())
fact = Function('fact', IntSort(), IntSort())

### R1
# table.add_rule((I <= 3), fun(I) == I-2)
# table.add_rule((I >= 1), fun(I) == I+1)

### R2
Example #14
0
import Sorting
import Graphs

# Sorting.SortScores(filePath = "score.txt", separator = "\t" * 2, ascending = False, orderBy = 1, ignLines = 4)

# Graphs.LinearAndBar(filePath = "score.txt", exportPath = "Generated.png", ignLines = 4, separator = "\t\t", xFunc = lambda l: int(l[0]), y1Func = lambda l: int(l[1]), y2Func = lambda l: int(l[4]) + int(l[3]))

# Generation / Score / Collectibles
# gen = lambda l: int(l[0])
# score = lambda l: int(l[2])
# coll = lambda l: int(l[4])

# Graphs.LinearAndBar(filePath = "../Data.log", exportPath = "Data.png", ignLines = 2, separator = "\t\t", xFunc = gen, y1Func = score, y2Func = coll, xLabel = "Generation", y1Label = "Score", y2Label = "Collectibles")

data, cont = Sorting.ReadData(filePath="Data.log", ignLines=2)
cont = Sorting.ConvertToArray(cont=cont, separator="\t\t")

Genomes = {}
SS = set()
with open("Trace.log", "r") as fs:
    for x in range(60):
        prefGenes = set()
        gen = 0
        next(fs)
        gen = int(fs.readline()[11:13])
        for i in range(5):
            next(fs)
        for i in range(6):
            line = fs.readline()
            genes = line.split(":")
            genes = list(map(lambda g: g[:-1].strip(), genes[2:]))
maxTime = 10 * 60
tests = [5, 10, 15, 20, 25]
num_runs = 5

if len(sys.argv) > 1:
    Algorithm_name = sys.argv[1]
    Algorithm = Algorithms[Algorithm_name]

result_fitness = {5: [], 10: [], 15: [], 20: [], 25: []}
result_time = {5: [], 10: [], 15: [], 20: [], 25: []}

for instance_size in tests:
    print("Test", instance_size)
    pop_size = 10 * instance_size
    SortingInstance = Sorting.Sorting(instance_size)
    for test_num in range(1, num_runs + 1):
        try:
            fitness_evals, time_used = Algorithm.Run("Sorting",
                                                     SortingInstance,
                                                     pop_size,
                                                     maxTime=maxTime,
                                                     NumberOfTemplateCuts=4,
                                                     findIdentity=True)
            result_fitness[instance_size].append(fitness_evals)
            result_time[instance_size].append(time_used)
            print(fitness_evals)
        except RuntimeError:
            print("runtime error")
        except OverflowError:
            print("overflow error")
Example #16
0
# -------------------
# 22/4/2018
# Test simple Person example
# -------------------

from Sorting import *  #@UnusedWildImport
from time import *  #@UnusedWildImport

# --------------------------
Type = DeclareSort('Type')

table = Sorting()
# Variables
table.add_variable("X", Type)
X = table.get_variable(0)

student = Function('student', Type, BoolSort())
person = Function('person', Type, BoolSort())
allow = Function('allow', Type, BoolSort())
other = Function('other', Type, BoolSort())

table.add_rule(student(X), person(X))
table.add_rule(student(X), allow(X))
table.add_rule(person(X), Not(allow(X)))

### ===========================
table.compute_table(3)
table.check()
print(str(table))
def Run(ProblemType,
        ProblemInstance,
        N,
        maxTime=60,
        NumberOfTemplateCuts=0,
        findIdentity=False,
        DistanceMeasure=None):
    # seed = 12
    # random.seed(seed)
    # np.random.seed(seed)
    startTime = time.time()

    if N is None:
        N = 10 * ProblemInstance.dim
    pop_size = N
    # pop_size = 1
    selection_size = N // 2
    # selection_size = 1
    offspring_size = N - 1
    # offspring_size = 1

    # Two parameters necessary for defining model
    central_permutation = None
    Theta = [None] * (ProblemInstance.dim - 1)

    if ProblemType == "TSP" and DistanceMeasure != None:
        DistanceMeasure = None
    elif ProblemType == "Sorting" and DistanceMeasure == None:
        DistanceMeasure = SwapDistance

    # Create initial population randomly
    population = [(ProblemInstance.Fitness(DistanceMeasure,
                                           individual), individual)
                  for individual in
                  [[i for i in np.random.permutation(ProblemInstance.dim)]
                   for _ in range(pop_size)]]
    population = sorted(population,
                        key=lambda t: (t[0], random.random()),
                        reverse=True)

    canContinue = True
    its = 0
    while canContinue:
        its += 1
        # print("run", its)
        # Make selection
        selection = population[:selection_size]

        ## Find central permutation using Borda algorithm
        # Find the average of each position
        averages = [0] * ProblemInstance.dim
        for i in range(ProblemInstance.dim):
            for individual in selection:
                averages[i] += individual[1][i]
            averages[i] = (averages[i] / len(selection), i)

        # Sort the averages
        averages = sorted(averages, key=lambda t: (t[0], random.random()))

        # Create central permutation
        central_permutation = [0] * ProblemInstance.dim
        for i in range(ProblemInstance.dim):
            central_permutation[averages[i][1]] = i

        # If we are solving the sorting problem and the central permutation is the identity, break
        if findIdentity and Sorting.IsIdentity(central_permutation):
            canContinue = False
            break

        # Calculate Theta
        sample = [perm for _, perm in selection]
        for j in range(len(central_permutation) - 1):
            try:
                t = optimize.newton(LogLikelihoodSingleJ,
                                    0.1,
                                    maxiter=100,
                                    tol=0.001,
                                    args=(
                                        j,
                                        sample,
                                        len(central_permutation),
                                        central_permutation,
                                    ))
            except RuntimeError:
                t = 0.1
            if t < 0:
                t = 0.1
                # print("setting t=0.1")
            Theta[j] = t

            # stop=1
            # print(central_permutation)
            # print(sample)
            # t = optimize.newton(LogLikelihoodSingleJ, 0.1, tol=0.0001, args=(j, sample, len(central_permutation), central_permutation,))
            # import matplotlib.pyplot as plt

            # x = []
            # y = []
            # # j=2
            # # import numpy as np
            # for Theta_plot in np.arange(0.0001,1,0.01):
            #     x.append(Theta_plot)
            #     val = LogLikelihoodSingleJ(Theta_plot, j , sample, len(central_permutation), central_permutation)
            #     y.append(val)

            # plt.plot(x,y)
            # plt.show()
            # hi=1

        # Make list for samples. Use length (offspring_size+1) so there is space for pop[0]
        sample = [None] * (offspring_size + 1)
        sample[0] = population[0]

        for i in range(1, offspring_size + 1):
            s = SampleMallowsModel(central_permutation, Theta)
            fitness = ProblemInstance.Fitness(DistanceMeasure, s)

            sample[i] = (fitness, s)

            # If we are solving the sorting problem and s is the identity, break and stop loop
            if findIdentity and Sorting.IsIdentity(s):
                canContinue = False
                # break

        # Sort the sample by fitness and make copy
        if its == 10:
            hi = 1
        sample = sorted(sample,
                        key=lambda t: (t[0], random.random()),
                        reverse=True)
        population = [s for s in sample]

        # Check if we can continue
        if time.time() - startTime >= maxTime:
            canContinue = False
        if findIdentity and Sorting.IsIdentity(population[0][1]):
            canContinue = False

    # If we are solving the sorting problem, return the number of fitness evals and the time it took
    if findIdentity:
        return ProblemInstance.fitness_evaluations, time.time() - startTime

    # Return best permutation and its fitness
    return population[0][1], population[0][0]
Example #18
0
# -------------------
# 22/6/2018
# RBAC2 from http://www3.cs.stonybrook.edu/~stoller/ccs2007/
# -------------------
### without simplification
### encoding revoke: similar to assign
### but needs to add extra condition and discrete time
# -----------------

from Sorting import *  #@UnusedWildImport

# --------------------------
Person = DeclareSort('Person')
Resource = DeclareSort('Resource')

table = Sorting()
# Variables
table.add_variable("X", Person)
table.add_variable("R", Resource)
table.add_variable("Y", Person)
table.add_variable("T", IntSort())  # linear time
table.add_variable("P", IntSort())  # linear time
X = table.get_variable(0)
R = table.get_variable(1)
Y = table.get_variable(2)
T = table.get_variable(3)
P = table.get_variable(4)

### --------------------------
### predicates for roles
Employee = Function('Employee', IntSort(), Person, BoolSort())
Example #19
0
# -------------------
# 20/6/2018
# CONTINUE A from test.tspass
# -------------------

from Sorting import *  #@UnusedWildImport
from time import *  #@UnusedWildImport

# Sorts
Subject = DeclareSort('Subject')
Resource = DeclareSort('Resource')

#table = Enumerative()
#table = Iterative()
table = Sorting()
# Variables
table.add_variable("R", Resource)
table.add_variable("X", Subject)
R = table.get_variable(0)
X = table.get_variable(1)

# predicates
### subjects
subject = Function('subject', Subject, BoolSort())
admin = Function('admin', Subject, BoolSort())
pcchair = Function('pcchair', Subject, BoolSort())
pcmember = Function('pcmember', Subject, BoolSort())
subreviewer = Function('subreviewer', Subject, BoolSort())
### actions
Pdelete = Function('Pdelete', Subject, Resource, BoolSort())
Pcreate = Function('Pcreate', Subject, Resource, BoolSort())
Example #20
0
# -------------------
# 22/4/2018
# test Shaikh2010
# -------------------

from Sorting import *  #@UnusedWildImport
from time import *  #@UnusedWildImport

Data = DeclareSort('Data')
Person = DeclareSort('Person')

root = Const('root', Person)
tech = Const('tech', Person)
data = Const('data', Data)

table = Sorting()
# Variables
table.add_variable("A", Person)
table.add_variable("C", Person)
table.add_variable("D", Data)
A = table.get_variable(0)
C = table.get_variable(1)
D = table.get_variable(2)

#  predicates
rights = Function('rights', Person, Data, BoolSort())
pread = Function('pread', Person, Data, BoolSort())
pwrite = Function('pwrite', Person, Data, BoolSort())
pdelete = Function('pdelete', Person, Data, BoolSort())
person = Function('person', Person, BoolSort())
administrator = Function('administrator', Person, BoolSort())
Example #21
0
# -------------------
# 29/4/2018
# Test Adi2009
# -------------------

from Sorting import *  #@UnusedWildImport
from time import *  #@UnusedWildImport

# --------------------------
Patient = DeclareSort('Patient')
Hospital = DeclareSort('Hospital')

table = Sorting()
# Variables
table.add_variable("p", Patient)
table.add_variable("h", Hospital)
p = table.get_variable(0)
h = table.get_variable(1)
# more
X = Const('X', Hospital)
toubib = Const('toubib', Hospital)
nounou = Const('nounou', Hospital)
bob = Const('bob', Patient)

# 4/1 + 3/2 predicates
hospital = Function('hospital', Hospital, BoolSort())
doctor = Function('doctor', Hospital, BoolSort())
nurse = Function('nurse', Hospital, BoolSort())
chief = Function('chief', Hospital, BoolSort())
pread = Function('pread', Hospital, Patient, BoolSort())
pwrite = Function('pwrite', Hospital, Patient, BoolSort())
Example #22
0
    current_price = csp.getPrice()

    if (fs_df.empty):
        print("Financial Statement doesn't exist")
        nNoFS += 1
        NoFS.append(code_df.iloc[idx]['name'])
        continue

    if (current_price <= 0):
        print("Cannot get price info")
        nCannotGetPrice += 1
        CannotGetPrice.append(code_df.iloc[idx]['name'])
        continue

    check_list = []
    sorting = Sorting.Sorting(fs_df, current_price)
    check_list = sorting.algorithm()

    # 8 : Diamond 7 : Gold, 6 : Silver, 4~5 : Bronze
    if (check_list.count(True) >= 8):
        underEstimated_Diamond.append(code_df.iloc[idx]['name'])
    elif (check_list.count(True) >= 7):
        underEstimated_Gold.append(code_df.iloc[idx]['name'])
    elif (check_list.count(True) >= 6):
        underEstimated_Silver.append(code_df.iloc[idx]['name'])
    elif (check_list.count(True) >= 4):
        underEstimated_Bronze.append(code_df.iloc[idx]['name'])
    #     fs_df.to_excel(writer, sheet_name = code_df.iloc[idx]['name'])
    #     writer.save()
print("No FinancialStatement : {}".format(nNoFS))
print(NoFS)