Why a float is required? - python

There is a code:
from arcpy.sa import *
arcpy.CheckOutExtension("Spatial")
print "Creating and defining X and Y coordinates:" #set env properties
env.workspace = r"C:\Users\Desktop\data\new"
env.overwriteOutput = 1
theme = '/watersheds_3D.shp' #polygons in vector format
demName = '/demlab4' # raster of DEM
rasObject = Raster(demName)
my_extent = rasObject.extent #find a grid cell size:
my_cellsize = (rasObject.meanCellHeight + rasObject.meanCellWidth)/2
print my_cellsize
slope_deg = Slope(demName)
slope_deg.save('/demlab4_slope')
for row in arcpy.da.SearchCursor(theme, ["FID","SHAPE#"]): # inside shp file -
print ("Polygon # {}: ".format(row[0]))
for part in row[1]: # Inside the polygon
xCoords = []
yCoords = []
zCoords = []
for pnt in part:
print (" {}, {}, {} ".format(pnt.X, pnt.Y, pnt.Z))
xCoords.append(pnt.X)
yCoords.append(pnt.Y)
zCoords.append(pnt.Z)
area3D = lab4_arcpy_module.define3Darea(my_cellsize, slope_deg)
and function to calculate this:
def define3Darea(my_cellsize, slope_deg):
a = my_cellsize
slope_rad = math.pi * slope_deg / 180 # return in radiant
c = math.sqrt(a**2 + (math.tan(slope_rad)*a)**2)
area3D = a*c
print "Total 3D Area is: ", area3D, "m^2"
return area3D
it gives: TypeError: a float is required.
What can be a problem?
Also need to calculate 3D Area inside the each polygon (4). How t do it?

Not sure what Raster and Slope are doing, but this TypeError: a float is required comes when you try to some float operations on a variable that is not of float type. My guess would be that problem is with : slope_deg variable. See here :
slope_deg = Slope(demName)
slope_deg.save('/demlab4_slope')
You are declaring and doing some operation with slope_deg variable. And now in this statement:
area3D = lab4_arcpy_module.define3Darea(my_cellsize, slope_deg)
you are using same variable which is an instance of Slope class and not a float variable. Either there has to be some attribute of this(Slope) which is float or you have to use correct variable.

i found that theres is some error trying to print loss so:
print ("Model paramters:" )
print ("Weight:%f" %sess.run(W))
print ("bias:%f" %sess.run(b))
#print ("loss:%f" %(loss)) <------
make the error disapear, still don't understand well why is this.

Related

change data type to float or numpy float

I want my def variable gives out float or numpy float the type.
Here is my solution:
def answer_deg(xyz_file):
file = open('cysteine.xyz','r')
coords = file.readlines()[2:]
file.close()
#S-C bond: vectors and lengths
x_sc=float(coords[7].split()[1])-float(coords[6].split()[1])
y_sc=float(coords[7].split()[2])-float(coords[6].split()[2])
z_sc=float(coords[7].split()[3])-float(coords[6].split()[3])
sc = [x_sc,y_sc,z_sc]
sc_length = sqrt(x_sc**2 + y_sc**2 + z_sc**2)
#S-H bond: vectors and lengths
x_sh=float(coords[7].split()[1])-float(coords[11].split()[1])
y_sh=float(coords[7].split()[2])-float(coords[11].split()[2])
z_sh=float(coords[7].split()[3])-float(coords[11].split()[3])
sh = [x_sh,y_sh,z_sh]
sh_length = sqrt(x_sh**2 + y_sh**2 + z_sh**2)
#S-C-H valence angle
theta = acos(np.dot(sc, sh)/(sc_length*sh_length))
theta_deg = np.degrees(theta)
return round(theta_deg, 2)
print(answer_deg('cysteine.xyz'))
print(type(answer_deg))
This solution will print out:
print(answer_deg('cysteine.xyz')) = 96.47
print(type(answer_deg)) = <class 'function'>
I don't intend type(answer_deg) to gives out 'function' as its types. Do you know where I'm wrong or where I should amend so that it will print float or np.float as its types?
You can force the answer_deg to be of type:float by using the following print(float(answer_deg('cysteine.xyz'))) .

