Exemplo n.º 1
0
def add_temperatures(t_start, t_end, fluid_type, coolprop_fluid, pressure, t_init=273.15):
    """
    Add new temperature with associated heat capacity and viscosity
    :return: None
    """
    with rpw.db.Transaction("Add temperatures"):
        for i in xrange(t_start, t_end + 1):
            # Call CoolProp to get fluid properties and convert it to internal units if necessary
            temperature = t_init + i
            viscosity = UnitUtils.ConvertToInternalUnits(
                PropsSI('V', 'T', temperature, 'P', pressure, coolprop_fluid), DisplayUnitType.DUT_PASCAL_SECONDS)
            density = UnitUtils.ConvertToInternalUnits(PropsSI('D', 'T', temperature, 'P', pressure, coolprop_fluid),
                                                          DisplayUnitType.DUT_KILOGRAMS_PER_CUBIC_METER)
            logger.debug('ν={}, ρ={}'.format(viscosity, density))
            # Catching exceptions and trying to overwrite temperature if asked by user in the TaskDialog
            try:
                fluid_type.AddTemperature(FluidTemperature(temperature, viscosity, density))
            except Exceptions.ArgumentException:
                result = TaskDialog.Show("Error", "Temperature already exist, do you want to overwrite it ?",
                                         TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No |
                                         TaskDialogCommonButtons.Cancel,
                                         TaskDialogResult.Yes)
                if result == TaskDialogResult.Yes:
                    try:
                        fluid_type.RemoveTemperature(temperature)
                        fluid_type.AddTemperature(FluidTemperature(temperature, viscosity, density))
                    except Exceptions.ArgumentException:
                        TaskDialog.Show("Overwrite error", "Temperature is currently in use and cannot be overwritten")
                elif result == TaskDialogResult.No:
                    pass
                else:
                    break
Exemplo n.º 2
0
def move_element_schedule(scheduleview_port, view, value_x, value_y):
    bb_vp = scheduleview_port.get_BoundingBox(view)
    if bb_vp:
        x = UnitUtils.ConvertToInternalUnits(value_x, DisplayUnitType.DUT_MILLIMETERS)
        y = UnitUtils.ConvertToInternalUnits(value_y, DisplayUnitType.DUT_MILLIMETERS)
        new_x = x - bb_vp.Max.X - bb_vp.Min.X
        pt3 = XYZ(new_x, y, 0)
        point = ElementTransformUtils.MoveElement(doc, scheduleview_port.Id, pt3)
        return point
Exemplo n.º 3
0
 def create_assets(self, revit_material, layer):
     doc = self.doc
     layer_name = self.layer_name
     country = self.country
     thermal_asset = ThermalAsset(layer_name, ThermalMaterialType.Solid)
     structural_asset = StructuralAsset(layer_name,
                                        StructuralAssetClass.Basic)
     thermal = utils.get_by_country(layer.thermal, country)
     physical = utils.get_by_country(layer.physical, country)
     density = getattr(physical, "density", 0)
     if density:
         thermal_asset.Density = (
             structural_asset.Density) = UnitUtils.ConvertToInternalUnits(
                 density,
                 get_density_unit(),
             )
     thermal_asset.Porosity = getattr(physical, "Porosity", 0) or 0
     specific_heat_capacity = (getattr(thermal, "therm_capa", 0)
                               or 0) * 3600
     if specific_heat_capacity:
         thermal_asset.SpecificHeat = UnitUtils.ConvertToInternalUnits(
             specific_heat_capacity,
             get_heat_capacity_unit(),
         )
     thermal_conductivity = getattr(thermal, "lambda_value", 0) or 0
     if thermal_conductivity:
         thermal_asset.ThermalConductivity = UnitUtils.ConvertToInternalUnits(
             thermal_conductivity,
             get_conductivity_unit(),
         )
     # Create thermal and structural property sets
     thermal_property_set = PropertySetElement.Create(doc, thermal_asset)
     structural_property_set = PropertySetElement.Create(
         doc, structural_asset)
     thermal_property_set.get_Parameter(
         BuiltInParameter.PROPERTY_SET_DESCRIPTION).Set(self.description)
     structural_property_set.get_Parameter(
         BuiltInParameter.PROPERTY_SET_DESCRIPTION).Set(self.description)
     thermal_property_set.get_Parameter(
         BuiltInParameter.MATERIAL_ASSET_PARAM_SOURCE_URL).Set(self.url)
     structural_property_set.get_Parameter(
         BuiltInParameter.MATERIAL_ASSET_PARAM_SOURCE_URL).Set(self.url)
     thermal_property_set.get_Parameter(
         BuiltInParameter.MATERIAL_ASSET_PARAM_SOURCE).Set(
             "materialsdb.org")
     structural_property_set.get_Parameter(
         BuiltInParameter.MATERIAL_ASSET_PARAM_SOURCE).Set(
             "materialsdb.org")
     # Assign thermal and structural property sets to material
     revit_material.SetMaterialAspectByPropertySet(MaterialAspect.Thermal,
                                                   thermal_property_set.Id)
     revit_material.SetMaterialAspectByPropertySet(
         MaterialAspect.Structural, structural_property_set.Id)
