Get random element from attributes in an object - python

I have an object which got 16 double attributes and I want to pick one of them randomly so I create a method which create a random number between 0-15, but this method is not really what I want I think it's a pretty dirty method if you guys got another cleanest method
class Currencies(object):
EURToUSD = 0.0
EURToJPY = 0.0
EURToBTC = 0.0
USDToEUR = 0.0
USDToBTC = 0.0
USDToJPY = 0.0
BTCToEUR = 0.0
BTCToJPY = 0.0
BTCToUSD = 0.0
JPYToEUR = 0.0
JPYToUSD = 0.0
JPYToBTC = 0.0
EURToEUR = 0.0
JPYToJPY = 0.0
USDToUSD = 0.0
BTCToBTC = 0.0
def __init__ (self):
try:
rates = urllib2.urlopen("http://fx.priceonomics.com/v1/rates/")
except urllib2.URLError as e:
return e.reasonx
res = json.load(rates)
self.EURToEUR = 1.000000
self.USDToUSD = 1.000000
self.JPYToJPY = 1.000000
self.BTCToBTC = 1.000000
self.EURToUSD = res['EUR_USD']
self.EURToJPY = res['EUR_JPY']
self.EURToBTC = res['EUR_BTC']
self.USDToEUR = res['USD_EUR']
self.USDToBTC = res['USD_BTC']
self.USDToJPY = res['USD_JPY']
self.BTCToEUR = res['BTC_EUR']
self.BTCToJPY = res['BTC_JPY']
self.BTCToUSD = res['BTC_USD']
self.JPYToEUR = res['JPY_EUR']
self.JPYToUSD = res['JPY_USD']
self.JPYToBTC = res['JPY_BTC']
def getRandomRate():
randomNumber = randint(0,15)
if(randomNumber == 1):
return EURToUSD = 0.0
if(...)

You could just select a random attribute from the vars(self) dictionary, filtering on names that match a pattern:
def getRandomRate(self):
return random.choice([v for attr, v in vars(self).items()
if len(attr) == 8 and attr[3:5] == 'To'])
This picks a random value from all attributes whose name is 8 characters long and contain the word To in the middle.
A short demo using your class:
>>> import random
>>> c = Currencies()
>>> vars(c)
{'EURToBTC': u'0.0108027', 'BTCToJPY': u'12816.8350063', 'JPYToJPY': 1.0, 'USDToBTC': u'0.0094131', 'JPYToBTC': u'0.0000702', 'BTCToUSD': u'125.2057142', 'USDToUSD': 1.0, 'USDToJPY': u'116.1736146', 'EURToEUR': 1.0, 'JPYToUSD': u'0.0084464', 'BTCToEUR': u'92.3549138', 'USDToEUR': u'0.8820255', 'BTCToBTC': 1.0, 'JPYToEUR': u'0.0065705', 'EURToUSD': u'1.2338648', 'EURToJPY': u'126.4193644'}
>>> [v for attr, v in vars(c).items() if len(attr) == 8 and attr[3:5] == 'To']
[u'0.0108027', u'12816.8350063', 1.0, u'0.0094131', u'0.0000702', u'125.2057142', 1.0, u'116.1736146', 1.0, u'0.0084464', u'92.3549138', u'0.8820255', 1.0, u'0.0065705', u'1.2338648', u'126.4193644']
>>> random.choice([v for attr, v in vars(c).items() if len(attr) == 8 and attr[3:5] == 'To'])
u'0.0108027'
So the list comprehension extracted the 16 values for each of the conversion rates, and random.choice() then picks one of those rates at random.

Related

How do I apply a material to a .glb/.gltf mesh?

