Example #1
0
def test_pivots_by_comparing():
    # Find vertices using bland
    b = Bland(*reader('data/cs_polytopes_boxed.ine'))
    b.augment_matrix_with_objective()
    b.init_dicts()
    b.add_box_constraints(b.bounding_box)
    b.first_basis()
    search = b.search()
    status = SearchStatus.NONE
    while status != SearchStatus.DONE:
        status = search.__next__()

    # Find vertices using criss-cross
    c = CrissCross(*reader('data/cs_polytopes_boxed.ine'))
    c.augment_matrix_with_objective()
    c.init_dicts()
    c.add_box_constraints(b.bounding_box)
    c.first_basis()
    search = c.search()
    status = SearchStatus.NONE
    while status != SearchStatus.DONE:
        status = search.__next__()

    assert len(set(b.vertices) -
               set(c.vertices)) == len(set(c.vertices) - set(b.vertices)) == 0

    from brute_force import brute_force_vertices

    vertices, vertices_inside_box = brute_force_vertices(
        b.hyperplanes, b.bounding_box)

    for vertex in set(b.vertices) - vertices_inside_box:
        assert any([cob.box_variable for cob in vertex.cobasis])
Example #2
0
 def open_file(self):
     options = QFileDialog.Options()
     options |= QFileDialog.DontUseNativeDialog
     fileName, _ = QFileDialog.getOpenFileName(
         self,
         "QFileDialog.getOpenFileName()",
         "",
         "All Files (*);;Ine Files (*.ine)",
         options=options)
     if fileName:
         if self.lrs is not None:
             self.reset_controls()
             self.first_basis_found = False
         else:
             self.create_coordinate_controls()
             self.first_basis_button.setDisabled(False)
     self.pivot_rule_button.deleteLater()
     self.search_status = SearchStatus.NONE
     if self.pivot_rule == 'CrissCross':
         self.lrs = CrissCross(*reader(fileName))
     elif self.pivot_rule == 'Bland':
         self.lrs = Bland(*reader(fileName))
     self.lrs.augment_matrix_with_objective()
     self.lrs.init_dicts()
     if len(self.lrs.bounding_box) > 0:
         self.lrs.add_box_constraints(self.lrs.bounding_box)
     self.update_status(update_hyperplanes=True)
Example #3
0
def search_folder(read_path: str, dict_path: list):
    #global folder
    #myfolder = open_folder_path(dict_path)
    global global_path
    filt = reader.reader.filter(read_path)
    files = reader.reader(read_path).read_all()
    global_path = read_path
    folders = reader.create_list(files, None, check_folder,
                                 True)  #file_filter)#filt.file_filter()
    files = filt.invert(folders)
    files = reader.create_list(files, "bin", reader.end)
    for file in files:
        #myfolder[""]
        add_to_folder(dict_path, file)

    for fold in folders:
        d_path = dict_path
        add_folder_to_folder(d_path, "{}", str(fold))
        #print ("dict path before:", dict_path)
        p = dict_path
        p.append(str(fold))
        r_path = read_path
        #print ("dict path after:", dict_path)
        search_folder(r_path + "/" + str(fold), p)
        del dict_path[len(dict_path) - 1]
Example #4
0
 def read(self):
     """ Read a MySQL dump schema file """
     parsing = reader.reader(self._schemaFile)
     self._prologue = parsing["prologue"]
     self.convertSQLToSchema(parsing["schema"])
     self._engine = parsing["engine"]
     self._epilogue = parsing["epilogue"]
def sky(filename):
    """ Takes as input the name of the file, where all the parameters are, and
    from this takes the sky data file (Palomar data as default choice).
    Returns flux from sky."""

    # import the parameters from the parameter file so to use the sky data file
    filtername, spectraltype, mV,  startrange, endrange, arrsize, skyfile,\
                atmofile, telefile, pbfiltername, fudgefactor, expostime, diameter,\
                seeingvalue, quantumeff, startrange2, endrange2, vbessel, umag, gmag,\
                rmag,imag,zmag = reader(filename)

    old = os.getcwd()  # current folder
    folder = r"../data files to load"  # select the data folder
    os.chdir(folder)  # and go to it

    skydata = np.genfromtxt(skyfile)
    skydata_spectra = skydata[:, 1] * 2.5  # add 1 mag for Palomar sky

    # debug by plotting skydata
    #    plt.figure()
    #    plt.plot(skydata[:,0],skydata_spectra)
    #    plt.xlabel(" ")
    #    plt.ylabel(" ")
    #    plt.title("Sky spectrum")
    #    plt.show()

    return skydata_spectra

    os.chdir(old)  # return to the original folder
Example #6
0
    def initializeParameters(self):

        with open('./.pathToAP', 'r') as textFile:
            self.pathToAP = textFile.readline()

        sys.path.append(self.pathToAP)
        from reader import reader

        reader = reader()
        reader.readParameters()
        parameters = reader.getParameters()

        for item in parameters:
            try:
                setattr(self, item[:item.find('=')],
                        int(item[item.find('=') + 1:]))
            except ValueError:
                setattr(self, item[:item.find('=')], item[item.find('=') + 1:])

        self.mouseCursor = PyMouse()
        if self.control != 'tracker':
            self.mousePosition = self.winWidth - 8 - self.xBorder, self.winHeight - 48 - self.yBorder
            self.mouseCursor.move(*self.mousePosition)

        mixer.init()
        if self.pressSound.lower() != 'off':
            self.pressingSound = mixer.Sound(self.pathToAP +
                                             '/sounds/pressSound.ogg')