Exemplo n.º 4
0
def convert_cm_to_feet(length):
    """Function to convert cm to feet."""
    rvt_year = int(app.VersionNumber)

    # RVT >= 2022
    if rvt_year < 2022:
        from Autodesk.Revit.DB import DisplayUnitType
        return UnitUtils.Convert(length, DisplayUnitType.DUT_CENTIMETERS,
                                 DisplayUnitType.DUT_DECIMAL_FEET)
    # RVT >= 2022
    else:
        from Autodesk.Revit.DB import UnitTypeId
        return UnitUtils.ConvertToInternalUnits(length, UnitTypeId.Centimeters)
Exemplo n.º 5
0
def get_layers_to_string(structure_element, element_param_name, material_param_name, base=''):
    element_type = doc.GetElement(structure_element.GetTypeId())
    element_param = element_type.LookupParameter(element_param_name)
    if element_param:
        structure = element_type.GetCompoundStructure()
        variable_layer_index = structure.VariableLayerIndex
        max_point = get_max_slab_shape_vertex(structure_element)
        layers = structure.GetLayers()
        data = ''
        for i in range(0, len(layers)):
            width = to_int(UnitUtils.ConvertFromInternalUnits(layers[i].Width, DisplayUnitType.DUT_MILLIMETERS))
            name = get_material_name(layers[i].MaterialId, material_param_name).capitalize()
            if not name:
                name = 'Value_is_missing'
            is_variable_layer = layers[i].LayerId == variable_layer_index
            if width != 0 and not is_variable_layer or isinstance(max_point, str):
                data += '\r\n{}. {} - {} мм'.format(i + 1, name, width)
            elif is_variable_layer and not isinstance(max_point, str):
                total_width = to_int(width + max_point)
                data += '\r\n{}. {} - от {}-{} мм'.format(i + 1, name, width, total_width)
            else:
                data += '\r\n{}. {}'.format(i + 1, name)
        if base:
            data += '\r\n{}. {}'.format(len(layers) + 1, base)
        if element_param.StorageType == StorageType.String:
            element_param.Set(data.strip())
        return data.strip()
Exemplo n.º 6
0
def unit_conversion():
    """Convert Revit units to Dynamo Units."""
    doc = DocumentManager.Instance.CurrentDBDocument
    doc_units = doc.GetUnits()
    length_unit = doc_units.GetFormatOptions(UnitType.UT_Length).DisplayUnits

    return UnitUtils.ConvertFromInternalUnits(1.0, length_unit)
Exemplo n.º 7
0
def set_value_by_param_name(elem, parameter_name, value):
    param = elem.LookupParameter(parameter_name)
    if param:
        if param.StorageType == StorageType.String:
            val = UnitUtils.ConvertFromInternalUnits(value, DisplayUnitType.DUT_SQUARE_METERS)
            param.Set(str(val))
        elif param.StorageType == StorageType.Double:
            param.Set(value)
Exemplo n.º 8
0
def get_max_slab_shape_vertex(structure_element):
    if structure_element.Category.Id.IntegerValue == -2000032:
        slab_shape_editor = structure_element.SlabShapeEditor
        if slab_shape_editor:
            slab_shape_vertices = slab_shape_editor.SlabShapeVertices
            point_z = [vertice.Position.Z for vertice in slab_shape_vertices]
            return UnitUtils.ConvertFromInternalUnits(max(point_z), DisplayUnitType.DUT_MILLIMETERS)
    else:
        return 'no shape editor'
Exemplo n.º 9
0
def Convert_length(length):
    """ 
    convert  length To Internal Units \n
    Converts a value from a given display unit to Revit's internal units.
    """
    # retrieve unit display current in revit 
    unit_format_options = doc.GetUnits().GetFormatOptions(UnitType.UT_Length)
    display_unit = unit_format_options.DisplayUnits
    return UnitUtils.ConvertToInternalUnits(float(length), display_unit)
