Example #1
0
def idFromTable(infc, outfc, inField, outIdField, outPrefixField):
	tab.copy(infc, outfc)
	tables = rd.tables()
	arcpy.management.AddField(tables[outfc], outIdField, 'TEXT')
	arcpy.management.AddField(tables[outfc], outPrefixField, 'TEXT')

	with arcpy.da.UpdateCursor(tables[outfc], (inField, outIdField, outPrefixField)) as cursor:
		for row in cursor:
			inSplit =  row[0].split('[')[1].split(']')[-2]
			fid = None
			prefix = None
			if 'CD' in inSplit:
				fid = inSplit.split('CD')[1]
				fid = fid[0:2] + fid[4:]
				fid = fid[0:4]
				prefix = 'CD'
			elif 'CCS' in inSplit:
				fid = inSplit.split('CCS')[1]
				fid = fid[0:2] + fid[4:]
				prefix = 'CCS'
			elif 'CAR' in inSplit:
				fid = inSplit.split('CAR')[1]
				prefix = 'CAR'
			elif 'PR' in inSplit:
				fid = inSplit.split('PR')[1]
				prefix = 'PR'
			else:
				fid = inSplit
				prefix = 'CO'
			
			# print fid
			row[1] = fid
			row[2] = prefix
			cursor.updateRow(row)
Example #2
0
def extractId(infc, outfc, extractFields):
	tab.copy(infc, outfc)
	with arcpy.da.SearchCursor(outfc, ['geo']) as cursor:
		for row in sorted(cursor):
			fid =  row[0].split('[')[1].split(']')[0]
			splitId = fid.split('CD')
			if len(splitId) > 1:
				print splitId[1]
Example #3
0
    def createSubDomainTables(self, run, projections, tables):
        """If there are SubDomains represented by the projections in the
           run but not in any tables in that run, this function will create
           a table containing just the IDs for each SubDomain. This is
           calculated by performing all possible projections into that
           unrepresented Subdomain and taking the union of the results.
        """
        # Determine which subdomains are not covered by tables
        uncovered_subdomains = set(run._projection_subdomains) \
            - set(run._table_subdomains)
        for subdomain in uncovered_subdomains:
            # Find projections that cover this subdomain 
            projection_list = list()
            for projection in projections._children:
                if (subdomain == projection._projection.source
                    or subdomain == projection._projection.destination):
                    projection_list.append(projection._projection)

            # Create a Table Meta Information
            greater_subdomain = SubDomain.instantiate(subdomain)
            table_meta = dict()
            table_meta['filetype'] = 'table'
            table_meta['domain'] = greater_subdomain.domain()
            table_meta['type'] = greater_subdomain.typename()
            table_meta['flags'] = 0
            table_meta['field'] = table_meta['type'] + "_id"
            # Find a list of IDs for this subdomain from those projections
            id_list = list()
            for projection in projection_list:

                if subdomain == projection.source:
                    ids = projection.source_ids()
                    if isinstance(projection, TableProjection):
                        # If there's a TableProjection, use that field name
                        # instead
                        table_meta['field'] = projection._source_key
                else: # destination
                    ids = projection.destination_ids()
                    if isinstance(projection, TableProjection):
                        table_meta['field'] = projection._destination_key

                if ids is not None:
                    id_list.extend(ids)

            id_list = list(set(id_list))

            # Create Table
            data = np.rec.fromrecords([(x,) for x in id_list])
            data.dtype.names = (table_meta['field'],)
            atable = Table()
            atable.fromRecArray(greater_subdomain, table_meta['field'], data)

            # Insert Table
            self.insertTable(subdomain, atable, table_meta, \
                parent = self.createIndex(tables.childCount(), 0, tables))

            # Update subdomain list
            run._table_subdomains.append(subdomain)
	def __init__(self):

		self.table = Table(1212, 634)

		self.whiteBall =  BilliardBall(0, 18, Point2D(0,0))
		self.yellowBall = BilliardBall(1, 1, Point2D(0,0))
		self.blueBall =   BilliardBall(2, 18, Point2D(0,0))
		self.redBall =    BilliardBall(3, 1, Point2D(0,0))
		self.purpleBall = BilliardBall(4, 1, Point2D(0,0))
		self.orangeBall = BilliardBall(5, 18, Point2D(0,0))
		self.greenBall =  BilliardBall(6, 18, Point2D(0,0))
		self.brownBall =  BilliardBall(7, 18, Point2D(0,0))
		self.blackBall =  BilliardBall(8, 18, Point2D(0,0))
		self.strYellowBall = BilliardBall(9, 18, Point2D(0,0))
		self.strBlueBall =   BilliardBall(10, 1, Point2D(0,0))
		self.strRedBall =    BilliardBall(11, 1, Point2D(0,0))
		self.strPurpleBall = BilliardBall(12, 1, Point2D(0,0))
		self.strOrangeBall = BilliardBall(13, 1, Point2D(0,0))
		self.strGreenBall =  BilliardBall(14, 1, Point2D(0,0))
		self.strBrownBall =  BilliardBall(15, 1, Point2D(0,0))

		self.balls = [ self.whiteBall,  self.yellowBall, \
		               self.blueBall,   self.redBall, \
		               self.purpleBall, self.orangeBall, \
		               self.greenBall,  self.brownBall, \
		               self.blackBall,      self.strYellowBall, \
		               self.strBlueBall,   self.strRedBall, \
		               self.strPurpleBall, self.strOrangeBall, \
		               self.strGreenBall,  self.strBrownBall]
Example #5
0
    def DrawTopRecPlots(self, Data):
        dataType = type( Data )
        data = dataType. __getattribute__(Data , self.Channel)
        self.t_TopRecPropertiesLinks = Table(False)
        TheRow = RowObject()
        PropertiesLinks = {}
        for Property in self.AllTopRecStacks.keys():
            stack_prop = self.AllTopRecStacks[Property]
            hPropd = data.AllTopRecPlots[Property]
                
            ImgFileName = 'bbb'+ Property
            ImgFileName = ImgFileName.replace("_", 'z')
            TotalDiff = self.DrawAndSave(stack_prop, hPropd, ImgFileName ,0)
            
            TheRow[Property] = '@<a id="%(id)s" href="%(file)s" class="highslide" onclick="return hs.expand(this)">%(PropName)s@</a>' % {'file':self.Channel + '/' + ImgFileName + '.gif' , 'id':(Property).replace('_', 'x') , 'PropName':Property}


        stack_prop = self.stack_NPrVtxAll
        hPropd = data.NPrVtxAll
        
        ImgFileName = 'bbbNPrVtxAll'
        TotalDiff = self.DrawAndSave(stack_prop, hPropd, ImgFileName , 0)
        TheRow['NPrVtxAll'] = '@<a id="%(PropName)s" href="%(file)s" class="highslide" onclick="return hs.expand(this)">%(PropName)s@</a>' % {'file':self.Channel + '/' + ImgFileName + '.gif' ,  'PropName':Property}        

        stack_prop = self.stack_NPrVtxAllNoW
        hPropd = data.NPrVtxAllNoW      
        ImgFileName = 'bbbNPrVtxAllNoW'
        TotalDiff = self.DrawAndSave(stack_prop, hPropd, ImgFileName , 0)
        TheRow['NPrVtxAllNoW'] = '@<a id="%(PropName)s" href="%(file)s" class="highslide" onclick="return hs.expand(this)">%(PropName)s@</a>' % {'file':self.Channel + '/' + ImgFileName + '.gif' ,  'PropName':Property}        

        self.t_TopRecPropertiesLinks.append( TheRow )
        return self.t_TopRecPropertiesLinks
Example #6
0
    def DrawAllProperties(self , Data):
        dataType = type( Data )
        data = dataType. __getattribute__(Data , self.Channel)
        self.t_PropertiesLinks = Table(False)
        PropertiesLinks = {}
        for Property in self.PropertiesToDraw.keys():
            PropertiesLinks[Property] = RowObject()
            
            PropertiesLinks[Property]['0-Property'] = Property
            
            for CutID in sorted(self.AllSortedDirectories.keys()):
                Cut = self.AllSortedDirectories[CutID]
                stack_prop = self.PropertiesToDraw[Property][Cut]
                hPropd = data.PropertiesToDraw[Property][Cut]
                if Cut == '':
                    stack_prop.SetTitle( '%(Channel)s : after pair choose' % {'Channel':self.Channel } )
                else:
                    stack_prop.SetTitle( '%(Channel)s : after cut on  %(Cut)s' % {'Channel':self.Channel, 'Cut':Cut  } )
                    
                ImgFileName = 'aaa'+ str(CutID)+ "_" +Cut+  "_"  + Property
                ImgFileName = ImgFileName.replace("_", 'z')
                TotalDiff = self.DrawAndSave(stack_prop, hPropd, ImgFileName , 0)
                               
                PropertiesLinks[Property]['%(ID)d-%(Name)s'%{'ID':CutID+1 , 'Name':Cut}] = '@<a id="%(id)s" href="%(file)s" class="highslide" onclick="return hs.expand(this)">%(Diff)d@</a>' % {'file':self.Channel + '/' + ImgFileName + '.gif' , 'id':(Cut+'_'+Property).replace('_', 'x') , 'Diff':TotalDiff}
                CutID = CutID+1

            self.t_PropertiesLinks.append( PropertiesLinks[Property] )
        return self.t_PropertiesLinks
Example #7
0
	def new_table(self, aggregate_func = lambda a,b: None, empty_total = None, cmp_func = cmp):
		new_policy = {
			'serialize' : self.policy['serialize'],
			'deserialize' : self.policy['deserialize'],
			'cmp' : cmp_func,
			'aggregate' : aggregate_func
		}
		return Table._Table(abtree_c.DiskTree(self.store, new_policy), cmp_func, empty_total, None, None)
Example #8
0
def parse_ANA_output(prosa_output):

    if not os.path.exists(prosa_output):
        raise 'prosa output %s is missing.' % prosa_output

    t = Table.fromFile(prosa_output)

    return N.array(t[2:]).astype(N.Float32)
Example #9
0
 def from_node(self, node):
     self.parent = node.prop('inherits')
     for hook in node.xpathEval('hooks/hook'):
         name = hook.prop('name')
         assert name
         self.hooks.append(name)
     for table in node.xpathEval('table'):
         name = table.prop('name')
         self.tables[name] = Table.new(self, name, table)
Example #10
0
def generate_tex_table(caption='My Table', header=[], columns=[], label = 'tab:mytable',sigfigs=2):
    import StringIO
    out_str_io = StringIO.StringIO()

    t = Table(len(header), caption=caption, label=label)
    t.add_header_row(header)
    t.add_data(columns, sigfigs=sigfigs)
    t.print_table(out_str_io)

    return out_str_io.getvalue()
Example #11
0
	def load(self, 
		name, 
		aggregate_func = lambda a,b: None, 
		empty_total = None,
		cmp_func = cmp):
		new_policy = {
			'serialize' : self.policy['serialize'],
			'deserialize' : self.policy['deserialize'],
			'cmp' : cmp_func,
			'aggregate' : aggregate_func
		}
		return Table._Table(self.store.load(name, new_policy), cmp_func, empty_total, None, None)
Example #12
0
	def attach(self, 
		name, 
		aggregate_func = lambda a,b: None, 
		empty_total = None,
		cmp_func = cmp):
		new_policy = {
			'serialize' : self.policy['serialize'],
			'deserialize' : self.policy['deserialize'],
			'cmp' : cmp_func,
			'aggregate' : aggregate_func
		}
		with self.lock:
			t = Table._Table(self.store.attach(name, new_policy), self, cmp_func, empty_total, None, None)
		self.tables[name] = t
		return t
Example #13
0
class FrameManager():

    def __init__(self, frames, hdd):
        self._frames = frames
        self._free_frames = frames
        self._table = Table()
        self._hdd = hdd

    def update_free_frames(self):
        self._free_frames = filter(lambda frame: not frame.is_in_use(), self._frames)

    def assign_page_to_frame(self, pcb):
        print("Attempting to Assign Page for PCB ID: " + str(pcb._id))
        pcb_pages = pcb.get_info_holder().get_hold()
        page = next(iter(filter(lambda p: not p.has_been_used(), pcb_pages)))
        pages = self._hdd.find_page(page.get_index())
        if pages:
            page = pages[0]
        policy_result = self.assign(page)
        self.update_free_frames()
        return policy_result

    def free_frame_available(self):
        return len(self._free_frames) > 0

    def empty_youngest_frame(self):
        youngest = min(self._frames, key=lambda x: x.get_life())
        self._hdd.add_to_swap(youngest)
        youngest.set_not_in_use()

    def assign(self, page):
        if self.free_frame_available():
            policy_result = self._table.put_page(page, self._frames, self._free_frames)
            print("Page successfuly assigned!")
            return policy_result
        else:
            self.empty_youngest_frame()
            self.update_free_frames()
            print("A frame became empty!")
            self.assign(page)

    def get_frames(self):
        return self._frames