python function multiple return

I would like to transform this code to have a function instead :
variables = ['oki']
for var in variables:
lm_full = sm.formula.ols(formula='%s ~ diag + age + ICVcm3' % var, data=dfwo2).fit()
print("===============================================================================")
print(" formule = %s ~ diag + age + ICVcm3" % var)
print("===============================================================================")
print(lm_full.summary())
At the end I would like something that looks like :
function(oki,diag,age,ICVcm3,dfwo2) that would return the result of the loop.
I have no clue of how to do it. The examples that I found on the internet are very basic.... I don't even know what to type on google to get an answer.
You can return a list of tuples:
def myFunction(variables):
result = []
for var in variables:
formula = " formule = %s ~ diag + age + ICVcm3" % var
lm_full = sm.formula.ols(formula=formula, data=dfwo2).fit()
result.append((formula, lm_full.summary()))
return result
This code shows you how to return the items that have been computed in the function and how to retrieve them in the calling function. Notice how you can return as many, or as few, items as you wish, and that, even if the function returns items your calling code doesn't need you can ignore them. (That's the purpose of the variables named dummy.)
I'm using one of the datasets that comes with statsmodels since I don't recognise the one you're using.
import statsmodels as sm
df = sm.datasets.get_rdataset("Guerry", "HistData").data
df = df[['Lottery', 'Literacy', 'Wealth', 'Region']].dropna()
import statsmodels.formula.api as smf
def regress(variables):
results = [ ]
for variable in variables:
mod = smf.ols(formula='Lottery ~ %s' % variable, data=df)
result = mod.fit()
results . append ( (variable, result.params, result.df_resid, result.rsquared) )
return results
for result in regress (['Literacy', 'Wealth', 'Region']):
variable, dummy, dummy, R_squared = result
print ( variable, R_squared )
Results are like this:
Literacy 0.145720612937
Wealth 0.243180384656
Region 0.142107524677
your loop is var in variables which only contains 1 item: a string.
So what is the purpose of such a loop anyway? diag,age,ICVcm3,dfwo2 where are all these values delcared? What is the function about? Is seems to be some very specific wierd topic.
Though just guessing, something like this could be what you've been looking for:
def myfunction(variables,diag,age,ICVcm3,dfwo2):
for var in variables:
lm_full = sm.formula.ols(formula='%s ~ diag + age + ICVcm3' % var, data=dfwo2).fit()
print("===============================================================================")
print(" formule = %s ~ diag + age + ICVcm3" % var)
print("===============================================================================")
print(lm_full.summary())

Input into a polynomial regression formula with Python

