예제 #1
0
    def get_args(self, line, parser, print_function=print):
        """
        parser a command line with a given parser

        @param      line            string (command line)
        @param      parser          parser which has to be used to parse *line*
        @param      print_function  function to use to display the help
        @return                     results

        If the line cannot be parsed, the function displays the help
        using function print.

        Example::

            @line_magic
            def custom_magic_command(self, line):
                parser = self.get_parser(MagicClass.custom_magic_command_parser, "custom_magic_command")
                args = self.get_args(line, parser)
                if args is not None:
                    param = args.param

                    # ....
        """
        try:
            args = parser.parse_cmd(line, context=self.Context)
        except SystemExit:
            print_function(parser.format_usage())
            args = None

        return args
예제 #2
0
    def check_pipeline(self, *args, **kwargs):
        bad_pipeline = True
        num_test = 0 # number of tests
        while bad_pipeline and num_test < 10: # a pool for workable pipeline
            # clone individual before each func call so it is not altered for the possible next cycle loop
            args = [self._toolbox.clone(arg) if isinstance(arg, creator.Individual) else arg for arg in args]
            try:
                with warnings.catch_warnings():
                    warnings.simplefilter('ignore')
                    expr = func(self, *args, **kwargs)
                    # mutation operator returns tuple (ind,); crossover operator returns tuple (ind1, ind2)
                    expr_tuple = expr if isinstance(expr, tuple) else (expr,)
                    for expr_test in expr_tuple:
                        #print(num_test, generate_pipeline_code(expr_to_tree(expr), self.operators)) # debug
                        sklearn_pipeline = eval(generate_pipeline_code(expr_to_tree(expr_test, self._pset), self.operators), self.operators_context)
                        if self.classification:
                            sklearn_pipeline.fit(pretest_X, pretest_y)
                        else:
                            sklearn_pipeline.fit(pretest_X_reg, pretest_y_reg)
                        bad_pipeline = False
            except BaseException as e:
                if self.verbosity > 2:
                    print_function = print
                    # Use the pbar output stream if it's active
                    if not isinstance(self._pbar, type(None)):
                        print_function = self._pbar.write
                    print_function('_pre_test decorator: {fname}: num_test={n} {e}'.format(n=num_test, fname=func.__name__, e=e))
            finally:
                num_test += 1

        return expr
예제 #3
0
def print_dispatch(outputfile):
    job = ccopen(outputfile)
    program_types = (
        (cclib.parser.adfparser.ADF, print_epr_adf),
        (cclib.parser.daltonparser.DALTON, print_epr_dalton),
        (cclib.parser.orcaparser.ORCA, print_epr_orca),
        (cclib.parser.qchemparser.QChem, print_epr_qchem),
    )
    for (program_type, print_function) in program_types:
        if isinstance(job, program_type):
            d = print_function(outputfile)
    return d
예제 #4
0
 def __str__(_):
     import io
     sio = io.StringIO()
     for k in self._sigdict:
         print_function(k, self._sigdict[k], file=sio)
     return sio.getvalue()
예제 #5
0
def write_iterable_to_file_line_by_line(iterable, f):
	for line in iterable:
		print_function(line.encode('utf-8'), file=f)
예제 #6
0
def search(problem, strategy, max_nodes, options ):

    print( "======= Running Brandon's Python Queue-Based Search Procedure =======" )

    initialise_func    = problem[0]
    problem_info_func  = problem[1]
    initial_state      = problem[2]
    poss_act_func      = problem[3]
    successor_func     = problem[4]
    goal_test_func     = problem[5]
    global OPTIONS     
    OPTIONS            = options

    if not(initialise_func == None):
       ## apply( initialise_func, () ) # Call function to initialise problem
       initialise_func()  # Call function to initialise problem
       
    ##apply( problem_info_func, () )  # Call function to print problem info
    problem_info_func()  # Call function to print problem info
    
    print( "Strategy:", strategy )
    print( "Search Limit: max_nodes =", max_nodes )
    print( "Options:", options )
    print( "*** starting search ***" )

    start_time = time.clock()

    node_queue = get_initial_node_queue( initial_state )
    for nodes_tested in range(max_nodes):
          ##print_node_queue(node_queue)
          if 'node_dots' in options:
             print_function( ".", end = '' )
          if nodes_tested % 1000 == 0:
             print( nodes_tested, ' ', end = '' )
             sys.stdout.flush() ## flush output to force immediate printing
          if node_queue == []:
             print( "\n:-( <FAILURE> )-:" )
             print( "The entire search space was searched --- this problem has NO SOLUTION!" )
             print( "Total nodes tested = " + str(nodes_tested+1) )
             print( "Time taken =", time.clock() - start_time, "seconds\n" )
             return False
          first_node = node_queue.pop(0)  #take 1st node from queue
          if 'loop_check' in options and node_state_occurs_in_ancestor( first_node ):
             if 'print_loops' in options:
                print( "loop detected", end = '' )
             continue
          if 'show_expand' in options:
             print( "Expanding ", end = '' )
             print( node_get_state( first_node ) )
              
          #if apply(goal_test_func, [node_get_state( first_node )] ):
          if goal_test_func( node_get_state( first_node ) ):   
             action_path = node_get_path(first_node)
             print( "\n:-)) *SUCCESS* ((-:" )
             print( "The action path to the solution is:" )
             print_action_list(action_path)
             print( "Path length = " + str( len(action_path) ) )
             print( "Total nodes tested = " + str(nodes_tested+1) )
             print( "Time taken =", time.clock() - start_time, "seconds\n" )
             return action_path
          children = node_get_children(node_expand( first_node, 
                                                    poss_act_func,
                                                    successor_func 
                                                  )
                                      )
          node_queue = add_to_node_queue(strategy, node_queue, children)
    print( "\n:-( <FAILURE> )-:" )
    print( "Search aborted --- node limit reached (MAX_NODES=%i)\n" % max_nodes )
    print( "Time taken =", time.clock() - start_time, "seconds\n" )
    return False
