index
int64 | repo_name
string | branch_name
string | path
string | content
string | import_graph
string |
|---|---|---|---|---|---|
8,572
|
rikenshah/Well-thy
|
refs/heads/master
|
/pyScripts/get_health_score.py
|
import csv
import json
import re
import os
maxHealthScore = 1000
featureWeights_dict={}
def initialize():
reader = csv.reader(open('pyScripts/feature_weights.csv'))
for row in reader:
value=[]
split_row= row[0].split('\t')
key=split_row[0]
value=split_row[1:]
featureWeights_dict[key]=value
print(featureWeights_dict)
def getHealthScore(input_dict):
healthScore = 0
for key in featureWeights_dict:
weight = float(featureWeights_dict[key][0])
value = maxHealthScore
if featureWeights_dict[key][1]=='negative' :
value = value - (value*input_dict[key][0]/input_dict[key][1])
elif featureWeights_dict[key][1]=='positive' :
value = value - (value*(input_dict[key][1]-input_dict[key][0]-1)/input_dict[key][1])
value = value * weight
input_dict[key] = value #optional
healthScore = healthScore + value
# savings = getCostSavings(healthScore,input_dict["healthcare_costs"])
# return round(healthScore,2),round(savings,2)
return round(healthScore,2)
def getCostSavings(improvementPoints,healthcare_costs):
savings = (improvementPoints)/maxHealthScore
return savings*healthcare_costs
def preprocessData(data):
# print("in preprocess",data)
initialize()
# data["exercise"] = [data["exercise"],3]
# data["travel_time"] = [data["travel_time"],3]
# data["sleep_time"] = [data["sleep_time"],3]
# data["drink"] = [1 if data["drink"] else 0,2]
# data["tobacco"] = [1 if data["tobacco"] else 0,2]
# data["smoke"] = [1 if data["smoke"] else 0,2]
# """Bag of words to identify past ailments and dangerous job types"""
# ailments=set(['heart','brain','kidney','liver','breating','asthema'])
# job_type=set(['army','defence','factory'])
# #pattern = re.compile("\s+|^\s+|\s*,*\s*|\s+$")
# pattern = re.compile("\s+,*\s*")
# current_ailments = set([ x for x in pattern.split(data["ailments"]) if x])
# current_jobtype = set([ x for x in pattern.split(data["job_type"]) if x])
# data["ailments"] = [1 if current_ailments.intersection(ailments) else 0,2]
# data["job_type"] = [1 if current_jobtype.intersection(job_type) else 0,2]
# """Identifying Healthy BMI & Age range"""
# data["age"]=[0 if data["age"]>18 and data["age"]<45 else 1,2]
# data["bmi"]=data["weight"]/(data["height"]*data["height"])
# data["bmi"]=[0 if data["bmi"]>18.5 and data["bmi"]<24.9 else 1,2]
# print("preprocess",data)
return getHealthScore(data)
if __name__ == "__main__":
initialize()
input_dict = {}
input_dict['age']=45 #1 means out of healthy age range
input_dict['height']= 1.8 #1 means out of healthy BMI range
input_dict['weight']=80
input_dict['ailments']="heart ailments" #0 means no ailments
input_dict['tobacco']=False #binary
input_dict['smoke']=True
input_dict['drink']= True
input_dict['exercise']=1 #more exercise
input_dict['travel_time']=1
input_dict['sleep_time']=1
input_dict['healthcare_costs']=500
input_dict['job_type']="" #moderate risky job
result = preprocessData(input_dict)
print("Health Score is ",result[0])
print("Savings is ",result[1])
|
{"/health/views.py": ["/health/models.py"]}
|
8,573
|
rikenshah/Well-thy
|
refs/heads/master
|
/pyScripts/score_prediction.py
|
Ins_Age,Ht,Wt,Individual_Rate,Individual Tobacco Rate,rate_diff,BMI,Response
# take all the inputs like Ht, Wt, Rate, Age
|
{"/health/views.py": ["/health/models.py"]}
|
8,574
|
rikenshah/Well-thy
|
refs/heads/master
|
/pyScripts/base-for-health-score.py
|
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import GradientBoostingRegressor
#from sklearn.preprocessing import LabelEncoder
## Loading data and preprocessing
data = pd.read_csv('../datasets/merged.csv')
train_data=data.iloc[:,0:10]
data["Individual_Rate"] = (data["Individual_Rate"]-data["Individual_Rate"].min())/(data["Individual_Rate"].max()-data["Individual_Rate"].min())
Y=data.iloc[:,10]
#test_data = pd.read_csv('../datasets/merged.csv')
features=['Ins_Age','BMI','Individual_Rate']
##Linear Regression
LinReg_model = LinearRegression()
LinReg_model.fit(train_data[features], Y)
linReg_score = cross_val_score(LinReg_model, train_data[features], Y, cv=10,scoring='r2').mean()
print("R2 score using Linear Regression is ",linReg_score*100)
print("Linear reg coef",LinReg_model.coef_)
##Random Forest Regressor
##
##RanForest_model = RandomForestRegressor( random_state=0)
##RanForest_model.fit(train_data[features], Y)
##ranForest_score = cross_val_score(RanForest_model, train_data[features], Y, cv=10,scoring='r2').mean()
##print("R2 score using Random Forest Regression is ",ranForest_score*100)
##Gradient Boosting Regressor
GradBoost_model = GradientBoostingRegressor(max_depth=3, random_state=0,learning_rate=0.1,n_estimators=200)
GradBoost_model.fit(train_data[features], Y)
GradBoost_model.apply(train_data[features])
gradBoost_score = cross_val_score(GradBoost_model, train_data[features], Y, cv=10,scoring='r2').mean()
print("Feature Importance ",GradBoost_model.feature_importances_)
print("R2 score using Gradient Boosting Regressor is ",gradBoost_score*100)
|
{"/health/views.py": ["/health/models.py"]}
|
8,575
|
rikenshah/Well-thy
|
refs/heads/master
|
/health/migrations/0004_auto_20180426_1547.py
|
# Generated by Django 2.0.1 on 2018-04-26 15:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('health', '0003_auto_20180426_1527'),
]
operations = [
migrations.AlterField(
model_name='healthprofile',
name='sleep_time',
field=models.IntegerField(blank=True, choices=[(2, '>8 hours/day'), (1, '6-8 hours/day'), (0, '<6 hours/day')], default=(1, '6-8 hours/day'), help_text='Select how much do you sleep?'),
),
]
|
{"/health/views.py": ["/health/models.py"]}
|
8,576
|
rikenshah/Well-thy
|
refs/heads/master
|
/health/migrations/0002_auto_20180414_0114.py
|
# Generated by Django 2.0.1 on 2018-04-14 01:14
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('health', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='healthprofile',
name='healthcare_costs',
field=models.FloatField(blank=True, help_text='Enter your total healthcare costs', null=True, validators=[django.core.validators.MaxValueValidator(50000), django.core.validators.MinValueValidator(0)]),
),
migrations.AlterField(
model_name='healthprofile',
name='height',
field=models.FloatField(blank=True, help_text='Enter height (In Inches) :', null=True, validators=[django.core.validators.MaxValueValidator(300), django.core.validators.MinValueValidator(20)]),
),
migrations.AlterField(
model_name='healthprofile',
name='user',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
]
|
{"/health/views.py": ["/health/models.py"]}
|
8,577
|
rikenshah/Well-thy
|
refs/heads/master
|
/health/views.py
|
from django.shortcuts import render
from .models import HealthProfile
from django.contrib.auth.decorators import login_required
from django.views.generic import TemplateView,ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from django.contrib.auth.models import User
from .models import HealthProfile
from django.shortcuts import redirect
from pyScripts import get_health_score
from pyScripts import get_recommendations
import json
from django.core import serializers
# Create your views here.
def profile(request):
if(request.user):
p = HealthProfile.objects.filter(user=request.user)
if len(p)>0 :
json_p = json.loads(serializers.serialize('json',[p[0]]))[0]["fields"]
print("json p")
print(json_p)
# json_p["healthcare_costs"] = 100
recommendations,savings = get_recommendations.processRecommendations(json_p, 1000)
result = get_health_score.preprocessData(json_p)
# recommendations = "hello"
return render(request,'health/profile.html',{'health_profile' : p[0], 'health_score' : result, 'savings' : savings, 'recommendations' : recommendations})
else:
return render(request,'health/profile.html')
class HealthProfileDisplay(ListView):
model = HealthProfile
def handle_profile(request):
h = HealthProfile()
if(request.user):
p = HealthProfile.objects.filter(user=request.user)
if len(p)>0 :
print("Profile exists : Reditecting to edit")
s = "/health/update/"+str(p[0].id)
return redirect(s)
else:
print("Creating new profile")
return redirect("/health/input")
class HealthProfileCreate(CreateView):
model = HealthProfile
fields = ['age','height','weight','ailments','healthcare_costs','tobacco','smoke','drink','exercise','travel_time', 'sleep_time','job_type']
success_url = reverse_lazy('health:health_profile')
# initial = {'sleep_time':1}
def form_valid(self, form):
form.instance.user = self.request.user
print("+++++++++++++",form.instance.sleep_time)
return super().form_valid(form)
class HealthProfileUpdate(UpdateView):
model = HealthProfile
fields = ['age','height','weight','ailments','healthcare_costs','tobacco','smoke','drink','exercise','travel_time', 'sleep_time','job_type']
success_url = reverse_lazy('health:health_profile')
|
{"/health/views.py": ["/health/models.py"]}
|
8,578
|
rikenshah/Well-thy
|
refs/heads/master
|
/health/urls.py
|
from django.urls import path
from . import views
from django.contrib.auth.decorators import login_required
app_name = 'lesson'
urlpatterns = [
# path('', views.index, name='index'),
path('profile',login_required(views.profile),name='health_profile'),
path('handle',login_required(views.handle_profile),name='handle'),
path('input', login_required(views.HealthProfileCreate.as_view(template_name="health/form.html")), name='health_new'),
path('update/<pk>', login_required(views.HealthProfileUpdate.as_view(template_name="health/form.html")), name='health_update')
]
|
{"/health/views.py": ["/health/models.py"]}
|
8,630
|
leying95/stereopy
|
refs/heads/main
|
/stereo/plots/_plot_basic/__init__.py
|
#!/usr/bin/env python3
# coding: utf-8
"""
@author: Shixu He heshixu@genomics.cn
@last modified by: Shixu He
@file:__init__.py.py
@time:2021/03/15
"""
|
{"/stereo/log_manager.py": ["/stereo/config.py"], "/stereo/plots/plot_utils.py": ["/stereo/plots/_plot_basic/heatmap_plt.py", "/stereo/log_manager.py"], "/stereo/plots/plots.py": ["/stereo/plots/_plot_basic/heatmap_plt.py", "/stereo/log_manager.py"], "/stereo/utils/__init__.py": ["/stereo/utils/correlation.py"], "/stereo/core/stereo_result.py": ["/stereo/log_manager.py"], "/stereo/plots/_plot_basic/heatmap_plt.py": ["/stereo/log_manager.py"]}
|
8,631
|
leying95/stereopy
|
refs/heads/main
|
/stereo/log_manager.py
|
#!/usr/bin/env python3
# coding: utf-8
"""
@author: Ping Qiu qiuping1@genomics.cn
@last modified by: Ping Qiu
@file:log_manager.py
@time:2021/03/05
"""
import logging
from .config import stereo_conf
class LogManager(object):
def __init__(self, log_path=None, level=None):
self.level_map = {'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL}
self.format = stereo_conf.log_format
self.formatter = logging.Formatter(self.format, "%Y-%m-%d %H:%M:%S")
self.log_path = log_path
self.level = level.lower() if level else stereo_conf.log_level.lower()
if self.log_path:
self.file_handler = logging.FileHandler(self.log_path)
self.file_handler.setLevel(self.level_map[self.level])
self.file_handler.setFormatter(self.formatter)
else:
self.stream_handler = logging.StreamHandler()
self.stream_handler.setLevel(self.level_map[self.level])
self.stream_handler.setFormatter(self.formatter)
def get_logger(self, name="Spateo"):
"""
get logger object
:param name: logger name
:return: logger object
"""
alogger = logging.getLogger(name)
alogger.propagate = 0
alogger.setLevel(self.level_map[self.level])
self._add_handler(alogger)
return alogger
def _add_handler(self, alogger):
"""
add handler of logger
:param logger: logger object
:return:
"""
if self.log_path:
alogger.addHandler(self.file_handler)
else:
alogger.addHandler(self.stream_handler)
logger = LogManager().get_logger(name='Spateo')
|
{"/stereo/log_manager.py": ["/stereo/config.py"], "/stereo/plots/plot_utils.py": ["/stereo/plots/_plot_basic/heatmap_plt.py", "/stereo/log_manager.py"], "/stereo/plots/plots.py": ["/stereo/plots/_plot_basic/heatmap_plt.py", "/stereo/log_manager.py"], "/stereo/utils/__init__.py": ["/stereo/utils/correlation.py"], "/stereo/core/stereo_result.py": ["/stereo/log_manager.py"], "/stereo/plots/_plot_basic/heatmap_plt.py": ["/stereo/log_manager.py"]}
|
8,632
|
leying95/stereopy
|
refs/heads/main
|
/stereo/tools/neighbors.py
|
#!/usr/bin/env python3
# coding: utf-8
"""
@author: Ping Qiu qiuping1@genomics.cn
@last modified by: Ping Qiu
@file:neighbors.py
@time:2021/03/23
"""
from scipy.sparse import coo_matrix
from sklearn.neighbors import NearestNeighbors
import igraph as ig
import numpy as np
from umap.umap_ import fuzzy_simplicial_set
class Neighbors(object):
def __init__(self, x, n_neighbors):
self.x = x
self.n_neighbors = n_neighbors
def find_n_neighbors(self):
nbrs = NearestNeighbors(n_neighbors=self.n_neighbors + 1, algorithm='ball_tree').fit(self.x)
dists, indices = nbrs.kneighbors(self.x)
nn_idx = indices[:, 1:]
nn_dist = dists[:, 1:]
return nn_idx, nn_dist
def get_igraph_from_knn(self, nn_idx, nn_dist):
j = nn_idx.ravel().astype(int)
dist = nn_dist.ravel()
i = np.repeat(np.arange(nn_idx.shape[0]), self.n_neighbors)
vertex = list(range(nn_dist.shape[0]))
edges = list(tuple(zip(i, j)))
G = ig.Graph()
G.add_vertices(vertex)
G.add_edges(edges)
G.es['weight'] = dist
return G
def get_parse_distances(self, nn_idx, nn_dist):
n_obs = self.x.shape[0]
rows = np.zeros((n_obs * self.n_neighbors), dtype=np.int64)
cols = np.zeros((n_obs * self.n_neighbors), dtype=np.int64)
vals = np.zeros((n_obs * self.n_neighbors), dtype=np.float64)
for i in range(nn_idx.shape[0]):
for j in range(self.n_neighbors):
if nn_idx[i, j] == -1:
continue # We didn't get the full knn for i
if nn_idx[i, j] == i:
val = 0.0
else:
val = nn_dist[i, j]
rows[i * self.n_neighbors + j] = i
cols[i * self.n_neighbors + j] = nn_idx[i, j]
vals[i * self.n_neighbors + j] = val
distances = coo_matrix((vals, (rows, cols)), shape=(n_obs, n_obs))
distances.eliminate_zeros()
return distances.tocsr()
def get_connectivities(self, nn_idx, nn_dist):
n_obs = self.x.shape[0]
x = coo_matrix(([], ([], [])), shape=(n_obs, 1))
connectivities = fuzzy_simplicial_set(x, self.n_neighbors, None, None, knn_indices=nn_idx, knn_dists=nn_dist,
set_op_mix_ratio=1.0, local_connectivity=1.0)
if isinstance(connectivities, tuple):
connectivities = connectivities[0]
return connectivities.tocsr()
|
{"/stereo/log_manager.py": ["/stereo/config.py"], "/stereo/plots/plot_utils.py": ["/stereo/plots/_plot_basic/heatmap_plt.py", "/stereo/log_manager.py"], "/stereo/plots/plots.py": ["/stereo/plots/_plot_basic/heatmap_plt.py", "/stereo/log_manager.py"], "/stereo/utils/__init__.py": ["/stereo/utils/correlation.py"], "/stereo/core/stereo_result.py": ["/stereo/log_manager.py"], "/stereo/plots/_plot_basic/heatmap_plt.py": ["/stereo/log_manager.py"]}
|
8,633
|
leying95/stereopy
|
refs/heads/main
|
/stereo/core/stereo_data.py
|
#!/usr/bin/env python3
# coding: utf-8
"""
@author: Ping Qiu qiuping1@genomics.cn
@last modified by: Ping Qiu
@file:stereo_data.py
@time:2021/03/22
"""
class StereoData(object):
def __init__(self, raw_file=None, exp_matrix=None, genes=None, bins=None, position=None, partitions=1):
self.index = None
self.index_file = None
self.exp_matrix = exp_matrix
self.genes = genes
self.bins = bins
self.position = position
self.raw_file = raw_file
self.partitions = partitions
def filter_genes(self):
pass
def filter_bins(self):
pass
def search(self):
pass
def combine_bins(self, bin_size, step):
pass
def select_by_genes(self, gene_list):
pass
def select_by_position(self, x_min, y_min, x_max, y_max, bin_size):
pass
def transform_matrix(self):
pass
def get_genes(self):
pass
def get_bins(self):
pass
def split_data(self):
pass
def sparse2array(self):
pass
|
{"/stereo/log_manager.py": ["/stereo/config.py"], "/stereo/plots/plot_utils.py": ["/stereo/plots/_plot_basic/heatmap_plt.py", "/stereo/log_manager.py"], "/stereo/plots/plots.py": ["/stereo/plots/_plot_basic/heatmap_plt.py", "/stereo/log_manager.py"], "/stereo/utils/__init__.py": ["/stereo/utils/correlation.py"], "/stereo/core/stereo_result.py": ["/stereo/log_manager.py"], "/stereo/plots/_plot_basic/heatmap_plt.py": ["/stereo/log_manager.py"]}
|
8,634
|
leying95/stereopy
|
refs/heads/main
|
/stereo/preprocess/qc.py
|
#!/usr/bin/env python3
# coding: utf-8
"""
@author: Ping Qiu qiuping1@genomics.cn
@last modified by: Ping Qiu
@file:qc.py
@time:2021/03/26
"""
from scipy.sparse import issparse
import numpy as np
def cal_qc(andata):
exp_matrix = andata.X.toarray() if issparse(andata.X) else andata.X
total_count = exp_matrix.sum(1)
n_gene_by_count = np.count_nonzero(exp_matrix, axis=1)
mt_index = andata.var_names.str.startswith('MT-')
mt_count = np.array(andata.X[:, mt_index].sum(1)).reshape(-1)
andata.obs['total_counts'] = total_count
andata.obs['pct_counts_mt'] = mt_count / total_count * 100
andata.obs['n_genes_by_counts'] = n_gene_by_count
return andata
|
{"/stereo/log_manager.py": ["/stereo/config.py"], "/stereo/plots/plot_utils.py": ["/stereo/plots/_plot_basic/heatmap_plt.py", "/stereo/log_manager.py"], "/stereo/plots/plots.py": ["/stereo/plots/_plot_basic/heatmap_plt.py", "/stereo/log_manager.py"], "/stereo/utils/__init__.py": ["/stereo/utils/correlation.py"], "/stereo/core/stereo_result.py": ["/stereo/log_manager.py"], "/stereo/plots/_plot_basic/heatmap_plt.py": ["/stereo/log_manager.py"]}
|
8,635
|
leying95/stereopy
|
refs/heads/main
|
/stereo/config.py
|
#!/usr/bin/env python3
# coding: utf-8
"""
@author: Ping Qiu qiuping1@genomics.cn
@last modified by: Ping Qiu
@file:config.py
@time:2021/03/05
"""
from typing import Union, Optional
from pathlib import Path
import os
from matplotlib import rcParams, rcParamsDefault
class StereoConfig(object):
"""
config of stereo.
"""
def __init__(
self,
file_format: str = "h5ad",
auto_show: bool = True,
n_jobs=1,
log_file: Union[str, Path, None] = None,
log_level: str = "info",
log_format: str = "%(asctime)s %(name)s %(levelname)s: %(message)s",
output: str = "./output",
data_dir: str = None
):
self._file_format = file_format
self._auto_show = auto_show
self._n_jobs = n_jobs
self._log_file = log_file
self._log_level = log_level
self._log_format = log_format
self.out_dir = output
self.data_dir = data_dir if data_dir else os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data')
@property
def log_file(self) -> Union[str, Path, None]:
"""
get the file path of log.
:return:
"""
return self._log_file
@log_file.setter
def log_file(self, value):
"""
set file path of log.
:param value: value of log file path
:return:
"""
if value:
dir_path = os.path.dirname(value)
if not os.path.exists(dir_path):
raise FileExistsError("folder does not exist, please check!")
self._log_file = value
@property
def log_format(self) -> str:
"""
get the format of log.
:return:
"""
return self._log_format
@log_format.setter
def log_format(self, value):
"""
set file path of log.
:param value: value of log format
:return:
"""
self._log_format = value
@property
def log_level(self) -> str:
"""
get log level
:return:
"""
return self._log_level
@log_level.setter
def log_level(self, value):
"""
set log level
:param value: the value of log level
:return:
"""
if value.lower() not in ['info', 'warning', 'debug', 'error', 'critical']:
print('the log level is out of range, please check and it is not modified.')
else:
self._log_level = value
@property
def auto_show(self):
"""
Auto show figures if `auto_show == True` (default `True`).
:return:
"""
return self._auto_show
@auto_show.setter
def auto_show(self, value):
"""
set value of auto_show
:param value: value of auto_show
:return:
"""
self._auto_show = value
@property
def file_format(self) -> str:
"""
file format of saving anndata object
:return:
"""
return self._file_format
@file_format.setter
def file_format(self, value):
"""
set the value of file format
:param value: the value of file format
:return:
"""
self._file_format = value
@property
def n_jobs(self) -> int:
return self._n_jobs
@n_jobs.setter
def n_jobs(self, value):
self._n_jobs = value
@staticmethod
def set_plot_param(fontsize: int = 14, figsize: Optional[int] = None, color_map: Optional[str] = None,
facecolor: Optional[str] = None, transparent: bool = False,):
if fontsize is not None:
rcParams['font.size'] = fontsize
if color_map is not None:
rcParams['image.cmap'] = color_map
if figsize is not None:
rcParams['figure.figsize'] = figsize
if facecolor is not None:
rcParams['figure.facecolor'] = facecolor
rcParams['axes.facecolor'] = facecolor
if transparent is not None:
rcParams["savefig.transparent"] = transparent
@staticmethod
def set_rcparams_defaults():
"""
reset `matplotlib.rcParams` to defaults.
:return:
"""
rcParams.update(rcParamsDefault)
stereo_conf = StereoConfig()
|
{"/stereo/log_manager.py": ["/stereo/config.py"], "/stereo/plots/plot_utils.py": ["/stereo/plots/_plot_basic/heatmap_plt.py", "/stereo/log_manager.py"], "/stereo/plots/plots.py": ["/stereo/plots/_plot_basic/heatmap_plt.py", "/stereo/log_manager.py"], "/stereo/utils/__init__.py": ["/stereo/utils/correlation.py"], "/stereo/core/stereo_result.py": ["/stereo/log_manager.py"], "/stereo/plots/_plot_basic/heatmap_plt.py": ["/stereo/log_manager.py"]}
|
8,636
|
leying95/stereopy
|
refs/heads/main
|
/stereo/plots/plot_utils.py
|
#!/usr/bin/env python3
# coding: utf-8
"""
@author: Shixu He heshixu@genomics.cn
@last modified by: Shixu He
@file:plot_utils.py
@time:2021/03/15
"""
from anndata import AnnData
import pandas as pd
import numpy as np
import math
from matplotlib.colors import Normalize, ListedColormap
from matplotlib import gridspec
from matplotlib.cm import get_cmap
from matplotlib.axes import Axes
import matplotlib.pyplot as plt
import seaborn
from ._plot_basic.scatter_plt import scatter, plot_cluster_result
from ._plot_basic.heatmap_plt import heatmap, _plot_categories_as_colorblocks, _plot_gene_groups_brackets
from typing import Optional, Sequence, Union
from ..log_manager import logger
def plot_spatial_distribution(
adata: AnnData,
obs_key: list = ["total_counts", "n_genes_by_counts"],
ncols=2,
dot_size=None,
color_list=None,
invert_y=False
): # scatter plot, 表达矩阵空间分布
"""
Plot spatial distribution of specified obs data.
============ Arguments ============
:param adata: AnnData object.
:param obs_key: specified obs key list, for example: ["total_counts", "n_genes_by_counts"]
:param ncols: numbr of plot columns.
:param dot_size: marker size.
:param cmap: Color map.
:param invert_y: whether to invert y-axis.
============ Return ============
None
============ Example ============
plot_spatial_distribution(adata=adata)
"""
# sc.pl.embedding(adata, basis="spatial", color=["total_counts", "n_genes_by_counts"],size=30)
if dot_size is None:
dot_size = 120000 / adata.shape[0]
ncols = min(ncols, len(obs_key))
nrows = np.ceil(len(obs_key) / ncols).astype(int)
# each panel will have the size of rcParams['figure.figsize']
fig = plt.figure(figsize=(ncols * 10, nrows * 8))
left = 0.2 / ncols
bottom = 0.13 / nrows
axs = gridspec.GridSpec(
nrows=nrows,
ncols=ncols,
left=left,
right=1 - (ncols - 1) * left - 0.01 / ncols,
bottom=bottom,
top=1 - (nrows - 1) * bottom - 0.1 / nrows,
# hspace=hspace,
# wspace=wspace,
)
if color_list is None:
cmap = get_cmap()
else:
cmap = ListedColormap(color_list)
# 把特定值改为 np.nan 之后,可以利用 cmap.set_bad("white") 来遮盖掉这部分数据
# 散点图上每个点的坐标数据来自于 adata 的 obsm["spatial"],每个点的颜色(数值)数据来自于 adata 的 obs_vector()
for i, key in enumerate(obs_key):
# color_data = np.asarray(adata.obs_vector(key), dtype=float)
color_data = adata.obs_vector(key)
order = np.argsort(~pd.isnull(color_data), kind="stable")
spatial_data = np.array(adata.obsm["spatial"])[:, 0: 2]
color_data = color_data[order]
spatial_data = spatial_data[order, :]
# color_data 是图像中各个点的值,也对应了每个点的颜色。data_points则对应了各个点的坐标
ax = fig.add_subplot(axs[i]) # ax = plt.subplot(axs[i]) || ax = fig.add_subplot(axs[1, 1]))
ax.set_title(key)
ax.set_yticks([])
ax.set_xticks([])
ax.set_xlabel("spatial1")
ax.set_ylabel("spatial2")
pathcollection = scatter(
spatial_data[:, 0],
spatial_data[:, 1],
ax=ax,
marker=".",
dot_colors=color_data,
dot_size=dot_size,
cmap=cmap,
)
plt.colorbar(
pathcollection,
ax=ax,
pad=0.01,
fraction=0.08,
aspect=30,
)
ax.autoscale_view()
if invert_y:
ax.invert_yaxis()
def plot_spatial_cluster(
adata: AnnData,
obs_key: list = ["phenograph"],
plot_cluster: list = None,
bad_color="lightgrey",
ncols=2,
dot_size=None,
invert_y=False,
color_list=['violet', 'turquoise', 'tomato', 'teal',
'tan', 'silver', 'sienna', 'red', 'purple',
'plum', 'pink', 'orchid', 'orangered', 'orange',
'olive', 'navy', 'maroon', 'magenta', 'lime',
'lightgreen', 'lightblue', 'lavender', 'khaki',
'indigo', 'grey', 'green', 'gold', 'fuchsia',
'darkgreen', 'darkblue', 'cyan', 'crimson', 'coral',
'chocolate', 'chartreuse', 'brown', 'blue', 'black',
'beige', 'azure', 'aquamarine', 'aqua']): # scatter plot, 聚类后表达矩阵空间分布
"""
Plot spatial distribution of specified obs data.
============ Arguments ============
:param adata: AnnData object.
:param obs_key: specified obs cluster key list, for example: ["phenograph"].
:param plot_cluster: the name list of clusters to show.
:param ncols: numbr of plot columns.
:param dot_size: marker size.
:param cmap: Color map.
:param invert_y: whether to invert y-axis.
============ Return ============
None.
============ Example ============
plot_spatial_cluster(adata = adata)
"""
# sc.pl.embedding(adata, basis="spatial", color=["total_counts", "n_genes_by_counts"],size=30)
if isinstance(obs_key, str):
obs_key = ["obs_key"]
plot_cluster_result(adata, obs_key=obs_key, pos_key="spatial", plot_cluster=plot_cluster, bad_color=bad_color,
ncols=ncols, dot_size=dot_size, invert_y=invert_y, color_list=color_list)
def plot_to_select_filter_value(
adata: AnnData,
x=["total_counts", "total_counts"],
y=["pct_counts_mt", "n_genes_by_counts"],
ncols=1,
**kwargs): # scatter plot, 线粒体分布图
"""
Plot .
============ Arguments ============
:param adata: AnnData object.
:param x, y: obs key pairs for drawing. For example, assume x=["a", "a", "b"] and y=["c", "d", "e"], the output plots will include "a-c", "a-d", "b-e".
============ Return ============
None.
============ Example ============
plot_spatial_cluster(adata = adata)
"""
# sc.pl.scatter(adata, x='total_counts', y='pct_counts_mt')
# sc.pl.scatter(adata, x='total_counts', y='n_genes_by_counts')
if isinstance(x, str):
x = [x]
if isinstance(y, str):
y = [y]
width = 20
height = 10
nrows = math.ceil(len(x) / ncols)
doc_color = "gray"
fig = plt.figure(figsize=(width, height))
axs = gridspec.GridSpec(
nrows=nrows,
ncols=ncols,
)
for i, (xi, yi) in enumerate(zip(x, y)):
draw_data = np.c_[adata.obs_vector(xi), adata.obs_vector(yi)]
dot_size = 120000 / draw_data.shape[0]
ax = fig.add_subplot(axs[i])
# ax.set_title()
# ax.set_yticks([])
# ax.set_xticks([])
ax.set_xlabel(xi)
ax.set_ylabel(yi)
scatter(
draw_data[:, 0],
draw_data[:, 1],
ax=ax,
marker=".",
dot_colors=doc_color,
dot_size=dot_size
)
def plot_variable_gene(adata: AnnData, logarize=False): # scatter plot, 表达量差异-均值图
"""
Copied from scanpy and modified.
"""
# 该图像需要前置数据处理:sc.pp.highly_variable_genes(adata, min_mean=0.0125, max_mean=3, min_disp=0.5)
# 再画图:sc.pl.highly_variable_genes(adata)
result = adata.var
gene_subset = result.highly_variable
means = result.means
var_or_disp = result.dispersions
var_or_disp_norm = result.dispersions_norm
width = 10
height = 10
plt.figure(figsize=(2 * width, height))
plt.subplots_adjust(wspace=0.3)
for idx, d in enumerate([var_or_disp_norm, var_or_disp]):
plt.subplot(1, 2, idx + 1)
for label, color, mask in zip(
['highly variable genes', 'other genes'],
['black', 'grey'],
[gene_subset, ~gene_subset],
):
if False:
means_, var_or_disps_ = np.log10(means[mask]), np.log10(d[mask])
else:
means_, var_or_disps_ = means[mask], d[mask]
plt.scatter(means_, var_or_disps_, label=label, c=color, s=1)
if logarize: # there's a bug in autoscale
plt.xscale('log')
plt.yscale('log')
y_min = np.min(var_or_disp)
y_min = 0.95 * y_min if y_min > 0 else 1e-1
plt.xlim(0.95 * np.min(means), 1.05 * np.max(means))
plt.ylim(y_min, 1.05 * np.max(var_or_disp))
if idx == 0:
plt.legend()
plt.xlabel(('$log_{10}$ ' if False else '') + 'mean expressions of genes')
data_type = 'dispersions'
plt.ylabel(
('$log_{10}$ ' if False else '')
+ '{} of genes'.format(data_type)
+ (' (normalized)' if idx == 0 else ' (not normalized)')
)
def plot_cluster_umap(
adata: AnnData,
obs_key: list = ["phenograph"],
plot_cluster: list = None,
bad_color="lightgrey",
ncols=2,
dot_size=None,
invert_y=False,
color_list=['violet', 'turquoise', 'tomato', 'teal',
'tan', 'silver', 'sienna', 'red', 'purple',
'plum', 'pink', 'orchid', 'orangered', 'orange',
'olive', 'navy', 'maroon', 'magenta', 'lime',
'lightgreen', 'lightblue', 'lavender', 'khaki',
'indigo', 'grey', 'green', 'gold', 'fuchsia',
'darkgreen', 'darkblue', 'cyan', 'crimson', 'coral',
'chocolate', 'chartreuse', 'brown', 'blue', 'black',
'beige', 'azure', 'aquamarine', 'aqua',
]
): # scatter plot,聚类结果PCA/umap图
"""
Plot spatial distribution of specified obs data.
============ Arguments ============
:param adata: AnnData object.
:param obs_key: specified obs cluster key list, for example: ["phenograph"].
:param plot_cluster: the name list of clusters to show.
:param ncols: numbr of plot columns.
:param dot_size: marker size.
:param cmap: Color map.
:param invert_y: whether to invert y-axis.
============ Return ============
None.
============ Example ============
plot_cluster_umap(adata = adata)
"""
if (isinstance(obs_key, str)):
obs_key = [obs_key]
plot_cluster_result(adata, obs_key=obs_key, pos_key="X_umap", plot_cluster=plot_cluster, bad_color=bad_color,
ncols=ncols, dot_size=dot_size, invert_y=invert_y, color_list=color_list)
def plot_expression_difference(
adata: AnnData,
groups: Union[str, Sequence[str]] = None,
n_genes: int = 20,
key: Optional[str] = 'rank_genes_groups',
fontsize: int = 8,
ncols: int = 4,
sharey: bool = True,
show: Optional[bool] = None,
save: Optional[bool] = None,
ax: Optional[Axes] = None,
**kwds,
): # scatter plot, 差异基因显著性图,类碎石图
"""
Copied from scanpy and modified.
"""
# 调整图像 panel/grid 相关参数
if 'n_panels_per_row' in kwds:
n_panels_per_row = kwds['n_panels_per_row']
else:
n_panels_per_row = ncols
group_names = adata.uns[key]['names'].dtype.names if groups is None else groups
# one panel for each group
# set up the figure
n_panels_x = min(n_panels_per_row, len(group_names))
n_panels_y = np.ceil(len(group_names) / n_panels_x).astype(int)
# 初始化图像
width = 10
height = 10
fig = plt.figure(
figsize=(
n_panels_x * width, # rcParams['figure.figsize'][0],
n_panels_y * height, # rcParams['figure.figsize'][1],
)
)
gs = gridspec.GridSpec(nrows=n_panels_y, ncols=n_panels_x, wspace=0.22, hspace=0.3)
ax0 = None
ymin = np.Inf
ymax = -np.Inf
for count, group_name in enumerate(group_names):
gene_names = adata.uns[key]['names'][group_name][:n_genes]
scores = adata.uns[key]['scores'][group_name][:n_genes]
# Setting up axis, calculating y bounds
if sharey:
ymin = min(ymin, np.min(scores))
ymax = max(ymax, np.max(scores))
if ax0 is None:
ax = fig.add_subplot(gs[count])
ax0 = ax
else:
ax = fig.add_subplot(gs[count], sharey=ax0)
else:
ymin = np.min(scores)
ymax = np.max(scores)
ymax += 0.3 * (ymax - ymin)
ax = fig.add_subplot(gs[count])
ax.set_ylim(ymin, ymax)
ax.set_xlim(-0.9, n_genes - 0.1)
# Making labels
for ig, gene_name in enumerate(gene_names):
ax.text(
ig,
scores[ig],
gene_name,
rotation='vertical',
verticalalignment='bottom',
horizontalalignment='center',
fontsize=fontsize,
)
ax.set_title('{} vs. {}'.format(group_name, "Others"))
if count >= n_panels_x * (n_panels_y - 1):
ax.set_xlabel('ranking')
# print the 'score' label only on the first panel per row.
if count % n_panels_x == 0:
ax.set_ylabel('score')
if sharey is True:
ymax += 0.3 * (ymax - ymin)
ax.set_ylim(ymin, ymax)
def plot_violin_distribution(adata): # 小提琴统计图
"""
绘制数据的分布小提琴图。
============ Arguments ============
:param adata: AnnData object.
============ Return ============
None
"""
_, axs = plt.subplots(1, 3, figsize=(15, 4))
seaborn.violinplot(y=adata.obs['total_counts'], ax=axs[0])
seaborn.violinplot(y=adata.obs['n_genes_by_counts'], ax=axs[1])
seaborn.violinplot(y=adata.obs['pct_counts_mt'], ax=axs[2])
def plot_heatmap_maker_genes(
adata: AnnData = None,
cluster_method="phenograph",
marker_uns_key=None,
num_show_gene=8,
show_labels=True,
order_cluster=True,
marker_clusters=None,
cluster_colors_array=None,
**kwargs
): # heatmap, 差异基因热图
"""
绘制 Marker gene 的热图。热图中每一行代表一个 bin 的所有基因的表达量,所有的 bin 会根据所属的 cluster 进行聚集, cluster 具体展示在热图的左侧,用颜色区分。
============ Arguments ============
:param adata: AnnData object.
:param cluster_methpd: method used in clustering. for example: phenograph, leiden
:param marker_uns_key: the key of adata.uns, the default value is "marker_genes"
:param num_show_gene: number of genes to show in each cluster.
:param show_labels: show gene name on axis.
:param order_cluster: reorder the cluster list in plot (y axis).
:param marker_clusters: the list of clusters to show on the heatmap.
:param cluster_colors_array: the list of colors in the color block on the left of heatmap.
============ Return ============
============ Example ============
plot_heatmap_maker_genes(adata=adata, marker_uns_key = "rank_genes_groups", figsize = (20, 10))
"""
if marker_uns_key is None:
marker_uns_key = 'marker_genes' # "rank_genes_groups" in original scanpy pipeline
# if cluster_method is None:
# cluster_method = str(adata.uns[marker_uns_key]['params']['groupby'])
# cluster_colors_array = adata.uns["phenograph_colors"]
if marker_clusters is None:
marker_clusters = adata.uns[marker_uns_key]['names'].dtype.names
if not set(marker_clusters).issubset(set(adata.uns[marker_uns_key]['names'].dtype.names)):
marker_clusters = adata.uns[marker_uns_key]['names'].dtype.names
gene_names_dict = {} # dict in which each cluster is the keyand the num_show_gene are the values
for cluster in marker_clusters:
# get all genes that are 'non-nan'
genes_array = adata.uns[marker_uns_key]['names'][cluster]
genes_array = genes_array[~pd.isnull(genes_array)]
if len(genes_array) == 0:
logger.warning("Cluster {} has no genes.".format(cluster))
continue
gene_names_dict[cluster] = list(genes_array[:num_show_gene])
adata._sanitize()
gene_names = []
gene_group_labels = []
gene_group_positions = []
start = 0
for label, gene_list in gene_names_dict.items():
if isinstance(gene_list, str):
gene_list = [gene_list]
gene_names.extend(list(gene_list))
gene_group_labels.append(label)
gene_group_positions.append((start, start + len(gene_list) - 1))
start += len(gene_list)
# 此处获取所有绘图所需的数据 (表达量矩阵)
draw_df = pd.DataFrame(index=adata.obs_names)
uniq_gene_names = np.unique(gene_names)
draw_df = pd.concat(
[draw_df, pd.DataFrame(adata.X[tuple([slice(None), adata.var.index.get_indexer(uniq_gene_names)])],
columns=uniq_gene_names, index=adata.obs_names)],
axis=1
)
# add obs values
draw_df = pd.concat([draw_df, adata.obs[cluster_method]], axis=1)
# reorder columns to given order (including duplicates keys if present)
draw_df = draw_df[list([cluster_method]) + list(uniq_gene_names)]
draw_df = draw_df[gene_names].set_index(draw_df[cluster_method].astype('category'))
if order_cluster:
draw_df = draw_df.sort_index()
# From scanpy
# define a layout of 2 rows x 3 columns
# first row is for 'brackets' (if no brackets needed, the height of this row
# is zero) second row is for main content. This second row is divided into
# three axes:
# first ax is for the categories defined by `cluster_method`
# second ax is for the heatmap
# fourth ax is for colorbar
kwargs.setdefault("figsize", (10, 10))
kwargs.setdefault("colorbar_width", 0.2)
colorbar_width = kwargs.get("colorbar_width")
figsize = kwargs.get("figsize")
cluster_block_width = kwargs.setdefault("cluster_block_width", 0.2) if order_cluster else 0
if figsize is None:
height = 6
if show_labels:
heatmap_width = len(gene_names) * 0.3
else:
heatmap_width = 8
width = heatmap_width + cluster_block_width
else:
width, height = figsize
heatmap_width = width - cluster_block_width
if gene_group_positions is not None and len(gene_group_positions) > 0:
# add some space in case 'brackets' want to be plotted on top of the image
height_ratios = [0.15, height]
else:
height_ratios = [0, height]
width_ratios = [
cluster_block_width,
heatmap_width,
colorbar_width,
]
fig = plt.figure(figsize=(width, height))
axs = gridspec.GridSpec(
nrows=2,
ncols=3,
width_ratios=width_ratios,
wspace=0.15 / width,
hspace=0.13 / height,
height_ratios=height_ratios,
)
heatmap_ax = fig.add_subplot(axs[1, 1])
width, height = fig.get_size_inches()
max_cbar_height = 4.0
if height > max_cbar_height:
# to make the colorbar shorter, the
# ax is split and the lower portion is used.
axs2 = gridspec.GridSpecFromSubplotSpec(2, 1, subplot_spec=axs[1, 2],
height_ratios=[height - max_cbar_height, max_cbar_height],
)
heatmap_cbar_ax = fig.add_subplot(axs2[1])
else:
heatmap_cbar_ax = fig.add_subplot(axs[1, 2])
heatmap(df=draw_df, ax=heatmap_ax,
norm=Normalize(vmin=None, vmax=None), plot_colorbar=True, colorbar_ax=heatmap_cbar_ax,
show_labels=True, plot_hline=True)
if order_cluster:
_plot_categories_as_colorblocks(
fig.add_subplot(axs[1, 0]), draw_df, colors=cluster_colors_array, orientation='left'
)
# plot cluster legends on top of heatmap_ax (if given)
if gene_group_positions is not None and len(gene_group_positions) > 0:
_plot_gene_groups_brackets(
fig.add_subplot(axs[0, 1], sharex=heatmap_ax),
group_positions=gene_group_positions,
group_labels=gene_group_labels,
rotation=None,
left_adjustment=-0.3,
right_adjustment=0.3,
)
# plt.savefig()
|
{"/stereo/log_manager.py": ["/stereo/config.py"], "/stereo/plots/plot_utils.py": ["/stereo/plots/_plot_basic/heatmap_plt.py", "/stereo/log_manager.py"], "/stereo/plots/plots.py": ["/stereo/plots/_plot_basic/heatmap_plt.py", "/stereo/log_manager.py"], "/stereo/utils/__init__.py": ["/stereo/utils/correlation.py"], "/stereo/core/stereo_result.py": ["/stereo/log_manager.py"], "/stereo/plots/_plot_basic/heatmap_plt.py": ["/stereo/log_manager.py"]}
|
8,637
|
leying95/stereopy
|
refs/heads/main
|
/stereo/tools/cluster.py
|
#!/usr/bin/env python3
# coding: utf-8
"""
@author: Ping Qiu qiuping1@genomics.cn
@last modified by: Ping Qiu
@file:cluster.py
@time:2021/03/19
"""
import leidenalg as la
from sklearn.decomposition import PCA
from scipy.sparse import coo_matrix
from sklearn.neighbors import NearestNeighbors
import igraph as ig
import numpy as np
from umap.umap_ import fuzzy_simplicial_set
class Neighbors(object):
def __init__(self, x, n_neighbors):
self.x = x
self.n_neighbors = n_neighbors
def find_n_neighbors(self):
nbrs = NearestNeighbors(n_neighbors=self.n_neighbors + 1, algorithm='ball_tree').fit(self.x)
dists, indices = nbrs.kneighbors(self.x)
nn_idx = indices[:, 1:]
nn_dist = dists[:, 1:]
return nn_idx, nn_dist
def get_igraph_from_knn(self, nn_idx, nn_dist):
j = nn_idx.ravel().astype(int)
dist = nn_dist.ravel()
i = np.repeat(np.arange(nn_idx.shape[0]), self.n_neighbors)
vertex = list(range(nn_dist.shape[0]))
edges = list(tuple(zip(i, j)))
G = ig.Graph()
G.add_vertices(vertex)
G.add_edges(edges)
G.es['weight'] = dist
return G
def get_parse_distances(self, nn_idx, nn_dist):
n_obs = self.x.shape[0]
rows = np.zeros((n_obs * self.n_neighbors), dtype=np.int64)
cols = np.zeros((n_obs * self.n_neighbors), dtype=np.int64)
vals = np.zeros((n_obs * self.n_neighbors), dtype=np.float64)
for i in range(nn_idx.shape[0]):
for j in range(self.n_neighbors):
if nn_idx[i, j] == -1:
continue # We didn't get the full knn for i
if nn_idx[i, j] == i:
val = 0.0
else:
val = nn_dist[i, j]
rows[i * self.n_neighbors + j] = i
cols[i * self.n_neighbors + j] = nn_idx[i, j]
vals[i * self.n_neighbors + j] = val
distances = coo_matrix((vals, (rows, cols)), shape=(n_obs, n_obs))
distances.eliminate_zeros()
return distances.tocsr()
def get_connectivities(self, nn_idx, nn_dist):
n_obs = self.x.shape[0]
x = coo_matrix(([], ([], [])), shape=(n_obs, 1))
connectivities = fuzzy_simplicial_set(x, self.n_neighbors, None, None, knn_indices=nn_idx, knn_dists=nn_dist,
set_op_mix_ratio=1.0, local_connectivity=1.0)
if isinstance(connectivities, tuple):
connectivities = connectivities[0]
return connectivities.tocsr()
def run_neighbors(x, neighbors=30):
neighbor = Neighbors(x, neighbors)
nn_idx, nn_dist = neighbor.find_n_neighbors()
return neighbor, nn_idx, nn_dist
def run_louvain(x, neighbor, nn_idx, nn_dist):
g = neighbor.get_igraph_from_knn(nn_idx, nn_dist)
louvain_partition = g.community_multilevel(weights=g.es['weight'], return_levels=False)
clusters = np.arange(x.shape[0])
for i in range(len(louvain_partition)):
clusters[louvain_partition[i]] = str(i)
return clusters
def run_knn_leiden(x, neighbor, nn_idx, nn_dist, diff=1):
g = neighbor.get_igraph_from_knn(nn_idx, nn_dist)
optimiser = la.Optimiser()
leiden_partition = la.ModularityVertexPartition(g, weights=g.es['weight'])
while diff > 0:
diff = optimiser.optimise_partition(leiden_partition, n_iterations=10)
clusters = np.arange(x.shape[0])
for i in range(len(leiden_partition)):
clusters[leiden_partition[i]] = str(i)
return clusters
def run_cluster(x, method='leiden', do_pca=True, n_pcs=30):
"""
:param x: np.array, shape: (m, n),m个bin, n为embedding
:param method:
:param do_pca:
:param n_pcs:
:return:
"""
if do_pca:
pca_obj = PCA(n_components=n_pcs)
x = pca_obj.fit_transform(x)
neighbor, nn_idx, nn_dist = run_neighbors(x)
if method == 'leiden':
cluster = run_knn_leiden(x, neighbor, nn_idx, nn_dist)
else:
cluster = run_louvain(x, neighbor, nn_idx, nn_dist)
return cluster
|
{"/stereo/log_manager.py": ["/stereo/config.py"], "/stereo/plots/plot_utils.py": ["/stereo/plots/_plot_basic/heatmap_plt.py", "/stereo/log_manager.py"], "/stereo/plots/plots.py": ["/stereo/plots/_plot_basic/heatmap_plt.py", "/stereo/log_manager.py"], "/stereo/utils/__init__.py": ["/stereo/utils/correlation.py"], "/stereo/core/stereo_result.py": ["/stereo/log_manager.py"], "/stereo/plots/_plot_basic/heatmap_plt.py": ["/stereo/log_manager.py"]}
|
8,638
|
leying95/stereopy
|
refs/heads/main
|
/stereo/plots/plots.py
|
#!/usr/bin/env python3
# coding: utf-8
"""
@author: Ping Qiu qiuping1@genomics.cn
@last modified by: Ping Qiu
@file:plots.py
@time:2021/03/31
"""
from matplotlib.cm import get_cmap
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap, to_hex, Normalize
from matplotlib import gridspec
from ._plot_basic.get_stereo_data import get_cluster_res, get_reduce_x, get_position_array, get_degs_res
import numpy as np
import pandas as pd
from anndata import AnnData
from ._plot_basic.scatter_plt import scatter
import seaborn
from typing import Optional, Sequence, Union
from matplotlib.axes import Axes
from ._plot_basic.heatmap_plt import heatmap, plot_categories_as_colorblocks, plot_gene_groups_brackets
from ..log_manager import logger
from scipy.sparse import issparse
def plot_spatial_cluster(
adata: AnnData,
obs_key: list = ["phenograph"],
pos_key: str = "spatial",
plot_cluster: list = None,
bad_color: str = "lightgrey",
ncols: int = 2,
dot_size: int = None,
color_list=['violet', 'turquoise', 'tomato', 'teal','tan', 'silver', 'sienna', 'red', 'purple', 'plum', 'pink',
'orchid', 'orangered', 'orange', 'olive', 'navy', 'maroon', 'magenta', 'lime',
'lightgreen', 'lightblue', 'lavender', 'khaki', 'indigo', 'grey', 'green', 'gold', 'fuchsia',
'darkgreen', 'darkblue', 'cyan', 'crimson', 'coral', 'chocolate', 'chartreuse', 'brown', 'blue', 'black',
'beige', 'azure', 'aquamarine', 'aqua',
],
): # scatter plot, 聚类后表达矩阵空间分布
"""
Plot spatial distribution of specified obs data.
============ Arguments ============
:param adata: AnnData object.
:param obs_key: specified obs cluster key list, for example: ["phenograph"].
:param pos_key: the coordinates of data points for scatter plots. the data points are stored in adata.obsm[pos_key]. choice: "spatial", "X_umap", "X_pca".
:param plot_cluster: the name list of clusters to show.
:param bad_color: the name list of clusters to show.
:param ncols: numbr of plot columns.
:param dot_size: marker size.
:param color_list: whether to invert y-axis.
============ Return ============
None.
============ Example ============
plot_spatial_cluster(adata = adata)
"""
# sc.pl.embedding(adata, basis="spatial", color=["total_counts", "n_genes_by_counts"],size=30)
if dot_size is None:
dot_size = 120000 / adata.shape[0]
ncols = min(ncols, len(obs_key))
nrows = np.ceil(len(obs_key) / ncols).astype(int)
# each panel will have the size of rcParams['figure.figsize']
fig = plt.figure(figsize=(ncols * 10, nrows * 8))
left = 0.2 / ncols
bottom = 0.13 / nrows
axs = gridspec.GridSpec(
nrows=nrows,
ncols=ncols,
left=left,
right=1 - (ncols - 1) * left - 0.01 / ncols,
bottom=bottom,
top=1 - (nrows - 1) * bottom - 0.1 / nrows,
# hspace=hspace,
# wspace=wspace,
)
if color_list is None:
cmap = get_cmap()
else:
cmap = ListedColormap(color_list)
cmap.set_bad(bad_color)
# 把特定值改为 np.nan 之后,可以利用 cmap.set_bad("white") 来遮盖掉这部分数据
for i, key in enumerate(obs_key):
# color_data = adata.obs_vector(key) # TODO replace by get_cluster_res
color_data = get_cluster_res(adata, data_key=key)
pc_logic = False
# color_data = np.asarray(color_data_raw, dtype=float)
order = np.argsort(~pd.isnull(color_data), kind="stable")
# spatial_data = np.array(adata.obsm[pos_key])[:, 0: 2]
spatial_data = get_reduce_x(data=adata, data_key=pos_key)[:, 0:2] if pos_key != 'spatial' \
else get_position_array(adata, pos_key)
color_data = color_data[order]
spatial_data = spatial_data[order, :]
color_dict = {}
has_na = False
if pd.api.types.is_categorical_dtype(color_data):
pc_logic = True
if plot_cluster is None:
plot_cluster = list(color_data.categories)
if pc_logic:
cluster_n = len(np.unique(color_data))
if len(color_list) < cluster_n:
color_list = color_list * cluster_n
cmap = ListedColormap(color_list)
cmap.set_bad(bad_color)
if len(color_data.categories) > len(plot_cluster):
color_data = color_data.replace(color_data.categories.difference(plot_cluster), np.nan)
has_na = True
color_dict = {str(k): to_hex(v) for k, v in enumerate(color_list)}
print(color_dict)
color_data = color_data.map(color_dict)
if pd.api.types.is_categorical_dtype(color_data):
color_data = pd.Categorical(color_data)
if has_na:
color_data = color_data.add_categories([to_hex(bad_color)])
color_data = color_data.fillna(to_hex(bad_color))
# color_dict["NA"]
# color_data 是图像中各个点的值,也对应了每个点的颜色。data_points则对应了各个点的坐标
ax = fig.add_subplot(axs[i]) # ax = plt.subplot(axs[i]) || ax = fig.add_subplot(axs[1, 1]))
ax.set_title(key)
ax.set_yticks([])
ax.set_xticks([])
ax.set_xlabel("spatial1")
ax.set_ylabel("spatial2")
pathcollection = scatter(
spatial_data[:, 0],
spatial_data[:, 1],
ax=ax,
marker=".",
dot_colors=color_data,
dot_size=dot_size
)
if pc_logic:
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.91, box.height])
# -------------modified by qiuping1@genomics.cn-------------
# valid_cate = color_data.categories
# cat_num = len(adata.obs_vector(key).categories)
# for label in adata.obs_vector(key).categories:
categories = get_cluster_res(adata, data_key=key).categories
cat_num = len(categories)
for label in categories:
# --------modified end------------------
ax.scatter([], [], c=color_dict[label], label=label)
ax.legend(
frameon=False,
loc='center left',
bbox_to_anchor=(1, 0.5),
ncol=(1 if cat_num <= 14 else 2 if cat_num <= 30 else 3),
# fontsize=legend_fontsize,
)
else:
plt.colorbar(pathcollection, ax=ax, pad=0.01, fraction=0.08, aspect=30)
ax.autoscale_view()
def plot_violin_distribution(adata): # 小提琴统计图
"""
绘制数据的分布小提琴图。
============ Arguments ============
:param adata: AnnData object.
============ Return ============
None
"""
_, axs = plt.subplots(1, 3, figsize=(15, 4))
seaborn.violinplot(y=adata.obs['total_counts'], ax=axs[0])
seaborn.violinplot(y=adata.obs['n_genes_by_counts'], ax=axs[1])
seaborn.violinplot(y=adata.obs['pct_counts_mt'], ax=axs[2])
def plot_degs(
adata: AnnData,
groups: Union[str, Sequence[str]] = 'all',
n_genes: int = 20,
key: Optional[str] = 'find_marker',
fontsize: int = 8,
ncols: int = 4,
sharey: bool = True,
ax: Optional[Axes] = None,
**kwds,
): # scatter plot, 差异基因显著性图,类碎石图
"""
Copied from scanpy and modified.
"""
# 调整图像 panel/grid 相关参数
if 'n_panels_per_row' in kwds:
n_panels_per_row = kwds['n_panels_per_row']
else:
n_panels_per_row = ncols
# group_names = adata.uns[key]['names'].dtype.names if groups is None else groups
if groups == 'all':
group_names = list(adata.uns[key].keys())
else:
group_names = [groups] if isinstance(groups, str) else groups
# one panel for each group
# set up the figure
n_panels_x = min(n_panels_per_row, len(group_names))
n_panels_y = np.ceil(len(group_names) / n_panels_x).astype(int)
# 初始化图像
width = 10
height = 10
fig = plt.figure(
figsize=(
n_panels_x * width, # rcParams['figure.figsize'][0],
n_panels_y * height, # rcParams['figure.figsize'][1],
)
)
gs = gridspec.GridSpec(nrows=n_panels_y, ncols=n_panels_x, wspace=0.22, hspace=0.3)
ax0 = None
ymin = np.Inf
ymax = -np.Inf
for count, group_name in enumerate(group_names):
result = get_degs_res(adata, data_key=key, group_key=group_name, top_k=n_genes)
gene_names = result.genes.values
scores = result.scores.values
# Setting up axis, calculating y bounds
if sharey:
ymin = min(ymin, np.min(scores))
ymax = max(ymax, np.max(scores))
if ax0 is None:
ax = fig.add_subplot(gs[count])
ax0 = ax
else:
ax = fig.add_subplot(gs[count], sharey=ax0)
else:
ymin = np.min(scores)
ymax = np.max(scores)
ymax += 0.3 * (ymax - ymin)
ax = fig.add_subplot(gs[count])
ax.set_ylim(ymin, ymax)
ax.set_xlim(-0.9, n_genes - 0.1)
# Making labels
for ig, gene_name in enumerate(gene_names):
ax.text(
ig,
scores[ig],
gene_name,
rotation='vertical',
verticalalignment='bottom',
horizontalalignment='center',
fontsize=fontsize,
)
ax.set_title(group_name)
if count >= n_panels_x * (n_panels_y - 1):
ax.set_xlabel('ranking')
# print the 'score' label only on the first panel per row.
if count % n_panels_x == 0:
ax.set_ylabel('score')
if sharey is True:
ymax += 0.3 * (ymax - ymin)
ax.set_ylim(ymin, ymax)
def plot_spatial_distribution(
adata: AnnData,
obs_key: list = ["total_counts", "n_genes_by_counts"],
ncols=2,
dot_size=None,
color_list=None,
invert_y=False
): # scatter plot, 表达矩阵空间分布
"""
Plot spatial distribution of specified obs data.
============ Arguments ============
:param adata: AnnData object.
:param obs_key: specified obs key list, for example: ["total_counts", "n_genes_by_counts"]
:param ncols: numbr of plot columns.
:param dot_size: marker size.
:param color_list: Color list.
:param invert_y: whether to invert y-axis.
============ Return ============
None
============ Example ============
plot_spatial_distribution(adata=adata)
"""
# sc.pl.embedding(adata, basis="spatial", color=["total_counts", "n_genes_by_counts"],size=30)
if dot_size is None:
dot_size = 120000 / adata.shape[0]
ncols = min(ncols, len(obs_key))
nrows = np.ceil(len(obs_key) / ncols).astype(int)
# each panel will have the size of rcParams['figure.figsize']
fig = plt.figure(figsize=(ncols * 10, nrows * 8))
left = 0.2 / ncols
bottom = 0.13 / nrows
axs = gridspec.GridSpec(
nrows=nrows,
ncols=ncols,
left=left,
right=1 - (ncols - 1) * left - 0.01 / ncols,
bottom=bottom,
top=1 - (nrows - 1) * bottom - 0.1 / nrows,
# hspace=hspace,
# wspace=wspace,
)
if color_list is None:
cmap = get_cmap()
else:
cmap = ListedColormap(color_list)
# 把特定值改为 np.nan 之后,可以利用 cmap.set_bad("white") 来遮盖掉这部分数据
# 散点图上每个点的坐标数据来自于 adata 的 obsm["spatial"],每个点的颜色(数值)数据来自于 adata 的 obs_vector()
for i, key in enumerate(obs_key):
# color_data = np.asarray(adata.obs_vector(key), dtype=float)
color_data = adata.obs_vector(key)
order = np.argsort(~pd.isnull(color_data), kind="stable")
spatial_data = np.array(adata.obsm["spatial"])[:, 0: 2]
color_data = color_data[order]
spatial_data = spatial_data[order, :]
# color_data 是图像中各个点的值,也对应了每个点的颜色。data_points则对应了各个点的坐标
ax = fig.add_subplot(axs[i]) # ax = plt.subplot(axs[i]) || ax = fig.add_subplot(axs[1, 1]))
ax.set_title(key)
ax.set_yticks([])
ax.set_xticks([])
ax.set_xlabel("spatial1")
ax.set_ylabel("spatial2")
pathcollection = scatter(
spatial_data[:, 0],
spatial_data[:, 1],
ax=ax,
marker=".",
dot_colors=color_data,
dot_size=dot_size,
cmap=cmap,
)
plt.colorbar(
pathcollection,
ax=ax,
pad=0.01,
fraction=0.08,
aspect=30,
)
ax.autoscale_view()
if invert_y:
ax.invert_yaxis()
def plot_heatmap_maker_genes(
adata: AnnData = None,
cluster_method="phenograph",
marker_uns_key=None,
num_show_gene=8,
show_labels=True,
order_cluster=True,
marker_clusters=None,
cluster_colors_array=None,
**kwargs
): # heatmap, 差异基因热图
"""
绘制 Marker gene 的热图。热图中每一行代表一个 bin 的所有基因的表达量,所有的 bin 会根据所属的 cluster 进行聚集, cluster 具体展示在热图的左侧,用颜色区分。
============ Arguments ============
:param adata: AnnData object.
:param cluster_method: method used in clustering. for example: phenograph, leiden
:param marker_uns_key: the key of adata.uns, the default value is "marker_genes"
:param num_show_gene: number of genes to show in each cluster.
:param show_labels: show gene name on axis.
:param order_cluster: reorder the cluster list in plot (y axis).
:param marker_clusters: the list of clusters to show on the heatmap.
:param cluster_colors_array: the list of colors in the color block on the left of heatmap.
============ Return ============
============ Example ============
plot_heatmap_maker_genes(adata=adata, marker_uns_key = "rank_genes_groups", figsize = (20, 10))
"""
if marker_uns_key is None:
marker_uns_key = 'marker_genes' # "rank_genes_groups" in original scanpy pipeline
marker_res = adata.uns[marker_uns_key]
default_cluster = [i for i in marker_res.keys()]
if marker_clusters is None:
marker_clusters = default_cluster
if not set(marker_clusters).issubset(set(default_cluster)):
marker_clusters = default_cluster
gene_names_dict = {} # dict in which each cluster is the keyand the num_show_gene are the values
for cluster in marker_clusters:
top_marker = marker_res[cluster].top_k_marker(top_k_genes=num_show_gene, sort_key='scores')
genes_array = top_marker['genes'].values
if len(genes_array) == 0:
logger.warning("Cluster {} has no genes.".format(cluster))
continue
gene_names_dict[cluster] = genes_array
gene_names = []
gene_group_labels = []
gene_group_positions = []
start = 0
for label, gene_list in gene_names_dict.items():
if isinstance(gene_list, str):
gene_list = [gene_list]
gene_names.extend(list(gene_list))
gene_group_labels.append(label)
gene_group_positions.append((start, start + len(gene_list) - 1))
start += len(gene_list)
# 此处获取所有绘图所需的数据 (表达量矩阵)
uniq_gene_names = np.unique(gene_names)
exp_matrix = adata.X.toarray() if issparse(adata.X) else adata.X
draw_df = pd.DataFrame(exp_matrix[:, adata.var.index.get_indexer(uniq_gene_names)],
columns=uniq_gene_names, index=adata.obs_names)
# add obs values
cluster_data = adata.uns[cluster_method].cluster.set_index('bins')
draw_df = pd.concat([draw_df, cluster_data], axis=1)
draw_df = draw_df[gene_names].set_index(draw_df['cluster'].astype('category'))
if order_cluster:
draw_df = draw_df.sort_index()
kwargs.setdefault("figsize", (10, 10))
kwargs.setdefault("colorbar_width", 0.2)
colorbar_width = kwargs.get("colorbar_width")
figsize = kwargs.get("figsize")
cluster_block_width = kwargs.setdefault("cluster_block_width", 0.2) if order_cluster else 0
if figsize is None:
height = 6
if show_labels:
heatmap_width = len(gene_names) * 0.3
else:
heatmap_width = 8
width = heatmap_width + cluster_block_width
else:
width, height = figsize
heatmap_width = width - cluster_block_width
if gene_group_positions is not None and len(gene_group_positions) > 0:
# add some space in case 'brackets' want to be plotted on top of the image
height_ratios = [0.15, height]
else:
height_ratios = [0, height]
width_ratios = [
cluster_block_width,
heatmap_width,
colorbar_width,
]
fig = plt.figure(figsize=(width, height))
axs = gridspec.GridSpec(
nrows=2,
ncols=3,
width_ratios=width_ratios,
wspace=0.15 / width,
hspace=0.13 / height,
height_ratios=height_ratios,
)
heatmap_ax = fig.add_subplot(axs[1, 1])
width, height = fig.get_size_inches()
max_cbar_height = 4.0
if height > max_cbar_height:
# to make the colorbar shorter, the
# ax is split and the lower portion is used.
axs2 = gridspec.GridSpecFromSubplotSpec(2, 1, subplot_spec=axs[1, 2],
height_ratios=[height - max_cbar_height, max_cbar_height],
)
heatmap_cbar_ax = fig.add_subplot(axs2[1])
else:
heatmap_cbar_ax = fig.add_subplot(axs[1, 2])
heatmap(df=draw_df, ax=heatmap_ax,
norm=Normalize(vmin=None, vmax=None), plot_colorbar=True, colorbar_ax=heatmap_cbar_ax,
show_labels=True, plot_hline=True)
if order_cluster:
plot_categories_as_colorblocks(
fig.add_subplot(axs[1, 0]), draw_df, colors=cluster_colors_array, orientation='left'
)
# plot cluster legends on top of heatmap_ax (if given)
if gene_group_positions is not None and len(gene_group_positions) > 0:
plot_gene_groups_brackets(
fig.add_subplot(axs[0, 1], sharex=heatmap_ax),
group_positions=gene_group_positions,
group_labels=gene_group_labels,
rotation=None,
left_adjustment=-0.3,
right_adjustment=0.3,
)
|
{"/stereo/log_manager.py": ["/stereo/config.py"], "/stereo/plots/plot_utils.py": ["/stereo/plots/_plot_basic/heatmap_plt.py", "/stereo/log_manager.py"], "/stereo/plots/plots.py": ["/stereo/plots/_plot_basic/heatmap_plt.py", "/stereo/log_manager.py"], "/stereo/utils/__init__.py": ["/stereo/utils/correlation.py"], "/stereo/core/stereo_result.py": ["/stereo/log_manager.py"], "/stereo/plots/_plot_basic/heatmap_plt.py": ["/stereo/log_manager.py"]}
|
8,639
|
leying95/stereopy
|
refs/heads/main
|
/stereo/utils/__init__.py
|
#!/usr/bin/env python3
# coding: utf-8
"""
@author: Ping Qiu qiuping1@genomics.cn
@last modified by: Ping Qiu
@file:__init__.py.py
@time:2021/03/05
"""
import shutil
import os
from .correlation import pearson_corr, spearmanr_corr
from .data_helper import select_group
def remove_file(path):
if os.path.isfile(path):
os.remove(path)
if os.path.isdir(path):
shutil.rmtree(path)
|
{"/stereo/log_manager.py": ["/stereo/config.py"], "/stereo/plots/plot_utils.py": ["/stereo/plots/_plot_basic/heatmap_plt.py", "/stereo/log_manager.py"], "/stereo/plots/plots.py": ["/stereo/plots/_plot_basic/heatmap_plt.py", "/stereo/log_manager.py"], "/stereo/utils/__init__.py": ["/stereo/utils/correlation.py"], "/stereo/core/stereo_result.py": ["/stereo/log_manager.py"], "/stereo/plots/_plot_basic/heatmap_plt.py": ["/stereo/log_manager.py"]}
|
8,640
|
leying95/stereopy
|
refs/heads/main
|
/stereo/utils/correlation.py
|
#!/usr/bin/env python3
# coding: utf-8
"""
@author: Ping Qiu qiuping1@genomics.cn
@last modified by: Ping Qiu
@file:correlation.py
@time:2021/03/11
"""
import numpy as np
import pandas as pd
from scipy import stats
def pearson(arr1, arr2):
"""
calculate pearson correlation between two numpy arrays.
:param arr1: one array, the feature is a column. the shape is `m * n`
:param arr2: the other array, the feature is a column. the shape is `m * k`
:return: a pearson score np.array , the shape is `k * n`
"""
assert arr1.shape[0] == arr2.shape[0]
n = arr1.shape[0]
sums = np.multiply.outer(arr2.sum(0), arr1.sum(0))
stds = np.multiply.outer(arr2.std(0), arr1.std(0))
return (arr2.T.dot(arr1) - sums / n) / stds / n
def pearson_corr(df1, df2):
"""
calculate pearson correlation between two dataframes.
:param df1: one dataframe
:param df2: the other dataframe
:return: a pearson score dataframe, the index is the columns of `df1`, the columns is the columns of `df2`
"""
v1, v2 = df1.values, df2.values
corr_matrix = pearson(v1, v2)
return pd.DataFrame(corr_matrix, df2.columns, df1.columns)
def spearmanr_corr(df1, df2):
"""
calculate pearson correlation between two dataframes.
:param df1: one dataframe
:param df2: the other dataframe
:return: a spearmanr score dataframe, the index is the columns of `df1`, the columns is the columns of `df2`
"""
score, pvalue = stats.spearmanr(df1.values, df2.values)
score = score[df1.shape[1]:, 0:df1.shape[1]]
return pd.DataFrame(score, df2.columns, df1.columns)
|
{"/stereo/log_manager.py": ["/stereo/config.py"], "/stereo/plots/plot_utils.py": ["/stereo/plots/_plot_basic/heatmap_plt.py", "/stereo/log_manager.py"], "/stereo/plots/plots.py": ["/stereo/plots/_plot_basic/heatmap_plt.py", "/stereo/log_manager.py"], "/stereo/utils/__init__.py": ["/stereo/utils/correlation.py"], "/stereo/core/stereo_result.py": ["/stereo/log_manager.py"], "/stereo/plots/_plot_basic/heatmap_plt.py": ["/stereo/log_manager.py"]}
|
8,641
|
leying95/stereopy
|
refs/heads/main
|
/stereo/core/stereo_result.py
|
#!/usr/bin/env python3
# coding: utf-8
"""
@author: Ping Qiu qiuping1@genomics.cn
@last modified by: Ping Qiu
@file:stereo_result.py
@time:2021/03/18
"""
from typing import Optional
import numpy as np
import pandas as pd
from ..log_manager import logger
class StereoResult(object):
def __init__(self, name: str = 'stereo', param: Optional[dict] = None):
self.name = name
self.params = {} if param is None else param
def update_params(self, v):
self.params = v
def __str__(self):
class_info = f'{self.__class__.__name__} of {self.name}. \n'
class_info += f' params: {self.params}\n'
return class_info
def __repr__(self):
return self.__str__()
class DimReduceResult(StereoResult):
def __init__(self, name: str = 'dim_reduce', param: Optional[dict] = None, x_reduce: Optional[np.ndarray] = None,
variance_pca: Optional[np.ndarray] = None, variance_ratio: Optional[np.ndarray] = None,
pcs: Optional[np.ndarray] = None):
super(DimReduceResult, self).__init__(name, param)
self.x_reduce = x_reduce
self.variance_pca = variance_pca
self.variance_ratio = variance_ratio
self.pcs = pcs
class FindMarkerResult(StereoResult):
def __init__(self, name: str = 'find_marker', param: Optional[dict] = None,
degs_data: Optional[pd.DataFrame] = None):
super(FindMarkerResult, self).__init__(name, param)
self.degs_data = degs_data
def __str__(self):
info = super(FindMarkerResult, self).__str__()
if self.degs_data is not None:
info += f' result: a DataFrame which has `genes`,`pvalues`,`pvalues_adj`, `log2fc`, `score` columns.\n'
info += f' the shape is: {self.degs_data.shape}'
return info
def top_k_marker(self, top_k_genes=10, sort_key='pvalues', ascend=False):
"""
obtain the first k significantly different genes
:param top_k_genes: the number of top k
:param sort_key: sort by the column
:param ascend: the ascend order of sorting.
:return:
"""
if self.degs_data is not None:
top_k_data = self.degs_data.sort_values(by=sort_key, ascending=ascend).head(top_k_genes)
return top_k_data
else:
logger.warning('the result of degs is None, return None.')
return None
class CellTypeResult(StereoResult):
def __init__(self, name='cell_type_anno', param=None, anno_data=None):
super(CellTypeResult, self).__init__(name=name, param=param)
self.anno_data = anno_data
def __str__(self):
info = super(CellTypeResult, self).__str__()
if self.anno_data is not None:
info += f' result: a DataFrame which has `cells`,`cell type`,`corr_score` columns.\n'
info += f' the shape is: {self.anno_data.shape}'
return info
class ClusterResult(StereoResult):
def __init__(self, name='cluster', param=None, cluster_info=None):
super(ClusterResult, self).__init__(name=name, param=param)
self.cluster = cluster_info
def __str__(self):
info = super(ClusterResult, self).__str__()
if self.cluster is not None:
info += f' result: a DataFrame which has `cells`,`cluster` columns.\n'
info += f' the shape is: {self.cluster.shape}'
return info
|
{"/stereo/log_manager.py": ["/stereo/config.py"], "/stereo/plots/plot_utils.py": ["/stereo/plots/_plot_basic/heatmap_plt.py", "/stereo/log_manager.py"], "/stereo/plots/plots.py": ["/stereo/plots/_plot_basic/heatmap_plt.py", "/stereo/log_manager.py"], "/stereo/utils/__init__.py": ["/stereo/utils/correlation.py"], "/stereo/core/stereo_result.py": ["/stereo/log_manager.py"], "/stereo/plots/_plot_basic/heatmap_plt.py": ["/stereo/log_manager.py"]}
|
8,642
|
leying95/stereopy
|
refs/heads/main
|
/stereo/core/__init__.py
|
#!/usr/bin/env python3
# coding: utf-8
"""
@author: Ping Qiu qiuping1@genomics.cn
@last modified by: Ping Qiu
@file:__init__.py.py
@time:2021/03/17
"""
|
{"/stereo/log_manager.py": ["/stereo/config.py"], "/stereo/plots/plot_utils.py": ["/stereo/plots/_plot_basic/heatmap_plt.py", "/stereo/log_manager.py"], "/stereo/plots/plots.py": ["/stereo/plots/_plot_basic/heatmap_plt.py", "/stereo/log_manager.py"], "/stereo/utils/__init__.py": ["/stereo/utils/correlation.py"], "/stereo/core/stereo_result.py": ["/stereo/log_manager.py"], "/stereo/plots/_plot_basic/heatmap_plt.py": ["/stereo/log_manager.py"]}
|
8,643
|
leying95/stereopy
|
refs/heads/main
|
/stereo/plots/_plot_basic/heatmap_plt.py
|
#!/usr/bin/env python3
# coding: utf-8
"""
@author: Shixu He heshixu@genomics.cn
@last modified by: Shixu He
@file:heatmap_plt.py
@time:2021/03/15
"""
from matplotlib.cm import get_cmap
from matplotlib.axes import Axes
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize
from matplotlib import gridspec
from anndata import AnnData
import numpy as np
import pandas as pd
from typing import List, Iterable, Sequence, Optional, Tuple
from typing_extensions import Literal
from ...log_manager import logger
def heatmap(df: pd.DataFrame = None, ax: Axes = None, cmap=None, norm=None, plot_colorbar=False,
colorbar_ax: Axes = None, show_labels=True, plot_hline=False, **kwargs):
"""
:param df:
:param ax:
:param cmap:
:param norm:
:param plot_colorbar:
:param colorbar_ax:
:param show_labels:
:param plot_hline:
:param kwargs:
:return:
"""
if norm == None:
norm = Normalize(vmin=None, vmax=None)
if (plot_colorbar and colorbar_ax == None):
logger.warning("Colorbar ax is not provided.")
plot_colorbar = False
kwargs.setdefault('interpolation', 'nearest')
im = ax.imshow(df.values, aspect='auto', norm=norm, **kwargs)
ax.set_ylim(df.shape[0] - 0.5, -0.5)
ax.set_xlim(-0.5, df.shape[1] - 0.5)
ax.tick_params(axis='y', left=False, labelleft=False)
ax.set_ylabel('')
ax.grid(False)
if show_labels:
ax.tick_params(axis='x', labelsize='small')
ax.set_xticks(np.arange(df.shape[1]))
ax.set_xticklabels(list(df.columns), rotation=90)
else:
ax.tick_params(axis='x', labelbottom=False, bottom=False)
if plot_colorbar:
plt.colorbar(im, cax=colorbar_ax)
if plot_hline:
line_coord = (
np.cumsum(df.index.value_counts(sort=False))[:-1] - 0.5
)
ax.hlines(
line_coord,
-0.5,
df.shape[1] - 0.5,
lw=1,
color='black',
zorder=10,
clip_on=False,
)
def plot_categories_as_colorblocks(
groupby_ax: Axes,
obs_tidy: pd.DataFrame,
colors=None,
orientation: Literal['top', 'bottom', 'left', 'right'] = 'left',
cmap_name: str = 'tab20',
):
"""from scanpy"""
groupby = obs_tidy.index.name
from matplotlib.colors import ListedColormap, BoundaryNorm
if colors is None:
groupby_cmap = plt.get_cmap(cmap_name)
else:
groupby_cmap = ListedColormap(colors, groupby + '_cmap')
norm = BoundaryNorm(np.arange(groupby_cmap.N + 1) - 0.5, groupby_cmap.N)
# determine groupby label positions such that they appear
# centered next/below to the color code rectangle assigned to the category
value_sum = 0
ticks = [] # list of centered position of the labels
labels = []
label2code = {} # dictionary of numerical values asigned to each label
for code, (label, value) in enumerate(
obs_tidy.index.value_counts(sort=False).iteritems()
):
ticks.append(value_sum + (value / 2))
labels.append(label)
value_sum += value
label2code[label] = code
groupby_ax.grid(False)
if orientation == 'left':
groupby_ax.imshow(
np.array([[label2code[lab] for lab in obs_tidy.index]]).T,
aspect='auto',
cmap=groupby_cmap,
norm=norm,
)
if len(labels) > 1:
groupby_ax.set_yticks(ticks)
groupby_ax.set_yticklabels(labels)
# remove y ticks
groupby_ax.tick_params(axis='y', left=False, labelsize='small')
# remove x ticks and labels
groupby_ax.tick_params(axis='x', bottom=False, labelbottom=False)
# remove surrounding lines
groupby_ax.spines['right'].set_visible(False)
groupby_ax.spines['top'].set_visible(False)
groupby_ax.spines['left'].set_visible(False)
groupby_ax.spines['bottom'].set_visible(False)
groupby_ax.set_ylabel(groupby)
else:
groupby_ax.imshow(
np.array([[label2code[lab] for lab in obs_tidy.index]]),
aspect='auto',
cmap=groupby_cmap,
norm=norm,
)
if len(labels) > 1:
groupby_ax.set_xticks(ticks)
if max([len(str(x)) for x in labels]) < 3:
# if the labels are small do not rotate them
rotation = 0
else:
rotation = 90
groupby_ax.set_xticklabels(labels, rotation=rotation)
# remove x ticks
groupby_ax.tick_params(axis='x', bottom=False, labelsize='small')
# remove y ticks and labels
groupby_ax.tick_params(axis='y', left=False, labelleft=False)
# remove surrounding lines
groupby_ax.spines['right'].set_visible(False)
groupby_ax.spines['top'].set_visible(False)
groupby_ax.spines['left'].set_visible(False)
groupby_ax.spines['bottom'].set_visible(False)
groupby_ax.set_xlabel(groupby)
return label2code, ticks, labels, groupby_cmap, norm
def plot_gene_groups_brackets(
gene_groups_ax: Axes,
group_positions: Iterable[Tuple[int, int]],
group_labels: Sequence[str],
left_adjustment: float = -0.3,
right_adjustment: float = 0.3,
rotation: Optional[float] = None,
orientation: Literal['top', 'right'] = 'top',
):
"""from scanpy"""
import matplotlib.patches as patches
from matplotlib.path import Path
# get the 'brackets' coordinates as lists of start and end positions
left = [x[0] + left_adjustment for x in group_positions]
right = [x[1] + right_adjustment for x in group_positions]
# verts and codes are used by PathPatch to make the brackets
verts = []
codes = []
if orientation == 'top':
# rotate labels if any of them is longer than 4 characters
if rotation is None and group_labels:
if max([len(x) for x in group_labels]) > 4:
rotation = 90
else:
rotation = 0
for idx in range(len(left)):
verts.append((left[idx], 0)) # lower-left
verts.append((left[idx], 0.6)) # upper-left
verts.append((right[idx], 0.6)) # upper-right
verts.append((right[idx], 0)) # lower-right
codes.append(Path.MOVETO)
codes.append(Path.LINETO)
codes.append(Path.LINETO)
codes.append(Path.LINETO)
try:
group_x_center = left[idx] + float(right[idx] - left[idx]) / 2
gene_groups_ax.text(
group_x_center,
1.1,
group_labels[idx],
ha='center',
va='bottom',
rotation=rotation,
)
except:
pass
else:
top = left
bottom = right
for idx in range(len(top)):
verts.append((0, top[idx])) # upper-left
verts.append((0.15, top[idx])) # upper-right
verts.append((0.15, bottom[idx])) # lower-right
verts.append((0, bottom[idx])) # lower-left
codes.append(Path.MOVETO)
codes.append(Path.LINETO)
codes.append(Path.LINETO)
codes.append(Path.LINETO)
try:
diff = bottom[idx] - top[idx]
group_y_center = top[idx] + float(diff) / 2
if diff * 2 < len(group_labels[idx]):
# cut label to fit available space
group_labels[idx] = group_labels[idx][: int(diff * 2)] + "."
gene_groups_ax.text(
0.6,
group_y_center,
group_labels[idx],
ha='right',
va='center',
rotation=270,
fontsize='small',
)
except Exception as e:
print('problems {}'.format(e))
pass
path = Path(verts, codes)
patch = patches.PathPatch(path, facecolor='none', lw=1.5)
gene_groups_ax.add_patch(patch)
gene_groups_ax.grid(False)
gene_groups_ax.axis('off')
# remove y ticks
gene_groups_ax.tick_params(axis='y', left=False, labelleft=False)
# remove x ticks and labels
gene_groups_ax.tick_params(
axis='x', bottom=False, labelbottom=False, labeltop=False
)
def _check_indices(
dim_df: pd.DataFrame,
alt_index: pd.Index,
dim: "Literal['obs', 'var']",
keys: List[str],
alias_index: pd.Index = None,
use_raw: bool = False,
):
"""from scanpy"""
if use_raw:
alt_repr = "adata.raw"
else:
alt_repr = "adata"
alt_dim = ("obs", "var")[dim == "obs"]
alias_name = None
if alias_index is not None:
alt_names = pd.Series(alt_index, index=alias_index)
alias_name = alias_index.name
alt_search_repr = f"{alt_dim}['{alias_name}']"
else:
alt_names = pd.Series(alt_index, index=alt_index)
alt_search_repr = f"{alt_dim}_names"
col_keys = []
index_keys = []
index_aliases = []
not_found = []
# check that adata.obs does not contain duplicated columns
# if duplicated columns names are present, they will
# be further duplicated when selecting them.
if not dim_df.columns.is_unique:
dup_cols = dim_df.columns[dim_df.columns.duplicated()].tolist()
raise ValueError(
f"adata.{dim} contains duplicated columns. Please rename or remove "
"these columns first.\n`"
f"Duplicated columns {dup_cols}"
)
if not alt_index.is_unique:
raise ValueError(
f"{alt_repr}.{alt_dim}_names contains duplicated items\n"
f"Please rename these {alt_dim} names first for example using "
f"`adata.{alt_dim}_names_make_unique()`"
)
# use only unique keys, otherwise duplicated keys will
# further duplicate when reordering the keys later in the function
for key in np.unique(keys):
if key in dim_df.columns:
col_keys.append(key)
if key in alt_names.index:
raise KeyError(
f"The key '{key}' is found in both adata.{dim} and {alt_repr}.{alt_search_repr}."
)
elif key in alt_names.index:
val = alt_names[key]
if isinstance(val, pd.Series):
# while var_names must be unique, adata.var[gene_symbols] does not
# It's still ambiguous to refer to a duplicated entry though.
assert alias_index is not None
raise KeyError(
f"Found duplicate entries for '{key}' in {alt_repr}.{alt_search_repr}."
)
index_keys.append(val)
index_aliases.append(key)
else:
not_found.append(key)
if len(not_found) > 0:
raise KeyError(
f"Could not find keys '{not_found}' in columns of `adata.{dim}` or in"
f" {alt_repr}.{alt_search_repr}."
)
return col_keys, index_keys, index_aliases
|
{"/stereo/log_manager.py": ["/stereo/config.py"], "/stereo/plots/plot_utils.py": ["/stereo/plots/_plot_basic/heatmap_plt.py", "/stereo/log_manager.py"], "/stereo/plots/plots.py": ["/stereo/plots/_plot_basic/heatmap_plt.py", "/stereo/log_manager.py"], "/stereo/utils/__init__.py": ["/stereo/utils/correlation.py"], "/stereo/core/stereo_result.py": ["/stereo/log_manager.py"], "/stereo/plots/_plot_basic/heatmap_plt.py": ["/stereo/log_manager.py"]}
|
8,654
|
kensaku-okada/Greenhouse-with-OPV-film-Model
|
refs/heads/master
|
/CropElectricityYeildSimulatorConstant.py
|
# -*- coding: utf-8 -*-
#######################################################
# author :Kensaku Okada [kensakuokada@email.arizona.edu]
# create date : 06 Nov 2016
# last edit date: 19 Apr 2017
#######################################################
##########import package files##########
import numpy as np
import math
import datetime
# #########################################################################
# ########### Reinforcement Learning (RL) constants start##################
# #########################################################################
# # labels of weights for features
# w_0 = "bias(w_0)"
# ##### 1 DLI to plants with the state and action
# w_1 = "DLIEachDayToPlants(w_1)"
# ##### 2 plant weight increase with the state and action
# w_2 = "unitDailyFreshWeightIncrease(w_2)"
# ##### 3 plant weight at the state
# w_3 = "accumulatedUnitDailyFreshWeightIncrease(w_3)"
# ##### 4 averageDLITillTheDay
# w_4 = "averageDLITillHarvestDay(w_4)"
# ##### 5 season effects (winter) representing dates.
# w_5 = "isSpring(w_5)"
# ##### 6 season effects (spring) representing dates.
# w_6 = "isSummer(w_6)"
# ##### 7 season effects (summer) representing dates.
# w_7 = "isAutumn(w_7)"
# ##### 8 season effects (autumn) representing dates.
# w_8 = "isWinter(w_8)"
#
# # starts from middle of Feb
# daysFromJanStartApril = 45
# # starts from May first
# daysFromJanStartSummer = 121
# # starts from middle of September
# daysFromJanStartAutumn = 259
# # starts from middle of Winter
# daysFromJanStartWinter = 320
#
# fileNameQLearningTrainedWeight = "qLearningTraintedWeights"
#
# ifRunTraining = True
# ifSaveCalculatedWeight = True
# ifLoadWeight = True
# ##############################################
# ########### RL constants end##################
# ##############################################
#####################################################
############ filepath and file name start ###########
#####################################################
environmentData = "20130101-20170101" + ".csv"
romaineLettceRetailPriceFileName = "romaineLettuceRetailPrice.csv"
romaineLettceRetailPriceFilePath = ""
averageRetailPriceOfElectricityMonthly = "averageRetailPriceOfElectricityMonthly.csv"
plantGrowthModelValidationData = "plantGrowthModelValidationData.csv"
# source: https://www.eia.gov/dnav/ng/hist/n3010az3m.htm
ArizonaPriceOfNaturalGasDeliveredToResidentialConsumers = "ArizonaPriceOfNaturalGasDeliveredToResidentialConsumers.csv"
###################################################
############ filepath and file name end ###########
###################################################
###############################################################
####################### If statement flag start ###############
###############################################################
# True: use the real data (the imported data whose source is the local weather station "https://midcdmz.nrel.gov/ua_oasis/),
# False: use the
ifUseOnlyRealData = False
# ifUseOnlyRealData = True
#If True, export measured horizontal and estimated data when the simulation day is one day.
# ifExportMeasuredHorizontalAndExtimatedData = True
#If True, export measured horizontal and estimated data only on 15th day each month.
ifGet15thDayData = True
# ifGet15thDayData = False
# if consider the photo inhibition by too strong sunlight, True, if not, False
# IfConsiderPhotoInhibition = True
IfConsiderPhotoInhibition = False
# if consider the price discount by tipburn , True, if not, False
IfConsiderDiscountByTipburn = False
# make this false when running optimization algorithm
exportCSVFiles = True
# exportCSVFiles = False
# if you want to export CVS file and figures, then true
ifExportCSVFile = True
# ifExportCSVFile = False
# ifExportFigures = True
ifExportFigures = False
# if you want to refer to the price of lettuce grown at greenhouse (sales per head), True, if you sell lettuce at open field farming price (sales per kg), False
sellLettuceByGreenhouseRetailPrice = True
# sellLettuceByGreenhouseRetailPrice = False
print("sellLettuceByGreenhouseRetailPrice:{}".format(sellLettuceByGreenhouseRetailPrice))
#############################################################
####################### If statement flag end################
#############################################################
########################################
##########other constant start##########
########################################
# day on each month: days of Jan, Feb, ...., December
dayperMonthArray = np.array([31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31])
dayperMonthLepArray = np.array([31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31])
# keep them int
secondperMinute = 60
minuteperHour = 60
hourperDay = 24
dayperYear = 365
monthsperYear = 12
dayperLeapYear = 366
noonHour = 12
#the temperature at STC (Standard Test Conditions) unit [Celsius]
STCtemperature = 25.0
# current prepared data range: 20130101-20170101", 20150101 to 20160815 was the only correctly observed period. some 2014 data work too.
# do not choose "20140201 to 20160101" specifically. somehow it does not work.
# do not include 1/19/2014 as start date because 1/19/2014 partially misses its hourly data
# do not include after 8/18/2016 because the dates after 8/18/2016 do not correctly log the body temperature.
SimulationStartDate="20150101"
# SimulationStartDate="20150323"
# SimulationStartDate="20151215"
SimulationEndDate = "20151231"
# SimulationEndDate = "20150419"
# one cultivation cycle
# SimulationEndDate = "20151215"
sunnyDaysList = ["20150115", "20150217", "20150316", "20150413", "20150517", "20150615", "20150711", "20150815", "20150918", "20151013", "20151117", "20151215"]
print("SimulationStartDate:{}, SimulationEndDate:{}".format(SimulationStartDate, SimulationEndDate))
# latitude at Tucson == 32.2800408 N
Latitude = math.radians(32.2800408)
# longitude at Tucson 110.9422745 W
Longitude = math.radians(110.9422745)
# lambda (longitude of the site) = 32.2800408 N: latitude,-110.9422745 W : longitude [degree]
# lambda_R ( the longitude of the time zone in which the site is situated) = 33.4484, 112.074 [degree]
# J' (the day angle in the year ) =
# John Page, "The Role of Solar-Radiation Climatology in the Design of Photovoltaic Systems", 2nd edition
# there is a equation calculating LAT.
# p618 (46 in pdf file)
# The passage of days is described mathematically by numbering the days continuously through the year to produce a Julian day number, J: 1
# January, J 5 1; 1 February, J 5 32; 1 March, J 5 57 in a nonleap year and 58 in a leap year; and so on. Each day in the year can be then be
# expressed in an angular form as a day angle, J0, in degrees by multiplying
# J by 360/365.25. The day angle is used in the many of the trigonometric expressions that follow.
# EOT (equation of time) =
#watt To PPFD Conversion coefficient for sunlight (W m^-2) -> (μmol/m^2/s)
# the range of wavelength considered is around from 280 to 2800 (shortwave sunlight), not from 400nm to 700nm (visible sunlight).
wattToPPFDConversionRatio = 2.05
# wattToPPFDConversionRatio = 4.57 <- this ratio is used when the range of wavelength of PAR [W m^-2] is between 400nm and 700nm (visible sunlight)
# [W/m^2]
solarConstant = 1367.0
# ground reflectance of sunlight. source: https://www2.pvlighthouse.com.au/resources/courses/altermatt/The%20Solar%20Spectrum/The%20reflectance%20of%20the%20ground.aspx
groundReflectance = 0.1
# referred from A. Yano et. al., 2009, "Electrical energy generated by photovoltaic modules mounted inside the roof of a north–south oriented greenhouse"
# this number should be carefully definted according to the weather property of the simulation region (very cloudy: 0.0 ~ 1.0: very sunny)
# atmosphericTransmissivity = 0.6
# atmosphericTransmissivity = 0.7
# the reason why this coefficient was changed into this value is described in my paper
atmosphericTransmissivity = 0.643
print("atmosphericTransmissivity:{}".format(atmosphericTransmissivity))
# unit conversion. [cwt] -> [kg] US standard
kgpercwt = 45.3630
# if this is true, then continue to grow plants during the Summer period. the default value is False in the object(instance)
# ifGrowForSummerPeriod = True
ifGrowForSummerPeriod = False
print("ifGrowForSummerPeriod:{}".format(ifGrowForSummerPeriod))
######################################
##########other constant end##########
######################################
#########################################################
##########Specification of the greenhouse start##########
#########################################################
# #########################################################
# # Our real greenhouse specification source:
# # http://www.gpstructures.com/pdfs/Windjammer.pdf
# # We used 6' TALL SIDEWALL HEIGHT 30' width, Free Standing Structures in our project.
# #greenhouse roof type
# greenhouseRoofType = "SimplifiedAFlame"
# #width of the greenhouse (m)
# greenhouseWidth = 9.144 # = 30 [feet]
# #depth of the greenhouse (m)
# greenhouseDepth = 14.6
# #area of the greenhouse (m**2)
# greenhouseFloorArea = greenhouseWidth * greenhouseDepth
# # print("greenhouseFloorArea[m^2]:{}".format(greenhouseFloorArea))
# #width of the greenhouse cultivation area (m)
# greenhouseCultivationFloorWidth = 7.33
# #depth of the greenhouse cultivation area(m)
# greenhouseCultivationFloorDepth = 10.89
# #floor area of greenhouse cultivation area(m**2)
# greenhouseCultivationFloorArea = greenhouseCultivationFloorWidth * greenhouseCultivationFloorDepth
# # greenhouseCultivationFloorArea = greenhouseWidth * greenhouseDepth * 0.9
# # print("greenhouseCultivationFloorArea[m^2]:{}".format(greenhouseCultivationFloorArea))
# # number of roofs. If this is 1, the greenhouse is a single roof greenhouse. If >1, multi-roof greenhouse
# numOfRoofs = 1
# # the type of roof direction
# roofDirectionNotation = "EastWestDirectionRoof"
# #side wall height of greenhouse (m)
# greenhouseHeightSideWall = 1.8288 # = 6[feet]
# #center height of greenhouse (m)
# greenhouseHeightRoofTop = 4.8768 # = 16[feet]
# #width of the rooftop. calculate from the Pythagorean theorem. assumed that the shape of rooftop is straight, not curved.
# greenhouseRoofWidth = math.sqrt((greenhouseWidth/2.0)**2.0 + (greenhouseHeightRoofTop-greenhouseHeightSideWall)**2.0)
# #print ("greenhouseRoofWidth: {}".format(greenhouseRoofWidth))
# #angle of the rooftop (theta θ). [rad]
#
# greenhouseRoofAngle = math.acos((greenhouseWidth/2.0) / greenhouseRoofWidth)
# # print ("greenhouseRoofAngle (rad) : {}".format(greenhouseRoofAngle))
# # the angle of the roof facing north or east [rad]
# roofAngleNorthOrEast = greenhouseRoofAngle
# # the angle of the roof facing south or west [rad]. This should be modified if the roof angle is different from the other side.
# roofAngleWestOrSouth = greenhouseRoofAngle
# #area of the rooftop [m^2]. summing the left and right side of rooftops from the center.
# greenhouseTotalRoofArea = greenhouseRoofWidth * greenhouseDepth * 2.0
# # print ("greenhouseRoofArea[m^2]: {}".format(greenhouseTotalRoofArea))1
# #########################################################
#########################################################
# Virtual greenhouse specification, the multi-roof greenhouse virtually connected 10 of our real greenhouses.
# You can change these numbers according to your greenhouse design and specification
#greenhouse roof type
greenhouseRoofType = "SimplifiedAFlame"
# #width of the greenhouse (m)
# greenhouseWidth = 91.44 #
# #depth of the greenhouse (m)
# greenhouseDepth = 14.6
# the greenhouse floor area was replaced with the following, referring to a common business size greenhouse
# number of roofs (-). If this is 1, the greenhouse is a single roof greenhouse. If >1, multi-roof greenhouse.
numOfRoofs = 10.0
# source: https://www.interempresas.net/FeriaVirtual/Catalogos_y_documentos/1381/Multispan-greenhouse-ULMA-Agricola.pdf,
# source: https://www.alibaba.com/product-detail/Multi-roof-Poly-Film-Tunnel-Greenhouse_60184626287.html
# this should be cahnged depending on the type of greenhouse simulated. (m)
widthPerRoof = 9.6
#total width of the greenhouse (m)
# greenhouseWidth = 91.44
greenhouseWidth = numOfRoofs * widthPerRoof
#depth of the greenhouse (m)
greenhouseDepth = 14.6
#area of the greenhouse (m**2)
greenhouseFloorArea = greenhouseWidth * greenhouseDepth
print("greenhouseFloorArea[m^2]:{}".format(greenhouseFloorArea))
# # the following calculation gives the real cultivation area of our research greenhouse. However, since it has too large vacant space which is unrealistic for business greenhouse, this number was not used.
# #width of the greenhouse cultivation area (m)
# greenhouseCultivationFloorWidth = 73.3
# #depth of the greenhouse cultivation area(m)
# greenhouseCultivationFloorDepth = 10.89
# #floor area of greenhouse cultivation area(m**2)
# greenhouseCultivationFloorArea = greenhouseCultivationFloorWidth * greenhouseCultivationFloorDepth
# Instead, it was assumed the cultivation area is 0.9 time of the total greenhouse floor area
greenhouseCultivationFloorArea = greenhouseFloorArea * 0.9
print("greenhouseCultivationFloorArea[m^2]:{}".format(greenhouseCultivationFloorArea))
# the type of roof direction
roofDirectionNotation = "EastWestDirectionRoof"
# roofDirectionNotation = "NorthSouthDirectionRoof"
#side wall height of greenhouse (m)
greenhouseHeightSideWall = 1.8288 # = 6[feet]
# the total sidewall area
greenhouseSideWallArea = 2.0 * (greenhouseWidth + greenhouseDepth) * greenhouseHeightSideWall
print("greenhouseSideWallArea[m^2]:{}".format(greenhouseSideWallArea))
#center height of greenhouse (m)
greenhouseHeightRoofTop = 4.8768 # = 16[feet]
#width of the rooftop. calculate from the Pythagorean theorem. assumed that the shape of rooftop is straight (not curved), and the top height and roof angels are same at each roof.
greenhouseRoofWidth = math.sqrt((greenhouseWidth/(numOfRoofs*2.0))**2.0 + (greenhouseHeightRoofTop-greenhouseHeightSideWall)**2.0)
print ("greenhouseRoofWidth [m]: {}".format(greenhouseRoofWidth))
# the length of the roof facing east or north
greenhouseRoofWidthEastOrNorth = greenhouseRoofWidth
# the length of the roof facing west or south
greenhouseRoofWidthWestOrSouth = greenhouseRoofWidth
#angle of the rooftop (theta θ). [rad]
greenhouseRoofAngle = math.acos(((greenhouseWidth/(numOfRoofs*2.0)) / greenhouseRoofWidth))
# greenhouseRoofAngle = 0.0
print ("greenhouseRoofAngle (rad) : {}".format(greenhouseRoofAngle))
# the angle of the roof facing north or east [rad]
roofAngleEastOrNorth = greenhouseRoofAngle
# the angle of the roof facing south or west [rad]. This should be modified if the roof angle is different from the other side.
roofAngleWestOrSouth = greenhouseRoofAngle
# area of the rooftop [m^2]. summing the left and right side of rooftops from the center.
greenhouseTotalRoofArea = greenhouseRoofWidth * greenhouseDepth * numOfRoofs * 2.0
print ("greenhouseTotalRoofArea[m^2]: {}".format(greenhouseTotalRoofArea))
greenhouseRoofTotalAreaEastOrNorth = greenhouseRoofWidthEastOrNorth * greenhouseDepth * numOfRoofs
print ("greenhouseRoofTotalAreaEastOrNorth[m^2]: {}".format(greenhouseRoofTotalAreaEastOrNorth))
greenhouseRoofTotalAreaWestOrSouth = greenhouseRoofWidthWestOrSouth * greenhouseDepth * numOfRoofs
print ("greenhouseRoofTotalAreaWestOrSouth[m^2]: {}".format(greenhouseRoofTotalAreaWestOrSouth))
#########################################################
#the proportion of shade made by the greenhouse inner structure, actuator (e.g. sensors and fog cooling systems) and farming equipments (e.g. gutters) (-)
# GreenhouseShadeProportion = 0.1
GreenhouseShadeProportionByInnerStructures = 0.05
# DLI [mol m^-2 day^-1]
DLIForButterHeadLettuceWithNoTipburn = 17.0
# PPFD [umol m^-2 s^-1]
# the PPFD was divided by 2.0 because it was assumed that the time during the day was the half of a day (12 hours)
# OptimumPPFDForButterHeadLettuceWithNoTipburn = DLIForButterHeadLettuceWithNoTipburn * 1000000.0 / float(secondperMinute*minuteperHour*hourperDay)
OptimumPPFDForButterHeadLettuceWithNoTipburn = DLIForButterHeadLettuceWithNoTipburn * 1000000.0 / float(secondperMinute*minuteperHour*hourperDay/2.0)
print("OptimumPPFDForButterHeadLettuceWithNoTipburn (PPFD):{}".format(OptimumPPFDForButterHeadLettuceWithNoTipburn))
# 1.5 is an arbitrary number
# the amount of PPFD to deploy shading curtain
shadingCurtainDeployPPFD = OptimumPPFDForButterHeadLettuceWithNoTipburn * 1.5
print("shadingCurtainDeployPPFD:{}".format(shadingCurtainDeployPPFD))
# The maximum value of m: the number of roofs that incident light penetrating in the model. This value is used at SolarIrradianceMultiroofRoof.py.
# if the angle between the incident light and the horizonta ql axis is too small, the m can be too large, which cause a system error at Util.sigma by iterating too much and make the simulation slow.
# Thus, the upper limit was set.
mMax = numOfRoofs
# defaultIterationLimit = 495
#######################################################
##########Specification of the greenhouse end##########
#######################################################
##################################################################
##########specification of glazing (covering film) start##########
##################################################################
greenhouseGlazingType = "polyethylene (PE) DoubleLayer"
#ratio of visible light (400nm - 750nm) through a glazing material (-)
#source: Nadia Sabeh, "TOMATO GREENHOUSE ROADMAP" https://www.amazon.com/Tomato-Greenhouse-Roadmap-Guide-Production-ebook/dp/B00O4CPO42
# https://www.goodreads.com/book/show/23878832-tomato-greenhouse-roadmap
# singlePEPERTransmittance = 0.875
singlePERTransmittance = 0.85
dobulePERTransmittance = singlePERTransmittance ** 2.0
# reference: https://www.filmetrics.com/refractive-index-database/Polyethylene/PE-Polyethene
PEFilmRefractiveIndex = 1.5
# reference: https://en.wikipedia.org/wiki/Refractive_index
AirRefractiveIndex = 1.000293
# Source of reference https://www.amazon.com/Tomato-Greenhouse-Roadmap-Guide-Production-ebook/dp/B00O4CPO42
singlePolycarbonateTransmittance = 0.91
doublePolycarbonateTransmittance = singlePolycarbonateTransmittance ** 2.0
roofCoveringTransmittance = singlePERTransmittance
sideWallTransmittance = singlePERTransmittance
################################################################
##########specification of glazing (covering film) end##########
################################################################
#####################################################################
##########specification of OPV module (film or panel) start##########
#####################################################################
# [rad]. tilt of OPV module = tilt of the greenhouse roof
# OPVAngle = math.radians(0.0)
OPVAngle = greenhouseRoofAngle
# the coverage ratio of OPV module on the greenhouse roof [-]
# OPVAreaCoverageRatio = 0.20
# OPVAreaCoverageRatio = 0.58
# OPVAreaCoverageRatio = 0.5
OPVAreaCoverageRatio = 0.009090909090909
# print("OPVAreaCoverageRatio:{}".format(OPVAreaCoverageRatio))
# the coverage ratio of OPV module on the greenhouse roof [-]. If you set this value same as OPVAreaCoverageRatio, it assumed that the OPV coverage ratio does not change during the whole period
# OPVAreaCoverageRatioSummerPeriod = 1.0
# OPVAreaCoverageRatioSummerPeriod = 0.5
OPVAreaCoverageRatioSummerPeriod = OPVAreaCoverageRatio
# OPVAreaCoverageRatioSummerPeriod = 0.0
print("OPVAreaCoverageRatioSummerPeriod:{}".format(OPVAreaCoverageRatioSummerPeriod))
#the area of OPV on the roofTop.
OPVArea = OPVAreaCoverageRatio * greenhouseTotalRoofArea
print("OPVArea:{}".format(OPVArea))
# the PV module area facing each angle
OPVAreaFacingEastOrNorthfacingRoof = OPVArea * (greenhouseRoofTotalAreaEastOrNorth/greenhouseTotalRoofArea)
OPVAreaFacingWestOrSouthfacingRoof = OPVArea * (greenhouseRoofTotalAreaWestOrSouth/greenhouseTotalRoofArea)
#the ratio of degradation per day (/day)
# TODO: find a paper describing the general degradation ratio of OPV module
#the specification document of our PV module says that the guaranteed quality period is 1 year.
# reference (degradation ratio of PV module): https://www.nrel.gov/docs/fy12osti/51664.pdf, https://www.solar-partners.jp/pv-eco-informations-41958.html
# It was assumed that inorganic PV module expiration date is 20 years and its yearly degradation rate is 0.8% (from the first reference page 6), which indicates the OPV film degrades faster by 20 times.
PVDegradationRatioPerHour = 20.0 * 0.008 / dayperYear / hourperDay
print("PVDegradationRatioPerHour:{}".format(PVDegradationRatioPerHour))
# the coefficient converting the ideal (given by manufacturers) cell efficiency to the real efficiency under actual conditions
# degradeCoefficientFromIdealtoReal = 0.85
# this website (https://franklinaid.com/2013/02/06/solar-power-for-subs-the-panels/) says "In real-life conditions, the actual values will be somewhat more or less than listed by the manufacturer."
# So it was assumed the manufacture's spec sheet correctly shows the actual power
degradeCoefficientFromIdealtoReal = 1.00
########################################################################################################################
# the following information should be taken from the spec sheet provided by a PV module manufacturer
########################################################################################################################
#unit[/K]. The proportion of a change of voltage which the OPV film generates under STC condition (25°C),
# mentioned in # Table 1-2-1
TempCoeffitientVmpp = -0.0019
#unit[/K]. The proportion of a change of current which the OPV film generates under STC condition (25°C),
# mentioned in Table 1-2-1
TempCoeffitientImpp = 0.0008
#unit[/K]. The proportion of a change of power which the OPV film generates under STC condition (25°C),
# mentioned in Table 1-2-
TempCoeffitientPmpp = 0.0002
#transmission ratio of VISIBLE sunlight through OPV film.
#OPVPARTransmittance = 0.6
OPVPARTransmittance = 0.3
# unit: [A]
shortCircuitCurrent = 0.72
# unit [V]
openCIrcuitVoltage = 24.0
# unit: [A]
currentAtMaximumPowerPoint = 0.48
# unit [V]
voltageAtMaximumPowerPoint = 16.0
# unit: [watt]
maximumPower = currentAtMaximumPowerPoint * voltageAtMaximumPowerPoint
print("maximumPower:{}".format(maximumPower))
# unit: [m^2]. This is the area per sheet, not roll (having 8 sheets concatenated). This area excludes the margin space of the OPV sheet. THe margin space are made from transparent laminated film with connectors.
OPVAreaPerSheet = 0.849 * 0.66
#conversion efficiency from ligtht energy to electricity
#The efficiency of solar panels is based on standard testing conditions (STC),
#under which all solar panel manufacturers must test their modules. STC specifies a temperature of 25°C (77 F),
#solar irradiance of 1000 W/m2 and an air mass 1.5 (AM1.5) spectrums.
#The STC efficiency of a 240-watt module measuring 1.65 square meters is calculated as follows:
#240 watts ÷ (1.65m2 (module area) x 1000 W/m2) = 14.54%.
#source: http://www.solartown.com/learning/solar-panels/solar-panel-efficiency-have-you-checked-your-eta-lately/
# http://www.isu.edu/~rodrrene/Calculating%20the%20Efficiency%20of%20the%20Solar%20Cell.doc
# unit: -
# OPVEfficiencyRatioSTC = maximumPower / OPVAreaPerSheet / 1000.0
# OPVEfficiencyRatioSTC = 0.2
# this value is the cell efficiency of OPV film purchased at Kacira Lab, CEAC at University of Arizona
# OPVEfficiencyRatioSTC = 0.0137
# source: 19. Lucera, L., Machui, F., Schmidt, H. D., Ahmad, T., Kubis, P., St rohm, S., … Brabec, C. J. (2017). Printed semi-transparent large area organic photovoltaic modules with power conversion efficiencies of close to 5 %. Organic Electronics: Physics, Materials, Applications, 45, 41–45. https://doi.org/10.1016/j.orgel.2017.03.013
OPVEfficiencyRatioSTC = 0.043
print("OPVCellEfficiencyRatioSTC:{}".format(OPVEfficiencyRatioSTC))
#what is an air mass??
#エアマスとは太陽光の分光放射分布を表すパラメーター、標準状態の大気(標準気圧1013hPa)に垂直に入射(太陽高度角90°)した
# 太陽直達光が通過する路程の長さをAM1.0として、それに対する比で表わされます。
#source: http://www.solartech.jp/module_char/standard.html
########################################################################################################################
#source: http://energy.gov/sites/prod/files/2014/01/f7/pvmrw13_ps5_3m_nachtigal.pdf (3M Ultra-Barrier Solar Film spec.pdf)
#the price of OPV per area [EUR/m^2]
# [EUR]
originalOPVPriceEUR = 13305.6
OPVPriceEUR = 13305.6
# [m^2]
OPVSizePurchased = 6.0 * 0.925 * 10.0
# [EUR/m^2]
OPVPriceperAreaEUR = OPVPriceEUR / OPVSizePurchased
#as of 11Nov/2016 [USD/EUR]
CurrencyConversionRatioUSDEUR= 1/1.0850
#the price of OPV per area [USD/m^2]
# OPVPricePerAreaUSD = OPVPriceperAreaEUR*CurrencyConversionRatioUSDEUR
# OPVPricePerAreaUSD = 50.0
OPVPricePerAreaUSD = 0.0
# reference of PV panel purchase cost. 200 was a reasonable price in the US.
# https://www.homedepot.com/p/Grape-Solar-265-Watt-Polycrystalline-Solar-Panel-4-Pack-GS-P60-265x4/206365811?cm_mmc=Shopping%7cVF%7cG%7c0%7cG-VF-PLA%7c&gclid=Cj0KCQjw6pLZBRCxARIsALaaY9YIkZf5W4LESs9HA2RgxsYaeXOfzvMuMCUT9iZ7xU65GafQel6FIY8aApLfEALw_wcB&dclid=CLjZj46A2NsCFYQlfwodGQoKsQ
# https://www.nrel.gov/docs/fy17osti/68925.pdf
# OPVPricePerAreaUSD = 200.0
print("OPVPricePerAreaUSD:{}".format(OPVPricePerAreaUSD))
# True == consider the OPV cost, False == ignore the OPV cost
ifConsiderOPVCost = True
# if you set this 730, you assume the purchase cost of is OPV zero because at the simulator class, this number divides the integer number, which gives zero.
# OPVDepreciationPeriodDays = 730.0
OPVDepreciationPeriodDays = 365.0
OPVDepreciationMethod = "StraightLine"
###################################################################
##########specification of OPV module (film or panel) end##########
###################################################################
##########################################################
##########specification of shading curtain start##########
##########################################################
#the transmittance ratio of shading curtain
shadingTransmittanceRatio = 0.45
isShadingCurtainReinforcementLearning = True
#if True, a black net is covered over the roof for shading in summer
# hasShadingCurtain = False
hasShadingCurtain = True
openCurtainString = "openCurtain"
closeCurtainString = "closeCurtain"
# ######## default setting ########
# ShadingCurtainDeployStartMMSpring = 5
# ShadingCurtainDeployStartDDSpring = 31
# ShadingCurtainDeployEndMMSpring = 5
# ShadingCurtainDeployEndDDSpring = 31
# ShadingCurtainDeployStartMMFall =9
# ShadingCurtainDeployStartDDFall =15
# ShadingCurtainDeployEndMMFall =6
# ShadingCurtainDeployEndDDFall =29
# # # optimzed period on greenhouse retail price, starting from minimum values
# ShadingCurtainDeployStartMMSpring = 1
# ShadingCurtainDeployStartDDSpring = 1
# ShadingCurtainDeployEndMMSpring = 1
# ShadingCurtainDeployEndDDSpring = 4
# ShadingCurtainDeployStartMMFall = 1
# ShadingCurtainDeployStartDDFall = 6
# ShadingCurtainDeployEndMMFall = 1
# ShadingCurtainDeployEndDDFall = 16
# # # optimzed period on greenhouse retail price, starting from middle values
# ShadingCurtainDeployStartMMSpring = 6
# ShadingCurtainDeployStartDDSpring = 19
# ShadingCurtainDeployEndMMSpring = 7
# ShadingCurtainDeployEndDDSpring = 5
# ShadingCurtainDeployStartMMFall = 7
# ShadingCurtainDeployStartDDFall = 14
# ShadingCurtainDeployEndMMFall = 7
# ShadingCurtainDeployEndDDFall = 15
# # # optimzed period on greenhouse retail price, starting from max values
# ShadingCurtainDeployStartMMSpring = 12
# ShadingCurtainDeployStartDDSpring = 24
# ShadingCurtainDeployEndMMSpring = 12
# ShadingCurtainDeployEndDDSpring = 28
# ShadingCurtainDeployStartMMFall = 12
# ShadingCurtainDeployStartDDFall = 30
# ShadingCurtainDeployEndMMFall = 12
# ShadingCurtainDeployEndDDFall = 31
# optimzed period on open field farming retail price, starting from max values
# ShadingCurtainDeployStartMMSpring = 8
# ShadingCurtainDeployStartDDSpring = 28
# ShadingCurtainDeployEndMMSpring = 12
# ShadingCurtainDeployEndDDSpring = 2
# ShadingCurtainDeployStartMMFall = 12
# ShadingCurtainDeployStartDDFall = 12
# ShadingCurtainDeployEndMMFall = 12
# ShadingCurtainDeployEndDDFall = 31
# # # initial date s for optimization
ShadingCurtainDeployStartMMSpring = 5
ShadingCurtainDeployStartDDSpring = 17
ShadingCurtainDeployEndMMSpring = 6
ShadingCurtainDeployEndDDSpring = 12
ShadingCurtainDeployStartMMFall = 6
ShadingCurtainDeployStartDDFall = 23
ShadingCurtainDeployEndMMFall = 7
ShadingCurtainDeployEndDDFall = 2
# Summer period. This should happend soon after ending the shading curtain deployment period.
SummerPeriodStartDate = datetime.date(int(SimulationStartDate[0:4]), ShadingCurtainDeployEndMMSpring, ShadingCurtainDeployEndDDSpring) + datetime.timedelta(days=1)
SummerPeriodEndDate = datetime.date(int(SimulationStartDate[0:4]), ShadingCurtainDeployStartMMFall, ShadingCurtainDeployStartDDFall) - datetime.timedelta(days=1)
SummerPeriodStartMM = int(SummerPeriodStartDate.month)
print("SummerPeriodStartMM:{}".format(SummerPeriodStartMM))
SummerPeriodStartDD = int(SummerPeriodStartDate.day)
print("SummerPeriodStartDD:{}".format(SummerPeriodStartDD))
SummerPeriodEndMM = int(SummerPeriodEndDate.month)
print("SummerPeriodEndMM:{}".format(SummerPeriodEndMM))
SummerPeriodEndDD = int(SummerPeriodEndDate.day)
print("SummerPeriodEndDD:{}".format(SummerPeriodEndDD))
# this is gonna be True when you want to deploy shading curtains only from ShadigCuratinDeployStartHH to ShadigCuratinDeployEndHH
IsShadingCurtainDeployOnlyDayTime = True
ShadigCuratinDeployStartHH = 10
ShadigCuratinDeployEndHH = 14
IsDifferentShadingCurtainDeployTimeEachMonth = True
# this is gonna be true when you want to control shading curtain opening and closing every hour
IsHourlyShadingCurtainDeploy = False
########################################################
##########specification of shading curtain end##########
########################################################
#################################################
##########Specification of plants start##########
#################################################
#Cost of plant production. the unit is USD/m^2
# the conversion rate was calculated from from University of California Cooperative Extension (UCEC) UC Small farm program (http://sfp.ucdavis.edu/crops/coststudieshtml/lettuce/LettuceTable1/)
plantProductionCostperSquareMeterPerYear = 1.096405
numberOfRidge = 5.0
#unit: m. plant density can be derived from this.
distanceBetweenPlants = 0.2
# plant density (num of heads per area) [head/m^2]
plantDensity = 1.0/(distanceBetweenPlants**2.0)
print("plantDensity:{}".format(plantDensity))
#number of heads
# numberOFheads = int(greenhouseCultivationFloorDepth/distanceBetweenPlants * numberOfRidge)
numberOFheads = int (plantDensity * greenhouseCultivationFloorArea)
print("numberOFheads:{}".format(numberOFheads))
# number of head per cultivation area [heads/m^2]
numberOFheadsPerArea = float(numberOFheads / greenhouseCultivationFloorArea)
#photoperiod (time of lighting in a day). the unit is hour
# TODO: this should be revised so that the photo period is calculated by the sum of PPFD each day or the change of direct solar radiation or the diff of sunse and sunrise
photoperiod = 14.0
#number of cultivation days (days/harvest)
cultivationDaysperHarvest = 35
# cultivationDaysperHarvest = 30
# the constant of each plant growth model
# Source: https://www.researchgate.net/publication/266453402_TEN_YEARS_OF_HYDROPONIC_LETTUCE_RESEARCH
A_J_Both_Modified_TaylorExpantionWithFluctuatingDLI = "A_J_Both_Modified_TaylorExpantionWithFluctuatingDLI"
# Source: https://www.researchgate.net/publication/4745082_Validation_of_a_dynamic_lettuce_growth_model_for_greenhouse_climate_control
E_J_VanHenten1994 = "E_J_VanHenten1994"
# Source: https://www.researchgate.net/publication/286938495_A_validated_model_to_predict_the_effects_of_environment_on_the_growth_of_lettuce_Lactuca_sativa_L_Implications_for_climate_change
S_Pearson1997 = "S_Pearson1997"
plantGrowthModel = E_J_VanHenten1994
# lettuce base temperature [Celusius]
# Reference: A validated model to predict the effects of environment on the growth of lettuce (Lactuca sativa L.): Implications for climate change
# https://www.tandfonline.com/doi/abs/10.1080/14620316.1997.11515538
lettuceBaseTemperature = 0.0
DryMassToFreshMass = 1.0/0.045
# the weight to harvest [g]
harvestDryWeight = 200.0 / DryMassToFreshMass
# harvestDryWeight = 999.0 / DryMassToFreshMass
# operation cost of plants [USD/m^2/year]
plantcostperSquaremeterperYear = 1.096405
# the DLI upper limitation causing some tipburn
DLIforTipBurn = DLIForButterHeadLettuceWithNoTipburn
# the discount ratio when there are some tipburn observed
tipburnDiscountRatio = 0.2
# make this number 1.0 in the end. change this only for simulation experiment
plantPriceDiscountRatio_justForSimulation = 1.0
# the set point temperature during day time [Celusius]
# reference: A.J. Both, TEN YEARS OF HYDROPONIC LETTUCE RESEARCH: https://www.researchgate.net/publication/266453402_TEN_YEARS_OF_HYDROPONIC_LETTUCE_RESEARCH
setPointTemperatureDayTime = 24.0
# setPointTemperatureDayTime = 16.8
# the set point temperature during night time [Celusius]
# reference: A.J. Both, TEN YEARS OF HYDROPONIC LETTUCE RESEARCH: https://www.researchgate.net/publication/266453402_TEN_YEARS_OF_HYDROPONIC_LETTUCE_RESEARCH
setPointTemperatureNightTime = 19.0
# setPointTemperatureNightTime = 16.8
setPointHumidityDayTime = 0.65
# setPointHumidityDayTime = 0.7
setPointHumidityNightTime = 0.8
# setPointHumidityNightTime = 0.7
# the flags indicating daytime or nighttime at each time step
daytime = "daytime"
nighttime = "nighttime"
# sales price of lettuce grown at greenhouses, which is usually higher than that of open field farming grown lettuce
# source
# 1.99 USD head-1 for "Lettuce, Other, Boston-Greenhouse") cited from USDA (https://www.ams.usda.gov/mnreports/fvwretail.pdf)
# other source: USDA, Agricultural, Marketing, Service, National Retail Report - Specialty Crops page 9 and others: https://www.ams.usda.gov/mnreports/fvwretail.pdf
# unit: USD head-1
romainLettucePriceBasedOnHeadPrice = 1.99
###################################################
##########Specification of the plants end##########
###################################################
###################################################
##########Specification of labor cost start########
###################################################
# source: https://onlinelibrary.wiley.com/doi/abs/10.1111/cjag.12161
# unit: people/10000kg yield
necessaryLaborPer10000kgYield = 0.315
# source:https://www.bls.gov/regions/west/news-release/occupationalemploymentandwages_tucson.htm
# unit:USD/person/hour
hourlyWagePerPerson = 12.79
# unit: hour/day
workingHourPerDay = 8.0
###################################################
##########Specification of labor cost end########
###################################################
###################################################
##########Specification of energy cost start#######
###################################################
# energy efficiency of heating equipment [-]
# source: https://www.alibaba.com/product-detail/Natural-gas-fired-hot-air-heater_60369835987.html?spm=a2700.7724838.2017115.1.527251bcQ2pojZ
# source: https://www.aga.org/natural-gas/in-your-home/heating/
heatingEquipmentEfficiency = 0.9
# unit: USD
heatingEquipmentQurchaseCost = 0.0
# source: http://www.world-nuclear.org/information-library/facts-and-figures/heat-values-of-various-fuels.aspx
# source: http://agnatural.pt/documentos/ver/natural-gas-conversion-guide_cb4f0ccd80ccaf88ca5ec336a38600867db5aaf1.pdf
# unit: MJ m-3
naturalGasSpecificEnergy = {"MJ m-3" :38.7}
naturalGasSpecificEnergy["MJ ft-3"] = naturalGasSpecificEnergy["MJ m-3"] / 35.3147
heatOfWaterEcaporation = {"J kg-1" : 2257}
# source: https://www.researchgate.net/publication/265890843_A_Review_of_Evaporative_Cooling_Technologies?enrichId=rgreq-2c40013798cfb3c564cf35844f4947fb-XXX&enrichSource=Y292ZXJQYWdlOzI2NTg5MDg0MztBUzoxNjUxOTgyMjg4OTM2OTdAMTQxNjM5NzczNTk5Nw%3D%3D&el=1_x_3&_esc=publicationCoverPdf
# COP = coefficient of persormance. COP = Q/W
# Q is the useful heat supplied or removed by the considered system. W is the work required by the considered system.
PadAndFanCOP = 15.0
###################################################
##########Specification of energy cost end#########
###################################################
#########################################################################
###########################Global variable end###########################
#########################################################################
class CropElectricityYeildSimulatorConstant:
"""
a constant class.
"""
###########the constractor##################
def __init__(self):
print ("call CropElectricityYeildSimulatorConstant")
###########the constractor end##################
###########the methods##################
def method(self, val):
print("call CropElectricityYeildSimulatorConstant method")
###########the methods end##################
|
{"/OPVFilm.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/ShadingCurtain.py"], "/CropElectricityYieldProfitMINLP.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelS_Pearson1997.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/PlantGrowthModelS_Pearson1997Constant.py", "/Lettuce.py"], "/GreenhouseEnergyBalanceConstant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/Util.py": ["/CropElectricityYeildSimulatorConstant.py"], "/SolarIrradianceMultiSpanRoof.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/GreenhouseEnergyBalance.py": ["/Lettuce.py", "/CropElectricityYeildSimulatorConstant.py", "/GreenhouseEnergyBalanceConstant.py", "/Util.py"], "/SimulatorMain.py": ["/CropElectricityYeildSimulator1.py", "/Util.py", "/CropElectricityYeildSimulatorConstant.py"], "/CropElectricityYieldProfitRLShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/ShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelValidation.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulator1.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulatorDetail.py": ["/ShadingCurtain.py", "/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/Lettuce.py", "/PlantGrowthModelS_Pearson1997.py", "/SolarIrradianceMultiSpanRoof.py", "/GreenhouseEnergyBalance.py"], "/PlantGrowthModelS_Pearson1997Constant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/SimulatorClass.py": ["/CropElectricityYeildSimulatorConstant.py"], "/Lettuce.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/plantGrowthModelE_J_VanHenten.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py"]}
|
8,655
|
kensaku-okada/Greenhouse-with-OPV-film-Model
|
refs/heads/master
|
/OPVFilm.py
|
# -*- coding: utf-8 -*-
##########import package files##########
from scipy import stats
import sys
import datetime
import calendar
import os as os
import numpy as np
import matplotlib.pyplot as plt
import math
import CropElectricityYeildSimulatorConstant as constant
import Util as util
import ShadingCurtain
#######################################################
# command to show all array data
# np.set_printoptions(threshold=np.inf)
# print ("hourlyHorizontalDirectOuterSolarIrradiance:{}".format(hourlyHorizontalDirectOuterSolarIrradiance))
# np.set_printoptions(threshold=1000)
# np.set_printoptions(threshold=np.inf)
# print ("hourlySolarIncidenceAngle: {}".format(hourlySolarIncidenceAngle))
# np.set_printoptions(threshold=1000)
def getOPVArea(OPVCoverageRatio):
'''
return the OPV area given a certain OPV coverage ratio
:param OPVCoverageRatio:
:return: [m^2]
'''
return OPVCoverageRatio * constant.greenhouseTotalRoofArea
def calcDeclinationAngle (year, month, day):
'''
calculate the declination angle [°]
:param month: list of months.
:param day: list of days
:return: declinationAngle [rad]
'''
# number of days from January first
n = np.zeros(year.shape[0])
declinationAngleperHour = np.zeros(year.shape[0])
# print "year:{}".format(year)
# print "year.shape[0]:{}".format(year.shape[0])
# print "month.shape:{}".format(month.shape)
# print "day:{}".format(day)
for i in range (0, year.shape[0]):
n[i] = (datetime.date(year[i], month[i], day[i]) - datetime.date(year[i], 1, 1)).days + 1
# print "n[{}]:{}".format(i,n[i])
declinationAngleperHour[i] = math.radians(23.45 * math.sin(math.radians(360.0 * (284 + n[i]) / 365)))
# print "i:{}, n[i]:{}".format(i, n[i])
return declinationAngleperHour
def getSolarHourAngleKacira2003(hour):
'''
calculate the solar hour angle [°]
:param hour:
:return:solarHourAngle [degree]
'''
return np.radians(constant.minuteperHour*(hour - constant.noonHour ) / 4.0)
# Be careful! The paper indicates the following equation to get hour angle, but when integrating it with Yano et al. (2009), you need to let it negative in the morning and positive in the afternoon.
# return np.radians(constant.minuteperHour*(constant.noonHour - hour ) / 4.0)
def getSolarHourAngleYano2009(hour):
'''
calculate the solar hour angle [°]
:param hour:
:return:solarHourAngle [degree]
'''
# TODO: adopt the authorized way to calculate the local apparent time LAT. now it is approximated to be 0.4 based on Tucson, Arizona, US referring to Dr Kacira's calculation .
localApparentTime = hour - 0.4
return (math.pi/12.0) * (localApparentTime - constant.noonHour)
# longitude at Tucson 32.2800408,-110.9422745
# lambda (longitude of the site) = 32.2800408 N: latitude,-110.9422745 W : longitude [degree]
# lambda_R ( the longitude of the time zone in which the site is situated) = 33.4484, 112.074 [degree]
# J' (the day angle in the year ) =
# EOT (equation of time) =
def calcSolarAltitudeAngle(hourlyDeclinationAngle, hourlySolarHourAngle):
'''
calculate the solar altitude angle [rad]
constant.Latitude: symbol phi [rad]
:param hourlyDeclinationAngle:symbol delta [rad]
:param hourlySolarHourAngle:symbol omega [rad]
:return: hourlySolarAltitudeAngle [rad]
'''
sinDelta = np.sin(hourlyDeclinationAngle)
cosDelta = np.cos(hourlyDeclinationAngle)
sinOmega = np.sin(hourlySolarHourAngle)
cosOmega = np.cos(hourlySolarHourAngle)
sinPhi = np.sin(constant.Latitude)
cosPhi = np.cos(constant.Latitude)
return np.arcsin(cosPhi*cosDelta*cosOmega + sinPhi*sinDelta)
def calcSolarAzimuthAngle(hourlyDeclinationAngle, hourlySolarAltitudeAngle, hourlySolarHourAngle):
'''
calculate the azimuth angle [rad]
constant.Latitude: symbol phi [rad]
:param hourlyDeclinationAngle:symbol delta [rad]
:param hourlySolarAltitudeAngle:symbol alpha [rad]
:param hourlySolarHourAngle:symbol omega [rad]
:return: hourlyAzimuthAngle [rad]
'''
sinDelta = np.sin(hourlyDeclinationAngle)
cosDelta = np.cos(hourlyDeclinationAngle)
sinAlpha = np.sin(hourlySolarAltitudeAngle)
cosAlpha = np.cos(hourlySolarAltitudeAngle)
sinPhi = np.sin(constant.Latitude)
cosPhi = np.cos(constant.Latitude)
# print ("sinDelta:{}".format(sinDelta))
# print ("sinAlpha:{}".format(sinAlpha))
# print ("cosAlpha:{}".format(cosAlpha))
# print ("sinPhi:{}".format(sinPhi))
# print ("cosPhi:{}".format(cosPhi))
# [rad]
# hourlyAzimuthAngle is multiplied by -1 when hourlySolarHourAngle (omega) < 0
# when using the function of "", "np.arccos((sinAlpha*sinPhi - sinDelta) / (cosAlpha * cosPhi))" value became nan when "(sinAlpha*sinPhi - sinDelta) / (cosAlpha * cosPhi)" is "-1."
# Thus this if statement corrects this error.
a = (sinAlpha*sinPhi - sinDelta) / (cosAlpha * cosPhi)
for i in range (0, a.shape[0]):
if a[i] < -1.0:
a[i] = -1.0
elif a[i] > 1.0:
a[i] = 1.0
# print("a:{}".format(a))
hourlyAzimuthAngle = np.sign(hourlySolarHourAngle) * np.arccos(a)
# print("hourlyAzimuthAngle:{}".format(hourlyAzimuthAngle))
return hourlyAzimuthAngle
def calcSolarIncidenceAngleKacira2003(hourlyDeclinationAngle, hourlySolarHourAngle ,hourlysurfaceAzimuthAngle):
'''
calculate solar incidence angle
constant.OPVAngle: symbol capital s (S) [rad]
constant.Latitude: symbol phi [rad]
:param hourlyDeclinationAngle: symbol delta [rad]
:param hourlySolarHourAngle: symbol omega [rad]
:param hourlysurfaceAzimuthAngle: symbol gamma [rad]
:return: SolarIncidenceAngle [rad]
'''
sinDelta = np.sin(hourlyDeclinationAngle)
cosDelta = np.cos(hourlyDeclinationAngle)
sinPhi = np.sin(constant.Latitude)
cosPhi = np.cos(constant.Latitude)
sinOmega = np.sin(hourlySolarHourAngle)
cosOmega = np.cos(hourlySolarHourAngle)
sinGamma = np.sin(hourlysurfaceAzimuthAngle)
cosGamma = np.cos(hourlysurfaceAzimuthAngle)
sinS = np.sin(constant.OPVAngle)
cosS = np.cos(constant.OPVAngle)
# TODO check which is correct
# From Kacira et al. (2003)
# solarIncidenceAngle = sinDelta*sinPhi*cosS - sinDelta*cosPhi*sinS*cosGamma + cosDelta*cosPhi*cosS*cosOmega \
# + cosDelta*sinPhi*sinS*cosGamma*cosOmega + cosDelta*sinS*sinGamma*sinOmega
# from ITACA: http://www.itacanet.org/the-sun-as-a-source-of-energy/part-3-calculating-solar-angles/
solarIncidenceAngle = sinDelta*sinPhi*cosS + sinDelta*cosPhi*sinS*cosGamma + cosDelta*cosPhi*cosS*cosOmega \
- cosDelta*sinPhi*sinS*cosGamma*cosOmega - cosDelta*sinS*sinGamma*sinOmega
# for i in range (0, sinDelta.shape[0]):
# if -1 > solarIncidenceAngle[i] or 1 < solarIncidenceAngle[i]:
# solarIncidenceAngle[i] = (solarIncidenceAngle[i] + solarIncidenceAngle[i])/2.0
return np.arccos(solarIncidenceAngle)
def calcSolarIncidenceAngleYano2009(hourlySolarAltitudeAngle, hourlySolarAzimuthAngle, hourlyModuleAzimuthAngle, OPVAngle = constant.OPVAngle):
'''
calculate solar incidence angle. the equation wat taken from
constant.OPVAngle: symbol capital s (S) [rad]
constant.Latitude: symbol phi [rad]
:param hourlyDeclinationAngle: symbol delta [rad]
:param hourlySolarHourAngle: symbol omega [rad]
:param hourlySurfaceAzimuthAngle: symbol gamma [rad]
:param hourlySolarAltitudeAngle: symbol alpha [rad]
:param hourlySolarAzimuthAngle: symbol phi_S [rad]
:param hourlyModuleAzimuthAngle: symbol phi_P [rad]
:return: SolarIncidenceAngle [rad]
'''
# sinPhi = np.sin(constant.Latitude)
# cosPhi = np.cos(constant.Latitude)
sinS = np.sin(OPVAngle)
cosS = np.cos(OPVAngle)
sinAlpha = np.sin(hourlySolarAltitudeAngle)
cosAlpha = np.cos(hourlySolarAltitudeAngle)
sinPhiS = np.sin(hourlySolarAzimuthAngle)
cosPhiS = np.cos(hourlySolarAzimuthAngle)
sinPhiP = np.sin(hourlyModuleAzimuthAngle)
cosPhiP = np.cos(hourlyModuleAzimuthAngle)
solarIncidenceAngle = np.arccos(sinAlpha*cosS + cosAlpha*sinS*np.cos(hourlySolarAzimuthAngle - hourlyModuleAzimuthAngle))
# print("solarIncidenceAngle:{}".format(solarIncidenceAngle))
return solarIncidenceAngle
def getMaxDirectBeamSolarRadiationKacira2003(hourlySolarAltitudeAngle, hourlyHorizontalDirectOuterSolarIrradiance, hourlyZenithAngle):
'''
calculate the max direct beam solar radiation
:param hourlySolarAltitudeAngle: [rad]
:param hourlyHorizontalDirectOuterSolarIrradiance: [W m^-2]
:param hourlyZenithAngle: [rad]
:return: maxDirectBeamSolarRadiation [W m^-2]
'''
# if the altitude angle is minus, it means it is night. Thus, the maxDirectBeamSolarRadiation becomes zero.
maxDirectBeamSolarRadiation = np.zeros(hourlySolarAltitudeAngle.shape[0])
# if the altitude angle is minus, it means it is night. Thus, the directBeamSolarRadiationNormalToTiltedOPV becomes zero.
for i in range (0, hourlySolarAltitudeAngle.shape[0]):
if hourlySolarAltitudeAngle[i] < 0:
maxDirectBeamSolarRadiation[i] = 0
else:
maxDirectBeamSolarRadiation[i] = hourlyHorizontalDirectOuterSolarIrradiance[i] / np.cos(hourlyZenithAngle[i])
# print "np.degrees(hourlyZenithAngle):{}".format(np.degrees(hourlyZenithAngle))
# print "np.cos(hourlyZenithAngle):{}".format(np.cos(hourlyZenithAngle))
# print"hourlyHorizontalDirectOuterSolarIrradiance:{}".format(hourlyHorizontalDirectOuterSolarIrradiance)
# print "maxDirectBeamSolarRadiation:{}".format(maxDirectBeamSolarRadiation)
return maxDirectBeamSolarRadiation
def getDirectHorizontalSolarRadiation(hourlySolarAltitudeAngle, hourlyHorizontalSolarIncidenceAngle):
'''
calculate the direct solar radiation to horizontal surface. referred to Yano 2009 equation (6)
:param hourlySolarAltitudeAngle: [rad]
:param hourlyHorizontalSolarIncidenceAngle: [rad]
:return: maxDirectBeamSolarRadiation [W m^-2]
'''
directHorizontalSolarRadiation = constant.solarConstant * (constant.atmosphericTransmissivity**(1.0/np.sin(hourlySolarAltitudeAngle))) * \
np.sin(hourlySolarAltitudeAngle)
# TODO maybe the condition of if statement is not incidence angle but azimuth angle(alpha)
# if the incidence angle is >|90| the radiation is 0
for i in range (0, hourlyHorizontalSolarIncidenceAngle.shape[0]):
# if abs(hourlyHorizontalSolarIncidenceAngle[i]) >= math.pi / 2.0:
if hourlySolarAltitudeAngle[i] < 0.0:
directHorizontalSolarRadiation[i] = 0.0
return directHorizontalSolarRadiation
def getDiffuseHorizontalSolarRadiation(hourlySolarAltitudeAngle, hourlyHorizontalSolarIncidenceAngle):
'''
calculate the diffuse solar radiation to horizontal surface. referred to Yano 2009 equation (7)
:param hourlySolarAltitudeAngle: [rad]
:return: maxDirectBeamSolarRadiation [W m^-2]
'''
diffuseHorizontalSolarRadiation = constant.solarConstant * np.sin(hourlySolarAltitudeAngle) * (1 - constant.atmosphericTransmissivity**(1.0/np.sin(hourlySolarAltitudeAngle))) \
/ (2.0 * (1 - 1.4*np.log(constant.atmosphericTransmissivity)))
# if the incidence angle is >|90| the radiation is 0
for i in range (0, hourlyHorizontalSolarIncidenceAngle.shape[0]):
# if abs(hourlyHorizontalSolarIncidenceAngle[i]) >= (math.pi) / 2.0:
if hourlySolarAltitudeAngle[i] < 0.0:
diffuseHorizontalSolarRadiation[i] = 0.0
return diffuseHorizontalSolarRadiation
# def getDirectTitledSolarRadiation(simulatorClass, hourlySolarAltitudeAngle, hourlySolarIncidenceAngle, hourlyHorizontalDirectOuterSolarIrradiance = \
# np.zeros(util.calcSimulationDaysInt() * constant.hourperDay)):
def getDirectTitledSolarRadiation(simulatorClass, hourlySolarAltitudeAngle, hourlySolarIncidenceAngle, hourlyHorizontalDirectOuterSolarIrradiance):
'''
calculate the direct solar radiation to tilted surface. referred to Yano 2009 for both cases
'''
# if we estimate the solar radiation (calculate the solar radiation without real data), get into this statement
if simulatorClass.getEstimateSolarRadiationMode() == True:
# if (hourlyHorizontalDirectOuterSolarIrradiance == 0.0).all():
# print("at OPVFilm.getDirectTitledSolarRadiation, hourlyHorizontalDirectOuterSolarIrradiance does not have data")
# if there is no data about solar radiation, assume the solar radiation from the following equation, which is cited from A. Yano, "electrical energy generated by photovoltaic modules mounted inside the roof of a north-south oriented greenhouse", 2009
directTiltedSolarRadiation = constant.solarConstant * (constant.atmosphericTransmissivity ** (1.0 / np.sin(hourlySolarAltitudeAngle))) * \
np.cos(hourlySolarIncidenceAngle)
# direct tilted solar radiation is defined as 0 when the incidence angle is >90 or <-90 (|incidence angle| > 90 degree)
for i in range (0, hourlySolarIncidenceAngle.shape[0]):
# if abs(hourlySolarIncidenceAngle[i]) >= (math.pi) / 2.0:
if hourlySolarAltitudeAngle[i] < 0.0 or directTiltedSolarRadiation[i] < 0.0:
directTiltedSolarRadiation[i] = 0.0
# np.set_printoptions(threshold=np.inf)
# print ("directTiltedSolarRadiation: {}".format(directTiltedSolarRadiation))
# np.set_printoptions(threshold=1000)
return directTiltedSolarRadiation
# if we calculate the solar radiation with real data, get into this statement
else:
directTiltedSolarRadiation = constant.solarConstant * (constant.atmosphericTransmissivity ** (1.0 / np.sin(hourlySolarAltitudeAngle))) * \
np.cos(hourlySolarIncidenceAngle)
# direct tilted solar radiation is defined as 0 when the incidence angle is >90 or <-90 (|incidence angle| > 90 degree)
for i in range (0, hourlySolarIncidenceAngle.shape[0]):
# if abs(hourlySolarIncidenceAngle[i]) >= (math.pi) / 2.0:
if hourlySolarAltitudeAngle[i] < 0.0 or directTiltedSolarRadiation[i] < 0.0:
directTiltedSolarRadiation[i] = 0.0
# print ("directTiltedSolarRadiation:{}".format(directTiltedSolarRadiation))
# TODO: delete the following process if not necessary
############ outliers data correction start ############
# when this value is 2, then average just 1 hour before and after the ith hour
averageHourRange = 2
numElBefore = averageHourRange -1
numElAfter = averageHourRange
# [W m^-2]
outlierLimitation = 1100.0
print ("max light intensity:{}".format(np.max(directTiltedSolarRadiation)))
print ("mean light intensity:{}".format(np.mean(directTiltedSolarRadiation)))
#First correction. If the solar radiations binding the outlier are zero, then set the outlier zero.
for i in range (1, hourlySolarIncidenceAngle.shape[0]-1):
# if directTiltedSolarRadiation[i] > outlierLimitation and (directTiltedSolarRadiation[i -1] == 0.) and (directTiltedSolarRadiation[i + 1] == 0.):
if (directTiltedSolarRadiation[i -1] == 0.) and (directTiltedSolarRadiation[i + 1] == 0.):
directTiltedSolarRadiation[i] = 0.0
# Second correction. If the solar radiations binding the outlier are not zero, then set the outlier the average of solar radiations 1 hour after and before the outlier hour.
# print ("outlier indices before correction:{}".format([i for i, x in enumerate(directTiltedSolarRadiation) if x > 1.2 * (np.sum(directTiltedSolarRadiation[i-numElBefore :i+numElAfter]) - directTiltedSolarRadiation[i]) / (numElBefore+numElAfter -1.0)]))
print ("outlier indices before correction:{}".format([i for i, x in enumerate(directTiltedSolarRadiation) if x > outlierLimitation]))
# this correction was made because some outliers occured by the calculation of directTiltedSolarRadiation (= hourlyHorizontalDirectOuterSolarIrradiance * np.cos(hourlySolarIncidenceAngle) / np.sin(hourlySolarAltitudeAngle))
# "np.cos(hourlySolarIncidenceAngle) / np.sin(hourlySolarAltitudeAngle)" can be very larger number like 2000
# if a light intensity [W /m^2] at a certain hour is more than the maximum light intensity by 20%, the value is replaced by the average light intensity before/after 3 hours
# directTiltedSolarRadiationExcludingOutliers = np.array([(np.sum(directTiltedSolarRadiation[i-numElBefore :i+numElAfter]) - directTiltedSolarRadiation[i]) / float(numElBefore+numElAfter -1.0) if\
# x > 1.5 * (np.sum(directTiltedSolarRadiation[i-numElBefore :i+numElAfter]) - directTiltedSolarRadiation[i]) / (numElBefore+numElAfter -1.0) \
# else x for i, x in enumerate(directTiltedSolarRadiation) ])
directTiltedSolarRadiationExcludingOutliers = np.array([(np.sum(directTiltedSolarRadiation[i-numElBefore :i+numElAfter]) - directTiltedSolarRadiation[i]) / float(numElBefore+numElAfter -1.0) if\
x > outlierLimitation else x for i, x in enumerate(directTiltedSolarRadiation) ])
print ("outlier indices after correction:{}".format([i for i, x in enumerate(directTiltedSolarRadiationExcludingOutliers) if x > outlierLimitation]))
############ outliers data correction end ############
# print ("outlier indices after correction:{}".format([i for i, x in enumerate(directTiltedSolarRadiationExcludingOutliers) if x > 1.2 * (np.sum(directTiltedSolarRadiationExcludingOutliers[i-numElBefore :i+numElAfter]) - directTiltedSolarRadiationExcludingOutliers[i]) / (numElBefore+numElAfter -1.0)]))
# print "hourlySolarIncidenceAngle:{}".format(hourlySolarIncidenceAngle)
# print "directTiltedSolarRadiationExcludingOutliers:{}".format(directTiltedSolarRadiationExcludingOutliers)
# return directTiltedSolarRadiation
return directTiltedSolarRadiationExcludingOutliers
def getDiffuseTitledSolarRadiation(simulatorClass, hourlySolarAltitudeAngle, estimatedDiffuseHorizontalSolarRadiation, hourlyHorizontalDiffuseOuterSolarIrradiance = \
np.zeros(util.calcSimulationDaysInt() * constant.hourperDay)):
'''
calculate the diffuse solar radiation to tilted surface. referred to Yano 2009
:param hourlySolarAltitudeAngle: [rad]
:param diffuseHorizontalSolarRadiation: [W m^-2]
:return: maxDirectBeamSolarRadiation [W m^-2]
'''
# if (hourlyHorizontalDiffuseOuterSolarIrradiance == 0.0).all():
if simulatorClass.getEstimateSolarRadiationMode() == True:
print("at OPVFilm.getDiffuseTitledSolarRadiation, hourlyHorizontalDiffuseOuterSolarIrradiance does not have data")
# if there is no data about solar radiation, assume the solar radiation from the following equation, which is cited from A. Yano, "electrical energy generated by photovoltaic modules mounted inside the roof of a north-south oriented greenhouse", 2009
diffuseTiltedSolarRadiation = estimatedDiffuseHorizontalSolarRadiation * (1 + np.cos(constant.OPVAngle)) / 2.0
else:
print("at OPVFilm.getDiffuseTitledSolarRadiation, hourlyHorizontalDiffuseOuterSolarIrradiance has data")
diffuseTiltedSolarRadiation = hourlyHorizontalDiffuseOuterSolarIrradiance * (1 + np.cos(constant.OPVAngle)) / 2.0
# diffuse tilted solar radiation is defined as 0 when the elevation/altitude angle is <= 0
for i in range (0, hourlySolarAltitudeAngle.shape[0]):
if hourlySolarAltitudeAngle[i] < 0.0:
diffuseTiltedSolarRadiation[i] = 0.0
return diffuseTiltedSolarRadiation
def getAlbedoTitledSolarRadiation(simulatorClass, hourlySolarAltitudeAngle, estimatedTotalHorizontalSolarRadiation, hourlyHorizontalTotalOuterSolarIrradiance = \
np.zeros(util.calcSimulationDaysInt() * constant.hourperDay)):
'''
calculate the albedo (reflection) solar radiation to tilted surface. referred to Yano 2009
:param diffuseHorizontalSolarRadiation: [W m^-2]
:param hourlySolarAltitudeAngle: [rad]
:return: totalHorizontalSolarRadiation [W m^-2]
'''
# if (hourlyHorizontalTotalOuterSolarIrradiance == 0.0).all():
if simulatorClass.getEstimateSolarRadiationMode() == True:
print("at OPVFilm.getAlbedoTitledSolarRadiation, getAlbedoTitledSolarRadiation does not have data")
# if there is no data about solar radiation, assume the solar radiation from the following equation, which is cited from A. Yano, "electrical energy generated by photovoltaic modules mounted inside the roof of a north-south oriented greenhouse", 2009
albedoTiltedSolarRadiation = constant.groundReflectance * estimatedTotalHorizontalSolarRadiation * (1 - np.cos(constant.OPVAngle)) / 2.0
else:
print("at OPVFilm.getAlbedoTitledSolarRadiation, getAlbedoTitledSolarRadiation has data")
albedoTiltedSolarRadiation = constant.groundReflectance * hourlyHorizontalTotalOuterSolarIrradiance * (1 - np.cos(constant.OPVAngle)) / 2.0
# diffuse tilted solar radiation is defined as 0 when the elevation/altitude angle is <= 0
for i in range (0, hourlySolarAltitudeAngle.shape[0]):
# if abs(hourlySolarAltitudeAngle[i]) <= 0.0:
if hourlySolarAltitudeAngle[i] < 0.0:
albedoTiltedSolarRadiation[i] = 0.0
return albedoTiltedSolarRadiation
def calcDirectBeamSolarRadiationNormalToTiltedOPVKacira2003(hourlySolarAltitudeAngle,maxDirectBeamSolarRadiation, hourlySolarIncidenceAngle):
'''
calculate the max direct beam solar radiation perpendicular to the tilted OPV
:param hourlySolarAltitudeAngle: [rad]
:param maxDirectBeamSolarRadiation: [W m^-2]
:param hourlySolarIncidenceAngle: [rad]
:return: directBeamSolarRadiationNormalToTiltedOPV [W m^-2]
'''
directBeamSolarRadiationNormalToTiltedOPV = np.zeros(hourlySolarAltitudeAngle.shape[0])
# print "directBeamSolarRadiationNormalToTiltedOPV:{}".format(directBeamSolarRadiationNormalToTiltedOPV)
# if the altitude angle is minus, it means it is night. Thus, the directBeamSolarRadiationNormalToTiltedOPV becomes zero.
for i in range (0, hourlySolarAltitudeAngle.shape[0]):
if hourlySolarAltitudeAngle[i] < 0.0:
directBeamSolarRadiationNormalToTiltedOPV[i] = 0.0
else:
directBeamSolarRadiationNormalToTiltedOPV[i] = maxDirectBeamSolarRadiation[i] * np.cos(hourlySolarIncidenceAngle[i])
# print"maxDirectBeamSolarRadiation:{}".format(maxDirectBeamSolarRadiation)
# print "np.degrees(hourlySolarIncidenceAngle):{}".format(np.degrees(hourlySolarIncidenceAngle))
return directBeamSolarRadiationNormalToTiltedOPV
def calcOPVElectricEnergyperArea(simulatorClass, hourlyOPVTemperature, solarRadiationToOPV):
'''
calculate the electric energy per OPV area during the defined days [J/day/m^2]
:param hourlyOPVTemperature:
:param Popvin:
:return:
'''
# print("at OPVfilm.py, hourlyOPVTemperature.shape:{}".format(hourlyOPVTemperature.shape))
dailyJopvout = np.zeros(util.calcSimulationDaysInt())
# make the list of OPV coverage ratio at each hour changing during summer
# OPVAreaCoverageRatioChangingInSummer = getDifferentOPVCoverageRatioInSummerPeriod(constant.OPVAreaCoverageRatio, simulatorClass)
# the PV module degradation ratio by time
PVDegradationRatio = np.array([1.0 - constant.PVDegradationRatioPerHour * i for i in range (0, hourlyOPVTemperature.shape[0])])
for day in range (0, util.calcSimulationDaysInt()):
# print "day:{}, Popvin[day*constant.hourperDay : (day+1)*constant.hourperDay]:{}".format(day, Popvin[day*constant.hourperDay : (day+1)*constant.hourperDay])
# unit: [W/m^2] -> [J/m^2] per day
dailyJopvout[day] = calcOPVElectricEnergyperAreaperDay(\
hourlyOPVTemperature[day*constant.hourperDay : (day+1)*constant.hourperDay], \
solarRadiationToOPV[day*constant.hourperDay : (day+1)*constant.hourperDay], PVDegradationRatio[day*constant.hourperDay : (day+1)*constant.hourperDay])
return dailyJopvout
def calcOPVElectricEnergyperAreaperDay(hourlyOPVTemperature, Popvin, PVDegradationRatio):
'''
calculate the electric energy per OPV area only for a day [J/day/m^2]
[the electric energy per OPV area per day]
W_opvout=0.033∫_(t_sunrise)^(t_sunset) (1+C_Voctemp * (T_opv - 25[°C]))(1+ C_Isctemp * (T_opv - 25[°C])) * P_opvin
param: Popvin: Hourly Outer Light Intensity [Watt/m^2] = [J/second/m^2]
param: HourlyOuterTemperature: Hourly Outer Temperature [Celsius/hour]
return: Wopvout, scalar: OPV Electric Energy production per Area per day [J/day/m^2].
'''
#unit [W/m^2]
JopvoutAday = 0
##change the unit from second to hour [J/second/m^2] -> [J/hour/m^2]
Popvin = Popvin * 60.0 * 60.0
#print"int(constant.hourperDay):{}".format(int(constant.hourperDay))
#calculate the electric energy per OPV area (watt/m^2)
for hour in range (0, int(constant.hourperDay)):
# Jopvout += constant.OPVEfficiencyRatioSTC * constant.degradeCoefficientFromIdealtoReal * \
# (1.0 + constant.TempCoeffitientVmpp * (hourlyOPVTemperature[hour] - constant.STCtemperature)) * \
# (1.0 + constant.TempCoeffitientImpp * (hourlyOPVTemperature[hour] - constant.STCtemperature)) * \
# Popvin [hour]
JopvoutAday += constant.OPVEfficiencyRatioSTC * constant.degradeCoefficientFromIdealtoReal * PVDegradationRatio[hour] * \
(1.0 + constant.TempCoeffitientPmpp * (hourlyOPVTemperature[hour] - constant.STCtemperature)) * Popvin[hour]
#print "Jopvout:{} (J/m^2)".format(Wopvout)
return JopvoutAday
def getMonthlyElectricityProductionFromDailyData (dailyElectricityPerArea, yearOfeachDay, monthOfeachDay):
'''
summing the daily electricity produce to monthly produce
'''
# print "yearOfeachDay:{}".format(yearOfeachDay)
# print "monthOfeachDay:{}".format(monthOfeachDay)
numOfMonths = util.getSimulationMonthsInt()
# print "numOfMonths:{}".format(numOfMonths)
monthlyElectricityPerArea = np.zeros(numOfMonths)
month = 0
# insert the initial value
monthlyElectricityPerArea[month] += dailyElectricityPerArea[0]
for day in range (1, util.calcSimulationDaysInt()):
if monthOfeachDay[day-1] != monthOfeachDay[day]:
month += 1
monthlyElectricityPerArea[month] += dailyElectricityPerArea[day]
return monthlyElectricityPerArea
def getMonthlyElectricitySalesperArea(monthlyKWhopvoutperArea, monthlyResidentialElectricityPrice):
'''
:param monthlyKWhopvoutperArea:
:param monthlyResidentialElectricityPrice:
:return: [USD/month/m^2]
'''
# devided by 100 to convert [USCent] into [USD]
return monthlyKWhopvoutperArea * (monthlyResidentialElectricityPrice / 100.0)
def calcRevenueOfElectricityProductionperMonth(WopvoutperHarvestperMonth, monthlyAverageElectricityPrice):
'''
calculate the electric energy wholesale price per month.
param: WopvoutperHarvestperMonth: electric energy produced per month with given area [J/month]
param: monthlyTucsonAverageWholesalelPriceOfElectricity: wholesale price of electricity in Tucson [USD/Mega Watt hour (MWh) for each month]
return: revenueOfElectricityProductionperMonth, scalar: the wholesale price revenue of electricity per month (USD/month).
'''
#unit conversion [J/month = Watt*sec/month -> MWh/month]
#WopvoutperHarvestMWhperMonth = WopvoutperHarvestperMonth * 3600.0 / (10.0**6)
WopvoutperHarvestMWhperMonth = WopvoutperHarvestperMonth / (10.0**6) / 3600.0
#print "WopvoutperHarvestMWhperMonth:{}".format(WopvoutperHarvestMWhperMonth)
#print "monthlyTucsonAverageWholesalelPriceOfElectricity:{}".format(monthlyTucsonAverageWholesalelPriceOfElectricity)
#unit: USD/month
revenueOfElectricityProductionperMonth = WopvoutperHarvestMWhperMonth * monthlyAverageElectricityPrice
#print "revenueOfElectricityProductionperMonth(USD/month):{}".format(revenueOfElectricityProductionperMonth)
return revenueOfElectricityProductionperMonth
def calcCostofElectricityProduction(OPVArea):
'''
calculate the cost to install OPV film
param: OPVArea: area of OPV film (m^2)
return: cost for the OPV film (USD)
'''
return OPVArea * constant.OPVPricePerAreaUSD
def getDirectSolarIrradianceBeforeShadingCurtain(simulatorClass):
# get the direct solar irradiance after penetrating multi span roof [W/m^2]
hourlyDirectSolarRadiationAfterMultiSpanRoof = simulatorClass.getHourlyDirectSolarRadiationAfterMultiSpanRoof()
# OPVAreaCoverageRatio = simulatorClass.getOPVAreaCoverageRatio()
OPVAreaCoverageRatio = constant.OPVAreaCoverageRatio
# ShadingCurtainDeployPPFD = simulatorClass.getShadingCurtainDeployPPFD()
OPVPARTransmittance = constant.OPVPARTransmittance
# make the list of OPV coverage ratio at each hour changing during summer
OPVAreaCoverageRatioChangingInSummer = getDifferentOPVCoverageRatioInSummerPeriod(OPVAreaCoverageRatio, simulatorClass)
# print("OPVAreaCoverageRatioChangingInSummer:{}".format(OPVAreaCoverageRatioChangingInSummer))
# consider the transmission ratio of OPV film
hourlyDirectSolarRadiationAfterOPVAndRoof = hourlyDirectSolarRadiationAfterMultiSpanRoof * (1 - OPVAreaCoverageRatioChangingInSummer) \
+ hourlyDirectSolarRadiationAfterMultiSpanRoof * OPVAreaCoverageRatioChangingInSummer * OPVPARTransmittance
# print "OPVAreaCoverageRatio:{}, HourlyInnerLightIntensityPPFDThroughOPV:{}".format(OPVAreaCoverageRatio, HourlyInnerLightIntensityPPFDThroughOPV)
# consider the light reduction by greenhouse inner structures and equipments like pipes, poles and gutters
hourlyDirectSolarRadiationAfterInnerStructure = (1 - constant.GreenhouseShadeProportionByInnerStructures) * hourlyDirectSolarRadiationAfterOPVAndRoof
# print "hourlyInnerLightIntensityPPFDThroughInnerStructure:{}".format(hourlyInnerLightIntensityPPFDThroughInnerStructure)
return hourlyDirectSolarRadiationAfterInnerStructure
def getDirectSolarIrradianceToPlants(simulatorClass, hourlyDirectSolarRadiationAfterInnerStructure):
hasShadingCurtain = simulatorClass.getIfHasShadingCurtain()
# take date and time
year = simulatorClass.getYear()
month = simulatorClass.getMonth()
day = simulatorClass.getDay()
hour = simulatorClass.getHour()
# array storing the light intensity after penetrating the shading curtain
hourlyDirectSolarRadiationAfterShadingCurtain= np.zeros(hour.shape[0])
# consider the shading curtain
if hasShadingCurtain == True:
# if the date is between the following time and date, discount the irradiance by the shading curtain transmittance.
# if we assume the shading curtain is deployed all time for the given period,
if constant.IsShadingCurtainDeployOnlyDayTime == False:
for i in range(0, hour.shape[0]):
if (datetime.date(year[i], month[i], day[i]) >= datetime.date(year[i], constant.ShadingCurtainDeployStartMMSpring, constant.ShadingCurtainDeployStartDDSpring ) and \
datetime.date(year[i], month[i], day[i]) <= datetime.date(year[i], constant.ShadingCurtainDeployEndMMSpring, constant.ShadingCurtainDeployEndDDSpring)) or\
(datetime.date(year[i], month[i], day[i]) >= datetime.date(year[i], constant.ShadingCurtainDeployStartMMFall, constant.ShadingCurtainDeployStartDDFall ) and \
datetime.date(year[i], month[i], day[i]) <= datetime.date(year[i], constant.ShadingCurtainDeployEndMMFall, constant.ShadingCurtainDeployEndDDFall)):
# deploy the shading curtain
hourlyDirectSolarRadiationAfterShadingCurtain[i] = hourlyDirectSolarRadiationAfterInnerStructure[i] * constant.shadingTransmittanceRatio
else:
# not deploy the curtain
hourlyDirectSolarRadiationAfterShadingCurtain[i] = hourlyDirectSolarRadiationAfterInnerStructure[i]
# if we assume the shading curtain is deployed only for a fixed hot time defined at the constant class in a day, use this
elif constant.IsShadingCurtainDeployOnlyDayTime == True and constant.IsDifferentShadingCurtainDeployTimeEachMonth == False:
for i in range(0, hour.shape[0]):
if (datetime.date(year[i], month[i], day[i]) >= datetime.date(year[i], constant.ShadingCurtainDeployStartMMSpring, constant.ShadingCurtainDeployStartDDSpring ) and \
datetime.date(year[i], month[i], day[i]) <= datetime.date(year[i], constant.ShadingCurtainDeployEndMMSpring, constant.ShadingCurtainDeployEndDDSpring) and \
hour[i] >= constant.ShadigCuratinDeployStartHH and hour[i] <= constant.ShadigCuratinDeployEndHH) or\
(datetime.date(year[i], month[i], day[i]) >= datetime.date(year[i], constant.ShadingCurtainDeployStartMMFall, constant.ShadingCurtainDeployStartDDFall ) and \
datetime.date(year[i], month[i], day[i]) <= datetime.date(year[i], constant.ShadingCurtainDeployEndMMFall, constant.ShadingCurtainDeployEndDDFall) and \
hour[i] >= constant.ShadigCuratinDeployStartHH and hour[i] <= constant.ShadigCuratinDeployEndHH):
# deploy the shading curtain
hourlyDirectSolarRadiationAfterShadingCurtain[i] = hourlyDirectSolarRadiationAfterInnerStructure[i] * constant.shadingTransmittanceRatio
else:
# not deploy the curtain
hourlyDirectSolarRadiationAfterShadingCurtain[i] = hourlyDirectSolarRadiationAfterInnerStructure[i]
# if we assume the shading curtain is deployed for the time which dynamically changes each month, use this
elif constant.IsShadingCurtainDeployOnlyDayTime == True and constant.IsDifferentShadingCurtainDeployTimeEachMonth == True:
# having shading curtain transmittance each hour. 1 = no shading curatin, the transmittance of shading curtain = deploy curtain
transmittanceThroughShadingCurtainChangingEachMonth = simulatorClass.transmittanceThroughShadingCurtainChangingEachMonth
hourlyDirectSolarRadiationAfterShadingCurtain = hourlyDirectSolarRadiationAfterInnerStructure * transmittanceThroughShadingCurtainChangingEachMonth
return hourlyDirectSolarRadiationAfterShadingCurtain
def getDiffuseSolarIrradianceBeforeShadingCurtain(simulatorClass):
# get the diffuse solar irradiance, which has not consider the transmittance of OPV film yet.
# diffuseHorizontalSolarRadiation = simulatorClass.getDiffuseSolarRadiationToOPV()
diffuseHorizontalSolarRadiation = simulatorClass.diffuseHorizontalSolarRadiation
# print("diffuseHorizontalSolarRadiation.shape:{}".format(diffuseHorizontalSolarRadiation.shape))
# consider the influecne of the PV module on the roof
overallRoofCoveringTrasmittance = constant.roofCoveringTransmittance * (1 - constant.OPVAreaCoverageRatio) + \
(constant.roofCoveringTransmittance + constant.OPVPARTransmittance) * constant.OPVAreaCoverageRatio
# get the average transmittance through roof and sidewall
transmittanceThroughWallAndRoof = (constant.greenhouseSideWallArea * constant.sideWallTransmittance + constant.greenhouseTotalRoofArea * overallRoofCoveringTrasmittance) \
/ (constant.greenhouseSideWallArea + constant.greenhouseTotalRoofArea)
# consider the light reflection by greenhouse inner structures and equipments like pipes, poles and gutters
transmittanceThroughInnerStructure = (1 - constant.GreenhouseShadeProportionByInnerStructures) * transmittanceThroughWallAndRoof
hourlyDiffuseSolarRadiationAfterShadingCurtain = diffuseHorizontalSolarRadiation * transmittanceThroughInnerStructure
return hourlyDiffuseSolarRadiationAfterShadingCurtain
def getDiffuseSolarIrradianceToPlants(simulatorClass, hourlyDiffuseSolarRadiationAfterShadingCurtain):
'''
the diffuse solar radiation was calculated by multiplying the average transmittance of all covering materials of the greenhouse (side wall, roof and PV module
'''
transmittanceThroughShadingCurtainChangingEachMonth = simulatorClass.transmittanceThroughShadingCurtainChangingEachMonth
# print("at OPVFilm, getDiffuseSolarIrradianceToPlants, transmittanceThroughShadingCurtainChangingEachMonth:{}".format(transmittanceThroughShadingCurtainChangingEachMonth))
# consider the influence of shading curtain
transmittanceThroughShadingCurtain = (constant.greenhouseSideWallArea + transmittanceThroughShadingCurtainChangingEachMonth * constant.greenhouseFloorArea) / (constant.greenhouseSideWallArea + constant.greenhouseFloorArea)
# get the diffuse solar irradiance after penetrating the greenhouse cover material
diffuseSolarIrradianceToPlants = hourlyDiffuseSolarRadiationAfterShadingCurtain * transmittanceThroughShadingCurtain
return diffuseSolarIrradianceToPlants
def calcHourlyInnerLightIntensityPPFD(HourlyOuterLightIntensityPPFD, OPVAreaCoverageRatio, OPVPARTransmissionRatio, hasShadingCurtain=False, \
shadingCurtainDeployPPFD=constant.shadingCurtainDeployPPFD, cropElectricityYieldSimulator1 = None):
'''
calculate the light intensity inside the greenhouse (inner light intensity) each hour
param:HourlyOuterLightIntensityPPFD, vector: [μmol/m^2/s]
param:OPVAreaCoverageRatio: the ratio that OPV film covers the roof
param:OPVPARTransmissionRatio: the ratio of OPV film light transmittance
param:hasShadingCurtain:
param:shadingCurtainDeployPPFD: the baseline of shading curtain opening/closing
param:cropElectricityYieldSimulator1: instance
return: vector: [μmol/m^2/s]
'''
#consider the transmittance ratio of glazing
InnerLightIntensityPPFDThroughGlazing = constant.dobulePERTransmittance * HourlyOuterLightIntensityPPFD
# print "OPVAreaCoverageRatio:{}, HourlyOuterLightIntensityPPFD:{}".format(OPVAreaCoverageRatio, HourlyOuterLightIntensityPPFD)
# print "OPVAreaCoverageRatio:{}, InnerLightIntensityPPFDThroughGlazing:{}".format(OPVAreaCoverageRatio, InnerLightIntensityPPFDThroughGlazing)
# make the list of OPV coverage ratio at each hour fixing the ratio during summer
oPVAreaCoverageRatioFixingInSummer = getDifferentOPVCoverageRatioInSummerPeriod(OPVAreaCoverageRatio, cropElectricityYieldSimulator1)
# TODO the light intensity decrease by OPV film will be considered in calculating the solar iiradiance to multispan roof. move this calculation to CropElecricityYieldSimulationDetail.getSolarIrradianceToMultiSpanRoof in the future.
#consider the transmission ratio of OPV film
HourlyInnerLightIntensityPPFDThroughOPV = InnerLightIntensityPPFDThroughGlazing * (1 - oPVAreaCoverageRatioFixingInSummer) + InnerLightIntensityPPFDThroughGlazing * oPVAreaCoverageRatioFixingInSummer * OPVPARTransmissionRatio
# print "OPVAreaCoverageRatio:{}, HourlyInnerLightIntensityPPFDThroughOPV:{}".format(OPVAreaCoverageRatio, HourlyInnerLightIntensityPPFDThroughOPV)
#consider the light reflection by greenhouse inner structures and equipments like pipes, poles and gutters
hourlyInnerLightIntensityPPFDThroughInnerStructure = (1 - constant.GreenhouseShadeProportionByInnerStructures) * HourlyInnerLightIntensityPPFDThroughOPV
# print "hourlyInnerLightIntensityPPFDThroughInnerStructure:{}".format(hourlyInnerLightIntensityPPFDThroughInnerStructure)
# set the value to the instance
# cropElectricityYieldSimulator1.setHourlyInnerLightIntensityPPFDThroughInnerStructure(hourlyInnerLightIntensityPPFDThroughInnerStructure)
# set the value to the instance
cropElectricityYieldSimulator1.setHourlyInnerLightIntensityPPFDThroughGlazing(InnerLightIntensityPPFDThroughGlazing)
cropElectricityYieldSimulator1.setHourlyInnerLightIntensityPPFDThroughInnerStructure(hourlyInnerLightIntensityPPFDThroughInnerStructure)
# take date and time
year = cropElectricityYieldSimulator1.getYear()
month = cropElectricityYieldSimulator1.getMonth()
day = cropElectricityYieldSimulator1.getDay()
hour = cropElectricityYieldSimulator1.getHour()
# array storing the light intensity after penetrating the shading curtain
hourlyInnerLightIntensityPPFDThroughShadingCurtain = np.zeros(hour.shape[0])
# consider the shading curtain
if hasShadingCurtain == True:
# if te date is between the following time and date, then discount the PPFD by the shading curtain transmittance the information about date is taken from cropElectricityYieldSimulator1 object
# if we assume the shading curtain is deployed whole day for the given period,
if constant.IsShadingCurtainDeployOnlyDayTime == False:
for i in range(0, hour.shape[0]):
if (datetime.date(year[i], month[i], day[i]) >= datetime.date(year[i], constant.ShadingCurtainDeployStartMMSpring, constant.ShadingCurtainDeployStartDDSpring ) and \
datetime.date(year[i], month[i], day[i]) <= datetime.date(year[i], constant.ShadingCurtainDeployEndMMSpring, constant.ShadingCurtainDeployEndDDSpring)) or\
(datetime.date(year[i], month[i], day[i]) >= datetime.date(year[i], constant.ShadingCurtainDeployStartMMFall, constant.ShadingCurtainDeployStartDDFall ) and \
datetime.date(year[i], month[i], day[i]) <= datetime.date(year[i], constant.ShadingCurtainDeployEndMMFall, constant.ShadingCurtainDeployEndDDFall)):
# deploy the shading curtain
hourlyInnerLightIntensityPPFDThroughShadingCurtain[i] = hourlyInnerLightIntensityPPFDThroughInnerStructure[i] * constant.shadingTransmittanceRatio
else:
# not deploy the curtain
hourlyInnerLightIntensityPPFDThroughShadingCurtain[i] = hourlyInnerLightIntensityPPFDThroughInnerStructure[i]
return hourlyInnerLightIntensityPPFDThroughShadingCurtain
# if we assume the shading curtain is deployed only for a certain hot time in a day,
elif constant.IsShadingCurtainDeployOnlyDayTime == True:
for i in range(0, hour.shape[0]):
if (datetime.date(year[i], month[i], day[i]) >= datetime.date(year[i], constant.ShadingCurtainDeployStartMMSpring, constant.ShadingCurtainDeployStartDDSpring ) and \
datetime.date(year[i], month[i], day[i]) <= datetime.date(year[i], constant.ShadingCurtainDeployEndMMSpring, constant.ShadingCurtainDeployEndDDSpring) and \
hour[i] >= constant.ShadigCuratinDeployStartHH and hour[i] <= constant.ShadigCuratinDeployEndHH) or\
(datetime.date(year[i], month[i], day[i]) >= datetime.date(year[i], constant.ShadingCurtainDeployStartMMFall, constant.ShadingCurtainDeployStartDDFall ) and \
datetime.date(year[i], month[i], day[i]) <= datetime.date(year[i], constant.ShadingCurtainDeployEndMMFall, constant.ShadingCurtainDeployEndDDFall) and \
hour[i] >= constant.ShadigCuratinDeployStartHH and hour[i] <= constant.ShadigCuratinDeployEndHH):
# deploy the shading curtain
hourlyInnerLightIntensityPPFDThroughShadingCurtain[i] = hourlyInnerLightIntensityPPFDThroughInnerStructure[i] * constant.shadingTransmittanceRatio
else:
# not deploy the curtain
hourlyInnerLightIntensityPPFDThroughShadingCurtain[i] = hourlyInnerLightIntensityPPFDThroughInnerStructure[i]
return hourlyInnerLightIntensityPPFDThroughShadingCurtain
# the shading curtain algorithm which open/close shading curatin each hour
# if PPFD is over hourlyInnerLightIntensityPPFD, then deploy the shading curtain, and decrease PPFD. otehrwise leave it
# hourlyInnerLightIntensityPPFDThroughShadingCurtain = np.array([x * constant.shadingTransmittanceRatio\
# if x > shadingCurtainDeployPPFD else x for x in hourlyInnerLightIntensityPPFDThroughInnerStructure])
# print "InnerLightIntensityPPFDThroughShadingCurtain:{}".format(InnerLightIntensityPPFDThroughShadingCurtain)
# return hourlyInnerLightIntensityPPFDThroughShadingCurtain
# come to here when not considering shading curtain
return hourlyInnerLightIntensityPPFDThroughInnerStructure
def getDifferentOPVCoverageRatioInSummerPeriod(OPVAreaCoverageRatio, simulatorClass):
'''
this function changes the opv coverage ratio during the summer period into the constant ratio defined at the constant class.,
:param OPVPARTransmissionRatio:
:param cropElectricityYieldSimulator1:
:return:
'''
# take date and time
year = simulatorClass.getYear()
month = simulatorClass.getMonth()
day = simulatorClass.getDay()
OPVCoverageRatio = np.zeros(year.shape[0])
for i in range(0, year.shape[0]):
# if it is during the summer period when shading curtain is deployed.
if datetime.date(year[i], month[i], day[i]) >= datetime.date(year[i], constant.SummerPeriodStartMM, constant.SummerPeriodStartDD) and \
datetime.date(year[i], month[i], day[i]) <= datetime.date(year[i], constant.SummerPeriodEndMM, constant.SummerPeriodEndDD):
OPVCoverageRatio[i] = constant.OPVAreaCoverageRatioSummerPeriod
else:
OPVCoverageRatio[i] = OPVAreaCoverageRatio
# set the array to the objec
simulatorClass.OPVCoverageRatiosConsiderSummerRatio = OPVCoverageRatio
# print("OPVCoverageRatio:{}".format(OPVCoverageRatio))
return OPVCoverageRatio
|
{"/OPVFilm.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/ShadingCurtain.py"], "/CropElectricityYieldProfitMINLP.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelS_Pearson1997.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/PlantGrowthModelS_Pearson1997Constant.py", "/Lettuce.py"], "/GreenhouseEnergyBalanceConstant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/Util.py": ["/CropElectricityYeildSimulatorConstant.py"], "/SolarIrradianceMultiSpanRoof.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/GreenhouseEnergyBalance.py": ["/Lettuce.py", "/CropElectricityYeildSimulatorConstant.py", "/GreenhouseEnergyBalanceConstant.py", "/Util.py"], "/SimulatorMain.py": ["/CropElectricityYeildSimulator1.py", "/Util.py", "/CropElectricityYeildSimulatorConstant.py"], "/CropElectricityYieldProfitRLShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/ShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelValidation.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulator1.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulatorDetail.py": ["/ShadingCurtain.py", "/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/Lettuce.py", "/PlantGrowthModelS_Pearson1997.py", "/SolarIrradianceMultiSpanRoof.py", "/GreenhouseEnergyBalance.py"], "/PlantGrowthModelS_Pearson1997Constant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/SimulatorClass.py": ["/CropElectricityYeildSimulatorConstant.py"], "/Lettuce.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/plantGrowthModelE_J_VanHenten.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py"]}
|
8,656
|
kensaku-okada/Greenhouse-with-OPV-film-Model
|
refs/heads/master
|
/CropElectricityYieldProfitMINLP.py
|
##########import package files##########
from scipy import stats
import datetime
import sys
import os as os
import numpy as np
import matplotlib.pyplot as plt
import math
import CropElectricityYeildSimulatorConstant as constant
import Util as util
import OPVFilm
#import Lettuce
import CropElectricityYeildSimulatorDetail as simulatorDetail
import QlearningAgentShadingCurtain as QRLshadingCurtain
import SimulatorClass as SimulatorClass
#######################################################
def simulateCropElectricityYieldProfitForMINLP():
'''
1st simulator of crop and electricity yield and their profit
:return: profitVSOPVCoverageData
'''
print ("start modeling: datetime.datetime.now():{}".format(datetime.datetime.now()))
# declare the class
simulatorClass = SimulatorClass.SimulatorClass()
##########file import (TucsonHourlyOuterEinvironmentData) start##########
fileName = "20130101-20170101" + ".csv"
year, \
month, \
day, \
hour, \
hourlyHorizontalDiffuseOuterSolarIrradiance, \
hourlyHorizontalTotalOuterSolarIrradiance, \
hourlyHorizontalDirectOuterSolarIrradiance, \
hourlyHorizontalTotalBeamMeterBodyTemperature, \
hourlyAirTemperature, simulatorClass = util.getArraysFromData(fileName, simulatorClass)
##########file import (TucsonHourlyOuterEinvironmentData) end##########
# set the values to the object
simulatorClass.setYear(year)
simulatorClass.setMonth(month)
simulatorClass.setDay(day)
simulatorClass.setHour(hour)
##########file import (TucsonHourlyOuterEinvironmentData) end##########
##########solar irradiance to OPV calculation start##########
# calculate with real data
# hourly average [W m^-2]
directSolarRadiationToOPVEastDirection, directSolarRadiationToOPVWestDirection, diffuseSolarRadiationToOPV, albedoSolarRadiationToOPV = \
simulatorDetail.calcOPVmoduleSolarIrradianceGHRoof(year, month, day, hour, hourlyHorizontalDiffuseOuterSolarIrradiance, \
hourlyHorizontalDirectOuterSolarIrradiance, "EastWestDirectionRoof")
# [W m^-2] per hour
totalSolarRadiationToOPV = (directSolarRadiationToOPVEastDirection + directSolarRadiationToOPVWestDirection) / 2.0 + diffuseSolarRadiationToOPV + albedoSolarRadiationToOPV
# # calculate without real data.
# simulatedDirectSolarRadiationToOPVEastDirection, \
# simulatedDirectSolarRadiationToOPVWestDirection, \
# simulatedDiffuseSolarRadiationToOPV, \
# simulatedAlbedoSolarRadiationToOPV = simulatorDetail.calcOPVmoduleSolarIrradianceGHRoof(year, month, day, hour)
# # [W m^-2] per hour
# simulatedTotalSolarRadiationToOPV = simulatedDirectSolarRadiationToOPVEastDirection + simulatedDirectSolarRadiationToOPVWestDirection + \
# simulatedDiffuseSolarRadiationToOPV + simulatedAlbedoSolarRadiationToOPV
# print "directSolarRadiationToOPV:{}".format(directSolarRadiationToOPV)
# print "diffuseSolarRadiationToOPV:{}".format(diffuseSolarRadiationToOPV)
# print "groundReflectedSolarradiationToOPV:{}".format(groundReflectedSolarradiationToOPV)
# unit change: [W m^-2] -> [umol m^-2 s^-1] == PPFD
directPPFDToOPVEastDirection = util.convertFromWattperSecSquareMeterToPPFD(directSolarRadiationToOPVEastDirection)
directPPFDToOPVWestDirection = util.convertFromWattperSecSquareMeterToPPFD(directSolarRadiationToOPVWestDirection)
diffusePPFDToOPV = util.convertFromWattperSecSquareMeterToPPFD(diffuseSolarRadiationToOPV)
groundReflectedPPFDToOPV = util.convertFromWattperSecSquareMeterToPPFD(albedoSolarRadiationToOPV)
totalPPFDToOPV = directPPFDToOPVEastDirection + directPPFDToOPVWestDirection + diffusePPFDToOPV + groundReflectedPPFDToOPV
# print"diffusePPFDToOPV.shape:{}".format(diffusePPFDToOPV.shape)
# set the matrix to the object
simulatorClass.setDirectPPFDToOPVEastDirection(directPPFDToOPVEastDirection)
simulatorClass.setDirectPPFDToOPVWestDirection(directPPFDToOPVWestDirection)
simulatorClass.setDiffusePPFDToOPV(diffusePPFDToOPV)
simulatorClass.setGroundReflectedPPFDToOPV(groundReflectedPPFDToOPV)
# unit change: hourly [umol m^-2 s^-1] -> [mol m^-2 day^-1] == DLI :number of photons received in a square meter per day
directDLIToOPVEastDirection = util.convertFromHourlyPPFDWholeDayToDLI(directPPFDToOPVEastDirection)
directDLIToOPVWestDirection = util.convertFromHourlyPPFDWholeDayToDLI(directPPFDToOPVWestDirection)
diffuseDLIToOPV = util.convertFromHourlyPPFDWholeDayToDLI(diffusePPFDToOPV)
groundReflectedDLIToOPV = util.convertFromHourlyPPFDWholeDayToDLI(groundReflectedPPFDToOPV)
totalDLIToOPV = directDLIToOPVEastDirection + directDLIToOPVWestDirection + diffuseDLIToOPV + groundReflectedDLIToOPV
# print "directDLIToOPVEastDirection:{}".format(directDLIToOPVEastDirection)
# print "diffuseDLIToOPV.shape:{}".format(diffuseDLIToOPV.shape)
# print "groundReflectedDLIToOPV:{}".format(groundReflectedDLIToOPV)
# ################## plot the difference of real data and simulated data start######################
# Title = "difference of the model output with real data and with no data"
# xAxisLabel = "time [hour]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
# yAxisLabel = "total Solar irradiance [W m^-2]"
# util.plotTwoData(np.linspace(0, simulationDaysInt * constant.hourperDay, simulationDaysInt * constant.hourperDay), \
# totalSolarRadiationToOPV, simulatedTotalSolarRadiationToOPV ,Title, xAxisLabel, yAxisLabel, "with real data", "wth no data")
# util.saveFigure(Title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
# ################## plot the difference of real data and simulated data end######################
# ################## plot the distribution of direct and diffuse PPFD start######################
# Title = "TOTAL outer PPFD to OPV"
# xAxisLabel = "time [hour]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
# yAxisLabel = "PPFD [umol m^-2 s^-1]"
# util.plotData(np.linspace(0, simulationDaysInt * constant.hourperDay, simulationDaysInt * constant.hourperDay), \
# directPPFDToOPV + diffusePPFDToOPV + groundReflectedPPFDToOPV, Title, xAxisLabel, yAxisLabel)
# util.saveFigure(Title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
# ################## plot the distribution of direct and diffuse PPFD end######################
# ################## plot the distribution of direct and diffuse solar DLI start######################
# Title = "direct and diffuse outer DLI to OPV"
# xAxisLabel = "time [day]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
# yAxisLabel = "DLI [mol m^-2 day^-1]"
# y1Label = "(directDLIToOPVEastDirection+directDLIToOPVWestDirection)/2.0"
# y2Label = "diffuseDLIToOPV"
# util.plotTwoData(np.linspace(0, simulationDaysInt, simulationDaysInt), (directDLIToOPVEastDirection+directDLIToOPVWestDirection)/2.0, diffuseDLIToOPV, Title,
# xAxisLabel, yAxisLabel, y1Label, y2Label)
# util.saveFigure(Title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
# ################## plot the distribution of direct and diffuse solar DLI end######################
# ################## plot the distribution of various DLI to OPV film start######################
# Title = "various DLI to OPV film"
# plotDataSet = np.array([directDLIToOPVEastDirection, directDLIToOPVWestDirection, diffuseDLIToOPV,
# groundReflectedDLIToOPV])
# labelList = np.array(["directDLIToOPVEastDirection", "directDLIToOPVWestDirection", "diffuseDLIToOPV",
# "groundReflectedDLIToOPV"])
# xAxisLabel = "time [day]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
# yAxisLabel = "DLI [mol m^-2 day^-1]"
# util.plotMultipleData(np.linspace(0, simulationDaysInt, simulationDaysInt), plotDataSet, labelList, Title,
# xAxisLabel, yAxisLabel)
# util.saveFigure(Title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
# ################## plot the distribution of various DLI to OPV film end######################
################## calculate the daily electricity yield per area start#####################
# TODO maybe we need to consider the tilt of OPV and OPV material for the temperature of OPV film. right now, just use the measured temperature
# get the daily electricity yield per area per day ([J/m^2] per day) based on the given light intensity ([Celsius],[W/m^2]).
dailyJopvoutperArea = simulatorDetail.calcDailyElectricityYieldSimulationperArea(hourlyHorizontalTotalBeamMeterBodyTemperature, \
directSolarRadiationToOPVEastDirection + directSolarRadiationToOPVWestDirection,
diffuseSolarRadiationToOPV,
albedoSolarRadiationToOPV)
# unit Exchange [J/m^2] -> [wh / m^2]
dailyWhopvoutperArea = util.convertFromJouleToWattHour(dailyJopvoutperArea)
# unit Exchange [Wh/ m^2] -> [kWh/m^2]
dailykWhopvoutperArea = util.convertWhTokWh(dailyWhopvoutperArea)
# ################### plot the electricity yield per area with given OPV film
# title = "electricity yield per area vs OPV film"
# xAxisLabel = "time [day]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
# yAxisLabel = "Electricity yield per OPV area [kWh/m^2/day]"
# util.plotData(np.linspace(0, simulationDaysInt, simulationDaysInt), dailykWhopvoutperArea, title, xAxisLabel, yAxisLabel)
# util.saveFigure(title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
# ################## calculate the daily electricity yield per area end#####################
################## calculate the daily electricity sales start#####################
# convert the year of each hour to the year to each day
yearOfeachDay = year[::24]
# convert the month of each hour to the month to each day
monthOfeachDay = month[::24]
# get the monthly electricity sales per area [USD/month/m^2]
monthlyElectricitySalesperArea = simulatorDetail.getMonthlyElectricitySalesperArea(dailyJopvoutperArea, yearOfeachDay, monthOfeachDay)
# set the value to the object
simulatorClass.setMonthlyElectricitySalesperArea(monthlyElectricitySalesperArea)
# print "simulatorClass.getMonthlyElectricitySalesperArea():{}".format(simulatorClass.getMonthlyElectricitySalesperArea())
################## calculate the daily electricity sales end#####################
##################calculate the electricity cost per area start######################################
# initialOPVCostUSD = constant.OPVPricePerAreaUSD * OPVFilm.getOPVArea(constant.OPVAreaCoverageRatio)
# # [USD]
# OPVCostUSDForDepreciation = initialOPVCostUSD * (simulationDaysInt / constant.OPVDepreciationPeriodDays)
# # set the value to the object
# simulatorClass.setOPVCostUSDForDepreciationperArea(OPVCostUSDForDepreciation / OPVFilm.getOPVArea(constant.OPVAreaCoverageRatio))
if constant.ifConsiderOPVCost is True:
initialOPVCostUSD = constant.OPVPricePerAreaUSD * OPVFilm.getOPVArea(constant.OPVAreaCoverageRatio)
# [USD]
OPVCostUSDForDepreciation = initialOPVCostUSD * (util.getSimulationDaysInt() / constant.OPVDepreciationPeriodDays)
# set the value to the object
simulatorClass.setOPVCostUSDForDepreciationperArea(
OPVCostUSDForDepreciation / OPVFilm.getOPVArea(constant.OPVAreaCoverageRatio))
else:
# set the value to the object. the value is zero if not consider the purchase cost
simulatorClass.setOPVCostUSDForDepreciationperArea(0.0)
##################calculate the electricity cost per area end######################################
################## calculate the daily plant yield start#####################
# [String]
plantGrowthModel = constant.TaylorExpantionWithFluctuatingDLI
# cultivation days per harvest [days/harvest]
cultivationDaysperHarvest = constant.cultivationDaysperHarvest
# OPV coverage ratio [-]
OPVCoverage = constant.OPVAreaCoverageRatio
# boolean
hasShadingCurtain = constant.hasShadingCurtain
# PPFD [umol m^-2 s^-1]
ShadingCurtainDeployPPFD = constant.ShadingCurtainDeployPPFD
# calculate plant yield given an OPV coverage and model :daily [g/unit]
shootFreshMassList, unitDailyFreshWeightIncrease, accumulatedUnitDailyFreshWeightIncrease, unitDailyHarvestedFreshWeight = \
simulatorDetail.calcPlantYieldSimulation(plantGrowthModel, cultivationDaysperHarvest, OPVCoverage, \
(directPPFDToOPVEastDirection + directPPFDToOPVWestDirection) / 2.0, diffusePPFDToOPV, groundReflectedPPFDToOPV,
hasShadingCurtain, ShadingCurtainDeployPPFD, simulatorClass)
# the DLI to plants [mol/m^2/day]
TotalDLItoPlants = simulatorDetail.getTotalDLIToPlants(OPVCoverage, (directPPFDToOPVEastDirection + directPPFDToOPVWestDirection) / 2.0, diffusePPFDToOPV,
groundReflectedPPFDToOPV, \
hasShadingCurtain, ShadingCurtainDeployPPFD, simulatorClass)
# print "TotalDLItoPlants:{}".format(TotalDLItoPlants)
# print "TotalDLItoPlants.shape:{}".format(TotalDLItoPlants.shape)
# set the value to the instance
simulatorClass.setTotalDLItoPlantsBaselineShadingCuratin(TotalDLItoPlants)
# ######################### plot a graph showing only shootFreshMassList per unit
# title = "plant yield per head vs time (OPV coverage " + str(int(100 * OPVCoverage)) + "%)"
# xAxisLabel = "time [day]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
# yAxisLabel = "plant fresh weight[g/head]"
# util.plotData(np.linspace(0, simulationDaysInt, simulationDaysInt), shootFreshMassList, title, xAxisLabel, yAxisLabel)
# util.saveFigure(title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
# #######################################################################
# # unit conversion; get the plant yield per day per area: [g/unit] -> [g/m^2]
# shootFreshMassListperArea = util.convertUnitShootFreshMassToShootFreshMassperArea(shootFreshMassList)
# # unit conversion: [g/m^2] -> [kg/m^2]
# shootFreshMassListperAreaKg = util.convertFromgramTokilogram(shootFreshMassListperArea)
# ######################## plot a graph showing only shootFreshMassList per square meter
# title = "plant yield per area vs time (OPV coverage " + str(int(100 * OPVCoverage)) + "%)"
# xAxisLabel = "time [day]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
# yAxisLabel = "plant fresh weight[kg/m^2]"
# util.plotData(np.linspace(0, simulationDaysInt, simulationDaysInt), shootFreshMassListperAreaKg, title, xAxisLabel, yAxisLabel)
# util.saveFigure(title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
# ######################################################################
# ################## plot various unit Plant Yield vs time
# plotDataSet = np.array([shootFreshMassList, unitDailyFreshWeightIncrease, accumulatedUnitDailyFreshWeightIncrease, unitDailyHarvestedFreshWeight])
# labelList = np.array(["shootFreshMassList", "unitDailyFreshWeightIncrease", "accumulatedUnitDailyFreshWeightIncrease", "unitDailyHarvestedFreshWeight"])
# title = "Various unit Plant Yield vs time (OPV coverage " + str(int(100 * OPVCoverage)) + "%)"
# xAxisLabel = "time [day]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
# yAxisLabel = "Unit plant Fresh Weight [g/unit]"
# util.plotMultipleData(np.linspace(0, simulationDaysInt, simulationDaysInt), plotDataSet, labelList, title, xAxisLabel, yAxisLabel)
# util.saveFigure(title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
# #######################################################################
################## calculate the daily plant yield end#####################
################## calculate the daily plant sales start#####################
################## calculate the daily plant sales end#####################
################## calculate the daily plant cost start#####################
################## calculate the daily plant cost end#####################
print ("end modeling: datetime.datetime.now():{}".format(datetime.datetime.now()))
return simulatorClass
|
{"/OPVFilm.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/ShadingCurtain.py"], "/CropElectricityYieldProfitMINLP.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelS_Pearson1997.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/PlantGrowthModelS_Pearson1997Constant.py", "/Lettuce.py"], "/GreenhouseEnergyBalanceConstant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/Util.py": ["/CropElectricityYeildSimulatorConstant.py"], "/SolarIrradianceMultiSpanRoof.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/GreenhouseEnergyBalance.py": ["/Lettuce.py", "/CropElectricityYeildSimulatorConstant.py", "/GreenhouseEnergyBalanceConstant.py", "/Util.py"], "/SimulatorMain.py": ["/CropElectricityYeildSimulator1.py", "/Util.py", "/CropElectricityYeildSimulatorConstant.py"], "/CropElectricityYieldProfitRLShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/ShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelValidation.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulator1.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulatorDetail.py": ["/ShadingCurtain.py", "/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/Lettuce.py", "/PlantGrowthModelS_Pearson1997.py", "/SolarIrradianceMultiSpanRoof.py", "/GreenhouseEnergyBalance.py"], "/PlantGrowthModelS_Pearson1997Constant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/SimulatorClass.py": ["/CropElectricityYeildSimulatorConstant.py"], "/Lettuce.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/plantGrowthModelE_J_VanHenten.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py"]}
|
8,657
|
kensaku-okada/Greenhouse-with-OPV-film-Model
|
refs/heads/master
|
/PlantGrowthModelS_Pearson1997.py
|
# -*- coding: utf-8 -*-
##########import package files##########
import sys
import os as os
import numpy as np
import math
import CropElectricityYeildSimulatorConstant as constant
import Util as util
import PlantGrowthModelS_Pearson1997Constant as PearsonConstant
import Lettuce
#######################################################
# command to show all array data
# np.set_printoptions(threshold=np.inf)
# print ("hourlyHorizontalDirectOuterSolarIrradiance:{}".format(hourlyHorizontalDirectOuterSolarIrradiance))
# np.set_printoptions(threshold=1000)
# ####################################################################################################
# # Stop execution here...
# sys.exit()
# # Move the above line to different parts of the assignment as you implement more of the functionality.
# ####################################################################################################
def calcUnitDailyFreshWeightS_Pearson1997(simulatorClass):
'''
reference: S. Pearson, T. R. Wheeler, P. Hadley & A. E. Wheldon, 1997, "A validated model to predict the effects of environment on the growth of lettuce (Lactuca sativa L.): Implications for climate change"
https://www.researchgate.net/publication/286938495_A_validated_model_to_predict_the_effects_of_environment_on_the_growth_of_lettuce_Lactuca_sativa_L_Implications_for_climate_change
D. G. SWEENEY, D. W. HAND, G. SLACK AND J. H. M. THORNLEY, 1981, "Modelling the Growth of Winter Lettuce": http://agris.fao.org/agris-search/search.do?recordID=US201301972216
:return:
'''
# cultivationDaysperHarvest = simulatorClass.getCultivationDaysperHarvest()
# OPVAreaCoverageRatio = simulatorClass.getOPVAreaCoverageRatio()
# hasShadingCurtain = simulatorClass.getIfHasShadingCurtain()
# ShadingCurtainDeployPPFD = simulatorClass.getShadingCurtainDeployPPFD()
simulationDaysInt = util.getSimulationDaysInt()
##################################
##### input variables start #####
##################################
# Temperature [Clusius]
# it was assumed that the canopy temperature is instantaneously adjusted to the setpoint temperature at each hour.
T_a = Lettuce.getGreenhouseTemperatureEachDay(simulatorClass)
# Horizontal irradiance above the canopy (PAR) [W/m^2]
directSolarIrradianceToPlants = simulatorClass.directSolarIrradianceToPlants
diffuseSolarIrradianceToPlants = simulatorClass.diffuseSolarIrradianceToPlants
totalSolarIrradianceToPlants = directSolarIrradianceToPlants + diffuseSolarIrradianceToPlants
# By dividing the irradiance by 2, the shortwave radiation is converted into PAR [W/m^2]
totalSolarIrradianceToPlantsPAR = totalSolarIrradianceToPlants/2.0
# convert the unit from [average W / m^2 each hour] to [J / m^2 each day]
J = util.convertWattPerSquareMeterEachHourToJoulePerSaureMeterEachDay(totalSolarIrradianceToPlantsPAR)
# CO_2 concentration [kg(CO_2) / m^3]
# it is temporarily assumed that all hourly CO2 concentration is 400 [ppm] = 775 [kg / m^3] 355 [ppm] = 688 [kg / m^3]
# You can convert the unit of CO2 concentration at https://www.lenntech.com/calculators/ppm/converter-parts-per-million.htm
C = np.array([775.0] * T_a.shape[0])
# Thermal time [Celsius * d]: calculating thermal time by totalling the mean temperatures for each day during each cultivation period.
# theta = getThermalTime(T_a)
theta = np.zeros(T_a.shape[0])
print("T_a:{}".format(T_a))
print("J:{}".format(J))
print("C:{}".format(C))
# ####################################################################################################
# # Stop execution here...
# sys.exit()
# # Move the above line to different parts of the assignment as you implement more of the functionality.
# ####################################################################################################
##################################
##### input variables end #####
##################################
# dependent variables
# Structured dry weight [g]
W_G = np.zeros(T_a.shape[0])
# Storage (non-structural) dry weight [g]
W_S = np.zeros(T_a.shape[0])
# The plant dry weight (excluding roots) [g]
W = np.zeros(T_a.shape[0])
# initial values
# reference:
# it was estimated from the reference of SWEENEY et al. (1981) saying "The cropping area was divided into three east-west strips (5.49 m X 1.83 m) with 0.6 m wide pathways on either side." and
# its initial values W_G(1) (= 1.9 * 10^(-6) kg) and W_S(1) (= 1.9 * 10^(-6) kg), and Pearson et al (1997) saying "... the initial dry weight of transplants comprised 80% structural and 20% storage material, since Goudriaan et al. (1985) indicated that storage dry weight rarely exceeds 25% of the total dry matter."
# input initial data [g]
# W_G[0] = 1.9*10**(-3.0)*2 * 0.8 * constant.greenhouseCultivationFloorArea / (5.49 * 1.83)
W_G[0] = 1.9*10**(-3.0)*2 * 0.8
# Storage dry weight [g]
W_S[0] = 1.9*10**(-3.0)*2 * 0.2
# It was assumed to take 2 days to the next cultivation cycle assuming "transplanting shock prevented growth during the first 48 h"
# initial total dry weight
W[0] = W_G[0] + W_S[0]
theta[0] = T_a[0]
# print("W_G[0]:{}".format(W_G[0]))
# print("W_S[0]:{}".format(W_S[0]))
# loop counter
i = 1
# reference: Pearson et al. (1997)
# It was assumed that the germination and growth before transplanting were done at the growth chamber. The simulation period starts when the first cycle lettuces were planted in a greenhouse.
while i < simulationDaysInt:
# print("i-1:{}, W_G[i-1]:{}, W_S[i-1]:{}".format(i-1, W_G[i-1],W_S[i-1]))
# the sub-optimal equivalent of a supra-optimal temperature) eq 8
T_e = PearsonConstant.T_o - abs(PearsonConstant.T_o - T_a[i-1])
# print("T_e:{}".format(T_e))
# the increase in structured dry weight
# dW_G = W_G[i-1] * PearsonConstant.k * T_e
dW_G = (W_G[i-1]) * PearsonConstant.k * T_e
W_G[i] = W_G[i - 1] + dW_G
# print("dW_G:{}".format(dW_G))
# T_ep: effective temperature [Celusius]
# According to Pearson, S. Hadley, P. Wheldon, A.E. (1993), "A reanalysis of the effects of temperature and irradiance on time to flowering in chrysanthemum
# (Dendranthema grandiflora)", Effective temperature is the sub-optimum temperature equivalent of a supra-optimum temperature in terms of developmental rate.
# Also, since Pearson et al. (1997) says "The effective temperature (Tep) for photosynthesis was determined with an optimum of Top and the function had a rate constant phi."
# it was assumed that T_ep can be derived with the same equation and variables as T_e
T_ep = PearsonConstant.T_op - abs(PearsonConstant.T_op - T_a[i-1])
# print("T_ep:{}".format(T_ep))
# the decline in photosynthesis with plant age
# Pg = PearsonConstant.alpha_m*((1.0-PearsonConstant.beta)/(PearsonConstant.tau*C[i-1]))*J[i-1]*T_ep*PearsonConstant.phi*(PearsonConstant.theta_m-theta[0])/PearsonConstant.theta_m
Pg = PearsonConstant.alpha_m * ((1.0-PearsonConstant.beta)/ (PearsonConstant.tau * C[i-1]))*J[i-1]*T_ep*PearsonConstant.phi*(PearsonConstant.theta_m-theta[i-1])/PearsonConstant.theta_m
# print("Pg:{}".format(Pg))
# the relation describing respiration losses
# print("PearsonConstant.R_G:{}".format(PearsonConstant.R_G))
# print("PearsonConstant.theta_m:{}".format(PearsonConstant.theta_m))
# print("PearsonConstant.gamma:{}".format(PearsonConstant.gamma))
# print("PearsonConstant.epsilon:{}".format(PearsonConstant.epsilon))
# Rd = PearsonConstant.R_G * ((PearsonConstant.theta_m - theta[0])/PearsonConstant.gamma) / PearsonConstant.theta_m * T_a[i-1] * PearsonConstant.epsilon * dW_G
# this part was changed from the reference's original formula: theta[0] -> theta[i-1]
Rd = PearsonConstant.R_G * ((PearsonConstant.theta_m - theta[i-1])/PearsonConstant.gamma) / PearsonConstant.theta_m * T_a[i-1] * PearsonConstant.epsilon * dW_G
# print("Rd:{}".format(Rd))
dW_S = PearsonConstant.psi * (PearsonConstant.h)**2.0 * (1.0 - math.exp(-PearsonConstant.F_G * W_G[i-1] / ((PearsonConstant.h)**2.0))) * Pg - Rd
# print("dW_S:{}".format(dW_S))
W_S[i] = W_S[i - 1] + dW_S
# The plant dry weight (excluding roots) W
W[i] = W_G[i] + W_S[i]
# print("i:{}, W[i]:{}".format(i, W[i]))
# accumulate the thermal time
theta[i] = theta[i - 1] + T_a[i - 1]
# if the dry weight exceeds the weight for cultimvation, then reset the dryweight
if W[i] > constant.harvestDryWeight :
# It was assumed to take 3 days to the next cultivation cycle assuming "transplanting shock prevented growth during the first 48 h", and it takes one day for preparation.
i += 3 + 1
if(i >= simulationDaysInt): break
# reset the weights
W_S[i-1] = W_G[0]
W_S[i-2] = W_G[0]
W_G[i-1] = W_S[0]
W_G[i-2] = W_S[0]
# The plant dry weight (excluding roots) W
W[i-1] = W_S[i-1] + W_G[i-1]
W[i-2] = W_S[i-2] + W_G[i-2]
# accumulate the thermal time
theta[i - 2] = T_a[i-2]
theta[i-1] = theta[i - 2] + T_a[i-1]
theta[i] = theta[i-1] + T_a[i]
else:
# increment the counter for one day
i += 1
print("theta:{}".format(theta))
print("W_G:{}".format(W_G))
print("W_S:{}".format(W_S))
print("W:{}".format(W))
# convert the dry weight into fresh weight
WFreshPerHead = constant.DryMassToFreshMass * W
print("WFresh:{}".format(WFreshPerHead))
# get the fresh weight increase
WFreshPerHeadWeightIncrease = Lettuce.getFreshWeightIncrease(WFreshPerHead)
# get the accumulated fresh weight during the simulation period
WAccumulatedFreshWeightIncreasePerHead = Lettuce.getAccumulatedFreshWeightIncrease(WFreshPerHead)
# get the harvested weight
WHarvestedFreshWeightPerHead = Lettuce.getHarvestedFreshWeight(WFreshPerHead)
return WFreshPerHead, WFreshPerHeadWeightIncrease, WAccumulatedFreshWeightIncreasePerHead, WHarvestedFreshWeightPerHead
# Moved to Lettuce.py
# def getGreenhouseTemperatureEachDay(simulatorClass):
# # It was assumed the greenhouse temperature was instantaneously adjusted to the set point temperatures at daytime and night time respectively
# hourlyDayOrNightFlag = simulatorClass.hourlyDayOrNightFlag
# greenhouseTemperature = np.array([constant.setPointTemperatureDayTime if i == constant.daytime else constant.setPointTemperatureNightTime for i in hourlyDayOrNightFlag])
#
# # calc the mean temperature each day
# dailyAverageTemperature = np.zeros(util.getSimulationDaysInt())
# for i in range(0, util.getSimulationDaysInt()):
# dailyAverageTemperature[i] = np.average(greenhouseTemperature[i * constant.hourperDay: (i + 1) * constant.hourperDay])
# return dailyAverageTemperature
def getThermalTime(dailyAverageTemperature):
'''
definition of thermal time in plant science reference: http://onlinelibrary.wiley.com/doi/10.1111/j.1744-7348.2005.04088.x/pdf
:param dailyAverageTemperature: average [Celusius] per day
:return:
'''
thermalTime = np.zeros(dailyAverageTemperature.shape[0])
for i in range(0, thermalTime.shape[0]):
thermalTime[i] = sum(dailyAverageTemperature[0:i+1])
return thermalTime
# Moved to Lettuce.py
# def getFreshWeightIncrease(WFresh):
# # get the fresh weight increase
#
# freshWeightIncrease = np.array([WFresh[i] - WFresh[i-1] if WFresh[i] - WFresh[i-1] > 0 else 0.0 for i in range (1, WFresh.shape[0])])
# # insert the value for i == 0
# freshWeightIncrease[0] = 0.0
#
# return freshWeightIncrease
#
# def getAccumulatedFreshWeight(WFresh):
# # get accumulated fresh weight
#
# accumulatedFreshWeight = np.array([WFresh[i] + WFresh[i-1] if WFresh[i] - WFresh[0] > 0 else WFresh[i-1] for i in range (1, WFresh.shape[0])])
# # insert the value for i == 0
# accumulatedFreshWeight[0] = WFresh[0]
#
# return accumulatedFreshWeight
#
#
# def getHarvestedFreshWeight(WFresh):
# # get the harvested fresh weight
#
# # record the fresh weight harvested at each harvest date
# harvestedFreshWeight = np.array([WFresh[i-1] if WFresh[i] - WFresh[i-1] < 0 else 0.0 for i in range (1, WFresh.shape[0])])
# # insert the value for i == 0
# harvestedFreshWeight[0] = 0.0
#
# return harvestedFreshWeight
|
{"/OPVFilm.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/ShadingCurtain.py"], "/CropElectricityYieldProfitMINLP.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelS_Pearson1997.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/PlantGrowthModelS_Pearson1997Constant.py", "/Lettuce.py"], "/GreenhouseEnergyBalanceConstant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/Util.py": ["/CropElectricityYeildSimulatorConstant.py"], "/SolarIrradianceMultiSpanRoof.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/GreenhouseEnergyBalance.py": ["/Lettuce.py", "/CropElectricityYeildSimulatorConstant.py", "/GreenhouseEnergyBalanceConstant.py", "/Util.py"], "/SimulatorMain.py": ["/CropElectricityYeildSimulator1.py", "/Util.py", "/CropElectricityYeildSimulatorConstant.py"], "/CropElectricityYieldProfitRLShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/ShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelValidation.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulator1.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulatorDetail.py": ["/ShadingCurtain.py", "/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/Lettuce.py", "/PlantGrowthModelS_Pearson1997.py", "/SolarIrradianceMultiSpanRoof.py", "/GreenhouseEnergyBalance.py"], "/PlantGrowthModelS_Pearson1997Constant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/SimulatorClass.py": ["/CropElectricityYeildSimulatorConstant.py"], "/Lettuce.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/plantGrowthModelE_J_VanHenten.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py"]}
|
8,658
|
kensaku-okada/Greenhouse-with-OPV-film-Model
|
refs/heads/master
|
/GreenhouseEnergyBalanceConstant.py
|
# -*- coding: utf-8 -*-
#############command to print out all array data
# np.set_printoptions(threshold=np.inf)
# print ("directSolarRadiationToOPVWestDirection:{}".format(directSolarRadiationToOPVWestDirection))
# np.set_printoptions(threshold=1000)
#############
# ####################################################################################################
# # Stop execution here...
# sys.exit()
# # Move the above line to different parts of the assignment as you implement more of the functionality.
# ####################################################################################################
##########import package files##########
import datetime
import sys
import os
import numpy as np
import math
import CropElectricityYeildSimulatorConstant as constant
import Util as util
#######################################################
# the heat transfer coefficient [W m-2 Celsius degree] (ASHRAE guide and data book fundamentals, 1981)
# source: https://www.crcpress.com/Greenhouses-Advanced-Technology-for-Protected-Horticulture/Hanan/p/book/9780849316982
# Hanan, J.J. (1998). Chapter 2 Structures: locations, styles, and covers. Greenhouses: advanced technology for protected horticulture (56). CRC Press. Boca Raton, FL.
# I directly got this value from a confidential research thesis in Kacira Lab at CEAC in University of Arizona. the paper said this value was taken from Hanan (1998)
U = 6.3
# if the roof is made from double PE
# U = 4.0
# e Stefan-Boltzmann's constant [W m-2 K-4]
delta = 5.67 * 10.0**(-8)
# transmissitiy of thermal radiation (not solar radiation) for the single layer high density polyethylene
# source:Nadia Sabeh, tomato greenhouse roadmap - a guide to greenhouse tomato production, page 24, https://www.amazon.com/Tomato-Greenhouse-Roadmap-Guide-Production-ebook/dp/B00O4CPO42
tau_tc = 0.8
# source: S. Zhu, J. Deltour, S. Wang, 1998, Modeling the thermal characteristics of greenhouse pond systems,
# tau_tc = 0.42
# average emissivity of the interior surface, assuming the high density polyethylene
# source: S. Zhu, J. Deltour, S. Wang, 1998, Modeling the thermal characteristics of greenhouse pond systems,
# epsilon_i = 0.53
# source: Tomohiro OKADA, Ryohei ISHIGE, and Shinji ANDO, 2016, Analysis of Thermal Radiation Properties of Polyimide and Polymeric Materials Based on ATR-IR spectroscopy
# This paper seems to be more reliable at a content of research
epsilon_i = 0.3
################## constnats for Q_e, latent heat transfer by plant transpiration start #######################
# another source: http://edis.ifas.ufl.edu/pdffiles/ae/ae45900.pdf
# specific heat constant pressure [MJ kg-1 Celsius-1]
c_p = 1.013 * 10.0**(-3)
# atmospheric pressure at 700m elevation [KPa]
# source: http://www.fao.org/docrep/X0490E/x0490e07.htm
# source: Water Evaluation And Planning System, user guide, page 17, https://www.sei.org/projects-and-tools/tools/weap/
# elevation of the model [m]
elevation = 700
P = 101.3 * ((293 - 0.0065 * elevation)/293)**5.26
# ratio of molecular weight of water vapor to dry air [0.622]
epsilon = 0.622
# latent heat of water vaporization [MJ kg-1]
# source: https://en.wikipedia.org/wiki/Latent_heat
# lambda_ = 2.2264705
# this source gives a different number 2.45, :http://www.fao.org/docrep/X0490E/x0490e07.htm
# source: Water Evaluation And Planning System, user guide, page 17, https://www.sei.org/projects-and-tools/tools/weap/
lambda_ = 2.45
# Specific heat of dry air [J kg-1 K-1]
C_p = 1010.0
# the density of air [kg m-3]
rho = 1.204
# the soild flux [W m-2]. It was assumed this value is zero due to the significantly small impact to the model and difficulty of estimation
F = 0.0
################## constnats for Q_e, latent heat transfer by plant transpiration end #######################
|
{"/OPVFilm.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/ShadingCurtain.py"], "/CropElectricityYieldProfitMINLP.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelS_Pearson1997.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/PlantGrowthModelS_Pearson1997Constant.py", "/Lettuce.py"], "/GreenhouseEnergyBalanceConstant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/Util.py": ["/CropElectricityYeildSimulatorConstant.py"], "/SolarIrradianceMultiSpanRoof.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/GreenhouseEnergyBalance.py": ["/Lettuce.py", "/CropElectricityYeildSimulatorConstant.py", "/GreenhouseEnergyBalanceConstant.py", "/Util.py"], "/SimulatorMain.py": ["/CropElectricityYeildSimulator1.py", "/Util.py", "/CropElectricityYeildSimulatorConstant.py"], "/CropElectricityYieldProfitRLShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/ShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelValidation.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulator1.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulatorDetail.py": ["/ShadingCurtain.py", "/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/Lettuce.py", "/PlantGrowthModelS_Pearson1997.py", "/SolarIrradianceMultiSpanRoof.py", "/GreenhouseEnergyBalance.py"], "/PlantGrowthModelS_Pearson1997Constant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/SimulatorClass.py": ["/CropElectricityYeildSimulatorConstant.py"], "/Lettuce.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/plantGrowthModelE_J_VanHenten.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py"]}
|
8,659
|
kensaku-okada/Greenhouse-with-OPV-film-Model
|
refs/heads/master
|
/Util.py
|
# -*- coding: utf-8 -*-
#######################################################
# author :Kensaku Okada [kensakuokada@email.arizona.edu]
# create date : 12 Dec 2016
# last edit date: 14 Dec 2016
#######################################################
##########import package files##########
from scipy import stats
import datetime
import calendar
from textwrap import wrap
import os as os
import numpy as np
import matplotlib.pyplot as plt
# from sklearn import datasets
import math
import CropElectricityYeildSimulatorConstant as constant
import csv
import random
import glob
#######################################################
def flipCoin( p ):
'''
:param p:0.0 to 1.0
:return:
'''
r = random.random()
return r < p
def getStartDateDateType():
'''
return the start date as date type
:return:
'''
return datetime.date(int(constant.SimulationStartDate[0:4]), int(constant.SimulationStartDate[4:6]), int(constant.SimulationStartDate[6:8]))
def getEndDateDateType():
'''
return the end date as date type
:return:
'''
return datetime.date(int(constant.SimulationEndDate[0:4]), int(constant.SimulationEndDate[4:6]), int(constant.SimulationEndDate[6:8]))
def getSimulationDaysInt():
'''
calculate the simulation days.
:return: simulationDaysInt
'''
# get start date and end date of simulation from constant class as String
startDateDateType = getStartDateDateType()
# print "type(startDateDateType):{}".format(type(startDateDateType))
# print "startDateDateType:{}".format(startDateDateType)
endDateDateType = getEndDateDateType()
# print "endDateDateType:{}".format(endDateDateType)
# print "int(constant.SimulationEndDate[0:4]):{}".format(int(constant.SimulationEndDate[0:4]))
# print "int(constant.SimulationEndDate[5:6]):{}".format(int(constant.SimulationEndDate[4:6]))
# print "int(constant.SimulationEndDate[7:8]):{}".format(int(constant.SimulationEndDate[6:8]))
simulationDays = endDateDateType - startDateDateType
# print "simulationDays:{}".format(simulationDays)
# print "type(simulationDays):{}".format(type(simulationDays))
# convert the data type
simulationDaysInt = simulationDays.days + 1
# print "simulationDaysInt:{}".format(simulationDaysInt)
# print "type(simulationDaysInt):{}".format(type(simulationDaysInt))
return simulationDaysInt
def calcSimulationDaysInt():
'''
calculate the simulation days.
:return: simulationDaysInt
'''
# get start date and end date of simulation from constant class as String
startDateDateType = getStartDateDateType()
# print "type(startDateDateType):{}".format(type(startDateDateType))
# print "startDateDateType:{}".format(startDateDateType)
endDateDateType = getEndDateDateType()
# print "endDateDateType:{}".format(endDateDateType)
# print "int(constant.SimulationEndDate[0:4]):{}".format(int(constant.SimulationEndDate[0:4]))
# print "int(constant.SimulationEndDate[5:6]):{}".format(int(constant.SimulationEndDate[4:6]))
# print "int(constant.SimulationEndDate[7:8]):{}".format(int(constant.SimulationEndDate[6:8]))
simulationDays = endDateDateType - startDateDateType
# print "simulationDays:{}".format(simulationDays)
# print "type(simulationDays):{}".format(type(simulationDays))
# convert the data type
simulationDaysInt = simulationDays.days + 1
# print "simulationDaysInt:{}".format(simulationDaysInt)
# print "type(simulationDaysInt):{}".format(type(simulationDaysInt))
return simulationDaysInt
def getSimulationMonthsInt():
# get start date and end date of simulation from constant class as String
startDateDateType = getStartDateDateType()
# print "type(startDateDateType):{}".format(type(startDateDateType))
# print "startDateDateType:{}".format(startDateDateType)
endDateDateType = getEndDateDateType()
return (endDateDateType.year - startDateDateType.year)*12 + endDateDateType.month - startDateDateType.month + 1
def getDaysFirstMonth():
startDate = getStartDateDateType()
_, daysFirstMonth = calendar.monthrange(startDate.year, startDate.month)
# print "month_day:{}".format(month_day)
return daysFirstMonth
def getDaysLastMonth():
lastDate = getEndDateDateType()
_, daysLastMonth = calendar.monthrange(lastDate.year, lastDate.month)
# print "month_day:{}".format(month_day)
return daysLastMonth
def getDaysFirstMonthForGivenPeriod():
daysFirstMonth = getDaysFirstMonth()
startDate = getStartDateDateType()
days = startDate.day
# print "day:{}".format(day)
# print "type(day):{}".format(type(day))
daysFirstMonthForGivenPeriod = daysFirstMonth - days + 1
return daysFirstMonthForGivenPeriod
def getNumOfDaysFromJan1st(date):
jan1stdate = datetime.date(date.year, 1, 1)
daysFromJan1st = date - jan1stdate
return daysFromJan1st.days
def getOnly15thDay(hourlySolarradiation):
# print (hourlySolarradiation.shape)
# print (type(hourlySolarradiation.shape))
# hourlySolarradiationOnly15th = np.array([])
hourlySolarradiationOnly15th = []
date = datetime.datetime(getStartDateDateType().year, getStartDateDateType().month, getStartDateDateType().day)
for i in range (0, hourlySolarradiation.shape[0]):
# print (date.day)
if date.day == 15:
# np.append(hourlySolarradiationOnly15th, hourlySolarradiation[i])
hourlySolarradiationOnly15th.append(hourlySolarradiation[i])
# hourlySolarradiationOnly15th.append(hourlySolarradiation[i])
# print("hourlySolarradiation[i]:{}".format(hourlySolarradiation[i]))
# print("hourlySolarradiationOnly15th:{}".format(hourlySolarradiationOnly15th))
# set the date object 1 hour ahead.
date += datetime.timedelta(hours=1)
# print ("hourlySolarradiationOnly15th.shape[0]:{}".format(len(hourlySolarradiationOnly15th)))
return hourlySolarradiationOnly15th
def getSummerDays(year):
'''
:param years:
:return:
'''
return datetime.date(year, constant.SummerPeriodEndMM,constant.SummerPeriodEndDD) - datetime.date(year, constant.SummerPeriodStartMM, constant.SummerPeriodStartDD)
def dateFormConversionYyyyMmDdToMnSlashddSlashYyyy(yyyymmdd):
yyyy = yyyymmdd[0:4]
mm = yyyymmdd[4:6]
dd = yyyymmdd[6:8]
mmSlashddSlashyyyy = mm + "/" + dd + "/" + yyyy
return mmSlashddSlashyyyy
def readData(fileName, relativePath = "", skip_header=0, d=','):
'''
retrieve the data from the file named fileName
you may have to modify the path below in other OSs.
in Linux, Mac OS, the partition is "/". In Windows OS, the partition is "\" (backslash).
os.sep means "\" in windows. So the following path is adjusted for Windows OS
param filename: filename
param relativePath: the relative path from "data" folder to the folder where there is a file you want to import
param d: the type of data separator, which s "," by default
return: a numpy.array of the data
'''
# read a file in "data" folder
if relativePath == "":
filePath = os.path.dirname(__file__).replace('/', os.sep) + '\\' + 'data\\' + fileName
print("filePath:{}".format(filePath))
print("os.path.dirname(__file__):{}".format(os.path.dirname(__file__)))
else:
filePath = os.path.dirname(__file__).replace('/', os.sep) + '\\' + 'data\\' + relativePath + '\\' + fileName
# print "filePath:{}".format(filePath)
if skip_header == 0:
return np.genfromtxt(filePath, delimiter=d, dtype=None)
else:
return np.genfromtxt(filePath, delimiter=d, dtype=None, skip_header=skip_header)
def exportCSVFile(dataMatrix, fileName="exportFile", relativePath=""):
'''
export dataMatrix
:param dataMatrix:
:param path:
:param fileName:
:return: None
'''
# print (dataMatrix)
currentDir = os.getcwd()
# change the directory to export
if relativePath == "":
os.chdir(currentDir + "/exportData")
else:
os.chdir(currentDir + relativePath)
# print "os.getcwd():{}".format(os.getcwd())
f = open(fileName + ".csv", 'w') # open the file with writing mode
csvWriter = csv.writer(f, lineterminator="\n")
# print "dataMatrix:{}".format(dataMatrix)
for data in dataMatrix:
csvWriter.writerow(data)
f.close() # close the file
# take back the current directory
os.chdir(currentDir)
# print "os.getcwd():{}".format(os.getcwd())
def importDictionaryAsCSVFile(fileName="exportFile", relativePath=""):
'''
import the values of dictionary
:param fileName:
:param relativePath:
:return:
'''
currentDir = os.getcwd()
# print ("currentDir:{}".format(currentDir))
# currentDir = unicode(currentDir, encoding='shift-jis')
# print ("currentDir:{}".format(currentDir))
# change the directory to export
if relativePath == "":
os.chdir(currentDir + "/exportData")
else:
os.chdir(currentDir + relativePath)
dict = Counter()
for key, val in csv.reader(open(fileName+".csv")):
dict[key] = val
# take back the current directory
os.chdir(currentDir)
# print "os.getcwd():{}".format(os.getcwd())
return dict
def exportDictionaryAsCSVFile(dictionary, fileName="exportFile", relativePath=""):
'''
export the values of dictionary
:param dictionary:
:param fileName:
:param relativePath:
:return:
'''
currentDir = os.getcwd()
# change the directory to export
if relativePath == "":
os.chdir(currentDir + "/exportData")
else:
os.chdir(currentDir + relativePath)
# print ("dictionary:{}".format(dictionary))
w = csv.writer(open(fileName + ".csv", "w"))
for key, val in dictionary.items():
w.writerow([key, val])
# take back the current directory
os.chdir(currentDir)
# print "os.getcwd():{}".format(os.getcwd())
def getArraysFromData(fileName, simulatorClass):
'''
read data from a file, process the data and return them as arrays
:param fileName: String
:return:
'''
# get the simulation days set in the constant class
simulationDaysInt = calcSimulationDaysInt()
# print "simulationDaysInt:{}".format(simulationDaysInt)
# get start date and end date of simulation from constant class as String
startDateDateType = getStartDateDateType()
# print "startDateDateType:{}".format(startDateDateType)
# print "type(startDateDateType):{}".format(type(startDateDateType))
endDateDateType = getEndDateDateType()
# if there are dates where there are any missing lines, skip the date and subtract the number from the simulation days
trueSimulationDaysInt = simulationDaysInt
missingDates = np.array([])
# automatically changes its length dependent on the amoutn of imported data
year = np.zeros(simulationDaysInt * constant.hourperDay, dtype=np.int)
# print "year.shape:{}".format(year.shape)
month = np.zeros(simulationDaysInt * constant.hourperDay, dtype=np.int)
# print "month:{}".format(month.shape)
day = np.zeros(simulationDaysInt * constant.hourperDay, dtype=np.int)
hour = np.zeros(simulationDaysInt * constant.hourperDay, dtype=np.int)
# dates = np.chararray(simulationDaysInt * constant.hourperDay)
dates = [""] * (simulationDaysInt * constant.hourperDay)
# print "dates:{}".format(dates)
# [W/m^2]
hourlyHorizontalDiffuseOuterSolarIrradiance = np.zeros(simulationDaysInt * constant.hourperDay)
# [W/m^2]
hourlyHorizontalTotalOuterSolarIrradiance = np.zeros(simulationDaysInt * constant.hourperDay)
# [W/m^2]
hourlyHorizontalDirectOuterSolarIrradiance = np.zeros(simulationDaysInt * constant.hourperDay)
# [deg C]
hourlyHorizontalTotalBeamMeterBodyTemperature = np.zeros(simulationDaysInt * constant.hourperDay)
# [deg C]
hourlyHorizonalDirectBeamMeterBodyTemperature = np.zeros(simulationDaysInt * constant.hourperDay)
# [deg C]
hourlyAirTemperature = np.zeros(simulationDaysInt * constant.hourperDay)
# [%]
hourlyRelativeHumidity = np.zeros(simulationDaysInt * constant.hourperDay)
# import the file removing the header
fileData = readData(fileName, relativePath="", skip_header=1)
# print "fileData:{}".format(fileData)
# print "fileData.shape:{}".format(fileData.shape)
# change the date format
simulationStartDate = dateFormConversionYyyyMmDdToMnSlashddSlashYyyy(constant.SimulationStartDate)
simulationEndDate = dateFormConversionYyyyMmDdToMnSlashddSlashYyyy(constant.SimulationEndDate)
# print ("simulationStartDate:{}".format(simulationStartDate))
# print ("simulationEndDate:{}".format(simulationEndDate))
# print ("fileData.shape:{}".format(fileData.shape))
########## store the imported data to lists
# index for data storing
index = 0
for hourlyData in fileData:
# for day in range(0, simulationDaysInt):
# print"hourlyData:{}".format(hourlyData)
dateList = hourlyData[0].split("/")
# print "dateList:{}".format(dateList)
# print "month:{}".format(month)
# print "day:{}".format(day)
# exclude the data out of the set start date and end date
if datetime.date(int(dateList[2]), int(dateList[0]), int(dateList[1])) < startDateDateType or \
datetime.date(int(dateList[2]), int(dateList[0]), int(dateList[1])) > endDateDateType:
continue
# print "datetime.date(int(dateList[2]), int(dateList[0]), int(dateList[1])):{}".format(datetime.date(int(dateList[2]), int(dateList[0]), int(dateList[1])))
# print "startDateDateType:{}".format(startDateDateType)
# print "endDateDateType:{}".format(endDateDateType)
year[index] = int(dateList[2])
month[index] = int(dateList[0])
day[index] = int(dateList[1])
hour[index] = hourlyData[1]
dates[index] = hourlyData[0]
# print "hourlyData[0]:{}".format(hourlyData[0])
# print "dates:{}".format(dates)
# print "index:{}, year:{}, hour[index]:{}".format(index, year, hour)
# print "hourlyData[0]:{}".format(hourlyData[0])
# print "year[index]:{}".format(year[index])
# [W/m^2]
hourlyHorizontalDiffuseOuterSolarIrradiance[index] = hourlyData[4]
# [W/m^2]
hourlyHorizontalTotalOuterSolarIrradiance[index] = hourlyData[2]
# the direct beam solar radiation is not directly got from the file, need to calculate from "the total irradiance - the diffuse irradiance"
# [W/m^2]
hourlyHorizontalDirectOuterSolarIrradiance[index] = hourlyHorizontalTotalOuterSolarIrradiance[index] \
- hourlyHorizontalDiffuseOuterSolarIrradiance[index]
# unit: [celusis]
hourlyHorizontalTotalBeamMeterBodyTemperature[index] = hourlyData[7]
# unit: [celusis]
hourlyHorizonalDirectBeamMeterBodyTemperature[index] = hourlyData[8]
# unit: [celusis]
hourlyAirTemperature[index] = hourlyData[5]
# print "hourlyAirTemperature:{}".format(hourlyAirTemperature)
# unit: [-] <- [%]
hourlyRelativeHumidity = hourlyData[6] * 0.01
# print "hour[index] - hour[index-1]:{}".format(hourlyData[1] - hour[index-1])
# print "year[index]:{}, month[index]:{}, day[index]:{}, hour[index]:{}".format(year[index], month[index], day[index], hour[index])
# print "year[index]:{}, month[index]:{}, day[index]:{}, hour[index]:{}".format(year[index-1], month[index-1], day[index-1], hour[index-1])
# print "datetime.datetime(year[index], month[index], day[index], hour = hour[index]):{}".format(datetime.datetime(year[index], month[index], day[index], hour = hour[index]))
# print "datetime.datetime(year[index-1], month[index-1], day[index-1]),hour = hour[index-1]:{}".format(datetime.datetime(year[index-1], month[index-1], day[index-1],hour = hour[index-1]))
# if index <> 0 and datetime.timedelta(hours=1) <> datetime.datetime(year[index], month[index], day[index], hour = hour[index]) - \
# datetime.datetime(year[index-1], month[index-1], day[index-1], hour = hour[index-1]):
# missingDates = np.append(missingDates, hourlyData)
index += 1
# print "year:{}".format(year)
# print "month:{}".format(month)
# print "day:{}".format(day)
# print "hour:{}".format(hour)
# print "hourlyHorizontalTotalOuterSolarIrradiance:{}".format(hourlyHorizontalTotalOuterSolarIrradiance)
# print "hourlyHorizontalTotalBeamMeterBodyTemperature:{}".format(hourlyHorizontalTotalBeamMeterBodyTemperature)
# print "hourlyHorizontalDirectOuterSolarIrradiance:{}".format(hourlyHorizontalDirectOuterSolarIrradiance)
# print "hourlyHorizonalDirectBeamMeterBodyTemperature.shape:{}".format(hourlyHorizonalDirectBeamMeterBodyTemperature.shape)
# print "hourlyAirTemperature:{}".format(hourlyAirTemperature)
# print "hourlyAirTemperature.shape:{}".format(hourlyAirTemperature.shape)
# set the values to the object
simulatorClass.setYear(year)
simulatorClass.setMonth(month)
simulatorClass.setDay(day)
simulatorClass.setHour(hour)
simulatorClass.setImportedHourlyHorizontalDirectSolarRadiation(hourlyHorizontalDirectOuterSolarIrradiance)
simulatorClass.setImportedHourlyHorizontalDiffuseSolarRadiation(hourlyHorizontalDiffuseOuterSolarIrradiance)
simulatorClass.setImportedHourlyHorizontalTotalBeamMeterBodyTemperature(hourlyHorizontalTotalBeamMeterBodyTemperature)
simulatorClass.setImportedHourlyAirTemperature(hourlyAirTemperature)
simulatorClass.hourlyRelativeHumidity = hourlyRelativeHumidity
##########file import (TucsonHourlyOuterEinvironmentData) end##########
return year, month, day, hour, hourlyHorizontalDiffuseOuterSolarIrradiance, \
hourlyHorizontalTotalOuterSolarIrradiance, \
hourlyHorizontalDirectOuterSolarIrradiance, \
hourlyHorizontalTotalBeamMeterBodyTemperature, \
hourlyAirTemperature
def deriveOtherArraysFromImportedData(simulatorClass):
# Other data can be added in the future
# set the the flag indicating daytime or nighttime
hourlyHorizontalDirectOuterSolarIrradiance = simulatorClass.getImportedHourlyHorizontalDirectSolarRadiation()
hourlyDayOrNightFlag = np.array([constant.daytime if i > 0.0 else constant.nighttime for i in hourlyHorizontalDirectOuterSolarIrradiance])
simulatorClass.hourlyDayOrNightFlag = hourlyDayOrNightFlag
def convertFromJouleToWattHour(joule):
'''
[J] == [W*sec] -> [W*hour]
:param joule:
:return:
'''
return joule / constant.minuteperHour /constant.secondperMinute
def convertWattPerSquareMeterEachHourToJoulePerSaureMeterEachDay(hourlySolarIrradiance):
'''
Unit conversion: [average W / m^2 each hour] -> [J / m^2 each day]
'''
# convert W / m^2 (= J/(s * m^2)) into J/(hour * m^2)
SolarRadiantEnergyPerHour = hourlySolarIrradiance * constant.secondperMinute * constant.minuteperHour
dailySolarEnergy = np.zeros(int(SolarRadiantEnergyPerHour.shape[0]/constant.hourperDay))
for i in range (0, dailySolarEnergy.shape[0]):
dailySolarEnergy[i] = sum(SolarRadiantEnergyPerHour[i*constant.hourperDay : (i+1)*constant.hourperDay])
return dailySolarEnergy
def convertFromgramTokilogram(weightg):
'''
convert the unit from g to kg
param: weightg, weight (g)
return: weight(kg)
'''
return weightg/1000.0
def convertWhTokWh(electricityYield):
'''
convert the unit from Wh to kWh
:param electricityYieldkW:
:return:
'''
return electricityYield / 1000.0
def convertFromMJperHourSquareMeterToWattperSecSquareMeter(MJperSquareMeter):
'''
change the unit of light intensity from MJ/hour/m^2 to Watt/sec/m^2 (unit of light energy in terms of energy),
which is for OPV electricity generation
param: MJperSquareMeter (MJ/hour/m^2)
return: (Watt/m^2) = (J/sec/m^2)
'''
return MJperSquareMeter *10.0**6 / 60.0 / 60.0
def convertFromHourlyPPFDWholeDayToDLI(hourlyPPFDWholePeriod):
'''
[umol m^-2 s^-1] -> [mol m^-2 day^-1]
:param hourlyPPFDWholePeriod:
:return:DLI
'''
DLIWholePeriod = np.zeros(calcSimulationDaysInt())
# convert the unit: [umol m^-2 s^-1] -> [umol m^-2 day^-1]
for day in range (0, calcSimulationDaysInt()):
for hour in range(0, hourlyPPFDWholePeriod.shape[0]/calcSimulationDaysInt()):
DLIWholePeriod[day] += hourlyPPFDWholePeriod[day * constant.hourperDay + hour] * constant.secondperMinute * constant.minuteperHour
# convert the unit: [umol m^-2 day^-1] -> [mol m^-2 day^-1]
DLIWholePeriod = DLIWholePeriod / float(10**6)
# print "DLIWholePeriod:{}".format(DLIWholePeriod)
return DLIWholePeriod
# def convertFromJouleperDayperAreaToWattper(hourlyPPFDWholePeriod):
# '''
# [umol m^-2 s^-1] -> [mol m^-2 day^-1]
# :param hourlyPPFDWholePeriod:
# :return:DLI
# '''
# DLIWholePeriod = np.zeros(calcSimulationDaysInt())
#
# # convert the unit: [umol m^-2 s^-1] -> [umol m^-2 day^-1]
# for day in range (0, calcSimulationDaysInt()):
# for hour in range(0, hourlyPPFDWholePeriod.shape[0]/calcSimulationDaysInt()):
# DLIWholePeriod[day] += hourlyPPFDWholePeriod[day * constant.hourperDay + hour] * constant.secondperMinute * constant.minuteperHour
#
# # convert the unit: [umol m^-2 day^-1] -> [mol m^-2 day^-1]
# DLIWholePeriod = DLIWholePeriod / float(10**6)
# # print "DLIWholePeriod:{}".format(DLIWholePeriod)
# return DLIWholePeriod
def convertFromWattperSecSquareMeterToPPFD(WattperSquareMeter):
'''
change the unit of light intensity from MJ/m^2 to μmol/m^2/s (unit of PPFD in terms of photon desnity for photosynthesis),
which is for photosynthesis plant production
source of the coefficient
http://www.apogeeinstruments.com/conversion-ppf-to-watts/ : 1/0.219 = 4.57
http://www.egc.com/useful_info_lighting.php: 1/0.327 = 3.058103976
param: WattperSecSquare (Watt/m^2) = (J/sec/m^2)
return: (μmol/m^2/s in solar radiation)
'''
return WattperSquareMeter * constant.wattToPPFDConversionRatio
def convertUnitShootFreshMassToShootFreshMassperArea(shootFreshMassList):
'''
:return:
'''
# unit convert [g/head] -> [g/m^2]
shootFreshMassListPerCultivationFloorArea = shootFreshMassList * constant.plantDensity
return shootFreshMassListPerCultivationFloorArea
def convertcwtToKg(cwt):
# unit convert [cwt] -> [kg]
return cwt * constant.kgpercwt
def convertHourlyTemperatureToDailyAverageTemperature(hourlyTemperature):
'''
Unit conversion: [g/head] -> [g/m^2]
'''
dailyAverageTemperature = np.zeros(int(hourlyTemperature.shape[0]/constant.hourperDay))
for i in range (0, hourlyTemperature.shape[0]):
dailyAverageTemperature[i] = np.average(hourlyTemperature[i*constant.hourperDay : (i+1)*constant.hourperDay])
return dailyAverageTemperature
def convertPoundToKg(pound):
return pound / (1.0 / 0.45359237)
def convertKgToPound(kg):
return kg * (1.0 / 0.45359237)
def saveFigure (filename):
'''
save the figure with given file name at the curent directory
param: filename: file name
return: :
'''
# (relative to your python current working directory)
path = os.path.dirname(__file__).replace('/', os.sep)
os.chdir(path)
figure_path = './exportData/'
# figure_path = '../'
# set to True in order to automatically save the generated plots
filename = '{}'.format(filename)
# print "figure_path + filename:{}".format(figure_path + filename)
plt.savefig(figure_path + filename)
def plotMultipleData(x, yList, yLabelList, title = "data", xAxisLabel = "x", yAxisLabel = "y", yMin = None, yMax = None):
'''
Plot single input feature x data with multiple corresponding response values a scatter plot
:param x:
:param yList:
:param yLabelList:
:param title:
:param xAxisLabel:
:param yAxisLabe:
:return: None
'''
fig = plt.figure() # Create a new figure object for plotting
ax = fig.add_subplot(111)
markerList = np.array([",", "o", "v", "^", "<", ">", "1", "2", "3", "4", "8", "s", "p", "*", "h", "H", "+", "x", "D", "d",])
markerList = markerList[ 0 : yLabelList.shape[0] ]
# load iris data
# iris = datasets.load_iris()
for i in range (0, yList.shape[0]):
# plt.scatter(x, yList[i], plt.cm.hot(float(i) / yList.shape[0]), color=plt.cm.hot(float(i) / yList.shape[0]), marker='o', label = yLabelList[i])
# for color print
plt.scatter(x, yList[i], s=8, color=plt.cm.hot(float(i) / yList.shape[0]), marker='o', label=yLabelList[i])
# for monochrome print
# plt.scatter(x, yList[i], s=8, color= str(float(i) / yList.shape[0]*0.80), marker=markerList[i], label=yLabelList[i])
# add explanatory note
plt.legend()
# add labels to each axis
plt.xlabel(xAxisLabel)
plt.ylabel(yAxisLabel)
# add title
plt.title(title)
if yMin is not None:
plt.ylim(ymin = yMin)
if yMax is not None:
plt.ylim(ymax = yMax)
# ax.set_title("\n".join(wrap(title + "OPVPricePerArea: " + str(OPVPricePerAreaUSD), 60)))
plt.pause(.1) # required on some systems so that rendering can happen
def plotData(x, t, title = "data", xAxisLabel = "x", yAxisLabel = "t", OPVPricePerAreaUSD = constant.OPVPricePerAreaUSD, arbitraryRegressionLine = False, \
coeff0 = 0.0, coeff1 = 0.0, coeff2 = 0.0, coeff3 = 0.0, coeff4 = 0.0, coeff5 = 0.0):
"""
Plot single input feature x data with corresponding response
values t as a scatter plot
:param x: sequence of 1-dimensional input data features
:param t: sequence of 1-dimensional responses
:param title: the title of the plot
:param xAxisLabel: x-axix label of the plot
:param xAxisLabel: y-axix label of the plot
;OPVPricePerAreaUSD: the OPV Price Per Area (USD/m^2)
:return: None
"""
#print "x:{}".format(x)
#print "t:{}".format(t)
#ax.ticklabel_format(style='plain',axis='y')
fig = plt.figure() # Create a new figure object for plotting
ax = fig.add_subplot(111)
plt.scatter(x, t, edgecolor='b', color='w', s = 8, marker='o')
plt.xlabel(xAxisLabel)
plt.ylabel(yAxisLabel)
#plt.title(title + "OPVPricePerArea: " + OPVPricePerAreaUSD)
plt.title(title)
# add the OPV price per area [USD/m^2]
# ax.set_title("\n".join(wrap(title + " (OPVPricePerArea: " + str(OPVPricePerAreaUSD)+"[USD/m^2])", 60)))
if arbitraryRegressionLine:
xLine = np.linspace(0, np.max(x), 100)
y = coeff0 + coeff1 * xLine + coeff2 * xLine**2 + coeff3 * xLine**3 + coeff4 * xLine**4 + coeff5 * xLine**5
plt.plot(xLine, y)
plt.pause(.1) # required on some systems so that rendering can happen
def plotTwoData(x, y1, y2, title = "data", xAxisLabel = "x", yAxisLabel = "t", y1Label = "data1", y2Label = "data2"):
'''
Plot single input feature x data with two corresponding response values y1 and y2 as a scatter plot
:param x:
:param y1:
:param y2:
:param title:
:param xAxisLabel:
:param yAxisLabel:
:return: None
'''
fig = plt.figure() # Create a new figure object for plotting
ax = fig.add_subplot(111)
# for color printing
plt.scatter(x, y1, edgecolor='red', color='red', s = 8, marker='o', label = y1Label)
plt.scatter(x, y2, edgecolor='blue', color='blue', s = 8, marker='o', label = y2Label)
# for monochrome printing
# plt.scatter(x, y1, edgecolor='0.1', color='0.1', s = 8, marker='o', label = y1Label)
# plt.scatter(x, y2, edgecolor='0.7', color='0.8', s = 8, marker='x', label = y2Label)
plt.legend()
plt.xlabel(xAxisLabel)
plt.ylabel(yAxisLabel)
plt.title(title)
# ax.set_title("\n".join(wrap(title + "OPVPricePerArea: " + str(OPVPricePerAreaUSD), 60)))
plt.pause(.1) # required on some systems so that rendering can happen
def plotTwoDataMultipleYaxes(x, y1, y2, title, xAxisLabel, yAxisLabel1, yAxisLabel2, yLabel1, yLabel2):
'''
:param OPVCoverageList:
:param unitDailyFreshWeightIncreaseList:
:param electricityYield:
:param title:
:param xAxisLabel:
:param yAxisLabel1:
:param yAxisLabel2:
:param yLabel1:
:param yLabel2:
:return:
'''
# Create a new figure object for plotting
# fig = plt.figure()
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
# for color printing
ax1.scatter(x, y1, edgecolor='red', color='red', s = 8, marker='o', label = yLabel1)
ax2.scatter(x, y2, edgecolor='blue', color='blue', s = 8, marker='o', label = yLabel2)
# for monochrome printing
# ax1.scatter(x, y1, edgecolor='0.1', color='0.1', s = 8, marker='o', label = yLabel1)
# ax2.scatter(x, y2, edgecolor='0.7', color='0.8', s = 8, marker='x', label = yLabel2)
# add the explanatory note
ax1.legend()
ax2.legend()
ax1.set_xlabel(xAxisLabel)
ax1.set_ylabel(yAxisLabel1)
ax2.set_ylabel(yAxisLabel2)
plt.title(title)
# ax.set_title("\n".join(wrap(title + "OPVPricePerArea: " + str(OPVPricePerAreaUSD), 60)))
plt.pause(.1) # required on some systems so that rendering can happen
def plotCvResults(cv_loss, train_loss, cv_loss_title, figw=800, figh=420, mydpi=96, filepath=None, ylbl='Log Loss'):
plt.figure(figsize=(figw / mydpi, figh / mydpi), dpi=mydpi)
print ('>>>>> cv_loss.shape', cv_loss.shape)
x = np.arange(0, cv_loss.shape[0])
# cv_loss = np.mean(cv_loss, 0)
# train_loss = np.mean(train_loss, 0)
# put y-axis on same scale for all plots
min_ylim = min(list(cv_loss) + list(train_loss))
min_ylim = int(np.floor(min_ylim))
max_ylim = max(list(cv_loss) + list(train_loss))
max_ylim = int(np.ceil(max_ylim))
print ('min_ylim={0}, max_ylim={1}'.format(min_ylim, max_ylim))
plt.subplot(121)
plt.plot(x, cv_loss, linewidth=2)
plt.xlabel('Model Order')
plt.ylabel(ylbl)
plt.title(cv_loss_title)
plt.pause(.1) # required on some systems so that rendering can happen
plt.ylim(min_ylim, max_ylim)
plt.subplot(122)
plt.plot(x, train_loss, linewidth=2)
plt.xlabel('Model Order')
plt.ylabel(ylbl)
plt.title('Train Loss')
plt.pause(.1) # required on some systems so that rendering can happen
plt.ylim(min_ylim, max_ylim)
plt.subplots_adjust(right=0.95, wspace=0.25, bottom=0.2)
plt.draw()
if filepath:
# plt.savefig(filepath, format='pdf')
# print ("filepath:{}".format(filepath))
plt.savefig(filepath)
def plotDataAndModel(x, y, w, title='Plot of data + appx curve (green curve)',filepath=None):
plotDataSimple(x, y)
plt.title(title + "_" + str(len(w)-1) + "th_order")
plotModel(x, w, color='g')
if filepath:
plt.savefig(filepath, format='png')
def plotDataSimple(x, y):
"""
Plot single input feature x data with corresponding response
values y as a scatter plot
:param x: sequence of 1-dimensional input data features
:param y: sequence of 1-dimensional responses
:return: None
"""
plt.figure() # Create a new figure object for plotting
plt.scatter(x, y, edgecolor='b', color='w', s = 8, marker='o')
plt.xlabel('x')
plt.ylabel('y')
plt.xlim (min(x)*0.98, max(x)*1.02)
plt.ylim (min(y)*0.98, max(y)*1.02)
plt.title('Data')
plt.pause(.1) # required on some systems so that rendering can happen
def plotModel(x, w, color='r'):
"""
Plot the curve for an n-th order polynomial model:
t = w0*x^0 + w1*x^1 + w2*x^2 + ... wn*x^n
This works by creating a set of x-axis (plotx) points and
then use the model parameters w to determine the corresponding
t-axis (plott) points on the model curve.
:param x: sequence of 1-dimensional input data features
:param w: n-dimensional sequence of model parameters: w0, w1, w2, ..., wn
:param color: matplotlib color to plot model curve
:return: the plotx and plott values for the plotted curve
"""
# NOTE: this assumes a figure() object has already been created.
plotx = np.linspace(min(x) - 0.25, max(x) + 0.25, 100)
plotX = np.zeros((plotx.shape[0], w.size))
for k in range(w.size):
plotX[:, k] = np.power(plotx, k)
plott = np.dot(plotX, w)
plt.plot(plotx, plott, color=color, markersize = 10, linewidth=2)
plt.pause(.1) # required on some systems so that rendering can happen
return plotx, plott
def sigma(m, n, func, s=0):
'''
calculate the summation for a given function.
Reference: https://qiita.com/SheepCloud/items/b8bd929c4f35dfd7b1bd
:param m: initial index
:param n: final index. The term with the final index is calculated
:param func: the function
:param s: the default value before summing f(m). this is usually 0.0
:return:
'''
# print("m:{}, n:{}, s:{}".format(m, n, s))
if m > n: return s
return sigma(m + 1, n, func, s + func(m))
class Counter(dict):
"""
A counter keeps track of counts for a set of keys.
The counter class is an extension of the standard python
dictionary type. It is specialized to have number values
(integers or floats), and includes a handful of additional
functions to ease the task of counting data. In particular,
all keys are defaulted to have value 0. Using a dictionary:
a = {}
print a['test']
would give an error, while the Counter class analogue:
>>> a = Counter()
>>> print a['test']
0
returns the default 0 value. Note that to reference a key
that you know is contained in the counter,
you can still use the dictionary syntax:
>>> a = Counter()
>>> a['test'] = 2
>>> print a['test']
2
This is very useful for counting things without initializing their counts,
see for example:
>>> a['blah'] += 1
>>> print a['blah']
1
The counter also includes additional functionality useful in implementing
the classifiers for this assignment. Two counters can be added,
subtracted or multiplied together. See below for details. They can
also be normalized and their total count and arg max can be extracted.
"""
def __getitem__(self, idx):
self.setdefault(idx, 0)
return dict.__getitem__(self, idx)
def incrementAll(self, keys, count):
"""
Increments all elements of keys by the same count.
>>> a = Counter()
>>> a.incrementAll(['one','two', 'three'], 1)
>>> a['one']
1
>>> a['two']
1
"""
for key in keys:
self[key] += count
def argMax(self):
"""
Returns the key with the highest value.
"""
if len(self.keys()) == 0: return None
all = self.items()
values = [x[1] for x in all]
maxIndex = values.index(max(values))
return all[maxIndex][0]
def sortedKeys(self):
"""
Returns a list of keys sorted by their values. Keys
with the highest values will appear first.
>>> a = Counter()
>>> a['first'] = -2
>>> a['second'] = 4
>>> a['third'] = 1
>>> a.sortedKeys()
['second', 'third', 'first']
"""
sortedItems = self.items()
compare = lambda x, y: sign(y[1] - x[1])
sortedItems.sort(cmp=compare)
return [x[0] for x in sortedItems]
def totalCount(self):
"""
Returns the sum of counts for all keys.
"""
return sum(self.values())
def normalize(self):
"""
Edits the counter such that the total count of all
keys sums to 1. The ratio of counts for all keys
will remain the same. Note that normalizing an empty
Counter will result in an error.
"""
total = float(self.totalCount())
if total == 0: return
for key in self.keys():
self[key] = self[key] / total
def divideAll(self, divisor):
"""
Divides all counts by divisor
"""
divisor = float(divisor)
for key in self:
self[key] /= divisor
def copy(self):
"""
Returns a copy of the counter
"""
return Counter(dict.copy(self))
def __mul__(self, y):
"""
Multiplying two counters gives the dot product of their vectors where
each unique label is a vector element.
>>> a = Counter()
>>> b = Counter()
>>> a['first'] = -2
>>> a['second'] = 4
>>> b['first'] = 3
>>> b['second'] = 5
>>> a['third'] = 1.5
>>> a['fourth'] = 2.5
>>> a * b
14
"""
sum = 0
x = self
if len(x) > len(y):
x, y = y, x
for key in x:
if key not in y:
continue
sum += x[key] * y[key]
return sum
def __radd__(self, y):
"""
Adding another counter to a counter increments the current counter
by the values stored in the second counter.
>>> a = Counter()
>>> b = Counter()
>>> a['first'] = -2
>>> a['second'] = 4
>>> b['first'] = 3
>>> b['third'] = 1
>>> a += b
>>> a['first']
1
"""
for key, value in y.items():
self[key] += value
def __add__(self, y):
"""
Adding two counters gives a counter with the union of all keys and
counts of the second added to counts of the first.
>>> a = Counter()
>>> b = Counter()
>>> a['first'] = -2
>>> a['second'] = 4
>>> b['first'] = 3
>>> b['third'] = 1
>>> (a + b)['first']
1
"""
addend = Counter()
for key in self:
if key in y:
addend[key] = self[key] + y[key]
else:
addend[key] = self[key]
for key in y:
if key in self:
continue
addend[key] = y[key]
return addend
def __sub__(self, y):
"""
Subtracting a counter from another gives a counter with the union of all keys and
counts of the second subtracted from counts of the first.
>>> a = Counter()
>>> b = Counter()
>>> a['first'] = -2
>>> a['second'] = 4
>>> b['first'] = 3
>>> b['third'] = 1
>>> (a - b)['first']
-5
"""
addend = Counter()
for key in self:
if key in y:
addend[key] = self[key] - y[key]
else:
addend[key] = self[key]
for key in y:
if key in self:
continue
addend[key] = -1 * y[key]
return addend
|
{"/OPVFilm.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/ShadingCurtain.py"], "/CropElectricityYieldProfitMINLP.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelS_Pearson1997.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/PlantGrowthModelS_Pearson1997Constant.py", "/Lettuce.py"], "/GreenhouseEnergyBalanceConstant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/Util.py": ["/CropElectricityYeildSimulatorConstant.py"], "/SolarIrradianceMultiSpanRoof.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/GreenhouseEnergyBalance.py": ["/Lettuce.py", "/CropElectricityYeildSimulatorConstant.py", "/GreenhouseEnergyBalanceConstant.py", "/Util.py"], "/SimulatorMain.py": ["/CropElectricityYeildSimulator1.py", "/Util.py", "/CropElectricityYeildSimulatorConstant.py"], "/CropElectricityYieldProfitRLShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/ShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelValidation.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulator1.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulatorDetail.py": ["/ShadingCurtain.py", "/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/Lettuce.py", "/PlantGrowthModelS_Pearson1997.py", "/SolarIrradianceMultiSpanRoof.py", "/GreenhouseEnergyBalance.py"], "/PlantGrowthModelS_Pearson1997Constant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/SimulatorClass.py": ["/CropElectricityYeildSimulatorConstant.py"], "/Lettuce.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/plantGrowthModelE_J_VanHenten.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py"]}
|
8,660
|
kensaku-okada/Greenhouse-with-OPV-film-Model
|
refs/heads/master
|
/SolarIrradianceMultiSpanRoof.py
|
# -*- coding: utf-8 -*-
##########import package files##########
from scipy import stats
import sys
import datetime
import os as os
import numpy as np
import matplotlib.pyplot as plt
import math
import CropElectricityYeildSimulatorConstant as constant
import Util as util
#######################################################
def getAngleBetweenIncientRayAndHorizontalAxisPerpendicularToGHSpan(simulatorClass, hourlyModuleAzimuthAngle):
# alpha: solar altitude angle
alpha = simulatorClass.hourlySolarAltitudeAngle
hourlySolarAzimuthAngle = simulatorClass.hourlySolarAzimuthAngle
E = np.arcsin( np.sin(alpha) / np.sqrt(np.sin(alpha)**2 + (np.cos(alpha)*np.cos(hourlyModuleAzimuthAngle - hourlySolarAzimuthAngle))**2))
# It was interpreted that the reference of the model Soriano et al., 2004,"A Study of Direct Solar Radiation transmittance in Asymmetrical Multi-span Greenhouses using Scale Models and Simulation Models"
# need the angle E be expressed less than pi/2, when the solar position changes from east to east side in the sky passing meridian
# By definition, E wants to take more than pi/2 [rad] when the sun moves from east to west, which occurs at noon.
E = np.array([math.pi - E[i] if i!=0 and E[i] > 0.0 and E[i]-E[i-1] < 0.0 else E[i] for i in range (0, E.shape[0])])
return E
def getAngleBetweenIncientRayAndHorizontalAxisParallelToGHSpan(simulatorClass, hourlyModuleAzimuthAngle):
# alpha: solar altitude angle
alpha = simulatorClass.hourlySolarAltitudeAngle
hourlySolarAzimuthAngle = simulatorClass.hourlySolarAzimuthAngle
EParallel = np.arcsin( np.sin(alpha) / np.sqrt(np.sin(alpha)**2 + (np.cos(alpha)*np.sin(hourlyModuleAzimuthAngle - hourlySolarAzimuthAngle))**2))
return EParallel
def getTransmittanceForPerpendicularIrrThroughMultiSpanRoofFacingEastOrNorth(simulatorClass, directSolarRadiationToOPVEastDirection, \
EPerpendicularEastOrNorthFacingRoof):
"""
:param simulatorClass:
:return:
"""
alpha = constant.roofAngleWestOrSouth
beta = constant.roofAngleEastOrNorth
L_1 = constant.greenhouseRoofWidthWestOrSouth
L_2 = constant.greenhouseRoofWidthEastOrNorth
# the transmittance of roof surfaces 1 (facing west or south)
T_1 = np.zeros(directSolarRadiationToOPVEastDirection.shape[0])
# the transmittance of roof surfaces 2 (facing east or north)
T_2 = np.zeros(directSolarRadiationToOPVEastDirection.shape[0])
# the reflectance of roof surfaces 1 (facing west or south)
F_1 = np.zeros(directSolarRadiationToOPVEastDirection.shape[0])
# the reflectance of roof surfaces 2 (facing west or south)
F_2 = np.zeros(directSolarRadiationToOPVEastDirection.shape[0])
# the transmittance/reflectance of solar irradiance directly transmitted to the soil through roof each direction of roof (surfaces east and west) (A10)
T_12 = np.zeros(directSolarRadiationToOPVEastDirection.shape[0])
# the transmittance/reflectance on the roof facing west of solar irradiance reflected by the surface facing west and transmitted to the soil (surfaces west or south)
T_r11 = np.zeros(directSolarRadiationToOPVEastDirection.shape[0])
F_r11 = np.zeros(directSolarRadiationToOPVEastDirection.shape[0])
# the transmittance/reflectance on the roof facing east of solar irradiance reflected by the surface facing west and transmitted to the soil (surfaces east or north)
T_r12 = np.zeros(directSolarRadiationToOPVEastDirection.shape[0])
F_r12 = np.zeros(directSolarRadiationToOPVEastDirection.shape[0])
# transmittance through multispan roof
T_matPerpendicular = np.zeros(directSolarRadiationToOPVEastDirection.shape[0])
# T_matParallel = np.zeros(directSolarRadiationToOPVEastDirection.shape[0])
# print("num of iteration at getTransmittanceForPerpendicularIrrThroughMultiSpanRoofFacingEastOrNorth:{}".format(directSolarRadiationToOPVEastDirection.shape[0]))
##############################################################################################################################
# calculate the transmittance of perpendicular direction from the EAST facing roof after penetrating multi-span roof per hour
##############################################################################################################################
for i in range(0, directSolarRadiationToOPVEastDirection.shape[0]):
# print("i:{}".format(i))
# print("EPerpendicularEastOrNorthFacingRoof[i]:{}".format(EPerpendicularEastOrNorthFacingRoof[i]))
# print("directSolarRadiationToOPVEastDirection[i]:{}".format(directSolarRadiationToOPVEastDirection[i]))
# if the solar irradiance at a certain time is zero, then skip the element
if directSolarRadiationToOPVEastDirection[i] == 0.0: continue
# case A1: if the roof-slope angle of the west side is greater than the angle E formed by the incident ray with the horizontal axis perpendicular to the greenhouse span
# It was assumed the direct solar radiation is 0 when math.pi - alpha <= EPerpendicularEastOrNorthFacingRoof[i]:
elif EPerpendicularEastOrNorthFacingRoof[i] <= alpha:
# print ("call case A1")
# the number of intercepting spans, which can very depending on E.
m = getNumOfInterceptingSPans(alpha, EPerpendicularEastOrNorthFacingRoof[i])
# print("case A1 i:{}, m:{}, sys.getrecursionlimit():{}".format(i, m,sys.getrecursionlimit()))
# fraction (percentage) of light which does not pass through the first span [-]
l_a = m * L_1 * math.sin(alpha + EPerpendicularEastOrNorthFacingRoof[i]) - (m + 1) * L_2 * math.sin(beta - EPerpendicularEastOrNorthFacingRoof[i])
# fraction (percentage) of light which crosses the first span before continuing on towards the others [-]
l_b = m * L_2 * math.sin(beta - EPerpendicularEastOrNorthFacingRoof[i]) - (m - 1) * L_1 * math.sin(alpha + EPerpendicularEastOrNorthFacingRoof[i])
# print("l_a at case A1:{}".format(l_a))
# print("l_b at case A1:{}".format(l_b))
# claculate the incidence angle for each facing roof
incidentAngleForEastOrNorthRoof = getIncidentAngleForEastOrNorthRoof(EPerpendicularEastOrNorthFacingRoof[i], beta)
incidentAngleForWestOrSouthhRoof = getIncidentAngleForWestOrSouthRoof(EPerpendicularEastOrNorthFacingRoof[i], alpha)
# print("incidentAngleForEastOrNorthRoof at case A1:{}".format(incidentAngleForEastOrNorthRoof))
# print("incidentAngleForWestOrSouthhRoof at case A1:{}".format(incidentAngleForWestOrSouthhRoof))
# calculate the transmittance and reflectance to each roof
T_2[i], F_2[i] = fresnelEquation(incidentAngleForEastOrNorthRoof)
T_1[i], F_1[i] = fresnelEquation(incidentAngleForWestOrSouthhRoof)
# print("T_1[i]:{}, T_2[i]:{}, F_1[i]:{}, F_2[i]:{}".format(T_1[i], T_2[i], F_1[i], F_2[i]))
T_matPerpendicular[i] = getTransmittanceThroughMultiSpanCoveringCaseA1ForEastOrNorthFacingRoof(l_a, l_b, m, T_1[i], F_1[i], T_2[i], F_2[i])
# print("T_matPerpendicular[i]:{}".format(T_matPerpendicular[i]))
# case A2.1: if the angle E is greater than the roof angle of the north side beta (beta < E < 2*beta)
elif (alpha < EPerpendicularEastOrNorthFacingRoof[i] and EPerpendicularEastOrNorthFacingRoof[i] < 2.0*alpha) or \
(math.pi - 2.0*alpha < EPerpendicularEastOrNorthFacingRoof[i] and EPerpendicularEastOrNorthFacingRoof[i] < math.pi - alpha):
# print ("call case A2.1")
l_1, l_2, T_1[i], F_1[i], T_2[i], F_2[i], T_12[i] = getSolarIrradianceDirectlhyTransmittedToPlants(\
alpha, beta, L_1, L_2, EPerpendicularEastOrNorthFacingRoof[i])
# get the angle E reflected from the west or south facing roof and transmit through multi-span roofs
reflectedE = getReflectedE(EPerpendicularEastOrNorthFacingRoof[i], alpha)
# get the incidence angle for each facing roof
incidentAngleOfReflectedLightForEastOrNorthRoof = getIncidentAngleForEastOrNorthRoof(reflectedE, beta)
incidentAngleOfReflectedLightForWestOrSouthRoof = getIncidentAngleForWestOrSouthRoof(reflectedE, alpha)
# get the Transmittance and reflection on each roof from the reflected irradiance
T_r12[i], F_r12[i] = fresnelEquation(incidentAngleOfReflectedLightForEastOrNorthRoof)
T_r11[i], F_r11[i] = fresnelEquation(incidentAngleOfReflectedLightForWestOrSouthRoof)
# the number of intercepting spans, which can very depending on E.
x = abs(2.0 * alpha - EPerpendicularEastOrNorthFacingRoof[i])
m = getNumOfInterceptingSPans(alpha, x)
# print("case A2.1 i:{}, m:{}, sys.getrecursionlimit():{}".format(i, m,sys.getrecursionlimit()))
# l_a: fraction (percentage) of reflected light which does not pass through the first span [-], equation (A14)
# l_b: fraction (percentage) of reflected light which crosses the first span before continuing on towards the others [-], equation (A15)
l_a, l_b = getFractionOfTransmittanceOfReflectedSolarIrradiance(alpha, beta, L_1, L_2, m, EPerpendicularEastOrNorthFacingRoof[i])
T_matPerpendicular[i] = getTransmittanceOfReflectedLightThroughMultiSpanCoveringCaseA2_1ForEastOrNorthFacingRoof(l_a, l_b, m, T_r11[i], T_r12[i], F_r11[i], F_r12[i], F_1[i], l_1, l_2) +\
+ T_12[i]
# print("T_matPerpendicular[i]:{}".format(T_matPerpendicular[i]))
# case A2.2: if the angle E is greater than the roof angle of the north side beta (2*beta < E < 3*beta)
elif (2.0*alpha < EPerpendicularEastOrNorthFacingRoof[i] and EPerpendicularEastOrNorthFacingRoof[i] < 3.0*alpha) or \
(math.pi - 3.0 * alpha < EPerpendicularEastOrNorthFacingRoof[i] and EPerpendicularEastOrNorthFacingRoof[i] < math.pi - 2.0 * alpha):
# print ("call case A2.2")
l_1, l_2, T_1[i], F_1[i], T_2[i], F_2[i], T_12[i] = getSolarIrradianceDirectlhyTransmittedToPlants(\
alpha, beta, L_1, L_2, EPerpendicularEastOrNorthFacingRoof[i])
# get the angle E reflected from the west or south facing roof and transmit through multi-span roofs
reflectedE = getReflectedE(EPerpendicularEastOrNorthFacingRoof[i], alpha)
# get the incidence angle for each facing roof
incidentAngleOfReflectedLightForEastOrNorthRoof = getIncidentAngleForEastOrNorthRoof(reflectedE, beta)
incidentAngleOfReflectedLightForWestOrSouthRoof = getIncidentAngleForWestOrSouthRoof(reflectedE, alpha)
# get the Transmittance and reflection on each roof from the reflected irradiance
T_r12[i], F_r12[i] = fresnelEquation(incidentAngleOfReflectedLightForEastOrNorthRoof)
T_r11[i], F_r11[i] = fresnelEquation(incidentAngleOfReflectedLightForWestOrSouthRoof)
# the number of intercepting spans, which can very depending on E.
x = abs(2.0 * alpha - EPerpendicularEastOrNorthFacingRoof[i])
m = getNumOfInterceptingSPans(alpha, x)
# l_a: fraction (percentage) of reflected light which does not pass through the first span [-], equation (A14)
# l_b: fraction (percentage) of reflected light which crosses the first span before continuing on towards the others [-], equation (A15)
l_a, l_b = getFractionOfTransmittanceOfReflectedSolarIrradiance(alpha, beta, L_1, L_2, m, EPerpendicularEastOrNorthFacingRoof[i])
T_matPerpendicular[i] = getTransmittanceOfReflectedLightThroughMultiSpanCoveringCaseA2_1ForEastOrNorthFacingRoof(l_a, l_b, m, T_r11[i], T_r12[i], F_r11[i], F_r12[i], F_1[i], l_1, l_2) \
+ T_12[i]
# print("T_matPerpendicular[i]:{}".format(T_matPerpendicular[i]))
# case A2.3: if 3.0 * alpha < EPerpendicularEastOrNorthFacingRoof[i]
# since this model assumes north-south direction greenhouse, the E can be more than pi/2.0, and thus the following range was set
elif 3.0 * alpha < EPerpendicularEastOrNorthFacingRoof[i] and EPerpendicularEastOrNorthFacingRoof[i] < (math.pi - 3.0 * alpha):
# print ("call case A2.3")
_, _, _, _, _, _, T_12[i] = getSolarIrradianceDirectlhyTransmittedToPlants(alpha, beta, L_1, L_2, EPerpendicularEastOrNorthFacingRoof[i])
T_matPerpendicular[i] = T_12[i]
# print("T_matPerpendicular[i]:{}".format(T_matPerpendicular[i]))
# print("T_1 :{}".format(T_1))
# print("F_1 :{}".format(F_1))
# print("T_2 :{}".format(T_2))
# print("F_2 :{}".format(F_2))
# print("T_12 :{}".format(T_12))
# print("T_r11 :{}".format(T_r11))
# print("F_r11 :{}".format(F_r11))
# print("T_r12 :{}".format(T_r12))
# print("F_r12 :{}".format(F_r12))
# print("T_matPerpendicular :{}.format(T_matPerpendicular))
return T_matPerpendicular
def getTransmittanceForPerpendicularIrrThroughMultiSpanRoofFacingWestOrSouth(simulatorClass, directSolarRadiationToOPVWestDirection, \
EPerpendicularWestOrSouthFacingRoof):
"""
:return:
"""
alpha = constant.roofAngleWestOrSouth
beta = constant.roofAngleEastOrNorth
L_1 = constant.greenhouseRoofWidthWestOrSouth
L_2 = constant.greenhouseRoofWidthEastOrNorth
# the Transmittances of roof surfaces 1 (facing west or south)
T_1 = np.zeros(directSolarRadiationToOPVWestDirection.shape[0])
# the Transmittances of roof surfaces 2 (facing east or north)
T_2 = np.zeros(directSolarRadiationToOPVWestDirection.shape[0])
# the reflectance of roof surfaces 1 (facing west or south)
F_1 = np.zeros(directSolarRadiationToOPVWestDirection.shape[0])
# the reflectance of roof surfaces 2 (facing west or south)
F_2 = np.zeros(directSolarRadiationToOPVWestDirection.shape[0])
# the transmittance/reflectance of solar irradiance directly transmitted to the soil through roof each direction of roof (surfaces east and west) (A10)
T_12 = np.zeros(directSolarRadiationToOPVWestDirection.shape[0])
# the transmittance/reflectance on the roof facing west of solar irradiance reflected by the surface facing east and transmitted to the soil (surfaces west or south)
T_r21 = np.zeros(directSolarRadiationToOPVWestDirection.shape[0])
F_r21 = np.zeros(directSolarRadiationToOPVWestDirection.shape[0])
# the transmittance/reflectance on the roof facing east of solar irradiance reflected by the surface facing east and transmitted to the soil (surfaces east or north)
T_r22 = np.zeros(directSolarRadiationToOPVWestDirection.shape[0])
F_r22 = np.zeros(directSolarRadiationToOPVWestDirection.shape[0])
# transmittance through multispan roof
T_matPerpendicular = np.zeros(directSolarRadiationToOPVWestDirection.shape[0])
# T_matParallel = np.zeros(directSolarRadiationToOPVWestDirection.shape[0])
# calculate the solar irradiacne from the EAST facing roof after penetrating multi-span roof per hour
for i in range(0, directSolarRadiationToOPVWestDirection.shape[0]):
# print("i:{}".format(i))
# print("EPerpendicularWestOrSouthFacingRoof[i]:{}".format(EPerpendicularWestOrSouthFacingRoof[i]))
# print("directSolarRadiationToOPVWestDirection[i]:{}".format(directSolarRadiationToOPVWestDirection[i]))
# if the solar irradiance at a certain time is zero, then skip the element
if directSolarRadiationToOPVWestDirection[i] == 0.0: continue
# case A1: if the roof-slope angle of the west side is greater than the angle E formed by the incident ray with the horizontal axis perpendicular to the greenhouse span
# It was assumed the direct solar radiation is 0 when EPerpendicularWestOrSouthFacingRoof[i] <= alpha
# elif EPerpendicularWestOrSouthFacingRoof[i] <= alpha or math.pi - alpha <= EPerpendicularWestOrSouthFacingRoof[i]:
elif math.pi - alpha <= EPerpendicularWestOrSouthFacingRoof[i]:
# print ("call case A1")
# since the original model does not suppose EPerpendicular is more than pi/2 (the cause it assume the angle of the greenhouse is east-west, not north-south where the sun croees the greenhouse)
# EPerpendicular is converted into pi - EPerpendicular when it is more than pi/2
if EPerpendicularWestOrSouthFacingRoof[i] > math.pi/2.0:
EPerpendicularWestOrSouthFacingRoof[i] = math.pi - EPerpendicularWestOrSouthFacingRoof[i]
# print("EPerpendicularWestOrSouthFacingRoof_CaseA1[i]:{}".format(EPerpendicularWestOrSouthFacingRoof[i]))
# the number of intercepting spans, which can very depending on E.
m = getNumOfInterceptingSPans(alpha, EPerpendicularWestOrSouthFacingRoof[i])
# fraction (percentage) of light which does not pass through the first span [-]
l_a = m * L_1 * math.sin(alpha + EPerpendicularWestOrSouthFacingRoof[i]) - (m + 1) * L_2 * math.sin(beta - EPerpendicularWestOrSouthFacingRoof[i])
# fraction (percentage) of light which crosses the first span before continuing on towards the others [-]
l_b = m * L_2 * math.sin(beta - EPerpendicularWestOrSouthFacingRoof[i]) - (m - 1) * L_1 * math.sin(alpha + EPerpendicularWestOrSouthFacingRoof[i])
# print("l_a at case A1:{}".format(l_a))
# print("l_b at case A1:{}".format(l_b))
# the following functions works to if you do not rollback EPerpendicularWestOrSouthFacingRoof
# claculate the incidence angle for each facing roof
incidentAngleForEastOrNorthRoof = getIncidentAngleForEastOrNorthRoofWithBeamComingFromWestOrSouth(EPerpendicularWestOrSouthFacingRoof[i], beta)
incidentAngleForWestOrSouthRoof = getIncidentAngleForWestOrSouthRoofWithBeamComingFromWestOrSouth(EPerpendicularWestOrSouthFacingRoof[i], alpha)
# print("incidentAngleForEastOrNorthRoof at case A1:{}".format(incidentAngleForEastOrNorthRoof))
# print("incidentAngleForWestOrSouthRoof at case A1:{}".format(incidentAngleForWestOrSouthRoof))
# calculate the transmittance and reflectance to each roof
T_2[i], F_2[i] = fresnelEquation(incidentAngleForEastOrNorthRoof)
T_1[i], F_1[i] = fresnelEquation(incidentAngleForWestOrSouthRoof)
# print("T_1[i]:{}, T_2[i]:{}, F_1[i]:{}, F_2[i]:{}".format(T_1[i], T_2[i], F_1[i], F_2[i]))
T_matPerpendicular[i] = getTransmittanceThroughMultiSpanCoveringCaseA1ForWestOrSouthFacingRoof(l_a, l_b, m, T_1[i], F_1[i], T_2[i], F_2[i])
# print("T_matPerpendicular[i]:{}".format(T_matPerpendicular[i]))
# case A2.1: if the angle E is greater than the roof angle of the north side beta (beta < E < 2*beta)
elif (alpha < EPerpendicularWestOrSouthFacingRoof[i] and EPerpendicularWestOrSouthFacingRoof[i] < 2.0*alpha) or \
(math.pi - 2.0 * alpha < EPerpendicularWestOrSouthFacingRoof[i] and EPerpendicularWestOrSouthFacingRoof[i] < math.pi - alpha):
# print ("call case A2.1")
l_1, l_2, T_1[i], F_1[i], T_2[i], F_2[i], T_12[i] = getSolarIrradianceDirectlhyTransmittedToPlants(\
alpha, beta, L_1, L_2, EPerpendicularWestOrSouthFacingRoof[i])
# get the angle E reflected from the west or south facing roof and transmit through multi-span roofs
reflectedE = getReflectedE(EPerpendicularWestOrSouthFacingRoof[i], alpha)
# get the incidence angle for each facing roof
incidentAngleOfReflectedLightForEastOrNorthRoof = getIncidentAngleForEastOrNorthRoof(reflectedE, beta)
incidentAngleOfReflectedLightForWestOrSouthRoof = getIncidentAngleForWestOrSouthRoof(reflectedE, alpha)
# get the Transmittance and reflection on each roof from the reflected irradiance
T_r22[i], F_r22[i] = fresnelEquation(incidentAngleOfReflectedLightForEastOrNorthRoof)
T_r21[i], F_r21[i] = fresnelEquation(incidentAngleOfReflectedLightForWestOrSouthRoof)
# the number of intercepting spans, which can very depending on E.
x = abs(2.0 * alpha - EPerpendicularWestOrSouthFacingRoof[i])
m = getNumOfInterceptingSPans(alpha, x)
# l_a: fraction (percentage) of reflected light which does not pass through the first span [-], equation (A14)
# l_b: fraction (percentage) of reflected light which crosses the first span before continuing on towards the others [-], equation (A15)
l_a, l_b = getFractionOfTransmittanceOfReflectedSolarIrradiance(alpha, beta, L_1, L_2, m, EPerpendicularWestOrSouthFacingRoof[i])
# print("l_a:{}, l_b:{}".format(l_a, l_b))
# # fraction (percentage) of light which does not pass through the first span [-], equation (A14)
# l_a = L_2 * m * math.sin(EPerpendicularWestOrSouthFacingRoof[i] - beta) - L_1 * (m - 1) * math.sin(alpha + 2.0 * beta - EPerpendicularWestOrSouthFacingRoof[i])
# # fraction (percentage) of light which crosses the first span before continuing on towards the others [-], equation (A15)
# l_b = L_1 * math.sin(alpha + 2.0 * beta - EPerpendicularWestOrSouthFacingRoof[i]) - L_2 * math.sin(EPerpendicularWestOrSouthFacingRoof[i] - beta)
T_matPerpendicular[i] = getTransmittanceOfReflectedLightThroughMultiSpanCoveringCaseA2_1ForWestOrSouthFacingRoof(l_a, l_b, m, T_r21[i], T_r22[i], F_r21[i], F_r22[i], F_1[i], l_1, l_2)\
+ T_12[i]
# print("T_matPerpendicular[i]:{}".format(T_matPerpendicular[i]))
# case A2.2: if the angle E is greater than the roof angle of the north side beta (2*beta < E < 3*beta)
elif (2.0*alpha < EPerpendicularWestOrSouthFacingRoof[i] and EPerpendicularWestOrSouthFacingRoof[i] < 3.0*alpha) or \
(math.pi - 3.0 * alpha < EPerpendicularWestOrSouthFacingRoof[i] and EPerpendicularWestOrSouthFacingRoof[i] < math.pi - 2.0 * alpha):
# print ("call case A2.2")
l_1, l_2, T_1[i], F_1[i], T_2[i], F_2[i], T_12[i] = getSolarIrradianceDirectlhyTransmittedToPlants(\
alpha, beta, L_1, L_2, EPerpendicularWestOrSouthFacingRoof[i])
# get the angle E reflected from the west or south facing roof and transmit through multi-span roofs
reflectedE = getReflectedE(EPerpendicularWestOrSouthFacingRoof[i], alpha)
# get the incidence angle for each facing roof
incidentAngleOfReflectedLightForEastOrNorthRoof = getIncidentAngleForEastOrNorthRoof(reflectedE, beta)
incidentAngleOfReflectedLightForWestOrSouthRoof = getIncidentAngleForWestOrSouthRoof(reflectedE, alpha)
# get the Transmittance and reflection on each roof from the reflected irradiance
T_r22[i], F_r22[i] = fresnelEquation(incidentAngleOfReflectedLightForEastOrNorthRoof)
T_r21[i], F_r21[i] = fresnelEquation(incidentAngleOfReflectedLightForWestOrSouthRoof)
# the number of intercepting spans, which can very depending on E.
x = abs(2.0 * alpha - EPerpendicularWestOrSouthFacingRoof[i])
m = getNumOfInterceptingSPans(alpha, x)
# fraction (percentage) of light which does not pass through the first span [-], equation (A16)
l_a = L_2 * (1-m) * math.sin(EPerpendicularWestOrSouthFacingRoof[i] - beta) + L_1 * m * math.sin(alpha + 2.0 * beta - EPerpendicularWestOrSouthFacingRoof[i])
# fraction (percentage) of light which crosses the first span before continuing on towards the others [-], equation (A17)
l_b = L_2 * math.sin(EPerpendicularWestOrSouthFacingRoof[i] - beta) - L_1 * math.sin(alpha + 2.0 * beta - EPerpendicularWestOrSouthFacingRoof[i])
# print("l_a:{}, l_b:{}".format(l_a, l_b))
T_matPerpendicular[i] = getTransmittanceOfReflectedLightThroughMultiSpanCoveringCaseA2_1ForWestOrSouthFacingRoof(l_a, l_b, m, T_r21[i], T_r22[i], F_r21[i], F_r22[i], F_1[i], l_1, l_2) \
+ T_12[i]
# print("T_matPerpendicular[i]:{}".format(T_matPerpendicular[i]))
# case A2.3: if 3.0 * alpha < EPerpendicularEastOrNorthFacingRoof[i]
# since this model assumes north-south direction greenhouse, the E can be more than pi/2.0, and thus the following range was set
elif (3.0*alpha < EPerpendicularWestOrSouthFacingRoof[i] and EPerpendicularWestOrSouthFacingRoof[i] < (math.pi - 3.0*alpha)):
# print ("call case A2.3")
_, _, _, _, _, _, T_12[i] = getSolarIrradianceDirectlhyTransmittedToPlants(alpha, beta, L_1, L_2, EPerpendicularWestOrSouthFacingRoof[i])
T_matPerpendicular[i] = T_12[i]
# print("T_1 :{}".format(T_1))
# print("F_1 :{}".format(F_1))
# print("T_2 :{}".format(T_2))
# print("F_2 :{}".format(F_2))
# print("T_12 :{}".format(T_12))
# print("T_r21 :{}".format(T_r21))
# print("F_r21 :{}".format(F_r21))
# print("T_r22 :{}".format(T_r22))
# print("F_r22 :{}".format(F_r22))
# print("T_matPerpendicular :{}".format(T_matPerpendicular))
return T_matPerpendicular
def getNumOfInterceptingSPans(alpha, EPerpendicularWestOrSouthFacingRoof):
'''
# the number of intercepting spans, which can very depending on E.
'''
m = int(1.0 / 2.0 * (1 + math.tan(alpha) / math.tan(EPerpendicularWestOrSouthFacingRoof)))
# print("WestOrSouth case A1 i:{}, m:{}, math.tan(alpha):{}, math.tan(EPerpendicularEastOrNorthFacingRoof[i]):{}".format(i, m, math.tan(alpha), math.tan(EPerpendicularEastOrNorthFacingRoof[i])))
# if the angle between the incident light and the horizontal axis is too small, the m can be too large, which cause a system error at Util.sigma by iterating too much. Thus, the upper limit was set
if m > constant.mMax: m = constant.mMax
return m
def getTransmittanceForParallelIrrThroughMultiSpanRoof(simulatorClass, EParallelEastOrNorthFacingRoof):
'''
In the parallel direction to the grenhouse roof, the agle of the roof is 0. There is no reflection transmitted to other part of the roof.
:return:
'''
##############################################################################################################################
# calculate the transmittance of perpendicular direction from the EAST facing roof after penetrating multi-span roof per hour
##############################################################################################################################
# the transmittance of roof surfaces
T = np.zeros(simulatorClass.getDirectSolarRadiationToOPVEastDirection().shape[0])
# the reflectance of roof surfaces
F = np.zeros(simulatorClass.getDirectSolarRadiationToOPVEastDirection().shape[0])
for i in range(0, simulatorClass.getDirectSolarRadiationToOPVEastDirection().shape[0]):
# calculate the transmittance and reflectance to each roof
T[i], F[i] = fresnelEquation(EParallelEastOrNorthFacingRoof[i])
return T
def getIncidentAngleForEastOrNorthRoof(EPerpendicularEastOrNorthFacingRoof, beta):
# calculate the incident angle [rad]
# the incident angle should be the angle between the solar irradiance and the normal to the tilted roof
return abs(math.pi / 2.0 - abs(beta + EPerpendicularEastOrNorthFacingRoof))
# if beta + EPerpendicularEastOrNorthFacingRoof < math.pi/2.0:
# return math.pi/2.0 - abs(beta + EPerpendicularEastOrNorthFacingRoof)
# # if the angle E + alpha is over pi/2 (the sun pass the normal to the tilted roof )
# else:
# return abs(beta + EPerpendicularEastOrNorthFacingRoof) - math.pi / 2.0
def getIncidentAngleForWestOrSouthRoof(EPerpendicularWestOrSouthFacingRoof, alpha):
# calculate the incident angle [rad]
# the incident angle should be the angle between the solar irradiance and the normal to the tilted roof
return abs(math.pi/2.0 - abs(alpha - EPerpendicularWestOrSouthFacingRoof))
def getIncidentAngleForEastOrNorthRoofWithBeamComingFromWestOrSouth(EPerpendicularEastOrNorthFacingRoof, beta):
# calculate the incident angle [rad]
# the incident angle should be the angle between the solar irradiance and the normal to the tilted roof
return abs(math.pi / 2.0 - abs(beta - EPerpendicularEastOrNorthFacingRoof))
def getIncidentAngleForWestOrSouthRoofWithBeamComingFromWestOrSouth(EPerpendicularWestOrSouthFacingRoof, alpha):
# calculate the incident angle [rad]
# the incident angle should be the angle between the solar irradiance and the normal to the tilted roof
return abs(math.pi / 2.0 - abs(alpha + EPerpendicularWestOrSouthFacingRoof))
def fresnelEquation(SolarIrradianceIncidentAngle):
'''
calculate the transmittance and reflectance for a given incidnet angle and index of reflectances
reference:
http://hyperphysics.phy-astr.gsu.edu/hbase/phyopt/freseq.html
https://www.youtube.com/watch?v=ayxFyRF-SrM
https://ja.wikipedia.org/wiki/%E3%83%95%E3%83%AC%E3%83%8D%E3%83%AB%E3%81%AE%E5%BC%8F
:return: transmittance, reflectance
'''
# reference: https://www.filmetrics.com/refractive-index-database/Polyethylene/PE-Polyethene
PEFilmRefractiveIndex = constant.PEFilmRefractiveIndex
# reference: https://en.wikipedia.org/wiki/Refractive_index
AirRefractiveIndex = constant.AirRefractiveIndex
# print("SolarIrradianceIncidentAngle:{}".format(SolarIrradianceIncidentAngle))
# Snell's law, calculating the transmittance raw after refractance
transmittanceAngle = math.asin(AirRefractiveIndex/PEFilmRefractiveIndex*math.sin(SolarIrradianceIncidentAngle))
# S (perpendicular) wave
perpendicularlyPolarizedTransmittance = 2.0 * AirRefractiveIndex*math.cos(SolarIrradianceIncidentAngle) / \
(AirRefractiveIndex*math.cos(SolarIrradianceIncidentAngle) + PEFilmRefractiveIndex*math.cos(transmittanceAngle))
perpendicularlyPolarizedReflectance = (AirRefractiveIndex*math.cos(SolarIrradianceIncidentAngle) - PEFilmRefractiveIndex*math.cos(transmittanceAngle)) / \
(AirRefractiveIndex*math.cos(SolarIrradianceIncidentAngle) + PEFilmRefractiveIndex*math.cos(transmittanceAngle))
# P (parallel) wave
parallelPolarizedTransmittance = 2.0 * AirRefractiveIndex*math.cos(SolarIrradianceIncidentAngle) / \
(PEFilmRefractiveIndex*math.cos(SolarIrradianceIncidentAngle) + AirRefractiveIndex*math.cos(transmittanceAngle))
parallelPolarizedReflectance = (PEFilmRefractiveIndex*math.cos(SolarIrradianceIncidentAngle) - AirRefractiveIndex*math.cos(transmittanceAngle)) / \
(PEFilmRefractiveIndex*math.cos(SolarIrradianceIncidentAngle) + AirRefractiveIndex*math.cos(transmittanceAngle))
# according to https://www.youtube.com/watch?v=ayxFyRF-SrM at around 17:00, the reflection can be negative when the phase of light changes by 180 degrees
# Here it was assumed the phase shift does not influence the light intensity (absolute stength), and so the negative sign was changed into the positive
perpendicularlyPolarizedReflectance = abs(perpendicularlyPolarizedReflectance)
parallelPolarizedReflectance = abs(parallelPolarizedReflectance)
# Assuming that sunlight included diversely oscilating radiation by 360 degrees, the transmittance and reflectance was averaged with those of parpendicular and parallel oscilation
transmittanceForSolarIrradiance = (perpendicularlyPolarizedTransmittance + parallelPolarizedTransmittance) / 2.0
ReflectanceForSolarIrradiance = (perpendicularlyPolarizedReflectance + parallelPolarizedReflectance) / 2.0
return transmittanceForSolarIrradiance, ReflectanceForSolarIrradiance
def getTransmittanceThroughMultiSpanCoveringCaseA1ForEastOrNorthFacingRoof(l_a, l_b, m, T_1, F_1, T_2, F_2):
'''
the equation number in the reference: (A8), page 252
'''
# print("l_a:{}, l_b:{}, m:{}, T_1:{}, F_1:{}, T_2:{}, F_2:{}".format(l_a, l_b, m, T_1, F_1, T_2, F_2))
transmittanceThroughMultiSpanCoveringCaseA1ForEastOrNorthFacingRoof = (l_a*T_2*(F_1*util.sigma(0, m-2, lambda s: (T_1*T_2)**s,0) + (T_1*T_2)**(m-1)) + \
l_b*T_2*(F_1*util.sigma(0, m-1, lambda s: (T_1*T_2)**s,0) + (T_1*T_2)**m)) / (l_a + l_b)
# print("transmittanceThroughMultiSpanCoveringCaseA1ForEastOrNorthFacingRoof:{}".format(transmittanceThroughMultiSpanCoveringCaseA1ForEastOrNorthFacingRoof))
return transmittanceThroughMultiSpanCoveringCaseA1ForEastOrNorthFacingRoof
def getTransmittanceThroughMultiSpanCoveringCaseA1ForWestOrSouthFacingRoof(l_a, l_b, m, T_1, F_1, T_2, F_2):
'''
the equation number in the reference: (A8), page 252
the content of this function is same as getTransmittanceThroughMultiSpanCoveringCaseA1ForEastOrNorthFacingRoof, but made this just for clarifying the meaning of variables.
'''
transmittanceThroughMultiSpanCoveringCaseA1ForWestOrSouthFacingRoof = (l_a*T_1*(F_2*util.sigma(0, m-2, lambda x: (T_1*T_2)**x,0) + (T_1*T_2)**(m-1)) + \
l_b*T_1*(F_2*util.sigma(0, m-1, lambda x: (T_1*T_2)**x,0) + (T_1*T_2)**m)) / (l_a + l_b)
# print("transmittanceThroughMultiSpanCoveringCaseA1ForWestOrSouthFacingRoof:{}".format(transmittanceThroughMultiSpanCoveringCaseA1ForWestOrSouthFacingRoof))
return transmittanceThroughMultiSpanCoveringCaseA1ForWestOrSouthFacingRoof
def getReflectedE(E, roofAngle):
incidentAngle = getIncidentAngleForWestOrSouthRoof(E, roofAngle)
# the reflected incident angle E' is pi - (pi - alpha) - (pi/2.0 - incidentAngle))
return abs(roofAngle - incidentAngle - math.pi/2.0)
def getFractionOfTransmittanceOfReflectedSolarIrradiance(alpha, beta, L_1, L_2, m, EPerpendicular):
# The original source G.P.A. Bot 1983, "Greenhouse Climate: from physical processes to a dynamic model" does not seem to suppose EPerpendicular becomes more than pi/2, thus,
# l_a and l_b became negative when EPerpendicular > pi/2 indeed. Thus it was converted to the rest of the angle
if EPerpendicular > math.pi/2.0:
EPerpendicular = math.pi/2.0 - EPerpendicular
# fraction (percentage) of light which does not pass through the first span [-], equation (A14)
l_a = L_2 * m * math.sin(EPerpendicular - beta) - L_1 * (m - 1) * math.sin(alpha + 2.0 * beta - EPerpendicular)
# print("m:{}, L_1:{}, L_2:{}, alpha:{}, beta:{}".format(m, L_1, L_2, alpha, beta))
# print("EPerpendicular - beta):{}".format(math.sin(EPerpendicular - beta)))
# print("math.sin(alpha + 2.0*beta - EPerpendicular):{}".format(math.sin(alpha + 2.0 * beta - EPerpendicular)))
# fraction (percentage) of light which crosses the first span before continuing on towards the others [-], equation (A15)
l_b = L_1 * math.sin(alpha + 2.0 * beta - EPerpendicular) - L_2 * math.sin(EPerpendicular - beta)
# print("l_a:{}, l_b:{}".format(l_a, l_b))
return l_a, l_b
def getTransmittanceOfReflectedLightThroughMultiSpanCoveringCaseA2_1ForEastOrNorthFacingRoof(l_a, l_b, m, T_r11, T_r12, F_r11, F_r12, F_1, l_1, l_2):
'''
the equation number in the reference: (A13)
'''
# print("called from CaseA2_1: l_a:{}, l_b:{}, m:{}, T_r11:{}, T_r12:{}, F_r11:{}, F_r12:{}, F_1:{}, l_1:{}, l_2:{}".format(l_a, l_b, m, T_r11, T_r12, F_r11, F_r12, F_1, l_1, l_2))
# transmittanceOfReflectedLight = (F_1*l_a*T_r11*(F_r12*util.sigma(2, m-2, lambda s: (T_r11*T_r12)**s,0.0) + (T_r11*T_r12)**(m-1)) + \
# F_1*l_b*T_r11*(F_r12*util.sigma(0, m-3, lambda s: util.sigma(0, s, lambda n: (T_r11*T_r12)**n,0),0.0) + \
# util.sigma(0, m-2, lambda s: (T_r11 * T_r12)**s, 0.0))) / (l_1 + l_2)
#
# # print ("transmittanceOfReflectedLight:{}".format(transmittanceOfReflectedLight))
#
# return transmittanceOfReflectedLight
return (F_1*l_a*T_r11*(F_r12*util.sigma(2, m-2, lambda s: (T_r11*T_r12)**s,0.0) + (T_r11*T_r12)**(m-1)) + \
F_1*l_b*T_r11*(F_r12*util.sigma(0, m-3, lambda s: util.sigma(0, s, lambda n: (T_r11*T_r12)**n,0),0.0) + \
util.sigma(0, m-2, lambda s: (T_r11 * T_r12)**s, 0.0))) / (l_1 + l_2)
def getTransmittanceOfReflectedLightThroughMultiSpanCoveringCaseA2_1ForWestOrSouthFacingRoof(l_a, l_b, m, T_r21, T_r22, F_r22, F_r21, F_2, l_1, l_2):
'''
the content of this function is same as getTransmittanceThroughMultiSpanCoveringCaseA2_1ForEastOrNorthFacingRoof, but made this just for clarifying the meaning of variables.
'''
# print("T_r21:{}, T_r22:{}, F_r21:{}, F_r22:{}, F_2:{}, l_1:{}, l_2:{}".format(T_r21, T_r22, F_r21, F_r22, F_2, l_1, l_2))
return (F_2*l_a*T_r21*(F_r22*util.sigma(2, m-2, lambda s: (T_r21*T_r22)**s,0) + (T_r21*T_r22)**(m-1)) + \
F_2*l_b*T_r21*(F_r22*util.sigma(0, m-3, lambda s: util.sigma(0, s, lambda n: (T_r21*T_r22)**n,0),0) + \
util.sigma(0, m-2, lambda s: (T_r21 * T_r22)**s, 0))) / (l_1 + l_2)
def getTransmittanceThroughMultiSpanCoveringCaseA2_2ForEastOrNorthFacingRoof(l_a, l_b, m, T_r11, T_r12, F_r11, F_r12, F_1, l_1, l_2):
'''
the equation number in the reference: (A18)
'''
return (l_a*F_1 + T_r11*F_r12*util.sigma(0, m-1, lambda s: (T_r11*T_r12)**s,0) + \
l_b*F_1*T_r11*T_r12*util.sigma(0, m - 2, lambda s: util.sigma(0, s, lambda n: (T_r11 * T_r12)**n, 0), 0))/(l_1+l_2)
def getTransmittanceThroughMultiSpanCoveringCaseA2_2ForWestOrSouthFacingRoof(l_a, l_b, m, T_r21, T_r22, F_r21, F_r22, F_2, l_1, l_2):
'''
the equation number in the reference: (A18)
the content of this function is same as getTransmittanceThroughMultiSpanCoveringCaseA2_2ForEastOrNorthFacingRoof, but made this just for clarifying the meaning of variables.
'''
return (l_a*F_2 + T_r21*F_r22*util.sigma(0, m-1, lambda s: (T_r21*T_r22)**s,0) + \
l_b*F_2*T_r21*T_r22*util.sigma(0, m - 2, lambda s: util.sigma(0, s, lambda n: (T_r21 * T_r22)**n, 0), 0))/(l_1+l_2)
def getSolarIrradianceDirectlhyTransmittedToPlants(alpha, beta, L_1, L_2, EPerpendicular):
'''
get direct radiation directly transmitted to the soil through roof surfaces
:return:
'''
# the portion of the beam of incident light that travels through the first side (west or south side) of the roof
# the following formula is from Soriano et al. (2004), but this seems to be wrong
# l_1 = L_1 * math.cos(alpha - EPerpendicular)
# the following formula was cited from the original source of this model: G. P. A. Bot, 1983 "Greenhouse Climate: from physical processes to a dynamic model", page 90
# l_1 = L_1 * math.sin(alpha + EPerpendicular)
# In addition, the difference of greenhouse direction was considered (l_1 is for west facing roof, and l_2 is for east facing roof. The solar radiation comes from the east in the morning)
# if the sunlight comes from east (right side in the figure)
if EPerpendicular < math.pi:
l_1 = L_1 * math.sin(EPerpendicular - alpha)
# the portion of the beam of incident light that travels through the second side (east or north side) of the roof.
l_2 = L_2 * math.sin(EPerpendicular + beta)
# if the sunlight comes from west (right side in the figure)
else:
l_1 = L_1 * math.sin(EPerpendicular + alpha)
# the portion of the beam of incident light that travels through the second side (east or north side) of the roof.
l_2 = L_2 * math.sin(EPerpendicular - beta)
# print("l_1:{}".format(l_1))
# print("l_2:{}".format(l_2))
# get the incidence angle for each facing roof
incidentAngleForEastOrNorthRoof = getIncidentAngleForEastOrNorthRoof(EPerpendicular, beta)
incidentAngleForWestOrSouthRoof = getIncidentAngleForWestOrSouthRoof(EPerpendicular, alpha)
# print("incidentAngleForEastOrNorthRoof :{}".format(incidentAngleForEastOrNorthRoof))
# print("incidentAngleForWestOrSouthRoof :{}".format(incidentAngleForWestOrSouthRoof))
# get the transmittance
T_2, F_2 = fresnelEquation(incidentAngleForEastOrNorthRoof)
T_1, F_1 = fresnelEquation(incidentAngleForWestOrSouthRoof)
# print("T_1:{}, F_1:{}, T_2:{}, F_2:{}".format(T_1, F_1, T_2, F_2))
# the transmittance of solar irradiance directly transmitted to the soil through roof each direction of roof (surfaces east and west) (A10)
T_12 = (T_1 * l_1 + T_2 * l_2) / (l_1 + l_2)
# print("T_12:{}".format(T_12))
return l_1, l_2, T_1, F_1, T_2, F_2, T_12
def getIntegratedT_matFromBothRoofs(T_matForPerpendicularIrrEastOrNorthFacingRoof, T_matForPerpendicularIrrWestOrSouthFacingRoof):
'''
:return: integratedT_mat
'''
integratedT_mat = np.zeros(T_matForPerpendicularIrrEastOrNorthFacingRoof.shape[0])
for i in range (0, integratedT_mat.shape[0]):
if T_matForPerpendicularIrrEastOrNorthFacingRoof[i] == 0.0 and T_matForPerpendicularIrrWestOrSouthFacingRoof[i] == 0.0: continue
elif T_matForPerpendicularIrrEastOrNorthFacingRoof[i] != 0.0 and T_matForPerpendicularIrrWestOrSouthFacingRoof[i] == 0.0:
integratedT_mat[i] = T_matForPerpendicularIrrEastOrNorthFacingRoof[i]
elif T_matForPerpendicularIrrEastOrNorthFacingRoof[i] == 0.0 and T_matForPerpendicularIrrWestOrSouthFacingRoof[i] != 0.0:
integratedT_mat[i] = T_matForPerpendicularIrrWestOrSouthFacingRoof[i]
# if both t_mat are not 0
else:
integratedT_mat[i] = (T_matForPerpendicularIrrEastOrNorthFacingRoof[i] + T_matForPerpendicularIrrWestOrSouthFacingRoof[i]) / 2.0
return integratedT_mat
|
{"/OPVFilm.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/ShadingCurtain.py"], "/CropElectricityYieldProfitMINLP.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelS_Pearson1997.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/PlantGrowthModelS_Pearson1997Constant.py", "/Lettuce.py"], "/GreenhouseEnergyBalanceConstant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/Util.py": ["/CropElectricityYeildSimulatorConstant.py"], "/SolarIrradianceMultiSpanRoof.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/GreenhouseEnergyBalance.py": ["/Lettuce.py", "/CropElectricityYeildSimulatorConstant.py", "/GreenhouseEnergyBalanceConstant.py", "/Util.py"], "/SimulatorMain.py": ["/CropElectricityYeildSimulator1.py", "/Util.py", "/CropElectricityYeildSimulatorConstant.py"], "/CropElectricityYieldProfitRLShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/ShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelValidation.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulator1.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulatorDetail.py": ["/ShadingCurtain.py", "/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/Lettuce.py", "/PlantGrowthModelS_Pearson1997.py", "/SolarIrradianceMultiSpanRoof.py", "/GreenhouseEnergyBalance.py"], "/PlantGrowthModelS_Pearson1997Constant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/SimulatorClass.py": ["/CropElectricityYeildSimulatorConstant.py"], "/Lettuce.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/plantGrowthModelE_J_VanHenten.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py"]}
|
8,661
|
kensaku-okada/Greenhouse-with-OPV-film-Model
|
refs/heads/master
|
/GreenhouseEnergyBalance.py
|
# -*- coding: utf-8 -*-
#############command to print out all array data
# np.set_printoptions(threshold=np.inf)
# print ("directSolarRadiationToOPVWestDirection:{}".format(directSolarRadiationToOPVWestDirection))
# np.set_printoptions(threshold=1000)
#############
# ####################################################################################################
# # Stop execution here...
# sys.exit()
# # Move the above line to different parts of the assignment as you implement more of the functionality.
# ####################################################################################################
##########import package files##########
import datetime
import sys
import os
import numpy as np
import math
import Lettuce
import CropElectricityYeildSimulatorConstant as constant
import GreenhouseEnergyBalanceConstant as energyBalanceConstant
import Util
from dateutil.relativedelta import *
from time import strptime
#######################################################
def getGHEnergyConsumptionByCoolingHeating(simulatorClass):
'''
all of the energy data calculated in this function is the average energy during each hour, not the total energy during eah hour.
reference:
1
Unknown author, Greenhouse Steady State Energy Balance Model
https://fac.ksu.edu.sa/sites/default/files/lmhdr_lthlth_wlrb.pdf
or
http://ecoursesonline.iasri.res.in/mod/page/view.php?id=1635
accessed on May 18 2018
2
Idso, S. B. 1981. A set of equations for full spectrum and 8-µm to 14-µm and 10.5-µm to
12.5-µm thermal radiation from cloudless skies. Water Resources Research, 17: 295-
304. https://agupubs.onlinelibrary.wiley.com/doi/abs/10.1029/WR017i002p00295
'''
# get the necessary data
# unit: W m-2
directSolarIrradianceToPlants = simulatorClass.directSolarIrradianceToPlants
# unit: W m-2
diffuseSolarIrradianceToPlants = simulatorClass.diffuseSolarIrradianceToPlants
# unit: Celsius degree
hourlyAirTemperatureOutside = simulatorClass.getImportedHourlyAirTemperature()
# unit: -
relativeHumidityOutside = simulatorClass.hourlyRelativeHumidity
# the amount of direct and diffuse shortwave solar radiation in the greenhouse [W m-2]
################# get Q_sr start ################
'''
in the reference papre, the formula is,
Q_sr = tau_c * S_l * I_sr * A_f
where tau_c is transmissivity of the greenhouse covering materials for solar radiation,
S_l is shading level, and I_sr is the amount of solar radiation energy received per unit are and per unit time on a horizontal surface outside the greenhouse [W m2].
However, since tau_c * S_l * I_sr is already calculated as the sum of directSolarIrradianceToPlants and diffuseSolarIrradianceToPlants, I arranged the formula as below.
'''
# unit: W m-2
totalSolarIrradianceToPlants = directSolarIrradianceToPlants + diffuseSolarIrradianceToPlants
Q_sr = totalSolarIrradianceToPlants
# ############command to print out all array data
# np.set_printoptions(threshold=np.inf)
# print("Q_sr:{}".format(Q_sr))
# np.set_printoptions(threshold=1000)
# ############
################# get Q_sr end ################
# latent heat energy flux due to plant transpiration [W m-2]
################# get Q_lh (Q_e) start ################
# '''
# todo delete this comment if not necessary
# # rate of transpiration [Kg_H2O sec-1 m-2]
# # according to Ricardo Aroca et al. (2008). Mycorrhizal and non-mycorrhizal Lactuca sativa plants exhibit contrasting responses to exogenous ABA during drought stress and recovery
# this value was around 6.6 [mg_H2O hour-1 cm-2]. This should be converted as below.
# '''
# ET = 6.6 / 1000.0 / (constant.secondperMinute * constant.minuteperHour) * 10000.0
Q_lh = getLatentHeatTransferByTranspiration(simulatorClass, totalSolarIrradianceToPlants)
# ############command to print out all array data
# np.set_printoptions(threshold=np.inf)
# print("Q_lh:{}".format(Q_lh))
# np.set_printoptions(threshold=1000)
# ############
################# get Q_lh (Q_e) end ################
# sensible heat from conduction and convection through the greenhouse covering material [W m-2]
################# get Q_sh (Q_cd in reference 1) start ################
# # the area of greenhouse covers [m2]
# A_c = constant.greenhouseTotalRoofArea
# inside (set point) air temperature [Celsius degree]
T_iC = Lettuce.getGreenhouseTemperatureEachHour(simulatorClass)
# inside air temperature [K]
T_iK = T_iC + 273.0
# outside air temperature [C]
T_oC = hourlyAirTemperatureOutside
# outside air temperature [K]
T_oK = hourlyAirTemperatureOutside + 273.0
Q_sh = energyBalanceConstant.U * (T_iC - T_oC)
# ############command to print out all array data
# np.set_printoptions(threshold=np.inf)
# print("Q_sh:{}".format(Q_sh))
# np.set_printoptions(threshold=1000)
# ############
################# get Q_sh (Q_cd in reference 1) end ################
# net thermal radiation through the greenhouse covers to the atmosphere [W m-2], the difference between the thermal radiation emitted from the surface and the thermal radiation gained from the atmosphere
################# get Q_lw (Q_t in reference 1) start ################
# ambient vapor pressure outside [Pa]
# source: https://www.weather.gov/media/epz/wxcalc/vaporPressure.pdf
_, e_a = getSturatedAndActualVaporPressure(T_oC, relativeHumidityOutside)
# print("e_a.shape:{}".format(e_a.shape))
# ############command to print out all array data
# np.set_printoptions(threshold=np.inf)
# print("e_a:{}".format(e_a))
# np.set_printoptions(threshold=1000)
# ############
# apparent emissivity of the sky (Idso, 1981)
# source: reference 2
epsilon_sky = 0.7 - 5.95 * 10.0**(-7) * e_a * math.e**(1500.0 / T_oK)
# ############command to print out all array data
# np.set_printoptions(threshold=np.inf)
# print("epsilon_sky.shape:{}, epsilon_sky:{}".format(epsilon_sky.shape, epsilon_sky))
# np.set_printoptions(threshold=1000)
# ############
# transmissivity of the shading shading curtain
tau_os = constant.shadingTransmittanceRatio
# ############command to print out all array data
# np.set_printoptions(threshold=np.inf)
# print("T_o:{}".format(T_o))
# np.set_printoptions(threshold=1000)
# ############
# the sky temperature (the Swinbank model (1963) ) [K]
T_sky = 0.0552 * T_oK**1.5
# print("T_sky.shape:{}".format(T_sky.shape))
# ############command to print out all array data
# np.set_printoptions(threshold=np.inf)
# print("T_sky:{}".format(T_sky))
# np.set_printoptions(threshold=1000)
# ############
Q_lw = energyBalanceConstant.delta * energyBalanceConstant.tau_tc * tau_os * \
(energyBalanceConstant.epsilon_i * T_iK**4.0 - epsilon_sky * T_sky**4.0)
# ############command to print out all array data
# np.set_printoptions(threshold=np.inf)
# print("Q_lw.shape:{}, Q_lw:{}".format(Q_lw.shape, Q_lw))
# np.set_printoptions(threshold=1000)
# ############
################# get Q_lw (Q_t in reference 1) end ################
# energy removed by ventilation air or added by heating[W m-2]
################# get Q_v start ################
# if positive, cooling. if negative, heating
Q_v = getQ_v(simulatorClass, Q_sr, Q_lh, Q_sh, Q_lw)
# Q_v = Q_sr - Q_lh - Q_sh - Q_lw
# print("Q_v.shape:{}".format(Q_v.shape))
################# get Q_v end ################
# set the data to the object. all units are W m-2
simulatorClass.Q_v["coolingOrHeatingEnergy W m-2"] = Q_v
simulatorClass.Q_sr["solarIrradianceToPlants W m-2"] = Q_sr
simulatorClass.Q_lh["latentHeatByTranspiration W m-2"] = Q_lh
simulatorClass.Q_sh["sensibleHeatFromConductionAndConvection W m-2"] = Q_sh
simulatorClass.Q_lw["longWaveRadiation W m-2"] = Q_lw
# print("Q_sr.shape:{}".format(Q_sr.shape))
# print("Q_lh.shape:{}".format(Q_lh.shape))
# print("Q_sh.shape:{}".format(Q_sh.shape))
# print("Q_lw.shape:{}".format(Q_lw.shape))
def getLatentHeatTransferByTranspiration(simulatorClass, totalSolarIrradianceToPlants):
'''
reference:
1
Pollet, S. and Bleyaert, P. 2000.
APPLICATION OF THE PENMAN-MONTEITH MODEL TO CALCULATE THE EVAPOTRANSPIRATION OF HEAD LETTUCE (Lactuca sativa L. var.capitata) IN GLASSHOUSE CONDITIONS
https://www.actahort.org/books/519/519_15.htm
2
Andriolo, J.L., da Luz, G.L., Witter, M.H., Godoi, R.S., Barros, G.T., Bortolotto, O.C.
(2005). Growth and yield of lettuce plant under salinity. Horticulture Brasileira,
23(4), 931-934.
'''
# inside (set point) air temperature [Celsius degree]
T_iC = Lettuce.getGreenhouseTemperatureEachHour(simulatorClass)
hourlyDayOrNightFlag = simulatorClass.hourlyDayOrNightFlag
relativeHumidityInGH = np.array([constant.setPointHumidityDayTime if i == constant.daytime else constant.setPointHumidityNightTime for i in hourlyDayOrNightFlag])
# leaf temperature [Celsius degree]. It was assumed that the difference between the leaf temperature and the air temperature was always 2. This is just an assumption of unofficial experiment at Kacira Lab at CEAC in University of Arizona
T_l = T_iC + 2.0
# dimention of leaf [m]. This is just an assumption of unofficial experiment at Kacira Lab at CEAC in University of Arizona
d = 0.14
# arerodynamic resistance of the leaf [s m-1]
# source: reference No 1, Pollet et al. 2000
r_a = 840.0 * (d/abs(T_l - T_iC))**(1.0/4.0)
# print("r_a:{}".format(r_a))
# the leaf area index [-]
# source: reference No 2, Andriolo et al. 2005
# L = 4.3
# source: Van Henten (1994)
L = simulatorClass.LeafAreaIndex_J_VanHenten1994
# print("leaf area index (L):{}".format(L))
# arerodynamic resistance of the crop [s m-1]
# source: reference No 1, Pollet et al. 2000
r_b = r_a /(2.0 * L)
# ############command to print out all array data
# np.set_printoptions(threshold=np.inf)
# print("r_b:{}".format(r_b))
# np.set_printoptions(threshold=1000)
# ############
# short wave radiation [W m-2]
# Need to figure out why dividing the solar irradiance inside by 0.844. see the differnce. -> This is probably because the suthor considered some light prevention by internal equipment. Considering the definition, it should be same as the soalr irradiance to plants
# I_s = 0.844 * totalSolarIrradianceToPlants
I_s = totalSolarIrradianceToPlants
############### calc the vapor pressure deficit start ###############
# saturated vapore pressure [Pa]
# source: http://cronklab.wikidot.com/calculation-of-vapour-pressure-deficit
# source: https://www.weather.gov/media/epz/wxcalc/vaporPressure.pdf
e_s, e_a = getSturatedAndActualVaporPressure(T_iC, relativeHumidityInGH)
# vapor pressure deficit [Pa]
D_Pa = e_s - e_a
# unit conversion: Pa (vapor pressure deficit) -> g m-2 (humidity deficit)
# source: http://mackenmov.sunnyday.jp/macken/plantf/term/housa/hosa.html
VH = 217.0 * e_s / (T_iC + 273.15)
D = (1.0 - relativeHumidityInGH) * VH
############### calc the vapor pressure deficit end ###############
# the stomatal resistance [sec m-1]
# source: reference No 1, Pollet et al. 2000
r_s = 164.0*(31.029+I_s)/(6.740+I_s) * (1 + 0.011*(D - 3.0)**2) * (1 + 0.016*(T_iC - 16.4)**2)
# crop resistance [sec m-1]
# source: reference No 1, Pollet et al. 2000
r_c = r_s / L
################## calc psychrometric constant start ##################
# print("energyBalanceConstant.c_p / (energyBalanceConstant.epsilon * energyBalanceConstant.lambda_:{}".format(energyBalanceConstant.c_p / (energyBalanceConstant.epsilon * energyBalanceConstant.lambda_)))
# print("energyBalanceConstant.P:{}".format(energyBalanceConstant.P))
# psychrometric constant
# source: http://www.fao.org/docrep/X0490E/x0490e07.htm
gamma = energyBalanceConstant.c_p * energyBalanceConstant.P / (energyBalanceConstant.epsilon * energyBalanceConstant.lambda_)
# gamma = 0.665 * 10**(-3) * energyBalanceConstant.P
# print("gamma:{}".format(gamma))
# gamma_star = gamma * (1 + r_c / r_b)
gamma_star = gamma * (1 + r_c / r_b)
# ############command to print out all array data
# np.set_printoptions(threshold=np.inf)
# print("gamma_star:{}".format(gamma_star))
# np.set_printoptions(threshold=1000)
# ############
################## calc psychrometric constant end ##################
# slope of saturation vapore pressure - temperature curve [kPa C-1]
# source: http://www.fao.org/docrep/X0490E/x0490e0k.htm
# source: http://edis.ifas.ufl.edu/pdffiles/ae/ae45900.pdf
s = 4098.0 * 610.8 * math.e**((17.27 * T_iC)/(T_iC + 273.3)) / ((T_iC + 273.3)**2.0)
# ############command to print out all array data
# np.set_printoptions(threshold=np.inf)
# print("s:{}".format(s))
# np.set_printoptions(threshold=1000)
# ############
# net all wave radiation above the crop surface == above the canopy [W m-2]
# R_n = totalSolarIrradianceToPlants
# source: (Stanghellini, 1987)
R_n = 0.86 * (1.0 - np.exp(-0.7 * L)) * I_s
# The Penman-Monteith equation
Q_lh = s * (R_n - energyBalanceConstant.F) / (s + gamma_star) + (energyBalanceConstant.rho * energyBalanceConstant.C_p * D / r_b) / (s + gamma_star)
# when L (leaf area index is 0.0 Q_lh (r_b and r_c) beomes Nan. To avoid it, Nan is converted into 0.0)
Q_lh = np.nan_to_num(Q_lh)
# ############command to print out all array data
# np.set_printoptions(threshold=np.inf)
# print("Q_lh:{}".format(Q_lh))
# np.set_printoptions(threshold=1000)
# ############
# simulatorClass.r_a = r_a
# print("r_a.shape:{}".format(r_a.shape))
# simulatorClass.L = L
# print(L.shape)
# simulatorClass.r_b = r_b
# print(r_b.shape)
# simulatorClass.e_a = e_a
# print(e_a.shape)
# simulatorClass.e_s = e_s
# print(e_s.shape)
# simulatorClass.r_s = r_s
# print(r_s.shape)
# simulatorClass.r_c = r_c
# print(r_c.shape)
# # simulatorClass.gamma = gamma
# # print(gamma.shape)
# simulatorClass.gamma_star = gamma_star
# print(gamma_star.shape)
# simulatorClass.s = s
# print(s.shape)
# simulatorClass.R_n = R_n
# print(R_n.shape)
return Q_lh
def getSturatedAndActualVaporPressure(actualT, relativeHumidity):
e_s = 610.7 * 10.0**((7.5 * actualT)/(237.3+actualT))
e_a = e_s * relativeHumidity
return e_s, e_a
def getQ_v(simulatorClass, Q_sr, Q_lh, Q_sh, Q_lw):
'''
consider the greenhouse size (floor area, roofa are, wall area), calc Q_v
'''
# unit: W
Q_srW = Q_sr * constant.greenhouseFloorArea
# unit: W
Q_lhW = Q_lh * constant.greenhouseCultivationFloorArea
# unit: W
Q_shW = Q_sh * (constant.greenhouseTotalRoofArea + constant.greenhouseSideWallArea)
# unit: W
# it was assumed the greenhouse ceiling area (not the roof area because it would be strange that we get more long wave radiation as the angle of the roof increases) was same as the floor area.
Q_lwW = Q_lw * constant.greenhouseFloorArea
# unit: W
# In the default definition, when Q_lhW, Q_shW, and Q_lwW are positive, heat energy gets out of the greenhouse. Thus, the unit was converted into negative value
Q_vW = Q_srW - (Q_lhW + Q_shW + Q_lwW)
# ############command to print out all array data
# np.set_printoptions(threshold=np.inf)
# print("simulatorClass.shootFreshMassList:{}".format(simulatorClass.shootFreshMassList))
# print("simulatorClass.summerPeriodFlagArray:{}".format(simulatorClass.summerPeriodFlagArray))
# np.set_printoptions(threshold=1000)
# ############
# if it is the summer period or the preparation day for the next cultivation (the fresh mass is zero), let Q_vw zero.
Q_vW = np.array([0.0 if simulatorClass.shootFreshMassList[i] == 0.0 or simulatorClass.summerPeriodFlagArray[i] == 1.0 else Q_vW[i] for i in range(Q_vW.shape[0])])
simulatorClass.Q_vW["coolingOrHeatingEnergy W"] = Q_vW
simulatorClass.Q_srW["solarIrradianceToPlants W"] = Q_srW
simulatorClass.Q_lhW["sensibleHeatFromConductionAndConvection W"] = Q_lhW
simulatorClass.Q_shW["latentHeatByTranspiration W"] = Q_shW
simulatorClass.Q_lwW["longWaveRadiation W"] = Q_lwW
# unit: W m-2
return Q_vW / constant.greenhouseFloorArea
def getGHHeatingEnergyCostForPlants(requiredHeatingEnergyForPlants, simulatorClass):
# ############command to print out all array data
# np.set_printoptions(threshold=np.inf)
# print("requiredHeatingEnergyForPlants:{}".format(requiredHeatingEnergyForPlants))
# np.set_printoptions(threshold=1000)
# ############
# unit: W
requiredHeatingEnergyConsumptionForPlants = {"W": requiredHeatingEnergyForPlants / constant.heatingEquipmentEfficiency}
# unit conversion: W (= J sec-1) -> MJ
requiredHeatingEnergyConsumptionForPlants["MJ"] = requiredHeatingEnergyConsumptionForPlants["W"] * constant.secondperMinute * constant.minuteperHour / 1000000.0
# unit conversion: MJ -> ft3
requiredHeatingEnergyConsumptionForPlants["ft3"] = requiredHeatingEnergyConsumptionForPlants["MJ"] / constant.naturalGasSpecificEnergy["MJ ft-3"]
# print("requiredHeatingEnergyConsumptionForPlants:{}".format(requiredHeatingEnergyConsumptionForPlants))
# get the price of natural gas
fileName = constant.ArizonaPriceOfNaturalGasDeliveredToResidentialConsumers
# import the file removing the header
fileData = Util.readData(fileName, relativePath="", skip_header=5, d=',')
# print ("fileData.shape:{}".format(fileData.shape))
# reverse the file data becasue the data starts from the newest date. requiredHeatingEnergyForPlants starts from the old time.
fileData = fileData[::-1]
# ############command to print out all array data
# np.set_printoptions(threshold=np.inf)
# print ("fileData:{}".format(fileData))
# np.set_printoptions(threshold=1000)
# ############
# unit ft3 month-1
monthlyRequiredGHHeatingEnergyForPlants = getMonthlyRequiredGHHeatingEnergyForPlants(requiredHeatingEnergyConsumptionForPlants["ft3"], simulatorClass)
# set the data to the object
simulatorClass.monthlyRequiredGHHeatingEnergyForPlants = monthlyRequiredGHHeatingEnergyForPlants
monthlyHeatingCostForPlants = np.zeros(monthlyRequiredGHHeatingEnergyForPlants.shape[0])
index = 0
for fileDataLine in fileData:
# split first column into month and year
month = strptime(fileDataLine[0].split()[0],'%b').tm_mon
# print("month:{}".format(month))
year = fileDataLine[0].split()[1]
# unit: USD thousand ft-3
monthlyNaturalGasPrice = float(fileDataLine[1])
# print("monthlyNaturalGasPrice:{}".format(monthlyNaturalGasPrice))
# exclude the data out of the set start month and end month
if datetime.date(int(year), int(month), 1) + relativedelta(months=1) <= Util.getStartDateDateType() or \
datetime.date(int(year), int(month), 1) > Util.getEndDateDateType():
# if datetime.date(int(year[i]), int(month[i]), 1) + relativedelta(months=1) <= Util.getStartDateDateType() or \
# datetime.date(int(year[i]), int(month[i]), 1) > Util.getEndDateDateType():
continue
monthlyHeatingCostForPlants[index] = (monthlyNaturalGasPrice / 1000.0) * monthlyRequiredGHHeatingEnergyForPlants[index]
# print "monthlyData:{}".format(monthlyData)
index += 1
# print("monthlyHeatingCostForPlants:{}".format(monthlyHeatingCostForPlants))
totalHeatingCostForPlants = sum(monthlyHeatingCostForPlants)
return totalHeatingCostForPlants
def getMonthlyRequiredGHHeatingEnergyForPlants(requiredHeatingEnergyConsumptionForPlants, simulatorClass):
month = simulatorClass.getMonth()
numOfMonths = Util.getSimulationMonthsInt()
monthlyRequiredGHHeatingEnergyForPlants = np.zeros(numOfMonths)
monthIndex = 0
# insert the initial value
monthlyRequiredGHHeatingEnergyForPlants[0] = requiredHeatingEnergyConsumptionForPlants[0]
for i in range(1, month.shape[0]):
monthlyRequiredGHHeatingEnergyForPlants[monthIndex] += requiredHeatingEnergyConsumptionForPlants[i]
if month[i - 1] != month[i]:
# move onto the next month
monthIndex += 1
return monthlyRequiredGHHeatingEnergyForPlants
def getGHCoolingEnergyCostForPlants(requiredCoolingEnergyForPlants, simulatorClass):
# ############command to print out all array data
# np.set_printoptions(threshold=np.inf)
# print("requiredCoolingEnergyForPlants:{}".format(requiredCoolingEnergyForPlants))
# np.set_printoptions(threshold=1000)
# ############
# unit: W
requiredCoolingEnergyConsumptionForPlants = {"W": requiredCoolingEnergyForPlants / constant.PadAndFanCOP}
# unit conversion W -> kWh
requiredCoolingEnergyConsumptionForPlants["kWh"] = requiredCoolingEnergyConsumptionForPlants["W"] / 1000.0
# ############command to print out all array data
# np.set_printoptions(threshold=np.inf)
# print("requiredCoolingEnergyConsumptionForPlants[\"kWh\"]:{}".format(requiredCoolingEnergyConsumptionForPlants["kWh"]))
# np.set_printoptions(threshold=1000)
# ############
# get the imported electricity retail price
# unit: cent kWh-1
monthlyElectricityRetailPrice = simulatorClass.monthlyElectricityRetailPrice
# print("monthlyElectricityRetailPrice:{}".format(monthlyElectricityRetailPrice))
# unit kWh month-1
monthlyRequiredGHCoolingEnergyForPlants = getMonthlyRequiredGHCoolingEnergyForPlants(requiredCoolingEnergyConsumptionForPlants["kWh"], simulatorClass)
# set the data to the object
simulatorClass.monthlyRequiredGHCoolingEnergyForPlants = monthlyRequiredGHCoolingEnergyForPlants
# unit: usd month-1
monthlyCoolingCostForPlants = np.zeros(monthlyRequiredGHCoolingEnergyForPlants.shape[0])
index = 0
for monthlyData in monthlyElectricityRetailPrice:
year = monthlyData[1]
month = monthlyData[0]
# exclude the data out of the set start month and end month
# print("monthlyData:{}".format(monthlyData))
if datetime.date(int(year), int(month), 1) + relativedelta(months=1) <= Util.getStartDateDateType() or \
datetime.date(int(year), int(month), 1) > Util.getEndDateDateType():
continue
# the electricity retail cost for cooling. unit: USD month-1
monthlyCoolingCostForPlants[index] = (monthlyData[2] / 100.0 ) * monthlyRequiredGHCoolingEnergyForPlants[index]
index += 1
# print("monthlyCoolingCostForPlants:{}".format(monthlyCoolingCostForPlants))
totalCoolingCostForPlants = sum(monthlyCoolingCostForPlants)
return totalCoolingCostForPlants
# electricityCunsumptionByPad = getElectricityCunsumptionByPad(simulatorClass)
# electricityCunsumptionByFan = getElectricityCunsumptionByFan(simulatorClass)
# def getElectricityCunsumptionByPad(simulatorClass):
# def getElectricityCunsumptionByFan(simulatorClass):
def getMonthlyRequiredGHCoolingEnergyForPlants(requiredCoolingEnergyConsumptionForPlants, simulatorClass):
month = simulatorClass.getMonth()
numOfMonths = Util.getSimulationMonthsInt()
monthlyRequiredGHCoolingEnergyForPlants = np.zeros(numOfMonths)
monthIndex = 0
# insert the initial value
monthlyRequiredGHCoolingEnergyForPlants[0] = requiredCoolingEnergyConsumptionForPlants[0]
for i in range(1, month.shape[0]):
monthlyRequiredGHCoolingEnergyForPlants[monthIndex] += requiredCoolingEnergyConsumptionForPlants[i]
if month[i - 1] != month[i]:
# move onto the next month
monthIndex += 1
return monthlyRequiredGHCoolingEnergyForPlants
|
{"/OPVFilm.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/ShadingCurtain.py"], "/CropElectricityYieldProfitMINLP.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelS_Pearson1997.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/PlantGrowthModelS_Pearson1997Constant.py", "/Lettuce.py"], "/GreenhouseEnergyBalanceConstant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/Util.py": ["/CropElectricityYeildSimulatorConstant.py"], "/SolarIrradianceMultiSpanRoof.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/GreenhouseEnergyBalance.py": ["/Lettuce.py", "/CropElectricityYeildSimulatorConstant.py", "/GreenhouseEnergyBalanceConstant.py", "/Util.py"], "/SimulatorMain.py": ["/CropElectricityYeildSimulator1.py", "/Util.py", "/CropElectricityYeildSimulatorConstant.py"], "/CropElectricityYieldProfitRLShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/ShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelValidation.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulator1.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulatorDetail.py": ["/ShadingCurtain.py", "/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/Lettuce.py", "/PlantGrowthModelS_Pearson1997.py", "/SolarIrradianceMultiSpanRoof.py", "/GreenhouseEnergyBalance.py"], "/PlantGrowthModelS_Pearson1997Constant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/SimulatorClass.py": ["/CropElectricityYeildSimulatorConstant.py"], "/Lettuce.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/plantGrowthModelE_J_VanHenten.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py"]}
|
8,662
|
kensaku-okada/Greenhouse-with-OPV-film-Model
|
refs/heads/master
|
/SimulatorMain.py
|
# -*- coding: utf-8 -*-
#######################################################
# author :Kensaku Okada [kensakuokada@email.arizona.edu]
# create date : 19 Dec 2017
# last edit date: 19 Dec 2017
######################################################
##########import package files##########
# from scipy import stats
import datetime
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
import math
import CropElectricityYeildSimulator1 as Simulator1
# import TwoDimLeastSquareAnalysis as TwoDimLS
import Util
import CropElectricityYeildSimulatorConstant as constant
# import importlib
case = "OneCaseSimulation"
# case = "OptimizeOnlyOPVCoverageRatio"
# case = "OptimizationByMINLPSolver"
if case == "OneCaseSimulation":
print("run OneCaseSimulation")
# get the 2-D data for least square method
simulatorClass = Simulator1.simulateCropElectricityYieldProfit1()
# print "profitVSOPVCoverageData:{}".format(profitVSOPVCoverageData)
print("OneCaseSimulation finished")
# ####################################################################################################
# Stop execution here...
sys.exit()
# Move the above line to different parts of the assignment as you implement more of the functionality.
# ####################################################################################################
# # Least Square method
# if case == "LeastSquareMethod":
# print("run LeastSquareMethod")
#
# # get the 2-D data for least square method
# simulatorClass = Simulator1.simulateCropElectricityYieldProfit1()
# # print "profitVSOPVCoverageData:{}".format(profitVSOPVCoverageData)
#
# # create the instance
# twoDimLeastSquare = TwoDimLS.TwoDimLeastSquareAnalysis(profitVSOPVCoverageData)
# # print "twoDimLeastSquare.getXaxis():{}".format(twoDimLeastSquare.getXAxis())
#
# x = twoDimLeastSquare.getXAxis()
# y = twoDimLeastSquare.getYAxis()
#
# ########################### 10-fold CV (Cross Validation)
# NumOfFold = 10
# maxorder = 15
# k10BestPolyOrder, min_log_mean_10cv_loss = twoDimLeastSquare.runCrossValidation(NumOfFold, maxorder, x, y,
# randomize_data=True,
# cv_loss_title='10-fold CV Loss',
# filepath='./exportData/10fold-CV.png')
#
# # curve fitting (least square method) with given order w
# w = twoDimLeastSquare.getApproximatedFittingCurve(k10BestPolyOrder)
#
# # This polyfit is just for generating non-optimal order figure. Commend out this except debugging or experiment
# w = np.polyfit(x, y, 15)
# w = w[::-1]
#
# # plot the best order curve with the data points
# Util.plotDataAndModel(x, y, w, filepath='./exportData/bestPolynomialKFold.png')
# print ('\n======================')
# print ('10-fold the best order = {0}. loss = {1}, func coefficients w = {2}'.format(k10BestPolyOrder, min_log_mean_10cv_loss, w))
#
# ########################### LOOCV (Leave One Out Cross Validation)
# NumOfFold = twoDimLeastSquare.getXAxis().shape[0]
# loocv_best_poly, min_log_mean_loocv_loss = twoDimLeastSquare.runCrossValidation(NumOfFold, maxorder, x, y,
# randomize_data=True,
# cv_loss_title='LOOCV Loss',
# filepath='./exportData/LOOCV.png')
#
# # curve fitting (least square method) with given order w
# wLOOCV = twoDimLeastSquare.getApproximatedFittingCurve(k10BestPolyOrder)
# # This polyfit is just for generating non-optimal order figure. Commend out this except debugging or experiment
# # wLOOCV = np.polyfit(x, y, 8)
# # wLOOCV = wLOOCV[::-1]
#
# # plot the best order curve with the data points
# Util.plotDataAndModel(x, y, wLOOCV, filepath='./exportData/bestPolynomialLOOCV.png')
# print ('\n======================')
# print ('\n(LOOCV) the best order = {0}. loss = {1}, func coefficients w = {2}'.format(loocv_best_poly, min_log_mean_loocv_loss, w))
elif case == "OptimizeOnlyOPVCoverageRatio":
# print ("run Simulator1.simulateCropElectricityYieldProfit1")
# simulatorClass = Simulator1.simulateCropElectricityYieldProfit1()
print ("run Simulator1.optimizeOPVCoverageRatio")
####################################################################################################
################ parameter preparation for optimization of OPV coverage ratio start ################
####################################################################################################
# x-axis
OPVCoverageDelta = 0.01
# OPVCoverageDelta = 0.001
# the array for x-axis (OPV area [m^2])
OPVCoverages = np.array([i * 0.01 for i in range (0, int(1.0/OPVCoverageDelta)+1)])
# print("OPVCoverages:{}".format(OPVCoverages))
# total DLI to plants
totalDLIstoPlants = np.zeros(OPVCoverages.shape[0], dtype=float)
# electricity yield for a given period: [kwh] for a given period
totalkWhopvouts = np.zeros(OPVCoverages.shape[0], dtype=float)
totalkWhopvoutsPerRoofArea = np.zeros(OPVCoverages.shape[0], dtype=float)
totalkWhopvoutsPerGHFloorArea = np.zeros(OPVCoverages.shape[0], dtype=float)
# monthly electricity sales per area with each OPV film coverage [USD/month]
# monthlyElectricitySalesListEastRoof = np.zeros(OPVCoverages.shape[0], Util.getSimulationMonthsInt()), dtype=float)
# monthlyElectricitySalesListWestRoof = np.zeros(OPVCoverages.shape[0], Util.getSimulationMonthsInt()), dtype=float)
# electricity sales with each OPV film coverage [USD]
totalElectricitySales = np.zeros(OPVCoverages.shape[0], dtype=float)
totalElectricitySalesPerOPVArea = np.zeros(OPVCoverages.shape[0], dtype=float)
totalElectricitySalesPerGHFloorArea = np.zeros(OPVCoverages.shape[0], dtype=float)
# electricitySalesListperAreaEastRoof = np.zeros(int(1.0/OPVCoverageDelta), dtype = float)
# electricitySalesListperAreaWestRoof = np.zeros(int(1.0/OPVCoverageDelta), dtype = float)
# electricity cost with each OPV film coverage [USD]
totalElectricityCosts = np.zeros(OPVCoverages.shape[0], dtype=float)
totalElectricityCostsPerOPVArea = np.zeros(OPVCoverages.shape[0], dtype=float)
totalElectricityCostsPerGHFloorArea = np.zeros(OPVCoverages.shape[0], dtype=float)
# electricity profit with each OPV film coverage [USD]
totalElectricityProfits = np.zeros(OPVCoverages.shape[0], dtype=float)
totalElectricityProfitsPerCultivationFloorArea = np.zeros(OPVCoverages.shape[0], dtype=float)
totalElectricityProfitsPerGHFloorArea = np.zeros(OPVCoverages.shape[0], dtype=float)
# plant yield for a given period. unit:
# totalGrowthFreshWeightsPerHead = np.zeros(OPVCoverages.shape[0], dtype=float)
totalGrowthFreshWeightsPerCultivationFloorArea = np.zeros(OPVCoverages.shape[0], dtype=float)
totalGrowthFreshWeightsPerGHFloorArea = np.zeros(OPVCoverages.shape[0], dtype=float)
# unit harvested fresh mass weight for a whole given period with each OPV film coverage. unit: kg m-2
totalHarvestedShootFreshMassPerCultivationFloorAreaKgPerDay = np.zeros(OPVCoverages.shape[0], dtype=float)
# plant sales per square meter with each OPV film coverage: [USD/m^2] totalPlantSaleses =
totalPlantSalesesPerCultivationFloorArea = np.zeros(OPVCoverages.shape[0], dtype=float)
totalPlantSalesesPerGHFloorArea = np.zeros(OPVCoverages.shape[0], dtype=float)
# plant cost per square meter with each OPV film coverage: [USD/m^2]
totalPlantCostsPerGHFloorArea = np.zeros(OPVCoverages.shape[0], dtype = float)
# plant profit per square meter with each OPV film coverage: [USD/m^2]
totalPlantProfitsPerGHFloorArea = np.zeros(OPVCoverages.shape[0], dtype=float)
# plant profit with each OPV film coverage: [USD/m^2]
totalPlantProfits = np.zeros(OPVCoverages.shape[0], dtype=float)
# economicProfit summing the electricity and plant profit [USD]
totalEconomicProfits = np.zeros(OPVCoverages.shape[0], dtype=float)
# economicProfit summing the electricity and plant profit per area [USD m-2]
economicProfitPerGHFloorArea = np.zeros(OPVCoverages.shape[0], dtype=float)
##################################################################################################
################ parameter preparation for optimization of OPV coverage ratio end ################
##################################################################################################
for i in range(0, OPVCoverages.shape[0]):
#set OPV coverage ratio [-]
constant.OPVAreaCoverageRatio = OPVCoverages[i]
# constantFilePath = os.path.dirname(__file__).replace('/', os.sep) + '\\' + 'CropElectricityYeildSimulatorConstant.py'
# os.execv(constantFilePath, [os.path.abspath(constantFilePath)])
# reload(constant)
# change the other relevant parameters
constant.OPVArea = OPVCoverages[i] * constant.greenhouseTotalRoofArea
constant.OPVAreaFacingEastOrNorthfacingRoof = OPVCoverages[i] * (constant.greenhouseRoofTotalAreaEastOrNorth / constant.greenhouseTotalRoofArea)
constant.OPVAreaFacingWestOrSouthfacingRoof = OPVCoverages[i] * (constant.greenhouseRoofTotalAreaWestOrSouth / constant.greenhouseTotalRoofArea)
print("i:{}, constant.OPVArea:{}".format(i, constant.OPVArea))
# run the simulation
simulatorClass = Simulator1.simulateCropElectricityYieldProfit1()
# total DLI to plant during the whole simulation days with each OPV coverage ratio
totalDLIstoPlants[i] = sum(simulatorClass.totalDLItoPlants)
# store the data from the simulator
# unit: kwh
totalkWhopvouts[i] = sum(simulatorClass.totalkWhopvoutPerday)
# unit: kwh/m^2
# print("totalkWhopvoutsPerRoofArea = sum(simulatorClass.totalkWhopvoutPerAreaPerday):{}".format(sum(simulatorClass.totalkWhopvoutPerAreaPerday)))
totalkWhopvoutsPerRoofArea[i] = sum(simulatorClass.totalkWhopvoutPerAreaPerday)
totalkWhopvoutsPerGHFloorArea[i] = totalkWhopvouts[i] / constant.greenhouseFloorArea
# print("simulatorClass.totalElectricitySales:{}".format(simulatorClass.totalElectricitySales))
# unit:: USD
totalElectricitySales[i] = simulatorClass.totalElectricitySales
# print("simulatorClass.totalElectricitySalesPerAreaPerMonth:{}".format(simulatorClass.totalElectricitySalesPerAreaPerMonth))
# unit: USD/m^2
totalElectricitySalesPerOPVArea[i] = sum(simulatorClass.totalElectricitySalesPerAreaPerMonth)
totalElectricitySalesPerGHFloorArea[i] = totalElectricitySales[i] / constant.greenhouseFloorArea
# unit: USD
# print("simulatorClass.totalOPVCostUSDForDepreciation:{}".format(simulatorClass.totalOPVCostUSDForDepreciation))
totalElectricityCosts[i] = simulatorClass.totalOPVCostUSDForDepreciation
# unit: USD/m^2
# print("simulatorClass.getOPVCostUSDForDepreciationPerOPVArea:{}".format(simulatorClass.getOPVCostUSDForDepreciationPerOPVArea()))
totalElectricityCostsPerOPVArea[i] = simulatorClass.getOPVCostUSDForDepreciationPerOPVArea()
totalElectricityCostsPerGHFloorArea[i] = totalElectricityCosts[i] / constant.greenhouseFloorArea
# electricity profits
totalElectricityProfits[i] = totalElectricitySales[i] - totalElectricityCosts[i]
# electricity profits per greenhouse floor. unit: USD/m^2
totalElectricityProfitsPerGHFloorArea[i] = totalPlantSalesesPerGHFloorArea[i] - totalElectricityCostsPerGHFloorArea[i]
# plant yield for a given period. unit:kg
# totalGrowthFreshWeightsPerHead[i] =
totalGrowthFreshWeightsPerCultivationFloorArea[i] = sum(simulatorClass.shootFreshMassPerAreaKgPerDay)
totalGrowthFreshWeightsPerGHFloorArea[i] = totalGrowthFreshWeightsPerCultivationFloorArea[i] * constant.greenhouseCultivationFloorArea / constant.greenhouseFloorArea
# unit harvested fresh mass weight for a whole given period with each OPV film coverage. unit: kg m-2
# totalHarvestedShootFreshMassPerAreaKgPerHead[i] =
totalHarvestedShootFreshMassPerCultivationFloorAreaKgPerDay[i] = sum(simulatorClass.harvestedShootFreshMassPerAreaKgPerDay)
# plant sales per square meter with each OPV film coverage: [USD/m^2]
# print("simulatorClass.totalPlantSalesperSquareMeter:{}".format(simulatorClass.totalPlantSalesperSquareMeter))
totalPlantSalesesPerCultivationFloorArea[i] = simulatorClass.totalPlantSalesperSquareMeter
# print("simulatorClass.totalPlantSalesPerGHFloorArea:{}".format(simulatorClass.totalPlantSalesPerGHFloorArea))
totalPlantSalesesPerGHFloorArea[i] = simulatorClass.totalPlantSalesPerGHFloorArea
# plant cost per square meter with each OPV film coverage: [USD/m^2]
# print("simulatorClass.totalPlantProductionCostPerGHFloorArea:{}".format(simulatorClass.totalPlantProductionCostPerGHFloorArea))
totalPlantCostsPerGHFloorArea[i] = simulatorClass.totalPlantProductionCostPerGHFloorArea
# plant profit per square meter with each OPV film coverage: [USD/m^2]
totalPlantProfitsPerGHFloorArea[i] = totalPlantSalesesPerGHFloorArea[i] - totalPlantCostsPerGHFloorArea[i]
totalPlantProfits[i] = totalPlantProfitsPerGHFloorArea[i] * constant.greenhouseFloorArea
# plant profit with each OPV film coverage: [USD/m^2]
totalEconomicProfits[i] = totalElectricityProfits[i] + totalPlantProfitsPerGHFloorArea[i] * constant.greenhouseFloorArea
economicProfitPerGHFloorArea[i] = simulatorClass.economicProfitPerGHFloorArea
######################################################
##### display the optimization results start #########
######################################################
# print "plantCostperSquareMeter:{}".format(plantCostperSquareMeter)
# print "unitDailyHarvestedFreshWeightList:{}".format(unitDailyHarvestedFreshWeightList)
# print "plantSalesperSquareMeterList:{}".format(plantSalesperSquareMeterList)
################# plot the electricity yield with different OPV coverage for given period #################
title = "total electricity sales per GH floor area vs OPV film"
xAxisLabel = "OPV Coverage Ratio [-]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
yAxisLabel = "electricity sales per GH floor area[USD/m^2]"
Util.plotData(OPVCoverages, totalElectricitySalesPerGHFloorArea, title, xAxisLabel, yAxisLabel)
Util.saveFigure(title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
######################################################################################## #############
################# plot the electricity yield with different OPV coverage for given period #################
title = "harvested plant weights vs OPV film"
xAxisLabel = "OPV Coverage Ratio [-]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
yAxisLabel = "harvested plant weight [kg]"
Util.plotData(OPVCoverages, totalHarvestedShootFreshMassPerCultivationFloorAreaKgPerDay, title, xAxisLabel, yAxisLabel)
Util.saveFigure(title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
######################################################################################## #############
################# plot the electricity yield with different OPV coverage for given period #################
title = "DLI to plants vs OPV film"
xAxisLabel = "OPV Coverage Ratio [-]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
yAxisLabel = "DLI to plants [mol/m^2/day]"
Util.plotData(OPVCoverages, totalDLIstoPlants, title, xAxisLabel, yAxisLabel)
Util.saveFigure(title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
######################################################################################## #############
################## plot various sales and cost
plotDataSet = np.array([totalPlantSalesesPerGHFloorArea, totalPlantCostsPerGHFloorArea, totalElectricitySalesPerGHFloorArea, totalElectricityCostsPerGHFloorArea])
labelList = np.array(["totalPlantSalesesPerGHFloorArea", "totalPlantCostsPerGHFloorArea", "totalElectricitySalesPerGHFloorArea", "totalElectricityCostsPerGHFloorArea"])
title = "Various sales and cost"
xAxisLabel = "time [day]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
yAxisLabel = "Prcie per GH Floor area [USD/m^2]"
Util.plotMultipleData(np.linspace(0, OPVCoverages.shape[0], OPVCoverages.shape[0]), plotDataSet, labelList, title, xAxisLabel, yAxisLabel)
Util.saveFigure(title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
#######################################################################
################# plot the electricity yield with different OPV coverage for given period #################
title = "electricity yield with a given area vs OPV film"
xAxisLabel = "OPV Coverage Ratio [-]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
yAxisLabel = "electricity yield [kwh]"
Util.plotData(OPVCoverages, totalkWhopvouts, title, xAxisLabel, yAxisLabel)
Util.saveFigure(title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
######################################################################################## #############
################# plot the plant profit with different OPV coverage for given period #################
title = "plant profit with a given area vs OPV film"
xAxisLabel = "OPV Coverage Ratio [-]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
yAxisLabel = "plant profit for a given period [USD]"
Util.plotData(OPVCoverages, totalPlantProfitsPerGHFloorArea, title, xAxisLabel, yAxisLabel)
Util.saveFigure(title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
######################################################################################## #############
######################## plot by two y-axes ##########################
title = "plant yield per area and electricity yield vs OPV film"
xAxisLabel = "OPV Coverage Ratio [-]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
yAxisLabel1 = "plant fresh weight per cultivation floor for given period [kg/m^2]"
yAxisLabel2 = "Electricity yield [kWh]"
yLabel1 = "totalGrowthFreshWeights * greenhouseCultivationFloorArea"
yLabel2 = "electricityYield[Kwh]"
Util.plotTwoDataMultipleYaxes(OPVCoverages, totalGrowthFreshWeightsPerCultivationFloorArea * constant.greenhouseCultivationFloorArea, \
totalkWhopvouts, title, xAxisLabel, yAxisLabel1, yAxisLabel2, yLabel1, yLabel2)
Util.saveFigure(title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
#######################################################################
######################## plot by two y-axes ##########################
title = "plant yield per area and electricity yield per foot print vs OPV film"
xAxisLabel = "OPV Coverage Ratio [-]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
yAxisLabel1 = "plant fresh weight per foot print for given period [kg/m^2]"
yAxisLabel2 = "Electricity yield per foot print [kW*h/m^2]"
yLabel1 = "totalGrowthFreshWeightsPerGHFloorArea"
yLabel2 = "totalkWhopvoutsPerGHFloorArea"
Util.plotTwoDataMultipleYaxes(OPVCoverages, totalGrowthFreshWeightsPerGHFloorArea, \
totalkWhopvoutsPerGHFloorArea, title, xAxisLabel, yAxisLabel1, yAxisLabel2, yLabel1, yLabel2)
Util.saveFigure(title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
# #######################################################################
# data export
Util.exportCSVFile(
np.array([OPVCoverages, totalkWhopvouts, totalkWhopvoutsPerGHFloorArea, totalGrowthFreshWeightsPerCultivationFloorArea * constant.greenhouseCultivationFloorArea,\
totalGrowthFreshWeightsPerGHFloorArea,totalHarvestedShootFreshMassPerCultivationFloorAreaKgPerDay ]).T, \
"PlantAndElectricityYieldWholeAndPerFootPrint")
Util.exportCSVFile(
np.array([OPVCoverages, totalElectricitySalesPerGHFloorArea, totalElectricityCostsPerGHFloorArea, totalPlantSalesesPerGHFloorArea, \
totalPlantCostsPerGHFloorArea,totalEconomicProfits, economicProfitPerGHFloorArea]).T, \
"SalesAndCostPerFootPrint")
# plotting this graph is the coal of this simulation!!!
################# plot the economic profit with different OPV coverage for given period
title = "whole economic profit with a given area vs OPV film"
xAxisLabel = "OPV Coverage Ratio [-]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
yAxisLabel = "economic profit for a given period [USD]"
Util.plotData(OPVCoverages, totalEconomicProfits, title, xAxisLabel, yAxisLabel)
Util.saveFigure(title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
# #######################################################################
################# plot the economic profit with different OPV coverage for given period per GH area
title = "whole economic profit per GH area vs OPV film"
xAxisLabel = "OPV Coverage Ratio [-]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
yAxisLabel = "economic profit for a given period [USD]"
Util.plotData(OPVCoverages, economicProfitPerGHFloorArea, title, xAxisLabel, yAxisLabel)
Util.saveFigure(title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
# #######################################################################
####################################################################################################
# Stop execution here...
# sys.exit()
# Move the above line to different parts of the assignment as you implement more of the functionality.
####################################################################################################
###########################################################################################################
########################### Mixed integer non-liner programming with constraints###########################
###########################################################################################################
elif case == "OptimizationByMINLPSolver":
print ("run SimulatorMINLPc.py")
########################################################################
#
# This is an example call of MIDACO 5.0
# -------------------------------------
#
# MIDACO solves Multi-Objective Mixed-Integer Non-Linear Problems:
#
#
# Minimize F_1(X),... F_O(X) where X(1,...N-NI) is CONTINUOUS
# and X(N-NI+1,...N) is DISCRETE
#
# subject to G_j(X) = 0 (j=1,...ME) equality constraints
# G_j(X) >= 0 (j=ME+1,...M) inequality constraints
#
# and bounds XL <= X <= XU
#
#
# The problem statement of this example is given below. You can use
# this example as template to run your own problem. To do so: Replace
# the objective functions 'F' (and in case the constraints 'G') given
# here with your own problem and follow the below instruction steps.
#
########################################################################
###################### OPTIMIZATION PROBLEM ########################
########################################################################
def inputParameters(x):
'''
substitute the parameters to the simulator
return: None
'''
# unit: [-]
OPVAreaCoverageRatio = x[0]
# set OPV coverage ratio [-]
constant.OPVAreaCoverageRatio = OPVAreaCoverageRatio
print("constant.OPVAreaCoverageRatio :{}".format(constant.OPVAreaCoverageRatio ))
# change the other relevant parameters
constant.OPVArea = OPVAreaCoverageRatio * constant.greenhouseTotalRoofArea
constant.OPVAreaFacingEastOrNorthfacingRoof = OPVAreaCoverageRatio * (constant.greenhouseRoofTotalAreaEastOrNorth / constant.greenhouseTotalRoofArea)
constant.OPVAreaFacingWestOrSouthfacingRoof = OPVAreaCoverageRatio * (constant.greenhouseRoofTotalAreaWestOrSouth / constant.greenhouseTotalRoofArea)
# unit: [days] <- be careful this!!!!!!!!!! The hour is calculated from the beginning of the year (Jan 1st 0 am)
shadingCurtainDeployStartDateSpring = x[1]
shadingCurtainDeployEndDateSpring = x[2]
shadingCurtainDeployStartDateFall = x[3]
shadingCurtainDeployEndDateFall = x[4]
# simulationEndDate = Util.getEndDateDateType()
year = Util.getStartDateDateType().year
shadingCurtainDeployStartDateSpring = datetime.date(year=year, month=1, day=1) + datetime.timedelta(days=shadingCurtainDeployStartDateSpring)
shadingCurtainDeployEndDateSpring = datetime.date(year=year, month=1, day=1) + datetime.timedelta(days=shadingCurtainDeployEndDateSpring)
shadingCurtainDeployStartDateFall = datetime.date(year=year, month=1, day=1) + datetime.timedelta(days=shadingCurtainDeployStartDateFall)
shadingCurtainDeployEndDateFall = datetime.date(year=year, month=1, day=1) + datetime.timedelta(days=shadingCurtainDeployEndDateFall)
print("shadingCurtainDeployStartDateSpring:{}".format(shadingCurtainDeployStartDateSpring))
print("shadingCurtainDeployEndDateSpring:{}".format(shadingCurtainDeployEndDateSpring))
print("shadingCurtainDeployStartDateFall:{}".format(shadingCurtainDeployStartDateFall))
print("shadingCurtainDeployEndDateFall:{}".format(shadingCurtainDeployEndDateFall))
# set the shading curtain deployment periods
constant.ShadingCurtainDeployStartMMSpring = shadingCurtainDeployStartDateSpring.month
constant.ShadingCurtainDeployStartDDSpring = shadingCurtainDeployStartDateSpring.day
constant.ShadingCurtainDeployEndMMSpring = shadingCurtainDeployEndDateSpring.month
constant.ShadingCurtainDeployEndDDSpring = shadingCurtainDeployEndDateSpring.day
constant.ShadingCurtainDeployStartMMFall = shadingCurtainDeployStartDateFall.month
constant.ShadingCurtainDeployStartDDFall = shadingCurtainDeployStartDateFall.day
constant.ShadingCurtainDeployEndMMFall = shadingCurtainDeployEndDateFall.month
constant.ShadingCurtainDeployEndDDFall = shadingCurtainDeployEndDateFall.day
print("constant.ShadingCurtainDeployStartMMFall:{}".format(constant.ShadingCurtainDeployStartMMFall))
print("constant.ShadingCurtainDeployStartDDFall:{}".format(constant.ShadingCurtainDeployStartDDFall))
print("constant.ShadingCurtainDeployEndMMFall:{}".format(constant.ShadingCurtainDeployEndMMFall))
print("constant.ShadingCurtainDeployEndDDFall:{}".format(constant.ShadingCurtainDeployEndDDFall))
return None
def problem_function(x):
'''
:param x: decision variables. In this model, the variables are pv module coverage ratio,
'''
f = [0.0] * 1 # Initialize array for objectives F(X)
g = [0.0] * 3 # Initialize array for constraints G(X)
# input the parameters at each iteration
inputParameters(x)
# Objective functions F(X)
# call the simulator
simulatorClass = Simulator1.simulateCropElectricityYieldProfit1()
# print("simulatorClass.economicProfitPerGHFloorArea:{}".format(simulatorClass.economicProfitPerGHFloorArea))
# since we need to maximize the objective function, the minus sign is added
f[0] = -simulatorClass.economicProfitPerGHFloorArea
# Equality constraints G(X) = 0 MUST COME FIRST in g[0:me-1]
# No eauality constraints
# Inequality constraints G(X) >= 0 MUST COME SECOND in g[me:m-1]
shadingCurtainDeployStartDateSpring = x[1]
shadingCurtainDeployEndDateSpring = x[2]
shadingCurtainDeployStartDateFall = x[3]
shadingCurtainDeployEndDateFall = x[4]
g[0] = shadingCurtainDeployEndDateSpring - (shadingCurtainDeployStartDateSpring + 1)
g[1] = shadingCurtainDeployStartDateFall - (shadingCurtainDeployEndDateSpring + 1)
g[2] = shadingCurtainDeployEndDateFall - (shadingCurtainDeployStartDateFall + 1)
# print("f:{}, g:{}".format(f,g))
return f, g
########################################################################
######################### MAIN PROGRAM #############################
########################################################################
key = 'Kensaku_Okada_(University_of_Arizona)_[ACADEMIC-SINGLE-USER]'
problem = {} # Initialize dictionary containing problem specifications
option = {} # Initialize dictionary containing MIDACO options
problem['@'] = problem_function # Handle for problem function name
########################################################################
### Step 1: Problem definition #####################################
########################################################################
# STEP 1.A: Problem dimensions
##############################
problem['o'] = 1 # Number of objectives
problem['n'] = 5 # Number of variables (in total)
problem['ni'] = 4 # Number of integer variables (0 <= ni <= n)
problem['m'] = 3 # Number of constraints (in total)
problem['me'] = 0 # Number of equality constraints (0 <= me <= m)
# STEP 1.B: Lower and upper bounds 'xl' & 'xu'
##############################################
# get the simulation period by hour [hours]
numOfSimulationDays = Util.getSimulationDaysInt()-1
# print("numOfSimulationDays:{}".format(numOfSimulationDays))
problem['xl'] = [0.0, 1, 1, 1, 1]
problem['xu'] = [1.0, numOfSimulationDays, numOfSimulationDays, numOfSimulationDays, numOfSimulationDays]
# STEP 1.C: Starting point 'x'
##############################
# start from the minimum values
# problem['x'] = problem['xl'] # Here for example: starting point = lower bounds
# # start from the middle values
# problem['x'] = [(problem['xl'][i] + problem['xu'][i])/2.0 for i in range(0, len(problem['xl'])) ] # start from the middle
# # start from the maximum values
# problem['x'] = problem['xu'] # Here for example: starting point = lower bounds
# print("problem['x']:{}".format(problem['x']))
# start from the minimum values for OPV coverage ratio and middle values for numOfSimulationDays, numOfSimulationDays, numOfSimulationDays, numOfSimulationDays
# problem['x'] = [0.0, 183, 183, 183, 183]
# start from the minimum values for numOfSimulationDays, numOfSimulationDays, numOfSimulationDays, numOfSimulationDays and middle value for OPV coverage ratio
# problem['x'] = [0.5, 1, 1, 1, 1]
# start from the max values for OPV coverage ratio and middle value for numOfSimulationDays, numOfSimulationDays, numOfSimulationDays, numOfSimulationDays
problem['x'] = [0.0, 183, 183, 183, 183]
########################################################################
### Step 2: Choose stopping criteria and printing options ###########
########################################################################
# STEP 2.A: Stopping criteria
#############################
# option['maxeval'] = 10000 # Maximum number of function evaluation (e.g. 1000000), 999999999 (-> disabled)
option['maxeval'] = 500 # Maximum number of function evaluation (e.g. 1000000), 999999999 (-> disabled)
option['maxtime'] = 60 * 60 * 24 # Maximum time limit in Seconds (e.g. 1 Day = 60*60*24)
# STEP 2.B: Printing options
############################
option['printeval'] = 10 # Print-Frequency for current best solution (e.g. 1000)
option['save2file'] = 1 # Save SCREEN and SOLUTION to TXT-files [0=NO/1=YES]
########################################################################
### Step 3: Choose MIDACO parameters (FOR ADVANCED USERS) ###########
########################################################################
# this parameter defines the accuracy for the constraint violation. It is considered an equality constraints (G(X)) to be feasible if |G(X)| <= PARAM(1).
# An inequality is considered feasible, if G(X) ≥ -PARAM(1). If the user sets PARAM(1) = 0, MIDACO uses a default accuracy of 0.001.
option['param1'] = 0.0 # ACCURACY
# this defines the initial seed for MIDACO's internal pseudo random number generator.
option['param2'] = 0.0 # SEED
option['param3'] = 0.0 # FSTOP
option['param4'] = 0.0 # ALGOSTOP
# option['param5'] = 500.0005 # EVALSTOP
option['param5'] = 0.0 # EVALSTOP
# This parameter forces MIDACO to focus its search process around the current best solution and
# thus makes it more greedy or local. The larger the FOCUS value, the closer MIDACO will focus its search on the current best solution.
# option['param6'] = 0.0 # FOCUS
# option['param6'] = 1.0 # FOCUS
option['param6'] = 10.0 # FOCUS
# option['param6'] = 20.0 # FOCUS
option['param7'] = 0.0 # ANTS
option['param8'] = 0.0 # KERNEL
# This parameter specifies a user given oracle parameter to the penalty function within MIDACO.
# This parameter is only relevant for constrained problems.
option['param9'] = 0.0 # ORACLE
option['param10'] = 0.0 # PARETOMAX
option['param11'] = 0.0 # EPSILON
option['param12'] = 0.0 # CHARACTER
########################################################################
### Step 4: Choose Parallelization Factor ############################
########################################################################
# option['parallel'] = 10 # Serial: 0 or 1, Parallel: 2,3,4,5,6,7,8...
option['parallel'] = 1 # Serial: 0 or 1, Parallel: 2,3,4,5,6,7,8...
########################################################################
############################ Run MIDACO ################################
########################################################################
# add the directory to import MIDACO files
sys.path.append("./MIDACO")
import midaco
if __name__ == '__main__':
solution = midaco.run(problem, option, key)
# print solution['f']
# print solution['g']
# print solution['x']
print("simulation finished.")
########################### Reinforcement learning (q learning)###########################
elif case == "ShadingCurtainReinforcementLearning":
# run simulateCropElectricityYieldProfit1 to set values to an object of CropElectricityYieldSimulator1
cropElectricityYieldSimulator1, qLearningAgentsShadingCurtain = Simulator1.simulateCropElectricityYieldProfitRLShadingCurtain()
|
{"/OPVFilm.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/ShadingCurtain.py"], "/CropElectricityYieldProfitMINLP.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelS_Pearson1997.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/PlantGrowthModelS_Pearson1997Constant.py", "/Lettuce.py"], "/GreenhouseEnergyBalanceConstant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/Util.py": ["/CropElectricityYeildSimulatorConstant.py"], "/SolarIrradianceMultiSpanRoof.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/GreenhouseEnergyBalance.py": ["/Lettuce.py", "/CropElectricityYeildSimulatorConstant.py", "/GreenhouseEnergyBalanceConstant.py", "/Util.py"], "/SimulatorMain.py": ["/CropElectricityYeildSimulator1.py", "/Util.py", "/CropElectricityYeildSimulatorConstant.py"], "/CropElectricityYieldProfitRLShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/ShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelValidation.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulator1.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulatorDetail.py": ["/ShadingCurtain.py", "/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/Lettuce.py", "/PlantGrowthModelS_Pearson1997.py", "/SolarIrradianceMultiSpanRoof.py", "/GreenhouseEnergyBalance.py"], "/PlantGrowthModelS_Pearson1997Constant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/SimulatorClass.py": ["/CropElectricityYeildSimulatorConstant.py"], "/Lettuce.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/plantGrowthModelE_J_VanHenten.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py"]}
|
8,663
|
kensaku-okada/Greenhouse-with-OPV-film-Model
|
refs/heads/master
|
/CropElectricityYieldProfitRLShadingCurtain.py
|
##########import package files##########
from scipy import stats
import datetime
import sys
import os as os
import numpy as np
import matplotlib.pyplot as plt
import math
import CropElectricityYeildSimulatorConstant as constant
import Util as util
import OPVFilm
#import Lettuce
import CropElectricityYeildSimulatorDetail as simulatorDetail
import QlearningAgentShadingCurtain as QRLshadingCurtain
import SimulatorClass as SimulatorClass
#######################################################
def simulateCropElectricityYieldProfitRLShadingCurtain():
'''
:return:
'''
print ("start modeling: datetime.datetime.now():{}".format(datetime.datetime.now()))
# declare the class
cropElectricityYieldSimulator1 = SimulatorClass.CropElectricityYieldSimulator1()
##########file import (TucsonHourlyOuterEinvironmentData) start##########
fileName = "20130101-20170101" + ".csv"
year, \
month, \
day, \
hour, \
hourlyHorizontalDiffuseOuterSolarIrradiance, \
hourlyHorizontalTotalOuterSolarIrradiance, \
hourlyHorizontalDirectOuterSolarIrradiance, \
hourlyHorizontalTotalBeamMeterBodyTemperature, \
hourlyAirTemperature, cropElectricityYieldSimulator1 = util.getArraysFromData(fileName, cropElectricityYieldSimulator1)
##########file import (TucsonHourlyOuterEinvironmentData) end##########
# set the values to the object
cropElectricityYieldSimulator1.setYear(year)
cropElectricityYieldSimulator1.setMonth(month)
cropElectricityYieldSimulator1.setDay(day)
cropElectricityYieldSimulator1.setHour(hour)
##########solar irradiance to OPV calculation start##########
# calculate with real data
# hourly average [W m^-2]
directSolarRadiationToOPVEastDirection, directSolarRadiationToOPVWestDirection, diffuseSolarRadiationToOPV, albedoSolarRadiationToOPV = \
simulatorDetail.calcOPVmoduleSolarIrradianceGHRoof(year, month, day, hour, hourlyHorizontalDiffuseOuterSolarIrradiance, \
hourlyHorizontalDirectOuterSolarIrradiance, "EastWestDirectionRoof")
# [W m^-2] per hour
totalSolarRadiationToOPV = (directSolarRadiationToOPVEastDirection + directSolarRadiationToOPVWestDirection) / 2.0 + diffuseSolarRadiationToOPV + albedoSolarRadiationToOPV
# # calculate without real data.
# simulatedDirectSolarRadiationToOPVEastDirection, \
# simulatedDirectSolarRadiationToOPVWestDirection, \
# simulatedDiffuseSolarRadiationToOPV, \
# simulatedAlbedoSolarRadiationToOPV = simulatorDetail.calcOPVmoduleSolarIrradianceGHRoof(year, month, day, hour)
# # [W m^-2] per hour
# simulatedTotalSolarRadiationToOPV = simulatedDirectSolarRadiationToOPVEastDirection + simulatedDirectSolarRadiationToOPVWestDirection + \
# simulatedDiffuseSolarRadiationToOPV + simulatedAlbedoSolarRadiationToOPV
# print "directSolarRadiationToOPV:{}".format(directSolarRadiationToOPV)
# print "diffuseSolarRadiationToOPV:{}".format(diffuseSolarRadiationToOPV)
# print "groundReflectedSolarradiationToOPV:{}".format(groundReflectedSolarradiationToOPV)
# unit change: [W m^-2] -> [umol m^-2 s^-1] == PPFD
directPPFDToOPVEastDirection = util.convertFromWattperSecSquareMeterToPPFD(directSolarRadiationToOPVEastDirection)
directPPFDToOPVWestDirection = util.convertFromWattperSecSquareMeterToPPFD(directSolarRadiationToOPVWestDirection)
diffusePPFDToOPV = util.convertFromWattperSecSquareMeterToPPFD(diffuseSolarRadiationToOPV)
groundReflectedPPFDToOPV = util.convertFromWattperSecSquareMeterToPPFD(albedoSolarRadiationToOPV)
totalPPFDToOPV = directPPFDToOPVEastDirection + directPPFDToOPVWestDirection + diffusePPFDToOPV + groundReflectedPPFDToOPV
# print"diffusePPFDToOPV.shape:{}".format(diffusePPFDToOPV.shape)
########## set the matrix to the object ###########
cropElectricityYieldSimulator1.setDirectPPFDToOPVEastDirection(directPPFDToOPVEastDirection)
cropElectricityYieldSimulator1.setDirectPPFDToOPVWestDirection(directPPFDToOPVWestDirection)
cropElectricityYieldSimulator1.setDiffusePPFDToOPV(diffusePPFDToOPV)
cropElectricityYieldSimulator1.setGroundReflectedPPFDToOPV(groundReflectedPPFDToOPV)
###################################################
# unit change: hourly [umol m^-2 s^-1] -> [mol m^-2 day^-1] == DLI :number of photons received in a square meter per day
directDLIToOPVEastDirection = util.convertFromHourlyPPFDWholeDayToDLI(directPPFDToOPVEastDirection)
directDLIToOPVWestDirection = util.convertFromHourlyPPFDWholeDayToDLI(directPPFDToOPVWestDirection)
diffuseDLIToOPV = util.convertFromHourlyPPFDWholeDayToDLI(diffusePPFDToOPV)
groundReflectedDLIToOPV = util.convertFromHourlyPPFDWholeDayToDLI(groundReflectedPPFDToOPV)
totalDLIToOPV = directDLIToOPVEastDirection + directDLIToOPVWestDirection + diffuseDLIToOPV + groundReflectedDLIToOPV
# print "directDLIToOPVEastDirection:{}".format(directDLIToOPVEastDirection)
# print "diffuseDLIToOPV.shape:{}".format(diffuseDLIToOPV.shape)
# print "groundReflectedDLIToOPV:{}".format(groundReflectedDLIToOPV)
########## set the matrix to the object ##########
cropElectricityYieldSimulator1.setDirectDLIToOPVEastDirection(directDLIToOPVEastDirection)
cropElectricityYieldSimulator1.setDirectDLIToOPVWestDirection(directDLIToOPVWestDirection)
cropElectricityYieldSimulator1.setDiffuseDLIToOPV(diffuseDLIToOPV)
cropElectricityYieldSimulator1.setGroundReflectedDLIToOPV(groundReflectedDLIToOPV)
##################################################
# ################## plot the difference of real data and simulated data start######################
# Title = "difference of the model output with real data and with no data"
# xAxisLabel = "time [hour]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
# yAxisLabel = "total Solar irradiance [W m^-2]"
# util.plotTwoData(np.linspace(0, simulationDaysInt * constant.hourperDay, simulationDaysInt * constant.hourperDay), \
# totalSolarRadiationToOPV, simulatedTotalSolarRadiationToOPV ,Title, xAxisLabel, yAxisLabel, "with real data", "wth no data")
# util.saveFigure(Title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
# ################## plot the difference of real data and simulated data end######################
# ################## plot the distribution of direct and diffuse PPFD start######################
# Title = "TOTAL outer PPFD to OPV"
# xAxisLabel = "time [hour]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
# yAxisLabel = "PPFD [umol m^-2 s^-1]"
# util.plotData(np.linspace(0, simulationDaysInt * constant.hourperDay, simulationDaysInt * constant.hourperDay), \
# directPPFDToOPV + diffusePPFDToOPV + groundReflectedPPFDToOPV, Title, xAxisLabel, yAxisLabel)
# util.saveFigure(Title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
# ################## plot the distribution of direct and diffuse PPFD end######################
# ################## plot the distribution of direct and diffuse solar DLI start######################
# Title = "direct and diffuse outer DLI to OPV"
# xAxisLabel = "time [day]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
# yAxisLabel = "DLI [mol m^-2 day^-1]"
# y1Label = "(directDLIToOPVEastDirection+directDLIToOPVWestDirection)/2.0"
# y2Label = "diffuseDLIToOPV"
# util.plotTwoData(np.linspace(0, simulationDaysInt, simulationDaysInt), (directDLIToOPVEastDirection+directDLIToOPVWestDirection)/2.0, diffuseDLIToOPV, Title,
# xAxisLabel, yAxisLabel, y1Label, y2Label)
# util.saveFigure(Title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
# ################## plot the distribution of direct and diffuse solar DLI end######################
# ################## plot the distribution of various DLI to OPV film start######################
# Title = "various DLI to OPV film"
# plotDataSet = np.array([directDLIToOPVEastDirection, directDLIToOPVWestDirection, diffuseDLIToOPV,
# groundReflectedDLIToOPV])
# labelList = np.array(["directDLIToOPVEastDirection", "directDLIToOPVWestDirection", "diffuseDLIToOPV",
# "groundReflectedDLIToOPV"])
# xAxisLabel = "time [day]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
# yAxisLabel = "DLI [mol m^-2 day^-1]"
# util.plotMultipleData(np.linspace(0, simulationDaysInt, simulationDaysInt), plotDataSet, labelList, Title,
# xAxisLabel, yAxisLabel)
# util.saveFigure(Title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
# ################## plot the distribution of various DLI to OPV film end######################
################## calculate the daily electricity yield per area start#####################
# TODO maybe we need to consider the tilt of OPV and OPV material for the temperature of OPV film. right now, just use the measured temperature
# get the daily electricity yield per area per day ([J/m^2] per day) based on the given light intensity ([Celsius],[W/m^2]).
dailyJopvoutperArea = simulatorDetail.calcDailyElectricityYieldSimulationperArea(hourlyHorizontalTotalBeamMeterBodyTemperature, \
directSolarRadiationToOPVEastDirection + directSolarRadiationToOPVWestDirection,
diffuseSolarRadiationToOPV,
albedoSolarRadiationToOPV)
# unit Exchange [J/m^2] -> [wh / m^2]
dailyWhopvoutperArea = util.convertFromJouleToWattHour(dailyJopvoutperArea)
# unit Exchange [Wh/ m^2] -> [kWh/m^2]
dailykWhopvoutperArea = util.convertWhTokWh(dailyWhopvoutperArea)
# ################### plot the electricity yield per area with given OPV film
# title = "electricity yield per area vs OPV film"
# xAxisLabel = "time [day]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
# yAxisLabel = "Electricity yield per OPV area [kWh/m^2/day]"
# util.plotData(np.linspace(0, simulationDaysInt, simulationDaysInt), dailykWhopvoutperArea, title, xAxisLabel, yAxisLabel)
# util.saveFigure(title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
################### calculate the daily electricity yield per area end#####################
################## calculate the daily electricity sales start#####################
# convert the year of each hour to the year to each day
yearOfeachDay = year[::24]
# convert the month of each hour to the month to each day
monthOfeachDay = month[::24]
# get the monthly electricity sales per area [USD/month/m^2]
monthlyElectricitySalesperArea = simulatorDetail.getMonthlyElectricitySalesperArea(dailyJopvoutperArea, yearOfeachDay, monthOfeachDay)
# set the value to the object
cropElectricityYieldSimulator1.setMonthlyElectricitySalesperArea(monthlyElectricitySalesperArea)
# print "cropElectricityYieldSimulator1.getMonthlyElectricitySalesperArea():{}".format(cropElectricityYieldSimulator1.getMonthlyElectricitySalesperArea())
################## calculate the daily electricity sales end#####################
##################calculate the electricity cost per area start######################################
if constant.ifConsiderOPVCost is True:
initialOPVCostUSD = constant.OPVPricePerAreaUSD * OPVFilm.getOPVArea(constant.OPVAreaCoverageRatio)
# [USD]
OPVCostUSDForDepreciation = initialOPVCostUSD * (util.getSimulationDaysInt() / constant.OPVDepreciationPeriodDays)
# set the value to the object
cropElectricityYieldSimulator1.setOPVCostUSDForDepreciationperArea(
OPVCostUSDForDepreciation / OPVFilm.getOPVArea(constant.OPVAreaCoverageRatio))
else:
# set the value to the object. the value is zero if not consider the purchase cost
cropElectricityYieldSimulator1.setOPVCostUSDForDepreciationperArea(0.0)
##################calculate the electricity cost per area end######################################
################## calculate the daily plant yield start#####################
# [String]
plantGrowthModel = constant.TaylorExpantionWithFluctuatingDLI
# cultivation days per harvest [days/harvest]
cultivationDaysperHarvest = constant.cultivationDaysperHarvest
# OPV coverage ratio [-]
OPVCoverage = constant.OPVAreaCoverageRatio
# boolean
hasShadingCurtain = constant.hasShadingCurtain
# PPFD [umol m^-2 s^-1]
ShadingCurtainDeployPPFD = constant.ShadingCurtainDeployPPFD
# calculate plant yield given an OPV coverage and model :daily [g/unit]. the shading curtain influence is considered in this function.
shootFreshMassList, unitDailyFreshWeightIncrease, accumulatedUnitDailyFreshWeightIncrease, unitDailyHarvestedFreshWeight = \
simulatorDetail.calcPlantYieldSimulation(plantGrowthModel, cultivationDaysperHarvest, OPVCoverage, \
(directPPFDToOPVEastDirection + directPPFDToOPVWestDirection) / 2.0, diffusePPFDToOPV, groundReflectedPPFDToOPV,
hasShadingCurtain, ShadingCurtainDeployPPFD, cropElectricityYieldSimulator1)
# set the values to the instance
cropElectricityYieldSimulator1.setShootFreshMassList(shootFreshMassList)
cropElectricityYieldSimulator1.setUnitDailyFreshWeightIncrease(unitDailyFreshWeightIncrease)
cropElectricityYieldSimulator1.setAccumulatedUnitDailyFreshWeightIncrease(accumulatedUnitDailyFreshWeightIncrease)
cropElectricityYieldSimulator1.setUnitDailyHarvestedFreshWeight(unitDailyHarvestedFreshWeight)
# the DLI to plants [mol/m^2/day]
TotalDLItoPlants = simulatorDetail.getTotalDLIToPlants(OPVCoverage, (directPPFDToOPVEastDirection + directPPFDToOPVWestDirection) / 2.0, diffusePPFDToOPV,
groundReflectedPPFDToOPV, \
hasShadingCurtain, ShadingCurtainDeployPPFD, cropElectricityYieldSimulator1)
# set the value to the instance
cropElectricityYieldSimulator1.setTotalDLItoPlantsBaselineShadingCuratin(TotalDLItoPlants)
# print "TotalDLItoPlants:{}".format(TotalDLItoPlants)
# print "TotalDLItoPlants.shape:{}".format(TotalDLItoPlants.shape)
# ######################### plot a graph showing only shootFreshMassList per unit
# title = "plant yield per head vs time (OPV coverage " + str(int(100 * OPVCoverage)) + "%)"
# xAxisLabel = "time [day]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
# yAxisLabel = "plant fresh weight[g/head]"
# util.plotData(np.linspace(0, util.getSimulationDaysInt(), util.getSimulationDaysInt()), shootFreshMassList, title, xAxisLabel, yAxisLabel)
# util.saveFigure(title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
# #######################################################################
# # unit conversion; get the plant yield per day per area: [g/unit] -> [g/m^2]
# shootFreshMassListperArea = util.convertUnitShootFreshMassToShootFreshMassperArea(shootFreshMassList)
# # unit conversion: [g/m^2] -> [kg/m^2]
# shootFreshMassListperAreaKg = util.convertFromgramTokilogram(shootFreshMassListperArea)
# ######################## plot a graph showing only shootFreshMassList per square meter
# title = "plant yield per area vs time (OPV coverage " + str(int(100 * OPVCoverage)) + "%)"
# xAxisLabel = "time [day]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
# yAxisLabel = "plant fresh weight[kg/m^2]"
# util.plotData(np.linspace(0, util.getSimulationDaysInt(), util.getSimulationDaysInt()), shootFreshMassListperAreaKg, title, xAxisLabel, yAxisLabel)
# util.saveFigure(title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
# ######################################################################
################## plot various unit Plant Yield vs time
plotDataSet = np.array([shootFreshMassList, unitDailyFreshWeightIncrease, accumulatedUnitDailyFreshWeightIncrease, unitDailyHarvestedFreshWeight])
labelList = np.array(["shootFreshMassList", "unitDailyFreshWeightIncrease", "accumulatedUnitDailyFreshWeightIncrease", "unitDailyHarvestedFreshWeight"])
title = "Various unit Plant Yield vs time (OPV coverage " + str(int(100 * OPVCoverage)) + "%)"
xAxisLabel = "time [day]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
yAxisLabel = "Unit plant Fresh Weight [g/unit]"
util.plotMultipleData(np.linspace(0, util.getSimulationDaysInt(), util.getSimulationDaysInt()), plotDataSet, labelList, title, xAxisLabel, yAxisLabel)
util.saveFigure(title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
###########################################################################
################## calculate the daily plant yield end#####################
################## calculate the daily plant sales start#####################
# unit conversion; get the daily plant yield per given period per area: [g/unit] -> [g/m^2]
dailyHarvestedFreshWeightperArea = util.convertUnitShootFreshMassToShootFreshMassperArea(unitDailyHarvestedFreshWeight)
# unit conversion: [g/m^2] -> [kg/m^2]1
dailyHarvestedFreshWeightperAreaKg = util.convertFromgramTokilogram(dailyHarvestedFreshWeightperArea)
# get the sales price of plant [USD/m^2]
# if the average DLI during each harvest term is more than 17 mol/m^2/day, discount the price
# TODO may need to improve the affect of Tipburn
dailyPlantSalesperSquareMeter = simulatorDetail.getPlantSalesperSquareMeter(year, dailyHarvestedFreshWeightperAreaKg, TotalDLItoPlants)
plantSalesperSquareMeter = sum(dailyPlantSalesperSquareMeter)
# print "dailyPlantSalesperSquareMeter.shape:{}".format(dailyPlantSalesperSquareMeter.shape)
print ("(The baseline) plantSalesperSquareMeter [USD/m^2]:{}".format(plantSalesperSquareMeter))
################## calculate the daily plant sales end#####################
################## calculate the daily plant cost start#####################
# plant operation cost per square meter for given simulation period [USD/m^2]
plantCostperSquareMeter = simulatorDetail.getPlantCostperSquareMeter(util.getSimulationDaysInt())
################## calculate the daily plant cost end#####################
################## calculate the plant profit start#######################
###### calculate the plant profit per square meter [USD/m^2]
plantProfitperSquareMeter = plantSalesperSquareMeter - plantCostperSquareMeter
# print "plantProfitperSquareMeterList[i]:{}".format(plantProfitperSquareMeterList[i])
# print "plantProfitperSquareMeterList[{}]:{}".format(i, plantProfitperSquareMeterList[i])
plantProfit = plantProfitperSquareMeter * constant.greenhouseCultivationFloorArea
# print "plantCostperSquareMeter:{}".format(plantCostperSquareMeter)
# print "unitDailyHarvestedFreshWeightList:{}".format(unitDailyHarvestedFreshWeightList)
# print "plantSalesperSquareMeterList:{}".format(plantSalesperSquareMeterList)
print ("(The baseline) plantProfit by normal simulation [USD]:{}".format(plantProfit))
################## calculate the plant profit end#######################
#####################################################################################################
################## reinforcement learning plant simulation start#####################################
#####################################################################################################
################## calculate the plant sales with RL shading curtain start##########################
if constant.isShadingCurtainReinforcementLearning:
# declare the instance for RL
# qLearningAgentsShadingCurtain = QRLshadingCurtain.QLearningAgentShadingCurtain(cropElectricityYieldSimulator1, \
# numTraining=1500, numTesting = 1, epsilon=0.18, gamma=0.999, alpha=0.2e-6)
qLearningAgentsShadingCurtain = QRLshadingCurtain.QLearningAgentShadingCurtain(cropElectricityYieldSimulator1, \
numTraining=1200, numTesting = 1, epsilon=0.18, gamma=0.99, alpha=0.2e-6)
# set values necessary for RL training/testing
# for dLIEachdayThroughInnerStructure on a certain day
hourlyInnerLightIntensityPPFDThroughInnerStructure = simulatorClass.getHourlyInnerLightIntensityPPFDThroughInnerStructure()
# set dLIThroughInnerStructure to the object
dLIThroughInnerStructure = util.convertFromHourlyPPFDWholeDayToDLI(hourlyInnerLightIntensityPPFDThroughInnerStructure)
qLearningAgentsShadingCurtain.setDLIThroughInnerStructure(dLIThroughInnerStructure)
################################ Training #################################
if constant.ifRunTraining:
#training the approximate q value function. returns the wegiths of q value function
qLearningAgentsShadingCurtain = simulatorDetail.trainWeightsRLShadingCurtainDayStep(hasShadingCurtain, qLearningAgentsShadingCurtain, simulatorClass)
# print ("qLearningAgentsShadingCurtain.weights:{}".format(qLearningAgentsShadingCurtain.weights))
################################ Save the trained weight #################################
# save the calculated weight by the training
if constant.ifSaveCalculatedWeight:
util.exportDictionaryAsCSVFile(qLearningAgentsShadingCurtain.weights, constant.fileNameQLearningTrainedWeight)
# load the calculated weight by the training
if constant.ifLoadWeight:
qLearningAgentsShadingCurtain.weights = util.importDictionaryAsCSVFile(constant.fileNameQLearningTrainedWeight, relativePath="")
print ("loaded qLearningAgentsShadingCurtain.weights:{}".format(qLearningAgentsShadingCurtain.weights))
################################ Testing ##################################
# with the trained q value function,
plantSalesperSquareMeterRLShadingCurtainList = simulatorDetail.testWeightsRLShadingCurtainDayStep(hasShadingCurtain, \
qLearningAgentsShadingCurtain, simulatorClass)
print ("(RL) plantSalesperSquareMeterRLShadingCurtain [USD/m^2]:{}".format(plantSalesperSquareMeterRLShadingCurtainList))
################## calculate the plant cost start#####################
# plant operation cost per square meter for given simulation period [USD/m^2]
# plantCostperSquareMeter = simulatorDetail.getPlantCostperSquareMeter(simulationDaysInt)
################## calculate the plant cost end#####################
################## calculate the plant economic profit start#######################
###### calculate the plant profit per square meter [USD/m^2]
plantProfitperSquareMeterRLShadingCurtainList = plantSalesperSquareMeterRLShadingCurtainList - plantCostperSquareMeter
# print "plantProfitperSquareMeterList[i]:{}".format(plantProfitperSquareMeterList[i])
# print "plantProfitperSquareMeterList[{}]:{}".format(i, plantProfitperSquareMeterList[i])
plantProfitRLShadingCurtainList = plantProfitperSquareMeterRLShadingCurtainList * constant.greenhouseCultivationFloorArea
print ("(RL) plantProfitRLShadingCurtainList [USD]:{}".format(plantProfitRLShadingCurtainList))
# set the result of profits
qLearningAgentsShadingCurtain.plantProfitRLShadingCurtainList = plantProfitRLShadingCurtainList
################## calculate the plant economic profit end#######################
else:
print ("reinforcement learning shading curtain waa not assumed. skip the simulation")
#####################################################################################################
################## reinforcement learning plant simulation end#####################################
#####################################################################################################
print ("end modeling: datetime.datetime.now():{}".format(datetime.datetime.now()))
# print actions
print ("qLearningAgentsShadingCurtain.policies:{}".format(qLearningAgentsShadingCurtain.policies))
# print DLI to plants
print ("qLearningAgentsShadingCurtain.dLIEachDayToPlants:{}".format(qLearningAgentsShadingCurtain.dLIEachDayToPlants))
return simulatorClass, qLearningAgentsShadingCurtain
# ####################################################################################################
# Stop execution here...
# sys.exit()
# Move the above line to different parts of the assignment as you implement more of the functionality.
# ####################################################################################################
|
{"/OPVFilm.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/ShadingCurtain.py"], "/CropElectricityYieldProfitMINLP.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelS_Pearson1997.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/PlantGrowthModelS_Pearson1997Constant.py", "/Lettuce.py"], "/GreenhouseEnergyBalanceConstant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/Util.py": ["/CropElectricityYeildSimulatorConstant.py"], "/SolarIrradianceMultiSpanRoof.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/GreenhouseEnergyBalance.py": ["/Lettuce.py", "/CropElectricityYeildSimulatorConstant.py", "/GreenhouseEnergyBalanceConstant.py", "/Util.py"], "/SimulatorMain.py": ["/CropElectricityYeildSimulator1.py", "/Util.py", "/CropElectricityYeildSimulatorConstant.py"], "/CropElectricityYieldProfitRLShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/ShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelValidation.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulator1.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulatorDetail.py": ["/ShadingCurtain.py", "/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/Lettuce.py", "/PlantGrowthModelS_Pearson1997.py", "/SolarIrradianceMultiSpanRoof.py", "/GreenhouseEnergyBalance.py"], "/PlantGrowthModelS_Pearson1997Constant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/SimulatorClass.py": ["/CropElectricityYeildSimulatorConstant.py"], "/Lettuce.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/plantGrowthModelE_J_VanHenten.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py"]}
|
8,664
|
kensaku-okada/Greenhouse-with-OPV-film-Model
|
refs/heads/master
|
/ShadingCurtain.py
|
# -*- coding: utf-8 -*-
#############command to print out all array data
# np.set_printoptions(threshold=np.inf)
# print ("directSolarRadiationToOPVWestDirection:{}".format(directSolarRadiationToOPVWestDirection))
# np.set_printoptions(threshold=1000)
#############
# ####################################################################################################
# # Stop execution here...
# sys.exit()
# # Move the above line to different parts of the assignment as you implement more of the functionality.
# ####################################################################################################
##########import package files##########
from scipy import stats
import datetime
import calendar
import sys
import os as os
import numpy as np
import math
import CropElectricityYeildSimulatorConstant as constant
import Util as util
import OPVFilm
#import Lettuce
import CropElectricityYeildSimulatorDetail as simulatorDetail
import SimulatorClass
#######################################################
# def getHourlyShadingCurtainDeploymentPatternChangingEachMonthPrep():
# '''
# calculate the shading curtain deployment start and end hour each month so that the average DLI becomes as optimal (constant.DLIforTipBurn) as possible
# The optimal hour is calculated by averaging the solar irradiance each month
# '''
#
# # get the num of simulation days
# simulationDaysInt = util.getSimulationDaysInt()
#
# # declare the class and instance
# simulatorClass = SimulatorClass.SimulatorClass()
#
# ##########file import (TucsonHourlyOuterEinvironmentData) start##########
# fileName = constant.environmentData
# year, \
# month, \
# day, \
# hour, \
# hourlyHorizontalDiffuseOuterSolarIrradiance, \
# hourlyHorizontalTotalOuterSolarIrradiance, \
# hourlyHorizontalDirectOuterSolarIrradiance, \
# hourlyHorizontalTotalBeamMeterBodyTemperature, \
# hourlyAirTemperature = util.getArraysFromData(fileName, simulatorClass)
# ##########file import (TucsonHourlyOuterEinvironmentData) end##########
#
# # set the imported data
# simulatorClass.hourlyHorizontalDirectOuterSolarIrradiance = hourlyHorizontalDirectOuterSolarIrradiance
# simulatorClass.hourlyHorizontalDiffuseOuterSolarIrradiance = hourlyHorizontalDiffuseOuterSolarIrradiance
# simulatorClass.hourlyHorizontalTotalOuterSolarIrradiance = hourlyHorizontalTotalOuterSolarIrradiance
# simulatorClass.hourlyHorizontalTotalBeamMeterBodyTemperature = hourlyHorizontalTotalBeamMeterBodyTemperature
# simulatorClass.hourlyAirTemperature = hourlyAirTemperature
#
# # set new data which can be derived from the imported data
# util.deriveOtherArraysFromImportedData(simulatorClass)
#
# ################################################################################
# ##########solar irradiance to OPV calculation with imported data start##########
# ################################################################################
# if constant.ifUseOnlyRealData == True:
#
# # calculate with real data
# # hourly average [W m^-2]
# directSolarRadiationToOPVEastDirection, \
# directSolarRadiationToOPVWestDirection, \
# diffuseSolarRadiationToOPV, \
# albedoSolarRadiationToOPV = simulatorDetail.calcOPVmoduleSolarIrradianceGHRoof(simulatorClass)
#
# # set the calculated data
# simulatorClass.setDirectSolarRadiationToOPVEastDirection(directSolarRadiationToOPVEastDirection)
# simulatorClass.setDirectSolarRadiationToOPVWestDirection(directSolarRadiationToOPVWestDirection)
# simulatorClass.setDiffuseSolarRadiationToOPV(diffuseSolarRadiationToOPV)
# simulatorClass.setAlbedoSolarRadiationToOPV(albedoSolarRadiationToOPV)
#
# # [W m^-2] per hour
# totalSolarRadiationToOPV = (simulatorClass.getDirectSolarRadiationToOPVEastDirection() + simulatorClass.getDirectSolarRadiationToOPVWestDirection()) / 2.0 \
# + simulatorClass.getDiffuseSolarRadiationToOPV() + simulatorClass.getAlbedoSolarRadiationToOPV()
#
# ###################data export start##################
# util.exportCSVFile(np.array(
# [year, month, day, hour, simulatorClass.getDirectSolarRadiationToOPVEastDirection(), simulatorClass.getDirectSolarRadiationToOPVWestDirection(), \
# simulatorClass.getDiffuseSolarRadiationToOPV(), simulatorClass.getAlbedoSolarRadiationToOPV(), totalSolarRadiationToOPV]).T,
# "hourlyMeasuredSolarRadiations")
# ###################data export end##################
#
# ###################data export start##################
# util.exportCSVFile(np.array([year, month, day, hour, hourlyHorizontalTotalOuterSolarIrradiance, totalSolarRadiationToOPV]).T,
# "hourlyMeasuredSolarRadiationToHorizontalAndTilted")
# ###################data export end##################
#
# # unit change: [W m^-2] -> [umol m^-2 s^-1] == PPFD
# directPPFDToOPVEastDirection = util.convertFromWattperSecSquareMeterToPPFD(directSolarRadiationToOPVEastDirection)
# directPPFDToOPVWestDirection = util.convertFromWattperSecSquareMeterToPPFD(directSolarRadiationToOPVWestDirection)
# diffusePPFDToOPV = util.convertFromWattperSecSquareMeterToPPFD(diffuseSolarRadiationToOPV)
# groundReflectedPPFDToOPV = util.convertFromWattperSecSquareMeterToPPFD(albedoSolarRadiationToOPV)
# # print"diffusePPFDToOPV.shape:{}".format(diffusePPFDToOPV.shape)
#
# # set the matrix to the object
# simulatorClass.setDirectPPFDToOPVEastDirection(directPPFDToOPVEastDirection)
# simulatorClass.setDirectPPFDToOPVWestDirection(directPPFDToOPVWestDirection)
# simulatorClass.setDiffusePPFDToOPV(diffusePPFDToOPV)
# simulatorClass.setGroundReflectedPPFDToOPV(groundReflectedPPFDToOPV)
#
# # unit change: hourly [umol m^-2 s^-1] -> [mol m^-2 day^-1] == daily light integral (DLI) :number of photons received in a square meter per day
# directDLIToOPVEastDirection = util.convertFromHourlyPPFDWholeDayToDLI(directPPFDToOPVEastDirection)
# directDLIToOPVWestDirection = util.convertFromHourlyPPFDWholeDayToDLI(directPPFDToOPVWestDirection)
# diffuseDLIToOPV = util.convertFromHourlyPPFDWholeDayToDLI(diffusePPFDToOPV)
# groundReflectedDLIToOPV = util.convertFromHourlyPPFDWholeDayToDLI(groundReflectedPPFDToOPV)
# totalDLIToOPV = (directDLIToOPVEastDirection + directDLIToOPVWestDirection) / 2.0 + diffuseDLIToOPV + groundReflectedDLIToOPV
# # print "directDLIToOPVEastDirection:{}".format(directDLIToOPVEastDirection)
# # print "diffuseDLIToOPV.shape:{}".format(diffuseDLIToOPV.shape)
# # print "groundReflectedDLIToOPV:{}".format(groundReflectedDLIToOPV)
#
# # set the array to the object
# simulatorClass.setDirectDLIToOPVEastDirection(directDLIToOPVEastDirection)
# simulatorClass.setDirectDLIToOPVWestDirection(directDLIToOPVWestDirection)
# simulatorClass.setDiffuseDLIToOPV(diffuseDLIToOPV)
# simulatorClass.setGroundReflectedDLIToOPV(groundReflectedDLIToOPV)
#
# ########################################################################################################################
# ################# calculate solar irradiance without real data (estimate solar irradiance) start #######################
# ########################################################################################################################
# elif constant.ifUseOnlyRealData == False:
#
# # activate the mode to use the formulas for estimation. This is used for branching the solar irradiance to PV module. See OPVFilm.py
# simulatorClass.setEstimateSolarRadiationMode(True)
#
# # calculate the solar radiation to the OPV film
# # [W m^-2] per hour
# estimatedDirectSolarRadiationToOPVEastDirection, \
# estimatedDirectSolarRadiationToOPVWestDirection, \
# estimatedDiffuseSolarRadiationToOPV, \
# estimatedAlbedoSolarRadiationToOPV = simulatorDetail.calcOPVmoduleSolarIrradianceGHRoof(simulatorClass)
# estimatedTotalSolarRadiationToOPV = (
# estimatedDirectSolarRadiationToOPVEastDirection + estimatedDirectSolarRadiationToOPVWestDirection) / 2.0 + estimatedDiffuseSolarRadiationToOPV + estimatedAlbedoSolarRadiationToOPV
#
# # set the calc results
# # [W m^-2] per hour
# simulatorClass.setDirectSolarRadiationToOPVEastDirection(estimatedDirectSolarRadiationToOPVEastDirection)
# simulatorClass.setDirectSolarRadiationToOPVWestDirection(estimatedDirectSolarRadiationToOPVWestDirection)
# simulatorClass.setDiffuseSolarRadiationToOPV(estimatedDiffuseSolarRadiationToOPV)
# simulatorClass.setAlbedoSolarRadiationToOPV(estimatedAlbedoSolarRadiationToOPV)
#
# # [estimated data] unit change:
# estimatedDirectPPFDToOPVEastDirection = util.convertFromWattperSecSquareMeterToPPFD(estimatedDirectSolarRadiationToOPVEastDirection)
# estimatedDirectPPFDToOPVWestDirection = util.convertFromWattperSecSquareMeterToPPFD(estimatedDirectSolarRadiationToOPVWestDirection)
# estimatedDiffusePPFDToOPV = util.convertFromWattperSecSquareMeterToPPFD(estimatedDiffuseSolarRadiationToOPV)
# estimatedGroundReflectedPPFDToOPV = util.convertFromWattperSecSquareMeterToPPFD(estimatedAlbedoSolarRadiationToOPV)
# # print("estimatedDirectPPFDToOPVEastDirection:{}".format(estimatedDirectPPFDToOPVEastDirection))
# # print("estimatedDirectPPFDToOPVWestDirection:{}".format(estimatedDirectPPFDToOPVWestDirection))
#
# # set the variables
# simulatorClass.setDirectPPFDToOPVEastDirection(estimatedDirectPPFDToOPVEastDirection)
# simulatorClass.setDirectPPFDToOPVWestDirection(estimatedDirectPPFDToOPVWestDirection)
# simulatorClass.setDiffusePPFDToOPV(estimatedDiffusePPFDToOPV)
# simulatorClass.setGroundReflectedPPFDToOPV(estimatedGroundReflectedPPFDToOPV)
#
# # [estimated data] unit change:
# estimatedDirectDLIToOPVEastDirection = util.convertFromHourlyPPFDWholeDayToDLI(estimatedDirectPPFDToOPVEastDirection)
# estimatedDirectDLIToOPVWestDirection = util.convertFromHourlyPPFDWholeDayToDLI(estimatedDirectPPFDToOPVWestDirection)
# estimatedDiffuseDLIToOPV = util.convertFromHourlyPPFDWholeDayToDLI(estimatedDiffusePPFDToOPV)
# estimatedGroundReflectedDLIToOPV = util.convertFromHourlyPPFDWholeDayToDLI(estimatedGroundReflectedPPFDToOPV)
# # estimatedTotalDLIToOPV = (estimatedDirectDLIToOPVEastDirection + estimatedDirectDLIToOPVWestDirection) / 2.0 + estimatedDiffuseDLIToOPV + estimatedGroundReflectedDLIToOPV
# # set the variables
# simulatorClass.setDirectDLIToOPVEastDirection(estimatedDirectDLIToOPVEastDirection)
# simulatorClass.setDirectDLIToOPVWestDirection(estimatedDirectDLIToOPVWestDirection)
# simulatorClass.setDiffuseDLIToOPV(estimatedDiffuseDLIToOPV)
# simulatorClass.setGroundReflectedDLIToOPV(estimatedGroundReflectedDLIToOPV)
#
# # deactivate the mode to the default value.
# simulatorClass.setEstimateSolarRadiationMode(False)
#
# # data export of solar irradiance
# util.exportCSVFile(np.array([year, month, day, hour,
# simulatorClass.getDirectSolarRadiationToOPVEastDirection(),
# simulatorClass.getDirectSolarRadiationToOPVWestDirection(),
# simulatorClass.getDiffuseSolarRadiationToOPV(),
# simulatorClass.getAlbedoSolarRadiationToOPV(),
# estimatedTotalSolarRadiationToOPV]).T,
# "SolarIrradianceToHorizontalSurface")
# ################# calculate solar irradiance without real data (estimate the data) end #######################
#
#
# ###############################################################################################
# ###################calculate the solar irradiance through multi span roof start################
# ###############################################################################################
# # The calculated irradiance is stored to the object in this function
# simulatorDetail.getDirectSolarIrradianceThroughMultiSpanRoof(simulatorClass)
# # data export
# util.exportCSVFile(
# np.array([year, month, day, hour, simulatorClass.integratedT_mat, simulatorClass.getHourlyDirectSolarRadiationAfterMultiSpanRoof(), ]).T,
# "directSolarRadiationAfterMultiSpanRoof")
# ###########################################################################################
# ###################calculate the solar irradiance through multi span roof end##############
# ###########################################################################################
#
# ###########################################################################################
# ###################calculate the solar irradiance to plants start##########################
# ###########################################################################################
# # get/set cultivation days per harvest [days/harvest]
# cultivationDaysperHarvest = constant.cultivationDaysperHarvest
# simulatorClass.setCultivationDaysperHarvest(cultivationDaysperHarvest)
#
# # get/set OPV coverage ratio [-]
# OPVCoverage = constant.OPVAreaCoverageRatio
# simulatorClass.setOPVAreaCoverageRatio(OPVCoverage)
#
# # get/set OPV coverage ratio during fallow period[-]
# OPVCoverageSummerPeriod = constant.OPVAreaCoverageRatioSummerPeriod
# simulatorClass.setOPVCoverageRatioSummerPeriod(OPVCoverageSummerPeriod)
#
# # get if we assume to have shading curtain
# hasShadingCurtain = constant.hasShadingCurtain
# simulatorClass.setIfHasShadingCurtain(hasShadingCurtain)
#
# # get the direct solar irradiance after penetrating multi span roof [W/m^2]
# hourlyDirectSolarRadiationAfterMultiSpanRoof = simulatorClass.getHourlyDirectSolarRadiationAfterMultiSpanRoof()
#
# # OPVAreaCoverageRatio = simulatorClass.getOPVAreaCoverageRatio()
# OPVAreaCoverageRatio = constant.OPVAreaCoverageRatio
# hasShadingCurtain = simulatorClass.getIfHasShadingCurtain()
# # ShadingCurtainDeployPPFD = simulatorClass.getShadingCurtainDeployPPFD()
# OPVPARTransmittance = constant.OPVPARTransmittance
#
#
# # make the list of OPV coverage ratio at each hour changing during summer
# OPVAreaCoverageRatioChangingInSummer = OPVFilm.getDifferentOPVCoverageRatioInSummerPeriod(OPVAreaCoverageRatio, simulatorClass)
#
# # ############command to print out all array data
# # np.set_printoptions(threshold=np.inf)
# # print("OPVAreaCoverageRatioChangingInSummer:{}".format(OPVAreaCoverageRatioChangingInSummer))
# # np.set_printoptions(threshold=1000)
# # ############
#
# # consider the transmission ratio of OPV film
# hourlyDirectSolarRadiationAfterOPVAndRoof = hourlyDirectSolarRadiationAfterMultiSpanRoof * (1 - OPVAreaCoverageRatioChangingInSummer) \
# + hourlyDirectSolarRadiationAfterMultiSpanRoof * OPVAreaCoverageRatioChangingInSummer * OPVPARTransmittance
# # print "OPVAreaCoverageRatio:{}, HourlyInnerLightIntensityPPFDThroughOPV:{}".format(OPVAreaCoverageRatio, HourlyInnerLightIntensityPPFDThroughOPV)
#
# # consider the light reduction by greenhouse inner structures and equipments like pipes, poles and gutters
# hourlyDirectSolarRadiationAfterInnerStructure = (1 - constant.GreenhouseShadeProportionByInnerStructures) * hourlyDirectSolarRadiationAfterOPVAndRoof
#
#
# transmittanceThroughShadingCurtainChangingEachMonth = getHourlyShadingCurtainDeploymentPatternChangingEachMonthMain(simulatorClass, hourlyDirectSolarRadiationAfterInnerStructure)
#
# return transmittanceThroughShadingCurtainChangingEachMonth
# def getHourlyShadingCurtainDeploymentPatternChangingEachMonthMain(simulatorClass, hourlyDirectSolarRadiationAfterInnerStructure):
def getHourlyShadingCurtainDeploymentPatternChangingEachMonthMain(simulatorClass):
'''
calculate the shading curtain deployement pattern which changes each month.
The deployment is judges by comparing the average DLI and the optimal DLI that is defined at CropElectricityYeildSimulatorConstant
'''
directSolarIrradianceBeforeShadingCurtain = simulatorClass.directSolarIrradianceBeforeShadingCurtain
diffuseSolarIrradianceBeforeShadingCurtain = simulatorClass.diffuseSolarIrradianceBeforeShadingCurtain
totalSolarIrradianceBeforeShadingCurtain = directSolarIrradianceBeforeShadingCurtain + diffuseSolarIrradianceBeforeShadingCurtain
# print("totalSolarIrradianceBeforeShadingCurtain:{}".format(totalSolarIrradianceBeforeShadingCurtain))
################### calc shading deployment pattern start ###########################
if constant.IsShadingCurtainDeployOnlyDayTime == True and constant.IsDifferentShadingCurtainDeployTimeEachMonth == True:
# 1 = no shading curatin, the transmittance of shading curtain = deploey curtain
transmittanceThroughShadingCurtainChangingEachMonth = np.zeros(len(totalSolarIrradianceBeforeShadingCurtain))
#############
# 1: deploy shading curtain, 0 = not deploy
shadingHours = {
# "0": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
# ,"12": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
# ,"12-13": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
# , "11-13":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
# , "11-14":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
# , "10-14":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
# , "10-15":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]
# , "9-15": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]
# , "9-16": [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0]
# , "8-16": [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0]
# , "8-17": [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0]
# , "7-17": [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0]
# , "7-18": [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]
# , "6-18": [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]
# , "6-19": [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0]
# , "5-19": [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0]
# , "5-20": [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0]
# , "4-20": [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0]
# , "4-21": [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0]
# , "3-21": [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0]
# , "3-22": [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]
# , "2-22": [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]
# , "2-23": [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
# , "1-23": [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
# , "0-23": [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
0: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
, 1: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
, 2: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
, 3: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
, 4: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
, 5: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
, 6: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]
, 7: [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]
, 8: [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0]
, 9: [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0]
, 10: [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0]
, 11: [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0]
, 12: [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]
, 13: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]
, 14: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0]
, 15: [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0]
, 16: [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0]
, 17: [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0]
, 18: [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0]
, 19: [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0]
, 20: [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]
, 21: [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]
, 22: [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
, 23: [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
, 24: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
}
# print("len(shadingHours):{}".format(len(shadingHours)))
##############set the initial values start##############
# get the num of simulation months, rounding up.
# e.g. when the simulation period is 1st Jan to 15th Jan, it is 1.
# e.g. when the simulation period is 1st 16th Nov to 1st Dec, it is 2.
# simulationMonths = util.getSimulationMonthsInt()
# unit: hour
simulationHours = util.getSimulationDaysInt() * constant.hourperDay
# print("simulationHours:{}".format(simulationHours))
currnetDate = util.getStartDateDateType()
currentYear = util.getStartDateDateType().year
currentMonth = util.getStartDateDateType().month
currentDay = util.getStartDateDateType().day
# SimulatedMonths = 1
hour = 0
##############set the initial values end##############
# total sollar irradiance per day which does not cause tipburn. unit conversion: DLI(mol m-2 day) -> W m-2
# totalSolarIrradiancePerDayNoTipburn = constant.DLIforTipBurn * 1000000.0 / constant.minuteperHour / constant.secondperMinute / constant.wattToPPFDConversionRatio
# loop each hour
hour = 0
while hour < simulationHours:
# print("hour:{}".format(hour))
# get the number of days each month
_, currentMonthDays = calendar.monthrange(currnetDate.year, currnetDate.month)
# print("currentMonthDays:{}".format(currentMonthDays))
daysOfEachMonth = (datetime.date(currentYear, currentMonth, currentMonthDays) - currnetDate).days + 1
# print("daysOfEachMonth:{}".format(daysOfEachMonth))
# loop for each shading curtain deployment pattern
for i in range(0, len(shadingHours)):
# if shading curtain: constant.shadingTransmittanceRatio, if no shading: 1.0 transmittance
TransmittanceThroughShadingCurtain = np.array([constant.shadingTransmittanceRatio if j == 1 else 1.0 for j in shadingHours[i]])
# print("TransmittanceThroughShadingCurtain:{}".format(TransmittanceThroughShadingCurtain))
# extend the shading curatin pattern for whole month
transmittanceThroughShadingCurtainWholeMonth = []
[transmittanceThroughShadingCurtainWholeMonth .extend(TransmittanceThroughShadingCurtain) for k in range(0, daysOfEachMonth)]
# print("len(transmittanceThroughShadingCurtainWholeMonth ):{}".format(len(transmittanceThroughShadingCurtainWholeMonth )))
# get the solar irradiance through shading curtain
hourlyDirectSolarRadiationAfterShadingCurtain = totalSolarIrradianceBeforeShadingCurtain[hour : hour + daysOfEachMonth * constant.hourperDay] * transmittanceThroughShadingCurtainWholeMonth
# print("hourlyDirectSolarRadiationAfterShadingCurtain:{}".format(hourlyDirectSolarRadiationAfterShadingCurtain))
# print("len(hourlyDirectSolarRadiationAfterShadingCurtain):{}".format(len(hourlyDirectSolarRadiationAfterShadingCurtain)))
# print("sum(hourlyDirectSolarRadiationAfterShadingCurtain):{}".format(sum(hourlyDirectSolarRadiationAfterShadingCurtain)))
# convert the unit from W m-2 to DLI (mol m-2 day-1)
DLIAfterShadingCurtain = sum(hourlyDirectSolarRadiationAfterShadingCurtain) / daysOfEachMonth * constant.wattToPPFDConversionRatio * constant.secondperMinute * constant.minuteperHour / 1000000.0
# print("DLIAfterShadingCurtain:{}".format(DLIAfterShadingCurtain))
# print("i:{}".format(i))
# if the average DLI is less than the optimal DLI
if DLIAfterShadingCurtain <= constant.DLIforTipBurn:
# store the transmittance which shading curatin deployed
transmittanceThroughShadingCurtainChangingEachMonth[hour : hour + daysOfEachMonth * constant.hourperDay] = transmittanceThroughShadingCurtainWholeMonth
# increment hour
hour += daysOfEachMonth * constant.hourperDay
# variable update
# print("before currnetDate:{}".format(currnetDate))
currnetDate = currnetDate + datetime.timedelta(days = daysOfEachMonth)
# print("after currnetDate:{}".format(currnetDate))
currentYear = currnetDate.year
currentMonth = currnetDate.month
# move to the next month. break the for loop
break
# if the average solar irradiance does not become below the optimal DLI, then store the solar irradiance for shadingHours[24]
elif i == 24:
# store the transmittance which shading curatin deployed
transmittanceThroughShadingCurtainChangingEachMonth[hour : hour + daysOfEachMonth * constant.hourperDay] = transmittanceThroughShadingCurtainWholeMonth
# increment hour
hour += daysOfEachMonth * constant.hourperDay
# variable update
# print("before currnetDate:{}".format(currnetDate))
currnetDate = currnetDate + datetime.timedelta(days = daysOfEachMonth)
# print("after currnetDate:{}".format(currnetDate))
currentYear = currnetDate.year
currentMonth = currnetDate.month
# move to the next month. break the for loop
break
# store the data
simulatorClass.transmittanceThroughShadingCurtainChangingEachMonth = transmittanceThroughShadingCurtainChangingEachMonth
return transmittanceThroughShadingCurtainChangingEachMonth
else:
print("error: please let constant.IsShadingCurtainDeployOnlyDayTime == True and constant.IsDifferentShadingCurtainDeployTimeEachMonth == True")
####################################################################################################
# Stop execution here...
sys.exit()
# Move the above line to different parts of the assignment as you implement more of the functionality.
####################################################################################################
# print "hourlyInnerLightIntensityPPFDThroughInnerStructure:{}".format(hourlyInnerLightIntensityPPFDThroughInnerStructure)
# if __name__ == '__main__':
# transmittanceThroughShadingCurtainChangingEachMonth = getHourlyShadingCurtainDeploymentPatternChangingEachMonthPrep()
# print("transmittanceThroughShadingCurtainChangingEachMonth:{}".format(transmittanceThroughShadingCurtainChangingEachMonth))
#
# # export the data
|
{"/OPVFilm.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/ShadingCurtain.py"], "/CropElectricityYieldProfitMINLP.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelS_Pearson1997.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/PlantGrowthModelS_Pearson1997Constant.py", "/Lettuce.py"], "/GreenhouseEnergyBalanceConstant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/Util.py": ["/CropElectricityYeildSimulatorConstant.py"], "/SolarIrradianceMultiSpanRoof.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/GreenhouseEnergyBalance.py": ["/Lettuce.py", "/CropElectricityYeildSimulatorConstant.py", "/GreenhouseEnergyBalanceConstant.py", "/Util.py"], "/SimulatorMain.py": ["/CropElectricityYeildSimulator1.py", "/Util.py", "/CropElectricityYeildSimulatorConstant.py"], "/CropElectricityYieldProfitRLShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/ShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelValidation.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulator1.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulatorDetail.py": ["/ShadingCurtain.py", "/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/Lettuce.py", "/PlantGrowthModelS_Pearson1997.py", "/SolarIrradianceMultiSpanRoof.py", "/GreenhouseEnergyBalance.py"], "/PlantGrowthModelS_Pearson1997Constant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/SimulatorClass.py": ["/CropElectricityYeildSimulatorConstant.py"], "/Lettuce.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/plantGrowthModelE_J_VanHenten.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py"]}
|
8,665
|
kensaku-okada/Greenhouse-with-OPV-film-Model
|
refs/heads/master
|
/PlantGrowthModelValidation.py
|
# -*- coding: utf-8 -*-
#######################################################
# author :Kensaku Okada [kensakuokada@email.arizona.edu]
# create date : 21 April 2018
#######################################################
# ####################################################################################################
# np.set_printoptions(threshold=np.inf)
# print "hourlySolarIncidenceAngle:{}".format(np.degrees(hourlySolarIncidenceAngle))
# np.set_printoptions(threshold=1000)
# ####################################################################################################
# ####################################################################################################
# # Stop execution here...
# sys.exit()
# # Move the above line to different parts of the assignment as you implement more of the functionality.
# ####################################################################################################
##########import package files##########
import os as os
import numpy as np
import sys
import matplotlib.pyplot as plt
import math
import CropElectricityYeildSimulatorConstant as constant
import Util
import datetime
import Lettuce
import PlantGrowthModelE_J_VanHentenConstant as VanHentenConstant
import SimulatorClass
import PlantGrowthModelE_J_VanHenten
def importPlantGrowthModelValidationData(fileName, simulatorClass):
# fileData = Util.readData(fileName, "", skip_header=1,d='\t')
fileData = Util.readData(fileName, "", skip_header=1,d=',')
print("fileData.shape:{}".format(fileData.shape))
# ####################################################################################################
# # np.set_printoptions(threshold=np.inf)
# np.set_printoptions(threshold=np.inf)
# print("filedata:{}".format(fileData))
# np.set_printoptions(threshold=1000)
# ####################################################################################################
year = np.zeros(fileData.shape[0], dtype=int)
month = np.zeros(fileData.shape[0], dtype=int)
day = np.zeros(fileData.shape[0], dtype=int)
hour = np.zeros(fileData.shape[0], dtype=int)
GHSolarIrradiance = np.zeros(fileData.shape[0])
GHAirTemperature = np.zeros(fileData.shape[0])
for i in range(0, fileData.shape[0]):
year[i] = int(fileData[i][0])
month[i] = int(fileData[i][1])
day[i] = int(fileData[i][2])
hour[i] = int(fileData[i][3])
GHSolarIrradiance[i] = fileData[i][4]
GHAirTemperature[i] = fileData[i][5]
# print("year[0]:{}".format(year[0]))
# set the imported values to the object
simulatorClass.setYear(year)
simulatorClass.setMonth(month)
simulatorClass.setDay(day)
simulatorClass.setHour(hour)
# simulatorClass.GHSolarIrradianceValidationData = GHSolarIrradiance
simulatorClass.directSolarIrradianceToPlants = GHSolarIrradiance/2.0
simulatorClass.diffuseSolarIrradianceToPlants = GHSolarIrradiance/2.0
simulatorClass.GHAirTemperatureValidationData = GHAirTemperature
return simulatorClass
########################################################################################################################################
# Note: To run this file and validation, please change constant.SimulationStartDate and constant.SimulationEndDate according to the date of imported data.
########################################################################################################################################
# data import
# get the num of simulation days
simulationDaysInt = Util.getSimulationDaysInt()
# declare the class and instance
simulatorClass = SimulatorClass.SimulatorClass()
# set spececific numbers to the instance
# simulatorDetail.setSimulationSpecifications(simulatorClass)
##########file import (TucsonHourlyOuterEinvironmentData) start##########
fileName = constant.environmentData
year, \
month, \
day, \
hour, \
hourlyHorizontalDiffuseOuterSolarIrradiance, \
hourlyHorizontalTotalOuterSolarIrradiance, \
hourlyHorizontalDirectOuterSolarIrradiance, \
hourlyHorizontalTotalBeamMeterBodyTemperature, \
hourlyAirTemperature = Util.getArraysFromData(fileName, simulatorClass)
##########file import (TucsonHourlyOuterEinvironmentData) end##########
# # set the imported data
# simulatorClass.hourlyHorizontalDirectOuterSolarIrradiance = hourlyHorizontalDirectOuterSolarIrradiance
# simulatorClass.hourlyHorizontalDiffuseOuterSolarIrradiance = hourlyHorizontalDiffuseOuterSolarIrradiance
# simulatorClass.hourlyHorizontalTotalOuterSolarIrradiance = hourlyHorizontalTotalOuterSolarIrradiance
# simulatorClass.hourlyHorizontalTotalBeamMeterBodyTemperature = hourlyHorizontalTotalBeamMeterBodyTemperature
# simulatorClass.hourlyAirTemperature = hourlyAirTemperature
# import the weather data with which you want to validate the plant growth model. This data overwrite the originally imported data above.
fileName = constant.plantGrowthModelValidationData
importPlantGrowthModelValidationData(fileName, simulatorClass)
# set new data which can be derived from the imported data
Util.deriveOtherArraysFromImportedData(simulatorClass)
FWPerHead, WFreshWeightIncrease, WAccumulatedFreshWeightIncrease, WHarvestedFreshWeight = PlantGrowthModelE_J_VanHenten.calcUnitDailyFreshWeightE_J_VanHenten1994(simulatorClass)
# data export
Util.exportCSVFile(np.array([simulatorClass.getYear(),simulatorClass.getMonth(), simulatorClass.getDay(), simulatorClass.getHour(), \
FWPerHead, WFreshWeightIncrease, WHarvestedFreshWeight]).T, "plantGrowthModelValidationdata")
# print("day:{}".format(day))
# print("simulatorClass.getDay():{}".format(simulatorClass.getDay()))
# print("simulatorClass.getDay().shape:{}".format(simulatorClass.getDay().shape))
# print("FWPerHead.shape:{}".format(FWPerHead.shape))
# Util.exportCSVFile(np.array([year,month, day, hour, \
# FWPerHead, WFreshWeightIncrease, WHarvestedFreshWeight]).T, "plantGrowthModelValidationdata")
|
{"/OPVFilm.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/ShadingCurtain.py"], "/CropElectricityYieldProfitMINLP.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelS_Pearson1997.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/PlantGrowthModelS_Pearson1997Constant.py", "/Lettuce.py"], "/GreenhouseEnergyBalanceConstant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/Util.py": ["/CropElectricityYeildSimulatorConstant.py"], "/SolarIrradianceMultiSpanRoof.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/GreenhouseEnergyBalance.py": ["/Lettuce.py", "/CropElectricityYeildSimulatorConstant.py", "/GreenhouseEnergyBalanceConstant.py", "/Util.py"], "/SimulatorMain.py": ["/CropElectricityYeildSimulator1.py", "/Util.py", "/CropElectricityYeildSimulatorConstant.py"], "/CropElectricityYieldProfitRLShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/ShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelValidation.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulator1.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulatorDetail.py": ["/ShadingCurtain.py", "/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/Lettuce.py", "/PlantGrowthModelS_Pearson1997.py", "/SolarIrradianceMultiSpanRoof.py", "/GreenhouseEnergyBalance.py"], "/PlantGrowthModelS_Pearson1997Constant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/SimulatorClass.py": ["/CropElectricityYeildSimulatorConstant.py"], "/Lettuce.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/plantGrowthModelE_J_VanHenten.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py"]}
|
8,666
|
kensaku-okada/Greenhouse-with-OPV-film-Model
|
refs/heads/master
|
/CropElectricityYeildSimulator1.py
|
# -*- coding: utf-8 -*-
#############command to print out all array data
# np.set_printoptions(threshold=np.inf)
# print ("directSolarRadiationToOPVWestDirection:{}".format(directSolarRadiationToOPVWestDirection))
# np.set_printoptions(threshold=1000)
#############
# ####################################################################################################
# # Stop execution here...
# sys.exit()
# # Move the above line to different parts of the assignment as you implement more of the functionality.
# ####################################################################################################
##########import package files##########
import datetime
import sys
import os
import numpy as np
import math
import CropElectricityYeildSimulatorConstant as constant
import Util as util
import OPVFilm
#import Lettuce
import CropElectricityYeildSimulatorDetail as simulatorDetail
import SimulatorClass
#######################################################
def simulateCropElectricityYieldProfit1():
'''
version 1.0
simulator of crop and electricity yield and the total profit
'''
# print ("start modeling: datetime.datetime.now():{}".format(datetime.datetime.now()))
# get the num of simulation days
simulationDaysInt = util.getSimulationDaysInt()
# declare the class and instance
simulatorClass = SimulatorClass.SimulatorClass()
# set spececific numbers to the instance
# simulatorDetail.setSimulationSpecifications(simulatorClass)
##########file import (TucsonHourlyOuterEinvironmentData) start##########
fileName = constant.environmentData
year, \
month, \
day, \
hour, \
hourlyHorizontalDiffuseOuterSolarIrradiance, \
hourlyHorizontalTotalOuterSolarIrradiance, \
hourlyHorizontalDirectOuterSolarIrradiance, \
hourlyHorizontalTotalBeamMeterBodyTemperature, \
hourlyAirTemperature = util.getArraysFromData(fileName, simulatorClass)
##########file import (TucsonHourlyOuterEinvironmentData) end##########
# set the imported data
simulatorClass.hourlyHorizontalDirectOuterSolarIrradiance = hourlyHorizontalDirectOuterSolarIrradiance
simulatorClass.hourlyHorizontalDiffuseOuterSolarIrradiance = hourlyHorizontalDiffuseOuterSolarIrradiance
simulatorClass.hourlyHorizontalTotalOuterSolarIrradiance = hourlyHorizontalTotalOuterSolarIrradiance
simulatorClass.hourlyHorizontalTotalBeamMeterBodyTemperature = hourlyHorizontalTotalBeamMeterBodyTemperature
simulatorClass.hourlyAirTemperature = hourlyAirTemperature
# ################## plot the imported direct and diffuse solar radiation start######################
# Title = "imported (measured horizontal) direct and diffuse solar radiation"
# xAxisLabel = "time [hour]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
# yAxisLabel = "total Solar irradiance [W m^-2]"
# util.plotTwoData(np.linspace(0, simulationDaysInt * constant.hourperDay, simulationDaysInt * constant.hourperDay), \
# simulatorClass.getImportedHourlyHorizontalDirectSolarRadiation(), simulatorClass.getImportedHourlyHorizontalDiffuseSolarRadiation() ,Title, xAxisLabel, yAxisLabel, \
# "hourlyHorizontalDirectOuterSolarIrradiance", "hourlyHorizontalDiffuseOuterSolarIrradiance")
# util.saveFigure(Title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
# ################## plot the imported direct and diffuse solar radiation end######################
# print ("hourlyHorizontalDirectOuterSolarIrradiance:{}".format(hourlyHorizontalDirectOuterSolarIrradiance))
# print ("max(simulatorClass.getImportedHourlyHorizontalDirectSolarRadiation()):{}".format(max(simulatorClass.getImportedHourlyHorizontalDirectSolarRadiation())))
# set new data which can be derived from the imported data
util.deriveOtherArraysFromImportedData(simulatorClass)
################################################################################
##########solar irradiance to OPV calculation with imported data start##########
################################################################################
if constant.ifUseOnlyRealData == True:
# calculate with real data
# hourly average [W m^-2]
directSolarRadiationToOPVEastDirection, \
directSolarRadiationToOPVWestDirection, \
diffuseSolarRadiationToOPV, \
albedoSolarRadiationToOPV = simulatorDetail.calcOPVmoduleSolarIrradianceGHRoof(simulatorClass)
# set the calculated data
simulatorClass.setDirectSolarRadiationToOPVEastDirection(directSolarRadiationToOPVEastDirection)
simulatorClass.setDirectSolarRadiationToOPVWestDirection(directSolarRadiationToOPVWestDirection)
simulatorClass.setDiffuseSolarRadiationToOPV(diffuseSolarRadiationToOPV)
simulatorClass.setAlbedoSolarRadiationToOPV(albedoSolarRadiationToOPV)
# [W m^-2] per hour
totalSolarRadiationToOPV = (simulatorClass.getDirectSolarRadiationToOPVEastDirection() + simulatorClass.getDirectSolarRadiationToOPVWestDirection() ) / 2.0 \
+ simulatorClass.getDiffuseSolarRadiationToOPV() + simulatorClass.getAlbedoSolarRadiationToOPV()
# if constant.ifExportFigures:
# ##################plot the various real light intensity to OPV film start######################
# Title = "various real light intensity to OPV film"
# plotDataSet = np.array([simulatorClass.getDirectSolarRadiationToOPVEastDirection(), simulatorClass.getDirectSolarRadiationToOPVWestDirection(), \
# simulatorClass.getDiffuseSolarRadiationToOPV(), simulatorClass.getAlbedoSolarRadiationToOPV()])
# labelList = np.array(["direct To East Direction", "direct To West Direction", "diffuse", "albedo"])
# xAxisLabel = "time [day]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
# yAxisLabel = "[W m^-2]"
# util.plotMultipleData(np.linspace(0, simulationDaysInt * constant.hourperDay, simulationDaysInt * constant.hourperDay), plotDataSet, labelList, Title, xAxisLabel, yAxisLabel)
# util.saveFigure(Title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
# ##################plot the various real light intensity to OPV film end######################
# ##################plot the difference of total solar radiation with imported data (radiation to horizontal surface) and simulated data (radiation to tilted surface start######################
# hourlyHorizontalTotalOuterSolarIrradiance = simulatorClass.getImportedHourlyHorizontalDirectSolarRadiation() + simulatorClass.getImportedHourlyHorizontalDiffuseSolarRadiation()
# Title = "total solar radiation to OPV with measured data"
# xAxisLabel = "time [hour]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
# yAxisLabel = "total Solar irradiance [W m^-2]"
# util.plotTwoData(np.linspace(0, simulationDaysInt * constant.hourperDay, simulationDaysInt * constant.hourperDay), \
# hourlyHorizontalTotalOuterSolarIrradiance, totalSolarRadiationToOPV, Title, xAxisLabel, yAxisLabel, "measured horizontal", "tilted with measured")
# util.saveFigure(Title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
# ##################plot the difference of total solar radiation with imported data (radiation to horizontal surface) and simulated data (radiation to tilted surface end######################
###################data export start##################
util.exportCSVFile(np.array([year, month, day, hour,
hourlyHorizontalDirectOuterSolarIrradiance,
hourlyHorizontalDiffuseOuterSolarIrradiance,
hourlyHorizontalTotalOuterSolarIrradiance,
simulatorClass.getDirectSolarRadiationToOPVEastDirection(),
simulatorClass.getDirectSolarRadiationToOPVWestDirection(),
simulatorClass.getDiffuseSolarRadiationToOPV(),
simulatorClass.getAlbedoSolarRadiationToOPV(),
totalSolarRadiationToOPV]).T,
"hourlyMeasuredSolarRadiations")
###################data export end##################
# unit change: [W m^-2] -> [umol m^-2 s^-1] == PPFD
directPPFDToOPVEastDirection = util.convertFromWattperSecSquareMeterToPPFD(directSolarRadiationToOPVEastDirection)
directPPFDToOPVWestDirection = util.convertFromWattperSecSquareMeterToPPFD(directSolarRadiationToOPVWestDirection)
diffusePPFDToOPV = util.convertFromWattperSecSquareMeterToPPFD(diffuseSolarRadiationToOPV)
groundReflectedPPFDToOPV = util.convertFromWattperSecSquareMeterToPPFD(albedoSolarRadiationToOPV)
# print"diffusePPFDToOPV.shape:{}".format(diffusePPFDToOPV.shape)
# set the matrix to the object
simulatorClass.setDirectPPFDToOPVEastDirection(directPPFDToOPVEastDirection)
simulatorClass.setDirectPPFDToOPVWestDirection(directPPFDToOPVWestDirection)
simulatorClass.setDiffusePPFDToOPV(diffusePPFDToOPV)
simulatorClass.setGroundReflectedPPFDToOPV(groundReflectedPPFDToOPV)
# unit change: hourly [umol m^-2 s^-1] -> [mol m^-2 day^-1] == daily light integral (DLI) :number of photons received in a square meter per day
directDLIToOPVEastDirection = util.convertFromHourlyPPFDWholeDayToDLI(directPPFDToOPVEastDirection)
directDLIToOPVWestDirection = util.convertFromHourlyPPFDWholeDayToDLI(directPPFDToOPVWestDirection)
diffuseDLIToOPV = util.convertFromHourlyPPFDWholeDayToDLI(diffusePPFDToOPV)
groundReflectedDLIToOPV = util.convertFromHourlyPPFDWholeDayToDLI(groundReflectedPPFDToOPV)
totalDLIToOPV = (directDLIToOPVEastDirection+directDLIToOPVWestDirection) / 2.0 + diffuseDLIToOPV + groundReflectedDLIToOPV
# print "directDLIToOPVEastDirection:{}".format(directDLIToOPVEastDirection)
# print "diffuseDLIToOPV.shape:{}".format(diffuseDLIToOPV.shape)
# print "groundReflectedDLIToOPV:{}".format(groundReflectedDLIToOPV)
# set the array to the object
simulatorClass.setDirectDLIToOPVEastDirection(directDLIToOPVEastDirection)
simulatorClass.setDirectDLIToOPVWestDirection(directDLIToOPVWestDirection)
simulatorClass.setDiffuseDLIToOPV(diffuseDLIToOPV)
simulatorClass.setGroundReflectedDLIToOPV(groundReflectedDLIToOPV)
# If necessary, get the solar radiation data only on 15th day
if util.getSimulationDaysInt() > 31 and constant.ifGet15thDayData:
# measured horizontal data
hourlyMeasuredHorizontalTotalSolarRadiationOnly15th = util.getOnly15thDay(hourlyHorizontalTotalOuterSolarIrradiance)
# measured tilted value
hourlyMeasuredTiltedTotalSolarRadiationOnly15th = util.getOnly15thDay(totalSolarRadiationToOPV)
yearOnly15th = util.getOnly15thDay(year)
monthOnly15th = util.getOnly15thDay(month)
dayOnly15th = util.getOnly15thDay(day)
hourOnly15th = util.getOnly15thDay(hour)
# data export
util.exportCSVFile(np.array([yearOnly15th, monthOnly15th, dayOnly15th, hourOnly15th, hourlyMeasuredHorizontalTotalSolarRadiationOnly15th, hourlyMeasuredTiltedTotalSolarRadiationOnly15th]).T, "hourlyMeasuredTotalSolarRadiationOnly15th")
########################################################################################################################
################# calculate solar irradiance without real data (estimate solar irradiance) start #######################
########################################################################################################################
elif constant.ifUseOnlyRealData == False:
# activate the mode to use the formulas for estimation. This is used for branching the solar irradiance to PV module. See OPVFilm.py
simulatorClass.setEstimateSolarRadiationMode(True)
# calculate the solar radiation to the OPV film
# [W m^-2] per hour
estimatedDirectSolarRadiationToOPVEastDirection, \
estimatedDirectSolarRadiationToOPVWestDirection, \
estimatedDiffuseSolarRadiationToOPV, \
estimatedAlbedoSolarRadiationToOPV = simulatorDetail.calcOPVmoduleSolarIrradianceGHRoof(simulatorClass)
estimatedTotalSolarRadiationToOPV = (estimatedDirectSolarRadiationToOPVEastDirection + estimatedDirectSolarRadiationToOPVWestDirection) / 2.0 + estimatedDiffuseSolarRadiationToOPV + estimatedAlbedoSolarRadiationToOPV
# set the calc results
# [W m^-2] per hour
simulatorClass.setDirectSolarRadiationToOPVEastDirection(estimatedDirectSolarRadiationToOPVEastDirection)
simulatorClass.setDirectSolarRadiationToOPVWestDirection(estimatedDirectSolarRadiationToOPVWestDirection)
simulatorClass.setDiffuseSolarRadiationToOPV(estimatedDiffuseSolarRadiationToOPV)
simulatorClass.setAlbedoSolarRadiationToOPV(estimatedAlbedoSolarRadiationToOPV)
# # modified not to use the following variables
# simulatorClass.setEstimatedDirectSolarRadiationToOPVEastDirection(estimatedDirectSolarRadiationToOPVEastDirection)
# simulatorClass.setEstimatedDirectSolarRadiationToOPVWestDirection(estimatedDirectSolarRadiationToOPVWestDirection)
# simulatorClass.setEstimatedDiffuseSolarRadiationToOPV(estimatedDiffuseSolarRadiationToOPV)
# simulatorClass.setEstimatedAlbedoSolarRadiationToOPV(estimatedAlbedoSolarRadiationToOPV)
# np.set_printoptions(threshold=np.inf)
# print ("estimatedDirectSolarRadiationToOPVEastDirection[W m^-2]:{}".format(estimatedDirectSolarRadiationToOPVEastDirection))
# print ("estimatedDirectSolarRadiationToOPVWestDirection[W m^-2]:{}".format(estimatedDirectSolarRadiationToOPVWestDirection))
# print ("estimatedDiffuseSolarRadiationToOPV[W m^-2]:{}".format(estimatedDiffuseSolarRadiationToOPV))
# print ("estimatedAlbedoSolarRadiationToOPV[W m^-2]:{}".format(estimatedAlbedoSolarRadiationToOPV))
# np.set_printoptions(threshold=1000)
# if constant.ifExportFigures:
# ################## plot the distribution of estimated various DLI to OPV film start######################
# Title = "estimated various light intensity to tilted OPV film"
# plotDataSet = np.array([estimatedDirectSolarRadiationToOPVEastDirection, estimatedDirectSolarRadiationToOPVWestDirection, estimatedDiffuseSolarRadiationToOPV, estimatedAlbedoSolarRadiationToOPV])
# labelList = np.array(["Direct To East Direction", "Direct To West Direction", "Diffuse", "Albedo"])
# xAxisLabel = "time [hour]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
# yAxisLabel = "[W m^-2]"
# util.plotMultipleData(np.linspace(0, simulationDaysInt * constant.hourperDay, simulationDaysInt * constant.hourperDay), plotDataSet, labelList, Title, xAxisLabel, yAxisLabel)
# util.saveFigure(Title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
# ################## plot the distribution of estimated various DLI to OPV film end######################
# ################## plot the imported horizontal data vs estimated data (the tilt should be zeor) ######################
# title = "measured and estimated horizontal data (tilt should be zero)"
# xAxisLabel = "hourly measured horizontal total outer solar radiation [W m^-2]" + constant.SimulationStartDate + "-" + constant.SimulationEndDate
# yAxisLabel = "hourly estimated horizontal Total outer solar radiation [W m^-2]"
# util.plotData(hourlyHorizontalTotalOuterSolarIrradiance, estimatedTotalSolarRadiationToOPV, title, xAxisLabel, yAxisLabel, None, True, 0.0, 1.0)
# util.saveFigure(title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
# ################### plot the electricity yield per area with given OPV film end######################
# [estimated data] unit change:
estimatedDirectPPFDToOPVEastDirection = util.convertFromWattperSecSquareMeterToPPFD(estimatedDirectSolarRadiationToOPVEastDirection)
estimatedDirectPPFDToOPVWestDirection = util.convertFromWattperSecSquareMeterToPPFD(estimatedDirectSolarRadiationToOPVWestDirection)
estimatedDiffusePPFDToOPV = util.convertFromWattperSecSquareMeterToPPFD(estimatedDiffuseSolarRadiationToOPV)
estimatedGroundReflectedPPFDToOPV = util.convertFromWattperSecSquareMeterToPPFD(estimatedAlbedoSolarRadiationToOPV)
# print("estimatedDirectPPFDToOPVEastDirection:{}".format(estimatedDirectPPFDToOPVEastDirection))
# print("estimatedDirectPPFDToOPVWestDirection:{}".format(estimatedDirectPPFDToOPVWestDirection))
# set the variables
simulatorClass.setDirectPPFDToOPVEastDirection(estimatedDirectPPFDToOPVEastDirection)
simulatorClass.setDirectPPFDToOPVWestDirection(estimatedDirectPPFDToOPVWestDirection)
simulatorClass.setDiffusePPFDToOPV(estimatedDiffusePPFDToOPV)
simulatorClass.setGroundReflectedPPFDToOPV(estimatedGroundReflectedPPFDToOPV)
# # modified not to use the following variables
# simulatorClass.setEstimatedDirectPPFDToOPVEastDirection(estimatedDirectPPFDToOPVEastDirection)
# simulatorClass.setEstimatedDirectPPFDToOPVWestDirection(estimatedDirectPPFDToOPVWestDirection)
# simulatorClass.setEstimatedDiffusePPFDToOPV(estimatedDiffusePPFDToOPV)
# simulatorClass.setEstimatedGroundReflectedPPFDToOPV(estimatedGroundReflectedPPFDToOPV)
# [estimated data] unit change:
estimatedDirectDLIToOPVEastDirection = util.convertFromHourlyPPFDWholeDayToDLI(estimatedDirectPPFDToOPVEastDirection)
estimatedDirectDLIToOPVWestDirection = util.convertFromHourlyPPFDWholeDayToDLI(estimatedDirectPPFDToOPVWestDirection)
estimatedDiffuseDLIToOPV = util.convertFromHourlyPPFDWholeDayToDLI(estimatedDiffusePPFDToOPV)
estimatedGroundReflectedDLIToOPV = util.convertFromHourlyPPFDWholeDayToDLI(estimatedGroundReflectedPPFDToOPV)
# estimatedTotalDLIToOPV = (estimatedDirectDLIToOPVEastDirection + estimatedDirectDLIToOPVWestDirection) / 2.0 + estimatedDiffuseDLIToOPV + estimatedGroundReflectedDLIToOPV
# set the variables
# # modified not to use the following variables
# simulatorClass.setEstimatedDirectDLIToOPVEastDirection(estimatedDirectDLIToOPVEastDirection)
# simulatorClass.setEstimatedDirectDLIToOPVWestDirection(estimatedDirectDLIToOPVWestDirection)
# simulatorClass.setEstimatedDiffuseDLIToOPV(estimatedDiffuseDLIToOPV)
# simulatorClass.setEestimatedGroundReflectedDLIToOPV(estimatedGroundReflectedDLIToOPV)
simulatorClass.setDirectDLIToOPVEastDirection(estimatedDirectDLIToOPVEastDirection)
simulatorClass.setDirectDLIToOPVWestDirection(estimatedDirectDLIToOPVWestDirection)
simulatorClass.setDiffuseDLIToOPV(estimatedDiffuseDLIToOPV)
simulatorClass.setGroundReflectedDLIToOPV(estimatedGroundReflectedDLIToOPV)
# deactivate the mode to the default value.
simulatorClass.setEstimateSolarRadiationMode(False)
# data export of solar irradiance
util.exportCSVFile(np.array([year, month, day, hour,
simulatorClass.directHorizontalSolarRadiation,
simulatorClass.diffuseHorizontalSolarRadiation,
simulatorClass.totalHorizontalSolarRadiation,
simulatorClass.getDirectSolarRadiationToOPVEastDirection(),
simulatorClass.getDirectSolarRadiationToOPVWestDirection(),
simulatorClass.getDiffuseSolarRadiationToOPV(),
simulatorClass.getAlbedoSolarRadiationToOPV(),
estimatedTotalSolarRadiationToOPV]).T,
"estimatedSolarIrradiance")
# If necessary, get the solar radiation data only on 15th day
if util.getSimulationDaysInt() > 31 and constant.ifGet15thDayData:
# estimated horizontal value
hourlyEstimatedTotalHorizontalSolarRadiationOnly15th = util.getOnly15thDay(simulatorClass.totalHorizontalSolarRadiation)
# estmated tilted data
hourlyEstimatedTotalTiltedSolarRadiationToOPVOnly15th = util.getOnly15thDay(estimatedTotalSolarRadiationToOPV)
yearOnly15th = util.getOnly15thDay(year)
monthOnly15th = util.getOnly15thDay(month)
dayOnly15th = util.getOnly15thDay(day)
hourOnly15th = util.getOnly15thDay(hour)
# data export
util.exportCSVFile(np.array([yearOnly15th, monthOnly15th, dayOnly15th, hourOnly15th, hourlyEstimatedTotalHorizontalSolarRadiationOnly15th, hourlyEstimatedTotalTiltedSolarRadiationToOPVOnly15th]).T,
"hourlyEstimatedTotalSolarRadiationOnly15th")
# util.exportCSVFile(hourlyEstimatedTotalSolarRadiationToOPVOnly15th, "hourlyEstimatedTotalSolarRadiationToOPVOnly15th")
# if constant.ifExportFigures:
# ##################plot the difference of total solar radiation with imported data and simulated data start######################
# Title = "total solar radiation to OPV with measured horizontal and estimated tilted"
# xAxisLabel = "time [hour]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
# yAxisLabel = "total Solar irradiance [W m^-2]"
# util.plotTwoData(np.linspace(0, simulationDaysInt * constant.hourperDay, simulationDaysInt * constant.hourperDay), \
# hourlyHorizontalTotalOuterSolarIrradiance, estimatedTotalSolarRadiationToOPV ,Title, xAxisLabel, yAxisLabel, "measured horizontal", "estimated tilted")
# util.saveFigure(Title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
# ##################plot the difference of total solar radiation with imported data and simulated data end######################
# ################## plot the difference of total DLI with real data and simulated data start######################
# Title = "difference of total DLI to tilted OPV with real data and estimation"
# xAxisLabel = "time [hour]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
# yAxisLabel = "DLI [mol m^-2 day^-1]"
# util.plotTwoData(np.linspace(0, simulationDaysInt, simulationDaysInt), \
# totalDLIToOPV, estimatedTotalDLIToOPV ,Title, xAxisLabel, yAxisLabel, "with real data", "wth no data")
# util.saveFigure(Title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
# ################## plot the difference of total DLI with real data and simulated data end######################
################# calculate solar irradiance without real data (estimate the data) end #######################
# # ####################################################################################################
# # Stop execution here...
# sys.exit()
# # Move the above line to different parts of the assignment as you implement more of the functionality.
# # ####################################################################################################
# # export measured horizontal and estimated data only when the simulation date is 1 day. *Modify the condition if necessary.
# elif constant.ifExportMeasuredHorizontalAndExtimatedData == True and util.getSimulationDaysInt() == 1:
# util.exportCSVFile(np.array([estimatedTotalSolarRadiationToOPV, hourlyHorizontalTotalOuterSolarIrradiance]).T, "hourlyMeasuredHOrizontalAndEstimatedTotalSolarRadiation")
# if constant.ifExportFigures:
# ################## plot the distribution of direct and diffuse PPFD start######################
# Title = "TOTAL outer PPFD to OPV"
# xAxisLabel = "time [hour]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
# yAxisLabel = "PPFD [umol m^-2 s^-1]"
# util.plotData(np.linspace(0, simulationDaysInt * constant.hourperDay, simulationDaysInt * constant.hourperDay), \
# directPPFDToOPV + diffusePPFDToOPV + groundReflectedPPFDToOPV, Title, xAxisLabel, yAxisLabel)
# util.saveFigure(Title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
# ################## plot the distribution of direct and diffuse PPFD end######################
# ################## plot the distribution of direct and diffuse solar DLI with real data start######################
# Title = "direct and diffuse outer DLI to OPV"
# xAxisLabel = "time [day]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
# yAxisLabel = "DLI [mol m^-2 day^-1]"
# y1Label = "(directDLIToOPVEastDirection+directDLIToOPVWestDirection)/2.0"
# y2Label = "diffuseDLIToOPV"
# util.plotTwoData(np.linspace(0, simulationDaysInt, simulationDaysInt), (directDLIToOPVEastDirection+directDLIToOPVWestDirection)/2.0, diffuseDLIToOPV, Title,
# xAxisLabel, yAxisLabel, y1Label, y2Label)
# util.saveFigure(Title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
# ################## plot the distribution of direct and diffuse solar DLI end######################
# ################## plot the distribution of various DLI to OPV film start######################
# Title = "various DLI to OPV film"
# plotDataSet = np.array([simulatorClass.getDirectDLIToOPVEastDirection(), simulatorClass.getDirectDLIToOPVWestDirection(), simulatorClass.getDiffuseDLIToOPV(), simulatorClass.getGroundReflectedDLIToOPV()])
# labelList = np.array(["directDLIToOPVEastDirection", "directDLIToOPVWestDirection", "diffuseDLIToOPV", "groundReflectedDLIToOPV"])
# xAxisLabel = "time [day]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
# yAxisLabel = "DLI [mol m^-2 day^-1]"
# util.plotMultipleData(np.linspace(0, simulationDaysInt, simulationDaysInt), plotDataSet, labelList, Title, xAxisLabel, yAxisLabel)
# util.saveFigure(Title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
# ################## plot the distribution of various DLI to OPV film end######################
############################################################################################
################## calculate the daily electricity yield per area start#####################
############################################################################################
# TODO: for more accurate modeling, we need actual data (considering the OPV material) for the temperature of OPV film, but right now, just use the imported body temperature.
# get the daily electricity yield per area per day ([J/m^2/day]) based on the given light intensity ([Celsius],[W/m^2]).
# regard the east side and west tilted OPV module differently/
dailyJopvoutperAreaEastRoof = simulatorDetail.getDailyElectricityYieldperArea(simulatorClass, hourlyHorizontalTotalBeamMeterBodyTemperature, \
simulatorClass.getDirectSolarRadiationToOPVEastDirection(),
simulatorClass.getDiffuseSolarRadiationToOPV(),
simulatorClass.getAlbedoSolarRadiationToOPV())
dailyJopvoutperAreaWestRoof = simulatorDetail.getDailyElectricityYieldperArea(simulatorClass, hourlyHorizontalTotalBeamMeterBodyTemperature, \
simulatorClass.getDirectSolarRadiationToOPVWestDirection(),
simulatorClass.getDiffuseSolarRadiationToOPV(),
simulatorClass.getAlbedoSolarRadiationToOPV())
# print("dailyJopvoutperAreaEastRoof:{}".format(dailyJopvoutperAreaEastRoof))
# print("dailyJopvoutperAreaWestRoof:{}".format(dailyJopvoutperAreaWestRoof))
# unit change [J/m^2/day] -> [Wh/m^2/day]
# dailyWhopvoutperArea = util.convertFromJouleToWattHour(dailyJopvoutperArea)
dailyWhopvoutperAreaEastRoof = util.convertFromJouleToWattHour(dailyJopvoutperAreaEastRoof)
dailyWhopvoutperAreaWestRoof = util.convertFromJouleToWattHour(dailyJopvoutperAreaWestRoof)
# set the variables
simulatorClass.dailyWhopvoutperAreaEastRoof = dailyWhopvoutperAreaEastRoof
simulatorClass.dailyWhopvoutperAreaWestRoof = dailyWhopvoutperAreaWestRoof
# print("dailyWhopvoutperAreaEastRoof:{}".format(dailyWhopvoutperAreaEastRoof))
# print("dailyWhopvoutperAreaWestRoof:{}".format(dailyWhopvoutperAreaWestRoof ))
# electricity production unit Exchange [Wh/m^2/day] -> [kWh/m^2/day]
# dailykWhopvoutperArea = util.convertWhTokWh(dailyWhopvoutperArea)
dailykWhopvoutperAreaEastRoof = util.convertWhTokWh(dailyWhopvoutperAreaEastRoof)
dailykWhopvoutperAreaWestRoof = util.convertWhTokWh(dailyWhopvoutperAreaWestRoof)
# set the variables
simulatorClass.dailykWhopvoutperAreaEastRoof = dailykWhopvoutperAreaEastRoof
simulatorClass.dailykWhopvoutperAreaWestRoof = dailykWhopvoutperAreaWestRoof
# print("dailykWhopvoutperAreaEastRoof[kWh/m^2/day]:{}".format(dailykWhopvoutperAreaEastRoof))
# print("dailykWhopvoutperAreaWestRoof[kWh/m^2/day]:{}".format(dailykWhopvoutperAreaWestRoof))
# the total electricity produced (unit exchange: [kWh/m^2/day] -> [kWh/day])
# consider that the coverage ratio can be different during summer
OPVAreaCoverageRatioChangingInSummer = OPVFilm.getDifferentOPVCoverageRatioInSummerPeriod(constant.OPVAreaCoverageRatio, simulatorClass)
# change the number of elements: per hour -> per day
OPVAreaCoverageRatioPerDayChangingInSummer = OPVAreaCoverageRatioChangingInSummer[::constant.hourperDay]
# totalkWhopvoutPerday = dailykWhopvoutperAreaEastRoof * (constant.OPVAreaFacingEastOrNorthfacingRoof) + dailykWhopvoutperAreaWestRoof * (constant.OPVAreaFacingWestOrSouthfacingRoof)
totalkWhopvoutPerday = dailykWhopvoutperAreaEastRoof * OPVAreaCoverageRatioPerDayChangingInSummer * constant.greenhouseTotalRoofArea
# totalkWhopvoutPerAreaPerday = totalkWhopvoutPerday/constant.greenhouseTotalRoofArea
totalkWhopvoutPerRoofAreaPerday = totalkWhopvoutPerday/constant.greenhouseTotalRoofArea
# set the calculated value
simulatorClass.totalkWhopvoutPerday = totalkWhopvoutPerday
simulatorClass.totalkWhopvoutPerAreaPerday = totalkWhopvoutPerRoofAreaPerday
# print("totalkWhopvoutPerday[kWh/day]:{}".format(totalkWhopvoutPerday))
# print("totalkWhopvoutPerAreaPerday[kWh/m^2/day]:{}".format(totalkWhopvoutPerAreaPerday))
# if constant.ifExportFigures:
# ################### plot the electricity yield per area with given OPV film
# title = "electricity yield per area vs OPV film (east_west average)"
# xAxisLabel = "time [day]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
# yAxisLabel = "Electricity yield per OPV area [kWh/m^2/day]"
# util.plotData(np.linspace(0, simulationDaysInt, simulationDaysInt), (dailykWhopvoutperAreaEastRoof + dailykWhopvoutperAreaWestRoof)/2.0, title, xAxisLabel, yAxisLabel)
# util.saveFigure(title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
# ################### plot the electricity yield per area with given OPV film end
# data export
util.exportCSVFile(np.array([year[::24], month[::24], day[::24], dailykWhopvoutperAreaEastRoof, dailykWhopvoutperAreaWestRoof]).T,
"dailyElectricEnergyFromRoofsFacingEachDirection")
##########################################################################################
################## calculate the daily electricity yield per area end#####################
##########################################################################################
##########################################################################################
################## calculate the daily electricity sales per area start###################
##########################################################################################
# convert the year of each hour to the year to each day
yearOfeachDay = year[::24]
# convert the month of each hour to the month to each day
monthOfeachDay = month[::24]
# get the monthly electricity sales per area [USD/month/m^2]
monthlyElectricitySalesperAreaEastRoof = simulatorDetail.getMonthlyElectricitySalesperArea(dailyJopvoutperAreaEastRoof, yearOfeachDay, monthOfeachDay ,simulatorClass)
monthlyElectricitySalesperAreaWastRoof = simulatorDetail.getMonthlyElectricitySalesperArea(dailyJopvoutperAreaWestRoof, yearOfeachDay, monthOfeachDay, simulatorClass)
# print("monthlyElectricitySalesperAreaEastRoof:{}".format(monthlyElectricitySalesperAreaEastRoof))
# print("monthlyElectricitySalesperAreaWastRoof:{}".format(monthlyElectricitySalesperAreaWastRoof))
# set the value to the object
simulatorClass.setMonthlyElectricitySalesperAreaEastRoof(monthlyElectricitySalesperAreaEastRoof)
simulatorClass.setMonthlyElectricitySalesperAreaWestRoof(monthlyElectricitySalesperAreaWastRoof)
# print "simulatorClass.getMonthlyElectricitySalesperArea():{}".format(simulatorClass.getMonthlyElectricitySalesperArea())
# electricity sales unit Exchange [USD/m^2/month] -> [USD/month]
totalElectricitySalesPerMonth = monthlyElectricitySalesperAreaEastRoof * constant.OPVAreaFacingEastOrNorthfacingRoof + monthlyElectricitySalesperAreaWastRoof * constant.OPVAreaFacingWestOrSouthfacingRoof
# print("totalElectricitySalesPerMonth[USD/month]:{}".format(totalElectricitySalesPerMonth))
# the averaged electricity sales [USD/m^2/month]
if constant.OPVArea == 0.0:
totalElectricitySalesPerOPVAreaPerMonth = [0.0]
else:
totalElectricitySalesPerOPVAreaPerMonth = totalElectricitySalesPerMonth / constant.OPVArea
# set the value to the object
simulatorClass.totalElectricitySalesPerAreaPerMonth = totalElectricitySalesPerOPVAreaPerMonth
simulatorClass.totalElectricitySalesPerMonth = totalElectricitySalesPerMonth
simulatorClass.totalElectricitySales = sum(totalElectricitySalesPerMonth)
# print("totalElectricitySalesPerMonth:{}".format(totalElectricitySalesPerMonth))
# print("totalElectricitySales:{}".format(sum(totalElectricitySalesPerMonth)))
###########################################################################################
################## calculate the daily electricity sales per area end#####################
###########################################################################################
#####################################################################################################
##################calculate the electricity cost per area start######################################
#####################################################################################################
if constant.ifConsiderOPVCost is True:
# get the depreciation price for the whole simulation period
# it was assumed that the depreciation method is straight line method
# unit: USD
# initialOPVCostUSD = constant.OPVPricePerAreaUSD * OPVFilm.getOPVArea(constant.OPVAreaCoverageRatio)
initialOPVCostUSD = constant.OPVPricePerAreaUSD * OPVFilm.getOPVArea(max(simulatorClass.OPVCoverageRatiosConsiderSummerRatio))
# print("initialOPVCostUSD:{}".format(initialOPVCostUSD))
# unit: USD/day
totalOPVCostUSDForDepreciation = initialOPVCostUSD * (util.getSimulationDaysInt() / constant.OPVDepreciationPeriodDays)
# set the value to the object
# print("totalOPVCostUSDForDepreciation:{}".format(totalOPVCostUSDForDepreciation))
# print("OPVFilm.getOPVArea(constant.OPVAreaCoverageRatio):{}".format(OPVFilm.getOPVArea(constant.OPVAreaCoverageRatio)))
if constant.OPVAreaCoverageRatio == 0.0:
simulatorClass.setOPVCostUSDForDepreciationPerOPVArea(0.0)
else:
simulatorClass.setOPVCostUSDForDepreciationPerOPVArea(totalOPVCostUSDForDepreciation / OPVFilm.getOPVArea(constant.OPVAreaCoverageRatio))
simulatorClass.totalOPVCostUSDForDepreciation = totalOPVCostUSDForDepreciation
simulatorClass.totalOPVCostUSDForDepreciationPerGHFloorArea = totalOPVCostUSDForDepreciation / constant.greenhouseFloorArea
# print("OPVCostUSDForDepreciationPerOPVArea:{}".format(totalOPVCostUSDForDepreciation / OPVFilm.getOPVArea(constant.OPVAreaCoverageRatio)))
# print("totalOPVCostUSDForDepreciation:{}".format(totalOPVCostUSDForDepreciation))
else:
# set the value to the object. the value is zero if not consider the purchase cost
simulatorClass.setOPVCostUSDForDepreciationPerOPVArea(0.0)
simulatorClass.totalOPVCostUSDForDepreciation = 0.0
simulatorClass.totalOPVCostUSDForDepreciationPerGHFloorArea = 0.0
###################################################################################################
##################calculate the electricity cost per area end######################################
###################################################################################################
################################################################################
################## calculate the electricity production profit/loss start#######
################################################################################
# profit == sales - less(cost)
electricityProductionProfit = simulatorClass.totalElectricitySales - simulatorClass.totalOPVCostUSDForDepreciation
electricityProductionProfitPerGHFloorArea = electricityProductionProfit / constant.greenhouseFloorArea
# set the variable to the object
simulatorClass.electricityProductionProfit = electricityProductionProfit
simulatorClass.electricityProductionProfitPerGHFloorArea = electricityProductionProfitPerGHFloorArea
################################################################################
################## calculate the electricity production profit/loss end#########
################################################################################
###############################################################################################
###################calculate the solar irradiance through multi span roof start################
###############################################################################################
# The calculated irradiance is stored to the object in this function
simulatorDetail.setDirectSolarIrradianceThroughMultiSpanRoof(simulatorClass)
# data export
util.exportCSVFile(np.array([year, month, day, hour, simulatorClass.integratedT_mat, simulatorClass.getHourlyDirectSolarRadiationAfterMultiSpanRoof(),]).T,
"directSolarRadiationAfterMultiSpanRoof")
###########################################################################################
###################calculate the solar irradiance through multi span roof end##############
###########################################################################################
###########################################################################################
###################calculate the solar irradiance to plants start##########################
###########################################################################################
# get/set cultivation days per harvest [days/harvest]
cultivationDaysperHarvest = constant.cultivationDaysperHarvest
simulatorClass.setCultivationDaysperHarvest(cultivationDaysperHarvest)
# get/set OPV coverage ratio [-]
OPVCoverage = constant.OPVAreaCoverageRatio
simulatorClass.setOPVAreaCoverageRatio(OPVCoverage)
# get/set OPV coverage ratio during fallow period[-]
OPVCoverageSummerPeriod = constant.OPVAreaCoverageRatioSummerPeriod
simulatorClass.setOPVCoverageRatioSummerPeriod(OPVCoverageSummerPeriod)
# get if we assume to have shading curtain
hasShadingCurtain = constant.hasShadingCurtain
simulatorClass.setIfHasShadingCurtain(hasShadingCurtain)
# consider the OPV film, shading curtain, structure,
simulatorDetail.setSolarIrradianceToPlants(simulatorClass)
# data export
util.exportCSVFile(np.array([year, month, day, hour, simulatorClass.transmittanceThroughShadingCurtainChangingEachMonth]).T, "transmittanceThroughShadingCurtain")
util.exportCSVFile(np.array([year, month, day, hour, simulatorClass.directSolarIrradianceToPlants, simulatorClass.diffuseSolarIrradianceToPlants]).T, "solarIrradianceToPlants")
# the DLI to plants [mol/m^2/day]
# totalDLItoPlants = simulatorDetail.getTotalDLIToPlants(OPVCoverage, importedDirectPPFDToOPV, importedDiffusePPFDToOPV, importedGroundReflectedPPFDToOPV,\
# hasShadingCurtain, shadingCurtainDeployPPFD, simulatorClass)
totalDLItoPlants = simulatorClass.directDLIToPlants + simulatorClass.diffuseDLIToPlants
# print("totalDLItoPlants:{}".format(totalDLItoPlants))
# print "totalDLItoPlants.shape:{}".format(totalDLItoPlants.shape)
# unit: DLI/day
simulatorClass.totalDLItoPlants = totalDLItoPlants
# if constant.ifExportFigures:
# ######################### plot a graph showing the DLI to plants ######################################
# title = "DLI to plants (OPV coverage " + str(int(100*OPVCoverage)) + "%)"
# xAxisLabel = "time [day]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
# yAxisLabel = "DLI[mol/m^2/day]"
# util.plotData(np.linspace(0, simulationDaysInt, simulationDaysInt), totalDLItoPlants, title, xAxisLabel, yAxisLabel)
# util.saveFigure(title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
# #######################################################################################################
########################################################################################
###################calculate the solar irradiance to plants end#########################
########################################################################################
# ####################################################################################################
# # Stop execution here...
# sys.exit()
# # Move the above line to different parts of the assignment as you implement more of the functionality.
# ####################################################################################################
#############################################################################
################## calculate the daily plant yield start#####################
#############################################################################
# # On the model, since it was assumed the temperature in the greenhouse is maintained at the set point by cooling system (pad and fan system), this function is not used.
# # calc/set the thermal time to the object
# simulatorDetail.setThermalTimeToPlants(simulatorClass)
# get/set the plant growth model name [String]
plantGrowthModel = constant.plantGrowthModel
simulatorClass.setPlantGrowthModel(plantGrowthModel)
#calculate plant yield given an OPV coverage and model :daily [g/head]
shootFreshMassList, \
dailyFreshWeightPerHeadIncrease, \
accumulatedDailyFreshWeightPerHeadIncrease, \
dailyHarvestedFreshWeightPerHead = simulatorDetail.getPlantYieldSimulation(simulatorClass)
# np.set_printoptions(threshold=np.inf)
# print ("shootFreshMassList:{}".format(shootFreshMassList))
# print ("dailyFreshWeightPerHeadIncrease:{}".format(dailyFreshWeightPerHeadIncrease))
# print ("accumulatedDailyFreshWeightPerHeadIncrease:{}".format(accumulatedDailyFreshWeightPerHeadIncrease))
# print ("dailyHarvestedFreshWeightPerHead:{}".format(dailyHarvestedFreshWeightPerHead))
# np.set_printoptions(threshold=100)
# get the penalized plant fresh weight with too strong sunlight : :daily [g/unit]
# In this research, it was concluded not to assumed the penalty function. According to Jonathan M. Frantz and Glen Ritchie "2004". Exploring the Limits of Crop Productivity: Beyond the Limits of Tipburn in Lettuce, the literature on lettuce response to high PPF is not clear, and indeed, I also found there is a contradiction between Fu et al. (2012). Effects of different light intensities on anti-oxidative enzyme activity, quality and biomass in lettuce, and Jonathan M. Frantz and Glen Ritchie (2004) on this discussion.
if constant.IfConsiderPhotoInhibition is True:
penalizedDailyHarvestedFreshWeightPerHead = simulatorDetail.penalizeDailyHarvestedFreshWeightPerHead(dailyHarvestedFreshWeightPerHead, simulatorClass)
print("penalizedDailyHarvestedFreshWeightPerHead:{}".format(penalizedDailyHarvestedFreshWeightPerHead))
if constant.ifExportFigures:
######################### plot dailyHarvestedFreshWeightPerHead and penalized dailyHarvestedFreshWeightPerHead
# if no penalty occurs, these variables plot the same dots.
title = "HarvestedFreshWeight and penalized HarvestedFreshWeight "
xAxisLabel = "time [day]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
yAxisLabel = "plant fresh weight[g/unit]"
util.plotTwoData(np.linspace(0, util.getSimulationDaysInt(), util.getSimulationDaysInt()), \
dailyHarvestedFreshWeightPerHead, penalizedDailyHarvestedFreshWeightPerHead, title, xAxisLabel, yAxisLabel, "real data", "penalized data")
util.saveFigure(title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
#######################################################################
# ######################### plot a graph showing only shootFreshMassList per unit #######################
# title = "plant yield per head vs time (OPV coverage " + str(int(100*OPVCoverage)) + "%)"
# xAxisLabel = "time [day]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
# yAxisLabel = "plant fresh weight[g/head]"
# util.plotData(np.linspace(0, simulationDaysInt, simulationDaysInt), shootFreshMassList, title, xAxisLabel, yAxisLabel)
# util.saveFigure(title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
# #######################################################################################################
# ############command to print out all array data
# np.set_printoptions(threshold=np.inf)
# print("simulatorClass.LeafAreaIndex_J_VanHenten1994:{}".format(simulatorClass.LeafAreaIndex_J_VanHenten1994))
# np.set_printoptions(threshold=1000)
# ############
# data export
util.exportCSVFile(np.array([year[::24], month[::24], day[::24], totalDLItoPlants, shootFreshMassList]).T, "shootFreshMassAndDLIToPlants")
# util.exportCSVFile(np.array([year[::24], month[::24], day[::24], simulatorClass.LeafAreaIndex_J_VanHenten1994]).T, "LeafAreaIndex_J_VanHenten1994")
# unit conversion; get the plant yield per day per area: [g/head/day] -> [g/m^2/day]
shootFreshMassPerCultivationFloorAreaPerDay = util.convertUnitShootFreshMassToShootFreshMassperArea(shootFreshMassList)
# print("shootFreshMassPerAreaPerDay:{}".format(shootFreshMassPerAreaPerDay))
# unit [g/head] -> [g/m^2]
harvestedShootFreshMassPerCultivationFloorAreaPerDay = util.convertUnitShootFreshMassToShootFreshMassperArea(dailyHarvestedFreshWeightPerHead)
# print("harvestedShootFreshMassPerCultivationFloorAreaPerDay:{}".format(harvestedShootFreshMassPerCultivationFloorAreaPerDay))
# unit conversion: [g/m^2/day] -> [kg/m^2/day]
shootFreshMassPerCultivationFloorAreaKgPerDay = util.convertFromgramTokilogram(shootFreshMassPerCultivationFloorAreaPerDay)
harvestedShootFreshMassPerCultivationFloorAreaKgPerDay = util.convertFromgramTokilogram(harvestedShootFreshMassPerCultivationFloorAreaPerDay)
# print("harvestedShootFreshMassPerCultivationFloorAreaKgPerDay:{}".format(harvestedShootFreshMassPerCultivationFloorAreaKgPerDay))
# set the value to the object
simulatorClass.shootFreshMassPerAreaKgPerDay = shootFreshMassPerCultivationFloorAreaKgPerDay
simulatorClass.harvestedShootFreshMassPerAreaKgPerDay = harvestedShootFreshMassPerCultivationFloorAreaKgPerDay
simulatorClass.totalHarvestedShootFreshMass = sum(harvestedShootFreshMassPerCultivationFloorAreaKgPerDay) * constant.greenhouseCultivationFloorArea
# print("shootFreshMassPerAreaKgPerDay:{}".format(shootFreshMassPerCultivationFloorAreaKgPerDay))
# print("harvestedShootFreshMassPerCultivationFloorAreaKgPerDay:{}".format(harvestedShootFreshMassPerCultivationFloorAreaKgPerDay))
# print("simulatorClass.totalHarvestedShootFreshMass:{}".format(simulatorClass.totalHarvestedShootFreshMass))
if constant.ifExportFigures:
# ######################## plot a graph showing only shootFreshMassList per square meter ########################
# title = "plant yield per area vs time (OPV coverage " + str(int(100*OPVCoverage)) + "%)"
# xAxisLabel = "time [day]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
# yAxisLabel = "plant fresh weight[kg/m^2]"
# util.plotData(np.linspace(0, simulationDaysInt, simulationDaysInt), shootFreshMassPerAreaKgPerDay, title, xAxisLabel, yAxisLabel)
# util.saveFigure(title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
# ###############################################################################################################
################## plot various unit Plant Yield vs time
# plotDataSet = np.array([shootFreshMassList, dailyFreshWeightPerHeadIncrease, accumulatedDailyFreshWeightPerHeadIncrease, dailyHarvestedFreshWeightPerHead])
# labelList = np.array(["shootFreshMassList", "dailyFreshWeightPerHeadIncrease", "accumulatedDailyFreshWeightPerHeadIncrease", "dailyHarvestedFreshWeightPerHead"])
plotDataSet = np.array([shootFreshMassList, dailyFreshWeightPerHeadIncrease, dailyHarvestedFreshWeightPerHead])
labelList = np.array(["shootFreshMassList", "dailyFreshWeightPerHeadIncrease", "dailyHarvestedFreshWeightPerHead"])
title = "Various unit Plant Yield vs time (OPV coverage " + str(int(100*OPVCoverage)) + "%)"
xAxisLabel = "time [day]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
yAxisLabel = "Unit plant Fresh Weight [g/unit]"
yMin = 0.0
# yMax = 1850.0
yMax = 300.0
util.plotMultipleData(np.linspace(0, simulationDaysInt, simulationDaysInt), plotDataSet, labelList, title, xAxisLabel, yAxisLabel, yMin, yMax)
util.saveFigure(title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
#######################################################################
# data export
util.exportCSVFile(np.array([shootFreshMassList, dailyFreshWeightPerHeadIncrease, dailyHarvestedFreshWeightPerHead]).T, "VariousPlantYieldVsTime")
##########################################################################
################## calculate the daily plant yield end####################
##########################################################################
##########################################################################
################## calculate the daily plant sales start##################
##########################################################################
# get the sales price of plant [USD/m^2]
# It was assumed that there is no tipburn.
# unit: USD/m^2/day
dailyPlantSalesPerSquareMeter = simulatorDetail.getPlantSalesperSquareMeter(simulatorClass)
# print ("dailyPlantSalesperSquareMeter.shape:{}".format(dailyPlantSalesperSquareMeter.shape))
# unit: USD/m^2
# This sales is the sales per unit cultivation area, not per the whole greenhouse floor area.
totalPlantSalesPerCultivationFloorArea = sum(dailyPlantSalesPerSquareMeter)
# print ("totalPlantSalesperSquareMeter(USD):{}".format(totalPlantSalesPerCultivationFloorArea))
# unit: USD
totalplantSales = totalPlantSalesPerCultivationFloorArea * constant.greenhouseCultivationFloorArea
print ("totalplantSales(USD):{}".format(totalplantSales))
totalPlantSalesPerGHFloorArea = totalplantSales / constant.greenhouseFloorArea
# set the variable to the object
simulatorClass.totalPlantSalesperSquareMeter = totalPlantSalesPerCultivationFloorArea
simulatorClass.totalplantSales = totalplantSales
simulatorClass.totalPlantSalesPerGHFloorArea = totalPlantSalesPerGHFloorArea
print("totalPlantSalesPerGHFloorArea:{}".format(totalPlantSalesPerGHFloorArea))
##########################################################################
################## calculate the daily plant sales end####################
##########################################################################
######################################################################################################
################## calculate the daily plant cost (greenhouse operation cost) start###################
######################################################################################################
# it was assumed that the cost for growing plants is significantly composed of labor cost and electricity and fuel energy cost for heating/cooling (including pad and fan system)
# get the cost for cooling and heating
totalHeatingCostForPlants, totalCoolingCostForPlants = simulatorDetail.getGreenhouseOperationCostForGrowingPlants(simulatorClass)
# data export
util.exportCSVFile(np.array([simulatorClass.Q_v["coolingOrHeatingEnergy W m-2"], simulatorClass.Q_sr["solarIrradianceToPlants W m-2"], simulatorClass.Q_lh["latentHeatByTranspiration W m-2"], \
simulatorClass.Q_sh["sensibleHeatFromConductionAndConvection W m-2"], simulatorClass.Q_lw["longWaveRadiation W m-2"]]).T, "energeBalance(W m-2)")
# # data export
# util.exportCSVFile(np.array([simulatorClass.s, simulatorClass.gamma_star, simulatorClass.r_s, \
# simulatorClass.r_b, simulatorClass.e_s, simulatorClass.e_a, simulatorClass.R_n, \
# simulatorClass.r_a, simulatorClass.r_b, simulatorClass.L, simulatorClass.r_c ]).T, "latentHeatCalcData")
totalHeatingCostForPlantsPerGHFloorArea = totalHeatingCostForPlants / constant.greenhouseFloorArea
totalCoolingCostForPlantsPerGHFloorArea = totalCoolingCostForPlants / constant.greenhouseFloorArea
totalLaborCost = simulatorDetail.getLaborCost(simulatorClass)
totalLaborCostPerGHFloorArea = totalLaborCost / constant.greenhouseFloorArea
# set the values to the object
simulatorClass.totalLaborCost = totalLaborCost
simulatorClass.totalLaborCostPerGHFloorArea = totalLaborCostPerGHFloorArea
totalPlantProductionCost = totalHeatingCostForPlants + totalCoolingCostForPlants + totalLaborCost
totalPlantProductionCostPerGHFloorArea = totalHeatingCostForPlantsPerGHFloorArea + totalCoolingCostForPlantsPerGHFloorArea + totalLaborCostPerGHFloorArea
# set the values to the object
simulatorClass.totalPlantProductionCost = totalPlantProductionCost
simulatorClass.totalPlantProductionCostPerGHFloorArea = totalPlantProductionCostPerGHFloorArea
print("totalPlantProductionCost:{}".format(totalPlantProductionCost))
print("totalPlantProductionCostPerGHFloorArea:{}".format(totalPlantProductionCostPerGHFloorArea))
######################################################################################################
################## calculate the daily plant cost (greenhouse operation cost) end#####################
######################################################################################################
################################################################################
################## calculate the plant production profit/los start##############
################################################################################
totalPlantProfit = totalplantSales - totalPlantProductionCost
totalPlantProfitPerGHFloorArea = totalPlantSalesPerGHFloorArea - totalPlantProductionCostPerGHFloorArea
# set the values to the object
simulatorClass.totalPlantProfit = totalPlantProfit
simulatorClass.totalPlantProfitPerGHFloorArea = totalPlantProfitPerGHFloorArea
# print("totalPlantProfit:{}".format(totalPlantProfit))
# print("totalPlantProfitPerGHFloorArea:{}".format(totalPlantProfitPerGHFloorArea))
################################################################################
################## calculate the plant production profit/loss end###############
################################################################################
################################################################################
################## calculate the total economic profit/loss start###############
################################################################################
# get the economic profit
economicProfit = totalPlantProfit + electricityProductionProfit
economicProfitPerGHFloorArea = totalPlantProfitPerGHFloorArea + electricityProductionProfitPerGHFloorArea
# set the values to the object
simulatorClass.economicProfit = economicProfit
simulatorClass.economicProfitPerGHFloorArea = economicProfitPerGHFloorArea
print("economicProfit:{}".format(economicProfit))
print("economicProfitPerGHFloorArea:{}".format(economicProfitPerGHFloorArea))
##############################################################################
################## calculate the total economic profit/loss end###############
##############################################################################
# data export
# util.exportCSVFile(np.array([[simulatorClass.totalHarvestedShootFreshMass, simulatorClass.totalElectricitySales], [simulatorClass.totalOPVCostUSDForDepreciation], \
# [totalplantSales], [totalPlantSalesPerGHFloorArea], [totalPlantProductionCost], [totalPlantProductionCostPerGHFloorArea], \
# [economicProfit], [economicProfitPerGHFloorArea]]).T, "yieldProfitSalesCost")
# print("simulatorClass.totalHarvestedShootFreshMass:{}".format(simulatorClass.totalHarvestedShootFreshMass))
util.exportCSVFile(np.array([[simulatorClass.totalHarvestedShootFreshMass], [simulatorClass.totalElectricitySales], [simulatorClass.totalOPVCostUSDForDepreciation], \
[totalplantSales], [totalPlantSalesPerGHFloorArea], [totalPlantProductionCost], [totalPlantProductionCostPerGHFloorArea], \
[economicProfit], [economicProfitPerGHFloorArea]]).T, "yieldProfitSalesCost")
# print ("end modeling: datetime.datetime.now():{}".format(datetime.datetime.now()))
return simulatorClass
# def optimizeOPVCoverageRatio(simulatorClass):
# ############################################################################################
# ###################Simulation with various opv film coverage ratio start####################
# ############################################################################################
# # Choose the simulation type
# # simulationType = "economicProfitWithRealSolar"
# # simulationType = "plantAndElectricityYieldWithRealSolar"
# # simulationType = "RealSolarAndEstimatedSolarComparison"
# simulationType = "PlantAndElectricityYieldAndProfitOnEachOPVCoverage"
# # simulationType = "stop"
#
#
# if simulationType == "PlantAndElectricityYieldAndProfitOnEachOPVCoverage":
# #########initial parameters(statistics) value start##########
# # substitute the constant value here. You do not need to change the values in the constant class when you want to try other variables
#
# #cultivation days per harvest [days/harvest]
# cultivationDaysperHarvest = constant.cultivationDaysperHarvest
# #the coverage ratio by OPV on the roofTop.
# # OPVAreaCoverageRatio = constant.OPVAreaCoverageRatio
# # #the area of OPV on the roofTop.
# # OPVArea = OPVAreaCoverageRatio * constant.greenhouseRoofArea
# # OPV film unit price[USD/m^2]
# hasShadingCurtain = constant.hasShadingCurtain
# # PPFD [umol m^-2 s^-1]
# shadingCurtainDeployPPFD = constant.shadingCurtainDeployPPFD
# #plant growth model type
# # plantGrowthModel = constant.TaylorExpantionWithFluctuatingDLI
# plantGrowthModel = constant.plantGrowthModel
#
# #if you continue to grow plants during the fallow period, then True
# ifGrowForSummerPeriod = constant.ifGrowForSummerPeriod
# simulatorClass.setIfGrowForSummerPeriod(ifGrowForSummerPeriod)
#
# # x-axis
# OPVCoverageDelta = 0.01
# #OPVCoverageDelta = 0.001
# #the array for x-axis (OPV area [m^2])
# OPVCoverageList = np.zeros(int(1.0/OPVCoverageDelta), dtype = float)
# #########initial parameters(statistics) value end##########
#
# #########define objective functions start################
# # electricity yield for a given period: [J] for a given period
# electricityYield = np.zeros(int(1.0/OPVCoverageDelta), dtype = float)
# # unit plant yield for a given period: [g] for a given period
# unitPlantYield = np.zeros(int(1.0/OPVCoverageDelta), dtype = float)
# # unit total daily plant fresh mass increase for a given period with each OPV film coverage: [g] for a given period
# unitDailyFreshWeightList = np.zeros(int(1.0/OPVCoverageDelta), dtype = float)
# # unit harvested fresh mass weight for a given period with each OPV film coverage: [g] for a given period
# dailyHarvestedFreshWeightPerHeadList = np.zeros(int(1.0/OPVCoverageDelta), dtype = float)
# # plant sales per square meter with each OPV film coverage: [USD/m^2]
# plantSalesperSquareMeterList = np.zeros(int(1.0/OPVCoverageDelta), dtype = float)
# # plant cost per square meter with each OPV film coverage: [USD/m^2]
# # plantCostperSquareMeterList = np.zeros(int(1.0/OPVCoverageDelta), dtype = float)
# # plant profit per square meter with each OPV film coverage: [USD/m^2]
# plantProfitperSquareMeterList = np.zeros(int(1.0/OPVCoverageDelta), dtype = float)
# # plant profit with each OPV film coverage: [USD/m^2]
# plantProfitList = np.zeros(int(1.0/OPVCoverageDelta), dtype = float)
#
# # monthly electricity sales per area with each OPV film coverage [USD/month]
# monthlyElectricitySalesListEastRoof = np.zeros((int(1.0/OPVCoverageDelta), util.getSimulationMonthsInt()), dtype = float)
# monthlyElectricitySalesListWestRoof = np.zeros((int(1.0/OPVCoverageDelta), util.getSimulationMonthsInt()), dtype = float)
#
# # electricity sales with each OPV film coverage [USD]
# electricitySalesList = np.zeros(int(1.0/OPVCoverageDelta), dtype = float)
# # electricitySalesListperAreaEastRoof = np.zeros(int(1.0/OPVCoverageDelta), dtype = float)
# # electricitySalesListperAreaWestRoof = np.zeros(int(1.0/OPVCoverageDelta), dtype = float)
#
# # electricity sales with each OPV film coverage [USD]
# electricityProfitList = np.zeros(int(1.0/OPVCoverageDelta), dtype = float)
# # economicProfit summing the electricity and plant profit [USD]
# economicProfitList = np.zeros(int(1.0/OPVCoverageDelta), dtype = float)
# #########define objective function end################
#
# # convert the year of each hour to the year to each day
# yearOfeachDay = simulatorClass.getYear()[::24]
# # convert the month of each hour to the month to each day
# monthOfeachDay = simulatorClass.getMonth()[::24]
# # print "monthOfeachDay:{}".format(monthOfeachDay)
# # print "monthOfeachDay.shape:{}".format(monthOfeachDay.shape)
#
# # variable = OPV coverage ratio. loop by OPV coverage ratio
# for i in range (0, int(1.0/OPVCoverageDelta)):
# ################## calculate the electricity yield with different OPV coverage for given period start#####################
# OPVCoverageList[i] = i * OPVCoverageDelta
#
# # [J/m^2] per day -> [J] electricity yield for a given period with a given area.
# # sum the electricity yield of east and west direction roofs
# electricityYield[i] += simulatorDetail.getWholeElectricityYieldEachOPVRatio(OPVCoverageList[i], dailyJopvoutperAreaEastRoof, simulatorClass, constant.greenhouseRoofArea / 2.0)
# electricityYield[i] += simulatorDetail.getWholeElectricityYieldEachOPVRatio(OPVCoverageList[i], dailyJopvoutperAreaWestRoof, simulatorClass, constant.greenhouseRoofArea / 2.0)
# # print("i:{}, electricityYield[i]:{}".format(i, electricityYield[i]))
#
# # [J] -> [Wh]: divide by 3600
# electricityYield[i] = util.convertFromJouleToWattHour(electricityYield[i])
# # [Wh] -> [kWh]: divide by 1000
# electricityYield[i] = util.convertFromJouleToWattHour(electricityYield[i])
# ################## calculate the electricity yield with different OPV coverage for given period end#####################
#
# ##################calculate the electricity sales#######################
# # get the monthly electricity sales per area [USD/month/m^2]
# monthlyElectricitySalesperAreaEastRoof = simulatorDetail.getMonthlyElectricitySalesperArea(dailyJopvoutperAreaEastRoof, yearOfeachDay, monthOfeachDay)
# monthlyElectricitySalesperAreaWestRoof = simulatorDetail.getMonthlyElectricitySalesperArea(dailyJopvoutperAreaWestRoof, yearOfeachDay, monthOfeachDay)
#
# # get the monthly electricity sales per each OPV coverage ratio [USD/month]
# monthlyElectricitySalesListEastRoof[i] = simulatorDetail.getMonthlyElectricitySales(OPVCoverageList[i], monthlyElectricitySalesperAreaEastRoof, constant.greenhouseRoofArea / 2.0)
# monthlyElectricitySalesListWestRoof[i] = simulatorDetail.getMonthlyElectricitySales(OPVCoverageList[i], monthlyElectricitySalesperAreaWestRoof, constant.greenhouseRoofArea / 2.0)
#
# # get the electricity sales per each OPV coverage ratio for given period [USD], suming the monthly electricity sales.
# electricitySalesList[i] = sum(monthlyElectricitySalesListEastRoof[i]) + sum(monthlyElectricitySalesListWestRoof[i])
# # print"electricitySalesList:{}".format(electricitySalesList)
#
# ##################calculate the electricity cost######################################
# if constant.ifConsiderOPVCost is True:
# initialOPVCostUSD = constant.OPVPricePerAreaUSD * OPVFilm.getOPVArea(OPVCoverageList[i])
# OPVCostUSDForDepreciation =initialOPVCostUSD * (util.getSimulationDaysInt() / constant.OPVDepreciationPeriodDays)
# else:
# OPVCostUSDForDepreciation = 0.0
#
# ##################get the electricity profit ######################################
# electricityProfitList[i] = electricitySalesList[i] - OPVCostUSDForDepreciation
# # print ("electricityYield:{}".format(electricityYield))
#
#
# # calc the electricity production per area [kWh/m^2]
# print ("electricity yield per area with 100% coverage ratio [kWh/m^2] was : {}".format(electricityYield[int(1.0/OPVCoverageDelta) -1] / constant.greenhouseRoofArea))
#
# # ################## plot the electricity yield with different OPV coverage for given period start ################
# # title = "electricity yield with a given area vs OPV film"
# # xAxisLabel = "OPV Coverage Ratio [-]"
# # yAxisLabel = "Electricity yield for a given period [kWh]"
# # util.plotData(OPVCoverageList, electricityYield, title, xAxisLabel, yAxisLabel)
# # util.saveFigure(title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
# # ################## plot the electricity yield with different OPV coverage for given period end ##################
#
# # ################## plot the electricity profit with different OPV coverage for given period
# # title = "electricity profit for a given period vs OPV film coverage ratio"
# # xAxisLabel = "OPV Coverage Ratio [-]: " + constant.SimulationStartDate + "-" + constant.SimulationEndDate
# # yAxisLabel = "Electricity profit for a given period [USD]"
# # util.plotData(OPVCoverageList, electricityProfitList, title, xAxisLabel, yAxisLabel)
# # util.saveFigure(title + " " + constant.SimulationStartDate + "-" + constant.SimulationEndDate)
#
# ################## calculate the daily plant yield and profit start#####################
# # variable = OPV coverage ratio. loop by OPV coverage ratio
# for i in range (0, int(1.0/OPVCoverageDelta)):
#
# ##################calculate the plant yield
# # Since the plants are not tilted, do not use the light intensity to the tilted surface, just use the inmported data or estimated data with 0 degree surface.
# # daily [g/unit]
# # shootFreshMassList, dailyFreshWeightPerHeadIncrease, accumulatedDailyFreshWeightPerHeadIncrease, dailyHarvestedFreshWeightPerHead = \
# # simulatorDetail.getPlantYieldSimulation(plantGrowthModel, cultivationDaysperHarvest,OPVCoverageList[i], \
# # (directPPFDToOPVEastDirection + directPPFDToOPVWestDirection)/2.0, diffusePPFDToOPV, groundReflectedPPFDToOPV, hasShadingCurtain, shadingCurtainDeployPPFD, simulatorClass)
# shootFreshMassList, dailyFreshWeightPerHeadIncrease, accumulatedDailyFreshWeightPerHeadIncrease, dailyHarvestedFreshWeightPerHead = \
# simulatorDetail.getPlantYieldSimulation(plantGrowthModel, cultivationDaysperHarvest,OPVCoverageList[i], \
# importedDirectPPFDToOPV, importedDiffusePPFDToOPV, importedGroundReflectedPPFDToOPV, hasShadingCurtain, shadingCurtainDeployPPFD, simulatorClass)
#
# # sum the daily increase and get the total increase for a given period with a certain OPV coverage ratio
# unitDailyFreshWeightList[i] = sum(dailyFreshWeightPerHeadIncrease)
# # sum the daily increase and get the total harvest weight for a given period with a certain OPV coverage ratio
# dailyHarvestedFreshWeightPerHeadList[i] = sum(dailyHarvestedFreshWeightPerHead)
# # print "dailyHarvestedFreshWeightPerHead.shape:{}".format(dailyHarvestedFreshWeightPerHead.shape)
#
# ##################calculate the plant sales
# # unit conversion; get the daily plant yield per given period per area: [g/unit] -> [g/m^2]
# dailyHarvestedFreshWeightperArea = util.convertUnitShootFreshMassToShootFreshMassperArea(dailyHarvestedFreshWeightPerHead)
# # unit conversion: [g/m^2] -> [kg/m^2]1
# dailyHarvestedFreshWeightperAreaKg = util.convertFromgramTokilogram(dailyHarvestedFreshWeightperArea)
# # get the sales price of plant [USD/m^2]
# # if the average DLI during each harvest term is more than 17 mol/m^2/day, discount the price
# # TODO may need to improve the function representing the affect of Tipburn
# dailyPlantSalesperSquareMeter = simulatorDetail.getPlantSalesperSquareMeter(year, dailyHarvestedFreshWeightperAreaKg, totalDLItoPlants)
#
# plantSalesperSquareMeterList[i] = sum(dailyPlantSalesperSquareMeter)
# # print "dailyPlantSalesperSquareMeter.shape:{}".format(dailyPlantSalesperSquareMeter.shape)
#
# ##################calculate the plant cost
# # plant operation cost per square meter for given simulation period [USD/m^2]
# plantCostperSquareMeter = simulatorDetail.getPlantCostperSquareMeter(simulationDaysInt)
#
# ##################plant profit per square meter with each OPV film coverage: [USD/m^2]
# plantProfitperSquareMeterList[i] = plantSalesperSquareMeterList[i] - plantCostperSquareMeter
# # print "plantProfitperSquareMeterList[i]:{}".format(plantProfitperSquareMeterList[i])
# # print "plantProfitperSquareMeterList[{}]:{}".format(i, plantProfitperSquareMeterList[i])
# plantProfitList[i] = plantProfitperSquareMeterList[i] * constant.greenhouseCultivationFloorArea
#
# # get the economic profit
# economicProfitList = plantProfitList + electricityProfitList
#
#
#
#
# profitVSOPVCoverageData=np.array(zip(OPVCoverageList, economicProfitList))
# # export the OPVCoverageList and economicProfitList [USD]
# util.exportCSVFile(profitVSOPVCoverageData, "OPVCoverage-economicProfit")
#
# print ("end modeling: datetime.datetime.now():{}".format(datetime.datetime.now()))
#
# return profitVSOPVCoverageData, simulatorClass
#
# print("iteration cot conducted")
# return None
|
{"/OPVFilm.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/ShadingCurtain.py"], "/CropElectricityYieldProfitMINLP.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelS_Pearson1997.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/PlantGrowthModelS_Pearson1997Constant.py", "/Lettuce.py"], "/GreenhouseEnergyBalanceConstant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/Util.py": ["/CropElectricityYeildSimulatorConstant.py"], "/SolarIrradianceMultiSpanRoof.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/GreenhouseEnergyBalance.py": ["/Lettuce.py", "/CropElectricityYeildSimulatorConstant.py", "/GreenhouseEnergyBalanceConstant.py", "/Util.py"], "/SimulatorMain.py": ["/CropElectricityYeildSimulator1.py", "/Util.py", "/CropElectricityYeildSimulatorConstant.py"], "/CropElectricityYieldProfitRLShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/ShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelValidation.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulator1.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulatorDetail.py": ["/ShadingCurtain.py", "/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/Lettuce.py", "/PlantGrowthModelS_Pearson1997.py", "/SolarIrradianceMultiSpanRoof.py", "/GreenhouseEnergyBalance.py"], "/PlantGrowthModelS_Pearson1997Constant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/SimulatorClass.py": ["/CropElectricityYeildSimulatorConstant.py"], "/Lettuce.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/plantGrowthModelE_J_VanHenten.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py"]}
|
8,667
|
kensaku-okada/Greenhouse-with-OPV-film-Model
|
refs/heads/master
|
/plantGrowthModelTestA_J_Both.py
|
import numpy as np
import matplotlib.pyplot as plt
import math
# dliList = np.array([40,40,40,40,40,40,40,40,40,40,
# 40,40,40,40,40,40,40,40,40,40,
# 40,40,40,40,40,40,40,40,40,40,
# 40,40,40,40,40,])
dliList = np.array([22,22,22,22,22,22,22,22,22,22,
22,22,22,22,22,22,22,22,22,22,
22,22,22,22,22,22,22,22,22,22,
22,22,22,22,22,])
dli = dliList[0]
sdm = 0
d_sdm = 0
sdmAccumulated = 0
a = 0
b = 0.4822
c = -0.006225
t = 35
dt = 1
for t in range(1, 1+len(dliList)):
a = -8.596 + 0.0743 * dli
sdm = math.e ** (a + b * t + c * t**2)
d_sdm = (b + 2 * c * t) * sdm
sdmAccumulated += d_sdm
# print "t:{} d_sdm:{}".format(t, d_sdm)
fm = sdm/0.045
print "case1 sdm accumulated version: {}".format(sdmAccumulated)
##########################################################################
dli = dliList[0]
t = 35
a = -8.596 + 0.0743 * dli
sdm = math.e ** (a + b * t + c * t**2)
print "case2 sdm (analytical answer): {}".format(sdm)
##########################################################################
# case 3
# dliList = np.array([22,22,22,22,22,22,22,22,22,22,
# 22,22,22,22,22,22,22,22,22,22,
# 22,22,22,22,22,22,22,22,22,22,
# 22,22,22,22,22,])
dli = dliList[0]
sdmList = np.zeros(len(dliList)+1)
d_sdmList = np.zeros(len(dliList)+1)
dd_sdmList = np.zeros(len(dliList)+1)
d_sdm = 0
sdmAccumulated = 0
a = 0
b = 0.4822
c = -0.006225
t = 35
dt = 1
# sdmInit = math.e ** (a + b * 0 + c * 0 **2)
sdmInit = 0
sdmList[0] = sdmInit
for t in range(1, 1+len(dliList)):
a = -8.596 + 0.0743 * dli
sdmList[t] = math.e ** (a + b * t + c * t**2)
d_sdmList[t] = (b + 2 * c * t) * sdmList[t]
dd_sdmList[t] = 2*c*sdmList[t] + (b + 2 * c * t)**2 * sdmList[t]
# print "d_sdmList[{}]:{}".format(t, d_sdmList[t])
# print "dd_sdmList[{}]:{}".format(t, dd_sdmList[t])
# taylor expansion: x_0 = 0, h = 1 (source: http://eman-physics.net/math/taylor.html)
sdmList[t] = sdmList[t-1] + d_sdmList[t-1] * dt + (1.0/(math.factorial(2)))*dd_sdmList[t-1]*((dt)**2)
# print "t = {} case3 sdmList[len(dliList)]: {}".format(t, sdmList[t])
fm = sdm/0.045
print "t = {} case3 sdm (Taylor expansion 2nd order approximation): {}".format(len(dliList), sdmList[len(dliList)])
##############################################################################
# case4
#
# dliList = np.array([22,22,22,22,22,22,22,22,22,22,
# 22,22,22,22,22,22,22,22,22,22,
# 22,22,22,22,22,22,22,22,22,22,
# 22,22,22,22,22,])
dli = dliList[0]
sdmList = np.zeros(len(dliList)+1)
d_sdmList = np.zeros(len(dliList)+1)
dd_sdmList = np.zeros(len(dliList)+1)
ddd_sdmList = np.zeros(len(dliList)+1)
d_sdm = 0
sdmAccumulated = 0
a = 0
b = 0.4822
c = -0.006225
t = 35
dt = 1
# sdmInit = math.e ** (a + b * 0 + c * 0 **2)
sdmInit = 0.0001
sdmList[0] = sdmInit
# sdmList[0] = math.e ** (a + b * 0.0 + c * 0.0**2)
d_sdmList[0] = (b + 2 * c * 0.0) * sdmList[0]
dd_sdmList[0] = 2 * c * sdmList[0] + (b + 2 * c * 0.0) ** 2 * sdmList[0]
ddd_sdmList[0] = 2 * c * d_sdmList[0] + 4 * c * (b + 2 * c * t) * sdmList[0] + (b + 2 * c * 0.0) ** 2 * d_sdmList[0]
for t in range(1, 1+len(dliList)):
a = -8.596 + 0.0743 * dli
sdmList[t] = math.e ** (a + b * t + c * t**2)
d_sdmList[t] = (b + 2 * c * t) * sdmList[t]
dd_sdmList[t] = 2*c*sdmList[t] + (b + 2 * c * t)**2 * sdmList[t]
ddd_sdmList[t] = 2*c*d_sdmList[t] + 4*c*(b + 2 * c * t) * sdmList[t] + (b + 2 * c * t)**2 * d_sdmList[t]
# print "d_sdmList[{}]:{}".format(t, d_sdmList[t])
# print "dd_sdmList[{}]:{}".format(t, dd_sdmList[t])
# print "ddd_sdmList[t]:{}".format(t, ddd_sdmList[t])
sdmList[t] = math.e ** (a + b * t + c * t**2)
d_sdmList[t] = (b + 2 * c * t) * sdmList[t]
dd_sdmList[t] = 2*c*sdmList[t] + (b + 2 * c * t)**2 * sdmList[t]
# taylor expansion: x_0 = 0, h = 1 (source: http://eman-physics.net/math/taylor.html)
sdmList[t] = sdmList[t-1] + \
1.0/(math.factorial(1))*d_sdmList[t-1] * dt + \
1.0/(math.factorial(2))*dd_sdmList[t-1]*((dt)**2) + \
1.0/(math.factorial(3))*ddd_sdmList[t-1]*((dt)**3)
# sdmList[t] = sdmList[t] + \
# 1.0/(math.factorial(1))*d_sdmList[t] * dt + \
# 1.0/(math.factorial(2))*dd_sdmList[t]*((dt)**2) + \
# 1.0/(math.factorial(3))*ddd_sdmList[t]*((dt)**3)
# print "t = {} case4 sdmList[len(dliList)]: {}".format(t, sdmList[t])
# print "t = {} case4 (1/(math.factorial(3)))*ddd_sdmList[t-1]*((dt)**3): {}".format(t, (1.0/(math.factorial(3)))*ddd_sdmList[t-1]*((dt)**3))
# print "1/(math.factorial(3)):{}".format(1.0/(math.factorial(3)))
# print "1/(math.factorial(2)):{}".format(1.0/(math.factorial(2)))
# print "t:{}, sdmList:{}".format(t, sdmList)
fm = sdm/0.045
print "t = {} case4 sdmList (Taylor expansion 3rd order approximation): {}".format(len(dliList), sdmList[len(dliList)])
|
{"/OPVFilm.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/ShadingCurtain.py"], "/CropElectricityYieldProfitMINLP.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelS_Pearson1997.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/PlantGrowthModelS_Pearson1997Constant.py", "/Lettuce.py"], "/GreenhouseEnergyBalanceConstant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/Util.py": ["/CropElectricityYeildSimulatorConstant.py"], "/SolarIrradianceMultiSpanRoof.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/GreenhouseEnergyBalance.py": ["/Lettuce.py", "/CropElectricityYeildSimulatorConstant.py", "/GreenhouseEnergyBalanceConstant.py", "/Util.py"], "/SimulatorMain.py": ["/CropElectricityYeildSimulator1.py", "/Util.py", "/CropElectricityYeildSimulatorConstant.py"], "/CropElectricityYieldProfitRLShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/ShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelValidation.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulator1.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulatorDetail.py": ["/ShadingCurtain.py", "/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/Lettuce.py", "/PlantGrowthModelS_Pearson1997.py", "/SolarIrradianceMultiSpanRoof.py", "/GreenhouseEnergyBalance.py"], "/PlantGrowthModelS_Pearson1997Constant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/SimulatorClass.py": ["/CropElectricityYeildSimulatorConstant.py"], "/Lettuce.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/plantGrowthModelE_J_VanHenten.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py"]}
|
8,668
|
kensaku-okada/Greenhouse-with-OPV-film-Model
|
refs/heads/master
|
/CropElectricityYeildSimulatorDetail.py
|
# -*- coding: utf-8 -*-
#######################################################
# author :Kensaku Okada [kensakuokada@email.arizona.edu]
# create date : 06 Nov 2016
# last edit date: 14 Dec 2016
#######################################################
##########import package files##########
from scipy import stats
import datetime
import sys
import os as os
import numpy as np
import ShadingCurtain
import matplotlib.pyplot as plt
import math
import CropElectricityYeildSimulatorConstant as constant
import Util
import OPVFilm
import Lettuce
import PlantGrowthModelE_J_VanHenten
import PlantGrowthModelS_Pearson1997
import SolarIrradianceMultiSpanRoof
from dateutil.relativedelta import *
import GreenhouseEnergyBalance as energyBalance
#######################################################
# def setSimulationSpecifications(simulatorClass):
# '''
# reference of the model:
# :return:
# '''
def calcOPVmoduleSolarIrradianceGHRoof(simulatorClass, roofDirectionNotation=constant.roofDirectionNotation):
'''
calculate the every kind of solar irradiance (W/m^2) to the OPV film. The tilt angel and direction angle of OPV panes is define in CropElectricityYeildSimulatorConstant.py
Reference of the model: A. yano et. at., 2009, "Electrical energy generated by photovoltaic modules mounted inside the roof of a north–south oriented greenhouse" and M. kacira et. al., ""
Reference URL: "https://www.actahort.org/books/1037/1037_9.htm" and "https://www.sciencedirect.com/science/article/pii/S0960148104000060"
'''
year = simulatorClass.getYear()
month = simulatorClass.getMonth()
day = simulatorClass.getDay()
hour = simulatorClass.getHour()
hourlyHorizontalDiffuseOuterSolarIrradiance = simulatorClass.getImportedHourlyHorizontalDiffuseSolarRadiation()
hourlyHorizontalDirectOuterSolarIrradiance = simulatorClass.getImportedHourlyHorizontalDirectSolarRadiation()
# [rad] symbol: delta
hourlyDeclinationAngle = OPVFilm.calcDeclinationAngle(year, month, day)
# print "hourlyDecl inationAngle:{}".format(np.degrees(hourlyDeclinationAngle))
# print "hourlyDeclinationAngle:{}".format(hourlyDeclinationAngle)
# [rad] symbol: omega
hourlySolarHourAngle = OPVFilm.getSolarHourAngleKacira2003(hour)
# print ("hourlySolarHourAngle by Kacira2003:{}".format(np.degrees(hourlySolarHourAngle)))
# # [rad] symbol: omega
# hourlySolarHourAngle = OPVFilm.getSolarHourAngleYano2009(hour)
# print ("hourlySolarHourAngle by Yano2009:{}".format(np.degrees(hourlySolarHourAngle)))
# [rad] symbol: alpha. elevation angle = altitude angle
hourlySolarAltitudeAngle = OPVFilm.calcSolarAltitudeAngle(hourlyDeclinationAngle, hourlySolarHourAngle)
# print "np.degrees(hourlySolarAltitudeAngle):{}".format(np.degrees(hourlySolarAltitudeAngle))
# print "hourlySolarAltitudeAngle:{}".format(hourlySolarAltitudeAngle)
# set the solar altitude angle, which is necessary to calculate the solar radiation through multispan roof
simulatorClass.hourlySolarAltitudeAngle = hourlySolarAltitudeAngle
# [rad] symbol: beta. azimuth angle
hourlySolarAzimuthAngle = OPVFilm.calcSolarAzimuthAngle(hourlyDeclinationAngle, hourlySolarAltitudeAngle, hourlySolarHourAngle)
# print "hourlySolarAzimuthAngle:{}".format(hourlySolarAzimuthAngle)
# set the solar azimuth angle, which is necessary to calculate the solar radiation through multispan roof
simulatorClass.hourlySolarAzimuthAngle = hourlySolarAzimuthAngle
# used only in Kacira 2003
# [rad] symbol: theta_z
hourlyZenithAngle = math.radians(90.0) - hourlySolarAltitudeAngle
# print "math.radians(90.0):{}".format(math.radians(90.0))
# print "hourlyZenithAngle:{}".format(hourlyZenithAngle)
# if the direction of greenhouse is north-south and the roof tilt direction is east-west
if roofDirectionNotation == "EastWestDirectionRoof":
# [rad] symbol: phi_p
# module azimuth angle (yano 2009) == surface azimuth angle (kacira 2003)
# if the OPV module facing east
hourlyModuleAzimuthAngleEast = math.radians(-90.0)
# hourlyModuleAzimuthAngleEast = math.radians(180.0)
# if the OPV module facing west
hourlyModuleAzimuthAngleWest = math.radians(90.0)
# hourlyModuleAzimuthAngleWest = math.radians(0.0)
# if the direction of greenhouse is east-west and the roof tilt direction is north-south
elif roofDirectionNotation == "NorthSouthDirectionRoof":
hourlyModuleAzimuthAngleNorth = math.radians(180.0)
# if the OPV module facing west
hourlyModuleAzimuthAngleSouth = math.radians(0.0)
# set the module azimuth angle, which is necessary to calculate the solar radiation through multispan roof
simulatorClass.hourlyModuleAzimuthAngleEast = hourlyModuleAzimuthAngleEast
simulatorClass.hourlyModuleAzimuthAngleWest = hourlyModuleAzimuthAngleWest
# this computation is necessary to calculate the horizontal incidence angle for horizontal direct solar irradiance. This data is used at getDirectHorizontalSolarRadiation function
hourlyModuleAzimuthAngleSouth = math.radians(0.0)
hourlyHorizontalSolarIncidenceAngle = OPVFilm.calcSolarIncidenceAngleYano2009(hourlySolarAltitudeAngle, hourlySolarAzimuthAngle, hourlyModuleAzimuthAngleSouth, 0)
# print "hourlyHorizontalSolarIncidenceAngle:{}".format(hourlyHorizontalSolarIncidenceAngle)
if roofDirectionNotation == "EastWestDirectionRoof":
#The incident angle of the beam sunlight on the module surface. [rad] symbol: theta_I
hourlySolarIncidenceAngleEastDirection = OPVFilm.calcSolarIncidenceAngleYano2009(hourlySolarAltitudeAngle, hourlySolarAzimuthAngle, hourlyModuleAzimuthAngleEast)
hourlySolarIncidenceAngleWestDirection = OPVFilm.calcSolarIncidenceAngleYano2009(hourlySolarAltitudeAngle, hourlySolarAzimuthAngle, hourlyModuleAzimuthAngleWest)
# print("hourlySolarIncidenceAngleEastDirection:{}".format(hourlySolarIncidenceAngleEastDirection))
# print("hourlySolarIncidenceAngleWestDirection:{}".format(hourlySolarIncidenceAngleWestDirection))
# if the direction of greenhouse is east-west and the roof tilt direction is north-south
elif roofDirectionNotation == "NorthSouthDirectionRoof":
# The suitability of the output value is not examined because our greenhouse was "EastWestDirectionRoof" (= north-south direction greenhouse)
hourlySolarIncidenceAngleEastDirection = OPVFilm.calcSolarIncidenceAngleYano2009(hourlySolarAltitudeAngle, hourlySolarAzimuthAngle, hourlyModuleAzimuthAngleNorth)
hourlySolarIncidenceAngleWestDirection = OPVFilm.calcSolarIncidenceAngleYano2009(hourlySolarAltitudeAngle, hourlySolarAzimuthAngle, hourlyModuleAzimuthAngleSouth)
# print ("hourlySolarIncidenceAngleEastDirection:{}".format(hourlySolarIncidenceAngleEastDirection))
# print ("hourlySolarIncidenceAngleWestDirection:{}".format(hourlySolarIncidenceAngleWestDirection))
# set the incidence angle
simulatorClass.hourlySolarIncidenceAngleEastDirection = hourlySolarIncidenceAngleEastDirection
simulatorClass.hourlySolarIncidenceAngleWestDirection = hourlySolarIncidenceAngleWestDirection
# np.set_printoptions(threshold=np.inf)
# print("hourlySolarIncidenceAngleEastDirection:{}".format(hourlySolarIncidenceAngleEastDirection))
# print("hourlySolarIncidenceAngleWestDirection:{}".format(hourlySolarIncidenceAngleWestDirection))
# np.set_printoptions(threshold=1000)
# estimated horizontal solar irradiances [W m^-2]. these values are used only when estimating solar radiations.
# symbol: I_DH.
directHorizontalSolarRadiation = OPVFilm.getDirectHorizontalSolarRadiation(hourlySolarAltitudeAngle, hourlyHorizontalSolarIncidenceAngle)
# print "directHorizontalSolarRadiation:{}".format(directHorizontalSolarRadiation)
# set the data. this is necessary when estimating the solar irradiance under multi-span greenhouse with estimated data
simulatorClass.directHorizontalSolarRadiation = directHorizontalSolarRadiation
# symbol: I_S
diffuseHorizontalSolarRadiation = OPVFilm.getDiffuseHorizontalSolarRadiation(hourlySolarAltitudeAngle, hourlyHorizontalSolarIncidenceAngle)
simulatorClass.diffuseHorizontalSolarRadiation = diffuseHorizontalSolarRadiation
# print "diffuseHorizontalSolarRadiation:{}".format(diffuseHorizontalSolarRadiation)
# symbol: I_HT
totalHorizontalSolarRadiation = directHorizontalSolarRadiation + diffuseHorizontalSolarRadiation
simulatorClass.totalHorizontalSolarRadiation = totalHorizontalSolarRadiation
# print "totalHorizontalSolarRadiation:{}".format(totalHorizontalSolarRadiation)
# tilted surface solar radiation [W m^-2], real / estimated value branch is calculated in this functions
# symbol: I_TD (= H_b at Kacira 2004). direct beam radiation on the tilted surface
# print ("call getDirectTitledSolarRadiation for east direction OPV")
directTiltedSolarRadiationEastDirection = OPVFilm.getDirectTitledSolarRadiation(simulatorClass, hourlySolarAltitudeAngle, hourlySolarIncidenceAngleEastDirection, \
hourlyHorizontalDirectOuterSolarIrradiance)
# print ("call getDirectTitledSolarRadiation for west direction OPV")
directTiltedSolarRadiationWestDirection = OPVFilm.getDirectTitledSolarRadiation(simulatorClass, hourlySolarAltitudeAngle, hourlySolarIncidenceAngleWestDirection, \
hourlyHorizontalDirectOuterSolarIrradiance)
# print("directTiltedSolarRadiationEastDirection:{}".format(directTiltedSolarRadiationEastDirection))
# print("directTiltedSolarRadiationWestDirection:{}".format(directTiltedSolarRadiationWestDirection))
# symbol: I_TS (= H_d_p at Kacira 2004). diffused radiation on the tilted surface.
diffuseTiltedSolarRadiation = OPVFilm.getDiffuseTitledSolarRadiation(simulatorClass, hourlySolarAltitudeAngle, diffuseHorizontalSolarRadiation, \
hourlyHorizontalDiffuseOuterSolarIrradiance)
# print "diffuseTiltedSolarRadiation:{}".format(diffuseTiltedSolarRadiation)
# symbol: I_Trho (= H_gr at Kacira 2004) (albedo radiation = reflectance from the ground)
albedoTiltedSolarRadiation = OPVFilm.getAlbedoTitledSolarRadiation(simulatorClass, hourlySolarAltitudeAngle, totalHorizontalSolarRadiation, \
hourlyHorizontalDirectOuterSolarIrradiance+hourlyHorizontalDiffuseOuterSolarIrradiance)
return directTiltedSolarRadiationEastDirection, directTiltedSolarRadiationWestDirection, diffuseTiltedSolarRadiation, albedoTiltedSolarRadiation
# ####################################################################################################
# # Stop execution here...
# sys.exit()
# # Move the above line to different parts of the assignment as you implement more of the functionality.
# ####################################################################################################
def getDailyElectricityYieldperArea(simulatorClass,hourlyOPVTemperature, directSolarRadiationToOPV, diffuseSolarRadiationToOPV,groundReflectedSolarradiationToOPV):
'''
calculate the daily electricity yield per area (m^2).
:param hourlyOPVTemperature: [celsius]
:param directSolarRadiationToOPV: [W/m^2]
:param diffuseSolarRadiationToOPV: [W/m^2]
:param groundReflectedSolarradiationToOPV:[W/m^2]
:return:
'''
# print "total solar irradiance:{}".format(directSolarRadiationToOPV+diffuseSolarRadiationToOPV+groundReflectedSolarradiationToOPV)
# [W/m^2] == [J/s/m^2] -> [J/m^2] per day
dailyJopvoutperArea = OPVFilm.calcOPVElectricEnergyperArea(simulatorClass, hourlyOPVTemperature, directSolarRadiationToOPV+diffuseSolarRadiationToOPV+groundReflectedSolarradiationToOPV)
# print "dailyJopvout:{}".format(dailyJopvout)
return dailyJopvoutperArea
def setDirectSolarIrradianceThroughMultiSpanRoof(simulatorClass):
'''
calculate the solar irradiance to multi-span roof.
this calculates the solar irradiance to the single span.
the variables names follow the symbols in the reference.
Reference of the model: T. Soriano. et al, 2004, "A Study of Direct Solar Radiation Transmission in Asymmetrical Multi-span Greenhouses using Scale Models and Simulation Models"
source: https://www.sciencedirect.com/science/article/pii/S1537511004000455
'''
# get the direct solar radiation [W/m^2]. these values are not directly used to calculate the transmittance but just used to check the existance of solar irradicne at each hour.
directSolarRadiationToOPVEastFacingRoof = simulatorClass.getDirectSolarRadiationToOPVEastDirection()
directSolarRadiationToOPVWestFacingRoof = simulatorClass.getDirectSolarRadiationToOPVWestDirection()
# print("directSolarRadiationToOPVEastFacingRoof: {}".format(directSolarRadiationToOPVEastFacingRoof))
# print("directSolarRadiationToOPVWestFacingRoof: {}".format(directSolarRadiationToOPVWestFacingRoof))
# module azimuth of each roof facing the opposite direction [rad], which is a scalar value
hourlyModuleAzimuthAngleEast = simulatorClass.hourlyModuleAzimuthAngleEast
hourlyModuleAzimuthAngleWest = simulatorClass.hourlyModuleAzimuthAngleWest
# print("hourlyModuleAzimuthAngleEast: {}".format(hourlyModuleAzimuthAngleEast))
# print("hourlyModuleAzimuthAngleWest: {}".format(hourlyModuleAzimuthAngleWest))
# angle between the incident ray and the horizontal axis perpendicular to the greenhouse span. This angle is symbolized with E in the reference paper [rad]
EPerpendicularEastOrNorthFacingRoof = SolarIrradianceMultiSpanRoof.getAngleBetweenIncientRayAndHorizontalAxisPerpendicularToGHSpan(simulatorClass, hourlyModuleAzimuthAngleEast)
EPerpendicularWestOrSouthFacingRoof = SolarIrradianceMultiSpanRoof.getAngleBetweenIncientRayAndHorizontalAxisPerpendicularToGHSpan(simulatorClass, hourlyModuleAzimuthAngleWest)
# np.set_printoptions(threshold=np.inf)
# print("EPerpendicularEastOrNorthFacingRoof: {}".format(EPerpendicularEastOrNorthFacingRoof))
# print("EPerpendicularWestOrSouthFacingRoof: {}".format(EPerpendicularWestOrSouthFacingRoof))
# np.set_printoptions(threshold=1000)
# # Referring to Soriano. et al, (2004), it was found that we can get the direct solar irradiance to horizontal surface inside multi-span greenhouse just by
# # multiplying the outer solar irradiance to horizontal surface with
# # angle between the incident ray and the horizontal axis perpendicular to the greenhouse span. This angle is nit symbolized in the reference paper.
# # the following angles should be same in our case, but both were separately calculated for program expandability
# EParallelEastOrNorthFacingRoof = SolarIrradianceMultiSpanRoof.getAngleBetweenIncientRayAndHorizontalAxisParallelToGHSpan(simulatorClass, hourlyModuleAzimuthAngleEast)
# EParallelWestOrSouthFacingRoof = SolarIrradianceMultiSpanRoof.getAngleBetweenIncientRayAndHorizontalAxisParallelToGHSpan(simulatorClass, hourlyModuleAzimuthAngleWest)
# # print("EParallelEastOrNorthFacingRoof: {}".format(EParallelEastOrNorthFacingRoof))
# # print("EParallelWestOrSouthFacingRoof: {}".format(EParallelWestOrSouthFacingRoof))
#
# # get the T_mat for parallel irradiance
# T_matForParallelIrrEastOrNorthFacingRoof = SolarIrradianceMultiSpanRoof.getTransmittanceForParallelIrrThroughMultiSpanRoof(simulatorClass,EParallelEastOrNorthFacingRoof)
# T_matForParallelIrrWestOrSouthFacingRoof = SolarIrradianceMultiSpanRoof.getTransmittanceForParallelIrrThroughMultiSpanRoof(simulatorClass,EParallelWestOrSouthFacingRoof)
# print("T_matForParallelIrrEastOrNorthFacingRoof: {}".format(T_matForParallelIrrEastOrNorthFacingRoof))
# print("T_matForParallelIrrWestOrSouthFacingRoof: {}".format(T_matForParallelIrrWestOrSouthFacingRoof))
# get the incidence angles
hourlySolarIncidenceAngleEastDirection = simulatorClass.hourlySolarIncidenceAngleEastDirection
hourlySolarIncidenceAngleWestDirection = simulatorClass.hourlySolarIncidenceAngleWestDirection
# get the direct solar irradiance on each axis
directSolarIrradiancePerpendicularToOPVEastDirection = directSolarRadiationToOPVEastFacingRoof * np.cos(hourlySolarIncidenceAngleEastDirection)
directSolarIrradianceParallelToOPVEastDirection = directSolarRadiationToOPVEastFacingRoof * np.sin(hourlySolarIncidenceAngleEastDirection)
directSolarIrradiancePerpendicularToOPVWestDirection = directSolarRadiationToOPVWestFacingRoof * np.cos(hourlySolarIncidenceAngleWestDirection)
directSolarIrradianceParallelToOPVWestDirection = directSolarRadiationToOPVWestFacingRoof * np.sin(hourlySolarIncidenceAngleWestDirection)
# np.set_printoptions(threshold=np.inf)
# print("directSolarIrradiancePerpendicularToOPVEastDirection: {}".format(directSolarIrradiancePerpendicularToOPVEastDirection))
# print("directSolarIrradianceParallelToOPVEastDirection: {}".format(directSolarIrradianceParallelToOPVEastDirection))
# print("directSolarIrradiancePerpendicularToOPVWestDirection: {}".format(directSolarIrradiancePerpendicularToOPVWestDirection))
# print("directSolarIrradianceParallelToOPVWestDirection: {}".format(directSolarIrradianceParallelToOPVWestDirection))
# np.set_printoptions(threshold=1000)
# the the T_mat for parpendicular irradiance
# print("getTransmittanceForPerpendicularIrrThroughMultiSpanRoofFacingEastOrNorth start")
# to avoide the error "RuntimeError: maximum recursion depth exceeded", the maximum recursion limitation is increased.
# sys.setrecursionlimit(constant.mMax)
# print("sys.getrecursionlimit():{}".format(sys.getrecursionlimit()))
T_matForPerpendicularIrrEastOrNorthFacingRoof = SolarIrradianceMultiSpanRoof.getTransmittanceForPerpendicularIrrThroughMultiSpanRoofFacingEastOrNorth(\
simulatorClass, directSolarIrradiancePerpendicularToOPVEastDirection, EPerpendicularEastOrNorthFacingRoof)
# print("getTransmittanceForPerpendicularIrrThroughMultiSpanRoofFacingWestOrSouth start: {}")
T_matForPerpendicularIrrWestOrSouthFacingRoof = SolarIrradianceMultiSpanRoof.getTransmittanceForPerpendicularIrrThroughMultiSpanRoofFacingWestOrSouth(\
simulatorClass, directSolarIrradiancePerpendicularToOPVWestDirection, EPerpendicularWestOrSouthFacingRoof)
# roll back the recursive limitation setting. The default number should be changed according to each local env.
# sys.setrecursionlimit(constant.defaultIterationLimit)
# set the data
simulatorClass.T_matForPerpendicularIrrEastOrNorthFacingRoof = T_matForPerpendicularIrrEastOrNorthFacingRoof
simulatorClass.T_matForPerpendicularIrrWestOrSouthFacingRoof = T_matForPerpendicularIrrWestOrSouthFacingRoof
# the overall transmittance of multispanroof. The solar irradiance inside the greenhouse can be derived only by multiplying this with the outer solar irradiance for horizontal surface
integratedT_mat = SolarIrradianceMultiSpanRoof.getIntegratedT_matFromBothRoofs(T_matForPerpendicularIrrEastOrNorthFacingRoof, T_matForPerpendicularIrrWestOrSouthFacingRoof)
# set the data
simulatorClass.integratedT_mat = integratedT_mat
# np.set_printoptions(threshold=np.inf)
# print("T_matForPerpendicularIrrEastOrNorthFacingRoof: {}".format(T_matForPerpendicularIrrEastOrNorthFacingRoof))
# print("T_matForPerpendicularIrrWestOrSouthFacingRoof: {}".format(T_matForPerpendicularIrrWestOrSouthFacingRoof))
# print("integratedT_mat:{}".format(integratedT_mat))
# np.set_printoptions(threshold=1000)
# get the solar irradiance inside
if constant.ifUseOnlyRealData == True:
hourlyDirectSolarRadiationAfterMultiSpanRoof = integratedT_mat * simulatorClass.hourlyHorizontalDirectOuterSolarIrradiance
# this uses the estimated direct solar irradiance (without real data)
else:
hourlyDirectSolarRadiationAfterMultiSpanRoof = integratedT_mat * simulatorClass.directHorizontalSolarRadiation
# set the solar irradiance [W/m^2]
simulatorClass.setHourlyDirectSolarRadiationAfterMultiSpanRoof(hourlyDirectSolarRadiationAfterMultiSpanRoof)
# unit change of the imported outer solar radiation: [W m^-2] -> [umol m^-2 s^-1] == PPFD
hourlyDirectPPFDTAfterMultiSpanRoof = Util.convertFromWattperSecSquareMeterToPPFD(hourlyDirectSolarRadiationAfterMultiSpanRoof)
# set the solar irradiance [umol m^-2 s^-1] == PPFD
simulatorClass.setHourlyDirectPPFDAfterMultiSpanRoof(hourlyDirectPPFDTAfterMultiSpanRoof)
# convert the unit into PPFD snd DLI
directDLIAfterMultiSpanRoof = Util.convertFromHourlyPPFDWholeDayToDLI(hourlyDirectPPFDTAfterMultiSpanRoof)
simulatorClass.setHourlyDirectPPFDAfterMultiSpanRoof(directDLIAfterMultiSpanRoof)
def setSolarIrradianceToPlants(simulatorClass):
'''
# calculate the light intensity to plants after penetrating the roof, considering the sidewall material transmittance, shading curtain, and the greenhouse structure shading
it was assumed ground reflectance does not significantly affect the solar irradiance to plants
'''
directSolarIrradianceBeforeShadingCurtain = OPVFilm.getDirectSolarIrradianceBeforeShadingCurtain(simulatorClass)
# set the data to the object
simulatorClass.directSolarIrradianceBeforeShadingCurtain = directSolarIrradianceBeforeShadingCurtain
diffuseSolarIrradianceBeforeShadingCurtain = OPVFilm.getDiffuseSolarIrradianceBeforeShadingCurtain(simulatorClass)
# set the data to the object
simulatorClass.diffuseSolarIrradianceBeforeShadingCurtain = diffuseSolarIrradianceBeforeShadingCurtain
# get the shading curtain transmittance
ShadingCurtain.getHourlyShadingCurtainDeploymentPatternChangingEachMonthMain(simulatorClass)
# #############command to print out all array data
# np.set_printoptions(threshold=np.inf)
# print("simulatorClass.transmittanceThroughShadingCurtainChangingEachMonth:{}".format(simulatorClass.transmittanceThroughShadingCurtainChangingEachMonth))
# np.set_printoptions(threshold=1000)
# #############
# calculate the light intensity to plants [W m-2]
directSolarIrradianceToPlants = OPVFilm.getDirectSolarIrradianceToPlants(simulatorClass, directSolarIrradianceBeforeShadingCurtain)
diffuseSolarIrradianceToPlants = OPVFilm.getDiffuseSolarIrradianceToPlants(simulatorClass, diffuseSolarIrradianceBeforeShadingCurtain)
# # change this part if you can to see how plant fresh weight changes with the change of solar irradiance to plants
# directSolarIrradianceToPlants = directSolarIrradianceToPlants * 2.0
# diffuseSolarIrradianceToPlants = diffuseSolarIrradianceToPlants * 2.0
# set the data to the object
simulatorClass.directSolarIrradianceToPlants = directSolarIrradianceToPlants
simulatorClass.diffuseSolarIrradianceToPlants = diffuseSolarIrradianceToPlants
# #############command to print out all array data
# np.set_printoptions(threshold=np.inf)
# print("directSolarIrradianceToPlants:{}".format(directSolarIrradianceToPlants))
# print("diffuseSolarIrradianceToPlants:{}".format(diffuseSolarIrradianceToPlants))
# np.set_printoptions(threshold=1000)
# #############
# unit change of the imported outer solar radiation: [W m^-2] -> [umol m^-2 s^-1] == PPFD
directPPFDToPlants = Util.convertFromWattperSecSquareMeterToPPFD(directSolarIrradianceToPlants)
diffusePPFDToPlants = Util.convertFromWattperSecSquareMeterToPPFD(diffuseSolarIrradianceToPlants)
# set the solar irradiance [umol m^-2 s^-1] == PPFD
simulatorClass.directPPFDToPlants = directPPFDToPlants
simulatorClass.diffusePPFDToPlants = diffusePPFDToPlants
# convert the unit into PPFD snd DLI
directDLIToPlants = Util.convertFromHourlyPPFDWholeDayToDLI(directPPFDToPlants)
diffuseDLIToPlants = Util.convertFromHourlyPPFDWholeDayToDLI(diffusePPFDToPlants)
simulatorClass.directDLIToPlants = directDLIToPlants
simulatorClass.diffuseDLIToPlants = diffuseDLIToPlants
# #############command to print out all array data
# np.set_printoptions(threshold=np.inf)
# print("directDLIToPlants:{}".format(directDLIToPlants))
# print("diffuseDLIToPlants:{}".format(diffuseDLIToPlants))
# np.set_printoptions(threshold=1000)
# #############
# def setThermalTimeToPlants(simulatorClass):
# '''
# calc/set the thermal time to the object: average Celsius temperature per day * days [Celsius d]
# On the model, since it was assumed the temperature in the greenhouse is maintained at the set point by cooling system (pad and fan system), this function is not used.
# '''
# importedHourlyAirTemperature = simulatorClass.getImportedHourlyAirTemperature()
#
# # TODO assume the greenhouse temperature from the outer air temperature
# airTemperatureInGreenhouse = importedHourlyAirTemperature
# simulatorClass.setThermalTimeToPlants(airTemperatureInGreenhouse)
def getPlantYieldSimulation(simulatorClass):
'''
calculate the daily plant yield
:param cultivationDaysperHarvest: [days / harvest]
:param OPVAreaCoverageRatio: [-] range(0-1)
:param directPPFDToOPV: hourly average [umol m^-2 s^-1] == PPFD
:param diffusePPFDToOPV: hourly average [umol m^-2 s^-1] == PPFD
:param groundReflectedPPFDToOPV: hourly average [umol m^-2 s^-1] == PPFD
:param hasShadingCurtain: Boolean
:param ShadingCurtainDeployPPFD: float [umol m^-2 s^-1] == PPFD
:param cropElectricityYieldSimulator1: object
:return:
'''
plantGrowthModel = simulatorClass.getPlantGrowthModel()
# get cultivation days per harvest. this may not be used in some plant growth models
cultivationDaysperHarvest = simulatorClass.getCultivationDaysperHarvest()
# OPVAreaCoverageRatio = simulatorClass.getOPVAreaCoverageRatio()
# hasShadingCurtain = simulatorClass.getIfHasShadingCurtain()
# ShadingCurtainDeployPPFD = simulatorClass.getShadingCurtainDeployPPFD()
# # This unit conversion was done at getSolarIrradianceToPlants
# # calculate the light intensity to plants
# # hourly average PPFD [umol m^-2 s^-1]
# hourlyInnerPPFDToPlants = OPVFilm.calcHourlyInnerLightIntensityPPFD(directPPFDToMultiSpanRoof + diffusePPFDToMultiSpanRoof + groundReflectedPPFDToMultiSpanRoof, \
# OPVAreaCoverageRatio, constant.OPVPARTransmittance, hasShadingCurtain,ShadingCurtainDeployPPFD, simulatorClass)
# np.set_printoptions(threshold=np.inf)
# print "OPVAreaCoverageRatio:{}, directPPFDToOPV+diffusePPFDToOPV+groundReflectedPPFDToOPV:{}".format(OPVAreaCoverageRatio, directPPFDToOPV+diffusePPFDToOPV+groundReflectedPPFDToOPV)
# np.set_printoptions(threshold=1000)
# calculate the daily increase of unit fresh weight
# this model considers only solar irradiance, and so this will not be so practical
# the simulated cultivar is butter head lettuce
if plantGrowthModel == constant.A_J_Both_Modified_TaylorExpantionWithFluctuatingDLI:
#unit [g/head]
shootFreshMassList, unitDailyFreshWeightIncrease, accumulatedUnitDailyFreshWeightIncrease, unitHarvestedFreshWeight = \
Lettuce.calcUnitDailyFreshWeightBoth2003TaylorExpantionWithVaryingDLI(simulatorClass.directPPFDToPlants + simulatorClass.diffusePPFDToPlants, cultivationDaysperHarvest, simulatorClass)
# print "shootFreshMassList.shape:{}".format(shootFreshMassList.shape)
# the simulated cultivar is Berlo and Norden
elif plantGrowthModel == constant.E_J_VanHenten1994:
# unit [g/head]
shootFreshMassList, \
unitDailyFreshWeightIncrease, \
accumulatedUnitDailyFreshWeightIncrease, \
unitHarvestedFreshWeight = \
PlantGrowthModelE_J_VanHenten.calcUnitDailyFreshWeightE_J_VanHenten1994(simulatorClass)
# print("shootFreshMassList.shape[0]:{}".format(shootFreshMassList.shape[0]))
# print("unitDailyFreshWeightIncrease.shape[0]:{}".format(unitDailyFreshWeightIncrease.shape[0]))
# print("accumulatedUnitDailyFreshWeightIncrease.shape[0]:{}".format(accumulatedUnitDailyFreshWeightIncrease.shape[0]))
# print("unitHarvestedFreshWeight.shape[0]:{}".format(unitHarvestedFreshWeight.shape[0]))
# set the data
simulatorClass.shootFreshMassList = shootFreshMassList
# Be careful! this model returns hourly weight, not daily weight. so convert the hourly value into daily value.
dailyShootFreshMassList = shootFreshMassList[23::constant.hourperDay]
# print("dailyShootFreshMassList:{}".format(dailyShootFreshMassList))
# dailyUnitDailyFreshWeightIncrease = np.array(sum[ unitDailyFreshWeightIncrease[constant.hourperDay*(i-1):constant.hourperDay*i]] \
# for i in range (0, unitDailyFreshWeightIncrease.shape[0]/constant.hourperDay ))
dailyUnitDailyFreshWeightIncrease = Lettuce.getFreshWeightIncrease(dailyShootFreshMassList)
dailyAccumulatedUnitDailyFreshWeightIncrease = Lettuce.getAccumulatedFreshWeightIncrease(dailyShootFreshMassList)
dailyUnitHarvestedFreshWeight = Lettuce.getHarvestedFreshWeight(dailyShootFreshMassList)
# print("dailyUnitDailyFreshWeightIncrease.shape:{}".format(dailyUnitDailyFreshWeightIncrease.shape))
# print("dailyAccumulatedUnitDailyFreshWeightIncrease.shape:{}".format(dailyAccumulatedUnitDailyFreshWeightIncrease.shape))
# print("dailyUnitHarvestedFreshWeight.shape:{}".format(dailyUnitHarvestedFreshWeight.shape))
# print("dailyUnitHarvestedFreshWeight:{}".format(dailyUnitHarvestedFreshWeight))
# this model was coded, but the result was not better than constant.E_J_VanHenten1994
elif plantGrowthModel == constant.S_Pearson1997:
# unit [g/head]
dailyShootFreshMassList, \
dailyUnitDailyFreshWeightIncrease, \
dailyAccumulatedUnitDailyFreshWeightIncrease, \
dailyUnitHarvestedFreshWeight = \
PlantGrowthModelS_Pearson1997.calcUnitDailyFreshWeightS_Pearson1997(simulatorClass)
else:
print ("no valid model name is assigned. Stop the simulation. Please choose a registered one")
####################################################################################################
# Stop execution here...
sys.exit()
# Move the above line to different parts of the assignment as you implement more of the functionality.
####################################################################################################
# set the values to the object
simulatorClass.dailyShootFreshMass = dailyShootFreshMassList
simulatorClass.dailyUnitDailyFreshWeightIncrease = dailyUnitDailyFreshWeightIncrease
simulatorClass.dailyAccumulatedUnitDailyFreshWeightIncrease = dailyAccumulatedUnitDailyFreshWeightIncrease
simulatorClass.dailyUnitHarvestedFreshWeight = dailyUnitHarvestedFreshWeight
return dailyShootFreshMassList, dailyUnitDailyFreshWeightIncrease, dailyAccumulatedUnitDailyFreshWeightIncrease, dailyUnitHarvestedFreshWeight
def getTotalDLIToPlants(OPVAreaCoverageRatio, directPPFDToOPV, diffusePPFDToOPV, groundReflectedPPFDToOPV, hasShadingCurtain, ShadingCurtainDeployPPFD, \
cropElectricityYieldSimulator1):
'''
the daily light integral to plants for the given simulation period.
:param OPVAreaCoverageRatio:
:param directPPFDToOPV:
:param diffusePPFDToOPV:
:param groundReflectedPPFDToOPV:
:param hasShadingCurtain:
:param ShadingCurtainDeployPPFD:
:param cropElectricityYieldSimulator1: instance
:return:
'''
# calculate the light intensity to plants
# hourly average PPFD [umol m^-2 s^-1]
hourlyInnerPPFDToPlants = OPVFilm.calcHourlyInnerLightIntensityPPFD(directPPFDToOPV+diffusePPFDToOPV+groundReflectedPPFDToOPV, \
OPVAreaCoverageRatio, constant.OPVPARTransmittance, hasShadingCurtain,ShadingCurtainDeployPPFD, cropElectricityYieldSimulator1)
# convert PPFD to DLI
innerDLIToPlants = Util.convertFromHourlyPPFDWholeDayToDLI(hourlyInnerPPFDToPlants)
# print "innerDLIToPlants:{}".format(innerDLIToPlants)
return innerDLIToPlants
def penalizeDailyHarvestedFreshWeightPerHead(dailyHarvestedFreshWeightPerHead, simulatorClass):
'''
the function was made based on the data of plant fresh weights for 400 600, and 800 PPFD (umiol m^-2, s-1) in the source below:
Table 1 at "Effects of different light intensities on anti-oxidative enzyme activity, quality and biomass in lettuce, Weiguo Fu, Pingping Li, Yanyou Wu, Juanjuan Tang"
The parameters were derived with the solver of Excel 2007, the process is written in "penalizePlantYieldBySolarRadiation.xlsx"
Table 1. Quality and biomass of above-ground part of lettuce under different light intensity treatments
Light intensity (μmol m-2 s-1) Biomass of above-ground part (g plant-1, FW)
100 127.98 ± 8.32
200 145.65 ± 7.53
400 158.45 ± 6.21
600 162.89 ± 7.13
800 135.56 ± 5.76
'''
penalizedUnitDailyHarvestedFreshWeight = np.zeros(dailyHarvestedFreshWeightPerHead.shape[0])
# the DLI including both direct and diffuse to plants
totalDLItoPlants = simulatorClass.totalDLItoPlants
# print("totalDLItoPlants:{}".format(totalDLItoPlants))
# get the average DLI of each cultivation cycle.
if simulatorClass.getPlantGrowthModel() == constant.A_J_Both_Modified_TaylorExpantionWithFluctuatingDLI:
averageDLIonEachCycle = simulatorClass.getAverageDLIonEachCycle()
else:
averageDLIonEachCycle = np.zeros(simulatorClass.totalDLItoPlants.shape[0])
nextCultivationStartDay = 0
for i in range(0, simulatorClass.totalDLItoPlants.shape[0]):
# if the date is not the harvest date, then skip.
if dailyHarvestedFreshWeightPerHead[i] == 0.0:
continue
# Right row, E_J_VanHenten1994 is assumed
else:
# calc the average DLI during each cultivation cycle
averageDLIonEachCycle[i] = np.mean(totalDLItoPlants[nextCultivationStartDay:i + 1])
print("i:{}, averageDLIonEachCycle:{}".format(i, averageDLIonEachCycle[i]))
# update lastHarvestDay
# It was assumed to take 3 days to the next cultivation cycle assuming "transplanting shock prevented growth during the first 48 h", and it takes one day for preparation.
nextCultivationStartDay = i + 3
# print("averageDLIonEachCycle:{}".format(averageDLIonEachCycle))
# parameters, which is derived from the data of the reference
photoPriod = {"hour":14.0}
optimumLightIntensityDLI = {"mol m-2 d-1": 26.61516313}
# maximumYieldFW = {"g unit-1": 164.9777479}
maximumYieldFW = getPenalizedUnitFreshWeight(optimumLightIntensityDLI["mol m-2 d-1"])
# print("maximumYieldFW:{}".format(maximumYieldFW))
# convert PPFD to DLI
# optimumLightIntensityPPFD = {"umol m-2 s-1": 524.1249999}
# optimumLightIntensityDLI = {"mol m-2 d-1": optimumLightIntensityPPFD["umol m-2 s-1"] * constant.secondperMinute * constant.minuteperHour * photoPriod["hour"] / 1000000.0}
i = 0
while i < dailyHarvestedFreshWeightPerHead.shape[0]:
# if the date is not the harvest date, then skip.
if dailyHarvestedFreshWeightPerHead[i] == 0.0:
i += 1
continue
else:
print ("averageDLIonEachCycle:{}".format(averageDLIonEachCycle[i]))
print ("dailyHarvestedFreshWeightPerHead[i]:{}".format(dailyHarvestedFreshWeightPerHead[i]))
print("getPenalizedUnitFreshWeight(averageDLIonEachCycle[i]):{}, i:{}".format(getPenalizedUnitFreshWeight(averageDLIonEachCycle[i]), i))
if averageDLIonEachCycle[i] > optimumLightIntensityDLI["mol m-2 d-1"] and getPenalizedUnitFreshWeight(averageDLIonEachCycle[i]) > 0.0:
# penalize the plant fresh weight
print ("penaize the fresh weight, i:{}".format(i))
penalizedUnitDailyHarvestedFreshWeight[i] = dailyHarvestedFreshWeightPerHead[i] - dailyHarvestedFreshWeightPerHead[i] / maximumYieldFW["g unit-1"] * (maximumYieldFW["g unit-1"] - getPenalizedUnitFreshWeight(averageDLIonEachCycle[i]))
print("penalizedUnitDailyHarvestedFreshWeight[i]:{}".format(penalizedUnitDailyHarvestedFreshWeight[i]))
print("unitDailyHarvestedFreshWeight[i]:{}".format(dailyHarvestedFreshWeightPerHead[i]))
# if the penalty is too strong and the weight becomes zero
elif averageDLIonEachCycle[i] > optimumLightIntensityDLI["mol m-2 d-1"] and getPenalizedUnitFreshWeight(averageDLIonEachCycle[i]) <= 0.0:
print ("the light intensity may be too strong. The yield was penalized to zero")
penalizedUnitDailyHarvestedFreshWeight[i] = 0.0
# if no penalization occured
else:
penalizedUnitDailyHarvestedFreshWeight[i] = dailyHarvestedFreshWeightPerHead[i]
i += 1
return penalizedUnitDailyHarvestedFreshWeight
def getPenalizedUnitFreshWeight(lightIntensityDLI):
'''
The following parameters were derived from the soruce mentioned at penalizeDailyHarvestedFreshWeightPerHead
'''
a = -0.1563
b = 8.3199
c = 54.26
return a * lightIntensityDLI**2 + b * lightIntensityDLI + c
def getWholeElectricityYieldEachOPVRatio(OPVAreaCoverageRatio, dailyJopvout, cropElectricityYieldSimulator1, greenhouseRoofArea = None):
'''
return the total electricity yield for a given period by the given OPV area(OPVAreaCoverageRatio * constant.greenhouseRoofArea)
:param OPVAreaCoverageRatio: [-] proportionOPVAreaCoverageRatio
:param dailyJopvout: [J/m^2] per day
:return: dailyJopvout [J/m^2] by whole OPV area
'''
# get the OPV coverage ratio changing during the fallow period
unfixedOPVCoverageRatio = OPVFilm.getDifferentOPVCoverageRatioInSummerPeriod(OPVAreaCoverageRatio, cropElectricityYieldSimulator1)
# change the num of list from hourly data (365 * 24) to daily data (365)
unfixedOPVCoverageRatio = unfixedOPVCoverageRatio[::24]
if greenhouseRoofArea is None:
return sum(dailyJopvout * unfixedOPVCoverageRatio * constant.greenhouseRoofArea)
else:
return sum(dailyJopvout * unfixedOPVCoverageRatio * greenhouseRoofArea)
# # print "dailyJopvout:{}".format(dailyJopvout)
# totalJopvout = sum(dailyJopvout)
# if greenhouseRoofArea is None:
# return totalJopvout * unfixedOPVCoverageRatio * constant.greenhouseRoofArea
# else:
# return totalJopvout * unfixedOPVCoverageRatio * greenhouseRoofArea
def getMonthlyElectricitySalesperArea(dailyJopvoutperArea, yearOfeachDay, monthOfeachDay, simulatorClass):
'''
:param dailyJopvoutperArea:
:param yearOfeachDay:
:param monthOfeachDay:
:return:
'''
# unit: J/m^2/month
monthlyElectricityYieldperArea = OPVFilm.getMonthlyElectricityProductionFromDailyData(dailyJopvoutperArea, yearOfeachDay, monthOfeachDay)
# print("monthlyElectricityYieldperArea:{}".format(monthlyElectricityYieldperArea))
# import the electricity sales price file: source (download the CSV file): https://www.eia.gov/electricity/data/browser/#/topic/7?agg=0,1&geo=0000000001&endsec=vg&freq=M&start=200101&end=201802&ctype=linechart<ype=pin&rtype=s&maptype=0&rse=0&pin=
fileName = constant.averageRetailPriceOfElectricityMonthly
# import the file removing the header
fileData = Util.readData(fileName, relativePath="", skip_header=1, d='\t')
# print ("fileData:{}".format(fileData))
simulatorClass.monthlyElectricityRetailPrice = fileData
# print "monthlyElectricityYieldperArea.shape[0]:{}".format(monthlyElectricityYieldperArea.shape[0])
# year = np.zeros(monthlyElectricityYieldperArea.shape[0])
# month = np.zeros(monthlyElectricityYieldperArea.shape[0])
monthlyResidentialElectricityPrice = np.zeros(monthlyElectricityYieldperArea.shape[0])
index = 0
for monthlyData in fileData:
# exclude the data out of the set start month and end month
# print("monthlyData:{}".format(monthlyData))
if datetime.date(int(monthlyData[1]), int(monthlyData[0]), 1) + relativedelta(months=1) <= Util.getStartDateDateType() or \
datetime.date(int(monthlyData[1]), int(monthlyData[0]), 1) > Util.getEndDateDateType():
continue
# year[index] = monthlyData[1]
# month[index] = monthlyData[0]
# take the residential electricity retail price
monthlyResidentialElectricityPrice[index] = monthlyData[2]
# print "monthlyData:{}".format(monthlyData)
index += 1
# print("monthlyResidentialElectricityPrice[Cents/kwh]:{}".format(monthlyResidentialElectricityPrice))
# unit exchange: [J/m^2] -> [wh/m^2]
monthlyWhopvoutperArea =Util.convertFromJouleToWattHour(monthlyElectricityYieldperArea)
# unit exchange: [wh/m^2] -> [kwh/m^2]
monthlyKWhopvoutperArea =Util.convertWhTokWh(monthlyWhopvoutperArea)
# print("monthlyKWhopvoutperArea[kwh/m^2]:{}".format(monthlyKWhopvoutperArea))
# [USD/month/m^2]
monthlyElectricitySalesperArea = OPVFilm.getMonthlyElectricitySalesperArea(monthlyKWhopvoutperArea, monthlyResidentialElectricityPrice)
# print "monthlyElectricitySalesperArea:{}".format(monthlyElectricitySalesperArea)
return monthlyElectricitySalesperArea
def getMonthlyElectricitySales(OPVCoverage, monthlyElectricitySalesperArea, greenhouseRoofArea = None):
'''
return the monthly electricity saled given a cetain OPV coverage ratio
:param OPVCoverageList:
:param monthlyElectricitySalesperArea:
:return:
'''
if greenhouseRoofArea is None:
return monthlyElectricitySalesperArea * OPVCoverage * constant.greenhouseRoofArea
else:
return monthlyElectricitySalesperArea * OPVCoverage * greenhouseRoofArea
def getElectricitySalesperAreaEachOPVRatio():
return 0
def getElectricityCostperArea():
return 0
def getPlantSalesperSquareMeter(simulatorClass):
"""
calculate the sales price of lettuce per square meter.
The referred price is Lettuce, romaine, per lb. (453.6 gm) in U.S ( Northeast region: Connecticut, Maine, Massachusetts, New Hampshire, New Jersey, New York, Pennsylvania, Rhode Island, and Vermont.), city average, average price, not seasonally adjusted
reference URL: https://data.bls.gov/timeseries/APU0000FL2101?amp%253bdata_tool=XGtable&output_view=data&include_graphs=true
"""
# get the following data from the object
totalDLIToPlants = simulatorClass.totalDLItoPlants
#################### this conversion is not used any more ####################
# # the price of lettuce per hundredweight [cwt]
# priceperCwtEachHour = Lettuce.getLettucePricepercwt(year)
# # unit conversion: cwt -> kg
# priceperKgEachHour = priceperCwtEachHour / constant.kgpercwt * constant.plantPriceDiscountRatio_justForSimulation
# # print "harvestedFreshWeightListperAreaKg:{}".format(harvestedFreshWeightListperAreaKg)
# # print "dailyHarvestedFreshWeightListperAreaKg.shape:{}".format(dailyHarvestedFreshWeightListperAreaKg.shape)
# # print "priceperKg:{}".format(priceperKg)
# # convert the price each hour to the price each day
# priceperKgEachDay = priceperKgEachHour[::24]
# # print "priceperKgEachDay:{}".format(priceperKgEachDay)
# # print "priceperKgEachDay.shape:{}".format(priceperKgEachDay.shape)
#################################################################################0
# get the retail price of lettuce harvested at each cycle
# unit: USD/m^2/day
plantSalesPerSquareMeter = Lettuce.getRetailPricePerArea(simulatorClass)
# print ("plantSalesPerSquareMeter:{}".format(plantSalesPerSquareMeter))
if constant.IfConsiderDiscountByTipburn == True:
# Tipburn discount
# TODO: need to refine more
plantSalesperSquareMeter = Lettuce.discountPlantSalesperSquareMeterByTipburn(plantSalesPerSquareMeter, totalDLIToPlants)
return plantSalesPerSquareMeter
def getGreenhouseOperationCostForGrowingPlants(simulatorClass):
'''
This function estimates the economic cost for cooling and heating a greenhouse by simulating the energy balance model of a greenhouse.
'''
# get environment data to calculate the energy for cooling and heating
# the energy for cooling and heating
energyBalance.getGHEnergyConsumptionByCoolingHeating(simulatorClass)
# unit: W
Q_vW = simulatorClass.Q_vW
# ############command to print out all array data
# np.set_printoptions(threshold=np.inf)
# print("Q_vW:{}".format(Q_vW))
# np.set_printoptions(threshold=1000)
# ############
# if the energy balance is minus, we need to heat to maintain the internal temperature. [W m]
requiredHeatingEnergyForPlants = np.array([-Q_vW["coolingOrHeatingEnergy W"][i] if Q_vW["coolingOrHeatingEnergy W"][i] < 0.0 else 0.0 for i in range (Q_vW["coolingOrHeatingEnergy W"].shape[0])])
# if the energy balance is plus, we need to cool to maintain the internal temperature. [W m]
requiredCoolingEnergyForPlants = np.array([Q_vW["coolingOrHeatingEnergy W"][i] if Q_vW["coolingOrHeatingEnergy W"][i] > 0.0 else 0.0 for i in range (Q_vW["coolingOrHeatingEnergy W"].shape[0])])
# ############command to print out all array data
# np.set_printoptions(threshold=np.inf)
# print("requiredCoolingEnergyForPlants:{}".format(requiredCoolingEnergyForPlants))
# np.set_printoptions(threshold=1000)
# ############
# unit: USD
totalHeatingCostForPlants = energyBalance.getGHHeatingEnergyCostForPlants(requiredHeatingEnergyForPlants, simulatorClass)
totalCoolingCostForPlants = energyBalance.getGHCoolingEnergyCostForPlants(requiredCoolingEnergyForPlants, simulatorClass)
simulatorClass.totalHeatingCostForPlants = totalHeatingCostForPlants
simulatorClass.totalCoolingCostForPlants = totalCoolingCostForPlants
# unit: USD m-2
totalHeatingCostForPlantsPerGHFloorArea = totalHeatingCostForPlants / constant.greenhouseFloorArea
totalCoolingCostForPlantsPerGHFloorArea = totalCoolingCostForPlants / constant.greenhouseFloorArea
simulatorClass.totalHeatingCostForPlantsPerGHFloorArea = totalHeatingCostForPlantsPerGHFloorArea
simulatorClass.totalCoolingCostForPlantsPerGHFloorArea = totalCoolingCostForPlantsPerGHFloorArea
return totalHeatingCostForPlants, totalCoolingCostForPlants
def getLaborCost(simulatorClass):
"""
get the total labor cost during the simulation period
:return:
"""
harvestedShootFreshMassPerAreaKgPerDay = simulatorClass.harvestedShootFreshMassPerAreaKgPerDay
# unit:kg
totalHarvestedShootFreshMass = sum(harvestedShootFreshMassPerAreaKgPerDay) * constant.greenhouseCultivationFloorArea
# print("totalHarvestedShootFreshMass:{}".format(totalHarvestedShootFreshMass))
# source: https://onlinelibrary.wiley.com/doi/abs/10.1111/cjag.12161
# unit: [labors/10000 kg yield]
necessaryLaborPer10000kgYield = constant.necessaryLaborPer10000kgYield
# source:https://www.bls.gov/regions/west/news-release/occupationalemploymentandwages_tucson.htm
# unit:USD/labor/hour
hourlyWagePerPerson = constant.hourlyWagePerPerson
# unit:hour/day
workingHourPerDay = constant.workingHourPerDay
totalLaborCost = (totalHarvestedShootFreshMass / 10000.0) * necessaryLaborPer10000kgYield * workingHourPerDay * hourlyWagePerPerson * Util.getSimulationDaysInt()
# print("totalLaborCost:{}".format(totalLaborCost))
return totalLaborCost
def getPlantCostperSquareMeter(simulationDays):
'''
calculate the cost for plant cultivation for given period
:param year:
:return:
'''
# [USD/m^2]
return constant.plantcostperSquaremeterperYear * simulationDays / constant.dayperYear
################################################# old code below################################
def calcOptimizedOPVAreaMaximizingtotalEconomicProfit(OPVAreaVector, totalEconomicProfitperYearVector):
'''
determine the best OPVArea maximizing the economic profit
param:
OPVAreaVector
totalEconomicProfitperYearVector
return:
none
'''
maxtotalEconomicProfitperYear = np.max(totalEconomicProfitperYearVector)
bestOPVArea = OPVAreaVector[np.argmax(totalEconomicProfitperYearVector)]
print ("The OPV area maximizing the economic profit is {}m^2 the max economic profit is {}USD/year ".format(bestOPVArea, maxtotalEconomicProfitperYear))
def trainWeightsRLShadingCurtainDayStep(hasShadingCurtain, qLearningAgentsShadingCurtain=None, cropElectricityYieldSimulator1 = None):
'''
:param hasShadingCurtain:
:param cropElectricityYieldSimulator1:
:return:
'''
if hasShadingCurtain:
# # set values necessary for RL training/testing
# # for dLIEachdayThroughInnerStructure on a certain day
# hourlyInnerLightIntensityPPFDThroughInnerStructure = cropElectricityYieldSimulator1.getHourlyInnerLightIntensityPPFDThroughInnerStructure()
# # set dLIThroughInnerStructure to the object
# dLIThroughInnerStructure = Util.convertFromHourlyPPFDWholeDayToDLI(hourlyInnerLightIntensityPPFDThroughInnerStructure)
# qLearningAgentsShadingCurtain.setDLIThroughInnerStructure(dLIThroughInnerStructure)
print ("training parameters: epsilon={}, gamma={}, alpha={}, period:{}".format(\
qLearningAgentsShadingCurtain.epsilon, qLearningAgentsShadingCurtain.gamma, qLearningAgentsShadingCurtain.alpha, constant.SimulationStartDate + "-" + constant.SimulationEndDate))
for trainingIteration in range (0, qLearningAgentsShadingCurtain.numTraining):
if trainingIteration % 100 == 0:
# print("Iteration checkpoint: datetime.datetime.now():{}. trainingIteration:{}".format(datetime.datetime.now(), trainingIteration ))
print("trainingIteration: {}, qLearningAgentsShadingCurtain.weights:{}, datetime.datetime.now():{}".format(\
trainingIteration, qLearningAgentsShadingCurtain.weights, datetime.datetime.now()))
# training the q value function
for day in range (0, Util.getSimulationDaysInt()):
state = day
#########################################################################
############# set values necessary for RL training features##############
#########################################################################
# set day to the instance
qLearningAgentsShadingCurtain.setDay(day)
# dLIEachdayThroughInnerStructure on a certain day, necessary to cal DLI to PLants
# qLearningAgentsShadingCurtain.setDLIEachDayThroughInnerStructure(dLIThroughInnerStructure[state])
#set num of days from Jan 1st.
daysFromJan1st = Util.getNumOfDaysFromJan1st(Util.getStartDateDateType() + datetime.timedelta(days=day))
# date on a certain day
qLearningAgentsShadingCurtain.setDaysFromJan1st(daysFromJan1st)
# action = "openCurtain" or "closeCurtain"
# if the state is at the terminal state, action is None.
action = qLearningAgentsShadingCurtain.getAction(state)
# if the q value is not initialized, initialize the q value. if initialized, just get the q value given state and action
# state = qlearningAgentsShadingCurtain.getQValue(day, action)
approximateQvalue = qLearningAgentsShadingCurtain.getApproximateQValue(state, action)
# print ("approximateQvalue:{}".format(approximateQvalue))
# set approximateQvalue to Q
qLearningAgentsShadingCurtain.setApproximateQValue(approximateQvalue, state, action)
# approximatedQvalueNextState = []
# for action in qLearningAgentsShadingCurtain.getLegalActions(day):
# approximatedQvalueNextState.append(qLearningAgentsShadingCurtain.getApproximateQValue(day + 1, action))
# approximateMaxQvalueNextState = max[approximatedQvalueNextState]
# get the maximum q value in the next state
if (state+1) == Util.getSimulationDaysInt():
approximateMaxQvalueNextState = 0.0
else:
approximateMaxQvalueNextState = qLearningAgentsShadingCurtain.getApproximateValue(state + 1)
# calc the difference between the current q value and the maximum q value in the next state, which is used for updating weights
difference = (qLearningAgentsShadingCurtain.getReward(day) + approximateMaxQvalueNextState) - approximateQvalue
# print ("qLearningAgentsShadingCurtain.getReward(day):{}".format(qLearningAgentsShadingCurtain.getReward(day)))
# print ("approximateMaxQvalueNextState:{}".format(approximateMaxQvalueNextState))
# print ("approximateQvalue:{}".format(approximateQvalue))
# print ("difference:{}".format(difference))
# update weight of the q learning function
qLearningAgentsShadingCurtain.updateApproximateWeight(difference)
# print ("qLearningAgentsShadingCurtain.weights:{}".format(qLearningAgentsShadingCurtain.weights))
# print ("check trainingIteration:{}".format(trainingIteration))
# print ("qLearningAgentsShadingCurtain.weights:{}".format(qLearningAgentsShadingCurtain.weights))
print ("qLearningAgentsShadingCurtain.approximateQ:{}".format(qLearningAgentsShadingCurtain.approximateQ))
return qLearningAgentsShadingCurtain
# ####################################################################################################
# Stop execution here...
# sys.exit()
# Move the above line to different parts of the assignment as you implement more of the functionality.
# ####################################################################################################
def testWeightsRLShadingCurtainDayStep(hasShadingCurtain, qLearningAgentsShadingCurtain = None, cropElectricityYieldSimulator1=None):
numTesting = qLearningAgentsShadingCurtain.numTesting
if hasShadingCurtain:
# change the exploration rate into zero because in testing, RL does not explore
qLearningAgentsShadingCurtain.epsilon = 0.0
# array to store the sales price at each iteration
plantSalesperSquareMeterList = np.zeros(numTesting)
for testingIteration in range(0, numTesting):
# get values necessary for RL training, which was done at
# hourlyInnerLightIntensityPPFDThroughInnerStructure = cropElectricityYieldSimulator1.getHourlyInnerLightIntensityPPFDThroughInnerStructure()
# dLIThroughInnerStructure = Util.convertFromHourlyPPFDWholeDayToDLI(hourlyInnerLightIntensityPPFDThroughInnerStructure)
# set dLIThroughInnerStructure to the object
# qLearningAgentsShadingCurtain.setDLIThroughInnerStructure(dLIThroughInnerStructure)
print("testingIteration: {}, qLearningAgentsShadingCurtain.weights:{}, datetime.datetime.now():{}, period:{}".format( \
testingIteration, qLearningAgentsShadingCurtain.weights, datetime.datetime.now(), constant.SimulationStartDate + "-" + constant.SimulationEndDate ))
# training the q value function
for day in range(0, Util.getSimulationDaysInt()):
state = day
#########################################################################
############# set values necessary for RL training features##############
#########################################################################
# set day to the instance
qLearningAgentsShadingCurtain.setDay(day)
# dLIEachdayThroughInnerStructure on a certain day, necessary to cal DLI to PLants
# qLearningAgentsShadingCurtain.setDLIEachDayThroughInnerStructure(dLIThroughInnerStructure[state])
# set num of days from Jan 1st.
daysFromJan1st = Util.getNumOfDaysFromJan1st(Util.getStartDateDateType() + datetime.timedelta(days=day))
# date on a certain day
qLearningAgentsShadingCurtain.setDaysFromJan1st(daysFromJan1st)
# action = "openCurtain" or "closeCurtain"
# if the state is at the terminal state, action is None.
action = qLearningAgentsShadingCurtain.getPolicy(state)
# store the action at each state at tuples in list for a record.
qLearningAgentsShadingCurtain.policies[state] = action
################## calculate the daily plant yield start#####################
#### calc the DLI on a certain state
dLIEachDayThroughInnerStructure = qLearningAgentsShadingCurtain.getDLIThroughInnerStructureElement(state)
dLIEachDayToPlants = 0.0
if action == constant.openCurtainString:
dLIEachDayToPlants = dLIEachDayThroughInnerStructure
elif action == constant.closeCurtainString:
dLIEachDayToPlants = dLIEachDayThroughInnerStructure * constant.shadingTransmittanceRatio
#store the DLI ateach state by list for a record. since the sequence is important, not use a dictionary.
qLearningAgentsShadingCurtain.dLIEachDayToPlants[day] = dLIEachDayToPlants
###### calc plant weight increase with a certain DLI
# num of days from the latest seeding
daysFromSeeding = state % constant.cultivationDaysperHarvest
# if the calc method is A.J Both 2003 model
if qLearningAgentsShadingCurtain.cropElectricityYieldSimulator1.getPlantGrowthModel() == constant.TaylorExpantionWithFluctuatingDLI:
# daily [g/unit]
unitDailyFreshWeightIncreaseElement = \
Lettuce.calcUnitDailyFreshWeightIncreaseBoth2003Taylor(dLIEachDayToPlants, constant.cultivationDaysperHarvest, daysFromSeeding)
# update the values to the instance
qLearningAgentsShadingCurtain.setUnitDailyFreshWeightIncreaseElementShadingCurtain(unitDailyFreshWeightIncreaseElement, state)
# print ("1 unitDailyFreshWeightIncrease [g/unit]:{}, state:{}".format(unitDailyFreshWeightIncreaseElement, state))
else:
print ("[test] error: feasture w_2 not considered. choosing un-existing plant growth model")
################## calculate the daily plant yield end#####################
################## calculate the total plant sales start#####################
print ("DLI to plants at each day [mol/m^2/m^2]".format(qLearningAgentsShadingCurtain.dLIEachDayToPlants))
unitPlantWeight = qLearningAgentsShadingCurtain.getUnitDailyFreshWeightIncreaseListShadingCurtain()
print ("unitPlantWeight [g/unit]:{}".format(unitPlantWeight))
totalUnitPlantWeight = sum(unitPlantWeight)
# unit conversion; get the daily plant yield per given period per area: [g/unit] -> [g/m^2]
unitPlantWeightperArea = Util.convertUnitShootFreshMassToShootFreshMassperArea(unitPlantWeight)
# unit conversion: [g/m^2] -> [kg/m^2]1
unitPlantWeightperAreaKg = Util.convertFromgramTokilogram(unitPlantWeightperArea)
# get the sales price of plant [USD/m^2]
# if the average DLI during each harvest term is more than 17 mol/m^2/day, discount the price
dailyPlantSalesperSquareMeter = getPlantSalesperSquareMeter(\
cropElectricityYieldSimulator1.getYear(), unitPlantWeightperAreaKg, qLearningAgentsShadingCurtain.dLIEachDayToPlants)
plantSalesperSquareMeter = sum(dailyPlantSalesperSquareMeter)
plantSalesperSquareMeterList[testingIteration] = plantSalesperSquareMeter
# print "dailyPlantSalesperSquareMeter.shape:{}".format(dailyPlantSalesperSquareMeter.shape)
print ("plantSalesperSquareMeterList[{}]:{}".format(testingIteration, plantSalesperSquareMeterList))
################## calculate the total plant sakes end#####################
else:
print ("shading curtain assumed not to be given. the function without shading curtain will be made in the future")
# return the average of testing results
return plantSalesperSquareMeter
|
{"/OPVFilm.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/ShadingCurtain.py"], "/CropElectricityYieldProfitMINLP.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelS_Pearson1997.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/PlantGrowthModelS_Pearson1997Constant.py", "/Lettuce.py"], "/GreenhouseEnergyBalanceConstant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/Util.py": ["/CropElectricityYeildSimulatorConstant.py"], "/SolarIrradianceMultiSpanRoof.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/GreenhouseEnergyBalance.py": ["/Lettuce.py", "/CropElectricityYeildSimulatorConstant.py", "/GreenhouseEnergyBalanceConstant.py", "/Util.py"], "/SimulatorMain.py": ["/CropElectricityYeildSimulator1.py", "/Util.py", "/CropElectricityYeildSimulatorConstant.py"], "/CropElectricityYieldProfitRLShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/ShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelValidation.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulator1.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulatorDetail.py": ["/ShadingCurtain.py", "/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/Lettuce.py", "/PlantGrowthModelS_Pearson1997.py", "/SolarIrradianceMultiSpanRoof.py", "/GreenhouseEnergyBalance.py"], "/PlantGrowthModelS_Pearson1997Constant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/SimulatorClass.py": ["/CropElectricityYeildSimulatorConstant.py"], "/Lettuce.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/plantGrowthModelE_J_VanHenten.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py"]}
|
8,669
|
kensaku-okada/Greenhouse-with-OPV-film-Model
|
refs/heads/master
|
/PlantGrowthModelE_J_VanHentenConstant.py
|
# -*- coding: utf-8 -*-
#######################################################
# author :Kensaku Okada [kensakuokada@email.arizona.edu]
# create date : 15 Jun 2017
# last edit date: 15 Jun 2017
#######################################################
# convert ratio of CO2 into SUgar (CH2O)
c_alpha = 30.0 / 44.0
# respiratory and syntehsis losses of non-structural material due to growth
c_beta = 0.8
# the saturation growth rate at 20[C] [/s]
c_gr_max = {'s-1' :5.0 * 10**(-6)}
c_gamma = 1.0
# Q10 factor for growth
c_Q10_gr = 1.6
# the maintenance respiration coefficient for shoot at 25[C]
c_resp_sht = {'s-1' : 3.47 * 10**(-7)}
# the maintenance respiration coefficient for root at 25[C]
c_resp_rt = {'s-1' : 1.16 * 10**(-7)}
# Q10 factor of the maintenance respiration
c_Q10_resp = 2.0
# the ratio of the root dry weight to the total crop dry weight
c_tau = 0.15
# extinction coefficient
# c_K = 0.9
# extinction coefficient for 25 heads/m^2 density
c_K = 1.0
# structural leaf area ratio
c_lar = {'m2 g-2' : 75 * 10**(-3)}
# density of CO2
c_omega = {'g m-3' : 1.83 * 10**(-3) }
# the CO2 compensation point at 20[C]
c_upperCaseGamma = {'ppm': 40.0}
# the Q10 value which account for the effect of temperature on upperCaseGamma (Γ)
c_Q10_upperCaseGamma = 2.0
# light use efficiency at very high CO2 concentrations
c_epsilon = {'g J-1' : 17.0 * 10 ** (-6)}
# the boundary layer conductance of lettuce leaves
g_bnd = {'m s-1' : 0.007}
# the stomatal resistance
g_stm = {'m s-1': 0.005 }
# parameters for the carboxylation conductance
c_car1 = -1.32 * 10**(-5)
c_car2 = 5.94 * 10**(-4)
c_car3 = -2.64 * 10**(-3)
canopyTemp = {'celsius': 17.5 }
# canopyTemp = {'celsius': 40 }
# canopyTemp = {'celsius': 5 }
carboxilationConductatnce = c_car1 * canopyTemp['celsius']**2 + c_car1 * canopyTemp['celsius'] + c_car3
# print (carboxilationConductatnce)
canopyTemp = {'celsius': 40 }
carboxilationConductatnce = c_car1 * canopyTemp['celsius']**2 + c_car1 * canopyTemp['celsius'] + c_car3
# print (carboxilationConductatnce)
canopyTemp = {'celsius': 5 }
carboxilationConductatnce = c_car1 * canopyTemp['celsius']**2 + c_car1 * canopyTemp['celsius'] + c_car3
# print (carboxilationConductatnce)
|
{"/OPVFilm.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/ShadingCurtain.py"], "/CropElectricityYieldProfitMINLP.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelS_Pearson1997.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/PlantGrowthModelS_Pearson1997Constant.py", "/Lettuce.py"], "/GreenhouseEnergyBalanceConstant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/Util.py": ["/CropElectricityYeildSimulatorConstant.py"], "/SolarIrradianceMultiSpanRoof.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/GreenhouseEnergyBalance.py": ["/Lettuce.py", "/CropElectricityYeildSimulatorConstant.py", "/GreenhouseEnergyBalanceConstant.py", "/Util.py"], "/SimulatorMain.py": ["/CropElectricityYeildSimulator1.py", "/Util.py", "/CropElectricityYeildSimulatorConstant.py"], "/CropElectricityYieldProfitRLShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/ShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelValidation.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulator1.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulatorDetail.py": ["/ShadingCurtain.py", "/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/Lettuce.py", "/PlantGrowthModelS_Pearson1997.py", "/SolarIrradianceMultiSpanRoof.py", "/GreenhouseEnergyBalance.py"], "/PlantGrowthModelS_Pearson1997Constant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/SimulatorClass.py": ["/CropElectricityYeildSimulatorConstant.py"], "/Lettuce.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/plantGrowthModelE_J_VanHenten.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py"]}
|
8,670
|
kensaku-okada/Greenhouse-with-OPV-film-Model
|
refs/heads/master
|
/PlantGrowthModelS_Pearson1997Constant.py
|
# -*- coding: utf-8 -*-
##########import package files##########
from scipy import stats
import sys
import datetime
import os as os
import numpy as np
import matplotlib.pyplot as plt
import math
import CropElectricityYeildSimulatorConstant as constant
import Util
#######################################################
# reference of the model: https://www.tandfonline.com/doi/abs/10.1080/14620316.1997.11515538
# A validated model to predict the effects of environment on the growth of lettuce (Lactuca sativa L.): Implications for climate change
# Optimum temperature for conversion of storage to structural dry weight [Celsius]
T_OS = 30.0
# Partitioning coefficient of storage to structural dry weight [g / (g * day * Celsius)]
#TODO there is no source about the value k. In my model, this was changed in my own way so that the model exibits an appropriate transition of head weight. So, need to validate it.
# k = 6.9 * 10.0**(-2)
k = 6.9 * 10.0**(-2) / 4.0
# Factor to convert CO 2 to plant dry weight [-]
psi = 30.0/44.0
# Distance between plants [m]
h = 0.2
# Leaf area ratio [1/(m^2 * kg)]
F_G = 75.0
# Leaf light utilization efficiency [kg(CO_2) / J ]
alpha_m = 14.0 * 10**(-9)
# Photo-respiration constant [kg(CO_2) / (m^2 * s)]
beta = 1.0 * 10**(-7)
# Leaf conductance
tau = 0.002
# Thermal time for the cessation of photosynthesis [Celsius * d]
theta_m = 1600.0
# Optimum temperature for photosynthesis [Celsius]
T_op = 25.0
# Rate constant for the effect of temperature on photosynthesis [1/Celcius]
phi = 0.02
# Respiration rate constant [g(W_S)/g(W_G)]
R_G = 0.3
# Ontogenetic respiration rate constant [-]
gamma = 3.0
# Rate constant for the effect of temperature on respiration [1/Celsius]
epsilon = 0.03
# optimal temperature [Celusius]
# reference: Pearson, S. Hadley, P. Wheldon, A.E. (1993), "A reanalysis of the effects of temperature and irradiance on time to flowering in chrysanthemum (Dendranthema grandiflora)"
# https://scholar.google.com/citations?user=_xeFP80AAAAJ&hl=en#d=gs_md_cita-d&p=&u=%2Fcitations%3Fview_op%3Dview_citation%26hl%3Den%26user%3D_xeFP80AAAAJ%26citation_for_view%3D_xeFP80AAAAJ%3Au-x6o8ySG0sC%26tzom%3D420
# Effective temperature is the sub-optimum temperature equivalent of a supra-optimum temperature in terms of developmental rate.
T_o = T_op
|
{"/OPVFilm.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/ShadingCurtain.py"], "/CropElectricityYieldProfitMINLP.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelS_Pearson1997.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/PlantGrowthModelS_Pearson1997Constant.py", "/Lettuce.py"], "/GreenhouseEnergyBalanceConstant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/Util.py": ["/CropElectricityYeildSimulatorConstant.py"], "/SolarIrradianceMultiSpanRoof.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/GreenhouseEnergyBalance.py": ["/Lettuce.py", "/CropElectricityYeildSimulatorConstant.py", "/GreenhouseEnergyBalanceConstant.py", "/Util.py"], "/SimulatorMain.py": ["/CropElectricityYeildSimulator1.py", "/Util.py", "/CropElectricityYeildSimulatorConstant.py"], "/CropElectricityYieldProfitRLShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/ShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelValidation.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulator1.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulatorDetail.py": ["/ShadingCurtain.py", "/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/Lettuce.py", "/PlantGrowthModelS_Pearson1997.py", "/SolarIrradianceMultiSpanRoof.py", "/GreenhouseEnergyBalance.py"], "/PlantGrowthModelS_Pearson1997Constant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/SimulatorClass.py": ["/CropElectricityYeildSimulatorConstant.py"], "/Lettuce.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/plantGrowthModelE_J_VanHenten.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py"]}
|
8,671
|
kensaku-okada/Greenhouse-with-OPV-film-Model
|
refs/heads/master
|
/SimulatorClass.py
|
import CropElectricityYeildSimulatorConstant as constant
class SimulatorClass:
# constructor
def __init__(self):
self._OPVAreaCoverageRatio = constant.OPVAreaCoverageRatio
self._OPVCoverageRatioSummerPeriod = constant.OPVAreaCoverageRatioSummerPeriod
self._OPVCoverageRatiosConsiderSummerRatio = None
self._plantGrowthModel = constant.plantGrowthModel
self._shootFreshMassList = None
self._cultivationDaysperHarvest = constant.cultivationDaysperHarvest
self._hasShadingCurtain = constant.hasShadingCurtain
self._shadingCurtainDeployPPFD = constant.plantGrowthModel
self._profitVSOPVCoverageData = None
self._monthlyElectricitySalesperArea = None
self._monthlyElectricitySalesperAreaEastRoof = None
self._monthlyElectricitySalesperAreaWestRoof = None
self._totalElectricitySalesPerAreaPerMonth = None
self._totalElectricitySalesPerMonth = None
self._totalElectricitySales = None
self._oPVCostUSDForDepreciationPerOPVArea = None
self._totalOPVCostUSDForDepreciation = None
self._totalOPVCostUSDForDepreciationPerGHFloorArea = None
self._electricityProductionProfit = None
self._electricityProductionProfitPerGHFloorArea = None
self._hourlyInnerLightIntensityPPFDThroughGlazing = None
self._hourlyInnerLightIntensityPPFDThroughInnerStructure = None
self._directPPFDToOPVEastDirection = None
self._directPPFDToOPVWestDirection = None
self._diffusePPFDToOPV = None
self._groundReflectedPPFDToOPV = None
# self._totalDLItoPlantsBaselineShadingCuratin = None
self._directDLIToOPVEastDirection = None
self._directDLIToOPVWestDirection = None
self._diffuseDLIToOPV = None
self._groundReflectedDLIToOPV = None
self._hourlyDirectSolarRadiationAfterMultiSpanRoof = None
self._hourlyDiffuseSolarRadiationAfterMultiSpanRoof = None
self._groundReflectedRadiationAfterMultiSpanRoof = None
self._hourlyDirectPPFDAfterMultiSpanRoof = None
self._hourlyDiffusePPFDAfterMultiSpanRoof = None
self._groundReflectedPPFDAfterMultiSpanRoof = None
self._shootFreshMassList = None
self._unitDailyFreshWeightIncrease = None
self._accumulatedUnitDailyFreshWeightIncrease = None
self._unitDailyHarvestedFreshWeight = None
self._totalPlantSalesperSquareMeter = None
self._totalPlantSales = None
self._totalPlantSalesPerGHFloorArea = None
self._Q_v = {"coolingOrHeatingEnergy W m-2": None}
self._Q_sr = {"solarIrradianceToPlants W m-2": None}
self._Q_lh = {"sensibleHeatFromConductionAndConvection W m-2": None}
self._Q_sh = {"latentHeatByTranspiration W m-2": None}
self._Q_lw = {"longWaveRadiation W m-2": None}
self._Q_vW = {"coolingOrHeatingEnergy W": None}
self._Q_srW = {"solarIrradianceToPlants W": None}
self._Q_lhW = {"sensibleHeatFromConductionAndConvection W": None}
self._Q_shW = {"latentHeatByTranspiration W": None}
self._Q_lwW = {"longWaveRadiation W": None}
self._monthlyRequiredGHHeatingEnergyForPlants = None
self._totalHeatingCostForPlants = None
self._totalCoolingCostForPlants = None
self._totalLaborCost = None
self._totalLaborCostPerGHFloorArea = None
self._totalPlantProductionCost = None
self._totalPlantProductionCostPerGHFloorArea = None
self._totalPlantProfit = None
self._totalPlantProfitPerGHFloorArea = None
self._economicProfit = None
self._economicProfitPerGHFloorArea = None
self._averageDLIonEachCycle = None
self._year = None
self._month = None
self._day = None
self._hour = None
self._importedHourlyHorizontalDirectSolarRadiation = None
self._importedHourlyHorizontalDiffuseSolarRadiation = None
self._importedHourlyHorizontalTotalBeamMeterBodyTemperature = None
self._importedHourlyAirTemperature = None
self._hourlyRelativeHumidity = None
self._directSolarRadiationToOPVEastDirection = None
self._directSolarRadiationToOPVWestDirection = None
self._diffuseSolarRadiationToOPV = None
self._albedoSolarRadiationToOPV = None
self._estimatedDirectSolarRadiationToOPVEastDirection = None
self._estimatedDirectSolarRadiationToOPVWestDirection = None
self._estimatedDiffuseSolarRadiationToOPV = None
self._estimatedAlbedoSolarRadiationToOPV = None
self._hourlySolarIncidenceAngleEastDirection = None
self._hourlySolarIncidenceAngleWestDirection = None
self._directSolarIrradianceBeforeShadingCurtain = None
self._diffuseSolarIrradianceBeforeShadingCurtain = None
self._directSolarIrradianceToPlants = None
self._diffuseSolarIrradianceToPlants = None
self._transmittanceThroughShadingCurtainChangingEachMonth = None
self._directPPFDToPlants = None
self._diffusePPFDToPlants = None
self._directDLIToPlants = None
self._diffuseDLIToPlants = None
self._totalDLItoPlants = None
self._hourlyDayOrNightFlag = None
self._hourlyHorizontalDiffuseOuterSolarIrradiance = None
self._hourlyHorizontalTotalOuterSolarIrradiance = None
self._hourlyHorizontalDirectOuterSolarIrradiance = None
self._hourlyHorizontalTotalBeamMeterBodyTemperature = None
self._hourlyAirTemperature = None
# self._ifGrowForSummerPeriod = False
self._ifGrowForSummerPeriod = None
# if you want to calculate the estimated data which does not require the measured data, set this variable True.
self._estimateSolarRadiationMode = False
self._ifHasShadingCurtain = None
self._hourlySolarAltitudeAngle = None
self._hourlySolarAzimuthAngle = None
self._hourlyModuleAzimuthAngleEast = None
self._hourlyModuleAzimuthAngleWest = None
self._T_matForPerpendicularIrrEastOrNorthFacingRoof = None
self._T_matForPerpendicularIrrWestOrSouthFacingRoof = None
self._integratedT_mat = None
self._directHorizontalSolarRadiation = None
self._diffuseHorizontalSolarRadiation = None
self._totalHorizontalSolarRadiation = None
self._dailyWhopvoutperAreaEastRoof = None
self._dailyWhopvoutperAreaWestRoof = None
self._dailykWhopvoutperAreaEastRoof = None
self._dailykWhopvoutperAreaWestRoof = None
self._totalkWhopvoutPerday = None
self._monthlyElectricityRetailPrice = None
self._totalkWhopvoutPerAreaPerday = None
self._totalkWhopvoutPerAreaPerday = None
self._LeafAreaIndex_J_VanHenten1994 = None
self._summerPeriodFlagArray = None
self._dailyShootFreshMass = None
self._dailyUnitDailyFreshWeightIncrease = None
self._dailyAccumulatedUnitDailyFreshWeightIncrease = None
self._dailyUnitHarvestedFreshWeight = None
self._shootFreshMassPerAreaKgPerDay = None
self._harvestedShootFreshMassPerAreaKgPerDay = None
self._totalHarvestedShootFreshMass = None
# variables for validation
self._GHSolarIrradianceValidationData = None
self._GHAirTemperatureValidationData = None
#################################################################################################
################################## variables for debugging start ################################
#################################################################################################
self._r_a = None
self._L = None
self._r_b = None
self._e_a = None
self._e_s = None
self._r_s = None
self._r_c = None
self._gamma = None
self._gamma_star = None
self._s = None
self._R_n = None
@property
def r_a(self):
return self._r_a
@r_a.setter
def r_a(self, r_a):
self._r_a= r_a
@property
def L(self):
return self._L
@L.setter
def L(self, L):
self._L= L
@property
def r_b(self):
return self._r_b
@r_b.setter
def r_b(self, r_b):
self._r_b= r_b
@property
def e_a(self):
return self._e_a
@e_a.setter
def e_a(self, e_a):
self._e_a= e_a
@property
def e_s(self):
return self._e_s
@e_s.setter
def e_s(self, e_s):
self._e_s= e_s
@property
def r_s(self):
return self._r_s
@r_s.setter
def r_s(self, r_s):
self._r_s = r_s
@property
def r_c(self):
return self._r_c
@r_c.setter
def r_c(self, r_c):
self._r_c = r_c
@property
def gamma(self):
return self._gamma
@gamma.setter
def gamma(self, gamma):
self._gamma = gamma
@property
def gamma_star(self):
return self._gamma_star
@gamma_star.setter
def gamma_star(self, gamma_star):
self._gamma_star = gamma_star
@property
def s(self):
return self._s
@s.setter
def s(self, s):
self._s =s
@property
def R_n(self):
return self._R_n
@R_n.setter
def R_n(self, R_n):
self._R_n = R_n
#################################################################################################
################################## variables for debugging end ##################################
#################################################################################################
def setOPVAreaCoverageRatio(self, OPVAreaCoverageRatio):
self._OPVAreaCoverageRatio = OPVAreaCoverageRatio
def getOPVAreaCoverageRatio(self):
return self._OPVAreaCoverageRatio
def setOPVCoverageRatioSummerPeriod(self, OPVCoverageRatioSummerPeriod):
self._OPVCoverageRatioSummerPeriod = OPVCoverageRatioSummerPeriod
def getOPVCoverageRatioSummerPeriod(self):
return self._OPVCoverageRatioSummerPeriod
@property
def OPVCoverageRatiosConsiderSummerRatio(self):
return self._OPVCoverageRatiosConsiderSummerRatio
@OPVCoverageRatiosConsiderSummerRatio.setter
def OPVCoverageRatiosConsiderSummerRatio(self, OPVCoverageRatiosConsiderSummerRatio):
self._OPVCoverageRatiosConsiderSummerRatio = OPVCoverageRatiosConsiderSummerRatio
def setPlantGrowthModel(self, plantGrowthModel):
self._plantGrowthModel = plantGrowthModel
def getPlantGrowthModel(self):
return self._plantGrowthModel
@property
def shootFreshMassList(self):
return self._shootFreshMassList
@shootFreshMassList.setter
def shootFreshMassList(self, shootFreshMassList):
self._shootFreshMassList = shootFreshMassList
def setCultivationDaysperHarvest(self, cultivationDaysperHarvest):
self._cultivationDaysperHarvest = cultivationDaysperHarvest
def getCultivationDaysperHarvest(self):
return self._cultivationDaysperHarvest
def setHasShadingCurtain(self, hasShadingCurtain):
self._hasShadingCurtain = hasShadingCurtain
def getHasShadingCurtain(self):
return self.hasShadingCurtain
def setShadingCurtainDeployPPFD(self, shadingCurtainDeployPPFD):
self._shadingCurtainDeployPPFD = shadingCurtainDeployPPFD
def getShadingCurtainDeployPPFD(self):
return self._shadingCurtainDeployPPFD
def setProfitVSOPVCoverageData(self,profitVSOPVCoverageData):
self._profitVSOPVCoverageData = profitVSOPVCoverageData
def getProfitVSOPVCoverageData(self):
return self._profitVSOPVCoverageData
def setMonthlyElectricitySalesperArea(self, monthlyElectricitySalesperArea):
self._monthlyElectricitySalesperArea = monthlyElectricitySalesperArea
def getMonthlyElectricitySalesperArea(self):
return self._monthlyElectricitySalesperArea
def setMonthlyElectricitySalesperAreaEastRoof(self, monthlyElectricitySalesperAreaEastRoof):
self._monthlyElectricitySalesperAreaEastRoof = monthlyElectricitySalesperAreaEastRoof
def getMonthlyElectricitySalesperAreaEastRoof(self):
return self._monthlyElectricitySalesperAreaEastRoof
def setMonthlyElectricitySalesperAreaWestRoof(self, monthlyElectricitySalesperAreaWestRoof):
self._monthlyElectricitySalesperAreaWestRoof = monthlyElectricitySalesperAreaWestRoof
def getMonthlyElectricitySalesperAreaWestRoof(self):
return self._monthlyElectricitySalesperAreaWestRoof
@property
def totalElectricitySalesPerMonth(self):
return self._totalElectricitySalesPerMonth
@totalElectricitySalesPerMonth.setter
def totalElectricitySalesPerMonth(self, totalElectricitySalesPerMonth):
self._totalElectricitySalesPerMonth = totalElectricitySalesPerMonth
@property
def totalElectricitySalesPerAreaPerMonth(self):
return self._totalElectricitySalesPerAreaPerMonth
@totalElectricitySalesPerAreaPerMonth.setter
def totalElectricitySalesPerAreaPerMonth(self, totalElectricitySalesPerAreaPerMonth):
self._totalElectricitySalesPerAreaPerMonth = totalElectricitySalesPerAreaPerMonth
@property
def totalElectricitySales(self):
return self._totalElectricitySales
@totalElectricitySales.setter
def totalElectricitySales(self, totalElectricitySales):
self._totalElectricitySales = totalElectricitySales
def setOPVCostUSDForDepreciationPerOPVArea(self, oPVCostUSDForDepreciationPerOPVArea):
self._oPVCostUSDForDepreciationPerOPVArea = oPVCostUSDForDepreciationPerOPVArea
def getOPVCostUSDForDepreciationPerOPVArea(self):
return self._oPVCostUSDForDepreciationPerOPVArea
@property
def totalOPVCostUSDForDepreciation(self):
return self._totalOPVCostUSDForDepreciation
@totalOPVCostUSDForDepreciation.setter
def totalOPVCostUSDForDepreciation(self, totalOPVCostUSDForDepreciation):
self._totalOPVCostUSDForDepreciation = totalOPVCostUSDForDepreciation
@property
def totalOPVCostUSDForDepreciationPerGHFloorArea(self):
return self._totalOPVCostUSDForDepreciationPerGHFloorArea
@totalOPVCostUSDForDepreciationPerGHFloorArea.setter
def totalOPVCostUSDForDepreciationPerGHFloorArea(self, totalOPVCostUSDForDepreciationPerGHFloorArea):
self._totalOPVCostUSDForDepreciationPerGHFloorArea = totalOPVCostUSDForDepreciationPerGHFloorArea
@property
def electricityProductionProfit(self):
return self._electricityProductionProfit
@electricityProductionProfit.setter
def electricityProductionProfit(self, electricityProductionProfit):
self._electricityProductionProfit = electricityProductionProfit
@property
def electricityProductionProfitPerGHFloorArea(self):
return self._electricityProductionProfitPerGHFloorArea
@electricityProductionProfitPerGHFloorArea.setter
def electricityProductionProfitPerGHFloorArea(self, electricityProductionProfitPerGHFloorArea):
self._electricityProductionProfitPerGHFloorArea = electricityProductionProfitPerGHFloorArea
######################## measured solar radiation to OPV start ########################
def setDirectSolarRadiationToOPVEastDirection(self, directSolarRadiationToOPVEastDirection):
self._directSolarRadiationToOPVEastDirection = directSolarRadiationToOPVEastDirection
def getDirectSolarRadiationToOPVEastDirection(self):
return self._directSolarRadiationToOPVEastDirection
def setDirectSolarRadiationToOPVWestDirection(self, directSolarRadiationToOPVWestDirection):
self._directSolarRadiationToOPVWestDirection = directSolarRadiationToOPVWestDirection
def getDirectSolarRadiationToOPVWestDirection(self):
return self._directSolarRadiationToOPVWestDirection
def setDiffuseSolarRadiationToOPV(self, diffuseSolarRadiationToOPV):
self._diffuseSolarRadiationToOPV = diffuseSolarRadiationToOPV
def getDiffuseSolarRadiationToOPV(self):
return self._diffuseSolarRadiationToOPV
def setAlbedoSolarRadiationToOPV(self, albedoSolarRadiationToOPV):
self._albedoSolarRadiationToOPV = albedoSolarRadiationToOPV
def getAlbedoSolarRadiationToOPV(self):
return self._albedoSolarRadiationToOPV
######################## measured solar radiation to OPV end ########################
######################## estimated solar radiation to OPV start ########################
def setEstimatedDirectSolarRadiationToOPVEastDirection(self, estimatedDirectSolarRadiationToOPVEastDirection):
self._estimatedDirectSolarRadiationToOPVEastDirection = estimatedDirectSolarRadiationToOPVEastDirection
def getEstimatedDirectSolarRadiationToOPVEastDirection(self):
return self._estimatedDirectSolarRadiationToOPVEastDirection
def setEstimatedDirectSolarRadiationToOPVWestDirection(self, estimatedDirectSolarRadiationToOPVWestDirection):
self._estimatedDirectSolarRadiationToOPVWestDirection = estimatedDirectSolarRadiationToOPVWestDirection
def getEstimatedDirectSolarRadiationToOPVWestDirection(self):
return self._estimatedDirectSolarRadiationToOPVWestDirection
def setEstimatedDiffuseSolarRadiationToOPV(self, estimatedDiffuseSolarRadiationToOPV):
self._albedoSolarRadiationToOPV = estimatedDiffuseSolarRadiationToOPV
def getEstimatedDiffuseSolarRadiationToOPV(self):
return self._estimatedDiffuseSolarRadiationToOPV
def setEstimatedAlbedoSolarRadiationToOPV(self, estimatedAlbedoSolarRadiationToOPV):
self._estimatedAlbedoSolarRadiationToOPV = estimatedAlbedoSolarRadiationToOPV
def getEstimatedAlbedoSolarRadiationToOPV(self):
return self._estimatedAlbedoSolarRadiationToOPV
######################## estimated solar radiation to OPV end ########################
def setHourlyInnerLightIntensityPPFDThroughGlazing(self, hourlyInnerLightIntensityPPFDThroughGlazing):
self._hourlyInnerLightIntensityPPFDThroughGlazing = hourlyInnerLightIntensityPPFDThroughGlazing
def getHourlyInnerLightIntensityPPFDThroughGlazing(self):
return self._hourlyInnerLightIntensityPPFDThroughGlazing
def setHourlyInnerLightIntensityPPFDThroughInnerStructure(self, hourlyInnerLightIntensityPPFDThroughInnerStructure):
self._hourlyInnerLightIntensityPPFDThroughInnerStructure = hourlyInnerLightIntensityPPFDThroughInnerStructure
def getHourlyInnerLightIntensityPPFDThroughInnerStructure(self):
return self._hourlyInnerLightIntensityPPFDThroughInnerStructure
def setDirectPPFDToOPVEastDirection(self, directPPFDToOPVEastDirection):
self._directPPFDToOPVEastDirection = directPPFDToOPVEastDirection
def getDirectPPFDToOPVEastDirection(self):
return self._directPPFDToOPVEastDirection
def setDirectPPFDToOPVWestDirection(self, directPPFDToOPVWestDirection):
self._directPPFDToOPVWestDirection = directPPFDToOPVWestDirection
def getDirectPPFDToOPVWestDirection(self):
return self._directPPFDToOPVWestDirection
def setDiffusePPFDToOPV(self, diffusePPFDToOPV):
self._diffusePPFDToOPV = diffusePPFDToOPV
def getDiffusePPFDToOPV(self):
return self._diffusePPFDToOPV
def setGroundReflectedPPFDToOPV(self, groundReflectedPPFDToOPV):
self._groundReflectedPPFDToOPV = groundReflectedPPFDToOPV
def getGroundReflectedPPFDToOPV(self):
return self._groundReflectedPPFDToOPV
# def setTotalDLItoPlantsBaselineShadingCuratin(self, totalDLItoPlantsBaselineShadingCuratin):
# self._totalDLItoPlantsBaselineShadingCuratin = totalDLItoPlantsBaselineShadingCuratin
# def getTotalDLItoPlantsBaselineShadingCuratin(self):
# return self._totalDLItoPlantsBaselineShadingCuratin
def setDirectDLIToOPVEastDirection(self, directDLIToOPVEastDirection):
self._directDLIToOPVEastDirection = directDLIToOPVEastDirection
def getDirectDLIToOPVEastDirection(self):
return self._directDLIToOPVEastDirection
def setDirectDLIToOPVWestDirection(self, directDLIToOPVWestDirection):
self._directDLIToOPVWestDirection = directDLIToOPVWestDirection
def getDirectDLIToOPVWestDirection(self):
return self._directDLIToOPVWestDirection
def setDiffuseDLIToOPV(self, diffuseDLIToOPV):
self._diffuseDLIToOPV = diffuseDLIToOPV
def getDiffuseDLIToOPV(self):
return self._diffuseDLIToOPV
def setGroundReflectedDLIToOPV(self, groundReflectedDLIToOPV):
self._groundReflectedDLIToOPV = groundReflectedDLIToOPV
def getGroundReflectedDLIToOPV(self):
return self._groundReflectedDLIToOPV
##############################solar irradiance to multi span roof start##############################
def setHourlyDirectSolarRadiationAfterMultiSpanRoof(self, hourlyDirectSolarRadiationAfterMultiSpanRoof):
self._hourlyDirectSolarRadiationAfterMultiSpanRoof = hourlyDirectSolarRadiationAfterMultiSpanRoof
def getHourlyDirectSolarRadiationAfterMultiSpanRoof(self):
return self._hourlyDirectSolarRadiationAfterMultiSpanRoof
def setHourlyDiffuseSolarRadiationAfterMultiSpanRoof(self, hourlyDiffuseSolarRadiationAfterMultiSpanRoof):
self._hourlyDiffuseSolarRadiationAfterMultiSpanRoof = hourlyDiffuseSolarRadiationAfterMultiSpanRoof
def getHourlyDiffuseSolarRadiationAfterMultiSpanRoof(self):
return self._hourlyDiffuseSolarRadiationAfterMultiSpanRoof
def setGroundReflectedRadiationAfterMultiSpanRoof(self, groundReflectedRadiationAfterMultiSpanRoof):
self._groundReflectedRadiationAfterMultiSpanRoof = groundReflectedRadiationAfterMultiSpanRoof
def getGroundReflectedRadiationAfterMultiSpanRoof(self):
return self._groundReflectedRadiationAfterMultiSpanRoof
def setHourlyDirectPPFDAfterMultiSpanRoof(self, hourlyDirectPPFDAfterMultiSpanRoof):
self._hourlyDirectPPFDAfterMultiSpanRoof = hourlyDirectPPFDAfterMultiSpanRoof
def getHourlyDirectPPFDAfterMultiSpanRoof(self):
return self._hourlyDirectPPFDAfterMultiSpanRoof
def setHourlyDiffusePPFDAfterMultiSpanRoof(self, hourlyDiffusePPFDAfterMultiSpanRoof):
self._hourlyDiffusePPFDAfterMultiSpanRoof = hourlyDiffusePPFDAfterMultiSpanRoof
def getHourlyDiffusePPFDAfterMultiSpanRoof(self):
return self._hourlyDiffusePPFDAfterMultiSpanRoof
def setGroundReflectedPPFDAfterMultiSpanRoof(self, groundReflectedPPFDAfterMultiSpanRoof):
self._groundReflectedPPFDAfterMultiSpanRoof = groundReflectedPPFDAfterMultiSpanRoof
def getGroundReflectedPPFDAfterMultiSpanRoof(self):
return self._groundReflectedPPFDAfterMultiSpanRoof
##############################solar irradiance to multi span roof end##############################
def setShootFreshMassList(self, shootFreshMassList):
self._shootFreshMassList = shootFreshMassList
def getShootFreshMassList(self):
return self._shootFreshMassList
def setUnitDailyFreshWeightIncrease(self, setUnitDailyFreshWeightIncrease):
self._unitDailyFreshWeightIncrease = setUnitDailyFreshWeightIncrease
def getUnitDailyFreshWeightIncrease(self):
return self._unitDailyFreshWeightIncrease
def setAccumulatedUnitDailyFreshWeightIncrease(self, accumulatedUnitDailyFreshWeightIncrease):
self._accumulatedUnitDailyFreshWeightIncrease = accumulatedUnitDailyFreshWeightIncrease
def getAccumulatedUnitDailyFreshWeightIncrease(self):
return self._accumulatedUnitDailyFreshWeightIncrease
def setUnitDailyHarvestedFreshWeight(self, unitDailyHarvestedFreshWeight):
self._unitDailyHarvestedFreshWeight = unitDailyHarvestedFreshWeight
def getUnitDailyHarvestedFreshWeight(self):
return self._unitDailyHarvestedFreshWeight
@property
def totalPlantSales(self):
return self._totalPlantSales
@totalPlantSales.setter
def totalPlantSales(self, totalPlantSales):
self._totalPlantSales = totalPlantSales
@property
def totalPlantSalesperSquareMeter(self):
return self._totalPlantSalesperSquareMeter
@totalPlantSalesperSquareMeter.setter
def totalPlantSalesperSquareMeter(self, totalPlantSalesperSquareMeter):
self._totalPlantSalesperSquareMeter = totalPlantSalesperSquareMeter
@property
def totalPlantSalesPerGHFloorArea(self):
return self._totalPlantSalesPerGHFloorArea
@totalPlantSalesPerGHFloorArea.setter
def totalPlantSalesPerGHFloorArea(self, totalPlantSalesPerGHFloorArea):
self._totalPlantSalesPerGHFloorArea = totalPlantSalesPerGHFloorArea
@property
def Q_v(self):
return self._Q_v
@Q_v.setter
def Q_v(self, Q_v):
self._Q_v = Q_v
@property
def Q_sr(self):
return self._Q_sr
@Q_sr.setter
def Q_sr(self, Q_sr):
self._Q_sr = Q_sr
@property
def Q_lh(self):
return self._Q_lh
@Q_lh.setter
def Q_lh(self, Q_lh):
self._Q_lh = Q_lh
@property
def Q_sh(self):
return self._Q_sh
@Q_sh.setter
def Q_sh(self, Q_sh):
self._Q_sh = Q_sh
@property
def Q_lw(self):
return self._Q_lw
@Q_lw.setter
def Q_lw(self, Q_lw):
self._Q_lw = Q_lw
@property
def Q_vW(self):
return self._Q_vW
@Q_vW.setter
def Q_vW(self, Q_vW):
self._Q_vW = Q_vW
@property
def Q_srW(self):
return self._Q_srW
@Q_srW.setter
def Q_srW(self, Q_srW):
self._Q_srW = Q_srW
@property
def Q_lhW(self):
return self._Q_lhW
@Q_lhW.setter
def Q_lhW(self, Q_lhW):
self._Q_lhW = Q_lhW
@property
def Q_shW(self):
return self._Q_shW
@Q_shW.setter
def Q_shW(self, Q_shW):
self._Q_shW = Q_shW
@property
def Q_lwW(self):
return self._Q_lwW
@Q_lwW.setter
def Q_lwW(self, Q_lwW):
self._Q_lwW = Q_lwW
@property
def monthlyRequiredGHHeatingEnergyForPlants(self):
return self._monthlyRequiredGHHeatingEnergyForPlants
@monthlyRequiredGHHeatingEnergyForPlants.setter
def monthlyRequiredGHHeatingEnergyForPlants(self, monthlyRequiredGHHeatingEnergyForPlants):
self._monthlyRequiredGHHeatingEnergyForPlants = monthlyRequiredGHHeatingEnergyForPlants
@property
def totalHeatingCostForPlants(self):
return self._totalHeatingCostForPlants
@totalHeatingCostForPlants.setter
def totalHeatingCostForPlants(self, totalHeatingCostForPlants):
self._totalHeatingCostForPlants = totalHeatingCostForPlants
@property
def totalLaborCost(self):
return self._totalLaborCost
@totalLaborCost.setter
def totalLaborCost(self, totalLaborCost):
self._totalLaborCost = totalLaborCost
@property
def totalLaborCostPerGHFloorArea(self):
return self._totalLaborCostPerGHFloorArea
@totalLaborCostPerGHFloorArea.setter
def totalLaborCostPerGHFloorArea(self, totalLaborCostPerGHFloorArea):
self._totalLaborCostPerGHFloorArea = totalLaborCostPerGHFloorArea
@property
def totalPlantProductionCost(self):
return self._totalPlantProductionCost
@totalPlantProductionCost.setter
def totalPlantProductionCost(self, totalPlantProductionCost):
self._totalPlantProductionCost = totalPlantProductionCost
@property
def totalPlantProductionCostPerGHFloorArea(self):
return self._totalPlantProductionCostPerGHFloorArea
@totalPlantProductionCostPerGHFloorArea.setter
def totalPlantProductionCostPerGHFloorArea(self, totalPlantProductionCostPerGHFloorArea):
self._totalPlantProductionCostPerGHFloorArea = totalPlantProductionCostPerGHFloorArea
@property
def totalPlantProfit(self):
return self._totalPlantProfit
@totalPlantProfit.setter
def totalPlantProfit(self, totalPlantProfit):
self._totalPlantProfit = totalPlantProfit
@property
def totalPlantProfitPerGHFloorArea(self):
return self._totalPlantProfitPerGHFloorArea
@totalPlantProfitPerGHFloorArea.setter
def totalPlantProfitPerGHFloorArea(self, totalPlantProfitPerGHFloorArea):
self._totalPlantProfitPerGHFloorArea = totalPlantProfitPerGHFloorArea
@property
def economicProfit(self):
return self._economicProfit
@economicProfit.setter
def economicProfit(self, economicProfit):
self._economicProfit = economicProfit
@property
def economicProfitPerGHFloorArea(self):
return self._economicProfitPerGHFloorArea
@economicProfitPerGHFloorArea.setter
def economicProfitPerGHFloorArea(self, economicProfitPerGHFloorArea):
self._economicProfitPerGHFloorArea = economicProfitPerGHFloorArea
def setAverageDLIonEachCycle(self, averageDLIonEachCycle):
self._averageDLIonEachCycle = averageDLIonEachCycle
def getAverageDLIonEachCycle(self):
return self._averageDLIonEachCycle
def setYear(self, year):
self._year = year
def getYear(self):
return self._year
def setMonth(self, month):
self._month = month
def getMonth(self):
return self._month
def setDay(self, day):
self._day = day
def getDay(self):
return self._day
def setHour(self, hour):
self._hour = hour
def getHour(self):
return self._hour
######################### imported data start #########################
def setImportedHourlyHorizontalDirectSolarRadiation(self, importedHourlyHorizontalDirectSolarRadiation):
self._importedHourlyHorizontalDirectSolarRadiation = importedHourlyHorizontalDirectSolarRadiation
def getImportedHourlyHorizontalDirectSolarRadiation(self):
return self._importedHourlyHorizontalDirectSolarRadiation
def setImportedHourlyHorizontalDiffuseSolarRadiation(self, importedHourlyHorizontalDiffuseSolarRadiation):
self._importedHourlyHorizontalDiffuseSolarRadiation = importedHourlyHorizontalDiffuseSolarRadiation
def getImportedHourlyHorizontalDiffuseSolarRadiation(self):
return self._importedHourlyHorizontalDiffuseSolarRadiation
def setImportedHourlyHorizontalTotalBeamMeterBodyTemperature(self, importedHourlyHorizontalTotalBeamMeterBodyTemperature):
self._importedHourlyHorizontalTotalBeamMeterBodyTemperature = importedHourlyHorizontalTotalBeamMeterBodyTemperature
def getImportedHourlyHorizontalTotalBeamMeterBodyTemperature(self):
return self._importedHourlyHorizontalTotalBeamMeterBodyTemperature
def setImportedHourlyAirTemperature(self, importedHourlyAirTemperature):
self._importedHourlyAirTemperature = importedHourlyAirTemperature
def getImportedHourlyAirTemperature(self):
return self._importedHourlyAirTemperature
@property
def hourlyRelativeHumidity(self):
return self._hourlyRelativeHumidity
@hourlyRelativeHumidity.setter
def hourlyRelativeHumidity(self, hourlyRelativeHumidity):
self._hourlyRelativeHumidity = hourlyRelativeHumidity
######################### imported data end #########################
######################### solar radiation to tilted OPV (roof) start #########################
@property
def dailyWhopvoutperAreaEastRoof(self):
return self._dailyWhopvoutperAreaEastRoof
@dailyWhopvoutperAreaEastRoof.setter
def dailyWhopvoutperAreaEastRoof(self, dailyWhopvoutperAreaEastRoof):
self._dailyWhopvoutperAreaEastRoof = dailyWhopvoutperAreaEastRoof
@property
def dailyWhopvoutperAreaWestRoof(self):
return self._dailyWhopvoutperAreaWestRoof
@dailyWhopvoutperAreaWestRoof.setter
def dailyWhopvoutperAreaWestRoof(self, dailyWhopvoutperAreaWestRoof):
self._dailyWhopvoutperAreaWestRoof = dailyWhopvoutperAreaWestRoof
@property
def dailykWhopvoutperAreaEastRoof(self):
return self._dailykWhopvoutperAreaEastRoof
@dailykWhopvoutperAreaEastRoof.setter
def dailykWhopvoutperAreaEastRoof(self, dailykWhopvoutperAreaEastRoof):
self._dailykWhopvoutperAreaEastRoof = dailykWhopvoutperAreaEastRoof
@property
def dailykWhopvoutperAreaWestRoof(self):
return self._dailykWhopvoutperAreaWestRoof
@dailykWhopvoutperAreaWestRoof.setter
def dailykWhopvoutperAreaWestRoof(self, dailykWhopvoutperAreaWestRoof):
self._dailykWhopvoutperAreaWestRoof = dailykWhopvoutperAreaWestRoof
@property
def totalkWhopvoutPerday(self):
return self._totalkWhopvoutPerday
@totalkWhopvoutPerday.setter
def totalkWhopvoutPerday(self, totalkWhopvoutPerday):
self._totalkWhopvoutPerday = totalkWhopvoutPerday
@property
def monthlyElectricityRetailPrice(self):
return self._monthlyElectricityRetailPrice
@monthlyElectricityRetailPrice.setter
def monthlyElectricityRetailPrice(self, monthlyElectricityRetailPrice):
self._monthlyElectricityRetailPrice = monthlyElectricityRetailPrice
@property
def totalkWhopvoutPerAreaPerday(self):
return self._totalkWhopvoutPerAreaPerday
@totalkWhopvoutPerAreaPerday.setter
def totalkWhopvoutPerAreaPerday(self, totalkWhopvoutPerAreaPerday):
self._totalkWhopvoutPerAreaPerday = totalkWhopvoutPerAreaPerday
######################### solar radiation to tilted OPV (roof) end #########################
def setIfGrowForSummerPeriod(self, ifGrowForSummerPeriod):
self._ifGrowForSummerPeriod = ifGrowForSummerPeriod
def getIfGrowForSummerPeriod(self):
return self._ifGrowForSummerPeriod
def setEstimateSolarRadiationMode(self, estimateSolarRadiationMode):
self._estimateSolarRadiationMode = estimateSolarRadiationMode
def getEstimateSolarRadiationMode(self):
return self._estimateSolarRadiationMode
def setIfHasShadingCurtain(self, ifHasShadingCurtain):
self._ifHasShadingCurtain = ifHasShadingCurtain
def getIfHasShadingCurtain(self):
return self._ifHasShadingCurtain
############################################ angles start################
@property
def hourlySolarIncidenceAngleEastDirection(self):
return self._hourlySolarIncidenceAngleEastDirection
@hourlySolarIncidenceAngleEastDirection.setter
def hourlySolarIncidenceAngleEastDirection(self, hourlySolarIncidenceAngleEastDirection):
self._hourlySolarIncidenceAngleEastDirection = hourlySolarIncidenceAngleEastDirection
@property
def hourlySolarIncidenceAngleWestDirection(self):
return self._hourlySolarIncidenceAngleWestDirection
@hourlySolarIncidenceAngleWestDirection.setter
def hourlySolarIncidenceAngleWestDirection(self, hourlySolarIncidenceAngleWestDirection):
self._hourlySolarIncidenceAngleWestDirection = hourlySolarIncidenceAngleWestDirection
@property
def hourlySolarAltitudeAngle(self):
return self._hourlySolarAltitudeAngle
@hourlySolarAltitudeAngle.setter
def hourlySolarAltitudeAngle(self, hourlySolarAltitudeAngle):
self._hourlySolarAltitudeAngle = hourlySolarAltitudeAngle
@property
def hourlySolarAzimuthAngle(self):
return self._hourlySolarAzimuthAngle
@hourlySolarAzimuthAngle.setter
def hourlySolarAzimuthAngle(self, hourlySolarAzimuthAngle):
self._hourlySolarAzimuthAngle = hourlySolarAzimuthAngle
@property
def hourlyModuleAzimuthAngleEast(self):
return self._hourlyModuleAzimuthAngleEast
@hourlyModuleAzimuthAngleEast.setter
def hourlyModuleAzimuthAngleEast(self, hourlyModuleAzimuthAngleEast):
self._hourlyModuleAzimuthAngleEast = hourlyModuleAzimuthAngleEast
@property
def hourlyModuleAzimuthAngleWest(self):
return self._hourlyModuleAzimuthAngleWest
@hourlyModuleAzimuthAngleWest.setter
def hourlyModuleAzimuthAngleWest(self, hourlyModuleAzimuthAngleWest):
self._hourlyModuleAzimuthAngleWest = hourlyModuleAzimuthAngleWest
############################################ angles end################
##############################solar irradiance to plants start##############################
@property
def directSolarIrradianceBeforeShadingCurtain(self):
return self._directSolarIrradianceBeforeShadingCurtain
@directSolarIrradianceBeforeShadingCurtain.setter
def directSolarIrradianceBeforeShadingCurtain(self, directSolarIrradianceBeforeShadingCurtain):
self._directSolarIrradianceBeforeShadingCurtain = directSolarIrradianceBeforeShadingCurtain
@property
def diffuseSolarIrradianceBeforeShadingCurtain(self):
return self._diffuseSolarIrradianceBeforeShadingCurtain
@diffuseSolarIrradianceBeforeShadingCurtain.setter
def diffuseSolarIrradianceBeforeShadingCurtain(self, diffuseSolarIrradianceBeforeShadingCurtain):
self._diffuseSolarIrradianceBeforeShadingCurtain = diffuseSolarIrradianceBeforeShadingCurtain
@property
def directSolarIrradianceToPlants(self):
return self._directSolarIrradianceToPlants
@directSolarIrradianceToPlants.setter
def directSolarIrradianceToPlants(self, directSolarIrradianceToPlants):
self._directSolarIrradianceToPlants = directSolarIrradianceToPlants
@property
def diffuseSolarIrradianceToPlants(self):
return self._diffuseSolarIrradianceToPlants
@diffuseSolarIrradianceToPlants.setter
def diffuseSolarIrradianceToPlants(self, diffuseSolarIrradianceToPlants):
self._diffuseSolarIrradianceToPlants = diffuseSolarIrradianceToPlants
@property
def transmittanceThroughShadingCurtainChangingEachMonth(self):
return self._transmittanceThroughShadingCurtainChangingEachMonth
@transmittanceThroughShadingCurtainChangingEachMonth.setter
def transmittanceThroughShadingCurtainChangingEachMonth(self, transmittanceThroughShadingCurtainChangingEachMonth):
self._transmittanceThroughShadingCurtainChangingEachMonth = transmittanceThroughShadingCurtainChangingEachMonth
@property
def directPPFDToPlants(self):
return self._directPPFDToPlants
@directPPFDToPlants.setter
def directPPFDToPlants(self, directPPFDToPlants):
self._directPPFDToPlants = directPPFDToPlants
@property
def diffusePPFDToPlants(self):
return self._diffusePPFDToPlants
@diffusePPFDToPlants.setter
def diffusePPFDToPlants(self, diffusePPFDToPlants):
self._diffusePPFDToPlants = diffusePPFDToPlants
@property
def directDLIToPlants(self):
return self._directDLIToPlants
@directDLIToPlants.setter
def directDLIToPlants(self, directDLIToPlants):
self._directDLIToPlants = directDLIToPlants
@property
def diffuseDLIToPlants(self):
return self._diffuseDLIToPlants
@diffuseDLIToPlants.setter
def diffuseDLIToPlants(self, diffuseDLIToPlants):
self._diffuseDLIToPlants = diffuseDLIToPlants
@property
def totalDLItoPlants(self):
return self._totalDLItoPlants
@totalDLItoPlants.setter
def totalDLItoPlants(self, totalDLItoPlants):
self._totalDLItoPlants = totalDLItoPlants
##############################solar irradiance to plants end##############################
@property
def hourlyDayOrNightFlag(self):
return self._hourlyDayOrNightFlag
@hourlyDayOrNightFlag.setter
def hourlyDayOrNightFlag(self, hourlyDayOrNightFlag):
self._hourlyDayOrNightFlag = hourlyDayOrNightFlag
##############################imported data start##############################
@property
def hourlyHorizontalDirectOuterSolarIrradiance(self):
return self._hourlyHorizontalDirectOuterSolarIrradiance
@hourlyHorizontalDirectOuterSolarIrradiance.setter
def hourlyHorizontalDirectOuterSolarIrradiance(self, hourlyHorizontalDirectOuterSolarIrradiance):
self._hourlyHorizontalDirectOuterSolarIrradiance = hourlyHorizontalDirectOuterSolarIrradiance
@property
def hourlyHorizontalDiffuseOuterSolarIrradiance(self):
return self._hourlyHorizontalDiffuseOuterSolarIrradiance
@hourlyHorizontalDiffuseOuterSolarIrradiance.setter
def hourlyHorizontalDiffuseOuterSolarIrradiance(self, hourlyHorizontalDiffuseOuterSolarIrradiance):
self._hourlyHorizontalDiffuseOuterSolarIrradiance = hourlyHorizontalDiffuseOuterSolarIrradiance
@property
def hourlyHorizontalTotalOuterSolarIrradiance(self):
return self._hourlyHorizontalTotalOuterSolarIrradiance
@hourlyHorizontalTotalOuterSolarIrradiance.setter
def hourlyHorizontalTotalOuterSolarIrradiance(self, hourlyHorizontalTotalOuterSolarIrradiance):
self._hourlyHorizontalTotalOuterSolarIrradiance = hourlyHorizontalTotalOuterSolarIrradiance
@property
def hourlyHorizontalTotalBeamMeterBodyTemperature(self):
return self._hourlyHorizontalTotalBeamMeterBodyTemperature
@hourlyHorizontalTotalBeamMeterBodyTemperature.setter
def hourlyHorizontalTotalBeamMeterBodyTemperature(self, hourlyHorizontalTotalBeamMeterBodyTemperature):
self._hourlyHorizontalTotalBeamMeterBodyTemperature = hourlyHorizontalTotalBeamMeterBodyTemperature
@property
def hourlyAirTemperature(self):
return self._hourlyAirTemperature
@hourlyAirTemperature.setter
def hourlyAirTemperature(self, hourlyAirTemperature):
self._hourlyAirTemperature = hourlyAirTemperature
##############################imported data end##############################
##############################multispan roof transmittance start##############################
@property
def T_matForPerpendicularIrrEastOrNorthFacingRoof(self):
return self._T_matForPerpendicularIrrEastOrNorthFacingRoof
@T_matForPerpendicularIrrEastOrNorthFacingRoof.setter
def T_matForPerpendicularIrrEastOrNorthFacingRoof(self, T_matForPerpendicularIrrEastOrNorthFacingRoof):
self._T_matForPerpendicularIrrEastOrNorthFacingRoof = T_matForPerpendicularIrrEastOrNorthFacingRoof
@property
def T_matForPerpendicularIrrWestOrSouthFacingRoof(self):
return self._T_matForPerpendicularIrrWestOrSouthFacingRoof
@T_matForPerpendicularIrrWestOrSouthFacingRoof.setter
def T_matForPerpendicularIrrWestOrSouthFacingRoof(self, T_matForPerpendicularIrrWestOrSouthFacingRoof):
self._T_matForPerpendicularIrrWestOrSouthFacingRoof = T_matForPerpendicularIrrWestOrSouthFacingRoof
@property
def integratedT_mat(self):
return self._integratedT_mat
@integratedT_mat.setter
def integratedT_mat(self, integratedT_mat):
self._integratedT_mat = integratedT_mat
##############################multispan roof transmittance end##############################
@property
def directHorizontalSolarRadiation(self):
return self._directHorizontalSolarRadiation
@directHorizontalSolarRadiation.setter
def directHorizontalSolarRadiation(self, directHorizontalSolarRadiation):
self._directHorizontalSolarRadiation = directHorizontalSolarRadiation
@property
def diffuseHorizontalSolarRadiation(self):
return self._diffuseHorizontalSolarRadiation
@diffuseHorizontalSolarRadiation.setter
def diffuseHorizontalSolarRadiation(self, diffuseHorizontalSolarRadiation):
self._diffuseHorizontalSolarRadiation = diffuseHorizontalSolarRadiation
@property
def totalHorizontalSolarRadiation(self):
return self._totalHorizontalSolarRadiation
@totalHorizontalSolarRadiation.setter
def totalHorizontalSolarRadiation(self, totalHorizontalSolarRadiation):
self._totalHorizontalSolarRadiation = totalHorizontalSolarRadiation
##############################plant weights (growth)start ##############################
@property
def LeafAreaIndex_J_VanHenten1994(self):
return self._LeafAreaIndex_J_VanHenten1994
@LeafAreaIndex_J_VanHenten1994.setter
def LeafAreaIndex_J_VanHenten1994(self, LeafAreaIndex_J_VanHenten1994):
self._LeafAreaIndex_J_VanHenten1994 = LeafAreaIndex_J_VanHenten1994
@property
def summerPeriodFlagArray(self):
return self._summerPeriodFlagArray
@summerPeriodFlagArray.setter
def summerPeriodFlagArray(self, summerPeriodFlagArray):
self._summerPeriodFlagArray = summerPeriodFlagArray
@property
def dailyShootFreshMass(self):
return self._dailyShootFreshMass
@dailyShootFreshMass.setter
def dailyShootFreshMass(self, dailyShootFreshMass):
self._dailyShootFreshMass = dailyShootFreshMass
@property
def dailyUnitDailyFreshWeightIncrease(self):
return self._dailyUnitDailyFreshWeightIncrease
@dailyUnitDailyFreshWeightIncrease.setter
def dailyUnitDailyFreshWeightIncrease(self, dailyUnitDailyFreshWeightIncrease):
self._dailyUnitDailyFreshWeightIncrease = dailyUnitDailyFreshWeightIncrease
@property
def dailyAccumulatedUnitDailyFreshWeightIncrease(self):
return self._dailyAccumulatedUnitDailyFreshWeightIncrease
@dailyAccumulatedUnitDailyFreshWeightIncrease.setter
def dailyAccumulatedUnitDailyFreshWeightIncrease(self, dailyAccumulatedUnitDailyFreshWeightIncrease):
self._dailyAccumulatedUnitDailyFreshWeightIncrease = dailyAccumulatedUnitDailyFreshWeightIncrease
@property
def dailyUnitHarvestedFreshWeight(self):
return self._dailyUnitHarvestedFreshWeight
@dailyUnitHarvestedFreshWeight.setter
def dailyUnitHarvestedFreshWeight(self, dailyUnitHarvestedFreshWeight):
self._dailyUnitHarvestedFreshWeight = dailyUnitHarvestedFreshWeight
@property
def shootFreshMassPerAreaKgPerDay(self):
return self._shootFreshMassPerAreaKgPerDay
@shootFreshMassPerAreaKgPerDay.setter
def shootFreshMassPerAreaKgPerDay(self, shootFreshMassPerAreaKgPerDay):
self._shootFreshMassPerAreaKgPerDay = shootFreshMassPerAreaKgPerDay
@property
def harvestedShootFreshMassPerAreaKgPerDay(self):
return self._harvestedShootFreshMassPerAreaKgPerDay
@harvestedShootFreshMassPerAreaKgPerDay.setter
def harvestedShootFreshMassPerAreaKgPerDay(self, harvestedShootFreshMassPerAreaKgPerDay):
self._harvestedShootFreshMassPerAreaKgPerDay = harvestedShootFreshMassPerAreaKgPerDay
@property
def totalHarvestedShootFreshMass(self):
return self._totalHarvestedShootFreshMass
@totalHarvestedShootFreshMass.setter
def totalHarvestedShootFreshMass(self, totalHarvestedShootFreshMass):
self._totalHarvestedShootFreshMass = totalHarvestedShootFreshMass
@property
def GHSolarIrradianceValidationData(self):
return self._GHSolarIrradianceValidationData
@GHSolarIrradianceValidationData.setter
def GHSolarIrradianceValidationData(self, GHSolarIrradianceValidationData):
self._GHSolarIrradianceValidationData = GHSolarIrradianceValidationData
@property
def GHAirTemperatureValidationData(self):
return self._GHAirTemperatureValidationData
@GHAirTemperatureValidationData.setter
def GHAirTemperatureValidationData(self, GHAirTemperatureValidationData):
self._GHAirTemperatureValidationData = GHAirTemperatureValidationData
|
{"/OPVFilm.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/ShadingCurtain.py"], "/CropElectricityYieldProfitMINLP.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelS_Pearson1997.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/PlantGrowthModelS_Pearson1997Constant.py", "/Lettuce.py"], "/GreenhouseEnergyBalanceConstant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/Util.py": ["/CropElectricityYeildSimulatorConstant.py"], "/SolarIrradianceMultiSpanRoof.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/GreenhouseEnergyBalance.py": ["/Lettuce.py", "/CropElectricityYeildSimulatorConstant.py", "/GreenhouseEnergyBalanceConstant.py", "/Util.py"], "/SimulatorMain.py": ["/CropElectricityYeildSimulator1.py", "/Util.py", "/CropElectricityYeildSimulatorConstant.py"], "/CropElectricityYieldProfitRLShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/ShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelValidation.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulator1.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulatorDetail.py": ["/ShadingCurtain.py", "/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/Lettuce.py", "/PlantGrowthModelS_Pearson1997.py", "/SolarIrradianceMultiSpanRoof.py", "/GreenhouseEnergyBalance.py"], "/PlantGrowthModelS_Pearson1997Constant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/SimulatorClass.py": ["/CropElectricityYeildSimulatorConstant.py"], "/Lettuce.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/plantGrowthModelE_J_VanHenten.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py"]}
|
8,672
|
kensaku-okada/Greenhouse-with-OPV-film-Model
|
refs/heads/master
|
/Lettuce.py
|
# -*- coding: utf-8 -*-
#######################################################
# author :Kensaku Okada [kensakuokada@email.arizona.edu]
# create date : 12 Dec 2016
# last edit date: 14 Dec 2016
#######################################################
##########import package files##########
import os as os
import numpy as np
import matplotlib.pyplot as plt
import math
import CropElectricityYeildSimulatorConstant as constant
import Util as util
import datetime
import sys
from dateutil.relativedelta import relativedelta
#######################################################
def calcDailyInnerLightIntensityPPFDSum (HourlyInnerLightIntensityPPFD, productionCycle, cultivationDaysperHarvest, dayOfCultivation):
'''
sum all of the hourly light intensity for a specific cultivation day
param:HourlyInnerLightIntensityPPFD (μmol/m^2/s)
param:productionCycle (-)
param:cultivationDaysperHarvest (days)
param:dayOfCultivation (th day)
return:dailyInnerLightIntensityPPFD (μmol/m^2/s)
'''
#unit: (μmol/m^2/s)
dailyInnerLightIntensityPPFDsum = 0.0
# sum hourly solra radiation to the daily radiation
for hour in range (0, int(constant.hourperDay)):
dailyInnerLightIntensityPPFDsum += HourlyInnerLightIntensityPPFD[productionCycle * cultivationDaysperHarvest * int(constant.hourperDay) + dayOfCultivation * int(constant.hourperDay) + hour]
return dailyInnerLightIntensityPPFDsum
def calcDailyFreshWeightIncreaseByShimizuEtAl2008Revised(dailyInnerLightIntensityDLI, cultivationDaysperHarvest):
'''
calculate the fresh weight increase per day based on the revised model of Shimizu et at (2008): Hiroshi SHIMIZU, Megumi KUSHIDA and Wataru FUJINUMA, 2008, “A Growth Model for Leaf Lettuce under Greenhouse Environments”
The detail is described at ProjectB INFO 521
param:dailyInnerLightIntensityPPFD [μmol/m^2/s]
return: dailyFreshWeightIncrease[g/day]
'''
print("dailyInnerLightIntensityDLI:{}".format(dailyInnerLightIntensityDLI))
print("cultivationDaysperHarvest:{}".format(cultivationDaysperHarvest))
# average the light intensity for the cultivation by the period of lighting (photoperiod), which is assumed to be 14 hours.
dailyInnerLightIntensityDLIAverage = dailyInnerLightIntensityDLI / constant.photoperiod
# print "dailyInnerLightIntensityPPFDAverage:{}".format(dailyInnerLightIntensityPPFDAverage)
# the expected fresh weight at harvest. the unit is [g] coding Eq. 1-3-2-6 and 1-3-2-7
# the minimum final weight [g]
finalWeightperHarvest = 8.72
if dailyInnerLightIntensityDLIAverage < 1330:
# finalWeightperHarvest = 0.00000060 * HourlyinnerLightIntensityPPFDAveragePerproductionCycle**3 - 0.00162758 * HourlyinnerLightIntensityPPFDAveragePerproductionCycle**2 + 1.14477896 * HourlyinnerLightIntensityPPFDAveragePerproductionCycle - 46.39100859
finalWeightperHarvest = 0.00000060 * dailyInnerLightIntensityDLIAverage ** 3 - 0.00162758 * dailyInnerLightIntensityDLIAverage ** 2 + 1.14477896 * dailyInnerLightIntensityDLIAverage - 46.39100859
# the actual fresh weight of crop per harvest. the unit is g . Eq 1-3-2-4
dailyFreshWeightIncrease = (9.0977 * finalWeightperHarvest - 17.254) * (7.26 * 10 ** (-5)) ** math.e ** (
-0.05041 * cultivationDaysperHarvest)
return dailyFreshWeightIncrease
def calcUnitDailyFreshWeightBoth2003TaylorExpantionWithVaryingDLI(hourlyInnerPPFDToPlants, cultivationDaysperHarvest, cropElectricityYieldSimulator1 = None):
'''
calculate the unit fresh weight increase per day based on the revised model of Both (2003):
Both, A., 2003. Ten years of hydroponic lettuce research. Knowledgecenter.Illumitex.Com 18, 8.
param:hourlyInnerPPFDToPlants [μmol/m^2/s] per day
param:cultivationDaysperHarvest [days] per day
return: dailyFreshWeightIncrease[g/day]
return: hervestDay[days]: days after seeeding
'''
# print "dailyInnerLightIntensityDLI:{}".format(dailyInnerLightIntensityDLI)
# print "cultivationDaysperHarvest:{}".format(cultivationDaysperHarvest)
# convert PPFD to DLI
innerDLIToPlants = util.convertFromHourlyPPFDWholeDayToDLI(hourlyInnerPPFDToPlants)
# print "innerDLIToPlants:{}".format(innerDLIToPlants)
shootFreshMassList, unitDailyFreshWeightIncrease,accumulatedUnitDailyFreshWeightIncrease,unitHarvestedFreshWeight = \
calcUnitDailyFreshWeightBoth2003TaylorExpantionWithVaryingDLIDetail(innerDLIToPlants, cultivationDaysperHarvest, cropElectricityYieldSimulator1)
return shootFreshMassList, unitDailyFreshWeightIncrease,accumulatedUnitDailyFreshWeightIncrease,unitHarvestedFreshWeight
def calcUnitDailyFreshWeightBoth2003TaylorExpantionWithVaryingDLIDetail(innerDLIToPlants, cultivationDaysperHarvest, cropElectricityYieldSimulator1 = None):
'''
calculate the unit fresh weight increase per day based on the revised model of Both (2003):
Both, A., 2003. Ten years of hydroponic lettuce research. Knowledgecenter.Illumitex.Com 18, 8.
param:hourlyInnerPPFDToPlants [μmol/m^2/s] per day
param:cultivationDaysperHarvest [days] per day
return: dailyFreshWeightIncrease[g/day]
return: hervestDay[days]: days after seeeding
'''
# if you continue to grow plant during the summer period, then this is true
# ifGrowForSummerPeriod = cropElectricityYieldSimulator1.getIfGrowForSummerPeriod()
ifGrowForSummerPeriod = constant.ifGrowForSummerPeriod
# print ("ifGrowForSummerPeriod:{}".format(ifGrowForSummerPeriod))
# take date and time
year = cropElectricityYieldSimulator1.getYear()
month = cropElectricityYieldSimulator1.getMonth()
day = cropElectricityYieldSimulator1.getDay()
# change the number of array for DLI
yearEachDay = year[::24]
monthEachDay = month[::24]
dayEachDay = day[::24]
# define statistics for calculation
# daily unit plant weight on each cycle [g]
shootDryMassList = np.zeros(util.calcSimulationDaysInt())
# d_shootDryMassList = np.zeros(util.calcSimulationDaysInt())
# dd_shootDryMassList = np.zeros(util.calcSimulationDaysInt())
# ddd_shootDryMassList = np.zeros(util.calcSimulationDaysInt())
# daily increase in unit plant weight [g]
unitDailyFreshWeightIncrease = np.zeros(util.calcSimulationDaysInt())
# accumulated weight of daily increase in unit plant weight during the whole simulation days [g]
accumulatedUnitDailyFreshWeightIncrease = np.zeros(util.calcSimulationDaysInt())
# harvested daily unit plant weight [g]
unitHarvestedFreshWeight = np.zeros(util.calcSimulationDaysInt())
# the average light DLi of each cultivation cycle, the data is stored in the element on the harvest date.
# this data is used to calculate the penalty of plant yield by photo inhibition.
averageDLIonEachCycle = np.zeros(util.calcSimulationDaysInt())
# time step[day]
dt = 1
shootDryMassInit = 0.0001
ifharvestedLastDay = False
# the initial harvest days
harvestDaysList = np.array(range(cultivationDaysperHarvest - 1, util.getSimulationDaysInt(), cultivationDaysperHarvest))
# print ("harvestDaysList:{}".format(harvestDaysList))
# the variable storing the cultivation start day on each cycle
CultivationCycleStartDay = datetime.date(yearEachDay[0], monthEachDay[0], dayEachDay[0])
# CultivationCycleEndtDay = datetime.date(yearEachDay[0], monthEachDay[0], dayEachDay[0])
i = 0
# print "cycle * cultivationDaysperHarvest -1:{}".format(accumulatedUnitDailyFreshWeightIncrease[0 * cultivationDaysperHarvest -1])
while i < util.getSimulationDaysInt():
DaysperCycle = datetime.timedelta(days = cultivationDaysperHarvest)
# if ifGrowForSummerPeriod is False the end of the cultivation at a cycle is within the summer period, then skip the cycle (= plus 35 days to index)
if ifGrowForSummerPeriod is False and i % cultivationDaysperHarvest == 0 and \
datetime.date(yearEachDay[i], monthEachDay[i], dayEachDay[i]) + DaysperCycle >= datetime.date(yearEachDay[i], constant.SummerPeriodStartMM, constant.SummerPeriodStartDD) and \
datetime.date(yearEachDay[i], monthEachDay[i], dayEachDay[i]) + DaysperCycle <= datetime.date(yearEachDay[i], constant.SummerPeriodEndMM, constant.SummerPeriodEndDD):
# skip the cultivation cycle
i += cultivationDaysperHarvest
continue
# if ifGrowForSummerPeriod is False, and the end of the cultivation at a cycle is not within the summer period, but the first day is within the summer period, then shift the first day to
# the next day of the summer period, and shift all of the cultivation days in harvestDaysList
elif ifGrowForSummerPeriod is False and i % cultivationDaysperHarvest == 0 and \
datetime.date(yearEachDay[i], monthEachDay[i], dayEachDay[i]) >= datetime.date(yearEachDay[i], constant.SummerPeriodStartMM, constant.SummerPeriodStartDD) and \
datetime.date(yearEachDay[i], monthEachDay[i], dayEachDay[i]) <= datetime.date(yearEachDay[i], constant.SummerPeriodEndMM, constant.SummerPeriodEndDD):
# shift the first day to the next day of the summer period
dateDiff = datetime.date(yearEachDay[i], constant.SummerPeriodEndMM, constant.SummerPeriodEndDD) - datetime.date(yearEachDay[i], monthEachDay[i], dayEachDay[i])
i += dateDiff.days + 1
# shift each harvest period by dateDiff to keep the harvest period cultivationDaysperHarvest even after atarting the cultivation next to the summer period.
harvestDaysList += dateDiff.days + 1
continue
# define the initial values on each cycle [g]
if ifharvestedLastDay == True or i == 0:
# if i % cultivationDaysperHarvest == 0:
# print ("when if ifharvestedLastDay == True, i :{}".format(i))
# plant the new seed
shootDryMassList[i] = shootDryMassInit
CultivationCycleStartDay = datetime.date(yearEachDay[i], monthEachDay[i], dayEachDay[i])
# print ("cultivation start date:{}".format(CultivationCycleStartDay))
ifharvestedLastDay = False
# calculate the plant weight increase
else:
# the additional number 1 indicates the difference from the last cultivation day. The difference calculate the increase in calcUnitDailyFreshWeightIncreaseBoth2003TaylorNotForRL
# daysFromSeeding = i % cultivationDaysperHarvest + 1
daysFromSeeding = (datetime.date(yearEachDay[i], monthEachDay[i], dayEachDay[i]) - CultivationCycleStartDay).days + 1
# print("daysFromSeeding:{}".format(daysFromSeeding))
unitDailyFreshWeightIncrease[i] = calcUnitDailyFreshWeightIncreaseBoth2003TaylorNotForRL(innerDLIToPlants[i], shootDryMassList[i], dt, daysFromSeeding)
shootDryMassList[i] = shootDryMassList[i - 1] + unitDailyFreshWeightIncrease[i]
# since all of the initial values of accumulatedUnitDailyFreshWeightIncrease is zero, the value becomes zero when index == 0
accumulatedUnitDailyFreshWeightIncrease[i] = accumulatedUnitDailyFreshWeightIncrease[i - 1] + unitDailyFreshWeightIncrease[i]
# if it takes 35 days from seedling, harvest the plants!! the harvested fresh weight becomes just zero when index is zero because the initial values are zero.
# print("i:{}, np.where(harvestDaysList == i)[0].shape[0]:{}".format(i, np.where(harvestDaysList == i)[0].shape[0]))
if np.where(harvestDaysList == i)[0].shape[0] == 1:
# since the initial element index starts from zero, cultivationDaysperHarvest is minused by 1.
# if i % cultivationDaysperHarvest == cultivationDaysperHarvest - 1:
# print("harvest plants, i:{}".format(i))
unitHarvestedFreshWeight[i] = shootDryMassList[i]
averageDLIonEachCycle[i] = np.mean(innerDLIToPlants[i-(cultivationDaysperHarvest - 1):i+1])
ifharvestedLastDay = True
# delete the harvest day from harvestDaysList
# harvestDaysList = np.array([harvestDaysList[j] for j in range (0, harvestDaysList.shape[0]) if harvestDaysList[j] != i and harvestDaysList[j] > i ])
harvestDaysList = np.array([harvestDaysList[j] for j in range (0, harvestDaysList.shape[0]) if harvestDaysList[j] > i ])
# np.delete(harvestDaysList, np.where(harvestDaysList == i)[0][0])
# print("current harvestDaysList:{}".format(harvestDaysList))
# increment the counter
i += 1
# change dry mass weight into fresh mass weight
# daily increase in unit plant weight [g]
unitDailyFreshWeightIncrease = unitDailyFreshWeightIncrease * constant.DryMassToFreshMass
# accumulated weight of daily increase in unit plant weight during the whole simulation days [g]
accumulatedUnitDailyFreshWeightIncrease = accumulatedUnitDailyFreshWeightIncrease * constant.DryMassToFreshMass
# harvested daily unit plant weight [g]
unitHarvestedFreshWeight = unitHarvestedFreshWeight * constant.DryMassToFreshMass
# daily unit plant weight on each cycle [g]
shootFreshMassList = shootDryMassList * constant.DryMassToFreshMass
# print "shootDryMassList:{}".format(shootDryMassList)
# print "unitDailyFreshWeightIncrease:{}".format(unitDailyFreshWeightIncrease)
# print "accumulatedUnitDailyFreshWeightIncrease:{}".format(accumulatedUnitDailyFreshWeightIncrease)
# print "unitHarvestedFreshWeight:{}".format(unitHarvestedFreshWeight)
# set the average light DLi of each cultivation cycle, the data is stored in the element on the harvest date.
cropElectricityYieldSimulator1.setAverageDLIonEachCycle(averageDLIonEachCycle)
return shootFreshMassList, unitDailyFreshWeightIncrease, accumulatedUnitDailyFreshWeightIncrease, unitHarvestedFreshWeight
def calcUnitDailyFreshWeightIncreaseBoth2003TaylorNotForRL(innerDLIToPlants, shootDryMassList, dt, daysFromSeeding):
'''
this function is for general simulation. This is more accurate than calcUnitDailyFreshWeightIncreaseBoth2003Taylor, which should be replaced later.
:param innerDLIToPlants:
:param shootDryMassList:
:param dt:
:return:
'''
# update each statistic each day
a = -8.596 + 0.0743 * innerDLIToPlants
b = 0.4822
c = -0.006225
shootDryMassList = math.e ** (a + b * daysFromSeeding + c * daysFromSeeding ** 2)
d_shootDryMassList = (b + 2 * c * daysFromSeeding) * shootDryMassList
dd_shootDryMassList = 2 * c * shootDryMassList + (b + 2 * c * daysFromSeeding) ** 2 * shootDryMassList
ddd_shootDryMassList = 2 * c * d_shootDryMassList + 4 * c * (b + 2 * c * daysFromSeeding) * shootDryMassList + (b + 2 * c * daysFromSeeding) ** 2 * d_shootDryMassList
# Taylor expansion: x_0 = 0, h = 1 (source: http://eman-physics.net/math/taylor.html)
shootDryMassIncrease = 1.0 / (math.factorial(1)) * d_shootDryMassList * dt + 1.0 / (math.factorial(2)) * dd_shootDryMassList * ((dt) ** 2) + \
1.0 / (math.factorial(3)) * ddd_shootDryMassList * ((dt) ** 3)
return shootDryMassIncrease
# def calcUnitDailyFreshWeightIncreaseBoth2003Taylor(innerDLIToPlants, cultivationDaysperHarvest, daysFromSeeding):
# '''
# this function is only for the Q learning reinforcement learning
# calculate the unit fresh weight increase per day based on the revised model of Both (2003):
# Both, A., 2003. Ten years of hydroponic lettuce research. Knowledgecenter.Illumitex.Com 18, 8.
#
# param:innerDLIToPlants [mol/m^2/day] per day
# param:cultivationDaysperHarvest [days] per day
# param:daysFromSeeding [days] per day
#
# return: dailyFreshWeightIncrease[g/day]
# return: hervestDay[days]: days after seeeding
# '''
# # print "dailyInnerLightIntensityDLI:{}".format(dailyInnerLightIntensityDLI)
# # print "cultivationDaysperHarvest:{}".format(cultivationDaysperHarvest)
#
# # daily increase in unit plant weight [g]
# unitDailyFreshWeightIncrease = np.zeros(1)
# # accumulated weight of daily increase in unit plant weight during the whole simulation days [g]
# accumulatedUnitDailyFreshWeightIncrease = np.zeros(1)
# # harvested daily unit plant weight [g]
# unitHarvestedFreshWeight = np.zeros(1)
#
# # simulationDaysInt = util.calcSimulationDaysInt()
# simulationDaysInt = 1
#
# # num of cultivation cycle
# NumCultivationCycle = 0
# # print ("NumCultivationCycle:{}".format(NumCultivationCycle))
#
# # num of remained days when we cannot finish the cultivation, which is less than the num of cultivation days.
# CultivationDaysWithNoHarvest = simulationDaysInt - NumCultivationCycle * cultivationDaysperHarvest
# # print "CultivationDaysWithNoHarvest:{}".format(CultivationDaysWithNoHarvest)
#
# # define statistics for calculation
# # daily unit plant weight on each cycle [g]
# shootDryMassList = np.zeros(len(unitDailyFreshWeightIncrease))
# d_shootDryMassList = np.zeros(len(unitDailyFreshWeightIncrease))
# # dd_shootDryMassList = np.zeros(len(unitDailyFreshWeightIncrease))
# # ddd_shootDryMassList = np.zeros(len(unitDailyFreshWeightIncrease))
# a = 0
# b = 0.4822
# c = -0.006225
# # time step[day]
# dt = 1
#
# # print "cycle * cultivationDaysperHarvest -1:{}".format(accumulatedUnitDailyFreshWeightIncrease[0 * cultivationDaysperHarvest -1])
#
# for cycle in range(0, NumCultivationCycle + 1):
#
# # define the initial values on each cycle [g]
# # shootDryMassInit == the weight on day 0 == weight of seed [g]
# shootDryMassInit = 0.0001
# accumulatedUnitDailyFreshWeightIncrease[cycle * cultivationDaysperHarvest] = accumulatedUnitDailyFreshWeightIncrease[
# cycle * cultivationDaysperHarvest - 1] + shootDryMassInit
# shootDryMassList[cycle * cultivationDaysperHarvest] = shootDryMassInit
# d_shootDryMassList[cycle * cultivationDaysperHarvest] = (b + 2 * c * 0.0) * shootDryMassList[cycle * cultivationDaysperHarvest]
# # dd_shootDryMassList[cycle * cultivationDaysperHarvest] = 2 * c * shootDryMassList[cycle * cultivationDaysperHarvest] + \
# # (b + 2 * c * 0.0) ** 2 * shootDryMassList[cycle * cultivationDaysperHarvest]
# # ddd_shootDryMassList[cycle * cultivationDaysperHarvest] = 2 * c * d_shootDryMassList[cycle * cultivationDaysperHarvest] + \
# # 4 * c * (b + 2 * c * 0.0) * shootDryMassList[cycle * cultivationDaysperHarvest] + \
# # (b + 2 * c * 0) ** 2 * d_shootDryMassList[cycle * cultivationDaysperHarvest]
#
# # print "shootDryMassList[cycle*cultivationDaysperHarvest]:{}".format(shootDryMassList[cycle*cultivationDaysperHarvest])
# # print "d_shootDryMassList[cycle*cultivationDaysperHarvest]:{}".format(d_shootDryMassList[cycle*cultivationDaysperHarvest])
# # print "dd_shootDryMassList[cycle*cultivationDaysperHarvest]:{}".format(dd_shootDryMassList[cycle*cultivationDaysperHarvest])
# # print "ddd_shootDryMassList[cycle*cultivationDaysperHarvest]:{}".format(ddd_shootDryMassList[cycle*cultivationDaysperHarvest])
#
#
# # update each statistic each day
# a = -8.596 + 0.0743 * innerDLIToPlants
# shootDryMassList = math.e ** (a + b * daysFromSeeding + c * daysFromSeeding ** 2)
# d_shootDryMassList = (b + 2 * c * daysFromSeeding) * shootDryMassList
# dd_shootDryMassList = 2 * c * shootDryMassList + (b + 2 * c * daysFromSeeding) ** 2 * shootDryMassList
# ddd_shootDryMassList = 2 * c * d_shootDryMassList + 4 * c * (b + 2 * c * daysFromSeeding) * shootDryMassList + \
# (b + 2 * c * daysFromSeeding) ** 2 * d_shootDryMassList
#
# # print "day{}, a:{},shootDryMassList[{}]:{}".format(day, a, cycle*cultivationDaysperHarvest+day, shootDryMassList[cycle*cultivationDaysperHarvest+day])
#
# # Taylor expansion: x_0 = 0, h = 1 (source: http://eman-physics.net/math/taylor.html)
# # shootDryMassList[cycle * cultivationDaysperHarvest + day] = shootDryMassList[cycle * cultivationDaysperHarvest + day - 1] + \
# # 1.0 / (math.factorial(1)) * d_shootDryMassList[
# # cycle * cultivationDaysperHarvest + day - 1] * dt + \
# # 1.0 / (math.factorial(2)) * dd_shootDryMassList[
# # cycle * cultivationDaysperHarvest + day - 1] * ((dt) ** 2) + \
# # 1.0 / (math.factorial(3)) * ddd_shootDryMassList[
# # cycle * cultivationDaysperHarvest + day - 1] * ((dt) ** 3)
#
# # unitDailyFreshWeightIncrease[cycle * cultivationDaysperHarvest + day] = shootDryMassList[cycle * cultivationDaysperHarvest + day] - \
# # shootDryMassList[cycle * cultivationDaysperHarvest + day - 1]
# unitDailyFreshWeightIncrease = d_shootDryMassList
#
# # accumulatedUnitDailyFreshWeightIncrease[cycle * cultivationDaysperHarvest + day] = \
# # accumulatedUnitDailyFreshWeightIncrease[cycle * cultivationDaysperHarvest + day - 1] + unitDailyFreshWeightIncrease[
# # cycle * cultivationDaysperHarvest + day]
#
# # print "day:{}, cycle*cultivationDaysperHarvest+day:{}, shootDryMassList[cycle*cultivationDaysperHarvest + day]:{}".format(
# # day, cycle * cultivationDaysperHarvest + day, shootDryMassList[cycle * cultivationDaysperHarvest + day])
#
# # change dry mass weight into fresh mass weight
# # daily increase in unit plant weight [g]
# unitDailyFreshWeightIncrease = unitDailyFreshWeightIncrease * constant.DryMassToFreshMass
# # accumulated weight of daily increase in unit plant weight during the whole simulation days [g]
# # accumulatedUnitDailyFreshWeightIncrease = accumulatedUnitDailyFreshWeightIncrease * constant.DryMassToFreshMass
# # harvested daily unit plant weight [g]
# # unitHarvestedFreshWeight = unitHarvestedFreshWeight * constant.DryMassToFreshMass
# # daily unit plant weight on each cycle [g]
# # shootFreshMassList = shootDryMassList * constant.DryMassToFreshMass
#
# # print "shootDryMassList:{}".format(shootDryMassList)
# # print "unitDailyFreshWeightIncrease:{}".format(unitDailyFreshWeightIncrease)
# # print "accumulatedUnitDailyFreshWeightIncrease:{}".format(accumulatedUnitDailyFreshWeightIncrease)
# # print "unitHarvestedFreshWeight:{}".format(unitHarvestedFreshWeight)
#
# return unitDailyFreshWeightIncrease
def getLettucePricepercwt(year):
'''
return the lettuce price per cwt based on the year of sales
:param year:
:return:
'''
return 0.583 * year - 1130
def getRetailPricePerArea(simulatorClass):
# the source of the romaine lettuce retail price data
# https://data.bls.gov/timeseries/APU0000FL2101?amp%253bdata_tool=XGtable&output_view=data&include_graphs=true
# unit: kg/m^2/day
harvestedShootFreshMassPerAreaKgPerDay = simulatorClass.harvestedShootFreshMassPerAreaKgPerDay
# print("harvestedShootFreshMassPerAreaKgPerDay:{}".format(harvestedShootFreshMassPerAreaKgPerDay))
# unit: USD/m^2/day
harvestedFreshMassPricePerAreaPerDay = np.zeros(harvestedShootFreshMassPerAreaKgPerDay.shape[0])
# get the month and year lists
simulationMonthEachDay = simulatorClass.getMonth()[::24]
simulationYearEachDay = simulatorClass.getYear()[::24]
# if you refer to the price for greenhouse lettuce
if constant.sellLettuceByGreenhouseRetailPrice:
# define the price data
# source: https://www.ams.usda.gov/mnreports/fvwretail.pdf
# "Lettuce Other Boston-Greenhouse" 1.99 USD each
# make the price data in the same format as constant.romaineLettceRetailPriceFileName
# get the unit price (USD m-2)
# romaineLettuceRetailPricePerMonth = getRomainLettucePriceBasedOnHeadPrice()
# get the sales price of each harvested lettuce (weight)
for i in range(0, harvestedShootFreshMassPerAreaKgPerDay.shape[0]):
# if it is not the harvest date then skip the day. It is also skipped if the head weight does not reach 90% of the defined harvest fresh weight by kg m-2 day-1.
if harvestedShootFreshMassPerAreaKgPerDay[i] < (constant.harvestDryWeight * constant.DryMassToFreshMass) / 1000 * constant.plantDensity * 0.9 : continue
# unit: USD/m^2/day
harvestedFreshMassPricePerAreaPerDay[i] = constant.romainLettucePriceBasedOnHeadPrice * constant.plantDensity
else:
# import the price data
filename = constant.romaineLettceRetailPriceFileName
relativePath = constant.romaineLettceRetailPriceFilePath
romaineLettuceRetailPricePerMonth = util.readData(filename, relativePath, 0, ',')
# print("romaineLettuceRetailPricePerMonth:{}".format(romaineLettuceRetailPricePerMonth))
# print("type(romaineLettuceRetailPricePerMonth):{}".format(type(romaineLettuceRetailPricePerMonth)))
# get the sales price of each harvested lettuce (weight)
for i in range (0, harvestedShootFreshMassPerAreaKgPerDay.shape[0]):
# if it is not the harvest date then skip the day
if harvestedShootFreshMassPerAreaKgPerDay[i] == 0.0: continue
# get the unit price (USD pound-1)
unitRetailPricePerPound = getUnitRomainLettucePrice(simulationMonthEachDay[i], simulationYearEachDay[i], romaineLettuceRetailPricePerMonth)
# unit conversion: 1USD pound-1 -> USD kg-1
unitRetailPricePerKg = util.convertKgToPound(unitRetailPricePerPound)
# unit: USD/m^2/day
harvestedFreshMassPricePerAreaPerDay[i] = harvestedShootFreshMassPerAreaKgPerDay[i] * unitRetailPricePerKg
# print("In Lettuce.py, harvestedFreshMassPricePerAreaPerDay:{}".format(harvestedFreshMassPricePerAreaPerDay))
return harvestedFreshMassPricePerAreaPerDay
def getUnitRomainLettucePrice(month, year, priceInfoList):
"""
return the price of lettuce on a given month and year
"""
# print("priceInfoList:{}".format(priceInfoList))
# print("priceInfoList.shape:{}".format(priceInfoList.shape))
# print("type(month):{}".format(type(month)))
# print("type(year):{}".format(type(year)))
# assuming the list has the header, so skip the header
for i in range (1, priceInfoList.shape[0]):
priceInfo = priceInfoList[i]
# print("i:{}, priceInfo:{}".format(i, priceInfo))
# print("year:{}".format(year))
# print("type(year):{}".format(type(month)))
# print("month:{}".format(year))
# print("type(month):{}".format(type(month)))
# print("priceInfo[1]:{}".format(priceInfo[1]))
# print("priceInfo[2][0:2]:{}".format(priceInfo[2][1:]))
if year == int(priceInfo[1]) and month == int(priceInfo[2][1:]):
# print("priceInfo[3]:{}".format(priceInfo[3]))
# print("type(priceInfo[3]):{}".format(type(priceInfo[3])))
# unit: USD pound-1
return float(priceInfo[3])
print("The specified simulation period include the term where there is no lettuce unit price information. Simulation stopped.")
# ####################################################################################################
# # Stop execution here...
sys.exit()
# # Move the above line to different parts of the assignment as you implement more of the functionality.
# ####################################################################################################
def getRomainLettucePriceBasedOnHeadPrice():
# get init date
startDate = util.getStartDateDateType()
numOfSimulationMonths = util.getSimulationMonthsInt()
romainLettucePriceBasedOnHeadPrice = np.zeros((numOfSimulationMonths,4))
for i in range (numOfSimulationMonths):
romainLettucePriceBasedOnHeadPrice[i][0] = "dummy"
# set year
romainLettucePriceBasedOnHeadPrice[i][1] = (startDate + relativedelta(months = i)).year
# set month
romainLettucePriceBasedOnHeadPrice[i][2] = (startDate + relativedelta(months = i)).month
# set the head price
# unit: USD head-1
romainLettucePriceBasedOnHeadPrice[i][3] = constant.romainLettucePriceBasedOnHeadPrice
# unit convert: USD head-1 -> USD m-2
romainLettucePriceBasedOnHeadPrice[i][3] = romainLettucePriceBasedOnHeadPrice[i][3] * constant.plantDensity
return romainLettucePriceBasedOnHeadPrice
def discountPlantSalesperSquareMeterByTipburn(plantSalesperSquareMeter, TotalDLItoPlants):
'''
:param plantSalesperSquareMeter:
:param TotalDLItoPlants:
:return:
'''
# cultivationDaysWithoutHarvest = getCultivationDaysWithoutHarvest(plantSalesperSquareMeter)
cultivationDaysWithoutHarvest = int(util.calcSimulationDaysInt() % constant.cultivationDaysperHarvest)
# print "cultivationDaysWithoutHarvest:{}".format(cultivationDaysWithoutHarvest)
for cycle in range (0, int(util.calcSimulationDaysInt() / constant.cultivationDaysperHarvest)):
averageDLIperCycle = sum(TotalDLItoPlants[cycle*constant.cultivationDaysperHarvest:(cycle+1)*constant.cultivationDaysperHarvest]) / constant.cultivationDaysperHarvest
# print "averageDLIperCycle:{}".format(averageDLIperCycle)
# if the DLI is more than the amount with which there can be some tipburns, discount the price.
if averageDLIperCycle > constant.DLIforTipBurn:
plantSalesperSquareMeter[(cycle+1)*constant.cultivationDaysperHarvest-1] = constant.tipburnDiscountRatio * \
plantSalesperSquareMeter[(cycle+1)*constant.cultivationDaysperHarvest-1]
return plantSalesperSquareMeter
def getCultivationDaysWithoutHarvest(plantSalesperSquareMeter):
'''
num of remained days when we cannot finish the cultivation, which is less than the num of cultivation days.
:param plantSalesperSquareMeter:
:return:
'''
# num of cultivation cycle
NumCultivationCycle = int(util.calcSimulationDaysInt() / constant.cultivationDaysperHarvest)
# print "NumCultivationCycle:{}".format(NumCultivationCycle)
# num of remained days when we cannot finish the cultivation, which is less than the num of cultivation days.
CultivationDaysWithNoHarvest = util.calcSimulationDaysInt() - NumCultivationCycle * constant.cultivationDaysperHarvest
# print "CultivationDaysWithNoHarvest:{}".format(CultivationDaysWithNoHarvest)
return CultivationDaysWithNoHarvest
def getRevenueOfPlantYieldperHarvest(freshWeightTotalperHarvest):
'''
calculate the revenue of plant sales per harvest (USD/harvest)
param:freshWeightTotalperHarvest: fresh Weight perHarvest (kg/harvest)
return: revenueOfPlantProductionperHarvest: revenue Of Plant Production per Harvest (USD/harvest)
'''
return constant.lantUnitPriceUSDperKilogram * freshWeightTotalperHarvest
def getCostofPlantYieldperYear():
'''
calculate the cost of plant sales per harvest (USD/per)
param: :
return: : cost Of Plant Production per year (USD/year)
'''
return constant.plantProductionCostperSquareMeterPerYear * constant.greenhouseFloorArea
def getGreenhouseTemperatureEachDay(simulatorClass):
# It was assumed the greenhouse temperature was instantaneously adjusted to the set point temperatures at daytime and night time respectively
hourlyDayOrNightFlag = simulatorClass.hourlyDayOrNightFlag
greenhouseTemperature = np.array([constant.setPointTemperatureDayTime if i == constant.daytime else constant.setPointTemperatureNightTime for i in hourlyDayOrNightFlag])
# calc the mean temperature each day
dailyAverageTemperature = np.zeros(util.getSimulationDaysInt())
for i in range(0, util.getSimulationDaysInt()):
dailyAverageTemperature[i] = np.average(greenhouseTemperature[i * constant.hourperDay: (i + 1) * constant.hourperDay])
return dailyAverageTemperature
def getGreenhouseTemperatureEachHour(simulatorClass):
# It was assumed the greenhouse temperature was instantaneously adjusted to the set point temperatures at daytime and night time respectively
hourlyDayOrNightFlag = simulatorClass.hourlyDayOrNightFlag
greenhouseTemperature = np.array(
[constant.setPointTemperatureDayTime if i == constant.daytime else constant.setPointTemperatureNightTime for i in hourlyDayOrNightFlag])
return greenhouseTemperature
def getFreshWeightIncrease(FWPerHead):
# get the fresh weight increase
# freshWeightIncrease = np.array([WFresh[i] - WFresh[i-1] if WFresh[i] - WFresh[i-1] > 0 else 0.0 for i in range (1, WFresh.shape[0])])
# # insert the value for i == 0
# freshWeightIncrease[0] = 0.0
# it is possible that the weight decreases at E_J_VanHenten1994
freshWeightIncrease = np.array([0.0 if i == 0 or FWPerHead[i] - FWPerHead[i-1] <= -constant.harvestDryWeight*constant.DryMassToFreshMass/2.0\
else FWPerHead[i] - FWPerHead[i-1] for i in range (0, FWPerHead.shape[0])])
return freshWeightIncrease
def getAccumulatedFreshWeightIncrease(WFresh):
# get accumulated fresh weight
freshWeightIncrease = getFreshWeightIncrease(WFresh)
accumulatedFreshWeightIncrease = np.zeros(WFresh.shape[0])
accumulatedFreshWeightIncrease[0] = WFresh[0]
for i in range(1, freshWeightIncrease.shape[0]):
# print("i:{}, accumulatedFreshWeightIncrease[i]:{}, accumulatedFreshWeightIncrease[i-1]:{}, freshWeightIncrease[i]:{}".format(i, accumulatedFreshWeightIncrease[i], accumulatedFreshWeightIncrease[i-1], freshWeightIncrease[i]))
accumulatedFreshWeightIncrease[i] = accumulatedFreshWeightIncrease[i-1] + freshWeightIncrease[i]
return accumulatedFreshWeightIncrease
def getHarvestedFreshWeight(WFresh):
# get the harvested fresh weight
# record the fresh weight harvested at each harvest day or hour
# harvestedFreshWeight = np.array([WFresh[i] if WFresh[i] > 0.0 and WFresh[i+1] == 0.0 else 0.0 for i in range (0, WFresh.shape[0])])
harvestedFreshWeight = np.zeros(WFresh.shape[0])
for i in range (0, WFresh.shape[0]-1):
# print("i:{}, WFresh[i]:{}".format(i, WFresh[i]))
if WFresh[i] > 0.0 and WFresh[i+1] == 0.0:
harvestedFreshWeight[i] = WFresh[i]
else:
harvestedFreshWeight[i] = 0.0
# print("0 harvestedFreshWeight.shape[0]:{}".format(harvestedFreshWeight.shape[0]))
# if the last hour of the last day is the harvest date
if WFresh[-1] > constant.harvestDryWeight*constant.DryMassToFreshMass:
# harvestedFreshWeight = np.append(harvestedFreshWeight, [WFresh[-1]])
harvestedFreshWeight[-1] = WFresh[-1]
else:
harvestedFreshWeight[-1] = WFresh[-1]
return harvestedFreshWeight
|
{"/OPVFilm.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/ShadingCurtain.py"], "/CropElectricityYieldProfitMINLP.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelS_Pearson1997.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/PlantGrowthModelS_Pearson1997Constant.py", "/Lettuce.py"], "/GreenhouseEnergyBalanceConstant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/Util.py": ["/CropElectricityYeildSimulatorConstant.py"], "/SolarIrradianceMultiSpanRoof.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/GreenhouseEnergyBalance.py": ["/Lettuce.py", "/CropElectricityYeildSimulatorConstant.py", "/GreenhouseEnergyBalanceConstant.py", "/Util.py"], "/SimulatorMain.py": ["/CropElectricityYeildSimulator1.py", "/Util.py", "/CropElectricityYeildSimulatorConstant.py"], "/CropElectricityYieldProfitRLShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/ShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelValidation.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulator1.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulatorDetail.py": ["/ShadingCurtain.py", "/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/Lettuce.py", "/PlantGrowthModelS_Pearson1997.py", "/SolarIrradianceMultiSpanRoof.py", "/GreenhouseEnergyBalance.py"], "/PlantGrowthModelS_Pearson1997Constant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/SimulatorClass.py": ["/CropElectricityYeildSimulatorConstant.py"], "/Lettuce.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/plantGrowthModelE_J_VanHenten.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py"]}
|
8,673
|
kensaku-okada/Greenhouse-with-OPV-film-Model
|
refs/heads/master
|
/plantGrowthModelE_J_VanHenten.py
|
# -*- coding: utf-8 -*-
#######################################################
# author :Kensaku Okada [kensakuokada@email.arizona.edu]
# create date : 15 Jun 2017
# last edit date: 15 Jun 2017
#######################################################
# ####################################################################################################
# np.set_printoptions(threshold=np.inf)
# print "hourlySolarIncidenceAngle:{}".format(np.degrees(hourlySolarIncidenceAngle))
# np.set_printoptions(threshold=1000)
# ####################################################################################################
# ####################################################################################################
# # Stop execution here...
# sys.exit()
# # Move the above line to different parts of the assignment as you implement more of the functionality.
# ####################################################################################################
##########import package files##########
import os as os
import numpy as np
import sys
import matplotlib.pyplot as plt
import math
import CropElectricityYeildSimulatorConstant as constant
import Util as util
import datetime
import Lettuce
import PlantGrowthModelE_J_VanHentenConstant as VanHentenConstant
import PlantGrowthPenaltyByPhotoinhibition as Photoinhibition
def calcUnitDailyFreshWeightE_J_VanHenten1994(simulatorClass):
'''
"dt" is 1 second.
reference: E. J. Van Henten, 1994, "validation of a dynamic lettuce growth model for greenhouse climate control"
https://www.sciencedirect.com/science/article/pii/S0308521X94902801
'''
# According to Van Henten (1994), 'With data logging system connected to the greenhouse climate computer, half-hour mean values of the indoor climate data were recorded.'
# get the simulation days
simulationDaysInt = util.getSimulationDaysInt()
# print("simulationDaysInt:{}".format(simulationDaysInt))
# take date and time
year = simulatorClass.getYear()
month = simulatorClass.getMonth()
day = simulatorClass.getDay()
# print("year[0]:{}".format(year[0]))
# get the summer period hours
summerPeriodDays = datetime.date(year=year[0], month=constant.SummerPeriodEndMM, day=constant.SummerPeriodEndDD) - \
datetime.date(year=year[0], month=constant.SummerPeriodStartMM, day=constant.SummerPeriodStartDD)
# change the data type and unit
summerPeriodHours = summerPeriodDays.days * constant.hourperDay
# print("summerPeriodHours:{}".format(summerPeriodHours))
# [head/m^2]
plantDensity = constant.plantDensity
# plantDensity = 18.0
# it was assumed that the canopy temperature is instantaneously adjusted to the setpoint temperature at each hour.
U_T = Lettuce.getGreenhouseTemperatureEachHour(simulatorClass)
# the following definition of U_T is used for validation
# U_T = simulatorClass.GHAirTemperatureValidationData
# print("U_T:{}".format(U_T))
# print("U_T.shape:{}".format(U_T.shape))
# Horizontal irradiance above the canopy (PAR) [W/m^2]
directSolarIrradianceToPlants = simulatorClass.directSolarIrradianceToPlants
diffuseSolarIrradianceToPlants = simulatorClass.diffuseSolarIrradianceToPlants
totalSolarIrradianceToPlants = directSolarIrradianceToPlants + diffuseSolarIrradianceToPlants
# By dividing the irradiance by 2, the shortwave radiation is converted into PAR [W/m^2]
U_par = totalSolarIrradianceToPlants/2.0
# print("U_par:{}".format(U_par))
# unit: ppm - pers per million (1/1000000)
# it is temporarily assumed that all hourly CO2 concentration is 400 ppm
U_CO2 = np.array([400] * U_T.shape[0])
# structured dry weight on each day [g / m**2]
Xsdw = np.zeros(simulationDaysInt*constant.hourperDay)
# non structured dry weight on each day [g / m**2]
Xnsdw = np.zeros(simulationDaysInt*constant.hourperDay)
# total dry weight
DW = np.zeros(simulationDaysInt*constant.hourperDay)
# summer period flag array: 1.0 == summer, 0.0 == not summer
summerPeriodFlagArray = np.zeros(simulationDaysInt*constant.hourperDay)
# set the initial values
# according to the reference, the initial dry weight was 2.7 g/m^2 with the cultivar "Berlo" (started 17 October 1991), and 0.72 g/m^2 with "Norden"(started 21 January 1992)
# [g / m**2]
InitialdryWeight = 2.7
# [g / m**2]
Xsdw[0] = InitialdryWeight * 0.75
# [g / m**2]
Xnsdw[0] = InitialdryWeight * 0.25
# [g / m**2]
DW[0] = Xsdw[0] + Xnsdw[0]
# DWPerHead[0] = DW[0] / plantDensity
# FWPerHead[0] = DWPerHead[0] * constant.DryMassToFreshMass
# 1 loop == 1 hour
i = 1
while i < simulationDaysInt * constant.hourperDay:
# for i in range (1, constant.cultivationDaysperHarvest):
# if you do not grow plant during the summer period, then skip the summer period
# if simulatorClass.getIfGrowForSummerPeriod() is False and \
# the last condition was added to consider the case when the summer period is defined to be zero even if constant.ifGrowForSummerPeriod is False
if constant.ifGrowForSummerPeriod is False and \
datetime.date(year[i], month[i], day[i]) >= datetime.date(year[i], constant.SummerPeriodStartMM, constant.SummerPeriodStartDD) and \
datetime.date(year[i], month[i], day[i]) <= datetime.date(year[i], constant.SummerPeriodEndMM, constant.SummerPeriodEndDD) and \
datetime.date(year[i], constant.SummerPeriodEndMM, constant.SummerPeriodEndDD) > datetime.date(year[i], constant.SummerPeriodStartMM, constant.SummerPeriodStartDD):
# skip the summer period cultivation cycle
# It was assumed to take 3 days to the next cultivation cycle assuming "transplanting shock prevented growth during the first 48 h", and it takes one day for preparation.
# source: 21. Pearson, S., Wheeler, T. R., Hadley, P., & Wheldon, A. E. (1997). A validated model to predict the effects of environment on the growth of lettuce (Lactuca sativa L.): Implications for climate change. Journal of Horticultural Science, 72(4), 503–517. https://doi.org/10.1080/14620316.1997.11515538
i += summerPeriodHours + 3 * constant.hourperDay
# print("summerPeriodHours:{}".format(summerPeriodHours))
# record the summer period
summerPeriodFlagArray[i - summerPeriodHours + 3 * constant.hourperDay: i] = 1.0
# print("i:{}".format(i))
# print("resetInitialWeights(i, Xsdw[0], Xnsdw[0]):{}".format(resetInitialWeights(i, Xsdw[0], Xnsdw[0])))
# print("Xsdw[i - 2 * constant.hourperDay:i]:{}".format(Xsdw[i - 2 * constant.hourperDay:i]))
# print("Xnsdw[i - 2 * constant.hourperDay:i]:{}".format(Xnsdw[i - 2 * constant.hourperDay:i]))
# print("DW[i - 2 * constant.hourperDay:i]:{}".format(DW[i - 2 * constant.hourperDay:i]))
# initialize the plant weight for the cultivation soon after the summer period
Xsdw[i - 2 * constant.hourperDay:i], \
Xnsdw[i - 2 * constant.hourperDay:i], \
DW[i - 2 * constant.hourperDay:i] = resetInitialWeights(i, Xsdw[0], Xnsdw[0])
# print("i:{}, Xsdw[i - 2 * constant.hourperDay:i]:{}, Xnsdw[i - 2 * constant.hourperDay:i]:{}, DW[i - 2 * constant.hourperDay:i]:{}".\
# format(i, Xsdw[i - 2 * constant.hourperDay:i], Xnsdw[i - 2 * constant.hourperDay:i], DW[i - 2 * constant.hourperDay:i]))
continue
####################### parameters for calculating f_photo_max start #######################
# the carboxylation conductance
g_car = VanHentenConstant.c_car1 * (U_T[i-1])**2 + VanHentenConstant.c_car2 * U_T[i-1] + VanHentenConstant.c_car3
# print("i:{}, g_car:{}".format(i, g_car))
# the canopy conductance for diffusion of CO2 from the ambient air to the chloroplast :gross carbon dioxide assimilation rate of the canopy having an effective surface of 1m^2 per square meter soild at complete soil covering.
g_CO2 = VanHentenConstant.g_bnd['m s-1']*VanHentenConstant.g_stm['m s-1']* g_car / (VanHentenConstant.g_bnd['m s-1'] * VanHentenConstant.g_stm['m s-1'] \
+ VanHentenConstant.g_bnd['m s-1']*g_car + VanHentenConstant.g_stm['m s-1'] * g_car)
# print("g_CO2:{}".format(g_CO2))
# CO2 compensation point
gamma = VanHentenConstant.c_upperCaseGamma['ppm'] * VanHentenConstant.c_Q10_upperCaseGamma ** ((U_T[i-1] -20.0)/10.0)
# print("gamma:{}".format(gamma))
# light use efficiency
epsilon = {'g J-1': VanHentenConstant.c_epsilon['g J-1'] * (U_CO2[i-1] - gamma) / ( U_CO2[i-1] + 2.0 * gamma)}
# print("epsilon:{}".format(epsilon))
####################### parameters for calculating f_photo_max end #######################
# the response of canopy photosynthesis
f_photo_max = {'g m-2 s-2': epsilon['g J-1'] * U_par[i-1] * g_CO2 * VanHentenConstant.c_omega['g m-3'] * (U_CO2[i-1] - gamma) / \
(epsilon['g J-1']* U_par[i-1] + g_CO2 * VanHentenConstant.c_omega['g m-3'] * (U_CO2[i-1] - gamma))}
# print("f_photo_max:{}".format(f_photo_max))
# specific growth rate: the transfromation rate of non-structural dry weight to structural dry weight
r_gr = VanHentenConstant.c_gr_max['s-1'] * Xnsdw[i-1] / (VanHentenConstant.c_gamma * Xsdw[i-1] + Xnsdw[i-1]) * (VanHentenConstant.c_Q10_gr ** ((U_T[i] - 20.0) / 10.0))
# print("r_gr:{}".format(r_gr))
# the maintenance respiration rate of the crop
f_resp = (VanHentenConstant.c_resp_sht['s-1'] * (1 - VanHentenConstant.c_tau) * Xsdw[i-1] + VanHentenConstant.c_resp_rt['s-1'] * VanHentenConstant.c_tau * Xsdw[i-1])\
* VanHentenConstant.c_Q10_resp ** ((U_T[i-1] - 25.0)/10.0)
# print("f_resp:{}".format(f_resp))
# gross canopy photosynthesis
f_photo = (1.0 - np.exp( - VanHentenConstant.c_K * VanHentenConstant.c_lar['m2 g-2'] * (1- VanHentenConstant.c_tau) * Xsdw[i-1])) * f_photo_max['g m-2 s-2']
# print("f_photo:{}".format(f_photo))
# [g / m ** 2/ sec]
d_structuralDryWeight = r_gr * Xsdw[i-1]
# [g / m ** 2/ sec]
d_nonStructuralDryWeight = VanHentenConstant.c_alpha * f_photo - r_gr * Xsdw[i-1] - f_resp - (1 - VanHentenConstant.c_beta) / VanHentenConstant.c_beta * r_gr * Xsdw[i-1]
# unit conversion. [g m-2 sec-1] -> [g m-2 hour-1]
d_structuralDryWeight = d_structuralDryWeight * constant.secondperMinute * constant.minuteperHour
d_nonStructuralDryWeight = d_nonStructuralDryWeight * constant.secondperMinute * constant.minuteperHour
# print("d_structuralDryWeight:{}".format(d_structuralDryWeight))
# print("d_nonStructuralDryWeight:{}".format(d_nonStructuralDryWeight))
# increase the plant weight
Xsdw[i] = Xsdw[i-1] + d_structuralDryWeight
Xnsdw[i] = Xnsdw[i-1] + d_nonStructuralDryWeight
DW[i] = Xsdw[i] + Xnsdw[i]
# if the dry weight exceeds the weight for cultimvation, then reset the dryweight
if DW[i] > constant.harvestDryWeight * plantDensity:
# It was assumed to take 3 days to the next cultivation cycle assuming "transplanting shock prevented growth during the first 48 h", and it takes one day for preparation.
i += 3 * constant.hourperDay
if (i >= simulationDaysInt * constant.hourperDay): break
# The plant dry weight (excluding roots) W
Xsdw[i - 2 * constant.hourperDay:i], \
Xnsdw[i - 2 * constant.hourperDay:i],\
DW[i - 2 * constant.hourperDay:i] = resetInitialWeights(i, Xsdw[0], Xnsdw[0])
else:
# increment the counter for one hour
i += 1
# the plant weight per head
# Ydw = (Xsdw + Xnsdw) / float(constant.numOfHeadsPerArea)
# set variables to the object
simulatorClass.LeafAreaIndex_J_VanHenten1994 = VanHentenConstant.c_lar['m2 g-2'] * (1- VanHentenConstant.c_tau) * Xsdw
simulatorClass.summerPeriodFlagArray = summerPeriodFlagArray
DWPerHead = DW / plantDensity
# print("DWPerHead:{}".format(DWPerHead))
FWPerHead = DWPerHead * constant.DryMassToFreshMass
# get the fresh weight increase per head
WFreshWeightIncrease = Lettuce.getFreshWeightIncrease(FWPerHead)
# get the accumulated fresh weight per head during the simulation period
WAccumulatedFreshWeightIncrease = Lettuce.getAccumulatedFreshWeightIncrease(FWPerHead)
# get the harvested weight per head
WHarvestedFreshWeight = Lettuce.getHarvestedFreshWeight(FWPerHead)
# print("FWPerHead.shape:{}".format(FWPerHead.shape))
# print("WFreshWeightIncrease.shape:{}".format(WFreshWeightIncrease.shape))
# print("WAccumulatedFreshWeightIncrease.shape:{}".format(WAccumulatedFreshWeightIncrease.shape))
# print("WHarvestedFreshWeight.shape:{}".format(WHarvestedFreshWeight.shape))
# np.set_printoptions(threshold=np.inf)
# print("FWPerHead:{}".format(FWPerHead))
# print("WHarvestedFreshWeight:{}".format(WHarvestedFreshWeight))
# np.set_printoptions(threshold=1000)
return FWPerHead, WFreshWeightIncrease, WAccumulatedFreshWeightIncrease, WHarvestedFreshWeight
# np.set_printoptions(threshold=np.inf)
# print("Xsdw:{}".format(Xsdw))
# print("Xnsdw:{}".format(Xnsdw))
# print("DW:{}".format(DW))
# print("FWPerHead:{}".format(FWPerHead))
# np.set_printoptions(threshold=100)
###################################################
# From here, we consider the summer period ########
###################################################
def resetInitialWeights(i, initialXsdw, initialXnsdw):
# reset the weights
return initialXsdw * np.ones(2 * constant.hourperDay), initialXnsdw * np.ones(2 * constant.hourperDay),\
initialXsdw * np.ones(2 * constant.hourperDay) + initialXnsdw * np.ones(2 * constant.hourperDay)
|
{"/OPVFilm.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/ShadingCurtain.py"], "/CropElectricityYieldProfitMINLP.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelS_Pearson1997.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/PlantGrowthModelS_Pearson1997Constant.py", "/Lettuce.py"], "/GreenhouseEnergyBalanceConstant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/Util.py": ["/CropElectricityYeildSimulatorConstant.py"], "/SolarIrradianceMultiSpanRoof.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/GreenhouseEnergyBalance.py": ["/Lettuce.py", "/CropElectricityYeildSimulatorConstant.py", "/GreenhouseEnergyBalanceConstant.py", "/Util.py"], "/SimulatorMain.py": ["/CropElectricityYeildSimulator1.py", "/Util.py", "/CropElectricityYeildSimulatorConstant.py"], "/CropElectricityYieldProfitRLShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/ShadingCurtain.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/PlantGrowthModelValidation.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulator1.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/CropElectricityYeildSimulatorDetail.py", "/SimulatorClass.py"], "/CropElectricityYeildSimulatorDetail.py": ["/ShadingCurtain.py", "/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/OPVFilm.py", "/Lettuce.py", "/PlantGrowthModelS_Pearson1997.py", "/SolarIrradianceMultiSpanRoof.py", "/GreenhouseEnergyBalance.py"], "/PlantGrowthModelS_Pearson1997Constant.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/SimulatorClass.py": ["/CropElectricityYeildSimulatorConstant.py"], "/Lettuce.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py"], "/plantGrowthModelE_J_VanHenten.py": ["/CropElectricityYeildSimulatorConstant.py", "/Util.py", "/Lettuce.py", "/PlantGrowthModelE_J_VanHentenConstant.py"]}
|
8,678
|
lopamd/FAQ-semantic-matching
|
refs/heads/master
|
/faq_config.py
|
import csv
import base_objects
import nlp_config
import sys
class FAQReader( object ):
"""Abstract class. Please implement fetch to return a list of QAPairs."""
def fetch( self ):
raise NotImplementedError("Class %s doesn't implement fetch()" % (self.__class__.__name__))
class CSVFAQReader( FAQReader ):
def __init__(self, csvfilename):
self.csvfilename = csvfilename
def fetch( self ):
faqs = []
encoding = 'mac_roman' if sys.platform == 'darwin' else None
with open(self.csvfilename, encoding=encoding) as csvfile:
areader = csv.reader(csvfile)
for row in areader:
faqs.append(base_objects.QAPair(row[0].strip(), row[1].strip()))
return faqs
def getFAQs():
faqreader = CSVFAQReader(nlp_config.faq_input_file)
return faqreader.fetch()
def getEvaluationQns():
faqreader = CSVFAQReader(nlp_config.evaluation_input_file)
return faqreader.fetch()
#Usage:
#import faq_config
#for y in faq_config.getFAQs():
# print(y.question)
# print(y.answer)
|
{"/faq_config.py": ["/base_objects.py", "/nlp_config.py"], "/part4tester.py": ["/better_objects.py", "/faq_config.py", "/lesk.py", "/nlp_config.py", "/base_objects.py"], "/faq_nlp.py": ["/nltk_objects.py", "/faq_config.py", "/base_objects.py", "/nlp_algo.py", "/nlp_eval.py", "/nlp_config.py", "/better_objects.py", "/part4tester.py"], "/better_objects.py": ["/base_objects.py", "/nltk_objects.py"], "/nltk_objects.py": ["/base_objects.py", "/nlp_config.py"], "/serialize_synsets.py": ["/nltk_objects.py", "/faq_config.py", "/lesk.py"], "/nlp_eval.py": ["/nltk_objects.py", "/faq_config.py", "/base_objects.py", "/nlp_algo.py", "/better_objects.py", "/part4tester.py"], "/tester.py": ["/nltk_objects.py", "/faq_config.py"], "/serialize_tests.py": ["/nltk_objects.py", "/faq_config.py"]}
|
8,679
|
lopamd/FAQ-semantic-matching
|
refs/heads/master
|
/lesk.py
|
import nltk
from nltk.corpus import wordnet as wn
nltk.download('wordnet')
nltk.download('stopwords')
stops = set(nltk.corpus.stopwords.words('english'))
lemmatizer = nltk.stem.wordnet.WordNetLemmatizer()
def remove_lemma_and_stops(lemmas, lemma):
return {x for x in lemmas if x != lemma and x not in stops and x is not None}
def compute_overlap(synset, lemma_set, lemma):
def get_lemma_set(text):
#tokenize, lemmatize, and remove stops
ret = [lemmatizer.lemmatize(x) for x in nltk.word_tokenize(text)]
return remove_lemma_and_stops(ret, lemma)
def get_lemma_set_from_synset():
ret = get_lemma_set(synset.definition())
for example in synset.examples():
ret |= get_lemma_set(example)
return ret
synsets_lemmas = get_lemma_set_from_synset()
return len(synsets_lemmas & lemma_set)
#get the synset that most closely matches a lemma
#need to modify to allow restriction to a specific part of speech
def get_lemma_synset(lemma, lemma_neighbors):
lemma_set = remove_lemma_and_stops(lemma_neighbors, lemma)
synsets = wn.synsets(lemma)
if not synsets:
return None
best_option = (synsets[0], 0) #best synset, best overlap
for candidate_syn in synsets:
overlap_value = compute_overlap(candidate_syn, lemma_set, lemma)
if overlap_value > best_option[1]:
best_option = (candidate_syn, overlap_value)
return best_option[0]
#takes a textfeatureextraction object
def get_synsets_from_features(tfe):
return [get_lemma_synset(lemma, tfe.lemmas) for lemma in tfe.lemmas]
|
{"/faq_config.py": ["/base_objects.py", "/nlp_config.py"], "/part4tester.py": ["/better_objects.py", "/faq_config.py", "/lesk.py", "/nlp_config.py", "/base_objects.py"], "/faq_nlp.py": ["/nltk_objects.py", "/faq_config.py", "/base_objects.py", "/nlp_algo.py", "/nlp_eval.py", "/nlp_config.py", "/better_objects.py", "/part4tester.py"], "/better_objects.py": ["/base_objects.py", "/nltk_objects.py"], "/nltk_objects.py": ["/base_objects.py", "/nlp_config.py"], "/serialize_synsets.py": ["/nltk_objects.py", "/faq_config.py", "/lesk.py"], "/nlp_eval.py": ["/nltk_objects.py", "/faq_config.py", "/base_objects.py", "/nlp_algo.py", "/better_objects.py", "/part4tester.py"], "/tester.py": ["/nltk_objects.py", "/faq_config.py"], "/serialize_tests.py": ["/nltk_objects.py", "/faq_config.py"]}
|
8,680
|
lopamd/FAQ-semantic-matching
|
refs/heads/master
|
/part4tester.py
|
import better_objects as b
import faq_config
import random
import sys
import lesk
import nlp_config
import base_objects
from nltk.parse.stanford import StanfordDependencyParser
from nltk.corpus import wordnet_ic
import numpy as np
brown_ic = wordnet_ic.ic('ic-brown.dat')
'''test_questions = [
"When is hummingbird season?",
"Where do hummingbirds go in the winter?",
"Where do hummingbirds live?",
"What is the reproduction process like for hummingbirds?",
"How fast does a hummingbird fly?",
"Do hummingbirds damage flowers?",
"Do hummingbirds reuse their nest?",
"How much nectar does a hummingbird consume in a day?",
"Do hummingbirds eat termites?",
"What is a hummingbird's lifecycle?"]
"What do hummingbirds eat?",
"When do hummingbirds nest?",
"Does a hummingbird find flowers by smell?",
"How fast do hummingbird wings beat? How do they move?",
"How fast do hummingbird hearts beat?",
"How long does a hummingbird live?",
"How many species are there?",
"What makes a hummingbird's throat bright and colorful?",
"Can hummingbirds walk?",
"What is the smallest hummingbird?",
"How many feathers do hummingbirds have?",
"What part of a hummingbird weighs the most?",
"How big are a hummingbird's eggs?",
"How many breaths does a hummingbird take per minute?",
"How far can a hummingbird fly during migration?",
"Do hummingbirds sit on the backs of other birds during migration?",
"Can hummingbirds smell?",
"How do humminbirds eat nectar?",
"How fast can a hummingbird lick?",
"How quickly do humminbirds digest nectar?",
"Is there cross-breeding between species?",
"Are hummingbirds aggressive?",
"What is the longest bill a hummingbird can have?",
"Are hummingbirds found in the Eastern Hemisphere?",
"What threats are posed to hummingbirds today?"]
best_answers = [ix + 1 for ix in range(len(test_questions))]'''
test_questions = [
"What is the length of time that hummingbirds will be alive?",
"How many genera or sorts of hummingbirds can one find?",
"Is the hue of the larynx influenced by external factors?",
"What do they use their appendiges for and how do they move around?",
"How little can hummingbirds get and what is the length?",
"How much plumage do these birds have and is that amount high?",
"What which muscle has the greatest percentage of weight?",
"Is it true that a hummingbird lays the tiniest of ova?",
"What is the rate of breath intake for hummingbirds?",
"What is the farthest a hummingbird flies when it migrates?"
]
best_answers = [16 + ix for ix in range(10)]
#final_weights = [0.952926181485045, 0.9840099977685615, 1.0525210561258025, 1.051562827464642, 0.9532682412234448, 0.9520219911127934,
# 0.969117385075304, 0.9546066017400465, 1.013167700035129, 0.961371876331083, 0.9305470016082897, 0.9575960964407408,
# 1.0226004255054897, 0.9374376883134267, 1.0016046379331374, 1.0733357426136956, 0.9578154508191105, 0.9684130290554245,
# 0.9229061653172881]
final_weights = [0.7490120039192232, 0.5473259606903345, 0.7201503022341168, 1.1039197157559848, 0.5381058876841468, 0.543439633895209, 0.6933861804185498, 0.32936031784864706, 0.5162382838863742, 0.619586214260726, 1.1842453368513972, 0.40318774451844286, 1.531198544790128, 0.44753838998751644, 0.5750546156748142, 1.529495292317564, 0.5975599793129092, 0.5244313444345968, 0.5864861033072415, 0.4288517647857363, 0.45599724465641506]
#TODO: this should be in a central place
dependency_parser = StanfordDependencyParser(path_to_jar=nlp_config.path_to_stanford_jar, path_to_models_jar=nlp_config.path_to_stanford_models_jar)
class Annealer(object):
#all of the parameters are functions. e = energy, lower is better. p = probability.
def __init__(self, neighbor, e, p, temperature):
self.neighbor = neighbor
self.e = e
self.p = p
self.temperature = temperature
max_temp = 100
def neighbor(s, adj_min = 0.001, adj_max = 0.01):
#random index, random minor adjustment
idx = random.randrange(len(s.weights))
adj = random.uniform(adj_min, adj_max)
if random.randrange(2) == 0:
adj *= -1
new_weights = [w for w in s.weights]
new_weights[idx] += adj
return new_weights
#larger e is bad
#larger change in e is bad
#smaller temperature is bad (in terms of accepting the change)
def probability(e, e_prime, temperature):
if e_prime < e:
return 1
return (1 - (e_prime - e)) * temperature / max_temp
#between 0 and max_temp
def temperature(time): #time is k / kmax
return (1 - time) * max_temp
#needs to be between 0 and 1
def energy(state, weights):
all_scores = state.get_scores(weights)
total = 0
for ix, q_score_set in enumerate(all_scores):
total += q_score_set[state.best_choices[ix]]
return 1 - (total / len(all_scores))
#slot = 0
#x = sorted([(val, key) for key, val in scores.items()], reverse=True)
#for xx in x:
# if xx[1] == state.best_answer:
# break
# slot += 1
#super simple energy function. invert the score
#this is probably too naive, but we will try it.
#return (1 - scores[state.best_answer])# * slot / len(x)
def get_jcn_similarity(feat_a, feat_b, pos):
jcn_feature = []
for qsyn in feat_a.synsets:
if qsyn.pos() == pos:
for asyn in feat_b.synsets:
if asyn.pos() == pos:
similarity = qsyn.jcn_similarity(asyn, brown_ic)
if similarity > 1: #identical words are 1e+300 and it's causing infiniti errors
similarity = 1 #1 is the greatest a similarity can be because of the normalization
jcn_feature.append(similarity)
jcn_normalize = [1] * len(jcn_feature)
jcn_result = 0
if len(jcn_feature) > 0:
jcn_result = np.linalg.norm(jcn_feature) / np.linalg.norm(jcn_normalize)
return jcn_result
class State(object):
def __init__(self, qs_features, as_features, weights, best_choices):
self.weights = weights #never used
self.best_choices = best_choices
self.score_vectors = []
self.faq_feat = as_features
for qf in qs_features:
list_of_score_vectors = []
for af in as_features:
qa_score_vector = [get_score_simple(qf.tokens, af.tokens),
get_score_simple(qf.tokens_no_stops, af.tokens_no_stops),
get_score_simple(qf.lemmas, af.lemmas),
get_score_simple(qf.stems, af.stems),
get_score_simple(qf.pos_tags, af.pos_tags),
get_score_simple(qf.synset_lemmas, af.synset_lemmas),
get_score_simple(qf.antonym_lemmas, af.antonym_lemmas),
get_score_simple(qf.hyponym_lemmas, af.hyponym_lemmas),
get_score_simple(qf.hypernym_lemmas, af.hypernym_lemmas),
get_score_simple(qf.part_meronym_lemmas, af.part_meronym_lemmas),
get_score_simple(qf.part_holonym_lemmas, af.part_holonym_lemmas),
get_score_simple(qf.member_meronym_lemmas, af.member_meronym_lemmas),
get_score_simple(qf.member_holonym_lemmas, af.member_holonym_lemmas),
get_score_simple(qf.substance_meronym_lemmas, af.substance_meronym_lemmas),
get_score_simple(qf.substance_holonym_lemmas, af.substance_holonym_lemmas),
get_score_simple(qf.wn_definitions, af.wn_definitions),
get_score_simple(qf.wn_examples, af.wn_examples),
get_score_simple(qf.depgraph_deps, af.depgraph_deps),
get_score_simple(qf.depgraph_rels, af.depgraph_rels),
get_jcn_similarity(qf, af, 'v'),
get_jcn_similarity(qf, af, 'n')]
list_of_score_vectors.append(qa_score_vector)
self.score_vectors.append(list_of_score_vectors)
def get_scores(self, used_weights = None):
scores = []
for sv in self.score_vectors:
specific_q_scores = dict()
for jx, subv in enumerate(sv):
effective_score = b.score_features(subv, used_weights)
specific_q_scores[jx + 1] = effective_score
scores.append(specific_q_scores)
return scores
def get_final_scores(self, used_weights = None):
scores = []
for sv in self.score_vectors:
specific_q_scores = dict()
for jx, subv in enumerate(sv):
effective_score = b.score_features(subv, used_weights)
specific_q_scores[self.faq_feat[jx].qapair] = effective_score
scores.append(specific_q_scores)
return scores
def lt_default(a, b): return a < b
def get_score_simple(arr1, arr2):
if len(arr1) == 0 or len(arr2) == 0:
return 0
math_vecs = b.get_math_vectors(arr1, arr2, lt_default)
return b.cosine_similarity(math_vecs[0], math_vecs[1])
question = "What do hummingbirds eat?"#"What is the lifecycle of a hummingbird like as it grows from birth as a child to death?"#"Describe the hummingbird's lifecycle."#"What do hummingbirds eat?"#"At what speed do hummingbirds fly in the air?"
def get_question_features(qfeat):
for qf in qfeat:
qf.synsets = lesk.get_synsets_from_features(qf)
for qf in qfeat:
qf.depgraphs = [dg for dg in dependency_parser.raw_parse(question)] #TODO: not the best way to do this. also iter to make an array
for qf in qfeat:
qf.add_wordnet_features()
qf.add_depgraph_features()
def get_faq_features(faqs):
as_features = b.get_answers_features(faqs)
#this should set up the synsets
b.load_all_synsets(as_features)
#this should set up dependency graphs
b.load_all_depgraphs(as_features)
for f in as_features:
f.add_wordnet_features()
f.add_depgraph_features()
return as_features
def train_model(faqs):
feature_count = 21 #TODO: hardcoded
learned_weights = [1] * feature_count
qs_features = [b.TextFeatureExtraction(q, base_objects.QAPair(q,"")) for q in test_questions]
get_question_features(qs_features)
faq_features = get_faq_features(faqs)
'''
We train only once and save the weights
Uncomment this if you want to change algo and train again.
'''
max_steps = 7500#25000
state = State(qs_features, faq_features, learned_weights, best_answers)#10)#11) #5)
anneal = Annealer(neighbor, energy, probability, temperature)
for k in range(max_steps):
t = anneal.temperature(k / max_steps)
new_weights = anneal.neighbor(state)
e_old = anneal.e(state, state.weights)
e_new = anneal.e(state, new_weights)
if anneal.p(e_old, e_new, t) >= random.random():
state.weights = new_weights
if k % 20 == 0:
print("k: %5d, last energy: %f. weights = %s" % (k, e_old, state.weights)) #TODO: might not be e_old
learned_weights = state.weights
print(state.weights)
return state
|
{"/faq_config.py": ["/base_objects.py", "/nlp_config.py"], "/part4tester.py": ["/better_objects.py", "/faq_config.py", "/lesk.py", "/nlp_config.py", "/base_objects.py"], "/faq_nlp.py": ["/nltk_objects.py", "/faq_config.py", "/base_objects.py", "/nlp_algo.py", "/nlp_eval.py", "/nlp_config.py", "/better_objects.py", "/part4tester.py"], "/better_objects.py": ["/base_objects.py", "/nltk_objects.py"], "/nltk_objects.py": ["/base_objects.py", "/nlp_config.py"], "/serialize_synsets.py": ["/nltk_objects.py", "/faq_config.py", "/lesk.py"], "/nlp_eval.py": ["/nltk_objects.py", "/faq_config.py", "/base_objects.py", "/nlp_algo.py", "/better_objects.py", "/part4tester.py"], "/tester.py": ["/nltk_objects.py", "/faq_config.py"], "/serialize_tests.py": ["/nltk_objects.py", "/faq_config.py"]}
|
8,681
|
lopamd/FAQ-semantic-matching
|
refs/heads/master
|
/base_objects.py
|
class QAPair:
def __init__(self, question, answer):
self.question = question
self.answer = answer
def __str__(self):
return "Question: [%s] Answer: [%s]" % (self.question, self.answer)
class QAFeatureExtraction( object ):
'''qa_pairs is a list of QAPair objects'''
def __init__( self, qa_pairs ):
self.qa_pairs = qa_pairs
self._tokens = None
self._sentence_tokens = None
self._lemmas = None
self._stems = None
self._pos_tags = None
self._dependency_graphs = None
self._synsets = None
self._bow = None #This will hold a List of Counter object of each FAQ
'''Private abstract function to tokenize the questions and answers on word boundaries'''
def _tokenize( self ):
raise NotImplementedError("Class %s doesn't implement _tokenize()" % (self.__class__.__name__))
'''Private abstract function to tokenize the questions and answers on sentence boundaries'''
def _tokenize_sentences( self ):
raise NotImplementedError("Class %s doesn't implement _tokenize_sentences()" % (self.__class__.__name__))
'''Private abstract function to lemmatize the questions and answers'''
def _lemmatize( self ):
raise NotImplementedError("Class %s doesn't implement _lemmatize()" % (self.__class__.__name__))
'''Private abstract function to stem the questions and answers'''
def _stem( self ):
raise NotImplementedError("Class %s doesn't implement _stem()" % (self.__class__.__name__))
'''Private abstract function to pos tag the questions and answers'''
def _pos_tag( self ):
raise NotImplementedError("Class %s doesn't implement _pos_tag()" % (self.__class__.__name__))
'''Private abstract function to graph the dependencies for the questions and answers'''
def _graph_dependencies( self ):
raise NotImplementedError("Class %s doesn't implement _graph_dependencies()" % (self.__class__.__name__))
'''Private abstract function to get wordnet synsets for the lemmas in the questions and answers'''
def _get_synsets( self ):
raise NotImplementedError("Class %s doesn't implement _get_synsets()" % (self.__class__.__name__))
'''Private abstract function to get bag of words the questions and answers'''
def _get_bow( self ):
raise NotImplementedError("Class %s doesn't implement _get_synsets()" % (self.__class__.__name__))
@property
def tokens(self):
if self._tokens is None:
self._tokenize()
return self._tokens
@property
def sentence_tokens(self):
if self._sentence_tokens is None:
self._tokenize_sentences()
return self._sentence_tokens
@property
def lemmas(self):
if self._lemmas is None:
self._lemmatize()
return self._lemmas
@property
def stems(self):
if self._stems is None:
self._stem()
return self._stems
@property
def pos_tags(self):
if self._pos_tags is None:
self._pos_tag()
return self._pos_tags
@property
def dependency_graphs(self):
if self._dependency_graphs is None:
self._graph_dependencies()
return self._dependency_graphs
@property
def synsets(self):
if self._synsets is None:
self._get_synsets()
return self._synsets
@property
def bow(self):
if self._bow is None:
self._get_bow()
return self._bow
|
{"/faq_config.py": ["/base_objects.py", "/nlp_config.py"], "/part4tester.py": ["/better_objects.py", "/faq_config.py", "/lesk.py", "/nlp_config.py", "/base_objects.py"], "/faq_nlp.py": ["/nltk_objects.py", "/faq_config.py", "/base_objects.py", "/nlp_algo.py", "/nlp_eval.py", "/nlp_config.py", "/better_objects.py", "/part4tester.py"], "/better_objects.py": ["/base_objects.py", "/nltk_objects.py"], "/nltk_objects.py": ["/base_objects.py", "/nlp_config.py"], "/serialize_synsets.py": ["/nltk_objects.py", "/faq_config.py", "/lesk.py"], "/nlp_eval.py": ["/nltk_objects.py", "/faq_config.py", "/base_objects.py", "/nlp_algo.py", "/better_objects.py", "/part4tester.py"], "/tester.py": ["/nltk_objects.py", "/faq_config.py"], "/serialize_tests.py": ["/nltk_objects.py", "/faq_config.py"]}
|
8,682
|
lopamd/FAQ-semantic-matching
|
refs/heads/master
|
/faq_nlp.py
|
import nltk_objects
import faq_config
import base_objects
import operator
from nlp_algo import BOWAlgorithm
from nlp_eval import MRREvaluation
from nlp_config import *
import better_objects as b
import part4tester as model
RESULTS_TOPN = 10
master_training = False
do_training = master_training
report_training = master_training
do_main = not master_training
def print_results(user_q, resultDict, algoType):
sortedResults = sorted(resultDict.items(), key=lambda x:x[1], reverse=True)
count = 0
print("***********************************************************************")
print("Given user question: ", user_q)
print("***********************************************************************")
if (algoType == CONFIG_ALGO_BOW):
print("Top 10 results from Bag of words algorithm are:")
else:
print("Top 10 results NLP Pipeline algorithm are:")
for qa_pair,score in sortedResults:
if count < RESULTS_TOPN:
print(qa_pair.answer,score)
count = count + 1
def print_eval_result(evalObj, algoType):
if algoType == CONFIG_ALGO_BOW:
algoName = "BagOfWords"
else:
algoName = "NLP Pipeline"
print("***********************************************************************")
print("MRR EVALUATION for algorithm: ", algoName)
print("***********************************************************************")
print (evalObj.get_rr())
print ('------------------------------------------------------------')
print ("Total MRR of the QA Set: ",evalObj.get_mrr())
def run_mrr(faq_feat,algoType):
evaluation = MRREvaluation(algoType, faq_feat)
evaluation.computeResult()
print_eval_result(evaluation, algoType)
def run_userq(user_qa, faq_feat, algoType):
#FIXME: It has to be added to the empty list because nltk_object operates on the list
#Alt: Alternate approach. Only call __tokenize(). But move stops to a class variable.
user_q = user_qa[0].question
if (algoType == CONFIG_ALGO_BOW):
#BOW specific implementation.
uq_bow_feat = nltk_objects.NLTKFeatureExtraction(user_qa)
bow_algo = BOWAlgorithm(user_q, uq_bow_feat, faq_feat)
resultDict = bow_algo._compute()
else:
#NLP Pipeline specific
uq_nlp_feat = [b.TextFeatureExtraction(user_q, user_qa)]
'''
Testing code
'''
tstate = model.State(uq_nlp_feat, faq_feat, model.final_weights, None)
nlp_rdict = tstate.get_final_scores(model.final_weights)
resultDict = nlp_rdict[0]
print_results(user_q, resultDict, algoType)
def space_out():
print()
print()
print()
def main():
print("****** Hummingbird FAQ engine powered by NLTK *********")
faqs = faq_config.getFAQs()
'''
TRAINING Code
'''
if do_training:
state = model.train_model(faqs)
model.final_weights = state.weights
if report_training:
all_scores = state.get_scores(state.weights)
for ix, q_score_set in enumerate(all_scores):
dict_scores = sorted([(ascore, qnum) for qnum, ascore in q_score_set.items()], reverse=True)
print(state.best_choices[ix])
for pair in dict_scores:
print("%2d: %f" % (pair[1], pair[0]))
print()
if do_main:
faq_bow_feat = nltk_objects.NLTKFeatureExtraction(faqs)
faq_nlp_feat = model.get_faq_features(faqs)
run_mrr(faq_bow_feat, CONFIG_ALGO_BOW)
space_out()
run_mrr(faq_nlp_feat, CONFIG_ALGO_NLP)
print("You can enter question multiple times. Enter quit or Ctrl+c to quit")
while 1:
#'''
space_out()
user_q = input("Enter your question or 'quit' to Exit : ")
#user_q = "when is hummingbird season"
#user_q = "Do hummingbirds migrate in winter?"
#user_q = "How fast do hummingbirds' wings beat per second?"
if user_q == "" or user_q == None:
raise ValueError("Invalid question given. Exiting")
exit(1)
elif user_q == "quit":
print("Thank you for trying out our FAQ Engine..Exiting")
exit(1)
user_qa = [base_objects.QAPair(user_q, "")]
space_out()
run_userq(user_qa, faq_bow_feat, CONFIG_ALGO_BOW)
space_out()
run_userq(user_qa, faq_nlp_feat, CONFIG_ALGO_NLP)
if __name__ == "__main__":
main()
|
{"/faq_config.py": ["/base_objects.py", "/nlp_config.py"], "/part4tester.py": ["/better_objects.py", "/faq_config.py", "/lesk.py", "/nlp_config.py", "/base_objects.py"], "/faq_nlp.py": ["/nltk_objects.py", "/faq_config.py", "/base_objects.py", "/nlp_algo.py", "/nlp_eval.py", "/nlp_config.py", "/better_objects.py", "/part4tester.py"], "/better_objects.py": ["/base_objects.py", "/nltk_objects.py"], "/nltk_objects.py": ["/base_objects.py", "/nlp_config.py"], "/serialize_synsets.py": ["/nltk_objects.py", "/faq_config.py", "/lesk.py"], "/nlp_eval.py": ["/nltk_objects.py", "/faq_config.py", "/base_objects.py", "/nlp_algo.py", "/better_objects.py", "/part4tester.py"], "/tester.py": ["/nltk_objects.py", "/faq_config.py"], "/serialize_tests.py": ["/nltk_objects.py", "/faq_config.py"]}
|
8,683
|
lopamd/FAQ-semantic-matching
|
refs/heads/master
|
/nlp_algo.py
|
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
from collections import defaultdict
class NLPAlgorithm:
def __init__(self, uquestion, qfeat, docfeat):
self.user_question = uquestion
#This will contain the qapair:score
self.scoreDict = defaultdict()
self.qafeat = qfeat
self.docs_feature = docfeat
#Final results
self.results = list()
'''Private abstract function to implement the actual algorithm'''
def _compute(self):
raise NotImplementedError("Class %s doesn't implement _compute()" % (self.__class__.__name__))
'''Private abstract function to evaluate the output'''
def _evaluate(self):
raise NotImplementedError("Class %s doesn't implement _evaluate()" % (self.__class__.__name__))
'''Function to print the output'''
def _print(self):
print("Final Score is " + self.score)
class BOWAlgorithm(NLPAlgorithm):
def __init__(self, uquestion, qfeat, docfeat):
super().__init__(uquestion, qfeat, docfeat)
def __compute_cosine(self, query, doc):
query = np.array(query).reshape(1,-1)
doc = np.array(doc).reshape(1,-1)
return cosine_similarity(query, doc)
def _compute(self):
'''
TODO: QAFeatureExtraxction object has qa_pairs and _bow in the same order.
This works as both are sequentially accessed. So _bow index can be used to
access corresponding qa_pair
'''
query_vec = list(self.qafeat.bow[0].values())
for index, faq_bow in enumerate(self.docs_feature.bow):
faq_vec = []
for word in self.qafeat.bow[0]:
if word in faq_bow:
faq_vec.append(faq_bow[word])
else:
faq_vec.append(0)
if len(faq_vec) != 0:
#cosine similarity returns in numpy array. Convert it into regular val
simScore = self.__compute_cosine(query_vec, faq_vec).tolist()[0][0]
self.scoreDict[self.docs_feature.qa_pairs[index]] = simScore
else:
print("No matching words found")
return self.scoreDict
def _evaluate(self):
#Use the Evaluation objects here
pass
|
{"/faq_config.py": ["/base_objects.py", "/nlp_config.py"], "/part4tester.py": ["/better_objects.py", "/faq_config.py", "/lesk.py", "/nlp_config.py", "/base_objects.py"], "/faq_nlp.py": ["/nltk_objects.py", "/faq_config.py", "/base_objects.py", "/nlp_algo.py", "/nlp_eval.py", "/nlp_config.py", "/better_objects.py", "/part4tester.py"], "/better_objects.py": ["/base_objects.py", "/nltk_objects.py"], "/nltk_objects.py": ["/base_objects.py", "/nlp_config.py"], "/serialize_synsets.py": ["/nltk_objects.py", "/faq_config.py", "/lesk.py"], "/nlp_eval.py": ["/nltk_objects.py", "/faq_config.py", "/base_objects.py", "/nlp_algo.py", "/better_objects.py", "/part4tester.py"], "/tester.py": ["/nltk_objects.py", "/faq_config.py"], "/serialize_tests.py": ["/nltk_objects.py", "/faq_config.py"]}
|
8,684
|
lopamd/FAQ-semantic-matching
|
refs/heads/master
|
/better_objects.py
|
import nltk
import base_objects
import nltk_objects
from collections import Counter
import sklearn.metrics
import numpy as np
from nltk.corpus import wordnet as wn
from nltk.parse.dependencygraph import DependencyGraph
synset_folder = 'data/synsets/'
synset_filename_format = "%d_%s.txt" #%d is from 1 to 50, %s is question or answer
depgraph_folder = 'data/depgraphs/'
depgraph_filename_format = "%d_%s.conll" #%d is from 1 to 50, %s is question or answer
#TODO: normalize words??
#TODO: do lemmatize and stem need context?? tokens were already sorted
stops = set(nltk.corpus.stopwords.words('english'))
lemmatizer = nltk.stem.wordnet.WordNetLemmatizer()
stemmer = nltk.stem.PorterStemmer()
flatten = lambda l: [item for sublist in l for item in sublist]
#array of array of sorted answer tokens.
def do_tokenize(text):
return sorted(nltk.word_tokenize(text))
#array of array of sorted answer tokens, not including stop words.
def do_tokenize_no_stops(tokens):
return [w for w in tokens if w not in stops]
#array of array of sorted lemmas including stop words
def do_lemmatize(tokens):
return [lemmatizer.lemmatize(w) for w in tokens]
#array of array of sorted stems including stop words
def do_stem(tokens):
return [stemmer.stem(w) for w in tokens]
#array of array of tuples of the form ('word', 'pos')
def do_pos_tag(text):
return sorted(nltk.pos_tag(nltk.word_tokenize(text)))
class TextFeatureExtraction(object):
def __init__(self, text,qapair):
self.tokens = do_tokenize(text)
self.tokens_no_stops = do_tokenize_no_stops(self.tokens)
self.lemmas = do_lemmatize(self.tokens)
self.stems = do_stem(self.tokens)
self.pos_tags = do_pos_tag(text)
self.synsets = []
self.depgraphs = []
self.depgraph_deps = []
self.depgraph_rels = []
self.synset_lemmas = []
self.antonym_lemmas = []
self.hyponym_lemmas = []
self.hypernym_lemmas = []
self.part_meronym_lemmas = []
self.part_holonym_lemmas = []
self.member_meronym_lemmas = []
self.member_holonym_lemmas = []
self.substance_meronym_lemmas = []
self.substance_holonym_lemmas = []
self.wn_definitions = [] #just going to be a list of words
self.wn_examples = [] #just going to be a list of words
self.qapair = qapair
def add_wordnet_features(self):
#TODO: hack. do this better
self.synsets = [s for s in self.synsets if s is not None]
self.load_all_wordnet_lemmas()
self.load_all_wordnet_definitions()
self.load_all_wordnet_examples()
def load_all_wordnet_definitions(self):
self.wn_definitions = flatten([s.definition().split() for s in self.synsets])
def load_all_wordnet_examples(self):
for s in self.synsets:
self.wn_definitions.extend(flatten([e.split() for e in s.examples()]))
#grab all lemmas from wordnet possible
def load_all_wordnet_lemmas(self):
def internal_synset_lemmas(syns):
return flatten([s.lemma_names() for s in syns])
for s in self.synsets:
self.synset_lemmas.extend(s.lemma_names())
for lemma in s.lemmas():
self.antonym_lemmas.extend([a.name() for a in lemma.antonyms()])
self.hyponym_lemmas.extend(internal_synset_lemmas(s.hyponyms()))
self.hypernym_lemmas.extend(internal_synset_lemmas(s.hypernyms()))
self.part_meronym_lemmas.extend(internal_synset_lemmas(s.part_meronyms()))
self.part_holonym_lemmas.extend(internal_synset_lemmas(s.part_holonyms()))
self.member_meronym_lemmas.extend(internal_synset_lemmas(s.member_meronyms()))
self.member_holonym_lemmas.extend(internal_synset_lemmas(s.member_holonyms()))
self.substance_meronym_lemmas.extend(internal_synset_lemmas(s.substance_meronyms()))
self.substance_holonym_lemmas.extend(internal_synset_lemmas(s.substance_holonyms()))
def add_depgraph_features(self):
#('firstword', 'secondword', 'dependency')
for dg in self.depgraphs:
for addr, item in dg.nodes.items():
for dep, depaddr in item['deps'].items():
if len(depaddr) > 0:
item_lemma = item['lemma']
if item_lemma is None:
item_lemma = ""
self.depgraph_deps.append((item_lemma, dep, dg.nodes[depaddr[0]]['lemma']))
#('word', 'relation')
for dg in self.depgraphs:
for item in dg.nodes.values():
if item['lemma'] != "" and item['lemma'] is not None and item['rel'] != "" and item['rel'] is not None:
self.depgraph_rels.append((item['lemma'], item['rel']))
#takes a text feature extraction and a filename and hooks you up with the synsets
def add_synsets(tfe, filename):
lines = [line.rstrip('\n') for line in open(filename)]
synset_names = [line.split()[1] for line in lines] #grab the synset names
tfe.synsets.extend([wn.synset(synset_name) for synset_name in synset_names])
#TODO: consolidate load_all_synsets and load_all_depgraphs
def load_all_synsets(tfes):
current = 1
for tfe in tfes:
filename_question = synset_folder + (synset_filename_format % (current, "question"))
filename_answer = synset_folder + (synset_filename_format % (current, "answer"))
add_synsets(tfe, filename_question)
add_synsets(tfe, filename_answer)
current += 1
def load_all_depgraphs(tfes):
current = 1
for tfe in tfes:
filename_question = depgraph_folder + (depgraph_filename_format % (current, "question"))
filename_answer = depgraph_folder + (depgraph_filename_format % (current, "answer"))
graphs_question = DependencyGraph.load(filename_question)
graphs_answer = DependencyGraph.load(filename_answer)
tfe.depgraphs = graphs_question + graphs_answer
def get_answers_features(qapairs):
ret = []
for qa in qapairs:
ret.append(TextFeatureExtraction("%s %s" % (qa.question, qa.answer), qa))
return ret
def get_math_vectors(items_one, items_two, lt):
counters = (Counter(items_one), Counter(items_two))
#sort because we're going to be walking the lists
items = (sorted(counters[0].items()), sorted(counters[1].items()))
vectors = ([], [])
key_indices = (0, 0)
while key_indices[0] < len(items[0]) and key_indices[1] < len(items[1]):
itempair = (items[0][key_indices[0]], items[1][key_indices[1]])
if lt(itempair[0][0], itempair[1][0]): #comparing the keys
vectors[0].append(itempair[0][1]) #add the count to the math vector
vectors[1].append(0)
key_indices = (key_indices[0] + 1, key_indices[1])
elif lt(itempair[1][0], itempair[0][0]):
vectors[0].append(0)
vectors[1].append(itempair[1][1]) #add the count to the math vector
key_indices = (key_indices[0], key_indices[1] + 1)
else:
vectors[0].append(itempair[0][1]) #add the count to the math vector
vectors[1].append(itempair[1][1]) #add the count to the math vector
key_indices = (key_indices[0], key_indices[1] + 1)
while key_indices[0] < len(items[0]):
vectors[0].append(items[0][key_indices[0]][1]) #add the count to the math vector
vectors[1].append(0)
key_indices = (key_indices[0] + 1, key_indices[1])
while key_indices[1] < len(items[1]):
vectors[0].append(0)
vectors[1].append(items[1][key_indices[1]][1]) #add the count to the math vector
key_indices = (key_indices[0], key_indices[1] + 1)
return vectors
def cosine_similarity(a, b):
#the semantics of cosine_similarity are annoying.
#it must make sense in general because it's really annoying.
return sklearn.metrics.pairwise.cosine_similarity([a], [b])[0][0] #seriously, it's a number in a nested array
#a and b are already scored vectors
def score_features(scores, weights):
weighted_sims = [c * d for c, d in zip(scores, weights)]
return np.linalg.norm(weighted_sims) / np.linalg.norm(weights)
|
{"/faq_config.py": ["/base_objects.py", "/nlp_config.py"], "/part4tester.py": ["/better_objects.py", "/faq_config.py", "/lesk.py", "/nlp_config.py", "/base_objects.py"], "/faq_nlp.py": ["/nltk_objects.py", "/faq_config.py", "/base_objects.py", "/nlp_algo.py", "/nlp_eval.py", "/nlp_config.py", "/better_objects.py", "/part4tester.py"], "/better_objects.py": ["/base_objects.py", "/nltk_objects.py"], "/nltk_objects.py": ["/base_objects.py", "/nlp_config.py"], "/serialize_synsets.py": ["/nltk_objects.py", "/faq_config.py", "/lesk.py"], "/nlp_eval.py": ["/nltk_objects.py", "/faq_config.py", "/base_objects.py", "/nlp_algo.py", "/better_objects.py", "/part4tester.py"], "/tester.py": ["/nltk_objects.py", "/faq_config.py"], "/serialize_tests.py": ["/nltk_objects.py", "/faq_config.py"]}
|
8,685
|
lopamd/FAQ-semantic-matching
|
refs/heads/master
|
/nltk_objects.py
|
import base_objects
import nlp_config
import nltk
from collections import Counter
from nltk.parse.stanford import StanfordDependencyParser
from nltk.corpus import wordnet as wn
nltk.download('punkt')
nltk.download('wordnet')
nltk.download('stopwords')
nltk.download('averaged_perceptron_tagger')
dependency_parser = StanfordDependencyParser(path_to_jar=nlp_config.path_to_stanford_jar, path_to_models_jar=nlp_config.path_to_stanford_models_jar)
def penn2morphy(penntag, returnNone=False):
morphy_tag = {'NN':wn.NOUN, 'JJ':wn.ADJ,
'VB':wn.VERB, 'RB':wn.ADV}
try:
return morphy_tag[penntag[:2]]
except:
return None if returnNone else ''
def get_synset_name(lemma, pos, num=1):
return "%s.%s.%02d" % (lemma, pos, num)
class NLTKFeatureExtraction( base_objects.QAFeatureExtraction ):
def __init__( self, qa_pairs ):
super().__init__(qa_pairs)
'''
TODO: We may need to refactor rest of the functions as well if we have extract the features for given quesiton
The other approach is to not make answer mandatory so that we can extract features only for questions!
'''
def __tokenize_text( self, text, stops ):
return [w for w in nltk.word_tokenize(text) if w not in stops]
def _tokenize( self ):
self._tokens = []
stops = set(nltk.corpus.stopwords.words(nlp_config.default_locale))
for qa in self.qa_pairs:
question_tokens = self.__tokenize_text(qa.question, stops)
answer_tokens = self.__tokenize_text(qa.answer, stops)
self._tokens.append((question_tokens, answer_tokens))
def _get_bow( self ):
self._bow = []
for tokenpair in self.tokens:
#FIXME: We need to create one bow for both q & a ??
self._bow.append(Counter(tokenpair[0] + tokenpair[1]))
def _tokenize_sentences( self ):
self._sentence_tokens = []
for qa in self.qa_pairs:
question_sentences = nltk.sent_tokenize(qa.question)
answer_sentences = nltk.sent_tokenize(qa.answer)
self._sentence_tokens.append((question_sentences, answer_sentences))
def _lemmatize( self ):
self._lemmas = []
lemmatizer = nltk.stem.wordnet.WordNetLemmatizer()
for tokenpair in self.tokens:
question_lemmas = [lemmatizer.lemmatize(x) for x in tokenpair[0]]
answer_lemmas = [lemmatizer.lemmatize(x) for x in tokenpair[1]]
self._lemmas.append((question_lemmas, answer_lemmas))
def _stem( self ):
self._stems = []
stemmer = nltk.stem.PorterStemmer()
for tokenpair in self.tokens:
question_stems = [stemmer.stem(x) for x in tokenpair[0]]
answer_stems = [stemmer.stem(x) for x in tokenpair[1]]
self._stems.append((question_stems, answer_stems))
def _pos_tag( self ):
self._pos_tags = []
for tokenpair in self.sentence_tokens:
question_word_tokens = [nltk.word_tokenize(sentence) for sentence in tokenpair[0]]
answer_word_tokens = [nltk.word_tokenize(sentence) for sentence in tokenpair[1]]
question_pos_tags = [nltk.pos_tag(sentence) for sentence in question_word_tokens]
answer_pos_tags = [nltk.pos_tag(sentence) for sentence in answer_word_tokens]
self._pos_tags.append((question_pos_tags, answer_pos_tags))
def _graph_dependencies( self ):
self._dependency_graphs = []
for tokenpair in self.sentence_tokens:
question_graph = [dependency_parser.raw_parse(sentence) for sentence in tokenpair[0]]
answer_graph = [dependency_parser.raw_parse(sentence) for sentence in tokenpair[1]]
self._dependency_graphs.append((question_graph, answer_graph))
#the result of this function is 2-tuples of arrays of arrays of synsets. each inner array is one sentence.
#the first outer array in a 2-tuple is for the questions. the second outer array is for the answers.
#
#to get the rest of the relations, you can use:
# syn.hypernyms()
# .hyponyms()
# .part_meronyms()
# .substance_meronyms()
# .part_holonyms()
# .substance_holonyms()
def _get_synsets( self ):
self._synsets = []
lemmatizer = nltk.stem.wordnet.WordNetLemmatizer()
for qa_pos_tags in self.pos_tags:
#qa_pos_tags[0] is an array of arrays of pos tags for the question sentences. ('constructor', 'NN')
#qa_pos_tags[1] is an array of arrays of pos tags for the answers sentences.
def get_synsets_for_pos_tags(a_pos_tags):
ret_synsets = []
for word_pos_pair in a_pos_tags:
wordnet_pos = penn2morphy(word_pos_pair[1])
if wordnet_pos:
try:
ret_synsets.append(wn.synset(get_synset_name(lemmatizer.lemmatize(word_pos_pair[0]), wordnet_pos)))
except:
ret_synsets.append(None) #not sure if we should append none or just pass
return ret_synsets
q_sentence_synsets = [get_synsets_for_pos_tags(sentence_tags) for sentence_tags in qa_pos_tags[0]]
a_sentence_synsets = [get_synsets_for_pos_tags(sentence_tags) for sentence_tags in qa_pos_tags[1]]
self._synsets.append((q_sentence_synsets, a_sentence_synsets))
|
{"/faq_config.py": ["/base_objects.py", "/nlp_config.py"], "/part4tester.py": ["/better_objects.py", "/faq_config.py", "/lesk.py", "/nlp_config.py", "/base_objects.py"], "/faq_nlp.py": ["/nltk_objects.py", "/faq_config.py", "/base_objects.py", "/nlp_algo.py", "/nlp_eval.py", "/nlp_config.py", "/better_objects.py", "/part4tester.py"], "/better_objects.py": ["/base_objects.py", "/nltk_objects.py"], "/nltk_objects.py": ["/base_objects.py", "/nlp_config.py"], "/serialize_synsets.py": ["/nltk_objects.py", "/faq_config.py", "/lesk.py"], "/nlp_eval.py": ["/nltk_objects.py", "/faq_config.py", "/base_objects.py", "/nlp_algo.py", "/better_objects.py", "/part4tester.py"], "/tester.py": ["/nltk_objects.py", "/faq_config.py"], "/serialize_tests.py": ["/nltk_objects.py", "/faq_config.py"]}
|
8,686
|
lopamd/FAQ-semantic-matching
|
refs/heads/master
|
/serialize_synsets.py
|
import nltk_objects as no
import faq_config
import lesk
#shoutout to Avicii
#TODO: not sure if i need to remove stopwords before lemmatizing (ok, tokenizing does that)
# but i'm not sure if tokenizing should do that........
#TODO: some words (like In) may need to be lowercased
#TODO: maybe we should leave stopwords. like "to" should be there for verbs i feel...
#TODO: words like "United States" are being tagged with synsets separately
#TODO: need to add in parts of speech. look at question 50. "build" should not be a noun
sub_folder = 'data/synsets'
faqs = faq_config.getFAQs()
feature_extractor = no.NLTKFeatureExtraction(faqs)
#flatten = lambda l: [item for sublist in l for item in sublist]
def save_synsets(lemmas, filename):
with open(filename, "w+") as outfile:
first = True
for lemma in lemmas:
lemma_synset = lesk.get_lemma_synset(lemma, lemmas)
if lemma_synset is not None:
if not first:
outfile.write('\n')
outfile.write("%s %s" % (lemma, lemma_synset.name()))
first = False
faq_number = 1
for faq_lemmas in feature_extractor.lemmas:
q_lemmas = faq_lemmas[0]
a_lemmas = faq_lemmas[1]
save_synsets(q_lemmas, "%s/%d_question.txt" % (sub_folder, faq_number))
save_synsets(a_lemmas, "%s/%d_answer.txt" % (sub_folder, faq_number))
faq_number += 1
|
{"/faq_config.py": ["/base_objects.py", "/nlp_config.py"], "/part4tester.py": ["/better_objects.py", "/faq_config.py", "/lesk.py", "/nlp_config.py", "/base_objects.py"], "/faq_nlp.py": ["/nltk_objects.py", "/faq_config.py", "/base_objects.py", "/nlp_algo.py", "/nlp_eval.py", "/nlp_config.py", "/better_objects.py", "/part4tester.py"], "/better_objects.py": ["/base_objects.py", "/nltk_objects.py"], "/nltk_objects.py": ["/base_objects.py", "/nlp_config.py"], "/serialize_synsets.py": ["/nltk_objects.py", "/faq_config.py", "/lesk.py"], "/nlp_eval.py": ["/nltk_objects.py", "/faq_config.py", "/base_objects.py", "/nlp_algo.py", "/better_objects.py", "/part4tester.py"], "/tester.py": ["/nltk_objects.py", "/faq_config.py"], "/serialize_tests.py": ["/nltk_objects.py", "/faq_config.py"]}
|
8,687
|
lopamd/FAQ-semantic-matching
|
refs/heads/master
|
/nlp_eval.py
|
import nltk_objects
import faq_config
import base_objects
import operator
from nlp_algo import BOWAlgorithm
from collections import defaultdict
import better_objects as b
import part4tester as model
TOPTEN_ANS = []
class Evaluation(object):
def __init__(self, algoType,fext):
self.scores = 0
self.count = 0
self.aType = algoType
self.rdict = defaultdict()
self.fext = fext
def get_topNResults(self, resultDict, n):
sortedResults = sorted(resultDict.items(), key=lambda x:x[1], reverse=True)
count = 0
for qa_pair,score in sortedResults:
if count < n:
TOPTEN_ANS.append(qa_pair.answer)
count = count + 1
def computeResult(self):
#For evaluation of BOW
eval_qns = faq_config.getEvaluationQns()
for qns in eval_qns:
TOPTEN_ANS.clear()
user_qa = [base_objects.QAPair(qns.question, "")]
if self.aType == 1:
#BOW Type
user_feat_extractor = nltk_objects.NLTKFeatureExtraction(user_qa)
bow_algo = BOWAlgorithm(user_qa, user_feat_extractor, self.fext)
resultDict = bow_algo._compute()
else:
uq_nlp_feat = [b.TextFeatureExtraction(qns.question, qns)]
tstate = model.State(uq_nlp_feat, self.fext, model.final_weights, None)
resultDict = tstate.get_final_scores(model.final_weights)[0]
self.get_topNResults(resultDict, 10)
index_ = TOPTEN_ANS.index(qns.answer) if qns.answer in TOPTEN_ANS else -1
print ("Question is: ",qns.question)
print ("Correct answer at index: ", index_)
print ("--------------------------------------------")
self.rdict.update({qns.question : index_+1})
class MRREvaluation(Evaluation):
def __init__(self, algoType, fext):
super().__init__(algoType, fext)
def get_rr(self):
i = 0
for key, value in self.rdict.items():
if value != 0:
rr = 1.0 / float(value)
print (key, rr)
self.scores += rr
else:
print (key, 0)
self.count += 1
# mrr
def get_mrr(self):
return self.scores / self.count
|
{"/faq_config.py": ["/base_objects.py", "/nlp_config.py"], "/part4tester.py": ["/better_objects.py", "/faq_config.py", "/lesk.py", "/nlp_config.py", "/base_objects.py"], "/faq_nlp.py": ["/nltk_objects.py", "/faq_config.py", "/base_objects.py", "/nlp_algo.py", "/nlp_eval.py", "/nlp_config.py", "/better_objects.py", "/part4tester.py"], "/better_objects.py": ["/base_objects.py", "/nltk_objects.py"], "/nltk_objects.py": ["/base_objects.py", "/nlp_config.py"], "/serialize_synsets.py": ["/nltk_objects.py", "/faq_config.py", "/lesk.py"], "/nlp_eval.py": ["/nltk_objects.py", "/faq_config.py", "/base_objects.py", "/nlp_algo.py", "/better_objects.py", "/part4tester.py"], "/tester.py": ["/nltk_objects.py", "/faq_config.py"], "/serialize_tests.py": ["/nltk_objects.py", "/faq_config.py"]}
|
8,688
|
lopamd/FAQ-semantic-matching
|
refs/heads/master
|
/tester.py
|
import nltk_objects
import faq_config
faqs = faq_config.getFAQs()
feature_extractor = nltk_objects.NLTKFeatureExtraction(faqs)
for qatoken in feature_extractor.tokens:
print(qatoken)
for qatoken in feature_extractor.sentence_tokens:
print(qatoken)
for qabow in feature_extractor.bow:
print(qabow)
for qalemma in feature_extractor.lemmas:
print(qalemma)
for qastem in feature_extractor.stems:
print(qastem)
for postag in feature_extractor.pos_tags:
print(postag)
for graphs in feature_extractor.dependency_graphs:
print(graphs)
for syns in feature_extractor.synsets:
print(syns)
'''
Test cases:
Mandatory for Q2:
1. Exact same faq question in the input: It should return the same answer
2. Couple of words missing: It should return the same answer
3. Words jumbled or transposed: It should return the same answer
4. Synonyms or similar semantic meaing: Doesn't expect to return correct answer
Q3: Should show imporovements over Q2
TODO: Write the updated test cases here
'''
|
{"/faq_config.py": ["/base_objects.py", "/nlp_config.py"], "/part4tester.py": ["/better_objects.py", "/faq_config.py", "/lesk.py", "/nlp_config.py", "/base_objects.py"], "/faq_nlp.py": ["/nltk_objects.py", "/faq_config.py", "/base_objects.py", "/nlp_algo.py", "/nlp_eval.py", "/nlp_config.py", "/better_objects.py", "/part4tester.py"], "/better_objects.py": ["/base_objects.py", "/nltk_objects.py"], "/nltk_objects.py": ["/base_objects.py", "/nlp_config.py"], "/serialize_synsets.py": ["/nltk_objects.py", "/faq_config.py", "/lesk.py"], "/nlp_eval.py": ["/nltk_objects.py", "/faq_config.py", "/base_objects.py", "/nlp_algo.py", "/better_objects.py", "/part4tester.py"], "/tester.py": ["/nltk_objects.py", "/faq_config.py"], "/serialize_tests.py": ["/nltk_objects.py", "/faq_config.py"]}
|
8,689
|
lopamd/FAQ-semantic-matching
|
refs/heads/master
|
/nlp_config.py
|
import os
CONFIG_ALGO_BOW = 1
CONFIG_ALGO_NLP = 2
default_locale = 'english'
faq_input_file = 'input/Hummingbirds.csv'
evaluation_input_file = 'input/evaluationInput.csv'
path_to_stanford_lib = r'deps/stanford-corenlp-full-2018-02-27'
path_to_stanford_jar = path_to_stanford_lib + r'/stanford-corenlp-3.9.1.jar'
path_to_stanford_models_jar = path_to_stanford_lib + r'/stanford-corenlp-3.9.1-models.jar'
|
{"/faq_config.py": ["/base_objects.py", "/nlp_config.py"], "/part4tester.py": ["/better_objects.py", "/faq_config.py", "/lesk.py", "/nlp_config.py", "/base_objects.py"], "/faq_nlp.py": ["/nltk_objects.py", "/faq_config.py", "/base_objects.py", "/nlp_algo.py", "/nlp_eval.py", "/nlp_config.py", "/better_objects.py", "/part4tester.py"], "/better_objects.py": ["/base_objects.py", "/nltk_objects.py"], "/nltk_objects.py": ["/base_objects.py", "/nlp_config.py"], "/serialize_synsets.py": ["/nltk_objects.py", "/faq_config.py", "/lesk.py"], "/nlp_eval.py": ["/nltk_objects.py", "/faq_config.py", "/base_objects.py", "/nlp_algo.py", "/better_objects.py", "/part4tester.py"], "/tester.py": ["/nltk_objects.py", "/faq_config.py"], "/serialize_tests.py": ["/nltk_objects.py", "/faq_config.py"]}
|
8,690
|
lopamd/FAQ-semantic-matching
|
refs/heads/master
|
/serialize_tests.py
|
import nltk_objects as no
import faq_config
sub_folder = 'data/depgraphs'
faqs = faq_config.getFAQs()
feature_extractor = no.NLTKFeatureExtraction(faqs)
def save_dependency_graphs(graphs, filename):
with open(filename, "w+") as outfile:
first = True
for graph in graphs:
if not first:
outfile.write('\n')
outfile.write(graph.to_conll(4))
first = False
def extract_graphs(alist):
ret = []
for iter in alist:
ret.extend([x for x in iter])
return ret
faq_number = 1
for faq_graphs in feature_extractor.dependency_graphs:
q_graphs = faq_graphs[0] #these are lists of list iterators
a_graphs = faq_graphs[1] # because parsing returns a list iterator
save_dependency_graphs(extract_graphs(q_graphs), "%s/%d_question.conll" % (sub_folder, faq_number))
save_dependency_graphs(extract_graphs(a_graphs), "%s/%d_answer.conll" % (sub_folder, faq_number))
faq_number += 1
|
{"/faq_config.py": ["/base_objects.py", "/nlp_config.py"], "/part4tester.py": ["/better_objects.py", "/faq_config.py", "/lesk.py", "/nlp_config.py", "/base_objects.py"], "/faq_nlp.py": ["/nltk_objects.py", "/faq_config.py", "/base_objects.py", "/nlp_algo.py", "/nlp_eval.py", "/nlp_config.py", "/better_objects.py", "/part4tester.py"], "/better_objects.py": ["/base_objects.py", "/nltk_objects.py"], "/nltk_objects.py": ["/base_objects.py", "/nlp_config.py"], "/serialize_synsets.py": ["/nltk_objects.py", "/faq_config.py", "/lesk.py"], "/nlp_eval.py": ["/nltk_objects.py", "/faq_config.py", "/base_objects.py", "/nlp_algo.py", "/better_objects.py", "/part4tester.py"], "/tester.py": ["/nltk_objects.py", "/faq_config.py"], "/serialize_tests.py": ["/nltk_objects.py", "/faq_config.py"]}
|
8,744
|
indapa/pgmPy
|
refs/heads/master
|
/PythonNotebooks/testCliqueTreeMaxSumCalibrate.py
|
from Factor import *
from PGMcommon import *
from CliqueTree import *
from CliqueTreeOperations import *
from FactorOperations import *
import scipy.io as sio
import numpy as np
import pprint
import pdb
matfile='/Users/amit/BC_Classes/PGM/Prog4/PA4Sample.mat'
mat_contents=sio.loadmat(matfile)
mat_struct=mat_contents['MaxSumCalibrate']
val=mat_struct[0,0]
input_edges = val['INPUT']['edges'][0][0]
#print input_edges
input_cliqueList= val['INPUT']['cliqueList'][0][0][0]
clique_list_factorObj=[]
for tpl in input_cliqueList:
(var, card, values)=tpl
f= Factor( var[0].tolist(), card[0].tolist(), values[0].tolist(), 'factor' )
#print f
clique_list_factorObj.append(f)
P=CliqueTree( clique_list_factorObj , input_edges, clique_list_factorObj, [])
P=CliqueTreeCalibrate(P,1)
for f in P.getNodeList():
print f
print "=="
|
{"/PythonNotebooks/testCliqueTreeOperations.py": ["/Factor.py", "/PGMcommon.py", "/PedigreeFactors.py", "/FactorOperations.py", "/GeneticNetworkFactory.py", "/CliqueTree.py", "/CliqueTreeOperations.py"], "/CliqueTreeOperations.py": ["/CliqueTree.py", "/FactorOperations.py"], "/GeneticNetworkFactory.py": ["/Factor.py", "/FactorOperations.py", "/PedigreeFactors.py"]}
|
8,745
|
indapa/pgmPy
|
refs/heads/master
|
/PythonNotebooks/testMaxDecoding.py
|
from Factor import *
from PGMcommon import *
from CliqueTree import *
from CliqueTreeOperations import *
from FactorOperations import *
import scipy.io as sio
import numpy as np
import pprint
import pdb
matfile='/Users/amit/BC_Classes/PGM/Prog4/PA4Sample.mat'
mat_contents=sio.loadmat(matfile)
mat_struct=mat_contents['MaxDecoded']
val=mat_struct[0,0]
input_factors = val['INPUT']
factorList=[]
for elm in input_factors:
#print ary[0]
#print
(var, card, values)=elm[0]
#print var, card, values
f= Factor( var[0].tolist(), card[0].tolist(), values[0].tolist(), 'factor' )
print f
factorList.append( f )
DECODE= MaxDecoding( factorList )
ALPHABET=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
print DECODE
print [ALPHABET[idx] for idx in DECODE]
|
{"/PythonNotebooks/testCliqueTreeOperations.py": ["/Factor.py", "/PGMcommon.py", "/PedigreeFactors.py", "/FactorOperations.py", "/GeneticNetworkFactory.py", "/CliqueTree.py", "/CliqueTreeOperations.py"], "/CliqueTreeOperations.py": ["/CliqueTree.py", "/FactorOperations.py"], "/GeneticNetworkFactory.py": ["/Factor.py", "/FactorOperations.py", "/PedigreeFactors.py"]}
|
8,746
|
indapa/pgmPy
|
refs/heads/master
|
/PGMcommon.py
|
#!/usr/bin/env python
from Factor import *
import numpy as np
from itertools import product
import sys
import itertools
def getUniqueVar( factorList):
""" given factorList which is a list of Factor objects
return a list of unique variables appearing in the
Factor objects. See http://stackoverflow.com/a/2151553/1735942 """
return list(set().union(*[ list(f.getVar()) for f in factorList ] ))
def isMemberBoolean (A, B):
""" returns an list of the same length as A containing True where the elements of A are in B and False otherwise """
return [ x in B for x in A ]
def isMember( A, B):
""" return a python list containing indices in B where the elements of A are located
A and B are numpy 1-d arrays
mapA[i]=j if and only if B[i] == A[j]"""
mapA=[]
for i in range(len(A)):
mapA.append( np.where(B==A[i])[0].tolist()[0] )
return mapA
def accum(accmap, a, func=None, size=None, fill_value=0, dtype=None):
""" based on the recipie here to implement a numpy equivalent to matlab accumarray:
http://www.scipy.org/Cookbook/AccumarrayLike
An accumulation function similar to Matlab's `accumarray` function.
Parameters
----------
accmap : ndarray
This is the "accumulation map". It maps input (i.e. indices into
`a`) to their destination in the output array. The first `a.ndim`
dimensions of `accmap` must be the same as `a.shape`. That is,
`accmap.shape[:a.ndim]` must equal `a.shape`. For example, if `a`
has shape (15,4), then `accmap.shape[:2]` must equal (15,4). In this
case `accmap[i,j]` gives the index into the output array where
element (i,j) of `a` is to be accumulated. If the output is, say,
a 2D, then `accmap` must have shape (15,4,2). The value in the
last dimension give indices into the output array. If the output is
1D, then the shape of `accmap` can be either (15,4) or (15,4,1)
a : ndarray
The input data to be accumulated.
func : callable or None
The accumulation function. The function will be passed a list
of values from `a` to be accumulated.
If None, numpy.sum is assumed.
size : ndarray or None
The size of the output array. If None, the size will be determined
from `accmap`.
fill_value : scalar
The default value for elements of the output array.
dtype : numpy data type, or None
The data type of the output array. If None, the data type of
`a` is used.
Returns
-------
out : ndarray
The accumulated results.
The shape of `out` is `size` if `size` is given. Otherwise the
shape is determined by the (lexicographically) largest indices of
the output found in `accmap`.
Examples
--------
from numpy import array, prod
a = array([[1,2,3],[4,-1,6],[-1,8,9]])
a
array([[ 1, 2, 3],
[ 4, -1, 6],
[-1, 8, 9]])
# Sum the diagonals.
accmap = array([[0,1,2],[2,0,1],[1,2,0]])
s = accum(accmap, a)
array([9, 7, 15])
# A 2D output, from sub-arrays with shapes and positions like this:
# [ (2,2) (2,1)]
# [ (1,2) (1,1)]
accmap = array([
[[0,0],[0,0],[0,1]],
[[0,0],[0,0],[0,1]],
[[1,0],[1,0],[1,1]],
])
# Accumulate using a product.
accum(accmap, a, func=prod, dtype=float)
array([[ -8., 18.],
[ -8., 9.]])
# Same accmap, but create an array of lists of values.
accum(accmap, a, func=lambda x: x, dtype='O')
array([[[1, 2, 4, -1], [3, 6]],
[[-1, 8], [9]]], dtype=object)
"""
if accmap.shape[:a.ndim] != a.shape:
raise ValueError("The initial dimensions of accmap must be the same as a.shape")
if func is None:
func = np.sum
if dtype is None:
dtype = a.dtype
if accmap.shape == a.shape:
accmap = np.expand_dims(accmap, -1)
adims = tuple(range(a.ndim))
if size is None:
size = 1 + np.squeeze(np.apply_over_axes(np.max, accmap, axes=adims))
size = np.atleast_1d(size)
size=np.array(size, dtype=int)
# Create an array of python lists of values.
vals = np.empty(size, dtype='O')
for s in product(*[range(k) for k in size]):
vals[s] = []
for s in product(*[range(k) for k in a.shape]):
indx = tuple(accmap[s])
val = a[s]
vals[indx].append(val)
# Create the output array.
out = np.empty(size, dtype=dtype)
for s in product(*[range(k) for k in size]):
if vals[s] == []:
out[s] = fill_value
else:
out[s] = func(vals[s])
return out
def getIndex ( V, I):
""" this method finds for every element of 1d- NumPy array, the index in another 1d-NumPy array
based off of this StackOverflow answer http://stackoverflow.com/a/8251757/1735942
V is a numpy 1d array listing the variables of a factor in a PGM
I is the numpy list reprsenting the intersection of variables between two factors
This method returns the index of the intersection variables in the list V
"""
index=np.argsort(V) #np.argsort gives the index ordering of an array that would result in sorted order
#http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html
sorted_v=V[index] #sorted version of V array
sorted_index=np.searchsorted( sorted_v, I) #i ndices where elements of I would be inserted into sorted_v to maintain order
#http://docs.scipy.org/doc/numpy/reference/generated/numpy.searchsorted.html
vindex=np.take(index, sorted_index, mode='clip') #Take elements from an array along an axis.\
#http://docs.scipy.org/doc/numpy/reference/generated/numpy.take.html
#print vindex
return vindex.tolist()
def generateAlleleGenotypeMappers( numAlleles):
""" analogous to AssignmentToIndex and IndexToAssignment
this function maps alleles to genotypes and genotypes to alleles
each allele's id is its index in the list of alleles/list of allele freqs
Similar for genotypes, its id is its index in list of genotypes
This function returns to numpy 2-d arrays. if n is the number of alleles
and m is the number of genotypes, then the following NumPy data structures
are returned
allelesToGenotypes: n x n matrix that maps pairs of allele IDs to
genotype IDs -- if allelesToGenotypes[i, j] = k, then the genotype with
ID k comprises of the alleles with IDs i and j
genotypesToAlleles: m x 2 matrix of allele IDs, where m is the number of
genotypes -- if genotypesToAlleles(k, :) = i, j, then the genotype with ID k
is comprised of the allele with ID i and the allele with ID j
"""
allelesToGenotypes=np.zeros([numAlleles,numAlleles], dtype=np.int)
index=0
for i in range(numAlleles):
for j in range (i,numAlleles):
allelesToGenotypes[i, j] = index;
index+=1
for i in range(numAlleles):
for j in range(0,i):
allelesToGenotypes[i,j] = allelesToGenotypes[j,i]
numGenotypes= (numAlleles * (numAlleles - 1))/2 + numAlleles
genotypesToAlleles=np.zeros([numGenotypes,2], dtype=np.int)
index=0
for i in range(numGenotypes):
for j in range(i,numAlleles):
#print i, j
genotypesToAlleles[index, :] = [i, j];
index+=1
return ( allelesToGenotypes, genotypesToAlleles)
def genotypeToIndex( geno, alleles='ACGT',ploidy=2):
""" given a string enumerating possible alleles
return the index of geno in enumerated list of genotypes
by default, the enumerated list is all 10 possibel genotypes"""
genotypes= [ "".join(list(genotype)) for genotype in itertools.combinations_with_replacement(alleles, ploidy) ]
print genotypes
try:
return genotypes.index(geno)
except ValueError:
print "genotype not in list of genotypes."
def indexToGenotype( index, alleles='ACGT', ploidy=2):
""" return genotype at a given index position after
enumerating all possible genotypes given string of alleles and
assigning to a list. By default the list contains all possible 10 genotypes"""
genotypes= [ "".join(list(genotype)) for genotype in itertools.combinations_with_replacement(alleles, ploidy) ]
try:
return genotypes[index]
except IndexError:
print "Index out of bounds, not a valid index for list of genotypes"
def lognormalize(x):
"""http://atpassos.posterous.com/normalizing-log-probabilities-with-numpy
'when working with probabilities it's very easy to get floating point underflows,
so most people use log probabilities. Probability multiplication is very easy in
log-space (it's just addition), but probability addition (or normalization) is harder,
and the linked post gives an equation to compute that. I used to implement it myself,
but today I learned that numpy does almost everything you need.'
x is (natural) log list/array of numbers
this normalizes it in probabliity space"""
a=np.logaddexp.reduce(x)
return np.exp(x-a)
|
{"/PythonNotebooks/testCliqueTreeOperations.py": ["/Factor.py", "/PGMcommon.py", "/PedigreeFactors.py", "/FactorOperations.py", "/GeneticNetworkFactory.py", "/CliqueTree.py", "/CliqueTreeOperations.py"], "/CliqueTreeOperations.py": ["/CliqueTree.py", "/FactorOperations.py"], "/GeneticNetworkFactory.py": ["/Factor.py", "/FactorOperations.py", "/PedigreeFactors.py"]}
|
8,747
|
indapa/pgmPy
|
refs/heads/master
|
/PythonNotebooks/testComputeExactMaxMarginalsBP.py
|
from Factor import *
from PGMcommon import *
from CliqueTree import *
from CliqueTreeOperations import *
from FactorOperations import *
import scipy.io as sio
import numpy as np
import pprint
import pdb
matfile='/Users/amit/BC_Classes/PGM/Prog4/PA4Sample.mat'
mat_contents=sio.loadmat(matfile)
mat_struct=mat_contents['MaxMarginals']
val=mat_struct[0,0]
input_factors = val['INPUT'][0]
factorList=[]
ALPHABET=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
for tpl in input_factors:
(var, card, values)=tpl
#print var, card, values
f= Factor( var[0].tolist(), card[0].tolist(), values[0].tolist(), 'factor' )
#print f
factorList.append( f )
MARGINALS= ComputeExactMarginalsBP( factorList, [], 1 )
for m in MARGINALS:
print m
print
MAPAssignment=MaxDecoding( MARGINALS )
print [ALPHABET[idx] for idx in MAPAssignment]
|
{"/PythonNotebooks/testCliqueTreeOperations.py": ["/Factor.py", "/PGMcommon.py", "/PedigreeFactors.py", "/FactorOperations.py", "/GeneticNetworkFactory.py", "/CliqueTree.py", "/CliqueTreeOperations.py"], "/CliqueTreeOperations.py": ["/CliqueTree.py", "/FactorOperations.py"], "/GeneticNetworkFactory.py": ["/Factor.py", "/FactorOperations.py", "/PedigreeFactors.py"]}
|
8,748
|
indapa/pgmPy
|
refs/heads/master
|
/PythonNotebooks/testGetNextC.py
|
import scipy.io as sio
import numpy as np
import pprint
from Factor import *
from PGMcommon import *
from CliqueTree import *
from CliqueTreeOperations import *
from FactorOperations import *
import pickle
""" load the test data from the matlab file """
matfile='/Users/amit/BC_Classes/PGM/Prog4/PA4Sample.mat'
mat_contents=sio.loadmat(matfile)
mat_struct=mat_contents['GetNextC']
np.shape(mat_struct)
val=mat_struct[0,0]
input_edges = val['INPUT1']['edges'][0][0]
input_cliqueList= val['INPUT1']['cliqueList'][0][0][0]
clique_list_factorObj=[]
for tpl in input_cliqueList:
(var, card, values)=tpl
f= Factor( var[0].tolist(), card[0].tolist(), values[0].tolist(), 'factor' )
clique_list_factorObj.append(f)
messages=val['INPUT2']
messageFactors=[]
(nrow,ncol)=np.shape(messages)
for i in range( nrow ):
for j in range ( ncol ):
(var, card, values)=messages[i][j]
f=Factor( var[0].tolist(), card[0].tolist(), values[0].tolist(), 'factor' )
messageFactors.append(f)
MESSAGES= np.reshape( np.array ( messageFactors ), (nrow,ncol) )
""" dump it to Python pickle file """
with open('GetNextC.INPUT1.pickle', 'wb') as f:
pickle.dump(clique_list_factorObj,f)
with open('GetNextC.INPUT2.pickle', 'wb') as f:
pickle.dump(MESSAGES, f)
P=CliqueTree( clique_list_factorObj , input_edges, clique_list_factorObj, [])
(a,b)=getNextClique(P,MESSAGES)
print 'a: ', a, ' b:', b
|
{"/PythonNotebooks/testCliqueTreeOperations.py": ["/Factor.py", "/PGMcommon.py", "/PedigreeFactors.py", "/FactorOperations.py", "/GeneticNetworkFactory.py", "/CliqueTree.py", "/CliqueTreeOperations.py"], "/CliqueTreeOperations.py": ["/CliqueTree.py", "/FactorOperations.py"], "/GeneticNetworkFactory.py": ["/Factor.py", "/FactorOperations.py", "/PedigreeFactors.py"]}
|
8,749
|
indapa/pgmPy
|
refs/heads/master
|
/PythonNotebooks/testComputeExactMarginalsBP.py
|
from Factor import *
from PGMcommon import *
from CliqueTree import *
from CliqueTreeOperations import *
from FactorOperations import *
import scipy.io as sio
import numpy as np
import pprint
import pdb
matfile='/Users/amit/BC_Classes/PGM/Prog4/PA4Sample.mat'
mat_contents=sio.loadmat(matfile)
mat_struct=mat_contents['ExactMarginal']
val=mat_struct[0,0]
input_factors = val['INPUT'][0]
factorList=[]
for tpl in input_factors:
(var, card, values)=tpl
#print var, card, values
f= Factor( var[0].tolist(), card[0].tolist(), values[0].tolist(), 'factor' )
print f
factorList.append( f )
print
M=ComputeExactMarginalsBP( factorList )
#for marginal in M:
# print marginal
# print
|
{"/PythonNotebooks/testCliqueTreeOperations.py": ["/Factor.py", "/PGMcommon.py", "/PedigreeFactors.py", "/FactorOperations.py", "/GeneticNetworkFactory.py", "/CliqueTree.py", "/CliqueTreeOperations.py"], "/CliqueTreeOperations.py": ["/CliqueTree.py", "/FactorOperations.py"], "/GeneticNetworkFactory.py": ["/Factor.py", "/FactorOperations.py", "/PedigreeFactors.py"]}
|
8,750
|
indapa/pgmPy
|
refs/heads/master
|
/PythonNotebooks/testComputeExactMarginalsBP_SixPersonPedigree.py
|
from Factor import *
from PGMcommon import *
from CliqueTree import *
from CliqueTreeOperations import *
from FactorOperations import *
import scipy.io as sio
import numpy as np
import pprint
import pdb
matfile='/Users/indapa/software/PGM/Prog4/PA4Sample.mat'
mat_contents=sio.loadmat(matfile)
mat_struct=mat_contents['SixPersonPedigree']
val=mat_struct[0]
factorList=[]
for elem in val:
(var, card, val) =elem
f= Factor( var[0].tolist(), card[0].tolist(), val[0].tolist(), 'factor' )
#print f
factorList.append(f)
#print
jointFactor = ComputeJointDistribution(factorList)
#print jointFactor
MARGINALS= ComputeExactMarginalsBP( factorList, [], 1)
P=CreatePrunedInitCtree(factorList, [] )
(P, MESSAGES) = CliqueTreeCalibrate(P, isMax=1)
jointDistribution=ComputeJointDistributionFromCalibratedCliqueTree(P, MESSAGES, 1)
print jointDistribution
#for marginal in MARGINALS:
#print marginal
#print
MAPAssignment=MaxDecoding( MARGINALS )
print MAPAssignment
#for m in MARGINALS:
#m.setVal( np.log( lognormalize(m.getVal() ) ) )
#print np.sum( lognormalize(m.getVal() ) )
#print MAPAssignment
#for marginal in MARGINALS:
#print marginal.getVal()
#print
|
{"/PythonNotebooks/testCliqueTreeOperations.py": ["/Factor.py", "/PGMcommon.py", "/PedigreeFactors.py", "/FactorOperations.py", "/GeneticNetworkFactory.py", "/CliqueTree.py", "/CliqueTreeOperations.py"], "/CliqueTreeOperations.py": ["/CliqueTree.py", "/FactorOperations.py"], "/GeneticNetworkFactory.py": ["/Factor.py", "/FactorOperations.py", "/PedigreeFactors.py"]}
|
8,751
|
indapa/pgmPy
|
refs/heads/master
|
/CliqueTree.py
|
from Factor import *
from FactorOperations import *
import numpy as np
import networkx as nx
import pdb
class CliqueTree(object):
'represent a Clique tree'
def __init__(self, nodeList=[], edges=[], factorList=[],evidence=[]):
self.nodeList=nodeList
self.edges=edges
self.factorList=factorList
self.evidence=evidence
self.card= []
self.factorInds= []
def toString(self):
print 'nodes: ', self.nodeList
print 'card: ', self.card
print 'factorList: ', len( self.factorList)
print 'factorInds:', self.factorInds
print 'edges:\n',self.edges
def setNodeList(self,nodeList):
self.nodeList=nodeList
def setEdges(self,edges):
self.edges=edges
def setFactorList(self,factorList):
self.factorList=factorList
#self.factorInds= len( factorList ) * [None]
def setEvidence(self,evidence):
self.evidence=evidence
def setCard(self, cardinality):
self.card = cardinality
def getNodeList(self):
return self.nodeList
def getNodeCount(self):
return len(self.nodeList)
def getEdges(self):
return self.edges
def getFactorList(self):
return self.factorList
def getFactorCount(self):
return len(self.factorList)
def getEvidence(self):
return self.evidence
def incorporateEvidence(self):
for j in range ( len(self.evidence)):
k=j+1
if self.evidence[j] > 0:
self.factorList=ObserveEvidence(self.factorList, np.matrix([[k, self.evidence[j] ]] ) )
def eliminateVar(self,Z,E,factorList):
""" a variable elimination function
based on https://github.com/indapa/PGM/blob/master/Prog4/EliminateVar.m
Z is the variable to be eliminated. We base this code on the matlab file
linked to above as well as the Sum-product VE pseudo code in Koller and Friedman
page 298
E is a numpy 2d matrix representing adjacency matrix of variables
It represents the induced VE graph
Once a variable is eliminated, its edges are removed from E
"""
useFactors = []#the index of the factor that contains the variable Z
scope = []
#print 'Z: ', Z
#get a list containining the index in self.factorLlist of factors
#that contain the variable Z to be eliminated
# get the scope of variables from the factors that contain variable Z
for i in range (len(factorList)):
if Z in factorList[i].getVar().tolist():
useFactors.append(i)#the ith factor is being currently involved in elimination
scope=list(set.union(set(scope), factorList[i].getVar().tolist() ))
# update edge map
""" These represent the induced edges for the VE graph.
once the variable Z is eliminated, its edges are removed from the graph
but in the process of elimination, we create a new factor. This
introduces fill edges (see pg. 307 Koller and Friedman)
Z is one based, but the indices in E are zero based, hence Z-1
also the variable names in scope are 1 based, so we subtract 1 when
updating the induced VE graph """
for i in range ( len(scope)):
for j in range ( len(scope)):
if i != j:
E[ scope[i]-1, scope[j]-1 ]=1
E[ scope[j]-1, scope[i]-1 ]=1
E[Z-1,:]=0
E[:,Z-1]=0
#G=nx.from_numpy_matrix(E)
#print 'induced graph edges:\n', (G.edges())
#nx.draw_shell(G)
#plt.show()
#these are the indices of factorList which are not involved in VE
unusedFactors= list( set.difference ( set(range(len(factorList))), set(useFactors) ) )
newF=None
#check first if there are any unused factors left!
if len(unusedFactors) > 0:
newF=len(unusedFactors)*[None]
newmap=np.zeros(max(unusedFactors)+1,dtype=int).tolist()
#newF is a new factor list, we populate it first
#with the unused factors
#newmap is maps the new location of ith unusedFactor
for i in range( len(unusedFactors)):
newF[i]=factorList[ unusedFactors[i] ]
newmap[ unusedFactors[i] ]= i
#print 'newmap ', newmap,"\n"
#print 'length of newmap: ', len(newmap), "\n"
newFactor = Factor( [], [], [], 'newFactor')
#we multiple in all the factors that contain the variable Z
for i in range( len (useFactors)):
newFactor = FactorProduct(newFactor,factorList[ useFactors[i] ])
#then we marginalize Z out and obtain a new factor
#then append it the end of newF, the new factor list
newFactor = FactorMarginalization( newFactor,[Z] )
#print 'newFactor: ',newFactor
#newF(length(nonUseFactors)+1) = newFactor;
if newFactor != None:
newF.append ( newFactor )
if newF != None:
factorList=newF
#return E
########################################################################
""" the remaining code builds the edges of the clique tree """
""" add new node with the factors that contain the variable Z
adding a new node represents new clique.
The scope of every factor generated during the variable elimination process is a clique pg. 309 Koller & Friedman """
self.nodeList.append ( scope )
#newC is the total number of nodes in the clique tree
newC=len( self.nodeList )
#print 'newC: ', newC
#factorInds are individual factors with one variable ... I think
self.factorInds.append ( len(unusedFactors) + 1 )
#print 'range( newC -1) ', range( newC-1 )
#print 'factorInds: ', self.factorInds
#print 'useFactors: ', useFactors
#pdb.set_trace()
""" we update the edges of the clique tree """
for i in range( newC -1 ):
#if self.factorInds [ i ] -1 in useFactors:
#there was the off by onoe erorr - the values in factorInds
#were one-based, need to subtract 1
if self.factorInds [ i ] -1 in useFactors:
self.edges[ i, newC-1 ] = 1
self.edges [ newC-1, i ] = 1
self.factorInds[ i ] = 0
else:
if self.factorInds [i] != 0:
#print 'i: ', i
#print 'factorInds: ', self.factorInds
#print 'newmap: ', newmap
#print 'newmap [ self.factorInds[i] -1: ', newmap [ self.factorInds[i] -1 ]
#print 'self.factorInds[ i ] = newmap [ self.factorInds[i] - 1 ] + 1 '
if len(unusedFactors) > 0:
#self.factorInds[ i ] = newmap [ self.factorInds[i] -1 ] +1
self.factorInds[ i ] = newmap [ self.factorInds[i] -1 ] +1
#self.factorInds[ i ] = newmap [ self.factorInds[i] ]
#print 'factorInds right before returning: ', self.factorInds
return E, factorList
|
{"/PythonNotebooks/testCliqueTreeOperations.py": ["/Factor.py", "/PGMcommon.py", "/PedigreeFactors.py", "/FactorOperations.py", "/GeneticNetworkFactory.py", "/CliqueTree.py", "/CliqueTreeOperations.py"], "/CliqueTreeOperations.py": ["/CliqueTree.py", "/FactorOperations.py"], "/GeneticNetworkFactory.py": ["/Factor.py", "/FactorOperations.py", "/PedigreeFactors.py"]}
|
8,752
|
indapa/pgmPy
|
refs/heads/master
|
/PedigreeFactors.py
|
import sys
import numpy as np
from Factor import *
from PGMcommon import *
from FactorOperations import *
import itertools
class PhenotypeFactor (object):
""" represents a factor that encodes Pr(phenotype|genotype)
for purposes here the variable to the left of the conditioning
bar is the first variable in the PhenotypeFactor var list. """
def __init__(self, isDominant, genotypeVar, phenotypeVar, name):
#instantiate a Factor object
phenotype = Factor( [phenotypeVar, genotypeVar], [2, 3], [], name )
phenotype.setVal( np.zeros ( np.prod(phenotype.getCard())).tolist() )
#this enumerates the values the factor can take
# since there are 2x3 cardinality, 6 possible assignments
assignments=IndexToAssignment( np.arange(np.prod(phenotype.getCard())), phenotype.getCard() )
val=val = np.zeros(np.prod(phenotype.getCard() ))
(nrows,ncols)=np.shape(assignments)
for i in range(np.prod([2,3])):
#if its dominant, if you have at least one copy, you have the phenotype
(pheno,geno)=assignments[i]
if isDominant==1:
if pheno ==1: #affected
if geno ==1 or geno ==2:
val[i]=1
else:
val[i]=0
else:#uneffected
if geno == 3:
val[i]=1
if isDominant == 0:
if pheno == 1:
if geno==3:
val[i]=1
else:
if geno ==1 or geno == 2:
val[i]=1
phenotype.setVal( val.tolist() )
self.phenotype=phenotype
def getVar(self):
return self.phenotype.getVar()
def getCard(self):
return self.phenotype.getCard()
def getVal(self):
return self.phenotype.getVal()
def getFactor(self):
return self.phenotype
def __str__(self):
return self.phenotype.__str__()
class PhenotypeGivenGenotypeFactor(object):
""" construct factor of phenotype|genotype
#prob of being effected, given the ith genotype
#alphaList[i] is the prob of being effected given the ith genotype """
def __init__(self,alphaList, phenotypeVar, genotypeVar , name):
self.phenotypeFactor=Factor( [ phenotypeVar, genotypeVar], [], [], name)
self.alpha=np.array ( alphaList)
ngenotypes=len(alphaList)
self.phenotypeFactor.setCard( [2, ngenotypes])
values=[x for x in range( np.prod(self.phenotypeFactor.getCard()))]
for i in range( len(alphaList )):
values[i]=alphaList[i]
values[i+1]=1-alphaList[i]
ctr=0
alphas=2*len(alphaList)*[None]
for i in range(len(alphaList)):
alphas[ctr]=alphaList[i];
ctr=ctr+1
alphas[ctr]=1-alphaList[i];
ctr=ctr+1
values=alphas
self.phenotypeFactor.setVal( values)
def getVar(self):
return self.phenotypeFactor.getVar()
def getCard(self):
return self.phenotypeFactor.getCard()
def getVal(self):
return self.phenotypeFactor.getVal()
def setVal(self,val):
self.phenotypeFactor.setVal(val)
def getFactor(self):
return self.phenotypeFactor
def __str__(self):
return self.phenotypeFactor.__str__()
class GenotypeAlleleFreqFactor (object):
""" construct a factor that has the probability of each genotype
given allele frequencies Pr(genotype|allele_freq)"""
def __init__(self, allelefreqs, genotypeVar, name):
self.allelefreq=allelefreqs
#number of alleles == number of allele frequencies passed in
numAlleles=len(allelefreqs)
self.allelesToGenotypes=None
self.genotypesToAlleles=None
self.genotypeFactor=None
#map alleles to genotypes and genotyeps to alleles
(self.allelesToGenotypes, self.genotypesToAlleles)=generateAlleleGenotypeMappers(numAlleles)
(ngenos,ploidy)=np.shape(self.genotypesToAlleles)
self.genotypeFactor = Factor( [genotypeVar], [], [], name)
#the cardinality of the factor is the number of genotypes
self.genotypeFactor.setCard( [ngenos] )
#set the values to zero initially
values=np.zeros( (np.prod(self.genotypeFactor.getCard()))).tolist()
for i in range (ngenos):
alleles=self.genotypesToAlleles[i,:].tolist()
if alleles[0] == alleles[1]:
values[i]= np.prod( [ allelefreqs[j] for j in alleles ])
else:
values[i]= np.prod( [ allelefreqs[j] for j in alleles ]) * 2
self.genotypeFactor.setVal( values )
def getVar(self):
return self.genotypeFactor.getVar()
def getCard(self):
return self.genotypeFactor.getCard()
def getVal(self):
return self.genotypeFactor.getVal()
def setVal(self,val):
self.genotypeFactor.setVal(val)
def getFactor(self):
return self.genotypeFactor
def __str__(self):
return self.genotypeFactor.__str__()
class GenotypeGivenParentsFactor (object):
""" construct factor that has prob of genotype of child given both parents
Pr(g_child| g_mother, g_father """
def __init__(self,numAlleles, genotypeVarChild, genotypeVarParentOne, genotypeVarParentTwo, name):
self.genotypeFactor = Factor( [genotypeVarChild, genotypeVarParentOne, genotypeVarParentTwo ], [ ], [ ], name)
#map alleles to genotypes and genotyeps to alleles
(self.allelesToGenotypes, self.genotypesToAlleles)=generateAlleleGenotypeMappers(numAlleles)
(ngenos,ploidy)=np.shape(self.genotypesToAlleles)
self.genotypeFactor.setCard([ ngenos,ngenos,ngenos ] )
#set the values to zero initially
values=np.zeros( (np.prod(self.genotypeFactor.getCard()))).tolist()
#iterate thru variable assignments to random variables
#assign probablities based on Punnet square crosses
assignments=IndexToAssignment( np.arange(np.prod(self.genotypeFactor.getCard())), self.genotypeFactor.getCard() )-1
for z in range( np.prod(self.genotypeFactor.getCard() ) ):
curr_assign= assignments[z]
childAssignment=int(curr_assign[0])
parent1gametes= self.genotypesToAlleles[curr_assign[1],:]
parent2gametes= self.genotypesToAlleles[curr_assign[2],:]
#print 'parental gametes: ', parent1gametes, parent2gametes
#print 'child assignment: ', childAssignment
#list of tuples containing list of zygote(genotype) tuples
zygote_list=list(itertools.product(parent1gametes,parent2gametes))
punnet_freq=[ self.allelesToGenotypes[zygote[0],zygote[1]] for zygote in zygote_list ]
histc={}
hist=[]
for g in range( ngenos):
histc[g]=0.
for x in punnet_freq:
histc[x]+=1.
#print histc.values()
for g in range (ngenos):
hist.append ( histc[g] )
#print punnet_freq
hist=(np.array ( hist)) /4
#print 'hist:', hist
#print zygote_list
values[z]=hist[childAssignment]
self.genotypeFactor.setVal( values )
def getVar(self):
return self.genotypeFactor.getVar()
def getCard(self):
return self.genotypeFactor.getCard()
def getVal(self):
return self.genotypeFactor.getVal()
def setVal(self, val):
self.genotypeFactor.setVal(val)
def getFactor(self):
return self.genotypeFactor
def genotypeSlice(self):
pass
#see this http://stackoverflow.com/q/4257394/1735942
def __str__(self):
return self.genotypeFactor.__str__()
class ChildCopyGivenParentalsFactor(object):
""" this represents a de-coupled factor
given a parents two haplotypes, returns
factor whose values are the probablity
of inheriting (grand)paternal or (grand)maternal
haplotype. This allows for some more flexibility
in modeling inheritance, rather than clumping
a single parent's haplotype into a genotype
i.e. GenotypeGivenParentsFactor """
def __init__(self, numAlleles, geneCopyVarChild, geneCopyHapOne, geneCopyHapTwo):
self.numalleles=numAlleles
self.hapone=geneCopyVarChild
self.haptwo=geneCopyHapTwo
#geneCopyFactor = struct('var', [], 'card', [], 'val', []);
self.geneCopyFactor=Factor( [geneCopyVarChild, geneCopyHapOne, geneCopyHapTwo ], [], [], 'child|hap1,hap2')
self.geneCopyFactor.setCard( [self.numalleles,self.numalleles,self.numalleles ])
values=np.zeros( np.prod([ self.numalleles,self.numalleles,self.numalleles])).tolist()
#this keeps track of what posiiton you are in the values list
index=0
#the number of iterations thru the nested for loops should be equal to numallels^3
for i in range(numAlleles):
#iterate through alleles from
#grand(paternal) haplotype
for j in range(numAlleles):
#iterate through alleles from
#grand(maternal) haplotype
for k in range(numAlleles):
#iterate thru child alleles
print i, j, k
if j==k:#child has grandmotherhap
if i==k:#grandfatherhap is the same
values[index]=1
else:
values[index]=.5
elif i==k:#child has grandfather hap
values[index]=.5
else:
pass
index+=1
#print values
self.geneCopyFactor.setVal( values )
def getVar(self):
return self.geneCopyFactor.getVar()
def getCard(self):
return self.geneCopyFactor.getCard()
def getVal(self):
return self.geneCopyFactor.getVal()
def getFactor(self):
return self.geneCopyFactor
def __str__(self):
return self.geneCopyFactor.__str__()
class ChildCopyGivenFreqFactor(object):
""" for a founder, its particular haplotype is proprortional to the
given allelel freq of the locus. This factor is part of the decoupled
Bayesian Genetic network , along with ChildCopyGivenParentalsFactor"""
def __init__(self, alleleFreqs, geneCopyVar):
numAlleles = len(alleleFreqs)
self.geneCopyFactor=Factor( [geneCopyVar], [], [], 'founderHap')
self.geneCopyFactor.setCard ( [numAlleles])
self.geneCopyFactor.setVal( alleleFreqs )
#geneCopyFactor = struct('var', [], 'card', [], 'val', [])
#geneCopyFactor.var(1) = geneCopyVar;
#geneCopyFactor.card(1) = numAlleles;
#geneCopyFactor.val = alleleFreqs';
def getVar(self):
return self.geneCopyFactor.getVar()
def getCard(self):
return self.geneCopyFactor.getCard()
def getVal(self):
return self.geneCopyFactor.getVal()
def getFactor(self):
return self.genCopyFactor
def __str__(self):
return self.geneCopyFactor.__str__()
class phenotypeGivenHaplotypesFactor(object):
""" factor represents Pr(phenotype| paternal haplotype, maternal haplotype)
very similiar to PhenotypeGivenGenotypeFactor, but we are de-coupling into
paternal and maternal alleles rather than genotype"""
def __init__(self, alphaList, numAlleles, geneCopyVarOne, geneCopyVarTwo, phenotypeVar):
self.numalleles=numAlleles
self.alphaList=alphaList
self.phenotypeFactor=Factor([phenotypeVar,geneCopyVarOne, geneCopyVarTwo], [], [], 'phenotype| geneCopy1, geneCopy2')
ngenos=len(alphaList)
self.phenotypeFactor.setCard( [ 2, numAlleles, numAlleles])
#phenotypeFactor.val = zeros(1, prod(phenotypeFactor.card));
values=np.zeros( (1, np.prod(self.phenotypeFactor.getCard()))).flatten().tolist()
affectedAlphas=alphaList
unaffectedAlphas=[ 1- alpha for alpha in alphaList]
(allelesToGenotypes, genotypesToAlleles) = generateAlleleGenotypeMappers(numAlleles)
assignments=IndexToAssignment( np.arange(np.prod(self.phenotypeFactor.getCard())), self.phenotypeFactor.getCard() )-1
for z in range( np.prod(self.phenotypeFactor.getCard() ) ):
curr_assign= assignments[z]
curr_assign=assignments[z]
genotype_num=allelesToGenotypes[curr_assign[1], curr_assign[2]]
if curr_assign[0] == 0:
values[z] = affectedAlphas[genotype_num]
else:
values[z] = unaffectedAlphas[genotype_num]
self.phenotypeFactor.setVal( values )
#genotype_num=allelesToGenotypes(assignment(2), assignment(3));
def getVar(self):
return self.phenotypeFactor.getVar()
def getCard(self):
return self.phenotypeFactor.getCard()
def getVal(self):
return self.phenotypeFactor.getVal()
def getFactor(self):
return self.phenotypeFactor
def __str__(self):
return self.phenotypeFactor.__str__()
def __str__(self):
return self.phenotypeFactor.__str__()
##########################
class Ped(object):
""" represents a pedigree record in a Ped file http://pngu.mgh.harvard.edu/~purcell/plink/data.shtml#ped """
def __init__(self,famid='.', indv='.', paternal='.', maternal='.', sex='.', phenotype='.'):
""" attributes of a Ped object """
self.famid=famid
self.individ=indv
self.pid=paternal
self.mid=maternal
self.sex=sex
self.pheno=phenotype
def setfamid(self,famid):
self.famid=famid
def setindvid(self,indv):
self.individ=indv
def setmid(self,mid):
self.mid=mid
def setpid(self,pid):
self.pid=pid
def setsex(self,sex):
self.sex=sex
def setpheno(self,pheno):
self.pheno=pheno
def getfamid(self):
return self.famid
def getid(self):
return self.individ
def getmid(self):
return self.mid
def getpid(self):
return self.pid
def getsex(self):
return self.sex
def getpheno(self):
return self.pheno
def isFounder(self):
return self.pid == '0' and self.mid == '0'
def getParents(self):
return ( self.pid, self.mid)
def __str__(self):
return "\t".join( [ self.famid, self.individ, self.pid, self.mid, self.sex, self.pheno] )
class Pedfile(object):
""" a Pedfile object has a list of Ped objects """
def __init__(self,filename):
self.filename=filename
self.fh=open(self.filename, 'r')
self.pedlist=[]
def parsePedfile(self):
""" given a filehandle to a *.ped file read its contents and populate the list pedlist with Ped objects """
for line in self.fh:
fields=line.strip().split('\t')
(famid, indv, pid, mid, sex, pheno)=fields[0:6]
self.pedlist.append( Ped(famid, indv, pid, mid, sex, pheno) )
def returnFounders(self):
""" return the founders in a ped file (those with unknown paternal and maternids """
founders=[]
for pedobj in self.pedlist:
if pedobj.getpid() == "0":
founders.append(pedobj)
return founders
def returnFounderIds(self):
""" return the indiv ids of the founders in the ped file"""
founderids=[]
for pedobj in self.pedlist:
if pedobj.getpid() == "0":
founderids.append( pedobj.getid() )
return founderids
def returnNonFounderIds(self):
""" return the indiv ids of the founders in the ped file"""
nonfounderids=[]
for pedobj in self.pedlist:
if pedobj.getpid() != "0":
nonfounderids.append( pedobj.getid() )
return nonfounderids
def returnNonFounders(self):
""" return the founders in a ped file (those with unknown paternal and maternids """
nonfounders=[]
for pedobj in self.pedlist:
if pedobj.getpid() != "0":
nonfounders.append(pedobj)
return nonfounders
def returnIndivids(self):
""" return a list of indvi ids from the ped file """
#samplelist=[]
return [ ped.getid() for ped in self.pedlist]
def getPedList(self):
return self.pedlist
def getTotalSize(self):
return len(self.pedlist)
def yieldMembers(self):
for pedobj in self.pedlist:
yield pedobj
def __str__(self):
return "\n".join( [ x.__str__() for x in self.pedlist ] )
|
{"/PythonNotebooks/testCliqueTreeOperations.py": ["/Factor.py", "/PGMcommon.py", "/PedigreeFactors.py", "/FactorOperations.py", "/GeneticNetworkFactory.py", "/CliqueTree.py", "/CliqueTreeOperations.py"], "/CliqueTreeOperations.py": ["/CliqueTree.py", "/FactorOperations.py"], "/GeneticNetworkFactory.py": ["/Factor.py", "/FactorOperations.py", "/PedigreeFactors.py"]}
|
8,753
|
indapa/pgmPy
|
refs/heads/master
|
/PythonNotebooks/testFactorMaxMarginal.py
|
from Factor import *
from PGMcommon import *
from CliqueTree import *
from CliqueTreeOperations import *
from FactorOperations import *
import scipy.io as sio
import numpy as np
import pprint
import pdb
matfile='/Users/amit/BC_Classes/PGM/Prog4/PA4Sample.mat'
mat_contents=sio.loadmat(matfile)
mat_struct=mat_contents['FactorMax']
val=mat_struct[0,0]
input_factors = val['INPUT1'][0][0]
var = input_factors[0].flatten().tolist()
card=input_factors[1].flatten().tolist()
value=input_factors[2].flatten().tolist()
print var
print card
print value
INPUT1= Factor( var, card, value, 'test')
INPUT2= val['INPUT2'].flatten()
print INPUT1
print INPUT2
print FactorMaxMarginalization(INPUT1, INPUT2)
#example used in section 13.2 pg 555 of Friedman and Koller
print "====="
psi=Factor( [ 1,2,3], [3,2,2], [.25,.05,.15,.08,0,.09,.35,.07,.21,.16,0,.18])
maxfactor= FactorMaxMarginalization(psi, [2])
print maxfactor
print IndexToAssignment(np.arange(6),[3,2])
|
{"/PythonNotebooks/testCliqueTreeOperations.py": ["/Factor.py", "/PGMcommon.py", "/PedigreeFactors.py", "/FactorOperations.py", "/GeneticNetworkFactory.py", "/CliqueTree.py", "/CliqueTreeOperations.py"], "/CliqueTreeOperations.py": ["/CliqueTree.py", "/FactorOperations.py"], "/GeneticNetworkFactory.py": ["/Factor.py", "/FactorOperations.py", "/PedigreeFactors.py"]}
|
8,754
|
indapa/pgmPy
|
refs/heads/master
|
/PythonNotebooks/testCliqueTreeOperations.py
|
import sys
import numpy as np
from Factor import *
from PGMcommon import *
from PedigreeFactors import *
from FactorOperations import *
from GeneticNetworkFactory import *
from CliqueTree import *
import networkx as nx
import matplotlib.pyplot as plt
from CliqueTreeOperations import *
#to create a clique tree, we start with a list of factors
#and potentially some observed evidence
alphaList=[.8,.6,.1]
allelefreq=[.1,.9]
chrom='12'
position=1000
g1=GeneticNetworkFactory('sixperson.ped',alphaList,allelefreq, chrom,position)
g1.constructNetwork()
factorList=g1.getFactorList()
#for f in factorList:
# print f
# print
#print "+++++++++"
cTree = createCliqueTree(factorList)
G=nx.from_numpy_matrix( cTree.getEdges() )
nx.draw_shell(G)
plt.show()
#print cTree.getEdges()
#cTree.toString()
prunedCTree=PruneTree( cTree )
P=CliqueTreeInitialPotential( prunedCTree )
#for f in P.getNodeList():
# print f
# print
G=nx.from_numpy_matrix( prunedCTree.getEdges() )
nx.draw_shell(G)
plt.show()
|
{"/PythonNotebooks/testCliqueTreeOperations.py": ["/Factor.py", "/PGMcommon.py", "/PedigreeFactors.py", "/FactorOperations.py", "/GeneticNetworkFactory.py", "/CliqueTree.py", "/CliqueTreeOperations.py"], "/CliqueTreeOperations.py": ["/CliqueTree.py", "/FactorOperations.py"], "/GeneticNetworkFactory.py": ["/Factor.py", "/FactorOperations.py", "/PedigreeFactors.py"]}
|
8,755
|
indapa/pgmPy
|
refs/heads/master
|
/CliqueTreeOperations.py
|
import numpy as np
from CliqueTree import *
from FactorOperations import *
#import matplotlib.pyplot as plt
import networkx as nx
import pdb
def createCliqueTree( factorList,E=[]):
""" return a Clique Tree object given a list of factors
it peforms VE and returns the clique tree the VE
ordering defines. See Chapter 9 of Friedman and Koller
Probabilistic Graphical Models"""
V=getUniqueVar(factorList)
totalVars=len(V)
cardinality=np.zeros(len(V)).tolist()
for i in range(len(V)):
for j in range(len(factorList)):
try:
indx= factorList[j].getVar().tolist().index( V[i] )
cardinality[i]=factorList[j].getCard().tolist()[indx]
break
except:
continue
edges=np.zeros( (totalVars, totalVars))
""" Set up adjacency matrix: for each factor, get the list of variables in its scope and create an edge between each variable in the factor """
for f in factorList:
variableList=f.getVar()
for j in range(len(variableList) ):
for k in range (len(variableList) ):
edges[ variableList[j]-1, variableList[k]-1 ]=1
(nrows,nedges)=np.shape(edges)
C=CliqueTree()
C.setCard( cardinality )
C.setEdges(np.zeros( (totalVars, totalVars)))
C.setFactorList(factorList)
C.setEvidence(E)
C.setNodeList([])
#print 'length of factorList: ', len(factorList)
#print C.toString()
cliquesConsidered = 0
#pdb.set_trace()
while cliquesConsidered < len(V):
bestClique = 0
bestScore = sys.maxint
for i in range(nrows):
score=np.sum( edges[i,:] )
if score > 0 and score < bestScore:
bestScore = score
bestClique = i+1
cliquesConsidered+=1
(edges, factorList)=C.eliminateVar(bestClique, edges, factorList)
return C
def PruneTree ( C ):
""" prune a clique tree by determing if neighboring cliques are
supersets of each other. E.g.: [A,B,E] -- [A,B] -- [A,D]
pruned: [A,B,E] -- [A,D] """
ctree_edges=C.getEdges()
(nrows,ncols)=np.shape( ctree_edges )
totalNodes=nrows
Cnodes=C.getNodeList()
toRemove=[]
#print range( totalNodes )
for i in range ( totalNodes ):
if i in toRemove: continue
#np.nonzero returns tuple, hence the [0]
#we collect the neighbors of the ith clique
neighborsI = np.nonzero ( ctree_edges[i,:] )[0].tolist()
for c in range ( len(neighborsI) ):
j= neighborsI[c]
assert ( i != j), 'i cannot equal j: PruneTree'
if j in toRemove: continue
#here is where we look for superset neighboring nodes in the CTree
if sum ( [ x in Cnodes[j] for x in Cnodes[i] ] ) == len( Cnodes[i] ):
for nk in neighborsI:
cnodes_i = set ( Cnodes[i] )
cnodes_nk= set ( Cnodes[nk] )
if len( list ( set.intersection( cnodes_i, cnodes_nk) ) ) == len (Cnodes[i]):
neighborsI_set=set( neighborsI )
nk_set=set( [nk] )
ctree_edges [ list( neighborsI_set - nk_set ), nk ] = 1
ctree_edges [ nk, list( neighborsI_set - nk_set )] = 1
break
ctree_edges[i,:]=0
ctree_edges[:,i]=0
toRemove.append(i)
toKeep = list ( set ( range( totalNodes ) ) - set ( toRemove ) )
for indx in toRemove:
Cnodes[indx]=[]
Cnodes=[ item for item in Cnodes if len(item) > 0 ]
ctree_edges= ctree_edges[np.ix_(toKeep, toKeep)]
C.setNodeList( Cnodes )
C.setEdges( ctree_edges )
#pdb.set_trace()
#return the pruned tree with the updated nodes and edges
return C
def CliqueTreeObserveEvidence ( C, E ):
""" given a CliqueTree object C and list of values E, which represent evidence, update
the factors of the cliqueTree C to reflect the observed evidence.
Note that ObserveEvidence in FactorOperations assumes E is a Nx2 matrix,
here we build the Nx2 matrix by assuing the jth index of E is the evidence
for the variable j"""
factorList= C.getFactorList()
for j in range ( len (E)):
if E[j] > 0:
factorList=ObserveEvidence( factorList, np.array(np.matrix( [ j+1, E[j]] ) ) )
C.setFactorList(factorList)
#return the new CliqueTree object with the updated evidence
return C
def CliqueTreeInitialPotential( C ):
""" given a clique tree object C, calculate the initial potentials for each of the cliques
the factors in the updated clique list are FActor objects"""
N= C.getNodeCount()
totalFactorCount=C.getFactorCount()
nodeList=C.getNodeList()
factorList=C.getFactorList()
cliqueList=[ Factor( [], [], [], str(i) ) for i in range(N) ]
#edges=np.zeros( (N,N) )
""" First assign the factors to appropriate cliques
based on the skeleton cliqueTree cTree"""
factorsUsed=np.zeros( totalFactorCount, dtype=int).tolist()
#pdb.set_trace()
for i in range(N):
cliqueList[i].setVar( nodeList[i] )
F=[]
""" we add factors to the clique if they are in the variable scope of the clique """
for j in range( len(factorList) ):
if len( factorList[j].getVar().tolist() ) == len ( list( set.intersection ( set(cliqueList[i].getVar().tolist() ), set( factorList[j].getVar().tolist() ) ) ) ):
if factorsUsed[j] == 0:
F.append( factorList[j] )
factorsUsed[j] = 1
#print F
#pdb.set_trace()
#F= [ f.getFactor() for f in F ]
cliqueList[i]=ComputeJointDistribution ( F )
#pdb.set_trace()
C.setNodeList(cliqueList)
#pdb.set_trace()
return C
def getNextClique(P, messages):
""" we need to come up wih a proper message passing order. A clique is ready to pass
messages upward once its recieved all downstream messages from its neighbor (and vice versa)
its ready to transmit downstream once it recieves all its upstream messages
the ith clique C_i is ready to transmit to its neighbor C_j when C_i recieves all its
messages from neigbors except C_j. In cTree message passing, each message is passed
once. To get the process started we start with our initial potential cTree, P
and an empty matrix of factors, representing messages passed between the nodes on the clique
tree """
i=j=-1
edges=P.getEdges()
#print edges
(nrow, ncol) = np.shape(edges)
for r in range(nrow):
#we want to ignore nodes with only one neighbor
#becuae they are ready to pass messages
if np.sum(edges[r,:] ) == 1:
continue
foundmatch=0
for c in range(ncol):
if edges[r,c] == 1 and messages[r,c].getVarCount() == 0:
#list of indices indicating neighbors or r
#print 'r,c: ', r, ' ', c
#print 'edges[r,c]: ', edges[r,c]
Nbs=np.nonzero(edges[:,r])[0]
#print 'Nbs before:', Nbs
Nbs=Nbs[np.nonzero(Nbs!= c)[0]]
#print 'Nbs after: ', Nbs
allnbmp=1 #neighbors messages passed?
#find all of r's neighbors have sent messages *to* r
for z in range( len(Nbs) ):
#print messages[Nbs[z],r].getVarCount()
if messages[ Nbs[z],r].getVarCount() == 0:
allnbmp=0
if allnbmp == 1:
foundmatch=1
break
if foundmatch==1:
#sys.stderr.write("found match!\n")
i=r
j=c
break
return (i,j)
def CliqueTreeCalibrate( P, isMax=False):
""" this function performs sum-product or max-product algorithm for clique tree calibration.
P is the CliqueTree object. isMax is a boolean flag that when set to True performs Max-Product
instead of the default Sum-Product. The function returns a calibrated clique tree in which the
values of the factors is set to final calibrated potentials.
Once a tree is calibrated, in each clique (node) contains the marginal probability over the variables in
its scope. We can compute the marginal probability of a variable X by choosing a clique that contains the
variable of interest, and summing out non-query variables in the clique. See page 357 in Koller and Friedman
B_i(C_i)= sum_{X-C_i} P_phi(X)
The main advantage of clique tree calibration is that it facilitates the computation of posterior
probabliity of all variables in the graphical model with an efficient number of steps. See pg 358
of Koller and Friedman
After calibration, each clique will contain the marginal (or max-mariginal, if isMax is set to True)
"""
np.set_printoptions(suppress=True)
ctree_edges=P.getEdges()
ctree_cliqueList=P.getNodeList()
""" if max-sum, we work in log space """
if isMax == True:
ctree_cliqueList= [ LogFactor (factor) for factor in ctree_cliqueList ]
N=P.getNodeCount() #Ni is the total number of nodes (cliques) in cTree
#dummyFactor=Factor( [], [], [], 'factor')
#set up messsages to be passed
#MESSAGES[i,j] represents the message going from clique i to clique j
#MESSAGES will be a matrix of Factor objects
MESSAGES=np.tile( Factor( [], [], [], 'factor'), (N,N))
DUMMY=np.reshape( np.arange(N*N)+1, (N,N) )
"""While there are ready cliques to pass messages between, keep passing
messages. Use GetNextCliques to find cliques to pass messages between.
Once you have clique i that is ready to send message to clique
j, compute the message and put it in MESSAGES(i,j).
Remember that you only need an upward pass and a downward pass."""
""" leaf nodes are ready to pass messages right away
so we initialize MESSAGES with leaf message factors
recall, a node is a leave if row sum is equal to 1"""
for row in range(N):
rowsum= np.sum( ctree_edges[row,:] )
if rowsum ==1 :
#Returns a tuple of arrays, one for each dimension, we want the first, hence the [0]
leafnode=np.nonzero( ctree_edges[row,:] )[0].tolist()[0]
#I discovered NumPy set operations http://docs.scipy.org/doc/numpy/reference/routines.set.html
marginalize=np.setdiff1d( ctree_cliqueList[row].getVar(), ctree_cliqueList[leafnode].getVar() ).tolist()
sepset=np.intersect1d( ctree_cliqueList[row].getVar(), ctree_cliqueList[leafnode].getVar() ).tolist()
""" if isMax is false, this is sumproduct, so we do factor marginalization """
if isMax == 0:
#MESSAGES(row,leafnode)=FactorMarginalization(P.cliqueList(row),marginalize);
MESSAGES[row,leafnode]=FactorMarginalization(ctree_cliqueList[row], marginalize )
if np.sum( MESSAGES[row,leafnode].getVal() ) != 1:
newVal=MESSAGES[row,leafnode].getVal() / np.sum( MESSAGES[row,leafnode].getVal() )
MESSAGES[row,leafnode].setVal(newVal)
else:
""" if isMax is true, this is max-marginalization
don't normalize the value just yet"""
MESSAGES[row,leafnode]=FactorMaxMarginalization( ctree_cliqueList[row], marginalize )
""" now that the leaf messages are initialized, we begin with the rest of the clique tree
now we do a single pass to arrive at the calibrated clique tree. We depend on
GetNextCliques to figure out which nodes i,j pass messages to each other"""
while True:
(i,j)=getNextClique(P,MESSAGES)
if sum ( [ i, j] ) == -2:
break
#print 'i: ', i, 'j: ', j
""" similiar to above, we figure out the sepset and what variables to marginalize out
between the two cliques"""
marginalize=np.setdiff1d( ctree_cliqueList[i].getVar(), ctree_cliqueList[j].getVar() ).tolist()
sepset=np.intersect1d( ctree_cliqueList[i].getVar(), ctree_cliqueList[j].getVar() ).tolist()
""" find all the incoming neighbors, except j """
Nbs=np.nonzero( ctree_edges[:,i])[0] #returns a tuple ...
Nbs_minusj=[ elem for elem in Nbs if elem != j ]
#print 'Nbs_minusj: ', Nbs_minusj, ' [i]: ', [i]
#see numpy for matlab users http://www.scipy.org/NumPy_for_Matlab_Users
# these are incoming messages to the ith clique
Nbsfactors=MESSAGES[np.ix_(Nbs_minusj, [i] )].flatten().tolist()
#print DUMMY[np.ix_(Nbs_minusj, [i] )].flatten()
#for f in Nbsfactors:
#print f
""" this is sum/product """
if isMax == 0:
#print 'total number of Nbs factors: ', len(Nbsfactors)
if len(Nbsfactors) == 1:
Nbsproduct=FactorProduct( Nbsfactors[0], IdentityFactor(Nbsfactors[0]) )
else:
Nbsproduct=ComputeJointDistribution( Nbsfactors )
#pdb.set_trace()
#val=Nbsproduct.getVal()
#rowcount=len(val)/3
#print Nbsproduct.getVar()
#print Nbsproduct.getCard()
#print np.reshape( val, (rowcount,3))
#now mulitply wiht the clique factor
CliqueNbsproduct=FactorProduct( Nbsproduct, ctree_cliqueList[i] )
CliqueMarginal= FactorMarginalization ( CliqueNbsproduct, marginalize )
#normalize the marginal
newVal=CliqueMarginal.getVal() / np.sum( CliqueMarginal.getVal() )
CliqueMarginal.setVal( newVal )
MESSAGES[i,j] = CliqueMarginal
else:
if len(Nbsfactors) == 1:
Nbssum=Nbsfactors[0]
else:
Nbssum=reduce ( lambda x,y: FactorSum(x,y), Nbsfactors )
CliqueNbsSum=FactorSum( Nbssum, ctree_cliqueList[i] )
CliqueMarginal=FactorMaxMarginalization( CliqueNbsSum, marginalize )
MESSAGES[i,j] = CliqueMarginal
#print
#######################################################################
""" once out the while True loop, the clique tree has been calibrated
here is where we compute final belifs (potentials) for the cliques and place them in """
for i in range ( len(ctree_cliqueList)):
Nbs=np.nonzero( ctree_edges[:,i])[0]#returns a tuple
Nbsfactors=MESSAGES[np.ix_(Nbs, [i])].flatten().tolist()
if isMax == 0:
if len(Nbsfactors) == 1:
Nbsproduct=FactorProduct( Nbsfactors[0], IdentityFactor(Nbsfactors[0]) )
else:
Nbsproduct=ComputeJointDistribution ( Nbsfactors)
CliqueNbsProduct=FactorProduct(Nbsproduct, ctree_cliqueList[i])
#pdb.set_trace()
ctree_cliqueList[i]=CliqueNbsProduct
else:
if len(Nbsfactors) == 1:
Nbssum=Nbsfactors[0]
else:
Nbssum=reduce ( lambda x,y: FactorSum(x,y), Nbsfactors )
CliqueNbsSum=FactorSum(Nbssum, ctree_cliqueList[i])
ctree_cliqueList[i]=CliqueNbsSum
P.setNodeList( ctree_cliqueList )
#np.savetxt( 'numpy.cTree.edges.calibrated.txt',ctree_edges,fmt='%d', delimiter='\t')
#pdb.set_trace()
#return P
return (P, MESSAGES)
#for k in range(len(ctree_cliqueList)):
# print 'k: ', k
# print ctree_cliqueList[k]
#IndexToAssignment(1:prod(P.cliqueList(1).card), P.cliqueList(1).card)
# I=np.arange(np.prod( ctree_cliqueList[k].getCard() ))
# print IndexToAssignment( I, ctree_cliqueList[k].getCard() )
# print "=="
#return P
def CreatePrunedInitCtree(F,E=[]):
""" 1. create cTree from list of factors F and evidence E
2. prune it
3. compute initial potential of the tree
4. return it"""
cTree = createCliqueTree(F,E)
prunedCTree=PruneTree( cTree )
prunedCTree.incorporateEvidence()
return CliqueTreeInitialPotential( prunedCTree )
def ComputeExactMarginalsBP( F, E=[], isMax=False, computeJoint=0):
""" We take a list of Factor objects, observed Evidence E
and returns marignal proabilities for the variables in the
Bayesian network. If isMax is 1 it runs MAP inference ( *still need to
do this *) otherwise it runs exact inference using Sum/Product algorithm.
The ith element of the returned list represents the ith variable in the
network and its marginal prob of the variable
Note, we implicitly create, prune, initialize, and calibrate a clique tree
constructed from the factor list F """
MARGINALS=[]
#pdb.set_trace()
P = CreatePrunedInitCtree(F,E)
#G=nx.from_numpy_matrix( P.getEdges() )
#nx.draw_shell(G)
#plt.show()
#plt.savefig('cliqueTree.png', bbox_inches=0)
(P,MESSAGES) = CliqueTreeCalibrate(P,isMax)
#pdb.set_trace()
if computeJoint==1:
jointDistribution=ComputeJointDistributionFromCalibratedCliqueTree(P, MESSAGES, isMax)
else:
jointDistribution=None
#pdb.set_trace()
#P = CliqueTreeCalibrate(P,isMax)
cliqueList=P.getNodeList()
fh=open('ExactMarginals.CliqueTree.log','a')
for i in range(len(cliqueList)):
out = ",".join( map(str, cliqueList[i].getVar().tolist() ))
outstring= "node " + str(i) + ":\t" + out +'\n'
fh.write(outstring)
fh.write("\n")
#np.savetxt( 'numpy.cTree.edges.calibrated.txt',P.getEdges(),fmt='%d', delimiter='\t')
np.savetxt('ExactMarginals.CliqueTree.log',P.getEdges(),fmt='%d', delimiter='\t')
""" get the list of unique variables """
V=getUniqueVar(F)
for i in range ( len(V ) ):
for j in range ( len(cliqueList ) ):
if V[i] in cliqueList[j].getVar():
marginalize=np.setdiff1d ( cliqueList[j].getVar(), V[i] ).tolist()
if not marginalize:
MARGINALS.append( cliqueList[j] )
else:
if isMax == 0:
#mfactor=FactorMarginalization(P.cliqueList(j), marginalize);
mfactor=FactorMarginalization( cliqueList[j], marginalize )
newVal=mfactor.getVal() / np.sum( mfactor.getVal() )
mfactor.setVal( newVal )
MARGINALS.append ( mfactor )
else:
mfactor=FactorMaxMarginalization( cliqueList[j], marginalize )
MARGINALS.append( mfactor )
break
return (MARGINALS,jointDistribution)
def ComputeJointDistributionFromCalibratedCliqueTree( P, MESSAGES, isMax=0):
""" this is a function to attempt to compute the joint distribution from
a calibrated clique tree (cTree). The arguments are:
1. The calibrated cTree, P, which is a CliqueTree object
2. The sepset beliefs are is the matrix MESSAGES
The MESSAGES matrix is a matrix of Factor objects
We can get the indices of the sepset messages
from the edges of the clique tree.
This function attempts to implement equation 10.10 in Koller and Friedman
in section 10.2.3: A Calibrated Clique Tree as a Distribution
P_\Phi(X) = \frac{ \prod_{i \in V_T} \Beta_i(C_i) } { \prod_{i-j} \in E_T \mu_i,j(S_i,j) }
Basically A) multiply the clique beliefs
B) multiply the sepset beliefs
C) divide A/B
"""
cliqueFactors=P.getNodeList()
""" if this is a max-marginal calibrated clique tree the values are in log space
Just re-exponentiate them """
if isMax==1:
cliqueFactors = [ ExpFactorNormalize(c) for c in cliqueFactors ]
""" this is the numerator """
cliqueBeliefProducts=reduce(lambda x, y: FactorProduct(x,y), cliqueFactors)
""" get the adjacency matrix of the clique tree """
adj_matrix=P.getEdges()
""" get the nonzero indices, then compute the product of the sepset beliefs """
nonzero_rows=adj_matrix.nonzero()[0].tolist()
nonzero_cols=adj_matrix.nonzero()[1].tolist()
sepsetBeliefsFactors= [ MESSAGES[x,y] for (x,y) in zip(nonzero_rows, nonzero_cols) ]
""" if this is a max-marginal calibrated clique tree the values are in log space
Just re-exponentiate them """
if isMax == 1:
sepsetBeliefsFactors = [ ExpFactorNormalize(c) for c in sepsetBeliefsFactors ]
sepsetBeliefProducts= reduce( lambda x,y: FactorProduct(x,y), sepsetBeliefsFactors)
""" the re-parameterization of the joint (clique tree invariant)
divide the clique beliefs by the sepset messages """
jointDistrbution=FactorDiv(cliqueBeliefProducts, sepsetBeliefProducts)
val=jointDistrbution.getVal()/np.sum( jointDistrbution.getVal() )
jointDistrbution.setVal( val )
return jointDistrbution
|
{"/PythonNotebooks/testCliqueTreeOperations.py": ["/Factor.py", "/PGMcommon.py", "/PedigreeFactors.py", "/FactorOperations.py", "/GeneticNetworkFactory.py", "/CliqueTree.py", "/CliqueTreeOperations.py"], "/CliqueTreeOperations.py": ["/CliqueTree.py", "/FactorOperations.py"], "/GeneticNetworkFactory.py": ["/Factor.py", "/FactorOperations.py", "/PedigreeFactors.py"]}
|
8,756
|
indapa/pgmPy
|
refs/heads/master
|
/GeneticNetworkFactory.py
|
from Factor import *
from FactorOperations import *
from PedigreeFactors import *
import itertools
import numpy as np
"""" Still not sure how this is going to work
This class is a factory for generating a genetic network
If we consider each location in the genome independent
we generate a new network for each position along an interval.
A network is a collection of factors, so we return a python
list of Pedigree factors (either GenotypeAlleleFreqFactor for founders
or GenotypeGivenParentsFactor for non-founders. Each phenotype is conditionally
independent given its genotoype, so each member of the pedigree has a
PhenotypeGivenGenotypeFactor"""
class GeneticNetworkFactory(object):
def __init__(self, pedfile, alphaList, allelefreq, chrom, position):
#parse pedfile
self.alphaList=alphaList
self.allelefreq=allelefreq
self.totalAlleles=len(allelefreq)
self.chrom=chrom
self.pos=position
self.pedigree=Pedfile(pedfile)
self.pedigree.parsePedfile()
self.pedlist=self.pedigree.getPedList()
self.pedids=self.pedigree.returnIndivids()
#print self.pedids
#list of factors that will comprise the Genetic network
self.totalFactors=self.pedigree.getTotalSize() * 2
self.factorList=self.totalFactors*[None]
def constructNetwork(self):
totalPeople=self.pedigree.getTotalSize()
for i in range( totalPeople ):
if self.pedlist[i].isFounder():
#print self.pedlist[i].getid()
self.factorList[i]=GenotypeAlleleFreqFactor(self.allelefreq,i+1,self.pedlist[i].getid() + " genotype ")
#self.factorList[i]=GenotypeAlleleFreqFactor(self.allelefreq,self.pedlist[i].getid(),self.pedlist[i].getid())
#factorList(i)=genotypeGivenAlleleFreqsFactor(alleleFreqs,i);
else:
#3print self.pedlist[i].getParents(), self.pedlist[i].getid()
#GenotypeGivenParentsFactor(2,"bart","homer","marge","""Bart | Homer, Marge """)
#self.factorList[i]=GenotypeGivenParentsFactor(self.totalAlleles, self.pedlist[i].getid(), self.pedlist[i].getParents()[0], self.pedlist[i].getParents()[1], "child|Father,Child")
parent1Index=self.pedids.index( self.pedlist[i].getParents()[0] )
parent2Index=self.pedids.index( self.pedlist[i].getParents()[1] )
child=self.pedlist[i].getid()
parent1name=self.pedlist[parent1Index].getid()
parent2name=self.pedlist[parent2Index].getid()
name=child+" genotype |"+parent1name+","+parent2name
self.factorList[i]=GenotypeGivenParentsFactor(self.totalAlleles, i+1, parent1Index+1 , parent2Index+1 , name)
name=self.pedlist[i].getid()+" phenotype | " + self.pedlist[i].getid() + " genotype"
self.factorList[i+totalPeople]=PhenotypeGivenGenotypeFactor(self.alphaList,i+totalPeople+1,i+1, name )
def getFactorList(self):
return self.factorList
|
{"/PythonNotebooks/testCliqueTreeOperations.py": ["/Factor.py", "/PGMcommon.py", "/PedigreeFactors.py", "/FactorOperations.py", "/GeneticNetworkFactory.py", "/CliqueTree.py", "/CliqueTreeOperations.py"], "/CliqueTreeOperations.py": ["/CliqueTree.py", "/FactorOperations.py"], "/GeneticNetworkFactory.py": ["/Factor.py", "/FactorOperations.py", "/PedigreeFactors.py"]}
|
8,757
|
indapa/pgmPy
|
refs/heads/master
|
/PythonNotebooks/ocr_MAP.py
|
from Factor import *
from PGMcommon import *
from CliqueTree import *
from CliqueTreeOperations import *
from FactorOperations import *
import scipy.io as sio
import numpy as np
import pprint
import pdb
import matplotlib.pyplot as plt
import networkx as nx
matfile='/Users/amit/BC_Classes/PGM/Prog4/PA4Sample.mat'
mat_contents=sio.loadmat(matfile)
mat_struct=mat_contents['OCRNetworkToRun']
val=mat_struct
factorList=[]
ALPHABET=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
for data in val:
(var, card, values)=data[0]
f= Factor( var[0].tolist(), card[0].tolist(), values[0].tolist(), 'factor' )
factorList.append( f )
#MARGINALS= ComputeExactMarginalsBP( factorList, [], 1 )
#MAPAssignment=MaxDecoding( MARGINALS )
#print "".join( [ALPHABET[idx] for idx in MAPAssignment] )
MARGINALS= ComputeExactMarginalsBP( factorList, [], 1 )
for m in MARGINALS:
log_val= m.getVal()
prob_val_normalized=np.log( lognormalize( log_val ) )
m.setVal(prob_val_normalized)
MAPAssignment=MaxDecoding( MARGINALS )
print "".join( [ALPHABET[idx] for idx in MAPAssignment] )
for m in MARGINALS:
print np.sum( lognormalize(m.getVal() ) )
#V=getUniqueVar(factorList)
#print 'unique variables:'
#print V
#cTree=CreatePrunedInitCtree(factorList)
#G=nx.from_numpy_matrix( cTree.getEdges() )
#nx.draw_shell(G)
#plt.show()
|
{"/PythonNotebooks/testCliqueTreeOperations.py": ["/Factor.py", "/PGMcommon.py", "/PedigreeFactors.py", "/FactorOperations.py", "/GeneticNetworkFactory.py", "/CliqueTree.py", "/CliqueTreeOperations.py"], "/CliqueTreeOperations.py": ["/CliqueTree.py", "/FactorOperations.py"], "/GeneticNetworkFactory.py": ["/Factor.py", "/FactorOperations.py", "/PedigreeFactors.py"]}
|
8,758
|
indapa/pgmPy
|
refs/heads/master
|
/Factor.py
|
import sys
import numpy as np
class Factor(object):
""" Represents a factor in a PGM. A factor has variable scope, cardinality, value, and potentially a name.
A factor's values (which can potentially be multi-dimensional table, are represented as NumPy 1d-arrays.
See Chapter10 Friedman pg. 358 and Koller for more info. """
def __init__(self, var=[], card=[], val=[], name= 'None'):
""" a factor has list of variables, each with a cardinality, and for each possible assignment to its variable(s),
a position in the val array."""
self.var= np.array(var)
self.card=np.array(card)
self.val=np.array(val)
self.name=name
def __str__(self):
varstring= " ".join ( map(str, self.var) )
cardstring=" ".join ( map(str, self.card) )
valstring= " ".join( map(str, self.val))
return "\n".join( [ 'name: ' + self.name,'var: '+ varstring, 'card: '+ cardstring, 'val: ' + valstring])
def setVar(self, var):
self.var=np.array(var)
def getVar(self):
return self.var
def getVarCount(self):
return len( self.var.tolist() )
def setVal(self, val):
self.val=np.array(val)
def getVal(self):
return self.val
def setCard(self,card):
self.card=np.array(card)
def getCard(self):
return self.card
def getName(self):
return self.name
def setName(self, name):
self.name=name
|
{"/PythonNotebooks/testCliqueTreeOperations.py": ["/Factor.py", "/PGMcommon.py", "/PedigreeFactors.py", "/FactorOperations.py", "/GeneticNetworkFactory.py", "/CliqueTree.py", "/CliqueTreeOperations.py"], "/CliqueTreeOperations.py": ["/CliqueTree.py", "/FactorOperations.py"], "/GeneticNetworkFactory.py": ["/Factor.py", "/FactorOperations.py", "/PedigreeFactors.py"]}
|
8,759
|
indapa/pgmPy
|
refs/heads/master
|
/FactorOperations.py
|
#!/usr/bin/env python
from Factor import *
import numpy as np
from PGMcommon import *
import sys
import itertools
import common
import pdb
def IndexToAssignment( I, D):
""" given and index I (a row vector representing the indices of values a factor object's val field
and D, an array representing the cadinality of variables in a factor object, this function produces
a matrix of assignments, one assignment per row. See https://github.com/indapa/PGM/blob/master/Prog1/IndexToAssignment.m """
a=np.reshape ( np.arange(np.prod(D)).repeat(len(D)), (np.prod(D),len(D)))
b=tmp=list( D[:-1] )
tmp.insert(0,1)
tmp =np.cumprod ( np.array (tmp) )
b=np.tile( np.cumprod(b), (len(I), 1))
#print b
#print np.floor ( a /b )
c=np.tile ( D, ( len(I), 1) )
assignment = np.mod ( np.floor( a/b), c) +1
return assignment
def AssignmentToIndex ( A, D):
""" I = AssignmentToIndex(A, D) converts an assignment, A, over variables
with cardinality D to an index into the .val vector for a factor.
If A is a matrix then the function converts each row of A to an index.
See https://github.com/indapa/PGM/blob/master/Prog1/AssignmentToIndex.m """
D=D.flatten(0) #turn array into vector (note that this forces a copy), see http://www.scipy.org/NumPy_for_Matlab_Users#head-fd74115e6798fbf3a628094a55d1cb2b2b5cdd3c
I=np.array( [] )
(nrowA,ncolA)=np.shape(A)
if nrowA== 1 or ncolA ==1: #if assginments are 1 row or 1 col
#sys.stderr.write("if block ...\n")
b=tmp=list( D[:-1] )
tmp.insert(0,1)
tmp =np.cumprod ( np.array (tmp) )
tmp=(np.array(np.matrix(tmp)))
#print "tmp: ", tmp
a_flat=np.array ( np.matrix( A.flatten(0) ).transpose() )
#print "a flat: ", a_flat
I= ( tmp * (a_flat-1) ) + 1
return I
else:
#sys.stderr.write("else block ...\n")
b=tmp=list( D[:-1] )
tmp.insert(0,1)
tmp =np.cumprod ( np.array (tmp) )
tmp = np.tile( tmp, (nrowA,1) )
#print tmp
#print (A-1)
I= np.sum( np.multiply(tmp, (A-1)), 1) + 1
return np.array( np.matrix( I ).transpose() )
def SetValueOfAssignment( F, A, v, Vorder=None):
""" % SetValueOfAssignment Sets the value of a variable assignment in a factor.
%
% F = SetValueOfAssignment(F, A, v) sets the value of a variable assignment,
% A, in factor F to v. The order of the variables in A are assumed to be the
% same as the order in F.var.
%
% F = SetValueOfAssignment(F, A, v, VO) sets the value of a variable
% assignment, A, in factor F to v. The order of the variables in A are given
% by the vector VO. See https://github.com/indapa/PGM/blob/master/Prog1/SetValueOfAssignment.m """
if Vorder == None:
indx=AssignmentToIndex( A, F.getCard() )
else:
sys.stderr.write("assumes the order of variables in A are the sayme as in F.var ...\n")
pass
#http://stackoverflow.com/a/5183720, How to make List from Numpy Matrix in Python
#http://stackoverflow.com/a/8373103, numpy function to set elements of array to a value given a list of indices
indices=np.array(indx-1).flatten().tolist()
zeros=np.zeros(len(A))
zeros[indices]=v
F.setVal( zeros.tolist() )
def GetValueOfAssignment( F, A, Vorder = None ):
""" % GetValueOfAssignment Gets the value of a variable assignment in a factor.
%
% v = GetValueOfAssignment(F, A) returns the value of a variable assignment,
% A, in factor F. The order of the variables in A are assumed to be the
% same as the order in F.var.
%
% v = GetValueOfAssignment(F, A, VO) gets the value of a variable assignment,
% A, in factor F. The order of the variables in A are given by the vector VO. See https://github.com/indapa/PGM/blob/master/Prog1/GetValueOfAssignment.m """
if Vorder == None:
indx= AssignmentToIndex ( A, F.getCard() )
else:
sys.stderr.write("The order of the variables in A are assumed to be the same as the order in F var\n")
pass
#pdb.set_trace()
indices=np.array(indx-1).flatten().tolist()
return np.array ( np.matrix ( F.getVal()[indices] ))
def FactorProduct ( A, B):
""" FactorProduct Computes the product of two factors.
% C = FactorProduct(A,B) computes the product between two factors, A and B,
% where each factor is defined over a set of variables with given dimension.
% The factor data structure has the following fields:
% .var Vector of variables in the factor, e.g. [1 2 3]
% .card Vector of cardinalities corresponding to .var, e.g. [2 2 2]
% .val Value table of size prod(.card)
%
% See also FactorMarginalization IndexToAssignment,
% AssignmentToIndex, and https://github.com/indapa/PGM/blob/master/Prog1/FactorProduct.m """
#print "A: ", A
#print "===="
#print "B: ", B
C=Factor()
#check for empty factors
if len( A.getVar() ) == 0 :
sys.stderr.write("A factor is empty!\n")
return B
if len( B.getVar() ) == 0:
sys.stderr.write("B factor is empty!\n")
return A
#check of variables that in both A and B have the same cardinality
#print 'A.getVar(): ', A.getVar()
#print 'B.getVar(): ',B.getVar()
#setA= set( A.getVar() )
#setB= set( B.getVar() )
#intersect=np.array( list( setA.intersection(setB)))
intersect=np.intersect1d( A.getVar(), B.getVar() ).tolist()
#print "Intersection of variables in FactorProduct ", intersect
#print "A var: ", A.getVar()
#print "B var: ", B.getVar()
#if the intersection of variables in the two factors
#is non-zero, then make sure they have the same cardinality
if len(intersect) > 0:
#iA=np.nonzero(intersect - A.getVar()==0)[0].tolist() # see this http://stackoverflow.com/a/432146, return the index of something in an array?
iA=getIndex( A.getVar(), intersect )
#print "iA: ", iA
#iB=np.nonzero(intersect - B.getVar()==0)[0].tolist()
iB = getIndex ( B.getVar(), intersect )
#print "iB: ", iB
# check to see if any of the comparisons in the array resulting from of a.getCard()[iA] == b.getCard()[iB]
# are all False. If so print an error and exit
if len( np.where( A.getCard()[iA].all() == B.getCard()[iB].all() ==False)[0].tolist() ) > 0:
sys.stderr.write("dimensionality mismatch in factors!\n")
sys.exit(1)
#now set the variables of C to the union of variables in factors A and B
#print 'setA ' ,setA
#print 'setB ', setB
#print list( setA.union(setB) )
C.setVar( np.union1d ( A.getVar(), B.getVar() ).tolist() )
#C.setVar ( list( setA.union(setB) ) )
mapA=isMember(A.getVar(), C.getVar() )
mapB=isMember(B.getVar(), C.getVar() )
#Set the cardinality of variables in C
C.setCard( np.zeros( len(C.getVar())).tolist() )
C.getCard()[mapA]=A.getCard()
C.getCard()[mapB]=B.getCard()
#intitialize the values of the factor C to be zero
C.setVal( np.zeros(np.prod(C.getCard())).tolist() )
#some helper indices to tell what indices of A and B values to multiply
assignments=IndexToAssignment( np.arange(np.prod(C.getCard())), C.getCard() ) #get the assignment of values of C
indxA=AssignmentToIndex( assignments[:,mapA], A.getCard())-1 # re-arrange the assignment of C, to what it would be in factor A
indxB=AssignmentToIndex( assignments[:,mapB], B.getCard())-1 # re-arange the assignment of C to what it would be in factorB
c_val=A.getVal()[indxA.flatten().tolist()] * B.getVal()[indxB.flatten().tolist()] #now that we have the index into A.val and B.val vector, multiply them to factor product
C.setVal ( c_val.tolist() )
return C
def FactorMarginalization(A,V):
""" FactorMarginalization Sums given variables out of a factor.
B = FactorMarginalization(A,V) computes the factor with the variables
in V summed out. The factor data structure has the following fields:
.var Vector of variables in the factor, e.g. [1 2 3]
.card Vector of cardinalities corresponding to .var, e.g. [2 2 2]
.val Value table of size prod(.card)
The resultant factor should have at least one variable remaining or this
function will throw an error. See also FactorProduct, IndexToAssignment , and AssignmentToIndex
Based on matlab code found here: https://github.com/indapa/PGM/blob/master/Prog1/FactorMarginalization.m """
#the resulting factor after marginalizing out variables in python list V that are in
#the factor A
B=Factor()
#check for empy factor or variable list
if len( A.getVar() ) == 0 or len(V) == 0:
return A
#construct the variables of the marginalized factor by
#computing the set difference between A.var and V
#These variables in the difference set will be the scope of the new factor
setA=set( A.getVar() )
setV=set(V)
Bvar=np.array( list( setA.difference(setV)))
mapB=isMember(Bvar, A.getVar()) #indices of the variables of the new factor in the original factor A
#print mapB, Bvar
#check to see if the new factor has empty scope
if len(Bvar) == 0:
sys.stderr.write("FactorMarginalization:Error, resultant factor has empty scope...\n")
return None
#set the marginalized factor's variable scope and cardinality
B.setVar( Bvar.tolist() )
B.setCard( A.getCard()[mapB] )
B.setVal( np.zeros(np.prod(B.getCard())).tolist() )
#compute some helper indices
assignments=IndexToAssignment ( np.arange(np.prod(A.getCard()) ), A.getCard() )
#indxB tells which values in A to sum together when marginalizing out the variable(s) in B
indxB=AssignmentToIndex( assignments[:,mapB], B.getCard())-1
#accum is a numpy implementation of matlab accumarray
#accumarray sums data in each group
#here the group(s) are defined in indxB
#indxB is a map to tell which value in A.val to map the sum to
#see http://blogs.mathworks.com/loren/2008/02/20/under-appreciated-accumarray/
marginal_vals=accum(indxB, A.getVal() )
#set the marginal values to the new factor with teh variable(s) in V summed(marginalized) out
B.setVal( marginal_vals.tolist() )
return B
def ObserveEvidence (INPUTS, EVIDENCE):
""" ObserveEvidence Modify a vector of factors given some evidence.
F = ObserveEvidence(INPUTS, EVIDENCE) sets all entries in the vector of factors,INPUTS,
that are not consistent with the evidence, E, to zero. F is a vector of
factors, each a data structure with the following fields:
.var Vector of variables in the factor, e.g. [1 2 3]
.card Vector of cardinalities corresponding to .var, e.g. [2 2 2]
.val Value table of size prod(.card)
EVIDENCE is an N-by-2 matrix, where each row consists of a variable/value pair.
Variables are in the first column and values are in the second column. """
(nrows, ncols)=np.shape(EVIDENCE)
#total_factors=len(INPUTS)
#iterate through evidence
for i in range(nrows):
variable=EVIDENCE[i,0]
value=EVIDENCE[i,1]
#print 'var: ', variable, 'value: ', value
if int(value) == 0:
print "Evidence is not set for variable: ', variable, ' in evidence matrix.\n"
continue
for factor in INPUTS:
#the following returns a list
indx=np.where( factor.getVar() == variable )[0].tolist()
if indx: #if the indx is not empty, it contains the index value of the evidence variable in factor.val array
indx=indx[0]
if value > factor.getCard()[indx] or value < 0:
sys.stderr.write("invalid evidene for variable X_'" + str(variable) + " = " + str(value) + "\n")
sys.exit(1)
#get the assignments of variables for the factor
assignments=IndexToAssignment( np.arange(np.prod( factor.getCard() )), factor.getCard() )
# now get the indices in the assignments that don't agree with the observed value (evidence)
mask=np.where( assignments[:,indx] != value )[0].tolist()
#we are going to update the val array for the current factor
newvals=factor.getVal()
#set the mask indices to zero and reset the val array of the factor
newvals[mask]=0
factor.setVal( newvals.tolist() )
#now check to see the validity of the updated values of the factor
#given the observed evidence. We cannot have all zero values for the factor!
zeroIndices=np.where ( factor.getVal() == 0)[0].tolist()
if len(zeroIndices) == len (factor.getVal() ):
sys.stderr.write("All variable values are zero, which is not possible.\n")
return INPUTS
def ComputeJointDistribution(INPUTS):
""" ComputeJointDistribution Computes the joint distribution defined by a set of given factors
Joint = ComputeJointDistribution(INPUTS) computes the joint distribution
defined by a set of given factors
Joint is a factor that encapsulates the joint distribution given by INPUTS
INPUTS is a vector of Factor objects containing the factors defining the distribution
"""
totalFactors = len(INPUTS)
#check for empty list of INPUTS
if totalFactors== 0:
sys.stderr.write("Empty factor list given as input\n")
return Factor( [], [], [] )
else:
# see http://docs.python.org/library/functions.html#reduce for description of Python reduce function
return reduce(lambda x, y: FactorProduct(x,y), INPUTS)
def ComputeMarginal(V, F, E):
"""
ComputeMarginal Computes the marginal over a set of given variables
M = ComputeMarginal(V, F, E) computes the marginal over variables V
in the distribution induced by the set of factors F, given evidence E
M is a factor containing the marginal over variables V
V is a vector containing the variables in the marginal e.g. [1 2 3] for X_1, X_2 and X_3.
i.e. a result of FactorMarginalization
F is a vector of factors (struct array) containing the factors
defining the distribution
E is an N-by-2 matrix, each row being a variable/value pair.
Variables are in the first column and values are in the second column.
If there is no evidence, pass in the empty matrix [] for E.
"""
totalFactors=len(F)
#reshape a 1d array to 1 x ncol array
#since ObserveEvidence requires Nx2 array, we reshape to a 2 column array
#see http://stackoverflow.com/a/12576163 for reshaping 1d array to 2d array
EVIDENCE= np.reshape( np.array ( E ), (-1,2) )
#print np.shape(EVIDENCE)
if totalFactors == 0:
sys.stderr.write("empty factor list given as input.\n")
return Factor( [], [], [])
# union of all variables in list of factors F
variableList=[] # a list of of lists, where each element is a list containing the variables of the factor in F
for factor in F:
var=factor.getVar().tolist()
variableList.append( var )
#get the union of variables across all the factor in F
#see this http://stackoverflow.com/a/2151553, Pythonic Way to Create Union of All Values Contained in Multiple Lists
union_variables = set().union(*variableList)
#print union_variables
#v contains the variables not in the list of variables in the marginal
v=list( union_variables.difference(V) )
# compute the joint distribution, but then reduce it, given the evidence
# ComputeJointDistribution returns a factor, but ObserveEvidence expects a list
# of factors as the first argument, so hence the need for brackets [ ]
# ObserveEvidence returns a list, but we want the first element so thats why the [0]
jointE= ObserveEvidence ( [ComputeJointDistribution ( F )], EVIDENCE )[0]
#now we need to re-normaize the joint, since observe evidence doesn't do it for us
jointE_normalizedVal = jointE.getVal()/np.sum( jointE.getVal() )
jointE.setVal( jointE_normalizedVal.tolist() )
return FactorMarginalization ( jointE, v)
def IdentityFactor( F ):
return Factor ( F.getVar().tolist(), F.getCard().tolist(), np.ones( np.prod( F.getCard() ) ), F.getName()+ '_identity' )
def SumProductEliminateVar(z, factorList):
""" this is a non-graph based sum-product variable elimination function
z is a variable to eliminate
pass in a list of factors
1. figure out which factor contain z in their variable scope
2. figure out which factors don't contain z in their scope
3. mulitply in all factors that have z
4. sum out z (marginalize) and return new factor with variable z eliminated"""
useFactors = []# list of factors that contains the variable Z
unusedFactors=[] #list of factors that don't contain variable Z
scope = []
"""get a list containining the index in self.factorLlist of factors
that contain the variable Z to be eliminated
get the scope of variables from the factors that contain variable Z """
for fi in factorList:
if z in fi.getVar().tolist():
useFactors.append(fi)#the ith factor is being currently involved in elimination
scope=list(set.union(set(scope), fi.getVar().tolist() ))
else:
unusedFactors.append( fi )
#for f in useFactors:
# print 'useFactor: ', f
#print '==='
#for f in unusedFactors:
# print 'unusedFactor: ', f
psiFactor= ComputeJointDistribution ( useFactors )
tauFactor=FactorMarginalization( psiFactor,[z] )
#print 'psiFactor: ', psiFactor
#print 'tauFactor: ', tauFactor
return unusedFactors + [ tauFactor ]
def SumProductVE ( Z, F ):
""" A wrapper function for SumProductEliminateVar
sum-product variable elimination based on pseudocode algorithm 9.1 in Koller and Friedman
We are giving a list of variables to eliminate in Z (in the order we want to
elimiinate them) and a list of factors F
eliminate each one getting getting the marginal distribution of the last variable in the list
Z. """
for z in Z:
F=SumProductEliminateVar(z, F)
return reduce(lambda x, y: FactorProduct(x,y), F)
def FactorMaxMarginalization( A, V ):
""" computes the factor with the variables in V *maxed* out.
The resulting factor will have all the variables in A minus
those variables in V. This is quite similiar to FactorMarginalization, but rather then summing out variables in V
we take the max. In the code, this translates passing np.max as the function to accum
See section 13.2 in Koller and Friedman for more information"""
B=Factor()
#check for empy factor or variable list
if len( A.getVar() ) == 0 or len(V) == 0:
return A
Bvar=np.setdiff1d( A.getVar(), V)
mapB=isMember(Bvar, A.getVar())
if len(Bvar) == 0:
sys.stderr.write("FactorMaxMarginalization: Error, resultant factor has empty scope...\n")
return np.max (A.getVal() )
#set the marginalized factor's variable scope and cardinality
B.setVar( Bvar.tolist() )
B.setCard( A.getCard()[mapB] )
B.setVal( np.zeros(np.prod(B.getCard())).tolist() )
#compute some helper indices
assignments=IndexToAssignment ( np.arange(np.prod(A.getCard()) ), A.getCard() )
#indxB tells which values in A to sum together when marginalizing out the variable(s) in B
indxB=AssignmentToIndex( assignments[:,mapB], B.getCard())-1
#here we pass in the function np.max
#NumPy and Python are awesome
max_vals=accum(indxB, A.getVal(), np.max )
B.setVal( max_vals.tolist() )
return B
def MaxProductEliminateVar(z, factorList):
""" this is a non-graph based MAX-product variable elimination function
z is a variable to eliminate
pass in a list of factors
1. figure out which factor contain z in their variable scope
2. figure out which factors don't contain z in their scope
3. mulitply in all factors that have z
4. max marginalize out z and return new factor with variable z eliminated"""
useFactors = []# list of factors that contains the variable Z
unusedFactors=[] #list of factors that don't contain variable Z
scope = []
"""get a list containining the index in self.factorLlist of factors
that contain the variable Z to be eliminated
get the scope of variables from the factors that contain variable Z """
for fi in factorList:
if z in fi.getVar().tolist():
useFactors.append(fi)#the ith factor is being currently involved in elimination
scope=list(set.union(set(scope), fi.getVar().tolist() ))
else:
unusedFactors.append( fi )
""" psiFactor is an intermediate factor, prior to max-marginalization """
psiFactor= ComputeJointDistribution ( useFactors )
tauFactor=FactorMaxMarginalization( psiFactor,[z] )
""" we return tuple consisting of
1. a list factors that are unused, plus the result of max-marginal
such that the variable z is not eliminated from the list of factors remaining.
2. For traceback, we return the intermediate factor generated in the process of eliminating
variable z. """
return unusedFactors + [ tauFactor ], psiFactor
def TracebackMAP(FI, Z):
"""We are back-tracing to the most probable assingments here ...
See psuedo-code in Koller and Friedman page 557
In order to return the most probable assignment from MaxProductVE
we take in a list of intermediate factors, FI, that were generated in the process
of MaxProductVE. Z is the same elimination ordering used as MaxProductVE.
We traceback our steps by iterating in reverse order the elimination ordering Z.
Following arguments section 13.2.2 page 558 in Koller and Friedman, as one eliminates
variables you cannot determine their maximizing value. But you can compute their 'conditional'
maximizing value - their max value given the other variables not eliminate yet. Once
the last variable is eliminated, we can traceback to get the maximzing value of the remaining
variables. Hence the reason for iterating thru the elimination ordering Z in reverse order
Returns a python dictionary with key: variable value: variable assignment in the MAP"""
z_i=Z[-1]
f_i=FI[-1]
Z=Z[:-1]
FI=FI[:-1]
#print 'z_i:', z_i
#print 'f_i:', f_i
values=f_i.getVal().tolist()
fidx= IndexToAssignment( np.arange( np.prod( f_i.getCard() ) ), f_i.getCard() )
maxidx=values.index(max(values))
maxed_vars={} #key variable, value: max assignment value
#print 'variable: ', z_i
#print 'max value: ', fidx.flatten()[maxidx]
maxed_vars[z_i]=int(fidx.flatten()[maxidx])
#print maxed_vars
#print
for (z, f) in itertools.izip( reversed(Z), reversed(FI) ):
#print z
#print f
#print 'setdiff: ', np.setdiff1d( f_i.getVar(), [z]).tolist()
variables=np.setdiff1d( f_i.getVar(), [z]).tolist()
evidence=[ [v, maxed_vars[v] ] for v in variables]
#print 'Evidence: ',evidence
f=ObserveEvidence( [f], np.matrix(evidence) )[0]
#print f
values=f.getVal().tolist()
fidx= IndexToAssignment( np.arange( np.prod( f.getCard() ) ), f.getCard() )
#print fidx
#print max(values)
maxidx=values.index(max(values))
maxed_vars[z]=int(fidx.flatten()[maxidx])
#print 'variable: ', z
#print 'max value: ', fidx.flatten()[maxidx]
#print
#print maxed_vars
return maxed_vars
def MaxDecoding ( F ):
""" F is a list of max marginal factors passed in. The factors have a variable scope over a single variable only
So no backtracing is inovlved, we just get the index of the highest number in the value array.
The code here is based on https://github.com/indapa/PGM/blob/master/Prog4/MaxDecoding.m """
ASSIGNMENTS=[]
for f in F:
values=f.getVal().tolist()
ASSIGNMENTS.append ( values.index( max(values) ) )
return ASSIGNMENTS
def MaxDecodingNonUniq ( F ):
""" F is a list of max marginal factors passed in. We don't assume that there is a unique
max value. So we get the indices of the non-uniq max value as a tuple and add it to """
ASSIGNMENTS=[]
for f in F:
values=f.getVal().tolist()
maxvalue=max(values)
""" if the maxvalue is duplicated, we get the indices of where it resides in the value array """
if common.isMaxDuplicated(values):
dup_indices_list=[dup for dup in sorted(common.list_duplicates(values)) ]
dup_values= [ x for (x, y) in dup_indices_list ]
dup_indices= [ y for (x, y) in dup_indices_list ]
non_uniq_max_indices=tuple(dup_indices [ dup_values.index(maxvalue) ])
ASSIGNMENTS.append ( non_uniq_max_indices )
else:
ASSIGNMENTS.append( values.index(maxvalue))
return ASSIGNMENTS
def posterior_genotypes_values(factorList, ALPHABET,samplenames,bedstring,fh):
""" given the factorlist of posterior marginals, the genotype alphabet, samplenames,bedstring position,
and prettybase file handle, print to file the posterior marginals for all 10 possibel genotypes
for each sample. """
genotype_factors=factorList[0:len(samplenames)]
sample_factorObj_zip=zip(samplenames, genotype_factors)
#print bedstring
for sample, f in sample_factorObj_zip:
#print sample, ": "
#values=f.getVal().tolist()
#prob_val_normalized=( lognormalize( f.getVal() ) )
prob_val_normalized=f.getVal()/np.sum(f.getVal())
#print sample
#val=f.getVal()
#print np.sum(val)
#print val/np.sum(val)
#pdb.set_trace()
#print prob_val_normalized.tolist()
#genotype_probZip=zip(ALPHABET,values)
posteriors=[]
#print prob_val_normalized.tolist()
for posterior_val in prob_val_normalized.tolist():
#for posterior_val in values:
posteriors.append(str(posterior_val))
#posteriors.append(str(round(posterior_val,5) ))
#print posteriors
gstring="\t".join(posteriors)
#print gstring
outstring="\t".join([bedstring, sample,gstring])
fh.write(outstring + "\n")
def MaxProductVE ( Z, F ):
""" A wrapper function for MaxProductEliminateVar
sum-product variable elimination based on pseudocode algorithm 9.1 in Koller and Friedman
We are giving a list of variables to eliminate in Z (in the order we want to
elimiinate them) and a list of factors F
eliminate each one getting getting the marginal distribution of the last variable in the list
Z.
Returns the probabliity of the MAP configuration as well as the variable assignments of the MAP configuration"""
intermediateMaxFactors=[]
for z in Z:
(F, intermediateFactor)=MaxProductEliminateVar(z, F)
intermediateMaxFactors.append ( intermediateFactor )
#intermediateMaxFactors.append ( intermediateFactor )
#MaxDecodingBT( intermediateMaxFactors, Z )
bt_results=TracebackMAP( intermediateMaxFactors, Z )
return (reduce(lambda x, y: FactorProduct(x,y), F), bt_results)
def FactorSum ( A, B):
""" FactorSum Computes the sum of two factors.
% Similiar to FactorProduct
We would use this in log space where multiplication becomes addition
% Based on the code here https://github.com/indapa/PGM/blob/master/Prog4/FactorSum.m """
C=Factor()
#check for empty factors
if len( A.getVar() ) == 0 :
sys.stderr.write("A factor is empty!\n")
return B
if len( B.getVar() ) == 0:
sys.stderr.write("B factor is empty!\n")
return A
#check of variables that in both A and B have the same cardinality
#print 'A.getVar(): ', A.getVar()
#print 'B.getVar(): ',B.getVar()
#setA= set( A.getVar() )
#setB= set( B.getVar() )
#intersect=np.array( list( setA.intersection(setB)))
intersect=np.intersect1d( A.getVar(), B.getVar() ).tolist()
#print "Intersection of variables in FactorProduct ", intersect
#print "A var: ", A.getVar()
#print "B var: ", B.getVar()
#if the intersection of variables in the two factors
#is non-zero, then make sure they have the same cardinality
if len(intersect) > 0:
#iA=np.nonzero(intersect - A.getVar()==0)[0].tolist() # see this http://stackoverflow.com/a/432146, return the index of something in an array?
iA=getIndex( A.getVar(), intersect )
#print "iA: ", iA
#iB=np.nonzero(intersect - B.getVar()==0)[0].tolist()
iB = getIndex ( B.getVar(), intersect )
#print "iB: ", iB
# check to see if any of the comparisons in the array resulting from of a.getCard()[iA] == b.getCard()[iB]
# are all False. If so print an error and exit
if len( np.where( A.getCard()[iA].all() == B.getCard()[iB].all() ==False)[0].tolist() ) > 0:
sys.stderr.write("dimensionality mismatch in factors!\n")
sys.exit(1)
#now set the variables of C to the union of variables in factors A and B
#print 'setA ' ,setA
#print 'setB ', setB
#print list( setA.union(setB) )
C.setVar( np.union1d ( A.getVar(), B.getVar() ).tolist() )
#C.setVar ( list( setA.union(setB) ) )
mapA=isMember(A.getVar(), C.getVar() )
mapB=isMember(B.getVar(), C.getVar() )
#Set the cardinality of variables in C
C.setCard( np.zeros( len(C.getVar())).tolist() )
C.getCard()[mapA]=A.getCard()
C.getCard()[mapB]=B.getCard()
#intitialize the values of the factor C to be zero
C.setVal( np.zeros(np.prod(C.getCard())).tolist() )
#some helper indices to tell what indices of A and B values to multiply
assignments=IndexToAssignment( np.arange(np.prod(C.getCard())), C.getCard() ) #get the assignment of values of C
indxA=AssignmentToIndex( assignments[:,mapA], A.getCard())-1 # re-arrange the assignment of C, to what it would be in factor A
indxB=AssignmentToIndex( assignments[:,mapB], B.getCard())-1 # re-arange the assignment of C to what it would be in factorB
#print 'indxA ', indxA
#print 'indxB ', indxB
c_val=A.getVal()[indxA.flatten().tolist()] + B.getVal()[indxB.flatten().tolist()] #now that we have the index into A.val and B.val vector, multiply them to factor product
C.setVal ( c_val.tolist() )
return C
def LogFactor( F ):
""" return a factor whose values are the natural log of the orginal factor F """
return Factor ( F.getVar().tolist(), F.getCard().tolist(), np.log ( F.getVal() ).tolist(), F.getName() )
def ExpFactorNormalize ( logF ):
""" exponentiate a factor to probablity space from log space
Since moving from log space to probablity space incures a decrease in dynamic range,
factors should be normalized before applying the transform. One trick we use here is
to shift every entry by the maximum entry. For example: phi[i] = exp{logPhi[i] -c}
The value of c is max(logPhi). This type of transformation ensures the resulting factor
has a maximum entry of 1 and prevents overflow. See page 360 of Koller and Friedman text"""
logPhi=logF.getVal()
#phi=lognormalize( logPhi )
phi=np.exp(logPhi-np.max(logPhi) )
logF.setVal( phi )
return logF
def ExpFactor( logF ):
""" similiar to above, but don't normalize """
logPhi=logF.getVal()
phi=np.exp( logPhi )
logF.setVal( phi )
return logF
def FactorDiv ( A, B):
""" FactorProduct Computes the dividend of two factors.
% Similiar to Factor Product, but if we divide 0/0, return 0
see page 365 in Koller and Friedman for definition of FactorDivision """
#print "A: ", A
#print "===="
#print "B: ", B
C=Factor()
#check for empty factors
if len( A.getVar() ) == 0 :
sys.stderr.write("A factor is empty!\n")
return B
if len( B.getVar() ) == 0:
sys.stderr.write("B factor is empty!\n")
return A
#check of variables that in both A and B have the same cardinality
#print 'A.getVar(): ', A.getVar()
#print 'B.getVar(): ',B.getVar()
#setA= set( A.getVar() )
#setB= set( B.getVar() )
#intersect=np.array( list( setA.intersection(setB)))
intersect=np.intersect1d( A.getVar(), B.getVar() ).tolist()
#print "Intersection of variables in FactorProduct ", intersect
#print "A var: ", A.getVar()
#print "B var: ", B.getVar()
#if the intersection of variables in the two factors
#is non-zero, then make sure they have the same cardinality
if len(intersect) > 0:
#iA=np.nonzero(intersect - A.getVar()==0)[0].tolist() # see this http://stackoverflow.com/a/432146, return the index of something in an array?
iA=getIndex( A.getVar(), intersect )
#print "iA: ", iA
#iB=np.nonzero(intersect - B.getVar()==0)[0].tolist()
iB = getIndex ( B.getVar(), intersect )
#print "iB: ", iB
# check to see if any of the comparisons in the array resulting from of a.getCard()[iA] == b.getCard()[iB]
# are all False. If so print an error and exit
if len( np.where( A.getCard()[iA].all() == B.getCard()[iB].all() ==False)[0].tolist() ) > 0:
sys.stderr.write("dimensionality mismatch in factors!\n")
sys.exit(1)
#now set the variables of C to the union of variables in factors A and B
#print 'setA ' ,setA
#print 'setB ', setB
#print list( setA.union(setB) )
C.setVar( np.union1d ( A.getVar(), B.getVar() ).tolist() )
#C.setVar ( list( setA.union(setB) ) )
mapA=isMember(A.getVar(), C.getVar() )
mapB=isMember(B.getVar(), C.getVar() )
#Set the cardinality of variables in C
C.setCard( np.zeros( len(C.getVar())).tolist() )
C.getCard()[mapA]=A.getCard()
C.getCard()[mapB]=B.getCard()
#intitialize the values of the factor C to be zero
C.setVal( np.zeros(np.prod(C.getCard())).tolist() )
#some helper indices to tell what indices of A and B values to multiply
assignments=IndexToAssignment( np.arange(np.prod(C.getCard())), C.getCard() ) #get the assignment of values of C
indxA=AssignmentToIndex( assignments[:,mapA], A.getCard())-1 # re-arrange the assignment of C, to what it would be in factor A
indxB=AssignmentToIndex( assignments[:,mapB], B.getCard())-1 # re-arange the assignment of C to what it would be in factorB
numerator=A.getVal()[indxA.flatten().tolist()]
denominator=B.getVal()[indxB.flatten().tolist()]
#print numerator
#print denominator
#print zip(numerator, denominator)
val= map( lambda x: common.zerodiv_tuple(x), zip(numerator,denominator) )
#print val
C.setVal ( val )
return C
def variableStride( f ):
""" given a Factor object f, calculate its variable stride in value array of the factor """
strides=[]
iF=IndexToAssignment ( np.arange(np.prod(f.getCard()) ), f.getCard() )
variables=f.getVar()
cardinalties=f.getCard()
for i in range(0, len(variables) ):
#assignment_slice=iF[:,i]
#var_card=cardinalties[i]
#print variables[i], cardinalties[i]
curr_stride=iF[:,i]
if cardinalties[i] > 1:
stride=np.where(curr_stride==2)
else:
stride=0
strides.append(stride)
continue
#print variables[i], cardinalties[i], stride[0][0]
strides.append( stride[0][0] )
#print
return strides
def IndexOfAssignment( f, strides, assignment):
""" given a Factor object f and the strides of each of the variables of f and
a list of assignments of those variables, return the position in the value array of that assignment
see page 358 box 10.a in Friedman and Koller text on how efficiently map a particular variable
assignment to the and index in the value array of a factor
"""
idx=0
#cardinalities=f.getCard()
for (ass, stride) in zip( assignment, strides):
#print ass, stride
idx +=(ass *stride)
return idx
|
{"/PythonNotebooks/testCliqueTreeOperations.py": ["/Factor.py", "/PGMcommon.py", "/PedigreeFactors.py", "/FactorOperations.py", "/GeneticNetworkFactory.py", "/CliqueTree.py", "/CliqueTreeOperations.py"], "/CliqueTreeOperations.py": ["/CliqueTree.py", "/FactorOperations.py"], "/GeneticNetworkFactory.py": ["/Factor.py", "/FactorOperations.py", "/PedigreeFactors.py"]}
|
8,790
|
youilab/ShowGeoData
|
refs/heads/master
|
/prueba.py
|
import mapGeoData as mp
import pandas as pd
mapa = mp.set_data('SLP_mancha.shp')
slp = mp.read_shapefile(mapa)
y_lim = (22.00, 22.25)#latitude
x_lim = (-101.1, -100.83)#longitude
#Grafica el polígono 30 del mapa
#mp.plot_shape(30, mapa)
#Grafica el mapa dados los limites en X y Y
#mp.plot_map(mapa, x_lim, y_lim)
#Muestra los polígonos del 100 al 150 en el mapa en color verde
#ids = range(100, 150)
#mp.fill_multiples_shapes(ids, mapa, x_lim, y_lim, color='g')
#Muestra el polígono 30 con un relleno color rojo
#mp.fill_shape_into_map(30, mapa, x_lim, y_lim, color='r')
#Muestra los polígonos del 100 al 150 rellenos en rojo dentro del mapa
#ids = range(100, 150)
#mp.fill_multiples_shapes(ids, mapa, x_lim, y_lim, color='r')
#Muestra un mapa de calor dados los datos de nivel de riesgo
cds_data = pd.read_csv('cds_ssslp.data.csv')
cds_data_risk = cds_data[['Riesgo','lat','long']]
dat, ids = mp.get_heat_data(slp, cds_data_risk)
mp.fill_multiples_ids_tone(mapa, dat, ids, 8, x_lim, y_lim)
|
{"/prueba.py": ["/mapGeoData.py"], "/Densidad/densidad_pob.py": ["/mapGeoData.py"]}
|
8,791
|
youilab/ShowGeoData
|
refs/heads/master
|
/density.py
|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.neighbors import KernelDensity
try:
from mpl_toolkits.basemap import Basemap
basemap = True
except ImportError:
basemap = False
df = pd.read_csv('cds_ssslp.data.csv')
# Filter SLP location data in
lat = df['lat']
long = df['long']
risk = df['Riesgo']
slp_top_left = [22.219247, -101.053618]
slp_bottom_right = [22.023170, -100.817158]
inslp = [];
count = 0;
for i in range(len(lat)):
inslp.append(False);
if lat[i] < slp_top_left[0] and lat[i] > slp_bottom_right[0] and long[i] > slp_top_left[1] and long[i] < slp_bottom_right[1]:
inslp[i] = True;
count = count +1;
latSLP = []
longSLP = []
riskSLP = []
label = []
for i in range(len(risk)):
label.append(False)
if risk[i] == "MARRON" or risk[i] == "ROJO" or risk[i] == "MORADO":
label[i] = True;
for i in range(len(lat)):
if inslp[i] == True and label[i] == True:
latSLP.append(lat[i])
longSLP.append(long[i])
riskSLP.append(risk[i])
opt = ["Bajo", # AMARILLO 0
"Grave", # MARRON 1
"Síntomas respiratorios",#MORADO 2
"Medio ", #NARANJA 3
"Alto", #ROJO 4
"Sin riesgo" #VERDE 5
];
# compuate data arrays for KDE
Xtrain = np.vstack([latSLP, longSLP]).T
Xtrain *= np.pi / 180. # Convert lat/long to radians
kde = KernelDensity(bandwidth=0.0001, metric='haversine',
kernel='gaussian', algorithm='ball_tree')
kde.fit(Xtrain)
# compute grid
gridSize = 500
ygrid = np.linspace(slp_bottom_right[0], slp_top_left[0], gridSize )
xgrid = np.linspace(slp_bottom_right[1], slp_top_left[1], gridSize )
X, Y = np.meshgrid(xgrid, ygrid)
xy = np.vstack([Y.ravel(), X.ravel()]).T
xy *= np.pi / 180.
Z = np.exp(kde.score_samples(xy))
Z = Z.reshape(X.shape)
fig = plt.figure()
levels = np.linspace(0, Z.max(), 25)
#contour = plt.contour(X, Y, Z, levels=levels, cmap=plt.cm.Reds)
plt.contour(X,Y,Z, levels=levels, cmap=plt.cm.Reds)
plt.show()
|
{"/prueba.py": ["/mapGeoData.py"], "/Densidad/densidad_pob.py": ["/mapGeoData.py"]}
|
8,792
|
youilab/ShowGeoData
|
refs/heads/master
|
/mapGeoData.py
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import shapefile as shp
import seaborn as sns
from shapely.geometry import Point, Polygon
def set_data(path):
'''
Returns a shapefile object
'''
return shp.Reader(path)
def read_shapefile(mapa):
"""
Read a shapefile into a Pandas dataframe with a 'coords'
column holding the geometry information. This uses the pyshp
package
"""
fields = [x[0] for x in mapa.fields][1:]
records = mapa.records()
shps = [s.points for s in mapa.shapes()]
df = pd.DataFrame(columns=fields, data=records)
df = df.assign(coords=shps)
return df
def plot_shape(id, mapa):
""" PLOTS A SINGLE SHAPE """
plt.figure()
ax = plt.axes()
ax.set_aspect('equal')
shape_ex = mapa.shape(id)
df = read_shapefile(mapa)
x_lon = np.zeros((len(shape_ex.points),1))
y_lat = np.zeros((len(shape_ex.points),1))
for ip in range(len(shape_ex.points)):
x_lon[ip] = shape_ex.points[ip][0]
y_lat[ip] = shape_ex.points[ip][1]
plt.plot(x_lon,y_lat)
x0 = np.mean(x_lon)
y0 = np.mean(y_lat)
plt.text(x0, y0, df.iloc[id]['Name'], fontsize=10)
# use bbox (bounding box) to set plot limits
plt.xlim(shape_ex.bbox[0],shape_ex.bbox[2])
plt.show()
#return x0, y0
def plot_map(mapa, x_lim=None, y_lim=None, figsize=(11, 9)):
'''
Requires the set_data shapefile object.
Plot map with lim coordinates
'''
plt.figure(figsize=figsize)
id = 0
for shape in mapa.shapeRecords():
x = [i[0] for i in shape.shape.points[:]]
y = [i[1] for i in shape.shape.points[:]]
plt.plot(x, y, 'k')
if (x_lim == None) & (y_lim == None):
x0 = np.mean(x)
y0 = np.mean(y)
plt.text(x0, y0, id, fontsize=10)
id = id + 1
if (x_lim != None) & (y_lim != None):
plt.xlim(x_lim)
plt.ylim(y_lim)
plt.show()
def plot_shape_into_map(id, mapa, x_lim=None, y_lim=None, figsize=(11, 9)):
'''
Highlight a single shape within a map
'''
plt.figure(figsize=figsize)
for shape in mapa.shapeRecords():
x = [i[0] for i in shape.shape.points[:]]
y = [i[1] for i in shape.shape.points[:]]
plt.plot(x, y, 'k')
shape_ex = mapa.shape(id)
x_lon = np.zeros((len(shape_ex.points), 1))
y_lat = np.zeros((len(shape_ex.points), 1))
for ip in range(len(shape_ex.points)):
x_lon[ip] = shape_ex.points[ip][0]
y_lat[ip] = shape_ex.points[ip][1]
plt.plot(x_lon, y_lat, 'r', linewidth=2)
if (x_lim != None) & (y_lim != None):
plt.xlim(x_lim)
plt.ylim(y_lim)
plt.show()
def fill_shape_into_map(id, mapa, x_lim=None, y_lim=None, figsize=(11, 9), color = 'r'):
'''
Fill a single shape within a map
'''
plt.figure(figsize=figsize)
for shape in mapa.shapeRecords():
x = [i[0] for i in shape.shape.points[:]]
y = [i[1] for i in shape.shape.points[:]]
plt.plot(x, y, 'k')
shape_ex = mapa.shape(id)
x_lon = np.zeros((len(shape_ex.points), 1))
y_lat = np.zeros((len(shape_ex.points), 1))
for ip in range(len(shape_ex.points)):
x_lon[ip] = shape_ex.points[ip][0]
y_lat[ip] = shape_ex.points[ip][1]
plt.fill(x_lon,y_lat, color)
if (x_lim != None) & (y_lim != None):
plt.xlim(x_lim)
plt.ylim(y_lim)
plt.show()
def fill_multiples_shapes(ids, mapa, x_lim=None, y_lim=None, figsize=(11, 9), color='r'):
'''
Fill multiple shapes by id within a map
'''
plt.figure(figsize=figsize)
for shape in mapa.shapeRecords():
x = [i[0] for i in shape.shape.points[:]]
y = [i[1] for i in shape.shape.points[:]]
plt.plot(x, y, 'k')
for id in ids:
shape_ex = mapa.shape(id)
x_lon = np.zeros((len(shape_ex.points), 1))
y_lat = np.zeros((len(shape_ex.points), 1))
for ip in range(len(shape_ex.points)):
x_lon[ip] = shape_ex.points[ip][0]
y_lat[ip] = shape_ex.points[ip][1]
plt.fill(x_lon, y_lat, color)
#x0 = np.mean(x_lon)
#y0 = np.mean(y_lat)
#plt.text(x0, y0, id, fontsize=10)
if (x_lim != None) & (y_lim != None):
plt.xlim(x_lim)
plt.ylim(y_lim)
plt.show()
def calc_color(data, color=None):
"""
Set the color scales for a heating map
"""
if color == 1:
color_sq = ['#dadaebFF', '#bcbddcF0', '#9e9ac8F0', '#807dbaF0', '#6a51a3F0', '#54278fF0']
colors = 'Purples'
elif color == 2:
color_sq = ['#c7e9b4', '#7fcdbb', '#41b6c4', '#1d91c0', '#225ea8', '#253494']
colors = 'YlGnBu'
elif color == 3:
color_sq = ['#f7f7f7', '#d9d9d9', '#bdbdbd', '#969696', '#636363', '#252525']
colors = 'Greys'
elif color == 9:
color_sq = ['#ff0000', '#ff0000', '#ff0000', '#ff0000', '#ff0000', '#ff0000']
else:
color_sq = ['#ffffd4', '#fee391', '#fec44f', '#fe9929', '#d95f0e', '#993404']
colors = 'YlOrBr'
dat = set(data)
dat = list(dat)
new_data, bins = pd.qcut(dat, 6, retbins=True, labels=list(range(6)))
color_ton = []
for val in new_data:
color_ton.append(color_sq[val])
tonos = []
for i in range(len(data)):
if data[i] > 0 and data[i] < int(bins[1]):
tonos.append(color_sq[0])
if data[i] > int(bins[1])-1 and data[i] < int(bins[2]):
tonos.append(color_sq[1])
if data[i] > int(bins[2])-1 and data[i] < int(bins[3]):
tonos.append(color_sq[2])
if data[i] > int(bins[3])-1 and data[i] < int(bins[4]):
tonos.append(color_sq[3])
if data[i] > int(bins[4])-1 and data[i] < int(bins[5]):
tonos.append(color_sq[4])
if data[i] > int(bins[5])-1:
tonos.append(color_sq[5])
if color != 9:
colors = sns.color_palette(colors, n_colors=6)
sns.palplot(colors, 0.6)
#for i in range(6):
# print("\n" + str(i + 1) + ': ' + str(int(bins[i])) + " => " + str(int(bins[i + 1]) - 1), end=" ")
#print("\n\n 1 2 3 4 5 6")
return tonos, bins
def plot_ids_data(mapa, ids, data=None, color=None):
'''
Plot map with selected comunes, using specific color
'''
color_ton, bins = calc_color(data, color)
df = read_shapefile(mapa)
comuna_id = []
for i in ids:
i = conv_comuna(i).upper()
comuna_id.append(df[df.NOM_COMUNA == i.upper()].index.get_values()[0])
fill_multiples_ids_tone(mapa, ids, color_ton, bins, x_lim=None, y_lim=None, figsize=(11, 9))
def fill_multiples_ids_tone(mapa, data, ids, color, x_lim=None, y_lim=None, figsize=(11, 9)):
'''
Plot map with lim coordinates
'''
color_ton, bins = calc_color(data, color)
plt.figure(figsize=figsize)
#fig, ax = plt.subplots(figsize=figsize)
for shape in mapa.shapeRecords():
x = [i[0] for i in shape.shape.points[:]]
y = [i[1] for i in shape.shape.points[:]]
plt.plot(x, y, 'k')
for id in range(len(ids)):
shape_ex = mapa.shape(ids[id])
x_lon = np.zeros((len(shape_ex.points), 1))
y_lat = np.zeros((len(shape_ex.points), 1))
for ip in range(len(shape_ex.points)):
x_lon[ip] = shape_ex.points[ip][0]
y_lat[ip] = shape_ex.points[ip][1]
plt.fill(x_lon, y_lat, color_ton[id])
if (x_lim != None) & (y_lim != None):
plt.xlim(x_lim)
plt.ylim(y_lim)
plt.show()
def get_heat_data(map, app_data):
"""
Requires a pandas dataFrame containing the fields: Riesgo, lat, long
Returns the ids and the given risk value for each id
"""
k = 0
data = np.zeros(len(map))
for i in range(len(app_data)):
coords = Point(app_data['long'].iloc[i], app_data['lat'].iloc[i])
for j in range(len(map)):
poly = Polygon(map['coords'].iloc[j])
if coords.within(poly):
k += 1
if app_data['Riesgo'].iloc[i] == 'AMARILLO':
data[j] += 1
if app_data['Riesgo'].iloc[i] == 'NARANJA':
data[j] += 2
if app_data['Riesgo'].iloc[i] == 'ROJO':
data[j] += 3
if app_data['Riesgo'].iloc[i] == 'MARRON':
data[j] += 4
if app_data['Riesgo'].iloc[i] == 'MORADO':
data[j] += 5
dat = []
ids = []
for i in range(len(data)):
if data[i] > 0:
dat.append(int(data[i]))
ids.append(i)
return dat, ids
|
{"/prueba.py": ["/mapGeoData.py"], "/Densidad/densidad_pob.py": ["/mapGeoData.py"]}
|
8,793
|
youilab/ShowGeoData
|
refs/heads/master
|
/Densidad/densidad_pob.py
|
import pandas as pd
import mapGeoData as mp
import numpy as np
from shapely.geometry import Point, Polygon
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from haversine import haversine, Unit
def get_heat_data(map, app_data):
k = 0
data = np.zeros(len(map))
for i in range(len(app_data)):
coords = Point(app_data['long'].iloc[i], app_data['lat'].iloc[i])
for j in range(len(map)):
poly = Polygon(map['coords'].iloc[j])
if coords.within(poly):
k += 1
if app_data['Riesgo'].iloc[i] != 'VERDE':
data[j] += 1
dat = []
ids = []
for i in range(len(data)):
if data[i] > 0:
dat.append(int(data[i]))
ids.append(i)
return dat, ids
def calc_color(data, nom, color=None):
"""
Set the color scales for a heating map
"""
nom = nom + '_paleta.png'
if color == 1:
color_sq = ['#dadaebFF', '#bcbddcF0', '#9e9ac8F0', '#807dbaF0', '#6a51a3F0', '#54278fF0']
#Purples
elif color == 2:
color_sq = ['#ccffe5', '#84ffe0', '#2db7b7', '#3399CC', '#3366CC', '#000099']
#Blues
elif color == 3:
color_sq = ['#e4bfbf', '#c97f7f', '#ae3f3f', '#942525', '#631919', '#310c0c']
#Brouns
elif color == 4:
color_sq = ['#ffffcc', '#ffff99', '#ffff66', '#ffff00', '#cccc00', '#7f7f00']
#Yellows
elif color == 5:
color_sq = ['#ffcccc', '#ff7f7f', '#ff4c4c', '#ff0000', '#7f0000', '#4c0000']
#Reds
elif color == 6:
color_sq = ['#ffe4b2', '#ffc966', '#ffae19', '#ffa500', '#cc8400', '#7f5200']
#Oranges
elif color == 7:
color_sq = ['#b2d8b2', '#66b266', '#329932', '#008000', '#005900', '#003300']
#Geens
elif color == 9:
color_sq = ['#ff0000', '#ff0000', '#ff0000', '#ff0000', '#ff0000', '#ff0000']
else:
color_sq = ['#ffffd4', '#fee391', '#fec44f', '#fe9929', '#d95f0e', '#993404']
#Heat
dat = set(data)
if max(dat) >= 6:
n = 6
elif max(dat) < 6:
n = max(dat)
dat = list(dat)
try:
new_data, bins = pd.qcut(dat, n, retbins=True, labels=list(range(n)))
except:
new_data, bins = pd.qcut(dat, 6, retbins=True, labels=False)
color_ton = []
for val in new_data:
color_ton.append(color_sq[val])
tonos = []
if max(dat) > 6:
for i in range(len(data)):
if data[i] > 0 and data[i] < int(bins[1]):
tonos.append(color_sq[0])
if data[i] > int(bins[1])-1 and data[i] < int(bins[2]):
tonos.append(color_sq[1])
if data[i] > int(bins[2])-1 and data[i] < int(bins[3]):
tonos.append(color_sq[2])
if data[i] > int(bins[3])-1 and data[i] < int(bins[4]):
tonos.append(color_sq[3])
if data[i] > int(bins[4])-1 and data[i] < int(bins[5]):
tonos.append(color_sq[4])
if data[i] > int(bins[5])-1 :
tonos.append(color_sq[5])
elif max(dat) < 7:
#try:
#for i in range(len(data)):
# print("hola2")
# tonos.append(color_sq[new_data[i]-1])
f = 0
#except:
for i in range(len(data)):
if data[i] > 0 and data[i] < bins[1]:
tonos.append(color_sq[0])
f += 1
elif data[i] >= bins[1] and data[i] < bins[2]:
tonos.append(color_sq[1])
f += 1
elif data[i] >= bins[2] and data[i] < bins[3]:
tonos.append(color_sq[2])
f += 1
elif data[i] >= bins[3] and data[i] < bins[4]:
tonos.append(color_sq[3])
f += 1
elif data[i] >= bins[4] and data[i] < bins[5]:
tonos.append(color_sq[4])
f += 1
elif data[i] >= bins[5] - 1:
tonos.append(color_sq[5])
f += 1
return tonos, bins, color_sq
def fill_multiples_ids_tone(Lat, Long, mapa, data, ids, color, nom, ids_slp, x_lim=None, y_lim=None, figsize=(19.37, 17.86)):
'''
Plot map with lim coordinates
'''
ids_no = [801, 815, 814, 802, 806, 798, 774, 727, 762, 547, 612, 493, 364, 390, 402, 492, 794,
473, 399, 406, 382, 378, 304, 371, 370, 476, 779, 403, 387, 745, 770, 800, 809, 803,
805, 808, 797, 807, 816, 804, 365, 363, 375, 376, 813, 811, 810, 791, 817, 799, 812]
color_ton, bins, color_sq = calc_color(data, nom, color)
labels = []
print(bins)
#if max(data) < 7:
for i in range(6):
if i == 0:
labels.append('0 - ' + str(round(bins[1],3)))
else:
labels.append(str(round(bins[i], 1)) + ' - ' + str(round(bins[i+1], 1)))
"""
elif max(data) > 6:
for i in range(6):
labels.append(bins[i+1]/max(data))
labels[i] *= 100
if i == 0:
labels[i] = round(labels[i], 2)
labels[i] = '0% - ' + str(labels[i]) + '%'
else:
labels[i] = round(labels[i], 2)
lbl1 = bins[i]/max(data)
lbl1 *= 100
lbl1 = round(lbl1 + 0.01,2)
labels[i] = str(lbl1) + '% - ' + str(round(labels[i],1)) + '%'
"""
plt.figure(figsize=figsize)
#fig, ax = plt.subplots(figsize=figsize)
d = 0
for shape in mapa.shapeRecords():
d += 1
if d not in ids_no:
x = [i[0] for i in shape.shape.points[:]]
y = [i[1] for i in shape.shape.points[:]]
#x0 = np.mean(x)
#y0 = np.mean(y)
#plt.text(x0, y0, d, fontsize=8)
plt.plot(x, y, 'k')
#print(len(color_ton))
#print(ids)
notfill = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 29, 32, 99, 102, 173, 395, 384, 368, 351, 412,
400, 415, 417, 418, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 32]
for i in range(len(ids)):
if i not in notfill:
"""if i > 412 and i < 416:#390
shape_ex = mapa.shape(ids[i])
x_lon = np.zeros((len(shape_ex.points), 1))
y_lat = np.zeros((len(shape_ex.points), 1))
for ip in range(len(shape_ex.points)):
x_lon[ip] = shape_ex.points[ip][0]
y_lat[ip] = shape_ex.points[ip][1]
plt.fill(x_lon, y_lat, "#ff0000")
else:"""
shape_ex = mapa.shape(ids[i])
x_lon = np.zeros((len(shape_ex.points), 1))
y_lat = np.zeros((len(shape_ex.points), 1))
for ip in range(len(shape_ex.points)):
x_lon[ip] = shape_ex.points[ip][0]
y_lat[ip] = shape_ex.points[ip][1]
plt.fill(x_lon, y_lat, color_ton[i])
if (x_lim != None) & (y_lim != None):
plt.xlim(x_lim)
plt.ylim(y_lim)
lgnd = []
for k in range(len(color_sq)):
lgnd.append(mpatches.Patch(color=color_sq[k]))
plt.legend(lgnd, labels, loc="best", prop={'size': 12})
plt.axis('off')
plt.tight_layout()
plt.scatter(Long, Lat, marker='o', color='red', s=80, zorder=3)
#plt.savefig(nom)
plt.savefig("test_densidad.svg", format="svg")
d_pob = mp.set_data('Poblacion_Densidad_secc_mun.shp')
slp_dp = mp.read_shapefile(d_pob)
#estado
# y_lim = (21.07, 24.53)#latitude
#x_lim = (-102.33, -98.3)#longitude
#capital
y_lim = (22.0684, 22.229)#latitude
x_lim = (-101.057, -100.869)#longitude
H = haversine([y_lim[0], x_lim[0]], [y_lim[0], x_lim[1]])
W = haversine([y_lim[0], x_lim[0]], [y_lim[1], x_lim[0]])
#Muestra un mapa de calor dados los datos de nivel de riesgo
cds_data = pd.read_csv('cds_ssslp.data.csv')
#ids_not = [801, 815, 814, 802, 806, 798, 774, 727, 762, 547, 612, 493, 364,
# 390, 402, 492, 473, 399, 406, 382, 378, 304, 371, 370, 476, 779,
# 403, 387, 745, 770, 800, 809, 805, 808, 797, 807, 816, 804]
slp_top_left = [22.219247, -101.053618]
slp_bottom_right = [22.023170, -100.817158]
lat = cds_data['lat']
long = cds_data['long']
inslp = []
count = 0;
for i in range(len(lat)):
inslp.append(False);
if lat[i] < slp_top_left[0] and lat[i] > slp_bottom_right[0] and long[i] > slp_top_left[1] and long[i] < slp_bottom_right[1]:
inslp[i] = True;
count = count +1;
indices = []
for i in range(len(cds_data)):
if not inslp[i]:
indices.append(i)
csv = cds_data.drop(indices)
Lat = []
Long = []
for i in range(len(csv)):
if csv['Riesgo'].iloc[i] != 'VERDE':
Lat.append(float(csv['lat'].iloc[i]))
Long.append(float(csv['long'].iloc[i]))
#plt.scatter(Long, Lat, marker='o', color='red', s=20)
#plt.show()
ids_not = []
ids_slp = []
for i in range(len(slp_dp)):
if slp_dp.MUNICIPIO[i] == 28.0 or slp_dp.MUNICIPIO[i] == 35.0:
ids_slp.append(i)
for i in range(len(slp_dp)):
if slp_dp.MUNICIPIO[i] != 28.0 and slp_dp.MUNICIPIO[i] != 35.0:
ids_not.append(i)
dp = slp_dp.drop(ids_not)
cds_data_risk = csv[['Riesgo','lat','long']]
#dat, ids = get_heat_data(slp_dp, cds_data_risk)
#Calculo de densidad
casos_densidad = []
"""
for i in range(len(dat)):
casos_densidad.append(dat[i]/slp_dp['densidad'].iloc[ids[i]]*100)
casos_densidad[i] = round(casos_densidad[i],3)
"""
for i in range(len(ids_slp)):
casos_densidad.append(slp_dp['densidad'].iloc[ids_slp[i]])
casos_densidad[i] = round(casos_densidad[i], 1)
print(len(ids_slp))
#print(len(casos_densidad))
fill_multiples_ids_tone(Lat, Long, d_pob, casos_densidad, ids_slp, 2, 'densidad_pob',ids_slp , x_lim, y_lim, figsize=(H, W))
plt.show()
|
{"/prueba.py": ["/mapGeoData.py"], "/Densidad/densidad_pob.py": ["/mapGeoData.py"]}
|
8,795
|
techonomics69/Chatbot-with-booking
|
refs/heads/master
|
/timeslots/app/demo/v1/api/dentist_timeslots_did.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function
from flask import request, g, Response
from . import Resource
from .. import schemas
from flask import jsonify
import json
class DentistTimeslotsDid(Resource):
def get(self, did):
token = request.args.get('token')
if (token != None):
with open('demo/data.json') as data_file:
data = json.load(data_file)
key = data.keys()
dflag = 0
availabletime = ""
for item in key:
if item == did:
dflag = 1
doctime = data[item]['availableTime']
for each in doctime:
availabletime += each + ", "
availabletime = availabletime[:-2]
if dflag == 1:
return jsonify("A list of available timeslot of " + did + ": " + availabletime)
else:
return jsonify("Please correct the doctor name.")
else:
return Response("Please login to get further information.", status=401)
|
{"/timeslots/app/demo/v1/routes.py": ["/timeslots/app/demo/v1/api/dentist_timeslots_did.py", "/timeslots/app/demo/v1/api/dentist_did_timeslot_tid_cancel.py"]}
|
8,796
|
techonomics69/Chatbot-with-booking
|
refs/heads/master
|
/timeslots/app/demo/v1/api/dentist_did_timeslot_tid_cancel.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function
from flask import request, g, Response
from . import Resource
from .. import schemas
from flask import jsonify
import json
class DentistDidTimeslotTidCancel(Resource):
def put(self, did, tid):
token = request.args.get('token')
if (token != None):
with open('demo/data.json') as data_file:
data = json.load(data_file)
file_out = open('demo/data.json', "w")
key = data.keys()
numberofavailable = 0
lenoftime = 0
tflag = 0
tflag1 = 0
dflag = 0
for item in key:
if item == did:
dflag = 1
docinfo = data[item]
time = docinfo["time"]
lenoftime = len(time)
for each in time:
if each == tid and time[each] == "reserved":
tflag = 1
time[each] = "not reserved"
break;
if each == tid and time[each] == "not reserved":
tflag1 = 2
for item in key:
if item == did:
time = docinfo["time"]
for each in time:
if time[each] == "not reserved":
numberofavailable += 1
if numberofavailable >= 1:
docinfo['status'] = "available"
file_out.write(json.dumps(data))
data_file.close()
file_out.close()
if tflag1 == 2 and dflag == 1:
return jsonify("The time " + tid + " you would like to cancel is available")
if tflag == 1 and dflag == 1:
return jsonify("You have successfully canceled " + tid + " with " + did)
if tflag == 0 and dflag == 1:
return jsonify("Please correct the " + tid + " you would like to cancel with "+ did)
if tflag == 0 or dflag == 0:
return jsonify("Please double check with the dentist and the timeslot")
else:
return Response("Please login to get further information.", status=401)
|
{"/timeslots/app/demo/v1/routes.py": ["/timeslots/app/demo/v1/api/dentist_timeslots_did.py", "/timeslots/app/demo/v1/api/dentist_did_timeslot_tid_cancel.py"]}
|
8,797
|
techonomics69/Chatbot-with-booking
|
refs/heads/master
|
/dentist/app/demo/v1/api/dentists.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function
from flask import request, g, Response
from . import Resource
from .. import schemas
from flask import jsonify
import requests
import json
class Dentists(Resource):
def get(self):
token = request.args.get('token')
if (token != None):
with open('demo/data.json') as data_file:
data = json.load(data_file)
file_out = open('demo/data.json', "w")
file_out.write(json.dumps(data))
data_file.close()
file_out.close()
result = ""
originaldata = data.keys()
for each in originaldata:
if each == "availableDentist":
for time in data[each]:
result += time + ", "
result = result[:-2]
return jsonify("The available dentists: " + result)
else:
return Response("Please login to get further information.", status=401)
|
{"/timeslots/app/demo/v1/routes.py": ["/timeslots/app/demo/v1/api/dentist_timeslots_did.py", "/timeslots/app/demo/v1/api/dentist_did_timeslot_tid_cancel.py"]}
|
8,798
|
techonomics69/Chatbot-with-booking
|
refs/heads/master
|
/dentist/app/demo/v1/api/dentist_info_did.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function
from flask import request, g, Response
from . import Resource
from .. import schemas
from flask import jsonify
import json
class DentistInfoDid(Resource):
def get(self, did):
token = request.args.get('token')
if (token != None):
with open('demo/data.json') as data_file:
data = json.load(data_file)
key = data.keys()
info = {}
flag = 0
for item in key:
if item == did:
flag = 1
docinfo = data[item]
info['name'] = item
info['location'] = docinfo['location']
info['specialization'] = docinfo['specialization']
if flag == 1:
return jsonify(info['name'] + " is located at " + info['location'] + " specializing in " + info['specialization'])
else:
return jsonify("The doctor you want to find does not exist")
else:
return Response("Please login to get further information.", status=401)
|
{"/timeslots/app/demo/v1/routes.py": ["/timeslots/app/demo/v1/api/dentist_timeslots_did.py", "/timeslots/app/demo/v1/api/dentist_did_timeslot_tid_cancel.py"]}
|
8,799
|
techonomics69/Chatbot-with-booking
|
refs/heads/master
|
/timeslots/app/demo/v1/routes.py
|
# -*- coding: utf-8 -*-
###
### DO NOT CHANGE THIS FILE
###
### The code is auto generated, your change will be overwritten by
### code generating.
###
from __future__ import absolute_import
from .api.dentist_timeslots_did import DentistTimeslotsDid
from .api.dentist_did_timeslot_tid_cancel import DentistDidTimeslotTidCancel
from .api.dentist_did_timeslot_tid_reserve import DentistDidTimeslotTidReserve
routes = [
dict(resource=DentistTimeslotsDid, urls=['/dentist/timeslots/<did>'], endpoint='dentist_timeslots_did'),
dict(resource=DentistDidTimeslotTidCancel, urls=['/dentist/<did>/timeslot/<tid>/cancel'], endpoint='dentist_did_timeslot_tid_cancel'),
dict(resource=DentistDidTimeslotTidReserve, urls=['/dentist/<did>/timeslot/<tid>/reserve'], endpoint='dentist_did_timeslot_tid_reserve'),
]
|
{"/timeslots/app/demo/v1/routes.py": ["/timeslots/app/demo/v1/api/dentist_timeslots_did.py", "/timeslots/app/demo/v1/api/dentist_did_timeslot_tid_cancel.py"]}
|
8,800
|
techonomics69/Chatbot-with-booking
|
refs/heads/master
|
/dialogflow/dialogflow.py
|
import os
import sys
import dialogflow_v2 as dialogflow
from uuid import uuid4
sys.path.append("..")
# from conf.Response import IntentResponse
import requests
import json
from flask import make_response, jsonify, request, Flask, url_for
import os
import re
from flask_cors import CORS
import jwt
import datetime
from functools import wraps
app = Flask(__name__)
CORS(app)
app.config['SECRET_KEY'] = 'thisismykey'
def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
token = request.json["token"]
if not token:
return jsonify("Please login first")
try:
data = jwt.decode(token, app.config['SECRET_KEY'])
except:
return jsonify("Please try to login again")
return f(*args, **kwargs)
return decorated
@app.route("/login", methods=['POST'])
def login():
user = request.json["user"]
password = request.json["password"]
if user and password and user == "1234" and password == {'words': [555953961, 2052564391, 1133070862, 1249910723], 'sigBytes': 16}:
token = jwt.encode({'user': user, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes = 30)}, app.config['SECRET_KEY'])
global_token = token
return jsonify({'token': token.decode('UTF-8')})
return jsonify("Please correct your username and password")
PATH = os.path.dirname(os.path.realpath(__file__))
DIALOGFLOW_PROJECT_ID = 'dentistappoinment'
GOOGLE_APPLICATION_CREDENTIALS = "DentistAppoinment-18719af8aa7b.json"
GOOGLE_APPLICATION_CREDENTIALS_PATH = os.path.join(PATH, GOOGLE_APPLICATION_CREDENTIALS)
class IntentResponse:
def __init__(self, intent, message):
self.intent = intent
self.message = message
class FallbackResponse:
def __init__(self, intent, message, confidence):
self.intent = intent
self.message = message
self.confidence = confidence
session_id=uuid4()
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = GOOGLE_APPLICATION_CREDENTIALS_PATH
project_id, session_id = DIALOGFLOW_PROJECT_ID, session_id
session_client = dialogflow.SessionsClient()
session = session_client.session_path(DIALOGFLOW_PROJECT_ID, session_id)
@app.route("/webhook", methods=['POST'])
@token_required
def detect_intent_texts(language_code='en'):
"""Returns the result of detect intent with texts as inputs.
Using the same `session_id` between requests allows continuation
of the conversation.
:param text: message
:type str
:param language_code: the language code of the language
:type: str
"""
token = request.json["token"]
if not request.json:
abort(400)
text = request.json["text"]
text_input = dialogflow.types.TextInput(text=text, language_code=language_code)
query_input = dialogflow.types.QueryInput(text=text_input)
response = session_client.detect_intent(session=session, query_input=query_input)
query = response.query_result.query_text
intent = response.query_result.intent.display_name
fullfillment = response.query_result.fulfillment_text
if (intent == 'Default Fallback Intent' or intent == ""):
return fullfillment
if (intent == 'How can I book an appoinment'):
return fullfillment
if (intent == 'How can I cancel an appoinment'):
return fullfillment
if (intent == 'Greeting' or intent == 'Default Welcome Intent'):
return fullfillment
if (fullfillment == 'Asking for all dentists'):
try:
send_token = {'token' : token}
url = requests.get("http://localhost:8000/v1/dentists", params=send_token)
available = url.json()
return available
except:
return jsonify("The dentist system is under maintenance")
if (intent == "Give the details of Mike" or intent == "Give the details of Jim" or intent == "Give the details of Tracey" or intent == "Give the details of Oliver" or intent == "Give the details of Jack" or intent == "Give the details of Harry" or intent == "Give the details of Oscar" or intent == "Give the details of James" or intent == "Give the details of William" or intent == "Give the details of Joe"):
if (fullfillment == 'Mike' or fullfillment == 'Jim' or fullfillment == 'Tracey' or fullfillment == 'Oliver' or fullfillment == 'Jack' or fullfillment == 'Harry' or fullfillment == 'Oscar' or fullfillment == 'James' or fullfillment == 'William' or fullfillment == 'Joe'):
try:
send_token = {'token' : token}
url = requests.get("http://localhost:8000/v1/dentist/info/"+ fullfillment, params=send_token)
available = url.json()
return jsonify(available)
except:
return jsonify("The dentist system is under maintenance")
if (intent == "Available time for Mike" or intent == "Available time for Jim" or intent == "Available time for Tracey" or intent == "Available time for Oliver" or intent == "Available time for Jack" or intent == "Available time for Harry" or intent == "Available time for Oscar" or intent == "Available time for James" or intent == "Available time for William" or intent == "Available time for Joe"):
if (fullfillment == 'Mike' or fullfillment == 'Jim' or fullfillment == 'Tracey' or fullfillment == 'Oliver' or fullfillment == 'Jack' or fullfillment == 'Harry' or fullfillment == 'Oscar' or fullfillment == 'James' or fullfillment == 'William' or fullfillment == 'Joe'):
try:
send_token = {'token' : token}
url = requests.get("http://localhost:4000/v1/dentist/timeslots/"+ fullfillment, params=send_token)
available = url.json()
return available
except:
return jsonify("The timeslot system is under maintenance")
if (intent == "Reserve time with Mike" or intent == "Reserve time with Jim" or intent == "Reserve time with Tracey" or intent == "Reserve time with Oliver" or intent == "Reserve time with Jack" or intent == "Reserve time with Harry" or intent == "Reserve time with Oscar" or intent == "Reserve time with James" or intent == "Reserve time with William" or intent == "Reserve time with Joe"):
if (fullfillment == 'Mike' or fullfillment == 'Jim' or fullfillment == 'Tracey' or fullfillment == 'Oliver' or fullfillment == 'Jack' or fullfillment == 'Harry' or fullfillment == 'Oscar' or fullfillment == 'James' or fullfillment == 'William' or fullfillment == 'Joe'):
time = query.split("#", 1)[0]
try:
send_token = {'token' : token}
url = requests.get("http://localhost:4000/v1/dentist/" + fullfillment +"/timeslot/" + time+ "/reserve", params=send_token)
available = url.json()
return available
except:
return jsonify("The timeslot system is under maintenance")
if (intent == "Cancel time with Mike" or intent == "Cancel time with Jim" or intent == "Cancel time with Tracey" or intent == "Cancel time with Oliver" or intent == "Cancel time with Jack" or intent == "Cancel time with Harry" or intent == "Cancel time with Oscar" or intent == "Cancel time with James" or intent == "Cancel time with William" or intent == "Cancel time with Joe"):
if (fullfillment == 'Mike' or fullfillment == 'Jim' or fullfillment == 'Tracey' or fullfillment == 'Oliver' or fullfillment == 'Jack' or fullfillment == 'Harry' or fullfillment == 'Oscar' or fullfillment == 'James' or fullfillment == 'William' or fullfillment == 'Joe'):
time = query.split("~", 1)[0]
try:
send_token = {'token' : token}
url = requests.put("http://localhost:4000/v1/dentist/" + fullfillment +"/timeslot/" + time+ "/cancel", params=send_token)
available = url.json()
return available
except:
return jsonify("The timeslot system is under maintenance")
if __name__ == '__main__':
app.run(host = '127.0.0.1', port = 2000)
|
{"/timeslots/app/demo/v1/routes.py": ["/timeslots/app/demo/v1/api/dentist_timeslots_did.py", "/timeslots/app/demo/v1/api/dentist_did_timeslot_tid_cancel.py"]}
|
8,803
|
aidarbek/database_systems_project
|
refs/heads/master
|
/benchmark.py
|
import user
import time
import neo
import tweet
sum_neo = 0.0
sum_sql = 0.0
start_id = 1
end_id = 1001
n = (end_id - start_id) * 1.0
for i in range(start_id, end_id):
handle = "a" + str(i)
# Benchmark SQL
start_sql = time.clock()
data = tweet.get(handle = handle, page="feed", limit = 10000)
sql_time = time.clock() - start_sql
# Benchmark Neo4j
start_neo = time.clock()
neo.get_feed(handle)
neo_time = time.clock() - start_neo
if i == start_id:
continue
sum_sql += sql_time
sum_neo += neo_time
print("SQL average feed time for 1000 records: " + str(sum_sql / n))
print("Neo4j average feed time for 1000 records: " + str(sum_neo / n))
|
{"/benchmark.py": ["/user.py", "/neo.py", "/tweet.py"], "/fill.py": ["/user.py", "/neo.py", "/tweet.py"], "/user.py": ["/config.py"], "/app.py": ["/notification.py", "/user.py", "/tweet.py"], "/notification.py": ["/config.py"]}
|
8,804
|
aidarbek/database_systems_project
|
refs/heads/master
|
/tweet.py
|
#!/usr/bin/python
import MySQLdb
import config
def isOwner(handle, tweet_id):
db = MySQLdb.connect(config.DB["host"], config.DB["user"], config.DB["password"], config.DB["db"])
cursor = db.cursor()
cursor.execute("SELECT Creator FROM tweet WHERE tweet_id={} AND Creator='{}'".format(tweet_id, handle))
result = cursor.fetchone()
db.close()
if result is None:
return False
return True
def add(handle, text, files):
db = MySQLdb.connect(config.DB["host"], config.DB["user"], config.DB["password"], config.DB["db"])
cursor = db.cursor()
try:
cursor.execute("INSERT INTO tweet(Creator, content) VALUES('{}', '{}')".format(handle, text))
tweet_id = cursor.lastrowid
db.commit()
except Exception as e:
print(str(e))
db.close()
return None
try:
if len(files) > 0:
for f in files:
cursor.execute("INSERT INTO attach_list(tweet, file) VALUES({}, {})".format(tweet_id, f))
db.commit()
except Exception as e:
print(str(e))
db.close()
return None
db.close()
return tweet_id
def likes(user, tweet):
db = MySQLdb.connect(config.DB["host"], config.DB["user"], config.DB["password"], config.DB["db"])
cursor = db.cursor()
try:
cursor.execute("INSERT INTO likes(handle, tweet_id) VALUES('{}', {})".format(user, tweet))
db.commit()
except:
db.close()
raise Exception("Couldn't insert")
db.close()
def delete(tweet):
db = MySQLdb.connect(config.DB["host"], config.DB["user"], config.DB["password"], config.DB["db"])
cursor = db.cursor()
try:
cursor.execute("DELETE FROM attach_list WHERE tweet = {}".format(tweet))
cursor.execute("DELETE FROM likes WHERE tweet_id = {}".format(tweet))
cursor.execute("DELETE FROM tweet WHERE tweet_id = {}".format(tweet))
db.commit()
except Exception as e:
print(str(e))
raise Exception("Couldn't delete")
db.close()
def unlikes(user, tweet):
db = MySQLdb.connect(config.DB["host"], config.DB["user"], config.DB["password"], config.DB["db"])
cursor = db.cursor()
try:
cursor.execute("DELETE FROM likes WHERE handle = '{}' AND tweet_id = {}".format(user, tweet))
db.commit()
except:
db.close()
raise Exception("Couldn't unlike")
db.close()
def get(handle, page="feed", limit = 10, last = None, current_user = None):
"""
handle - handle of the user. Depending on "page" parameter it can be:
1) Handle of user, whose feed we would like to get
2) Handle of user, whose tweets we would like to get
page - ("feed" or "user" or "search") - get user feed, user tweets or search respectively
limit - limit number of tweets
last - ID of the last tweet
"""
db = MySQLdb.connect(config.DB["host"], config.DB["user"], config.DB["password"], config.DB["db"])
cursor = db.cursor()
additional_condition = ""
if last is not None:
# Necessary to continue the tweet
additional_condition = "tweet.tweet_id < {} AND ".format(last)
if page == "feed":
# User news feed
cursor.execute("""SELECT tweet.tweet_id,content, Created, Creator,
COUNT(likes.handle) FROM tweet
LEFT JOIN likes ON likes.tweet_id = tweet.tweet_id
WHERE {} (
tweet.Creator IN
(SELECT to_user FROM follows WHERE from_user='{}')
OR
tweet.Creator = '{}'
)
GROUP BY tweet.tweet_id
ORDER BY tweet.tweet_id DESC LIMIT {}""".format(additional_condition, handle, handle, limit))
elif page == "user":
# Tweets of particular user only
cursor.execute("""SELECT tweet.tweet_id,content, Created, Creator,
COUNT(likes.handle) FROM tweet
LEFT JOIN likes ON likes.tweet_id = tweet.tweet_id
WHERE {} Creator = '{}'
GROUP BY tweet.tweet_id
ORDER BY tweet_id DESC LIMIT {}""".format(additional_condition, handle, limit))
elif page == "search":
# Tweets of particular user only
cursor.execute("""SELECT tweet.tweet_id,content, Created, Creator,
COUNT(likes.handle) FROM tweet
LEFT JOIN likes ON likes.tweet_id = tweet.tweet_id
WHERE {} content LIKE '%{}%'
GROUP BY tweet.tweet_id
ORDER BY tweet_id DESC LIMIT {}""".format(additional_condition, handle, limit))
results = cursor.fetchall()
data = []
for row in results:
row_data = {}
row_data["tweet_id"] = row[0]
row_data["content"] = row[1]
row_data["Created"] = row[2].strftime('%Y-%m-%d %H:%M:%S')
row_data["Creator"] = row[3]
row_data["likes"] = row[4]
cursor.execute("SELECT file.file_url, file.file_type FROM file INNER JOIN attach_list ON attach_list.file = file.file_id WHERE attach_list.tweet = {}".format(row_data["tweet_id"]))
files = cursor.fetchall()
row_data["files"] = [{"file_url": f[0], "file_type": f[1]} for f in files]
row_data["liked"] = False
if current_user is not None:
cursor.execute("SELECT * FROM likes WHERE tweet_id = {} AND handle = '{}' ".format(row_data["tweet_id"], current_user))
liked = cursor.fetchone()
if liked is not None:
row_data["liked"] = True
data.append(row_data)
db.close()
return data
def addFile(data):
db = MySQLdb.connect(config.DB["host"], config.DB["user"], config.DB["password"], config.DB["db"])
cursor = db.cursor()
try:
cursor.execute("INSERT INTO file(file_url, file_type) VALUES('{}', '{}')".format(data["file_url"], data["file_type"]))
db.commit()
cursor.execute("SELECT file_id FROM file ORDER BY file_id DESC LIMIT 1")
data["file_id"] = cursor.fetchone()[0]
except Exception as e:
raise e
db.close()
return data
if __name__ == '__main__':
#add("aidarbek1", "New tweet", [2,3])
delete(1139)
#print(get("hello", "search", 10))
pass
|
{"/benchmark.py": ["/user.py", "/neo.py", "/tweet.py"], "/fill.py": ["/user.py", "/neo.py", "/tweet.py"], "/user.py": ["/config.py"], "/app.py": ["/notification.py", "/user.py", "/tweet.py"], "/notification.py": ["/config.py"]}
|
8,805
|
aidarbek/database_systems_project
|
refs/heads/master
|
/fill.py
|
import user
import time
import neo
import tweet
sum_neo = 0.0
sum_sql = 0.0
start_id = 1
end_id = 1001
n = (end_id - start_id) * 1.0
for i in range(start_id, end_id):
handle = "a" + str(i)
# Benchmark SQL
start_sql = time.clock()
user.register(handle, handle, handle, handle, handle)
sql_time = time.clock() - start_sql
# Benchmark Neo4j
start_neo = time.clock()
neo.insert_user(handle)
neo_time = time.clock() - start_neo
if i == start_id:
continue
sum_sql += sql_time
sum_neo += neo_time
print("SQL average user adding time of 1000 records: " + str(sum_sql / n))
print("Neo4j average user adding time of 1000 records: " + str(sum_neo / n))
sum_neo = 0.0
sum_sql = 0.0
for i in range(start_id, end_id):
for j in range(start_id, end_id):
if i == j:
continue
handle1 = "a" + str(i)
handle2 = "a" + str(j)
# Benchmark SQL
start_sql = time.clock()
user.follow(handle1, handle2)
sql_time = time.clock() - start_sql
# Benchmark Neo4j
start_neo = time.clock()
neo.insert_relation(handle1, handle2)
neo_time = time.clock() - start_neo
if i == start_id and j == start_id:
continue
sum_sql += sql_time
sum_neo += neo_time
print("SQL average relationship adding time of 1000 records: " + str(sum_sql / n))
print("Neo4j average relationship adding time of 1000 records: " + str(sum_neo / n))
sum_neo = 0.0
sum_sql = 0.0
for i in range(start_id, end_id):
handle = "a" + str(i)
text = "What a good day!"
tweet_id = i
# Benchmark SQL
start_sql = time.clock()
tweet.add(handle, text, "")
sql_time = time.clock() - start_sql
# Benchmark Neo4j
start_neo = time.clock()
neo.add_tweet(handle, text, tweet_id)
neo_time = time.clock() - start_neo
if i == start_id:
continue
sum_sql += sql_time
sum_neo += neo_time
print("SQL average tweet adding time of 1000 records: " + str(sum_sql / n))
print("Neo4j average tweet adding time of 1000 records: " + str(sum_neo / n))
|
{"/benchmark.py": ["/user.py", "/neo.py", "/tweet.py"], "/fill.py": ["/user.py", "/neo.py", "/tweet.py"], "/user.py": ["/config.py"], "/app.py": ["/notification.py", "/user.py", "/tweet.py"], "/notification.py": ["/config.py"]}
|
8,806
|
aidarbek/database_systems_project
|
refs/heads/master
|
/config.py
|
DB = {
"host": "localhost",
"user": "root",
"password": "",
"db": "db_course"
}
|
{"/benchmark.py": ["/user.py", "/neo.py", "/tweet.py"], "/fill.py": ["/user.py", "/neo.py", "/tweet.py"], "/user.py": ["/config.py"], "/app.py": ["/notification.py", "/user.py", "/tweet.py"], "/notification.py": ["/config.py"]}
|
8,807
|
aidarbek/database_systems_project
|
refs/heads/master
|
/user.py
|
#!/usr/bin/python
import MySQLdb
import config
class User:
def __init__(self, login = None, password = None):
"""
Class constructor can become also authorization function
"""
self.handle = None
self.auth = False
if login != None:
if self.__exists(login):
self.handle = login
else:
self.handle = None
if password != None:
if self.__login(password):
self.auth = True
else:
self.auth = False
def isAuth(self):
return self.auth
def setAuth(self):
self.auth = True
def getHandle(self):
return self.handle
def getInfo(self):
db = MySQLdb.connect(config.DB["host"], config.DB["user"], config.DB["password"], config.DB["db"])
cursor = db.cursor()
cursor.execute("SELECT handle, full_name, email, phone_number, photo_url FROM user WHERE handle='{}'".format(self.handle))
data = {}
data["handle"], data["full_name"], data["email"], data["phone"], data["photo_url"] = cursor.fetchone()
cursor.execute("SELECT COUNT(*) FROM follows WHERE from_user='{}'".format(self.handle))
data["following"] = cursor.fetchone()[0]
cursor.execute("SELECT COUNT(*) FROM follows WHERE to_user='{}'".format(self.handle))
data["followers"] = cursor.fetchone()[0]
db.close()
return data
def followedBy(self, handle):
if handle is None:
return False
db = MySQLdb.connect(config.DB["host"], config.DB["user"], config.DB["password"], config.DB["db"])
cursor = db.cursor()
cursor.execute("SELECT from_user FROM follows WHERE from_user='{}' AND to_user='{}'".format(handle, self.handle))
follows = cursor.fetchone()
db.close()
if follows is not None:
return True
return False
def update(self, columns, values):
set_string = ""
if len(columns) != len(values):
raise Exception("Columns do not match values!")
set_string = ",".join([columns[i] + "='" + values[i]+"'" for i in range(len(columns))])
db = MySQLdb.connect(config.DB["host"], config.DB["user"], config.DB["password"], config.DB["db"])
cursor = db.cursor()
cursor.execute("UPDATE user SET {} WHERE handle = '{}'".format(set_string, self.handle))
db.commit()
db.close()
def __exists(self, handle):
db = MySQLdb.connect(config.DB["host"], config.DB["user"], config.DB["password"], config.DB["db"])
cursor = db.cursor()
cursor.execute("SELECT handle FROM user WHERE handle='{}'".format(handle))
handle = cursor.fetchone()
db.close()
if handle is None:
return False
return True
def register(self, handle, email, full_name, phone, password):
db = MySQLdb.connect(config.DB["host"], config.DB["user"], config.DB["password"], config.DB["db"])
cursor = db.cursor()
try:
cursor.execute("INSERT INTO user(handle, email, full_name, phone_number, password) VALUES('{}', '{}', '{}', '{}', '{}')".format(handle, email, full_name, phone, password))
db.commit()
except:
db.close()
raise Exception("Couldn't create user")
db.close()
def __login(self, password):
db = MySQLdb.connect(config.DB["host"], config.DB["user"], config.DB["password"], config.DB["db"])
cursor = db.cursor()
cursor.execute("SELECT handle FROM user WHERE handle='{}' AND password='{}'".format(self.handle, password))
handle = cursor.fetchone()
db.close()
if handle is None:
return False
return True
def follow(self, to_user):
db = MySQLdb.connect(config.DB["host"], config.DB["user"], config.DB["password"], config.DB["db"])
cursor = db.cursor()
try:
if self.isAuth():
cursor.execute("INSERT INTO follows(from_user, to_user) VALUES('{}', '{}')".format(self.handle, to_user))
cursor.execute("INSERT INTO notification(content, url, handle) VALUES('@{} user followed you', '/{}', '{}')".format(self.handle, self.handle, to_user))
db.commit()
else:
raise Exception("")
except:
db.close()
raise Exception("Couldn't insert")
db.close()
def unfollow(self, to_user):
db = MySQLdb.connect(config.DB["host"], config.DB["user"], config.DB["password"], config.DB["db"])
cursor = db.cursor()
try:
if self.isAuth():
cursor.execute("DELETE FROM follows WHERE from_user = '{}' AND to_user = '{}'".format(self.handle, to_user))
db.commit()
else:
raise Exception("")
except:
db.close()
raise Exception("Couldn't unfollow")
db.close()
if __name__ == '__main__':
user = User("aidarbek1", "qwerty")
user.update(["full_name"], ["Aidarbek Suleimenov"])
pass
|
{"/benchmark.py": ["/user.py", "/neo.py", "/tweet.py"], "/fill.py": ["/user.py", "/neo.py", "/tweet.py"], "/user.py": ["/config.py"], "/app.py": ["/notification.py", "/user.py", "/tweet.py"], "/notification.py": ["/config.py"]}
|
8,808
|
aidarbek/database_systems_project
|
refs/heads/master
|
/neo.py
|
"""
MATCH (a:User),(b:User)
WHERE a.handle = 'a1' AND b.handle = 'a2'
CREATE (a)-[r:FOLLOWS]->(b)
RETURN r
"""
query = """
MATCH (person {name: "Keanu Reeves"})-[:ACTED_IN]->(movie)<-[:ACTED_IN]-(guy)
RETURN person.name, guy.name, movie.title;
"""
from neo4j.v1 import GraphDatabase, basic_auth
driver = GraphDatabase.driver("bolt://localhost:7687", auth=basic_auth("neo4j", "neo4j"))
def insert_user(handle):
session = driver.session()
query = "CREATE (n:User {handle: \""+ handle + "\", email: \""+ handle + "\",full_name: \""+ handle + "\",phone: \""+ handle + "\",password: \""+ handle + "\"})"
result = session.run(query)
session.close()
def insert_relation(handle1, handle2):
session = driver.session()
query = """
MATCH (a:User),(b:User)
WHERE a.handle = '"""+handle1+"""' AND b.handle = '"""+handle2+"""'
CREATE (a)-[r:FOLLOWS]->(b)
RETURN r
"""
result = session.run(query)
session.close()
def add_tweet(handle, tweet, tweet_id):
session = driver.session()
query = "CREATE (n:Tweet {tweet_id: \""+str(tweet_id)+"\", text: \""+ tweet + "\"})"
result = session.run(query)
query = """
MATCH (a:User),(b:Tweet)
WHERE a.handle = '"""+handle+"""' AND b.tweet_id = '"""+str(tweet_id)+"""'
CREATE (a)-[r:TWEETS]->(b)
RETURN r
"""
result = session.run(query)
session.close()
def get_feed(handle):
session = driver.session()
query = """
MATCH (person {handle: \"""" +handle+ """\"})-[:FOLLOWS]->(guy)-[:TWEETS]->(tweet)
RETURN tweet;
"""
result = session.run(query)
session.close()
|
{"/benchmark.py": ["/user.py", "/neo.py", "/tweet.py"], "/fill.py": ["/user.py", "/neo.py", "/tweet.py"], "/user.py": ["/config.py"], "/app.py": ["/notification.py", "/user.py", "/tweet.py"], "/notification.py": ["/config.py"]}
|
8,809
|
aidarbek/database_systems_project
|
refs/heads/master
|
/app.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from flask import Flask, Response
from flask import request
from flask import abort, redirect, url_for
from flask import render_template
import os
import json
from flask import jsonify, send_from_directory
from flask.ext.cors import CORS, cross_origin
import notification
from werkzeug.routing import BaseConverter
from user import User
import tweet
from werkzeug.utils import secure_filename
UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
app = Flask(__name__, static_url_path='/uploads')
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
class RegexConverter(BaseConverter):
def __init__(self, url_map, *items):
super(RegexConverter, self).__init__(url_map)
self.regex = items[0]
app.url_map.converters['regex'] = RegexConverter
app.secret_key = "Key"
app.debug = True
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/uploads/<path>')
def send_img(path):
return send_from_directory(app.config['UPLOAD_FOLDER'],
path)
@app.route('/uploads/open-iconic/font/css/<path>')
def send_css(path):
return send_from_directory(app.config['UPLOAD_FOLDER'] + "/open-iconic/font/css",
path)
@app.route('/uploads/open-iconic/font/fonts/<path>')
def send_fonts(path):
return send_from_directory(app.config['UPLOAD_FOLDER'] + "/open-iconic/font/fonts",
path)
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return "Nothing"
file = request.files['file']
# if user does not select file, browser also
# submit a empty part without filename
if file.filename == '':
flash('No selected file')
return "No filename"
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
data = {}
data["file_url"] = "/uploads/" + filename
data["file_type"] = file.filename.rsplit('.', 1)[1].lower()
data = tweet.addFile(data)
p = json.dumps(data)
resp = Response(response=p,
status=200,
mimetype="text/plain")
return resp
return '''
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
'''
@app.route("/", methods=['GET'])
def index():
handle = request.cookies.get('handle')
if handle is not None:
user = User(handle)
user.setAuth()
user_data = user.getInfo()
return render_template("feed.html", handle = handle, full_name = user_data["full_name"], email = user_data["email"])
return render_template("index.html")
@app.route("/search", methods=['GET'])
def search_controller():
handle = request.cookies.get('handle')
search = request.args.get('q')
if handle is not None:
user = User(handle)
user.setAuth()
user_data = user.getInfo()
return render_template("search.html", handle = handle, full_name = user_data["full_name"], email = user_data["email"], search = search)
return render_template("index.html")
@app.route("/", methods=['POST'])
def register():
handle = str(request.form["handle"].encode('utf-8'))
email = str(request.form["email"].encode('utf-8'))
full_name = str(request.form["full_name"].encode('utf-8'))
phone = str(request.form["phone"].encode('utf-8'))
password = str(request.form["password"].encode('utf-8'))
data = {"success": "User have been registered"}
user = User()
try:
user.register(handle, email, full_name, phone, password)
except:
data = {"error": "Couldn't register user! Check handle or email"}
p = json.dumps(data)
resp = Response(response=p,
status=200,
mimetype="text/plain")
return resp
@app.route("/login", methods=['POST'])
def login():
tmp_handle = request.cookies.get('handle')
handle = request.form["handle"]
password = request.form["password"]
data = {"success": "You logged in"}
user = User(handle, password)
if not user.isAuth():
handle = None
data = {"error": "Couldn't log in user!"}
else:
data = {"success": "You logged in!"}
p = json.dumps(data)
resp = Response(response=p,
status=200,
mimetype="text/plain")
if handle is not None:
resp.set_cookie("handle", handle)
return resp
@app.route("/tweet", methods=['POST'])
def add_tweet():
handle = request.cookies.get('handle')
data = {}
if handle is not None:
text = request.form["text"]
files = request.form["files"] # Comma separated list of file_id
if files == "":
files = []
else:
files = files.split(",")
tweet_id = tweet.add(handle, text, files)
if tweet_id is None:
data["error"] = "Error occured while adding the tweet"
else:
data["success"] = "Tweet added"
p = json.dumps(data)
resp = Response(response=p,
status=200,
mimetype="text/plain")
if handle is not None:
resp.set_cookie("handle", handle)
return resp
@app.route("/follow", methods=['POST'])
def follow():
from_handle = request.cookies.get('handle')
to_handle = request.form["handle"]
data = {"error": "You must log in!"}
if from_handle is not None:
user = User(from_handle)
user.setAuth()
try:
data = {"success": "You followed the user!"}
user.follow(to_handle)
except:
try:
user.unfollow(to_handle)
data = {"success": "You unfollowed the user!"}
except:
data = {"error": "Couldn't follow the user"}
p = json.dumps(data)
resp = Response(response=p,
status=200,
mimetype="text/plain")
return resp
@app.route("/notification/count", methods=['GET'])
def notification_count():
handle = request.cookies.get('handle')
data = {"count": 0}
print(handle)
if handle is not None:
try:
data["count"] = notification.count(handle)
except Exception as e:
print(str(e))
data["count"] = 0
p = json.dumps(data)
resp = Response(response=p,
status=200,
mimetype="text/plain")
return resp
@app.route("/notification", methods=['GET'])
def notification_page():
handle = request.cookies.get('handle')
data = {"notifications": []}
if handle is not None:
try:
data["notifications"] = notification.get(handle)
except:
data["notifications"] = []
user = User(handle)
user.setAuth()
user_data = user.getInfo()
return render_template("notification.html", handle = handle, full_name = user_data["full_name"], email = user_data["email"],
notifications = data["notifications"])
else:
return render_template("index.html")
@app.route("/notification", methods=['POST'])
def notification_get():
handle = request.cookies.get('handle')
data = {"notifications": []}
if handle is not None:
try:
data["notifications"] = notification.get(handle)
except:
data["notifications"] = []
p = json.dumps(data)
resp = Response(response=p,
status=200,
mimetype="text/plain")
return resp
@app.route("/like", methods=['POST'])
def like():
handle = request.cookies.get('handle')
tweet_id = request.form["tweet_id"]
data = {"success": "You liked tweet!"}
if handle is not None:
try:
tweet.likes(handle, tweet_id)
except:
try:
tweet.unlikes(handle, tweet_id)
data = {"success": "You unliked the tweet!"}
except:
data = {"error": "Couldn't unlike the tweet"}
p = json.dumps(data)
resp = Response(response=p,
status=200,
mimetype="text/plain")
return resp
@app.route("/tweet/delete", methods=['POST'])
def tweet_delete():
handle = request.cookies.get('handle')
tweet_id = request.form["tweet_id"]
data = {"success": "You delete tweet!"}
if handle is not None:
try:
if tweet.isOwner(handle, tweet_id):
tweet.delete(tweet_id)
except Exception as e:
print(str(e))
data = {"error": "Couldn't unlike the tweet"}
p = json.dumps(data)
resp = Response(response=p,
status=200,
mimetype="text/plain")
return resp
@app.route("/tweet/feed", methods=['GET'])
def feed():
handle = request.cookies.get('handle')
last = request.args.get('last')
data = {}
if handle is not None:
data = tweet.get(handle, "feed", 10, last, handle)
p = json.dumps(data)
resp = Response(response=p,
status=200,
mimetype="text/plain")
return resp
@app.route("/tweet/search", methods=['GET'])
def search():
handle = request.cookies.get('handle')
last = request.args.get('last')
search = request.args.get('q')
print(handle)
print(search)
data = {}
if handle is not None:
data = tweet.get(search, "search", 10, last, handle)
p = json.dumps(data)
resp = Response(response=p,
status=200,
mimetype="text/plain")
return resp
@app.route("/logout", methods=['GET'])
def logout():
handle = request.cookies.get('handle')
p = ""
if handle is not None:
p = "You logged out"
headers = {
'Location': '/'
}
resp = redirect(url_for("index"))
if handle is not None:
resp.set_cookie("handle", '', expires=0)
return resp
return redirect(url_for("index"))
@app.route('/user/<handle>', methods=['GET'])
def profile(handle):
user = User(handle)
data = {}
current_user = request.cookies.get('handle')
last = request.args.get('last')
if user.getHandle() is not None:
data = tweet.get(handle, "user", 10, last, current_user)
p = json.dumps(data)
resp = Response(response=p,
status=200,
mimetype="text/plain")
else:
resp = Response(response="User not found",
status=404,
mimetype="text/plain")
return resp
@app.route('/settings', methods=['GET', 'POST'])
def settings():
current_user = request.cookies.get('handle')
if current_user is not None:
authorised = True
else:
authorised = False
return redirect(url_for("index"))
user = User(current_user)
if request.method == 'POST':
email = str(request.form["email"].encode('utf-8'))
full_name = str(request.form["full_name"].encode('utf-8'))
phone = str(request.form["phone"].encode('utf-8'))
photo_url = str(request.form["photo_url"].encode('utf-8'))
user.update(["email", "full_name", "phone_number", "photo_url"],
[email, full_name, phone, photo_url])
data = user.getInfo()
if user.getHandle() is not None:
if data["photo_url"] == "":
data["photo_url"] = "http://via.placeholder.com/200x150"
resp = render_template("settings.html", data = data, handle = current_user)
else:
resp = Response(response="User not found",
status=404,
mimetype="text/plain")
return resp
@app.route('/<handle>', methods=['GET'])
def profile_page(handle):
user = User(handle)
data = {}
current_user = request.cookies.get('handle')
if current_user is not None:
authorised = True
else:
authorised = False
if user.getHandle() is not None:
data = user.getInfo()
if data["photo_url"] == "":
data["photo_url"] = "http://via.placeholder.com/200x150"
resp = render_template("user.html", handle=data["handle"], full_name=data["full_name"],
followers = data["followers"], following = data["following"], photo_url = data["photo_url"], current_user = current_user,
authorised = authorised, followed = user.followedBy(current_user), current_user_page = current_user == data["handle"])
else:
resp = Response(response="User not found",
status=404,
mimetype="text/plain")
return resp
if __name__ == "__main__":
app.run(threaded=True)
|
{"/benchmark.py": ["/user.py", "/neo.py", "/tweet.py"], "/fill.py": ["/user.py", "/neo.py", "/tweet.py"], "/user.py": ["/config.py"], "/app.py": ["/notification.py", "/user.py", "/tweet.py"], "/notification.py": ["/config.py"]}
|
8,810
|
aidarbek/database_systems_project
|
refs/heads/master
|
/notification.py
|
#!/usr/bin/python
import MySQLdb
import config
def get(handle):
db = MySQLdb.connect(config.DB["host"], config.DB["user"], config.DB["password"], config.DB["db"])
cursor = db.cursor()
cursor.execute("SELECT `id`, `content`, `url` FROM `notification` WHERE `handle`='{}' AND `read` = 0 LIMIT 10".format(handle))
result = cursor.fetchall()
data = []
notifications = []
for row in result:
row_data = {}
row_data["content"] = row[1]
row_data["url"] = row[2]
data.append(row_data)
notifications.append(str(row[0]))
if len(notifications) > 0:
cursor.execute("UPDATE `notification` SET `read` = 1 WHERE `id` IN({})".format(",".join(notifications)))
db.commit()
db.close()
return data
def count(handle):
db = MySQLdb.connect(config.DB["host"], config.DB["user"], config.DB["password"], config.DB["db"])
cursor = db.cursor()
cursor.execute("SELECT COUNT(`id`) FROM `notification` WHERE `handle`='{}' AND `read` = 0 ".format(handle))
result = cursor.fetchone()[0]
db.close()
return result
if __name__ == '__main__':
print(count("aidarbek1"))
pass
|
{"/benchmark.py": ["/user.py", "/neo.py", "/tweet.py"], "/fill.py": ["/user.py", "/neo.py", "/tweet.py"], "/user.py": ["/config.py"], "/app.py": ["/notification.py", "/user.py", "/tweet.py"], "/notification.py": ["/config.py"]}
|
8,817
|
slavkoBV/Startups_scrapy
|
refs/heads/master
|
/startapps/items.py
|
import scrapy
class StartupItem(scrapy.Item):
company_name = scrapy.Field()
request_url = scrapy.Field()
request_company_url = scrapy.Field()
location = scrapy.Field()
tags = scrapy.Field()
founding_date = scrapy.Field()
founders = scrapy.Field()
employee_range = scrapy.Field()
urls = scrapy.Field()
emails = scrapy.Field()
phones = scrapy.Field()
description_short = scrapy.Field()
description = scrapy.Field()
|
{"/startapps/spiders/startup_spider.py": ["/startapps/items.py"]}
|
8,818
|
slavkoBV/Startups_scrapy
|
refs/heads/master
|
/startapps/pipelines.py
|
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
class StartappsPipeline(object):
def process_item(self, item, spider):
for key in item.keys():
if key == 'description':
if item[key]:
item[key] = item[key].strip()
else:
if not item[key]:
item[key] = ''
return item
|
{"/startapps/spiders/startup_spider.py": ["/startapps/items.py"]}
|
8,819
|
slavkoBV/Startups_scrapy
|
refs/heads/master
|
/startapps/spiders/startup_spider.py
|
import scrapy
import json
from scrapy import Selector
from ..items import StartupItem
class StartupSpider(scrapy.Spider):
name = 'startup'
allowed_domains = ['e27.co']
count = 0
COUNT_MAX = 500
def start_requests(self):
url = 'https://e27.co/startups'
for page in range(1, 33):
url += '/load_startups_ajax?all&per_page={}&append=1&_=2018-08-29_13:37:36_03' \
''.format(page)
yield scrapy.Request(url, callback=self.page_parse)
def page_parse(self, response):
data = json.loads(response.body)
content = data['pagecontent'].strip()
startups = Selector(text=content).xpath('//div[@class="startup-block"]')
for startup in startups:
if self.count < self.COUNT_MAX:
url = startup.xpath('.//a[1]/@href').extract_first() + '?json'
self.count += 1
yield scrapy.Request(url, callback=self.parse_item)
def parse_item(self, response):
item = StartupItem()
content = response.body.strip()
header = Selector(text=content).xpath('//div[@class="page-head"]')
profile_content = Selector(text=content).xpath('//div[@class="profile-content"]')
item['company_name'] = header.xpath('.//h1[@class="profile-startup"]/text()').extract_first()
item['request_url'] = response.url.replace('?json', '')
item['request_company_url'] = header.xpath('.//a[1]/@href').extract_first()
item['location'] = header.xpath('.//div[@class="mbt"]/span[3]/a/text()').extract_first()
item['tags'] = header.xpath('.//div[contains(@style, "word-wrap")]/span/a/text()').extract()
item['founding_date'] = header.xpath('.//p[contains(text(), "Founded:")]/span/text()').extract_first()
item['urls'] = header.xpath('.//div[contains(@class, "socials")]/a/@href').extract()
item['description_short'] = header.xpath('.//div[h1[@class="profile-startup"]]/div[1]/text()').extract_first()
item['founders'] = profile_content.xpath('.//span[contains(text(), "ounder")]/'
'preceding-sibling::span/a/text()').extract()
item['description'] = profile_content.xpath('.//p[@class="profile-desc-text"]/text()').extract_first()
item['employee_range'] = ''
item['emails'] = ''
item['phones'] = ''
yield item
|
{"/startapps/spiders/startup_spider.py": ["/startapps/items.py"]}
|
8,820
|
ottonemo/pytorch-sru
|
refs/heads/master
|
/test.py
|
import torch
import numpy as np
from torch.autograd import Variable
from torch.nn.utils import rnn
from torchsru import SRU
def test():
batch_first = False
sru = SRU(4, 4,
batch_first=batch_first,
bidirectional=True,
use_sigmoid=False).cuda()
sru.reset_parameters()
x = Variable(torch.randn(3, 2, 4)).cuda()
lens = [3, 3]
h1, c1 = sru(x)
pack = rnn.pack_padded_sequence(x, lens, batch_first=batch_first)
h2, c2 = sru(pack)
h2, _ = rnn.pad_packed_sequence(h2, batch_first=batch_first)
x = torch.cat([x, Variable(x.data.new(1, 2, 4).zero_())])
pack = rnn.pack_padded_sequence(x, lens, batch_first=batch_first)
h3, c3 = sru(pack)
h3, _ = rnn.pad_packed_sequence(h3, batch_first=batch_first)
h3.mean().backward()
h_eq = (h1 == h2) == (h1 == h3)
c_eq = (c1 == c2) == (c1 == c3)
assert h_eq.sum().data[0] == np.prod(h_eq.size()) and \
c_eq.sum().data[0] == np.prod(c_eq.size())
|
{"/src/torchsru/__init__.py": ["/src/torchsru/model.py"]}
|
8,821
|
ottonemo/pytorch-sru
|
refs/heads/master
|
/src/torchsru/model.py
|
# Code copied and slightly modified from https://github.com/taolei87/sru
import pkg_resources
from collections import namedtuple
import torch
import torch.nn as nn
from torch.autograd import Function
from torch.autograd import Variable
import torch.nn.utils.rnn as R
from cupy.cuda import function
from pynvrtc.compiler import Program
class SRU_Compute(Function):
SRU_CUDA_INITIALIZED = False
SRU_FWD_FUNC = None
SRU_BWD_FUNC = None
SRU_BiFWD_FUNC = None
SRU_BiBWD_FUNC = None
SRU_STREAM = {}
def __init__(self, use_tanh, d_out, bidirectional=False, use_sigmoid=True):
global SRU_CUDA_INITIALIZED
super(SRU_Compute, self).__init__()
self.use_tanh = use_tanh
self.d_out = d_out
self.bidirectional = bidirectional
self.use_sigmoid = use_sigmoid
if not self.SRU_CUDA_INITIALIZED:
self.initialize()
@classmethod
def initialize(cls):
code = pkg_resources.resource_string(__name__, 'sru.cu').decode(
"utf-8")
prog = Program(code.encode('utf-8'),
'sru_prog.cu'.encode('utf-8'))
ptx = prog.compile()
mod = function.Module()
mod.load(bytes(ptx.encode()))
cls.SRU_FWD_FUNC = mod.get_function('sru_fwd')
cls.SRU_BWD_FUNC = mod.get_function('sru_bwd')
cls.SRU_BiFWD_FUNC = mod.get_function('sru_bi_fwd')
cls.SRU_BiBWD_FUNC = mod.get_function('sru_bi_bwd')
cls.SRU_CUDA_INITIALIZED = True
def get_stream(self):
device_id = self.
if device_id not in cls.SRU_STREAM:
Stream = namedtuple('Stream', ['ptr'])
stream = Stream(ptr=torch.cuda.c.cuda_stream)
cls.SRU_STREAM[device_id] = stream
return cls.SRU_STREAM.get(device_id)
def forward(self, u, x, bias, lens, init=None, mask_h=None):
bidir = 2 if self.bidirectional else 1
max_length = x.size(0) if x.dim() == 3 else 1
batch = x.size(-2)
d = self.d_out
k = u.size(-1) // d
k_ = k // 2 if self.bidirectional else k
ncols = batch * d * bidir
thread_per_block = min(512, ncols)
num_block = (ncols - 1) // thread_per_block + 1
init_ = x.new(ncols).zero_() if init is None else init
size = (max_length, batch, d * bidir) \
if x.dim() == 3 else (batch, d * bidir)
c = x.new(*size)
h = x.new(*size)
FUNC = self.SRU_FWD_FUNC if not self.bidirectional else self.SRU_BiFWD_FUNC
stream = self.get_stream()
FUNC(args=[
u.contiguous().data_ptr(),
x.contiguous().data_ptr() if k_ == 3 else 0,
bias.data_ptr(),
init_.contiguous().data_ptr(),
mask_h.data_ptr() if mask_h is not None else 0,
lens.data_ptr(),
batch,
max_length,
d,
k_,
h.data_ptr(),
c.data_ptr(),
self.use_tanh,
self.use_sigmoid],
block=(thread_per_block, 1, 1),
grid=(num_block, 1, 1),
stream=stream
)
self.save_for_backward(u, x, bias, init, mask_h)
self.intermediate = c
self.lens = lens
if x.dim() == 2:
last_cell = c
elif self.bidirectional:
d_size = (max_length, batch, d)
index_l = (lens - 1).unsqueeze(0).unsqueeze(-1).expand(*d_size)
index_r = lens.new(*d_size).zero_()
index = torch.cat([index_l, index_r], 2)
last_cell = torch.gather(c, 0, index.long())[0]
else:
index = (lens - 1).unsqueeze(0).unsqueeze(-1).expand_as(c)
last_cell = torch.gather(c, 0, index.long())[0]
return h, last_cell
def backward(self, grad_h, grad_last):
lens = self.lens
bidir = 2 if self.bidirectional else 1
u, x, bias, init, mask_h = self.saved_tensors
c = self.intermediate
max_length = x.size(0) if x.dim() == 3 else 1
batch = x.size(-2)
d = self.d_out
k = u.size(-1) // d
k_ = k // 2 if self.bidirectional else k
ncols = batch * d * bidir
thread_per_block = min(512, ncols)
num_block = (ncols - 1) // thread_per_block + 1
init_ = x.new(ncols).zero_() if init is None else init
grad_u = u.new(*u.size())
grad_bias = x.new(2, batch, d * bidir)
grad_init = x.new(batch, d * bidir)
# For DEBUG
# size = (length, batch, x.size(-1)) if x.dim() == 3 else (batch, x.size(-1))
# grad_x = x.new(*x.size()) if k_ == 3 else x.new(*size).zero_()
# Normal use
grad_x = x.new(*x.size()) if k_ == 3 else None
FUNC = self.SRU_BWD_FUNC if not self.bidirectional else self.SRU_BiBWD_FUNC
stream = self.get_stream()
FUNC(args=[
u.contiguous().data_ptr(),
x.contiguous().data_ptr() if k_ == 3 else 0,
bias.data_ptr(),
init_.contiguous().data_ptr(),
mask_h.data_ptr() if mask_h is not None else 0,
c.data_ptr(),
grad_h.contiguous().data_ptr(),
grad_last.contiguous().data_ptr(),
lens.data_ptr(),
batch,
max_length,
d,
k_,
grad_u.data_ptr(),
grad_x.data_ptr() if k_ == 3 else 0,
grad_bias.data_ptr(),
grad_init.data_ptr(),
self.use_tanh,
self.use_sigmoid],
block=(thread_per_block, 1, 1),
grid=(num_block, 1, 1),
stream=stream
)
return grad_u, grad_x, grad_bias.sum(1).view(-1), grad_init, None
class SRUCell(nn.Module):
def __init__(self, n_in, n_out, dropout=0, rnn_dropout=0, use_sigmoid=1,
use_tanh=1, bidirectional=False):
super(SRUCell, self).__init__()
self.n_in = n_in
self.n_out = n_out
self.rnn_dropout = rnn_dropout
self.dropout = dropout
self.bidirectional = bidirectional
self.use_tanh = use_tanh
self.use_sigmoid = use_sigmoid
out_size = n_out * 2 if bidirectional else n_out
k = 4 if n_in != out_size else 3
self.size_per_dir = n_out * k
self.weight = nn.Parameter(torch.Tensor(
n_in,
self.size_per_dir * 2 if bidirectional else self.size_per_dir
))
self.bias = nn.Parameter(torch.Tensor(
n_out * 4 if bidirectional else n_out * 2
))
self.reset_parameters()
def reset_parameters(self):
val_range = (3.0 / self.n_in) ** 0.5
self.weight.data.uniform_(-val_range, val_range)
self.bias.data.zero_()
def init_weight(self):
return self.reset_parameters()
def set_bias(self, bias_val=0):
n_out = self.n_out
if self.bidirectional:
self.bias.data[n_out * 2:].zero_().add_(bias_val)
else:
self.bias.data[n_out:].zero_().add_(bias_val)
def forward(self, input, c0=None, lens=None):
assert input.dim() == 2 or input.dim() == 3
if input.dim() == 1:
max_len = 1
else:
max_len = input.size(0)
n_in, n_out = self.n_in, self.n_out
batch = input.size(-2)
if c0 is None:
c0 = Variable(input.data.new(
batch, n_out if not self.bidirectional else n_out * 2
).zero_())
if self.training and (self.rnn_dropout > 0):
mask = self.get_dropout_mask_((batch, n_in), self.rnn_dropout)
x = input * mask.expand_as(input)
else:
x = input
x_2d = x if x.dim() == 2 else x.contiguous().view(-1, n_in)
u = x_2d.mm(self.weight)
if lens is None:
lens = Variable(x.data.new(batch).int().fill_(max_len))
computer = SRU_Compute(self.use_tanh, n_out, self.bidirectional,
use_sigmoid=self.use_sigmoid)
if self.training and (self.dropout > 0):
bidir = 2 if self.bidirectional else 1
mask_h = self.get_dropout_mask_((batch, n_out * bidir),
self.dropout)
h, c = computer(u, input, self.bias, lens, c0, mask_h)
else:
h, c = computer(u, input, self.bias, lens, c0)
return h, c
def get_dropout_mask_(self, size, p):
w = self.weight.data
return Variable(w.new(*size).bernoulli_(1 - p).div_(1 - p))
class SRU(nn.Module):
def __init__(self, input_size, hidden_size, num_layers=2, dropout=0,
rnn_dropout=0, batch_first=True, use_sigmoid=1,
use_tanh=1, bidirectional=False):
super(SRU, self).__init__()
self.n_in = input_size
self.n_out = hidden_size
self.depth = num_layers
self.dropout = dropout
self.batch_first = batch_first
self.rnn_dropout = rnn_dropout
self.rnn_lst = nn.ModuleList()
self.bidirectional = bidirectional
self.out_size = hidden_size * 2 if bidirectional else hidden_size
for i in range(num_layers):
l = SRUCell(
n_in=self.n_in if i == 0 else self.out_size,
n_out=self.n_out,
dropout=dropout if i + 1 != num_layers else 0,
rnn_dropout=rnn_dropout,
use_tanh=use_tanh,
use_sigmoid=use_sigmoid,
bidirectional=bidirectional
)
self.rnn_lst.append(l)
def set_bias(self, bias_val=0):
for l in self.rnn_lst:
l.set_bias(bias_val)
def reset_parameters(self):
for rnn in self.rnn_lst:
rnn.reset_parameters()
def forward(self, input, c0=None, return_hidden=True):
packed = isinstance(input, R.PackedSequence)
batch_dim = 0 if self.batch_first else 1
seq_dim = 1 if self.batch_first else 0
if packed:
input, lens = R.pad_packed_sequence(input,
batch_first=self.batch_first)
lens_list = lens
lens = Variable(torch.IntTensor(lens))
if input.data.is_cuda:
lens = lens.cuda(input.data.get_device())
else:
lens = None
if self.batch_first:
input = input.transpose(1, 0)
assert input.dim() == 3 # (len, batch, n_in)
dir_ = 2 if self.bidirectional else 1
if c0 is None:
zeros = Variable(input.data.new(
input.size(1), self.n_out * dir_
).zero_())
c0 = [zeros for i in range(self.depth)]
else:
assert c0.dim() == 3 # (depth, batch, n_out*dir_)
c0 = c0.chunk(self.depth, 0)
prevx = input
lstc = []
for i, rnn in enumerate(self.rnn_lst):
h, c = rnn(prevx, c0[i], lens)
prevx = h
lstc.append(c)
if self.batch_first:
prevx = prevx.transpose(1, 0)
if packed:
prevx = R.pack_padded_sequence(prevx, lens_list,
batch_first=self.batch_first)
if return_hidden:
return prevx, torch.stack(lstc)
else:
return prevx
|
{"/src/torchsru/__init__.py": ["/src/torchsru/model.py"]}
|
8,822
|
ottonemo/pytorch-sru
|
refs/heads/master
|
/src/torchsru/__init__.py
|
from .model import SRU
from .model import SRUCell
|
{"/src/torchsru/__init__.py": ["/src/torchsru/model.py"]}
|
8,839
|
TestaVuota/COCO-Style-Dataset-Generator-GUI
|
refs/heads/master
|
/coco_dataset_generator/extras/cut_objects.py
|
import numpy as np
import sys
np.set_printoptions(threshold=sys.maxsize)
import matplotlib.pyplot as plt
from PIL import Image, ImageDraw
import json
from collections import defaultdict
import random
from matplotlib.path import Path
import argparse
import glob
import os
import time
#from skimage.measure import find_contours
from ..gui.contours import find_contours
class Occlusion_Generator_Bbox(object):
def __init__(self, json_file, bg_dir, max_objs, imgs_path, curve_factor):
self.dataset = json.load(open(json_file))
self.max_objs = max_objs
self.imgToAnns = defaultdict(list)
for ann in self.dataset['annotations']:
self.imgToAnns[ann['image_id']].append(ann)
self.objToAnns = [[] for _ in range(len(self.dataset['classes'])+1)]
for index in self.imgToAnns:
for obj in self.imgToAnns[index]:
self.objToAnns[obj['category_id']].append({'image': obj['image_id'], 'bbox':obj['bbox']})
self.bg_dir = bg_dir
self.imgs_dir = imgs_path
self.set_random_background()
self.classes = ['BG'] + self.dataset['classes']
self.curve_factor = curve_factor
def set_random_background(self):
imgs = [x for x in glob.glob(os.path.join(self.bg_dir, '*')) if 'txt' not in x]
print (imgs, self.bg_dir)
bg_path = random.choice(imgs)
self.img = Image.open(bg_path).convert("RGBA")
self.mask_img = Image.new('L', self.img.size, 0)
self.text = ''
def cut_bbox(self, rect): # Takes a bounding box of the form [x_min, y_min, x_max, y_max] and splits it in 2 based on a sine wave and returns 2 PIL polygons
x = np.linspace(rect[0], rect[2], num=50)
y = (rect[3]+rect[1])/2 + 15*np.sin(x/(rect[3]/np.pi/self.curve_factor))
x1 = np.concatenate((x, np.array([rect[2], rect[0]])))
y1 = np.concatenate((y, np.array([rect[3], rect[3]])))
x2 = np.concatenate((x, np.array([rect[2], rect[0]])))
y2 = np.concatenate((y, np.array([rect[1], rect[1]])))
poly1 = [(x,y) for x,y in zip(x1, y1)]
poly2 = [(x,y) for x,y in zip(x2, y2)]
return random.choice([poly1, poly2])
def add_objects(self): #Adds enlarged versions of n_objs (RANDOM) objects to self.img at random locations without overlap
self.text += '%d'%self.image_id + '\n' + os.path.abspath(os.path.join(self.imgs_dir, '%d.jpg'%self.image_id))+'\n'+' '.join([str(x) for x in self.img.size])+'\n\n'
n_objs = random.randint(5, self.max_objs)
for _ in range(n_objs):
c1 = random.randint(1, len(self.objToAnns)-1)
c2 = random.randint(0, len(self.objToAnns[c1])-1)
obj = Image.open(next(item for item in self.dataset['images'] if item["id"] == self.objToAnns[c1][c2]['image'])['file_name'])
obj_bbox = self.objToAnns[c1][c2]['bbox']
obj_bbox = (obj_bbox[2], obj_bbox[3], obj_bbox[0], obj_bbox[1])
obj_mask = Image.new('L', obj.size, 0)
random_occ = self.cut_bbox(obj_bbox)
ImageDraw.Draw(obj_mask).polygon(random_occ, outline=255, fill=255)
obj = obj.crop(obj_bbox)
obj_mask = obj_mask.crop(obj_bbox)
obj = obj.resize(np.array(np.array(obj.size)*1.35, dtype=int))
obj_mask = obj_mask.resize(np.array(np.array(obj_mask.size)*1.35, dtype=int))
done_flag, timeout = False, False
clk = time.time()
while not done_flag:
if time.time()-clk > 1: # One second timeout
timeout = True
randx = random.randint(0, self.img.size[0]-obj.size[0]-2)
randy = random.randint(0, self.img.size[1]-obj.size[1]-2)
temp_mask = self.mask_img.copy()
temp_mask.paste(Image.new('L', obj_mask.size, 0), (randx, randy))
if (temp_mask == self.mask_img):
self.img.paste(obj, (randx, randy), obj_mask)
self.mask_img.paste(obj_mask, (randx, randy))
obj_ann = Image.new('L', self.mask_img.size, 0)
obj_ann.paste(obj_mask, (randx, randy))
padded_mask = np.zeros((obj_ann.size[0] + 2, obj_ann.size[1] + 2), dtype=np.uint8)
padded_mask[1:-1, 1:-1] = np.array(obj_ann)
contours = find_contours(padded_mask, 0.5)
contours = [np.fliplr(verts) - 1 for verts in contours]
x, y = contours[0][:,0], contours[0][:,1]
area = (0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1))))/2 #shoelace algorithm
self.text += self.classes[c1]+'\n'+'%.2f'%area+'\n'+np.array2string(contours[0].flatten(), max_line_width=np.inf, formatter={'float_kind':lambda x: "%.2f" % x})[1:-1]+'\n\n'
done_flag=True
if not done_flag and timeout: # Add timeout-based object-preferencing
print ('Object Timeout')
timeout = False
c2 = random.randint(0, len(self.objToAnns[c1])-1)
obj = Image.open(next(item for item in self.dataset['images'] if item["id"] == self.objToAnns[c1][c2]['image'])['file_name'])
obj_bbox = self.objToAnns[c1][c2]['bbox']
obj_bbox = (obj_bbox[2], obj_bbox[3], obj_bbox[0], obj_bbox[1])
obj_mask = Image.new('L', obj.size, 0)
random_occ = self.cut_bbox(obj_bbox)
ImageDraw.Draw(obj_mask).polygon(random_occ, outline=255, fill=255)
obj = obj.crop(obj_bbox)
obj_mask = obj_mask.crop(obj_bbox)
obj = obj.resize(np.array(np.array(obj.size)*1.35, dtype=int))
obj_mask = obj_mask.resize(np.array(np.array(obj_mask.size)*1.35, dtype=int))
with open(os.path.join(self.imgs_dir, '%d.txt'%self.image_id), 'w') as f:
f.write(self.text)
self.img.convert('RGB').save(os.path.join(self.imgs_dir, '%d.jpg'%self.image_id))
def generate_images(self, num_imgs):
self.image_id = 0
for i in range(num_imgs):
self.set_random_background()
self.add_objects()
self.image_id += 1
print ('Image %d/%d created successfully!!!'%(i+1, num_imgs))
if __name__=='__main__':
parser = argparse.ArgumentParser(
description='Create occluded dataset.')
parser.add_argument('--json_file', required=True,
metavar="/path/to/json_file/",
help='Path to JSON file', default='../pascal_dataset.json')
parser.add_argument('--bg_dir', required=True,
metavar="/path/to/possible/background/images",
help="Path to Background Images", default='background/')
parser.add_argument('--new_dir', required=True,
help="Path to the new dataset directory", default='10')
parser.add_argument('--max_objs', required=True,
help="Maximum number of objects in an image (min=5)", default='10')
parser.add_argument('--curve_factor', required=False,
help="Amount of curvature of the sine wave (>2 values lead to high freq cuts)", default='1.4')
parser.add_argument('--num_imgs', required=True,
help="Total number of images in the synthetic dataset", default='50')
args = parser.parse_args()
occ = Occlusion_Generator_Bbox(args.json_file, args.bg_dir, int(args.max_objs), args.new_dir, float(args.curve_factor))
occ.generate_images(int(args.num_imgs))
|
{"/coco_dataset_generator/extras/cut_objects.py": ["/coco_dataset_generator/gui/contours.py"], "/coco_dataset_generator/gui/segment.py": ["/coco_dataset_generator/gui/contours.py"], "/coco_dataset_generator/extras/occlusion_transforms.py": ["/coco_dataset_generator/gui/contours.py"], "/coco_dataset_generator/utils/create_json_file.py": ["/coco_dataset_generator/gui/segment.py"]}
|
8,840
|
TestaVuota/COCO-Style-Dataset-Generator-GUI
|
refs/heads/master
|
/coco_dataset_generator/gui/contours.py
|
from skimage.measure import find_contours as FC
import numpy as np
from simplification.cutil import simplify_coords
def find_contours(*args):
contours = FC(*args)
simplified_contours = [np.array(simplify_coords(x, 1), dtype=np.int32) \
for x in contours]
return simplified_contours
|
{"/coco_dataset_generator/extras/cut_objects.py": ["/coco_dataset_generator/gui/contours.py"], "/coco_dataset_generator/gui/segment.py": ["/coco_dataset_generator/gui/contours.py"], "/coco_dataset_generator/extras/occlusion_transforms.py": ["/coco_dataset_generator/gui/contours.py"], "/coco_dataset_generator/utils/create_json_file.py": ["/coco_dataset_generator/gui/segment.py"]}
|
8,841
|
TestaVuota/COCO-Style-Dataset-Generator-GUI
|
refs/heads/master
|
/coco_dataset_generator/extras/move_dataset_to_single_folder.py
|
import argparse
import shutil
import json
import os
if __name__=='__main__':
ap = argparse.ArgumentParser()
ap.add_argument('dir', help='Path to folder to put all images in the dataset')
ap.add_argument('json', help='Path to folder to put all images in the dataset')
args = ap.parse_args()
with open(args.json, 'r') as f:
obj = json.load(f)
try:
os.makedirs(args.dir)
except Exception:
pass
for idx, img in enumerate(obj['images']):
path = img['file_name']
newpath = os.path.join(args.dir, '%s.'%(str(idx).zfill(5))+path.split('.')[-1])
shutil.copyfile(path, newpath)
print ("Moving %s to %s"%(path, newpath))
obj['images'][idx]['file_name'] = newpath
print ("Writing new JSON file!")
base, direc = os.path.basename(args.dir), os.path.dirname(args.dir)
with open(os.path.join(direc, '%s_dataset.json'%(base)), 'w') as f:
json.dump(obj, f)
print ("JSON file written!")
|
{"/coco_dataset_generator/extras/cut_objects.py": ["/coco_dataset_generator/gui/contours.py"], "/coco_dataset_generator/gui/segment.py": ["/coco_dataset_generator/gui/contours.py"], "/coco_dataset_generator/extras/occlusion_transforms.py": ["/coco_dataset_generator/gui/contours.py"], "/coco_dataset_generator/utils/create_json_file.py": ["/coco_dataset_generator/gui/segment.py"]}
|
8,842
|
TestaVuota/COCO-Style-Dataset-Generator-GUI
|
refs/heads/master
|
/coco_dataset_generator/gui/segment.py
|
from matplotlib import pyplot as plt
from matplotlib.collections import PatchCollection
from matplotlib.patches import Polygon
from matplotlib.widgets import RadioButtons
from matplotlib.path import Path
from PIL import Image
import matplotlib
import argparse
import numpy as np
import glob
import os
from matplotlib.widgets import Button
from matplotlib.lines import Line2D
from matplotlib.artist import Artist
from .poly_editor import PolygonInteractor, dist_point_to_segment
import sys
from ..utils.visualize_dataset import return_info
class COCO_dataset_generator(object):
def __init__(self, fig, ax, args):
self.ax = ax
self.ax.set_yticklabels([])
self.ax.set_xticklabels([])
self.img_dir = args['image_dir']
self.index = 0
self.fig = fig
self.polys = []
self.zoom_scale, self.points, self.prev, self.submit_p, self.lines, self.circles = 1.2, [], None, None, [], []
self.zoom_id = fig.canvas.mpl_connect('scroll_event', self.zoom)
self.click_id = fig.canvas.mpl_connect('button_press_event', self.onclick)
self.clickrel_id = fig.canvas.mpl_connect('button_release_event', self.onclick_release)
self.keyboard_id = fig.canvas.mpl_connect('key_press_event', self.onkeyboard)
self.axradio = plt.axes([0.0, 0.0, 0.2, 1])
self.axbringprev = plt.axes([0.3, 0.05, 0.17, 0.05])
self.axreset = plt.axes([0.48, 0.05, 0.1, 0.05])
self.axsubmit = plt.axes([0.59, 0.05, 0.1, 0.05])
self.axprev = plt.axes([0.7, 0.05, 0.1, 0.05])
self.axnext = plt.axes([0.81, 0.05, 0.1, 0.05])
self.b_bringprev = Button(self.axbringprev, 'Bring Previous Annotations')
self.b_bringprev.on_clicked(self.bring_prev)
self.b_reset = Button(self.axreset, 'Reset')
self.b_reset.on_clicked(self.reset)
self.b_submit = Button(self.axsubmit, 'Submit')
self.b_submit.on_clicked(self.submit)
self.b_next = Button(self.axnext, 'Next')
self.b_next.on_clicked(self.next)
self.b_prev = Button(self.axprev, 'Prev')
self.b_prev.on_clicked(self.previous)
self.button_axes = [self.axbringprev, self.axreset, self.axsubmit, self.axprev, self.axnext, self.axradio]
self.existing_polys = []
self.existing_patches = []
self.selected_poly = False
self.objects = []
self.feedback = args['feedback']
self.right_click = False
self.text = ''
with open(args['class_file'], 'r') as f:
self.class_names = [x.strip() for x in f.readlines() if x.strip() != ""]
self.radio = RadioButtons(self.axradio, self.class_names)
self.class_names = ('BG',) + tuple(self.class_names)
self.img_paths = sorted(glob.glob(os.path.join(self.img_dir, '*.jpg')))
if len(self.img_paths)==0:
self.img_paths = sorted(glob.glob(os.path.join(self.img_dir, '*.png')))
if os.path.exists(self.img_paths[self.index][:-3]+'txt'):
self.index = len(glob.glob(os.path.join(self.img_dir, '*.txt')))
self.checkpoint = self.index
try:
im = Image.open(self.img_paths[self.index])
except IndexError:
print ("Reached end of dataset! Delete some TXT files if you want to relabel some images in the folder")
exit()
width, height = im.size
im.close()
image = plt.imread(self.img_paths[self.index])
if args['feedback']:
from mask_rcnn import model as modellib
from mask_rcnn.get_json_config import get_demo_config
#from skimage.measure import find_contours
from .contours import find_contours
from mask_rcnn.visualize_cv2 import random_colors
config = get_demo_config(len(self.class_names)-2, True)
if args['config_path'] is not None:
config.from_json(args['config_path'])
# Create model object in inference mode.
model = modellib.MaskRCNN(mode="inference", model_dir='/'.join(args['weights_path'].split('/')[:-2]), config=config)
# Load weights trained on MS-COCO
model.load_weights(args['weights_path'], by_name=True)
r = model.detect([image], verbose=0)[0]
# Number of instances
N = r['rois'].shape[0]
masks = r['masks']
# Generate random colors
colors = random_colors(N)
# Show area outside image boundaries.
height, width = image.shape[:2]
class_ids, scores = r['class_ids'], r['scores']
for i in range(N):
color = colors[i]
# Label
class_id = class_ids[i]
score = scores[i] if scores is not None else None
label = self.class_names[class_id]
# Mask
mask = masks[:, :, i]
# Mask Polygon
# Pad to ensure proper polygons for masks that touch image edges.
padded_mask = np.zeros(
(mask.shape[0] + 2, mask.shape[1] + 2), dtype=np.uint8)
padded_mask[1:-1, 1:-1] = mask
contours = find_contours(padded_mask, 0.5)
for verts in contours:
# Subtract the padding and flip (y, x) to (x, y)
verts = np.fliplr(verts) - 1
pat = PatchCollection([Polygon(verts, closed=True)], facecolor='green', linewidths=0, alpha=0.6)
self.ax.add_collection(pat)
self.objects.append(label)
self.existing_patches.append(pat)
self.existing_polys.append(Polygon(verts, closed=True, alpha=0.25, facecolor='red'))
self.ax.imshow(image, aspect='auto')
self.text+=str(self.index)+'\n'+os.path.abspath(self.img_paths[self.index])+'\n'+str(width)+' '+str(height)+'\n\n'
def bring_prev(self, event):
if not self.feedback:
poly_verts, self.objects = return_info(self.img_paths[self.index-1][:-3]+'txt')
for num in poly_verts:
self.existing_polys.append(Polygon(num, closed=True, alpha=0.5, facecolor='red'))
pat = PatchCollection([Polygon(num, closed=True)], facecolor='green', linewidths=0, alpha=0.6)
self.ax.add_collection(pat)
self.existing_patches.append(pat)
def points_to_polygon(self):
return np.reshape(np.array(self.points), (int(len(self.points)/2), 2))
def deactivate_all(self):
self.fig.canvas.mpl_disconnect(self.zoom_id)
self.fig.canvas.mpl_disconnect(self.click_id)
self.fig.canvas.mpl_disconnect(self.clickrel_id)
self.fig.canvas.mpl_disconnect(self.keyboard_id)
def onkeyboard(self, event):
if not event.inaxes:
return
elif event.key == 'a':
if self.selected_poly:
self.points = self.interactor.get_polygon().xy.flatten()
self.interactor.deactivate()
self.right_click = True
self.selected_poly = False
self.fig.canvas.mpl_connect(self.click_id, self.onclick)
self.polygon.color = (0,255,0)
self.fig.canvas.draw()
else:
for i, poly in enumerate(self.existing_polys):
if poly.get_path().contains_point((event.xdata, event.ydata)):
self.radio.set_active(self.class_names.index(self.objects[i])-1)
self.polygon = self.existing_polys[i]
self.existing_patches[i].set_visible(False)
self.fig.canvas.mpl_disconnect(self.click_id)
self.ax.add_patch(self.polygon)
self.fig.canvas.draw()
self.interactor = PolygonInteractor(self.ax, self.polygon)
self.selected_poly = True
self.existing_polys.pop(i)
break
elif event.key == 'r':
for i, poly in enumerate(self.existing_polys):
if poly.get_path().contains_point((event.xdata, event.ydata)):
self.existing_patches[i].set_visible(False)
self.existing_patches[i].remove()
self.existing_patches.pop(i)
self.existing_polys.pop(i)
break
self.fig.canvas.draw()
def next(self, event):
if len(self.text.split('\n'))>5:
print (self.img_paths[self.index][:-3]+'txt')
with open(self.img_paths[self.index][:-3]+'txt', "w") as text_file:
text_file.write(self.text)
self.ax.clear()
self.ax.set_yticklabels([])
self.ax.set_xticklabels([])
if (self.index<len(self.img_paths)-1):
self.index += 1
else:
exit()
image = plt.imread(self.img_paths[self.index])
self.ax.imshow(image, aspect='auto')
im = Image.open(self.img_paths[self.index])
width, height = im.size
im.close()
self.reset_all()
self.text+=str(self.index)+'\n'+os.path.abspath(self.img_paths[self.index])+'\n'+str(width)+' '+str(height)+'\n\n'
def reset_all(self):
self.polys = []
self.text = ''
self.points, self.prev, self.submit_p, self.lines, self.circles = [], None, None, [], []
def previous(self, event):
if (self.index>self.checkpoint):
self.index-=1
#print (self.img_paths[self.index][:-3]+'txt')
os.remove(self.img_paths[self.index][:-3]+'txt')
self.ax.clear()
self.ax.set_yticklabels([])
self.ax.set_xticklabels([])
image = plt.imread(self.img_paths[self.index])
self.ax.imshow(image, aspect='auto')
im = Image.open(self.img_paths[self.index])
width, height = im.size
im.close()
self.reset_all()
self.text+=str(self.index)+'\n'+os.path.abspath(self.img_paths[self.index])+'\n'+str(width)+' '+str(height)+'\n\n'
def onclick(self, event):
if not event.inaxes:
return
if not any([x.in_axes(event) for x in self.button_axes]):
if event.button==1:
self.points.extend([event.xdata, event.ydata])
#print (event.xdata, event.ydata)
circle = plt.Circle((event.xdata,event.ydata),2.5,color='black')
self.ax.add_artist(circle)
self.circles.append(circle)
if (len(self.points)<4):
self.r_x = event.xdata
self.r_y = event.ydata
else:
if len(self.points)>5:
self.right_click=True
self.fig.canvas.mpl_disconnect(self.click_id)
self.click_id = None
self.points.extend([self.points[0], self.points[1]])
#self.prev.remove()
if (len(self.points)>2):
line = self.ax.plot([self.points[-4], self.points[-2]], [self.points[-3], self.points[-1]], 'b--')
self.lines.append(line)
self.fig.canvas.draw()
if len(self.points)>4:
if self.prev:
self.prev.remove()
self.p = PatchCollection([Polygon(self.points_to_polygon(), closed=True)], facecolor='red', linewidths=0, alpha=0.4)
self.ax.add_collection(self.p)
self.prev = self.p
self.fig.canvas.draw()
#if len(self.points)>4:
# print 'AREA OF POLYGON: ', self.find_poly_area(self.points)
#print event.x, event.y
def find_poly_area(self):
coords = self.points_to_polygon()
x, y = coords[:,0], coords[:,1]
return (0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1))))/2 #shoelace algorithm
def onclick_release(self, event):
if any([x.in_axes(event) for x in self.button_axes]) or self.selected_poly:
return
if hasattr(self, 'r_x') and hasattr(self, 'r_y') and None not in [self.r_x, self.r_y, event.xdata, event.ydata]:
if np.abs(event.xdata - self.r_x)>10 and np.abs(event.ydata - self.r_y)>10: # 10 pixels limit for rectangle creation
if len(self.points)<4:
self.right_click=True
self.fig.canvas.mpl_disconnect(self.click_id)
self.click_id = None
bbox = [np.min([event.xdata, self.r_x]), np.min([event.ydata, self.r_y]), np.max([event.xdata, self.r_x]), np.max([event.ydata, self.r_y])]
self.r_x = self.r_y = None
self.points = [bbox[0], bbox[1], bbox[0], bbox[3], bbox[2], bbox[3], bbox[2], bbox[1], bbox[0], bbox[1]]
self.p = PatchCollection([Polygon(self.points_to_polygon(), closed=True)], facecolor='red', linewidths=0, alpha=0.4)
self.ax.add_collection(self.p)
self.fig.canvas.draw()
def zoom(self, event):
if not event.inaxes:
return
cur_xlim = self.ax.get_xlim()
cur_ylim = self.ax.get_ylim()
xdata = event.xdata # get event x location
ydata = event.ydata # get event y location
if event.button == 'down':
# deal with zoom in
scale_factor = 1 / self.zoom_scale
elif event.button == 'up':
# deal with zoom out
scale_factor = self.zoom_scale
else:
# deal with something that should never happen
scale_factor = 1
print (event.button)
new_width = (cur_xlim[1] - cur_xlim[0]) * scale_factor
new_height = (cur_ylim[1] - cur_ylim[0]) * scale_factor
relx = (cur_xlim[1] - xdata)/(cur_xlim[1] - cur_xlim[0])
rely = (cur_ylim[1] - ydata)/(cur_ylim[1] - cur_ylim[0])
self.ax.set_xlim([xdata - new_width * (1-relx), xdata + new_width * (relx)])
self.ax.set_ylim([ydata - new_height * (1-rely), ydata + new_height * (rely)])
self.ax.figure.canvas.draw()
def reset(self, event):
if not self.click_id:
self.click_id = fig.canvas.mpl_connect('button_press_event', self.onclick)
#print (len(self.lines))
#print (len(self.circles))
if len(self.points)>5:
for line in self.lines:
line.pop(0).remove()
for circle in self.circles:
circle.remove()
self.lines, self.circles = [], []
self.p.remove()
self.prev = self.p = None
self.points = []
#print (len(self.lines))
#print (len(self.circles))
def print_points(self):
ret = ''
for x in self.points:
ret+='%.2f'%x+' '
return ret
def submit(self, event):
if not self.right_click:
print ('Right click before submit is a must!!')
else:
self.text+=self.radio.value_selected+'\n'+'%.2f'%self.find_poly_area()+'\n'+self.print_points()+'\n\n'
self.right_click = False
#print (self.points)
self.lines, self.circles = [], []
self.click_id = fig.canvas.mpl_connect('button_press_event', self.onclick)
self.polys.append(Polygon(self.points_to_polygon(), closed=True, color=np.random.rand(3), alpha=0.4, fill=True))
if self.submit_p:
self.submit_p.remove()
self.submit_p = PatchCollection(self.polys, cmap=matplotlib.cm.jet, alpha=0.4)
self.ax.add_collection(self.submit_p)
self.points = []
if __name__=='__main__':
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image_dir", required=True, help="Path to the image dir")
ap.add_argument("-c", "--class_file", required=True, help="Path to the classes file of the dataset")
ap.add_argument('-w', "--weights_path", default=None, help="Path to Mask RCNN checkpoint save file")
ap.add_argument('-x', "--config_path", default=None, help="Path to Mask RCNN training config JSON file to load model based on specific parameters")
args = vars(ap.parse_args())
args['feedback'] = args['weights_path'] is not None
fig = plt.figure(figsize=(14, 14))
ax = plt.gca()
gen = COCO_dataset_generator(fig, ax, args)
plt.subplots_adjust(bottom=0.2)
plt.show()
gen.deactivate_all()
|
{"/coco_dataset_generator/extras/cut_objects.py": ["/coco_dataset_generator/gui/contours.py"], "/coco_dataset_generator/gui/segment.py": ["/coco_dataset_generator/gui/contours.py"], "/coco_dataset_generator/extras/occlusion_transforms.py": ["/coco_dataset_generator/gui/contours.py"], "/coco_dataset_generator/utils/create_json_file.py": ["/coco_dataset_generator/gui/segment.py"]}
|
8,843
|
TestaVuota/COCO-Style-Dataset-Generator-GUI
|
refs/heads/master
|
/coco_dataset_generator/extras/combine_json_files.py
|
'''
USAGE:
python combine_json_files.py <LIST OF FILES>
'''
import os
import json
import glob
import sys
import numpy as np
import argparse
import os
def cleanup_utf8(array):
arr = [x.encode('ascii', errors='ignore').decode('utf-8') for x in array]
return list(map(lambda x: x.strip().strip('\"').strip('\''), arr))
def merge_json(files, outfile='merged_dataset.json', abspath=False):
img_counter = 0
ann_counter = 0
images, annotations, classes = [], [], []
for file_path in files:
with open(file_path, 'r') as f:
obj = json.load(f)
for img in obj["images"]:
img["id"] += img_counter
if not abspath:
img['file_name'] = os.path.join(
os.path.abspath(os.path.dirname(file_path)),
img['file_name'])
for ann in obj["annotations"]:
ann["id"] += ann_counter
ann["image_id"] += img_counter
ann_counter += len(obj["annotations"])
img_counter += len(obj["images"])
if len(images)==0:
images = obj['images']
annotations = obj['annotations']
classes = cleanup_utf8(obj['classes'])
else:
obj['classes'] = cleanup_utf8(obj['classes'])
if classes != obj["classes"]:
print ("CLASSES MISMATCH BETWEEN:")
print (classes)
print (obj['classes'])
if len(obj['classes']) < len(classes):
c1, c2 = obj['classes'], classes
new = True
else:
c1, c2 = classes, obj['classes']
new = False
mapping = {}
for idx, c in enumerate(c1):
try:
mapping[idx] = c2.index(c)
except Exception:
c2.append(c)
mapping[idx] = len(c2) - 1
print ('MAPPING: ', mapping)
if not new:
for idx, ann in enumerate(annotations):
annotations[idx]['category_id'] = mapping[ann['category_id']-1] + 1
classes = obj['classes']
else:
for idx, ann in enumerate(obj['annotations']):
obj['annotations'][idx]['category_id'] = mapping[ann['category_id']-1] + 1
obj['classes'] = classes
print ("CHANGE IN NUMBER OF CLASSES HAS BEEN DETECTED BETWEEN JSON FILES")
print ("NOW MAPPING OLD CLASSES TO NEW LIST BASED ON TEXTUAL MATCHING")
for k, v in mapping.items():
print (c1[k], "==>", c2[v])
remaining = set(c2) - set(c1)
for r in remaining:
print ("NEW CLASS: ", r)
images.extend(obj["images"])
annotations.extend(obj["annotations"])
with open(outfile, "w") as f:
data = {'images': images, 'annotations':annotations, 'classes': classes, 'categories':[]}
json.dump(data, f)
if __name__=='__main__':
if len(sys.argv) < 3:
print ("Not enough input files to combine into a single dataset file")
exit()
ap = argparse.ArgumentParser()
ap.add_argument('files', nargs='+', help='List of JSON files to combine into single JSON dataset file')
ap.add_argument('--absolute', nargs='+', help='Flag to use absolute paths in JSON file')
args = ap.parse_args()
merge_json(args.files, 'merged_json.json', args.absolute)
|
{"/coco_dataset_generator/extras/cut_objects.py": ["/coco_dataset_generator/gui/contours.py"], "/coco_dataset_generator/gui/segment.py": ["/coco_dataset_generator/gui/contours.py"], "/coco_dataset_generator/extras/occlusion_transforms.py": ["/coco_dataset_generator/gui/contours.py"], "/coco_dataset_generator/utils/create_json_file.py": ["/coco_dataset_generator/gui/segment.py"]}
|
8,844
|
TestaVuota/COCO-Style-Dataset-Generator-GUI
|
refs/heads/master
|
/coco_dataset_generator/extras/occlusion_transforms.py
|
import numpy as np
import glob
import os
import argparse
import scipy.interpolate
import time
from shapely.geometry import Polygon
#from skimage.measure import find_contours
from ..gui.contours import find_contours
from PIL import Image, ImageDraw
class Occlusion_Generator(object):
def __init__(self, strip_width):
self.random_factor = 8
self.distance = strip_width
class Annotation(object):
def __init__(self):
self.objects = []
self.classes = []
self.all_images = []
self.images = []
self.polys = []
self.im_shape = np.asarray(Image.open(glob.glob(os.path.join(args["image_dir"], "*.jpg"))[0])).shape
for ptr, f in enumerate(glob.glob(os.path.join(args["image_dir"], "*.jpg"))):
print ("Processing Image %d/%d"%(ptr+1, len(glob.glob(os.path.join(args["image_dir"], "*.jpg")))))
im = Image.open(f).convert('RGBA')
im.load()
self.images.append(np.asarray(Image.open(f)))
# convert to numpy (for convenience)
imArray = np.asarray(im)
lines = [x for x in range(50, imArray.shape[0], 100)]
image_contents = Annotation()
with open(f[:-3]+'txt', 'r') as f:
txt = f.read().split('\n')
for index in range(6, len(txt), 4):
num = [float(x) for x in txt[index].split(' ')[:-1]]
num = [(num[i], num[i+1]) for i in range(0, len(num), 2)]
image_contents.objects.append([num])
image_contents.classes.append(txt[index-2])
strips = [Annotation() for _ in range(len(lines[2:]))]
poly = [(imArray.shape[1], 0), (0, 0)]
for pos, l in enumerate(lines[2:]):
if ptr == 0:
x, y = [0, imArray.shape[1]], [l, l+self.distance]
y_interp = scipy.interpolate.interp1d(x, y)
x_pts, y_pts = [x[0]], [y[0]]
for p in range(0, imArray.shape[1], 5):
yt = y_interp(p) + (2*np.random.random_sample()-1)*self.random_factor
x_pts.append(p + (2*np.random.random_sample()-1)*self.random_factor)
y_pts.append(yt)
x_pts.append(x[1])
y_pts.append(y[1])
pts = [(x, y) for x, y in zip(x_pts, y_pts)]
poly.extend(pts)
self.polys.append(poly)
else:
poly = self.polys[pos]
#ImageDraw.Draw(im).polygon(poly, fill="white", outline=None)
#ImageDraw.Draw(im).line(pts, fill=128)
#im.show()
#time.sleep(.1)
# create mask
maskimg = Image.new('L', (imArray.shape[1], imArray.shape[0]), 0)
ImageDraw.Draw(maskimg).polygon(poly, outline=1, fill=1)
mask = np.array(maskimg)
#maskimg.show()
for i in range(len(image_contents.classes)):
obj_img = Image.new('L', (imArray.shape[1], imArray.shape[0]), 0)
ImageDraw.Draw(obj_img).polygon(image_contents.objects[i][0], outline=1, fill=1)
obj = np.array(obj_img)
logical_and = mask * obj
if (np.sum(logical_and)>150):
# Mask Polygon
# Pad to ensure proper polygons for masks that touch image edges.
padded_mask = np.zeros(
(logical_and.shape[0] + 2, logical_and.shape[1] + 2), dtype=np.uint8)
padded_mask[1:-1, 1:-1] = logical_and
contours = find_contours(padded_mask, 0.5)
strips[pos].objects.append([np.fliplr(verts) - 1 for verts in contours])
strips[pos].classes.append(image_contents.classes[i])
if ptr == 0:
poly = list(map(tuple, np.flip(np.array(pts), 0)))
self.all_images.append(strips)
def polys_to_string(self, polys):
ret = ''
for poly in polys:
for (x, y) in poly:
ret+='%.2f %.2f '%(x, y)
ret+='\n'
return ret
def find_poly_area(self, poly):
x, y = np.zeros(len(poly)), np.zeros(len(poly))
for i, (xp, yp) in enumerate(poly):
x[i] = xp
y[i] = yp
return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1))) #shoelace algorithm
def generate_samples(self, num, path):
cumulative_mask = None
text = ''
if not os.path.exists(path):
os.mkdir(path)
for i in range(num):
newImage = Image.new('RGBA', (self.im_shape[1], self.im_shape[0]), 0)
text+="occ%d\n%s\n%d %d\n\n"%(i, os.path.join(path, 'occ_%d.jpg'%(i+1)), self.im_shape[0], self.im_shape[1])
for j in range(len(self.all_images[0])):
rand = np.random.randint(len(self.all_images))
# create mask
maskimg = Image.new('L', (self.im_shape[1], self.im_shape[0]), 0)
ImageDraw.Draw(maskimg).polygon(self.polys[j], outline=1, fill=1)
mask = np.array(maskimg)
#Image.fromarray(mask*255, 'L').show()
if cumulative_mask is None:
cumulative_mask = mask
else:
cumulative_mask += mask
#Image.fromarray(cumulative_mask*255, 'L').show()
#time.sleep(.5)
# assemble new image (uint8: 0-255)
newImArray = np.empty(self.im_shape[:2]+(4,), dtype='uint8')
# colors (three first columns, RGB)
newImArray[:,:,:3] = self.images[rand][:,:,:3]
# transparency (4th column)
newImArray[:,:,3] = mask*255
# back to Image from numpy
newIm = Image.fromarray(newImArray, "RGBA")
newImage.paste(newIm, (0, 0), newIm)
for anns, cls in zip(self.all_images[rand][j].objects, self.all_images[rand][j].classes):
text += cls+'\n'
area = 0
for poly in anns:
area += self.find_poly_area(poly)
text+='%.2f\n'%area
text += self.polys_to_string(anns)
text +='\n'
background = Image.new("RGB", (newImArray.shape[1], newImArray.shape[0]), (0, 0, 0))
background.paste(newImage, mask=newImage.split()[3]) # 3 is the alpha channel
background.save(os.path.join(path, 'occ_%d.jpg'%(i+1)))
with open(os.path.join(path, 'occ_%d.txt'%(i+1)), 'w') as f:
f.write(text)
text = ''
print ('Generated %d/%d Images: %s'%(i+1, num, os.path.join(path, 'occ_%d.jpg'%(i+1))))
if __name__=="__main__":
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image_dir", required=True, help="Path to the image dir")
ap.add_argument("-o", "--output_dir", required=True, help="Path to the output dir")
ap.add_argument("-s", "--strip_width", required=True, help="width of strip")
ap.add_argument("-n", "--num_images", required=True, help="number of new images to generate")
args = vars(ap.parse_args())
occlusion_gen = Occlusion_Generator(int(args['strip_width']))
occlusion_gen.generate_samples(int(args['num_images']), args['output_dir'])
|
{"/coco_dataset_generator/extras/cut_objects.py": ["/coco_dataset_generator/gui/contours.py"], "/coco_dataset_generator/gui/segment.py": ["/coco_dataset_generator/gui/contours.py"], "/coco_dataset_generator/extras/occlusion_transforms.py": ["/coco_dataset_generator/gui/contours.py"], "/coco_dataset_generator/utils/create_json_file.py": ["/coco_dataset_generator/gui/segment.py"]}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.