Пример #1
0
    def __init__(self, model):
        self.notifier = Notifier()
        self.model = model
        self.lut = vtk.vtkLookupTable()
        lut_num = model.n_levels
        self.lut.SetNumberOfTableValues(lut_num)
        ctf = vtk.vtkColorTransferFunction()
        ctf.SetColorSpaceToDiverging()
        ctf.AddRGBPoint(0.0, 0, 0, 1.0)
        ctf.AddRGBPoint(1.0, 1.0, 0, 0)
        for ii, ss in enumerate(
            [float(xx) / float(lut_num) for xx in range(lut_num)]):
            cc = ctf.GetColor(ss)
            self.lut.SetTableValue(ii, cc[0], cc[1], cc[2], 1.0)

        def get_color(node):
            return self.lut.GetTableValue(node.level)[:3]

        self.volumes = [Volume(n, get_color(n)) for n in self.model.nodes]

        plane = vtk.vtkPlane()
        plane.SetOrigin(0, 0, 0)
        plane.SetNormal(0, 0, 1)

        self.__cut_z = 0
        self.cuts = [Cut(v, plane, self.__cut_z) for v in self.volumes]
        self.cut_indicators = [CutIndicator(c) for c in self.cuts]
Пример #2
0
    def solve(self, goals, env, gvars, level):
        goal = goals.pop(0)

        if isinstance(goal, bool):
            return self.bcprove(goals, env, gvars, level + 1)
        elif isinstance(goal, tuple) and goal[0].name is "cut":
            goals.insert(0, goal[1])
            result = self.bcprove(goals, env, gvars, level + 1)
            Cut().set()
            return result

        key = self.make_key(goal)
        iteratorBcr = self.bcr[key].__iter__()

        for kbRule in iteratorBcr:
            freshRule = copy.deepcopy(kbRule)
            freshvars = self.get_variables(freshRule)

            for i in freshvars:
                i.rename(level)

            newenv = {}
            newenv.update(env)
            test = True

            for i in range(len(freshRule[0])):
                q = Unify().unify(freshRule[0][i], goal[i], newenv)

                if q is None:
                    test = False
                    break
                else:
                    newenv.update(q)

            if test:
                newgoals = copy.deepcopy(goals)
                newgoals.insert(0, freshRule[1])
                result = self.bcprove(newgoals, newenv, gvars, level + 1)

                if Cut().test() or result:
                    return result

        return False
Пример #3
0
    def prove(self, goals):
        print "?-", Printer().deref(goals, {})

        Cut().reset()
        gvars = self.get_variables(goals)
        result = self.bcprove(goals, {}, gvars, 0)

        print Printer().deref(result, {}), "\n"

        return result
Пример #4
0
 def loadDataFromCutFile(self, totalnum):
     doc = []
     cut = Cut()
     for i in range(1, totalnum):
         line = cut.getRow(i, Global.cutnews_dir, Global.filesize)
         if not line:
             break
         data = json.loads(line)
         keyword = analyse.extract_tags(data['content'], topK=20)
         seg = " ".join(keyword)
         print seg
         doc.append(seg)
     return doc
Пример #5
0
 def __init__(self, **kw):
     "Create tables"
     self.kw = kw
     self.verbose = self.kw.get('verbose', False)
     self.codepointToDigit = {}
     self.preIndex = Cut()
     self.wide = self.kw.get('wide', False)
     for _ in range(self.preIndex.the.base):
         self.append([_] * self.preIndex.the.enum)
     self.append([-1] * self.preIndex.the.enum)
     self._ingest()
     self.shape = (len(self), len(self[0]))
     if self.verbose:
         print 'table shape (%d,%d)' % self.shape
Пример #6
0
 def QueryById(self, no):
     no = int(no.decode('utf-8'))
     default = dict()
     default['title'] = "No Such News"
     default['time'] = ''
     default['content'] = "Oh No!"
     default['url'] = "#"
     if not no:
         return default
     cut = Cut()
     line = cut.getRow(no, Global.cutnews_origin_dir, Global.filesize)
     if line:
         data = json.loads(line)
         return data
     else:
         return default
