Simstock API docs
The simstock.SimstockDataframe class
- class simstock.SimstockDataframe(inputobject: Any, polygon_column_name: str = None, uid_column_name: str = None, epw_file: str = None, tol: float = 0.1, use_base_idf: str = False, idd_file: str = None, **kwargs)
A
SimstockDataframeis an object used by Simstock to store all input data and perform the necessary geometric simplification steps to make it a compatable with EnergyPlus. It behaves the in the same way as a PandasDataFrame, but with some key additional methods to perform geometric-based pre-processing.The
SimstockDataframeobject also stores EnergyPlus settings, such as constructions, materials, and schedules. The class provides an interface for viewing and editing these settings. The settings can be viewed via theSimstockDataframe’s properties; e.g..constructionsto view constructions, or.schedulesto view schedules. These settings are stored in the form of Eppy EpBunch objects which can be edited directly (see examples below). Settings can also be set by usingcsvfiles (see example below andoverride_settings_with_csv()). By default theSimstockDataframewill contain some standard settings. If you wish to start from a blank slate with no settings so that you can specify all of them yourself, then specifiyuse_base_idf=Truewhen constructing theSimstockDataframe.Once the settings and data have been set, the
preprocessing()method can be used to ensure all geometries are compatable with E+, such as adjacent coordinates being a suitable tolerance away from each other (see example below). An EnergyPlus simulation can then be run using theIDFmanagerclass.- Parameters:
inputobject (dict,
DataFrame,SimstockDataframe) – The geometric data, containing polygons, a unique identifier, shading etc.polygon_coloumn_name (str) – Optional. The name of the column or field containing the geometric data (which should either be shapely objects or wkb or wkt strings). This is only required if the column is named something other that
polygonuid_column_name (str) – Optional. The name of the column containing the unique IDs. This is only required if the ID column name is something other than
osgbepw_file (str) – Optional. The file name, including the path, to your epw weather file. If none is specified, Simstock will default to using the St. James’s park epw data
tol (float) – Optional. The minimum distance in metres that two coordinates are allowed to be after geometric simplification. EnergyPlus requires this to be at least 0.1m.
use_base_idf (bool) – Optional Whether or not to start with a blank slate settings object, so that you can populate the settings from scratch. Defaults to False
idd_file (str) – Optional The file name, including the path, to your EnergyPlus .idd file. If none is specified, Simstock will look in common locations, such as
C:\EnergyPlus*\if you are running Windows or/usr/local/EnergyPlus*or/Applications/EnergyPlus*if you are running Unix (note * will be the version number)
- Raises:
SystemError – If your operating systemm is of unknown type
FileNotFoundError – If an EnergyPlus .idd file could not be found
TypeError – If the input data is not a dict,
DataFrame, orSimstockDataframe, or if your polygon data is not comprised of shapely objects or wkb or wkt stringsKeyError – If a valid unique ID column could not be found. Hint: if your ID column is named something other than
osgb, then specifiy its name using the uid_column_name parameter
See also:
IDFmanagerExample
import simstock as sim # Create a SimstockDataframe from an already existing dict d sdf = sim.SimstockDataframe(d)
If your EnergyPlus installation, and therfore your .idd file is stored in a non-standard place, then use the idd_file parameter:
sdf = sim.SimstockDataframe( d, idd_file="pathto/myenergyplusinstallation/my_idd_file.idd" )
To view settings, e.g. the materials:
mats = sdf.materials print(mats)
Each setting is an Eppy EpBunch object; e.g.,
# This is a list of EpBunch objects, # one for each material mats = sdf.materials # print the first material in the list print(mats[0])
returns:
MATERIAL, 10mm_carpet, !- Name Rough, !- Roughness 0.01, !- Thickness 0.058, !- Conductivity 20, !- Density 1000, !- Specific Heat 0.9, !- Thermal Absorptance 0.5, !- Solar Absorptance 0.5; !- Visible AbsorptanceTo edit any field in each bunch, you can do ``bunchobject.Fieldname`. For example, to edit the Name field of the material above:
# Change the name mats[0].Name = "new_name" # Now print to see the new name print(mats[0])
returns:
MATERIAL, 10mm_carpet, !- new_name Rough, !- Roughness 0.01, !- Thickness 0.058, !- Conductivity 20, !- Density 1000, !- Specific Heat 0.9, !- Thermal Absorptance 0.5, !- Solar Absorptance 0.5; !- Visible AbsorptanceAs another example, let’s adjust the heat balance algorithm:
# Print the heat balance algorithm EpBunch print(sdf.heat_balance_algorithm)
returns:
HEAT_BALANCE_ALGORITHM, ConductionTransferFunction, !- Algorithm 200; !- Surface Temperature Upper LimitNow edit the surface temperature upper limit field and print the result:
sdf.heat_balance_algorithm.Surface_Temperature_Upper_Limit = 210 print(heat_balance_algorithm)
gives:
HEAT_BALANCE_ALGORITHM, ConductionTransferFunction, !- Algorithm 210; !- Surface Temperature Upper LimitSettings can be edited in this programmatic fashion, or, alternatively, settings can be read in as csv files (see
override_settings_with_csv()andcreate_csv_folder()). To do this, it is recommended to start from a blank settings template by doing:# Use the use_base_idf option to start from a blank settings template sdf = sim.SimstockDataframe(d, use_base_idf=True)
Once you are satisfied with the settings, you can run the
preprocessing()function, to get the data ready for an EnergyPlus simulation:# Perform all necessary geometric simplification steps sdf.preprocessing()
Note
The
SimstockDataframeconstructor creates aSimstockDataframefrom an object such as dict or PandasDataFramethat has been already instantiated and is in memory. To create aSimstockDataframefrom a file, see the functionsread_csv(),read_json(),read_parquet(), andread_geopackage_layer().Class properties:
- tol: float
The minumum allowable distance between adjacent coordinates in a polygon
Example
# Create a SimstockDaframe with tolerance 20cm sdf = sim.SimstockDataframe(d, tol=0.2) # View the tolerance print(sdf.tol) # Change the tolerance to 10cm sdf.tol = 0.1
- property is_exterior_ccw: list[bool]
True if polygon exteriors are counter-clockwise
- property is_valid: list[bool]
True if the polygon column’s objects are valid shapely geometries
- property length: int
Number of data entries in this SimstockDataframe
- property built_islands: int
The number of built islands
- property materials: list
The list of materials (in
eppy.bunch_subclass.EpBunchformat)Example
# Print each material's EpBunch for mat in sdf.materials: print(mat) # Change the name of the first material in the list sdf.materials[0].Name = "some_new_name"
- property material_nomass: list
The list of no-mass materials (in
eppy.bunch_subclass.EpBunchformat)
- property window_material_glazing: list
The list of window glazing materials (in
eppy.bunch_subclass.EpBunchformat)
- property window_material_gas: list
The list of window gas layer materials (in
eppy.bunch_subclass.EpBunchformat)
- property constructions: list
The list of constructions (in
eppy.bunch_subclass.EpBunchformat)Example
# Print each constructions's EpBunch for cons in sdf.sonstructions: print(cons) # Change the name of the first construction in the list sdf.constructions[0].Name = "some_new_name"
- property schedules: list
The list of schedules (in
eppy.bunch_subclass.EpBunchformat)
- property building: EpBunch
eppy.bunch_subclass.EpBunchobject containing the building simulation options:“Name”, defaults to “building”
“North Axis”, defaults to 0
“Terrain”, defaults to “City”
“Loads Convergence Tolerance Value”, defaults to 0.04
“Temperature Convergence Tolerance Value”, defaults to 0.4
“Solar Distribution”, defaults to “FullExerior”
“Maximum Number of Warmup Days”, defaults to 25
“Minimum Number of Warmup Days”, defaults to 6
- property simulation_control: EpBunch
eppy.bunch_subclass.EpBunchobject containing the building simulation options:“Name”, defaults to “building”
“North Axis”, defaults to 0
“Terrain”, defaults to “City”
“Loads Convergence Tolerance Value”, defaults to 0.04
“Temperature Convergence Tolerance Value”, defaults to 0.4
“Solar Distribution”, defaults to “FullExerior”
“Maximum Number of Warmup Days”, defaults to 25
“Minimum Number of Warmup Days”, defaults to 6
- property shadow_calculation: EpBunch
eppy.bunch_subclass.EpBunchobject containing the shadow calculation options:“Calculation Method”, defaults to “AverageOverDaysInFrequency”
“Calculation Frequency”, defaults to 20
“Maximum Figure in Shadow Overlap Calculations”, defaults to 15000
“Polygon Clipping Algorithm”, defaults to “SutherlandHodgman”
“Sky Diffuse Mofeling Algorithm”, defaults to “SimpleSkyDiffuseModeling”
- property inside_convection_algorithm: EpBunch
eppy.bunch_subclass.EpBunchobject containing the inside surface convection algorithm, defaults to “TARP”
- property outside_convection_algorithm: EpBunch
eppy.bunch_subclass.EpBunchobject containing the outside surface convection algorithm, defaults to “TARP”
- property heat_balance_algorithm: EpBunch
eppy.bunch_subclass.EpBunchobject containing the heat balance algorithm options:“Algorithm”, defaults to “ConductionTransferFunction
“Surface Temperature Upper Limit”, defaults to 200
- property timestep: int
The number of timesteps per hour, defaults to 4
- property run_period: EpBunch
eppy.bunch_subclass.EpBunchobject containing the run period options:“Name”, defaults to NA
“Begin Month”, defaults to 1
“Begin Day of Month”, defaults to 1
“End Month”, defaults to 12
“End Day of Month”, defaults to 31
“Day of Week for Start Day”, defaults to “Monday”
“Use Weather File Holidays and Special Days”, defaults to “Yes”
“Use Weather File Daylight Saving Period”, defaults to “Yes”
“Apply Weekend Holiday Rule”, “defaults to “No”
“Use Weather File Rain Indicators”, defaults to “Yes”
“Use Weather File Snow Indicators”, defaults to “Yes”
“Number of Times Runperiod to be Repeated”, defaults to 1
- property schedule_type_limits: list
List of
eppy.bunch_subclass.EpBunchobjects containing schedule type limits
- property schedule_constant: EpBunch
eppy.bunch_subclass.EpBunchobject containing constant schedule options:“Name”, defaults to “Always 4”
“Schedule Type Limits Name”, defaults to “Control Type”
“Hourly Value”, defauts to 4
- property people: list
The list of people types (in
eppy.bunch_subclass.EpBunchformat)
- property lights: list
The lighting list (in
eppy.bunch_subclass.EpBunchformat)
- property electric_equipment: list
The list of electrical equipment (in
eppy.bunch_subclass.EpBunchformat)
- property thermostat: list
The list of thermostats (in
eppy.bunch_subclass.EpBunchformat)
- property thermostat_dual_setpoint: list
The list of thermostat dual set points (in
eppy.bunch_subclass.EpBunchformat)
- property output_variable_dictionary: EpBunch
The output variable dictionary (in
eppy.bunch_subclass.EpBunchformat)
- property output_variable: list
The list of desired EnergyPlus simulation output variables (in
eppy.bunch_subclass.EpBunchformat)
- property output_diagnostics: EpBunch
The EnergyPlus simulation output diagnostics (in
eppy.bunch_subclass.EpBunchformat)
- print_settings() None
Function to print the entire settings in a readable format. Interally, the SimstockDataframe stores settings as an
IDFobject. This function essentially displays this object.Example
# Given a simstockdataframe sdf sdf.print_settings()
Idividual settings, such as
constructionscan be viewed and edited using the invidual settings properties, such asconstructions()
- create_csv_folder(settings_csv_path: str = 'simulation_settings') None
Function to create an empty directory full of csv files, into which you can add your settings. The directory will have the following structure:
simulation_settings/├── DB-Fabric-CONSTRUCTION.csv├── DB-Fabric-MATERIAL_NOMASS.csv├── DB-Fabric-MATERIAL.csv├── DB-Fabric-WINDOWMATERIAL_GAS.csv├── DB-Fabric-WINDOWMATERIAL_GLAZING.csv├── DB-HeatingCooling-OnOff.csv├── DB-Loads-ELECTRICEQUIPMENT.csv├── DB-Loads-LIGHTS.csv├── DB-Loads-PEOPLE.csv├── DB-Schedules-SCHEDULE_COMPACT.csv├── infiltration_dict.json└── ventilation_dict.jsonThe
override_settings_with_csv()method can then be used to set the SimstockDataframe’s internal settings using these csv files.- Parameters:
settings_csv_path – Optional. The name of the directory (including the full path from your current working directory) into which to place the csv files. Defaults to
simulation_settings/, which we be placed in your working directory
Warning
If the directory settings_csv_path (default: “simulation_settings/”) already exists, then it will be overwritten.
- override_settings_with_csv(**kwargs) None
Function that reads in the settings stored in the csv files in the directory
settings_csv_path(default `` simulation_settings``) and uses them to set the internal SimstockDataframe settings, such as materials etc.An
FileNotFoundErrorwill be raised if thesettings_csv_pathdirectory cannot be found. In this case, either call thecreate_csv_folder()method to create it, or specify the path to one that already exists using the SimstockDataframe’ssettings_csv_pathproperty. Equivalently, you could specify this as a key word argument when calling theoverride_settings_with_csv().- Parameters:
**kwargs – Optional keyword parameters, such as settings_csv_path or any of the other SimstockDataframe properties
- Raises:
FileNotFoundError – If the settings_csv_path does not exist or has not been specified.
KeyError – If the input csv data contains unrecognised fields. Try running
create_csv_folder()to generate correctly formated files.
See also:
create_csv_folder()Example
# If you already have settings csv files saved in a directory # called my_directory within your working directory, you could call: sdf.override_settings_with_csv(settings_csv_path="my_directory")
- orientate_polygons(**kwargs) None
Function to ensure that polygon exteriors are orientated anticlockwise annd interiors clockwise. This is to ensure internal consistency.
- Parameters:
**kwargs – Optional keyword parameters: any of the SimstockDataframe properties
- remove_duplicate_coords(**kwargs) None
Function to remove duplicated coordinates from polygons, while ensuring the polygons remain valid shapely objects.
- Parameters:
**kwargs – Optional keyword parameters: any of the SimstockDataframe properties
Example
import simstock as sim sdf = sim.read_csv("path/to/file.csv") sdf.remove_duplicate_coords()
- polygon_topology(**kwargs) None
Function that checks whether polygons are touching or interecting each other. If any intersections are detected, an error is thrown.
This function adds an additonal column to the SimstockDataframe called
touching. The ith entry intouchinglists theosbgvalues of all polygons touching the polygon in row i.- Parameters:
**kwargs – Optional keyword parameters: any of the SimstockDataframe properties
- Raises:
ValueError - If any polygons are touching.
Example
import simstock as sim sdf = sim.read_csv("path/to/file.csv") sdf.polygon_topology()
- polygon_tolerance(**kwargs) None
A function to assess which polygons need simplifying, based on a user-specifed tolerance. This can be set via the tol property, or also via the key word arguments of this function.
Simplification here means removing intermediate coordinates in a shape while preserving the shapes topology. Coordinates that are closer together than some tolerance are candidates for removal.
This function adds a boolean column named
simplifywhich specifies whether each polygon needs simplifying or not, based on the tolerance. A value in this column will be True if the corresponding geometry contains coordinate that are closer together than tol (in metres). This is important bacause EnergyPlus requires that no two coordinates are closer together than 0.1m.- Parameters:
**kwargs – Optional keyword parameters: any of the SimstockDataframe properties
Example
# To check if any polygons have coordinates closer than # 0.2m together, first call sdf.polygon_tolerance(tol=0.2) # This will add a new column called simplify, which # can now be viewed: print(sdf["simplify"])
- polygon_simplification(**kwargs) None
Function that simplifies polygons, by e.g. exploiting transitivity of points and merging points within tolerances, such that no polygons contain coordinates closer together than
tol.Only functions that have been marked for simplification by the
polygon_tolerance()function will be simplified. Therefore,polygon_tolerance()must be called first.- Parameters:
**kwargs – Optional keyword parameters: any of the SimstockDataframe properties
- Raises:
KeyError - If no
simplifycolumn can be found, meaning thatpolygon_tolerance()has not yet been called.
See also:
polygon_tolerance()
- collinear_exterior(**kwargs) None
Function that removes collinear points from polygons and determines exterior surfaces.
- Parameters:
**kwargs – Optional keyword parameters: any of the SimstockDataframe properties
- bi_adj(**kwargs) None
Function to group buildings into built islands (BIs). E.g. two semi-detatched houses in BIs. This adds a new column to the SimstockDataframe called BI, which contains unique building island IDs.
- Parameters:
**kwargs – Optional keyword parameters: any of the SimstockDataframe properties
- Raises:
ValueError - If building islands are unable to be resolved.
- preprocessing(**kwargs) None
Function to perform default all the necessary geometric simplification and processing on the SimstockDataframe to make it EnergyPlus compatable. Specifically this function takes ensures all the necessary conditions ar met, such as no adjacent coordinates ina polygon being closer than 0.1m together.
This function calls the following functions in order:
In essence, this function first checks that all polygons are correctly orientated. It then proceeds to remove duplicate coordinates and simplify polygons while ensuring that polygons do not intersect each other.
- Parameters:
**kwargs – Optional keyword parameters: any of the SimstockDataframe properties
Hint
You can instead call functions 1. to 9. above manually for finer grained control.
The simstock.IDFmanager class
- class simstock.IDFmanager(data: SimstockDataframe, min_avail_width_for_window: float | int = 1, min_avail_height: float | int = 80, out_dir: str = 'outs', bi_mode: bool = True, data_fname: str = None, save_building_count: bool = False, epw: str = None, buffer_radius: float | int = 50, ventilation_dict: dict = None, infiltration_dict: dict = None)
An
IDFmanageris a container object used to create elements for an EnergyPlus simulation. The object contains functions to take geometric and contextual data in the form of a SimstockDataframe, and create an IDF file or Eppy IDF object for an E+ run.- Parameters:
data (
simstock.SimstockDataframe) – The input data containing polygon information, and optionally built-island data.min_avail_width_for_window (float, int) – Optional. Do not place window if the wall width is less than this number
min_avail_height (float, int) – Optional. Do not place window if partially exposed external wall is less than this number % of zone height
out_dir (str) – Optional. The directory (including full file path) into which to place the EnergyPlus output files, defaults to
outs/bi_mode (bool) – Optional. Whether or not to group buildings into built islands (BIs)
data_fname (str) – Optional. Unique name for this simuation project. Only necessary if you want to save the building count, in which case that information will be saved to a file called data_fname within the out_dir directory
save_building_count (bool) – Optional. Whether or not to save the number of buildings being simulated to a file called data_fname within out_dir. If not data_fname is supplied, then a unique string will be generated for the file name instead
epw (str) – Optional. Path and file name of an epw weather file to use for the weather settings. If none is specified, the St. James’s park weather data will be used instead
buffer_radius (float, int) – Optional. The distance in metres of building buffers
ventilation_dict (dict) – Optional. Dictioary containing ventilation settings. If none is specified, then default settings will be used
infiltration_dict (dict) – Optional. Dictionary containing infiltration settings. If none is specified, then default settings will be used
- Raises:
TypeError – If the input data is not of type
simstock.SimstockDataframeSimstockException – If the input data does not contain the necessary fields. (See data specification above)
Example
# Basic usage example # given a SimstockDataframe sdf simulation = sim.IDFmanager(sdf) # Now compute model IDFs for each built island simulation.create_model_idf(bi_mode=True) # Run E+ simulation, this will put outputs into outs/ folder by default simulation.run()
See also:
SimstockDataframe- property is_valid: bool
Are all of the necessary column names present
- property missing_columns: list
Necessary column names that are missing from the data
- create_model_idf(**kwargs) None
Function to create IDF objects for each built island (if bi_mode=True), or else a single IDF for the entire model.
Creates a new attibute called bi_idf_list containing all the created IDF objects. Each of these can be used to run a simulation.
Example
# Assuming we have a correctly processed SimstockDataframe sdf, # instantiate a IDFmanager object simulation = sim.IDFmanager(sdf) # Now compute IDFs for each built island simulation.create_model_idf(bi_mode=True) # This will create a list constaining the IDFs for each BI # This can be accessed via idf_list = simulation.bi_idf_list print(idf_list) # Alternatively, we can create a single IDF for the whole # model using the command simulation.create_model_idf(bi_mode=False) # This will create a list of length 1 called bi_idf_list # which will contain the single IDF for the model # This can be accessed via model_idf = simulation.bi_idf_list[0]
- Parameters:
**kwargs – Optional keyword parameters, such as bi_mode or any of the other IDFmanager properties
See also:
save_idfs()– Used to save the IDF objects
- save_idfs(**kwargs) None
Function to save the IDF objects in a directory. By default, this directory will be called “outs/” and be located in the working directory. A different directory can be specified by the parameter or keyword argument “out_dir”.
Each IDF object is saved in its own file within the directory, and will be named “built_island_i.idf”, where “i” will be the index of each built island. If built island mode is not being used (bi_mode=False), then only a single IDF is saved.
- Parameters:
**kwargs – Optional keyword parameters, such as out_dir or any of the other IDFmanager properties
- Raises:
SimstockException – If no IDF objects yet exist. This is likely because
create_model_idf()has not yet been called
Example
# Output the idf objects to some folder of your choice simulation.save_idfs(out_dir="path/to/some_folder")
- run(**kwargs) None
Function to run an EnergyPlus simulation on each of the model IDF objects created by
create_model_idf(). The settings used for the simulation will be those specified within theSimstockDataframe.The EnergyPlus output files resulting from the simulations will be saved into a directory. By default, this directory will be called “outs/” and be located in the working directory. A different directory can be specified by the parameter or keyword argument “out_dir”. Within this directory, a further subdirectory will be made for each simulation (one per built island) containind all E+ files. Each subdirectory will be called “built_island_i_ep_outputs” where “i” will be the index of the built island. If built island mode is not being used (bi_mode=False), then only a single such subdirectory will be created.
- Parameters:
**kwargs – Optional keyword parameters, such as out_dir or any of the other IDFmanager properties
# Assuming creat_model_idf() has already been called to # create the model IDFs. We can check how many IDFs, # corresponding to the number of built islands there # are by doing no_bi = len(simulation.bi_idf_list) # If bi_mode=False, then no_bi will equal 1. Now when we call # run(), it will create no_bi subdirectories inside out_dir # directory. E.g. simulation.run() # This will have created, by default a directory called outs/ # containing at least one subdirectory containing E+ outputs
Data reading functions
- simstock.read_csv(path: str, **kwargs) SimstockDataframe
Function to read in a
csvfile and return aSimstockDataframe. It must conform to Simstock data standards; i.e., it must contain apolygoncolumn or key or field containing shapely geometry data or similar as well as a column of unique IDs called “osgb”. Additional columns “shading”, “height”, “wwr”, “nofloors” and “construction” must be present. Seesimstock.SimstockDataframefor full data specifications.If the unique ID and geometry data columns are named something other than
osgbandpolygonrespectively, then their names can be specified using the kwargs. See example below.Example
import simstock as sim # To read in data with that has column names osgb, polygon etc sdf = sim.read_csv("/pathtofile/examplefile.csv") # If the data's geometric data is named something other than # polygon, say in this case it is called geom, then we can do sdf = sim.read_csv( "/pathtofile/examplefile.csv", polygon_column_name="geom" ) # Also, if the unique ID column is something other than osgb, # say its called uuid in this case, then we can do sdf = sim.read_csv( "/pathtofile/examplefile.csv", polygon_column_name="geom", uid_column_name="uuid" )
- Parameters:
path (str) – The file path including the
csvfile**kwargs – optional keyword argumetns to be passed to the SimstockDataframe constructor. See
simstock.SimstockDataframedocs for details of allowed arguments.
- Returns:
A
simstock.SimstockDataframecontaining the data and settings. Seesimstock.SimstockDataframedocs for full list of attributes, properties and methods.- Raises:
TypeError – If
csvfile does not conform to Simstock standards.
- simstock.read_json(path: str, **kwargs) SimstockDataframe
Function to read in a
jsonfile and return aSimstockDataframe. It must conform to Simstock data standards; i.e., it must contain apolygoncolumn or key or field containing shapely geometry data or similar as well as a column of unique IDs called “osgb”. Additional columns “shading”, “height”, “wwr”, “nofloors” and “construction” must be present. Seesimstock.SimstockDataframefor full data specifications.If the unique ID and geometry data columns are named something other than
osgbandpolygonrespectively, then their names can be specified using the kwargs. See example below.Example
import simstock as sim # To read in data with that has column names osgb, polygon etc sdf = sim.read_json("/pathtofile/examplefile.json") # If the data's geometric data is named something other than # polygon, say in this case it is called geom, then we can do sdf = sim.read_json( "/pathtofile/examplefile.json", polygon_column_name="geom" ) # Also, if the unique ID column is something other than osgb, # say its called uuid in this case, then we can do sdf = sim.read_json( "/pathtofile/examplefile.json", polygon_column_name="geom", uid_column_name="uuid" )
- Parameters:
path (str) – The file path including the
jsonfile**kwargs – optional keyword argumetns to be passed to the SimstockDataframe constructor. See
simstock.SimstockDataframedocs for details of allowed arguments.
- Returns:
A
simstock.SimstockDataframecontaining the data and settings. Seesimstock.SimstockDataframedocs for full list of attributes, properties and methods.- Raises:
TypeError – If
jsonfile does not conform to Simstock standards.
- simstock.read_parquet(path: str, **kwargs) SimstockDataframe
Function to read in a
parquetfile and return aSimstockDataframe. It must conform to Simstock data standards; i.e., it must contain apolygoncolumn or key or field containing shapely geometry data or similar as well as a column of unique IDs called “osgb”. Additional columns “shading”, “height”, “wwr”, “nofloors” and “construction” must be present. Seesimstock.SimstockDataframefor full data specifications.If the unique ID and geometry data columns are named something other than
osgbandpolygonrespectively, then their names can be specified using the kwargs. See example below.Example
import simstock as sim # To read in data with that has column names osgb, polygon etc sdf = sim.read_parquet("/pathtofile/examplefile.parquet") # If the data's geometric data is named something other than # polygon, say in this case it is called geom, then we can do sdf = sim.read_parquet( "/pathtofile/examplefile.parquet", polygon_column_name="geom" ) # Also, if the unique ID column is something other than osgb, # say its called uuid in this case, then we can do sdf = sim.read_parquet( "/pathtofile/examplefile.parquet", polygon_column_name="geom", uid_column_name="uuid" )
- Parameters:
path (str) – The file path including the
parquetfile**kwargs – optional keyword argumetns to be passed to the SimstockDataframe constructor. See
simstock.SimstockDataframedocs for details of allowed arguments.
- Returns:
A
simstock.SimstockDataframecontaining the data and settings. Seesimstock.SimstockDataframedocs for full list of attributes, properties and methods.- Raises:
TypeError – If
parquetfile does not conform to Simstock standards.
- simstock.read_geopackage_layer(path: str, layer_name: str, **kwargs) SimstockDataframe
Function to read in a layer of a geopackage
.gpkgfile and return aSimstockDataframe. The data should contain a column of unique IDs as well as columns “shading”, “height”, “wwr”, “nofloors” and “construction” must be present. Seesimstock.SimstockDataframefor full data specifications.The geometric data can need not be specified manually. Once the geopackage layer has been read in, the geometric data will be available to view using the polygon attribute of the the SimstockDataframe.
Note
The name of the layer must be specified. If you do not know the layer names in your geopackage, you can use the helper function
get_gpkg_layer_names().Example
import simstock as sim # To read in data with that has column names osgb, polygon etc sdf = sim.read_geopackage_layer("/pathtofile/examplefile.gpkg", "my_layer")
- Parameters:
path (str) – The file path including the
csvfilelayer_name (str) – The name of the geopackage_layer to be read
**kwargs – optional keyword argumetns to be passed to the SimstockDataframe constructor. See
simstock.SimstockDataframedocs for details of allowed arguments.
- Returns:
A
simstock.SimstockDataframecontaining the data and settings. Seesimstock.SimstockDataframedocs for full list of attributes, properties and methods.- Raises:
TypeError – If
csvfile does not conform to Simstock standards.
See also:
get_gpkg_layer_names()
- simstock.get_gpkg_layer_names(path: str) list[str]
Function to get thr names of all geographical layers from a geopackage file
Example
import simstock as sim # Print all the layer names in a file for layer in sim.get_gpkg_layer_names("pathto/myfile.gpkg"): print(layer)
- Parameters:
path (str) – The file name (including path from your working directory) of the geopackage
- Returns:
A list of the names of the layers
The simstock.plot() function
- simstock.plot(sdf: SimstockDataframe | Series | DataFrame, facecolor: str = 'lightblue', edgecolor: str = 'red', polygon_column_name: str = 'polygon', **kwargs) Axes
Function to plot geometric data from either a
SimstockDataframe, PandasDataFrame, or PandasSeriesusing matplotlib.pyplot. The geometric data column should be namedpolygon; if it is named anything else then it should be specified using the polygon_column_name parameter. You may also pass a matplotlibAxesobject via the optional parameter ax, in order to plot onto an existing axis (see examples below).- Parameters:
sdf (Union[SimstockDataframe, Series, DataFrame]) – The
SimstockDataframe, Pandas :py:class`DataFrame`, or PandasSeriescontaining the geometric data to be plotted. This data must be in the form of shapely geometries: eitherPolygon,Point, orLineString.facecolor (str) – Optional. The fill colour of the shapesm defaults to
lightblueedgecolor (str) – Optional. The border colour of the shapes, defaults to
redpolygon_column_name (str) – Optional. The name of the column containing the geographical data to be plotted, defaults to
polygon**kwargs – Optional keyword parameters to be passed to matplotlib; e.g.
ax
- Returns:
A
Axesobjects containing the plotted geometric data- Raises:
TypeError – If the geometric data are not valid Shapely
Polygon,Point, orLineString
Example
# Basic usage import matplotlib.pyplot as plt import simstock as sim # Create test simstockdataframe sdf = sim.read_csv("testdata.csv") # Plot sim.plot(sdf, facecolor="lightblue", edgecolor="red") plt.show()
Advanced example: plotting to an already existing axes in order to add a background image
import matplotlib.pyplot as plt import simstock as sim # Create test simstockdataframe sdf = sim.read_csv("testdata.csv") # Create matplotlib figure and axis fig = plt.figure() ax = fig.add_subplot(111) # Read in an image to be used as a background map bg_img = plt.imread("pathto/background_map.png") # Plot the background map ax.imshow(bg_img) # Plot the data the existing axis, thereby overlaying # it onto the background map sim.plot( sdf, facecolor="lightblue", edgecolor="red", ax=ax ) # Set some attributes ax.title("Test Plot") ax.set_xticks([]) ax.set_yticks([]) # Display plot plt.show()