Python3 Print on Same Line - Numbers in 7-Segment-Device Format - python

I'm new to Python and having difficulty getting the output to print on one line.
This is pertaining to the online Python class Learning Python Essentials Lab 5.1.10.6 and printing to a 7-segment-device. If you are unfamiliar with a 7-segment-device, see Wikipedia.
I am NOT using any external device. I only need it to print to my own terminal. All the other StackOverflow solutions I found are related to using actual devices and didn't help.
Lab Link:
https://edube.org/learn/programming-essentials-in-python-part-2/lab-a-led-display
Purpose: Prompt user for number; print number in 7-segment display
format to your terminal.
Notes: Using Python3.9. I tried 3 alternate solutions (Option 1,2,3), but none do what I want it to.
INSTRUCTIONS: Un/Comment Option 1,2,or 3 to run just that option
I did find this alternate solution, which I mostly understand. However, it's a totally different approach and not one I would have come up with. I know there are many ways to skin a 7-segment-device, and if this is the most correct, then I'll learn it. But I feel like I'm so close and only a superfluous '\n' away from figuring it out with my own method and trying to understand what I'm missing.
Thank you for your help.
Desired Output
### ## ### ### # # ### ### ### ### ###
# # ### # # # # # # # # # # #
# # ## ### ### ### ### ### # ### ###
# # ## # # # # # # # # # #
### ## ### ### # ### ### # ### ###
My Code
# clear screen each time you run the script
import os
clear = lambda: os.system('cls')
clear()
#
# Dictionary of (number:7-segment-hash)
dict1 = {
'0':('###','# #','# #','# #','###'),
'1':('#####'),
'2':('###',' #','###','# ','###'),
'3':('###',' #','###',' #','###'),
'4':('# #','# #','###',' #',' #'),
'5':('###','# ','###',' #','###'),
'6':('###','# ','###','# #','###'),
'7':('###',' #',' #',' #',' #'),
'8':('###','# #','###','# #','###'),
'9':('###','# #','###',' #','###')
}
# Function to print numbers in 7-segment-device format
def fun_PrintNums(num):
if num < 0 or num % 1 > 0 or type(num)!=int: # if num is NOT a positive whole integer
return "Invalid entry, please try again"
else:
display = [' ']
for i in str(num): # convert 'num' to STRING; for each "number" in string 'num'
#'''Option 1: works, but prints nums vertically instead of side-by-side; Return=None ''' #
for char in dict1[i]:
print(*char)
print(fun_PrintNums(int(input("Enter any string of whole numbers: "))))
#----------------------------------------------------------------#
#''' Option 2: Return works, but still vertical and not spaced out ''' #
# for char in dict1[i]:
# display.append(char)
# return display
# print('\n'.join(fun_PrintNums(int(input("Enter any string of whole numbers: ")))))
#---------------------------------------------------------------------#
#''' Option 3: 'display' row1 offset; spaced out as desired, but vertical; Return=None''' #
# for char in dict1[i]:
# display += char
# display += '\n'
# a = print(*display,end='')
# return a
# print(fun_PrintNums(int(input("Enter any string of whole numbers: "))))
#---------------------------------------------------------------#
Option 1 Output
Works, but prints nums vertically instead of side-by-side; Return=None
# # #
#
# # #
#
# # #
# # #
#
# # #
#
# # #
None
Option 2 Output
Return works, but still vertical and not spaced out.
###
#
###
#
###
###
#
###
#
###
Option 3 Output
'display' row1 offset; spaced out as desired, but vertical; Return=None
# # #
#
# # #
#
# # #
# # #
#
# # #
#
# # #
None

Your problem is that you are printing each number before the next, but you need to print each row before the next. As a simplified example:
dict1 = {
'0':('###','# #','# #','# #','###'),
'1':(' ##','###',' ##',' ##',' ##'),
'2':('###',' #','###','# ','###'),
'3':('###',' #','###',' #','###'),
'4':('# #','# #','###',' #',' #'),
'5':('###','# ','###',' #','###'),
'6':('###','# ','###','# #','###'),
'7':('###',' #',' #',' #',' #'),
'8':('###','# #','###','# #','###'),
'9':('###','# #','###',' #','###')
}
num = '0123456789'
for row in range(len(dict1['0'])):
print(' '.join(dict1[i][row] for i in num))
Output:
### ## ### ### # # ### ### ### ### ###
# # ### # # # # # # # # # # #
# # ## ### ### ### ### ### # ### ###
# # ## # # # # # # # # # #
### ## ### ### # ### ### # ### ###
If you don't want to use a list comprehension inside join, you can unroll that like this:
for row in range(len(dict1['0'])):
line = []
for i in num:
line.append(dict1[i][row])
print(' '.join(line))

Related

Simulations taking too long and failing with simple model in abaqus

