コード例 #1
0
    def test_assembly_inner_product_2_forms(self):
        """Test the assembly of 1-forms inner products."""
        func_space_lob = FunctionSpace(self.mesh, '2-lobatto', self.p)
        func_space_gauss = FunctionSpace(self.mesh, '2-gauss', self.p)
        func_space_extgauss = FunctionSpace(self.mesh, '2-ext_gauss', self.p)

        basis_lob = BasisForm(func_space_lob)
        basis_lob.quad_grid = 'gauss'
        M_lob = inner(basis_lob, basis_lob)

        basis_gauss = BasisForm(func_space_gauss)
        basis_gauss.quad_grid = 'lobatto'
        M_gauss = inner(basis_gauss, basis_gauss)

        basis_ext_gauss = BasisForm(func_space_extgauss)
        print(basis_ext_gauss.num_basis)
        basis_ext_gauss.quad_grid = 'lobatto'
        M_extgauss = inner(basis_ext_gauss, basis_ext_gauss)

        M_lob_ass_ref = assemble_slow(self.mesh, M_lob, func_space_lob.dof_map.dof_map,
                                      func_space_lob.dof_map.dof_map)
        M_gauss_ass_ref = assemble_slow(self.mesh, M_gauss, func_space_gauss.dof_map.dof_map,
                                        func_space_gauss.dof_map.dof_map)
        M_extgauss_ass_ref = assemble_slow(
            self.mesh, M_extgauss, func_space_extgauss.dof_map.dof_map_internal, func_space_extgauss.dof_map.dof_map_internal)

        M_lob_ass = assemble(M_lob, func_space_lob, func_space_lob).toarray()
        M_gauss_ass = assemble(M_gauss, func_space_gauss, func_space_gauss).toarray()
        M_extgauss_ass = assemble(M_extgauss, func_space_extgauss,
                                  func_space_extgauss).toarray()

        npt.assert_array_almost_equal(M_lob_ass_ref, M_lob_ass)
        npt.assert_array_almost_equal(M_gauss_ass_ref, M_gauss_ass)
        npt.assert_array_almost_equal(M_extgauss_ass_ref, M_extgauss_ass)
コード例 #2
0
ファイル: update_job.py プロジェクト: 61a-ide/cs61a-apps
def update():
    print("=================================================")
    roster_export.export()

    print("=================================================")
    okpy_export.export()

    gs_assignments = {}

    if not gscope:
        print("No Gradescope assignments found!", file=sys.stderr)

    for name, gs_code in gscope:
        print("=================================================")
        full_name = gs_export.export(name, gs_code)
        if full_name:
            gs_assignments[name] = full_name
        else:
            print(
                f"Gradescope export for '{name} ({gs_code})' failed.", file=sys.stderr
            )

    if sections:
        print("=================================================")
        sections_export.export()

    print("=================================================")
    adj = list(acadh[0]) if acadh else []
    assemble.assemble(
        gscope=gs_assignments, recovery=True, sections=sections, adjustments=adj
    )

    print("=================================================")
コード例 #3
0
ファイル: solving_utils.py プロジェクト: chromy/firedrake
 def __init__(self, problems):
     problems = as_tuple(problems)
     self._problems = problems
     # Build the jacobian with the correct sparsity pattern.  Note
     # that since matrix assembly is lazy this doesn't actually
     # force an additional assembly of the matrix since in
     # form_jacobian we call assemble again which drops this
     # computation on the floor.
     self._jacs = tuple(assemble.assemble(problem.J, bcs=problem.bcs,
                                          form_compiler_parameters=problem.form_compiler_parameters,
                                          nest=problem._nest)
                        for problem in problems)
     if problems[-1].Jp is not None:
         self._pjacs = tuple(assemble.assemble(problem.Jp, bcs=problem.bcs,
                                               form_compiler_parameters=problem.form_compiler_parameters,
                                               nest=problem._nest)
                             for problem in problems)
     else:
         self._pjacs = self._jacs
     # Function to hold current guess
     self._xs = tuple(function.Function(problem.u) for problem in problems)
     self.Fs = tuple(ufl.replace(problem.F, {problem.u: x}) for problem, x in zip(problems,
                                                                                  self._xs))
     self.Js = tuple(ufl.replace(problem.J, {problem.u: x}) for problem, x in zip(problems,
                                                                                  self._xs))
     if problems[-1].Jp is not None:
         self.Jps = tuple(ufl.replace(problem.Jp, {problem.u: x}) for problem, x in zip(problems,
                                                                                        self._xs))
     else:
         self.Jps = tuple(None for _ in problems)
     self._Fs = tuple(function.Function(F.arguments()[0].function_space())
                      for F in self.Fs)
     self._jacobians_assembled = [False for _ in problems]
コード例 #4
0
ファイル: solving_utils.py プロジェクト: chromy/firedrake
    def form_function(cls, snes, X, F):
        """Form the residual for this problem

        :arg snes: a PETSc SNES object
        :arg X: the current guess (a Vec)
        :arg F: the residual at X (a Vec)
        """
        dm = snes.getDM()
        ctx = dm.getAppCtx()
        _, lvl = utils.get_level(dm)

        # FIXME: Think about case where DM is refined but we don't
        # have a hierarchy of problems better.
        if len(ctx._problems) == 1:
            lvl = -1
        problem = ctx._problems[lvl]
        # X may not be the same vector as the vec behind self._x, so
        # copy guess in from X.
        with ctx._xs[lvl].dat.vec as v:
            if v != X:
                X.copy(v)

        assemble.assemble(ctx.Fs[lvl], tensor=ctx._Fs[lvl],
                          form_compiler_parameters=problem.form_compiler_parameters,
                          nest=problem._nest)
        for bc in problem.bcs:
            bc.zero(ctx._Fs[lvl])

        # F may not be the same vector as self._F, so copy
        # residual out to F.
        with ctx._Fs[lvl].dat.vec_ro as v:
            v.copy(F)
コード例 #5
0
def assemble_command(options, command_log):
    from assemble import assemble
    options['--bb'] = False
    options['--chrom-size'] = None
    options['--remove-rRNA'] = False
    options['--max-bundle-frags'] = None
    assemble(options, command=command_log, name='assemble')
コード例 #6
0
    def H(self, _0form, update_self_cochain=True):
        """
        #SUMMARY: Compute the Hodge Matrix H: self = H * _2form
        #OUTPUTS: [0] Assembled H
        """
        assert self.is_inner is not _0form.is_inner, " Hodge needs to connect two differently oriented forms"
        if _0form.__class__.__name__ == 'Gauss0form':
            W = _0form.wedged(self)
            H = np.tensordot(self.invM, W, axes=((2), (0)))
            H = np.rollaxis(H, 0, 3)
            H_a = assemble(H, self.dof_map, _0form.dof_map)
            if _0form.cochain is not None and update_self_cochain is True:
                self.cochain = H_a.dot(_0form.cochain)
                if _0form.func is not None:
                    self.func = _0form.func
            return H, H_a

        if _0form.__class__.__name__ == 'ExtGauss0form':
            W = _0form.wedged(self)
            H = np.tensordot(self.invM, W, axes=((2), (0)))
            H = np.rollaxis(H, 0, 3)
            H_a = assemble(H, self.dof_map, _0form.dof_map_internal)
            if _0form.cochain_internal is not None and update_self_cochain is True:
                self.cochain = H_a.dot(_0form.cochain_internal)
                if _0form.func is not None:
                    self.func = _0form.func
            return H, H_a
コード例 #7
0
    def test_multiple_elements(self):
        """Test the anysotropic case in multiple element."""
        p = (6, 6)
        is_inner = False
        crazy_mesh = CrazyMesh(2, (8, 5),  ((-1, 1), (-1, 1)), curvature=0.1)

        func_space_2_lobatto = FunctionSpace(crazy_mesh, '2-lobatto', p, is_inner)
        func_space_1_lobatto = FunctionSpace(crazy_mesh, '1-lobatto', p, is_inner)
        func_space_1_lobatto.dof_map.continous_dof = True

        def diffusion_11(x, y): return 4 * np.ones(np.shape(x))

        def diffusion_12(x, y): return 3 * np.ones(np.shape(x))

        def diffusion_22(x, y): return 5 * np.ones(np.shape(x))

        def source(x, y):
            return -36 * np.pi ** 2 * np.sin(2 * np.pi * x) * np.sin(2 * np.pi * y) + 24 * np.pi ** 2 * np.cos(2 * np.pi * x) * np.cos(2 * np.pi * y)

        # mesh function to inject the anisotropic tensor
        mesh_k = MeshFunction(crazy_mesh)
        mesh_k.continous_tensor = [diffusion_11, diffusion_12, diffusion_22]

        # definition of the basis functions
        basis_1 = BasisForm(func_space_1_lobatto)
        basis_1.quad_grid = 'gauss'
        basis_2 = BasisForm(func_space_2_lobatto)
        basis_2.quad_grid = 'gauss'

        # solution form
        phi_2 = Form(func_space_2_lobatto)
        phi_2.basis.quad_grid = 'gauss'

        form_source = Form(func_space_2_lobatto)
        form_source.discretize(source, ('gauss', 30))
        # find inner product
        M_1k = inner(basis_1, basis_1, mesh_k)
        N_2 = inner(d(basis_1), basis_2)
        M_2 = inner(basis_2, basis_2)
        # assemble
        M_1k = assemble(M_1k, func_space_1_lobatto)
        N_2 = assemble(N_2, (func_space_1_lobatto, func_space_2_lobatto))
        M_2 = assemble(M_2, func_space_2_lobatto)

        lhs = sparse.bmat([[M_1k, N_2], [N_2.transpose(), None]]).tocsc()
        rhs_source = (form_source.cochain @ M_2)[:, np.newaxis]
        rhs_zeros = np.zeros(lhs.shape[0] - np.size(rhs_source))[:, np.newaxis]
        rhs = np.vstack((rhs_zeros, rhs_source))

        solution = sparse.linalg.spsolve(lhs, rhs)
        phi_2.cochain = solution[-func_space_2_lobatto.num_dof:]

        # sample the solution
        xi = eta = np.linspace(-1, 1, 200)
        phi_2.reconstruct(xi, eta)
        (x, y), data = phi_2.export_to_plot()
        plt.contourf(x, y, data)
        plt.show()
        print("max value {0} \nmin value {1}" .format(np.max(data), np.min(data)))
        npt.assert_array_almost_equal(self.solution(x, y), data, decimal=2)
コード例 #8
0
def main():
    # parse command
    command_log = 'CIRCexplorer parameters: ' + ' '.join(sys.argv)
    if len(sys.argv) == 1:
        sys.exit(help_doc)
    elif sys.argv[1] == '--version' or sys.argv[1] == '-v':
        sys.exit(__version__)
    elif sys.argv[1] == 'align':
        import align
        align.align(docopt(align.__doc__, version=__version__),
                    command=command_log, name='align')
    elif sys.argv[1] == 'parse':
        import parse
        parse.parse(docopt(parse.__doc__, version=__version__),
                    command=command_log, name='parse')
    elif sys.argv[1] == 'annotate':
        import annotate
        annotate.annotate(docopt(annotate.__doc__, version=__version__),
                          command=command_log, name='annotate')
    elif sys.argv[1] == 'assemble':
        import assemble
        assemble.assemble(docopt(assemble.__doc__, version=__version__),
                          command=command_log, name='assemble')
    elif sys.argv[1] == 'denovo':
        import denovo
        denovo.denovo(docopt(denovo.__doc__, version=__version__),
                      command=command_log, name='denovo')
    else:
        sys.exit(help_doc)
コード例 #9
0
    def compile(self):
        self.ui.console.clear()
        infile = str(self.filename)
        out = os.path.splitext(infile)
        if out[1] != '.ys':
            self.showtext('Unable to compile %s' % infile)
            self.ui.console.setPlainText('Invalid file to compile')
            return
        outfile = out[0] + '.yo'
        infile = open(infile, 'r')
        outfile = open(outfile, 'w')
        assemble.assemble(infile, outfile)

        outfile.close()
        outfile = open(out[0]+'.yo', 'r')
        
        error = assemble.error
        if error != '':
            self.ui.console.setPlainText(error)
            self.ui.codeout.clear()
        else:
            self.ui.console.setPlainText('Compile success')
            self.ui.runButton.setEnabled(True)
            text = outfile.read()
            self.ui.codeout.setPlainText(text)
        
        return