Example #7
0
def main():
	# data = get_parse()
	trace = reader(sys.argv[1])
	print(trace[0][0], end = " ")
	print(trace[0][1])
	print(trace[1][0], end = " ")
	print(trace[1][1])
Example #8
0
 def add(self, blockchain, help, chainresult):
     print("To add more type ADD if you have added all files type END")
     s = input()
     if s == "END":
         if chainresult != []:
             print("Hash von " + str(chainresult) + " ist fehlerhaft.")
             self.blockchain = blockchain
             return
         if chainresult == []:
             block.block(str(help + 1), "Blockchain richtig.", "")
             self.blockchain = blockchain
             return
     if s == "ADD":
         print("Type the next block file path")
         file = input()
         help = help + 1
         print(blockchain.chainlist)
         print(len(blockchain.chainlist))
         blockfile = reader.reader(file)
         blockf = block.block(blockfile.fileblocknr, blockfile.filedata,
                              blockchain, blockfile.nonce)
         if blockf.hash != blockfile.filehash:
             print(str(blockf.hash) + " File" + str(blockfile.filehash))
             chainresult.append("Block " + str(help))
         self.add(blockchain, help, chainresult)
Example #9
0
    def initializeParameters(self):

        textFile = codecs.open("./.pathToAP", mode="r", encoding="utf-8")
        self.pathToAP = textFile.readline()
        textFile.close()

        sys.path.append(self.pathToAP)
        from reader import reader

        reader = reader()
        reader.readParameters()
        parameters = reader.getParameters()

        for item in parameters:
            try:
                setattr(self, item[:item.find('=')],
                        int(item[item.find('=') + 1:]))
            except ValueError:
                setattr(self, item[:item.find('=')], item[item.find('=') + 1:])

        self.flaga = 0
        self.checkFlag = False
        self.flag = 'row'
        self.columnIteration = 0
        self.rowIteration = 0
        self.maxRowIteration = 2 * 5
        self.maxColumnIteration = 2 * 4
        self.countRow = 0
        self.countColumn = 0

        self.pressFlag = True
        self.PicNr = 0
        self.result = 0

        self.labels = ['speak', 'literuj', 'undo', 'exit']

        self.WordsList = os.listdir(self.pathToAP +
                                    'multimedia/ewriting/pictures')
        shuffle(self.WordsList)
        self.poczatek = True
        self.czyBack = False
        self.numberOfExtraWords = 3

        self.numberOfPresses = 1

        if self.control != 'tracker':
            self.mouseCursor = PyMouse()
            self.mousePosition = self.winWidth - 8 - self.xBorder, self.winHeight - 8 - self.yBorder
            self.mouseCursor.move(*self.mousePosition)

        if self.switchSound.lower() != 'off' or self.pressSound.lower(
        ) != 'off':
            mixer.init()
            self.switchingSound = mixer.Sound(self.pathToAP +
                                              '/sounds/switchSound.ogg')
            self.pressingSound = mixer.Sound(self.pathToAP +
                                             '/sounds/pressSound.ogg')

            self.powrotSound = mixer.Sound(self.pathToAP +
                                           '/sounds/powrot.ogg')
Example #10
0
 def __init__(self,infile='../../examples/test.info'):
     self.msg=messages.messages()
     self.msg.print_intro()
     self.reader=reader.reader(infile)
     
     pdf_set=self.reader.get_str_variable('pdf_set','NNPDF30_nnlo_as_0118')
     pdf_mem=self.reader.get_i_variable('pdf_mem',0)
     order_5f=self.reader.get_i_variable('order_5f',2)
     order_fonll=self.reader.get_i_variable('order_fonll',2)
     mb=self.reader.get_d_variable('mb',4.58)
     mur=self.reader.get_d_variable('mur',125.)
     muf=self.reader.get_d_variable('muf',125.)
     mh=self.reader.get_d_variable('mh',125.)
     sqrts=self.reader.get_d_variable('sqrts',13000)
     iter=self.reader.get_i_variable('iter',100000)
     a_min=self.reader.get_d_variable('a_min',0.7e-2)
     proc=self.reader.get_str_variable('proc','bbz') 
     self.scale=fb.new_Scales(2,2,mb,mur,muf,mh,sqrts,iter,pdf_mem,a_min,proc)
     self.calc=self.reader.get_str_variable('calc_type','var_mass')              
     self.pdf=fb.new_LUMI(pdf_set, pdf_mem, muf, mb, False);
     nlo_file=self.reader.get_str_variable('4f_nlo_file','4f/4F_NLO.txt')
     lo_file=self.reader.get_str_variable('4f_lo_file','4f/4F_LO.txt')
     gg_file=self.reader.get_str_variable('4f_gg_file','4f/4F_gg.txt')
     
     self.B=f_4f.B_coeff(nlo_file,lo_file,gg_file,self.pdf,[mur,muf,mb])
     self.A=f_5f.A_coeff(self.scale,pdf_set)
     self.A0=massless_lim.A0_coeff(self.scale,pdf_set)
     
     self.mh=mh
     self.mur=mur
     self.muf=muf
     self.order_5f=order_5f
     self.order_fonll=order_fonll
Example #11
0
def method_edge_counter(topic):
    d = reader(topic)
    count = 0
    for n in d:
        if isinstance(n, int):
            continue
        count += len(n.past)
    return count
