Files
@ 30c79f1dc4f8
Branch filter:
Location: light9/light9/effect/settings.py
30c79f1dc4f8
6.8 KiB
text/x-python
fix suggestPrefixes to send suggestions to rdfdb
Ignore-this: 637142dcc1de97c9046d75d1396a9446
Ignore-this: 637142dcc1de97c9046d75d1396a9446
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 | from __future__ import division
"""
Data structure and convertors for a table of (device,attr,value)
rows. These might be effect attrs ('strength'), device attrs ('rx'),
or output attrs (dmx channel).
"""
import decimal
import numpy
from rdflib import URIRef, Literal
from light9.namespaces import RDF, L9, DEV
from light9.rdfdb.patch import Patch
import logging
log = logging.getLogger('settings')
def parseHex(h):
if h[0] != '#': raise ValueError(h)
return [int(h[i:i+2], 16) for i in 1, 3, 5]
def toHex(rgbFloat):
return '#%02x%02x%02x' % tuple(int(v * 255) for v in rgbFloat)
def getVal(graph, subj):
lit = graph.value(subj, L9['value']) or graph.value(subj, L9['scaledValue'])
ret = lit.toPython()
if isinstance(ret, decimal.Decimal):
ret = float(ret)
return ret
class _Settings(object):
"""
default values are 0 or '#000000'. Internal rep must not store zeros or some
comparisons will break.
"""
def __init__(self, graph, settingsList):
self.graph = graph # for looking up all possible attrs
self._compiled = {} # dev: { attr: val }; val is number or colorhex
for row in settingsList:
self._compiled.setdefault(row[0], {})[row[1]] = row[2]
# self._compiled may not be final yet- see _fromCompiled
self._delZeros()
@classmethod
def _fromCompiled(cls, graph, compiled):
obj = cls(graph, [])
obj._compiled = compiled
obj._delZeros()
return obj
@classmethod
def fromResource(cls, graph, subj):
settingsList = []
with graph.currentState() as g:
for s in g.objects(subj, L9['setting']):
d = g.value(s, L9['device'])
da = g.value(s, L9['deviceAttr'])
v = getVal(g, s)
settingsList.append((d, da, v))
return cls(graph, settingsList)
@classmethod
def fromVector(cls, graph, vector):
compiled = {}
i = 0
for (d, a) in cls(graph, [])._vectorKeys():
if a == L9['color']:
v = toHex(vector[i:i+3])
i += 3
else:
v = vector[i]
i += 1
compiled.setdefault(d, {})[a] = v
return cls._fromCompiled(graph, compiled)
def _zeroForAttr(self, attr):
if attr == L9['color']:
return '#000000'
return 0
def _delZeros(self):
for dev, av in self._compiled.items():
for attr, val in av.items():
if val == self._zeroForAttr(attr):
del av[attr]
if not av:
del self._compiled[dev]
def __hash__(self):
itemed = tuple([(d, tuple([(a, v) for a, v in sorted(av.items())]))
for d, av in sorted(self._compiled.items())])
return hash(itemed)
def __eq__(self, other):
if not issubclass(other.__class__, self.__class__):
raise TypeError("can't compare %r to %r" % (self.__class__, other.__class__))
return self._compiled == other._compiled
def __ne__(self, other):
return not self == other
def __nonzero__(self):
return bool(self._compiled)
def __repr__(self):
words = []
def accum():
for dev, av in self._compiled.iteritems():
for attr, val in av.iteritems():
words.append('%s.%s=%s' % (dev.rsplit('/')[-1],
attr.rsplit('/')[-1],
val))
if len(words) > 5:
words.append('...')
return
accum()
return '<%s %s>' % (self.__class__.__name__, ' '.join(words))
def getValue(self, dev, attr):
return self._compiled.get(dev, {}).get(attr, self._zeroForAttr(attr))
def _vectorKeys(self):
"""stable order of all the dev,attr pairs for this type of settings"""
raise NotImplementedError
def asList(self):
"""old style list of (dev, attr, val) tuples"""
out = []
for dev, av in self._compiled.iteritems():
for attr, val in av.iteritems():
out.append((dev, attr, val))
return out
def devices(self):
return self._compiled.keys()
def toVector(self):
out = []
for dev, attr in self._vectorKeys():
# color components may need to get spread out
v = self.getValue(dev, attr)
if attr == L9['color']:
out.extend([x / 255 for x in parseHex(v)])
else:
out.append(v)
return out
def byDevice(self):
for dev, av in self._compiled.iteritems():
yield dev, self.__class__._fromCompiled(self.graph, {dev: av})
def ofDevice(self, dev):
return self.__class__._fromCompiled(self.graph,
{dev: self._compiled.get(dev, {})})
def distanceTo(self, other):
diff = numpy.array(self.toVector()) - other.toVector()
d = numpy.linalg.norm(diff, ord=None)
log.info('distanceTo %r - %r = %g', self, other, d)
return d
def statements(self, subj, ctx, settingRoot, settingsSubgraphCache):
"""
settingRoot can be shared across images (or even wider if you want)
"""
# ported from live.coffee
add = []
for i, (dev, attr, val) in enumerate(self.asList()):
# hopefully a unique number for the setting so repeated settings converge
settingHash = hash((dev, attr, val)) % 9999999
setting = URIRef('%sset%s' % (settingRoot, settingHash))
add.append((subj, L9['setting'], setting, ctx))
if setting in settingsSubgraphCache:
continue
scaledAttributeTypes = [L9['color'], L9['brightness'], L9['uv']]
settingType = L9['scaledValue'] if attr in scaledAttributeTypes else L9['value']
add.extend([
(setting, L9['device'], dev, ctx),
(setting, L9['deviceAttr'], attr, ctx),
(setting, settingType, Literal(val), ctx),
])
settingsSubgraphCache.add(setting)
return add
class DeviceSettings(_Settings):
def _vectorKeys(self):
with self.graph.currentState() as g:
devs = set() # devclass, dev
for dc in g.subjects(RDF.type, L9['DeviceClass']):
for dev in g.subjects(RDF.type, dc):
devs.add((dc, dev))
keys = []
for dc, dev in sorted(devs):
for attr in sorted(g.objects(dc, L9['deviceAttr'])):
keys.append((dev, attr))
return keys
|