예제 #7
0
def print_func(arg):
    print_function(arg)
# Enter your code here. Read input from STDIN. Print output to STDOUT
from __future__ import print_function
print_function(eval(raw_input()))
예제 #9
0
    def plot(self):
        """ Process loaded histograms and draw these """

        # the main executable script should make sure only one plot is loaded:
        # /cutflow or /cutflow_no_weight
        channels = self.plots[self.plots.keys().pop()]

        signal_channels = set(["zp", "zpwide", "kk"])
        channel.expand(self._channel_config, signal_channels)

        background_channels = set(["mc"])
        channel.expand(self._channel_config, background_channels)

        signal_ = {}
        background_ = {}
        total_background_ = None
        data_ = None
        for channel_, hist in channels.items():
            if channel_ in signal_channels:
                signal_[channel_] = cutflow(hist)
            elif channel_ in background_channels:
                background_[channel_] = cutflow(hist)
                if not total_background_:
                    total_background_ = hist.Clone()
                else:
                    total_background_.Add(hist)
            elif channel_ == "data":
                data_ = cutflow(hist)

        total_background_ = cutflow(total_background_)

        channel_names = (
            {
                "zprime_m1000_w10": r"Z' 1 Tev/c\textsuperscript{2}",
                "zprime_m2000_w20": r"Z' 2 Tev/c\textsuperscript{2}",
                "zprime_m3000_w30": r"Z' 3 Tev/c\textsuperscript{2}",
                "stop": r"Single-Top",
                "zjets": r"$Z/\gamma^{\ast}\rightarrow l^{+}l^{-}$",
                # "wjets": r"$W\rightarrow l\nu$",
                "wb": r"$W\rightarrow l\nu$ (bX)",
                "wc": r"$W\rightarrow l\nu$ (cX)",
                "wlight": r"$W\rightarrow l\nu$ (lightX)",
                "ttbar": r"QCD $t\bar{t}$",
            }
            if "text" != self._print_mode
            else {
                "zprime_m1000_w10": r"Z' 1 Tev",
                "zprime_m2000_w20": r"Z' 2 Tev",
                "zprime_m3000_w30": r"Z' 3 Tev",
                "stop": r"Single-Top",
                "zjets": r"Z/gamma -> l+ l-",
                # "wjets": r"W -> l nu",
                "wb": r"W-> l nu (bX)",
                "wc": r"W-> l nu (cX)",
                "wlight": r"W-> l nu (lightX)",
                "ttbar": r"QCD ttbar",
            }
        )

        print_function = print_cutflow_in_text if self._print_mode == "text" else print_cutflow_in_tex

        fields_to_print = [["jets", "electron", "veto_lepton", "twod_cut"], ["jet1", "htlep", "tricut", "met"]]
        if self._non_threshold:
            fields_to_print.append(["chi2", "non_threshold", "eff"])
            for samples_cutflow_ in (signal_, background_):
                if not samples_cutflow_:
                    continue

                for channel_, cutflow_ in samples_cutflow_.items():
                    cutflow_["eff"] = efficiency(cutflow_.get("non_threshold", 0), cutflow_.get("chi2", 0))

            for cutflow_ in (total_background_, data_):
                cutflow_["eff"] = efficiency(cutflow_.get("non_threshold", 0), cutflow_.get("chi2", 0))

        for fields in fields_to_print:
            print_function(None, None, fields)

            for channel_ in self._channel_config["order"]:
                if not channel_.startswith("zprime") or channel_ not in signal_:

                    continue

                print_function(channel_names.get(channel_, channel_), signal_[channel_], fields)

            for channel_ in ["stop", "zjets", "wb", "wc", "wlight", "ttbar"]:
                if channel_ not in background_:
                    continue

                print_function(channel_names.get(channel_, channel_), background_[channel_], fields)

            print_function("Total MC", total_background_, fields)

            if data_:
                print_function("Data 2011", data_, fields)

            print()

        return None
예제 #10
0
def prettyDict(input_dict, indent=0, print_function=print):
    """Prints a directory."""
    for key, value in input_dict.items():
        print_function('\t' * indent + str(key)+' :\t' + str(value))