Exemplo n.º 10
0
 def around_axis_click(self, sender, e):
     try:
         rotate_elements.angles = UnitUtils.ConvertToInternalUnits(
             float(self.rotation_angle.Text), angle_unit)
         rotate_elements.selection = uidoc.Selection.GetElementIds()
     except ValueError:
         self.warning.Text = "Incorrect angles, input format required '0.0'"
     else:
         customizable_event.raise_event(rotate_elements.around_axis)
Exemplo n.º 11
0
def cutElements(col, paramName, value):  # Получение список плиток меньше значения value из paramName
    result = []
    for i in col:
        para = i.LookupParameter(paramName)
        if para:
            param_value = round(UnitUtils.ConvertFromInternalUnits(para.AsDouble(), para.DisplayUnitType))
            if param_value < value:
                result.append(i)
    return result
Exemplo n.º 12
0
def set_unit(val):
    '''display given value with the conversion variables on top
    '''
    val_out = None
    try:
        val_out = UnitUtils.Convert(val, USER_UNIT_IN, USER_UNIT_OUT)

    except:
        val_out = val

    return val_out
Exemplo n.º 13
0
def set_parameter_by_name(value, param_name, document):
    f_manager = document.FamilyManager
    if len(list(f_manager.Types)) == 0:
        f_manager.NewType('Тип 1')
    param = f_manager.get_Parameter(param_name)
    if param:
        if param.CanAssignFormula:
            val = UnitUtils.ConvertFromInternalUnits(value, param.DisplayUnitType)
            f_manager.SetFormula(param, str(val))
            return '{} - {}'.format(param_name, val)
    else:
        return 'Not OK'
Exemplo n.º 14
0
 def around_itself_click(self, sender, e):
     try:
         rotate_elements.selection = uidoc.Selection.GetElementIds()
         angles = [self.x_axis.Text, self.y_axis.Text, self.z_axis.Text]
         internal_angles = [
             UnitUtils.ConvertToInternalUnits(float(i), angle_unit)
             for i in angles
         ]
         rotate_elements.angles = internal_angles
     except ValueError:
         self.warning.Text = "Incorrect angles, input format required '0.0'"
     else:
         self.warning.Text = ""
         customizable_event.raise_event(rotate_elements.around_itself)
Exemplo n.º 15
0
def get_square_from_runs_and_landings(stair):
    if stair.Category.Id.IntegerValue == -2000120:
        document = stair.Document
        runs_square = get_square_from_part(stair.GetStairsRuns(), document)
        landings_square = get_square_from_part(stair.GetStairsLandings(),
                                               document)
        if runs_square:
            set_value(stair, IN[1], runs_square)  # noqa
            value_runs = UnitUtils.ConvertFromInternalUnits(
                runs_square, DisplayUnitType.DUT_SQUARE_METERS)
        else:
            set_value(stair, IN[1], 0)  # noqa
            value_runs = 'нет маршей'
        if landings_square:
            set_value(stair, IN[2], landings_square)  # noqa
            value_landings = UnitUtils.ConvertFromInternalUnits(
                landings_square, DisplayUnitType.DUT_SQUARE_METERS)
        else:
            set_value(stair, IN[2], 0)  # noqa
            value_landings = 'нет площадок'
        return 'Площадь ступенек: {}'.format(
            value_runs), 'Площадь площадок: {}'.format(value_landings)
    else:
        return 'Select stair'
Exemplo n.º 16
0
def renameLevel(levels, sign=True):
    count = 1
    TransactionManager.Instance.EnsureInTransaction(doc)
    for ld in levels:
        elev_mm = UnitUtils.ConvertFromInternalUnits(
            ld.Elevation, DisplayUnitType.DUT_METERS)
        param = ld.get_Parameter(BuiltInParameter.DATUM_TEXT)
        if param:
            if sign:
                name_level = "L{}(+{:.3f})".format(count, elev_mm)
            else:
                name_level = "B{}({:.3f})".format(count, elev_mm)
            param.Set(name_level)
            count += 1
    TransactionManager.Instance.TransactionTaskDone()
Exemplo n.º 17
0
def CreateDimensions(filledRegion, dimensionDirection):
    document = filledRegion.Document
    view = filledRegion.Document.GetElement(filledRegion.OwnerViewId)
    edgesDirection = dimensionDirection.CrossProduct(view.ViewDirection)
    edges = []
    for x in FindRegionEdges(filledRegion):
        if IsEdgeDirectionSatisfied(x, edgesDirection):
            edges.append(x)
    if len(edges) < 2:
        return
    shift = UnitUtils.ConvertToInternalUnits(
        -10 * view.Scale, DisplayUnitType.DUT_MILLIMETERS) * edgesDirection
    dimensionLine = Line.CreateUnbound(
        filledRegion.get_BoundingBox(view).Min + shift, dimensionDirection)
    references = ReferenceArray()
    for edge in edges:
        references.Append(edge.Reference)
    document.Create.NewDimension(view, dimensionLine, references)
