Ejemplo n.º 1
0
 def scanBool(self, source):
     if Symbol.isBooleanTrue(self.symbol_buffer):
         return Token(TokenType.BOOL_TRUE, self.symbol_buffer, self.start_position, self.current_position)
     elif Symbol.isBooleanFalse(self.symbol_buffer):
         return Token(TokenType.BOOL_FALSE, self.symbol_buffer, self.start_position, self.current_position)
     
     pos_str = self.positionToString(self.current_position)
     raise ScanException('Error scanning boolean at %s.' % (pos_str) )
Ejemplo n.º 2
0
 def scanObject(self, source):
     while Symbol.isCharacter(self.current_symbol):
         self.acceptSymbol(source)
         
     if Symbol.isSeparator(self.current_symbol):
         return Token(TokenType.OBJECT, self.symbol_buffer, self.start_position, self.current_position)
     
     pos_str = self.positionToString(self.current_position)
     raise ScanException('Error scanning object at %s.' % (pos_str) )
Ejemplo n.º 3
0
 def scanProperty(self, source):
     while Symbol.isCharacter(self.current_symbol):
         self.acceptSymbol(source)
         
     if Symbol.isColon(self.current_symbol):
         return Token(TokenType.PROPERTY, self.symbol_buffer, self.start_position, self.current_position)
     
     pos_str = self.positionToString(self.current_position)
     raise ScanException('Error scanning property at %s.' % (pos_str) )
Ejemplo n.º 4
0
 def scanDigit(self, source):
     while Symbol.isDigit(self.current_symbol):
         self.acceptSymbol(source)
         
     if Symbol.isDecimalPoint(self.current_symbol):
         return self.scanFloat(source)
     elif Symbol.isSeparator(self.current_symbol):
         return self.scanInt(source)
     else:
         pos_str = self.positionToString(self.current_position)
         raise ScanException('Error scanning digit at %s.' % (pos_str) )
Ejemplo n.º 5
0
 def scanDash(self, source):
     self.acceptSymbol(source)
     if Symbol.isCharacter(self.current_symbol):
         return self.scanObject(source)
     elif Symbol.isDigit(self.current_symbol):
         return self.scanDigit(source)
     elif Symbol.isDecimalPoint(self.current_symbol):
         return self.scanFloat(source)
     else:
         pos_str = self.positionToString(self.current_position)
         raise ScanException('Error scanning dash at %s.' % (pos_str) )
Ejemplo n.º 6
0
 def scanChar(self, source):
     while Symbol.isCharacter(self.current_symbol):
         self.acceptSymbol(source)
         
     if Symbol.isColon(self.current_symbol):
         return self.scanProperty(source)
     elif Symbol.isSeparator(self.current_symbol):
         return self.scanBool(source)
     else:
         pos_str = self.positionToString(self.current_position)
         raise ScanException('Error scanning character at %s.' % (pos_str) )
Ejemplo n.º 7
0
 def scan(self, source):
     self.current_symbol, self.current_position = source.getNextSymbol()
     self.start_position = deepcopy( self.current_position )
     
     while True:
         if Symbol.isComment(self.current_symbol):
             self.scanComment(source)
         elif Symbol.isSeparator(self.current_symbol):
             self.scanSeperator(source)
         elif Symbol.isEof(self.current_symbol):
             return None
         else:
             return self.scanToken(source)
 def send(self, m_i):
     smsg = TxSerialMsg()
     #smsg.set_counter(self.counter)
     smsg.set_crow(self.current_row)
     #smsg.set_V_row(self.A[self.current_row])
     smsg.set_V_row(V[m_i, :])
     smsg.set_data(self.tx_symbols[:, m_i])
     Symbol(V[self.current_row, :], self.W, self.map)
     smsg.set_data(self.sym[self.current_row])
     self.mif.sendMsg(self.source, 0xFFFF, smsg.get_amType(), 0, smsg)
Ejemplo n.º 9
0
 def scanString(self, source, start_symbol):
     self.acceptSymbol(source)
     
     while not Symbol.isQuote(self.current_symbol, start_symbol):
         self.acceptSymbol(source)
         self.testForEof()
         
     self.acceptSymbol(source)
     
     return Token(TokenType.STRING, self.symbol_buffer, self.start_position, self.current_position)
Ejemplo n.º 10
0
 def scanCode(self, source):
     self.acceptSymbol(source)
     
     while not Symbol.isRightCurlyBrace(self.current_symbol):
         self.acceptSymbol(source)
         self.testForEof()
         
     self.acceptSymbol(source)
     
     return Token(TokenType.CODE, self.symbol_buffer, self.start_position, self.current_position)
