Пример #1
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
Пример #2
0
class CPT(object):
    "Code Point Table."

    def _preinit(self):
        "Internal function for initializing the lookup table"
        self.base, self.data = [1, [[0] * self.size, [0] * self.size]]

    def __init__(self):
        "Setup sizing, lookup table, and redo dictionary"
        self.snip = Cut()
        self.size = self.snip.the.enum
        self._preinit()
        self.redo = {}

    def __setitem__(self, glyph, table):
        "Set the table number for the glyph.  TODO develop __delitem__  method"
        codepoint = glyph if isinstance(glyph, int) else ord(glyph)
        this, cuts = [1, self.snip.cut(codepoint)]
        self.redo[codepoint] = table
        for segment in cuts[:-1]:
            N = len(self.data)
            if self.data[this][segment] == 0:
                if this < self.base:
                    self.data[this][segment] = table
                else:
                    self.data[this][segment] = N
                    self.data.append([0] * self.size)
                    this = N
            else:
                this = self.data[this][segment]
        self.data[this][cuts[-1]] = -table

    def __getitem__(self, glyph):
        "Get the table number for the glyph"
        codepoint = glyph if isinstance(glyph, int) else ord(glyph)
        cuts = self.snip.cut(codepoint)
        this = 1
        for segment in cuts:
            this = self.data[this][segment]
        return -this

    def __delitem__(self, glyph):
        "Remove glyph:table association from lookup table"
        codepoint = glyph if isinstance(glyph, int) else ord(glyph)
        present = self[codepoint]
        if present != 0:
            del self.redo[codepoint]  # Eliminate codepoint from lookup table
            self._preinit()  # Initialize the lookup table
            for codepoint, table in self.redo.iteritems():
                self[codepoint] = table  # Refill the lookup table

    def __len__(self):
        "Return the count of glyphs available for lookup"
        return len(self.redo.keys())
Пример #3
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
Пример #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 __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]
Пример #7
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
Пример #8
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
Пример #9
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()
Пример #10
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
Пример #11
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
Пример #12
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()
Пример #13
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
Пример #14
0
	def __init__(self,selectedObject):
		Cut.__init__(self,selectedObject)
Пример #15
0
 def __init__(self):
     "Setup sizing, lookup table, and redo dictionary"
     self.snip = Cut()
     self.size = self.snip.the.enum
     self._preinit()
     self.redo = {}
Пример #16
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
Пример #17
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]
 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"
     )