I inherited a project in the middle of pandemonium and to makes matters worse I am just learning python.
I managed to implement a polynomial function into my code and the results
are the same as the ones posted in the examples of this web page.
[z = numpy.polyfit(x, y, 5)]
However, I will like to know how to modify the program so I can insert an input of one of the know values of y to find x.
In other words. I have x and y arrays where:
- array x holds values for know kilograms weights (0.0, 0.5, 1.0, 1.5, 2.0)
- array y (0.074581967, 0.088474754, 0.106797419, 0.124461935, 0.133726833)
I have a program who reads a load of weight and the tension created by a phidget and generates the array to be used by this program.
What I need to accomplish is to read the next value from the phidget and be able to convert the reading into kilograms, from within the provided array.
Is there a way to do this? I feel I am only missing a line of code but I don't know how to implement the results of the returned values from the formula. (z)
Thanks in advance.
CODE ADDED AS REQUESTED
from Phidgets.PhidgetException import PhidgetException
from Phidgets.Devices.Bridge import Bridge, BridgeGain
import datetime
import os
import re
import sys
import time
import numpy
wgh = list()
avg = list()
buf = list()
x = []
y = []
def nonlinear_regression(): # reads the calibration mapping and generates the conversion coefficients
fd = open("calibration.csv", "r")
for line in fd:
[v0, v1] = line.split(",")
x.append(float(v0))
y.append(float(v1[:len(v1) - 1]))
xdata = numpy.array(x)
ydata = numpy.array(y)
z = numpy.polyfit(x, y, 5)
return z
def create_data_directory(): # create the data directory
if not os.path.exists("data"):
os.makedirs("data")
def parse_config(): # get config-file value
v = int()
config = open("config.properties", "r")
for line in config:
toks = re.split(r"[\n= ]+", line)
if toks[0] == "record_interval":
v = int(toks[1])
return v
def read_bridge_data(event): # read the data
buf.append(event.value)
def record_data(f_name, date, rms):
if not os.path.isfile(f_name):
fd = open(f_name, "w")
fd.write("time,weight\n")
fd.write(datetime.datetime.strftime(date, "%H:%M"))
fd.write(",")
fd.write(str(rms) + "\n")
fd.close()
else:
fd = open(f_name, "a")
fd.write(datetime.datetime.strftime(date, "%H:%M"))
fd.write(",")
fd.write(str(rms) + "\n")
fd.close()
print("Data recorded.")
def release_bridge(event): # release the phidget device
try:
event.device.closePhidget()
except:
print("Phidget bridge could not be released properly.")
sys.exit(1)
def main():
create_data_directory()
RECORD_INTERVAL = parse_config() # get the config-file value
calibrate = nonlinear_regression() # get calibration function; use like: calibrate(some_input)
bridge = Bridge()
try:
bridge.setOnBridgeDataHandler(read_bridge_data)
bridge.setOnDetachHandler(release_bridge) # when the phidget gets physically detached
bridge.setOnErrorhandler(release_bridge) # asynchronous exception (i.e. keyboard interrupt)
except:
print("Phidget bridge event binding failed.")
sys.exit(1)
try:
bridge.openPhidget()
bridge.waitForAttach(3000)
except:
print("Phidget bridge opening failed.")
sys.exit(1)
last_record = int()
while (True):
date = datetime.datetime.now()
f_name = "data\\" + datetime.datetime.strftime(date, "%B_%d_%Y") + ".csv"
curr = time.time() * 1000
if (curr - last_record) > (RECORD_INTERVAL * 1000):
try:
bridge.setDataRate(10)
last = time.time() * 1000
bridge.setEnabled(0, True)
while (time.time() * 1000 - last) < 1000: # collects over 1 sec
pass
bridge.setEnabled(0, False)
except:
print("Phidget bridge data reading error.")
bridge.setEnabled(0, False)
bridge.closePhidget()
sys.exit(1)
vol = sum(buf) / len(buf)
del buf[:]
last_record = curr
record_data(f_name, date, vol) # replace curr with calibrated data
#THIS IS WHERE I WILL LIKE TO INCORPORATE THE CHANGES TO SAVE THE WEIGHT
#record_data(f_name, date, conversion[0] * vol + conversion[1]) # using the linear conversion function
else:
time.sleep(RECORD_INTERVAL - 1) # to reduce the CPU's busy-waiting
if __name__ == "__main__":
main()
The linear conversion function from the calibrations is returned by numpy.polyfit as an array of coefficients. Since you passed 5 for the degree argument of polyfit, you will get an array of six coefficients:
f(x) = ax5 + bx4 + cx3 + dx2 + ex + f
Where a, b, c, d, e, and f are the elements of the z array returned by nonlinear_regression.
To implement the linear conversion formula, simply use the power operator **, the elements of z, and the value of vol:
vol_calibrated = vol**5 * z[0] + vol**4 * z[1] + vol**3 * z[2] + vol**2 * z[3] + vol * z[4] + z[5]
Or more generally:
degree = len(z) - 1
vol_calibrated = sum(vol**(degree-i) * coeff for i, coeff in enumerate(z))

