Beispiel #1
0
    def from_json(
            cls, 
            input_problem: str, 
            name: Optional[str] = None
        ) -> Problem:
        """Deserializes the problem from a
        json serialized with Problem.serialize()

        :param input_problem:
            the json string to be deserialized to a `Problem` instance
        :type problem_msgs: str
        :param
        :param name: 
            The name of the problem is optional, since it will try 
            to read the serialized name from the json payload.
            If this parameter is not empty, it will use it as the
            problem name ignoring the serialized value.
        :type name: Optional[str]
        """
        result = json.loads(input_problem)

        if name is None:
            metadata = result.get("metadata")
            if metadata is not None:
                name = metadata.get("name")

        terms = [Term.from_dict(t) for t in result["cost_function"]["terms"]] if "terms" in result["cost_function"] else []
        if "terms_slc" in result["cost_function"]:
            terms.append([SlcTerm.from_dict(t) for t in result["cost_function"]["terms_slc"]])

        problem = cls(
            name=name,
            terms=terms,
            problem_type=ProblemType[result["cost_function"]["type"]],
        )

        if "initial_configuration" in result["cost_function"]:
            problem.init_config = result["cost_function"]["initial_configuration"]

        return problem
Beispiel #2
0
    def deserialize(cls, problem_as_json: str, name: str):
        """Deserializes the problem from a
            JSON string serialized with Problem.serialize()

        :param problem_as_json:
            The string to be deserialized to a `Problem` instance
        :type problem_as_json: str
        :param name: The name of the problem
        :type name: str
        """
        result = json.loads(problem_as_json)
        problem = Problem(
            name=name,
            terms=[
                Term.from_dict(t) for t in result["cost_function"]["terms"]
            ],
            problem_type=ProblemType[result["cost_function"]["type"]],
        )

        if "initial_configuration" in result["cost_function"]:
            problem.init_config = result["cost_function"][
                "initial_configuration"]

        return problem