Пример #7
0
 def QuerySingle(self, searchWord, ishow):
     if self.kw_id.has_key(searchWord.decode('utf-8')):
         idx = self.kw_id[searchWord.decode('utf-8')]
         cut = Cut()
         ii_line = cut.getInverseIndexRow(idx, Global.inverse_dir,
                                          Global.filesize)
         record = json.loads(ii_line)
         if ishow:
             for rec in record:
                 line = cut.getRow(int(rec), Global.cutnews_origin_dir,
                                   Global.filesize)
                 data = json.loads(line)
                 print data['title'], '\n', data['time'], '\n', data[
                     'content'], '\n'
     #返回单个词项对应的倒排记录表
         return record
     else:
         if isshow:
             print 'Not Exists Record!'
         #调用该函数后需要对结果进行判断
         return dict()
Пример #8
0
 def QueryPhrase(self, searchPhrase, isshow=True):
     words = jieba.cut(searchPhrase.decode('utf-8'), cut_all=False)
     cut = Cut()
     result = set(range(1, 100000))
     for word in words:
         if not self.kw_id.has_key(word):
             print 'Not Exist Record'
             return set()
         idx = self.kw_id[word]
         ii_line = cut.getInverseIndexRow(idx, Global.inverse_dir,
                                          Global.filesize)
         record = json.loads(ii_line)
         re = set()
         for rec in record:
             re.add(int(rec))
         result = result & re
     if len(result) == 0:
         print 'Not Exists Record!'
     newslist = list()
     count = 0
     for rst in result:
         count += 1
         if count > Global.listsize:
             break
         line = cut.getRow(int(rst), Global.cutnews_origin_dir,
                           Global.filesize)
         data = json.loads(line)
         if isshow:
             print data['title'], '\n', data['time'], '\n', data[
                 'content'], '\n'
         tm = time.localtime(int(data['time']))
         data['time'] = time.strftime('%Y-%m-%d %H:%M:%S', tm)
         data['content'] = data['content'][0:Global.snippetsize]
         data['id'] = rst
         newslist.append(data)
     return newslist
    def write_execute_block(self, f):
        met_filter = Cut(name="MET",
                         cpp_condition="met > 400.",
                         signal_region="Signal")

        at_least_one_lepton = Cut(name="at least one lepton",
                                  cpp_condition="leptons.size() != 0",
                                  signal_region="Signal")

        lepton_trigger = Cut(name="Lepton trigger",
                             cpp_condition="leptons[0]->pt() > 100.",
                             signal_region="Signal")

        pt_eta_cut = Cut(name="pt_eta_cuts",
                         cpp_condition="pt_eta_condition == true",
                         signal_region="Signal")

        two_leptons = Cut(name="2 leptons",
                          cpp_condition="leptons.size() == 2",
                          signal_region="Signal")

        SF_leptons = Cut(name="SF leptons",
                         cpp_condition="electrons.size() != 1",
                         signal_region="Signal")

        OS_leptons = Cut(
            name="OS leptons",
            cpp_condition="leptons[0]->charge() != leptons[1]->charge()",
            signal_region="Signal")

        two_b_jets = Cut(name="2 b jets",
                         cpp_condition="b_jets.size() > 1",
                         signal_region="Signal")

        # PT and Eta conditions
        pt_eta_condition = """\

    bool pt_eta_condition = true;

    for (unsigned int i = 0; i < leptons.size(); i++) {
        if (leptons[i]->pt() < 15. or fabs(leptons[i]->eta()) > 2.5) pt_eta_condition = false;
    }

    for (unsigned int i = 0; i < b_jets.size(); i++) {
        if (b_jets[i]->pt() < 30. or fabs(b_jets[i]->eta()) > 2.5) pt_eta_condition = false;
    }

    """

        # MET definition
        met_definition = """\
    RecParticleFormat met_particle = event.rec()->MET();
    double met = met_particle.pt();
    MAVector3 met_vector = met_particle.momentum().Vect(); 
    """

        # Invariant mass definitions
        invariant_mass_definitions = """\
    // Z and h candidates
    ParticleBaseFormat Z_candidate = leptons[0]->momentum()+leptons[1]->momentum();
    ParticleBaseFormat h_candidate = b_jets[0]->momentum() + b_jets[1]->momentum();
    double m_ll = Z_candidate.m();
    double m_bb = Z_candidate.m();
    """

        razor_variable_definitions = """\

    ParticleBaseFormat q_1, q_2;
    q_1 = Z_candidate.momentum(); q_2 = h_candidate.momentum();

    MAVector3 q_12T = MAVector3(Z_candidate.px()+h_candidate.px(),
                                Z_candidate.py()+h_candidate.py(),
                                0.);

    double E_1, E_2, q_1z, q_2z, m_R, m_T_R, R_squared;

    E_1 = Z_candidate.e(); E_2 = h_candidate.e();
    q_1z = Z_candidate.pz(); q_2z = h_candidate.pz();

    m_R = sqrt( pow(E_1 + E_2, 2) - pow(q_1z + q_2z, 2)); 
    m_T_R = sqrt(.5*(met*(q_1.pt()+q_2.pt()) - met_vector.Dot(q_12T)));
    R_squared = pow(m_T_R/m_R, 2); 

    """
        self.write_pre_execute(f)

        at_least_one_lepton.write(f, self.cuts)
        lepton_trigger.write(f, self.cuts)

        f.write(pt_eta_condition)
        pt_eta_cut.write(f, self.cuts)

        two_leptons.write(f, self.cuts)
        SF_leptons.write(f, self.cuts)
        OS_leptons.write(f, self.cuts)
        two_b_jets.write(f, self.cuts)

        f.write(met_definition)
        f.write(invariant_mass_definitions)
        f.write(razor_variable_definitions)

        variables = ['met', 'm_ll', 'm_bb', 'm_R', 'm_T_R']

        for var in variables:
            f.write(var + 's.push_back({});\n'.format(var))

        f.write("\t return true;\n")
        f.write("}\n\n")