Example #14
0
def WriteANTable(outUV, meta, err):
    """
    Write data in meta to AN table

     * outUV    = Obit UV object
     * meta     = dict with data meta data
     * err      = Python Obit Error/message stack to init
    """
    ################################################################
    antab = outUV.NewTable(Table.READWRITE, "AIPS AN", 1, err)
    if err.isErr:
        OErr.printErrMsg(err, "Error with AN table")
    antab.Open(Table.READWRITE, err)
    if err.isErr:
        OErr.printErrMsg(err, "Error opening AN table")
    # Update header
    antab.keys['RefDate'] = meta["obsdate"]
    antab.keys['Freq'] = meta["spw"][0][1]
    JD = UVDesc.PDate2JD(meta["obsdate"])
    antab.keys['GSTiat0'] = UVDesc.GST0(JD) * 15.0
    antab.keys['DEGPDY'] = UVDesc.ERate(JD) * 360.0
    Table.PDirty(antab)
    # Force update
    row = antab.ReadRow(1, err)
    if err.isErr:
        OErr.printErrMsg(err, "Error reading AN table")
    OErr.printErr(err)
    irow = 0
    for ant in meta["ants"]:
        irow += 1
        row['NOSTA'] = [ant[0]]
        row['ANNAME'] = [ant[1] + "    "]
        row['STABXYZ'] = [ant[2], ant[3], ant[4]]
        row['DIAMETER'] = [ant[5]]
        row['POLAA'] = [90.0]
        antab.WriteRow(irow, row, err)
        if err.isErr:
            OErr.printErrMsg(err, "Error writing AN table")
    antab.Close(err)
    if err.isErr:
        OErr.printErrMsg(err, "Error closing AN table")
Example #15
0
def AppendVLTable(infile, outfile=outfile, err=err):
    """ Copy VL table ver 1 from infile to outfile

    infile   = name of input FITS image file with VL table
    outfile  = name of output FITS image file with extant VL table
    err      = Python Obit Error/message stack
    """
    ################################################################
    # Get images
    inImage = Image.newPFImage("Input image", infile, indisk, 1, err)
    outImage = Image.newPFImage("Output image", outfile, outdisk, 1, err)
    OErr.printErrMsg(err, "Error creating image objects")
    #
    # obtain "AIPS VL" tables from each
    inTable = Image.PImageNewImageTable(inImage, 1, "AIPS VL", 1, err)
    outTable = Image.PImageNewImageTable(outImage, 3, "AIPS VL", 1, err)
    OErr.printErrMsg(err, "Error extracting AIPS VL table objects")
    # Concatenate
    Table.PConcat(inTable, outTable, err)
    OErr.printErrMsg(err, "Error concatenatinfg tables")
    print "Appended", infile, "to", outfile
Example #16
0
def PMFPrint(MFTable, image, err, file="stdout"):
    """
    Write human readable version of an MF table to a file
    
    Print contents of MF table

    * MFTable   = Input Obit MF Table
    * image     = Image being cataloged
    * err       = Python Obit Error/message stack
    * file      = Name of a file or "stdout" for terminal display
    """
    ################################################################
    # Checks
    if not Table.PIsA(MFTable):
        print("Actually ", MFTable.__class__)
        raise TypeError("MFTable MUST be a Python Obit Table")
    if not Image.PIsA(image):
        print("Actually ", image.__class__)
        raise TypeError("image MUST be a Python Obit Image")
    #
    Obit.TableMFPrint(MFTable.me, image.me, file, err.me)
Example #17
0
def PVLPrint(VLTable, image, err, file="stdout"):
    """
    Write human readable version of an VL table to a file
    
    Print contents of VL table

    * VLTable   = Input Obit VL Table, infoList member:
    *             minSNR = min SNR to select
    * image     = Image being cataloged
    * err       = Python Obit Error/message stack
    * file      = Name of a file or "stdout" for terminal display
    """
    ################################################################
    # Checks
    if not Table.PIsA(VLTable):
        print "Actually ", VLTable.__class__
        raise TypeError, "VLTable MUST be a Python Obit Table"
    if not Image.PIsA(image):
        print "Actually ", image.__class__
        raise TypeError, "image MUST be a Python Obit Image"
    #
    Obit.TableVLPrint(VLTable.me, image.me, file, err.me)
Example #18
0
 def readData(self, name):
     f = open(name, 'r')
     r = f.readline()
     while (r != ''):
         temp_list = r.split()
         if (temp_list[0] == 'CREATE'):
             attributes = f.readline().split()
             self.__tables.insert(len(self.__tables),
                                  Table.table(attributes, temp_list[1]))
         else:
             i = 0
             for value in temp_list:
                 if value[0] != "'":
                     temp_list[i] = int(temp_list[i])
                 '''
                 else:
                     temp_list[i] = value[1:len(value)-1]
                 '''
                 i += 1
             current_table = self.__tables[len(self.__tables) - 1]
             current_table.insert(temp_list)
         r = f.readline()
Example #19
0
 def Insert(self, evt):
     L = self.helper.getMaxBookID()
     if L != None:
         BookID = int(L[0]) + 1
     else:
         BookID = 10000
     Name = self.text1.GetValue()
     Author = self.text2.GetValue()
     Press = self.text3.GetValue()
     Number = self.text4.GetValue()
     Date = self.YearList[int(self.List1.GetSelection())]
     Type = self.TypeList[int(self.List3.GetSelection())]
     if Name == "" or Author == "" or Press == "" or Number == "" or Date == "" or Type == "":
         warn = wx.MessageDialog(self,
                                 message="所有信息均不能为空",
                                 caption="错误警告",
                                 style=wx.YES_DEFAULT | wx.ICON_ERROR)
         warn.ShowModal()
         warn.Destroy()
         return
     Book = Table.Book(BookID, Name, Author, Press, Date, Type, Number)
     self.helper.BookInsert(Book)
Example #20
0
def PCCScale(inCCTab, startComp, endComp, scale, err):
    """
    Scale flux densities in a CC table
    
    Flux densities of CC entries startComp through endComp are scales by scle

    * inCCTab   = Input Python TableCC
    * startComp = first (1-rel) component
    * endComp   = highest component [1-rel= 0=> all
    * scale     = flux density scaling factor
    * err       = Python Obit Error/message stack
    """
    ################################################################
    # Checks
    if not Table.PIsA(inCCTab):
        raise TypeError("inCCTab MUST be a Python Obit Table")
    if not err.IsA():
        raise TypeError("err MUST be an OErr")
    #
    Obit.ImageUtilCCScale(inCCTab.me, startComp, endComp, scale, err.me)
    if err.isErr:
        OErr.printErrMsg(err, "Error scaling CC table")
Example #21
0
def PFSPrint(FSTable, image, err, file="stdout"):
    """
    Write human readable version of an FS table to a file
    
    Print contents of FS table

    * FSTable   = Input Obit FS Table, List controls:
    *             minSNR = min SNR to select
    * image     = Image being cataloged
    * err       = Python Obit Error/message stack
    * file      = Name of a file or "stdout" for terminal display
    """
    ################################################################
    # Checks
    if not Table.PIsA(FSTable):
        print("Actually ", FSTable.__class__)
        raise TypeError("FSTable MUST be a Python Obit Table")
    if not Image.PIsA(image):
        print("Actually ", image.__class__)
        raise TypeError("image MUST be a Python Obit Image")
    #
    Obit.TableFSPrint(FSTable.me, image.me, file, err.me)
Example #22
0
def tables():
    try:
        TABLES_DATA = Table().get_all_db_data()
        EMPLOYEES_DATA = Employee().get_all_db_data()

        indexes = []
        for item in TABLES_DATA:
            indexes.append(item[0])

        RENDERED_TABLES_DATA = Employee().render(TABLES_DATA)

        return render_template("tables.html",
                               indexes=indexes,
                               EMPLOYEES_DATA=EMPLOYEES_DATA,
                               TABLES_DATA=RENDERED_TABLES_DATA,
                               error=None)
    except Exception as e:
        return render_template("tables.html",
                               indexes=[],
                               TABLES_DATA={},
                               EMPLOYEES_DATA={},
                               error="Exception has been caught: " + e.args[0])
Example #23
0
    def get_tables(self):
        """
        Extracts each table on the page and places it in a dictionary.
        Converts each dictionary to a Table object. Returns a list of
        pointers to the respective Table object(s).
        """

        raw_html = self.link.read()
        soup = BeautifulSoup(raw_html, "html.parser")
        tables = soup.findAll("table")

        # have to extract each entry using nested loops
        table_list = []
        for table in tables:
            # empty dictionary each time represents our table
            table_dict = {}
            rows = table.findAll("tr")
            # count will be the key for each list of values
            count = 0
            for row in rows:
                value_list = []
                entries = row.findAll("td")
                for entry in entries:
                    # fix the encoding issues with utf-8
                    entry = entry.text.encode("utf-8", "ignore")
                    strip_unicode = re.compile(
                        "([^-_a-zA-Z0-9!@#%&=,/'\";:~`\$\^\*\(\)\+\[\]\.\{\}\|\?\<\>\\]+|[^\s]+)"
                    )
                    entry = strip_unicode.sub(" ", entry)
                    value_list.append(entry)
                # we don't want empty data packages
                if len(value_list) > 0:
                    table_dict[count] = value_list
                    count += 1

            table_obj = Table(table_dict)
            table_list.append(table_obj)

        return table_list
Example #24
0
def PGain(inOTF, outOTF, err):
    """ Determine gain calibration for an OTF from a residual data set.

    Gain Calibration is based on the "Cal" values in the data.
    Average value of the noise Cal is computed and entered in the data. (Gain only)
    Additive values are determined from the median values of the residual data.
    Solution type controlled by calType 
    Calibration parameters are on the inOTF info member.
    "solInt"    float scalar Solution interval in days [def 10 sec].
                This should not exceed 1000 samples.  Solutions will be truncated
                at this limit.
    "minRMS"    float scalar minimum allowable fractional solution RMS [def 0.1].
                bad solutions are replaced with pervious good value. [Gain soln]
    "calJy"     float array Calibrator value in Jy per detector [Gain soln] [def 1.0] .
    "minEl"     float scalar Minimum elevation allowed (deg)
    "calType"   string  Calibration type desired
                "Gain" => Gain (multiplicative, cal) solution only
                "Offset" => Offset (additive) solution only
                "GainOffset" both gain and offset calibration (probably bad idea).
                anything else or absent => Gain only.
    returns OTFSoln table with solutions
    inOTF   = Python Obit OTF (residual) from which the solution is to be determined 
    outOTF  = Python Obit OTF onto which the solution table is to be appended.
    err     = Python Obit Error/message stack
    """
    ################################################################
    # Checks
    if not OTF.PIsA(inOTF):
        raise TypeError, "inOTF MUST be a Python Obit OTF"
    if not OTF.PIsA(outOTF):
        raise TypeError, "outOTF MUST be a Python Obit OTF"
    if not OErr.OErrIsA(err):
        raise TypeError, "err MUST be a Python ObitErr"
    #
    out = Table.Table(" ")
    if err.isErr:  # existing error?
        return out
    out.me = Obit.OTFGetSolnGain(inOTF.me, outOTF.me, err.me)
    return out
Example #25
0
def PSNSmo (inSC, err, input=UVSelfSNSmoInput):
    """ Smooth SN table possibly replacing blanked soln.

    inSC    = Selfcal object
    err     = Python Obit Error/message stack
    input   = input parameter dictionary
    
    Input dictionary entries:
    InData   = Input Python UV data 
    InTable  = Input SN table
    isuba    = Desired subarray, 0=> 1 
    smoType  = Smoothing type MWF, GAUS or BOX, def BOX
    smoAmp   = Amplitude smoothing time in min
    smpPhase = Phase smoothing time in min. (0 => fix failed only')
    """
    ################################################################
    # Get input parameters
    InData    = input["InData"]
    InTable   = input["InTable"]
    isuba     = input["isuba"]
    #
    # Checks
    if not UV.PIsA(InData):
        raise TypeError('PCal: Bad input UV data')
    if not Table.PIsA(InTable):
        raise TypeError('PCal: Bad input table')
    # Set control values on UV 
    dim[0] = 1;
    inInfo = UV.PGetList(InData)  # Add control to UV data
    dim[0] = len(input["smoType"]);
    InfoList.PAlwaysPutString  (inInfo, "smoType", dim, [input["smoType"]])
    dim[0] = 1;
    InfoList.PPutFloat   (inInfo, "smoAmp",  dim, [input["smoAmp"]],  err)
    InfoList.PPutFloat   (inInfo, "smoPhase",dim, [input["smoPhase"]],err)
    # Smooth
    Obit.UVSolnSNSmo(InTable.me, isuba, err.me)
    if err.isErr:
        printErrMsg(err, "Error smoothing SN table")
Example #26
0
def P(inOTF, outOTF, err):
    """ Determine gain offset calibration for an OTF dataset.

    The offset is determined from an atmospheric model.
    The gain calibration is determined from the average noise cal values
    and the atmospheric opacity.
    Results are placed in a newly created OTFSoln table.
    Calibration parameters are on the inOTF info member.
    "solInt"   float (1,1,1) Solution interval in days [def 10 sec].
    "Tau0"     float (1,1,1) Zenith opacity in nepers [def 0].
    "aTemp"    float (*,1,1) Effective atmospheric temperature in data units.
                i.e. the additional offset per airmass due to the atmosphere.
                per detector in units of the cal.
    "minEl"    float (1,1,1) Minimum elevation (deg)
    "tRx"      float (*,1,1) Receiver temperature per detector in units of the cal
    "calJy"    float (*,1,1) Noise cal value in Jy, per detector [def 1.0] .
    "Azoff"    float (*,1,1) Offset in deg to add to (cross El) [def 0] .
    "Eloff"    float (*,1,1) Offset in deg to add to El  [def 0.0] .

    returns OTFSoln table with solutions
    inOTF   = Python Obit OTF from which the solution is to be determined
    outOTF  = Python Obit OTF onto which the solution table is to be appended.
    err     = Python Obit Error/message stack
    """
    ################################################################
    # Checks
    if not OTF.PIsA(inOTF):
        raise TypeError,"inOTF MUST be a Python Obit OTF"
    if not OTF.PIsA(outOTF):
        raise TypeError,"outOTF MUST be a Python Obit OTF"
    if not OErr.OErrIsA(err):
        raise TypeError,"err MUST be a Python ObitErr"
    #
    out = Table.Table(" ")
    if err.isErr: # existing error?
        return out
    out.me = Obit.ObitOTFGetAtmCor (inOTF.me, outOTF.me, err.me)
    return out