I have a model in .glb format with nothing edit(but a mesh) in the scene. How do I apply a material of a glb/gltf mesh using Python? I am using Pygltflib and Trimesh although I can use other libraries.
I can only give a genereal answer, because you did not provide any code, but you would do it like this in principal:
material = Material() # Create a material
pbr = PbrMetallicRoughness() # Use PbrMetallicRoughness
pbr.baseColorFactor = [1.0, 0.0, 0.0, 1.0] # solid red
material.pbrMetallicRoughness = pbr
after that supply the material to your primitive like that
primitive.material = 0
and do not forget to add it to the gltf. As always if you use more materials, the order will be important of course:
gltf.materials.append(material)
For completeness here is how to add a double sided red metallicRoughnessMaterial with "MASK" alphaMode to the triangle example and save it as .glb:
from pygltflib import *
# create gltf objects for a scene with a primitive triangle with indexed geometry
gltf = GLTF2()
scene = Scene()
mesh = Mesh()
material = Material()
primitive = Primitive()
node = Node()
buffer = Buffer()
bufferView1 = BufferView()
bufferView2 = BufferView()
accessor1 = Accessor()
accessor2 = Accessor()
# add data
buffer.uri = "data:application/octet-stream;base64,AAABAAIAAAAAAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAACAPwAAAAA="
buffer.byteLength = 44
bufferView1.buffer = 0
bufferView1.byteOffset = 0
bufferView1.byteLength = 6
bufferView1.target = ELEMENT_ARRAY_BUFFER
bufferView2.buffer = 0
bufferView2.byteOffset = 8
bufferView2.byteLength = 36
bufferView2.target = ARRAY_BUFFER
accessor1.bufferView = 0
accessor1.byteOffset = 0
accessor1.componentType = UNSIGNED_SHORT
accessor1.count = 3
accessor1.type = SCALAR
accessor1.max = [2]
accessor1.min = [0]
accessor2.bufferView = 1
accessor2.byteOffset = 0
accessor2.componentType = FLOAT
accessor2.count = 3
accessor2.type = VEC3
accessor2.max = [1.0, 1.0, 0.0]
accessor2.min = [0.0, 0.0, 0.0]
pbr = PbrMetallicRoughness() # Use PbrMetallicRoughness
pbr.baseColorFactor = [1.0, 0.0, 0.0, 1.0] # solid red
material.pbrMetallicRoughness = pbr
material.doubleSided = True # make material double sided
material.alphaMode = MASK # to get around 'MATERIAL_ALPHA_CUTOFF_INVALID_MODE' warning
primitive.attributes.POSITION = 1
primitive.material = 0
node.mesh = 0
scene.nodes = [0]
# assemble into a gltf structure
gltf.scenes.append(scene)
gltf.meshes.append(mesh)
gltf.materials.append(material)
gltf.meshes[0].primitives.append(primitive)
gltf.nodes.append(node)
gltf.buffers.append(buffer)
gltf.bufferViews.append(bufferView1)
gltf.bufferViews.append(bufferView2)
gltf.accessors.append(accessor1)
gltf.accessors.append(accessor2)
gltf.convert_buffers(BufferFormat.BINARYBLOB) # Convert buffers to allow saving as .glb
# save to a .glb file
gltf.save("triangle.glb")

How to fix config Error in python neat openai retro

following the guide at: https://www.youtube.com/watch?v=8dY3nQRcsac&list=PLTWFMbPFsvz3CeozHfeuJIXWAJMkPtAdS&index=7
when I run the python program the is an error in the python neat config file
it looks like it has something to do with the genome variable
my python neat config file now
#--- parameters for the XOR-2 experiment ---#
[NEAT]
fitness_criterion = max
fitness_threshold = 10000
pop_size = 20
reset_on_extinction = True
[DefaultGenome]
# node activation options
activation_default = sigmoid
activation_mutate_rate = 0.05
activation_options = sigmoid
# node aggregation options
aggregation_default = sum
aggregation_mutate_rate = 0.05
aggregation_options = sum
# node bias options
bias_init_mean = 0.0
bias_init_stdev = 1.0
bias_max_value = 30.0
bias_min_value = -30.0
bias_mutate_power = 0.5
bias_mutate_rate = 0.7
bias_replace_rate = 0.1
# genome compatibility options
compatibility_disjoint_coefficient = 1.0
compatibility_weight_coefficient = 0.5
# connection add/remove rates
conn_add_prob = 0.5
conn_delete_prob = 0.5
# connection enable options
enabled_default = True
enabled_mutate_rate = 0.01
feed_forward = False
initial_connection = unconn nected
# node add/remove rates
node_add_prob = 0.5
node_delete_prob = 0.2
# network parameters
num_hidden = 0
num_inputs = 1120
num_outputs = 12
# node response options
response_init_mean = 1.0
response_init_stdev = 0.0
response_max_value = 30.0
response_min_value = -30.0
response_mutate_power = 0.0
response_mutate_rate = 0.0
response_replace_rate = 0.0
# connection weight options
weight_init_mean = 0.0
weight_init_stdev = 1.0
weight_max_value = 30
weight_min_value = -30
weight_mutate_power = 0.5
weight_mutate_rate = 0.8
weight_replace_rate = 0.1
[DefaultSpeciesSet]
compatibility_threshold = 205
[DefaultStagnation]
species_fitness_func = max
max_stagnation = 50
species_elitism = 0
[DefaultReproduction]
elitism = 3
survival_threshold = 0.2
the Error code from the terminal
'config-feedforward')
File "/home/gym/OPAI/lib/python3.6/site-packages/neat/config.py", line 189, in __init__
self.genome_config = genome_type.parse_config(genome_dict)
File "/home/gym/OPAI/lib/python3.6/site-packages/neat/genome.py", line 158, in parse_config
return DefaultGenomeConfig(param_dict)
File "/home/gym/OPAI/lib/python3.6/site-packages/neat/genome.py", line 72, in __init__
assert self.initial_connection in self.allowed_connectivity
AssertionError
config code from the python neat code
config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
neat.DefaultSpeciesSet, neat.DefaultStagnation,
config-feedforward')
The issue is on the line that reads "initial_connection = unconn nected"
There's a typo. There shoudn't be a break in 'unconnected' It shouold read as follows:
"initial_connection = unconnected"

