Simulations taking too long and failing with simple model in abaqus - python
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()
Related
How to vitalize training and loss in Json file?
I have JSON file that has data where this dat orgnized in **dicttionary **format .I am writting small script for reading this json file and wanna convert it to spefic dict format (on other words rearrange data structuer and extract some spesfic data to make plot or vitulazation later ) The input Json file(trainer_state) can be found trainer_state.json This file produced by trainer class from huggingface lib Script.py import pandas as pd import json filename = '/checkpoint-2000/trainer_state.json' df = pd.read_json(filename) column_names = list(df.columns.values) print('column_names\n', column_names) # Opening JSON file with open(filename) as json_file: data = json.load(json_file) # print('show log_history', data['log_history']) log_history =data['log_history'] # print('\nlog_history\n',log_history[0]['epoch']) odd_dict , even_dict= {},{} log_history_dict = {} for count, value in enumerate(log_history): log_history_dict[count] = value print('\nlog_history_dict \n', log_history_dict) for k ,v in log_history_dict.items(): if k % 2 == 0: even_dict[k] = v else: odd_dict[k] = v # print('\n even_dict',even_dict , '\nodd_dict' , odd_dict) # log_history_clean = {} # for v in odd_dict.values(): # log_history_clean ['epoch'] = v['epoch'] # log_history_clean['learning_rate']= v['learning_rate'] # log_history_clean['loss']= v['loss'] # log_history_clean['step']= v['step'] # # for key ,value in v.items(): # # log_history_clean[key] = value # # print(key,value) # print(log_history_clean) Sample ex : we have this data structuer inside json file (trainer_state.json) # { # "best_metric": null, # "best_model_checkpoint": null, # "epoch": 1.4265335235378032, # "global_step": 2000, # "is_hyper_param_search": false, # "is_local_process_zero": true, # "is_world_process_zero": true, # "log_history":[ # { # "epoch": 0.36, # "learning_rate": 3.94339514978602e-05, # "loss": 0.5516, # "step": 500 # }, # { # "epoch": 0.36, # "eval_cer": 4.407666576772222, # "eval_loss": 0.25193867087364197, # "eval_runtime": 1338.5651, # "eval_samples_per_second": 13.973, # "eval_steps_per_second": 0.583, # "eval_wer": 17.79562559983836, # "step": 500 # }, # ] # } The expacted dict out I am trying to meet is : witten here # Goal : { 'index' : 0 # 'epoch': 0.36 , # 'learning_rate': 3.94339514978602e-05, # 'loss': 0.5516, # 'step': 500 , # 'epoch': 0.36 # 'eval_cer': 4.407666576772222, # 'eval_loss': 0.25193867087364, # 'eval_runtime': 1338.5651, # 'eval_samples_per_second': 13.973, # 'eval_steps_per_second': 0.583, # 'eval_wer': 17.79562559983836, # 'step': 500, # ... # # ..... # # }
Cannot visualize the points around one of the selected points in point cloud. Not sure what I am missing
I used this code. What it does is just takes a pointcloud and convert it into polydata and visualize it. After visualizing the pointcloud, I use mouse to select one point and calculate points around that particular point in a given radius. I am able to calculate those points but not able to visualize those. Also moving further I select 1000 random points in data and calculate their clusters too, calculate Hausdorff distances of each with original cluster and visualize the minimum distance cluster. In all this I am not able to visualize any cluster.` import vtk import numpy as np import open3d as o3d import math from numpy import random from scipy.spatial.distance import directed_hausdorff import vtkmodules.vtkRenderingOpenGL2 from vtkmodules.vtkCommonColor import vtkNamedColors from vtkmodules.vtkCommonCore import vtkIdTypeArray from vtkmodules.vtkCommonDataModel import ( vtkSelection, vtkSelectionNode, vtkUnstructuredGrid ) from vtkmodules.vtkFiltersCore import vtkTriangleFilter from vtkmodules.vtkFiltersExtraction import vtkExtractSelection from vtkmodules.vtkFiltersSources import vtkPlaneSource from vtkmodules.vtkInteractionStyle import vtkInteractorStyleTrackballCamera from vtkmodules.vtkRenderingCore import ( vtkActor, vtkCellPicker, vtkDataSetMapper, vtkPolyDataMapper, vtkRenderWindow, vtkRenderWindowInteractor, vtkRenderer ) class VtkPointCloud: def __init__(self, zMin=-10.0, zMax=10.0, maxNumPoints=2e6): # c = vtkNamedColors() self.maxNumPoints = maxNumPoints self.vtkPolyData = vtk.vtkPolyData() self.clearPoints() mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(self.vtkPolyData) mapper.SetColorModeToDefault() mapper.SetScalarRange(zMin, zMax) mapper.SetScalarVisibility(1) self.vtkActor = vtk.vtkActor() # self.vtkActor.GetProperty().SetColor(1,1,1) # self.vtkActor.GetProperty().SetColor(c.GetColor3d('Yellow')) self.vtkActor.SetMapper(mapper) def addPoint(self, point): if self.vtkPoints.GetNumberOfPoints() < self.maxNumPoints: pointId = self.vtkPoints.InsertNextPoint(point[:]) self.vtkDepth.InsertNextValue(point[2]) self.vtkCells.InsertNextCell(1) self.vtkCells.InsertCellPoint(pointId) else: r = random.randint(0, self.maxNumPoints) self.vtkPoints.SetPoint(r, point[:]) self.vtkCells.Modified() self.vtkPoints.Modified() self.vtkDepth.Modified() def clearPoints(self): self.vtkPoints = vtk.vtkPoints() self.vtkCells = vtk.vtkCellArray() self.vtkDepth = vtk.vtkDoubleArray() self.vtkDepth.SetName('DepthArray') self.vtkPolyData.SetPoints(self.vtkPoints) self.vtkPolyData.SetVerts(self.vtkCells) self.vtkPolyData.GetPointData().SetScalars(self.vtkDepth) self.vtkPolyData.GetPointData().SetActiveScalars('DepthArray') # Catch mouse events class MouseInteractorStyle(vtkInteractorStyleTrackballCamera): def __init__(self, data): self.AddObserver('LeftButtonPressEvent', self.left_button_press_event) self.AddObserver('RightButtonPressEvent', self.right_button_press_event) self.data = data self.selected_mapper = vtkDataSetMapper() self.selected_actor = vtkActor() self.selected_mapper2 = vtkDataSetMapper() self.selected_actor2 = vtkActor() self.vtk_list = vtk.vtkIdList() self.locator = vtk.vtkPointLocator() self.locator.SetDataSet(self.data) self.locator.BuildLocator() self.colors = vtkNamedColors() def left_button_press_event(self, obj, event): pos = self.GetInteractor().GetEventPosition() picker = vtkCellPicker() picker.SetTolerance(0.001) # Pick from this location. picker.Pick(pos[0], pos[1], 0, self.GetDefaultRenderer()) world_position = picker.GetPickPosition() print(f'Cell id is: {picker.GetCellId()}') # print(world_position) self.locator.FindPointsWithinRadius(0.02,world_position, self.vtk_list) print(self.vtk_list) if picker.GetCellId() != -1: print(f'Pick position is: ({world_position[0]:.6g}, {world_position[1]:.6g}, {world_position[2]:.6g})') ids = vtkIdTypeArray() ids.SetNumberOfComponents(1) ids.InsertNextValue(picker.GetCellId()) # print(ids,'\n') selection_node = vtkSelectionNode() selection_node.SetFieldType(vtkSelectionNode.CELL) selection_node.SetContentType(vtkSelectionNode.INDICES) selection_node.SetSelectionList(ids) selection = vtkSelection() selection.AddNode(selection_node) extract_selection = vtkExtractSelection() extract_selection.SetInputData(0, self.data) extract_selection.SetInputData(1, selection) extract_selection.Update() # In selection selected = vtkUnstructuredGrid() selected.ShallowCopy(extract_selection.GetOutput()) print(f'Number of points in the selection: {selected.GetNumberOfPoints()}') # print(f'Number of cells in the selection : {selected.GetNumberOfCells()}\n') print('########################\n') self.selected_mapper.SetInputData(selected) self.selected_actor.SetMapper(self.selected_mapper) # self.selected_actor.GetProperty().EdgeVisibilityOn() self.selected_actor.GetProperty().SetColor(self.colors.GetColor3d('Black')) self.selected_actor.GetProperty().SetPointSize(10) self.selected_actor.GetProperty().SetLineWidth(3) # print(self.selected_actor) self.GetInteractor().GetRenderWindow().GetRenderers().GetFirstRenderer().AddActor(self.selected_actor) # Forward events self.OnLeftButtonDown() def right_button_press_event(self, obj, event): if self.vtk_list.GetNumberOfIds() == 0: return else: ids2 = vtkIdTypeArray() ids2.SetNumberOfComponents(1) for i in range(self.vtk_list.GetNumberOfIds()): # print(i) ids2.InsertNextValue(i) # print(ids2) selection_node2 = vtkSelectionNode() selection_node2.SetFieldType(vtkSelectionNode.CELL) selection_node2.SetContentType(vtkSelectionNode.INDICES) selection_node2.SetSelectionList(ids2) selection2 = vtkSelection() selection2.AddNode(selection_node2) extract_selection2 = vtkExtractSelection() extract_selection2.SetInputData(0, self.data) extract_selection2.SetInputData(1, selection2) extract_selection2.Update() # # In selection selected2 = vtkUnstructuredGrid() selected2.ShallowCopy(extract_selection2.GetOutput()) print(f'Number of neighboring points: {selected2.GetNumberOfPoints()}') # # print(f'Number of neighboring cells: {selected2.GetNumberOfCells()}\n') print('########################\n') self.selected_mapper2.SetInputData(selected2) self.selected_actor2.SetMapper(self.selected_mapper2) # self.selected_actor.GetProperty().EdgeVisibilityOn() self.selected_actor2.GetProperty().SetColor(self.colors.GetColor3d("tan")) self.selected_actor2.GetProperty().SetPointSize(10) self.selected_actor2.GetProperty().SetLineWidth(3) # print(self.selected_actor2) self.GetInteractor().GetRenderWindow().GetRenderers().GetFirstRenderer().AddActor(self.selected_actor2) print('Randomly Selecting 1000 points in the data........') point_indices = [] cluster_points = np.zeros((self.vtk_list.GetNumberOfIds(),3)) # print(cluster_points) print('Calculating the clusters around the centers ......') for i in range(self.vtk_list.GetNumberOfIds()): point_indices.append(self.vtk_list.GetId(i)) cluster_points[i]=pointCloud.vtkPolyData.GetPoint(self.vtk_list.GetId(i)) point_indices = np.asarray(point_indices) new_points= np.delete(points,point_indices, axis=0) random_array = np.random.randint(0,new_points.shape[0],(1000)) min_haus = 1000000000.0 for i in range(random_array.shape[0]): new_list=vtk.vtkIdList() new_center = new_points[random_array[i]] # print('new center to find cluster:',new_center) self.locator.FindPointsWithinRadius(0.02,new_center, new_list) new_cluster_points = np.zeros((new_list.GetNumberOfIds(),3)) for x in range(new_list.GetNumberOfIds()): new_cluster_points[x]=pointCloud.vtkPolyData.GetPoint(new_list.GetId(x)) haus = directed_hausdorff(cluster_points,new_cluster_points)[0] if haus<min_haus: min_haus = haus idx = random_array[i] min_center = new_points[random_array[i]] # print('haus:',haus) print('min haus:',min_haus) print('idx of min haus:',idx) print('center of the min haus cluster:',min_center) min_list = vtk.vtkIdList() self.locator.FindPointsWithinRadius(0.02,min_center, min_list) print('Min list for min center', min_list) # # Forward events self.OnRightButtonDown() # Initialize point clouds pointCloud = VtkPointCloud() pointCloud2 = VtkPointCloud() # print(type(pointCloud)) # Loading Point cloud using open3d pt_cloud = o3d.io.read_point_cloud('fused_cloud_normal.ply') points = np.asarray(pt_cloud.points) pt_cloud2 = o3d.io.read_point_cloud('all_projected_pts.ply') points2 = np.asarray(pt_cloud2.points) # Adding the points into polydata for row in points: pointCloud.addPoint(row) for row in points2: pointCloud2.addPoint(row) # Intialize actor c = vtkNamedColors() actor = pointCloud.vtkActor actor.GetProperty().SetPointSize(10) actor.GetProperty().SetColor(c.GetColor3d('Yellow')) # actor.GetProperty().SetColor(0,0,0) # Renderer renderer = vtk.vtkRenderer() renderer.AddActor(actor) # renderer.AddActor(pointCloud2.vtkActor) renderer.SetBackground(.1, .1, .4) renderer.ResetCamera() # Render Window renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) style = MouseInteractorStyle(pointCloud.vtkPolyData) style.SetDefaultRenderer(renderer) # Interactor renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) renderWindowInteractor.SetInteractorStyle(style) # Begin Interaction renderWindow.Render() renderWindowInteractor.Start() `
Python3 Print on Same Line - Numbers in 7-Segment-Device Format
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))
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 convert a grayscale image into a list of pixel values?
I am trying to create a python program which takes a grayscale, 24*24 pixel image file (I haven't decided on the type, so suggestions are welcome) and converts it to a list of pixel values from 0 (white) to 255 (black). I plan on using this array for creating a MNIST-like bytefile of the picture, that can be recognized by Tensor-Flow handwriting recognition algorithms. I have found the Pillow library to be the most useful in this task, by iterating over each pixel and appending its value to an array from PIL import Image img = Image.open('eggs.png').convert('1') rawData = img.load() data = [] for y in range(24): for x in range(24): data.append(rawData[x,y]) Yet this solution has two problems: The pixel values are not stored as integers, but pixel objects which cannot be further mathematically manipulated and are therefore useless. Even the Pillow docs state that: Accessing individual pixels is fairly slow. If you are looping over all of the pixels in an image, there is likely a faster way using other parts of the Pillow API.
You can convert the image data into a Python list (or list-of-lists) like this: from PIL import Image img = Image.open('eggs.png').convert('L') # convert image to 8-bit grayscale WIDTH, HEIGHT = img.size data = list(img.getdata()) # convert image data to a list of integers # convert that to 2D list (list of lists of integers) data = [data[offset:offset+WIDTH] for offset in range(0, WIDTH*HEIGHT, WIDTH)] # At this point the image's pixels are all in memory and can be accessed # individually using data[row][col]. # For example: for row in data: print(' '.join('{:3}'.format(value) for value in row)) # Here's another more compact representation. chars = '#%#*+=-:. ' # Change as desired. scale = (len(chars)-1)/255. print() for row in data: print(' '.join(chars[int(value*scale)] for value in row)) Here's an enlarged version of a small 24x24 RGB eggs.png image I used for testing: Here's the output from the first example of access: And here the output from the second example: # # % * # # # # % - . * # # # # # # # # # # # # # # . . + # # . = # # # # # # # # # # # # # * . . * # # # # # # # # # # # # # # . . . . + % % # # # # # = # # # # # % . : - - - : % # % : # # # # # # . = = - - - = - . . = = % # # # # = - = : - - : - = . . . : . % # # # % . = - - - - : - = . . - = = = - # # # = . - = - : : = + - : . - = - : - = : * % - . . - = + = - . . - = : - - - = . - = . : : . - - . : = - - - - - = . . % % : : . . : - - . : = - - - : = : # # # # : . . = = - - = . = + - - = - . . # # # # # . - = : - : = - . - = = : . . # # # # % : = - - - : = - : - . . . - # # # * : = : - - - = . . - . . . + # # # . = - : - = : : : . - % # # # * . . . : = = - : . . - . - # # # # # * . . . : . . . - = . = # # # # # # # : - - . . . . # # # # # # # # # # # = # # # * . . . - # # # # # # # # # # # # # # # # . . . # # # # # # # # # # # # # # # # # # # - . % # # # # # # # # # # # # # # # # # # # # . : % # # # # # # # # # # # # # Access to the pixel data should now be faster than using the object img.load() returns (and the values will be integers in the range of 0..255).
You can access the greyscale value of each individual pixel by accessing the r, g, or b value, which will all be the same for a greyscale image. I.e. img = Image.open('eggs.png').convert('1') rawData = img.load() data = [] for y in range(24): for x in range(24): data.append(rawData[x,y][0]) This doesn't solve the problem of access speed. I'm more familiar with scikit-image than Pillow. It seems to me that if all you are after is listing the greyscale values, you could use scikit-image, which stores images as numpy arrays, and use img_as_ubyte to represent the image as a uint array, containing values between 0 and 255. Images are NumPy Arrays provides a good starting point to see what the code looks like.