Example #12
0
    def initializeParameters(self):

        textFile = codecs.open("./.pathToAP", mode="r", encoding="utf-8")
        self.pathToAP = textFile.readline()
        textFile.close()

        # with open( './.pathToAP' ,'r' ) as textFile:
        # 	self.pathToAP = textFile.readline( )

        sys.path.append(self.pathToAP)
        from reader import reader

        reader = reader()
        reader.readParameters()
        parameters = reader.getParameters()

        for item in parameters:
            try:
                setattr(self, item[:item.find('=')],
                        int(item[item.find('=') + 1:]))
            except ValueError:
                setattr(self, item[:item.find('=')], item[item.find('=') + 1:])

        self.ownWord = ''
        self.flaga = 0
        self.checkFlag = False
        self.PicNr = 0
        self.result = 0

        self.WordsList = os.listdir(
            unicode(self.pathToAP) + u"multimedia/ewriting/pictures")
        shuffle(self.WordsList)

        self.poczatek = True
        self.czyBack = False

        self.numberOfPresses = 1
        self.pressFlag = False

        self.numberOfIteration = 0
        self.maxNumberOfIteration = 2 * 5

        if self.control != 'tracker':
            self.mouseCursor = PyMouse()
            self.mousePosition = self.winWidth - 8 - self.xBorder, self.winHeight - 8 - self.yBorder
            self.mouseCursor.move(*self.mousePosition)

        if self.switchSound.lower() != 'off' or self.pressSound.lower(
        ) != 'off':
            mixer.init()
            self.switchingSound = mixer.Sound(self.pathToAP +
                                              '/sounds/switchSound.ogg')
            self.pressingSound = mixer.Sound(self.pathToAP +
                                             '/sounds/pressSound.ogg')

            self.powrotSound = mixer.Sound(self.pathToAP +
                                           '/sounds/powrot.ogg')
Example #13
0
    def initializeParameters(self):

        with open('.pathToAP', 'r') as textFile:
            self.pathToAP = textFile.readline()

        sys.path.append(self.pathToAP)
        from reader import reader

        reader = reader()
        reader.readParameters()
        parameters = reader.getParameters()

        for item in parameters:
            try:
                setattr(self, item[:item.find('=')],
                        int(item[item.find('=') + 1:]))
            except ValueError:
                setattr(self, item[:item.find('=')], item[item.find('=') + 1:])

        self.flag = 'row'
        self.pressFlag = False
        self.pressedStopFlag = False

        self.rowIteration = 0
        self.colIteration = 0

        self.numberOfColumns = 2,
        self.numberOfRows = 7,

        self.numberOfEmptyIteration = 0
        self.countRows = 0
        self.countColumns = 0
        self.countMaxRows = 2
        self.countMaxColumns = 2
        self.numberOfPresses = 0
        self.trackCounter = 0

        self.initCount = 0  #it's better to use another timer than conditions
        self.initCount2 = 0

        self.mouseCursor = PyMouse()
        if self.control != 'tracker':
            self.mousePosition = self.winWidth - 8 - self.xBorder, self.winHeight - 48 - self.yBorder
            self.mouseCursor.move(*self.mousePosition)

        if self.switchSound.lower() == 'on' or self.pressSound.lower() == 'on':
            mixer.init()
            if self.switchSound.lower() == 'on':
                self.switchingSound = mixer.Sound(self.pathToAP +
                                                  '/sounds/switchSound.ogg')
            if self.pressSound.lower() == 'on':
                self.pressingSound = mixer.Sound(self.pathToAP +
                                                 '/sounds/pressSound.ogg')

        self.width = self.numberOfColumns[0] * 120
        self.height = self.numberOfRows[0] * 100
Example #14
0
def get_data():
    
    grid_data = get_shape()
    
    if grid_data.nd >= 1:
        x = reader('x',[0,1,-1],0,0)
        grid_data.xlim = x[[0,2]]
        grid_data.Lx   = x[2] - x[0]
    if grid_data.nd >= 2:
        y = reader('y',0,[0,1,-1],0)
        grid_data.ylim = y[[0,2]]
        grid_data.Ly   = y[2] - y[0]
    if grid_data.nd >= 3:
        z = reader('z',0,0,[0,1,-1])
        grid_data.zlim = z[[0,2]]
        grid_data.Lz   = z[2] - z[0]
    
    return grid_data
## ------
def generatorspectra(spectype, mV, filename): 
    """Takes as inputs: 
    the spectral type and magnitude of an object;
    and the name of the file, where all the parameters are.
    Generates a spectra."""
    
    # import the parameters from the parameter file 
    ffiltername, spectraltype, mV,  startrange, endrange, arrsize, skyfile,\
                atmofile, telefile, pbfiltername, fudgefactor, expostime, diameter,\
                seeingvalue, quantumeff, startrange2, endrange2, vbessel, umag, gmag,\
                rmag,imag,zmag = reader(filename)    
    
    # take into account the filter    
    vf, fluxfilt = loadfilter(filename)

     # spectra in 1 Angstrom bins from 0 to 9999 Angstroms
    spectra = np.zeros(arrsize)

    # Generate a blackbody spectra if spectype < 100
    if spectype > 100: # if spectral type > 100, then power law with slope type
        T = spectype    # blackbody temperature is given by the spectral type
        
        # waveleng in cm; array starts from 1 to avoid division by zero
        wavelength = np.arange(1,arraysize) * 1E-8  
        spectra[1:,] = (2.0*h*c**2/wavelength**5)\
        /( np.exp(np.longfloat(h*c/(wavelength*k*T)))-1.0 ) #Planck's law

    # Generate a power law spectra if spectype is smaller or equal to 100
    if spectype <= 100:        
        powerbase = np.arange(1,arrsize)
        # start from 1 to avoid problems when dividing by zero
        spectra[1:,] = powerbase ** spectype
    
    # normalize 
    spectra = spectra/np.max(spectra[startrange:endrange])  
    fluxspec = np.sum(spectra[startrange:endrange])/(endrange-startrange)
    spectra = spectra/ fluxspec
    
    # normalised convolution of spectra and filter
    fluxV = np.sum(vf[startrange:endrange] * spectra[startrange:endrange]) / (endrange-startrange) 
    
    # Normalize to specified mV - result should be in erg/s/cm^2/Angstrom
    spectra = spectra * (fluxV/fluxfilt) * 3.63E-9 * (10.0 ** (-mV/2.5)) # fluxfilt is flux from the filter (default is V filter)
    
       # debug below: check the spectra by plotting it
