Search in sources :

Example 1 with AisShipStatic

use of au.gov.amsa.ais.message.AisShipStatic in project risky by amsa-code.

the class ShipTypeBreakdownMain method main.

public static void main(String[] args) throws FileNotFoundException, IOException {
    // load a shapefile
    final GeometryFactory gf = new GeometryFactory();
    File file = new File("/home/dxm/temp/srr.shp");
    Map<String, Serializable> map = new HashMap<>();
    map.put("url", file.toURI().toURL());
    DataStore datastore = DataStoreFinder.getDataStore(map);
    String typeName = datastore.getTypeNames()[0];
    System.out.println(typeName);
    SimpleFeatureSource source = datastore.getFeatureSource(typeName);
    final SimpleFeatureCollection features = source.getFeatures();
    final List<PreparedGeometry> geometries = new ArrayList<>();
    SimpleFeatureIterator it = features.features();
    while (it.hasNext()) {
        SimpleFeature feature = it.next();
        Geometry g = (Geometry) feature.getDefaultGeometry();
        geometries.add(PreparedGeometryFactory.prepare(g));
    }
    // System.exit(0);
    String filename = "/media/analysis/nmea/2014/NMEA_ITU_20140815.gz";
    final Set<Long> mmsi = new HashSet<Long>();
    final Set<Long> mmsiA = new HashSet<Long>();
    final Set<Long> mmsiB = new HashSet<Long>();
    Streams.extract(Streams.nmeaFromGzip(filename)).flatMap(aisPositionsOnly).lift(Logging.<TimestampedAndLine<AisPosition>>logger().showCount().every(100000).log()).doOnNext(m -> {
        AisPosition p = m.getMessage().get().message();
        if (p.getLatitude() != null && p.getLongitude() != null && contains(gf, geometries, p.getLatitude(), p.getLongitude())) {
            long mmsiNo = m.getMessage().get().message().getMmsi();
            mmsi.add(mmsiNo);
            if (m.getMessage().get().message() instanceof AisPositionA)
                mmsiA.add(mmsiNo);
            else
                mmsiB.add(mmsiNo);
        }
    }).subscribe();
    final Map<ShipTypeClass, Set<Integer>> countsByShipType = new ConcurrentHashMap<>();
    Streams.extract(Streams.nmeaFromGzip(filename)).flatMap(aisShipStaticOnly).doOnNext(m -> {
        AisShipStatic s = m.getMessage().get().message();
        if (mmsi.contains(Long.valueOf(s.getMmsi()))) {
            boolean isClassA = s instanceof AisShipStaticA;
            ShipTypeClass shipTypeClass = new ShipTypeClass(isClassA, s.getShipType());
            if (countsByShipType.get(shipTypeClass) == null)
                countsByShipType.put(shipTypeClass, new HashSet<Integer>());
            else
                countsByShipType.get(shipTypeClass).add(s.getMmsi());
        }
    }).subscribe();
    System.out.println(countsByShipType);
    Set<String> set = new TreeSet<String>();
    int sizeA = 0;
    int sizeB = 0;
    for (Entry<ShipTypeClass, Set<Integer>> s : countsByShipType.entrySet()) {
        set.add(ShipTypeDecoder.getShipType(s.getKey().shipType) + "\t" + (s.getKey().isClassA ? "A" : "B") + "\t" + s.getValue().size());
        if (s.getKey().isClassA)
            sizeA += s.getValue().size();
        else
            sizeB += s.getValue().size();
    }
    set.stream().forEach(System.out::println);
    System.out.println("Unknown\tA\t" + (mmsiA.size() - sizeA));
    System.out.println("Unknown\tB\t" + (mmsiB.size() - sizeB));
    log.info("finished");
}
Also used : ShipTypeDecoder(au.gov.amsa.ais.ShipTypeDecoder) Logging(com.github.davidmoten.rx.slf4j.Logging) AisPosition(au.gov.amsa.ais.message.AisPosition) AisShipStatic(au.gov.amsa.ais.message.AisShipStatic) LoggerFactory(org.slf4j.LoggerFactory) Coordinate(org.locationtech.jts.geom.Coordinate) HashMap(java.util.HashMap) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) SimpleFeatureSource(org.geotools.data.simple.SimpleFeatureSource) Observable(rx.Observable) HashSet(java.util.HashSet) Func1(rx.functions.Func1) AisPositionA(au.gov.amsa.ais.message.AisPositionA) SimpleFeature(org.opengis.feature.simple.SimpleFeature) Streams(au.gov.amsa.ais.rx.Streams) Map(java.util.Map) DataStoreFinder(org.geotools.data.DataStoreFinder) PreparedGeometry(org.locationtech.jts.geom.prep.PreparedGeometry) TimestampedAndLine(au.gov.amsa.ais.rx.Streams.TimestampedAndLine) GeometryFactory(org.locationtech.jts.geom.GeometryFactory) Logger(org.slf4j.Logger) SimpleFeatureCollection(org.geotools.data.simple.SimpleFeatureCollection) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) IOException(java.io.IOException) AisMessage(au.gov.amsa.ais.AisMessage) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) DataStore(org.geotools.data.DataStore) Serializable(java.io.Serializable) List(java.util.List) Entry(java.util.Map.Entry) Optional(java.util.Optional) Geometry(org.locationtech.jts.geom.Geometry) AisShipStaticA(au.gov.amsa.ais.message.AisShipStaticA) SimpleFeatureIterator(org.geotools.data.simple.SimpleFeatureIterator) Timestamped(au.gov.amsa.ais.Timestamped) PreparedGeometryFactory(org.locationtech.jts.geom.prep.PreparedGeometryFactory) Serializable(java.io.Serializable) GeometryFactory(org.locationtech.jts.geom.GeometryFactory) PreparedGeometryFactory(org.locationtech.jts.geom.prep.PreparedGeometryFactory) TreeSet(java.util.TreeSet) HashSet(java.util.HashSet) Set(java.util.Set) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) SimpleFeatureSource(org.geotools.data.simple.SimpleFeatureSource) ArrayList(java.util.ArrayList) SimpleFeatureIterator(org.geotools.data.simple.SimpleFeatureIterator) AisPositionA(au.gov.amsa.ais.message.AisPositionA) TreeSet(java.util.TreeSet) DataStore(org.geotools.data.DataStore) AisShipStatic(au.gov.amsa.ais.message.AisShipStatic) TimestampedAndLine(au.gov.amsa.ais.rx.Streams.TimestampedAndLine) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) AisShipStaticA(au.gov.amsa.ais.message.AisShipStaticA) HashSet(java.util.HashSet) SimpleFeature(org.opengis.feature.simple.SimpleFeature) SimpleFeatureCollection(org.geotools.data.simple.SimpleFeatureCollection) AisPosition(au.gov.amsa.ais.message.AisPosition) PreparedGeometry(org.locationtech.jts.geom.prep.PreparedGeometry) Geometry(org.locationtech.jts.geom.Geometry) PreparedGeometry(org.locationtech.jts.geom.prep.PreparedGeometry) File(java.io.File)

