Is there an equivalent to ESLL in ANSYS ACT? - python-2.7

I'm looking for an ACT command that selects all elements that are connected to a line. In MAPDL this command was called ESLL.
Currently my script, which saves the elements in a named selection, looks kind of clunky:
geo_body = geo_data.GeoEntityById (line_body) # Get geoEdgeWrapper id
tree_body = tree_geometrie.GetBody (geo_body) # get connected body in tree
sel.Ids = [geo_body.Id] # construct selection from id
## Results
namedSel = ExtAPI.DataModel.Project.Model.NamedSelections.AddNamedSelection ()
namedSel.Name = tree_body.Name + '_elements'
namedSel.ScopingMethod = GeometryDefineByType.Worksheet
namedSel.GenerationCriteria.Add (None)
namedSel.GenerationCriteria [0] .EntityType = SelectionType.GeoBody
namedSel.GenerationCriteria [0] .Criterion = SelectionCriterionType.Name
namedSel.GenerationCriteria [0] .Operator = SelectionOperatorType.Equal
namedSel.GenerationCriteria [0] .Value = tree_body.Name
namedSel.GenerationCriteria.Add (None)
namedSel.GenerationCriteria [1] .Action = SelectionActionType.Convert
namedSel.GenerationCriteria [1] .EntityType = SelectionType.MeshElement
namedSel.Generate ()

You can actually retrieve mesh data directly from geometric entities (using the Id). From your script, considering that you know the Id of your line body as 'line_body' var, you can do:
# Get access to mesh data:
meshGroup = ExtAPI.DataModel.MeshDataByName('Global')
mesh_line = meshGroup.MeshRegionById(line_body)
elem_line = mesh_line.Elements
This will return list of element objects associated to the line body.
Note that you can check name of meshes available in:
meshGroup = ExtAPI.DataModel.MeshDataNames

Related

Dynamically referring to JSON node in Power Query M