コード例 #10
0
def main():
    # parse command
    command_log = 'CIRCexplorer parameters: ' + ' '.join(sys.argv)
    if len(sys.argv) == 1:
        sys.exit(help_doc)
    elif sys.argv[1] == '--version' or sys.argv[1] == '-v':
        sys.exit(__version__)
    elif sys.argv[1] == 'align':
        import align
        align.align(docopt(align.__doc__, version=__version__),
                    command=command_log,
                    name='align')
    elif sys.argv[1] == 'parse':
        import parse
        parse.parse(docopt(parse.__doc__, version=__version__),
                    command=command_log,
                    name='parse')
    elif sys.argv[1] == 'annotate':
        import annotate
        annotate.annotate(docopt(annotate.__doc__, version=__version__),
                          command=command_log,
                          name='annotate')
    elif sys.argv[1] == 'assemble':
        import assemble
        assemble.assemble(docopt(assemble.__doc__, version=__version__),
                          command=command_log,
                          name='assemble')
    elif sys.argv[1] == 'denovo':
        import denovo
        denovo.denovo(docopt(denovo.__doc__, version=__version__),
                      command=command_log,
                      name='denovo')
    else:
        sys.exit(help_doc)
コード例 #11
0
def multiple_element():
    mesh = CrazyMesh(2, (5, 7), ((-1, 1), (-1, 1)), curvature=0.3)
    p = 10, 10
    func_space_vort = FunctionSpace(mesh, '0-ext_gauss', (p[0] - 1, p[1] - 1), is_inner=False)
    func_space_outer_vel = FunctionSpace(
        mesh, '1-total_ext_gauss', (p[0], p[1]), is_inner=False)
    # func_space_outer_vel = FunctionSpace(
    #     mesh, '1-gauss', (p[0], p[1]), is_inner=False)
    func_space_inner_vel = FunctionSpace(mesh, '1-lobatto', p, is_inner=True)
    func_space_inner_vel.dof_map.continous_dof = True
    func_space_source = FunctionSpace(mesh, '2-lobatto', p, is_inner=True)

    basis_vort = BasisForm(func_space_vort)
    basis_vel_in = BasisForm(func_space_inner_vel)
    basis_vel_in.quad_grid = 'lobatto'
    basis_vel_out = BasisForm(func_space_outer_vel)
    basis_vel_out.quad_grid = 'lobatto'
    basis_2 = BasisForm(func_space_source)

    psi = Form(func_space_vort)
    u_in = Form(func_space_inner_vel)
    source = Form(func_space_source)
    source.discretize(ffun)

    M_1 = inner(basis_vel_in, basis_vel_in)
    E_21_in = d(func_space_inner_vel)
    W_02 = basis_2.wedged(basis_vort)
    W_02_E21 = np.transpose(W_02 @ E_21_in)

    M_1 = assemble(M_1, (func_space_inner_vel, func_space_inner_vel))
    print(np.shape(M_1))
    W_02_E21 = assemble(W_02_E21, (func_space_inner_vel, func_space_vort))
    print(np.shape(W_02_E21))
    W_02 = assemble(W_02, (func_space_source, func_space_vort))

    lhs = spr.bmat([[M_1, W_02_E21], [W_02_E21.transpose(), None]])
    print(np.shape(lhs))
    rhs = np.zeros(np.shape(lhs)[0])
    rhs[-func_space_source.num_dof:] = W_02 @ source.cochain

    solution = spr.linalg.spsolve(lhs.tocsc(), rhs)
    u_in.cochain = solution[:func_space_inner_vel.num_dof]
    cochian_psi = np.zeros(func_space_vort.num_dof)
    cochian_psi[:func_space_vort.num_internal_dof] = solution[-func_space_vort.num_internal_dof:]
    psi.cochain = cochian_psi

    xi = eta = np.linspace(-1, 1, 40)
    u_in.reconstruct(xi, eta)
    (x, y), u_x, u_y = u_in.export_to_plot()
    plt.contourf(x, y, u_x)
    plt.colorbar()
    plt.title("u_x inner")
    plt.show()
    psi.reconstruct(xi, eta)
    (x, y), psi_value = psi.export_to_plot()
    plt.contourf(x, y, psi_value)
    plt.title("psi outer"
              )
    plt.colorbar()
    plt.show()
コード例 #12
0
    def compile(self):
        self.ui.console.clear()
        infile = str(self.filename)
        out = os.path.splitext(infile)
        if out[1] != '.ys':
            self.showtext('Unable to compile %s' % infile)
            self.ui.console.setPlainText('Invalid file to compile')
            return
        outfile = out[0] + '.yo'
        infile = open(infile, 'r')
        outfile = open(outfile, 'w')
        assemble.assemble(infile, outfile)

        outfile.close()
        outfile = open(out[0] + '.yo', 'r')

        error = assemble.error
        if error != '':
            self.ui.console.setPlainText(error)
            self.ui.codeout.clear()
        else:
            self.ui.console.setPlainText('Compile success')
            self.ui.runButton.setEnabled(True)
            text = outfile.read()
            self.ui.codeout.setPlainText(text)

        return
コード例 #13
0
 def form_jacobian(self, snes, X_, J_, P_):
     if self._problem._constant_jacobian and self._jacobian_assembled:
         # Don't need to do any work with a constant jacobian
         # that's already assembled
         return
     self._jacobian_assembled = True
     # X_ may not be the same vector as the vec behind self._x, so
     # copy guess in from X_.
     with self._x.dat.vec as v:
         if v != X_:
             with v as _v, X_ as _x:
                 _v[:] = _x[:]
     assemble.assemble(self._problem.J_ufl,
                       tensor=self._jac_tensor,
                       bcs=self._problem.bcs,
                       form_compiler_parameters=self._problem.form_compiler_parameters)
     self._jac_tensor.M._force_evaluation()
     if self._problem.Jp is not None:
         assemble.assemble(self._problem.Jp,
                           tensor=self._jac_ptensor,
                           bcs=self._problem.bcs,
                           form_compiler_parameters=self._problem.form_compiler_parameters)
         self._jac_ptensor.M._force_evaluation()
         return PETSc.Mat.Structure.DIFFERENT_NONZERO_PATTERN
     return PETSc.Mat.Structure.SAME_NONZERO_PATTERN
コード例 #14
0
def assemble_command(options, command_log):
    from assemble import assemble
    options['--bb'] = False
    options['--tophat-dir'] = None
    options['--chrom-size'] = None
    options['--remove-rRNA'] = False
    options['--max-bundle-frags'] = None
    options['<circ_dir>'] = options['--output']
    assemble(options, command=command_log, name='assemble')
コード例 #15
0
    def test_assemble_incidence_matrices(self):
        p_dual = (self.p[0] - 1, self.p[1] - 1)
        func_space_lob_0 = FunctionSpace(self.mesh, '0-lobatto', self.p)
        func_space_extgauss_0 = FunctionSpace(self.mesh, '0-ext_gauss', p_dual)

        func_space_lob_1 = NextSpace(func_space_lob_0)
        func_space_extgauss_1 = FunctionSpace(self.mesh, '1-ext_gauss', p_dual)

        func_space_lob_2 = FunctionSpace(self.mesh, '2-lobatto', self.p)
        func_space_extgauss_2 = FunctionSpace(self.mesh, '2-ext_gauss', p_dual)

        e10_lob = d(func_space_lob_0)
        e21_lob = d(func_space_lob_1)
        e10_ext = d(func_space_extgauss_0)
        # e21_ext = d(func_space_extgauss_1)
        #
        e10_lob_assembled_ref = assemble_slow(
            self.mesh, e10_lob, func_space_lob_1.dof_map.dof_map, func_space_lob_0.dof_map.dof_map, mode='replace')

        e21_lob_assembled_ref = assemble_slow(
            self.mesh, e21_lob, func_space_lob_2.dof_map.dof_map,
            func_space_lob_1.dof_map.dof_map, mode='replace')

        e10_ext_assembled_ref = assemble_slow(
            self.mesh, e10_ext, func_space_extgauss_1.dof_map.dof_map,
            func_space_extgauss_0.dof_map.dof_map, mode='replace')

        # e21_ext_assembled_ref = assemble_slow(
        #     self.mesh, e21_ext, func_space_extgauss_2.dof_map.dof_map,
        #     func_space_extgauss_1.dof_map.dof_map, mode='replace')

        e10_lob_assembled = assemble(e10_lob, (func_space_lob_1, func_space_lob_0)).toarray()
        e21_lob_assembled = assemble(e21_lob, (func_space_lob_2, func_space_lob_1)).toarray()
        e10_ext_assembled = assemble(e10_ext, (func_space_extgauss_1,
                                               func_space_extgauss_0)).toarray()
        # e21_ext_assembled = assemble(e21_ext, func_space_extgauss_2,
        #                              func_space_extgauss_1).toarray()

        npt.assert_array_almost_equal(e10_lob_assembled_ref, e10_lob_assembled)
        npt.assert_array_almost_equal(e21_lob_assembled_ref, e21_lob_assembled)
        npt.assert_array_almost_equal(e10_ext_assembled_ref, e10_ext_assembled)
        # npt.assert_array_almost_equal(e21_ext_assembled_ref, e21_ext_assembled)

        e10_internal = d(func_space_extgauss_0)[:func_space_extgauss_1.num_internal_local_dof]

        e10_internal_assembled_ref = assemble_slow(
            self.mesh, e10_internal, func_space_extgauss_1.dof_map.dof_map_internal, func_space_extgauss_0.dof_map.dof_map)
        e10_internal_assembled = assemble(
            e10_internal, (func_space_extgauss_1, func_space_extgauss_0)).toarray()

        npt.assert_array_almost_equal(e10_internal_assembled_ref, e10_internal_assembled)
コード例 #16
0
def update():
    if not os.path.exists("data"):
        try:
            os.makedirs("data")
        except FileExistsError as e:
            print("Data folder exists, false alarm!")

    sections = "sp21" in get_endpoint(course="cs61a")

    with connect_db() as db:
        gscope: List[Tuple[str, str]] = db(
            "SELECT name, gs_code FROM gscope",
            [],
        ).fetchall()
        adjustments: List[Tuple[str, str]] = db(
            "SELECT url, sheet FROM adjustments",
            [],
        ).fetchall()

    print("=================================================")
    roster_export.export()

    print("=================================================")
    okpy_export.export()

    gs_assignments = {}

    if not gscope:
        print("No Gradescope assignments found!", file=sys.stderr)

    for name, gs_code in gscope:
        print("=================================================")
        full_name = gs_export.export(name, gs_code)
        if full_name:
            gs_assignments[name] = full_name
        else:
            print(f"Gradescope export for '{name} ({gs_code})' failed.",
                  file=sys.stderr)

    if sections:
        print("=================================================")
        sections_export.export()

    print("=================================================")
    assemble.assemble(gscope=gs_assignments,
                      recovery=True,
                      sections=sections,
                      adjustments=adjustments)

    print("=================================================")
コード例 #17
0
    def M(self, K=None):
        """
        #SUMMARY: Compute the Mass Matrix: M
        #OUTPUTS: [0] Local M
                  [1] Assembled Mass M
        """
        M = self.inner(self, K)

        # # extra lines to show local mass matrix
        # M_print = np.matrix(M)
        # print('\n\n===mass_local===\n\n', M_print)
        # plt.matshow(M_print)
        # plt.colorbar()
        # plt.clim(-1, 1)
        # plt.set_cmap('YlGnBu')
        #
        # # extra line to show global mass matrix
        # M_assemble = assemble(M, self.dof_map, self.dof_map).todense()
        # print('\n\n===mass_global===\n\n', M_assemble)
        # plt.matshow(M_assemble)
        # plt.colorbar()
        # plt.clim(-1, 1)
        # plt.set_cmap('YlGnBu')
        # plt.show()

        return M, assemble(M, self.dof_map, self.dof_map)
コード例 #18
0
ファイル: booth.py プロジェクト: antonmiakotin/snazzy
def run():
	camera.warmup(width, height)
	images = []
	for i in range(takes):			
		pic_paths = camera.take(1, width, height)
		start = time.time()
		image1 = util.process(pic_paths[0], assemble.get_height_each())
		end = time.time()
		diff = end - start
		images.append(image1)
		print "took in: " + str(diff) + "ms"
		if(diff < PAUSE_MAX and i < takes - 1):
			sleep_time = PAUSE_MAX - diff
			print "sleeping for another: " + str(sleep_time) + "ms"
			time.sleep(diff)

	assemble.assemble(images)
コード例 #19
0
ファイル: booth.py プロジェクト: skalpin/snazzy
def run():
    camera.warmup(width, height)
    images = []
    for i in range(takes):
        pic_paths = camera.take(1, width, height)
        start = time.time()
        image1 = util.process(pic_paths[0], assemble.get_height_each())
        end = time.time()
        diff = end - start
        images.append(image1)
        print "took in: " + str(diff) + "ms"
        if (diff < PAUSE_MAX and i < takes - 1):
            sleep_time = PAUSE_MAX - diff
            print "sleeping for another: " + str(sleep_time) + "ms"
            time.sleep(diff)

    assemble.assemble(images)
