How to extract sketches from shell part in ABAQUS - python

I have a 2D shell part containing a number of shell faces. I would like to extract one different sketch for each of the faces in the part. So far I know how to create a single sketch containing all the shell faces information but this is not what I want. I would like to know how to create one sketch per shell face. This is what I have done (not right).
stest= model.ConstrainedSketch(name='__polyTest__',sheetSize=2000.0)
mdb.models['Model-1'].parts['Result'].projectReferencesOntoSketch(filter=
COPLANAR_EDGES, sketch=mdb.models['Model-1'].sketches['__polyTest__'])
Many thanks for your help.

Open your part in the current viewport and try this:
from part import *
from sketch import *
p=session.viewports[session.currentViewportName].displayedObject
currentModel=mdb.models[p.modelName]
for faceNum,face in enumerate(p.faces):
try: # Will only work on valid sketch planes. Must be a flat face
t = p.MakeSketchTransform(sketchPlane=face, sketchUpEdge=p.edges[0],
sketchPlaneSide=SIDE1, origin=(659.077803, 0.256062, -816.16))
s = currentModel.ConstrainedSketch(name='__profile__',
sheetSize=834.36, gridSpacing=20.85, transform=t)
edgeList=[p.edges[edgeNum] for edgeNum in face.getEdges()]
p.projectEdgesOntoSketch(sketch=s, edges=tuple(edgeList))
currentModel.ConstrainedSketch(name='Sketch-face' + str(edgeNum), objectToCopy=s)
except:
pass

Related

Extruding an STL from a binary png image with python

I have been working on this code for a project at work which will (hopefully) take in images from a scanning electron microscope and generate 3D STL files of the structures were imaging. I'm at the stage with the code where I'm trying to generate a 3D structure from a 'coloured in' binary image I've made with some edge detection code I wrote. I came across this post How can i extrude a stl with python that basically does exactly what I need (generating a meshed 3D structure from a binary image). I've tried using/adapting the code in the answer to that post (see below) but I keep running into the following error: polyline2 = mr.distanceMapTo2DIsoPolyline(dm.value(), isoValue=127) RuntimeError: Bad expected access. I cant find anything online about why this is happening and I'm no expert in Python so have no idea myself. If anyone has an idea, I'd really appreciate it!
Code from answer to above post:
import meshlib.mrmeshpy as mr
# load image as Distance Map object:
dm = mr.loadDistanceMapFromImage(mr.Path("your-image.png"), 0)
# find boundary contour of the letter:
polyline2 = mr.distanceMapTo2DIsoPolyline(dm.value(), isoValue=127)
# triangulate the contour
mesh = mr.triangulateContours(polyline2.contours2())
# extrude itself:
mr.addBaseToPlanarMesh(mesh, zOffset=30)
# export the result:
mr.saveMesh(mesh, mr.Path("output-mesh.stl"))
I have tried the following:
Reconfigured the MeshLib package that this command uses. Package docs here: https://meshinspector.github.io/MeshLib/html/index.html#PythonIntegration
Updating VS studio/python/MeshLib
In older version of meshlib python module RuntimeError: Bad expected access indicated that mr.loadDistanceMapFromImage had failed, you should had checked it like this:
import meshlib.mrmeshpy as mr
# load image as Distance Map object:
dm = mr.loadDistanceMapFromImage(mr.Path("your-image.png"), 0)
# check dm
if ( not dm.has_value() ):
raise Exception(dm.error())
# find boundary contour of the letter:
polyline2 = mr.distanceMapTo2DIsoPolyline(dm.value(), isoValue=127)
# triangulate the contour
mesh = mr.triangulateContours(polyline2.contours2())
# extrude itself:
mr.addBaseToPlanarMesh(mesh, zOffset=30)
# export the result:
mr.saveMesh(mesh, mr.Path("output-mesh.stl"))
But in actual release your code will rise exception with real error.
Please make sure that path is correct, if it doesn't help please provide more info like png file and version of python and version of MeshLib and anything else you find related.
P.S. If there is real problem with MeshLib better open issue in github.

pyautocad - automate drawing - import DWG - write text - import image