Пример #10
0
 def apply(self):
     ui = self.defineJobUi
     if self.selectedObject == None:
         obj = FreeCAD.ActiveDocument.addObject(
             'App::DocumentObjectGroupPython', "GCodeJob")
         ViewGCode(obj.ViewObject)
         self.selectedObject = obj
     obj = self.selectedObject
     obj.Label = ui.nameLE.text()
     if hasattr(obj, "ObjectType") == False:
         obj.addProperty("App::PropertyString",
                         "ObjectType").ObjectType = "GCodeJob"
     if hasattr(obj, 'ToolTable') == False:
         obj.addProperty("App::PropertyString", "ToolTable")
     obj.ToolTable = ui.toolTableCB.currentText()
     if hasattr(obj, 'WorkPiece') == False:
         obj.addProperty("App::PropertyString", "WorkPiece")
     obj.WorkPiece = ui.workpieceCB.currentText()
     if hasattr(obj, 'XOrigin') == False:
         obj.addProperty("App::PropertyString", "XOrigin")
     obj.XOrigin = ui.xaxisCB.currentText()
     if hasattr(obj, 'XOriginValue') == False:
         obj.addProperty("App::PropertyDistance", "XOriginValue")
     obj.XOriginValue = VAL.toSystemValue(ui.xaxisLE, 'length')
     if hasattr(obj, 'YOrigin') == False:
         obj.addProperty("App::PropertyString", "YOrigin")
     obj.YOrigin = ui.yaxisCB.currentText()
     if hasattr(obj, 'YOriginValue') == False:
         obj.addProperty("App::PropertyDistance", "YOriginValue")
     obj.YOriginValue = VAL.toSystemValue(ui.yaxisLE, 'length')
     if hasattr(obj, 'ZOrigin') == False:
         obj.addProperty("App::PropertyString", "ZOrigin")
     obj.ZOrigin = ui.zaxisCB.currentText()
     if hasattr(obj, 'ZOriginValue') == False:
         obj.addProperty("App::PropertyDistance", "ZOriginValue")
     obj.ZOriginValue = VAL.toSystemValue(ui.zaxisLE, 'length')
     for cut in obj.Group:
         FreeCAD.ActiveDocument.removeObject(cut.Name)
     for line in self.cutList:
         for prop in line:
             if prop[1] == "CutType":
                 if prop[2] == "Registration": cut = RegistrationCut(obj)
                 elif prop[2] == "Drill": cut = DrillCut(obj)
                 elif prop[2] == "Facing": cut = FaceCut(obj)
                 elif prop[2] == "Perimeter": cut = PerimeterCut(obj)
                 elif prop[2] == "Pocket2D": cut = Pocket2DCut(obj)
                 elif prop[2] == "Volume2D": cut = Volume2DCut(obj)
                 elif prop[2] == "Pocket3D": cut = Pocket3DCut(obj)
                 elif prop[2] == "Volume3D": cut = Volume3DCut(obj)
                 elif prop[2] == "Surface3D": cut = Surface3DCut(obj)
                 else: cut = Cut(obj)
         cut.getObject().Label = ui.nameLE.text()
         cut.setProperties(line, cut.getObject())
     if hasattr(obj, "OutputUnits") == False:
         obj.addProperty("App::PropertyString", "OutputUnits")
     if ui.metricRB.isChecked() == True: obj.OutputUnits = 'METRIC'
     else: obj.OutputUnits = 'IMPERIAL'
     if hasattr(obj, "OutputFile") == False:
         obj.addProperty("App::PropertyString", "OutputFile")
     obj.OutputFile = ui.outFileL.text()
     self.dirty = False
     ui.runB.setEnabled(True)