Ejemplo n.º 11
0
def parseJsonResult(result):
    data = json.loads(result)
    
    strOut = ""
    
    print(data)
    
    #Checking if the actual result from yahoo is empty.
    #Occasionally this would come back as none causing an exception
    if data['query']['results'] is not None:
        for idx, val in enumerate(data['query']['results']['quote']):
            tempSymbol = Symbol( val['symbol'], val['LastTradePriceOnly'], val['ChangeRealtime'], val['Volume'])
            
            strOut += tempSymbol.toString() + ' | '
    
            if(idx < len(data)-1):
                strOut += " | "
    
    return strOut
    
Ejemplo n.º 12
0
 def __init__(self, four_list_str, symbol_map_str):
     four_list_json = json.loads(four_list_str)
     for j in four_list_json:
         self.__four_list.append(Four(j))
     symbol_map_json = json.loads(symbol_map_str)
     symbol_map_json = [
         s for s in symbol_map_json if s['type'] == 2 and s['token'] != 0
     ]
     for j in symbol_map_json:
         s = Symbol(j)
         self.__symbol_map[s.content] = s
Ejemplo n.º 13
0
  def __init__(self,
      s_symbol=None,
      s_attribute=None,
      s_value=None,
      s_bias=None,
      symbol_obj=None,
    ):
    self.s_symbol       = s_symbol
    self.symbol_obj     = symbol_obj
    self.s_attribute    = s_attribute
    self.s_value        = s_value
    self.s_bias         = s_bias
    self.f_current_val  = None

    if not symbol_obj and s_symbol:
      self.symbol_obj = Symbol.get_from_symbol_dict(s_symbol)
    return None
Ejemplo n.º 14
0
    def generate(self):
        # Generates productions of the grammar.

        super(ProductionGenerator, self).__init__()
        left, right = self.str_productions.split(":=")
        left = left.strip()
        productions_split = right.split("|")
        productions = []
        for str_production in productions_split:
            q = []
            for symbol in str_production.strip().split(" "):
                if symbol != "E":  # TODO: Set Epsila as global variable.
                    q.append(Symbol(symbol, self.grammar))
            productions.append(q)

        # Create a list of production objects and return
        return [Production(left, production, self.grammar) \
               for production in productions]
Ejemplo n.º 15
0
 def scanToken(self, source):
     self.symbol_buffer = ''
     
     if Symbol.isTilda(self.current_symbol):
         return self.scanAggregateProperty(source)
     elif Symbol.isSingleQuote(self.current_symbol):
         return self.scanString(Symbol.SINGLE_QUOTE[0])
     elif Symbol.isDoubleQuote(self.current_symbol):
         return self.scanString(Symbol.DOUBLE_QUOTE[0])
     elif Symbol.isLeftCurlyBrace(self.current_symbol):
         return self.scanCode(source)
     elif Symbol.isLeftBrace(self.current_symbol):
         return self.scanLeftBrace(source)
     elif Symbol.isRightBrace(self.current_symbol):
         return self.scanRightBrace(source)
     elif Symbol.isDash(self.current_symbol):
         return self.scanDash(source)
     elif Symbol.isDigit(self.current_symbol):
         return self.scanDigit(source)
     elif Symbol.isCharacter(self.current_symbol):
         return self.scanChar(source)
     else:
         pos_str = self.positionToString(self.current_position)
         raise ScanException('Error scanning token at %s.' % (pos_str) )
Ejemplo n.º 16
0
    def set_grid(self, row, column, screen, current_player):
        if self.grid_is_empty(row, column):
            # Set with new grid change.
            # Get symbols
            symbols = Symbol.load_symbol(current_player.get_symbol())
            self.grid[row][column] = symbols[0]
            # Draw grid.
            screen.blit(
                symbols[1],
                (self.grid_position[row][column][0],
                 self.grid_position[row][column][1]),
            )

            done = self.check_game_won(screen, row, column,
                                       current_player.get_symbol())
            self.change_player()
            return done
        else:
            print('Cannot put grid here.')
Ejemplo n.º 17
0
    def insert(self, sym: Symbol):
        """Add a symbol to the table.
        
        @params sym: a Symbol object
        
        The function gets the name of the symbol to use as it's
        table key. Then, if there is no key of that name in the
        table, it inserts the key:symbol pair (note that it only checks
        the current scope, not it's parent). If a key with that
        name already exists, an exception is raised to notify the
        error handler that the compiler tried to insert a duplicate
        key (the compiler should never try to do this).
        """
        key = sym.getName()

        if key not in self:
            self[key] = sym
            self.__symbols += 1
        else:
            raise DuplicateSymbolException(key, self.__descr)