Example #27
0
def PVL2FS(VLTable, image, FSver, err):
    """
    Convert contents in an ObitTableVL to entries in an FS table
    
    Converts an VL table produced by FndSou (or AIPS tasks SAD, VSAD)
    to a FS table (allows spectra).

    * VLTable   = Input Obit VL Table, control parameters on List:
                  minFlux = Minimum acceptable flux density (Jy) [def 0]
    * image     = Image cube being cataloged
    * FSver     = FS version
    * err       = Python Obit Error/message stack
    """
    ################################################################
    # Checks
    if not Table.PIsA(VLTable):
        print("Actually ", VLTable.__class__)
        raise TypeError("VLTable MUST be a Python Obit Table")
    if not Image.PIsA(image):
        print("Actually ", image.__class__)
        raise TypeError("image MUST be a Python Obit Image")
    #
    Obit.TableVL2FS(VLTable.me, image.me, FSver, err.me)
Example #28
0
def PRef (inSC, SNTab, isuba, refant, err):
    """ rereference phases of subarray isuba in a SN table to refant

    inSC      = Selfcal object
    SNTab     = Python AIPS SN Table
    isuba     = subarray [def. 1]
    refant    = reference antenna, if 0 -> pick one
    err       = Python Obit Error/message stack
    Returns actual reference antenna used
    """
    ################################################################
    # Checks
    if not PIsA(inSC):
        raise TypeError('Bad input selfcalibrator')
    if not Table.PIsA(SNTab):
        raise TypeError("SNTab MUST be a Python Obit Table")
    if not OErr.OErrIsA(err):
        raise TypeError("err MUST be an OErr")
    #
    ret = Obit.UVSolnRefAnt (SNTab.me, isuba, refant, err.me)
    if err.isErr:
        printErrMsg(err, "Error rereferencing phases")
    return ret
Example #29
0
def slurp(list, names):
    #Vivek
    #print list # [[decision + objectives (represented as '?')]] ? means missing values, it is a list of lists
    #print names  # [<$>decision.names (<<)objectives.names]

    t = want = None

    #print "Length of the list is : ", len(list)

    for rows in list:
        if t:
            if len(
                    rows
            ) == want:  #check if it has the same numbers of columns as the first row
                t.put(rows)
        else:
            want, t = len(rows), Table(
                names)  # it seems Joe has skipped the first row
            t.put(rows)  # added by Vivek

    # print "Number of rows in the table is: ", len(t.rows)
    # print "This is how a row looks like: ", t.rows[0]
    return t
Example #30
0
def hypothesis():
    print("Введите уровень значимости критерия - ")
    alfa = float(input())
    n, a = Initialize(e1, e2)
    q_table[0].destroy()
    lb = GetLeftEdge(a)
    rb = 1
    n_of_part = int(e3.get()) + 1
    if GetMode() == 1:
        x2 = GetArr(lb, rb, n_of_part - 2)
    else:
        x2 = np.linspace(lb, 1, n_of_part)
    ForTable3 = tuple("[" + str(x2[i - 1])[0:5] + "," + str(x2[i])[0:5] + "]"
                      for i in range(1, n_of_part))
    q_arr = [Get_q(a, x2[i - 1], x2[i]) for i in range(1, n_of_part)]
    q_table[0] = Tbl.Table(f_inside3, ForTable3, [q_arr], 1)
    q_table[0].pack(expand=tk.YES, fill=tk.BOTH)
    R_o = GetR(res[0], x2, n_of_part, n, a)
    print("F(R0) - ", GetXi_integral(n_of_part, R_o))
    if GetXi_integral(n_of_part, R_o) < alfa:
        print("Гипотеза отклонена")
    else:
        print("Гипотеза принята")
Example #31
0
def customer_address(rowCount):

    t = Table.Table('ecomm_shop', 'customer_address')

    t.add(
        Column.Column('customer_address_id', cDmy.DT_NUM, '999', '',
                      cDmy.FMT_4d))
    t.add(Column.Column('customer_id', cDmy.DT_NUM, '999', '', cDmy.FMT_4d))
    t.add(Column.Column('address_type', cDmy.DT_STR, '', 'R', cDmy.FMT_EMPTY))
    t.add(
        Column.Column('apartment_building', cDmy.DT_STR, 'Apt-', '',
                      cDmy.FMT_3d))
    t.add(Column.Column('first_line', cDmy.DT_STR, '', ' ', cDmy.FMT_EMPTY))
    t.add(Column.Column('second_line', cDmy.DT_STR, '', ' ', cDmy.FMT_EMPTY))
    t.add(
        Column.Column('street', cDmy.DT_STR, '', '90 feet rd', cDmy.FMT_EMPTY))
    t.add(Column.Column('city', cDmy.DT_STR, 'City-', '', cDmy.FMT_3d))
    t.add(Column.Column('state', cDmy.DT_STR, '', 'MH', cDmy.FMT_EMPTY))
    t.add(Column.Column('country', cDmy.DT_STR, '', 'India', cDmy.FMT_EMPTY))
    t.add(Column.Column('zip_code', cDmy.DT_NUM, '400', '', cDmy.FMT_3d))

    sql = SqlStatement.SqlStatement(t)
    return sql.generateInsert() + sql.generateSelect(rowCount)
Example #32
0
def attributes_test(verbose):
    relative_file_path = "../../resources/sql/accountSchema.sql"

    file_contents = Reader.open_file(relative_file_path)
    parser = Reader.SQL_Parser(file_contents)
    table_name = parser.parse_table()
    table_attributes = parser.parse_attributes()

    t = Table.Table(table_name, file_contents, table_attributes)

    expected_attribute_dict = {'account_email': 'VARCHAR', 'account_id': 'VARCHAR', 'account_type': 'CHAR'}

    count = 0

    if len(t.get_attributes()) != len(expected_attribute_dict):
        return 0
    for key in expected_attribute_dict:
        if t.get_attributes()[key] == expected_attribute_dict[key]:
            count+= 1
    if count == len(expected_attribute_dict):
        return 1

    return 0
Example #33
0
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, title="批量入库", size=(300, 300))
        self.helper = dbhelper.DBHelper()
        Dia = wx.FileDialog(parent,
                            message="Choose a file",
                            defaultDir="C:\\Users\Sail\Desktop\DBLab5",
                            style=1)
        L = self.helper.getMaxBookID()
        if L != None and L[0] != None:
            BookID = int(L[0]) + 1
        else:
            BookID = 10000

        if Dia.ShowModal() == wx.ID_OK:
            f = open(Dia.GetPath(), 'r')
            num = 1
            Book = Table.Book(BookID)
            for line in f:
                line.rstrip('\n')
                line = line.split()
                Book.setID(BookID)
                Book.setName(line[0])
                Book.setAuthor(line[1])
                Book.setPress(line[2])
                Book.setPressDate(line[3])
                Book.setType(line[4])
                Book.setNumber(line[5])
                BookID = BookID + 1
                self.helper.BookInsert(Book)
                num = num + 1
                print(line)
            f.close()
            result = wx.MessageDialog(self, message="导入成功", caption="导入结果")
            result.ShowModal()
            result.Destroy()
        Dia.Destroy()
        self.Destroy()
Example #34
0
 def edit(self, evt):
     global BookID
     Name = self.text1.GetValue()
     Author = self.text2.GetValue()
     Press = self.text3.GetValue()
     Number = self.text4.GetValue()
     Date = self.YearList[self.List1.GetSelection()]
     Type = self.TypeList[self.List3.GetSelection()]
     if Name == "" or Author == "" or Press == "" or Number == "" or Date == "" or Type == "":
         warn = wx.MessageDialog(self,
                                 message="所有信息均不能为空",
                                 caption="错误警告",
                                 style=wx.YES_DEFAULT | wx.ICON_ERROR)
         warn.ShowModal()
         warn.Destroy()
         return
     Book = Table.Book(self.ID, Name, Author, Press, Date, Type, Number)
     self.helper.updateBook(Book, self.ID)
     warn4 = wx.MessageDialog(self,
                              message="修改成功",
                              caption="修改结果",
                              style=wx.YES_DEFAULT)
     warn4.ShowModal()
     warn4.Destroy()
Example #35
0
    def testTable(self):
        driver = self.driver
        WebSite = os.path.join(os.path.dirname(__file__), os.path.pardir,
                               os.path.pardir, 'Html', '11.18.html')
        driver.get(WebSite)
        time.sleep(2)

        WebTable = driver.find_element_by_tag_name(
            'table')  #获取测试页面中的表哥元素,存储在WebTable变量中
        table = Table(WebTable)  #使用table变量对Table类进行实例化
        print("表格中有" + str(table.getRowCount()) + "行")
        print("表格中有" + str(table.getColumnCount()) + "列")

        Cell = table.getCell(1, 2)  #获取表格中第一行第二列的单元格对象
        self.assertAlmostEqual('第一行第二列', Cell.text)  #验证第一行第二列的单元格的文字是否一致

        CellInput = table.getWebElementInCell(3, 3, 'tag name',
                                              'input')  #获取第三行第三列中单元格的输入框对象
        CellInput.send_keys('这里的确是第三行第三列!')  #在该输入框内输入指定内容

        time.sleep(3)
Example #36
0
 def test_Table(self):
     """test Table class"""
     self.assertEqual(Table.Table().north.position, Table.position('North').position)
Example #37
0
 def test_pos2index(self):
     """pos2index"""
     self.assertEqual(0, Table.pos2index('North', 'North'))
     self.assertEqual(1, Table.pos2index('North', 'East'))
     self.assertEqual(2, Table.pos2index('North', 'South'))
     self.assertEqual(3, Table.pos2index('North', 'West'))
Example #38
0
 def __init__(self,parent):
     self.formsList = []
     self.parent=parent
     self.tableManager=Table(self)
     self.formsManager=Formulaire(self)
     self.users=Users(self)
Example #39
0
class Model():
    def __init__(self,parent):
        self.formsList = []
        self.parent=parent
        self.tableManager=Table(self)
        self.formsManager=Formulaire(self)
        self.users=Users(self)

    def getUsers(self):
        return self.users.getUsers()

    def createUser(self,newUser):
        self.users.createUser(newUser)

    def deleteUser(self, userToDelete):
        self.users.deleteUsers(userToDelete)

    def createTable(self,tablename,columns):
        self.tableManager.createNewTable(tablename,columns)
    def getGroupRights(self,id):
        sqlCommand="SELECT *  FROM Sys_droitsGroupes WHERE groupid=" + str(id)
        result=self.parent.serverCommunication.runSQLQuery(sqlCommand,None)[0]
        print(result)
        rights={"motdepasseautre":result[1],"motdepassepersonnel":result[2],
                "cronjobs":result[3],"regleaffaire":result[4],
                "lireforms":result[5],"modifforms":result[6],"remplirformulaire":result[7],"modifusagers":result[8],"lireusagers":result[9],"modifrapport":result[10],"lirerapport":[11]}
        return rights;
    def getGroups(self):
        sqlCommand="SELECT * FROM Sys_GroupesUtilisateurs"
        return self.parent.serverCommunication.runSQLQuery(sqlCommand,None)
    def saveGroup(self,group,modify):

        if(modify==False): #then creates the group
            sqlCommand="Insert into Sys_GroupesUtilisateurs(nom,niveau) VALUES"
            self.parent.serverCommunication.runSQLQuery(sqlCommand,(group["name"],group["security"]))
        else:
            group["id"]=self.parent.serverCommunication.runSQLQuery("SELECT id FROM Sys_GroupesUtilisateurs WHERE nom ='"+group["oldname"]+"'",None)[0][0]
            sqlCommand="UPDATE Sys_GroupesUtilisateurs SET nom='%s' ,niveau=%s WHERE id=%s" % (group["name"],group["security"],group["id"])
            print(sqlCommand)
            self.parent.serverCommunication.runSQLQuery(sqlCommand,None)
        group["id"]=self.parent.serverCommunication.runSQLQuery("SELECT id FROM Sys_GroupesUtilisateurs WHERE nom ='"+group["name"]+"'",None)[0][0]
        if(modify==False):
            sqlCommand="Insert into Sys_droitsGroupes(groupid,motdepasseautre,motdepassepersonnel,cronjobs,regleaffaire,lireforms,modifforms,remplirformulaire,modifusagers,lireusagers,modifrapport,lirerapport) VALUES"
            rights=group["rights"]
            self.parent.serverCommunication.runSQLQuery(sqlCommand,(group["id"],rights["motdepasseautre"],rights["motdepassepersonnel"]
                                                                    ,rights["cronjobs"],rights["regleaffaire"],rights["lireforms"]
                                                                    ,rights["modifforms"],rights["remplirformulaire"],rights["modifusagers"]
                                                                    ,rights["lireusagers"],rights["modifrapport"],rights["lirerapport"]
                        ))
        else:
            rights=group["rights"]
            sqlCommand="UPDATE Sys_droitsGroupes SET motdepasseautre=%d,motdepassepersonnel=%s,cronjobs=%s,regleaffaire=%s,lireforms=%s,modifforms=%s,remplirformulaire=%s,modifusagers=%s,lireusagers=%s,modifrapport=%s,lirerapport=%s WHERE groupid=%s" %(rights["motdepasseautre"],rights["motdepassepersonnel"]
                                                                    ,rights["cronjobs"],rights["regleaffaire"],rights["lireforms"]
                                                                    ,rights["modifforms"],rights["remplirformulaire"],rights["modifusagers"]
                                                                    ,rights["lireusagers"],rights["modifrapport"],rights["lirerapport"],group["id"])
            self.parent.serverCommunication.runSQLQuery(sqlCommand,None)
    def modifyTable(self,tablename,columns):
        
        self.tableManager.modifyTable(tablename,columns)
    def deleteTable(self,tablename):
        
        self.tableManager.deleteTable(tablename)

    def testOfDestruction(self):
        for i in range (50000):
            bindings = [ None, "dragomir"+str(i),"allo" , "ca va", "yooo", "allo" ]
            self.parent.serverCommunication.runSQLQuery('INSERT INTO Sys_Usagers values', bindings )
