def get_quake_desc(event,lat,lon,isMainEvent): ndeaths = event['TotalDeaths'] #summarize the exposure values exposures = np.array([event['MMI1'],event['MMI2'],event['MMI3'],event['MMI4'],event['MMI5'], event['MMI6'],event['MMI7'],event['MMI8'],event['MMI9+']]) exposures = np.array([round_to_nearest(exp,1000) for exp in exposures]) #get the highest two exposures greater than zero iexp = np.where(exposures > 0)[0][::-1] romans = ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX or greater'] if len(iexp) >= 2: exposures = [exposures[iexp[1]],exposures[iexp[0]]] ilevels = [romans[iexp[1]],romans[iexp[0]]] expfmt = ', with estimated population exposures of %s at intensity' expfmt = expfmt + ' %s and %s at intensity %s' exptxt = expfmt % (commify(int(exposures[0])),ilevels[0],commify(int(exposures[1])),ilevels[1]) else: exptxt = '' #create string describing this most impactful event dfmt = 'A magnitude %.1f earthquake %i km %s of this event struck %s on %s (UTC)%s' mag = event['Magnitude'] etime = event['Time'].strftime('%B %d, %Y') etime = re.sub(' 0',' ',etime) country = Country() if not event['Name']: if event['CountryCode'] == 'UM' and event['Latitude'] > 40: #hack for persistent error in expocat cdict = country.getCountryCode('US') else: cdict = country.getCountryCode(event['CountryCode']) if cdict: cname = cdict['Name'] else: cname = 'in the open ocean' else: cname = event['Name'].replace('"','') cdist = round(geodetic_distance(event['Lat'],event['Lon'],lat,lon)) cdir = get_compass_dir(lat,lon,event['Lat'],event['Lon'],format='long').lower() if ndeaths and str(ndeaths) != "nan": dfmt = dfmt + ', resulting in a reported %s %s.' if ndeaths > 1: dstr = 'fatalities' else: dstr = 'fatality' ndeathstr = commify(int(ndeaths)) eqdesc = dfmt % (mag,cdist,cdir,cname,etime,exptxt,ndeathstr,dstr) else: dfmt = dfmt + ', with no reported fatalities.' eqdesc = dfmt % (mag,cdist,cdir,cname,etime,exptxt) return eqdesc
def createDebrisTable(self): # values are in thousands wood = self._dataframe['DebrisW'].sum() / 1e3 steel = self._dataframe['DebrisS'].sum() / 1e3 wood_total = '%.3f' % wood steel_total = '%.3f' % steel debris_total = '%.3f' % (wood + steel) table_lines = [ '\\begin{tabularx}{\\barwidth}{l*{1}{>{\\raggedleft\\arraybackslash}X}}' ] table_lines.append('\\hline') table_lines.append('\\ & \\textbf{Tons} \\\\') table_lines.append('\\textbf{Category} & \\textbf{(millions)} \\\\') table_lines.append('\\hline') table_lines.append('Brick / Wood & %s \\\\' % wood_total) table_lines.append('Reinforced Concrete / Steel & %s \\\\' % steel_total) table_lines.append('\\textbf{Total} & \\textbf{%s} \\' % debris_total) table_lines.append('& \\\\') table_lines.append('& \\\\') trucks = commify(int(round(((wood + steel) * 1e6) / 25))) fmt = '\\textbf{Truck Loads (@25 tons/truck)} & \\textbf{%s} \\' line = fmt % trucks table_lines.append(line) table_lines.append('\\end{tabularx}') table_text = '\n'.join(table_lines) return table_text
def createDebrisTable(self): # values are in thousands wood = self._dataframe["DebrisW"].sum() / 1e3 steel = self._dataframe["DebrisS"].sum() / 1e3 wood_total = "%.3f" % wood steel_total = "%.3f" % steel debris_total = "%.3f" % (wood + steel) table_lines = [ "\\begin{tabularx}{\\barwidth}{l*{1}{>{\\raggedleft\\arraybackslash}X}}" ] table_lines.append("\\hline") table_lines.append("\\ & \\textbf{Tons} \\\\") table_lines.append("\\textbf{Category} & \\textbf{(millions)} \\\\") table_lines.append("\\hline") table_lines.append("Brick / Wood & %s \\\\" % wood_total) table_lines.append("Reinforced Concrete / Steel & %s \\\\" % steel_total) table_lines.append("\\textbf{Total} & \\textbf{%s} \\\\" % debris_total) table_lines.append("& \\\\") table_lines.append("& \\\\") trucks = commify(int(round(((wood + steel) * 1e6) / 25))) fmt = "\\textbf{Truck Loads (@25 tons/truck)} & \\textbf{%s} \\\\" line = fmt % trucks table_lines.append(line) table_lines.append("\\end{tabularx}") table_text = "\n".join(table_lines) return table_text
def format_city_table(cities): """Abbreviate a Pandas dataframe of city information Output should look like: MMI City Population IV Muisne 13,393 IV Rosa Zarate 42,121 III Pedernales 5,983 Input will a dataframe with columns: ccode iscap lat lon mmi name on_map pop :param cities: Pandas dataframe. :returns: String of city table info abbreviated for email delivery. """ #name, mmi,pop fmt = '{mmi:5s} {city:30s} {pop:<10s}\n' city_table = '' if len(cities): city_table += fmt.format(mmi='MMI', city='City', pop='Population') for idx, city in cities.iterrows(): mmiroman = dec_to_roman(city['mmi']) if city['pop'] == 0: citypop = '<1k' else: citypop = commify(city['pop']) city_table += fmt.format(mmi=mmiroman, city=city['name'], pop=citypop) #city_table = dedent(city_table) return city_table
def test(): print('Testing decimal to roman number conversion...') assert text.dec_to_roman(10) == 'X' print('Passed decimal to roman number conversion...') print('Testing setting number precision...') assert text.set_num_precision(7642, 2) == 7600 assert text.set_num_precision(321, 2) == 320 print('Passed setting number precision...') print('Testing rounding population value...') assert text.pop_round(7642) == '8,000' print('Passed rounding population value...') print('Testing rounding dollar value...') assert text.dollar_round(1.234e9, digits=2, mode='short') == '$1.2B' assert text.dollar_round(1.234e9, digits=2, mode='long') == '$1.2 billion' print('Passed rounding population value...') print('Testing abbreviating population value...') assert text.pop_round_short(1024125) == '1,024k' print('Passed abbreviating population value...') print('Testing rounding to nearest integer value...') assert text.round_to_nearest(998, round_value=1000) == 1000 assert text.round_to_nearest(78, round_value=100) == 100 print('Passed rounding population value...') print('Testing flooring to nearest integer value...') assert text.floor_to_nearest(1501, floor_value=1000) == 1000 assert text.floor_to_nearest(51, floor_value=100) == 0 print('Passed flooring population value...') print('Testing ceiling to nearest integer value...') assert text.ceil_to_nearest(1001, ceil_value=1000) == 2000 assert text.ceil_to_nearest(49, ceil_value=100) == 100 print('Passed ceiling population value...') print('Testing commify...') assert text.commify(1234567) == '1,234,567' print('Passed commify...') assert text.floor_to_nearest(0.56, floor_value=0.1) == 0.5 assert text.ceil_to_nearest(0.44, ceil_value=0.1) == 0.5 assert text.round_to_nearest(0.48, round_value=0.1) == 0.5 assert text.pop_round_short(125) == '125' assert text.pop_round_short(1.23e6, usemillion=True) == '1m' assert text.pop_round_short(0) == '0' assert text.dollar_round(1.23, digits=2, mode='short') == '$1' assert text.dollar_round(1.23e3, digits=2, mode='short') == '$1.2K' assert text.dollar_round(1.23e3, digits=2, mode='long') == '$1.2 thousand' assert text.dollar_round(1.23e6, digits=2, mode='short') == '$1.2M' assert text.dollar_round(1.23e6, digits=2, mode='long') == '$1.2 million' assert text.dec_to_roman(10) == 'X'
def test_historical(): clat = 0.37 clon = -79.94 expodict = {'EC': [0, 0, 115000, 5238000, 5971000, 2085000, 1760000, 103000, 0, 0], 'TotalExposure': [0, 0, 115000, 5238000, 5971000, 2085000, 1760000, 103000, 0, 0]} fatdict = {'EC': 98, 'TotalDeaths': 98} ccode = 'EC' histcomment = get_historical_comment(clat, clon, 7.8, expodict, fatdict) expocat = ExpoCat.fromDefault() minicat = expocat.selectByRadius(clat, clon, SEARCH_RADIUS) df = minicat.getDataFrame() df = df.sort_values( ['TotalDeaths', 'MaxMMI', 'NumMaxMMI'], ascending=False) assert histcomment.find(commify(int(df.iloc[0]['TotalDeaths']))) > -1
def get_quake_desc(event, lat, lon, isMainEvent): ndeaths = event["TotalDeaths"] # summarize the exposure values exposures = np.array([ event["MMI1"], event["MMI2"], event["MMI3"], event["MMI4"], event["MMI5"], event["MMI6"], event["MMI7"], event["MMI8"], event["MMI9+"], ]) exposures = np.array([round_to_nearest(exp, 1000) for exp in exposures]) # get the highest two exposures greater than zero iexp = np.where(exposures > 0)[0][::-1] romans = [ "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX or greater" ] if len(iexp) >= 2: exposures = [exposures[iexp[1]], exposures[iexp[0]]] ilevels = [romans[iexp[1]], romans[iexp[0]]] expfmt = ", with estimated population exposures of %s at intensity" expfmt = expfmt + " %s and %s at intensity %s" exptxt = expfmt % ( commify(int(exposures[0])), ilevels[0], commify(int(exposures[1])), ilevels[1], ) else: exptxt = "" # create string describing this most impactful event dfmt = "A magnitude %.1f earthquake %i km %s of this event struck %s on %s (UTC)%s" mag = event["Magnitude"] etime = pd.Timestamp(event["Time"]) etime = etime.strftime("%B %d, %Y") etime = re.sub(" 0", " ", etime) country = Country() if pd.isnull(event["Name"]): # hack for persistent error in expocat if event["CountryCode"] == "UM" and event["Lat"] > 40: cdict = country.getCountry("US") else: cdict = country.getCountry(event["CountryCode"]) if cdict: cname = cdict["Name"] else: cname = "in the open ocean" else: cname = event["Name"].replace('"', "") cdist = round(geodetic_distance(event["Lat"], event["Lon"], lat, lon)) cdir = get_compass_dir(lat, lon, event["Lat"], event["Lon"], format="long").lower() if ndeaths and str(ndeaths) != "nan": dfmt = dfmt + ", resulting in a reported %s %s." if ndeaths > 1: dstr = "fatalities" else: dstr = "fatality" ndeathstr = commify(int(ndeaths)) eqdesc = dfmt % (mag, cdist, cdir, cname, etime, exptxt, ndeathstr, dstr) else: dfmt = dfmt + ", with no reported fatalities." eqdesc = dfmt % (mag, cdist, cdir, cname, etime, exptxt) return eqdesc