Exemplo n.º 1
0
class StrategyCalculator():
    def __init__(self, tickerName):
        self.tickerName = tickerName
        self.comparator = Comparator(self.tickerName)
        self.analyser = Analyser(self.tickerName, self.comparator)

    def inform(self, df):
        # print("Calculating Strategy for " + str(self.tickerName) + " at " + str(timeStamp) + "...")
        ### TO-DO: Develop strategies to calculate

        ##
        ## Inform Analyser to do the interval Analysis first
        ## This is before the pseudotrades to ensure no clashes
        self.analyser.intervalAnalysis(df.head(1))
        self.comparator.intervalAnalysis(df.head(1))

        indi = ind.Indicator()

        Results = indi.beginCalc(df, self.tickerName)

        for i in Results:
            # print('Indicator: ' + i)
            # print('Position: ' + str((Results[i])['position']))
            if (Results[i])["position"] != 0:
                self.analyser.PseudoTrade(df, i, Results[i])

            ### for testing
            # self.analyser.PseudoTrade(df,i, Results[i], atr)
            ###
        ### END TO-DO
        # print("Calculated Strategy for " + str(self.tickerName) + " at " + str(timeStamp))
        self.comparator.compare(Results, df["date"].values[0])
Exemplo n.º 2
0
class StrategyCalculator():
    def __init__(self, tickerName):
        self.tickerName = tickerName
        self.comparator = Comparator(self.tickerName)
        self.analyser = Analyser(self.tickerName, self.comparator)

    def inform(self, df):
        # print("Calculating Strategy for " + str(self.tickerName) + " at " + str(timeStamp) + "...")
        ### TO-DO: Develop strategies to calculate

        ##
        ## Inform Analyser to do the interval Analysis first
        ## This is before the pseudotrades to ensure no clashes
        self.analyser.intervalAnalysis(df.head(1))

        #1. Calculate ATR for potential trade
        atr = atrcalc.ATRcalc(df)
        indi = ind.Indicator()

        Results = indi.beginCalc(df, self.tickerName, atr)

        for i in Results:
            if Results[i] != 0:
                self.analyser.PseudoTrade(df, i, Results[i], atr)

            ### for testing
            # self.analyser.PseudoTrade(df,i, Results[i], atr)
            ###
        ### END TO-DO
        # print("Calculated Strategy for " + str(self.tickerName) + " at " + str(timeStamp))
        self.comparator.compare(Results, atr)
Exemplo n.º 3
0
def kmp_match(t, p):
    '''
    Find all instances of p in t, runs a comparator class that keeps track of the number of comparisons made
    '''
    pi = compute_prefix(p)
    q = 0  #number of thus far matched characters in the pattern
    c = Comparator()
    results = []
    for i in range(0, len(t)):
        # we've matched some characters, but not enough, so we shift forward by the prefix amount
        while q > 0 and not c.compare(p, q, t, i):
            q = pi[q]
        # we've matched another character
        if c.compare(p, q, t, i):
            q += 1
        # we've matched as many chars are there in the pattern, we've found a match
        if q == len(p):
            results.append(i - len(p) + 1)
            q = pi[q - 1]
    return results, c
Exemplo n.º 4
0
class ComparatorPnml(object):

    def __init__(self, filename, nfilename=None,
            max_coef=10, smt_timeout_iter=0, smt_timeout_matrix=0,
            positive_log=None):
        self.filename = filename
        parser = PnmlParser(filename)
        parser.parse()
        self.net = parser.petrinet
        self.dim = parser.dim
        self.event_dictionary = parser.event_dictionary
        self.positive_log = positive_log

        # Helper pach. Doesn't actually compute hull
        self.pach = PacH(filename, nfilename=nfilename)
        self.pach.event_dictionary = parser.event_dictionary
        self.pach.dim = self.dim
        self.pach.reversed_dictionary = rotate_dict(parser.event_dictionary)
        if nfilename:
            self.pach.parse_negatives()

        #qhull = self.net.get_qhull()
