예제 #1
0
def main():
    try:
        from src.run import run
        run()
    except Exception:
        sys.exit(1)
    return
예제 #2
0
def demo():    
    import src.utils.logger as log
    import src.utils.path as pth
    import src.parser.toml as tml
    from src.utils.tools import download, extract
    
    
    # Downloading data from URLs and extracting downloaded files

    dry_url = tml.value('urls', section='demo', subkey='dry')
    fx_url = tml.value('urls', section='demo', subkey='fx')

    dry_dpath = tml.value('dnames', section='demo', subkey='input')
    fx_fname = tml.value('fx_name', section='demo')

    log.info("Downloading and extracting dataset and fx")

    fx_fpath = download(fx_url)
    pth.__rename_file(fx_fpath, fx_fname)
    
    if not pth.__exists(dry_dpath):
        dry_fpath = download(dry_url)
        extract(dry_fpath, dry_dpath)
    else:
        log.warning("\"{0}\" already exist, skipping dataset downloading".format(dry_dpath))

    run(dry_dpath, fx_fname, tml.value('dnames', section='demo', subkey='output'))
예제 #3
0
def main():
    from src.utils.tools import usage

    import sys

    if len(sys.argv) < 3:
        raise SystemExit(
            usage(__file__.replace('./', ''),
                  required_args=[
                      'path/to/dry/signals/dir', 'path/to/impulse/response'
                  ],
                  optional_args=['path/to/output/dir']))

    run(*sys.argv[1:])
예제 #4
0
 def expectedExactUtility_SDD_2(self,query_action,save=None,load=None):
     r = run.run(self.aspContent, self.args)
     r.args = self.args
     result = r.infer(['utility'],query_action)
     total = 0
     for atom in result:
         reward = eval(str(atom[0].arguments[0]).strip('\"'))
         total += reward * atom[1]
     return "Utility: " + str(total)
예제 #5
0
    def max_walk_sat_exact_sdd_2(self):
        solution = ""
        utility = -float("inf")
        r = run.run(self.aspContent,self.args)


        for _ in range(1,self.mt):
            mcASPObj = marginal_mcsat.mcSAT(self.aspContent, "", [], self.xorMode,1)
            mcASPObj.runMCASP()
            firstSample = mcASPObj.getSamples()
            decisionAssignments = self.completeTruthAssignment(firstSample[0])
            tempSoln = decisionAssignments
            tempUtility = self.max_walk_sat_sdd2_helper(r, tempSoln)

            for _ in range(1,self.mf):
                vf=""
                deltCostVf = float("inf")
                orgUtility = self.max_walk_sat_sdd2_helper(r,tempSoln)

                if self.p < random.random():
                    vf = tempSoln[random.randint(0, len(tempSoln) - 1)]
                    newDecisionAssignments = self.flipDecisionAtom(tempSoln,vf)
                    flippedUtility =self.max_walk_sat_sdd2_helper(r,newDecisionAssignments)
                    if flippedUtility != False:
                        deltCostVf = orgUtility - flippedUtility
                else:
                    deltaCost = []
                    for decToFlip in tempSoln:
                        newDecisionAssignments = self.flipDecisionAtom(tempSoln, decToFlip)
                        flippedUtility = self.max_walk_sat_sdd2_helper(r,newDecisionAssignments)
                        if flippedUtility != False:
                            deltaCost.append((decToFlip,orgUtility - flippedUtility))
                    if len(deltaCost) != 0:
                        minDeltaCost = min(deltaCost,key=lambda t:t[1])
                    else:
                        continue

                    vf = minDeltaCost[0]
                    deltCostVf = minDeltaCost[1]

                if deltCostVf<0:
                    tempSoln = self.flipDecisionAtom(tempSoln, vf)
                    tempUtility = tempUtility - deltCostVf

            if tempUtility >utility:
                utility = tempUtility
                solution = tempSoln

        return solution,utility