#    wavelengths = np.arange(10000) *1E-8    
#    plt.figure()
#    plt.plot(wavelengths*1E8, spectra)
#    plt.xlabel("Wavelength (cm)")
#    plt.ylabel("Spectral radiance")
#    plt.legend()
#    plt.show()
       
#    print "mAB at 6000 Angstroms = ",-2.5*np.log10(spectra[6000]) - 21.1 
    return spectra   
Example #16
0
def confirm_Page(domain, term):


    body = reader.reader(domain, "OJ6jo9V0rAu5OITm4SbhzWHrJcKyzDtaB8s4INic", 720)

    d = json.loads(str(body))
    if(term in str((d['content']))):
        return True

    else:
        return False
Example #17
0
def translate_cue_code(cue_code):
    nodes = reader(cue_code.split('\n'), CueGeneric)
    root = nodes.next()

    tree = Transformer().visit(root)

    print ast.dump(tree)

    out = StringIO()
    Unparser(tree, out)
    return out.getvalue()
Example #18
0
 def addgen(self, chainresult):
     print("Type the path of the next block file in the right order")
     genesisIn = input()
     gen = reader.reader(genesisIn)
     testChain = blockchain.blockchain([])
     gent = block.block(gen.fileblocknr, gen.filedata, testChain, gen.nonce)
     print("genesis block has been added to the testchain")
     if gent.hash != gen.filehash:
         chainresult.append("Block 0")
     help = 0
     self.add(testChain, help, chainresult)
Example #19
0
	def initializeParameters(self):

		with open( './.pathToAP' ,'r' ) as textFile:
			self.pathToAP = textFile.readline( )

		sys.path.append( self.pathToAP )
		from reader import reader
		
		reader = reader()
		reader.readParameters()
		parameters = reader.getParameters()

		for item in parameters:
			try:
				setattr(self, item[:item.find('=')], int(item[item.find('=')+1:]))
			except ValueError:
				setattr(self, item[:item.find('=')], item[item.find('=')+1:])
							
		self.pressFlag = False

		self.numberOfColumns = 2,
		self.numberOfRows = 2,
		
		self.columnIteration = 0
		self.rowIteration = 0						
		self.panelIteration = 0
		self.emptyColumnIteration = 0
		self.emptyRowIteration = 0
		self.emptyPanelIteration = 0
		self.maxEmptyColumnIteration = 2									
		self.maxEmptyRowIteration = 2									
		self.maxEmptyPanelIteration = 2
		
		self.numberOfPresses = 1

		if self.control != 'tracker':
			self.mouseCursor = PyMouse( )
			self.mousePosition = self.winWidth - 8 - self.yBorder, self.winHeight - 8 - self.xBorder
			self.mouseCursor.move( *self.mousePosition )			

                mixer.init()
		if self.switchSound.lower( ) != 'off' or self.pressSound.lower( ) != 'off':
				self.switchingSound = mixer.Sound( self.pathToAP + '/sounds/switchSound.ogg' )
				self.pressingSound = mixer.Sound( self.pathToAP + '/sounds/pressSound.ogg' )
                                
                                self.graSound = mixer.Sound( self.pathToAP + '/sounds/gra.ogg' )
                                self.oneSound = mixer.Sound( self.pathToAP + '/sounds/rows/1.ogg' )
                                self.pisanieSound = mixer.Sound( self.pathToAP + '/sounds/pisanie.ogg' )
                                self.powrotSound = mixer.Sound( self.pathToAP + '/sounds/powrot.ogg' )
                                self.usypiamSound = mixer.Sound( self.pathToAP + '/sounds/usypiam.ogg' )
		
		self.SetBackgroundColour( 'black' )
Example #20
0
    def __init__(self, _adr, _psw, _w3, _firstRev):

        self.Writer = writer(_psw, _adr, _w3)

        self.w3 = _w3

        self.Reader = reader(_adr, _w3)

        self.Password = _psw

        self.Address = _adr

        self.ToReveal = json.dumps(_firstRev)
