NetLogo / CSV-Extension

A NetLogo extension for reading CSV
5 stars 6 forks source link

NetLogo CSV extension

This NetLogo extension adds CSV parsing capabilities to models.

Building

Run sbt package.

If compilation succeeds, csv.jar will be created. This file and commons-csv-1.0.jar should then be placed in a folder named csv in your NetLogo extensions directory.

Common use cases and examples

Read a file all at once

Just use csv:from-file "/path/to/myfile.csv"! See from-file for more information.

Read a file one line at a time

For really big files, you may not want to store the entire file in memory, but rather just process it a line at a time. For instance, if you want to sum each of the columns of a numeric CSV file, you can do:

You can also use this technique to...

Read a file one line per tick

Here's an example model that reads in a file one line per tick:

Write a file

Just use csv:to-file "/path/to/myfile.csv" my-data! See to-file for more information.

Primitives

Formatting NetLogo data as CSV

csv:to-row csv:to-string csv:to-file

Parsing CSV input to NetLogo data

csv:from-row csv:from-string csv:from-file

csv:from-row

Parses the given string as though it were a row from a CSV file and returns it as a list of values. For example:

Quotes can be used when items contain commas:

You can put two quotes in a row to put an actual quote in an entry. If the entry is not quoted, you can just use one quote:

Number-like-entries will be parsed as numbers:

true and false with any capitalization will be parsed as booleans:

To use a different delimiter, you can specify a second, optional argument. Only single character delimiters are supported:

Different types of values can be mixed freely:

csv:from-string

Parses a string representation of one or more CSV rows and returns it as a list of lists of values. For example:

csv:from-file

Parses an entire CSV file to a list of lists of values. For example, if we have a file example.csv that contains:

1,2,3
4,5,6
7,8,9
10,11,12

Then, we get:

The parser doesn't care if the rows have different numbers of items on them. The number of items in the rows list will always be <number of delimiters> + 1, though blank lines are skipped. This makes handling files with headers quite easy. For instance, if we have header.csv that contains:

My Data
2/1/2015

Parameters:
start,stop,resolution,population,birth?
0,4,1,100,true

Data:
time,x,y
0,0,0
1,1,1
2,4,8
3,9,27

This gives:

csv:to-row

Reports the given list as a CSV row. For example:

csv:to-string

Reports the given list of lists as a CSV string. For example:

csv:to-file

Writes the given list of lists to a new CSV file. For example:

will result in a file myfile.csv containing:

1,two,3
4,5