예제 #6
0
    def exact_maxSDD_2(self):
        table = list(itertools.product([False, True], repeat=len(self.grounded_dec_atoms)))
        completeDecisionAssignment = []
        for t in table:
            decAssignmentLine = []
            for i in range(0, len(self.grounded_dec_atoms)):
                tuple = (self.grounded_dec_atoms[i], t[i])
                decAssignmentLine.append(tuple)
            completeDecisionAssignment.append(decAssignmentLine)

        completeUitlity = []
        r = run.run(self.aspContent,self.args)
        r.args = self.args
        if self.args.verbosity >0:
            print("There are ",str(len(completeDecisionAssignment))," different decisions, start to evaluate them one by one.")
        counter = 0
        for decAssiment in completeDecisionAssignment:
            counter+=1
            if self.args.verbosity > 4:
                print("Start evaluating decision: ", counter)
            elif self.args.verbosity > 0:
                if counter == int(0.25*len(completeDecisionAssignment)):
                    print("1/4 is done!")
                elif counter == int(0.5*len(completeDecisionAssignment)):
                    print("1/2 is done!")
                elif counter == int(0.75*len(completeDecisionAssignment)):
                    print("3/4 is done!")


            evidence = self.buildASPEvidenceForm(decAssiment)
            if self.satisfiableChecker(evidence):
                result = r.infer(['utility'],decAssiment)
                total = 0
                for atom in result:
                    reward = eval(str(atom[0].arguments[0]).strip('\"'))
                    total += reward * atom[1]
                completeUitlity.append((decAssiment,total))
        if self.args.verbosity > 0:
            print("All done! Printing final decision.")
        maxDec = max(completeUitlity,key=lambda item:item[1])
        return maxDec
예제 #7
0
        root_logger.addHandler(timed_rotating_fh)
        root_logger.info("Will log to a time rotating file at: %s", log_path)

    if set_debug:
        root_logger.info("Log level set to DEBUG.")
    else:
        root_logger.info("Log level set to INFO.")


if __name__ == "__main__":
    arg_parser = ArgumentParser()
    arg_parser.add_argument(
        "-d", "--debug", action="store_true", help="Enable debug logging"
    )
    arg_parser.add_argument(
        "-lp",
        "--log-path",
        help="Sets a rotating file handler at the given path",
    )

    arguments = arg_parser.parse_args()

    load_dotenv()
    _init_loggers(arguments.debug, log_path=arguments.log_path)
    try:
        run()
    except Exception:
        logger = logging.getLogger()
        logger.error("Something went wrong.", exc_info=True)
        raise
예제 #8
0
    group = arg_parser.add_mutually_exclusive_group()
    group.add_argument('-M',
                       '--Manhatan',
                       action='store_true',
                       help="(default heuristic)")
    group.add_argument('-H', '--Hamming_distance', action='store_true')
    group.add_argument('-L', '--Linear_conflict', action='store_true')
    group.add_argument('-E', '--Euclidian', action='store_true')
    group.add_argument('-U', '--uniform_cost', action='store_true')
    arg_parser.add_argument('-G', '--greedy_search', action='store_true')
    arg_parser.add_argument('-t',
                            '--timer',
                            action='store_true',
                            help="print total execution time")
    arg_parser.add_argument('-v', '--verbose', action='store_true')
    arg_parser.add_argument("files",
                            metavar="file",
                            nargs="*",
                            help="input file with a puzzle")
    args = arg_parser.parse_args()
    try:
        puzzle = parser.parser(args.files)
    except error.ParsingError as err:
        print("Parsing Error : {}".format(err.message))
        exit(1)
    if args.timer:
        t = Timer(lambda: run.run(puzzle, args, args.verbose))
        print("exe time : {}".format(t.timeit(number=1)))
    else:
        run.run(puzzle, args, args.verbose)
예제 #9
0
os.environ["PYGAME_HIDE_SUPPORT_PROMPT"] = "1"

from src import run


