LogoLogo
HomeWeb PlatformForum
  • User Manual
  • Get Started
    • Create a Pollination Account
    • Setting up an Organization
      • 1. Create an Organization
      • 2. Add Organization Seats
      • 3. Add Team Members
      • 4. Purchase and Manage CAD Licenses
      • 5. Manage License Pools
      • 6. Add Additional Computing Resources
    • Setting up Rhino, Grasshopper and Revit Plugins
      • Download CAD Plugins
      • Install CAD Plugins
      • Purchase and Manage CAD Plugins
      • The Difference between CAD Licenses and Organization Seats
  • REVIT PLUGIN
    • Getting Started in Revit
    • Exporting Energy Models from Revit
      • Understanding the Export Process
      • Managing Pollination Revit License
      • Setting Up Linked Models
      • Creating Snapshots
      • Editing and Exporting Snapshots
    • Modeling Best Practices
  • Model Editor
    • What is Pollination Model Editor
    • Getting Started
    • Workflows
    • Commands
      • By Use Case
        • Room Commands
          • Edit
          • Windows
          • New
          • Adjacency
          • Line
          • Visualize
        • Line Commands
        • Roof Commands
        • Model Commands
      • Alphabetically
        • 3D preview
        • Align
        • Auto align
        • Auto top ground
        • Change units
        • Convert to room2D
        • Create boundary
        • Create rooms
        • Explode polyline
        • Export roofs
        • Fill holes
        • Find adjacency gaps
        • Find roof gaps
        • Find roof intersection
        • Floor area change
        • Generate alignment axes
        • Import roofs
        • Join coplanar faces
        • Join segments
        • Merge Small Rooms
        • Merge rooms
        • Multipliers to geometry
        • Offset
        • Offset windows
        • Preview roofs
        • Pull to room
        • Remove colinear vertices
        • Remove holes
        • Remove short segments
        • Repair windows
        • Resolve roof overlaps
        • Roof to shade
        • Separate plenums
        • Set air boundaries
        • Show tilt
        • Simplify Curved Edges
        • Simplify windows
        • Snap to grid
        • Solve adjacency
        • Split
        • Split core and perimeter
        • Subtract roofs
        • Subtract rooms
        • Validate model
        • Vertically split
    • Supported File Formats
      • Export
      • Import
    • Python Script Editor
      • Your First Python Script
      • Editor Class API Documentation
      • Available Python Libraries
    • FAQ
    • Changelog
  • Rhino Plugin
    • Getting Started in Rhino
    • Modeling Best Practices
      • Create Rooms
      • Create Apertures
      • Create Doors
      • Solve Adjacency
      • Create Shade or Context
      • Editing your Model
      • Using Room Selection Mode
    • Energy Modeling
      • Assign Program Types
      • Assign Construction Sets
      • Assign HVAC Systems
      • Energy Settings and Parameters
      • Run Simulation and Load Results
    • Daylight Modeling
      • Assign Modifier Sets
      • Assign Modifiers
      • Add Sensor Grid
      • Add View
      • Run Simulation and Visualize Daylighting Results
    • Interoperability
      • Ladybug Tools Grasshopper Plugins
        • Entity components
      • Import
        • Import HBJSON
        • Import gbXML
        • Import OSM
        • Import IDF
      • Export
        • Export HBJSON
        • Export gbXML
        • Export OSM and IDF
    • Troubleshooting
      • Rhino Plugin Errors
      • Validation Error Codes
    • Pollination Commands
      • By Use Case
        • General
        • Geometry Setup
        • Model Alignment & Updates
        • Setup & Run Simulation
        • Load, Visualize, and Export Results
      • Alphabetically
        • PO_AddApertureShades
        • PO_AddApertures
        • PO_AddAperturesByWWR
        • PO_AddBuildingShades
        • PO_AddDoors
        • PO_AddOpaqueFaces
        • PO_AddRadialGrid
        • PO_AddRooms
        • PO_AddRoomsByLayer
        • PO_AddSensorGrid
        • PO_AddShades
        • PO_AddSiteContext
        • PO_AddSkylightsByRatio
        • PO_AddView
        • PO_Align2DPlans
        • PO_AlignInElevation
        • PO_AlignInPlan
        • PO_AlignInPlan2D
        • PO_Check2DOrtho
        • PO_CheckAdjacency
        • PO_CheckPlanarity
        • PO_CheckUpdates
        • PO_ColorByBoundaryCondition
        • PO_ColorByFaceNormal
        • PO_ColorByFaceType
        • PO_ConstructionSetManager
        • PO_ConstructionManager
        • PO_DownloadModel
        • PO_DrawApertures
        • PO_DrawDoors
        • PO_DrawPlanarSurface
        • PO_DrawRoom
        • PO_DupAperturesDoors
        • PO_EditApertureProperties
        • PO_EditDoorProperties
        • PO_EditFaceProperties
        • PO_EditInPlace
        • PO_EditProperties
        • PO_EditRoomProperties
        • PO_EditSensorGridProperties
        • PO_EditShadeProperties
        • PO_EditViewProperties
        • PO_EmbedUserLibrary
        • PO_Extrude2DPlans
        • PO_FixRoomChildrenLinks
        • PO_GenAlignGrids
        • PO_GenRoomPerimeters
        • PO_HVACManager
        • PO_IsolateAdjacencies
        • PO_LicenseManager
        • PO_LoadResults
        • PO_MaterialManager
        • PO_MatchChildGeometry
        • PO_MatchRoomProperties
        • PO_MergeRooms
        • PO_ModifierSetManager
        • PO_ModifierManager
        • PO_OffsetChildObjects
        • PO_PluginInfo
        • PO_Pollination
        • PO_ProgramTypeManager
        • PO_ProjectChildToHost
        • PO_ProjectSrf
        • PO_PurgeUserLibrary
        • PO_RebuildRooms
        • PO_RemoveProperties
        • PO_RemoveShortSegments
        • PO_RebuildAperturesDoors
        • PO_ResetBoundaryCondition
        • PO_ResetDisplayName
        • PO_ResetIdentifier
        • PO_ResetLegendLocation
        • PO_ResetResourceIDs
        • PO_RunSimulation
        • PO_SaveToUserLibrary
        • PO_SelApertures
        • PO_SelDoors
        • PO_SelOpaqueFaces
        • PO_SelRooms
        • PO_SelSensorGrids
        • PO_SelShades
        • PO_SelSiteContexts
        • PO_SelViews
        • PO_SetAirBoundariesByGuides
        • PO_SetRoomStoryByElevation
        • PO_ShowObjectNotes
        • PO_SHWManager
        • PO_ScheduleManager
        • PO_SimulationParameter
        • PO_SolveAdjacency
        • PO_SplitRooms
        • PO_SyncModel
        • PO_TestLocalAppEnvironment
        • PO_UnitsSetting
        • PO_UploadModel
        • PO_UserManual
        • PO_ValidateModel
  • Grasshopper Plugin
    • Download and Install the Grasshopper Plugin
    • Grasshopper User Interface
      • 1:Primitives
        • PO_Aperture
        • PO_Door
        • PO_Face
        • PO_Model
        • PO_Room
        • PO_SensorGrid
        • PO_Shade
        • PO_View
        • PO_VisualizationSet
        • PO_Construction
        • PO_ConstructionSet
        • PO_Material
        • PO_Modifier
        • PO_ModifierSet
        • PO_ProgramType
        • PO_Schedule
      • 2:Pollination
        • Check_Run_Inputs
        • Check_Run_Results
        • List_Run_Assets
        • Setup_Runs
        • User_Data
        • Pollinate
        • Check_Study_Status
        • List_Studies
        • Add_a_project
        • Get_a_project
        • List_Project_Assets
        • Load_Assets
        • Upload_Assets
        • Login
      • 3:Parametric
        • Fly
        • Fly_ID
      • 4:Serialization
        • PO_Dump_GEM
        • PO_Dump_IDM
        • PO_Dump_INP
        • PO_Dump_SDD
    • Your First Simulation
    • Create a Parametric Run
    • Visualize Results
  • Web Platform
    • Create a New Project
    • Manage Access to a Project
    • Create a New Study
    • Create Teams
  • Developers
    • Create an API Key
    • API
      • Add Members to an Organization
      • Create a New Project
      • Schedule a Study on Pollination
    • Apps
      • Create a Simple Chart
      • Create a Filtered Chart
      • Create a Study
      • Check Study Status
      • Download an Output
      • Visualize Results on the Web
      • Integrate the Pollination Viewer
      • Visualize Results in Rhino
      • Prepare an App folder
      • Deploy an App using the Command Line
      • Deploy an App using Github
      • Automate the App Deployment
      • Update an App
  • Legal
    • Terms of Service
    • Privacy Policy
    • Subprocessors
    • Data Processing Addendum
    • Service Level Agreement
