def __init__(self, b, time, mags, errs=None, tshift=0., mshift=0.): """Creates a Light Curve instance. Required parameters: b (band), time, mags.""" if isinstance(b, str): # convert band-name to band instance if band.is_exist(b): self._b = band.band_by_name(b) else: raise ValueError("No such band: {}".format(b)) else: self._b = b super().__init__(self._b.Name, time, mags, errs, tshift=tshift) self._mshift = mshift self._attrs = {}
def table2curves(name, tbl, bands=None, colt=('time', 'JD', 'MJD'), is_filter_zero=True): # time = None for nm in colt: if nm in tbl.dtype.names: time = tbl[nm] break else: raise ValueError( "THe table should contain a column with name in [{0}]".format( ', '.join(colt))) curves = SetLightCurve(name) if bands is None: bands = [n for n in tbl.dtype.names if band.is_exist(n)] for bname in bands: b = band.band_by_name(bname) mag = tbl[bname] mask = ~np.isnan(mag) # filter if is_filter_zero: mask = np.logical_and(mask, mag != 0) # filter out values not equal 0 mask = np.logical_and(mask, mag < 99) t = time[mask] m = mag[mask] for err_name in (prefix + bname for prefix in err_prefix): if err_name in tbl.dtype.names: err = tbl[err_name] e = err[mask] lc = LightCurve(b, t, m, e) break else: lc = LightCurve(b, t, m) curves.add(lc) return curves
def to_curves(self): ph = pandas.DataFrame.from_dict(self.photometry) def add(d, k, v): if k in d: d[k].append(v) else: d[k] = [v] times = {} mags = {} err = {} # {'magnitude': '6.36', 'u_time': 'MJD', 'time': '46849.44', 'band': 'V', 'source': '44,62'} if 'e_magnitude' in ph.keys(): for b, t, m, e in zip(ph.band, ph.time, ph.magnitude, ph.e_magnitude): add(times, b, t) add(mags, b, m) add(err, b, e) else: for b, t, m in zip(ph.band, ph.time, ph.magnitude): add(times, b, t) add(mags, b, m) bands = list(times.keys()) band.Band.load_settings() curves = SetLightCurve(self.Name) for bname in bands: if band.is_exist(bname): tt = list(map(float, times[bname])) mm = list(map(float, mags[bname])) if len(err) > 0: ee = list(map(float, err[bname])) lc = LightCurve(bname, tt, mm, ee) else: lc = LightCurve(bname, tt, mm) curves.add(lc) return curves
def main(): path = '/home/bakl/Sn/Release/seb_git/res/tt/tanaka' mname = 'cat_R500_M15_Ni008_E40' try: opts, args = getopt.getopt(sys.argv[1:], "hp:i:b:") except getopt.GetoptError as err: print(str(err)) # will print something like "option -a not recognized" usage() sys.exit(2) for opt, arg in opts: if opt == '-i': mname = str(arg) break if opt == '-b': bands = str(arg).split('-') for b in bands: if not band.is_exist(b): print('No such band: ' + b) sys.exit(2) continue if opt == '-p': path = str(arg) if not (os.path.isdir(path) and os.path.exists(path)): print("No such directory: " + path) sys.exit(2) continue elif opt == '-h': usage() sys.exit(2) compare_ABzVSugri(mname, path) path = '/home/bakl/Sn/Release/seb_git/res/tt' compare_ttVSubv(mname, path)
def load(dic=None): """ Load points from dat-files. Reader data-file with mix bname data, like: >>% head photometry.txt jd filter mag mage 2457059.6228778586 V 17.493766309999998 0.0592200135089 2457059.6244578934 V 17.539956019999998 0.0542402986717 2457059.6261980557 g 17.782871193345898 0.0454000142503 2457059.6287036575 g 17.7782469177482 0.0395424488201 :return SetLightCurves: """ fname = None tshift = 0. mshift = 0. mag_lim = 30. skiprows = 1. arg = [] if dic is not None: mag_lim = dic.get('mag_lim', 30.) skiprows = dic.get('skiprows', 1) if 'args' in dic: arg = dic['args'] if len(arg) > 0: fname = arg.pop(0) fname = os.path.expanduser(fname) if len(arg) > 0: s = arg.pop(0) if s.isnumeric(): tshift = float(s) elif len(arg) > 0: tshift = float(arg.pop(0)) if len(arg) > 0: mshift = float(arg.pop(0)) print("Load {0} tshift={1} mshift={2}".format(fname, tshift, mshift)) # read data dtype = [('time', '<f4'), ('b', 'str'), ('mag', '<f4'), ('err', '<f4')] # lc_data = np.loadtxt(fname, skiprows=skiprows, dtype=dtype, comments='#') # jd filter mag mage # lc_data = np.genfromtxt(fname, skip_header=skiprows, dtype=dtype, comments='#') # jd filter mag mage lc_data = np.genfromtxt(fname, skip_header=skiprows, dtype=None, names=[v[0] for v in dtype], comments='#') b_tot = lc_data['b'] bnames = np.unique(b_tot) curves = SetLightCurve() for bname in bnames: if band.is_exist(bname.decode()): # filter of the current band d = lc_data[np.where(lc_data['b'] == bname)] # is_good = list(map(lambda x: x == bname, b_tot)) # t = (lc_data['time'])[is_good] # m = lc_data['mag'][is_good] # e = lc_data['err'][is_good] # add light curve b = band.band_by_name(bname.decode()) lc = LightCurve(b, d['time'], d['mag'], d['err']) # lc = LightCurve(b, t, m, e) curves.add(lc) else: print('Could read the light curve. There is no band: {}. ' 'You may try to add it to dir data/bands'.format(bname)) # remove bad data res_curves = SetLightCurve(curves.Name) for lc_orig in curves: is_good = lc_orig.Mag < mag_lim t = lc_orig.Time[is_good] m = lc_orig.Mag[is_good] e = None if lc_orig.IsErr: e = lc_orig.Err[is_good] lc = LightCurve(lc_orig.Band, t, m, e) res_curves.add(lc) res_curves.set_tshift(tshift) res_curves.set_mshift(mshift) return res_curves
def curves_read_mix(fname, dtype=None, skiprows=1, comments='#', is_full=False, is_out=False): """ Reader data-file with mix bname data, like: >>% head photometry.txt jd filter mag mage 2457059.6228778586 V 17.493766309999998 0.0592200135089 2457059.6244578934 V 17.539956019999998 0.0542402986717 2457059.6261980557 g 17.782871193345898 0.0454000142503 2457059.6287036575 g 17.7782469177482 0.0395424488201 :param is_out: :param fname: file with data :param dtype: You should define the colums: time, mag, err and filter, example: (('time', '<f4'), ('filter', 'S1'), ('mag', '<f4'), ('err', '<f4')) :param skiprows: skip rows, default: 1 for header :param comments: skip comments, default: # :param is_full: return also table data, default: False :param is_out: print first line of data :return: curves """ from pystella.rf import band band.Band.load_settings() if dtype is None: dtype = [('time', np.float), ('filter', 'S8'), ('mag', np.float), ('err', np.float)] lc_data = np.loadtxt(fname, skiprows=skiprows, dtype=dtype, comments=comments) # jd filter mag mage if is_out: print(lc_data.dtype) print(lc_data[0]) print(lc_data[1]) b_tot = lc_data['filter'] bnames = np.unique(b_tot) curves = SetLightCurve() for bname in bnames: bname_s = bname try: bname_s = bname_s.decode() except AttributeError: pass if band.is_exist(bname_s): # filter of the current band is_good = np.array(list(map(lambda x: x == bname, b_tot)), dtype=bool) t = lc_data['time'][is_good] m = lc_data['mag'][is_good] e = lc_data['err'][is_good] # add light curve b = band.band_by_name(bname_s) lc = LightCurve(b, t, m, e) curves.add(lc) else: print('Could read the light curve. There is no band: {}. ' 'You may try to add it to dir data/bands'.format(bname)) if is_full: return curves, lc_data return curves
def main(name='', path='./'): model_ext = '.ph' is_time_points = False z = 0 distance = 10. # pc band.Band.load_settings() try: opts, args = getopt.getopt(sys.argv[1:], "hwtp:i:b:") except getopt.GetoptError as err: print(str(err)) # will print something like "option -a not recognized" usage() sys.exit(2) if not name: if len(opts) == 0: usage() sys.exit(2) for opt, arg in opts: if opt == '-i': path = ROOT_DIRECTORY name = str(arg) break bands = ['UVW1', 'U'] for opt, arg in opts: if opt == '-b': bands = str(arg).split('-') for b in bands: if not band.is_exist(b): print('No such band: ' + b) sys.exit(2) elif opt == '-p': path = os.path.expanduser(str(arg)) if not (os.path.isdir(path) and os.path.exists(path)): print("No such directory: " + path) sys.exit(2) elif opt == '-t': is_time_points = True elif opt == '-h': usage() sys.exit(2) names = [] if name != '': names.append(name) else: # run for all files in the path files = [ f for f in os.listdir(path) if isfile(join(path, f)) and f.endswith(model_ext) ] for f in files: names.append(os.path.splitext(f)[0]) if len(names) > 0: dic_results = {} # dict((k, None) for k in names) i = 0 for name in names: i += 1 mags = compute_mag(name, path, bands, z=z, distance=distance, t_cut=0.1, t_up=5., tdiff=0.5) dmdt = compute_dmdt(mags, bands, is_spline=True, s=0.) dic_results[name] = dict(m=mags, d=dmdt) print("Finish: %s [%d/%d]" % (name, i, len(names))) plot_dmdt(dic_results, bands, is_time_points=is_time_points) else: print("There are no models in the directory: %s with extension: %s " % (path, model_ext))
def main(): view_opts = ('single', 'grid', 'gridl', 'gridm') opt_grid = view_opts[0] label = None fsave = None callback = None xlim = None ylim = None band.Band.load_settings() try: opts, args = getopt.getopt(sys.argv[1:], "hqc:g:b:l:s:x:y:") except getopt.GetoptError as err: print(str(err)) # will print something like "option -a not recognized" usage() sys.exit(2) if len(opts) == 0: usage() sys.exit(2) bnames = None # bnames = ['U', 'B', 'V', 'R', "I"] # bands = ['U', 'B', 'V', 'R', "I", 'UVM2', "UVW1", "UVW2", 'g', "r", "i"] for opt, arg in opts: if opt == '-b': bnames = [] for b in str(arg).split('-'): # extract band shift if ':' in b: bname, shift = b.split(':') bshift = {} if '_' in shift: bshift[bname] = -float(shift.replace('_', '')) else: bshift[bname] = float(shift) else: bname = b if not band.is_exist(bname): print('No such band: ' + bname) sys.exit(2) bnames.append(bname) continue if opt == '-c': c = cb.lc_wrapper(str(arg)) if callback is not None: c = cb.CallBackArray((callback, c)) callback = c continue if opt == '-g': opt_grid = str.strip(arg).lower() if opt_grid not in view_opts: print('No such view option: {0}. Can be '.format(opt_grid, '|'.join(view_opts))) sys.exit(2) continue if opt == '-l': label = str.strip(arg) continue if opt == '-s': fsave = str.strip(arg) continue if opt == '-x': xlim = list(float(x) for x in str(arg).split(':')) continue if opt == '-y': ylim = list(float(x) for x in str(arg).split(':')) continue elif opt == '-h': usage() sys.exit(2) if callback is None: print('No obs data. You my use lcobs or other callbacks.') usage() sys.exit(2) if opt_grid in view_opts[1:]: sep = opt_grid[:-1] if sep == 'd': sep = 'l' # line separator fig = plot_grid(callback, bnames, xlim=xlim, ylim=ylim, sep=sep, is_grid=False) else: fig = plot_all(callback, bnames, xlim=xlim, ylim=ylim, title=label) plt.show() # plt.show(block=False) if fsave is not None: if fsave == 1: fsave = "ubv_obs" d = os.path.expanduser('~/') fsave = os.path.join(d, os.path.splitext(fsave)[0]) + '.pdf' print("Save plot to %s " % fsave) fig.savefig(fsave, bbox_inches='tight')