Example #40
0
        if key not in flat_data:
            flat_data[key] = []
            long_data[key] = []

        with open(fname, "r") as handle:
            for line in handle:
                cmin, cmax, Hj, Hc = line.strip().split(",")
                if cmin == "0" and cmax == index:
                    if flatten:
                        append_flatten_data(key, cmin, cmax, Hj, Hc)
                    else:
                        append_data(key, cmin, cmax, Hj, Hc)

# Create the table...
t = Table.Table(8, justs='lccccccc', caption='Table mang.', label="tab:table")
cols = [range(1, 21)]  # base on the data
print len(flat_data.keys())
t.add_header_row(["Index Offset"] + flat_data.keys())

for key in flat_data:
    col = []
    for (cmin, cmax, Hj, Hc) in flat_data[key]:
        if int(cmax) < 21:
            orig = float(base[cmax][0])
            Hj = float(Hj)
            if orig == 0.0:
                col.append("NaN")
            else:
                percent = ((float(Hj) - float(orig)) / float(orig)) * 100.0
                col.append(percent)
Example #41
0
 def __FROM(self, table):
     self.tables.insert(0, Table.copy(table))
class BilliardGame:

	def __init__(self):

		self.table = Table(1212, 634)

		self.whiteBall =  BilliardBall(0, 18, Point2D(0,0))
		self.yellowBall = BilliardBall(1, 1, Point2D(0,0))
		self.blueBall =   BilliardBall(2, 18, Point2D(0,0))
		self.redBall =    BilliardBall(3, 1, Point2D(0,0))
		self.purpleBall = BilliardBall(4, 1, Point2D(0,0))
		self.orangeBall = BilliardBall(5, 18, Point2D(0,0))
		self.greenBall =  BilliardBall(6, 18, Point2D(0,0))
		self.brownBall =  BilliardBall(7, 18, Point2D(0,0))
		self.blackBall =  BilliardBall(8, 18, Point2D(0,0))
		self.strYellowBall = BilliardBall(9, 18, Point2D(0,0))
		self.strBlueBall =   BilliardBall(10, 1, Point2D(0,0))
		self.strRedBall =    BilliardBall(11, 1, Point2D(0,0))
		self.strPurpleBall = BilliardBall(12, 1, Point2D(0,0))
		self.strOrangeBall = BilliardBall(13, 1, Point2D(0,0))
		self.strGreenBall =  BilliardBall(14, 1, Point2D(0,0))
		self.strBrownBall =  BilliardBall(15, 1, Point2D(0,0))

		self.balls = [ self.whiteBall,  self.yellowBall, \
		               self.blueBall,   self.redBall, \
		               self.purpleBall, self.orangeBall, \
		               self.greenBall,  self.brownBall, \
		               self.blackBall,      self.strYellowBall, \
		               self.strBlueBall,   self.strRedBall, \
		               self.strPurpleBall, self.strOrangeBall, \
		               self.strGreenBall,  self.strBrownBall]



	def transformBall(self, number, vector):
		self.balls[number].move(vector)


	def getAfterCollisionRange(self, moveBall, stayBall):
		radius = moveBall.radius
		dist = distance(moveBall.position, stayBall.position)
		m.


	def getCollisionPos(self, moveBall, stayBall):
		#moveBall = self.balls[moveBallNum]
		#stayBall = self.balls[stayBallNum]
		radius = moveBall.radius
		sx = stayBall.position.x
		sy = stayBall.position.y
		#moveFunc = LinearFunc(0, moveBall.velocity.x)

		move_function = Linear_function(point1 = moveBall.position, vector = moveBall.velocity)
		a = move_function.slope * move_function.slope + 1.0
		b = 2.0 * (move_function.slope * move_function.constant - move_function.slope * sy - sx)
		c = sx * sx - 4.0 * radius * radius + (sy - move_function.constant) * (sy - move_function.constant)
		delta = b * b - 4.0 * a * c

		if delta <= 0:
			raise Failure("\nSimulation terminated unexpectedly\n ERROR: no collision detected")

		#elif delta == 0:
		#	collision_x = (-1 * b) / (2 * a)
		#	collision_y = move_function.getValue(collision_x)
		#	return Point2D(collision_x, collision_y)

		else:
			x1 = ((-1 * b) - m.sqrt(delta)) / (2 * a)
			y1 = move_function.getValue(x1)
			x1y1 = Point2D(x1, y1)

			x2 = ((-1 * b) + m.sqrt(delta)) / (2 * a)
			y2 = move_function.getValue(x2)
			x2y2 = Point2D(x2, y2)


			x1y1_to_stay_function = Linear_function(point1 = Point2D(x1, y1), point2 = stayBall.position)

			x2y2_to_stay_function = Linear_function(point1 = Point2D(x2, y2), point2 = stayBall.position)

			tan_x1y1 = (x1y1_to_stay_function.slope - move_function.slope) / (1 + x1y1_to_stay_function.slope * move_function.slope)

			tan_x2y2 = (x2y2_to_stay_function.slope - move_function.slope) / (1 + x2y2_to_stay_function.slope * move_function.slope)

			if distance(moveBall.position, x1y1) < distance(moveBall.position, x2y2):

				theta = m.pi/2 - m.atan(tan_x1y1)

				new_stay_sp = moveBall.speed * m.sin(theta)

				new_stay_ve = Vector2D(from_point = x1y1, to_point = stayBall.position)

				k = new_stay_sp / new_stay_ve.length()

				stayBall.setVelocity(new_stay_ve.scale(k))
				#self.balls[stayBallNum].setVelocity(new_stay_ve.scale(k))

				new_move_sp = moveBall.speed * m.cos(theta)
				new_move_ve = new_stay_ve.normal()
				k_ = new_move_sp / new_move_ve.length()

				self.haloBall = BilliardBall(99, 9, x1y1)
				self.haloBall.setVelocity(new_move_ve.scale(k_))

				return x1y1

			else:

				theta = m.pi/2 - m.atan(tan_x2y2)
				#print "tan_x2y2 = ", tan_x2y2
				#print "delta = ", m.degrees(m.atan(tan_x2y2))
				#print "theta = ", m.degrees(theta)


				new_stay_sp = moveBall.speed * m.sin(theta)
				#print "move ball speed = ", moveBall.speed
				#print "new_stay_sp = ", new_stay_sp


				new_stay_ve = Vector2D(from_point = x2y2, to_point = stayBall.position)
				#print "new_stay_ve = (", new_stay_ve.x_factor, ",", new_stay_ve.y_factor, ")"

				k = new_stay_sp / new_stay_ve.length()
				#print "new_stay_ve.length = ", new_stay_ve.length()
				#print "scale k = ", k

				stayBall.setVelocity(new_stay_ve.scale(k))

				#self.balls[stayBallNum].setVelocity(new_stay_ve.scale(k))

				new_move_sp = moveBall.speed * m.cos(theta)
				new_move_ve = new_stay_ve.normal()
				k_ = new_move_sp / new_move_ve.length()

				self.haloBall = BilliardBall(99, 9, x2y2)
				self.haloBall.setVelocity(new_move_ve.scale(k_))


				return x2y2



	def getClosestPocket(self, ball):

		min_dist = float('inf')
		pocket_num = 0
		for pocket in self.table.pockets:
			dist = distance(ball.position, pocket.position)
			if dist < min_dist:
				min_dist = dist
				pocket_num = pocket.number

		return pocket_num



	def simulate(self):

		print "____________________________________________________"
		print "                                                    "
		print "          Pool Ball Game Simulation begin           "
		print "____________________________________________________\n\n"
		img = cv2.imread('simple_game_crop.png')
		height, width, channels = img.shape
		print "image width: ", width
		print "image height: ", height

		white_ball_pos  = Point2D(1061.0, 510.0)
		yellow_ball_pos = Point2D(863.0, 268.0)
		blue_ball_pos = Point2D(271.0, 316.0)
		brown_ball_pos = Point2D(780.0, 58.0)
		orange_ball_pos = Point2D(698.0, 185.0)
		green_ball_pos = Point2D(624.0, 213.0)
		black_ball_pos = Point2D(71.0, 92.0)

		sim_velocity = Vector2D(from_point = white_ball_pos, to_point = yellow_ball_pos).scale(0.5)


		self.balls[0].setPosition(point = white_ball_pos)
		self.balls[9].setPosition(point = yellow_ball_pos)
		self.balls[2].setPosition(point = blue_ball_pos)
		self.balls[5].setPosition(point = orange_ball_pos)
		self.balls[6].setPosition(point = green_ball_pos)
		self.balls[7].setPosition(point = brown_ball_pos)
		self.balls[8].setPosition(point = black_ball_pos)

		# check balls have velocity or not
		self.balls[0].setVelocity(sim_velocity)

		#p = Point2D(0,0)

		white = self.balls[0]
		cv2.circle(img,(int(white.position.x),int(white.position.y)), white.radius, (0,0,255), 2)

		yellow = self.balls[9]
		cv2.circle(img,(int(yellow.position.x),int(yellow.position.y)), yellow.radius, (0,0,255), 2)


		blue = self.balls[2]
		cv2.circle(img,(int(blue.position.x),int(blue.position.y)), blue.radius, (0,0,255), 2)

		orange = self.balls[5]
		cv2.circle(img,(int(orange.position.x),int(orange.position.y)), orange.radius, (0,0,255), 2)

		green = self.balls[6]
		cv2.circle(img,(int(green.position.x),int(green.position.y)), green.radius, (0,0,255), 2)

		brown = self.balls[7]
		cv2.circle(img,(int(brown.position.x),int(brown.position.y)), brown.radius, (0,0,255), 2)

		black = self.balls[8]
		cv2.circle(img,(int(black.position.x),int(black.position.y)), black.radius, (0,0,255), 2)



		p = self.getCollisionPos(self.balls[0], self.balls[9])


		print "white ball located at: (", white.position.x, ",", white.position.y, ")"
		print "white ball speed is: ", white.speed
		print "yellow ball located at: (", yellow.position.x, ",", yellow.position.y, ")"
		print "the closest pocket to yellow is: ", self.getClosestPocket(yellow)
		print "collision point is at: (", p.x, ",", p.y, ")"

		yellow = self.balls[9]

		print "After collision: \n       yellow ball speed is: ", yellow.speed



		cv2.line(img, (int(white.position.x),int(white.position.y)), (int(white.position.x+white.velocity.x_factor),
			int(white.position.y+white.velocity.y_factor)), (0,0,255), 2)


		cv2.line(img, (int(yellow.position.x),int(yellow.position.y)), (int(yellow.position.x+yellow.velocity.x_factor),
			int(yellow.position.y+yellow.velocity.y_factor)), (0,0,255), 2)


		cv2.circle(img,(int(p.x),int(p.y)), white.radius, (0,0,255), 2)

		q = self.haloBall
		cv2.line(img, (int(q.position.x),int(q.position.y)), (int(q.position.x+q.velocity.x_factor),int(q.position.y+q.velocity.y_factor)), (0,0,255), 2)



		self.table.showPockets(img)

		cv2.imshow('image',img)
		cv2.waitKey(0)
		cv2.destroyAllWindows()


		print "\n\n##########simulation terminated successfully##########\n"