コード例 #20
0
ファイル: test-assemble.py プロジェクト: Toseter/mspgcc
 def testFormatII(self):
     for line, desired_iop, desired_cylces in formatIItests:
         iop, comment, cycles = assemble.assemble(line)
         # ~ print
         # ~ print iop, cycles
         # ~ print desired_iop, desired_cylces
         self.failUnless(desired_iop == iop, "%r failed, wrong iop" % line)
         self.failUnless(desired_cylces == cycles, "%r failed, wrong number of cycles" % line)
コード例 #21
0
    def form_function(self, snes, X_, F_):
        # X_ may not be the same vector as the vec behind self._x, so
        # copy guess in from X_.
        with self._x.dat.vec as v:
            if v != X_:
                with v as _v, X_ as _x:
                    _v[:] = _x[:]
        assemble.assemble(self._problem.F_ufl, tensor=self._F_tensor,
                          form_compiler_parameters=self._problem.form_compiler_parameters)
        for bc in self._problem.bcs:
            bc.zero(self._F_tensor)

        # F_ may not be the same vector as self._F_tensor, so copy
        # residual out to F_.
        with self._F_tensor.dat.vec_ro as v:
            if F_ != v:
                with v as _v, F_ as _f:
                    _f[:] = _v[:]
コード例 #22
0
def do_assemble(arch):
    r.recvuntil('( in base64 encoded format ): \n')
    code = r.recvuntil('Answer:')[:-7]
    print(code)

    code = assemble(code, arch)
    code = b64encode(code)
    print(code)
    r.sendline(code)
コード例 #23
0
ファイル: cl_compiler.py プロジェクト: petersn/cl
def source_to_bytecode(source, source_file_path="<sourceless>"):
    parser = ClParser()
    compiler = ClCompiler()
    ast = parser.parse(source)
    ast[0].pprint()
    bytecode_text = compiler.generate_overall_bytecode(ast)
    print "Bytecode text:"
    print bytecode_text
    assembly_unit = assemble.make_assembly_unit(bytecode_text)
    bytecode = assemble.assemble(assembly_unit, source_file_path)
    return bytecode
コード例 #24
0
    def M(self):
        """
        #SUMMARY: Compute the Mass Matrix: M
        #OUTPUTS: [0] Local M
                  [1] Assembled Mass M
        """
        if self._M is not None and self._M_a is not None:
            return self._M, self._M_a

        self._M = self.inner(self)
        self._M_a = assemble(self._M, self.dof_map, self.dof_map)
        return self._M, self._M_a
コード例 #25
0
ファイル: solving_utils.py プロジェクト: chromy/firedrake
    def form_jacobian(cls, snes, X, J, P):
        """Form the Jacobian for this problem

        :arg snes: a PETSc SNES object
        :arg X: the current guess (a Vec)
        :arg J: the Jacobian (a Mat)
        :arg P: the preconditioner matrix (a Mat)
        """
        dm = snes.getDM()
        ctx = dm.getAppCtx()
        _, lvl = utils.get_level(dm)

        # FIXME: Think about case where DM is refined but we don't
        # have a hierarchy of problems better.
        if len(ctx._problems) == 1:
            lvl = -1
        problem = ctx._problems[lvl]
        if problem._constant_jacobian and ctx._jacobians_assembled[lvl]:
            # Don't need to do any work with a constant jacobian
            # that's already assembled
            return
        ctx._jacobians_assembled[lvl] = True

        # X may not be the same vector as the vec behind self._x, so
        # copy guess in from X.
        with ctx._xs[lvl].dat.vec as v:
            X.copy(v)
        assemble.assemble(ctx.Js[lvl],
                          tensor=ctx._jacs[lvl],
                          bcs=problem.bcs,
                          form_compiler_parameters=problem.form_compiler_parameters,
                          nest=problem._nest)
        ctx._jacs[lvl].M._force_evaluation()
        if ctx.Jps[lvl] is not None:
            assemble.assemble(ctx.Jps[lvl],
                              tensor=ctx._pjacs[lvl],
                              bcs=problem.bcs,
                              form_compiler_parameters=problem.form_compiler_parameters,
                              nest=problem._nest)
            ctx._pjacs[lvl].M._force_evaluation()
コード例 #26
0
def run(config_path,
        train_dataset_path,
        val_dataset_path,
        output_path,
        raw_data_path):
    if not os.path.exists(output_path):
        os.makedirs(output_path)
    attempts = 0
    device = get_first_free_device()
    while attempts < 5 and device is None:
        print("All devices busy, retrying...", flush=True)
        time.sleep(60)
        device = get_first_free_device()
    print(f"Using device:{device}", flush=True)
    os.environ["CUDA_VISIBLE_DEVICES"] = device
    train_start = datetime.fromtimestamp(time.time()).isoformat()
    log_time(output_path, 'train_start', train_start)
    train(config_path, train_dataset_path, val_dataset_path, output_path)
    train_end = datetime.fromtimestamp(time.time()).isoformat()
    log_time(output_path, 'train_end', train_end)
    print(f'Finished training')
    tf.reset_default_graph()
    test(output_path, train_dataset_path)
    tf.reset_default_graph()
    eval_start = datetime.fromtimestamp(time.time()).isoformat()
    log_time(output_path, 'eval_start', eval_start)
    evaluate(output_path, raw_data_path, os.path.join(output_path, 'logits'))
    eval_end = datetime.fromtimestamp(time.time()).isoformat()
    log_time(output_path, 'eval_end', eval_end)
    print('Finished calculating logits')
    tf.reset_default_graph()
    assemble_start = datetime.fromtimestamp(time.time()).isoformat()
    log_time(output_path, 'assemble_start', assemble_start)
    assemble(os.path.join(output_path, 'logits'),
             os.path.join(output_path, 'fasta'),
             'beam_search',
             'simple')
    assemble_end = datetime.fromtimestamp(time.time()).isoformat()
    log_time(output_path, 'assemble_end', assemble_end)
    print('Finished assembly')
コード例 #27
0
ファイル: norms.py プロジェクト: chromy/firedrake
def norm(v, norm_type="L2", mesh=None):
    """Compute the norm of ``v``.

    :arg v: a :class:`.Function` to compute the norm of
    :arg norm_type: the type of norm to compute, see below for
         options.
    :arg mesh: an optional mesh on which to compute the norm
         (currently ignored).

    Available norm types are:

    * L2

       .. math::

          ||v||_{L^2}^2 = \int (v, v) \mathrm{d}x

    * H1

       .. math::

          ||v||_{H^1}^2 = \int (v, v) + (\\nabla v, \\nabla v) \mathrm{d}x

    * Hdiv

       .. math::

          ||v||_{H_\mathrm{div}}^2 = \int (v, v) + (\\nabla\cdot v, \\nabla \cdot v) \mathrm{d}x

    * Hcurl

       .. math::

          ||v||_{H_\mathrm{curl}}^2 = \int (v, v) + (\\nabla \wedge v, \\nabla \wedge v) \mathrm{d}x
    """
    assert isinstance(v, function.Function)

    typ = norm_type.lower()
    mesh = v.function_space().mesh()
    dx = mesh._dx
    if typ == 'l2':
        form = inner(v, v)*dx
    elif typ == 'h1':
        form = inner(v, v)*dx + inner(grad(v), grad(v))*dx
    elif typ == "hdiv":
        form = inner(v, v)*dx + div(v)*div(v)*dx
    elif typ == "hcurl":
        form = inner(v, v)*dx + inner(curl(v), curl(v))*dx
    else:
        raise RuntimeError("Unknown norm type '%s'" % norm_type)

    return sqrt(assemble.assemble(form))
コード例 #28
0
    def H(self, _1form, update_self_cochain=True):
        """
        #SUMMARY: Compute the Hodge Matrix H: self = H * _2form
        #OUTPUTS: [0] H
                  [1] Assembled H
        """
        assert self.is_inner is not _1form.is_inner, \
            "<FORM> <GL> : Hodge needs to connect two differently oriented forms"
        if _1form.__class__.__name__ in ('ExtGauss1form', ):
            W = _1form.wedged(self)
            H = np.tensordot(self.invM(), W, axes=(2, 0))
            H = np.rollaxis(H, 0, 3)
            if self.is_inner is True:
                H_a = -assemble(H, self.dof_map, _1form.dof_map_internal)
            else:
                H_a = assemble(H, self.dof_map, _1form.dof_map_internal)

            if _1form.cochain_internal is not None and update_self_cochain is True:
                self.cochain = H_a.dot(_1form.cochain_internal)
                if _1form.u is not None and _1form.v is not None:
                    self.func = (_1form.u, _1form.v)
            return H, H_a
コード例 #29
0
 def openFile(self):
     self.opentxt=QFileDialog.getOpenFileName(self,"Open file","/")  
     if self.opentxt != None and self.opentxt != '':
         try:
             self.loadAdd.setText(str(self.opentxt))
         except UnicodeEncodeError:
             self.showerror("invalid input file format")
         path = os.path.splitext(str(self.opentxt))
         try:
             prefix = path[0]
             suffix = path[1]
             if suffix not in ('.yo', '.ys', '.ybo'):
                 self.showerror("invalid input file format")
         except:
             self.showerror("invalid input file format")
         
         try:
             file=open(str(self.opentxt))
             if suffix == '.ys':
                 outputfilename = prefix+'.yo'
                 outputfile = open(outputfilename, 'w')
                 assemble.assemble(file,outputfile )
                 outputfile.close()
                 file = open(outputfilename, 'r')
                 if assemble.error != '':
                     raise Exception('Assemble Failure')
                 self.opentxt = outputfilename
                 
             self.displaytext=file.read()
             self.Code.setText(self.displaytext)
             file.close()
             
         except IOError:
             self.showerror("Cannot open file")
         except:
             self.assemblefailure(self.opentxt)
     return
コード例 #30
0
    def test_assemble_hodge(self):
        p_dual = (self.p[0] - 1, self.p[1] - 1)
        func_space_lob_0 = FunctionSpace(self.mesh, '0-lobatto', self.p)
        func_space_extgauss_0 = FunctionSpace(self.mesh, '0-ext_gauss', p_dual)

        func_space_lob_2 = FunctionSpace(self.mesh, '2-lobatto', self.p)
        func_space_extgauss_2 = FunctionSpace(self.mesh, '2-ext_gauss', p_dual)

        func_space_lob_1 = FunctionSpace(self.mesh, '1-lobatto', self.p)
        func_space_extgauss_1 = FunctionSpace(self.mesh, '1-ext_gauss', p_dual)

        hodge_20_ext = hodge(func_space_extgauss_0)

        hodge_11_lob = hodge(func_space_lob_1)

        hodge_02_lob = hodge(func_space_lob_2)

        hodge_assembled_ref = assemble_slow(
            self.mesh, hodge_20_ext, func_space_lob_2.dof_map.dof_map, func_space_extgauss_0.dof_map.dof_map_internal)
        hodge_assembled = assemble(
            hodge_20_ext, (func_space_lob_2, func_space_extgauss_0)).toarray()

        npt.assert_array_almost_equal(hodge_assembled_ref, hodge_assembled)

        hodge_assembled_ref = assemble_slow(
            self.mesh, hodge_11_lob, func_space_extgauss_1.dof_map.dof_map_internal, func_space_lob_1.dof_map.dof_map)
        hodge_assembled = assemble(
            hodge_11_lob, (func_space_extgauss_1, func_space_lob_1)).toarray()

        npt.assert_array_almost_equal(hodge_assembled_ref, hodge_assembled)
        hodge_assembled_ref = assemble_slow(
            self.mesh, hodge_02_lob, func_space_extgauss_0.dof_map.dof_map_internal, func_space_lob_2.dof_map.dof_map)
        hodge_assembled = assemble(
            hodge_02_lob, (func_space_extgauss_0, func_space_lob_2)).toarray()

        npt.assert_array_almost_equal(hodge_assembled_ref, hodge_assembled)
コード例 #31
0
def process(note):
    marked = time_parser.mark(note)
    date_time = time_parser.extract_parse_datetime(marked)
    context = time_parser.extract_context(marked)
    smart_note = assemble.assemble(context)
    emotion = sentiment.empathize(context)

    return {
        "context": context,
        "datetime": date_time,
        "sentiment": {
            "polarity": emotion.polarity,
            "confidence": emotion.subjectivity
        }
    }