Пример #19
0
class Digit(list):
    """
    This class ingests UnicodeData.txt and organizes digits from all languages
    into an efficient search tree for conversions.
    """

    class UnicodeDataLine(dict):
        """
        This class supports turning a line into a Unicode compliant dictionary.
        """

        def __init__(self, columnNames):
            self.__dict__ = self
            self.columnNames = columnNames

        def __call__(self, line):
            if not line:
                return False
            line = line.split(';')
            if len(line) != len(self.columnNames):
                return False
            self.update(dict(zip(self.columnNames, line)))
            return True

    def _columnNameIngest(self):
        """ftp://ftp.unicode.org/Public/3.0-Update/UnicodeData-3.0.0.html
        Column names are hand copied from this URL changing ' ' and '.' to '_',
        and changing 10646_comment_field to comment_field_10646,
        and changing column 0 to its common name: Codepoint.
        It is possible to extract column names using BeautifulSoup but
        the added complexity over using manifest constants is not merited.
        The alternative is to use BeautifulSoup to extract column names from
        TR44 which is organized poorly for column name extraction.
        These names become member names in a UnicodeDataLine instance.
        This considerably simplifies maintenance relative to the publications.
        """
        Unicode_3_0_0_columns = """
Codepoint
Character_name
General_Category
Canonical_Combining_Classes
Bidirectional_Category
Character_Decomposition_Mapping
Decimal_digit_value
Digit_value
Numeric_value
Mirrored
Unicode_1_0_Name
comment_field_10646
Uppercase_Mapping
Lowercase_Mapping
Titlecase_Mapping
        """
        columnNames = Unicode_3_0_0_columns.strip().split('\n')
        self.line = Digit.UnicodeDataLine(columnNames)

    def _digitDataIngest(self):
        "Get data from unicode.org file from which to create tables"
        with open("local/UnicodeData.txt") as source:
            while True:
                if not self.line(source.readline()):
                    break
                if self.line.General_Category == 'Nd':
                    codepoint = int(self.line.Codepoint, 0x10)
                    digit = int(self.line.Digit_value)
                    languageparts = self.line.Character_name.split(' ')[:-2]
                    language = ' '.join(languageparts)
                    if language.strip() == "":
                        language = 'ASCII'
                    self.codepointToLanguage[codepoint] = language
                    self.codepointToDigit[codepoint] = digit
                    self.integerToCodepointList[digit].append(codepoint)
                    if self.wide or codepoint < 0x10000:  # unichr restriction
                        temp = self.languageToDigits.get(language, "")
                        self.languageToDigits[language] = temp
                        self.languageToDigits[language] += unichr(codepoint)

    def _ingest(self):
        "get data to initialize the tables"
        if self.kw.get('ingest', False):
            self.integerToCodepointList = {i: [] for i in range(10)}
            self.codepointToDigit = {}
            self.codepointToLanguage = {}
            self.languageToDigits = {}

            self._columnNameIngest()
            self._digitDataIngest()

            if self.verbose:
                print(str(self.integerToCodepointList))
            for integer in self.integerToCodepointList.keys():
                for character in self.integerToCodepointList[integer]:
                    self(character, integer)
        elif self.kw.get('unique', False):
            for integer, character in enumerate(u"0123456789"):
                self(ord(character), integer)
        else:
            for integer, character in enumerate(u"0123456789"):
                self(ord(character), integer)
            for integer, character in enumerate(u"௦௧௨௩௪௫௬௭௮௯"):
                self(ord(character), integer)
        return self

    def sequence(self, language=None):
        "Generate the digit string '0-9' for a given language"
        if language is None:
            return self.languageToDigits.keys()
        return self.languageToDigits.get(language, "unknown")

    def whatLanguageIs(self, codepoint):
        "Return the language block name associated with a codepoint"
        if isinstance(codepoint, type(u"")):
            codepoint = ord(codepoint)
        return self.codepointToLanguage.get(codepoint, 'Unknown')

    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

    def __call__(self, glyph, digit=-1):
        """
        functor to either add digit codepoint pairs or find codepoint digits
        TODO fix this to use CPT mechanism to follow DRY principle.
        """
        codepoint = glyph if isinstance(glyph, int) else ord(glyph)
        this = 10
        if digit == -1:
            # get mode
            cuts = self.preIndex.cut(codepoint)
            for segment in cuts:
                this = self[this][segment]
                if this < self.preIndex.the.base:
                    return this
            return digit
        else:
            # put mode
            cuts = self.preIndex.cut(codepoint)
            if self.verbose:
                print("    INSERT %d %06x %s" % (digit, codepoint, cuts))
            for segment in cuts[:-1]:
                N = len(self)
                if self[this][segment] == -1:
                    if this < self.preIndex.the.base:
                        self[this][segment] = digit
                    else:
                        self[this][segment] = N
                        self.append([-1] * self.preIndex.the.enum)
                        this = N
                else:
                    this = self[this][segment]
                if self.verbose:
                    print 'self[%d][%d] = %d' % (this, segment, this)
            self[this][cuts[-1]] = digit

    def productions(self):
        "create javascript usable content"
        show = u"""
document.jlettvin = {};
document.jlettvin.unidigit = {
/** Digit tables for handling digits in all Unicode supported alphabets.
Unicode strings containing numbers may be converted to integer,
arithmetic operations may be performed,
and the result output generated in the alphabet of choice.
Digits may be freely intermixed in number strings.
 */
"""

        # TODO Fix the bug in this code
        show += u"var integerToCodepointList = [\n    "
        show += u',\n    '.join([
            u"%d => %s" % (i, str(self.integerToCodepointList[i]))
            for i in range(10)])
        show += u"\n];\n"

        show += u"var codepointToDigit = [\n    "
        show += u'\n    '.join([
            u"0x%06x => '%d'" % (k, w)
            for k, w in self.codepointToDigit.iteritems()])
        show += u"\n];\n"

        show += u"var codepointToLanguage = [\n    "
        show += u',\n    '.join([
            u"0x%06x => '%s'" % (k, w)
            for k, w in self.codepointToLanguage.iteritems()])
        show += u"\n];\n"

        show += u"var languageToDigits = [\n    "
        show += u',\n    '.join([
            u"'%s' => '%s'" % (k, w)
            for k, w in self.languageToDigits.iteritems()])
        show += u"\n];\n"

        show += u"var digitLookup = [\n    "
        show += u',\n    '.join([
            u"%3d => %s" % (index, str(page))
            for index, page in enumerate(self)])
        show += u"\n];\n"

        show += """
var cutCodepoint = function(codepoint) {
    var bits = %d;
    var mask = %d;
    var need = %d;
    var cuts = new int[need];
    for (var shft = need; shft--; ) {
        cuts[need-shft-1] = codepoint >> (shft * bits) & mask;
    }
    return cuts;
};

var asDigit = function(codepoint) {
    var cuts = cutCodepoint(codepoint);
    var this = %d;
    var base = %d;
    var done = null;
    for (var segment of cuts) {
        var this = digitLookup[this][segment];
        if (this < base) {
            done = this;
            break;
        }
    }
    cuts = null;
    return done == null ? -1 : done;
};
};
""" % ( self.bits,
        self.mask,
        self.need,
        self.preIndex.the.base,
        self.preIndex.the.base)

        return show

    def emit(self):
        "Generate javascript usable tables and function."
        with open('Digit.js', 'w+b') as target:
            UTF8Writer = codecs.getwriter('utf8')
            target = UTF8Writer(target)
            print>>target, self.productions()
        return self
Пример #20
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)
    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")
Пример #22
0
 def setUp(self):
     self.unidigit = Cut()