parser = argparse.ArgumentParser()
parser.add_argument(
    "n",
    type=int,
    help="Number of points."
)
parser.add_argument(
    "-w",
    "--window-size",
    metavar=("<width>", "<height>"),
    nargs=2,
    type=int,
    help="Specify the window width and height in pixels.",
    default=(800, 600)
)
parser.add_argument(
    "-m",
    "--min-distance",
    metavar="<min-distance>",
    type=int,
    help="Minimum distance between points.",
    default=15
)
args = parser.parse_args()
run.run(args.n, args.window_size, args.min_distance)
예제 #10
0
    def solve(self):
        wholeInput = ""
        evidenceInput = ""

        if self.arg_list['nn_indictor']:
            wholeInput += nn_processor.process(self.arg_list['file_name'][-1])
            self.arg_list['file_name'] = self.arg_list['file_name'][:-1]

        for lpmln_file in self.arg_list['file_name']:
            with open(lpmln_file, 'r') as lpmln_content:
                wholeInput += lpmln_content.read()
            lpmln_content.close()

        for evid_file in self.arg_list['evidence']:
            with open(evid_file, 'r') as evidence_content:
                evidenceInput += evidence_content.read()
            evidence_content.close()

        if self.arg_list['mode'] == "sdd":
            content = self.lpmln_to_asp_sdd_parser(wholeInput, False,
                                                   self.arg_list['mf'])
            parsed_lpmln = self.asp_domain_2_asp_parser(content)
        elif self.arg_list['mode'] == "mcasp":
            content = self.lpmln_to_lpmln_neg_parser(wholeInput,
                                                     self.arg_list['mf'])
            content = self.lpmln_to_asp_parser(content, False,
                                               self.arg_list['mf'])
            parsed_lpmln = self.asp_domain_2_asp_parser(content)
        elif self.arg_list['mode'] == "map":
            content = self.lpmln_to_asp_parser(wholeInput,
                                               self.arg_list['hard'],
                                               self.arg_list['mf'], True)
            parsed_lpmln = self.asp_domain_2_asp_parser(content)
        else:
            content = self.lpmln_to_asp_parser(wholeInput,
                                               self.arg_list['hard'],
                                               self.arg_list['mf'], True)
            parsed_lpmln = self.asp_domain_2_asp_parser(content)

        if self.args.verbosity > 4:
            print(
                "================== Parsed ASP Program ======================")
            print(parsed_lpmln)

        if self.arg_list['mode'] == "map":
            with open('asp.pl', 'w') as fw:
                fw.write(parsed_lpmln + evidenceInput)
            if self.arg_list['hard']:
                command = "clingo " + os.getcwd() + "/asp.pl --opt-mode=enum 0"
            else:
                command = "clingo " + os.getcwd() + "/asp.pl "
            os.system(command)
        elif self.arg_list['mode'] == "ex":
            warn_option = "--warn=none"
            thread_option = "-t 4"
            enumerateAll = "--opt-mode=enum"
            listAll = "0"
            warn = "--warn=no-atom-undefined"
            options = [warn_option, thread_option, enumerateAll, listAll, warn]
            exactInfer = exactProbInfer.exactProbInfer(
                parsed_lpmln + evidenceInput, options, self.arg_list['query'],
                self.arg_list['hard'], self.arg_list['all'])
            if self.arg_list['hard']:
                with open('asp.pl', 'w') as fw:
                    fw.write(parsed_lpmln + evidenceInput)
                command = "clingo " + os.getcwd() + "/asp.pl --opt-mode=enum 0"
                os.system(command)
            exactInfer.solve()
        elif self.arg_list['mode'] == "mcasp":
            mcASPObj = marginal_mcsat.mcSAT(parsed_lpmln, evidenceInput,
                                            self.arg_list['query'],
                                            self.arg_list['xor_mode'],
                                            self.arg_list['sample'])
            mcASPObj.args = self.args
            mcASPObj.runMCASP()
            mcASPObj.printQuery()
        elif self.arg_list['mode'] == "kcor":
            marginal_coherent_obj = marginal_coherent.Marginal_coherent(
                parsed_lpmln, evidenceInput, self.arg_list['query'],
                self.arg_list['sample'])
            marginal_coherent_obj.args = self.args
            marginal_coherent_obj.run()
            marginal_coherent_obj.printQuery()

        elif self.arg_list['mode'] == "sdd":
            inferObj = sdd_infer.sddInference(evidenceInput,
                                              self.arg_list['query'])
            inferObj.args = self.args
            if self.arg_list['sddPara'][0] == 0:
                inferObj.sddConstructorFromLPMLN(parsed_lpmln, False)
                inferObj.inferencePrtQuery()
            elif self.arg_list['sddPara'][0] == 1:
                inferObj.sddConstructorFromFile(self.arg_list['sddPara'][1])
                inferObj.inferencePrtQuery()
            else:
                inferObj.sddConstructorFromLPMLN(parsed_lpmln, True,
                                                 self.arg_list['sddPara'][1])
                inferObj.inferencePrtQuery()
        else:
            r = run.run(parsed_lpmln, self.args)
            result = r.infer(self.arg_list['query'], evidenceInput)
            for r in result:
                print(r[0].to_string(), ": ", r[1])
예제 #11
0
import argparse
import os
os.environ["PYGAME_HIDE_SUPPORT_PROMPT"] = "1"

from src import constants
from src import run


parser = argparse.ArgumentParser()
parser.add_argument(
    "-w",
    "--window-size",
    metavar=("<width>", "<height>"),
    nargs=2,
    type=int,
    help="Specify the window width and height in pixels.",
    default=constants.DEEFAULT_WINDOW_SIZE
)
args = parser.parse_args()
run.run(args.window_size)
예제 #12
0
def run_it():
    code = request.json["code"]
    input_data = request.json["input"]
    ext = request.json["ext"]
    return run.run(code, input_data, ext)