ID3 Algorithm in Python

I am trying to plot a decision tree using ID3 in Python. I am really new to Python and couldn't understand the implementation of the following code. I need to know how I can apply this code to my data.
from math import log
import operator
def entropy(data):
entries = len(data)
labels = {}
for feat in data:
label = feat[-1]
if label not in labels.keys():
labels[label] = 0
labels[label] += 1
entropy = 0.0
for key in labels:
probability = float(labels[key])/entries
entropy -= probability * log(probability,2)
return entropy
def split(data, axis, val):
newData = []
for feat in data:
if feat[axis] == val:
reducedFeat = feat[:axis]
reducedFeat.extend(feat[axis+1:])
newData.append(reducedFeat)
return newData
def choose(data):
features = len(data[0]) - 1
baseEntropy = entropy(data)
bestInfoGain = 0.0;
bestFeat = -1
for i in range(features):
featList = [ex[i] for ex in data]
uniqueVals = set(featList)
newEntropy = 0.0
for value in uniqueVals:
newData = split(data, i, value)
probability = len(newData)/float(len(data))
newEntropy += probability * entropy(newData)
infoGain = baseEntropy - newEntropy
if (infoGain > bestInfoGain):
bestInfoGain = infoGain
bestFeat = i
return bestFeat
def majority(classList):
classCount={}
for vote in classList:
if vote not in classCount.keys(): classCount[vote] = 0
classCount[vote] += 1
sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True)
return sortedClassCount[0][0]
def tree(data,labels):
classList = [ex[-1] for ex in data]
if classList.count(classList[0]) == len(classList):
return classList[0]
if len(data[0]) == 1:
return majority(classList)
bestFeat = choose(data)
bestFeatLabel = labels[bestFeat]
theTree = {bestFeatLabel:{}}
del(labels[bestFeat])
featValues = [ex[bestFeat] for ex in data]
uniqueVals = set(featValues)
for value in uniqueVals:
subLabels = labels[:]
theTree[bestFeatLabel][value] = tree(split/(data, bestFeat, value),subLabels)
return theTree
So what I did after this is the following:
infile=open("SData.csv","r")
data=infile.read()
tree(data)
The error which I got is "1 argument is missing" which is the label which I have to define and this is where I don't know what I have to put. I tried the variable for which I have to make the decision tree but it doesn't work:
tree(data,MinTemp)
Here I get an error "MinTemp is not defined".
Please help me out and let me know what I should do to have a look at the tree.
Following is the part of data and I want to generate a tree for MinTemp
MinTemp,Rainfall,Tempat9,RHat9,CAat9,WSat9
high,no,mild,normal,overcast,weak
high,no,mild,normal,cloudy,weak
high,no,mild,normal,cloudy,mild
high,yes,mild,high,cloudy,weak
high,yes,mild,high,cloudy,mild
medium,yes,mild,high,cloudy,mild
high,no,mild,high,overcast,weak
high,no,mild,normal,sunny,weak
high,no,hot,normal,sunny,weak
high,no,hot,normal,overcast,weak