Ejemplo n.º 18
0
 def insert(self, sym: Symbol):
     """Add a symbol to the table.
     
     @params sym: a Symbol object
     
     The function gets the name of the symbol to use as it's
     table key. Then, if there is no key of that name in the
     table, it inserts the key:symbol pair (note that it only checks
     the current scope, not it's parent). If a key with that
     name already exists, an exception is raised to notify the
     error handler that the compiler tried to insert a duplicate
     key (the compiler should never try to do this).
     """
     key = sym.getName()
     
     if key not in self:
         self[key] = sym
         self.__symbols += 1
     else:
         raise DuplicateSymbolException(key, self.__descr)
Ejemplo n.º 19
0
 def scanFloat(self, source):
     while Symbol.isDigit(self.current_symbol):
         self.acceptSymbol(source)
         
     if Symbol.isSeparator(self.current_symbol):
         return Token(TokenType.FLOAT, self.symbol_buffer, self.start_position, self.current_position)
     elif Symbol.isExponent(self.current_symbol):
         self.acceptSymbol(source)
         if Symbol.isDash(self.current_symbol):
             self.acceptSymbol(source)
             
             while Symbol.isDigit(self.current_symbol):
                 self.acceptSymbol(source)
                 
             if Symbol.isSeparator(self.current_symbol):
                 return Token(TokenType.FLOAT, self.symbol_buffer, self.start_position, self.current_position)
             
     pos_str = self.positionToString(self.current_position)
     raise ScanException('Error scanning float at %s.' % (pos_str) )
Ejemplo n.º 20
0
open(outputPath, 'w').close()
open(symbolOutputPath, 'w').close()
#check and write to output 
f = open(outputPath, 'w')   
fSymbol = open(symbolOutputPath, 'w')   

ti = TechIndicators(key=cfg.APIKey, output_format=cfg.format)
ts = TimeSeries(key=cfg.APIKey, output_format=cfg.format)

len = symbols.__len__()
count = 1
for stock in symbols:
    print 'checking #' + stock
    print (count*100/len).__str__() + '%'
    count += 1
    symbolObj = Symbol(stock, cfg.intervalDaily, ts, ti)
    try:
        bullish, flag, info, rate = symbolObj.rate(MAMustBull=True, CandleMustBull=True)
    except:
        continue  

    if bullish:
        info = rate.__str__() + '\n' + info + '\n\n'
        print info
        f.write(info)
        fSymbol.write(stock+',')
    print '\n'
  
    
f.close()
fSymbol.close()
Ejemplo n.º 21
0
    def receive(
        self, src, msg
    ):  #make this main_loop and have it call tdma_stage and index_stage?, or set different modes in the other functions
        #tdma tx, index tx, or completed depending on mode
        if self.TDMA_MODE == 1:
            #print 'ileft is ', self.ileft, ', size if tdleft is  ', np.size(self.TDleft)
            if self.ileft == np.size(self.TDleft):
                self.ileft = 0
                #only update acklist here?
                #not completely correct?? what if size changes inbetween?
                #only update tdleft here?
                self.TDleft = np.nonzero(np.isnan(self.ackList.reshape(-1)))[0]
            print 'RECEIVE FUNCTION (TDMA)'
            rmsg = T2HMsg(msg.dataGet())
            #check for acks, remove nodes with ack type 1 from TDMAleft, record transmissions?
            newAck = rmsg.get_ACKs()
            print 'Acks for transmission number ', rmsg.get_transmission(
            ), ': ', newAck  #first one is 8? 2? garbage value
            #print 'Element equal to 1: ', np.array(newAck)==1 #want this to be an array of logicals
            self.ackList[np.array(newAck) == 1] = 1
            #self.TDleft = np.nonzero(np.isnan(self.ackList.reshape(-1)))[0]
            #call tdma_stage(self) at end if np.any(np.isnan(self.ackList))
            if np.any(np.isnan(self.ackList)):
                #self.tm = self.tm + 1
                #for i in self.TDleft:
                Transmitter.tdma_stage(self)
                self.ileft += 1

            else:
                print 'Finished TDMA after ', self.TDMA_TRANSMISSIONS, ' transmissions.'  #use get_transmission from receive function? will it make a difference?
                #COMPUTE ATTEMPTS PER NODE??
                self.TDMA_MODE = 0
                #initialize and proceed to index coding mode
                self.m_i = 0
                self.i = 1
                self.m = 0
                self.unsolved = self.map > -50
                #array of true the size of self.map
                self.rx_symbols = 0
                self.eps_vec = 0 * np.ones(self.N)
                R = transmit_messages(1, self.eps_vec[self.map])
                self.rx_symbols = R
                #send the first index message here? call compute_matrices for the first time here?
                #handle first case here?

        elif self.TDMA_MODE == 0:
            print 'RECEIVE FUNCTION (INDEX CODING)'
            #get next set of messages
            #if self.m_i == m or self.i == 0:
            #update data structures and map (next unsolved vector) once the round has been completed
            #if self.m_i == self.m or np.any(~self.unsolved):
            #self.m_i = 0;
            if self.TOTAL_TRANSMISSIONS == 0:
                self.map = np.nonzero(np.isnan(
                    self.final_messages.reshape(-1)))[0]
                self.rx_symbols = self.rx_symbols[self.unsolved, :]
                self.J = self.J[self.unsolved, :]
                self.I = self.I[self.unsolved, :]
                self.A = self.A[self.unsolved, :]
                Transmitter.compute_matrices(self)
                #time.sleep(3)
                #case for first transmission, must compute matrices first?
                self.TOTAL_TRANSMISSIONS = 1
                Transmitter.index_stage(self)
                #self.m_i += 1
                #self.i += 1
                return

            #if self.m_i == self.m or np.any(~self.unsolved):
            ##Transmitter.compute_matrices(self)
            #self.map = np.nonzero(np.isnan(self.final_messages.reshape(-1)))[0]
            #self.rx_symbols = self.rx_symbols[self.unsolved, :]
            #self.J = self.J[self.unsolved, :]
            #self.I = self.I[self.unsolved, :]
            #self.A = self.A[self.unsolved, :]
            #Transmitter.compute_matrices(self)
            ##case for first transmission, must compute matrices first?
            #if self.TOTAL_TRANSMISSIONS == 0:
            #self.TOTAL_TRANSMISSIONS = 1
            #Transmitter.index_stage(self)
            #self.m_i += 1
            #self.i += 1
            #return


