Skip to content

Commit

Permalink
clean up
Browse files Browse the repository at this point in the history
  • Loading branch information
mEDI-S committed Sep 23, 2015
1 parent 308adb1 commit 771c03b
Show file tree
Hide file tree
Showing 17 changed files with 760 additions and 693 deletions.
514 changes: 266 additions & 248 deletions elite/db.py

Large diffs are not rendered by default.

125 changes: 63 additions & 62 deletions elite/dealsroute.py
Expand Up @@ -5,16 +5,17 @@
@author: mEDI
'''

from datetime import datetime, date, time, timedelta
from datetime import datetime, timedelta
import elite


class route(object):
'''
calculate a A-B-A or A-B(x) route,
set speed control and result details over limitCalc()
'''

mydb=None
mydb = None
deals = []
forceHops = None
locked = None
Expand All @@ -23,16 +24,16 @@ class route(object):
options["startSystem"] = None
options["tradingHops"] = 2 # +1 for the back hop
options["maxJumpDistance"] = 16.3
options["maxDist"] = options["maxJumpDistance"]*3 # max distace for B system
options["maxSearchRange"] = options["maxJumpDistance"]*5 # on start search used
options["maxDist"] = options["maxJumpDistance"] * 3 # max distace for B system
options["maxSearchRange"] = options["maxJumpDistance"] * 5 # on start search used
options["maxStarDist"] = 1300
options["maxAge"] = 14 # max data age in days
options["minTradeProfit"] = 1000 # only to minimize results (speedup)
options["minStock"] = 50000 # > 10000 = stable route > 50000 = extrem stable route and faster results
options["resultLimit"] = None # calculated by self.limitCalc()
options["padsize"] = None # None = Any, allow a list
options["resultLimit"] = None # calculated by self.limitCalc()
options["padsize"] = None # None = Any, allow a list

maxAgeDate = None # calculated by setMaxAgeDate()
maxAgeDate = None # calculated by setMaxAgeDate()
elitetime = None

def __init__(self, mydb):
Expand All @@ -58,24 +59,24 @@ def getStationA(self, route, hopID):
if hopID == 0:
return route["path"][hopID]["StationA"]

return route["path"][hopID-1]["StationB"]
return route["path"][hopID - 1]["StationB"]

def getStationB(self, route, hopID):
if hopID < len(route["path"]):
return route["path"][hopID]["StationB"]
else: # back to start
else: # back to start
return route["path"][0]["StationA"]

def getSystemA(self, route, hopID):
if hopID == 0:
return route["path"][hopID]["SystemA"]

return route["path"][hopID-1]["SystemB"]
return route["path"][hopID - 1]["SystemB"]

def getSystemB(self,route,hopID):
def getSystemB(self, route, hopID):
if hopID < len(route["path"]):
return route["path"][hopID]["SystemB"]
else: # back to start
else: # back to start
return route["path"][0]["SystemA"]

def getRouteIDbyPointer(self, deal):
Expand All @@ -90,7 +91,7 @@ def getPriceID(self, route, hopID):

def limitCalc(self, accuracy=0):
''' ["normal","fast","nice","slow","all"] '''
maxResults = 100000 # normal
maxResults = 100000 # normal

if accuracy == 1:
maxResults = 5000
Expand All @@ -100,15 +101,15 @@ def limitCalc(self, accuracy=0):
maxResults = 4000000

if self.forceHops:
maxResults = maxResults*2
self.options["resultLimit"] = round( maxResults**(1.0 / self.options["tradingHops"] )) #max results = 1000000 = resultLimit^tradingHops
maxResults = maxResults * 2
self.options["resultLimit"] = round(maxResults ** (1.0 / self.options["tradingHops"])) # max results = 1000000 = resultLimit^tradingHops

if accuracy == 4:
self.options["resultLimit"] = 999999


def setMaxAgeDate(self):
self.maxAgeDate = datetime.utcnow() - timedelta(days = self.options["maxAge"] )
self.maxAgeDate = datetime.utcnow() - timedelta(days=self.options["maxAge"])

def calcRoute(self):
self.deals = []
Expand All @@ -121,18 +122,18 @@ def calcRoute(self):
self.calcRating()

def findStartDeal(self):
startdeals = self.mydb.getBestDealsinDistance( self.options["startSystem"], self.options["maxDist"], self.options["maxSearchRange"], self.maxAgeDate, self.options["maxStarDist"], self.options["minTradeProfit"], self.options["minStock"], self.options["resultLimit"], self.options["padsize"])
startdeals = self.mydb.getBestDealsinDistance(self.options["startSystem"], self.options["maxDist"], self.options["maxSearchRange"], self.maxAgeDate, self.options["maxStarDist"], self.options["minTradeProfit"], self.options["minStock"], self.options["resultLimit"], self.options["padsize"])

for deal in startdeals:
self.deals.append({ "profit":0, "time":0 , "path":[deal], "backToStartDeal":None, "activeRoute":None, "lastHop":None})
self.deals.append({ "profit": 0, "time": 0, "path": [deal], "backToStartDeal": None, "activeRoute": None, "lastHop": None})


def findHops(self):
for deep in range( 1, self.options["tradingHops"] ):
print("deep", deep+1)
for deep in range(1, self.options["tradingHops"]):
print("deep", deep + 1)
for deal in self.deals[:]:
if deep == len(deal["path"]):
delsX = self.mydb.getBestDealsFromStationInDistance(deal["path"][ len(deal["path"])-1 ]["StationBID"], self.options["maxDist"], self.maxAgeDate, self.options["maxStarDist"], self.options["minTradeProfit"], self.options["minStock"], self.options["resultLimit"], self.options["padsize"])
delsX = self.mydb.getBestDealsFromStationInDistance(deal["path"][ len(deal["path"]) - 1 ]["StationBID"], self.options["maxDist"], self.maxAgeDate, self.options["maxStarDist"], self.options["minTradeProfit"], self.options["minStock"], self.options["resultLimit"], self.options["padsize"])
for dealX in delsX:
''' if same item in route already exist?'''
ifExists = None
Expand All @@ -143,24 +144,25 @@ def findHops(self):

if not ifExists:
dealnew = deal.copy()
dealnew["path"] = list(deal["path"]) #deepcopy do not work
dealnew["path"] = list(deal["path"]) # deepcopy do not work

dealnew["path"].append(dealX)
self.deals.append(dealnew)

elif self.forceHops :
elif self.forceHops:
self.deals.remove(deal)

def delToShortRoutes(self):
if not self.forceHops: return
if not self.forceHops:
return

for deal in self.deals[:]:
if len(deal["path"]) < self.forceHops:
self.deals.remove(deal)

def findBackToStartDeals(self):
for deal in self.deals:
backdeals = self.mydb.getDealsFromTo( deal["path"][ len(deal["path"])-1 ]["StationBID"], deal["path"][0]["StationAID"], self.maxAgeDate, 1000)
backdeals = self.mydb.getDealsFromTo(deal["path"][ len(deal["path"]) - 1 ]["StationBID"], deal["path"][0]["StationAID"], self.maxAgeDate, 1000)
if backdeals:
deal["backToStartDeal"] = backdeals[0]

Expand All @@ -175,84 +177,83 @@ def calcRating(self):
deal["time"] += self.elitetime.calcTimeFromTo(step["SystemAID"], step["StationBID"], step["SystemBID"])
Systembefore = step["SystemBID"]
else:
deal["time"] += self.elitetime.calcTimeFromTo(Systembefore , step["StationBID"], step["SystemBID"])
deal["time"] += self.elitetime.calcTimeFromTo(Systembefore, step["StationBID"], step["SystemBID"])
Systembefore = step["SystemBID"]

# add back to start time
deal["time"] += self.elitetime.calcTimeFromTo(Systembefore , deal["path"][0]["StationAID"], deal["path"][0]["SystemAID"])
deal["time"] += self.elitetime.calcTimeFromTo(Systembefore, deal["path"][0]["StationAID"], deal["path"][0]["SystemAID"])
if deal["backToStartDeal"]:
deal["profit"] += deal["backToStartDeal"]["profit"]

lapsInHour = int(3600 / deal["time"]) # round down

profitHour = int(3600.0 / deal["time"] * deal["profit"]) #hmm mit lapsInHour oder mit hochrechnung rechnen?
deal["profitAverage"] = round(deal["profit"] / (len(deal["path"]) + 1),0)
profitHour = int(3600.0 / deal["time"] * deal["profit"]) # hmm mit lapsInHour oder mit hochrechnung rechnen?
deal["profitAverage"] = round(deal["profit"] / (len(deal["path"]) + 1), 0)
deal["profitHour"] = profitHour
deal["lapsInHour"] = lapsInHour

self.sortDealsByProfitH()

def sortDealsByProfitH(self, order=True):
self.locked = True
self.deals = sorted(self.deals , key=lambda deal: deal["profitHour"], reverse=order)
self.locked = None
def sortDealsByProfitH(self, order=True):
self.locked = True
self.deals = sorted(self.deals, key=lambda deal: deal["profitHour"], reverse=order)
self.locked = None

def sortDealsByProfit(self, order=True):
self.locked = True
self.deals = sorted(self.deals , key=lambda deal: deal["profit"], reverse=order)
self.locked = None
def sortDealsByProfit(self, order=True):
self.locked = True
self.deals = sorted(self.deals, key=lambda deal: deal["profit"], reverse=order)
self.locked = None

def sortDealsByProfitAverage(self, order=True):
self.locked = True
self.deals = sorted(self.deals , key=lambda deal: deal["profitAverage"], reverse=order)
self.locked = None
def sortDealsByProfitAverage(self, order=True):
self.locked = True
self.deals = sorted(self.deals, key=lambda deal: deal["profitAverage"], reverse=order)
self.locked = None

def sortDealsByLapTime(self, order=True):
self.locked = True
self.deals = sorted(self.deals , key=lambda deal: deal["time"], reverse=order)
self.locked = None
def sortDealsByLapTime(self, order=True):
self.locked = True
self.deals = sorted(self.deals, key=lambda deal: deal["time"], reverse=order)
self.locked = None

def sortDealsByStartDist(self, order=True):
self.locked = True
self.deals = sorted(self.deals , key=lambda deal: deal["path"][0]["startDist"], reverse=order)
self.locked = None
def sortDealsByStartDist(self, order=True):
self.locked = True
self.deals = sorted(self.deals, key=lambda deal: deal["path"][0]["startDist"], reverse=order)
self.locked = None

def printList(self):
print("routes found", len(self.deals))

for i, deal in enumerate(self.deals):
if i >= 40: break
if i >= 40:
break

timeT = "%s:%s" % (divmod(deal["time"] * deal["lapsInHour"], 60))
timeL = "%s:%s" % (divmod(deal["time"], 60))

print("\n%d. profit: %d profit/h:%d Laps/h: %d/%s LapTime: %s (Start dist: %s ly)" % (i + 1, deal["profit"], deal["profitHour"], deal["lapsInHour"], timeT, timeL, deal["path"][0]["startDist"]))
print("\n%d. profit: %d profit/h:%d Laps/h: %d/%s LapTime: %s (Start dist: %s ly)" % (i + 1, deal["profit"], deal["profitHour"], deal["lapsInHour"], timeT, timeL, deal["path"][0]["startDist"]))


before = { "StationB":deal["path"][0]["StationA"], "SystemB":deal["path"][0]["SystemA"], "StarDist":deal["path"][0]["stationA.StarDist"], "refuel":deal["path"][0]["stationA.refuel"] }
before = { "StationB": deal["path"][0]["StationA"], "SystemB": deal["path"][0]["SystemA"], "StarDist": deal["path"][0]["stationA.StarDist"], "refuel": deal["path"][0]["stationA.refuel"] }

for d in deal["path"]:
#print(d.keys())
print("\t%s : %s (%d ls) (%s buy:%d sell:%d profit:%d) (%s ly)-> %s:%s" % (before["SystemB"], before["StationB"], before["StarDist"] , d["itemName"],d["StationSell"], d["StationBuy"], d["profit"], d["dist"],d["SystemB"],d["StationB"] ) )
# print(d.keys())
print("\t%s : %s (%d ls) (%s buy:%d sell:%d profit:%d) (%s ly)-> %s:%s" % (before["SystemB"], before["StationB"], before["StarDist"], d["itemName"], d["StationSell"], d["StationBuy"], d["profit"], d["dist"], d["SystemB"], d["StationB"]))
if before["refuel"] != 1:
print("\t\tWarning: %s have no refuel!?" % before["StationB"])

before = d

backdist = self.mydb.getDistanceFromTo(deal["path"][0]["SystemAID"] , deal["path"][ len(deal["path"])-1 ]["SystemBID"])
backdist = self.mydb.getDistanceFromTo(deal["path"][0]["SystemAID"], deal["path"][ len(deal["path"]) - 1 ]["SystemBID"])

if deal["backToStartDeal"]:
#print(deal["backToStartDeal"].keys())
print("\t%s : %s (%d ls) (%s buy:%d sell:%d profit:%d) (%s ly)-> %s:%s" % (before["SystemB"], deal["backToStartDeal"]["fromStation"] , before["StarDist"], deal["backToStartDeal"]["itemName"], deal["backToStartDeal"]["StationSell"],deal["backToStartDeal"]["StationBuy"], deal["backToStartDeal"]["profit"], backdist, deal["path"][0]["SystemA"], deal["path"][0]["StationA"] ) )
# print(deal["backToStartDeal"].keys())
print("\t%s : %s (%d ls) (%s buy:%d sell:%d profit:%d) (%s ly)-> %s:%s" % (before["SystemB"], deal["backToStartDeal"]["fromStation"], before["StarDist"], deal["backToStartDeal"]["itemName"], deal["backToStartDeal"]["StationSell"], deal["backToStartDeal"]["StationBuy"], deal["backToStartDeal"]["profit"], backdist, deal["path"][0]["SystemA"], deal["path"][0]["StationA"]))
else:
print("\tno back deal (%s ly) ->%s : %s" % (backdist, deal["path"][0]["SystemA"], deal["path"][0]["StationA"] ))
print("\tno back deal (%s ly) ->%s : %s" % (backdist, deal["path"][0]["SystemA"], deal["path"][0]["StationA"]))

if before["refuel"] != 1:
print("\t\tWarning: %s have no refuel!?" % before["StationB"])



print("\noptions: startSystem:%s, tradingHops:%d, maxDist:%d, maxJumpDistance:%d, maxSearchRange:%d, maxStarDist:%d, maxAge:%d, minTradeProfit:%d, minStock:%d, resultLimit:%d"
% (self.options["startSystem"], self.options["tradingHops"], self.options["maxDist"], self.options["maxJumpDistance"], self.options["maxSearchRange"], self.options["maxStarDist"], self.options["maxAge"], self.options["minTradeProfit"], self.options["minStock"], self.options["resultLimit"]) )


print("\noptions: startSystem:%s, tradingHops:%d, maxDist:%d, maxJumpDistance:%d, maxSearchRange:%d, maxStarDist:%d, maxAge:%d, minTradeProfit:%d, minStock:%d, resultLimit:%d"
% (self.options["startSystem"], self.options["tradingHops"], self.options["maxDist"], self.options["maxJumpDistance"], self.options["maxSearchRange"], self.options["maxStarDist"], self.options["maxAge"], self.options["minTradeProfit"], self.options["minStock"], self.options["resultLimit"]))
33 changes: 15 additions & 18 deletions elite/loader/edsc.py
Expand Up @@ -7,23 +7,21 @@
@author: mEDI
'''