Example #43
0
class SamplesStack:
    def DrawAndSave(self, stack , hist , name , LogY = 0 , external_title = '' , errors_to_draw=[]):
        #if not name == "bbbTopTopEta" :
        #    return 0.0

        if not os.access( self.Channel , os.F_OK) :
            os.mkdir( self.Channel )

        hOne = TH1D('hOne' , 'One' , hist.GetNbinsX() , hist.GetBinLowEdge(1) , hist.GetBinLowEdge(hist.GetNbinsX())+hist.GetBinWidth(hist.GetNbinsX()) )  
        hOne.SetStats(0)
        hOne.SetLineColor(4)
        hOne.SetLineWidth(2)
        hOne.SetLineStyle(3)

        for nBin in range(1, hist.GetNbinsX()+1):
            err = sqrt(hist.GetBinContent(nBin))
            hist.SetBinError(nBin, err)

            hOne.SetBinContent( nBin , 1)
            hOne.SetBinError( nBin , 0)

        c = TCanvas(name, '', 800, 800)
        c.Divide(1,2, 0.0 , 0.0)

        c1 = c.cd(1)

        c1.SetLeftMargin(0.09)
        c1.SetRightMargin(0.02333333)
        c1.SetTopMargin(0.04)

        c1.SetLogy(LogY)
        maxVal = stack.GetMaximum()
        if hist.GetBinContent(hist.GetMaximumBin()) > maxVal:
            stack.SetMaximum( 1.01*hist.GetBinContent(hist.GetMaximumBin()) )
            maxVal = hist.GetBinContent(hist.GetMaximumBin())
            if not len(errors_to_draw) == 0 :
                maxVal *= 1.4

        stack.Draw("9 HIST")

        xaxisTitle = hist.GetXaxis().GetTitle()
        if not external_title == '':
            xaxisTitle = external_title

        stack.GetHistogram().GetXaxis().SetTitle( '' )
        stack.GetHistogram().GetXaxis().SetLabelSize(0.0)

        #if LogY == 1:
            #stack.GetHistogram().GetYaxis().SetRangeUser(1 , maxVal)
        #else:
        stack.GetHistogram().GetYaxis().SetRangeUser(0.0 , maxVal)
        
        hist.SetLineWidth( 2 )
        hist.GetXaxis().SetTitle('')
        hist.GetXaxis().SetLabelSize(0.0)
        hist.GetYaxis().SetTitle('')
        hist.Draw("9 E1 SAME")

        leg = TLegend(0.75,0.75,0.95,0.95)
        leg.SetBorderSize( 0 )
        leg.SetTextFont(62)
        leg.SetLineColor(1)
        leg.SetLineStyle(1)
        leg.SetLineWidth(1)
        leg.SetFillColor(0)
        leg.SetFillStyle(0)

        for category in SampleCategoriesOrdered:
            if category == "Systematics" :
                continue

            color = SampleCategoriesColors[category]
            leg_entry_name = "%(cat)s_%(color)d" % {"cat":"category" , "color":color}
            print leg_entry_name
            entry = None
            if category == "Data":
                entry=leg.AddEntry(leg_entry_name,category,"PLE")
            else:
                entry=leg.AddEntry(leg_entry_name,category,"F")
            
            entry.SetLineColor(color)
            entry.SetLineStyle(1)
            entry.SetLineWidth(1)
            entry.SetMarkerColor(color)
            entry.SetMarkerStyle(21)
            entry.SetMarkerSize(1)
            entry.SetFillColor(color)
            entry.SetFillStyle(1001)

        c1.SetPad( 0 , 0.295 , 1, 1)
        c1.cd()
        leg.SetOption("BR NDC")
        leg.ConvertNDCtoPad()
        leg.Draw()

        latex = TLatex( 0.15 , 0.91 , "CMS Preliminary, 4.6 fb^{-1} at #sqrt{s} =7TeV" )
        c1.cd()
        latex.SetNDC(True)
        latex.Draw()
        c1.Modified()
        

        c2 =  c.cd(2)
        c2.SetPad( c2.GetXlowNDC(), c2.GetXlowNDC() , 1 , 0.295)

        c2.Range(-2.636104,-0.3032786,225.4441,1.568279)

        c2.SetLeftMargin(0.09)
        c2.SetRightMargin(0.02333333)
        c2.SetTopMargin(0.04)
        c2.SetBottomMargin(0.4)

        hDivision = TH1D('hDivision' , 'Data/MC' , hist.GetNbinsX() , hist.GetBinLowEdge(1) , hist.GetBinLowEdge(hist.GetNbinsX())+hist.GetBinWidth(hist.GetNbinsX()) )
        hSum = TH1D('hSum' , 'SUM_MC' , hist.GetNbinsX() , hist.GetBinLowEdge(1) , hist.GetBinLowEdge(hist.GetNbinsX())+hist.GetBinWidth(hist.GetNbinsX()) )

        #hSum.Print("ALL")
        #hist.Print("ALL")

        Errors = {}
        for nBin in range(1, hist.GetNbinsX()+1):
            Errors[nBin] = 0.0

        xx_for_errors = array.array('d')
        yy_for_errors = array.array('d')
        xxerr_for_errors = array.array('d')
        yyerr_for_errors = array.array('d')

        for h_MC in stack.GetHists():
            #h_MC.Print()
            hSum.Add( h_MC )
        
        for nBin in range(1, hSum.GetNbinsX()+1):
            Errors[nBin] = hSum.GetBinError(nBin)
            if not len(errors_to_draw) == 0:
                xx_for_errors.append( hSum.GetBinCenter(nBin) )
                yy_for_errors.append( hSum.GetBinContent(nBin) )
                yyerr_for_errors.append( errors_to_draw[nBin-1] )
                xxerr_for_errors.append( hSum.GetBinWidth(nBin)/2 )

                Errors[nBin] = sqrt( errors_to_draw[nBin-1]*errors_to_draw[nBin-1] + hSum.GetBinError(nBin)*hSum.GetBinError(nBin) )
        
        if not len(errors_to_draw) == 0:
            err_graph = TGraphErrors( hSum.GetNbinsX() , xx_for_errors , yy_for_errors ,  xxerr_for_errors ,  yyerr_for_errors)
            c.cd(1)
            err_graph.SetFillColor(kBlack)
            err_graph.SetFillStyle(3005)
            err_graph.Draw('2')

            entry=leg.AddEntry("Systematics_Uncertainity","Syst. Unc.","F")
            entry.SetFillColor(kBlack)
            entry.SetFillStyle(3005)

            c.cd(2)

        for nBin in range(1, hSum.GetNbinsX()+1):
            hSum.SetBinError( nBin , Errors[nBin] )

        hDivision.Divide( hist , hSum )
        hDivision.GetYaxis().SetRangeUser( 0.5 , 1.5)
        hDivision.SetStats(0)
        hDivision.SetLineWidth(2)
        hDivision.SetLineColor(2)
        hDivision.GetYaxis().SetLabelSize(0.08)
        hDivision.GetXaxis().SetLabelSize(0.1)
        hDivision.GetXaxis().SetTitleSize(0.2)
        hDivision.GetXaxis().SetTitle(xaxisTitle)
        #hDivision.GetXaxis().SetLabelSize(0.0)
        hDivision.GetYaxis().SetNdivisions(3 , 6 , 0 , True)
        hDivision.Draw("E1")
        hOne.Draw("SAME C")

        total_difference = 0.0
        for nBin in range(1, hist.GetNbinsX()+1):
            data_in_bin = hist.GetBinContent(nBin)
            mc_in_bin = hSum.GetBinContent(nBin)
            total_difference += (data_in_bin - mc_in_bin)

        c.cd()
        c.Modified()
        c.SaveAs(self.Channel + '/' + name + '.gif' )
        c.SaveAs(self.Channel + '/' + name + '.C' )
        c.SaveAs(self.Channel + '/' + name + '.pdf' )
        # c.SaveAs(self.Channel + '/' + name + '.eps' )
        c.Close()
        return total_difference    

    def DrawCosTheta(self , Data , Errors = []):
        dataType = type( Data )
        data = dataType. __getattribute__(Data , self.Channel)

        NNName = '_cos_theta'
        if not len(Errors) == 0:
            NNName += '_errors'

        deltaMC_Data_CosTheta = self.DrawAndSave( self.stack_costheta['10'] ,  data.hCosTheta['10'] , self.Channel + NNName , 0 , 'cos(#theta^{*})' , Errors )
        deltaMC_Data_CosTheta_LogY = self.DrawAndSave( self.stack_costheta['10'] ,  data.hCosTheta['10'] , self.Channel +NNName + '_logy' , 1 , 'cos(#theta^{*})' , Errors )

        ret = '*** Plot of Cos(\\theta) for selected events \n'
        ret = ret + '    - Difference is : 2*' + str(deltaMC_Data_CosTheta/2) + '\n'
        ret = ret + '    [[[%(Channel)s/%(Channel)s%(NNName)s.gif]]]'%{'Channel':self.Channel, 'NNName':NNName}  + '\n'
        ret = ret + '    [[[%(Channel)s/%(Channel)s%(NNName)s_logy.gif]]]'%{'Channel':self.Channel, 'NNName':NNName}  + '\n'
        if len(Errors) == 0:
            deltaMC_Data_CosThetaPreselected = self.DrawAndSave( self.stack_costheta_preselected ,  data.hCosThetaPreselected , self.Channel + '_cos_theta_preselected',1, 'cos(#theta^{*})' )            
            ret = ret +  '*** Plot of Cos(\\theta) for pre-selected events \n'
            ret = ret + '    - Difference is : 2*' + str(deltaMC_Data_CosThetaPreselected/2)  + '\n'
            ret = ret + '    [[[%(Channel)s/%(Channel)s_cos_theta_preselected.gif]]]'%{'Channel':self.Channel} + '\n'

        return ret


    def DrawTopRecPlots(self, Data):
        dataType = type( Data )
        data = dataType. __getattribute__(Data , self.Channel)
        self.t_TopRecPropertiesLinks = Table(False)
        TheRow = RowObject()
        PropertiesLinks = {}
        for Property in self.AllTopRecStacks.keys():
            stack_prop = self.AllTopRecStacks[Property]
            hPropd = data.AllTopRecPlots[Property]
                
            ImgFileName = 'bbb'+ Property
            ImgFileName = ImgFileName.replace("_", 'z')
            TotalDiff = self.DrawAndSave(stack_prop, hPropd, ImgFileName ,0)
            
            TheRow[Property] = '@<a id="%(id)s" href="%(file)s" class="highslide" onclick="return hs.expand(this)">%(PropName)s@</a>' % {'file':self.Channel + '/' + ImgFileName + '.gif' , 'id':(Property).replace('_', 'x') , 'PropName':Property}


        stack_prop = self.stack_NPrVtxAll
        hPropd = data.NPrVtxAll
        
        ImgFileName = 'bbbNPrVtxAll'
        TotalDiff = self.DrawAndSave(stack_prop, hPropd, ImgFileName , 0)
        TheRow['NPrVtxAll'] = '@<a id="%(PropName)s" href="%(file)s" class="highslide" onclick="return hs.expand(this)">%(PropName)s@</a>' % {'file':self.Channel + '/' + ImgFileName + '.gif' ,  'PropName':Property}        

        stack_prop = self.stack_NPrVtxAllNoW
        hPropd = data.NPrVtxAllNoW      
        ImgFileName = 'bbbNPrVtxAllNoW'
        TotalDiff = self.DrawAndSave(stack_prop, hPropd, ImgFileName , 0)
        TheRow['NPrVtxAllNoW'] = '@<a id="%(PropName)s" href="%(file)s" class="highslide" onclick="return hs.expand(this)">%(PropName)s@</a>' % {'file':self.Channel + '/' + ImgFileName + '.gif' ,  'PropName':Property}        

        self.t_TopRecPropertiesLinks.append( TheRow )
        return self.t_TopRecPropertiesLinks
        

    def DrawAllProperties(self , Data):
        dataType = type( Data )
        data = dataType. __getattribute__(Data , self.Channel)
        self.t_PropertiesLinks = Table(False)
        PropertiesLinks = {}
        for Property in self.PropertiesToDraw.keys():
            PropertiesLinks[Property] = RowObject()
            
            PropertiesLinks[Property]['0-Property'] = Property
            
            for CutID in sorted(self.AllSortedDirectories.keys()):
                Cut = self.AllSortedDirectories[CutID]
                stack_prop = self.PropertiesToDraw[Property][Cut]
                hPropd = data.PropertiesToDraw[Property][Cut]
                if Cut == '':
                    stack_prop.SetTitle( '%(Channel)s : after pair choose' % {'Channel':self.Channel } )
                else:
                    stack_prop.SetTitle( '%(Channel)s : after cut on  %(Cut)s' % {'Channel':self.Channel, 'Cut':Cut  } )
                    
                ImgFileName = 'aaa'+ str(CutID)+ "_" +Cut+  "_"  + Property
                ImgFileName = ImgFileName.replace("_", 'z')
                TotalDiff = self.DrawAndSave(stack_prop, hPropd, ImgFileName , 0)
                               
                PropertiesLinks[Property]['%(ID)d-%(Name)s'%{'ID':CutID+1 , 'Name':Cut}] = '@<a id="%(id)s" href="%(file)s" class="highslide" onclick="return hs.expand(this)">%(Diff)d@</a>' % {'file':self.Channel + '/' + ImgFileName + '.gif' , 'id':(Cut+'_'+Property).replace('_', 'x') , 'Diff':TotalDiff}
                CutID = CutID+1

            self.t_PropertiesLinks.append( PropertiesLinks[Property] )
        return self.t_PropertiesLinks

        

    def __init__(self , ArrayOfAllSamples, sortedSamples , StackCosTheta = True , StackControlPlots = True , StackOtherPlots = True):
        self.Row  = RowObject()
        self.RowW = RowObject()
        
        sample_id = 0
        for category in reversed(SampleCategoriesOrdered):
            for sampleName in sortedSamples:
                if ArrayOfAllSamples.keys().count(sampleName) == 0:
                    continue
                sample = ArrayOfAllSamples[sampleName]

                if category.count( sample.Category ) == 0:
                    continue
                
                #print sample.Sample
                if sample_id == 0:
                    self.Channel = sample.Channel
                    self.AllSortedDirectories = sample.AllSortedDirectories

                    if StackCosTheta:
                        self.stack_costheta = {}

                        for cosTheta in sample.hCosTheta.keys():
                            self.stack_costheta[cosTheta] =  THStack("stackCosTheta" +cosTheta+ "_" + self.Channel ,'CosTheta for ' + self.Channel +' Events')
                        # self.stack_costheta['10'] =  THStack("stackCosTheta10_" + self.Channel ,'CosTheta for ' + self.Channel +' Events')
                        # self.stack_costheta['20'] =  THStack("stackCosTheta20_" + self.Channel ,'CosTheta for ' + self.Channel +' Events')
                        # self.stack_costheta['25'] =  THStack("stackCosTheta25_" + self.Channel ,'CosTheta for ' + self.Channel +' Events')
                        # self.stack_costheta['50'] =  THStack("stackCosTheta50_" + self.Channel ,'CosTheta for ' + self.Channel +' Events')
                        # self.stack_costheta['100'] =  THStack("stackCosTheta100_" + self.Channel ,'CosTheta for ' + self.Channel +' Events')

                        self.stack_costheta_preselected =  THStack("preselected_stackCosTheta_" + self.Channel ,'CosTheta for preselected ' + self.Channel +' Events')

                    if StackControlPlots:
                        self.PropertiesToDraw = {}

                        for column in sample.Row:
                            self.Row[column] = sample.Row[column]
                        self.Row[ sorted(self.Row.keys())[0] ] = ''
                        for column in sample.RowW:
                            self.RowW[column] = sample.RowW[column]
                        self.RowW[ sorted(self.RowW.keys())[0] ] = ''

                        for Property in sample.PropertiesToDraw.keys():
                            allStacks = {}
                            for Cut in sample.PropertiesToDraw[Property].keys():
                                stack_newName = 'stack_%(Channel)s_%(Cut)s_%(Property)s' % {'Cut':Cut , 'Property':Property , 'Channel':self.Channel }
                                allStacks[Cut]= THStack( stack_newName , stack_newName )
                                allStacks[Cut].Add( sample.PropertiesToDraw[Property][Cut] )

                            self.PropertiesToDraw[Property] = allStacks

                    if StackOtherPlots:

                        self.AllTopRecStacks = {}
                        for prop in sample.AllTopRecPlots.keys():
                            self.AllTopRecStacks[prop] = THStack("stack_" + prop + "_" + self.Channel , sample.AllTopRecPlots[prop].GetTitle() )
                            self.AllTopRecStacks[prop].Add( sample.AllTopRecPlots[prop] )

                        self.stack_NPrVtxAll = THStack("stack_NPrVtxAll_" + self.Channel , '# Primary vertices')
                        self.stack_NPrVtxAllNoW = THStack("stack_NPrVtxAllNoW_" + self.Channel , '# Primary vertices , no pu')
                    sample_id = 1
                else:
                    if StackControlPlots:
                        for column in sorted(self.Row.keys())[1:]:
                            self.Row[column] = self.Row[column] + sample.Row[column]
                        for column in sorted(self.RowW.keys())[1:]:
                            self.RowW[column] = self.RowW[column] + sample.RowW[column]

                        for Property in sample.PropertiesToDraw.keys():
                            for Cut in sample.PropertiesToDraw[Property].keys():
                                self.PropertiesToDraw[Property][Cut].Add( sample.PropertiesToDraw[Property][Cut] )

                    if StackOtherPlots:
                        for prop in sample.AllTopRecPlots.keys():
                            self.AllTopRecStacks[prop].Add( sample.AllTopRecPlots[prop] )

                if StackCosTheta:
                    for cosTheta in sample.hCosTheta.keys():
                        self.stack_costheta[cosTheta].Add( sample.hCosTheta[cosTheta] )
                    # self.stack_costheta['10'].Add( sample.hCosTheta['10'] )
                    # self.stack_costheta['20'].Add( sample.hCosTheta['20'] )
                    # self.stack_costheta['25'].Add( sample.hCosTheta['25'] )
                    # self.stack_costheta['50'].Add( sample.hCosTheta['50'] )
                    # self.stack_costheta['100'].Add( sample.hCosTheta['100'] )

                    self.stack_costheta_preselected.Add( sample.hCosThetaPreselected )

                if StackOtherPlots:
                    self.stack_NPrVtxAll.Add( sample.NPrVtxAll )
                    self.stack_NPrVtxAllNoW.Add( sample.NPrVtxAllNoW )
