Skip to content

Commit

Permalink
finalize
Browse files Browse the repository at this point in the history
  • Loading branch information
LukeWIN committed Mar 24, 2021
1 parent 415ca22 commit e12b75f
Show file tree
Hide file tree
Showing 3 changed files with 157 additions and 63 deletions.
146 changes: 100 additions & 46 deletions filters.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,20 @@
"""Provide filters for querying close approaches and limit the generated results.
"""Provide filters for querying close approaches and limit the generated
results.
The `create_filters` function produces a collection of objects that is used by
the `query` method to generate a stream of `CloseApproach` objects that match
all of the desired criteria. The arguments to `create_filters` are provided by
the main module and originate from the user's command-line options.
This function can be thought to return a collection of instances of subclasses
of `AttributeFilter` - a 1-argument callable (on a `CloseApproach`) constructed
from a comparator (from the `operator` module), a reference value, and a class
method `get` that subclasses can override to fetch an attribute of interest from
the supplied `CloseApproach`.
method `get` that subclasses can override to fetch an attribute of interest
from the supplied `CloseApproach`.
The `limit` function simply limits the maximum number of values produced by an
iterator.
You'll edit this file in Tasks 3a and 3c.
"""
import operator
from itertools import islice


class UnsupportedCriterionError(NotImplementedError):
Expand All @@ -25,27 +23,23 @@ class UnsupportedCriterionError(NotImplementedError):

class AttributeFilter:
"""A general superclass for filters on comparable attributes.
An `AttributeFilter` represents the search criteria pattern comparing some
attribute of a close approach (or its attached NEO) to a reference value. It
essentially functions as a callable predicate for whether a `CloseApproach`
object satisfies the encoded criterion.
attribute of a close approach (or its attached NEO) to a reference value.
It essentially functions as a callable predicate for whether a
`CloseApproach` object satisfies the encoded criterion.
It is constructed with a comparator operator and a reference value, and
calling the filter (with __call__) executes `get(approach) OP value` (in
infix notation).
Concrete subclasses can override the `get` classmethod to provide custom
behavior to fetch a desired attribute from the given `CloseApproach`.
"""
def __init__(self, op, value):
"""Construct a new `AttributeFilter` from an binary predicate and a reference value.
"""Construct a new `AttributeFilter` from an binary predicate and a
reference value.
The reference value will be supplied as the second (right-hand side)
argument to the operator function. For example, an `AttributeFilter`
with `op=operator.le` and `value=10` will, when called on an approach,
evaluate `some_attribute <= 10`.
:param op: A 2-argument predicate comparator (such as `operator.le`).
:param value: The reference value to compare against.
"""
Expand All @@ -59,17 +53,47 @@ def __call__(self, approach):
@classmethod
def get(cls, approach):
"""Get an attribute of interest from a close approach.
Concrete subclasses must override this method to get an attribute of
interest from the supplied `CloseApproach`.
:param approach: A `CloseApproach` on which to evaluate this filter.
:return: The value of an attribute of interest, comparable to `self.value` via `self.op`.
:return: The value of an attribute of interest, comparable to
`self.value` via `self.op`.
"""
raise UnsupportedCriterionError

def __repr__(self):
return f"{self.__class__.__name__}(op=operator.{self.op.__name__}, value={self.value})"
return (f"""{self.__class__.__name__}"""
"""(op=operator.{self.op.__name__}, value={self.value})""")


class DistanceFilter(AttributeFilter):
@classmethod
def get(cls, approach):
return approach.distance


class DateFilter(AttributeFilter):
@classmethod
def get(cls, approach):
return approach.time.date()


class VelocityFilter(AttributeFilter):
@classmethod
def get(cls, approach):
return approach.velocity


class DiameterFilter(AttributeFilter):
@classmethod
def get(cls, approach):
return approach.neo.diameter


class HazardousFilter(AttributeFilter):
@classmethod
def get(cls, approach):
return approach.neo.hazardous


