Esempio n. 1
0
    def _evaluate(self,
                  x,  #
                  out,
                  *args,
                  **kwargs):
        """
        This method iterate over an Individual, execute the refactoring operation sequentially,
        and compute quality attributes for the refactored version of the program, as objectives of the search

        params:
        x (Individual): x is an instance of Individual (i.e., a list of refactoring operations)

        """
        # Stage 0: Git restore
        logger.debug("Executing git restore.")
        git_restore(config.PROJECT_PATH)
        update_understand_database(config.UDB_PATH)
        # Stage 1: Execute all refactoring operations in the sequence x
        logger.debug(f"Reached Individual with Size {len(x[0])}")
        for refactoring_operation in x[0]:
            refactoring_operation.do_refactoring()
            # Update Understand DB
            update_understand_database(config.UDB_PATH)

        # Stage 2: Computing quality attributes
        obj = Objectives(udb_path=config.UDB_PATH)
        o1 = obj.average
        del obj
        o2 = testability_main(config.UDB_PATH)
        o3 = modularity_main(config.UDB_PATH)
        logger.info(f"QMOOD AVG Score: {o1}")
        logger.info(f"Testability Score: {o2}")
        logger.info(f"Modularity Score: {o3}")
        # Stage 3: Marshal objectives into vector
        out["F"] = np.array([-1 * o1, -1 * o2, -1 * o3], dtype=float)
    def _evaluate(
            self,
            x,  #
            out,
            *args,
            **kwargs):
        """
        This method iterate over an Individual, execute the refactoring operation sequentially,
        and compute quality attributes for the refactored version of the program, as objectives of the search

        params:
        x (Individual): x is an instance of Individual (i.e., a list of refactoring operations)

        """
        # Git restore`
        logger.debug("Executing git restore.")
        git_restore(config.PROJECT_PATH)
        update_understand_database(config.UDB_PATH)
        # Stage 1: Execute all refactoring operations in the sequence x
        logger.debug(f"Reached Individual with Size {len(x[0])}")
        for refactoring_operation in x[0]:
            refactoring_operation.do_refactoring()
            # Update Understand DB
            update_understand_database(config.UDB_PATH)

        # Stage 2: Computing quality attributes
        qmood = DesignQualityAttributes(udb_path=config.UDB_PATH)
        o1 = qmood.reusability
        o2 = qmood.understandability
        o3 = qmood.flexibility
        o4 = qmood.functionality
        o5 = qmood.effectiveness
        o6 = qmood.extendability
        del qmood
        o7 = testability_main(config.UDB_PATH)
        o8 = modularity_main(config.UDB_PATH)

        logger.info(f"Reusability Score: {o1}")
        logger.info(f"Understandability Score: {o2}")
        logger.info(f"Flexibility Score: {o3}")
        logger.info(f"Functionality Score: {o4}")
        logger.info(f"Effectiveness Score: {o5}")
        logger.info(f"Extendability Score: {o6}")
        logger.info(f"Testability Score: {o7}")
        logger.info(f"Modularity Score: {o8}")

        # Stage 3: Marshal objectives into vector
        out["F"] = np.array([
            -1 * o1,
            -1 * o2,
            -1 * o3,
            -1 * o4,
            -1 * o5,
            -1 * o6,
            -1 * o7,
            -1 * o8,
        ],
                            dtype=float)
Esempio n. 3
0
def main(udb_path, source_package, source_class, source_field, *args, **kwargs):
    """


    """

    db = und.open(udb_path)
    field_ent = db.lookup(f"{source_package}.{source_class}.{source_field}", "Variable")

    if len(field_ent) == 0:
        logger.error("Invalid inputs.")
        db.close()
        return False

    field_ent = field_ent[0]
    if field_ent.simplename() != source_field:
        logger.error("Invalid entity.")
        db.close()
        return False

    # Strong overlay precondition
    # if not field_ent.kind().check("Public"):
    #     logger.error("Field is not public.")
    #     db.close()
    #     return False

    for ref in field_ent.refs("Useby,Setby"):
        ent = ref.ent()
        if f"{source_package}.{source_class}" not in ent.longname():
            logger.debug(f"{source_package}.{source_class} not in {ent.longname()}")
            logger.error("Field cannot set to private.")
            db.close()
            return False

    parent = field_ent.parent()
    while parent.parent() is not None:
        parent = parent.parent()

    main_file = parent.longname()
    db.close()

    parse_and_walk(
        file_path=main_file,
        listener_class=DecreaseFieldVisibilityListener,
        has_write=True,
        source_class=source_class,
        source_field=source_field
    )

    return True