Пример #11
0
 def __init__(self):
     "Setup sizing, lookup table, and redo dictionary"
     self.snip = Cut()
     self.size = self.snip.the.enum
     self._preinit()
     self.redo = {}
Пример #12
0
 def setUp(self):
     self.unidigit = Cut()
 def m_T_R_cut(m_T_R):
     return Cut(
         name = "m_T_R", 
         cpp_condition = "m_T_R > {}".format(str(m_T_R)), 
         signal_region = "Signal"
     )
Пример #14
0
    def split(self, axis_name, rightmost_of_left_bins,
              discriminator_axis_child_0, discriminator_axis_child_1):
        """ Split a node using a cut on axis iaxis (index with respect
        to the list of axes: axes) at the bin number
        rightmost_of_left_bins. As the name implies the bin will be
        included in the 'left hand side' of the cut.

        Opposite of merge function
        
        Return nothing on success

        Return -1 if the requested splitting is impossible
        (because it is out of range or because previous cuts on
        ancestors of the node already exclude the requested region)
        """

        # Init all other boundaries with sanity check
        leftmost_of_left_bins = 1
        leftmost_of_right_bins = rightmost_of_left_bins + 1
        if leftmost_of_right_bins > self.axes[axis_name].nbins:
            if self.verbose:
                print "Invalid subdivision, leftmost_of_right_bins > self.axes[axis_name].nbins"
            return -1
        rightmost_of_right_bins = self.axes[axis_name].nbins

        # Get the list of all previous cuts on the ancestors
        # the order here is imporant - we have to execute the cuts from
        # TOP to BOTTOM
        # so the TIGHTEST cut on a given axis comes LAST
        all_previous_cuts = [p.cut for p in self.all_parents()] + [self.cut]

        # Loop over cuts to apply previous constraints
        for c in all_previous_cuts:
            # Make sure the cut is defined (ignore the root node) and
            # modifies the axis we are testing right now
            if c and c.axis.name == axis_name:

                if c.lo > leftmost_of_left_bins:
                    leftmost_of_left_bins = c.lo
                if c.lo > rightmost_of_left_bins:
                    rightmost_of_left_bins = c.lo

                if c.hi < leftmost_of_right_bins:
                    leftmost_of_right_bins = c.hi
                if c.hi < rightmost_of_right_bins:
                    rightmost_of_right_bins = c.hi
        # End of loop over cuts

        # Sanity check: make sure our cut is still doable after the
        # preselections have been applied
        if leftmost_of_right_bins <= rightmost_of_left_bins:
            if self.verbose:
                print "leftmost_of_right_bins <= rightmost_of_left_bins"
            return -1
        if leftmost_of_right_bins > self.axes[axis_name].nbins:
            if self.verbose:
                print "Invalid subdivision, leftmost_of_right_bins > self.axes[axis_name].nbins"
            return -1

        # Sanity check if the requested discriminator variable is defined for both children
        # First get all the cuts, including the one we would apply for the children
        all_cuts_child_0 = all_previous_cuts + [
            Cut(axis_name, leftmost_of_left_bins, rightmost_of_left_bins)
        ]
        all_cuts_child_1 = all_previous_cuts + [
            Cut(axis_name, leftmost_of_right_bins, rightmost_of_right_bins)
        ]

        # Get the prerequisites for the requested discriminators
        if not discriminator_axis_child_0 is None:
            prereqs_for_child_0 = self.axes[
                discriminator_axis_child_0].discPrereq
            if not all([
                    any([c.is_subset_of(p) for c in all_cuts_child_0])
                    for p in prereqs_for_child_0
            ]):
                return -1
        if not discriminator_axis_child_1 is None:
            prereqs_for_child_1 = self.axes[
                discriminator_axis_child_1].discPrereq
            if not all([
                    any([c.is_subset_of(p) for c in all_cuts_child_1])
                    for p in prereqs_for_child_1
            ]):
                return -1

        # We want for ALL prerequisits that at LEAST ONE is as tight as the prerequiste
        # all([]) returns True - so this also works if there are no prerequs

        # And finally: actually spawn two new children and add the Nodes to the tree
        child_pass = Categorization(
            Cut(axis_name, leftmost_of_left_bins, rightmost_of_left_bins),
            parent=self,
            discriminator_axis=discriminator_axis_child_0)
        child_fail = Categorization(
            Cut(axis_name, leftmost_of_right_bins, rightmost_of_right_bins),
            parent=self,
            discriminator_axis=discriminator_axis_child_1)

        self.children = [child_pass, child_fail]