Example #44
0
    def insertRun(self, filename, position = -1, rows = 1):
        """Insert a run with all of its child tables and projections
           into the data datatree/data store. The input filename should
           refer to the meta file denoting the run.
        """
        parentItem = self._rootItem
        metadata, filelist = yl.load_meta(filename)
        if position == -1:
            position = parentItem.childCount()

        # Create RunItem
        self.beginInsertRows(QModelIndex(), position, position + rows - 1)
        runItem = RunItem(os.path.basename(filename), metadata, parentItem)
        self.endInsertRows()

        # Create groups for Tables and Projections
        self.beginInsertRows(self.createIndex(position, 0, runItem), 0, 2)
        tablesItem = GroupItem("tables", parent = runItem)
        projectionsItem = GroupItem("projections", parent = runItem)
        self.endInsertRows()

        # Create TableItems and ProjectionItems
        for filedict in filelist:
            if filedict['filetype'].upper() == "TABLE":
                type_string = filedict['domain'] + "_" + filedict['type']
                data_type = SubDomain.instantiate(type_string)
                if data_type is None:
                    print "No matching type found for", filedict['type'], \
                        "! Skipping table..."
                    continue

                filepath = os.path.join(os.path.dirname(filename),
                    filedict['filename'])
                metadata, data = yl.load_table(filepath)
                if metadata:
                    combined_meta = dict(metadata.items() + filedict.items())
                else:
                    combined_meta = filedict
                atable = Table()
                atable.fromRecArray(data_type, filedict['field'], data)
                self.insertTable(filedict['filename'], atable, combined_meta, \
                    parent = self.createIndex(position, 0, tablesItem))
            elif filedict['filetype'].upper() == "PROJECTION":
                domainlist = filedict['subdomain']
                mydomains = list()
                mykeys = list()
                for subdomaindict in domainlist:
                    type_string = subdomaindict['domain'] + "_" \
                        + subdomaindict['type']
                    data_type = SubDomain.instantiate(type_string)
                    if data_type is None:
                        print "No matching type found for", \
                            subdomaindict['type'], "! Skipping projection..."
                        continue
                    else:
                        mydomains.append(data_type)
                        mykeys.append(subdomaindict['field'])

                if len(mydomains) != 2:
                    print "Not enough domains for projection. Skipping..."
                    continue

                # Different projections created here per type. Again, probably
                # should be moved to different class.
                if filedict['type'].upper() == "FILE":
                    filepath = os.path.join(os.path.dirname(filename),
                        filedict['filename'])
                    metadata, data = yl.load_table(filepath)
                    if metadata:
                        combined_meta = dict(metadata.items() + filedict.items())
                    else:
                        combined_meta = filedict
                    atable = Table()
                    atable.fromRecArray(mydomains[0], mykeys[0], data)
                    aprojection = TableProjection(mydomains[0], mydomains[1],
                        source_key = mykeys[0], destination_key = mykeys[1],
                        table = atable)
                    self.insertProjection(mydomains[0].typename() + "<->"
                        + mydomains[1].typename(), aprojection, combined_meta,
                        parent = self.createIndex(position, 0, projectionsItem))
                else:
                    aprojection = Projection.instantiate(filedict['type'],
                        mydomains[0], mydomains[1], run = runItem, **filedict)
                    self.insertProjection(mydomains[0].typename() + "<->"
                        + mydomains[1].typename(), aprojection, filedict,
                        parent = self.createIndex(position, 0, projectionsItem))


        runItem.refreshSubdomains()
        self.createSubDomainTables(runItem, projectionsItem, tablesItem)
        return True
Example #45
0
	def __init__(self, table_info):
		self.__decision_block = TableGui.DecisionBlock()

		self.__table_info = table_info
		self.__table      = Table(table_info, self)