def create_filters(date=None, start_date=None, end_date=None,
Expand All @@ -78,46 +102,76 @@ def create_filters(date=None, start_date=None, end_date=None,
diameter_min=None, diameter_max=None,
hazardous=None):
"""Create a collection of filters from user-specified criteria.
Each of these arguments is provided by the main module with a value from the
user's options at the command line. Each one corresponds to a different type
of filter. For example, the `--date` option corresponds to the `date`
argument, and represents a filter that selects close approaches that occured
on exactly that given date. Similarly, the `--min-distance` option
Each of these arguments is provided by the main module with a value from
the user's options at the command line. Each one corresponds to a different
type of filter. For example, the `--date` option corresponds to the `date`
argument, and represents a filter that selects close approaches that
occured on exactly that given date. Similarly, the `--min-distance` option
corresponds to the `distance_min` argument, and represents a filter that
selects close approaches whose nominal approach distance is at least that
far away from Earth. Each option is `None` if not specified at the command
line (in particular, this means that the `--not-hazardous` flag results in
`hazardous=False`, not to be confused with `hazardous=None`).
The return value must be compatible with the `query` method of `NEODatabase`
because the main module directly passes this result to that method. For now,
this can be thought of as a collection of `AttributeFilter`s.
The return value must be compatible with the `query` method of
`NEODatabase` because the main module directly passes this result to that
method. For now, this can be thought of as a collection of
`AttributeFilter`s.
:param date: A `date` on which a matching `CloseApproach` occurs.
:param start_date: A `date` on or after which a matching `CloseApproach` occurs.
:param end_date: A `date` on or before which a matching `CloseApproach` occurs.
:param distance_min: A minimum nominal approach distance for a matching `CloseApproach`.
:param distance_max: A maximum nominal approach distance for a matching `CloseApproach`.
:param velocity_min: A minimum relative approach velocity for a matching `CloseApproach`.
:param velocity_max: A maximum relative approach velocity for a matching `CloseApproach`.
:param diameter_min: A minimum diameter of the NEO of a matching `CloseApproach`.
:param diameter_max: A maximum diameter of the NEO of a matching `CloseApproach`.
:param hazardous: Whether the NEO of a matching `CloseApproach` is potentially hazardous.
:param start_date: A `date` on or after which a matching `CloseApproach`
occurs.
:param end_date: A `date` on or before which a matching `CloseApproach`
occurs.
:param distance_min: A minimum nominal approach distance for a matching
`CloseApproach`.
:param distance_max: A maximum nominal approach distance for a matching
`CloseApproach`.
:param velocity_min: A minimum relative approach velocity for a matching
`CloseApproach`.
:param velocity_max: A maximum relative approach velocity for a matching
`CloseApproach`.
:param diameter_min: A minimum diameter of the NEO of a matching
`CloseApproach`.
:param diameter_max: A maximum diameter of the NEO of a matching
`CloseApproach`.
:param hazardous: Whether the NEO of a matching `CloseApproach` is
potentially hazardous.
:return: A collection of filters for use with `query`.
"""
# TODO: Decide how you will represent your filters.
return ()

queries = []

if date:
queries.append(DateFilter(operator.eq, date))
if start_date:
queries.append(DateFilter(operator.ge, start_date))
if end_date:
queries.append(DateFilter(operator.le, end_date))
if distance_min:
queries.append(DistanceFilter(operator.ge, distance_min))
if distance_max:
queries.append(DistanceFilter(operator.le, distance_max))
if velocity_min:
queries.append(VelocityFilter(operator.ge, velocity_min))
if velocity_max:
queries.append(VelocityFilter(operator.le, velocity_max))
if diameter_min:
queries.append(DiameterFilter(operator.ge, diameter_min))
if diameter_max:
queries.append(DiameterFilter(operator.le, diameter_max))
if hazardous is not None:
queries.append(HazardousFilter(operator.eq, hazardous))

return queries


def limit(iterator, n=None):
"""Produce a limited stream of values from an iterator.
If `n` is 0 or None, don't limit the iterator at all.
:param iterator: An iterator of values.
:param n: The maximum number of values to produce.
:yield: The first (at most) `n` values from the iterator.
"""
# TODO: Produce at most `n` values from the given iterator.
return iterator
if n:
return islice(iterator, n)
else:
return iterator
14 changes: 14 additions & 0 deletions models.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,20 @@ def time_str(self):
# else:
# return f"{self.designation}"

def serialize(self):
result = {
'datetime_utc': datetime_to_str(self.time),
'distance_au': self.distance,
'velocity_km_s': self.velocity,
'neo': {
'designation': self.neo.designation,
'name': self.neo.name,
'diameter_km': self.neo.diameter,
'potentially_hazardous': self.neo.hazardous
},
}
return result

def __str__(self):
"""Return `str(self)`."""
# TODO: Use this object's attributes to return a human-readable string representation.
Expand Down
60 changes: 43 additions & 17 deletions write.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
"""Write a stream of close approaches to CSV or to JSON.
This module exports two functions: `write_to_csv` and `write_to_json`, each of
which accept an `results` stream of close approaches and a path to which to
write the data.
These functions are invoked by the main module with the output of the `limit`
function and the filename supplied by the user at the command line. The file's
extension determines which of these functions is used.
You'll edit this file in Part 4.
"""
import csv
Expand All @@ -16,27 +13,56 @@

def write_to_csv(results, filename):
"""Write an iterable of `CloseApproach` objects to a CSV file.
The precise output specification is in `README.md`. Roughly, each output row
corresponds to the information in a single close approach from the `results`
stream and its associated near-Earth object.
The precise output specification is in `README.md`. Roughly, each output
row corresponds to the information in a single close approach from the
`results` stream and its associated near-Earth object.
:param results: An iterable of `CloseApproach` objects.
:param filename: A Path-like object pointing to where the data should be saved.
:param filename: A Path-like object pointing to where the data should be
saved.
"""
fieldnames = ('datetime_utc', 'distance_au', 'velocity_km_s', 'designation', 'name', 'diameter_km', 'potentially_hazardous')
# TODO: Write the results to a CSV file, following the specification in the instructions.
fieldnames = {
'datetime_utc': 'String date object as UTC',
'distance_au': 'Distance',
'velocity_km_s': 'Velocity in km/s',
'designation': 'Designation',
'name': 'Name',
'diameter_km': 'Diameter in km',
'potentially_hazardous': 'Potentially hazardous',
}

with open(filename, 'w') as outfile:
writer = csv.DictWriter(outfile, fieldnames.keys())
writer.writeheader()
for result in results:
cad_object = result.serialize()
row = {
'datetime_utc': cad_object['datetime_utc'],
'distance_au': cad_object['distance_au'],
'velocity_km_s': cad_object['velocity_km_s'],
'designation': cad_object['neo']['designation'],
'name': (cad_object['neo']['name'] if cad_object['neo']['name']
else 'None'),
'diameter_km': cad_object['neo']['diameter_km'],
'potentially_hazardous': ('True' if cad_object['neo']
['potentially_hazardous']
else 'False'),
}
writer.writerow(row)


def write_to_json(results, filename):
"""Write an iterable of `CloseApproach` objects to a JSON file.
The precise output specification is in `README.md`. Roughly, the output is a
list containing dictionaries, each mapping `CloseApproach` attributes to
The precise output specification is in `README.md`. Roughly, the output is
a list containing dictionaries, each mapping `CloseApproach` attributes to
their values and the 'neo' key mapping to a dictionary of the associated
NEO's attributes.
:param results: An iterable of `CloseApproach` objects.
:param filename: A Path-like object pointing to where the data should be saved.
:param filename: A Path-like object pointing to where the data should be
saved.
"""
# TODO: Write the results to a JSON file, following the specification in the instructions.
results_output = []
for result in results:
results_output.append(result.serialize())

with open(filename, 'w') as outfile:
json.dump(results_output, outfile, indent=2)

0 comments on commit e12b75f

Please sign in to comment.