Exemplo n.º 18
0
def GetBalisterCount(items, document):
    types = []
    info = []
    for item in items:
        param_length = item.get_Parameter(BuiltInParameter.CURVE_ELEM_LENGTH)
        railingType = document.GetElement(item.GetTypeId())
        bp = railingType.BalusterPlacement.BalusterPattern
        cornerPost = railingType.BalusterPlacement.PostPattern
        cornerPost_el = doc.GetElement(cornerPost.CornerPost.BalusterFamilyId)
        info.append(
            UnitUtils.ConvertFromInternalUnits(
                bp.PatternAngle, DisplayUnitType.DUT_DEGREES_AND_MINUTES))
        if bp.DistributionJustification == PatternJustification.Beginning or \
                bp.DistributionJustification == PatternJustification.End:
            count = int(param_length.AsDouble() / bp.Length)
        elif bp.DistributionJustification == PatternJustification.Center:
            count = int(param_length.AsDouble() / bp.Length) + 2
        elif bp.DistributionJustification == PatternJustification.SpreadPatternToFit:
            count = int(param_length.AsDouble() / bp.Length) - 2
        if cornerPost_el:
            count += 1
        types.append(count)

    return types, info
Exemplo n.º 19
0
def import_config_length(length):
    return str(UnitUtils.ConvertFromInternalUnits(float(length), display_unit))
Exemplo n.º 20
0
def ConvertFromInteralUnitToMM(Parameter):
    Parameter = UnitUtils.ConvertFromInternalUnits(
        float(Parameter), DisplayUnitType.DUT_MILLIMETERS)
    return Parameter
Exemplo n.º 21
0
def Convert_length(length):
    Int_Length = (UnitUtils.ConvertFromInternalUnits(float(length),
                                                     display_unit))
    return int(round(Int_Length))
Exemplo n.º 22
0
def valueParameter(param, paramName):
    para = param.LookupParameter(paramName)
    return round(UnitUtils.ConvertFromInternalUnits(para.AsDouble(), para.DisplayUnitType))
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager

doc = DocumentManager.Instance.CurrentDBDocument

# argument assigned the IN port
elements = list(UnwrapElement(IN[0]))
load_value = IN[1]
load_type = list(UnwrapElement(IN[2]))

# wrap input inside a list (if not a list)
if not isinstance(load_value, list):
    load_value = [load_value]

# output unit
dut = DisplayUnitType.DUT_METERS

# core data processing
loads = []
TransactionManager.Instance.EnsureInTransaction(doc)
for ids, (element, outer) in enumerate(zip(elements, load_value)):
    for inner in outer:
        Zaxis = UnitUtils.ConvertFromInternalUnits(inner, dut)
        areaload = AreaLoad.Create(doc, element, XYZ(0, 0, Zaxis),
                                   load_type[0])
        loads.append(areaload)
TransactionManager.Instance.ForceCloseTransaction()

# return assigned the OUT port
OUT = loads
Exemplo n.º 24
0
def export_config_length(lenght):
    return str(UnitUtils.ConvertToInternalUnits(float(lenght), display_unit))
Exemplo n.º 25
0
from RevitServices.Transactions import TransactionManager


doc = DocumentManager.Instance.CurrentDBDocument

el_fam = FilteredElementCollector(doc).OfClass(Family).ToElements()
el_inst = FilteredElementCollector(doc).OfClass(FamilyInstance).ToElements()
schemaGuid = System.Guid('3cd61681-a611-4a2f-b49c-ea8f0030807b')
sch = Schema.Lookup(schemaGuid)

fam_name = [f.Name for f in el_fam if f.GetEntity(sch).SchemaGUID == schemaGuid]

el = []
param_offset_guid = System.Guid('e4793a44-6050-45b3-843e-cfb49d9191c5')
param_guid = System.Guid('6ec2f9e9-3d50-4d75-a453-26ef4e6d1625')

TransactionManager.Instance.EnsureInTransaction(doc)
for e in el_inst:
    if e.Symbol.Family.Name in fam_name and e.get_Parameter(param_offset_guid):
        lev = UnitUtils.ConvertFromInternalUnits(e.Location.Point.Z, DisplayUnitType.DUT_MILLIMETERS)
        param = e.get_Parameter(param_offset_guid)
        param_value = UnitUtils.ConvertFromInternalUnits(param.AsDouble(), param.DisplayUnitType)
        if e.get_Parameter(param_guid):
            param_set = e.get_Parameter(param_guid)
            value = UnitUtils.ConvertToInternalUnits(lev + param_value, param_set.DisplayUnitType)
            param_set.Set(value)
        el.append(e)
TransactionManager.Instance.TransactionTaskDone()

OUT = el
Exemplo n.º 26
0
def meter(double):
    return UnitUtils.ConvertFromInternalUnits(double,
                                              DisplayUnitType.DUT_METERS)
Exemplo n.º 27
0
def convert_to_internal(value, unit="mm"):
    return UnitUtils.ConvertToInternalUnits(
        float(value), LENGTH_UNIT
    )
# Revit and Dynamo module
from Autodesk.Revit.DB import Material, DisplayUnitType, UnitUtils
from RevitServices.Persistence import DocumentManager

doc = DocumentManager.Instance.CurrentDBDocument

# argument assigned the IN port
elements = list(UnwrapElement(IN[0]))

# wrap input inside a list (if not a list)
if not isinstance(elements, list):
    elements = [elements]

# core data processing
unit = DisplayUnitType.DUT_KILOGRAMS_PER_CUBIC_METER
structural_asset, thermal_asset, element = [], [], []
for elem in elements:
    try:
        t1 = doc.GetElement(
            elem.StructuralAssetId).GetStructuralAsset().Density
        structural_asset.append(UnitUtils.ConvertFromInternalUnits(t1, unit))
        t2 = doc.GetElement(elem.ThermalAssetId).GetThermalAsset().Density
        thermal_asset.append(UnitUtils.ConvertFromInternalUnits(t2, unit))
        element.append(elem)
    except BaseException:
        pass

# return assigned the OUT port
OUT = structural_asset, thermal_asset, element
Exemplo n.º 29
0
        scale = v.Scale
        elems = FilteredElementCollector(doc, v.Id).OfClass(CurveElement)
        for e in elems:
            graphics_style_cat = e.LineStyle.GraphicsStyleCategory
            id_cat = graphics_style_cat.Id
            if BuiltInCategory(id_cat.IntegerValue) == BuiltInCategory.OST_ProfileFamilies:
                cat = graphics_style_cat
                line_length += e.GeometryCurve.Length

gs = cat.GetGraphicsStyle(GraphicsStyleType.Projection)
gsCat = gs.GraphicsStyleCategory
gsCat.LineColor = Color(IN[1].Red, IN[1].Green, IN[1].Blue)  # noqa
v.Scale = 1
v.Scale = scale

line_length = UnitUtils.ConvertFromInternalUnits(line_length, DisplayUnitType.DUT_MILLIMETERS)

f_manager = doc.FamilyManager
param_name = "_Профиль.Длина"
length_param = f_manager.get_Parameter(param_name)

if len(list(f_manager.Types)) == 0:
    f_manager.NewType('Тип 1')

if length_param:
    if length_param.CanAssignFormula:
        f_manager.SetFormula(length_param, str(line_length))
        OUT = "Длина профиля {}".format(round(line_length))
else:
    fparameter = f_manager.AddParameter(
        param_name, BuiltInParameterGroup.PG_DATA, ParameterType.Length, False)
Exemplo n.º 30
0
lnkdoc = linkdoc[0]
transform = rvtlinks[0].GetTotalTransform()

rooms = FilteredElementCollector(lnkdoc).OfCategory(
    BuiltInCategory.OST_Rooms).ToElements()
fam_col = FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Furniture). \
    WhereElementIsNotElementType().ToElements()

mlist = []
for room in rooms:
    llist = []
    room_box = room.get_BoundingBox(None)
    boxMin = transform.OfPoint(room_box.Min)
    boxMax = transform.OfPoint(room_box.Max)
    outline = Outline(boxMin, boxMax)
    bbfilter = BoundingBoxIntersectsFilter(outline)
    fam_ins = FilteredElementCollector(doc).OfCategory(
        BuiltInCategory.OST_Furniture).WherePasses(bbfilter).ToElements()
    llist.append(fam_ins)
    param = room.get_Parameter(BuiltInParameter.ROOM_AREA).AsDouble()
    llist.append(
        UnitUtils.ConvertFromInternalUnits(param,
                                           DisplayUnitType.DUT_SQUARE_METERS))
    mlist.append(llist)

flist = []
for f in fam_col:
    flist.append(lnkdoc.GetRoomAtPoint(f.Location.Point))

OUT = flist, fam_col