Example #46
0
class TableGui:
	card_height = 70
	card_width  = 50
	blind_size  = 45

	info_height = 150
	info_width  = 150
	name_height = 20

	center_x = 300
	center_y = 200

	table_card_coef = 1.5

	class PlayerInfoView:
		def __init__(self, player_info, scene, x, y):
			self.__player_info = player_info
			self.__scene = scene
			self.__pos = (x, y)

			self.__player_info.add_crl_cards(self)
			self.__player_info.add_crl_many(self)
			self.__player_info.add_crl_blind(self)
			self.__player_info.add_crl_ante(self)
			self.__player_info.add_crl_active_alive(self)

			self.__init_player_background()
			self.__init_player_name_view()
			self.__init_hand_card_view()
			self.__init_many_view()
			self.__init_ante_view()
			self.__init_blind_view()

		def __init_player_background(self):
			x = self.__pos[0]
			y = self.__pos[1]
			# self.__player_background = QGraphicsRectItem(x - 20, y - 20, TableGui.card_width * 3 + 40, TableGui.card_height + 70)
			self.__player_background = QGraphicsRectItem(x, y, TableGui.info_width, TableGui.info_height)

			self.__player_background.setBrush(Qt.yellow)
			self.__scene.addItem(self.__player_background)

		def __init_player_name_view(self):
			x = self.__pos[0]
			y = self.__pos[1]
			self.__name_view = QGraphicsTextItem(self.__player_info.name())
			self.__name_view.setPos(x, y)
			self.__scene.addItem(self.__name_view)

		def __init_hand_card_view(self):
			x = self.__pos[0] + TableGui.name_height
			y = self.__pos[1] + TableGui.name_height
			self.__hand = self.__player_info.hand_cards()
			self.__hand_pixmaps = []

			cur_card_x = x
			for card in self.__hand:
				if not self.__player_info.is_hand_hidden():
					picture_path = card.image_path()
				else:
					picture_path = card.jacket_image_path()

				pixmap_item = QGraphicsPixmapItem(QPixmap(picture_path).scaledToHeight(TableGui.card_height))
				pixmap_item.setPos(cur_card_x, y)
				self.__scene.addItem(pixmap_item)
				self.__hand_pixmaps.append(pixmap_item)

				cur_card_x += TableGui.card_width

		def hand_cards_changed(self):
			self.__hand = self.__player_info.hand_cards()

			i = 0
			for card in self.__hand:
				if not self.__player_info.is_hand_hidden():
					picture_path = card.image_path()
				else:
					picture_path = card.jacket_image_path()

				self.__hand_pixmaps[i].setPixmap(QPixmap(picture_path).scaledToHeight(TableGui.card_height))
				i += 1


		def blind_changed(self):
			blind = self.__player_info.blind()

			if blind == 0:
				self.__blind.setPixmap(QPixmap())
			elif blind == 1:
				self.__blind.setPixmap(QPixmap('images/littleblind.jpg').scaledToWidth(TableGui.card_width))
			else:
				self.__blind.setPixmap(QPixmap('images/bigblind.jpg').scaledToWidth(TableGui.card_width))

		def ante_changed(self):
			ante_text = 'FOLD'
			if not self.__player_info.is_folded():
				ante = self.__player_info.ante()
				ante_text = str(ante)
			self.__ante_text.setPlainText('Ante: ' + ante_text)

		def many_changed(self):
			many = self.__player_info.many()
			self.__many_text.setPlainText('Many: ' + str(many))

		def active_alive_changed(self):
			if not self.__player_info.is_alive():
				self.__player_background.setBrush(Qt.red)
				return
			if self.__player_info.is_active():
				self.__player_background.setBrush(Qt.green)
				return
			
			self.__player_background.setBrush(Qt.yellow)
			return

		def __init_many_view(self):
			x = self.__pos[0]
			y = self.__pos[1] + TableGui.name_height
			self.__many_text = QGraphicsTextItem('Many: ' + str(self.__player_info.many()))
			self.__many_text.setPos(x, y + TableGui.card_height)
			self.__scene.addItem(self.__many_text)

		def __init_ante_view(self):
			x = self.__pos[0]
			y = self.__pos[1] + TableGui.name_height
			self.__ante_text = QGraphicsTextItem('Ante: ' + str(self.__player_info.ante()))
			self.__ante_text.setPos(x, y + TableGui.card_height + TableGui.name_height)
			self.__scene.addItem(self.__ante_text)

		def __init_blind_view(self):
			x = self.__pos[0]
			y = self.__pos[1] + TableGui.name_height
			self.__blind = QGraphicsPixmapItem(QPixmap())
			if self.__player_info.blind() == 1:
				self.__blind = QGraphicsPixmapItem(QPixmap('images/littleblind.jpg').scaledToWidth(TableGui.blind_size))
			elif self.__player_info.blind() == 2:
				self.__blind = QGraphicsPixmapItem(QPixmap('images/bigblind.jpg').scaledToWidth(TableGui.blind_size))
			self.__blind.setPos(x + 1.8 * TableGui.card_width, y + TableGui.card_height * 1.1)
			self.__scene.addItem(self.__blind)		

	class OpenedCardView:
		def __init__(self, scene, table_info):
			self.__scene = scene
			self.__table_info = table_info

			table_info.add_crl_opened_cards(self)

			self.__card_view = []
			self.__card_view.append(QGraphicsPixmapItem(QPixmap()))
			self.__scene.addItem(self.__card_view[0])
			self.__card_view.append(QGraphicsPixmapItem(QPixmap()))
			self.__scene.addItem(self.__card_view[1])
			self.__card_view.append(QGraphicsPixmapItem(QPixmap()))
			self.__scene.addItem(self.__card_view[2])
			self.__card_view.append(QGraphicsPixmapItem(QPixmap()))
			self.__scene.addItem(self.__card_view[3])
			self.__card_view.append(QGraphicsPixmapItem(QPixmap()))
			self.__scene.addItem(self.__card_view[4])

			self.__card_view[0].setPos(TableGui.center_x - TableGui.card_width *     TableGui.table_card_coef, TableGui.center_y - TableGui.card_height / 2)
			self.__card_view[1].setPos(TableGui.center_x,                                                      TableGui.center_y - TableGui.card_height / 2)
			self.__card_view[2].setPos(TableGui.center_x + TableGui.card_width *     TableGui.table_card_coef, TableGui.center_y - TableGui.card_height / 2)
			self.__card_view[3].setPos(TableGui.center_x + TableGui.card_width * 2 * TableGui.table_card_coef, TableGui.center_y - TableGui.card_height / 2)
			self.__card_view[4].setPos(TableGui.center_x + TableGui.card_width * 3 * TableGui.table_card_coef, TableGui.center_y - TableGui.card_height / 2)

			self.opened_cards_changed()

		def opened_cards_changed(self):
			# clear
			for card_view in self.__card_view:
				card_view.setPixmap(QPixmap())

			i = 0
			for card in self.__table_info.opened_cards():
				self.__card_view[i].setPixmap(QPixmap(card.image_path()).scaledToHeight(TableGui.card_height * TableGui.table_card_coef))
				i += 1

	class BankView:
		def __init__(self, scene, table_info):
			self.__scene = scene
			self.__table_info = table_info

			self.__table_info.add_crl_bank(self)

			self.__bank_text = QGraphicsTextItem('Bank: %d' % table_info.bank())
			self.__bank_text.setPos(TableGui.center_x, TableGui.center_y + TableGui.card_height)
			self.__scene.addItem(self.__bank_text)

		def bank_changed(self):
			self.__bank_text.setPlainText('Bank: %d' % self.__table_info.bank())

	class DecisionBlock:
		btn_width  = 70
		btn_height = 25

		def __init__(self):
			pass

		def start(self, scene, type, x, y):
			# type must be 'Call' or 'Check'
			self.__scene = scene
			self.__type  = type

			self.__call_check_btn = QPushButton(type)
			self.__call_check_btn.setGeometry(x, y, self.btn_width, self.btn_height)
			self.__call_check_btn.setEnabled(False)
			self.__scene.addWidget(self.__call_check_btn)

			self.__fold_btn  = QPushButton('Fold')
			self.__fold_btn.setGeometry(x, y + self.btn_height, self.btn_width, self.btn_height)
			self.__fold_btn.setEnabled(False)
			self.__scene.addWidget(self.__fold_btn)

			self.__raise_btn = QPushButton('Raise:')
			self.__raise_btn.setGeometry(x + self.btn_width, y, self.btn_width, self.btn_height)
			self.__raise_btn.setEnabled(False)
			self.__scene.addWidget(self.__raise_btn)

			self.__raise_sum_input = QLineEdit()
			self.__raise_sum_input.setGeometry(x + self.btn_width * 2, y, self.btn_width, self.btn_height)
			self.__raise_sum_input.setEnabled(False)
			self.__scene.addWidget(self.__raise_sum_input)

			self.__allin_btn = QPushButton('All-in')
			self.__allin_btn.setGeometry(x + self.btn_width, y + self.btn_height, self.btn_width * 2, self.btn_height)
			self.__allin_btn.setEnabled(False)
			self.__scene.addWidget(self.__allin_btn)

			self.__fold_btn.clicked.connect(self.__fold_clicked)
			self.__call_check_btn.clicked.connect(self.__call_check_clicked)
			self.__allin_btn.clicked.connect(self.__allin_clicked)
			self.__raise_btn.clicked.connect(self.__raise_clicked)

		def __fold_clicked(self):
			self.deactivate(Turn('fold', 0))

		def __call_check_clicked(self):
			if (self.__player.player_info().many() + self.__player.player_info().ante() >= self.__min_value) and (
					self.__min_value >= self.__player.player_info().ante()):
				self.deactivate(Turn('check or call', self.__min_value))

		def __allin_clicked(self):
			if self.__player.player_info().many() > 0:
				self.deactivate(Turn('allin', self.__player.player_info().many() + self.__player.player_info().ante()))
			else:
				msg_box = QMessageBox()
				msg_box.setText('You have no many!')
				msg_box.exec_()				

		def __raise_clicked(self):
			try:
				sum = int(self.__raise_sum_input.text())
				if sum >= self.__blind and sum <= self.__player.player_info().many():
					self.deactivate(Turn('raise', self.__player.player_info().ante() + sum))
				else:
					msg_box = QMessageBox()
					msg_box.setText('You have no many enough to this raise!')
					msg_box.exec_()				

			except ValueError:
				msg_box = QMessageBox()
				msg_box.setText('Not number in the input field!')
				msg_box.exec_()

		def activate(self, value, blind, player, func_to_call):
			self.__call_check_btn.setEnabled(True)
			self.__fold_btn.setEnabled(True)
			self.__raise_btn.setEnabled(True)
			self.__raise_sum_input.setEnabled(True)
			self.__allin_btn.setEnabled(True)

			self.__min_value = value
			self.__blind     = blind
			self.__player    = player
			self.__func_to_call = func_to_call

		def deactivate(self, turn_res):
			self.__call_check_btn.setEnabled(False)
			self.__fold_btn.setEnabled(False)
			self.__raise_btn.setEnabled(False)
			self.__raise_sum_input.setEnabled(False)
			self.__allin_btn.setEnabled(False)

			self.__func_to_call(turn_res)

	def __init__(self, table_info):
		self.__decision_block = TableGui.DecisionBlock()

		self.__table_info = table_info
		self.__table      = Table(table_info, self)

	def decision_block(self):
		return self.__decision_block

	def start(self):		
		self.__scene = QGraphicsScene()
		self.__view  = QGraphicsView(self.__scene)
		
		self.__table_image = QGraphicsPixmapItem(QPixmap('table.png'))
		self.__scene.addItem(self.__table_image)

		angle = math.pi * 2 / self.__table_info.player_count()
		radius_x = 400
		radius_y = 250
		cur_angle = math.pi / 2
		for player in self.__table_info.players():
			player_info_view = TableGui.PlayerInfoView(
				player
				, self.__scene
				, TableGui.center_x + radius_x * math.cos(cur_angle)
				, TableGui.center_y + radius_y * math.sin(cur_angle)
				)
			cur_angle += angle

		opened_card_view = TableGui.OpenedCardView(self.__scene, self.__table_info)
		bank_view = TableGui.BankView(self.__scene, self.__table_info)
		self.__decision_block.start(self.__scene, 'Call', 300, 320)

		self.__view.show()

	def __call__(self):
		self.__table.round()
Example #47
0
            files_xsec = files_ee_weights
            DirectoryNameForSteps = ['None', 'None', 'None' , 'None' , 'None' , 'None', 'None', 'None', '_NumberOfBJets']
    elif WhichChannel=='MM' :
        data_file = 'DoubleMuon2011'
        integrated_lumi = 4459.007
        SF_OF_Value = 'SameFlavours'
        DirectoryNameForSteps = ['None', 'None', 'None' , '' , '_InvMass12' , '_InvMassZ', '_NJets', '_MET', '_NumberOfBJets']
        EventTypeMinVal = 3
        EventTypeMaxVal = 4
        if RunOnSelectedEvents:
            files_xsec = files_mm_weights
            DirectoryNameForSteps = ['None', 'None', 'None' , 'None' , 'None' , 'None', 'None', 'None', '_NumberOfBJets']
        #Properties
    PropertiesToDraw = {'NumberOfJets':{} , 'PFMET':{}, 'Electrons_InvariantMass':{}, 'JetsHT':{} , 'NumberOfBJets':{} , 'FirstLeptonEta':{} , 'FirstLeptonPt':{} , 'SecondLeptonEta':{} , 'SecondLeptonPt':{} , 'FirstJetPt':{} , 'SecondJetPt':{} , 'ThirdJetPt':{} }

    t_PropertiesLinks = Table(False)
    PropertiesLinks = {}
    for Property in PropertiesToDraw.keys():
        PropertiesLinks[Property] = RowObject()
        t_PropertiesLinks.append( PropertiesLinks[Property] )
        
    PropertiesHistoPathFormat = 'Selection/EventSelectionHistosAfterObjectCreation/%(SF_OF)s%(Folder)s/%(SF_OF)s%(Folder)s_DiLeptonEvent_EventTypevs%(Property)s'

    cosThetaPlotName = 'costheta_%(channel)s/hCosThetaAllLepton' % {'channel':WhichChannel.lower()}
    stack_costheta = THStack("stackCosTheta",'CosTheta for ' + WhichChannel +' Events')
        
    selectionPlotName = 'Selection/hEventSelection%(channel)s' % {'channel':WhichChannel}

        #STYLE INFO
    colors = {'TTBarSummer2011':41, 'DYSummer2011':46 ,'WJetsSummer2011':31 , 'WWSummer2011':29 , 'SingleTopSummer2011':4 , 'SingleTopTWSummer2011':7 , 'WZSummer2011':90 , 'ZZSummer2011':66 }
Example #48
0
def UpdateAN2(outUV, nIF, err):
    """ 
    Convert AN table in outUV to nIF IFs
    
    * outUV       = output Obit UV object, defined but not instantiated
    * nIF         = number of desired output IFs
    * err         = Obit error/message stack
    """
    ################################################################
    iANTab = outUV.NewTable(Table.READONLY, "AIPS AN", 1, err)
    oANTab = outUV.NewTable(Table.WRITEONLY, "AIPS AN", 2, err, numIF=nIF)

    iANTab.Open(Table.READONLY, err)
    oANTab.Open(Table.WRITEONLY, err)

    # copy keys
    for k in iANTab.keys:
        oANTab.keys[k] = iANTab.keys[k]

    nrow = iANTab.Desc.Dict['nrow']  # How many rows?
    maxant = -1
    for irow in range(1, nrow + 1):
        row = iANTab.ReadRow(irow, err)  # Read input row
        if row['NOSTA'][0] > maxant:
            maxant = row['NOSTA'][0]
        # Update  row
        pca0 = row['POLCALA'][0]
        pca1 = row['POLCALA'][1]
        pcb0 = row['POLCALB'][0]
        pcb1 = row['POLCALB'][1]
        bm = row['BEAMFWHM'][0]
        Beama = []
        PolcalAa = []
        PolcalBa = []
        for i in range(0, nIF):
            Beama.append(bm)
            PolcalAa.append(pca0)
            PolcalAa.append(pca1)
            PolcalBa.append(pcb0)
            PolcalBa.append(pcb1)

        row['BEAMFWHM'] = Beama
        row['POLCALA'] = PolcalAa
        row['POLCALB'] = PolcalBa

        # Write output
        oANTab.WriteRow(irow, row, err)
        # End loop over rows
    iANTab.Close(err)
    oANTab.Close(err)
    # zap AN old
    outUV.ZapTable("AIPS AN", 1, err)
    # Copy
    iANTab = outUV.NewTable(Table.READONLY, "AIPS AN", 2, err)
    oANTab = outUV.NewTable(Table.WRITEONLY, "AIPS AN", 1, err)
    Table.PCopy(iANTab, oANTab, err)
    # zap AN old
    outUV.ZapTable("AIPS AN", 2, err)
    # Update
    outUV.UpdateDesc(err)
    OErr.printErrMsg(err, "Error converting AN Table")
    return maxant