Example 2 with AisShipStatic

use of au.gov.amsa.ais.message.AisShipStatic in project risky by amsa-code.

the class ShipStaticDataCreator method writeStaticDataToFileWithTimestamps.

public static Observable<Timestamped<AisShipStatic>> writeStaticDataToFileWithTimestamps(List<File> files, File outputFile, Scheduler scheduler) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    Func0<PrintStream> resourceFactory = Checked.f0(() -> new PrintStream(outputFile));
    Func1<PrintStream, Observable<Timestamped<AisShipStatic>>> observableFactory = out -> Observable.from(files).buffer(Math.max(1, files.size() / Runtime.getRuntime().availableProcessors() - 1)).flatMap(list -> // 
    Observable.from(list).lift(// 
    Logging.<File>logger().showValue().showMemory().log()).concatMap(// 
    file -> timestampedShipStatics(file))).groupBy(// 
    m -> m.message().getMmsi()).flatMap(// 
    g -> collect(g).subscribeOn(scheduler)).compose(Transformers.doOnFirst(x -> {
        out.println("# MMSI, Time, IMO, AisClass, AisShipType, MaxPresentStaticDraughtMetres, DimAMetres, DimBMetres, DimCMetres, DimDMetres, LengthMetres, WidthMetres, Name");
        out.println("# columns are tab delimited");
        out.println("# -1 = not present");
    })).filter(// 
    set -> set.size() <= 10).flatMapIterable(// 
    set -> set).doOnNext(k -> {
        AisShipStatic m = k.message();
        out.format("%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n", m.getMmsi(), sdf.format(new Date(k.time())), getImo(m).orElse(-1), m instanceof AisShipStaticA ? "A" : "B", m.getShipType(), getMaximumPresentStaticDraughtMetres(m).orElse(-1F), m.getDimensionA().orElse(-1), m.getDimensionB().orElse(-1), m.getDimensionC().orElse(-1), m.getDimensionD().orElse(-1), AisShipStaticUtil.lengthMetres(m).orElse(-1), AisShipStaticUtil.widthMetres(m).orElse(-1), prepareName(m.getName()));
        out.flush();
    });
    Action1<PrintStream> disposeAction = out -> out.close();
    return Observable.using(resourceFactory, observableFactory, disposeAction);
}
Also used : Date(java.util.Date) Logging(com.github.davidmoten.rx.slf4j.Logging) AisShipStatic(au.gov.amsa.ais.message.AisShipStatic) SimpleDateFormat(java.text.SimpleDateFormat) Preconditions(com.github.davidmoten.guavamini.Preconditions) Action1(rx.functions.Action1) TreeSet(java.util.TreeSet) Observable(rx.Observable) Func0(rx.functions.Func0) Func1(rx.functions.Func1) AisShipStaticUtil(au.gov.amsa.ais.message.AisShipStaticUtil) Streams(au.gov.amsa.ais.rx.Streams) Schedulers(rx.schedulers.Schedulers) TimestampedAndLine(au.gov.amsa.ais.rx.Streams.TimestampedAndLine) PrintStream(java.io.PrintStream) Transformers(com.github.davidmoten.rx.Transformers) Iterator(java.util.Iterator) TimeZone(java.util.TimeZone) Checked(com.github.davidmoten.rx.Checked) AisMessage(au.gov.amsa.ais.AisMessage) Scheduler(rx.Scheduler) File(java.io.File) List(java.util.List) GroupedObservable(rx.observables.GroupedObservable) Optional(java.util.Optional) AisShipStaticA(au.gov.amsa.ais.message.AisShipStaticA) Timestamped(au.gov.amsa.ais.Timestamped) PrintStream(java.io.PrintStream) AisShipStatic(au.gov.amsa.ais.message.AisShipStatic) AisShipStaticA(au.gov.amsa.ais.message.AisShipStaticA) SimpleDateFormat(java.text.SimpleDateFormat) File(java.io.File) Observable(rx.Observable) GroupedObservable(rx.observables.GroupedObservable) Date(java.util.Date)