i'm not a professional coder and i'm so sorry for my english :)
i hope you understand.
I'm trying to automate part of my job.
i have to create dwg; every layer for me is a sheet (like A4 paper), for that reason i have to change layer and import specific dwg/dxf from my repository symbol.
For example i have to:
(start new project)
open newproject.dwg
(paste dwg)
import C:\repository_cad\symbol1.dwg in layer n°3 with coordinate X 100 Y 200.
(write text in the middle of symbol)
write "SYMBOL_1" layer n°3 coordinate X 150 Y200 alignment center.
(insert logo image)
import C:\repository_cad\image1.jpg in coordinate X 10 Y 20
i'm trying to use pyautocad, but i cant find a command for import dxf, and i dont find information about changing layer.
i find out only the command for draw the line, circle ecc, but if i have to re-draw all my repository by python i need to much time, i hope is possible copy draw from another dwg and paste it in my new dwg.
can someone give to me a little help with these 3 command?
maybe is not possible making this stuff on pyautocad? is there other library for python?
i read the docs but i dont see info about some import function.
so, i tried:
from pyautocad import Autocad, APoint
acad = Autocad(create_if_not_exists=False)
acad.prompt("Hello, Autocad from Python\n")
print (acad.doc.Name)
and it's works, on autocad terminal i can see "Hello, Autocad from Python"
in the Docs i find out how write a autocad-command from python.
The function is:
prompt()
i tried:
acad.prompt('-INSERT') #-INSERT is the autocad command for import dxf or dwg
acad.prompt('C:\SPAC\Librerie\Elettr\02-15-04.dwg')#this is the path of the cad
acad.prompt('-15 -15') #coord X Y of the point where i want to paste
acad.prompt('1') # 1 is the scale factor in X
acad.prompt('1') # 1 is the scale factor in Y (autocad askt first in X and after in Y
acad.prompt('0') #degree of rotation
at this point i havent error on python and no error on autocad terminal, but the draw not appear on cad
thanks
Max
acad.prompt() will just echo the string to the command line. What you are looking for is acad.doc.SendCommand(), e.g.
acad.doc.SendCommand('-INSERT ')
Notice there is a blank space after the autocad command, that stands for to activate the command.

Increase graph size in plantUML from python?

MWE
To generate PlantUML diagrams in (sub)folder: /Diagrams/ I use the following python script:
from plantuml import PlantUML
import os
from os.path import abspath
from shutil import copyfile
os.environ['PLANTUML_LIMIT_SIZE'] = str(4096 * 4) # set max with to 4 times the default (16,384)
server = PlantUML(url='http://www.plantuml.com/plantuml/img/',
basic_auth={},
form_auth={}, http_opts={}, request_opts={})
diagram_dir = "./Diagrams"
#directory = os.fsencode()
for file in os.listdir(diagram_dir):
filename = os.fsdecode(file)
if filename.endswith(".txt"):
server.processes_file(abspath(f'./Diagrams/{filename}'))
It is used to generate for example the following test.txt file:
#startuml
'Enforce straight lines
skinparam linetype ortho
' Set direction of graph hierarchy
Left to Right direction
' create work package data
rectangle "something something something" as ffd0
rectangle "something something something" as ffd1
rectangle "something something something something something" as ffd2
rectangle "something something something something" as ffd3
rectangle "something something somethingsomethingsomething" as ffd4
rectangle "something something something something something something" as ffd5
rectangle "something something something something" as ffd6
rectangle "something something something " as ffd7
' Implement graph hierarchy
ffd0-->ffd1
ffd1-->ffd2
ffd2-->ffd3
ffd3-->ffd4
ffd4-->ffd5
ffd5-->ffd6
ffd6-->ffd7
#enduml
Expected behavior
Because I set the PLANTUML_LIMIT_SIZE variable to 16384 (pixels) as the FAQ suggests, I would expect this to fill up the picture of the diagram with all the blocks connected side by side up to a max width of 4096 * 4 pixels.
To test whether perhaps setting it from the python script was implemented incorrectly I also tried to set it manually with: set PLANTUML_LIMIT_SIZE=16384 to expect the same behavior as explained in the above paragraph (a picture filled up till 16384 pixels).
Observed behavior
Instead PlantUML cuts off the picture at 2000 horizontal pictures as shown in the figure below:
Question
How can I ensure the PlantUML does not cut off the blocks of the diagrams of n pixels (height or width), from a python script?
The best way I've found to prevent diagrams from being cut off, without trying to guess at the size or picking some arbitrarily large limit, is to select SVG output.
Note that setting PLANTUML_LIMIT_SIZE is only going to have an effect if you're running PlantUML locally, but it appears the Python interface you're using sends the diagram to the online service. I don't know the internals of that interface, but per the documentation you should be able to get SVG output by using http://www.plantuml.com/plantuml/svg/ as the service URL.
If you need the final image in PNG format, you will need to convert it with another tool.
Approach 1:
To prevent the diagram from being cut off I followed the following steps:
Downloaded the plantuml.jar from this location http://sourceforge.net/projects/plantuml/files/plantuml.jar/download
Put the diagram which I wrote in a someLargeDiagram.txt file, in the same directory as the plantuml.jar file.
Opened terminal on Ubuntu 20.04 in that same directory and ran:
java -jar plantuml.jar -verbose someLargeDiagram.txt
That successfully generated the diagram as .png file, which was not cut off.
Approach 2:
After creating even larger graphs, they got cut-off again, and it gave the message to increase the PLANTUML_LIMIT_SIZE. I tried passing the size as an argument in the commandline using: java -jar plantuml.jar -verbose -PLANTUML_LIMIT_SIZE=8192 Diagrams/latest.uml however that did not work, nor did ..-PLANTUML_LIMIT_SIZE 8192... This link suggested one could set it as an environment variable, so I did that in Ubuntu 20.04 using command: export PLANTUML_LIMIT_SIZE 8192, after which I successfully created a larger diagram that was not cut-off with command:
java -jar plantuml.jar -verbose Diagrams/latest.uml

