Module: Footballdata
- Defined in:
- lib/footballdata.rb,
lib/footballdata/mods.rb,
lib/footballdata/stat.rb,
lib/footballdata/teams.rb,
lib/footballdata/leagues.rb,
lib/footballdata/download.rb,
lib/footballdata/convert_csv.rb,
lib/footballdata/prettyprint.rb,
lib/footballdata/convert_json.rb,
lib/footballdata/convert-score.rb
Defined Under Namespace
Classes: Configuration, Metal, Stat
Constant Summary collapse
- MODS =
{ 'br.1' => { 'América FC' => 'América Mineiro', # in year 2018 ?? }, 'copa.l' => { 'América FC' => 'América Mineiro', # in year 2022 }, 'pt.1' => { 'Vitória SC' => 'Vitória Guimarães', ## avoid easy confusion with Vitória SC <=> Vitória FC 'Vitória FC' => 'Vitória Setúbal', }, }
- STAGES =
beautify stages constant names
{ 'REGULAR_SEASON' => 'Regular Season', 'QUALIFICATION' => 'Qualification', 'PRELIMINARY_ROUND' => 'Preliminary Round', 'PRELIMINARY_SEMI_FINALS' => 'Preliminary Semifinals', 'PRELIMINARY_FINAL' => 'Preliminary Final', '1ST_QUALIFYING_ROUND' => '1st Qualifying Round', '2ND_QUALIFYING_ROUND' => '2nd Qualifying Round', '3RD_QUALIFYING_ROUND' => '3rd Qualifying Round', 'QUALIFICATION_ROUND_1' => 'Qualification Round 1', 'QUALIFICATION_ROUND_2' => 'Qualification Round 2', 'QUALIFICATION_ROUND_3' => 'Qualification Round 3', 'ROUND_1' => 'Round 1', 'ROUND_2' => 'Round 2', 'ROUND_3' => 'Round 3', 'PLAY_OFF_ROUND' => 'Playoff Round', 'PLAYOFF_ROUND_1' => 'Playoff Round 1', 'LEAGUE_STAGE' => 'League', ## add Stage - why? why not? 'GROUP_STAGE' => 'Group', 'PLAYOFFS' => 'Playoffs', ## -- used in champs 'PLAY_OFFS' => 'Playoffs', ## -- used in copa liber. 'LAST_32' => 'Round of 32', 'ROUND_OF_16' => 'Round of 16', 'LAST_16' => 'Round of 16', ## use Last 16 - why? why not? 'QUARTER_FINALS' => 'Quarterfinals', 'SEMI_FINALS' => 'Semifinals', 'THIRD_PLACE' => 'Third place', 'FINAL' => 'Final', }
- MAX_HEADERS =
[ 'Stage', # 0 'Group', # 1 'Matchday', # 2 'Date', # 3 'Time', # 4 'Timezone', # 5 ## move back column - why? why not? 'Team 1', # 6 'FT', # 7 'HT', # 8 'Team 2', # 9 'ET', # 10 # extra: incl. extra time 'P', # 11 # extra: incl. penalties 'Comments', # 12 'Status', # 13 / -2 # e.g. 'UTC', # 14 / -1 # date utc ]
- MIN_HEADERS =
always keep even if all empty
[ ## always keep even if all empty 'Date', 'Team 1', 'FT', 'Team 2' ]
Class Method Summary collapse
- .assert(cond, msg) ⇒ Object
- .config ⇒ Object
-
.configure {|config| ... } ⇒ Object
lets you use Footballdata.configure do |config| config.convert.out_dir = './o' end.
- .convert_csv(league:, season:) ⇒ Object
- .convert_json(league:, season:) ⇒ Object
- .convert_score(score) ⇒ Object
- .convert_score_to_hash(score) ⇒ Object
- .export_teams(league:, season:) ⇒ Object
- .find_league!(league) ⇒ Object
-
.find_league_seasons!(league) ⇒ Object
quick (and dirty) hack - return seasons by league code - todo/fix - use one find_league_info method for all or such.
- .fmt_competition(rec) ⇒ Object
- .fmt_count(h, sort: false) ⇒ Object
- .fmt_match(rec) ⇒ Object
- .matches(league:, season:) ⇒ Object
- .pp_matches(data) ⇒ Object
-
.schedule(league:, season:) ⇒ Object
porcelain "api".
- .teams(league:, season:) ⇒ Object
-
.vacuum(rows, headers: MAX_HEADERS, fixed_headers: MIN_HEADERS) ⇒ Object
move upstream to cocos!! (re)use vacuum_csv !!!!.
Class Method Details
.assert(cond, msg) ⇒ Object
4 5 6 7 8 9 10 11 |
# File 'lib/footballdata/prettyprint.rb', line 4 def self.assert( cond, msg ) if cond # do nothing else puts "!!! assert failed - #{msg}" exit 1 end end |
.config ⇒ Object
24 |
# File 'lib/footballdata.rb', line 24 def self.config() @config ||= Configuration.new; end |
.configure {|config| ... } ⇒ Object
lets you use Footballdata.configure do |config| config.convert.out_dir = './o' end
23 |
# File 'lib/footballdata.rb', line 23 def self.configure() yield( config ); end |
.convert_csv(league:, season:) ⇒ Object
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 |
# File 'lib/footballdata/convert_csv.rb', line 42 def self.convert_csv( league:, season: ) season = Season( season ) ## cast (ensure) season class (NOT string, integer, etc.) ### note - find_league returns the metal_league_code ## e.g. eng.1 => PL league_code = find_league!( league ) matches_url = Metal.competition_matches_url( league_code, season.start_year ) teams_url = Metal.competition_teams_url( league_code, season.start_year ) data = Webcache.read_json( matches_url ) data_teams = Webcache.read_json( teams_url ) ## build a team lookup by name (& short_name) teams = Teams.new teams.add( data_teams['teams'] ) puts "#{teams.size} team(s)" ## add/update match counts teams.add_matches( data['matches'] ) ### ## todo/fix - use find_by! - add upstream!!! league_info = LeagueCodes.find_by( code: league, season: season ) ## check for time zone tz = league_info['tz'] pp tz ## note - for international club tournaments ## auto-add (fifa) country code e.g. ## Liverpool FC => Liverpool FC (ENG) ## ## todo/fix - move flag to league_info via .csv config - why? why not? clubs_intl = ['uefa.cl', 'copa.l'].include?(league.downcase) ? true : false mods = MODS[ league.downcase ] || {} recs = [] # stat = Stat.new ## track stage, match status et stats = { 'status' => Hash.new(0), 'stage' => Hash.new(0), } matches = data[ 'matches'] matches.each do |m| # stat.update( m ) # use ? or N.N. or ? for nil - why? why not? team1_name = m['homeTeam']['name'] team2_name = m['awayTeam']['name'] team1 = team1_name ? teams.find_by!(name: team1_name ) : { name: 'N.N.' } team2 = team2_name ? teams.find_by!(name: team2_name ) : { name: 'N.N.' } ## use "normed" team names team1_name = team1[:name] team2_name = team2[:name] ### mods - rename club names unless mods.nil? || mods.empty? team1_name = mods[ team1_name ] if mods[ team1_name ] team2_name = mods[ team2_name ] if mods[ team2_name ] end #### # auto-add (fifa) country code if int'l club tournament if clubs_intl if team1_name != 'N.N.' ## note - ignore no team/placeholder (e.g. N.N) team1_name = "#{team1_name} (#{team1[:country][:code]})" end if team2_name != 'N.N.' ## note - ignore no team/placeholder (e.g. N.N) team2_name = "#{team2_name} (#{team2[:country][:code]})" end end group = m['group'] stage_key = m['stage'] stats['stage'][ stage_key ] += 1 ## track stage counts ## add group stats? ## GROUP_A ## shorten group to A|B|C etc. if group ## assert group only used with GROUP_STAGE if stage_key != 'GROUP_STAGE' raise ArgumentError, "group defined BUT stage set to >#{stage_key}< (expected GROUP_STAGE)" + "and matchday to >#{m['matchday']}<" end if group =~ /^(GROUP_|Group )/ group = group.sub( /^(GROUP_|Group )/, '' ) else raise ArgumentError, "group defined with NON GROUP!? >#{group}< reset to empty"+ " and matchday to >#{m['matchday']}<" end else ## assume group.nil? group = '' end ## map stage to stage + round ## note - if no mapping defined; use (fallback to) upcase version stage = STAGES[ stage_key ] if stage.nil? puts "!! WARN - no stage mapping found for stage >#{stage_key}<" stage = stage_key end matchday = m['matchday'] matchday = nil if matchday == 0 ## change 0 to nil (empty) too score = m['score'] comments = '' ft = '' ht = '' et = '' pen = '' stats['status'][m['status']] += 1 ## track status counts case m['status'] when 'SCHEDULED', 'TIMED', 'PAUSED', 'IN_PLAY' ## IN_PLAY, PAUSED ft = '' ht = '' when 'FINISHED' ft, ht, et, pen = convert_score( score ) when 'AWARDED' # AWARDED assert( score['duration'] == 'REGULAR', 'score.duration REGULAR expected' ) ft = "#{score['fullTime']['home']}-#{score['fullTime']['away']}" ft << ' (*)' ht = '' comments = 'awarded' when 'CANCELLED' ## note cancelled might have scores!! -- add/fix later!!! ## ht only or ft+ht!!! (see fr 2021/22) ft = '(*)' ht = '' comments = 'canceled' ## us eng ? -> canceled, british eng. cancelled ? when 'POSTPONED' ft = '(*)' ht = '' comments = 'postponed' else raise ArgumentError, "unsupported match status >#{m['status']}< - sorry:" end utc = UTC.strptime( m['utcDate'], '%Y-%m-%dT%H:%M:%SZ' ) assert( utc.strftime( '%Y-%m-%dT%H:%M:%SZ' ) == m['utcDate'], 'utc time mismatch' ) ## do NOT add time if status is SCHEDULED ## or POSTPONED for now ## otherwise assume time always present - why? why not? ## ## assume NOT valid utc time if 00:00 if utc.hour == 0 && utc.min == 0 && ['SCHEDULED','POSTPONED'].include?( m['status'] ) date = utc.strftime( '%Y-%m-%d' ) time = '' timezone = '' else local = tz.to_local( utc ) date = local.strftime( '%Y-%m-%d' ) time = local.strftime( '%H:%M' ) ## pretty print timezone ### todo/fix - bundle into fmt_timezone method or such for reuse tz_abbr = local.strftime( '%Z' ) ## e.g. EEST or if not available +03 or such tz_offset = local.strftime( '%z' ) ## e.g. +0300 timezone = if tz_abbr =~ /^[+-][0-9]+$/ ## only digits (no abbrev.) tz_offset else "#{tz_abbr}/#{tz_offset}" end end recs << [stage, group, matchday.to_s, ## not convert nil or Integer to str e.g. "", "1" date, time, timezone, team1_name, ft, ht, team2_name, et, pen, comments, ## add more columns e.g. utc date, status m['status'], # e.g. FINISHED, TIMED, etc. m['utcDate'], ] end # each match ## note: get season from first match ## assert - all other matches include the same season ## e.g. # "season": { # "id": 154, # "startDate": "2018-08-03", # "endDate": "2019-05-05", # "currentMatchday": 46 # } start_date = Date.strptime( matches[0]['season']['startDate'], '%Y-%m-%d' ) end_date = Date.strptime( matches[0]['season']['endDate'], '%Y-%m-%d' ) dates = "#{start_date.strftime('%b %-d')} - #{end_date.strftime('%b %-d')}" buf = '' buf << "#{season.key} (#{dates}) - " buf << "#{teams.size} teams, " buf << "#{recs.size} matches" # buf << "#{stat[:regular_season][:goals]} goals" buf << "\n" puts buf =begin ## note: warn if stage is greater one and not regular season!! File.open( './errors.txt' , 'a:utf-8' ) do |f| if stat[:all][:stage].keys != ['REGULAR_SEASON'] f.write "!! WARN - league: #{league}, season: #{season.key} includes non-regular stage(s):\n" f.write " #{stat[:all][:stage].keys.inspect}\n" end end =end File.open( './logs.txt', 'a:utf-8' ) do |f| f.write "==== #{league} #{season.key} =============\n" f.write " #{stats.inspect}\n" end =begin f.write "\n================================\n" f.write "==== #{league} =============\n" f.write buf f.write " match status: #{stat[:regular_season][:status].inspect}\n" f.write " match duration: #{stat[:regular_season][:duration].inspect}\n" f.write "#{teams.keys.size} teams:\n" teams.each do |name, count| rec = teams_by_name[ name ] f.write " #{count}x #{name}" if rec f.write " | #{rec['shortName']} " if name != rec['shortName'] f.write " › #{rec['area']['name']}" f.write " - #{rec['address']}" else puts "!! ERROR - no team record found in teams.json for >#{name}<" exit 1 end f.write "\n" end end =end ## ## sort buy utc date ??? - why? why not? # recs = recs.sort { |l,r| l[1] <=> r[1] } ## reformat date / beautify e.g. Sat Aug 7 1993 recs = recs.map do |rec| rec[3] = Date.strptime( rec[3], '%Y-%m-%d' ).strftime( '%a %b %-d %Y' ) rec end ## pp recs ## check if all status colums ### are FINISHED ### if yes, set all to empty (for vacuum) if stats['status'].keys.size == 1 && stats['status'].keys[0] == 'FINISHED' recs = recs.map { |rec| rec[-2] = ''; rec } end if stats['stage'].keys.size == 1 && stats['stage'].keys[0] == 'REGULAR_SEASON' recs = recs.map { |rec| rec[0] = ''; rec } end recs, headers = vacuum( recs ) ## note: change season_key from 2019/20 to 2019-20 (for path/directory!!!!) write_csv( "#{config.convert.out_dir}/#{season.to_path}/#{league.downcase}.csv", recs, headers: headers ) teams.each do |rec| print " #{rec[:count]}x " print rec[:name] print " | #{rec[:short_name]} " if rec[:name] != rec[:short_name] print " › #{rec[:country][:name]} (#{rec[:country][:code]})" print " - #{rec[:address]}" print "\n" end ## pp stat end |
.convert_json(league:, season:) ⇒ Object
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 |
# File 'lib/footballdata/convert_json.rb', line 8 def self.convert_json( league:, season: ) season = Season( season ) ## cast (ensure) season class (NOT string, integer, etc.) ### note - find_league returns the metal_league_code league_code = find_league!( league ) matches_url = Metal.competition_matches_url( league_code, season.start_year ) teams_url = Metal.competition_teams_url( league_code, season.start_year ) data = Webcache.read_json( matches_url ) data_teams = Webcache.read_json( teams_url ) ## note - for international club tournaments ## auto-add (fifa) country code e.g. ## Liverpool FC => Liverpool FC (ENG) ## ## todo/fix - move flag to league_info via .csv config - why? why not? ## clubs_intl = ['uefa.cl', ## 'copa.l'].include?(league.downcase) ? true : false ## build a team lookup by name (& short_name) teams = Teams.new teams.add( data_teams['teams'] ) puts "#{teams.size} team(s)" ## add/update match counts teams.add_matches( data['matches'] ) stages = Stages.new stages.add_matches( data['matches'] ) recs = [] ## track (meta stats) stage, match status et stats = { status: Hash.new(0), ## e.g. TIMED,etc score: Hash.new(0), ## e.g. REGULAR,etc. } data[ 'matches'].each do |m| ## use ? or N.N. or ? for nil - why? why not? team1_name = m['homeTeam']['name'] team2_name = m['awayTeam']['name'] team1 = team1_name ? teams.find_by!(name: team1_name ) : { name: 'N.N.' } team2 = team2_name ? teams.find_by!(name: team2_name ) : { name: 'N.N.' } stage = m['stage'] group = m['group'] matchday = m['matchday'] matchday = nil if matchday == 0 ## change 0 to nil (empty) too stats[:status][m['status']] += 1 ## track status counts stats[:score][m['score']['duration']] += 1 case m['status'] when 'SCHEDULED', 'TIMED', 'PAUSED', 'IN_PLAY' ## IN_PLAY, PAUSED score = [] when 'FINISHED' score = convert_score_to_hash( m['score'] ) when 'AWARDED' # AWARDED assert( m['score']['duration'] == 'REGULAR', 'score.duration REGULAR expected' ) score = [m['score']['fullTime']['home'], m['score']['fullTime']['away']] when 'CANCELLED' ## note cancelled might have scores!! -- add/fix later!!! ## ht only or ft+ht!!! (see fr 2021/22) ## score = convert_score_to_hash( m['score'] ) ## ## note - there is cancelled (e.g. not/played) AND ## annulled/voided (e.g. played!! with score) score = [] when 'POSTPONED' score = [] else raise ArgumentError, "unsupported match status >#{m['status']}< - sorry: #{m.pretty_inspect}" end rec = { status: m['status'], stage: stage } utc = UTC.strptime( m['utcDate'], '%Y-%m-%dT%H:%M:%SZ' ) assert( utc.strftime( '%Y-%m-%dT%H:%M:%SZ' ) == m['utcDate'], 'utc time mismatch' ) ## do NOT add time if status is SCHEDULED ## or POSTPONED for now ## otherwise assume time always present - why? why not? ## ## assume NOT valid utc time if 00:00 if utc.hour == 0 && utc.min == 0 && ['SCHEDULED','POSTPONED'].include?( m['status'] ) ## assume local date - why? why not? rec[:date] = utc.strftime( '%Y-%m-%d' ) else rec[:date_utc] = utc.strftime( '%Y-%m-%dT%H:%M:%SZ' ) end rec[:group] = group if group rec[:matchday] = matchday if matchday rec[:team1] = team1[:name] rec[:team2] = team2[:name] rec[:score] = score unless score.empty? recs << rec end stats[:matches] = recs.size stats[:teams] = teams.size data = { slug: league, season: season.to_s, meta: stats, stages: stages.as_json, teams: teams.as_json, matches: recs } path = "#{config.convert.out_dir}/#{season.to_path}/#{league.downcase}.json" ## note: change season_key from 2019/20 to 2019-20 (for path/directory!!!!) puts " writing to >#{path}<" write_json( path, data ) end |
.convert_score(score) ⇒ Object
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/footballdata/convert-score.rb', line 13 def self.convert_score( score ) ## duration: REGULAR · PENALTY_SHOOTOUT · EXTRA_TIME ft, ht, et, pen = ["","","",""] if score['duration'] == 'REGULAR' ft = "#{score['fullTime']['home']}-#{score['fullTime']['away']}" ht = "#{score['halfTime']['home']}-#{score['halfTime']['away']}" elsif score['duration'] == 'EXTRA_TIME' et = "#{score['regularTime']['home']+score['extraTime']['home']}" et << "-" et << "#{score['regularTime']['away']+score['extraTime']['away']}" ft = "#{score['regularTime']['home']}-#{score['regularTime']['away']}" ht = "#{score['halfTime']['home']}-#{score['halfTime']['away']}" elsif score['duration'] == 'PENALTY_SHOOTOUT' if score['extraTime'] ## quick & dirty hack - calc et via regulartime+extratime pen = "#{score['penalties']['home']}-#{score['penalties']['away']}" et = "#{score['regularTime']['home']+score['extraTime']['home']}" et << "-" et << "#{score['regularTime']['away']+score['extraTime']['away']}" ft = "#{score['regularTime']['home']}-#{score['regularTime']['away']}" ht = "#{score['halfTime']['home']}-#{score['halfTime']['away']}" else ### south american-style (no extra time) ## quick & dirty hacke - calc ft via fullTime-penalties pen = "#{score['penalties']['home']}-#{score['penalties']['away']}" ft = "#{score['fullTime']['home']-score['penalties']['home']}" ft << "-" ft << "#{score['fullTime']['away']-score['penalties']['away']}" ht = "#{score['halfTime']['home']}-#{score['halfTime']['away']}" end else puts "!! unknown score duration:" pp score exit 1 end [ft,ht,et,pen] end |
.convert_score_to_hash(score) ⇒ Object
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
# File 'lib/footballdata/convert-score.rb', line 56 def self.convert_score_to_hash( score ) ## duration: REGULAR · PENALTY_SHOOTOUT · EXTRA_TIME if score['duration'] == 'REGULAR' { ft: [score['fullTime']['home'], score['fullTime']['away']], ht: [score['halfTime']['home'], score['halfTime']['away']] } elsif score['duration'] == 'EXTRA_TIME' { et: [score['regularTime']['home']+score['extraTime']['home'], score['regularTime']['away']+score['extraTime']['away']], ft: [score['regularTime']['home'], score['regularTime']['away']], ht: [score['halfTime']['home'], score['halfTime']['away']] } elsif score['duration'] == 'PENALTY_SHOOTOUT' if score['extraTime'] ## quick & dirty hack - calc et via regulartime+extratime { pen: [score['penalties']['home'], score['penalties']['away']], et: [score['regularTime']['home']+score['extraTime']['home'], score['regularTime']['away']+score['extraTime']['away']], ft: [score['regularTime']['home'], score['regularTime']['away']], ht: [score['halfTime']['home'], score['halfTime']['away']] } else ### south american-style (no extra time) ## quick & dirty hacke - calc ft via fullTime-penalties { pen: [score['penalties']['home'], score['penalties']['away']], ft: [score['fullTime']['home']-score['penalties']['home'], score['fullTime']['away']-score['penalties']['away']], ht: [score['halfTime']['home'], score['halfTime']['away']] } end else raise ArgumentError, "!! unknown score duration - #{score.inspect}" end end |
.export_teams(league:, season:) ⇒ Object
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
# File 'lib/footballdata/teams.rb', line 8 def self.export_teams( league:, season: ) season = Season( season ) ## cast (ensure) season class (NOT string, integer, etc.) league_code = find_league!( league ) teams_url = Metal.competition_teams_url( league_code, season.start_year ) data_teams = Webcache.read_json( teams_url ) ## build a (reverse) team lookup by name puts "#{data_teams['teams'].size} teams" clubs = {} ## by country data_teams['teams'].each do |rec| buf = String.new ### use for string buffer (or String.new('') - why? why not? buf << "#{rec['name']}" buf << ", #{rec['founded']}" if rec['founded'] if rec['venue'] buf << ", @ #{rec['venue']}" # buf << " # #{rec['area']['name']}" end buf << "\n" alt_names = String.new alt_names << " | #{rec['shortName']}" if rec['shortName'] && rec['shortName'] != rec['name'] && rec['shortName'] != rec['tla'] alt_names << " | #{rec['tla']}" if rec['tla'] && rec['tla'] != rec['name'] if alt_names.size > 0 buf << " " buf << alt_names buf << "\n" end ## clean null in address (or keep nulls) - why? why not? ## e.g. null Rionegro null ## Calle 104 No. 13a - 32 Bogotá null buf << " address: #{rec['address'].gsub( /\bnull\b/, '')}" buf << "\n" buf << " web: #{rec['website']}" buf << "\n" buf << " colors: #{rec['clubColors']}" buf << "\n" country = rec['area']['name'] ary = clubs[ country] ||= [] ary << buf end # puts buf ## pp clubs buf = String.new if clubs.size > 1 clubs.each do |country, ary| buf << "# #{country} - #{ary.size} clubs\n" end buf << "\n" end clubs.each do |country, ary| buf << "= #{country} # #{ary.size} clubs\n\n" buf << ary.join( "\n" ) buf << "\n\n" end path = "#{config.convert.out_dir}/#{season.to_path}/#{league.downcase}.clubs.txt" write_text( path, buf ) end |
.find_league!(league) ⇒ Object
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/footballdata/leagues.rb', line 10 def self.find_league!( league ) @leagues ||= begin recs = read_csv( "#{FootballdataApi.root}/config/leagues_tier1.csv" ) leagues = {} recs.each do |rec| leagues[ rec['key'] ] = rec['code'] end leagues end key = league.downcase code = @leagues[ key ] if code.nil? puts "!! ERROR - no code/mapping found for league >#{league}<" puts " mappings include:" pp @leagues exit 1 end code end |
.find_league_seasons!(league) ⇒ Object
quick (and dirty) hack - return seasons by league code - todo/fix - use one find_league_info method for all or such
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/footballdata/leagues.rb', line 34 def self.find_league_seasons!( league ) @league_seasons ||= begin recs = read_csv( "#{FootballdataApi.root}/config/leagues_tier1.csv" ) leagues = {} recs.each do |rec| leagues[ rec['key'] ] = rec['seasons'] end leagues end key = league.downcase seasons = @league_seasons[ key ] if seasons.nil? puts "!! ERROR - no code/mapping found for league >#{league}<" puts " mappings include:" pp @league_seasons exit 1 end ### split string into array seasons = seasons.split( /[ ]+/ ) seasons end |
.fmt_competition(rec) ⇒ Object
13 14 15 16 17 18 19 20 21 22 23 24 25 |
# File 'lib/footballdata/prettyprint.rb', line 13 def self.fmt_competition( rec ) buf = String.new buf << "==> " buf << "#{rec['competition']['name']} (#{rec['competition']['code']}) -- " buf << "#{rec['area']['name']} (#{rec['area']['code']}) " buf << "#{rec['competition']['type']} " buf << "#{rec['season']['startDate']} - #{rec['season']['endDate']} " buf << "@ #{rec['season']['currentMatchday']}" buf << "\n" buf end |
.fmt_count(h, sort: false) ⇒ Object
164 165 166 167 168 169 170 171 172 173 174 175 |
# File 'lib/footballdata/prettyprint.rb', line 164 def self.fmt_count( h, sort: false ) pairs = h.to_a if sort pairs = pairs.sort do |l,r| res = r[1] <=> l[1] ## bigger number first res = l[0] <=> r[0] if res == 0 res end end pairs = pairs.map { |name,count| "#{name} (#{count})" } pairs.join( ' · ' ) end |
.fmt_match(rec) ⇒ Object
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 |
# File 'lib/footballdata/prettyprint.rb', line 27 def self.fmt_match( rec ) buf = String.new ## -- todo - make sure / assert it's always utc - how??? ## utc = ## tz_utc.strptime( m['utcDate'], '%Y-%m-%dT%H:%M:%SZ' ) ## note: DateTime.strptime is supposed to be unaware of timezones!!! ## use to parse utc utc = DateTime.strptime( rec['utcDate'], '%Y-%m-%dT%H:%M:%SZ' ).to_time.utc assert( utc.strftime( '%Y-%m-%dT%H:%M:%SZ' ) == rec['utcDate'], 'utc time mismatch' ) status = rec['status'] assert( %w[SCHEDULED TIMED FINISHED POSTPONED AWARDED CANCELLED IN_PLAY PAUSED ].include?( status ), "unknown status - #{status}" ) buf << '%-10s' % status buf << utc.strftime( '%a %b %d %Y %H:%M') buf << ' ' # pp rec['utcDate'] team1 = rec['homeTeam']['name'] ? "#{rec['homeTeam']['name']} (#{rec['homeTeam']['tla']})" : '?' team2 = rec['awayTeam']['name'] ? "#{rec['awayTeam']['name']} (#{rec['awayTeam']['tla']})" : '?' buf << '%22s' % team1 buf << " - " buf << '%-22s' % team2 buf << " " stage = rec['stage'] group = rec['group'] buf << "#{rec['matchday']} - #{stage} " buf << "/ #{group} " if group buf << "\n" buf << " " buf << '%-20s' % rec['score']['duration'] buf << ' '*24 duration = rec['score']['duration'] assert( %w[REGULAR EXTRA_TIME PENALTY_SHOOTOUT ].include?( duration ), "unknown duration - #{duration}" ) ft, ht, et, pen = convert_score( rec['score'] ) score = String.new if !pen.empty? if et.empty? ### south american-style (no extra time) score << "#{pen} pen. " score << "(#{ft}, #{ht})" else score << "#{pen} pen. " score << "#{et} a.e.t. " score << "(#{ft}, #{ht})" end elsif !et.empty? score << "#{et} a.e.t. " score << "(#{ft}, #{ht})" else if !ht.empty? score << "#{ft} (#{ht})" else score << "#{ft}" end end buf << score buf << "\n" buf end |
.matches(league:, season:) ⇒ Object
17 18 19 20 21 22 23 |
# File 'lib/footballdata/download.rb', line 17 def self.matches( league:, season: ) season = Season( season ) ## cast (ensure) season class (NOT string, integer, etc.) league_code = find_league!( league ) puts " mapping league >#{league}< to >#{league_code}<" Metal.matches( league_code, season.start_year ) end |
.pp_matches(data) ⇒ Object
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 |
# File 'lib/footballdata/prettyprint.rb', line 108 def self.pp_matches( data ) ## track match status and score duration stats = { 'status' => Hash.new(0), 'duration' => Hash.new(0), 'stage' => Hash.new(0), 'group' => Hash.new(0), } first = Date.strptime( data['resultSet']['first'], '%Y-%m-%d' ) last = Date.strptime( data['resultSet']['last'], '%Y-%m-%d' ) diff = (last - first).to_i # note - returns rational number (e.g. 30/1) print "==> #{data['competition']['name']}, " print "#{first.strftime('%a %b %d %Y')} - #{last.strftime('%a %b %d %Y')}" print " (#{diff}d)" print "\n" data['matches'].each do |rec| print fmt_match( rec ) ## track stats status = rec['status'] stats['status'][status] += 1 stage = rec['stage'] stats['stage'][stage] += 1 group = rec['group'] stats['group'][group] += 1 if group duration = rec['score']['duration'] stats['duration'][duration] += 1 end print " #{data['resultSet']['played']}/#{data['resultSet']['count']} matches" print "\n" print " status (#{stats['status'].size}): " print fmt_count( stats['status'], sort: true ) print "\n" print " duration (#{stats['duration'].size}): " print fmt_count( stats['duration'], sort: true ) print "\n" print " stage (#{stats['stage'].size}): " print fmt_count( stats['stage'] ) print "\n" print " group (#{stats['group'].size}): " print fmt_count( stats['group'] ) print "\n" end |
.schedule(league:, season:) ⇒ Object
porcelain "api"
6 7 8 9 10 11 12 13 14 |
# File 'lib/footballdata/download.rb', line 6 def self.schedule( league:, season: ) season = Season( season ) ## cast (ensure) season class (NOT string, integer, etc.) league_code = find_league!( league ) puts " mapping league >#{league}< to >#{league_code}<" Metal.teams( league_code, season.start_year ) Metal.matches( league_code, season.start_year ) end |
.teams(league:, season:) ⇒ Object
26 27 28 29 30 31 32 |
# File 'lib/footballdata/download.rb', line 26 def self.teams( league:, season: ) season = Season( season ) ## cast (ensure) season class (NOT string, integer, etc.) league_code = find_league!( league ) puts " mapping league >#{league}< to >#{league_code}<" Metal.teams( league_code, season.start_year ) end |
.vacuum(rows, headers: MAX_HEADERS, fixed_headers: MIN_HEADERS) ⇒ Object
move upstream to cocos!! (re)use vacuum_csv !!!!
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 |
# File 'lib/footballdata/convert_csv.rb', line 421 def self.vacuum( rows, headers: MAX_HEADERS, fixed_headers: MIN_HEADERS ) ## check for unused columns and strip/remove counter = Array.new( MAX_HEADERS.size, 0 ) rows.each do |row| row.each_with_index do |col, idx| counter[idx] += 1 unless col.nil? || col.empty? end end ## pp counter ## check empty columns headers = [] indices = [] empty_headers = [] empty_indices = [] counter.each_with_index do |num, idx| header = MAX_HEADERS[ idx ] if num > 0 || (num == 0 && fixed_headers.include?( header )) headers << header indices << idx else empty_headers << header empty_indices << idx end end if empty_indices.size > 0 rows = rows.map do |row| row_vacuumed = [] row.each_with_index do |col, idx| ## todo/fix: use values or such?? row_vacuumed << col unless empty_indices.include?( idx ) end row_vacuumed end end [rows, headers] end |