from pathlib import Path from hashlib import sha256 from io import BytesIO import json import requests import pandas as pd import numpy as np import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from openpyxl import load_workbook from PIL import Image,ImageOps HERE=Path(__file__).resolve().parent CHARTS=HERE/"charts" CHARTS.mkdir(exist_ok=True) SOURCE="https://ohss.dhs.gov/system/files/2026-06/2026_0604_ohss_yearbook_lawful_permanent_residents_fy2024.xlsx" YEARBOOK="https://ohss.dhs.gov/topics/immigration/yearbook/2024" EXPECTED_HASH="19c500a6e6445e73c0a39c5bc382585e2a13fc8f52f6e4d9a3cf6a84bf9bab6a" rows={8:"All recipients",9:"Immediate relatives",10:"Spouses",11:"Children",12:"Parents", 13:"Family preferences",14:"Family first",15:"Family second",16:"Family third",17:"Family fourth", 18:"Employment preferences",19:"Employment first",20:"Employment second",21:"Employment third", 22:"Employment fourth",23:"Employment fifth",24:"Diversity",25:"Refugees",26:"Asylees", 27:"Parolees",28:"Children born abroad",29:"Certain Iraqis and Afghans",30:"Cancellation of removal", 31:"Human trafficking victims",32:"Crime victims and relatives",33:"Other"} input_path=next(Path("data/launch_verification/launch_dhs_lpr_2024_yearbook").glob("*.xlsx"),None) if input_path: binary=input_path.read_bytes() else: response=requests.get(SOURCE,timeout=30);response.raise_for_status();binary=response.content assert sha256(binary).hexdigest()==EXPECTED_HASH book=load_workbook(BytesIO(binary),read_only=True,data_only=True) table=list(book["Table 6"].values) records=[] for row,label in rows.items(): for j,end_year in enumerate(range(2015,2025),1): sum_count,adj,new=(table[row+k-1][j] for k in (0,27,54)) assert all(isinstance(v,int) for v in (sum_count,adj,new)) assert abs(sum_count-adj-new)<=10 records.append({"class":label,"fiscal_year":end_year,"all_recipients":sum_count, "adjustments":adj,"new_arrivals":new, "adjustment_pct":(100*adj/sum_count) if sum_count else None}) data=pd.DataFrame(records) data.to_csv(HERE/"table-6-extract.csv",index=False) scale=1000 FILL="#fdf6f5"; INK="#3a2933"; WINE="#864653"; BLUE="#316e7b"; GOLD="#aa7539" plan=[] def make(title, y_label, note): fig,ax=plt.subplots(figsize=(10.7,5.9),dpi=150,facecolor=FILL) fig.subplots_adjust(left=.13,right=.96,top=.81,bottom=.20) fig.text(.13,.92,title,fontweight="bold",fontsize=18,color=INK) fig.text(.13,.055,"DHS Office of Homeland Security Statistics · "+note,fontsize=9,color="#5f4955") ax.set_facecolor(FILL) ax.set_ylabel(y_label,color=INK) ax.tick_params(colors=INK,labelsize=10,length=0) ax.spines[["top","right","left"]].set_visible(False) ax.spines["bottom"].set_color("#c8b3bd") ax.grid(axis="y",alpha=.25) ax.set_axisbelow(True) return fig,ax def export(num,fig,values,title,question,period,pop,unit,takeaway): png=f"charts/chart-{num}.png"; csv=f"charts/chart-{num}.csv" values.to_csv(HERE/csv,index=False,float_format="%.10g") fig.savefig(HERE/png,facecolor=FILL) plt.close(fig) plan.append({"asset":png,"data":csv,"title":title,"question":question,"source":SOURCE, "population":pop,"period":period,"unit":unit,"takeaway":takeaway}) all_years=data.loc[data["class"].eq("All recipients")].copy() period_full="Federal fiscal years 2015–2024" pop_all="People obtaining lawful permanent resident status in the OHSS yearbook" fig,ax=make("Adjustments drove most of the fiscal 2024 increase","People, thousands","Persons obtaining lawful permanent residence · Counts rounded by OHSS") ax.bar(all_years.fiscal_year,all_years.adjustments/scale,color=WINE,label="Adjustments of status") ax.bar(all_years.fiscal_year,all_years.new_arrivals/scale,bottom=all_years.adjustments/scale,color=BLUE,label="New arrivals") ax.legend(loc="upper left",frameon=False) ax.set_xticks(all_years.fiscal_year) export("01-yearly-totals",fig,all_years,"Adjustments drove most of the fiscal 2024 increase","How large was each pathway in every year of the decade?",period_full,pop_all,"People","Adjustments grew by about 174,540 people in fiscal 2024 and new arrivals by about 16,630.") fig,ax=make("Fiscal 2021 had the highest adjustment share","Adjustment share, %","Adjustment counts divided by all grants · Rounded source figures") ax.axhline(50,color="#98828e",linewidth=1) ax.plot(all_years.fiscal_year,all_years.adjustment_pct,linewidth=2.3,marker="o",color=WINE) ax.set_ylim(42,75) ax.set_xticks(all_years.fiscal_year) for row in all_years.loc[all_years.fiscal_year.isin([2016,2019,2021,2023,2024])].itertuples(): ax.annotate(f"{row.adjustment_pct:.1f}%",(row.fiscal_year,row.adjustment_pct),xytext=(0,9),ha="center",textcoords="offset points",fontsize=9) export("02-pathway-share",fig,all_years,"Fiscal 2021 had the highest adjustment share","When did adjustments make up the largest fraction of new LPR grants?",period_full,pop_all,"Percent of persons obtaining LPR status","The 2021 share approached 70%, while the fiscal 2024 share was 57.4%.") major=["Immediate relatives","Family preferences","Employment preferences","Diversity","Refugees","Asylees","Certain Iraqis and Afghans"] deltas=(data.loc[data["class"].isin(major)].pivot(index="class",columns="fiscal_year",values="all_recipients") .reindex(major).reset_index()[["class",2023,2024]].rename(columns={2023:"FY2023",2024:"FY2024"})) deltas["delta"]=deltas.FY2024-deltas.FY2023 remainder=int(all_years.iloc[-1].all_recipients-all_years.iloc[-2].all_recipients-deltas.delta.sum()) deltas=pd.concat([deltas,pd.DataFrame([{"class":"Other / rounding","FY2023":int(all_years.iloc[-2].all_recipients-deltas.FY2023.sum()),"FY2024":int(all_years.iloc[-1].all_recipients-deltas.FY2024.sum()),"delta":remainder}])],ignore_index=True) fig,ax=make("Immediate relatives and refugees led the net change","","Selected broad classes and residual · Counts rounded by OHSS") fig.subplots_adjust(left=.28) deltas=deltas.sort_values("delta") ax.barh(deltas["class"],deltas.delta/scale,color=[BLUE if x<0 else WINE for x in deltas.delta]) ax.axvline(0,color="#8f7b85",linewidth=.8) ax.set_xlabel("Change in people receiving permanent residence, thousands") export("03-change-by-class",fig,deltas,"Immediate relatives and refugees led the net change", "Which non-overlapping broad categories contributed to or offset the net gain from FY2023 to FY2024?", "Fiscal 2023 to fiscal 2024",pop_all,"Change in people","Immediate relatives and refugees added nearly 240,000 combined before offsets.") compare=["Immediate relatives","Family preferences","Employment preferences","Diversity","Refugees","Asylees","Certain Iraqis and Afghans"] latest=data.loc[data.fiscal_year.eq(2024)&data["class"].isin(compare)].sort_values("adjustment_pct") fig,ax=make("The route differed sharply across admission classes","","Published adjustment count divided by the class total") fig.subplots_adjust(left=.29) ax.barh(latest["class"],latest.adjustment_pct,color=WINE) ax.set_xlim(0,115);ax.set_xlabel("Adjustment share of class, %") for i,n in enumerate(latest.adjustment_pct):ax.text(n+2,i,f"{n:.1f}%",va="center",fontsize=9) export("04-class-route-shares",fig,latest,"The route differed sharply across admission classes", "In FY2024, what share of each class had adjustment recorded?", "Fiscal 2024",pop_all,"Percent of grants in class","Over 69% of employment preferences were adjustments, compared with 5.5% of family preferences.") family=data.loc[data["class"].isin(["Spouses","Children","Parents"])&data.fiscal_year.isin([2023,2024])].pivot(index="class",columns="fiscal_year",values=["adjustments","new_arrivals"]) vals=[] for name in ["Spouses","Children","Parents"]: for route in ["adjustments","new_arrivals"]: vals.append({"class":name,"route":route,"FY2023":family.loc[name,(route,2023)],"FY2024":family.loc[name,(route,2024)]}) growth=pd.DataFrame(vals) growth["delta"]=growth.FY2024-growth.FY2023 fig,ax=make("Spouses and parents led the immediate-relative gains","Change in people, thousands","Immediate-relatives classes only · Child figures include orphans") for shift,route,color,label in [(-.17,"adjustments",WINE,"Adjustments"),(.17,"new_arrivals",BLUE,"New arrivals")]: xx=growth.loc[growth.route.eq(route)] ax.bar(np.arange(len(xx))+shift,xx.delta/scale,.31,color=color,label=label) ax.set_xticks([0,1,2],["Spouses","Children","Parents"]) ax.legend(loc="upper right",frameon=False) export("05-immediate-family-growth",fig,growth,"Spouses and parents led the immediate-relative gains", "How did gains differ by relationship and route within the immediate-relative group?", "Fiscal 2023 to fiscal 2024","Immediate relatives of U.S. citizens obtaining LPR status","Change in people","Spouses added over 53,000 adjustments, more than any other immediate-relative relationship.") preference=data.loc[data["class"].isin(["Family first","Family second","Family third","Family fourth"])&data.fiscal_year.between(2019,2024)].copy() fig,ax=make("Second-preference new arrivals had the largest recent swing","New arrivals, thousands","Family preference classes, separate from immediate relatives") for label,color,marker in [("Family first",GOLD,"o"),("Family second",WINE,"o"),("Family third","#795b86","^"),("Family fourth",BLUE,"s")]: xx=preference.loc[preference["class"].eq(label)] ax.plot(xx.fiscal_year,xx.new_arrivals/scale,label=label,color=color,marker=marker,linewidth=2) ax.set_xticks(range(2019,2025)) ax.legend(ncol=2,loc="upper left",frameon=False,fontsize=9) export("06-family-preference",fig,preference,"Second-preference new arrivals had the largest recent swing", "Which of the four family-preference classes experienced the largest change in new arrivals from FY2023 to FY2024?", "Fiscal 2019–2024","People granted LPR status under family-sponsored preferences by class","New arrivals", "Family second-preference new arrivals fell from about 110,860 to 83,410.") emp=data.loc[data["class"].eq("Employment preferences")].copy() fig,ax=make("Employment adjustments rose and fell much faster","People, thousands","Employment-based preferences only · Counts rounded to nearest ten") for col,color,label in [("adjustments",WINE,"Adjustments"),("new_arrivals",BLUE,"New arrivals")]: ax.plot(emp.fiscal_year,emp[col]/scale,marker="o",color=color,linewidth=2.3,label=label) ax.set_xticks(emp.fiscal_year) ax.legend(loc="upper left",frameon=False) export("07-employment-paths",fig,emp,"Employment adjustments rose and fell much faster", "Which route explains the rise and subsequent decline in employment-based preference grants?", period_full,"Employment-based preferences in the OHSS yearbook","People","Adjustments fell from about 221,370 in FY2022 to 118,410 in FY2024, while new arrivals increased.") jobgroup=data.loc[data["class"].isin(["Employment first","Employment second","Employment third","Employment fourth","Employment fifth"])&data.fiscal_year.eq(2024)].copy() fig,ax=make("Employment preferences varied by subcategory","","FY2024 · Published totals can differ slightly from sums of rounded pathways") fig.subplots_adjust(left=.24) ax.barh(jobgroup["class"],jobgroup.adjustments/scale,color=WINE,label="Adjustments") ax.barh(jobgroup["class"],jobgroup.new_arrivals/scale,left=jobgroup.adjustments/scale,color=BLUE,label="New arrivals") ax.set_xlabel("People granted permanent residence, thousands") ax.legend(loc="lower center",bbox_to_anchor=(.52,1.01),ncol=2,frameon=False) export("08-employment-subtypes",fig,jobgroup,"Employment preferences varied by subcategory", "How did the direction and magnitude of the route split differ across employment preference classes?", "Fiscal 2024","Employment preference recipients by the five published subcategories","People", "The first preference was predominantly adjustments, while most fifth-preference grants were new arrivals.") cases=data.loc[data["class"].isin(["Refugees","Asylees"])].copy() fig,ax=make("Refugee adjustments drove the largest humanitarian change","Adjustments, thousands", "Year of lawful permanent residence · Not refugee arrival or asylum grant year") for label,color in [("Refugees",WINE),("Asylees",BLUE)]: xx=cases.loc[cases["class"].eq(label)] ax.plot(xx.fiscal_year,xx.adjustments/scale,label=label,color=color,linewidth=2.5,marker="o") ax.set_xticks(range(2015,2025)); ax.legend(frameon=False,loc="upper left") export("09-humanitarian-adjustments",fig,cases,"Refugee adjustments drove the largest humanitarian change", "How did green-card adjustments in the refugee and asylee classes move over the decade?", period_full,"People obtaining LPR status in OHSS refugee and asylee classes","People", "Refugee-class adjustments increased by about 119,170 in fiscal 2024, alongside a much smaller change for asylees.") counter=all_years[["fiscal_year","all_recipients"]].copy() ref=data.loc[data["class"].eq("Refugees"),["fiscal_year","all_recipients"]].rename(columns={"all_recipients":"refugee_class"}) counter=counter.merge(ref,on="fiscal_year",validate="one_to_one") counter["excluding_refugee_class"]=counter.all_recipients-counter.refugee_class counter=counter.loc[counter.fiscal_year.between(2020,2024)] fig,ax=make("The grant series still rises without the refugee class","People, thousands", "Analytical comparison · Published total minus the refugee class") for col,color,label in [("all_recipients",WINE,"Published total"),("excluding_refugee_class",BLUE,"Total excluding refugee class")]: ax.plot(counter.fiscal_year,counter[col]/scale,marker="o",color=color,linewidth=2.3,label=label) ax.set_xticks(counter.fiscal_year) ax.legend(frameon=False,loc="upper left") export("10-refugee-sensitivity",fig,counter,"The grant series still rises without the refugee class", "How much would the upward trend change if the refugee adjustment class were left out of both endpoints?", "Fiscal 2020–2024",pop_all,"People","In the 2023–2024 step, the difference falls to about 72,010 after excluding the refugee class.") (HERE/"CHART-PLAN.json").write_text(json.dumps(plan,indent=2,ensure_ascii=False)+"\n",encoding="utf-8") (HERE/"evidence.json").write_text(json.dumps({"source":SOURCE,"sha256":EXPECTED_HASH,"workbook_sheet":"Table 6", "rounding":"Nearest 10 persons as published","total_rows":len(data),"fiscal_years":[2015,2024], "release_access":"Working workbook verified in D: source manifest"},indent=2)+"\n",encoding="utf-8") print(all_years.to_string(index=False)); print(deltas.to_string(index=False)); print(latest.to_string(index=False)) print(growth.to_string(index=False));print(preference[preference.fiscal_year.isin([2023,2024])].to_string(index=False)) print(counter.to_string(index=False)) URL="https://upload.wikimedia.org/wikipedia/commons/1/17/Embassy_of_the_United_States_of_America_-_London_%2851792911775%29.jpg" if not (HERE/"HERO.json").exists(): r=requests.get(URL,headers={"User-Agent":"VisaAndEntryEditorial/1.0 (https://visaandentry.com/)"},timeout=30) r.raise_for_status() with Image.open(BytesIO(r.content)) as im: im=ImageOps.exif_transpose(im).convert("RGB") assert im.width>1570 and im.height>900 im.thumbnail((1500,1100),Image.Resampling.LANCZOS) im.save(HERE/"hero.webp",format="WEBP",quality=86,method=6) h={"title":"U.S. Embassy in London","alt":"An American flag hangs outside the U.S. Embassy in London, beside a geometric metallic facade.", "caption":"The U.S. Embassy in London in 2021. The building illustrates the consular route; the yearbook covers nationwide grants and worldwide immigrant arrivals.", "credit":"Mark Wordy via Flickr and Wikimedia Commons","source_url":"https://commons.wikimedia.org/wiki/File:Embassy_of_the_United_States_of_America_-_London_(51792911775).jpg", "license":"CC BY 2.0","license_url":"https://creativecommons.org/licenses/by/2.0/","original_url":URL,"original_sha256":sha256(r.content).hexdigest(), "processing":"Resized to 1500 pixels wide without cropping and converted to WebP. Derived copy CC BY 2.0.","asset_type":"Photo"} (HERE/"HERO.json").write_text(json.dumps(h,ensure_ascii=False,indent=2)+"\n",encoding="utf-8")