Powered by GitBook
On this page

Was this helpful?

  1. Developers
  2. API

Schedule a Study on Pollination

PreviousCreate a New ProjectNextApps

Last updated 3 months ago

Was this helpful?

This page shows an example code for creating a single study with multiple runs on Pollination using the Pollination API. It also includes a function that waits for the study to finish and downloads the results.

This code was originally posted on Discourse in response to this topic. You can download the sample files from Discourse.

Here is the study that is submitted to Pollination using the sample code:

"""
Sample code for using the API to submit several HBJSON files from a folder to
Pollination, and download the results when ready.
"""
import pathlib
import time
import requests
from requests.exceptions import HTTPError
import zipfile
import tempfile
import shutil

from typing import List

from pollination_io.api.client import ApiClient
from pollination_io.interactors import NewJob, Recipe, Job
from queenbee.job.job import JobStatusEnum


def submit_study(
    study_name: str, api_client: ApiClient, owner: str, project: str, epw: pathlib.Path,
        ddy: pathlib.Path, models_folder: pathlib.Path) -> Job:

    print(f'Creating a new study: {study_name}')
    # Assumption: the recipe has been already added to the project manually
    recipe = Recipe('ladybug-tools', 'annual-energy-use', '0.5.7', client=api_client)

    input_folder = pathlib.Path(models_folder)

    # create a new study
    new_study = NewJob(owner, project, recipe, client=api_client)
    new_study.name = study_name
    new_study.description = f'Annual Energy Simulation {input_folder.name}'

    # upload the weather files - you only need to upload them once, and you can use
    # the path to them directly
    assert epw.is_file(), f'{epw} is not a valid file path.'
    assert ddy.is_file(), f'{ddy} is not a valid file path.'

    epw_path = new_study.upload_artifact(epw, target_folder='weather-data')
    ddy_path = new_study.upload_artifact(ddy, target_folder='weather-data')

    recipe_inputs = {
        'epw': epw_path,
        'ddy': ddy_path
    }

    study_inputs = []
    for model in input_folder.glob('*.hbjson'):
        inputs = dict(recipe_inputs)  # create a copy of the recipe
        # upload this model to the project
        print(f'Uploading model: {model.name}')
        uploaded_path = new_study.upload_artifact(model, target_folder=input_folder.name)
        inputs['model'] = uploaded_path
        inputs['model_id'] = model.stem  # use model name as the ID.
        study_inputs.append(inputs)

    # add the inputs to the study
    # each set of inputs creates a new run
    new_study.arguments = study_inputs

    # # create the study
    running_study = new_study.create()

    job_url = f'https://app.pollination.solutions/{running_study.owner}/projects/{running_study.project}/jobs/{running_study.id}'
    print(job_url)
    time.sleep(5)
    return running_study


