def get_artemis_data_params(data_file_path):
    '''Function to obtain information about the ARTEMiS-format photometry data file,
    without reading the whole file.'''

    params = {}
    if path.isfile(data_file_path) == True:
        params['short_name'] = path.basename(data_file_path).split('.')[0]
        params['long_name'] = utilities.short_to_long_name( params['short_name'] )
    
        # Find and read the last entry in the file, without reading the whole file
        st_results = stat(data_file_path)
        st_size = max(0,(st_results[6] - 200))
        data_file = open(data_file_path,'r')
        data_file.seek(st_size)
        last_lines = data_file.readlines()
        params['last_JD'] = float(last_lines[-1].split()[2])
        params['last_mag'] = float(last_lines[-1].split()[0])
    
        # Ask the OS how many datapoints are in the file.
        # Turns out there isn't an easy Python way to do this without
        # reading the whole file, so ask the OS.  Then decrement the number
        # of lines to account for the 1-line header.
        command = 'wc -l '+data_file_path
        args = command.split()
        p = subprocess.Popen(args,stdout=subprocess.PIPE, bufsize=1)
        p.wait()
        params['ndata'] = int(str(p.stdout.readline()).split()[0]) - 1
        
    return params
def read_artemis_model_file(model_file_path):
    '''Function to read an ARTEMiS model file and parse the contents'''

    params = {}
    
    if path.isfile(model_file_path) == True:
        file = open(model_file_path, 'r')
        lines = file.readlines()
        file.close()
        
        if len( lines ) > 0 and len( lines[0] ) > 0 \
            and lines[0].lstrip()[0:1] != '$':
            
            try: 
                entries = lines[0].split()
                params['ra'] = entries[0]
                params['dec'] = entries[1]
                params['short_name'] = entries[2]
                params['long_name'] = utilities.short_to_long_name( params['short_name'] )
                params['t0'] = float(entries[3]) + 2450000.0
                params['sig_t0'] = float(entries[4])
                params['te'] = float(entries[5])
                params['sig_te'] = float(entries[6])
                params['u0'] = float(entries[7])
                params['sig_u0'] = float(entries[8])
                params['chi2'] = float(entries[9])
                params['ndata'] = float(entries[10])
        
                ts = path.getmtime(model_file_path)
                ts = datetime.fromtimestamp(ts)
                params['last_modified'] = ts
            
            # In case of a file with zero content
            except IndexError: 
                pass
            
            # In case of mal-formed file content:
            except ValueError:
                pass
                
    return params
def get_event_params( config, event_id, log ):
    """Function to retrieve the parameters of RTmodel's current best-fitting
    model for a given event. 
    The summary page for each event may list one or more models, of which
    we assume the top model has the lowest chisq, i.e. the current best fit, 
    and scrape the relevant parameters, which may include a subset of the
    full parameter set
    """
    
    url = path.join( str(config['root_url']), str(config['year']), \
                        event_id + '.htm' )
    (page_data,msg) = utilities.get_http_page(url,parse=False)
    
    model = event_classes.RTModel()
    model.event_name = utilities.short_to_long_name(event_id)
    model.url = url
    
    # Identify the top model, and extract the first line which contains the
    # parameters.  Separate them from the HTML and set the model parameters.
    page_lines = page_data.split('\n')
    i = 0
    while i < (len(page_lines)):
        entries = page_lines[i].split()
        if len(entries) > 0 and '>Model ' in page_lines[i] and \
                '&chi;<sup>2</sup>' in page_lines[i]:
            idx = i
            i = len(page_lines)
        i = i + 1
    
    line = page_lines[idx]
    entry = line.split('&chi;<sup>2</sup>')[1].replace('=','')
    entry = entry.split('</b>')[0]
    
    model.chisq = float(entry)
    
    params = {'s':'<br>s=', \
                'q':'q', \
                'u0': 'u<sub>0</sub>', \
                'theta': '&theta;', \
                'rho': '&rho;<sub>*</sub>', \
                'tE': 't<sub>E</sub>', \
                't0': 't<sub>0</sub>',\
                'pi_perp': '&pi;<sub>&perp;</sub>',\
                'pi_para': '&pi;<sub>||</sub>'
                }
    
    for key, search_term in params.items():
        try:
            i = line.index(search_term)
            istart = i + line[i:].index('=') + 1
            iend = i + line[i:].index('&plusmn;')
            par = line[i:i+len(search_term)]
            value = float(line[istart:iend])
            istart = iend + len('&plusmn;')
            iend = istart + line[istart:].index('&nbsp;')
            sigma = float(line[istart:iend])
            
            if key == 't0':
                value = 2450000.0 + value
            
            setattr(model,key, value)
            setattr(model,'sig_'+key, sigma)
            
        except ValueError:
            pass
      
    return model