# TODO WTF!?
        qhull = self.net.get_qhull(neg_points=self.pach.npv_set)
        qhull.prepare_negatives()
        # Hull for NO SMT
        qhull_no_smt = copy.deepcopy(qhull)
        # Hull for SMT iterative simp
        qhull_smt_iter = copy.deepcopy(qhull)
        # Hull for SMT matrix simp
        qhull_smt_matrix = qhull

        self.comparator = Comparator(qhull_no_smt, qhull_smt_iter, qhull_smt_matrix,
                max_coef, smt_timeout_iter, smt_timeout_matrix)

    def generate_pnml(self):
        output_pnml = self.filename
        output_pnml = (output_pnml.endswith('.pnml') and output_pnml[:-5])\
                or output_pnml or ''
        return self.comparator.generate_pnml(filename=output_pnml,
                reversed_dictionary=self.pach.reversed_dictionary)

    def compare(self):
        return self.comparator.compare()

    def generate_outputs(self):
        # For every benchmark, generate the output
        return self.comparator.generate_outputs(pach=self.pach)

    def check_hull(self):
        if self.positive_log:
            return self.comparator.check_hull(log_file=self.positive_log,
                    event_dictionary=self.event_dictionary)
Exemplo n.º 5
0
def bmh_matcher(t,p):
    table = make_table(p)
    c = Comparator()
    results = []
    i = 0
    while i < len(t):
        try:
            first = t[i+len(p)]
        except IndexError:
            return results, c
        for j in range(len(p)-1,-1,-1):
            if not c.compare(p,j,t,i+j):
                i += table[first]
                break
            elif j == 0:
                results.append(i)
                i+=table[first]
    return results, c
def test_1():
    ref_file = open('./tests/data/input/optimization1.out.json',
                    'r',
                    encoding="utf-8")
    comp_file = open('./tests/data/input/optimization2.out.json',
                     'r',
                     encoding="utf-8")
    ref_content = json.loads(ref_file.read())
    comp_content = json.loads(comp_file.read())
    ref_file.close()
    comp_file.close()

    comp = Comparator(ref_content, comp_content)
    comp_results = comp.compare()

    assert isinstance(comp_results, List)
    assert len(comp_results) == 3

    # First result
    res = comp_results[0]
    assert isinstance(res, TestResult)
    assert res.file_path == '/home/evaluation/evaluation/pub/bench/lorem/ipsum/1'
    exit_diff = res.exit_diff
    assert isinstance(exit_diff, Diff)
    assert exit_diff.label == 'Exit value'
    assert exit_diff.reference == 4
    assert exit_diff.value == 2
    assert exit_diff.diff == -2
    assert exit_diff.variation == -50
    diffs = res.diffs
    assert isinstance(diffs, List)
    assert len(diffs) == 2
    diff_bound = diffs[0]
    assert diff_bound.label == 'bound'
    assert diff_bound.reference == 12
    assert diff_bound.value == 12
    assert diff_bound.diff == 0
    assert diff_bound.variation == 0
    diff_time = diffs[1]
    assert diff_time.label == 'time'
    assert diff_time.reference == 2
    assert diff_time.value == 1
    assert diff_time.diff == -1
    assert diff_time.variation == -50