Example 3 with AisShipStatic

use of au.gov.amsa.ais.message.AisShipStatic in project risky by amsa-code.

the class ShipStaticDataCreator method writeStaticDataToFile.

public static Observable<AisShipStatic> writeStaticDataToFile(List<File> files, File outputFile, Scheduler scheduler) {
    Func0<PrintStream> resourceFactory = Checked.f0(() -> new PrintStream(outputFile));
    Func1<PrintStream, Observable<AisShipStatic>> observableFactory = out -> Observable.from(files).buffer(Math.max(1, files.size() / Runtime.getRuntime().availableProcessors() - 1)).flatMap(list -> // 
    Observable.from(list).lift(// 
    Logging.<File>logger().showValue().showMemory().log()).concatMap(file -> // 
    Streams.extract(Streams.nmeaFromGzip(file)).flatMap(// 
    aisShipStaticOnly).map(// 
    m -> m.getMessage().get().message()).distinct(// 
    m -> m.getMmsi()).doOnError(e -> System.err.println("could not read " + file + ": " + // 
    e.getMessage())).onErrorResumeNext(// 
    Observable.<AisShipStatic>empty())).distinct(// 
    m -> m.getMmsi()).subscribeOn(// 
    scheduler)).distinct(// 
    m -> m.getMmsi()).compose(// 
    Transformers.mapWithIndex()).doOnNext(indexed -> {
        if (indexed.index() == 0) {
            out.println("# MMSI, IMO, AisClass, AisShipType, MaxPresentStaticDraughtMetres, DimAMetres, DimBMetres, DimCMetres, DimDMetres, LengthMetres, WidthMetres, Name");
            out.println("# columns are tab delimited");
            out.println("# -1 = not present");
        }
    }).map(indexed -> indexed.value()).doOnNext(m -> {
        out.format("%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n", m.getMmsi(), getImo(m).orElse(-1), m instanceof AisShipStaticA ? "A" : "B", m.getShipType(), getMaximumPresentStaticDraughtMetres(m).orElse(-1F), m.getDimensionA().orElse(-1), m.getDimensionB().orElse(-1), m.getDimensionC().orElse(-1), m.getDimensionD().orElse(-1), AisShipStaticUtil.lengthMetres(m).orElse(-1), AisShipStaticUtil.widthMetres(m).orElse(-1), prepareName(m.getName()));
        out.flush();
    });
    Action1<PrintStream> disposeAction = out -> out.close();
    return Observable.using(resourceFactory, observableFactory, disposeAction);
}
Also used : Date(java.util.Date) Logging(com.github.davidmoten.rx.slf4j.Logging) AisShipStatic(au.gov.amsa.ais.message.AisShipStatic) SimpleDateFormat(java.text.SimpleDateFormat) Preconditions(com.github.davidmoten.guavamini.Preconditions) Action1(rx.functions.Action1) TreeSet(java.util.TreeSet) Observable(rx.Observable) Func0(rx.functions.Func0) Func1(rx.functions.Func1) AisShipStaticUtil(au.gov.amsa.ais.message.AisShipStaticUtil) Streams(au.gov.amsa.ais.rx.Streams) Schedulers(rx.schedulers.Schedulers) TimestampedAndLine(au.gov.amsa.ais.rx.Streams.TimestampedAndLine) PrintStream(java.io.PrintStream) Transformers(com.github.davidmoten.rx.Transformers) Iterator(java.util.Iterator) TimeZone(java.util.TimeZone) Checked(com.github.davidmoten.rx.Checked) AisMessage(au.gov.amsa.ais.AisMessage) Scheduler(rx.Scheduler) File(java.io.File) List(java.util.List) GroupedObservable(rx.observables.GroupedObservable) Optional(java.util.Optional) AisShipStaticA(au.gov.amsa.ais.message.AisShipStaticA) Timestamped(au.gov.amsa.ais.Timestamped) PrintStream(java.io.PrintStream) AisShipStatic(au.gov.amsa.ais.message.AisShipStatic) AisShipStaticA(au.gov.amsa.ais.message.AisShipStaticA) Observable(rx.Observable) GroupedObservable(rx.observables.GroupedObservable)