Пример #15
0
def CategorizationFromString(string):
    """Build the whole cutflow tree from a string and return the root
    node. Works with the output of print_tree.    
    """

    r = Categorization(Cut())

    last_depth = 0
    last_node = r

    for line in string.split("\n"):

        # remove the first character - it's usually a space (we count
        # the depth by how indented the line is and one space is extra
        # offset)
        line = line[1:].rstrip()
        depth = line.count("   ")

        # Now split by spaces, if nothing remains, ignore this line
        line_atoms = [x for x in line.split(' ') if x]
        if not line_atoms:
            continue

        # Take the first piece of the text - this should now be the cutstring
        cut_string = line_atoms[0]

        # For the first entry we don't have a cutstring
        # just set the discriminator variable of the ROOT node correctly
        if "Discr" in cut_string:
            discriminator = cut_string.split("=")[1]
            last_node.discriminator_axis = discriminator
            continue

        # Otherwise the discriminator will be the second item
        discriminator = line_atoms[1].split("=")[1]
        if discriminator == "None":
            discriminator = None

        # If we also have a rebinning prescription
        if len(line_atoms) > 2:
            rebin = int(line_atoms[2].split("=")[1])
        else:
            rebin = 0

        # Build the cut object from the string
        cut = Cut(cut_string)

        # Here the real fun starts
        # - if the depth icreased by one, we do a splitting
        if depth > last_depth:
            last_node.split(cut.axis.name, cut.hi, discriminator,
                            discriminator)
            last_node = last_node[0]
            last_depth = depth
        # - if the depth stayed the same we go to the other child
        elif depth == last_depth:
            last_node = last_node.parent[1]
        # - and if the depth decreased
        #     we first go out the appropriate amount
        #     and then switch to the other child
        elif depth < last_depth:
            for _ in range(last_depth - depth):
                last_node = last_node.parent
            last_node = last_node.parent[1]
            last_depth = depth
        last_node.discriminator_axis = discriminator
        last_node.rebin_discriminator = rebin

    # End of loop over lines

    return r