Exemplo n.º 7
0
class Diler:
    class Client:
        class Status:
            pass

        class NotReady(Status):
            def ready(self):
                return False

        class Ready(Status):
            def ready(self):
                return True

        class Check(Ready):
            pass

        class Bet(Ready):
            pass

        class AllIn(Bet):
            pass

        class Called(Bet):
            pass

        class Rised(Bet):
            pass

        class Pass(Ready):
            pass

        def __init__(self, id, conn):
            self.rise_client = None
            self.conn = conn
            self.id = id
            self.cards = []
            self.status = Diler.Client.NotReady()
            self.bet = 0
            self.money = 1000
            self.pass = False

        def __eq__(self, other):
            return self.id == other.id

        def addCard(self, card):
            self.cards.append(card)

        def ready(self, max_bet):
            return self.money == 0 or self.bet >= max_bet or self.pass

    def __init__(self, server):
        self.server = server
        self.deck = createCards()
        self.table = []
        self.clients = []
        self.comparator = Comparator()
        self.rise_client = None
        self.bet = 0
        self.bank = 0
        self.big_blind = 100

    def getClient(self, client):
        missing = Diler.Client(client[1][1], client[0])
        if missing in self.clients:
            return self.clients[self.clients.index(missing)]
        self.clients.append(missing)
        return self.clients[-1]

    def request(self, client):
        card = self.getCard()
        self.getClient(client).addCard(card)
        return card

    def getCard(self):
        return self.deck.pop(randint(0, len(self.deck) - 1))

    def getState(self):
        return self.clients

    def roundRun(self):
        for client in filter(lambda x: type(x.status) != Diler.Client.Pass, self.clients):
            client.status = Diler.Client.NotReady()
            
        k = 0 if self.rise_client is None else self.rise_client
        
        while not all([client.ready() for client in self.clients]) or len(list(filter(lambda x: type(x.status) != Diler.Client.Pass, self.clients))) < 2:
            if not self.clients[k].ready():
                sleep(0.01)
                if self.bet > 0:
                    self.server.send(self.clients[k].conn, 'ask1 ' + str(bet - self.clients[k].bet))
                else:
                    self.server.send(self.clients[k].conn, 'ask0')
                ans = self.server.recv(self.clients[k].conn)
                self.broadcast('info: игрок ' + str(self.clients[k].id) + ' ответил ' + ans)
                if ans == 'check':
                    self.clients[k].status = Diler.Client.Check()
                elif ans == 'pass':
                    self.clients[k].status = Diler.Client.Pass()
                elif ans == 'call':
                    self.clients[k].status = Diler.Client.Called()
                elif ans[:4] == 'rise' or ans[:3] == 'bet':
                    for c in filter(lambda x: type(x.status) != Diler.Client.Pass, self.clients):
                        c.status = Diler.Client.NotReady()
                    self.clients[k].status = Diler.Client.Rised()
                    self.rise_client = k
                    bet = int(ans[4:])
                    self.bank += bet
                    self.clients[k].bet = bet
                else:
                    self.clients[k].status = Diler.Client.Pass()
                    print('error: непонятный ответ от клиента')
            k = (k + 1) % len(self.clients)

    def blind(self):
        self.bank += self.big_blind // 2
        self.bank += self.big_blind
        self.clients[0].bed(self.big_blind // 2)
        self.clients[1].bed(self.big_blind)
        self.bet = True
        return "Игрок " + str(self.clients[0].id) + " поставил " + str(self.big_blind // 2) + ", игрок " + str(self.clients[1].id) + " поставил " + str(self.big_blind)

    def flop(self):
        self.roundRun()
        for i in range(3):
            self.table.append(self.getCard())
        print('flop', ' '.join(map(str, self.table[0: 3])))
        return ' '.join(map(str, self.table))

    def turn(self):
        self.roundRun()
        self.table.append(self.getCard())
        print('turn', str(self.table[-1]))
        return str(self.table[-1])

    def river(self):
        self.roundRun()
        self.table.append(self.getCard())
        print('river', str(self.table[-1]))
        return str(self.table[-1])

    def opening(self):
        self.roundRun()
        clients = {}
        for client in filter(lambda x: type(x.status) != Diler.Client.Pass, self.clients):
            clients[client.id] = client.cards
        win = self.comparator.compare(clients, self.table)
        if len(win) == 1:
            res = 'победитель: ' + str(win[0])
        else:
            res = 'победители: ' + ', '.join(map(str, win))
        return res

    def game(self):
        self.broadcast(self.blind())
        self.broadcast(self.flop())
        self.broadcast(self.turn())
        self.broadcast(self.river())
        self.broadcast(self.opening())
        self.next_turn()
        self.broadcast("Спасибо за игру!")

    def broadcast(self, msg):
        for client in self.clients:
            self.server.send(client.conn, msg)

    def next_turn(self):
        self.clients.append(self.clients.pop(0))
Exemplo n.º 8
0
import sys
from comparator import Comparator

if __name__ == "__main__":
    args = sys.argv
    if len(args) != 3:
        print('incorrect args')
        sys.exit(0)

    comparator = Comparator()
    degree = comparator.compare(sys.argv[1], sys.argv[2])
    sys.stdout.write(str(degree))
    sys.exit(0)
Exemplo n.º 9
0
class Diler:
    class Client:
        class Status:
            pass

        class NotReady(Status):
            def ready(self):
                return False

        class Ready(Status):
            def ready(self):
                return True

        class Check(Ready):
            pass

        class AllIn(Ready):
            pass

        class Called(Ready):
            pass

        class Rised(Ready):
            pass

        class Pass(Ready):
            pass

        def __init__(self, id, conn):
            self.rise_client = None
            self.conn = conn
            self.id = id
            self.cards = []
            self.status = Diler.Client.NotReady()

        def __eq__(self, other):
            return self.id == other.id

        def addCard(self, card):
            self.cards.append(card)

        def ready(self):
            return self.status.ready()

    def __init__(self, server):
        self.server = server
        self.deck = createCards()
        self.table = []
        self.clients = []
        self.comparator = Comparator()
        self.rise_client = None

    def getClient(self, client):
        missing = Diler.Client(client[1][1], client[0])
        if missing in self.clients:
            return self.clients[self.clients.index(missing)]
        self.clients.append(missing)
        return self.clients[-1]

    def request(self, client):
        card = self.getCard()
        self.getClient(client).addCard(card)
        return card

    def getCard(self):
        return self.deck.pop(randint(0, len(self.deck) - 1))

    def getState(self):
        return self.clients

    def roundRun(self):
        if len(list(filter(lambda x: type(x.status) != Diler.Client.Pass, self.clients))) < 2:
            return

        for client in filter(lambda x: type(x.status) != Diler.Client.Pass, self.clients):
            client.status = Diler.Client.NotReady()
            
        k = 0 if self.rise_client is None else self.rise_client
        
        while not all([client.ready() for client in self.clients]):
            if not self.clients[k].ready():
                sleep(0.01)
                self.server.send(self.clients[k].conn, 'ask')
                ans = self.server.recv(self.clients[k].conn)
                self.server.broadcast('info: игрок ' + str(self.clients[k].id) + ' ответил ' + ans)
                if ans == 'pass':
                    self.clients[k].status = Diler.Client.Pass()
                elif ans == 'call':
                    self.clients[k].status = Diler.Client.Called()
                elif ans == 'rise':
                    for c in filter(lambda x: type(x.status) != Diler.Client.Pass, self.clients):
                        c.status = Diler.Client.NotReady()
                    self.clients[k].status = Diler.Client.Rised()
                    self.rise_client = k
                else:
                    self.clients[k].status = Diler.Client.Pass()
                    print('error: непонятный ответ от клиента')
            k = (k + 1) % len(self.clients)

    def flop(self):
        self.roundRun()
        for i in range(3):
            self.table.append(self.getCard())
        print('flop', ' '.join(map(str, self.table[0: 3])))
        return ' '.join(map(str, self.table))

    def turn(self):
        self.roundRun()
        self.table.append(self.getCard())
        print('turn', str(self.table[-1]))
        return str(self.table[-1])

    def river(self):
        self.roundRun()
        self.table.append(self.getCard())
        print('river', str(self.table[-1]))
        return str(self.table[-1])

    def opening(self):
        self.roundRun()
        clients = {}
        for client in filter(lambda x: type(x.status) != Diler.Client.Pass, self.clients):
            clients[client.id] = client.cards
        win = self.comparator.compare(clients, self.table)
        if len(win) == 1:
            res = 'победитель: ' + str(win[0])
        else:
            res = 'победители: ' + ', '.join(map(str, win))
        return res

    def next_turn(self):
        self.clients.append(self.clients.pop(0))
Exemplo n.º 10
0
class ComparatorXes(object):

    def __init__(self, filename,
            samp_num=1, samp_size=None,
            proj_size=None, proj_connected=True,
            nfilename=None, max_coef=10,
            smt_timeout_iter=0,
            smt_timeout_matrix=0,
            sanity_check=False):
        self.pach = PacH(filename,
            samp_num=samp_num, samp_size=samp_size,
            proj_size=proj_size, proj_connected=proj_connected,
            nfilename=nfilename, max_coef=max_coef,
            sanity_check=sanity_check)
        self.pach.parse()

        qhull = self.pach.qhull
        # Hull for NO SMT
        qhull_no_smt = copy.deepcopy(qhull)
        # Hull for SMT iterative simp
        qhull_smt_iter = copy.deepcopy(qhull)
        # Hull for SMT matrix simp
        qhull_smt_matrix = copy.deepcopy(qhull)

        self.comparator = Comparator(qhull_no_smt, qhull_smt_iter, qhull_smt_matrix,
                max_coef, smt_timeout_iter, smt_timeout_matrix)

    def generate_pnml(self):
        return self.comparator.generate_pnml(filename=self.pach.filename,
                reversed_dictionary=self.pach.reversed_dictionary)

    def compare(self,log_file='', event_dictionary={}):
        return self.comparator.compare(log_file=log_file, event_dictionary=event_dictionary)

    def generate_outputs(self):
        # For every benchmark, generate the output
        qhull = self.comparator.qhull_no_smt
        self.pach.output.get('times',{}).update(qhull.output.get('times',{}))
        self.pach.qhull = qhull
        self.pach.smt_matrix = False
        self.pach.smt_iter = False
        # Force initial complexity for effectiveness calculation
        self.pach.initial_complexity = self.comparator.no_smt_initial_complexity
        self.pach.generate_output_file()
        logger.info('Generated output for NO SMT simplification')
        qhull = self.comparator.qhull_smt_iter
        self.pach.output.get('times',{}).update(qhull.output.get('times',{}))
        self.pach.qhull = qhull
        self.pach.smt_matrix = False
        self.pach.smt_iter = True
        # Force initial complexity for effectiveness calculation
        self.pach.initial_complexity = self.comparator.iter_initial_complexity
        self.pach.generate_output_file()
        logger.info('Generated output for Iterative SMT simplification')
        qhull = self.comparator.qhull_smt_matrix
        self.pach.output.get('times',{}).update(qhull.output.get('times',{}))
        self.pach.qhull = qhull
        self.pach.smt_matrix = True
        self.pach.smt_iter = False
        # Force initial complexity for effectiveness calculation
        self.pach.initial_complexity = self.comparator.matrix_initial_complexity
        self.pach.generate_output_file()
        logger.info('Generated output for Matrix SMT simplification')
        return True
Exemplo n.º 11
0
def main():
    station = 'Działoszyn - PM10'
    from_datetime = datetime(year=2020, month=3, day=1, hour=0, minute=0)
    to_datetime = datetime(year=2020, month=6, day=30, hour=23, minute=0)
    comparator = Comparator(station, from_datetime, to_datetime)
    comparator.compare().plot()
Exemplo n.º 12
0
class Diler:
    class Client:
        def __init__(self, id, conn):
            self.conn = conn
            self.id = id
            self.cards = []
            self.bet = 0
            self.money = 1000
            self.in_game = True
            self.big_blind = False

        def __eq__(self, other):
            return self.id == other.id

        def addCard(self, card):
            assert(len(self.cards) < 2)
            self.cards.append(card)

        def skip(self, max_bet):
            return self.money == 0 or self.bet >= max_bet or not self.in_game or not self.big_blind

    def __init__(self, server):
        self.server = server
        self.deck = createCards()
        self.table = []
        self.clients = []
        self.comparator = Comparator()
        self.rise_client = None
        self.bet = 0
        self.bank = [0]
        self.big_blind = 100

    def getClient(self, client):
        missing = Diler.Client(client[1][1], client[0])
        if missing in self.clients:
            return self.clients[self.clients.index(missing)]
        self.clients.append(missing)
        return self.clients[-1]

    def request(self, client):
        card = self.getCard()
        self.getClient(client).addCard(card)
        return card

    def getCard(self):
        return self.deck.pop(randint(0, len(self.deck) - 1))

    def dispense(self):
        for client in self.clients:
            self.send(client.conn, str(self.request(client.id)))

    def roundRun(self):
        k = 0 if self.rise_client is None else self.rise_client
        while not all([client.skip() for client in self.clients]) and len(list(filter(lambda client: client.in_game, self.clients))) > 1:
            if not self.clients[k].skip():
                sleep(0.01)
                request = ['fold', 'rise']
                if self.bet == 0 or self.clients[k].big_blind and self.clients[k].bet == self.bet:
                    request.append('check')
                else:
                    request.append('call')
                self.send(self.clients[k].conn, '|'.join(request))
                ans = self.server.recv(self.clients[k].conn)
                self.broadcast('info: игрок ' + str(self.clients[k].id) + ' ответил ' + ans)
                if ans.count('check') > 0:
                    self.
                elif ans.count('fold') > 0:
                    self.clients[k].in_game = False
                elif ans.count('call') > 0:
                    self.clients[k].bet = self.bet
                elif ans.count('rise') > 0:
                    self.clients[k].bet = int(ans.split()[1])
                    assert(self.bet < self.clients[k].bet)
                    self.bet = self.clients[k].bet
                    self.rise_client = k
                    self.bank += self.bet
                else:
                    assert(False)
            k = (k + 1) % len(self.clients)
        for client in self.clients:
            client.bet = 0

    def pre_flop(self):
        for i in range(2):
            self.dispense()
        self.bank += self.big_blind // 2
        self.bank += self.big_blind
        self.clients[0].bed = self.big_blind // 2
        self.clients[1].bed = self.big_blind
        self.clients[1].big_blind = True
        self.bet = self.big_blind
        return "Игрок " + str(self.clients[0].id) + " поставил " + str(self.big_blind // 2) + ", игрок " + str(self.clients[1].id) + " поставил " + str(self.big_blind)

    def flop(self):
        self.bet = 0
        self.roundRun()
        for i in range(3):
            self.table.append(self.getCard())
        print('flop', ' '.join(map(str, self.table[0: 3])))
        return ' '.join(map(str, self.table))

    def turn(self):
        self.bet = 0
        self.roundRun()
        self.table.append(self.getCard())
        print('turn', str(self.table[-1]))
        return str(self.table[-1])

    def river(self):
        self.bet = 0
        self.roundRun()
        self.table.append(self.getCard())
        print('river', str(self.table[-1]))
        return str(self.table[-1])

    def opening(self):
        self.bet = 0
        self.roundRun()
        clients = {}
        for client in filter(lambda x: type(x.status) != Diler.Client.Pass, self.clients):
            clients[client.id] = client.cards
        win = self.comparator.compare(clients, self.table)
        if len(win) == 1:
            res = 'победитель: ' + str(win[0])
        else:
            res = 'победители: ' + ', '.join(map(str, win))
        return res

    def game(self):
        self.broadcast(self.pre_flop())
        self.broadcast(self.flop())
        self.broadcast(self.turn())
        self.broadcast(self.river())
        self.broadcast(self.opening())
        self.next_turn()
        self.broadcast("Спасибо за игру!")

    def broadcast(self, msg):
        for client in self.clients:
            self.server.send(client.conn, msg)

    def next_turn(self):
        self.clients.append(self.clients.pop(0))
Exemplo n.º 13
0
    argv = docopt(__doc__)

    if argv['seq']:
        source_genome = argv['<reference>']

        avg_quality = int(argv['--quality'])
        if avg_quality < Sequencer.quality_min or avg_quality > Sequencer.quality_max:
            raise ValueError(
                "Average quality of nucleotides must be from {} to {}. Try again..."
                .format(Sequencer.quality_min, Sequencer.quality_max))

        coverage = float(argv['--coverage'])
        if coverage < 0 or coverage > 2:
            raise ValueError("Coverage must be real value from 0 to 2.")

        print(
            "Started sequencing with the average nucleotide quality of {} and the coverage of {}."
            .format(avg_quality, coverage))

        my_sequencer = Sequencer(source_genome, avg_quality, coverage)
        my_sequencer.simulate()

        print("The reads are ready! Check your folder...")
    elif argv['cmp']:
        my_comparator = Comparator(
            argv['--aln_src'],
            argv['<aln_trgt>'],
        )
        my_comparator.compare()