コード例 #32
0
ファイル: interface.py プロジェクト: v-liuwei/LC-3-Assembler
 def assemble(self):
     input_text = self.inputbox.get(1.0, 'end')[:-1]
     if input_text:
         self.save()
         self.infobox.config(state=tk.NORMAL)
         self.outputbox.config(state=tk.NORMAL)
         self.outputbox.delete(1.0, 'end')
         self.infobox.delete(1.0, 'end')
         time.sleep(0.01)
         input_text = input_text.split('\n')
         success, assemble_info, results = assemble(input_text)
         assemble_info[0] = 'Assembling {}...'.format(self.filepath)
         self.infobox.insert('insert', '\n'.join(assemble_info))
         if success:
             self.outputbox.insert('insert', '\n'.join(results) + '\n')
             self.save_result()
         self.infobox.config(state=tk.DISABLED)
         self.outputbox.config(state=tk.DISABLED)
コード例 #33
0
    def coboundary(self):
        """
        #SUMMARY: Compute the E21
        # INPUTS:
        #   OPTIONAL:
        #OUTPUTS: [0] E21
                  [1] (OPTIONAL) E21_assembled
                  [2] (OPTIONAL) _2form
        """
        if self.is_inner is True:
            E21 = -self.E21
        else:
            E21 = self.E21

        _2form = Lobatto2form(self.mesh, self.p, is_inner=self.is_inner)
        E21_a = assemble(E21, _2form.dof_map, self.dof_map)
        if self._cochain is not None:
            _2form.cochain = E21_a.dot(self.cochain)
        return E21, E21_a, _2form
コード例 #34
0
num_local_ghost_nodes = func_space_0_ext_gauss.num_local_dof - \
    func_space_0_ext_gauss.num_internal_local_dof
num_total_ghost_nodes = px * elements_layout[0] * (
    elements_layout[1] + 1) + py * elements_layout[1] * (elements_layout[0] +
                                                         1)
num_local_element_edges = 2 * px * (px + 1)
num_total_edges = func_space_1_lobatto.num_dof
num_total_surfaces = func_space_2_lobatto.num_dof
num_local_surfaces = func_space_2_lobatto.num_local_dof

dof_map_ext_gauss_nodes = func_space_0_ext_gauss.dof_map.dof_map
dof_map_lobatto_edges_discontinous = func_space_1_lobatto.dof_map.dof_map
dof_map_lobatto_faces = dof_map_ext_gauss_nodes
"""Define 1-form mass matrix"""
M_1 = inner(basis_1, basis_1)
M1_assembled = assemble(M_1, (func_space_1_lobatto, func_space_1_lobatto))
"""Define wedge 1"""
E21 = d_21_lobatto_outer(p)
W1 = basis_2.wedged(basis_0)

W1_E21 = np.dot(W1, E21)
W1_E21_3D = np.repeat(W1_E21[:, :, np.newaxis], num_total_elements, axis=2)

W1_E21_assembled = assemble(W1_E21_3D,
                            (func_space_0_ext_gauss, func_space_1_lobatto))
"""Define Wedge 2"""
"""Define the second wedge / duality pairing / element connectivity matrix"""
virtual_E21 = d_21_lobatto_outer_virtual(p)
W2 = wedge_2()

