Python dynamo set parameter

Ошибка в ‘SetParameterByName’

Если мы на входе в питон получаем список труб то через: OUT=[i.SetParameterByName(Параметр, Значение) for i in IN[0]] задаем значения (если не получается , то UnwrapElement(i) добавляем – обычно помогает) У меня код: con_ps=[[x.Owner.SetParameterByName(«kmc_equip_ASDK», kmc_eqp(y.Owner)/2) for y in con_eq_pt for x in i if x.IsConnectedTo(y)==True ] for i in con_set_ps ] код корректно выдает трубы (если убрать SetParameter) , то есть работает норм, но не могу задать значения ….
здесь x.Owner – это труба (выдает Pipe на выходе, т.е. я получаю родительскую трубу коннектора), и при выполнении скрипта, вылетает ошибка: AttributeError: ‘Pipe’ object has no attribute ‘SetParameterByName’ Чувствую что то надо добавить к x.Owner , только что …

Вроде все правильно. Могу только предположить, что возможно, получаем “чистую” трубу без обёртки в Динамо.
SetParameterByName – это метод именно ДизайнСкрипта на “чистой” трубе из ревитАпи не отработает.
Я бы попробовал в нод подавать трубы из Динамо, а не получать через комманды. Не знаю, в питоне понятно что добавлять ToDSType(). А вот в ДизайнСкрипте – хз

думаю вы правы, но возможно как то можно преобразовать трубу…
что т вроде : x.Owner.ToDSType .. (что тоже не работает)
либо как то создать список..
не хотелось бы вытаскивать элементы из скрипта …

Читайте также:  Sign in with google java

А чем питон смущает? Может, попробовать через него? Там просто присваивать значения параметра.
Только я бы все же там пользовался методами АПИ через транзакцию. Скорей всего будет быстрее немножко.

Блин, что-то подумал, что это дизайнСкрипт.
Тогда как по мне, генератор списка написан немножко не в питоновской парадигме – все должно быть читаемо.
Чаще используйте комманду map, а не генерируйте список циклом.
Я бы сделал отдельную функцию, в которой прописал бы что надо делать для одного элемента.
Но это уже особенности стилистики. def MakeSmth (x):
return x
OUT = map(MakeSmth, IN[0]) По возможности, не пользуйтесь в Питоне методами ДизайнСкрипта. Часто это вызывает конфликты пространства имен. Например как сейчас – фиг поймешь, то ли “pipe” это объект ДС или АПИ?

Хорошо, понял.
тогда вместо GetParameter используем в скрипте LookupParameter
а вместо SetParameter что ?

Параметры надо через транзакцию записывать.
В скрипт закидываем “стандартные” импорты и смотрим, чтоб была строка про документ
Ниже пример из реального скрипта, в котором я устанавливаю новый диаметр трубы. doc = DocumentManager.Instance.CurrentDBDocument
TransactionManager.Instance.EnsureInTransaction(doc)
#Можно было бы заменить на Лукап. Но Лукап языкозависимый. Я предпочитаю не делать привязку к языку, если возможно
#diam = pp.LookupParameter(“Диаметр”)
diam = pp.get_Parameter(BuiltInParameter.RBS_PIPE_DIAMETER_PARAM)
diam.Set(IN[1][1])
TransactionManager.Instance.TransactionTaskDone()

Спасибо за подсказку, получилось так:
con_ps=[[ x.Owner.LookupParameter(«kmc_equip_ASDK»).Set(y.Owner.LookupParameter(«kmc_equip_ASDK»).AsDouble()) for y in con_eq_pt for x in i if x.IsConnectedTo(y)==True ] for i in con_set_ps ] через

diam = pp.get_Parameter(BuiltInParameter.RBS_PIPE_DIAMETER_PARAM)
diam.Set(IN[1][1])
не получилось так как get_Parameter требует BuiltInParameter.RBS… значение которого у меня для данного параметра нет

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add nodes to get/set parameters of the active family doc (not loaded type/instance) #494

add nodes to get/set parameters of the active family doc (not loaded type/instance) #494

Comments

we need a way to get and set parameter if you are working in a family document.

note this is different than the getters/setters for family types and instances.
it’s a pretty easy interfaces to deal with.
doc.FamilyManager is the access point if active doc is family. iterate list and match name in same way as other param getters do.

note that after setting you do need to regen the doc i think.

The text was updated successfully, but these errors were encountered:

I wonder if this needs a little safeguards. Your link example with setters like:

doc.FamilyManager.Set(height, doc.FamilyManager.CurrentType.AsDouble(height)+ 10)

is good example of potential trouble: each run of the graph will increment the height by 10!
I think it is interesting challenge to separate sensible setting from its opposite, but I do not see a good way yet except running the graph twice and assure same values of family parameters at the end of the run.

But sometimes incrementing is just what you might want.
Imagine you have a mass family set up in such a way that that you can control most of the parameters of placed family instances (or properties of divided surfaces/path or . ) through the family types tool of that mass. And now you want to go through hundreds of iterations to explore alternatives (and maybe export an image or some data for each iteration).
It takes a bit longer to set up the family file, but setting up the dynamo definition would be quicker/leaner — because you could get to the params directly without having to go through any placed family instances — you just pick all the params you want to manipulate directly from the FamilyManager.

