def createEconTable(self): table_lines = [ '\\begin{tabularx}{\\barwidth}{lc*{1}{>{\\raggedleft\\arraybackslash}X}}' ] table_lines.append('\\hline') table_lines.append( '\\textbf{County} & \\textbf{State} & \\textbf{Total (\\textdollar M)} \\\\' ) table_lines.append('\\hline') total = self._dataframe['EconLoss'].sum() ntotal = len(self._dataframe) for i in range(0, self._ncounties): row = self._dataframe.iloc[i] fips = int(row['CountyFips']) county_name, state_abbrev = self._county_dict[fips] loss_str = pop_round_short(row['EconLoss'])[0:-1] line = '%s & %s & %s \\\\' % (county_name, state_abbrev, loss_str) table_lines.append(line) fmt = '\\multicolumn{2}{l}{\\textbf{Total (%i counties)}} & \\multicolumn{1}{>{\\raggedleft}X}{\\textbf{%s}} \\\\' line = fmt % (ntotal, pop_round_short(total)[0:-1]) table_lines.append(line) table_lines.append('\\hline') table_lines.append('\\end{tabularx}') table_text = '\n'.join(table_lines) return table_text
def createInjuryTable(self): pop_total = pop_round_short(self._dataframe['Population'].sum()) injured_total = pop_round_short(self._dataframe['NonFatal5p'].sum()) table_lines = [ '\\begin{tabularx}{\\barwidth}{lc*{2}{>{\\raggedleft\\arraybackslash}X}}' ] table_lines.append('\\hline') table_lines.append( '\\textbf{County} & \\textbf{State} & \\textbf{Population} & \\textbf{Total NFI} \\\\' ) table_lines.append('\\hline') ncounties = len(self._dataframe) for i in range(0, self._ncounties): row = self._dataframe.iloc[i] fips = int(row['CountyFips']) county_name, state_abbrev = self._county_dict[fips] pop = pop_round_short(row['Population']) injuries = pop_round_short(row['NonFatal5p']) fmt = '%s & %s & %s & %s \\\\' line = fmt % (county_name, state_abbrev, pop, injuries) table_lines.append(line) fmt = '\\multicolumn{2}{l}{\\textbf{Total (%i counties)}} & \\multicolumn{1}{>{\\raggedleft}X}{\\textbf{%s}} & \\multicolumn{1}{>{\\raggedleft}X}{\\textbf{%s}} \\\\' line = fmt % (ncounties, pop_total, injured_total) table_lines.append(line) table_lines.append('\\hline') table_lines.append('\\end{tabularx}') table_text = '\n'.join(table_lines) return table_text
def format_earthquakes(histquakes): # distance,date,magnitude,maxmmi,maxmmiexp,deaths default = 'There were no earthquakes with significant population exposure to shaking within a 400 km radius of this event.' if histquakes[0] is None: return default tablestr = '' hdr = '{date:16s} {dist:10s} {mag:8s} {mmi:10s} {deaths:14s}\n' hdr = hdr.format(date='Date (UTC)', dist='Dist. (km)', mag='Mag.', mmi='Max MMI(#)', deaths='Shaking Deaths') tablestr += hdr fmt = '{date:16s} {dist:10d} {mag:4.1f} {mmi:10s} {deaths:14s}\n' for histquake in histquakes: eqtime = datetime.strptime(histquake['Time'], '%Y-%m-%d %H:%M:%S') datestr = eqtime.strftime(DATE_FMT) mmistr = '{}({})'.format(dec_to_roman(histquake['MaxMMI']), pop_round_short(histquake['NumMaxMMI'])) if histquake['TotalDeaths'] is None or np.isnan( histquake['TotalDeaths']): death_str = '-' else: death_str = pop_round_short(histquake['TotalDeaths']) line = fmt.format(date=datestr, dist=int(histquake['Distance']), mag=histquake['Magnitude'], mmi=mmistr, deaths=death_str) tablestr += line return tablestr
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 create_tag_table(self, tag_dict, title): table_lines = ['\\begin{tabularx}{3.4cm}{lr}'] table_lines.append('& \\\\') table_lines.append('\\multicolumn{2}{c}{\\textbf{%s}} \\\\' % title) table_lines.append('\\textbf{Occupancy} & \\textbf{\\# of tags} \\\\') for key, value in tag_dict.items(): line = '%s & %s \\\\' % (key, pop_round_short(value)) table_lines.append(line) table_lines.append('\\end{tabularx}') table_text = '\n'.join(table_lines) return table_text
def create_tag_table(self, tag_dict, title): table_lines = ["\\begin{tabularx}{3.4cm}{lr}"] table_lines.append("& \\\\") table_lines.append("\\multicolumn{2}{c}{\\textbf{%s}} \\\\" % title) table_lines.append("\\textbf{Occupancy} & \\textbf{\\# of tags} \\\\") for key, value in tag_dict.items(): line = "%s & %s \\\\" % (key, pop_round_short(value)) table_lines.append(line) table_lines.append("\\end{tabularx}") table_text = "\n".join(table_lines) return table_text
def format_earthquakes(histquakes): #distance,date,magnitude,maxmmi,maxmmiexp,deaths tablestr = '' hdr = '{date:16s} {dist:10s} {mag:4s} {mmi:10s} {deaths:14s}\n' hdr = hdr.format(date='Date (UTC)', dist='Dist. (km)', mag='Mag.', mmi='Max MMI(#)', deaths='Shaking Deaths') tablestr += hdr fmt = '{date:16s} {dist:10d} {mag:4.1f} {mmi:10s} {deaths:14s}\n' for histquake in histquakes: datestr = histquake['date'].strftime(DATEFMT) mmistr = '{}({})'.format(dec_to_roman(histquake['maxmmi']), pop_round_short(histquake['maxmmiexp'])) line = fmt.format(date=datestr, dist=int(histquake['distance']), mag=histquake['magnitude'], mmi=mmistr, deaths=pop_round_short(histquake['deaths'])) tablestr += line return tablestr
def createShelterTable(self): house_total = pop_round_short(self._dataframe['Households'].sum()) displaced_total = pop_round_short(self._dataframe['DisplHouse'].sum()) shelter_total = pop_round_short(self._dataframe['Shelter'].sum()) ncounties = len(self._dataframe) table_lines = [ '\\begin{tabularx}{\\barwidth}{lc*{3}{>{\\raggedleft\\arraybackslash}X}}' ] table_lines.append('\\hline') table_lines.append( '\\ & & \\textbf{Total} & \\textbf{Displ} & \\textbf{People} \\\\' ) table_lines.append( '\\ & & \\textbf{House-} & \\textbf{House-} & \\textbf{Needing} \\\\' ) table_lines.append( '\\textbf{County} & \\textbf{State} & \\textbf{holds} & \\textbf{holds} & \\textbf{Shelter} \\\\' ) table_lines.append('\\hline') for i in range(0, self._ncounties): row = self._dataframe.iloc[i] fips = int(row['CountyFips']) county_name, state_abbrev = self._county_dict[fips] households = pop_round_short(row['Households']) displaced = pop_round_short(row['DisplHouse']) shelter = pop_round_short(row['Shelter']) fmt = '%s & %s & %s & %s & %s \\\\' line = fmt % (county_name, state_abbrev, households, displaced, shelter) table_lines.append(line) fmt = '\\multicolumn{2}{l}{\\textbf{Total (%i counties)}} & \\multicolumn{1}{>{\\raggedleft}X}{\\textbf{%s}} & \\multicolumn{1}{>{\\raggedleft}X}{\\textbf{%s}} & \\multicolumn{1}{>{\\raggedleft}X}{\\textbf{%s}} \\\\' line = fmt % (ncounties, house_total, displaced_total, shelter_total) table_lines.append(line) table_lines.append('\\hline') table_lines.append('\\end{tabularx}') table_text = '\n'.join(table_lines) return table_text
def createShelterTable(self): house_total = pop_round_short(self._dataframe["Households"].sum()) displaced_total = pop_round_short(self._dataframe["DisplHouse"].sum()) shelter_total = pop_round_short(self._dataframe["Shelter"].sum()) ncounties = len(self._dataframe) table_lines = [ "\\begin{tabularx}{\\barwidth}{lc*{3}{>{\\raggedleft\\arraybackslash}X}}" ] table_lines.append("\\hline") table_lines.append( "\\ & & \\textbf{Total} & \\textbf{Displ} & \\textbf{Total} \\\\" ) table_lines.append( "\\ & & \\textbf{House} & \\textbf{House} & \\textbf{People} \\\\" ) table_lines.append( "\\textbf{County} & \\textbf{State} & \\textbf{holds} & \\textbf{holds} & \\\\" ) table_lines.append("\\hline") for i in range(0, self._ncounties): row = self._dataframe.iloc[i] fips = int(row["CountyFips"]) county_name, state_abbrev = self._county_dict[fips] households = pop_round_short(row["Households"]) displaced = pop_round_short(row["DisplHouse"]) shelter = pop_round_short(row["Shelter"]) fmt = "\\truncate{2.4cm}{%s} & %s & %s & %s & %s \\\\" line = fmt % (county_name, state_abbrev, households, displaced, shelter) table_lines.append(line) fmt = "\\multicolumn{2}{l}{\\textbf{Total (%i counties)}} & \\multicolumn{1}{>{\\raggedleft}X}{\\textbf{%s}} & \\multicolumn{1}{>{\\raggedleft}X}{\\textbf{%s}} & \\multicolumn{1}{>{\\raggedleft}X}{\\textbf{%s}} \\\\" line = fmt % (ncounties, house_total, displaced_total, shelter_total) table_lines.append(line) table_lines.append("\\hline") table_lines.append("\\end{tabularx}") table_text = "\n".join(table_lines) return table_text
def create_onepager(pdata, version_dir, debug=False): """ :param pdata: PagerData object. :param version_dir: Path of event version directory. :param debug: bool for whether or not to add textpos boxes to onepager. """ #--------------------------------------------------------------------------- # Sort out some paths #--------------------------------------------------------------------------- # Locaiton of this module mod_dir, dummy = os.path.split(__file__) # losspager package direcotry losspager_dir = os.path.join(mod_dir, '..') # Repository root directory root_dir = os.path.join(losspager_dir, '..') # Data directory data_dir = os.path.join(losspager_dir, 'data') # Onepager latex template file template_file = os.path.join(data_dir, 'onepager2.tex') #--------------------------------------------------------------------------- # Read in pager data and latex template #--------------------------------------------------------------------------- json_dir = os.path.join(version_dir, 'json') pdict = pdata._pagerdict edict = pdata.getEventInfo() with open(template_file, 'r') as f: template = f.read() #--------------------------------------------------------------------------- # Fill in template values #--------------------------------------------------------------------------- # Sort out origin time olat = edict['lat'] olon = edict['lon'] otime_utc = edict['time'] date_utc = datetime.strptime(otime_utc, "%Y-%m-%d %H:%M:%S") date_local = pdata.local_time DoW = date_local.strftime('%a') otime_local = date_local.strftime('%H:%M:%S') otime_local = DoW + ' ' + otime_local template = template.replace("[ORIGTIME]", otime_utc) template = template.replace("[LOCALTIME]", otime_local) # Some paths template = template.replace("[VERSIONFOLDER]", version_dir) template = template.replace("[HOMEDIR]", root_dir) # Magnitude location string under USGS logo magloc = 'M %.1f, %s' % (edict['mag'], texify(edict['location'])) template = template.replace("[MAGLOC]", magloc) # Pager version ver = "Version " + str(pdict['pager']['version_number']) template = template.replace("[VERSION]", ver) template = template.replace("[VERSIONX]", "2.5") # Epicenter location lat = edict['lat'] lon = edict['lon'] dep = edict['depth'] if lat > 0: hlat = "N" else: hlat = "S" if lon > 0: hlon = "E" else: hlon = "W" template = template.replace("[LAT]", '%.4f' % abs(lat)) template = template.replace("[LON]", '%.4f' % abs(lon)) template = template.replace("[HEMILAT]", hlat) template = template.replace("[HEMILON]", hlon) template = template.replace("[DEPTH]", '%.1f' % dep) # Tsunami warning? --- need to fix to be a function of tsunamic flag if edict['tsunami']: template = template.replace( "[TSUNAMI]", "FOR TSUNAMI INFORMATION, SEE: tsunami.gov") else: template = template.replace("[TSUNAMI]", "") if pdata.isScenario(): elapse = '' else: elapse = "Created: " + pdict['pager'][ 'elapsed_time'] + " after earthquake" template = template.replace("[ELAPSED]", elapse) template = template.replace("[IMPACT1]", texify(pdict['comments']['impact1'])) template = template.replace("[IMPACT2]", texify(pdict['comments']['impact2'])) template = template.replace("[STRUCTCOMMENT]", texify(pdict['comments']['struct_comment'])) # Summary alert color template = template.replace("[SUMMARYCOLOR]", pdata.summary_alert.capitalize()) template = template.replace("[ALERTFILL]", pdata.summary_alert) # fill in exposure values max_border_mmi = pdata._pagerdict['population_exposure'][ 'maximum_border_mmi'] explist = pdata.getTotalExposure() pophold = 0 for mmi in range(1, 11): iexp = mmi - 1 if mmi == 2: pophold += explist[iexp] continue elif mmi == 3: pop = explist[iexp] + pophold macro = '[MMI2-3]' else: pop = explist[iexp] macro = '[MMI%i]' % mmi if pop < 1000: pop = round_to_nearest(pop, round_value=1000) if max_border_mmi > mmi and mmi <= 4: if pop == 0: popstr = '--*' else: if pop < 1000: pop = round_to_nearest(pop, round_value=1000) popstr = pop_round_short(pop) + '*' else: popstr = pop_round_short(pop) template = template.replace(macro, popstr) # MMI color pal pal = ColorPalette.fromPreset('mmi') # Historical table htab = pdata.getHistoricalTable() if htab[0] is None: # use pdata.getHistoricalComment() htex = pdata.getHistoricalComment() else: # build latex table htex = """ \\begin{tabularx}{7.25cm}{lrc*{1}{>{\\centering\\arraybackslash}X}*{1}{>{\\raggedleft\\arraybackslash}X}} \hline \\textbf{Date} &\\textbf{Dist.}&\\textbf{Mag.}&\\textbf{Max} &\\textbf{Shaking}\\\\ \\textbf{(UTC)}&\\textbf{(km)} & &\\textbf{MMI(\#)}&\\textbf{Deaths} \\\\ \hline [TABLEDATA] \hline \multicolumn{5}{p{7.2cm}}{\\small [COMMENT]} \end{tabularx}""" comment = pdata._pagerdict['comments']['secondary_comment'] htex = htex.replace("[COMMENT]", texify(comment)) tabledata = "" nrows = len(htab) for i in range(nrows): date = htab[i]['Time'].split()[0] dist = str(int(htab[i]['Distance'])) mag = str(htab[i]['Magnitude']) mmi = dec_to_roman(np.round(htab[i]['MaxMMI'], 0)) col = pal.getDataColor(htab[i]['MaxMMI']) texcol = "%s,%s,%s" % (col[0], col[1], col[2]) nmmi = pop_round_short(htab[i]['NumMaxMMI']) mmicell = '%s(%s)' % (mmi, nmmi) shakedeath = htab[i]['ShakingDeaths'] if np.isnan(shakedeath): death = "--" else: death = pop_round_short(shakedeath) row = '%s & %s & %s & \cellcolor[rgb]{%s} %s & %s \\\\ '\ '\n' %(date, dist, mag, texcol, mmicell, death) tabledata = tabledata + row htex = htex.replace("[TABLEDATA]", tabledata) template = template.replace("[HISTORICAL_BLOCK]", htex) # City table ctex = """ \\begin{tabularx}{7.25cm}{lXr} \hline \\textbf{MMI} & \\textbf{City} & \\textbf{Population} \\\\ \hline [TABLEDATA] \hline \end{tabularx}""" ctab = pdata.getCityTable() nrows = len(ctab.index) tabledata = "" for i in range(nrows): mmi = dec_to_roman(np.round(ctab['mmi'].iloc[i], 0)) city = ctab['name'].iloc[i] if ctab['pop'].iloc[i] == 0: pop = '$<$1k' else: if ctab['pop'].iloc[i] < 1000: popnum = round_to_nearest(ctab['pop'].iloc[i], round_value=1000) else: popnum = ctab['pop'].iloc[i] pop = pop_round_short(popnum) col = pal.getDataColor(ctab['mmi'].iloc[i]) texcol = "%s,%s,%s" % (col[0], col[1], col[2]) if ctab['on_map'].iloc[i] == 1: if ctab['pop'].iloc[i] == 0: pop = '\\boldmath$<$\\textbf{1k}' row = '\\rowcolor[rgb]{%s}\\textbf{%s} & \\textbf{%s} & '\ '%s\\\\ \n' %(texcol, mmi, city, pop) else: row = '\\rowcolor[rgb]{%s}\\textbf{%s} & \\textbf{%s} & '\ '\\textbf{%s}\\\\ \n' %(texcol, mmi, city, pop) else: row = '\\rowcolor[rgb]{%s}%s & %s & '\ '%s\\\\ \n' %(texcol, mmi, city, pop) tabledata = tabledata + row ctex = ctex.replace("[TABLEDATA]", tabledata) template = template.replace("[CITYTABLE]", ctex) eventid = edict['eventid'] # query ComCat for information about this event # fill in the url, if we can find it try: ccinfo = ComCatInfo(eventid) eventid, allids = ccinfo.getAssociatedIds() event_url = ccinfo.getURL() + '#pager' except: event_url = DEFAULT_PAGER_URL eventid = "Event ID: " + eventid template = template.replace("[EVENTID]", texify(eventid)) template = template.replace("[EVENTURL]", texify(event_url)) # Write latex file tex_output = os.path.join(version_dir, 'onepager.tex') with open(tex_output, 'w') as f: f.write(template) pdf_output = os.path.join(version_dir, 'onepager.pdf') stderr = '' try: cwd = os.getcwd() os.chdir(version_dir) cmd = '%s -interaction nonstopmode --output-directory %s %s' % ( LATEX_TO_PDF_BIN, version_dir, tex_output) print('Running %s...' % cmd) res, stdout, stderr = get_command_output(cmd) os.chdir(cwd) if not res: return (None, stderr) else: if os.path.isfile(pdf_output): return (pdf_output, stderr) else: pass except Exception as e: pass finally: os.chdir(cwd) return (None, stderr)
def __renderHistory(self, pager): #<comment> # <![CDATA[<blockTable style="historyhdrtablestyle" rowHeights="24" colWidths="42,30,25,45,38"> # <tr> # <td><para alignment="LEFT" fontName="Helvetica-Bold" fontSize="9">Date (UTC)</para></td> # <td><para alignment="RIGHT" fontName="Helvetica-Bold" fontSize="9">Dist. (km)</para></td> # <td><para alignment="CENTER" fontName="Helvetica-Bold" fontSize="9">Mag.</para></td> # <td><para alignment="CENTER" fontName="Helvetica-Bold" fontSize="9">Max MMI(#)</para></td> # <td><para alignment="RIGHT" fontName="Helvetica-Bold" fontSize="9">Shaking Deaths</para></td> # </tr> # </blockTable> # <blockTable style="historytablestyle" rowHeights="12,12,12" colWidths="42,30,25,45,38"> # <tr> # <td><para alignment="LEFT" fontName="Helvetica" fontSize="9">1993-03-06</para></td> # <td><para alignment="RIGHT" fontName="Helvetica" fontSize="9">238</para></td> # <td><para alignment="CENTER" fontName="Helvetica" fontSize="9">6.6</para></td> # <td background="#7aff93"><para alignment="CENTER" fontName="Helvetica" fontSize="9">V(7k)</para></td> # <td><para alignment="RIGHT" fontName="Helvetica" fontSize="9">0</para></td> # </blockTable><para style="commentstyle"></para>]]> </comment> if not any(self._pagerdict['historical_earthquakes']): return pager table_dict = { 'style': 'historyhdrtablestyle', 'rowHeights': '24', 'colWidths': '42,30,25,45,38' } header_tag = etree.Element('blockTable', attrib=table_dict) hdr_alignments = ['LEFT', 'RIGHT', 'CENTER', 'CENTER', 'RIGHT'] hdr_fonts = ['Helvetica-Bold'] * 5 hdr_sizes = ['9'] * 5 hdr_data = [ 'Date (UTC)', 'Dist. (km)', 'Mag.', 'Max MMI(#)', 'Shaking Deaths' ] row1_tag = etree.SubElement(header_tag, 'tr') for i in range(0, 5): align = hdr_alignments[i] font = hdr_fonts[i] size = hdr_sizes[i] hdr_text = hdr_data[i] pdict = {'alignment': align, 'fontName': font, 'fontSize': font} cell_tag = etree.SubElement(row1_tag, 'td') para_tag = etree.SubElement(row1_tag, 'para', attrib=pdict, text=hdr_text) bdict = { 'style': 'historytablestyle', 'rowHeights': '12,12,12', 'colWidths': '42,30,25,45,38' } block_tag = etree.Element('blockTable', attrib=bdict) for event in self._pagerdict['historical_earthquakes']: rom_maxmmi = dec_to_roman(event['MaxMMI']) nmmi_str = pop_round_short(event['MaxMMI'], usemillion=True) deaths = event['ShakingDeaths'] if np.isnan(deaths): deaths = 'NA' else: deaths = '%i' % deaths content = [ event['Time'][0:10], '%i' % (event['Distance']), '%.1f' % (event['Magnitude']), '%s(%s)' % (rom_maxmmi, nmmi_str), '%s' % (deaths) ] row_tag = etree.SubElement(block_tag, 'tr') for i in range(0, 5): align = hdr_alignments[i] font = hdr_fonts[i] size = hdr_sizes[i] td_tag = etree.SubElement(row_tag, 'td') pdict = { 'alignment': align, 'fontName': font, 'fontSize': size } if i == 3: pdict['background'] = event['Color'] para_tag = etree.SubElement(td_tag, 'para', attrib=pdict, text=content[i]) para_tag = etree.SubElement(header_tag, 'para', attrib={'style': 'commentstyle'}) history_text = etree.tostring(header_tag, pretty_print=True) comment_tag = etree.SubElement(pager, 'comment') comment_tag.text = etree.CDATA(history_text) return pager