def check_study_status(study: Job):
    """"""
    status = study.status.status
    http_errors = 0
    while True:
        status_info = study.status
        print('\t# ------------------ #')
        print(f'\t# pending runs: {status_info.runs_pending}')
        print(f'\t# running runs: {status_info.runs_running}')
        print(f'\t# failed runs: {status_info.runs_failed}')
        print(f'\t# completed runs: {status_info.runs_completed}')
        if status in [
            JobStatusEnum.pre_processing, JobStatusEnum.running, JobStatusEnum.created,
            JobStatusEnum.unknown
        ]:
            time.sleep(15)
            try:
                study.refresh()
            except HTTPError as e:
                status_code = e.response.status_code
                print(str(e))
                if status_code == 500:
                    http_errors += 1
                    if http_errors > 3:
                        # failed for than 3 times with no success
                        raise HTTPError(e)
                    # wait for additional 15 seconds
                    time.sleep(10)
            else:
                http_errors = 0
                status = status_info.status
        else:
            # study is finished
            time.sleep(2)
            break


def _download_results(
    owner: str, project: str, study_id: int, download_folder: pathlib.Path,
    api_client: ApiClient, page: int = 1
        ):
    print(f'Downloading page {page}')
    per_page = 25
    url = f'https://api.pollination.solutions/projects/{owner}/{project}/runs'
    params = {
        'job_id': study_id,
        'status': 'Succeeded',
        'page': page,
        'per-page': per_page
    }
    response = requests.get(url, params=params, headers=api_client.headers)
    response_dict = response.json()
    runs = response_dict['resources']
    temp_dir = tempfile.TemporaryDirectory()
    # with tempfile.TemporaryDirectory() as temp_dir:
    if temp_dir:
        temp_folder = pathlib.Path(temp_dir.name)
        for run in runs:
            run_id = run['id']
            # the model-id is hardcoded in submit_study. This is not necessarily good
            # practice and makes the code to only be useful for this example.
            input_id = [
                inp['value']
                for inp in run['status']['inputs'] if inp['name'] == 'model_id'
            ][0]
            run_folder = temp_folder.joinpath(input_id)
            eui_file = run_folder.joinpath('eui.json')
            out_file = download_folder.joinpath(f'{input_id}.json')
            print(f'downloading {input_id}.json to {out_file.as_posix()}')
            run_folder.mkdir(parents=True, exist_ok=True)
            download_folder.mkdir(parents=True, exist_ok=True)
            url = f'https://api.pollination.solutions/projects/{owner}/{project}/runs/{run_id}/outputs/eui'
            signed_url = requests.get(url, headers=api_client.headers)
            output = api_client.download_artifact(signed_url=signed_url.json())
            with zipfile.ZipFile(output) as zip_folder:
                zip_folder.extractall(run_folder.as_posix())
            # move the json file to study folder
            shutil.copy(eui_file.as_posix(), out_file.as_posix())

    next_page = response_dict.get('next_page')
    if next_page is not None:
        time.sleep(1)
        _download_results(
            owner, project, study_id, download_folder, api_client, page=next_page
        )


