-
Notifications
You must be signed in to change notification settings - Fork 31
/
tradedb.py
2175 lines (1874 loc) · 69.2 KB
/
tradedb.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# --------------------------------------------------------------------
# Copyright (C) Oliver 'kfsone' Smith 2014 <oliver@kfs.org>:
# Copyright (C) Bernd 'Gazelle' Gollesch 2016, 2017
# Copyright (C) Jonathan 'eyeonus' Jones 2018
#
# You are free to use, redistribute, or even print and eat a copy of
# this software so long as you include this copyright notice.
# I guarantee there is at least one bug neither of us knew about.
# --------------------------------------------------------------------
# TradeDangerous :: Modules :: Database Module
"""
Provides the primary classes used within TradeDangerous:
TradeDB, System, Station, Ship, Item, RareItem and Trade.
These classes are primarily for describing the database.
Simplistic use might be:
import tradedb
# Create an instance: You can specify a debug level as a
# parameter, for more advanced configuration, see the
# tradeenv.TradeEnv() class.
tdb = tradedb.TradeDB()
# look up a System by name
sol = tdb.lookupSystem("SOL")
ibootis = tdb.lookupSystem("i BootiS")
ibootis = tdb.lookupSystem("ibootis")
# look up a Station by name
abe = tdb.lookupStation("Abraham Lincoln")
abe = tdb.lookupStation("Abraham Lincoln", sol)
abe = tdb.lookupStation("hamlinc")
# look up something that could be a system or station,
# where 'place' syntax can be:
# SYS, STN, SYS/STN, @SYS, /STN or @SYS/STN
abe = tdb.lookupPlace("Abraham Lincoln")
abe = tdb.lookupPlace("HamLinc")
abe = tdb.lookupPlace("@SOL/HamLinc")
abe = tdb.lookupPlace("so/haml")
abe = tdb.lookupPlace("sol/abraham lincoln")
abe = tdb.lookupPlace("@sol/abrahamlincoln")
james = tdb.lookupPlace("shin/jamesmem")
"""
######################################################################
# Imports
from collections import namedtuple, defaultdict
from pathlib import Path
from tradeenv import TradeEnv
from tradeexcept import TradeException
import cache
import heapq
import itertools
import locale
import math
import os
import re
import sqlite3
import sys
haveNumpy = False
try:
if os.environ['NUMPY']:
import numpy
import numpy.linalg
haveNumpy = True
except (KeyError, ImportError):
pass
if not haveNumpy:
class numpy(object):
array = False
float32 = False
ascontiguousarray = False
class linalg(object):
norm = False
locale.setlocale(locale.LC_ALL, '')
######################################################################
# Classes
class AmbiguityError(TradeException):
"""
Raised when a search key could match multiple entities.
Attributes:
lookupType - description of what was being queried,
searchKey - the key given to the search routine,
anyMatch - list of anyMatch
key - retrieve the display string for a candidate
"""
def __init__(
self, lookupType, searchKey, anyMatch, key=lambda item: item
):
self.lookupType = lookupType
self.searchKey = searchKey
self.anyMatch = anyMatch
self.key = key
def __str__(self):
anyMatch, key = self.anyMatch, self.key
if len(anyMatch) > 10:
opportunities = ", ".join([
key(c) for c in anyMatch[:10]
] + ["..."])
else:
opportunities = ", ".join(
key(c) for c in anyMatch[0:-1]
)
opportunities += " or " + key(anyMatch[-1])
return '{} "{}" could match {}'.format(
self.lookupType, str(self.searchKey),
opportunities
)
class SystemNotStationError(TradeException):
"""
Raised when a station lookup matched a System but
could not be automatically reduced to a Station.
"""
pass
######################################################################
def makeStellarGridKey(x, y, z):
"""
The Stellar Grid is a map of systems based on their Stellar
co-ordinates rounded down to 32lys. This makes it much easier
to find stars within rectangular volumes.
"""
return (int(x) >> 5, int(y) >> 5, int(z) >> 5)
class System(object):
"""
Describes a star system which may contain one or more Station objects.
Caution: Do not use _rangeCache directly, use TradeDB.genSystemsInRange.
"""
__slots__ = (
'ID',
'dbname', 'posX', 'posY', 'posZ', 'pos', 'stations',
'addedID',
'_rangeCache'
)
class RangeCache(object):
"""
Lazily populated cache of neighboring systems.
"""
def __init__(self):
self.systems = []
self.probedLy = 0.
def __init__(
self, ID, dbname, posX, posY, posZ, addedID,
ary=numpy.array,
nptype=numpy.float32,
):
self.ID = ID
self.dbname = dbname
self.posX, self.posY, self.posZ = posX, posY, posZ
if ary:
self.pos = ary([posX, posY, posZ], nptype)
self.addedID = addedID or 0
self.stations = ()
self._rangeCache = None
@property
def system(self):
return self
def distToSq(self, other):
"""
Returns the square of the distance between two systems.
It is slightly cheaper to calculate the square of the
distance between two points, so when you are primarily
doing distance checks you can use this less expensive
distance query and only perform a sqrt (** 0.5) on the
distances that fall within your constraint.
Args:
other:
The other System to measure the distance between.
Returns:
Distance in light years to the power of 2 (i.e. squared).
Example:
# Calculate which of [systems] is within 12 ly
# of System "target".
maxLySq = 12 ** 2 # Maximum of 12 ly.
inRange = []
for sys in systems:
if sys.distToSq(target) <= maxLySq:
inRange.append(sys)
"""
return (
(self.posX - other.posX) ** 2 +
(self.posY - other.posY) ** 2 +
(self.posZ - other.posZ) ** 2
)
def distanceTo(self, other):
"""
Returns the distance (in ly) between two systems.
NOTE: If you are primarily testing/comparing
distances, consider using "distToSq" for the test.
Returns:
Distance in light years.
Example:
print("{} -> {}: {} ly".format(
lhs.name(), rhs.name(),
lhs.distanceTo(rhs),
))
"""
return (
(self.posX - other.posX) ** 2 +
(self.posY - other.posY) ** 2 +
(self.posZ - other.posZ) ** 2
) ** 0.5 # fast sqrt
if haveNumpy:
def all_distances(
self, iterable,
ary=numpy.ascontiguousarray, norm=numpy.linalg.norm,
):
"""
Takes a list of systems and returns their distances from this system.
"""
return numpy.linalg.norm(
ary([s.pos for s in iterable]) - self.pos,
ord=2, axis=1.
)
def getStation(self, stationName):
"""
Quick case-insensitive lookup of a station name within the
stations in this system.
Returns:
Station() object if a match is found,
otherwise None.
"""
upperName = stationName.upper()
for station in self.stations:
if station.dbname.upper() == upperName:
return station
return None
def name(self, detail=0):
return self.dbname
def str(self):
return self.dbname
######################################################################
class Destination(namedtuple('Destination', [
'system', 'station', 'via', 'distLy'
])):
pass
class DestinationNode(namedtuple('DestinationNode', [
'system', 'via', 'distLy'
])):
pass
class Station(object):
"""
Describes a station (trading or otherwise) in a system.
For obtaining trade information for a given station see one of:
TradeCalc.getTrades (fast and cheap)
"""
__slots__ = (
'ID', 'system', 'dbname',
'lsFromStar', 'market', 'blackMarket', 'shipyard', 'maxPadSize',
'outfitting', 'rearm', 'refuel', 'repair', 'planetary',
'itemCount', 'dataAge',
)
def __init__(
self, ID, system, dbname,
lsFromStar, market, blackMarket, shipyard, maxPadSize,
outfitting, rearm, refuel, repair, planetary,
itemCount=0, dataAge=None,
):
self.ID, self.system, self.dbname = ID, system, dbname
self.lsFromStar = int(lsFromStar)
self.market = market if itemCount == 0 else 'Y'
self.blackMarket = blackMarket
self.shipyard = shipyard
self.maxPadSize = maxPadSize
self.outfitting = outfitting
self.rearm = rearm
self.refuel = refuel
self.repair = repair
self.planetary = planetary
self.itemCount = itemCount
self.dataAge = dataAge
system.stations = system.stations + (self,)
def name(self, detail=0):
return '%s/%s' % (self.system.dbname, self.dbname)
def checkPadSize(self, maxPadSize):
"""
Tests if the Station's max pad size matches one of the
values in 'maxPadSize'.
Args:
maxPadSize
A string of one or more max pad size values that
you want to match against.
Returns:
True
If self.maxPadSize is None or empty, or matches a
member of maxPadSize
False
If maxPadSize was not empty but self.maxPadSize
did not match it.
Examples:
# Require a medium max pad size - not small or large
station.checkPadSize("M")
# Require medium or unknown
station.checkPadSize("M?")
# Require small, large or unknown
station.checkPadSize("SL?")
"""
return (not maxPadSize or self.maxPadSize in maxPadSize)
def checkPlanetary(self, planetary):
"""
Tests if the Station's planetary matches one of the
values in 'planetary'.
Args:
askPlanetary
A string of one or more planetary values that
you want to match against.
Returns:
True
If self.planetary is None or empty, or matches a
member of planetary
False
If planetary was not empty but self.planetary
did not match it.
Examples:
# Require a planetary station
station.checkPlanetary("Y")
# Require planetary or unknown
station.checkPadSize("Y?")
# Require no planetary station
station.checkPadSize("N")
"""
return (not planetary or self.planetary in planetary)
def distFromStar(self, addSuffix=False):
"""
Returns a textual description of the distance from this
Station to the parent star.
Args:
addSuffix[=False]:
Always add a unit suffix (ls, Kls, ly)
"""
ls = self.lsFromStar
if not ls:
if addSuffix:
return "Unk"
else:
return '?'
if ls < 1000:
suffix = 'ls' if addSuffix else ''
return '{:n}'.format(ls)+suffix
if ls < 10000:
suffix = 'ls' if addSuffix else ''
return '{:.2f}K'.format(ls / 1000)+suffix
if ls < 1000000:
suffix = 'ls' if addSuffix else ''
return '{:n}K'.format(int(ls / 1000))+suffix
return '{:.2f}ly'.format(ls / (365*24*60*60))
@property
def isTrading(self):
"""
True if the station is thought to be trading.
A station is considered 'trading' if it has an item count > 0 or
if it's "market" column is flagged 'Y'.
"""
return (self.itemCount > 0 or self.market == 'Y')
@property
def itemDataAgeStr(self):
""" Returns the age in days of item data if present, else "-". """
if self.itemCount and self.dataAge:
return "{:7.2f}".format(self.dataAge)
return "-"
def str(self):
return '%s/%s' % (self.system.dbname, self.dbname)
######################################################################
class Ship(namedtuple('Ship', (
'ID', 'dbname', 'cost', 'fdevID', 'stations'
))):
"""
Ship description.
Attributes:
ID -- The database ID
dbname -- The name as present in the database
cost -- How many credits to buy
fdevID -- FDevID as provided by the companion API.
stations -- List of Stations ship is sold at.
"""
def name(self, detail=0):
return self.dbname
######################################################################
class Category(namedtuple('Category', (
'ID', 'dbname', 'items'
))):
"""
Item Category
Items are organized into categories (Food, Drugs, Metals, etc).
Category object describes a category's ID, name and list of items.
Attributes:
ID
The database ID
dbname
The name as present in the database.
items
List of Item objects within this category.
Member Functions:
name()
Returns the display name for this Category.
"""
def name(self, detail=0):
return self.dbname.upper()
######################################################################
class Item(object):
"""
A product that can be bought/sold in the game.
Attributes:
ID -- Database ID.
dbname -- Name as it appears in-game and in the DB.
category -- Reference to the category.
fullname -- Combined category/dbname for lookups.
avgPrice -- Galactic average as shown in game.
fdevID -- FDevID as provided by the companion API.
"""
__slots__ = ('ID', 'dbname', 'category', 'fullname', 'avgPrice', 'fdevID')
def __init__(self, ID, dbname, category, fullname, avgPrice=None, fdevID=None):
self.ID = ID
self.dbname = dbname
self.category = category
self.fullname = fullname
self.avgPrice = avgPrice
self.fdevID = fdevID
def name(self, detail=0):
return self.fullname if detail > 0 else self.dbname
######################################################################
class RareItem(namedtuple('RareItem', (
'ID', 'station', 'dbname', 'costCr', 'maxAlloc', 'illegal',
'suppressed', 'category', 'fullname',
))):
"""
Describes a RareItem from the database.
Attributes:
ID -- Database ID,
station -- Which Station this is bought from,
dbname -- The name are presented in the database,
costCr -- Buying price.
maxAlloc -- How many the player can carry at a time,
illegal -- If the item may be considered illegal,
suppressed -- The item is suppressed.
category -- Reference to the category.
fullname -- Combined category/dbname.
"""
def name(self, detail=0):
return self.fullname if detail > 0 else self.dbname
######################################################################
class Trade(namedtuple('Trade', (
'item',
'costCr', 'gainCr',
'supply', 'supplyLevel',
'demand', 'demandLevel',
'srcAge', 'dstAge'
))):
"""
Describes what it would cost and how much you would gain
when selling an item between two specific stations.
"""
def name(self, detail=0):
return self.item.name(detail=detail)
######################################################################
class TradeDB(object):
"""
Encapsulation for the database layer.
Attributes:
dataPath
Path() to the data directory
dbPath
Path() of the .db location
tradingCount
Number of "profitable trade" items processed
tradingStationCount
Number of stations trade data has been loaded for
tdenv
The TradeEnv associated with this TradeDB
sqlPath
Path() of the .sql file
pricesPath
Path() of the .prices file
importTables
List of the .csv files
Static methods:
calculateDistance2(lx, ly, lz, rx, ry, rz)
Returns the square of the distance in ly between two points.
calculateDistance(lx, ly, lz, rx, ry, rz)
Returns the distance in ly between two points.
listSearch(...)
Performs partial and ambiguity matching of a word from a list
of potential values.
normalizedStr(text)
Case and punctuation normalizes a string to make it easier
to find approximate matches.
titleFixup(text)
Case formats a proper noun.
"""
# Translation map for normalizing strings
normalizeTrans = str.maketrans(
'abcdefghijklmnopqrstuvwxyz',
'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'[]()*+-.,{}:'
)
trimTrans = str.maketrans('', '', ' \'')
# The DB cache
defaultDB = 'TradeDangerous.db'
# File containing SQL to build the DB cache from
defaultSQL = 'TradeDangerous.sql'
# File containing text description of prices
defaultPrices = 'TradeDangerous.prices'
# array containing standard tables, csvfilename and tablename
# WARNING: order is important because of dependencies!
defaultTables = (
('Added.csv', 'Added'),
('System.csv', 'System'),
('Station.csv', 'Station'),
('Ship.csv', 'Ship'),
('ShipVendor.csv', 'ShipVendor'),
('Upgrade.csv', 'Upgrade'),
('UpgradeVendor.csv', 'UpgradeVendor'),
('Category.csv', 'Category'),
('Item.csv', 'Item'),
('RareItem.csv', 'RareItem'),
('FDevShipyard.csv', 'FDevShipyard'),
('FDevOutfitting.csv', 'FDevOutfitting'),
)
# Translation matrixes for attributes -> common presentation
marketStates = planetStates = {'?': '?', 'Y': 'Yes', 'N': 'No'}
marketStatesExt = planetStatesExt = {'?': 'Unk', 'Y': 'Yes', 'N': 'No'}
padSizes = {'?': '?', 'S': 'Sml', 'M': 'Med', 'L': 'Lrg'}
padSizesExt = {'?': 'Unk', 'S': 'Sml', 'M': 'Med', 'L': 'Lrg'}
def __init__(
self,
tdenv=None,
load=True,
debug=None,
):
self.conn = None
self.cur = None
self.tradingCount = None
tdenv = tdenv or TradeEnv(debug=(debug or 0))
self.tdenv = tdenv
self.dataPath = dataPath = Path(tdenv.dataDir).resolve()
self.dbPath = Path(tdenv.dbFilename or dataPath / TradeDB.defaultDB)
self.sqlPath = dataPath / Path(tdenv.sqlFilename or TradeDB.defaultSQL)
pricePath = Path(tdenv.pricesFilename or TradeDB.defaultPrices)
self.pricesPath = dataPath / pricePath
self.importTables = [
(str(dataPath / Path(fn)), tn)
for fn, tn in TradeDB.defaultTables
]
self.importPaths = {tn: tp for tp, tn in self.importTables}
self.dbFilename = str(self.dbPath)
self.sqlFilename = str(self.sqlPath)
self.pricesFilename = str(self.pricesPath)
self.avgSelling, self.avgBuying = None, None
self.tradingStationCount = 0
if load:
self.reloadCache()
self.load(maxSystemLinkLy=tdenv.maxSystemLinkLy)
@staticmethod
def calculateDistance2(lx, ly, lz, rx, ry, rz):
"""
Returns the distance in ly between two points.
"""
dX = (lx - rx)
dY = (ly - ry)
dZ = (lz - rz)
distSq = (dX ** 2) + (dY ** 2) + (dZ ** 2)
return distSq
@staticmethod
def calculateDistance(lx, ly, lz, rx, ry, rz):
"""
Returns the distance in ly between two points.
"""
dX = (lx - rx)
dY = (ly - ry)
dZ = (lz - rz)
distSq = (dX ** 2) + (dY ** 2) + (dZ ** 2)
return distSq ** 0.5
############################################################
# Access to the underlying database.
def getDB(self):
if self.conn:
return self.conn
self.tdenv.DEBUG1("Connecting to DB")
conn = sqlite3.connect(self.dbFilename)
conn.execute("PRAGMA foreign_keys=ON")
conn.execute("PRAGMA synchronous=OFF")
conn.execute("PRAGMA temp_store=MEMORY")
conn.create_function('dist2', 6, TradeDB.calculateDistance2)
return conn
def query(self, *args):
""" Perform an SQL query on the DB and return the cursor. """
conn = self.getDB()
cur = conn.cursor()
cur.execute(*args)
return cur
def queryColumn(self, *args):
""" perform an SQL query and return a single column. """
return self.query(args).fetchone()[0]
def reloadCache(self):
"""
Checks if the .sql, .prices or *.csv files are newer than the cache.
"""
if self.dbPath.exists():
dbFileStamp = self.dbPath.stat().st_mtime
paths = [self.sqlPath]
paths += [Path(f) for (f, _) in self.importTables]
changedPaths = [
[path, path.stat().st_mtime]
for path in paths
if path.exists() and path.stat().st_mtime > dbFileStamp
]
if not changedPaths:
# Do we need to reload the .prices file?
if not self.pricesPath.exists():
self.tdenv.DEBUG1("No .prices file to load")
return
pricesStamp = self.pricesPath.stat().st_mtime
if pricesStamp <= dbFileStamp:
self.tdenv.DEBUG1("DB Cache is up to date.")
return
self.tdenv.DEBUG0(".prices has changed: re-importing")
cache.importDataFromFile(
self, self.tdenv, self.pricesPath, reset=True
)
return
self.tdenv.DEBUG0("Rebuilding DB Cache [{}]", str(changedPaths))
else:
self.tdenv.DEBUG0("Building DB Cache")
cache.buildCache(self, self.tdenv)
############################################################
# Load "added" data.
def _loadAdded(self):
"""
Loads the Added table as a simple dictionary
"""
stmt = """
SELECT added_id, name
FROM Added
"""
self.cur.execute(stmt)
addedByID = {}
for ID, name in self.cur:
addedByID[ID] = name
self.addedByID = addedByID
self.tdenv.DEBUG1("Loaded {:n} Addeds", len(addedByID))
def lookupAdded(self, name):
name = name.lower()
for ID, added in self.addedByID.items():
if added.lower() == name:
return ID
raise KeyError(name)
############################################################
# Star system data.
def systems(self):
""" Iterate through the list of systems. """
yield from self.systemByID.values()
def _loadSystems(self):
"""
Initial load the (raw) list of systems.
CAUTION: Will orphan previously loaded objects.
"""
stmt = """
SELECT system_id,
name, pos_x, pos_y, pos_z,
added_id
FROM System
"""
self.cur.execute(stmt)
systemByID, systemByName = {}, {}
for (ID, name, posX, posY, posZ, addedID) in self.cur:
system = System(ID, name, posX, posY, posZ, addedID)
systemByID[ID] = systemByName[name.upper()] = system
self.systemByID, self.systemByName = systemByID, systemByName
self.tdenv.DEBUG1("Loaded {:n} Systems", len(systemByID))
def lookupSystem(self, key):
"""
Look up a System object by it's name.
"""
if isinstance(key, System):
return key
if isinstance(key, Station):
return key.system
return TradeDB.listSearch(
"System", key, self.systems(), key=lambda system: system.dbname
)
def addLocalSystem(
self,
name,
x, y, z,
added="Local",
modified='now',
commit=True,
):
"""
Add a system to the local cache and memory copy.
"""
db = self.getDB()
cur = db.cursor()
cur.execute("""
INSERT INTO System (
name, pos_x, pos_y, pos_z, added_id, modified
) VALUES (
?, ?, ?, ?,
(SELECT added_id FROM Added WHERE name = ?),
DATETIME(?)
)
""", [
name, x, y, z, added, modified,
])
ID = cur.lastrowid
system = System(ID, name.upper(), x, y, z, 0)
self.systemByID[ID] = system
self.systemByName[system.dbname] = system
if commit:
db.commit()
self.tdenv.NOTE(
"Added new system #{}: {} [{},{},{}]",
ID, name, x, y, z
)
# Invalidate the grid
self.stellarGrid = None
return system
def updateLocalSystem(
self, system,
name, x, y, z, added="Local", modified='now',
force=False,
commit=True,
):
"""
Updates an entry for a local system.
"""
oldname = system.dbname
dbname = name.upper()
if not force:
if oldname == dbname and \
system.posX == x and \
system.posY == y and \
system.posZ == z:
return False
del self.systemByName[oldname]
db = self.getDB()
db.execute("""
UPDATE System
SET name=?,
pos_x=?, pos_y=?, pos_z=?,
added_id=(SELECT added_id FROM Added WHERE name = ?),
modified=DATETIME(?)
WHERE system_id = ?
""", [
dbname, x, y, z, added, modified,
system.ID,
])
if commit:
db.commit()
self.tdenv.NOTE(
"{} (#{}) updated in {}: {}, {}, {}, {}, {}, {}",
oldname, system.ID,
self.dbPath if self.tdenv.detail > 1 else "local db",
dbname,
x, y, z,
added, modified,
)
self.systemByName[dbname] = system
return True
def removeLocalSystem(
self, system,
commit=True,
):
""" Removes a system and it's stations from the local DB. """
for stn in self.stations:
self.removeLocalStation(stn, commit=False)
db = self.getDB()
db.execute("""
DELETE FROM System WHERE system_id = ?
""", [
system.ID
])
if commit:
db.commit()
del self.systemByName[system.dbname]
del self.systemByID[system.ID]
self.tdenv.NOTE(
"{} (#{}) deleted from {}",
system.name(), system.ID,
self.dbPath if self.tdenv.detail > 1 else "local db",
)
system.dbname = "DELETED " + system.dbname
del system
def __buildStellarGrid(self):
"""
Divides the galaxy into a fixed-sized grid allowing us to
aggregate small numbers of stars by locality.
"""
stellarGrid = self.stellarGrid = dict()
for system in self.systemByID.values():
key = makeStellarGridKey(system.posX, system.posY, system.posZ)
try:
grid = stellarGrid[key]
except KeyError:
grid = stellarGrid[key] = []
grid.append(system)
def genStellarGrid(self, system, ly):
"""
Yields Systems within a given radius of a specified System.
Args:
system:
The System to center the search on,
ly:
The radius of the search around system,
Yields:
(candidate, distLySq)
candidate:
System that was found,
distLySq:
The *SQUARE* of the distance in light-years
between system and candidate.
"""
if self.stellarGrid is None:
self.__buildStellarGrid()
sysX, sysY, sysZ = system.posX, system.posY, system.posZ
lwrBound = makeStellarGridKey(sysX - ly, sysY - ly, sysZ - ly)
uprBound = makeStellarGridKey(sysX + ly, sysY + ly, sysZ + ly)
lySq = ly ** 2
stellarGrid = self.stellarGrid
for x in range(lwrBound[0], uprBound[0]+1):
for y in range(lwrBound[1], uprBound[1]+1):
for z in range(lwrBound[2], uprBound[2]+1):
try:
grid = stellarGrid[(x, y, z)]
except KeyError:
continue
for candidate in grid:
distSq = (candidate.posX - sysX) ** 2
if distSq > lySq:
continue
distSq += (candidate.posY - sysY) ** 2
if distSq > lySq:
continue
distSq += (candidate.posZ - sysZ) ** 2
if distSq > lySq:
continue
if candidate is not system:
yield candidate, distSq ** 0.5
def genSystemsInRange(self, system, ly, includeSelf=False):
"""
Yields Systems within a given radius of a specified System.
Results are sorted by distance and cached for subsequent