def pdf_3d(epos): #plot in 3D # doesn't support log scale on axes, need a workaround fig = plt.figure() ax = fig.gca(projection='3d') ax.set_title('Synthetic Model Populations') ax.set_xlabel('Orbital Period [days]') ax.set_zlabel('Planets/bin') if epos.RV: ax.set_ylabel(r'Planet Mass [M$_\bigoplus$]') else: ax.set_ylabel(r'Planet Radius [R$_\bigoplus$]') ax.set_xlim(np.log10(epos.xtrim)) ax.set_ylim(np.log10(epos.ytrim)) xplane, yplane= np.log10(epos.xtrim[0]), np.log10(epos.ytrim[-1]) ax.set_zlim(0,2000) #ax.set_xscale('log') #ax.set_yscale('log') sim=epos.synthetic_survey # PDF, individual contributions # if epos.populationtype is 'model': # for k, sg in enumerate(epos.groups): # subset= sim['i sg']==k # P= sim['P'][subset] # R= sim['Y'][subset] # ax.plot(np.log10(P),np.log10(R), zs=0,zdir='z', # ls='',marker='.',mew=0,ms=5.0,color=clrs[k % 4]) # # xgrid= np.logspace(*np.log10(epos.xtrim)) # pdf= regression.sliding_window_log(P, None, xgrid) #, width=2. ) # ax.plot(np.log10(xgrid), pdf, zs=yplane,zdir='y', # ls='-', marker='', color=clrs[k % 4], # label='{} x{:.3f}'.format(sg['name'], sg['weight'])) # # ygrid= np.logspace(*np.log10(epos.ytrim)) # pdf= regression.sliding_window_log(R, None, ygrid) #, width=2. ) # ax.plot(np.log10(ygrid), pdf, zs=xplane, zdir='x', # ls='-', marker='', color=clrs[k % 4]) # else: # top left panel (P,R) ax.plot(np.log10(sim['P']), np.log10(sim['Y']),zs=0,zdir='z', ls='', marker='.', mew=0, ms=5.0, color='k') # PDF, all combined, 2 panels xgrid= np.logspace(*np.log10(epos.xtrim)) pdf= regression.sliding_window_log(sim['P'], None, xgrid) #, width=2. ) weight= np.sum([sg['weight'] for sg in epos.groups]) if epos.populationtype is 'model' else epos.fitpars.get('pps',Init=True) ax.plot(np.log10(xgrid), pdf, zs=yplane,zdir='y', ls='-', marker='', color='k',label='combined x {:.3f}'.format(weight)) ygrid= np.logspace(*np.log10(epos.ytrim)) pdf= regression.sliding_window_log(sim['Y'], None, ygrid) #, width=2. ) ax.plot(np.log10(ygrid), pdf, zs=xplane,zdir='x', ls='-', marker='', color='k') # observations if epos.Observation and epos.DetectionEfficiency: ax.plot(np.log10(epos.obs_xvar), np.log10(epos.obs_yvar), zs=-10,zdir='z', ls='', marker='.', mew=0, ms=5.0, color='0.7',zorder=0) pdf= regression.sliding_window_log(epos.obs_xvar, None, xgrid) ax.plot(np.log10(xgrid), pdf, zs=yplane,zdir='y', ls=':', marker='', color='k', label='Kepler') pdf= regression.sliding_window_log(epos.obs_yvar, None, ygrid) ax.plot(np.log10(ygrid), pdf, zs=xplane,zdir='x', ls=':', marker='', color='k') # xmax= ax.get_ylim()[-1] # ymax= ax.get_zlim()[-1] # ax.errorbar(xmax/1.5, ymax*0.9, yerr=(xmax/1.5*(1.-np.sqrt(1./2.)) ), # zs=0,zdir='y', color='k') # # xmax= ax.get_xlim()[-1] # ymax= ax.get_zlim()[-1] # ax.errorbar(xmax/1.5, ymax*0.9, xerr=(xmax/1.5*(1.-np.sqrt(1./2.)) ), # zs=0,zdir='x', color='k') #ax2.tick_params(labelbottom='on') # does not re-enable axis ''' Legend instead of 4th plot''' #ax.legend() ax.legend(shadow=False, prop={'size':14},bbox_to_anchor=(0.7,0.0)) ax.view_init(elev=20., azim=-35) helpers.save(plt, epos.plotdir+'output/pdf.3D.diag')
def main(): link = session.query(Link)\ .filter(Link.visited_at == None)\ .order_by(asc(Link.id))\ .first() if link is None: print('Nothing to visit right now') try: print('Trying to visit: {}'.format(link)) r = requests.get(link, timeout=5) soup = BeautifulSoup(r.text, 'html.parser') domain_on_redirect = get_domain(r.url) if not domain_exists(session, domain_on_redirect): print('Found new domain: {}'.format(domain_on_redirect)) save(session, Domain(url=domain_on_redirect)) print('Saved that new domain.') for site_url in set([o.get('href') for o in soup.find_all('a')]): if site_url is None: continue url = site_url if not is_url(site_url): url = urljoin(get_domain(link.url), site_url) print('Found: {}'.format(url)) l = session.query(Link)\ .filter(Link.url == url).first() if l is not None: continue l = Link(url=url) domain = get_domain(l.url) domain_in_db = session.query(Domain)\ .filter(Domain.url == domain)\ .first() if domain_in_db is None: print('Found new domain: {}'.format(domain)) domain_in_db = Domain(url=domain) save(session, domain_in_db) l.domain = domain_in_db save(session, l) except Exception as e: print('Something went wrong') print(e) finally: link.visited_at = datetime.now() save(session, link)
dmsh.Circle([0.0, +0.5], 1.0)]) pts = np.array([[0.0, -5.0], [0.0, 4.1]]) pts = geo.boundary_step(pts.T).T ref = np.array([[0.0, -0.5], [0.0, 0.5]]) assert np.all(np.abs(pts - ref) < 1.0e-10) pts = np.array([[0.0, -0.1], [0.0, 0.1]]) pts = geo.boundary_step(pts.T).T ref = np.array([[0.0, -0.5], [0.0, 0.5]]) assert np.all(np.abs(pts - ref) < 1.0e-10) def test_boundary_step2(): geo = dmsh.Intersection( [dmsh.Circle([0.0, -0.5], 1.0), dmsh.Circle([0.0, +0.5], 1.0)]) np.random.seed(0) pts = np.random.uniform(-1.0, 1.0, (2, 100)) pts = geo.boundary_step(pts) # geo.plot() # import matplotlib.pyplot as plt # plt.plot(pts[0], pts[1], "xk") # plt.show() assert np.all(np.abs(geo.dist(pts)) < 1.0e-7) if __name__ == "__main__": X, cells = test_intersection(show=True) save("intersection.png", X, cells) # test_boundary_step2()
def periodinner(epos, MC=False, N=False, Input=False, MCMC=False): # plot multiplicity f, ax = plt.subplots() ax.set_title('Period of the Innermost Planet') #ax.set_xlabel('Orbital Period [days]') ax.set_ylabel('Planet Counts') #ax.set_xscale('log') #ax.set_xlim(epos.xtrim) helpers.set_axis_distance(ax, epos, Trim=True) #bins= np.geomspace(*epos.xtrim) bins = epos.MC_xvar #pdf= regression.sliding_window_log(P, None, xgrid) #, width=2. ) #ax3.plot(xgrid, pdf, ls='-', marker='', color=clrs[k % 4],label='{} x{:.3f}'.format(sg['name'], sg['weight'])) # MC data if MC or MCMC: ss = epos.synthetic_survey if MCMC: for ss in epos.ss_sample: ax.hist(ss['multi']['Pinner'], bins=bins, color='b', alpha=0.1, histtype='step') else: ax.hist(ss['multi']['Pinner'], bins=bins, color='C0', histtype='stepfilled', label='Simulated') #epos.name) # Solar system analologs (from dr25_solarsystem.py) # Pcut=45 # Pcut=130 # print 'P_in > {} days:'.format(Pcut) # print ' obs: {}'.format((epos.obs_zoom['multi']['Pinner']>Pcut).sum()) # print ' sim: {}'.format((ss['multi']['Pinner']>Pcut).sum()) # print '' #if False: if hasattr(epos, 'ss_extra'): # advance color cycle # ax._get_lines.get_next_color() ax.plot([], []) ax.plot([], []) # plot extra epos runs for ss in epos.ss_extra: ax.hist(ss['multi']['Pinner'], bins=bins, histtype='step', label=ss['name']) if N: # Innermost is nth planet #ax.hist(ss['multi']['PN'][0], bins=bins, # ec='k', histtype='step', label='actual inner planet') # Not actual inner planet ax.hist(np.concatenate(ss['multi']['PN'][1:]), bins=bins, color='r', histtype='stepfilled', label='Not Inner Planet') else: # observed all ax.hist(epos.multi['Pinner'], bins=bins, color='0.7', label='Kepler all') ''' Initial distribution or zoomed observations ''' if Input and epos.Parametric: Pingrid = np.geomspace(*epos.xtrim) _, _, pdf0_X, _ = draw_PR(epos, Init=True, ybin=epos.yzoom, xgrid=Pingrid) norm = 0.95 * ax.get_ylim()[1] / max(pdf0_X) ax.plot(Pingrid, pdf0_X * norm, marker='', ls='-', color='r', label='Intrinsic') elif epos.Zoom and not N: ax.hist(epos.obs_zoom['multi']['Pinner'], bins=bins, ec='C1', histtype='step', label='Kepler') prefix = 'output' if MC else 'survey' suffix = '.index' if N else '' suffix = '.input' if Input else suffix if MCMC: prefix = 'mcmc' if MC: ax.legend(loc='upper right', shadow=False, prop={'size': 14}, numpoints=1) helpers.save(plt, '{}{}/innerperiod{}'.format(epos.plotdir, prefix, suffix))
def polar(epos): ''' Plot planet populations as a half circle (not quite working) ''' # plot multiplicity f, axlist = plt.subplots(2, 2, subplot_kw=dict(projection='polar'), figsize=(10, 8)) pop = epos.population # ticks not showing on log plot Bugged = True for ax, key in zip([axlist[0, 0], axlist[0, 1], axlist[1, 0]], ['system', 'single', 'multi']): ax.set_title(key) ax.set_xlabel('fraction') ax.set_ylabel('P [days]') ax.set_xlim(-0.05, 1.05) ax.set_xticks(np.pi * np.linspace(0, 1, 5)) try: ax.set_thetamin(0) ax.set_thetamax(180) except AttributeError: print 'Update pyplot' raise if Bugged: ax.set_ylim(-1, 3) #ax.set_yticks([0,1,2,3]) ax.set_yticks([1]) ax.set_yticklabels(['10']) ax.plot(pop[key]['order'] * np.pi, np.log10(pop[key]['P']), ls='', marker='.', mew=0, ms=3, color='k') else: ax.set_ylim(0.1, 1000) # 7. ax.set_yscale('log') ax.set_yticks([1, 10, 100, 1000]) #ax.set_yticks([10]) #ax.set_rlim(0.1,1000) #ax.set_rscale('log') #ax.set_rgrids([1, 10, 100, 1000]) #ax.set_rticks([1, 10, 100, 1000]) ax.plot(pop[key]['order'] * np.pi, pop[key]['P'], ls='', marker='.', mew=0, ms=3, color='k') # nope #ax.set_yscale('log') #ax.set_yticks([1, 10, 100, 1000]) ax4 = axlist[1, 1] ax4.set_title('all') ax4.set_xlabel('fraction') ax4.set_ylabel('P [days]') ax4.set_xlim(-0.05, 1.05) ax4.set_ylim(0.1, 1000) # 7. ax4.set_yscale('log') try: ax4.set_thetamin(0) ax4.set_thetamax(180) except AttributeError: print 'Update pyplot' raise ax4.plot(pop['order'] * np.pi, pop['P'], ls='', marker='.', mew=0, ms=3, color='gray') helpers.save(plt, '{}/population/polar_test'.format(epos.plotdir))
file_names = ['cowper.txt', 'derby.txt', 'butler.txt', 'shakespeare.txt'] buffer_size = 50000 batch_size = 64 take_size = 5000 embedding_size = 64 lstm_size = 64 labeled_datasets = makeLabledDatasets(file_names) labeled_datasets = processData(labeled_datasets, buffer_size) vocab_size, vocab_set = tokenizeDataset(labeled_datasets) encoded_data = encodeDataset(labeled_datasets, vocab_set) opts = (take_size, buffer_size, batch_size) train_data, test_data = generateTrainingSets(encoded_data, opts) model = Sequential() model.add(Embedding(vocab_size, embedding_size)) model.add(Bidirectional(LSTM(lstm_size))) model.add(Dense(64, activation='relu')) model.add(Dense(64, activation='relu')) model.add(Dense(4, activation='softmax')) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(train_data, epochs=10, validation_data=test_data) save(model) saveVocab(vocab_set) plotHistory(model.history.history)
def periodradius(epos, Nth=False, MC=True): f, (ax, axR, axP) = helpers.make_panels(plt) if MC: sim = epos.synthetic_survey ID = sim['ID'] P = sim['P'] Y = sim['Y'] outdir = 'output' title = 'Simulated Detections' else: ID = epos.obs_starID P = epos.obs_xvar Y = epos.obs_yvar outdir = 'survey' title = r'Planet Candidates (score$\geq$0.9)' ''' plot R(P), main panel''' ax.set_title(title) helpers.set_axes(ax, epos, Trim=True) ''' Period side panel ''' helpers.set_axis_distance(axP, epos, Trim=True) #axP.set_yscale('log') #axP.set_ylim([2e-3,5]) #axP.set_yticks([0.01,0.1,1]) #axP.set_yticklabels(['1%','10%','100%']) axP.yaxis.tick_right() axP.yaxis.set_ticks_position('both') #axP.tick_params(axis='y', which='minor',left='off',right='off') #axP.hist(sim['P'], bins=epos.MC_xvar, color='0.7') ''' Radius side panel''' helpers.set_axis_size(axR, epos, Trim=True, In=epos.MassRadius) #axR.set_xscale('log') #axR.set_xlim([2e-3,5]) #axR.set_xticks([1,10,100,1000]) #axR.set_xticklabels(['1','10','100','1000'], rotation=70) for tick in axR.get_xticklabels(): tick.set_rotation(70) #axR.tick_params(axis='x', which='minor',top='off',bottom='off') #axP.tick_params(axis='y', which='minor',left='off',right='off') ''' which multiplanets to color ''' # single, multi= EPOS.multi.indices(sim['ID']) # for k, (label, subset) in enumerate(zip(['single','multi'],[single, multi])): # ax.plot(sim['P'][subset], sim['Y'][subset], ls='', marker='.', mew=0, ms=5.0, \ # label=label) if Nth: single, multi, ksys, multis = EPOS.multi.nth_planet(ID, P) suffix = '.nth' label_single = 'single' else: single, multi, ksys, multis = EPOS.multi.indices(ID) suffix = '' label_single = '1' ax.plot(P[single], Y[single], ls='', marker='.', \ color='0.7', label=label_single) ''' Multiplanets with colors''' Stacked = True plist = [] ylist = [] colors = [] CDF = False #stacked histogram for k, subset in zip(ksys, multis): ht, = ax.plot(P[subset], Y[subset], ls='', marker='.', \ label=k) if not CDF: if Stacked: plist.insert(0, P[subset]) ylist.insert(0, Y[subset]) colors.insert(0, ht.get_color()) # pdf else: axP.hist(P[subset], bins=epos.MC_xvar, color=ht.get_color(), histtype='step') if k == ksys[-1]: axP.hist(P[single], bins=epos.MC_xvar, color='0.7', histtype='step') else: # cumulative Plist = np.sort(P[subset]) axP.step(Plist, np.arange(Plist.size, dtype=float) / Plist.size) if Stacked: plist.append(P[single]) ylist.append(Y[single]) colors.append('0.7') axP.hist(plist, bins=epos.MC_xvar, color=colors, histtype='barstacked') axR.hist(ylist, bins=epos.MC_yvar, orientation='horizontal', color=colors, histtype='barstacked') else: #axR.hist(Y,orientation='horizontal', bins=epos.MC_yvar, color='0.7') axR.hist(Y, orientation='horizontal', bins=epos.MC_yvar, color='k', histtype='step') axR.hist(Y[single], orientation='horizontal', bins=epos.MC_yvar, color='0.7') #ax.legend(loc='lower left', shadow=False, prop={'size':14}, numpoints=1) ax.legend(bbox_to_anchor=(1.0, 1.0), markerscale=2, frameon=True, borderpad=0.2, handlelength=1, handletextpad=0.2) helpers.save(plt, '{}{}/PR.multi{}'.format(epos.plotdir, outdir, suffix))
student_data = [] for i, episode in enumerate(expert_data): seed = episode['seed'] teacher_states = episode['states'] env.seed(seed) states, actions, rewards = run_episode(env, sess, state_ph, p_action, sleep=0.01) print("#{index}\tseed: {seed}\trewards: {rewards}".format( index=i, seed=seed, rewards=len(rewards))) student_data.append( dict(seed=seed, states=states, actions=actions, rewards=rewards)) helpers.save('./imitation-data/cartpole_vpc_student.tau', student_data) print('cartpole_vpc_student.tau data is saved.') ### Results: # # The performance quickly converges, giving very good behavior cloning. # This is expected because the domain is very small and there are only 8 parameters. # # 0. 46 1. 42 2. 56 3. 73 4. 49 # 0. 132 1. 151 2. 175 3. 199 4. 140 # 0. 1277 1. 471 2. 176 3. 691 4. 382 # 0. 211 1. 2389 2. 3074 3. 88 4. 87 # 0. 4737 1. 1324 2. 4820 3. 4999 4. 227 # 0. 4999 1. 4999 2. 4999 3. 4999 4. 4999 # 0. 4999 1. 1176 2. 4999 3. 4999 4. 4999 # 0. 4936 1. 4999 2. 4999 3. 4999 4. 4999
import numpy import pytest import dmsh from helpers import assert_norm_equality, save @pytest.mark.parametrize( "radius,ref_norms", [(0.1, [327.95194, 14.263721, 1.0]), (0.4, [18.899253166, 3.70111746, 1.0])], ) def test_circle(radius, ref_norms, show=False): geo = dmsh.Circle([0.0, 0.0], 1.0) X, cells = dmsh.generate(geo, radius, show=show) # make sure the origin is part of the mesh assert numpy.sum(numpy.einsum("ij,ij->i", X, X) < 1.0e-10) == 1 assert_norm_equality(X.flatten(), ref_norms, 1.0e-5) return X, cells if __name__ == "__main__": X, cells = test_circle(0.1, [327.95194, 14.263721, 1.0], show=False) save("circle.png", X, cells)
def completeness(epos, PlotBox=False, Transit=False, Vetting=True): assert epos.DetectionEfficiency f, (ax, axb) = plt.subplots(1, 2, gridspec_kw={'width_ratios': [20, 1]}) f.subplots_adjust(wspace=0) #f.set_size_inches(7, 5) ax.set_title('Detection Efficiency' if Transit else 'Survey Completeness') helpers.set_axes(ax, epos, Trim=False, Eff=True) if Transit: toplot = epos.eff_2D if Vetting and hasattr(epos, 'vetting'): toplot *= epos.vetting else: toplot = epos.completeness if Vetting else epos.completeness_novet with np.errstate(divide='ignore'): log_completeness = np.log10(toplot) ''' color map and ticks''' cmap = 'YlOrBr' if Transit else 'PuRd' #cmap = 'rainbow' if Transit else 'PuRd' vmin, vmax = -4, 0 if Transit: vmin = -3 ticks = np.linspace(vmin, vmax, (vmax - vmin) + 1) levels = np.linspace(vmin, vmax, 256) cs = ax.contourf(epos.eff_xvar, epos.eff_yvar, log_completeness.T, cmap=cmap, levels=levels, vmin=vmin, vmax=vmax) cbar = f.colorbar(cs, cax=axb, ticks=ticks) axb.set_yticklabels(100 * 10.**ticks) axb.tick_params(axis='y', direction='out') axb.set_title('%') ''' Plot the zoom box or a few black contours''' if PlotBox: fname = '.box' assert epos.Range ax.add_patch( patches.Rectangle((epos.xtrim[0], epos.ytrim[0]), epos.xtrim[1] - epos.xtrim[0], epos.ytrim[1] - epos.ytrim[0], fill=False, zorder=1, ls='--')) if epos.Zoom: ax.add_patch( patches.Rectangle((epos.xzoom[0], epos.yzoom[0]), epos.xzoom[1] - epos.xzoom[0], epos.yzoom[1] - epos.yzoom[0], fill=False, zorder=1)) else: if hasattr(epos, 'xtrim'): ax.set_xlim(*epos.xtrim) ax.set_ylim(*epos.ytrim) if epos.RV: levels = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9] labels = ['10', '20', '30', '40', '50', '60', '70', '80', '90'] cs= ax.contour(epos.eff_xvar, epos.eff_yvar, toplot.T,\ levels= levels, colors = 'k', linewidths=2.) else: levels = [1e-3, 0.01, 0.1, 0.5, 0.9] if Transit else 10.**ticks cs = ax.contour(epos.eff_xvar, epos.eff_yvar, toplot.T, colors='k', levels=levels) fmt_percent = lambda x: '{:g} %'.format(100. * x) plt.clabel(cs, cs.levels, inline=True, fmt=fmt_percent) fname = '' if not Vetting: fname += '.novet' helpers.save(plt, epos.plotdir+'survey/'+('efficiency' if Transit else 'completeness')+ \ fname)
def observed(epos, PlotBox=True, PlotScore=False): assert epos.Observation if PlotScore: f, (ax, axb) = plt.subplots(1, 2, gridspec_kw={'width_ratios': [20, 1]}) f.subplots_adjust(wspace=0) else: f, ax = plt.subplots() ax.set_title('Observed Population') helpers.set_axes(ax, epos, Trim=epos.Range) if PlotScore: ''' color scale? ''' cmap = 'plasma' # viridis, plasma, inferno, magma, spring, cool vmin, vmax = 0, 1 #ticks=np.linspace(vmin, vmax, (vmax-vmin)+1) clrs, norm = helpers.color_array(epos.obs_score, vmin=vmin, vmax=vmax, cmap=cmap) ax.scatter(epos.obs_xvar, epos.obs_yvar, color=clrs, s=3) # colorbar? cb1 = clrbar.ColorbarBase(axb, cmap=cmap, norm=norm, orientation='vertical') # horizontal axb.tick_params(axis='y', direction='out') fname = '.score' else: ax.plot(epos.obs_xvar, epos.obs_yvar, ls='', marker='.', mew=0, ms=5.0, color='k') fname = '' # add multis? if PlotBox: fname = '.box' assert epos.Range ax.add_patch( patches.Rectangle((epos.xtrim[0], epos.ytrim[0]), epos.xtrim[1] - epos.xtrim[0], epos.ytrim[1] - epos.ytrim[0], fill=False, zorder=1, ls='--')) if epos.Zoom: ax.add_patch( patches.Rectangle((epos.xzoom[0], epos.yzoom[0]), epos.xzoom[1] - epos.xzoom[0], epos.yzoom[1] - epos.yzoom[0], fill=False, zorder=1)) helpers.save(plt, epos.plotdir + 'survey/planets' + fname)
def panels(epos, MCMC=False): f, (ax, axR, axP)= helpers.make_panels(plt) sim=epos.synthetic_survey clr_bf= 'g' ''' plot R(P), main panel''' ax.set_title('Simulated Detections') helpers.set_axes(ax, epos, Trim=True) if epos.MonteCarlo: ax.plot(sim['P'], sim['Y'], ls='', marker='.', color=clr_bf if MCMC else 'C0') else: levels= np.linspace(0,np.max(sim['pdf'])) ax.contourf(epos.MC_xvar, epos.MC_yvar, sim['pdf'].T, cmap='Blues', levels=levels) ''' Period side panel ''' helpers.set_axis_distance(axP, epos, Trim=True) #axP.set_yscale('log') #axP.set_ylim([2e-3,5]) #axP.set_yticks([0.01,0.1,1]) #axP.set_yticklabels(['1%','10%','100%']) axP.yaxis.tick_right() axP.yaxis.set_ticks_position('both') #axP.tick_params(axis='y', which='minor',left='off',right='off') ''' Radius side panel''' helpers.set_axis_size(axR, epos, Trim=True) #, In= epos.MassRadius) #axR.set_xscale('log') #axR.set_xlim([2e-3,5]) #axR.set_xticks([1,10,100,1000]) #axR.set_xticklabels(['1','10','100','1000'], rotation=70) for tick in axR.get_xticklabels(): tick.set_rotation(70) #axR.tick_params(axis='x', which='minor',top='off',bottom='off') #axP.tick_params(axis='y', which='minor',left='off',right='off') ''' Histograms / posterior samples ''' try: xbins= np.geomspace(*epos.xzoom, num=20) ybins= np.geomspace(*epos.yzoom, num=10) except: xbins= np.logspace(*np.log10(epos.xzoom), num=20) ybins= np.logspace(*np.log10(epos.yzoom), num=10) xscale= np.log(xbins[1]/xbins[0]) yscale= np.log(ybins[1]/ybins[0]) if MCMC: histkeys= {'color':'b', 'alpha':0.1} for ss in epos.ss_sample: if epos.MonteCarlo: axP.hist(ss['P zoom'], bins=xbins, histtype='step', **histkeys) axR.hist(ss['Y zoom'], bins=ybins, orientation='horizontal', \ histtype='step', **histkeys) else: axP.plot(ss['P zoom'], ss['P zoom pdf']*xscale, marker='', ls='-', **histkeys) axR.plot(ss['Y zoom pdf']*yscale, ss['Y zoom'], marker='', ls='-', **histkeys) histdict= {'histtype':'step', 'color':clr_bf} else: histdict={} if epos.MonteCarlo: axP.hist(sim['P zoom'], bins=xbins, **histdict) axR.hist(sim['Y zoom'], bins=ybins, orientation='horizontal', **histdict) else: axP.plot(sim['P zoom'], sim['P zoom pdf']*xscale, marker='', ls='-') axR.plot(sim['Y zoom pdf']*yscale, sim['Y zoom'], marker='', ls='-') ''' Observations''' axP.hist(epos.obs_zoom['x'], bins=xbins,histtype='step', color='C1') axR.hist(epos.obs_zoom['y'], bins=ybins, orientation='horizontal',histtype='step', color='C1') ''' Box/ lines''' if epos.Zoom: for zoom in epos.xzoom: axP.axvline(zoom, ls='--', color='k') for zoom in epos.yzoom: axR.axhline(zoom, ls='--', color='k') ax.add_patch(patches.Rectangle( (epos.xzoom[0],epos.yzoom[0]), epos.xzoom[1]-epos.xzoom[0], epos.yzoom[1]-epos.yzoom[0],fill=False, zorder=1) ) #ax.legend(loc='lower left', shadow=False, prop={'size':14}, numpoints=1) fdir= 'mcmc' if MCMC else 'output' helpers.save(plt, '{}{}/pdf.zoom'.format(epos.plotdir, fdir))
def cdf(epos): f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2) f.set_size_inches(9, 7) # default 7, 5 ''' top left: synthetic obsservation ''' sim= epos.synthetic_survey helpers.set_axes(ax1, epos, Trim=True) ax1.set_title('Synthetic ({})'.format(sim['nobs'])) if epos.MonteCarlo: ax1.plot(sim['P'], sim['Y'], ls='', marker='.', mew=0, ms=5.0, color='r', alpha=0.5) else: levels= np.linspace(0,np.max(sim['pdf'])) ax1.contourf(epos.MC_xvar, epos.MC_yvar, sim['pdf'].T, cmap='Reds', levels=levels) if epos.Zoom: ax1.add_patch(patches.Rectangle( (epos.xzoom[0],epos.yzoom[0]), epos.xzoom[1]-epos.xzoom[0], epos.yzoom[1]-epos.yzoom[0],fill=False, zorder=1) ) ''' Top right: observed population ''' ax2.set_title('Observed ({})'.format(epos.obs_zoom['x'].size)) helpers.set_axes(ax2, epos, Trim=True) ax2.plot(epos.obs_xvar, epos.obs_yvar, ls='', marker='.', mew=0, ms=5.0, color='b') if epos.Zoom: ax2.add_patch(patches.Rectangle( (epos.xzoom[0],epos.yzoom[0]), epos.xzoom[1]-epos.xzoom[0], epos.yzoom[1]-epos.yzoom[0],fill=False, zorder=1) ) ''' cdf orbital period ''' if 'xvar' in epos.prob: ax3.set_title('Period, p={:.3g}'.format(epos.prob['xvar'])) else: ax3.set_title('Orbital Period') ax3.set_xlabel('Orbital Period [days]') ax3.set_ylabel('CDF') ax3.set_xscale('log') ax3.set_ylim([-0.05,1.05]) ax3.set_xlim(*epos.xzoom) if epos.MonteCarlo: #model histogram x P= sim['P zoom'] ax3.plot(np.sort(P), np.arange(P.size, dtype=float)/P.size, ls='-', marker='', color='r') else: ax3.plot(sim['P zoom'], sim['P zoom cdf'], ls='-', marker='', color='r') #obs histogram x P= epos.obs_zoom['x'] ax3.plot(np.sort(P), np.arange(P.size, dtype=float)/P.size, ls='-', marker='', color='b') ''' CDF planet radius ''' if 'yvar' in epos.prob: ax4.set_title('{}, p={:.3g}'.format('M sin i' if epos.RV else 'Radius', epos.prob['yvar'])) else: ax4.set_title('{}'.format('M sin i' if epos.RV else 'Radius')) if epos.RV: ax4.set_xlabel(r'Planet M sin i [M$_\bigoplus$]') else: ax4.set_xlabel(r'Planet Radius [R$_\bigoplus$]') ax4.set_ylabel('CDF') ax4.set_xscale('log') ax4.set_ylim([-0.05,1.05]) ax4.set_xlim(*epos.yzoom) ax4.set_xticks(epos.yticks) ax4.get_xaxis().set_major_formatter(tck.ScalarFormatter()) if epos.MonteCarlo: #model histogram x R= sim['Y zoom'] ax4.plot(np.sort(R), np.arange(R.size, dtype=float)/R.size, ls='-', marker='', color='r') else: ax4.plot(sim['Y zoom'], sim['Y zoom cdf'], ls='-', marker='', color='r') #obs histogram x R= epos.obs_zoom['y'] ax4.plot(np.sort(R), np.arange(R.size, dtype=float)/R.size, ls='-', marker='', color='b') f.tight_layout() helpers.save(plt, epos.plotdir+'output/cdf.diag')
def pdf(epos): #assert epos.populationtype is 'model' f, ((ax1,ax2),(ax3,ax4)) = plt.subplots(2, 2, sharex='col', sharey='row') f.subplots_adjust(hspace=0, wspace=0) # 1 2 # 3 4 ax1.set_title('Synthetic Model Populations',loc='left') ax3.set_xlabel('Orbital Period [days]') if epos.RV: ax1.set_ylabel(r'Planet Mass [M$_\bigoplus$]') else: ax1.set_ylabel(r'Planet Radius [R$_\bigoplus$]') ax2.set_xlabel('Planets/bin') ax3.set_ylabel('Planets/bin') ax1.set_xlim(epos.xtrim) ax1.set_ylim(epos.ytrim) ax1.set_xscale('log') ax1.set_yscale('log') sim=epos.synthetic_survey # PDF, individual contributions if epos.populationtype is 'model': for k, sg in enumerate(epos.groups): subset= sim['i sg']==k P= sim['P'][subset] R= sim['Y'][subset] ax1.plot(P,R, ls='', marker='.', mew=0, ms=5.0, color=clrs[k % 4]) xgrid= np.logspace(*np.log10(epos.xtrim)) pdf= regression.sliding_window_log(P, None, xgrid) #, width=2. ) ax3.plot(xgrid, pdf, ls='-', marker='', color=clrs[k % 4],label='{} x{:.3f}'.format(sg['name'], sg['weight'])) ygrid= np.logspace(*np.log10(epos.ytrim)) pdf= regression.sliding_window_log(R, None, ygrid) #, width=2. ) ax2.plot(pdf, ygrid, ls='-', marker='', color=clrs[k % 4]) else: # top left panel (P,R) ax1.plot(sim['P'], sim['Y'], ls='', marker='.', mew=0, ms=5.0, color='k') # PDF, all combined, 2 panels xgrid= np.logspace(*np.log10(epos.xtrim)) pdf= regression.sliding_window_log(sim['P'], None, xgrid) #, width=2. ) weight= np.sum([sg['weight'] for sg in epos.groups]) if epos.populationtype is 'model' else epos.fitpars.get('pps',Init=True) ax3.plot(xgrid, pdf, ls='-', marker='', color='k',label='combined x {:.3f}'.format(weight)) ygrid= np.logspace(*np.log10(epos.ytrim)) pdf= regression.sliding_window_log(sim['Y'], None, ygrid) #, width=2. ) ax2.plot(pdf, ygrid, ls='-', marker='', color='k') # observations if epos.Observation and epos.DetectionEfficiency: pdf= regression.sliding_window_log(epos.obs_xvar, None, xgrid) ax3.plot(xgrid, pdf, ls=':', marker='', color='k', label='Kepler') pdf= regression.sliding_window_log(epos.obs_yvar, None, ygrid) ax2.plot(pdf, ygrid, ls=':', marker='', color='k') xmax= ax3.get_xlim()[-1] ymax= ax3.get_ylim()[-1] ax3.errorbar(xmax/1.5, ymax*0.9, xerr=(xmax/1.5*(1.-np.sqrt(1./2.)) ), color='k') xmax= ax2.get_xlim()[-1] ymin= ax2.get_ylim()[0] ax2.errorbar(xmax*0.9, ymin*1.5, yerr=(ymin*1.5*(1.-np.sqrt(1./2.)) ), color='k') #ax2.tick_params(labelbottom='on') # does not re-enable axis ''' Legend instead of 4th plot''' ax3.legend(loc='center left', shadow=False, prop={'size':14}, numpoints=1,bbox_to_anchor=(1,0.5)) ax4.axis('off') helpers.save(plt, epos.plotdir+'output/pdf.diag')
def period(epos, Population=False, Occurrence=False, Observation=False, Tag=False, color='C1', Zoom=False, Rbin=[1., 4.]): ''' Model occurrence as function of orbital period''' f, ax = plt.subplots() helpers.set_axis_distance(ax, epos, Trim=True) ax.set_xlim(0.5, 200) ax.set_ylabel( r'Planet Occurrence {:.2g}-{:.2g} $R_\bigoplus$'.format(*Rbin)) ax.set_yscale('log') pfm = epos.pfm eta = epos.modelpars.get('eta', Init=True) if not 'R' in pfm: pfm['R'], _ = epos.MR(pfm['M']) if Tag: # function that return a simulation subset based on the tag subset = { 'Fe/H<=0': lambda tag: tag <= 0, 'Fe/H>0': lambda tag: tag > 0 } ''' Bins ''' #xbins= np.geomspace(1,1000,10)/(10.**(1./3.)) #xbins= np.geomspace(0.5,200,15) dwP = 0.3 # bin width in ln space if Zoom: xbins = np.exp( np.arange(np.log(epos.xzoom[0]), np.log(epos.xzoom[-1]) + dwP, dwP)) else: xbins = np.exp( np.arange(np.log(epos.xtrim[0]), np.log(epos.xtrim[-1]) + dwP, dwP)) ''' Plot model occurrence or observed counts''' weights = np.full(pfm['np'], eta / pfm['ns']) if 'draw prob' in pfm and not Tag: prob = pfm['draw prob'][pfm['ID']] weights *= prob * pfm['ns'] # system weights sum up to 1 # histograms if Tag: for key, f in subset.iteritems(): toplot = f(pfm['tag']) #& (pfm['R']>1.) weights = np.where(toplot, eta, 0.) / f(pfm['system tag']).sum() ax.hist(pfm['P'], bins=xbins, weights=weights, histtype='step', label=key, color='#88CCEE' if key == 'Fe/H<=0' else '#332288') else: ax.hist(pfm['P'], bins=xbins, weights=weights, color=color, histtype='step') if Tag: fname = '.tag' ax.set_title(epos.name + ': Disk Fe/H') ax.legend(fontsize='small', loc='lower right') else: fname = '' if Occurrence: cut = (Rbin[0] < epos.obs_yvar) & (epos.obs_yvar < Rbin[-1]) weights = epos.occurrence['planet']['occ'][cut] ax.hist(epos.obs_xvar[cut], bins=xbins, weights=weights, histtype='step', color='k') helpers.save(plt, '{}occurrence/model.period{}'.format(epos.plotdir, fname)) # elif Observation: # counts else: helpers.save(plt, '{}model/input.period{}'.format(epos.plotdir, fname))
import numpy import dmsh from helpers import assert_norm_equality, save def test_union(show=False): angles = numpy.pi * numpy.array([3.0 / 6.0, 7.0 / 6.0, 11.0 / 6.0]) geo = dmsh.Intersection( [ dmsh.Circle([numpy.cos(angles[0]), numpy.sin(angles[0])], 1.5), dmsh.Circle([numpy.cos(angles[1]), numpy.sin(angles[1])], 1.5), dmsh.Circle([numpy.cos(angles[2]), numpy.sin(angles[2])], 1.5), ] ) X, cells = dmsh.generate(geo, 0.1, show=show, tol=1.0e-10) ref_norms = [6.8247386668599034e01, 5.1256971008793917e00, 7.2474487138537913e-01] assert_norm_equality(X.flatten(), ref_norms, 1.0e-12) return X, cells if __name__ == "__main__": X, cells = test_union(show=False) save("intersection_three_circles.png", X, cells)
def HansenMurray(epos, color='purple'): ''' figures not included ''' import matplotlib.image as mpimg pfm = epos.pfm print pfm.keys() ''' Hansen & Murray 2013 Figure 1 ''' f, ax = plt.subplots() ax.set_xlabel('$N_p$') ax.set_ylabel('counts') ax.set_xlim([0.5, 10.5]) ax.set_ylim([0, 35]) fig1 = mpimg.imread('HM13figs/fig1_cut.png') ax.imshow(fig1, aspect='auto', extent=[0.5, 10.5, 0, 35]) _, counts = np.unique(pfm['ID'], return_counts=True) ax.hist(counts, bins=np.arange(0, 11), align='left', color='purple', alpha=0.7, weights=np.full_like(counts, 2)) helpers.save(plt, '{}HM13/fig1'.format(epos.plotdir), dpi=300) ''' Hansen & Murray 2013 Figure 5 ''' f, ax = plt.subplots() ax.set_xlabel('$P_2/P_1$') ax.set_ylabel('counts') ax.set_xlim([1, 4]) ax.set_ylim([0, 32]) #ax.set_xscale('log') #ax.set_yscale('log') fig1 = mpimg.imread('HM13figs/fig5_cut.png') ax.imshow(fig1, aspect='auto', extent=[1, 4, 0, 32]) dP = pfm['dP'][pfm['dP'] > 1] ax.hist(dP, bins=np.linspace(1. + (1.5 / 37.), 4, 38), align='mid', color='purple', alpha=0.7, weights=np.full_like(dP, 2)) helpers.save(plt, '{}HM13/fig5'.format(epos.plotdir), dpi=300) ''' Hansen & Murray 2013 Figure 9 ''' f, ax = plt.subplots() ax.set_xlabel('Eccentricity') ax.set_ylabel('counts') ax.set_xlim([0, 0.24]) ax.set_ylim([0, 35]) #ax.set_xscale('log') #ax.set_yscale('log') fig1 = mpimg.imread('HM13figs/fig9_cut.png') ax.imshow(fig1, aspect='auto', extent=[0, 0.24, 0, 35]) ax.hist(pfm['ecc'], bins=np.linspace(0.01, 0.25, 25), align='left', color='purple', alpha=0.7, weights=np.full_like(pfm['ecc'], 2)) helpers.save(plt, '{}HM13/fig9'.format(epos.plotdir), dpi=300) ''' Hansen & Murray 2013 Figure 10 ''' f, ax = plt.subplots() ax.set_xlabel('sma [au]') ax.set_ylabel('Inclination') ax.set_xlim([0.04, 1.2]) ax.set_ylim([0, 33]) #ax.set_xscale('log') fig10 = mpimg.imread('HM13figs/fig10_cut.png') ax.imshow(fig10, aspect='auto', extent=[0.04, 1.2, 0, 33]) ax.get_xaxis().set_ticks([]) axlog = ax.twiny() axlog.set_xlim([0.04, 1.2]) axlog.set_xscale('log') axlog.plot(pfm['sma'], pfm['inc'], color='purple', alpha=0.7, marker='o', ls='') helpers.save(plt, '{}HM13/fig10'.format(epos.plotdir), dpi=300) ''' Hansen & Murray 2013 Figure 11 ''' f, (axa, axb) = plt.subplots(2) fig11a = mpimg.imread('HM13figs/fig11a_cut.png') fig11b = mpimg.imread('HM13figs/fig11b_cut.png') #ax[0].set_xlabel('Inclination') axa.set_ylabel('counts') axa.set_xlim([0, 24.5]) axa.set_ylim([0, 20]) axb.set_xlabel('Inclination') axb.set_ylabel('counts') axb.set_xlim([0, 14.5]) axb.set_ylim([0, 35]) axa.imshow(fig11a, aspect='auto', extent=[0, 24.5, 0, 20]) axb.imshow(fig11b, aspect='auto', extent=[0, 14.5, 0, 35]) inner = pfm['inc'][pfm['sma'] < 0.1] outer = pfm['inc'][(pfm['sma'] > 0.1) & (pfm['sma'] < 1.0)] axa.hist(inner, bins=np.linspace(0, 25, 26), align='mid', color='purple', alpha=0.7, weights=np.full_like(inner, 2)) axb.hist(outer, bins=np.linspace(0, 15, 50), align='mid', color='purple', alpha=0.7, weights=np.full_like(outer, 2)) helpers.save(plt, '{}HM13/fig11'.format(epos.plotdir), dpi=300)
import dmsh from helpers import assert_norm_equality, save def test_pacman(show=False): geo = dmsh.Difference( dmsh.Circle([0.0, 0.0], 1.0), dmsh.Polygon([[0.0, 0.0], [1.5, 0.4], [1.5, -0.4]]), ) X, cells = dmsh.generate(geo, 0.1, show=show, tol=1.0e-10) ref_norms = [3.0385105041432689e02, 1.3644964912810719e01, 1.0] assert_norm_equality(X.flatten(), ref_norms, 1.0e-12) return X, cells if __name__ == "__main__": X, cells = test_pacman(show=False) save("pacman.png", X, cells)
def multiplicity(epos, MC=False, Planets=False, MCMC=False): # plot multiplicity f, ax = plt.subplots() ax.set_title('Multi-Planet Frequency') ax.set_xlabel('Planets per System') ax.set_ylabel('Planet Counts' if Planets else 'System Counts') ax.set_xlim(0.5, 7.5) if not Planets: ax.set_ylim(0.5, 1e4) # 7. ax.set_yscale('log') #ax.get_yaxis().set_major_formatter(tck.ScalarFormatter()) key = 'pl cnt' if Planets else 'count' # MC data if MC or MCMC: ss = epos.synthetic_survey if Planets: ax.bar(ss['multi']['bin'], ss['multi'][key], color='C0', label='Simulated', width=1) f_iso = epos.fitpars.get('f_iso') if f_iso > 0: fsingle = np.sum(ss['multi']['count']) * f_iso ax.bar(1, fsingle, bottom=ss['multi'][key][0] - fsingle, color='', label='Single Planets', width=1, hatch='xx') #, ec='k') #ax.plot(1, ss['multi'][key][0]-fsingle, marker='+', ms=10, ls='', color='k', label='no dichotomy') elif MCMC: for ss in epos.ss_sample: ax.hlines(ss['multi'][key], ss['multi']['bin'] - 0.5, ss['multi']['bin'] + 0.5, color='b', alpha=0.1) else: #ax.step(ss['multi']['bin'], ss['multi'][key], color='C0',label=epos.name, where='mid') ax.plot(ss['multi']['bin'], ss['multi'][key], ls='', marker='+', ms=10, color='C0', label=epos.name) if hasattr(epos, 'ss_extra'): # advance color cycle # ax._get_lines.get_next_color() ax.plot([], []) ax.plot([], []) # plot extra epos runs for ss in epos.ss_extra: ax.plot(ss['multi']['bin'], ss['multi'][key], ls='', marker='+', ms=10, label=ss['name']) # observations in same region ax.step(epos.obs_zoom['multi']['bin'], epos.obs_zoom['multi'][key], where='mid', color='C1', label='Kepler') else: # observations ax.plot(epos.multi['bin'], epos.multi[key], drawstyle='steps-mid', ls='--', marker='', color='gray', label='Kepler all') ax.legend(loc='upper right', shadow=False, prop={'size': 14}, numpoints=1) prefix = 'output' if MC else 'survey' if MCMC: prefix = 'mcmc' suffix = '.planets' if Planets else '' helpers.save(plt, '{}{}/multiplicity{}'.format(epos.plotdir, prefix, suffix))
import numpy as np from helpers import assert_norm_equality, save import dmsh def test(show=False): r = dmsh.Rectangle(-1.0, +1.0, -1.0, +1.0) c = dmsh.Circle([0.0, 0.0], 0.3) geo = dmsh.Difference(r, c) X, cells = dmsh.generate( geo, lambda pts: np.abs(c.dist(pts)) / 5 + 0.05, show=show, tol=1.0e-10, max_steps=100, ) ref_norms = [2.48e02, 1.200e01, 1.0] assert_norm_equality(X.flatten(), ref_norms, 1.0e-2) return X, cells if __name__ == "__main__": X, cells = test(show=True) save("square_hole_refined.png", X, cells)
def periodratio(epos, MC=False, N=False, Input=False, MCMC=False): # plot multiplicity f, ax = plt.subplots() ax.set_title('Period Ratio of Adjacent Planets') ax.set_xlabel(r'$\mathcal{P}$ = Period Outer/Inner') ax.set_ylabel('Planet Counts') ax.set_xlim(1, 10) ax.set_xscale('log') for s in [ax.set_xticks, ax.set_xticklabels]: s([1, 2, 3, 4, 5, 7, 10]) ax.set_xticks([], minor=True) # minor ticks generate labels bins = np.logspace(0, 1, 15) # 1,10 # MC data if MC or MCMC: ss = epos.synthetic_survey if MCMC: for ss in epos.ss_sample: # bar? ax.hist(ss['multi']['Pratio'], bins=bins, histtype='step', color='b', alpha=0.1) #ax.hist(ss['multi']['Pratio'], bins=bins, color='b', alpha=1./len(epos.ss_sample)) else: ax.hist(ss['multi']['Pratio'], bins=bins, color='C0', histtype='stepfilled', label='Simulated') #epos.name) if N: # planets inbetween? #ax.hist(ss['multi']['dPN'][0], \ # bins=bins, ec='k', histtype='step', label='Adjacent planet') ax.hist(np.concatenate(ss['multi']['dPN'][1:]), bins=bins, hatch='xx', histtype='stepfilled', label='Planet Inbetween') # ec, color else: #ax.axvline(np.median(ss['multi']['Pratio']), color='C0', ls='--') pass if hasattr(epos, 'ss_extra'): # advance color cycle # ax._get_lines.get_next_color() ax.plot([], []) ax.plot([], []) ax.plot([], []) # plot extra epos runs for ss in epos.ss_extra: ax.hist(ss['multi']['Pratio'], bins=bins, histtype='step', label=ss['name']) else: # observed all ax.hist(epos.multi['Pratio'], bins=bins, color='0.7', label='Kepler all') #ax.axvline(np.median(epos.multi['Pratio']), color='0.7', ls='--') ''' input distribution ''' if Input and epos.Parametric: #Pgrid=bins Pgrid = np.logspace(0, 1) pdf, _ = draw_dP(epos, Pgrid=Pgrid) pdf *= 0.95 * ax.get_ylim()[1] / max(pdf) ax.plot(Pgrid, pdf, marker='', ls='-', color='r', label='Intrinsic') elif epos.Zoom: # Observed zoom ax.hist(epos.obs_zoom['multi']['Pratio'], \ bins=bins, ec='C1', histtype='step', label='Kepler') if not MCMC: ax.axvline(np.median(epos.obs_zoom['multi']['Pratio']), color='C1', ls='--') prefix = 'output' if MC else 'survey' suffix = '.index' if N else '' if Input: suffix += '.input' if MCMC: prefix = 'mcmc' if MC: ax.legend(loc='upper right', shadow=False, prop={'size': 14}, numpoints=1) helpers.save(plt, '{}{}/periodratio{}'.format(epos.plotdir, prefix, suffix))
def panels_radius(epos, Population=False, Occurrence=False, Observation=False, Tag=False, color='C0', clr_obs='C3', Shade=True, Fancy=True, Zoom=False): f, (ax, axR, axP) = helpers.make_panels(plt, Fancy=Fancy) pfm = epos.pfm eta = epos.modelpars.get('eta', Init=True) title = '' if not 'R' in pfm: pfm['R'], _ = epos.MR(pfm['M']) if Tag: # function that return a simulation subset based on the tag subset = { 'Fe/H<=0': lambda tag: tag <= 0, 'Fe/H>0': lambda tag: tag > 0 } ''' Bins ''' dwR = 0.2 # bin width in ln space dwP = 0.3 if Zoom: xbins = np.exp( np.arange(np.log(epos.xzoom[0]), np.log(epos.xzoom[-1]) + dwP, dwP)) ybins = np.exp( np.arange(np.log(epos.yzoom[0]), np.log(epos.yzoom[-1]) + dwR, dwR)) else: xbins = np.exp( np.arange(np.log(epos.xtrim[0]), np.log(epos.xtrim[-1]) + dwP, dwP)) ybins = np.exp( np.arange(np.log(epos.ytrim[0]), np.log(epos.ytrim[-1]) + dwR, dwR)) ''' Plot model occurrence or observed counts''' if Observation: # plot model planets * completeness weights = eta * epos.occurrence['model']['completeness'] / pfm['ns'] else: weights = np.full(pfm['np'], eta / pfm['ns']) if 'draw prob' in pfm and not Tag: prob = pfm['draw prob'][pfm['ID']] weights *= prob * pfm['ns'] # system weights sum up to 1 #nonzero= np.where(prob>0, 1., 0.) #weights*= nonzero*(pfm['np']/nonzero.sum()) # histograms if Tag: for key, f in subset.iteritems(): toplot = f(pfm['tag']) #weights= eta*epos.occurrence['model']['completeness'] \ # *np.where(toplot,1.,0.)/f(pfm['system tag']).sum() weights = np.where(toplot, eta, 0.) / f(pfm['system tag']).sum() axP.hist(pfm['P'], bins=xbins, weights=weights, histtype='step', label=key) axR.hist(pfm['R'], bins=ybins, orientation='horizontal', weights=weights, histtype='step') else: # color have to be 1-element lists ?? axP.hist(pfm['P'], bins=xbins, weights=weights, color=[color]) axR.hist(pfm['R'], bins=ybins, orientation='horizontal', weights=weights, color=[color]) ''' Overplot observations? ''' if Population: assert hasattr(epos, 'func') fname = '.pop' + ('.zoom' if Zoom else '') title = epos.title pps, pdf, pdf_X, pdf_Y = periodradius(epos, Init=True) _, _, pdf_X, _ = periodradius(epos, Init=True, ybin=ybins) _, _, _, pdf_Y = periodradius(epos, Init=True, xbin=xbins) pps, _, _, _ = periodradius(epos, Init=True, xbin=xbins, ybin=ybins) #pdf/= np.max(pdf) #pdflog= np.log10(pdf) # in % levels = np.linspace(0, np.max(pdf)) lines = np.array([0.1, 0.5]) * np.max(pdf) if Shade: ax.contourf(epos.X_in, epos.Y_in, pdf, cmap='Purples', levels=levels) #ax.contour(epos.X_in, epos.Y_in, pdf, levels=lines) # Side panels #print 'pps model= {}'.format(eta) axP.plot(epos.MC_xvar, pdf_X * dwP, marker='', ls='-', color='purple') axR.plot(pdf_Y * dwR, epos.in_yvar, marker='', ls='-', color='purple') else: # renormalize xnorm = axP.get_ylim()[1] / max(pdf_X) ynorm = axR.get_xlim()[1] / max(pdf_Y) axP.plot(epos.MC_xvar, pdf_X * xnorm, marker='', ls='-', color=clr_obs) axR.plot(pdf_Y * ynorm, epos.in_yvar, marker='', ls='-', color=clr_obs) elif Observation: fname = '.obs' + ('.zoom' if Zoom else '') title = epos.title + ': Counts' ax.plot(epos.obs_xvar, epos.obs_yvar, ls='', marker='.', ms=5.0, color='0.5') weights = np.full(epos.obs_xvar.size, 1. / epos.nstars) axP.hist(epos.obs_xvar, bins=xbins, weights=weights, histtype='step', color='0.5') axR.hist(epos.obs_yvar, bins=ybins, weights=weights, orientation='horizontal', histtype='step', color='0.5') elif Occurrence: fname = '.occ' + ('.zoom' if Zoom else '') title = epos.title + r': Occurrence, $\eta={:.2g}$'.format(eta) ax.plot(epos.obs_xvar, epos.obs_yvar, ls='', marker='.', ms=5.0, color='0.5') cut = epos.obs_yvar > 0.45 weights = 1. / (epos.occurrence['planet']['completeness'][cut] * epos.nstars) axP.hist(epos.obs_xvar[cut], bins=xbins, weights=weights, histtype='step', color='k') axR.hist(epos.obs_yvar[cut], bins=ybins, weights=weights, orientation='horizontal', histtype='step', color='k') elif Tag: fname = '.tag' ax.set_title(epos.title + ': Tag') axP.legend(frameon=False, fontsize='small') # for k, tag in enumerate(subset): # axP.text(0.98,0.95-0.05*k,tag,ha='right',va='top',color='C1', # transform=axP.transAxes) else: fname = '' if Fancy: plt.suptitle(title, ha='center') #, x=0.05) else: ax.set_title(title) ''' plot main panel''' #helpers.set_axes(ax, epos, Trim=True) helpers.set_axes(ax, epos, Trim=True) if Tag: for key, f in subset.iteritems(): todraw = f(pfm['tag']) ax.plot(pfm['P'][todraw], pfm['R'][todraw], **fmt_symbol) elif 'draw prob' in pfm: #fmt_symbol['alpha']= 0.6*pfm['draw prob'][pfm['ID']] # alpha can't be array todraw = pfm['draw prob'][pfm['ID']] > 0 ax.plot(pfm['P'][todraw], pfm['R'][todraw], color=color, **fmt_symbol) else: ax.plot(pfm['P'], pfm['R'], color=color, **fmt_symbol) ''' Period side panel ''' #axP.yaxis.tick_right() #axP.yaxis.set_ticks_position('both') #axP.tick_params(axis='y', which='minor',left='off',right='off') helpers.set_axis_distance(axP, epos, Trim=True) ''' Mass side panel''' helpers.set_axis_size(axR, epos, Trim=True) #, In= epos.MassRadius) helpers.save(plt, '{}model/input.radius{}'.format(epos.plotdir, fname))
def inner(epos): ''' Plot inner planet ''' # plot multiplicity f, ax = plt.subplots() pop = epos.population ax.set_title('Simulated Systems') ax.set_xlabel('Orbital Period (days)') ax.set_ylabel('Fraction of stars') # 0-45 % #ax.set_ylim(-0.05, 1.05) ax.set_ylim(0, 1) ax.set_xlim(0.2, 730) ax.set_xscale('log') x = np.geomspace(0.2, 730) # ax.fill_between(x, 0.0, 0.159, color='g', alpha=0.2, lw=0) # ax.fill_between(x, 0.159, 0.841, color='c', alpha=0.2, lw=0) # ax.fill_between(x, 0.841, 1, color='g', alpha=0.2, lw=0) ax.fill_between(x, 0.0, 0.023, color='g', alpha=0.2, lw=0) ax.fill_between(x, 0.023, 0.159, color='c', alpha=0.2, lw=0) ax.fill_between(x, 0.159, 0.841, color='y', alpha=0.2, lw=0) ax.fill_between(x, 0.841, 0.977, color='c', alpha=0.2, lw=0) ax.fill_between(x, 0.977, 1, color='g', alpha=0.2, lw=0) ax.axhline(0.5, color='k', lw=1) xtext = 0.21 ax.text(xtext, 0.023, '$2\sigma$', va='center', size=10) ax.text(xtext, 0.159, '$1\sigma$', va='center', size=10) #ax.text(xtext, 0.5, 'mean', va='center',size=8) ax.text(xtext, 0.5 + 0.01, 'mean', size=10) ax.text(xtext, 0.841, '$1\sigma$', va='center', size=10) ax.text(xtext, 0.977, '$2\sigma$', va='center', size=10) # BG all planets? # ax.plot(pop['P'], pop['order'], # ls='', marker='.', mew=0, ms=3, color='0.8') # all multis key = 'single' ax.plot(pop[key]['P'], pop[key]['order'], ls='', marker='.', mew=0, ms=3, color='b') key = 'multi' ax.plot(pop[key]['P'], pop[key]['order'], ls='', marker='.', mew=0, ms=3, color='purple') # for key in ['system','single','multi']: # ax.plot(pop['P'], pop['order'], # ls='', marker='.', mew=0, ms=3, color='gray') # Solar System #ax.plot([0.95]*4,[]) yss = 0.9 #yss= 0.1 ax.text(88, yss, 'M', ha='center', va='center', color='r', size=8) ax.text(225, yss, 'V', ha='center', va='center', color='r', size=8) ax.text(365, yss, 'E', ha='center', va='center', color='r', size=8) ax.text(687, yss, 'M', ha='center', va='center', color='r', size=8) helpers.save(plt, '{}/population/inner_test'.format(epos.plotdir))
def panels_mass(epos, Population=False, color='C1'): f, (ax, axM, axP) = helpers.make_panels(plt) pfm = epos.pfm eta = epos.modelpars.get('eta', Init=True) ''' Bins ''' dw = 0.5 # bin width in ln space xbins = np.exp( np.arange(np.log(pfm['P limits'][0]), np.log(pfm['P limits'][-1]) + dw, dw)) ybins = np.exp( np.arange(np.log(pfm['M limits'][0]), np.log(pfm['M limits'][-1]) + dw, dw)) ''' Posterior ''' if Population: assert hasattr(epos, 'func') fname = '.pop' # side panels marginalized over M and P limits pps, pdf, pdf_X, pdf_Y = periodradius(epos, Init=True) _, _, pdf_X, _ = periodradius(epos, Init=True, ybin=ybins) _, _, _, pdf_Y = periodradius(epos, Init=True, xbin=xbins) pps, _, _, _ = periodradius(epos, Init=True, xbin=xbins, ybin=ybins) #pdf/= np.max(pdf) #pdflog= np.log10(pdf) # in % levels = np.linspace(0, np.max(pdf)) lines = np.array([0.1, 0.5]) * np.max(pdf) ax.contourf(epos.X_in, epos.Y_in, pdf, cmap='Purples', levels=levels) #ax.contour(epos.X_in, epos.Y_in, pdf, levels=lines) # Side panels #print 'pps model= {}'.format(eta) scale = dw axP.plot(epos.MC_xvar, pdf_X * scale, marker='', ls='-', color='purple') axM.plot(pdf_Y * scale, epos.in_yvar, marker='', ls='-', color='purple') else: fname = '' ''' plot main panel''' ax.set_title(epos.name) #helpers.set_axes(ax, epos, Trim=True) ax.set_xscale('log') ax.set_yscale('log') #ax.set_xlim(epos.mod_xlim) #ax.set_ylim(epos.mod_ylim) ax.plot(pfm['P'], pfm['M'], color=color, **fmt_symbol) xlim = ax.get_xlim() ylim = ax.get_ylim() ''' Period side panel ''' #axP.yaxis.tick_right() #axP.yaxis.set_ticks_position('both') #axP.tick_params(axis='y', which='minor',left='off',right='off') axP.set_xscale('log') axP.set_xlim(xlim) #ax.set_xlabel('Semi-Major Axis [au]') axP.set_xlabel('Orbital Period [days]') axP.hist(pfm['P'], color=color, bins=xbins, weights=np.full(pfm['np'], eta / pfm['np'])) ''' Mass side panel''' #helpers.set_axis_size(axR, epos, Trim=True) #, In= epos.MassRadius) axM.set_ylabel(r'Planet Mass [M$_\bigoplus$]') axM.set_yscale('log') axM.set_ylim(ylim) axM.hist(pfm['M'], bins=ybins, orientation='horizontal', weights=np.full(pfm['np'], eta / pfm['np']), color=color) helpers.save(plt, '{}model/input.mass{}'.format(epos.plotdir, fname))
import numpy import dmsh from helpers import assert_norm_equality, save def test(show=False): geo = dmsh.Rotation(dmsh.Rectangle(-1.0, +2.0, -1.0, +1.0), 0.1 * numpy.pi) X, cells = dmsh.generate(geo, 0.1, show=show, tol=1.0e-10) ref_norms = [ 9.5352192763033452e02, 3.1344318120314945e01, 2.2111300269652543e00 ] assert_norm_equality(X.flatten(), ref_norms, 1.0e-10) return X, cells if __name__ == "__main__": X, cells = test(show=False) save("rotation.png", X, cells)
def periodratio(epos, color='C0', clr_obs='C3', Simple=False, Fancy=True): pfm = epos.pfm if Fancy: f, (ax, axR, axP) = helpers.make_panels(plt, Fancy=True) f.suptitle('Multi-planets {}'.format(epos.title)) else: f, (ax, axR, axP) = helpers.make_panels_right(plt) ax.set_title('Input Multi-planets {}'.format(epos.title)) ''' Inc-sma''' ax.set_xlabel('Semi-Major Axis [au]') ax.set_ylabel('Period ratio') #ax.set_xlim(epos.mod_xlim) ax.set_ylim(0.9, 10) ax.set_xscale('log') ax.set_yscale('log') #ax.axhline(np.median(pfm['inc']), ls='--') single = pfm['dP'] == np.nan inner = pfm['dP'] == 1 nth = pfm['dP'] > 1 # print pfm['dP'][single] # print pfm['dP'][nth] # print pfm['dP'][inner] # print pfm['dP'][nth].size, pfm['np'] # ok ax.plot(pfm['sma'][single], pfm['dP'][single], color='0.7', **fmt_symbol) ax.plot(pfm['sma'][nth], pfm['dP'][nth], color=color, **fmt_symbol) ax.plot(pfm['sma'][inner], pfm['dP'][inner], color='C1', **fmt_symbol) ''' Histogram Period Ratio''' axR.set_yscale('log') axR.set_ylim(0.9, 10) #dP= np.logspace(0,1,15) dP = np.logspace(0, 1, 25) axR.hist(pfm['dP'][nth], bins=dP, orientation='horizontal', color=color) if not Simple: ax.axhline(np.median(pfm['dP'][nth]), ls='--', color=color, zorder=-1) #Model best-fit dP = np.logspace(0, 1) xmax = axR.get_xlim()[-1] with np.errstate(divide='ignore'): Dgrid = np.log10(2. * (dP**(2. / 3.) - 1.) / (dP**(2. / 3.) + 1.)) Dgrid[0] = -2 if Simple: scale = -0.37 pdf = scipy.stats.norm(scale, 0.19).pdf(Dgrid) pdf *= xmax / max(pdf) axR.plot(pdf, dP, ls='-', color=clr_obs) pscale = np.interp(scale, Dgrid, dP) #ax.axhline(pscale, color=clr_obs, ls='--') else: for scale, ls in zip([-0.30, -0.37, -0.41], [':', '--', ':']): pdf = scipy.stats.norm(scale, 0.19).pdf(Dgrid) pdf *= xmax / max(pdf) axR.plot(pdf, dP, ls=ls, color='purple') pscale = np.interp(scale, Dgrid, dP) ax.axhline(pscale, color='purple', ls=ls, zorder=-1) ''' Histogram Inner Planet''' axP.set_xscale('log') axP.set_xlim(ax.get_xlim()) sma = np.geomspace(*ax.get_xlim(), num=25) axP.hist(pfm['sma'][inner], bins=sma, color='C1', label='Inner Planet') ymax = axP.get_ylim()[-1] P = np.geomspace(0.5, 730) smaP = (P / 365.25)**(1. / 1.5) pdf = brokenpowerlaw1D(P, 10, 1.5, -0.8) pdf *= ymax / max(pdf) #axP.legend(frameon=False) if Fancy: ax.text(0.02, 0.98, 'Inner Planet', ha='left', va='top', color='C1', transform=ax.transAxes) ax.text(0.02, 0.98, '\nOuter Planet(s)', ha='left', va='top', color=color, transform=ax.transAxes) else: axP.text(0.98, 0.95, 'Inner Planet', ha='right', va='top', color='C1', transform=axP.transAxes) axP.plot(smaP, pdf, ls='-', color=clr_obs) #helpers.set_axes(ax, epos, Trim=True) #helpers.set_axis_distance(axP, epos, Trim=True) #helpers.set_axis_size(axR, epos, Trim=True) #, In= epos.MassRadius) helpers.save(plt, epos.plotdir + 'model/Pratio-sma')
from helpers import assert_norm_equality, save import dmsh def test(show=False): geo = dmsh.Rectangle(0.0, 1.0, 0.0, 1.0) # p0 = dmsh.Path([[0.0, 0.0]]) p1 = dmsh.Path([[0.4, 0.6], [0.6, 0.4]]) def edge_size(x): return 0.03 + 0.1 * p1.dist(x) X, cells = dmsh.generate(geo, edge_size, show=show, tol=1.0e-10, max_steps=100) ref_norms = [3.7918105331047593e02, 1.5473837427489348e01, 1.0000000000000000e00] assert_norm_equality(X.flatten(), ref_norms, 1.0e-3) return X, cells if __name__ == "__main__": X, cells = test(show=False) save("refinement_line.png", X, cells)
def periodratio_size(epos, color='C1'): pfm = epos.pfm f, (ax, axR, axP) = helpers.make_panels_right(plt) ''' Inc-sma''' ax.set_title('Input Multi-planets {}'.format(epos.name)) axP.set_xlabel('Period ratio') #ax.set_ylabel(r'Size [$R_\bigoplus$]') ax.set_xlim(0.9, 10) #ax.set_ylim(0.3,20) ax.set_xscale('log') #ax.set_yscale('log') helpers.set_axis_size(ax, epos, Trim=True) ''' grids ''' dP = np.logspace(0, 1) dP_bins = np.logspace(0, 1, 15) # exoplanet data + hist ax.plot(epos.multi['Pratio'], epos.multi['Rpair'], ls='', marker='.', ms=5.0, color='0.5') #ax.axhline(np.median(pfm['inc']), ls='--') single = pfm['dP'] == np.nan inner = pfm['dP'] == 1 nth = pfm['dP'] > 1 # print pfm['dP'][single] # print pfm['dP'][nth] # print pfm['dP'][inner] # print pfm['dP'][nth].size, pfm['np'] # ok ax.plot(pfm['dP'][single], pfm['R'][single], color='0.7', **fmt_symbol) ax.plot(pfm['dP'][nth], pfm['R'][nth], color=color, **fmt_symbol) ax.plot(pfm['dP'][inner], pfm['R'][inner], color='C1', **fmt_symbol) ''' Histogram Period Ratio''' axP.set_xscale('log') axP.set_xlim(0.9, 10) axP.hist(pfm['dP'][nth], bins=dP_bins, color=color) ax.axvline(np.median(pfm['dP'][nth]), ls='--', color=color) ''' Model best-fit ''' xmax = axP.get_ylim()[-1] with np.errstate(divide='ignore'): Dgrid = np.log10(2. * (dP**(2. / 3.) - 1.) / (dP**(2. / 3.) + 1.)) Dgrid[0] = -2 for scale, ls in zip([-0.30, -0.37, -0.41], [':', '--', ':']): pdf = scipy.stats.norm(scale, 0.19).pdf(Dgrid) pdf *= xmax / max(pdf) axP.plot(dP, pdf, ls=ls, color='purple') pscale = np.interp(scale, Dgrid, dP) ax.axvline(pscale, color='purple', ls=ls) ''' Raw data''' scale = 1. * pfm['dP'][nth].size / epos.multi['Pratio'].size weights = np.full(epos.multi['Pratio'].size, scale) axP.hist(epos.multi['Pratio'], bins=dP_bins, weights=weights, histtype='step', color='0.5', zorder=1) ''' Histogram Planet Size''' axR.set_yscale('log') axR.set_ylim(ax.get_ylim()) radius = np.geomspace(*ax.get_ylim(), num=15) axR.hist(pfm['R'][inner], bins=radius, orientation='horizontal', color='C1', label='Inner Planet') #helpers.set_axes(ax, epos, Trim=True) #helpers.set_axis_distance(axP, epos, Trim=True) ''' Linear regression ''' try: # data slope, intercept, r_value, p_value, std_err= \ scipy.stats.linregress(np.log(epos.multi['Pratio']), np.log(epos.multi['Rpair'])) ax.plot(dP, np.exp(intercept + slope * np.log(dP)), label='r={:.2f}'.format(r_value), marker='', ls='-', color='0.5') #print slope, intercept, r_value, p_value slope, intercept, r_value, p_value, std_err= \ scipy.stats.linregress(np.log(pfm['dP'][nth]), np.log(pfm['R'][nth])) ax.plot(dP, np.exp(intercept + slope * np.log(dP)), label='r={:.2f}'.format(r_value), marker='', ls='-', color=color) ax.legend(loc='lower right') except Exception as e: print(e) helpers.save(plt, epos.plotdir + 'model/Pratio-size')
x0=chains['x0'][maxlike], z=z, mwebv=float(mwebv)) # the errors passed in here are errors in the measured parameters. Best-fit taken from maximum likelihood sample sncosmo.plot_lc(emfit.data, model=model, errors=err, fname='./plots/emcee/jla/%s.pdf' % (nickname), color='black') if args.noskew: triangle_keys = ['mB', 'c', 't0', 'x1'] else: triangle_keys = ['mB', 'c', 's', 't0', 'x1'] helpers.save(chains, './chains/%s.chains' % (nickname)) # triangle plots emfit.plots(chains, nickname, triangle_keys, outdir='./plots/emcee/jla/triangle') except Exception as e: # as of final release of the code no JLA SNe fail the try except: # occasionally a simulated LC will fail, usually due to poor S/N traceback.print_exc() continue # output lcfit file outdir = os.path.abspath('./fit_results/emcee/JLA/%s' % (nickname)) if not os.path.exists(outdir):
import numpy import dmsh from helpers import assert_norm_equality, save def test_halfspace(show=False): geo = dmsh.Intersection([ dmsh.HalfSpace(numpy.sqrt(0.5) * numpy.array([1.0, 1.0]), 0.0), dmsh.Circle([0.0, 0.0], 1.0), ]) X, cells = dmsh.generate(geo, 0.1, show=show) ref_norms = [ 1.6445971629723411e02, 1.0032823867864321e01, 9.9962000746451751e-01 ] assert_norm_equality(X.flatten(), ref_norms, 1.0e-12) return X, cells if __name__ == "__main__": X, cells = test_halfspace(show=False) save("halfspace.png", X, cells)