#

            rmsgx = T2HMsg(msg.dataGet())
            #check for acks, remove nodes with ack type 1 from TDMAleft, record transmissions?
            newAck = np.array(rmsgx.get_ACKs())
            #print 'Acks for transmission number ', rmsgx.get_transmission(), ': ', newAck
            print 'RX ACKS: ', newAck
            print 'Remaining nodes: ', self.map
            self.unsolved = newAck[self.map] != 1
            #self.final_messages2 = self.final_messages
            self.final_messages[newAck == 1] = 1
            #CALCULATE ERASURES FROM THE NUMBER OF 2S
            #self.unsolved = self.final_messages != 1
            #print 'Rx DEST ', self.dest
            #print 'Rx NEW UNSOLVED: ', self.unsolved
            #print 'Rx NEW finalmessages: '
            #print self.final_messages

            if self.m_i == self.m or np.any(~self.unsolved):
                #Transmitter.compute_matrices(self)
                self.m_i = 0
                self.map = np.nonzero(np.isnan(
                    self.final_messages.reshape(-1)))[0]
                self.rx_symbols = self.rx_symbols[self.unsolved, :]
                self.J = self.J[self.unsolved, :]
                self.I = self.I[self.unsolved, :]
                self.A = self.A[self.unsolved, :]
                Transmitter.compute_matrices(self)
                #time.sleep(3)

            #send to all motes at end if np.any(np.isnan(self.final_messages)) ??
            if np.any(np.isnan(self.final_messages)):
                #print 'm_i' ,self.m_i
                self.tx_symbols = np.append(
                    self.tx_symbols,
                    Symbol(self.V[self.m_i, :], self.W, self.map))
                R = transmit_messages(1, self.eps_vec[self.map])
                if self.i == 1:
                    self.rx_symbols = R
                else:
                    self.rx_symbols = np.bmat([self.rx_symbols, R])
                #if self.verbose:
                #print 'Transmission ', self.m_i+1, '/', self.m  #m_i+1 or now just m_i ???
                #print self.rx_symbols.astype(int)
                self.TOTAL_TRANSMISSIONS += 1
                Transmitter.index_stage(self)
                #self.m_i += 1
                #self.i += 1
                #Transmitter.compute_matrices(self)
                #print 'late unsolved is ', self.unsolved
            else:
                if self.verbose:
                    print 'ITERATION', self.it, ', INDEX CODING TRANSMISSIONS:', self.TOTAL_TRANSMISSIONS
                #COMPUTE ATTEMPTS PER NODE?
                #self.TDMA_MODE = -1
                #call cleanup and reset functions!!!!!
                Transmitter.cleanup(self)
                if (self.it < self.itMax):
                    Transmitter.reset(self)
                else:
                    self.TDMA_MODE = -1
                return self.TOTAL_TRANSMISSIONS  #also exit program?
        else:
            #completed, print this indefinitely
            #print 'INDEX CODING COMPLETE: Total number of transmissions: ', self.TOTAL_TRANSMISSIONS
            print self.it, 'ITERATIONS COMPLETE'
            return self.TOTAL_TRANSMISSIONS