Python NetCDF IOError: netcdf: NetCDF: Invalid dimension ID or name

I am writing a script in python for handling NetCDF files, but I am facing some issues in creating variables, here is the part of the code:
stepnumber_var = ofl.createVariable("step_number", "i",("step_number",))
stepnumber_var.standard_name = "step_number"
atomNumber_var = ofl.createVariable("atom_number", "i", ("atom_number",))
atomNumber_var.standard_name = "atom__number"
But gives me this error:
Traceback (most recent call last):
File "sub_avg.py", line 141, in <module>
atomNumber_var = ofl.createVariable("atom_number", "i", ("atom_number",))
IOError: netcdf: NetCDF: Invalid dimension ID or name
My question is, why the first variable is created without any problem and the second doesn't work?
Thanks
Here it is the full code
from array import array
import os
import sys
import math
import string as st
import numpy as N
from Scientific.IO.NetCDF import NetCDFFile as S
if len(sys.argv) < 2:
sys.exit( "No input file found. \nPlease privide NetCDF trajectory input file" )
#######################
## Open NetCDF file ###
#######################
infl = S(sys.argv[1], 'r')
file = sys.argv[1]
title,ext = file.split(".")
#for v in infl.variables: # Lists the variables in file
# print(v)
#################################################################################
# Variable "configurations" has the structure [step_number, atom_number, x y z] #
#################################################################################
varShape = infl.variables['configuration'].shape # This gets the shape of the variable, i.e. the dimension in terms of elements
nSteps = varShape[0]
nAtoms = varShape[1]
coordX_atom = N.zeros((nSteps,nAtoms))
coordY_atom = N.zeros((nSteps,nAtoms))
coordZ_atom = N.zeros((nSteps,nAtoms))
sumX = [0] * nAtoms
sumY = [0] * nAtoms
sumZ = [0] * nAtoms
######################################################
# 1) Calculate the average structure fron trajectory #
######################################################
for i in range(0, 3):
for j in range(0, 3):
coordX_atom[i][j] = infl.variables["configuration"][i,j,0]
coordY_atom[i][j] = infl.variables["configuration"][i,j,1]
coordZ_atom[i][j] = infl.variables["configuration"][i,j,2]
sumX[j] = sumX[j] + coordX_atom[i][j]
sumY[j] = sumY[j] + coordY_atom[i][j]
sumZ[j] = sumZ[j] + coordZ_atom[i][j]
avgX = [0] * nAtoms
avgY = [0] * nAtoms
avgZ = [0] * nAtoms
for j in range(0, 3):
avgX[j] = sumX[j]/nSteps
avgY[j] = sumY[j]/nSteps
avgZ[j] = sumZ[j]/nSteps
##############################################################
# 2) Subtract average structure to each atom and for each frame #
##############################################################
for i in range(0, 3):
for j in range(0, 3):
coordX_atom[i][j] = infl.variables["configuration"][i,j,0] - avgX[j]
coordY_atom[i][j] = infl.variables["configuration"][i,j,1] - avgY[j]
coordZ_atom[i][j] = infl.variables["configuration"][i,j,2] - avgZ[j]
#######################################
# 3) Write new NetCDF trajectory file #
#######################################
ofl = S(title + "_subAVG.nc", "a")
############################################################
# Get information of variables contained in the NetCDF input file
#############################################################
i = 0
for v in infl.variables:
varNames = [v for v in infl.variables]
i += 1
#############################################
# Respectively get, elements names in variable, dimension of elements and lenght of the array variableNames
##############################################
for v in infl.variables["box_size"].dimensions:
boxSizeNames = [v for v in infl.variables["box_size"].dimensions]
for v in infl.variables["box_size"].shape:
boxSizeShape = [v for v in infl.variables["box_size"].shape]
boxSizeLenght = boxSizeNames.__len__()
print boxSizeLenght
for v in infl.variables["step"].dimensions:
stepNames = [v for v in infl.variables["step"].dimensions]
for v in infl.variables["step"].shape:
stepShape = [v for v in infl.variables["box_size"].shape]
stepLenght = stepNames.__len__()
print stepLenght
for v in infl.variables["configuration"].dimensions:
configurationNames = [v for v in infl.variables["configuration"].dimensions]
for v in infl.variables["configuration"].shape:
configurationShape = [v for v in infl.variables["configuration"].shape]
configurationLenght = configurationNames.__len__()
print configurationLenght
for v in infl.variables["description"].dimensions:
descriptionNames = [v for v in infl.variables["description"].dimensions]
for v in infl.variables["description"].shape:
descriptionShape = [v for v in infl.variables["description"].shape]
descriptionLenght = descriptionNames.__len__()
print descriptionLenght
for v in infl.variables["time"].dimensions:
timeNames = [v for v in infl.variables["time"].dimensions]
for v in infl.variables["time"].shape:
timeShape = [v for v in infl.variables["time"].shape]
timeLenght = timeNames.__len__()
print timeLenght
#Get Box size
xBox = infl.variables["box_size"][0,0]
yBox = infl.variables["box_size"][0,1]
zBox = infl.variables["box_size"][0,2]
# Get description lenght
description_lenghtLenght = infl.variables["description"][:]
############################################################
# Create Dimensions
############################################################
stepnumber_var = ofl.createVariable("step_number", "i",("step_number",))
stepnumber_var.standard_name = "step_number"
atomNumber_var = ofl.createVariable("atom_number", "i", ("atom_number",))
atomNumber_var.standard_name = "atom__number"
#
#xyz_var = ofl.createVariable("xyz", "f",("xyz",))
#xyz_var.units = "nanometers"
#xyz_var.standard_name = "xyz"
#
#configuration_var = ofl.createVariable("configuration", "f", ("step_number", "atom_number", "xyz"))
#configuration_var.units = "nanometers"
#configuration_var.standard_name = "configuration"
#
#print configuration_var.shape
#step_var = ofl.createVariable("box_size_lenght", 3)
#configuration_var = ofl.createVariable("atom_number", nAtoms)
#description_var = ofl.createVariable("xyz", 3)
#time_var = ofl.createVariable(description_lenght, description_lenghtLenght)
#
#a = infl.variables["step_number"].dimensions.keys()
#print a
Thanks!
This may be a case of a library trying to be "helpful" (see the end of my post for details, but I can't confirm it). To fix this, you should explicitly create dimensions for atom_number and step_number, by using the following before you create the variables (assuming I am understanding nSteps and nAtoms correctly):
ofl.createDimension("step_number", nSteps)
ofl.createDimension("atom_number", nAtoms)
If you are new to netCDF, I might suggest looking at either the netcdf4-python package,
http://unidata.github.io/netcdf4-python/
of the netCDF package found in scipy:
http://docs.scipy.org/doc/scipy/reference/io.html
What might be going on: it looks like the issue is that when you create the variable step_number, the library is trying to be helpful by creating a step_number dimension with unlimited length. However, you can only have one unlimited dimension in a netcdf-3 file, so the helpful "trick" does not work.
atomNumber_var.standard_name = "atom__number"
The atom__number has two "__" instead of one "_". I am not sure if this is your problem, but it may be something to look at.
I would also suggest making your netcdf file steps clearer. I like to break them down into 3 steps. I used an example of scientific data using ocean sst. You also have a section for creating dimensions, but you don't actually do it. This is more correctly create variable section.
Create Dimensions
Create Variable
Fill the variable
from netCDF4 import Dataset
ncfile = Dataset('temp.nc','w')
lonsdim = latdata.shape #Set dimension lengths
latsdim = londata.shape
###############
#Create Dimensions
###############
latdim = ncfile.createDimension('latitude', latsdim)
londim = ncfile.createDimension('longitude', lonsdim)
###############
#Create Variables
################# The variables contain the dimensions previously set
latitude = ncfile.createVariable('latitude','f8',('latitude'))
longitude = ncfile.createVariable('longitude','f8',('longitude'))
oceantemp = ncfile.createVariable('SST','f4' ('latitude','longitude'),fill_value=-99999.0)
###############
Fill Variables
################
latitude[:] = latdata #lat data to fill in
longitude[:] = londata #lon data to fill in
oceantemp[:,:] = sst[:,:] #some variable previous calculated
I hope this is helpful.

How to pull specific information from an output in Python

So I have a code that gives an output, and what I need to do is pull the information out in between the commas, assign them to a variable that changes dynamically when called... here is my code:
import re
data_directory = 'Z:/Blender_Roto/'
data_file = 'diving_board.shape4ae'
fullpath = data_directory + data_file
print("====init=====")
file = open(fullpath)
for line in file:
current_line = line
# massive room for optimized code here.
# this assumes the last element of the line containing the words
# "Units Per Second" is the number we are looking for.
# this is a non float number, generally.
if current_line.find("Units Per Second") != -1:
fps = line_split = float(current_line.split()[-1])
print("Frames Per Second:", fps)
# source dimensions
if current_line.find("Source Width") != -1:
source_width = line_split = int(current_line.split()[-1])
print("Source Width:", source_width)
if current_line.find("Source Height") != -1:
source_height = line_split = int(current_line.split()[-1])
print("Source Height:", source_height)
# aspect ratios
if current_line.find("Source Pixel Aspect Ratio") != -1:
source_px_aspect = line_split = int(current_line.split()[-1])
print("Source Pixel Aspect Ratio:", source_px_aspect)
if current_line.find("Comp Pixel Aspect Ratio") != -1:
comp_aspect = line_split = int(current_line.split()[-1])
print("Comp Pixel Aspect Ratio:", comp_aspect)
# assumption, ae file can contain multiple mocha shapes.
# without knowing the exact format i will limit the script
# to deal with one mocha shape being animated N frames.
# this gathers the shape details, and frame number but does not
# include error checking yet.
if current_line.find("XSpline") != -1:
# record the frame number.
frame = re.search("\s*(\d*)\s*XSpline", current_line)
if frame.group(1) != None:
frame = frame.group(1)
print("frame:", frame)
# pick part the part of the line that deals with geometry
match = re.search("XSpline\((.+)\)\n", current_line)
line_to_strip = match.group(1)
points = re.findall('(\(.*?\))', line_to_strip)
print(len(points))
for point in points:
print(point)
print("="*40)
file.close()
This gives me the output:
====init=====
Frames Per Second: 24.0
Source Width: 2048
Source Height: 778
Source Pixel Aspect Ratio: 1
Comp Pixel Aspect Ratio: 1
frame: 20
5
(0.793803,0.136326,0,0.5,0)
(0.772345,0.642332,0,0.5,0)
(0.6436,0.597615,0,0.5,0)
(0.70082,0.143387,0,0.5,0.25)
(0.70082,0.112791,0,0.5,0)
========================================
So what I need for example is to be able to assign (0.793803, 0.136326, 0, 0.5, 0) to (1x,1y,1z,1w,1s), (0.772345,0.642332,0,0.5,0) to (2x, 2y, 2z, 2w, 2s) etc so that no matter what numbers are filling those positions they will take on that value.
here is the code I need to put those numbers into:
#-------------------------------------------------------------------------------
# Name: Mocha Rotoscoping Via Blender
# Purpose: Make rotoscoping more efficient
#
# Author: Jeff Owens
#
# Created: 11/07/2011
# Copyright: (c) jeff.owens 2011
# Licence: Grasshorse
#-------------------------------------------------------------------------------
#!/usr/bin/env python
import sys
import os
import parser
sys.path.append('Z:\_protomotion\Prog\HelperScripts')
import GetDir
sys.path.append('Z:\_tutorials\01\tut01_001\prod\Blender_Test')
filename = 'diving_board.shape4ae'
infile = 'Z:\_tutorials\01\tut01_001\prod\Blender_Test'
import bpy
from mathutils import Vector
#below are taken from mocha export
x_width =2048
y_height = 778
z_depth = 0
frame = 20
def readText():
text_file = open('diving_board.shape4ae', 'r')
lines = text_file.readlines()
print (lines)
print (len.lines)
for line in lines:
print (line)
##sets points final x,y,z value taken from mocha export for blender interface
point1x = (0.642706 * x_width)
point1y = (0.597615 * y_height)
point1z = (0 * z_depth)
point2x = (0.770557 * x_width)
point2y = (0.647039 * y_height)
point2z = (0 * z_depth)
point3x = (0.794697 * x_width)
point3y = (0.0869024 * y_height)
point3z = (0 * z_depth)
point4x = (0.707973* x_width)
point4y = (0.0751348 * y_height)
point4z = (0 * z_depth)
w = 1 # weight
listOfVectors = [Vector((point1x,point1y,point1z)),Vector((point2x,point2y,point2z)),Vector((point3x,point3 y,point3z)),Vector((point4x,point4y,point4z)), Vector((point1x,point1y,point1z))]
def MakePolyLine(objname, curvename, cList):
curvedata = bpy.data.curves.new(name=curvename, type='CURVE')
curvedata.dimensions = '3D'
objectdata = bpy.data.objects.new(objname, curvedata)
objectdata.location = (0,0,0) #object origin
bpy.context.scene.objects.link(objectdata)
polyline = curvedata.splines.new('POLY')
polyline.points.add(len(cList)-1)
for num in range(len(cList)):
x, y, z = cList[num]
polyline.points[num].co = (x, y, z, w)
MakePolyLine("NameOfMyCurveObject", "NameOfMyCurve", listOfVectors)
So where I have my vector I would like to be able to place (p.x, p.y,0.z,p.w,p.s) then (p2.x,p2.y,p2.zp2.wp2.s) etc so that it can change per the number given
Any help will be great.. thank you in advance!
-jeff
Instead of printing each output, you can create point objects and index them by name. For example:
>>> class Point:
... def __init__(self, t):
... (self.x,self.y,self.z,self.w,self.s) = t
...
>>> p = Point( (3,4,5,3,1) )
>>> p.w
3
You can place these point objects in an array, then access components by
myPoints[3].x
ADDENDUM
If it is important to you not to pull the points from an array, but rather use actual variable names, you can do the following, where points is your array of tuples:
(p0x,p0y,p0z,p0w,p0s) = points[0]
(p1x,p1y,p1z,p1w,p1s) = points[1]
(p2x,p2y,p2z,p2w,p2s) = points[2]
...
and so on.
Do consider whether this is an appropriate approach though. Having a point class allows you to have any number of points. With defined variable names, creating an unbounded number of these things on the fly is possible but almost always a bad idea. Here is a caveat about doing so: http://mail.python.org/pipermail/tutor/2005-January/035232.html.
When you have an array of point objects you do what you want much better! For example you can do the following:
myPoints[i].y = 12
thereby changing the y-coordinate of the ith point. This is next to impossible when you have fixed the variable names. Hope that helps! (And hope I understand your clarification! Let me know if not....)
If I'm reading your code right, the relevant portion is the loop at the end that produces your tuples.
data = []
for point in points:
data.append(point)
print(point)
That will create a new list and add each tuple to the list. So, data[0] holds (0.793803,0.136326,0,0.5,0) and data[0][0] holds 0.793803.

Categories