예제 #1
0
def isDownloadTriggered():
    trigger = 0

    try:
        if isExternalTriggered() == 1:
            ackExternalTrigger()
            trigger = 1
        elif isTimerExpired() == 1:
            trigger = 1
        else:
            trigger = 0

        if trigger == 1:
            if isMinimumTimerExpired() == 1:
                ackTimerTrigger()
                trigger = 1
            else:
                soclogging.logDebug(1, "Last Download less then " + '{:.0f}'.format(
                    parameters.getParameter('timerMinInterval') / 60) + " minutes ago. Cancelling download")
                trigger = 0

        if trigger == 1:
            if state.getState('charged') == 0 and state.getState('unplug') == 0:
                trigger = 0
                soclogging.logDebug(1, "Vehicle was not unplugged or charging since last download. Cancelling download")

    except:
        raise

    return trigger
예제 #2
0
def doExternalUpdate():
    attempt = 0

    if state.getState('lastSuccess') == 1:
        maxAttempt = 3
    else:
        maxAttempt = 1

    while attempt < maxAttempt:
        try:
            soc = soc_external.DownloadSoC()
        except:
            soc = 0
            raise

        if soc > 0:
            saveSoc(soc, 0)
            state.setState('lastSuccess', 1)
            break
        else:
            attempt += 1
            state.setState('lastSuccess', 0)
            if attempt < maxAttempt:
                soclogging.logDebug(2, "Retrying in 60 Seconds...")
                time.sleep(60)

    return
예제 #3
0
파일: main2.py 프로젝트: moonblade/smith
def main():
    count=1
    outputList=[]

    globalVariables.rawScoreMatrix = pickle.load(open(globalVariables.scoreMatrixFile,"rb"))
    globalVariables.states = pickle.load(open(globalVariables.statesFile,"rb"))
    globalVariables.timedStates = pickle.load(open(globalVariables.timedStatesFile,"rb"))
    # print(globalVariables.rawScoreMatrix)
    # print(globalVariables.states)
    # print(globalVariables.timedStates)
    with open(globalVariables.inputcsv, 'r') as csvfile:
        reader = csv.DictReader(csvfile)
        names=reader.fieldnames
        for row in reader:
            # Assuming that the sequences will be in the first two rows
            # Compute probabilities with sequence 1 and reverse of sequence 2
            seq1=row[names[0]]
            seq2=row[names[1]]
            scoreMatrix, startPos = score.initScoreMatrix(seq1,seq2)
            alinedOne, alinedTwo = score.traceback(scoreMatrix, startPos, seq1,seq2)
            alignmentString=score.alignment_string(alinedOne,alinedTwo)
            place=globalVariables.reverseEndIndex-globalVariables.reverseStartIndex-1
            stateNeeded=state.getState(alinedOne[::-1][place],alinedTwo[::-1][place])
            print(count)
            print(alinedOne)
            print(alignmentString)
            print(alinedTwo)
            print()
            outputList.append(str(count)+","+stateNeeded+","+str(globalVariables.timedStates[place][stateNeeded]['probability']))
            count+=1
    print()
    for line in outputList:
        print(line)
예제 #4
0
def Max_checkGeo_Region(inputType, compOpt):
	GeoArr  				= inputType.split(',')
	countryCode				= GeoArr[0]
	del GeoArr[0]
	


	ipaddress 			= os.environ["REMOTE_ADDR"]
	#ipaddress			= '169.149.12.64'
	# print(ipaddress)
	# sys.exit() 	
	reader 				= geoip2.database.Reader('limitation/GeoLite2-City.mmdb')
	try:
		response 				= reader.city(ipaddress)
		userCountryCode			= response.country.iso_code
		stateCode				= response.subdivisions.most_specific.iso_code
		state					= response.subdivisions.most_specific.name
		stateNumCode			= getState(userCountryCode,state)
	
		if(countryCode	== userCountryCode):
			if(stateNumCode and GeoArr.count(stateNumCode) > 0):
				return True
			else:
				return False
			return True
		else:
			return False
		return True
				
	except Exception:
		return False
	finally:
		reader.close()