Can't make MatPlotLib display mid-function

I am writing a programme to input data into a JSON database. Part of this is:
displaying an image (file name entered by user)
asking for coordinates of interest (entered by user)
re-displaying cropped image using those coordinates
asking for tags for this cropped segment (entered by user)
saving tags & coordinates in the JSON database
This same process was used for text files but now that I am doing images I am having the problem that when my programme calls the function:
img = mpimg.imread("raw_data" + system_slash + "images" + system_slash + database[i]['image_file'])
plot.imshow(img)
it does not display the image immediately, but instead only after the whole programme completes. Could anyone suggest a different call to make it display in line, like a print function for text?
*the system slash is a quick and dirty fix for me and my colleague using both PC and MAC file systems when using the programme, so either / or \
After the plotting command, you should put matplotlib.pyplot.pause(t), where t is the time you want to pause. The interval t is in seconds, so if you want for example an animation with roughly 60fps, you could set t=1/60.
The function updates the figure and displays it for t seconds.
EDIT What also came to my mind is: Don't call plt.imshow repeatedly. This is very slow. Better call it once and then just set the data. Little demo:
import matplotlib.pyplot as plt
import numpy as np
im = plt.imshow(np.random.rand(10,10))
while True:
im.set_data(np.random.rand(10,10))
plt.pause(1/10)

How to view real time mosaicing of large image?

I have built a code which will stitch 100X100 images approx. I want to view this stitiching process in real time. I am using pyvips to create large image. I am saving final image in .DZI format as it will take very less memory footprint to display.
Below code is copied just for testing purpose https://github.com/jcupitt/pyvips/issues/43.
#!/usr/bin/env python
import sys
import pyvips
# overlap joins by this many pixels
H_OVERLAP = 100
V_OVERLAP = 100
# number of images in mosaic
ACROSS = 40
DOWN = 40
if len(sys.argv) < 2 + ACROSS * DOWN:
print 'usage: %s output-image input1 input2 ..'
sys.exit(1)
def join_left_right(filenames):
images = [pyvips.Image.new_from_file(filename) for filename in filenames]
row = images[0]
for image in images[1:]:
row = row.merge(image, 'horizontal', H_OVERLAP - row.width, 0)
return row
def join_top_bottom(rows):
image = rows[0]
for row in rows[1:]:
image = image.merge(row, 'vertical', 0, V_OVERLAP - image.height)
return image
rows = []
for y in range(0, DOWN):
start = 2 + y * ACROSS
end = start + ACROSS
rows.append(join_left_right(sys.argv[start:end]))
image = join_top_bottom(rows)
image.write_to_file(sys.argv[1])
To run this code:
$ export VIPS_DISC_THRESHOLD=100
$ export VIPS_PROGRESS=1
$ export VIPS_CONCURRENCY=1
$ mkdir sample
$ for i in {1..1600}; do cp ~/pics/k2.jpg sample/$i.jpg; done
$ time ./mergeup.py x.dz sample/*.jpg
here cp ~/pics/k2.jpg will copy k2.jpg image 1600 times from pics folder, so change according to your image name and location.
I want to display this process in real time. Right now after creating final mosaiced image I am able to display. Just an idea,I am thinking to make a large image and display it, then insert smaller images. I don't know, how it can be done. I am confused as we also have to make pyramidal structure. So If we create large image first we have to replace each level images with the new images. Creating .DZI image is expensive, so I don't want to create it in every running loop. Replacing images may be a solution. Any suggestion folks??
I suppose you have two challenges: how to keep the pyramid up-to-date on the server, and how to keep it up-to-date on the client. The brute force method would be to constantly rebuild the DZI on the server, and periodically flush the tiles on the client (so they reload). For something like that you'll also need to add a cache bust to the tile URLs each time, or the browser will think it should just use its local copy (not realizing it has updated). Of course this brute force method is probably too slow (though it might be interesting to try!).
For a little more finesse, you'd want to make a pyramid that's exactly aligned with the sub images. That way when you change a single sub image, it's obvious which tiles need to be updated. You can do this with DZI if you have square sub images and you use a tile size that is some even fraction of the sub image size. Also no tile overlap. Of course you'll have to build your own DZI constructor, since the existing ones aren't primed to simply replace individual tiles. If you know which tiles you changed on the server, you can communicate that to the client (either via periodic polling or with something like web sockets) and then flush only those tiles (again with the cache busting).
Another solution you could experiment with would be to not attempt a pyramid, per se, but just a flat set of tiles at a reasonable resolution to allow the user to pan around the scene. This would greatly simplify your pyramid updating on the server, since all you would need to do would be replace a single image for each sub image. This could be loaded and shown in a custom (non-OpenSeadragon) fashion on the client, or you could even use OpenSeadragon's multi-image feature to take advantage of its panning and zooming, like here: http://www.letsfathom.com/ (each album cover is its own independent image object).

Categories

Resources