Retrieve ScannerSubscription results using IbPy

I'm struggling with the results of a ScannerSubscription.
For example, if I request:
qqq_id = 0
subscript = ScannerSubscription()
subscript.numberOfRows(15)
subscript.m_scanCode = 'HIGH_OPEN_GAP'
subscript.m_instrument = 'STK'
subscript.m_averageOptionVolumeAbove = ''
subscript.m_couponRateAbove = ''
subscript.m_couponRateBelow = ''
subscript.m_abovePrice = '5'
subscript.m_belowPrice = ''
subscript.m_marketCapAbove = ''
subscript.m_marketCapBelow = ''
subscript.m_aboveVolume = '100000'
subscript.m_stockTypeFilter = 'ALL'
subscript.locationCode('STK.US.MAJOR')
tws_conn.reqScannerSubscription(qqq_id, subscript)
tws_conn.reqScannerParameters()
I received a scannerData response like this:
<scannerData reqId=0, rank=0, contractDetails=<ib.ext.ContractDetails.ContractDetails object at 0x00000000036EFA58>, distance=None, benchmark=None, projection=None, legsStr=None>
etc...
But I cannot retrieve the result values, for example:
reqScannerParameters() xml result specifies <colId>390</colId> as the colId for the Gap value:
<ScanType>
<displayName>Top Close-to-Open % Gainers</displayName>
<scanCode>HIGH_OPEN_GAP</scanCode>
<instruments>STK,STOCK.NA,STOCK.EU,STOCK.HK,FUT.US,FUT.HK,FUT.EU,FUT.NA</instruments>
<absoluteColumns>false</absoluteColumns>
<Columns varName="columns">
<Column>
<colId>390</colId>
<name>Gap</name>
<display>true</display>
<section>m</section>
<displayType>DATA</displayType>
</Column>
How do I retrieve the GAP value?
Is this even possible ?
Now I'm sure you're supposed to request data after getting the contract.
import pandas as pd
scans = 15
res = pd.DataFrame(index = range(scans), columns = ['sym','open','close','calc']).fillna(0)
msgs = []
from ib.ext.Contract import Contract
from ib.opt import ibConnection, message
from ib.ext.TickType import TickType as tt
def tickPrice(msg):
global scans
if msg.field in [tt.OPEN, tt.CLOSE]:
res.loc[msg.tickerId,tt.getField(msg.field)] = msg.price
op = res.loc[msg.tickerId,'open']
cl = res.loc[msg.tickerId,'close']
if op > 0 and cl > 0 and res.loc[msg.tickerId,'calc'] == 0:
res.loc[msg.tickerId,'calc'] = ((op-cl)*100/cl)
con.cancelMktData(msg.tickerId)
scans -= 1
if scans == 0:
print(res)
con.disconnect()
def snapshot(msg):
res.loc[msg.rank,'sym'] = msg.contractDetails.m_summary.m_symbol
#tt.OPEN (14) isn't coming with snapshot
con.reqMktData(str(msg.rank), msg.contractDetails.m_summary, "", False)
def watcher(msg):
#print (msg)
msgs.append(msg)
def scanData(msg):
snapshot(msg)
def scanDataEnd(msg):
con.cancelScannerSubscription(qqq_id)
con = ibConnection(port=7497, clientId=888)
con.registerAll(watcher)
con.unregister(watcher, message.scannerData)
con.register(scanData, message.scannerData)
con.unregister(watcher, message.scannerDataEnd)
con.register(scanDataEnd, message.scannerDataEnd)
con.unregister(watcher, message.tickPrice)
con.register(tickPrice, message.tickPrice)
con.connect()
from ib.ext.ScannerSubscription import ScannerSubscription
qqq_id = 0
subscript = ScannerSubscription()
subscript.numberOfRows(15)
subscript.m_scanCode = 'HIGH_OPEN_GAP'
subscript.m_instrument = 'STK'
subscript.m_averageOptionVolumeAbove ='0'
subscript.m_abovePrice = '5'
subscript.m_aboveVolume = '100000'
con.reqScannerSubscription(qqq_id, subscript)
res at 1 pm est =
sym open close calc
0 TAC 4.95 4.25 16.470588
1 CTRP 44.80 40.99 9.294950
2 IIIN 39.26 36.58 7.326408
3 LFC 14.60 13.63 7.116654
4 ACH 11.59 10.87 6.623735
5 KALV 9.01 8.38 7.517900
6 OMER 13.25 12.75 3.921569
7 DWTI 68.00 66.50 2.255639
8 WLDN 23.75 23.43 1.365770
9 BZQ 19.67 18.73 5.018687
10 JNUG 6.55 6.43 1.866252
11 GXP PRB 50.78 49.80 1.967871
12 AU 10.85 10.59 2.455146
13 USLV 13.07 12.81 2.029664
14 CBD 16.60 16.03 3.555833
I don't know why they don't come in rank order??