예제 #5
0
def isTimerExpired():
    now = int(time.time())

    if state.isPlugged() == 1:
        secLeft = (state.getState('lastRun') + (parameters.getParameter('timerInterval') * 60)) - now
    else:
        secLeft = (state.getState('lastRun') + (parameters.getParameter('timerIntervalUnplug') * 60)) - now

    if secLeft < 0:
        trigger = 1
        soclogging.logDebug(1, "SoC download triggered by timer")
    else:
        trigger = 0
        soclogging.logDebug(2, "Next Update: " + '{:.1f}'.format(secLeft / 60) + " minutes")

    return trigger
예제 #6
0
def isMinimumTimerExpired():
    now = int(time.time())
    secSince = now - state.getState('lastRun')

    if secSince < parameters.getParameter('timerMinInterval'):
        trigger = 0
    else:
        trigger = 1

    return trigger
예제 #7
0
def doManualUpdate():
    try:
        f = open(parameters.getParameter('meterFile'), 'r')
        currentMeter = float(f.read())
        f.close()
    except:
        soclogging.logDebug(2, "Could not find current meter file")
        raise

    try:
        lastMeter = state.getState('lastMeter')
        lastSoc = state.getState('lastSoc')
        f.close()
    except:
        raise

    batterySize = parameters.getParameter('batterySize')
    efficiency = parameters.getParameter('efficiency')
    meterDiff = currentMeter - lastMeter
    meterDiffEff = meterDiff * (efficiency / 100)
    socDiff = 100 * (meterDiffEff / batterySize)
    newSoc = int(max(min(lastSoc + socDiff, 100), 1))

    soclogging.logDebug(
        2, "Charged since last update: " + '{:.3f}'.format(meterDiff) +
        " kWh = " + '{:.3f}'.format(meterDiffEff) + " kWh @ " +
        '{:.0f}'.format(efficiency) + "% efficency")
    soclogging.logDebug(
        2, "Charged since last update: " + '{:.3f}'.format(meterDiffEff) +
        " kWh of " + '{:.0f}'.format(batterySize) + " kWh = " +
        '{:.2f}'.format(socDiff) + "% SoC")
    soclogging.logDebug(
        1, "Estimated SoC: " + '{:.0f}'.format(lastSoc) +
        "% (last update) + " + '{:.2f}'.format(socDiff) +
        "% (extrapolation) = " + '{:.0f}'.format(newSoc) + "% SoC")

    saveSoc(newSoc, 1)

    return
예제 #8
0
파일: score.py 프로젝트: moonblade/smith
def alignment_string(aligned_seq1, aligned_seq2):
    # Build the string as a list of characters to avoid costly string
    # concatenation.
    idents, gaps, mismatches = 0, 0, 0
    alignment_string = []
    for base1, base2 in zip(aligned_seq1, aligned_seq2):
        if (getState(base1, base2) == 'mismatch'):
            alignment_string.append(' ')
            gaps += 1
        elif (base1 + base2 == 'CG' or base1 + base2 == 'GC'):
            alignment_string.append(':')
            idents += 1
        else:
            alignment_string.append('|')
            mismatches += 1

    return ''.join(alignment_string)
예제 #9
0
파일: score.py 프로젝트: moonblade/smith
def alignment_string(aligned_seq1, aligned_seq2):
    # Build the string as a list of characters to avoid costly string
    # concatenation.
    idents, gaps, mismatches = 0, 0, 0
    alignment_string = []
    for base1, base2 in zip(aligned_seq1, aligned_seq2):
        if (getState(base1,base2)=='mismatch'):
            alignment_string.append(' ')
            gaps += 1
        elif (base1+base2=='CG' or base1+base2=='GC'):
            alignment_string.append(':')
            idents += 1
        else:
            alignment_string.append('|')
            mismatches += 1

    return ''.join(alignment_string)
예제 #10
0
def main():
    # default sleep = 10 hours
    config = state.getState()
    if config['state'] >= 1:
        if config['state'] == 1:
            av.warning()
            state.trigger()
        else:
            if config['state'] == 2:
                state.notify()
                av.alarm()
            else:
                state.upone()
                av.alarm()
    #check BLE
    state.bt_check()
    #go to sleep
    py.setup_sleep(3600)
    py.go_to_sleep()