I'm trying to simulate the compression of a tensegrity structure in abaqus but can't achieve a solution as the time increment is too slow and the simulations keep on failing.
The model simulates a tensegrity regular truncated cuboctahedron being compressed of 0.15 of the radius of the circumsphere surrounding the structure (not present in the model as it is only used to size the model).
The model is fixed at the bottom while the upper part is free to rotate while a displacement BC is used to compress the structure. I've added some constraint to the nodes in the middle to force them to stay in the same plane (this should be a typical behaviour for tensegrity structures and the BCs are okay since they don't produce significant reaction forces).
My goal would be to run this and many other tensegrity simulations adding bendability (using quadratic beams in the simulation) and other internal structures but all simulations have more or less the same problem as at some point it fails due to excess rotation.
BCs can be seen here
The model has few elements and nodes so it should be easy to run in abaqus but if I don't force mass scaling I end up having very small increments and that's not feasible for my model.
The material properties are taken from the literature as the model simulates the compression of a cytoskeleton of a cell. I've tried everything from increasing or decreasing the seed number on the beams to adjusting the boundary conditions and I don't know what to do anymore.
I'm attaching the python3 code that I made to create this model, in the initial part it is possible to adjust mass scaling, the seeding of the beams and the geometrical and mechanical parameters of the model.
Thanks to anyone who'll help me understand what I'm doing wrong!
# Sript aimed at generating the necessary geometries and material properties
# of the Tensegrity cuboctahedron with 1 layer (no nucleoskeleton).
## Units
# Length - mm
# Force - N
# Stress - MPa
# Mass - Ton
# Density - Ton/mm3
# Time - s
# # # # # # # # VARIABLES INITIALIZATION # # # # # # # #
# General
import copy
import math
# -*- coding: mbcs -*-
import mesh
from part import *
from material import *
from section import *
from assembly import *
from step import *
from interaction import *
from load import *
from mesh import *
from optimization import *
from job import *
from sketch import *
from visualization import *
from connectorBehavior import *
import numpy as np
# import matplotlib.pyplot as plt
# General
MassScale = 1e-4
cpus = 1
seedmt = 2
# Type of experiment
Bendable = True
Compression = True
Time = 9 # seconds
Displace = 0.15 # Relative displacement (Percentage of cell radius)
# Microtubules
Emt = 1200 # Young's Module in MPa
BSmt = 1 # Bending Stiffness
CAmt = 0.00000000019 # Cross sectional Area in mm2
vmt = 0.3 # Poisson's ratio
Rmt = math.sqrt(CAmt / math.pi) # Radius of the cross sectional area
Densmt = 1.43e-09 # Density
# Microfilaments
Emf = 2600 # Young's Module in MPa
CAmf = 0.000000000019 # Cross sectional Area in nm2
vmf = 0.3 # Poisson's ratio
Rmf = math.sqrt(CAmf / math.pi) # Radius of the cross sectional area
Densmf = 1.43e-09 # Density
# Almost fixed variables
cell_radius = 0.015
prestress = 0
model_name = ''
Displace = cell_radius*Displace # Total displacement in nm (if Stress Relaxation)
# Compute model name
if Bendable:
model_name = model_name + 'B_'
if Compression:
model_name = model_name + 'Comp'
else:
model_name = model_name + 'Trac'
model_name = model_name
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # CALCULATIONS FOR NODES # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Input points
x = np.array([-1.5, -1.5, -1, -1, -1, -1, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 1, 1, 1, 1, 1.5, 1.5])
y = np.array([-0.5, 0.5, -1, -1, 1, 1, -1.5, -0.5, -0.5, 0.5, 0.5, 1.5, -1.5, -0.5, -0.5, 0.5, 0.5, 1.5, -1, -1, 1, 1, -0.5, 0.5])
z = np.array([0, 0, -(1/math.sqrt(2)), 1/math.sqrt(2), -(1/math.sqrt(2)), 1/math.sqrt(2), 0, -(math.sqrt(2)), math.sqrt(2), -(math.sqrt(2)), math.sqrt(2), 0, 0, -(math.sqrt(2)), math.sqrt(2), -(math.sqrt(2)), math.sqrt(2), 0,-(1/math.sqrt(2)), 1/math.sqrt(2), -(1/math.sqrt(2)), 1/math.sqrt(2), 0, 0])
# Adjust to the cell radius
factor = (1/math.sqrt(5/2))*cell_radius
x1 = np.multiply(x, factor)
y1 = np.multiply(y, factor)
z1 = np.multiply(z, factor)
p1 = np.array([x1[0], y1[0], z1[0]])
p2 = np.array([x1[1], y1[1], z1[1]])
p3 = np.array([x1[2], y1[2], z1[2]])
p4 = np.array([x1[3], y1[3], z1[3]])
p5 = np.array([x1[4], y1[4], z1[4]])
p6 = np.array([x1[5], y1[5], z1[5]])
p7 = np.array([x1[6], y1[6], z1[6]])
p8 = np.array([x1[7], y1[7], z1[7]])
p9 = np.array([x1[8], y1[8], z1[8]])
p10 = np.array([x1[9], y1[9], z1[9]])
p11 = np.array([x1[10], y1[10], z1[10]])
p12 = np.array([x1[11], y1[11], z1[11]])
p13 = np.array([x1[12], y1[12], z1[12]])
p14 = np.array([x1[13], y1[13], z1[13]])
p15 = np.array([x1[14], y1[14], z1[14]])
p16 = np.array([x1[15], y1[15], z1[15]])
p17 = np.array([x1[16], y1[16], z1[16]])
p18 = np.array([x1[17], y1[17], z1[17]])
p19 = np.array([x1[18], y1[18], z1[18]])
p20 = np.array([x1[19], y1[19], z1[19]])
p21 = np.array([x1[20], y1[20], z1[20]])
p22 = np.array([x1[21], y1[21], z1[21]])
p23 = np.array([x1[22], y1[22], z1[22]])
p24 = np.array([x1[23], y1[23], z1[23]])
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # PART CREATION # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
profile_name = 'CytoskeletonProfile'
Model = mdb.Model(modelType=STANDARD_EXPLICIT, name=model_name)
# Microtubuli
CskPart = Model.Part(dimensionality=THREE_D, name='Csk', type=DEFORMABLE_BODY)
CskPart.ReferencePoint(point=(p17[0], p17[1], p17[2]))
CskPart.DatumPointByCoordinate(coords=(p13[0], p13[1], p13[2]))
CskPart.DatumPointByCoordinate(coords=(p19[0], p19[1], p19[2]))
CskPart.DatumPointByCoordinate(coords=(p4[0], p4[1], p4[2]))
CskPart.DatumPointByCoordinate(coords=(p20[0], p20[1], p20[2]))
CskPart.DatumPointByCoordinate(coords=(p21[0], p21[1], p21[2]))
CskPart.DatumPointByCoordinate(coords=(p8[0], p8[1], p8[2]))
CskPart.DatumPointByCoordinate(coords=(p23[0], p23[1], p23[2]))
CskPart.DatumPointByCoordinate(coords=(p7[0], p7[1], p7[2]))
CskPart.DatumPointByCoordinate(coords=(p10[0], p10[1], p10[2]))
CskPart.DatumPointByCoordinate(coords=(p3[0], p3[1], p3[2]))
CskPart.DatumPointByCoordinate(coords=(p6[0], p6[1], p6[2]))
CskPart.DatumPointByCoordinate(coords=(p15[0], p15[1], p15[2]))
CskPart.DatumPointByCoordinate(coords=(p1[0], p1[1], p1[2]))
CskPart.DatumPointByCoordinate(coords=(p16[0], p16[1], p16[2]))
CskPart.DatumPointByCoordinate(coords=(p2[0], p2[1], p2[2]))
CskPart.DatumPointByCoordinate(coords=(p22[0], p22[1], p22[2]))
CskPart.DatumPointByCoordinate(coords=(p5[0], p5[1], p5[2]))
CskPart.DatumPointByCoordinate(coords=(p9[0], p9[1], p9[2]))
CskPart.DatumPointByCoordinate(coords=(p12[0], p12[1], p12[2]))
CskPart.DatumPointByCoordinate(coords=(p18[0], p18[1], p18[2]))
CskPart.DatumPointByCoordinate(coords=(p14[0], p14[1], p14[2]))
CskPart.DatumPointByCoordinate(coords=(p24[0], p24[1], p24[2]))
CskPart.DatumPointByCoordinate(coords=(p11[0], p11[1], p11[2]))
Microtubules = CskPart.WirePolyLine(meshable=ON, points=((CskPart.referencePoints[1], CskPart.datums[2]),
(CskPart.datums[3], CskPart.datums[4]),
(CskPart.datums[5], CskPart.datums[6]),
(CskPart.datums[7], CskPart.datums[8]),
(CskPart.datums[9], CskPart.datums[10]),
(CskPart.datums[11], CskPart.datums[12]),
(CskPart.datums[13], CskPart.datums[14]),
(CskPart.datums[15], CskPart.datums[16]),
(CskPart.datums[17], CskPart.datums[18]),
(CskPart.datums[19], CskPart.datums[20]),
(CskPart.datums[21], CskPart.datums[22]),
(CskPart.datums[23], CskPart.datums[24]))) # IMPRINT
Microfilaments = CskPart.WirePolyLine(meshable=ON, points=((CskPart.referencePoints[1], CskPart.datums[24]),
(CskPart.referencePoints[1], CskPart.datums[17]),
(CskPart.referencePoints[1], CskPart.datums[13]),
(CskPart.datums[2], CskPart.datums[5]),
(CskPart.datums[2], CskPart.datums[9]),
(CskPart.datums[2], CskPart.datums[3]),
(CskPart.datums[3], CskPart.datums[8]),
(CskPart.datums[3], CskPart.datums[22]),
(CskPart.datums[4], CskPart.datums[19]),
(CskPart.datums[4], CskPart.datums[14]),
(CskPart.datums[4], CskPart.datums[9]),
(CskPart.datums[5], CskPart.datums[13]),
(CskPart.datums[5], CskPart.datums[8]),
(CskPart.datums[6], CskPart.datums[15]),
(CskPart.datums[6], CskPart.datums[23]),
(CskPart.datums[6], CskPart.datums[21]),
(CskPart.datums[7], CskPart.datums[11]),
(CskPart.datums[7], CskPart.datums[10]),
(CskPart.datums[7], CskPart.datums[22]),
(CskPart.datums[8], CskPart.datums[23]),
(CskPart.datums[9], CskPart.datums[11]),
(CskPart.datums[10], CskPart.datums[18]),
(CskPart.datums[10], CskPart.datums[15]),
(CskPart.datums[11], CskPart.datums[14]),
(CskPart.datums[12], CskPart.datums[16]),
(CskPart.datums[12], CskPart.datums[20]),
(CskPart.datums[12], CskPart.datums[24]),
(CskPart.datums[13], CskPart.datums[19]),
(CskPart.datums[14], CskPart.datums[16]),
(CskPart.datums[15], CskPart.datums[22]),
(CskPart.datums[16], CskPart.datums[18]),
(CskPart.datums[17], CskPart.datums[23]),
(CskPart.datums[17], CskPart.datums[21]),
(CskPart.datums[18], CskPart.datums[20]),
(CskPart.datums[19], CskPart.datums[24]),
(CskPart.datums[20], CskPart.datums[21]))) # IMPRINT
# Sets
MtSet = CskPart.Set(edges=CskPart.getFeatureEdges(Microtubules.name), name='MtSet')
MfSet = CskPart.Set(edges=CskPart.getFeatureEdges(Microfilaments.name), name='MfSet')
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # PROPERTIES # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
## Material properties
# Microfilaments
MfMat = Model.Material(name='Microfilaments')
MfMat.Density(table=((Densmf,),))
MfMat.Elastic(noCompression=OFF, table=((Emf, vmf),)) # Table contains E and v
# Microtubules
MtMat = Model.Material(name='Microtubules')
MtMat.Density(table=((Densmt,),))
MtMat.Elastic(noCompression=OFF, table=((Emt, vmt),)) # Table contains E and v
## Section assignment
if Bendable:
# Microtubules
MtProfile = Model.CircularProfile(name='MicrotubulesProfile', r=Rmt)
MtSection = Model.BeamSection(consistentMassMatrix=False, integration=DURING_ANALYSIS, material=MtMat.name, name='MtSection', poissonRatio=0.3, profile=MtProfile.name, temperatureVar=LINEAR)
CskPart.SectionAssignment(offset=0.0, offsetField='', offsetType=MIDDLE_SURFACE, region=MtSet, sectionName=MtSection.name, thicknessAssignment=FROM_SECTION)
CskPart.assignBeamSectionOrientation(method=N1_COSINES, n1=(0.0, 1.0, -1.0), region=MtSet)
else:
# Microtubules
MtSection = Model.TrussSection(area=CAmt, material=MtMat.name, name='MtSection')
CskPart.SectionAssignment(offset=0.0, offsetField='', offsetType=MIDDLE_SURFACE, region=MtSet, sectionName=MtSection.name, thicknessAssignment=FROM_SECTION)
# Microfilaments
MfSection = Model.TrussSection(area=CAmf, material=MfMat.name, name='MfSection')
CskPart.SectionAssignment(offset=0.0, offsetField='', offsetType=MIDDLE_SURFACE, region=MfSet, sectionName=MfSection.name, thicknessAssignment=FROM_SECTION)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # ASSEMBLY # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Generate Assembly
Assembly = Model.rootAssembly
Assembly.DatumCsysByDefault(CARTESIAN)
# Create Cytoskeleton
CskInstance = Assembly.Instance(dependent=ON, name='Csk', part=CskPart)
Centroid = np.array([(p14[0] + p24[0]) / 2, (p14[1] + p24[1]) / 2, (p14[2] + p24[2]) / 2])
norm = Centroid / np.linalg.norm(Centroid)
zaxis = np.array([0,0,1])
direct = np.cross(norm,zaxis)
angle = math.acos(norm[2])
angle = angle * 180 / math.pi
Assembly.rotate(angle=angle, axisDirection=direct, axisPoint=(0.0, 0.0, 0.0), instanceList=[CskInstance.name])
Model.rootAssembly.regenerate()
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # STEPS # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Preparing steps for explicit solver
Model.ExplicitDynamicsStep(improvedDtMethod=ON, timePeriod=Time,
massScaling=((SEMI_AUTOMATIC, MODEL, THROUGHOUT_STEP, 0.0, MassScale, BELOW_MIN, 1, 0, 0.0,
0.0, 0, None),),
name='Loading', previous='Initial')
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # LOADS # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Create Set of fixed nodes
minz = 0
maxz = 0
for i in range(24):
tempz = CskInstance.vertices[i].pointOn[0][2]
if tempz < minz:
minz = tempz
elif tempz > maxz:
maxz = tempz
LoadNodes = []
FixedNodes = []
InternalNodes = []
for i in range(24):
node = CskInstance.vertices[i]
tempz = node.pointOn[0][2]
if tempz == minz:
FixedNodes.append(node)
elif tempz == maxz:
LoadNodes.append(node)
else:
InternalNodes.append(node)
# Reverse Force and displacement if traction
if not Compression:
Displace = - Displace
Model.TabularAmplitude(data=((0.0, 0.0), (Time/float(2), 0.5), (Time, 1)), name='LinearLoading', smooth=SOLVER_DEFAULT, timeSpan=STEP)
# Create Loads and boundary conditions
Model.DisplacementBC(name='Displacement', createStepName='Loading', region=LoadNodes, amplitude='LinearLoading', u3=-Displace, ur3=0)
Model.EncastreBC(createStepName='Initial', localCsys=None, name='FixedNodes', region=FixedNodes)
Model.DisplacementBC(name='InternalPlanes', createStepName='Loading', region=InternalNodes, amplitude='LinearLoading', ur1=0, ur2=0)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # MESH # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
if not Bendable:
seedmt = 1
# Assign number of elements per microfilaments and Microtubules
CskPart.seedEdgeByNumber(edges=MtSet.edges[:], number=seedmt, constraint=FINER)
CskPart.seedEdgeByNumber(edges=MfSet.edges[:], number=1, constraint=FINER)
TrussMeshMf = mesh.ElemType(elemCode=T3D2, elemLibrary=EXPLICIT) # Microfilaments are always not bendable
if Bendable:
TrussMeshMt = mesh.ElemType(elemCode=B32, elemLibrary=EXPLICIT) # B31 Linear Beam, B32 Quadratic Beam
else:
TrussMeshMt = mesh.ElemType(elemCode=T3D2, elemLibrary=EXPLICIT)
# Assign Element type
CskPart.setElementType(regions=MfSet, elemTypes=(TrussMeshMf,))
CskPart.setElementType(regions=MtSet, elemTypes=(TrussMeshMt,))
# Generate the mesh
CskPart.generateMesh()
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # JOB # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Build job name
JobName = 'Cubo'
if Bendable:
JobName = JobName + '_Bend'
if Compression:
JobName = JobName + '_Comp'
else:
JobName = JobName + '_Tract'
JobName = JobName
# Build Job
mdb.Job(name=JobName, model=model_name, description='A description',
type=ANALYSIS, atTime=None, waitMinutes=0, waitHours=0, queue=None,
memory=90, memoryUnits=PERCENTAGE, explicitPrecision=DOUBLE_PLUS_PACK,
nodalOutputPrecision=FULL, echoPrint=OFF, modelPrint=OFF,
contactPrint=OFF, historyPrint=OFF, userSubroutine='', scratch='',
resultsFormat=ODB, parallelizationMethodExplicit=DOMAIN, numDomains=cpus,
activateLoadBalancing=False, multiprocessingMode=DEFAULT, numCpus=cpus)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # HISTORY # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
Model.FieldOutputRequest(createStepName='Loading',
name='Loading', numIntervals=300, variables=PRESELECT)
Model.HistoryOutputRequest(createStepName='Loading',
name='Loading', variables=PRESELECT)
Model.rootAssembly.regenerate()

