def vents(vv, dv, origine, sites): """ Calcule les statistiques relatives aux pourcentages d'influence du site émetteur d'origine sur les sites récepteurs au travers du calcul de la rose des vents. Seuls les vents > 1 m/s seront pris en compte dans les calculs, pour une rose des vents de 16 secteurs. Paramètres: vv: vitesses de vent dv: directions du vent origine: Site origine des vents à étudier sites: liste de sites récepteurs à calculer """ nsector = 16 classes = np.arange(1, 30, 1) # classes de vitesses de vent vv = vv.astype(float) dv = dv.astype(float) # suppression des données nulles vv, dv = utils.dissolveMask(vv, dv) vv = vv.dropna() dv = dv.dropna() # Calcul des pourcentages de vents par secteur dirs, bins, table = histogram(dir=dv, var=vv, bins=classes, nsector=nsector, normed=False, blowto=True) freq = table.sum(axis=0) / table.sum() * 100 # Création du dataframe des résultats de pourcentages sous les vents freq = pd.DataFrame(zip(dirs, freq), columns=('dir_debut', 'pourcentage')) # Décalage des directions pour supprimer le problème du secteur nord [350°-10°] delta = 360. / nsector / 2 freq['dir_debut'] = freq['dir_debut'] + delta # on ajoute une colonne où sont stockées les directions de fin freq['dir_fin'] = freq['dir_debut'].shift(-1) freq.at[freq.index[0], 'dir_debut'] = 0. freq.at[freq.index[-1], 'dir_fin'] = 360. # Calcule des angles et distances des sites par rapport à l'origine angles = angles_avec(sites, origine) distances = distances_avec(sites, origine) # On regroupe angles et distances dans un unique dataframe df = angles.join(distances) # Pour chaque site, on cherche le pourcentage sous les vents de l'origine df['pourcentage'] = 0. for idx in df.index: ang = df.at[idx, 'angle'] cond = (ang >= freq['dir_debut']) & (ang < freq['dir_fin']) p = freq.get(cond)['pourcentage'] try: df.at[idx, 'pourcentage'] = p except: pass df = df.applymap(np.round) return df
def _make_textresult(station, df, units, nsector, sname, monthinfo, hourinfo, level, bins): """Generate a text table of windrose information Args: station (str): the station identifier df (pd.DataFrame): The dataframe with data units (str): the units of the `sknt` values nsector (int): number of sectors to divide rose into sname (str): the station name monthinfo (dict): information on month limiting hourinfo (dict): information on hour limiting level (int): in case of RAOB, which level do we care for bins (list): values to bin the wind speeds Returns: str of information""" wu = WINDUNITS[units] if level is None else RAOB_WINDUNITS[units] if len(bins) > 0: wu['bins'] = bins # Effectively filters out the nulls df2 = df[df['drct'] >= 0] dir_edges, var_bins, table = histogram(df2['drct'].values, df2['speed'].values, np.asarray(wu['bins']), nsector, normed=True) res = ("# Windrose Data Table (Percent Frequency) " "for %s (%s)\n" ) % ( sname if sname is not None else "((%s))" % (station, ), station) res += ("# Observations Used/Missing/Total: %s/%s/%s\n" ) % (len(df2.index), len(df.index)-len(df2.index), len(df.index)) res += ("# Period: %s - %s\n" ) % (df['valid'].min().strftime("%-d %b %Y"), df['valid'].max().strftime("%-d %b %Y")) res += "# Hour Limiter: %s\n" % (hourinfo['labeltext'],) res += "# Month Limiter: %s\n" % (monthinfo['labeltext'],) res += "# Wind Speed Units: %s\n" % (wu['label'],) if level is not None: res += "# RAOB Pressure (hPa) Level: %s\n" % (level,) res += ("# Generated %s UTC, contact: [email protected]\n" ) % (datetime.datetime.utcnow().strftime("%d %b %Y %H:%M"),) res += "# First value in table is CALM\n" res += " ," for j in range(len(var_bins)-1): res += " %4.1f-%4.1f," % (var_bins[j], var_bins[j+1]-0.1) res += "\n" dir_edges2 = np.concatenate((np.array(dir_edges), [dir_edges[-1] + (dir_edges[-1] - dir_edges[-2]), ])) for i in range(len(dir_edges2)-1): res += "%03i-%03i," % (dir_edges2[i], dir_edges2[i+1]) for j in range(len(var_bins)-1): res += " %9.3f," % (table[j, i], ) res += "\n" return res
def _make_textresult(station, sknt, drct, units, nsector, sname, minvalid, maxvalid, monthinfo, hourinfo, level, bins): """Generate a text table of windrose information Args: station (str): the station identifier sknt (list): The wind speed values drct (list): the wind direction values units (str): the units of the `sknt` values nsector (int): number of sectors to divide rose into sname (str): the station name minvalid (datetime): the minimum observation time maxvalid (datetime): the maximum observation time monthinfo (dict): information on month limiting hourinfo (dict): information on hour limiting level (int): in case of RAOB, which level do we care for bins (list): values to bin the wind speeds Returns: str of information""" wu = WINDUNITS[units] if level is None else RAOB_WINDUNITS[units] if len(bins) > 0: wu['bins'] = bins dir_edges, var_bins, table = histogram(drct, sknt, np.asarray( wu['bins']), nsector, normed=True) res = ("# Windrose Data Table (Percent Frequency) " "for %s (%s)\n" ) % ( sname if sname is not None else "((%s))" % (station, ), station) res += "# Observation Count: %s\n" % (len(sknt),) res += ("# Period: %s - %s\n" ) % (minvalid.strftime("%-d %b %Y"), maxvalid.strftime("%-d %b %Y")) res += "# Hour Limiter: %s\n" % (hourinfo['labeltext'],) res += "# Month Limiter: %s\n" % (monthinfo['labeltext'],) res += "# Wind Speed Units: %s\n" % (wu['label'],) if level is not None: res += "# RAOB Pressure (hPa) Level: %s\n" % (level,) res += ("# Generated %s UTC, contact: [email protected]\n" ) % (datetime.datetime.utcnow().strftime("%d %b %Y %H:%M"),) res += "# First value in table is CALM\n" res += " ," for j in range(len(var_bins)-1): res += " %4.1f-%4.1f," % (var_bins[j], var_bins[j+1]-0.1) res += "\n" dir_edges2 = np.concatenate((np.array(dir_edges), [dir_edges[-1] + (dir_edges[-1] - dir_edges[-2]), ])) for i in range(len(dir_edges2)-1): res += "%03i-%03i," % (dir_edges2[i], dir_edges2[i+1]) for j in range(len(var_bins)-1): res += " %9.3f," % (table[j, i], ) res += "\n" return res
def highcharts(fdict): """ Generate the highcharts variant""" import matplotlib matplotlib.use('agg') from windrose.windrose import histogram ctx = get_context(fdict) dir_edges, var_bins, table = histogram(ctx['df']['drct'].values, ctx['df']['smph'].values, np.array([0, 2, 5, 7, 10, 15, 20]), 18, True) arr = [drct2text(mydir) for mydir in dir_edges] return """ var arr = """ + str(arr) + """; $("#ap_container").highcharts({ series: [{name: '2 - 5', data: """ + str(zip(arr, table[1])) + """, _colorIndex: 0}, {name: '5 - 7', data: """ + str(zip(arr, table[2])) + """, _colorIndex: 1}, {name: '7 - 10', data: """ + str(zip(arr, table[3])) + """, _colorIndex: 2}, {name: '10 - 15', data: """ + str(zip(arr, table[4])) + """, _colorIndex: 3}, {name: '15 - 20', data: """ + str(zip(arr, table[5])) + """, _colorIndex: 4}, {name: '20 +', data: """ + str(zip(arr, table[6])) + """, _colorIndex: 5}], chart: { polar: true, type: 'column' }, title: { 'text': '""" + ctx['title'] + """' }, subtitle: { 'text': '""" + ctx['subtitle'] + """'
def highcharts(fdict): """ Generate the highcharts variant""" import matplotlib matplotlib.use('agg') from windrose.windrose import histogram ctx = get_context(fdict) dir_edges, var_bins, table = histogram(ctx['df']['drct'].values, ctx['df']['smph'].values, np.array([0, 2, 5, 7, 10, 15, 20]), 18, True) arr = [drct2text(mydir) for mydir in dir_edges] return """ var arr = """+str(arr)+"""; $("#ap_container").highcharts({ series: [{name: '2 - 5', data: """+str(zip(arr, table[1]))+""", _colorIndex: 0}, {name: '5 - 7', data: """+str(zip(arr, table[2]))+""", _colorIndex: 1}, {name: '7 - 10', data: """+str(zip(arr, table[3]))+""", _colorIndex: 2}, {name: '10 - 15', data: """+str(zip(arr, table[4]))+""", _colorIndex: 3}, {name: '15 - 20', data: """+str(zip(arr, table[5]))+""", _colorIndex: 4}, {name: '20 +', data: """+str(zip(arr, table[6]))+""", _colorIndex: 5}], chart: { polar: true, type: 'column' }, title: { 'text': '"""+ctx['title']+"""' }, subtitle: { 'text': '"""+ctx['subtitle']+"""'
def highcharts(fdict): """ Generate the highcharts variant""" ctx = get_context(fdict) dir_edges, _, table = histogram( ctx["df"]["drct"].values, ctx["df"]["smph"].values, np.array([0, 2, 5, 7, 10, 15, 20]), 18, True, ) arr = [drct2text(mydir) for mydir in dir_edges] return (""" var arr = """ + str(arr) + """; $("#ap_container").highcharts({ series: [{name: '2 - 5', data: """ + str(list(zip(arr, table[1]))) + """, _colorIndex: 0}, {name: '5 - 7', data: """ + str(list(zip(arr, table[2]))) + """, _colorIndex: 1}, {name: '7 - 10', data: """ + str(list(zip(arr, table[3]))) + """, _colorIndex: 2}, {name: '10 - 15', data: """ + str(list(zip(arr, table[4]))) + """, _colorIndex: 3}, {name: '15 - 20', data: """ + str(list(zip(arr, table[5]))) + """, _colorIndex: 4}, {name: '20 +', data: """ + str(list(zip(arr, table[6]))) + """, _colorIndex: 5}], chart: { polar: true, type: 'column' }, title: { 'text': '""" + ctx["title"] + """' }, subtitle: { 'text': '""" + ctx["subtitle"] + """' }, pane: { 'size': '85%' }, legend: { title: {text: 'Wind Speed [MPH]'}, verticalAlign: 'bottom', layout: 'horizontal' }, xAxis: { 'tickInterval': 18./8., 'labels': { formatter: function(){ var v = this.value.toFixed(1); if (v == '0.0') {return 'N';} if (v == '2.3') {return 'NE';} if (v == '4.5') {return 'E';} if (v == '6.8') {return 'SE';} if (v == '9.0') {return 'S';} if (v == '11.3') {return 'SW';} if (v == '13.5') {return 'W';} if (v == '15.8') {return 'NW';} return v; } } }, yAxis: { 'min': 0, 'endOnTick': false, 'showLastLabel': true, 'title': { 'text': 'Frequency (%)' }, 'reversedStacks': false }, tooltip: { positioner: function () { return { x: 10, y: 10 }; }, 'valueSuffix': '%', shared: true, valueDecimals: 1, formatter: function () { var s = '<b>' + arr[this.x] + ' ('+ this.points[0].total.toFixed(1)+'%)</b>'; $.each(this.points, function () { s += '<br/>' + this.series.name + ': ' + this.y.toFixed(1) + '%'; }); return s; }, }, plotOptions: { 'series': { 'stacking': 'normal', 'shadow': false, 'groupPadding': 0, 'pointPlacement': 'on' } } }); """)