Ejemplo n.º 1
0
def pipeline(args):
    '''
    Runs the model loop.

    If you wish to edit any of the parameters for the models, please edit the
    model_loop.py file directly.
    '''
    train_data = SparseMatrix()
    train_data.load_csv(args.train_filename)
    y_train = train_data.get(args.label).todense()
    X_train = train_data.get_all_except(args.label)
    y_train[y_train>1] = 1 # Remove multiclass
    y_train = np.array(np.reshape(y_train, y_train.shape[0]))[0] # Correct shape

    test_data = SparseMatrix()
    test_data.load_csv(args.test_filename)
    y_test = test_data.get(args.label).todense()
    X_test = test_data.get_all_except(args.label)
    y_test[y_test>1] = 1 # Remove multiclass
    y_test = np.array(np.reshape(y_test, y_test.shape[0]))[0] # Correct shape

    loop = ModelLoop(X_train, X_test, y_train, y_test, args.models,
                     args.iterations, args.run_name,
                     args.thresholds, args.label, float(args.comparison),
                     args.project_folder)
    loop.run()
Ejemplo n.º 2
0
class FEM:
    def __init__(self, file, detail):
        self.nodes = []
        self.elements = []
        self.temps = []
        self.K = SparseMatrix(None, True)
        self.F = []
        self.detail = detail
        self.read_mesh(file)

    def read_mesh(self, file):
        with open(file) as fobj:
            xml = fobj.read().encode()
        objectify.fromstring(xml)
        dolfin = etree.fromstring(xml)
        mesh = dolfin.getchildren()[0]
        vertices = mesh.getchildren()[0]
        cells = mesh.getchildren()[1]
        for vertex in vertices.getchildren():
            self.nodes.append(
                Node(int(vertex.get('index')), float(vertex.get('x')),
                     float(vertex.get('y'))))
        for cell in cells.getchildren():
            self.elements.append(
                Element(int(cell.get('index')),
                        self.nodes[int(cell.get('v0'))],
                        self.nodes[int(cell.get('v1'))],
                        self.nodes[int(cell.get('v2'))]))

    def set_type_border(self, elem):
        """
        Description
        -----------
        If the element is on border defines its type: convective_heat_transfer, defined_T or heat_flow
        """
        is_border = False
        for i in range(len(self.detail.borders)):
            if i in [0, 1, 2, 3, 5]:
                type = 'convective_heat_transfer'
                if i in [3, 5]:
                    val = ALPHA1
                else:
                    val = ALPHA2
            elif i == 4:
                type = 'defined_T'
                val = T_DEF
            else:
                type = 'heat_flow'
                val = Q_DEF

            if elem.s1.is_in_line(
                    self.detail.borders[i]) and elem.s2.is_in_line(
                        self.detail.borders[i]):
                is_border = True
                border = '12'
                if type == 'defined_T':
                    self.nodes[elem.s1.index].t = val
                    self.nodes[elem.s2.index].t = val
            if elem.s2.is_in_line(
                    self.detail.borders[i]) and elem.s3.is_in_line(
                        self.detail.borders[i]):
                is_border = True
                border = '23'
                if type == 'defined_T':
                    self.nodes[elem.s2.index].t = val
                    self.nodes[elem.s3.index].t = val
            if elem.s3.is_in_line(
                    self.detail.borders[i]) and elem.s1.is_in_line(
                        self.detail.borders[i]):
                is_border = True
                border = '31'
                if type == 'defined_T':
                    self.nodes[elem.s3.index].t = val
                    self.nodes[elem.s1.index].t = val
            if is_border:
                elem.borders[border]['type'] = type
                elem.borders[border]['val'] = val
            is_border = False

    def define_border_conditions(self):
        for elem in self.elements:
            self.set_type_border(elem)

    def build_system(self):
        """
        Description
        -----------
        Forms system of equations to solve
        """
        self.K.shape = (len(self.nodes), len(self.nodes))
        self.F = np.zeros(len(self.nodes))
        for i, elem in enumerate(self.elements):
            k = elem.form_elem_matrix(Kxx, Kyy)
            for j in range(3):
                for r in range(3):
                    self.K.add(index=(elem.s[j].index, elem.s[r].index),
                               val=k[j][r])
            f = elem.form_vector_of_external_influences(
                self.detail.source_points)

            for j in range(3):
                self.F[elem.s[j].index] += f[j]

        for node in self.nodes:
            if node.t is not None:
                self.K.set(index=(node.index, node.index), val=1)
                self.F[node.index] = node.t
                for node_k in self.nodes:
                    if node_k.index != node.index:
                        self.K.set(index=(node.index, node_k.index), val=0)
                        self.F[node_k.index] -= self.K.get(
                            index=(node_k.index, node.index)) * node.t
                        self.K.set(index=(node_k.index, node.index), val=0)

    def solve_system(self):
        self.temps = solve(self.K, self.F)

    def get_info(self):
        print('mesh: {} nodes, {} elements'.format(len(self.nodes),
                                                   len(self.elements)))
        print('max temperature is {}'.format(np.max(self.temps)))
        print('min temperature is {}'.format(np.min(self.temps)))
        print('mean temperature is {}'.format(np.mean(self.temps)))

    def build_gradients(self):
        """
        Description
        -----------
        Builds gradients fields and view it
        """
        for elem in self.elements:
            for p in self.detail.source_points:
                if abs(p.x - elem.s1.x) < 0.0001 and abs(p.y -
                                                         elem.s1.y) < 0.0001:
                    elem.ps = True
                    break
                else:
                    elem.ps = False
            elem.grad = 1 / (2 * elem.A) * np.dot(
                np.array([[elem.b[0], elem.b[1], elem.b[2]],
                          [elem.c[0], elem.c[1], elem.c[2]]]),
                np.array([[self.temps[elem.s1.index]],
                          [self.temps[elem.s2.index]],
                          [self.temps[elem.s3.index]]]))
        w = 3
        X = np.array([(elem.s1.x + elem.s2.x + elem.s3.x) / 2
                      for elem in self.elements])
        Y = np.array([(elem.s1.y + elem.s2.y + elem.s3.y) / 2
                      for elem in self.elements])
        U = np.array([elem.grad[0][0] for elem in self.elements])
        V = np.array([elem.grad[1][0] for elem in self.elements])

        fig3, ax3 = plt.subplots()
        speed = np.sqrt(U**2 + V**2)
        Q = ax3.quiver(X, Y, U, V, speed, width=0.0008)
        ax3.quiverkey(Q,
                      0.9,
                      0.9,
                      2,
                      r'$2 \frac{m}{s}$',
                      labelpos='E',
                      coordinates='figure')
        ax3.scatter(X, Y, color='0.5', s=1.1)
        plt.gca().set_aspect('equal', adjustable='box')
        plt.show()

    def create_vtu(self, file):
        """
        Description
        -----------
        Forms vtu file for paraview vizualization
        """
        output = '<?xml version="1.0"?>\n<VTKFile type="UnstructuredGrid" version="0.1" >\n\t<UnstructuredGrid>'
        output += '\n\t\t<Piece NumberOfPoints="{}" NumberOfCells="{}">'.format(
            len(self.nodes), len(self.elements))
        components = ''
        for node in self.nodes:
            components += '{} {} 0 '.format(node.x, node.y)
        output += '\n\t\t<Points>\n\t\t\t<DataArray type="Float64" ' \
                  'NumberOfComponents="3" format="ascii">{}</DataArray>\n\t\t</Points>'.format(components)
        output += '\n\t\t<Cells>'
        connectivity = ''
        offsets = ''
        types = ''
        temps = ''

        for elem in self.elements:
            connectivity += '{} {} {} '.format(elem.s1.index, elem.s2.index,
                                               elem.s3.index)
        for i in range(len(self.elements)):
            offsets += '{} '.format((i + 1) * 3)
            types += '{} '.format(5)
        for t in self.temps:
            temps += '{} '.format(t)

        output += '\n\t\t\t<DataArray type="UInt32" Name="connectivity" format="ascii">{}</DataArray>'.format(
            connectivity)
        output += '\n\t\t\t<DataArray type="UInt32" Name="offsets" format="ascii">{}</DataArray>'.format(
            offsets)
        output += '\n\t\t\t<DataArray type="UInt8" Name="types" format="ascii">{}</DataArray>'.format(
            types)
        output += '\n\t\t</Cells>'
        output += '\n\t\t<PointData Scalars="T">\n\t\t\t<DataArray type="Float64" Name="T"' \
                  ' format="ascii">{}</DataArray>\n\t\t</PointData>'.format(temps)
        output += '\n\t\t</Piece>\n\t</UnstructuredGrid>\n</VTKFile>'

        f = open(file, "w+")
        f.write(output)
        f.close()