W2_vE21 = np.dot(W2, virtual_E21)
コード例 #35
0
def solver(p, n, c):
    print("\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^")
    print("Start curl curl solver @ p=", p)
    print("                       @ n=", n)
    print("                       @ c=", c)
    px = py = p
    nx = n
    ny = n
    mesh = CrazyMesh(2, (nx, ny), ((-1, 1), (-1, 1)), c)
    xi = eta = np.linspace(-1, 1, np.ceil(500 / (nx * ny)) + 1)
    # %% exact p(0)
    func_space_gl0 = FunctionSpace(mesh,
                                   '0-lobatto', (px + 1, py + 1),
                                   is_inner=False)
    p0_exact = Form(func_space_gl0)
    p0_exact.discretize(pfun)
    p0_exact.reconstruct(xi, eta)
    (x, y), data = p0_exact.export_to_plot()
    plt.contourf(x, y, data)
    plt.title('exact lobatto 0-form, p0')
    plt.colorbar()
    plt.show()

    # %% p(0)
    func_space_gl0 = FunctionSpace(mesh,
                                   '0-lobatto', (px + 1, py + 1),
                                   is_inner=False)
    p0 = Form(func_space_gl0)

    # %%
    func_space_gl1 = FunctionSpace(mesh,
                                   '1-lobatto', (px + 1, py + 1),
                                   is_inner=False)
    uo = Form(func_space_gl1)

    # %%
    func_space_eg1 = FunctionSpace(mesh, '1-ext_gauss', (px, py))
    ui = Form(func_space_eg1)

    # %%
    func_space_eg2 = FunctionSpace(mesh, '2-ext_gauss', (px, py))
    f2 = Form(func_space_eg2)
    f2_exact = Form(func_space_eg2)
    f2_exact.discretize(ffun)
    #    f2_exact.reconstruct(xi, eta)
    #    (x, y), data = f2_exact.export_to_plot()
    #    plt.contourf(x, y, data)
    #    plt.title('exact extended-gauss 2-form, f2')
    #    plt.colorbar()
    #    plt.show()

    # %%
    E10 = d(func_space_gl0)
    #    E10_assembled = assemble(mesh, E10, uo.function_space.dof_map.dof_map,p0.function_space.dof_map.dof_map, mode='replace')
    E10_assembled = assemble(E10, (uo.function_space, p0.function_space))

    H = hodge(func_space_gl1)
    #    H_assembled   = assemble(mesh, H  , ui.function_space.dof_map.dof_map_internal, uo.function_space.dof_map.dof_map)
    H_assembled = assemble(H, (ui.function_space, uo.function_space))
    #H_assembled   = np.linalg.inv(H_assembled)

    E21 = d(func_space_eg1)
    #    E21_assembled = assemble(mesh, E21, f2.function_space.dof_map.dof_map, ui.function_space.dof_map.dof_map, mode = 'replace')
    E21_assembled = assemble(E21, (f2.function_space, ui.function_space))
    # %%
    #    uo.cochain = E10_assembled.dot(p0_exact.cochain)
    #    uo.reconstruct(xi, eta)
    #    (x, y), data_dx, data_dy = uo.export_to_plot()
    #    plt.contourf(x, y, data_dx)
    #    plt.title('exact lobatto 1-form dx')
    #    plt.colorbar()
    #    plt.show()
    #    print('uo_dx max:', np.max(data_dx))
    #    print('uo_dx min:', np.min(data_dx))
    #
    #    plt.contourf(x, y, data_dy)
    #    plt.title('exact lobatto 1-form dy')
    #    plt.colorbar()
    #    plt.show()
    #    print('uo_dy max:', np.max(data_dy))
    #    print('uo_dy min:', np.min(data_dy))
    #
    #    ui_internal_cochain = H_assembled.dot(uo.cochain)
    #    ui.cochain = np.concatenate((ui_internal_cochain, np.zeros(
    #        ui.function_space.num_dof - ui.basis.num_basis * ui.mesh.num_elements)), axis=0)
    #    ui.reconstruct(xi, eta)
    #    (x, y), data_dx, data_dy = ui.export_to_plot()
    #    plt.contourf(x, y, data_dx)
    #    plt.title('ext_gauss 1-form dx')
    #    plt.colorbar()
    #    plt.show()
    #    print('ui_dx max:', np.max(data_dx))
    #    print('ui_dy min:', np.min(data_dx))
    #
    #    plt.contourf(x, y, data_dy)
    #    plt.title('ext_gauss 1-form dy')
    #    plt.colorbar()
    #    plt.show()
    #    print('ui_dy max:', np.max(data_dy))
    #    print('ui_dy min:', np.min(data_dy))
    #    def UBC(mesh, s, p, position):
    #        def pullbackedfun_dx(xi, eta):
    #            x, y = mesh.mapping(xi, eta, s)
    #            return ui_dx(x, y)
    #
    #        def pullbackedfun_dy(xi, eta):
    #            x, y = mesh.mapping(xi, eta, s)
    #            return ui_dy(x, y)
    #
    #        def fun2bint_dxi(xi, eta):
    #            return pullbackedfun_dx(xi, eta) * mesh.dx_dxi(xi, eta, s)  + pullbackedfun_dy(xi, eta) * mesh.dy_dxi(xi, eta, s)
    #
    #        def fun2bint_deta(xi, eta):
    #            return pullbackedfun_dx(xi, eta) * mesh.dx_deta(xi, eta, s) + pullbackedfun_dy(xi, eta) * mesh.dy_deta(xi, eta, s)
    #
    #        UBC_s = np.zeros(shape = (p+1))
    #        extended_gauss_nodes, _ = extended_gauss_quad(p-1)
    #        if position == 'Left':
    #            for i in range(p+1):
    #    #            print("hello, Left world")
    #                def fun2bint_deta_BC(eta):
    #                    return fun2bint_deta(-1, eta)
    #                UBC_s[i] = quad(fun2bint_deta_BC, extended_gauss_nodes[i], extended_gauss_nodes[i+1] )[0]
    #        elif position == 'Right':
    #            for i in range(p+1):
    #    #            print("hello, Right world")
    #                def fun2bint_deta_BC(eta):
    #                    return fun2bint_deta(+1, eta)
    #                UBC_s[i] = quad(fun2bint_deta_BC, extended_gauss_nodes[i], extended_gauss_nodes[i+1] )[0]
    #        elif position == 'Bottom':
    #            for i in range(p+1):
    #    #            print("hello, Bottom world")
    #                def fun2bint_dxi_BC(xi):
    #                    return fun2bint_dxi(xi, -1)
    #                UBC_s[i] = quad(fun2bint_dxi_BC, extended_gauss_nodes[i], extended_gauss_nodes[i+1] )[0]
    #        elif position == 'Top':
    #            for i in range(p+1):
    #    #            print("hello, Top world")
    #                def fun2bint_dxi_BC(xi):
    #                    return fun2bint_dxi(xi, +1)
    #                UBC_s[i] = quad(fun2bint_dxi_BC, extended_gauss_nodes[i], extended_gauss_nodes[i+1] )[0]
    #        return UBC_s
    #
    #    def extended_gauss1_general_boundary_edges(mesh, p, gathering_matrix):
    #        p+=1
    #        nx = mesh.n_x
    #        ny = mesh.n_y
    #
    #        Left   = np.zeros( shape = (ny*(p+1)), dtype=np.int32 )
    #        Right  = np.zeros( shape = (ny*(p+1)), dtype=np.int32 )
    #        Bottom = np.zeros( shape = (nx*(p+1)), dtype=np.int32 )
    #        Top    = np.zeros( shape = (nx*(p+1)), dtype=np.int32 )
    #
    #        M = 2 * p * (p+1)
    #        N = p+1
    #
    #        UBC_L = UBC_R = UBC_B = UBC_T = 0
    #
    #        for J in range(ny):
    #            eleidLeft  = J
    #            Left[  J*N : J*N + N ] = gathering_matrix[ eleidLeft , M +2*N : M +3*N ]
    #            UBC_s=UBC(mesh, eleidLeft, p, "Left")
    #            if UBC_L is 0:
    #                UBC_L= UBC_s
    #            else:
    #                UBC_L = np.hstack((UBC_L, UBC_s))
    #
    #            eleidRight = (nx-1)*ny + J
    #            Right[ J*N : J*N + N ] = gathering_matrix[ eleidRight, M +3*N : M +4*N ]
    #            UBC_s=UBC(mesh, eleidRight, p, "Right")
    #            if UBC_R is 0:
    #                UBC_R= UBC_s
    #            else:
    #                UBC_R = np.hstack((UBC_R, UBC_s))
    #
    #        for I in range(nx):
    #            eleidBottom = I*ny
    #            Bottom[ I*N : I*N + N ] = gathering_matrix[ eleidBottom, M     : M +   N ]
    #            UBC_s=UBC(mesh, eleidBottom, p, "Bottom")
    #            if UBC_B is 0:
    #                UBC_B= UBC_s
    #            else:
    #                UBC_B = np.hstack((UBC_B, UBC_s))
    #
    #            eleidTop = I*ny + ny -1
    #            Top[ I*N : I*N + N ]    = gathering_matrix[ eleidTop   , M + N : M + 2*N ]
    #            UBC_s=UBC(mesh, eleidTop, p, "Top")
    #            if UBC_T is 0:
    #                UBC_T= UBC_s
    #            else:
    #                UBC_T = np.hstack((UBC_T, UBC_s))
    #
    #        return np.vstack((Left, UBC_L)), np.vstack((Right, UBC_R)), np.vstack((Bottom, UBC_B)), np.vstack((Top, UBC_T))
    #
    #    Left, Right, Bottom, Top = extended_gauss1_general_boundary_edges(mesh, px, ui.function_space.dof_map.dof_map)
    #    Boundaryedgs = np.hstack( (Left, Right, Bottom, Top) )
    #    for i in range(np.shape(Boundaryedgs)[1]):
    #        ui.cochain[int(Boundaryedgs[0, i])] =Boundaryedgs[1, i]
    #
    #    f2.cochain = E21_assembled.dot(ui.cochain)
    #    f2.reconstruct(xi, eta)
    #    (x, y), data = f2.export_to_plot()
    #    plt.contourf(x, y, data)
    #    plt.title('exact extended-gauss 2-form, f2')
    #    plt.colorbar()
    #    plt.show()
    # %%
    # system:
    #  |  I     -H       0  |   | ui |      | 0 |
    #  |                    |   |    |      |   |
    #  |  0      I     -E10 | * | uo |   =  | 0 |
    #  |                    |   |    |      |   |
    #  | E21     0       0  |   | p  |      | f |
    ui_num_dof_internal = ui.basis.num_basis * ui.mesh.num_elements
    ui_num_dof_external = ui.function_space.num_dof - ui_num_dof_internal

    #    LHS1 = np.hstack((   np.eye(ui_num_dof_internal) ,
    #                         np.zeros((ui_num_dof_internal, ui_num_dof_external)),
    #                        -H_assembled ,
    #                         np.zeros((ui_num_dof_internal, p0.function_space.num_dof))   ))
    LHS1 = sparse.hstack(
        (sparse.eye(ui_num_dof_internal),
         sparse.csc_matrix(
             (ui_num_dof_internal, ui_num_dof_external)), -H_assembled,
         sparse.csc_matrix((ui_num_dof_internal, p0.function_space.num_dof))))

    #    LHS2 = np.hstack((  np.zeros((uo.function_space.num_dof, ui.function_space.num_dof )) ,
    #                        np.eye(uo.function_space.num_dof) ,
    #                       -E10_assembled    ))
    LHS2 = sparse.hstack(
        (sparse.csc_matrix(
            (uo.function_space.num_dof, ui.function_space.num_dof)),
         sparse.eye(uo.function_space.num_dof), -E10_assembled))

    #    LHS3 = np.hstack((  E21_assembled ,
    #                        np.zeros((f2.function_space.num_dof, uo.function_space.num_dof )) ,
    #                        np.zeros((f2.function_space.num_dof, f2.function_space.num_dof ))    ))
    LHS3 = sparse.hstack(
        (E21_assembled,
         sparse.csc_matrix(
             (f2.function_space.num_dof, uo.function_space.num_dof)),
         sparse.csc_matrix(
             (f2.function_space.num_dof, f2.function_space.num_dof))))

    RHS1 = np.zeros((ui_num_dof_internal, 1))
    RHS2 = np.zeros((uo.function_space.num_dof, 1))
    RHS3 = f2_exact.cochain.reshape((f2_exact.function_space.num_dof, 1))

    # %% boundary edges
    #    def UBC(mesh, s, p, position):
    #        def pullbackedfun_dx(xi, eta):
    #            x, y = mesh.mapping(xi, eta, s)
    #            return ufun_u(x, y)
    #
    #        def pullbackedfun_dy(xi, eta):
    #            x, y = mesh.mapping(xi, eta, s)
    #            return ufun_v(x, y)
    #
    #        def fun2bint_dxi(xi, eta):
    #            return pullbackedfun_dx(xi, eta) * mesh.dx_dxi(xi, eta, s)  + pullbackedfun_dy(xi, eta) * mesh.dy_dxi(xi, eta, s)
    #
    #        def fun2bint_deta(xi, eta):
    #            return pullbackedfun_dx(xi, eta) * mesh.dx_deta(xi, eta, s) + pullbackedfun_dy(xi, eta) * mesh.dy_deta(xi, eta, s)
    #
    #        UBC_s = np.zeros(shape = (p+1))
    #        extended_gauss_nodes, _ = extended_gauss_quad(p-1)
    #        if position == 'Left':
    #            for i in range(p+1):
    #    #            print("hello, Left world")
    #                def fun2bint_deta_BC(eta):
    #                    return fun2bint_deta(-1, eta)
    #                UBC_s[i] = quad(fun2bint_deta_BC, extended_gauss_nodes[i], extended_gauss_nodes[i+1] )[0]
    #        elif position == 'Right':
    #            for i in range(p+1):
    #    #            print("hello, Right world")
    #                def fun2bint_deta_BC(eta):
    #                    return fun2bint_deta(+1, eta)
    #                UBC_s[i] = quad(fun2bint_deta_BC, extended_gauss_nodes[i], extended_gauss_nodes[i+1] )[0]
    #        elif position == 'Bottom':
    #            for i in range(p+1):
    #    #            print("hello, Bottom world")
    #                def fun2bint_dxi_BC(xi):
    #                    return fun2bint_dxi(xi, -1)
    #                UBC_s[i] = quad(fun2bint_dxi_BC, extended_gauss_nodes[i], extended_gauss_nodes[i+1] )[0]
    #        elif position == 'Top':
    #            for i in range(p+1):
    #    #            print("hello, Top world")
    #                def fun2bint_dxi_BC(xi):
    #                    return fun2bint_dxi(xi, +1)
    #                UBC_s[i] = quad(fun2bint_dxi_BC, extended_gauss_nodes[i], extended_gauss_nodes[i+1] )[0]
    #        return UBC_s
    #
    #    def extended_gauss1_general_boundary_edges(mesh, p, gathering_matrix):
    #        p+=1
    #        nx = mesh.n_x
    #        ny = mesh.n_y
    #
    #        Left   = np.zeros( shape = (ny*(p+1)), dtype=np.int32 )
    #        Right  = np.zeros( shape = (ny*(p+1)), dtype=np.int32 )
    #        Bottom = np.zeros( shape = (nx*(p+1)), dtype=np.int32 )
    #        Top    = np.zeros( shape = (nx*(p+1)), dtype=np.int32 )
    #
    #        M = 2 * p * (p+1)
    #        N = p+1
    #
    #        UBC_L = UBC_R = UBC_B = UBC_T = 0
    #
    #        for J in range(ny):
    #            eleidLeft  = J
    #            Left[  J*N : J*N + N ] = gathering_matrix[ eleidLeft , M +2*N : M +3*N ]
    #            UBC_s=UBC(mesh, eleidLeft, p, "Left")
    #            if UBC_L is 0:
    #                UBC_L= UBC_s
    #            else:
    #                UBC_L = np.hstack((UBC_L, UBC_s))
    #
    #            eleidRight = (nx-1)*ny + J
    #            Right[ J*N : J*N + N ] = gathering_matrix[ eleidRight, M +3*N : M +4*N ]
    #            UBC_s=UBC(mesh, eleidRight, p, "Right")
    #            if UBC_R is 0:
    #                UBC_R= UBC_s
    #            else:
    #                UBC_R = np.hstack((UBC_R, UBC_s))
    #
    #        for I in range(nx):
    #            eleidBottom = I*ny
    #            Bottom[ I*N : I*N + N ] = gathering_matrix[ eleidBottom, M     : M +   N ]
    #            UBC_s=UBC(mesh, eleidBottom, p, "Bottom")
    #            if UBC_B is 0:
    #                UBC_B= UBC_s
    #            else:
    #                UBC_B = np.hstack((UBC_B, UBC_s))
    #
    #            eleidTop = I*ny + ny -1
    #            Top[ I*N : I*N + N ]    = gathering_matrix[ eleidTop   , M + N : M + 2*N ]
    #            UBC_s=UBC(mesh, eleidTop, p, "Top")
    #            if UBC_T is 0:
    #                UBC_T= UBC_s
    #            else:
    #                UBC_T = np.hstack((UBC_T, UBC_s))
    #
    #        return np.vstack((Left, UBC_L)), np.vstack((Right, UBC_R)), np.vstack((Bottom, UBC_B)), np.vstack((Top, UBC_T))
    #
    #    Left, Right, Bottom, Top = extended_gauss1_general_boundary_edges(mesh, px, ui.function_space.dof_map.dof_map)
    #    Boundaryedgs = np.hstack( (Left, Right, Bottom, Top) )
    #
    ##    LBC = np.zeros( shape = ( np.shape(Boundaryedgs)[1], ui.function_space.num_dof+ uo.function_space.num_dof + p0.function_space.num_dof ) )
    #    LBC = sparse.lil_matrix( ( np.shape(Boundaryedgs)[1], ui.function_space.num_dof+ uo.function_space.num_dof + p0.function_space.num_dof ) )
    #
    #    RBC = np.zeros( shape = ( np.shape(Boundaryedgs)[1], 1) )
    #    for i in range(np.shape(Boundaryedgs)[1]):
    #        if i == 0 :
    #            LBC[0, ui.function_space.num_dof+ uo.function_space.num_dof] = 1
    #            RBC[0] = p0_exact.cochain[0]
    #        else:
    #            LBC[i, int(Boundaryedgs[0, i])] =1
    #            RBC[i] = Boundaryedgs[1, i]

    # %%
    def PBC(p, nx, ny, gathering_matrix, gathering_matrix_edge):
        p += 1

        Left = np.zeros(shape=(ny * (p + 1), 4), dtype=np.int32)
        Right = np.zeros(shape=(ny * (p + 1), 4), dtype=np.int32)
        Bottom = np.zeros(shape=(nx * (p + 1), 4), dtype=np.int32)
        Top = np.zeros(shape=(nx * (p + 1), 4), dtype=np.int32)

        N = p + 1
        P = 2 * p * (p + 1)
        Q = (p + 1)

        for J in range(ny):
            eleidLeft = J
            Left[J * N:J * N + N, 0] = gathering_matrix[eleidLeft, :N]
            if eleidLeft == 0:  # left-bottom corner element
                Left[0, 0] = -1  # left - bottom corner point
                Left[0, 1] = gathering_matrix_edge[0, P + 2 * Q]
                Left[0, 2] = gathering_matrix_edge[0, P]
            if eleidLeft == ny - 1:  # left-top corner element
                Left[-1, 0] = -3  # left _- top corner point
                Left[-1, 1] = gathering_matrix_edge[eleidLeft, P + Q]
                Left[-1, 2] = gathering_matrix_edge[eleidLeft, P + 3 * Q - 1]
            if eleidLeft >= 0 and eleidLeft < ny - 1:
                Left[J * N + N - 1, 0] = -2  # left
                Left[J * N + N - 1, 1] = gathering_matrix_edge[eleidLeft,
                                                               P + 3 * Q - 1]
                Left[J * N + N - 1, 2] = gathering_matrix_edge[eleidLeft,
                                                               P + Q]
                Left[J * N + N - 1, 3] = gathering_matrix_edge[eleidLeft + 1,
                                                               P + 2 * Q]

            eleidRight = (nx - 1) * ny + J
            Right[J * N:J * N + N, 0] = gathering_matrix[eleidRight, -N:]
            if eleidRight == nx * ny - ny:  # right bottom element
                Right[0, 0] = -4
                Right[0, 1] = gathering_matrix_edge[eleidRight, P + Q - 1]
                Right[0, 2] = gathering_matrix_edge[eleidRight, P + 3 * Q]
            if eleidRight == nx * ny - 1:  # right top element
                Right[-1, 0] = -5
                Right[-1, 1] = gathering_matrix_edge[eleidRight, P + 2 * Q - 1]
                Right[-1, 2] = gathering_matrix_edge[eleidRight, -1]
            if eleidRight >= nx * ny - ny and eleidRight < nx * ny - 1:  # right elements
                Right[J * N + N - 1, 0] = -6
                Right[J * N + N - 1, 1] = gathering_matrix_edge[eleidRight, -1]
                Right[J * N + N - 1, 2] = gathering_matrix_edge[eleidRight,
                                                                P + 2 * Q - 1]
                Right[J * N + N - 1, 3] = gathering_matrix_edge[eleidRight + 1,
                                                                P + 3 * Q]

        for I in range(nx):
            eleidBottom = I * ny
            Bottom[I * N:I * N + N, 0] = gathering_matrix[eleidBottom,
                                                          0:N**2:N]
            if eleidBottom >= 0 and eleidBottom < nx * ny - ny:  # bottom elements
                Bottom[I * N + N - 1, 0] = -7
                Bottom[I * N + N - 1, 1] = gathering_matrix_edge[eleidBottom,
                                                                 P + Q - 1]
                Bottom[I * N + N - 1, 2] = gathering_matrix_edge[eleidBottom,
                                                                 P + 3 * Q]
                Bottom[I * N + N - 1,
                       3] = gathering_matrix_edge[eleidBottom + ny, P]

            eleidTop = I * ny + ny - 1
            Top[I * N:I * N + N, 0] = gathering_matrix[eleidTop, N - 1:N**2:N]

            if eleidTop >= 0 and eleidTop < nx * ny - 1:  # bottom elements
                Top[I * N + N - 1, 0] = -8
                Top[I * N + N - 1, 1] = gathering_matrix_edge[eleidTop,
                                                              P + 2 * Q - 1]
                Top[I * N + N - 1, 2] = gathering_matrix_edge[eleidTop, -1]
                Top[I * N + N - 1, 3] = gathering_matrix_edge[eleidTop + ny,
                                                              P + Q]

        return Left, Right, Bottom, Top

    Left, Right, Bottom, Top = PBC(p, nx, ny,
                                   p0_exact.function_space.dof_map.dof_map,
                                   ui.function_space.dof_map.dof_map)

    Boundarypoints = np.vstack((Left, Right, Bottom, Top))

    LBC = sparse.lil_matrix(
        (np.shape(Boundarypoints)[0], ui.function_space.num_dof +
         uo.function_space.num_dof + p0.function_space.num_dof))
    RBC = np.zeros(shape=(np.shape(Boundarypoints)[0], 1))
    for i in range(np.shape(Boundarypoints)[0]):
        if Boundarypoints[i, 0] == -1:
            LBC[i, Boundarypoints[i, 1]] = +1
            LBC[i, Boundarypoints[i, 2]] = +1
            RBC[i] = 0
        elif Boundarypoints[i, 0] == -2:
            LBC[i, Boundarypoints[i, 1]] = -2
            LBC[i, Boundarypoints[i, 2]] = +1
            LBC[i, Boundarypoints[i, 3]] = +1
            RBC[i] = 0
        elif Boundarypoints[i, 0] == -3:
            LBC[i, Boundarypoints[i, 1]] = +1
            LBC[i, Boundarypoints[i, 2]] = -1
            RBC[i] = 0
        elif Boundarypoints[i, 0] == -4:
            LBC[i, Boundarypoints[i, 1]] = +1
            LBC[i, Boundarypoints[i, 2]] = -1
            RBC[i] = 0
        elif Boundarypoints[i, 0] == -5:
            LBC[i, Boundarypoints[i, 1]] = +1
            LBC[i, Boundarypoints[i, 2]] = +1
            RBC[i] = 0
        elif Boundarypoints[i, 0] == -6:
            LBC[i, Boundarypoints[i, 1]] = +1
            LBC[i, Boundarypoints[i, 2]] = +1
            LBC[i, Boundarypoints[i, 3]] = -2
            RBC[i] = 0
        elif Boundarypoints[i, 0] == -7:
            LBC[i, Boundarypoints[i, 1]] = -2
            LBC[i, Boundarypoints[i, 2]] = +1
            LBC[i, Boundarypoints[i, 3]] = +1
            RBC[i] = 0
        elif Boundarypoints[i, 0] == -8:
            LBC[i, Boundarypoints[i, 1]] = +1
            LBC[i, Boundarypoints[i, 2]] = +1
            LBC[i, Boundarypoints[i, 3]] = -2
            RBC[i] = 0
        else:
            LBC[i, ui.function_space.num_dof + uo.function_space.num_dof +
                int(Boundarypoints[i, 0])] = 1
            RBC[i] = p0_exact.cochain[Boundarypoints[i, 0]]

    # %%
    def dof_map_crazy_lobatto_point_pair(mesh, p, global_numbering,
                                         global_numbering_edges):
        nx, ny = mesh.n_x, mesh.n_y

        N = p + 1

        interface_point_pair = np.zeros(
            (((nx - 1) * ny + nx * (ny - 1)) * N, 4), dtype=np.int32)

        n = 0

        P = 2 * p * (p + 1)
        Q = (p + 1)

        for i in range(nx - 1):
            for j in range(ny):
                s1 = j + i * ny
                s2 = j + (i + 1) * ny
                #            print(s1, s2)
                for m in range(N):
                    interface_point_pair[n, 0] = global_numbering[s1,
                                                                  N * p + m]
                    interface_point_pair[n, 1] = global_numbering[s2, m]

                    if j < ny - 1 and m == N - 1:
                        s3 = s2 + 1
                        interface_point_pair[n,
                                             0] = global_numbering_edges[s1,
                                                                         P +
                                                                         2 *
                                                                         Q - 1]
                        interface_point_pair[n, 1] = global_numbering_edges[s1,
                                                                            -1]
                        interface_point_pair[n,
                                             2] = global_numbering_edges[s2,
                                                                         P + Q]
                        interface_point_pair[n,
                                             3] = global_numbering_edges[s3,
                                                                         P +
                                                                         2 * Q]
                    n += 1
        for i in range(nx):
            for j in range(ny - 1):
                s1 = j + i * ny
                s2 = j + 1 + i * ny
                #            print(s1, s2)
                for m in range(N):
                    interface_point_pair[n,
                                         0] = global_numbering[s1,
                                                               (m + 1) * N - 1]
                    interface_point_pair[n, 1] = global_numbering[s2, m * N]
                    n += 1
        return interface_point_pair

    interface_point_pair = dof_map_crazy_lobatto_point_pair(
        mesh, px + 1, p0.function_space.dof_map.dof_map,
        ui.function_space.dof_map.dof_map)
    #    Lintface = np.zeros( shape = ( np.shape( interface_point_pair )[0], ui.function_space.num_dof+ uo.function_space.num_dof + p0.function_space.num_dof ) )
    Lintface = sparse.lil_matrix(
        (np.shape(interface_point_pair)[0], ui.function_space.num_dof +
         uo.function_space.num_dof + p0.function_space.num_dof))
    #Rintface = np.zeros( shape = ( np.shape( interface_point_pair )[0]-(nx-1)*(ny-1), 1) )
    Rintface = np.zeros(shape=(np.shape(interface_point_pair)[0], 1))
    for i in range(np.shape(interface_point_pair)[0]):
        if interface_point_pair[i, 2] != 0 and interface_point_pair[i, 3] != 0:
            Lintface[i, interface_point_pair[i, 0]] = 1
            Lintface[i, interface_point_pair[i, 1]] = 1
            Lintface[i, interface_point_pair[i, 2]] = -1
            Lintface[i, interface_point_pair[i, 3]] = -1
        else:
            Lintface[i, ui.function_space.num_dof + uo.function_space.num_dof +
                     interface_point_pair[i, 0]] = 1
            Lintface[i, ui.function_space.num_dof + uo.function_space.num_dof +
                     interface_point_pair[i, 1]] = -1