def download_study_results(
        api_client: ApiClient, study: Job, output_folder: pathlib.Path):
    owner = study.owner
    project = study.project
    study_id = study.id

    _download_results(
        owner=owner, project=project, study_id=study_id, download_folder=output_folder,
        api_client=api_client
    )


if __name__ == '__main__':
    api_key = 'YOUR-API-KEY'
    assert api_key is not None, 'You must provide valid Pollination API key.'

    # project owner and project name - Change these!
    owner = 'mostapha'
    project = 'agent-based-energy-simulation'

    # change this to where the study folder is
    study_folder = pathlib.Path(__file__).parent
    input_folder = study_folder.joinpath('dataset_1')
    epw = study_folder.joinpath('PER_Arequipa.847520_IWEC.epw')
    ddy = study_folder.joinpath('PER_Arequipa.847520_IWEC.ddy')
    results_folder = study_folder.joinpath('results/dataset_1')
    name = 'YOUR-STUDY-NAME'
    api_client = ApiClient(api_token=api_key)

    study = submit_study(name, api_client, owner, project, epw, ddy, input_folder)
    # wait until the study is finished
    check_study_status(study=study)
    download_study_results(
        api_client=api_client, study=study, output_folder=results_folder
    )
How to submit an energy simulation to Pollination using the APIPollination Discourse
Pollination
Logo
Logo