Maze Pattern Building in Python - 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.

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,
# ...
#
# .....
#
# }

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()

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))

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.

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