#    Lintface = sparse.csr_matrix(Lintface)
# %%
#Lintface=Lintface[~np.all(Lintface == 0, axis=1)]

    LHS = sparse.vstack((LHS1, LHS2, LHS3, Lintface, LBC))
    RHS = np.vstack((RHS1, RHS2, RHS3, Rintface, RBC))
    #rrefLHS = np.array(Matrix(LHS).rref()[0]).astype(None)
    #print(rrefLHS)
    print("----------------------------------------------------")
    print("LHS shape:", np.shape(LHS))

    print("------ solve the square sparse system:......")
    LHS = sparse.csr_matrix(LHS)
    Res = sparse.linalg.spsolve(LHS, RHS)
    #
    #    print("------ solve the singular square sparse system:......")
    #    solution = sparse.linalg.lsqr(LHS,RHS, atol=1e-20, btol=1e-20)
    #    Res = solution[0].reshape((np.size(solution[0]),1))
    #    residual = np.sum(np.abs(LHS.dot(Res) - RHS))
    #    print("------ least square solution error =",residual)

    #    print("++++++ solve the singular square full system:......")
    #    solution= np.linalg.lstsq(LHS,RHS)

    # %% eigen values and eigen vector
    #    w, v = sp.linalg.eig(LHS.todense())

    # %%
    ui.cochain = Res[0:ui.function_space.num_dof].reshape(
        ui.function_space.num_dof)
    uo.cochain = Res[ui.function_space.
                     num_dof:-p0.function_space.num_dof].reshape(
                         uo.function_space.num_dof)
    p0.cochain = Res[-p0.function_space.num_dof:].reshape(
        p0.function_space.num_dof)

    # %% view the result
    p0.reconstruct(xi, eta)
    (x, y), data = p0.export_to_plot()
    plt.contourf(x, y, data)
    plt.title('solution lobatto 0-form, p0')
    plt.colorbar()
    plt.show()
    print('p0 max:', np.max(data))
    print('p0 min:', np.min(data))

    uo.reconstruct(xi, eta)
    (x, y), data_dx, data_dy = uo.export_to_plot()
    plt.contourf(x, y, data_dx)
    plt.title('solution lobatto 1-form dx')
    plt.colorbar()
    plt.show()
    print('uo max:', np.max(data_dx))
    print('uo min:', np.min(data_dx))

    plt.contourf(x, y, data_dy)
    plt.title('solution lobatto 1-form dy')
    plt.colorbar()
    plt.show()
    print('uo max:', np.max(data_dy))
    print('uo min:', np.min(data_dy))
    #    #
    ui.reconstruct(xi, eta)
    (x, y), data_dx, data_dy = ui.export_to_plot()
    plt.contourf(x, y, data_dx)
    plt.title('solution extended_gauss 1-form dx')
    plt.colorbar()
    plt.show()
    print('ui max:', np.max(data_dx))
    print('ui min:', np.min(data_dx))

    plt.contourf(x, y, data_dy)
    plt.title('solution extended_gauss 1-form dy')
    plt.colorbar()
    plt.show()
    print('ui max:', np.max(data_dy))
    print('ui min:', np.min(data_dy))

    f2_exact.reconstruct(xi, eta)
    (x, y), data = f2_exact.export_to_plot()
    plt.contourf(x, y, data)
    plt.title('exact extended-gauss 2-form, f2')
    plt.colorbar()
    plt.show()

    # %% error
    L2_error_p0 = p0.l_2_norm(pfun, ('gauss', 10))[0]
    print("------ L2_error_psi0 =", L2_error_p0)

    L2_error_ui = ui.l_2_norm((ui_dx, ui_dy), ('gauss', 5))[0]
    print("------ L2_error_ui =", L2_error_ui)
    print("vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv\n")
    # %% return
    return L2_error_p0, L2_error_ui
コード例 #36
0
ファイル: main.py プロジェクト: aneeshdash/ALL
import re,assemble,link,loader,machine
files=[]
print 'Enter file names(in descending order of execution):'
while True:
	print 'File Name:',
	fname=raw_input()
	if fname is '':
		break;
	files.append(fname)
print 'Enter Offset:',
offset=int(raw_input())
main=files[-1].split('.')[0]+'.asm'
symbols=assemble.assemble(files)
link.linker(main, symbols)
loader.loader(main, offset)
machine.machine(main)
print 'Symbol Table:'
for key in symbols:
	print 'File: '+key
	print symbols[key]
コード例 #37
0
    assembly_headers = [x.splitlines()[0] for x in assemblies]
    new_assembly_parts = [f'.MIXED_{assembly_headers[0][1:]}']

    for header in assembly_headers:
        new_assembly_parts.append(f'jmp {header[1:]}')
    for body in assemblies:
        new_assembly_parts.append(body)

    return '\n'.join(new_assembly_parts)


if __name__ == '__main__':

    if len(sys.argv) != 3:
        print("Incorrect number of arguments")
        print(f"usage:   {sys.argv[0]} <input_file> <structure_name>")
        print(f"example: {sys.argv[0]} example.cbc example_structure")
        exit(1)

    input_file_name = sys.argv[1]
    output_file_name = sys.argv[2]

    lexer = lex.lex()
    parser = yacc.yacc(debug=1)

    print(f"compiling {input_file_name}")
    assembly_file = compile_cbc(input_file_name)
    Path(input_file_name.rsplit('.', maxsplit=1)[0] +
         '.cba').write_text(assembly_file)
    assemble.assemble(assembly_file, output_file_name).write_file()