Example #21
0
def simulatekid(spectra,
                expostime,
                sky,
                filename,
                output,
                default_exptime=True):
    """Takes as input the initial spectra, 
        the exposure time in seconds,
        the sky spectra,
        the name of the file, where all the parameters are,
        if default_exptime = True uses the exposure time in the parameter file,
        otherwise that inserted in the input.
        outpt=1 returns SNR; output = 3 returns SNR, photons and skyphotons"""

    # import the parameters from the parameter file
    filtername, spectraltype, mV,  startrange, endrange, arrsize, skyfile,\
                atmofile, telefile, pbfiltername, fudgefactor, exposure_time, diameter,\
                seeingvalue, quantumeff, startrange2, endrange2, vbessel, umag, gmag,\
                rmag,imag,zmag  = reader(filename)

    # if default_exptime = True uses the exposure time in the parameter file,
    # otherwise that inserted in the input.
    if default_exptime == True:
        expostime = exposure_time

    wavelength = np.arange(arrsize) * 1E-8  # wavelength in cm
    kidQE = np.zeros(arrsize)
    kidQE[startrange2:endrange2] = quantumeff

    # compue photons from spectra and convert into ergs/Angstrom
    photons = spectra * np.pi * expostime * (diameter * 50.0)**2
    photons = photons * kidQE  # take into account QE of the device
    photons = photons * wavelength / (h * c)
    tphot = np.sum(photons)

    # Compute sky background and convert into ergs/Angstrom
    skyphotons = sky * np.pi * expostime * (diameter * 50.0)**2 * np.pi * (
        seeingvalue / 2.0)**2
    skyphotons = skyphotons * kidQE  # takes into account QE of the device
    skyphotons = skyphotons * wavelength / (h * c)
    tsky = np.sum(skyphotons)

    SNR = tphot / np.sqrt(tsky)
    if tphot < 10:
        SNR = 0.0

    # select desired output
    if output == 3:
        return SNR, photons, skyphotons
    if output == 1:
        return SNR
Example #22
0
    def initializeParameters(self):

        with open('./.pathToAP', 'r') as textFile:
            self.pathToAP = textFile.readline()

        sys.path.append(self.pathToAP)
        from reader import reader

        reader = reader()
        reader.readParameters()
        parameters = reader.getParameters()

        for item in parameters:
            try:
                setattr(self, item[:item.find('=')],
                        int(item[item.find('=') + 1:]))
            except ValueError:
                setattr(self, item[:item.find('=')], item[item.find('=') + 1:])

        self.pressFlag = False

        self.numberOfRows = 3,
        self.numberOfColumns = 1,
        self.numberOfIteration = 0
        self.maxNumberOfIteration = 2 * self.numberOfRows[0]

        self.flaga = 0

        if self.control != 'tracker':
            self.mouseCursor = PyMouse()
            self.mousePosition = self.winWidth - 8 - self.xBorder, self.winHeight - 8 - self.yBorder
            self.mouseCursor.move(*self.mousePosition)

        if self.switchSound.lower() != 'off' or self.pressSound.lower(
        ) != 'off':
            mixer.init()
            self.switchingSound = mixer.Sound(self.pathToAP +
                                              '/sounds/switchSound.ogg')
            self.pressingSound = mixer.Sound(self.pathToAP +
                                             '/sounds/pressSound.ogg')

            self.powrotSound = mixer.Sound(self.pathToAP +
                                           '/sounds/powrot.ogg')
            self.slowoSound = mixer.Sound(self.pathToAP + '/sounds/slowo.ogg')
            self.dziuraSound = mixer.Sound(self.pathToAP +
                                           '/sounds/dziura.ogg')

        self.poczatek = True
        self.numberOfPresses = 1
Example #23
0
    def __init__(self, path, pcDir):

        self.pcDir = pcDir
        self.injectionPoint = "{}/Blueprints/Tracks/AethonBlueprint01.blueprint".format(
            self.pcDir)

        self.dataPath = path + "/fcompressedsave_blueprint"
        self.data = open(self.dataPath, "rb").read()
        self.data = self.deflateE(self.data)
        self.data = self.data[16:]
        self.dataReader = reader(self.data)

        self.metaPath = path + "/fcompressedsave_metadata"
        self.metaData = open(str(self.metaPath), "rb").read()
        self.metaData = self.deflateE(self.metaData)
        self.metaData = self.metaData[16:]
        self.metaJson = json.loads(self.metaData)

        self.name = self.metaJson["sName"]

        self.header = self.dataReader.ReadBytes(11)
        self.version = self.dataReader.ReadBytes(15)
        self.steam = self.dataReader.ReadBytes(7)
        self.unknown = self.dataReader.ReadBytes(1)
        self.unknown2 = self.dataReader.ReadBytes(40)
        self.unknown3 = self.dataReader.ReadBytes(2)
        self.stringHeader = self.dataReader.ReadBytes(8)
        self.stringsCount = self.dataReader.ReadNum(1)
        self.stringsPos = self.dataReader.pointer

        self.strings = []
        self.stringLength = 0

        for i in range(self.stringsCount):
            self.string = ""
            while True:
                self.char = self.dataReader.ReadBytes(1)
                if int.from_bytes(self.char, "little", signed=False) != 0:
                    try:
                        self.string = self.string + self.char.decode("utf-8")
                    except:
                        pass
                else:
                    self.strings.append(self.string)
                    self.stringLength += len(self.string)
                    break

        self.endPos = self.dataReader.pointer
Example #24
0
 def __init__(self,fields,file_name,origin,where_cond,group_field,group_cond,order_fields):
     self.old_scheme = reader.read_scheme(origin)
     self.old_table = reader.reader(origin, False,self.old_scheme)
     if fields != "*":
         self.fields = {field : self.old_scheme.type_by_field(field) for field in fields}
     else:
         self.fields = {item['field'] : item['type'] for item in self.old_scheme.fields}
     self.origin = origin
     self.name = file_name
     if where_cond != []:
         self.get_where(where_cond)
     else: self.where_lines = '*'
     self.order = order_fields
     if group_field or group_cond:
         raise NotImplementedError
     self.file_name = file_name