How can I make my plot smoother in Python?

I have a function called calculate_cost which calculates the performance of supplier for different S_range (stocking level). The function works but the plots are not smooth, is there a way to smooth it in Python?
import numpy
import scipy.stats
import scipy.integrate
import scipy.misc
import matplotlib
import math
import pylab
from scipy.stats import poisson
def calculate_cost(s, h, d, r, k, alphaR):
cost = 0.0
for i in range(0, alphaR + 1):
#i = i-1
binom = math.factorial(r) / ((math.factorial(i)) * (math.factorial(r - i)))
func = scipy.stats.poisson.cdf(s, d)
cost += ((k/r) * binom * (func ** i) * ((1.0-func) ** (r-i)))
for p in range (s):
cost += h*(s-p)*scipy.stats.poisson.pmf(p, d) #This a formula
return cost
graphs = []
class Graph:
def __init__(self):
self.label = ""
self.h = 0
self.d = 0
self.r = 0
self.k = 0
self.alphaR = 0
graph = Graph()
graph.label = "A"
graph.h = 1.0
graph.d = 10
graph.r = 30
graph.k = 283.0
graph.alphaR = 23
graphs.append(graph)
graph = Graph()
graph.label = "B"
graph.h = 1.0
graph.d = 10
graph.r = 30
graph.k = 146.0
graph.alphaR = 24
#graph.LineStyle = '*-'
graphs.append(graph)
graph = Graph()
graph.label = "C"
graph.h = 1.0
graph.d = 10
graph.r = 30
graph.k = 92.0
graph.alphaR = 25
#graph.LineStyle = '*-'
graphs.append(graph)
graph = Graph()
graph.label = "D"
graph.h = 1.0
graph.d = 10
graph.r = 30
graph.k = 80.0
graph.alphaR = 26
#graph.LineStyle = '*-'
graphs.append(graph)
graph = Graph()
graph.label = "E"
graph.h = 1.0
graph.d = 10
graph.r = 30
graph.k = 77.0
graph.alphaR = 27
#graph.LineStyle = '*-'
graphs.append(graph)
s_range = numpy.arange(0,21,1)
for graph in graphs:
cost = []
for s in s_range:
cost.append(calculate_cost(s, graph.h, graph.d, graph.r, graph.k, graph.alphaR))
matplotlib.pyplot.plot(s_range, cost, label = graph.label)
pylab.legend()
matplotlib.pyplot.xlabel(' S_range')
matplotlib.pyplot.ylabel('Cost')
pylab.show()
One solution would be to use the scipy.iterp1D function with a 'cubic' type :
from scipy import interpolate
....
s_range = numpy.arange(0,21,1)
for graph in graphs:
cost = []
for s in s_range:
cost.append(calculate_cost(s, graph.h, graph.d, graph.r, graph.k, graph.alphaR))
f = interpolate.interp1d(s_range, cost, kind='cubic')
s_range_new = np.arange(0,20, 0.1)
cost_new = f(s_range_new)
matplotlib.pyplot.plot(s_range_new, cost_new, label = graph.label)
pylab.legend()
matplotlib.pyplot.xlabel(' S_range')
matplotlib.pyplot.ylabel('Cost')
pylab.show()
This gives you :
Be careful in how you use this as this is only interpolated points and not real data points.
Hope this helps

Categories