I think this example could be handled based on list of family parameters values or function (custom node) producing such list. The main node will take family and such list and will process each resulting variation per criteria.

On this path special node will take 3 inputs: family, list of values for each parameter (could be list of function/custom node computing values), and function/custom node which for each variation produces evaluation criteria.

Such node could produce list of images for each variations or other review-able data and let selection of best variation done manually.

The output is set of parameters with maximal evaluation criteria. Then add resulting type to the family, but have limit on number of such types,. When limit is reached, force deletion of some types.

Did I get your example right?

the getter is actually quite useful to you can grab instance or type params
from the family you are developing a dynamo workflow in.

the setter is useful if you are doing something iterative like andreas
mentioned. I would not simply add 10 to the current value per run but do it
based on a condition like what Z-value we are at or other cases Andreas
mentioned.

both are fairly trivial to create as they reuse about 80-90% of the
Type/Instance nodes. When I built the Type nodes I thought about
refactoring, there would be more of a case now for a FamilyParamBase class
that parameter getter/setters for Type, Instance and Family Definition
nodes all derive from.

On Fri, Sep 20, 2013 at 10:21 AM, Andreas Dieckmann notifications@github.com> wrote:

Источник

filtering with Revit parameters (python for Dynamo) link

laptop with title, cloud shaped balloons, rocket shaped balloon, orange and green

When I first started my blog, my original intent was to cover equal parts Dynamo content and Revit API content. Due to numerous circumstances, I dove headfirst into developing plug-ins for Revit and haven’t spent much time in Dynamo since August of last year. Every time I did go in to write a script, I also encountered some of the same frustrations. Don’t get me wrong, I think Dynamo is invaluable, but if you don’t utilize the Revit API, there are limitations. Recently, I’ve been spending more time in Dynamo and am going to start interjecting some Dynamo posts on my blog. Of course anything you can do in Dynamo you can due purely in Python or C#, but I see value in creating graphs including ease of use and speed. I think there is a benefit to using Dynamo nodes but also to utilizing opportunities to make your graphs more efficient. Currently, I’m trying to collect Python snippets that you can use in a Python node in Dynamo to make your workflow faster and easier.

A minor note on terminology, when I am discussing parameters for elements in Revit I will do my best to always refer to them as Revit parameters to avoid confusion with method parameters.

collecting elements that have a specific Revit parameter:

Personally, one of my least favorite things to do in Dynamo is filter lists. I find filtering with nodes unnecessarily complicated and often I need so many nodes to filter out what I want. One of these examples is filtering for Revit parameters. Last week, for example, I wanted a Dynamo script to turn off the visibility setting of a certain instance Revit parameter in all the title blocks in a project. I wrote two helpful nodes that are super simple but save you so much time.

The first challenge I ran into is we had planning packages and construction document sheets set up and not all of them contained the Revit visibility parameter I wanted to toggle. So the first Python node finds all elements that have a certain Revit parameter.

The node has two inputs. The input at index 0 is a list of elements and the input at index 1 is a list of the element’s Revit parameters. You can get these inputs with Dynamo nodes (see graph at the end of this post). After creating a new empty list, the node then looks at each element and that element’s Revit parameters. If the element has a Revit parameter with the name “Consultant Stamp” it adds it to our new list. You can copy and paste the code below into a Python node in your own Dynamo script and change the p.Name from “Consultant Stamp” to the Revit parameter relevant to you. Please note when comparing strings, the name needs to be an exact match including spaces and capitalizations. The block then returns a list of elements that have a Revit parameter equal to the p.Name you specified.

filter list based on Revit parameter value

After I found all the title blocks that had the Consultant Stamp Revit parameter, I wanted to hide it if it was visible so I had to filter the list one more time. This time, I needed to filter by the Revit parameter value. This node will only have one input and that will be the list of Revit parameters of the elements we filtered with the previous Python node.

Because the Consultant Stamp Revit parameter is a visibility Revit parameter, a value of 0 means it is hidden and a value of 1 means it is visible. I want to check if p.Name is equal to “Consultant Stamp” and p.Value is equal to 1. In other words, I want to select all the elements with the Revit parameter “Consultant Stamp” equal to 1 which means it is visible. Then we can add the element to our new list. The output will be a list of the Revit parameters that we need to hide. We can do this using the Revit Parameter.SetValue node and simply set the value to 0. Remember to also update the p.Name in this node.

And this is what the graph looks like in use:

dynamo graph with collect elements with parameter node and filter list based on parameter value node

summary

And now when we connect our Python nodes with the other nodes, we can easily change the value of a Revit parameter. These nodes can be reused to filter for a number of Revit parameters for different types of elements, not just title blocks. I hope this gives you a few tools that you can use and modify to make your Dynamo workflow more efficient. Happy scripting!

resources

If you want to learn to code and don’t know where to start check out my posts about Steps to Learn to Code [for architects and designers] Part 1 and Part 2.

Источник

Оцените статью