import os

from datetime import datetime, date, time, timedelta
import json

import gzip
import io
import sys

try:
from _version import __buildid__ , __version__, __builddate__, __toolname__, __useragent__
from _version import __buildid__, __version__, __builddate__, __toolname__, __useragent__
except ImportError:
__buildid__ = "UNKNOWN"
__version__ = "UNKNOWN"
__builddate__ = "NONE"
__toolname__ = "mEDI s Elite Tools"
__useragent__ = '%s/%s (%s) %s(%s)' % (__toolname__.replace(" ", ""), __version__, sys.platform, __buildid__, __builddate__.replace(" ", "").replace("-", "").replace(":", ""))
__useragent__ = '%s/%s (%s) %s(%s)' % (__toolname__.replace(" ", ""), __version__, sys.platform, __buildid__, __builddate__.replace(" ", "").replace("-", "").replace(":", ""))

try:
import urllib2
Expand All @@ -33,6 +31,7 @@
__edscAPIurl__ = 'http://edstarcoordinator.com/api.asmx'
__test__ = 'false'


class edsc(object):


Expand All @@ -43,18 +42,17 @@ def __init__(self):
def getSystemCoords(self, systemname):
apiPath = "GetSystems"
apiurl = "%s/%s" % (__edscAPIurl__, apiPath)
postrequest = {
"data": {
postrequest = {"data": {
"ver": 2,
'test': __test__,
"outputmode": 2,
"filter":{
"knownstatus":1,
"filter": {
"knownstatus": 1,
"cr": 1, # 1 or 5?
"systemname": systemname,
"date": '1990-01-01'
}
}
}
}

josnData = self.sendAPIRequest(apiurl, postrequest)
Expand All @@ -78,13 +76,13 @@ def submitDistances(self, targetSystemname, commander, refsystems ):
apiurl = "%s/%s" % (__edscAPIurl__, apiPath)
postrequest = {
"data": {
"ver": 2,
'test': __test__,
"commander": commander,
"p0":{ "name": targetSystemname },
"ver": 2,
'test': __test__,
"commander": commander,
"p0": { "name": targetSystemname },
"refs": refsystems,
}
}
}

# print(postrequest)
josnData = self.sendAPIRequest(apiurl, postrequest)
Expand Down Expand Up @@ -114,8 +112,8 @@ def sendAPIRequest(self, apiurl, postrequest):
response = urllib2.urlopen(request)
except:
e = sys.exc_info()
print("sendAPIRequest except",e)
return {"error":e}
print("sendAPIRequest except", e)
return {"error": e}

if response.info().get('Content-Encoding') == 'gzip':
# print("gzip ok")
Expand All @@ -128,5 +126,4 @@ def sendAPIRequest(self, apiurl, postrequest):
result = f.read()
josnData = json.loads(result.decode('utf-8'))

return josnData

return josnData

0 comments on commit 771c03b

Please sign in to comment.