Ejemplo n.º 22
0
def defsym(sym):
    command = "__builtin__."+sym+"=FSymbol('"+sym+"')"
    exec command

def deflop(lop):
    command = "__builtin__."+lop+"=LOperator('"+lop+"')"
    exec command

# checks if a given symbol is already definend

THEN = Infix(lambda x,y:KB.__kb__.make_fc_rule(x,y))
IF = Infix(lambda x,y:KB.__kb__.make_bc_rule(x,y))
#THAT = Infix(lambda x,y:KB.__kb__.make_and_concept(x,y))

NOT_GIVEN   = Symbol("NOT_GIVEN")
NOT_FOUND   = Symbol("NOT_FOUND")

#This function sets up common variable names
#and logic operators and returns a new KB
#possibly to be extended

def init():
    kb=KB()
    # initializing standard variables
    # variables are uppercase letters
    defvar('_')
    for var in string.uppercase:
        defvar(var)
        defvar(var+"1")
        defvar(var+"2")
# Class: CSCI 410 - Elements of Computing Systems
# Written in: Python 2.7

import sys, string, os
from Parser import Parser
from Code import Code
from Symbol import Symbol


infile = sys.argv[1]  # Sys.argv is the system argument list object

outfile = infile.replace(".asm", ".hack")
parse = Parser(infile)
outfilecontents = ""
code = Code()
sym = Symbol()
i = 0
numOfNonLabelSymbols = 0
while parse.hasMoreCommands():
    parse.advance()
    parse.output()
    parse.stripwhitespace()
    if len(parse.parsedline) != 0 and parse.parsedline != "\n" and parse.commandType() == 2:
        if not sym.contains(parse.symbol()):
            sym.addEntry(parse.symbol(), str(i))
    if len(parse.parsedline) != 0 and parse.parsedline != "\n" and parse.commandType() != 2:
        i += 1

parse = Parser(infile)
while parse.hasMoreCommands():
    parse.advance()
Ejemplo n.º 24
0
def initialize():
    global symbolTable
    symbolTable = Symbol()
Ejemplo n.º 25
0
 def scanSeperator(self, source):
     while Symbol.isSeparator(self.current_symbol):
         self.current_symbol, self.current_position = source.getNextSymbol()
Ejemplo n.º 26
0
 def scanComment(self, source):
     while not Symbol.isEol(self.current_symbol):
         self.current_symbol, self.current_position = source.getNextSymbol()
         
     self.current_symbol, self.current_position = source.getNextSymbol()
Ejemplo n.º 27
0
from git import Repo

PATH_OF_GIT_REPO = r'.git'  # make sure .git folder is properly configured
COMMIT_MESSAGE = 'update'


def git_push():
    try:
        repo = Repo(PATH_OF_GIT_REPO)
        repo.git.add(update=True)
        repo.index.commit(COMMIT_MESSAGE)
        origin = repo.remote(name='origin')
        origin.push()
    except:
        print('Some error occured while pushing the code')


sl = 3600 * 24
while True:
    today = [[
        Symbol.from_url(ohlcurl + x, macdurl + x, '5min', x) for x in symbols
    ]]
    fname = '/home/sergio/github/algotrader/data/' + '_'.join(
        time.ctime().split()) + '.pkl'
    with open(fname, 'w+') as f:
        pk.dump(today, f)
    print('done')
    git_push()

    time.sleep(sl)