"Could not convert string to float" when importing CSV to Blender

I have a script I'm trying to use (not mine) which is meant to import CSV data into Blender as a mesh.
I have two CSV files which are two parts of the same model, the script works fine for importing one of the CSV files but throws a "ValueError" when I try to import the second.
The error can be seen here:
As far as I know there's only one "-1" in the script, I've tried changing it, removing it, nothing works, I still get the same error.
I've also tried changing the encoding on the CVS files themselves but that didn't work either.
I don't know much about scripting and I'm at my wits end, any help would be greatly appreciated.
The script I'm using is here:
https://github.com/sbobovyc/GameTools/blob/master/Blender/import_pix.py
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
# <pep8 compliant>
import bpy
import csv
import mathutils
from bpy_extras.io_utils import unpack_list, unpack_face_list, axis_conversion
from bpy.props import (BoolProperty,
FloatProperty,
StringProperty,
EnumProperty,
)
from collections import OrderedDict
bl_info = {
"name": "PIX CSV",
"author": "Stanislav Bobovych",
"version": (1, 0, 0),
"blender": (2, 7, 8),
"location": "File > Import-Export",
"description": "Import PIX csv dump of mesh. Import mesh, normals and UVs.",
"category": "Import"}
class PIX_CSV_Operator(bpy.types.Operator):
bl_idname = "object.pix_csv_importer"
bl_label = "Import PIX csv"
filepath = bpy.props.StringProperty(subtype="FILE_PATH")
filter_glob = StringProperty(default="*.csv", options={'HIDDEN'})
mirror_x = bpy.props.BoolProperty(name="Mirror X",
description="Mirror all the vertices across X axis",
default=True)
vertex_order = bpy.props.BoolProperty(name="Change vertex order",
description="Reorder vertices in counter-clockwise order",
default=True)
axis_forward = EnumProperty(
name="Forward",
items=(('X', "X Forward", ""),
('Y', "Y Forward", ""),
('Z', "Z Forward", ""),
('-X', "-X Forward", ""),
('-Y', "-Y Forward", ""),
('-Z', "-Z Forward", ""),
),
default='Z')
axis_up = EnumProperty(
name="Up",
items=(('X', "X Up", ""),
('Y', "Y Up", ""),
('Z', "Z Up", ""),
('-X', "-X Up", ""),
('-Y', "-Y Up", ""),
('-Z', "-Z Up", ""),
),
default='Y',
)
def execute(self, context):
keywords = self.as_keywords(ignore=("axis_forward",
"axis_up",
"filter_glob"))
global_matrix = axis_conversion(from_forward=self.axis_forward,
from_up=self.axis_up,
).to_4x4()
keywords["global_matrix"] = global_matrix
print(keywords)
importCSV(**keywords)
return {'FINISHED'}
def invoke(self, context, event):
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
def draw(self, context):
layout = self.layout
col = layout.column()
col.label(text="Import options")
row = col.row()
row.prop(self, "mirror_x")
row = col.row()
row.prop(self, "vertex_order")
layout.prop(self, "axis_forward")
layout.prop(self, "axis_up")
def make_mesh(verteces, faces, normals, uvs, global_matrix):
mesh = bpy.data.meshes.new('name')
mesh.vertices.add(len(verteces))
mesh.vertices.foreach_set("co", unpack_list(verteces))
mesh.tessfaces.add(len(faces))
mesh.tessfaces.foreach_set("vertices_raw", unpack_face_list(faces))
index = 0
for vertex in mesh.vertices:
vertex.normal = normals[index]
index += 1
uvtex = mesh.tessface_uv_textures.new()
uvtex.name = "UV"
for face, uv in enumerate(uvs):
data = uvtex.data[face]
data.uv1 = uv[0]
data.uv2 = uv[1]
data.uv3 = uv[2]
mesh.update(calc_tessface=False, calc_edges=False)
obj = bpy.data.objects.new('name', mesh)
# apply transformation matrix
obj.matrix_world = global_matrix
bpy.context.scene.objects.link(obj) # link object to scene
def importCSV(filepath=None, mirror_x=False, vertex_order=True, global_matrix=None):
if global_matrix is None:
global_matrix = mathutils.Matrix()
if filepath == None:
return
vertex_dict = {}
normal_dict = {}
vertices = []
faces = []
normals = []
uvs = []
with open(filepath) as f:
reader = csv.reader(f)
next(reader) # skip header
# face_count = sum(1 for row in reader) / 3
# print(face_count)
f.seek(0)
reader = csv.reader(f)
next(reader) # skip header
current_face = []
current_uv = []
i = 0
x_mod = 1
if mirror_x:
x_mod = -1
for row in reader:
vertex_index = int(row[0])
vertex_dict[vertex_index] = (x_mod*float(row[2]), float(row[3]), float(row[4]))
#TODO how are axis really ligned up?
# x, y, z = (vertex_dict[vertex_index][0], vertex_dict[vertex_index][1], vertex_dict[vertex_index][2])
# vertex_dict[vertex_index] = (x, z, y)
normal_dict[vertex_index] = (float(row[6]), float(row[7]), float(row[8]))
#TODO add support for changing the origin of UV coords
uv = (float(row[9]), 1.0 - float(row[10])) # modify V
if i < 2:
current_face.append(vertex_index)
current_uv.append(uv)
i += 1
else:
current_face.append(vertex_index)
#TODO add option to change order of marching vertices
if vertex_order:
faces.append((current_face[2], current_face[1], current_face[0]))
else:
faces.append(current_face)
current_uv.append(uv)
uvs.append(current_uv)
current_face = []
current_uv = []
i = 0
for i in range(len(vertex_dict)):
if i in vertex_dict:
pass
else:
# print("missing",i)
vertex_dict[i] = (0, 0, 0)
normal_dict[i] = (0, 0, 0)
# dictionary sorted by key
vertex_dict = OrderedDict(sorted(vertex_dict.items(), key=lambda t: t[0]))
normal_dict = OrderedDict(sorted(normal_dict.items(), key=lambda t: t[0]))
for key in vertex_dict:
vertices.append(list(vertex_dict[key]))
# print(key,vertex_dict[key])
for key in normal_dict:
normals.append(list(normal_dict[key]))
# print(vertices)
# print(faces)
# print(normals)
# print(uvs)
make_mesh(vertices, faces, normals, uvs, global_matrix)
def menu_func_import(self, context):
self.layout.operator(PIX_CSV_Operator.bl_idname, text="PIX CSV (.csv)")
def register():
bpy.utils.register_module(__name__)
bpy.types.INFO_MT_file_import.append(menu_func_import)
def unregister():
bpy.utils.unregister_module(__name__)
bpy.types.INFO_MT_file_import.remove(menu_func_import)
if __name__ == "__main__":
# register()
# These run the script from "Run script" button
bpy.utils.register_class(PIX_CSV_Operator)
bpy.ops.object.pix_csv_importer('INVOKE_DEFAULT')
Can you search if the string -, occurs anywhere in the CSV file that doesn’t work? - mkrieger1