Example #25
0
def register():

    error = None
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        if db.checkIfNameTaken(username) == False:
            newPerson = reader.reader(username, password)
            try:
                db.addUser(newPerson)
                return redirect(url_for('home'))
            except:
                error = 'Name Taken. Please try again.'
        else:
            error = "Username Taken"
    return render_template('register.html', error=error)
Example #26
0
def main():
    db = Database()
    filename = 'abs.txt'
    post_generator = reader(filename)
    session = db.Session()

    # parse and add data
    # for post in post_generator:
    #     s = post.split('MSK')
    #     strdate = s[0][-18:-1]
    #     date = datetime.datetime.strptime(strdate, '%m/%d/%y %H:%M:%S')
    #     question = s[0]
    #     answer = s[1]
    #     tags = []
    #     db.add_post(session, date, question, answer, tags)

    # get all posts
    # posts = session.query(Post).all()
    # for post in posts:
    #     print(post.question)

    # get all tags
    # tags = db.get_tags(session)
    # print(tags)


    # get first post
    # first = db.get_first_post(session)

    # get last post
    print(db.get_count(session))
    last = db.get_last_post(session)
    print(last)

    # update post
    # db.update_post(session, last, question, answer, who_asked, date, tags)

    # get portion
    # portion = db.select_portion(session, 2, 4)
    # for post in portion:
    #     print(post.question)
    #     print('-----------------')
    #     print(post.answer)
    #     print('=================')


    session.close()
Example #27
0
    def __init__(self,makeDirs=True):
        self.R = reader.reader()
        self.W = wfanal.wfanal()
        self.writer = writer.writer()
        self.cT = calibThermocouple.calibThermocouple()
        self.gU= graphUtils.graphUtils()
        self.pip= pipath.pipath()

        self.writeRecon = None
        self.overlaps = 0
        self.lastEventDumped = None
        
        self.Hists = {}
        self.TDChistnames = {}
        self.refTDCs = ['S2','H0']
        self.WFHists = []
        self.Times = []
        self.rawTemps = []
        self.calTemps = []
        self.AllTrigsfname = None
        self.rootpyEvts = None
        self.NoHists = False

        if makeDirs:
            now = datetime.datetime.now()
            self.start_time = now
            fmt = '%Y%m%d_%H%M%S_%f'
            cnow = now.strftime(fmt)
            parentDir = 'Results/'+cnow+'/'
            self.logdir = parentDir + 'Log/'
            self.figdir = parentDir + 'Figures/'
            self.WFfigdir = self.figdir + 'WF/'
            self.TDCfigdir= self.figdir + 'TDC/'
            self.outputdir= parentDir + 'Output/'
            # create list of platform-independent path
            dirs = self.pip.fix( [parentDir, self.logdir, self.figdir, self.WFfigdir, self.TDCfigdir, self.outputdir] )
            parentDir, self.logdir, self.figdir, self.WFfigdir, self.TDCfigdir, self.outputdir = dirs
            for d in dirs:
                if os.path.isdir(d):
                    pass
                else:
                    try:
                        os.makedirs(d)
                    except IOError,e:
                        print 'process__init__',e
                    else:
                        print 'process__init__ created',d
Example #28
0
def test_hueh_boxed():
    from reader import reader
    path = '/nfs/OPTI/bzfander/lrs_python/data/hueh_358_boxed.ine'
    parsed = reader(path)
    lrs = CrissCross(*parsed)
    lrs.augment_matrix_with_objective()
    lrs.init_dicts()
    lrs.add_box_constraints(lrs.bounding_box)
    lrs.first_basis()
    search = lrs.forest_search()
    from lrs import SearchStatus
    status = SearchStatus.NONE
    i = 0
    while status != SearchStatus.DONE and i < 1000:
        status = search.__next__()
        i += 1
    assert i == 1000
Example #29
0
def home():
    global db
    db = database.database
    db.connect()
    error = None
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        global person
        person = reader.reader(username, password)
        valid = db.checkForUser(person)
        if valid == False:
            error = 'Invalid Credentials. Please try again.'
        else:
            db.userId(person)
            return redirect(url_for('start'))
    return render_template('login.html', error=error)
def main(argv):
    inputfile = handleInput(argv)
    if not inputfile:
        sys.exit("You need to provide a dataset file path")
    epochs = 10
    autoencoder = convolutionalAutoencoder()
    all_images = reader(inputfile)
    (history, decoded_imgs, test) = training(autoencoder, all_images)

    while True:
        option = input('''
		******************************************
		*	Press 1 for re-execution         *
		*	Press 2 to display figures       *
		*	Press 3 to save the model        *
		******************************************
		''')

        if option == "1":
            epochs, batch_size, filter_pixel, filters, layers = [
                int(i) for i in input(
                    "Insert epochs, batch size, filter_pixel, filters, layers: "
                ).split(",")
            ]
            if layers > 5:
                print("You need to provide less than or equal to 5 layers")
                continue
            if layers < 1:
                print("Please provide a positive number of layers")
                continue
            autoencoder = convolutionalAutoencoder(int(filter_pixel),
                                                   int(filters), int(layers))
            (history, decoded_imgs, test) = training(autoencoder, all_images,
                                                     int(epochs),
                                                     int(batch_size))
        elif option == "2":
            plotting(history, decoded_imgs, test, int(epochs))
        elif option == "3":
            path = input("Insert the path to save model: ")
            autoencoder.save(path + "/model.h5")
        else:
            print("Wrong input")

    return 0
