How to create a result output on a user defined section

Post Reply
aziz_barzuk
Posts: 22
Joined: Thu Mar 07, 2024 3:37 pm

How to create a result output on a user defined section

Post by aziz_barzuk » Sat Jan 25, 2025 5:18 pm

Hello,
Is there a way to extract the results from the selected points automatically?
i.e. if I would get the displacements in time of selected points.
Could you give me some idea what should be the correct python commands to use ?
Could you tell me where I can find the information about the python post-processing API code ?

Thanks in advance

STKO Team
Posts: 3066
Joined: Tue Oct 29, 2019 8:45 am

Re: How to create a result output on a user defined section

Post by STKO Team » Mon Feb 03, 2025 9:18 am

Could you tell me where I can find the information about the python post-processing API code ?
https://asdeasoft.github.io/STKO-Python ... index.html

Is there a way to extract the results from the selected points automatically?
You can check the example test_virtual_result_query_node.py from #020 Intro to STKO v2.0's Python API.
We show how to extract data from a node, but the node_id is hard-coded.

You can combine the above-mentioned code with this code-snippet to get all selected nodes from all selected plots of the active plot group:

Code: Select all

doc = App.postDocument()
nodes = set([node_id for plot_id, selection in doc.scene.plotSelection.items() for node_id in selection.info.nodes])
print(nodes)

aziz_barzuk
Posts: 22
Joined: Thu Mar 07, 2024 3:37 pm

Re: How to create a result output on a user defined section

Post by aziz_barzuk » Thu Mar 27, 2025 3:06 pm

I followed your indication.
Just to keep it simple, I need:
1) to extract the gauss point stress and strain results for a quadUP element for both an Elastic and PIMY plastic material and write them in a txt file, so I will define 2 different output in the PyMPC code because the stress output is different for the 2 ndMaterials. It has to be noted that: a) the analysis is a transient analysis and b) the mpco file regarding the el. pl. region can't be readed by the hdf5 viewer.

2)to extract the output of all the gauss point like the common recorder stress (or strain) opensees output considering that the analysis was performed in parallel (but this is only a particular becuase the stko mpco reader is able to join all the results automatically).

3)how can I install the tkinter package in stko ?(getStressStrain_hdf5_python.py)
from tkinter import filediaolog

I tried this code, but there is something strange because the index are printed in a random way and than the code crashs.

this is the code that starts from the one available in the advanced training:

from PyMpc import *
from PyMpc import MpcOdbVirtualResult as vr
from time import sleep
import traceback
import numpy as np
from time import sleep
import traceback
import numpy as np
from PySide2.QtCore import (
QObject,
Signal,
Slot,
QCoreApplication,
QTimer,
QThread,
QEventLoop,
)
from PySide2.QtWidgets import (
QWidget,
QDialog,
QSizePolicy,
QVBoxLayout,
)

################################################################################
# matplotlib stuff
################################################################################
import matplotlib
# Make sure that we are using QT5
matplotlib.use('Qt5Agg')
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure

# A simple matplotlib-based widget
class MyMplCanvas(FigureCanvas):
# signals
requestUpdateFigure = Signal()
updateFigureDone = Signal()
def __init__(self, parent=None, width=5, height=4, dpi=100,
title=None, labelx=None, labely=None):
self.figure = Figure(figsize=(width, height), dpi=dpi)
FigureCanvas.__init__(self, self.figure)
self.control = parent
self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.axes = self.figure.add_subplot(111)
self.axes.grid(True, ls=':', color=(0.6,0.6,0.6))
if title: self.axes.set_title(title)
if labelx: self.axes.set_xlabel(labelx)
if labely: self.axes.set_ylabel(labely)
self.setParent(parent)
FigureCanvas.updateGeometry(self)
self.x = []
self.y = []
self.linestyle = []
self.lines = []
# set up connections
self.requestUpdateFigure.connect(self.onUpdateFigureRequested)
def add(self, x, y, ls):
self.x.append(x)
self.y.append(y)
self.linestyle.append(ls)
self.lines.append(self.axes.plot(x, y, ls)[0])
@Slot()
def onUpdateFigureRequested(self):
try:
for i in range(len(self.x)):
self.lines.set_data(self.x, self.y)
self.axes.relim()
self.axes.autoscale_view()
self.draw()
except Exception as ex:
IO.write_cerr("Exception in onUpdateFigureRequested:\n{}\n".format(ex))
finally:
self.updateFigureDone.emit()
def updateFigure(self):
loop = QEventLoop()
self.updateFigureDone.connect(loop.quit)
self.requestUpdateFigure.emit()
loop.exec_()

# a dialog for the matplotlib widget
class MyMplDialog(QDialog):
def __init__(self, canvas, parent=None):
QDialog.__init__(self, parent)
self.canvas = canvas
layout = QVBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
layout.addWidget(self.canvas)
self.setLayout(layout)