Maze Pattern Building in Python

Hello I am a newbie to python and using python 3.
I wish to learn patterns and printing e.g stars etc. I want to make maze pattern but i confused to make maze no 2-no4
No 1
# #############
# #
############# #
# #
# #############
# #
############# #
# #
# #############
# #
############# #
# #
# #############
# #
############# #
No 2
# #############
# # # # #
# # # # # # ###
# # # # # # #
# # # # # ### #
# # # # # #
# # # # #######
# # # # #
# # # ####### #
# # # #
# # ###########
# # #
# ########### #
# #
###############
No 3
# #############
# # #
# # ######### #
# # # # #
# # # ##### # #
# # # # # # #
# # # # # # # #
# # # # # # # #
# # # ### # # #
# # # # # #
# # ####### # #
# # # #
# ########### #
# #
###############
No 4
# #############
# # #
# # ######### #
# # # # #
# # # ##### # #
# # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # #
# # ##### # # #
# # # # #
# ######### # #
# # #
############# #
This is my code maze no1:
def SimpleMaze(S):
bool=1
for i in range(S):
if (i+1)%2==0:
print('#'+' '*(S-2)+'#')
else:
if bool==1:
print('#'+' '+'#'*(S-2))
else:
print('#'*(S-2)+' '+'#')
bool=not bool
S= input("Nilai S:")
SimpleMaze(int(S))
You built Maze 1 by assembling it row by row, but the other mazes appear to have messier patterns when you think about them in terms of rows.
Here's another way to break down the problem. Start with a solid block, with rows 0..R and columns 0..C (inclusive).
###############
###############
###############
###############
###############
###############
###############
###############
###############
###############
###############
###############
###############
###############
###############
Then envision yourself creating a maze by driving a bulldozer through it, opening up the path as you go. Under this approach, we can represent a maze as a set of driving instructions. For example, Maze 1 looks like this:
Start at r==-1, c==1.
Go South 2 steps.
Go East until c==C-1.
Go South 2 steps.
Go West until c==1.
Repeat ... until r>R.
I think Mazes 2 through 4 will be easier to think about in those terms. Ideally, each of those concepts (go south, go east, etc) could be implemented as simple functions or methods.