Example #31
0
def run():
    """Pre-processing"""
########################################################################################
    wd_total = '%s/total' % config.WORK_DIR
    file_io.mk_path('%s/dumps' % wd_total)
    file_io.mk_path('%s/pickles' % wd_total)
    to_open = "%s/pickles/%s.pkl" % (wd_total, config.CONF)

    file_list, my_dict = load(to_open)
    import reader
    import dict_utils
    import matrix
    cpt = 1
    for f in glob.glob(config.RELP_FILES):
        if f in file_list:
            print >> sys.stderr, 'READER (%d): File already read: %s' % (cpt, f) 
            continue
        print >> sys.stderr, 'READER (%d): Starting file: %s' % (cpt, f) 
        cpt += 1
        my_dict = reader.reader(f, my_dict)
        file_list.add(f)
        if len(file_list) % config.SAVE_FREQ == 0:
            wd = "%s/%d/" % (config.WORK_DIR, len(file_list))
            file_io.mk_path('%s/dumps' %wd)
            file_io.mk_path('%s/pickles' %wd)

            save("%s/pickles/%s.pkl" % (wd, config.CONF), file_list, my_dict)
            # Filter lines
            dd = my_dict.copy()
            if config.WORD1:
                dict_utils.filter_words(dd, config.WORD1, (2,3))
            dd = dict_utils.popular(dd, config.POPULAR)
            m_rows, m_columns, my_matrix = dict_utils.dict_to_matrix(dd)
            my_matrix = matrix.Matrix(rows=m_rows, columns=m_columns, count=my_matrix)
            my_matrix.save('%s/dumps/%s_%s' % (wd, config.OUTPUT_FILE, config.CONF))
    save(to_open, file_list, my_dict)
    # Filter lines
    if config.WORD1:
        dict_utils.filter_words(my_dict, config.WORD1, (2,3))
    my_dict = dict_utils.popular(my_dict, config.POPULAR)
    m_rows, m_columns, my_matrix = dict_utils.dict_to_matrix(my_dict)
    my_matrix = matrix.Matrix(rows=m_rows, columns=m_columns, count=my_matrix)
    my_matrix.save('%s/dumps/%s_%s' % (wd_total, config.OUTPUT_FILE, config.CONF))
def loadfilter(filename):
    """ Takes as input the name of the file, where all the parameters are, and
    from this uses the filter data file"""
    
    # import the parameters from the parameter file so to use the filter data file
    filtername, spectraltype, mV,  startrange, endrange, arrsize, skyfile,\
                atmofile, telefile, pbfiltername, fudgefactor, expostime, diameter,\
                seeingvalue, quantumeff, startrange2, endrange2, vbessel, umag, gmag,\
                rmag,imag,zmag = reader(filename)
    
    old = os.getcwd()                           # current folder
    folder = r"../data files to load"           # select the data folder
    os.chdir(folder)                            # and go to it
    
    # load up filter. Default is V filter using data from 
    # hhttp://www.noao.edu/kpno/mosaic/filters/c6026.html                                       
    Vfilter = np.genfromtxt(filtername.strip())
    Vfilter_y = Vfilter[:,1]

    idx = np.where(Vfilter_y < 0)
    if np.prod(np.shape(idx)) != 0: # check that the array is not empty
        if np.min(idx) >= 0:
            Vfilter_y[idx] = 0
    x_values = np.arange(arrsize) # rebin into 1 angstrom bins

    vf = np.interp(x_values, Vfilter[:,0],Vfilter_y/100)
    vf = vf/max(vf) # normalize
    
    # debug below: check the filter by plotting it 
#    plt.figure()
#    plt.plot(Vfilter[:,0],Vfilter[:,1])
#    #plt.plot(Vfilter[:,0],vf, label = "Interpolated data")
#    plt.xlabel("Wavelength (Angstrom)")
#    plt.ylabel("Transmission (%)")
#    plt.legend() 
    
    
    #select the region of interest
    fluxfilt = np.sum(vf[startrange:endrange]) / (endrange-startrange) 
    return vf, fluxfilt

    os.chdir(old)                           # return to the original folder
Example #33
0
def grid(type='vector'):
    # This reads in the grid and produces a dictionary
    # that contains x, y, z, dx, dy, dz, Lx, Lx,
    # Lz, Nx, Ny, and Nz.
    
    if type == 'vector':
        x = reader('x', [0,-1],0,0)
        y = reader('y', 0,[0,-1],0)
        z = reader('z', 0,0,[0,-1])
    elif type == 'full':
        x = reader('x', [0,-1],[0,-1],[0,-1])
        y = reader('y', [0,-1],[0,-1],[0,-1])
        z = reader('z', [0,-1],[0,-1],[0,-1])

    return x,y,z