Example #49
0
    def _render_icon_list(self):
        # Include its JavaScript file
        #
        txt = '<script src="/static/js/icons.js" type="text/javascript"></script>'
        txt += "<h1>Icons configuration</h1>"

        tabs = []

        # Suffixes
        #
        icons = self._cfg['icons!suffix']

        tmp = ''
        if icons and icons.has_child():
            tmp += "<h3>Extension list</h3>"

            table = Table(4, 1)
            table += ('', 'File', 'Extensions', '')

            for icon in icons:
                cfg_key = 'icons!suffix!%s' % (icon)
                im = self._get_img_from_icon(icon, cfg_key)

                entry = self.InstanceEntry(cfg_key, 'text', size=45)
                js = "post_del_key('/icons/update', '%s');" % (cfg_key)
                link_del = self.InstanceImage("bin.png",
                                              "Delete",
                                              border="0",
                                              onClick=js)
                table += (im, icon, entry, link_del)

            tmp += self.Indent(table)

        # New suffix
        fo1 = Form("/%s/add_suffix" % (self._id), add_submit=False, auto=False)
        op1, im1 = self._get_options_icons('suffix_new_file',
                                           self._filter_icons_in_suffixes)
        en2 = self.InstanceEntry('suffix_new_exts', 'text')
        ta1 = Table(4, 1)
        ta1 += ('', 'Icon', 'Extensions', '')
        ta1 += (im1, op1, en2, SUBMIT_ADD)
        tmp += "<h3>Add suffix</h3>"
        tmp += fo1.Render(self.Indent(ta1))

        tabs += [('Extensions', tmp)]

        # Special icons
        #
        table = Table(3, 1)
        icons = self._cfg['icons']

        op_def, im_def = self._get_options_icons('icons!default')
        op_dir, im_dir = self._get_options_icons('icons!directory')
        op_par, im_par = self._get_options_icons('icons!parent_directory')

        table += ('', 'Icon', 'File')
        table += (im_def, 'Default', op_def)
        table += (im_dir, 'Directory', op_dir)
        table += (im_par, 'Go to Parent', op_par)

        tmp = "<h3>Special Entries</h3>"
        tmp += self.Indent(table)

        tabs += [('Special Icons', tmp)]

        # Files
        #
        icons = self._cfg['icons!file']

        tmp = ''
        if icons and icons.has_child():
            tmp += "<h3>File list</h3>"

            table = Table(4, 1)
            table += ('', 'Match', 'File')

            for icon_name in icons:
                cfg_key = 'icons!file!%s' % (icon_name)
                match = self._cfg.get_val(cfg_key)
                op, im = self._get_options_icons(cfg_key, selected=icon_name)
                js = "post_del_key('/icons/update', '%s');" % (cfg_key)
                link_del = self.InstanceImage("bin.png",
                                              "Delete",
                                              border="0",
                                              onClick=js)
                table += (im, match, op, link_del)

            tmp += self.Indent(table)

        # New file
        fo1 = Form("/%s/add_file" % (self._id), add_submit=False, auto=False)
        op1, im1 = self._get_options_icons('file_new_file')
        en1 = self.InstanceEntry('file_new_match', 'text')
        ta1 = Table(4, 1)
        ta1 += ('', 'File', 'Icon', '')
        ta1 += (im1, en1, op1, SUBMIT_ADD)
        tmp += "<h3>Add file</h3>"
        tmp += fo1.Render(self.Indent(ta1))

        tabs += [('Files', tmp)]

        txt += self.InstanceTab(tabs)
        return txt
Example #50
0
from Test import Test
import Table
import Plot

N = 1000

t = Test(N)

isb = t.InsertionSortBest()
ism = t.InsertionSortRandom()
isw = t.InsertionSortWorst()
msb = t.MergeSortBest()
msm = t.MergeSortRandom()
msw = t.MergeSortWorst()

Plot.GraphicPlot(N, isb, ism, isw, msb, msm, msw)
Table.ExperimentalDataTable(isb, ism, isw, msb, msm, msw)
Example #51
0
 def __init__(self, frames, hdd):
     self._frames = frames
     self._free_frames = frames
     self._table = Table()
     self._hdd = hdd
Example #52
0
    def __WHERE(self, conditions, inTable=None):
        OR_condition = self.__ORsplit(conditions)
        temp = ''
        result = None
        self.__copyTable()
        for o in OR_condition:
            AND_condition = self.__ANDsplit(o)
            temp_result = None
            self.__reNew()
            for c in AND_condition:
                inC = c.split()

                notIN = False
                if 'IN' in inC:
                    inData = ''

                    for i in range(len(inC)):
                        if inC[i] == 'IN':
                            for j in range(i + 1, len(inC)):
                                inData += ' ' + inC[j]
                            outDataI = i
                            break
                        elif inC[i] == 'NOT' and inC[i + 1] == 'IN':
                            notIN = True
                            for j in range(i + 2, len(inC)):
                                inData += ' ' + inC[j]
                            outDataI = i
                            break
                    outData = ''
                    for i in range(0, outDataI):
                        outData += inC[i]
                    outData = outData.strip('(').strip(')')

                    inData = inData.strip()
                    inst = instruction()
                    inst.setData(inData)

                    inst.addFROM(self.instruction.getFROM())
                    q = querier()
                    inTable = q.execute(inst, self.data)

                    c1 = outData.split(',')
                    c2 = inst.getSELECT().split(',')
                    self.tables.insert(0, inTable)
                    index1 = -1
                    index2 = -1
                    for j in range(len(c1)):
                        c1[j] = c1[j].strip()
                        c2[j] = c2[j].strip()
                        newC = c1[j] + ' = ' + c2[j]
                        index1 = -1
                        index2 = -1
                        for i in range(len(self.tables)):
                            if c1[j] in self.tables[i].getAttributes():
                                index1 = i
                            if c2[j] in self.tables[i].getAttributes():
                                index2 = i
                        temp_result = Table.join(self.tables[index1],
                                                 self.tables[index2], newC)
                        if (notIN):
                            self.tables[index1] = Table.minus(
                                self.tables[index1], temp_result)

                        else:
                            self.tables[index1] = Table.copy(temp_result)
                        temp_result = self.tables[index1]
                        if index1 != index2:
                            del (self.tables[index2])
                else:
                    c = self.__normorize(c)
                    c_list = c.split()
                    index1 = -1
                    index2 = -1
                    for i in range(len(self.tables)):
                        if c_list[0] in self.tables[i].getAttributes():
                            index1 = i
                        if c_list[2] in self.tables[i].getAttributes():
                            index2 = i

                    if index2 == -1:
                        self.tables[index1] = self.tables[index1].select(c)
                        temp_result = Table.copy(self.tables[index1])
                    else:
                        self.tables[index1] = Table.join(
                            self.tables[index1], self.tables[index2], c)
                        temp_result = Table.copy(self.tables[index1])
                        if index1 != index2:
                            del (self.tables[index2])
            result = Table.union(result, temp_result)
        if self.instruction.hasGROUP():
            result = result.project(self.attributes,
                                    self.instruction.getGROUPBY())
            c = self.__normorize(self.instruction.getHAVING())
            result = result.select(c)
            return result
        else:

            if len(self.attributes) == 1 and self.attributes[0].strip() == '*':
                return result
            print(result)
            return result.project(self.attributes)
Example #53
0
 def test_position(self):
     """position"""
     self.assertRaises(ValueError, Table.position, 'badval')
     self.assertEqual('North', Table.position('North').position)
     self.assertEqual(0, Table.position('North').score)
Example #54
0
def UpdateFQ2(outUV, nIF, err):
    """ 
    Convert FQ table in outUV to nIF IFs
    
    * outUV       = output Obit UV object, defined but not instantiated
    * nIF         = number of desired output IFs
                    MUST be the same number of channels per IF
    * err         = Obit error/message stack
    """
    ################################################################
    iFQTab = outUV.NewTable(Table.READONLY, "AIPS FQ", 1, err)
    oFQTab = outUV.NewTable(Table.WRITEONLY, "AIPS FQ", 2, err, numIF=nIF)
    # Input info
    d = outUV.Desc.Dict
    jlocf = d["jlocf"]
    reffreq = d["crval"][jlocf]
    delfreq = d["cdelt"][jlocf]
    freqpix = d["crpix"][jlocf]
    nchan = d["inaxes"][jlocf]
    # Can use row from input table
    iFQTab.Open(Table.READONLY, err)
    oFQTab.Open(Table.WRITEONLY, err)
    row = iFQTab.ReadRow(1, err)
    iFQTab.Close(err)

    # Update row for nif IFs
    freqarr = []
    chw = row['CH WIDTH'][0]
    chwarr = []
    tbw = row['TOTAL BANDWIDTH'][0] / nIF
    tbwarr = []
    sideband = row['SIDEBAND'][0]
    sbarr = []
    rxc = row['RXCODE'][0]
    rxcarr = ""
    for iIF in range(1, nIF + 1):
        freqarr.append((iIF - freqpix) * delfreq * nchan)
        chwarr.append(chw)
        tbwarr.append(tbw)
        sbarr.append(sideband)
        rxcarr += rxc
    row['IF FREQ'] = freqarr
    row['CH WIDTH'] = chwarr
    row['TOTAL BANDWIDTH'] = tbwarr
    row['SIDEBAND'] = sbarr
    row['RXCODE'] = [rxcarr]

    # Write output
    oFQTab.WriteRow(1, row, err)
    oFQTab.Close(err)
    # zap FQ old
    outUV.ZapTable("AIPS FQ", 1, err)
    # Copy
    iFQTab = outUV.NewTable(Table.READONLY, "AIPS FQ", 2, err)
    oFQTab = outUV.NewTable(Table.WRITEONLY, "AIPS FQ", 1, err)
    Table.PCopy(iFQTab, oFQTab, err)
    # zap FQ old
    outUV.ZapTable("AIPS FQ", 2, err)
    # Update
    outUV.UpdateDesc(err)
    OErr.printErrMsg(err, "Error converting FQ Table")
Example #55
0
        ret +=  "|" + str(the_vals[2])
        ret +=  "|" + str(the_vals[3])
        ret +=  "|" + str(the_vals[4])
        ret +=  "|" + str(the_vals[5])
        ret +=  "|" + str(the_vals[6])
        ret +=  "|" + str(the_vals[7])
        
        ret += "|"

        return ret
        

for  WhichChannel_ in ['Combined']: # ,'EM' , 'MM' , 'EE' ]:
     WhichChannel = WhichChannel_
     
     t_mc = Table()
     t_mc_w = Table()

     #AllSamples = [ SampleInfoType. __getattribute__( SamplesInfo[sample] , WhichChannel) for sample in SamplesInfo ]
     AllSamples = dict( ( sample , SampleInfoType. __getattribute__( SamplesInfo[sample] , WhichChannel) ) for sample in SamplesInfo  )

     print >>org_file,'* ' + WhichChannel
     if PrintCutFlowTables:
         print AllSamples
         print >>org_file,"** Wights"

         last_column_name = ''
         last_column_name_w = ''

         for sampleName in sorted_samples:
             sample = AllSamples[sampleName]
Example #56
0
def UpdateSU2(outUV, nIF, err):
    """ 
    Convert SU table in outUV to nIF IFs
    
    * outUV       = output Obit UV object, defined but not instantiated
    * nIF         = number of desired output IFs
    * err         = Obit error/message stack
    """
    ################################################################
    # Is there an SU table?
    try:
        iSUTab = outUV.NewTable(Table.READONLY, "AIPS SU", 1, err)
        oSUTab = outUV.NewTable(Table.WRITEONLY, "AIPS SU", 2, err, numIF=nIF)
    except:
        return

    iSUTab.Open(Table.READONLY, err)
    oSUTab.Open(Table.WRITEONLY, err)
    nrow = iSUTab.Desc.Dict['nrow']  # How many rows?

    for irow in range(1, nrow + 1):
        row = iSUTab.ReadRow(irow, err)  # Read input row

        # Update row
        fo = row['FREQOFF'][0]
        bw = row['BANDWIDTH'][0]
        iflx = row['IFLUX'][0]
        qflx = row['QFLUX'][0]
        uflx = row['UFLUX'][0]
        vflx = row['VFLUX'][0]
        lsr = row['LSRVEL'][0]
        rest = row['RESTFREQ'][0]
        iflxa = []
        qflxa = []
        uflxa = []
        vflxa = []
        foa = []
        lsra = []
        rfa = []
        for i in range(0, nIF):
            iflxa.append(iflx)
            qflxa.append(qflx)
            uflxa.append(uflx)
            vflxa.append(vflx)
            foa.append(fo)
            lsra.append(lsr)
            rfa.append(rest)

        row['IFLUX'] = iflxa
        row['QFLUX'] = qflxa
        row['UFLUX'] = uflxa
        row['VFLUX'] = vflxa
        row['FREQOFF'] = foa
        row['LSRVEL'] = lsra
        row['RESTFREQ'] = rfa

        # Write output
        oSUTab.WriteRow(irow, row, err)
        # end loop over rows
    iSUTab.Close(err)
    oSUTab.Close(err)
    # zap SU old
    outUV.ZapTable("AIPS SU", 1, err)
    # Copy
    iSUTab = outUV.NewTable(Table.READONLY, "AIPS SU", 2, err)
    oSUTab = outUV.NewTable(Table.WRITEONLY, "AIPS SU", 1, err)
    Table.PCopy(iSUTab, oSUTab, err)
    # zap SU old
    outUV.ZapTable("AIPS SU", 2, err)
    # Update
    outUV.UpdateDesc(err)
    OErr.printErrMsg(err, "Error converting SU Table")
Example #57
0
    if not CalcWeights:
        files = files_ee_weights
    integrated_lumi = 4529.518
elif WhichChannel=='mm' :
    files_data = { 'DoubleMuon2011':1 }
    if not CalcWeights:
        files = files_mm_weights
    integrated_lumi = 4459.007

if not MC :
    files = files_data

if CalcWeights:
	files = files_xsec

t=Table()

cosThetaPlot_Name = 'costheta_%(channel)s/hCosThetaAllLepton' % {'channel':WhichChannel}
hs = THStack("hs",WhichChannel)
histos = {}
canvases = {}

print WhichChannel
print "- Wights"

for wpol_file in files.keys():
    #print wpol_file
    colIndex = 0
    file = TFile( 'WPol_SelectedTTBars_%s.root' % wpol_file , "READ")
    r = RowObject()
    colName = '%(colIndex)d-%(step)s' % {'colIndex': colIndex , 'step': 'DataSet'}