################################################################################

# clear terminal
App.clearTerminal()

# get document
doc = App.postDocument()

# get first database
if len(doc.databases) == 0:
raise Exception("You need a database with ID = 1 for this test")
db = doc.getDatabase(1)

# create evaluation options
# here we want to extract data for all steps of the last stage
all_stages = db.getStageIDs()
last_stage = all_stages[-1]
all_steps = db.getStepIDs(last_stage)
opt = MpcOdbVirtualResultEvaluationOptions()
opt.stage = last_stage

# begin figure
#canvas = MyMplCanvas(parent=None, width=8, height=6,
# title='Force/Deformation', labelx='Ky', labely='My')
#dialog = MyMplDialog(canvas)

# begin figure data
x = []
y = []
xpos = []
ypos = []
xneg = []
yneg = []
#canvas.add(x, y, ':k')
#canvas.add(xpos, ypos, '-r')
#canvas.add(xneg, yneg, '-b')


def envelope(mult, xpos, ypos):
tol = 1.0e-8
nsamples = 200
if len(x) < 2:
return
if len(xpos) != nsamples:
xpos.extend([0.0 for i in range(nsamples)])
ypos.extend([0.0 for i in range(nsamples)])
edges = [(i,i+1) for i in range(len(x)-1)]
for i in range(len(edges)):
n1,n2 = edges
if x[n1] > x[n2]:
edges = (n2,n1)
xmax = -1.0e100
xmin = -xmax
for ix in x:
if ix > xmax:
xmax = ix
if ix < xmin:
xmin = ix
dx = (xmax-xmin)/float(nsamples-1)
for i in range(nsamples):
ix = xmin+dx*float(i)
iy = None
for n1,n2 in edges:
x1 = x[n1]
if ix < x1-tol: continue
x2 = x[n2]
if ix > x2+tol: continue
y1 = y[n1]
y2 = y[n2]
span = x2-x1
if span == 0.0:
iy_trial = max(y1,y2)*mult
else:
iy_trial = mult*((y2-y1)*(ix-x1)/span + y1)
if iy is None:
iy = iy_trial
else:
if iy_trial > iy-tol:
iy = iy_trial
xpos = ix
ypos = iy/mult


# The worker class. It will run the lengthy function on a working thread
# and emit signals for calling the connected slots on the main thread
class Worker(QObject):
# signals
finished = Signal()
# lengthy function
@Slot()
def run(self):
try:
x = []
y = []
x_values = open('x_valu.txt', 'w')
x_values.close
# gauss result
result_x = db.getElementalResult("material.strain", match = MpcOdb.Contains)
result_y = db.getElementalResult("material.stress", match = MpcOdb.Contains)
#print(result_x)
row = MpcOdbResultField.gauss(18423, 0) # the gauss field object is the row identifier
#in the result field
col = 1
#print(col)
# for envelope
xmin = 0
xmax = 0
ymin = 0
ymax = 0
# for updating every n steps
num_steps = len(all_steps)
print(f'nume_steps: {num_steps}')
#max_updates = min(num_steps, 100)
max_updates = 10000
update_freq = int(num_steps/max_updates)
update_counter = 0
# evaluate for each step
for i in range(num_steps):
x_values = open('x_valu.txt', 'a')
print(f'step: {i}')
opt.step = all_steps
field_x = result_x.evaluate(opt)
field_y = result_y.evaluate(opt)
ix = field_x[row, col]
iy = field_y[row, col]
# full
x.append(ix)
y.append(iy)
x_values.write(f'{x}\n')
x_values.close()

except Exception as ex:
# Store the exception outside in the global variable
global the_exception
the_exception = ex
finally:
# Done
self.finished.emit()

# create the thread, the worker, and move the worker to the thread
thread = QThread()
worker = Worker()
worker.moveToThread(thread)

# set up worker and thread connections
worker.finished.connect(thread.quit)
worker.finished.connect(worker.deleteLater)
thread.started.connect(worker.run)
thread.finished.connect(thread.deleteLater)

# start the thread
thread.start()

# run dialog
#dialog.exec_()

print("DONE")


thanks in advance

STKO Team
Posts: 3066
Joined: Tue Oct 29, 2019 8:45 am

Re: How to create a result output on a user defined section

Post by STKO Team » Fri Apr 11, 2025 8:08 am

3)how can I install the tkinter package in stko ?(getStressStrain_hdf5_python.py)
from tkinter import filediaolog
don't do it, STKO is already using a GUI library that is Qt, so if you want to create widgets, use PySide2
I tried this code, but there is something strange because the index are printed in a random way and than the code crashs.
Please post the code using the "code" command (5th button in the forum's post editor). The code you posted lost all indentations

Post Reply