Esempio n. 4
0
    def exitFieldDeclaration(self,
                             ctx: JavaParserLabeled.FieldDeclarationContext):
        if self.in_source_class and self.in_selected_package:
            if ctx.variableDeclarators().variableDeclarator(
                    0).variableDeclaratorId().getText(
                    ) == self.field_identifier:
                if not ctx.parentCtx.parentCtx.modifier(0):
                    self.token_stream_rewriter.insertBeforeIndex(
                        index=ctx.typeType().stop.tokenIndex, text='private ')

                elif ctx.parentCtx.parentCtx.modifier(0).getText() == 'public':
                    self.token_stream_rewriter.replaceRange(
                        from_idx=ctx.parentCtx.parentCtx.modifier(
                            0).start.tokenIndex,
                        to_idx=ctx.parentCtx.parentCtx.modifier(
                            0).stop.tokenIndex,
                        text='private')
                else:
                    return

                for c in ctx.parentCtx.parentCtx.parentCtx.classBodyDeclaration(
                ):
                    try:
                        print('method name: ' + c.memberDeclaration().
                              methodDeclaration().IDENTIFIER().getText())

                        if c.memberDeclaration().methodDeclaration().IDENTIFIER() \
                                .getText() == 'get' + str.capitalize(
                            self.field_identifier):
                            self.getter_exist = True

                        if c.memberDeclaration().methodDeclaration().IDENTIFIER() \
                                .getText() == 'set' + str.capitalize(
                            self.field_identifier):
                            self.setter_exist = True

                    except:
                        logger.error("not method !!!")

                logger.debug("setter find: " + str(self.setter_exist))
                logger.debug("getter find: " + str(self.getter_exist))

                # generate accessor and mutator methods
                # Accessor body
                new_code = ''
                if not self.getter_exist:
                    new_code = '\n\t// new getter method\n\t'
                    new_code += 'public ' + ctx.typeType().getText() + \
                                ' get' + str.capitalize(self.field_identifier)
                    new_code += '() { \n\t\treturn this.' + self.field_identifier \
                                + ';' + '\n\t}\n'

                # Mutator body
                if not self.setter_exist:
                    new_code += '\n\t// new setter method\n\t'
                    new_code += 'public void set' + str.capitalize(
                        self.field_identifier)
                    new_code += '(' + ctx.typeType().getText() + ' ' \
                                + self.field_identifier + ') { \n\t\t'
                    new_code += 'this.' + self.field_identifier + ' = ' \
                                + self.field_identifier + ';' + '\n\t}\n'
                self.token_stream_rewriter.insertAfter(ctx.stop.tokenIndex,
                                                       new_code)

                hidden = self.token_stream.getHiddenTokensToRight(
                    ctx.stop.tokenIndex)