I have a function that extracts a node from JSON document as follows:
...
Json = GetJson(Url),
Value = Json[#"values"]
values correspond to the actual node within the JSON document.
I would like to generalize this piece of code and provide the name of the node as a variable like:
let myFunc = (parentNodeName as text) =>
...
Json = GetJson(Url),
Value = Json[parentNodeName]
However getting this error:
An error occurred in the ‘myFunc’ query. Expression.Error: The field 'parentNodeName' of the record wasn't found.
How can I refer to the JSON node dynamically?
Try
(Json, parentNodeName ) =>
let
...
Value = Record.Field(Json,parentNodeName)
in Value
sample code:
let Json = Json.Document(Web.Contents("http://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=json")),
Value=myFunc(Json,"title")
in Value
and myFunc:
(Json, parentNodeName ) =>
let
Value = Record.Field(Json,parentNodeName)
in Value

M & Power Query: How to use the $Skip ODATA expression within a loop?

Good afternoon all,
I'm trying to call all of the results within an API that has:
6640 total records
100 records per page
67 pages of results (total records / records per page)
This is an ever growing list so I've used variables to create the above values.
I can obviously use the $Skip ODATA expression to get any one of the 67 pages by adding the expression to the end of the URL like so (which would skip the first 100, therefore returning the 2nd page:
https://psa.pulseway.com/api/servicedesk/tickets/?$Skip=100
What I'm trying to do though is to create a custom function that will loop through each of the 67 calls, changing the $Skip value by an increment of 100 each time.
I thought I'd accomplished the goal with the below code:
let
Token = "Token",
BaseURL = "https://psa.pulseway.com/api/",
Path = "servicedesk/tickets/",
RecordsPerPage = 100,
CountTickets = Json.Document(Web.Contents(BaseURL,[Headers = [Authorization="Bearer " & Token],RelativePath = Path & "count"])),
TotalRecords = CountTickets[TotalRecords],
GetJson = (Url) =>
let Options = [Headers=[ #"Authorization" = "Bearer " & Token ]],
RawData = Web.Contents(Url, Options),
Json = Json.Document(RawData)
in Json,
GetPage = (Index) =>
let Skip = "$Skip=" & Text.From(Index * RecordsPerPage),
URL = BaseURL & Path & "?" & Skip,
Json = GetJson(URL)
in Json,
TotalPages = Number.RoundUp(TotalRecords / RecordsPerPage),
PageIndicies = {0.. TotalPages - 1},
Pages = List.Transform(PageIndicies, each GetPage(_))
in
Pages
I got all happy when it successfully made the 67 API calls and combined the results into a list for me to load in to a Power Query table, however what I'm actually seeing is the first 100 records repeated 67 times.
That tells me that my GetPage custom function which handles the $Skip value isn't changing and is stuck on the first one. To make sure the Skip index was generating them properly I duplicated the query and changed the code to load in the $Skip values and see what they are, expecting them all to be $Skip=0, what I see though is the correct $Skip values as below:
Image showing correct Skip values
It seems everything is working as it should be, only I'm only getting the first page 67 times.
I've made a couple of posts on other community site around this issue before but I realise the problem I was (poorly) describing was far too broad to get any meaningful assistance. I think now I've gotten to the point where I understand what my own code is doing and have really zoomed in to the problem - I just don't know how to fix it when I'm at the final hurdle...
Any help/advice would be massively appreciated. Thank you.
Edit: Updated following #RicardoDiaz answer.
let
// Define base parameters
Filter = "",
Path = "servicedesk/tickets/",
URL = "https://psa.pulseway.com/api/",
Token = "Token",
Limit = "100",
// Build the table based on record start and any filters
GetEntityRaw = (Filter as any, RecordStart as text, Path as text) =>
let
Options = [Headers=[ #"Authorization" = "Bearer " & Token ]],
URLbase = URL & Path & "?bearer=" & Token & "&start=" & RecordStart & "&limit=" & Text.From(Limit),
URLentity = if Filter <> null then URLbase & Filter else URLbase,
Source = Json.Document(Web.Contents(URLentity, Options)),
Result = Source[Result],
toTable = Table.FromList(Result, Splitter.SplitByNothing(), null, null, ExtraValues.Error)
in
toTable,
// Recursively call the build table function
GetEntity = (optional RecordStart as text) as table =>
let
result = GetEntityRaw(Filter, RecordStart, Path),
nextStart = Text.From(Number.From(RecordStart) + Limit),
nextTable = Table.Combine({result, #GetEntity(nextStart)}),
check = try nextTable otherwise result
in
check,
resultTable = GetEntity("0")
in
resultTable
As I couldn't test your code, it's kind of hard to provide you a concrete answer.
Said that, please review the generic code I use to connect to an api and see if you can find where yours is not working
EDIT: Changed api_record_limit type to number (removed the quotation marks)
let
// Define base parameters
api_url_filter = "",
api_entity = "servicedesk/tickets/",
api_url = "https://psa.pulseway.com/api/",
api_token = "Token",
api_record_limit = 500,
// Build the table based on record start and any filters
fx_api_get_entity_raw = (api_url_filter as any, api_record_start as text, api_entity as text) =>
let
api_url_base = api_url & api_entity & "?api_token=" & api_token & "&start=" & api_record_start & "&limit=" & Text.From(api_record_limit),
api_url_entity = if api_url_filter <> null then api_url_base & api_url_filter else api_url_base,
Source = Json.Document(Web.Contents(api_url_entity)),
data = Source[data],
toTable = Table.FromList(data, Splitter.SplitByNothing(), null, null, ExtraValues.Error)
in
toTable,
// Recursively call the build table function
fxGetEntity = (optional api_record_start as text) as table =>
let
result = fx_api_get_entity_raw(api_url_filter, api_record_start, api_entity),
nextStart = Text.From(Number.From(api_record_start) + api_record_limit),
nextTable = Table.Combine({result, #fxGetEntity(nextStart)}),
check = try nextTable otherwise result
in
check,
resultTable = fxGetEntity("0"),
expandColumn = Table.ExpandRecordColumn(
resultTable,
"Column1",
Record.FieldNames(resultTable{0}[Column1]),
List.Transform(Record.FieldNames(resultTable{0}[Column1]), each _)
)
in
expandColumn
QUESTION TO OP:
Regarding this line:
Result = Source[Result],
Does the json return a field called result instead of data?

Python 3.5 loop to generate a new list each iteration

I'm trying to write some code that (pseudo-randomly) generates a list of 7 numbers. I have it working for a single run. I'd like to be able to loop this code to generate multiple lists, which I can output to a txt file (I don't need help with this I'm quite comfortable working with i/o and files :)
I'm now using this code (thanks Jason for getting it this far):
import random
pool = []
original_pool = list( range( 1,60))
def selectAndPrune(x):
pool = []
list1 = []
random.shuffle(pool)
pool = original_pool.copy()
current_choice = random.choice(pool)
list1.append(current_choice)
pool.remove(current_choice)
random.shuffle(pool)
print(list1)
def repeater():
for i in range(19):
pool_list = []
pool = original_pool.copy()
a = [ selectAndPrune(pool) for x in range(7)]
pool_list.append(a)
repeater()
This is giving output of single value lists like:
[21]
[1]
[54]
[48]
[4]
[32]
[15]
etc.
The output I want is 19 lists, all containing 7 random ints:
[1,4,17,23,45,51,3]
[10,2,9,38,4,1,24]
[15,42,35,54,43,28,14]
etc
If I am understanding the question correctly, the objective is to repeat a function 19 times. However, this function slowly removes items from the list at each call, making it impossible to run past the size of the pool as currently written in the question. I suspect that the solution is something like this:
import random
def spinAndPrune():
random.shuffle( pool )
current_choice = random.choice( pool )
pool.remove( current_choice )
random.shuffle( pool )
return current_choice
First, I added a return command at the end of the function call. Next, you can make copy of the original pool, so that it is possible to re-run it as many times as desired. Also, you need to store the lists you want to keep:
# create an original pool of values
original_pool = list( range( 1, 60 ) )
# initialize a variable that stores previous runs
pool_list = []
# repeat 19 times
for i in range( 19 ):
# create a copy of the original pool to a temporary pool
pool = original_pool.copy()
# run seven times, storing the current choice in variable a
a = [ spinAndPrune() for x in range( 7 ) ]
# keep track of variable a in the pool_list
pool_list.append( a )
print( a )
Note the .copy() function to make a copy of the list. As an aside, the range() makes it easy to create lists containing integers 1-59.
If you need to extract a specific list, you can do something along the lines of this:
# print first list
print( pool_list[ 0 ] )
# print fifth list
print( pool_list[ 4 ] )
# print all the lists
print( pool_list )
In my other answer, I approached it by modifying the code in the original question. However, if the point is just to extract X number of values without repeat in a collection/list, it is probably easiest to just use the random.sample() function. The code can be something along the lines of this:
import random
pool = list( range( 1, 60 ) )
pool_list = []
# sample 19 times and store to the pool_list
for i in range( 19 ):
sample = random.sample( pool, 7 )
pool_list.append( sample )
print( sample )

Coldfusion dynamic column names to pass into a function

A user can supply answers for up to 5 question, and each question has 3 columns in the database:
st_m1_id
st_m1_fam
st_m1_cip
st_m2_id
st_m2_fam
st_m2_cip
etc
When the form is submitted I get the IDs into an array and then loop over that and then query a different table to look up fam and cip.
aidms = listToArray(form['idms[]']);
for( i=1;i<=arrayLen(aidms);i++ ) {
qryData = invoke(dataCFC,'queryData', { smid = aidms[i]});
temp = invoke(userCFC,'updateUser',{
userid = session.userid,
st_m#i#_id = aidms[i],
st_m#i#_fam = qryData.fam,
etc......
});
};
How do I notate the dynamic query column names in the function so that when they are passed to updateUser the correct columns are referenced?

How to restore variables using CheckpointReader in Tensorflow

I'm trying to restore some variables from checkpoint file if same variable name is in current model.
And I found that there is some way as in Tensorfow Github
So what I want to do is checking variable names in checkpoint file using has_tensor("variable.name") as below,
...
reader = tf.train.NewCheckpointReader(ckpt_path)
for v in tf.trainable_variables():
print v.name
if reader.has_tensor(v.name):
print 'has tensor'
...
But I found that v.name returns both variable name and colon+number. For example, I have variable name W_o and b_o then v.name returns W_o:0, b_o:0.
However reader.has_tensor() requires name without colon and number as W_o, b_o.
My question is: how to remove the colon and number at the end of the variable name in order to read the variables?
Is there a better way to restore such variables?
You could use string.split() to get the tensor name:
...
reader = tf.train.NewCheckpointReader(ckpt_path)
for v in tf.trainable_variables():
tensor_name = v.name.split(':')[0]
print tensor_name
if reader.has_tensor(tensor_name):
print 'has tensor'
...
Next, let me use an example to show how I would restore every possible variable from a .cpkt file. First, let's save v2 and v3 in tmp.ckpt:
import tensorflow as tf
v1 = tf.Variable(tf.ones([1]), name='v1')
v2 = tf.Variable(2 * tf.ones([1]), name='v2')
v3 = tf.Variable(3 * tf.ones([1]), name='v3')
saver = tf.train.Saver({'v2': v2, 'v3': v3})
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
saver.save(sess, 'tmp.ckpt')
That's how I would restore every variable (belonging to a new graph) showing up in tmp.ckpt:
with tf.Graph().as_default():
assert len(tf.trainable_variables()) == 0
v1 = tf.Variable(tf.zeros([1]), name='v1')
v2 = tf.Variable(tf.zeros([1]), name='v2')
reader = tf.train.NewCheckpointReader('tmp.ckpt')
restore_dict = dict()
for v in tf.trainable_variables():
tensor_name = v.name.split(':')[0]
if reader.has_tensor(tensor_name):
print('has tensor ', tensor_name)
restore_dict[tensor_name] = v
saver = tf.train.Saver(restore_dict)
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
saver.restore(sess, 'tmp.ckpt')
print(sess.run([v1, v2])) # prints [array([ 0.], dtype=float32), array([ 2.], dtype=float32)]
Also, you may want to ensure that shapes and dtypes match.
tf.train.NewCheckpointReader is a nifty method that creates a CheckpointReader object. CheckpointReader has several very useful methods. The method that would be the most relevant to your question would be get_variable_to_shape_map().
get_variable_to_shape_map() provides a dictionary with variable names and shapes:
saved_shapes = reader.get_variable_to_shape_map()
print 'fire9/squeeze1x1/kernels:', saved_shapes['fire9/squeeze1x1/kernels']
Please take a look at this quick tutorial below:
Loading Variables from Existing Checkpoints
Simple answer:
reader = tf.train.NewCheckpointReader(checkpoint_file)
variable1 = reader.get_tensor('layer_name1/layer_type_name')
variable2 = reader.get_tensor('layer_name2/layer_type_name')
Now, after modification to these variables, you can assign it back.
layer_name1_var.set_weights([variable1, variable2])