how to insert keyword in the step load definition section using python script? - abaqus

I am using python to insert *Include, Input=file.inp into step load definition section to apply for pressure boundary condition on nodes. Here is my script, however, it is inserted in Part level section. I am wondering how to control the insert position using python. Thanks
def GetKeywordPosition(myModel, blockPrefix, occurrence=1):
if blockPrefix == '':
return len(myModel.keywordBlock.sieBlocks)+1
pos = 0
foundCount = 0
for block in myModel.keywordBlock.sieBlocks:
if string.lower(block[0:len(blockPrefix)])==\
string.lower(blockPrefix):
foundCount = foundCount + 1
if foundCount >= occurrence:
return pos
pos=pos+1
return +1
position = GetKeywordPosition(myModel, '*step')+24
myModel.keywordBlock.synchVersions(storeNodesAndElements=False)
myModel.keywordBlock.insert(position, "\n*INCLUDE, INPUT=file.inp")

You can adapt the re module. This should work
import re
# Get keywordBlock object
kw_block = myModel.keywordBlock
kw_block.synchVersions(storeNodesAndElements=False)
sie_blocks = kw_block.sieBlocks
# Define keywords for the search (don't forget to exclude special symbols with '\')
kw_list = ['\*Step, name="My Step"']
# Find index
idx = 0
for kw in kw_list:
r = re.compile(kw)
full_str = filter(r.match, sie_blocks[idx:])[0]
idx += sie_blocks[idx:].index(full_str)
UPD: Some explanations as requested
As keywords in the .inp file could be somewhat repetitive, the main idea here is to create a "search route", where the last pattern in the list will correspond to a place where you want to make your modifications (for example, if you want to find the "*End" keyword after a specific "*Instance" keyword).
So we proceed iteratively through our "search route" == list of search patterns:
Compile the regex expression;
Find the first appearance of the pattern in the sie_blocks starting from the index idx;
Update the idx so the next search is performed from this point.
Hope this will help

Related

Lua - How to ignore a result from a table iteration without removing it?

I wanto to create a crossword puzzles's solver with Lua. I'm not used to this language tho and my english is poor, sorry for that.
I have to iterate multiples times the same table of tables checking if the given word is present or not and, if present, replace every char of that word in the table with a "*" simbol.
For example:
schema= {
{"A","B","C","D","H","F","G","W","T","Y"},
{"U","H","E","L","L","O","I","I","O","L"},
{"G","F","D","R","Y","T","R","G","R","R"}}
function(schema,"HELLO")
schema= {
{"A","B","C","D","H","F","G","W","T","Y"},
{"U","*","*","*","*","*","I","I","O","L"},
{"G","F","D","R","Y","T","R","G","R","R"}}
For now i'm focusing on find the word scanning the table from left to right. Here's my code:
i = 1
t = {}
for k,w in pairs(schema) do
t[k] = w
end
cercaPrima = function(tabella,stringa)
for v = 1, 10 do
if string.sub(stringa,1,1) == t[i][v] then
print(t[i][v]) v = v+1
return cercaDS(t,stringa,i,v)
else
v = v+1
end
end
if i < #t then
i = i+1
cercaPrima(tabella,stringa)
else
return print("?")
end
end
cercaDS = function(tabella,stringa,d,s)
local o = 2
local l = 2
while o <= #stringa do
if string.sub(stringa,o,l) == tabella[d][s] then
print(tabella[d][s])
tabella[d][s] = "*"
s=s+1
o=o+1
l=l+1
else
l=l-1
s=s-l
o=#stringa+1
tabella[d][s] = "*"
return cercaPrima(tabella,stringa)
end
end
end
cercaPrima(schema,"HELLO")
It's probably overcomplicated, but my question is: How can I make it ignore the first "H" (not turning it into a "*") while keep iterating the table looking for another "H" who fits the criteria?
My goal is to create a function who takes a table and a list of words in input, iterates the table looking for every single word, if it finds them all it replaces every char of every word found in the table with a "*" and print the remaining characters as a string.
Another problem that i'll probabily have is: what if a char of a word is a char of another word too? It will read "*" instead of the real char if it has already found the first word.
Should I create a new table for every word I'm looking for? But then how can i merge those table togheter to extrapolate the remaining characters?
Thank you for your help!
If you want to ignore something one time you can use a conditional statement. Just remember that you encountered it already using a variable. But I don't see how this makes sense here.
A problem like this is probably solved better by turing each line and column into strings and then stimply search the strings for words.
I find string.gsub() is a great find and replacement tool.
Maybe it hit not all requirements but maybe it inspire you.
> function cercaPrisma(tab,txt) for i=1,#tab do print((table.concat(tab[i]):gsub(txt, ('*'):rep(txt:len())))) end end
> cercaPrisma(schema, 'HELLO')
ABCDHFGWTY
U*****IIOL
GFDRYTRGRR
> cercaPrisma(schema, 'DRY')
ABCDHFGWTY
UHELLOIIOL
GF***TRGRR