Esempio n. 5
0
    def _evaluate(self, x, out, *args, **kwargs):
        """
        By default, elementwise_evaluation is set to False, which implies the _evaluate retrieves a set of solutions.

        params:
            x (Population): x is a matrix where each row is an individual, and each column a variable.
            We have one variable of type list (Individual) ==> x.shape = (len(Population), 1)

        """

        objective_values = []
        for k, individual_ in enumerate(x):
            # Stage 0: Git restore
            logger.debug("Executing git restore.")
            git_restore(config.PROJECT_PATH)
            logger.debug("Updating understand database after git restore.")
            update_understand_database(config.UDB_PATH)

            # Stage 1: Execute all refactoring operations in the sequence x
            logger.debug(
                f"Reached an Individual with size {len(individual_[0])}")
            for refactoring_operation in individual_[0]:
                refactoring_operation.do_refactoring()
                # Update Understand DB
                logger.debug(
                    f"Updating understand database after {refactoring_operation.name}."
                )
                update_understand_database(config.UDB_PATH)

            # Stage 2:
            arr = Array('d', range(8))
            if self.evaluate_in_parallel:
                # Stage 2 (parallel mood): Computing quality attributes
                p1 = Process(target=calc_qmood_objectives, args=(arr, ))
                p2 = Process(target=calc_testability_objective,
                             args=(
                                 config.UDB_PATH,
                                 arr,
                             ))
                p3 = Process(target=calc_modularity_objective,
                             args=(
                                 config.UDB_PATH,
                                 arr,
                             ))
                p1.start(), p2.start(), p3.start()
                p1.join(), p2.join(), p3.join()
            else:
                # Stage 2 (sequential mood): Computing quality attributes
                qmood = Objectives(udb_path=config.UDB_PATH)
                arr[0] = qmood.reusability
                arr[1] = qmood.understandability
                arr[2] = qmood.flexibility
                arr[3] = qmood.functionality
                arr[4] = qmood.effectiveness
                arr[5] = qmood.extendability
                arr[6] = testability_main(
                    config.UDB_PATH,
                    initial_value=config.CURRENT_METRICS.get("TEST", 1.0))
                arr[7] = modularity_main(
                    config.UDB_PATH,
                    initial_value=config.CURRENT_METRICS.get("MODULE", 1.0))
                del qmood

            # Stage 3: Marshal objectives into vector
            objective_values.append([-1 * i for i in arr])
            logger.info(
                f"Objective values for individual {k}: {[i for i in arr]}")

        # Stage 4: Marshal all objectives into out dictionary
        out['F'] = np.array(objective_values, dtype=float)
Esempio n. 6
0
    def _evaluate(
            self,
            x,  #
            out,
            *args,
            **kwargs):
        """
        This method iterate over an Individual, execute the refactoring operation sequentially,
        and compute quality attributes for the refactored version of the program, as objectives of the search

        params:
        x (Population): x is a matrix where each row is an individual, and each column a variable.
            We have one variable of type list (Individual) ==> x.shape = (len(Population), 1)

        """
        objective_values = []
        for k, individual_ in enumerate(x):
            # Stage 0: Git restore
            logger.debug("Executing git restore.")
            git_restore(config.PROJECT_PATH)
            logger.debug("Updating understand database after git restore.")
            update_understand_database(config.UDB_PATH)

            # Stage 1: Execute all refactoring operations in the sequence x
            logger.debug(f"Reached Individual with Size {len(individual_[0])}")
            for refactoring_operation in individual_[0]:
                refactoring_operation.do_refactoring()
                # Update Understand DB
                logger.debug(
                    f"Updating understand database after {refactoring_operation.name}."
                )
                update_understand_database(config.UDB_PATH)

            # Stage 2:
            arr = Array('d', range(8))
            if self.evaluate_in_parallel:
                # Stage 2 (parallel mood): Computing quality attributes
                p1 = Process(target=calc_qmood_objectives, args=(arr, ))
                p2 = Process(target=calc_testability_objective,
                             args=(
                                 config.UDB_PATH,
                                 arr,
                             ))
                p3 = Process(target=calc_modularity_objective,
                             args=(
                                 config.UDB_PATH,
                                 arr,
                             ))
                p1.start(), p2.start(), p3.start()
                p1.join(), p2.join(), p3.join()
                o1 = sum([i for i in arr[:6]]) / 6.
                o2 = arr[7]
                o3 = arr[8]
            else:
                # Stage 2 (sequential mood): Computing quality attributes
                qmoods = Objectives(udb_path=config.UDB_PATH)
                o1 = qmoods.average
                o2 = testability_main(config.UDB_PATH,
                                      initial_value=config.CURRENT_METRICS.get(
                                          "TEST", 1.0))
                o3 = modularity_main(config.UDB_PATH,
                                     initial_value=config.CURRENT_METRICS.get(
                                         "MODULE", 1.0))
                del qmoods

            # Stage 3: Marshal objectives into vector
            objective_values.append([-1 * o1, -1 * o2, -1 * o3])
            logger.info(
                f"Objective values for individual {k}: {[-1 * o1, -1 * o2, -1 * o3]}"
            )

        # Stage 4: Marshal all objectives into out dictionary
        out['F'] = np.array(objective_values, dtype=float)