Ejemplo n.º 28
0
    def main_loop(self):
        eps_vec = .5 * np.ones(self.N)
        i = 1
        while np.any(np.isnan(self.final_messages)):
            Kprime = len(self.map)
            if self.verbose:
                print 'Remaining ', Kprime, ' nodes are: '
                print self.map

            ## special case for one remaining node
            if Kprime == 1:
                self.TOTAL_TRANSMISSIONS += 1
                while not transmit_messages(1, eps_vec[self.map]):
                    self.TOTAL_TRANSMISSIONS += 1
                self.final_messages[self.map] = self.W[self.map]
            else:
                ## Generate next m transmissions
                (V, U) = alignment('mixed', self.J, 1e-4, 100, False)
                m = np.shape(V)[0]
                if self.verbose:
                    print 'Minimum rank is ', m

                # generate next symbol based on current V
                L = len(self.tx_symbols)
                if i == 1:
                    L = 0

                unsolved = np.ones(Kprime) > 0
                m_i = 0
                while np.all(unsolved) and m_i < m:
                    self.tx_symbols = np.append(
                        self.tx_symbols, Symbol(V[m_i, :], self.W, self.map))
                    R = transmit_messages(1, eps_vec[self.map])
                    if i == 1:
                        self.rx_symbols = R
                    else:
                        self.rx_symbols = np.bmat([self.rx_symbols, R])
                    if self.verbose:
                        print 'Transmission ', m_i + 1, '/', m
                        print self.rx_symbols.astype(int)
                    self.TOTAL_TRANSMISSIONS += 1
                    # solve for messages if possible
                    #SEND TO TARGET HERE
                    (unsolved, final_messages) = bs_decode_messages(
                        self.dest, Kprime, self.map, self.rx_symbols,
                        self.tx_symbols, self.A, self.I, self.J, self.W,
                        self.final_messages, self.verbose)
                    #RECEIVE FROM TARGET HERE
                    #INTERPRET ACKS HERE
                    m_i += 1
                    i += 1
                    self.final_messages = final_messages
                # update data structures
                self.map = np.nonzero(np.isnan(
                    self.final_messages.reshape(-1)))[0]
                self.rx_symbols = self.rx_symbols[unsolved, :]
                self.J = self.J[unsolved, :]
                self.I = self.I[unsolved, :]
                self.A = self.A[unsolved, :]
        if self.verbose:
            print 'Total number of transmissions: ', self.TOTAL_TRANSMISSIONS
        return self.TOTAL_TRANSMISSIONS
Ejemplo n.º 29
0
    def main_loop(self):  #change to compute_matrixes
        smsgx = TxSerialMsg()
        self.TDMA_MODE = 0
        eps_vec = .5 * np.ones(self.N)
        i = 1
        while np.any(np.isnan(self.final_messages)):
            Kprime = len(self.map)
            if self.verbose:
                print 'Remaining ', Kprime, ' nodes are: '
                print self.map

            ## special case for one remaining node
            if Kprime == 1:
                self.TOTAL_TRANSMISSIONS += 1
                while not transmit_messages(1, eps_vec[self.map]):
                    self.TOTAL_TRANSMISSIONS += 1
                self.final_messages[self.map] = self.W[self.map]
            else:
                ## Generate next m transmissions
                (V, U) = alignment('mixed', self.J, 1e-4, 100, False)
                m = np.shape(V)[0]
                if self.verbose:
                    print 'Minimum rank is ', m

                # generate next symbol based on current V
                L = len(self.tx_symbols)
                if i == 1:
                    L = 0

                self.unsolved = np.ones(Kprime) > 0
                m_i = 0
                while np.all(self.unsolved) and m_i < m:
                    self.tx_symbols = np.append(
                        self.tx_symbols, Symbol(V[m_i, :], self.W, self.map))
                    R = transmit_messages(1, eps_vec[self.map])
                    if i == 1:
                        self.rx_symbols = R
                    else:
                        self.rx_symbols = np.bmat([self.rx_symbols, R])
                    if self.verbose:
                        print 'Transmission ', m_i + 1, '/', m
                        print self.rx_symbols.astype(int)
                    self.TOTAL_TRANSMISSIONS += 1
                    # solve for messages if possible
                    (self.unsolved, final_messages) = bs_decode_messages(
                        self.dest, Kprime, self.map, self.rx_symbols,
                        self.tx_symbols, self.A, self.I, self.J, self.W,
                        self.final_messages, self.verbose)
                    time.sleep(.2)
                    print 'UNSOLVED: ', self.unsolved
                    print 'MAP: ', self.map
                    #SEND TO TARGET HERE, rewrite these lines
                    #smsg.set_crow
                    print 'tx map ', self.map
                    smsgx.set_messageid(
                        255)  #now something to represent index coding, 255?
                    smsgx.set_data(np.dot(
                        V[m_i],
                        self.W,
                    ))
                    ##also send own message w[i] for comparison????
                    smsgx.set_V_row(V[m_i])
                    smsgx.set_current_transmission(self.TOTAL_TRANSMISSIONS)
                    self.mif.sendMsg(self.source, 0xFFFF, smsgx.get_amType(),
                                     0, smsgx)
                    #time.sleep(1) #.125 too fast?

                    #INTERPRET ACKS IN RECEIVE FUNCTION
                    m_i += 1
                    i += 1
                    self.final_messages = final_messages  #still need final messages??
                # update data structures
                self.map = np.nonzero(np.isnan(
                    self.final_messages.reshape(-1)))[0]
                self.rx_symbols = self.rx_symbols[self.unsolved, :]
                self.J = self.J[self.unsolved, :]
                self.I = self.I[self.unsolved, :]
                self.A = self.A[self.unsolved, :]
        if self.verbose:
            print 'Total number of transmissions: ', self.TOTAL_TRANSMISSIONS
        return self.TOTAL_TRANSMISSIONS