コード例 #38
0
ファイル: kunkel_full.py プロジェクト: dacarlin/kunkel-app
def kunkel_full(protocol, params):
    growth_media = params["construct_setup"]['growth_media']
    num_colonies = params["construct_setup"]['num_colonies']
    ssDNA = params["construct_setup"]['ssDNA']
    mutant_constructs = []

    # make mutant objects for accessibility
    construct_collect = {}
    for csv_row in params["construct_setup"]['mutant_upload']:
        if csv_row["mutant_label"] not in construct_collect.keys():
            construct_collect[csv_row["mutant_label"]] = []
            construct_collect[csv_row["mutant_label"]].append(
                {
                "sequence": csv_row["sequence"],
                "purification": csv_row["purification"],
                "scale": csv_row["scale"],
                "oligo_label": csv_row["oligo_label"]

            })
        else:
            construct_collect[csv_row["mutant_label"]].append(
                {
                "sequence": csv_row["sequence"],
                "purification": csv_row["purification"],
                "scale": csv_row["scale"],
                "oligo_label": csv_row["oligo_label"]

            }
                )

    oligo_collect = {}
    for row in params["construct_setup"]["mutant_upload"]:
        if (row["sequence"] not in oligo_collect.keys() and row["oligo_label"] in protocol.refs.keys()):
            raise RuntimeError("You cannot specify two different "
                   "oligos to be synthesized with the "
                   "same name %s" % row['oligo_label'])
        elif row["sequence"] not in oligo_collect.keys():
            oligo_collect[row["sequence"]] = {
                "sequence": row["sequence"],
                "purification": row["purification"],
                "scale": row["scale"],
                "destination": protocol.ref(row["oligo_label"], None, "micro-2.0", storage="cold_4").well(0)
            }


    for mut in construct_collect.keys():
        mut_oligos = [o for o in construct_collect[mut]]
        mutant = Mutant(mut)
        for oligo in mut_oligos:
            mutant.add_oligos(oligo_collect[oligo["sequence"]]["destination"])
        mutant_constructs.append(mutant)


    oligos_to_synthesize = []
    for o in oligo_collect.keys():
        scale_default(len(oligo_collect[o]["sequence"]), oligo_collect[o]["scale"], oligo_collect[o]["destination"].container.name)
        oligos_to_synthesize.append(oligo_collect[o])
    protocol.oligosynthesize(oligos_to_synthesize)

    assemble_params = {
        'ssDNA': ssDNA,
        'constructs': [{
            'mutant_name': mu.name,
            'oligos': mu.oligos} for mu in mutant_constructs],
        'mutant_objs': mutant_constructs

    }

    annealing_plate = assemble(protocol, assemble_params)
    protocol.unseal(annealing_plate)

    transform_params = {
        'num_colonies': num_colonies,
        'growth_media': growth_media,
        'constructs': [mu.anneal_well for mu in mutant_constructs],
        'mutant_objs': mutant_constructs

    }

    growth_plate = transform(protocol, transform_params)

    seq_primers = []

    for seq_primer in params["sequencing"]:
        if seq_primer["seq_choice"] != "No sequencing.":
        # make temp container with name of stock primer
            primer = protocol.ref(seq_primer["seq_choice"], None, "micro-1.5",
                                  discard=True).well(0)
            primer.set_name(seq_primer["seq_choice"])
            primer_vol = "1:microliter"
            seq_primers.append(primer)

    sequence_params = {
        'seq_set': [{
            'growth_wells': WellGroup([w for w in mu.growth_wells]),
            'seq_primers': seq_primers} for mu in mutant_constructs]

    }
    if seq_primers:
        protocol.uncover(growth_plate)
        sequence(protocol, sequence_params)
        protocol.cover(growth_plate, lid="low_evaporation")

    if params["other_processing"]["other_processing"] != "No processing.":
        protocol.uncover(growth_plate)
        if params["other_processing"]["other_processing"] == "Miniprep":
            mini_samples = []
            for mu in mutant_constructs:
                for w in mu.growth_wells:
                    mini_samples.append({"sample": w, "name": w.name})

            miniprep_params = {
                        "type": "Miniprep",
                        "media": growth_media,
                        'samples': mini_samples,
                        "growth_plate": growth_plate
                        }

            plasmidprep(protocol, miniprep_params)

        if params["other_processing"]["other_processing"] == "Return Colonies":
            return_plate = protocol.ref("return_plate_%s" % printdatetime(time=False), cont_type='96-pcr', storage='cold_4')
            for mut in  mutant_constructs:
                for g_well in mut.growth_wells:
                    protocol.transfer(g_well, return_plate.well(g_well.index), "30:microliter")
                    return_plate.well(g_well.index).set_name(g_well.name)

            protocol.seal(return_plate)
            protocol.cover(growth_plate, lid="low_evaporation")

        if params["other_processing"]["other_processing"] == "Return Colonies Glycerol":
            return_plate = protocol.ref("return_plate_glycerol_%s" % printdatetime(time=False), cont_type='96-pcr', storage='cold_4')
            for mut in  mutant_constructs:
                for g_well in mut.growth_wells:
                    protocol.transfer(g_well, return_plate.well(g_well.index), "30:microliter")
                    return_plate.well(g_well.index).set_name(g_well.name)
            for mut in  mutant_constructs:
                for g_well in mut.growth_wells:
                    protocol.provision("rs17rrhqpsxyh2", return_plate.well(g_well.index), "30:microliter")

            protocol.seal(return_plate)
            protocol.cover(growth_plate, lid="low_evaporation")
コード例 #39
0
for j in range(px):
    vol_id = px**2 + j
    edge_id = px * (px + 1) + j
    virtual_E21[vol_id - px**2, edge_id] = 1
    virtual_E21[vol_id - px**2 + px, edge_id + px**2] = -1

for i in range(px):
    vol_id = px**2 + 2 * px + i
    edge_id = (px + 1) * i
    virtual_E21[vol_id - px**2, edge_id] = 1
    virtual_E21[vol_id - px**2 + px, edge_id + px] = -1

# define the mass and wedge matrices

M_1 = inner(basis_1, basis_1)
M1_assembled = assemble(M_1, (func_space_1_lobatto, func_space_1_lobatto))

W_i_2 = basis_2.wedged(basis_0)
Wi_2_E_21 = np.dot(W_i_2, E21)

lhs = sparse.bmat(
    [[M1_assembled,
      Wi_2_E_21.transpose(),
      virtual_E21.transpose()], [Wi_2_E_21, None, None],
     [virtual_E21, None, None]]).tolil()

rhs_1 = np.zeros(2 * px * (px + 1))
rhs_2 = np.dot(W_i_2, source_form.cochain)
rhs_3 = np.zeros(4 * px)
rhs = np.hstack((rhs_1, rhs_2, rhs_3))
コード例 #40
0
#                          p0.function_space.dof_map.dof_map_internal,mode='add')
#
#Mn           = inner   (    f2.basis,          f2.basis)
#Mn_assembled = assemble(Mn, f2.function_space, f2.function_space)
#
#M0           = inner   (    p0.basis         , p0.basis)
#M0_assembled = assemble(M0, p0.function_space, p0.function_space)
#
#H11           = hodge    (func_space_gl1)
#H11_assembled = -assemble(H11, ui.function_space,uo.function_space)

#ui_num_dof_internal = ui.basis.num_basis * ui.mesh.num_elements
p0_num_dof_internal = p0.basis.num_basis * ui.mesh.num_elements
# %% LHS 11
Mnm1 = inner(uo.basis, uo.basis)
Mnm1_assembled = assemble(Mnm1, uo.function_space, uo.function_space)

# %% LHS 21
W0n = f2.basis.wedged(p0.basis)
W0n_assembled = assemble_(mesh,
                          W0n,
                          p0.function_space.dof_map.dof_map_internal,
                          f2.function_space.dof_map.dof_map,
                          mode='add')
E21 = d(func_space_gl1)

#E21_assembled = assemble_(mesh, E21, f2.function_space.dof_map.dof_map,
#                          uo.function_space.dof_map.dof_map, mode='replace')

LHS21_local = W0n.dot(E21)
LHS12_local = LHS21_local.T
コード例 #41
0
ファイル: run.py プロジェクト: balajipandian/taco
 def assemble(self):
     kwargs = vars(self.args)
     kwargs.update(vars(self.results))
     assemble(**kwargs)
コード例 #42
0
ファイル: tests.py プロジェクト: Bletchley13/ssexy
def test(debug):
	global count
	_stack = cdll.msvcrt.malloc(4 * 4)
	stack = _stack + 4 * 4
	code = windll.kernel32.VirtualAlloc(None, 0x1000, \
	        MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE)
	for test in ut:
		test['asm'] = [] ; enc.Enc(None).reset_labels()
		test['lines'] = [
			'jmp m128_init0_end',
			'align 16, db 0',
			'm128_init0: dd 0x11111111, 0x22222222, 0x33333333, 0x44444444',
			'm128_init0_end:',
			'jmp m128_init1_end',
			'align 16, db 0',
			'm128_init1: dd 0x%08x, 0x66666666, 0x77777777, 0x88888888' \
			        % stack, 'm128_init1_end:',
			'movapd xmm6, dqword [m128_init0]',
			'movapd xmm7, dqword [m128_init1]']
		for dis in DecomposeGenerator(0, test['hex'].decode('hex'), \
		        Decode32Bits):
			test['lines'] += enc.Enc(dis).encode()
			test['asm'].append(str(dis))
		test['code'] = assemble.assemble(test['lines'], 'testing/' + str(count))
		
		sys.stderr.write('Processing %s -> %s (%d)\r' % \
		        (test['hex'], ' ; '.join(test['asm']), count))
		output = list(struct.unpack('L' * 36, \
		        assemble.Debuggable(test['code'], _stack, code).run()))
		# adjust the `esp' register to remain correctly.. :)
		if (output[28] >> 16) == (stack >> 16):
		    output[28] = 0xb00b0ffc - stack + output[28]
		if test['type'] in ['reg', 'mem'] and test['regs'] != \
		        tuple(output[24:32]):
			print '%s -> %s gave register problems (%d)!' % \
			        (test['hex'], ' ; '.join(test['asm']), count)
			print 'Generated SSE Assembly:\n' + '\n'.join(test['lines']) + '\n'
			# print all xmm registers
			for i in xrange(8): print 'xmm%d 0x%08x 0x%08x 0x%08x 0x%08x' % \
			        tuple([i] + list(output[i*4:i*4+4]))
			# print all gpr's stored in xmm registers,
			# 16 is offset of EAX in the Registers array
			for i in xrange(8): print '%s 0x%08x -> 0x%08x' % \
			        (Registers[16+i], output[24+i], test['regs'][i])
			print '' # newline
			
			assemble.Debuggable(test['code'], _stack, code).debug()
		
		# unit test with memory changes
		elif test['type'] == 'mem' and test['mem'] != output[32:]:
			print '%s -> %s gave memory problems (%d)!' % \
			        (test['hex'], ' ; '.join(test['asm']), count)
			print 'Generated SSE Assembly:\n' + '\n'.join(test['lines']) + '\n'
			
			# print the memory stuff
			for i in xrange(len(output)-32): print '%-3d: 0x%08x -> 0x%08x' % \
			        (i, output[32+i], test['mem'][i])
			print '' # newline
			
			assemble.Debuggable(test['code'], _stack, code).debug()
		
		elif debug:
			assemble.Debuggable(test['code'], _stack, code).debug()
		
		count += 1
	
	# free the stack
	cdll.msvcrt.free(_stack)
	
	# free the machine code
	windll.kernel32.VirtualFree(code, 0, MEM_RELEASE)
コード例 #43
0
ファイル: enc.py プロジェクト: Bletchley13/ssexy
		self.lines.append('psubd xmm1, xmm0')
		self._write_value_xmm(0, 1)
	
	def _encode_xchg(self):
		self._read_value_xmm(0)
		self._read_value_xmm(1, 1)
		self._write_value_xmm(1, 0)
		self._write_value_xmm(0, 1)
	
	def _encode_leave(self):
		# leave = mov esp, ebp ; pop ebp
		self.lines += enc_apply('8be5')
		self.lines += enc_apply('5d')
	
	def _encode_ret(self):
		# ret = pop eip
		
		# we encode as pop eax ; jmp eax
		self._read_emugpr_xmm(assemble.ESP)
		self.lines.append('movd eax, xmm0')
		
		# esp is the first dword in the xmm7 register
		self.lines.append('paddd xmm7, %s' % self._m128([4, 0, 0, 0]))
		
		# jump to the address
		self.lines.append('jmp dword [eax]')
if __name__ == '__main__':
	lines = sys.stdin.readlines()
	code = assemble.assemble(lines)
	print binascii.hexlify(code)
コード例 #44
0
stiffnessTensor = E/(1-nu)*np.array([
	[1, nu, 0],
	[nu, 1, 0],
	[0, 0, (1-nu)/2],
	])

nodex = np.array([0,1,0,1]) # x coord of nodes
nodey = np.array([0,0,1,1]) # y coord of nodes
connectivityArray = np.array([
	[0,1,2],
	[2,1,3],
])