How to make PyCollada output multiple meshes to the same scene?

So I am using pyCollada to try to export multiple meshes to the same scene. Alas, whenever I try to do so, I can only see one of the meshes I have loaded in. Am I doing something wrong when I create the file? Each individual mesh renders perfectly if I separate them into their own file, but they fail when I attempt to output them to the same file. I have looked through the API, but the documentation is very limited. Any help would be appreciated.
My code is listed shown below.
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 12 14:43:05 2015
#author: skylion
"""
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 11 11:01:48 2015
#author: danaukes
"""
import sys
import popupcad_deprecated
import popupcad_manufacturing_plugins
import popupcad
from popupcad.filetypes.design import Design
import PySide.QtGui as qg
#Draws Collada stuff
from collada import *
import numpy
geom_index = 0;
def exportBodyToMesh(output):
# csg = output.csg
generic = output.generic_laminate()
# layers = generic.layers()
layerdef = d.return_layer_definition()
layerdef.refreshzvalues()
# layers = layerdef.layers
mesh = Collada()
nodes = []
for layer in layerdef.layers:
shapes = generic.geoms[layer]#TODO Add it in for other shapes
zvalue = layerdef.zvalue[layer]
height = zvalue * 1/ popupcad.internal_argument_scaling
print zvalue
if (len(shapes) == 0) : #In case there are no shapes.
print "No shapes skipping"
continue
print shapes
for s in shapes:
geom = createMeshFromShape(s, height, mesh)
mesh.geometries.append(geom)
effect = material.Effect("effect" + str(geom_index), [], "phone", diffuse=(1,0,0), specular=(0,1,0))
mat = material.Material("material" + str(geom_index), "mymaterial", effect)
matnode = scene.MaterialNode("materialref" + str(geom_index), mat, inputs=[])
mesh.effects.append(effect)
mesh.materials.append(mat)
geomnode = scene.GeometryNode(geom, [matnode])
node = scene.Node("node" + str(geom_index), children=[geomnode])
nodes.append(node)
print nodes
myscene = scene.Scene("myscene", nodes)
mesh.scenes.append(myscene)
mesh.scene = myscene
# layer_num = layer_num + 1 #Add the layer thicknes instead of simply + 1
filename = str(output) + '.dae'
mesh.write(filename)
#TODO Add handling in case rigid body has already been selected.
print filename + " has been saved"
def createMeshFromShape(s,layer_num, mesh):
s.exteriorpoints()
a = s.triangles3()
vertices = []
global geom_index
for coord in a:
for dec in coord:
vertices.append(dec[0]) #x-axis
vertices.append(dec[1]) #y-axis
vertices.append(layer_num ) #z-axi
#This scales the verticies properly.
vert_floats = [x/popupcad.internal_argument_scaling for x in vertices]
vert_src = source.FloatSource("cubeverts-array" + str(geom_index), numpy.array(vert_floats), ('X', 'Y', 'Z'))
geom = geometry.Geometry(mesh, "geometry" + str(geom_index), "mycube", [vert_src])
input_list = source.InputList()
input_list.addInput(0, 'VERTEX', "#cubeverts-array" + str(geom_index))
indices = numpy.array(range(0,(len(vertices) / 3)));
triset = geom.createTriangleSet(indices, input_list, "materialref")
geom_index += 1
triset.generateNormals()
geom.primitives.append(triset)
return geom
#Start of actual script
print sys.argv
app = qg.QApplication('exporter.py')
d = Design.open()
print "Loading..."
d.reprocessoperations()
operation = d.operations[3] #Identify bodies
for output in operation.output:
exportBodyToMesh(output)
print "All objects printed"
#sys.exit(app.exec_())
Your code to add the geometry to the scene is outside your inner loop. You're only adding the last geometry to the scene, rather than all of them. You should be creating multiple GeometryNode and adding all of them to the Scene.