Ejemplo n.º 30
0
	def __init__(self, ticker, name, exchange, categoryName, categoryNr):
		Symbol.__init__(self, ticker, name, exchange)
		self.categoryName = categoryName
		self.categoryNr = categoryNr
Ejemplo n.º 31
0
    def makeERE(erlist, symbols):
        if type(erlist) is list:
            negflag = False
            orflag = False
            catflag = False
            andflag = False
            #need some initial ERE to make sure this works correctly
            currentERE = Empty()
            for ind, obj in enumerate(erlist):
                if obj == "*":
                    if ind == 0:
                        raise SyntaxError("Kleene closure must be after stuff")
                    currentERE = Kleene.getERE(currentERE)
                elif obj == "~":
                    negflag = True
                    continue
                elif obj == "|":
                    orflag = True
                    continue
                elif obj == "+":
                    catflag = True
                    continue
                elif obj == "&":
                    andflag = True
                    continue
                else:
                    if ind == 0 | negflag:
                        currentERE = EREMachine.makeERE(obj, symbols)
                    elif orflag:
                        currentERE = Or.getERE(
                            [currentERE,
                             EREMachine.makeERE(obj, symbols)])
                        orflag = False
                    elif catflag:
                        currentERE = Concat.getERE(
                            currentERE, EREMachine.makeERE(obj, symbols))
                        catflag = False
                    elif andflag:
                        currentERE = Negation.getERE(
                            Concat.getERE(
                                Negation.getERE(currentERE),
                                Negation.getERE(
                                    EREMachine.makeERE(obj, symbols))))
                        andflag = False
                    else:
                        currentERE = Concat.getERE(
                            currentERE, EREMachine.makeERE(obj, symbols))
                    if negflag:
                        currentERE = Negation.getERE(currentERE)
                        negflag = False
            return currentERE

        else:
            if erlist == 'empty':
                return Empty.getERE()
            elif erlist == 'epsilon':
                return Epsilon.getERE()
            elif erlist in symbols:
                return Symbol.getERE(erlist)
            elif not erlist:
                return
            else:
                raise ValueError(
                    'Either you have used a symbol not tied to event, or epsilon/empty is misspelled'
                )
Ejemplo n.º 32
0
 def testForEof(self):
     if Symbol.isEof(self.current_symbol):
         pos_str = self.positionToString(self.current_position)
         raise ScanException('Error scanning at %s.' % (pos_str) )
Ejemplo n.º 33
0
	def getRow(self):
		return Symbol.getRow(self) + [self.categoryName , self.categoryNr]
Ejemplo n.º 34
0
def make_test_data():
    #### ADDING USER AND TRIGGERS FOR EoD
    Users.add_user('hari')
    # create a symbol
    reliance = Symbol(name='Reliance',
                      y_symbol='RELIANCE.BO',
                      g_symbol='NSE:RELIANCE')
    # create a trigger
    trigger_list = []
    trigger_list.append(
        Trigger(
            # s_symbol='RELIANCE.BO',
            symbol_obj=reliance,
            s_attribute='RSI_period_1_param_10',
            s_value='10',
            s_bias='+',
        ))
    trigger_list.append(
        Trigger(
            symbol_obj=reliance,
            s_attribute='RSI_period_1_param_20',
            s_value='10',
            s_bias='+',
        ))
    trigger_list.append(
        Trigger(
            symbol_obj=reliance,
            s_attribute='Price_',
            s_value='10',
            s_bias='+',
        ))
    # useing trigger, create a reminder
    reminder = Reminder(trigger_list)
    Users.get_by_name('hari').add_reminder(reminder)

    #### ADDING USER AND TRIGGERS FOR intraday
    Users.add_user('hari_intraday')
    # create a symbol
    asianpaint = Symbol(name='Asianpaint',
                        y_symbol='ASIANPAINT.BO',
                        g_symbol='NSE:ASIANPAINT')
    # create a trigger
    trigger_list = []
    trigger_list.append(
        Trigger(
            symbol_obj=asianpaint,
            s_attribute='RSI_period_1_param_10_symbolmode_intraday',
            s_value='10',
            s_bias='+',
        ))
    trigger_list.append(
        Trigger(
            symbol_obj=asianpaint,
            s_attribute='RSI_period_1_param_20_symbolmode_intraday',
            s_value='10',
            s_bias='+',
        ))
    trigger_list.append(
        Trigger(
            symbol_obj=asianpaint,
            s_attribute='Price_symbolmode_intraday',
            s_value='10',
            s_bias='+',
        ))
    # useing trigger, create a reminder
    reminder = Reminder(trigger_list)
    Users.get_by_name('hari_intraday').add_reminder(reminder)