Example 4 with AisShipStatic

use of au.gov.amsa.ais.message.AisShipStatic in project risky by amsa-code.

the class ExtractStaticDataAsCsvFromNmeaGz method extractStaticData.

public static void extractStaticData(File input, File output) throws IOException {
    output.getParentFile().mkdirs();
    try (PrintStream out = new PrintStream(output)) {
        // 
        Streams.nmeaFromGzip(input).compose(// 
        o -> Streams.extractMessages(o)).filter(x -> // 
        (x.message() instanceof AisShipStatic) || // 
        (x.message() instanceof AisBStaticDataReportPartA) || // 
        (x.message() instanceof AisBStaticDataReportPartB)).groupBy(// 
        x -> ((HasMmsi) x.message()).getMmsi()).flatMap(o -> // 
        o.scan(// 
        new Timed<State>(new State(o.getKey(), null, null, null, null, null), 0L), (timed, x) -> {
            State state = timed.object;
            String name = state.name;
            String callsign = state.callsign;
            Integer imo = state.imo;
            Integer shipType = state.shipType;
            AisClass aisClass = state.aisClass;
            if (x.message() instanceof AisShipStaticA) {
                AisShipStaticA a = (AisShipStaticA) x.message();
                callsign = a.getCallsign();
                name = a.getName();
                imo = a.getImo().orElse(null);
                shipType = a.getShipType();
                aisClass = AisClass.A;
            } else if (x.message() instanceof AisPositionBExtended) {
                AisPositionBExtended a = (AisPositionBExtended) x.message();
                name = a.getName();
                shipType = a.getShipType();
                aisClass = AisClass.B;
            } else if (x.message() instanceof AisBStaticDataReportPartA) {
                AisBStaticDataReportPartA a = (AisBStaticDataReportPartA) x.message();
                if (a.getName().isPresent()) {
                    name = a.getName().get();
                }
                aisClass = AisClass.B;
            } else if (x.message() instanceof AisBStaticDataReportPartB) {
                aisClass = AisClass.B;
            }
            return new Timed<State>(new State(o.getKey(), aisClass, name, callsign, imo, shipType), x.time());
        }).skip(// 
        1).distinctUntilChanged(ts -> ts.object)).doOnNext(x -> {
            State y = x.object;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
            String line = // 
            y.mmsi + "," + sdf.format(new Date(x.time)) + // 
            "," + y.aisClass + // 
            "," + integer(y.imo) + // 
            "," + integer(y.shipType) + // 
            "," + string(y.name) + ",";
            out.println(line);
        }).subscribe();
    }
}
Also used : PrintStream(java.io.PrintStream) AisBStaticDataReportPartA(au.gov.amsa.ais.message.AisBStaticDataReportPartA) Date(java.util.Date) TimeZone(java.util.TimeZone) AisClass(au.gov.amsa.risky.format.AisClass) AisShipStatic(au.gov.amsa.ais.message.AisShipStatic) SimpleDateFormat(java.text.SimpleDateFormat) IOException(java.io.IOException) AisPositionBExtended(au.gov.amsa.ais.message.AisPositionBExtended) File(java.io.File) AisBStaticDataReportPartB(au.gov.amsa.ais.message.AisBStaticDataReportPartB) HasMmsi(au.gov.amsa.ais.HasMmsi) Streams(au.gov.amsa.ais.rx.Streams) AisShipStaticA(au.gov.amsa.ais.message.AisShipStaticA) PrintStream(java.io.PrintStream) AisPositionBExtended(au.gov.amsa.ais.message.AisPositionBExtended) Date(java.util.Date) HasMmsi(au.gov.amsa.ais.HasMmsi) AisShipStatic(au.gov.amsa.ais.message.AisShipStatic) AisClass(au.gov.amsa.risky.format.AisClass) AisBStaticDataReportPartA(au.gov.amsa.ais.message.AisBStaticDataReportPartA) AisBStaticDataReportPartB(au.gov.amsa.ais.message.AisBStaticDataReportPartB) AisShipStaticA(au.gov.amsa.ais.message.AisShipStaticA) SimpleDateFormat(java.text.SimpleDateFormat)

Aggregations

AisShipStatic (au.gov.amsa.ais.message.AisShipStatic)4 AisShipStaticA (au.gov.amsa.ais.message.AisShipStaticA)4 Streams (au.gov.amsa.ais.rx.Streams)4 File (java.io.File)4 AisMessage (au.gov.amsa.ais.AisMessage)3 Timestamped (au.gov.amsa.ais.Timestamped)3 TimestampedAndLine (au.gov.amsa.ais.rx.Streams.TimestampedAndLine)3 Logging (com.github.davidmoten.rx.slf4j.Logging)3 PrintStream (java.io.PrintStream)3 SimpleDateFormat (java.text.SimpleDateFormat)3 Date (java.util.Date)3 List (java.util.List)3 Optional (java.util.Optional)3 TimeZone (java.util.TimeZone)3 TreeSet (java.util.TreeSet)3 Observable (rx.Observable)3 Func1 (rx.functions.Func1)3 AisShipStaticUtil (au.gov.amsa.ais.message.AisShipStaticUtil)2 Preconditions (com.github.davidmoten.guavamini.Preconditions)2 Checked (com.github.davidmoten.rx.Checked)2