예제 #11
0
파일: main2.py 프로젝트: moonblade/smith
def main():
    count = 1
    outputList = []

    globalVariables.rawScoreMatrix = pickle.load(
        open(globalVariables.scoreMatrixFile, "rb"))
    globalVariables.states = pickle.load(open(globalVariables.statesFile,
                                              "rb"))
    globalVariables.timedStates = pickle.load(
        open(globalVariables.timedStatesFile, "rb"))
    # print(globalVariables.rawScoreMatrix)
    # print(globalVariables.states)
    # print(globalVariables.timedStates)
    with open(globalVariables.inputcsv, 'r') as csvfile:
        reader = csv.DictReader(csvfile)
        names = reader.fieldnames
        for row in reader:
            # Assuming that the sequences will be in the first two rows
            # Compute probabilities with sequence 1 and reverse of sequence 2
            seq1 = row[names[0]]
            seq2 = row[names[1]]
            scoreMatrix, startPos = score.initScoreMatrix(seq1, seq2)
            alinedOne, alinedTwo = score.traceback(scoreMatrix, startPos, seq1,
                                                   seq2)
            alignmentString = score.alignment_string(alinedOne, alinedTwo)
            place = globalVariables.reverseEndIndex - globalVariables.reverseStartIndex - 1
            stateNeeded = state.getState(alinedOne[::-1][place],
                                         alinedTwo[::-1][place])
            print(count)
            print(alinedOne)
            print(alignmentString)
            print(alinedTwo)
            print()
            outputList.append(
                str(count) + "," + stateNeeded + "," +
                str(globalVariables.timedStates[place][stateNeeded]
                    ['probability']))
            count += 1
    print()
    for line in outputList:
        print(line)
예제 #12
0
def main(places, transitions, silent, invisible=False):

    numberOfRestarts = 1000

    #initialize states to 0
    states = []
    for place in places:
        states.append(State(0, place, getTransitions(place.getId(), transitions)))
    
    #declare state for scope
    state = None
    
    #variable to keep track of how many iterations states don't change utilities
    noChange = 0
    total = 99999999
    oldTotal = 1
    converged = 0
    
    for i in range(numberOfRestarts):
        #select a random state to start in
        state = states[random.randint(0, len(states) -1)]
        if not silent and converged == 0: print '' #newline
        
        while not state.isTerminal():
            #update the utility for that state
            state.updateUtility(states)
            
            #use absolute value of oldTotal / total < .9999 as the indicator converged values
            values = []
            for x in states: values.append(x.getUtility())
            total = sum(values)
            if str(total) == str(oldTotal): noChange += 1
            else: noChange = 0
            
            oldTotal = total
            
            if noChange == 10: converged = i
            
            if not silent and converged == 0: print "State:{0}\tBest:{1}\tUtility({2})={3}={4}".format(str(state.getId()).ljust(3), state.getBestTransition().getActionAsString(),state.getId(),  state.getFormula(states), round(state.getUtility(),4))

            #if not a terminal, then choose the state from the best transition
            state = getState(state.getBestTransition().choosePlace(), states)
            
        #update and print terminal state
        state.updateUtility(states)
        
        if not silent and converged == 0: print "State:{0}\tBest:{1}\tUtility({2})={3}={4}".format(str(state.getId()).ljust(3), 'Terminal', state.getId(), state.getFormula(states, True), round(state.getUtility(),4))
        
    
    #output policy

    #output iteration of convergence
    if not invisible: print '\nConsidered converged on iteration {0} of {1}'.format(converged, numberOfRestarts)
    
    if not invisible: print '\nResults'
    if not invisible: print '-'*80
    for state in states:
        if not state.isTerminal(): 
            if not invisible: print 'State:{0}\tUtility = {1}\tPolicy = {2}'.format(str(state.getId()).ljust(3), str(state.getUtility()).ljust(15), state.getBestTransition().getActionAsString())
        else: 
            if not invisible: print 'State:{0}\tUtility = {1}\tPolicy = {2}'.format(str(state.getId()).ljust(3), str(state.getUtility()).ljust(15), 'Terminal')

    return converged