collision of two boxes:VIZARD:PYTHON

I used the collision of boxes that are placed in enviornment having two tables. I used the mouse cursor to grab the objects and placed in the other table. But i am facing one problem in case of collision detection between the objects. I used the proximity sensor for the objects and mouse when they are collided with each other ( minimum distance) then mouse picks/links that object. I am using the same sensor for collision also, some physics idea that are given in the documentation of vizard bt boxes are collided to each other but due to the gravity they are flying. i put the density as it is given in the documentation bt i does not works. Then idecided to move from this logic and try something else i tried to form the two proximity one for boxex collision and one between boxes and mouse but boxes are flying. I used the similar concept with crates that is define by vizard it work there bt not in the blocks. Please give some idea to resolve this problem. Here i am attaching thre function - one for hand , other for linking mouse and block and in last placing of blocks. In enviornment i already used the collide palne and collission for table also. So for collision what methodss i should go for because when i am working on same proximity sensors it will not works. All objects are placed in origin in vizard and then manually set the positions for plaing on table.`
global hand
hand = viz.addChild( 'marker.wrl' )
#hand.collidebox()
#xa,ya,za=hand.getPosition()
#hand.collideBox()
hand.enable(viz.COLLIDE_NOTIFY)
#hand.density=0.0000001
#viz.phys.setGravity([0,-1,0])
#vizact.onkeydown(' ', viz.phys.enable)
hand.setPosition( [-7.5, 1.2, -10] )
hand.setEuler(0,0,0)
hand.setScale(0.3,0.3,0.3)
ViewLink = viz.link(hand,viz.MainView)
viz.link(hand,device)
ViewLink.preEuler( [0,25 ,0] )
ViewLink.preTrans( [0,0.2,-0.5] )
def p_ball(e):
# print 'hit'
# global sound1
# sound1.play()
global bn
# grab = 1
# ball.addAction(blast
# b[z].addAction(blast)
for i in range(len(b)):
#global xh,zh
xh,yh,zh=hand.getPosition()
# zh= (zh)
# print 'abcd'
xb,yb,zb=b[i].getPosition()
zb= (abs(zb))
zh= (abs(zh))
xb= (abs(xb))
xh= (abs(xh))
#print zh,zb
if (abs(zh-zb)<.4 and abs(xh-xb)<.4):
# b[i].addAction(blast)
# b[i].visible(viz.OFF)
# b[i].visible(viz.ON)
global link
if bn==100:
link = None
link = viz.grab( hand, b[i] )
#tool.grabAndHold()
if link == True:
global Block1
Pos=Block1.getPosition(MODE=VIZ.REL_GLOBAL)
# else:
# print 'aaaaaa'
bn=i
#UpdateMovement()
#UpdateMovement()
global k
k=k+1
tbox2.message(str(k))
/i tried something here but it wont work. here i am using the proximity sensor for the collision of boxes.
xb11,yb11,zb11=b[0].getPosition() ####### proximity POSITION 1
print xb11,yb11,zb11
xb1= (abs(xb11))
zb1= (abs(zb11))
print xb1,zb1
xb22,yb22,zb22=b[1].getPosition() ` ` ####### proximity POSITION 2
print xb22,yb22,zb22
xb2= (abs(xb22))
zb2= (abs(zb22))
print xb2,zb2
xb33,yb33,zb33=b[2].getPosition() ` ` ####### proximity POSITION 3
print xb33,yb33,zb33
xb3= (abs(xb33))
zb3= (abs(zb33))
print xb3,zb3
#
# if ((zb1-zb2)<1.5 or (zb1-zb3)<1.5 or (xb1-xb2)<1.5
or (xb1-xb3)<1.5):
#
# print 'Ashish'
# global tbox22
# tbox22=viz.addTextbox()
# tbox22.setPosition(0.11,0.1,0.1)
# global touch11
# touch11='OBSTACLE-ERROR'
# tbox22.message(str(touch11))
#
# Block1.setPosition([-7.5,1.1,-2.9]) ` ####### POSITION OF THE BALLOON`
# Block2.setPosition([-7.5,1.1,-1.9]) ` ####### POSITION OF THE BALLOON`
#
# #Block0.setPosition(xb11-1,yb11,zb11-1) ` ####### POSITION OF THE BALLOON`
#
#
# elif ((zb2-zb1)<.5 or (zb2-zb3)<.5 or (xb2-xb1)<.5
or (xb2-xb3)<.5):
#
# print 'Ashish'
# global tbox22
# tbox22=viz.addTextbox()
#
# tbox22.setPosition(0.11,0.1,0.1)
# global touch11
# touch11='OBSTACLE-ERROR'
# tbox22.message(str(touch11))
#
# Block0.setPosition([-7.5,1.11,-3.7]) ` ####### POSITION OF THE BALLOON`
# Block2.setPosition([-7.5,1.1,-1.9]) ` ####### POSITION OF THE BALLOON`
#
# #Block1.setPosition(xb22-1,yb22,zb22-1) ` ####### POSITION OF THE BALLOON`
#
#
# elif ((zb3-zb1)<.5 or (zb3-zb2)<.5 or (xb3-xb1)<.5
or (xb3-xb2)<.5):`
#
# print 'Ashish'
# global tbox22
# tbox22=viz.addTextbox()
#
# tbox22.setPosition(0.11,0.03,0.1)
# global touch11
# touch11='OBSTACLE-ERROR'
# tbox22.message(str(touch11))
#
`# Block0.setPosition([-7.5,1.11,-3.7])` `
`# Block1.setPosition([-7.5,1.1,-2.9])` `
# #Block2.setPosition(xb33-1,yb33,zb33-1)
#abc()
fb()
/code for blocks i put the collision with the blocks same i put with plane /and tables while with ground plane then gravity pulls the object /downwards so i collision i used with the tables to`put the blocks on the /table
def put_balloons(manager_b,b,b_y,b2):
# import vizshape
# aa=vizshape.addCube()
# aa.setPosition(-7.5,1.1,2.4)
# kk=aa.collideBox()
# kk.density=100000
/BLOCK 1---------- TABLE 1
global Block0
Block0=viz.addChild('b2.osgb')
#crate = viz.addChild('crate.osgb',pos=[-7.38,1.2,-3.9])
#crate.visible(viz.OFF)
#crate.collideBox(density=50000000000)
#crate.alpha(0.3)
Block0.setPosition(-7.5,1.1,-3.7)
Block0.setEuler(90,0,0)
Block0.setScale(.3,.3,.3)
bs=vizproximity.addBoundingBoxSensor(Block0)
manager_b.addSensor(bs)
b.append(Block0)
#Block0.collideBox()
Block0.disable(viz.DYNAMICS)
# global link
# ss=viz.link(crate,Block0)
# ss.preTrans( [-0.17,-0.1,-.1 ])
# Block0.enable(viz.RENDERING)
/BLOCK 2---------- TABLE 1
global Block1
Block1=viz.addChild('b7.osgb')
#crate = viz.addChild('crate.osgb',pos=[-7.38,1.2,-3])
#crate.visible(viz.OFF)
#crate.collideBox(density=50000000000)
#crate.alpha(0.3)
Block1.setPosition(-7.5,1.1,-2.9)
Block1.setEuler(90,0,0)
Block1.setScale(.3,.3,.3)
bs=vizproximity.addBoundingBoxSensor(Block1)
manager_b.addSensor(bs)
b.append(Block1)
#Block1.collideBox()
Block1.disable(viz.DYNAMICS)
#Block1.enable(viz.RENDERING)
/BLOCK 3--------- TABLE
global Block2
Block2=viz.addChild('b9.osgb')
#crate = viz.addChild('crate.osgb',pos=[-7.38,1.2,-2.1])
#crate.visible(viz.OFF)
#crate.collideBox(density=50000000000)
#crate.alpha(0.3)
Block2.setPosition(-7.5,1.1,-1.9)
Block2.setEuler(90,0,0)
Block2.setScale(.3,.3,.3)
bs=vizproximity.addBoundingBoxSensor(Block2)
manager_b.addSensor(bs)
b.append(Block2)
Block2.collideBox()
#Block2.density=0.0000001
Block2.disable(viz.DYNAMICS)
#Block2.enable(viz.RENDERING)
/BLOCK 1----------TABLE2
global Block00
Block00=viz.addChild('b2.osgb')
Block00.setPosition(-7.5,1.15,4)
Block00.setEuler(90,0,0)
Block00.setScale(.3,.01,.3) #.025,.0004,.02,
b2.append(Block00)
/BLOCK 2----------TABLE2
global Block11
Block11=viz.addChild('b7.osgb')
Block11.setPosition(-7.5,1.15,5)
Block11.setEuler(90,0,0)
Block11.setScale(.3,.01,.3)
b2.append(Block11)
/BLOCK 3----------TABLE3
global Block22
Block22=viz.addChild('b9.osgb')
Block22.setPosition(-7.5,1.1,6)
Block22.setEuler(90,0,0)
Block22.setScale(.3,.01,.3)
b2.append(Block22)
#
#viz.phys.setGravity(0,-9) #Sets the Y plane gravity to -2
put_balloons(manager_b,b,b_y,b2)

Categories