I can't figure out how to do an simple algoritm to get the sum of two numbers

I am trying to find a solution to the problem "Two Sum" if you recognize it , and I've run into a problem and I cannot figure it out (Lua)
Code:
num = {2,7,11,15}
target = 9
current = 0
repeat
createNum1 = tonumber(num[math.random(1,#num)])
createNum2 = tonumber(num[math.random(1,#num)])
current = createNum1 + createNum2
until current == target
print(table.find(num,createNum1), table.find(num,createNum2))
Error:
lua5.3: HelloWorld.lua:9: attempt to call a nil value (field 'find')
stack traceback:
HelloWorld.lua:9: in main chunk
[C]: in ?
Thank you!
Lua has no table.find function in its very small standard library; just take a look at the reference manual.
You could implement your own table.find function, but that would just be monkey-patching an overall broken algorithm. There is no need to use a probabilistic algorithm that probably runs in at least quadratic time if there only is one pair of numbers that adds up to the desired number. Instead, you should leverage Lua's tables - associative arrays - here. First build an index of [number] = last index:
local num = {2,7,11,15}
local target = 9
local idx = {}
for i, n in ipairs(num) do idx[n] = i end
then loop over the numbers; given a number m you just need to look for target - m in your idx lookup:
for i, n in ipairs(num) do local j = idx[target - n]; if j then print(i, j) break end end
if you want to exit early - sometimes without building the full idx table - you can fuse the two loops:
local idx = {}
for i, n in ipairs(num) do
local j = idx[target - n]
if j then
print(j, i)
break
end
idx[n] = i
end
other solutions exist (e.g. using sorting, which requires no auxiliary space), but this one is elegant in that it runs in O(n) time & O(n) space to produce a solution and leverages Lua's builtin data structures.

I am looking for a Lua find and replace logic

enter image description here
I just started working on lua scripting since a week. I have a lua file where in the logic needs to be written for a certain condition.
The condition when gets triggered
it does an iteration on one of the fields to change value from
(ABC123-XYZ) to this value
(ABC123#1-XYZ) and it keeps increasing whenever iterations happens (ABC123#2-XYZ)
I need to run a function that removes the # followed by number to change it back to (ABC123-XYZ). Looking for any advice!
Edit 1:
Below is the updated code that is written Thanks to #Piglet
I have another scenario if therr are two hashes in the variable.
local x = 'BUS144611111-PNB_00#80901#1555-122TRNHUBUS'
local b = x:gsub("#%d+","")
function remove_char(a) a=a:gsub("#%d+","")
return a;
end if string.match(x,"#")
then print('function')
print(remove_char(x));
else print(x);
end
Expected output should be
x = 'BUS144611111-PNB_00#80901-122TRNHUBUS' for the aforesaid variable
local a = "ABC123#1-XYZ"
local b = a:gsub("#%d+", "")
this will remove any # followed by or one more digits from your string.

find Variables in a module

I'm new to DXL and I want to extract the variables containing
_I_,_O_ and _IO_
from a module and export then to csv file. Please help me with this
EG:
ADCD_WE_I_DFGJDGFJ_12_QWE and CVFDFH_AWEQ_I_EHH[X] is set to some value
This question has two parts.
You want to find variables that contain those parts in their name
You want to export to a .csv file
Another person may be able to expand on a better way, but the only way coming to mind right now for 1. is this:
Loop over the attributes in the module (for ad in m do {}) and get the string of the attribute names.
I am assuming that your attributes are valued at _I_, _O_ or _OI_? Like alpha = "_I_"? Are these enumerate values?
If they are, then you only need to check the value of each object's attribute. If one of those are the attribute values, then add it to something like a skip list. Having a counter here would be useful, maybe one for each attribute, like countI, countO, countOI, you can then use the counters as keys for the put() function for the skip list.
Once you have found all the attributes then you can move on to writing to csv
Stream out = write("filepathname/filename.csv") // to declare the stream
out << "_I_, _O_, _OI_\n"
Then you could loop over your Skip lists at the same time
int ijk = 0; bool finito = false
while(!finito) do {
if(ijk<countI) {
at = get(skipListI, ijk)
out << at.name ","
}
else out << ","
if(ijk<countO) {
at = get(skipListO, ijk)
out << at.name ","
}
else out << ","
if(ijk<countOI) {
at = get(skipListOI, ijk)
out << at.name "\n"
}
else out << "\n"
ijk++
// check if the next iteration would be outside of bounds on all lists
if(ijk >= countI && ijk >= countO && ijk >= countIO) finito = true
}
Or instead of at.name, you could print out whatever part of the attribute you wanted. The name, the value, "name:value" or whatever.
I have not run this, so you will be left to do any troubleshooting.
--
I hope this idea gets you started, write out what you want on paper first and then follow that plan. The key things I have mentioned that would be useful here are Skip lists, and Stream write (or append, if you want to keep adding).
In the future, please consider making your question more clear. Are you looking for those search terms in the name of the attribute, or in the value of the attribute. Are you looking to print out the names or the values, or the what? What kind of format for the .csv are you going to have? Any information will help your question be answered.

vba to find word or phrase then highlight the entire paragraph that follows it

I've used the following code to find a key word or phrase then highlight the line -- but can't figure out how to make it highlight the entire paragraph and/ or list that follows it...
For example:
(ideally, highlighting this paragraph AND the list that provides further details would be best -but if only the paragraph is achievable, that's better than nothing):
"The Contractor shall turn in monthly status reports within ten business days after the end of each month. The report should include:
(a) Accomplishments
(b) Meetings and Outcomes
(c) Completed Travel and Purpose of Travel"
I've researched several commands and looked for examples but still at a loss as a novice. I tried "wdParagraph" but couldn't get that to work. Located refs of maybe using a "paragraph.range.select" and also found a note that advised these "start" and "end" terms (below) to select a paragraph.. but not sure how to achieve this? Hoping someone has an example of how to accomplish this as it will help greatly with quickly identifying hundreds of software reqs out of a 100 page word doc.. so frustrated!
* Selection.StartOf Unit:=wdParagraphm
* Selection.MoveEnd Unit:=wdParagraph
Sub Find_Highlight_Word_to_End_of_Line()
'BUT NEED IT TO HIGHLIGHT THROUGH END OF PARAGRAPH
'AND HIGHLIGHT LISTED ITEMS IF APPLICABLE
'LIKE THE LISTS IN THE EXAMPLE DOCUMENT
Dim sFindText As String
'Start from the top of the document
Selection.HomeKey wdStory
sFindText = "Contractor Shall"
Selection.Find.Execute sFindText
Do Until Selection.Find.Found = False
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
Selection.Range.HighlightColorIndex = wdYellow
Selection.MoveRight
Selection.Find.Execute
Loop
End Sub
A couple of awesome experts shared 2 methods with me to achieve the full paragraph highlighting I needed.. Hope these help others! Fascinating to see different ways to achieve the same result!
Method 2 Code (Alternative) is shorter:
Sub Highlight_Paragraph()
Dim oRng As Range
Set oRng = ActiveDocument.Range
With oRng.Find
Do While .Execute(FindText:="Contractor Shall")
oRng.Paragraphs(1).Range.HighlightColorIndex = wdYellow
oRng.Collapse 0
Loop
End With
lbl_Exit:
Set oRng = Nothing
Exit Sub
End Sub
Method 1 Code (MatchWildcards=False):
Sub Demo()
Application.ScreenUpdating = False
With ActiveDocument.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "Contractor Shall"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = True
.MatchWildcards = False
.Execute
End With
Do While .Find.Found
.Duplicate.Paragraphs.First.Range.HighlightColorIndex = wdYellow
.Start = .Duplicate.Paragraphs.First.Range.End
.Find.Execute
Loop
End With
Application.ScreenUpdating = True
End Sub

Resources