xil = np.array([1./3, 2./15, 2./15, 11./15]);
etal = np.array([1./3, 11./15, 2./15, 2./15]);
weight = np.array([-27, 25, 25, 25])/96;
nint = len(xil)
sfGen = ShapeFunctionGenerator()
# Raw shape functions for each variable
psi,dxi,deta = sfGen.generateShapeFunctionsTri(xil,etal)

assemble(nodex,nodey,connectivityArray,
	psi,dxi,deta,weight,stiffnessTensor)

# A = np.ones([2,2,2])
# f = np.array([3,2])
# B = A*f
# print B[0,0,:]
print [1+(1-nu/2), nu+(1-nu)/2,-1,-(1-nu)/2]
コード例 #45
0
def kunkel_full(protocol, params):
    growth_media = params["construct_setup"]['growth_media']
    #num_colonies = params["construct_setup"]['num_colonies']
    ssDNA = params["construct_setup"]['ssDNA']
    mutant_constructs = []

    # make mutant objects for accessibility
    construct_collect = {}
    for csv_row in params["construct_setup"]['mutant_upload']:
        if csv_row["mutant_label"] not in construct_collect.keys():
            construct_collect[csv_row["mutant_label"]] = []
            construct_collect[csv_row["mutant_label"]].append({
                "sequence":
                csv_row["sequence"],
                "purification":
                csv_row["purification"],
                "scale":
                csv_row["scale"],
                "oligo_label":
                csv_row["oligo_label"]
            })
        else:
            construct_collect[csv_row["mutant_label"]].append({
                "sequence":
                csv_row["sequence"],
                "purification":
                csv_row["purification"],
                "scale":
                csv_row["scale"],
                "oligo_label":
                csv_row["oligo_label"]
            })

    oligo_collect = {}
    for row in params["construct_setup"]["mutant_upload"]:
        if (row["sequence"] not in oligo_collect.keys()
                and row["oligo_label"] in protocol.refs.keys()):
            raise RuntimeError("You cannot specify two different "
                               "oligos to be synthesized with the "
                               "same name %s" % row['oligo_label'])
        elif row["sequence"] not in oligo_collect.keys():
            oligo_collect[row["sequence"]] = {
                "sequence":
                row["sequence"],
                "purification":
                row["purification"],
                "scale":
                row["scale"],
                "destination":
                protocol.ref(row["oligo_label"],
                             None,
                             "micro-2.0",
                             storage="cold_4").well(0)
            }

    for mut in construct_collect.keys():
        mut_oligos = [o for o in construct_collect[mut]]
        mutant = Mutant(mut)
        for oligo in mut_oligos:
            mutant.add_oligos(oligo_collect[oligo["sequence"]]["destination"])
        mutant_constructs.append(mutant)

    oligos_to_synthesize = []
    for o in oligo_collect.keys():
        scale_default(len(oligo_collect[o]["sequence"]),
                      oligo_collect[o]["scale"],
                      oligo_collect[o]["destination"].container.name)
        oligos_to_synthesize.append(oligo_collect[o])
    protocol.oligosynthesize(oligos_to_synthesize)

    assemble_params = {
        'ssDNA':
        ssDNA,
        'constructs': [{
            'mutant_name': mu.name,
            'oligos': mu.oligos
        } for mu in mutant_constructs],
        'mutant_objs':
        mutant_constructs
    }

    annealing_plate = assemble(protocol, assemble_params)
    protocol.unseal(annealing_plate)

    transform_params = {
        #'num_colonies': num_colonies,
        'growth_media': growth_media,
        'constructs': [mu.anneal_well for mu in mutant_constructs],
        'mutant_objs': mutant_constructs
    }

    # get agar plates back from transform protocol
    agar_plates = transform(protocol, transform_params)

    for agar_plate in agar_plates:
        protocol.cover(agar_plate)
コード例 #46
0
    def __init__(self, *args, **kwargs):
        """
        :arg problem: A :class:`NonlinearVariationalProblem` to solve.
        :kwarg nullspace: an optional :class:`.VectorSpaceBasis` (or
               :class:`.MixedVectorSpaceBasis`) spanning the null
               space of the operator.
        :kwarg solver_parameters: Solver parameters to pass to PETSc.
            This should be a dict mapping PETSc options to values.  For
            example, to set the nonlinear solver type to just use a linear
            solver:

        .. code-block:: python

            {'snes_type': 'ksponly'}

        PETSc flag options should be specified with `bool` values. For example:

        .. code-block:: python

            {'snes_monitor': True}

        .. warning ::

            Since this object contains a circular reference and a
            custom ``__del__`` attribute, you *must* call :meth:`.destroy`
            on it when you are done, otherwise it will never be
            garbage collected.

        """
        assert isinstance(args[0], NonlinearVariationalProblem)
        self._problem = args[0]
        # Build the jacobian with the correct sparsity pattern.  Note
        # that since matrix assembly is lazy this doesn't actually
        # force an additional assembly of the matrix since in
        # form_jacobian we call assemble again which drops this
        # computation on the floor.
        self._jac_tensor = assemble.assemble(self._problem.J_ufl, bcs=self._problem.bcs,
                                             form_compiler_parameters=self._problem.form_compiler_parameters)
        if self._problem.Jp is not None:
            self._jac_ptensor = assemble.assemble(self._problem.Jp, bcs=self._problem.bcs,
                                                  form_compiler_parameters=self._problem.form_compiler_parameters)
        else:
            self._jac_ptensor = self._jac_tensor
        test = self._problem.F_ufl.arguments()[0]
        self._F_tensor = function.Function(test.function_space())
        # Function to hold current guess
        self._x = function.Function(self._problem.u_ufl)
        self._problem.F_ufl = ufl.replace(self._problem.F_ufl, {self._problem.u_ufl:
                                                                self._x})
        self._problem.J_ufl = ufl.replace(self._problem.J_ufl, {self._problem.u_ufl:
                                                                self._x})
        if self._problem.Jp is not None:
            self._problem.Jp = ufl.replace(self._problem.Jp, {self._problem.u_ufl:
                                                              self._x})
        self._jacobian_assembled = False
        self.snes = PETSc.SNES().create()
        self._opt_prefix = 'firedrake_snes_%d_' % NonlinearVariationalSolver._id
        NonlinearVariationalSolver._id += 1
        self.snes.setOptionsPrefix(self._opt_prefix)

        parameters = kwargs.get('solver_parameters', None)
        if 'parameters' in kwargs:
            warning(RED % "The 'parameters' keyword to %s is deprecated, use 'solver_parameters' instead.",
                    self.__class__.__name__)
            parameters = kwargs['parameters']
            if 'solver_parameters' in kwargs:
                warning(RED % "'parameters' and 'solver_parameters' passed to %s, using the latter",
                        self.__class__.__name__)
                parameters = kwargs['solver_parameters']

        # Make sure we don't stomp on a dict the user has passed in.
        parameters = parameters.copy() if parameters is not None else {}
        # Mixed problem, use jacobi pc if user has not supplied one.
        if self._jac_tensor._M.sparsity.shape != (1, 1):
            parameters.setdefault('pc_type', 'jacobi')

        self.parameters = parameters

        ksp = self.snes.getKSP()
        pc = ksp.getPC()
        pmat = self._jac_ptensor._M
        names = [fs.name if fs.name else str(i)
                 for i, fs in enumerate(test.function_space())]

        ises = solving_utils.set_fieldsplits(pmat, pc, names=names)

        with self._F_tensor.dat.vec as v:
            self.snes.setFunction(self.form_function, v)
        self.snes.setJacobian(self.form_jacobian, J=self._jac_tensor._M.handle,
                              P=self._jac_ptensor._M.handle)

        nullspace = kwargs.get('nullspace', None)
        if nullspace is not None:
            self.set_nullspace(nullspace, ises=ises)
コード例 #47
0
ファイル: test-assemble.py プロジェクト: Toseter/mspgcc
 def testMiscInsns(self):
     iop, comment, cycles = assemble.assemble("reti")
     self.failUnless(iop == [["OPC", 0x1300]])
     self.failUnless(cycles == 5)
コード例 #48
0
def multiple_element_v1():
    mesh = CrazyMesh(2, (1, 1), ((-1, 1), (-1, 1)), curvature=0.0)
    p = 4, 4
    func_space_vort = FunctionSpace(mesh, '0-lobatto', p, is_inner=False)
    func_space_outer_vel = FunctionSpace(
        mesh, '1-lobatto', p, is_inner=False)
    func_space_outer_vel.dof_map.continous_dof = True
    # func_space_outer_vel = FunctionSpace(
    #     mesh, '1-gauss', (p[0], p[1]), is_inner=False)
    func_space_inner_vel = FunctionSpace(
        mesh, '1-gauss', (p[0], p[1]), is_inner=True)
    print('dof gauss :', func_space_inner_vel.num_dof)
    func_space_inner_vel.dof_map.continous_dof = False
    func_space_source = FunctionSpace(mesh, '2-gauss', (p[0] + 1, p[1] + 1), is_inner=True)
    print("dof source :", func_space_source.num_dof)

    basis_vort = BasisForm(func_space_vort)
    basis_vel_in = BasisForm(func_space_inner_vel)
    basis_vel_in.quad_grid = 'lobatto'
    basis_vel_out = BasisForm(func_space_outer_vel)
    basis_vel_out.quad_grid = 'lobatto'
    basis_2 = BasisForm(func_space_source)

    psi = Form(func_space_vort)
    u_in = Form(func_space_inner_vel)
    source = Form(func_space_source)
    source.discretize(ffun)

    M_1 = inner(basis_vel_in, basis_vel_in)
    # E_21_in = d(func_space_inner_vel)
    W_02 = basis_2.wedged(basis_vort)
    W_11 = basis_vel_in.wedged(basis_vel_out)
    E_10_out = d(func_space_vort)
    print(np.shape(W_11), np.shape(E_10_out))
    W_E = W_11 @ E_10_out
    W_11_inv = basis_vel_out.wedged(basis_vel_in)
    E_W = np.transpose(E_10_out) @ W_11_inv
    print("shape ew : ", np.shape(W_E))
    print(np.shape(W_02))

    M_1 = assemble(M_1, (func_space_inner_vel, func_space_inner_vel))
    print(func_space_source.num_local_dof)
    W_E = assemble(W_E, (func_space_outer_vel, func_space_vort))
    E_W = assemble(E_W, (func_space_vort, func_space_outer_vel))
    W_02 = assemble(W_02, (func_space_vort, func_space_source))

    lhs = spr.bmat([[M_1, W_E], [W_E.transpose(), None]])
    rhs = np.zeros(np.shape(lhs)[0])
    rhs[-func_space_source.num_dof:] = W_02 @ source.cochain

    solution = spr.linalg.spsolve(lhs.tocsc(), rhs)
    u_in.cochain = solution[:func_space_inner_vel.num_dof]
    psi.cochain = solution[-func_space_vort.num_dof:]

    xi = eta = np.linspace(-1, 1, 40)
    u_in.reconstruct(xi, eta)
    (x, y), u_x, u_y = u_in.export_to_plot()
    plt.contourf(x, y, u_x)
    plt.colorbar()
    plt.title("u_x inner")
    plt.show()
    psi.reconstruct(xi, eta)
    (x, y), psi_value = psi.export_to_plot()
    plt.contourf(x, y, psi_value)
    plt.title("psi outer")
    plt.colorbar()
    plt.show()
コード例 #49
0
ファイル: server.py プロジェクト: antonmiakotin/snazzy
 def assemble(self):
     filename = assemble.assemble(self.session_images)
     printer.print_file(filename)
コード例 #50
0
from assemble.assemble import *
from engine.holdings_engine import *
from engine.assets_engine import *
from utils.oracle import *
from utils.select_translate import *
from utils.move_back_up import *

print('\n')
print('-----------------------------------')
print('...extracte from excel...')
extraction = extraction()
extraction.debug()
print('...add industry information...')
oracle.procedure('do_industry')
print('...assemble to fof...')
assemble = assemble()
assemble.debug()
print('...calculate assets performance...')
select_list = translate()
assets = assets_engine()
assets.select_port_list = select_list
assets.debug()
print('...calculate holdings performance...')
for select_item in select_list:
	fund_id = select_item[0]
	port_id = select_item[1]
	holdings = holdings_engine()
	holdings.fund_names = fund_id
	holdings.port_names = port_id
	abspath_str =  os.path.abspath(".") + '\\performance_monitoring'
	with open(abspath_str+'\\configuration\\manager_fof_construction.json', 'r') as file: