示例#1
0
def EnergyNeedGraph(f1, f2, action):
    outerdata = rm.OpenTemperatureModel(f1)
    innerdata = rm.OpenTemperatureModel(f2)

    innerTemp, outerTemp, energyNeed, x_axis = [], [], [], []

    for array in innerdata:
        innerTemp.append(array[1])
        x_axis.append(array[0])

    for array in outerdata:
        outerTemp.append(array[1])

    for i in range(0, len(innerTemp)):
        space = action['Space'][0] * action['Space'][1] * action['Space'][2]
        #space2 = action['Space'][0] * action['Space'][1] * action['Space'][3]
        energyNeed.append(
            f.EnergyRequired(f.SubstanceMass(space, 1.29), 1005,
                             (innerTemp[i] - outerTemp[i])))
        #+f.EnergyRequired(f.SubstanceMass(space2, 2500), 920, (innerTemp[i] - innerTemp[i-1])))

    fig = plt.figure()
    fig.show()
    ax = fig.add_subplot(111)

    ax.plot(x_axis, energyNeed, label="EnergyNeed", fillstyle="none")

    plt.xlabel("Time (hours)")
    plt.gcf().autofmt_xdate()
    plt.ylabel("Energy Need (Q in Joules)")
    plt.legend(loc=0)
    plt.draw()
    plt.show()
示例#2
0
文件: Simulator.py 项目: RK21898/WPS
 def __init__(self, action):
     self.action = action
     self.energyNeed = _CalculateNeeds(self.action)
     self.action_space = _CalculateSpace(self.action)
     self.space_output = f.FloorWarmingPower(self.action_space['surface'])
     self.powerlevel = 0
     self.desiredTemp = 20 #Get from dataset based on time (userinput values)
     self.currentTemp = 20 #Get from dataset based on time (imaginary sensor)
     self.time = datetime.now()
     self.fulfilledNeedsData = {}
示例#3
0
文件: Simulator.py 项目: RK21898/WPS
def _CalculateNeeds(action):
    """"CalculateNeeds calculates the needs"""
    innerData = rm.OpenTemperatureModel("InsideRequestTemp")
    outerData = rm.OpenTemperatureModel("OutsideTemp")

    innerTemp, outerTemp, energyNeed = [], [], []

    for array in innerData:
        innerTemp.append(array[1])

    for array in outerData:
        outerTemp.append(array[1])

    for i in range(0, len(innerTemp)):
        space = action['Space'][0] * action['Space'][1] * action['Space'][2]
        #space2 = action['Space'][0] * action['Space'][1] * action['Space'][3]
        #print((innerTemp[i] - innerTemp[i-1]))
        energyNeed.append(f.EnergyRequired(f.SubstanceMass(space, 1.29), 1005, (innerTemp[i] - outerTemp[i])))
                            #+f.EnergyRequired(f.SubstanceMass(space2, 2500), 920, (innerTemp[i] - innerTemp[i-1])))
    
    return energyNeed
示例#4
0
    def get_data5(self, pointers=False):

        result = {'filenames':[],'filesmesh':[],'filenames_mn':[],'filesmesh_mn':[],'filenames_for':[]}
        
        # default value
        result['fieldtype'] = 'scalar' # vector

        mesh = self.get_attribs().get(config.PLOT_MESH)
        add_mesh = self.get_attribs().get(config.PLOT_ADD_MESH)
        point = self.get_attribs().get(config.PLOT_POINT_DATA)
        cell = self.get_attribs().get(config.PLOT_CELL_DATA)
        data = self.get_attribs().get(config.PLOT_DATA)
        formula = self.get_attribs().get(config.PLOT_FORMULA) # pointers?

        evolution = self.get_attribs().get(config.PLOT_EVOLUTION)
        if evolution is None:
            result['evolution'] = 'Time'
            result['evolution_lower'] = 'time'
            result['evolution_upper'] = 'Time'
        else: # mellorable loxica de maiuscula/minuscula
            result['evolution'] = evolution
            evu = evolution
            if len(evolution) > 0:
                evu = evu[0].lower() + evu[1:]
            result['evolution_lower'] = evu
            evu = evolution
            if len(evolution) > 0:
                evu = evu[0].upper() + evu[1:]
            result['evolution_upper'] = evu

        interpolation = self.get_attribs().get(config.PLOT_INTERPOLATION)
        result['interpolation'] = interpolation != config.VALUE_FALSE

        # esto podría sobrar: dim en el mismo elemento del gráfico, frente a en el leaf file
        #dim1 = self.get_attribs().get(config.AT_DIM)
        #if dim1 is not None:
        #    try:
        #        result['dim'] = int(dim1)
        #    except ValueError:
        #        return 'Incorrect dimension: ' + dim1

        # whether computes dependences or not
        if pointers:
            objects = []
        else:
            objects = None

        field = None
        if point is not None:
            result['fielddomain'] = 'point'
            field = point
        if cell is not None:
            result['fielddomain'] = 'cell'
            field = cell

        if point is not None and cell is not None:
            return u'Both "celldata" and "pointdata" attributes present'
        
        if data is not None and (mesh is not None or add_mesh is not None or point is not None or cell is not None):
            return u'"data" attribute is incompatible with "mesh","add_mesh","pointdata","celldata"'
        if data is not None and formula is not None:
            return u'"data" attribute is incompatible with "formula" attribute'
#        if (mesh is not None or add_mesh is not None or point is not None or cell is not None) and formula is not None: # ou compatible con point/cell para indicar o tipo de datos
#            return u'"mesh","add_mesh","pointdata","celldata" attributes are incompatible with "formula" attribute'
#        if (mesh is not None or add_mesh is not None) and formula is not None:
#            return u'"mesh","add_mesh" attributes are incompatible with "formula" attribute'
        if data is None and mesh is None and formula is None:
            return u'Missing "mesh" or "data" or "formula" attributes'


        if formula is not None:
            fv = psps.extract_parts(formula)
            if isinstance(fv, basestring):
                return 'Error in formula: ' + fv
            result['formula_text'] = fv[0]
            result['formula_vars'] = fv[1]
            result['formula_data'] = []
            result['formula_is'] = True
            # encher recursivamente outras
            for i in xrange(len(result['formula_vars'])):
                var = result['formula_vars'][i]
                name = var[0]
                type_ = var[1]
                path = var[2]

                # extra
                if type_ == 'menu': # or type_ == 'field' or type_ == 'value':

                    # sen variables
                    #node = self.get_node_from_path(path) # ou outra funcion que permita o uso de variables
                    #if isinstance(node, basestring): # error
                    #    return "Invalid path: " + node
                    #if node is None: # invalid node
                    #    return "Invalid path: " + path

                    # con variables (por se acaso, xa que so admite un nodo)
                    nodes = self.parse_path_varx(path, True, False, objects, True, None) # objects duplicados abaixo ?
                    if Debug: print 'parse_path_varx.objects', map(Node.get_path, objects)
                    if isinstance(nodes, basestring): # error
                        return "Invalid path: " + nodes
                    if nodes is None: # invalid node
                        return "Invalid path: " + path
                    if len(nodes) != 1:
                        return "Invalid number of referenced nodes: " + unicode(len(nodes))
                    node = nodes[0]

                else:
                    node = None
                var.append(node) # 3

                type2 = None
                if type_ == 'menu':
                    if node.get_attribs().get(config.PLOT_MESH) is not None or \
                        node.get_attribs().get(config.PLOT_FORMULA) is not None: # se ten grafico
                        type2 = 'menu-field'
                    elif node.get_tag() == 'leaf' and (node.get_attribs().get(config.AT_TYPE) == 'float' or node.get_attribs().get(config.AT_TYPE) == 'complex'): # se e un leaf float
                        type2 = 'menu-value'
                    else:
                        return 'Type of node unknown'
                else:
                    type2 = type_
                var.append(type2) # 4

                if type2 == 'menu-field':
                    res = node.get_data5(pointers)
                    if isinstance(res, basestring):
                        return 'Error in dependence of formula: ' + res
                    if objects is not None:
                        objects.extend(res.get('dependencies')) # objects duplicados arriba ?
                        if Debug: print 'subdata.dependencies', map(Node.get_path,res.get('dependencies'))

                    if res.get('fielddomain') != result.get('fielddomain'):
                        return 'Mismatched field domains: ' + unicode(result.get('fielddomain')) + ' and ' + unicode(res.get('fielddomain'))
                    result['formula_data'].append(res)
                    result['filenames_for'].extend(res.get('filenames'))
                    result['filenames'].extend(res.get('filenames'))
                elif type2 == 'menu-value':
                    if objects is not None:
                        objects.append(node)
                    result['formula_data'].append(None)
                elif type2 == 'data': # non permitido este caso
                    result['formula_data'].append(None)
                else:
                    result['formula_data'].append(None)


        if mesh is not None: # >=0
            mesh_names = []
            # type, string
            parsed = self.parse_source_string_1(mesh)
            if parsed[0] is None:
                return u'Error parsing "mesh" source string'
            elif parsed[0] == 1: # file
                res = self.parse_path_varx(parsed[1],False,False,objects,mesh_names=mesh_names)
            elif parsed[0] == 2: # menu
                res = self.parse_path_varx(parsed[1],True,True,objects,mesh_names=mesh_names)
            else:
                return u'"mesh" attribute only allows "file:" and "menu:" prefixes'

            if isinstance(res, basestring):
                return res

            result['filesmesh1'] = res
            result['filesmesh'].extend(res)
            result['filenames'].extend(res) # mesh files are always first files
            result['filesmesh1_mn'] = mesh_names
            result['filesmesh_mn'].extend(mesh_names)
            result['filenames_mn'].extend(mesh_names)


        if add_mesh is not None: # >=0
            mesh_names = []
            # type, string
            parsed = self.parse_source_string_1(add_mesh)                
            if parsed[0] is None:
                return u'Error parsing "add_mesh" source string'
            elif parsed[0] == 1: # file
                res = self.parse_path_varx(parsed[1],False,False,objects,mesh_names=mesh_names)
            elif parsed[0] == 2: # menu
                res = self.parse_path_varx(parsed[1],True,True,objects,mesh_names=mesh_names)
            else:
                return u'"add_mesh" attribute only allows "file:" and "menu:" prefixes'

            if isinstance(res, basestring):
                return res

            result['filesmesh2'] = res
            result['filesmesh'].extend(res)
            result['filenames'].extend(res) # add_mesh files are always second files
            result['filesmesh2_mn'] = mesh_names
            result['filesmesh_mn'].extend(mesh_names)
            result['filenames_mn'].extend(mesh_names)


        if field is not None: # solo 1
            mesh_names = []
            tupf = self.parse_source_string_2(field, objects, mesh_names=mesh_names)
            if tupf[0] is None:
                return u'Error parsing "' + result.get('fielddomain') + 'data" source string'
            if tupf[0] != 0 and tupf[0] != 1 and tupf[0] != 2:
                return u'"celldata" and "pointdata" attributes only allow "data:", "file:" and "menu:" prefixes'
            if tupf[2] is not None and result.get('dim') is None:
                result['dim'] = tupf[2]
            if tupf[0] == 1 or tupf[0] == 2:
                result['filenames'].append(tupf[1]) # field, if present, is last file
                result['filesfield'] = [tupf[1]]
                result['filenames_mn'].extend(mesh_names)
                result['filesfield_mn'] = mesh_names

                # en caso de fichero de campo: poner campo = nombre de fichero
                # o bien: poner nombre fijo
                
                temp = os.path.basename(tupf[1])
                
                i = temp.rfind('.')
                if i <= 0: # correcto <= en vez de <, porque: para '.mff' proporciona '.mff', no ''
                    temp2 = temp
                else:
                    temp2 = temp[:i]

                result['fieldname'] = temp2#.replace(' ','_') deprecated

            elif tupf[0] == 0:
                result['fieldname'] = tupf[1]

        if data is not None: # test.gr2 por exemplo # solo 1
            # type, string, dim(int or None)
            tupm = self.parse_source_string_2(data, objects)
            if tupm[0] is None:
                return u'Error parsing "data" source string'
            if tupm[0] != 1 and tupm[0] != 2:
                return u'"data" attribute only allows "file:" and "menu:" prefixes'
            #Graph2d permite menu:
            graph2d_filenames = self.parse_path_varx(tupm[1],False,False,objects)
            result['filesdata'] = graph2d_filenames
            for f in graph2d_filenames:
                result['filenames'].append(f)


#        print 'DEBUG: get_data5.filenames: ', result['filenames']

        if Debug and objects is not None:
            print 'start pointers for', self.get_path()
            # un plot pode ter varios structs !!!
            #clear ?
            #self.set_dependencies(objects, True)
            for o in objects:
                print ':', o.get_path()
            print 'end pointers', 'total', len(objects)
            
        result['dependencies'] = objects
        
        return result
示例#5
0
def run():

    # These have to be in meters
    total_radius = Decimal(30)
    outer_radius = Decimal(4)
    wall_thickness = Decimal(.0254 * 1)

    # m/s2
    acceleration = Decimal(9.81)

    # Must be in kilograms
    additional_mass = Decimal(100000)

    # Put in terms of g/cm3
    density_of_material = Decimal(2.84)  # g/cm3 Al alloy 2219
    density_of_material = Decimal(
        Conversions.g_cm3_to_kg_m3(density_of_material))

    # Max tensile strength of the material given in MPa
    tensile_strength = Decimal(248)

    if wall_thickness > outer_radius:
        print(
            "Wall thickness cannot be bigger than the outer radius and will be clamped to that number"
        )
        wall_thickness = outer_radius

    # Find a lot of common variables which are used often in other equations
    linear_velocity = Formulas.linear_speed_rotational(total_radius,
                                                       acceleration)
    rpm = Conversions.linear_to_rpm(total_radius, linear_velocity)
    volume_of_walls = Formulas.volume_of_torus_wall(total_radius, outer_radius,
                                                    wall_thickness)

    # Calculate the stress on the torus in MPa
    stress = Formulas.stress_on_torus(total_radius, outer_radius,
                                      wall_thickness, density_of_material,
                                      acceleration, additional_mass)

    # Volume of torus wall
    print('Volume of torus wall(internal): ' +
          str(round(volume_of_walls, pretty_round)) +
          ' m3'.translate(superscript))

    # Internal volume of torus for thickness of wall
    print('Volume of torus (hollow): ' + str(
        round(
            Formulas.volume_of_hollow_torus(total_radius, outer_radius,
                                            wall_thickness), pretty_round)) +
          ' m3'.translate(superscript))

    # Speed torus would have to spin linearly to achieve centripetal acceleration
    print('Linear speed: ' + str(round(linear_velocity, pretty_round)) +
          ' m/s'.translate(superscript))

    # 2-3 rpm is optimal, 10 rpm max can be trained
    print('RPM: ' + str(
        round(Conversions.linear_to_rpm(total_radius, linear_velocity),
              pretty_round)) + ' rpm')

    # Outer circumference of torus
    print('Outer circumference: ' + str(
        round(Formulas.circumference_of_circle(total_radius), pretty_round)) +
          ' m')

    # Cross section used to calculate force acting on torus
    print('Cross Section of torus: ' + str(
        round(
            Formulas.cross_section_hollow_torus(outer_radius, wall_thickness),
            pretty_round)) + ' m2'.translate(superscript))

    # Convert to imperial so it's easier to read
    print('Internal radius of torus: ' + str(
        round(Conversions.meter_to_feet(outer_radius -
                                        wall_thickness), pretty_round)) +
          ' ft')

    # Useful when performing other calculations
    print('Angular Velocity: ' +
          str(round(Conversions.rpm_to_angular(rpm), pretty_round)) + ' rad/s')

    # Give others an idea how big torus would be
    print('Stories high: ' +
          str(round((total_radius * Decimal(2)) / Decimal(ft_per_story))) +
          ' (' + str(ft_per_story) + ' ft per story)'.translate(superscript))
    # Mass of ring
    print('Mass: ' +
          str(round(density_of_material * volume_of_walls +
                    additional_mass, 2)) + ' kg')

    print('---------------------')
    # Force along cross sectional area in MPa
    print('Force on torus: ' + str(round(stress, 2)) + ' MPa')

    if stress <= tensile_strength:
        print("The torus can hold itself with: " +
              str(round(tensile_strength - stress, 2)) + ' MPa remaining (' +
              str(100 * (1 - round(
                  (tensile_strength - stress) / tensile_strength, 2))) +
              "% of total applicable)")
    else:
        print("The torus can't hold itself with: " +
              str(round(tensile_strength - stress, 2)) + ' MPa in excess (' +
              str(100 * (1 - round(
                  (tensile_strength - stress) / tensile_strength, 2))) +
              "% of total applicable)")

    if draw:
        Drawing.draw_torus(total_radius,
                           outer_radius,
                           kind=GraphType.MPL,
                           z_ratio=0)
示例#6
0
def inch_to_meter(inches):
    return Formulas.round_floating_point(Decimal(inches * 0.0254))
示例#7
0
def g_cm3_to_kg_m3(g_cm3):
    kg_m3 = Decimal(1000) * g_cm3

    return Formulas.round_floating_point(kg_m3)
示例#8
0
def rpm_to_angular(rpm):
    angular = (Decimal(2) * pi * rpm) / 60

    return Formulas.round_floating_point(angular)
示例#9
0
def rpm_to_linear(total_radius, rpm):
    linear = Decimal(rpm * 2 * total_radius * pi) / Decimal(60)

    return Formulas.round_floating_point(linear)
示例#10
0
def linear_to_rpm(total_radius, linear_speed):
    rpm = Decimal(linear_speed * 60) / Decimal(2 * total_radius * pi)

    return Formulas.round_floating_point(rpm)
示例#11
0
def meter_to_feet(meter):
    return Formulas.round_floating_point(Decimal(meter / Decimal(0.0254 * 12)))
示例#12
0
def feet_to_inch(feet):
    return Formulas.round_floating_point(Decimal(feet / 12))
示例#13
0
def inch_to_feet(inches):
    return Formulas.round_floating_point(Decimal(inches * 12))