## ------
Example #34
0
 def build_model(self):
     '''DataLoader'''
     gl._init()
     gl.set_value('rho', 0)
     l2 = fluid.regularizer.L2Decay(self.weight_decay)
     self.train_reader, self.test_reader = reader(self.batch_size)
     self.genA2B = ResnetGenerator(in_channels=3,
                                   out_channels=3,
                                   ngf=self.ch,
                                   n_blocks=self.n_res,
                                   img_size=self.img_size,
                                   light=self.light)
     self.genB2A = ResnetGenerator(in_channels=3,
                                   out_channels=3,
                                   ngf=self.ch,
                                   n_blocks=self.n_res,
                                   img_size=self.img_size,
                                   light=self.light)
     self.disGA = Discriminator(in_channels=3, ndf=self.ch, n_layers=7)
     self.disGB = Discriminator(in_channels=3, ndf=self.ch, n_layers=7)
     self.disLA = Discriminator(in_channels=3, ndf=self.ch, n_layers=5)
     self.disLB = Discriminator(in_channels=3, ndf=self.ch, n_layers=5)
     self.clip = fluid.clip.GradientClipByValue(1,
                                                0,
                                                need_clip=self.fileter_func)
     self.G_opt = fluid.optimizer.Adam(
         learning_rate=self.lr1,
         beta1=0.5,
         beta2=0.999,
         regularization=l2,
         parameter_list=self.genA2B.parameters() + self.genB2A.parameters())
     self.D_opt = fluid.optimizer.Adam(
         learning_rate=self.lr2,
         beta1=0.5,
         beta2=0.999,
         regularization=l2,
         parameter_list=self.disGA.parameters() + self.disGB.parameters() +
         self.disLA.parameters() + self.disLB.parameters())
     self.L1loss = fluid.dygraph.L1Loss()
     self.BCELoss = fluid.dygraph.BCELoss()
Example #35
0
def jupiter_system():
    """returnerer jupiter og dens måner"""
    #leser inn data
    input_data = reader("data/jupiter_moons.txt")

    #definerer sentrumet som planeten jupiter
    #(vi bruker her det zevsentriske systemet) (jupiters navn på gresk = zevs)
    jupiter = Body(1.89E27, color="red", name="Jupiter")

    #månene
    moons = []
    #orker ikke å gi planetene forskjellige farger, så legger de til i en loop
    for key in input_data:
        #alle kretser om jupiter og vi bryr oss ikke om fargene
        moons.append(
            Body(planet=key,
                 centre=jupiter,
                 input_data=input_data,
                 color="white"))

    #retunerer lista over alle planetene
    return [jupiter, *moons]
Example #36
0
def solar_system(planet_name):
    """returnerer alle planetene i solsystemet"""
    #leser inn data
    input_data = reader("data/solar_system.txt")
    """
    Vi definerer alle planetene vi ønsker. Dette kunne enkelt blitt gjort i en
    funksjon (se jupiter-systemet), men da mister vi muligheten til å bestemme
    fargene på planetene på en oversiktlig måte. Derfor har jeg gjort det slik
    jeg gjorde nedenfor"""

    ret = []

    #sola må defineres som en punktmasse uten fart i sentrum
    sun = Body(M, color="yellow", name="Sun")

    planet_names = [
        "Earth", "Mars", "Venus", "Mercury", "Jupiter", "Saturn", "Uranus",
        "Neptune", "Pluto"
    ]
    planet_colors = [
        "blue", "red", "green", "brown", "brown", "yellow", "yellow", "blue",
        "grey"
    ]

    #alle planetene
    ret += solar_system_aux(planet_names, planet_colors, sun, planet_name,
                            input_data)
    ret.append(sun)

    #månen (jorda er den første planeten)
    ret.append(
        Body(planet="Moon", centre=ret[0], color="grey",
             input_data=input_data))

    #deimos = Body(planet="Deimos", centre=mars, color="brown",  input_data = input_data)
    #phobos = Body(planet="Phobos", centre=mars, color="yellow", input_data = input_data)

    #returnerer en array med alle planetene
    return ret
Example #37
0
# run.py

import sys
sys.path.append("/home/jeff/")
import reader
import xval
import zeror

if __name__ == "__main__":
	try:
		filename = sys.argv[-1]
		table = reader.reader(filename)
		xval.xvals(table, zeror)
	except IndexError:
		print "Must specify csv file"
		sys.exit(1)
Example #38
0
def test_reader():

    nodes = reader(dummy_lines)
    nodes = list(nodes)

    eq_(len(nodes), 12)

    types = [node.type for node in nodes]
    eq_(types, [
        'expression',
        'language',
        'symbol',
        'symbol',
        'language',
        'symbol',
        'NULL',
        'double',
        'NULL',
        'language',
        'symbol',
        'pairlist',
    ])

    recs = [node.recs for node in nodes]
    eq_(recs, [
        [],
        [],
        [Rec('content', '<-')],
        [Rec('content', 'foo')],
        [],
        [Rec('content', 'function')],
        [Rec('content', None)],
        [Rec('content', '1')],
        [Rec('content', None)],
        [],
        [Rec('content', 'function')],
        [
            Rec('argname', 'x'),
            Rec('argvalue', None),
            Rec('argtype', 'symbol'),
            Rec('argname', 'bar'),
            Rec('argvalue', 'foo'),
            Rec('argtype', 'symbol'),
            Rec('argname', 'gz'),
            Rec('argvalue', '2'),
            Rec('argtype', 'double'),
        ]
    ])

    children = [node.children for node in nodes]
    expected = [
        [nodes[1], nodes[9]],
        nodes[2:5],
        [],
        [],
        nodes[5:9],
        [],
        [],
        [],
        [],
        nodes[10:12],
        [],
        []
    ]
    eq_(children, expected)
Example #39
0
def record(camera, name):
    reader.reader().capture(camera, name)
Example #40
0
import reader
import matplotlib.pyplot as plt
r=reader.reader("C:\\Users\\Ravi Ponmalai\\Desktop\\test1.txt")

data_list=r.get_final_data()


for i in data_list['Y']:
    
    plt.plot(data_list['X']['TIME'],data_list['Y'][i],'o')
plt.xlabel(r.get_x_list()[0][0]+" "+r.get_x_list()[0][1])
plt.show()