Ejemplo n.º 35
0
def bs_index_coding(K, eps, verbose=True, dest=False):
    if dest == False:
        rand_dest = True
    else:
        rand_dest = False

    eps_vec = eps * np.ones(K)

    if verbose:
        print ' '
        print 'Number of receivers/nodes: ', K
        print 'Erasure prob is ', eps
        print '-----------'

    # generate random messages
    W = np.random.randint(1, 257, (K, 1))

    # store final received messages. goal is to "de-NaN" by the end
    final_messages = np.nan * np.zeros((K, 1))
    # keep track of all transmitted and received messages/symbols
    tx_symbols = np.array([])  # [1 -by- # of transmissions]

    # keep track of number of transmissions
    TOTAL_TRANSMISSIONS = 0

    ## Base Station - to - cellular model
    # Uplink is assumed perfect, i.e. the BS has access to all messages and
    # their destinations
    if rand_dest:
        if verbose:
            print 'Message destinations chosen randomly'
        dest = singlerandperm(K)
        # receiver i wants message dest(i)
        print dest
    A = np.diag(W.reshape(
        -1))  # receiver (row) i has access to the message it plans to send
    mat_dest = (np.arange(K), np.array(dest))
    signal_space = np.zeros((K, K)) > 0
    signal_space[mat_dest] = True
    I = compute_interferers(A, signal_space)
    J = I.astype(float)
    J[mat_dest] = -1
    map = np.arange(K)

    if verbose:
        print 'Interferer matrix is:'
        print J

    i = 1
    while np.any(np.isnan(final_messages)):
        Kprime = len(map)
        if verbose:
            print 'Remaining ', Kprime, ' nodes are: '
            print map

        ## special case for one remaining node
        if Kprime == 1:
            TOTAL_TRANSMISSIONS = TOTAL_TRANSMISSIONS + 1
            while not transmit_messages(1, eps_vec[map]):
                TOTAL_TRANSMISSIONS = TOTAL_TRANSMISSIONS + 1
            final_messages[map] = W[map]
        else:
            ## Generate next m transmissions
            (V, U) = alignment('mixed', J, 1e-4, 100, False)
            m = np.shape(V)[0]
            if verbose:
                print 'Minimum rank is ', m

            # generate next symbol based on current V
            L = len(tx_symbols)
            if i == 1:
                L = 0

            unsolved = np.ones(Kprime) > 0
            m_i = 0
            while np.all(unsolved) and m_i < m:
                tx_symbols = np.append(tx_symbols, Symbol(V[m_i, :], W, map))
                R = transmit_messages(1, eps_vec[map])
                if i == 1:
                    rx_symbols = R
                else:
                    rx_symbols = np.bmat([rx_symbols, R])
                if verbose:
                    print 'Transmission ', m_i + 1, '/', m
                    print rx_symbols.astype(int)
                TOTAL_TRANSMISSIONS += 1
                # solve for messages if possible
                (unsolved, final_messages) = bs_decode_messages(
                    dest, Kprime, map, rx_symbols, tx_symbols, A, I, J, W,
                    final_messages, verbose)
                m_i += 1
                i += 1
            # update data structures
            map = np.nonzero(np.isnan(final_messages.reshape(-1)))[0]
            rx_symbols = rx_symbols[unsolved, :]
            J = J[unsolved, :]
            I = I[unsolved, :]
            A = A[unsolved, :]
    if verbose:
        print 'Total number of transmissions: ', TOTAL_TRANSMISSIONS
    return TOTAL_TRANSMISSIONS
Ejemplo n.º 36
0
    def domToSymtab(self, symtab):
        """construct symbols into table given from our dom read from file."""
        d = self.dom
        interfaces = d.getElementsByTagName("interfaceDeployment")
        for i in interfaces:
            s = Symbol(self.filename)
            s.readInterface(i)
            self.addSymtabEntry(symtab, s)

        classes = d.getElementsByTagName("classDeployment")
        for i in classes:
            s = Symbol(self.filename)
            s.readClass(i)
            self.addSymtabEntry(symtab, s)

        ports = d.getElementsByTagName("portDeployment")
        for i in ports:
            s = Symbol(self.filename)
            s.readPort(i)
            self.addSymtabEntry(symtab, s)

        components = d.getElementsByTagName("componentDeployment")
        for i in components:
            s = Symbol(self.filename)
            s.readComponent(i)
            self.addSymtabEntry(symtab, s)

        self.indexed = True