hexsha
stringlengths 40
40
| size
int64 4
1.02M
| ext
stringclasses 8
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
209
| max_stars_repo_name
stringlengths 5
121
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
10
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
209
| max_issues_repo_name
stringlengths 5
121
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
10
| max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
209
| max_forks_repo_name
stringlengths 5
121
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
10
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 4
1.02M
| avg_line_length
float64 1.07
66.1k
| max_line_length
int64 4
266k
| alphanum_fraction
float64 0.01
1
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
32390574078c22a929abd1f5d6de9e9a77027363
| 19,445
|
py
|
Python
|
src/framework/vm2vmLib.py
|
securedataplane/mts
|
9ffe415ce586600e558e7a2855348c9cd1651f49
|
[
"MIT"
] | 1
|
2022-03-10T13:00:25.000Z
|
2022-03-10T13:00:25.000Z
|
src/framework/vm2vmLib.py
|
securedataplane/mts
|
9ffe415ce586600e558e7a2855348c9cd1651f49
|
[
"MIT"
] | 1
|
2019-07-23T08:49:09.000Z
|
2019-07-23T08:49:09.000Z
|
src/framework/vm2vmLib.py
|
securedataplane/mts
|
9ffe415ce586600e558e7a2855348c9cd1651f49
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 9 10:30:56 2018
@author: saad
"""
import expLib as exp
from datetime import datetime
###############################################################################
DpdkMem="1024,0"
#Destination MAC (needed for Flow Rules)
outDestMac="00:00:00:00:30:56"
# RAM value used for Tenant- and OvS VMs
VmRam="4G"
#Cpu Cores for Tenant VMs
TenantVmCores= 2
# Total number of cpu cores
totalCpuCores=16
#message
InitMessage="The scenario is getting prepared ..."
###############################################################################
# SR-IOV Scenarios
###############################################################################
def vm2vm_SRIOV_OneOvs(cnx_server, isDPDK, nbrCores):
cpuArray= exp.cpuAllocation(1, nbrCores, True, True, 4, TenantVmCores, totalCpuCores)
exp.HOST_CPU=cpuArray["hostCpu"]
OvsCpu= cpuArray["ovsCpu"]
DpdkCpu=cpuArray["ovsDpdk"]
cpuDpdkPorts= cpuArray["cpuDpdkPorts"]
TenantVMsCpuArray= cpuArray["TenantVMsCpuArray"]
OvsVMsCpuArray= cpuArray["OvsVMsCpuArray"]
exp.NicConfig=["1","10"]
exp.NicType= "mlx"
exp.isSRIOV= True
exp.Server_cnx= cnx_server
exp.pf_index=0
exp.pfs=[]
exp.vfs=[]
exp.scsName= "vm2vm_SRIOV_OneOvs"+"_IsDPDK="+str(isDPDK)
logTimeStamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
exp.EmailNotify(InitMessage, "is beeing prepared", logTimeStamp)
exp.Logs("", logTimeStamp)
if isDPDK:
exp.IsDPDK= True
exp.OVS_PATH= exp.dpdk_path
else:
exp.IsDPDK= False
exp.OVS_PATH= exp.nodpdk_path
#----------------------------------------#
exp.PhyPorts= [
("enp3s0f0", "10"),
("enp3s0f1", "10")
]
exp.InitialConfig()
port_1_Vfs=exp.pfs[0][2]
port_2_Vfs=exp.pfs[1][2]
exp.MyVfs= [
(port_1_Vfs[0], "0", "off", "vswitch-vm"),
(port_2_Vfs[0], "0", "off", "vswitch-vm"),
(port_1_Vfs[1], "10", "off", "vswitch-vm"),
(port_2_Vfs[1], "10", "off", "vswitch-vm"),
(port_1_Vfs[2], "10", "off", "tenant-green-1"),
(port_2_Vfs[2], "10", "off", "tenant-green-1"),
(port_1_Vfs[3], "20", "off", "vswitch-vm"),
(port_2_Vfs[3], "20", "off", "vswitch-vm"),
(port_1_Vfs[4], "20", "off", "tenant-green-2"),
(port_2_Vfs[4], "20", "off", "tenant-green-2"),
(port_1_Vfs[6], "30", "off", "vswitch-vm"),
(port_2_Vfs[6], "30", "off", "vswitch-vm"),
(port_1_Vfs[7], "30", "off", "tenant-green-3"),
(port_2_Vfs[7], "30", "off", "tenant-green-3"),
(port_1_Vfs[8], "40", "off", "vswitch-vm"),
(port_2_Vfs[8], "40", "off", "vswitch-vm"),
(port_1_Vfs[9], "40", "off", "tenant-green-4"),
(port_2_Vfs[9], "40", "off", "tenant-green-4")
]
exp.usedVms=[
("vswitch-vm", OvsVMsCpuArray[0], VmRam),
("tenant-green-1", TenantVMsCpuArray[0], VmRam),
("tenant-green-2", TenantVMsCpuArray[1], VmRam),
("tenant-green-3", TenantVMsCpuArray[2], VmRam),
("tenant-green-4", TenantVMsCpuArray[3], VmRam)]
if isDPDK:
#----------------- OVS-VM_1------------------
OvsVmPorts1= [
(port_1_Vfs[0], True, cpuDpdkPorts),
(port_2_Vfs[0], True, cpuDpdkPorts),
(port_1_Vfs[1], True, cpuDpdkPorts),
(port_2_Vfs[1], True, cpuDpdkPorts),
(port_1_Vfs[3], True, cpuDpdkPorts),
(port_2_Vfs[3], True, cpuDpdkPorts),
(port_1_Vfs[6], True, cpuDpdkPorts),
(port_2_Vfs[6], True, cpuDpdkPorts),
(port_1_Vfs[8], True, cpuDpdkPorts),
(port_2_Vfs[8], True, cpuDpdkPorts)]
else:
#----------------- OVS-VM_1------------------
OvsVmPorts1= [
(port_1_Vfs[0], False),
(port_2_Vfs[0], False),
(port_1_Vfs[1], False),
(port_2_Vfs[1], False),
(port_1_Vfs[3], False),
(port_2_Vfs[3], False),
(port_1_Vfs[6], False),
(port_2_Vfs[6], False),
(port_1_Vfs[8], False),
(port_2_Vfs[8], False)]
msg= exp.GetScenarioSummary([OvsVmPorts1], OvsCpu, DpdkCpu, DpdkMem)
exp.EmailNotify(msg, "is beeing prepared", logTimeStamp)
exp.Logs(msg, logTimeStamp)
#----------------------------------------#
exp.Vfsconfig()
if isDPDK:
exp.ConfigOVS("vswitch-vm", "br0", OvsVmPorts1, OvsCpu, DpdkMem, DpdkCpu)
else:
exp.ConfigOVS("vswitch-vm", "br0", OvsVmPorts1, OvsCpu)
'''
OVS Flow Rules for OVS-VM-1:
'''
################################# Tenant_1 ##############################
#Flow Rules (1)
#---------------------------------------------------------
match="in_port="+exp.VfsMatch[port_1_Vfs[0]]+",ip,nw_dst=10.0.0.2"
action="mod_dl_dst:"+exp.GetMacByVf(port_1_Vfs[2])+","+exp.VfsMatch[port_1_Vfs[1]]
exp.addFlowRule("vswitch-vm" , exp.OVS_PATH, "br0", match, action)
#Flow Rules (2)
#---------------------------------------------------------
match="in_port="+exp.VfsMatch[port_2_Vfs[1]]
action="mod_dl_dst:"+exp.GetMacByVf(port_1_Vfs[4])+","+exp.VfsMatch[port_1_Vfs[3]]
exp.addFlowRule("vswitch-vm" , exp.OVS_PATH, "br0", match, action)
#Flow Rules (3)
#---------------------------------------------------------
match="in_port="+exp.VfsMatch[port_2_Vfs[3]]
action="mod_dl_dst:"+outDestMac+","+exp.VfsMatch[port_2_Vfs[0]]
exp.addFlowRule("vswitch-vm" , exp.OVS_PATH, "br0", match, action)
################################# Tenant_2 ##############################
#Flow Rules (1)
#---------------------------------------------------------
match="in_port="+exp.VfsMatch[port_1_Vfs[0]]+",ip,nw_dst=10.0.0.4"
action="mod_dl_dst:"+exp.GetMacByVf(port_1_Vfs[7])+","+exp.VfsMatch[port_1_Vfs[6]]
exp.addFlowRule("vswitch-vm" , exp.OVS_PATH, "br0", match, action)
#Flow Rules (2)
#---------------------------------------------------------
match="in_port="+exp.VfsMatch[port_2_Vfs[6]]
action="mod_dl_dst:"+exp.GetMacByVf(port_1_Vfs[9])+","+exp.VfsMatch[port_1_Vfs[8]]
exp.addFlowRule("vswitch-vm" , exp.OVS_PATH, "br0", match, action)
#Flow Rules (3)
#---------------------------------------------------------
match="in_port="+exp.VfsMatch[port_2_Vfs[8]]
action="mod_dl_dst:"+outDestMac+","+exp.VfsMatch[port_2_Vfs[0]]
exp.addFlowRule("vswitch-vm" , exp.OVS_PATH, "br0", match, action)
#show Flow rules of br0
exp.showFlowRules("vswitch-vm", exp.OVS_PATH,"br0")
exp.startL2Frwd(1)
exp.EmailNotify(msg, "is ready", logTimeStamp)
return True
###############################################################################
def vm2vm_SRIOV_TwoOvs(cnx_server, isDPDK, nbrCores, isIsolated):
cpuArray= exp.cpuAllocation(2, nbrCores, isIsolated, True, 4,TenantVmCores, totalCpuCores)
exp.HOST_CPU=cpuArray["hostCpu"];
OvsCpu= cpuArray["ovsCpu"];
DpdkCpu=cpuArray["ovsDpdk"];
cpuDpdkPorts= cpuArray["cpuDpdkPorts"];
TenantVMsCpuArray= cpuArray["TenantVMsCpuArray"];
OvsVMsCpuArray= cpuArray["OvsVMsCpuArray"];
exp.NicConfig=["1","10"]
exp.NicType= "mlx"
exp.isSRIOV= True
exp.Server_cnx= cnx_server
exp.pf_index=0
exp.pfs=[]
exp.vfs=[]
exp.scsName= "vm2vm_SRIOV_TwoOvs"+"_IsDPDK="+str(isDPDK)+"_IsIsolated="+str(isIsolated)
logTimeStamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
exp.EmailNotify(InitMessage, "is beeing prepared", logTimeStamp)
exp.Logs("", logTimeStamp)
if isDPDK:
exp.IsDPDK= True
exp.OVS_PATH= exp.dpdk_path
else:
exp.IsDPDK= False
exp.OVS_PATH= exp.nodpdk_path
#----------------------------------------#
exp.PhyPorts= [
("enp3s0f0", "10"),
("enp3s0f1", "10")
]
exp.InitialConfig()
port_1_Vfs=exp.pfs[0][2]
port_2_Vfs=exp.pfs[1][2]
exp.MyVfs= [
(port_1_Vfs[0], "0", "off", "vswitch-vm"),
(port_2_Vfs[0], "0", "off", "vswitch-vm"),
(port_1_Vfs[1], "10", "off", "vswitch-vm"),
(port_2_Vfs[1], "10", "off", "vswitch-vm"),
(port_1_Vfs[2], "10", "off", "tenant-green-1"),
(port_2_Vfs[2], "10", "off", "tenant-green-1"),
(port_1_Vfs[3], "20", "off", "vswitch-vm"),
(port_2_Vfs[3], "20", "off", "vswitch-vm"),
(port_1_Vfs[4], "20", "off", "tenant-green-2"),
(port_2_Vfs[4], "20", "off", "tenant-green-2"),
(port_1_Vfs[5], "0", "off", "vswitch-vm-2"),
(port_2_Vfs[5], "0", "off", "vswitch-vm-2"),
(port_1_Vfs[6], "30", "off", "vswitch-vm-2"),
(port_2_Vfs[6], "30", "off", "vswitch-vm-2"),
(port_1_Vfs[7], "30", "off", "tenant-green-3"),
(port_2_Vfs[7], "30", "off", "tenant-green-3"),
(port_1_Vfs[8], "40", "off", "vswitch-vm-2"),
(port_2_Vfs[8], "40", "off", "vswitch-vm-2"),
(port_1_Vfs[9], "40", "off", "tenant-green-4"),
(port_2_Vfs[9], "40", "off", "tenant-green-4")
]
exp.usedVms=[
("vswitch-vm", OvsVMsCpuArray[0], VmRam),
("tenant-green-1", TenantVMsCpuArray[0], VmRam),
("tenant-green-2", TenantVMsCpuArray[1], VmRam),
("vswitch-vm-2", OvsVMsCpuArray[1], VmRam),
("tenant-green-3", TenantVMsCpuArray[2], VmRam),
("tenant-green-4", TenantVMsCpuArray[3], VmRam)]
if isDPDK:
#----------------- OVS-VM_1------------------
OvsVmPorts1= [
(port_1_Vfs[0], True, cpuDpdkPorts),
(port_2_Vfs[0], True, cpuDpdkPorts),
(port_1_Vfs[1], True, cpuDpdkPorts),
(port_2_Vfs[1], True, cpuDpdkPorts),
(port_1_Vfs[3], True, cpuDpdkPorts),
(port_2_Vfs[3], True, cpuDpdkPorts)]
#----------------- OVS-VM_2------------------
OvsVmPorts2= [
(port_1_Vfs[5], True, cpuDpdkPorts),
(port_2_Vfs[5], True, cpuDpdkPorts),
(port_1_Vfs[6], True, cpuDpdkPorts),
(port_2_Vfs[6], True, cpuDpdkPorts),
(port_1_Vfs[8], True, cpuDpdkPorts),
(port_2_Vfs[8], True, cpuDpdkPorts)]
else:
#----------------- OVS-VM_1------------------
OvsVmPorts1= [
(port_1_Vfs[0], False),
(port_2_Vfs[0], False),
(port_1_Vfs[1], False),
(port_2_Vfs[1], False),
(port_1_Vfs[3], False),
(port_2_Vfs[3], False)]
#----------------- OVS-VM_2------------------
OvsVmPorts2= [
(port_1_Vfs[5], False),
(port_2_Vfs[5], False),
(port_1_Vfs[6], False),
(port_2_Vfs[6], False),
(port_1_Vfs[8], False),
(port_2_Vfs[8], False)]
msg= exp.GetScenarioSummary([OvsVmPorts1, OvsVmPorts2], OvsCpu, DpdkCpu, DpdkMem, isIsolated)
exp.EmailNotify(msg, "is beeing prepared", logTimeStamp)
exp.Logs(msg, logTimeStamp)
#----------------------------------------#
exp.Vfsconfig()
if isDPDK:
exp.ConfigOVS("vswitch-vm", "br0", OvsVmPorts1, OvsCpu, DpdkMem, DpdkCpu)
exp.ConfigOVS("vswitch-vm-2", "br0", OvsVmPorts2, OvsCpu, DpdkMem, DpdkCpu)
else:
exp.ConfigOVS("vswitch-vm", "br0", OvsVmPorts1, OvsCpu)
exp.ConfigOVS("vswitch-vm-2", "br0", OvsVmPorts2, OvsCpu)
'''
OVS Flow Rules for OVS-VM-1:
'''
#Flow Rules (1)
#---------------------------------------------------------
match="in_port="+exp.VfsMatch[port_1_Vfs[0]]+",ip,nw_dst=10.0.0.2"
action="mod_dl_dst:"+exp.GetMacByVf(port_1_Vfs[2])+","+exp.VfsMatch[port_1_Vfs[1]]
exp.addFlowRule("vswitch-vm" , exp.OVS_PATH, "br0", match, action)
#Flow Rules (2)
#---------------------------------------------------------
match="in_port="+exp.VfsMatch[port_2_Vfs[1]]
action="mod_dl_dst:"+exp.GetMacByVf(port_1_Vfs[4])+","+exp.VfsMatch[port_1_Vfs[3]]
exp.addFlowRule("vswitch-vm" , exp.OVS_PATH, "br0", match, action)
#Flow Rules (3)
#---------------------------------------------------------
match="in_port="+exp.VfsMatch[port_2_Vfs[3]]
action="mod_dl_dst:"+outDestMac+","+exp.VfsMatch[port_2_Vfs[0]]
exp.addFlowRule("vswitch-vm" , exp.OVS_PATH, "br0", match, action)
#show Flow rules of br0
exp.showFlowRules("vswitch-vm", exp.OVS_PATH,"br0")
'''
OVS Flow Rules for OVS-VM-2:
'''
#Flow Rules (1)
#---------------------------------------------------------
match="in_port="+exp.VfsMatch[port_1_Vfs[5]]+",ip,nw_dst=10.0.0.4"
action="mod_dl_dst:"+exp.GetMacByVf(port_1_Vfs[7])+","+exp.VfsMatch[port_1_Vfs[6]]
exp.addFlowRule("vswitch-vm-2" , exp.OVS_PATH, "br0", match, action)
#Flow Rules (2)
#---------------------------------------------------------
match="in_port="+exp.VfsMatch[port_2_Vfs[6]]
action="mod_dl_dst:"+exp.GetMacByVf(port_1_Vfs[9])+","+exp.VfsMatch[port_1_Vfs[8]]
exp.addFlowRule("vswitch-vm-2" , exp.OVS_PATH, "br0", match, action)
#Flow Rules (3)
#---------------------------------------------------------
match="in_port="+exp.VfsMatch[port_2_Vfs[8]]
action="mod_dl_dst:"+outDestMac+","+exp.VfsMatch[port_2_Vfs[5]]
exp.addFlowRule("vswitch-vm-2" , exp.OVS_PATH, "br0", match, action)
#show Flow rules of br0
exp.showFlowRules("vswitch-vm-2", exp.OVS_PATH,"br0")
exp.startL2Frwd(2)
exp.EmailNotify(msg, "is ready", logTimeStamp)
return True
###############################################################################
# Baseline
###############################################################################
def vm2vm_Baseline(cnx_server, isDPDK, nbrCores):
cpuArray= exp.cpuAllocation(1, nbrCores, True, False, 4, TenantVmCores, totalCpuCores)
exp.HOST_CPU=cpuArray["hostCpu"]
OvsCpu= cpuArray["ovsCpu"]
DpdkCpu=cpuArray["ovsDpdk"]
cpuDpdkPorts= cpuArray["cpuDpdkPorts"]
TenantVMsCpuArray= cpuArray["TenantVMsCpuArray"]
exp.NicType= "mlx"
exp.isSRIOV= False
exp.Server_cnx= cnx_server
exp.scsName= "vm2vm_Baseline"+"_IsDPDK="+str(isDPDK)
logTimeStamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
if isDPDK:
exp.IsDPDK= True
exp.OVS_PATH= exp.dpdk_path
else:
exp.IsDPDK= False
exp.OVS_PATH= exp.nodpdk_path
# ----------------------------------------#
exp.VirtualPorts = [
("1", "br0", "tenant-green-1"),
("2", "br0", "tenant-green-1"),
("4", "br0", "tenant-green-2"),
("5", "br0", "tenant-green-2"),
("7", "br0", "tenant-green-3"),
("8", "br0", "tenant-green-3"),
("10", "br0", "tenant-green-4"),
("11", "br0", "tenant-green-4")
]
exp.usedVms = [
("tenant-green-1", TenantVMsCpuArray[0], VmRam),
("tenant-green-2", TenantVMsCpuArray[1], VmRam),
("tenant-green-3", TenantVMsCpuArray[2], VmRam),
("tenant-green-4", TenantVMsCpuArray[3], VmRam)]
if isDPDK:
exp.PhyPorts= [
("enp3s0f0", "br0", True, cpuDpdkPorts),
("enp3s0f1", "br0", True, cpuDpdkPorts)]
else:
exp.PhyPorts= [
("enp3s0f0", "br0"),
("enp3s0f1", "br0")]
msg= exp.GetScenarioSummary([], OvsCpu, DpdkCpu, DpdkMem)
exp.EmailNotify(msg, "is beeing prepared", logTimeStamp)
exp.Logs(msg, logTimeStamp)
# ----------------------------------------#
exp.InitialConfig(isDPDK)
if isDPDK:
exp.ConfigOVS(exp.Server_cnx, "br0", " ", OvsCpu, DpdkMem, DpdkCpu)
else:
exp.ConfigOVS(exp.Server_cnx, "br0", " ", OvsCpu)
exp.VirPortConfig()
'''
OVS Flow Rules T1 --> T2:
'''
# Flow Rules (1)
# ---------------------------------------------------------
match = "in_port=enp3s0f0,ip,nw_dst=10.0.0.2"
action = "vnet1"
exp.addFlowRule(exp.Server_cnx, exp.OVS_PATH, "br0", match, action)
# Flow Rules (2)
# ---------------------------------------------------------
match = "in_port=vnet2"
action = "vnet4"
exp.addFlowRule(exp.Server_cnx, exp.OVS_PATH, "br0", match, action)
# Flow Rules (3)
# ---------------------------------------------------------
match = "in_port=vnet5"
action = "enp3s0f1"
exp.addFlowRule(exp.Server_cnx, exp.OVS_PATH, "br0", match, action)
'''
OVS Flow Rules T3 --> T4:
'''
# Flow Rules (1)
# ---------------------------------------------------------
match = "in_port=enp3s0f0,ip,nw_dst=10.0.0.4"
action = "vnet7"
exp.addFlowRule(exp.Server_cnx, exp.OVS_PATH, "br0", match, action)
# Flow Rules (2)
# ---------------------------------------------------------
match = "in_port=vnet8"
action = "vnet10"
exp.addFlowRule(exp.Server_cnx, exp.OVS_PATH, "br0", match, action)
# Flow Rules (3)
# ---------------------------------------------------------
match = "in_port=vnet11"
action = "enp3s0f1"
exp.addFlowRule(exp.Server_cnx, exp.OVS_PATH, "br0", match, action)
# show Flow rules of br0
exp.showFlowRules(exp.Server_cnx, exp.OVS_PATH, "br0")
# exp.startL2Frwd(nbrOvs=1 ,nicType="e1000", tenantCount=4, vswitchMode="Baseline_4Tenants")
exp.SetBridging("tenant-green-1", exp.VirPortsMatch["1"], exp.VirPortsMatch["2"])
exp.SetBridging("tenant-green-2", exp.VirPortsMatch["4"], exp.VirPortsMatch["5"])
exp.SetBridging("tenant-green-3", exp.VirPortsMatch["7"], exp.VirPortsMatch["8"])
exp.SetBridging("tenant-green-4", exp.VirPortsMatch["10"], exp.VirPortsMatch["11"])
exp.EmailNotify(msg, "is ready", logTimeStamp)
return True
##############################################################################
| 36.619586
| 98
| 0.475546
|
4d5733dc21b2dd7bb8e9d525da478e5b9cfa9d15
| 1,166
|
py
|
Python
|
filterconfig.py
|
bpmbank/xiaohuangji-new
|
3eafcbdbf4379eee3064bd6cbb1c7807d8d54b2d
|
[
"MIT"
] | 311
|
2015-01-15T10:09:41.000Z
|
2022-02-25T04:32:52.000Z
|
filterconfig.py
|
larusx/xiaohuangji-new
|
bae882487416483af0ef94206a232d93f843d85d
|
[
"MIT"
] | 5
|
2015-11-07T12:50:53.000Z
|
2017-12-06T07:25:54.000Z
|
filterconfig.py
|
larusx/xiaohuangji-new
|
bae882487416483af0ef94206a232d93f843d85d
|
[
"MIT"
] | 129
|
2015-06-26T02:30:46.000Z
|
2021-09-11T05:58:48.000Z
|
#-*-coding:utf-8-*-
"""
Copyright (c) 2012 Qijiang Fan <fqj1994@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from filter import *
rules_question = []
rules_answer = []
| 37.612903
| 70
| 0.786449
|
8814ce443df24387952f3781612a4cacebe6c241
| 31,668
|
py
|
Python
|
sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_12_01/models/_paged_models.py
|
iscai-msft/azure-sdk-for-python
|
83715b95c41e519d5be7f1180195e2fba136fc0f
|
[
"MIT"
] | 1
|
2021-06-02T08:01:35.000Z
|
2021-06-02T08:01:35.000Z
|
sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_12_01/models/_paged_models.py
|
iscai-msft/azure-sdk-for-python
|
83715b95c41e519d5be7f1180195e2fba136fc0f
|
[
"MIT"
] | 226
|
2019-07-24T07:57:21.000Z
|
2019-10-15T01:07:24.000Z
|
sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_12_01/models/_paged_models.py
|
iscai-msft/azure-sdk-for-python
|
83715b95c41e519d5be7f1180195e2fba136fc0f
|
[
"MIT"
] | 1
|
2019-06-17T22:18:23.000Z
|
2019-06-17T22:18:23.000Z
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.paging import Paged
class ApplicationGatewayPaged(Paged):
"""
A paging container for iterating over a list of :class:`ApplicationGateway <azure.mgmt.network.v2018_12_01.models.ApplicationGateway>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[ApplicationGateway]'}
}
def __init__(self, *args, **kwargs):
super(ApplicationGatewayPaged, self).__init__(*args, **kwargs)
class ApplicationGatewaySslPredefinedPolicyPaged(Paged):
"""
A paging container for iterating over a list of :class:`ApplicationGatewaySslPredefinedPolicy <azure.mgmt.network.v2018_12_01.models.ApplicationGatewaySslPredefinedPolicy>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[ApplicationGatewaySslPredefinedPolicy]'}
}
def __init__(self, *args, **kwargs):
super(ApplicationGatewaySslPredefinedPolicyPaged, self).__init__(*args, **kwargs)
class ApplicationSecurityGroupPaged(Paged):
"""
A paging container for iterating over a list of :class:`ApplicationSecurityGroup <azure.mgmt.network.v2018_12_01.models.ApplicationSecurityGroup>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[ApplicationSecurityGroup]'}
}
def __init__(self, *args, **kwargs):
super(ApplicationSecurityGroupPaged, self).__init__(*args, **kwargs)
class AvailableDelegationPaged(Paged):
"""
A paging container for iterating over a list of :class:`AvailableDelegation <azure.mgmt.network.v2018_12_01.models.AvailableDelegation>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[AvailableDelegation]'}
}
def __init__(self, *args, **kwargs):
super(AvailableDelegationPaged, self).__init__(*args, **kwargs)
class AzureFirewallPaged(Paged):
"""
A paging container for iterating over a list of :class:`AzureFirewall <azure.mgmt.network.v2018_12_01.models.AzureFirewall>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[AzureFirewall]'}
}
def __init__(self, *args, **kwargs):
super(AzureFirewallPaged, self).__init__(*args, **kwargs)
class AzureFirewallFqdnTagPaged(Paged):
"""
A paging container for iterating over a list of :class:`AzureFirewallFqdnTag <azure.mgmt.network.v2018_12_01.models.AzureFirewallFqdnTag>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[AzureFirewallFqdnTag]'}
}
def __init__(self, *args, **kwargs):
super(AzureFirewallFqdnTagPaged, self).__init__(*args, **kwargs)
class DdosProtectionPlanPaged(Paged):
"""
A paging container for iterating over a list of :class:`DdosProtectionPlan <azure.mgmt.network.v2018_12_01.models.DdosProtectionPlan>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[DdosProtectionPlan]'}
}
def __init__(self, *args, **kwargs):
super(DdosProtectionPlanPaged, self).__init__(*args, **kwargs)
class EndpointServiceResultPaged(Paged):
"""
A paging container for iterating over a list of :class:`EndpointServiceResult <azure.mgmt.network.v2018_12_01.models.EndpointServiceResult>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[EndpointServiceResult]'}
}
def __init__(self, *args, **kwargs):
super(EndpointServiceResultPaged, self).__init__(*args, **kwargs)
class ExpressRouteCircuitAuthorizationPaged(Paged):
"""
A paging container for iterating over a list of :class:`ExpressRouteCircuitAuthorization <azure.mgmt.network.v2018_12_01.models.ExpressRouteCircuitAuthorization>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[ExpressRouteCircuitAuthorization]'}
}
def __init__(self, *args, **kwargs):
super(ExpressRouteCircuitAuthorizationPaged, self).__init__(*args, **kwargs)
class ExpressRouteCircuitPeeringPaged(Paged):
"""
A paging container for iterating over a list of :class:`ExpressRouteCircuitPeering <azure.mgmt.network.v2018_12_01.models.ExpressRouteCircuitPeering>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[ExpressRouteCircuitPeering]'}
}
def __init__(self, *args, **kwargs):
super(ExpressRouteCircuitPeeringPaged, self).__init__(*args, **kwargs)
class ExpressRouteCircuitConnectionPaged(Paged):
"""
A paging container for iterating over a list of :class:`ExpressRouteCircuitConnection <azure.mgmt.network.v2018_12_01.models.ExpressRouteCircuitConnection>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[ExpressRouteCircuitConnection]'}
}
def __init__(self, *args, **kwargs):
super(ExpressRouteCircuitConnectionPaged, self).__init__(*args, **kwargs)
class PeerExpressRouteCircuitConnectionPaged(Paged):
"""
A paging container for iterating over a list of :class:`PeerExpressRouteCircuitConnection <azure.mgmt.network.v2018_12_01.models.PeerExpressRouteCircuitConnection>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[PeerExpressRouteCircuitConnection]'}
}
def __init__(self, *args, **kwargs):
super(PeerExpressRouteCircuitConnectionPaged, self).__init__(*args, **kwargs)
class ExpressRouteCircuitPaged(Paged):
"""
A paging container for iterating over a list of :class:`ExpressRouteCircuit <azure.mgmt.network.v2018_12_01.models.ExpressRouteCircuit>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[ExpressRouteCircuit]'}
}
def __init__(self, *args, **kwargs):
super(ExpressRouteCircuitPaged, self).__init__(*args, **kwargs)
class ExpressRouteServiceProviderPaged(Paged):
"""
A paging container for iterating over a list of :class:`ExpressRouteServiceProvider <azure.mgmt.network.v2018_12_01.models.ExpressRouteServiceProvider>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[ExpressRouteServiceProvider]'}
}
def __init__(self, *args, **kwargs):
super(ExpressRouteServiceProviderPaged, self).__init__(*args, **kwargs)
class ExpressRouteCrossConnectionPaged(Paged):
"""
A paging container for iterating over a list of :class:`ExpressRouteCrossConnection <azure.mgmt.network.v2018_12_01.models.ExpressRouteCrossConnection>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[ExpressRouteCrossConnection]'}
}
def __init__(self, *args, **kwargs):
super(ExpressRouteCrossConnectionPaged, self).__init__(*args, **kwargs)
class ExpressRouteCrossConnectionPeeringPaged(Paged):
"""
A paging container for iterating over a list of :class:`ExpressRouteCrossConnectionPeering <azure.mgmt.network.v2018_12_01.models.ExpressRouteCrossConnectionPeering>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[ExpressRouteCrossConnectionPeering]'}
}
def __init__(self, *args, **kwargs):
super(ExpressRouteCrossConnectionPeeringPaged, self).__init__(*args, **kwargs)
class ExpressRoutePortsLocationPaged(Paged):
"""
A paging container for iterating over a list of :class:`ExpressRoutePortsLocation <azure.mgmt.network.v2018_12_01.models.ExpressRoutePortsLocation>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[ExpressRoutePortsLocation]'}
}
def __init__(self, *args, **kwargs):
super(ExpressRoutePortsLocationPaged, self).__init__(*args, **kwargs)
class ExpressRoutePortPaged(Paged):
"""
A paging container for iterating over a list of :class:`ExpressRoutePort <azure.mgmt.network.v2018_12_01.models.ExpressRoutePort>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[ExpressRoutePort]'}
}
def __init__(self, *args, **kwargs):
super(ExpressRoutePortPaged, self).__init__(*args, **kwargs)
class ExpressRouteLinkPaged(Paged):
"""
A paging container for iterating over a list of :class:`ExpressRouteLink <azure.mgmt.network.v2018_12_01.models.ExpressRouteLink>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[ExpressRouteLink]'}
}
def __init__(self, *args, **kwargs):
super(ExpressRouteLinkPaged, self).__init__(*args, **kwargs)
class InterfaceEndpointPaged(Paged):
"""
A paging container for iterating over a list of :class:`InterfaceEndpoint <azure.mgmt.network.v2018_12_01.models.InterfaceEndpoint>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[InterfaceEndpoint]'}
}
def __init__(self, *args, **kwargs):
super(InterfaceEndpointPaged, self).__init__(*args, **kwargs)
class LoadBalancerPaged(Paged):
"""
A paging container for iterating over a list of :class:`LoadBalancer <azure.mgmt.network.v2018_12_01.models.LoadBalancer>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[LoadBalancer]'}
}
def __init__(self, *args, **kwargs):
super(LoadBalancerPaged, self).__init__(*args, **kwargs)
class BackendAddressPoolPaged(Paged):
"""
A paging container for iterating over a list of :class:`BackendAddressPool <azure.mgmt.network.v2018_12_01.models.BackendAddressPool>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[BackendAddressPool]'}
}
def __init__(self, *args, **kwargs):
super(BackendAddressPoolPaged, self).__init__(*args, **kwargs)
class FrontendIPConfigurationPaged(Paged):
"""
A paging container for iterating over a list of :class:`FrontendIPConfiguration <azure.mgmt.network.v2018_12_01.models.FrontendIPConfiguration>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[FrontendIPConfiguration]'}
}
def __init__(self, *args, **kwargs):
super(FrontendIPConfigurationPaged, self).__init__(*args, **kwargs)
class InboundNatRulePaged(Paged):
"""
A paging container for iterating over a list of :class:`InboundNatRule <azure.mgmt.network.v2018_12_01.models.InboundNatRule>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[InboundNatRule]'}
}
def __init__(self, *args, **kwargs):
super(InboundNatRulePaged, self).__init__(*args, **kwargs)
class LoadBalancingRulePaged(Paged):
"""
A paging container for iterating over a list of :class:`LoadBalancingRule <azure.mgmt.network.v2018_12_01.models.LoadBalancingRule>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[LoadBalancingRule]'}
}
def __init__(self, *args, **kwargs):
super(LoadBalancingRulePaged, self).__init__(*args, **kwargs)
class OutboundRulePaged(Paged):
"""
A paging container for iterating over a list of :class:`OutboundRule <azure.mgmt.network.v2018_12_01.models.OutboundRule>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[OutboundRule]'}
}
def __init__(self, *args, **kwargs):
super(OutboundRulePaged, self).__init__(*args, **kwargs)
class NetworkInterfacePaged(Paged):
"""
A paging container for iterating over a list of :class:`NetworkInterface <azure.mgmt.network.v2018_12_01.models.NetworkInterface>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[NetworkInterface]'}
}
def __init__(self, *args, **kwargs):
super(NetworkInterfacePaged, self).__init__(*args, **kwargs)
class ProbePaged(Paged):
"""
A paging container for iterating over a list of :class:`Probe <azure.mgmt.network.v2018_12_01.models.Probe>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[Probe]'}
}
def __init__(self, *args, **kwargs):
super(ProbePaged, self).__init__(*args, **kwargs)
class NetworkInterfaceIPConfigurationPaged(Paged):
"""
A paging container for iterating over a list of :class:`NetworkInterfaceIPConfiguration <azure.mgmt.network.v2018_12_01.models.NetworkInterfaceIPConfiguration>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[NetworkInterfaceIPConfiguration]'}
}
def __init__(self, *args, **kwargs):
super(NetworkInterfaceIPConfigurationPaged, self).__init__(*args, **kwargs)
class NetworkInterfaceTapConfigurationPaged(Paged):
"""
A paging container for iterating over a list of :class:`NetworkInterfaceTapConfiguration <azure.mgmt.network.v2018_12_01.models.NetworkInterfaceTapConfiguration>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[NetworkInterfaceTapConfiguration]'}
}
def __init__(self, *args, **kwargs):
super(NetworkInterfaceTapConfigurationPaged, self).__init__(*args, **kwargs)
class NetworkProfilePaged(Paged):
"""
A paging container for iterating over a list of :class:`NetworkProfile <azure.mgmt.network.v2018_12_01.models.NetworkProfile>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[NetworkProfile]'}
}
def __init__(self, *args, **kwargs):
super(NetworkProfilePaged, self).__init__(*args, **kwargs)
class NetworkSecurityGroupPaged(Paged):
"""
A paging container for iterating over a list of :class:`NetworkSecurityGroup <azure.mgmt.network.v2018_12_01.models.NetworkSecurityGroup>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[NetworkSecurityGroup]'}
}
def __init__(self, *args, **kwargs):
super(NetworkSecurityGroupPaged, self).__init__(*args, **kwargs)
class SecurityRulePaged(Paged):
"""
A paging container for iterating over a list of :class:`SecurityRule <azure.mgmt.network.v2018_12_01.models.SecurityRule>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[SecurityRule]'}
}
def __init__(self, *args, **kwargs):
super(SecurityRulePaged, self).__init__(*args, **kwargs)
class NetworkWatcherPaged(Paged):
"""
A paging container for iterating over a list of :class:`NetworkWatcher <azure.mgmt.network.v2018_12_01.models.NetworkWatcher>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[NetworkWatcher]'}
}
def __init__(self, *args, **kwargs):
super(NetworkWatcherPaged, self).__init__(*args, **kwargs)
class PacketCaptureResultPaged(Paged):
"""
A paging container for iterating over a list of :class:`PacketCaptureResult <azure.mgmt.network.v2018_12_01.models.PacketCaptureResult>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[PacketCaptureResult]'}
}
def __init__(self, *args, **kwargs):
super(PacketCaptureResultPaged, self).__init__(*args, **kwargs)
class ConnectionMonitorResultPaged(Paged):
"""
A paging container for iterating over a list of :class:`ConnectionMonitorResult <azure.mgmt.network.v2018_12_01.models.ConnectionMonitorResult>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[ConnectionMonitorResult]'}
}
def __init__(self, *args, **kwargs):
super(ConnectionMonitorResultPaged, self).__init__(*args, **kwargs)
class OperationPaged(Paged):
"""
A paging container for iterating over a list of :class:`Operation <azure.mgmt.network.v2018_12_01.models.Operation>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[Operation]'}
}
def __init__(self, *args, **kwargs):
super(OperationPaged, self).__init__(*args, **kwargs)
class PublicIPAddressPaged(Paged):
"""
A paging container for iterating over a list of :class:`PublicIPAddress <azure.mgmt.network.v2018_12_01.models.PublicIPAddress>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[PublicIPAddress]'}
}
def __init__(self, *args, **kwargs):
super(PublicIPAddressPaged, self).__init__(*args, **kwargs)
class PublicIPPrefixPaged(Paged):
"""
A paging container for iterating over a list of :class:`PublicIPPrefix <azure.mgmt.network.v2018_12_01.models.PublicIPPrefix>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[PublicIPPrefix]'}
}
def __init__(self, *args, **kwargs):
super(PublicIPPrefixPaged, self).__init__(*args, **kwargs)
class RouteFilterPaged(Paged):
"""
A paging container for iterating over a list of :class:`RouteFilter <azure.mgmt.network.v2018_12_01.models.RouteFilter>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[RouteFilter]'}
}
def __init__(self, *args, **kwargs):
super(RouteFilterPaged, self).__init__(*args, **kwargs)
class RouteFilterRulePaged(Paged):
"""
A paging container for iterating over a list of :class:`RouteFilterRule <azure.mgmt.network.v2018_12_01.models.RouteFilterRule>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[RouteFilterRule]'}
}
def __init__(self, *args, **kwargs):
super(RouteFilterRulePaged, self).__init__(*args, **kwargs)
class RouteTablePaged(Paged):
"""
A paging container for iterating over a list of :class:`RouteTable <azure.mgmt.network.v2018_12_01.models.RouteTable>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[RouteTable]'}
}
def __init__(self, *args, **kwargs):
super(RouteTablePaged, self).__init__(*args, **kwargs)
class RoutePaged(Paged):
"""
A paging container for iterating over a list of :class:`Route <azure.mgmt.network.v2018_12_01.models.Route>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[Route]'}
}
def __init__(self, *args, **kwargs):
super(RoutePaged, self).__init__(*args, **kwargs)
class BgpServiceCommunityPaged(Paged):
"""
A paging container for iterating over a list of :class:`BgpServiceCommunity <azure.mgmt.network.v2018_12_01.models.BgpServiceCommunity>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[BgpServiceCommunity]'}
}
def __init__(self, *args, **kwargs):
super(BgpServiceCommunityPaged, self).__init__(*args, **kwargs)
class ServiceEndpointPolicyPaged(Paged):
"""
A paging container for iterating over a list of :class:`ServiceEndpointPolicy <azure.mgmt.network.v2018_12_01.models.ServiceEndpointPolicy>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[ServiceEndpointPolicy]'}
}
def __init__(self, *args, **kwargs):
super(ServiceEndpointPolicyPaged, self).__init__(*args, **kwargs)
class ServiceEndpointPolicyDefinitionPaged(Paged):
"""
A paging container for iterating over a list of :class:`ServiceEndpointPolicyDefinition <azure.mgmt.network.v2018_12_01.models.ServiceEndpointPolicyDefinition>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[ServiceEndpointPolicyDefinition]'}
}
def __init__(self, *args, **kwargs):
super(ServiceEndpointPolicyDefinitionPaged, self).__init__(*args, **kwargs)
class UsagePaged(Paged):
"""
A paging container for iterating over a list of :class:`Usage <azure.mgmt.network.v2018_12_01.models.Usage>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[Usage]'}
}
def __init__(self, *args, **kwargs):
super(UsagePaged, self).__init__(*args, **kwargs)
class VirtualNetworkPaged(Paged):
"""
A paging container for iterating over a list of :class:`VirtualNetwork <azure.mgmt.network.v2018_12_01.models.VirtualNetwork>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[VirtualNetwork]'}
}
def __init__(self, *args, **kwargs):
super(VirtualNetworkPaged, self).__init__(*args, **kwargs)
class VirtualNetworkUsagePaged(Paged):
"""
A paging container for iterating over a list of :class:`VirtualNetworkUsage <azure.mgmt.network.v2018_12_01.models.VirtualNetworkUsage>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[VirtualNetworkUsage]'}
}
def __init__(self, *args, **kwargs):
super(VirtualNetworkUsagePaged, self).__init__(*args, **kwargs)
class SubnetPaged(Paged):
"""
A paging container for iterating over a list of :class:`Subnet <azure.mgmt.network.v2018_12_01.models.Subnet>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[Subnet]'}
}
def __init__(self, *args, **kwargs):
super(SubnetPaged, self).__init__(*args, **kwargs)
class VirtualNetworkPeeringPaged(Paged):
"""
A paging container for iterating over a list of :class:`VirtualNetworkPeering <azure.mgmt.network.v2018_12_01.models.VirtualNetworkPeering>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[VirtualNetworkPeering]'}
}
def __init__(self, *args, **kwargs):
super(VirtualNetworkPeeringPaged, self).__init__(*args, **kwargs)
class VirtualNetworkGatewayPaged(Paged):
"""
A paging container for iterating over a list of :class:`VirtualNetworkGateway <azure.mgmt.network.v2018_12_01.models.VirtualNetworkGateway>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[VirtualNetworkGateway]'}
}
def __init__(self, *args, **kwargs):
super(VirtualNetworkGatewayPaged, self).__init__(*args, **kwargs)
class VirtualNetworkGatewayConnectionListEntityPaged(Paged):
"""
A paging container for iterating over a list of :class:`VirtualNetworkGatewayConnectionListEntity <azure.mgmt.network.v2018_12_01.models.VirtualNetworkGatewayConnectionListEntity>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[VirtualNetworkGatewayConnectionListEntity]'}
}
def __init__(self, *args, **kwargs):
super(VirtualNetworkGatewayConnectionListEntityPaged, self).__init__(*args, **kwargs)
class VirtualNetworkGatewayConnectionPaged(Paged):
"""
A paging container for iterating over a list of :class:`VirtualNetworkGatewayConnection <azure.mgmt.network.v2018_12_01.models.VirtualNetworkGatewayConnection>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[VirtualNetworkGatewayConnection]'}
}
def __init__(self, *args, **kwargs):
super(VirtualNetworkGatewayConnectionPaged, self).__init__(*args, **kwargs)
class LocalNetworkGatewayPaged(Paged):
"""
A paging container for iterating over a list of :class:`LocalNetworkGateway <azure.mgmt.network.v2018_12_01.models.LocalNetworkGateway>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[LocalNetworkGateway]'}
}
def __init__(self, *args, **kwargs):
super(LocalNetworkGatewayPaged, self).__init__(*args, **kwargs)
class VirtualNetworkTapPaged(Paged):
"""
A paging container for iterating over a list of :class:`VirtualNetworkTap <azure.mgmt.network.v2018_12_01.models.VirtualNetworkTap>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[VirtualNetworkTap]'}
}
def __init__(self, *args, **kwargs):
super(VirtualNetworkTapPaged, self).__init__(*args, **kwargs)
class VirtualWANPaged(Paged):
"""
A paging container for iterating over a list of :class:`VirtualWAN <azure.mgmt.network.v2018_12_01.models.VirtualWAN>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[VirtualWAN]'}
}
def __init__(self, *args, **kwargs):
super(VirtualWANPaged, self).__init__(*args, **kwargs)
class VpnSitePaged(Paged):
"""
A paging container for iterating over a list of :class:`VpnSite <azure.mgmt.network.v2018_12_01.models.VpnSite>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[VpnSite]'}
}
def __init__(self, *args, **kwargs):
super(VpnSitePaged, self).__init__(*args, **kwargs)
class VirtualHubPaged(Paged):
"""
A paging container for iterating over a list of :class:`VirtualHub <azure.mgmt.network.v2018_12_01.models.VirtualHub>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[VirtualHub]'}
}
def __init__(self, *args, **kwargs):
super(VirtualHubPaged, self).__init__(*args, **kwargs)
class HubVirtualNetworkConnectionPaged(Paged):
"""
A paging container for iterating over a list of :class:`HubVirtualNetworkConnection <azure.mgmt.network.v2018_12_01.models.HubVirtualNetworkConnection>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[HubVirtualNetworkConnection]'}
}
def __init__(self, *args, **kwargs):
super(HubVirtualNetworkConnectionPaged, self).__init__(*args, **kwargs)
class VpnGatewayPaged(Paged):
"""
A paging container for iterating over a list of :class:`VpnGateway <azure.mgmt.network.v2018_12_01.models.VpnGateway>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[VpnGateway]'}
}
def __init__(self, *args, **kwargs):
super(VpnGatewayPaged, self).__init__(*args, **kwargs)
class VpnConnectionPaged(Paged):
"""
A paging container for iterating over a list of :class:`VpnConnection <azure.mgmt.network.v2018_12_01.models.VpnConnection>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[VpnConnection]'}
}
def __init__(self, *args, **kwargs):
super(VpnConnectionPaged, self).__init__(*args, **kwargs)
class P2SVpnServerConfigurationPaged(Paged):
"""
A paging container for iterating over a list of :class:`P2SVpnServerConfiguration <azure.mgmt.network.v2018_12_01.models.P2SVpnServerConfiguration>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[P2SVpnServerConfiguration]'}
}
def __init__(self, *args, **kwargs):
super(P2SVpnServerConfigurationPaged, self).__init__(*args, **kwargs)
class P2SVpnGatewayPaged(Paged):
"""
A paging container for iterating over a list of :class:`P2SVpnGateway <azure.mgmt.network.v2018_12_01.models.P2SVpnGateway>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[P2SVpnGateway]'}
}
def __init__(self, *args, **kwargs):
super(P2SVpnGatewayPaged, self).__init__(*args, **kwargs)
class WebApplicationFirewallPolicyPaged(Paged):
"""
A paging container for iterating over a list of :class:`WebApplicationFirewallPolicy <azure.mgmt.network.v2018_12_01.models.WebApplicationFirewallPolicy>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[WebApplicationFirewallPolicy]'}
}
def __init__(self, *args, **kwargs):
super(WebApplicationFirewallPolicyPaged, self).__init__(*args, **kwargs)
| 36.823256
| 191
| 0.655962
|
b100138aefddba8738737c3b970841dcbba9b6a1
| 74
|
py
|
Python
|
Lib/site-packages/amf/Util/Body.py
|
raychorn/svn_Python-2.5.1
|
425005b1b489ba44ec0bb989e077297e8953d9be
|
[
"PSF-2.0"
] | null | null | null |
Lib/site-packages/amf/Util/Body.py
|
raychorn/svn_Python-2.5.1
|
425005b1b489ba44ec0bb989e077297e8953d9be
|
[
"PSF-2.0"
] | null | null | null |
Lib/site-packages/amf/Util/Body.py
|
raychorn/svn_Python-2.5.1
|
425005b1b489ba44ec0bb989e077297e8953d9be
|
[
"PSF-2.0"
] | null | null | null |
class Body:
target = ""
value = ""
response = ""
type = ""
| 14.8
| 17
| 0.432432
|
f9b144fa493902408cf2e346393a2e2b19decfc2
| 542
|
py
|
Python
|
abyssal_market/settings/local.template.py
|
kimnnmadsen/eve-abyssal-market
|
1e07498b98be9282b969badff51d55258c72e7ed
|
[
"MIT"
] | 13
|
2018-08-23T14:27:22.000Z
|
2020-12-07T12:35:38.000Z
|
abyssal_market/settings/local.template.py
|
kimnnmadsen/eve-abyssal-market
|
1e07498b98be9282b969badff51d55258c72e7ed
|
[
"MIT"
] | 25
|
2018-10-09T14:37:33.000Z
|
2020-05-15T20:21:48.000Z
|
abyssal_market/settings/local.template.py
|
kimnnmadsen/eve-abyssal-market
|
1e07498b98be9282b969badff51d55258c72e7ed
|
[
"MIT"
] | 4
|
2021-08-12T05:34:05.000Z
|
2022-01-06T05:28:36.000Z
|
# flake8: noqa
import os
from .base import *
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'dev'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
ESI_SWAGGER_JSON = "https://esi.tech.ccp.is/latest/swagger.json?datasource=tranquility"
ESI_CALLBACK = ""
ESI_CLIENT_ID = ""
ESI_SECRET_KEY = ""
ESI_USER_AGENT = ""
| 20.074074
| 87
| 0.684502
|
899d070414c57c1ac862f2ada05f62a0230ef8e3
| 2,704
|
py
|
Python
|
parlai/agents/drqa/config.py
|
zl930216/ParlAI
|
abf0ad6d1779af0f8ce0b5aed00d2bab71416684
|
[
"MIT"
] | 1
|
2021-03-03T12:22:38.000Z
|
2021-03-03T12:22:38.000Z
|
parlai/agents/drqa/config.py
|
zl930216/ParlAI
|
abf0ad6d1779af0f8ce0b5aed00d2bab71416684
|
[
"MIT"
] | 3
|
2021-09-08T03:20:02.000Z
|
2022-03-12T00:58:14.000Z
|
parlai/agents/drqa/config.py
|
zl930216/ParlAI
|
abf0ad6d1779af0f8ce0b5aed00d2bab71416684
|
[
"MIT"
] | 1
|
2020-09-05T20:25:13.000Z
|
2020-09-05T20:25:13.000Z
|
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from parlai.core.build_data import modelzoo_path
from parlai.utils.io import PathManager
def set_defaults(opt):
init_model = None
# check first for 'init_model' for loading model from file
if opt.get('init_model') and PathManager.exists(opt['init_model']):
init_model = opt['init_model']
# next check for 'model_file', this would override init_model
if opt.get('model_file') and PathManager.exists(opt['model_file']):
init_model = opt['model_file']
if init_model is None:
# Embeddings options
opt['embedding_file'] = modelzoo_path(
opt.get('datapath'), opt['embedding_file']
)
if opt.get('embedding_file'):
if not PathManager.exists(opt['embedding_file']):
raise IOError('No such file: %s' % opt['embedding_file'])
with PathManager.open(opt['embedding_file']) as f:
dim = len(f.readline().strip().split(' ')) - 1
if dim == 1:
# first line was a dud
dim = len(f.readline().strip().split(' ')) - 1
opt['embedding_dim'] = dim
elif not opt.get('embedding_dim'):
raise RuntimeError(
('Either embedding_file or embedding_dim ' 'needs to be specified.')
)
# Make sure tune_partial and fix_embeddings are consistent
if opt['tune_partial'] > 0 and opt['fix_embeddings']:
print('Setting fix_embeddings to False as tune_partial > 0.')
opt['fix_embeddings'] = False
# Make sure fix_embeddings and embedding_file are consistent
if opt['fix_embeddings'] and not opt.get('embedding_file'):
print('Setting fix_embeddings to False as embeddings are random.')
opt['fix_embeddings'] = False
def override_args(opt, override_opt):
# Major model args are reset to the values in override_opt.
# Non-architecture args (like dropout) are kept.
args = set(
[
'embedding_file',
'embedding_dim',
'hidden_size',
'doc_layers',
'question_layers',
'rnn_type',
'optimizer',
'concat_rnn_layers',
'question_merge',
'use_qemb',
'use_in_question',
'use_tf',
'vocab_size',
'num_features',
'use_time',
]
)
for k, v in override_opt.items():
if k in args:
opt[k] = v
| 36.540541
| 84
| 0.587278
|
4d0d5be2e081928b3f2fc7551a8b3e215b2dac67
| 6,665
|
py
|
Python
|
PhysicsTools/HeppyCore/python/statistics/tree.py
|
Purva-Chaudhari/cmssw
|
32e5cbfe54c4d809d60022586cf200b7c3020bcf
|
[
"Apache-2.0"
] | 852
|
2015-01-11T21:03:51.000Z
|
2022-03-25T21:14:00.000Z
|
PhysicsTools/HeppyCore/python/statistics/tree.py
|
Purva-Chaudhari/cmssw
|
32e5cbfe54c4d809d60022586cf200b7c3020bcf
|
[
"Apache-2.0"
] | 30,371
|
2015-01-02T00:14:40.000Z
|
2022-03-31T23:26:05.000Z
|
PhysicsTools/HeppyCore/python/statistics/tree.py
|
Purva-Chaudhari/cmssw
|
32e5cbfe54c4d809d60022586cf200b7c3020bcf
|
[
"Apache-2.0"
] | 3,240
|
2015-01-02T05:53:18.000Z
|
2022-03-31T17:24:21.000Z
|
import numpy
from ROOT import TTree
import ROOT
class Tree(object):
def __init__(self, name, title, defaultFloatType="D", defaultIntType="I"):
self.vars = {}
self.vecvars = {}
self.tree = TTree(name, title)
self.defaults = {}
self.vecdefaults = {}
self.defaultFloatType = defaultFloatType
self.defaultIntType = defaultIntType
self.fillers = {}
def setDefaultFloatType(self, defaultFloatType):
self.defaultFloatType = defaultFloatType
def setDefaultIntType(self, defaultIntType):
self.defaultIntType = defaultIntType
def copyStructure(self, tree):
for branch in tree.GetListOfBranches():
name = branch.GetName()
typeName = branch.GetListOfLeaves()[0].GetTypeName()
type = float
if typeName == 'Int_t':
type = int
self.var(name, type)
def branch_(self, selfmap, varName, type, len, postfix="", storageType="default", title=None):
"""Backend function used to create scalar and vector branches.
Users should call "var" and "vector", not this function directly."""
if storageType == "default":
storageType = self.defaultIntType if type is int else self.defaultFloatType
if type is float :
if storageType == "F":
selfmap[varName]=numpy.zeros(len,numpy.float32)
self.tree.Branch(varName,selfmap[varName],varName+postfix+'/F')
elif storageType == "D":
selfmap[varName]=numpy.zeros(len,numpy.float64)
self.tree.Branch(varName,selfmap[varName],varName+postfix+'/D')
else:
raise RuntimeError('Unknown storage type %s for branch %s' % (storageType, varName))
elif type is int:
dtypes = {
"i" : numpy.uint32,
"s" : numpy.uint16,
"b" : numpy.uint8,
"l" : numpy.uint64,
"I" : numpy.int32,
"S" : numpy.int16,
"B" : numpy.int8,
"L" : numpy.int64,
}
if storageType not in dtypes:
raise RuntimeError('Unknown storage type %s for branch %s' % (storageType, varName))
selfmap[varName]=numpy.zeros(len,dtypes[storageType])
self.tree.Branch(varName,selfmap[varName],varName+postfix+'/'+storageType)
else:
raise RuntimeError('Unknown type %s for branch %s' % (type, varName))
if title:
self.tree.GetBranch(varName).SetTitle(title)
def var(self, varName,type=float, default=-99, title=None, storageType="default", filler=None ):
if type in [int, float]:
self.branch_(self.vars, varName, type, 1, title=title, storageType=storageType)
self.defaults[varName] = default
elif __builtins__['type'](type) == str:
# create a value, looking up the type from ROOT and calling the default constructor
self.vars[varName] = getattr(ROOT,type)()
if type in [ "TLorentzVector" ]: # custom streamer classes
self.tree.Branch(varName+".", type, self.vars[varName], 8000,-1)
else:
self.tree.Branch(varName+".", type, self.vars[varName])
if filler is None:
raise RuntimeError("Error: when brancing with an object, filler should be set to a function that takes as argument an object instance and a value, and set the instance to the value (as otherwise python assignment of objects changes the address as well)")
self.fillers[varName] = filler
else:
raise RuntimeError('Unknown type %s for branch %s: it is not int, float or a string' % (type, varName))
self.defaults[varName] = default
def vector(self, varName, lenvar, maxlen=None, type=float, default=-99, title=None, storageType="default", filler=None ):
"""either lenvar is a string, and maxlen an int (variable size array), or lenvar is an int and maxlen is not specified (fixed array)"""
if type in [int, float]:
if __builtins__['type'](lenvar) == int: # need the __builtins__ since 'type' is a variable here :-/
self.branch_(self.vecvars, varName, type, lenvar, postfix="[%d]" % lenvar, title=title, storageType=storageType)
else:
if maxlen == None: RuntimeError, 'You must specify a maxlen if making a dynamic array';
self.branch_(self.vecvars, varName, type, maxlen, postfix="[%s]" % lenvar, title=title, storageType=storageType)
elif __builtins__['type'](type) == str:
self.vecvars[varName] = ROOT.TClonesArray(type,(lenvar if __builtins__['type'](lenvar) == int else maxlen))
if type in [ "TLorentzVector" ]: # custom streamer classes
self.tree.Branch(varName+".", self.vecvars[varName], 32000, -1)
else:
self.tree.Branch(varName+".", self.vecvars[varName])
if filler is None:
raise RuntimeError("Error: when brancing with an object, filler should be set to a function that takes as argument an object instance and a value, and set the instance to the value (as otherwise python assignment of objects changes the address as well)")
self.fillers[varName] = filler
self.vecdefaults[varName] = default
def reset(self):
for name,value in self.vars.items():
if name in self.fillers:
self.fillers[name](value, self.defaults[name])
else:
value[0]=self.defaults[name]
for name,value in self.vecvars.items():
if isinstance(value, numpy.ndarray):
value.fill(self.vecdefaults[name])
else:
if isinstance(value, ROOT.TObject) and value.ClassName() == "TClonesArray":
value.ExpandCreateFast(0)
def fill(self, varName, value ):
if isinstance(self.vars[varName], numpy.ndarray):
self.vars[varName][0]=value
else:
self.fillers[varName](self.vars[varName],value)
def vfill(self, varName, values ):
a = self.vecvars[varName]
if isinstance(a, numpy.ndarray):
for (i,v) in enumerate(values):
a[i]=v
else:
if isinstance(a, ROOT.TObject) and a.ClassName() == "TClonesArray":
a.ExpandCreateFast(len(values))
fillit = self.fillers[varName]
for (i,v) in enumerate(values):
fillit(a[i],v)
| 50.112782
| 270
| 0.593548
|
1cc9fac68b4d69ceb5ad2bb7cabb66cb74507105
| 1,189
|
py
|
Python
|
src/old/QtableEnemy.py
|
Blackdevil132/machineLearning
|
de048bb1473994052f8ed1afb11a15b7833b506d
|
[
"MIT"
] | 1
|
2019-05-04T07:28:19.000Z
|
2019-05-04T07:28:19.000Z
|
src/old/QtableEnemy.py
|
Blackdevil132/machineLearning
|
de048bb1473994052f8ed1afb11a15b7833b506d
|
[
"MIT"
] | 3
|
2019-04-29T09:20:11.000Z
|
2019-04-29T09:23:22.000Z
|
src/old/QtableEnemy.py
|
Blackdevil132/machineLearning
|
de048bb1473994052f8ed1afb11a15b7833b506d
|
[
"MIT"
] | null | null | null |
import numpy as np
from src.qrl.Qtable import Qtable
# Qtable for 2-dim storing
class QtableEnemy(Qtable):
def __init__(self, action_space, observation_space_1, observation_space_2):
Qtable.__init__(self)
self.action_space = action_space
self.observation_space = (observation_space_1, observation_space_2)
self.table = [{j: np.zeros(action_space) for j in range(observation_space_2)} for i in range(observation_space_1)]
for i in range(self.observation_space[0]):
self.table[i][255] = np.zeros(action_space)
def get(self, state, action=None):
if action is None:
return self.table[state[0]][state[1]][:]
return self.table[state[0]][state[1]][action]
def update(self, state, action, newValue):
self.table[state[0]][state[1]][action] = newValue
def show(self):
for dim1 in range(self.observation_space[0]):
print("%i " % dim1, end='')
for key in self.table[dim1].keys():
print("\t%i: " % key, end='')
for action in self.table[dim1][key]:
print("\t%.3f, " % action, end='')
print()
| 36.030303
| 122
| 0.607233
|
8667f9b304d57627c0fd801338b5bb68d7d4f426
| 21,872
|
py
|
Python
|
qa/rpc-tests/replace-by-fee.py
|
Plorark/KORE
|
35685f0a1ce898e883ba4c80e0c6de3c3535767d
|
[
"MIT"
] | null | null | null |
qa/rpc-tests/replace-by-fee.py
|
Plorark/KORE
|
35685f0a1ce898e883ba4c80e0c6de3c3535767d
|
[
"MIT"
] | null | null | null |
qa/rpc-tests/replace-by-fee.py
|
Plorark/KORE
|
35685f0a1ce898e883ba4c80e0c6de3c3535767d
|
[
"MIT"
] | 1
|
2018-04-16T17:11:15.000Z
|
2018-04-16T17:11:15.000Z
|
#!/usr/bin/env python3
# Copyright (c) 2014-2016 The Kore Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test replace by fee code
#
from test_framework.test_framework import KoreTestFramework
from test_framework.util import *
from test_framework.script import *
from test_framework.mininode import *
MAX_REPLACEMENT_LIMIT = 100
def txToHex(tx):
return bytes_to_hex_str(tx.serialize())
def make_utxo(node, amount, confirmed=True, scriptPubKey=CScript([1])):
"""Create a txout with a given amount and scriptPubKey
Mines coins as needed.
confirmed - txouts created will be confirmed in the blockchain;
unconfirmed otherwise.
"""
fee = 1*COIN
while node.getbalance() < satoshi_round((amount + fee)/COIN):
node.generate(100)
#print (node.getbalance(), amount, fee)
new_addr = node.getnewaddress()
#print new_addr
txid = node.sendtoaddress(new_addr, satoshi_round((amount+fee)/COIN))
tx1 = node.getrawtransaction(txid, 1)
txid = int(txid, 16)
i = None
for i, txout in enumerate(tx1['vout']):
#print i, txout['scriptPubKey']['addresses']
if txout['scriptPubKey']['addresses'] == [new_addr]:
#print i
break
assert i is not None
tx2 = CTransaction()
tx2.vin = [CTxIn(COutPoint(txid, i))]
tx2.vout = [CTxOut(amount, scriptPubKey)]
tx2.rehash()
signed_tx = node.signrawtransaction(txToHex(tx2))
txid = node.sendrawtransaction(signed_tx['hex'], True)
# If requested, ensure txouts are confirmed.
if confirmed:
mempool_size = len(node.getrawmempool())
while mempool_size > 0:
node.generate(1)
new_size = len(node.getrawmempool())
# Error out if we have something stuck in the mempool, as this
# would likely be a bug.
assert(new_size < mempool_size)
mempool_size = new_size
return COutPoint(int(txid, 16), 0)
class ReplaceByFeeTest(KoreTestFramework):
def setup_network(self):
self.nodes = []
self.nodes.append(start_node(0, self.options.tmpdir, ["-maxorphantx=1000", "-debug",
"-relaypriority=0", "-whitelist=127.0.0.1",
"-limitancestorcount=50",
"-limitancestorsize=101",
"-limitdescendantcount=200",
"-limitdescendantsize=101"
]))
self.is_network_split = False
def run_test(self):
make_utxo(self.nodes[0], 1*COIN)
print("Running test simple doublespend...")
self.test_simple_doublespend()
print("Running test doublespend chain...")
self.test_doublespend_chain()
print("Running test doublespend tree...")
self.test_doublespend_tree()
print("Running test replacement feeperkb...")
self.test_replacement_feeperkb()
print("Running test spends of conflicting outputs...")
self.test_spends_of_conflicting_outputs()
print("Running test new unconfirmed inputs...")
self.test_new_unconfirmed_inputs()
print("Running test too many replacements...")
self.test_too_many_replacements()
print("Running test opt-in...")
self.test_opt_in()
print("Running test prioritised transactions...")
self.test_prioritised_transactions()
print("Passed\n")
def test_simple_doublespend(self):
"""Simple doublespend"""
tx0_outpoint = make_utxo(self.nodes[0], int(1.1*COIN))
tx1a = CTransaction()
tx1a.vin = [CTxIn(tx0_outpoint, nSequence=0)]
tx1a.vout = [CTxOut(1*COIN, CScript([b'a']))]
tx1a_hex = txToHex(tx1a)
tx1a_txid = self.nodes[0].sendrawtransaction(tx1a_hex, True)
# Should fail because we haven't changed the fee
tx1b = CTransaction()
tx1b.vin = [CTxIn(tx0_outpoint, nSequence=0)]
tx1b.vout = [CTxOut(1*COIN, CScript([b'b']))]
tx1b_hex = txToHex(tx1b)
try:
tx1b_txid = self.nodes[0].sendrawtransaction(tx1b_hex, True)
except JSONRPCException as exp:
assert_equal(exp.error['code'], -26) # insufficient fee
else:
assert(False)
# Extra 0.1 BTC fee
tx1b = CTransaction()
tx1b.vin = [CTxIn(tx0_outpoint, nSequence=0)]
tx1b.vout = [CTxOut(int(0.9*COIN), CScript([b'b']))]
tx1b_hex = txToHex(tx1b)
tx1b_txid = self.nodes[0].sendrawtransaction(tx1b_hex, True)
mempool = self.nodes[0].getrawmempool()
assert (tx1a_txid not in mempool)
assert (tx1b_txid in mempool)
assert_equal(tx1b_hex, self.nodes[0].getrawtransaction(tx1b_txid))
def test_doublespend_chain(self):
"""Doublespend of a long chain"""
initial_nValue = 50*COIN
tx0_outpoint = make_utxo(self.nodes[0], initial_nValue)
prevout = tx0_outpoint
remaining_value = initial_nValue
chain_txids = []
while remaining_value > 10*COIN:
remaining_value -= 1*COIN
tx = CTransaction()
tx.vin = [CTxIn(prevout, nSequence=0)]
tx.vout = [CTxOut(remaining_value, CScript([1]))]
tx_hex = txToHex(tx)
txid = self.nodes[0].sendrawtransaction(tx_hex, True)
chain_txids.append(txid)
prevout = COutPoint(int(txid, 16), 0)
# Whether the double-spend is allowed is evaluated by including all
# child fees - 40 BTC - so this attempt is rejected.
dbl_tx = CTransaction()
dbl_tx.vin = [CTxIn(tx0_outpoint, nSequence=0)]
dbl_tx.vout = [CTxOut(initial_nValue - 30*COIN, CScript([1]))]
dbl_tx_hex = txToHex(dbl_tx)
try:
self.nodes[0].sendrawtransaction(dbl_tx_hex, True)
except JSONRPCException as exp:
assert_equal(exp.error['code'], -26) # insufficient fee
else:
assert(False) # transaction mistakenly accepted!
# Accepted with sufficient fee
dbl_tx = CTransaction()
dbl_tx.vin = [CTxIn(tx0_outpoint, nSequence=0)]
dbl_tx.vout = [CTxOut(1*COIN, CScript([1]))]
dbl_tx_hex = txToHex(dbl_tx)
self.nodes[0].sendrawtransaction(dbl_tx_hex, True)
mempool = self.nodes[0].getrawmempool()
for doublespent_txid in chain_txids:
assert(doublespent_txid not in mempool)
def test_doublespend_tree(self):
"""Doublespend of a big tree of transactions"""
initial_nValue = 50*COIN
tx0_outpoint = make_utxo(self.nodes[0], initial_nValue)
def branch(prevout, initial_value, max_txs, tree_width=5, fee=0.0001*COIN, _total_txs=None):
if _total_txs is None:
_total_txs = [0]
if _total_txs[0] >= max_txs:
return
txout_value = (initial_value - fee) // tree_width
if txout_value < fee:
return
vout = [CTxOut(txout_value, CScript([i+1]))
for i in range(tree_width)]
tx = CTransaction()
tx.vin = [CTxIn(prevout, nSequence=0)]
tx.vout = vout
tx_hex = txToHex(tx)
assert(len(tx.serialize()) < 100000)
txid = self.nodes[0].sendrawtransaction(tx_hex, True)
yield tx
_total_txs[0] += 1
txid = int(txid, 16)
for i, txout in enumerate(tx.vout):
for x in branch(COutPoint(txid, i), txout_value,
max_txs,
tree_width=tree_width, fee=fee,
_total_txs=_total_txs):
yield x
fee = int(0.0001*COIN)
n = MAX_REPLACEMENT_LIMIT
tree_txs = list(branch(tx0_outpoint, initial_nValue, n, fee=fee))
assert_equal(len(tree_txs), n)
# Attempt double-spend, will fail because too little fee paid
dbl_tx = CTransaction()
dbl_tx.vin = [CTxIn(tx0_outpoint, nSequence=0)]
dbl_tx.vout = [CTxOut(initial_nValue - fee*n, CScript([1]))]
dbl_tx_hex = txToHex(dbl_tx)
try:
self.nodes[0].sendrawtransaction(dbl_tx_hex, True)
except JSONRPCException as exp:
assert_equal(exp.error['code'], -26) # insufficient fee
else:
assert(False)
# 1 BTC fee is enough
dbl_tx = CTransaction()
dbl_tx.vin = [CTxIn(tx0_outpoint, nSequence=0)]
dbl_tx.vout = [CTxOut(initial_nValue - fee*n - 1*COIN, CScript([1]))]
dbl_tx_hex = txToHex(dbl_tx)
self.nodes[0].sendrawtransaction(dbl_tx_hex, True)
mempool = self.nodes[0].getrawmempool()
for tx in tree_txs:
tx.rehash()
assert (tx.hash not in mempool)
# Try again, but with more total transactions than the "max txs
# double-spent at once" anti-DoS limit.
for n in (MAX_REPLACEMENT_LIMIT+1, MAX_REPLACEMENT_LIMIT*2):
fee = int(0.0001*COIN)
tx0_outpoint = make_utxo(self.nodes[0], initial_nValue)
tree_txs = list(branch(tx0_outpoint, initial_nValue, n, fee=fee))
assert_equal(len(tree_txs), n)
dbl_tx = CTransaction()
dbl_tx.vin = [CTxIn(tx0_outpoint, nSequence=0)]
dbl_tx.vout = [CTxOut(initial_nValue - 2*fee*n, CScript([1]))]
dbl_tx_hex = txToHex(dbl_tx)
try:
self.nodes[0].sendrawtransaction(dbl_tx_hex, True)
except JSONRPCException as exp:
assert_equal(exp.error['code'], -26)
assert_equal("too many potential replacements" in exp.error['message'], True)
else:
assert(False)
for tx in tree_txs:
tx.rehash()
self.nodes[0].getrawtransaction(tx.hash)
def test_replacement_feeperkb(self):
"""Replacement requires fee-per-KB to be higher"""
tx0_outpoint = make_utxo(self.nodes[0], int(1.1*COIN))
tx1a = CTransaction()
tx1a.vin = [CTxIn(tx0_outpoint, nSequence=0)]
tx1a.vout = [CTxOut(1*COIN, CScript([b'a']))]
tx1a_hex = txToHex(tx1a)
tx1a_txid = self.nodes[0].sendrawtransaction(tx1a_hex, True)
# Higher fee, but the fee per KB is much lower, so the replacement is
# rejected.
tx1b = CTransaction()
tx1b.vin = [CTxIn(tx0_outpoint, nSequence=0)]
tx1b.vout = [CTxOut(int(0.001*COIN), CScript([b'a'*999000]))]
tx1b_hex = txToHex(tx1b)
try:
tx1b_txid = self.nodes[0].sendrawtransaction(tx1b_hex, True)
except JSONRPCException as exp:
assert_equal(exp.error['code'], -26) # insufficient fee
else:
assert(False)
def test_spends_of_conflicting_outputs(self):
"""Replacements that spend conflicting tx outputs are rejected"""
utxo1 = make_utxo(self.nodes[0], int(1.2*COIN))
utxo2 = make_utxo(self.nodes[0], 3*COIN)
tx1a = CTransaction()
tx1a.vin = [CTxIn(utxo1, nSequence=0)]
tx1a.vout = [CTxOut(int(1.1*COIN), CScript([b'a']))]
tx1a_hex = txToHex(tx1a)
tx1a_txid = self.nodes[0].sendrawtransaction(tx1a_hex, True)
tx1a_txid = int(tx1a_txid, 16)
# Direct spend an output of the transaction we're replacing.
tx2 = CTransaction()
tx2.vin = [CTxIn(utxo1, nSequence=0), CTxIn(utxo2, nSequence=0)]
tx2.vin.append(CTxIn(COutPoint(tx1a_txid, 0), nSequence=0))
tx2.vout = tx1a.vout
tx2_hex = txToHex(tx2)
try:
tx2_txid = self.nodes[0].sendrawtransaction(tx2_hex, True)
except JSONRPCException as exp:
assert_equal(exp.error['code'], -26)
else:
assert(False)
# Spend tx1a's output to test the indirect case.
tx1b = CTransaction()
tx1b.vin = [CTxIn(COutPoint(tx1a_txid, 0), nSequence=0)]
tx1b.vout = [CTxOut(1*COIN, CScript([b'a']))]
tx1b_hex = txToHex(tx1b)
tx1b_txid = self.nodes[0].sendrawtransaction(tx1b_hex, True)
tx1b_txid = int(tx1b_txid, 16)
tx2 = CTransaction()
tx2.vin = [CTxIn(utxo1, nSequence=0), CTxIn(utxo2, nSequence=0),
CTxIn(COutPoint(tx1b_txid, 0))]
tx2.vout = tx1a.vout
tx2_hex = txToHex(tx2)
try:
tx2_txid = self.nodes[0].sendrawtransaction(tx2_hex, True)
except JSONRPCException as exp:
assert_equal(exp.error['code'], -26)
else:
assert(False)
def test_new_unconfirmed_inputs(self):
"""Replacements that add new unconfirmed inputs are rejected"""
confirmed_utxo = make_utxo(self.nodes[0], int(1.1*COIN))
unconfirmed_utxo = make_utxo(self.nodes[0], int(0.1*COIN), False)
tx1 = CTransaction()
tx1.vin = [CTxIn(confirmed_utxo)]
tx1.vout = [CTxOut(1*COIN, CScript([b'a']))]
tx1_hex = txToHex(tx1)
tx1_txid = self.nodes[0].sendrawtransaction(tx1_hex, True)
tx2 = CTransaction()
tx2.vin = [CTxIn(confirmed_utxo), CTxIn(unconfirmed_utxo)]
tx2.vout = tx1.vout
tx2_hex = txToHex(tx2)
try:
tx2_txid = self.nodes[0].sendrawtransaction(tx2_hex, True)
except JSONRPCException as exp:
assert_equal(exp.error['code'], -26)
else:
assert(False)
def test_too_many_replacements(self):
"""Replacements that evict too many transactions are rejected"""
# Try directly replacing more than MAX_REPLACEMENT_LIMIT
# transactions
# Start by creating a single transaction with many outputs
initial_nValue = 10*COIN
utxo = make_utxo(self.nodes[0], initial_nValue)
fee = int(0.0001*COIN)
split_value = int((initial_nValue-fee)/(MAX_REPLACEMENT_LIMIT+1))
actual_fee = initial_nValue - split_value*(MAX_REPLACEMENT_LIMIT+1)
outputs = []
for i in range(MAX_REPLACEMENT_LIMIT+1):
outputs.append(CTxOut(split_value, CScript([1])))
splitting_tx = CTransaction()
splitting_tx.vin = [CTxIn(utxo, nSequence=0)]
splitting_tx.vout = outputs
splitting_tx_hex = txToHex(splitting_tx)
txid = self.nodes[0].sendrawtransaction(splitting_tx_hex, True)
txid = int(txid, 16)
# Now spend each of those outputs individually
for i in range(MAX_REPLACEMENT_LIMIT+1):
tx_i = CTransaction()
tx_i.vin = [CTxIn(COutPoint(txid, i), nSequence=0)]
tx_i.vout = [CTxOut(split_value-fee, CScript([b'a']))]
tx_i_hex = txToHex(tx_i)
self.nodes[0].sendrawtransaction(tx_i_hex, True)
# Now create doublespend of the whole lot; should fail.
# Need a big enough fee to cover all spending transactions and have
# a higher fee rate
double_spend_value = (split_value-100*fee)*(MAX_REPLACEMENT_LIMIT+1)
inputs = []
for i in range(MAX_REPLACEMENT_LIMIT+1):
inputs.append(CTxIn(COutPoint(txid, i), nSequence=0))
double_tx = CTransaction()
double_tx.vin = inputs
double_tx.vout = [CTxOut(double_spend_value, CScript([b'a']))]
double_tx_hex = txToHex(double_tx)
try:
self.nodes[0].sendrawtransaction(double_tx_hex, True)
except JSONRPCException as exp:
assert_equal(exp.error['code'], -26)
assert_equal("too many potential replacements" in exp.error['message'], True)
else:
assert(False)
# If we remove an input, it should pass
double_tx = CTransaction()
double_tx.vin = inputs[0:-1]
double_tx.vout = [CTxOut(double_spend_value, CScript([b'a']))]
double_tx_hex = txToHex(double_tx)
self.nodes[0].sendrawtransaction(double_tx_hex, True)
def test_opt_in(self):
""" Replacing should only work if orig tx opted in """
tx0_outpoint = make_utxo(self.nodes[0], int(1.1*COIN))
# Create a non-opting in transaction
tx1a = CTransaction()
tx1a.vin = [CTxIn(tx0_outpoint, nSequence=0xffffffff)]
tx1a.vout = [CTxOut(1*COIN, CScript([b'a']))]
tx1a_hex = txToHex(tx1a)
tx1a_txid = self.nodes[0].sendrawtransaction(tx1a_hex, True)
# Shouldn't be able to double-spend
tx1b = CTransaction()
tx1b.vin = [CTxIn(tx0_outpoint, nSequence=0)]
tx1b.vout = [CTxOut(int(0.9*COIN), CScript([b'b']))]
tx1b_hex = txToHex(tx1b)
try:
tx1b_txid = self.nodes[0].sendrawtransaction(tx1b_hex, True)
except JSONRPCException as exp:
assert_equal(exp.error['code'], -26)
else:
print(tx1b_txid)
assert(False)
tx1_outpoint = make_utxo(self.nodes[0], int(1.1*COIN))
# Create a different non-opting in transaction
tx2a = CTransaction()
tx2a.vin = [CTxIn(tx1_outpoint, nSequence=0xfffffffe)]
tx2a.vout = [CTxOut(1*COIN, CScript([b'a']))]
tx2a_hex = txToHex(tx2a)
tx2a_txid = self.nodes[0].sendrawtransaction(tx2a_hex, True)
# Still shouldn't be able to double-spend
tx2b = CTransaction()
tx2b.vin = [CTxIn(tx1_outpoint, nSequence=0)]
tx2b.vout = [CTxOut(int(0.9*COIN), CScript([b'b']))]
tx2b_hex = txToHex(tx2b)
try:
tx2b_txid = self.nodes[0].sendrawtransaction(tx2b_hex, True)
except JSONRPCException as exp:
assert_equal(exp.error['code'], -26)
else:
assert(False)
# Now create a new transaction that spends from tx1a and tx2a
# opt-in on one of the inputs
# Transaction should be replaceable on either input
tx1a_txid = int(tx1a_txid, 16)
tx2a_txid = int(tx2a_txid, 16)
tx3a = CTransaction()
tx3a.vin = [CTxIn(COutPoint(tx1a_txid, 0), nSequence=0xffffffff),
CTxIn(COutPoint(tx2a_txid, 0), nSequence=0xfffffffd)]
tx3a.vout = [CTxOut(int(0.9*COIN), CScript([b'c'])), CTxOut(int(0.9*COIN), CScript([b'd']))]
tx3a_hex = txToHex(tx3a)
self.nodes[0].sendrawtransaction(tx3a_hex, True)
tx3b = CTransaction()
tx3b.vin = [CTxIn(COutPoint(tx1a_txid, 0), nSequence=0)]
tx3b.vout = [CTxOut(int(0.5*COIN), CScript([b'e']))]
tx3b_hex = txToHex(tx3b)
tx3c = CTransaction()
tx3c.vin = [CTxIn(COutPoint(tx2a_txid, 0), nSequence=0)]
tx3c.vout = [CTxOut(int(0.5*COIN), CScript([b'f']))]
tx3c_hex = txToHex(tx3c)
self.nodes[0].sendrawtransaction(tx3b_hex, True)
# If tx3b was accepted, tx3c won't look like a replacement,
# but make sure it is accepted anyway
self.nodes[0].sendrawtransaction(tx3c_hex, True)
def test_prioritised_transactions(self):
# Ensure that fee deltas used via prioritisetransaction are
# correctly used by replacement logic
# 1. Check that feeperkb uses modified fees
tx0_outpoint = make_utxo(self.nodes[0], int(1.1*COIN))
tx1a = CTransaction()
tx1a.vin = [CTxIn(tx0_outpoint, nSequence=0)]
tx1a.vout = [CTxOut(1*COIN, CScript([b'a']))]
tx1a_hex = txToHex(tx1a)
tx1a_txid = self.nodes[0].sendrawtransaction(tx1a_hex, True)
# Higher fee, but the actual fee per KB is much lower.
tx1b = CTransaction()
tx1b.vin = [CTxIn(tx0_outpoint, nSequence=0)]
tx1b.vout = [CTxOut(int(0.001*COIN), CScript([b'a'*740000]))]
tx1b_hex = txToHex(tx1b)
# Verify tx1b cannot replace tx1a.
try:
tx1b_txid = self.nodes[0].sendrawtransaction(tx1b_hex, True)
except JSONRPCException as exp:
assert_equal(exp.error['code'], -26)
else:
assert(False)
# Use prioritisetransaction to set tx1a's fee to 0.
self.nodes[0].prioritisetransaction(tx1a_txid, 0, int(-0.1*COIN))
# Now tx1b should be able to replace tx1a
tx1b_txid = self.nodes[0].sendrawtransaction(tx1b_hex, True)
assert(tx1b_txid in self.nodes[0].getrawmempool())
# 2. Check that absolute fee checks use modified fee.
tx1_outpoint = make_utxo(self.nodes[0], int(1.1*COIN))
tx2a = CTransaction()
tx2a.vin = [CTxIn(tx1_outpoint, nSequence=0)]
tx2a.vout = [CTxOut(1*COIN, CScript([b'a']))]
tx2a_hex = txToHex(tx2a)
tx2a_txid = self.nodes[0].sendrawtransaction(tx2a_hex, True)
# Lower fee, but we'll prioritise it
tx2b = CTransaction()
tx2b.vin = [CTxIn(tx1_outpoint, nSequence=0)]
tx2b.vout = [CTxOut(int(1.01*COIN), CScript([b'a']))]
tx2b.rehash()
tx2b_hex = txToHex(tx2b)
# Verify tx2b cannot replace tx2a.
try:
tx2b_txid = self.nodes[0].sendrawtransaction(tx2b_hex, True)
except JSONRPCException as exp:
assert_equal(exp.error['code'], -26)
else:
assert(False)
# Now prioritise tx2b to have a higher modified fee
self.nodes[0].prioritisetransaction(tx2b.hash, 0, int(0.1*COIN))
# tx2b should now be accepted
tx2b_txid = self.nodes[0].sendrawtransaction(tx2b_hex, True)
assert(tx2b_txid in self.nodes[0].getrawmempool())
if __name__ == '__main__':
ReplaceByFeeTest().main()
| 37.324232
| 105
| 0.600951
|
bbe3ef9331a19b1f71353c011f5d3db2ff57a4a6
| 904
|
py
|
Python
|
test/test_potrace.py
|
beesandbombs/coldtype
|
d02c7dd36bf1576fa37dc8c50d5c1a6e47b1c5ea
|
[
"Apache-2.0"
] | 1
|
2021-04-04T15:25:06.000Z
|
2021-04-04T15:25:06.000Z
|
test/test_potrace.py
|
beesandbombs/coldtype
|
d02c7dd36bf1576fa37dc8c50d5c1a6e47b1c5ea
|
[
"Apache-2.0"
] | null | null | null |
test/test_potrace.py
|
beesandbombs/coldtype
|
d02c7dd36bf1576fa37dc8c50d5c1a6e47b1c5ea
|
[
"Apache-2.0"
] | null | null | null |
from coldtype import *
import coldtype.filtering as fl
import skia
co = Font.Cacheable("assets/ColdtypeObviously-VF.ttf")
@animation(bg=bw(0), storyboard=[0], timeline=Timeline(30))
def render(f):
raw = (StyledString("COLD",
Style(co, 700, wdth=0.5, tu=-155*f.a.progress(f.i).e, r=1, ro=1, rotate=10))
.pens()
.align(f.a.r)
.f(1))
letter = (raw
.copy()
.precompose(f.a.r)
.attr(skp=dict(
ImageFilter=skia.BlurImageFilter.Make(10, 10),
ColorFilter=skia.LumaColorFilter.Make()
))
.precompose(f.a.r)
.attr(skp=dict(
ColorFilter=fl.compose(
fl.as_filter(fl.contrast_cut(250, 3)),
fl.fill(bw(1)),
))))
return [
(letter.copy()
.potrace(f.a.r, ["-O", 1])
.f(Gradient.Vertical(f.a.r, hsl(0.5), hsl(0.7))))]
| 30.133333
| 84
| 0.530973
|
06999b312202850f61a989a61ef33197bce7f733
| 560
|
py
|
Python
|
src/models/user.py
|
ramasubbaiya/flask-api-starter-kit
|
3f00769f349908ffa5ccc7acb332d70e1f2c6f6f
|
[
"MIT"
] | 393
|
2016-11-21T10:52:01.000Z
|
2022-03-28T13:37:27.000Z
|
src/models/user.py
|
trenchmortar/flask-api-starter-kit
|
4a9bcbb37c4e81aacf2aef2df4ed28e8662e6d07
|
[
"MIT"
] | 10
|
2019-09-04T03:43:35.000Z
|
2019-09-11T06:35:22.000Z
|
src/models/user.py
|
trenchmortar/flask-api-starter-kit
|
4a9bcbb37c4e81aacf2aef2df4ed28e8662e6d07
|
[
"MIT"
] | 127
|
2017-04-20T11:33:00.000Z
|
2022-03-28T06:28:44.000Z
|
"""
Define the User model
"""
from . import db
from .abc import BaseModel, MetaBaseModel
class User(db.Model, BaseModel, metaclass=MetaBaseModel):
""" The User model """
__tablename__ = "user"
first_name = db.Column(db.String(300), primary_key=True)
last_name = db.Column(db.String(300), primary_key=True)
age = db.Column(db.Integer, nullable=True)
def __init__(self, first_name, last_name, age=None):
""" Create a new User """
self.first_name = first_name
self.last_name = last_name
self.age = age
| 25.454545
| 60
| 0.6625
|
620c5515d62a7d90d4b6d68bc6c02f9b3a4d6ae2
| 416
|
py
|
Python
|
scripts/dev/metrics-filter.py
|
braveheart12/insolar-31-08-19
|
0e58bb01fa38faee3205d0bdedc6a3cfb82d778f
|
[
"Apache-2.0"
] | null | null | null |
scripts/dev/metrics-filter.py
|
braveheart12/insolar-31-08-19
|
0e58bb01fa38faee3205d0bdedc6a3cfb82d778f
|
[
"Apache-2.0"
] | null | null | null |
scripts/dev/metrics-filter.py
|
braveheart12/insolar-31-08-19
|
0e58bb01fa38faee3205d0bdedc6a3cfb82d778f
|
[
"Apache-2.0"
] | null | null | null |
#!/usr/bin/env python3
import csv
import sys
seen = {}
with open(sys.argv[1], 'r') if len(sys.argv) > 1 else sys.stdin as f:
csv_in = csv.DictReader(f)
csv_out = csv.DictWriter(sys.stdout, fieldnames=csv_in.fieldnames)
csv_out.writeheader()
for row in csv_in:
if seen.get(row['name']):
continue
# print(row)
seen[row['name']] = True
csv_out.writerow(row)
| 26
| 70
| 0.612981
|
ccce59e754c87bca2370b61ad3a565b76db9e241
| 8,144
|
py
|
Python
|
tests/components/test_ffmpeg.py
|
lupin-de-mid/home-assistant
|
35f6dbc9dc0fb12d1d04837acbf09dabb325f4fe
|
[
"Apache-2.0"
] | 1
|
2021-01-02T14:13:46.000Z
|
2021-01-02T14:13:46.000Z
|
tests/components/test_ffmpeg.py
|
lupin-de-mid/home-assistant
|
35f6dbc9dc0fb12d1d04837acbf09dabb325f4fe
|
[
"Apache-2.0"
] | null | null | null |
tests/components/test_ffmpeg.py
|
lupin-de-mid/home-assistant
|
35f6dbc9dc0fb12d1d04837acbf09dabb325f4fe
|
[
"Apache-2.0"
] | null | null | null |
"""The tests for Home Assistant ffmpeg."""
import asyncio
from unittest.mock import patch, MagicMock
import homeassistant.components.ffmpeg as ffmpeg
from homeassistant.bootstrap import setup_component
from homeassistant.util.async import (
run_callback_threadsafe, run_coroutine_threadsafe)
from tests.common import (
get_test_home_assistant, assert_setup_component, mock_coro)
class MockFFmpegDev(ffmpeg.FFmpegBase):
"""FFmpeg device mock."""
def __init__(self, initial_state=True, entity_id='test.ffmpeg_device'):
"""Initialize mock."""
super().__init__(initial_state)
self.entity_id = entity_id
self.ffmpeg = MagicMock
self.called_stop = False
self.called_start = False
self.called_restart = False
@asyncio.coroutine
def async_start_ffmpeg(self):
"""Mock start."""
self.called_start = True
@asyncio.coroutine
def async_stop_ffmpeg(self):
"""Mock stop."""
self.called_stop = True
@asyncio.coroutine
def async_restart_ffmpeg(self):
"""Mock restart."""
self.called_restart = True
class TestFFmpegSetup(object):
"""Test class for ffmpeg."""
def setup_method(self):
"""Setup things to be run when tests are started."""
self.hass = get_test_home_assistant()
def teardown_method(self):
"""Stop everything that was started."""
self.hass.stop()
def test_setup_component(self):
"""Setup ffmpeg component."""
with assert_setup_component(2):
setup_component(self.hass, ffmpeg.DOMAIN, {ffmpeg.DOMAIN: {}})
assert self.hass.data[ffmpeg.DATA_FFMPEG].binary == 'ffmpeg'
def test_setup_component_test_service(self):
"""Setup ffmpeg component test services."""
with assert_setup_component(2):
setup_component(self.hass, ffmpeg.DOMAIN, {ffmpeg.DOMAIN: {}})
assert self.hass.services.has_service(ffmpeg.DOMAIN, 'start')
assert self.hass.services.has_service(ffmpeg.DOMAIN, 'stop')
assert self.hass.services.has_service(ffmpeg.DOMAIN, 'restart')
def test_setup_component_test_register(self):
"""Setup ffmpeg component test register."""
with assert_setup_component(2):
setup_component(self.hass, ffmpeg.DOMAIN, {ffmpeg.DOMAIN: {}})
self.hass.bus.async_listen_once = MagicMock()
ffmpeg_dev = MockFFmpegDev()
manager = self.hass.data[ffmpeg.DATA_FFMPEG]
run_callback_threadsafe(
self.hass.loop, manager.async_register_device, ffmpeg_dev).result()
assert self.hass.bus.async_listen_once.called
assert self.hass.bus.async_listen_once.call_count == 2
assert len(manager.entities) == 1
assert manager.entities[0] == ffmpeg_dev
def test_setup_component_test_register_no_startup(self):
"""Setup ffmpeg component test register without startup."""
with assert_setup_component(2):
setup_component(self.hass, ffmpeg.DOMAIN, {ffmpeg.DOMAIN: {}})
self.hass.bus.async_listen_once = MagicMock()
ffmpeg_dev = MockFFmpegDev(False)
manager = self.hass.data[ffmpeg.DATA_FFMPEG]
run_callback_threadsafe(
self.hass.loop, manager.async_register_device, ffmpeg_dev).result()
assert self.hass.bus.async_listen_once.called
assert self.hass.bus.async_listen_once.call_count == 1
assert len(manager.entities) == 1
assert manager.entities[0] == ffmpeg_dev
def test_setup_component_test_servcie_start(self):
"""Setup ffmpeg component test service start."""
with assert_setup_component(2):
setup_component(self.hass, ffmpeg.DOMAIN, {ffmpeg.DOMAIN: {}})
ffmpeg_dev = MockFFmpegDev(False)
manager = self.hass.data[ffmpeg.DATA_FFMPEG]
run_callback_threadsafe(
self.hass.loop, manager.async_register_device, ffmpeg_dev).result()
ffmpeg.start(self.hass)
self.hass.block_till_done()
assert ffmpeg_dev.called_start
def test_setup_component_test_servcie_stop(self):
"""Setup ffmpeg component test service stop."""
with assert_setup_component(2):
setup_component(self.hass, ffmpeg.DOMAIN, {ffmpeg.DOMAIN: {}})
ffmpeg_dev = MockFFmpegDev(False)
manager = self.hass.data[ffmpeg.DATA_FFMPEG]
run_callback_threadsafe(
self.hass.loop, manager.async_register_device, ffmpeg_dev).result()
ffmpeg.stop(self.hass)
self.hass.block_till_done()
assert ffmpeg_dev.called_stop
def test_setup_component_test_servcie_restart(self):
"""Setup ffmpeg component test service restart."""
with assert_setup_component(2):
setup_component(self.hass, ffmpeg.DOMAIN, {ffmpeg.DOMAIN: {}})
ffmpeg_dev = MockFFmpegDev(False)
manager = self.hass.data[ffmpeg.DATA_FFMPEG]
run_callback_threadsafe(
self.hass.loop, manager.async_register_device, ffmpeg_dev).result()
ffmpeg.restart(self.hass)
self.hass.block_till_done()
assert ffmpeg_dev.called_restart
def test_setup_component_test_servcie_start_with_entity(self):
"""Setup ffmpeg component test service start."""
with assert_setup_component(2):
setup_component(self.hass, ffmpeg.DOMAIN, {ffmpeg.DOMAIN: {}})
ffmpeg_dev = MockFFmpegDev(False)
manager = self.hass.data[ffmpeg.DATA_FFMPEG]
run_callback_threadsafe(
self.hass.loop, manager.async_register_device, ffmpeg_dev).result()
ffmpeg.start(self.hass, 'test.ffmpeg_device')
self.hass.block_till_done()
assert ffmpeg_dev.called_start
def test_setup_component_test_run_test_false(self):
"""Setup ffmpeg component test run_test false."""
with assert_setup_component(2):
setup_component(self.hass, ffmpeg.DOMAIN, {ffmpeg.DOMAIN: {
'run_test': False,
}})
manager = self.hass.data[ffmpeg.DATA_FFMPEG]
assert run_coroutine_threadsafe(
manager.async_run_test("blabalblabla"), self.hass.loop).result()
assert len(manager._cache) == 0
@patch('haffmpeg.Test.run_test',
return_value=mock_coro(return_value=True)())
def test_setup_component_test_run_test(self, mock_test):
"""Setup ffmpeg component test run_test."""
with assert_setup_component(2):
setup_component(self.hass, ffmpeg.DOMAIN, {ffmpeg.DOMAIN: {}})
manager = self.hass.data[ffmpeg.DATA_FFMPEG]
assert run_coroutine_threadsafe(
manager.async_run_test("blabalblabla"), self.hass.loop).result()
assert mock_test.called
assert mock_test.call_count == 1
assert len(manager._cache) == 1
assert manager._cache['blabalblabla']
assert run_coroutine_threadsafe(
manager.async_run_test("blabalblabla"), self.hass.loop).result()
assert mock_test.called
assert mock_test.call_count == 1
assert len(manager._cache) == 1
assert manager._cache['blabalblabla']
@patch('haffmpeg.Test.run_test',
return_value=mock_coro(return_value=False)())
def test_setup_component_test_run_test_test_fail(self, mock_test):
"""Setup ffmpeg component test run_test."""
with assert_setup_component(2):
setup_component(self.hass, ffmpeg.DOMAIN, {ffmpeg.DOMAIN: {}})
manager = self.hass.data[ffmpeg.DATA_FFMPEG]
assert not run_coroutine_threadsafe(
manager.async_run_test("blabalblabla"), self.hass.loop).result()
assert mock_test.called
assert mock_test.call_count == 1
assert len(manager._cache) == 1
assert not manager._cache['blabalblabla']
assert not run_coroutine_threadsafe(
manager.async_run_test("blabalblabla"), self.hass.loop).result()
assert mock_test.called
assert mock_test.call_count == 1
assert len(manager._cache) == 1
assert not manager._cache['blabalblabla']
| 35.719298
| 79
| 0.673379
|
ab2ef97b07f0789be246f2d714f662a7feec8881
| 141,571
|
py
|
Python
|
scipy/stats/tests/test_distributions.py
|
idan-david/scipy
|
2cc09f55687eef3343442387b6beec701ca79fd6
|
[
"FSFAP"
] | null | null | null |
scipy/stats/tests/test_distributions.py
|
idan-david/scipy
|
2cc09f55687eef3343442387b6beec701ca79fd6
|
[
"FSFAP"
] | null | null | null |
scipy/stats/tests/test_distributions.py
|
idan-david/scipy
|
2cc09f55687eef3343442387b6beec701ca79fd6
|
[
"FSFAP"
] | null | null | null |
""" Test functions for stats module
"""
from __future__ import division, print_function, absolute_import
import warnings
import re
import sys
import pickle
import os
from numpy.testing import (assert_equal, assert_array_equal,
assert_almost_equal, assert_array_almost_equal,
assert_allclose, assert_, assert_warns)
import pytest
from pytest import raises as assert_raises
from scipy._lib._numpy_compat import suppress_warnings
import numpy
import numpy as np
from numpy import typecodes, array
from numpy.lib.recfunctions import rec_append_fields
from scipy import special
from scipy.integrate import IntegrationWarning
import scipy.stats as stats
from scipy.stats._distn_infrastructure import argsreduce
import scipy.stats.distributions
from scipy.special import xlogy
from .test_continuous_basic import distcont
# python -OO strips docstrings
DOCSTRINGS_STRIPPED = sys.flags.optimize > 1
# Generate test cases to test cdf and distribution consistency.
# Note that this list does not include all distributions.
dists = ['uniform', 'norm', 'lognorm', 'expon', 'beta',
'powerlaw', 'bradford', 'burr', 'fisk', 'cauchy', 'halfcauchy',
'foldcauchy', 'gamma', 'gengamma', 'loggamma',
'alpha', 'anglit', 'arcsine', 'betaprime', 'dgamma', 'moyal',
'exponnorm', 'exponweib', 'exponpow', 'frechet_l', 'frechet_r',
'gilbrat', 'f', 'ncf', 'chi2', 'chi', 'nakagami', 'genpareto',
'genextreme', 'genhalflogistic', 'pareto', 'lomax', 'halfnorm',
'halflogistic', 'fatiguelife', 'foldnorm', 'ncx2', 't', 'nct',
'weibull_min', 'weibull_max', 'dweibull', 'maxwell', 'rayleigh',
'genlogistic', 'logistic', 'gumbel_l', 'gumbel_r', 'gompertz',
'hypsecant', 'laplace', 'reciprocal', 'trapz', 'triang',
'tukeylambda', 'vonmises', 'vonmises_line', 'pearson3', 'gennorm',
'halfgennorm', 'rice', 'kappa4', 'kappa3', 'truncnorm', 'argus',
'crystalball']
def _assert_hasattr(a, b, msg=None):
if msg is None:
msg = '%s does not have attribute %s' % (a, b)
assert_(hasattr(a, b), msg=msg)
def test_api_regression():
# https://github.com/scipy/scipy/issues/3802
_assert_hasattr(scipy.stats.distributions, 'f_gen')
# check function for test generator
def check_distribution(dist, args, alpha):
with suppress_warnings() as sup:
# frechet_l and frechet_r are deprecated, so all their
# methods generate DeprecationWarnings.
sup.filter(category=DeprecationWarning, message=".*frechet_")
D, pval = stats.kstest(dist, '', args=args, N=1000)
if (pval < alpha):
D, pval = stats.kstest(dist, '', args=args, N=1000)
assert_(pval > alpha,
msg="D = {}; pval = {}; alpha = {}; args = {}".format(
D, pval, alpha, args))
def cases_test_all_distributions():
np.random.seed(1234)
for dist in dists:
distfunc = getattr(stats, dist)
nargs = distfunc.numargs
alpha = 0.01
if dist == 'fatiguelife':
alpha = 0.001
if dist == 'trapz':
args = tuple(np.sort(np.random.random(nargs)))
elif dist == 'triang':
args = tuple(np.random.random(nargs))
elif dist == 'reciprocal' or dist == 'truncnorm':
vals = np.random.random(nargs)
vals[1] = vals[0] + 1.0
args = tuple(vals)
elif dist == 'vonmises':
yield dist, (10,), alpha
yield dist, (101,), alpha
args = tuple(1.0 + np.random.random(nargs))
else:
args = tuple(1.0 + np.random.random(nargs))
yield dist, args, alpha
@pytest.mark.parametrize('dist,args,alpha', cases_test_all_distributions())
def test_all_distributions(dist, args, alpha):
check_distribution(dist, args, alpha)
def check_vonmises_pdf_periodic(k, l, s, x):
vm = stats.vonmises(k, loc=l, scale=s)
assert_almost_equal(vm.pdf(x), vm.pdf(x % (2*numpy.pi*s)))
def check_vonmises_cdf_periodic(k, l, s, x):
vm = stats.vonmises(k, loc=l, scale=s)
assert_almost_equal(vm.cdf(x) % 1, vm.cdf(x % (2*numpy.pi*s)) % 1)
def test_vonmises_pdf_periodic():
for k in [0.1, 1, 101]:
for x in [0, 1, numpy.pi, 10, 100]:
check_vonmises_pdf_periodic(k, 0, 1, x)
check_vonmises_pdf_periodic(k, 1, 1, x)
check_vonmises_pdf_periodic(k, 0, 10, x)
check_vonmises_cdf_periodic(k, 0, 1, x)
check_vonmises_cdf_periodic(k, 1, 1, x)
check_vonmises_cdf_periodic(k, 0, 10, x)
def test_vonmises_line_support():
assert_equal(stats.vonmises_line.a, -np.pi)
assert_equal(stats.vonmises_line.b, np.pi)
def test_vonmises_numerical():
vm = stats.vonmises(800)
assert_almost_equal(vm.cdf(0), 0.5)
@pytest.mark.parametrize('dist',
['alpha', 'betaprime', 'burr', 'burr12',
'fatiguelife', 'invgamma', 'invgauss', 'invweibull',
'johnsonsb', 'levy', 'levy_l', 'lognorm', 'gilbrat',
'powerlognorm', 'rayleigh', 'wald'])
def test_support(dist):
"""gh-6235"""
dct = dict(distcont)
args = dct[dist]
dist = getattr(stats, dist)
assert_almost_equal(dist.pdf(dist.a, *args), 0)
assert_equal(dist.logpdf(dist.a, *args), -np.inf)
assert_almost_equal(dist.pdf(dist.b, *args), 0)
assert_equal(dist.logpdf(dist.b, *args), -np.inf)
@pytest.mark.parametrize('dist,args,alpha', cases_test_all_distributions())
def test_retrieving_support(dist, args, alpha):
""""""
dist = getattr(stats, dist)
loc, scale = 1, 2
supp = dist.support(*args)
supp_loc_scale = dist.support(*args, loc=loc, scale=scale)
assert_almost_equal(np.array(supp)*scale + loc, np.array(supp_loc_scale))
class TestRandInt(object):
def setup_method(self):
np.random.seed(1234)
def test_rvs(self):
vals = stats.randint.rvs(5, 30, size=100)
assert_(numpy.all(vals < 30) & numpy.all(vals >= 5))
assert_(len(vals) == 100)
vals = stats.randint.rvs(5, 30, size=(2, 50))
assert_(numpy.shape(vals) == (2, 50))
assert_(vals.dtype.char in typecodes['AllInteger'])
val = stats.randint.rvs(15, 46)
assert_((val >= 15) & (val < 46))
assert_(isinstance(val, numpy.ScalarType), msg=repr(type(val)))
val = stats.randint(15, 46).rvs(3)
assert_(val.dtype.char in typecodes['AllInteger'])
def test_pdf(self):
k = numpy.r_[0:36]
out = numpy.where((k >= 5) & (k < 30), 1.0/(30-5), 0)
vals = stats.randint.pmf(k, 5, 30)
assert_array_almost_equal(vals, out)
def test_cdf(self):
x = np.linspace(0,36,100)
k = numpy.floor(x)
out = numpy.select([k >= 30, k >= 5], [1.0, (k-5.0+1)/(30-5.0)], 0)
vals = stats.randint.cdf(x, 5, 30)
assert_array_almost_equal(vals, out, decimal=12)
class TestBinom(object):
def setup_method(self):
np.random.seed(1234)
def test_rvs(self):
vals = stats.binom.rvs(10, 0.75, size=(2, 50))
assert_(numpy.all(vals >= 0) & numpy.all(vals <= 10))
assert_(numpy.shape(vals) == (2, 50))
assert_(vals.dtype.char in typecodes['AllInteger'])
val = stats.binom.rvs(10, 0.75)
assert_(isinstance(val, int))
val = stats.binom(10, 0.75).rvs(3)
assert_(isinstance(val, numpy.ndarray))
assert_(val.dtype.char in typecodes['AllInteger'])
def test_pmf(self):
# regression test for Ticket #1842
vals1 = stats.binom.pmf(100, 100, 1)
vals2 = stats.binom.pmf(0, 100, 0)
assert_allclose(vals1, 1.0, rtol=1e-15, atol=0)
assert_allclose(vals2, 1.0, rtol=1e-15, atol=0)
def test_entropy(self):
# Basic entropy tests.
b = stats.binom(2, 0.5)
expected_p = np.array([0.25, 0.5, 0.25])
expected_h = -sum(xlogy(expected_p, expected_p))
h = b.entropy()
assert_allclose(h, expected_h)
b = stats.binom(2, 0.0)
h = b.entropy()
assert_equal(h, 0.0)
b = stats.binom(2, 1.0)
h = b.entropy()
assert_equal(h, 0.0)
def test_warns_p0(self):
# no spurious warnigns are generated for p=0; gh-3817
with warnings.catch_warnings():
warnings.simplefilter("error", RuntimeWarning)
assert_equal(stats.binom(n=2, p=0).mean(), 0)
assert_equal(stats.binom(n=2, p=0).std(), 0)
class TestBernoulli(object):
def setup_method(self):
np.random.seed(1234)
def test_rvs(self):
vals = stats.bernoulli.rvs(0.75, size=(2, 50))
assert_(numpy.all(vals >= 0) & numpy.all(vals <= 1))
assert_(numpy.shape(vals) == (2, 50))
assert_(vals.dtype.char in typecodes['AllInteger'])
val = stats.bernoulli.rvs(0.75)
assert_(isinstance(val, int))
val = stats.bernoulli(0.75).rvs(3)
assert_(isinstance(val, numpy.ndarray))
assert_(val.dtype.char in typecodes['AllInteger'])
def test_entropy(self):
# Simple tests of entropy.
b = stats.bernoulli(0.25)
expected_h = -0.25*np.log(0.25) - 0.75*np.log(0.75)
h = b.entropy()
assert_allclose(h, expected_h)
b = stats.bernoulli(0.0)
h = b.entropy()
assert_equal(h, 0.0)
b = stats.bernoulli(1.0)
h = b.entropy()
assert_equal(h, 0.0)
class TestBradford(object):
# gh-6216
def test_cdf_ppf(self):
c = 0.1
x = np.logspace(-20, -4)
q = stats.bradford.cdf(x, c)
xx = stats.bradford.ppf(q, c)
assert_allclose(x, xx)
class TestNBinom(object):
def setup_method(self):
np.random.seed(1234)
def test_rvs(self):
vals = stats.nbinom.rvs(10, 0.75, size=(2, 50))
assert_(numpy.all(vals >= 0))
assert_(numpy.shape(vals) == (2, 50))
assert_(vals.dtype.char in typecodes['AllInteger'])
val = stats.nbinom.rvs(10, 0.75)
assert_(isinstance(val, int))
val = stats.nbinom(10, 0.75).rvs(3)
assert_(isinstance(val, numpy.ndarray))
assert_(val.dtype.char in typecodes['AllInteger'])
def test_pmf(self):
# regression test for ticket 1779
assert_allclose(np.exp(stats.nbinom.logpmf(700, 721, 0.52)),
stats.nbinom.pmf(700, 721, 0.52))
# logpmf(0,1,1) shouldn't return nan (regression test for gh-4029)
val = scipy.stats.nbinom.logpmf(0, 1, 1)
assert_equal(val, 0)
class TestNormInvGauss(object):
def setup_method(self):
np.random.seed(1234)
def test_cdf_R(self):
# test pdf and cdf vals against R
# require("GeneralizedHyperbolic")
# x_test <- c(-7, -5, 0, 8, 15)
# r_cdf <- GeneralizedHyperbolic::pnig(x_test, mu = 0, a = 1, b = 0.5)
# r_pdf <- GeneralizedHyperbolic::dnig(x_test, mu = 0, a = 1, b = 0.5)
r_cdf = np.array([8.034920282e-07, 2.512671945e-05, 3.186661051e-01,
9.988650664e-01, 9.999848769e-01])
x_test = np.array([-7, -5, 0, 8, 15])
vals_cdf = stats.norminvgauss.cdf(x_test, a=1, b=0.5)
assert_allclose(vals_cdf, r_cdf, atol=1e-9)
def test_pdf_R(self):
# values from R as defined in test_cdf_R
r_pdf = np.array([1.359600783e-06, 4.413878805e-05, 4.555014266e-01,
7.450485342e-04, 8.917889931e-06])
x_test = np.array([-7, -5, 0, 8, 15])
vals_pdf = stats.norminvgauss.pdf(x_test, a=1, b=0.5)
assert_allclose(vals_pdf, r_pdf, atol=1e-9)
def test_stats(self):
a, b = 1, 0.5
gamma = np.sqrt(a**2 - b**2)
v_stats = (b / gamma, a**2 / gamma**3, 3.0 * b / (a * np.sqrt(gamma)),
3.0 * (1 + 4 * b**2 / a**2) / gamma)
assert_equal(v_stats, stats.norminvgauss.stats(a, b, moments='mvsk'))
def test_ppf(self):
a, b = 1, 0.5
x_test = np.array([0.001, 0.5, 0.999])
vals = stats.norminvgauss.ppf(x_test, a, b)
assert_allclose(x_test, stats.norminvgauss.cdf(vals, a, b))
class TestGeom(object):
def setup_method(self):
np.random.seed(1234)
def test_rvs(self):
vals = stats.geom.rvs(0.75, size=(2, 50))
assert_(numpy.all(vals >= 0))
assert_(numpy.shape(vals) == (2, 50))
assert_(vals.dtype.char in typecodes['AllInteger'])
val = stats.geom.rvs(0.75)
assert_(isinstance(val, int))
val = stats.geom(0.75).rvs(3)
assert_(isinstance(val, numpy.ndarray))
assert_(val.dtype.char in typecodes['AllInteger'])
def test_pmf(self):
vals = stats.geom.pmf([1, 2, 3], 0.5)
assert_array_almost_equal(vals, [0.5, 0.25, 0.125])
def test_logpmf(self):
# regression test for ticket 1793
vals1 = np.log(stats.geom.pmf([1, 2, 3], 0.5))
vals2 = stats.geom.logpmf([1, 2, 3], 0.5)
assert_allclose(vals1, vals2, rtol=1e-15, atol=0)
# regression test for gh-4028
val = stats.geom.logpmf(1, 1)
assert_equal(val, 0.0)
def test_cdf_sf(self):
vals = stats.geom.cdf([1, 2, 3], 0.5)
vals_sf = stats.geom.sf([1, 2, 3], 0.5)
expected = array([0.5, 0.75, 0.875])
assert_array_almost_equal(vals, expected)
assert_array_almost_equal(vals_sf, 1-expected)
def test_logcdf_logsf(self):
vals = stats.geom.logcdf([1, 2, 3], 0.5)
vals_sf = stats.geom.logsf([1, 2, 3], 0.5)
expected = array([0.5, 0.75, 0.875])
assert_array_almost_equal(vals, np.log(expected))
assert_array_almost_equal(vals_sf, np.log1p(-expected))
def test_ppf(self):
vals = stats.geom.ppf([0.5, 0.75, 0.875], 0.5)
expected = array([1.0, 2.0, 3.0])
assert_array_almost_equal(vals, expected)
def test_ppf_underflow(self):
# this should not underflow
assert_allclose(stats.geom.ppf(1e-20, 1e-20), 1.0, atol=1e-14)
class TestPlanck(object):
def setup_method(self):
np.random.seed(1234)
def test_sf(self):
vals = stats.planck.sf([1, 2, 3], 5.)
expected = array([4.5399929762484854e-05,
3.0590232050182579e-07,
2.0611536224385579e-09])
assert_array_almost_equal(vals, expected)
def test_logsf(self):
vals = stats.planck.logsf([1000., 2000., 3000.], 1000.)
expected = array([-1001000., -2001000., -3001000.])
assert_array_almost_equal(vals, expected)
class TestGennorm(object):
def test_laplace(self):
# test against Laplace (special case for beta=1)
points = [1, 2, 3]
pdf1 = stats.gennorm.pdf(points, 1)
pdf2 = stats.laplace.pdf(points)
assert_almost_equal(pdf1, pdf2)
def test_norm(self):
# test against normal (special case for beta=2)
points = [1, 2, 3]
pdf1 = stats.gennorm.pdf(points, 2)
pdf2 = stats.norm.pdf(points, scale=2**-.5)
assert_almost_equal(pdf1, pdf2)
class TestHalfgennorm(object):
def test_expon(self):
# test against exponential (special case for beta=1)
points = [1, 2, 3]
pdf1 = stats.halfgennorm.pdf(points, 1)
pdf2 = stats.expon.pdf(points)
assert_almost_equal(pdf1, pdf2)
def test_halfnorm(self):
# test against half normal (special case for beta=2)
points = [1, 2, 3]
pdf1 = stats.halfgennorm.pdf(points, 2)
pdf2 = stats.halfnorm.pdf(points, scale=2**-.5)
assert_almost_equal(pdf1, pdf2)
def test_gennorm(self):
# test against generalized normal
points = [1, 2, 3]
pdf1 = stats.halfgennorm.pdf(points, .497324)
pdf2 = stats.gennorm.pdf(points, .497324)
assert_almost_equal(pdf1, 2*pdf2)
class TestTruncnorm(object):
def setup_method(self):
np.random.seed(1234)
def test_ppf_ticket1131(self):
vals = stats.truncnorm.ppf([-0.5, 0, 1e-4, 0.5, 1-1e-4, 1, 2], -1., 1.,
loc=[3]*7, scale=2)
expected = np.array([np.nan, 1, 1.00056419, 3, 4.99943581, 5, np.nan])
assert_array_almost_equal(vals, expected)
def test_isf_ticket1131(self):
vals = stats.truncnorm.isf([-0.5, 0, 1e-4, 0.5, 1-1e-4, 1, 2], -1., 1.,
loc=[3]*7, scale=2)
expected = np.array([np.nan, 5, 4.99943581, 3, 1.00056419, 1, np.nan])
assert_array_almost_equal(vals, expected)
def test_gh_2477_small_values(self):
# Check a case that worked in the original issue.
low, high = -11, -10
x = stats.truncnorm.rvs(low, high, 0, 1, size=10)
assert_(low < x.min() < x.max() < high)
# Check a case that failed in the original issue.
low, high = 10, 11
x = stats.truncnorm.rvs(low, high, 0, 1, size=10)
assert_(low < x.min() < x.max() < high)
def test_moments(self):
m, v, s, k = stats.truncnorm.stats(-30, 30, moments='mvsk')
assert_almost_equal(m, 0)
assert_almost_equal(v, 1)
assert_almost_equal(s, 0.0)
assert_almost_equal(k, 0.0)
@pytest.mark.xfail(reason="truncnorm rvs is know to fail at extreme tails")
def test_gh_2477_large_values(self):
# Check a case that fails because of extreme tailness.
low, high = 100, 101
with np.errstate(divide='ignore'):
x = stats.truncnorm.rvs(low, high, 0, 1, size=10)
assert_(low < x.min() < x.max() < high)
def test_gh_1489_trac_962_rvs(self):
# Check the original example.
low, high = 10, 15
x = stats.truncnorm.rvs(low, high, 0, 1, size=10)
assert_(low < x.min() < x.max() < high)
class TestHypergeom(object):
def setup_method(self):
np.random.seed(1234)
def test_rvs(self):
vals = stats.hypergeom.rvs(20, 10, 3, size=(2, 50))
assert_(numpy.all(vals >= 0) &
numpy.all(vals <= 3))
assert_(numpy.shape(vals) == (2, 50))
assert_(vals.dtype.char in typecodes['AllInteger'])
val = stats.hypergeom.rvs(20, 3, 10)
assert_(isinstance(val, int))
val = stats.hypergeom(20, 3, 10).rvs(3)
assert_(isinstance(val, numpy.ndarray))
assert_(val.dtype.char in typecodes['AllInteger'])
def test_precision(self):
# comparison number from mpmath
M = 2500
n = 50
N = 500
tot = M
good = n
hgpmf = stats.hypergeom.pmf(2, tot, good, N)
assert_almost_equal(hgpmf, 0.0010114963068932233, 11)
def test_args(self):
# test correct output for corner cases of arguments
# see gh-2325
assert_almost_equal(stats.hypergeom.pmf(0, 2, 1, 0), 1.0, 11)
assert_almost_equal(stats.hypergeom.pmf(1, 2, 1, 0), 0.0, 11)
assert_almost_equal(stats.hypergeom.pmf(0, 2, 0, 2), 1.0, 11)
assert_almost_equal(stats.hypergeom.pmf(1, 2, 1, 0), 0.0, 11)
def test_cdf_above_one(self):
# for some values of parameters, hypergeom cdf was >1, see gh-2238
assert_(0 <= stats.hypergeom.cdf(30, 13397950, 4363, 12390) <= 1.0)
def test_precision2(self):
# Test hypergeom precision for large numbers. See #1218.
# Results compared with those from R.
oranges = 9.9e4
pears = 1.1e5
fruits_eaten = np.array([3, 3.8, 3.9, 4, 4.1, 4.2, 5]) * 1e4
quantile = 2e4
res = [stats.hypergeom.sf(quantile, oranges + pears, oranges, eaten)
for eaten in fruits_eaten]
expected = np.array([0, 1.904153e-114, 2.752693e-66, 4.931217e-32,
8.265601e-11, 0.1237904, 1])
assert_allclose(res, expected, atol=0, rtol=5e-7)
# Test with array_like first argument
quantiles = [1.9e4, 2e4, 2.1e4, 2.15e4]
res2 = stats.hypergeom.sf(quantiles, oranges + pears, oranges, 4.2e4)
expected2 = [1, 0.1237904, 6.511452e-34, 3.277667e-69]
assert_allclose(res2, expected2, atol=0, rtol=5e-7)
def test_entropy(self):
# Simple tests of entropy.
hg = stats.hypergeom(4, 1, 1)
h = hg.entropy()
expected_p = np.array([0.75, 0.25])
expected_h = -np.sum(xlogy(expected_p, expected_p))
assert_allclose(h, expected_h)
hg = stats.hypergeom(1, 1, 1)
h = hg.entropy()
assert_equal(h, 0.0)
def test_logsf(self):
# Test logsf for very large numbers. See issue #4982
# Results compare with those from R (v3.2.0):
# phyper(k, n, M-n, N, lower.tail=FALSE, log.p=TRUE)
# -2239.771
k = 1e4
M = 1e7
n = 1e6
N = 5e4
result = stats.hypergeom.logsf(k, M, n, N)
exspected = -2239.771 # From R
assert_almost_equal(result, exspected, decimal=3)
class TestLoggamma(object):
def test_stats(self):
# The following precomputed values are from the table in section 2.2
# of "A Statistical Study of Log-Gamma Distribution", by Ping Shing
# Chan (thesis, McMaster University, 1993).
table = np.array([
# c, mean, var, skew, exc. kurt.
0.5, -1.9635, 4.9348, -1.5351, 4.0000,
1.0, -0.5772, 1.6449, -1.1395, 2.4000,
12.0, 2.4427, 0.0869, -0.2946, 0.1735,
]).reshape(-1, 5)
for c, mean, var, skew, kurt in table:
computed = stats.loggamma.stats(c, moments='msvk')
assert_array_almost_equal(computed, [mean, var, skew, kurt],
decimal=4)
class TestLogistic(object):
# gh-6226
def test_cdf_ppf(self):
x = np.linspace(-20, 20)
y = stats.logistic.cdf(x)
xx = stats.logistic.ppf(y)
assert_allclose(x, xx)
def test_sf_isf(self):
x = np.linspace(-20, 20)
y = stats.logistic.sf(x)
xx = stats.logistic.isf(y)
assert_allclose(x, xx)
def test_extreme_values(self):
# p is chosen so that 1 - (1 - p) == p in double precision
p = 9.992007221626409e-16
desired = 34.53957599234088
assert_allclose(stats.logistic.ppf(1 - p), desired)
assert_allclose(stats.logistic.isf(p), desired)
class TestLogser(object):
def setup_method(self):
np.random.seed(1234)
def test_rvs(self):
vals = stats.logser.rvs(0.75, size=(2, 50))
assert_(numpy.all(vals >= 1))
assert_(numpy.shape(vals) == (2, 50))
assert_(vals.dtype.char in typecodes['AllInteger'])
val = stats.logser.rvs(0.75)
assert_(isinstance(val, int))
val = stats.logser(0.75).rvs(3)
assert_(isinstance(val, numpy.ndarray))
assert_(val.dtype.char in typecodes['AllInteger'])
def test_pmf_small_p(self):
m = stats.logser.pmf(4, 1e-20)
# The expected value was computed using mpmath:
# >>> import mpmath
# >>> mpmath.mp.dps = 64
# >>> k = 4
# >>> p = mpmath.mpf('1e-20')
# >>> float(-(p**k)/k/mpmath.log(1-p))
# 2.5e-61
# It is also clear from noticing that for very small p,
# log(1-p) is approximately -p, and the formula becomes
# p**(k-1) / k
assert_allclose(m, 2.5e-61)
def test_mean_small_p(self):
m = stats.logser.mean(1e-8)
# The expected mean was computed using mpmath:
# >>> import mpmath
# >>> mpmath.dps = 60
# >>> p = mpmath.mpf('1e-8')
# >>> float(-p / ((1 - p)*mpmath.log(1 - p)))
# 1.000000005
assert_allclose(m, 1.000000005)
class TestPareto(object):
def test_stats(self):
# Check the stats() method with some simple values. Also check
# that the calculations do not trigger RuntimeWarnings.
with warnings.catch_warnings():
warnings.simplefilter("error", RuntimeWarning)
m, v, s, k = stats.pareto.stats(0.5, moments='mvsk')
assert_equal(m, np.inf)
assert_equal(v, np.inf)
assert_equal(s, np.nan)
assert_equal(k, np.nan)
m, v, s, k = stats.pareto.stats(1.0, moments='mvsk')
assert_equal(m, np.inf)
assert_equal(v, np.inf)
assert_equal(s, np.nan)
assert_equal(k, np.nan)
m, v, s, k = stats.pareto.stats(1.5, moments='mvsk')
assert_equal(m, 3.0)
assert_equal(v, np.inf)
assert_equal(s, np.nan)
assert_equal(k, np.nan)
m, v, s, k = stats.pareto.stats(2.0, moments='mvsk')
assert_equal(m, 2.0)
assert_equal(v, np.inf)
assert_equal(s, np.nan)
assert_equal(k, np.nan)
m, v, s, k = stats.pareto.stats(2.5, moments='mvsk')
assert_allclose(m, 2.5 / 1.5)
assert_allclose(v, 2.5 / (1.5*1.5*0.5))
assert_equal(s, np.nan)
assert_equal(k, np.nan)
m, v, s, k = stats.pareto.stats(3.0, moments='mvsk')
assert_allclose(m, 1.5)
assert_allclose(v, 0.75)
assert_equal(s, np.nan)
assert_equal(k, np.nan)
m, v, s, k = stats.pareto.stats(3.5, moments='mvsk')
assert_allclose(m, 3.5 / 2.5)
assert_allclose(v, 3.5 / (2.5*2.5*1.5))
assert_allclose(s, (2*4.5/0.5)*np.sqrt(1.5/3.5))
assert_equal(k, np.nan)
m, v, s, k = stats.pareto.stats(4.0, moments='mvsk')
assert_allclose(m, 4.0 / 3.0)
assert_allclose(v, 4.0 / 18.0)
assert_allclose(s, 2*(1+4.0)/(4.0-3) * np.sqrt((4.0-2)/4.0))
assert_equal(k, np.nan)
m, v, s, k = stats.pareto.stats(4.5, moments='mvsk')
assert_allclose(m, 4.5 / 3.5)
assert_allclose(v, 4.5 / (3.5*3.5*2.5))
assert_allclose(s, (2*5.5/1.5) * np.sqrt(2.5/4.5))
assert_allclose(k, 6*(4.5**3 + 4.5**2 - 6*4.5 - 2)/(4.5*1.5*0.5))
def test_sf(self):
x = 1e9
b = 2
scale = 1.5
p = stats.pareto.sf(x, b, loc=0, scale=scale)
expected = (scale/x)**b # 2.25e-18
assert_allclose(p, expected)
class TestGenpareto(object):
def test_ab(self):
# c >= 0: a, b = [0, inf]
for c in [1., 0.]:
c = np.asarray(c)
stats.genpareto._argcheck(c) # ugh
a, b = stats.genpareto._get_support(c)
assert_equal(a, 0.)
assert_(np.isposinf(b))
# c < 0: a=0, b=1/|c|
c = np.asarray(-2.)
stats.genpareto._argcheck(c)
assert_allclose(stats.genpareto._get_support(c), [0., 0.5])
def test_c0(self):
# with c=0, genpareto reduces to the exponential distribution
rv = stats.genpareto(c=0.)
x = np.linspace(0, 10., 30)
assert_allclose(rv.pdf(x), stats.expon.pdf(x))
assert_allclose(rv.cdf(x), stats.expon.cdf(x))
assert_allclose(rv.sf(x), stats.expon.sf(x))
q = np.linspace(0., 1., 10)
assert_allclose(rv.ppf(q), stats.expon.ppf(q))
def test_cm1(self):
# with c=-1, genpareto reduces to the uniform distr on [0, 1]
rv = stats.genpareto(c=-1.)
x = np.linspace(0, 10., 30)
assert_allclose(rv.pdf(x), stats.uniform.pdf(x))
assert_allclose(rv.cdf(x), stats.uniform.cdf(x))
assert_allclose(rv.sf(x), stats.uniform.sf(x))
q = np.linspace(0., 1., 10)
assert_allclose(rv.ppf(q), stats.uniform.ppf(q))
# logpdf(1., c=-1) should be zero
assert_allclose(rv.logpdf(1), 0)
def test_x_inf(self):
# make sure x=inf is handled gracefully
rv = stats.genpareto(c=0.1)
assert_allclose([rv.pdf(np.inf), rv.cdf(np.inf)], [0., 1.])
assert_(np.isneginf(rv.logpdf(np.inf)))
rv = stats.genpareto(c=0.)
assert_allclose([rv.pdf(np.inf), rv.cdf(np.inf)], [0., 1.])
assert_(np.isneginf(rv.logpdf(np.inf)))
rv = stats.genpareto(c=-1.)
assert_allclose([rv.pdf(np.inf), rv.cdf(np.inf)], [0., 1.])
assert_(np.isneginf(rv.logpdf(np.inf)))
def test_c_continuity(self):
# pdf is continuous at c=0, -1
x = np.linspace(0, 10, 30)
for c in [0, -1]:
pdf0 = stats.genpareto.pdf(x, c)
for dc in [1e-14, -1e-14]:
pdfc = stats.genpareto.pdf(x, c + dc)
assert_allclose(pdf0, pdfc, atol=1e-12)
cdf0 = stats.genpareto.cdf(x, c)
for dc in [1e-14, 1e-14]:
cdfc = stats.genpareto.cdf(x, c + dc)
assert_allclose(cdf0, cdfc, atol=1e-12)
def test_c_continuity_ppf(self):
q = np.r_[np.logspace(1e-12, 0.01, base=0.1),
np.linspace(0.01, 1, 30, endpoint=False),
1. - np.logspace(1e-12, 0.01, base=0.1)]
for c in [0., -1.]:
ppf0 = stats.genpareto.ppf(q, c)
for dc in [1e-14, -1e-14]:
ppfc = stats.genpareto.ppf(q, c + dc)
assert_allclose(ppf0, ppfc, atol=1e-12)
def test_c_continuity_isf(self):
q = np.r_[np.logspace(1e-12, 0.01, base=0.1),
np.linspace(0.01, 1, 30, endpoint=False),
1. - np.logspace(1e-12, 0.01, base=0.1)]
for c in [0., -1.]:
isf0 = stats.genpareto.isf(q, c)
for dc in [1e-14, -1e-14]:
isfc = stats.genpareto.isf(q, c + dc)
assert_allclose(isf0, isfc, atol=1e-12)
def test_cdf_ppf_roundtrip(self):
# this should pass with machine precision. hat tip @pbrod
q = np.r_[np.logspace(1e-12, 0.01, base=0.1),
np.linspace(0.01, 1, 30, endpoint=False),
1. - np.logspace(1e-12, 0.01, base=0.1)]
for c in [1e-8, -1e-18, 1e-15, -1e-15]:
assert_allclose(stats.genpareto.cdf(stats.genpareto.ppf(q, c), c),
q, atol=1e-15)
def test_logsf(self):
logp = stats.genpareto.logsf(1e10, .01, 0, 1)
assert_allclose(logp, -1842.0680753952365)
class TestPearson3(object):
def setup_method(self):
np.random.seed(1234)
def test_rvs(self):
vals = stats.pearson3.rvs(0.1, size=(2, 50))
assert_(numpy.shape(vals) == (2, 50))
assert_(vals.dtype.char in typecodes['AllFloat'])
val = stats.pearson3.rvs(0.5)
assert_(isinstance(val, float))
val = stats.pearson3(0.5).rvs(3)
assert_(isinstance(val, numpy.ndarray))
assert_(val.dtype.char in typecodes['AllFloat'])
assert_(len(val) == 3)
def test_pdf(self):
vals = stats.pearson3.pdf(2, [0.0, 0.1, 0.2])
assert_allclose(vals, np.array([0.05399097, 0.05555481, 0.05670246]),
atol=1e-6)
vals = stats.pearson3.pdf(-3, 0.1)
assert_allclose(vals, np.array([0.00313791]), atol=1e-6)
vals = stats.pearson3.pdf([-3, -2, -1, 0, 1], 0.1)
assert_allclose(vals, np.array([0.00313791, 0.05192304, 0.25028092,
0.39885918, 0.23413173]), atol=1e-6)
def test_cdf(self):
vals = stats.pearson3.cdf(2, [0.0, 0.1, 0.2])
assert_allclose(vals, np.array([0.97724987, 0.97462004, 0.97213626]),
atol=1e-6)
vals = stats.pearson3.cdf(-3, 0.1)
assert_allclose(vals, [0.00082256], atol=1e-6)
vals = stats.pearson3.cdf([-3, -2, -1, 0, 1], 0.1)
assert_allclose(vals, [8.22563821e-04, 1.99860448e-02, 1.58550710e-01,
5.06649130e-01, 8.41442111e-01], atol=1e-6)
class TestKappa4(object):
def test_cdf_genpareto(self):
# h = 1 and k != 0 is generalized Pareto
x = [0.0, 0.1, 0.2, 0.5]
h = 1.0
for k in [-1.9, -1.0, -0.5, -0.2, -0.1, 0.1, 0.2, 0.5, 1.0,
1.9]:
vals = stats.kappa4.cdf(x, h, k)
# shape parameter is opposite what is expected
vals_comp = stats.genpareto.cdf(x, -k)
assert_allclose(vals, vals_comp)
def test_cdf_genextreme(self):
# h = 0 and k != 0 is generalized extreme value
x = np.linspace(-5, 5, 10)
h = 0.0
k = np.linspace(-3, 3, 10)
vals = stats.kappa4.cdf(x, h, k)
vals_comp = stats.genextreme.cdf(x, k)
assert_allclose(vals, vals_comp)
def test_cdf_expon(self):
# h = 1 and k = 0 is exponential
x = np.linspace(0, 10, 10)
h = 1.0
k = 0.0
vals = stats.kappa4.cdf(x, h, k)
vals_comp = stats.expon.cdf(x)
assert_allclose(vals, vals_comp)
def test_cdf_gumbel_r(self):
# h = 0 and k = 0 is gumbel_r
x = np.linspace(-5, 5, 10)
h = 0.0
k = 0.0
vals = stats.kappa4.cdf(x, h, k)
vals_comp = stats.gumbel_r.cdf(x)
assert_allclose(vals, vals_comp)
def test_cdf_logistic(self):
# h = -1 and k = 0 is logistic
x = np.linspace(-5, 5, 10)
h = -1.0
k = 0.0
vals = stats.kappa4.cdf(x, h, k)
vals_comp = stats.logistic.cdf(x)
assert_allclose(vals, vals_comp)
def test_cdf_uniform(self):
# h = 1 and k = 1 is uniform
x = np.linspace(-5, 5, 10)
h = 1.0
k = 1.0
vals = stats.kappa4.cdf(x, h, k)
vals_comp = stats.uniform.cdf(x)
assert_allclose(vals, vals_comp)
def test_integers_ctor(self):
# regression test for gh-7416: _argcheck fails for integer h and k
# in numpy 1.12
stats.kappa4(1, 2)
class TestPoisson(object):
def setup_method(self):
np.random.seed(1234)
def test_pmf_basic(self):
# Basic case
ln2 = np.log(2)
vals = stats.poisson.pmf([0, 1, 2], ln2)
expected = [0.5, ln2/2, ln2**2/4]
assert_allclose(vals, expected)
def test_mu0(self):
# Edge case: mu=0
vals = stats.poisson.pmf([0, 1, 2], 0)
expected = [1, 0, 0]
assert_array_equal(vals, expected)
interval = stats.poisson.interval(0.95, 0)
assert_equal(interval, (0, 0))
def test_rvs(self):
vals = stats.poisson.rvs(0.5, size=(2, 50))
assert_(numpy.all(vals >= 0))
assert_(numpy.shape(vals) == (2, 50))
assert_(vals.dtype.char in typecodes['AllInteger'])
val = stats.poisson.rvs(0.5)
assert_(isinstance(val, int))
val = stats.poisson(0.5).rvs(3)
assert_(isinstance(val, numpy.ndarray))
assert_(val.dtype.char in typecodes['AllInteger'])
def test_stats(self):
mu = 16.0
result = stats.poisson.stats(mu, moments='mvsk')
assert_allclose(result, [mu, mu, np.sqrt(1.0/mu), 1.0/mu])
mu = np.array([0.0, 1.0, 2.0])
result = stats.poisson.stats(mu, moments='mvsk')
expected = (mu, mu, [np.inf, 1, 1/np.sqrt(2)], [np.inf, 1, 0.5])
assert_allclose(result, expected)
class TestZipf(object):
def setup_method(self):
np.random.seed(1234)
def test_rvs(self):
vals = stats.zipf.rvs(1.5, size=(2, 50))
assert_(numpy.all(vals >= 1))
assert_(numpy.shape(vals) == (2, 50))
assert_(vals.dtype.char in typecodes['AllInteger'])
val = stats.zipf.rvs(1.5)
assert_(isinstance(val, int))
val = stats.zipf(1.5).rvs(3)
assert_(isinstance(val, numpy.ndarray))
assert_(val.dtype.char in typecodes['AllInteger'])
def test_moments(self):
# n-th moment is finite iff a > n + 1
m, v = stats.zipf.stats(a=2.8)
assert_(np.isfinite(m))
assert_equal(v, np.inf)
s, k = stats.zipf.stats(a=4.8, moments='sk')
assert_(not np.isfinite([s, k]).all())
class TestDLaplace(object):
def setup_method(self):
np.random.seed(1234)
def test_rvs(self):
vals = stats.dlaplace.rvs(1.5, size=(2, 50))
assert_(numpy.shape(vals) == (2, 50))
assert_(vals.dtype.char in typecodes['AllInteger'])
val = stats.dlaplace.rvs(1.5)
assert_(isinstance(val, int))
val = stats.dlaplace(1.5).rvs(3)
assert_(isinstance(val, numpy.ndarray))
assert_(val.dtype.char in typecodes['AllInteger'])
assert_(stats.dlaplace.rvs(0.8) is not None)
def test_stats(self):
# compare the explicit formulas w/ direct summation using pmf
a = 1.
dl = stats.dlaplace(a)
m, v, s, k = dl.stats('mvsk')
N = 37
xx = np.arange(-N, N+1)
pp = dl.pmf(xx)
m2, m4 = np.sum(pp*xx**2), np.sum(pp*xx**4)
assert_equal((m, s), (0, 0))
assert_allclose((v, k), (m2, m4/m2**2 - 3.), atol=1e-14, rtol=1e-8)
def test_stats2(self):
a = np.log(2.)
dl = stats.dlaplace(a)
m, v, s, k = dl.stats('mvsk')
assert_equal((m, s), (0., 0.))
assert_allclose((v, k), (4., 3.25))
class TestInvGamma(object):
def test_invgamma_inf_gh_1866(self):
# invgamma's moments are only finite for a>n
# specific numbers checked w/ boost 1.54
with warnings.catch_warnings():
warnings.simplefilter('error', RuntimeWarning)
mvsk = stats.invgamma.stats(a=19.31, moments='mvsk')
expected = [0.05461496450, 0.0001723162534, 1.020362676,
2.055616582]
assert_allclose(mvsk, expected)
a = [1.1, 3.1, 5.6]
mvsk = stats.invgamma.stats(a=a, moments='mvsk')
expected = ([10., 0.476190476, 0.2173913043], # mmm
[np.inf, 0.2061430632, 0.01312749422], # vvv
[np.nan, 41.95235392, 2.919025532], # sss
[np.nan, np.nan, 24.51923076]) # kkk
for x, y in zip(mvsk, expected):
assert_almost_equal(x, y)
def test_cdf_ppf(self):
# gh-6245
x = np.logspace(-2.6, 0)
y = stats.invgamma.cdf(x, 1)
xx = stats.invgamma.ppf(y, 1)
assert_allclose(x, xx)
def test_sf_isf(self):
# gh-6245
if sys.maxsize > 2**32:
x = np.logspace(2, 100)
else:
# Invgamme roundtrip on 32-bit systems has relative accuracy
# ~1e-15 until x=1e+15, and becomes inf above x=1e+18
x = np.logspace(2, 18)
y = stats.invgamma.sf(x, 1)
xx = stats.invgamma.isf(y, 1)
assert_allclose(x, xx, rtol=1.0)
class TestF(object):
def test_f_moments(self):
# n-th moment of F distributions is only finite for n < dfd / 2
m, v, s, k = stats.f.stats(11, 6.5, moments='mvsk')
assert_(np.isfinite(m))
assert_(np.isfinite(v))
assert_(np.isfinite(s))
assert_(not np.isfinite(k))
def test_moments_warnings(self):
# no warnings should be generated for dfd = 2, 4, 6, 8 (div by zero)
with warnings.catch_warnings():
warnings.simplefilter('error', RuntimeWarning)
stats.f.stats(dfn=[11]*4, dfd=[2, 4, 6, 8], moments='mvsk')
@pytest.mark.xfail(reason='f stats does not properly broadcast')
def test_stats_broadcast(self):
# stats do not fully broadcast just yet
mv = stats.f.stats(dfn=11, dfd=[11, 12])
def test_rvgeneric_std():
# Regression test for #1191
assert_array_almost_equal(stats.t.std([5, 6]), [1.29099445, 1.22474487])
def test_moments_t():
# regression test for #8786
assert_equal(stats.t.stats(df=1, moments='mvsk'),
(np.inf, np.nan, np.nan, np.nan))
assert_equal(stats.t.stats(df=1.01, moments='mvsk'),
(0.0, np.inf, np.nan, np.nan))
assert_equal(stats.t.stats(df=2, moments='mvsk'),
(0.0, np.inf, np.nan, np.nan))
assert_equal(stats.t.stats(df=2.01, moments='mvsk'),
(0.0, 2.01/(2.01-2.0), np.nan, np.inf))
assert_equal(stats.t.stats(df=3, moments='sk'), (np.nan, np.inf))
assert_equal(stats.t.stats(df=3.01, moments='sk'), (0.0, np.inf))
assert_equal(stats.t.stats(df=4, moments='sk'), (0.0, np.inf))
assert_equal(stats.t.stats(df=4.01, moments='sk'), (0.0, 6.0/(4.01 - 4.0)))
class TestRvDiscrete(object):
def setup_method(self):
np.random.seed(1234)
def test_rvs(self):
states = [-1, 0, 1, 2, 3, 4]
probability = [0.0, 0.3, 0.4, 0.0, 0.3, 0.0]
samples = 1000
r = stats.rv_discrete(name='sample', values=(states, probability))
x = r.rvs(size=samples)
assert_(isinstance(x, numpy.ndarray))
for s, p in zip(states, probability):
assert_(abs(sum(x == s)/float(samples) - p) < 0.05)
x = r.rvs()
assert_(isinstance(x, int))
def test_entropy(self):
# Basic tests of entropy.
pvals = np.array([0.25, 0.45, 0.3])
p = stats.rv_discrete(values=([0, 1, 2], pvals))
expected_h = -sum(xlogy(pvals, pvals))
h = p.entropy()
assert_allclose(h, expected_h)
p = stats.rv_discrete(values=([0, 1, 2], [1.0, 0, 0]))
h = p.entropy()
assert_equal(h, 0.0)
def test_pmf(self):
xk = [1, 2, 4]
pk = [0.5, 0.3, 0.2]
rv = stats.rv_discrete(values=(xk, pk))
x = [[1., 4.],
[3., 2]]
assert_allclose(rv.pmf(x),
[[0.5, 0.2],
[0., 0.3]], atol=1e-14)
def test_cdf(self):
xk = [1, 2, 4]
pk = [0.5, 0.3, 0.2]
rv = stats.rv_discrete(values=(xk, pk))
x_values = [-2, 1., 1.1, 1.5, 2.0, 3.0, 4, 5]
expected = [0, 0.5, 0.5, 0.5, 0.8, 0.8, 1, 1]
assert_allclose(rv.cdf(x_values), expected, atol=1e-14)
# also check scalar arguments
assert_allclose([rv.cdf(xx) for xx in x_values],
expected, atol=1e-14)
def test_ppf(self):
xk = [1, 2, 4]
pk = [0.5, 0.3, 0.2]
rv = stats.rv_discrete(values=(xk, pk))
q_values = [0.1, 0.5, 0.6, 0.8, 0.9, 1.]
expected = [1, 1, 2, 2, 4, 4]
assert_allclose(rv.ppf(q_values), expected, atol=1e-14)
# also check scalar arguments
assert_allclose([rv.ppf(q) for q in q_values],
expected, atol=1e-14)
def test_cdf_ppf_next(self):
# copied and special cased from test_discrete_basic
vals = ([1, 2, 4, 7, 8], [0.1, 0.2, 0.3, 0.3, 0.1])
rv = stats.rv_discrete(values=vals)
assert_array_equal(rv.ppf(rv.cdf(rv.xk[:-1]) + 1e-8),
rv.xk[1:])
def test_expect(self):
xk = [1, 2, 4, 6, 7, 11]
pk = [0.1, 0.2, 0.2, 0.2, 0.2, 0.1]
rv = stats.rv_discrete(values=(xk, pk))
assert_allclose(rv.expect(), np.sum(rv.xk * rv.pk), atol=1e-14)
def test_multidimension(self):
xk = np.arange(12).reshape((3, 4))
pk = np.array([[0.1, 0.1, 0.15, 0.05],
[0.1, 0.1, 0.05, 0.05],
[0.1, 0.1, 0.05, 0.05]])
rv = stats.rv_discrete(values=(xk, pk))
assert_allclose(rv.expect(), np.sum(rv.xk * rv.pk), atol=1e-14)
def test_bad_input(self):
xk = [1, 2, 3]
pk = [0.5, 0.5]
assert_raises(ValueError, stats.rv_discrete, **dict(values=(xk, pk)))
pk = [1, 2, 3]
assert_raises(ValueError, stats.rv_discrete, **dict(values=(xk, pk)))
xk = [1, 2, 3]
pk = [0.5, 1.2, -0.7]
assert_raises(ValueError, stats.rv_discrete, **dict(values=(xk, pk)))
xk = [1, 2, 3, 4, 5]
pk = [0.3, 0.3, 0.3, 0.3, -0.2]
assert_raises(ValueError, stats.rv_discrete, **dict(values=(xk, pk)))
def test_shape_rv_sample(self):
# tests added for gh-9565
# mismatch of 2d inputs
xk, pk = np.arange(4).reshape((2, 2)), np.ones((2, 3)) / 6
assert_raises(ValueError, stats.rv_discrete, **dict(values=(xk, pk)))
# same number of elements, but shapes not compatible
xk, pk = np.arange(6).reshape((3, 2)), np.ones((2, 3)) / 6
assert_raises(ValueError, stats.rv_discrete, **dict(values=(xk, pk)))
# same shapes => no error
xk, pk = np.arange(6).reshape((3, 2)), np.ones((3, 2)) / 6
assert_equal(stats.rv_discrete(values=(xk, pk)).pmf(0), 1/6)
class TestSkewNorm(object):
def setup_method(self):
np.random.seed(1234)
def test_normal(self):
# When the skewness is 0 the distribution is normal
x = np.linspace(-5, 5, 100)
assert_array_almost_equal(stats.skewnorm.pdf(x, a=0),
stats.norm.pdf(x))
def test_rvs(self):
shape = (3, 4, 5)
x = stats.skewnorm.rvs(a=0.75, size=shape)
assert_equal(shape, x.shape)
x = stats.skewnorm.rvs(a=-3, size=shape)
assert_equal(shape, x.shape)
def test_moments(self):
X = stats.skewnorm.rvs(a=4, size=int(1e6), loc=5, scale=2)
expected = [np.mean(X), np.var(X), stats.skew(X), stats.kurtosis(X)]
computed = stats.skewnorm.stats(a=4, loc=5, scale=2, moments='mvsk')
assert_array_almost_equal(computed, expected, decimal=2)
X = stats.skewnorm.rvs(a=-4, size=int(1e6), loc=5, scale=2)
expected = [np.mean(X), np.var(X), stats.skew(X), stats.kurtosis(X)]
computed = stats.skewnorm.stats(a=-4, loc=5, scale=2, moments='mvsk')
assert_array_almost_equal(computed, expected, decimal=2)
def test_cdf_large_x(self):
# Regression test for gh-7746.
# The x values are large enough that the closest 64 bit floating
# point representation of the exact CDF is 1.0.
p = stats.skewnorm.cdf([10, 20, 30], -1)
assert_allclose(p, np.ones(3), rtol=1e-14)
p = stats.skewnorm.cdf(25, 2.5)
assert_allclose(p, 1.0, rtol=1e-14)
def test_cdf_sf_small_values(self):
# Triples are [x, a, cdf(x, a)]. These values were computed
# using CDF[SkewNormDistribution[0, 1, a], x] in Wolfram Alpha.
cdfvals = [
[-8, 1, 3.870035046664392611e-31],
[-4, 2, 8.1298399188811398e-21],
[-2, 5, 1.55326826787106273e-26],
[-9, -1, 2.257176811907681295e-19],
[-10, -4, 1.523970604832105213e-23],
]
for x, a, cdfval in cdfvals:
p = stats.skewnorm.cdf(x, a)
assert_allclose(p, cdfval, rtol=1e-8)
# For the skew normal distribution, sf(-x, -a) = cdf(x, a).
p = stats.skewnorm.sf(-x, -a)
assert_allclose(p, cdfval, rtol=1e-8)
class TestExpon(object):
def test_zero(self):
assert_equal(stats.expon.pdf(0), 1)
def test_tail(self): # Regression test for ticket 807
assert_equal(stats.expon.cdf(1e-18), 1e-18)
assert_equal(stats.expon.isf(stats.expon.sf(40)), 40)
class TestExponNorm(object):
def test_moments(self):
# Some moment test cases based on non-loc/scaled formula
def get_moms(lam, sig, mu):
# See wikipedia for these formulae
# where it is listed as an exponentially modified gaussian
opK2 = 1.0 + 1 / (lam*sig)**2
exp_skew = 2 / (lam * sig)**3 * opK2**(-1.5)
exp_kurt = 6.0 * (1 + (lam * sig)**2)**(-2)
return [mu + 1/lam, sig*sig + 1.0/(lam*lam), exp_skew, exp_kurt]
mu, sig, lam = 0, 1, 1
K = 1.0 / (lam * sig)
sts = stats.exponnorm.stats(K, loc=mu, scale=sig, moments='mvsk')
assert_almost_equal(sts, get_moms(lam, sig, mu))
mu, sig, lam = -3, 2, 0.1
K = 1.0 / (lam * sig)
sts = stats.exponnorm.stats(K, loc=mu, scale=sig, moments='mvsk')
assert_almost_equal(sts, get_moms(lam, sig, mu))
mu, sig, lam = 0, 3, 1
K = 1.0 / (lam * sig)
sts = stats.exponnorm.stats(K, loc=mu, scale=sig, moments='mvsk')
assert_almost_equal(sts, get_moms(lam, sig, mu))
mu, sig, lam = -5, 11, 3.5
K = 1.0 / (lam * sig)
sts = stats.exponnorm.stats(K, loc=mu, scale=sig, moments='mvsk')
assert_almost_equal(sts, get_moms(lam, sig, mu))
def test_extremes_x(self):
# Test for extreme values against overflows
assert_almost_equal(stats.exponnorm.pdf(-900, 1), 0.0)
assert_almost_equal(stats.exponnorm.pdf(+900, 1), 0.0)
assert_almost_equal(stats.exponnorm.pdf(1, 0.01), 0.0)
assert_almost_equal(stats.exponnorm.pdf(-900, 0.01), 0.0)
assert_almost_equal(stats.exponnorm.pdf(+900, 0.01), 0.0)
class TestGenExpon(object):
def test_pdf_unity_area(self):
from scipy.integrate import simps
# PDF should integrate to one
p = stats.genexpon.pdf(numpy.arange(0, 10, 0.01), 0.5, 0.5, 2.0)
assert_almost_equal(simps(p, dx=0.01), 1, 1)
def test_cdf_bounds(self):
# CDF should always be positive
cdf = stats.genexpon.cdf(numpy.arange(0, 10, 0.01), 0.5, 0.5, 2.0)
assert_(numpy.all((0 <= cdf) & (cdf <= 1)))
class TestExponpow(object):
def test_tail(self):
assert_almost_equal(stats.exponpow.cdf(1e-10, 2.), 1e-20)
assert_almost_equal(stats.exponpow.isf(stats.exponpow.sf(5, .8), .8),
5)
class TestSkellam(object):
def test_pmf(self):
# comparison to R
k = numpy.arange(-10, 15)
mu1, mu2 = 10, 5
skpmfR = numpy.array(
[4.2254582961926893e-005, 1.1404838449648488e-004,
2.8979625801752660e-004, 6.9177078182101231e-004,
1.5480716105844708e-003, 3.2412274963433889e-003,
6.3373707175123292e-003, 1.1552351566696643e-002,
1.9606152375042644e-002, 3.0947164083410337e-002,
4.5401737566767360e-002, 6.1894328166820688e-002,
7.8424609500170578e-002, 9.2418812533573133e-002,
1.0139793148019728e-001, 1.0371927988298846e-001,
9.9076583077406091e-002, 8.8546660073089561e-002,
7.4187842052486810e-002, 5.8392772862200251e-002,
4.3268692953013159e-002, 3.0248159818374226e-002,
1.9991434305603021e-002, 1.2516877303301180e-002,
7.4389876226229707e-003])
assert_almost_equal(stats.skellam.pmf(k, mu1, mu2), skpmfR, decimal=15)
def test_cdf(self):
# comparison to R, only 5 decimals
k = numpy.arange(-10, 15)
mu1, mu2 = 10, 5
skcdfR = numpy.array(
[6.4061475386192104e-005, 1.7810985988267694e-004,
4.6790611790020336e-004, 1.1596768997212152e-003,
2.7077485103056847e-003, 5.9489760066490718e-003,
1.2286346724161398e-002, 2.3838698290858034e-002,
4.3444850665900668e-002, 7.4392014749310995e-002,
1.1979375231607835e-001, 1.8168808048289900e-001,
2.6011268998306952e-001, 3.5253150251664261e-001,
4.5392943399683988e-001, 5.5764871387982828e-001,
6.5672529695723436e-001, 7.4527195703032389e-001,
8.1945979908281064e-001, 8.7785257194501087e-001,
9.2112126489802404e-001, 9.5136942471639818e-001,
9.7136085902200120e-001, 9.8387773632530240e-001,
9.9131672394792536e-001])
assert_almost_equal(stats.skellam.cdf(k, mu1, mu2), skcdfR, decimal=5)
class TestLognorm(object):
def test_pdf(self):
# Regression test for Ticket #1471: avoid nan with 0/0 situation
# Also make sure there are no warnings at x=0, cf gh-5202
with warnings.catch_warnings():
warnings.simplefilter('error', RuntimeWarning)
pdf = stats.lognorm.pdf([0, 0.5, 1], 1)
assert_array_almost_equal(pdf, [0.0, 0.62749608, 0.39894228])
def test_logcdf(self):
# Regression test for gh-5940: sf et al would underflow too early
x2, mu, sigma = 201.68, 195, 0.149
assert_allclose(stats.lognorm.sf(x2-mu, s=sigma),
stats.norm.sf(np.log(x2-mu)/sigma))
assert_allclose(stats.lognorm.logsf(x2-mu, s=sigma),
stats.norm.logsf(np.log(x2-mu)/sigma))
class TestBeta(object):
def test_logpdf(self):
# Regression test for Ticket #1326: avoid nan with 0*log(0) situation
logpdf = stats.beta.logpdf(0, 1, 0.5)
assert_almost_equal(logpdf, -0.69314718056)
logpdf = stats.beta.logpdf(0, 0.5, 1)
assert_almost_equal(logpdf, np.inf)
def test_logpdf_ticket_1866(self):
alpha, beta = 267, 1472
x = np.array([0.2, 0.5, 0.6])
b = stats.beta(alpha, beta)
assert_allclose(b.logpdf(x).sum(), -1201.699061824062)
assert_allclose(b.pdf(x), np.exp(b.logpdf(x)))
class TestBetaPrime(object):
def test_logpdf(self):
alpha, beta = 267, 1472
x = np.array([0.2, 0.5, 0.6])
b = stats.betaprime(alpha, beta)
assert_(np.isfinite(b.logpdf(x)).all())
assert_allclose(b.pdf(x), np.exp(b.logpdf(x)))
def test_cdf(self):
# regression test for gh-4030: Implementation of
# scipy.stats.betaprime.cdf()
x = stats.betaprime.cdf(0, 0.2, 0.3)
assert_equal(x, 0.0)
alpha, beta = 267, 1472
x = np.array([0.2, 0.5, 0.6])
cdfs = stats.betaprime.cdf(x, alpha, beta)
assert_(np.isfinite(cdfs).all())
# check the new cdf implementation vs generic one:
gen_cdf = stats.rv_continuous._cdf_single
cdfs_g = [gen_cdf(stats.betaprime, val, alpha, beta) for val in x]
assert_allclose(cdfs, cdfs_g, atol=0, rtol=2e-12)
class TestGamma(object):
def test_pdf(self):
# a few test cases to compare with R
pdf = stats.gamma.pdf(90, 394, scale=1./5)
assert_almost_equal(pdf, 0.002312341)
pdf = stats.gamma.pdf(3, 10, scale=1./5)
assert_almost_equal(pdf, 0.1620358)
def test_logpdf(self):
# Regression test for Ticket #1326: cornercase avoid nan with 0*log(0)
# situation
logpdf = stats.gamma.logpdf(0, 1)
assert_almost_equal(logpdf, 0)
class TestChi2(object):
# regression tests after precision improvements, ticket:1041, not verified
def test_precision(self):
assert_almost_equal(stats.chi2.pdf(1000, 1000), 8.919133934753128e-003,
decimal=14)
assert_almost_equal(stats.chi2.pdf(100, 100), 0.028162503162596778,
decimal=14)
def test_ppf(self):
# Expected values computed with mpmath.
df = 4.8
x = stats.chi2.ppf(2e-47, df)
assert_allclose(x, 1.098472479575179840604902808e-19, rtol=1e-10)
x = stats.chi2.ppf(0.5, df)
assert_allclose(x, 4.15231407598589358660093156, rtol=1e-10)
df = 13
x = stats.chi2.ppf(2e-77, df)
assert_allclose(x, 1.0106330688195199050507943e-11, rtol=1e-10)
x = stats.chi2.ppf(0.1, df)
assert_allclose(x, 7.041504580095461859307179763, rtol=1e-10)
class TestGumbelL(object):
# gh-6228
def test_cdf_ppf(self):
x = np.linspace(-100, -4)
y = stats.gumbel_l.cdf(x)
xx = stats.gumbel_l.ppf(y)
assert_allclose(x, xx)
def test_logcdf_logsf(self):
x = np.linspace(-100, -4)
y = stats.gumbel_l.logcdf(x)
z = stats.gumbel_l.logsf(x)
u = np.exp(y)
v = -special.expm1(z)
assert_allclose(u, v)
def test_sf_isf(self):
x = np.linspace(-20, 5)
y = stats.gumbel_l.sf(x)
xx = stats.gumbel_l.isf(y)
assert_allclose(x, xx)
class TestLevyStable(object):
def test_fit(self):
# construct data to have percentiles that match
# example in McCulloch 1986.
x = [-.05413,-.05413,
0.,0.,0.,0.,
.00533,.00533,.00533,.00533,.00533,
.03354,.03354,.03354,.03354,.03354,
.05309,.05309,.05309,.05309,.05309]
alpha1, beta1, loc1, scale1 = stats.levy_stable._fitstart(x)
assert_allclose(alpha1, 1.48, rtol=0, atol=0.01)
assert_almost_equal(beta1, -.22, 2)
assert_almost_equal(scale1, 0.01717, 4)
assert_almost_equal(loc1, 0.00233, 2) # to 2 dps due to rounding error in McCulloch86
# cover alpha=2 scenario
x2 = x + [.05309,.05309,.05309,.05309,.05309]
alpha2, beta2, loc2, scale2 = stats.levy_stable._fitstart(x2)
assert_equal(alpha2, 2)
assert_equal(beta2, -1)
assert_almost_equal(scale2, .02503, 4)
assert_almost_equal(loc2, .03354, 4)
@pytest.mark.slow
def test_pdf_nolan_samples(self):
""" Test pdf values against Nolan's stablec.exe output
see - http://fs2.american.edu/jpnolan/www/stable/stable.html
There's a known limitation of Nolan's executable for alpha < 0.2.
Repeat following with beta = -1, -.5, 0, .5 and 1
stablec.exe <<
1 # pdf
1 # Nolan S equivalent to S0 in scipy
.25,2,.25 # alpha
-1,-1,0 # beta
-10,10,1 # x
1,0 # gamma, delta
2 # output file
"""
data = np.load(os.path.abspath(os.path.join(os.path.dirname(__file__),
'data/stable-pdf-sample-data.npy')))
data = np.core.records.fromarrays(data.T, names='x,p,alpha,beta')
# support numpy 1.8.2 for travis
npisin = np.isin if hasattr(np, "isin") else np.in1d
tests = [
# best selects
['best', None, 8, None],
# quadrature is accurate for most alpha except 0.25; perhaps limitation of Nolan stablec?
# we reduce size of x to speed up computation as numerical integration slow.
['quadrature', None, 8, lambda r: (r['alpha'] > 0.25) & (npisin(r['x'], [-10,-5,0,5,10]))],
# zolatarev is accurate except at alpha==1, beta != 0
['zolotarev', None, 8, lambda r: r['alpha'] != 1],
['zolotarev', None, 8, lambda r: (r['alpha'] == 1) & (r['beta'] == 0)],
['zolotarev', None, 1, lambda r: (r['alpha'] == 1) & (r['beta'] != 0)],
# fft accuracy reduces as alpha decreases, fails at low values of alpha and x=0
['fft', 0, 4, lambda r: r['alpha'] > 1],
['fft', 0, 3, lambda r: (r['alpha'] < 1) & (r['alpha'] > 0.25)],
['fft', 0, 1, lambda r: (r['alpha'] == 0.25) & (r['x'] != 0)], # not useful here
]
for ix, (default_method, fft_min_points, decimal_places, filter_func) in enumerate(tests):
stats.levy_stable.pdf_default_method = default_method
stats.levy_stable.pdf_fft_min_points_threshold = fft_min_points
subdata = data[filter_func(data)] if filter_func is not None else data
with suppress_warnings() as sup:
sup.record(RuntimeWarning, "Density calculation unstable for alpha=1 and beta!=0.*")
sup.record(RuntimeWarning, "Density calculations experimental for FFT method.*")
p = stats.levy_stable.pdf(subdata['x'], subdata['alpha'], subdata['beta'], scale=1, loc=0)
subdata2 = rec_append_fields(subdata, 'calc', p)
failures = subdata2[(np.abs(p-subdata['p']) >= 1.5*10.**(-decimal_places)) | np.isnan(p)]
assert_almost_equal(p, subdata['p'], decimal_places, "pdf test %s failed with method '%s'\n%s" % (ix, default_method, failures), verbose=False)
@pytest.mark.slow
def test_cdf_nolan_samples(self):
""" Test cdf values against Nolan's stablec.exe output
see - http://fs2.american.edu/jpnolan/www/stable/stable.html
There's a known limitation of Nolan's executable for alpha < 0.2.
Repeat following with beta = -1, -.5, 0, .5 and 1
stablec.exe <<
2 # cdf
1 # Nolan S equivalent to S0 in scipy
.25,2,.25 # alpha
-1,-1,0 # beta
-10,10,1 # x
1,0 # gamma, delta
2 # output file
"""
data = np.load(os.path.abspath(os.path.join(os.path.dirname(__file__),
'data/stable-cdf-sample-data.npy')))
data = np.core.records.fromarrays(data.T, names='x,p,alpha,beta')
tests = [
# zolatarev is accurate for all values
['zolotarev', None, 8, None],
# fft accuracy poor, very poor alpha < 1
['fft', 0, 2, lambda r: r['alpha'] > 1],
]
for ix, (default_method, fft_min_points, decimal_places, filter_func) in enumerate(tests):
stats.levy_stable.pdf_default_method = default_method
stats.levy_stable.pdf_fft_min_points_threshold = fft_min_points
subdata = data[filter_func(data)] if filter_func is not None else data
with suppress_warnings() as sup:
sup.record(RuntimeWarning, 'FFT method is considered ' +
'experimental for cumulative distribution ' +
'function evaluations.*')
p = stats.levy_stable.cdf(subdata['x'], subdata['alpha'], subdata['beta'], scale=1, loc=0)
subdata2 = rec_append_fields(subdata, 'calc', p)
failures = subdata2[(np.abs(p-subdata['p']) >= 1.5*10.**(-decimal_places)) | np.isnan(p)]
assert_almost_equal(p, subdata['p'], decimal_places, "cdf test %s failed with method '%s'\n%s" % (ix, default_method, failures), verbose=False)
def test_pdf_alpha_equals_one_beta_non_zero(self):
""" sample points extracted from Tables and Graphs of Stable Probability
Density Functions - Donald R Holt - 1973 - p 187.
"""
xs = np.array([0, 0, 0, 0,
1, 1, 1, 1,
2, 2, 2, 2,
3, 3, 3, 3,
4, 4, 4, 4])
density = np.array([.3183, .3096, .2925, .2622,
.1591, .1587, .1599, .1635,
.0637, .0729, .0812, .0955,
.0318, .0390, .0458, .0586,
.0187, .0236, .0285, .0384])
betas = np.array([0, .25, .5, 1,
0, .25, .5, 1,
0, .25, .5, 1,
0, .25, .5, 1,
0, .25, .5, 1])
tests = [
['quadrature', None, 4],
#['fft', 0, 4],
['zolotarev', None, 1],
]
with np.errstate(all='ignore'), suppress_warnings() as sup:
sup.filter(category=RuntimeWarning, message="Density calculation unstable.*")
for default_method, fft_min_points, decimal_places in tests:
stats.levy_stable.pdf_default_method = default_method
stats.levy_stable.pdf_fft_min_points_threshold = fft_min_points
#stats.levy_stable.fft_grid_spacing = 0.0001
pdf = stats.levy_stable.pdf(xs, 1, betas, scale=1, loc=0)
assert_almost_equal(pdf, density, decimal_places, default_method)
def test_stats(self):
param_sets = [
[(1.48,-.22, 0, 1), (0,np.inf,np.NaN,np.NaN)],
[(2,.9, 10, 1.5), (10,4.5,0,0)]
]
for args, exp_stats in param_sets:
calc_stats = stats.levy_stable.stats(args[0], args[1], loc=args[2], scale=args[3], moments='mvsk')
assert_almost_equal(calc_stats, exp_stats)
class TestArrayArgument(object): # test for ticket:992
def setup_method(self):
np.random.seed(1234)
def test_noexception(self):
rvs = stats.norm.rvs(loc=(np.arange(5)), scale=np.ones(5),
size=(10, 5))
assert_equal(rvs.shape, (10, 5))
class TestDocstring(object):
def test_docstrings(self):
# See ticket #761
if stats.rayleigh.__doc__ is not None:
assert_("rayleigh" in stats.rayleigh.__doc__.lower())
if stats.bernoulli.__doc__ is not None:
assert_("bernoulli" in stats.bernoulli.__doc__.lower())
def test_no_name_arg(self):
# If name is not given, construction shouldn't fail. See #1508.
stats.rv_continuous()
stats.rv_discrete()
class TestEntropy(object):
def test_entropy_positive(self):
# See ticket #497
pk = [0.5, 0.2, 0.3]
qk = [0.1, 0.25, 0.65]
eself = stats.entropy(pk, pk)
edouble = stats.entropy(pk, qk)
assert_(0.0 == eself)
assert_(edouble >= 0.0)
def test_entropy_base(self):
pk = np.ones(16, float)
S = stats.entropy(pk, base=2.)
assert_(abs(S - 4.) < 1.e-5)
qk = np.ones(16, float)
qk[:8] = 2.
S = stats.entropy(pk, qk)
S2 = stats.entropy(pk, qk, base=2.)
assert_(abs(S/S2 - np.log(2.)) < 1.e-5)
def test_entropy_zero(self):
# Test for PR-479
assert_almost_equal(stats.entropy([0, 1, 2]), 0.63651416829481278,
decimal=12)
def test_entropy_2d(self):
pk = [[0.1, 0.2], [0.6, 0.3], [0.3, 0.5]]
qk = [[0.2, 0.1], [0.3, 0.6], [0.5, 0.3]]
assert_array_almost_equal(stats.entropy(pk, qk),
[0.1933259, 0.18609809])
def test_entropy_2d_zero(self):
pk = [[0.1, 0.2], [0.6, 0.3], [0.3, 0.5]]
qk = [[0.0, 0.1], [0.3, 0.6], [0.5, 0.3]]
assert_array_almost_equal(stats.entropy(pk, qk),
[np.inf, 0.18609809])
pk[0][0] = 0.0
assert_array_almost_equal(stats.entropy(pk, qk),
[0.17403988, 0.18609809])
def TestArgsreduce():
a = array([1, 3, 2, 1, 2, 3, 3])
b, c = argsreduce(a > 1, a, 2)
assert_array_equal(b, [3, 2, 2, 3, 3])
assert_array_equal(c, [2, 2, 2, 2, 2])
b, c = argsreduce(2 > 1, a, 2)
assert_array_equal(b, a[0])
assert_array_equal(c, [2])
b, c = argsreduce(a > 0, a, 2)
assert_array_equal(b, a)
assert_array_equal(c, [2] * numpy.size(a))
class TestFitMethod(object):
skip = ['ncf']
def setup_method(self):
np.random.seed(1234)
@pytest.mark.slow
@pytest.mark.parametrize('dist,args,alpha', cases_test_all_distributions())
def test_fit(self, dist, args, alpha):
if dist in self.skip:
pytest.skip("%s fit known to fail" % dist)
distfunc = getattr(stats, dist)
with np.errstate(all='ignore'), suppress_warnings() as sup:
sup.filter(category=DeprecationWarning, message=".*frechet_")
res = distfunc.rvs(*args, **{'size': 200})
vals = distfunc.fit(res)
vals2 = distfunc.fit(res, optimizer='powell')
# Only check the length of the return
# FIXME: should check the actual results to see if we are 'close'
# to what was created --- but what is 'close' enough
assert_(len(vals) == 2+len(args))
assert_(len(vals2) == 2+len(args))
@pytest.mark.slow
@pytest.mark.parametrize('dist,args,alpha', cases_test_all_distributions())
def test_fix_fit(self, dist, args, alpha):
# Not sure why 'ncf', and 'beta' are failing
# frechet has different len(args) than distfunc.numargs
if dist in self.skip + ['frechet']:
pytest.skip("%s fit known to fail" % dist)
distfunc = getattr(stats, dist)
with np.errstate(all='ignore'), suppress_warnings() as sup:
sup.filter(category=DeprecationWarning, message=".*frechet_")
res = distfunc.rvs(*args, **{'size': 200})
vals = distfunc.fit(res, floc=0)
vals2 = distfunc.fit(res, fscale=1)
assert_(len(vals) == 2+len(args))
assert_(vals[-2] == 0)
assert_(vals2[-1] == 1)
assert_(len(vals2) == 2+len(args))
if len(args) > 0:
vals3 = distfunc.fit(res, f0=args[0])
assert_(len(vals3) == 2+len(args))
assert_(vals3[0] == args[0])
if len(args) > 1:
vals4 = distfunc.fit(res, f1=args[1])
assert_(len(vals4) == 2+len(args))
assert_(vals4[1] == args[1])
if len(args) > 2:
vals5 = distfunc.fit(res, f2=args[2])
assert_(len(vals5) == 2+len(args))
assert_(vals5[2] == args[2])
def test_fix_fit_2args_lognorm(self):
# Regression test for #1551.
np.random.seed(12345)
with np.errstate(all='ignore'):
x = stats.lognorm.rvs(0.25, 0., 20.0, size=20)
expected_shape = np.sqrt(((np.log(x) - np.log(20))**2).mean())
assert_allclose(np.array(stats.lognorm.fit(x, floc=0, fscale=20)),
[expected_shape, 0, 20], atol=1e-8)
def test_fix_fit_norm(self):
x = np.arange(1, 6)
loc, scale = stats.norm.fit(x)
assert_almost_equal(loc, 3)
assert_almost_equal(scale, np.sqrt(2))
loc, scale = stats.norm.fit(x, floc=2)
assert_equal(loc, 2)
assert_equal(scale, np.sqrt(3))
loc, scale = stats.norm.fit(x, fscale=2)
assert_almost_equal(loc, 3)
assert_equal(scale, 2)
def test_fix_fit_gamma(self):
x = np.arange(1, 6)
meanlog = np.log(x).mean()
# A basic test of gamma.fit with floc=0.
floc = 0
a, loc, scale = stats.gamma.fit(x, floc=floc)
s = np.log(x.mean()) - meanlog
assert_almost_equal(np.log(a) - special.digamma(a), s, decimal=5)
assert_equal(loc, floc)
assert_almost_equal(scale, x.mean()/a, decimal=8)
# Regression tests for gh-2514.
# The problem was that if `floc=0` was given, any other fixed
# parameters were ignored.
f0 = 1
floc = 0
a, loc, scale = stats.gamma.fit(x, f0=f0, floc=floc)
assert_equal(a, f0)
assert_equal(loc, floc)
assert_almost_equal(scale, x.mean()/a, decimal=8)
f0 = 2
floc = 0
a, loc, scale = stats.gamma.fit(x, f0=f0, floc=floc)
assert_equal(a, f0)
assert_equal(loc, floc)
assert_almost_equal(scale, x.mean()/a, decimal=8)
# loc and scale fixed.
floc = 0
fscale = 2
a, loc, scale = stats.gamma.fit(x, floc=floc, fscale=fscale)
assert_equal(loc, floc)
assert_equal(scale, fscale)
c = meanlog - np.log(fscale)
assert_almost_equal(special.digamma(a), c)
def test_fix_fit_beta(self):
# Test beta.fit when both floc and fscale are given.
def mlefunc(a, b, x):
# Zeros of this function are critical points of
# the maximum likelihood function.
n = len(x)
s1 = np.log(x).sum()
s2 = np.log(1-x).sum()
psiab = special.psi(a + b)
func = [s1 - n * (-psiab + special.psi(a)),
s2 - n * (-psiab + special.psi(b))]
return func
# Basic test with floc and fscale given.
x = np.array([0.125, 0.25, 0.5])
a, b, loc, scale = stats.beta.fit(x, floc=0, fscale=1)
assert_equal(loc, 0)
assert_equal(scale, 1)
assert_allclose(mlefunc(a, b, x), [0, 0], atol=1e-6)
# Basic test with f0, floc and fscale given.
# This is also a regression test for gh-2514.
x = np.array([0.125, 0.25, 0.5])
a, b, loc, scale = stats.beta.fit(x, f0=2, floc=0, fscale=1)
assert_equal(a, 2)
assert_equal(loc, 0)
assert_equal(scale, 1)
da, db = mlefunc(a, b, x)
assert_allclose(db, 0, atol=1e-5)
# Same floc and fscale values as above, but reverse the data
# and fix b (f1).
x2 = 1 - x
a2, b2, loc2, scale2 = stats.beta.fit(x2, f1=2, floc=0, fscale=1)
assert_equal(b2, 2)
assert_equal(loc2, 0)
assert_equal(scale2, 1)
da, db = mlefunc(a2, b2, x2)
assert_allclose(da, 0, atol=1e-5)
# a2 of this test should equal b from above.
assert_almost_equal(a2, b)
# Check for detection of data out of bounds when floc and fscale
# are given.
assert_raises(ValueError, stats.beta.fit, x, floc=0.5, fscale=1)
y = np.array([0, .5, 1])
assert_raises(ValueError, stats.beta.fit, y, floc=0, fscale=1)
assert_raises(ValueError, stats.beta.fit, y, floc=0, fscale=1, f0=2)
assert_raises(ValueError, stats.beta.fit, y, floc=0, fscale=1, f1=2)
# Check that attempting to fix all the parameters raises a ValueError.
assert_raises(ValueError, stats.beta.fit, y, f0=0, f1=1,
floc=2, fscale=3)
def test_expon_fit(self):
x = np.array([2, 2, 4, 4, 4, 4, 4, 8])
loc, scale = stats.expon.fit(x)
assert_equal(loc, 2) # x.min()
assert_equal(scale, 2) # x.mean() - x.min()
loc, scale = stats.expon.fit(x, fscale=3)
assert_equal(loc, 2) # x.min()
assert_equal(scale, 3) # fscale
loc, scale = stats.expon.fit(x, floc=0)
assert_equal(loc, 0) # floc
assert_equal(scale, 4) # x.mean() - loc
def test_lognorm_fit(self):
x = np.array([1.5, 3, 10, 15, 23, 59])
lnxm1 = np.log(x - 1)
shape, loc, scale = stats.lognorm.fit(x, floc=1)
assert_allclose(shape, lnxm1.std(), rtol=1e-12)
assert_equal(loc, 1)
assert_allclose(scale, np.exp(lnxm1.mean()), rtol=1e-12)
shape, loc, scale = stats.lognorm.fit(x, floc=1, fscale=6)
assert_allclose(shape, np.sqrt(((lnxm1 - np.log(6))**2).mean()),
rtol=1e-12)
assert_equal(loc, 1)
assert_equal(scale, 6)
shape, loc, scale = stats.lognorm.fit(x, floc=1, fix_s=0.75)
assert_equal(shape, 0.75)
assert_equal(loc, 1)
assert_allclose(scale, np.exp(lnxm1.mean()), rtol=1e-12)
def test_uniform_fit(self):
x = np.array([1.0, 1.1, 1.2, 9.0])
loc, scale = stats.uniform.fit(x)
assert_equal(loc, x.min())
assert_equal(scale, x.ptp())
loc, scale = stats.uniform.fit(x, floc=0)
assert_equal(loc, 0)
assert_equal(scale, x.max())
loc, scale = stats.uniform.fit(x, fscale=10)
assert_equal(loc, 0)
assert_equal(scale, 10)
assert_raises(ValueError, stats.uniform.fit, x, floc=2.0)
assert_raises(ValueError, stats.uniform.fit, x, fscale=5.0)
def test_fshapes(self):
# take a beta distribution, with shapes='a, b', and make sure that
# fa is equivalent to f0, and fb is equivalent to f1
a, b = 3., 4.
x = stats.beta.rvs(a, b, size=100, random_state=1234)
res_1 = stats.beta.fit(x, f0=3.)
res_2 = stats.beta.fit(x, fa=3.)
assert_allclose(res_1, res_2, atol=1e-12, rtol=1e-12)
res_2 = stats.beta.fit(x, fix_a=3.)
assert_allclose(res_1, res_2, atol=1e-12, rtol=1e-12)
res_3 = stats.beta.fit(x, f1=4.)
res_4 = stats.beta.fit(x, fb=4.)
assert_allclose(res_3, res_4, atol=1e-12, rtol=1e-12)
res_4 = stats.beta.fit(x, fix_b=4.)
assert_allclose(res_3, res_4, atol=1e-12, rtol=1e-12)
# cannot specify both positional and named args at the same time
assert_raises(ValueError, stats.beta.fit, x, fa=1, f0=2)
# check that attempting to fix all parameters raises a ValueError
assert_raises(ValueError, stats.beta.fit, x, fa=0, f1=1,
floc=2, fscale=3)
# check that specifying floc, fscale and fshapes works for
# beta and gamma which override the generic fit method
res_5 = stats.beta.fit(x, fa=3., floc=0, fscale=1)
aa, bb, ll, ss = res_5
assert_equal([aa, ll, ss], [3., 0, 1])
# gamma distribution
a = 3.
data = stats.gamma.rvs(a, size=100)
aa, ll, ss = stats.gamma.fit(data, fa=a)
assert_equal(aa, a)
def test_extra_params(self):
# unknown parameters should raise rather than be silently ignored
dist = stats.exponnorm
data = dist.rvs(K=2, size=100)
dct = dict(enikibeniki=-101)
assert_raises(TypeError, dist.fit, data, **dct)
class TestFrozen(object):
def setup_method(self):
np.random.seed(1234)
# Test that a frozen distribution gives the same results as the original
# object.
#
# Only tested for the normal distribution (with loc and scale specified)
# and for the gamma distribution (with a shape parameter specified).
def test_norm(self):
dist = stats.norm
frozen = stats.norm(loc=10.0, scale=3.0)
result_f = frozen.pdf(20.0)
result = dist.pdf(20.0, loc=10.0, scale=3.0)
assert_equal(result_f, result)
result_f = frozen.cdf(20.0)
result = dist.cdf(20.0, loc=10.0, scale=3.0)
assert_equal(result_f, result)
result_f = frozen.ppf(0.25)
result = dist.ppf(0.25, loc=10.0, scale=3.0)
assert_equal(result_f, result)
result_f = frozen.isf(0.25)
result = dist.isf(0.25, loc=10.0, scale=3.0)
assert_equal(result_f, result)
result_f = frozen.sf(10.0)
result = dist.sf(10.0, loc=10.0, scale=3.0)
assert_equal(result_f, result)
result_f = frozen.median()
result = dist.median(loc=10.0, scale=3.0)
assert_equal(result_f, result)
result_f = frozen.mean()
result = dist.mean(loc=10.0, scale=3.0)
assert_equal(result_f, result)
result_f = frozen.var()
result = dist.var(loc=10.0, scale=3.0)
assert_equal(result_f, result)
result_f = frozen.std()
result = dist.std(loc=10.0, scale=3.0)
assert_equal(result_f, result)
result_f = frozen.entropy()
result = dist.entropy(loc=10.0, scale=3.0)
assert_equal(result_f, result)
result_f = frozen.moment(2)
result = dist.moment(2, loc=10.0, scale=3.0)
assert_equal(result_f, result)
assert_equal(frozen.a, dist.a)
assert_equal(frozen.b, dist.b)
def test_gamma(self):
a = 2.0
dist = stats.gamma
frozen = stats.gamma(a)
result_f = frozen.pdf(20.0)
result = dist.pdf(20.0, a)
assert_equal(result_f, result)
result_f = frozen.cdf(20.0)
result = dist.cdf(20.0, a)
assert_equal(result_f, result)
result_f = frozen.ppf(0.25)
result = dist.ppf(0.25, a)
assert_equal(result_f, result)
result_f = frozen.isf(0.25)
result = dist.isf(0.25, a)
assert_equal(result_f, result)
result_f = frozen.sf(10.0)
result = dist.sf(10.0, a)
assert_equal(result_f, result)
result_f = frozen.median()
result = dist.median(a)
assert_equal(result_f, result)
result_f = frozen.mean()
result = dist.mean(a)
assert_equal(result_f, result)
result_f = frozen.var()
result = dist.var(a)
assert_equal(result_f, result)
result_f = frozen.std()
result = dist.std(a)
assert_equal(result_f, result)
result_f = frozen.entropy()
result = dist.entropy(a)
assert_equal(result_f, result)
result_f = frozen.moment(2)
result = dist.moment(2, a)
assert_equal(result_f, result)
assert_equal(frozen.a, frozen.dist.a)
assert_equal(frozen.b, frozen.dist.b)
def test_regression_ticket_1293(self):
# Create a frozen distribution.
frozen = stats.lognorm(1)
# Call one of its methods that does not take any keyword arguments.
m1 = frozen.moment(2)
# Now call a method that takes a keyword argument.
frozen.stats(moments='mvsk')
# Call moment(2) again.
# After calling stats(), the following was raising an exception.
# So this test passes if the following does not raise an exception.
m2 = frozen.moment(2)
# The following should also be true, of course. But it is not
# the focus of this test.
assert_equal(m1, m2)
def test_ab(self):
# test that the support of a frozen distribution
# (i) remains frozen even if it changes for the original one
# (ii) is actually correct if the shape parameters are such that
# the values of [a, b] are not the default [0, inf]
# take a genpareto as an example where the support
# depends on the value of the shape parameter:
# for c > 0: a, b = 0, inf
# for c < 0: a, b = 0, -1/c
c = -0.1
rv = stats.genpareto(c=c)
a, b = rv.dist._get_support(c)
assert_equal([a, b], [0., 10.])
c = 0.1
stats.genpareto.pdf(0, c=c)
assert_equal(rv.dist._get_support(c), [0, np.inf])
rv1 = stats.genpareto(c=0.1)
assert_(rv1.dist is not rv.dist)
def test_rv_frozen_in_namespace(self):
# Regression test for gh-3522
assert_(hasattr(stats.distributions, 'rv_frozen'))
def test_random_state(self):
# only check that the random_state attribute exists,
frozen = stats.norm()
assert_(hasattr(frozen, 'random_state'))
# ... that it can be set,
frozen.random_state = 42
assert_equal(frozen.random_state.get_state(),
np.random.RandomState(42).get_state())
# ... and that .rvs method accepts it as an argument
rndm = np.random.RandomState(1234)
frozen.rvs(size=8, random_state=rndm)
def test_pickling(self):
# test that a frozen instance pickles and unpickles
# (this method is a clone of common_tests.check_pickling)
beta = stats.beta(2.3098496451481823, 0.62687954300963677)
poiss = stats.poisson(3.)
sample = stats.rv_discrete(values=([0, 1, 2, 3],
[0.1, 0.2, 0.3, 0.4]))
for distfn in [beta, poiss, sample]:
distfn.random_state = 1234
distfn.rvs(size=8)
s = pickle.dumps(distfn)
r0 = distfn.rvs(size=8)
unpickled = pickle.loads(s)
r1 = unpickled.rvs(size=8)
assert_equal(r0, r1)
# also smoke test some methods
medians = [distfn.ppf(0.5), unpickled.ppf(0.5)]
assert_equal(medians[0], medians[1])
assert_equal(distfn.cdf(medians[0]),
unpickled.cdf(medians[1]))
def test_expect(self):
# smoke test the expect method of the frozen distribution
# only take a gamma w/loc and scale and poisson with loc specified
def func(x):
return x
gm = stats.gamma(a=2, loc=3, scale=4)
gm_val = gm.expect(func, lb=1, ub=2, conditional=True)
gamma_val = stats.gamma.expect(func, args=(2,), loc=3, scale=4,
lb=1, ub=2, conditional=True)
assert_allclose(gm_val, gamma_val)
p = stats.poisson(3, loc=4)
p_val = p.expect(func)
poisson_val = stats.poisson.expect(func, args=(3,), loc=4)
assert_allclose(p_val, poisson_val)
class TestExpect(object):
# Test for expect method.
#
# Uses normal distribution and beta distribution for finite bounds, and
# hypergeom for discrete distribution with finite support
def test_norm(self):
v = stats.norm.expect(lambda x: (x-5)*(x-5), loc=5, scale=2)
assert_almost_equal(v, 4, decimal=14)
m = stats.norm.expect(lambda x: (x), loc=5, scale=2)
assert_almost_equal(m, 5, decimal=14)
lb = stats.norm.ppf(0.05, loc=5, scale=2)
ub = stats.norm.ppf(0.95, loc=5, scale=2)
prob90 = stats.norm.expect(lambda x: 1, loc=5, scale=2, lb=lb, ub=ub)
assert_almost_equal(prob90, 0.9, decimal=14)
prob90c = stats.norm.expect(lambda x: 1, loc=5, scale=2, lb=lb, ub=ub,
conditional=True)
assert_almost_equal(prob90c, 1., decimal=14)
def test_beta(self):
# case with finite support interval
v = stats.beta.expect(lambda x: (x-19/3.)*(x-19/3.), args=(10, 5),
loc=5, scale=2)
assert_almost_equal(v, 1./18., decimal=13)
m = stats.beta.expect(lambda x: x, args=(10, 5), loc=5., scale=2.)
assert_almost_equal(m, 19/3., decimal=13)
ub = stats.beta.ppf(0.95, 10, 10, loc=5, scale=2)
lb = stats.beta.ppf(0.05, 10, 10, loc=5, scale=2)
prob90 = stats.beta.expect(lambda x: 1., args=(10, 10), loc=5.,
scale=2., lb=lb, ub=ub, conditional=False)
assert_almost_equal(prob90, 0.9, decimal=13)
prob90c = stats.beta.expect(lambda x: 1, args=(10, 10), loc=5,
scale=2, lb=lb, ub=ub, conditional=True)
assert_almost_equal(prob90c, 1., decimal=13)
def test_hypergeom(self):
# test case with finite bounds
# without specifying bounds
m_true, v_true = stats.hypergeom.stats(20, 10, 8, loc=5.)
m = stats.hypergeom.expect(lambda x: x, args=(20, 10, 8), loc=5.)
assert_almost_equal(m, m_true, decimal=13)
v = stats.hypergeom.expect(lambda x: (x-9.)**2, args=(20, 10, 8),
loc=5.)
assert_almost_equal(v, v_true, decimal=14)
# with bounds, bounds equal to shifted support
v_bounds = stats.hypergeom.expect(lambda x: (x-9.)**2,
args=(20, 10, 8),
loc=5., lb=5, ub=13)
assert_almost_equal(v_bounds, v_true, decimal=14)
# drop boundary points
prob_true = 1-stats.hypergeom.pmf([5, 13], 20, 10, 8, loc=5).sum()
prob_bounds = stats.hypergeom.expect(lambda x: 1, args=(20, 10, 8),
loc=5., lb=6, ub=12)
assert_almost_equal(prob_bounds, prob_true, decimal=13)
# conditional
prob_bc = stats.hypergeom.expect(lambda x: 1, args=(20, 10, 8), loc=5.,
lb=6, ub=12, conditional=True)
assert_almost_equal(prob_bc, 1, decimal=14)
# check simple integral
prob_b = stats.hypergeom.expect(lambda x: 1, args=(20, 10, 8),
lb=0, ub=8)
assert_almost_equal(prob_b, 1, decimal=13)
def test_poisson(self):
# poisson, use lower bound only
prob_bounds = stats.poisson.expect(lambda x: 1, args=(2,), lb=3,
conditional=False)
prob_b_true = 1-stats.poisson.cdf(2, 2)
assert_almost_equal(prob_bounds, prob_b_true, decimal=14)
prob_lb = stats.poisson.expect(lambda x: 1, args=(2,), lb=2,
conditional=True)
assert_almost_equal(prob_lb, 1, decimal=14)
def test_genhalflogistic(self):
# genhalflogistic, changes upper bound of support in _argcheck
# regression test for gh-2622
halflog = stats.genhalflogistic
# check consistency when calling expect twice with the same input
res1 = halflog.expect(args=(1.5,))
halflog.expect(args=(0.5,))
res2 = halflog.expect(args=(1.5,))
assert_almost_equal(res1, res2, decimal=14)
def test_rice_overflow(self):
# rice.pdf(999, 0.74) was inf since special.i0 silentyly overflows
# check that using i0e fixes it
assert_(np.isfinite(stats.rice.pdf(999, 0.74)))
assert_(np.isfinite(stats.rice.expect(lambda x: 1, args=(0.74,))))
assert_(np.isfinite(stats.rice.expect(lambda x: 2, args=(0.74,))))
assert_(np.isfinite(stats.rice.expect(lambda x: 3, args=(0.74,))))
def test_logser(self):
# test a discrete distribution with infinite support and loc
p, loc = 0.3, 3
res_0 = stats.logser.expect(lambda k: k, args=(p,))
# check against the correct answer (sum of a geom series)
assert_allclose(res_0,
p / (p - 1.) / np.log(1. - p), atol=1e-15)
# now check it with `loc`
res_l = stats.logser.expect(lambda k: k, args=(p,), loc=loc)
assert_allclose(res_l, res_0 + loc, atol=1e-15)
def test_skellam(self):
# Use a discrete distribution w/ bi-infinite support. Compute two first
# moments and compare to known values (cf skellam.stats)
p1, p2 = 18, 22
m1 = stats.skellam.expect(lambda x: x, args=(p1, p2))
m2 = stats.skellam.expect(lambda x: x**2, args=(p1, p2))
assert_allclose(m1, p1 - p2, atol=1e-12)
assert_allclose(m2 - m1**2, p1 + p2, atol=1e-12)
def test_randint(self):
# Use a discrete distribution w/ parameter-dependent support, which
# is larger than the default chunksize
lo, hi = 0, 113
res = stats.randint.expect(lambda x: x, (lo, hi))
assert_allclose(res,
sum(_ for _ in range(lo, hi)) / (hi - lo), atol=1e-15)
def test_zipf(self):
# Test that there is no infinite loop even if the sum diverges
assert_warns(RuntimeWarning, stats.zipf.expect,
lambda x: x**2, (2,))
def test_discrete_kwds(self):
# check that discrete expect accepts keywords to control the summation
n0 = stats.poisson.expect(lambda x: 1, args=(2,))
n1 = stats.poisson.expect(lambda x: 1, args=(2,),
maxcount=1001, chunksize=32, tolerance=1e-8)
assert_almost_equal(n0, n1, decimal=14)
def test_moment(self):
# test the .moment() method: compute a higher moment and compare to
# a known value
def poiss_moment5(mu):
return mu**5 + 10*mu**4 + 25*mu**3 + 15*mu**2 + mu
for mu in [5, 7]:
m5 = stats.poisson.moment(5, mu)
assert_allclose(m5, poiss_moment5(mu), rtol=1e-10)
class TestNct(object):
def test_nc_parameter(self):
# Parameter values c<=0 were not enabled (gh-2402).
# For negative values c and for c=0 results of rv.cdf(0) below were nan
rv = stats.nct(5, 0)
assert_equal(rv.cdf(0), 0.5)
rv = stats.nct(5, -1)
assert_almost_equal(rv.cdf(0), 0.841344746069, decimal=10)
def test_broadcasting(self):
res = stats.nct.pdf(5, np.arange(4, 7)[:, None],
np.linspace(0.1, 1, 4))
expected = array([[0.00321886, 0.00557466, 0.00918418, 0.01442997],
[0.00217142, 0.00395366, 0.00683888, 0.01126276],
[0.00153078, 0.00291093, 0.00525206, 0.00900815]])
assert_allclose(res, expected, rtol=1e-5)
def test_variance_gh_issue_2401(self):
# Computation of the variance of a non-central t-distribution resulted
# in a TypeError: ufunc 'isinf' not supported for the input types,
# and the inputs could not be safely coerced to any supported types
# according to the casting rule 'safe'
rv = stats.nct(4, 0)
assert_equal(rv.var(), 2.0)
def test_nct_inf_moments(self):
# n-th moment of nct only exists for df > n
m, v, s, k = stats.nct.stats(df=1.9, nc=0.3, moments='mvsk')
assert_(np.isfinite(m))
assert_equal([v, s, k], [np.inf, np.nan, np.nan])
m, v, s, k = stats.nct.stats(df=3.1, nc=0.3, moments='mvsk')
assert_(np.isfinite([m, v, s]).all())
assert_equal(k, np.nan)
class TestRice(object):
def test_rice_zero_b(self):
# rice distribution should work with b=0, cf gh-2164
x = [0.2, 1., 5.]
assert_(np.isfinite(stats.rice.pdf(x, b=0.)).all())
assert_(np.isfinite(stats.rice.logpdf(x, b=0.)).all())
assert_(np.isfinite(stats.rice.cdf(x, b=0.)).all())
assert_(np.isfinite(stats.rice.logcdf(x, b=0.)).all())
q = [0.1, 0.1, 0.5, 0.9]
assert_(np.isfinite(stats.rice.ppf(q, b=0.)).all())
mvsk = stats.rice.stats(0, moments='mvsk')
assert_(np.isfinite(mvsk).all())
# furthermore, pdf is continuous as b\to 0
# rice.pdf(x, b\to 0) = x exp(-x^2/2) + O(b^2)
# see e.g. Abramovich & Stegun 9.6.7 & 9.6.10
b = 1e-8
assert_allclose(stats.rice.pdf(x, 0), stats.rice.pdf(x, b),
atol=b, rtol=0)
def test_rice_rvs(self):
rvs = stats.rice.rvs
assert_equal(rvs(b=3.).size, 1)
assert_equal(rvs(b=3., size=(3, 5)).shape, (3, 5))
class TestErlang(object):
def setup_method(self):
np.random.seed(1234)
def test_erlang_runtimewarning(self):
# erlang should generate a RuntimeWarning if a non-integer
# shape parameter is used.
with warnings.catch_warnings():
warnings.simplefilter("error", RuntimeWarning)
# The non-integer shape parameter 1.3 should trigger a
# RuntimeWarning
assert_raises(RuntimeWarning,
stats.erlang.rvs, 1.3, loc=0, scale=1, size=4)
# Calling the fit method with `f0` set to an integer should
# *not* trigger a RuntimeWarning. It should return the same
# values as gamma.fit(...).
data = [0.5, 1.0, 2.0, 4.0]
result_erlang = stats.erlang.fit(data, f0=1)
result_gamma = stats.gamma.fit(data, f0=1)
assert_allclose(result_erlang, result_gamma, rtol=1e-3)
class TestRayleigh(object):
# gh-6227
def test_logpdf(self):
y = stats.rayleigh.logpdf(50)
assert_allclose(y, -1246.0879769945718)
def test_logsf(self):
y = stats.rayleigh.logsf(50)
assert_allclose(y, -1250)
class TestExponWeib(object):
def test_pdf_logpdf(self):
# Regression test for gh-3508.
x = 0.1
a = 1.0
c = 100.0
p = stats.exponweib.pdf(x, a, c)
logp = stats.exponweib.logpdf(x, a, c)
# Expected values were computed with mpmath.
assert_allclose([p, logp],
[1.0000000000000054e-97, -223.35075402042244])
def test_a_is_1(self):
# For issue gh-3508.
# Check that when a=1, the pdf and logpdf methods of exponweib are the
# same as those of weibull_min.
x = np.logspace(-4, -1, 4)
a = 1
c = 100
p = stats.exponweib.pdf(x, a, c)
expected = stats.weibull_min.pdf(x, c)
assert_allclose(p, expected)
logp = stats.exponweib.logpdf(x, a, c)
expected = stats.weibull_min.logpdf(x, c)
assert_allclose(logp, expected)
def test_a_is_1_c_is_1(self):
# When a = 1 and c = 1, the distribution is exponential.
x = np.logspace(-8, 1, 10)
a = 1
c = 1
p = stats.exponweib.pdf(x, a, c)
expected = stats.expon.pdf(x)
assert_allclose(p, expected)
logp = stats.exponweib.logpdf(x, a, c)
expected = stats.expon.logpdf(x)
assert_allclose(logp, expected)
class TestWeibull(object):
def test_logpdf(self):
# gh-6217
y = stats.weibull_min.logpdf(0, 1)
assert_equal(y, 0)
def test_with_maxima_distrib(self):
# Tests for weibull_min and weibull_max.
# The expected values were computed using the symbolic algebra
# program 'maxima' with the package 'distrib', which has
# 'pdf_weibull' and 'cdf_weibull'. The mapping between the
# scipy and maxima functions is as follows:
# -----------------------------------------------------------------
# scipy maxima
# --------------------------------- ------------------------------
# weibull_min.pdf(x, a, scale=b) pdf_weibull(x, a, b)
# weibull_min.logpdf(x, a, scale=b) log(pdf_weibull(x, a, b))
# weibull_min.cdf(x, a, scale=b) cdf_weibull(x, a, b)
# weibull_min.logcdf(x, a, scale=b) log(cdf_weibull(x, a, b))
# weibull_min.sf(x, a, scale=b) 1 - cdf_weibull(x, a, b)
# weibull_min.logsf(x, a, scale=b) log(1 - cdf_weibull(x, a, b))
#
# weibull_max.pdf(x, a, scale=b) pdf_weibull(-x, a, b)
# weibull_max.logpdf(x, a, scale=b) log(pdf_weibull(-x, a, b))
# weibull_max.cdf(x, a, scale=b) 1 - cdf_weibull(-x, a, b)
# weibull_max.logcdf(x, a, scale=b) log(1 - cdf_weibull(-x, a, b))
# weibull_max.sf(x, a, scale=b) cdf_weibull(-x, a, b)
# weibull_max.logsf(x, a, scale=b) log(cdf_weibull(-x, a, b))
# -----------------------------------------------------------------
x = 1.5
a = 2.0
b = 3.0
# weibull_min
p = stats.weibull_min.pdf(x, a, scale=b)
assert_allclose(p, np.exp(-0.25)/3)
lp = stats.weibull_min.logpdf(x, a, scale=b)
assert_allclose(lp, -0.25 - np.log(3))
c = stats.weibull_min.cdf(x, a, scale=b)
assert_allclose(c, -special.expm1(-0.25))
lc = stats.weibull_min.logcdf(x, a, scale=b)
assert_allclose(lc, np.log(-special.expm1(-0.25)))
s = stats.weibull_min.sf(x, a, scale=b)
assert_allclose(s, np.exp(-0.25))
ls = stats.weibull_min.logsf(x, a, scale=b)
assert_allclose(ls, -0.25)
# Also test using a large value x, for which computing the survival
# function using the CDF would result in 0.
s = stats.weibull_min.sf(30, 2, scale=3)
assert_allclose(s, np.exp(-100))
ls = stats.weibull_min.logsf(30, 2, scale=3)
assert_allclose(ls, -100)
# weibull_max
x = -1.5
p = stats.weibull_max.pdf(x, a, scale=b)
assert_allclose(p, np.exp(-0.25)/3)
lp = stats.weibull_max.logpdf(x, a, scale=b)
assert_allclose(lp, -0.25 - np.log(3))
c = stats.weibull_max.cdf(x, a, scale=b)
assert_allclose(c, np.exp(-0.25))
lc = stats.weibull_max.logcdf(x, a, scale=b)
assert_allclose(lc, -0.25)
s = stats.weibull_max.sf(x, a, scale=b)
assert_allclose(s, -special.expm1(-0.25))
ls = stats.weibull_max.logsf(x, a, scale=b)
assert_allclose(ls, np.log(-special.expm1(-0.25)))
# Also test using a value of x close to 0, for which computing the
# survival function using the CDF would result in 0.
s = stats.weibull_max.sf(-1e-9, 2, scale=3)
assert_allclose(s, -special.expm1(-1/9000000000000000000))
ls = stats.weibull_max.logsf(-1e-9, 2, scale=3)
assert_allclose(ls, np.log(-special.expm1(-1/9000000000000000000)))
class TestRdist(object):
@pytest.mark.slow
def test_rdist_cdf_gh1285(self):
# check workaround in rdist._cdf for issue gh-1285.
distfn = stats.rdist
values = [0.001, 0.5, 0.999]
assert_almost_equal(distfn.cdf(distfn.ppf(values, 541.0), 541.0),
values, decimal=5)
class TestTrapz(object):
def test_reduces_to_triang(self):
modes = [0, 0.3, 0.5, 1]
for mode in modes:
x = [0, mode, 1]
assert_almost_equal(stats.trapz.pdf(x, mode, mode),
stats.triang.pdf(x, mode))
assert_almost_equal(stats.trapz.cdf(x, mode, mode),
stats.triang.cdf(x, mode))
def test_reduces_to_uniform(self):
x = np.linspace(0, 1, 10)
assert_almost_equal(stats.trapz.pdf(x, 0, 1), stats.uniform.pdf(x))
assert_almost_equal(stats.trapz.cdf(x, 0, 1), stats.uniform.cdf(x))
def test_cases(self):
# edge cases
assert_almost_equal(stats.trapz.pdf(0, 0, 0), 2)
assert_almost_equal(stats.trapz.pdf(1, 1, 1), 2)
assert_almost_equal(stats.trapz.pdf(0.5, 0, 0.8),
1.11111111111111111)
assert_almost_equal(stats.trapz.pdf(0.5, 0.2, 1.0),
1.11111111111111111)
# straightforward case
assert_almost_equal(stats.trapz.pdf(0.1, 0.2, 0.8), 0.625)
assert_almost_equal(stats.trapz.pdf(0.5, 0.2, 0.8), 1.25)
assert_almost_equal(stats.trapz.pdf(0.9, 0.2, 0.8), 0.625)
assert_almost_equal(stats.trapz.cdf(0.1, 0.2, 0.8), 0.03125)
assert_almost_equal(stats.trapz.cdf(0.2, 0.2, 0.8), 0.125)
assert_almost_equal(stats.trapz.cdf(0.5, 0.2, 0.8), 0.5)
assert_almost_equal(stats.trapz.cdf(0.9, 0.2, 0.8), 0.96875)
assert_almost_equal(stats.trapz.cdf(1.0, 0.2, 0.8), 1.0)
def test_trapz_vect(self):
# test that array-valued shapes and arguments are handled
c = np.array([0.1, 0.2, 0.3])
d = np.array([0.5, 0.6])[:, None]
x = np.array([0.15, 0.25, 0.9])
v = stats.trapz.pdf(x, c, d)
cc, dd, xx = np.broadcast_arrays(c, d, x)
res = np.empty(xx.size, dtype=xx.dtype)
ind = np.arange(xx.size)
for i, x1, c1, d1 in zip(ind, xx.ravel(), cc.ravel(), dd.ravel()):
res[i] = stats.trapz.pdf(x1, c1, d1)
assert_allclose(v, res.reshape(v.shape), atol=1e-15)
class TestTriang(object):
def test_edge_cases(self):
with np.errstate(all='raise'):
assert_equal(stats.triang.pdf(0, 0), 2.)
assert_equal(stats.triang.pdf(0.5, 0), 1.)
assert_equal(stats.triang.pdf(1, 0), 0.)
assert_equal(stats.triang.pdf(0, 1), 0)
assert_equal(stats.triang.pdf(0.5, 1), 1.)
assert_equal(stats.triang.pdf(1, 1), 2)
assert_equal(stats.triang.cdf(0., 0.), 0.)
assert_equal(stats.triang.cdf(0.5, 0.), 0.75)
assert_equal(stats.triang.cdf(1.0, 0.), 1.0)
assert_equal(stats.triang.cdf(0., 1.), 0.)
assert_equal(stats.triang.cdf(0.5, 1.), 0.25)
assert_equal(stats.triang.cdf(1., 1.), 1)
def test_540_567():
# test for nan returned in tickets 540, 567
assert_almost_equal(stats.norm.cdf(-1.7624320982), 0.03899815971089126,
decimal=10, err_msg='test_540_567')
assert_almost_equal(stats.norm.cdf(-1.7624320983), 0.038998159702449846,
decimal=10, err_msg='test_540_567')
assert_almost_equal(stats.norm.cdf(1.38629436112, loc=0.950273420309,
scale=0.204423758009),
0.98353464004309321,
decimal=10, err_msg='test_540_567')
def test_regression_ticket_1316():
# The following was raising an exception, because _construct_default_doc()
# did not handle the default keyword extradoc=None. See ticket #1316.
g = stats._continuous_distns.gamma_gen(name='gamma')
def test_regression_ticket_1326():
# adjust to avoid nan with 0*log(0)
assert_almost_equal(stats.chi2.pdf(0.0, 2), 0.5, 14)
def test_regression_tukey_lambda():
# Make sure that Tukey-Lambda distribution correctly handles
# non-positive lambdas.
x = np.linspace(-5.0, 5.0, 101)
olderr = np.seterr(divide='ignore')
try:
for lam in [0.0, -1.0, -2.0, np.array([[-1.0], [0.0], [-2.0]])]:
p = stats.tukeylambda.pdf(x, lam)
assert_((p != 0.0).all())
assert_(~np.isnan(p).all())
lam = np.array([[-1.0], [0.0], [2.0]])
p = stats.tukeylambda.pdf(x, lam)
finally:
np.seterr(**olderr)
assert_(~np.isnan(p).all())
assert_((p[0] != 0.0).all())
assert_((p[1] != 0.0).all())
assert_((p[2] != 0.0).any())
assert_((p[2] == 0.0).any())
@pytest.mark.skipif(DOCSTRINGS_STRIPPED, reason="docstrings stripped")
def test_regression_ticket_1421():
assert_('pdf(x, mu, loc=0, scale=1)' not in stats.poisson.__doc__)
assert_('pmf(x,' in stats.poisson.__doc__)
def test_nan_arguments_gh_issue_1362():
with np.errstate(invalid='ignore'):
assert_(np.isnan(stats.t.logcdf(1, np.nan)))
assert_(np.isnan(stats.t.cdf(1, np.nan)))
assert_(np.isnan(stats.t.logsf(1, np.nan)))
assert_(np.isnan(stats.t.sf(1, np.nan)))
assert_(np.isnan(stats.t.pdf(1, np.nan)))
assert_(np.isnan(stats.t.logpdf(1, np.nan)))
assert_(np.isnan(stats.t.ppf(1, np.nan)))
assert_(np.isnan(stats.t.isf(1, np.nan)))
assert_(np.isnan(stats.bernoulli.logcdf(np.nan, 0.5)))
assert_(np.isnan(stats.bernoulli.cdf(np.nan, 0.5)))
assert_(np.isnan(stats.bernoulli.logsf(np.nan, 0.5)))
assert_(np.isnan(stats.bernoulli.sf(np.nan, 0.5)))
assert_(np.isnan(stats.bernoulli.pmf(np.nan, 0.5)))
assert_(np.isnan(stats.bernoulli.logpmf(np.nan, 0.5)))
assert_(np.isnan(stats.bernoulli.ppf(np.nan, 0.5)))
assert_(np.isnan(stats.bernoulli.isf(np.nan, 0.5)))
def test_frozen_fit_ticket_1536():
np.random.seed(5678)
true = np.array([0.25, 0., 0.5])
x = stats.lognorm.rvs(true[0], true[1], true[2], size=100)
olderr = np.seterr(divide='ignore')
try:
params = np.array(stats.lognorm.fit(x, floc=0.))
finally:
np.seterr(**olderr)
assert_almost_equal(params, true, decimal=2)
params = np.array(stats.lognorm.fit(x, fscale=0.5, loc=0))
assert_almost_equal(params, true, decimal=2)
params = np.array(stats.lognorm.fit(x, f0=0.25, loc=0))
assert_almost_equal(params, true, decimal=2)
params = np.array(stats.lognorm.fit(x, f0=0.25, floc=0))
assert_almost_equal(params, true, decimal=2)
np.random.seed(5678)
loc = 1
floc = 0.9
x = stats.norm.rvs(loc, 2., size=100)
params = np.array(stats.norm.fit(x, floc=floc))
expected = np.array([floc, np.sqrt(((x-floc)**2).mean())])
assert_almost_equal(params, expected, decimal=4)
def test_regression_ticket_1530():
# Check the starting value works for Cauchy distribution fit.
np.random.seed(654321)
rvs = stats.cauchy.rvs(size=100)
params = stats.cauchy.fit(rvs)
expected = (0.045, 1.142)
assert_almost_equal(params, expected, decimal=1)
def test_gh_pr_4806():
# Check starting values for Cauchy distribution fit.
np.random.seed(1234)
x = np.random.randn(42)
for offset in 10000.0, 1222333444.0:
loc, scale = stats.cauchy.fit(x + offset)
assert_allclose(loc, offset, atol=1.0)
assert_allclose(scale, 0.6, atol=1.0)
def test_tukeylambda_stats_ticket_1545():
# Some test for the variance and kurtosis of the Tukey Lambda distr.
# See test_tukeylamdba_stats.py for more tests.
mv = stats.tukeylambda.stats(0, moments='mvsk')
# Known exact values:
expected = [0, np.pi**2/3, 0, 1.2]
assert_almost_equal(mv, expected, decimal=10)
mv = stats.tukeylambda.stats(3.13, moments='mvsk')
# 'expected' computed with mpmath.
expected = [0, 0.0269220858861465102, 0, -0.898062386219224104]
assert_almost_equal(mv, expected, decimal=10)
mv = stats.tukeylambda.stats(0.14, moments='mvsk')
# 'expected' computed with mpmath.
expected = [0, 2.11029702221450250, 0, -0.02708377353223019456]
assert_almost_equal(mv, expected, decimal=10)
def test_poisson_logpmf_ticket_1436():
assert_(np.isfinite(stats.poisson.logpmf(1500, 200)))
def test_powerlaw_stats():
"""Test the powerlaw stats function.
This unit test is also a regression test for ticket 1548.
The exact values are:
mean:
mu = a / (a + 1)
variance:
sigma**2 = a / ((a + 2) * (a + 1) ** 2)
skewness:
One formula (see https://en.wikipedia.org/wiki/Skewness) is
gamma_1 = (E[X**3] - 3*mu*E[X**2] + 2*mu**3) / sigma**3
A short calculation shows that E[X**k] is a / (a + k), so gamma_1
can be implemented as
n = a/(a+3) - 3*(a/(a+1))*a/(a+2) + 2*(a/(a+1))**3
d = sqrt(a/((a+2)*(a+1)**2)) ** 3
gamma_1 = n/d
Either by simplifying, or by a direct calculation of mu_3 / sigma**3,
one gets the more concise formula:
gamma_1 = -2.0 * ((a - 1) / (a + 3)) * sqrt((a + 2) / a)
kurtosis: (See https://en.wikipedia.org/wiki/Kurtosis)
The excess kurtosis is
gamma_2 = mu_4 / sigma**4 - 3
A bit of calculus and algebra (sympy helps) shows that
mu_4 = 3*a*(3*a**2 - a + 2) / ((a+1)**4 * (a+2) * (a+3) * (a+4))
so
gamma_2 = 3*(3*a**2 - a + 2) * (a+2) / (a*(a+3)*(a+4)) - 3
which can be rearranged to
gamma_2 = 6 * (a**3 - a**2 - 6*a + 2) / (a*(a+3)*(a+4))
"""
cases = [(1.0, (0.5, 1./12, 0.0, -1.2)),
(2.0, (2./3, 2./36, -0.56568542494924734, -0.6))]
for a, exact_mvsk in cases:
mvsk = stats.powerlaw.stats(a, moments="mvsk")
assert_array_almost_equal(mvsk, exact_mvsk)
def test_powerlaw_edge():
# Regression test for gh-3986.
p = stats.powerlaw.logpdf(0, 1)
assert_equal(p, 0.0)
def test_exponpow_edge():
# Regression test for gh-3982.
p = stats.exponpow.logpdf(0, 1)
assert_equal(p, 0.0)
# Check pdf and logpdf at x = 0 for other values of b.
p = stats.exponpow.pdf(0, [0.25, 1.0, 1.5])
assert_equal(p, [np.inf, 1.0, 0.0])
p = stats.exponpow.logpdf(0, [0.25, 1.0, 1.5])
assert_equal(p, [np.inf, 0.0, -np.inf])
def test_gengamma_edge():
# Regression test for gh-3985.
p = stats.gengamma.pdf(0, 1, 1)
assert_equal(p, 1.0)
# Regression tests for gh-4724.
p = stats.gengamma._munp(-2, 200, 1.)
assert_almost_equal(p, 1./199/198)
p = stats.gengamma._munp(-2, 10, 1.)
assert_almost_equal(p, 1./9/8)
def test_ksone_fit_freeze():
# Regression test for ticket #1638.
d = np.array(
[-0.18879233, 0.15734249, 0.18695107, 0.27908787, -0.248649,
-0.2171497, 0.12233512, 0.15126419, 0.03119282, 0.4365294,
0.08930393, -0.23509903, 0.28231224, -0.09974875, -0.25196048,
0.11102028, 0.1427649, 0.10176452, 0.18754054, 0.25826724,
0.05988819, 0.0531668, 0.21906056, 0.32106729, 0.2117662,
0.10886442, 0.09375789, 0.24583286, -0.22968366, -0.07842391,
-0.31195432, -0.21271196, 0.1114243, -0.13293002, 0.01331725,
-0.04330977, -0.09485776, -0.28434547, 0.22245721, -0.18518199,
-0.10943985, -0.35243174, 0.06897665, -0.03553363, -0.0701746,
-0.06037974, 0.37670779, -0.21684405])
try:
olderr = np.seterr(invalid='ignore')
with suppress_warnings() as sup:
sup.filter(IntegrationWarning,
"The maximum number of subdivisions .50. has been "
"achieved.")
sup.filter(RuntimeWarning,
"floating point number truncated to an integer")
stats.ksone.fit(d)
finally:
np.seterr(**olderr)
def test_norm_logcdf():
# Test precision of the logcdf of the normal distribution.
# This precision was enhanced in ticket 1614.
x = -np.asarray(list(range(0, 120, 4)))
# Values from R
expected = [-0.69314718, -10.36010149, -35.01343716, -75.41067300,
-131.69539607, -203.91715537, -292.09872100, -396.25241451,
-516.38564863, -652.50322759, -804.60844201, -972.70364403,
-1156.79057310, -1356.87055173, -1572.94460885, -1805.01356068,
-2053.07806561, -2317.13866238, -2597.19579746, -2893.24984493,
-3205.30112136, -3533.34989701, -3877.39640444, -4237.44084522,
-4613.48339520, -5005.52420869, -5413.56342187, -5837.60115548,
-6277.63751711, -6733.67260303]
assert_allclose(stats.norm().logcdf(x), expected, atol=1e-8)
# also test the complex-valued code path
assert_allclose(stats.norm().logcdf(x + 1e-14j).real, expected, atol=1e-8)
# test the accuracy: d(logcdf)/dx = pdf / cdf \equiv exp(logpdf - logcdf)
deriv = (stats.norm.logcdf(x + 1e-10j)/1e-10).imag
deriv_expected = np.exp(stats.norm.logpdf(x) - stats.norm.logcdf(x))
assert_allclose(deriv, deriv_expected, atol=1e-10)
def test_levy_cdf_ppf():
# Test levy.cdf, including small arguments.
x = np.array([1000, 1.0, 0.5, 0.1, 0.01, 0.001])
# Expected values were calculated separately with mpmath.
# E.g.
# >>> mpmath.mp.dps = 100
# >>> x = mpmath.mp.mpf('0.01')
# >>> cdf = mpmath.erfc(mpmath.sqrt(1/(2*x)))
expected = np.array([0.9747728793699604,
0.3173105078629141,
0.1572992070502851,
0.0015654022580025495,
1.523970604832105e-23,
1.795832784800726e-219])
y = stats.levy.cdf(x)
assert_allclose(y, expected, rtol=1e-10)
# ppf(expected) should get us back to x.
xx = stats.levy.ppf(expected)
assert_allclose(xx, x, rtol=1e-13)
def test_hypergeom_interval_1802():
# these two had endless loops
assert_equal(stats.hypergeom.interval(.95, 187601, 43192, 757),
(152.0, 197.0))
assert_equal(stats.hypergeom.interval(.945, 187601, 43192, 757),
(152.0, 197.0))
# this was working also before
assert_equal(stats.hypergeom.interval(.94, 187601, 43192, 757),
(153.0, 196.0))
# degenerate case .a == .b
assert_equal(stats.hypergeom.ppf(0.02, 100, 100, 8), 8)
assert_equal(stats.hypergeom.ppf(1, 100, 100, 8), 8)
def test_distribution_too_many_args():
np.random.seed(1234)
# Check that a TypeError is raised when too many args are given to a method
# Regression test for ticket 1815.
x = np.linspace(0.1, 0.7, num=5)
assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, loc=1.0)
assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, 4, loc=1.0)
assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, 4, 5)
assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, loc=1.0, scale=0.5)
assert_raises(TypeError, stats.gamma.rvs, 2., 3, loc=1.0, scale=0.5)
assert_raises(TypeError, stats.gamma.cdf, x, 2., 3, loc=1.0, scale=0.5)
assert_raises(TypeError, stats.gamma.ppf, x, 2., 3, loc=1.0, scale=0.5)
assert_raises(TypeError, stats.gamma.stats, 2., 3, loc=1.0, scale=0.5)
assert_raises(TypeError, stats.gamma.entropy, 2., 3, loc=1.0, scale=0.5)
assert_raises(TypeError, stats.gamma.fit, x, 2., 3, loc=1.0, scale=0.5)
# These should not give errors
stats.gamma.pdf(x, 2, 3) # loc=3
stats.gamma.pdf(x, 2, 3, 4) # loc=3, scale=4
stats.gamma.stats(2., 3)
stats.gamma.stats(2., 3, 4)
stats.gamma.stats(2., 3, 4, 'mv')
stats.gamma.rvs(2., 3, 4, 5)
stats.gamma.fit(stats.gamma.rvs(2., size=7), 2.)
# Also for a discrete distribution
stats.geom.pmf(x, 2, loc=3) # no error, loc=3
assert_raises(TypeError, stats.geom.pmf, x, 2, 3, 4)
assert_raises(TypeError, stats.geom.pmf, x, 2, 3, loc=4)
# And for distributions with 0, 2 and 3 args respectively
assert_raises(TypeError, stats.expon.pdf, x, 3, loc=1.0)
assert_raises(TypeError, stats.exponweib.pdf, x, 3, 4, 5, loc=1.0)
assert_raises(TypeError, stats.exponweib.pdf, x, 3, 4, 5, 0.1, 0.1)
assert_raises(TypeError, stats.ncf.pdf, x, 3, 4, 5, 6, loc=1.0)
assert_raises(TypeError, stats.ncf.pdf, x, 3, 4, 5, 6, 1.0, scale=0.5)
stats.ncf.pdf(x, 3, 4, 5, 6, 1.0) # 3 args, plus loc/scale
def test_ncx2_tails_ticket_955():
# Trac #955 -- check that the cdf computed by special functions
# matches the integrated pdf
a = stats.ncx2.cdf(np.arange(20, 25, 0.2), 2, 1.07458615e+02)
b = stats.ncx2._cdfvec(np.arange(20, 25, 0.2), 2, 1.07458615e+02)
assert_allclose(a, b, rtol=1e-3, atol=0)
def test_ncx2_tails_pdf():
# ncx2.pdf does not return nans in extreme tails(example from gh-1577)
# NB: this is to check that nan_to_num is not needed in ncx2.pdf
with suppress_warnings() as sup:
sup.filter(RuntimeWarning, "divide by zero encountered in log")
assert_equal(stats.ncx2.pdf(1, np.arange(340, 350), 2), 0)
logval = stats.ncx2.logpdf(1, np.arange(340, 350), 2)
assert_(np.isneginf(logval).all())
def test_foldnorm_zero():
# Parameter value c=0 was not enabled, see gh-2399.
rv = stats.foldnorm(0, scale=1)
assert_equal(rv.cdf(0), 0) # rv.cdf(0) previously resulted in: nan
def test_stats_shapes_argcheck():
# stats method was failing for vector shapes if some of the values
# were outside of the allowed range, see gh-2678
mv3 = stats.invgamma.stats([0.0, 0.5, 1.0], 1, 0.5) # 0 is not a legal `a`
mv2 = stats.invgamma.stats([0.5, 1.0], 1, 0.5)
mv2_augmented = tuple(np.r_[np.nan, _] for _ in mv2)
assert_equal(mv2_augmented, mv3)
# -1 is not a legal shape parameter
mv3 = stats.lognorm.stats([2, 2.4, -1])
mv2 = stats.lognorm.stats([2, 2.4])
mv2_augmented = tuple(np.r_[_, np.nan] for _ in mv2)
assert_equal(mv2_augmented, mv3)
# FIXME: this is only a quick-and-dirty test of a quick-and-dirty bugfix.
# stats method with multiple shape parameters is not properly vectorized
# anyway, so some distributions may or may not fail.
# Test subclassing distributions w/ explicit shapes
class _distr_gen(stats.rv_continuous):
def _pdf(self, x, a):
return 42
class _distr2_gen(stats.rv_continuous):
def _cdf(self, x, a):
return 42 * a + x
class _distr3_gen(stats.rv_continuous):
def _pdf(self, x, a, b):
return a + b
def _cdf(self, x, a):
# Different # of shape params from _pdf, to be able to check that
# inspection catches the inconsistency."""
return 42 * a + x
class _distr6_gen(stats.rv_continuous):
# Two shape parameters (both _pdf and _cdf defined, consistent shapes.)
def _pdf(self, x, a, b):
return a*x + b
def _cdf(self, x, a, b):
return 42 * a + x
class TestSubclassingExplicitShapes(object):
# Construct a distribution w/ explicit shapes parameter and test it.
def test_correct_shapes(self):
dummy_distr = _distr_gen(name='dummy', shapes='a')
assert_equal(dummy_distr.pdf(1, a=1), 42)
def test_wrong_shapes_1(self):
dummy_distr = _distr_gen(name='dummy', shapes='A')
assert_raises(TypeError, dummy_distr.pdf, 1, **dict(a=1))
def test_wrong_shapes_2(self):
dummy_distr = _distr_gen(name='dummy', shapes='a, b, c')
dct = dict(a=1, b=2, c=3)
assert_raises(TypeError, dummy_distr.pdf, 1, **dct)
def test_shapes_string(self):
# shapes must be a string
dct = dict(name='dummy', shapes=42)
assert_raises(TypeError, _distr_gen, **dct)
def test_shapes_identifiers_1(self):
# shapes must be a comma-separated list of valid python identifiers
dct = dict(name='dummy', shapes='(!)')
assert_raises(SyntaxError, _distr_gen, **dct)
def test_shapes_identifiers_2(self):
dct = dict(name='dummy', shapes='4chan')
assert_raises(SyntaxError, _distr_gen, **dct)
def test_shapes_identifiers_3(self):
dct = dict(name='dummy', shapes='m(fti)')
assert_raises(SyntaxError, _distr_gen, **dct)
def test_shapes_identifiers_nodefaults(self):
dct = dict(name='dummy', shapes='a=2')
assert_raises(SyntaxError, _distr_gen, **dct)
def test_shapes_args(self):
dct = dict(name='dummy', shapes='*args')
assert_raises(SyntaxError, _distr_gen, **dct)
def test_shapes_kwargs(self):
dct = dict(name='dummy', shapes='**kwargs')
assert_raises(SyntaxError, _distr_gen, **dct)
def test_shapes_keywords(self):
# python keywords cannot be used for shape parameters
dct = dict(name='dummy', shapes='a, b, c, lambda')
assert_raises(SyntaxError, _distr_gen, **dct)
def test_shapes_signature(self):
# test explicit shapes which agree w/ the signature of _pdf
class _dist_gen(stats.rv_continuous):
def _pdf(self, x, a):
return stats.norm._pdf(x) * a
dist = _dist_gen(shapes='a')
assert_equal(dist.pdf(0.5, a=2), stats.norm.pdf(0.5)*2)
def test_shapes_signature_inconsistent(self):
# test explicit shapes which do not agree w/ the signature of _pdf
class _dist_gen(stats.rv_continuous):
def _pdf(self, x, a):
return stats.norm._pdf(x) * a
dist = _dist_gen(shapes='a, b')
assert_raises(TypeError, dist.pdf, 0.5, **dict(a=1, b=2))
def test_star_args(self):
# test _pdf with only starargs
# NB: **kwargs of pdf will never reach _pdf
class _dist_gen(stats.rv_continuous):
def _pdf(self, x, *args):
extra_kwarg = args[0]
return stats.norm._pdf(x) * extra_kwarg
dist = _dist_gen(shapes='extra_kwarg')
assert_equal(dist.pdf(0.5, extra_kwarg=33), stats.norm.pdf(0.5)*33)
assert_equal(dist.pdf(0.5, 33), stats.norm.pdf(0.5)*33)
assert_raises(TypeError, dist.pdf, 0.5, **dict(xxx=33))
def test_star_args_2(self):
# test _pdf with named & starargs
# NB: **kwargs of pdf will never reach _pdf
class _dist_gen(stats.rv_continuous):
def _pdf(self, x, offset, *args):
extra_kwarg = args[0]
return stats.norm._pdf(x) * extra_kwarg + offset
dist = _dist_gen(shapes='offset, extra_kwarg')
assert_equal(dist.pdf(0.5, offset=111, extra_kwarg=33),
stats.norm.pdf(0.5)*33 + 111)
assert_equal(dist.pdf(0.5, 111, 33),
stats.norm.pdf(0.5)*33 + 111)
def test_extra_kwarg(self):
# **kwargs to _pdf are ignored.
# this is a limitation of the framework (_pdf(x, *goodargs))
class _distr_gen(stats.rv_continuous):
def _pdf(self, x, *args, **kwargs):
# _pdf should handle *args, **kwargs itself. Here "handling"
# is ignoring *args and looking for ``extra_kwarg`` and using
# that.
extra_kwarg = kwargs.pop('extra_kwarg', 1)
return stats.norm._pdf(x) * extra_kwarg
dist = _distr_gen(shapes='extra_kwarg')
assert_equal(dist.pdf(1, extra_kwarg=3), stats.norm.pdf(1))
def shapes_empty_string(self):
# shapes='' is equivalent to shapes=None
class _dist_gen(stats.rv_continuous):
def _pdf(self, x):
return stats.norm.pdf(x)
dist = _dist_gen(shapes='')
assert_equal(dist.pdf(0.5), stats.norm.pdf(0.5))
class TestSubclassingNoShapes(object):
# Construct a distribution w/o explicit shapes parameter and test it.
def test_only__pdf(self):
dummy_distr = _distr_gen(name='dummy')
assert_equal(dummy_distr.pdf(1, a=1), 42)
def test_only__cdf(self):
# _pdf is determined from _cdf by taking numerical derivative
dummy_distr = _distr2_gen(name='dummy')
assert_almost_equal(dummy_distr.pdf(1, a=1), 1)
@pytest.mark.skipif(DOCSTRINGS_STRIPPED, reason="docstring stripped")
def test_signature_inspection(self):
# check that _pdf signature inspection works correctly, and is used in
# the class docstring
dummy_distr = _distr_gen(name='dummy')
assert_equal(dummy_distr.numargs, 1)
assert_equal(dummy_distr.shapes, 'a')
res = re.findall(r'logpdf\(x, a, loc=0, scale=1\)',
dummy_distr.__doc__)
assert_(len(res) == 1)
@pytest.mark.skipif(DOCSTRINGS_STRIPPED, reason="docstring stripped")
def test_signature_inspection_2args(self):
# same for 2 shape params and both _pdf and _cdf defined
dummy_distr = _distr6_gen(name='dummy')
assert_equal(dummy_distr.numargs, 2)
assert_equal(dummy_distr.shapes, 'a, b')
res = re.findall(r'logpdf\(x, a, b, loc=0, scale=1\)',
dummy_distr.__doc__)
assert_(len(res) == 1)
def test_signature_inspection_2args_incorrect_shapes(self):
# both _pdf and _cdf defined, but shapes are inconsistent: raises
assert_raises(TypeError, _distr3_gen, name='dummy')
def test_defaults_raise(self):
# default arguments should raise
class _dist_gen(stats.rv_continuous):
def _pdf(self, x, a=42):
return 42
assert_raises(TypeError, _dist_gen, **dict(name='dummy'))
def test_starargs_raise(self):
# without explicit shapes, *args are not allowed
class _dist_gen(stats.rv_continuous):
def _pdf(self, x, a, *args):
return 42
assert_raises(TypeError, _dist_gen, **dict(name='dummy'))
def test_kwargs_raise(self):
# without explicit shapes, **kwargs are not allowed
class _dist_gen(stats.rv_continuous):
def _pdf(self, x, a, **kwargs):
return 42
assert_raises(TypeError, _dist_gen, **dict(name='dummy'))
@pytest.mark.skipif(DOCSTRINGS_STRIPPED, reason="docstring stripped")
def test_docstrings():
badones = [r',\s*,', r'\(\s*,', r'^\s*:']
for distname in stats.__all__:
dist = getattr(stats, distname)
if isinstance(dist, (stats.rv_discrete, stats.rv_continuous)):
for regex in badones:
assert_(re.search(regex, dist.__doc__) is None)
def test_infinite_input():
assert_almost_equal(stats.skellam.sf(np.inf, 10, 11), 0)
assert_almost_equal(stats.ncx2._cdf(np.inf, 8, 0.1), 1)
def test_lomax_accuracy():
# regression test for gh-4033
p = stats.lomax.ppf(stats.lomax.cdf(1e-100, 1), 1)
assert_allclose(p, 1e-100)
def test_gompertz_accuracy():
# Regression test for gh-4031
p = stats.gompertz.ppf(stats.gompertz.cdf(1e-100, 1), 1)
assert_allclose(p, 1e-100)
def test_truncexpon_accuracy():
# regression test for gh-4035
p = stats.truncexpon.ppf(stats.truncexpon.cdf(1e-100, 1), 1)
assert_allclose(p, 1e-100)
def test_rayleigh_accuracy():
# regression test for gh-4034
p = stats.rayleigh.isf(stats.rayleigh.sf(9, 1), 1)
assert_almost_equal(p, 9.0, decimal=15)
def test_genextreme_give_no_warnings():
"""regression test for gh-6219"""
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
p = stats.genextreme.cdf(.5, 0)
p = stats.genextreme.pdf(.5, 0)
p = stats.genextreme.ppf(.5, 0)
p = stats.genextreme.logpdf(-np.inf, 0.0)
number_of_warnings_thrown = len(w)
assert_equal(number_of_warnings_thrown, 0)
def test_genextreme_entropy():
# regression test for gh-5181
euler_gamma = 0.5772156649015329
h = stats.genextreme.entropy(-1.0)
assert_allclose(h, 2*euler_gamma + 1, rtol=1e-14)
h = stats.genextreme.entropy(0)
assert_allclose(h, euler_gamma + 1, rtol=1e-14)
h = stats.genextreme.entropy(1.0)
assert_equal(h, 1)
h = stats.genextreme.entropy(-2.0, scale=10)
assert_allclose(h, euler_gamma*3 + np.log(10) + 1, rtol=1e-14)
h = stats.genextreme.entropy(10)
assert_allclose(h, -9*euler_gamma + 1, rtol=1e-14)
h = stats.genextreme.entropy(-10)
assert_allclose(h, 11*euler_gamma + 1, rtol=1e-14)
def test_genextreme_sf_isf():
# Expected values were computed using mpmath:
#
# import mpmath
#
# def mp_genextreme_sf(x, xi, mu=0, sigma=1):
# # Formula from wikipedia, which has a sign convention for xi that
# # is the opposite of scipy's shape parameter.
# if xi != 0:
# t = mpmath.power(1 + ((x - mu)/sigma)*xi, -1/xi)
# else:
# t = mpmath.exp(-(x - mu)/sigma)
# return 1 - mpmath.exp(-t)
#
# >>> mpmath.mp.dps = 1000
# >>> s = mp_genextreme_sf(mpmath.mp.mpf("1e8"), mpmath.mp.mpf("0.125"))
# >>> float(s)
# 1.6777205262585625e-57
# >>> s = mp_genextreme_sf(mpmath.mp.mpf("7.98"), mpmath.mp.mpf("-0.125"))
# >>> float(s)
# 1.52587890625e-21
# >>> s = mp_genextreme_sf(mpmath.mp.mpf("7.98"), mpmath.mp.mpf("0"))
# >>> float(s)
# 0.00034218086528426593
x = 1e8
s = stats.genextreme.sf(x, -0.125)
assert_allclose(s, 1.6777205262585625e-57)
x2 = stats.genextreme.isf(s, -0.125)
assert_allclose(x2, x)
x = 7.98
s = stats.genextreme.sf(x, 0.125)
assert_allclose(s, 1.52587890625e-21)
x2 = stats.genextreme.isf(s, 0.125)
assert_allclose(x2, x)
x = 7.98
s = stats.genextreme.sf(x, 0)
assert_allclose(s, 0.00034218086528426593)
x2 = stats.genextreme.isf(s, 0)
assert_allclose(x2, x)
def test_burr12_ppf_small_arg():
prob = 1e-16
quantile = stats.burr12.ppf(prob, 2, 3)
# The expected quantile was computed using mpmath:
# >>> import mpmath
# >>> mpmath.mp.dps = 100
# >>> prob = mpmath.mpf('1e-16')
# >>> c = mpmath.mpf(2)
# >>> d = mpmath.mpf(3)
# >>> float(((1-prob)**(-1/d) - 1)**(1/c))
# 5.7735026918962575e-09
assert_allclose(quantile, 5.7735026918962575e-09)
def test_crystalball_function():
"""
All values are calculated using the independent implementation of the
ROOT framework (see https://root.cern.ch/).
Corresponding ROOT code is given in the comments.
"""
X = np.linspace(-5.0, 5.0, 21)[:-1]
# for(float x = -5.0; x < 5.0; x+=0.5)
# std::cout << ROOT::Math::crystalball_pdf(x, 1.0, 2.0, 1.0) << ", ";
calculated = stats.crystalball.pdf(X, beta=1.0, m=2.0)
expected = np.array([0.0202867, 0.0241428, 0.0292128, 0.0360652, 0.045645,
0.059618, 0.0811467, 0.116851, 0.18258, 0.265652,
0.301023, 0.265652, 0.18258, 0.097728, 0.0407391,
0.013226, 0.00334407, 0.000658486, 0.000100982,
1.20606e-05])
assert_allclose(expected, calculated, rtol=0.001)
# for(float x = -5.0; x < 5.0; x+=0.5)
# std::cout << ROOT::Math::crystalball_pdf(x, 2.0, 3.0, 1.0) << ", ";
calculated = stats.crystalball.pdf(X, beta=2.0, m=3.0)
expected = np.array([0.0019648, 0.00279754, 0.00417592, 0.00663121,
0.0114587, 0.0223803, 0.0530497, 0.12726, 0.237752,
0.345928, 0.391987, 0.345928, 0.237752, 0.12726,
0.0530497, 0.0172227, 0.00435458, 0.000857469,
0.000131497, 1.57051e-05])
assert_allclose(expected, calculated, rtol=0.001)
# for(float x = -5.0; x < 5.0; x+=0.5) {
# std::cout << ROOT::Math::crystalball_pdf(x, 2.0, 3.0, 2.0, 0.5);
# std::cout << ", ";
# }
calculated = stats.crystalball.pdf(X, beta=2.0, m=3.0, loc=0.5, scale=2.0)
expected = np.array([0.00785921, 0.0111902, 0.0167037, 0.0265249,
0.0423866, 0.0636298, 0.0897324, 0.118876, 0.147944,
0.172964, 0.189964, 0.195994, 0.189964, 0.172964,
0.147944, 0.118876, 0.0897324, 0.0636298, 0.0423866,
0.0265249])
assert_allclose(expected, calculated, rtol=0.001)
# for(float x = -5.0; x < 5.0; x+=0.5)
# std::cout << ROOT::Math::crystalball_cdf(x, 1.0, 2.0, 1.0) << ", ";
calculated = stats.crystalball.cdf(X, beta=1.0, m=2.0)
expected = np.array([0.12172, 0.132785, 0.146064, 0.162293, 0.18258,
0.208663, 0.24344, 0.292128, 0.36516, 0.478254,
0.622723, 0.767192, 0.880286, 0.94959, 0.982834,
0.995314, 0.998981, 0.999824, 0.999976, 0.999997])
assert_allclose(expected, calculated, rtol=0.001)
# for(float x = -5.0; x < 5.0; x+=0.5)
# std::cout << ROOT::Math::crystalball_cdf(x, 2.0, 3.0, 1.0) << ", ";
calculated = stats.crystalball.cdf(X, beta=2.0, m=3.0)
expected = np.array([0.00442081, 0.00559509, 0.00730787, 0.00994682,
0.0143234, 0.0223803, 0.0397873, 0.0830763, 0.173323,
0.320592, 0.508717, 0.696841, 0.844111, 0.934357,
0.977646, 0.993899, 0.998674, 0.999771, 0.999969,
0.999997])
assert_allclose(expected, calculated, rtol=0.001)
# for(float x = -5.0; x < 5.0; x+=0.5) {
# std::cout << ROOT::Math::crystalball_cdf(x, 2.0, 3.0, 2.0, 0.5);
# std::cout << ", ";
# }
calculated = stats.crystalball.cdf(X, beta=2.0, m=3.0, loc=0.5, scale=2.0)
expected = np.array([0.0176832, 0.0223803, 0.0292315, 0.0397873, 0.0567945,
0.0830763, 0.121242, 0.173323, 0.24011, 0.320592,
0.411731, 0.508717, 0.605702, 0.696841, 0.777324,
0.844111, 0.896192, 0.934357, 0.960639, 0.977646])
assert_allclose(expected, calculated, rtol=0.001)
def test_crystalball_function_moments():
"""
All values are calculated using the pdf formula and the integrate function
of Mathematica
"""
# The Last two (alpha, n) pairs test the special case n == alpha**2
beta = np.array([2.0, 1.0, 3.0, 2.0, 3.0])
m = np.array([3.0, 3.0, 2.0, 4.0, 9.0])
# The distribution should be correctly normalised
expected_0th_moment = np.array([1.0, 1.0, 1.0, 1.0, 1.0])
calculated_0th_moment = stats.crystalball._munp(0, beta, m)
assert_allclose(expected_0th_moment, calculated_0th_moment, rtol=0.001)
# calculated using wolframalpha.com
# e.g. for beta = 2 and m = 3 we calculate the norm like this:
# integrate exp(-x^2/2) from -2 to infinity +
# integrate (3/2)^3*exp(-2^2/2)*(3/2-2-x)^(-3) from -infinity to -2
norm = np.array([2.5511, 3.01873, 2.51065, 2.53983, 2.507410455])
a = np.array([-0.21992, -3.03265, np.inf, -0.135335, -0.003174])
expected_1th_moment = a / norm
calculated_1th_moment = stats.crystalball._munp(1, beta, m)
assert_allclose(expected_1th_moment, calculated_1th_moment, rtol=0.001)
a = np.array([np.inf, np.inf, np.inf, 3.2616, 2.519908])
expected_2th_moment = a / norm
calculated_2th_moment = stats.crystalball._munp(2, beta, m)
assert_allclose(expected_2th_moment, calculated_2th_moment, rtol=0.001)
a = np.array([np.inf, np.inf, np.inf, np.inf, -0.0577668])
expected_3th_moment = a / norm
calculated_3th_moment = stats.crystalball._munp(3, beta, m)
assert_allclose(expected_3th_moment, calculated_3th_moment, rtol=0.001)
a = np.array([np.inf, np.inf, np.inf, np.inf, 7.78468])
expected_4th_moment = a / norm
calculated_4th_moment = stats.crystalball._munp(4, beta, m)
assert_allclose(expected_4th_moment, calculated_4th_moment, rtol=0.001)
a = np.array([np.inf, np.inf, np.inf, np.inf, -1.31086])
expected_5th_moment = a / norm
calculated_5th_moment = stats.crystalball._munp(5, beta, m)
assert_allclose(expected_5th_moment, calculated_5th_moment, rtol=0.001)
def test_argus_function():
# There is no usable reference implementation.
# (RootFit implementation returns unreasonable results which are not
# normalized correctly.)
# Instead we do some tests if the distribution behaves as expected for
# different shapes and scales.
for i in range(1, 10):
for j in range(1, 10):
assert_equal(stats.argus.pdf(i + 0.001, chi=j, scale=i), 0.0)
assert_(stats.argus.pdf(i - 0.001, chi=j, scale=i) > 0.0)
assert_equal(stats.argus.pdf(-0.001, chi=j, scale=i), 0.0)
assert_(stats.argus.pdf(+0.001, chi=j, scale=i) > 0.0)
for i in range(1, 10):
assert_equal(stats.argus.cdf(1.0, chi=i), 1.0)
assert_equal(stats.argus.cdf(1.0, chi=i),
1.0 - stats.argus.sf(1.0, chi=i))
class TestHistogram(object):
def setup_method(self):
np.random.seed(1234)
# We have 8 bins
# [1,2), [2,3), [3,4), [4,5), [5,6), [6,7), [7,8), [8,9)
# But actually np.histogram will put the last 9 also in the [8,9) bin!
# Therefore there is a slight difference below for the last bin, from
# what you might have expected.
histogram = np.histogram([1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5,
6, 6, 6, 6, 7, 7, 7, 8, 8, 9], bins=8)
self.template = stats.rv_histogram(histogram)
data = stats.norm.rvs(loc=1.0, scale=2.5, size=10000, random_state=123)
norm_histogram = np.histogram(data, bins=50)
self.norm_template = stats.rv_histogram(norm_histogram)
def test_pdf(self):
values = np.array([0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5,
5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5])
pdf_values = np.asarray([0.0/25.0, 0.0/25.0, 1.0/25.0, 1.0/25.0,
2.0/25.0, 2.0/25.0, 3.0/25.0, 3.0/25.0,
4.0/25.0, 4.0/25.0, 5.0/25.0, 5.0/25.0,
4.0/25.0, 4.0/25.0, 3.0/25.0, 3.0/25.0,
3.0/25.0, 3.0/25.0, 0.0/25.0, 0.0/25.0])
assert_allclose(self.template.pdf(values), pdf_values)
# Test explicitly the corner cases:
# As stated above the pdf in the bin [8,9) is greater than
# one would naively expect because np.histogram putted the 9
# into the [8,9) bin.
assert_almost_equal(self.template.pdf(8.0), 3.0/25.0)
assert_almost_equal(self.template.pdf(8.5), 3.0/25.0)
# 9 is outside our defined bins [8,9) hence the pdf is already 0
# for a continuous distribution this is fine, because a single value
# does not have a finite probability!
assert_almost_equal(self.template.pdf(9.0), 0.0/25.0)
assert_almost_equal(self.template.pdf(10.0), 0.0/25.0)
x = np.linspace(-2, 2, 10)
assert_allclose(self.norm_template.pdf(x),
stats.norm.pdf(x, loc=1.0, scale=2.5), rtol=0.1)
def test_cdf_ppf(self):
values = np.array([0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5,
5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5])
cdf_values = np.asarray([0.0/25.0, 0.0/25.0, 0.0/25.0, 0.5/25.0,
1.0/25.0, 2.0/25.0, 3.0/25.0, 4.5/25.0,
6.0/25.0, 8.0/25.0, 10.0/25.0, 12.5/25.0,
15.0/25.0, 17.0/25.0, 19.0/25.0, 20.5/25.0,
22.0/25.0, 23.5/25.0, 25.0/25.0, 25.0/25.0])
assert_allclose(self.template.cdf(values), cdf_values)
# First three and last two values in cdf_value are not unique
assert_allclose(self.template.ppf(cdf_values[2:-1]), values[2:-1])
# Test of cdf and ppf are inverse functions
x = np.linspace(1.0, 9.0, 100)
assert_allclose(self.template.ppf(self.template.cdf(x)), x)
x = np.linspace(0.0, 1.0, 100)
assert_allclose(self.template.cdf(self.template.ppf(x)), x)
x = np.linspace(-2, 2, 10)
assert_allclose(self.norm_template.cdf(x),
stats.norm.cdf(x, loc=1.0, scale=2.5), rtol=0.1)
def test_rvs(self):
N = 10000
sample = self.template.rvs(size=N, random_state=123)
assert_equal(np.sum(sample < 1.0), 0.0)
assert_allclose(np.sum(sample <= 2.0), 1.0/25.0 * N, rtol=0.2)
assert_allclose(np.sum(sample <= 2.5), 2.0/25.0 * N, rtol=0.2)
assert_allclose(np.sum(sample <= 3.0), 3.0/25.0 * N, rtol=0.1)
assert_allclose(np.sum(sample <= 3.5), 4.5/25.0 * N, rtol=0.1)
assert_allclose(np.sum(sample <= 4.0), 6.0/25.0 * N, rtol=0.1)
assert_allclose(np.sum(sample <= 4.5), 8.0/25.0 * N, rtol=0.1)
assert_allclose(np.sum(sample <= 5.0), 10.0/25.0 * N, rtol=0.05)
assert_allclose(np.sum(sample <= 5.5), 12.5/25.0 * N, rtol=0.05)
assert_allclose(np.sum(sample <= 6.0), 15.0/25.0 * N, rtol=0.05)
assert_allclose(np.sum(sample <= 6.5), 17.0/25.0 * N, rtol=0.05)
assert_allclose(np.sum(sample <= 7.0), 19.0/25.0 * N, rtol=0.05)
assert_allclose(np.sum(sample <= 7.5), 20.5/25.0 * N, rtol=0.05)
assert_allclose(np.sum(sample <= 8.0), 22.0/25.0 * N, rtol=0.05)
assert_allclose(np.sum(sample <= 8.5), 23.5/25.0 * N, rtol=0.05)
assert_allclose(np.sum(sample <= 9.0), 25.0/25.0 * N, rtol=0.05)
assert_allclose(np.sum(sample <= 9.0), 25.0/25.0 * N, rtol=0.05)
assert_equal(np.sum(sample > 9.0), 0.0)
def test_munp(self):
for n in range(4):
assert_allclose(self.norm_template._munp(n),
stats.norm._munp(n, 1.0, 2.5), rtol=0.05)
def test_entropy(self):
assert_allclose(self.norm_template.entropy(),
stats.norm.entropy(loc=1.0, scale=2.5), rtol=0.05)
| 38.190181
| 159
| 0.577936
|
934bb9f336f3d858730e70dc41abaff2c7239800
| 3,075
|
py
|
Python
|
saleor/dashboard/customer/urls.py
|
glosoftgroup/KahawaHardware
|
893e94246583addf41c3bb0d58d2ce6bcd233c4f
|
[
"BSD-3-Clause"
] | null | null | null |
saleor/dashboard/customer/urls.py
|
glosoftgroup/KahawaHardware
|
893e94246583addf41c3bb0d58d2ce6bcd233c4f
|
[
"BSD-3-Clause"
] | null | null | null |
saleor/dashboard/customer/urls.py
|
glosoftgroup/KahawaHardware
|
893e94246583addf41c3bb0d58d2ce6bcd233c4f
|
[
"BSD-3-Clause"
] | null | null | null |
from django.conf.urls import url
from django.contrib.auth.decorators import login_required, permission_required
from . import views, sales
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^$', permission_required('customer.view_customer', login_url='account_login')
(views.users), name='customers'),
url(r'^add/$', permission_required('customer.add_customer', login_url='account_login')
(views.user_add), name='customer-add'),
url(r'^customer_process/$', views.user_process, name='customer_process'),
url(r'^d/(?P<pk>[0-9]+)/$', views.user_detail, name='customer-detail'),
url(r'^sd/(?P<pk>[0-9]+)/$', views.sales_detail, name='customer-sales-detail'),
url(r'^cst/pdf/detail/(?P<pk>[0-9]+)/$', sales.sales_detail, name='cust-pdf-sale-detail'),
url(r'^std/(?P<pk>[0-9]+)/(?P<ck>[0-9]+)/$', views.sales_items_detail, name='customer-sales-items-detail'),
url(r'^delete/(?P<pk>[0-9]+)/$', permission_required('customer.delete_customer', login_url='account_login')
(views.user_delete), name='customer-delete'),
url(r'^edit/(?P<pk>[0-9]+)/$', permission_required('customer.change_customer', login_url='account_login')
(views.user_edit), name='customer-edit'),
url(r'^user_update(?P<pk>[0-9]+)/$', views.user_update, name='customer-update'),
url(r'^customer/paginate/$', views.customer_pagination, name='customer-paginate'),
url(r'^customer/search/$', views.customer_search, name='customer-search'),
url( r'^customer/sales/paginate/customer-sales-detail$', sales.sales_paginate, name = 'customer_sales_paginate'),
url( r'^customer/sales/search/$', sales.sales_search, name = 'customer_sales_search'),
url(r'^customer/sales/list/pdf/$', sales.sales_list_pdf, name='customers_sales_list_pdf'),
url( r'^customer/canbe/creditable/$', views.is_creditable, name = 'is_creditable'),
# reports urls
url(r'^reports/$', permission_required('customer.view_customer', login_url='not_found')
(views.customer_report), name='customer_report_list'),
url(r'^report/paginate/$', views.report_pagination, name='customer-report-paginate'),
url(r'^report/search/$', views.report_search, name='customer-report-search'),
url(r'^reports/loyalty-points/pdf/$', views.costomer_loyalty_points_pdf, name='costomer_loyalty_points_pdf'),
# credit urls
url(r'^credit-list/$', permission_required('customer.view_customer', login_url='not_found')
(views.credit_report), name='customer_credit_list'),
url(r'^credit/paginate/$', views.credit_pagination, name='customer-credit-paginate'),
url(r'^credit/search/$', views.credit_search, name='customer-credit-search'),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
| 60.294118
| 121
| 0.673496
|
87d4150936e92f8319e89907fe39a028cc3a377f
| 5,253
|
py
|
Python
|
app.py
|
TurconiAndrea/water-footprint-reducer-rs
|
1f1b734bc2037bf4ac2dcef75db85438403d8a42
|
[
"MIT"
] | null | null | null |
app.py
|
TurconiAndrea/water-footprint-reducer-rs
|
1f1b734bc2037bf4ac2dcef75db85438403d8a42
|
[
"MIT"
] | null | null | null |
app.py
|
TurconiAndrea/water-footprint-reducer-rs
|
1f1b734bc2037bf4ac2dcef75db85438403d8a42
|
[
"MIT"
] | null | null | null |
"""
Module containing the Streamlit app to explore the project.
"""
import pandas as pd
import streamlit as st
from cb_recommender import CBRecommender
from cf_recommender import CFRecommender
from configuration import load_configuration
content_bases_algo = "Content Based"
collaborative_filtering_algo = "Collaborative filtering"
class App:
"""
Class that represents the app of the recommender system.
It provides a Streamlit app to run on local browser
and the possibility to configure the system with the
two different algorithm and the water footprint filter.
"""
def __init__(self):
"""
Constructor method for the class.
It loads the paths for the orders and the recipes datasets
"""
config = load_configuration()
self.path_orders = config["path_orders"]
self.path_recipes = config["path_recipes"]
@st.cache
def load_recipes(self):
"""
Load the recipes dataset from the default folder.
:return: a dataframe containing the recipes.
"""
return pd.read_pickle(self.path_recipes)
@st.cache
def load_orders(self):
"""
Load the orders from the default folder.
:return: a dataframe containing the orders and ratings.
"""
return pd.read_pickle(self.path_orders)
def generate_user_orders(self, user_id, orders, recipes):
"""
Return the user orders ratings merged with the recipes
water footprint information.
:param user_id: the id of the user.
:param orders: the dataframe containing orders.
:param recipes: the dataframe containing recipes.
:return: a dataframe with user orders ratings and
recipe water footprint information.
"""
user_orders = orders.query(f"user_id == {user_id}")
return pd.merge(user_orders, recipes, on=["id"])[
["name", "rating", "wf", "category"]
]
def get_recipe_recommendations(
self, user_id, n_recommendations, filter_wf, algo_type
):
"""
Get recipe recommendations for provided user using
one of the two algorithm and the water footprint filter.
:param user_id: the id of the user to recommend recipes.
:param n_recommendations: the number of recommendations.
:param filter_wf: the information about the activation of
water footprint filter or not.
:param algo_type: the type of the recommendation algorithm.
:return: a dataframe containing user recommendations.
"""
wf_recommenders = {
content_bases_algo: CBRecommender(
n_recommendations=n_recommendations, disable_filter_wf=not filter_wf
),
collaborative_filtering_algo: CFRecommender(
n_recommendations=n_recommendations, disable_filter_wf=not filter_wf
),
}
wf_recommender = wf_recommenders[algo_type]
return wf_recommender.get_user_recommendations(user_id)
def build_app(self):
"""
Build the app with Streamlit package.
App provides some configuration like the id of the user
to recommend recipes, the possibility to choose between
a content based or a collaborative filtering algorithm
and the possibility to activate or deactivate the
water footprint filter.
:return: None.
"""
recipes = self.load_recipes()
orders = self.load_orders()
st.markdown("# Recommender System for reducing Water footprint ")
st.sidebar.write("### Configure the system")
user_id = st.sidebar.selectbox(
"Select a user", orders["user_id"].unique(), index=0
)
algo_type = st.sidebar.selectbox(
"Select the algorithm for recommendation",
[content_bases_algo, collaborative_filtering_algo],
index=0,
)
n_recommendations = st.sidebar.slider(
"Select number of recommendations",
min_value=1,
max_value=20,
value=10,
step=1,
)
st.sidebar.markdown("***")
st.sidebar.write(
"Water Footprint filter is activate by default, check the option to change"
)
filter_wf = st.sidebar.checkbox(
"Deactivate the Water Footprint filter", value=True
)
st.markdown("### User rating for recipes")
st.dataframe(self.generate_user_orders(user_id, orders, recipes))
if st.button("Recommend recipes!"):
with st.spinner(text="Generating recommendations"):
st.markdown("### Recommendations for user to lower the Water Footprint")
recommendations = self.get_recipe_recommendations(
user_id, n_recommendations, filter_wf, algo_type
)[["name", "wf", "category"]].reset_index(drop=True)
st.write(
"Total Water footprint of recommendations:",
round(recommendations["wf"].sum(), 2),
)
st.dataframe(recommendations)
if __name__ == "__main__":
app = App()
app.build_app()
| 34.788079
| 88
| 0.630687
|
847f543ebca4de6c36de9ee22fd8dc07f36454e2
| 61,871
|
py
|
Python
|
pandas/core/internals/managers.py
|
rebecca-palmer/pandas
|
7c94949dc89c62cae1bc647acd87266d6c3a0468
|
[
"PSF-2.0",
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | 1
|
2020-01-21T17:05:14.000Z
|
2020-01-21T17:05:14.000Z
|
pandas/core/internals/managers.py
|
rebecca-palmer/pandas
|
7c94949dc89c62cae1bc647acd87266d6c3a0468
|
[
"PSF-2.0",
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | null | null | null |
pandas/core/internals/managers.py
|
rebecca-palmer/pandas
|
7c94949dc89c62cae1bc647acd87266d6c3a0468
|
[
"PSF-2.0",
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | 1
|
2021-01-19T09:48:37.000Z
|
2021-01-19T09:48:37.000Z
|
from collections import defaultdict
from functools import partial
import itertools
import operator
import re
from typing import List, Optional, Sequence, Tuple, Union
import numpy as np
from pandas._libs import Timedelta, Timestamp, internals as libinternals, lib
from pandas.util._validators import validate_bool_kwarg
from pandas.core.dtypes.cast import (
find_common_type,
infer_dtype_from_scalar,
maybe_convert_objects,
maybe_promote,
)
from pandas.core.dtypes.common import (
_NS_DTYPE,
is_datetimelike_v_numeric,
is_extension_array_dtype,
is_list_like,
is_numeric_v_string_like,
is_scalar,
is_sparse,
)
from pandas.core.dtypes.concat import concat_compat
from pandas.core.dtypes.dtypes import ExtensionDtype
from pandas.core.dtypes.generic import ABCExtensionArray, ABCSeries
from pandas.core.dtypes.missing import isna
import pandas.core.algorithms as algos
from pandas.core.base import PandasObject
from pandas.core.indexers import maybe_convert_indices
from pandas.core.indexes.api import Index, MultiIndex, ensure_index
from pandas.core.internals.blocks import (
Block,
CategoricalBlock,
DatetimeTZBlock,
ExtensionBlock,
ObjectValuesExtensionBlock,
_extend_blocks,
_merge_blocks,
_safe_reshape,
get_block_type,
make_block,
)
from pandas.core.internals.concat import ( # all for concatenate_block_managers
combine_concat_plans,
concatenate_join_units,
get_mgr_concatenation_plan,
is_uniform_join_units,
)
from pandas.io.formats.printing import pprint_thing
# TODO: flexible with index=None and/or items=None
class BlockManager(PandasObject):
"""
Core internal data structure to implement DataFrame, Series, etc.
Manage a bunch of labeled 2D mixed-type ndarrays. Essentially it's a
lightweight blocked set of labeled data to be manipulated by the DataFrame
public API class
Attributes
----------
shape
ndim
axes
values
items
Methods
-------
set_axis(axis, new_labels)
copy(deep=True)
get_dtype_counts
get_dtypes
apply(func, axes, block_filter_fn)
get_bool_data
get_numeric_data
get_slice(slice_like, axis)
get(label)
iget(loc)
take(indexer, axis)
reindex_axis(new_labels, axis)
reindex_indexer(new_labels, indexer, axis)
delete(label)
insert(loc, label, value)
set(label, value)
Parameters
----------
Notes
-----
This is *not* a public API class
"""
__slots__ = [
"axes",
"blocks",
"_ndim",
"_shape",
"_known_consolidated",
"_is_consolidated",
"_blknos",
"_blklocs",
]
def __init__(
self,
blocks: Sequence[Block],
axes: Sequence[Index],
do_integrity_check: bool = True,
):
self.axes = [ensure_index(ax) for ax in axes]
self.blocks: Tuple[Block, ...] = tuple(blocks)
for block in blocks:
if self.ndim != block.ndim:
raise AssertionError(
f"Number of Block dimensions ({block.ndim}) must equal "
f"number of axes ({self.ndim})"
)
if do_integrity_check:
self._verify_integrity()
self._consolidate_check()
self._rebuild_blknos_and_blklocs()
def make_empty(self, axes=None):
""" return an empty BlockManager with the items axis of len 0 """
if axes is None:
axes = [ensure_index([])] + [ensure_index(a) for a in self.axes[1:]]
# preserve dtype if possible
if self.ndim == 1:
blocks = np.array([], dtype=self.array_dtype)
else:
blocks = []
return type(self)(blocks, axes)
def __nonzero__(self):
return True
# Python3 compat
__bool__ = __nonzero__
@property
def shape(self):
return tuple(len(ax) for ax in self.axes)
@property
def ndim(self) -> int:
return len(self.axes)
def set_axis(self, axis, new_labels):
new_labels = ensure_index(new_labels)
old_len = len(self.axes[axis])
new_len = len(new_labels)
if new_len != old_len:
raise ValueError(
f"Length mismatch: Expected axis has {old_len} elements, new "
f"values have {new_len} elements"
)
self.axes[axis] = new_labels
def rename_axis(self, mapper, axis, copy=True, level=None):
"""
Rename one of axes.
Parameters
----------
mapper : unary callable
axis : int
copy : boolean, default True
level : int, default None
"""
obj = self.copy(deep=copy)
obj.set_axis(axis, _transform_index(self.axes[axis], mapper, level))
return obj
@property
def _is_single_block(self):
if self.ndim == 1:
return True
if len(self.blocks) != 1:
return False
blk = self.blocks[0]
return blk.mgr_locs.is_slice_like and blk.mgr_locs.as_slice == slice(
0, len(self), 1
)
def _rebuild_blknos_and_blklocs(self):
"""
Update mgr._blknos / mgr._blklocs.
"""
new_blknos = np.empty(self.shape[0], dtype=np.int64)
new_blklocs = np.empty(self.shape[0], dtype=np.int64)
new_blknos.fill(-1)
new_blklocs.fill(-1)
for blkno, blk in enumerate(self.blocks):
rl = blk.mgr_locs
new_blknos[rl.indexer] = blkno
new_blklocs[rl.indexer] = np.arange(len(rl))
if (new_blknos == -1).any():
raise AssertionError("Gaps in blk ref_locs")
self._blknos = new_blknos
self._blklocs = new_blklocs
@property
def items(self):
return self.axes[0]
def _get_counts(self, f):
""" return a dict of the counts of the function in BlockManager """
self._consolidate_inplace()
counts = dict()
for b in self.blocks:
v = f(b)
counts[v] = counts.get(v, 0) + b.shape[0]
return counts
def get_dtype_counts(self):
return self._get_counts(lambda b: b.dtype.name)
def get_dtypes(self):
dtypes = np.array([blk.dtype for blk in self.blocks])
return algos.take_1d(dtypes, self._blknos, allow_fill=False)
def __getstate__(self):
block_values = [b.values for b in self.blocks]
block_items = [self.items[b.mgr_locs.indexer] for b in self.blocks]
axes_array = list(self.axes)
extra_state = {
"0.14.1": {
"axes": axes_array,
"blocks": [
dict(values=b.values, mgr_locs=b.mgr_locs.indexer)
for b in self.blocks
],
}
}
# First three elements of the state are to maintain forward
# compatibility with 0.13.1.
return axes_array, block_values, block_items, extra_state
def __setstate__(self, state):
def unpickle_block(values, mgr_locs):
return make_block(values, placement=mgr_locs)
if isinstance(state, tuple) and len(state) >= 4 and "0.14.1" in state[3]:
state = state[3]["0.14.1"]
self.axes = [ensure_index(ax) for ax in state["axes"]]
self.blocks = tuple(
unpickle_block(b["values"], b["mgr_locs"]) for b in state["blocks"]
)
else:
raise NotImplementedError("pre-0.14.1 pickles are no longer supported")
self._post_setstate()
def _post_setstate(self):
self._is_consolidated = False
self._known_consolidated = False
self._rebuild_blknos_and_blklocs()
def __len__(self) -> int:
return len(self.items)
def __repr__(self) -> str:
output = type(self).__name__
for i, ax in enumerate(self.axes):
if i == 0:
output += f"\nItems: {ax}"
else:
output += f"\nAxis {i}: {ax}"
for block in self.blocks:
output += f"\n{pprint_thing(block)}"
return output
def _verify_integrity(self):
mgr_shape = self.shape
tot_items = sum(len(x.mgr_locs) for x in self.blocks)
for block in self.blocks:
if block._verify_integrity and block.shape[1:] != mgr_shape[1:]:
construction_error(tot_items, block.shape[1:], self.axes)
if len(self.items) != tot_items:
raise AssertionError(
"Number of manager items must equal union of "
f"block items\n# manager items: {len(self.items)}, # "
f"tot_items: {tot_items}"
)
def reduce(self, func, *args, **kwargs):
# If 2D, we assume that we're operating column-wise
if self.ndim == 1:
# we'll be returning a scalar
blk = self.blocks[0]
return func(blk.values, *args, **kwargs)
res = {}
for blk in self.blocks:
bres = func(blk.values, *args, **kwargs)
if np.ndim(bres) == 0:
# EA
assert blk.shape[0] == 1
new_res = zip(blk.mgr_locs.as_array, [bres])
else:
assert bres.ndim == 1, bres.shape
assert blk.shape[0] == len(bres), (blk.shape, bres.shape, args, kwargs)
new_res = zip(blk.mgr_locs.as_array, bres)
nr = dict(new_res)
assert not any(key in res for key in nr)
res.update(nr)
return res
def apply(self, f, filter=None, **kwargs):
"""
Iterate over the blocks, collect and create a new BlockManager.
Parameters
----------
f : str or callable
Name of the Block method to apply.
filter : list, if supplied, only call the block if the filter is in
the block
Returns
-------
BlockManager
"""
result_blocks = []
# filter kwarg is used in replace-* family of methods
if filter is not None:
filter_locs = set(self.items.get_indexer_for(filter))
if len(filter_locs) == len(self.items):
# All items are included, as if there were no filtering
filter = None
else:
kwargs["filter"] = filter_locs
self._consolidate_inplace()
if f == "where":
align_copy = True
if kwargs.get("align", True):
align_keys = ["other", "cond"]
else:
align_keys = ["cond"]
elif f == "putmask":
align_copy = False
if kwargs.get("align", True):
align_keys = ["new", "mask"]
else:
align_keys = ["mask"]
elif f == "fillna":
# fillna internally does putmask, maybe it's better to do this
# at mgr, not block level?
align_copy = False
align_keys = ["value"]
else:
align_keys = []
# TODO(EA): may interfere with ExtensionBlock.setitem for blocks
# with a .values attribute.
aligned_args = {
k: kwargs[k]
for k in align_keys
if not isinstance(kwargs[k], ABCExtensionArray)
and hasattr(kwargs[k], "values")
}
for b in self.blocks:
if filter is not None:
if not b.mgr_locs.isin(filter_locs).any():
result_blocks.append(b)
continue
if aligned_args:
b_items = self.items[b.mgr_locs.indexer]
for k, obj in aligned_args.items():
axis = obj._info_axis_number
kwargs[k] = obj.reindex(b_items, axis=axis, copy=align_copy)
if callable(f):
applied = b.apply(f, **kwargs)
else:
applied = getattr(b, f)(**kwargs)
result_blocks = _extend_blocks(applied, result_blocks)
if len(result_blocks) == 0:
return self.make_empty(self.axes)
bm = type(self)(result_blocks, self.axes, do_integrity_check=False)
return bm
def quantile(
self,
axis=0,
consolidate=True,
transposed=False,
interpolation="linear",
qs=None,
numeric_only=None,
):
"""
Iterate over blocks applying quantile reduction.
This routine is intended for reduction type operations and
will do inference on the generated blocks.
Parameters
----------
axis: reduction axis, default 0
consolidate: boolean, default True. Join together blocks having same
dtype
transposed: boolean, default False
we are holding transposed data
interpolation : type of interpolation, default 'linear'
qs : a scalar or list of the quantiles to be computed
numeric_only : ignored
Returns
-------
Block Manager (new object)
"""
# Series dispatches to DataFrame for quantile, which allows us to
# simplify some of the code here and in the blocks
assert self.ndim >= 2
if consolidate:
self._consolidate_inplace()
def get_axe(block, qs, axes):
# Because Series dispatches to DataFrame, we will always have
# block.ndim == 2
from pandas import Float64Index
if is_list_like(qs):
ax = Float64Index(qs)
else:
ax = axes[0]
return ax
axes, blocks = [], []
for b in self.blocks:
block = b.quantile(axis=axis, qs=qs, interpolation=interpolation)
axe = get_axe(b, qs, axes=self.axes)
axes.append(axe)
blocks.append(block)
# note that some DatetimeTZ, Categorical are always ndim==1
ndim = {b.ndim for b in blocks}
assert 0 not in ndim, ndim
if 2 in ndim:
new_axes = list(self.axes)
# multiple blocks that are reduced
if len(blocks) > 1:
new_axes[1] = axes[0]
# reset the placement to the original
for b, sb in zip(blocks, self.blocks):
b.mgr_locs = sb.mgr_locs
else:
new_axes[axis] = Index(np.concatenate([ax.values for ax in axes]))
if transposed:
new_axes = new_axes[::-1]
blocks = [
b.make_block(b.values.T, placement=np.arange(b.shape[1]))
for b in blocks
]
return type(self)(blocks, new_axes)
# single block, i.e. ndim == {1}
values = concat_compat([b.values for b in blocks])
# compute the orderings of our original data
if len(self.blocks) > 1:
indexer = np.empty(len(self.axes[0]), dtype=np.intp)
i = 0
for b in self.blocks:
for j in b.mgr_locs:
indexer[j] = i
i = i + 1
values = values.take(indexer)
return SingleBlockManager(
[make_block(values, ndim=1, placement=np.arange(len(values)))], axes[0]
)
def isna(self, func):
return self.apply("apply", func=func)
def where(self, **kwargs):
return self.apply("where", **kwargs)
def setitem(self, **kwargs):
return self.apply("setitem", **kwargs)
def putmask(self, **kwargs):
return self.apply("putmask", **kwargs)
def diff(self, **kwargs):
return self.apply("diff", **kwargs)
def interpolate(self, **kwargs):
return self.apply("interpolate", **kwargs)
def shift(self, **kwargs):
return self.apply("shift", **kwargs)
def fillna(self, **kwargs):
return self.apply("fillna", **kwargs)
def downcast(self, **kwargs):
return self.apply("downcast", **kwargs)
def astype(self, dtype, copy: bool = False, errors: str = "raise"):
return self.apply("astype", dtype=dtype, copy=copy, errors=errors)
def convert(self, **kwargs):
return self.apply("convert", **kwargs)
def replace(self, value, **kwargs):
assert np.ndim(value) == 0, value
return self.apply("replace", value=value, **kwargs)
def replace_list(self, src_list, dest_list, inplace=False, regex=False):
""" do a list replace """
inplace = validate_bool_kwarg(inplace, "inplace")
# figure out our mask a-priori to avoid repeated replacements
values = self.as_array()
def comp(s, regex=False):
"""
Generate a bool array by perform an equality check, or perform
an element-wise regular expression matching
"""
if isna(s):
return isna(values)
if isinstance(s, (Timedelta, Timestamp)) and getattr(s, "tz", None) is None:
return _compare_or_regex_search(
maybe_convert_objects(values), s.asm8, regex
)
return _compare_or_regex_search(values, s, regex)
masks = [comp(s, regex) for i, s in enumerate(src_list)]
result_blocks = []
src_len = len(src_list) - 1
for blk in self.blocks:
# its possible to get multiple result blocks here
# replace ALWAYS will return a list
rb = [blk if inplace else blk.copy()]
for i, (s, d) in enumerate(zip(src_list, dest_list)):
# TODO: assert/validate that `d` is always a scalar?
new_rb = []
for b in rb:
m = masks[i][b.mgr_locs.indexer]
convert = i == src_len
result = b._replace_coerce(
mask=m,
to_replace=s,
value=d,
inplace=inplace,
convert=convert,
regex=regex,
)
if m.any() or convert:
new_rb = _extend_blocks(result, new_rb)
else:
new_rb.append(b)
rb = new_rb
result_blocks.extend(rb)
bm = type(self)(result_blocks, self.axes)
bm._consolidate_inplace()
return bm
def is_consolidated(self):
"""
Return True if more than one block with the same dtype
"""
if not self._known_consolidated:
self._consolidate_check()
return self._is_consolidated
def _consolidate_check(self):
ftypes = [blk.ftype for blk in self.blocks]
self._is_consolidated = len(ftypes) == len(set(ftypes))
self._known_consolidated = True
@property
def is_mixed_type(self):
# Warning, consolidation needs to get checked upstairs
self._consolidate_inplace()
return len(self.blocks) > 1
@property
def is_numeric_mixed_type(self):
# Warning, consolidation needs to get checked upstairs
self._consolidate_inplace()
return all(block.is_numeric for block in self.blocks)
@property
def any_extension_types(self):
"""Whether any of the blocks in this manager are extension blocks"""
return any(block.is_extension for block in self.blocks)
@property
def is_view(self):
""" return a boolean if we are a single block and are a view """
if len(self.blocks) == 1:
return self.blocks[0].is_view
# It is technically possible to figure out which blocks are views
# e.g. [ b.values.base is not None for b in self.blocks ]
# but then we have the case of possibly some blocks being a view
# and some blocks not. setting in theory is possible on the non-view
# blocks w/o causing a SettingWithCopy raise/warn. But this is a bit
# complicated
return False
def get_bool_data(self, copy=False):
"""
Parameters
----------
copy : boolean, default False
Whether to copy the blocks
"""
self._consolidate_inplace()
return self.combine([b for b in self.blocks if b.is_bool], copy)
def get_numeric_data(self, copy=False):
"""
Parameters
----------
copy : boolean, default False
Whether to copy the blocks
"""
self._consolidate_inplace()
return self.combine([b for b in self.blocks if b.is_numeric], copy)
def combine(self, blocks, copy=True):
""" return a new manager with the blocks """
if len(blocks) == 0:
return self.make_empty()
# FIXME: optimization potential
indexer = np.sort(np.concatenate([b.mgr_locs.as_array for b in blocks]))
inv_indexer = lib.get_reverse_indexer(indexer, self.shape[0])
new_blocks = []
for b in blocks:
b = b.copy(deep=copy)
b.mgr_locs = algos.take_1d(
inv_indexer, b.mgr_locs.as_array, axis=0, allow_fill=False
)
new_blocks.append(b)
axes = list(self.axes)
axes[0] = self.items.take(indexer)
return type(self)(new_blocks, axes, do_integrity_check=False)
def get_slice(self, slobj: slice, axis: int = 0):
if axis >= self.ndim:
raise IndexError("Requested axis not found in manager")
if axis == 0:
new_blocks = self._slice_take_blocks_ax0(slobj)
else:
_slicer = [slice(None)] * (axis + 1)
_slicer[axis] = slobj
slicer = tuple(_slicer)
new_blocks = [blk.getitem_block(slicer) for blk in self.blocks]
new_axes = list(self.axes)
new_axes[axis] = new_axes[axis][slobj]
bm = type(self)(new_blocks, new_axes, do_integrity_check=False)
bm._consolidate_inplace()
return bm
def __contains__(self, item) -> bool:
return item in self.items
@property
def nblocks(self) -> int:
return len(self.blocks)
def copy(self, deep=True):
"""
Make deep or shallow copy of BlockManager
Parameters
----------
deep : bool or string, default True
If False, return shallow copy (do not copy data)
If 'all', copy data and a deep copy of the index
Returns
-------
BlockManager
"""
# this preserves the notion of view copying of axes
if deep:
# hit in e.g. tests.io.json.test_pandas
def copy_func(ax):
if deep == "all":
return ax.copy(deep=True)
else:
return ax.view()
new_axes = [copy_func(ax) for ax in self.axes]
else:
new_axes = list(self.axes)
res = self.apply("copy", deep=deep)
res.axes = new_axes
return res
def as_array(self, transpose: bool = False) -> np.ndarray:
"""
Convert the blockmanager data into an numpy array.
Parameters
----------
transpose : boolean, default False
If True, transpose the return array
Returns
-------
arr : ndarray
"""
if len(self.blocks) == 0:
arr = np.empty(self.shape, dtype=float)
return arr.transpose() if transpose else arr
mgr = self
if self._is_single_block and mgr.blocks[0].is_datetimetz:
# TODO(Block.get_values): Make DatetimeTZBlock.get_values
# always be object dtype. Some callers seem to want the
# DatetimeArray (previously DTI)
arr = mgr.blocks[0].get_values(dtype=object)
elif self._is_single_block or not self.is_mixed_type:
arr = np.asarray(mgr.blocks[0].get_values())
else:
arr = mgr._interleave()
return arr.transpose() if transpose else arr
def _interleave(self):
"""
Return ndarray from blocks with specified item order
Items must be contained in the blocks
"""
dtype = _interleaved_dtype(self.blocks)
# TODO: https://github.com/pandas-dev/pandas/issues/22791
# Give EAs some input on what happens here. Sparse needs this.
if is_sparse(dtype):
dtype = dtype.subtype
elif is_extension_array_dtype(dtype):
dtype = "object"
result = np.empty(self.shape, dtype=dtype)
itemmask = np.zeros(self.shape[0])
for blk in self.blocks:
rl = blk.mgr_locs
result[rl.indexer] = blk.get_values(dtype)
itemmask[rl.indexer] = 1
if not itemmask.all():
raise AssertionError("Some items were not contained in blocks")
return result
def to_dict(self, copy=True):
"""
Return a dict of str(dtype) -> BlockManager
Parameters
----------
copy : boolean, default True
Returns
-------
values : a dict of dtype -> BlockManager
Notes
-----
This consolidates based on str(dtype)
"""
self._consolidate_inplace()
bd = {}
for b in self.blocks:
bd.setdefault(str(b.dtype), []).append(b)
return {dtype: self.combine(blocks, copy=copy) for dtype, blocks in bd.items()}
def fast_xs(self, loc):
"""
get a cross sectional for a given location in the
items ; handle dups
return the result, is *could* be a view in the case of a
single block
"""
if len(self.blocks) == 1:
return self.blocks[0].iget((slice(None), loc))
items = self.items
# non-unique (GH4726)
if not items.is_unique:
result = self._interleave()
if self.ndim == 2:
result = result.T
return result[loc]
# unique
dtype = _interleaved_dtype(self.blocks)
n = len(items)
if is_extension_array_dtype(dtype):
# we'll eventually construct an ExtensionArray.
result = np.empty(n, dtype=object)
else:
result = np.empty(n, dtype=dtype)
for blk in self.blocks:
# Such assignment may incorrectly coerce NaT to None
# result[blk.mgr_locs] = blk._slice((slice(None), loc))
for i, rl in enumerate(blk.mgr_locs):
result[rl] = blk.iget((i, loc))
if is_extension_array_dtype(dtype):
result = dtype.construct_array_type()._from_sequence(result, dtype=dtype)
return result
def consolidate(self):
"""
Join together blocks having same dtype
Returns
-------
y : BlockManager
"""
if self.is_consolidated():
return self
bm = type(self)(self.blocks, self.axes)
bm._is_consolidated = False
bm._consolidate_inplace()
return bm
def _consolidate_inplace(self):
if not self.is_consolidated():
self.blocks = tuple(_consolidate(self.blocks))
self._is_consolidated = True
self._known_consolidated = True
self._rebuild_blknos_and_blklocs()
def get(self, item):
"""
Return values for selected item (ndarray or BlockManager).
"""
if self.items.is_unique:
if not isna(item):
loc = self.items.get_loc(item)
else:
indexer = np.arange(len(self.items))[isna(self.items)]
# allow a single nan location indexer
if not is_scalar(indexer):
if len(indexer) == 1:
loc = indexer.item()
else:
raise ValueError("cannot label index with a null key")
return self.iget(loc)
else:
if isna(item):
raise TypeError("cannot label index with a null key")
indexer = self.items.get_indexer_for([item])
return self.reindex_indexer(
new_axis=self.items[indexer], indexer=indexer, axis=0, allow_dups=True
)
def iget(self, i):
"""
Return the data as a SingleBlockManager if possible
Otherwise return as a ndarray
"""
block = self.blocks[self._blknos[i]]
values = block.iget(self._blklocs[i])
# shortcut for select a single-dim from a 2-dim BM
return SingleBlockManager(
[
block.make_block_same_class(
values, placement=slice(0, len(values)), ndim=1
)
],
self.axes[1],
)
def delete(self, item):
"""
Delete selected item (items if non-unique) in-place.
"""
indexer = self.items.get_loc(item)
is_deleted = np.zeros(self.shape[0], dtype=np.bool_)
is_deleted[indexer] = True
ref_loc_offset = -is_deleted.cumsum()
is_blk_deleted = [False] * len(self.blocks)
if isinstance(indexer, int):
affected_start = indexer
else:
affected_start = is_deleted.nonzero()[0][0]
for blkno, _ in _fast_count_smallints(self._blknos[affected_start:]):
blk = self.blocks[blkno]
bml = blk.mgr_locs
blk_del = is_deleted[bml.indexer].nonzero()[0]
if len(blk_del) == len(bml):
is_blk_deleted[blkno] = True
continue
elif len(blk_del) != 0:
blk.delete(blk_del)
bml = blk.mgr_locs
blk.mgr_locs = bml.add(ref_loc_offset[bml.indexer])
# FIXME: use Index.delete as soon as it uses fastpath=True
self.axes[0] = self.items[~is_deleted]
self.blocks = tuple(
b for blkno, b in enumerate(self.blocks) if not is_blk_deleted[blkno]
)
self._shape = None
self._rebuild_blknos_and_blklocs()
def set(self, item, value):
"""
Set new item in-place. Does not consolidate. Adds new Block if not
contained in the current set of items
"""
# FIXME: refactor, clearly separate broadcasting & zip-like assignment
# can prob also fix the various if tests for sparse/categorical
value_is_extension_type = is_extension_array_dtype(value)
# categorical/sparse/datetimetz
if value_is_extension_type:
def value_getitem(placement):
return value
else:
if value.ndim == self.ndim - 1:
value = _safe_reshape(value, (1,) + value.shape)
def value_getitem(placement):
return value
else:
def value_getitem(placement):
return value[placement.indexer]
if value.shape[1:] != self.shape[1:]:
raise AssertionError(
"Shape of new values must be compatible with manager shape"
)
try:
loc = self.items.get_loc(item)
except KeyError:
# This item wasn't present, just insert at end
self.insert(len(self.items), item, value)
return
if isinstance(loc, int):
loc = [loc]
blknos = self._blknos[loc]
blklocs = self._blklocs[loc].copy()
unfit_mgr_locs = []
unfit_val_locs = []
removed_blknos = []
for blkno, val_locs in libinternals.get_blkno_placements(blknos, group=True):
blk = self.blocks[blkno]
blk_locs = blklocs[val_locs.indexer]
if blk.should_store(value):
blk.set(blk_locs, value_getitem(val_locs))
else:
unfit_mgr_locs.append(blk.mgr_locs.as_array[blk_locs])
unfit_val_locs.append(val_locs)
# If all block items are unfit, schedule the block for removal.
if len(val_locs) == len(blk.mgr_locs):
removed_blknos.append(blkno)
else:
self._blklocs[blk.mgr_locs.indexer] = -1
blk.delete(blk_locs)
self._blklocs[blk.mgr_locs.indexer] = np.arange(len(blk))
if len(removed_blknos):
# Remove blocks & update blknos accordingly
is_deleted = np.zeros(self.nblocks, dtype=np.bool_)
is_deleted[removed_blknos] = True
new_blknos = np.empty(self.nblocks, dtype=np.int64)
new_blknos.fill(-1)
new_blknos[~is_deleted] = np.arange(self.nblocks - len(removed_blknos))
self._blknos = algos.take_1d(
new_blknos, self._blknos, axis=0, allow_fill=False
)
self.blocks = tuple(
blk for i, blk in enumerate(self.blocks) if i not in set(removed_blknos)
)
if unfit_val_locs:
unfit_mgr_locs = np.concatenate(unfit_mgr_locs)
unfit_count = len(unfit_mgr_locs)
new_blocks = []
if value_is_extension_type:
# This code (ab-)uses the fact that sparse blocks contain only
# one item.
new_blocks.extend(
make_block(
values=value.copy(),
ndim=self.ndim,
placement=slice(mgr_loc, mgr_loc + 1),
)
for mgr_loc in unfit_mgr_locs
)
self._blknos[unfit_mgr_locs] = np.arange(unfit_count) + len(self.blocks)
self._blklocs[unfit_mgr_locs] = 0
else:
# unfit_val_locs contains BlockPlacement objects
unfit_val_items = unfit_val_locs[0].append(unfit_val_locs[1:])
new_blocks.append(
make_block(
values=value_getitem(unfit_val_items),
ndim=self.ndim,
placement=unfit_mgr_locs,
)
)
self._blknos[unfit_mgr_locs] = len(self.blocks)
self._blklocs[unfit_mgr_locs] = np.arange(unfit_count)
self.blocks += tuple(new_blocks)
# Newly created block's dtype may already be present.
self._known_consolidated = False
def insert(self, loc: int, item, value, allow_duplicates: bool = False):
"""
Insert item at selected position.
Parameters
----------
loc : int
item : hashable
value : array_like
allow_duplicates: bool
If False, trying to insert non-unique item will raise
"""
if not allow_duplicates and item in self.items:
# Should this be a different kind of error??
raise ValueError(f"cannot insert {item}, already exists")
if not isinstance(loc, int):
raise TypeError("loc must be int")
# insert to the axis; this could possibly raise a TypeError
new_axis = self.items.insert(loc, item)
block = make_block(values=value, ndim=self.ndim, placement=slice(loc, loc + 1))
for blkno, count in _fast_count_smallints(self._blknos[loc:]):
blk = self.blocks[blkno]
if count == len(blk.mgr_locs):
blk.mgr_locs = blk.mgr_locs.add(1)
else:
new_mgr_locs = blk.mgr_locs.as_array.copy()
new_mgr_locs[new_mgr_locs >= loc] += 1
blk.mgr_locs = new_mgr_locs
if loc == self._blklocs.shape[0]:
# np.append is a lot faster, let's use it if we can.
self._blklocs = np.append(self._blklocs, 0)
self._blknos = np.append(self._blknos, len(self.blocks))
else:
self._blklocs = np.insert(self._blklocs, loc, 0)
self._blknos = np.insert(self._blknos, loc, len(self.blocks))
self.axes[0] = new_axis
self.blocks += (block,)
self._shape = None
self._known_consolidated = False
if len(self.blocks) > 100:
self._consolidate_inplace()
def reindex_axis(
self, new_index, axis, method=None, limit=None, fill_value=None, copy=True
):
"""
Conform block manager to new index.
"""
new_index = ensure_index(new_index)
new_index, indexer = self.axes[axis].reindex(
new_index, method=method, limit=limit
)
return self.reindex_indexer(
new_index, indexer, axis=axis, fill_value=fill_value, copy=copy
)
def reindex_indexer(
self, new_axis, indexer, axis, fill_value=None, allow_dups=False, copy=True
):
"""
Parameters
----------
new_axis : Index
indexer : ndarray of int64 or None
axis : int
fill_value : object
allow_dups : bool
pandas-indexer with -1's only.
"""
if indexer is None:
if new_axis is self.axes[axis] and not copy:
return self
result = self.copy(deep=copy)
result.axes = list(self.axes)
result.axes[axis] = new_axis
return result
self._consolidate_inplace()
# some axes don't allow reindexing with dups
if not allow_dups:
self.axes[axis]._can_reindex(indexer)
if axis >= self.ndim:
raise IndexError("Requested axis not found in manager")
if axis == 0:
new_blocks = self._slice_take_blocks_ax0(indexer, fill_tuple=(fill_value,))
else:
new_blocks = [
blk.take_nd(
indexer,
axis=axis,
fill_tuple=(
fill_value if fill_value is not None else blk.fill_value,
),
)
for blk in self.blocks
]
new_axes = list(self.axes)
new_axes[axis] = new_axis
return type(self)(new_blocks, new_axes)
def _slice_take_blocks_ax0(self, slice_or_indexer, fill_tuple=None):
"""
Slice/take blocks along axis=0.
Overloaded for SingleBlock
Returns
-------
new_blocks : list of Block
"""
allow_fill = fill_tuple is not None
sl_type, slobj, sllen = _preprocess_slice_or_indexer(
slice_or_indexer, self.shape[0], allow_fill=allow_fill
)
if self._is_single_block:
blk = self.blocks[0]
if sl_type in ("slice", "mask"):
return [blk.getitem_block(slobj, new_mgr_locs=slice(0, sllen))]
elif not allow_fill or self.ndim == 1:
if allow_fill and fill_tuple[0] is None:
_, fill_value = maybe_promote(blk.dtype)
fill_tuple = (fill_value,)
return [
blk.take_nd(
slobj,
axis=0,
new_mgr_locs=slice(0, sllen),
fill_tuple=fill_tuple,
)
]
if sl_type in ("slice", "mask"):
blknos = self._blknos[slobj]
blklocs = self._blklocs[slobj]
else:
blknos = algos.take_1d(
self._blknos, slobj, fill_value=-1, allow_fill=allow_fill
)
blklocs = algos.take_1d(
self._blklocs, slobj, fill_value=-1, allow_fill=allow_fill
)
# When filling blknos, make sure blknos is updated before appending to
# blocks list, that way new blkno is exactly len(blocks).
#
# FIXME: mgr_groupby_blknos must return mgr_locs in ascending order,
# pytables serialization will break otherwise.
blocks = []
for blkno, mgr_locs in libinternals.get_blkno_placements(blknos, group=True):
if blkno == -1:
# If we've got here, fill_tuple was not None.
fill_value = fill_tuple[0]
blocks.append(
self._make_na_block(placement=mgr_locs, fill_value=fill_value)
)
else:
blk = self.blocks[blkno]
# Otherwise, slicing along items axis is necessary.
if not blk._can_consolidate:
# A non-consolidatable block, it's easy, because there's
# only one item and each mgr loc is a copy of that single
# item.
for mgr_loc in mgr_locs:
newblk = blk.copy(deep=False)
newblk.mgr_locs = slice(mgr_loc, mgr_loc + 1)
blocks.append(newblk)
else:
blocks.append(
blk.take_nd(
blklocs[mgr_locs.indexer],
axis=0,
new_mgr_locs=mgr_locs,
fill_tuple=None,
)
)
return blocks
def _make_na_block(self, placement, fill_value=None):
# TODO: infer dtypes other than float64 from fill_value
if fill_value is None:
fill_value = np.nan
block_shape = list(self.shape)
block_shape[0] = len(placement)
dtype, fill_value = infer_dtype_from_scalar(fill_value)
block_values = np.empty(block_shape, dtype=dtype)
block_values.fill(fill_value)
return make_block(block_values, placement=placement)
def take(self, indexer, axis=1, verify=True, convert=True):
"""
Take items along any axis.
"""
self._consolidate_inplace()
indexer = (
np.arange(indexer.start, indexer.stop, indexer.step, dtype="int64")
if isinstance(indexer, slice)
else np.asanyarray(indexer, dtype="int64")
)
n = self.shape[axis]
if convert:
indexer = maybe_convert_indices(indexer, n)
if verify:
if ((indexer == -1) | (indexer >= n)).any():
raise Exception("Indices must be nonzero and less than the axis length")
new_labels = self.axes[axis].take(indexer)
return self.reindex_indexer(
new_axis=new_labels, indexer=indexer, axis=axis, allow_dups=True
)
def equals(self, other):
self_axes, other_axes = self.axes, other.axes
if len(self_axes) != len(other_axes):
return False
if not all(ax1.equals(ax2) for ax1, ax2 in zip(self_axes, other_axes)):
return False
self._consolidate_inplace()
other._consolidate_inplace()
if len(self.blocks) != len(other.blocks):
return False
# canonicalize block order, using a tuple combining the mgr_locs
# then type name because there might be unconsolidated
# blocks (say, Categorical) which can only be distinguished by
# the iteration order
def canonicalize(block):
return (block.mgr_locs.as_array.tolist(), block.dtype.name)
self_blocks = sorted(self.blocks, key=canonicalize)
other_blocks = sorted(other.blocks, key=canonicalize)
return all(
block.equals(oblock) for block, oblock in zip(self_blocks, other_blocks)
)
def unstack(self, unstacker_func, fill_value):
"""Return a blockmanager with all blocks unstacked.
Parameters
----------
unstacker_func : callable
A (partially-applied) ``pd.core.reshape._Unstacker`` class.
fill_value : Any
fill_value for newly introduced missing values.
Returns
-------
unstacked : BlockManager
"""
n_rows = self.shape[-1]
dummy = unstacker_func(np.empty((0, 0)), value_columns=self.items)
new_columns = dummy.get_new_columns()
new_index = dummy.get_new_index()
new_blocks = []
columns_mask = []
for blk in self.blocks:
blocks, mask = blk._unstack(
partial(unstacker_func, value_columns=self.items[blk.mgr_locs.indexer]),
new_columns,
n_rows,
fill_value,
)
new_blocks.extend(blocks)
columns_mask.extend(mask)
new_columns = new_columns[columns_mask]
bm = BlockManager(new_blocks, [new_columns, new_index])
return bm
class SingleBlockManager(BlockManager):
""" manage a single block with """
ndim = 1
_is_consolidated = True
_known_consolidated = True
__slots__ = ()
def __init__(
self,
block: Block,
axis: Union[Index, List[Index]],
do_integrity_check: bool = False,
fastpath: bool = False,
):
if isinstance(axis, list):
if len(axis) != 1:
raise ValueError(
"cannot create SingleBlockManager with more than 1 axis"
)
axis = axis[0]
# passed from constructor, single block, single axis
if fastpath:
self.axes = [axis]
if isinstance(block, list):
# empty block
if len(block) == 0:
block = [np.array([])]
elif len(block) != 1:
raise ValueError(
"Cannot create SingleBlockManager with more than 1 block"
)
block = block[0]
else:
self.axes = [ensure_index(axis)]
# create the block here
if isinstance(block, list):
# provide consolidation to the interleaved_dtype
if len(block) > 1:
dtype = _interleaved_dtype(block)
block = [b.astype(dtype) for b in block]
block = _consolidate(block)
if len(block) != 1:
raise ValueError(
"Cannot create SingleBlockManager with more than 1 block"
)
block = block[0]
if not isinstance(block, Block):
block = make_block(block, placement=slice(0, len(axis)), ndim=1)
self.blocks = tuple([block])
def _post_setstate(self):
pass
@property
def _block(self):
return self.blocks[0]
@property
def _values(self):
return self._block.values
@property
def _blknos(self):
""" compat with BlockManager """
return None
@property
def _blklocs(self):
""" compat with BlockManager """
return None
def get_slice(self, slobj, axis=0):
if axis >= self.ndim:
raise IndexError("Requested axis not found in manager")
return type(self)(self._block._slice(slobj), self.index[slobj], fastpath=True)
@property
def index(self):
return self.axes[0]
@property
def dtype(self):
return self._block.dtype
@property
def array_dtype(self):
return self._block.array_dtype
def get_dtype_counts(self):
return {self.dtype.name: 1}
def get_dtypes(self):
return np.array([self._block.dtype])
def external_values(self):
"""The array that Series.values returns"""
return self._block.external_values()
def internal_values(self):
"""The array that Series._values returns"""
return self._block.internal_values()
def get_values(self):
""" return a dense type view """
return np.array(self._block.to_dense(), copy=False)
@property
def _can_hold_na(self):
return self._block._can_hold_na
def is_consolidated(self):
return True
def _consolidate_check(self):
pass
def _consolidate_inplace(self):
pass
def delete(self, item):
"""
Delete single item from SingleBlockManager.
Ensures that self.blocks doesn't become empty.
"""
loc = self.items.get_loc(item)
self._block.delete(loc)
self.axes[0] = self.axes[0].delete(loc)
def fast_xs(self, loc):
"""
fast path for getting a cross-section
return a view of the data
"""
return self._block.values[loc]
def concat(self, to_concat, new_axis):
"""
Concatenate a list of SingleBlockManagers into a single
SingleBlockManager.
Used for pd.concat of Series objects with axis=0.
Parameters
----------
to_concat : list of SingleBlockManagers
new_axis : Index of the result
Returns
-------
SingleBlockManager
"""
non_empties = [x for x in to_concat if len(x) > 0]
# check if all series are of the same block type:
if len(non_empties) > 0:
blocks = [obj.blocks[0] for obj in non_empties]
if len({b.dtype for b in blocks}) == 1:
new_block = blocks[0].concat_same_type(blocks)
else:
values = [x.values for x in blocks]
values = concat_compat(values)
new_block = make_block(values, placement=slice(0, len(values), 1))
else:
values = [x._block.values for x in to_concat]
values = concat_compat(values)
new_block = make_block(values, placement=slice(0, len(values), 1))
mgr = SingleBlockManager(new_block, new_axis)
return mgr
# --------------------------------------------------------------------
# Constructor Helpers
def create_block_manager_from_blocks(blocks, axes):
try:
if len(blocks) == 1 and not isinstance(blocks[0], Block):
# if blocks[0] is of length 0, return empty blocks
if not len(blocks[0]):
blocks = []
else:
# It's OK if a single block is passed as values, its placement
# is basically "all items", but if there're many, don't bother
# converting, it's an error anyway.
blocks = [
make_block(values=blocks[0], placement=slice(0, len(axes[0])))
]
mgr = BlockManager(blocks, axes)
mgr._consolidate_inplace()
return mgr
except ValueError as e:
blocks = [getattr(b, "values", b) for b in blocks]
tot_items = sum(b.shape[0] for b in blocks)
construction_error(tot_items, blocks[0].shape[1:], axes, e)
def create_block_manager_from_arrays(arrays, names, axes):
try:
blocks = form_blocks(arrays, names, axes)
mgr = BlockManager(blocks, axes)
mgr._consolidate_inplace()
return mgr
except ValueError as e:
construction_error(len(arrays), arrays[0].shape, axes, e)
def construction_error(tot_items, block_shape, axes, e=None):
""" raise a helpful message about our construction """
passed = tuple(map(int, [tot_items] + list(block_shape)))
# Correcting the user facing error message during dataframe construction
if len(passed) <= 2:
passed = passed[::-1]
implied = tuple(len(ax) for ax in axes)
# Correcting the user facing error message during dataframe construction
if len(implied) <= 2:
implied = implied[::-1]
if passed == implied and e is not None:
raise e
if block_shape[0] == 0:
raise ValueError("Empty data passed with indices specified.")
raise ValueError(f"Shape of passed values is {passed}, indices imply {implied}")
# -----------------------------------------------------------------------
def form_blocks(arrays, names, axes):
# put "leftover" items in float bucket, where else?
# generalize?
items_dict = defaultdict(list)
extra_locs = []
names_idx = ensure_index(names)
if names_idx.equals(axes[0]):
names_indexer = np.arange(len(names_idx))
else:
assert names_idx.intersection(axes[0]).is_unique
names_indexer = names_idx.get_indexer_for(axes[0])
for i, name_idx in enumerate(names_indexer):
if name_idx == -1:
extra_locs.append(i)
continue
k = names[name_idx]
v = arrays[name_idx]
block_type = get_block_type(v)
items_dict[block_type.__name__].append((i, k, v))
blocks = []
if len(items_dict["FloatBlock"]):
float_blocks = _multi_blockify(items_dict["FloatBlock"])
blocks.extend(float_blocks)
if len(items_dict["ComplexBlock"]):
complex_blocks = _multi_blockify(items_dict["ComplexBlock"])
blocks.extend(complex_blocks)
if len(items_dict["TimeDeltaBlock"]):
timedelta_blocks = _multi_blockify(items_dict["TimeDeltaBlock"])
blocks.extend(timedelta_blocks)
if len(items_dict["IntBlock"]):
int_blocks = _multi_blockify(items_dict["IntBlock"])
blocks.extend(int_blocks)
if len(items_dict["DatetimeBlock"]):
datetime_blocks = _simple_blockify(items_dict["DatetimeBlock"], _NS_DTYPE)
blocks.extend(datetime_blocks)
if len(items_dict["DatetimeTZBlock"]):
dttz_blocks = [
make_block(array, klass=DatetimeTZBlock, placement=[i])
for i, _, array in items_dict["DatetimeTZBlock"]
]
blocks.extend(dttz_blocks)
if len(items_dict["BoolBlock"]):
bool_blocks = _simple_blockify(items_dict["BoolBlock"], np.bool_)
blocks.extend(bool_blocks)
if len(items_dict["ObjectBlock"]) > 0:
object_blocks = _simple_blockify(items_dict["ObjectBlock"], np.object_)
blocks.extend(object_blocks)
if len(items_dict["CategoricalBlock"]) > 0:
cat_blocks = [
make_block(array, klass=CategoricalBlock, placement=[i])
for i, _, array in items_dict["CategoricalBlock"]
]
blocks.extend(cat_blocks)
if len(items_dict["ExtensionBlock"]):
external_blocks = [
make_block(array, klass=ExtensionBlock, placement=[i])
for i, _, array in items_dict["ExtensionBlock"]
]
blocks.extend(external_blocks)
if len(items_dict["ObjectValuesExtensionBlock"]):
external_blocks = [
make_block(array, klass=ObjectValuesExtensionBlock, placement=[i])
for i, _, array in items_dict["ObjectValuesExtensionBlock"]
]
blocks.extend(external_blocks)
if len(extra_locs):
shape = (len(extra_locs),) + tuple(len(x) for x in axes[1:])
# empty items -> dtype object
block_values = np.empty(shape, dtype=object)
block_values.fill(np.nan)
na_block = make_block(block_values, placement=extra_locs)
blocks.append(na_block)
return blocks
def _simple_blockify(tuples, dtype):
""" return a single array of a block that has a single dtype; if dtype is
not None, coerce to this dtype
"""
values, placement = _stack_arrays(tuples, dtype)
# TODO: CHECK DTYPE?
if dtype is not None and values.dtype != dtype: # pragma: no cover
values = values.astype(dtype)
block = make_block(values, placement=placement)
return [block]
def _multi_blockify(tuples, dtype=None):
""" return an array of blocks that potentially have different dtypes """
# group by dtype
grouper = itertools.groupby(tuples, lambda x: x[2].dtype)
new_blocks = []
for dtype, tup_block in grouper:
values, placement = _stack_arrays(list(tup_block), dtype)
block = make_block(values, placement=placement)
new_blocks.append(block)
return new_blocks
def _stack_arrays(tuples, dtype):
# fml
def _asarray_compat(x):
if isinstance(x, ABCSeries):
return x._values
else:
return np.asarray(x)
def _shape_compat(x):
if isinstance(x, ABCSeries):
return (len(x),)
else:
return x.shape
placement, names, arrays = zip(*tuples)
first = arrays[0]
shape = (len(arrays),) + _shape_compat(first)
stacked = np.empty(shape, dtype=dtype)
for i, arr in enumerate(arrays):
stacked[i] = _asarray_compat(arr)
return stacked, placement
def _interleaved_dtype(
blocks: List[Block],
) -> Optional[Union[np.dtype, ExtensionDtype]]:
"""Find the common dtype for `blocks`.
Parameters
----------
blocks : List[Block]
Returns
-------
dtype : Optional[Union[np.dtype, ExtensionDtype]]
None is returned when `blocks` is empty.
"""
if not len(blocks):
return None
return find_common_type([b.dtype for b in blocks])
def _consolidate(blocks):
"""
Merge blocks having same dtype, exclude non-consolidating blocks
"""
# sort by _can_consolidate, dtype
gkey = lambda x: x._consolidate_key
grouper = itertools.groupby(sorted(blocks, key=gkey), gkey)
new_blocks = []
for (_can_consolidate, dtype), group_blocks in grouper:
merged_blocks = _merge_blocks(
list(group_blocks), dtype=dtype, _can_consolidate=_can_consolidate
)
new_blocks = _extend_blocks(merged_blocks, new_blocks)
return new_blocks
def _compare_or_regex_search(a, b, regex=False):
"""
Compare two array_like inputs of the same shape or two scalar values
Calls operator.eq or re.search, depending on regex argument. If regex is
True, perform an element-wise regex matching.
Parameters
----------
a : array_like or scalar
b : array_like or scalar
regex : bool, default False
Returns
-------
mask : array_like of bool
"""
if not regex:
op = lambda x: operator.eq(x, b)
else:
op = np.vectorize(
lambda x: bool(re.search(b, x)) if isinstance(x, str) else False
)
is_a_array = isinstance(a, np.ndarray)
is_b_array = isinstance(b, np.ndarray)
if is_datetimelike_v_numeric(a, b) or is_numeric_v_string_like(a, b):
# GH#29553 avoid deprecation warnings from numpy
result = False
else:
result = op(a)
if is_scalar(result) and (is_a_array or is_b_array):
type_names = [type(a).__name__, type(b).__name__]
if is_a_array:
type_names[0] = f"ndarray(dtype={a.dtype})"
if is_b_array:
type_names[1] = f"ndarray(dtype={b.dtype})"
raise TypeError(
f"Cannot compare types {repr(type_names[0])} and {repr(type_names[1])}"
)
return result
def _transform_index(index, func, level=None):
"""
Apply function to all values found in index.
This includes transforming multiindex entries separately.
Only apply function to one level of the MultiIndex if level is specified.
"""
if isinstance(index, MultiIndex):
if level is not None:
items = [
tuple(func(y) if i == level else y for i, y in enumerate(x))
for x in index
]
else:
items = [tuple(func(y) for y in x) for x in index]
return MultiIndex.from_tuples(items, names=index.names)
else:
items = [func(x) for x in index]
return Index(items, name=index.name, tupleize_cols=False)
def _fast_count_smallints(arr):
"""Faster version of set(arr) for sequences of small numbers."""
counts = np.bincount(arr.astype(np.int_))
nz = counts.nonzero()[0]
return np.c_[nz, counts[nz]]
def _preprocess_slice_or_indexer(slice_or_indexer, length, allow_fill):
if isinstance(slice_or_indexer, slice):
return (
"slice",
slice_or_indexer,
libinternals.slice_len(slice_or_indexer, length),
)
elif (
isinstance(slice_or_indexer, np.ndarray) and slice_or_indexer.dtype == np.bool_
):
return "mask", slice_or_indexer, slice_or_indexer.sum()
else:
indexer = np.asanyarray(slice_or_indexer, dtype=np.int64)
if not allow_fill:
indexer = maybe_convert_indices(indexer, length)
return "fancy", indexer, len(indexer)
def concatenate_block_managers(mgrs_indexers, axes, concat_axis, copy):
"""
Concatenate block managers into one.
Parameters
----------
mgrs_indexers : list of (BlockManager, {axis: indexer,...}) tuples
axes : list of Index
concat_axis : int
copy : bool
"""
concat_plans = [
get_mgr_concatenation_plan(mgr, indexers) for mgr, indexers in mgrs_indexers
]
concat_plan = combine_concat_plans(concat_plans, concat_axis)
blocks = []
for placement, join_units in concat_plan:
if len(join_units) == 1 and not join_units[0].indexers:
b = join_units[0].block
values = b.values
if copy:
values = values.copy()
else:
values = values.view()
b = b.make_block_same_class(values, placement=placement)
elif is_uniform_join_units(join_units):
b = join_units[0].block.concat_same_type(
[ju.block for ju in join_units], placement=placement
)
else:
b = make_block(
concatenate_join_units(join_units, concat_axis, copy=copy),
placement=placement,
)
blocks.append(b)
return BlockManager(blocks, axes)
| 30.997495
| 88
| 0.568699
|
0ace1099b0c9dcc1f6b98d9e7dd7eedbe75b8af9
| 3,021
|
py
|
Python
|
wikipedia_for_humans/util.py
|
JarbasAl/wikipedia_for_humans
|
b5a4c308e9c83d650d3593d39eba13d21a433a97
|
[
"MIT"
] | 39
|
2020-04-11T22:06:39.000Z
|
2020-05-16T11:22:16.000Z
|
wikipedia_for_humans/util.py
|
JarbasAl/wikipedia_for_humans
|
b5a4c308e9c83d650d3593d39eba13d21a433a97
|
[
"MIT"
] | 1
|
2021-02-09T20:13:36.000Z
|
2021-02-25T22:47:17.000Z
|
wikipedia_for_humans/util.py
|
JarbasAl/wikipedia_for_humans
|
b5a4c308e9c83d650d3593d39eba13d21a433a97
|
[
"MIT"
] | 4
|
2020-08-11T17:12:16.000Z
|
2021-10-08T04:03:19.000Z
|
from difflib import SequenceMatcher
import re
from inflection import singularize as _singularize_en
from quebra_frases import sentence_tokenize, flatten
def singularize(word, lang="en"):
if lang.startswith("en"):
return _singularize_en(word)
return word.rstrip("s")
def split_sentences(text, new_lines=False):
if new_lines:
return text.split("\n")
return flatten([sentence_tokenize(t) for t in text.split("\n")])
def fuzzy_match(x, against):
"""Perform a 'fuzzy' comparison between two strings.
Returns:
float: match percentage -- 1.0 for perfect match,
down to 0.0 for no match at all.
"""
return SequenceMatcher(None, x, against).ratio()
def match_one(query, choices):
"""
Find best match from a list or dictionary given an input
Arguments:
query: string to test
choices: list or dictionary of choices
Returns: tuple with best match, score
"""
if isinstance(choices, dict):
_choices = list(choices.keys())
elif isinstance(choices, list):
_choices = choices
else:
raise ValueError('a list or dict of choices must be provided')
best = (_choices[0], fuzzy_match(query, _choices[0]))
for c in _choices[1:]:
score = fuzzy_match(query, c)
if score > best[1]:
best = (c, score)
if isinstance(choices, dict):
return (choices[best[0]], best[1])
else:
return best
def remove_parentheses(answer):
# remove [xx] (xx) {xx}
answer = re.sub(r'\[[^)]*\]', '', answer)
answer = re.sub(r'\([^)]*\)', '', answer)
answer = re.sub(r'\{[^)]*\}', '', answer)
answer = answer.replace("(", "").replace(")", "") \
.replace("[", "").replace("]", "").replace("{", "") \
.replace("}", "").strip()
# remove extra spaces
words = [w for w in answer.split(" ") if w.strip()]
answer = " ".join(words)
if not answer:
return None
return answer
def summarize(answer):
if not answer:
return None
return normalize(split_sentences(answer)[0])
def normalize(answer):
if not answer:
return None
return remove_parentheses(answer)
if __name__ == "__main__":
s = "hello. He said"
for s in split_sentences(s):
print(s)
s = "hello . He said"
for s in split_sentences(s):
print(s)
# no splitting
s = "hello.com"
for s in split_sentences(s):
print(s)
s = "A.E:I.O.U"
for s in split_sentences(s):
print(s)
# ambiguous, but will split
s = "hello.He said"
for s in split_sentences(s):
print(s)
# ambiguous, no split
s = "hello. he said" # could be "Jones Jr. thinks ..."
for s in split_sentences(s):
print(s)
s = "hello.he said" # could be "www.hello.com"
for s in split_sentences(s):
print(s)
s = "hello . he said" # TODO maybe split this one?
for s in split_sentences(s):
print(s)
| 26.043103
| 70
| 0.588878
|
ed3a447d0e5ac15886a0bf3c2289032d1ef83e66
| 7,666
|
py
|
Python
|
curequests/cuhttp.py
|
guyskk/curequests
|
731e1996ebd57aec4bd36e728a5a0f7edb83933e
|
[
"MIT"
] | 262
|
2017-10-29T13:48:23.000Z
|
2022-02-22T08:11:32.000Z
|
curequests/cuhttp.py
|
guyskk/curequests
|
731e1996ebd57aec4bd36e728a5a0f7edb83933e
|
[
"MIT"
] | 41
|
2017-10-29T17:15:02.000Z
|
2020-04-01T11:11:01.000Z
|
curequests/cuhttp.py
|
guyskk/curequests
|
731e1996ebd57aec4bd36e728a5a0f7edb83933e
|
[
"MIT"
] | 9
|
2017-10-30T08:42:33.000Z
|
2020-06-15T03:24:13.000Z
|
import zlib
from collections import namedtuple
import httptools
from curio import timeout_after, TaskTimeout
from curio.io import StreamBase
from requests.structures import CaseInsensitiveDict
from requests import ReadTimeout as ReadTimeoutError
from urllib3.response import GzipDecoder as GzipDecoderBase
from urllib3.response import DeflateDecoder as DeflateDecoderBase
from urllib3.exceptions import DecodeError
class ProtocolError(httptools.HttpParserError):
"""ProtocolError"""
class _Decoder:
def decompress(self, *args, **kwargs):
try:
return super().decompress(*args, **kwargs)
except zlib.error as ex:
msg = 'failed to decode response with {}'.format(
type(self).__name__)
raise DecodeError(msg) from ex
class GzipDecoder(_Decoder, GzipDecoderBase):
"""GzipDecoder"""
class DeflateDecoder(_Decoder, DeflateDecoderBase):
"""DeflateDecoder"""
Response = namedtuple('Response', [
'status',
'reason',
'version',
'keep_alive',
'headers',
'stream',
])
MAX_BUFFER_SIZE = 64 * 1024
DEFAULT_BUFFER_SIZE = 4 * 1024
class ResponseStream(StreamBase):
"""Response stream as file object"""
def __init__(self, sock, gen, buffer_size_setter):
super().__init__(sock)
self._gen = gen
self._set_buffer_size = buffer_size_setter
async def _read(self, maxbytes=-1):
maxbytes = maxbytes if maxbytes > 0 else MAX_BUFFER_SIZE
self._set_buffer_size(maxbytes)
try:
return await self._gen.__anext__()
except StopAsyncIteration:
return b''
class ResponseParser:
"""
Attrs:
version
status
reason
keep_alive
headers
body_stream
started
headers_completed
completed
"""
def __init__(self, sock, *, buffer_size=DEFAULT_BUFFER_SIZE, timeout=None):
self._sock = sock
self._parser = httptools.HttpResponseParser(self)
# options
self.buffer_size = buffer_size
self.timeout = timeout
# primary attrs
self.version = None
self.status = None
self.reason = b''
self.headers = []
# temp attrs
self.current_buffer_size = self.buffer_size
self.header_name = b''
self.body_chunks = []
# state
self.started = False
self.headers_completed = False
self.completed = False
# ========= httptools callbacks ========
def on_message_begin(self):
self.started = True
def on_status(self, status: bytes):
self.reason += status
def on_header(self, name: bytes, value: bytes or None):
self.header_name += name
if value is not None:
self.headers.append((self.header_name.decode(), value.decode()))
self.header_name = b''
def on_headers_complete(self):
self.version = self._parser.get_http_version()
self.status = self._parser.get_status_code()
self.reason = self.reason.decode()
self.keep_alive = self._parser.should_keep_alive()
self.headers = CaseInsensitiveDict(self.headers)
self.headers_completed = True
def on_body(self, body: bytes):
# Implement Note: a `feed_data` can cause multi `on_body` when data
# is large, eg: len(data) > 8192, so we should store `body` in a list
self.body_chunks.append(body)
def on_message_complete(self):
self.completed = True
# ========= end httptools callbacks ========
async def recv(self):
if not self.timeout or self.timeout <= 0:
return await self._sock.recv(self.current_buffer_size)
else:
try:
return await timeout_after(
self.timeout,
self._sock.recv(self.current_buffer_size)
)
except TaskTimeout as ex:
raise ReadTimeoutError(str(ex)) from None
def _set_current_buffer_size(self, buffer_size):
self.current_buffer_size = buffer_size
def _get_decoder(self):
mode = self.headers.get('Content-Encoding', '').lower()
if mode == 'gzip':
return GzipDecoder()
elif mode == 'deflate':
return DeflateDecoder()
return None
async def parse(self):
while not self.headers_completed:
data = await self.recv()
self._parser.feed_data(data)
if not data:
break
if not self.headers_completed:
raise ProtocolError('incomplete response headers')
body_stream = self.body_stream()
decoder = self._get_decoder()
if decoder:
body_stream = _decompress(body_stream, decoder)
def stream(chunk_size=DEFAULT_BUFFER_SIZE):
self._set_current_buffer_size(chunk_size)
return body_stream
environ = dict(
version=self.version,
status=self.status,
reason=self.reason,
keep_alive=self.keep_alive,
headers=self.headers,
stream=stream,
)
return Response(**environ)
async def body_stream(self):
while self.body_chunks:
yield self.body_chunks.pop(0)
while not self.completed:
data = await self.recv()
# feed data even when data is empty, so parser will completed
self._parser.feed_data(data)
while self.body_chunks:
yield self.body_chunks.pop(0)
if not data:
break
if not self.completed:
raise ProtocolError('incomplete response body')
class RequestSerializer:
def __init__(self, path, method='GET', *, version='HTTP/1.1', headers=None,
body=b'', body_stream=None):
self.path = path
self.method = method
self.version = version
if headers is None:
self.headers = {}
else:
self.headers = headers
self.body = body if body is not None else b''
self.body_stream = body_stream
def _format_headers(self):
headers = [f'{self.method} {self.path} {self.version}']
for k, v in self.headers.items():
headers.append(f'{k}: {v}')
return '\r\n'.join(headers).encode() + b'\r\n\r\n'
def _format_chunk(self, chunk):
return format(len(chunk), 'X').encode() + b'\r\n' + chunk + b'\r\n'
def _is_chunked(self):
return self.headers.get('Transfer-Encoding', '').lower() == 'chunked'
async def __aiter__(self):
if self.body_stream is None:
# one-off request
if self.method in {'POST', 'PUT', 'PATCH'}:
self.headers['Content-Length'] = len(self.body)
yield self._format_headers()
if self.body:
yield self.body
else:
# stream request
if self._is_chunked():
yield self._format_headers()
async for chunk in self.body_stream:
yield self._format_chunk(chunk)
yield b'0\r\n\r\n'
else:
if 'Content-Length' not in self.headers:
raise ValueError('Content-Length not set')
yield self._format_headers()
async for chunk in self.body_stream:
yield chunk
async def _decompress(body_stream, decoder):
async for chunk in body_stream:
yield decoder.decompress(chunk)
buf = decoder.decompress(b'')
yield buf + decoder.flush()
| 30.181102
| 79
| 0.59653
|
42aad51994083de1541e03763974ae0196f307b8
| 635
|
py
|
Python
|
setup.py
|
Mrucznik/django-workers
|
938fb7ff804532c2b1b6e965e162f28db2c4094a
|
[
"MIT"
] | null | null | null |
setup.py
|
Mrucznik/django-workers
|
938fb7ff804532c2b1b6e965e162f28db2c4094a
|
[
"MIT"
] | null | null | null |
setup.py
|
Mrucznik/django-workers
|
938fb7ff804532c2b1b6e965e162f28db2c4094a
|
[
"MIT"
] | null | null | null |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="django-workers",
version="0.1.3",
author="Gavin Vickery",
author_email="gavin@geekforbrains.com",
description="Simple background tasks for Django",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/Mrucznik/django-workers",
packages=setuptools.find_packages(),
classifiers=(
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
),
)
| 28.863636
| 53
| 0.674016
|
b4ac3afb4636e883081df208c755e55b31271b61
| 5,925
|
py
|
Python
|
online.py
|
AMshoka/Local-Client-Server-Search-engine
|
4357e42757cc46fbe078ca2fee7eadd693431add
|
[
"MIT"
] | null | null | null |
online.py
|
AMshoka/Local-Client-Server-Search-engine
|
4357e42757cc46fbe078ca2fee7eadd693431add
|
[
"MIT"
] | null | null | null |
online.py
|
AMshoka/Local-Client-Server-Search-engine
|
4357e42757cc46fbe078ca2fee7eadd693431add
|
[
"MIT"
] | null | null | null |
from difflib import get_close_matches
import ast
import io
import math
import numpy as np
import json
class QueryNotFoundException(Exception):
pass
def get_result(index_body, index_title, data,q):
# with io.open("index_title.txt", "r", encoding="utf-8") as f:
# text = f.read()
# index_title = ast.literal_eval(text)
lb = index_body.keys()
lt = index_title.keys()
dic = list(lb) + list(lt)
dic = list(dict.fromkeys(dic))
sc = {}
lq = q.split(" ")
res_body = []
res_title = []
word = ''
body_intersect = []
final_result_body = []
#
title_intersect = []
final_result_title = []
if len(lq) > 1:
for w in lq:
pl_body = index_body.get(w)
pl_title = index_title.get(w)
if pl_body != None:
for i in pl_body:
res_body.append(i[0])
if pl_title != None:
for j in pl_title:
res_title.append(j[0])
if pl_body == None and pl_title == None:
return 0,get_close_matches(w, dic, 5, 0.6)
body_intersect = list(set([x for x in res_body if res_body.count(x) > 1]))
title_intersect = list(set([x for x in res_body if res_body.count(x) > 1]))
score_body = {}
score_title = {}
for i in body_intersect:
sum_body = 0
for w in lq:
pl_body = index_body.get(w)
if pl_body != None:
for j in pl_body:
if j[0] == i:
tf = j[1]
sum_body += tf * np.log10(10782 / len(pl_body))
score_body.update({i: sum_body})
for i in title_intersect:
sum_title = 0
for w in lq:
pl_title = index_title.get(w)
# print(pl_title)
if pl_title != None:
for j in pl_title:
if j[0] == i:
tf = j[1]
sum_title += tf * np.log10(10782 / len(pl_title))
score_title.update({i: sum_title})
final_list = body_intersect + title_intersect
final_score = {}
final_sum = 0
for i in final_list:
if i in body_intersect and i in title_intersect:
final_sum = score_body.get(i) + 47 * score_title.get(i)
if i in body_intersect and i not in title_intersect:
final_sum = score_body.get(i)
if i not in body_intersect and i in title_intersect:
final_sum = 47 * score_title.get(i)
final_score.update({i: final_sum})
# sort = sorted(final_score.values())
# sort = list(dict.fromkeys(sort))
# print(sort)
# print('*****************************')
# if sort.reverse() != None:
sigle = {k: v for k, v in sorted(final_score.items(), key=lambda item: item[1])}
sort = list(sigle.keys())
f_result = []
# sort = list(dict.fromkeys(sort))
counter = 0
for i in reversed(sort):
result = data.get(str(i))
result[0] = '{}...'.format(result[0][1:200])
f_result.append(result)
counter += 1
if counter == 20 or counter == len(sort):
break
# print(i)
# print(data.get(str(i)))
return 1, f_result
else:
w = lq[0]
sum_body = 0
sum_title = 0
pl_body = index_body.get(w)
pl_title = index_title.get(w)
if pl_body != None:
for i in pl_body:
res_body.append(i[0])
if pl_title != None:
for j in pl_title:
res_title.append(j[0])
if pl_body == None and pl_title == None:
return 0,get_close_matches(w, dic, 5, 0.6)
score_body = {}
score_title = {}
for i in res_body:
sum_body = 0
pl_body = index_body.get(w)
if pl_body != None:
for j in pl_body:
if j[0] == i:
tf = j[1]
sum_body = tf * np.log10(10782 / len(pl_body))
score_body.update({i: sum_body})
for i in res_title:
sum_title = 0
pl_title = index_title.get(w)
if pl_title != None:
for j in pl_title:
if j[0] == i:
tf = j[1]
sum_title = tf * np.log10(10782 / len(pl_title))
score_title.update({i: sum_title})
final_list = res_body + res_title
final_score = {}
final_sum = 0
for i in final_list:
if i in res_body and i in res_title:
final_sum = score_body.get(i) + 47 * score_title.get(i)
if i in res_body and i not in res_title:
final_sum = score_body.get(i)
if i not in res_body and i in res_title:
final_sum = 47 * score_title.get(i)
final_score.update({i: final_sum})
# print(final_score)
sigle = {k: v for k, v in sorted(final_score.items(), key=lambda item: item[1])}
si = list(sigle.keys())
f_result = []
# si = list(dict.fromkeys(si))
counter = 0
for i in reversed(si):
result = data.get(str(i))
result[0] = '{}...'.format(result[0][1:200])
f_result.append(result)
counter += 1
if counter == 20 or counter == len(si):
break
return 1,f_result
# for i in reversed(si):
# print(data.get(str(i)))
# print(i)
| 35.692771
| 89
| 0.474599
|
8e27ffcda4bd6499803344cfbb2439cc7fe2f9b3
| 1,704
|
py
|
Python
|
test/base.py
|
schlosser/flask-seed
|
0c0dbca87391692087a0a4ab280635f493e8998b
|
[
"MIT"
] | 4
|
2017-01-13T13:28:48.000Z
|
2019-05-10T16:54:12.000Z
|
test/base.py
|
schlosser/flask-seed
|
0c0dbca87391692087a0a4ab280635f493e8998b
|
[
"MIT"
] | null | null | null |
test/base.py
|
schlosser/flask-seed
|
0c0dbca87391692087a0a4ab280635f493e8998b
|
[
"MIT"
] | 1
|
2018-03-06T20:20:10.000Z
|
2018-03-06T20:20:10.000Z
|
"""
.. module:: base
:synopsis: This defines common functionality in our test suite, in the base
class :class:`TestingTemplate`, which should be inherited by all test
suite classes.
.. moduleauthor:: Dan Schlosser <dan@dan@schlosser.io>
"""
import unittest
import mongoengine
from app import create_app
class TestingTemplate(unittest.TestCase):
def setUp(self): # noqa
"""Before every test, make some an example user."""
from app.models import User
user = User(name='Test User', email="testuser@test.com")
user.save()
def tearDown(self): # noqa
"""After every test, delete users created in :func:`setUp`."""
from app.models import User
User.drop_collection()
@classmethod
def setUpClass(cls): # noqa
"""Sets up a test database before each set of tests."""
cls.app = create_app(
MONGODB_SETTINGS={'DB': 'testing'},
TESTING=True,
CSRF_ENABLED=False,
WTF_CSRF_ENABLED=False
)
def request(self, path, method='GET', role='admin', *args, **kwargs):
"""Make an http request with the given role's gplus_id
in the session and a User with the given role in the database.
"""
with self.app.test_client() as c:
kwargs['method'] = method
kwargs['path'] = path
return c.open(*args, **kwargs)
def test_create_test_app(self):
"""Assert that we are in a proper testing environment."""
self.assertTrue(self.app.config['TESTING'])
self.assertFalse(self.app.config['CSRF_ENABLED'])
self.assertEqual(mongoengine.connection.get_db().name, 'testing')
| 32.769231
| 79
| 0.626761
|
6d2cbe99c7d5e1d60be75f46ad89d493ecabcdd2
| 89
|
py
|
Python
|
contrib/bitflip_env/rlgraph/environments/custom/openai/envs/__init__.py
|
RLGraph/RLGraph
|
428fc136a9a075f29a397495b4226a491a287be2
|
[
"Apache-2.0"
] | 290
|
2018-07-29T15:30:57.000Z
|
2022-03-19T02:46:53.000Z
|
contrib/bitflip_env/rlgraph/environments/custom/openai/envs/__init__.py
|
RLGraph/RLGraph
|
428fc136a9a075f29a397495b4226a491a287be2
|
[
"Apache-2.0"
] | 76
|
2018-10-19T08:42:01.000Z
|
2020-05-03T08:34:21.000Z
|
contrib/bitflip_env/rlgraph/environments/custom/openai/envs/__init__.py
|
RLGraph/RLGraph
|
428fc136a9a075f29a397495b4226a491a287be2
|
[
"Apache-2.0"
] | 41
|
2018-10-30T07:05:05.000Z
|
2022-03-01T08:28:24.000Z
|
from contrib.bitflip_env.rlgraph.environments.custom.openai.envs.bit_flip import BitFlip
| 44.5
| 88
| 0.876404
|
0cde9826eeb22f5bd958c43a548d45d05a9b1e51
| 605
|
py
|
Python
|
tests/test_change_title_to_str.py
|
igormorgado/litcorpt
|
669c1852d42231f563fe0cdcf315f4fd66cf719b
|
[
"MIT"
] | null | null | null |
tests/test_change_title_to_str.py
|
igormorgado/litcorpt
|
669c1852d42231f563fe0cdcf315f4fd66cf719b
|
[
"MIT"
] | null | null | null |
tests/test_change_title_to_str.py
|
igormorgado/litcorpt
|
669c1852d42231f563fe0cdcf315f4fd66cf719b
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python
"""An example in how to change a field in model. Not for regular use"""
import litcorpt
def main():
"""Program entrypoint"""
corpus_db = litcorpt.corpus_load()
booksdir = litcorpt.utils.book_dir(litcorpt.utils.get_corpus_datapath())
for document in iter(corpus_db):
document['title'] = document['title'][0]
book = litcorpt.model.Book(**document)
bookdir = booksdir / book.index
print(f'Writting to {bookdir}')
litcorpt.book_write(book, bookdir)
if __name__ == '__main__':
print("This code should not be ran. Skipping.")
| 31.842105
| 76
| 0.667769
|
06e5fcb9b65e8b7b94cb6f78d36ed428b9f15dd9
| 10,765
|
py
|
Python
|
perses/analysis/load_simulations.py
|
hannahbrucemacdonald/perses
|
6b43d200501e587b352dce5aaefef38e4145048b
|
[
"MIT"
] | null | null | null |
perses/analysis/load_simulations.py
|
hannahbrucemacdonald/perses
|
6b43d200501e587b352dce5aaefef38e4145048b
|
[
"MIT"
] | null | null | null |
perses/analysis/load_simulations.py
|
hannahbrucemacdonald/perses
|
6b43d200501e587b352dce5aaefef38e4145048b
|
[
"MIT"
] | null | null | null |
import numpy as np
import matplotlib.pyplot as plt
import sys
from openeye import oechem, oegraphsim
import logging
_logger = logging.getLogger("analysis")
class Molecule(object):
def __init__(self, i, string):
from perses.utils.openeye import smiles_to_oemol
self.line = string
details = string.split(';')
self.index = i
self.smiles, self.name, self.exp, self.experr, self.calc, self.calcerr = details[1:7]
self.mol = smiles_to_oemol(self.smiles)
self.exp = kcal_to_kt(float(self.exp))
self.experr = kcal_to_kt(float(self.experr))
self.calc = kcal_to_kt(float(self.calc))
self.calcerr = kcal_to_kt(float(self.calcerr))
self.mw = self.calculate_molecular_weight()
self.ha = self.heavy_atom_count()
self.simtype = None
def calculate_molecular_weight(self):
""" Calculates the molecular weight of an oemol
Parameters
----------
Returns
-------
float, molecular weight of molecule
"""
return oechem.OECalculateMolecularWeight(self.mol)
def heavy_atom_count(self):
""" Counts the number of heavy atoms in an oemol
Parameters
----------
Returns
-------
int, number of heavy atoms in molecule
"""
return oechem.OECount(self.mol, oechem.OEIsHeavy())
class Simulation(object):
def __init__(self,A,B):
self.ligA = A
self.ligB = B
self.directory = f'lig{self.ligA}to{self.ligB}'
self.vacdg = None
self.vacddg = None
self.soldg = None
self.solddg = None
self.comdg = None
self.comddg = None
self.vacdg_history = []
self.soldg_history = []
self.comdg_history = []
self.vacddg_history = []
self.solddg_history = []
self.comddg_history = []
self.vacdg_history_es = []
self.soldg_history_es = []
self.comdg_history_es = []
self.vacddg_history_es = []
self.solddg_history_es = []
self.comddg_history_es = []
self.count = 0
self.load_data()
if self.vacdg is not None and self.soldg is not None:
self.hydrationdg = self.vacdg - self.soldg
self.hydrationddg = (self.vacddg + self.solddg)**0.5
self.hydrationdg_es = self.vacf_ij[0,-1] - self.solf_ij[0,-1]
self.hydrationddg_es = (self.vacdf_ij[0,-1] + self.soldf_ij[0,-1])**0.5
else:
print('Both vacuum and solvent legs need to be run for hydration free energies')
if self.comdg is not None and self.soldg is not None:
self.bindingdg = self.soldg - self.comdg
self.bindingddg = (self.comddg + self.solddg)**0.5
self.bindingdg_es = self.solf_ij[0,-1] - self.comf_ij[0,-1]
self.bindingddg_es = (self.soldf_ij[0,-1] + self.comdf_ij[0,-1])**0.5
else:
print('Both solvent and complex legs need to be run for binding free energies')
def load_data(self):
""" Calculate relative free energy details from the simulation by performing MBAR on the vacuum and solvent legs of the simualtion.
Parameters
----------
Returns
-------
None
"""
from pymbar import timeseries
from pymbar import MBAR
from perses.analysis import utils
import os
from openmmtools.multistate import MultiStateReporter, MultiStateSamplerAnalyzer
# find the output files
output = [x for x in os.listdir(self.directory) if x[-3:] == '.nc' and 'checkpoint' not in x]
for out in output:
if 'vacuum' in out:
vacuum_reporter = MultiStateReporter(f'{self.directory}/{out}')
vacuum_analyzer = MultiStateSamplerAnalyzer(vacuum_reporter)
f_ij, df_ij = vacuum_analyzer.get_free_energy()
self.vacdg = f_ij[1, -2]
self.vacddg = df_ij[1, -2] ** 2
self.vacf_ij = f_ij
self.vacdf_ij = df_ij
elif'solvent' in out:
solvent_reporter = MultiStateReporter(f'{self.directory}/{out}')
solvent_analyzer = MultiStateSamplerAnalyzer(solvent_reporter)
f_ij, df_ij = solvent_analyzer.get_free_energy()
self.soldg = f_ij[1, -2]
self.solddg = df_ij[1, -2] ** 2
self.solf_ij = f_ij
self.soldf_ij = df_ij
elif 'complex' in out:
complex_reporter = MultiStateReporter(f'{self.directory}/{out}')
complex_analyzer = MultiStateSamplerAnalyzer(complex_reporter)
f_ij, df_ij = complex_analyzer.get_free_energy()
self.comdg = f_ij[1, -2]
self.comddg = df_ij[1, -2] ** 2
self.comf_ij = f_ij
self.comdf_ij = df_ij
return
def historic_fes(self,stepsize=100):
from pymbar import timeseries
from pymbar import MBAR
from perses.analysis import utils
import os
from openmmtools.multistate import MultiStateReporter, MultiStateSamplerAnalyzer
# find the output files
output = [x for x in os.listdir(self.directory) if x[-3:] == '.nc' and 'checkpoint' not in x]
for out in output:
if 'vacuum' in out:
vacuum_reporter = MultiStateReporter(f'{self.directory}/{out}')
ncfile = utils.open_netcdf(f'{self.directory}/{out}')
n_iterations = ncfile.variables['last_iteration'][0]
for step in range(stepsize, n_iterations, stepsize):
vacuum_analyzer = MultiStateSamplerAnalyzer(vacuum_reporter,max_n_iterations=step)
f_ij, df_ij = vacuum_analyzer.get_free_energy()
self.vacdg_history.append(f_ij[1, -2])
self.vacddg_history.append(df_ij[1,-2])
self.vacdg_history_es.append(f_ij[0, -1])
self.vacddg_history_es.append(df_ij[0,-1])
if 'solvent' in out:
solvent_reporter = MultiStateReporter(f'{self.directory}/{out}')
ncfile = utils.open_netcdf(f'{self.directory}/{out}')
n_iterations = ncfile.variables['last_iteration'][0]
for step in range(stepsize, n_iterations, stepsize):
solvent_analyzer = MultiStateSamplerAnalyzer(solvent_reporter,max_n_iterations=step)
f_ij, df_ij = solvent_analyzer.get_free_energy()
self.soldg_history.append(f_ij[1, -2])
self.solddg_history.append(df_ij[1,-2])
self.soldg_history_es.append(f_ij[0, -1])
self.solddg_history_es.append(df_ij[0,-1])
if 'complex' in out:
complex_reporter = MultiStateReporter(f'{self.directory}/{out}')
ncfile = utils.open_netcdf(f'{self.directory}/{out}')
n_iterations = ncfile.variables['last_iteration'][0]
for step in range(stepsize, n_iterations, stepsize):
complex_analyzer = MultiStateSamplerAnalyzer(complex_reporter,max_n_iterations=step)
f_ij, df_ij = complex_analyzer.get_free_energy()
self.comdg_history.append(f_ij[1, -2])
self.comddg_history.append(df_ij[1,-2])
self.comdg_history_es.append(f_ij[0, -1])
self.comddg_history_es.append(df_ij[0,-1])
return
def sample_history(self,method='binding'):
vac = self.vacdg_history[self.count]
sol = self.soldg_history[self.count]
com = self.comdg_history[self.count]
vacvar = self.vacddg_history[self.count]
solvar = self.solddg_history[self.count]
comvar = self.comddg_history[self.count]
self.count += 1
if method == 'binding':
return sol - com , (solvar**2 + comvar**2)**0.5
elif method == 'hydration':
return vac - sol , (solvar**2 + vacvar**2)**0.5
else:
print('method not recognised, choose binding or hydration')
def reset_history(self):
self.count = 0
def kcal_to_kt(x):
"""
This should be deleted and just use the simtk units protocol
:param x: float, energy in kcal
:return: float, energy in kT
"""
# TODO remove this
return x*1.688
def get_experimental(molecules, i,j):
""" Determine experimental relative free energy from two experimntal absolute results
Parameters
----------
molecules : list
list of load_simulation.molecule objects
i : int
index of first molecule
j : int
index of second molecule
Returns
-------
tuple
relative free energy and associated error
"""
moli = molecules[i]
molj = molecules[j]
ddG = moli.exp - molj.exp
ddG_err = moli.experr - molj.experr
return (ddG, ddG_err)
def load_experimental(exp_file):
""" Load details from a freesolv database.txt-like file
Parameters
----------
exp_file : str
path to text file
Returns
-------
list
list of load_simulation.molecule objects, contained in the textfile
"""
molecules = []
with open(exp_file) as f:
for i, line in enumerate(f):
molecules.append(molecule(i, line))
return molecules
def run(molecules,simtype='sams',offline_freq=10):
"""Load the simulation data for a set of molecules, for both forward and backward simulations
Parameters
----------
molecules : list
list of load_simulation.molecule objects, of which to find simulation data for
simtype : type
Description of parameter `simtype`.
offline_freq : type
Description of parameter `offline_freq`.
Returns
-------
type
Description of returned object.
"""
import itertools
import os
n_ligands = len(molecules)
all_simulations = []
for a, b in itertools.combinations(range(0, n_ligands), 2):
path = f'lig{a}to{b}'
if os.path.isdir(path) == True:
sim = simulation(a, b)
all_simulations.append(sim)
else:
print(f'Output directory lig{a}to{b} doesnt exist')
# now run the opposite direction
path = f'lig{b}to{a}'
if os.path.isdir(path) == True:
sim = simulation(b, a)
all_simulations.append(sim)
else:
print(f'Output directory lig{b}to{a} doesnt exist')
return all_simulations
if __name__ == '__main__':
run(sys.argv[1])
| 34.614148
| 139
| 0.591547
|
b245a1128751ee40095502cf5b592f17c7b861d1
| 25,424
|
py
|
Python
|
tests/serialization/test_dag_serialization.py
|
harishmk/airflow
|
5abce471e0690c6b8d06ca25685b0845c5fd270f
|
[
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | 2
|
2019-01-14T16:39:27.000Z
|
2019-01-24T21:53:13.000Z
|
tests/serialization/test_dag_serialization.py
|
harishmk/airflow
|
5abce471e0690c6b8d06ca25685b0845c5fd270f
|
[
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | 3
|
2018-10-05T18:00:01.000Z
|
2019-03-27T22:17:44.000Z
|
tests/serialization/test_dag_serialization.py
|
harishmk/airflow
|
5abce471e0690c6b8d06ca25685b0845c5fd270f
|
[
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | 2
|
2018-09-26T19:37:33.000Z
|
2019-03-01T21:28:04.000Z
|
# -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Unit tests for stringified DAGs."""
import multiprocessing
import unittest
from datetime import datetime, timedelta
from unittest import mock
from dateutil.relativedelta import FR, relativedelta
from parameterized import parameterized
from airflow import example_dags
from airflow.contrib import example_dags as contrib_example_dags
from airflow.gcp import example_dags as gcp_example_dags
from airflow.hooks.base_hook import BaseHook
from airflow.models import DAG, Connection, DagBag, TaskInstance
from airflow.models.baseoperator import BaseOperator
from airflow.operators.bash_operator import BashOperator
from airflow.operators.subdag_operator import SubDagOperator
from airflow.serialization.json_schema import load_dag_schema_dict
from airflow.serialization.serialized_objects import SerializedBaseOperator, SerializedDAG
from tests.test_utils.mock_operators import CustomOperator, CustomOpLink, GoogleLink
serialized_simple_dag_ground_truth = {
"__version": 1,
"dag": {
"default_args": {
"__type": "dict",
"__var": {
"depends_on_past": False,
"retries": 1,
"retry_delay": {
"__type": "timedelta",
"__var": 300.0
}
}
},
"start_date": 1564617600.0,
"is_paused_upon_creation": False,
"_dag_id": "simple_dag",
"fileloc": None,
"tasks": [
{
"task_id": "simple_task",
"owner": "airflow",
"retries": 1,
"retry_delay": 300.0,
"_downstream_task_ids": [],
"_inlets": [],
"_outlets": [],
"ui_color": "#fff",
"ui_fgcolor": "#000",
"template_fields": [],
"_task_type": "BaseOperator",
"_task_module": "airflow.models.baseoperator",
},
{
"task_id": "custom_task",
"retries": 1,
"retry_delay": 300.0,
"_downstream_task_ids": [],
"_inlets": [],
"_outlets": [],
"_operator_extra_links": [{"tests.test_utils.mock_operators.CustomOpLink": {}}],
"ui_color": "#fff",
"ui_fgcolor": "#000",
"template_fields": [],
"_task_type": "CustomOperator",
"_task_module": "tests.test_utils.mock_operators",
},
],
"timezone": "UTC",
},
}
def make_example_dags(module):
"""Loads DAGs from a module for test."""
dagbag = DagBag(module.__path__[0])
return dagbag.dags
def make_simple_dag():
"""Make very simple DAG to verify serialization result."""
dag = DAG(
dag_id='simple_dag',
default_args={
"retries": 1,
"retry_delay": timedelta(minutes=5),
"depends_on_past": False,
},
start_date=datetime(2019, 8, 1),
is_paused_upon_creation=False,
)
BaseOperator(task_id='simple_task', dag=dag, owner='airflow')
CustomOperator(task_id='custom_task', dag=dag)
return {'simple_dag': dag}
def make_user_defined_macro_filter_dag():
""" Make DAGs with user defined macros and filters using locally defined methods.
For Webserver, we do not include ``user_defined_macros`` & ``user_defined_filters``.
The examples here test:
(1) functions can be successfully displayed on UI;
(2) templates with function macros have been rendered before serialization.
"""
def compute_next_execution_date(dag, execution_date):
return dag.following_schedule(execution_date)
default_args = {
'start_date': datetime(2019, 7, 10)
}
dag = DAG(
'user_defined_macro_filter_dag',
default_args=default_args,
user_defined_macros={
'next_execution_date': compute_next_execution_date,
},
user_defined_filters={
'hello': lambda name: 'Hello %s' % name
},
catchup=False
)
BashOperator(
task_id='echo',
bash_command='echo "{{ next_execution_date(dag, execution_date) }}"',
dag=dag,
)
return {dag.dag_id: dag}
def collect_dags():
"""Collects DAGs to test."""
dags = {}
dags.update(make_simple_dag())
dags.update(make_user_defined_macro_filter_dag())
dags.update(make_example_dags(example_dags))
dags.update(make_example_dags(contrib_example_dags))
dags.update(make_example_dags(gcp_example_dags))
# Filter subdags as they are stored in same row in Serialized Dag table
dags = {dag_id: dag for dag_id, dag in dags.items() if not dag.is_subdag}
return dags
def serialize_subprocess(queue):
"""Validate pickle in a subprocess."""
dags = collect_dags()
for dag in dags.values():
queue.put(SerializedDAG.to_json(dag))
queue.put(None)
class TestStringifiedDAGs(unittest.TestCase):
"""Unit tests for stringified DAGs."""
def setUp(self):
super().setUp()
BaseHook.get_connection = mock.Mock(
return_value=Connection(
extra=('{'
'"project_id": "mock", '
'"location": "mock", '
'"instance": "mock", '
'"database_type": "postgres", '
'"use_proxy": "False", '
'"use_ssl": "False"'
'}')))
self.maxDiff = None # pylint: disable=invalid-name
def test_serialization(self):
"""Serialization and deserialization should work for every DAG and Operator."""
dags = collect_dags()
serialized_dags = {}
for _, v in dags.items():
dag = SerializedDAG.to_dict(v)
SerializedDAG.validate_schema(dag)
serialized_dags[v.dag_id] = dag
# Compares with the ground truth of JSON string.
self.validate_serialized_dag(
serialized_dags['simple_dag'],
serialized_simple_dag_ground_truth)
def validate_serialized_dag(self, json_dag, ground_truth_dag):
"""Verify serialized DAGs match the ground truth."""
self.assertTrue(
json_dag['dag']['fileloc'].split('/')[-1] == 'test_dag_serialization.py')
json_dag['dag']['fileloc'] = None
def sorted_serialized_dag(dag_dict: dict):
"""
Sorts the "tasks" list in the serialised dag python dictionary
This is needed as the order of tasks should not matter but assertEqual
would fail if the order of tasks list changes in dag dictionary
"""
dag_dict["dag"]["tasks"] = sorted(dag_dict["dag"]["tasks"],
key=lambda x: sorted(x.keys()))
return dag_dict
self.assertEqual(sorted_serialized_dag(ground_truth_dag),
sorted_serialized_dag(json_dag))
def test_deserialization(self):
"""A serialized DAG can be deserialized in another process."""
queue = multiprocessing.Queue()
proc = multiprocessing.Process(
target=serialize_subprocess, args=(queue,))
proc.daemon = True
proc.start()
stringified_dags = {}
while True:
v = queue.get()
if v is None:
break
dag = SerializedDAG.from_json(v)
self.assertTrue(isinstance(dag, DAG))
stringified_dags[dag.dag_id] = dag
dags = collect_dags()
self.assertTrue(set(stringified_dags.keys()) == set(dags.keys()))
# Verify deserialized DAGs.
for dag_id in stringified_dags:
self.validate_deserialized_dag(stringified_dags[dag_id], dags[dag_id])
example_skip_dag = stringified_dags['example_skip_dag']
skip_operator_1_task = example_skip_dag.task_dict['skip_operator_1']
self.validate_deserialized_task(
skip_operator_1_task, 'DummySkipOperator', '#e8b7e4', '#000')
# Verify that the DAG object has 'full_filepath' attribute
# and is equal to fileloc
self.assertTrue(hasattr(example_skip_dag, 'full_filepath'))
self.assertEqual(example_skip_dag.full_filepath, example_skip_dag.fileloc)
example_subdag_operator = stringified_dags['example_subdag_operator']
section_1_task = example_subdag_operator.task_dict['section-1']
self.validate_deserialized_task(
section_1_task,
SubDagOperator.__name__,
SubDagOperator.ui_color,
SubDagOperator.ui_fgcolor
)
def validate_deserialized_dag(self, serialized_dag, dag):
"""
Verify that all example DAGs work with DAG Serialization by
checking fields between Serialized Dags & non-Serialized Dags
"""
fields_to_check = [
"task_ids", "params", "fileloc", "max_active_runs", "concurrency",
"is_paused_upon_creation", "doc_md", "safe_dag_id", "is_subdag",
"catchup", "description", "start_date", "end_date", "parent_dag",
"template_searchpath"
]
# fields_to_check = dag.get_serialized_fields()
for field in fields_to_check:
self.assertEqual(getattr(serialized_dag, field), getattr(dag, field))
def validate_deserialized_task(self, task, task_type, ui_color, ui_fgcolor):
"""Verify non-airflow operators are casted to BaseOperator."""
self.assertTrue(isinstance(task, SerializedBaseOperator))
# Verify the original operator class is recorded for UI.
self.assertTrue(task.task_type == task_type)
self.assertTrue(task.ui_color == ui_color)
self.assertTrue(task.ui_fgcolor == ui_fgcolor)
# Check that for Deserialised task, task.subdag is None for all other Operators
# except for the SubDagOperator where task.subdag is an instance of DAG object
if task.task_type == "SubDagOperator":
self.assertIsNotNone(task.subdag)
self.assertTrue(isinstance(task.subdag, DAG))
else:
self.assertIsNone(task.subdag)
self.assertEqual({}, task.params)
self.assertEqual({}, task.executor_config)
@parameterized.expand([
(datetime(2019, 8, 1), None, datetime(2019, 8, 1)),
(datetime(2019, 8, 1), datetime(2019, 8, 2), datetime(2019, 8, 2)),
(datetime(2019, 8, 1), datetime(2019, 7, 30), datetime(2019, 8, 1)),
])
def test_deserialization_start_date(self,
dag_start_date,
task_start_date,
expected_task_start_date):
dag = DAG(dag_id='simple_dag', start_date=dag_start_date)
BaseOperator(task_id='simple_task', dag=dag, start_date=task_start_date)
serialized_dag = SerializedDAG.to_dict(dag)
if not task_start_date or dag_start_date >= task_start_date:
# If dag.start_date > task.start_date -> task.start_date=dag.start_date
# because of the logic in dag.add_task()
self.assertNotIn("start_date", serialized_dag["dag"]["tasks"][0])
else:
self.assertIn("start_date", serialized_dag["dag"]["tasks"][0])
dag = SerializedDAG.from_dict(serialized_dag)
simple_task = dag.task_dict["simple_task"]
self.assertEqual(simple_task.start_date, expected_task_start_date)
@parameterized.expand([
(datetime(2019, 8, 1), None, datetime(2019, 8, 1)),
(datetime(2019, 8, 1), datetime(2019, 8, 2), datetime(2019, 8, 1)),
(datetime(2019, 8, 1), datetime(2019, 7, 30), datetime(2019, 7, 30)),
])
def test_deserialization_end_date(self,
dag_end_date,
task_end_date,
expected_task_end_date):
dag = DAG(dag_id='simple_dag', start_date=datetime(2019, 8, 1),
end_date=dag_end_date)
BaseOperator(task_id='simple_task', dag=dag, end_date=task_end_date)
serialized_dag = SerializedDAG.to_dict(dag)
if not task_end_date or dag_end_date <= task_end_date:
# If dag.end_date < task.end_date -> task.end_date=dag.end_date
# because of the logic in dag.add_task()
self.assertNotIn("end_date", serialized_dag["dag"]["tasks"][0])
else:
self.assertIn("end_date", serialized_dag["dag"]["tasks"][0])
dag = SerializedDAG.from_dict(serialized_dag)
simple_task = dag.task_dict["simple_task"]
self.assertEqual(simple_task.end_date, expected_task_end_date)
@parameterized.expand([
(None, None),
("@weekly", "@weekly"),
({"__type": "timedelta", "__var": 86400.0}, timedelta(days=1)),
])
def test_deserialization_schedule_interval(self, serialized_schedule_interval, expected):
serialized = {
"__version": 1,
"dag": {
"default_args": {"__type": "dict", "__var": {}},
"_dag_id": "simple_dag",
"fileloc": __file__,
"tasks": [],
"timezone": "UTC",
"schedule_interval": serialized_schedule_interval,
},
}
SerializedDAG.validate_schema(serialized)
dag = SerializedDAG.from_dict(serialized)
self.assertEqual(dag.schedule_interval, expected)
@parameterized.expand([
(relativedelta(days=-1), {"__type": "relativedelta", "__var": {"days": -1}}),
(relativedelta(month=1, days=-1), {"__type": "relativedelta", "__var": {"month": 1, "days": -1}}),
# Every friday
(relativedelta(weekday=FR), {"__type": "relativedelta", "__var": {"weekday": [4]}}),
# Every second friday
(relativedelta(weekday=FR(2)), {"__type": "relativedelta", "__var": {"weekday": [4, 2]}})
])
def test_roundtrip_relativedelta(self, val, expected):
serialized = SerializedDAG._serialize(val)
self.assertDictEqual(serialized, expected)
round_tripped = SerializedDAG._deserialize(serialized)
self.assertEqual(val, round_tripped)
@parameterized.expand([
(None, {}),
({"param_1": "value_1"}, {"param_1": "value_1"}),
])
def test_dag_params_roundtrip(self, val, expected_val):
"""
Test that params work both on Serialized DAGs & Tasks
"""
dag = DAG(dag_id='simple_dag', params=val)
BaseOperator(task_id='simple_task', dag=dag, start_date=datetime(2019, 8, 1))
serialized_dag = SerializedDAG.to_dict(dag)
if val:
self.assertIn("params", serialized_dag["dag"])
else:
self.assertNotIn("params", serialized_dag["dag"])
deserialized_dag = SerializedDAG.from_dict(serialized_dag)
deserialized_simple_task = deserialized_dag.task_dict["simple_task"]
self.assertEqual(expected_val, deserialized_dag.params)
self.assertEqual(expected_val, deserialized_simple_task.params)
@parameterized.expand([
(None, {}),
({"param_1": "value_1"}, {"param_1": "value_1"}),
])
def test_task_params_roundtrip(self, val, expected_val):
"""
Test that params work both on Serialized DAGs & Tasks
"""
dag = DAG(dag_id='simple_dag')
BaseOperator(task_id='simple_task', dag=dag, params=val,
start_date=datetime(2019, 8, 1))
serialized_dag = SerializedDAG.to_dict(dag)
if val:
self.assertIn("params", serialized_dag["dag"]["tasks"][0])
else:
self.assertNotIn("params", serialized_dag["dag"]["tasks"][0])
deserialized_dag = SerializedDAG.from_dict(serialized_dag)
deserialized_simple_task = deserialized_dag.task_dict["simple_task"]
self.assertEqual(expected_val, deserialized_simple_task.params)
def test_extra_serialized_field_and_operator_links(self):
"""
Assert extra field exists & OperatorLinks defined in Plugins and inbuilt Operator Links.
This tests also depends on GoogleLink() registered as a plugin
in tests/plugins/test_plugin.py
The function tests that if extra operator links are registered in plugin
in ``operator_extra_links`` and the same is also defined in
the Operator in ``BaseOperator.operator_extra_links``, it has the correct
extra link.
"""
test_date = datetime(2019, 8, 1)
dag = DAG(dag_id='simple_dag', start_date=test_date)
CustomOperator(task_id='simple_task', dag=dag, bash_command="true")
serialized_dag = SerializedDAG.to_dict(dag)
self.assertIn("bash_command", serialized_dag["dag"]["tasks"][0])
dag = SerializedDAG.from_dict(serialized_dag)
simple_task = dag.task_dict["simple_task"]
self.assertEqual(getattr(simple_task, "bash_command"), "true")
#########################################################
# Verify Operator Links work with Serialized Operator
#########################################################
# Check Serialized version of operator link only contains the inbuilt Op Link
self.assertEqual(
serialized_dag["dag"]["tasks"][0]["_operator_extra_links"],
[{'tests.test_utils.mock_operators.CustomOpLink': {}}]
)
# Test all the extra_links are set
self.assertCountEqual(simple_task.extra_links, ['Google Custom', 'airflow', 'github', 'google'])
ti = TaskInstance(task=simple_task, execution_date=test_date)
ti.xcom_push('search_query', "dummy_value_1")
# Test Deserialized inbuilt link
custom_inbuilt_link = simple_task.get_extra_links(test_date, CustomOpLink.name)
self.assertEqual('http://google.com/custom_base_link?search=dummy_value_1', custom_inbuilt_link)
# Test Deserialized link registered via Airflow Plugin
google_link_from_plugin = simple_task.get_extra_links(test_date, GoogleLink.name)
self.assertEqual("https://www.google.com", google_link_from_plugin)
def test_extra_serialized_field_and_multiple_operator_links(self):
"""
Assert extra field exists & OperatorLinks defined in Plugins and inbuilt Operator Links.
This tests also depends on GoogleLink() registered as a plugin
in tests/plugins/test_plugin.py
The function tests that if extra operator links are registered in plugin
in ``operator_extra_links`` and the same is also defined in
the Operator in ``BaseOperator.operator_extra_links``, it has the correct
extra link.
"""
test_date = datetime(2019, 8, 1)
dag = DAG(dag_id='simple_dag', start_date=test_date)
CustomOperator(task_id='simple_task', dag=dag, bash_command=["echo", "true"])
serialized_dag = SerializedDAG.to_dict(dag)
self.assertIn("bash_command", serialized_dag["dag"]["tasks"][0])
dag = SerializedDAG.from_dict(serialized_dag)
simple_task = dag.task_dict["simple_task"]
self.assertEqual(getattr(simple_task, "bash_command"), ["echo", "true"])
#########################################################
# Verify Operator Links work with Serialized Operator
#########################################################
# Check Serialized version of operator link only contains the inbuilt Op Link
self.assertEqual(
serialized_dag["dag"]["tasks"][0]["_operator_extra_links"],
[
{'tests.test_utils.mock_operators.CustomBaseIndexOpLink': {'index': 0}},
{'tests.test_utils.mock_operators.CustomBaseIndexOpLink': {'index': 1}},
]
)
# Test all the extra_links are set
self.assertCountEqual(simple_task.extra_links, [
'BigQuery Console #1', 'BigQuery Console #2', 'airflow', 'github', 'google'])
ti = TaskInstance(task=simple_task, execution_date=test_date)
ti.xcom_push('search_query', ["dummy_value_1", "dummy_value_2"])
# Test Deserialized inbuilt link #1
custom_inbuilt_link = simple_task.get_extra_links(test_date, "BigQuery Console #1")
self.assertEqual('https://console.cloud.google.com/bigquery?j=dummy_value_1', custom_inbuilt_link)
# Test Deserialized inbuilt link #2
custom_inbuilt_link = simple_task.get_extra_links(test_date, "BigQuery Console #2")
self.assertEqual('https://console.cloud.google.com/bigquery?j=dummy_value_2', custom_inbuilt_link)
# Test Deserialized link registered via Airflow Plugin
google_link_from_plugin = simple_task.get_extra_links(test_date, GoogleLink.name)
self.assertEqual("https://www.google.com", google_link_from_plugin)
def test_dag_serialized_fields_with_schema(self):
"""
Additional Properties are disabled on DAGs. This test verifies that all the
keys in DAG.get_serialized_fields are listed in Schema definition.
"""
dag_schema: dict = load_dag_schema_dict()["definitions"]["dag"]["properties"]
# The parameters we add manually in Serialization needs to be ignored
ignored_keys: set = {"is_subdag", "tasks"}
dag_params: set = set(dag_schema.keys()) - ignored_keys
self.assertEqual(set(DAG.get_serialized_fields()), dag_params)
def test_no_new_fields_added_to_base_operator(self):
"""
This test verifies that there are no new fields added to BaseOperator. And reminds that
tests should be added for it.
"""
base_operator = BaseOperator(task_id="10")
fields = base_operator.__dict__
self.assertEqual({'_dag': None,
'_downstream_task_ids': set(),
'_inlets': [],
'_log': base_operator.log,
'_outlets': [],
'_upstream_task_ids': set(),
'depends_on_past': False,
'do_xcom_push': True,
'email': None,
'email_on_failure': True,
'email_on_retry': True,
'end_date': None,
'execution_timeout': None,
'executor_config': {},
'inlets': [],
'max_retry_delay': None,
'on_execute_callback': None,
'on_failure_callback': None,
'on_retry_callback': None,
'on_success_callback': None,
'outlets': [],
'owner': 'airflow',
'params': {},
'pool': 'default_pool',
'priority_weight': 1,
'queue': 'default',
'resources': None,
'retries': 0,
'retry_delay': timedelta(0, 300),
'retry_exponential_backoff': False,
'run_as_user': None,
'sla': None,
'start_date': None,
'subdag': None,
'task_concurrency': None,
'task_id': '10',
'trigger_rule': 'all_success',
'wait_for_downstream': False,
'weight_rule': 'downstream'}, fields,
"""
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
ACTION NEEDED! PLEASE READ THIS CAREFULLY AND CORRECT TESTS CAREFULLY
Some fields were added to the BaseOperator! Please add them to the list above and make sure that
you add support for DAG serialization - you should add the field to
`airflow/serialization/schema.json` - they should have correct type defined there.
Note that we do not support versioning yet so you should only add optional fields to BaseOperator.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
"""
)
if __name__ == '__main__':
unittest.main()
| 41.678689
| 106
| 0.599158
|
240edd3679b8559ce96b35d822b8b68a3f89e2f7
| 8,756
|
py
|
Python
|
gui/pages/groups.py
|
arbeitsgruppe-digitale-altnordistik/Sammlung-Toole
|
502d6128e55622b760c245b03d973574f0adab4c
|
[
"MIT"
] | null | null | null |
gui/pages/groups.py
|
arbeitsgruppe-digitale-altnordistik/Sammlung-Toole
|
502d6128e55622b760c245b03d973574f0adab4c
|
[
"MIT"
] | 36
|
2021-08-29T20:04:31.000Z
|
2022-03-19T12:10:47.000Z
|
gui/pages/groups.py
|
arbeitsgruppe-digitale-altnordistik/Sammlung-Toole
|
502d6128e55622b760c245b03d973574f0adab4c
|
[
"MIT"
] | null | null | null |
from logging import Logger
from typing import Set
from uuid import UUID
import streamlit as st
from util import utils
from util.datahandler import DataHandler
from util.groups import Group, GroupType
from util.stateHandler import StateHandler, Step
from util.utils import SearchOptions
@st.experimental_singleton # type: ignore
def get_log() -> Logger:
return utils.get_logger(__name__)
log: Logger = get_log()
def browse_groups(state: StateHandler) -> None:
"""Page: Browse Groups
This page of the streamlit app allows browsing the different groups stored in the data handler.
Args:
state (StateHandler): The StateHandler object orchestrating the current session state.
"""
handler: DataHandler = state.data_handler
groups = handler.groups
log.debug(f"Browsing Groups: {groups}")
st.title("Groups")
if state.steps.browseGroups == Step.Browse_Groups.Browse:
# Manuscript Groups
st.header("Manuscript Groups")
mss = [(b.name, f"{len(b.items)} Manuscripts", b.date.strftime('%c')) for a, b in groups.manuscript_groups.items()]
st.table(mss)
if len(mss) >= 2 and st.button("Combine existing groups to a new group", key="btn_combine_mss"):
state.steps.browseGroups = Step.Browse_Groups.Combine_MSS
st.experimental_rerun()
# Text Groups
st.header("Text Groups")
txt = [(b.name, f"{len(b.items)} Texts", b.date.strftime('%c')) for a, b in groups.text_groups.items()]
st.table(txt)
if len(txt) >= 2 and st.button("Combine existing groups to a new group", key="btn_combine_txt"):
state.steps.browseGroups = Step.Browse_Groups.Combine_TXT
st.experimental_rerun()
# Person Groups
st.header("People Groups")
ppl = [(b.name, f"{len(b.items)} People", b.date.strftime('%c')) for a, b in groups.person_groups.items()]
st.table(ppl)
if len(ppl) >= 2 and st.button("Combine existing groups to a new group", key="btn_combine_ppl"):
state.steps.browseGroups = Step.Browse_Groups.Combine_PPL
st.experimental_rerun()
elif state.steps.browseGroups == Step.Browse_Groups.Combine_MSS:
__combine_mss_groups(state)
elif state.steps.browseGroups == Step.Browse_Groups.Combine_TXT:
__combine_txt_groups(state)
elif state.steps.browseGroups == Step.Browse_Groups.Combine_PPL:
__combine_ppl_groups(state)
def __combine_mss_groups(state: StateHandler) -> None:
"""Page for combining Manuscript groups"""
groups = state.data_handler.groups.manuscript_groups
st.header("Combine Manuscript Groups")
if st.button("Back to Overview"):
state.steps.browseGroups = Step.Browse_Groups.Browse
st.experimental_rerun()
st.write("---")
modes = {
'OR (union - pick items that appear in at least one selected group)': SearchOptions.CONTAINS_ONE,
'AND (intersection - pick items that appear in all selected groups)': SearchOptions.CONTAINS_ALL,
}
mode_selection = st.radio('Combination mode', modes.keys())
mode = modes[mode_selection]
st.write("---")
st.write("Select the groups you want to combine.")
selections: Set[UUID] = set()
for i, g in enumerate(groups.values()):
if st.checkbox(f"{i}: Group name: '{g.name}'", key=str(g.group_id)):
selections.add(g.group_id)
st.write("---")
if len(selections) > 1:
selected_groups = [groups[s] for s in selections]
sets = [g.items for g in selected_groups]
if mode == SearchOptions.CONTAINS_ONE:
res = set.union(*sets)
else:
res = set.intersection(*sets)
if not res:
st.write("No Manuscripts fitting the criteria. (Maybe consider using OR instead of AND for combination logic.)")
else:
st.write(f"The combination contains {len(res)} Manuscripts.")
previous_queries = ['(' + prev.name.removeprefix("Search results for <").removesuffix(">") + ')' for prev in selected_groups]
new_query = f" {mode.value} ".join(previous_queries)
new_name = f'Search results for <{new_query}>'
name = st.text_input(label="Select a group name", value=new_name)
if st.button("Save Combined Group"):
new_group = Group(GroupType.ManuscriptGroup, name=name, items=res)
state.data_handler.groups.set(new_group)
state.steps.browseGroups = Step.Browse_Groups.Browse
st.experimental_rerun()
def __combine_txt_groups(state: StateHandler) -> None:
"""Page for combining Text groups"""
groups = state.data_handler.groups.text_groups
st.header("Combine Text Groups")
if st.button("Back to Overview"):
state.steps.browseGroups = Step.Browse_Groups.Browse
st.experimental_rerun()
st.write("---")
modes = {
'OR (union - pick items that appear in at least one selected group)': SearchOptions.CONTAINS_ONE,
'AND (intersection - pick items that appear in all selected groups)': SearchOptions.CONTAINS_ALL,
}
mode_selection = st.radio('Combination mode', modes.keys())
mode = modes[mode_selection]
st.write("---")
st.write("Select the groups you want to combine.")
selections: Set[UUID] = set()
for i, g in enumerate(groups.values()):
if st.checkbox(f"{i}: Group name: '{g.name}'", key=str(g.group_id)):
selections.add(g.group_id)
st.write("---")
if len(selections) > 1:
selected_groups = [groups[s] for s in selections]
sets = [g.items for g in selected_groups]
if mode == SearchOptions.CONTAINS_ONE:
res = set.union(*sets)
else:
res = set.intersection(*sets)
if not res:
st.write("No Texts fitting the criteria. (Maybe consider using OR instead of AND for combination logic.)")
else:
st.write(f"The combination contains {len(res)} Texts.")
previous_queries = ['(' + prev.name.removeprefix("Search results for <").removesuffix(">") + ')' for prev in selected_groups]
new_query = f" {mode.value} ".join(previous_queries)
new_name = f'Search results for <{new_query}>'
name = st.text_input(label="Select a group name", value=new_name)
if st.button("Save Combined Group"):
new_group = Group(GroupType.TextGroup, name=name, items=res)
state.data_handler.groups.set(new_group)
state.steps.browseGroups = Step.Browse_Groups.Browse
st.experimental_rerun()
def __combine_ppl_groups(state: StateHandler) -> None:
"""Page for combining Person groups"""
groups = state.data_handler.groups.person_groups
st.header("Combine Person Groups")
if st.button("Back to Overview"):
state.steps.browseGroups = Step.Browse_Groups.Browse
st.experimental_rerun()
st.write("---")
modes = {
'OR (union - pick items that appear in at least one selected group)': SearchOptions.CONTAINS_ONE,
'AND (intersection - pick items that appear in all selected groups)': SearchOptions.CONTAINS_ALL,
}
mode_selection = st.radio('Combination mode', modes.keys())
mode = modes[mode_selection]
st.write("---")
st.write("Select the groups you want to combine.")
selections: Set[UUID] = set()
for i, g in enumerate(groups.values()):
if st.checkbox(f"{i}: Group name: '{g.name}'", key=str(g.group_id)):
selections.add(g.group_id)
st.write("---")
if len(selections) > 1:
selected_groups = [groups[s] for s in selections]
sets = [g.items for g in selected_groups]
if mode == SearchOptions.CONTAINS_ONE:
res = set.union(*sets)
else:
res = set.intersection(*sets)
if not res:
st.write("No person fitting the criteria. (Maybe consider using OR instead of AND for combination logic.)")
else:
st.write(f"The combination contains {len(res)} people.")
previous_queries = ['(' + prev.name.removeprefix("Search results for <").removesuffix(">") + ')' for prev in selected_groups]
new_query = f" {mode.value} ".join(previous_queries)
new_name = f'Search results for <{new_query}>'
name = st.text_input(label="Select a group name", value=new_name)
if st.button("Save Combined Group"):
new_group = Group(GroupType.PersonGroup, name=name, items=res)
state.data_handler.groups.set(new_group)
state.steps.browseGroups = Step.Browse_Groups.Browse
st.experimental_rerun()
| 46.328042
| 137
| 0.644244
|
e1fe991ff28a270649df59b91c5432a74aac3ccd
| 10,718
|
py
|
Python
|
test/python/basicaer/test_qasm_simulator.py
|
ajavadia/qiskit-sdk-py
|
a59e8e6be1793197e19998c1f7dcfc45e6f2f3af
|
[
"Apache-2.0"
] | 11
|
2019-06-27T09:53:29.000Z
|
2021-03-02T04:40:30.000Z
|
test/python/basicaer/test_qasm_simulator.py
|
ajavadia/qiskit-sdk-py
|
a59e8e6be1793197e19998c1f7dcfc45e6f2f3af
|
[
"Apache-2.0"
] | 12
|
2018-09-21T12:02:18.000Z
|
2018-09-25T09:14:59.000Z
|
test/python/basicaer/test_qasm_simulator.py
|
ajavadia/qiskit-sdk-py
|
a59e8e6be1793197e19998c1f7dcfc45e6f2f3af
|
[
"Apache-2.0"
] | 4
|
2019-08-05T15:35:33.000Z
|
2020-09-18T18:55:02.000Z
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test QASM simulator."""
import unittest
import io
from logging import StreamHandler, getLogger
import sys
import numpy as np
from qiskit import execute
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
from qiskit.compiler import transpile, assemble
from qiskit.providers.basicaer import QasmSimulatorPy
from qiskit.test import Path
from qiskit.test import providers
class StreamHandlerRaiseException(StreamHandler):
"""Handler class that will raise an exception on formatting errors."""
def handleError(self, record):
raise sys.exc_info()
class TestBasicAerQasmSimulator(providers.BackendTestCase):
"""Test the Basic qasm_simulator."""
backend_cls = QasmSimulatorPy
def setUp(self):
super().setUp()
self.seed = 88
qasm_filename = self._get_resource_path('example.qasm', Path.QASMS)
transpiled_circuit = QuantumCircuit.from_qasm_file(qasm_filename)
transpiled_circuit.name = 'test'
transpiled_circuit = transpile(transpiled_circuit, backend=self.backend)
self.qobj = assemble(transpiled_circuit, shots=1000, seed_simulator=self.seed)
logger = getLogger()
self.addCleanup(logger.setLevel, logger.level)
logger.setLevel('DEBUG')
self.log_output = io.StringIO()
logger.addHandler(StreamHandlerRaiseException(self.log_output))
def assertExecuteLog(self, log_msg):
""" Runs execute and check for logs containing specified message"""
shots = 100
qr = QuantumRegister(2, 'qr')
cr = ClassicalRegister(4, 'cr')
circuit = QuantumCircuit(qr, cr)
execute(
circuit,
backend=self.backend,
shots=shots,
seed_simulator=self.seed)
self.log_output.seek(0)
# Filter unrelated log lines
output_lines = self.log_output.readlines()
execute_log_lines = [x for x in output_lines if log_msg in x]
self.assertTrue(len(execute_log_lines) > 0)
def test_submission_log_time(self):
"""Check Total Job Submission Time is logged"""
self.assertExecuteLog('Total Job Submission Time')
def test_qasm_simulator_single_shot(self):
"""Test single shot run."""
shots = 1
self.qobj.config.shots = shots
result = self.backend.run(self.qobj).result()
self.assertEqual(result.success, True)
def test_measure_sampler_repeated_qubits(self):
"""Test measure sampler if qubits measured more than once."""
shots = 100
qr = QuantumRegister(2, 'qr')
cr = ClassicalRegister(4, 'cr')
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[1])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[1])
circuit.measure(qr[1], cr[2])
circuit.measure(qr[0], cr[3])
target = {'0110': shots}
job = execute(
circuit,
backend=self.backend,
shots=shots,
seed_simulator=self.seed)
result = job.result()
counts = result.get_counts(0)
self.assertEqual(counts, target)
def test_measure_sampler_single_qubit(self):
"""Test measure sampler if single-qubit is measured."""
shots = 100
num_qubits = 5
qr = QuantumRegister(num_qubits, 'qr')
cr = ClassicalRegister(1, 'cr')
for qubit in range(num_qubits):
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[qubit])
circuit.measure(qr[qubit], cr[0])
target = {'1': shots}
job = execute(
circuit,
backend=self.backend,
shots=shots,
seed_simulator=self.seed)
result = job.result()
counts = result.get_counts(0)
self.assertEqual(counts, target)
def test_measure_sampler_partial_qubit(self):
"""Test measure sampler if single-qubit is measured."""
shots = 100
num_qubits = 5
qr = QuantumRegister(num_qubits, 'qr')
cr = ClassicalRegister(4, 'cr')
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[3])
circuit.x(qr[1])
circuit.barrier(qr)
circuit.measure(qr[3], cr[1])
circuit.barrier(qr)
circuit.measure(qr[1], cr[0])
circuit.barrier(qr)
circuit.measure(qr[0], cr[2])
circuit.barrier(qr)
circuit.measure(qr[3], cr[3])
target = {'1011': shots}
job = execute(
circuit,
backend=self.backend,
shots=shots,
seed_simulator=self.seed)
result = job.result()
counts = result.get_counts(0)
self.assertEqual(counts, target)
def test_qasm_simulator(self):
"""Test data counts output for single circuit run against reference."""
result = self.backend.run(self.qobj).result()
shots = 1024
threshold = 0.04 * shots
counts = result.get_counts('test')
target = {'100 100': shots / 8, '011 011': shots / 8,
'101 101': shots / 8, '111 111': shots / 8,
'000 000': shots / 8, '010 010': shots / 8,
'110 110': shots / 8, '001 001': shots / 8}
self.assertDictAlmostEqual(counts, target, threshold)
def test_if_statement(self):
"""Test if statements."""
shots = 100
qr = QuantumRegister(3, 'qr')
cr = ClassicalRegister(3, 'cr')
circuit_if_true = QuantumCircuit(qr, cr)
circuit_if_true.x(qr[0])
circuit_if_true.x(qr[1])
circuit_if_true.measure(qr[0], cr[0])
circuit_if_true.measure(qr[1], cr[1])
circuit_if_true.x(qr[2]).c_if(cr, 0x3)
circuit_if_true.measure(qr[0], cr[0])
circuit_if_true.measure(qr[1], cr[1])
circuit_if_true.measure(qr[2], cr[2])
circuit_if_false = QuantumCircuit(qr, cr)
circuit_if_false.x(qr[0])
circuit_if_false.measure(qr[0], cr[0])
circuit_if_false.measure(qr[1], cr[1])
circuit_if_false.x(qr[2]).c_if(cr, 0x3)
circuit_if_false.measure(qr[0], cr[0])
circuit_if_false.measure(qr[1], cr[1])
circuit_if_false.measure(qr[2], cr[2])
job = execute([circuit_if_true, circuit_if_false],
backend=self.backend, shots=shots, seed_simulator=self.seed)
result = job.result()
counts_if_true = result.get_counts(circuit_if_true)
counts_if_false = result.get_counts(circuit_if_false)
self.assertEqual(counts_if_true, {'111': 100})
self.assertEqual(counts_if_false, {'001': 100})
def test_teleport(self):
"""Test teleportation as in tutorials"""
self.log.info('test_teleport')
pi = np.pi
shots = 2000
qr = QuantumRegister(3, 'qr')
cr0 = ClassicalRegister(1, 'cr0')
cr1 = ClassicalRegister(1, 'cr1')
cr2 = ClassicalRegister(1, 'cr2')
circuit = QuantumCircuit(qr, cr0, cr1, cr2, name='teleport')
circuit.h(qr[1])
circuit.cx(qr[1], qr[2])
circuit.ry(pi / 4, qr[0])
circuit.cx(qr[0], qr[1])
circuit.h(qr[0])
circuit.barrier(qr)
circuit.measure(qr[0], cr0[0])
circuit.measure(qr[1], cr1[0])
circuit.z(qr[2]).c_if(cr0, 1)
circuit.x(qr[2]).c_if(cr1, 1)
circuit.measure(qr[2], cr2[0])
job = execute(circuit, backend=self.backend, shots=shots, seed_simulator=self.seed)
results = job.result()
data = results.get_counts('teleport')
alice = {
'00': data['0 0 0'] + data['1 0 0'],
'01': data['0 1 0'] + data['1 1 0'],
'10': data['0 0 1'] + data['1 0 1'],
'11': data['0 1 1'] + data['1 1 1']
}
bob = {
'0': data['0 0 0'] + data['0 1 0'] + data['0 0 1'] + data['0 1 1'],
'1': data['1 0 0'] + data['1 1 0'] + data['1 0 1'] + data['1 1 1']
}
self.log.info('test_teleport: circuit:')
self.log.info(circuit.qasm())
self.log.info('test_teleport: data %s', data)
self.log.info('test_teleport: alice %s', alice)
self.log.info('test_teleport: bob %s', bob)
alice_ratio = 1 / np.tan(pi / 8) ** 2
bob_ratio = bob['0'] / float(bob['1'])
error = abs(alice_ratio - bob_ratio) / alice_ratio
self.log.info('test_teleport: relative error = %s', error)
self.assertLess(error, 0.05)
def test_memory(self):
"""Test memory."""
qr = QuantumRegister(4, 'qr')
cr0 = ClassicalRegister(2, 'cr0')
cr1 = ClassicalRegister(2, 'cr1')
circ = QuantumCircuit(qr, cr0, cr1)
circ.h(qr[0])
circ.cx(qr[0], qr[1])
circ.x(qr[3])
circ.measure(qr[0], cr0[0])
circ.measure(qr[1], cr0[1])
circ.measure(qr[2], cr1[0])
circ.measure(qr[3], cr1[1])
shots = 50
job = execute(circ, backend=self.backend, shots=shots, memory=True)
result = job.result()
memory = result.get_memory()
self.assertEqual(len(memory), shots)
for mem in memory:
self.assertIn(mem, ['10 00', '10 11'])
def test_unitary(self):
"""Test unitary gate instruction"""
max_qubits = 4
x_mat = np.array([[0, 1], [1, 0]])
# Test 1 to max_qubits for random n-qubit unitary gate
for i in range(max_qubits):
num_qubits = i + 1
# Apply X gate to all qubits
multi_x = x_mat
for _ in range(i):
multi_x = np.kron(multi_x, x_mat)
# Target counts
shots = 100
target_counts = {num_qubits * '1': shots}
# Test circuit
qr = QuantumRegister(num_qubits, 'qr')
cr = ClassicalRegister(num_qubits, 'cr')
circuit = QuantumCircuit(qr, cr)
circuit.unitary(multi_x, qr)
circuit.measure(qr, cr)
job = execute(circuit, self.backend, shots=shots)
result = job.result()
counts = result.get_counts(0)
self.assertEqual(counts, target_counts)
if __name__ == '__main__':
unittest.main()
| 36.332203
| 91
| 0.590129
|
27541d5dd28ce2eceb129aa064776106744db92d
| 1,428
|
py
|
Python
|
Pygame/Game/study/game1.py
|
danghohuuphuc/Code_Python
|
4aee488bc0c4a7bf2c110bbfad3c8fd48b31a070
|
[
"Apache-2.0"
] | null | null | null |
Pygame/Game/study/game1.py
|
danghohuuphuc/Code_Python
|
4aee488bc0c4a7bf2c110bbfad3c8fd48b31a070
|
[
"Apache-2.0"
] | null | null | null |
Pygame/Game/study/game1.py
|
danghohuuphuc/Code_Python
|
4aee488bc0c4a7bf2c110bbfad3c8fd48b31a070
|
[
"Apache-2.0"
] | null | null | null |
# import library
from dis import dis
import re
import pygame, sys
from pygame.locals import *
# Khởi tạo
pygame.init()
# Khởi tạo khung hình game
DISPLAYSURF = pygame.display.set_mode((500, 400), 0, 32)
# Thay đổi caption
pygame.display.set_caption("game 1")
# Thay đổi icon khung game
icongame1 = pygame.image.load("pikachu.png")
pygame.display.set_icon(icongame1)
# cài đặt màu săc
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
# draw on the surface object
DISPLAYSURF.fill(white)
# Vẽ hình năm cạnh
pygame.draw.polygon(DISPLAYSURF, green, ((146, 0), (291, 106),
(236, 277), (56, 277), (0, 106)))
# Vẽ đường thẳng
pygame.draw.line(DISPLAYSURF, blue, (60, 60), (120,60) ,10)
pygame.draw.line(DISPLAYSURF, blue, (120, 60), (60, 120), 10)
pygame.draw.line(DISPLAYSURF, blue, (60, 120), (120, 120), 10)
# Vẽ hình tròn
pygame.draw.circle(DISPLAYSURF, blue, (300, 50), 20, 0)
# Vẽ hình elcip
pygame.draw.ellipse(DISPLAYSURF, red, (300, 250, 40, 80), 5)
# Vẽ Hình chữ nhật
pygame.draw.rect(DISPLAYSURF, red, (200, 150, 100, 50))
pixObj = pygame.PixelArray(DISPLAYSURF)
pixObj[480][380] = black
pixObj[482][382] = black
pixObj[484][384] = black
pixObj[486][386] = black
pixObj[488][388] = black
del pixObj
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# update data
pygame.display.update()
| 23.032258
| 63
| 0.671569
|
2d798582c9aae66597138a9e7145af104df235eb
| 8,410
|
py
|
Python
|
asynchronous_qiwi/call/P2P.py
|
LexLuthorReal/asynchronous_qiwi
|
5847a8d4008493656e973e5283888a4e57234962
|
[
"MIT"
] | 3
|
2021-05-20T02:36:30.000Z
|
2021-11-28T16:00:15.000Z
|
asynchronous_qiwi/call/P2P.py
|
LexLuthorReal/asynchronous_qiwi
|
5847a8d4008493656e973e5283888a4e57234962
|
[
"MIT"
] | null | null | null |
asynchronous_qiwi/call/P2P.py
|
LexLuthorReal/asynchronous_qiwi
|
5847a8d4008493656e973e5283888a4e57234962
|
[
"MIT"
] | 1
|
2021-11-28T16:00:20.000Z
|
2021-11-28T16:00:20.000Z
|
from typing import Optional, Dict, Set, List, Any
from ..data_types.QIWIP2P import (
PaySourcesTypes
)
from .API.QIWIP2P import (
CreateInvoiceAPI, CheckInvoiceAPI, RejectInvoiceAPI, RefundInvoiceAPI, RefundStatusAPI
)
from .ADDONS.QIWIP2P import (
PublicFormGenerator
)
from ..models.QIWIP2P import (
Invoice, RefundData
)
class P2P:
def __init__(self, public_key: str, secret_key: str) -> None:
"""
:param public_key: The public key (PUBLIC_KEY) is used for invoicing through the form.
:param secret_key: Your requests are authorized with the API secret key (SECRET_KEY).
"""
self.public_key = public_key
self.secret_key = secret_key
async def generate_form(self, bill_id: Optional[str] = None, amount: Optional[float] = None,
phone_customer: Optional[str] = None, email_customer: Optional[str] = None,
account_customer: Optional[str] = None, comment: Optional[str] = None,
custom_fields: Optional[Dict[str, Any]] = None, theme_code: Optional[str] = None,
pay_sources_filter: Optional[List[Set[PaySourcesTypes]]] = None,
lifetime: Optional[int] = None, success_url: Optional[str] = None) -> str:
"""
Upon opening the form, the customer is automatically billed.
Account parameters are passed in clear text in the link.
:param bill_id: unique id.
:param amount: billed amount, round down to 2 decimal places
:param phone_customer: customer phone number (in international format).
:param email_customer: customer email.
:param account_customer: customer ID on your system.
:param comment: invoice comment.
:param custom_fields: if use custom_fields (pay_sources_filter, theme_code) will be ignored.
:param theme_code: customize your form personalization in (p2p.qiwi.com).
:param pay_sources_filter: when you open the form, only the specified translation methods will be displayed.
:param lifetime: the period until which the invoice will be available for payment (days).
:param success_url: URL to redirect to your site in case of successful translation.
:return: generated url for send to customer.
"""
url = await PublicFormGenerator.generate_form(public_key=self.public_key,
bill_id=bill_id,
amount=amount,
phone_customer=phone_customer,
email_customer=email_customer,
account_customer=account_customer,
comment=comment,
custom_fields=custom_fields,
theme_code=theme_code,
pay_sources_filter=pay_sources_filter,
lifetime=lifetime,
success_url=success_url)
return url
async def new_invoice(self, bill_id: str, amount: float, invoice_currency: str, lifetime: int = 1,
comment: Optional[str] = None, phone_customer: Optional[str] = None,
email_customer: Optional[str] = None, account_customer: Optional[str] = None,
custom_fields: Optional[Dict[str, Any]] = None, theme_code: Optional[str] = None,
pay_sources_filter: Optional[List[Set[PaySourcesTypes]]] = None) -> Invoice:
"""
:param bill_id: unique id.
:param amount: data on the amount of the bill.
:param invoice_currency: the currency of the invoice amount (RUB, KZT...).
:param lifetime: the period until which the invoice will be available for payment (days).
:param comment: invoice comment.
:param phone_customer: customer phone number (in international format).
:param email_customer: customer email.
:param account_customer: customer ID on your system.
:param custom_fields: if use custom_fields (pay_sources_filter, theme_code) will be ignored.
:param theme_code: customize your form personalization in (p2p.qiwi.com).
:param pay_sources_filter: when you open the form, only the specified translation methods will be displayed.
:return: Invoice model with details new invoice.
"""
response_data = await CreateInvoiceAPI.new_invoice(secret_key=self.secret_key,
bill_id=bill_id,
amount=amount,
invoice_currency=invoice_currency,
lifetime=lifetime,
comment=comment,
phone_customer=phone_customer,
email_customer=email_customer,
account_customer=account_customer,
theme_code=theme_code,
pay_sources_filter=pay_sources_filter,
custom_fields=custom_fields)
return Invoice(**response_data)
async def check_invoice(self, bill_id: str) -> Invoice:
"""
The method allows you to check the status of the transfer on the account.
:param bill_id: unique invoice identifier, specified when issuing.
:return: Invoice model with details invoice.
"""
response_data = await CheckInvoiceAPI.check_invoice(secret_key=self.secret_key,
bill_id=bill_id)
return Invoice(**response_data)
async def reject_invoice(self, bill_id: str) -> Invoice:
"""
The method allows you to cancel an account that has not been transferred.
:param bill_id: unique invoice identifier, specified when issuing.
:return: Invoice model with details invoice.
"""
response_data = await RejectInvoiceAPI.reject_invoice(secret_key=self.secret_key,
bill_id=bill_id)
return Invoice(**response_data)
async def refund_invoice(self, bill_id: str, refund_id: str, amount: float, return_currency: str) -> RefundData:
"""
The method allows you to return funds.
:param bill_id: unique invoice identifier, specified when issuing.
:param refund_id: unique identifier of the refund in the merchant's system.
:param amount: refund amount.
:param return_currency: return currency (RUB, KZT...).
:return: RefundData model with details.
"""
response_data = await RefundInvoiceAPI.refund_invoice(secret_key=self.secret_key,
bill_id=bill_id,
refund_id=refund_id,
amount=amount,
return_currency=return_currency)
return RefundData(**response_data)
async def refund_status(self, bill_id: str, refund_id: str) -> RefundData:
"""
The method allows you to check return status.
:param bill_id: unique invoice identifier, specified when issuing.
:param refund_id: unique identifier of the refund in the merchant's system.
:return: RefundData model with details.
"""
response_data = await RefundStatusAPI.refund_status(secret_key=self.secret_key,
bill_id=bill_id,
refund_id=refund_id)
return RefundData(**response_data)
| 58.811189
| 116
| 0.551605
|
a3a1617b650def583bebf056cb29979e0b210eb5
| 3,103
|
py
|
Python
|
sdk/applicationinsights/azure-mgmt-applicationinsights/azure/mgmt/applicationinsights/aio/_configuration.py
|
rsdoherty/azure-sdk-for-python
|
6bba5326677468e6660845a703686327178bb7b1
|
[
"MIT"
] | 3
|
2020-06-23T02:25:27.000Z
|
2021-09-07T18:48:11.000Z
|
sdk/applicationinsights/azure-mgmt-applicationinsights/azure/mgmt/applicationinsights/aio/_configuration.py
|
rsdoherty/azure-sdk-for-python
|
6bba5326677468e6660845a703686327178bb7b1
|
[
"MIT"
] | 510
|
2019-07-17T16:11:19.000Z
|
2021-08-02T08:38:32.000Z
|
sdk/applicationinsights/azure-mgmt-applicationinsights/azure/mgmt/applicationinsights/aio/_configuration.py
|
rsdoherty/azure-sdk-for-python
|
6bba5326677468e6660845a703686327178bb7b1
|
[
"MIT"
] | 5
|
2019-09-04T12:51:37.000Z
|
2020-09-16T07:28:40.000Z
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from typing import Any
from azure.core.configuration import Configuration
from azure.core.pipeline import policies
from azure.mgmt.core.policies import ARMHttpLoggingPolicy
from .._version import VERSION
class ApplicationInsightsManagementClientConfiguration(Configuration):
"""Configuration for ApplicationInsightsManagementClient.
Note that all parameters used to create this instance are saved as instance
attributes.
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param subscription_id: The ID of the target subscription.
:type subscription_id: str
"""
def __init__(
self,
credential, # type: "AsyncTokenCredential"
subscription_id, # type: str
**kwargs # type: Any
) -> None:
if credential is None:
raise ValueError("Parameter 'credential' must not be None.")
if subscription_id is None:
raise ValueError("Parameter 'subscription_id' must not be None.")
super(ApplicationInsightsManagementClientConfiguration, self).__init__(**kwargs)
self.credential = credential
self.subscription_id = subscription_id
self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default'])
kwargs.setdefault('sdk_moniker', 'azure-mgmt-applicationinsights/{}'.format(VERSION))
self._configure(**kwargs)
def _configure(
self,
**kwargs: Any
) -> None:
self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs)
self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs)
self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs)
self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs)
self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs)
self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs)
self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs)
self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs)
self.authentication_policy = kwargs.get('authentication_policy')
if self.credential and not self.authentication_policy:
self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs)
| 47.738462
| 134
| 0.696423
|
676aaea8d94d16202d51ba9ee969f20cb22dc552
| 5,846
|
py
|
Python
|
quantumclient/tests/unit/test_cli20_port.py
|
danwent/python-quantumclient
|
d16e00a056bbe7ba576c4b7195180bfc383bbfad
|
[
"Apache-2.0"
] | 1
|
2017-06-02T22:33:11.000Z
|
2017-06-02T22:33:11.000Z
|
quantumclient/tests/unit/test_cli20_port.py
|
danwent/python-quantumclient
|
d16e00a056bbe7ba576c4b7195180bfc383bbfad
|
[
"Apache-2.0"
] | null | null | null |
quantumclient/tests/unit/test_cli20_port.py
|
danwent/python-quantumclient
|
d16e00a056bbe7ba576c4b7195180bfc383bbfad
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2012 OpenStack LLC.
# All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
# vim: tabstop=4 shiftwidth=4 softtabstop=4
import sys
from quantumclient.tests.unit.test_cli20 import CLITestV20Base
from quantumclient.tests.unit.test_cli20 import MyApp
from quantumclient.quantum.v2_0.port import CreatePort
from quantumclient.quantum.v2_0.port import ListPort
from quantumclient.quantum.v2_0.port import UpdatePort
from quantumclient.quantum.v2_0.port import ShowPort
from quantumclient.quantum.v2_0.port import DeletePort
class CLITestV20Port(CLITestV20Base):
def test_create_port(self):
"""Create port: netid."""
resource = 'port'
cmd = CreatePort(MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
args = [netid]
position_names = ['network_id']
position_values = []
position_values.extend([netid])
_str = self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_port_full(self):
"""Create port: --mac_address mac --device_id deviceid netid."""
resource = 'port'
cmd = CreatePort(MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
args = ['--mac_address', 'mac', '--device_id', 'deviceid', netid]
position_names = ['network_id', 'mac_address', 'device_id']
position_values = [netid, 'mac', 'deviceid']
_str = self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_port_tenant(self):
"""Create port: --tenant_id tenantid netid."""
resource = 'port'
cmd = CreatePort(MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
args = ['--tenant_id', 'tenantid', netid, ]
position_names = ['network_id']
position_values = []
position_values.extend([netid])
_str = self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
tenant_id='tenantid')
def test_create_port_tags(self):
"""Create port: netid mac_address device_id --tags a b."""
resource = 'port'
cmd = CreatePort(MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
args = [netid, '--tags', 'a', 'b']
position_names = ['network_id']
position_values = []
position_values.extend([netid])
_str = self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
tags=['a', 'b'])
def test_list_ports(self):
"""List ports: -D."""
resources = "ports"
cmd = ListPort(MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, True)
def test_list_ports_tags(self):
"""List ports: -- --tags a b."""
resources = "ports"
cmd = ListPort(MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, tags=['a', 'b'])
def test_list_ports_detail_tags(self):
"""List ports: -D -- --tags a b."""
resources = "ports"
cmd = ListPort(MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, detail=True, tags=['a', 'b'])
def test_list_ports_fields(self):
"""List ports: --fields a --fields b -- --fields c d."""
resources = "ports"
cmd = ListPort(MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd,
fields_1=['a', 'b'], fields_2=['c', 'd'])
def test_update_port(self):
"""Update port: myid --name myname --tags a b."""
resource = 'port'
cmd = UpdatePort(MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--name', 'myname',
'--tags', 'a', 'b'],
{'name': 'myname', 'tags': ['a', 'b'], }
)
def test_show_port(self):
"""Show port: --fields id --fields name myid."""
resource = 'port'
cmd = ShowPort(MyApp(sys.stdout), None)
args = ['--fields', 'id', '--fields', 'name', self.test_id]
self._test_show_resource(resource, cmd, self.test_id,
args, ['id', 'name'])
def test_show_port_by_name(self):
"""Show port: --fields id --fields name myname."""
resource = 'port'
cmd = ShowPort(MyApp(sys.stdout), None)
myname = 'myname'
args = ['--fields', 'id', '--fields', 'name', myname]
self._test_show_resource_by_name(resource, cmd, myname,
args, ['id', 'name'])
def test_delete_port(self):
"""Delete port: myid."""
resource = 'port'
cmd = DeletePort(MyApp(sys.stdout), None)
myid = 'myid'
args = [myid]
self._test_delete_resource(resource, cmd, myid, args)
| 39.768707
| 79
| 0.572186
|
76d4396ad21efd874f4f073fc56ae2c0bf961b3e
| 29,252
|
py
|
Python
|
core/plugins/openstack/__init__.py
|
aserdean/hotsos
|
a0f17a7ee2f08a4da0a269d478dec7ebb8f12493
|
[
"Apache-2.0"
] | null | null | null |
core/plugins/openstack/__init__.py
|
aserdean/hotsos
|
a0f17a7ee2f08a4da0a269d478dec7ebb8f12493
|
[
"Apache-2.0"
] | null | null | null |
core/plugins/openstack/__init__.py
|
aserdean/hotsos
|
a0f17a7ee2f08a4da0a269d478dec7ebb8f12493
|
[
"Apache-2.0"
] | null | null | null |
import os
import re
from core.issues import (
issue_types,
issue_utils,
)
from core import (
checks,
constants,
host_helpers,
plugintools,
)
from core.ycheck.events import YEventCheckerBase
from core.checks import DPKGVersionCompare
from core.log import log
from core.cli_helpers import CmdBase, CLIHelper
from core.plugins.openstack.exceptions import (
EXCEPTIONS_COMMON,
BARBICAN_EXCEPTIONS,
CASTELLAN_EXCEPTIONS,
CINDER_EXCEPTIONS,
KEYSTONE_EXCEPTIONS,
MANILA_EXCEPTIONS,
PLACEMENT_EXCEPTIONS,
PYTHON_LIBVIRT_EXCEPTIONS,
NOVA_EXCEPTIONS,
NEUTRON_EXCEPTIONS,
OCTAVIA_EXCEPTIONS,
OVSDBAPP_EXCEPTIONS,
)
from core.plugins.kernel import (
KernelConfig,
SystemdConfig,
)
from core.plugins.system import (
NUMAInfo,
SystemBase,
)
APT_SOURCE_PATH = os.path.join(constants.DATA_ROOT, 'etc/apt/sources.list.d')
NEUTRON_HA_PATH = 'var/lib/neutron/ha_confs'
# Plugin config opts from global
AGENT_ERROR_KEY_BY_TIME = \
constants.bool_str(os.environ.get('AGENT_ERROR_KEY_BY_TIME',
'False'))
OST_REL_INFO = {
'barbican-common': {
'yoga': '1:14.0.0',
'xena': '1:13.0.0',
'wallaby': '1:12.0.0',
'victoria': '1:11.0.0',
'ussuri': '1:10.0.0',
'train': '1:9.0.0',
'stein': '1:8.0.0',
'rocky': '1:7.0.0',
'queens': '1:6.0.0'},
'cinder-common': {
'yoga': '2:20.0.0',
'xena': '2:19.0.0',
'wallaby': '2:18.0.0',
'victoria': '2:17.0.0',
'ussuri': '2:16.0.0',
'train': '2:15.0.0',
'stein': '2:14.0.0',
'rocky': '2:13.0.0',
'queens': '2:12.0.0'},
'designate-common': {
'yoga': '1:14.0.0',
'xena': '1:13.0.0',
'wallaby': '1:12.0.0',
'victoria': '1:11.0.0',
'ussuri': '1:10.0.0',
'train': '1:9.0.0',
'stein': '1:8.0.0',
'rocky': '1:7.0.0',
'queens': '1:6.0.0'},
'glance-common': {
'yoga': '2:24.0.0',
'xena': '2:23.0.0',
'wallaby': '2:22.0.0',
'victoria': '2:21.0.0',
'ussuri': '2:20.0.0',
'train': '2:19.0.0',
'stein': '2:18.0.0',
'rocky': '2:17.0.0',
'queens': '2:16.0.0'},
'heat-common': {
'yoga': '1:18.0.0',
'xena': '1:17.0.0',
'wallaby': '1:16.0.0',
'victoria': '1:15.0.0',
'ussuri': '1:14.0.0',
'train': '1:13.0.0',
'stein': '1:12.0.0',
'rocky': '1:11.0.0',
'queens': '1:10.0.0'},
'keystone': {
'yoga': '2:21.0.0',
'xena': '2:20.0.0',
'wallaby': '2:19.0.0',
'victoria': '2:18.0.0',
'ussuri': '2:17.0.0',
'train': '2:16.0.0',
'stein': '2:15.0.0',
'rocky': '2:14.0.0',
'queens': '2:13.0.0',
'pike': '2:12.0.0',
'ocata': '2:11.0.0'},
'nova-common': {
'yoga': '3:25.0.0',
'xena': '3:24.0.0',
'wallaby': '3:23.0.0',
'victoria': '2:22.0.0',
'ussuri': '2:21.0.0',
'train': '2:20.0.0',
'stein': '2:19.0.0',
'rocky': '2:18.0.0',
'queens': '2:17.0.0',
'pike': '2:16.0.0',
'ocata': '2:15.0.0',
'newton': '2:14.0.0',
'mitaka': '2:13.0.0',
'liberty': '2:12.0.0',
'kilo': '1:2015.1.0',
'juno': '1:2014.2.0',
'icehouse': '1:2014.1.0'},
'neutron-common': {
'yoga': '2:20.0.0',
'xena': '2:19.0.0',
'wallaby': '2:18.0.0',
'victoria': '2:17.0.0',
'ussuri': '2:16.0.0',
'train': '2:15.0.0',
'stein': '2:14.0.0',
'rocky': '2:13.0.0',
'queens': '2:12.0.0',
'pike': '2:11.0.0',
'ocata': '2:10.0.0',
'newton': '2:9.0.0',
'mitaka': '2:8.0.0',
'liberty': '2:7.0.0',
'kilo': '1:2015.1.0',
'juno': '1:2014.2.0',
'icehouse': '1:2014.1.0'},
'octavia-common': {
'yoga': '10.0.0',
'xena': '9.0.0',
'wallaby': '8.0.0',
'victoria': '7.0.0',
'ussuri': '6.0.0',
'train': '5.0.0',
'stein': '4.0.0',
'rocky': '3.0.0'}
}
OST_EXCEPTIONS = {'barbican': BARBICAN_EXCEPTIONS + CASTELLAN_EXCEPTIONS,
'cinder': CINDER_EXCEPTIONS + CASTELLAN_EXCEPTIONS,
'keystone': KEYSTONE_EXCEPTIONS,
'manila': MANILA_EXCEPTIONS,
'neutron': NEUTRON_EXCEPTIONS + OVSDBAPP_EXCEPTIONS,
'nova': NOVA_EXCEPTIONS + PYTHON_LIBVIRT_EXCEPTIONS,
'octavia': OCTAVIA_EXCEPTIONS,
'placement': PLACEMENT_EXCEPTIONS,
}
class OpenstackConfig(checks.SectionalConfigBase):
pass
class OSTProject(object):
SVC_VALID_SUFFIX = r'[0-9a-zA-Z-_]*'
PY_CLIENT_PREFIX = r"python3?-{}\S*"
def __init__(self, name, config=None, daemon_names=None,
apt_core_alt=None, systemd_masked_services=None,
log_path_overrides=None):
"""
@param name: name of this project
@param config: dict of config files keyed by a label used to identify
them. All projects should have a config file labelled
'main'.
@param daemon_names: list of daemon names of processes run by this
project.
@param apt_core_alt: optional list of apt packages (regex) that are
used by this project where the name of the project
is not the same as the name used for its packages.
@param systemd_masked_services: optional list of services that are
expected to be masked in systemd e.g. if they are actually being
run by apache.
"""
self.name = name
self.packages_core = [name]
if apt_core_alt:
self.packages_core.append(apt_core_alt)
client = self.PY_CLIENT_PREFIX.format(apt_core_alt)
else:
client = self.PY_CLIENT_PREFIX.format(name)
self.config = {}
if config:
for label, path in config.items():
path = os.path.join(constants.DATA_ROOT, 'etc', name, path)
self.config[label] = OpenstackConfig(path)
self.systemd_masked_services = systemd_masked_services or []
self.packages_core.append(client)
self.service_expr = '{}{}'.format(name, self.SVC_VALID_SUFFIX)
self.daemon_names = daemon_names or []
self.logs_path = os.path.join('var/log', name)
self.log_path_overrides = log_path_overrides or {}
self.exceptions = EXCEPTIONS_COMMON + OST_EXCEPTIONS.get(name, [])
@property
def log_paths(self):
"""
Returns tuples of daemon name, log path for each agent/daemon.
"""
proj_manage = "{}-manage".format(self.name)
yield proj_manage, os.path.join('var/log', self.name,
"{}.log".format(proj_manage))
for daemon in self.daemon_names:
path = os.path.join('var/log', self.name,
"{}.log".format(daemon))
yield daemon, self.log_path_overrides.get(daemon, path)
class OSTProjectCatalog(object):
# Services that are not actually openstack projects but are used by them
OST_SERVICES_DEPS = [r'apache2',
'dnsmasq',
'ganesha.nfsd',
'haproxy',
r"keepalived{}".format(OSTProject.SVC_VALID_SUFFIX),
'mysqld',
r"vault{}".format(OSTProject.SVC_VALID_SUFFIX),
r'qemu-system-\S+',
'radvd',
]
# Set of packages that any project can depend on
APT_DEPS_COMMON = ['conntrack',
'dnsmasq',
'haproxy',
'keepalived',
'libvirt-daemon',
'libvirt-bin',
r'mysql-?\S+',
'pacemaker',
'corosync',
'nfs--ganesha',
r'python3?-oslo[.-]',
'qemu-kvm',
'radvd',
]
def __init__(self):
self._projects = {}
self.add('aodh', config={'main': 'aodh.conf'},
systemd_masked_services=['aodh-api']),
self.add('barbican',
daemon_names=['barbican-api', 'barbican-worker'],
config={'main': 'barbican.conf'},
systemd_masked_services=['barbican-api']),
self.add('ceilometer', config={'main': 'ceilometer.conf'},
systemd_masked_services=['ceilometer-api']),
self.add('cinder',
daemon_names=['cinder-scheduler', 'cinder-volume'],
config={'main': 'cinder.conf'}),
self.add('designate',
daemon_names=['designate-agent', 'designate-api',
'designate-central', 'designate-mdns',
'designate-producer', 'designate-sink',
'designate-worker'],
config={'main': 'designate.conf'}),
self.add('glance', daemon_names=['glance-api'],
config={'main': 'glance-api.conf'}),
self.add('gnocchi', config={'main': 'gnocchi.conf'},
systemd_masked_services=['gnocchi-api']),
self.add('heat',
daemon_names=['heat-engine', 'heat-api', 'heat-api-cfn'],
config={'main': 'heat.conf'}),
self.add('horizon',
apt_core_alt='openstack-dashboard'),
self.add('keystone', daemon_names=['keystone'],
config={'main': 'keystone.conf'},
systemd_masked_services=['keystone']),
self.add('neutron',
daemon_names=['neutron-openvswitch-agent',
'neutron-dhcp-agent', 'neutron-l3-agent',
'neutron-server', 'neutron-sriov-agent'],
config={'main': 'neutron.conf',
'openvswitch-agent':
'plugins/ml2/openvswitch_agent.ini',
'l3-agent': 'l3_agent.ini',
'dhcp-agent': 'dhcp_agent.ini'},
systemd_masked_services=['nova-api-metadata']),
self.add('nova',
daemon_names=['nova-compute', 'nova-scheduler',
'nova-conductor', 'nova-api-os-compute',
'nova-api-wsgi', 'nova-api-metadata',
'nova-placement'],
config={'main': 'nova.conf'},
# See LP bug 1957760 for reason why neutron-server is added.
systemd_masked_services=['nova-api-os-compute',
'neutron-server'],
log_path_overrides={'nova-api-os-compute':
'var/log/apache2/nova-*.log'}),
self.add('manila',
daemon_names=['manila-api', 'manila-scheduler',
'manila-data', 'manila-share'],
config={'main': 'manila.conf'},
systemd_masked_services=['manila-api']),
self.add('masakari', config={'main': 'masakari.conf'},
systemd_masked_services=['masakari']),
self.add('octavia',
daemon_names=['octavia-api', 'octavia-worker',
'octavia-health-manager',
'octavia-housekeeping',
'octavia-driver-agent'],
config={'main': 'octavia.conf'},
systemd_masked_services=['octavia-api']),
self.add('placement', config={'main': 'placement.conf'},
systemd_masked_services=['placement'],
log_path_overrides={'placement':
'var/log/apache2/*error.log'}),
self.add('swift', config={'main': 'swift-proxy.conf',
'proxy': 'swift-proxy.conf'}),
def __getitem__(self, name):
return self._projects[name]
def __getattr__(self, name):
return self._projects[name]
@property
def all(self):
return self._projects
@property
def service_exprs(self):
# Expressions used to match openstack systemd services for each project
return [p.service_expr for p in self.all.values()] + \
self.OST_SERVICES_DEPS
@property
def default_masked_services(self):
"""
Returns a list of services that are expected to be marked as masked in
systemd.
"""
masked = []
for p in self.all.values():
masked += p.systemd_masked_services
return masked
def add(self, name, *args, **kwargs):
self._projects[name] = OSTProject(name, *args, **kwargs)
@property
def packages_core(self):
# Set of packages we consider to be core for openstack
core = []
for p in self.all.values():
core += p.packages_core
return core
@property
def package_dependencies(self):
return self.APT_DEPS_COMMON
class NovaInstance(object):
def __init__(self, uuid, name):
self.uuid = uuid
self.name = name
self.ports = []
self.memory_mbytes = None
def add_port(self, port):
self.ports.append(port)
class NeutronRouter(object):
def __init__(self, uuid, ha_state):
self.uuid = uuid
self.ha_state = ha_state
self.vr_id = None
class NeutronHAInfo(object):
def __init__(self):
self._routers = []
self._get_neutron_ha_info()
self.vr_id = None
def _get_neutron_ha_info(self):
if not os.path.exists(self.state_path):
return
for entry in os.listdir(self.state_path):
entry = os.path.join(self.state_path, entry)
if not os.path.isdir(entry):
# if its not a directory then it is probably not a live router
# so we ignore it.
continue
state_path = os.path.join(entry, 'state')
if not os.path.exists(state_path):
continue
with open(state_path) as fd:
uuid = os.path.basename(entry)
state = fd.read().strip()
router = NeutronRouter(uuid, state)
keepalived_conf_path = os.path.join(entry, 'keepalived.conf')
if os.path.isfile(keepalived_conf_path):
with open(keepalived_conf_path) as fd:
for line in fd:
expr = r'.+ virtual_router_id (\d+)'
ret = re.compile(expr).search(line)
if ret:
router.vr_id = ret.group(1)
self._routers.append(router)
def find_router_with_vr_id(self, id):
for r in self.ha_routers:
if r.vr_id == id:
return r
@property
def state_path(self):
return os.path.join(constants.DATA_ROOT, NEUTRON_HA_PATH)
@property
def ha_routers(self):
return self._routers
class OSTServiceBase(object):
def __init__(self, name, *args, **kwargs):
super().__init__(*args, **kwargs)
self.nethelp = host_helpers.HostNetworkingHelper()
self.project = OSTProjectCatalog()[name]
@property
def installed(self):
""" Return True if the openstack service is installed. """
core_pkgs = self.project.packages_core
return bool(checks.APTPackageChecksBase(core_pkgs=core_pkgs).core)
class OctaviaBase(OSTServiceBase):
OCTAVIA_HM_PORT_NAME = 'o-hm0'
def __init__(self, *args, **kwargs):
super().__init__('octavia', *args, **kwargs)
@property
def bind_interfaces(self):
"""
Fetch interface o-hm0 used by Openstack Octavia. Returned dict is
keyed by config key used to identify interface.
"""
interfaces = {}
port = self.nethelp.get_interface_with_name(self.OCTAVIA_HM_PORT_NAME)
if port:
interfaces.update({self.OCTAVIA_HM_PORT_NAME: port})
return interfaces
@property
def hm_port_has_address(self):
port = self.bind_interfaces.get(self.OCTAVIA_HM_PORT_NAME)
if port is None or not port.addresses:
return False
return True
@property
def hm_port_healthy(self):
port = self.bind_interfaces.get(self.OCTAVIA_HM_PORT_NAME)
if port is None:
return True
for counters in port.stats.values():
total = sum(counters.values())
if not total:
continue
pcent = int(100 / float(total) * float(counters.get('dropped', 0)))
if pcent > 1:
return False
pcent = int(100 / float(total) * float(counters.get('errors', 0)))
if pcent > 1:
return False
return True
class NovaBase(OSTServiceBase):
def __init__(self, *args, **kwargs):
super().__init__('nova', *args, **kwargs)
self._instances = None
self.nova_config = self.project.config['main']
@property
def instances(self):
if self._instances is not None:
return self._instances
instances = {}
for line in CLIHelper().ps():
ret = re.compile('.+product=OpenStack Nova.+').match(line)
if ret:
name = None
uuid = None
expr = r'.+uuid\s+([a-z0-9\-]+)[\s,]+.+'
ret = re.compile(expr).match(ret[0])
if ret:
uuid = ret[1]
expr = r'.+\s+-name\s+guest=(instance-\w+)[,]*.*\s+.+'
ret = re.compile(expr).match(ret[0])
if ret:
name = ret[1]
if not all([name, uuid]):
continue
guest = NovaInstance(uuid, name)
ret = re.compile(r'mac=([a-z0-9:]+)').findall(line)
if ret:
for mac in ret:
# convert libvirt to local/native
mac = 'fe' + mac[2:]
_port = self.nethelp.get_interface_with_hwaddr(mac)
if _port:
guest.add_port(_port)
ret = re.compile(r'.+\s-m\s+(\d+)').search(line)
if ret:
guest.memory_mbytes = int(ret.group(1))
instances[uuid] = guest
if not instances:
return {}
self._instances = instances
return self._instances
def get_nova_config_port(self, cfg_key):
"""
Fetch interface used by Openstack Nova config. Returns NetworkPort.
"""
addr = self.nova_config.get(cfg_key)
if not addr:
return
return self.nethelp.get_interface_with_addr(addr)
@property
def my_ip_port(self):
# NOTE: my_ip can be an address or fqdn, we currently only support
# searching by address.
return self.get_nova_config_port('my_ip')
@property
def live_migration_inbound_addr_port(self):
return self.get_nova_config_port('live_migration_inbound_addr')
@property
def bind_interfaces(self):
"""
Fetch interfaces used by Openstack Nova. Returned dict is keyed by
config key used to identify interface.
"""
interfaces = {}
if self.my_ip_port:
interfaces['my_ip'] = self.my_ip_port
if self.live_migration_inbound_addr_port:
port = self.live_migration_inbound_addr_port
interfaces['live_migration_inbound_addr'] = port
return interfaces
class NovaCPUPinning(NovaBase):
def __init__(self):
super().__init__()
self.numa = NUMAInfo()
self.systemd = SystemdConfig()
self.kernel = KernelConfig()
self.nova_cfg = OpenstackConfig(os.path.join(constants.DATA_ROOT,
'etc/nova/nova.conf'))
self.isolcpus = set(self.kernel.get('isolcpus',
expand_to_list=True) or [])
self.cpuaffinity = set(self.systemd.get('CPUAffinity',
expand_to_list=True) or [])
@property
def cpu_dedicated_set(self):
key = 'cpu_dedicated_set'
return self.nova_cfg.get(key, expand_to_list=True) or []
@property
def cpu_shared_set(self):
key = 'cpu_shared_set'
return self.nova_cfg.get(key, expand_to_list=True) or []
@property
def vcpu_pin_set(self):
key = 'vcpu_pin_set'
return self.nova_cfg.get(key, expand_to_list=True) or []
@property
def cpu_dedicated_set_name(self):
"""
If the vcpu_pin_set option has a value, we use that option as the name.
"""
if self.vcpu_pin_set:
return 'vcpu_pin_set'
return 'cpu_dedicated_set'
@property
def cpu_dedicated_set_intersection_isolcpus(self):
if self.vcpu_pin_set:
pinset = set(self.vcpu_pin_set)
else:
pinset = set(self.cpu_dedicated_set)
return list(pinset.intersection(self.isolcpus))
@property
def cpu_dedicated_set_intersection_cpuaffinity(self):
if self.vcpu_pin_set:
pinset = set(self.vcpu_pin_set)
else:
pinset = set(self.cpu_dedicated_set)
return list(pinset.intersection(self.cpuaffinity))
@property
def cpu_shared_set_intersection_isolcpus(self):
return list(set(self.cpu_shared_set).intersection(self.isolcpus))
@property
def cpuaffinity_intersection_isolcpus(self):
return list(self.cpuaffinity.intersection(self.isolcpus))
@property
def cpu_shared_set_intersection_cpu_dedicated_set(self):
if self.vcpu_pin_set:
pinset = set(self.vcpu_pin_set)
else:
pinset = set(self.cpu_dedicated_set)
return list(set(self.cpu_shared_set).intersection(pinset))
@property
def num_unpinned_cpus(self):
num_cpus = SystemBase().num_cpus
total_isolated = len(self.isolcpus.union(self.cpuaffinity))
return num_cpus - total_isolated
@property
def unpinned_cpus_pcent(self):
num_cpus = SystemBase().num_cpus
return int((float(100) / num_cpus) * self.num_unpinned_cpus)
@property
def nova_pinning_from_multi_numa_nodes(self):
if self.vcpu_pin_set:
pinset = set(self.vcpu_pin_set)
else:
pinset = set(self.cpu_dedicated_set)
node_count = 0
for node in self.numa.nodes:
node_cores = set(self.numa.cores(node))
if pinset.intersection(node_cores):
node_count += 1
return node_count > 1
class NeutronBase(OSTServiceBase):
def __init__(self, *args, **kwargs):
super().__init__('neutron', *args, **kwargs)
self.neutron_ovs_config = self.project.config['openvswitch-agent']
@property
def bind_interfaces(self):
"""
Fetch interfaces used by Openstack Neutron. Returned dict is keyed by
config key used to identify interface.
"""
local_ip = self.neutron_ovs_config.get('local_ip')
interfaces = {}
if not any([local_ip]):
return interfaces
if local_ip:
port = self.nethelp.get_interface_with_addr(local_ip)
# NOTE: local_ip can be an address or fqdn, we currently only
# support searching by address.
if port:
interfaces.update({'local_ip': port})
return interfaces
class OpenstackBase(object):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.ost_projects = OSTProjectCatalog()
other_pkgs = self.ost_projects.package_dependencies
self.apt_check = checks.APTPackageChecksBase(
core_pkgs=self.ost_projects.packages_core,
other_pkgs=other_pkgs)
self.nova = NovaBase()
self.neutron = NeutronBase()
self.octavia = OctaviaBase()
@property
def apt_packages_all(self):
return self.apt_check.all
@property
def bind_interfaces(self):
"""
Fetch interfaces used by Openstack services and return dict.
"""
interfaces = {}
ifaces = self.nova.bind_interfaces
if ifaces:
interfaces.update(ifaces)
ifaces = self.neutron.bind_interfaces
if ifaces:
interfaces.update(ifaces)
ifaces = self.octavia.bind_interfaces
if ifaces:
interfaces.update(ifaces)
return interfaces
@property
def release_name(self):
relname = None
relnames = set()
for pkg in OST_REL_INFO:
if pkg in self.apt_check.core:
# Since the versions we match against will always match our
# version - 1 we use last known lt as current version.
v_lt = None
r_lt = None
pkg_ver = DPKGVersionCompare(self.apt_check.core[pkg])
for rel, ver in OST_REL_INFO[pkg].items():
if pkg_ver > ver:
if v_lt is None:
v_lt = ver
r_lt = rel
elif ver > DPKGVersionCompare(v_lt):
v_lt = ver
r_lt = rel
if r_lt:
relnames.add(r_lt)
log.debug("release name(s) found: %s", ','.join(relnames))
if relnames:
relnames = sorted(list(relnames))
if len(relnames) > 1:
relnames
msg = ("openstack packages from mixed releases found - {}".
format(relnames))
issue = issue_types.OpenstackWarning(msg)
issue_utils.add_issue(issue)
relname = relnames[0]
if relname:
return relname
relname = 'unknown'
# fallback to uca version if exists
if not os.path.exists(APT_SOURCE_PATH):
return relname
release_info = {}
for source in os.listdir(APT_SOURCE_PATH):
apt_path = os.path.join(APT_SOURCE_PATH, source)
for line in CmdBase.safe_readlines(apt_path):
rexpr = r'deb .+ubuntu-cloud.+ [a-z]+-([a-z]+)/([a-z]+) .+'
ret = re.compile(rexpr).match(line)
if ret:
if 'uca' not in release_info:
release_info['uca'] = set()
if ret[1] != 'updates':
release_info['uca'].add("{}-{}".format(ret[2], ret[1]))
else:
release_info['uca'].add(ret[2])
if release_info.get('uca'):
return sorted(release_info['uca'], reverse=True)[0]
return relname
class OpenstackChecksBase(OpenstackBase, plugintools.PluginPartBase):
@property
def openstack_installed(self):
if self.apt_check.core:
return True
return False
@property
def plugin_runnable(self):
return self.openstack_installed
class OpenstackEventChecksBase(OpenstackChecksBase, YEventCheckerBase):
def __call__(self):
ret = self.run_checks()
if ret:
self._output.update(ret)
class OpenstackServiceChecksBase(OpenstackChecksBase,
checks.ServiceChecksBase):
def __init__(self):
service_exprs = OSTProjectCatalog().service_exprs
super().__init__(service_exprs=service_exprs, hint_range=(0, 3))
@property
def unexpected_masked_services(self):
masked = set(self.masked_services)
if not masked:
return []
expected_masked = self.ost_projects.default_masked_services
return list(masked.difference(expected_masked))
@property
def unexpected_masked_services_str(self):
masked = self.unexpected_masked_services
if not masked:
return ''
return '.'.join(self.unexpected_masked_services)
class OpenstackPackageChecksBase(OpenstackChecksBase):
pass
class OpenstackDockerImageChecksBase(OpenstackChecksBase,
checks.DockerImageChecksBase):
def __init__(self):
self.ost_projects = OSTProjectCatalog()
super().__init__(core_pkgs=self.ost_projects.packages_core,
other_pkgs=self.ost_projects.package_dependencies)
| 32.793722
| 79
| 0.538527
|
dc0d300cdaea724c3e28548250e520e1f7643933
| 847
|
py
|
Python
|
samples/client/petstore/python-experimental/test/test_grandparent_animal.py
|
MalcolmScoffable/openapi-generator
|
73605a0c0e0c825286c95123c63678ba75b44d5c
|
[
"Apache-2.0"
] | 4
|
2020-07-24T07:02:57.000Z
|
2022-01-08T17:37:38.000Z
|
samples/client/petstore/python-experimental/test/test_grandparent_animal.py
|
MalcolmScoffable/openapi-generator
|
73605a0c0e0c825286c95123c63678ba75b44d5c
|
[
"Apache-2.0"
] | 7
|
2021-05-12T00:00:20.000Z
|
2022-02-27T11:23:35.000Z
|
samples/client/petstore/python-experimental/test/test_grandparent_animal.py
|
MalcolmScoffable/openapi-generator
|
73605a0c0e0c825286c95123c63678ba75b44d5c
|
[
"Apache-2.0"
] | 2
|
2020-04-24T15:18:41.000Z
|
2021-12-07T09:39:40.000Z
|
# coding: utf-8
"""
OpenAPI Petstore
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import petstore_api
class TestGrandparentAnimal(unittest.TestCase):
"""GrandparentAnimal unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testGrandparentAnimal(self):
"""Test GrandparentAnimal"""
# FIXME: construct object with mandatory attributes with example values
# model = petstore_api.GrandparentAnimal() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
| 22.289474
| 174
| 0.689492
|
7bb0f62a4e51c3dd425f20a004921ad663758f62
| 3,216
|
py
|
Python
|
pvanalytics/quality/outliers.py
|
kanderso-nrel/pvanalytics
|
27ea3fdddaf0e885cce8b56438256b7e51e9bdea
|
[
"MIT",
"BSD-3-Clause"
] | 1
|
2022-01-04T14:26:06.000Z
|
2022-01-04T14:26:06.000Z
|
pvanalytics/quality/outliers.py
|
kanderso-nrel/pvanalytics
|
27ea3fdddaf0e885cce8b56438256b7e51e9bdea
|
[
"MIT",
"BSD-3-Clause"
] | null | null | null |
pvanalytics/quality/outliers.py
|
kanderso-nrel/pvanalytics
|
27ea3fdddaf0e885cce8b56438256b7e51e9bdea
|
[
"MIT",
"BSD-3-Clause"
] | 1
|
2021-02-22T23:12:25.000Z
|
2021-02-22T23:12:25.000Z
|
"""Functions for identifying and labeling outliers."""
import pandas as pd
from scipy import stats
from statsmodels import robust
def tukey(data, k=1.5):
r"""Identify outliers based on the interquartile range.
A value `x` is considered an outlier if it does *not* satisfy the
following condition
.. math::
Q_1 - k(Q_3 - Q_1) \le x \le Q_3 + k(Q_3 - Q_1)
where :math:`Q_1` is the value of the first quartile and
:math:`Q_3` is the value of the third quartile.
Parameters
----------
data : Series
The data in which to find outliers.
k : float, default 1.5
Multiplier of the interquartile range. A larger value will be more
permissive of values that are far from the median.
Returns
-------
Series
A series of booleans with True for each value that is an
outlier.
"""
first_quartile = data.quantile(0.25)
third_quartile = data.quantile(0.75)
iqr = third_quartile - first_quartile
return ((data < (first_quartile - k*iqr))
| (data > (third_quartile + k*iqr)))
def zscore(data, zmax=1.5):
"""Identify outliers using the z-score.
Points with z-score greater than `zmax` are considered as outliers.
Parameters
----------
data : Series
A series of numeric values in which to find outliers.
zmax : float
Upper limit of the absolute values of the z-score.
Returns
-------
Series
A series of booleans with True for each value that is an
outlier.
"""
return pd.Series((abs(stats.zscore(data)) > zmax), index=data.index)
def hampel(data, window=5, max_deviation=3.0, scale=None):
r"""Identify outliers by the Hampel identifier.
The Hampel identifier is computed according to [1]_.
Parameters
----------
data : Series
The data in which to find outliers.
window : int or offset, default 5
The size of the rolling window used to compute the Hampel
identifier.
max_deviation : float, default 3.0
Any value with a Hampel identifier > `max_deviation` standard
deviations from the median is considered an outlier.
scale : float, optional
Scale factor used to estimate the standard deviation as
:math:`MAD / scale`. If `scale=None` (default), then the scale
factor is taken to be ``scipy.stats.norm.ppf(3/4.)`` (approx. 0.6745),
and :math:`MAD / scale` approximates the standard deviation
of Gaussian distributed data.
Returns
-------
Series
True for each value that is an outlier according to its Hampel
identifier.
References
----------
.. [1] Pearson, R.K., Neuvo, Y., Astola, J. et al. Generalized
Hampel Filters. EURASIP J. Adv. Signal Process. 2016, 87
(2016). https://doi.org/10.1186/s13634-016-0383-6
"""
median = data.rolling(window=window, center=True).median()
deviation = abs(data - median)
kwargs = {}
if scale is not None:
kwargs = {'c': scale}
mad = data.rolling(window=window, center=True).apply(
robust.scale.mad,
kwargs=kwargs
)
return deviation > max_deviation * mad
| 29.777778
| 78
| 0.631841
|
2f571d7eecc6dfdf9c91c9e0445283f07f2619cf
| 35,903
|
py
|
Python
|
Lib/site-packages/mypy/plugin.py
|
edupyter/EDUPYTER38
|
396183cea72987506f1ef647c0272a2577c56218
|
[
"bzip2-1.0.6"
] | null | null | null |
Lib/site-packages/mypy/plugin.py
|
edupyter/EDUPYTER38
|
396183cea72987506f1ef647c0272a2577c56218
|
[
"bzip2-1.0.6"
] | null | null | null |
Lib/site-packages/mypy/plugin.py
|
edupyter/EDUPYTER38
|
396183cea72987506f1ef647c0272a2577c56218
|
[
"bzip2-1.0.6"
] | null | null | null |
"""Plugin system for extending mypy.
At large scale the plugin system works as following:
* Plugins are collected from the corresponding mypy config file option
(either via paths to Python files, or installed Python modules)
and imported using importlib.
* Every module should get an entry point function (called 'plugin' by default,
but may be overridden in the config file) that should accept a single string
argument that is a full mypy version (includes git commit hash for dev
versions) and return a subclass of mypy.plugins.Plugin.
* All plugin class constructors should match the signature of mypy.plugin.Plugin
(i.e. should accept an mypy.options.Options object), and *must* call
super().__init__().
* At several steps during semantic analysis and type checking mypy calls
special `get_xxx` methods on user plugins with a single string argument that
is a fully qualified name (full name) of a relevant definition
(see mypy.plugin.Plugin method docstrings for details).
* The plugins are called in the order they are passed in the config option.
Every plugin must decide whether to act on a given full name. The first
plugin that returns non-None object will be used.
* The above decision should be made using the limited common API specified by
mypy.plugin.CommonPluginApi.
* The callback returned by the plugin will be called with a larger context that
includes relevant current state (e.g. a default return type, or a default
attribute type) and a wider relevant API provider (e.g.
SemanticAnalyzerPluginInterface or CheckerPluginInterface).
* The result of this is used for further processing. See various `XxxContext`
named tuples for details about which information is given to each hook.
Plugin developers should ensure that their plugins work well in incremental and
daemon modes. In particular, plugins should not hold global state, and should
always call add_plugin_dependency() in plugin hooks called during semantic
analysis. See the method docstring for more details.
There is no dedicated cache storage for plugins, but plugins can store
per-TypeInfo data in a special .metadata attribute that is serialized to the
mypy caches between incremental runs. To avoid collisions between plugins, they
are encouraged to store their state under a dedicated key coinciding with
plugin name in the metadata dictionary. Every value stored there must be
JSON-serializable.
## Notes about the semantic analyzer
Mypy 0.710 introduced a new semantic analyzer that changed how plugins are
expected to work in several notable ways (from mypy 0.730 the old semantic
analyzer is no longer available):
1. The order of processing AST nodes in modules is different. The old semantic
analyzer processed modules in textual order, one module at a time. The new
semantic analyzer first processes the module top levels, including bodies of
any top-level classes and classes nested within classes. ("Top-level" here
means "not nested within a function/method".) Functions and methods are
processed only after module top levels have been finished. If there is an
import cycle, all module top levels in the cycle are processed before
processing any functions or methods. Each unit of processing (a module top
level or a function/method) is called a *target*.
This also means that function signatures in the same module have not been
analyzed yet when analyzing the module top level. If you need access to
a function signature, you'll need to explicitly analyze the signature first
using `anal_type()`.
2. Each target can be processed multiple times. This may happen if some forward
references are not ready yet, for example. This means that semantic analyzer
related plugin hooks can be called multiple times for the same full name.
These plugin methods must thus be idempotent.
3. The `anal_type` API function returns None if some part of the type is not
available yet. If this happens, the current target being analyzed will be
*deferred*, which means that it will be processed again soon, in the hope
that additional dependencies will be available. This may happen if there are
forward references to types or inter-module references to types within an
import cycle.
Note that if there is a circular definition, mypy may decide to stop
processing to avoid an infinite number of iterations. When this happens,
`anal_type` will generate an error and return an `AnyType` type object
during the final iteration (instead of None).
4. There is a new API method `defer()`. This can be used to explicitly request
the current target to be reprocessed one more time. You don't need this
to call this if `anal_type` returns None, however.
5. There is a new API property `final_iteration`, which is true once mypy
detected no progress during the previous iteration or if the maximum
semantic analysis iteration count has been reached. You must never
defer during the final iteration, as it will cause a crash.
6. The `node` attribute of SymbolTableNode objects may contain a reference to
a PlaceholderNode object. This object means that this definition has not
been fully processed yet. If you encounter a PlaceholderNode, you should
defer unless it's the final iteration. If it's the final iteration, you
should generate an error message. It usually means that there's a cyclic
definition that cannot be resolved by mypy. PlaceholderNodes can only refer
to references inside an import cycle. If you are looking up things from
another module, such as the builtins, that is outside the current module or
import cycle, you can safely assume that you won't receive a placeholder.
When testing your plugin, you should have a test case that forces a module top
level to be processed multiple times. The easiest way to do this is to include
a forward reference to a class in a top-level annotation. Example:
c: C # Forward reference causes second analysis pass
class C: pass
Note that a forward reference in a function signature won't trigger another
pass, since all functions are processed only after the top level has been fully
analyzed.
You can use `api.options.new_semantic_analyzer` to check whether the new
semantic analyzer is enabled (it's always true in mypy 0.730 and later).
"""
from abc import abstractmethod
from typing import Any, Callable, List, Tuple, Optional, NamedTuple, TypeVar, Dict, Union
from mypy_extensions import trait, mypyc_attr
from mypy.nodes import (
Expression, Context, ClassDef, SymbolTableNode, MypyFile, CallExpr, ArgKind, TypeInfo
)
from mypy.tvar_scope import TypeVarLikeScope
from mypy.types import (
Type, Instance, CallableType, TypeList, UnboundType, ProperType, FunctionLike
)
from mypy.messages import MessageBuilder
from mypy.options import Options
from mypy.lookup import lookup_fully_qualified
from mypy.errorcodes import ErrorCode
from mypy.message_registry import ErrorMessage
@trait
class TypeAnalyzerPluginInterface:
"""Interface for accessing semantic analyzer functionality in plugins.
Methods docstrings contain only basic info. Look for corresponding implementation
docstrings in typeanal.py for more details.
"""
# An options object. Note: these are the cloned options for the current file.
# This might be different from Plugin.options (that contains default/global options)
# if there are per-file options in the config. This applies to all other interfaces
# in this file.
options: Options
@abstractmethod
def fail(self, msg: str, ctx: Context, *, code: Optional[ErrorCode] = None) -> None:
"""Emit an error message at given location."""
raise NotImplementedError
@abstractmethod
def named_type(self, name: str, args: List[Type]) -> Instance:
"""Construct an instance of a builtin type with given name."""
raise NotImplementedError
@abstractmethod
def analyze_type(self, typ: Type) -> Type:
"""Analyze an unbound type using the default mypy logic."""
raise NotImplementedError
@abstractmethod
def analyze_callable_args(self, arglist: TypeList) -> Optional[Tuple[List[Type],
List[ArgKind],
List[Optional[str]]]]:
"""Find types, kinds, and names of arguments from extended callable syntax."""
raise NotImplementedError
# A context for a hook that semantically analyzes an unbound type.
class AnalyzeTypeContext(NamedTuple):
type: UnboundType # Type to analyze
context: Context # Relevant location context (e.g. for error messages)
api: TypeAnalyzerPluginInterface
@mypyc_attr(allow_interpreted_subclasses=True)
class CommonPluginApi:
"""
A common plugin API (shared between semantic analysis and type checking phases)
that all plugin hooks get independently of the context.
"""
# Global mypy options.
# Per-file options can be only accessed on various
# XxxPluginInterface classes.
options: Options
@abstractmethod
def lookup_fully_qualified(self, fullname: str) -> Optional[SymbolTableNode]:
"""Lookup a symbol by its full name (including module).
This lookup function available for all plugins. Return None if a name
is not found. This function doesn't support lookup from current scope.
Use SemanticAnalyzerPluginInterface.lookup_qualified() for this."""
raise NotImplementedError
@trait
class CheckerPluginInterface:
"""Interface for accessing type checker functionality in plugins.
Methods docstrings contain only basic info. Look for corresponding implementation
docstrings in checker.py for more details.
"""
msg: MessageBuilder
options: Options
path: str
# Type context for type inference
@property
@abstractmethod
def type_context(self) -> List[Optional[Type]]:
"""Return the type context of the plugin"""
raise NotImplementedError
@abstractmethod
def fail(self, msg: Union[str, ErrorMessage], ctx: Context, *,
code: Optional[ErrorCode] = None) -> None:
"""Emit an error message at given location."""
raise NotImplementedError
@abstractmethod
def named_generic_type(self, name: str, args: List[Type]) -> Instance:
"""Construct an instance of a builtin type with given type arguments."""
raise NotImplementedError
@trait
class SemanticAnalyzerPluginInterface:
"""Interface for accessing semantic analyzer functionality in plugins.
Methods docstrings contain only basic info. Look for corresponding implementation
docstrings in semanal.py for more details.
# TODO: clean-up lookup functions.
"""
modules: Dict[str, MypyFile]
# Options for current file.
options: Options
cur_mod_id: str
msg: MessageBuilder
@abstractmethod
def named_type(self, fullname: str,
args: Optional[List[Type]] = None) -> Instance:
"""Construct an instance of a builtin type with given type arguments."""
raise NotImplementedError
@abstractmethod
def builtin_type(self, fully_qualified_name: str) -> Instance:
"""Legacy function -- use named_type() instead."""
# NOTE: Do not delete this since many plugins may still use it.
raise NotImplementedError
@abstractmethod
def named_type_or_none(self, fullname: str,
args: Optional[List[Type]] = None) -> Optional[Instance]:
"""Construct an instance of a type with given type arguments.
Return None if a type could not be constructed for the qualified
type name. This is possible when the qualified name includes a
module name and the module has not been imported.
"""
raise NotImplementedError
@abstractmethod
def basic_new_typeinfo(self, name: str, basetype_or_fallback: Instance, line: int) -> TypeInfo:
raise NotImplementedError
@abstractmethod
def parse_bool(self, expr: Expression) -> Optional[bool]:
"""Parse True/False literals."""
raise NotImplementedError
@abstractmethod
def fail(self, msg: str, ctx: Context, serious: bool = False, *,
blocker: bool = False, code: Optional[ErrorCode] = None) -> None:
"""Emit an error message at given location."""
raise NotImplementedError
@abstractmethod
def anal_type(self, t: Type, *,
tvar_scope: Optional[TypeVarLikeScope] = None,
allow_tuple_literal: bool = False,
allow_unbound_tvars: bool = False,
report_invalid_types: bool = True,
third_pass: bool = False) -> Optional[Type]:
"""Analyze an unbound type.
Return None if some part of the type is not ready yet. In this
case the current target being analyzed will be deferred and
analyzed again.
"""
raise NotImplementedError
@abstractmethod
def class_type(self, self_type: Type) -> Type:
"""Generate type of first argument of class methods from type of self."""
raise NotImplementedError
@abstractmethod
def lookup_fully_qualified(self, name: str) -> SymbolTableNode:
"""Lookup a symbol by its fully qualified name.
Raise an error if not found.
"""
raise NotImplementedError
@abstractmethod
def lookup_fully_qualified_or_none(self, name: str) -> Optional[SymbolTableNode]:
"""Lookup a symbol by its fully qualified name.
Return None if not found.
"""
raise NotImplementedError
@abstractmethod
def lookup_qualified(self, name: str, ctx: Context,
suppress_errors: bool = False) -> Optional[SymbolTableNode]:
"""Lookup symbol using a name in current scope.
This follows Python local->non-local->global->builtins rules.
"""
raise NotImplementedError
@abstractmethod
def add_plugin_dependency(self, trigger: str, target: Optional[str] = None) -> None:
"""Specify semantic dependencies for generated methods/variables.
If the symbol with full name given by trigger is found to be stale by mypy,
then the body of node with full name given by target will be re-checked.
By default, this is the node that is currently analyzed.
For example, the dataclass plugin adds a generated __init__ method with
a signature that depends on types of attributes in ancestor classes. If any
attribute in an ancestor class gets stale (modified), we need to reprocess
the subclasses (and thus regenerate __init__ methods).
This is used by fine-grained incremental mode (mypy daemon). See mypy/server/deps.py
for more details.
"""
raise NotImplementedError
@abstractmethod
def add_symbol_table_node(self, name: str, stnode: SymbolTableNode) -> Any:
"""Add node to global symbol table (or to nearest class if there is one)."""
raise NotImplementedError
@abstractmethod
def qualified_name(self, n: str) -> str:
"""Make qualified name using current module and enclosing class (if any)."""
raise NotImplementedError
@abstractmethod
def defer(self) -> None:
"""Call this to defer the processing of the current node.
This will request an additional iteration of semantic analysis.
"""
raise NotImplementedError
@property
@abstractmethod
def final_iteration(self) -> bool:
"""Is this the final iteration of semantic analysis?"""
raise NotImplementedError
@property
@abstractmethod
def is_stub_file(self) -> bool:
raise NotImplementedError
# A context for querying for configuration data about a module for
# cache invalidation purposes.
class ReportConfigContext(NamedTuple):
id: str # Module name
path: str # Module file path
is_check: bool # Is this invocation for checking whether the config matches
# A context for a function signature hook that infers a better signature for a
# function. Note that argument types aren't available yet. If you need them,
# you have to use a method hook instead.
class FunctionSigContext(NamedTuple):
args: List[List[Expression]] # Actual expressions for each formal argument
default_signature: CallableType # Original signature of the method
context: Context # Relevant location context (e.g. for error messages)
api: CheckerPluginInterface
# A context for a function hook that infers the return type of a function with
# a special signature.
#
# A no-op callback would just return the inferred return type, but a useful
# callback at least sometimes can infer a more precise type.
class FunctionContext(NamedTuple):
arg_types: List[List[Type]] # List of actual caller types for each formal argument
arg_kinds: List[List[ArgKind]] # Ditto for argument kinds, see nodes.ARG_* constants
# Names of formal parameters from the callee definition,
# these will be sufficient in most cases.
callee_arg_names: List[Optional[str]]
# Names of actual arguments in the call expression. For example,
# in a situation like this:
# def func(**kwargs) -> None:
# pass
# func(kw1=1, kw2=2)
# callee_arg_names will be ['kwargs'] and arg_names will be [['kw1', 'kw2']].
arg_names: List[List[Optional[str]]]
default_return_type: Type # Return type inferred from signature
args: List[List[Expression]] # Actual expressions for each formal argument
context: Context # Relevant location context (e.g. for error messages)
api: CheckerPluginInterface
# A context for a method signature hook that infers a better signature for a
# method. Note that argument types aren't available yet. If you need them,
# you have to use a method hook instead.
# TODO: document ProperType in the plugin changelog/update issue.
class MethodSigContext(NamedTuple):
type: ProperType # Base object type for method call
args: List[List[Expression]] # Actual expressions for each formal argument
default_signature: CallableType # Original signature of the method
context: Context # Relevant location context (e.g. for error messages)
api: CheckerPluginInterface
# A context for a method hook that infers the return type of a method with a
# special signature.
#
# This is very similar to FunctionContext (only differences are documented).
class MethodContext(NamedTuple):
type: ProperType # Base object type for method call
arg_types: List[List[Type]] # List of actual caller types for each formal argument
# see FunctionContext for details about names and kinds
arg_kinds: List[List[ArgKind]]
callee_arg_names: List[Optional[str]]
arg_names: List[List[Optional[str]]]
default_return_type: Type # Return type inferred by mypy
args: List[List[Expression]] # Lists of actual expressions for every formal argument
context: Context
api: CheckerPluginInterface
# A context for an attribute type hook that infers the type of an attribute.
class AttributeContext(NamedTuple):
type: ProperType # Type of object with attribute
default_attr_type: Type # Original attribute type
context: Context # Relevant location context (e.g. for error messages)
api: CheckerPluginInterface
# A context for a class hook that modifies the class definition.
class ClassDefContext(NamedTuple):
cls: ClassDef # The class definition
reason: Expression # The expression being applied (decorator, metaclass, base class)
api: SemanticAnalyzerPluginInterface
# A context for dynamic class definitions like
# Base = declarative_base()
class DynamicClassDefContext(NamedTuple):
call: CallExpr # The r.h.s. of dynamic class definition
name: str # The name this class is being assigned to
api: SemanticAnalyzerPluginInterface
@mypyc_attr(allow_interpreted_subclasses=True)
class Plugin(CommonPluginApi):
"""Base class of all type checker plugins.
This defines a no-op plugin. Subclasses can override some methods to
provide some actual functionality.
All get_ methods are treated as pure functions (you should assume that
results might be cached). A plugin should return None from a get_ method
to give way to other plugins.
Look at the comments of various *Context objects for additional information on
various hooks.
"""
def __init__(self, options: Options) -> None:
self.options = options
self.python_version = options.python_version
# This can't be set in __init__ because it is executed too soon in build.py.
# Therefore, build.py *must* set it later before graph processing starts
# by calling set_modules().
self._modules: Optional[Dict[str, MypyFile]] = None
def set_modules(self, modules: Dict[str, MypyFile]) -> None:
self._modules = modules
def lookup_fully_qualified(self, fullname: str) -> Optional[SymbolTableNode]:
assert self._modules is not None
return lookup_fully_qualified(fullname, self._modules)
def report_config_data(self, ctx: ReportConfigContext) -> Any:
"""Get representation of configuration data for a module.
The data must be encodable as JSON and will be stored in the
cache metadata for the module. A mismatch between the cached
values and the returned will result in that module's cache
being invalidated and the module being rechecked.
This can be called twice for each module, once after loading
the cache to check if it is valid and once while writing new
cache information.
If is_check in the context is true, then the return of this
call will be checked against the cached version. Otherwise the
call is being made to determine what to put in the cache. This
can be used to allow consulting extra cache files in certain
complex situations.
This can be used to incorporate external configuration information
that might require changes to typechecking.
"""
return None
def get_additional_deps(self, file: MypyFile) -> List[Tuple[int, str, int]]:
"""Customize dependencies for a module.
This hook allows adding in new dependencies for a module. It
is called after parsing a file but before analysis. This can
be useful if a library has dependencies that are dynamic based
on configuration information, for example.
Returns a list of (priority, module name, line number) tuples.
The line number can be -1 when there is not a known real line number.
Priorities are defined in mypy.build (but maybe shouldn't be).
10 is a good choice for priority.
"""
return []
def get_type_analyze_hook(self, fullname: str
) -> Optional[Callable[[AnalyzeTypeContext], Type]]:
"""Customize behaviour of the type analyzer for given full names.
This method is called during the semantic analysis pass whenever mypy sees an
unbound type. For example, while analysing this code:
from lib import Special, Other
var: Special
def func(x: Other[int]) -> None:
...
this method will be called with 'lib.Special', and then with 'lib.Other'.
The callback returned by plugin must return an analyzed type,
i.e. an instance of `mypy.types.Type`.
"""
return None
def get_function_signature_hook(self, fullname: str
) -> Optional[Callable[[FunctionSigContext], FunctionLike]]:
"""Adjust the signature of a function.
This method is called before type checking a function call. Plugin
may infer a better type for the function.
from lib import Class, do_stuff
do_stuff(42)
Class()
This method will be called with 'lib.do_stuff' and then with 'lib.Class'.
"""
return None
def get_function_hook(self, fullname: str
) -> Optional[Callable[[FunctionContext], Type]]:
"""Adjust the return type of a function call.
This method is called after type checking a call. Plugin may adjust the return
type inferred by mypy, and/or emit some error messages. Note, this hook is also
called for class instantiation calls, so that in this example:
from lib import Class, do_stuff
do_stuff(42)
Class()
This method will be called with 'lib.do_stuff' and then with 'lib.Class'.
"""
return None
def get_method_signature_hook(self, fullname: str
) -> Optional[Callable[[MethodSigContext], FunctionLike]]:
"""Adjust the signature of a method.
This method is called before type checking a method call. Plugin
may infer a better type for the method. The hook is also called for special
Python dunder methods except __init__ and __new__ (use get_function_hook to customize
class instantiation). This function is called with the method full name using
the class where it was _defined_. For example, in this code:
from lib import Special
class Base:
def method(self, arg: Any) -> Any:
...
class Derived(Base):
...
var: Derived
var.method(42)
x: Special
y = x[0]
this method is called with '__main__.Base.method', and then with
'lib.Special.__getitem__'.
"""
return None
def get_method_hook(self, fullname: str
) -> Optional[Callable[[MethodContext], Type]]:
"""Adjust return type of a method call.
This is the same as get_function_hook(), but is called with the
method full name (again, using the class where the method is defined).
"""
return None
def get_attribute_hook(self, fullname: str
) -> Optional[Callable[[AttributeContext], Type]]:
"""Adjust type of an instance attribute.
This method is called with attribute full name using the class of the instance where
the attribute was defined (or Var.info.fullname for generated attributes).
For classes without __getattr__ or __getattribute__, this hook is only called for
names of fields/properties (but not methods) that exist in the instance MRO.
For classes that implement __getattr__ or __getattribute__, this hook is called
for all fields/properties, including nonexistent ones (but still not methods).
For example:
class Base:
x: Any
def __getattr__(self, attr: str) -> Any: ...
class Derived(Base):
...
var: Derived
var.x
var.y
get_attribute_hook is called with '__main__.Base.x' and '__main__.Base.y'.
However, if we had not implemented __getattr__ on Base, you would only get
the callback for 'var.x'; 'var.y' would produce an error without calling the hook.
"""
return None
def get_class_attribute_hook(self, fullname: str
) -> Optional[Callable[[AttributeContext], Type]]:
"""
Adjust type of a class attribute.
This method is called with attribute full name using the class where the attribute was
defined (or Var.info.fullname for generated attributes).
For example:
class Cls:
x: Any
Cls.x
get_class_attribute_hook is called with '__main__.Cls.x' as fullname.
"""
return None
def get_class_decorator_hook(self, fullname: str
) -> Optional[Callable[[ClassDefContext], None]]:
"""Update class definition for given class decorators.
The plugin can modify a TypeInfo _in place_ (for example add some generated
methods to the symbol table). This hook is called after the class body was
semantically analyzed, but *there may still be placeholders* (typically
caused by forward references).
NOTE: Usually get_class_decorator_hook_2 is the better option, since it
guarantees that there are no placeholders.
The hook is called with full names of all class decorators.
The hook can be called multiple times per class, so it must be
idempotent.
"""
return None
def get_class_decorator_hook_2(self, fullname: str
) -> Optional[Callable[[ClassDefContext], bool]]:
"""Update class definition for given class decorators.
Similar to get_class_decorator_hook, but this runs in a later pass when
placeholders have been resolved.
The hook can return False if some base class hasn't been
processed yet using class hooks. It causes all class hooks
(that are run in this same pass) to be invoked another time for
the file(s) currently being processed.
The hook can be called multiple times per class, so it must be
idempotent.
"""
return None
def get_metaclass_hook(self, fullname: str
) -> Optional[Callable[[ClassDefContext], None]]:
"""Update class definition for given declared metaclasses.
Same as get_class_decorator_hook() but for metaclasses. Note:
this hook will be only called for explicit metaclasses, not for
inherited ones.
TODO: probably it should also be called on inherited metaclasses.
"""
return None
def get_base_class_hook(self, fullname: str
) -> Optional[Callable[[ClassDefContext], None]]:
"""Update class definition for given base classes.
Same as get_class_decorator_hook() but for base classes. Base classes
don't need to refer to TypeInfos, if a base class refers to a variable with
Any type, this hook will still be called.
"""
return None
def get_customize_class_mro_hook(self, fullname: str
) -> Optional[Callable[[ClassDefContext], None]]:
"""Customize MRO for given classes.
The plugin can modify the class MRO _in place_. This method is called
with the class full name before its body was semantically analyzed.
"""
return None
def get_dynamic_class_hook(self, fullname: str
) -> Optional[Callable[[DynamicClassDefContext], None]]:
"""Semantically analyze a dynamic class definition.
This plugin hook allows one to semantically analyze dynamic class definitions like:
from lib import dynamic_class
X = dynamic_class('X', [])
For such definition, this hook will be called with 'lib.dynamic_class'.
The plugin should create the corresponding TypeInfo, and place it into a relevant
symbol table, e.g. using ctx.api.add_symbol_table_node().
"""
return None
T = TypeVar('T')
class ChainedPlugin(Plugin):
"""A plugin that represents a sequence of chained plugins.
Each lookup method returns the hook for the first plugin that
reports a match.
This class should not be subclassed -- use Plugin as the base class
for all plugins.
"""
# TODO: Support caching of lookup results (through a LRU cache, for example).
def __init__(self, options: Options, plugins: List[Plugin]) -> None:
"""Initialize chained plugin.
Assume that the child plugins aren't mutated (results may be cached).
"""
super().__init__(options)
self._plugins = plugins
def set_modules(self, modules: Dict[str, MypyFile]) -> None:
for plugin in self._plugins:
plugin.set_modules(modules)
def report_config_data(self, ctx: ReportConfigContext) -> Any:
config_data = [plugin.report_config_data(ctx) for plugin in self._plugins]
return config_data if any(x is not None for x in config_data) else None
def get_additional_deps(self, file: MypyFile) -> List[Tuple[int, str, int]]:
deps = []
for plugin in self._plugins:
deps.extend(plugin.get_additional_deps(file))
return deps
def get_type_analyze_hook(self, fullname: str
) -> Optional[Callable[[AnalyzeTypeContext], Type]]:
return self._find_hook(lambda plugin: plugin.get_type_analyze_hook(fullname))
def get_function_signature_hook(self, fullname: str
) -> Optional[Callable[[FunctionSigContext], FunctionLike]]:
return self._find_hook(lambda plugin: plugin.get_function_signature_hook(fullname))
def get_function_hook(self, fullname: str
) -> Optional[Callable[[FunctionContext], Type]]:
return self._find_hook(lambda plugin: plugin.get_function_hook(fullname))
def get_method_signature_hook(self, fullname: str
) -> Optional[Callable[[MethodSigContext], FunctionLike]]:
return self._find_hook(lambda plugin: plugin.get_method_signature_hook(fullname))
def get_method_hook(self, fullname: str
) -> Optional[Callable[[MethodContext], Type]]:
return self._find_hook(lambda plugin: plugin.get_method_hook(fullname))
def get_attribute_hook(self, fullname: str
) -> Optional[Callable[[AttributeContext], Type]]:
return self._find_hook(lambda plugin: plugin.get_attribute_hook(fullname))
def get_class_attribute_hook(self, fullname: str
) -> Optional[Callable[[AttributeContext], Type]]:
return self._find_hook(lambda plugin: plugin.get_class_attribute_hook(fullname))
def get_class_decorator_hook(self, fullname: str
) -> Optional[Callable[[ClassDefContext], None]]:
return self._find_hook(lambda plugin: plugin.get_class_decorator_hook(fullname))
def get_class_decorator_hook_2(self, fullname: str
) -> Optional[Callable[[ClassDefContext], bool]]:
return self._find_hook(lambda plugin: plugin.get_class_decorator_hook_2(fullname))
def get_metaclass_hook(self, fullname: str
) -> Optional[Callable[[ClassDefContext], None]]:
return self._find_hook(lambda plugin: plugin.get_metaclass_hook(fullname))
def get_base_class_hook(self, fullname: str
) -> Optional[Callable[[ClassDefContext], None]]:
return self._find_hook(lambda plugin: plugin.get_base_class_hook(fullname))
def get_customize_class_mro_hook(self, fullname: str
) -> Optional[Callable[[ClassDefContext], None]]:
return self._find_hook(lambda plugin: plugin.get_customize_class_mro_hook(fullname))
def get_dynamic_class_hook(self, fullname: str
) -> Optional[Callable[[DynamicClassDefContext], None]]:
return self._find_hook(lambda plugin: plugin.get_dynamic_class_hook(fullname))
def _find_hook(self, lookup: Callable[[Plugin], T]) -> Optional[T]:
for plugin in self._plugins:
hook = lookup(plugin)
if hook:
return hook
return None
| 41.362903
| 99
| 0.687463
|
0a38f96a395a7887fea46451cf005cb8e5ff8f70
| 583
|
py
|
Python
|
app/controllers/Unidade_medida_controller.py
|
amandapersampa/FastFrango
|
23a69d80576f6cef754e9d3acacf9908a4da30cd
|
[
"MIT"
] | null | null | null |
app/controllers/Unidade_medida_controller.py
|
amandapersampa/FastFrango
|
23a69d80576f6cef754e9d3acacf9908a4da30cd
|
[
"MIT"
] | null | null | null |
app/controllers/Unidade_medida_controller.py
|
amandapersampa/FastFrango
|
23a69d80576f6cef754e9d3acacf9908a4da30cd
|
[
"MIT"
] | null | null | null |
from app import app
from app.dao.Unidade_medida_dao import Unidade_medida_dao
from app.service.Unidade_medida_service import Unidade_medida_service
from flask import jsonify
import json
service = Unidade_medida_service()
@app.route("/unidadeMedida")
def salva_unidade_medida():
unidade = Unidade_medida_dao("M")
return jsonify(service.salvar(unidade))
@app.route("/unidadeMedida/list")
def findAll_unidade():
return jsonify(service.findAll())
@app.route("/unidadeMedida/<id>")
def findById_unidade(id):
service.findById(id)
return 'ok'
| 25.347826
| 70
| 0.746141
|
6c312a3cecfbf5d985cf3096e2a306e4d2d3c059
| 1,253
|
py
|
Python
|
benchmarks/asv_bench/benchmarks/import.py
|
chineking/mars
|
660098c65bcb389c6bbebc26b2502a9b3af43cf9
|
[
"Apache-2.0"
] | null | null | null |
benchmarks/asv_bench/benchmarks/import.py
|
chineking/mars
|
660098c65bcb389c6bbebc26b2502a9b3af43cf9
|
[
"Apache-2.0"
] | null | null | null |
benchmarks/asv_bench/benchmarks/import.py
|
chineking/mars
|
660098c65bcb389c6bbebc26b2502a9b3af43cf9
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 1999-2022 Alibaba Group Holding Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import subprocess
import sys
# make sure necessary pyc files generated
import mars.dataframe as md
import mars.tensor as mt
del md, mt
class ImportPackageSuite:
"""
Benchmark that times performance of chunk graph builder
"""
def time_import_mars(self):
proc = subprocess.Popen([sys.executable, "-c", "import mars"])
proc.wait(120)
def time_import_mars_tensor(self):
proc = subprocess.Popen([sys.executable, "-c", "import mars.tensor"])
proc.wait(120)
def time_import_mars_dataframe(self):
proc = subprocess.Popen([sys.executable, "-c", "import mars.dataframe"])
proc.wait(120)
| 30.560976
| 80
| 0.71668
|
b47e0baed684bba42a5130c1ba862fdcde0b72db
| 545
|
py
|
Python
|
src/detect_related_url/css_selectors.py
|
myuunews/myuunews-bot
|
44b00fd24fa51ce7b5145947490851d86379a44d
|
[
"MIT"
] | 6
|
2019-06-15T07:05:32.000Z
|
2019-09-29T08:08:09.000Z
|
src/detect_related_url/css_selectors.py
|
myuunews/myuunews-bot
|
44b00fd24fa51ce7b5145947490851d86379a44d
|
[
"MIT"
] | 5
|
2019-06-30T19:09:39.000Z
|
2019-12-11T07:12:13.000Z
|
src/detect_related_url/css_selectors.py
|
myuunews/myuunews-bot
|
44b00fd24fa51ce7b5145947490851d86379a44d
|
[
"MIT"
] | 3
|
2019-06-15T07:28:07.000Z
|
2019-09-09T16:24:22.000Z
|
# -*- coding: utf-8 -*-
import re
from typing import Dict, List, Optional
class Selectors:
def __init__(self, selectors: Dict[str, str], ignored_urls: List[str]):
self._selectors = selectors
self._ignored_urls = ignored_urls
def get_selector(self, url: str) -> Optional[str]:
for u in self._ignored_urls:
if re.match(u, url):
return None
for reg, selector in self._selectors.items():
if re.match(reg, url):
return selector
return 'body'
| 27.25
| 75
| 0.59633
|
363c05d2a4fa3d1a752c4b6458f4ac8dfe7a6085
| 19,443
|
py
|
Python
|
SCons/Tool/ninja/__init__.py
|
bquistorff/scons
|
271b7dde7a937cf38d4cf8d25c0958a83e891b62
|
[
"MIT"
] | 2
|
2021-11-08T02:51:47.000Z
|
2021-11-08T09:40:47.000Z
|
SCons/Tool/ninja/__init__.py
|
bquistorff/scons
|
271b7dde7a937cf38d4cf8d25c0958a83e891b62
|
[
"MIT"
] | null | null | null |
SCons/Tool/ninja/__init__.py
|
bquistorff/scons
|
271b7dde7a937cf38d4cf8d25c0958a83e891b62
|
[
"MIT"
] | null | null | null |
# MIT License
#
# Copyright 2020 MongoDB Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
"""Generate build.ninja files from SCons aliases."""
import importlib
import os
import subprocess
import sys
import SCons
import SCons.Tool.ninja.Globals
from SCons.Script import GetOption
from .Globals import NINJA_RULES, NINJA_POOLS, NINJA_CUSTOM_HANDLERS
from .Methods import register_custom_handler, register_custom_rule_mapping, register_custom_rule, register_custom_pool, \
set_build_node_callback, get_generic_shell_command, CheckNinjaCompdbExpand, get_command, \
gen_get_response_file_command
from .Overrides import ninja_hack_linkcom, ninja_hack_arcom, NinjaNoResponseFiles, ninja_always_serial, AlwaysExecAction
from .Utils import ninja_add_command_line_options, \
ninja_noop, ninja_print_conf_log, ninja_csig, ninja_contents, ninja_stat, ninja_whereis
try:
import ninja
NINJA_BINARY = ninja.__file__
except ImportError:
NINJA_BINARY = False
else:
from .NinjaState import NinjaState
NINJA_STATE = None
def ninja_builder(env, target, source):
"""Generate a build.ninja for source."""
if not isinstance(source, list):
source = [source]
if not isinstance(target, list):
target = [target]
# We have no COMSTR equivalent so print that we're generating
# here.
print("Generating:", str(target[0]))
generated_build_ninja = target[0].get_abspath()
NINJA_STATE.generate()
if env["PLATFORM"] == "win32":
# TODO: Is this necessary as you set env variable in the ninja build file per target?
# this is not great, its doesn't consider specific
# node environments, which means on linux the build could
# behave differently, because on linux you can set the environment
# per command in the ninja file. This is only needed if
# running ninja directly from a command line that hasn't
# had the environment setup (vcvarsall.bat)
with open('run_ninja_env.bat', 'w') as f:
for key in env['ENV']:
f.write('set {}={}\n'.format(key, env['ENV'][key]))
f.write('{} -f {} %*\n'.format(NINJA_STATE.ninja_bin_path, generated_build_ninja))
cmd = ['run_ninja_env.bat']
else:
cmd = [NINJA_STATE.ninja_bin_path, '-f', generated_build_ninja]
if not env.get("NINJA_DISABLE_AUTO_RUN"):
print("Executing:", str(' '.join(cmd)))
# execute the ninja build at the end of SCons, trying to
# reproduce the output like a ninja build would
def execute_ninja():
proc = subprocess.Popen(cmd,
stderr=sys.stderr,
stdout=subprocess.PIPE,
universal_newlines=True,
env=os.environ if env["PLATFORM"] == "win32" else env['ENV']
)
for stdout_line in iter(proc.stdout.readline, ""):
yield stdout_line
proc.stdout.close()
return_code = proc.wait()
if return_code:
raise subprocess.CalledProcessError(return_code, 'ninja')
erase_previous = False
for output in execute_ninja():
output = output.strip()
if erase_previous:
sys.stdout.write('\x1b[2K') # erase previous line
sys.stdout.write("\r")
else:
sys.stdout.write(os.linesep)
sys.stdout.write(output)
sys.stdout.flush()
# this will only erase ninjas [#/#] lines
# leaving warnings and other output, seems a bit
# prone to failure with such a simple check
erase_previous = output.startswith('[')
def exists(env):
"""Enable if called."""
if 'ninja' not in GetOption('experimental'):
return False
# This variable disables the tool when storing the SCons command in the
# generated ninja file to ensure that the ninja tool is not loaded when
# SCons should do actual work as a subprocess of a ninja build. The ninja
# tool is very invasive into the internals of SCons and so should never be
# enabled when SCons needs to build a target.
if env.get("__NINJA_NO", "0") == "1":
return False
# pypi ninja module detection done at top of file during import ninja.
if NINJA_BINARY:
return NINJA_BINARY
else:
raise SCons.Warnings.SConsWarning("Failed to import ninja, attempt normal SCons build.")
def ninja_emitter(target, source, env):
""" fix up the source/targets """
ninja_file = env.File(env.subst("$NINJA_FILE_NAME"))
ninja_file.attributes.ninja_file = True
# Someone called env.Ninja('my_targetname.ninja')
if not target and len(source) == 1:
target = source
# Default target name is $NINJA_PREFIX.$NINJA.SUFFIX
if not target:
target = [ninja_file, ]
# No source should have been passed. Drop it.
if source:
source = []
return target, source
def generate(env):
"""Generate the NINJA builders."""
global NINJA_STATE
if 'ninja' not in GetOption('experimental'):
return
if not SCons.Tool.ninja.Globals.ninja_builder_initialized:
SCons.Tool.ninja.Globals.ninja_builder_initialized = True
ninja_add_command_line_options()
if not NINJA_BINARY:
raise SCons.Warnings.SConsWarning("Failed to import ninja, attempt normal SCons build.")
env["NINJA_DISABLE_AUTO_RUN"] = env.get("NINJA_DISABLE_AUTO_RUN", GetOption('disable_execute_ninja'))
env["NINJA_FILE_NAME"] = env.get("NINJA_FILE_NAME", "build.ninja")
# Add the Ninja builder.
always_exec_ninja_action = AlwaysExecAction(ninja_builder, {})
ninja_builder_obj = SCons.Builder.Builder(action=always_exec_ninja_action,
emitter=ninja_emitter)
env.Append(BUILDERS={"Ninja": ninja_builder_obj})
env["NINJA_ALIAS_NAME"] = env.get("NINJA_ALIAS_NAME", "generate-ninja")
env['NINJA_DIR'] = env.get("NINJA_DIR", env.Dir(".ninja").path)
# here we allow multiple environments to construct rules and builds
# into the same ninja file
if NINJA_STATE is None:
ninja_file = env.Ninja()
env.AlwaysBuild(ninja_file)
env.Alias("$NINJA_ALIAS_NAME", ninja_file)
else:
if str(NINJA_STATE.ninja_file) != env["NINJA_FILE_NAME"]:
SCons.Warnings.SConsWarning("Generating multiple ninja files not supported, set ninja file name before tool initialization.")
ninja_file = [NINJA_STATE.ninja_file]
def ninja_generate_deps(env):
"""Return a list of SConscripts
TODO: Should we also include files loaded from site_scons/***
or even all loaded modules? https://stackoverflow.com/questions/4858100/how-to-list-imported-modules
TODO: Do we want this to be Nodes?
"""
return sorted([str(s) for s in SCons.Node.SConscriptNodes])
env['_NINJA_REGENERATE_DEPS_FUNC'] = ninja_generate_deps
env['NINJA_REGENERATE_DEPS'] = env.get('NINJA_REGENERATE_DEPS', '${_NINJA_REGENERATE_DEPS_FUNC(__env__)}')
# This adds the required flags such that the generated compile
# commands will create depfiles as appropriate in the Ninja file.
if env["PLATFORM"] == "win32":
env.Append(CCFLAGS=["/showIncludes"])
else:
env.Append(CCFLAGS=["-MMD", "-MF", "${TARGET}.d"])
env.AddMethod(CheckNinjaCompdbExpand, "CheckNinjaCompdbExpand")
# Provide a way for custom rule authors to easily access command
# generation.
env.AddMethod(get_generic_shell_command, "NinjaGetGenericShellCommand")
env.AddMethod(get_command, "NinjaGetCommand")
env.AddMethod(gen_get_response_file_command, "NinjaGenResponseFileProvider")
env.AddMethod(set_build_node_callback, "NinjaSetBuildNodeCallback")
# Provides a way for users to handle custom FunctionActions they
# want to translate to Ninja.
env[NINJA_CUSTOM_HANDLERS] = {}
env.AddMethod(register_custom_handler, "NinjaRegisterFunctionHandler")
# Provides a mechanism for inject custom Ninja rules which can
# then be mapped using NinjaRuleMapping.
env[NINJA_RULES] = {}
env.AddMethod(register_custom_rule, "NinjaRule")
# Provides a mechanism for inject custom Ninja pools which can
# be used by providing the NINJA_POOL="name" as an
# OverrideEnvironment variable in a builder call.
env[NINJA_POOLS] = {}
env.AddMethod(register_custom_pool, "NinjaPool")
# Add the ability to register custom NinjaRuleMappings for Command
# builders. We don't store this dictionary in the env to prevent
# accidental deletion of the CC/XXCOM mappings. You can still
# overwrite them if you really want to but you have to explicit
# about it this way. The reason is that if they were accidentally
# deleted you would get a very subtly incorrect Ninja file and
# might not catch it.
env.AddMethod(register_custom_rule_mapping, "NinjaRuleMapping")
# on windows we need to change the link action
ninja_hack_linkcom(env)
# Normally in SCons actions for the Program and *Library builders
# will return "${*COM}" as their pre-subst'd command line. However
# if a user in a SConscript overwrites those values via key access
# like env["LINKCOM"] = "$( $ICERUN $)" + env["LINKCOM"] then
# those actions no longer return the "bracketted" string and
# instead return something that looks more expanded. So to
# continue working even if a user has done this we map both the
# "bracketted" and semi-expanded versions.
def robust_rule_mapping(var, rule, tool):
provider = gen_get_response_file_command(env, rule, tool)
env.NinjaRuleMapping("${" + var + "}", provider)
env.NinjaRuleMapping(env.get(var, None), provider)
robust_rule_mapping("CCCOM", "CC", "$CC")
robust_rule_mapping("SHCCCOM", "CC", "$CC")
robust_rule_mapping("CXXCOM", "CXX", "$CXX")
robust_rule_mapping("SHCXXCOM", "CXX", "$CXX")
robust_rule_mapping("LINKCOM", "LINK", "$LINK")
robust_rule_mapping("SHLINKCOM", "LINK", "$SHLINK")
robust_rule_mapping("ARCOM", "AR", "$AR")
# Make SCons node walk faster by preventing unnecessary work
env.Decider("timestamp-match")
# Used to determine if a build generates a source file. Ninja
# requires that all generated sources are added as order_only
# dependencies to any builds that *might* use them.
# TODO: switch to using SCons to help determine this (Github Issue #3624)
env["NINJA_GENERATED_SOURCE_SUFFIXES"] = [".h", ".hpp"]
# Force ARCOM so use 's' flag on ar instead of separately running ranlib
ninja_hack_arcom(env)
if GetOption('disable_ninja'):
return env
SCons.Warnings.SConsWarning("Initializing ninja tool... this feature is experimental. SCons internals and all environments will be affected.")
# This is the point of no return, anything after this comment
# makes changes to SCons that are irreversible and incompatible
# with a normal SCons build. We return early if __NINJA_NO=1 has
# been given on the command line (i.e. by us in the generated
# ninja file) here to prevent these modifications from happening
# when we want SCons to do work. Everything before this was
# necessary to setup the builder and other functions so that the
# tool can be unconditionally used in the users's SCons files.
if not exists(env):
return
# Set a known variable that other tools can query so they can
# behave correctly during ninja generation.
env["GENERATING_NINJA"] = True
# These methods are no-op'd because they do not work during ninja
# generation, expected to do no work, or simply fail. All of which
# are slow in SCons. So we overwrite them with no logic.
SCons.Node.FS.File.make_ready = ninja_noop
SCons.Node.FS.File.prepare = ninja_noop
SCons.Node.FS.File.push_to_cache = ninja_noop
SCons.Executor.Executor.prepare = ninja_noop
SCons.Taskmaster.Task.prepare = ninja_noop
SCons.Node.FS.File.built = ninja_noop
SCons.Node.Node.visited = ninja_noop
# We make lstat a no-op because it is only used for SONAME
# symlinks which we're not producing.
SCons.Node.FS.LocalFS.lstat = ninja_noop
# This is a slow method that isn't memoized. We make it a noop
# since during our generation we will never use the results of
# this or change the results.
SCons.Node.FS.is_up_to_date = ninja_noop
# We overwrite stat and WhereIs with eternally memoized
# implementations. See the docstring of ninja_stat and
# ninja_whereis for detailed explanations.
SCons.Node.FS.LocalFS.stat = ninja_stat
SCons.Util.WhereIs = ninja_whereis
# Monkey patch get_csig and get_contents for some classes. It
# slows down the build significantly and we don't need contents or
# content signatures calculated when generating a ninja file since
# we're not doing any SCons caching or building.
SCons.Executor.Executor.get_contents = ninja_contents(
SCons.Executor.Executor.get_contents
)
SCons.Node.Alias.Alias.get_contents = ninja_contents(
SCons.Node.Alias.Alias.get_contents
)
SCons.Node.FS.File.get_contents = ninja_contents(SCons.Node.FS.File.get_contents)
SCons.Node.FS.File.get_csig = ninja_csig(SCons.Node.FS.File.get_csig)
SCons.Node.FS.Dir.get_csig = ninja_csig(SCons.Node.FS.Dir.get_csig)
SCons.Node.Alias.Alias.get_csig = ninja_csig(SCons.Node.Alias.Alias.get_csig)
# Ignore CHANGED_SOURCES and CHANGED_TARGETS. We don't want those
# to have effect in a generation pass because the generator
# shouldn't generate differently depending on the current local
# state. Without this, when generating on Windows, if you already
# had a foo.obj, you would omit foo.cpp from the response file. Do the same for UNCHANGED.
SCons.Executor.Executor._get_changed_sources = SCons.Executor.Executor._get_sources
SCons.Executor.Executor._get_changed_targets = SCons.Executor.Executor._get_targets
SCons.Executor.Executor._get_unchanged_sources = SCons.Executor.Executor._get_sources
SCons.Executor.Executor._get_unchanged_targets = SCons.Executor.Executor._get_targets
# Replace false action messages with nothing.
env["PRINT_CMD_LINE_FUNC"] = ninja_print_conf_log
# This reduces unnecessary subst_list calls to add the compiler to
# the implicit dependencies of targets. Since we encode full paths
# in our generated commands we do not need these slow subst calls
# as executing the command will fail if the file is not found
# where we expect it.
env["IMPLICIT_COMMAND_DEPENDENCIES"] = False
# This makes SCons more aggressively cache MD5 signatures in the
# SConsign file.
# TODO: WPD shouldn't this be set to 0?
env.SetOption("max_drift", 1)
# The Serial job class is SIGNIFICANTLY (almost twice as) faster
# than the Parallel job class for generating Ninja files. So we
# monkey the Jobs constructor to only use the Serial Job class.
SCons.Job.Jobs.__init__ = ninja_always_serial
ninja_syntax = importlib.import_module(".ninja_syntax", package='ninja')
if NINJA_STATE is None:
NINJA_STATE = NinjaState(env, ninja_file[0], ninja_syntax.Writer)
# TODO: this is hacking into scons, preferable if there were a less intrusive way
# We will subvert the normal builder execute to make sure all the ninja file is dependent
# on all targets generated from any builders
SCons_Builder_BuilderBase__execute = SCons.Builder.BuilderBase._execute
def NinjaBuilderExecute(self, env, target, source, overwarn={}, executor_kw={}):
# this ensures all environments in which a builder executes from will
# not create list actions for linking on windows
ninja_hack_linkcom(env)
targets = SCons_Builder_BuilderBase__execute(self, env, target, source, overwarn=overwarn, executor_kw=executor_kw)
if not SCons.Util.is_List(target):
target = [target]
for target in targets:
if target.check_attributes('ninja_file') is None and not target.is_conftest():
env.Depends(ninja_file, targets)
return targets
SCons.Builder.BuilderBase._execute = NinjaBuilderExecute
# Here we monkey patch the Task.execute method to not do a bunch of
# unnecessary work. If a build is a regular builder (i.e not a conftest and
# not our own Ninja builder) then we add it to the NINJA_STATE. Otherwise we
# build it like normal. This skips all of the caching work that this method
# would normally do since we aren't pulling any of these targets from the
# cache.
#
# In the future we may be able to use this to actually cache the build.ninja
# file once we have the upstream support for referencing SConscripts as File
# nodes.
def ninja_execute(self):
target = self.targets[0]
if target.get_env().get('NINJA_SKIP'):
return
if target.check_attributes('ninja_file') is None:
NINJA_STATE.add_build(target)
else:
target.build()
SCons.Taskmaster.Task.execute = ninja_execute
# Make needs_execute always return true instead of determining out of
# date-ness.
SCons.Script.Main.BuildTask.needs_execute = lambda x: True
# We will eventually need to overwrite TempFileMunge to make it
# handle persistent tempfiles or get an upstreamed change to add
# some configurability to it's behavior in regards to tempfiles.
#
# Set all three environment variables that Python's
# tempfile.mkstemp looks at as it behaves differently on different
# platforms and versions of Python.
# build_dir = env.subst("$NINJA_DIR")
# if build_dir == "":
# build_dir = "."
# os.environ["TMPDIR"] = env.Dir("{}/.response_files".format(build_dir)).get_abspath()
# os.environ["TEMP"] = os.environ["TMPDIR"]
# os.environ["TMP"] = os.environ["TMPDIR"]
# if not os.path.isdir(os.environ["TMPDIR"]):
# env.Execute(SCons.Defaults.Mkdir(os.environ["TMPDIR"]))
env['TEMPFILEDIR'] = "$NINJA_DIR/.response_files"
env["TEMPFILE"] = NinjaNoResponseFiles
| 43.015487
| 146
| 0.698915
|
b77f20e34fdc1d2904d297bb66a0886626e3e694
| 6,957
|
py
|
Python
|
tests/test_context.py
|
escamez/slackviews
|
0d5ea936c546a071eb6167cf9a8a8cf2fdaf922b
|
[
"MIT"
] | 2
|
2021-08-20T14:51:03.000Z
|
2021-08-23T17:57:35.000Z
|
tests/test_context.py
|
escamez/slackviews
|
0d5ea936c546a071eb6167cf9a8a8cf2fdaf922b
|
[
"MIT"
] | 2
|
2020-09-23T18:40:35.000Z
|
2021-12-14T09:46:31.000Z
|
tests/test_context.py
|
escamez/slackviews
|
0d5ea936c546a071eb6167cf9a8a8cf2fdaf922b
|
[
"MIT"
] | null | null | null |
"""
Class with nosetests for Context AbstractBlock in slack_view library
"""
from nose.tools import raises
from slackviews.view import Context, Image, MarkDown
__author__ = 'Agustin Escamez'
__email__ = 'aech22@gmail.com'
class TestContext:
def setup(self):
self.expected_block_id = 'any block id'
self.expected_image_alt_text = 'any alt text'
self.expected_image_url = 'any url'
self.expected_image_serialized = Image.Builder().alt_text(self.expected_image_alt_text) \
.image_url(self.expected_image_url).build().serialize()
self.context_instance_required = Context.Builder().element().Image().alt_text(self.expected_image_alt_text) \
.image_url(self.expected_image_url).up().build()
self.context_instance_all = Context.Builder().block_id_(self.expected_block_id).element() \
.Image().alt_text(self.expected_image_alt_text).image_url(self.expected_image_url).up().build()
self.expected_serialized_dict = {'type': 'context', 'block_id': self.expected_block_id,
'elements': [{'type': 'image', 'alt_text': self.expected_image_alt_text,
'image_url': self.expected_image_url}]}
self.expected_serialized_json = f'{{"type": "context", "block_id": "{self.expected_block_id}", ' \
f'"elements": [{{"type": "image", ' \
f'"alt_text": "{self.expected_image_alt_text}", ' \
f'"image_url": "{self.expected_image_url}"}}]}}'
def teardown(self):
Context.__all_slots__ = None
def test_should_context_builder_provide_a_valid_instance_with_required_values(self):
# GIVEN
expected_slots = ['_elements']
expected_all_slots = ['_block_id']
expected_all_slots.extend(expected_slots)
# WHEN
instance = self.context_instance_required
# THEN
assert isinstance(instance, Context)
assert hasattr(instance, '__all_slots__')
assert hasattr(instance, '__slots__')
for att in expected_slots:
assert att in getattr(instance, '__slots__')
for att in expected_all_slots:
assert att in getattr(instance, '__all_slots__')
assert isinstance(getattr(instance, '_elements'), list)
assert not hasattr(instance, '_block_id')
_image = getattr(instance, '_elements')[0]
assert isinstance(_image, Image)
assert getattr(_image, '_alt_text') == self.expected_image_alt_text
assert getattr(_image, '_image_url') == self.expected_image_url
assert _image.serialize() == self.expected_image_serialized
def test_should_context_builder_provide_a_valid_instance_with_all_values(self):
# GIVEN
instance = self.context_instance_all
# THEN
assert isinstance(getattr(instance, '_elements'), list)
_image = getattr(instance, '_elements')[0]
assert isinstance(_image, Image)
assert getattr(_image, '_alt_text') == self.expected_image_alt_text
assert getattr(_image, '_image_url') == self.expected_image_url
assert _image.serialize() == self.expected_image_serialized
assert getattr(instance, '_block_id') == self.expected_block_id
@raises(AttributeError)
def test_should_context_serialize_raise_assertionerror_if_missing_required_fields(self):
# WHEN
Context.Builder().block_id_('any').build().serialize()
def test_should_context_builder_provide_correct_element_type(self):
# GIVEN
isinstance_with_image = Context.Builder().element().Image().alt_text('any').image_url('any').up().build()
isinstance_with_text = Context.Builder().element().Text().text('any').up().build()
# THEN
assert isinstance(getattr(isinstance_with_image, '_elements'), list)
assert isinstance(getattr(isinstance_with_image, '_elements')[0], Image)
assert isinstance(getattr(isinstance_with_text, '_elements'), list)
assert isinstance(getattr(isinstance_with_text, '_elements')[0], MarkDown)
@raises(AssertionError)
def test_should_context_builder_raise_assertionerror_if_elements_is_not_a_list(self):
# GIVEN
_context = Context.Builder().build()
setattr(_context, '_elements', object())
# WHEN
_context.serialize()
@raises(AssertionError)
def test_should_context_builder_raise_assertionerror_if_element_is_not_an_allowed_element(self):
# GIVEN
_context = Context.Builder().build()
setattr(_context, '_elements', [object()])
# WHEN
_context.serialize()
@raises(AssertionError)
def test_should_context_serialize_raise_assertionerror_if_more_than_6_elements_are_provided(self):
# GIVEN
_context = Context.Builder().build()
setattr(_context, '_elements', [object() for i in range(6)])
# WHEN
_context.serialize()
@raises(AttributeError)
def test_should_actions_element_raise_attributeerror_if_trying_to_add_another_element_when_max_is_reached(self):
# GIVEN
_builder = Context.Builder()
for i in range(5):
_builder.element().Image().image_url(f'url_{i}').alt_text(f'alt_text_{i}')
# WHEN
_builder.element().Image().image_url('url_6').alt_text('alt_text_6')
def test_should_context_serialize_provide_correct_dict_and_json_data(self):
# GIVEN
instance = self.context_instance_all
# WHEN
serialized_dict = instance.serialize()
serialized_json = instance.serialize(as_json=True)
# THEN
assert serialized_dict == self.expected_serialized_dict
assert serialized_json == self.expected_serialized_json
def test_should_context_deserialize_provide_correct_instances_from_dict_and_json(self):
# GIVEN
serialized_dict = self.expected_serialized_dict
serialized_json = self.expected_serialized_json
# WHEN
instance_from_dict = Context.deserialize(serialized_dict)
instance_from_json = Context.deserialize(serialized_json, from_json=True)
# THEN
assert isinstance(instance_from_dict, Context)
assert isinstance(instance_from_json, Context)
for instance in (instance_from_dict, instance_from_json):
assert isinstance(getattr(instance, '_elements'), list)
_image = getattr(instance, '_elements')[0]
assert isinstance(_image, Image)
assert getattr(_image, '_alt_text') == self.expected_image_alt_text
assert getattr(_image, '_image_url') == self.expected_image_url
assert _image.serialize() == self.expected_image_serialized
assert getattr(instance, '_block_id') == self.expected_block_id
| 39.305085
| 117
| 0.672416
|
755ea7c04d7ac5b29052ad7ae61e5f6f2cd3b5ae
| 382
|
py
|
Python
|
tests/core_tests/test_scheduler.py
|
GaloisInc/csaf
|
553013fe507f77169ca303366c48176d44396b6a
|
[
"BSD-3-Clause"
] | 6
|
2021-08-17T23:31:13.000Z
|
2022-02-19T22:23:15.000Z
|
tests/core_tests/test_scheduler.py
|
GaloisInc/csaf
|
553013fe507f77169ca303366c48176d44396b6a
|
[
"BSD-3-Clause"
] | 29
|
2021-08-24T17:32:39.000Z
|
2022-02-28T16:28:35.000Z
|
tests/core_tests/test_scheduler.py
|
GaloisInc/csaf
|
553013fe507f77169ca303366c48176d44396b6a
|
[
"BSD-3-Clause"
] | 3
|
2021-09-15T14:20:30.000Z
|
2021-12-06T22:03:26.000Z
|
from csaf.core.scheduler import Scheduler
from csaf_f16.components import F16PlantComponent, F16GcasComponent
def test_scheduler():
a = F16PlantComponent()
b = F16GcasComponent()
a.check()
b.check()
s = Scheduler({"a": a, "b": b}, ["a", "b"])
assert len(s.get_schedule_tspan([1.0-1/30.0, 1.0])) == 1
assert len(s.get_schedule_tspan([0.0, 1e-08])) == 2
| 29.384615
| 67
| 0.651832
|
6f88456ee1031860d893bbf1dfcf4ff1dc450c63
| 6,728
|
py
|
Python
|
gennghttpxfun.py
|
codebytere/nghttp2
|
fa7a916ef3b6e518d7a65e6256a9ebab1bab83ce
|
[
"MIT"
] | null | null | null |
gennghttpxfun.py
|
codebytere/nghttp2
|
fa7a916ef3b6e518d7a65e6256a9ebab1bab83ce
|
[
"MIT"
] | null | null | null |
gennghttpxfun.py
|
codebytere/nghttp2
|
fa7a916ef3b6e518d7a65e6256a9ebab1bab83ce
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python3
from gentokenlookup import gentokenlookup
OPTIONS = [
"private-key-file",
"private-key-passwd-file",
"certificate-file",
"dh-param-file",
"subcert",
"backend",
"frontend",
"workers",
"http2-max-concurrent-streams",
"log-level",
"daemon",
"http2-proxy",
"http2-bridge",
"client-proxy",
"add-x-forwarded-for",
"strip-incoming-x-forwarded-for",
"no-via",
"frontend-http2-read-timeout",
"frontend-read-timeout",
"frontend-write-timeout",
"backend-read-timeout",
"backend-write-timeout",
"stream-read-timeout",
"stream-write-timeout",
"accesslog-file",
"accesslog-syslog",
"accesslog-format",
"errorlog-file",
"errorlog-syslog",
"backend-keep-alive-timeout",
"frontend-http2-window-bits",
"backend-http2-window-bits",
"frontend-http2-connection-window-bits",
"backend-http2-connection-window-bits",
"frontend-no-tls",
"backend-no-tls",
"backend-tls-sni-field",
"pid-file",
"user",
"syslog-facility",
"backlog",
"ciphers",
"client",
"insecure",
"cacert",
"backend-ipv4",
"backend-ipv6",
"backend-http-proxy-uri",
"read-rate",
"read-burst",
"write-rate",
"write-burst",
"worker-read-rate",
"worker-read-burst",
"worker-write-rate",
"worker-write-burst",
"npn-list",
"tls-proto-list",
"verify-client",
"verify-client-cacert",
"client-private-key-file",
"client-cert-file",
"frontend-http2-dump-request-header",
"frontend-http2-dump-response-header",
"http2-no-cookie-crumbling",
"frontend-frame-debug",
"padding",
"altsvc",
"add-request-header",
"add-response-header",
"worker-frontend-connections",
"no-location-rewrite",
"no-host-rewrite",
"backend-http1-connections-per-host",
"backend-http1-connections-per-frontend",
"listener-disable-timeout",
"tls-ticket-key-file",
"rlimit-nofile",
"backend-request-buffer",
"backend-response-buffer",
"no-server-push",
"backend-http2-connections-per-worker",
"fetch-ocsp-response-file",
"ocsp-update-interval",
"no-ocsp",
"include",
"tls-ticket-key-cipher",
"host-rewrite",
"tls-session-cache-memcached",
"tls-session-cache-memcached-tls",
"tls-ticket-key-memcached",
"tls-ticket-key-memcached-interval",
"tls-ticket-key-memcached-max-retry",
"tls-ticket-key-memcached-max-fail",
"mruby-file",
"accept-proxy-protocol",
"conf",
"fastopen",
"tls-dyn-rec-warmup-threshold",
"tls-dyn-rec-idle-timeout",
"add-forwarded",
"strip-incoming-forwarded",
"forwarded-by",
"forwarded-for",
"response-header-field-buffer",
"max-response-header-fields",
"request-header-field-buffer",
"max-request-header-fields",
"header-field-buffer",
"max-header-fields",
"no-http2-cipher-block-list",
"no-http2-cipher-black-list",
"backend-http1-tls",
"tls-session-cache-memcached-cert-file",
"tls-session-cache-memcached-private-key-file",
"tls-session-cache-memcached-address-family",
"tls-ticket-key-memcached-tls",
"tls-ticket-key-memcached-cert-file",
"tls-ticket-key-memcached-private-key-file",
"tls-ticket-key-memcached-address-family",
"backend-address-family",
"frontend-http2-max-concurrent-streams",
"backend-http2-max-concurrent-streams",
"backend-connections-per-frontend",
"backend-tls",
"backend-connections-per-host",
"error-page",
"no-kqueue",
"frontend-http2-settings-timeout",
"backend-http2-settings-timeout",
"api-max-request-body",
"backend-max-backoff",
"server-name",
"no-server-rewrite",
"frontend-http2-optimize-write-buffer-size",
"frontend-http2-optimize-window-size",
"frontend-http2-window-size",
"frontend-http2-connection-window-size",
"backend-http2-window-size",
"backend-http2-connection-window-size",
"frontend-http2-encoder-dynamic-table-size",
"frontend-http2-decoder-dynamic-table-size",
"backend-http2-encoder-dynamic-table-size",
"backend-http2-decoder-dynamic-table-size",
"ecdh-curves",
"tls-sct-dir",
"backend-connect-timeout",
"dns-cache-timeout",
"dns-lookup-timeout",
"dns-max-try",
"frontend-keep-alive-timeout",
"psk-secrets",
"client-psk-secrets",
"client-no-http2-cipher-block-list",
"client-no-http2-cipher-black-list",
"client-ciphers",
"accesslog-write-early",
"tls-min-proto-version",
"tls-max-proto-version",
"redirect-https-port",
"frontend-max-requests",
"single-thread",
"single-process",
"no-add-x-forwarded-proto",
"no-strip-incoming-x-forwarded-proto",
"ocsp-startup",
"no-verify-ocsp",
"verify-client-tolerate-expired",
"ignore-per-pattern-mruby-error",
"tls-no-postpone-early-data",
"tls-max-early-data",
"tls13-ciphers",
"tls13-client-ciphers",
"no-strip-incoming-early-data",
"quic-bpf-program-file",
"no-quic-bpf",
"http2-altsvc",
"frontend-http3-read-timeout",
"frontend-quic-idle-timeout",
"frontend-quic-debug-log",
"frontend-http3-window-size",
"frontend-http3-connection-window-size",
"frontend-http3-max-window-size",
"frontend-http3-max-connection-window-size",
"frontend-http3-max-concurrent-streams",
"frontend-quic-early-data",
"frontend-quic-qlog-dir",
"frontend-quic-require-token",
"frontend-quic-congestion-controller",
"frontend-quic-server-id",
"frontend-quic-secret-file",
"rlimit-memlock",
"max-worker-processes",
"worker-process-grace-shutdown-period",
"frontend-quic-initial-rtt",
]
LOGVARS = [
"remote_addr",
"time_local",
"time_iso8601",
"request",
"status",
"body_bytes_sent",
"remote_port",
"server_port",
"request_time",
"pid",
"alpn",
"ssl_cipher",
"ssl_protocol",
"ssl_session_id",
"ssl_session_reused",
"tls_cipher",
"tls_protocol",
"tls_session_id",
"tls_session_reused",
"tls_sni",
"tls_client_fingerprint_sha256",
"tls_client_fingerprint_sha1",
"tls_client_subject_name",
"tls_client_issuer_name",
"tls_client_serial",
"backend_host",
"backend_port",
"method",
"path",
"path_without_query",
"protocol_version",
]
if __name__ == '__main__':
gentokenlookup(OPTIONS, 'SHRPX_OPTID_', value_type='char', comp_fun='util::strieq_l')
gentokenlookup(LOGVARS, 'LogFragmentType::', value_type='char', comp_fun='util::strieq_l', return_type='LogFragmentType', fail_value='LogFragmentType::NONE')
| 28.033333
| 161
| 0.646849
|
602460c6d694b93979d2cb88251f2d49bdb84f5c
| 2,623
|
py
|
Python
|
tests/test_core.py
|
TieWei/molecule
|
67372aa5db84b1a14f6d75bb60b05aa54244f57f
|
[
"MIT"
] | 1
|
2016-05-18T19:05:25.000Z
|
2016-05-18T19:05:25.000Z
|
tests/test_core.py
|
TieWei/molecule
|
67372aa5db84b1a14f6d75bb60b05aa54244f57f
|
[
"MIT"
] | null | null | null |
tests/test_core.py
|
TieWei/molecule
|
67372aa5db84b1a14f6d75bb60b05aa54244f57f
|
[
"MIT"
] | null | null | null |
# Copyright (c) 2015 Cisco Systems
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import testtools
from molecule.core import Molecule
class TestCore(testtools.TestCase):
def setUp(self):
super(TestCore, self).setUp()
self._molecule = Molecule(None)
def test_parse_provisioning_output_failure_00(self):
failed_output = """
PLAY RECAP ********************************************************************
vagrant-01-ubuntu : ok=36 changed=29 unreachable=0 failed=0
"""
res, changed_tasks = self._molecule._parse_provisioning_output(failed_output)
self.assertFalse(res)
def test_parse_provisioning_output_failure_01(self):
failed_output = """
PLAY RECAP ********************************************************************
NI: cisco.common | Non idempotent task for testing
common-01-rhel-7 : ok=18 changed=14 unreachable=0 failed=0
"""
res, changed_tasks = self._molecule._parse_provisioning_output(failed_output)
self.assertFalse(res)
self.assertEqual(1, len(changed_tasks))
def test_parse_provisioning_output_success_00(self):
success_output = """
PLAY RECAP ********************************************************************
vagrant-01-ubuntu : ok=36 changed=0 unreachable=0 failed=0
"""
res, changed_tasks = self._molecule._parse_provisioning_output(success_output)
self.assertTrue(res)
self.assertEqual([], changed_tasks)
| 41.634921
| 87
| 0.645444
|
c179562d3b2e090ed6e9336c785a3de62d24ea7b
| 11,581
|
py
|
Python
|
tests/unit/test_solvers/test_processed_symbolic_variable.py
|
NunoEdgarGFlowHub/PyBaMM
|
4e4e1ab8c488b0c0a6efdb9934c5ac59e947a190
|
[
"BSD-3-Clause"
] | 1
|
2021-03-06T15:10:34.000Z
|
2021-03-06T15:10:34.000Z
|
tests/unit/test_solvers/test_processed_symbolic_variable.py
|
NunoEdgarGFlowHub/PyBaMM
|
4e4e1ab8c488b0c0a6efdb9934c5ac59e947a190
|
[
"BSD-3-Clause"
] | null | null | null |
tests/unit/test_solvers/test_processed_symbolic_variable.py
|
NunoEdgarGFlowHub/PyBaMM
|
4e4e1ab8c488b0c0a6efdb9934c5ac59e947a190
|
[
"BSD-3-Clause"
] | null | null | null |
#
# Tests for the Processed Variable class
#
import pybamm
import casadi
import numpy as np
import unittest
import tests
class TestProcessedSymbolicVariable(unittest.TestCase):
def test_processed_variable_0D(self):
# without inputs
y = pybamm.StateVector(slice(0, 1))
var = 2 * y
var.mesh = None
t_sol = np.linspace(0, 1)
y_sol = np.array([np.linspace(0, 5)])
solution = pybamm.Solution(t_sol, y_sol)
processed_var = pybamm.ProcessedSymbolicVariable(var, solution)
np.testing.assert_array_equal(processed_var.value(), 2 * y_sol)
# No sensitivity as variable is not symbolic
with self.assertRaisesRegex(ValueError, "Variable is not symbolic"):
processed_var.sensitivity()
def test_processed_variable_0D_with_inputs(self):
# with symbolic inputs
y = pybamm.StateVector(slice(0, 1))
p = pybamm.InputParameter("p")
q = pybamm.InputParameter("q")
var = p * y + q
var.mesh = None
t_sol = np.linspace(0, 1)
y_sol = np.array([np.linspace(0, 5)])
solution = pybamm.Solution(t_sol, y_sol)
solution.inputs = {"p": casadi.MX.sym("p"), "q": casadi.MX.sym("q")}
processed_var = pybamm.ProcessedSymbolicVariable(var, solution)
np.testing.assert_array_equal(
processed_var.value({"p": 3, "q": 4}).full(), 3 * y_sol + 4
)
np.testing.assert_array_equal(
processed_var.sensitivity({"p": 3, "q": 4}).full(),
np.c_[y_sol.T, np.ones_like(y_sol).T],
)
# via value_and_sensitivity
val, sens = processed_var.value_and_sensitivity({"p": 3, "q": 4})
np.testing.assert_array_equal(val.full(), 3 * y_sol + 4)
np.testing.assert_array_equal(
sens.full(), np.c_[y_sol.T, np.ones_like(y_sol).T]
)
# Test bad inputs
with self.assertRaisesRegex(TypeError, "inputs should be 'dict'"):
processed_var.value(1)
with self.assertRaisesRegex(KeyError, "Inconsistent input keys"):
processed_var.value({"not p": 3})
def test_processed_variable_0D_some_inputs(self):
# with some symbolic inputs and some non-symbolic inputs
y = pybamm.StateVector(slice(0, 1))
p = pybamm.InputParameter("p")
q = pybamm.InputParameter("q")
var = p * y - q
var.mesh = None
t_sol = np.linspace(0, 1)
y_sol = np.array([np.linspace(0, 5)])
solution = pybamm.Solution(t_sol, y_sol)
solution.inputs = {"p": casadi.MX.sym("p"), "q": 2}
processed_var = pybamm.ProcessedSymbolicVariable(var, solution)
np.testing.assert_array_equal(
processed_var.value({"p": 3}).full(), 3 * y_sol - 2
)
np.testing.assert_array_equal(
processed_var.sensitivity({"p": 3}).full(), y_sol.T
)
def test_processed_variable_1D(self):
var = pybamm.Variable("var", domain=["negative electrode", "separator"])
x = pybamm.SpatialVariable("x", domain=["negative electrode", "separator"])
eqn = var + x
# On nodes
disc = tests.get_discretisation_for_testing()
disc.set_variable_slices([var])
x_sol = disc.process_symbol(x).entries[:, 0]
eqn_sol = disc.process_symbol(eqn)
# With scalar t_sol
t_sol = [0]
y_sol = np.ones_like(x_sol)[:, np.newaxis] * 5
sol = pybamm.Solution(t_sol, y_sol)
processed_eqn = pybamm.ProcessedSymbolicVariable(eqn_sol, sol)
np.testing.assert_array_equal(
processed_eqn.value(), y_sol + x_sol[:, np.newaxis]
)
# With vector t_sol
t_sol = np.linspace(0, 1)
y_sol = np.ones_like(x_sol)[:, np.newaxis] * np.linspace(0, 5)
sol = pybamm.Solution(t_sol, y_sol)
processed_eqn = pybamm.ProcessedSymbolicVariable(eqn_sol, sol)
np.testing.assert_array_equal(
processed_eqn.value(), (y_sol + x_sol[:, np.newaxis]).T.reshape(-1, 1)
)
def test_processed_variable_1D_with_scalar_inputs(self):
var = pybamm.Variable("var", domain=["negative electrode", "separator"])
x = pybamm.SpatialVariable("x", domain=["negative electrode", "separator"])
p = pybamm.InputParameter("p")
q = pybamm.InputParameter("q")
eqn = var * p + 2 * q
# On nodes
disc = tests.get_discretisation_for_testing()
disc.set_variable_slices([var])
x_sol = disc.process_symbol(x).entries[:, 0]
eqn_sol = disc.process_symbol(eqn)
# Scalar t
t_sol = [0]
y_sol = np.ones_like(x_sol)[:, np.newaxis] * 5
sol = pybamm.Solution(t_sol, y_sol)
sol.inputs = {"p": casadi.MX.sym("p"), "q": casadi.MX.sym("q")}
processed_eqn = pybamm.ProcessedSymbolicVariable(eqn_sol, sol)
# Test values
np.testing.assert_array_equal(
processed_eqn.value({"p": 27, "q": -42}), 27 * y_sol - 84,
)
# Test sensitivities
np.testing.assert_array_equal(
processed_eqn.sensitivity({"p": 27, "q": -84}),
np.c_[y_sol, 2 * np.ones_like(y_sol)],
)
################################################################################
# Vector t
t_sol = np.linspace(0, 1)
y_sol = np.ones_like(x_sol)[:, np.newaxis] * np.linspace(0, 5)
sol = pybamm.Solution(t_sol, y_sol)
sol.inputs = {"p": casadi.MX.sym("p"), "q": casadi.MX.sym("q")}
processed_eqn = pybamm.ProcessedSymbolicVariable(eqn_sol, sol)
# Test values
np.testing.assert_array_equal(
processed_eqn.value({"p": 27, "q": -42}),
(27 * y_sol - 84).T.reshape(-1, 1),
)
# Test sensitivities
np.testing.assert_array_equal(
processed_eqn.sensitivity({"p": 27, "q": -42}),
np.c_[y_sol.T.flatten(), 2 * np.ones_like(y_sol.T.flatten())],
)
def test_processed_variable_1D_with_vector_inputs(self):
var = pybamm.Variable("var", domain=["negative electrode", "separator"])
x = pybamm.SpatialVariable("x", domain=["negative electrode", "separator"])
p = pybamm.InputParameter("p", domain=["negative electrode", "separator"])
p.set_expected_size(65)
q = pybamm.InputParameter("q")
eqn = (var * p) ** 2 + 2 * q
# On nodes
disc = tests.get_discretisation_for_testing()
disc.set_variable_slices([var])
x_sol = disc.process_symbol(x).entries[:, 0]
n = x_sol.size
eqn_sol = disc.process_symbol(eqn)
# Scalar t
t_sol = [0]
y_sol = np.ones_like(x_sol)[:, np.newaxis] * 5
sol = pybamm.Solution(t_sol, y_sol)
sol.inputs = {"p": casadi.MX.sym("p", n), "q": casadi.MX.sym("q")}
processed_eqn = pybamm.ProcessedSymbolicVariable(eqn_sol, sol)
# Test values - constant p
np.testing.assert_array_equal(
processed_eqn.value({"p": 27 * np.ones(n), "q": -42}),
(27 * y_sol) ** 2 - 84,
)
# Test values - varying p
p = np.linspace(0, 1, n)
np.testing.assert_array_equal(
processed_eqn.value({"p": p, "q": 3}), (p[:, np.newaxis] * y_sol) ** 2 + 6,
)
# Test sensitivities - constant p
np.testing.assert_array_equal(
processed_eqn.sensitivity({"p": 2 * np.ones(n), "q": -84}),
np.c_[100 * np.eye(y_sol.size), 2 * np.ones(n)],
)
# Test sensitivities - varying p
# d/dy((py)**2) = (2*p*y) * y
np.testing.assert_array_equal(
processed_eqn.sensitivity({"p": p, "q": -84}),
np.c_[
np.diag((2 * p[:, np.newaxis] * y_sol ** 2).flatten()), 2 * np.ones(n)
],
)
# Bad shape
with self.assertRaisesRegex(
ValueError, "Wrong shape for input 'p': expected 65, actual 5"
):
processed_eqn.value({"p": casadi.MX.sym("p", 5), "q": 1})
def test_1D_different_domains(self):
# Negative electrode domain
var = pybamm.Variable("var", domain=["negative electrode"])
x = pybamm.SpatialVariable("x", domain=["negative electrode"])
disc = tests.get_discretisation_for_testing()
disc.set_variable_slices([var])
x_sol = disc.process_symbol(x).entries[:, 0]
var_sol = disc.process_symbol(var)
t_sol = [0]
y_sol = np.ones_like(x_sol)[:, np.newaxis] * 5
sol = pybamm.Solution(t_sol, y_sol)
pybamm.ProcessedSymbolicVariable(var_sol, sol)
# Particle domain
var = pybamm.Variable("var", domain=["negative particle"])
r = pybamm.SpatialVariable("r", domain=["negative particle"])
disc = tests.get_discretisation_for_testing()
disc.set_variable_slices([var])
r_sol = disc.process_symbol(r).entries[:, 0]
var_sol = disc.process_symbol(var)
t_sol = [0]
y_sol = np.ones_like(r_sol)[:, np.newaxis] * 5
sol = pybamm.Solution(t_sol, y_sol)
pybamm.ProcessedSymbolicVariable(var_sol, sol)
# Current collector domain
var = pybamm.Variable("var", domain=["current collector"])
z = pybamm.SpatialVariable("z", domain=["current collector"])
disc = tests.get_1p1d_discretisation_for_testing()
disc.set_variable_slices([var])
z_sol = disc.process_symbol(z).entries[:, 0]
var_sol = disc.process_symbol(var)
t_sol = [0]
y_sol = np.ones_like(z_sol)[:, np.newaxis] * 5
sol = pybamm.Solution(t_sol, y_sol)
pybamm.ProcessedSymbolicVariable(var_sol, sol)
# Other domain
var = pybamm.Variable("var", domain=["line"])
x = pybamm.SpatialVariable("x", domain=["line"])
geometry = pybamm.Geometry(
{"line": {x: {"min": pybamm.Scalar(0), "max": pybamm.Scalar(1)}}}
)
submesh_types = {"line": pybamm.MeshGenerator(pybamm.Uniform1DSubMesh)}
var_pts = {x: 10}
mesh = pybamm.Mesh(geometry, submesh_types, var_pts)
disc = pybamm.Discretisation(mesh, {"line": pybamm.FiniteVolume()})
disc.set_variable_slices([var])
x_sol = disc.process_symbol(x).entries[:, 0]
var_sol = disc.process_symbol(var)
t_sol = [0]
y_sol = np.ones_like(x_sol)[:, np.newaxis] * 5
sol = pybamm.Solution(t_sol, y_sol)
pybamm.ProcessedSymbolicVariable(var_sol, sol)
# 2D fails
var = pybamm.Variable(
"var",
domain=["negative particle"],
auxiliary_domains={"secondary": "negative electrode"},
)
r = pybamm.SpatialVariable(
"r",
domain=["negative particle"],
auxiliary_domains={"secondary": "negative electrode"},
)
disc = tests.get_p2d_discretisation_for_testing()
disc.set_variable_slices([var])
r_sol = disc.process_symbol(r).entries[:, 0]
var_sol = disc.process_symbol(var)
t_sol = [0]
y_sol = np.ones_like(r_sol)[:, np.newaxis] * 5
sol = pybamm.Solution(t_sol, y_sol)
with self.assertRaisesRegex(NotImplementedError, "Shape not recognized"):
pybamm.ProcessedSymbolicVariable(var_sol, sol)
if __name__ == "__main__":
print("Add -v for more debug output")
import sys
if "-v" in sys.argv:
debug = True
pybamm.settings.debug_mode = True
unittest.main()
| 37
| 88
| 0.585269
|
c5f4e03338e4640524b6b8f26e26647c280f6315
| 561,555
|
py
|
Python
|
tests/examples/minlplib/portfol_robust100_09.py
|
ouyang-w-19/decogo
|
52546480e49776251d4d27856e18a46f40c824a1
|
[
"MIT"
] | 2
|
2021-07-03T13:19:10.000Z
|
2022-02-06T10:48:13.000Z
|
tests/examples/minlplib/portfol_robust100_09.py
|
ouyang-w-19/decogo
|
52546480e49776251d4d27856e18a46f40c824a1
|
[
"MIT"
] | 1
|
2021-07-04T14:52:14.000Z
|
2021-07-15T10:17:11.000Z
|
tests/examples/minlplib/portfol_robust100_09.py
|
ouyang-w-19/decogo
|
52546480e49776251d4d27856e18a46f40c824a1
|
[
"MIT"
] | null | null | null |
# MINLP written by GAMS Convert at 04/21/18 13:53:49
#
# Equation counts
# Total E G L N X C B
# 307 203 0 104 0 0 0 0
#
# Variable counts
# x b i s1s s2s sc si
# Total cont binary integer sos1 sos2 scont sint
# 404 303 101 0 0 0 0 0
# FX 0 0 0 0 0 0 0 0
#
# Nonzero counts
# Total const NL DLL
# 20908 20707 201 0
#
# Reformulation has removed 1 variable and 1 equation
from pyomo.environ import *
model = m = ConcreteModel()
m.x2 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x3 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x4 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x5 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x6 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x7 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x8 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x9 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x10 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x11 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x12 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x13 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x14 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x15 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x16 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x17 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x18 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x19 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x20 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x21 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x22 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x23 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x24 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x25 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x26 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x27 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x28 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x29 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x30 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x31 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x32 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x33 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x34 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x35 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x36 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x37 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x38 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x39 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x40 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x41 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x42 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x43 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x44 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x45 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x46 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x47 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x48 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x49 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x50 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x51 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x52 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x53 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x54 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x55 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x56 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x57 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x58 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x59 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x60 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x61 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x62 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x63 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x64 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x65 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x66 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x67 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x68 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x69 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x70 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x71 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x72 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x73 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x74 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x75 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x76 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x77 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x78 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x79 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x80 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x81 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x82 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x83 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x84 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x85 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x86 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x87 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x88 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x89 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x90 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x91 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x92 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x93 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x94 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x95 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x96 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x97 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x98 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x99 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x100 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x101 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x102 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x103 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x104 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x105 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x106 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x107 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x108 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x109 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x110 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x111 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x112 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x113 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x114 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x115 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x116 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x117 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x118 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x119 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x120 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x121 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x122 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x123 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x124 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x125 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x126 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x127 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x128 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x129 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x130 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x131 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x132 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x133 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x134 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x135 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x136 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x137 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x138 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x139 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x140 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x141 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x142 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x143 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x144 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x145 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x146 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x147 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x148 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x149 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x150 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x151 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x152 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x153 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x154 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x155 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x156 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x157 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x158 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x159 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x160 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x161 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x162 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x163 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x164 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x165 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x166 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x167 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x168 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x169 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x170 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x171 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x172 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x173 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x174 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x175 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x176 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x177 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x178 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x179 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x180 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x181 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x182 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x183 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x184 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x185 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x186 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x187 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x188 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x189 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x190 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x191 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x192 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x193 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x194 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x195 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x196 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x197 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x198 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x199 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x200 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x201 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x202 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x203 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x204 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x205 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x206 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x207 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x208 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x209 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x210 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x211 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x212 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x213 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x214 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x215 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x216 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x217 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x218 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x219 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x220 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x221 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x222 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x223 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x224 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x225 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x226 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x227 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x228 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x229 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x230 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x231 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x232 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x233 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x234 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x235 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x236 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x237 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x238 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x239 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x240 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x241 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x242 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x243 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x244 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x245 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x246 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x247 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x248 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x249 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x250 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x251 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x252 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x253 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x254 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x255 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x256 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x257 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x258 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x259 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x260 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x261 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x262 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x263 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x264 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x265 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x266 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x267 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x268 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x269 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x270 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x271 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x272 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x273 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x274 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x275 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x276 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x277 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x278 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x279 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x280 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x281 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x282 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x283 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x284 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x285 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x286 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x287 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x288 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x289 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x290 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x291 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x292 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x293 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x294 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x295 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x296 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x297 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x298 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x299 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x300 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x301 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x302 = Var(within=Reals,bounds=(0,1),initialize=0)
m.x303 = Var(within=Reals,bounds=(0,1),initialize=0)
m.b304 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b305 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b306 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b307 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b308 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b309 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b310 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b311 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b312 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b313 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b314 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b315 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b316 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b317 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b318 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b319 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b320 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b321 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b322 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b323 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b324 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b325 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b326 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b327 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b328 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b329 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b330 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b331 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b332 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b333 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b334 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b335 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b336 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b337 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b338 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b339 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b340 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b341 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b342 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b343 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b344 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b345 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b346 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b347 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b348 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b349 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b350 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b351 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b352 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b353 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b354 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b355 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b356 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b357 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b358 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b359 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b360 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b361 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b362 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b363 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b364 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b365 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b366 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b367 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b368 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b369 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b370 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b371 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b372 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b373 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b374 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b375 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b376 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b377 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b378 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b379 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b380 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b381 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b382 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b383 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b384 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b385 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b386 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b387 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b388 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b389 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b390 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b391 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b392 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b393 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b394 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b395 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b396 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b397 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b398 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b399 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b400 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b401 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b402 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b403 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b404 = Var(within=Binary,bounds=(0,1),initialize=0)
m.obj = Objective(expr= - m.x203, sense=minimize)
m.c2 = Constraint(expr=m.x2*m.x2 + m.x3*m.x3 + m.x4*m.x4 + m.x5*m.x5 + m.x6*m.x6 + m.x7*m.x7 + m.x8*m.x8 + m.x9*m.x9 +
m.x10*m.x10 + m.x11*m.x11 + m.x12*m.x12 + m.x13*m.x13 + m.x14*m.x14 + m.x15*m.x15 + m.x16*m.x16
+ m.x17*m.x17 + m.x18*m.x18 + m.x19*m.x19 + m.x20*m.x20 + m.x21*m.x21 + m.x22*m.x22 + m.x23*
m.x23 + m.x24*m.x24 + m.x25*m.x25 + m.x26*m.x26 + m.x27*m.x27 + m.x28*m.x28 + m.x29*m.x29 + m.x30
*m.x30 + m.x31*m.x31 + m.x32*m.x32 + m.x33*m.x33 + m.x34*m.x34 + m.x35*m.x35 + m.x36*m.x36 +
m.x37*m.x37 + m.x38*m.x38 + m.x39*m.x39 + m.x40*m.x40 + m.x41*m.x41 + m.x42*m.x42 + m.x43*m.x43
+ m.x44*m.x44 + m.x45*m.x45 + m.x46*m.x46 + m.x47*m.x47 + m.x48*m.x48 + m.x49*m.x49 + m.x50*
m.x50 + m.x51*m.x51 + m.x52*m.x52 + m.x53*m.x53 + m.x54*m.x54 + m.x55*m.x55 + m.x56*m.x56 + m.x57
*m.x57 + m.x58*m.x58 + m.x59*m.x59 + m.x60*m.x60 + m.x61*m.x61 + m.x62*m.x62 + m.x63*m.x63 +
m.x64*m.x64 + m.x65*m.x65 + m.x66*m.x66 + m.x67*m.x67 + m.x68*m.x68 + m.x69*m.x69 + m.x70*m.x70
+ m.x71*m.x71 + m.x72*m.x72 + m.x73*m.x73 + m.x74*m.x74 + m.x75*m.x75 + m.x76*m.x76 + m.x77*
m.x77 + m.x78*m.x78 + m.x79*m.x79 + m.x80*m.x80 + m.x81*m.x81 + m.x82*m.x82 + m.x83*m.x83 + m.x84
*m.x84 + m.x85*m.x85 + m.x86*m.x86 + m.x87*m.x87 + m.x88*m.x88 + m.x89*m.x89 + m.x90*m.x90 +
m.x91*m.x91 + m.x92*m.x92 + m.x93*m.x93 + m.x94*m.x94 + m.x95*m.x95 + m.x96*m.x96 + m.x97*m.x97
+ m.x98*m.x98 + m.x99*m.x99 + m.x100*m.x100 + m.x101*m.x101 <= 0.04)
m.c3 = Constraint(expr=m.x102*m.x102 + m.x103*m.x103 + m.x104*m.x104 + m.x105*m.x105 + m.x106*m.x106 + m.x107*m.x107 +
m.x108*m.x108 + m.x109*m.x109 + m.x110*m.x110 + m.x111*m.x111 + m.x112*m.x112 + m.x113*m.x113 +
m.x114*m.x114 + m.x115*m.x115 + m.x116*m.x116 + m.x117*m.x117 + m.x118*m.x118 + m.x119*m.x119 +
m.x120*m.x120 + m.x121*m.x121 + m.x122*m.x122 + m.x123*m.x123 + m.x124*m.x124 + m.x125*m.x125 +
m.x126*m.x126 + m.x127*m.x127 + m.x128*m.x128 + m.x129*m.x129 + m.x130*m.x130 + m.x131*m.x131 +
m.x132*m.x132 + m.x133*m.x133 + m.x134*m.x134 + m.x135*m.x135 + m.x136*m.x136 + m.x137*m.x137 +
m.x138*m.x138 + m.x139*m.x139 + m.x140*m.x140 + m.x141*m.x141 + m.x142*m.x142 + m.x143*m.x143 +
m.x144*m.x144 + m.x145*m.x145 + m.x146*m.x146 + m.x147*m.x147 + m.x148*m.x148 + m.x149*m.x149 +
m.x150*m.x150 + m.x151*m.x151 + m.x152*m.x152 + m.x153*m.x153 + m.x154*m.x154 + m.x155*m.x155 +
m.x156*m.x156 + m.x157*m.x157 + m.x158*m.x158 + m.x159*m.x159 + m.x160*m.x160 + m.x161*m.x161 +
m.x162*m.x162 + m.x163*m.x163 + m.x164*m.x164 + m.x165*m.x165 + m.x166*m.x166 + m.x167*m.x167 +
m.x168*m.x168 + m.x169*m.x169 + m.x170*m.x170 + m.x171*m.x171 + m.x172*m.x172 + m.x173*m.x173 +
m.x174*m.x174 + m.x175*m.x175 + m.x176*m.x176 + m.x177*m.x177 + m.x178*m.x178 + m.x179*m.x179 +
m.x180*m.x180 + m.x181*m.x181 + m.x182*m.x182 + m.x183*m.x183 + m.x184*m.x184 + m.x185*m.x185 +
m.x186*m.x186 + m.x187*m.x187 + m.x188*m.x188 + m.x189*m.x189 + m.x190*m.x190 + m.x191*m.x191 +
m.x192*m.x192 + m.x193*m.x193 + m.x194*m.x194 + m.x195*m.x195 + m.x196*m.x196 + m.x197*m.x197 +
m.x198*m.x198 + m.x199*m.x199 + m.x200*m.x200 + m.x201*m.x201 - m.x202*m.x202 <= 0)
m.c4 = Constraint(expr= m.x204 - m.b304 <= 0)
m.c5 = Constraint(expr= m.x205 - m.b305 <= 0)
m.c6 = Constraint(expr= m.x206 - m.b306 <= 0)
m.c7 = Constraint(expr= m.x207 - m.b307 <= 0)
m.c8 = Constraint(expr= m.x208 - m.b308 <= 0)
m.c9 = Constraint(expr= m.x209 - m.b309 <= 0)
m.c10 = Constraint(expr= m.x210 - m.b310 <= 0)
m.c11 = Constraint(expr= m.x211 - m.b311 <= 0)
m.c12 = Constraint(expr= m.x212 - m.b312 <= 0)
m.c13 = Constraint(expr= m.x213 - m.b313 <= 0)
m.c14 = Constraint(expr= m.x214 - m.b314 <= 0)
m.c15 = Constraint(expr= m.x215 - m.b315 <= 0)
m.c16 = Constraint(expr= m.x216 - m.b316 <= 0)
m.c17 = Constraint(expr= m.x217 - m.b317 <= 0)
m.c18 = Constraint(expr= m.x218 - m.b318 <= 0)
m.c19 = Constraint(expr= m.x219 - m.b319 <= 0)
m.c20 = Constraint(expr= m.x220 - m.b320 <= 0)
m.c21 = Constraint(expr= m.x221 - m.b321 <= 0)
m.c22 = Constraint(expr= m.x222 - m.b322 <= 0)
m.c23 = Constraint(expr= m.x223 - m.b323 <= 0)
m.c24 = Constraint(expr= m.x224 - m.b324 <= 0)
m.c25 = Constraint(expr= m.x225 - m.b325 <= 0)
m.c26 = Constraint(expr= m.x226 - m.b326 <= 0)
m.c27 = Constraint(expr= m.x227 - m.b327 <= 0)
m.c28 = Constraint(expr= m.x228 - m.b328 <= 0)
m.c29 = Constraint(expr= m.x229 - m.b329 <= 0)
m.c30 = Constraint(expr= m.x230 - m.b330 <= 0)
m.c31 = Constraint(expr= m.x231 - m.b331 <= 0)
m.c32 = Constraint(expr= m.x232 - m.b332 <= 0)
m.c33 = Constraint(expr= m.x233 - m.b333 <= 0)
m.c34 = Constraint(expr= m.x234 - m.b334 <= 0)
m.c35 = Constraint(expr= m.x235 - m.b335 <= 0)
m.c36 = Constraint(expr= m.x236 - m.b336 <= 0)
m.c37 = Constraint(expr= m.x237 - m.b337 <= 0)
m.c38 = Constraint(expr= m.x238 - m.b338 <= 0)
m.c39 = Constraint(expr= m.x239 - m.b339 <= 0)
m.c40 = Constraint(expr= m.x240 - m.b340 <= 0)
m.c41 = Constraint(expr= m.x241 - m.b341 <= 0)
m.c42 = Constraint(expr= m.x242 - m.b342 <= 0)
m.c43 = Constraint(expr= m.x243 - m.b343 <= 0)
m.c44 = Constraint(expr= m.x244 - m.b344 <= 0)
m.c45 = Constraint(expr= m.x245 - m.b345 <= 0)
m.c46 = Constraint(expr= m.x246 - m.b346 <= 0)
m.c47 = Constraint(expr= m.x247 - m.b347 <= 0)
m.c48 = Constraint(expr= m.x248 - m.b348 <= 0)
m.c49 = Constraint(expr= m.x249 - m.b349 <= 0)
m.c50 = Constraint(expr= m.x250 - m.b350 <= 0)
m.c51 = Constraint(expr= m.x251 - m.b351 <= 0)
m.c52 = Constraint(expr= m.x252 - m.b352 <= 0)
m.c53 = Constraint(expr= m.x253 - m.b353 <= 0)
m.c54 = Constraint(expr= m.x254 - m.b354 <= 0)
m.c55 = Constraint(expr= m.x255 - m.b355 <= 0)
m.c56 = Constraint(expr= m.x256 - m.b356 <= 0)
m.c57 = Constraint(expr= m.x257 - m.b357 <= 0)
m.c58 = Constraint(expr= m.x258 - m.b358 <= 0)
m.c59 = Constraint(expr= m.x259 - m.b359 <= 0)
m.c60 = Constraint(expr= m.x260 - m.b360 <= 0)
m.c61 = Constraint(expr= m.x261 - m.b361 <= 0)
m.c62 = Constraint(expr= m.x262 - m.b362 <= 0)
m.c63 = Constraint(expr= m.x263 - m.b363 <= 0)
m.c64 = Constraint(expr= m.x264 - m.b364 <= 0)
m.c65 = Constraint(expr= m.x265 - m.b365 <= 0)
m.c66 = Constraint(expr= m.x266 - m.b366 <= 0)
m.c67 = Constraint(expr= m.x267 - m.b367 <= 0)
m.c68 = Constraint(expr= m.x268 - m.b368 <= 0)
m.c69 = Constraint(expr= m.x269 - m.b369 <= 0)
m.c70 = Constraint(expr= m.x270 - m.b370 <= 0)
m.c71 = Constraint(expr= m.x271 - m.b371 <= 0)
m.c72 = Constraint(expr= m.x272 - m.b372 <= 0)
m.c73 = Constraint(expr= m.x273 - m.b373 <= 0)
m.c74 = Constraint(expr= m.x274 - m.b374 <= 0)
m.c75 = Constraint(expr= m.x275 - m.b375 <= 0)
m.c76 = Constraint(expr= m.x276 - m.b376 <= 0)
m.c77 = Constraint(expr= m.x277 - m.b377 <= 0)
m.c78 = Constraint(expr= m.x278 - m.b378 <= 0)
m.c79 = Constraint(expr= m.x279 - m.b379 <= 0)
m.c80 = Constraint(expr= m.x280 - m.b380 <= 0)
m.c81 = Constraint(expr= m.x281 - m.b381 <= 0)
m.c82 = Constraint(expr= m.x282 - m.b382 <= 0)
m.c83 = Constraint(expr= m.x283 - m.b383 <= 0)
m.c84 = Constraint(expr= m.x284 - m.b384 <= 0)
m.c85 = Constraint(expr= m.x285 - m.b385 <= 0)
m.c86 = Constraint(expr= m.x286 - m.b386 <= 0)
m.c87 = Constraint(expr= m.x287 - m.b387 <= 0)
m.c88 = Constraint(expr= m.x288 - m.b388 <= 0)
m.c89 = Constraint(expr= m.x289 - m.b389 <= 0)
m.c90 = Constraint(expr= m.x290 - m.b390 <= 0)
m.c91 = Constraint(expr= m.x291 - m.b391 <= 0)
m.c92 = Constraint(expr= m.x292 - m.b392 <= 0)
m.c93 = Constraint(expr= m.x293 - m.b393 <= 0)
m.c94 = Constraint(expr= m.x294 - m.b394 <= 0)
m.c95 = Constraint(expr= m.x295 - m.b395 <= 0)
m.c96 = Constraint(expr= m.x296 - m.b396 <= 0)
m.c97 = Constraint(expr= m.x297 - m.b397 <= 0)
m.c98 = Constraint(expr= m.x298 - m.b398 <= 0)
m.c99 = Constraint(expr= m.x299 - m.b399 <= 0)
m.c100 = Constraint(expr= m.x300 - m.b400 <= 0)
m.c101 = Constraint(expr= m.x301 - m.b401 <= 0)
m.c102 = Constraint(expr= m.x302 - m.b402 <= 0)
m.c103 = Constraint(expr= m.x303 - m.b403 <= 0)
m.c104 = Constraint(expr= m.x203 - m.b404 <= 0)
m.c105 = Constraint(expr= m.x204 + m.x205 + m.x206 + m.x207 + m.x208 + m.x209 + m.x210 + m.x211 + m.x212 + m.x213
+ m.x214 + m.x215 + m.x216 + m.x217 + m.x218 + m.x219 + m.x220 + m.x221 + m.x222 + m.x223
+ m.x224 + m.x225 + m.x226 + m.x227 + m.x228 + m.x229 + m.x230 + m.x231 + m.x232 + m.x233
+ m.x234 + m.x235 + m.x236 + m.x237 + m.x238 + m.x239 + m.x240 + m.x241 + m.x242 + m.x243
+ m.x244 + m.x245 + m.x246 + m.x247 + m.x248 + m.x249 + m.x250 + m.x251 + m.x252 + m.x253
+ m.x254 + m.x255 + m.x256 + m.x257 + m.x258 + m.x259 + m.x260 + m.x261 + m.x262 + m.x263
+ m.x264 + m.x265 + m.x266 + m.x267 + m.x268 + m.x269 + m.x270 + m.x271 + m.x272 + m.x273
+ m.x274 + m.x275 + m.x276 + m.x277 + m.x278 + m.x279 + m.x280 + m.x281 + m.x282 + m.x283
+ m.x284 + m.x285 + m.x286 + m.x287 + m.x288 + m.x289 + m.x290 + m.x291 + m.x292 + m.x293
+ m.x294 + m.x295 + m.x296 + m.x297 + m.x298 + m.x299 + m.x300 + m.x301 + m.x302 + m.x303
== 1)
m.c106 = Constraint(expr= m.b304 + m.b305 + m.b306 + m.b307 + m.b308 + m.b309 + m.b310 + m.b311 + m.b312 + m.b313
+ m.b314 + m.b315 + m.b316 + m.b317 + m.b318 + m.b319 + m.b320 + m.b321 + m.b322 + m.b323
+ m.b324 + m.b325 + m.b326 + m.b327 + m.b328 + m.b329 + m.b330 + m.b331 + m.b332 + m.b333
+ m.b334 + m.b335 + m.b336 + m.b337 + m.b338 + m.b339 + m.b340 + m.b341 + m.b342 + m.b343
+ m.b344 + m.b345 + m.b346 + m.b347 + m.b348 + m.b349 + m.b350 + m.b351 + m.b352 + m.b353
+ m.b354 + m.b355 + m.b356 + m.b357 + m.b358 + m.b359 + m.b360 + m.b361 + m.b362 + m.b363
+ m.b364 + m.b365 + m.b366 + m.b367 + m.b368 + m.b369 + m.b370 + m.b371 + m.b372 + m.b373
+ m.b374 + m.b375 + m.b376 + m.b377 + m.b378 + m.b379 + m.b380 + m.b381 + m.b382 + m.b383
+ m.b384 + m.b385 + m.b386 + m.b387 + m.b388 + m.b389 + m.b390 + m.b391 + m.b392 + m.b393
+ m.b394 + m.b395 + m.b396 + m.b397 + m.b398 + m.b399 + m.b400 + m.b401 + m.b402 + m.b403
+ m.b404 <= 11)
m.c107 = Constraint(expr= - m.x2 + 0.390247*m.x204 + 0.0355075*m.x205 + 0.0103892*m.x206 + 0.00949873*m.x207
+ 0.00890974*m.x208 - 0.0048198*m.x209 - 0.0151061*m.x210 - 0.0180772*m.x211
- 0.0547008*m.x212 - 0.00579598*m.x213 - 0.0181858*m.x214 - 0.00449728*m.x215
- 0.00308424*m.x216 + 0.0187901*m.x217 - 0.0184553*m.x218 + 0.0279672*m.x219
+ 0.0347489*m.x220 + 0.0439735*m.x221 - 0.0186044*m.x222 + 0.000382935*m.x223 + 0.01102*m.x224
- 0.000128201*m.x225 + 0.0136055*m.x226 - 0.00847303*m.x227 + 0.00772976*m.x228
- 0.0295372*m.x229 - 0.00761416*m.x230 - 4.24721E-5*m.x231 - 0.00459597*m.x232
+ 0.00232022*m.x233 + 0.0509778*m.x234 - 0.0156482*m.x235 + 0.0162671*m.x236
- 0.0132302*m.x237 + 0.0250776*m.x238 - 0.0120527*m.x239 + 0.0138503*m.x240 + 0.0174032*m.x241
+ 0.0141194*m.x242 + 0.0227987*m.x243 + 0.0193746*m.x244 + 0.0242182*m.x245 + 0.0115852*m.x246
- 0.00162455*m.x247 + 0.0485595*m.x248 + 0.00207472*m.x249 + 0.00660381*m.x250
+ 0.0335273*m.x251 - 0.00253464*m.x252 + 0.0243471*m.x253 - 4.32941E-5*m.x254
+ 0.0163137*m.x255 - 0.000494175*m.x256 + 0.0164977*m.x257 + 0.00852804*m.x258
+ 0.0112867*m.x259 + 0.0247222*m.x260 - 0.0163525*m.x261 + 0.00503011*m.x262
+ 0.0521947*m.x263 - 0.00318536*m.x264 + 0.0012286*m.x265 - 0.0157072*m.x266
- 0.0502192*m.x267 - 0.00188018*m.x268 + 0.00421152*m.x269 + 0.0127643*m.x270
+ 0.0174037*m.x271 - 0.0100234*m.x272 - 0.00217682*m.x273 + 0.00605866*m.x274
+ 0.0167264*m.x275 - 0.00986916*m.x276 + 0.000264178*m.x277 + 0.000443677*m.x278
+ 0.0156931*m.x279 - 0.00276268*m.x280 + 0.0162342*m.x281 - 0.00713742*m.x282
+ 0.0535351*m.x283 + 0.00652548*m.x284 - 0.0124237*m.x285 + 0.0284349*m.x286
- 0.0130366*m.x287 + 0.00243309*m.x288 + 0.00484607*m.x289 + 0.0192039*m.x290
- 0.0085911*m.x291 - 0.0062031*m.x292 + 0.00268854*m.x293 + 0.00374751*m.x294
+ 0.0123958*m.x295 - 0.00281911*m.x296 + 0.0022118*m.x297 + 0.0167955*m.x298
- 0.0279332*m.x299 + 0.0227079*m.x300 + 0.00975774*m.x301 + 0.000116986*m.x302
+ 0.00508413*m.x303 == 0)
m.c108 = Constraint(expr= - m.x3 + 0.0355075*m.x204 + 0.375363*m.x205 + 0.116457*m.x206 + 0.00752357*m.x207
+ 0.0293686*m.x208 + 0.0522029*m.x209 + 0.0199263*m.x210 - 0.00639786*m.x211
+ 0.0476511*m.x212 + 0.0308355*m.x213 + 0.0507195*m.x214 - 0.00222776*m.x215
- 0.00469082*m.x216 + 0.0220067*m.x217 + 0.0249277*m.x218 + 0.0260539*m.x219
+ 0.0301066*m.x220 + 0.0272172*m.x221 + 0.051374*m.x222 + 0.0518153*m.x223 + 0.0043452*m.x224
+ 0.066289*m.x225 + 0.000519585*m.x226 - 0.00046168*m.x227 + 0.00154905*m.x228
+ 0.0654627*m.x229 + 0.0180154*m.x230 + 0.00649144*m.x231 + 0.147396*m.x232 + 0.0126159*m.x233
+ 0.0114801*m.x234 + 0.00607166*m.x235 + 0.0404381*m.x236 - 0.00899911*m.x237
- 0.00165809*m.x238 + 0.0142276*m.x239 + 0.0344086*m.x240 + 0.0192482*m.x241
+ 0.0223002*m.x242 + 0.012791*m.x243 + 0.0190131*m.x244 + 6.63459E-5*m.x245 - 0.0244053*m.x246
+ 0.0151994*m.x247 + 0.0842548*m.x248 - 0.00547032*m.x249 + 0.00366432*m.x250
- 0.00269275*m.x251 + 0.0064107*m.x252 + 0.0159232*m.x253 + 0.0109604*m.x254
+ 0.0557033*m.x255 + 0.00892139*m.x256 - 0.00637132*m.x257 + 0.028098*m.x258
+ 0.0142655*m.x259 + 0.0264826*m.x260 - 0.0200925*m.x261 + 0.00429221*m.x262
+ 0.0268675*m.x263 - 0.00173957*m.x264 + 0.00182754*m.x265 + 0.0102239*m.x266
- 0.0136152*m.x267 + 0.0458865*m.x268 + 0.0178109*m.x269 + 0.0122813*m.x270 + 0.0104665*m.x271
- 0.0209121*m.x272 + 0.00754928*m.x273 + 0.00403463*m.x274 + 0.0479268*m.x275
- 0.0117451*m.x276 + 0.028956*m.x277 + 0.0186632*m.x278 + 0.0181645*m.x279 + 0.00696511*m.x280
- 0.00758658*m.x281 - 0.00157434*m.x282 + 0.0257631*m.x283 + 0.0226078*m.x284
+ 0.0117173*m.x285 + 0.022134*m.x286 + 0.00875918*m.x287 + 0.0213683*m.x288 + 0.0223469*m.x289
+ 0.0139068*m.x290 + 0.0353495*m.x291 + 0.00675913*m.x292 + 0.00676616*m.x293
- 0.0169577*m.x294 + 0.00339621*m.x295 + 0.0150229*m.x296 - 0.0133134*m.x297
+ 0.0134182*m.x298 + 0.0889001*m.x299 + 0.0286671*m.x300 + 0.0390347*m.x301
+ 0.00733705*m.x302 + 0.0374277*m.x303 == 0)
m.c109 = Constraint(expr= - m.x4 + 0.0103892*m.x204 + 0.116457*m.x205 + 0.494358*m.x206 + 0.00213378*m.x207
+ 0.0204691*m.x208 + 0.000419125*m.x209 - 0.0151413*m.x210 + 0.00865542*m.x211
- 0.0218289*m.x212 + 0.127486*m.x213 + 0.011904*m.x214 + 0.00842993*m.x215 + 0.00424642*m.x216
+ 0.0288695*m.x217 + 0.0119527*m.x218 - 0.00454489*m.x219 + 0.0070179*m.x220
- 0.0155243*m.x221 + 0.00154022*m.x222 + 0.0125708*m.x223 + 0.0104609*m.x224 + 0.145949*m.x225
- 0.0019853*m.x226 - 0.00879835*m.x227 - 0.0114691*m.x228 + 0.183686*m.x229 + 0.0420925*m.x230
+ 0.0250886*m.x231 + 0.138133*m.x232 + 0.0278877*m.x233 + 0.0545798*m.x234 - 0.0090554*m.x235
+ 0.138583*m.x236 + 0.0150959*m.x237 + 0.0162039*m.x238 + 0.0213625*m.x239 + 0.0200764*m.x240
- 0.00431381*m.x241 - 0.00842299*m.x242 - 0.00117286*m.x243 + 0.00911691*m.x244
- 0.00746052*m.x245 - 0.011358*m.x246 - 0.00410314*m.x247 + 0.00010559*m.x248
- 0.0124818*m.x249 + 0.0222942*m.x250 + 0.0641257*m.x251 - 0.00250627*m.x252
+ 0.00990617*m.x253 + 0.0106624*m.x254 - 0.00120817*m.x255 - 0.0113822*m.x256
+ 0.0115937*m.x257 - 0.0206532*m.x258 + 0.0357135*m.x259 - 0.00418977*m.x260 + 0.030475*m.x261
- 0.0301452*m.x262 + 0.0467552*m.x263 + 0.0103264*m.x264 - 0.0157278*m.x265 + 0.0167359*m.x266
+ 0.00653818*m.x267 + 0.0409725*m.x268 + 0.0331419*m.x269 + 0.0180349*m.x270
+ 0.0284386*m.x271 - 0.00694428*m.x272 + 0.00602621*m.x273 + 0.0281091*m.x274
+ 0.0213196*m.x275 - 0.0306486*m.x276 + 0.019325*m.x277 - 0.00667034*m.x278
+ 0.000467446*m.x279 + 0.0201785*m.x280 - 0.000464311*m.x281 - 0.0236607*m.x282
+ 0.0310239*m.x283 + 0.042261*m.x284 + 0.0185462*m.x285 - 0.0122475*m.x286 + 0.0280865*m.x287
+ 0.0121116*m.x288 + 0.00361683*m.x289 + 0.0180183*m.x290 + 0.0226601*m.x291
+ 0.0329849*m.x292 + 0.00576928*m.x293 - 0.00470462*m.x294 - 0.0153482*m.x295
+ 0.0172118*m.x296 - 0.0344168*m.x297 - 0.0408698*m.x298 + 0.0755415*m.x299 + 0.0219066*m.x300
+ 0.00157357*m.x301 + 0.0412011*m.x302 + 0.0159705*m.x303 == 0)
m.c110 = Constraint(expr= - m.x5 + 0.00949873*m.x204 + 0.00752357*m.x205 + 0.00213378*m.x206 + 0.202976*m.x207
+ 0.0236145*m.x208 + 0.0117362*m.x209 + 0.0102009*m.x210 - 0.00649661*m.x211
+ 0.000116182*m.x212 + 0.0232567*m.x213 + 0.0234073*m.x214 + 0.0470343*m.x215
+ 0.0216397*m.x216 - 0.0206614*m.x217 + 0.0146671*m.x218 + 0.0165581*m.x219 + 0.0400276*m.x220
+ 0.020625*m.x221 + 0.0170646*m.x222 + 0.0110715*m.x223 + 0.00747915*m.x224
- 0.00773408*m.x225 + 0.0277694*m.x226 + 0.00589594*m.x227 + 0.00860339*m.x228
- 0.0245255*m.x229 - 0.0103474*m.x230 + 0.0274283*m.x231 + 0.0223035*m.x232 + 0.0237512*m.x233
+ 0.0068636*m.x234 + 0.0216305*m.x235 - 0.00303771*m.x236 + 0.0013176*m.x237
+ 0.0157544*m.x238 + 0.0168579*m.x239 + 0.0319483*m.x240 + 0.0489611*m.x241 + 0.0165915*m.x242
+ 0.0104514*m.x243 + 0.0116238*m.x244 + 0.0187021*m.x245 + 0.0150923*m.x246
+ 0.00865558*m.x247 + 0.0274023*m.x248 + 0.00371704*m.x249 + 0.0278823*m.x250
+ 0.0276611*m.x251 + 0.0335727*m.x252 + 0.0350956*m.x253 + 0.00379579*m.x254
+ 0.0146599*m.x255 + 0.0202259*m.x256 + 0.00222715*m.x257 - 0.018228*m.x258 + 0.0386991*m.x259
+ 0.0209281*m.x260 + 0.0219851*m.x261 - 0.0106357*m.x262 + 0.0312148*m.x263 + 0.0168165*m.x264
+ 0.0159145*m.x265 - 0.00939875*m.x266 + 0.0209841*m.x267 + 0.0190617*m.x268
+ 0.0158536*m.x269 + 0.0246904*m.x270 + 0.00427924*m.x271 - 0.00467471*m.x272
+ 0.0177642*m.x273 + 0.00659994*m.x274 + 0.0149564*m.x275 + 0.0372578*m.x276
+ 0.00639167*m.x277 + 0.0113589*m.x278 + 0.0136237*m.x279 + 0.00548526*m.x280
+ 0.00938667*m.x281 - 0.0040516*m.x282 + 0.0204574*m.x283 + 0.00726938*m.x284
+ 0.0138296*m.x285 + 0.00730263*m.x286 + 0.00429398*m.x287 + 0.0216644*m.x288
+ 0.0233018*m.x289 + 0.0328639*m.x290 + 0.0305972*m.x291 - 0.00415707*m.x292
+ 0.00964148*m.x293 + 0.000244902*m.x294 + 0.0374478*m.x295 + 0.020036*m.x296
+ 0.00411236*m.x297 + 0.0103469*m.x298 - 0.012054*m.x299 + 0.0183139*m.x300 - 0.0288293*m.x301
+ 0.00250478*m.x302 + 0.0130454*m.x303 == 0)
m.c111 = Constraint(expr= - m.x6 + 0.00890974*m.x204 + 0.0293686*m.x205 + 0.0204691*m.x206 + 0.0236145*m.x207
+ 0.132744*m.x208 + 0.00939955*m.x209 + 0.0118432*m.x210 + 0.000995566*m.x211
+ 0.00478682*m.x212 + 0.0257712*m.x213 + 0.00349815*m.x214 + 0.0165971*m.x215
+ 0.0322053*m.x216 + 0.0281818*m.x217 + 0.0245199*m.x218 + 0.0118447*m.x219 + 0.0200262*m.x220
- 0.0135716*m.x221 + 0.0171357*m.x222 + 0.0064231*m.x223 + 0.0108965*m.x224 + 0.0493937*m.x225
+ 0.0194761*m.x226 + 0.00935395*m.x227 + 0.00691311*m.x228 + 0.00811154*m.x229
+ 0.0217094*m.x230 + 0.00509551*m.x231 + 0.0102365*m.x232 + 0.0598964*m.x233
+ 0.000151401*m.x234 + 0.0314895*m.x235 + 0.0222037*m.x236 + 0.0226771*m.x237
+ 0.0271938*m.x238 + 0.0166563*m.x239 + 0.0185838*m.x240 + 0.0240307*m.x241
- 0.00254427*m.x242 + 0.0207655*m.x243 + 0.0197923*m.x244 + 0.0613911*m.x245
+ 0.0110642*m.x246 + 0.0207267*m.x247 + 0.0169542*m.x248 - 0.0027153*m.x249 + 0.0227537*m.x250
+ 0.0245375*m.x251 + 0.0220219*m.x252 + 0.0142215*m.x253 + 0.0212008*m.x254 + 0.0295561*m.x255
+ 0.00841613*m.x256 + 0.00832278*m.x257 + 0.00806585*m.x258 + 0.0196795*m.x259
+ 0.0144357*m.x260 - 0.00152624*m.x261 - 0.00636291*m.x262 + 0.00719514*m.x263
+ 0.0109626*m.x264 + 0.00565965*m.x265 + 0.0101803*m.x266 - 0.0016346*m.x267
+ 0.0277761*m.x268 + 0.0225116*m.x269 - 0.00484509*m.x270 + 0.0047708*m.x271
+ 0.00518488*m.x272 + 0.0126256*m.x273 - 0.00994378*m.x274 + 0.00270935*m.x275
- 0.00761522*m.x276 + 0.00740387*m.x277 + 0.038373*m.x278 + 0.0330416*m.x279
+ 0.00915683*m.x280 + 0.0338859*m.x281 + 0.0110433*m.x282 + 0.00100659*m.x283
+ 0.038867*m.x284 + 0.00624966*m.x285 + 0.00420064*m.x286 + 0.0301859*m.x287
+ 0.0339489*m.x288 + 0.00230194*m.x289 + 0.0201638*m.x290 + 0.0148104*m.x291
+ 0.0193621*m.x292 + 0.00948047*m.x293 + 0.0107385*m.x294 + 0.00287505*m.x295
+ 0.0130434*m.x296 - 0.00176429*m.x297 + 0.036063*m.x298 + 0.0123589*m.x299 + 0.0190362*m.x300
- 0.01883*m.x301 + 0.0156576*m.x302 + 0.0265264*m.x303 == 0)
m.c112 = Constraint(expr= - m.x7 - 0.0048198*m.x204 + 0.0522029*m.x205 + 0.000419125*m.x206 + 0.0117362*m.x207
+ 0.00939955*m.x208 + 1.26577*m.x209 + 0.00746215*m.x210 + 0.00917556*m.x211
+ 0.0186178*m.x212 - 0.00694419*m.x213 + 0.0194384*m.x214 + 0.0120403*m.x215
+ 0.0375406*m.x216 + 0.031075*m.x217 - 0.00168578*m.x218 + 0.0459517*m.x219 + 0.0104064*m.x220
- 0.000580239*m.x221 - 0.0192679*m.x222 + 0.00573205*m.x223 - 0.00590063*m.x224
+ 0.00118752*m.x225 + 0.0146083*m.x226 + 0.00976886*m.x227 + 0.0122717*m.x228
+ 0.015996*m.x229 + 0.0262883*m.x230 + 0.0364425*m.x231 + 0.0587967*m.x232 + 0.00678878*m.x233
+ 0.0132248*m.x234 + 0.0117136*m.x235 - 0.00958286*m.x236 + 0.059318*m.x237 + 0.0162948*m.x238
+ 0.0161974*m.x239 + 0.00634078*m.x240 + 0.0120533*m.x241 + 0.000742111*m.x242
+ 0.0218172*m.x243 - 0.00438877*m.x244 + 0.0402544*m.x245 - 0.00602825*m.x246
+ 0.0189494*m.x247 + 0.00789539*m.x248 + 0.0132198*m.x249 + 0.0131179*m.x250
+ 0.0350419*m.x251 + 0.00782381*m.x252 - 0.00238836*m.x253 + 0.0282466*m.x254
- 0.0144879*m.x255 + 0.0254505*m.x256 + 0.00288051*m.x257 - 0.00244405*m.x258
+ 0.0133542*m.x259 + 0.0320697*m.x260 - 0.0217595*m.x261 + 0.0127581*m.x262 + 0.0200628*m.x263
+ 0.0123119*m.x264 + 0.0263411*m.x265 + 0.00564516*m.x266 - 0.0172992*m.x267
+ 0.0342875*m.x268 + 0.0155064*m.x269 - 0.00477146*m.x270 + 0.00415194*m.x271
+ 0.00797725*m.x272 + 0.0134081*m.x273 + 0.0355325*m.x274 + 0.00240413*m.x275
+ 0.0160415*m.x276 - 0.030207*m.x277 + 0.00296297*m.x278 + 0.0130072*m.x279
+ 0.00450281*m.x280 + 0.0121371*m.x281 - 0.0231401*m.x282 - 0.0106726*m.x283
+ 0.0230093*m.x284 + 0.0220687*m.x285 + 0.0720504*m.x286 + 0.0235846*m.x287 + 0.0134857*m.x288
+ 0.00278062*m.x289 - 0.00858219*m.x290 + 0.0238012*m.x291 + 0.0088678*m.x292
- 3.17943E-5*m.x293 + 0.0181268*m.x294 + 0.00782932*m.x295 + 0.00311794*m.x296
- 0.032215*m.x297 + 0.00207316*m.x298 + 0.0352617*m.x299 + 0.0157662*m.x300 + 0.243511*m.x301
+ 0.006698*m.x302 + 0.0576747*m.x303 == 0)
m.c113 = Constraint(expr= - m.x8 - 0.0151061*m.x204 + 0.0199263*m.x205 - 0.0151413*m.x206 + 0.0102009*m.x207
+ 0.0118432*m.x208 + 0.00746215*m.x209 + 0.136805*m.x210 - 0.00716314*m.x211
+ 0.0329462*m.x212 - 0.00444303*m.x213 + 0.0147918*m.x214 + 0.00156164*m.x215
+ 0.0314898*m.x216 - 0.00261112*m.x217 + 0.0315032*m.x218 + 0.0119617*m.x219
+ 0.00286605*m.x220 + 0.0229931*m.x221 - 0.0297937*m.x222 - 0.00124776*m.x223
+ 0.00819446*m.x224 + 0.0115835*m.x225 - 0.00151625*m.x226 - 0.0108978*m.x227
+ 0.00119563*m.x228 + 0.00380145*m.x229 + 0.01388*m.x230 + 0.018817*m.x231 + 0.00271468*m.x232
+ 0.0130573*m.x233 - 0.00937181*m.x234 + 0.0135407*m.x235 - 0.00205201*m.x236
+ 0.0110361*m.x237 - 0.00849477*m.x238 + 0.00439244*m.x239 + 0.0127402*m.x240
+ 0.0166285*m.x241 + 0.0264399*m.x242 + 0.0100685*m.x243 + 0.00274108*m.x244
+ 0.00935881*m.x245 + 0.0225873*m.x246 + 0.00733761*m.x247 + 0.0201234*m.x248
+ 0.00199539*m.x249 + 0.00883369*m.x250 - 0.00334111*m.x251 + 0.00675904*m.x252
+ 0.0174474*m.x253 + 0.000986276*m.x254 + 0.00773796*m.x255 + 0.0122267*m.x256
+ 0.0155811*m.x257 + 0.00782426*m.x258 + 0.03853*m.x259 + 0.0225766*m.x260 + 0.0150547*m.x261
- 0.00416059*m.x262 + 0.00755277*m.x263 - 0.0018521*m.x264 - 0.0101745*m.x265
- 0.00307772*m.x266 - 0.00815475*m.x267 + 0.0229656*m.x268 - 0.00130048*m.x269
+ 0.00871877*m.x270 - 0.0045347*m.x271 - 0.0157399*m.x272 + 0.00177914*m.x273
+ 0.0272626*m.x274 + 0.0117028*m.x275 + 0.00138295*m.x276 + 0.0185095*m.x277
+ 0.0171304*m.x278 + 0.0122791*m.x279 + 0.00233108*m.x280 + 0.0306379*m.x281
+ 0.0152496*m.x282 + 0.00760112*m.x283 + 0.0227379*m.x284 + 0.0315858*m.x285
+ 0.0060507*m.x286 + 0.0179103*m.x287 + 0.00721099*m.x288 + 0.00164949*m.x289
- 0.0109996*m.x290 + 0.0589001*m.x291 + 0.00615122*m.x292 - 0.00717082*m.x293
+ 0.0112392*m.x294 + 0.000610349*m.x295 + 0.0116254*m.x296 - 0.0224759*m.x297
+ 0.00642488*m.x298 + 0.00803335*m.x299 + 0.0180457*m.x300 + 0.0047812*m.x301
+ 0.00731383*m.x302 + 0.0122221*m.x303 == 0)
m.c114 = Constraint(expr= - m.x9 - 0.0180772*m.x204 - 0.00639786*m.x205 + 0.00865542*m.x206 - 0.00649661*m.x207
+ 0.000995566*m.x208 + 0.00917556*m.x209 - 0.00716314*m.x210 + 0.285403*m.x211
+ 0.0092214*m.x212 + 0.00968176*m.x213 - 0.0117263*m.x214 + 0.00488845*m.x215
+ 0.00932434*m.x216 - 0.0022426*m.x217 + 0.00079052*m.x218 - 0.010629*m.x219
+ 0.00272852*m.x220 - 0.00128164*m.x221 + 0.0092976*m.x222 + 0.00897629*m.x223
- 0.0051429*m.x224 + 0.0194189*m.x225 + 0.00807556*m.x226 + 0.014474*m.x227
- 0.00996885*m.x228 + 0.0499867*m.x229 - 0.0180156*m.x230 + 0.0369786*m.x231
- 0.0326873*m.x232 - 0.00929421*m.x233 + 0.00932232*m.x234 - 0.00128122*m.x235
+ 0.0044504*m.x236 + 0.0154868*m.x237 - 0.00246393*m.x238 - 0.00850907*m.x239
+ 0.010305*m.x240 - 0.0107958*m.x241 + 0.0184062*m.x242 - 0.000823765*m.x243
+ 0.0132777*m.x244 + 0.00103676*m.x245 - 0.00519952*m.x246 + 0.00505829*m.x247
- 0.003359*m.x248 + 0.00172548*m.x249 - 0.00798884*m.x250 - 0.00523044*m.x251
- 0.0106746*m.x252 + 0.00991922*m.x253 + 0.00762574*m.x254 - 0.0266695*m.x255
+ 0.00886183*m.x256 + 0.0170693*m.x257 - 0.0010862*m.x258 + 0.0164155*m.x259
- 0.00380167*m.x260 + 0.0200358*m.x261 - 0.0132264*m.x262 - 0.0108891*m.x263 + 0.020785*m.x264
+ 0.0086092*m.x265 - 0.00880776*m.x266 - 0.0195389*m.x267 + 0.00208113*m.x268
- 0.00273464*m.x269 - 0.000357808*m.x270 + 0.0647172*m.x271 - 0.0015303*m.x272
+ 0.0129634*m.x273 - 0.000139358*m.x274 - 0.0044266*m.x275 + 0.0294097*m.x276
- 0.00500434*m.x277 + 0.0311579*m.x278 + 0.0494097*m.x279 + 0.00288612*m.x280
+ 0.0105617*m.x281 + 0.00135164*m.x282 + 0.00925665*m.x283 + 0.00141295*m.x284
- 0.00247117*m.x285 - 0.0255331*m.x286 + 0.0200897*m.x287 + 0.022993*m.x288
- 0.000549013*m.x289 - 0.00068661*m.x290 - 0.00420057*m.x291 + 0.00921205*m.x292
+ 0.000865255*m.x293 + 0.00517365*m.x294 + 0.0240808*m.x295 + 0.00215238*m.x296
+ 0.0141697*m.x297 + 0.00516594*m.x298 + 0.00216393*m.x299 + 0.0179954*m.x300
- 0.00675247*m.x301 + 0.00119681*m.x302 - 0.00205582*m.x303 == 0)
m.c115 = Constraint(expr= - m.x10 - 0.0547008*m.x204 + 0.0476511*m.x205 - 0.0218289*m.x206 + 0.000116182*m.x207
+ 0.00478682*m.x208 + 0.0186178*m.x209 + 0.0329462*m.x210 + 0.0092214*m.x211 + 1.16965*m.x212
- 0.0339345*m.x213 + 0.000805966*m.x214 - 0.00862632*m.x215 + 0.00387244*m.x216
+ 0.0122928*m.x217 + 0.0567976*m.x218 - 0.00262157*m.x219 - 0.00869213*m.x220
+ 0.00994931*m.x221 + 0.00711671*m.x222 + 0.0652085*m.x223 + 0.0122233*m.x224
- 0.0152003*m.x225 + 0.0251098*m.x226 + 0.00797425*m.x227 + 0.00371891*m.x228
- 0.00148049*m.x229 + 0.0193177*m.x230 + 0.050764*m.x231 - 0.0288765*m.x232
- 0.000566519*m.x233 - 0.00504625*m.x234 - 0.0193402*m.x235 - 0.012241*m.x236
+ 0.0162554*m.x237 - 0.0167425*m.x238 + 0.00537524*m.x239 - 0.00325532*m.x240
+ 0.0143804*m.x241 + 0.0540646*m.x242 + 0.00225673*m.x243 + 0.0124663*m.x244
- 0.00398651*m.x245 + 0.0396497*m.x246 - 0.00309397*m.x247 + 0.0671213*m.x248
+ 0.0105468*m.x249 + 0.0076658*m.x250 + 0.046947*m.x251 + 0.000222582*m.x252
- 0.0116779*m.x253 - 0.00988969*m.x254 + 0.0132613*m.x255 - 0.00967266*m.x256
+ 0.0167367*m.x257 + 0.000760504*m.x258 - 0.0145817*m.x259 + 0.00627821*m.x260
+ 0.00589982*m.x261 + 0.0158731*m.x262 - 0.00692226*m.x263 + 0.018374*m.x264
+ 0.00783315*m.x265 - 0.00318606*m.x266 + 0.0253862*m.x267 - 0.00670214*m.x268
+ 0.01518*m.x269 + 0.0331725*m.x270 - 0.0229361*m.x271 - 0.0365251*m.x272 + 0.0190496*m.x273
+ 0.00542296*m.x274 + 0.00513392*m.x275 - 0.00866694*m.x276 + 0.066741*m.x277
+ 0.0166803*m.x278 + 0.0021271*m.x279 + 0.00823225*m.x280 + 0.00857754*m.x281
+ 0.0313512*m.x282 + 0.00130029*m.x283 - 0.0150965*m.x284 + 0.0772805*m.x285
+ 0.0392036*m.x286 + 0.0404836*m.x287 + 0.0233051*m.x288 + 0.00145357*m.x289
+ 0.0353783*m.x290 + 0.0245361*m.x291 + 0.00939562*m.x292 + 0.0167069*m.x293
- 0.0177537*m.x294 + 0.00699783*m.x295 - 0.0148329*m.x296 + 0.178873*m.x297
+ 0.00483769*m.x298 + 0.0402204*m.x299 + 0.111526*m.x300 - 0.00193246*m.x301
+ 0.0326706*m.x302 - 0.00767129*m.x303 == 0)
m.c116 = Constraint(expr= - m.x11 - 0.00579598*m.x204 + 0.0308355*m.x205 + 0.127486*m.x206 + 0.0232567*m.x207
+ 0.0257712*m.x208 - 0.00694419*m.x209 - 0.00444303*m.x210 + 0.00968176*m.x211
- 0.0339345*m.x212 + 0.41127*m.x213 + 0.00717303*m.x214 - 0.00672795*m.x215
- 0.00365582*m.x216 - 0.0113386*m.x217 - 0.00101702*m.x218 - 0.00403718*m.x219
+ 0.0075895*m.x220 + 0.0372281*m.x221 - 0.0191596*m.x222 - 0.00586128*m.x223
+ 0.0131072*m.x224 + 0.176793*m.x225 + 0.032372*m.x226 - 0.0206317*m.x227 + 0.0116962*m.x228
+ 0.0856918*m.x229 + 0.0056902*m.x230 + 0.00180131*m.x231 + 0.0296162*m.x232
+ 0.0209429*m.x233 - 0.00927325*m.x234 + 0.0316756*m.x235 + 0.155782*m.x236 + 0.0111882*m.x237
+ 0.0301704*m.x238 + 0.00605787*m.x239 + 0.00922974*m.x240 + 0.00186503*m.x241
- 0.0204732*m.x242 - 0.00336318*m.x243 + 0.0130752*m.x244 + 0.0383614*m.x245
- 0.0030681*m.x246 + 0.00188592*m.x247 + 0.0305494*m.x248 - 0.00910821*m.x249
+ 0.0135289*m.x250 + 0.103912*m.x251 + 0.0135404*m.x252 + 0.00765973*m.x253 + 0.005395*m.x254
- 0.0102711*m.x255 + 0.000261336*m.x256 + 0.00274854*m.x257 + 0.0082671*m.x258
+ 0.0215893*m.x259 - 0.0026586*m.x260 + 0.0389273*m.x261 + 0.00679229*m.x262
+ 0.0607996*m.x263 + 0.0264003*m.x264 + 0.00577287*m.x265 + 0.00499131*m.x266
- 0.00587637*m.x267 + 0.0419289*m.x268 + 0.00163644*m.x269 + 0.00084169*m.x270
+ 0.00995171*m.x271 + 0.00125486*m.x272 + 0.000587184*m.x273 + 0.00290832*m.x274
+ 0.0203179*m.x275 - 0.017854*m.x276 + 0.00702231*m.x277 + 0.000393591*m.x278
+ 0.0103674*m.x279 + 0.00633375*m.x280 + 0.0194224*m.x281 - 0.00963904*m.x282
+ 0.0241569*m.x283 + 0.0143008*m.x284 + 0.0127084*m.x285 + 0.0167294*m.x286 + 0.0346049*m.x287
+ 0.0161423*m.x288 + 0.00486934*m.x289 - 1.9656E-5*m.x290 - 0.0192722*m.x291
+ 0.0190744*m.x292 - 0.00901601*m.x293 - 0.00394108*m.x294 + 0.00072213*m.x295
+ 0.0287036*m.x296 - 0.00879298*m.x297 - 0.00130419*m.x298 + 0.0144463*m.x299 + 0.0227*m.x300
+ 0.00430831*m.x301 + 0.00196198*m.x302 + 0.006199*m.x303 == 0)
m.c117 = Constraint(expr= - m.x12 - 0.0181858*m.x204 + 0.0507195*m.x205 + 0.011904*m.x206 + 0.0234073*m.x207
+ 0.00349815*m.x208 + 0.0194384*m.x209 + 0.0147918*m.x210 - 0.0117263*m.x211
+ 0.000805966*m.x212 + 0.00717303*m.x213 + 0.219047*m.x214 + 0.023456*m.x215
+ 0.00195478*m.x216 + 0.0148068*m.x217 + 0.0380638*m.x218 + 0.00700216*m.x219
+ 0.0101168*m.x220 + 0.0569711*m.x221 - 0.00537336*m.x222 - 0.00676864*m.x223
- 0.000233965*m.x224 - 0.0053146*m.x225 + 0.0128605*m.x226 + 0.00379938*m.x227
+ 0.0202337*m.x228 + 0.0295931*m.x229 + 0.00286184*m.x230 + 0.0124339*m.x231 + 0.031981*m.x232
+ 0.0177141*m.x233 + 0.0133593*m.x234 + 0.0484803*m.x235 - 0.00479808*m.x236 + 0.04212*m.x237
+ 0.0157963*m.x238 + 0.00983178*m.x239 + 0.0208788*m.x240 + 0.0260342*m.x241
+ 0.00898847*m.x242 + 0.0194251*m.x243 + 0.0124203*m.x244 + 0.00730049*m.x245
+ 0.0250217*m.x246 - 0.00862089*m.x247 - 0.0336638*m.x248 - 0.00677995*m.x249
+ 0.00625335*m.x250 + 0.0263146*m.x251 + 0.00182442*m.x252 + 0.0180868*m.x253
+ 0.0139184*m.x254 + 0.0593808*m.x255 + 0.000709314*m.x256 + 0.00766591*m.x257
+ 0.0182084*m.x258 + 0.0215114*m.x259 + 0.0402573*m.x260 + 0.00451804*m.x261
+ 0.00173858*m.x262 + 0.0011291*m.x263 + 0.0213333*m.x264 + 0.00782635*m.x265
+ 0.031041*m.x266 + 0.0122097*m.x267 + 0.00799351*m.x268 - 0.00702948*m.x269
+ 0.00472328*m.x270 + 0.0103154*m.x271 + 0.0289129*m.x272 + 0.00688368*m.x273
+ 0.0161368*m.x274 + 0.0517634*m.x275 + 0.000715776*m.x276 + 0.0272845*m.x277
+ 0.0154336*m.x278 - 0.00822959*m.x279 + 0.000626594*m.x280 + 0.000631494*m.x281
+ 0.00874438*m.x282 + 0.00365132*m.x283 - 0.0056711*m.x284 + 0.0203348*m.x285
+ 0.0341872*m.x286 + 0.0102937*m.x287 + 0.0151637*m.x288 + 0.0152717*m.x289 + 0.011193*m.x290
+ 0.0112057*m.x291 + 0.00953528*m.x292 + 0.000108253*m.x293 + 0.00372088*m.x294
+ 0.00788742*m.x295 + 0.035638*m.x296 - 0.0118438*m.x297 - 0.00955396*m.x298
+ 0.0411535*m.x299 - 0.00808243*m.x300 - 0.0197548*m.x301 - 0.00408574*m.x302
+ 0.0233977*m.x303 == 0)
m.c118 = Constraint(expr= - m.x13 - 0.00449728*m.x204 - 0.00222776*m.x205 + 0.00842993*m.x206 + 0.0470343*m.x207
+ 0.0165971*m.x208 + 0.0120403*m.x209 + 0.00156164*m.x210 + 0.00488845*m.x211
- 0.00862632*m.x212 - 0.00672795*m.x213 + 0.023456*m.x214 + 0.278517*m.x215 + 0.0184356*m.x216
+ 0.0109592*m.x217 + 0.0153153*m.x218 - 0.0145985*m.x219 + 0.0120963*m.x220 + 0.0333257*m.x221
- 0.0138778*m.x222 + 0.0268692*m.x223 + 0.00636244*m.x224 - 0.0359516*m.x225
- 0.00319962*m.x226 - 0.00863008*m.x227 + 0.0341934*m.x228 - 0.0214998*m.x229
- 0.00165983*m.x230 + 0.011631*m.x231 - 0.00843246*m.x232 + 0.0122534*m.x233
+ 0.0201667*m.x234 + 0.0115615*m.x235 - 0.0151645*m.x236 + 0.00572447*m.x237
- 0.000867997*m.x238 + 0.0114198*m.x239 + 0.0218247*m.x240 + 0.0164584*m.x241
+ 0.0324793*m.x242 + 0.0165224*m.x243 - 0.0110707*m.x244 + 0.0108339*m.x245
+ 0.00496455*m.x246 + 0.0121501*m.x247 - 0.010913*m.x248 + 0.0136767*m.x249 + 0.0116898*m.x250
+ 0.0382384*m.x251 + 0.0131966*m.x252 + 0.0177887*m.x253 + 0.00125449*m.x254
+ 0.0146264*m.x255 + 0.0570949*m.x256 + 0.00451784*m.x257 - 0.0264793*m.x258
+ 0.00837984*m.x259 + 0.0137972*m.x260 + 0.0176927*m.x261 - 0.00573209*m.x262
+ 0.00992262*m.x263 + 0.00917944*m.x264 - 0.00185404*m.x265 + 0.00351722*m.x266
- 0.0165471*m.x267 - 0.0113949*m.x268 + 0.00780787*m.x269 - 0.00223059*m.x270
+ 0.0206811*m.x271 + 0.0521517*m.x272 - 0.00351079*m.x273 + 0.0212677*m.x274
+ 0.00680778*m.x275 + 0.0365571*m.x276 + 0.0121352*m.x277 + 0.0025257*m.x278
+ 0.0148074*m.x279 + 0.00353214*m.x280 + 0.0168133*m.x281 + 0.0119195*m.x282 - 0.012089*m.x283
- 0.00915576*m.x284 + 0.0251125*m.x285 + 0.00612187*m.x286 + 0.0024002*m.x287
+ 0.00206781*m.x288 - 0.000360419*m.x289 + 0.00210401*m.x290 + 0.000459202*m.x291
- 0.00600004*m.x292 - 0.0113285*m.x293 - 0.00379879*m.x294 + 0.015416*m.x295
+ 0.0100832*m.x296 - 0.0115254*m.x297 + 0.0489927*m.x298 + 0.00172935*m.x299
- 0.00821597*m.x300 - 0.0062146*m.x301 - 0.014221*m.x302 + 0.0110839*m.x303 == 0)
m.c119 = Constraint(expr= - m.x14 - 0.00308424*m.x204 - 0.00469082*m.x205 + 0.00424642*m.x206 + 0.0216397*m.x207
+ 0.0322053*m.x208 + 0.0375406*m.x209 + 0.0314898*m.x210 + 0.00932434*m.x211
+ 0.00387244*m.x212 - 0.00365582*m.x213 + 0.00195478*m.x214 + 0.0184356*m.x215
+ 0.221716*m.x216 + 0.00722185*m.x217 + 0.00354749*m.x218 + 0.0146274*m.x219
+ 0.0180021*m.x220 + 0.0288875*m.x221 + 0.0125621*m.x222 + 0.0182642*m.x223
+ 0.00895779*m.x224 + 0.00895103*m.x225 - 0.00232932*m.x226 + 0.00177054*m.x227
+ 0.0136257*m.x228 + 0.0032049*m.x229 + 0.00927708*m.x230 + 0.0260767*m.x231
- 0.0166592*m.x232 + 0.0328492*m.x233 + 0.0117288*m.x234 + 0.0189044*m.x235 - 0.0303469*m.x236
- 0.00624871*m.x237 - 0.00552184*m.x238 + 0.0151253*m.x239 + 0.00196396*m.x240
+ 0.0283164*m.x241 - 7.36214E-5*m.x242 + 0.0154669*m.x243 + 0.0335265*m.x244
+ 0.0247389*m.x245 + 0.000832224*m.x246 + 0.0166299*m.x247 + 0.0470539*m.x248
+ 0.0108543*m.x249 + 0.0041831*m.x250 + 0.00544939*m.x251 + 0.00847808*m.x252
+ 0.0136335*m.x253 + 0.0285916*m.x254 + 0.00654495*m.x255 + 0.01696*m.x256 + 0.09051*m.x257
- 0.00361466*m.x258 + 0.0141785*m.x259 + 0.0210091*m.x260 + 0.0471372*m.x261
- 0.0173444*m.x262 + 0.0395081*m.x263 + 0.0341682*m.x264 + 0.0266136*m.x265
+ 0.00530461*m.x266 - 0.00299125*m.x267 + 0.00534225*m.x268 - 0.00371224*m.x269
+ 0.0103986*m.x270 + 0.0396039*m.x271 - 0.00150631*m.x272 + 0.0236174*m.x273
+ 0.0233436*m.x274 + 0.0324887*m.x275 + 0.0227743*m.x276 + 0.0134993*m.x277 + 0.0313448*m.x278
+ 0.043333*m.x279 - 0.00386439*m.x280 + 0.108963*m.x281 - 0.00524662*m.x282
- 0.00652429*m.x283 - 0.00988714*m.x284 + 0.04316*m.x285 + 0.0469731*m.x286
+ 0.00266624*m.x287 + 0.00890446*m.x288 + 0.0106296*m.x289 + 0.00867089*m.x290
+ 0.0341752*m.x291 + 0.00683051*m.x292 + 0.00335904*m.x293 + 0.0162828*m.x294
+ 0.0256177*m.x295 + 0.021417*m.x296 - 0.00659726*m.x297 + 0.031985*m.x298 + 0.0158572*m.x299
+ 0.0232882*m.x300 + 0.00712137*m.x301 + 0.00355863*m.x302 + 0.00654047*m.x303 == 0)
m.c120 = Constraint(expr= - m.x15 + 0.0187901*m.x204 + 0.0220067*m.x205 + 0.0288695*m.x206 - 0.0206614*m.x207
+ 0.0281818*m.x208 + 0.031075*m.x209 - 0.00261112*m.x210 - 0.0022426*m.x211 + 0.0122928*m.x212
- 0.0113386*m.x213 + 0.0148068*m.x214 + 0.0109592*m.x215 + 0.00722185*m.x216 + 0.348093*m.x217
+ 0.0484952*m.x218 + 0.0195361*m.x219 + 0.024247*m.x220 + 0.0280244*m.x221 + 0.052103*m.x222
- 0.0075162*m.x223 - 0.0117391*m.x224 + 0.0581007*m.x225 + 0.00789376*m.x226
+ 0.0404865*m.x227 + 0.0065787*m.x228 + 0.0280359*m.x229 + 0.0284398*m.x230 + 0.0143595*m.x231
- 0.00772267*m.x232 + 0.0146342*m.x233 + 0.00596413*m.x234 + 0.000301534*m.x235
+ 0.0135036*m.x236 + 0.0145204*m.x237 + 0.0624288*m.x238 + 0.0136456*m.x239 + 0.0353273*m.x240
+ 0.016403*m.x241 + 0.0178385*m.x242 + 0.0349872*m.x243 + 0.0452332*m.x244 + 0.0258405*m.x245
+ 0.0200869*m.x246 - 0.00370708*m.x247 + 0.0445913*m.x248 + 0.0145696*m.x249
+ 0.0102428*m.x250 + 0.0541929*m.x251 + 0.0222686*m.x252 + 0.0200759*m.x253 + 0.0227414*m.x254
+ 0.0206173*m.x255 - 0.0067449*m.x256 + 0.0455555*m.x257 - 0.0220985*m.x258
+ 0.00916835*m.x259 + 0.022344*m.x260 + 0.00900194*m.x261 + 0.00271829*m.x262
- 0.0153606*m.x263 + 0.0224616*m.x264 + 0.0145659*m.x265 + 0.00845039*m.x266 - 0.01842*m.x267
+ 0.0230371*m.x268 + 0.00761157*m.x269 + 0.00153703*m.x270 + 0.0263619*m.x271
+ 0.0097183*m.x272 + 0.0242111*m.x273 + 0.00779182*m.x274 + 0.0138659*m.x275 + 0.029875*m.x276
+ 0.012011*m.x277 + 0.0334484*m.x278 + 0.0141205*m.x279 + 0.00456199*m.x280 + 0.041893*m.x281
- 0.0231716*m.x282 + 0.0374086*m.x283 + 0.0313221*m.x284 - 0.00981712*m.x285
+ 0.0545587*m.x286 + 0.0268496*m.x287 - 0.00176973*m.x288 + 0.0262312*m.x289
+ 0.00164063*m.x290 + 0.0339984*m.x291 - 0.00434935*m.x292 + 0.00655352*m.x293
+ 0.0190876*m.x294 + 0.0274041*m.x295 + 0.020182*m.x296 - 0.0260426*m.x297 + 0.0584498*m.x298
+ 0.0466449*m.x299 + 0.0330244*m.x300 + 0.0380016*m.x301 + 0.00172257*m.x302
+ 0.00682218*m.x303 == 0)
m.c121 = Constraint(expr= - m.x16 - 0.0184553*m.x204 + 0.0249277*m.x205 + 0.0119527*m.x206 + 0.0146671*m.x207
+ 0.0245199*m.x208 - 0.00168578*m.x209 + 0.0315032*m.x210 + 0.00079052*m.x211
+ 0.0567976*m.x212 - 0.00101702*m.x213 + 0.0380638*m.x214 + 0.0153153*m.x215
+ 0.00354749*m.x216 + 0.0484952*m.x217 + 0.216571*m.x218 + 0.0214552*m.x219 + 0.035258*m.x220
+ 0.00117393*m.x221 + 9.22617E-5*m.x222 - 0.00187826*m.x223 + 0.0118118*m.x224
+ 0.0252557*m.x225 + 0.00017817*m.x226 - 0.0141893*m.x227 + 0.0154338*m.x228
+ 0.0334612*m.x229 + 0.00975344*m.x230 - 0.00119135*m.x231 + 0.0146337*m.x232
+ 0.0371631*m.x233 + 0.0038431*m.x234 + 0.0207029*m.x235 + 0.0204577*m.x236 - 0.0031074*m.x237
+ 0.0124183*m.x238 + 0.0240257*m.x239 + 0.0441096*m.x240 + 0.0260726*m.x241
+ 0.00779136*m.x242 + 0.0194382*m.x243 + 0.0369654*m.x244 + 0.0154674*m.x245
+ 0.0140488*m.x246 + 0.0130156*m.x247 + 0.0104316*m.x248 + 0.0109843*m.x249
+ 0.00892909*m.x250 + 0.0139724*m.x251 + 0.0324222*m.x252 + 0.0258001*m.x253
+ 0.00536497*m.x254 - 0.0164481*m.x255 + 0.00992241*m.x256 + 0.0214377*m.x257
+ 0.0122468*m.x258 + 0.0297611*m.x259 + 0.0176119*m.x260 + 0.0115796*m.x261
- 0.00309314*m.x262 - 0.0165173*m.x263 + 0.0275152*m.x264 + 0.0464477*m.x265
+ 0.00779052*m.x266 - 0.0226061*m.x267 + 0.0267434*m.x268 + 0.0145246*m.x269
+ 0.00693016*m.x270 + 0.0360689*m.x271 + 0.0138448*m.x272 + 0.00553718*m.x273
+ 0.0203622*m.x274 + 0.00802954*m.x275 + 0.0162258*m.x276 + 0.0205116*m.x277
+ 0.0115061*m.x278 + 0.0101866*m.x279 + 0.0261645*m.x280 + 0.0332655*m.x281
+ 0.00110939*m.x282 + 0.0260692*m.x283 + 0.0012738*m.x284 + 0.0253402*m.x285
+ 0.0115293*m.x286 + 0.0157477*m.x287 + 0.0136669*m.x288 + 0.0102152*m.x289 + 0.0101419*m.x290
+ 0.0131187*m.x291 + 0.0171011*m.x292 + 0.0259854*m.x293 + 0.00869282*m.x294
+ 0.00673672*m.x295 + 0.0316891*m.x296 - 0.0156915*m.x297 + 0.0357759*m.x298
+ 0.0174851*m.x299 - 0.0063521*m.x300 - 0.0081262*m.x301 + 0.00733927*m.x302
+ 0.00484072*m.x303 == 0)
m.c122 = Constraint(expr= - m.x17 + 0.0279672*m.x204 + 0.0260539*m.x205 - 0.00454489*m.x206 + 0.0165581*m.x207
+ 0.0118447*m.x208 + 0.0459517*m.x209 + 0.0119617*m.x210 - 0.010629*m.x211 - 0.00262157*m.x212
- 0.00403718*m.x213 + 0.00700216*m.x214 - 0.0145985*m.x215 + 0.0146274*m.x216
+ 0.0195361*m.x217 + 0.0214552*m.x218 + 0.106718*m.x219 + 0.0174672*m.x220 + 0.0069313*m.x221
+ 0.00351107*m.x222 - 0.000894463*m.x223 - 0.00136425*m.x224 + 0.0125858*m.x225
+ 0.0161206*m.x226 + 0.00886365*m.x227 + 0.00490282*m.x228 + 0.00283525*m.x229
+ 0.00573587*m.x230 + 0.00932407*m.x231 + 0.0232678*m.x232 + 0.0251057*m.x233
- 0.0131257*m.x234 + 0.00951519*m.x235 + 0.00418042*m.x236 + 0.010377*m.x237
+ 0.00594827*m.x238 + 0.00260571*m.x239 + 0.00945499*m.x240 + 0.026132*m.x241
+ 0.0145947*m.x242 + 0.0107139*m.x243 + 0.0263189*m.x244 + 0.00760102*m.x245
+ 0.0184787*m.x246 + 0.010862*m.x247 + 0.0233605*m.x248 + 0.0254292*m.x249 + 0.026309*m.x250
+ 0.00373059*m.x251 + 0.0226732*m.x252 + 0.0151062*m.x253 + 0.00878227*m.x254
- 0.00659662*m.x255 + 0.00760297*m.x256 + 0.0166459*m.x257 + 0.00111556*m.x258
+ 0.0024162*m.x259 + 0.00726513*m.x260 + 0.032302*m.x261 - 0.000321415*m.x262
- 0.0027376*m.x263 + 0.0190897*m.x264 + 0.0346448*m.x265 + 0.0276531*m.x266
+ 0.000561195*m.x267 + 0.00605195*m.x268 + 0.0080424*m.x269 + 0.0117333*m.x270
+ 0.00873924*m.x271 + 0.0161705*m.x272 + 0.0227344*m.x273 + 0.0198156*m.x274
+ 0.0138875*m.x275 + 0.00149722*m.x276 + 0.0217898*m.x277 + 0.0236162*m.x278
+ 0.00886369*m.x279 + 0.0104275*m.x280 + 0.0249922*m.x281 + 0.00802207*m.x282
+ 0.00986454*m.x283 + 0.00924082*m.x284 + 0.00416101*m.x285 + 0.0228286*m.x286
+ 0.0243826*m.x287 + 0.0181062*m.x288 + 0.0141347*m.x289 + 0.0161554*m.x290 + 0.0142843*m.x291
+ 0.000969021*m.x292 + 0.0204454*m.x293 + 0.0180185*m.x294 + 0.00550125*m.x295
+ 0.0173229*m.x296 - 0.0118909*m.x297 + 0.00154333*m.x298 + 0.00648827*m.x299
- 0.00193745*m.x300 + 0.000983654*m.x301 + 0.0114558*m.x302 + 0.00327572*m.x303 == 0)
m.c123 = Constraint(expr= - m.x18 + 0.0347489*m.x204 + 0.0301066*m.x205 + 0.0070179*m.x206 + 0.0400276*m.x207
+ 0.0200262*m.x208 + 0.0104064*m.x209 + 0.00286605*m.x210 + 0.00272852*m.x211
- 0.00869213*m.x212 + 0.0075895*m.x213 + 0.0101168*m.x214 + 0.0120963*m.x215
+ 0.0180021*m.x216 + 0.024247*m.x217 + 0.035258*m.x218 + 0.0174672*m.x219 + 0.211469*m.x220
+ 0.0152764*m.x221 + 0.0236756*m.x222 + 0.0253815*m.x223 + 0.00488868*m.x224
+ 0.0163435*m.x225 + 0.0224046*m.x226 + 0.0114776*m.x227 + 0.0147622*m.x228 + 0.0168803*m.x229
- 0.0149916*m.x230 - 0.0110861*m.x231 + 0.00928934*m.x232 + 0.00769503*m.x233
- 0.0267594*m.x234 + 0.0083944*m.x235 + 0.0302366*m.x236 + 0.0261893*m.x237 + 0.013525*m.x238
+ 0.0268434*m.x239 + 0.0296532*m.x240 + 0.0116391*m.x241 + 0.00872571*m.x242
- 0.00545266*m.x243 + 0.0451888*m.x244 + 0.0174024*m.x245 + 0.0137917*m.x246
+ 0.00619143*m.x247 + 0.0353105*m.x248 + 0.0137663*m.x249 + 0.0126568*m.x250
+ 0.0131167*m.x251 + 0.0279086*m.x252 + 0.0187117*m.x253 + 0.0144307*m.x254
+ 0.00896247*m.x255 + 0.0230109*m.x256 + 0.0380049*m.x257 + 0.00594814*m.x258
+ 0.00156841*m.x259 + 0.0291383*m.x260 + 0.0197841*m.x261 - 0.00560644*m.x262
- 0.00570369*m.x263 + 0.0191435*m.x264 + 0.0154717*m.x265 + 0.0101111*m.x266
- 0.00546503*m.x267 + 0.0144737*m.x268 + 0.0137256*m.x269 + 0.0283908*m.x270
+ 0.0212112*m.x271 + 0.00924645*m.x272 + 0.038139*m.x273 + 0.00987474*m.x274
+ 0.0137739*m.x275 + 0.00346188*m.x276 + 0.018383*m.x277 + 0.0232466*m.x278 - 0.0111152*m.x279
- 0.000844745*m.x280 + 0.0332627*m.x281 + 0.0282131*m.x282 + 0.0233102*m.x283
- 0.00179937*m.x284 + 0.0144628*m.x285 + 0.0198321*m.x286 + 0.0080643*m.x287
+ 0.0113165*m.x288 + 0.0316648*m.x289 + 0.0143745*m.x290 + 0.0116517*m.x291
+ 0.00972696*m.x292 + 0.0132094*m.x293 + 0.0214788*m.x294 + 0.0108732*m.x295
+ 0.0316462*m.x296 - 0.0102103*m.x297 + 0.0284578*m.x298 + 0.0136054*m.x299 + 0.0283516*m.x300
- 0.0101858*m.x301 + 0.00777919*m.x302 + 0.00012158*m.x303 == 0)
m.c124 = Constraint(expr= - m.x19 + 0.0439735*m.x204 + 0.0272172*m.x205 - 0.0155243*m.x206 + 0.020625*m.x207
- 0.0135716*m.x208 - 0.000580239*m.x209 + 0.0229931*m.x210 - 0.00128164*m.x211
+ 0.00994931*m.x212 + 0.0372281*m.x213 + 0.0569711*m.x214 + 0.0333257*m.x215
+ 0.0288875*m.x216 + 0.0280244*m.x217 + 0.00117393*m.x218 + 0.0069313*m.x219
+ 0.0152764*m.x220 + 0.512899*m.x221 - 0.00554612*m.x222 + 0.0206016*m.x223
- 0.00982187*m.x224 + 0.00363825*m.x225 + 0.0232675*m.x226 - 0.000296286*m.x227
+ 0.0476329*m.x228 - 0.0197181*m.x229 + 0.0069109*m.x230 - 0.0189482*m.x231 + 0.0041263*m.x232
- 0.00884186*m.x233 + 0.000265289*m.x234 + 0.0138006*m.x235 - 0.00190656*m.x236
+ 0.0186477*m.x237 + 0.0209328*m.x238 - 0.0139724*m.x239 + 0.0376045*m.x240 + 0.0437592*m.x241
- 0.0223754*m.x242 + 0.0155505*m.x243 + 0.0318492*m.x244 + 0.00625964*m.x245
- 0.0212932*m.x246 + 0.00845798*m.x247 + 0.0602333*m.x248 + 0.0215291*m.x249
+ 0.000524806*m.x250 + 0.0502056*m.x251 + 0.0135373*m.x252 + 0.00412087*m.x253
- 0.00913314*m.x254 + 0.020479*m.x255 - 0.00154837*m.x256 + 0.0140183*m.x257
- 0.0157061*m.x258 + 0.0426323*m.x259 + 0.00626505*m.x260 + 0.00147777*m.x261
+ 0.0174915*m.x262 - 0.0106458*m.x263 - 0.0268525*m.x264 - 0.00592304*m.x265
+ 0.0265062*m.x266 - 0.0314803*m.x267 - 0.00113399*m.x268 - 0.00330446*m.x269
+ 0.0280983*m.x270 - 0.000715512*m.x271 + 0.0345476*m.x272 + 0.0640862*m.x273
+ 0.159324*m.x274 + 0.019995*m.x275 - 0.0150306*m.x276 + 0.0129312*m.x277 - 0.00349278*m.x278
+ 0.0610504*m.x279 + 0.00292058*m.x280 + 0.0234664*m.x281 - 0.0113617*m.x282
+ 0.0361401*m.x283 - 0.0108246*m.x284 + 0.0156378*m.x285 + 0.00137389*m.x286
- 0.0271238*m.x287 + 0.00450122*m.x288 + 0.0194887*m.x289 + 0.00448489*m.x290
+ 0.0154255*m.x291 - 0.00811765*m.x292 - 0.00385197*m.x293 - 0.00894921*m.x294
+ 0.0124411*m.x295 + 0.0222568*m.x296 + 0.05196*m.x297 + 0.000359792*m.x298 + 0.0473451*m.x299
+ 0.00195216*m.x300 - 0.0137668*m.x301 + 0.000840073*m.x302 + 0.0227501*m.x303 == 0)
m.c125 = Constraint(expr= - m.x20 - 0.0186044*m.x204 + 0.051374*m.x205 + 0.00154022*m.x206 + 0.0170646*m.x207
+ 0.0171357*m.x208 - 0.0192679*m.x209 - 0.0297937*m.x210 + 0.0092976*m.x211
+ 0.00711671*m.x212 - 0.0191596*m.x213 - 0.00537336*m.x214 - 0.0138778*m.x215
+ 0.0125621*m.x216 + 0.052103*m.x217 + 9.22617E-5*m.x218 + 0.00351107*m.x219
+ 0.0236756*m.x220 - 0.00554612*m.x221 + 1.47621*m.x222 - 0.00667053*m.x223
+ 0.00548936*m.x224 + 0.0134229*m.x225 - 0.00565979*m.x226 + 0.087054*m.x227
+ 0.0466708*m.x228 - 0.021498*m.x229 + 0.0145096*m.x230 + 0.0191174*m.x231 + 0.0170116*m.x232
+ 0.0266201*m.x233 - 0.00457471*m.x234 + 0.0324415*m.x235 - 0.0197364*m.x236
+ 0.00358424*m.x237 - 0.0174047*m.x238 + 0.00859465*m.x239 + 0.00102085*m.x240
+ 0.0207629*m.x241 + 0.00953252*m.x242 + 0.0229029*m.x243 + 0.0149903*m.x244
+ 0.0290781*m.x245 - 0.00449927*m.x246 + 0.0196626*m.x247 + 0.0720207*m.x248
+ 0.00312965*m.x249 + 0.0116736*m.x250 + 0.0683894*m.x251 + 0.021574*m.x252
- 0.00484013*m.x253 + 0.000594358*m.x254 - 0.0094595*m.x255 - 0.0318332*m.x256
+ 0.0316379*m.x257 + 0.0193443*m.x258 + 0.00259346*m.x259 + 0.019997*m.x260
- 0.00264326*m.x261 - 0.0162587*m.x262 - 0.00236544*m.x263 - 0.00879978*m.x264
- 0.0199739*m.x265 - 0.039269*m.x266 - 0.0186926*m.x267 + 0.0490725*m.x268 + 0.031858*m.x269
- 0.00221523*m.x270 + 0.0134724*m.x271 - 0.0102334*m.x272 + 0.0063437*m.x273
- 0.00607453*m.x274 + 0.0718984*m.x275 + 0.00984006*m.x276 - 0.00865423*m.x277
+ 0.0190688*m.x278 + 0.0249469*m.x279 + 0.00809967*m.x280 - 0.00269958*m.x281
- 0.0108567*m.x282 - 0.0246729*m.x283 + 0.030261*m.x284 - 0.0172947*m.x285 - 0.013192*m.x286
+ 0.0111854*m.x287 + 0.0114597*m.x288 + 0.0126843*m.x289 + 0.00210006*m.x290
+ 0.0549659*m.x291 + 0.00908995*m.x292 - 0.00445561*m.x293 - 0.0035093*m.x294
+ 0.0111934*m.x295 - 0.00595445*m.x296 + 0.00346376*m.x297 + 0.00938963*m.x298
+ 0.0125983*m.x299 + 0.0159186*m.x300 - 0.0256068*m.x301 + 0.00097566*m.x302
- 0.00691953*m.x303 == 0)
m.c126 = Constraint(expr= - m.x21 + 0.000382935*m.x204 + 0.0518153*m.x205 + 0.0125708*m.x206 + 0.0110715*m.x207
+ 0.0064231*m.x208 + 0.00573205*m.x209 - 0.00124776*m.x210 + 0.00897629*m.x211
+ 0.0652085*m.x212 - 0.00586128*m.x213 - 0.00676864*m.x214 + 0.0268692*m.x215
+ 0.0182642*m.x216 - 0.0075162*m.x217 - 0.00187826*m.x218 - 0.000894463*m.x219
+ 0.0253815*m.x220 + 0.0206016*m.x221 - 0.00667053*m.x222 + 0.502424*m.x223 + 0.0229683*m.x224
+ 0.0184159*m.x225 + 0.0119588*m.x226 + 0.0106382*m.x227 - 0.000494992*m.x228
+ 0.0131696*m.x229 + 0.000986151*m.x230 + 0.0141038*m.x231 + 0.0294696*m.x232
+ 0.0216055*m.x233 - 0.0119672*m.x234 + 0.00167869*m.x235 + 0.0241149*m.x236
+ 0.0114238*m.x237 - 0.00749631*m.x238 + 0.0126919*m.x239 - 0.0182367*m.x240
+ 0.00394727*m.x241 + 0.0421514*m.x242 + 0.00995652*m.x243 + 0.0111831*m.x244
+ 0.0348799*m.x245 - 0.0140575*m.x246 + 0.00499481*m.x247 + 0.0422832*m.x248
- 9.41833E-5*m.x249 - 0.00625035*m.x250 + 0.0135275*m.x251 - 0.00389379*m.x252
+ 0.0225012*m.x253 + 0.0108096*m.x254 + 0.0515904*m.x255 - 0.00645678*m.x256
- 0.0190381*m.x257 + 0.0138196*m.x258 - 0.0199045*m.x259 + 0.0230939*m.x260 + 0.0013091*m.x261
- 0.0175093*m.x262 + 0.0241302*m.x263 + 0.0125103*m.x264 + 0.0245635*m.x265 + 0.0207647*m.x266
- 0.0191503*m.x267 - 0.0052634*m.x268 + 0.00488365*m.x269 + 0.0136006*m.x270
- 0.00533096*m.x271 - 0.00725643*m.x272 + 0.0124666*m.x273 + 0.0367354*m.x274
+ 0.0182457*m.x275 + 0.00576651*m.x276 + 0.0355746*m.x277 + 0.023712*m.x278
+ 0.000684461*m.x279 - 0.00203509*m.x280 - 0.0114577*m.x281 - 0.0115916*m.x282
- 0.00776726*m.x283 - 0.010001*m.x284 + 0.000111057*m.x285 + 0.02061*m.x286 + 0.0103997*m.x287
+ 0.000675373*m.x288 + 0.0130083*m.x289 + 0.00539703*m.x290 + 0.0194179*m.x291
- 0.0052549*m.x292 - 0.00625738*m.x293 - 2.9997E-5*m.x294 + 0.0241985*m.x295
- 0.00345471*m.x296 + 0.0232975*m.x297 - 0.00383232*m.x298 - 0.000654628*m.x299
+ 0.00357173*m.x300 + 0.0350406*m.x301 + 0.00821698*m.x302 + 0.0156317*m.x303 == 0)
m.c127 = Constraint(expr= - m.x22 + 0.01102*m.x204 + 0.0043452*m.x205 + 0.0104609*m.x206 + 0.00747915*m.x207
+ 0.0108965*m.x208 - 0.00590063*m.x209 + 0.00819446*m.x210 - 0.0051429*m.x211
+ 0.0122233*m.x212 + 0.0131072*m.x213 - 0.000233965*m.x214 + 0.00636244*m.x215
+ 0.00895779*m.x216 - 0.0117391*m.x217 + 0.0118118*m.x218 - 0.00136425*m.x219
+ 0.00488868*m.x220 - 0.00982187*m.x221 + 0.00548936*m.x222 + 0.0229683*m.x223
+ 0.168624*m.x224 - 0.000890521*m.x225 + 0.0138206*m.x226 - 0.00374671*m.x227
+ 0.0124036*m.x228 + 0.00691469*m.x229 - 0.00519726*m.x230 - 0.00149288*m.x231
- 0.000893904*m.x232 - 0.000827347*m.x233 - 0.00369803*m.x234 + 0.0131454*m.x235
+ 0.00773376*m.x236 - 0.00297895*m.x237 + 0.0232383*m.x238 + 0.0229491*m.x239
- 0.00223419*m.x240 + 0.0203215*m.x241 + 0.00433463*m.x242 + 0.0171077*m.x243
- 0.0105983*m.x244 - 0.00372187*m.x245 - 0.00472458*m.x246 - 0.00195653*m.x247
+ 0.000456614*m.x248 + 0.00971748*m.x249 + 0.0122344*m.x250 - 0.023887*m.x251
+ 0.000162502*m.x252 + 0.00181967*m.x253 + 0.0068839*m.x254 + 0.00288958*m.x255
+ 0.0206887*m.x256 + 0.00659477*m.x257 - 0.00192784*m.x258 + 0.00381282*m.x259
+ 0.0130988*m.x260 + 0.0115547*m.x261 + 0.0146067*m.x262 + 0.0110104*m.x263 + 0.0023853*m.x264
+ 0.00213944*m.x265 + 0.0115639*m.x266 - 0.00246673*m.x267 + 0.0109023*m.x268
+ 0.00914522*m.x269 + 0.0180464*m.x270 - 0.00139956*m.x271 + 0.0063742*m.x272
- 0.0221093*m.x273 + 0.00993636*m.x274 + 0.0146925*m.x275 - 0.00160584*m.x276
- 0.00519309*m.x277 - 0.0141018*m.x278 + 0.0151075*m.x279 - 0.00436786*m.x280
+ 0.00467861*m.x281 + 0.0232455*m.x282 - 0.00329331*m.x283 - 0.000366056*m.x284
+ 0.0126412*m.x285 + 0.00320192*m.x286 - 0.0135153*m.x287 + 0.00126179*m.x288
+ 0.00970953*m.x289 - 0.00278401*m.x290 - 0.0110477*m.x291 + 0.0147706*m.x292
+ 0.00705238*m.x293 - 0.001978*m.x294 + 0.00955359*m.x295 + 0.0206419*m.x296
- 0.0195786*m.x297 + 0.0321854*m.x298 + 0.00830393*m.x299 + 0.0105133*m.x300
- 0.0266952*m.x301 + 0.00665696*m.x302 - 0.00571234*m.x303 == 0)
m.c128 = Constraint(expr= - m.x23 - 0.000128201*m.x204 + 0.066289*m.x205 + 0.145949*m.x206 - 0.00773408*m.x207
+ 0.0493937*m.x208 + 0.00118752*m.x209 + 0.0115835*m.x210 + 0.0194189*m.x211
- 0.0152003*m.x212 + 0.176793*m.x213 - 0.0053146*m.x214 - 0.0359516*m.x215 + 0.00895103*m.x216
+ 0.0581007*m.x217 + 0.0252557*m.x218 + 0.0125858*m.x219 + 0.0163435*m.x220
+ 0.00363825*m.x221 + 0.0134229*m.x222 + 0.0184159*m.x223 - 0.000890521*m.x224
+ 0.417419*m.x225 - 0.00289826*m.x226 + 0.00185106*m.x227 - 0.00344161*m.x228
+ 0.130367*m.x229 + 0.0228265*m.x230 + 0.0129488*m.x231 + 0.0412975*m.x232 + 0.0394092*m.x233
- 0.000460529*m.x234 + 0.0162175*m.x235 + 0.15033*m.x236 + 0.0103632*m.x237 + 0.0116646*m.x238
+ 0.00710012*m.x239 + 0.0212804*m.x240 + 0.00852316*m.x241 - 0.0215388*m.x242
+ 0.0180919*m.x243 + 0.0532482*m.x244 + 0.0406322*m.x245 - 0.0196231*m.x246
- 0.00111486*m.x247 + 0.086076*m.x248 + 0.00650857*m.x249 + 0.00551656*m.x250
+ 0.0234501*m.x251 - 0.00551305*m.x252 + 0.00168255*m.x253 - 0.0062463*m.x254
+ 0.00302148*m.x255 + 0.00339277*m.x256 + 0.00760958*m.x257 - 0.00714421*m.x258
+ 0.020719*m.x259 + 0.013493*m.x260 + 0.00400814*m.x261 - 0.00800908*m.x262 + 0.0239775*m.x263
+ 0.0023628*m.x264 + 0.041102*m.x265 + 0.0213565*m.x266 - 0.0313508*m.x267 + 0.0464899*m.x268
+ 0.0119209*m.x269 - 0.00311277*m.x270 + 0.0170407*m.x271 + 0.00635872*m.x272
+ 0.054717*m.x273 - 0.0107438*m.x274 + 0.00163408*m.x275 - 0.0203875*m.x276
- 0.00266029*m.x277 + 0.0137259*m.x278 + 0.0378261*m.x279 + 0.0152157*m.x280
+ 0.0169622*m.x281 - 0.00218688*m.x282 + 0.0252382*m.x283 + 0.0510044*m.x284
+ 0.0140353*m.x285 + 0.00976413*m.x286 + 0.0121898*m.x287 + 0.00257907*m.x288
+ 0.00858432*m.x289 - 0.00136755*m.x290 + 0.031019*m.x291 + 0.0172111*m.x292
+ 0.00272478*m.x293 - 0.000689796*m.x294 - 0.0132155*m.x295 - 0.0122813*m.x296
- 0.0179837*m.x297 - 0.0115174*m.x298 + 0.0545863*m.x299 + 0.0401891*m.x300 + 0.0297056*m.x301
+ 0.00722685*m.x302 + 0.0243685*m.x303 == 0)
m.c129 = Constraint(expr= - m.x24 + 0.0136055*m.x204 + 0.000519585*m.x205 - 0.0019853*m.x206 + 0.0277694*m.x207
+ 0.0194761*m.x208 + 0.0146083*m.x209 - 0.00151625*m.x210 + 0.00807556*m.x211
+ 0.0251098*m.x212 + 0.032372*m.x213 + 0.0128605*m.x214 - 0.00319962*m.x215
- 0.00232932*m.x216 + 0.00789376*m.x217 + 0.00017817*m.x218 + 0.0161206*m.x219
+ 0.0224046*m.x220 + 0.0232675*m.x221 - 0.00565979*m.x222 + 0.0119588*m.x223
+ 0.0138206*m.x224 - 0.00289826*m.x225 + 0.169013*m.x226 + 0.0220253*m.x227 + 0.0240871*m.x228
- 0.00322614*m.x229 + 0.0123559*m.x230 - 0.00108112*m.x231 + 0.00851439*m.x232
+ 0.00888525*m.x233 + 0.0104685*m.x234 + 0.0294179*m.x235 + 0.00544491*m.x236
+ 0.0403128*m.x237 + 0.019178*m.x238 + 0.0110456*m.x239 + 0.0039145*m.x240 + 0.0223593*m.x241
+ 0.0170012*m.x242 + 0.0208848*m.x243 + 0.00735012*m.x244 + 0.038773*m.x245 + 0.0242748*m.x246
+ 0.0111032*m.x247 - 0.00263182*m.x248 + 0.0168949*m.x249 + 0.0118048*m.x250
+ 0.0540289*m.x251 + 0.0155506*m.x252 + 0.0101127*m.x253 + 0.0135526*m.x254
+ 0.00456304*m.x255 + 0.00172033*m.x256 + 0.00174846*m.x257 + 0.0155517*m.x258
+ 0.00739069*m.x259 + 0.0279297*m.x260 + 0.0501498*m.x261 + 0.00507925*m.x262
+ 0.018196*m.x263 + 0.011861*m.x264 + 0.016458*m.x265 + 0.0113615*m.x266 - 0.00261119*m.x267
+ 0.0194988*m.x268 + 0.0159019*m.x269 + 0.0101301*m.x270 + 0.00719955*m.x271
+ 0.00758332*m.x272 + 0.00284196*m.x273 - 0.00558828*m.x274 + 0.0130101*m.x275
+ 0.00531061*m.x276 + 0.0106016*m.x277 + 0.0218053*m.x278 + 0.0181907*m.x279
+ 0.00963458*m.x280 + 0.00597376*m.x281 + 0.00648587*m.x282 + 0.0276238*m.x283
+ 0.0170493*m.x284 + 0.00242329*m.x285 - 0.0146684*m.x286 + 0.0212922*m.x287
+ 0.0327354*m.x288 + 0.0202473*m.x289 + 0.0242836*m.x290 + 0.00470611*m.x291
+ 0.0256701*m.x292 + 0.0286405*m.x293 + 0.00175624*m.x294 + 0.00904265*m.x295
+ 0.0101954*m.x296 + 0.00334169*m.x297 + 0.0120672*m.x298 - 0.00247613*m.x299
+ 0.00811643*m.x300 + 0.00451179*m.x301 + 0.0116179*m.x302 + 0.0132863*m.x303 == 0)
m.c130 = Constraint(expr= - m.x25 - 0.00847303*m.x204 - 0.00046168*m.x205 - 0.00879835*m.x206 + 0.00589594*m.x207
+ 0.00935395*m.x208 + 0.00976886*m.x209 - 0.0108978*m.x210 + 0.014474*m.x211
+ 0.00797425*m.x212 - 0.0206317*m.x213 + 0.00379938*m.x214 - 0.00863008*m.x215
+ 0.00177054*m.x216 + 0.0404865*m.x217 - 0.0141893*m.x218 + 0.00886365*m.x219
+ 0.0114776*m.x220 - 0.000296286*m.x221 + 0.087054*m.x222 + 0.0106382*m.x223
- 0.00374671*m.x224 + 0.00185106*m.x225 + 0.0220253*m.x226 + 0.205934*m.x227
+ 0.0290006*m.x228 - 0.00265519*m.x229 - 0.00469608*m.x230 + 0.0117576*m.x231
- 0.00041031*m.x232 + 0.0142087*m.x233 + 0.00223982*m.x234 + 0.00329632*m.x235
+ 0.00133736*m.x236 + 0.012366*m.x237 + 0.018724*m.x238 + 0.0082014*m.x239 + 0.0129307*m.x240
+ 0.0126422*m.x241 + 0.0488014*m.x242 + 0.0119438*m.x243 + 0.0120642*m.x244 + 0.0054971*m.x245
+ 0.0104361*m.x246 + 0.00451121*m.x247 - 0.0148276*m.x248 + 0.00531801*m.x249
+ 0.00527699*m.x250 + 0.00749425*m.x251 + 0.00218243*m.x252 + 0.00995275*m.x253
+ 0.0138831*m.x254 + 0.0179012*m.x255 + 0.00828721*m.x256 + 0.00342253*m.x257
+ 0.0144765*m.x258 + 0.030732*m.x259 + 0.0159408*m.x260 + 0.00458005*m.x261 - 0.0105654*m.x262
- 0.0022915*m.x263 + 0.0289602*m.x264 + 0.0145756*m.x265 + 4.79134E-5*m.x266
- 0.00267369*m.x267 + 0.00284388*m.x268 + 0.00640165*m.x269 + 0.00361398*m.x270
+ 0.0012624*m.x271 + 0.000823775*m.x272 - 0.00175507*m.x273 + 0.00806781*m.x274
- 0.00744934*m.x275 + 0.00473186*m.x276 + 0.0148345*m.x277 + 0.0291503*m.x278
+ 0.0126589*m.x279 + 0.00774713*m.x280 - 0.00678133*m.x281 - 0.000483346*m.x282
+ 0.00185776*m.x283 + 0.0211536*m.x284 - 0.00255587*m.x285 - 0.00832251*m.x286
+ 0.00243227*m.x287 + 0.000359588*m.x288 + 0.0204891*m.x289 + 0.0292669*m.x290
+ 0.0163439*m.x291 - 0.00379038*m.x292 - 0.00181686*m.x293 + 0.0125924*m.x294
+ 0.0294016*m.x295 + 0.014454*m.x296 + 0.00907196*m.x297 - 0.0155799*m.x298
- 0.000311276*m.x299 + 0.0367786*m.x300 - 0.0255962*m.x301 + 0.0136226*m.x302
+ 0.0209203*m.x303 == 0)
m.c131 = Constraint(expr= - m.x26 + 0.00772976*m.x204 + 0.00154905*m.x205 - 0.0114691*m.x206 + 0.00860339*m.x207
+ 0.00691311*m.x208 + 0.0122717*m.x209 + 0.00119563*m.x210 - 0.00996885*m.x211
+ 0.00371891*m.x212 + 0.0116962*m.x213 + 0.0202337*m.x214 + 0.0341934*m.x215
+ 0.0136257*m.x216 + 0.0065787*m.x217 + 0.0154338*m.x218 + 0.00490282*m.x219
+ 0.0147622*m.x220 + 0.0476329*m.x221 + 0.0466708*m.x222 - 0.000494992*m.x223
+ 0.0124036*m.x224 - 0.00344161*m.x225 + 0.0240871*m.x226 + 0.0290006*m.x227 + 0.165225*m.x228
- 0.00824969*m.x229 - 0.00255141*m.x230 + 0.0167987*m.x231 + 0.0266266*m.x232
+ 0.00715524*m.x233 + 0.0182101*m.x234 + 0.0126245*m.x235 - 0.0157858*m.x236
+ 0.0116227*m.x237 + 0.00350129*m.x238 - 0.00059745*m.x239 + 0.0252965*m.x240
+ 0.0251092*m.x241 - 0.00438159*m.x242 + 0.00928707*m.x243 + 0.013037*m.x244
- 0.00212582*m.x245 - 0.00808877*m.x246 + 0.00365229*m.x247 + 0.00411288*m.x248
+ 0.00931093*m.x249 + 0.0122374*m.x250 + 0.022339*m.x251 + 0.0160754*m.x252
+ 0.00927056*m.x253 - 0.00153332*m.x254 - 0.00274677*m.x255 + 0.011526*m.x256
+ 9.44861E-5*m.x257 + 0.0205903*m.x258 + 0.0219997*m.x259 + 0.0126357*m.x260
+ 0.0335534*m.x261 + 0.009157*m.x262 + 0.0103454*m.x263 + 0.00485118*m.x264 + 0.0191232*m.x265
+ 0.0224758*m.x266 + 0.00227773*m.x267 + 0.00710476*m.x268 + 0.00283558*m.x269
- 0.00150208*m.x270 + 0.0113113*m.x271 + 0.0160374*m.x272 + 0.0206604*m.x273
+ 0.0321612*m.x274 + 0.0164707*m.x275 - 0.00467826*m.x276 + 0.0091414*m.x277 + 0.019493*m.x278
- 0.00130846*m.x279 + 0.00402512*m.x280 + 0.0148477*m.x281 + 0.00831527*m.x282
- 0.00269199*m.x283 - 0.00146575*m.x284 + 0.00519983*m.x285 + 0.00563734*m.x286
- 0.0022015*m.x287 + 0.0164738*m.x288 + 0.0095043*m.x289 + 0.0194659*m.x290
+ 0.00940805*m.x291 - 0.00459271*m.x292 + 0.00697339*m.x293 - 0.00111199*m.x294
- 0.0171837*m.x295 + 0.00427236*m.x296 - 0.0133342*m.x297 + 0.0159789*m.x298
+ 0.0137361*m.x299 + 0.00616904*m.x300 - 0.0154329*m.x301 + 0.000498937*m.x302
+ 0.0264262*m.x303 == 0)
m.c132 = Constraint(expr= - m.x27 - 0.0295372*m.x204 + 0.0654627*m.x205 + 0.183686*m.x206 - 0.0245255*m.x207
+ 0.00811154*m.x208 + 0.015996*m.x209 + 0.00380145*m.x210 + 0.0499867*m.x211
- 0.00148049*m.x212 + 0.0856918*m.x213 + 0.0295931*m.x214 - 0.0214998*m.x215
+ 0.0032049*m.x216 + 0.0280359*m.x217 + 0.0334612*m.x218 + 0.00283525*m.x219
+ 0.0168803*m.x220 - 0.0197181*m.x221 - 0.021498*m.x222 + 0.0131696*m.x223 + 0.00691469*m.x224
+ 0.130367*m.x225 - 0.00322614*m.x226 - 0.00265519*m.x227 - 0.00824969*m.x228
+ 0.298039*m.x229 + 0.0146416*m.x230 - 0.0165239*m.x231 + 0.0375322*m.x232 + 0.00943115*m.x233
+ 0.0238879*m.x234 + 0.00785478*m.x235 + 0.0940611*m.x236 + 0.0163858*m.x237
- 0.0339757*m.x238 + 0.00813864*m.x239 + 0.0259598*m.x240 + 0.00820718*m.x241
- 0.00872187*m.x242 - 0.000343349*m.x243 + 0.0493071*m.x244 + 0.0191453*m.x245
+ 0.000222699*m.x246 - 0.00906245*m.x247 + 0.0126082*m.x248 - 0.0137446*m.x249
- 0.00568651*m.x250 - 0.00050512*m.x251 + 0.00295003*m.x252 + 0.0130362*m.x253
- 0.0100498*m.x254 + 0.0373415*m.x255 + 0.00554618*m.x256 + 0.0074701*m.x257
- 0.00778581*m.x258 + 0.0251306*m.x259 - 0.00245187*m.x260 - 0.00390438*m.x261
- 0.0316484*m.x262 + 0.0136876*m.x263 - 0.000726206*m.x264 + 0.0163476*m.x265
+ 0.00918681*m.x266 - 0.0125721*m.x267 + 0.0319031*m.x268 + 0.0180154*m.x269
- 0.00293849*m.x270 + 0.0370056*m.x271 - 0.0102022*m.x272 + 0.0059304*m.x273
+ 0.00317033*m.x274 - 0.00173148*m.x275 - 0.00926362*m.x276 - 0.0118778*m.x277
- 0.0065822*m.x278 + 0.00460217*m.x279 + 0.0200371*m.x280 + 0.0155593*m.x281
- 0.0144053*m.x282 - 0.0110697*m.x283 + 0.0217421*m.x284 + 0.0203773*m.x285
+ 0.00705351*m.x286 + 0.0171599*m.x287 - 0.001325*m.x288 + 0.00618414*m.x289 - 0.010655*m.x290
+ 0.0287315*m.x291 + 0.0267179*m.x292 - 0.0133302*m.x293 - 0.00269826*m.x294
- 0.0321221*m.x295 + 0.0256948*m.x296 - 0.0250774*m.x297 - 0.00835702*m.x298
+ 0.0620713*m.x299 + 0.0267618*m.x300 + 0.00732044*m.x301 + 0.0133219*m.x302
+ 0.0208839*m.x303 == 0)
m.c133 = Constraint(expr= - m.x28 - 0.00761416*m.x204 + 0.0180154*m.x205 + 0.0420925*m.x206 - 0.0103474*m.x207
+ 0.0217094*m.x208 + 0.0262883*m.x209 + 0.01388*m.x210 - 0.0180156*m.x211 + 0.0193177*m.x212
+ 0.0056902*m.x213 + 0.00286184*m.x214 - 0.00165983*m.x215 + 0.00927708*m.x216
+ 0.0284398*m.x217 + 0.00975344*m.x218 + 0.00573587*m.x219 - 0.0149916*m.x220
+ 0.0069109*m.x221 + 0.0145096*m.x222 + 0.000986151*m.x223 - 0.00519726*m.x224
+ 0.0228265*m.x225 + 0.0123559*m.x226 - 0.00469608*m.x227 - 0.00255141*m.x228
+ 0.0146416*m.x229 + 0.181643*m.x230 + 0.00593554*m.x231 + 0.0123054*m.x232 + 0.0131968*m.x233
+ 0.00359959*m.x234 + 0.0208179*m.x235 + 0.00164146*m.x236 + 0.0220766*m.x237
+ 0.0271537*m.x238 + 0.00684948*m.x239 + 0.00794658*m.x240 + 0.00864852*m.x241
- 0.00387113*m.x242 + 0.00676815*m.x243 + 0.0107582*m.x244 + 0.0282272*m.x245
+ 0.00730286*m.x246 - 0.0033586*m.x247 + 0.0351761*m.x248 + 0.00249494*m.x249
+ 0.0142173*m.x250 - 0.00543891*m.x251 - 0.00806152*m.x252 + 0.00341299*m.x253
- 0.00785713*m.x254 + 0.00317892*m.x255 + 0.0107528*m.x256 - 0.00906739*m.x257
+ 0.00425862*m.x258 + 0.00867625*m.x259 - 0.0023455*m.x260 + 0.00967889*m.x261
+ 0.00396363*m.x262 + 0.0431392*m.x263 + 0.0248388*m.x264 + 0.0208145*m.x265
- 0.0164721*m.x266 - 0.0223038*m.x267 + 0.0536968*m.x268 + 0.0222226*m.x269
- 0.00759212*m.x270 - 0.0161031*m.x271 - 0.00658237*m.x272 + 0.000576553*m.x273
+ 0.00804996*m.x274 - 0.00609273*m.x275 + 0.00484259*m.x276 + 0.0142463*m.x277
+ 0.00113796*m.x278 + 0.0109937*m.x279 + 0.0229961*m.x280 + 0.0124417*m.x281
+ 0.0367225*m.x282 - 0.0100286*m.x283 + 0.0358544*m.x284 + 0.00154206*m.x285
- 0.00258881*m.x286 + 0.0316383*m.x287 + 0.0170355*m.x288 + 0.000376344*m.x289
+ 0.0139374*m.x290 + 0.0275472*m.x291 + 0.0215472*m.x292 + 0.00487961*m.x293
+ 0.00165055*m.x294 - 0.00879465*m.x295 - 0.00601501*m.x296 - 0.0151708*m.x297
+ 0.0709325*m.x298 + 0.0366289*m.x299 + 0.000218956*m.x300 + 0.0460118*m.x301
+ 0.0341929*m.x302 - 0.00140343*m.x303 == 0)
m.c134 = Constraint(expr= - m.x29 - 4.24721E-5*m.x204 + 0.00649144*m.x205 + 0.0250886*m.x206 + 0.0274283*m.x207
+ 0.00509551*m.x208 + 0.0364425*m.x209 + 0.018817*m.x210 + 0.0369786*m.x211 + 0.050764*m.x212
+ 0.00180131*m.x213 + 0.0124339*m.x214 + 0.011631*m.x215 + 0.0260767*m.x216 + 0.0143595*m.x217
- 0.00119135*m.x218 + 0.00932407*m.x219 - 0.0110861*m.x220 - 0.0189482*m.x221
+ 0.0191174*m.x222 + 0.0141038*m.x223 - 0.00149288*m.x224 + 0.0129488*m.x225
- 0.00108112*m.x226 + 0.0117576*m.x227 + 0.0167987*m.x228 - 0.0165239*m.x229
+ 0.00593554*m.x230 + 0.260779*m.x231 - 0.0113531*m.x232 + 0.018462*m.x233 + 0.0575173*m.x234
+ 0.0068875*m.x235 + 0.00143503*m.x236 + 0.00410057*m.x237 + 0.00810772*m.x238
+ 0.0103469*m.x239 + 0.0289389*m.x240 + 0.0184668*m.x241 + 0.0107871*m.x242
+ 0.00920594*m.x243 + 0.0213098*m.x244 - 0.00379119*m.x245 + 0.0175626*m.x246
+ 0.00298817*m.x247 + 0.0054897*m.x248 + 0.00838146*m.x249 + 0.00738842*m.x250
+ 0.0443024*m.x251 - 0.00363873*m.x252 - 0.0276809*m.x253 + 0.00664334*m.x254
+ 0.00813124*m.x255 + 0.00525742*m.x256 + 0.015111*m.x257 + 0.0266351*m.x258
+ 0.0408723*m.x259 - 0.000700731*m.x260 + 0.00840972*m.x261 + 0.00252738*m.x262
+ 0.0676544*m.x263 + 0.01361*m.x264 + 0.010551*m.x265 - 0.00205468*m.x266 - 0.00837042*m.x267
+ 0.0198054*m.x268 + 0.0122407*m.x269 + 0.00412582*m.x270 + 0.0114679*m.x271
+ 0.0149085*m.x272 + 0.00320993*m.x273 + 0.00437204*m.x274 + 0.0185225*m.x275
+ 0.00426479*m.x276 - 0.0182268*m.x277 + 0.0156633*m.x278 - 0.0108916*m.x279
+ 0.0130582*m.x280 + 0.00465652*m.x281 - 0.000979902*m.x282 + 0.0258383*m.x283
+ 0.045075*m.x284 + 0.0236369*m.x285 + 0.0486461*m.x286 + 0.0157696*m.x287 + 0.0196175*m.x288
+ 0.00775608*m.x289 + 0.00139924*m.x290 + 0.000402288*m.x291 - 0.000836245*m.x292
+ 0.00367641*m.x293 - 0.0247945*m.x294 + 0.00750897*m.x295 + 0.00220324*m.x296
+ 0.00583633*m.x297 + 0.00119846*m.x298 - 0.0223825*m.x299 + 0.030938*m.x300
+ 0.0193729*m.x301 + 0.0100684*m.x302 + 0.00790278*m.x303 == 0)
m.c135 = Constraint(expr= - m.x30 - 0.00459597*m.x204 + 0.147396*m.x205 + 0.138133*m.x206 + 0.0223035*m.x207
+ 0.0102365*m.x208 + 0.0587967*m.x209 + 0.00271468*m.x210 - 0.0326873*m.x211
- 0.0288765*m.x212 + 0.0296162*m.x213 + 0.031981*m.x214 - 0.00843246*m.x215 - 0.0166592*m.x216
- 0.00772267*m.x217 + 0.0146337*m.x218 + 0.0232678*m.x219 + 0.00928934*m.x220
+ 0.0041263*m.x221 + 0.0170116*m.x222 + 0.0294696*m.x223 - 0.000893904*m.x224
+ 0.0412975*m.x225 + 0.00851439*m.x226 - 0.00041031*m.x227 + 0.0266266*m.x228
+ 0.0375322*m.x229 + 0.0123054*m.x230 - 0.0113531*m.x231 + 0.480672*m.x232
+ 0.000623588*m.x233 + 0.0310361*m.x234 - 0.011947*m.x235 + 0.0559217*m.x236
- 6.19624E-5*m.x237 - 0.0111159*m.x238 + 0.00214151*m.x239 - 0.00311936*m.x240
+ 0.0198678*m.x241 - 0.0274884*m.x242 - 0.00536695*m.x243 - 0.00621657*m.x244
+ 0.00759718*m.x245 - 0.0114733*m.x246 + 0.00536671*m.x247 + 0.00229741*m.x248
- 0.000669481*m.x249 + 0.0101225*m.x250 + 0.00629643*m.x251 + 0.00338529*m.x252
+ 0.00481268*m.x253 + 0.00636725*m.x254 + 0.0177429*m.x255 - 0.00438567*m.x256
- 0.00680131*m.x257 + 0.0104672*m.x258 - 0.00397893*m.x259 - 0.00363432*m.x260
+ 0.0101807*m.x261 - 0.0100285*m.x262 + 0.0068697*m.x263 + 0.0418921*m.x264
- 0.00534991*m.x265 - 0.0119127*m.x266 - 0.00152064*m.x267 + 0.0221966*m.x268
+ 0.0135936*m.x269 + 0.0218822*m.x270 - 0.0103847*m.x271 + 0.0192043*m.x272
+ 0.00830569*m.x273 - 0.00295904*m.x274 - 0.0141201*m.x275 + 0.000576517*m.x276
+ 0.0218241*m.x277 + 0.0288367*m.x278 + 0.00589724*m.x279 + 0.00723834*m.x280
- 0.0101934*m.x281 + 0.0299367*m.x282 - 0.00142157*m.x283 + 0.0157699*m.x284
- 0.00224841*m.x285 - 0.000196592*m.x286 - 0.00344939*m.x287 + 0.00552353*m.x288
- 0.00394771*m.x289 + 0.0357841*m.x290 + 0.00160462*m.x291 + 0.0130927*m.x292
+ 0.00657462*m.x293 + 0.0120928*m.x294 + 0.00756116*m.x295 + 0.00893784*m.x296
- 0.00747816*m.x297 + 0.00341049*m.x298 + 0.104347*m.x299 + 0.0194493*m.x300
- 0.00520844*m.x301 + 0.00369624*m.x302 + 0.0310417*m.x303 == 0)
m.c136 = Constraint(expr= - m.x31 + 0.00232022*m.x204 + 0.0126159*m.x205 + 0.0278877*m.x206 + 0.0237512*m.x207
+ 0.0598964*m.x208 + 0.00678878*m.x209 + 0.0130573*m.x210 - 0.00929421*m.x211
- 0.000566519*m.x212 + 0.0209429*m.x213 + 0.0177141*m.x214 + 0.0122534*m.x215
+ 0.0328492*m.x216 + 0.0146342*m.x217 + 0.0371631*m.x218 + 0.0251057*m.x219
+ 0.00769503*m.x220 - 0.00884186*m.x221 + 0.0266201*m.x222 + 0.0216055*m.x223
- 0.000827347*m.x224 + 0.0394092*m.x225 + 0.00888525*m.x226 + 0.0142087*m.x227
+ 0.00715524*m.x228 + 0.00943115*m.x229 + 0.0131968*m.x230 + 0.018462*m.x231
+ 0.000623588*m.x232 + 0.137262*m.x233 - 0.000370023*m.x234 + 0.0232111*m.x235
+ 0.0166258*m.x236 + 0.0140534*m.x237 + 0.0279772*m.x238 + 0.0139362*m.x239 + 0.0114782*m.x240
+ 0.0271294*m.x241 + 0.0231833*m.x242 + 0.0144716*m.x243 + 0.00178633*m.x244
+ 0.0573692*m.x245 + 0.0552261*m.x246 + 0.0161599*m.x247 + 0.00526805*m.x248
+ 0.00015225*m.x249 + 0.0278298*m.x250 + 0.0489272*m.x251 + 0.0300688*m.x252
+ 0.0188471*m.x253 + 0.00180223*m.x254 + 0.0269342*m.x255 + 0.0137397*m.x256
+ 0.00116831*m.x257 + 0.00270328*m.x258 + 0.0137686*m.x259 + 0.017504*m.x260
+ 0.0185947*m.x261 - 0.0233244*m.x262 + 0.00418422*m.x263 + 0.0090785*m.x264
+ 0.00995839*m.x265 + 0.0128665*m.x266 + 0.00262393*m.x267 + 0.0238425*m.x268
+ 0.0205163*m.x269 + 0.000443199*m.x270 + 0.0116392*m.x271 + 0.0183888*m.x272
+ 0.0157507*m.x273 + 0.011888*m.x274 + 0.0342241*m.x275 + 0.00771843*m.x276 + 0.021456*m.x277
+ 0.0151258*m.x278 + 0.0375829*m.x279 + 0.0243902*m.x280 + 0.0306235*m.x281 + 0.0131912*m.x282
- 0.00933997*m.x283 + 0.0198755*m.x284 + 0.0218691*m.x285 + 0.01283*m.x286 + 0.0304352*m.x287
+ 0.0336786*m.x288 + 0.00419472*m.x289 + 0.0326227*m.x290 + 0.0179917*m.x291
+ 0.00648866*m.x292 + 0.00140866*m.x293 + 0.00503874*m.x294 + 0.010448*m.x295
+ 0.0187694*m.x296 - 0.0111273*m.x297 + 0.013655*m.x298 + 0.0137759*m.x299 + 0.0225411*m.x300
- 0.0033488*m.x301 + 0.031476*m.x302 + 0.0123762*m.x303 == 0)
m.c137 = Constraint(expr= - m.x32 + 0.0509778*m.x204 + 0.0114801*m.x205 + 0.0545798*m.x206 + 0.0068636*m.x207
+ 0.000151401*m.x208 + 0.0132248*m.x209 - 0.00937181*m.x210 + 0.00932232*m.x211
- 0.00504625*m.x212 - 0.00927325*m.x213 + 0.0133593*m.x214 + 0.0201667*m.x215
+ 0.0117288*m.x216 + 0.00596413*m.x217 + 0.0038431*m.x218 - 0.0131257*m.x219
- 0.0267594*m.x220 + 0.000265289*m.x221 - 0.00457471*m.x222 - 0.0119672*m.x223
- 0.00369803*m.x224 - 0.000460529*m.x225 + 0.0104685*m.x226 + 0.00223982*m.x227
+ 0.0182101*m.x228 + 0.0238879*m.x229 + 0.00359959*m.x230 + 0.0575173*m.x231
+ 0.0310361*m.x232 - 0.000370023*m.x233 + 0.533349*m.x234 + 0.0257786*m.x235
- 0.00098694*m.x236 + 0.0558495*m.x237 + 0.0276478*m.x238 - 0.00168632*m.x239
+ 0.0152586*m.x240 + 0.00483299*m.x241 + 0.047323*m.x242 + 0.0195771*m.x243
- 0.000954098*m.x244 - 0.00045278*m.x245 - 0.00389567*m.x246 - 0.0062901*m.x247
+ 0.0361137*m.x248 + 0.00188213*m.x249 + 0.0105383*m.x250 + 0.0312435*m.x251
+ 0.00612172*m.x252 + 0.02564*m.x253 - 0.00360195*m.x254 + 0.0141086*m.x255 + 0.0367283*m.x256
+ 0.00320485*m.x257 - 0.0033721*m.x258 + 0.0182858*m.x259 - 0.0042177*m.x260
- 0.00092753*m.x261 + 0.00894155*m.x262 + 0.0454908*m.x263 + 0.0349551*m.x264
+ 0.0343384*m.x265 + 0.00879992*m.x266 - 0.00543751*m.x267 + 0.04327*m.x268 + 0.0141045*m.x269
- 0.00442873*m.x270 + 0.0329931*m.x271 + 0.00515876*m.x272 - 0.0196528*m.x273
- 0.0113905*m.x274 + 0.0445692*m.x275 + 0.00858179*m.x276 + 0.00833241*m.x277
- 0.00293272*m.x278 + 0.00601459*m.x279 + 0.00788825*m.x280 + 0.00317889*m.x281
- 0.00540247*m.x282 + 0.016911*m.x283 + 0.0317363*m.x284 + 0.00773321*m.x285 + 0.016704*m.x286
- 0.0141682*m.x287 + 0.0109291*m.x288 + 0.00776229*m.x289 - 0.0170139*m.x290
- 0.00984516*m.x291 + 0.00481705*m.x292 - 0.0055852*m.x293 - 0.00360636*m.x294
- 0.000266747*m.x295 + 0.00272322*m.x296 - 0.0135944*m.x297 - 0.0102535*m.x298
+ 0.0378678*m.x299 - 0.0155415*m.x300 + 0.00593378*m.x301 + 0.012364*m.x302 + 0.0241458*m.x303
== 0)
m.c138 = Constraint(expr= - m.x33 - 0.0156482*m.x204 + 0.00607166*m.x205 - 0.0090554*m.x206 + 0.0216305*m.x207
+ 0.0314895*m.x208 + 0.0117136*m.x209 + 0.0135407*m.x210 - 0.00128122*m.x211
- 0.0193402*m.x212 + 0.0316756*m.x213 + 0.0484803*m.x214 + 0.0115615*m.x215 + 0.0189044*m.x216
+ 0.000301534*m.x217 + 0.0207029*m.x218 + 0.00951519*m.x219 + 0.0083944*m.x220
+ 0.0138006*m.x221 + 0.0324415*m.x222 + 0.00167869*m.x223 + 0.0131454*m.x224
+ 0.0162175*m.x225 + 0.0294179*m.x226 + 0.00329632*m.x227 + 0.0126245*m.x228
+ 0.00785478*m.x229 + 0.0208179*m.x230 + 0.0068875*m.x231 - 0.011947*m.x232 + 0.0232111*m.x233
+ 0.0257786*m.x234 + 0.257028*m.x235 + 0.0147429*m.x236 + 0.00827753*m.x237 + 0.0183637*m.x238
+ 0.0108656*m.x239 + 0.0158994*m.x240 + 0.0222541*m.x241 + 0.0149035*m.x242
+ 0.00955212*m.x243 + 0.0478221*m.x244 + 0.0176484*m.x245 + 0.00428146*m.x246
+ 0.0067698*m.x247 + 0.00746688*m.x248 + 0.0224318*m.x249 + 0.00853378*m.x250
+ 0.00553395*m.x251 + 0.0306636*m.x252 + 0.0264708*m.x253 + 0.0366567*m.x254
- 0.00105083*m.x255 + 0.00408317*m.x256 - 0.0130126*m.x257 + 0.00691299*m.x258
+ 0.0230993*m.x259 + 0.0192279*m.x260 + 0.0119446*m.x261 + 0.0224351*m.x262 + 0.022391*m.x263
+ 0.0160624*m.x264 - 0.00427316*m.x265 + 0.00900964*m.x266 - 0.00432735*m.x267
+ 0.0397561*m.x268 + 0.00466481*m.x269 + 0.0123178*m.x270 + 0.0294165*m.x271
+ 0.00210584*m.x272 + 0.0156664*m.x273 + 0.0141543*m.x274 + 0.00715561*m.x275
+ 0.0136809*m.x276 + 0.000970616*m.x277 + 0.0221044*m.x278 + 0.0127205*m.x279
+ 0.0153277*m.x280 + 0.0189992*m.x281 + 0.0023179*m.x282 + 0.0192297*m.x283 + 0.0186293*m.x284
+ 0.0497975*m.x285 + 0.00488326*m.x286 + 0.0420958*m.x287 + 0.0926409*m.x288
- 0.000832904*m.x289 + 0.00842344*m.x290 + 0.0178015*m.x291 - 0.00668788*m.x292
+ 0.00142361*m.x293 + 0.0199408*m.x294 + 0.030029*m.x295 - 0.000706121*m.x296
+ 0.0120762*m.x297 + 0.0417235*m.x298 + 0.0169276*m.x299 + 0.0024374*m.x300 - 0.0096037*m.x301
+ 0.00722129*m.x302 + 0.018823*m.x303 == 0)
m.c139 = Constraint(expr= - m.x34 + 0.0162671*m.x204 + 0.0404381*m.x205 + 0.138583*m.x206 - 0.00303771*m.x207
+ 0.0222037*m.x208 - 0.00958286*m.x209 - 0.00205201*m.x210 + 0.0044504*m.x211
- 0.012241*m.x212 + 0.155782*m.x213 - 0.00479808*m.x214 - 0.0151645*m.x215 - 0.0303469*m.x216
+ 0.0135036*m.x217 + 0.0204577*m.x218 + 0.00418042*m.x219 + 0.0302366*m.x220
- 0.00190656*m.x221 - 0.0197364*m.x222 + 0.0241149*m.x223 + 0.00773376*m.x224 + 0.15033*m.x225
+ 0.00544491*m.x226 + 0.00133736*m.x227 - 0.0157858*m.x228 + 0.0940611*m.x229
+ 0.00164146*m.x230 + 0.00143503*m.x231 + 0.0559217*m.x232 + 0.0166258*m.x233
- 0.00098694*m.x234 + 0.0147429*m.x235 + 0.333103*m.x236 + 0.00824671*m.x237
+ 0.0501698*m.x238 + 0.000271976*m.x239 + 0.0187592*m.x240 + 0.013158*m.x241
- 0.00871004*m.x242 + 0.00801758*m.x243 + 0.0116152*m.x244 + 0.030594*m.x245
+ 0.0215083*m.x246 - 0.000673256*m.x247 - 0.00492434*m.x248 - 0.00146448*m.x249
+ 0.00882459*m.x250 + 0.0565808*m.x251 - 0.00265594*m.x252 - 0.0131072*m.x253
- 0.0185973*m.x254 + 0.00879757*m.x255 - 0.00320472*m.x256 - 0.0046504*m.x257
- 0.0112877*m.x258 + 0.0388425*m.x259 - 0.00375455*m.x260 + 1.76484E-5*m.x261
+ 0.0261447*m.x262 + 0.0421239*m.x263 - 0.00545796*m.x264 + 0.0164325*m.x265
+ 0.00365749*m.x266 - 0.0388477*m.x267 + 0.0381643*m.x268 + 0.0228523*m.x269 + 0.012621*m.x270
+ 0.032511*m.x271 + 0.0106022*m.x272 + 0.0149868*m.x273 - 0.00272959*m.x274 - 0.0084707*m.x275
- 0.016164*m.x276 + 0.0222678*m.x277 - 0.0154847*m.x278 + 0.00339709*m.x279 + 0.0202853*m.x280
- 0.0276747*m.x281 + 0.00131595*m.x282 - 0.0112676*m.x283 + 0.0194651*m.x284
- 0.000432208*m.x285 + 0.00548514*m.x286 + 0.0171493*m.x287 + 0.0191037*m.x288
+ 0.00214285*m.x289 + 0.0066923*m.x290 - 0.0250217*m.x291 + 0.0258152*m.x292
- 0.00246468*m.x293 + 0.0138925*m.x294 + 0.00427117*m.x295 + 0.0100517*m.x296
- 0.0267599*m.x297 - 0.00630875*m.x298 + 0.00112457*m.x299 + 0.0190696*m.x300
+ 0.0196793*m.x301 + 0.0119806*m.x302 + 0.0371377*m.x303 == 0)
m.c140 = Constraint(expr= - m.x35 - 0.0132302*m.x204 - 0.00899911*m.x205 + 0.0150959*m.x206 + 0.0013176*m.x207
+ 0.0226771*m.x208 + 0.059318*m.x209 + 0.0110361*m.x210 + 0.0154868*m.x211 + 0.0162554*m.x212
+ 0.0111882*m.x213 + 0.04212*m.x214 + 0.00572447*m.x215 - 0.00624871*m.x216 + 0.0145204*m.x217
- 0.0031074*m.x218 + 0.010377*m.x219 + 0.0261893*m.x220 + 0.0186477*m.x221 + 0.00358424*m.x222
+ 0.0114238*m.x223 - 0.00297895*m.x224 + 0.0103632*m.x225 + 0.0403128*m.x226 + 0.012366*m.x227
+ 0.0116227*m.x228 + 0.0163858*m.x229 + 0.0220766*m.x230 + 0.00410057*m.x231
- 6.19624E-5*m.x232 + 0.0140534*m.x233 + 0.0558495*m.x234 + 0.00827753*m.x235
+ 0.00824671*m.x236 + 0.391729*m.x237 + 0.0264733*m.x238 + 0.0134141*m.x239
- 0.00225583*m.x240 + 0.0317362*m.x241 - 0.00594899*m.x242 + 0.0316434*m.x243
+ 0.00798554*m.x244 + 0.020323*m.x245 + 0.00080856*m.x246 + 0.0158673*m.x247
+ 0.0139875*m.x248 + 0.00964636*m.x249 + 0.0135777*m.x250 + 0.0103222*m.x251
+ 0.00664455*m.x252 + 0.0426453*m.x253 + 0.014965*m.x254 - 0.0255534*m.x255 + 0.0104359*m.x256
+ 0.0058258*m.x257 + 0.0144468*m.x258 + 0.012515*m.x259 + 0.00320118*m.x260
- 0.000227592*m.x261 + 0.0223779*m.x262 + 0.00773196*m.x263 + 0.00267723*m.x264
- 0.00201299*m.x265 + 0.0224861*m.x266 - 0.0272888*m.x267 + 0.0102053*m.x268
+ 0.00464414*m.x269 + 0.0165262*m.x270 + 0.0099305*m.x271 + 0.000867918*m.x272
+ 0.00439394*m.x273 + 0.0178982*m.x274 + 0.0495734*m.x275 + 0.00617492*m.x276
+ 0.0124231*m.x277 + 0.0252473*m.x278 + 0.058582*m.x279 + 0.00629356*m.x280 - 0.001499*m.x281
+ 0.0143475*m.x282 - 0.00386864*m.x283 + 0.00970643*m.x284 + 0.0171804*m.x285
- 0.0153224*m.x286 + 0.00145169*m.x287 + 0.0165018*m.x288 + 0.0080802*m.x289
+ 0.0297617*m.x290 + 0.00416104*m.x291 + 0.00696121*m.x292 - 0.00477706*m.x293
+ 0.024389*m.x294 + 0.0151776*m.x295 - 0.00263518*m.x296 - 0.0223564*m.x297
+ 0.00104505*m.x298 + 0.0433625*m.x299 + 0.00802342*m.x300 + 0.0485713*m.x301
+ 0.0032333*m.x302 + 0.0332113*m.x303 == 0)
m.c141 = Constraint(expr= - m.x36 + 0.0250776*m.x204 - 0.00165809*m.x205 + 0.0162039*m.x206 + 0.0157544*m.x207
+ 0.0271938*m.x208 + 0.0162948*m.x209 - 0.00849477*m.x210 - 0.00246393*m.x211
- 0.0167425*m.x212 + 0.0301704*m.x213 + 0.0157963*m.x214 - 0.000867997*m.x215
- 0.00552184*m.x216 + 0.0624288*m.x217 + 0.0124183*m.x218 + 0.00594827*m.x219
+ 0.013525*m.x220 + 0.0209328*m.x221 - 0.0174047*m.x222 - 0.00749631*m.x223 + 0.0232383*m.x224
+ 0.0116646*m.x225 + 0.019178*m.x226 + 0.018724*m.x227 + 0.00350129*m.x228 - 0.0339757*m.x229
+ 0.0271537*m.x230 + 0.00810772*m.x231 - 0.0111159*m.x232 + 0.0279772*m.x233
+ 0.0276478*m.x234 + 0.0183637*m.x235 + 0.0501698*m.x236 + 0.0264733*m.x237 + 0.352371*m.x238
+ 0.0267802*m.x239 + 0.00740748*m.x240 + 0.0210208*m.x241 + 0.0371907*m.x242
+ 0.0185657*m.x243 + 0.00134719*m.x244 + 0.0357548*m.x245 + 0.000503105*m.x246
- 0.00504028*m.x247 + 0.0628923*m.x248 + 0.0158934*m.x249 + 0.0095123*m.x250
+ 0.00894769*m.x251 + 0.0126674*m.x252 - 0.00759544*m.x253 + 0.000920465*m.x254
+ 0.0125861*m.x255 - 0.00390865*m.x256 + 0.00253837*m.x257 + 0.0021617*m.x258
+ 0.00289448*m.x259 + 0.00470079*m.x260 - 0.000123939*m.x261 - 0.00572274*m.x262
+ 0.00812701*m.x263 - 0.00120612*m.x264 + 0.0192903*m.x265 + 0.0176128*m.x266
- 0.0403434*m.x267 + 0.00674116*m.x268 + 0.00290841*m.x269 + 0.0214671*m.x270
+ 0.00882407*m.x271 + 0.00182329*m.x272 + 0.0121867*m.x273 - 0.00471575*m.x274
+ 0.0180724*m.x275 + 0.0215306*m.x276 + 0.020355*m.x277 + 0.0180883*m.x278 + 0.0462503*m.x279
+ 0.0139857*m.x280 + 0.00783656*m.x281 - 0.010913*m.x282 - 0.0111746*m.x283 - 0.0212839*m.x284
+ 0.0109154*m.x285 - 0.00737614*m.x286 + 0.00226631*m.x287 + 0.0273084*m.x288
+ 0.0165011*m.x289 + 0.0353459*m.x290 + 0.00602501*m.x291 + 0.00280658*m.x292
+ 0.0141143*m.x293 - 0.0138066*m.x294 + 0.00103245*m.x295 + 0.0131295*m.x296
- 0.00507596*m.x297 + 0.037088*m.x298 - 0.0155039*m.x299 + 0.0401269*m.x300
- 0.00474519*m.x301 + 0.0102928*m.x302 + 0.0227151*m.x303 == 0)
m.c142 = Constraint(expr= - m.x37 - 0.0120527*m.x204 + 0.0142276*m.x205 + 0.0213625*m.x206 + 0.0168579*m.x207
+ 0.0166563*m.x208 + 0.0161974*m.x209 + 0.00439244*m.x210 - 0.00850907*m.x211
+ 0.00537524*m.x212 + 0.00605787*m.x213 + 0.00983178*m.x214 + 0.0114198*m.x215
+ 0.0151253*m.x216 + 0.0136456*m.x217 + 0.0240257*m.x218 + 0.00260571*m.x219
+ 0.0268434*m.x220 - 0.0139724*m.x221 + 0.00859465*m.x222 + 0.0126919*m.x223
+ 0.0229491*m.x224 + 0.00710012*m.x225 + 0.0110456*m.x226 + 0.0082014*m.x227
- 0.00059745*m.x228 + 0.00813864*m.x229 + 0.00684948*m.x230 + 0.0103469*m.x231
+ 0.00214151*m.x232 + 0.0139362*m.x233 - 0.00168632*m.x234 + 0.0108656*m.x235
+ 0.000271976*m.x236 + 0.0134141*m.x237 + 0.0267802*m.x238 + 0.175181*m.x239
- 0.00486027*m.x240 + 0.0103664*m.x241 - 0.000849903*m.x242 + 0.0119433*m.x243
+ 0.0210135*m.x244 + 0.0143453*m.x245 - 0.00292769*m.x246 + 0.014697*m.x247 + 0.0159248*m.x248
+ 0.0267699*m.x249 + 0.0109654*m.x250 + 0.0152969*m.x251 - 0.00705335*m.x252
+ 0.0069801*m.x253 - 0.00905371*m.x254 + 0.0143571*m.x255 + 0.0151841*m.x256
+ 0.0144667*m.x257 + 0.00865979*m.x258 + 0.00669218*m.x259 + 0.0128782*m.x260
- 0.00508847*m.x261 - 0.0146124*m.x262 + 0.0225587*m.x263 + 0.00526915*m.x264
+ 0.0180621*m.x265 - 0.00562995*m.x266 + 0.00935786*m.x267 + 0.0359849*m.x268
+ 0.00335704*m.x269 - 0.00719511*m.x270 + 0.017117*m.x271 + 0.00398062*m.x272
+ 0.0225777*m.x273 + 0.00892359*m.x274 + 0.0452262*m.x275 - 0.00767906*m.x276
+ 0.00992303*m.x277 - 0.0114508*m.x278 + 0.0197029*m.x279 + 0.00438907*m.x280
+ 0.0231162*m.x281 - 0.000788038*m.x282 + 0.0115195*m.x283 + 0.0165997*m.x284
+ 0.00247635*m.x285 + 0.00203383*m.x286 + 0.0149245*m.x287 + 0.00360648*m.x288
- 0.00766884*m.x289 + 0.0174822*m.x290 + 0.0127497*m.x291 + 0.000594747*m.x292
+ 0.0173728*m.x293 - 0.012529*m.x294 - 0.00810868*m.x295 + 0.0296006*m.x296 - 0.0055076*m.x297
- 0.000573198*m.x298 + 0.018767*m.x299 + 0.011041*m.x300 - 0.0114838*m.x301
+ 0.00268364*m.x302 + 0.0211458*m.x303 == 0)
m.c143 = Constraint(expr= - m.x38 + 0.0138503*m.x204 + 0.0344086*m.x205 + 0.0200764*m.x206 + 0.0319483*m.x207
+ 0.0185838*m.x208 + 0.00634078*m.x209 + 0.0127402*m.x210 + 0.010305*m.x211
- 0.00325532*m.x212 + 0.00922974*m.x213 + 0.0208788*m.x214 + 0.0218247*m.x215
+ 0.00196396*m.x216 + 0.0353273*m.x217 + 0.0441096*m.x218 + 0.00945499*m.x219
+ 0.0296532*m.x220 + 0.0376045*m.x221 + 0.00102085*m.x222 - 0.0182367*m.x223
- 0.00223419*m.x224 + 0.0212804*m.x225 + 0.0039145*m.x226 + 0.0129307*m.x227
+ 0.0252965*m.x228 + 0.0259598*m.x229 + 0.00794658*m.x230 + 0.0289389*m.x231
- 0.00311936*m.x232 + 0.0114782*m.x233 + 0.0152586*m.x234 + 0.0158994*m.x235
+ 0.0187592*m.x236 - 0.00225583*m.x237 + 0.00740748*m.x238 - 0.00486027*m.x239
+ 0.157789*m.x240 + 0.0262122*m.x241 + 0.00601169*m.x242 + 0.0119122*m.x243 + 0.0335948*m.x244
+ 0.0206336*m.x245 - 0.00897797*m.x246 - 0.0109459*m.x247 + 0.0170251*m.x248
+ 0.00864687*m.x249 + 0.00178605*m.x250 + 0.0216947*m.x251 + 0.0089316*m.x252
+ 0.0141917*m.x253 + 0.0171861*m.x254 + 0.0129119*m.x255 + 0.0235719*m.x256 + 0.0176837*m.x257
+ 0.00165906*m.x258 + 0.0824428*m.x259 + 0.0133704*m.x260 + 0.0137969*m.x261
+ 0.00197565*m.x262 + 0.0284788*m.x263 + 0.0192414*m.x264 + 0.0212005*m.x265
+ 0.0139235*m.x266 - 0.0180328*m.x267 + 0.0362249*m.x268 + 0.0194911*m.x269
- 0.00221392*m.x270 + 0.0224423*m.x271 + 0.00992082*m.x272 + 0.0236908*m.x273
+ 0.0163609*m.x274 + 0.0173916*m.x275 + 0.0271333*m.x276 + 0.0101687*m.x277 + 0.0167448*m.x278
+ 0.0145376*m.x279 + 0.0123315*m.x280 + 0.0119314*m.x281 + 0.0158911*m.x282 + 0.0101661*m.x283
+ 0.0257734*m.x284 + 0.0177688*m.x285 + 0.0138653*m.x286 - 0.00986807*m.x287
+ 0.0188003*m.x288 + 0.0172113*m.x289 + 0.0182402*m.x290 + 0.0285576*m.x291
- 0.00228211*m.x292 + 0.00194986*m.x293 + 0.00780586*m.x294 + 0.0298143*m.x295
+ 0.0316103*m.x296 - 0.0168264*m.x297 + 0.00133433*m.x298 + 0.0320353*m.x299
+ 0.0433973*m.x300 - 0.0108392*m.x301 + 0.00751702*m.x302 - 0.00144612*m.x303 == 0)
m.c144 = Constraint(expr= - m.x39 + 0.0174032*m.x204 + 0.0192482*m.x205 - 0.00431381*m.x206 + 0.0489611*m.x207
+ 0.0240307*m.x208 + 0.0120533*m.x209 + 0.0166285*m.x210 - 0.0107958*m.x211 + 0.0143804*m.x212
+ 0.00186503*m.x213 + 0.0260342*m.x214 + 0.0164584*m.x215 + 0.0283164*m.x216 + 0.016403*m.x217
+ 0.0260726*m.x218 + 0.026132*m.x219 + 0.0116391*m.x220 + 0.0437592*m.x221 + 0.0207629*m.x222
+ 0.00394727*m.x223 + 0.0203215*m.x224 + 0.00852316*m.x225 + 0.0223593*m.x226
+ 0.0126422*m.x227 + 0.0251092*m.x228 + 0.00820718*m.x229 + 0.00864852*m.x230
+ 0.0184668*m.x231 + 0.0198678*m.x232 + 0.0271294*m.x233 + 0.00483299*m.x234
+ 0.0222541*m.x235 + 0.013158*m.x236 + 0.0317362*m.x237 + 0.0210208*m.x238 + 0.0103664*m.x239
+ 0.0262122*m.x240 + 0.126617*m.x241 + 0.00918889*m.x242 + 0.00789765*m.x243
+ 0.0134287*m.x244 + 0.0335529*m.x245 + 0.00544385*m.x246 + 0.0105749*m.x247
- 0.00422865*m.x248 + 0.0165157*m.x249 + 0.0153668*m.x250 + 0.000861128*m.x251
+ 0.0256051*m.x252 + 0.0422426*m.x253 - 0.000803595*m.x254 + 0.00351671*m.x255
+ 0.0145538*m.x256 + 0.0131903*m.x257 + 0.00498598*m.x258 + 0.0347475*m.x259
+ 0.0244545*m.x260 + 0.0126796*m.x261 + 0.018523*m.x262 + 0.00388717*m.x263 + 0.020429*m.x264
+ 0.0233626*m.x265 + 0.00698084*m.x266 + 0.00155564*m.x267 + 0.00767128*m.x268
+ 0.0118559*m.x269 + 0.0189483*m.x270 + 0.0125617*m.x271 + 0.0165632*m.x272 + 0.0205214*m.x273
+ 0.0195565*m.x274 + 0.000493166*m.x275 + 0.0113544*m.x276 + 0.0130662*m.x277
+ 0.0237854*m.x278 + 0.0180646*m.x279 + 0.00659785*m.x280 + 0.019254*m.x281 + 0.0146391*m.x282
+ 0.0146836*m.x283 + 0.0134395*m.x284 + 0.0310356*m.x285 + 0.00956021*m.x286
+ 0.00391649*m.x287 + 0.037188*m.x288 + 0.0264564*m.x289 + 0.011678*m.x290 + 0.0335903*m.x291
+ 0.0133091*m.x292 + 0.0154967*m.x293 + 0.000594082*m.x294 + 0.0384969*m.x295
+ 0.0132003*m.x296 - 0.00324796*m.x297 + 0.0198875*m.x298 + 0.00123223*m.x299
+ 0.0178267*m.x300 - 0.00475543*m.x301 + 0.0129675*m.x302 + 0.00875978*m.x303 == 0)
m.c145 = Constraint(expr= - m.x40 + 0.0141194*m.x204 + 0.0223002*m.x205 - 0.00842299*m.x206 + 0.0165915*m.x207
- 0.00254427*m.x208 + 0.000742111*m.x209 + 0.0264399*m.x210 + 0.0184062*m.x211
+ 0.0540646*m.x212 - 0.0204732*m.x213 + 0.00898847*m.x214 + 0.0324793*m.x215
- 7.36214E-5*m.x216 + 0.0178385*m.x217 + 0.00779136*m.x218 + 0.0145947*m.x219
+ 0.00872571*m.x220 - 0.0223754*m.x221 + 0.00953252*m.x222 + 0.0421514*m.x223
+ 0.00433463*m.x224 - 0.0215388*m.x225 + 0.0170012*m.x226 + 0.0488014*m.x227
- 0.00438159*m.x228 - 0.00872187*m.x229 - 0.00387113*m.x230 + 0.0107871*m.x231
- 0.0274884*m.x232 + 0.0231833*m.x233 + 0.047323*m.x234 + 0.0149035*m.x235 - 0.00871004*m.x236
- 0.00594899*m.x237 + 0.0371907*m.x238 - 0.000849903*m.x239 + 0.00601169*m.x240
+ 0.00918889*m.x241 + 0.335076*m.x242 + 0.0124578*m.x243 + 0.0212803*m.x244
+ 0.00373452*m.x245 + 0.0252208*m.x246 - 0.0070303*m.x247 + 0.0675517*m.x248
- 0.0217225*m.x249 + 0.00424885*m.x250 + 0.00522672*m.x251 + 0.0111003*m.x252
+ 0.0034425*m.x253 - 0.0131086*m.x254 + 0.0891112*m.x255 + 0.0358926*m.x256 + 0.0274205*m.x257
+ 0.00568814*m.x258 - 0.00209651*m.x259 + 0.00931511*m.x260 - 0.00153738*m.x261
- 0.0039206*m.x262 + 0.0154733*m.x263 + 0.034914*m.x264 + 0.0149224*m.x265 + 0.0117364*m.x266
+ 0.00189931*m.x267 - 0.000952693*m.x268 + 0.00134611*m.x269 - 0.000237938*m.x270
+ 0.0043024*m.x271 - 0.0220684*m.x272 - 0.0319066*m.x273 + 0.00870017*m.x274
+ 0.0205621*m.x275 + 0.006158*m.x276 - 0.00856733*m.x277 + 0.0207092*m.x278 + 0.0123219*m.x279
+ 0.00161026*m.x280 + 0.0140309*m.x281 + 0.0311598*m.x282 + 0.0145619*m.x283
+ 0.0141748*m.x284 + 0.00619315*m.x285 - 0.00370778*m.x286 + 0.00148966*m.x287
- 0.00287831*m.x288 + 0.00458259*m.x289 + 0.0137472*m.x290 + 0.0189174*m.x291
- 0.00318997*m.x292 - 0.0127847*m.x293 + 0.00325109*m.x294 + 0.0175238*m.x295
+ 0.0105851*m.x296 + 0.0218937*m.x297 + 0.0120314*m.x298 + 0.0247783*m.x299 + 0.0295261*m.x300
- 0.0120001*m.x301 + 0.00121728*m.x302 - 0.00249785*m.x303 == 0)
m.c146 = Constraint(expr= - m.x41 + 0.0227987*m.x204 + 0.012791*m.x205 - 0.00117286*m.x206 + 0.0104514*m.x207
+ 0.0207655*m.x208 + 0.0218172*m.x209 + 0.0100685*m.x210 - 0.000823765*m.x211
+ 0.00225673*m.x212 - 0.00336318*m.x213 + 0.0194251*m.x214 + 0.0165224*m.x215
+ 0.0154669*m.x216 + 0.0349872*m.x217 + 0.0194382*m.x218 + 0.0107139*m.x219
- 0.00545266*m.x220 + 0.0155505*m.x221 + 0.0229029*m.x222 + 0.00995652*m.x223
+ 0.0171077*m.x224 + 0.0180919*m.x225 + 0.0208848*m.x226 + 0.0119438*m.x227
+ 0.00928707*m.x228 - 0.000343349*m.x229 + 0.00676815*m.x230 + 0.00920594*m.x231
- 0.00536695*m.x232 + 0.0144716*m.x233 + 0.0195771*m.x234 + 0.00955212*m.x235
+ 0.00801758*m.x236 + 0.0316434*m.x237 + 0.0185657*m.x238 + 0.0119433*m.x239
+ 0.0119122*m.x240 + 0.00789765*m.x241 + 0.0124578*m.x242 + 0.109635*m.x243 + 0.0153443*m.x244
+ 0.0259479*m.x245 - 0.00169431*m.x246 + 0.0128324*m.x247 + 0.0130568*m.x248
+ 0.00834641*m.x249 + 0.0233526*m.x250 + 0.00754003*m.x251 + 0.00962683*m.x252
+ 0.0131857*m.x253 - 0.00149067*m.x254 + 0.000467774*m.x255 + 0.0104228*m.x256
+ 0.00959745*m.x257 + 0.0216421*m.x258 + 0.0118242*m.x259 + 0.0207329*m.x260
+ 0.0150648*m.x261 - 0.00613654*m.x262 + 0.0074099*m.x263 + 0.0159826*m.x264
+ 0.0065965*m.x265 + 0.0154181*m.x266 + 0.00135221*m.x267 + 0.00855652*m.x268
+ 0.0195004*m.x269 + 0.013074*m.x270 + 0.0246559*m.x271 + 0.00174793*m.x272
- 0.00079277*m.x273 + 0.00677241*m.x274 + 0.017246*m.x275 + 0.0147256*m.x276
+ 0.0179741*m.x277 + 0.0247003*m.x278 + 0.0450965*m.x279 + 0.0172805*m.x280 + 0.0209097*m.x281
+ 0.011441*m.x282 + 0.0219237*m.x283 + 0.00710912*m.x284 + 8.9584E-5*m.x285
+ 0.00608136*m.x286 + 0.0200781*m.x287 + 0.0170146*m.x288 + 0.0215022*m.x289
+ 0.00958774*m.x290 + 0.0218437*m.x291 + 0.0058466*m.x292 + 0.0163626*m.x293
+ 0.00109195*m.x294 + 0.016576*m.x295 + 0.0121524*m.x296 + 0.0114468*m.x297 + 0.0229932*m.x298
+ 0.0274591*m.x299 + 0.0170962*m.x300 - 0.0143186*m.x301 + 0.00875979*m.x302
+ 0.00792635*m.x303 == 0)
m.c147 = Constraint(expr= - m.x42 + 0.0193746*m.x204 + 0.0190131*m.x205 + 0.00911691*m.x206 + 0.0116238*m.x207
+ 0.0197923*m.x208 - 0.00438877*m.x209 + 0.00274108*m.x210 + 0.0132777*m.x211
+ 0.0124663*m.x212 + 0.0130752*m.x213 + 0.0124203*m.x214 - 0.0110707*m.x215 + 0.0335265*m.x216
+ 0.0452332*m.x217 + 0.0369654*m.x218 + 0.0263189*m.x219 + 0.0451888*m.x220 + 0.0318492*m.x221
+ 0.0149903*m.x222 + 0.0111831*m.x223 - 0.0105983*m.x224 + 0.0532482*m.x225
+ 0.00735012*m.x226 + 0.0120642*m.x227 + 0.013037*m.x228 + 0.0493071*m.x229 + 0.0107582*m.x230
+ 0.0213098*m.x231 - 0.00621657*m.x232 + 0.00178633*m.x233 - 0.000954098*m.x234
+ 0.0478221*m.x235 + 0.0116152*m.x236 + 0.00798554*m.x237 + 0.00134719*m.x238
+ 0.0210135*m.x239 + 0.0335948*m.x240 + 0.0134287*m.x241 + 0.0212803*m.x242 + 0.0153443*m.x243
+ 0.472248*m.x244 + 0.00685165*m.x245 + 0.0126097*m.x246 - 0.00520594*m.x247
+ 0.0641494*m.x248 - 0.00275487*m.x249 + 0.009426*m.x250 + 0.0377236*m.x251 + 0.0273291*m.x252
+ 0.0239811*m.x253 + 0.00578221*m.x254 + 0.0121199*m.x255 - 0.00778263*m.x256
+ 0.0206125*m.x257 - 0.00233532*m.x258 + 0.037583*m.x259 + 0.0180524*m.x260 + 0.0438692*m.x261
+ 0.0261745*m.x262 - 0.0114466*m.x263 + 0.019726*m.x264 + 0.0217904*m.x265 - 0.0131236*m.x266
+ 0.00012462*m.x267 + 0.0111129*m.x268 - 0.00456618*m.x269 + 0.00494008*m.x270
+ 0.0375735*m.x271 - 0.0151984*m.x272 + 0.112574*m.x273 + 0.0185572*m.x274 + 0.0762045*m.x275
- 0.00779475*m.x276 + 0.0295755*m.x277 + 0.00943287*m.x278 + 0.0286273*m.x279
+ 0.00989437*m.x280 + 0.0238402*m.x281 + 0.00383314*m.x282 - 0.00120741*m.x283
- 0.000663857*m.x284 + 0.00556998*m.x285 - 0.00367056*m.x286 + 0.0290197*m.x287
+ 0.0308391*m.x288 + 0.0431137*m.x289 + 0.012869*m.x290 - 0.040724*m.x291 + 0.0241297*m.x292
+ 0.00261203*m.x293 + 0.0174076*m.x294 + 0.0155538*m.x295 + 0.0118422*m.x296
+ 0.0140178*m.x297 + 0.0167384*m.x298 + 0.0447304*m.x299 + 0.0519824*m.x300
+ 0.00580577*m.x301 + 0.012385*m.x302 + 0.0180453*m.x303 == 0)
m.c148 = Constraint(expr= - m.x43 + 0.0242182*m.x204 + 6.63459E-5*m.x205 - 0.00746052*m.x206 + 0.0187021*m.x207
+ 0.0613911*m.x208 + 0.0402544*m.x209 + 0.00935881*m.x210 + 0.00103676*m.x211
- 0.00398651*m.x212 + 0.0383614*m.x213 + 0.00730049*m.x214 + 0.0108339*m.x215
+ 0.0247389*m.x216 + 0.0258405*m.x217 + 0.0154674*m.x218 + 0.00760102*m.x219
+ 0.0174024*m.x220 + 0.00625964*m.x221 + 0.0290781*m.x222 + 0.0348799*m.x223
- 0.00372187*m.x224 + 0.0406322*m.x225 + 0.038773*m.x226 + 0.0054971*m.x227
- 0.00212582*m.x228 + 0.0191453*m.x229 + 0.0282272*m.x230 - 0.00379119*m.x231
+ 0.00759718*m.x232 + 0.0573692*m.x233 - 0.00045278*m.x234 + 0.0176484*m.x235
+ 0.030594*m.x236 + 0.020323*m.x237 + 0.0357548*m.x238 + 0.0143453*m.x239 + 0.0206336*m.x240
+ 0.0335529*m.x241 + 0.00373452*m.x242 + 0.0259479*m.x243 + 0.00685165*m.x244
+ 0.173324*m.x245 + 0.00435369*m.x246 + 0.0112326*m.x247 + 0.0300354*m.x248
+ 0.00838204*m.x249 + 0.0230848*m.x250 + 0.011347*m.x251 + 0.021257*m.x252 + 0.0308057*m.x253
+ 0.00779234*m.x254 + 0.0336911*m.x255 + 0.0131565*m.x256 + 0.0127459*m.x257
+ 0.00581905*m.x258 + 0.0246255*m.x259 + 0.0224446*m.x260 - 0.0172843*m.x261
- 0.00143913*m.x262 + 0.0179142*m.x263 + 0.00496924*m.x264 + 0.012034*m.x265
- 0.00248961*m.x266 - 0.00825333*m.x267 + 0.02346*m.x268 + 0.02262*m.x269 + 0.00735435*m.x270
+ 0.00373612*m.x271 + 0.0174021*m.x272 - 0.0101958*m.x273 - 0.0047133*m.x274
- 0.00607984*m.x275 + 0.00938905*m.x276 + 0.00171904*m.x277 + 0.0195252*m.x278
+ 0.0383478*m.x279 + 0.0224169*m.x280 + 0.0385198*m.x281 + 0.0274691*m.x282 - 0.0267822*m.x283
+ 0.0309656*m.x284 + 0.0175453*m.x285 + 0.0338365*m.x286 + 0.0150021*m.x287 + 0.0486356*m.x288
+ 0.0180063*m.x289 + 0.0225774*m.x290 + 0.0434221*m.x291 + 0.0276431*m.x292 + 0.0182416*m.x293
+ 0.00868526*m.x294 + 0.013908*m.x295 + 0.0117221*m.x296 - 0.00373821*m.x297
+ 0.0089429*m.x298 + 0.0223685*m.x299 + 0.00186956*m.x300 - 0.000502651*m.x301
+ 0.0174325*m.x302 + 0.0334254*m.x303 == 0)
m.c149 = Constraint(expr= - m.x44 + 0.0115852*m.x204 - 0.0244053*m.x205 - 0.011358*m.x206 + 0.0150923*m.x207
+ 0.0110642*m.x208 - 0.00602825*m.x209 + 0.0225873*m.x210 - 0.00519952*m.x211
+ 0.0396497*m.x212 - 0.0030681*m.x213 + 0.0250217*m.x214 + 0.00496455*m.x215
+ 0.000832224*m.x216 + 0.0200869*m.x217 + 0.0140488*m.x218 + 0.0184787*m.x219
+ 0.0137917*m.x220 - 0.0212932*m.x221 - 0.00449927*m.x222 - 0.0140575*m.x223
- 0.00472458*m.x224 - 0.0196231*m.x225 + 0.0242748*m.x226 + 0.0104361*m.x227
- 0.00808877*m.x228 + 0.000222699*m.x229 + 0.00730286*m.x230 + 0.0175626*m.x231
- 0.0114733*m.x232 + 0.0552261*m.x233 - 0.00389567*m.x234 + 0.00428146*m.x235
+ 0.0215083*m.x236 + 0.00080856*m.x237 + 0.000503105*m.x238 - 0.00292769*m.x239
- 0.00897797*m.x240 + 0.00544385*m.x241 + 0.0252208*m.x242 - 0.00169431*m.x243
+ 0.0126097*m.x244 + 0.00435369*m.x245 + 0.285352*m.x246 - 0.0138679*m.x247 + 0.0182951*m.x248
+ 0.018868*m.x249 + 0.0248387*m.x250 + 0.0906352*m.x251 + 0.00713202*m.x252 - 0.0104213*m.x253
+ 0.0108641*m.x254 - 0.0111579*m.x255 - 0.010758*m.x256 + 0.0162983*m.x257 + 0.00775024*m.x258
+ 0.00853849*m.x259 - 0.00130433*m.x260 + 0.00312367*m.x261 - 0.0160088*m.x262
+ 0.0308548*m.x263 + 0.0187432*m.x264 - 0.00426161*m.x265 - 0.00773906*m.x266
+ 0.00306814*m.x267 + 0.0128287*m.x268 + 0.00522194*m.x269 + 0.00258635*m.x270
+ 0.0129953*m.x271 + 0.000800136*m.x272 - 0.0165869*m.x273 + 0.0101507*m.x274
+ 0.0607045*m.x275 - 0.00928056*m.x276 + 0.00206923*m.x277 - 0.0163855*m.x278
+ 0.0271648*m.x279 - 0.00245982*m.x280 + 0.01456*m.x281 + 0.00939606*m.x282 + 0.0298789*m.x283
- 0.00119943*m.x284 - 0.0044664*m.x285 + 0.000712121*m.x286 + 0.00470761*m.x287
+ 0.0134195*m.x288 + 0.0369595*m.x289 - 0.0210138*m.x290 - 0.00303618*m.x291
+ 0.00239232*m.x292 + 0.000321826*m.x293 + 0.0159286*m.x294 - 0.000456654*m.x295
+ 0.0140437*m.x296 - 0.0133161*m.x297 + 0.00274327*m.x298 + 0.0088079*m.x299
- 0.0199075*m.x300 + 0.0201943*m.x301 + 0.0380042*m.x302 - 0.00589524*m.x303 == 0)
m.c150 = Constraint(expr= - m.x45 - 0.00162455*m.x204 + 0.0151994*m.x205 - 0.00410314*m.x206 + 0.00865558*m.x207
+ 0.0207267*m.x208 + 0.0189494*m.x209 + 0.00733761*m.x210 + 0.00505829*m.x211
- 0.00309397*m.x212 + 0.00188592*m.x213 - 0.00862089*m.x214 + 0.0121501*m.x215
+ 0.0166299*m.x216 - 0.00370708*m.x217 + 0.0130156*m.x218 + 0.010862*m.x219
+ 0.00619143*m.x220 + 0.00845798*m.x221 + 0.0196626*m.x222 + 0.00499481*m.x223
- 0.00195653*m.x224 - 0.00111486*m.x225 + 0.0111032*m.x226 + 0.00451121*m.x227
+ 0.00365229*m.x228 - 0.00906245*m.x229 - 0.0033586*m.x230 + 0.00298817*m.x231
+ 0.00536671*m.x232 + 0.0161599*m.x233 - 0.0062901*m.x234 + 0.0067698*m.x235
- 0.000673256*m.x236 + 0.0158673*m.x237 - 0.00504028*m.x238 + 0.014697*m.x239
- 0.0109459*m.x240 + 0.0105749*m.x241 - 0.0070303*m.x242 + 0.0128324*m.x243
- 0.00520594*m.x244 + 0.0112326*m.x245 - 0.0138679*m.x246 + 0.117019*m.x247
+ 0.00990186*m.x248 + 0.030525*m.x249 + 0.00866848*m.x250 + 0.00667345*m.x251
+ 0.00996622*m.x252 + 0.00563546*m.x253 + 0.0238284*m.x254 - 0.00200986*m.x255
+ 0.00469393*m.x256 + 0.00134527*m.x257 + 0.00374232*m.x258 + 0.00559832*m.x259
- 0.00188392*m.x260 + 9.17403E-5*m.x261 + 0.00219407*m.x262 + 0.00878374*m.x263
+ 0.00816234*m.x264 + 0.0139761*m.x265 + 0.00238266*m.x266 - 0.00331267*m.x267
+ 0.0130905*m.x268 - 0.00761858*m.x269 + 0.00239066*m.x270 + 0.00767196*m.x271
+ 0.0121103*m.x272 - 0.00250388*m.x273 + 0.00747713*m.x274 - 0.012371*m.x275
+ 0.000659729*m.x276 + 0.0140481*m.x277 + 0.0187041*m.x278 + 0.0306678*m.x279
+ 0.00641255*m.x280 + 0.0134395*m.x281 - 0.00179731*m.x282 - 0.00385651*m.x283
+ 0.0131706*m.x284 + 0.0115633*m.x285 - 0.00481073*m.x286 - 0.000228971*m.x287
+ 0.0126522*m.x288 + 0.0105163*m.x289 + 0.013309*m.x290 + 0.0161332*m.x291 + 0.0153765*m.x292
+ 0.0172788*m.x293 + 0.00454689*m.x294 - 0.00408178*m.x295 + 0.0106112*m.x296
- 0.00745302*m.x297 + 0.0138402*m.x298 - 0.00206706*m.x299 - 0.00104385*m.x300
- 0.0111014*m.x301 + 0.00860025*m.x302 + 0.0108073*m.x303 == 0)
m.c151 = Constraint(expr= - m.x46 + 0.0485595*m.x204 + 0.0842548*m.x205 + 0.00010559*m.x206 + 0.0274023*m.x207
+ 0.0169542*m.x208 + 0.00789539*m.x209 + 0.0201234*m.x210 - 0.003359*m.x211 + 0.0671213*m.x212
+ 0.0305494*m.x213 - 0.0336638*m.x214 - 0.010913*m.x215 + 0.0470539*m.x216 + 0.0445913*m.x217
+ 0.0104316*m.x218 + 0.0233605*m.x219 + 0.0353105*m.x220 + 0.0602333*m.x221 + 0.0720207*m.x222
+ 0.0422832*m.x223 + 0.000456614*m.x224 + 0.086076*m.x225 - 0.00263182*m.x226
- 0.0148276*m.x227 + 0.00411288*m.x228 + 0.0126082*m.x229 + 0.0351761*m.x230
+ 0.0054897*m.x231 + 0.00229741*m.x232 + 0.00526805*m.x233 + 0.0361137*m.x234
+ 0.00746688*m.x235 - 0.00492434*m.x236 + 0.0139875*m.x237 + 0.0628923*m.x238
+ 0.0159248*m.x239 + 0.0170251*m.x240 - 0.00422865*m.x241 + 0.0675517*m.x242
+ 0.0130568*m.x243 + 0.0641494*m.x244 + 0.0300354*m.x245 + 0.0182951*m.x246
+ 0.00990186*m.x247 + 1.28381*m.x248 + 0.0231821*m.x249 + 0.018721*m.x250 + 0.157526*m.x251
+ 0.0256558*m.x252 + 0.00662398*m.x253 + 0.00571637*m.x254 + 0.0314978*m.x255
+ 0.0144722*m.x256 + 0.0343682*m.x257 + 0.0244461*m.x258 + 0.0119362*m.x259
+ 0.00907288*m.x260 - 0.04778*m.x261 - 0.0108826*m.x262 + 0.00420738*m.x263 + 0.0658392*m.x264
- 0.00210493*m.x265 - 0.00489265*m.x266 - 0.0339851*m.x267 + 0.0142713*m.x268
+ 0.00850407*m.x269 - 0.00279322*m.x270 + 0.00139531*m.x271 + 0.00256477*m.x272
+ 0.0206991*m.x273 + 0.0167627*m.x274 + 0.11148*m.x275 - 0.0305247*m.x276 - 0.00481113*m.x277
+ 0.0231293*m.x278 + 0.0252067*m.x279 + 0.00522157*m.x280 + 0.0559574*m.x281
+ 0.0289862*m.x282 + 0.00382741*m.x283 - 0.00408493*m.x284 + 0.028825*m.x285 + 0.043114*m.x286
+ 0.0366449*m.x287 - 0.00847171*m.x288 + 0.0235286*m.x289 - 0.0234656*m.x290
+ 0.00121975*m.x291 + 0.00617827*m.x292 + 0.0181113*m.x293 - 0.0146448*m.x294
- 0.0232215*m.x295 + 0.00688969*m.x296 + 0.0659066*m.x297 + 0.0163443*m.x298
+ 0.0491497*m.x299 + 0.0230853*m.x300 + 0.0414341*m.x301 + 0.0105274*m.x302
+ 0.00672014*m.x303 == 0)
m.c152 = Constraint(expr= - m.x47 + 0.00207472*m.x204 - 0.00547032*m.x205 - 0.0124818*m.x206 + 0.00371704*m.x207
- 0.0027153*m.x208 + 0.0132198*m.x209 + 0.00199539*m.x210 + 0.00172548*m.x211
+ 0.0105468*m.x212 - 0.00910821*m.x213 - 0.00677995*m.x214 + 0.0136767*m.x215
+ 0.0108543*m.x216 + 0.0145696*m.x217 + 0.0109843*m.x218 + 0.0254292*m.x219 + 0.0137663*m.x220
+ 0.0215291*m.x221 + 0.00312965*m.x222 - 9.41833E-5*m.x223 + 0.00971748*m.x224
+ 0.00650857*m.x225 + 0.0168949*m.x226 + 0.00531801*m.x227 + 0.00931093*m.x228
- 0.0137446*m.x229 + 0.00249494*m.x230 + 0.00838146*m.x231 - 0.000669481*m.x232
+ 0.00015225*m.x233 + 0.00188213*m.x234 + 0.0224318*m.x235 - 0.00146448*m.x236
+ 0.00964636*m.x237 + 0.0158934*m.x238 + 0.0267699*m.x239 + 0.00864687*m.x240
+ 0.0165157*m.x241 - 0.0217225*m.x242 + 0.00834641*m.x243 - 0.00275487*m.x244
+ 0.00838204*m.x245 + 0.018868*m.x246 + 0.030525*m.x247 + 0.0231821*m.x248 + 0.110238*m.x249
+ 0.0123825*m.x250 - 0.0024984*m.x251 + 0.008478*m.x252 + 0.000741326*m.x253
+ 0.0216772*m.x254 + 0.0180178*m.x255 - 0.00109436*m.x256 + 0.00665208*m.x257
+ 0.0151547*m.x258 + 0.00745197*m.x259 + 0.01615*m.x260 + 0.00117437*m.x261
- 0.00321902*m.x262 + 0.00508728*m.x263 + 0.00978353*m.x264 + 0.0167338*m.x265
- 0.000552346*m.x266 - 0.0124862*m.x267 + 0.0092919*m.x268 - 0.000986526*m.x269
+ 0.004509*m.x270 + 0.00222268*m.x271 + 0.00595866*m.x272 - 0.00295638*m.x273
+ 0.0123014*m.x274 + 0.0116924*m.x275 + 0.00495294*m.x276 + 0.00276646*m.x277
- 0.00266202*m.x278 + 0.0232357*m.x279 + 0.00346212*m.x280 + 0.0255284*m.x281
+ 0.00412958*m.x282 + 0.0240524*m.x283 + 0.0102107*m.x284 + 0.0153982*m.x285
- 0.00470666*m.x286 + 0.0022653*m.x287 + 0.0126439*m.x288 + 0.00223458*m.x289
+ 0.000876921*m.x290 + 0.0255993*m.x291 + 0.000761757*m.x292 + 0.0226772*m.x293
- 0.00239856*m.x294 - 0.000303141*m.x295 + 0.00819898*m.x296 - 0.0155281*m.x297
+ 0.01631*m.x298 + 0.0130047*m.x299 + 0.007868*m.x300 + 0.0172829*m.x301 + 0.00542659*m.x302
+ 0.00997388*m.x303 == 0)
m.c153 = Constraint(expr= - m.x48 + 0.00660381*m.x204 + 0.00366432*m.x205 + 0.0222942*m.x206 + 0.0278823*m.x207
+ 0.0227537*m.x208 + 0.0131179*m.x209 + 0.00883369*m.x210 - 0.00798884*m.x211
+ 0.0076658*m.x212 + 0.0135289*m.x213 + 0.00625335*m.x214 + 0.0116898*m.x215
+ 0.0041831*m.x216 + 0.0102428*m.x217 + 0.00892909*m.x218 + 0.026309*m.x219 + 0.0126568*m.x220
+ 0.000524806*m.x221 + 0.0116736*m.x222 - 0.00625035*m.x223 + 0.0122344*m.x224
+ 0.00551656*m.x225 + 0.0118048*m.x226 + 0.00527699*m.x227 + 0.0122374*m.x228
- 0.00568651*m.x229 + 0.0142173*m.x230 + 0.00738842*m.x231 + 0.0101225*m.x232
+ 0.0278298*m.x233 + 0.0105383*m.x234 + 0.00853378*m.x235 + 0.00882459*m.x236
+ 0.0135777*m.x237 + 0.0095123*m.x238 + 0.0109654*m.x239 + 0.00178605*m.x240
+ 0.0153668*m.x241 + 0.00424885*m.x242 + 0.0233526*m.x243 + 0.009426*m.x244 + 0.0230848*m.x245
+ 0.0248387*m.x246 + 0.00866848*m.x247 + 0.018721*m.x248 + 0.0123825*m.x249 + 0.125525*m.x250
+ 0.0182178*m.x251 + 0.0177715*m.x252 + 0.0265062*m.x253 + 0.00964961*m.x254 + 0.023352*m.x255
+ 0.000843914*m.x256 + 0.0110552*m.x257 + 0.00964941*m.x258 + 0.00680548*m.x259
+ 0.00742778*m.x260 + 9.53631E-5*m.x261 - 0.00253774*m.x262 + 0.0180458*m.x263
+ 0.0185083*m.x264 + 0.0187542*m.x265 - 0.00848668*m.x266 - 0.0111347*m.x267 + 0.029197*m.x268
+ 0.0134837*m.x269 + 0.0134453*m.x270 + 0.0159389*m.x271 - 0.00298889*m.x272
- 0.0125802*m.x273 + 0.0123928*m.x274 + 0.0197059*m.x275 + 0.00699246*m.x276
+ 0.00608218*m.x277 + 0.0205119*m.x278 + 0.0201426*m.x279 + 0.00467559*m.x280
+ 0.00848245*m.x281 + 0.00560285*m.x282 - 0.000758449*m.x283 + 0.0116371*m.x284
+ 0.0124272*m.x285 + 0.0162343*m.x286 - 0.00172543*m.x287 + 0.0211089*m.x288
+ 0.00648963*m.x289 - 0.00342056*m.x290 + 0.0183674*m.x291 + 0.00194382*m.x292
+ 0.0120585*m.x293 + 0.004607*m.x294 + 0.017139*m.x295 + 0.0200535*m.x296 - 0.0108609*m.x297
+ 0.0112311*m.x298 - 0.000464008*m.x299 + 0.00372516*m.x300 + 0.00268954*m.x301
+ 0.0166562*m.x302 + 0.00639193*m.x303 == 0)
m.c154 = Constraint(expr= - m.x49 + 0.0335273*m.x204 - 0.00269275*m.x205 + 0.0641257*m.x206 + 0.0276611*m.x207
+ 0.0245375*m.x208 + 0.0350419*m.x209 - 0.00334111*m.x210 - 0.00523044*m.x211
+ 0.046947*m.x212 + 0.103912*m.x213 + 0.0263146*m.x214 + 0.0382384*m.x215 + 0.00544939*m.x216
+ 0.0541929*m.x217 + 0.0139724*m.x218 + 0.00373059*m.x219 + 0.0131167*m.x220
+ 0.0502056*m.x221 + 0.0683894*m.x222 + 0.0135275*m.x223 - 0.023887*m.x224 + 0.0234501*m.x225
+ 0.0540289*m.x226 + 0.00749425*m.x227 + 0.022339*m.x228 - 0.00050512*m.x229
- 0.00543891*m.x230 + 0.0443024*m.x231 + 0.00629643*m.x232 + 0.0489272*m.x233
+ 0.0312435*m.x234 + 0.00553395*m.x235 + 0.0565808*m.x236 + 0.0103222*m.x237
+ 0.00894769*m.x238 + 0.0152969*m.x239 + 0.0216947*m.x240 + 0.000861128*m.x241
+ 0.00522672*m.x242 + 0.00754003*m.x243 + 0.0377236*m.x244 + 0.011347*m.x245
+ 0.0906352*m.x246 + 0.00667345*m.x247 + 0.157526*m.x248 - 0.0024984*m.x249 + 0.0182178*m.x250
+ 0.819119*m.x251 - 0.0220075*m.x252 - 0.000377244*m.x253 + 0.00274662*m.x254
- 0.00112164*m.x255 - 0.0111344*m.x256 + 0.0327084*m.x257 - 0.0151267*m.x258
+ 0.0557771*m.x259 - 0.00515185*m.x260 - 0.0101051*m.x261 + 0.00981918*m.x262
+ 0.117196*m.x263 + 0.00665526*m.x264 - 0.0175406*m.x265 - 0.00134639*m.x266 - 0.039556*m.x267
- 0.00784993*m.x268 + 0.0249045*m.x269 - 0.00128867*m.x270 - 0.00261452*m.x271
+ 0.039282*m.x272 + 0.0509997*m.x273 + 0.0344311*m.x274 + 0.0814204*m.x275 - 0.00170809*m.x276
+ 0.0125969*m.x277 + 0.0302619*m.x278 + 0.0349979*m.x279 + 0.0190191*m.x280 + 0.0154082*m.x281
- 0.0261893*m.x282 + 0.0528557*m.x283 + 0.0243695*m.x284 - 0.000197615*m.x285
+ 0.0624011*m.x286 + 0.0338724*m.x287 - 0.0090107*m.x288 + 0.00951148*m.x289
+ 0.0107168*m.x290 + 0.0178279*m.x291 + 0.00290669*m.x292 - 0.011085*m.x293 - 0.020525*m.x294
- 0.0111643*m.x295 - 0.00203641*m.x296 + 0.00376918*m.x297 + 0.0118935*m.x298
+ 0.0159972*m.x299 + 0.00701074*m.x300 + 0.0129573*m.x301 + 0.00101054*m.x302
- 0.00326076*m.x303 == 0)
m.c155 = Constraint(expr= - m.x50 - 0.00253464*m.x204 + 0.0064107*m.x205 - 0.00250627*m.x206 + 0.0335727*m.x207
+ 0.0220219*m.x208 + 0.00782381*m.x209 + 0.00675904*m.x210 - 0.0106746*m.x211
+ 0.000222582*m.x212 + 0.0135404*m.x213 + 0.00182442*m.x214 + 0.0131966*m.x215
+ 0.00847808*m.x216 + 0.0222686*m.x217 + 0.0324222*m.x218 + 0.0226732*m.x219
+ 0.0279086*m.x220 + 0.0135373*m.x221 + 0.021574*m.x222 - 0.00389379*m.x223
+ 0.000162502*m.x224 - 0.00551305*m.x225 + 0.0155506*m.x226 + 0.00218243*m.x227
+ 0.0160754*m.x228 + 0.00295003*m.x229 - 0.00806152*m.x230 - 0.00363873*m.x231
+ 0.00338529*m.x232 + 0.0300688*m.x233 + 0.00612172*m.x234 + 0.0306636*m.x235
- 0.00265594*m.x236 + 0.00664455*m.x237 + 0.0126674*m.x238 - 0.00705335*m.x239
+ 0.0089316*m.x240 + 0.0256051*m.x241 + 0.0111003*m.x242 + 0.00962683*m.x243
+ 0.0273291*m.x244 + 0.021257*m.x245 + 0.00713202*m.x246 + 0.00996622*m.x247
+ 0.0256558*m.x248 + 0.008478*m.x249 + 0.0177715*m.x250 - 0.0220075*m.x251 + 0.114335*m.x252
+ 0.0512161*m.x253 + 0.0197406*m.x254 + 0.0196807*m.x255 + 0.00493219*m.x256
+ 0.00452567*m.x257 + 0.000714771*m.x258 + 0.00310895*m.x259 + 0.0185615*m.x260
+ 0.0258631*m.x261 + 0.00933346*m.x262 - 0.0221839*m.x263 + 0.0236734*m.x264
+ 0.0176283*m.x265 + 0.00446979*m.x266 - 0.0128737*m.x267 - 0.00682462*m.x268
+ 0.00523125*m.x269 + 0.0213069*m.x270 + 0.0081431*m.x271 + 0.00415461*m.x272
+ 0.0073977*m.x273 + 0.00728529*m.x274 + 0.0247762*m.x275 + 0.0153231*m.x276
+ 0.00286752*m.x277 + 0.0201839*m.x278 + 0.00924621*m.x279 + 0.0108718*m.x280
+ 0.0181957*m.x281 + 0.0030579*m.x282 + 0.0149032*m.x283 + 0.00765193*m.x284
+ 0.00635221*m.x285 + 0.0123886*m.x286 + 0.000661634*m.x287 + 0.0359152*m.x288
+ 0.0121599*m.x289 + 0.00929105*m.x290 + 0.0129496*m.x291 + 0.000165876*m.x292
+ 0.0104514*m.x293 + 0.0177858*m.x294 + 0.0273403*m.x295 + 0.00347406*m.x296
+ 0.00897938*m.x297 + 0.0131703*m.x298 + 0.0238145*m.x299 + 0.0112134*m.x300
- 0.00463261*m.x301 + 0.00520514*m.x302 - 0.00135479*m.x303 == 0)
m.c156 = Constraint(expr= - m.x51 + 0.0243471*m.x204 + 0.0159232*m.x205 + 0.00990617*m.x206 + 0.0350956*m.x207
+ 0.0142215*m.x208 - 0.00238836*m.x209 + 0.0174474*m.x210 + 0.00991922*m.x211
- 0.0116779*m.x212 + 0.00765973*m.x213 + 0.0180868*m.x214 + 0.0177887*m.x215
+ 0.0136335*m.x216 + 0.0200759*m.x217 + 0.0258001*m.x218 + 0.0151062*m.x219 + 0.0187117*m.x220
+ 0.00412087*m.x221 - 0.00484013*m.x222 + 0.0225012*m.x223 + 0.00181967*m.x224
+ 0.00168255*m.x225 + 0.0101127*m.x226 + 0.00995275*m.x227 + 0.00927056*m.x228
+ 0.0130362*m.x229 + 0.00341299*m.x230 - 0.0276809*m.x231 + 0.00481268*m.x232
+ 0.0188471*m.x233 + 0.02564*m.x234 + 0.0264708*m.x235 - 0.0131072*m.x236 + 0.0426453*m.x237
- 0.00759544*m.x238 + 0.0069801*m.x239 + 0.0141917*m.x240 + 0.0422426*m.x241
+ 0.0034425*m.x242 + 0.0131857*m.x243 + 0.0239811*m.x244 + 0.0308057*m.x245 - 0.0104213*m.x246
+ 0.00563546*m.x247 + 0.00662398*m.x248 + 0.000741326*m.x249 + 0.0265062*m.x250
- 0.000377244*m.x251 + 0.0512161*m.x252 + 0.196086*m.x253 - 0.00348555*m.x254
+ 0.0225156*m.x255 + 0.00631849*m.x256 + 0.00655318*m.x257 + 0.0189254*m.x258
+ 0.0128203*m.x259 + 0.0120199*m.x260 + 0.0197559*m.x261 + 0.0196814*m.x262
+ 0.00428319*m.x263 + 0.0202022*m.x264 + 0.0291275*m.x265 + 0.0180013*m.x266
- 0.00816153*m.x267 - 0.0005624*m.x268 + 0.0104426*m.x269 + 0.030677*m.x270
+ 0.00414094*m.x271 + 0.0226546*m.x272 + 0.0125649*m.x273 + 0.0031934*m.x274
+ 0.0170294*m.x275 + 0.0194417*m.x276 + 0.0221671*m.x277 + 0.00907431*m.x278
+ 0.0259533*m.x279 + 0.00674077*m.x280 + 0.0203818*m.x281 + 0.0079052*m.x282 + 0.02471*m.x283
+ 0.0263439*m.x284 + 0.0177662*m.x285 + 0.0459437*m.x286 + 0.031036*m.x287 + 0.0396615*m.x288
+ 0.0169315*m.x289 + 0.0265097*m.x290 + 0.00746963*m.x291 + 0.014075*m.x292
+ 0.000392536*m.x293 + 0.02246*m.x294 + 0.0196935*m.x295 + 0.0203211*m.x296
+ 0.00142186*m.x297 + 0.00797244*m.x298 + 0.0303016*m.x299 + 0.0163988*m.x300
- 0.0103262*m.x301 + 0.0138437*m.x302 + 0.00766798*m.x303 == 0)
m.c157 = Constraint(expr= - m.x52 - 4.32941E-5*m.x204 + 0.0109604*m.x205 + 0.0106624*m.x206 + 0.00379579*m.x207
+ 0.0212008*m.x208 + 0.0282466*m.x209 + 0.000986276*m.x210 + 0.00762574*m.x211
- 0.00988969*m.x212 + 0.005395*m.x213 + 0.0139184*m.x214 + 0.00125449*m.x215
+ 0.0285916*m.x216 + 0.0227414*m.x217 + 0.00536497*m.x218 + 0.00878227*m.x219
+ 0.0144307*m.x220 - 0.00913314*m.x221 + 0.000594358*m.x222 + 0.0108096*m.x223
+ 0.0068839*m.x224 - 0.0062463*m.x225 + 0.0135526*m.x226 + 0.0138831*m.x227
- 0.00153332*m.x228 - 0.0100498*m.x229 - 0.00785713*m.x230 + 0.00664334*m.x231
+ 0.00636725*m.x232 + 0.00180223*m.x233 - 0.00360195*m.x234 + 0.0366567*m.x235
- 0.0185973*m.x236 + 0.014965*m.x237 + 0.000920465*m.x238 - 0.00905371*m.x239
+ 0.0171861*m.x240 - 0.000803595*m.x241 - 0.0131086*m.x242 - 0.00149067*m.x243
+ 0.00578221*m.x244 + 0.00779234*m.x245 + 0.0108641*m.x246 + 0.0238284*m.x247
+ 0.00571637*m.x248 + 0.0216772*m.x249 + 0.00964961*m.x250 + 0.00274662*m.x251
+ 0.0197406*m.x252 - 0.00348555*m.x253 + 0.135419*m.x254 + 0.0148808*m.x255
- 0.00521642*m.x256 + 0.00301132*m.x257 + 0.0059386*m.x258 + 0.000656537*m.x259
- 5.81815E-5*m.x260 + 0.00610465*m.x261 + 0.00544527*m.x262 + 0.0153454*m.x263
+ 0.0292089*m.x264 + 0.0160595*m.x265 - 0.00416091*m.x266 - 0.0114877*m.x267
- 0.00518739*m.x268 + 0.00285023*m.x269 - 0.00263203*m.x270 + 0.00784535*m.x271
+ 0.00552304*m.x272 - 0.00966017*m.x273 + 0.00209512*m.x274 - 0.00647057*m.x275
+ 0.0011822*m.x276 + 0.0120375*m.x277 - 0.00082898*m.x278 + 0.00474529*m.x279
+ 0.00506484*m.x280 + 0.0257774*m.x281 - 0.00377692*m.x282 + 0.00714516*m.x283
+ 0.0077099*m.x284 + 0.0105595*m.x285 + 0.0161573*m.x286 + 0.00452026*m.x287
+ 0.00366557*m.x288 + 0.0131458*m.x289 - 0.00873615*m.x290 + 0.0046782*m.x291
+ 0.00459631*m.x292 + 0.0212014*m.x293 + 0.0117374*m.x294 + 0.0229518*m.x295
+ 0.00232247*m.x296 - 0.0141535*m.x297 + 0.00517337*m.x298 + 0.0102284*m.x299
+ 0.016647*m.x300 + 0.00970317*m.x301 + 0.0100764*m.x302 + 0.00923673*m.x303 == 0)
m.c158 = Constraint(expr= - m.x53 + 0.0163137*m.x204 + 0.0557033*m.x205 - 0.00120817*m.x206 + 0.0146599*m.x207
+ 0.0295561*m.x208 - 0.0144879*m.x209 + 0.00773796*m.x210 - 0.0266695*m.x211
+ 0.0132613*m.x212 - 0.0102711*m.x213 + 0.0593808*m.x214 + 0.0146264*m.x215
+ 0.00654495*m.x216 + 0.0206173*m.x217 - 0.0164481*m.x218 - 0.00659662*m.x219
+ 0.00896247*m.x220 + 0.020479*m.x221 - 0.0094595*m.x222 + 0.0515904*m.x223
+ 0.00288958*m.x224 + 0.00302148*m.x225 + 0.00456304*m.x226 + 0.0179012*m.x227
- 0.00274677*m.x228 + 0.0373415*m.x229 + 0.00317892*m.x230 + 0.00813124*m.x231
+ 0.0177429*m.x232 + 0.0269342*m.x233 + 0.0141086*m.x234 - 0.00105083*m.x235
+ 0.00879757*m.x236 - 0.0255534*m.x237 + 0.0125861*m.x238 + 0.0143571*m.x239
+ 0.0129119*m.x240 + 0.00351671*m.x241 + 0.0891112*m.x242 + 0.000467774*m.x243
+ 0.0121199*m.x244 + 0.0336911*m.x245 - 0.0111579*m.x246 - 0.00200986*m.x247
+ 0.0314978*m.x248 + 0.0180178*m.x249 + 0.023352*m.x250 - 0.00112164*m.x251 + 0.0196807*m.x252
+ 0.0225156*m.x253 + 0.0148808*m.x254 + 0.570686*m.x255 - 0.0118855*m.x256 - 0.014196*m.x257
+ 0.011069*m.x258 + 0.0175376*m.x259 + 0.0238431*m.x260 - 0.0397472*m.x261 - 0.0442114*m.x262
+ 0.0518827*m.x263 + 0.0161886*m.x264 + 0.00172998*m.x265 - 0.0149321*m.x266
- 0.00526354*m.x267 + 0.0191389*m.x268 - 0.000438258*m.x269 - 0.00523691*m.x270
- 0.00972975*m.x271 - 0.0150659*m.x272 - 0.0484007*m.x273 + 0.0154489*m.x274
+ 0.0227933*m.x275 + 0.00649497*m.x276 + 0.0365298*m.x277 + 0.00147956*m.x278
- 0.0171972*m.x279 + 0.0090494*m.x280 + 0.00449672*m.x281 + 0.000262274*m.x282
- 0.00945913*m.x283 + 0.0453251*m.x284 - 0.000808541*m.x285 + 0.0226841*m.x286
+ 0.0177547*m.x287 + 0.0128398*m.x288 + 0.0231386*m.x289 - 0.0113699*m.x290 + 0.0889439*m.x291
+ 0.0105083*m.x292 + 0.00390748*m.x293 + 0.00684597*m.x294 + 0.0131893*m.x295
- 0.0139354*m.x296 - 0.0247692*m.x297 + 0.0243459*m.x298 + 0.0752523*m.x299
- 0.00276693*m.x300 - 0.00836392*m.x301 + 0.0169651*m.x302 + 0.0207104*m.x303 == 0)
m.c159 = Constraint(expr= - m.x54 - 0.000494175*m.x204 + 0.00892139*m.x205 - 0.0113822*m.x206 + 0.0202259*m.x207
+ 0.00841613*m.x208 + 0.0254505*m.x209 + 0.0122267*m.x210 + 0.00886183*m.x211
- 0.00967266*m.x212 + 0.000261336*m.x213 + 0.000709314*m.x214 + 0.0570949*m.x215
+ 0.01696*m.x216 - 0.0067449*m.x217 + 0.00992241*m.x218 + 0.00760297*m.x219 + 0.0230109*m.x220
- 0.00154837*m.x221 - 0.0318332*m.x222 - 0.00645678*m.x223 + 0.0206887*m.x224
+ 0.00339277*m.x225 + 0.00172033*m.x226 + 0.00828721*m.x227 + 0.011526*m.x228
+ 0.00554618*m.x229 + 0.0107528*m.x230 + 0.00525742*m.x231 - 0.00438567*m.x232
+ 0.0137397*m.x233 + 0.0367283*m.x234 + 0.00408317*m.x235 - 0.00320472*m.x236
+ 0.0104359*m.x237 - 0.00390865*m.x238 + 0.0151841*m.x239 + 0.0235719*m.x240
+ 0.0145538*m.x241 + 0.0358926*m.x242 + 0.0104228*m.x243 - 0.00778263*m.x244
+ 0.0131565*m.x245 - 0.010758*m.x246 + 0.00469393*m.x247 + 0.0144722*m.x248
- 0.00109436*m.x249 + 0.000843914*m.x250 - 0.0111344*m.x251 + 0.00493219*m.x252
+ 0.00631849*m.x253 - 0.00521642*m.x254 - 0.0118855*m.x255 + 0.226022*m.x256
+ 0.0134414*m.x257 + 0.0132028*m.x258 + 0.0182593*m.x259 + 0.00378479*m.x260
+ 0.00402915*m.x261 + 0.00220607*m.x262 + 0.0103192*m.x263 + 0.0152444*m.x264
+ 0.0220514*m.x265 + 0.0445908*m.x266 - 0.00977257*m.x267 + 0.00947946*m.x268
+ 0.0081976*m.x269 + 0.00899719*m.x270 + 0.0216871*m.x271 + 0.0232*m.x272 + 0.0135089*m.x273
+ 0.0147635*m.x274 - 0.0169658*m.x275 + 0.00689011*m.x276 + 0.00530597*m.x277
+ 0.000210327*m.x278 - 0.00222996*m.x279 + 0.00353714*m.x280 + 0.0260232*m.x281
- 0.0188128*m.x282 - 0.00162038*m.x283 - 0.00901467*m.x284 + 0.031558*m.x285
+ 0.0131334*m.x286 + 0.010006*m.x287 - 0.00713827*m.x288 + 0.00638031*m.x289
+ 0.0140088*m.x290 + 0.0192336*m.x291 + 0.00082309*m.x292 + 0.00967333*m.x293
+ 0.000291585*m.x294 + 0.0165254*m.x295 + 0.00824013*m.x296 - 0.00561804*m.x297
+ 0.0192153*m.x298 - 0.00817059*m.x299 + 0.0078892*m.x300 + 0.00463932*m.x301
- 0.00593801*m.x302 + 0.00325836*m.x303 == 0)
m.c160 = Constraint(expr= - m.x55 + 0.0164977*m.x204 - 0.00637132*m.x205 + 0.0115937*m.x206 + 0.00222715*m.x207
+ 0.00832278*m.x208 + 0.00288051*m.x209 + 0.0155811*m.x210 + 0.0170693*m.x211
+ 0.0167367*m.x212 + 0.00274854*m.x213 + 0.00766591*m.x214 + 0.00451784*m.x215
+ 0.09051*m.x216 + 0.0455555*m.x217 + 0.0214377*m.x218 + 0.0166459*m.x219 + 0.0380049*m.x220
+ 0.0140183*m.x221 + 0.0316379*m.x222 - 0.0190381*m.x223 + 0.00659477*m.x224
+ 0.00760958*m.x225 + 0.00174846*m.x226 + 0.00342253*m.x227 + 9.44861E-5*m.x228
+ 0.0074701*m.x229 - 0.00906739*m.x230 + 0.015111*m.x231 - 0.00680131*m.x232
+ 0.00116831*m.x233 + 0.00320485*m.x234 - 0.0130126*m.x235 - 0.0046504*m.x236
+ 0.0058258*m.x237 + 0.00253837*m.x238 + 0.0144667*m.x239 + 0.0176837*m.x240
+ 0.0131903*m.x241 + 0.0274205*m.x242 + 0.00959745*m.x243 + 0.0206125*m.x244
+ 0.0127459*m.x245 + 0.0162983*m.x246 + 0.00134527*m.x247 + 0.0343682*m.x248
+ 0.00665208*m.x249 + 0.0110552*m.x250 + 0.0327084*m.x251 + 0.00452567*m.x252
+ 0.00655318*m.x253 + 0.00301132*m.x254 - 0.014196*m.x255 + 0.0134414*m.x256 + 0.438941*m.x257
+ 0.011138*m.x258 + 0.0267434*m.x259 + 0.0153667*m.x260 - 0.0139925*m.x261 + 0.00410561*m.x262
+ 0.0255464*m.x263 + 0.0476449*m.x264 + 0.0288895*m.x265 + 0.00855635*m.x266
- 0.0298097*m.x267 - 0.0193235*m.x268 - 0.00212818*m.x269 + 0.0152037*m.x270
+ 0.0243197*m.x271 + 0.0286571*m.x272 + 0.0238634*m.x273 + 0.00835242*m.x274
- 0.0044184*m.x275 + 0.0108029*m.x276 + 0.00721874*m.x277 + 0.0240962*m.x278
+ 0.0333277*m.x279 - 0.00435648*m.x280 + 0.0866383*m.x281 + 0.00354499*m.x282
+ 0.00280407*m.x283 - 0.0171587*m.x284 + 0.0167951*m.x285 + 0.0217323*m.x286
+ 0.0074812*m.x287 - 0.0200391*m.x288 + 0.00634167*m.x289 - 0.00043216*m.x290
- 0.000981924*m.x291 + 0.0100724*m.x292 + 0.00947697*m.x293 + 0.0122578*m.x294
+ 0.0215961*m.x295 + 0.0101139*m.x296 + 0.00689054*m.x297 + 0.0214997*m.x298
- 0.00197476*m.x299 + 0.0136175*m.x300 + 0.0236766*m.x301 + 0.00337669*m.x302
+ 0.0035861*m.x303 == 0)
m.c161 = Constraint(expr= - m.x56 + 0.00852804*m.x204 + 0.028098*m.x205 - 0.0206532*m.x206 - 0.018228*m.x207
+ 0.00806585*m.x208 - 0.00244405*m.x209 + 0.00782426*m.x210 - 0.0010862*m.x211
+ 0.000760504*m.x212 + 0.0082671*m.x213 + 0.0182084*m.x214 - 0.0264793*m.x215
- 0.00361466*m.x216 - 0.0220985*m.x217 + 0.0122468*m.x218 + 0.00111556*m.x219
+ 0.00594814*m.x220 - 0.0157061*m.x221 + 0.0193443*m.x222 + 0.0138196*m.x223
- 0.00192784*m.x224 - 0.00714421*m.x225 + 0.0155517*m.x226 + 0.0144765*m.x227
+ 0.0205903*m.x228 - 0.00778581*m.x229 + 0.00425862*m.x230 + 0.0266351*m.x231
+ 0.0104672*m.x232 + 0.00270328*m.x233 - 0.0033721*m.x234 + 0.00691299*m.x235
- 0.0112877*m.x236 + 0.0144468*m.x237 + 0.0021617*m.x238 + 0.00865979*m.x239
+ 0.00165906*m.x240 + 0.00498598*m.x241 + 0.00568814*m.x242 + 0.0216421*m.x243
- 0.00233532*m.x244 + 0.00581905*m.x245 + 0.00775024*m.x246 + 0.00374232*m.x247
+ 0.0244461*m.x248 + 0.0151547*m.x249 + 0.00964941*m.x250 - 0.0151267*m.x251
+ 0.000714771*m.x252 + 0.0189254*m.x253 + 0.0059386*m.x254 + 0.011069*m.x255
+ 0.0132028*m.x256 + 0.011138*m.x257 + 0.196677*m.x258 - 0.0016753*m.x259 + 0.0210475*m.x260
+ 0.0394424*m.x261 - 0.0137174*m.x262 + 0.0251559*m.x263 + 0.004979*m.x264 + 0.0286546*m.x265
+ 0.00245343*m.x266 - 0.0029273*m.x267 - 0.00576086*m.x268 + 0.0142978*m.x269
+ 0.000630997*m.x270 + 0.00317061*m.x271 - 0.0123761*m.x272 + 0.021312*m.x273
+ 0.00566315*m.x274 + 0.0328952*m.x275 - 0.00795682*m.x276 + 0.00577634*m.x277
+ 0.00671703*m.x278 + 0.0141594*m.x279 + 0.0189637*m.x280 - 0.0099332*m.x281
+ 0.0100466*m.x282 + 0.00647759*m.x283 + 0.0250933*m.x284 - 0.000881292*m.x285
+ 0.0263854*m.x286 + 0.0134424*m.x287 + 0.00802506*m.x288 + 0.00331125*m.x289
+ 0.00732372*m.x290 + 0.00825968*m.x291 + 0.0142932*m.x292 + 0.00984404*m.x293
- 0.00774969*m.x294 - 0.00584549*m.x295 - 0.00254807*m.x296 - 0.00996077*m.x297
- 0.00480671*m.x298 + 0.017175*m.x299 + 0.00103887*m.x300 - 2.46303E-5*m.x301
+ 0.00495815*m.x302 + 0.0225131*m.x303 == 0)
m.c162 = Constraint(expr= - m.x57 + 0.0112867*m.x204 + 0.0142655*m.x205 + 0.0357135*m.x206 + 0.0386991*m.x207
+ 0.0196795*m.x208 + 0.0133542*m.x209 + 0.03853*m.x210 + 0.0164155*m.x211 - 0.0145817*m.x212
+ 0.0215893*m.x213 + 0.0215114*m.x214 + 0.00837984*m.x215 + 0.0141785*m.x216
+ 0.00916835*m.x217 + 0.0297611*m.x218 + 0.0024162*m.x219 + 0.00156841*m.x220
+ 0.0426323*m.x221 + 0.00259346*m.x222 - 0.0199045*m.x223 + 0.00381282*m.x224
+ 0.020719*m.x225 + 0.00739069*m.x226 + 0.030732*m.x227 + 0.0219997*m.x228 + 0.0251306*m.x229
+ 0.00867625*m.x230 + 0.0408723*m.x231 - 0.00397893*m.x232 + 0.0137686*m.x233
+ 0.0182858*m.x234 + 0.0230993*m.x235 + 0.0388425*m.x236 + 0.012515*m.x237 + 0.00289448*m.x238
+ 0.00669218*m.x239 + 0.0824428*m.x240 + 0.0347475*m.x241 - 0.00209651*m.x242
+ 0.0118242*m.x243 + 0.037583*m.x244 + 0.0246255*m.x245 + 0.00853849*m.x246
+ 0.00559832*m.x247 + 0.0119362*m.x248 + 0.00745197*m.x249 + 0.00680548*m.x250
+ 0.0557771*m.x251 + 0.00310895*m.x252 + 0.0128203*m.x253 + 0.000656537*m.x254
+ 0.0175376*m.x255 + 0.0182593*m.x256 + 0.0267434*m.x257 - 0.0016753*m.x258 + 0.181831*m.x259
+ 0.0178859*m.x260 + 0.00593901*m.x261 + 0.0130043*m.x262 + 0.0296284*m.x263
+ 0.0122646*m.x264 + 0.00897029*m.x265 + 0.0101287*m.x266 - 0.0230152*m.x267
+ 0.0212254*m.x268 + 0.0151995*m.x269 + 0.00961517*m.x270 + 0.0216584*m.x271
+ 0.00890793*m.x272 + 0.0156085*m.x273 + 0.0179047*m.x274 + 0.0195461*m.x275
+ 0.0202055*m.x276 + 0.00312413*m.x277 - 0.0085337*m.x278 + 0.00691393*m.x279
+ 0.019103*m.x280 + 0.0121945*m.x281 - 0.01046*m.x282 + 7.7416E-5*m.x283 + 0.0195852*m.x284
+ 0.0203511*m.x285 + 0.00683799*m.x286 + 0.0150426*m.x287 + 0.0201186*m.x288
+ 0.0161444*m.x289 + 0.0127031*m.x290 + 0.0366677*m.x291 + 0.00820119*m.x292
- 0.00665374*m.x293 + 0.00551264*m.x294 + 0.0332128*m.x295 + 0.000520073*m.x296
- 0.00757188*m.x297 + 0.00641418*m.x298 + 0.00692204*m.x299 + 0.0175234*m.x300
- 0.0128168*m.x301 + 0.0164063*m.x302 + 0.00875325*m.x303 == 0)
m.c163 = Constraint(expr= - m.x58 + 0.0247222*m.x204 + 0.0264826*m.x205 - 0.00418977*m.x206 + 0.0209281*m.x207
+ 0.0144357*m.x208 + 0.0320697*m.x209 + 0.0225766*m.x210 - 0.00380167*m.x211
+ 0.00627821*m.x212 - 0.0026586*m.x213 + 0.0402573*m.x214 + 0.0137972*m.x215
+ 0.0210091*m.x216 + 0.022344*m.x217 + 0.0176119*m.x218 + 0.00726513*m.x219 + 0.0291383*m.x220
+ 0.00626505*m.x221 + 0.019997*m.x222 + 0.0230939*m.x223 + 0.0130988*m.x224 + 0.013493*m.x225
+ 0.0279297*m.x226 + 0.0159408*m.x227 + 0.0126357*m.x228 - 0.00245187*m.x229
- 0.0023455*m.x230 - 0.000700731*m.x231 - 0.00363432*m.x232 + 0.017504*m.x233
- 0.0042177*m.x234 + 0.0192279*m.x235 - 0.00375455*m.x236 + 0.00320118*m.x237
+ 0.00470079*m.x238 + 0.0128782*m.x239 + 0.0133704*m.x240 + 0.0244545*m.x241
+ 0.00931511*m.x242 + 0.0207329*m.x243 + 0.0180524*m.x244 + 0.0224446*m.x245
- 0.00130433*m.x246 - 0.00188392*m.x247 + 0.00907288*m.x248 + 0.01615*m.x249
+ 0.00742778*m.x250 - 0.00515185*m.x251 + 0.0185615*m.x252 + 0.0120199*m.x253
- 5.81815E-5*m.x254 + 0.0238431*m.x255 + 0.00378479*m.x256 + 0.0153667*m.x257
+ 0.0210475*m.x258 + 0.0178859*m.x259 + 0.139562*m.x260 - 0.00364834*m.x261 + 0.0199487*m.x262
- 0.00167911*m.x263 + 0.00860407*m.x264 - 0.0128582*m.x265 + 0.0245223*m.x266
- 0.00469692*m.x267 + 0.00503291*m.x268 + 0.00889461*m.x269 + 0.0140235*m.x270
+ 0.0150737*m.x271 - 0.0008781*m.x272 - 0.00187174*m.x273 + 0.00524362*m.x274
+ 0.0238296*m.x275 - 0.00255331*m.x276 + 0.0228347*m.x277 + 0.00908482*m.x278
- 0.000852062*m.x279 + 0.00890703*m.x280 + 0.0294183*m.x281 + 0.0037155*m.x282
+ 0.0369425*m.x283 + 0.0014252*m.x284 + 0.00588108*m.x285 + 0.0145498*m.x286
+ 0.0146631*m.x287 + 0.0173147*m.x288 + 0.0134929*m.x289 + 0.013611*m.x290 + 0.0214669*m.x291
+ 0.00624642*m.x292 + 0.00454738*m.x293 + 0.00717722*m.x294 + 0.0127629*m.x295
+ 0.019358*m.x296 + 0.0375824*m.x297 + 0.0198104*m.x298 + 0.0133092*m.x299 + 0.0195271*m.x300
- 0.00823347*m.x301 - 0.00820594*m.x302 + 0.00813384*m.x303 == 0)
m.c164 = Constraint(expr= - m.x59 - 0.0163525*m.x204 - 0.0200925*m.x205 + 0.030475*m.x206 + 0.0219851*m.x207
- 0.00152624*m.x208 - 0.0217595*m.x209 + 0.0150547*m.x210 + 0.0200358*m.x211
+ 0.00589982*m.x212 + 0.0389273*m.x213 + 0.00451804*m.x214 + 0.0176927*m.x215
+ 0.0471372*m.x216 + 0.00900194*m.x217 + 0.0115796*m.x218 + 0.032302*m.x219 + 0.0197841*m.x220
+ 0.00147777*m.x221 - 0.00264326*m.x222 + 0.0013091*m.x223 + 0.0115547*m.x224
+ 0.00400814*m.x225 + 0.0501498*m.x226 + 0.00458005*m.x227 + 0.0335534*m.x228
- 0.00390438*m.x229 + 0.00967889*m.x230 + 0.00840972*m.x231 + 0.0101807*m.x232
+ 0.0185947*m.x233 - 0.00092753*m.x234 + 0.0119446*m.x235 + 1.76484E-5*m.x236
- 0.000227592*m.x237 - 0.000123939*m.x238 - 0.00508847*m.x239 + 0.0137969*m.x240
+ 0.0126796*m.x241 - 0.00153738*m.x242 + 0.0150648*m.x243 + 0.0438692*m.x244
- 0.0172843*m.x245 + 0.00312367*m.x246 + 9.17403E-5*m.x247 - 0.04778*m.x248
+ 0.00117437*m.x249 + 9.53631E-5*m.x250 - 0.0101051*m.x251 + 0.0258631*m.x252
+ 0.0197559*m.x253 + 0.00610465*m.x254 - 0.0397472*m.x255 + 0.00402915*m.x256
- 0.0139925*m.x257 + 0.0394424*m.x258 + 0.00593901*m.x259 - 0.00364834*m.x260
+ 0.527736*m.x261 + 0.00582179*m.x262 + 0.0197223*m.x263 + 0.00508856*m.x264
+ 0.0419625*m.x265 - 0.0133944*m.x266 - 0.0152728*m.x267 + 0.0208192*m.x268 + 0.0106285*m.x269
+ 0.00455505*m.x270 + 0.0138845*m.x271 - 0.0100251*m.x272 + 0.00188325*m.x273
+ 0.00744129*m.x274 + 0.00536604*m.x275 - 0.00136449*m.x276 + 0.00692329*m.x277
+ 0.0109078*m.x278 - 0.00236473*m.x279 + 0.00505126*m.x280 + 0.0181113*m.x281
- 0.0184427*m.x282 - 0.00067668*m.x283 - 0.000180812*m.x284 + 0.020629*m.x285
- 0.00579727*m.x286 + 0.00633518*m.x287 - 0.0124431*m.x288 + 0.0253269*m.x289
+ 0.0201735*m.x290 + 0.017492*m.x291 + 0.0200526*m.x292 + 0.00522364*m.x293 + 0.0101262*m.x294
+ 0.033537*m.x295 + 0.0302725*m.x296 + 0.00311747*m.x297 + 0.00113182*m.x298
+ 0.0359219*m.x299 + 0.000595551*m.x300 + 4.13827E-5*m.x301 + 0.0152464*m.x302
- 0.0111606*m.x303 == 0)
m.c165 = Constraint(expr= - m.x60 + 0.00503011*m.x204 + 0.00429221*m.x205 - 0.0301452*m.x206 - 0.0106357*m.x207
- 0.00636291*m.x208 + 0.0127581*m.x209 - 0.00416059*m.x210 - 0.0132264*m.x211
+ 0.0158731*m.x212 + 0.00679229*m.x213 + 0.00173858*m.x214 - 0.00573209*m.x215
- 0.0173444*m.x216 + 0.00271829*m.x217 - 0.00309314*m.x218 - 0.000321415*m.x219
- 0.00560644*m.x220 + 0.0174915*m.x221 - 0.0162587*m.x222 - 0.0175093*m.x223
+ 0.0146067*m.x224 - 0.00800908*m.x225 + 0.00507925*m.x226 - 0.0105654*m.x227
+ 0.009157*m.x228 - 0.0316484*m.x229 + 0.00396363*m.x230 + 0.00252738*m.x231
- 0.0100285*m.x232 - 0.0233244*m.x233 + 0.00894155*m.x234 + 0.0224351*m.x235
+ 0.0261447*m.x236 + 0.0223779*m.x237 - 0.00572274*m.x238 - 0.0146124*m.x239
+ 0.00197565*m.x240 + 0.018523*m.x241 - 0.0039206*m.x242 - 0.00613654*m.x243
+ 0.0261745*m.x244 - 0.00143913*m.x245 - 0.0160088*m.x246 + 0.00219407*m.x247
- 0.0108826*m.x248 - 0.00321902*m.x249 - 0.00253774*m.x250 + 0.00981918*m.x251
+ 0.00933346*m.x252 + 0.0196814*m.x253 + 0.00544527*m.x254 - 0.0442114*m.x255
+ 0.00220607*m.x256 + 0.00410561*m.x257 - 0.0137174*m.x258 + 0.0130043*m.x259
+ 0.0199487*m.x260 + 0.00582179*m.x261 + 0.970548*m.x262 - 0.015973*m.x263 - 0.0127695*m.x264
+ 0.0162455*m.x265 - 0.0208167*m.x266 + 0.96806*m.x267 + 0.00562029*m.x268 - 0.00794541*m.x269
+ 0.000339474*m.x270 + 0.0011182*m.x271 + 0.00857265*m.x272 + 0.0126079*m.x273
- 0.018004*m.x274 - 0.0118023*m.x275 - 0.0147362*m.x276 - 0.00499549*m.x277 - 0.0143351*m.x278
+ 0.0135402*m.x279 + 0.000304222*m.x280 - 0.0196864*m.x281 + 0.0158055*m.x282
- 0.0123673*m.x283 + 0.0093129*m.x284 + 0.0180884*m.x285 - 0.0022627*m.x286 - 0.0178424*m.x287
+ 0.0201311*m.x288 + 0.0127648*m.x289 + 0.024251*m.x290 + 0.0212452*m.x291 + 0.0241234*m.x292
+ 0.0195278*m.x293 - 0.00432386*m.x294 - 0.00115008*m.x295 - 0.00414181*m.x296
- 0.0293668*m.x297 - 0.00629538*m.x298 - 0.0228968*m.x299 + 0.00307471*m.x300
+ 0.0204793*m.x301 + 0.00683967*m.x302 - 0.0105449*m.x303 == 0)
m.c166 = Constraint(expr= - m.x61 + 0.0521947*m.x204 + 0.0268675*m.x205 + 0.0467552*m.x206 + 0.0312148*m.x207
+ 0.00719514*m.x208 + 0.0200628*m.x209 + 0.00755277*m.x210 - 0.0108891*m.x211
- 0.00692226*m.x212 + 0.0607996*m.x213 + 0.0011291*m.x214 + 0.00992262*m.x215
+ 0.0395081*m.x216 - 0.0153606*m.x217 - 0.0165173*m.x218 - 0.0027376*m.x219
- 0.00570369*m.x220 - 0.0106458*m.x221 - 0.00236544*m.x222 + 0.0241302*m.x223
+ 0.0110104*m.x224 + 0.0239775*m.x225 + 0.018196*m.x226 - 0.0022915*m.x227 + 0.0103454*m.x228
+ 0.0136876*m.x229 + 0.0431392*m.x230 + 0.0676544*m.x231 + 0.0068697*m.x232
+ 0.00418422*m.x233 + 0.0454908*m.x234 + 0.022391*m.x235 + 0.0421239*m.x236
+ 0.00773196*m.x237 + 0.00812701*m.x238 + 0.0225587*m.x239 + 0.0284788*m.x240
+ 0.00388717*m.x241 + 0.0154733*m.x242 + 0.0074099*m.x243 - 0.0114466*m.x244
+ 0.0179142*m.x245 + 0.0308548*m.x246 + 0.00878374*m.x247 + 0.00420738*m.x248
+ 0.00508728*m.x249 + 0.0180458*m.x250 + 0.117196*m.x251 - 0.0221839*m.x252
+ 0.00428319*m.x253 + 0.0153454*m.x254 + 0.0518827*m.x255 + 0.0103192*m.x256
+ 0.0255464*m.x257 + 0.0251559*m.x258 + 0.0296284*m.x259 - 0.00167911*m.x260
+ 0.0197223*m.x261 - 0.015973*m.x262 + 0.336744*m.x263 + 0.0252049*m.x264 - 0.000715187*m.x265
- 0.0105093*m.x266 - 0.00396636*m.x267 + 0.020192*m.x268 + 0.0240284*m.x269
+ 0.00646055*m.x270 + 0.0240529*m.x271 - 0.0104475*m.x272 - 0.0100576*m.x273
+ 0.00619413*m.x274 + 0.0152866*m.x275 + 0.0172916*m.x276 - 0.0067214*m.x277
+ 0.00669297*m.x278 + 0.013914*m.x279 + 0.0234397*m.x280 + 0.0236703*m.x281 + 0.0307119*m.x282
+ 0.0135874*m.x283 + 0.0408449*m.x284 + 0.00693809*m.x285 + 0.0213571*m.x286
+ 0.0130973*m.x287 + 0.0121195*m.x288 + 0.0119547*m.x289 + 0.00901592*m.x290
+ 0.0227243*m.x291 + 0.00169162*m.x292 - 0.00631568*m.x293 - 0.014748*m.x294
+ 0.0202061*m.x295 + 0.00890168*m.x296 - 0.0256392*m.x297 + 0.046066*m.x298 - 0.0109849*m.x299
+ 0.00658164*m.x300 + 0.0362579*m.x301 + 0.00917306*m.x302 + 0.0146768*m.x303 == 0)
m.c167 = Constraint(expr= - m.x62 - 0.00318536*m.x204 - 0.00173957*m.x205 + 0.0103264*m.x206 + 0.0168165*m.x207
+ 0.0109626*m.x208 + 0.0123119*m.x209 - 0.0018521*m.x210 + 0.020785*m.x211 + 0.018374*m.x212
+ 0.0264003*m.x213 + 0.0213333*m.x214 + 0.00917944*m.x215 + 0.0341682*m.x216
+ 0.0224616*m.x217 + 0.0275152*m.x218 + 0.0190897*m.x219 + 0.0191435*m.x220 - 0.0268525*m.x221
- 0.00879978*m.x222 + 0.0125103*m.x223 + 0.0023853*m.x224 + 0.0023628*m.x225 + 0.011861*m.x226
+ 0.0289602*m.x227 + 0.00485118*m.x228 - 0.000726206*m.x229 + 0.0248388*m.x230
+ 0.01361*m.x231 + 0.0418921*m.x232 + 0.0090785*m.x233 + 0.0349551*m.x234 + 0.0160624*m.x235
- 0.00545796*m.x236 + 0.00267723*m.x237 - 0.00120612*m.x238 + 0.00526915*m.x239
+ 0.0192414*m.x240 + 0.020429*m.x241 + 0.034914*m.x242 + 0.0159826*m.x243 + 0.019726*m.x244
+ 0.00496924*m.x245 + 0.0187432*m.x246 + 0.00816234*m.x247 + 0.0658392*m.x248
+ 0.00978353*m.x249 + 0.0185083*m.x250 + 0.00665526*m.x251 + 0.0236734*m.x252
+ 0.0202022*m.x253 + 0.0292089*m.x254 + 0.0161886*m.x255 + 0.0152444*m.x256 + 0.0476449*m.x257
+ 0.004979*m.x258 + 0.0122646*m.x259 + 0.00860407*m.x260 + 0.00508856*m.x261
- 0.0127695*m.x262 + 0.0252049*m.x263 + 0.384602*m.x264 + 0.0253864*m.x265 + 0.0160924*m.x266
- 0.0390907*m.x267 + 0.00154115*m.x268 + 0.00142817*m.x269 + 0.00464688*m.x270
+ 0.0433953*m.x271 - 0.0108651*m.x272 + 0.0208448*m.x273 - 0.00749905*m.x274
+ 0.0181994*m.x275 + 0.0583548*m.x276 + 0.057555*m.x277 + 0.0268228*m.x278 - 0.00819768*m.x279
- 0.00195137*m.x280 + 0.0198979*m.x281 + 0.216012*m.x282 + 0.00795018*m.x283
+ 0.00230105*m.x284 + 0.0194778*m.x285 + 0.00852926*m.x286 + 0.0180986*m.x287
+ 0.0217749*m.x288 + 0.00366775*m.x289 - 0.00447213*m.x290 + 0.0267458*m.x291
+ 0.0216534*m.x292 + 0.0107144*m.x293 + 0.0142204*m.x294 + 0.0660462*m.x295 - 0.0111379*m.x296
- 0.0165798*m.x297 + 0.0260859*m.x298 + 0.0220738*m.x299 + 0.0291965*m.x300
- 0.00087998*m.x301 + 0.00952427*m.x302 + 0.00243344*m.x303 == 0)
m.c168 = Constraint(expr= - m.x63 + 0.0012286*m.x204 + 0.00182754*m.x205 - 0.0157278*m.x206 + 0.0159145*m.x207
+ 0.00565965*m.x208 + 0.0263411*m.x209 - 0.0101745*m.x210 + 0.0086092*m.x211
+ 0.00783315*m.x212 + 0.00577287*m.x213 + 0.00782635*m.x214 - 0.00185404*m.x215
+ 0.0266136*m.x216 + 0.0145659*m.x217 + 0.0464477*m.x218 + 0.0346448*m.x219 + 0.0154717*m.x220
- 0.00592304*m.x221 - 0.0199739*m.x222 + 0.0245635*m.x223 + 0.00213944*m.x224
+ 0.041102*m.x225 + 0.016458*m.x226 + 0.0145756*m.x227 + 0.0191232*m.x228 + 0.0163476*m.x229
+ 0.0208145*m.x230 + 0.010551*m.x231 - 0.00534991*m.x232 + 0.00995839*m.x233
+ 0.0343384*m.x234 - 0.00427316*m.x235 + 0.0164325*m.x236 - 0.00201299*m.x237
+ 0.0192903*m.x238 + 0.0180621*m.x239 + 0.0212005*m.x240 + 0.0233626*m.x241 + 0.0149224*m.x242
+ 0.0065965*m.x243 + 0.0217904*m.x244 + 0.012034*m.x245 - 0.00426161*m.x246 + 0.0139761*m.x247
- 0.00210493*m.x248 + 0.0167338*m.x249 + 0.0187542*m.x250 - 0.0175406*m.x251
+ 0.0176283*m.x252 + 0.0291275*m.x253 + 0.0160595*m.x254 + 0.00172998*m.x255
+ 0.0220514*m.x256 + 0.0288895*m.x257 + 0.0286546*m.x258 + 0.00897029*m.x259
- 0.0128582*m.x260 + 0.0419625*m.x261 + 0.0162455*m.x262 - 0.000715187*m.x263
+ 0.0253864*m.x264 + 0.270277*m.x265 + 0.0160166*m.x266 + 0.0135735*m.x267 + 0.00161591*m.x268
+ 0.0132148*m.x269 + 0.00836484*m.x270 + 0.0194914*m.x271 + 0.00987742*m.x272
- 0.0115779*m.x273 - 0.000442365*m.x274 + 0.0365121*m.x275 + 0.0226464*m.x276
+ 0.0143164*m.x277 + 0.00841295*m.x278 + 0.00921905*m.x279 + 0.00349776*m.x280
+ 0.0226748*m.x281 - 0.00159181*m.x282 + 0.00683403*m.x283 + 0.000980679*m.x284
+ 0.00186047*m.x285 + 0.0167378*m.x286 - 0.0130487*m.x287 + 0.00624026*m.x288
+ 0.0174197*m.x289 + 0.0230098*m.x290 + 9.8143E-5*m.x291 - 0.00953022*m.x292
+ 0.0169729*m.x293 + 0.0174156*m.x294 + 0.0182632*m.x295 + 0.00110738*m.x296
- 0.00610696*m.x297 + 0.0117812*m.x298 + 0.0127772*m.x299 + 0.0162*m.x300 - 0.0368529*m.x301
+ 0.0012669*m.x302 + 0.000788331*m.x303 == 0)
m.c169 = Constraint(expr= - m.x64 - 0.0157072*m.x204 + 0.0102239*m.x205 + 0.0167359*m.x206 - 0.00939875*m.x207
+ 0.0101803*m.x208 + 0.00564516*m.x209 - 0.00307772*m.x210 - 0.00880776*m.x211
- 0.00318606*m.x212 + 0.00499131*m.x213 + 0.031041*m.x214 + 0.00351722*m.x215
+ 0.00530461*m.x216 + 0.00845039*m.x217 + 0.00779052*m.x218 + 0.0276531*m.x219
+ 0.0101111*m.x220 + 0.0265062*m.x221 - 0.039269*m.x222 + 0.0207647*m.x223 + 0.0115639*m.x224
+ 0.0213565*m.x225 + 0.0113615*m.x226 + 4.79134E-5*m.x227 + 0.0224758*m.x228
+ 0.00918681*m.x229 - 0.0164721*m.x230 - 0.00205468*m.x231 - 0.0119127*m.x232
+ 0.0128665*m.x233 + 0.00879992*m.x234 + 0.00900964*m.x235 + 0.00365749*m.x236
+ 0.0224861*m.x237 + 0.0176128*m.x238 - 0.00562995*m.x239 + 0.0139235*m.x240
+ 0.00698084*m.x241 + 0.0117364*m.x242 + 0.0154181*m.x243 - 0.0131236*m.x244
- 0.00248961*m.x245 - 0.00773906*m.x246 + 0.00238266*m.x247 - 0.00489265*m.x248
- 0.000552346*m.x249 - 0.00848668*m.x250 - 0.00134639*m.x251 + 0.00446979*m.x252
+ 0.0180013*m.x253 - 0.00416091*m.x254 - 0.0149321*m.x255 + 0.0445908*m.x256
+ 0.00855635*m.x257 + 0.00245343*m.x258 + 0.0101287*m.x259 + 0.0245223*m.x260
- 0.0133944*m.x261 - 0.0208167*m.x262 - 0.0105093*m.x263 + 0.0160924*m.x264 + 0.0160166*m.x265
+ 0.383003*m.x266 - 0.00100771*m.x267 - 0.0063251*m.x268 + 0.00048997*m.x269
+ 0.0187309*m.x270 + 0.0152904*m.x271 + 0.0500151*m.x272 - 0.00998242*m.x273
- 0.000518247*m.x274 - 0.00949741*m.x275 - 0.00246233*m.x276 + 0.0237049*m.x277
- 0.00277129*m.x278 - 0.0145486*m.x279 - 0.0063327*m.x280 + 0.00429669*m.x281
+ 0.0119178*m.x282 - 0.0166029*m.x283 - 0.00474646*m.x284 - 0.00414121*m.x285
- 0.011543*m.x286 + 0.00920493*m.x287 + 0.0194176*m.x288 + 0.00717868*m.x289
- 0.0100831*m.x290 - 0.00430908*m.x291 + 0.0313277*m.x292 + 0.00449822*m.x293
- 0.00307272*m.x294 + 0.00735778*m.x295 + 0.015328*m.x296 - 0.00549157*m.x297
+ 0.0169898*m.x298 + 0.0267541*m.x299 - 0.019998*m.x300 - 0.00561625*m.x301 - 0.010356*m.x302
+ 0.0111971*m.x303 == 0)
m.c170 = Constraint(expr= - m.x65 - 0.0502192*m.x204 - 0.0136152*m.x205 + 0.00653818*m.x206 + 0.0209841*m.x207
- 0.0016346*m.x208 - 0.0172992*m.x209 - 0.00815475*m.x210 - 0.0195389*m.x211
+ 0.0253862*m.x212 - 0.00587637*m.x213 + 0.0122097*m.x214 - 0.0165471*m.x215
- 0.00299125*m.x216 - 0.01842*m.x217 - 0.0226061*m.x218 + 0.000561195*m.x219
- 0.00546503*m.x220 - 0.0314803*m.x221 - 0.0186926*m.x222 - 0.0191503*m.x223
- 0.00246673*m.x224 - 0.0313508*m.x225 - 0.00261119*m.x226 - 0.00267369*m.x227
+ 0.00227773*m.x228 - 0.0125721*m.x229 - 0.0223038*m.x230 - 0.00837042*m.x231
- 0.00152064*m.x232 + 0.00262393*m.x233 - 0.00543751*m.x234 - 0.00432735*m.x235
- 0.0388477*m.x236 - 0.0272888*m.x237 - 0.0403434*m.x238 + 0.00935786*m.x239
- 0.0180328*m.x240 + 0.00155564*m.x241 + 0.00189931*m.x242 + 0.00135221*m.x243
+ 0.00012462*m.x244 - 0.00825333*m.x245 + 0.00306814*m.x246 - 0.00331267*m.x247
- 0.0339851*m.x248 - 0.0124862*m.x249 - 0.0111347*m.x250 - 0.039556*m.x251 - 0.0128737*m.x252
- 0.00816153*m.x253 - 0.0114877*m.x254 - 0.00526354*m.x255 - 0.00977257*m.x256
- 0.0298097*m.x257 - 0.0029273*m.x258 - 0.0230152*m.x259 - 0.00469692*m.x260
- 0.0152728*m.x261 + 0.96806*m.x262 - 0.00396636*m.x263 - 0.0390907*m.x264 + 0.0135735*m.x265
- 0.00100771*m.x266 + 1.66947*m.x267 + 0.00495846*m.x268 + 0.000382122*m.x269
+ 0.00474442*m.x270 - 0.0198*m.x271 - 0.00114484*m.x272 + 0.0441795*m.x273 - 0.00598213*m.x274
- 0.00477587*m.x275 - 0.025348*m.x276 - 0.0195708*m.x277 - 0.00168274*m.x278
- 0.0318426*m.x279 - 0.00658838*m.x280 - 0.0168533*m.x281 - 0.0154167*m.x282 - 0.018515*m.x283
+ 0.00103058*m.x284 - 0.0178181*m.x285 - 0.0183739*m.x286 - 0.0131486*m.x287
+ 0.000857968*m.x288 + 0.0083299*m.x289 - 0.000461334*m.x290 + 0.0704456*m.x291
+ 0.00562888*m.x292 + 0.0251025*m.x293 + 0.00344892*m.x294 - 0.0224606*m.x295
+ 0.00833154*m.x296 - 0.0234811*m.x297 - 0.0262964*m.x298 - 0.0175235*m.x299
+ 0.0205719*m.x300 - 0.0402272*m.x301 - 0.00924209*m.x302 + 0.0228584*m.x303 == 0)
m.c171 = Constraint(expr= - m.x66 - 0.00188018*m.x204 + 0.0458865*m.x205 + 0.0409725*m.x206 + 0.0190617*m.x207
+ 0.0277761*m.x208 + 0.0342875*m.x209 + 0.0229656*m.x210 + 0.00208113*m.x211
- 0.00670214*m.x212 + 0.0419289*m.x213 + 0.00799351*m.x214 - 0.0113949*m.x215
+ 0.00534225*m.x216 + 0.0230371*m.x217 + 0.0267434*m.x218 + 0.00605195*m.x219
+ 0.0144737*m.x220 - 0.00113399*m.x221 + 0.0490725*m.x222 - 0.0052634*m.x223
+ 0.0109023*m.x224 + 0.0464899*m.x225 + 0.0194988*m.x226 + 0.00284388*m.x227
+ 0.00710476*m.x228 + 0.0319031*m.x229 + 0.0536968*m.x230 + 0.0198054*m.x231
+ 0.0221966*m.x232 + 0.0238425*m.x233 + 0.04327*m.x234 + 0.0397561*m.x235 + 0.0381643*m.x236
+ 0.0102053*m.x237 + 0.00674116*m.x238 + 0.0359849*m.x239 + 0.0362249*m.x240
+ 0.00767128*m.x241 - 0.000952693*m.x242 + 0.00855652*m.x243 + 0.0111129*m.x244
+ 0.02346*m.x245 + 0.0128287*m.x246 + 0.0130905*m.x247 + 0.0142713*m.x248 + 0.0092919*m.x249
+ 0.029197*m.x250 - 0.00784993*m.x251 - 0.00682462*m.x252 - 0.0005624*m.x253
- 0.00518739*m.x254 + 0.0191389*m.x255 + 0.00947946*m.x256 - 0.0193235*m.x257
- 0.00576086*m.x258 + 0.0212254*m.x259 + 0.00503291*m.x260 + 0.0208192*m.x261
+ 0.00562029*m.x262 + 0.020192*m.x263 + 0.00154115*m.x264 + 0.00161591*m.x265
- 0.0063251*m.x266 + 0.00495846*m.x267 + 0.228481*m.x268 + 0.0490214*m.x269 + 0.0126939*m.x270
+ 0.0286928*m.x271 + 0.00630082*m.x272 - 0.0070283*m.x273 + 0.0105371*m.x274
+ 0.0142667*m.x275 + 0.00283098*m.x276 + 0.0181153*m.x277 + 0.00272646*m.x278
+ 0.00912054*m.x279 + 0.0236631*m.x280 + 0.012122*m.x281 + 0.00657829*m.x282
- 0.0121548*m.x283 + 0.0355309*m.x284 + 0.00535639*m.x285 - 0.0102352*m.x286
+ 0.0343148*m.x287 + 0.0161535*m.x288 + 0.0145892*m.x289 + 0.00586937*m.x290
+ 0.0392681*m.x291 + 0.0321897*m.x292 + 0.00459229*m.x293 - 0.00116349*m.x294
+ 0.00533042*m.x295 + 0.0083884*m.x296 - 0.00154795*m.x297 + 0.00327212*m.x298
+ 0.0425838*m.x299 + 0.0191781*m.x300 + 0.00444886*m.x301 + 0.0219505*m.x302
+ 0.0116164*m.x303 == 0)
m.c172 = Constraint(expr= - m.x67 + 0.00421152*m.x204 + 0.0178109*m.x205 + 0.0331419*m.x206 + 0.0158536*m.x207
+ 0.0225116*m.x208 + 0.0155064*m.x209 - 0.00130048*m.x210 - 0.00273464*m.x211 + 0.01518*m.x212
+ 0.00163644*m.x213 - 0.00702948*m.x214 + 0.00780787*m.x215 - 0.00371224*m.x216
+ 0.00761157*m.x217 + 0.0145246*m.x218 + 0.0080424*m.x219 + 0.0137256*m.x220
- 0.00330446*m.x221 + 0.031858*m.x222 + 0.00488365*m.x223 + 0.00914522*m.x224
+ 0.0119209*m.x225 + 0.0159019*m.x226 + 0.00640165*m.x227 + 0.00283558*m.x228
+ 0.0180154*m.x229 + 0.0222226*m.x230 + 0.0122407*m.x231 + 0.0135936*m.x232 + 0.0205163*m.x233
+ 0.0141045*m.x234 + 0.00466481*m.x235 + 0.0228523*m.x236 + 0.00464414*m.x237
+ 0.00290841*m.x238 + 0.00335704*m.x239 + 0.0194911*m.x240 + 0.0118559*m.x241
+ 0.00134611*m.x242 + 0.0195004*m.x243 - 0.00456618*m.x244 + 0.02262*m.x245
+ 0.00522194*m.x246 - 0.00761858*m.x247 + 0.00850407*m.x248 - 0.000986526*m.x249
+ 0.0134837*m.x250 + 0.0249045*m.x251 + 0.00523125*m.x252 + 0.0104426*m.x253
+ 0.00285023*m.x254 - 0.000438258*m.x255 + 0.0081976*m.x256 - 0.00212818*m.x257
+ 0.0142978*m.x258 + 0.0151995*m.x259 + 0.00889461*m.x260 + 0.0106285*m.x261
- 0.00794541*m.x262 + 0.0240284*m.x263 + 0.00142817*m.x264 + 0.0132148*m.x265
+ 0.00048997*m.x266 + 0.000382122*m.x267 + 0.0490214*m.x268 + 0.100974*m.x269
+ 0.0128903*m.x270 + 0.00548068*m.x271 + 0.0199531*m.x272 + 0.0127807*m.x273
- 0.0025092*m.x274 + 0.0133094*m.x275 + 0.0060945*m.x276 - 0.00787035*m.x277
+ 0.00700317*m.x278 + 0.010213*m.x279 + 0.0358489*m.x280 + 0.0181724*m.x281
+ 0.00656133*m.x282 + 0.00426715*m.x283 + 0.0279955*m.x284 + 0.0107345*m.x285
- 0.00277805*m.x286 + 0.0184565*m.x287 + 0.00461119*m.x288 + 0.0123007*m.x289
+ 0.00724424*m.x290 + 0.0184584*m.x291 + 0.0225319*m.x292 - 0.00115612*m.x293
+ 0.000984092*m.x294 + 0.000260201*m.x295 - 0.00178894*m.x296 + 0.00486873*m.x297
+ 0.01*m.x298 + 0.00629557*m.x299 + 0.0103958*m.x300 + 0.0109707*m.x301 + 0.0344609*m.x302
+ 0.00845491*m.x303 == 0)
m.c173 = Constraint(expr= - m.x68 + 0.0127643*m.x204 + 0.0122813*m.x205 + 0.0180349*m.x206 + 0.0246904*m.x207
- 0.00484509*m.x208 - 0.00477146*m.x209 + 0.00871877*m.x210 - 0.000357808*m.x211
+ 0.0331725*m.x212 + 0.00084169*m.x213 + 0.00472328*m.x214 - 0.00223059*m.x215
+ 0.0103986*m.x216 + 0.00153703*m.x217 + 0.00693016*m.x218 + 0.0117333*m.x219
+ 0.0283908*m.x220 + 0.0280983*m.x221 - 0.00221523*m.x222 + 0.0136006*m.x223
+ 0.0180464*m.x224 - 0.00311277*m.x225 + 0.0101301*m.x226 + 0.00361398*m.x227
- 0.00150208*m.x228 - 0.00293849*m.x229 - 0.00759212*m.x230 + 0.00412582*m.x231
+ 0.0218822*m.x232 + 0.000443199*m.x233 - 0.00442873*m.x234 + 0.0123178*m.x235
+ 0.012621*m.x236 + 0.0165262*m.x237 + 0.0214671*m.x238 - 0.00719511*m.x239
- 0.00221392*m.x240 + 0.0189483*m.x241 - 0.000237938*m.x242 + 0.013074*m.x243
+ 0.00494008*m.x244 + 0.00735435*m.x245 + 0.00258635*m.x246 + 0.00239066*m.x247
- 0.00279322*m.x248 + 0.004509*m.x249 + 0.0134453*m.x250 - 0.00128867*m.x251
+ 0.0213069*m.x252 + 0.030677*m.x253 - 0.00263203*m.x254 - 0.00523691*m.x255
+ 0.00899719*m.x256 + 0.0152037*m.x257 + 0.000630997*m.x258 + 0.00961517*m.x259
+ 0.0140235*m.x260 + 0.00455505*m.x261 + 0.000339474*m.x262 + 0.00646055*m.x263
+ 0.00464688*m.x264 + 0.00836484*m.x265 + 0.0187309*m.x266 + 0.00474442*m.x267
+ 0.0126939*m.x268 + 0.0128903*m.x269 + 0.114142*m.x270 + 0.00309128*m.x271 + 0.0100597*m.x272
+ 0.0162104*m.x273 + 0.00865013*m.x274 + 0.00955259*m.x275 - 0.00981226*m.x276
+ 0.0203602*m.x277 + 0.0117019*m.x278 - 0.00029594*m.x279 + 0.00560833*m.x280
+ 0.00249681*m.x281 + 0.0204625*m.x282 - 0.0104074*m.x283 - 0.00117293*m.x284
+ 0.0119469*m.x285 + 0.0145851*m.x286 + 0.010394*m.x287 + 0.00513963*m.x288 + 0.0107918*m.x289
+ 0.0130978*m.x290 + 0.00470305*m.x291 + 0.0108874*m.x292 + 0.0151819*m.x293
+ 0.0195643*m.x294 + 0.0289658*m.x295 + 0.000514941*m.x296 - 0.00429564*m.x297
+ 0.0195899*m.x298 - 0.00999522*m.x299 + 0.00608684*m.x300 - 0.0133354*m.x301
+ 0.00371045*m.x302 - 0.00737205*m.x303 == 0)
m.c174 = Constraint(expr= - m.x69 + 0.0174037*m.x204 + 0.0104665*m.x205 + 0.0284386*m.x206 + 0.00427924*m.x207
+ 0.0047708*m.x208 + 0.00415194*m.x209 - 0.0045347*m.x210 + 0.0647172*m.x211
- 0.0229361*m.x212 + 0.00995171*m.x213 + 0.0103154*m.x214 + 0.0206811*m.x215
+ 0.0396039*m.x216 + 0.0263619*m.x217 + 0.0360689*m.x218 + 0.00873924*m.x219
+ 0.0212112*m.x220 - 0.000715512*m.x221 + 0.0134724*m.x222 - 0.00533096*m.x223
- 0.00139956*m.x224 + 0.0170407*m.x225 + 0.00719955*m.x226 + 0.0012624*m.x227
+ 0.0113113*m.x228 + 0.0370056*m.x229 - 0.0161031*m.x230 + 0.0114679*m.x231 - 0.0103847*m.x232
+ 0.0116392*m.x233 + 0.0329931*m.x234 + 0.0294165*m.x235 + 0.032511*m.x236 + 0.0099305*m.x237
+ 0.00882407*m.x238 + 0.017117*m.x239 + 0.0224423*m.x240 + 0.0125617*m.x241 + 0.0043024*m.x242
+ 0.0246559*m.x243 + 0.0375735*m.x244 + 0.00373612*m.x245 + 0.0129953*m.x246
+ 0.00767196*m.x247 + 0.00139531*m.x248 + 0.00222268*m.x249 + 0.0159389*m.x250
- 0.00261452*m.x251 + 0.0081431*m.x252 + 0.00414094*m.x253 + 0.00784535*m.x254
- 0.00972975*m.x255 + 0.0216871*m.x256 + 0.0243197*m.x257 + 0.00317061*m.x258
+ 0.0216584*m.x259 + 0.0150737*m.x260 + 0.0138845*m.x261 + 0.0011182*m.x262 + 0.0240529*m.x263
+ 0.0433953*m.x264 + 0.0194914*m.x265 + 0.0152904*m.x266 - 0.0198*m.x267 + 0.0286928*m.x268
+ 0.00548068*m.x269 + 0.00309128*m.x270 + 0.217144*m.x271 + 0.000766422*m.x272
+ 0.0266859*m.x273 - 0.00234615*m.x274 + 0.0268143*m.x275 + 0.0340288*m.x276
+ 0.0271041*m.x277 + 0.026112*m.x278 + 0.00239456*m.x279 + 0.00576057*m.x280
+ 0.0326962*m.x281 + 0.0163689*m.x282 - 0.00776661*m.x283 + 0.00451059*m.x284
+ 0.00792609*m.x285 + 0.00416542*m.x286 - 0.0019629*m.x287 + 0.0236126*m.x288
+ 0.0137167*m.x289 + 0.0121892*m.x290 + 0.000632641*m.x291 + 0.00328551*m.x292
- 0.00509853*m.x293 + 0.0148681*m.x294 + 0.0201209*m.x295 + 0.023585*m.x296
- 0.00188899*m.x297 - 0.0117063*m.x298 + 0.0273148*m.x299 + 0.0284999*m.x300
- 0.00353962*m.x301 + 0.00538445*m.x302 - 0.00465145*m.x303 == 0)
m.c175 = Constraint(expr= - m.x70 - 0.0100234*m.x204 - 0.0209121*m.x205 - 0.00694428*m.x206 - 0.00467471*m.x207
+ 0.00518488*m.x208 + 0.00797725*m.x209 - 0.0157399*m.x210 - 0.0015303*m.x211
- 0.0365251*m.x212 + 0.00125486*m.x213 + 0.0289129*m.x214 + 0.0521517*m.x215
- 0.00150631*m.x216 + 0.0097183*m.x217 + 0.0138448*m.x218 + 0.0161705*m.x219
+ 0.00924645*m.x220 + 0.0345476*m.x221 - 0.0102334*m.x222 - 0.00725643*m.x223
+ 0.0063742*m.x224 + 0.00635872*m.x225 + 0.00758332*m.x226 + 0.000823775*m.x227
+ 0.0160374*m.x228 - 0.0102022*m.x229 - 0.00658237*m.x230 + 0.0149085*m.x231
+ 0.0192043*m.x232 + 0.0183888*m.x233 + 0.00515876*m.x234 + 0.00210584*m.x235
+ 0.0106022*m.x236 + 0.000867918*m.x237 + 0.00182329*m.x238 + 0.00398062*m.x239
+ 0.00992082*m.x240 + 0.0165632*m.x241 - 0.0220684*m.x242 + 0.00174793*m.x243
- 0.0151984*m.x244 + 0.0174021*m.x245 + 0.000800136*m.x246 + 0.0121103*m.x247
+ 0.00256477*m.x248 + 0.00595866*m.x249 - 0.00298889*m.x250 + 0.039282*m.x251
+ 0.00415461*m.x252 + 0.0226546*m.x253 + 0.00552304*m.x254 - 0.0150659*m.x255 + 0.0232*m.x256
+ 0.0286571*m.x257 - 0.0123761*m.x258 + 0.00890793*m.x259 - 0.0008781*m.x260
- 0.0100251*m.x261 + 0.00857265*m.x262 - 0.0104475*m.x263 - 0.0108651*m.x264
+ 0.00987742*m.x265 + 0.0500151*m.x266 - 0.00114484*m.x267 + 0.00630082*m.x268
+ 0.0199531*m.x269 + 0.0100597*m.x270 + 0.000766422*m.x271 + 0.158054*m.x272
+ 0.00336053*m.x273 + 0.0289311*m.x274 + 0.00013573*m.x275 + 0.00721954*m.x276
- 0.00673825*m.x277 + 0.0133065*m.x278 + 0.0477885*m.x279 + 0.0279617*m.x280
- 0.00676451*m.x281 + 0.0244657*m.x282 + 0.011568*m.x283 - 0.00233863*m.x284
+ 0.0116962*m.x285 + 0.013257*m.x286 - 0.000584023*m.x287 - 0.00369328*m.x288
+ 0.0104073*m.x289 - 0.00391704*m.x290 - 0.0303804*m.x291 + 0.00348223*m.x292
- 0.00324749*m.x293 + 0.00746468*m.x294 - 0.00652909*m.x295 + 0.00590442*m.x296
- 0.0198962*m.x297 + 0.015777*m.x298 + 0.0320781*m.x299 - 0.00215074*m.x300 + 0.010315*m.x301
+ 0.0111624*m.x302 + 0.0154715*m.x303 == 0)
m.c176 = Constraint(expr= - m.x71 - 0.00217682*m.x204 + 0.00754928*m.x205 + 0.00602621*m.x206 + 0.0177642*m.x207
+ 0.0126256*m.x208 + 0.0134081*m.x209 + 0.00177914*m.x210 + 0.0129634*m.x211
+ 0.0190496*m.x212 + 0.000587184*m.x213 + 0.00688368*m.x214 - 0.00351079*m.x215
+ 0.0236174*m.x216 + 0.0242111*m.x217 + 0.00553718*m.x218 + 0.0227344*m.x219 + 0.038139*m.x220
+ 0.0640862*m.x221 + 0.0063437*m.x222 + 0.0124666*m.x223 - 0.0221093*m.x224 + 0.054717*m.x225
+ 0.00284196*m.x226 - 0.00175507*m.x227 + 0.0206604*m.x228 + 0.0059304*m.x229
+ 0.000576553*m.x230 + 0.00320993*m.x231 + 0.00830569*m.x232 + 0.0157507*m.x233
- 0.0196528*m.x234 + 0.0156664*m.x235 + 0.0149868*m.x236 + 0.00439394*m.x237
+ 0.0121867*m.x238 + 0.0225777*m.x239 + 0.0236908*m.x240 + 0.0205214*m.x241 - 0.0319066*m.x242
- 0.00079277*m.x243 + 0.112574*m.x244 - 0.0101958*m.x245 - 0.0165869*m.x246
- 0.00250388*m.x247 + 0.0206991*m.x248 - 0.00295638*m.x249 - 0.0125802*m.x250
+ 0.0509997*m.x251 + 0.0073977*m.x252 + 0.0125649*m.x253 - 0.00966017*m.x254
- 0.0484007*m.x255 + 0.0135089*m.x256 + 0.0238634*m.x257 + 0.021312*m.x258 + 0.0156085*m.x259
- 0.00187174*m.x260 + 0.00188325*m.x261 + 0.0126079*m.x262 - 0.0100576*m.x263
+ 0.0208448*m.x264 - 0.0115779*m.x265 - 0.00998242*m.x266 + 0.0441795*m.x267
- 0.0070283*m.x268 + 0.0127807*m.x269 + 0.0162104*m.x270 + 0.0266859*m.x271
+ 0.00336053*m.x272 + 0.315581*m.x273 + 0.0438235*m.x274 + 0.0578188*m.x275 + 0.0280953*m.x276
+ 0.0335154*m.x277 + 0.0472914*m.x278 + 0.0379*m.x279 + 0.0060603*m.x280 + 0.01743*m.x281
+ 0.00347436*m.x282 + 0.0134516*m.x283 - 0.0215081*m.x284 - 0.00588027*m.x285
+ 0.023436*m.x286 + 0.0518973*m.x287 + 0.00558955*m.x288 + 0.0276924*m.x289 + 0.0289396*m.x290
- 0.00526134*m.x291 + 0.012689*m.x292 + 0.0135528*m.x293 + 0.0136874*m.x294
- 0.000426475*m.x295 + 0.020855*m.x296 - 0.00692332*m.x297 + 0.00700229*m.x298
+ 0.016756*m.x299 + 0.0360264*m.x300 - 0.0259344*m.x301 + 0.00953552*m.x302 + 0.0189209*m.x303
== 0)
m.c177 = Constraint(expr= - m.x72 + 0.00605866*m.x204 + 0.00403463*m.x205 + 0.0281091*m.x206 + 0.00659994*m.x207
- 0.00994378*m.x208 + 0.0355325*m.x209 + 0.0272626*m.x210 - 0.000139358*m.x211
+ 0.00542296*m.x212 + 0.00290832*m.x213 + 0.0161368*m.x214 + 0.0212677*m.x215
+ 0.0233436*m.x216 + 0.00779182*m.x217 + 0.0203622*m.x218 + 0.0198156*m.x219
+ 0.00987474*m.x220 + 0.159324*m.x221 - 0.00607453*m.x222 + 0.0367354*m.x223
+ 0.00993636*m.x224 - 0.0107438*m.x225 - 0.00558828*m.x226 + 0.00806781*m.x227
+ 0.0321612*m.x228 + 0.00317033*m.x229 + 0.00804996*m.x230 + 0.00437204*m.x231
- 0.00295904*m.x232 + 0.011888*m.x233 - 0.0113905*m.x234 + 0.0141543*m.x235
- 0.00272959*m.x236 + 0.0178982*m.x237 - 0.00471575*m.x238 + 0.00892359*m.x239
+ 0.0163609*m.x240 + 0.0195565*m.x241 + 0.00870017*m.x242 + 0.00677241*m.x243
+ 0.0185572*m.x244 - 0.0047133*m.x245 + 0.0101507*m.x246 + 0.00747713*m.x247
+ 0.0167627*m.x248 + 0.0123014*m.x249 + 0.0123928*m.x250 + 0.0344311*m.x251
+ 0.00728529*m.x252 + 0.0031934*m.x253 + 0.00209512*m.x254 + 0.0154489*m.x255
+ 0.0147635*m.x256 + 0.00835242*m.x257 + 0.00566315*m.x258 + 0.0179047*m.x259
+ 0.00524362*m.x260 + 0.00744129*m.x261 - 0.018004*m.x262 + 0.00619413*m.x263
- 0.00749905*m.x264 - 0.000442365*m.x265 - 0.000518247*m.x266 - 0.00598213*m.x267
+ 0.0105371*m.x268 - 0.0025092*m.x269 + 0.00865013*m.x270 - 0.00234615*m.x271
+ 0.0289311*m.x272 + 0.0438235*m.x273 + 0.242658*m.x274 + 0.0306035*m.x275 + 0.0117336*m.x276
+ 0.0118774*m.x277 + 0.0838189*m.x278 + 0.0481403*m.x279 + 0.0110032*m.x280 + 0.014917*m.x281
- 0.00591529*m.x282 + 0.0063929*m.x283 + 0.00775199*m.x284 + 0.015887*m.x285
+ 0.00276734*m.x286 + 0.00368135*m.x287 + 0.00957517*m.x288 + 0.00642966*m.x289
- 0.0216798*m.x290 + 0.0227594*m.x291 + 0.00163182*m.x292 + 0.000148116*m.x293
- 0.00314438*m.x294 + 0.00826237*m.x295 + 0.0225842*m.x296 - 0.0145782*m.x297
- 0.00503236*m.x298 + 0.0195997*m.x299 + 0.00361997*m.x300 + 0.000208782*m.x301
+ 0.0145316*m.x302 + 0.0365771*m.x303 == 0)
m.c178 = Constraint(expr= - m.x73 + 0.0167264*m.x204 + 0.0479268*m.x205 + 0.0213196*m.x206 + 0.0149564*m.x207
+ 0.00270935*m.x208 + 0.00240413*m.x209 + 0.0117028*m.x210 - 0.0044266*m.x211
+ 0.00513392*m.x212 + 0.0203179*m.x213 + 0.0517634*m.x214 + 0.00680778*m.x215
+ 0.0324887*m.x216 + 0.0138659*m.x217 + 0.00802954*m.x218 + 0.0138875*m.x219
+ 0.0137739*m.x220 + 0.019995*m.x221 + 0.0718984*m.x222 + 0.0182457*m.x223 + 0.0146925*m.x224
+ 0.00163408*m.x225 + 0.0130101*m.x226 - 0.00744934*m.x227 + 0.0164707*m.x228
- 0.00173148*m.x229 - 0.00609273*m.x230 + 0.0185225*m.x231 - 0.0141201*m.x232
+ 0.0342241*m.x233 + 0.0445692*m.x234 + 0.00715561*m.x235 - 0.0084707*m.x236
+ 0.0495734*m.x237 + 0.0180724*m.x238 + 0.0452262*m.x239 + 0.0173916*m.x240
+ 0.000493166*m.x241 + 0.0205621*m.x242 + 0.017246*m.x243 + 0.0762045*m.x244
- 0.00607984*m.x245 + 0.0607045*m.x246 - 0.012371*m.x247 + 0.11148*m.x248 + 0.0116924*m.x249
+ 0.0197059*m.x250 + 0.0814204*m.x251 + 0.0247762*m.x252 + 0.0170294*m.x253
- 0.00647057*m.x254 + 0.0227933*m.x255 - 0.0169658*m.x256 - 0.0044184*m.x257
+ 0.0328952*m.x258 + 0.0195461*m.x259 + 0.0238296*m.x260 + 0.00536604*m.x261
- 0.0118023*m.x262 + 0.0152866*m.x263 + 0.0181994*m.x264 + 0.0365121*m.x265
- 0.00949741*m.x266 - 0.00477587*m.x267 + 0.0142667*m.x268 + 0.0133094*m.x269
+ 0.00955259*m.x270 + 0.0268143*m.x271 + 0.00013573*m.x272 + 0.0578188*m.x273
+ 0.0306035*m.x274 + 0.389075*m.x275 + 0.0225065*m.x276 + 0.0131023*m.x277 + 0.021475*m.x278
+ 0.078762*m.x279 + 0.00606592*m.x280 + 0.051157*m.x281 + 0.0256278*m.x282 + 0.0370739*m.x283
+ 0.0151235*m.x284 - 0.0209294*m.x285 + 0.04185*m.x286 + 0.025252*m.x287 + 0.0207561*m.x288
+ 0.0442676*m.x289 + 0.0205286*m.x290 + 0.00300826*m.x291 + 0.00755881*m.x292
+ 0.0070906*m.x293 + 0.0162991*m.x294 - 0.0210064*m.x295 + 0.0190915*m.x296 - 0.0125323*m.x297
+ 0.0147594*m.x298 + 0.0449847*m.x299 + 0.0390785*m.x300 - 0.0172229*m.x301 + 0.0289407*m.x302
+ 0.00458626*m.x303 == 0)
m.c179 = Constraint(expr= - m.x74 - 0.00986916*m.x204 - 0.0117451*m.x205 - 0.0306486*m.x206 + 0.0372578*m.x207
- 0.00761522*m.x208 + 0.0160415*m.x209 + 0.00138295*m.x210 + 0.0294097*m.x211
- 0.00866694*m.x212 - 0.017854*m.x213 + 0.000715776*m.x214 + 0.0365571*m.x215
+ 0.0227743*m.x216 + 0.029875*m.x217 + 0.0162258*m.x218 + 0.00149722*m.x219
+ 0.00346188*m.x220 - 0.0150306*m.x221 + 0.00984006*m.x222 + 0.00576651*m.x223
- 0.00160584*m.x224 - 0.0203875*m.x225 + 0.00531061*m.x226 + 0.00473186*m.x227
- 0.00467826*m.x228 - 0.00926362*m.x229 + 0.00484259*m.x230 + 0.00426479*m.x231
+ 0.000576517*m.x232 + 0.00771843*m.x233 + 0.00858179*m.x234 + 0.0136809*m.x235
- 0.016164*m.x236 + 0.00617492*m.x237 + 0.0215306*m.x238 - 0.00767906*m.x239
+ 0.0271333*m.x240 + 0.0113544*m.x241 + 0.006158*m.x242 + 0.0147256*m.x243 - 0.00779475*m.x244
+ 0.00938905*m.x245 - 0.00928056*m.x246 + 0.000659729*m.x247 - 0.0305247*m.x248
+ 0.00495294*m.x249 + 0.00699246*m.x250 - 0.00170809*m.x251 + 0.0153231*m.x252
+ 0.0194417*m.x253 + 0.0011822*m.x254 + 0.00649497*m.x255 + 0.00689011*m.x256
+ 0.0108029*m.x257 - 0.00795682*m.x258 + 0.0202055*m.x259 - 0.00255331*m.x260
- 0.00136449*m.x261 - 0.0147362*m.x262 + 0.0172916*m.x263 + 0.0583548*m.x264
+ 0.0226464*m.x265 - 0.00246233*m.x266 - 0.025348*m.x267 + 0.00283098*m.x268
+ 0.0060945*m.x269 - 0.00981226*m.x270 + 0.0340288*m.x271 + 0.00721954*m.x272
+ 0.0280953*m.x273 + 0.0117336*m.x274 + 0.0225065*m.x275 + 0.255333*m.x276 + 0.0165252*m.x277
+ 0.00800624*m.x278 - 0.00955165*m.x279 + 0.00466426*m.x280 + 0.0454029*m.x281
+ 0.00660178*m.x282 + 0.0186443*m.x283 - 0.0237599*m.x284 + 0.0194091*m.x285
+ 0.00341598*m.x286 + 0.0168686*m.x287 + 0.0161268*m.x288 + 0.0227145*m.x289
+ 0.00389974*m.x290 + 0.0230822*m.x291 - 0.0103966*m.x292 - 0.00167457*m.x293
+ 0.0127897*m.x294 + 0.0629866*m.x295 + 0.00369913*m.x296 + 0.0201848*m.x297
- 0.00505562*m.x298 - 0.0107799*m.x299 + 0.0045*m.x300 + 0.0173545*m.x301 + 0.000465444*m.x302
+ 0.00702905*m.x303 == 0)
m.c180 = Constraint(expr= - m.x75 + 0.000264178*m.x204 + 0.028956*m.x205 + 0.019325*m.x206 + 0.00639167*m.x207
+ 0.00740387*m.x208 - 0.030207*m.x209 + 0.0185095*m.x210 - 0.00500434*m.x211 + 0.066741*m.x212
+ 0.00702231*m.x213 + 0.0272845*m.x214 + 0.0121352*m.x215 + 0.0134993*m.x216 + 0.012011*m.x217
+ 0.0205116*m.x218 + 0.0217898*m.x219 + 0.018383*m.x220 + 0.0129312*m.x221 - 0.00865423*m.x222
+ 0.0355746*m.x223 - 0.00519309*m.x224 - 0.00266029*m.x225 + 0.0106016*m.x226
+ 0.0148345*m.x227 + 0.0091414*m.x228 - 0.0118778*m.x229 + 0.0142463*m.x230 - 0.0182268*m.x231
+ 0.0218241*m.x232 + 0.021456*m.x233 + 0.00833241*m.x234 + 0.000970616*m.x235
+ 0.0222678*m.x236 + 0.0124231*m.x237 + 0.020355*m.x238 + 0.00992303*m.x239 + 0.0101687*m.x240
+ 0.0130662*m.x241 - 0.00856733*m.x242 + 0.0179741*m.x243 + 0.0295755*m.x244
+ 0.00171904*m.x245 + 0.00206923*m.x246 + 0.0140481*m.x247 - 0.00481113*m.x248
+ 0.00276646*m.x249 + 0.00608218*m.x250 + 0.0125969*m.x251 + 0.00286752*m.x252
+ 0.0221671*m.x253 + 0.0120375*m.x254 + 0.0365298*m.x255 + 0.00530597*m.x256
+ 0.00721874*m.x257 + 0.00577634*m.x258 + 0.00312413*m.x259 + 0.0228347*m.x260
+ 0.00692329*m.x261 - 0.00499549*m.x262 - 0.0067214*m.x263 + 0.057555*m.x264
+ 0.0143164*m.x265 + 0.0237049*m.x266 - 0.0195708*m.x267 + 0.0181153*m.x268
- 0.00787035*m.x269 + 0.0203602*m.x270 + 0.0271041*m.x271 - 0.00673825*m.x272
+ 0.0335154*m.x273 + 0.0118774*m.x274 + 0.0131023*m.x275 + 0.0165252*m.x276 + 0.209637*m.x277
+ 0.0164161*m.x278 + 0.00796604*m.x279 + 0.0134275*m.x280 + 0.00599906*m.x281
+ 0.00283067*m.x282 + 0.021476*m.x283 + 0.00126553*m.x284 + 0.0109005*m.x285
- 0.00987739*m.x286 + 0.0246303*m.x287 + 0.0392551*m.x288 + 0.0197251*m.x289
+ 0.00960328*m.x290 - 0.000262221*m.x291 + 0.0117935*m.x292 - 0.00608545*m.x293
+ 0.00565714*m.x294 + 0.014422*m.x295 + 0.00362916*m.x296 + 0.0108815*m.x297
+ 0.00215519*m.x298 + 0.015215*m.x299 + 0.017746*m.x300 + 0.00771442*m.x301
+ 0.00826654*m.x302 - 0.0216509*m.x303 == 0)
m.c181 = Constraint(expr= - m.x76 + 0.000443677*m.x204 + 0.0186632*m.x205 - 0.00667034*m.x206 + 0.0113589*m.x207
+ 0.038373*m.x208 + 0.00296297*m.x209 + 0.0171304*m.x210 + 0.0311579*m.x211 + 0.0166803*m.x212
+ 0.000393591*m.x213 + 0.0154336*m.x214 + 0.0025257*m.x215 + 0.0313448*m.x216
+ 0.0334484*m.x217 + 0.0115061*m.x218 + 0.0236162*m.x219 + 0.0232466*m.x220
- 0.00349278*m.x221 + 0.0190688*m.x222 + 0.023712*m.x223 - 0.0141018*m.x224 + 0.0137259*m.x225
+ 0.0218053*m.x226 + 0.0291503*m.x227 + 0.019493*m.x228 - 0.0065822*m.x229 + 0.00113796*m.x230
+ 0.0156633*m.x231 + 0.0288367*m.x232 + 0.0151258*m.x233 - 0.00293272*m.x234
+ 0.0221044*m.x235 - 0.0154847*m.x236 + 0.0252473*m.x237 + 0.0180883*m.x238 - 0.0114508*m.x239
+ 0.0167448*m.x240 + 0.0237854*m.x241 + 0.0207092*m.x242 + 0.0247003*m.x243
+ 0.00943287*m.x244 + 0.0195252*m.x245 - 0.0163855*m.x246 + 0.0187041*m.x247
+ 0.0231293*m.x248 - 0.00266202*m.x249 + 0.0205119*m.x250 + 0.0302619*m.x251
+ 0.0201839*m.x252 + 0.00907431*m.x253 - 0.00082898*m.x254 + 0.00147956*m.x255
+ 0.000210327*m.x256 + 0.0240962*m.x257 + 0.00671703*m.x258 - 0.0085337*m.x259
+ 0.00908482*m.x260 + 0.0109078*m.x261 - 0.0143351*m.x262 + 0.00669297*m.x263
+ 0.0268228*m.x264 + 0.00841295*m.x265 - 0.00277129*m.x266 - 0.00168274*m.x267
+ 0.00272646*m.x268 + 0.00700317*m.x269 + 0.0117019*m.x270 + 0.026112*m.x271
+ 0.0133065*m.x272 + 0.0472914*m.x273 + 0.0838189*m.x274 + 0.021475*m.x275 + 0.00800624*m.x276
+ 0.0164161*m.x277 + 0.404015*m.x278 + 0.105549*m.x279 - 0.00776237*m.x280 + 0.027323*m.x281
+ 0.0127166*m.x282 + 0.0106842*m.x283 + 0.067325*m.x284 - 0.00516528*m.x285 + 0.0247823*m.x286
+ 0.016336*m.x287 + 0.0334571*m.x288 + 0.00051236*m.x289 + 0.0131673*m.x290 + 0.0237505*m.x291
+ 0.0259753*m.x292 + 0.00232003*m.x293 + 0.00642914*m.x294 - 0.000406401*m.x295
+ 0.0185527*m.x296 + 0.0077666*m.x297 + 0.012311*m.x298 + 0.0214616*m.x299 + 0.0298427*m.x300
- 0.00757473*m.x301 + 0.00326998*m.x302 + 0.0195985*m.x303 == 0)
m.c182 = Constraint(expr= - m.x77 + 0.0156931*m.x204 + 0.0181645*m.x205 + 0.000467446*m.x206 + 0.0136237*m.x207
+ 0.0330416*m.x208 + 0.0130072*m.x209 + 0.0122791*m.x210 + 0.0494097*m.x211 + 0.0021271*m.x212
+ 0.0103674*m.x213 - 0.00822959*m.x214 + 0.0148074*m.x215 + 0.043333*m.x216 + 0.0141205*m.x217
+ 0.0101866*m.x218 + 0.00886369*m.x219 - 0.0111152*m.x220 + 0.0610504*m.x221
+ 0.0249469*m.x222 + 0.000684461*m.x223 + 0.0151075*m.x224 + 0.0378261*m.x225
+ 0.0181907*m.x226 + 0.0126589*m.x227 - 0.00130846*m.x228 + 0.00460217*m.x229
+ 0.0109937*m.x230 - 0.0108916*m.x231 + 0.00589724*m.x232 + 0.0375829*m.x233
+ 0.00601459*m.x234 + 0.0127205*m.x235 + 0.00339709*m.x236 + 0.058582*m.x237
+ 0.0462503*m.x238 + 0.0197029*m.x239 + 0.0145376*m.x240 + 0.0180646*m.x241 + 0.0123219*m.x242
+ 0.0450965*m.x243 + 0.0286273*m.x244 + 0.0383478*m.x245 + 0.0271648*m.x246 + 0.0306678*m.x247
+ 0.0252067*m.x248 + 0.0232357*m.x249 + 0.0201426*m.x250 + 0.0349979*m.x251
+ 0.00924621*m.x252 + 0.0259533*m.x253 + 0.00474529*m.x254 - 0.0171972*m.x255
- 0.00222996*m.x256 + 0.0333277*m.x257 + 0.0141594*m.x258 + 0.00691393*m.x259
- 0.000852062*m.x260 - 0.00236473*m.x261 + 0.0135402*m.x262 + 0.013914*m.x263
- 0.00819768*m.x264 + 0.00921905*m.x265 - 0.0145486*m.x266 - 0.0318426*m.x267
+ 0.00912054*m.x268 + 0.010213*m.x269 - 0.00029594*m.x270 + 0.00239456*m.x271
+ 0.0477885*m.x272 + 0.0379*m.x273 + 0.0481403*m.x274 + 0.078762*m.x275 - 0.00955165*m.x276
+ 0.00796604*m.x277 + 0.105549*m.x278 + 0.645704*m.x279 + 0.0154494*m.x280 + 0.0227354*m.x281
- 0.0112145*m.x282 + 0.0439815*m.x283 + 0.038462*m.x284 + 0.00338593*m.x285
+ 0.00658251*m.x286 + 0.0538772*m.x287 + 0.00948208*m.x288 + 0.0231576*m.x289
+ 0.0128597*m.x290 + 0.00999317*m.x291 + 0.0274468*m.x292 + 0.00337803*m.x293
+ 0.0146469*m.x294 + 0.00469697*m.x295 + 0.02019*m.x296 - 0.012203*m.x297 + 0.00574997*m.x298
+ 0.0450781*m.x299 + 0.103864*m.x300 - 0.0301521*m.x301 + 0.0209427*m.x302 + 0.016127*m.x303
== 0)
m.c183 = Constraint(expr= - m.x78 - 0.00276268*m.x204 + 0.00696511*m.x205 + 0.0201785*m.x206 + 0.00548526*m.x207
+ 0.00915683*m.x208 + 0.00450281*m.x209 + 0.00233108*m.x210 + 0.00288612*m.x211
+ 0.00823225*m.x212 + 0.00633375*m.x213 + 0.000626594*m.x214 + 0.00353214*m.x215
- 0.00386439*m.x216 + 0.00456199*m.x217 + 0.0261645*m.x218 + 0.0104275*m.x219
- 0.000844745*m.x220 + 0.00292058*m.x221 + 0.00809967*m.x222 - 0.00203509*m.x223
- 0.00436786*m.x224 + 0.0152157*m.x225 + 0.00963458*m.x226 + 0.00774713*m.x227
+ 0.00402512*m.x228 + 0.0200371*m.x229 + 0.0229961*m.x230 + 0.0130582*m.x231
+ 0.00723834*m.x232 + 0.0243902*m.x233 + 0.00788825*m.x234 + 0.0153277*m.x235
+ 0.0202853*m.x236 + 0.00629356*m.x237 + 0.0139857*m.x238 + 0.00438907*m.x239
+ 0.0123315*m.x240 + 0.00659785*m.x241 + 0.00161026*m.x242 + 0.0172805*m.x243
+ 0.00989437*m.x244 + 0.0224169*m.x245 - 0.00245982*m.x246 + 0.00641255*m.x247
+ 0.00522157*m.x248 + 0.00346212*m.x249 + 0.00467559*m.x250 + 0.0190191*m.x251
+ 0.0108718*m.x252 + 0.00674077*m.x253 + 0.00506484*m.x254 + 0.0090494*m.x255
+ 0.00353714*m.x256 - 0.00435648*m.x257 + 0.0189637*m.x258 + 0.019103*m.x259
+ 0.00890703*m.x260 + 0.00505126*m.x261 + 0.000304222*m.x262 + 0.0234397*m.x263
- 0.00195137*m.x264 + 0.00349776*m.x265 - 0.0063327*m.x266 - 0.00658838*m.x267
+ 0.0236631*m.x268 + 0.0358489*m.x269 + 0.00560833*m.x270 + 0.00576057*m.x271
+ 0.0279617*m.x272 + 0.0060603*m.x273 + 0.0110032*m.x274 + 0.00606592*m.x275
+ 0.00466426*m.x276 + 0.0134275*m.x277 - 0.00776237*m.x278 + 0.0154494*m.x279
+ 0.121704*m.x280 + 0.0135097*m.x281 + 0.0148263*m.x282 + 0.0124017*m.x283 + 0.0386958*m.x284
+ 0.0135365*m.x285 - 0.00737633*m.x286 + 0.0145869*m.x287 + 0.0136899*m.x288
+ 0.00757632*m.x289 - 0.00174931*m.x290 + 0.0242284*m.x291 + 0.0223464*m.x292
+ 0.00218928*m.x293 - 0.00234487*m.x294 + 0.0106011*m.x295 + 0.00596788*m.x296
+ 0.0140801*m.x297 + 0.0111286*m.x298 + 0.0108432*m.x299 + 0.014432*m.x300 + 0.0196268*m.x301
+ 0.0388318*m.x302 + 0.0139537*m.x303 == 0)
m.c184 = Constraint(expr= - m.x79 + 0.0162342*m.x204 - 0.00758658*m.x205 - 0.000464311*m.x206 + 0.00938667*m.x207
+ 0.0338859*m.x208 + 0.0121371*m.x209 + 0.0306379*m.x210 + 0.0105617*m.x211
+ 0.00857754*m.x212 + 0.0194224*m.x213 + 0.000631494*m.x214 + 0.0168133*m.x215
+ 0.108963*m.x216 + 0.041893*m.x217 + 0.0332655*m.x218 + 0.0249922*m.x219 + 0.0332627*m.x220
+ 0.0234664*m.x221 - 0.00269958*m.x222 - 0.0114577*m.x223 + 0.00467861*m.x224
+ 0.0169622*m.x225 + 0.00597376*m.x226 - 0.00678133*m.x227 + 0.0148477*m.x228
+ 0.0155593*m.x229 + 0.0124417*m.x230 + 0.00465652*m.x231 - 0.0101934*m.x232
+ 0.0306235*m.x233 + 0.00317889*m.x234 + 0.0189992*m.x235 - 0.0276747*m.x236 - 0.001499*m.x237
+ 0.00783656*m.x238 + 0.0231162*m.x239 + 0.0119314*m.x240 + 0.019254*m.x241 + 0.0140309*m.x242
+ 0.0209097*m.x243 + 0.0238402*m.x244 + 0.0385198*m.x245 + 0.01456*m.x246 + 0.0134395*m.x247
+ 0.0559574*m.x248 + 0.0255284*m.x249 + 0.00848245*m.x250 + 0.0154082*m.x251
+ 0.0181957*m.x252 + 0.0203818*m.x253 + 0.0257774*m.x254 + 0.00449672*m.x255
+ 0.0260232*m.x256 + 0.0866383*m.x257 - 0.0099332*m.x258 + 0.0121945*m.x259 + 0.0294183*m.x260
+ 0.0181113*m.x261 - 0.0196864*m.x262 + 0.0236703*m.x263 + 0.0198979*m.x264 + 0.0226748*m.x265
+ 0.00429669*m.x266 - 0.0168533*m.x267 + 0.012122*m.x268 + 0.0181724*m.x269
+ 0.00249681*m.x270 + 0.0326962*m.x271 - 0.00676451*m.x272 + 0.01743*m.x273 + 0.014917*m.x274
+ 0.051157*m.x275 + 0.0454029*m.x276 + 0.00599906*m.x277 + 0.027323*m.x278 + 0.0227354*m.x279
+ 0.0135097*m.x280 + 0.232936*m.x281 - 0.0146937*m.x282 - 0.00711861*m.x283
+ 0.00900977*m.x284 + 0.0110451*m.x285 + 0.0316906*m.x286 + 0.0294815*m.x287
+ 0.0109427*m.x288 + 0.00947868*m.x289 - 0.00284713*m.x290 + 0.0481938*m.x291
- 0.00283589*m.x292 + 0.016211*m.x293 + 0.0174578*m.x294 + 0.0438875*m.x295 + 0.0271732*m.x296
- 0.00264823*m.x297 + 0.0161145*m.x298 + 0.00509121*m.x299 + 0.0367902*m.x300
- 0.0132156*m.x301 + 0.0177839*m.x302 + 0.0109642*m.x303 == 0)
m.c185 = Constraint(expr= - m.x80 - 0.00713742*m.x204 - 0.00157434*m.x205 - 0.0236607*m.x206 - 0.0040516*m.x207
+ 0.0110433*m.x208 - 0.0231401*m.x209 + 0.0152496*m.x210 + 0.00135164*m.x211
+ 0.0313512*m.x212 - 0.00963904*m.x213 + 0.00874438*m.x214 + 0.0119195*m.x215
- 0.00524662*m.x216 - 0.0231716*m.x217 + 0.00110939*m.x218 + 0.00802207*m.x219
+ 0.0282131*m.x220 - 0.0113617*m.x221 - 0.0108567*m.x222 - 0.0115916*m.x223 + 0.0232455*m.x224
- 0.00218688*m.x225 + 0.00648587*m.x226 - 0.000483346*m.x227 + 0.00831527*m.x228
- 0.0144053*m.x229 + 0.0367225*m.x230 - 0.000979902*m.x231 + 0.0299367*m.x232
+ 0.0131912*m.x233 - 0.00540247*m.x234 + 0.0023179*m.x235 + 0.00131595*m.x236
+ 0.0143475*m.x237 - 0.010913*m.x238 - 0.000788038*m.x239 + 0.0158911*m.x240
+ 0.0146391*m.x241 + 0.0311598*m.x242 + 0.011441*m.x243 + 0.00383314*m.x244 + 0.0274691*m.x245
+ 0.00939606*m.x246 - 0.00179731*m.x247 + 0.0289862*m.x248 + 0.00412958*m.x249
+ 0.00560285*m.x250 - 0.0261893*m.x251 + 0.0030579*m.x252 + 0.0079052*m.x253
- 0.00377692*m.x254 + 0.000262274*m.x255 - 0.0188128*m.x256 + 0.00354499*m.x257
+ 0.0100466*m.x258 - 0.01046*m.x259 + 0.0037155*m.x260 - 0.0184427*m.x261 + 0.0158055*m.x262
+ 0.0307119*m.x263 + 0.216012*m.x264 - 0.00159181*m.x265 + 0.0119178*m.x266 - 0.0154167*m.x267
+ 0.00657829*m.x268 + 0.00656133*m.x269 + 0.0204625*m.x270 + 0.0163689*m.x271
+ 0.0244657*m.x272 + 0.00347436*m.x273 - 0.00591529*m.x274 + 0.0256278*m.x275
+ 0.00660178*m.x276 + 0.00283067*m.x277 + 0.0127166*m.x278 - 0.0112145*m.x279
+ 0.0148263*m.x280 - 0.0146937*m.x281 + 0.76645*m.x282 + 0.0192994*m.x283 + 0.0105875*m.x284
+ 0.0314009*m.x285 + 0.00634296*m.x286 - 0.00196191*m.x287 + 0.0014521*m.x288
+ 0.0144924*m.x289 - 0.00756629*m.x290 - 0.0110851*m.x291 + 0.0361459*m.x292
- 0.00085728*m.x293 + 0.0474245*m.x294 - 0.0216252*m.x295 - 0.0305481*m.x296
+ 0.00800911*m.x297 - 0.00833087*m.x298 - 0.0224481*m.x299 + 0.026356*m.x300 + 0.020753*m.x301
+ 0.0316754*m.x302 + 0.00176788*m.x303 == 0)
m.c186 = Constraint(expr= - m.x81 + 0.0535351*m.x204 + 0.0257631*m.x205 + 0.0310239*m.x206 + 0.0204574*m.x207
+ 0.00100659*m.x208 - 0.0106726*m.x209 + 0.00760112*m.x210 + 0.00925665*m.x211
+ 0.00130029*m.x212 + 0.0241569*m.x213 + 0.00365132*m.x214 - 0.012089*m.x215
- 0.00652429*m.x216 + 0.0374086*m.x217 + 0.0260692*m.x218 + 0.00986454*m.x219
+ 0.0233102*m.x220 + 0.0361401*m.x221 - 0.0246729*m.x222 - 0.00776726*m.x223
- 0.00329331*m.x224 + 0.0252382*m.x225 + 0.0276238*m.x226 + 0.00185776*m.x227
- 0.00269199*m.x228 - 0.0110697*m.x229 - 0.0100286*m.x230 + 0.0258383*m.x231
- 0.00142157*m.x232 - 0.00933997*m.x233 + 0.016911*m.x234 + 0.0192297*m.x235
- 0.0112676*m.x236 - 0.00386864*m.x237 - 0.0111746*m.x238 + 0.0115195*m.x239
+ 0.0101661*m.x240 + 0.0146836*m.x241 + 0.0145619*m.x242 + 0.0219237*m.x243
- 0.00120741*m.x244 - 0.0267822*m.x245 + 0.0298789*m.x246 - 0.00385651*m.x247
+ 0.00382741*m.x248 + 0.0240524*m.x249 - 0.000758449*m.x250 + 0.0528557*m.x251
+ 0.0149032*m.x252 + 0.02471*m.x253 + 0.00714516*m.x254 - 0.00945913*m.x255
- 0.00162038*m.x256 + 0.00280407*m.x257 + 0.00647759*m.x258 + 7.7416E-5*m.x259
+ 0.0369425*m.x260 - 0.00067668*m.x261 - 0.0123673*m.x262 + 0.0135874*m.x263
+ 0.00795018*m.x264 + 0.00683403*m.x265 - 0.0166029*m.x266 - 0.018515*m.x267
- 0.0121548*m.x268 + 0.00426715*m.x269 - 0.0104074*m.x270 - 0.00776661*m.x271
+ 0.011568*m.x272 + 0.0134516*m.x273 + 0.0063929*m.x274 + 0.0370739*m.x275 + 0.0186443*m.x276
+ 0.021476*m.x277 + 0.0106842*m.x278 + 0.0439815*m.x279 + 0.0124017*m.x280 - 0.00711861*m.x281
+ 0.0192994*m.x282 + 0.486602*m.x283 - 0.00624267*m.x284 + 0.00303554*m.x285
- 0.0133479*m.x286 + 0.0125386*m.x287 + 0.0115422*m.x288 + 0.0239015*m.x289 + 0.0451897*m.x290
- 0.0310249*m.x291 + 0.00587297*m.x292 - 0.0136089*m.x293 - 0.000516624*m.x294
+ 0.0009259*m.x295 + 0.0175048*m.x296 + 0.0373561*m.x297 - 0.0112765*m.x298 + 0.0051311*m.x299
+ 0.014489*m.x300 - 0.00457749*m.x301 + 0.00838465*m.x302 - 0.0161154*m.x303 == 0)
m.c187 = Constraint(expr= - m.x82 + 0.00652548*m.x204 + 0.0226078*m.x205 + 0.042261*m.x206 + 0.00726938*m.x207
+ 0.038867*m.x208 + 0.0230093*m.x209 + 0.0227379*m.x210 + 0.00141295*m.x211 - 0.0150965*m.x212
+ 0.0143008*m.x213 - 0.0056711*m.x214 - 0.00915576*m.x215 - 0.00988714*m.x216
+ 0.0313221*m.x217 + 0.0012738*m.x218 + 0.00924082*m.x219 - 0.00179937*m.x220
- 0.0108246*m.x221 + 0.030261*m.x222 - 0.010001*m.x223 - 0.000366056*m.x224 + 0.0510044*m.x225
+ 0.0170493*m.x226 + 0.0211536*m.x227 - 0.00146575*m.x228 + 0.0217421*m.x229
+ 0.0358544*m.x230 + 0.045075*m.x231 + 0.0157699*m.x232 + 0.0198755*m.x233 + 0.0317363*m.x234
+ 0.0186293*m.x235 + 0.0194651*m.x236 + 0.00970643*m.x237 - 0.0212839*m.x238
+ 0.0165997*m.x239 + 0.0257734*m.x240 + 0.0134395*m.x241 + 0.0141748*m.x242
+ 0.00710912*m.x243 - 0.000663857*m.x244 + 0.0309656*m.x245 - 0.00119943*m.x246
+ 0.0131706*m.x247 - 0.00408493*m.x248 + 0.0102107*m.x249 + 0.0116371*m.x250
+ 0.0243695*m.x251 + 0.00765193*m.x252 + 0.0263439*m.x253 + 0.0077099*m.x254
+ 0.0453251*m.x255 - 0.00901467*m.x256 - 0.0171587*m.x257 + 0.0250933*m.x258
+ 0.0195852*m.x259 + 0.0014252*m.x260 - 0.000180812*m.x261 + 0.0093129*m.x262
+ 0.0408449*m.x263 + 0.00230105*m.x264 + 0.000980679*m.x265 - 0.00474646*m.x266
+ 0.00103058*m.x267 + 0.0355309*m.x268 + 0.0279955*m.x269 - 0.00117293*m.x270
+ 0.00451059*m.x271 - 0.00233863*m.x272 - 0.0215081*m.x273 + 0.00775199*m.x274
+ 0.0151235*m.x275 - 0.0237599*m.x276 + 0.00126553*m.x277 + 0.067325*m.x278 + 0.038462*m.x279
+ 0.0386958*m.x280 + 0.00900977*m.x281 + 0.0105875*m.x282 - 0.00624267*m.x283
+ 0.206832*m.x284 + 0.0147473*m.x285 + 0.00363982*m.x286 + 0.0393242*m.x287 + 0.0257997*m.x288
- 0.00620466*m.x289 + 0.00412578*m.x290 + 0.0127761*m.x291 + 0.0351101*m.x292
- 0.00463556*m.x293 + 0.00349789*m.x294 - 0.00754138*m.x295 - 0.00336606*m.x296
- 0.0216041*m.x297 + 0.0121631*m.x298 + 0.0125615*m.x299 + 0.012455*m.x300 + 0.018402*m.x301
+ 0.0384063*m.x302 + 0.0175444*m.x303 == 0)
m.c188 = Constraint(expr= - m.x83 - 0.0124237*m.x204 + 0.0117173*m.x205 + 0.0185462*m.x206 + 0.0138296*m.x207
+ 0.00624966*m.x208 + 0.0220687*m.x209 + 0.0315858*m.x210 - 0.00247117*m.x211
+ 0.0772805*m.x212 + 0.0127084*m.x213 + 0.0203348*m.x214 + 0.0251125*m.x215 + 0.04316*m.x216
- 0.00981712*m.x217 + 0.0253402*m.x218 + 0.00416101*m.x219 + 0.0144628*m.x220
+ 0.0156378*m.x221 - 0.0172947*m.x222 + 0.000111057*m.x223 + 0.0126412*m.x224
+ 0.0140353*m.x225 + 0.00242329*m.x226 - 0.00255587*m.x227 + 0.00519983*m.x228
+ 0.0203773*m.x229 + 0.00154206*m.x230 + 0.0236369*m.x231 - 0.00224841*m.x232
+ 0.0218691*m.x233 + 0.00773321*m.x234 + 0.0497975*m.x235 - 0.000432208*m.x236
+ 0.0171804*m.x237 + 0.0109154*m.x238 + 0.00247635*m.x239 + 0.0177688*m.x240
+ 0.0310356*m.x241 + 0.00619315*m.x242 + 8.9584E-5*m.x243 + 0.00556998*m.x244
+ 0.0175453*m.x245 - 0.0044664*m.x246 + 0.0115633*m.x247 + 0.028825*m.x248 + 0.0153982*m.x249
+ 0.0124272*m.x250 - 0.000197615*m.x251 + 0.00635221*m.x252 + 0.0177662*m.x253
+ 0.0105595*m.x254 - 0.000808541*m.x255 + 0.031558*m.x256 + 0.0167951*m.x257
- 0.000881292*m.x258 + 0.0203511*m.x259 + 0.00588108*m.x260 + 0.020629*m.x261
+ 0.0180884*m.x262 + 0.00693809*m.x263 + 0.0194778*m.x264 + 0.00186047*m.x265
- 0.00414121*m.x266 - 0.0178181*m.x267 + 0.00535639*m.x268 + 0.0107345*m.x269
+ 0.0119469*m.x270 + 0.00792609*m.x271 + 0.0116962*m.x272 - 0.00588027*m.x273
+ 0.015887*m.x274 - 0.0209294*m.x275 + 0.0194091*m.x276 + 0.0109005*m.x277 - 0.00516528*m.x278
+ 0.00338593*m.x279 + 0.0135365*m.x280 + 0.0110451*m.x281 + 0.0314009*m.x282
+ 0.00303554*m.x283 + 0.0147473*m.x284 + 0.140821*m.x285 + 0.015425*m.x286 + 0.0110252*m.x287
+ 0.0172034*m.x288 + 0.00430198*m.x289 - 0.00771995*m.x290 + 0.0307627*m.x291
+ 0.0181157*m.x292 - 0.00258019*m.x293 - 0.00682747*m.x294 + 0.0206012*m.x295
+ 0.00945896*m.x296 + 0.0244376*m.x297 + 0.0327088*m.x298 + 0.0159115*m.x299
+ 0.0166712*m.x300 + 0.0072935*m.x301 + 0.00573711*m.x302 + 0.0260562*m.x303 == 0)
m.c189 = Constraint(expr= - m.x84 + 0.0284349*m.x204 + 0.022134*m.x205 - 0.0122475*m.x206 + 0.00730263*m.x207
+ 0.00420064*m.x208 + 0.0720504*m.x209 + 0.0060507*m.x210 - 0.0255331*m.x211
+ 0.0392036*m.x212 + 0.0167294*m.x213 + 0.0341872*m.x214 + 0.00612187*m.x215
+ 0.0469731*m.x216 + 0.0545587*m.x217 + 0.0115293*m.x218 + 0.0228286*m.x219 + 0.0198321*m.x220
+ 0.00137389*m.x221 - 0.013192*m.x222 + 0.02061*m.x223 + 0.00320192*m.x224 + 0.00976413*m.x225
- 0.0146684*m.x226 - 0.00832251*m.x227 + 0.00563734*m.x228 + 0.00705351*m.x229
- 0.00258881*m.x230 + 0.0486461*m.x231 - 0.000196592*m.x232 + 0.01283*m.x233 + 0.016704*m.x234
+ 0.00488326*m.x235 + 0.00548514*m.x236 - 0.0153224*m.x237 - 0.00737614*m.x238
+ 0.00203383*m.x239 + 0.0138653*m.x240 + 0.00956021*m.x241 - 0.00370778*m.x242
+ 0.00608136*m.x243 - 0.00367056*m.x244 + 0.0338365*m.x245 + 0.000712121*m.x246
- 0.00481073*m.x247 + 0.043114*m.x248 - 0.00470666*m.x249 + 0.0162343*m.x250
+ 0.0624011*m.x251 + 0.0123886*m.x252 + 0.0459437*m.x253 + 0.0161573*m.x254 + 0.0226841*m.x255
+ 0.0131334*m.x256 + 0.0217323*m.x257 + 0.0263854*m.x258 + 0.00683799*m.x259
+ 0.0145498*m.x260 - 0.00579727*m.x261 - 0.0022627*m.x262 + 0.0213571*m.x263
+ 0.00852926*m.x264 + 0.0167378*m.x265 - 0.011543*m.x266 - 0.0183739*m.x267 - 0.0102352*m.x268
- 0.00277805*m.x269 + 0.0145851*m.x270 + 0.00416542*m.x271 + 0.013257*m.x272 + 0.023436*m.x273
+ 0.00276734*m.x274 + 0.04185*m.x275 + 0.00341598*m.x276 - 0.00987739*m.x277
+ 0.0247823*m.x278 + 0.00658251*m.x279 - 0.00737633*m.x280 + 0.0316906*m.x281
+ 0.00634296*m.x282 - 0.0133479*m.x283 + 0.00363982*m.x284 + 0.015425*m.x285 + 0.325214*m.x286
+ 0.00356847*m.x287 + 0.00352398*m.x288 + 0.00433638*m.x289 - 0.000835345*m.x290
+ 0.0177836*m.x291 + 0.00188467*m.x292 + 0.0090193*m.x293 - 0.000926932*m.x294
+ 0.0189143*m.x295 + 0.0239269*m.x296 + 0.0214766*m.x297 + 0.0299348*m.x298 + 0.0657669*m.x299
+ 0.00914343*m.x300 + 0.00979692*m.x301 + 0.00280778*m.x302 + 0.00369429*m.x303 == 0)
m.c190 = Constraint(expr= - m.x85 - 0.0130366*m.x204 + 0.00875918*m.x205 + 0.0280865*m.x206 + 0.00429398*m.x207
+ 0.0301859*m.x208 + 0.0235846*m.x209 + 0.0179103*m.x210 + 0.0200897*m.x211 + 0.0404836*m.x212
+ 0.0346049*m.x213 + 0.0102937*m.x214 + 0.0024002*m.x215 + 0.00266624*m.x216
+ 0.0268496*m.x217 + 0.0157477*m.x218 + 0.0243826*m.x219 + 0.0080643*m.x220 - 0.0271238*m.x221
+ 0.0111854*m.x222 + 0.0103997*m.x223 - 0.0135153*m.x224 + 0.0121898*m.x225 + 0.0212922*m.x226
+ 0.00243227*m.x227 - 0.0022015*m.x228 + 0.0171599*m.x229 + 0.0316383*m.x230
+ 0.0157696*m.x231 - 0.00344939*m.x232 + 0.0304352*m.x233 - 0.0141682*m.x234
+ 0.0420958*m.x235 + 0.0171493*m.x236 + 0.00145169*m.x237 + 0.00226631*m.x238
+ 0.0149245*m.x239 - 0.00986807*m.x240 + 0.00391649*m.x241 + 0.00148966*m.x242
+ 0.0200781*m.x243 + 0.0290197*m.x244 + 0.0150021*m.x245 + 0.00470761*m.x246
- 0.000228971*m.x247 + 0.0366449*m.x248 + 0.0022653*m.x249 - 0.00172543*m.x250
+ 0.0338724*m.x251 + 0.000661634*m.x252 + 0.031036*m.x253 + 0.00452026*m.x254
+ 0.0177547*m.x255 + 0.010006*m.x256 + 0.0074812*m.x257 + 0.0134424*m.x258 + 0.0150426*m.x259
+ 0.0146631*m.x260 + 0.00633518*m.x261 - 0.0178424*m.x262 + 0.0130973*m.x263
+ 0.0180986*m.x264 - 0.0130487*m.x265 + 0.00920493*m.x266 - 0.0131486*m.x267
+ 0.0343148*m.x268 + 0.0184565*m.x269 + 0.010394*m.x270 - 0.0019629*m.x271
- 0.000584023*m.x272 + 0.0518973*m.x273 + 0.00368135*m.x274 + 0.025252*m.x275
+ 0.0168686*m.x276 + 0.0246303*m.x277 + 0.016336*m.x278 + 0.0538772*m.x279 + 0.0145869*m.x280
+ 0.0294815*m.x281 - 0.00196191*m.x282 + 0.0125386*m.x283 + 0.0393242*m.x284
+ 0.0110252*m.x285 + 0.00356847*m.x286 + 0.253501*m.x287 + 0.0278664*m.x288 + 0.0165516*m.x289
+ 0.0153948*m.x290 + 0.0222877*m.x291 + 0.0232654*m.x292 + 0.00990806*m.x293
+ 0.00288787*m.x294 + 0.00781374*m.x295 - 0.000230336*m.x296 + 0.0165132*m.x297
+ 0.0382825*m.x298 - 0.016509*m.x299 + 0.0189584*m.x300 - 0.00704493*m.x301 + 0.0230199*m.x302
+ 0.0134259*m.x303 == 0)
m.c191 = Constraint(expr= - m.x86 + 0.00243309*m.x204 + 0.0213683*m.x205 + 0.0121116*m.x206 + 0.0216644*m.x207
+ 0.0339489*m.x208 + 0.0134857*m.x209 + 0.00721099*m.x210 + 0.022993*m.x211 + 0.0233051*m.x212
+ 0.0161423*m.x213 + 0.0151637*m.x214 + 0.00206781*m.x215 + 0.00890446*m.x216
- 0.00176973*m.x217 + 0.0136669*m.x218 + 0.0181062*m.x219 + 0.0113165*m.x220
+ 0.00450122*m.x221 + 0.0114597*m.x222 + 0.000675373*m.x223 + 0.00126179*m.x224
+ 0.00257907*m.x225 + 0.0327354*m.x226 + 0.000359588*m.x227 + 0.0164738*m.x228
- 0.001325*m.x229 + 0.0170355*m.x230 + 0.0196175*m.x231 + 0.00552353*m.x232 + 0.0336786*m.x233
+ 0.0109291*m.x234 + 0.0926409*m.x235 + 0.0191037*m.x236 + 0.0165018*m.x237 + 0.0273084*m.x238
+ 0.00360648*m.x239 + 0.0188003*m.x240 + 0.037188*m.x241 - 0.00287831*m.x242
+ 0.0170146*m.x243 + 0.0308391*m.x244 + 0.0486356*m.x245 + 0.0134195*m.x246 + 0.0126522*m.x247
- 0.00847171*m.x248 + 0.0126439*m.x249 + 0.0211089*m.x250 - 0.0090107*m.x251
+ 0.0359152*m.x252 + 0.0396615*m.x253 + 0.00366557*m.x254 + 0.0128398*m.x255
- 0.00713827*m.x256 - 0.0200391*m.x257 + 0.00802506*m.x258 + 0.0201186*m.x259
+ 0.0173147*m.x260 - 0.0124431*m.x261 + 0.0201311*m.x262 + 0.0121195*m.x263 + 0.0217749*m.x264
+ 0.00624026*m.x265 + 0.0194176*m.x266 + 0.000857968*m.x267 + 0.0161535*m.x268
+ 0.00461119*m.x269 + 0.00513963*m.x270 + 0.0236126*m.x271 - 0.00369328*m.x272
+ 0.00558955*m.x273 + 0.00957517*m.x274 + 0.0207561*m.x275 + 0.0161268*m.x276
+ 0.0392551*m.x277 + 0.0334571*m.x278 + 0.00948208*m.x279 + 0.0136899*m.x280
+ 0.0109427*m.x281 + 0.0014521*m.x282 + 0.0115422*m.x283 + 0.0257997*m.x284 + 0.0172034*m.x285
+ 0.00352398*m.x286 + 0.0278664*m.x287 + 0.168708*m.x288 + 0.016409*m.x289 + 0.0246084*m.x290
+ 0.0175327*m.x291 + 0.0132707*m.x292 + 0.00899692*m.x293 + 0.00791625*m.x294
+ 0.0177061*m.x295 + 0.00207808*m.x296 + 0.0251146*m.x297 + 0.0184837*m.x298
+ 0.00390491*m.x299 + 0.0146561*m.x300 - 0.0140423*m.x301 + 0.0118626*m.x302
- 0.00284169*m.x303 == 0)
m.c192 = Constraint(expr= - m.x87 + 0.00484607*m.x204 + 0.0223469*m.x205 + 0.00361683*m.x206 + 0.0233018*m.x207
+ 0.00230194*m.x208 + 0.00278062*m.x209 + 0.00164949*m.x210 - 0.000549013*m.x211
+ 0.00145357*m.x212 + 0.00486934*m.x213 + 0.0152717*m.x214 - 0.000360419*m.x215
+ 0.0106296*m.x216 + 0.0262312*m.x217 + 0.0102152*m.x218 + 0.0141347*m.x219 + 0.0316648*m.x220
+ 0.0194887*m.x221 + 0.0126843*m.x222 + 0.0130083*m.x223 + 0.00970953*m.x224
+ 0.00858432*m.x225 + 0.0202473*m.x226 + 0.0204891*m.x227 + 0.0095043*m.x228
+ 0.00618414*m.x229 + 0.000376344*m.x230 + 0.00775608*m.x231 - 0.00394771*m.x232
+ 0.00419472*m.x233 + 0.00776229*m.x234 - 0.000832904*m.x235 + 0.00214285*m.x236
+ 0.0080802*m.x237 + 0.0165011*m.x238 - 0.00766884*m.x239 + 0.0172113*m.x240
+ 0.0264564*m.x241 + 0.00458259*m.x242 + 0.0215022*m.x243 + 0.0431137*m.x244
+ 0.0180063*m.x245 + 0.0369595*m.x246 + 0.0105163*m.x247 + 0.0235286*m.x248
+ 0.00223458*m.x249 + 0.00648963*m.x250 + 0.00951148*m.x251 + 0.0121599*m.x252
+ 0.0169315*m.x253 + 0.0131458*m.x254 + 0.0231386*m.x255 + 0.00638031*m.x256
+ 0.00634167*m.x257 + 0.00331125*m.x258 + 0.0161444*m.x259 + 0.0134929*m.x260
+ 0.0253269*m.x261 + 0.0127648*m.x262 + 0.0119547*m.x263 + 0.00366775*m.x264
+ 0.0174197*m.x265 + 0.00717868*m.x266 + 0.0083299*m.x267 + 0.0145892*m.x268
+ 0.0123007*m.x269 + 0.0107918*m.x270 + 0.0137167*m.x271 + 0.0104073*m.x272 + 0.0276924*m.x273
+ 0.00642966*m.x274 + 0.0442676*m.x275 + 0.0227145*m.x276 + 0.0197251*m.x277
+ 0.00051236*m.x278 + 0.0231576*m.x279 + 0.00757632*m.x280 + 0.00947868*m.x281
+ 0.0144924*m.x282 + 0.0239015*m.x283 - 0.00620466*m.x284 + 0.00430198*m.x285
+ 0.00433638*m.x286 + 0.0165516*m.x287 + 0.016409*m.x288 + 0.118695*m.x289
- 0.000353137*m.x290 + 0.00614138*m.x291 + 0.00393938*m.x292 + 0.010258*m.x293
+ 0.00833436*m.x294 + 0.0155411*m.x295 + 0.00633652*m.x296 - 0.0129386*m.x297
+ 0.000524607*m.x298 + 0.00156656*m.x299 + 0.0195551*m.x300 + 0.0106125*m.x301
+ 0.0178558*m.x302 + 0.00553876*m.x303 == 0)
m.c193 = Constraint(expr= - m.x88 + 0.0192039*m.x204 + 0.0139068*m.x205 + 0.0180183*m.x206 + 0.0328639*m.x207
+ 0.0201638*m.x208 - 0.00858219*m.x209 - 0.0109996*m.x210 - 0.00068661*m.x211
+ 0.0353783*m.x212 - 1.9656E-5*m.x213 + 0.011193*m.x214 + 0.00210401*m.x215
+ 0.00867089*m.x216 + 0.00164063*m.x217 + 0.0101419*m.x218 + 0.0161554*m.x219
+ 0.0143745*m.x220 + 0.00448489*m.x221 + 0.00210006*m.x222 + 0.00539703*m.x223
- 0.00278401*m.x224 - 0.00136755*m.x225 + 0.0242836*m.x226 + 0.0292669*m.x227
+ 0.0194659*m.x228 - 0.010655*m.x229 + 0.0139374*m.x230 + 0.00139924*m.x231 + 0.0357841*m.x232
+ 0.0326227*m.x233 - 0.0170139*m.x234 + 0.00842344*m.x235 + 0.0066923*m.x236
+ 0.0297617*m.x237 + 0.0353459*m.x238 + 0.0174822*m.x239 + 0.0182402*m.x240 + 0.011678*m.x241
+ 0.0137472*m.x242 + 0.00958774*m.x243 + 0.012869*m.x244 + 0.0225774*m.x245 - 0.0210138*m.x246
+ 0.013309*m.x247 - 0.0234656*m.x248 + 0.000876921*m.x249 - 0.00342056*m.x250
+ 0.0107168*m.x251 + 0.00929105*m.x252 + 0.0265097*m.x253 - 0.00873615*m.x254
- 0.0113699*m.x255 + 0.0140088*m.x256 - 0.00043216*m.x257 + 0.00732372*m.x258
+ 0.0127031*m.x259 + 0.013611*m.x260 + 0.0201735*m.x261 + 0.024251*m.x262 + 0.00901592*m.x263
- 0.00447213*m.x264 + 0.0230098*m.x265 - 0.0100831*m.x266 - 0.000461334*m.x267
+ 0.00586937*m.x268 + 0.00724424*m.x269 + 0.0130978*m.x270 + 0.0121892*m.x271
- 0.00391704*m.x272 + 0.0289396*m.x273 - 0.0216798*m.x274 + 0.0205286*m.x275
+ 0.00389974*m.x276 + 0.00960328*m.x277 + 0.0131673*m.x278 + 0.0128597*m.x279
- 0.00174931*m.x280 - 0.00284713*m.x281 - 0.00756629*m.x282 + 0.0451897*m.x283
+ 0.00412578*m.x284 - 0.00771995*m.x285 - 0.000835345*m.x286 + 0.0153948*m.x287
+ 0.0246084*m.x288 - 0.000353137*m.x289 + 0.210429*m.x290 - 0.0117993*m.x291
- 0.0050296*m.x292 + 0.00496234*m.x293 + 0.0147187*m.x294 - 0.00638346*m.x295
+ 0.0218038*m.x296 - 0.0149617*m.x297 - 0.0174471*m.x298 - 0.0103608*m.x299
+ 0.00170449*m.x300 - 0.00509478*m.x301 - 0.002207*m.x302 - 0.0131227*m.x303 == 0)
m.c194 = Constraint(expr= - m.x89 - 0.0085911*m.x204 + 0.0353495*m.x205 + 0.0226601*m.x206 + 0.0305972*m.x207
+ 0.0148104*m.x208 + 0.0238012*m.x209 + 0.0589001*m.x210 - 0.00420057*m.x211
+ 0.0245361*m.x212 - 0.0192722*m.x213 + 0.0112057*m.x214 + 0.000459202*m.x215
+ 0.0341752*m.x216 + 0.0339984*m.x217 + 0.0131187*m.x218 + 0.0142843*m.x219 + 0.0116517*m.x220
+ 0.0154255*m.x221 + 0.0549659*m.x222 + 0.0194179*m.x223 - 0.0110477*m.x224 + 0.031019*m.x225
+ 0.00470611*m.x226 + 0.0163439*m.x227 + 0.00940805*m.x228 + 0.0287315*m.x229
+ 0.0275472*m.x230 + 0.000402288*m.x231 + 0.00160462*m.x232 + 0.0179917*m.x233
- 0.00984516*m.x234 + 0.0178015*m.x235 - 0.0250217*m.x236 + 0.00416104*m.x237
+ 0.00602501*m.x238 + 0.0127497*m.x239 + 0.0285576*m.x240 + 0.0335903*m.x241
+ 0.0189174*m.x242 + 0.0218437*m.x243 - 0.040724*m.x244 + 0.0434221*m.x245 - 0.00303618*m.x246
+ 0.0161332*m.x247 + 0.00121975*m.x248 + 0.0255993*m.x249 + 0.0183674*m.x250
+ 0.0178279*m.x251 + 0.0129496*m.x252 + 0.00746963*m.x253 + 0.0046782*m.x254
+ 0.0889439*m.x255 + 0.0192336*m.x256 - 0.000981924*m.x257 + 0.00825968*m.x258
+ 0.0366677*m.x259 + 0.0214669*m.x260 + 0.017492*m.x261 + 0.0212452*m.x262 + 0.0227243*m.x263
+ 0.0267458*m.x264 + 9.8143E-5*m.x265 - 0.00430908*m.x266 + 0.0704456*m.x267
+ 0.0392681*m.x268 + 0.0184584*m.x269 + 0.00470305*m.x270 + 0.000632641*m.x271
- 0.0303804*m.x272 - 0.00526134*m.x273 + 0.0227594*m.x274 + 0.00300826*m.x275
+ 0.0230822*m.x276 - 0.000262221*m.x277 + 0.0237505*m.x278 + 0.00999317*m.x279
+ 0.0242284*m.x280 + 0.0481938*m.x281 - 0.0110851*m.x282 - 0.0310249*m.x283 + 0.0127761*m.x284
+ 0.0307627*m.x285 + 0.0177836*m.x286 + 0.0222877*m.x287 + 0.0175327*m.x288
+ 0.00614138*m.x289 - 0.0117993*m.x290 + 0.264474*m.x291 + 0.00357945*m.x292
+ 0.0191207*m.x293 + 0.00389068*m.x294 + 0.0126524*m.x295 + 0.0128723*m.x296
- 0.00897073*m.x297 + 0.013333*m.x298 + 0.0517181*m.x299 + 0.0246646*m.x300 - 0.0307355*m.x301
+ 0.00730538*m.x302 + 0.0341094*m.x303 == 0)
m.c195 = Constraint(expr= - m.x90 - 0.0062031*m.x204 + 0.00675913*m.x205 + 0.0329849*m.x206 - 0.00415707*m.x207
+ 0.0193621*m.x208 + 0.0088678*m.x209 + 0.00615122*m.x210 + 0.00921205*m.x211
+ 0.00939562*m.x212 + 0.0190744*m.x213 + 0.00953528*m.x214 - 0.00600004*m.x215
+ 0.00683051*m.x216 - 0.00434935*m.x217 + 0.0171011*m.x218 + 0.000969021*m.x219
+ 0.00972696*m.x220 - 0.00811765*m.x221 + 0.00908995*m.x222 - 0.0052549*m.x223
+ 0.0147706*m.x224 + 0.0172111*m.x225 + 0.0256701*m.x226 - 0.00379038*m.x227
- 0.00459271*m.x228 + 0.0267179*m.x229 + 0.0215472*m.x230 - 0.000836245*m.x231
+ 0.0130927*m.x232 + 0.00648866*m.x233 + 0.00481705*m.x234 - 0.00668788*m.x235
+ 0.0258152*m.x236 + 0.00696121*m.x237 + 0.00280658*m.x238 + 0.000594747*m.x239
- 0.00228211*m.x240 + 0.0133091*m.x241 - 0.00318997*m.x242 + 0.0058466*m.x243
+ 0.0241297*m.x244 + 0.0276431*m.x245 + 0.00239232*m.x246 + 0.0153765*m.x247
+ 0.00617827*m.x248 + 0.000761757*m.x249 + 0.00194382*m.x250 + 0.00290669*m.x251
+ 0.000165876*m.x252 + 0.014075*m.x253 + 0.00459631*m.x254 + 0.0105083*m.x255
+ 0.00082309*m.x256 + 0.0100724*m.x257 + 0.0142932*m.x258 + 0.00820119*m.x259
+ 0.00624642*m.x260 + 0.0200526*m.x261 + 0.0241234*m.x262 + 0.00169162*m.x263
+ 0.0216534*m.x264 - 0.00953022*m.x265 + 0.0313277*m.x266 + 0.00562888*m.x267
+ 0.0321897*m.x268 + 0.0225319*m.x269 + 0.0108874*m.x270 + 0.00328551*m.x271
+ 0.00348223*m.x272 + 0.012689*m.x273 + 0.00163182*m.x274 + 0.00755881*m.x275
- 0.0103966*m.x276 + 0.0117935*m.x277 + 0.0259753*m.x278 + 0.0274468*m.x279 + 0.0223464*m.x280
- 0.00283589*m.x281 + 0.0361459*m.x282 + 0.00587297*m.x283 + 0.0351101*m.x284
+ 0.0181157*m.x285 + 0.00188467*m.x286 + 0.0232654*m.x287 + 0.0132707*m.x288
+ 0.00393938*m.x289 - 0.0050296*m.x290 + 0.00357945*m.x291 + 0.129639*m.x292
+ 0.00974484*m.x293 - 0.00732373*m.x294 + 0.000942944*m.x295 + 0.0036973*m.x296
- 0.00875675*m.x297 + 0.0111863*m.x298 + 0.02613*m.x299 + 0.000479972*m.x300
- 0.0143007*m.x301 + 0.0294992*m.x302 + 0.00229934*m.x303 == 0)
m.c196 = Constraint(expr= - m.x91 + 0.00268854*m.x204 + 0.00676616*m.x205 + 0.00576928*m.x206 + 0.00964148*m.x207
+ 0.00948047*m.x208 - 3.17943E-5*m.x209 - 0.00717082*m.x210 + 0.000865255*m.x211
+ 0.0167069*m.x212 - 0.00901601*m.x213 + 0.000108253*m.x214 - 0.0113285*m.x215
+ 0.00335904*m.x216 + 0.00655352*m.x217 + 0.0259854*m.x218 + 0.0204454*m.x219
+ 0.0132094*m.x220 - 0.00385197*m.x221 - 0.00445561*m.x222 - 0.00625738*m.x223
+ 0.00705238*m.x224 + 0.00272478*m.x225 + 0.0286405*m.x226 - 0.00181686*m.x227
+ 0.00697339*m.x228 - 0.0133302*m.x229 + 0.00487961*m.x230 + 0.00367641*m.x231
+ 0.00657462*m.x232 + 0.00140866*m.x233 - 0.0055852*m.x234 + 0.00142361*m.x235
- 0.00246468*m.x236 - 0.00477706*m.x237 + 0.0141143*m.x238 + 0.0173728*m.x239
+ 0.00194986*m.x240 + 0.0154967*m.x241 - 0.0127847*m.x242 + 0.0163626*m.x243
+ 0.00261203*m.x244 + 0.0182416*m.x245 + 0.000321826*m.x246 + 0.0172788*m.x247
+ 0.0181113*m.x248 + 0.0226772*m.x249 + 0.0120585*m.x250 - 0.011085*m.x251 + 0.0104514*m.x252
+ 0.000392536*m.x253 + 0.0212014*m.x254 + 0.00390748*m.x255 + 0.00967333*m.x256
+ 0.00947697*m.x257 + 0.00984404*m.x258 - 0.00665374*m.x259 + 0.00454738*m.x260
+ 0.00522364*m.x261 + 0.0195278*m.x262 - 0.00631568*m.x263 + 0.0107144*m.x264
+ 0.0169729*m.x265 + 0.00449822*m.x266 + 0.0251025*m.x267 + 0.00459229*m.x268
- 0.00115612*m.x269 + 0.0151819*m.x270 - 0.00509853*m.x271 - 0.00324749*m.x272
+ 0.0135528*m.x273 + 0.000148116*m.x274 + 0.0070906*m.x275 - 0.00167457*m.x276
- 0.00608545*m.x277 + 0.00232003*m.x278 + 0.00337803*m.x279 + 0.00218928*m.x280
+ 0.016211*m.x281 - 0.00085728*m.x282 - 0.0136089*m.x283 - 0.00463556*m.x284
- 0.00258019*m.x285 + 0.0090193*m.x286 + 0.00990806*m.x287 + 0.00899692*m.x288
+ 0.010258*m.x289 + 0.00496234*m.x290 + 0.0191207*m.x291 + 0.00974484*m.x292
+ 0.0989508*m.x293 + 0.00117698*m.x294 + 0.0186877*m.x295 + 0.0151336*m.x296
- 0.00798193*m.x297 + 0.0111385*m.x298 + 0.00565412*m.x299 - 0.00243878*m.x300
- 0.00072217*m.x301 + 0.00459902*m.x302 + 0.0100122*m.x303 == 0)
m.c197 = Constraint(expr= - m.x92 + 0.00374751*m.x204 - 0.0169577*m.x205 - 0.00470462*m.x206 + 0.000244902*m.x207
+ 0.0107385*m.x208 + 0.0181268*m.x209 + 0.0112392*m.x210 + 0.00517365*m.x211
- 0.0177537*m.x212 - 0.00394108*m.x213 + 0.00372088*m.x214 - 0.00379879*m.x215
+ 0.0162828*m.x216 + 0.0190876*m.x217 + 0.00869282*m.x218 + 0.0180185*m.x219
+ 0.0214788*m.x220 - 0.00894921*m.x221 - 0.0035093*m.x222 - 2.9997E-5*m.x223 - 0.001978*m.x224
- 0.000689796*m.x225 + 0.00175624*m.x226 + 0.0125924*m.x227 - 0.00111199*m.x228
- 0.00269826*m.x229 + 0.00165055*m.x230 - 0.0247945*m.x231 + 0.0120928*m.x232
+ 0.00503874*m.x233 - 0.00360636*m.x234 + 0.0199408*m.x235 + 0.0138925*m.x236
+ 0.024389*m.x237 - 0.0138066*m.x238 - 0.012529*m.x239 + 0.00780586*m.x240
+ 0.000594082*m.x241 + 0.00325109*m.x242 + 0.00109195*m.x243 + 0.0174076*m.x244
+ 0.00868526*m.x245 + 0.0159286*m.x246 + 0.00454689*m.x247 - 0.0146448*m.x248
- 0.00239856*m.x249 + 0.004607*m.x250 - 0.020525*m.x251 + 0.0177858*m.x252 + 0.02246*m.x253
+ 0.0117374*m.x254 + 0.00684597*m.x255 + 0.000291585*m.x256 + 0.0122578*m.x257
- 0.00774969*m.x258 + 0.00551264*m.x259 + 0.00717722*m.x260 + 0.0101262*m.x261
- 0.00432386*m.x262 - 0.014748*m.x263 + 0.0142204*m.x264 + 0.0174156*m.x265
- 0.00307272*m.x266 + 0.00344892*m.x267 - 0.00116349*m.x268 + 0.000984092*m.x269
+ 0.0195643*m.x270 + 0.0148681*m.x271 + 0.00746468*m.x272 + 0.0136874*m.x273
- 0.00314438*m.x274 + 0.0162991*m.x275 + 0.0127897*m.x276 + 0.00565714*m.x277
+ 0.00642914*m.x278 + 0.0146469*m.x279 - 0.00234487*m.x280 + 0.0174578*m.x281
+ 0.0474245*m.x282 - 0.000516624*m.x283 + 0.00349789*m.x284 - 0.00682747*m.x285
- 0.000926932*m.x286 + 0.00288787*m.x287 + 0.00791625*m.x288 + 0.00833436*m.x289
+ 0.0147187*m.x290 + 0.00389068*m.x291 - 0.00732373*m.x292 + 0.00117698*m.x293
+ 0.124044*m.x294 - 0.00410261*m.x295 + 0.00179877*m.x296 - 0.0030439*m.x297
+ 0.0192348*m.x298 + 0.0127468*m.x299 + 0.0208105*m.x300 + 0.0177241*m.x301
+ 0.00171535*m.x302 - 0.0084253*m.x303 == 0)
m.c198 = Constraint(expr= - m.x93 + 0.0123958*m.x204 + 0.00339621*m.x205 - 0.0153482*m.x206 + 0.0374478*m.x207
+ 0.00287505*m.x208 + 0.00782932*m.x209 + 0.000610349*m.x210 + 0.0240808*m.x211
+ 0.00699783*m.x212 + 0.00072213*m.x213 + 0.00788742*m.x214 + 0.015416*m.x215
+ 0.0256177*m.x216 + 0.0274041*m.x217 + 0.00673672*m.x218 + 0.00550125*m.x219
+ 0.0108732*m.x220 + 0.0124411*m.x221 + 0.0111934*m.x222 + 0.0241985*m.x223
+ 0.00955359*m.x224 - 0.0132155*m.x225 + 0.00904265*m.x226 + 0.0294016*m.x227
- 0.0171837*m.x228 - 0.0321221*m.x229 - 0.00879465*m.x230 + 0.00750897*m.x231
+ 0.00756116*m.x232 + 0.010448*m.x233 - 0.000266747*m.x234 + 0.030029*m.x235
+ 0.00427117*m.x236 + 0.0151776*m.x237 + 0.00103245*m.x238 - 0.00810868*m.x239
+ 0.0298143*m.x240 + 0.0384969*m.x241 + 0.0175238*m.x242 + 0.016576*m.x243 + 0.0155538*m.x244
+ 0.013908*m.x245 - 0.000456654*m.x246 - 0.00408178*m.x247 - 0.0232215*m.x248
- 0.000303141*m.x249 + 0.017139*m.x250 - 0.0111643*m.x251 + 0.0273403*m.x252
+ 0.0196935*m.x253 + 0.0229518*m.x254 + 0.0131893*m.x255 + 0.0165254*m.x256 + 0.0215961*m.x257
- 0.00584549*m.x258 + 0.0332128*m.x259 + 0.0127629*m.x260 + 0.033537*m.x261
- 0.00115008*m.x262 + 0.0202061*m.x263 + 0.0660462*m.x264 + 0.0182632*m.x265
+ 0.00735778*m.x266 - 0.0224606*m.x267 + 0.00533042*m.x268 + 0.000260201*m.x269
+ 0.0289658*m.x270 + 0.0201209*m.x271 - 0.00652909*m.x272 - 0.000426475*m.x273
+ 0.00826237*m.x274 - 0.0210064*m.x275 + 0.0629866*m.x276 + 0.014422*m.x277
- 0.000406401*m.x278 + 0.00469697*m.x279 + 0.0106011*m.x280 + 0.0438875*m.x281
- 0.0216252*m.x282 + 0.0009259*m.x283 - 0.00754138*m.x284 + 0.0206012*m.x285
+ 0.0189143*m.x286 + 0.00781374*m.x287 + 0.0177061*m.x288 + 0.0155411*m.x289
- 0.00638346*m.x290 + 0.0126524*m.x291 + 0.000942944*m.x292 + 0.0186877*m.x293
- 0.00410261*m.x294 + 0.211508*m.x295 - 0.00562326*m.x296 + 0.00136296*m.x297
- 0.00331104*m.x298 + 0.0156995*m.x299 + 0.028973*m.x300 - 0.0137125*m.x301
- 0.00137032*m.x302 + 0.00956384*m.x303 == 0)
m.c199 = Constraint(expr= - m.x94 - 0.00281911*m.x204 + 0.0150229*m.x205 + 0.0172118*m.x206 + 0.020036*m.x207
+ 0.0130434*m.x208 + 0.00311794*m.x209 + 0.0116254*m.x210 + 0.00215238*m.x211
- 0.0148329*m.x212 + 0.0287036*m.x213 + 0.035638*m.x214 + 0.0100832*m.x215 + 0.021417*m.x216
+ 0.020182*m.x217 + 0.0316891*m.x218 + 0.0173229*m.x219 + 0.0316462*m.x220 + 0.0222568*m.x221
- 0.00595445*m.x222 - 0.00345471*m.x223 + 0.0206419*m.x224 - 0.0122813*m.x225
+ 0.0101954*m.x226 + 0.014454*m.x227 + 0.00427236*m.x228 + 0.0256948*m.x229
- 0.00601501*m.x230 + 0.00220324*m.x231 + 0.00893784*m.x232 + 0.0187694*m.x233
+ 0.00272322*m.x234 - 0.000706121*m.x235 + 0.0100517*m.x236 - 0.00263518*m.x237
+ 0.0131295*m.x238 + 0.0296006*m.x239 + 0.0316103*m.x240 + 0.0132003*m.x241 + 0.0105851*m.x242
+ 0.0121524*m.x243 + 0.0118422*m.x244 + 0.0117221*m.x245 + 0.0140437*m.x246 + 0.0106112*m.x247
+ 0.00688969*m.x248 + 0.00819898*m.x249 + 0.0200535*m.x250 - 0.00203641*m.x251
+ 0.00347406*m.x252 + 0.0203211*m.x253 + 0.00232247*m.x254 - 0.0139354*m.x255
+ 0.00824013*m.x256 + 0.0101139*m.x257 - 0.00254807*m.x258 + 0.000520073*m.x259
+ 0.019358*m.x260 + 0.0302725*m.x261 - 0.00414181*m.x262 + 0.00890168*m.x263
- 0.0111379*m.x264 + 0.00110738*m.x265 + 0.015328*m.x266 + 0.00833154*m.x267
+ 0.0083884*m.x268 - 0.00178894*m.x269 + 0.000514941*m.x270 + 0.023585*m.x271
+ 0.00590442*m.x272 + 0.020855*m.x273 + 0.0225842*m.x274 + 0.0190915*m.x275
+ 0.00369913*m.x276 + 0.00362916*m.x277 + 0.0185527*m.x278 + 0.02019*m.x279
+ 0.00596788*m.x280 + 0.0271732*m.x281 - 0.0305481*m.x282 + 0.0175048*m.x283
- 0.00336606*m.x284 + 0.00945896*m.x285 + 0.0239269*m.x286 - 0.000230336*m.x287
+ 0.00207808*m.x288 + 0.00633652*m.x289 + 0.0218038*m.x290 + 0.0128723*m.x291
+ 0.0036973*m.x292 + 0.0151336*m.x293 + 0.00179877*m.x294 - 0.00562326*m.x295
+ 0.155072*m.x296 + 0.0153515*m.x297 + 0.00102254*m.x298 + 0.0159403*m.x299
+ 0.00179188*m.x300 - 0.0137303*m.x301 + 0.00491891*m.x302 + 0.00903696*m.x303 == 0)
m.c200 = Constraint(expr= - m.x95 + 0.0022118*m.x204 - 0.0133134*m.x205 - 0.0344168*m.x206 + 0.00411236*m.x207
- 0.00176429*m.x208 - 0.032215*m.x209 - 0.0224759*m.x210 + 0.0141697*m.x211 + 0.178873*m.x212
- 0.00879298*m.x213 - 0.0118438*m.x214 - 0.0115254*m.x215 - 0.00659726*m.x216
- 0.0260426*m.x217 - 0.0156915*m.x218 - 0.0118909*m.x219 - 0.0102103*m.x220 + 0.05196*m.x221
+ 0.00346376*m.x222 + 0.0232975*m.x223 - 0.0195786*m.x224 - 0.0179837*m.x225
+ 0.00334169*m.x226 + 0.00907196*m.x227 - 0.0133342*m.x228 - 0.0250774*m.x229
- 0.0151708*m.x230 + 0.00583633*m.x231 - 0.00747816*m.x232 - 0.0111273*m.x233
- 0.0135944*m.x234 + 0.0120762*m.x235 - 0.0267599*m.x236 - 0.0223564*m.x237
- 0.00507596*m.x238 - 0.0055076*m.x239 - 0.0168264*m.x240 - 0.00324796*m.x241
+ 0.0218937*m.x242 + 0.0114468*m.x243 + 0.0140178*m.x244 - 0.00373821*m.x245
- 0.0133161*m.x246 - 0.00745302*m.x247 + 0.0659066*m.x248 - 0.0155281*m.x249
- 0.0108609*m.x250 + 0.00376918*m.x251 + 0.00897938*m.x252 + 0.00142186*m.x253
- 0.0141535*m.x254 - 0.0247692*m.x255 - 0.00561804*m.x256 + 0.00689054*m.x257
- 0.00996077*m.x258 - 0.00757188*m.x259 + 0.0375824*m.x260 + 0.00311747*m.x261
- 0.0293668*m.x262 - 0.0256392*m.x263 - 0.0165798*m.x264 - 0.00610696*m.x265
- 0.00549157*m.x266 - 0.0234811*m.x267 - 0.00154795*m.x268 + 0.00486873*m.x269
- 0.00429564*m.x270 - 0.00188899*m.x271 - 0.0198962*m.x272 - 0.00692332*m.x273
- 0.0145782*m.x274 - 0.0125323*m.x275 + 0.0201848*m.x276 + 0.0108815*m.x277 + 0.0077666*m.x278
- 0.012203*m.x279 + 0.0140801*m.x280 - 0.00264823*m.x281 + 0.00800911*m.x282
+ 0.0373561*m.x283 - 0.0216041*m.x284 + 0.0244376*m.x285 + 0.0214766*m.x286 + 0.0165132*m.x287
+ 0.0251146*m.x288 - 0.0129386*m.x289 - 0.0149617*m.x290 - 0.00897073*m.x291
- 0.00875675*m.x292 - 0.00798193*m.x293 - 0.0030439*m.x294 + 0.00136296*m.x295
+ 0.0153515*m.x296 + 1.0439*m.x297 - 0.00146374*m.x298 + 0.00154313*m.x299 - 0.00279411*m.x300
- 0.0164048*m.x301 - 0.00262205*m.x302 - 0.000527897*m.x303 == 0)
m.c201 = Constraint(expr= - m.x96 + 0.0167955*m.x204 + 0.0134182*m.x205 - 0.0408698*m.x206 + 0.0103469*m.x207
+ 0.036063*m.x208 + 0.00207316*m.x209 + 0.00642488*m.x210 + 0.00516594*m.x211
+ 0.00483769*m.x212 - 0.00130419*m.x213 - 0.00955396*m.x214 + 0.0489927*m.x215
+ 0.031985*m.x216 + 0.0584498*m.x217 + 0.0357759*m.x218 + 0.00154333*m.x219 + 0.0284578*m.x220
+ 0.000359792*m.x221 + 0.00938963*m.x222 - 0.00383232*m.x223 + 0.0321854*m.x224
- 0.0115174*m.x225 + 0.0120672*m.x226 - 0.0155799*m.x227 + 0.0159789*m.x228
- 0.00835702*m.x229 + 0.0709325*m.x230 + 0.00119846*m.x231 + 0.00341049*m.x232
+ 0.013655*m.x233 - 0.0102535*m.x234 + 0.0417235*m.x235 - 0.00630875*m.x236
+ 0.00104505*m.x237 + 0.037088*m.x238 - 0.000573198*m.x239 + 0.00133433*m.x240
+ 0.0198875*m.x241 + 0.0120314*m.x242 + 0.0229932*m.x243 + 0.0167384*m.x244 + 0.0089429*m.x245
+ 0.00274327*m.x246 + 0.0138402*m.x247 + 0.0163443*m.x248 + 0.01631*m.x249 + 0.0112311*m.x250
+ 0.0118935*m.x251 + 0.0131703*m.x252 + 0.00797244*m.x253 + 0.00517337*m.x254
+ 0.0243459*m.x255 + 0.0192153*m.x256 + 0.0214997*m.x257 - 0.00480671*m.x258
+ 0.00641418*m.x259 + 0.0198104*m.x260 + 0.00113182*m.x261 - 0.00629538*m.x262
+ 0.046066*m.x263 + 0.0260859*m.x264 + 0.0117812*m.x265 + 0.0169898*m.x266 - 0.0262964*m.x267
+ 0.00327212*m.x268 + 0.01*m.x269 + 0.0195899*m.x270 - 0.0117063*m.x271 + 0.015777*m.x272
+ 0.00700229*m.x273 - 0.00503236*m.x274 + 0.0147594*m.x275 - 0.00505562*m.x276
+ 0.00215519*m.x277 + 0.012311*m.x278 + 0.00574997*m.x279 + 0.0111286*m.x280
+ 0.0161145*m.x281 - 0.00833087*m.x282 - 0.0112765*m.x283 + 0.0121631*m.x284
+ 0.0327088*m.x285 + 0.0299348*m.x286 + 0.0382825*m.x287 + 0.0184837*m.x288
+ 0.000524607*m.x289 - 0.0174471*m.x290 + 0.013333*m.x291 + 0.0111863*m.x292
+ 0.0111385*m.x293 + 0.0192348*m.x294 - 0.00331104*m.x295 + 0.00102254*m.x296
- 0.00146374*m.x297 + 0.791704*m.x298 - 0.0277421*m.x299 + 0.0494004*m.x300 - 0.0111381*m.x301
+ 0.0155984*m.x302 - 0.000109889*m.x303 == 0)
m.c202 = Constraint(expr= - m.x97 - 0.0279332*m.x204 + 0.0889001*m.x205 + 0.0755415*m.x206 - 0.012054*m.x207
+ 0.0123589*m.x208 + 0.0352617*m.x209 + 0.00803335*m.x210 + 0.00216393*m.x211
+ 0.0402204*m.x212 + 0.0144463*m.x213 + 0.0411535*m.x214 + 0.00172935*m.x215
+ 0.0158572*m.x216 + 0.0466449*m.x217 + 0.0174851*m.x218 + 0.00648827*m.x219
+ 0.0136054*m.x220 + 0.0473451*m.x221 + 0.0125983*m.x222 - 0.000654628*m.x223
+ 0.00830393*m.x224 + 0.0545863*m.x225 - 0.00247613*m.x226 - 0.000311276*m.x227
+ 0.0137361*m.x228 + 0.0620713*m.x229 + 0.0366289*m.x230 - 0.0223825*m.x231 + 0.104347*m.x232
+ 0.0137759*m.x233 + 0.0378678*m.x234 + 0.0169276*m.x235 + 0.00112457*m.x236
+ 0.0433625*m.x237 - 0.0155039*m.x238 + 0.018767*m.x239 + 0.0320353*m.x240 + 0.00123223*m.x241
+ 0.0247783*m.x242 + 0.0274591*m.x243 + 0.0447304*m.x244 + 0.0223685*m.x245 + 0.0088079*m.x246
- 0.00206706*m.x247 + 0.0491497*m.x248 + 0.0130047*m.x249 - 0.000464008*m.x250
+ 0.0159972*m.x251 + 0.0238145*m.x252 + 0.0303016*m.x253 + 0.0102284*m.x254 + 0.0752523*m.x255
- 0.00817059*m.x256 - 0.00197476*m.x257 + 0.017175*m.x258 + 0.00692204*m.x259
+ 0.0133092*m.x260 + 0.0359219*m.x261 - 0.0228968*m.x262 - 0.0109849*m.x263 + 0.0220738*m.x264
+ 0.0127772*m.x265 + 0.0267541*m.x266 - 0.0175235*m.x267 + 0.0425838*m.x268
+ 0.00629557*m.x269 - 0.00999522*m.x270 + 0.0273148*m.x271 + 0.0320781*m.x272
+ 0.016756*m.x273 + 0.0195997*m.x274 + 0.0449847*m.x275 - 0.0107799*m.x276 + 0.015215*m.x277
+ 0.0214616*m.x278 + 0.0450781*m.x279 + 0.0108432*m.x280 + 0.00509121*m.x281
- 0.0224481*m.x282 + 0.0051311*m.x283 + 0.0125615*m.x284 + 0.0159115*m.x285 + 0.0657669*m.x286
- 0.016509*m.x287 + 0.00390491*m.x288 + 0.00156656*m.x289 - 0.0103608*m.x290
+ 0.0517181*m.x291 + 0.02613*m.x292 + 0.00565412*m.x293 + 0.0127468*m.x294 + 0.0156995*m.x295
+ 0.0159403*m.x296 + 0.00154313*m.x297 - 0.0277421*m.x298 + 0.506744*m.x299 + 0.0310222*m.x300
- 0.00663623*m.x301 + 0.0161424*m.x302 + 0.00659053*m.x303 == 0)
m.c203 = Constraint(expr= - m.x98 + 0.0227079*m.x204 + 0.0286671*m.x205 + 0.0219066*m.x206 + 0.0183139*m.x207
+ 0.0190362*m.x208 + 0.0157662*m.x209 + 0.0180457*m.x210 + 0.0179954*m.x211 + 0.111526*m.x212
+ 0.0227*m.x213 - 0.00808243*m.x214 - 0.00821597*m.x215 + 0.0232882*m.x216 + 0.0330244*m.x217
- 0.0063521*m.x218 - 0.00193745*m.x219 + 0.0283516*m.x220 + 0.00195216*m.x221
+ 0.0159186*m.x222 + 0.00357173*m.x223 + 0.0105133*m.x224 + 0.0401891*m.x225
+ 0.00811643*m.x226 + 0.0367786*m.x227 + 0.00616904*m.x228 + 0.0267618*m.x229
+ 0.000218956*m.x230 + 0.030938*m.x231 + 0.0194493*m.x232 + 0.0225411*m.x233
- 0.0155415*m.x234 + 0.0024374*m.x235 + 0.0190696*m.x236 + 0.00802342*m.x237
+ 0.0401269*m.x238 + 0.011041*m.x239 + 0.0433973*m.x240 + 0.0178267*m.x241 + 0.0295261*m.x242
+ 0.0170962*m.x243 + 0.0519824*m.x244 + 0.00186956*m.x245 - 0.0199075*m.x246
- 0.00104385*m.x247 + 0.0230853*m.x248 + 0.007868*m.x249 + 0.00372516*m.x250
+ 0.00701074*m.x251 + 0.0112134*m.x252 + 0.0163988*m.x253 + 0.016647*m.x254
- 0.00276693*m.x255 + 0.0078892*m.x256 + 0.0136175*m.x257 + 0.00103887*m.x258
+ 0.0175234*m.x259 + 0.0195271*m.x260 + 0.000595551*m.x261 + 0.00307471*m.x262
+ 0.00658164*m.x263 + 0.0291965*m.x264 + 0.0162*m.x265 - 0.019998*m.x266 + 0.0205719*m.x267
+ 0.0191781*m.x268 + 0.0103958*m.x269 + 0.00608684*m.x270 + 0.0284999*m.x271
- 0.00215074*m.x272 + 0.0360264*m.x273 + 0.00361997*m.x274 + 0.0390785*m.x275 + 0.0045*m.x276
+ 0.017746*m.x277 + 0.0298427*m.x278 + 0.103864*m.x279 + 0.014432*m.x280 + 0.0367902*m.x281
+ 0.026356*m.x282 + 0.014489*m.x283 + 0.012455*m.x284 + 0.0166712*m.x285 + 0.00914343*m.x286
+ 0.0189584*m.x287 + 0.0146561*m.x288 + 0.0195551*m.x289 + 0.00170449*m.x290
+ 0.0246646*m.x291 + 0.000479972*m.x292 - 0.00243878*m.x293 + 0.0208105*m.x294
+ 0.028973*m.x295 + 0.00179188*m.x296 - 0.00279411*m.x297 + 0.0494004*m.x298
+ 0.0310222*m.x299 + 0.320585*m.x300 - 0.00421853*m.x301 + 0.00758314*m.x302
+ 0.0183194*m.x303 == 0)
m.c204 = Constraint(expr= - m.x99 + 0.00975774*m.x204 + 0.0390347*m.x205 + 0.00157357*m.x206 - 0.0288293*m.x207
- 0.01883*m.x208 + 0.243511*m.x209 + 0.0047812*m.x210 - 0.00675247*m.x211 - 0.00193246*m.x212
+ 0.00430831*m.x213 - 0.0197548*m.x214 - 0.0062146*m.x215 + 0.00712137*m.x216
+ 0.0380016*m.x217 - 0.0081262*m.x218 + 0.000983654*m.x219 - 0.0101858*m.x220
- 0.0137668*m.x221 - 0.0256068*m.x222 + 0.0350406*m.x223 - 0.0266952*m.x224 + 0.0297056*m.x225
+ 0.00451179*m.x226 - 0.0255962*m.x227 - 0.0154329*m.x228 + 0.00732044*m.x229
+ 0.0460118*m.x230 + 0.0193729*m.x231 - 0.00520844*m.x232 - 0.0033488*m.x233
+ 0.00593378*m.x234 - 0.0096037*m.x235 + 0.0196793*m.x236 + 0.0485713*m.x237
- 0.00474519*m.x238 - 0.0114838*m.x239 - 0.0108392*m.x240 - 0.00475543*m.x241
- 0.0120001*m.x242 - 0.0143186*m.x243 + 0.00580577*m.x244 - 0.000502651*m.x245
+ 0.0201943*m.x246 - 0.0111014*m.x247 + 0.0414341*m.x248 + 0.0172829*m.x249
+ 0.00268954*m.x250 + 0.0129573*m.x251 - 0.00463261*m.x252 - 0.0103262*m.x253
+ 0.00970317*m.x254 - 0.00836392*m.x255 + 0.00463932*m.x256 + 0.0236766*m.x257
- 2.46303E-5*m.x258 - 0.0128168*m.x259 - 0.00823347*m.x260 + 4.13827E-5*m.x261
+ 0.0204793*m.x262 + 0.0362579*m.x263 - 0.00087998*m.x264 - 0.0368529*m.x265
- 0.00561625*m.x266 - 0.0402272*m.x267 + 0.00444886*m.x268 + 0.0109707*m.x269
- 0.0133354*m.x270 - 0.00353962*m.x271 + 0.010315*m.x272 - 0.0259344*m.x273
+ 0.000208782*m.x274 - 0.0172229*m.x275 + 0.0173545*m.x276 + 0.00771442*m.x277
- 0.00757473*m.x278 - 0.0301521*m.x279 + 0.0196268*m.x280 - 0.0132156*m.x281 + 0.020753*m.x282
- 0.00457749*m.x283 + 0.018402*m.x284 + 0.0072935*m.x285 + 0.00979692*m.x286
- 0.00704493*m.x287 - 0.0140423*m.x288 + 0.0106125*m.x289 - 0.00509478*m.x290
- 0.0307355*m.x291 - 0.0143007*m.x292 - 0.00072217*m.x293 + 0.0177241*m.x294
- 0.0137125*m.x295 - 0.0137303*m.x296 - 0.0164048*m.x297 - 0.0111381*m.x298
- 0.00663623*m.x299 - 0.00421853*m.x300 + 0.579298*m.x301 + 0.0162035*m.x302
+ 0.0219849*m.x303 == 0)
m.c205 = Constraint(expr= - m.x100 + 0.000116986*m.x204 + 0.00733705*m.x205 + 0.0412011*m.x206 + 0.00250478*m.x207
+ 0.0156576*m.x208 + 0.006698*m.x209 + 0.00731383*m.x210 + 0.00119681*m.x211
+ 0.0326706*m.x212 + 0.00196198*m.x213 - 0.00408574*m.x214 - 0.014221*m.x215
+ 0.00355863*m.x216 + 0.00172257*m.x217 + 0.00733927*m.x218 + 0.0114558*m.x219
+ 0.00777919*m.x220 + 0.000840073*m.x221 + 0.00097566*m.x222 + 0.00821698*m.x223
+ 0.00665696*m.x224 + 0.00722685*m.x225 + 0.0116179*m.x226 + 0.0136226*m.x227
+ 0.000498937*m.x228 + 0.0133219*m.x229 + 0.0341929*m.x230 + 0.0100684*m.x231
+ 0.00369624*m.x232 + 0.031476*m.x233 + 0.012364*m.x234 + 0.00722129*m.x235 + 0.0119806*m.x236
+ 0.0032333*m.x237 + 0.0102928*m.x238 + 0.00268364*m.x239 + 0.00751702*m.x240
+ 0.0129675*m.x241 + 0.00121728*m.x242 + 0.00875979*m.x243 + 0.012385*m.x244
+ 0.0174325*m.x245 + 0.0380042*m.x246 + 0.00860025*m.x247 + 0.0105274*m.x248
+ 0.00542659*m.x249 + 0.0166562*m.x250 + 0.00101054*m.x251 + 0.00520514*m.x252
+ 0.0138437*m.x253 + 0.0100764*m.x254 + 0.0169651*m.x255 - 0.00593801*m.x256
+ 0.00337669*m.x257 + 0.00495815*m.x258 + 0.0164063*m.x259 - 0.00820594*m.x260
+ 0.0152464*m.x261 + 0.00683967*m.x262 + 0.00917306*m.x263 + 0.00952427*m.x264
+ 0.0012669*m.x265 - 0.010356*m.x266 - 0.00924209*m.x267 + 0.0219505*m.x268 + 0.0344609*m.x269
+ 0.00371045*m.x270 + 0.00538445*m.x271 + 0.0111624*m.x272 + 0.00953552*m.x273
+ 0.0145316*m.x274 + 0.0289407*m.x275 + 0.000465444*m.x276 + 0.00826654*m.x277
+ 0.00326998*m.x278 + 0.0209427*m.x279 + 0.0388318*m.x280 + 0.0177839*m.x281
+ 0.0316754*m.x282 + 0.00838465*m.x283 + 0.0384063*m.x284 + 0.00573711*m.x285
+ 0.00280778*m.x286 + 0.0230199*m.x287 + 0.0118626*m.x288 + 0.0178558*m.x289 - 0.002207*m.x290
+ 0.00730538*m.x291 + 0.0294992*m.x292 + 0.00459902*m.x293 + 0.00171535*m.x294
- 0.00137032*m.x295 + 0.00491891*m.x296 - 0.00262205*m.x297 + 0.0155984*m.x298
+ 0.0161424*m.x299 + 0.00758314*m.x300 + 0.0162035*m.x301 + 0.0858551*m.x302
- 0.00939134*m.x303 == 0)
m.c206 = Constraint(expr= - m.x101 + 0.00508413*m.x204 + 0.0374277*m.x205 + 0.0159705*m.x206 + 0.0130454*m.x207
+ 0.0265264*m.x208 + 0.0576747*m.x209 + 0.0122221*m.x210 - 0.00205582*m.x211
- 0.00767129*m.x212 + 0.006199*m.x213 + 0.0233977*m.x214 + 0.0110839*m.x215
+ 0.00654047*m.x216 + 0.00682218*m.x217 + 0.00484072*m.x218 + 0.00327572*m.x219
+ 0.00012158*m.x220 + 0.0227501*m.x221 - 0.00691953*m.x222 + 0.0156317*m.x223
- 0.00571234*m.x224 + 0.0243685*m.x225 + 0.0132863*m.x226 + 0.0209203*m.x227
+ 0.0264262*m.x228 + 0.0208839*m.x229 - 0.00140343*m.x230 + 0.00790278*m.x231
+ 0.0310417*m.x232 + 0.0123762*m.x233 + 0.0241458*m.x234 + 0.018823*m.x235 + 0.0371377*m.x236
+ 0.0332113*m.x237 + 0.0227151*m.x238 + 0.0211458*m.x239 - 0.00144612*m.x240
+ 0.00875978*m.x241 - 0.00249785*m.x242 + 0.00792635*m.x243 + 0.0180453*m.x244
+ 0.0334254*m.x245 - 0.00589524*m.x246 + 0.0108073*m.x247 + 0.00672014*m.x248
+ 0.00997388*m.x249 + 0.00639193*m.x250 - 0.00326076*m.x251 - 0.00135479*m.x252
+ 0.00766798*m.x253 + 0.00923673*m.x254 + 0.0207104*m.x255 + 0.00325836*m.x256
+ 0.0035861*m.x257 + 0.0225131*m.x258 + 0.00875325*m.x259 + 0.00813384*m.x260
- 0.0111606*m.x261 - 0.0105449*m.x262 + 0.0146768*m.x263 + 0.00243344*m.x264
+ 0.000788331*m.x265 + 0.0111971*m.x266 + 0.0228584*m.x267 + 0.0116164*m.x268
+ 0.00845491*m.x269 - 0.00737205*m.x270 - 0.00465145*m.x271 + 0.0154715*m.x272
+ 0.0189209*m.x273 + 0.0365771*m.x274 + 0.00458626*m.x275 + 0.00702905*m.x276
- 0.0216509*m.x277 + 0.0195985*m.x278 + 0.016127*m.x279 + 0.0139537*m.x280 + 0.0109642*m.x281
+ 0.00176788*m.x282 - 0.0161154*m.x283 + 0.0175444*m.x284 + 0.0260562*m.x285
+ 0.00369429*m.x286 + 0.0134259*m.x287 - 0.00284169*m.x288 + 0.00553876*m.x289
- 0.0131227*m.x290 + 0.0341094*m.x291 + 0.00229934*m.x292 + 0.0100122*m.x293
- 0.0084253*m.x294 + 0.00956384*m.x295 + 0.00903696*m.x296 - 0.000527897*m.x297
- 0.000109889*m.x298 + 0.00659053*m.x299 + 0.0183194*m.x300 + 0.0219849*m.x301
- 0.00939134*m.x302 + 0.203443*m.x303 == 0)
m.c207 = Constraint(expr= - m.x102 + 0.101389*m.x204 + 0.00922513*m.x205 + 0.0026992*m.x206 + 0.00246784*m.x207
+ 0.00231482*m.x208 - 0.00125222*m.x209 - 0.00392467*m.x210 - 0.0046966*m.x211
- 0.0142117*m.x212 - 0.00150584*m.x213 - 0.00472481*m.x214 - 0.00116843*m.x215
- 0.00080131*m.x216 + 0.0048818*m.x217 - 0.00479483*m.x218 + 0.00726609*m.x219
+ 0.00902802*m.x220 + 0.0114247*m.x221 - 0.00483357*m.x222 + 9.94895E-5*m.x223
+ 0.00286308*m.x224 - 3.33076E-5*m.x225 + 0.00353482*m.x226 - 0.00220136*m.x227
+ 0.00200825*m.x228 - 0.00767398*m.x229 - 0.00197822*m.x230 - 1.10346E-5*m.x231
- 0.00119407*m.x232 + 0.000602811*m.x233 + 0.0132444*m.x234 - 0.00406553*m.x235
+ 0.00422631*m.x236 - 0.00343731*m.x237 + 0.00651535*m.x238 - 0.00313138*m.x239
+ 0.00359841*m.x240 + 0.00452148*m.x241 + 0.00366834*m.x242 + 0.00592328*m.x243
+ 0.00503367*m.x244 + 0.00629207*m.x245 + 0.00300993*m.x246 - 0.00042207*m.x247
+ 0.0126161*m.x248 + 0.000539029*m.x249 + 0.00171572*m.x250 + 0.00871066*m.x251
- 0.000658519*m.x252 + 0.00632557*m.x253 - 1.12481E-5*m.x254 + 0.00423842*m.x255
- 0.000128391*m.x256 + 0.00428623*m.x257 + 0.00221565*m.x258 + 0.00293236*m.x259
+ 0.00642301*m.x260 - 0.00424851*m.x261 + 0.00130686*m.x262 + 0.0135606*m.x263
- 0.000827581*m.x264 + 0.000319199*m.x265 - 0.00408084*m.x266 - 0.0130473*m.x267
- 0.000488486*m.x268 + 0.00109418*m.x269 + 0.00331627*m.x270 + 0.0045216*m.x271
- 0.00260415*m.x272 - 0.000565556*m.x273 + 0.00157409*m.x274 + 0.00434565*m.x275
- 0.00256408*m.x276 + 6.86355E-5*m.x277 + 0.000115271*m.x278 + 0.00407719*m.x279
- 0.000717764*m.x280 + 0.00421776*m.x281 - 0.00185436*m.x282 + 0.0139088*m.x283
+ 0.00169537*m.x284 - 0.00322776*m.x285 + 0.00738761*m.x286 - 0.00338701*m.x287
+ 0.000632136*m.x288 + 0.00125905*m.x289 + 0.00498931*m.x290 - 0.00223203*m.x291
- 0.00161161*m.x292 + 0.000698504*m.x293 + 0.000973632*m.x294 + 0.00322052*m.x295
- 0.000732426*m.x296 + 0.000574642*m.x297 + 0.0043636*m.x298 - 0.00725725*m.x299
+ 0.00589969*m.x300 + 0.00253513*m.x301 + 3.03939E-5*m.x302 + 0.0013209*m.x303 == 0)
m.c208 = Constraint(expr= - m.x103 + 0.00922513*m.x204 + 0.0975221*m.x205 + 0.0302565*m.x206 + 0.00195468*m.x207
+ 0.00763018*m.x208 + 0.0135627*m.x209 + 0.005177*m.x210 - 0.00166221*m.x211
+ 0.0123801*m.x212 + 0.00801131*m.x213 + 0.0131773*m.x214 - 0.000578789*m.x215
- 0.00121871*m.x216 + 0.00571751*m.x217 + 0.00647641*m.x218 + 0.006769*m.x219
+ 0.00782192*m.x220 + 0.00707125*m.x221 + 0.0133473*m.x222 + 0.013462*m.x223
+ 0.00112892*m.x224 + 0.0172224*m.x225 + 0.000134992*m.x226 - 0.000119948*m.x227
+ 0.000402454*m.x228 + 0.0170077*m.x229 + 0.00468054*m.x230 + 0.00168652*m.x231
+ 0.0382947*m.x232 + 0.0032777*m.x233 + 0.00298262*m.x234 + 0.00157746*m.x235
+ 0.0105061*m.x236 - 0.00233804*m.x237 - 0.000430784*m.x238 + 0.00369645*m.x239
+ 0.00893962*m.x240 + 0.00500082*m.x241 + 0.00579376*m.x242 + 0.0033232*m.x243
+ 0.00493974*m.x244 + 1.72372E-5*m.x245 - 0.00634068*m.x246 + 0.00394893*m.x247
+ 0.02189*m.x248 - 0.00142123*m.x249 + 0.000952018*m.x250 - 0.000699597*m.x251
+ 0.00166555*m.x252 + 0.00413697*m.x253 + 0.0028476*m.x254 + 0.0144721*m.x255
+ 0.00231785*m.x256 - 0.00165532*m.x257 + 0.00730008*m.x258 + 0.00370628*m.x259
+ 0.00688037*m.x260 - 0.00522018*m.x261 + 0.00111515*m.x262 + 0.00698037*m.x263
- 0.000451953*m.x264 + 0.000474809*m.x265 + 0.00265625*m.x266 - 0.00353732*m.x267
+ 0.0119217*m.x268 + 0.00462742*m.x269 + 0.00319077*m.x270 + 0.00271929*m.x271
- 0.00543312*m.x272 + 0.00196136*m.x273 + 0.00104823*m.x274 + 0.0124518*m.x275
- 0.00305148*m.x276 + 0.00752299*m.x277 + 0.00484884*m.x278 + 0.00471928*m.x279
+ 0.00180959*m.x280 - 0.00197105*m.x281 - 0.000409026*m.x282 + 0.00669345*m.x283
+ 0.00587367*m.x284 + 0.00304423*m.x285 + 0.00575059*m.x286 + 0.0022757*m.x287
+ 0.00555164*m.x288 + 0.00580589*m.x289 + 0.00361309*m.x290 + 0.00918406*m.x291
+ 0.00175607*m.x292 + 0.0017579*m.x293 - 0.00440575*m.x294 + 0.000882362*m.x295
+ 0.00390306*m.x296 - 0.00345893*m.x297 + 0.00348614*m.x298 + 0.0230969*m.x299
+ 0.00744792*m.x300 + 0.0101415*m.x301 + 0.00190622*m.x302 + 0.00972401*m.x303 == 0)
m.c209 = Constraint(expr= - m.x104 + 0.0026992*m.x204 + 0.0302565*m.x205 + 0.128438*m.x206 + 0.000554371*m.x207
+ 0.00531804*m.x208 + 0.000108892*m.x209 - 0.00393381*m.x210 + 0.00224874*m.x211
- 0.00567132*m.x212 + 0.0331219*m.x213 + 0.00309274*m.x214 + 0.00219016*m.x215
+ 0.00110325*m.x216 + 0.00750053*m.x217 + 0.0031054*m.x218 - 0.0011808*m.x219
+ 0.0018233*m.x220 - 0.00403332*m.x221 + 0.000400161*m.x222 + 0.00326599*m.x223
+ 0.00271781*m.x224 + 0.0379186*m.x225 - 0.000515796*m.x226 - 0.00228588*m.x227
- 0.00297975*m.x228 + 0.0477231*m.x229 + 0.010936*m.x230 + 0.0065182*m.x231 + 0.0358881*m.x232
+ 0.00724543*m.x233 + 0.0141802*m.x234 - 0.00235266*m.x235 + 0.0360049*m.x236
+ 0.00392202*m.x237 + 0.0042099*m.x238 + 0.00555015*m.x239 + 0.00521599*m.x240
- 0.00112076*m.x241 - 0.00218836*m.x242 - 0.000304719*m.x243 + 0.00236864*m.x244
- 0.0019383*m.x245 - 0.00295089*m.x246 - 0.00106603*m.x247 + 2.7433E-5*m.x248
- 0.00324286*m.x249 + 0.0057922*m.x250 + 0.0166603*m.x251 - 0.000651147*m.x252
+ 0.0025737*m.x253 + 0.00277017*m.x254 - 0.000313893*m.x255 - 0.00295718*m.x256
+ 0.00301212*m.x257 - 0.00536586*m.x258 + 0.00927864*m.x259 - 0.00108853*m.x260
+ 0.00791765*m.x261 - 0.00783196*m.x262 + 0.0121474*m.x263 + 0.00268288*m.x264
- 0.0040862*m.x265 + 0.00434811*m.x266 + 0.00169867*m.x267 + 0.010645*m.x268
+ 0.00861052*m.x269 + 0.00468559*m.x270 + 0.00738855*m.x271 - 0.00180418*m.x272
+ 0.00156566*m.x273 + 0.00730297*m.x274 + 0.00553899*m.x275 - 0.00796275*m.x276
+ 0.00502078*m.x277 - 0.001733*m.x278 + 0.000121446*m.x279 + 0.00524254*m.x280
- 0.000120631*m.x281 - 0.00614724*m.x282 + 0.00806025*m.x283 + 0.0109797*m.x284
+ 0.00481845*m.x285 - 0.003182*m.x286 + 0.00729708*m.x287 + 0.00314668*m.x288
+ 0.00093968*m.x289 + 0.0046813*m.x290 + 0.00588727*m.x291 + 0.00856972*m.x292
+ 0.0014989*m.x293 - 0.0012223*m.x294 - 0.00398758*m.x295 + 0.00447174*m.x296
- 0.00894175*m.x297 - 0.0106183*m.x298 + 0.0196262*m.x299 + 0.00569151*m.x300
+ 0.000408826*m.x301 + 0.0107044*m.x302 + 0.00414926*m.x303 == 0)
m.c210 = Constraint(expr= - m.x105 + 0.00246784*m.x204 + 0.00195468*m.x205 + 0.000554371*m.x206 + 0.0527346*m.x207
+ 0.00613524*m.x208 + 0.00304915*m.x209 + 0.00265026*m.x210 - 0.00168787*m.x211
+ 3.0185E-5*m.x212 + 0.00604227*m.x213 + 0.00608141*m.x214 + 0.0122199*m.x215
+ 0.00562216*m.x216 - 0.005368*m.x217 + 0.00381063*m.x218 + 0.00430191*m.x219
+ 0.0103995*m.x220 + 0.00535853*m.x221 + 0.00443352*m.x222 + 0.00287646*m.x223
+ 0.00194314*m.x224 - 0.00200937*m.x225 + 0.00721471*m.x226 + 0.00153181*m.x227
+ 0.00223523*m.x228 - 0.00637192*m.x229 - 0.00268833*m.x230 + 0.00712607*m.x231
+ 0.00579462*m.x232 + 0.00617075*m.x233 + 0.00178322*m.x234 + 0.00561978*m.x235
- 0.000789221*m.x236 + 0.000342323*m.x237 + 0.00409312*m.x238 + 0.0043798*m.x239
+ 0.00830042*m.x240 + 0.0127205*m.x241 + 0.00431059*m.x242 + 0.00271535*m.x243
+ 0.00301995*m.x244 + 0.00485894*m.x245 + 0.0039211*m.x246 + 0.00224879*m.x247
+ 0.00711934*m.x248 + 0.000965714*m.x249 + 0.00724404*m.x250 + 0.00718655*m.x251
+ 0.00872243*m.x252 + 0.00911811*m.x253 + 0.000986175*m.x254 + 0.00380874*m.x255
+ 0.00525484*m.x256 + 0.00057863*m.x257 - 0.00473576*m.x258 + 0.0100543*m.x259
+ 0.00543729*m.x260 + 0.00571189*m.x261 - 0.00276324*m.x262 + 0.00810983*m.x263
+ 0.00436906*m.x264 + 0.00413471*m.x265 - 0.00244187*m.x266 + 0.00545183*m.x267
+ 0.00495238*m.x268 + 0.00411888*m.x269 + 0.00641475*m.x270 + 0.00111178*m.x271
- 0.00121453*m.x272 + 0.00461528*m.x273 + 0.00171472*m.x274 + 0.00388579*m.x275
+ 0.00967986*m.x276 + 0.0016606*m.x277 + 0.00295113*m.x278 + 0.00353955*m.x279
+ 0.00142511*m.x280 + 0.00243873*m.x281 - 0.00105264*m.x282 + 0.00531498*m.x283
+ 0.00188864*m.x284 + 0.00359302*m.x285 + 0.00189728*m.x286 + 0.00111561*m.x287
+ 0.00562859*m.x288 + 0.00605398*m.x289 + 0.00853829*m.x290 + 0.00794939*m.x291
- 0.00108004*m.x292 + 0.00250493*m.x293 + 6.36275E-5*m.x294 + 0.00972923*m.x295
+ 0.0052055*m.x296 + 0.00106842*m.x297 + 0.00268821*m.x298 - 0.00313171*m.x299
+ 0.0047581*m.x300 - 0.00749006*m.x301 + 0.00065076*m.x302 + 0.0033893*m.x303 == 0)
m.c211 = Constraint(expr= - m.x106 + 0.00231482*m.x204 + 0.00763018*m.x205 + 0.00531804*m.x206 + 0.00613524*m.x207
+ 0.0344878*m.x208 + 0.00244207*m.x209 + 0.00307695*m.x210 + 0.000258656*m.x211
+ 0.00124365*m.x212 + 0.00669557*m.x213 + 0.000908845*m.x214 + 0.00431206*m.x215
+ 0.00836718*m.x216 + 0.00732185*m.x217 + 0.00637045*m.x218 + 0.00307733*m.x219
+ 0.00520295*m.x220 - 0.00352601*m.x221 + 0.00445198*m.x222 + 0.00166877*m.x223
+ 0.00283099*m.x224 + 0.0128329*m.x225 + 0.00506005*m.x226 + 0.00243023*m.x227
+ 0.00179608*m.x228 + 0.00210744*m.x229 + 0.00564026*m.x230 + 0.00132385*m.x231
+ 0.00265952*m.x232 + 0.0155615*m.x233 + 3.93351E-5*m.x234 + 0.00818121*m.x235
+ 0.00576868*m.x236 + 0.00589168*m.x237 + 0.00706516*m.x238 + 0.00432744*m.x239
+ 0.0048282*m.x240 + 0.00624337*m.x241 - 0.00066102*m.x242 + 0.00539504*m.x243
+ 0.0051422*m.x244 + 0.0159499*m.x245 + 0.00287456*m.x246 + 0.00538495*m.x247
+ 0.00440483*m.x248 - 0.000705455*m.x249 + 0.00591159*m.x250 + 0.00637504*m.x251
+ 0.00572145*m.x252 + 0.00369485*m.x253 + 0.00550813*m.x254 + 0.00767889*m.x255
+ 0.00218657*m.x256 + 0.00216232*m.x257 + 0.00209557*m.x258 + 0.00511289*m.x259
+ 0.00375052*m.x260 - 0.000396528*m.x261 - 0.00165313*m.x262 + 0.00186935*m.x263
+ 0.00284817*m.x264 + 0.00147042*m.x265 + 0.00264492*m.x266 - 0.000424681*m.x267
+ 0.00721645*m.x268 + 0.00584868*m.x269 - 0.00125879*m.x270 + 0.00123949*m.x271
+ 0.00134707*m.x272 + 0.00328024*m.x273 - 0.00258347*m.x274 + 0.000703909*m.x275
- 0.00197849*m.x276 + 0.00192358*m.x277 + 0.00996959*m.x278 + 0.00858445*m.x279
+ 0.00237901*m.x280 + 0.00880383*m.x281 + 0.00286914*m.x282 + 0.00026152*m.x283
+ 0.010098*m.x284 + 0.00162371*m.x285 + 0.00109136*m.x286 + 0.00784252*m.x287
+ 0.00882019*m.x288 + 0.000598062*m.x289 + 0.0052387*m.x290 + 0.00384785*m.x291
+ 0.00503042*m.x292 + 0.0024631*m.x293 + 0.00278995*m.x294 + 0.00074696*m.x295
+ 0.00338877*m.x296 - 0.000458376*m.x297 + 0.00936944*m.x298 + 0.00321093*m.x299
+ 0.00494576*m.x300 - 0.00489219*m.x301 + 0.00406797*m.x302 + 0.00689176*m.x303 == 0)
m.c212 = Constraint(expr= - m.x107 - 0.00125222*m.x204 + 0.0135627*m.x205 + 0.000108892*m.x206 + 0.00304915*m.x207
+ 0.00244207*m.x208 + 0.328857*m.x209 + 0.00193872*m.x210 + 0.00238388*m.x211
+ 0.00483704*m.x212 - 0.00180415*m.x213 + 0.00505025*m.x214 + 0.00312816*m.x215
+ 0.00975333*m.x216 + 0.00807353*m.x217 - 0.00043798*m.x218 + 0.0119386*m.x219
+ 0.00270366*m.x220 - 0.000150751*m.x221 - 0.00500595*m.x222 + 0.00148923*m.x223
- 0.00153303*m.x224 + 0.000308528*m.x225 + 0.00379536*m.x226 + 0.00253802*m.x227
+ 0.00318827*m.x228 + 0.00415587*m.x229 + 0.0068299*m.x230 + 0.00946803*m.x231
+ 0.0152758*m.x232 + 0.00176378*m.x233 + 0.0034359*m.x234 + 0.00304328*m.x235
- 0.0024897*m.x236 + 0.0154113*m.x237 + 0.00423352*m.x238 + 0.00420821*m.x239
+ 0.00164738*m.x240 + 0.00313153*m.x241 + 0.000192806*m.x242 + 0.00566827*m.x243
- 0.00114024*m.x244 + 0.0104584*m.x245 - 0.00156619*m.x246 + 0.00492319*m.x247
+ 0.00205128*m.x248 + 0.0034346*m.x249 + 0.00340814*m.x250 + 0.00910415*m.x251
+ 0.00203269*m.x252 - 0.000620515*m.x253 + 0.00733867*m.x254 - 0.00376408*m.x255
+ 0.00661222*m.x256 + 0.000748379*m.x257 - 0.000634982*m.x258 + 0.00346952*m.x259
+ 0.00833195*m.x260 - 0.00565329*m.x261 + 0.00331464*m.x262 + 0.00521247*m.x263
+ 0.00319873*m.x264 + 0.00684361*m.x265 + 0.00146666*m.x266 - 0.00449445*m.x267
+ 0.00890815*m.x268 + 0.00402867*m.x269 - 0.00123966*m.x270 + 0.00107871*m.x271
+ 0.00207255*m.x272 + 0.00348354*m.x273 + 0.00923163*m.x274 + 0.000624611*m.x275
+ 0.00416771*m.x276 - 0.00784802*m.x277 + 0.000769801*m.x278 + 0.00337936*m.x279
+ 0.00116986*m.x280 + 0.00315331*m.x281 - 0.00601197*m.x282 - 0.00277281*m.x283
+ 0.00597799*m.x284 + 0.00573361*m.x285 + 0.0187193*m.x286 + 0.00612747*m.x287
+ 0.00350368*m.x288 + 0.000722427*m.x289 - 0.00222972*m.x290 + 0.00618374*m.x291
+ 0.00230392*m.x292 - 8.26039E-6*m.x293 + 0.00470948*m.x294 + 0.00203412*m.x295
+ 0.000810064*m.x296 - 0.00836969*m.x297 + 0.000538622*m.x298 + 0.00916125*m.x299
+ 0.00409619*m.x300 + 0.0632661*m.x301 + 0.00174019*m.x302 + 0.0149843*m.x303 == 0)
m.c213 = Constraint(expr= - m.x108 - 0.00392467*m.x204 + 0.005177*m.x205 - 0.00393381*m.x206 + 0.00265026*m.x207
+ 0.00307695*m.x208 + 0.00193872*m.x209 + 0.0355431*m.x210 - 0.00186104*m.x211
+ 0.00855968*m.x212 - 0.00115433*m.x213 + 0.00384303*m.x214 + 0.000405725*m.x215
+ 0.0081813*m.x216 - 0.000678388*m.x217 + 0.00818477*m.x218 + 0.00310775*m.x219
+ 0.000744621*m.x220 + 0.00597378*m.x221 - 0.00774064*m.x222 - 0.000324177*m.x223
+ 0.00212898*m.x224 + 0.00300949*m.x225 - 0.000393934*m.x226 - 0.00283134*m.x227
+ 0.000310634*m.x228 + 0.000987645*m.x229 + 0.00360613*m.x230 + 0.0048888*m.x231
+ 0.000705294*m.x232 + 0.0033924*m.x233 - 0.00243487*m.x234 + 0.00351798*m.x235
- 0.000533129*m.x236 + 0.00286727*m.x237 - 0.002207*m.x238 + 0.00114119*m.x239
+ 0.00331*m.x240 + 0.00432021*m.x241 + 0.0068693*m.x242 + 0.00261587*m.x243
+ 0.000712154*m.x244 + 0.00243149*m.x245 + 0.00586835*m.x246 + 0.00190637*m.x247
+ 0.00522821*m.x248 + 0.000518417*m.x249 + 0.00229506*m.x250 - 0.000868046*m.x251
+ 0.00175605*m.x252 + 0.00453298*m.x253 + 0.000256242*m.x254 + 0.00201038*m.x255
+ 0.00317659*m.x256 + 0.00404808*m.x257 + 0.0020328*m.x258 + 0.0100104*m.x259
+ 0.00586558*m.x260 + 0.00391134*m.x261 - 0.00108095*m.x262 + 0.00196227*m.x263
- 0.00048119*m.x264 - 0.00264342*m.x265 - 0.000799614*m.x266 - 0.00211867*m.x267
+ 0.00596663*m.x268 - 0.000337876*m.x269 + 0.0022652*m.x270 - 0.00117815*m.x271
- 0.00408935*m.x272 + 0.000462235*m.x273 + 0.00708304*m.x274 + 0.00304047*m.x275
+ 0.0003593*m.x276 + 0.00480892*m.x277 + 0.00445062*m.x278 + 0.00319021*m.x279
+ 0.000605631*m.x280 + 0.00795997*m.x281 + 0.00396196*m.x282 + 0.00197483*m.x283
+ 0.00590748*m.x284 + 0.00820622*m.x285 + 0.00157202*m.x286 + 0.00465324*m.x287
+ 0.00187347*m.x288 + 0.000428549*m.x289 - 0.00285777*m.x290 + 0.0153027*m.x291
+ 0.00159813*m.x292 - 0.00186303*m.x293 + 0.00292004*m.x294 + 0.000158573*m.x295
+ 0.00302037*m.x296 - 0.00583942*m.x297 + 0.00166923*m.x298 + 0.00208712*m.x299
+ 0.00468842*m.x300 + 0.00124219*m.x301 + 0.00190019*m.x302 + 0.00317539*m.x303 == 0)
m.c214 = Constraint(expr= - m.x109 - 0.0046966*m.x204 - 0.00166221*m.x205 + 0.00224874*m.x206 - 0.00168787*m.x207
+ 0.000258656*m.x208 + 0.00238388*m.x209 - 0.00186104*m.x210 + 0.0741498*m.x211
+ 0.00239579*m.x212 + 0.0025154*m.x213 - 0.00304658*m.x214 + 0.00127006*m.x215
+ 0.00242253*m.x216 - 0.000582646*m.x217 + 0.000205383*m.x218 - 0.0027615*m.x219
+ 0.000708891*m.x220 - 0.000332979*m.x221 + 0.00241559*m.x222 + 0.00233211*m.x223
- 0.00133617*m.x224 + 0.00504517*m.x225 + 0.00209809*m.x226 + 0.00376046*m.x227
- 0.00258998*m.x228 + 0.0129869*m.x229 - 0.00468059*m.x230 + 0.00960732*m.x231
- 0.0084924*m.x232 - 0.00241471*m.x233 + 0.00242201*m.x234 - 0.00033287*m.x235
+ 0.00115625*m.x236 + 0.00402359*m.x237 - 0.000640147*m.x238 - 0.00221072*m.x239
+ 0.00267732*m.x240 - 0.00280484*m.x241 + 0.00478207*m.x242 - 0.00021402*m.x243
+ 0.00344966*m.x244 + 0.000269359*m.x245 - 0.00135088*m.x246 + 0.00131418*m.x247
- 0.000872693*m.x248 + 0.000448292*m.x249 - 0.00207556*m.x250 - 0.00135891*m.x251
- 0.00277333*m.x252 + 0.00257709*m.x253 + 0.00198123*m.x254 - 0.00692894*m.x255
+ 0.00230237*m.x256 + 0.00443474*m.x257 - 0.000282204*m.x258 + 0.00426487*m.x259
- 0.000987702*m.x260 + 0.00520545*m.x261 - 0.00343631*m.x262 - 0.00282907*m.x263
+ 0.00540009*m.x264 + 0.00223674*m.x265 - 0.00228832*m.x266 - 0.00507634*m.x267
+ 0.000540695*m.x268 - 0.000710481*m.x269 - 9.29613E-5*m.x270 + 0.016814*m.x271
- 0.000397583*m.x272 + 0.00336798*m.x273 - 3.62062E-5*m.x274 - 0.00115006*m.x275
+ 0.00764087*m.x276 - 0.00130017*m.x277 + 0.00809507*m.x278 + 0.012837*m.x279
+ 0.000749837*m.x280 + 0.00274401*m.x281 + 0.000351167*m.x282 + 0.00240495*m.x283
+ 0.000367094*m.x284 - 0.000642028*m.x285 - 0.0066337*m.x286 + 0.00521946*m.x287
+ 0.00597375*m.x288 - 0.000142638*m.x289 - 0.000178386*m.x290 - 0.00109134*m.x291
+ 0.00239336*m.x292 + 0.0002248*m.x293 + 0.00134415*m.x294 + 0.00625637*m.x295
+ 0.000559204*m.x296 + 0.00368139*m.x297 + 0.00134215*m.x298 + 0.000562204*m.x299
+ 0.00467534*m.x300 - 0.00175434*m.x301 + 0.000310939*m.x302 - 0.000534117*m.x303 == 0)
m.c215 = Constraint(expr= - m.x110 - 0.0142117*m.x204 + 0.0123801*m.x205 - 0.00567132*m.x206 + 3.0185E-5*m.x207
+ 0.00124365*m.x208 + 0.00483704*m.x209 + 0.00855968*m.x210 + 0.00239579*m.x211
+ 0.303885*m.x212 - 0.00881645*m.x213 + 0.000209396*m.x214 - 0.00224118*m.x215
+ 0.00100609*m.x216 + 0.00319377*m.x217 + 0.0147564*m.x218 - 0.000681104*m.x219
- 0.00225828*m.x220 + 0.00258491*m.x221 + 0.00184898*m.x222 + 0.0169417*m.x223
+ 0.0031757*m.x224 - 0.00394915*m.x225 + 0.00652373*m.x226 + 0.00207177*m.x227
+ 0.000966201*m.x228 - 0.000384643*m.x229 + 0.00501887*m.x230 + 0.0131889*m.x231
- 0.00750233*m.x232 - 0.000147186*m.x233 - 0.00131105*m.x234 - 0.00502474*m.x235
- 0.0031803*m.x236 + 0.00422327*m.x237 - 0.00434983*m.x238 + 0.00139653*m.x239
- 0.000845758*m.x240 + 0.00373613*m.x241 + 0.0140464*m.x242 + 0.000586315*m.x243
+ 0.00323884*m.x244 - 0.00103573*m.x245 + 0.0103013*m.x246 - 0.000803836*m.x247
+ 0.0174386*m.x248 + 0.00274013*m.x249 + 0.00199163*m.x250 + 0.0121972*m.x251
+ 5.78285E-5*m.x252 - 0.003034*m.x253 - 0.00256942*m.x254 + 0.00344538*m.x255
- 0.00251303*m.x256 + 0.00434833*m.x257 + 0.000197585*m.x258 - 0.00378844*m.x259
+ 0.00163113*m.x260 + 0.00153282*m.x261 + 0.00412394*m.x262 - 0.00179846*m.x263
+ 0.00477371*m.x264 + 0.00203511*m.x265 - 0.000827761*m.x266 + 0.00659553*m.x267
- 0.00174127*m.x268 + 0.00394387*m.x269 + 0.00861848*m.x270 - 0.00595897*m.x271
- 0.0094895*m.x272 + 0.00494924*m.x273 + 0.00140893*m.x274 + 0.00133383*m.x275
- 0.00225174*m.x276 + 0.0173398*m.x277 + 0.00433366*m.x278 + 0.000552636*m.x279
+ 0.0021388*m.x280 + 0.00222851*m.x281 + 0.00814529*m.x282 + 0.000337824*m.x283
- 0.00392219*m.x284 + 0.0200781*m.x285 + 0.0101854*m.x286 + 0.010518*m.x287
+ 0.00605484*m.x288 + 0.000377649*m.x289 + 0.00919154*m.x290 + 0.00637465*m.x291
+ 0.00244105*m.x292 + 0.00434059*m.x293 - 0.00461254*m.x294 + 0.00181809*m.x295
- 0.0038537*m.x296 + 0.0464725*m.x297 + 0.00125687*m.x298 + 0.0104496*m.x299
+ 0.0289754*m.x300 - 0.000502067*m.x301 + 0.00848806*m.x302 - 0.00199306*m.x303 == 0)
m.c216 = Constraint(expr= - m.x111 - 0.00150584*m.x204 + 0.00801131*m.x205 + 0.0331219*m.x206 + 0.00604227*m.x207
+ 0.00669557*m.x208 - 0.00180415*m.x209 - 0.00115433*m.x210 + 0.0025154*m.x211
- 0.00881645*m.x212 + 0.106851*m.x213 + 0.00186361*m.x214 - 0.00174797*m.x215
- 0.000949809*m.x216 - 0.00294584*m.x217 - 0.000264229*m.x218 - 0.00104889*m.x219
+ 0.00197181*m.x220 + 0.00967216*m.x221 - 0.00497782*m.x222 - 0.0015228*m.x223
+ 0.00340534*m.x224 + 0.0459321*m.x225 + 0.00841049*m.x226 - 0.00536028*m.x227
+ 0.00303875*m.x228 + 0.0222634*m.x229 + 0.00147836*m.x230 + 0.000467993*m.x231
+ 0.00769452*m.x232 + 0.00544112*m.x233 - 0.00240926*m.x234 + 0.00822957*m.x235
+ 0.0404735*m.x236 + 0.00290678*m.x237 + 0.00783851*m.x238 + 0.00157388*m.x239
+ 0.00239796*m.x240 + 0.00048455*m.x241 - 0.00531909*m.x242 - 0.000873781*m.x243
+ 0.00339704*m.x244 + 0.00996659*m.x245 - 0.000797116*m.x246 + 0.000489977*m.x247
+ 0.00793697*m.x248 - 0.00236638*m.x249 + 0.00351492*m.x250 + 0.0269972*m.x251
+ 0.0035179*m.x252 + 0.00199006*m.x253 + 0.00140166*m.x254 - 0.00266851*m.x255
+ 6.78972E-5*m.x256 + 0.000714092*m.x257 + 0.00214786*m.x258 + 0.00560907*m.x259
- 0.000690724*m.x260 + 0.0101136*m.x261 + 0.00176469*m.x262 + 0.0157962*m.x263
+ 0.00685899*m.x264 + 0.00149984*m.x265 + 0.00129678*m.x266 - 0.00152672*m.x267
+ 0.0108934*m.x268 + 0.000425159*m.x269 + 0.000218677*m.x270 + 0.00258553*m.x271
+ 0.000326023*m.x272 + 0.000152555*m.x273 + 0.000755605*m.x274 + 0.00527875*m.x275
- 0.00463861*m.x276 + 0.00182445*m.x277 + 0.000102258*m.x278 + 0.00269352*m.x279
+ 0.00164556*m.x280 + 0.00504609*m.x281 - 0.0025043*m.x282 + 0.00627615*m.x283
+ 0.00371545*m.x284 + 0.00330175*m.x285 + 0.00434643*m.x286 + 0.00899061*m.x287
+ 0.00419388*m.x288 + 0.00126509*m.x289 - 5.10678E-6*m.x290 - 0.00500706*m.x291
+ 0.00495567*m.x292 - 0.00234243*m.x293 - 0.00102392*m.x294 + 0.000187615*m.x295
+ 0.00745742*m.x296 - 0.00228448*m.x297 - 0.000338838*m.x298 + 0.00375325*m.x299
+ 0.00589763*m.x300 + 0.00111933*m.x301 + 0.000509737*m.x302 + 0.00161055*m.x303 == 0)
m.c217 = Constraint(expr= - m.x112 - 0.00472481*m.x204 + 0.0131773*m.x205 + 0.00309274*m.x206 + 0.00608141*m.x207
+ 0.000908845*m.x208 + 0.00505025*m.x209 + 0.00384303*m.x210 - 0.00304658*m.x211
+ 0.000209396*m.x212 + 0.00186361*m.x213 + 0.0569102*m.x214 + 0.00609405*m.x215
+ 0.000507867*m.x216 + 0.00384693*m.x217 + 0.00988926*m.x218 + 0.00181921*m.x219
+ 0.00262843*m.x220 + 0.0148015*m.x221 - 0.00139604*m.x222 - 0.00175854*m.x223
- 6.07859E-5*m.x224 - 0.00138077*m.x225 + 0.00334125*m.x226 + 0.000987108*m.x227
+ 0.00525686*m.x228 + 0.00768851*m.x229 + 0.000743528*m.x230 + 0.00323042*m.x231
+ 0.00830891*m.x232 + 0.00460225*m.x233 + 0.00347085*m.x234 + 0.0125956*m.x235
- 0.00124658*m.x236 + 0.0109431*m.x237 + 0.00410401*m.x238 + 0.00255437*m.x239
+ 0.00542448*m.x240 + 0.00676388*m.x241 + 0.00233527*m.x242 + 0.00504678*m.x243
+ 0.00322689*m.x244 + 0.00189672*m.x245 + 0.00650083*m.x246 - 0.00223977*m.x247
- 0.00874611*m.x248 - 0.00176148*m.x249 + 0.00162467*m.x250 + 0.00683673*m.x251
+ 0.000473999*m.x252 + 0.00469908*m.x253 + 0.00361612*m.x254 + 0.0154276*m.x255
+ 0.000184285*m.x256 + 0.00199166*m.x257 + 0.00473067*m.x258 + 0.00558883*m.x259
+ 0.0104591*m.x260 + 0.00117382*m.x261 + 0.000451696*m.x262 + 0.00029335*m.x263
+ 0.00554255*m.x264 + 0.00203335*m.x265 + 0.00806469*m.x266 + 0.00317218*m.x267
+ 0.00207678*m.x268 - 0.00182631*m.x269 + 0.00122714*m.x270 + 0.00268003*m.x271
+ 0.0075118*m.x272 + 0.00178843*m.x273 + 0.00419246*m.x274 + 0.0134485*m.x275
+ 0.000185964*m.x276 + 0.00708873*m.x277 + 0.00400977*m.x278 - 0.00213811*m.x279
+ 0.000162794*m.x280 + 0.000164067*m.x281 + 0.00227186*m.x282 + 0.00094864*m.x283
- 0.00147339*m.x284 + 0.00528313*m.x285 + 0.0088821*m.x286 + 0.00267439*m.x287
+ 0.00393964*m.x288 + 0.00396771*m.x289 + 0.00290804*m.x290 + 0.00291132*m.x291
+ 0.00247734*m.x292 + 2.81248E-5*m.x293 + 0.000966712*m.x294 + 0.00204921*m.x295
+ 0.00925901*m.x296 - 0.00307712*m.x297 - 0.00248219*m.x298 + 0.010692*m.x299
- 0.00209988*m.x300 - 0.00513244*m.x301 - 0.00106151*m.x302 + 0.00607889*m.x303 == 0)
m.c218 = Constraint(expr= - m.x113 - 0.00116843*m.x204 - 0.000578789*m.x205 + 0.00219016*m.x206 + 0.0122199*m.x207
+ 0.00431206*m.x208 + 0.00312816*m.x209 + 0.000405725*m.x210 + 0.00127006*m.x211
- 0.00224118*m.x212 - 0.00174797*m.x213 + 0.00609405*m.x214 + 0.0723609*m.x215
+ 0.00478971*m.x216 + 0.00284727*m.x217 + 0.00397902*m.x218 - 0.00379281*m.x219
+ 0.0031427*m.x220 + 0.00865827*m.x221 - 0.00360555*m.x222 + 0.00698081*m.x223
+ 0.00165301*m.x224 - 0.0093405*m.x225 - 0.000831286*m.x226 - 0.00224216*m.x227
+ 0.0088837*m.x228 - 0.00558582*m.x229 - 0.000431237*m.x230 + 0.00302183*m.x231
- 0.00219082*m.x232 + 0.00318353*m.x233 + 0.00523947*m.x234 + 0.00300376*m.x235
- 0.00393984*m.x236 + 0.00148726*m.x237 - 0.000225512*m.x238 + 0.00296695*m.x239
+ 0.00567021*m.x240 + 0.00427603*m.x241 + 0.00843837*m.x242 + 0.00429264*m.x243
- 0.00287625*m.x244 + 0.00281472*m.x245 + 0.00128983*m.x246 + 0.0031567*m.x247
- 0.00283528*m.x248 + 0.00355332*m.x249 + 0.00303711*m.x250 + 0.00993462*m.x251
+ 0.00342858*m.x252 + 0.00462163*m.x253 + 0.000325927*m.x254 + 0.00380006*m.x255
+ 0.0148337*m.x256 + 0.00117377*m.x257 - 0.00687953*m.x258 + 0.00217715*m.x259
+ 0.00358463*m.x260 + 0.0045967*m.x261 - 0.00148924*m.x262 + 0.00257797*m.x263
+ 0.00238489*m.x264 - 0.000481693*m.x265 + 0.0009138*m.x266 - 0.00429905*m.x267
- 0.00296047*m.x268 + 0.00202854*m.x269 - 0.000579525*m.x270 + 0.00537311*m.x271
+ 0.0135494*m.x272 - 0.00091213*m.x273 + 0.00552551*m.x274 + 0.00176871*m.x275
+ 0.00949781*m.x276 + 0.00315281*m.x277 + 0.000656197*m.x278 + 0.00384708*m.x279
+ 0.000917677*m.x280 + 0.00436823*m.x281 + 0.00309677*m.x282 - 0.00314082*m.x283
- 0.00237874*m.x284 + 0.00652441*m.x285 + 0.00159051*m.x286 + 0.00062359*m.x287
+ 0.000537233*m.x288 - 9.36397E-5*m.x289 + 0.000546637*m.x290 + 0.000119304*m.x291
- 0.00155886*m.x292 - 0.00294322*m.x293 - 0.000986956*m.x294 + 0.0040052*m.x295
+ 0.00261969*m.x296 - 0.00299439*m.x297 + 0.0127287*m.x298 + 0.000449299*m.x299
- 0.00213457*m.x300 - 0.0016146*m.x301 - 0.00369472*m.x302 + 0.00287968*m.x303 == 0)
m.c219 = Constraint(expr= - m.x114 - 0.00080131*m.x204 - 0.00121871*m.x205 + 0.00110325*m.x206 + 0.00562216*m.x207
+ 0.00836718*m.x208 + 0.00975333*m.x209 + 0.0081813*m.x210 + 0.00242253*m.x211
+ 0.00100609*m.x212 - 0.000949809*m.x213 + 0.000507867*m.x214 + 0.00478971*m.x215
+ 0.0576035*m.x216 + 0.00187629*m.x217 + 0.000921665*m.x218 + 0.0038003*m.x219
+ 0.00467709*m.x220 + 0.00750521*m.x221 + 0.00326373*m.x222 + 0.00474518*m.x223
+ 0.0023273*m.x224 + 0.00232554*m.x225 - 0.000605176*m.x226 + 0.000459999*m.x227
+ 0.00354005*m.x228 + 0.000832659*m.x229 + 0.00241026*m.x230 + 0.00677493*m.x231
- 0.0043282*m.x232 + 0.00853448*m.x233 + 0.00304723*m.x234 + 0.00491152*m.x235
- 0.00788435*m.x236 - 0.00162346*m.x237 - 0.00143462*m.x238 + 0.00392967*m.x239
+ 0.000510251*m.x240 + 0.00735682*m.x241 - 1.91274E-5*m.x242 + 0.00401842*m.x243
+ 0.00871044*m.x244 + 0.00642735*m.x245 + 0.000216218*m.x246 + 0.00432057*m.x247
+ 0.012225*m.x248 + 0.00282004*m.x249 + 0.0010868*m.x250 + 0.00141579*m.x251
+ 0.00220267*m.x252 + 0.00354208*m.x253 + 0.00742831*m.x254 + 0.00170043*m.x255
+ 0.00440633*m.x256 + 0.0235152*m.x257 - 0.000939116*m.x258 + 0.00368368*m.x259
+ 0.00545833*m.x260 + 0.0122466*m.x261 - 0.0045062*m.x262 + 0.0102645*m.x263
+ 0.00887716*m.x264 + 0.00691443*m.x265 + 0.00137818*m.x266 - 0.000777149*m.x267
+ 0.00138796*m.x268 - 0.000964469*m.x269 + 0.00270163*m.x270 + 0.0102894*m.x271
- 0.000391351*m.x272 + 0.00613597*m.x273 + 0.00606486*m.x274 + 0.00844082*m.x275
+ 0.00591694*m.x276 + 0.00350723*m.x277 + 0.00814361*m.x278 + 0.0112582*m.x279
- 0.001004*m.x280 + 0.0283095*m.x281 - 0.00136311*m.x282 - 0.00169506*m.x283
- 0.00256875*m.x284 + 0.0112133*m.x285 + 0.012204*m.x286 + 0.000692709*m.x287
+ 0.00231345*m.x288 + 0.00276166*m.x289 + 0.00225276*m.x290 + 0.00887897*m.x291
+ 0.00177462*m.x292 + 0.000872704*m.x293 + 0.0042304*m.x294 + 0.00665568*m.x295
+ 0.00556431*m.x296 - 0.00171402*m.x297 + 0.00830996*m.x298 + 0.00411981*m.x299
+ 0.00605045*m.x300 + 0.00185019*m.x301 + 0.000924558*m.x302 + 0.00169926*m.x303 == 0)
m.c220 = Constraint(expr= - m.x115 + 0.0048818*m.x204 + 0.00571751*m.x205 + 0.00750053*m.x206 - 0.005368*m.x207
+ 0.00732185*m.x208 + 0.00807353*m.x209 - 0.000678388*m.x210 - 0.000582646*m.x211
+ 0.00319377*m.x212 - 0.00294584*m.x213 + 0.00384693*m.x214 + 0.00284727*m.x215
+ 0.00187629*m.x216 + 0.0904371*m.x217 + 0.0125994*m.x218 + 0.00507562*m.x219
+ 0.00629955*m.x220 + 0.00728095*m.x221 + 0.0135368*m.x222 - 0.00195276*m.x223
- 0.00304991*m.x224 + 0.015095*m.x225 + 0.00205086*m.x226 + 0.0105187*m.x227
+ 0.0017092*m.x228 + 0.00728394*m.x229 + 0.00738888*m.x230 + 0.00373072*m.x231
- 0.00200641*m.x232 + 0.00380207*m.x233 + 0.00154953*m.x234 + 7.83409E-5*m.x235
+ 0.00350834*m.x236 + 0.00377252*m.x237 + 0.0162195*m.x238 + 0.00354522*m.x239
+ 0.0091783*m.x240 + 0.00426163*m.x241 + 0.00463458*m.x242 + 0.00908995*m.x243
+ 0.0117519*m.x244 + 0.00671356*m.x245 + 0.00521873*m.x246 - 0.000963126*m.x247
+ 0.0115852*m.x248 + 0.00378529*m.x249 + 0.00266115*m.x250 + 0.0140797*m.x251
+ 0.00578554*m.x252 + 0.00521587*m.x253 + 0.00590839*m.x254 + 0.00535654*m.x255
- 0.00175238*m.x256 + 0.0118357*m.x257 - 0.00574135*m.x258 + 0.00238201*m.x259
+ 0.00580515*m.x260 + 0.00233877*m.x261 + 0.000706233*m.x262 - 0.0039908*m.x263
+ 0.00583571*m.x264 + 0.00378434*m.x265 + 0.00219548*m.x266 - 0.00478566*m.x267
+ 0.0059852*m.x268 + 0.00197755*m.x269 + 0.000399331*m.x270 + 0.00684901*m.x271
+ 0.00252489*m.x272 + 0.00629022*m.x273 + 0.00202437*m.x274 + 0.00360247*m.x275
+ 0.00776175*m.x276 + 0.00312055*m.x277 + 0.00869015*m.x278 + 0.0036686*m.x279
+ 0.00118524*m.x280 + 0.0108841*m.x281 - 0.00602015*m.x282 + 0.00971903*m.x283
+ 0.00813772*m.x284 - 0.00255056*m.x285 + 0.0141748*m.x286 + 0.00697572*m.x287
- 0.000459789*m.x288 + 0.00681506*m.x289 + 0.000426248*m.x290 + 0.00883306*m.x291
- 0.00113*m.x292 + 0.00170265*m.x293 + 0.00495909*m.x294 + 0.00711981*m.x295
+ 0.00524342*m.x296 - 0.00676607*m.x297 + 0.0151857*m.x298 + 0.0121187*m.x299 + 0.00858*m.x300
+ 0.00987312*m.x301 + 0.000447536*m.x302 + 0.00177245*m.x303 == 0)
m.c221 = Constraint(expr= - m.x116 - 0.00479483*m.x204 + 0.00647641*m.x205 + 0.0031054*m.x206 + 0.00381063*m.x207
+ 0.00637045*m.x208 - 0.00043798*m.x209 + 0.00818477*m.x210 + 0.000205383*m.x211
+ 0.0147564*m.x212 - 0.000264229*m.x213 + 0.00988926*m.x214 + 0.00397902*m.x215
+ 0.000921665*m.x216 + 0.0125994*m.x217 + 0.0562668*m.x218 + 0.00557422*m.x219
+ 0.00916029*m.x220 + 0.000304997*m.x221 + 2.39703E-5*m.x222 - 0.000487986*m.x223
+ 0.00306879*m.x224 + 0.00656162*m.x225 + 4.629E-5*m.x226 - 0.00368649*m.x227
+ 0.00400982*m.x228 + 0.00869348*m.x229 + 0.00253402*m.x230 - 0.000309521*m.x231
+ 0.00380195*m.x232 + 0.00965526*m.x233 + 0.000998466*m.x234 + 0.00537877*m.x235
+ 0.00531506*m.x236 - 0.000807326*m.x237 + 0.00322637*m.x238 + 0.00624206*m.x239
+ 0.01146*m.x240 + 0.00677387*m.x241 + 0.00202426*m.x242 + 0.0050502*m.x243
+ 0.00960388*m.x244 + 0.00401854*m.x245 + 0.00364998*m.x246 + 0.00338155*m.x247
+ 0.0027102*m.x248 + 0.00285381*m.x249 + 0.00231984*m.x250 + 0.00363014*m.x251
+ 0.00842352*m.x252 + 0.00670307*m.x253 + 0.00139386*m.x254 - 0.00427335*m.x255
+ 0.00257792*m.x256 + 0.00556967*m.x257 + 0.00318181*m.x258 + 0.00773217*m.x259
+ 0.00457572*m.x260 + 0.00300847*m.x261 - 0.000803621*m.x262 - 0.00429132*m.x263
+ 0.00714866*m.x264 + 0.0120675*m.x265 + 0.00202404*m.x266 - 0.00587325*m.x267
+ 0.00694813*m.x268 + 0.00377359*m.x269 + 0.00180051*m.x270 + 0.00937097*m.x271
+ 0.00359699*m.x272 + 0.0014386*m.x273 + 0.00529025*m.x274 + 0.00208614*m.x275
+ 0.00421559*m.x276 + 0.00532908*m.x277 + 0.00298937*m.x278 + 0.00264656*m.x279
+ 0.00679774*m.x280 + 0.00864262*m.x281 + 0.000288227*m.x282 + 0.00677297*m.x283
+ 0.000330943*m.x284 + 0.00658359*m.x285 + 0.0029954*m.x286 + 0.00409136*m.x287
+ 0.00355076*m.x288 + 0.00265398*m.x289 + 0.00263496*m.x290 + 0.00340833*m.x291
+ 0.00444299*m.x292 + 0.0067512*m.x293 + 0.00225846*m.x294 + 0.00175025*m.x295
+ 0.00823308*m.x296 - 0.00407677*m.x297 + 0.00929486*m.x298 + 0.00454276*m.x299
- 0.00165032*m.x300 - 0.00211125*m.x301 + 0.0019068*m.x302 + 0.00125766*m.x303 == 0)
m.c222 = Constraint(expr= - m.x117 + 0.00726609*m.x204 + 0.006769*m.x205 - 0.0011808*m.x206 + 0.00430191*m.x207
+ 0.00307733*m.x208 + 0.0119386*m.x209 + 0.00310775*m.x210 - 0.0027615*m.x211
- 0.000681104*m.x212 - 0.00104889*m.x213 + 0.00181921*m.x214 - 0.00379281*m.x215
+ 0.0038003*m.x216 + 0.00507562*m.x217 + 0.00557422*m.x218 + 0.0277262*m.x219
+ 0.00453811*m.x220 + 0.00180081*m.x221 + 0.000912203*m.x222 - 0.000232388*m.x223
- 0.000354441*m.x224 + 0.00326988*m.x225 + 0.00418825*m.x226 + 0.00230284*m.x227
+ 0.00127379*m.x228 + 0.000736619*m.x229 + 0.00149022*m.x230 + 0.00242247*m.x231
+ 0.00604515*m.x232 + 0.00652264*m.x233 - 0.00341015*m.x234 + 0.00247212*m.x235
+ 0.00108611*m.x236 + 0.00269604*m.x237 + 0.00154541*m.x238 + 0.000676983*m.x239
+ 0.00245648*m.x240 + 0.0067893*m.x241 + 0.00379181*m.x242 + 0.00278355*m.x243
+ 0.00683784*m.x244 + 0.0019748*m.x245 + 0.00480092*m.x246 + 0.00282204*m.x247
+ 0.00606924*m.x248 + 0.0066067*m.x249 + 0.00683528*m.x250 + 0.000969236*m.x251
+ 0.00589067*m.x252 + 0.0039247*m.x253 + 0.0022817*m.x254 - 0.00171385*m.x255
+ 0.00197531*m.x256 + 0.00432474*m.x257 + 0.000289832*m.x258 + 0.000627748*m.x259
+ 0.00188754*m.x260 + 0.0083923*m.x261 - 8.3506E-5*m.x262 - 0.00071125*m.x263
+ 0.00495966*m.x264 + 0.00900098*m.x265 + 0.0071845*m.x266 + 0.000145803*m.x267
+ 0.00157234*m.x268 + 0.00208948*m.x269 + 0.0030484*m.x270 + 0.00227052*m.x271
+ 0.00420122*m.x272 + 0.00590657*m.x273 + 0.00514824*m.x274 + 0.00360809*m.x275
+ 0.000388988*m.x276 + 0.00566117*m.x277 + 0.00613568*m.x278 + 0.00230286*m.x279
+ 0.00270915*m.x280 + 0.00649316*m.x281 + 0.0020842*m.x282 + 0.00256288*m.x283
+ 0.00240084*m.x284 + 0.00108106*m.x285 + 0.00593105*m.x286 + 0.00633478*m.x287
+ 0.00470412*m.x288 + 0.0036723*m.x289 + 0.00419729*m.x290 + 0.00371118*m.x291
+ 0.000251759*m.x292 + 0.00531186*m.x293 + 0.00468134*m.x294 + 0.00142927*m.x295
+ 0.00450063*m.x296 - 0.00308935*m.x297 + 0.000400969*m.x298 + 0.0016857*m.x299
- 0.000503363*m.x300 + 0.000255561*m.x301 + 0.00297631*m.x302 + 0.000851058*m.x303 == 0)
m.c223 = Constraint(expr= - m.x118 + 0.00902802*m.x204 + 0.00782192*m.x205 + 0.0018233*m.x206 + 0.0103995*m.x207
+ 0.00520295*m.x208 + 0.00270366*m.x209 + 0.000744621*m.x210 + 0.000708891*m.x211
- 0.00225828*m.x212 + 0.00197181*m.x213 + 0.00262843*m.x214 + 0.0031427*m.x215
+ 0.00467709*m.x216 + 0.00629955*m.x217 + 0.00916029*m.x218 + 0.00453811*m.x219
+ 0.0549413*m.x220 + 0.00396892*m.x221 + 0.0061511*m.x222 + 0.0065943*m.x223
+ 0.00127012*m.x224 + 0.00424617*m.x225 + 0.00582089*m.x226 + 0.00298198*m.x227
+ 0.00383534*m.x228 + 0.00438562*m.x229 - 0.00389494*m.x230 - 0.00288026*m.x231
+ 0.00241344*m.x232 + 0.00199923*m.x233 - 0.0069523*m.x234 + 0.00218093*m.x235
+ 0.00785569*m.x236 + 0.00680418*m.x237 + 0.00351389*m.x238 + 0.00697412*m.x239
+ 0.00770413*m.x240 + 0.00302394*m.x241 + 0.00226701*m.x242 - 0.00141664*m.x243
+ 0.0117404*m.x244 + 0.00452128*m.x245 + 0.00358318*m.x246 + 0.00160858*m.x247
+ 0.00917394*m.x248 + 0.0035766*m.x249 + 0.00328833*m.x250 + 0.00340781*m.x251
+ 0.00725086*m.x252 + 0.00486144*m.x253 + 0.0037492*m.x254 + 0.00232852*m.x255
+ 0.00597841*m.x256 + 0.00987396*m.x257 + 0.00154537*m.x258 + 0.000407484*m.x259
+ 0.00757036*m.x260 + 0.00514005*m.x261 - 0.00145659*m.x262 - 0.00148186*m.x263
+ 0.00497362*m.x264 + 0.00401966*m.x265 + 0.00262695*m.x266 - 0.00141986*m.x267
+ 0.00376038*m.x268 + 0.00356601*m.x269 + 0.00737614*m.x270 + 0.00551084*m.x271
+ 0.0024023*m.x272 + 0.00990879*m.x273 + 0.00256553*m.x274 + 0.00357857*m.x275
+ 0.000899423*m.x276 + 0.00477605*m.x277 + 0.00603965*m.x278 - 0.00288781*m.x279
- 0.000219471*m.x280 + 0.00864189*m.x281 + 0.00732999*m.x282 + 0.00605617*m.x283
- 0.000467489*m.x284 + 0.00375754*m.x285 + 0.00515253*m.x286 + 0.00209517*m.x287
+ 0.00294012*m.x288 + 0.00822675*m.x289 + 0.00373459*m.x290 + 0.0030272*m.x291
+ 0.00252714*m.x292 + 0.00343189*m.x293 + 0.00558036*m.x294 + 0.00282494*m.x295
+ 0.00822193*m.x296 - 0.0026527*m.x297 + 0.00739356*m.x298 + 0.00353478*m.x299
+ 0.00736597*m.x300 - 0.00264635*m.x301 + 0.00202109*m.x302 + 3.15874E-5*m.x303 == 0)
m.c224 = Constraint(expr= - m.x119 + 0.0114247*m.x204 + 0.00707125*m.x205 - 0.00403332*m.x206 + 0.00535853*m.x207
- 0.00352601*m.x208 - 0.000150751*m.x209 + 0.00597378*m.x210 - 0.000332979*m.x211
+ 0.00258491*m.x212 + 0.00967216*m.x213 + 0.0148015*m.x214 + 0.00865827*m.x215
+ 0.00750521*m.x216 + 0.00728095*m.x217 + 0.000304997*m.x218 + 0.00180081*m.x219
+ 0.00396892*m.x220 + 0.133255*m.x221 - 0.00144092*m.x222 + 0.00535246*m.x223
- 0.0025518*m.x224 + 0.000945245*m.x225 + 0.00604507*m.x226 - 7.69773E-5*m.x227
+ 0.0123754*m.x228 - 0.00512292*m.x229 + 0.0017955*m.x230 - 0.00492288*m.x231
+ 0.00107204*m.x232 - 0.00229718*m.x233 + 6.89241E-5*m.x234 + 0.00358549*m.x235
- 0.00049534*m.x236 + 0.00484482*m.x237 + 0.00543851*m.x238 - 0.00363013*m.x239
+ 0.00976994*m.x240 + 0.011369*m.x241 - 0.00581329*m.x242 + 0.00404015*m.x243
+ 0.00827466*m.x244 + 0.0016263*m.x245 - 0.00553215*m.x246 + 0.00219745*m.x247
+ 0.0156491*m.x248 + 0.00559342*m.x249 + 0.000136349*m.x250 + 0.0130438*m.x251
+ 0.00351709*m.x252 + 0.00107063*m.x253 - 0.00237286*m.x254 + 0.0053206*m.x255
- 0.000402279*m.x256 + 0.00364206*m.x257 - 0.00408056*m.x258 + 0.0110762*m.x259
+ 0.00162771*m.x260 + 0.000383935*m.x261 + 0.00454443*m.x262 - 0.00276585*m.x263
- 0.00697647*m.x264 - 0.00153885*m.x265 + 0.00688652*m.x266 - 0.00817883*m.x267
- 0.000294619*m.x268 - 0.000858525*m.x269 + 0.00730014*m.x270 - 0.000185895*m.x271
+ 0.00897574*m.x272 + 0.0166501*m.x273 + 0.0413935*m.x274 + 0.00519486*m.x275
- 0.00390506*m.x276 + 0.00335963*m.x277 - 0.000907451*m.x278 + 0.0158614*m.x279
+ 0.000758788*m.x280 + 0.00609675*m.x281 - 0.00295186*m.x282 + 0.00938947*m.x283
- 0.00281231*m.x284 + 0.00406283*m.x285 + 0.000356947*m.x286 - 0.00704698*m.x287
+ 0.00116945*m.x288 + 0.00506331*m.x289 + 0.00116521*m.x290 + 0.00400767*m.x291
- 0.00210903*m.x292 - 0.00100077*m.x293 - 0.00232507*m.x294 + 0.0032323*m.x295
+ 0.00578248*m.x296 + 0.0134996*m.x297 + 9.34767E-5*m.x298 + 0.0123006*m.x299
+ 0.000507185*m.x300 - 0.00357673*m.x301 + 0.000218257*m.x302 + 0.00591064*m.x303 == 0)
m.c225 = Constraint(expr= - m.x120 - 0.00483357*m.x204 + 0.0133473*m.x205 + 0.000400161*m.x206 + 0.00443352*m.x207
+ 0.00445198*m.x208 - 0.00500595*m.x209 - 0.00774064*m.x210 + 0.00241559*m.x211
+ 0.00184898*m.x212 - 0.00497782*m.x213 - 0.00139604*m.x214 - 0.00360555*m.x215
+ 0.00326373*m.x216 + 0.0135368*m.x217 + 2.39703E-5*m.x218 + 0.000912203*m.x219
+ 0.0061511*m.x220 - 0.00144092*m.x221 + 0.383529*m.x222 - 0.00173305*m.x223
+ 0.00142618*m.x224 + 0.00348738*m.x225 - 0.00147046*m.x226 + 0.0226173*m.x227
+ 0.0121254*m.x228 - 0.00558535*m.x229 + 0.00376971*m.x230 + 0.00496685*m.x231
+ 0.00441973*m.x232 + 0.0069161*m.x233 - 0.00118855*m.x234 + 0.00842854*m.x235
- 0.00512765*m.x236 + 0.000931212*m.x237 - 0.00452187*m.x238 + 0.00223296*m.x239
+ 0.000265224*m.x240 + 0.00539435*m.x241 + 0.00247662*m.x242 + 0.00595035*m.x243
+ 0.00389459*m.x244 + 0.00755471*m.x245 - 0.00116895*m.x246 + 0.00510849*m.x247
+ 0.0187115*m.x248 + 0.000813106*m.x249 + 0.0030329*m.x250 + 0.0177681*m.x251
+ 0.0056051*m.x252 - 0.0012575*m.x253 + 0.000154419*m.x254 - 0.00245765*m.x255
- 0.00827052*m.x256 + 0.00821977*m.x257 + 0.00502581*m.x258 + 0.0006738*m.x259
+ 0.00519536*m.x260 - 0.00068674*m.x261 - 0.00422415*m.x262 - 0.000614559*m.x263
- 0.00228625*m.x264 - 0.00518938*m.x265 - 0.0102024*m.x266 - 0.00485647*m.x267
+ 0.0127494*m.x268 + 0.00827695*m.x269 - 0.000575534*m.x270 + 0.00350023*m.x271
- 0.00265872*m.x272 + 0.00164814*m.x273 - 0.00157821*m.x274 + 0.0186797*m.x275
+ 0.00255652*m.x276 - 0.00224843*m.x277 + 0.00495422*m.x278 + 0.00648139*m.x279
+ 0.00210436*m.x280 - 0.000701372*m.x281 - 0.00282066*m.x282 - 0.0064102*m.x283
+ 0.00786204*m.x284 - 0.00449328*m.x285 - 0.00342739*m.x286 + 0.00290604*m.x287
+ 0.00297731*m.x288 + 0.00329549*m.x289 + 0.000545613*m.x290 + 0.0142805*m.x291
+ 0.00236164*m.x292 - 0.0011576*m.x293 - 0.000911744*m.x294 + 0.00290814*m.x295
- 0.00154701*m.x296 + 0.000899911*m.x297 + 0.0024395*m.x298 + 0.00327313*m.x299
+ 0.00413577*m.x300 - 0.00665285*m.x301 + 0.000253484*m.x302 - 0.00179775*m.x303 == 0)
m.c226 = Constraint(expr= - m.x121 + 9.94895E-5*m.x204 + 0.013462*m.x205 + 0.00326599*m.x206 + 0.00287646*m.x207
+ 0.00166877*m.x208 + 0.00148923*m.x209 - 0.000324177*m.x210 + 0.00233211*m.x211
+ 0.0169417*m.x212 - 0.0015228*m.x213 - 0.00175854*m.x214 + 0.00698081*m.x215
+ 0.00474518*m.x216 - 0.00195276*m.x217 - 0.000487986*m.x218 - 0.000232388*m.x219
+ 0.0065943*m.x220 + 0.00535246*m.x221 - 0.00173305*m.x222 + 0.130534*m.x223
+ 0.00596734*m.x224 + 0.00478458*m.x225 + 0.00310698*m.x226 + 0.00276388*m.x227
- 0.000128603*m.x228 + 0.00342157*m.x229 + 0.00025621*m.x230 + 0.00366426*m.x231
+ 0.00765642*m.x232 + 0.00561328*m.x233 - 0.00310918*m.x234 + 0.000436137*m.x235
+ 0.00626525*m.x236 + 0.00296798*m.x237 - 0.0019476*m.x238 + 0.00329745*m.x239
- 0.00473803*m.x240 + 0.00102553*m.x241 + 0.0109513*m.x242 + 0.00258678*m.x243
+ 0.00290544*m.x244 + 0.00906206*m.x245 - 0.00365224*m.x246 + 0.00129769*m.x247
+ 0.0109855*m.x248 - 2.44696E-5*m.x249 - 0.00162389*m.x250 + 0.00351454*m.x251
- 0.00101164*m.x252 + 0.00584599*m.x253 + 0.00280841*m.x254 + 0.0134036*m.x255
- 0.00167752*m.x256 - 0.00494624*m.x257 + 0.00359045*m.x258 - 0.00517133*m.x259
+ 0.00599997*m.x260 + 0.000340114*m.x261 - 0.00454905*m.x262 + 0.00626921*m.x263
+ 0.00325028*m.x264 + 0.00638179*m.x265 + 0.00539482*m.x266 - 0.0049754*m.x267
- 0.00136747*m.x268 + 0.00126881*m.x269 + 0.00353355*m.x270 - 0.00138502*m.x271
- 0.00188528*m.x272 + 0.00323891*m.x273 + 0.00954413*m.x274 + 0.00474038*m.x275
+ 0.00149818*m.x276 + 0.00924254*m.x277 + 0.00616055*m.x278 + 0.000177828*m.x279
- 0.000528732*m.x280 - 0.00297681*m.x281 - 0.0030116*m.x282 - 0.00201799*m.x283
- 0.00259834*m.x284 + 2.88534E-5*m.x285 + 0.00535464*m.x286 + 0.00270192*m.x287
+ 0.000175467*m.x288 + 0.00337965*m.x289 + 0.00140219*m.x290 + 0.00504492*m.x291
- 0.00136526*m.x292 - 0.00162571*m.x293 - 7.79346E-6*m.x294 + 0.00628695*m.x295
- 0.000897559*m.x296 + 0.00605286*m.x297 - 0.000995666*m.x298 - 0.000170077*m.x299
+ 0.000927962*m.x300 + 0.00910382*m.x301 + 0.00213483*m.x302 + 0.00406122*m.x303 == 0)
m.c227 = Constraint(expr= - m.x122 + 0.00286308*m.x204 + 0.00112892*m.x205 + 0.00271781*m.x206 + 0.00194314*m.x207
+ 0.00283099*m.x208 - 0.00153303*m.x209 + 0.00212898*m.x210 - 0.00133617*m.x211
+ 0.0031757*m.x212 + 0.00340534*m.x213 - 6.07859E-5*m.x214 + 0.00165301*m.x215
+ 0.0023273*m.x216 - 0.00304991*m.x217 + 0.00306879*m.x218 - 0.000354441*m.x219
+ 0.00127012*m.x220 - 0.0025518*m.x221 + 0.00142618*m.x222 + 0.00596734*m.x223
+ 0.0438098*m.x224 - 0.000231364*m.x225 + 0.00359071*m.x226 - 0.000973423*m.x227
+ 0.00322256*m.x228 + 0.00179649*m.x229 - 0.00135029*m.x230 - 0.000387863*m.x231
- 0.000232243*m.x232 - 0.000214951*m.x233 - 0.000960776*m.x234 + 0.00341529*m.x235
+ 0.00200929*m.x236 - 0.000773953*m.x237 + 0.00603748*m.x238 + 0.00596236*m.x239
- 0.00058046*m.x240 + 0.00527967*m.x241 + 0.00112617*m.x242 + 0.00444472*m.x243
- 0.00275351*m.x244 - 0.000966969*m.x245 - 0.00122748*m.x246 - 0.000508322*m.x247
+ 0.000118632*m.x248 + 0.00252467*m.x249 + 0.00317859*m.x250 - 0.00620603*m.x251
+ 4.22193E-5*m.x252 + 0.000472764*m.x253 + 0.00178849*m.x254 + 0.000750734*m.x255
+ 0.00537508*m.x256 + 0.00171337*m.x257 - 0.000500867*m.x258 + 0.000990598*m.x259
+ 0.00340317*m.x260 + 0.00300201*m.x261 + 0.00379494*m.x262 + 0.00286059*m.x263
+ 0.000619718*m.x264 + 0.000555843*m.x265 + 0.0030044*m.x266 - 0.000640874*m.x267
+ 0.0028325*m.x268 + 0.002376*m.x269 + 0.00468858*m.x270 - 0.000363617*m.x271
+ 0.00165607*m.x272 - 0.00574416*m.x273 + 0.00258154*m.x274 + 0.00381723*m.x275
- 0.000417211*m.x276 - 0.0013492*m.x277 - 0.00366376*m.x278 + 0.00392505*m.x279
- 0.0011348*m.x280 + 0.00121554*m.x281 + 0.00603936*m.x282 - 0.000855626*m.x283
- 9.51042E-5*m.x284 + 0.00328428*m.x285 + 0.000831883*m.x286 - 0.00351138*m.x287
+ 0.000327824*m.x288 + 0.00252261*m.x289 - 0.000723307*m.x290 - 0.00287027*m.x291
+ 0.00383752*m.x292 + 0.00183226*m.x293 - 0.000513898*m.x294 + 0.00248209*m.x295
+ 0.00536292*m.x296 - 0.00508668*m.x297 + 0.00836202*m.x298 + 0.00215742*m.x299
+ 0.00273144*m.x300 - 0.00693562*m.x301 + 0.00172953*m.x302 - 0.00148411*m.x303 == 0)
m.c228 = Constraint(expr= - m.x123 - 3.33076E-5*m.x204 + 0.0172224*m.x205 + 0.0379186*m.x206 - 0.00200937*m.x207
+ 0.0128329*m.x208 + 0.000308528*m.x209 + 0.00300949*m.x210 + 0.00504517*m.x211
- 0.00394915*m.x212 + 0.0459321*m.x213 - 0.00138077*m.x214 - 0.0093405*m.x215
+ 0.00232554*m.x216 + 0.015095*m.x217 + 0.00656162*m.x218 + 0.00326988*m.x219
+ 0.00424617*m.x220 + 0.000945245*m.x221 + 0.00348738*m.x222 + 0.00478458*m.x223
- 0.000231364*m.x224 + 0.108449*m.x225 - 0.00075299*m.x226 + 0.000480919*m.x227
- 0.000894157*m.x228 + 0.0338703*m.x229 + 0.00593049*m.x230 + 0.0033642*m.x231
+ 0.0107294*m.x232 + 0.0102388*m.x233 - 0.000119649*m.x234 + 0.00421343*m.x235
+ 0.0390568*m.x236 + 0.00269243*m.x237 + 0.00303055*m.x238 + 0.00184466*m.x239
+ 0.00552881*m.x240 + 0.00221438*m.x241 - 0.00559594*m.x242 + 0.0047004*m.x243
+ 0.0138343*m.x244 + 0.0105566*m.x245 - 0.00509823*m.x246 - 0.00028965*m.x247
+ 0.0223632*m.x248 + 0.00169098*m.x249 + 0.00143324*m.x250 + 0.0060925*m.x251
- 0.00143233*m.x252 + 0.00043714*m.x253 - 0.00162284*m.x254 + 0.000785002*m.x255
+ 0.000881467*m.x256 + 0.00197703*m.x257 - 0.00185612*m.x258 + 0.00538296*m.x259
+ 0.00350559*m.x260 + 0.00104134*m.x261 - 0.00208082*m.x262 + 0.00622953*m.x263
+ 0.000613874*m.x264 + 0.0106786*m.x265 + 0.00554857*m.x266 - 0.00814519*m.x267
+ 0.0120784*m.x268 + 0.00309714*m.x269 - 0.000808721*m.x270 + 0.00442729*m.x271
+ 0.00165204*m.x272 + 0.0142159*m.x273 - 0.00279132*m.x274 + 0.000424545*m.x275
- 0.00529683*m.x276 - 0.000691165*m.x277 + 0.0035661*m.x278 + 0.00982752*m.x279
+ 0.00395315*m.x280 + 0.00440691*m.x281 - 0.000568168*m.x282 + 0.00655708*m.x283
+ 0.0132513*m.x284 + 0.00364648*m.x285 + 0.0025368*m.x286 + 0.003167*m.x287
+ 0.000670063*m.x288 + 0.00223027*m.x289 - 0.0003553*m.x290 + 0.00805896*m.x291
+ 0.00447158*m.x292 + 0.000707919*m.x293 - 0.000179214*m.x294 - 0.00343349*m.x295
- 0.00319077*m.x296 - 0.00467229*m.x297 - 0.00299231*m.x298 + 0.0141819*m.x299
+ 0.0104414*m.x300 + 0.00771774*m.x301 + 0.00187759*m.x302 + 0.00633113*m.x303 == 0)
m.c229 = Constraint(expr= - m.x124 + 0.00353482*m.x204 + 0.000134992*m.x205 - 0.000515796*m.x206 + 0.00721471*m.x207
+ 0.00506005*m.x208 + 0.00379536*m.x209 - 0.000393934*m.x210 + 0.00209809*m.x211
+ 0.00652373*m.x212 + 0.00841049*m.x213 + 0.00334125*m.x214 - 0.000831286*m.x215
- 0.000605176*m.x216 + 0.00205086*m.x217 + 4.629E-5*m.x218 + 0.00418825*m.x219
+ 0.00582089*m.x220 + 0.00604507*m.x221 - 0.00147046*m.x222 + 0.00310698*m.x223
+ 0.00359071*m.x224 - 0.00075299*m.x225 + 0.0439109*m.x226 + 0.00572233*m.x227
+ 0.006258*m.x228 - 0.000838175*m.x229 + 0.00321015*m.x230 - 0.000280882*m.x231
+ 0.0022121*m.x232 + 0.00230846*m.x233 + 0.0027198*m.x234 + 0.00764299*m.x235
+ 0.00141463*m.x236 + 0.0104736*m.x237 + 0.00498259*m.x238 + 0.00286973*m.x239
+ 0.00101702*m.x240 + 0.00580911*m.x241 + 0.00441704*m.x242 + 0.00542603*m.x243
+ 0.00190962*m.x244 + 0.0100735*m.x245 + 0.00630679*m.x246 + 0.00288469*m.x247
- 0.000683767*m.x248 + 0.00438943*m.x249 + 0.00306698*m.x250 + 0.0140371*m.x251
+ 0.00404018*m.x252 + 0.00262736*m.x253 + 0.00352108*m.x254 + 0.00118551*m.x255
+ 0.000446955*m.x256 + 0.000454264*m.x257 + 0.00404046*m.x258 + 0.00192016*m.x259
+ 0.00725634*m.x260 + 0.0130293*m.x261 + 0.00131963*m.x262 + 0.00472747*m.x263
+ 0.00308159*m.x264 + 0.0042759*m.x265 + 0.00295181*m.x266 - 0.000678406*m.x267
+ 0.00506594*m.x268 + 0.00413143*m.x269 + 0.00263189*m.x270 + 0.0018705*m.x271
+ 0.0019702*m.x272 + 0.000738364*m.x273 - 0.00145188*m.x274 + 0.00338012*m.x275
+ 0.00137974*m.x276 + 0.00275438*m.x277 + 0.0056652*m.x278 + 0.00472609*m.x279
+ 0.00250314*m.x280 + 0.00155203*m.x281 + 0.00168508*m.x282 + 0.00717688*m.x283
+ 0.00442955*m.x284 + 0.000629589*m.x285 - 0.00381097*m.x286 + 0.00553188*m.x287
+ 0.00850491*m.x288 + 0.0052604*m.x289 + 0.00630907*m.x290 + 0.00122268*m.x291
+ 0.00666929*m.x292 + 0.00744101*m.x293 + 0.000456284*m.x294 + 0.00234935*m.x295
+ 0.00264885*m.x296 + 0.000868196*m.x297 + 0.00313515*m.x298 - 0.000643318*m.x299
+ 0.00210871*m.x300 + 0.0011722*m.x301 + 0.00301842*m.x302 + 0.00345188*m.x303 == 0)
m.c230 = Constraint(expr= - m.x125 - 0.00220136*m.x204 - 0.000119948*m.x205 - 0.00228588*m.x206 + 0.00153181*m.x207
+ 0.00243023*m.x208 + 0.00253802*m.x209 - 0.00283134*m.x210 + 0.00376046*m.x211
+ 0.00207177*m.x212 - 0.00536028*m.x213 + 0.000987108*m.x214 - 0.00224216*m.x215
+ 0.000459999*m.x216 + 0.0105187*m.x217 - 0.00368649*m.x218 + 0.00230284*m.x219
+ 0.00298198*m.x220 - 7.69773E-5*m.x221 + 0.0226173*m.x222 + 0.00276388*m.x223
- 0.000973423*m.x224 + 0.000480919*m.x225 + 0.00572233*m.x226 + 0.0535032*m.x227
+ 0.00753458*m.x228 - 0.000689838*m.x229 - 0.00122008*m.x230 + 0.00305472*m.x231
- 0.000106602*m.x232 + 0.00369153*m.x233 + 0.000581923*m.x234 + 0.000856409*m.x235
+ 0.000347455*m.x236 + 0.00321278*m.x237 + 0.00486463*m.x238 + 0.00213079*m.x239
+ 0.00335949*m.x240 + 0.00328455*m.x241 + 0.012679*m.x242 + 0.0031031*m.x243
+ 0.00313438*m.x244 + 0.00142819*m.x245 + 0.00271139*m.x246 + 0.00117205*m.x247
- 0.00385233*m.x248 + 0.00138166*m.x249 + 0.001371*m.x250 + 0.00194706*m.x251
+ 0.000567011*m.x252 + 0.0025858*m.x253 + 0.00360694*m.x254 + 0.00465088*m.x255
+ 0.00215308*m.x256 + 0.000889199*m.x257 + 0.00376111*m.x258 + 0.00798442*m.x259
+ 0.00414154*m.x260 + 0.00118993*m.x261 - 0.00274497*m.x262 - 0.000595349*m.x263
+ 0.00752408*m.x264 + 0.00378686*m.x265 + 1.24483E-5*m.x266 - 0.000694644*m.x267
+ 0.000738861*m.x268 + 0.0016632*m.x269 + 0.00093894*m.x270 + 0.00032798*m.x271
+ 0.000214023*m.x272 - 0.000455981*m.x273 + 0.00209608*m.x274 - 0.00193539*m.x275
+ 0.00122937*m.x276 + 0.00385412*m.x277 + 0.00757348*m.x278 + 0.00328889*m.x279
+ 0.00201276*m.x280 - 0.00176184*m.x281 - 0.000125577*m.x282 + 0.000482661*m.x283
+ 0.00549587*m.x284 - 0.000664034*m.x285 - 0.00216225*m.x286 + 0.000631923*m.x287
+ 9.34236E-5*m.x288 + 0.00532323*m.x289 + 0.00760376*m.x290 + 0.00424627*m.x291
- 0.000984769*m.x292 - 0.000472034*m.x293 + 0.0032716*m.x294 + 0.00763876*m.x295
+ 0.00375527*m.x296 + 0.00235696*m.x297 - 0.00404778*m.x298 - 8.08719E-5*m.x299
+ 0.00955537*m.x300 - 0.00665009*m.x301 + 0.00353927*m.x302 + 0.00543525*m.x303 == 0)
m.c231 = Constraint(expr= - m.x126 + 0.00200825*m.x204 + 0.000402454*m.x205 - 0.00297975*m.x206 + 0.00223523*m.x207
+ 0.00179608*m.x208 + 0.00318827*m.x209 + 0.000310634*m.x210 - 0.00258998*m.x211
+ 0.000966201*m.x212 + 0.00303875*m.x213 + 0.00525686*m.x214 + 0.0088837*m.x215
+ 0.00354005*m.x216 + 0.0017092*m.x217 + 0.00400982*m.x218 + 0.00127379*m.x219
+ 0.00383534*m.x220 + 0.0123754*m.x221 + 0.0121254*m.x222 - 0.000128603*m.x223
+ 0.00322256*m.x224 - 0.000894157*m.x225 + 0.006258*m.x226 + 0.00753458*m.x227
+ 0.0429268*m.x228 - 0.00214333*m.x229 - 0.000662876*m.x230 + 0.00436442*m.x231
+ 0.00691779*m.x232 + 0.00185899*m.x233 + 0.00473111*m.x234 + 0.00327993*m.x235
- 0.00410127*m.x236 + 0.00301966*m.x237 + 0.000909662*m.x238 - 0.000155222*m.x239
+ 0.00657222*m.x240 + 0.00652355*m.x241 - 0.00113837*m.x242 + 0.00241285*m.x243
+ 0.00338711*m.x244 - 0.000552305*m.x245 - 0.00210153*m.x246 + 0.000948894*m.x247
+ 0.00106856*m.x248 + 0.00241905*m.x249 + 0.00317936*m.x250 + 0.00580385*m.x251
+ 0.00417651*m.x252 + 0.00240856*m.x253 - 0.000398367*m.x254 - 0.000713633*m.x255
+ 0.00299454*m.x256 + 2.45482E-5*m.x257 + 0.00534951*m.x258 + 0.00571568*m.x259
+ 0.00328284*m.x260 + 0.00871742*m.x261 + 0.00237906*m.x262 + 0.00268782*m.x263
+ 0.00126037*m.x264 + 0.00496836*m.x265 + 0.00583939*m.x266 + 0.000591772*m.x267
+ 0.00184587*m.x268 + 0.000736705*m.x269 - 0.000390252*m.x270 + 0.00293877*m.x271
+ 0.00416663*m.x272 + 0.00536772*m.x273 + 0.00835572*m.x274 + 0.00427922*m.x275
- 0.00121545*m.x276 + 0.002375*m.x277 + 0.00506443*m.x278 - 0.000339949*m.x279
+ 0.00104576*m.x280 + 0.00385754*m.x281 + 0.00216037*m.x282 - 0.000699399*m.x283
- 0.000380813*m.x284 + 0.00135096*m.x285 + 0.00146462*m.x286 - 0.000571967*m.x287
+ 0.00428001*m.x288 + 0.00246929*m.x289 + 0.00505738*m.x290 + 0.00244428*m.x291
- 0.00119322*m.x292 + 0.00181174*m.x293 - 0.000288904*m.x294 - 0.00446445*m.x295
+ 0.00110999*m.x296 - 0.00346431*m.x297 + 0.00415143*m.x298 + 0.00356873*m.x299
+ 0.00160276*m.x300 - 0.00400958*m.x301 + 0.000129628*m.x302 + 0.00686574*m.x303 == 0)
m.c232 = Constraint(expr= - m.x127 - 0.00767398*m.x204 + 0.0170077*m.x205 + 0.0477231*m.x206 - 0.00637192*m.x207
+ 0.00210744*m.x208 + 0.00415587*m.x209 + 0.000987645*m.x210 + 0.0129869*m.x211
- 0.000384643*m.x212 + 0.0222634*m.x213 + 0.00768851*m.x214 - 0.00558582*m.x215
+ 0.000832659*m.x216 + 0.00728394*m.x217 + 0.00869348*m.x218 + 0.000736619*m.x219
+ 0.00438562*m.x220 - 0.00512292*m.x221 - 0.00558535*m.x222 + 0.00342157*m.x223
+ 0.00179649*m.x224 + 0.0338703*m.x225 - 0.000838175*m.x226 - 0.000689838*m.x227
- 0.00214333*m.x228 + 0.0774329*m.x229 + 0.00380399*m.x230 - 0.00429303*m.x231
+ 0.00975116*m.x232 + 0.00245028*m.x233 + 0.00620626*m.x234 + 0.00204073*m.x235
+ 0.0244378*m.x236 + 0.00425715*m.x237 - 0.00882714*m.x238 + 0.00211448*m.x239
+ 0.00674457*m.x240 + 0.00213229*m.x241 - 0.00226601*m.x242 - 8.92046E-5*m.x243
+ 0.0128103*m.x244 + 0.00497409*m.x245 + 5.78589E-5*m.x246 - 0.00235449*m.x247
+ 0.00327571*m.x248 - 0.00357096*m.x249 - 0.0014774*m.x250 - 0.000131234*m.x251
+ 0.00076644*m.x252 + 0.0033869*m.x253 - 0.00261102*m.x254 + 0.00970161*m.x255
+ 0.00144094*m.x256 + 0.00194079*m.x257 - 0.00202281*m.x258 + 0.00652913*m.x259
- 0.000637013*m.x260 - 0.00101439*m.x261 - 0.0082225*m.x262 + 0.00355615*m.x263
- 0.000188674*m.x264 + 0.00424723*m.x265 + 0.0023868*m.x266 - 0.00326633*m.x267
+ 0.00828866*m.x268 + 0.00468054*m.x269 - 0.000763441*m.x270 + 0.00961433*m.x271
- 0.00265062*m.x272 + 0.00154076*m.x273 + 0.000823677*m.x274 - 0.000449853*m.x275
- 0.00240676*m.x276 - 0.00308594*m.x277 - 0.00171011*m.x278 + 0.00119568*m.x279
+ 0.00520579*m.x280 + 0.00404244*m.x281 - 0.00374261*m.x282 - 0.002876*m.x283
+ 0.00564875*m.x284 + 0.00529419*m.x285 + 0.00183255*m.x286 + 0.00445827*m.x287
- 0.000344244*m.x288 + 0.00160669*m.x289 - 0.00276824*m.x290 + 0.00746466*m.x291
+ 0.00694152*m.x292 - 0.00346329*m.x293 - 0.000701028*m.x294 - 0.00834557*m.x295
+ 0.00667569*m.x296 - 0.00651531*m.x297 - 0.00217122*m.x298 + 0.0161266*m.x299
+ 0.00695292*m.x300 + 0.00190191*m.x301 + 0.00346113*m.x302 + 0.00542579*m.x303 == 0)
m.c233 = Constraint(expr= - m.x128 - 0.00197822*m.x204 + 0.00468054*m.x205 + 0.010936*m.x206 - 0.00268833*m.x207
+ 0.00564026*m.x208 + 0.0068299*m.x209 + 0.00360613*m.x210 - 0.00468059*m.x211
+ 0.00501887*m.x212 + 0.00147836*m.x213 + 0.000743528*m.x214 - 0.000431237*m.x215
+ 0.00241026*m.x216 + 0.00738888*m.x217 + 0.00253402*m.x218 + 0.00149022*m.x219
- 0.00389494*m.x220 + 0.0017955*m.x221 + 0.00376971*m.x222 + 0.00025621*m.x223
- 0.00135029*m.x224 + 0.00593049*m.x225 + 0.00321015*m.x226 - 0.00122008*m.x227
- 0.000662876*m.x228 + 0.00380399*m.x229 + 0.0471923*m.x230 + 0.0015421*m.x231
+ 0.00319704*m.x232 + 0.00342862*m.x233 + 0.000935202*m.x234 + 0.00540865*m.x235
+ 0.000426465*m.x236 + 0.00573566*m.x237 + 0.00705473*m.x238 + 0.00177955*m.x239
+ 0.00206458*m.x240 + 0.00224695*m.x241 - 0.00100575*m.x242 + 0.00175842*m.x243
+ 0.00279507*m.x244 + 0.00733365*m.x245 + 0.00189734*m.x246 - 0.00087259*m.x247
+ 0.00913902*m.x248 + 0.000648204*m.x249 + 0.00369376*m.x250 - 0.00141307*m.x251
- 0.00209444*m.x252 + 0.000886721*m.x253 - 0.00204134*m.x254 + 0.000825909*m.x255
+ 0.00279365*m.x256 - 0.00235578*m.x257 + 0.00110642*m.x258 + 0.00225416*m.x259
- 0.000609378*m.x260 + 0.00251465*m.x261 + 0.00102978*m.x262 + 0.0112079*m.x263
+ 0.00645332*m.x264 + 0.00540775*m.x265 - 0.00427958*m.x266 - 0.0057947*m.x267
+ 0.0139508*m.x268 + 0.00577359*m.x269 - 0.00197249*m.x270 - 0.0041837*m.x271
- 0.00171015*m.x272 + 0.000149793*m.x273 + 0.00209144*m.x274 - 0.00158294*m.x275
+ 0.00125814*m.x276 + 0.00370129*m.x277 + 0.00029565*m.x278 + 0.00285626*m.x279
+ 0.00597457*m.x280 + 0.00323244*m.x281 + 0.00954078*m.x282 - 0.00260552*m.x283
+ 0.00931525*m.x284 + 0.000400638*m.x285 - 0.000672593*m.x286 + 0.00821988*m.x287
+ 0.00442595*m.x288 + 9.7777E-5*m.x289 + 0.00362104*m.x290 + 0.00715697*m.x291
+ 0.00559812*m.x292 + 0.00126776*m.x293 + 0.000428826*m.x294 - 0.00228492*m.x295
- 0.00156275*m.x296 - 0.0039415*m.x297 + 0.0184288*m.x298 + 0.00951648*m.x299
+ 5.68864E-5*m.x300 + 0.0119542*m.x301 + 0.00888358*m.x302 - 0.000364621*m.x303 == 0)
m.c234 = Constraint(expr= - m.x129 - 1.10346E-5*m.x204 + 0.00168652*m.x205 + 0.0065182*m.x206 + 0.00712607*m.x207
+ 0.00132385*m.x208 + 0.00946803*m.x209 + 0.0048888*m.x210 + 0.00960732*m.x211
+ 0.0131889*m.x212 + 0.000467993*m.x213 + 0.00323042*m.x214 + 0.00302183*m.x215
+ 0.00677493*m.x216 + 0.00373072*m.x217 - 0.000309521*m.x218 + 0.00242247*m.x219
- 0.00288026*m.x220 - 0.00492288*m.x221 + 0.00496685*m.x222 + 0.00366426*m.x223
- 0.000387863*m.x224 + 0.0033642*m.x225 - 0.000280882*m.x226 + 0.00305472*m.x227
+ 0.00436442*m.x228 - 0.00429303*m.x229 + 0.0015421*m.x230 + 0.0677524*m.x231
- 0.00294961*m.x232 + 0.00479656*m.x233 + 0.0149434*m.x234 + 0.00178942*m.x235
+ 0.000372831*m.x236 + 0.00106536*m.x237 + 0.00210645*m.x238 + 0.00268821*m.x239
+ 0.00751856*m.x240 + 0.00479783*m.x241 + 0.00280258*m.x242 + 0.00239177*m.x243
+ 0.00553645*m.x244 - 0.00098498*m.x245 + 0.00456291*m.x246 + 0.00077635*m.x247
+ 0.00142627*m.x248 + 0.00217757*m.x249 + 0.00191957*m.x250 + 0.0115101*m.x251
- 0.000945371*m.x252 - 0.0071917*m.x253 + 0.00172599*m.x254 + 0.00211256*m.x255
+ 0.00136592*m.x256 + 0.00392595*m.x257 + 0.00691999*m.x258 + 0.0106189*m.x259
- 0.000182055*m.x260 + 0.00218491*m.x261 + 0.000656633*m.x262 + 0.0175771*m.x263
+ 0.00353599*m.x264 + 0.00274124*m.x265 - 0.000533821*m.x266 - 0.0021747*m.x267
+ 0.00514558*m.x268 + 0.00318024*m.x269 + 0.00107192*m.x270 + 0.00297944*m.x271
+ 0.00387335*m.x272 + 0.000833965*m.x273 + 0.00113589*m.x274 + 0.00481228*m.x275
+ 0.00110802*m.x276 - 0.00473546*m.x277 + 0.00406944*m.x278 - 0.00282972*m.x279
+ 0.00339262*m.x280 + 0.0012098*m.x281 - 0.000254586*m.x282 + 0.00671298*m.x283
+ 0.0117108*m.x284 + 0.00614105*m.x285 + 0.0126386*m.x286 + 0.00409707*m.x287
+ 0.00509678*m.x288 + 0.00201509*m.x289 + 0.000363534*m.x290 + 0.000104518*m.x291
- 0.000217263*m.x292 + 0.000955159*m.x293 - 0.0064418*m.x294 + 0.00195089*m.x295
+ 0.000572419*m.x296 + 0.00151632*m.x297 + 0.000311369*m.x298 - 0.00581513*m.x299
+ 0.00803792*m.x300 + 0.00503323*m.x301 + 0.00261585*m.x302 + 0.0020532*m.x303 == 0)
m.c235 = Constraint(expr= - m.x130 - 0.00119407*m.x204 + 0.0382947*m.x205 + 0.0358881*m.x206 + 0.00579462*m.x207
+ 0.00265952*m.x208 + 0.0152758*m.x209 + 0.000705294*m.x210 - 0.0084924*m.x211
- 0.00750233*m.x212 + 0.00769452*m.x213 + 0.00830891*m.x214 - 0.00219082*m.x215
- 0.0043282*m.x216 - 0.00200641*m.x217 + 0.00380195*m.x218 + 0.00604515*m.x219
+ 0.00241344*m.x220 + 0.00107204*m.x221 + 0.00441973*m.x222 + 0.00765642*m.x223
- 0.000232243*m.x224 + 0.0107294*m.x225 + 0.0022121*m.x226 - 0.000106602*m.x227
+ 0.00691779*m.x228 + 0.00975116*m.x229 + 0.00319704*m.x230 - 0.00294961*m.x231
+ 0.124882*m.x232 + 0.000162013*m.x233 + 0.00806342*m.x234 - 0.00310391*m.x235
+ 0.0145289*m.x236 - 1.60983E-5*m.x237 - 0.002888*m.x238 + 0.00055638*m.x239
- 0.000810434*m.x240 + 0.0051618*m.x241 - 0.00714171*m.x242 - 0.00139437*m.x243
- 0.00161511*m.x244 + 0.00197381*m.x245 - 0.00298086*m.x246 + 0.00139431*m.x247
+ 0.000596885*m.x248 - 0.000173936*m.x249 + 0.00262989*m.x250 + 0.00163586*m.x251
+ 0.000879524*m.x252 + 0.00125037*m.x253 + 0.00165426*m.x254 + 0.00460974*m.x255
- 0.00113943*m.x256 - 0.00176703*m.x257 + 0.00271945*m.x258 - 0.00103376*m.x259
- 0.000944225*m.x260 + 0.00264501*m.x261 - 0.00260547*m.x262 + 0.0017848*m.x263
+ 0.0108839*m.x264 - 0.00138995*m.x265 - 0.00309501*m.x266 - 0.000395075*m.x267
+ 0.00576686*m.x268 + 0.00353172*m.x269 + 0.00568516*m.x270 - 0.00269802*m.x271
+ 0.00498942*m.x272 + 0.00215788*m.x273 - 0.000768782*m.x274 - 0.00366851*m.x275
+ 0.000149784*m.x276 + 0.00567007*m.x277 + 0.00749201*m.x278 + 0.00153215*m.x279
+ 0.00188058*m.x280 - 0.00264831*m.x281 + 0.00777778*m.x282 - 0.000369335*m.x283
+ 0.00409714*m.x284 - 0.000584153*m.x285 - 5.10761E-5*m.x286 - 0.000896178*m.x287
+ 0.00143506*m.x288 - 0.00102564*m.x289 + 0.00929697*m.x290 + 0.000416892*m.x291
+ 0.00340158*m.x292 + 0.00170814*m.x293 + 0.00314179*m.x294 + 0.00196445*m.x295
+ 0.00232212*m.x296 - 0.00194288*m.x297 + 0.000886071*m.x298 + 0.0271101*m.x299
+ 0.00505307*m.x300 - 0.00135319*m.x301 + 0.000960311*m.x302 + 0.00806487*m.x303 == 0)
m.c236 = Constraint(expr= - m.x131 + 0.000602811*m.x204 + 0.0032777*m.x205 + 0.00724543*m.x206 + 0.00617075*m.x207
+ 0.0155615*m.x208 + 0.00176378*m.x209 + 0.0033924*m.x210 - 0.00241471*m.x211
- 0.000147186*m.x212 + 0.00544112*m.x213 + 0.00460225*m.x214 + 0.00318353*m.x215
+ 0.00853448*m.x216 + 0.00380207*m.x217 + 0.00965526*m.x218 + 0.00652264*m.x219
+ 0.00199923*m.x220 - 0.00229718*m.x221 + 0.0069161*m.x222 + 0.00561328*m.x223
- 0.000214951*m.x224 + 0.0102388*m.x225 + 0.00230846*m.x226 + 0.00369153*m.x227
+ 0.00185899*m.x228 + 0.00245028*m.x229 + 0.00342862*m.x230 + 0.00479656*m.x231
+ 0.000162013*m.x232 + 0.0356618*m.x233 - 9.61349E-5*m.x234 + 0.00603043*m.x235
+ 0.00431951*m.x236 + 0.00365119*m.x237 + 0.00726868*m.x238 + 0.00362074*m.x239
+ 0.00298213*m.x240 + 0.00704842*m.x241 + 0.00602321*m.x242 + 0.00375983*m.x243
+ 0.000464103*m.x244 + 0.014905*m.x245 + 0.0143482*m.x246 + 0.00419847*m.x247
+ 0.00136868*m.x248 + 3.95557E-5*m.x249 + 0.0072304*m.x250 + 0.0127117*m.x251
+ 0.00781209*m.x252 + 0.00489662*m.x253 + 0.000468232*m.x254 + 0.00699772*m.x255
+ 0.00356967*m.x256 + 0.000303537*m.x257 + 0.000702332*m.x258 + 0.00357718*m.x259
+ 0.00454768*m.x260 + 0.00483103*m.x261 - 0.00605986*m.x262 + 0.00108709*m.x263
+ 0.00235866*m.x264 + 0.00258727*m.x265 + 0.00334281*m.x266 + 0.000681716*m.x267
+ 0.00619447*m.x268 + 0.00533029*m.x269 + 0.000115147*m.x270 + 0.00302395*m.x271
+ 0.00477754*m.x272 + 0.00409215*m.x273 + 0.0030886*m.x274 + 0.00889169*m.x275
+ 0.00200531*m.x276 + 0.00557444*m.x277 + 0.00392979*m.x278 + 0.00976432*m.x279
+ 0.00633676*m.x280 + 0.00795621*m.x281 + 0.00342719*m.x282 - 0.0024266*m.x283
+ 0.00516382*m.x284 + 0.00568177*m.x285 + 0.00333333*m.x286 + 0.00790729*m.x287
+ 0.00874995*m.x288 + 0.00108982*m.x289 + 0.00847563*m.x290 + 0.00467438*m.x291
+ 0.0016858*m.x292 + 0.000365981*m.x293 + 0.0013091*m.x294 + 0.00271448*m.x295
+ 0.00487642*m.x296 - 0.00289096*m.x297 + 0.00354767*m.x298 + 0.00357909*m.x299
+ 0.00585634*m.x300 - 0.000870044*m.x301 + 0.00817771*m.x302 + 0.00321544*m.x303 == 0)
m.c237 = Constraint(expr= - m.x132 + 0.0132444*m.x204 + 0.00298262*m.x205 + 0.0141802*m.x206 + 0.00178322*m.x207
+ 3.93351E-5*m.x208 + 0.0034359*m.x209 - 0.00243487*m.x210 + 0.00242201*m.x211
- 0.00131105*m.x212 - 0.00240926*m.x213 + 0.00347085*m.x214 + 0.00523947*m.x215
+ 0.00304723*m.x216 + 0.00154953*m.x217 + 0.000998466*m.x218 - 0.00341015*m.x219
- 0.0069523*m.x220 + 6.89241E-5*m.x221 - 0.00118855*m.x222 - 0.00310918*m.x223
- 0.000960776*m.x224 - 0.000119649*m.x225 + 0.0027198*m.x226 + 0.000581923*m.x227
+ 0.00473111*m.x228 + 0.00620626*m.x229 + 0.000935202*m.x230 + 0.0149434*m.x231
+ 0.00806342*m.x232 - 9.61349E-5*m.x233 + 0.138568*m.x234 + 0.00669748*m.x235
- 0.000256415*m.x236 + 0.0145101*m.x237 + 0.00718311*m.x238 - 0.000438119*m.x239
+ 0.00396431*m.x240 + 0.00125565*m.x241 + 0.0122949*m.x242 + 0.00508627*m.x243
- 0.000247882*m.x244 - 0.000117636*m.x245 - 0.00101212*m.x246 - 0.00163422*m.x247
+ 0.00938261*m.x248 + 0.00048899*m.x249 + 0.00273794*m.x250 + 0.0081173*m.x251
+ 0.00159047*m.x252 + 0.00666147*m.x253 - 0.000935815*m.x254 + 0.00366551*m.x255
+ 0.00954228*m.x256 + 0.000832645*m.x257 - 0.000876097*m.x258 + 0.0047508*m.x259
- 0.00109579*m.x260 - 0.000240979*m.x261 + 0.00232308*m.x262 + 0.0118189*m.x263
+ 0.00908161*m.x264 + 0.00892137*m.x265 + 0.00228629*m.x266 - 0.00141271*m.x267
+ 0.0112419*m.x268 + 0.00366445*m.x269 - 0.00115062*m.x270 + 0.00857186*m.x271
+ 0.00134029*m.x272 - 0.00510595*m.x273 - 0.00295933*m.x274 + 0.0115794*m.x275
+ 0.00222961*m.x276 + 0.00216482*m.x277 - 0.000761944*m.x278 + 0.00156264*m.x279
+ 0.00204943*m.x280 + 0.000825899*m.x281 - 0.0014036*m.x282 + 0.00439362*m.x283
+ 0.00824533*m.x284 + 0.00200915*m.x285 + 0.00433982*m.x286 - 0.00368101*m.x287
+ 0.00283946*m.x288 + 0.0020167*m.x289 - 0.00442035*m.x290 - 0.00255785*m.x291
+ 0.00125151*m.x292 - 0.00145108*m.x293 - 0.000936959*m.x294 - 6.93028E-5*m.x295
+ 0.000707514*m.x296 - 0.00353193*m.x297 - 0.00266393*m.x298 + 0.00983835*m.x299
- 0.0040378*m.x300 + 0.00154164*m.x301 + 0.00321227*m.x302 + 0.00627327*m.x303 == 0)
m.c238 = Constraint(expr= - m.x133 - 0.00406553*m.x204 + 0.00157746*m.x205 - 0.00235266*m.x206 + 0.00561978*m.x207
+ 0.00818121*m.x208 + 0.00304328*m.x209 + 0.00351798*m.x210 - 0.00033287*m.x211
- 0.00502474*m.x212 + 0.00822957*m.x213 + 0.0125956*m.x214 + 0.00300376*m.x215
+ 0.00491152*m.x216 + 7.83409E-5*m.x217 + 0.00537877*m.x218 + 0.00247212*m.x219
+ 0.00218093*m.x220 + 0.00358549*m.x221 + 0.00842854*m.x222 + 0.000436137*m.x223
+ 0.00341529*m.x224 + 0.00421343*m.x225 + 0.00764299*m.x226 + 0.000856409*m.x227
+ 0.00327993*m.x228 + 0.00204073*m.x229 + 0.00540865*m.x230 + 0.00178942*m.x231
- 0.00310391*m.x232 + 0.00603043*m.x233 + 0.00669748*m.x234 + 0.0667779*m.x235
+ 0.00383032*m.x236 + 0.00215057*m.x237 + 0.00477102*m.x238 + 0.00282296*m.x239
+ 0.00413078*m.x240 + 0.00578179*m.x241 + 0.00387204*m.x242 + 0.00248171*m.x243
+ 0.0124245*m.x244 + 0.00458518*m.x245 + 0.00111236*m.x246 + 0.00175884*m.x247
+ 0.00193995*m.x248 + 0.00582795*m.x249 + 0.00221714*m.x250 + 0.00143776*m.x251
+ 0.00796665*m.x252 + 0.00687732*m.x253 + 0.00952368*m.x254 - 0.000273013*m.x255
+ 0.00106084*m.x256 - 0.00338076*m.x257 + 0.00179605*m.x258 + 0.00600138*m.x259
+ 0.00499556*m.x260 + 0.00310331*m.x261 + 0.0058288*m.x262 + 0.00581735*m.x263
+ 0.00417314*m.x264 - 0.0011102*m.x265 + 0.00234077*m.x266 - 0.00112428*m.x267
+ 0.0103289*m.x268 + 0.00121195*m.x269 + 0.00320026*m.x270 + 0.00764263*m.x271
+ 0.000547113*m.x272 + 0.00407025*m.x273 + 0.0036774*m.x274 + 0.00185908*m.x275
+ 0.0035544*m.x276 + 0.000252173*m.x277 + 0.0057429*m.x278 + 0.00330489*m.x279
+ 0.00398224*m.x280 + 0.00493613*m.x281 + 0.000602209*m.x282 + 0.00499603*m.x283
+ 0.00484005*m.x284 + 0.0129378*m.x285 + 0.00126871*m.x286 + 0.0109368*m.x287
+ 0.0240688*m.x288 - 0.000216395*m.x289 + 0.00218847*m.x290 + 0.00462496*m.x291
- 0.00173756*m.x292 + 0.000369864*m.x293 + 0.00518077*m.x294 + 0.00780177*m.x295
- 0.000183456*m.x296 + 0.00313748*m.x297 + 0.0108401*m.x298 + 0.00439792*m.x299
+ 0.000633255*m.x300 - 0.00249511*m.x301 + 0.00187615*m.x302 + 0.00489037*m.x303 == 0)
m.c239 = Constraint(expr= - m.x134 + 0.00422631*m.x204 + 0.0105061*m.x205 + 0.0360049*m.x206 - 0.000789221*m.x207
+ 0.00576868*m.x208 - 0.0024897*m.x209 - 0.000533129*m.x210 + 0.00115625*m.x211
- 0.0031803*m.x212 + 0.0404735*m.x213 - 0.00124658*m.x214 - 0.00393984*m.x215
- 0.00788435*m.x216 + 0.00350834*m.x217 + 0.00531506*m.x218 + 0.00108611*m.x219
+ 0.00785569*m.x220 - 0.00049534*m.x221 - 0.00512765*m.x222 + 0.00626525*m.x223
+ 0.00200929*m.x224 + 0.0390568*m.x225 + 0.00141463*m.x226 + 0.000347455*m.x227
- 0.00410127*m.x228 + 0.0244378*m.x229 + 0.000426465*m.x230 + 0.000372831*m.x231
+ 0.0145289*m.x232 + 0.00431951*m.x233 - 0.000256415*m.x234 + 0.00383032*m.x235
+ 0.0865427*m.x236 + 0.00214256*m.x237 + 0.0130345*m.x238 + 7.06613E-5*m.x239
+ 0.00487378*m.x240 + 0.00341855*m.x241 - 0.00226294*m.x242 + 0.00208303*m.x243
+ 0.00301773*m.x244 + 0.00794854*m.x245 + 0.00558802*m.x246 - 0.000174917*m.x247
- 0.00127938*m.x248 - 0.000380482*m.x249 + 0.0022927*m.x250 + 0.0147001*m.x251
- 0.000690034*m.x252 - 0.00340535*m.x253 - 0.00483173*m.x254 + 0.00228568*m.x255
- 0.00083261*m.x256 - 0.00120821*m.x257 - 0.00293263*m.x258 + 0.0100916*m.x259
- 0.000975461*m.x260 + 4.58518E-6*m.x261 + 0.00679259*m.x262 + 0.0109441*m.x263
- 0.00141802*m.x264 + 0.00426929*m.x265 + 0.000950245*m.x266 - 0.0100929*m.x267
+ 0.00991537*m.x268 + 0.00593721*m.x269 + 0.00327904*m.x270 + 0.0084466*m.x271
+ 0.00275452*m.x272 + 0.00389367*m.x273 - 0.000709167*m.x274 - 0.00220075*m.x275
- 0.00419952*m.x276 + 0.00578535*m.x277 - 0.00402305*m.x278 + 0.000882589*m.x279
+ 0.00527028*m.x280 - 0.00719009*m.x281 + 0.000341894*m.x282 - 0.00292742*m.x283
+ 0.00505718*m.x284 - 0.000112291*m.x285 + 0.00142508*m.x286 + 0.00445551*m.x287
+ 0.00496328*m.x288 + 0.000556729*m.x289 + 0.00173871*m.x290 - 0.00650082*m.x291
+ 0.00670699*m.x292 - 0.000640342*m.x293 + 0.00360938*m.x294 + 0.00110968*m.x295
+ 0.00261151*m.x296 - 0.00695241*m.x297 - 0.00163906*m.x298 + 0.000292171*m.x299
+ 0.00495442*m.x300 + 0.00511283*m.x301 + 0.00311265*m.x302 + 0.00964866*m.x303 == 0)
m.c240 = Constraint(expr= - m.x135 - 0.00343731*m.x204 - 0.00233804*m.x205 + 0.00392202*m.x206 + 0.000342323*m.x207
+ 0.00589168*m.x208 + 0.0154113*m.x209 + 0.00286727*m.x210 + 0.00402359*m.x211
+ 0.00422327*m.x212 + 0.00290678*m.x213 + 0.0109431*m.x214 + 0.00148726*m.x215
- 0.00162346*m.x216 + 0.00377252*m.x217 - 0.000807326*m.x218 + 0.00269604*m.x219
+ 0.00680418*m.x220 + 0.00484482*m.x221 + 0.000931212*m.x222 + 0.00296798*m.x223
- 0.000773953*m.x224 + 0.00269243*m.x225 + 0.0104736*m.x226 + 0.00321278*m.x227
+ 0.00301966*m.x228 + 0.00425715*m.x229 + 0.00573566*m.x230 + 0.00106536*m.x231
- 1.60983E-5*m.x232 + 0.00365119*m.x233 + 0.0145101*m.x234 + 0.00215057*m.x235
+ 0.00214256*m.x236 + 0.101774*m.x237 + 0.00687798*m.x238 + 0.00348508*m.x239
- 0.000586083*m.x240 + 0.00824532*m.x241 - 0.00154559*m.x242 + 0.00822121*m.x243
+ 0.0020747*m.x244 + 0.00528007*m.x245 + 0.00021007*m.x246 + 0.00412244*m.x247
+ 0.00363406*m.x248 + 0.0025062*m.x249 + 0.00352758*m.x250 + 0.00268179*m.x251
+ 0.0017263*m.x252 + 0.0110796*m.x253 + 0.00388802*m.x254 - 0.00663898*m.x255
+ 0.00271133*m.x256 + 0.00151359*m.x257 + 0.00375338*m.x258 + 0.00325149*m.x259
+ 0.00083169*m.x260 - 5.91301E-5*m.x261 + 0.00581394*m.x262 + 0.00200882*m.x263
+ 0.000695564*m.x264 - 0.00052299*m.x265 + 0.00584205*m.x266 - 0.00708984*m.x267
+ 0.00265142*m.x268 + 0.00120658*m.x269 + 0.00429363*m.x270 + 0.00258002*m.x271
+ 0.000225492*m.x272 + 0.00114158*m.x273 + 0.00465008*m.x274 + 0.0128796*m.x275
+ 0.00160429*m.x276 + 0.00322761*m.x277 + 0.00655944*m.x278 + 0.0152201*m.x279
+ 0.00163512*m.x280 - 0.000389451*m.x281 + 0.0037276*m.x282 - 0.0010051*m.x283
+ 0.0025218*m.x284 + 0.0044636*m.x285 - 0.00398086*m.x286 + 0.00037716*m.x287
+ 0.00428731*m.x288 + 0.0020993*m.x289 + 0.00773233*m.x290 + 0.00108107*m.x291
+ 0.00180858*m.x292 - 0.00124112*m.x293 + 0.00633646*m.x294 + 0.00394326*m.x295
- 0.00068464*m.x296 - 0.00580836*m.x297 + 0.000271513*m.x298 + 0.0112659*m.x299
+ 0.00208455*m.x300 + 0.0126192*m.x301 + 0.000840037*m.x302 + 0.00862854*m.x303 == 0)
m.c241 = Constraint(expr= - m.x136 + 0.00651535*m.x204 - 0.000430784*m.x205 + 0.0042099*m.x206 + 0.00409312*m.x207
+ 0.00706516*m.x208 + 0.00423352*m.x209 - 0.002207*m.x210 - 0.000640147*m.x211
- 0.00434983*m.x212 + 0.00783851*m.x213 + 0.00410401*m.x214 - 0.000225512*m.x215
- 0.00143462*m.x216 + 0.0162195*m.x217 + 0.00322637*m.x218 + 0.00154541*m.x219
+ 0.00351389*m.x220 + 0.00543851*m.x221 - 0.00452187*m.x222 - 0.0019476*m.x223
+ 0.00603748*m.x224 + 0.00303055*m.x225 + 0.00498259*m.x226 + 0.00486463*m.x227
+ 0.000909662*m.x228 - 0.00882714*m.x229 + 0.00705473*m.x230 + 0.00210645*m.x231
- 0.002888*m.x232 + 0.00726868*m.x233 + 0.00718311*m.x234 + 0.00477102*m.x235
+ 0.0130345*m.x236 + 0.00687798*m.x237 + 0.0915486*m.x238 + 0.0069577*m.x239
+ 0.00192452*m.x240 + 0.00546136*m.x241 + 0.00966242*m.x242 + 0.0048235*m.x243
+ 0.000350009*m.x244 + 0.00928938*m.x245 + 0.000130711*m.x246 - 0.0013095*m.x247
+ 0.0163399*m.x248 + 0.00412922*m.x249 + 0.00247137*m.x250 + 0.00232468*m.x251
+ 0.00329108*m.x252 - 0.00197335*m.x253 + 0.000239144*m.x254 + 0.00326997*m.x255
- 0.0010155*m.x256 + 0.000659488*m.x257 + 0.000561626*m.x258 + 0.000752009*m.x259
+ 0.0012213*m.x260 - 3.22002E-5*m.x261 - 0.00148681*m.x262 + 0.00211146*m.x263
- 0.000313358*m.x264 + 0.00501177*m.x265 + 0.00457594*m.x266 - 0.0104815*m.x267
+ 0.0017514*m.x268 + 0.000755628*m.x269 + 0.00557733*m.x270 + 0.00229256*m.x271
+ 0.000473704*m.x272 + 0.0031662*m.x273 - 0.00122519*m.x274 + 0.00469534*m.x275
+ 0.00559382*m.x276 + 0.00528838*m.x277 + 0.00469948*m.x278 + 0.0120162*m.x279
+ 0.00363359*m.x280 + 0.002036*m.x281 - 0.00283527*m.x282 - 0.00290324*m.x283
- 0.00552971*m.x284 + 0.0028359*m.x285 - 0.00191638*m.x286 + 0.000588805*m.x287
+ 0.00709492*m.x288 + 0.00428712*m.x289 + 0.00918313*m.x290 + 0.00156534*m.x291
+ 0.00072917*m.x292 + 0.00366701*m.x293 - 0.00358706*m.x294 + 0.000268238*m.x295
+ 0.00341113*m.x296 - 0.00131877*m.x297 + 0.00963574*m.x298 - 0.00402802*m.x299
+ 0.0104253*m.x300 - 0.00123284*m.x301 + 0.00267415*m.x302 + 0.00590155*m.x303 == 0)
m.c242 = Constraint(expr= - m.x137 - 0.00313138*m.x204 + 0.00369645*m.x205 + 0.00555015*m.x206 + 0.0043798*m.x207
+ 0.00432744*m.x208 + 0.00420821*m.x209 + 0.00114119*m.x210 - 0.00221072*m.x211
+ 0.00139653*m.x212 + 0.00157388*m.x213 + 0.00255437*m.x214 + 0.00296695*m.x215
+ 0.00392967*m.x216 + 0.00354522*m.x217 + 0.00624206*m.x218 + 0.000676983*m.x219
+ 0.00697412*m.x220 - 0.00363013*m.x221 + 0.00223296*m.x222 + 0.00329745*m.x223
+ 0.00596236*m.x224 + 0.00184466*m.x225 + 0.00286973*m.x226 + 0.00213079*m.x227
- 0.000155222*m.x228 + 0.00211448*m.x229 + 0.00177955*m.x230 + 0.00268821*m.x231
+ 0.00055638*m.x232 + 0.00362074*m.x233 - 0.000438119*m.x234 + 0.00282296*m.x235
+ 7.06613E-5*m.x236 + 0.00348508*m.x237 + 0.0069577*m.x238 + 0.0455133*m.x239
- 0.00126273*m.x240 + 0.00269327*m.x241 - 0.000220811*m.x242 + 0.00310296*m.x243
+ 0.00545946*m.x244 + 0.00372702*m.x245 - 0.000760636*m.x246 + 0.00381839*m.x247
+ 0.00413739*m.x248 + 0.00695501*m.x249 + 0.0028489*m.x250 + 0.00397424*m.x251
- 0.00183251*m.x252 + 0.00181348*m.x253 - 0.00235222*m.x254 + 0.00373008*m.x255
+ 0.00394493*m.x256 + 0.00375855*m.x257 + 0.00224988*m.x258 + 0.00173868*m.x259
+ 0.00334586*m.x260 - 0.00132202*m.x261 - 0.00379641*m.x262 + 0.00586093*m.x263
+ 0.00136897*m.x264 + 0.00469266*m.x265 - 0.0014627*m.x266 + 0.00243124*m.x267
+ 0.00934914*m.x268 + 0.000872186*m.x269 - 0.00186934*m.x270 + 0.00444714*m.x271
+ 0.00103419*m.x272 + 0.00586585*m.x273 + 0.00231842*m.x274 + 0.0117501*m.x275
- 0.00199508*m.x276 + 0.00257808*m.x277 - 0.002975*m.x278 + 0.00511897*m.x279
+ 0.00114031*m.x280 + 0.00600576*m.x281 - 0.000204738*m.x282 + 0.00299286*m.x283
+ 0.00431272*m.x284 + 0.000643374*m.x285 + 0.000528405*m.x286 + 0.0038775*m.x287
+ 0.000936991*m.x288 - 0.00199242*m.x289 + 0.004542*m.x290 + 0.00331247*m.x291
+ 0.00015452*m.x292 + 0.00451357*m.x293 - 0.00325512*m.x294 - 0.0021067*m.x295
+ 0.00769045*m.x296 - 0.00143092*m.x297 - 0.000148921*m.x298 + 0.0048758*m.x299
+ 0.00286852*m.x300 - 0.00298357*m.x301 + 0.000697231*m.x302 + 0.00549383*m.x303 == 0)
m.c243 = Constraint(expr= - m.x138 + 0.00359841*m.x204 + 0.00893962*m.x205 + 0.00521599*m.x206 + 0.00830042*m.x207
+ 0.0048282*m.x208 + 0.00164738*m.x209 + 0.00331*m.x210 + 0.00267732*m.x211
- 0.000845758*m.x212 + 0.00239796*m.x213 + 0.00542448*m.x214 + 0.00567021*m.x215
+ 0.000510251*m.x216 + 0.0091783*m.x217 + 0.01146*m.x218 + 0.00245648*m.x219
+ 0.00770413*m.x220 + 0.00976994*m.x221 + 0.000265224*m.x222 - 0.00473803*m.x223
- 0.00058046*m.x224 + 0.00552881*m.x225 + 0.00101702*m.x226 + 0.00335949*m.x227
+ 0.00657222*m.x228 + 0.00674457*m.x229 + 0.00206458*m.x230 + 0.00751856*m.x231
- 0.000810434*m.x232 + 0.00298213*m.x233 + 0.00396431*m.x234 + 0.00413078*m.x235
+ 0.00487378*m.x236 - 0.000586083*m.x237 + 0.00192452*m.x238 - 0.00126273*m.x239
+ 0.0409948*m.x240 + 0.00681013*m.x241 + 0.00156188*m.x242 + 0.00309487*m.x243
+ 0.00872817*m.x244 + 0.00536076*m.x245 - 0.00233255*m.x246 - 0.00284383*m.x247
+ 0.00442326*m.x248 + 0.00224652*m.x249 + 0.000464028*m.x250 + 0.00563646*m.x251
+ 0.0023205*m.x252 + 0.00368711*m.x253 + 0.00446507*m.x254 + 0.00335461*m.x255
+ 0.00612415*m.x256 + 0.00459437*m.x257 + 0.000431036*m.x258 + 0.0214193*m.x259
+ 0.00347374*m.x260 + 0.00358454*m.x261 + 0.000513289*m.x262 + 0.00739902*m.x263
+ 0.00499907*m.x264 + 0.00550805*m.x265 + 0.00361742*m.x266 - 0.00468506*m.x267
+ 0.00941149*m.x268 + 0.00506394*m.x269 - 0.000575193*m.x270 + 0.00583068*m.x271
+ 0.00257751*m.x272 + 0.00615504*m.x273 + 0.00425069*m.x274 + 0.00451846*m.x275
+ 0.00704945*m.x276 + 0.00264191*m.x277 + 0.00435042*m.x278 + 0.00377697*m.x279
+ 0.00320382*m.x280 + 0.00309988*m.x281 + 0.00412862*m.x282 + 0.00264123*m.x283
+ 0.00669612*m.x284 + 0.00461646*m.x285 + 0.0036023*m.x286 - 0.0025638*m.x287
+ 0.00488446*m.x288 + 0.00447164*m.x289 + 0.00473894*m.x290 + 0.00741949*m.x291
- 0.00059291*m.x292 + 0.000506587*m.x293 + 0.00202802*m.x294 + 0.00774598*m.x295
+ 0.0082126*m.x296 - 0.00437163*m.x297 + 0.00034667*m.x298 + 0.00832302*m.x299
+ 0.0112749*m.x300 - 0.00281611*m.x301 + 0.00195298*m.x302 - 0.000375713*m.x303 == 0)
m.c244 = Constraint(expr= - m.x139 + 0.00452148*m.x204 + 0.00500082*m.x205 - 0.00112076*m.x206 + 0.0127205*m.x207
+ 0.00624337*m.x208 + 0.00313153*m.x209 + 0.00432021*m.x210 - 0.00280484*m.x211
+ 0.00373613*m.x212 + 0.00048455*m.x213 + 0.00676388*m.x214 + 0.00427603*m.x215
+ 0.00735682*m.x216 + 0.00426163*m.x217 + 0.00677387*m.x218 + 0.0067893*m.x219
+ 0.00302394*m.x220 + 0.011369*m.x221 + 0.00539435*m.x222 + 0.00102553*m.x223
+ 0.00527967*m.x224 + 0.00221438*m.x225 + 0.00580911*m.x226 + 0.00328455*m.x227
+ 0.00652355*m.x228 + 0.00213229*m.x229 + 0.00224695*m.x230 + 0.00479783*m.x231
+ 0.0051618*m.x232 + 0.00704842*m.x233 + 0.00125565*m.x234 + 0.00578179*m.x235
+ 0.00341855*m.x236 + 0.00824532*m.x237 + 0.00546136*m.x238 + 0.00269327*m.x239
+ 0.00681013*m.x240 + 0.032896*m.x241 + 0.00238734*m.x242 + 0.00205187*m.x243
+ 0.00348887*m.x244 + 0.00871729*m.x245 + 0.00141435*m.x246 + 0.00274745*m.x247
- 0.00109864*m.x248 + 0.0042909*m.x249 + 0.0039924*m.x250 + 0.000223728*m.x251
+ 0.00665241*m.x252 + 0.0109749*m.x253 - 0.00020878*m.x254 + 0.000913669*m.x255
+ 0.0037812*m.x256 + 0.00342695*m.x257 + 0.0012954*m.x258 + 0.00902766*m.x259
+ 0.00635346*m.x260 + 0.00329425*m.x261 + 0.00481242*m.x262 + 0.00100992*m.x263
+ 0.00530761*m.x264 + 0.00606979*m.x265 + 0.00181367*m.x266 + 0.000404166*m.x267
+ 0.00199306*m.x268 + 0.00308026*m.x269 + 0.00492292*m.x270 + 0.00326363*m.x271
+ 0.00430324*m.x272 + 0.00533161*m.x273 + 0.00508092*m.x274 + 0.000128128*m.x275
+ 0.00294995*m.x276 + 0.0033947*m.x277 + 0.00617964*m.x278 + 0.00469332*m.x279
+ 0.00171417*m.x280 + 0.00500233*m.x281 + 0.00380334*m.x282 + 0.00381492*m.x283
+ 0.00349169*m.x284 + 0.00806328*m.x285 + 0.00248382*m.x286 + 0.00101753*m.x287
+ 0.00966172*m.x288 + 0.00687358*m.x289 + 0.00303402*m.x290 + 0.008727*m.x291
+ 0.00345779*m.x292 + 0.00402615*m.x293 + 0.000154347*m.x294 + 0.0100018*m.x295
+ 0.00342953*m.x296 - 0.000843844*m.x297 + 0.00516692*m.x298 + 0.000320143*m.x299
+ 0.00463152*m.x300 - 0.0012355*m.x301 + 0.00336904*m.x302 + 0.00227586*m.x303 == 0)
m.c245 = Constraint(expr= - m.x140 + 0.00366834*m.x204 + 0.00579376*m.x205 - 0.00218836*m.x206 + 0.00431059*m.x207
- 0.00066102*m.x208 + 0.000192806*m.x209 + 0.0068693*m.x210 + 0.00478207*m.x211
+ 0.0140464*m.x212 - 0.00531909*m.x213 + 0.00233527*m.x214 + 0.00843837*m.x215
- 1.91274E-5*m.x216 + 0.00463458*m.x217 + 0.00202426*m.x218 + 0.00379181*m.x219
+ 0.00226701*m.x220 - 0.00581329*m.x221 + 0.00247662*m.x222 + 0.0109513*m.x223
+ 0.00112617*m.x224 - 0.00559594*m.x225 + 0.00441704*m.x226 + 0.012679*m.x227
- 0.00113837*m.x228 - 0.00226601*m.x229 - 0.00100575*m.x230 + 0.00280258*m.x231
- 0.00714171*m.x232 + 0.00602321*m.x233 + 0.0122949*m.x234 + 0.00387204*m.x235
- 0.00226294*m.x236 - 0.00154559*m.x237 + 0.00966242*m.x238 - 0.000220811*m.x239
+ 0.00156188*m.x240 + 0.00238734*m.x241 + 0.0870554*m.x242 + 0.00323664*m.x243
+ 0.00552878*m.x244 + 0.000970258*m.x245 + 0.00655255*m.x246 - 0.00182652*m.x247
+ 0.0175505*m.x248 - 0.00564367*m.x249 + 0.00110388*m.x250 + 0.00135794*m.x251
+ 0.00288393*m.x252 + 0.000894389*m.x253 - 0.00340572*m.x254 + 0.0231518*m.x255
+ 0.00932518*m.x256 + 0.00712405*m.x257 + 0.00147782*m.x258 - 0.000544689*m.x259
+ 0.00242014*m.x260 - 0.000399422*m.x261 - 0.0010186*m.x262 + 0.00402009*m.x263
+ 0.00907092*m.x264 + 0.00387696*m.x265 + 0.00304921*m.x266 + 0.000493456*m.x267
- 0.000247517*m.x268 + 0.000349729*m.x269 - 6.1818E-5*m.x270 + 0.0011178*m.x271
- 0.00573353*m.x272 - 0.00828959*m.x273 + 0.00226037*m.x274 + 0.00534219*m.x275
+ 0.00159989*m.x276 - 0.00222586*m.x277 + 0.0053804*m.x278 + 0.00320131*m.x279
+ 0.000418358*m.x280 + 0.00364534*m.x281 + 0.00809556*m.x282 + 0.00378329*m.x283
+ 0.00368273*m.x284 + 0.00160903*m.x285 - 0.000963309*m.x286 + 0.000387026*m.x287
- 0.000747807*m.x288 + 0.00119059*m.x289 + 0.00357163*m.x290 + 0.0049149*m.x291
- 0.000828779*m.x292 - 0.00332156*m.x293 + 0.000844659*m.x294 + 0.00455282*m.x295
+ 0.0027501*m.x296 + 0.00568815*m.x297 + 0.00312586*m.x298 + 0.00643759*m.x299
+ 0.0076711*m.x300 - 0.00311771*m.x301 + 0.000316259*m.x302 - 0.000648959*m.x303 == 0)
m.c246 = Constraint(expr= - m.x141 + 0.00592328*m.x204 + 0.0033232*m.x205 - 0.000304719*m.x206 + 0.00271535*m.x207
+ 0.00539504*m.x208 + 0.00566827*m.x209 + 0.00261587*m.x210 - 0.00021402*m.x211
+ 0.000586315*m.x212 - 0.000873781*m.x213 + 0.00504678*m.x214 + 0.00429264*m.x215
+ 0.00401842*m.x216 + 0.00908995*m.x217 + 0.0050502*m.x218 + 0.00278355*m.x219
- 0.00141664*m.x220 + 0.00404015*m.x221 + 0.00595035*m.x222 + 0.00258678*m.x223
+ 0.00444472*m.x224 + 0.0047004*m.x225 + 0.00542603*m.x226 + 0.0031031*m.x227
+ 0.00241285*m.x228 - 8.92046E-5*m.x229 + 0.00175842*m.x230 + 0.00239177*m.x231
- 0.00139437*m.x232 + 0.00375983*m.x233 + 0.00508627*m.x234 + 0.00248171*m.x235
+ 0.00208303*m.x236 + 0.00822121*m.x237 + 0.0048235*m.x238 + 0.00310296*m.x239
+ 0.00309487*m.x240 + 0.00205187*m.x241 + 0.00323664*m.x242 + 0.0284839*m.x243
+ 0.00398656*m.x244 + 0.00674147*m.x245 - 0.000440194*m.x246 + 0.00333395*m.x247
+ 0.00339227*m.x248 + 0.00216846*m.x249 + 0.0060672*m.x250 + 0.00195896*m.x251
+ 0.00250112*m.x252 + 0.00342576*m.x253 - 0.000387287*m.x254 + 0.000121531*m.x255
+ 0.00270791*m.x256 + 0.00249349*m.x257 + 0.00562279*m.x258 + 0.00307201*m.x259
+ 0.00538657*m.x260 + 0.00391396*m.x261 - 0.00159432*m.x262 + 0.00192515*m.x263
+ 0.0041524*m.x264 + 0.00171382*m.x265 + 0.00400573*m.x266 + 0.000351314*m.x267
+ 0.00222305*m.x268 + 0.00506636*m.x269 + 0.00339671*m.x270 + 0.00640579*m.x271
+ 0.000454124*m.x272 - 0.000205968*m.x273 + 0.00175952*m.x274 + 0.00448064*m.x275
+ 0.00382583*m.x276 + 0.00466981*m.x277 + 0.00641732*m.x278 + 0.0117164*m.x279
+ 0.0044896*m.x280 + 0.00543249*m.x281 + 0.00297247*m.x282 + 0.00569595*m.x283
+ 0.001847*m.x284 + 2.32746E-5*m.x285 + 0.00157998*m.x286 + 0.00521645*m.x287
+ 0.00442051*m.x288 + 0.00558644*m.x289 + 0.00249097*m.x290 + 0.00567517*m.x291
+ 0.00151899*m.x292 + 0.00425113*m.x293 + 0.000283697*m.x294 + 0.00430656*m.x295
+ 0.00315729*m.x296 + 0.00297396*m.x297 + 0.00597381*m.x298 + 0.00713407*m.x299
+ 0.00444173*m.x300 - 0.00372007*m.x301 + 0.00227586*m.x302 + 0.00205933*m.x303 == 0)
m.c247 = Constraint(expr= - m.x142 + 0.00503367*m.x204 + 0.00493974*m.x205 + 0.00236864*m.x206 + 0.00301995*m.x207
+ 0.0051422*m.x208 - 0.00114024*m.x209 + 0.000712154*m.x210 + 0.00344966*m.x211
+ 0.00323884*m.x212 + 0.00339704*m.x213 + 0.00322689*m.x214 - 0.00287625*m.x215
+ 0.00871044*m.x216 + 0.0117519*m.x217 + 0.00960388*m.x218 + 0.00683784*m.x219
+ 0.0117404*m.x220 + 0.00827466*m.x221 + 0.00389459*m.x222 + 0.00290544*m.x223
- 0.00275351*m.x224 + 0.0138343*m.x225 + 0.00190962*m.x226 + 0.00313438*m.x227
+ 0.00338711*m.x228 + 0.0128103*m.x229 + 0.00279507*m.x230 + 0.00553645*m.x231
- 0.00161511*m.x232 + 0.000464103*m.x233 - 0.000247882*m.x234 + 0.0124245*m.x235
+ 0.00301773*m.x236 + 0.0020747*m.x237 + 0.000350009*m.x238 + 0.00545946*m.x239
+ 0.00872817*m.x240 + 0.00348887*m.x241 + 0.00552878*m.x242 + 0.00398656*m.x243
+ 0.122694*m.x244 + 0.00178011*m.x245 + 0.00327609*m.x246 - 0.00135254*m.x247
+ 0.0166665*m.x248 - 0.000715736*m.x249 + 0.00244895*m.x250 + 0.00980088*m.x251
+ 0.00710031*m.x252 + 0.00623048*m.x253 + 0.00150226*m.x254 + 0.00314883*m.x255
- 0.00202199*m.x256 + 0.00535529*m.x257 - 0.000606735*m.x258 + 0.00976436*m.x259
+ 0.00469016*m.x260 + 0.0113975*m.x261 + 0.00680033*m.x262 - 0.00297392*m.x263
+ 0.00512496*m.x264 + 0.00566131*m.x265 - 0.00340962*m.x266 + 3.23772E-5*m.x267
+ 0.00288722*m.x268 - 0.00118633*m.x269 + 0.00128347*m.x270 + 0.00976189*m.x271
- 0.00394866*m.x272 + 0.0292476*m.x273 + 0.00482129*m.x274 + 0.0197985*m.x275
- 0.00202513*m.x276 + 0.00768395*m.x277 + 0.00245073*m.x278 + 0.0074376*m.x279
+ 0.00257063*m.x280 + 0.00619385*m.x281 + 0.000995878*m.x282 - 0.000313695*m.x283
- 0.000172475*m.x284 + 0.00144712*m.x285 - 0.000953639*m.x286 + 0.00753955*m.x287
+ 0.00801224*m.x288 + 0.0112013*m.x289 + 0.00334346*m.x290 - 0.0105804*m.x291
+ 0.00626909*m.x292 + 0.000678624*m.x293 + 0.00452262*m.x294 + 0.00404098*m.x295
+ 0.00307669*m.x296 + 0.00364193*m.x297 + 0.00434876*m.x298 + 0.0116213*m.x299
+ 0.0135054*m.x300 + 0.00150838*m.x301 + 0.00321772*m.x302 + 0.00468832*m.x303 == 0)
m.c248 = Constraint(expr= - m.x143 + 0.00629207*m.x204 + 1.72372E-5*m.x205 - 0.0019383*m.x206 + 0.00485894*m.x207
+ 0.0159499*m.x208 + 0.0104584*m.x209 + 0.00243149*m.x210 + 0.000269359*m.x211
- 0.00103573*m.x212 + 0.00996659*m.x213 + 0.00189672*m.x214 + 0.00281472*m.x215
+ 0.00642735*m.x216 + 0.00671356*m.x217 + 0.00401854*m.x218 + 0.0019748*m.x219
+ 0.00452128*m.x220 + 0.0016263*m.x221 + 0.00755471*m.x222 + 0.00906206*m.x223
- 0.000966969*m.x224 + 0.0105566*m.x225 + 0.0100735*m.x226 + 0.00142819*m.x227
- 0.000552305*m.x228 + 0.00497409*m.x229 + 0.00733365*m.x230 - 0.00098498*m.x231
+ 0.00197381*m.x232 + 0.014905*m.x233 - 0.000117636*m.x234 + 0.00458518*m.x235
+ 0.00794854*m.x236 + 0.00528007*m.x237 + 0.00928938*m.x238 + 0.00372702*m.x239
+ 0.00536076*m.x240 + 0.00871729*m.x241 + 0.000970258*m.x242 + 0.00674147*m.x243
+ 0.00178011*m.x244 + 0.045031*m.x245 + 0.00113112*m.x246 + 0.00291832*m.x247
+ 0.00780343*m.x248 + 0.00217772*m.x249 + 0.0059976*m.x250 + 0.00294803*m.x251
+ 0.00552272*m.x252 + 0.00800356*m.x253 + 0.00202451*m.x254 + 0.00875321*m.x255
+ 0.00341817*m.x256 + 0.00331148*m.x257 + 0.00151183*m.x258 + 0.0063979*m.x259
+ 0.00583129*m.x260 - 0.00449059*m.x261 - 0.000373896*m.x262 + 0.00465423*m.x263
+ 0.00129105*m.x264 + 0.00312652*m.x265 - 0.000646819*m.x266 - 0.00214428*m.x267
+ 0.00609509*m.x268 + 0.00587685*m.x269 + 0.00191072*m.x270 + 0.000970672*m.x271
+ 0.0045212*m.x272 - 0.00264895*m.x273 - 0.00122455*m.x274 - 0.00157959*m.x275
+ 0.00243935*m.x276 + 0.000446619*m.x277 + 0.00507279*m.x278 + 0.00996305*m.x279
+ 0.00582409*m.x280 + 0.0100077*m.x281 + 0.00713668*m.x282 - 0.00695821*m.x283
+ 0.00804511*m.x284 + 0.0045584*m.x285 + 0.00879099*m.x286 + 0.00389765*m.x287
+ 0.0126359*m.x288 + 0.00467816*m.x289 + 0.00586578*m.x290 + 0.0112814*m.x291
+ 0.00718189*m.x292 + 0.00473931*m.x293 + 0.0022565*m.x294 + 0.00361341*m.x295
+ 0.00304548*m.x296 - 0.000971214*m.x297 + 0.00232343*m.x298 + 0.0058115*m.x299
+ 0.000485725*m.x300 - 0.000130592*m.x301 + 0.0045291*m.x302 + 0.00868416*m.x303 == 0)
m.c249 = Constraint(expr= - m.x144 + 0.00300993*m.x204 - 0.00634068*m.x205 - 0.00295089*m.x206 + 0.0039211*m.x207
+ 0.00287456*m.x208 - 0.00156619*m.x209 + 0.00586835*m.x210 - 0.00135088*m.x211
+ 0.0103013*m.x212 - 0.000797116*m.x213 + 0.00650083*m.x214 + 0.00128983*m.x215
+ 0.000216218*m.x216 + 0.00521873*m.x217 + 0.00364998*m.x218 + 0.00480092*m.x219
+ 0.00358318*m.x220 - 0.00553215*m.x221 - 0.00116895*m.x222 - 0.00365224*m.x223
- 0.00122748*m.x224 - 0.00509823*m.x225 + 0.00630679*m.x226 + 0.00271139*m.x227
- 0.00210153*m.x228 + 5.78589E-5*m.x229 + 0.00189734*m.x230 + 0.00456291*m.x231
- 0.00298086*m.x232 + 0.0143482*m.x233 - 0.00101212*m.x234 + 0.00111236*m.x235
+ 0.00558802*m.x236 + 0.00021007*m.x237 + 0.000130711*m.x238 - 0.000760636*m.x239
- 0.00233255*m.x240 + 0.00141435*m.x241 + 0.00655255*m.x242 - 0.000440194*m.x243
+ 0.00327609*m.x244 + 0.00113112*m.x245 + 0.0741366*m.x246 - 0.00360297*m.x247
+ 0.00475321*m.x248 + 0.00490204*m.x249 + 0.00645328*m.x250 + 0.0235477*m.x251
+ 0.00185295*m.x252 - 0.00270753*m.x253 + 0.00282259*m.x254 - 0.0028989*m.x255
- 0.00279501*m.x256 + 0.00423442*m.x257 + 0.00201357*m.x258 + 0.00221836*m.x259
- 0.000338874*m.x260 + 0.000811554*m.x261 - 0.00415921*m.x262 + 0.0080163*m.x263
+ 0.00486963*m.x264 - 0.0011072*m.x265 - 0.00201067*m.x266 + 0.000797127*m.x267
+ 0.00333299*m.x268 + 0.0013567*m.x269 + 0.000671953*m.x270 + 0.00337629*m.x271
+ 0.000207882*m.x272 - 0.00430941*m.x273 + 0.00263722*m.x274 + 0.0157715*m.x275
- 0.00241116*m.x276 + 0.000537603*m.x277 - 0.00425708*m.x278 + 0.00705762*m.x279
- 0.000639079*m.x280 + 0.00378279*m.x281 + 0.00244117*m.x282 + 0.00776276*m.x283
- 0.000311621*m.x284 - 0.0011604*m.x285 + 0.000185014*m.x286 + 0.00122307*m.x287
+ 0.0034865*m.x288 + 0.00960237*m.x289 - 0.00545954*m.x290 - 0.000788822*m.x291
+ 0.000621542*m.x292 + 8.36128E-5*m.x293 + 0.00413836*m.x294 - 0.000118642*m.x295
+ 0.00364867*m.x296 - 0.00345963*m.x297 + 0.000712721*m.x298 + 0.00228836*m.x299
- 0.00517211*m.x300 + 0.00524662*m.x301 + 0.00987378*m.x302 - 0.00153163*m.x303 == 0)
m.c250 = Constraint(expr= - m.x145 - 0.00042207*m.x204 + 0.00394893*m.x205 - 0.00106603*m.x206 + 0.00224879*m.x207
+ 0.00538495*m.x208 + 0.00492319*m.x209 + 0.00190637*m.x210 + 0.00131418*m.x211
- 0.000803836*m.x212 + 0.000489977*m.x213 - 0.00223977*m.x214 + 0.0031567*m.x215
+ 0.00432057*m.x216 - 0.000963126*m.x217 + 0.00338155*m.x218 + 0.00282204*m.x219
+ 0.00160858*m.x220 + 0.00219745*m.x221 + 0.00510849*m.x222 + 0.00129769*m.x223
- 0.000508322*m.x224 - 0.00028965*m.x225 + 0.00288469*m.x226 + 0.00117205*m.x227
+ 0.000948894*m.x228 - 0.00235449*m.x229 - 0.00087259*m.x230 + 0.00077635*m.x231
+ 0.00139431*m.x232 + 0.00419847*m.x233 - 0.00163422*m.x234 + 0.00175884*m.x235
- 0.000174917*m.x236 + 0.00412244*m.x237 - 0.0013095*m.x238 + 0.00381839*m.x239
- 0.00284383*m.x240 + 0.00274745*m.x241 - 0.00182652*m.x242 + 0.00333395*m.x243
- 0.00135254*m.x244 + 0.00291832*m.x245 - 0.00360297*m.x246 + 0.0304025*m.x247
+ 0.00257258*m.x248 + 0.00793062*m.x249 + 0.00225214*m.x250 + 0.00173381*m.x251
+ 0.0025893*m.x252 + 0.00146414*m.x253 + 0.00619079*m.x254 - 0.000522178*m.x255
+ 0.00121952*m.x256 + 0.000349511*m.x257 + 0.000972283*m.x258 + 0.00145449*m.x259
- 0.000489457*m.x260 + 2.38348E-5*m.x261 + 0.000570035*m.x262 + 0.00228208*m.x263
+ 0.00212064*m.x264 + 0.00363109*m.x265 + 0.000619034*m.x266 - 0.000860656*m.x267
+ 0.00340102*m.x268 - 0.00197937*m.x269 + 0.000621111*m.x270 + 0.00199323*m.x271
+ 0.00314636*m.x272 - 0.000650527*m.x273 + 0.00194261*m.x274 - 0.00321407*m.x275
+ 0.000171403*m.x276 + 0.00364979*m.x277 + 0.00485946*m.x278 + 0.00796772*m.x279
+ 0.00166603*m.x280 + 0.00349167*m.x281 - 0.000466954*m.x282 - 0.00100195*m.x283
+ 0.00342181*m.x284 + 0.00300422*m.x285 - 0.00124986*m.x286 - 5.94885E-5*m.x287
+ 0.00328713*m.x288 + 0.00273221*m.x289 + 0.00345779*m.x290 + 0.00419154*m.x291
+ 0.00399493*m.x292 + 0.00448916*m.x293 + 0.00118132*m.x294 - 0.00106048*m.x295
+ 0.00275687*m.x296 - 0.00193635*m.x297 + 0.0035958*m.x298 - 0.000537039*m.x299
- 0.000271199*m.x300 - 0.00288422*m.x301 + 0.00223441*m.x302 + 0.00280782*m.x303 == 0)
m.c251 = Constraint(expr= - m.x146 + 0.0126161*m.x204 + 0.02189*m.x205 + 2.7433E-5*m.x206 + 0.00711934*m.x207
+ 0.00440483*m.x208 + 0.00205128*m.x209 + 0.00522821*m.x210 - 0.000872693*m.x211
+ 0.0174386*m.x212 + 0.00793697*m.x213 - 0.00874611*m.x214 - 0.00283528*m.x215
+ 0.012225*m.x216 + 0.0115852*m.x217 + 0.0027102*m.x218 + 0.00606924*m.x219
+ 0.00917394*m.x220 + 0.0156491*m.x221 + 0.0187115*m.x222 + 0.0109855*m.x223
+ 0.000118632*m.x224 + 0.0223632*m.x225 - 0.000683767*m.x226 - 0.00385233*m.x227
+ 0.00106856*m.x228 + 0.00327571*m.x229 + 0.00913902*m.x230 + 0.00142627*m.x231
+ 0.000596885*m.x232 + 0.00136868*m.x233 + 0.00938261*m.x234 + 0.00193995*m.x235
- 0.00127938*m.x236 + 0.00363406*m.x237 + 0.0163399*m.x238 + 0.00413739*m.x239
+ 0.00442326*m.x240 - 0.00109864*m.x241 + 0.0175505*m.x242 + 0.00339227*m.x243
+ 0.0166665*m.x244 + 0.00780343*m.x245 + 0.00475321*m.x246 + 0.00257258*m.x247
+ 0.333543*m.x248 + 0.00602288*m.x249 + 0.00486385*m.x250 + 0.0409265*m.x251
+ 0.00666557*m.x252 + 0.00172096*m.x253 + 0.00148516*m.x254 + 0.00818338*m.x255
+ 0.00375999*m.x256 + 0.00892913*m.x257 + 0.00635127*m.x258 + 0.00310111*m.x259
+ 0.0023572*m.x260 - 0.0124136*m.x261 - 0.00282737*m.x262 + 0.00109311*m.x263
+ 0.0171055*m.x264 - 0.000546877*m.x265 - 0.00127115*m.x266 - 0.00882959*m.x267
+ 0.00370779*m.x268 + 0.00220942*m.x269 - 0.0007257*m.x270 + 0.000362512*m.x271
+ 0.000666346*m.x272 + 0.00537778*m.x273 + 0.00435506*m.x274 + 0.0289633*m.x275
- 0.00793056*m.x276 - 0.00124997*m.x277 + 0.00600917*m.x278 + 0.00654889*m.x279
+ 0.0013566*m.x280 + 0.0145382*m.x281 + 0.00753084*m.x282 + 0.000994392*m.x283
- 0.0010613*m.x284 + 0.00748896*m.x285 + 0.0112013*m.x286 + 0.00952063*m.x287
- 0.00220101*m.x288 + 0.00611291*m.x289 - 0.00609654*m.x290 + 0.000316901*m.x291
+ 0.00160516*m.x292 + 0.00470546*m.x293 - 0.00380484*m.x294 - 0.00603313*m.x295
+ 0.00178999*m.x296 + 0.017123*m.x297 + 0.00424638*m.x298 + 0.0127695*m.x299
+ 0.00599775*m.x300 + 0.0107649*m.x301 + 0.00273511*m.x302 + 0.00174594*m.x303 == 0)
m.c252 = Constraint(expr= - m.x147 + 0.000539029*m.x204 - 0.00142123*m.x205 - 0.00324286*m.x206 + 0.000965714*m.x207
- 0.000705455*m.x208 + 0.0034346*m.x209 + 0.000518417*m.x210 + 0.000448292*m.x211
+ 0.00274013*m.x212 - 0.00236638*m.x213 - 0.00176148*m.x214 + 0.00355332*m.x215
+ 0.00282004*m.x216 + 0.00378529*m.x217 + 0.00285381*m.x218 + 0.0066067*m.x219
+ 0.0035766*m.x220 + 0.00559342*m.x221 + 0.000813106*m.x222 - 2.44696E-5*m.x223
+ 0.00252467*m.x224 + 0.00169098*m.x225 + 0.00438943*m.x226 + 0.00138166*m.x227
+ 0.00241905*m.x228 - 0.00357096*m.x229 + 0.000648204*m.x230 + 0.00217757*m.x231
- 0.000173936*m.x232 + 3.95557E-5*m.x233 + 0.00048899*m.x234 + 0.00582795*m.x235
- 0.000380482*m.x236 + 0.0025062*m.x237 + 0.00412922*m.x238 + 0.00695501*m.x239
+ 0.00224652*m.x240 + 0.0042909*m.x241 - 0.00564367*m.x242 + 0.00216846*m.x243
- 0.000715736*m.x244 + 0.00217772*m.x245 + 0.00490204*m.x246 + 0.00793062*m.x247
+ 0.00602288*m.x248 + 0.0286408*m.x249 + 0.00321708*m.x250 - 0.000649104*m.x251
+ 0.00220265*m.x252 + 0.000192602*m.x253 + 0.0056319*m.x254 + 0.00468117*m.x255
- 0.000284323*m.x256 + 0.00172826*m.x257 + 0.00393731*m.x258 + 0.00193608*m.x259
+ 0.00419589*m.x260 + 0.000305111*m.x261 - 0.000836327*m.x262 + 0.00132171*m.x263
+ 0.00254184*m.x264 + 0.00434758*m.x265 - 0.000143504*m.x266 - 0.00324401*m.x267
+ 0.00241411*m.x268 - 0.000256307*m.x269 + 0.00117147*m.x270 + 0.000577468*m.x271
+ 0.00154811*m.x272 - 0.000768089*m.x273 + 0.00319599*m.x274 + 0.00303778*m.x275
+ 0.00128681*m.x276 + 0.000718747*m.x277 - 0.000691613*m.x278 + 0.0060368*m.x279
+ 0.000899485*m.x280 + 0.00663248*m.x281 + 0.0010729*m.x282 + 0.006249*m.x283
+ 0.00265281*m.x284 + 0.00400057*m.x285 - 0.00122283*m.x286 + 0.000588542*m.x287
+ 0.00328499*m.x288 + 0.000580561*m.x289 + 0.000227831*m.x290 + 0.0066509*m.x291
+ 0.00019791*m.x292 + 0.00589171*m.x293 - 0.000623163*m.x294 - 7.87584E-5*m.x295
+ 0.00213016*m.x296 - 0.00403433*m.x297 + 0.00423746*m.x298 + 0.00337871*m.x299
+ 0.00204417*m.x300 + 0.00449024*m.x301 + 0.00140987*m.x302 + 0.00259129*m.x303 == 0)
m.c253 = Constraint(expr= - m.x148 + 0.00171572*m.x204 + 0.000952018*m.x205 + 0.0057922*m.x206 + 0.00724404*m.x207
+ 0.00591159*m.x208 + 0.00340814*m.x209 + 0.00229506*m.x210 - 0.00207556*m.x211
+ 0.00199163*m.x212 + 0.00351492*m.x213 + 0.00162467*m.x214 + 0.00303711*m.x215
+ 0.0010868*m.x216 + 0.00266115*m.x217 + 0.00231984*m.x218 + 0.00683528*m.x219
+ 0.00328833*m.x220 + 0.000136349*m.x221 + 0.0030329*m.x222 - 0.00162389*m.x223
+ 0.00317859*m.x224 + 0.00143324*m.x225 + 0.00306698*m.x226 + 0.001371*m.x227
+ 0.00317936*m.x228 - 0.0014774*m.x229 + 0.00369376*m.x230 + 0.00191957*m.x231
+ 0.00262989*m.x232 + 0.0072304*m.x233 + 0.00273794*m.x234 + 0.00221714*m.x235
+ 0.0022927*m.x236 + 0.00352758*m.x237 + 0.00247137*m.x238 + 0.0028489*m.x239
+ 0.000464028*m.x240 + 0.0039924*m.x241 + 0.00110388*m.x242 + 0.0060672*m.x243
+ 0.00244895*m.x244 + 0.0059976*m.x245 + 0.00645328*m.x246 + 0.00225214*m.x247
+ 0.00486385*m.x248 + 0.00321708*m.x249 + 0.0326124*m.x250 + 0.00473313*m.x251
+ 0.00461718*m.x252 + 0.0068865*m.x253 + 0.00250704*m.x254 + 0.00606702*m.x255
+ 0.000219255*m.x256 + 0.00287223*m.x257 + 0.00250699*m.x258 + 0.00176811*m.x259
+ 0.00192979*m.x260 + 2.4776E-5*m.x261 - 0.000659325*m.x262 + 0.00468844*m.x263
+ 0.00480861*m.x264 + 0.00487248*m.x265 - 0.00220491*m.x266 - 0.00289289*m.x267
+ 0.00758561*m.x268 + 0.00350318*m.x269 + 0.0034932*m.x270 + 0.00414106*m.x271
- 0.000776536*m.x272 - 0.00326844*m.x273 + 0.00321975*m.x274 + 0.00511975*m.x275
+ 0.0018167*m.x276 + 0.0015802*m.x277 + 0.00532914*m.x278 + 0.0052332*m.x279
+ 0.00121475*m.x280 + 0.00220381*m.x281 + 0.00145566*m.x282 - 0.000197051*m.x283
+ 0.00302341*m.x284 + 0.00322867*m.x285 + 0.0042178*m.x286 - 0.00044828*m.x287
+ 0.00548425*m.x288 + 0.00168605*m.x289 - 0.000888688*m.x290 + 0.004772*m.x291
+ 0.000505019*m.x292 + 0.00313289*m.x293 + 0.00119693*m.x294 + 0.00445284*m.x295
+ 0.00521004*m.x296 - 0.00282173*m.x297 + 0.00291792*m.x298 - 0.000120553*m.x299
+ 0.000967824*m.x300 + 0.000698762*m.x301 + 0.00432741*m.x302 + 0.00166067*m.x303 == 0)
m.c254 = Constraint(expr= - m.x149 + 0.00871066*m.x204 - 0.000699597*m.x205 + 0.0166603*m.x206 + 0.00718655*m.x207
+ 0.00637504*m.x208 + 0.00910415*m.x209 - 0.000868046*m.x210 - 0.00135891*m.x211
+ 0.0121972*m.x212 + 0.0269972*m.x213 + 0.00683673*m.x214 + 0.00993462*m.x215
+ 0.00141579*m.x216 + 0.0140797*m.x217 + 0.00363014*m.x218 + 0.000969236*m.x219
+ 0.00340781*m.x220 + 0.0130438*m.x221 + 0.0177681*m.x222 + 0.00351454*m.x223
- 0.00620603*m.x224 + 0.0060925*m.x225 + 0.0140371*m.x226 + 0.00194706*m.x227
+ 0.00580385*m.x228 - 0.000131234*m.x229 - 0.00141307*m.x230 + 0.0115101*m.x231
+ 0.00163586*m.x232 + 0.0127117*m.x233 + 0.0081173*m.x234 + 0.00143776*m.x235
+ 0.0147001*m.x236 + 0.00268179*m.x237 + 0.00232468*m.x238 + 0.00397424*m.x239
+ 0.00563646*m.x240 + 0.000223728*m.x241 + 0.00135794*m.x242 + 0.00195896*m.x243
+ 0.00980088*m.x244 + 0.00294803*m.x245 + 0.0235477*m.x246 + 0.00173381*m.x247
+ 0.0409265*m.x248 - 0.000649104*m.x249 + 0.00473313*m.x250 + 0.212813*m.x251
- 0.00571772*m.x252 - 9.80108E-5*m.x253 + 0.000713594*m.x254 - 0.000291411*m.x255
- 0.0028928*m.x256 + 0.00849788*m.x257 - 0.00393003*m.x258 + 0.0144913*m.x259
- 0.00133849*m.x260 - 0.00262538*m.x261 + 0.0025511*m.x262 + 0.0304485*m.x263
+ 0.00172909*m.x264 - 0.00455718*m.x265 - 0.000349801*m.x266 - 0.010277*m.x267
- 0.00203947*m.x268 + 0.00647039*m.x269 - 0.000334806*m.x270 - 0.000679271*m.x271
+ 0.0102058*m.x272 + 0.0132501*m.x273 + 0.00894547*m.x274 + 0.0211536*m.x275
- 0.000443774*m.x276 + 0.00327277*m.x277 + 0.00786226*m.x278 + 0.00909273*m.x279
+ 0.0049413*m.x280 + 0.00400317*m.x281 - 0.00680418*m.x282 + 0.0137323*m.x283
+ 0.00633139*m.x284 - 5.13418E-5*m.x285 + 0.0162123*m.x286 + 0.00880031*m.x287
- 0.00234105*m.x288 + 0.00247115*m.x289 + 0.00278431*m.x290 + 0.00463181*m.x291
+ 0.00075518*m.x292 - 0.00287996*m.x293 - 0.00533256*m.x294 - 0.00290057*m.x295
- 0.000529075*m.x296 + 0.000979263*m.x297 + 0.00309003*m.x298 + 0.00415618*m.x299
+ 0.00182144*m.x300 + 0.00336642*m.x301 + 0.000262547*m.x302 - 0.000847169*m.x303 == 0)
m.c255 = Constraint(expr= - m.x150 - 0.000658519*m.x204 + 0.00166555*m.x205 - 0.000651147*m.x206 + 0.00872243*m.x207
+ 0.00572145*m.x208 + 0.00203269*m.x209 + 0.00175605*m.x210 - 0.00277333*m.x211
+ 5.78285E-5*m.x212 + 0.0035179*m.x213 + 0.000473999*m.x214 + 0.00342858*m.x215
+ 0.00220267*m.x216 + 0.00578554*m.x217 + 0.00842352*m.x218 + 0.00589067*m.x219
+ 0.00725086*m.x220 + 0.00351709*m.x221 + 0.0056051*m.x222 - 0.00101164*m.x223
+ 4.22193E-5*m.x224 - 0.00143233*m.x225 + 0.00404018*m.x226 + 0.000567011*m.x227
+ 0.00417651*m.x228 + 0.00076644*m.x229 - 0.00209444*m.x230 - 0.000945371*m.x231
+ 0.000879524*m.x232 + 0.00781209*m.x233 + 0.00159047*m.x234 + 0.00796665*m.x235
- 0.000690034*m.x236 + 0.0017263*m.x237 + 0.00329108*m.x238 - 0.00183251*m.x239
+ 0.0023205*m.x240 + 0.00665241*m.x241 + 0.00288393*m.x242 + 0.00250112*m.x243
+ 0.00710031*m.x244 + 0.00552272*m.x245 + 0.00185295*m.x246 + 0.0025893*m.x247
+ 0.00666557*m.x248 + 0.00220265*m.x249 + 0.00461718*m.x250 - 0.00571772*m.x251
+ 0.0297052*m.x252 + 0.0133063*m.x253 + 0.00512875*m.x254 + 0.00511319*m.x255
+ 0.00128142*m.x256 + 0.0011758*m.x257 + 0.000185703*m.x258 + 0.000807728*m.x259
+ 0.00482243*m.x260 + 0.00671943*m.x261 + 0.0024249*m.x262 - 0.00576356*m.x263
+ 0.00615053*m.x264 + 0.00457997*m.x265 + 0.00116129*m.x266 - 0.00334468*m.x267
- 0.00177309*m.x268 + 0.00135912*m.x269 + 0.0055357*m.x270 + 0.00211564*m.x271
+ 0.0010794*m.x272 + 0.00192198*m.x273 + 0.00189277*m.x274 + 0.00643706*m.x275
+ 0.00398105*m.x276 + 0.000745003*m.x277 + 0.00524394*m.x278 + 0.00240223*m.x279
+ 0.00282459*m.x280 + 0.00472739*m.x281 + 0.000794467*m.x282 + 0.00387197*m.x283
+ 0.00198803*m.x284 + 0.00165035*m.x285 + 0.00321866*m.x286 + 0.000171898*m.x287
+ 0.00933104*m.x288 + 0.00315924*m.x289 + 0.00241389*m.x290 + 0.00336441*m.x291
+ 4.30958E-5*m.x292 + 0.00271535*m.x293 + 0.00462087*m.x294 + 0.00710323*m.x295
+ 0.000902586*m.x296 + 0.00233291*m.x297 + 0.00342174*m.x298 + 0.00618718*m.x299
+ 0.00291333*m.x300 - 0.00120359*m.x301 + 0.00135234*m.x302 - 0.000351985*m.x303 == 0)
m.c256 = Constraint(expr= - m.x151 + 0.00632557*m.x204 + 0.00413697*m.x205 + 0.0025737*m.x206 + 0.00911811*m.x207
+ 0.00369485*m.x208 - 0.000620515*m.x209 + 0.00453298*m.x210 + 0.00257709*m.x211
- 0.003034*m.x212 + 0.00199006*m.x213 + 0.00469908*m.x214 + 0.00462163*m.x215
+ 0.00354208*m.x216 + 0.00521587*m.x217 + 0.00670307*m.x218 + 0.0039247*m.x219
+ 0.00486144*m.x220 + 0.00107063*m.x221 - 0.0012575*m.x222 + 0.00584599*m.x223
+ 0.000472764*m.x224 + 0.00043714*m.x225 + 0.00262736*m.x226 + 0.0025858*m.x227
+ 0.00240856*m.x228 + 0.0033869*m.x229 + 0.000886721*m.x230 - 0.0071917*m.x231
+ 0.00125037*m.x232 + 0.00489662*m.x233 + 0.00666147*m.x234 + 0.00687732*m.x235
- 0.00340535*m.x236 + 0.0110796*m.x237 - 0.00197335*m.x238 + 0.00181348*m.x239
+ 0.00368711*m.x240 + 0.0109749*m.x241 + 0.000894389*m.x242 + 0.00342576*m.x243
+ 0.00623048*m.x244 + 0.00800356*m.x245 - 0.00270753*m.x246 + 0.00146414*m.x247
+ 0.00172096*m.x248 + 0.000192602*m.x249 + 0.0068865*m.x250 - 9.80108E-5*m.x251
+ 0.0133063*m.x252 + 0.0509447*m.x253 - 0.000905573*m.x254 + 0.00584973*m.x255
+ 0.00164159*m.x256 + 0.00170257*m.x257 + 0.00491697*m.x258 + 0.00333082*m.x259
+ 0.00312286*m.x260 + 0.00513272*m.x261 + 0.00511337*m.x262 + 0.00111281*m.x263
+ 0.00524869*m.x264 + 0.00756756*m.x265 + 0.00467689*m.x266 - 0.00212043*m.x267
- 0.000146116*m.x268 + 0.00271306*m.x269 + 0.00797013*m.x270 + 0.00107585*m.x271
+ 0.00588583*m.x272 + 0.00326447*m.x273 + 0.000829669*m.x274 + 0.00442436*m.x275
+ 0.00505109*m.x276 + 0.00575919*m.x277 + 0.00235758*m.x278 + 0.00674287*m.x279
+ 0.0017513*m.x280 + 0.00529534*m.x281 + 0.00205383*m.x282 + 0.00641984*m.x283
+ 0.00684435*m.x284 + 0.00461578*m.x285 + 0.0119365*m.x286 + 0.00806339*m.x287
+ 0.0103044*m.x288 + 0.00439893*m.x289 + 0.00688742*m.x290 + 0.00194067*m.x291
+ 0.00365679*m.x292 + 0.000101984*m.x293 + 0.00583528*m.x294 + 0.00511653*m.x295
+ 0.00527957*m.x296 + 0.00036941*m.x297 + 0.0020713*m.x298 + 0.00787258*m.x299
+ 0.00426053*m.x300 - 0.00268282*m.x301 + 0.0035967*m.x302 + 0.0019922*m.x303 == 0)
m.c257 = Constraint(expr= - m.x152 - 1.12481E-5*m.x204 + 0.0028476*m.x205 + 0.00277017*m.x206 + 0.000986175*m.x207
+ 0.00550813*m.x208 + 0.00733867*m.x209 + 0.000256242*m.x210 + 0.00198123*m.x211
- 0.00256942*m.x212 + 0.00140166*m.x213 + 0.00361612*m.x214 + 0.000325927*m.x215
+ 0.00742831*m.x216 + 0.00590839*m.x217 + 0.00139386*m.x218 + 0.0022817*m.x219
+ 0.0037492*m.x220 - 0.00237286*m.x221 + 0.000154419*m.x222 + 0.00280841*m.x223
+ 0.00178849*m.x224 - 0.00162284*m.x225 + 0.00352108*m.x226 + 0.00360694*m.x227
- 0.000398367*m.x228 - 0.00261102*m.x229 - 0.00204134*m.x230 + 0.00172599*m.x231
+ 0.00165426*m.x232 + 0.000468232*m.x233 - 0.000935815*m.x234 + 0.00952368*m.x235
- 0.00483173*m.x236 + 0.00388802*m.x237 + 0.000239144*m.x238 - 0.00235222*m.x239
+ 0.00446507*m.x240 - 0.00020878*m.x241 - 0.00340572*m.x242 - 0.000387287*m.x243
+ 0.00150226*m.x244 + 0.00202451*m.x245 + 0.00282259*m.x246 + 0.00619079*m.x247
+ 0.00148516*m.x248 + 0.0056319*m.x249 + 0.00250704*m.x250 + 0.000713594*m.x251
+ 0.00512875*m.x252 - 0.000905573*m.x253 + 0.035183*m.x254 + 0.00386613*m.x255
- 0.00135527*m.x256 + 0.000782363*m.x257 + 0.00154289*m.x258 + 0.000170573*m.x259
- 1.5116E-5*m.x260 + 0.00158604*m.x261 + 0.00141472*m.x262 + 0.00398684*m.x263
+ 0.00758869*m.x264 + 0.00417238*m.x265 - 0.00108104*m.x266 - 0.00298459*m.x267
- 0.00134772*m.x268 + 0.000740512*m.x269 - 0.000683822*m.x270 + 0.00203828*m.x271
+ 0.00143493*m.x272 - 0.00250979*m.x273 + 0.000544328*m.x274 - 0.0016811*m.x275
+ 0.000307144*m.x276 + 0.00312743*m.x277 - 0.000215375*m.x278 + 0.00123286*m.x279
+ 0.00131588*m.x280 + 0.00669716*m.x281 - 0.000981274*m.x282 + 0.00185637*m.x283
+ 0.00200309*m.x284 + 0.00274343*m.x285 + 0.00419778*m.x286 + 0.0011744*m.x287
+ 0.000952343*m.x288 + 0.00341538*m.x289 - 0.00226972*m.x290 + 0.00121543*m.x291
+ 0.00119416*m.x292 + 0.00550828*m.x293 + 0.00304948*m.x294 + 0.00596306*m.x295
+ 0.000603395*m.x296 - 0.00367719*m.x297 + 0.00134408*m.x298 + 0.00265743*m.x299
+ 0.00432502*m.x300 + 0.00252096*m.x301 + 0.00261792*m.x302 + 0.00239977*m.x303 == 0)
m.c258 = Constraint(expr= - m.x153 + 0.00423842*m.x204 + 0.0144721*m.x205 - 0.000313893*m.x206 + 0.00380874*m.x207
+ 0.00767889*m.x208 - 0.00376408*m.x209 + 0.00201038*m.x210 - 0.00692894*m.x211
+ 0.00344538*m.x212 - 0.00266851*m.x213 + 0.0154276*m.x214 + 0.00380006*m.x215
+ 0.00170043*m.x216 + 0.00535654*m.x217 - 0.00427335*m.x218 - 0.00171385*m.x219
+ 0.00232852*m.x220 + 0.0053206*m.x221 - 0.00245765*m.x222 + 0.0134036*m.x223
+ 0.000750734*m.x224 + 0.000785002*m.x225 + 0.00118551*m.x226 + 0.00465088*m.x227
- 0.000713633*m.x228 + 0.00970161*m.x229 + 0.000825909*m.x230 + 0.00211256*m.x231
+ 0.00460974*m.x232 + 0.00699772*m.x233 + 0.00366551*m.x234 - 0.000273013*m.x235
+ 0.00228568*m.x236 - 0.00663898*m.x237 + 0.00326997*m.x238 + 0.00373008*m.x239
+ 0.00335461*m.x240 + 0.000913669*m.x241 + 0.0231518*m.x242 + 0.000121531*m.x243
+ 0.00314883*m.x244 + 0.00875321*m.x245 - 0.0028989*m.x246 - 0.000522178*m.x247
+ 0.00818338*m.x248 + 0.00468117*m.x249 + 0.00606702*m.x250 - 0.000291411*m.x251
+ 0.00511319*m.x252 + 0.00584973*m.x253 + 0.00386613*m.x254 + 0.148268*m.x255
- 0.00308793*m.x256 - 0.00368823*m.x257 + 0.00287582*m.x258 + 0.00455641*m.x259
+ 0.00619463*m.x260 - 0.0103266*m.x261 - 0.0114865*m.x262 + 0.0134795*m.x263
+ 0.00420593*m.x264 + 0.000449462*m.x265 - 0.00387947*m.x266 - 0.00136751*m.x267
+ 0.00497244*m.x268 - 0.000113863*m.x269 - 0.00136059*m.x270 - 0.00252786*m.x271
- 0.00391423*m.x272 - 0.0125749*m.x273 + 0.00401374*m.x274 + 0.00592187*m.x275
+ 0.00168744*m.x276 + 0.00949071*m.x277 + 0.000384402*m.x278 - 0.00446796*m.x279
+ 0.0023511*m.x280 + 0.00116828*m.x281 + 6.81408E-5*m.x282 - 0.00245755*m.x283
+ 0.0117758*m.x284 - 0.000210065*m.x285 + 0.0058935*m.x286 + 0.00461282*m.x287
+ 0.00333587*m.x288 + 0.00601159*m.x289 - 0.00295399*m.x290 + 0.0231083*m.x291
+ 0.00273013*m.x292 + 0.00101519*m.x293 + 0.00177864*m.x294 + 0.00342669*m.x295
- 0.00362052*m.x296 - 0.00643522*m.x297 + 0.00632524*m.x298 + 0.0195511*m.x299
- 0.00071887*m.x300 - 0.00217301*m.x301 + 0.00440766*m.x302 + 0.00538072*m.x303 == 0)
m.c259 = Constraint(expr= - m.x154 - 0.000128391*m.x204 + 0.00231785*m.x205 - 0.00295718*m.x206 + 0.00525484*m.x207
+ 0.00218657*m.x208 + 0.00661222*m.x209 + 0.00317659*m.x210 + 0.00230237*m.x211
- 0.00251303*m.x212 + 6.78972E-5*m.x213 + 0.000184285*m.x214 + 0.0148337*m.x215
+ 0.00440633*m.x216 - 0.00175238*m.x217 + 0.00257792*m.x218 + 0.00197531*m.x219
+ 0.00597841*m.x220 - 0.000402279*m.x221 - 0.00827052*m.x222 - 0.00167752*m.x223
+ 0.00537508*m.x224 + 0.000881467*m.x225 + 0.000446955*m.x226 + 0.00215308*m.x227
+ 0.00299454*m.x228 + 0.00144094*m.x229 + 0.00279365*m.x230 + 0.00136592*m.x231
- 0.00113943*m.x232 + 0.00356967*m.x233 + 0.00954228*m.x234 + 0.00106084*m.x235
- 0.00083261*m.x236 + 0.00271133*m.x237 - 0.0010155*m.x238 + 0.00394493*m.x239
+ 0.00612415*m.x240 + 0.0037812*m.x241 + 0.00932518*m.x242 + 0.00270791*m.x243
- 0.00202199*m.x244 + 0.00341817*m.x245 - 0.00279501*m.x246 + 0.00121952*m.x247
+ 0.00375999*m.x248 - 0.000284323*m.x249 + 0.000219255*m.x250 - 0.0028928*m.x251
+ 0.00128142*m.x252 + 0.00164159*m.x253 - 0.00135527*m.x254 - 0.00308793*m.x255
+ 0.0587222*m.x256 + 0.00349217*m.x257 + 0.00343019*m.x258 + 0.00474389*m.x259
+ 0.000983317*m.x260 + 0.00104681*m.x261 + 0.000573155*m.x262 + 0.002681*m.x263
+ 0.00396062*m.x264 + 0.00572913*m.x265 + 0.011585*m.x266 - 0.00253899*m.x267
+ 0.00246284*m.x268 + 0.0021298*m.x269 + 0.00233754*m.x270 + 0.00563448*m.x271
+ 0.00602755*m.x272 + 0.00350973*m.x273 + 0.00383568*m.x274 - 0.00440784*m.x275
+ 0.0017901*m.x276 + 0.00137853*m.x277 + 5.46446E-5*m.x278 - 0.000579361*m.x279
+ 0.000918975*m.x280 + 0.00676102*m.x281 - 0.00488771*m.x282 - 0.000420988*m.x283
- 0.00234208*m.x284 + 0.00819901*m.x285 + 0.00341215*m.x286 + 0.00259963*m.x287
- 0.00185458*m.x288 + 0.00165765*m.x289 + 0.0036396*m.x290 + 0.00499705*m.x291
+ 0.000213845*m.x292 + 0.00251321*m.x293 + 7.57559E-5*m.x294 + 0.00429343*m.x295
+ 0.00214085*m.x296 - 0.00145961*m.x297 + 0.00499227*m.x298 - 0.00212278*m.x299
+ 0.00204967*m.x300 + 0.00120533*m.x301 - 0.00154274*m.x302 + 0.000846548*m.x303 == 0)
m.c260 = Constraint(expr= - m.x155 + 0.00428623*m.x204 - 0.00165532*m.x205 + 0.00301212*m.x206 + 0.00057863*m.x207
+ 0.00216232*m.x208 + 0.000748379*m.x209 + 0.00404808*m.x210 + 0.00443474*m.x211
+ 0.00434833*m.x212 + 0.000714092*m.x213 + 0.00199166*m.x214 + 0.00117377*m.x215
+ 0.0235152*m.x216 + 0.0118357*m.x217 + 0.00556967*m.x218 + 0.00432474*m.x219
+ 0.00987396*m.x220 + 0.00364206*m.x221 + 0.00821977*m.x222 - 0.00494624*m.x223
+ 0.00171337*m.x224 + 0.00197703*m.x225 + 0.000454264*m.x226 + 0.000889199*m.x227
+ 2.45482E-5*m.x228 + 0.00194079*m.x229 - 0.00235578*m.x230 + 0.00392595*m.x231
- 0.00176703*m.x232 + 0.000303537*m.x233 + 0.000832645*m.x234 - 0.00338076*m.x235
- 0.00120821*m.x236 + 0.00151359*m.x237 + 0.000659488*m.x238 + 0.00375855*m.x239
+ 0.00459437*m.x240 + 0.00342695*m.x241 + 0.00712405*m.x242 + 0.00249349*m.x243
+ 0.00535529*m.x244 + 0.00331148*m.x245 + 0.00423442*m.x246 + 0.000349511*m.x247
+ 0.00892913*m.x248 + 0.00172826*m.x249 + 0.00287223*m.x250 + 0.00849788*m.x251
+ 0.0011758*m.x252 + 0.00170257*m.x253 + 0.000782363*m.x254 - 0.00368823*m.x255
+ 0.00349217*m.x256 + 0.11404*m.x257 + 0.00289374*m.x258 + 0.00694813*m.x259
+ 0.00399238*m.x260 - 0.00363536*m.x261 + 0.00106667*m.x262 + 0.00663715*m.x263
+ 0.0123785*m.x264 + 0.0075057*m.x265 + 0.00222301*m.x266 - 0.0077448*m.x267
- 0.00502038*m.x268 - 0.000552918*m.x269 + 0.00395004*m.x270 + 0.00631844*m.x271
+ 0.00744533*m.x272 + 0.00619991*m.x273 + 0.00217002*m.x274 - 0.00114793*m.x275
+ 0.00280667*m.x276 + 0.00187548*m.x277 + 0.00626037*m.x278 + 0.00865879*m.x279
- 0.00113185*m.x280 + 0.0225093*m.x281 + 0.000921016*m.x282 + 0.000728519*m.x283
- 0.00445797*m.x284 + 0.00436349*m.x285 + 0.00564621*m.x286 + 0.00194367*m.x287
- 0.0052063*m.x288 + 0.00164762*m.x289 - 0.000112278*m.x290 - 0.000255111*m.x291
+ 0.00261688*m.x292 + 0.00246219*m.x293 + 0.00318467*m.x294 + 0.00561083*m.x295
+ 0.00262766*m.x296 + 0.00179022*m.x297 + 0.00558577*m.x298 - 0.000513059*m.x299
+ 0.00353794*m.x300 + 0.00615137*m.x301 + 0.000877291*m.x302 + 0.000931697*m.x303 == 0)
m.c261 = Constraint(expr= - m.x156 + 0.00221565*m.x204 + 0.00730008*m.x205 - 0.00536586*m.x206 - 0.00473576*m.x207
+ 0.00209557*m.x208 - 0.000634982*m.x209 + 0.0020328*m.x210 - 0.000282204*m.x211
+ 0.000197585*m.x212 + 0.00214786*m.x213 + 0.00473067*m.x214 - 0.00687953*m.x215
- 0.000939116*m.x216 - 0.00574135*m.x217 + 0.00318181*m.x218 + 0.000289832*m.x219
+ 0.00154537*m.x220 - 0.00408056*m.x221 + 0.00502581*m.x222 + 0.00359045*m.x223
- 0.000500867*m.x224 - 0.00185612*m.x225 + 0.00404046*m.x226 + 0.00376111*m.x227
+ 0.00534951*m.x228 - 0.00202281*m.x229 + 0.00110642*m.x230 + 0.00691999*m.x231
+ 0.00271945*m.x232 + 0.000702332*m.x233 - 0.000876097*m.x234 + 0.00179605*m.x235
- 0.00293263*m.x236 + 0.00375338*m.x237 + 0.000561626*m.x238 + 0.00224988*m.x239
+ 0.000431036*m.x240 + 0.0012954*m.x241 + 0.00147782*m.x242 + 0.00562279*m.x243
- 0.000606735*m.x244 + 0.00151183*m.x245 + 0.00201357*m.x246 + 0.000972283*m.x247
+ 0.00635127*m.x248 + 0.00393731*m.x249 + 0.00250699*m.x250 - 0.00393003*m.x251
+ 0.000185703*m.x252 + 0.00491697*m.x253 + 0.00154289*m.x254 + 0.00287582*m.x255
+ 0.00343019*m.x256 + 0.00289374*m.x257 + 0.0510981*m.x258 - 0.000435255*m.x259
+ 0.00546829*m.x260 + 0.0102474*m.x261 - 0.00356388*m.x262 + 0.0065357*m.x263
+ 0.00129358*m.x264 + 0.00744467*m.x265 + 0.00063742*m.x266 - 0.000760534*m.x267
- 0.00149672*m.x268 + 0.00371467*m.x269 + 0.000163938*m.x270 + 0.00082375*m.x271
- 0.00321542*m.x272 + 0.00553702*m.x273 + 0.00147133*m.x274 + 0.00854643*m.x275
- 0.00206724*m.x276 + 0.00150074*m.x277 + 0.00174514*m.x278 + 0.00367872*m.x279
+ 0.00492691*m.x280 - 0.00258072*m.x281 + 0.00261019*m.x282 + 0.00168293*m.x283
+ 0.00651943*m.x284 - 0.000228966*m.x285 + 0.00685513*m.x286 + 0.00349243*m.x287
+ 0.00208497*m.x288 + 0.000860289*m.x289 + 0.00190276*m.x290 + 0.00214593*m.x291
+ 0.00371348*m.x292 + 0.00255756*m.x293 - 0.00201343*m.x294 - 0.0015187*m.x295
- 0.000662009*m.x296 - 0.00258788*m.x297 - 0.00124882*m.x298 + 0.00446219*m.x299
+ 0.000269906*m.x300 - 6.39913E-6*m.x301 + 0.00128816*m.x302 + 0.00584908*m.x303 == 0)
m.c262 = Constraint(expr= - m.x157 + 0.00293236*m.x204 + 0.00370628*m.x205 + 0.00927864*m.x206 + 0.0100543*m.x207
+ 0.00511289*m.x208 + 0.00346952*m.x209 + 0.0100104*m.x210 + 0.00426487*m.x211
- 0.00378844*m.x212 + 0.00560907*m.x213 + 0.00558883*m.x214 + 0.00217715*m.x215
+ 0.00368368*m.x216 + 0.00238201*m.x217 + 0.00773217*m.x218 + 0.000627748*m.x219
+ 0.000407484*m.x220 + 0.0110762*m.x221 + 0.0006738*m.x222 - 0.00517133*m.x223
+ 0.000990598*m.x224 + 0.00538296*m.x225 + 0.00192016*m.x226 + 0.00798442*m.x227
+ 0.00571568*m.x228 + 0.00652913*m.x229 + 0.00225416*m.x230 + 0.0106189*m.x231
- 0.00103376*m.x232 + 0.00357718*m.x233 + 0.0047508*m.x234 + 0.00600138*m.x235
+ 0.0100916*m.x236 + 0.00325149*m.x237 + 0.000752009*m.x238 + 0.00173868*m.x239
+ 0.0214193*m.x240 + 0.00902766*m.x241 - 0.000544689*m.x242 + 0.00307201*m.x243
+ 0.00976436*m.x244 + 0.0063979*m.x245 + 0.00221836*m.x246 + 0.00145449*m.x247
+ 0.00310111*m.x248 + 0.00193608*m.x249 + 0.00176811*m.x250 + 0.0144913*m.x251
+ 0.000807728*m.x252 + 0.00333082*m.x253 + 0.000170573*m.x254 + 0.00455641*m.x255
+ 0.00474389*m.x256 + 0.00694813*m.x257 - 0.000435255*m.x258 + 0.0472411*m.x259
+ 0.00464689*m.x260 + 0.001543*m.x261 + 0.00337863*m.x262 + 0.00769769*m.x263
+ 0.00318644*m.x264 + 0.00233055*m.x265 + 0.00263152*m.x266 - 0.00597953*m.x267
+ 0.00551452*m.x268 + 0.00394894*m.x269 + 0.0024981*m.x270 + 0.00562702*m.x271
+ 0.00231435*m.x272 + 0.00405522*m.x273 + 0.00465177*m.x274 + 0.00507821*m.x275
+ 0.00524954*m.x276 + 0.000811673*m.x277 - 0.00221712*m.x278 + 0.00179629*m.x279
+ 0.0049631*m.x280 + 0.00316822*m.x281 - 0.00271758*m.x282 + 2.01133E-5*m.x283
+ 0.00508838*m.x284 + 0.00528738*m.x285 + 0.00177656*m.x286 + 0.00390817*m.x287
+ 0.00522697*m.x288 + 0.00419445*m.x289 + 0.00330037*m.x290 + 0.00952656*m.x291
+ 0.00213073*m.x292 - 0.00172869*m.x293 + 0.00143223*m.x294 + 0.00862894*m.x295
+ 0.000135119*m.x296 - 0.00196723*m.x297 + 0.00166645*m.x298 + 0.0017984*m.x299
+ 0.00455272*m.x300 - 0.0033299*m.x301 + 0.00426249*m.x302 + 0.00227416*m.x303 == 0)
m.c263 = Constraint(expr= - m.x158 + 0.00642301*m.x204 + 0.00688037*m.x205 - 0.00108853*m.x206 + 0.00543729*m.x207
+ 0.00375052*m.x208 + 0.00833195*m.x209 + 0.00586558*m.x210 - 0.000987702*m.x211
+ 0.00163113*m.x212 - 0.000690724*m.x213 + 0.0104591*m.x214 + 0.00358463*m.x215
+ 0.00545833*m.x216 + 0.00580515*m.x217 + 0.00457572*m.x218 + 0.00188754*m.x219
+ 0.00757036*m.x220 + 0.00162771*m.x221 + 0.00519536*m.x222 + 0.00599997*m.x223
+ 0.00340317*m.x224 + 0.00350559*m.x225 + 0.00725634*m.x226 + 0.00414154*m.x227
+ 0.00328284*m.x228 - 0.000637013*m.x229 - 0.000609378*m.x230 - 0.000182055*m.x231
- 0.000944225*m.x232 + 0.00454768*m.x233 - 0.00109579*m.x234 + 0.00499556*m.x235
- 0.000975461*m.x236 + 0.00083169*m.x237 + 0.0012213*m.x238 + 0.00334586*m.x239
+ 0.00347374*m.x240 + 0.00635346*m.x241 + 0.00242014*m.x242 + 0.00538657*m.x243
+ 0.00469016*m.x244 + 0.00583129*m.x245 - 0.000338874*m.x246 - 0.000489457*m.x247
+ 0.0023572*m.x248 + 0.00419589*m.x249 + 0.00192979*m.x250 - 0.00133849*m.x251
+ 0.00482243*m.x252 + 0.00312286*m.x253 - 1.5116E-5*m.x254 + 0.00619463*m.x255
+ 0.000983317*m.x256 + 0.00399238*m.x257 + 0.00546829*m.x258 + 0.00464689*m.x259
+ 0.0362593*m.x260 - 0.000947867*m.x261 + 0.00518283*m.x262 - 0.000436247*m.x263
+ 0.0022354*m.x264 - 0.00334067*m.x265 + 0.00637109*m.x266 - 0.0012203*m.x267
+ 0.00130759*m.x268 + 0.00231089*m.x269 + 0.00364342*m.x270 + 0.00391626*m.x271
- 0.000228137*m.x272 - 0.000486291*m.x273 + 0.00136233*m.x274 + 0.00619112*m.x275
- 0.000663369*m.x276 + 0.00593263*m.x277 + 0.00236031*m.x278 - 0.000221372*m.x279
+ 0.00231411*m.x280 + 0.00764311*m.x281 + 0.000965316*m.x282 + 0.00959794*m.x283
+ 0.000370277*m.x284 + 0.00152795*m.x285 + 0.00378016*m.x286 + 0.00380959*m.x287
+ 0.00449849*m.x288 + 0.00350555*m.x289 + 0.00353625*m.x290 + 0.00557726*m.x291
+ 0.00162287*m.x292 + 0.00118145*m.x293 + 0.0018647*m.x294 + 0.00331591*m.x295
+ 0.00502936*m.x296 + 0.00976419*m.x297 + 0.00514689*m.x298 + 0.00345782*m.x299
+ 0.00507329*m.x300 - 0.00213912*m.x301 - 0.00213196*m.x302 + 0.00211323*m.x303 == 0)
m.c264 = Constraint(expr= - m.x159 - 0.00424851*m.x204 - 0.00522018*m.x205 + 0.00791765*m.x206 + 0.00571189*m.x207
- 0.000396528*m.x208 - 0.00565329*m.x209 + 0.00391134*m.x210 + 0.00520545*m.x211
+ 0.00153282*m.x212 + 0.0101136*m.x213 + 0.00117382*m.x214 + 0.0045967*m.x215
+ 0.0122466*m.x216 + 0.00233877*m.x217 + 0.00300847*m.x218 + 0.0083923*m.x219
+ 0.00514005*m.x220 + 0.000383935*m.x221 - 0.00068674*m.x222 + 0.000340114*m.x223
+ 0.00300201*m.x224 + 0.00104134*m.x225 + 0.0130293*m.x226 + 0.00118993*m.x227
+ 0.00871742*m.x228 - 0.00101439*m.x229 + 0.00251465*m.x230 + 0.00218491*m.x231
+ 0.00264501*m.x232 + 0.00483103*m.x233 - 0.000240979*m.x234 + 0.00310331*m.x235
+ 4.58518E-6*m.x236 - 5.91301E-5*m.x237 - 3.22002E-5*m.x238 - 0.00132202*m.x239
+ 0.00358454*m.x240 + 0.00329425*m.x241 - 0.000399422*m.x242 + 0.00391396*m.x243
+ 0.0113975*m.x244 - 0.00449059*m.x245 + 0.000811554*m.x246 + 2.38348E-5*m.x247
- 0.0124136*m.x248 + 0.000305111*m.x249 + 2.4776E-5*m.x250 - 0.00262538*m.x251
+ 0.00671943*m.x252 + 0.00513272*m.x253 + 0.00158604*m.x254 - 0.0103266*m.x255
+ 0.00104681*m.x256 - 0.00363536*m.x257 + 0.0102474*m.x258 + 0.001543*m.x259
- 0.000947867*m.x260 + 0.13711*m.x261 + 0.00151254*m.x262 + 0.00512402*m.x263
+ 0.00132205*m.x264 + 0.0109022*m.x265 - 0.00347997*m.x266 - 0.00396798*m.x267
+ 0.00540898*m.x268 + 0.00276138*m.x269 + 0.00118344*m.x270 + 0.00360731*m.x271
- 0.00260459*m.x272 + 0.000489283*m.x273 + 0.0019333*m.x274 + 0.00139414*m.x275
- 0.000354506*m.x276 + 0.00179872*m.x277 + 0.00283392*m.x278 - 0.000614375*m.x279
+ 0.00131236*m.x280 + 0.00470546*m.x281 - 0.00479156*m.x282 - 0.000175807*m.x283
- 4.69764E-5*m.x284 + 0.00535958*m.x285 - 0.00150618*m.x286 + 0.00164593*m.x287
- 0.00323282*m.x288 + 0.00658013*m.x289 + 0.00524124*m.x290 + 0.00454456*m.x291
+ 0.00520983*m.x292 + 0.00135714*m.x293 + 0.00263088*m.x294 + 0.00871316*m.x295
+ 0.00786502*m.x296 + 0.000809943*m.x297 + 0.000294055*m.x298 + 0.0093328*m.x299
+ 0.000154729*m.x300 + 1.07515E-5*m.x301 + 0.00396114*m.x302 - 0.00289961*m.x303 == 0)
m.c265 = Constraint(expr= - m.x160 + 0.00130686*m.x204 + 0.00111515*m.x205 - 0.00783196*m.x206 - 0.00276324*m.x207
- 0.00165313*m.x208 + 0.00331464*m.x209 - 0.00108095*m.x210 - 0.00343631*m.x211
+ 0.00412394*m.x212 + 0.00176469*m.x213 + 0.000451696*m.x214 - 0.00148924*m.x215
- 0.0045062*m.x216 + 0.000706233*m.x217 - 0.000803621*m.x218 - 8.3506E-5*m.x219
- 0.00145659*m.x220 + 0.00454443*m.x221 - 0.00422415*m.x222 - 0.00454905*m.x223
+ 0.00379494*m.x224 - 0.00208082*m.x225 + 0.00131963*m.x226 - 0.00274497*m.x227
+ 0.00237906*m.x228 - 0.0082225*m.x229 + 0.00102978*m.x230 + 0.000656633*m.x231
- 0.00260547*m.x232 - 0.00605986*m.x233 + 0.00232308*m.x234 + 0.0058288*m.x235
+ 0.00679259*m.x236 + 0.00581394*m.x237 - 0.00148681*m.x238 - 0.00379641*m.x239
+ 0.000513289*m.x240 + 0.00481242*m.x241 - 0.0010186*m.x242 - 0.00159432*m.x243
+ 0.00680033*m.x244 - 0.000373896*m.x245 - 0.00415921*m.x246 + 0.000570035*m.x247
- 0.00282737*m.x248 - 0.000836327*m.x249 - 0.000659325*m.x250 + 0.0025511*m.x251
+ 0.0024249*m.x252 + 0.00511337*m.x253 + 0.00141472*m.x254 - 0.0114865*m.x255
+ 0.000573155*m.x256 + 0.00106667*m.x257 - 0.00356388*m.x258 + 0.00337863*m.x259
+ 0.00518283*m.x260 + 0.00151254*m.x261 + 0.252156*m.x262 - 0.00414992*m.x263
- 0.00331763*m.x264 + 0.00422071*m.x265 - 0.00540834*m.x266 + 0.251509*m.x267
+ 0.00146019*m.x268 - 0.00206428*m.x269 + 8.81979E-5*m.x270 + 0.000290516*m.x271
+ 0.00222724*m.x272 + 0.00327562*m.x273 - 0.00467757*m.x274 - 0.00306634*m.x275
- 0.00382859*m.x276 - 0.00129787*m.x277 - 0.00372436*m.x278 + 0.00351785*m.x279
+ 7.90391E-5*m.x280 - 0.00511468*m.x281 + 0.00410639*m.x282 - 0.00321313*m.x283
+ 0.00241956*m.x284 + 0.00469951*m.x285 - 0.000587868*m.x286 - 0.0046356*m.x287
+ 0.00523023*m.x288 + 0.0033164*m.x289 + 0.00630061*m.x290 + 0.00551966*m.x291
+ 0.00626743*m.x292 + 0.00507348*m.x293 - 0.00112337*m.x294 - 0.0002988*m.x295
- 0.00107607*m.x296 - 0.00762971*m.x297 - 0.00163559*m.x298 - 0.00594877*m.x299
+ 0.000798834*m.x300 + 0.00532067*m.x301 + 0.001777*m.x302 - 0.00273965*m.x303 == 0)
m.c266 = Constraint(expr= - m.x161 + 0.0135606*m.x204 + 0.00698037*m.x205 + 0.0121474*m.x206 + 0.00810983*m.x207
+ 0.00186935*m.x208 + 0.00521247*m.x209 + 0.00196227*m.x210 - 0.00282907*m.x211
- 0.00179846*m.x212 + 0.0157962*m.x213 + 0.00029335*m.x214 + 0.00257797*m.x215
+ 0.0102645*m.x216 - 0.0039908*m.x217 - 0.00429132*m.x218 - 0.00071125*m.x219
- 0.00148186*m.x220 - 0.00276585*m.x221 - 0.000614559*m.x222 + 0.00626921*m.x223
+ 0.00286059*m.x224 + 0.00622953*m.x225 + 0.00472747*m.x226 - 0.000595349*m.x227
+ 0.00268782*m.x228 + 0.00355615*m.x229 + 0.0112079*m.x230 + 0.0175771*m.x231
+ 0.0017848*m.x232 + 0.00108709*m.x233 + 0.0118189*m.x234 + 0.00581735*m.x235
+ 0.0109441*m.x236 + 0.00200882*m.x237 + 0.00211146*m.x238 + 0.00586093*m.x239
+ 0.00739902*m.x240 + 0.00100992*m.x241 + 0.00402009*m.x242 + 0.00192515*m.x243
- 0.00297392*m.x244 + 0.00465423*m.x245 + 0.0080163*m.x246 + 0.00228208*m.x247
+ 0.00109311*m.x248 + 0.00132171*m.x249 + 0.00468844*m.x250 + 0.0304485*m.x251
- 0.00576356*m.x252 + 0.00111281*m.x253 + 0.00398684*m.x254 + 0.0134795*m.x255
+ 0.002681*m.x256 + 0.00663715*m.x257 + 0.0065357*m.x258 + 0.00769769*m.x259
- 0.000436247*m.x260 + 0.00512402*m.x261 - 0.00414992*m.x262 + 0.0874887*m.x263
+ 0.00654843*m.x264 - 0.000185811*m.x265 - 0.00273039*m.x266 - 0.00103049*m.x267
+ 0.00524602*m.x268 + 0.00624277*m.x269 + 0.0016785*m.x270 + 0.00624913*m.x271
- 0.00271435*m.x272 - 0.00261305*m.x273 + 0.00160928*m.x274 + 0.00397158*m.x275
+ 0.00449248*m.x276 - 0.00174627*m.x277 + 0.00173888*m.x278 + 0.00361497*m.x279
+ 0.00608981*m.x280 + 0.00614973*m.x281 + 0.00797918*m.x282 + 0.00353012*m.x283
+ 0.0106118*m.x284 + 0.00180257*m.x285 + 0.00554875*m.x286 + 0.00340277*m.x287
+ 0.00314873*m.x288 + 0.00310593*m.x289 + 0.00234241*m.x290 + 0.00590393*m.x291
+ 0.000439495*m.x292 - 0.00164086*m.x293 - 0.00383165*m.x294 + 0.0052497*m.x295
+ 0.00231272*m.x296 - 0.00666127*m.x297 + 0.0119683*m.x298 - 0.00285395*m.x299
+ 0.00170996*m.x300 + 0.00942007*m.x301 + 0.00238323*m.x302 + 0.00381314*m.x303 == 0)
m.c267 = Constraint(expr= - m.x162 - 0.000827581*m.x204 - 0.000451953*m.x205 + 0.00268288*m.x206 + 0.00436906*m.x207
+ 0.00284817*m.x208 + 0.00319873*m.x209 - 0.00048119*m.x210 + 0.00540009*m.x211
+ 0.00477371*m.x212 + 0.00685899*m.x213 + 0.00554255*m.x214 + 0.00238489*m.x215
+ 0.00887716*m.x216 + 0.00583571*m.x217 + 0.00714866*m.x218 + 0.00495966*m.x219
+ 0.00497362*m.x220 - 0.00697647*m.x221 - 0.00228625*m.x222 + 0.00325028*m.x223
+ 0.000619718*m.x224 + 0.000613874*m.x225 + 0.00308159*m.x226 + 0.00752408*m.x227
+ 0.00126037*m.x228 - 0.000188674*m.x229 + 0.00645332*m.x230 + 0.00353599*m.x231
+ 0.0108839*m.x232 + 0.00235866*m.x233 + 0.00908161*m.x234 + 0.00417314*m.x235
- 0.00141802*m.x236 + 0.000695564*m.x237 - 0.000313358*m.x238 + 0.00136897*m.x239
+ 0.00499907*m.x240 + 0.00530761*m.x241 + 0.00907092*m.x242 + 0.0041524*m.x243
+ 0.00512496*m.x244 + 0.00129105*m.x245 + 0.00486963*m.x246 + 0.00212064*m.x247
+ 0.0171055*m.x248 + 0.00254184*m.x249 + 0.00480861*m.x250 + 0.00172909*m.x251
+ 0.00615053*m.x252 + 0.00524869*m.x253 + 0.00758869*m.x254 + 0.00420593*m.x255
+ 0.00396062*m.x256 + 0.0123785*m.x257 + 0.00129358*m.x258 + 0.00318644*m.x259
+ 0.0022354*m.x260 + 0.00132205*m.x261 - 0.00331763*m.x262 + 0.00654843*m.x263
+ 0.0999224*m.x264 + 0.00659559*m.x265 + 0.00418092*m.x266 - 0.0101561*m.x267
+ 0.000400403*m.x268 + 0.00037105*m.x269 + 0.00120729*m.x270 + 0.0112744*m.x271
- 0.00282282*m.x272 + 0.00541563*m.x273 - 0.00194831*m.x274 + 0.00472835*m.x275
+ 0.015161*m.x276 + 0.0149532*m.x277 + 0.00696878*m.x278 - 0.00212982*m.x279
- 0.000506982*m.x280 + 0.00516964*m.x281 + 0.0561216*m.x282 + 0.00206552*m.x283
+ 0.00059783*m.x284 + 0.00506047*m.x285 + 0.00221597*m.x286 + 0.00470215*m.x287
+ 0.00565729*m.x288 + 0.000952909*m.x289 - 0.00116189*m.x290 + 0.00694876*m.x291
+ 0.00562572*m.x292 + 0.00278368*m.x293 + 0.00369458*m.x294 + 0.0171593*m.x295
- 0.00289371*m.x296 - 0.00430756*m.x297 + 0.00677732*m.x298 + 0.00573494*m.x299
+ 0.00758548*m.x300 - 0.000228625*m.x301 + 0.00247448*m.x302 + 0.000632226*m.x303 == 0)
m.c268 = Constraint(expr= - m.x163 + 0.000319199*m.x204 + 0.000474809*m.x205 - 0.0040862*m.x206 + 0.00413471*m.x207
+ 0.00147042*m.x208 + 0.00684361*m.x209 - 0.00264342*m.x210 + 0.00223674*m.x211
+ 0.00203511*m.x212 + 0.00149984*m.x213 + 0.00203335*m.x214 - 0.000481693*m.x215
+ 0.00691443*m.x216 + 0.00378434*m.x217 + 0.0120675*m.x218 + 0.00900098*m.x219
+ 0.00401966*m.x220 - 0.00153885*m.x221 - 0.00518938*m.x222 + 0.00638179*m.x223
+ 0.000555843*m.x224 + 0.0106786*m.x225 + 0.0042759*m.x226 + 0.00378686*m.x227
+ 0.00496836*m.x228 + 0.00424723*m.x229 + 0.00540775*m.x230 + 0.00274124*m.x231
- 0.00138995*m.x232 + 0.00258727*m.x233 + 0.00892137*m.x234 - 0.0011102*m.x235
+ 0.00426929*m.x236 - 0.00052299*m.x237 + 0.00501177*m.x238 + 0.00469266*m.x239
+ 0.00550805*m.x240 + 0.00606979*m.x241 + 0.00387696*m.x242 + 0.00171382*m.x243
+ 0.00566131*m.x244 + 0.00312652*m.x245 - 0.0011072*m.x246 + 0.00363109*m.x247
- 0.000546877*m.x248 + 0.00434758*m.x249 + 0.00487248*m.x250 - 0.00455718*m.x251
+ 0.00457997*m.x252 + 0.00756756*m.x253 + 0.00417238*m.x254 + 0.000449462*m.x255
+ 0.00572913*m.x256 + 0.0075057*m.x257 + 0.00744467*m.x258 + 0.00233055*m.x259
- 0.00334067*m.x260 + 0.0109022*m.x261 + 0.00422071*m.x262 - 0.000185811*m.x263
+ 0.00659559*m.x264 + 0.07022*m.x265 + 0.00416125*m.x266 + 0.00352651*m.x267
+ 0.000419826*m.x268 + 0.00343332*m.x269 + 0.00217325*m.x270 + 0.00506401*m.x271
+ 0.00256623*m.x272 - 0.00300804*m.x273 - 0.00011493*m.x274 + 0.00948613*m.x275
+ 0.00588371*m.x276 + 0.00371951*m.x277 + 0.00218575*m.x278 + 0.00239518*m.x279
+ 0.000908744*m.x280 + 0.00589109*m.x281 - 0.000413564*m.x282 + 0.00177553*m.x283
+ 0.000254788*m.x284 + 0.000483366*m.x285 + 0.00434862*m.x286 - 0.00339015*m.x287
+ 0.00162127*m.x288 + 0.00452576*m.x289 + 0.00597812*m.x290 + 2.54983E-5*m.x291
- 0.00247603*m.x292 + 0.0044097*m.x293 + 0.00452471*m.x294 + 0.00474492*m.x295
+ 0.000287705*m.x296 - 0.00158663*m.x297 + 0.00306085*m.x298 + 0.00331961*m.x299
+ 0.00420889*m.x300 - 0.00957465*m.x301 + 0.000329151*m.x302 + 0.000204814*m.x303 == 0)
m.c269 = Constraint(expr= - m.x164 - 0.00408084*m.x204 + 0.00265625*m.x205 + 0.00434811*m.x206 - 0.00244187*m.x207
+ 0.00264492*m.x208 + 0.00146666*m.x209 - 0.000799614*m.x210 - 0.00228832*m.x211
- 0.000827761*m.x212 + 0.00129678*m.x213 + 0.00806469*m.x214 + 0.0009138*m.x215
+ 0.00137818*m.x216 + 0.00219548*m.x217 + 0.00202404*m.x218 + 0.0071845*m.x219
+ 0.00262695*m.x220 + 0.00688652*m.x221 - 0.0102024*m.x222 + 0.00539482*m.x223
+ 0.0030044*m.x224 + 0.00554857*m.x225 + 0.00295181*m.x226 + 1.24483E-5*m.x227
+ 0.00583939*m.x228 + 0.0023868*m.x229 - 0.00427958*m.x230 - 0.000533821*m.x231
- 0.00309501*m.x232 + 0.00334281*m.x233 + 0.00228629*m.x234 + 0.00234077*m.x235
+ 0.000950245*m.x236 + 0.00584205*m.x237 + 0.00457594*m.x238 - 0.0014627*m.x239
+ 0.00361742*m.x240 + 0.00181367*m.x241 + 0.00304921*m.x242 + 0.00400573*m.x243
- 0.00340962*m.x244 - 0.000646819*m.x245 - 0.00201067*m.x246 + 0.000619034*m.x247
- 0.00127115*m.x248 - 0.000143504*m.x249 - 0.00220491*m.x250 - 0.000349801*m.x251
+ 0.00116129*m.x252 + 0.00467689*m.x253 - 0.00108104*m.x254 - 0.00387947*m.x255
+ 0.011585*m.x256 + 0.00222301*m.x257 + 0.00063742*m.x258 + 0.00263152*m.x259
+ 0.00637109*m.x260 - 0.00347997*m.x261 - 0.00540834*m.x262 - 0.00273039*m.x263
+ 0.00418092*m.x264 + 0.00416125*m.x265 + 0.0995071*m.x266 - 0.00026181*m.x267
- 0.00164331*m.x268 + 0.000127298*m.x269 + 0.00486644*m.x270 + 0.00397255*m.x271
+ 0.0129943*m.x272 - 0.00259351*m.x273 - 0.000134645*m.x274 - 0.0024675*m.x275
- 0.000639732*m.x276 + 0.0061587*m.x277 - 0.000720003*m.x278 - 0.00377983*m.x279
- 0.00164528*m.x280 + 0.00111631*m.x281 + 0.00309633*m.x282 - 0.00431355*m.x283
- 0.00123317*m.x284 - 0.00107592*m.x285 - 0.00299895*m.x286 + 0.00239151*m.x287
+ 0.00504485*m.x288 + 0.00186508*m.x289 - 0.00261967*m.x290 - 0.00111953*m.x291
+ 0.00813916*m.x292 + 0.00116867*m.x293 - 0.000798317*m.x294 + 0.00191161*m.x295
+ 0.00398234*m.x296 - 0.00142675*m.x297 + 0.00441408*m.x298 + 0.00695092*m.x299
- 0.00519564*m.x300 - 0.00145915*m.x301 - 0.00269056*m.x302 + 0.0029091*m.x303 == 0)
m.c270 = Constraint(expr= - m.x165 - 0.0130473*m.x204 - 0.00353732*m.x205 + 0.00169867*m.x206 + 0.00545183*m.x207
- 0.000424681*m.x208 - 0.00449445*m.x209 - 0.00211867*m.x210 - 0.00507634*m.x211
+ 0.00659553*m.x212 - 0.00152672*m.x213 + 0.00317218*m.x214 - 0.00429905*m.x215
- 0.000777149*m.x216 - 0.00478566*m.x217 - 0.00587325*m.x218 + 0.000145803*m.x219
- 0.00141986*m.x220 - 0.00817883*m.x221 - 0.00485647*m.x222 - 0.0049754*m.x223
- 0.000640874*m.x224 - 0.00814519*m.x225 - 0.000678406*m.x226 - 0.000694644*m.x227
+ 0.000591772*m.x228 - 0.00326633*m.x229 - 0.0057947*m.x230 - 0.0021747*m.x231
- 0.000395075*m.x232 + 0.000681716*m.x233 - 0.00141271*m.x234 - 0.00112428*m.x235
- 0.0100929*m.x236 - 0.00708984*m.x237 - 0.0104815*m.x238 + 0.00243124*m.x239
- 0.00468506*m.x240 + 0.000404166*m.x241 + 0.000493456*m.x242 + 0.000351314*m.x243
+ 3.23772E-5*m.x244 - 0.00214428*m.x245 + 0.000797127*m.x246 - 0.000860656*m.x247
- 0.00882959*m.x248 - 0.00324401*m.x249 - 0.00289289*m.x250 - 0.010277*m.x251
- 0.00334468*m.x252 - 0.00212043*m.x253 - 0.00298459*m.x254 - 0.00136751*m.x255
- 0.00253899*m.x256 - 0.0077448*m.x257 - 0.000760534*m.x258 - 0.00597953*m.x259
- 0.0012203*m.x260 - 0.00396798*m.x261 + 0.251509*m.x262 - 0.00103049*m.x263
- 0.0101561*m.x264 + 0.00352651*m.x265 - 0.00026181*m.x266 + 0.433741*m.x267
+ 0.00128825*m.x268 + 9.92783E-5*m.x269 + 0.00123264*m.x270 - 0.0051442*m.x271
- 0.000297438*m.x272 + 0.0114782*m.x273 - 0.0015542*m.x274 - 0.00124081*m.x275
- 0.00658561*m.x276 - 0.00508464*m.x277 - 0.000437189*m.x278 - 0.00827295*m.x279
- 0.00171171*m.x280 - 0.00437862*m.x281 - 0.00400538*m.x282 - 0.00481033*m.x283
+ 0.000267753*m.x284 - 0.00462929*m.x285 - 0.00477368*m.x286 - 0.0034161*m.x287
+ 0.000222907*m.x288 + 0.00216417*m.x289 - 0.000119858*m.x290 + 0.0183023*m.x291
+ 0.00146243*m.x292 + 0.00652183*m.x293 + 0.000896056*m.x294 - 0.00583543*m.x295
+ 0.0021646*m.x296 - 0.00610058*m.x297 - 0.006832*m.x298 - 0.00455273*m.x299
+ 0.00534474*m.x300 - 0.0104513*m.x301 - 0.00240116*m.x302 + 0.00593878*m.x303 == 0)
m.c271 = Constraint(expr= - m.x166 - 0.000488486*m.x204 + 0.0119217*m.x205 + 0.010645*m.x206 + 0.00495238*m.x207
+ 0.00721645*m.x208 + 0.00890815*m.x209 + 0.00596663*m.x210 + 0.000540695*m.x211
- 0.00174127*m.x212 + 0.0108934*m.x213 + 0.00207678*m.x214 - 0.00296047*m.x215
+ 0.00138796*m.x216 + 0.0059852*m.x217 + 0.00694813*m.x218 + 0.00157234*m.x219
+ 0.00376038*m.x220 - 0.000294619*m.x221 + 0.0127494*m.x222 - 0.00136747*m.x223
+ 0.0028325*m.x224 + 0.0120784*m.x225 + 0.00506594*m.x226 + 0.000738861*m.x227
+ 0.00184587*m.x228 + 0.00828866*m.x229 + 0.0139508*m.x230 + 0.00514558*m.x231
+ 0.00576686*m.x232 + 0.00619447*m.x233 + 0.0112419*m.x234 + 0.0103289*m.x235
+ 0.00991537*m.x236 + 0.00265142*m.x237 + 0.0017514*m.x238 + 0.00934914*m.x239
+ 0.00941149*m.x240 + 0.00199306*m.x241 - 0.000247517*m.x242 + 0.00222305*m.x243
+ 0.00288722*m.x244 + 0.00609509*m.x245 + 0.00333299*m.x246 + 0.00340102*m.x247
+ 0.00370779*m.x248 + 0.00241411*m.x249 + 0.00758561*m.x250 - 0.00203947*m.x251
- 0.00177309*m.x252 - 0.000146116*m.x253 - 0.00134772*m.x254 + 0.00497244*m.x255
+ 0.00246284*m.x256 - 0.00502038*m.x257 - 0.00149672*m.x258 + 0.00551452*m.x259
+ 0.00130759*m.x260 + 0.00540898*m.x261 + 0.00146019*m.x262 + 0.00524602*m.x263
+ 0.000400403*m.x264 + 0.000419826*m.x265 - 0.00164331*m.x266 + 0.00128825*m.x267
+ 0.0593612*m.x268 + 0.0127361*m.x269 + 0.00329798*m.x270 + 0.00745462*m.x271
+ 0.001637*m.x272 - 0.00182601*m.x273 + 0.00273762*m.x274 + 0.00370659*m.x275
+ 0.00073551*m.x276 + 0.00470649*m.x277 + 0.000708354*m.x278 + 0.00236959*m.x279
+ 0.00614785*m.x280 + 0.00314938*m.x281 + 0.00170909*m.x282 - 0.0031579*m.x283
+ 0.0092312*m.x284 + 0.00139163*m.x285 - 0.00265918*m.x286 + 0.00891526*m.x287
+ 0.0041968*m.x288 + 0.00379037*m.x289 + 0.00152491*m.x290 + 0.0102022*m.x291
+ 0.00836314*m.x292 + 0.00119311*m.x293 - 0.000302283*m.x294 + 0.00138488*m.x295
+ 0.00217937*m.x296 - 0.000402168*m.x297 + 0.000850121*m.x298 + 0.0110636*m.x299
+ 0.00498262*m.x300 + 0.00115585*m.x301 + 0.00570291*m.x302 + 0.00301803*m.x303 == 0)
m.c272 = Constraint(expr= - m.x167 + 0.00109418*m.x204 + 0.00462742*m.x205 + 0.00861052*m.x206 + 0.00411888*m.x207
+ 0.00584868*m.x208 + 0.00402867*m.x209 - 0.000337876*m.x210 - 0.000710481*m.x211
+ 0.00394387*m.x212 + 0.000425159*m.x213 - 0.00182631*m.x214 + 0.00202854*m.x215
- 0.000964469*m.x216 + 0.00197755*m.x217 + 0.00377359*m.x218 + 0.00208948*m.x219
+ 0.00356601*m.x220 - 0.000858525*m.x221 + 0.00827695*m.x222 + 0.00126881*m.x223
+ 0.002376*m.x224 + 0.00309714*m.x225 + 0.00413143*m.x226 + 0.0016632*m.x227
+ 0.000736705*m.x228 + 0.00468054*m.x229 + 0.00577359*m.x230 + 0.00318024*m.x231
+ 0.00353172*m.x232 + 0.00533029*m.x233 + 0.00366445*m.x234 + 0.00121195*m.x235
+ 0.00593721*m.x236 + 0.00120658*m.x237 + 0.000755628*m.x238 + 0.000872186*m.x239
+ 0.00506394*m.x240 + 0.00308026*m.x241 + 0.000349729*m.x242 + 0.00506636*m.x243
- 0.00118633*m.x244 + 0.00587685*m.x245 + 0.0013567*m.x246 - 0.00197937*m.x247
+ 0.00220942*m.x248 - 0.000256307*m.x249 + 0.00350318*m.x250 + 0.00647039*m.x251
+ 0.00135912*m.x252 + 0.00271306*m.x253 + 0.000740512*m.x254 - 0.000113863*m.x255
+ 0.0021298*m.x256 - 0.000552918*m.x257 + 0.00371467*m.x258 + 0.00394894*m.x259
+ 0.00231089*m.x260 + 0.00276138*m.x261 - 0.00206428*m.x262 + 0.00624277*m.x263
+ 0.00037105*m.x264 + 0.00343332*m.x265 + 0.000127298*m.x266 + 9.92783E-5*m.x267
+ 0.0127361*m.x268 + 0.0262339*m.x269 + 0.003349*m.x270 + 0.00142392*m.x271
+ 0.00518398*m.x272 + 0.00332053*m.x273 - 0.000651909*m.x274 + 0.00345787*m.x275
+ 0.0015834*m.x276 - 0.00204478*m.x277 + 0.00181948*m.x278 + 0.0026534*m.x279
+ 0.00931383*m.x280 + 0.00472133*m.x281 + 0.00170468*m.x282 + 0.00110864*m.x283
+ 0.00727345*m.x284 + 0.00278892*m.x285 - 0.000721759*m.x286 + 0.00479513*m.x287
+ 0.00119802*m.x288 + 0.00319581*m.x289 + 0.00188211*m.x290 + 0.00479563*m.x291
+ 0.00585396*m.x292 - 0.000300368*m.x293 + 0.000255675*m.x294 + 6.76023E-5*m.x295
- 0.000464781*m.x296 + 0.00126493*m.x297 + 0.00259808*m.x298 + 0.00163564*m.x299
+ 0.00270092*m.x300 + 0.00285028*m.x301 + 0.00895321*m.x302 + 0.00219665*m.x303 == 0)
m.c273 = Constraint(expr= - m.x168 + 0.00331627*m.x204 + 0.00319077*m.x205 + 0.00468559*m.x206 + 0.00641475*m.x207
- 0.00125879*m.x208 - 0.00123966*m.x209 + 0.0022652*m.x210 - 9.29613E-5*m.x211
+ 0.00861848*m.x212 + 0.000218677*m.x213 + 0.00122714*m.x214 - 0.000579525*m.x215
+ 0.00270163*m.x216 + 0.000399331*m.x217 + 0.00180051*m.x218 + 0.0030484*m.x219
+ 0.00737614*m.x220 + 0.00730014*m.x221 - 0.000575534*m.x222 + 0.00353355*m.x223
+ 0.00468858*m.x224 - 0.000808721*m.x225 + 0.00263189*m.x226 + 0.00093894*m.x227
- 0.000390252*m.x228 - 0.000763441*m.x229 - 0.00197249*m.x230 + 0.00107192*m.x231
+ 0.00568516*m.x232 + 0.000115147*m.x233 - 0.00115062*m.x234 + 0.00320026*m.x235
+ 0.00327904*m.x236 + 0.00429363*m.x237 + 0.00557733*m.x238 - 0.00186934*m.x239
- 0.000575193*m.x240 + 0.00492292*m.x241 - 6.1818E-5*m.x242 + 0.00339671*m.x243
+ 0.00128347*m.x244 + 0.00191072*m.x245 + 0.000671953*m.x246 + 0.000621111*m.x247
- 0.0007257*m.x248 + 0.00117147*m.x249 + 0.0034932*m.x250 - 0.000334806*m.x251
+ 0.0055357*m.x252 + 0.00797013*m.x253 - 0.000683822*m.x254 - 0.00136059*m.x255
+ 0.00233754*m.x256 + 0.00395004*m.x257 + 0.000163938*m.x258 + 0.0024981*m.x259
+ 0.00364342*m.x260 + 0.00118344*m.x261 + 8.81979E-5*m.x262 + 0.0016785*m.x263
+ 0.00120729*m.x264 + 0.00217325*m.x265 + 0.00486644*m.x266 + 0.00123264*m.x267
+ 0.00329798*m.x268 + 0.003349*m.x269 + 0.0296551*m.x270 + 0.000803138*m.x271
+ 0.00261358*m.x272 + 0.00421158*m.x273 + 0.00224737*m.x274 + 0.00248184*m.x275
- 0.0025493*m.x276 + 0.00528975*m.x277 + 0.00304023*m.x278 - 7.68874E-5*m.x279
+ 0.00145709*m.x280 + 0.000648689*m.x281 + 0.00531632*m.x282 - 0.00270393*m.x283
- 0.000304736*m.x284 + 0.00310389*m.x285 + 0.00378933*m.x286 + 0.00270045*m.x287
+ 0.00133532*m.x288 + 0.00280379*m.x289 + 0.00340292*m.x290 + 0.00122189*m.x291
+ 0.00282862*m.x292 + 0.00394438*m.x293 + 0.00508295*m.x294 + 0.00752552*m.x295
+ 0.000133786*m.x296 - 0.00111604*m.x297 + 0.00508961*m.x298 - 0.00259683*m.x299
+ 0.00158141*m.x300 - 0.00346463*m.x301 + 0.000964003*m.x302 - 0.00191532*m.x303 == 0)
m.c274 = Constraint(expr= - m.x169 + 0.0045216*m.x204 + 0.00271929*m.x205 + 0.00738855*m.x206 + 0.00111178*m.x207
+ 0.00123949*m.x208 + 0.00107871*m.x209 - 0.00117815*m.x210 + 0.016814*m.x211
- 0.00595897*m.x212 + 0.00258553*m.x213 + 0.00268003*m.x214 + 0.00537311*m.x215
+ 0.0102894*m.x216 + 0.00684901*m.x217 + 0.00937097*m.x218 + 0.00227052*m.x219
+ 0.00551084*m.x220 - 0.000185895*m.x221 + 0.00350023*m.x222 - 0.00138502*m.x223
- 0.000363617*m.x224 + 0.00442729*m.x225 + 0.0018705*m.x226 + 0.00032798*m.x227
+ 0.00293877*m.x228 + 0.00961433*m.x229 - 0.0041837*m.x230 + 0.00297944*m.x231
- 0.00269802*m.x232 + 0.00302395*m.x233 + 0.00857186*m.x234 + 0.00764263*m.x235
+ 0.0084466*m.x236 + 0.00258002*m.x237 + 0.00229256*m.x238 + 0.00444714*m.x239
+ 0.00583068*m.x240 + 0.00326363*m.x241 + 0.0011178*m.x242 + 0.00640579*m.x243
+ 0.00976189*m.x244 + 0.000970672*m.x245 + 0.00337629*m.x246 + 0.00199323*m.x247
+ 0.000362512*m.x248 + 0.000577468*m.x249 + 0.00414106*m.x250 - 0.000679271*m.x251
+ 0.00211564*m.x252 + 0.00107585*m.x253 + 0.00203828*m.x254 - 0.00252786*m.x255
+ 0.00563448*m.x256 + 0.00631844*m.x257 + 0.00082375*m.x258 + 0.00562702*m.x259
+ 0.00391626*m.x260 + 0.00360731*m.x261 + 0.000290516*m.x262 + 0.00624913*m.x263
+ 0.0112744*m.x264 + 0.00506401*m.x265 + 0.00397255*m.x266 - 0.0051442*m.x267
+ 0.00745462*m.x268 + 0.00142392*m.x269 + 0.000803138*m.x270 + 0.0564156*m.x271
+ 0.000199122*m.x272 + 0.0069332*m.x273 - 0.000609549*m.x274 + 0.00696655*m.x275
+ 0.00884095*m.x276 + 0.00704184*m.x277 + 0.00678411*m.x278 + 0.000622126*m.x279
+ 0.00149664*m.x280 + 0.00849473*m.x281 + 0.00425277*m.x282 - 0.00201782*m.x283
+ 0.00117189*m.x284 + 0.00205926*m.x285 + 0.00108221*m.x286 - 0.000509977*m.x287
+ 0.00613474*m.x288 + 0.0035637*m.x289 + 0.00316685*m.x290 + 0.000164365*m.x291
+ 0.000853601*m.x292 - 0.00132464*m.x293 + 0.00386284*m.x294 + 0.00522755*m.x295
+ 0.00612756*m.x296 - 0.000490773*m.x297 - 0.00304139*m.x298 + 0.00709659*m.x299
+ 0.00740449*m.x300 - 0.000919619*m.x301 + 0.00139892*m.x302 - 0.00120848*m.x303 == 0)
m.c275 = Constraint(expr= - m.x170 - 0.00260415*m.x204 - 0.00543312*m.x205 - 0.00180418*m.x206 - 0.00121453*m.x207
+ 0.00134707*m.x208 + 0.00207255*m.x209 - 0.00408935*m.x210 - 0.000397583*m.x211
- 0.0094895*m.x212 + 0.000326023*m.x213 + 0.0075118*m.x214 + 0.0135494*m.x215
- 0.000391351*m.x216 + 0.00252489*m.x217 + 0.00359699*m.x218 + 0.00420122*m.x219
+ 0.0024023*m.x220 + 0.00897574*m.x221 - 0.00265872*m.x222 - 0.00188528*m.x223
+ 0.00165607*m.x224 + 0.00165204*m.x225 + 0.0019702*m.x226 + 0.000214023*m.x227
+ 0.00416663*m.x228 - 0.00265062*m.x229 - 0.00171015*m.x230 + 0.00387335*m.x231
+ 0.00498942*m.x232 + 0.00477754*m.x233 + 0.00134029*m.x234 + 0.000547113*m.x235
+ 0.00275452*m.x236 + 0.000225492*m.x237 + 0.000473704*m.x238 + 0.00103419*m.x239
+ 0.00257751*m.x240 + 0.00430324*m.x241 - 0.00573353*m.x242 + 0.000454124*m.x243
- 0.00394866*m.x244 + 0.0045212*m.x245 + 0.000207882*m.x246 + 0.00314636*m.x247
+ 0.000666346*m.x248 + 0.00154811*m.x249 - 0.000776536*m.x250 + 0.0102058*m.x251
+ 0.0010794*m.x252 + 0.00588583*m.x253 + 0.00143493*m.x254 - 0.00391423*m.x255
+ 0.00602755*m.x256 + 0.00744533*m.x257 - 0.00321542*m.x258 + 0.00231435*m.x259
- 0.000228137*m.x260 - 0.00260459*m.x261 + 0.00222724*m.x262 - 0.00271435*m.x263
- 0.00282282*m.x264 + 0.00256623*m.x265 + 0.0129943*m.x266 - 0.000297438*m.x267
+ 0.001637*m.x268 + 0.00518398*m.x269 + 0.00261358*m.x270 + 0.000199122*m.x271
+ 0.0410637*m.x272 + 0.000873092*m.x273 + 0.00751651*m.x274 + 3.52637E-5*m.x275
+ 0.00187569*m.x276 - 0.00175065*m.x277 + 0.00345714*m.x278 + 0.0124158*m.x279
+ 0.00726466*m.x280 - 0.00175747*m.x281 + 0.00635637*m.x282 + 0.00300545*m.x283
- 0.000607595*m.x284 + 0.00303877*m.x285 + 0.00344426*m.x286 - 0.000151734*m.x287
- 0.000959542*m.x288 + 0.0027039*m.x289 - 0.00101768*m.x290 - 0.00789306*m.x291
+ 0.000904711*m.x292 - 0.000843722*m.x293 + 0.00193938*m.x294 - 0.00169631*m.x295
+ 0.00153401*m.x296 - 0.0051692*m.x297 + 0.004099*m.x298 + 0.00833415*m.x299
- 0.000558778*m.x300 + 0.00267992*m.x301 + 0.00290008*m.x302 + 0.00401961*m.x303 == 0)
m.c276 = Constraint(expr= - m.x171 - 0.000565556*m.x204 + 0.00196136*m.x205 + 0.00156566*m.x206 + 0.00461528*m.x207
+ 0.00328024*m.x208 + 0.00348354*m.x209 + 0.000462235*m.x210 + 0.00336798*m.x211
+ 0.00494924*m.x212 + 0.000152555*m.x213 + 0.00178843*m.x214 - 0.00091213*m.x215
+ 0.00613597*m.x216 + 0.00629022*m.x217 + 0.0014386*m.x218 + 0.00590657*m.x219
+ 0.00990879*m.x220 + 0.0166501*m.x221 + 0.00164814*m.x222 + 0.00323891*m.x223
- 0.00574416*m.x224 + 0.0142159*m.x225 + 0.000738364*m.x226 - 0.000455981*m.x227
+ 0.00536772*m.x228 + 0.00154076*m.x229 + 0.000149793*m.x230 + 0.000833965*m.x231
+ 0.00215788*m.x232 + 0.00409215*m.x233 - 0.00510595*m.x234 + 0.00407025*m.x235
+ 0.00389367*m.x236 + 0.00114158*m.x237 + 0.0031662*m.x238 + 0.00586585*m.x239
+ 0.00615504*m.x240 + 0.00533161*m.x241 - 0.00828959*m.x242 - 0.000205968*m.x243
+ 0.0292476*m.x244 - 0.00264895*m.x245 - 0.00430941*m.x246 - 0.000650527*m.x247
+ 0.00537778*m.x248 - 0.000768089*m.x249 - 0.00326844*m.x250 + 0.0132501*m.x251
+ 0.00192198*m.x252 + 0.00326447*m.x253 - 0.00250979*m.x254 - 0.0125749*m.x255
+ 0.00350973*m.x256 + 0.00619991*m.x257 + 0.00553702*m.x258 + 0.00405522*m.x259
- 0.000486291*m.x260 + 0.000489283*m.x261 + 0.00327562*m.x262 - 0.00261305*m.x263
+ 0.00541563*m.x264 - 0.00300804*m.x265 - 0.00259351*m.x266 + 0.0114782*m.x267
- 0.00182601*m.x268 + 0.00332053*m.x269 + 0.00421158*m.x270 + 0.0069332*m.x271
+ 0.000873092*m.x272 + 0.0819903*m.x273 + 0.0113857*m.x274 + 0.0150218*m.x275
+ 0.00729937*m.x276 + 0.00870756*m.x277 + 0.0122867*m.x278 + 0.00984671*m.x279
+ 0.00157451*m.x280 + 0.00452844*m.x281 + 0.000902665*m.x282 + 0.00349484*m.x283
- 0.00558798*m.x284 - 0.00152774*m.x285 + 0.00608886*m.x286 + 0.0134833*m.x287
+ 0.00145221*m.x288 + 0.0071947*m.x289 + 0.00751873*m.x290 - 0.00136694*m.x291
+ 0.0032967*m.x292 + 0.00352111*m.x293 + 0.00355609*m.x294 - 0.000110801*m.x295
+ 0.00541829*m.x296 - 0.00179873*m.x297 + 0.00181925*m.x298 + 0.00435334*m.x299
+ 0.00935992*m.x300 - 0.00673796*m.x301 + 0.0024774*m.x302 + 0.00491578*m.x303 == 0)
m.c277 = Constraint(expr= - m.x172 + 0.00157409*m.x204 + 0.00104823*m.x205 + 0.00730297*m.x206 + 0.00171472*m.x207
- 0.00258347*m.x208 + 0.00923163*m.x209 + 0.00708304*m.x210 - 3.62062E-5*m.x211
+ 0.00140893*m.x212 + 0.000755605*m.x213 + 0.00419246*m.x214 + 0.00552551*m.x215
+ 0.00606486*m.x216 + 0.00202437*m.x217 + 0.00529025*m.x218 + 0.00514824*m.x219
+ 0.00256553*m.x220 + 0.0413935*m.x221 - 0.00157821*m.x222 + 0.00954413*m.x223
+ 0.00258154*m.x224 - 0.00279132*m.x225 - 0.00145188*m.x226 + 0.00209608*m.x227
+ 0.00835572*m.x228 + 0.000823677*m.x229 + 0.00209144*m.x230 + 0.00113589*m.x231
- 0.000768782*m.x232 + 0.0030886*m.x233 - 0.00295933*m.x234 + 0.0036774*m.x235
- 0.000709167*m.x236 + 0.00465008*m.x237 - 0.00122519*m.x238 + 0.00231842*m.x239
+ 0.00425069*m.x240 + 0.00508092*m.x241 + 0.00226037*m.x242 + 0.00175952*m.x243
+ 0.00482129*m.x244 - 0.00122455*m.x245 + 0.00263722*m.x246 + 0.00194261*m.x247
+ 0.00435506*m.x248 + 0.00319599*m.x249 + 0.00321975*m.x250 + 0.00894547*m.x251
+ 0.00189277*m.x252 + 0.000829669*m.x253 + 0.000544328*m.x254 + 0.00401374*m.x255
+ 0.00383568*m.x256 + 0.00217002*m.x257 + 0.00147133*m.x258 + 0.00465177*m.x259
+ 0.00136233*m.x260 + 0.0019333*m.x261 - 0.00467757*m.x262 + 0.00160928*m.x263
- 0.00194831*m.x264 - 0.00011493*m.x265 - 0.000134645*m.x266 - 0.0015542*m.x267
+ 0.00273762*m.x268 - 0.000651909*m.x269 + 0.00224737*m.x270 - 0.000609549*m.x271
+ 0.00751651*m.x272 + 0.0113857*m.x273 + 0.0630445*m.x274 + 0.00795102*m.x275
+ 0.00304849*m.x276 + 0.00308585*m.x277 + 0.0217768*m.x278 + 0.0125072*m.x279
+ 0.00285872*m.x280 + 0.00387554*m.x281 - 0.00153684*m.x282 + 0.00166093*m.x283
+ 0.00201403*m.x284 + 0.00412755*m.x285 + 0.000718975*m.x286 + 0.000956443*m.x287
+ 0.0024877*m.x288 + 0.00167048*m.x289 - 0.00563257*m.x290 + 0.00591306*m.x291
+ 0.00042396*m.x292 + 3.84816E-5*m.x293 - 0.000816933*m.x294 + 0.00214663*m.x295
+ 0.00586755*m.x296 - 0.00378753*m.x297 - 0.00130744*m.x298 + 0.00509215*m.x299
+ 0.000940496*m.x300 + 5.42431E-5*m.x301 + 0.00377541*m.x302 + 0.00950302*m.x303 == 0)
m.c278 = Constraint(expr= - m.x173 + 0.00434565*m.x204 + 0.0124518*m.x205 + 0.00553899*m.x206 + 0.00388579*m.x207
+ 0.000703909*m.x208 + 0.000624611*m.x209 + 0.00304047*m.x210 - 0.00115006*m.x211
+ 0.00133383*m.x212 + 0.00527875*m.x213 + 0.0134485*m.x214 + 0.00176871*m.x215
+ 0.00844082*m.x216 + 0.00360247*m.x217 + 0.00208614*m.x218 + 0.00360809*m.x219
+ 0.00357857*m.x220 + 0.00519486*m.x221 + 0.0186797*m.x222 + 0.00474038*m.x223
+ 0.00381723*m.x224 + 0.000424545*m.x225 + 0.00338012*m.x226 - 0.00193539*m.x227
+ 0.00427922*m.x228 - 0.000449853*m.x229 - 0.00158294*m.x230 + 0.00481228*m.x231
- 0.00366851*m.x232 + 0.00889169*m.x233 + 0.0115794*m.x234 + 0.00185908*m.x235
- 0.00220075*m.x236 + 0.0128796*m.x237 + 0.00469534*m.x238 + 0.0117501*m.x239
+ 0.00451846*m.x240 + 0.000128128*m.x241 + 0.00534219*m.x242 + 0.00448064*m.x243
+ 0.0197985*m.x244 - 0.00157959*m.x245 + 0.0157715*m.x246 - 0.00321407*m.x247
+ 0.0289633*m.x248 + 0.00303778*m.x249 + 0.00511975*m.x250 + 0.0211536*m.x251
+ 0.00643706*m.x252 + 0.00442436*m.x253 - 0.0016811*m.x254 + 0.00592187*m.x255
- 0.00440784*m.x256 - 0.00114793*m.x257 + 0.00854643*m.x258 + 0.00507821*m.x259
+ 0.00619112*m.x260 + 0.00139414*m.x261 - 0.00306634*m.x262 + 0.00397158*m.x263
+ 0.00472835*m.x264 + 0.00948613*m.x265 - 0.0024675*m.x266 - 0.00124081*m.x267
+ 0.00370659*m.x268 + 0.00345787*m.x269 + 0.00248184*m.x270 + 0.00696655*m.x271
+ 3.52637E-5*m.x272 + 0.0150218*m.x273 + 0.00795102*m.x274 + 0.101085*m.x275
+ 0.00584736*m.x276 + 0.00340406*m.x277 + 0.00557937*m.x278 + 0.020463*m.x279
+ 0.00157597*m.x280 + 0.013291*m.x281 + 0.00665831*m.x282 + 0.00963207*m.x283
+ 0.00392921*m.x284 - 0.00543762*m.x285 + 0.010873*m.x286 + 0.00656066*m.x287
+ 0.00539259*m.x288 + 0.0115011*m.x289 + 0.00533348*m.x290 + 0.000781568*m.x291
+ 0.00196384*m.x292 + 0.00184219*m.x293 + 0.00423463*m.x294 - 0.00545762*m.x295
+ 0.00496011*m.x296 - 0.00325598*m.x297 + 0.00383461*m.x298 + 0.0116874*m.x299
+ 0.0101529*m.x300 - 0.00447465*m.x301 + 0.00751902*m.x302 + 0.00119155*m.x303 == 0)
m.c279 = Constraint(expr= - m.x174 - 0.00256408*m.x204 - 0.00305148*m.x205 - 0.00796275*m.x206 + 0.00967986*m.x207
- 0.00197849*m.x208 + 0.00416771*m.x209 + 0.0003593*m.x210 + 0.00764087*m.x211
- 0.00225174*m.x212 - 0.00463861*m.x213 + 0.000185964*m.x214 + 0.00949781*m.x215
+ 0.00591694*m.x216 + 0.00776175*m.x217 + 0.00421559*m.x218 + 0.000388988*m.x219
+ 0.000899423*m.x220 - 0.00390506*m.x221 + 0.00255652*m.x222 + 0.00149818*m.x223
- 0.000417211*m.x224 - 0.00529683*m.x225 + 0.00137974*m.x226 + 0.00122937*m.x227
- 0.00121545*m.x228 - 0.00240676*m.x229 + 0.00125814*m.x230 + 0.00110802*m.x231
+ 0.000149784*m.x232 + 0.00200531*m.x233 + 0.00222961*m.x234 + 0.0035544*m.x235
- 0.00419952*m.x236 + 0.00160429*m.x237 + 0.00559382*m.x238 - 0.00199508*m.x239
+ 0.00704945*m.x240 + 0.00294995*m.x241 + 0.00159989*m.x242 + 0.00382583*m.x243
- 0.00202513*m.x244 + 0.00243935*m.x245 - 0.00241116*m.x246 + 0.000171403*m.x247
- 0.00793056*m.x248 + 0.00128681*m.x249 + 0.0018167*m.x250 - 0.000443774*m.x251
+ 0.00398105*m.x252 + 0.00505109*m.x253 + 0.000307144*m.x254 + 0.00168744*m.x255
+ 0.0017901*m.x256 + 0.00280667*m.x257 - 0.00206724*m.x258 + 0.00524954*m.x259
- 0.000663369*m.x260 - 0.000354506*m.x261 - 0.00382859*m.x262 + 0.00449248*m.x263
+ 0.015161*m.x264 + 0.00588371*m.x265 - 0.000639732*m.x266 - 0.00658561*m.x267
+ 0.00073551*m.x268 + 0.0015834*m.x269 - 0.0025493*m.x270 + 0.00884095*m.x271
+ 0.00187569*m.x272 + 0.00729937*m.x273 + 0.00304849*m.x274 + 0.00584736*m.x275
+ 0.0663374*m.x276 + 0.00429338*m.x277 + 0.00208008*m.x278 - 0.00248159*m.x279
+ 0.00121181*m.x280 + 0.011796*m.x281 + 0.00171519*m.x282 + 0.00484394*m.x283
- 0.006173*m.x284 + 0.00504263*m.x285 + 0.000887498*m.x286 + 0.00438259*m.x287
+ 0.00418985*m.x288 + 0.00590139*m.x289 + 0.00101318*m.x290 + 0.00599692*m.x291
- 0.00270112*m.x292 - 0.000435065*m.x293 + 0.00332285*m.x294 + 0.0163644*m.x295
+ 0.000961062*m.x296 + 0.00524417*m.x297 - 0.00131349*m.x298 - 0.00280069*m.x299
+ 0.00116913*m.x300 + 0.00450883*m.x301 + 0.000120926*m.x302 + 0.0018262*m.x303 == 0)
m.c280 = Constraint(expr= - m.x175 + 6.86355E-5*m.x204 + 0.00752299*m.x205 + 0.00502078*m.x206 + 0.0016606*m.x207
+ 0.00192358*m.x208 - 0.00784802*m.x209 + 0.00480892*m.x210 - 0.00130017*m.x211
+ 0.0173398*m.x212 + 0.00182445*m.x213 + 0.00708873*m.x214 + 0.00315281*m.x215
+ 0.00350723*m.x216 + 0.00312055*m.x217 + 0.00532908*m.x218 + 0.00566117*m.x219
+ 0.00477605*m.x220 + 0.00335963*m.x221 - 0.00224843*m.x222 + 0.00924254*m.x223
- 0.0013492*m.x224 - 0.000691165*m.x225 + 0.00275438*m.x226 + 0.00385412*m.x227
+ 0.002375*m.x228 - 0.00308594*m.x229 + 0.00370129*m.x230 - 0.00473546*m.x231
+ 0.00567007*m.x232 + 0.00557444*m.x233 + 0.00216482*m.x234 + 0.000252173*m.x235
+ 0.00578535*m.x236 + 0.00322761*m.x237 + 0.00528838*m.x238 + 0.00257808*m.x239
+ 0.00264191*m.x240 + 0.0033947*m.x241 - 0.00222586*m.x242 + 0.00466981*m.x243
+ 0.00768395*m.x244 + 0.000446619*m.x245 + 0.000537603*m.x246 + 0.00364979*m.x247
- 0.00124997*m.x248 + 0.000718747*m.x249 + 0.0015802*m.x250 + 0.00327277*m.x251
+ 0.000745003*m.x252 + 0.00575919*m.x253 + 0.00312743*m.x254 + 0.00949071*m.x255
+ 0.00137853*m.x256 + 0.00187548*m.x257 + 0.00150074*m.x258 + 0.000811673*m.x259
+ 0.00593263*m.x260 + 0.00179872*m.x261 - 0.00129787*m.x262 - 0.00174627*m.x263
+ 0.0149532*m.x264 + 0.00371951*m.x265 + 0.0061587*m.x266 - 0.00508464*m.x267
+ 0.00470649*m.x268 - 0.00204478*m.x269 + 0.00528975*m.x270 + 0.00704184*m.x271
- 0.00175065*m.x272 + 0.00870756*m.x273 + 0.00308585*m.x274 + 0.00340406*m.x275
+ 0.00429338*m.x276 + 0.0544652*m.x277 + 0.00426504*m.x278 + 0.00206964*m.x279
+ 0.00348858*m.x280 + 0.0015586*m.x281 + 0.000735431*m.x282 + 0.00557963*m.x283
+ 0.000328794*m.x284 + 0.00283205*m.x285 - 0.00256622*m.x286 + 0.00639915*m.x287
+ 0.0101988*m.x288 + 0.00512473*m.x289 + 0.002495*m.x290 - 6.81269E-5*m.x291
+ 0.00306404*m.x292 - 0.00158105*m.x293 + 0.00146977*m.x294 + 0.00374693*m.x295
+ 0.000942883*m.x296 + 0.00282709*m.x297 + 0.000559935*m.x298 + 0.00395298*m.x299
+ 0.00461055*m.x300 + 0.00200426*m.x301 + 0.00214771*m.x302 - 0.00562506*m.x303 == 0)
m.c281 = Constraint(expr= - m.x176 + 0.000115271*m.x204 + 0.00484884*m.x205 - 0.001733*m.x206 + 0.00295113*m.x207
+ 0.00996959*m.x208 + 0.000769801*m.x209 + 0.00445062*m.x210 + 0.00809507*m.x211
+ 0.00433366*m.x212 + 0.000102258*m.x213 + 0.00400977*m.x214 + 0.000656197*m.x215
+ 0.00814361*m.x216 + 0.00869015*m.x217 + 0.00298937*m.x218 + 0.00613568*m.x219
+ 0.00603965*m.x220 - 0.000907451*m.x221 + 0.00495422*m.x222 + 0.00616055*m.x223
- 0.00366376*m.x224 + 0.0035661*m.x225 + 0.0056652*m.x226 + 0.00757348*m.x227
+ 0.00506443*m.x228 - 0.00171011*m.x229 + 0.00029565*m.x230 + 0.00406944*m.x231
+ 0.00749201*m.x232 + 0.00392979*m.x233 - 0.000761944*m.x234 + 0.0057429*m.x235
- 0.00402305*m.x236 + 0.00655944*m.x237 + 0.00469948*m.x238 - 0.002975*m.x239
+ 0.00435042*m.x240 + 0.00617964*m.x241 + 0.0053804*m.x242 + 0.00641732*m.x243
+ 0.00245073*m.x244 + 0.00507279*m.x245 - 0.00425708*m.x246 + 0.00485946*m.x247
+ 0.00600917*m.x248 - 0.000691613*m.x249 + 0.00532914*m.x250 + 0.00786226*m.x251
+ 0.00524394*m.x252 + 0.00235758*m.x253 - 0.000215375*m.x254 + 0.000384402*m.x255
+ 5.46446E-5*m.x256 + 0.00626037*m.x257 + 0.00174514*m.x258 - 0.00221712*m.x259
+ 0.00236031*m.x260 + 0.00283392*m.x261 - 0.00372436*m.x262 + 0.00173888*m.x263
+ 0.00696878*m.x264 + 0.00218575*m.x265 - 0.000720003*m.x266 - 0.000437189*m.x267
+ 0.000708354*m.x268 + 0.00181948*m.x269 + 0.00304023*m.x270 + 0.00678411*m.x271
+ 0.00345714*m.x272 + 0.0122867*m.x273 + 0.0217768*m.x274 + 0.00557937*m.x275
+ 0.00208008*m.x276 + 0.00426504*m.x277 + 0.104966*m.x278 + 0.0274224*m.x279
- 0.00201672*m.x280 + 0.00709871*m.x281 + 0.00330387*m.x282 + 0.00277583*m.x283
+ 0.0174915*m.x284 - 0.00134198*m.x285 + 0.00643863*m.x286 + 0.00424422*m.x287
+ 0.0086924*m.x288 + 0.000133115*m.x289 + 0.00342096*m.x290 + 0.00617057*m.x291
+ 0.00674858*m.x292 + 0.00060276*m.x293 + 0.00167034*m.x294 - 0.000105586*m.x295
+ 0.00482014*m.x296 + 0.00201782*m.x297 + 0.00319848*m.x298 + 0.00557589*m.x299
+ 0.00775337*m.x300 - 0.00196797*m.x301 + 0.000849566*m.x302 + 0.00509184*m.x303 == 0)
m.c282 = Constraint(expr= - m.x177 + 0.00407719*m.x204 + 0.00471928*m.x205 + 0.000121446*m.x206 + 0.00353955*m.x207
+ 0.00858445*m.x208 + 0.00337936*m.x209 + 0.00319021*m.x210 + 0.012837*m.x211
+ 0.000552636*m.x212 + 0.00269352*m.x213 - 0.00213811*m.x214 + 0.00384708*m.x215
+ 0.0112582*m.x216 + 0.0036686*m.x217 + 0.00264656*m.x218 + 0.00230286*m.x219
- 0.00288781*m.x220 + 0.0158614*m.x221 + 0.00648139*m.x222 + 0.000177828*m.x223
+ 0.00392505*m.x224 + 0.00982752*m.x225 + 0.00472609*m.x226 + 0.00328889*m.x227
- 0.000339949*m.x228 + 0.00119568*m.x229 + 0.00285626*m.x230 - 0.00282972*m.x231
+ 0.00153215*m.x232 + 0.00976432*m.x233 + 0.00156264*m.x234 + 0.00330489*m.x235
+ 0.000882589*m.x236 + 0.0152201*m.x237 + 0.0120162*m.x238 + 0.00511897*m.x239
+ 0.00377697*m.x240 + 0.00469332*m.x241 + 0.00320131*m.x242 + 0.0117164*m.x243
+ 0.0074376*m.x244 + 0.00996305*m.x245 + 0.00705762*m.x246 + 0.00796772*m.x247
+ 0.00654889*m.x248 + 0.0060368*m.x249 + 0.0052332*m.x250 + 0.00909273*m.x251
+ 0.00240223*m.x252 + 0.00674287*m.x253 + 0.00123286*m.x254 - 0.00446796*m.x255
- 0.000579361*m.x256 + 0.00865879*m.x257 + 0.00367872*m.x258 + 0.00179629*m.x259
- 0.000221372*m.x260 - 0.000614375*m.x261 + 0.00351785*m.x262 + 0.00361497*m.x263
- 0.00212982*m.x264 + 0.00239518*m.x265 - 0.00377983*m.x266 - 0.00827295*m.x267
+ 0.00236959*m.x268 + 0.0026534*m.x269 - 7.68874E-5*m.x270 + 0.000622126*m.x271
+ 0.0124158*m.x272 + 0.00984671*m.x273 + 0.0125072*m.x274 + 0.020463*m.x275
- 0.00248159*m.x276 + 0.00206964*m.x277 + 0.0274224*m.x278 + 0.167759*m.x279
+ 0.00401387*m.x280 + 0.00590684*m.x281 - 0.00291362*m.x282 + 0.0114267*m.x283
+ 0.00999273*m.x284 + 0.000879691*m.x285 + 0.00171019*m.x286 + 0.0139977*m.x287
+ 0.00246352*m.x288 + 0.00601652*m.x289 + 0.00334106*m.x290 + 0.0025963*m.x291
+ 0.00713089*m.x292 + 0.000877639*m.x293 + 0.00380538*m.x294 + 0.00122031*m.x295
+ 0.00524552*m.x296 - 0.00317043*m.x297 + 0.00149389*m.x298 + 0.0117116*m.x299
+ 0.0269848*m.x300 - 0.00783374*m.x301 + 0.00544106*m.x302 + 0.00418992*m.x303 == 0)
m.c283 = Constraint(expr= - m.x178 - 0.000717764*m.x204 + 0.00180959*m.x205 + 0.00524254*m.x206 + 0.00142511*m.x207
+ 0.00237901*m.x208 + 0.00116986*m.x209 + 0.000605631*m.x210 + 0.000749837*m.x211
+ 0.0021388*m.x212 + 0.00164556*m.x213 + 0.000162794*m.x214 + 0.000917677*m.x215
- 0.001004*m.x216 + 0.00118524*m.x217 + 0.00679774*m.x218 + 0.00270915*m.x219
- 0.000219471*m.x220 + 0.000758788*m.x221 + 0.00210436*m.x222 - 0.000528732*m.x223
- 0.0011348*m.x224 + 0.00395315*m.x225 + 0.00250314*m.x226 + 0.00201276*m.x227
+ 0.00104576*m.x228 + 0.00520579*m.x229 + 0.00597457*m.x230 + 0.00339262*m.x231
+ 0.00188058*m.x232 + 0.00633676*m.x233 + 0.00204943*m.x234 + 0.00398224*m.x235
+ 0.00527028*m.x236 + 0.00163512*m.x237 + 0.00363359*m.x238 + 0.00114031*m.x239
+ 0.00320382*m.x240 + 0.00171417*m.x241 + 0.000418358*m.x242 + 0.0044896*m.x243
+ 0.00257063*m.x244 + 0.00582409*m.x245 - 0.000639079*m.x246 + 0.00166603*m.x247
+ 0.0013566*m.x248 + 0.000899485*m.x249 + 0.00121475*m.x250 + 0.0049413*m.x251
+ 0.00282459*m.x252 + 0.0017513*m.x253 + 0.00131588*m.x254 + 0.0023511*m.x255
+ 0.000918975*m.x256 - 0.00113185*m.x257 + 0.00492691*m.x258 + 0.0049631*m.x259
+ 0.00231411*m.x260 + 0.00131236*m.x261 + 7.90391E-5*m.x262 + 0.00608981*m.x263
- 0.000506982*m.x264 + 0.000908744*m.x265 - 0.00164528*m.x266 - 0.00171171*m.x267
+ 0.00614785*m.x268 + 0.00931383*m.x269 + 0.00145709*m.x270 + 0.00149664*m.x271
+ 0.00726466*m.x272 + 0.00157451*m.x273 + 0.00285872*m.x274 + 0.00157597*m.x275
+ 0.00121181*m.x276 + 0.00348858*m.x277 - 0.00201672*m.x278 + 0.00401387*m.x279
+ 0.0316196*m.x280 + 0.00350992*m.x281 + 0.00385198*m.x282 + 0.00322206*m.x283
+ 0.0100535*m.x284 + 0.00351688*m.x285 - 0.00191643*m.x286 + 0.00378979*m.x287
+ 0.00355674*m.x288 + 0.00196838*m.x289 - 0.000454484*m.x290 + 0.00629473*m.x291
+ 0.00580576*m.x292 + 0.000568793*m.x293 - 0.000609214*m.x294 + 0.00275425*m.x295
+ 0.0015505*m.x296 + 0.00365812*m.x297 + 0.00289131*m.x298 + 0.00281716*m.x299
+ 0.00374955*m.x300 + 0.0050992*m.x301 + 0.0100888*m.x302 + 0.00362527*m.x303 == 0)
m.c284 = Constraint(expr= - m.x179 + 0.00421776*m.x204 - 0.00197105*m.x205 - 0.000120631*m.x206 + 0.00243873*m.x207
+ 0.00880383*m.x208 + 0.00315331*m.x209 + 0.00795997*m.x210 + 0.00274401*m.x211
+ 0.00222851*m.x212 + 0.00504609*m.x213 + 0.000164067*m.x214 + 0.00436823*m.x215
+ 0.0283095*m.x216 + 0.0108841*m.x217 + 0.00864262*m.x218 + 0.00649316*m.x219
+ 0.00864189*m.x220 + 0.00609675*m.x221 - 0.000701372*m.x222 - 0.00297681*m.x223
+ 0.00121554*m.x224 + 0.00440691*m.x225 + 0.00155203*m.x226 - 0.00176184*m.x227
+ 0.00385754*m.x228 + 0.00404244*m.x229 + 0.00323244*m.x230 + 0.0012098*m.x231
- 0.00264831*m.x232 + 0.00795621*m.x233 + 0.000825899*m.x234 + 0.00493613*m.x235
- 0.00719009*m.x236 - 0.000389451*m.x237 + 0.002036*m.x238 + 0.00600576*m.x239
+ 0.00309988*m.x240 + 0.00500233*m.x241 + 0.00364534*m.x242 + 0.00543249*m.x243
+ 0.00619385*m.x244 + 0.0100077*m.x245 + 0.00378279*m.x246 + 0.00349167*m.x247
+ 0.0145382*m.x248 + 0.00663248*m.x249 + 0.00220381*m.x250 + 0.00400317*m.x251
+ 0.00472739*m.x252 + 0.00529534*m.x253 + 0.00669716*m.x254 + 0.00116828*m.x255
+ 0.00676102*m.x256 + 0.0225093*m.x257 - 0.00258072*m.x258 + 0.00316822*m.x259
+ 0.00764311*m.x260 + 0.00470546*m.x261 - 0.00511468*m.x262 + 0.00614973*m.x263
+ 0.00516964*m.x264 + 0.00589109*m.x265 + 0.00111631*m.x266 - 0.00437862*m.x267
+ 0.00314938*m.x268 + 0.00472133*m.x269 + 0.000648689*m.x270 + 0.00849473*m.x271
- 0.00175747*m.x272 + 0.00452844*m.x273 + 0.00387554*m.x274 + 0.013291*m.x275
+ 0.011796*m.x276 + 0.0015586*m.x277 + 0.00709871*m.x278 + 0.00590684*m.x279
+ 0.00350992*m.x280 + 0.0605186*m.x281 - 0.00381753*m.x282 - 0.00184947*m.x283
+ 0.00234081*m.x284 + 0.0028696*m.x285 + 0.00823346*m.x286 + 0.00765951*m.x287
+ 0.00284298*m.x288 + 0.00246263*m.x289 - 0.000739706*m.x290 + 0.0125211*m.x291
- 0.000736787*m.x292 + 0.00421174*m.x293 + 0.00453567*m.x294 + 0.0114023*m.x295
+ 0.00705981*m.x296 - 0.000688029*m.x297 + 0.00418666*m.x298 + 0.00132274*m.x299
+ 0.00955838*m.x300 - 0.00343351*m.x301 + 0.00462039*m.x302 + 0.00284859*m.x303 == 0)
m.c285 = Constraint(expr= - m.x180 - 0.00185436*m.x204 - 0.000409026*m.x205 - 0.00614724*m.x206 - 0.00105264*m.x207
+ 0.00286914*m.x208 - 0.00601197*m.x209 + 0.00396196*m.x210 + 0.000351167*m.x211
+ 0.00814529*m.x212 - 0.0025043*m.x213 + 0.00227186*m.x214 + 0.00309677*m.x215
- 0.00136311*m.x216 - 0.00602015*m.x217 + 0.000288227*m.x218 + 0.0020842*m.x219
+ 0.00732999*m.x220 - 0.00295186*m.x221 - 0.00282066*m.x222 - 0.0030116*m.x223
+ 0.00603936*m.x224 - 0.000568168*m.x225 + 0.00168508*m.x226 - 0.000125577*m.x227
+ 0.00216037*m.x228 - 0.00374261*m.x229 + 0.00954078*m.x230 - 0.000254586*m.x231
+ 0.00777778*m.x232 + 0.00342719*m.x233 - 0.0014036*m.x234 + 0.000602209*m.x235
+ 0.000341894*m.x236 + 0.0037276*m.x237 - 0.00283527*m.x238 - 0.000204738*m.x239
+ 0.00412862*m.x240 + 0.00380334*m.x241 + 0.00809556*m.x242 + 0.00297247*m.x243
+ 0.000995878*m.x244 + 0.00713668*m.x245 + 0.00244117*m.x246 - 0.000466954*m.x247
+ 0.00753084*m.x248 + 0.0010729*m.x249 + 0.00145566*m.x250 - 0.00680418*m.x251
+ 0.000794467*m.x252 + 0.00205383*m.x253 - 0.000981274*m.x254 + 6.81408E-5*m.x255
- 0.00488771*m.x256 + 0.000921016*m.x257 + 0.00261019*m.x258 - 0.00271758*m.x259
+ 0.000965316*m.x260 - 0.00479156*m.x261 + 0.00410639*m.x262 + 0.00797918*m.x263
+ 0.0561216*m.x264 - 0.000413564*m.x265 + 0.00309633*m.x266 - 0.00400538*m.x267
+ 0.00170909*m.x268 + 0.00170468*m.x269 + 0.00531632*m.x270 + 0.00425277*m.x271
+ 0.00635637*m.x272 + 0.000902665*m.x273 - 0.00153684*m.x274 + 0.00665831*m.x275
+ 0.00171519*m.x276 + 0.000735431*m.x277 + 0.00330387*m.x278 - 0.00291362*m.x279
+ 0.00385198*m.x280 - 0.00381753*m.x281 + 0.19913*m.x282 + 0.00501413*m.x283
+ 0.00275071*m.x284 + 0.00815821*m.x285 + 0.00164795*m.x286 - 0.00050972*m.x287
+ 0.000377268*m.x288 + 0.00376524*m.x289 - 0.00196578*m.x290 - 0.00288*m.x291
+ 0.00939099*m.x292 - 0.000222728*m.x293 + 0.0123212*m.x294 - 0.0056184*m.x295
- 0.00793664*m.x296 + 0.00208083*m.x297 - 0.00216442*m.x298 - 0.0058322*m.x299
+ 0.00684748*m.x300 + 0.00539178*m.x301 + 0.00822951*m.x302 + 0.000459309*m.x303 == 0)
m.c286 = Constraint(expr= - m.x181 + 0.0139088*m.x204 + 0.00669345*m.x205 + 0.00806025*m.x206 + 0.00531498*m.x207
+ 0.00026152*m.x208 - 0.00277281*m.x209 + 0.00197483*m.x210 + 0.00240495*m.x211
+ 0.000337824*m.x212 + 0.00627615*m.x213 + 0.00094864*m.x214 - 0.00314082*m.x215
- 0.00169506*m.x216 + 0.00971903*m.x217 + 0.00677297*m.x218 + 0.00256288*m.x219
+ 0.00605617*m.x220 + 0.00938947*m.x221 - 0.0064102*m.x222 - 0.00201799*m.x223
- 0.000855626*m.x224 + 0.00655708*m.x225 + 0.00717688*m.x226 + 0.000482661*m.x227
- 0.000699399*m.x228 - 0.002876*m.x229 - 0.00260552*m.x230 + 0.00671298*m.x231
- 0.000369335*m.x232 - 0.0024266*m.x233 + 0.00439362*m.x234 + 0.00499603*m.x235
- 0.00292742*m.x236 - 0.0010051*m.x237 - 0.00290324*m.x238 + 0.00299286*m.x239
+ 0.00264123*m.x240 + 0.00381492*m.x241 + 0.00378329*m.x242 + 0.00569595*m.x243
- 0.000313695*m.x244 - 0.00695821*m.x245 + 0.00776276*m.x246 - 0.00100195*m.x247
+ 0.000994392*m.x248 + 0.006249*m.x249 - 0.000197051*m.x250 + 0.0137323*m.x251
+ 0.00387197*m.x252 + 0.00641984*m.x253 + 0.00185637*m.x254 - 0.00245755*m.x255
- 0.000420988*m.x256 + 0.000728519*m.x257 + 0.00168293*m.x258 + 2.01133E-5*m.x259
+ 0.00959794*m.x260 - 0.000175807*m.x261 - 0.00321313*m.x262 + 0.00353012*m.x263
+ 0.00206552*m.x264 + 0.00177553*m.x265 - 0.00431355*m.x266 - 0.00481033*m.x267
- 0.0031579*m.x268 + 0.00110864*m.x269 - 0.00270393*m.x270 - 0.00201782*m.x271
+ 0.00300545*m.x272 + 0.00349484*m.x273 + 0.00166093*m.x274 + 0.00963207*m.x275
+ 0.00484394*m.x276 + 0.00557963*m.x277 + 0.00277583*m.x278 + 0.0114267*m.x279
+ 0.00322206*m.x280 - 0.00184947*m.x281 + 0.00501413*m.x282 + 0.126423*m.x283
- 0.00162189*m.x284 + 0.000788655*m.x285 - 0.00346789*m.x286 + 0.00325763*m.x287
+ 0.00299874*m.x288 + 0.00620979*m.x289 + 0.0117406*m.x290 - 0.00806051*m.x291
+ 0.00152584*m.x292 - 0.00353569*m.x293 - 0.000134223*m.x294 + 0.000240556*m.x295
+ 0.00454787*m.x296 + 0.00970541*m.x297 - 0.00292971*m.x298 + 0.0013331*m.x299
+ 0.00376435*m.x300 - 0.00118927*m.x301 + 0.0021784*m.x302 - 0.00418691*m.x303 == 0)
m.c287 = Constraint(expr= - m.x182 + 0.00169537*m.x204 + 0.00587367*m.x205 + 0.0109797*m.x206 + 0.00188864*m.x207
+ 0.010098*m.x208 + 0.00597799*m.x209 + 0.00590748*m.x210 + 0.000367094*m.x211
- 0.00392219*m.x212 + 0.00371545*m.x213 - 0.00147339*m.x214 - 0.00237874*m.x215
- 0.00256875*m.x216 + 0.00813772*m.x217 + 0.000330943*m.x218 + 0.00240084*m.x219
- 0.000467489*m.x220 - 0.00281231*m.x221 + 0.00786204*m.x222 - 0.00259834*m.x223
- 9.51042E-5*m.x224 + 0.0132513*m.x225 + 0.00442955*m.x226 + 0.00549587*m.x227
- 0.000380813*m.x228 + 0.00564875*m.x229 + 0.00931525*m.x230 + 0.0117108*m.x231
+ 0.00409714*m.x232 + 0.00516382*m.x233 + 0.00824533*m.x234 + 0.00484005*m.x235
+ 0.00505718*m.x236 + 0.0025218*m.x237 - 0.00552971*m.x238 + 0.00431272*m.x239
+ 0.00669612*m.x240 + 0.00349169*m.x241 + 0.00368273*m.x242 + 0.001847*m.x243
- 0.000172475*m.x244 + 0.00804511*m.x245 - 0.000311621*m.x246 + 0.00342181*m.x247
- 0.0010613*m.x248 + 0.00265281*m.x249 + 0.00302341*m.x250 + 0.00633139*m.x251
+ 0.00198803*m.x252 + 0.00684435*m.x253 + 0.00200309*m.x254 + 0.0117758*m.x255
- 0.00234208*m.x256 - 0.00445797*m.x257 + 0.00651943*m.x258 + 0.00508838*m.x259
+ 0.000370277*m.x260 - 4.69764E-5*m.x261 + 0.00241956*m.x262 + 0.0106118*m.x263
+ 0.00059783*m.x264 + 0.000254788*m.x265 - 0.00123317*m.x266 + 0.000267753*m.x267
+ 0.0092312*m.x268 + 0.00727345*m.x269 - 0.000304736*m.x270 + 0.00117189*m.x271
- 0.000607595*m.x272 - 0.00558798*m.x273 + 0.00201403*m.x274 + 0.00392921*m.x275
- 0.006173*m.x276 + 0.000328794*m.x277 + 0.0174915*m.x278 + 0.00999273*m.x279
+ 0.0100535*m.x280 + 0.00234081*m.x281 + 0.00275071*m.x282 - 0.00162189*m.x283
+ 0.0537365*m.x284 + 0.00383147*m.x285 + 0.000945652*m.x286 + 0.0102167*m.x287
+ 0.00670296*m.x288 - 0.00161202*m.x289 + 0.00107191*m.x290 + 0.00331932*m.x291
+ 0.00912186*m.x292 - 0.00120435*m.x293 + 0.00090878*m.x294 - 0.00195931*m.x295
- 0.000874528*m.x296 - 0.00561291*m.x297 + 0.00316007*m.x298 + 0.00326358*m.x299
+ 0.0032359*m.x300 + 0.00478097*m.x301 + 0.00997826*m.x302 + 0.00455818*m.x303 == 0)
m.c288 = Constraint(expr= - m.x183 - 0.00322776*m.x204 + 0.00304423*m.x205 + 0.00481845*m.x206 + 0.00359302*m.x207
+ 0.00162371*m.x208 + 0.00573361*m.x209 + 0.00820622*m.x210 - 0.000642028*m.x211
+ 0.0200781*m.x212 + 0.00330175*m.x213 + 0.00528313*m.x214 + 0.00652441*m.x215
+ 0.0112133*m.x216 - 0.00255056*m.x217 + 0.00658359*m.x218 + 0.00108106*m.x219
+ 0.00375754*m.x220 + 0.00406283*m.x221 - 0.00449328*m.x222 + 2.88534E-5*m.x223
+ 0.00328428*m.x224 + 0.00364648*m.x225 + 0.000629589*m.x226 - 0.000664034*m.x227
+ 0.00135096*m.x228 + 0.00529419*m.x229 + 0.000400638*m.x230 + 0.00614105*m.x231
- 0.000584153*m.x232 + 0.00568177*m.x233 + 0.00200915*m.x234 + 0.0129378*m.x235
- 0.000112291*m.x236 + 0.0044636*m.x237 + 0.0028359*m.x238 + 0.000643374*m.x239
+ 0.00461646*m.x240 + 0.00806328*m.x241 + 0.00160903*m.x242 + 2.32746E-5*m.x243
+ 0.00144712*m.x244 + 0.0045584*m.x245 - 0.0011604*m.x246 + 0.00300422*m.x247
+ 0.00748896*m.x248 + 0.00400057*m.x249 + 0.00322867*m.x250 - 5.13418E-5*m.x251
+ 0.00165035*m.x252 + 0.00461578*m.x253 + 0.00274343*m.x254 - 0.000210065*m.x255
+ 0.00819901*m.x256 + 0.00436349*m.x257 - 0.000228966*m.x258 + 0.00528738*m.x259
+ 0.00152795*m.x260 + 0.00535958*m.x261 + 0.00469951*m.x262 + 0.00180257*m.x263
+ 0.00506047*m.x264 + 0.000483366*m.x265 - 0.00107592*m.x266 - 0.00462929*m.x267
+ 0.00139163*m.x268 + 0.00278892*m.x269 + 0.00310389*m.x270 + 0.00205926*m.x271
+ 0.00303877*m.x272 - 0.00152774*m.x273 + 0.00412755*m.x274 - 0.00543762*m.x275
+ 0.00504263*m.x276 + 0.00283205*m.x277 - 0.00134198*m.x278 + 0.000879691*m.x279
+ 0.00351688*m.x280 + 0.0028696*m.x281 + 0.00815821*m.x282 + 0.000788655*m.x283
+ 0.00383147*m.x284 + 0.0365864*m.x285 + 0.00400753*m.x286 + 0.00286442*m.x287
+ 0.00446958*m.x288 + 0.00111769*m.x289 - 0.0020057*m.x290 + 0.00799239*m.x291
+ 0.00470659*m.x292 - 0.000670353*m.x293 - 0.00177383*m.x294 + 0.00535235*m.x295
+ 0.00245751*m.x296 + 0.00634908*m.x297 + 0.00849798*m.x298 + 0.00413392*m.x299
+ 0.00433132*m.x300 + 0.00189491*m.x301 + 0.00149054*m.x302 + 0.0067696*m.x303 == 0)
m.c289 = Constraint(expr= - m.x184 + 0.00738761*m.x204 + 0.00575059*m.x205 - 0.003182*m.x206 + 0.00189728*m.x207
+ 0.00109136*m.x208 + 0.0187193*m.x209 + 0.00157202*m.x210 - 0.0066337*m.x211
+ 0.0101854*m.x212 + 0.00434643*m.x213 + 0.0088821*m.x214 + 0.00159051*m.x215
+ 0.012204*m.x216 + 0.0141748*m.x217 + 0.0029954*m.x218 + 0.00593105*m.x219
+ 0.00515253*m.x220 + 0.000356947*m.x221 - 0.00342739*m.x222 + 0.00535464*m.x223
+ 0.000831883*m.x224 + 0.0025368*m.x225 - 0.00381097*m.x226 - 0.00216225*m.x227
+ 0.00146462*m.x228 + 0.00183255*m.x229 - 0.000672593*m.x230 + 0.0126386*m.x231
- 5.10761E-5*m.x232 + 0.00333333*m.x233 + 0.00433982*m.x234 + 0.00126871*m.x235
+ 0.00142508*m.x236 - 0.00398086*m.x237 - 0.00191638*m.x238 + 0.000528405*m.x239
+ 0.0036023*m.x240 + 0.00248382*m.x241 - 0.000963309*m.x242 + 0.00157998*m.x243
- 0.000953639*m.x244 + 0.00879099*m.x245 + 0.000185014*m.x246 - 0.00124986*m.x247
+ 0.0112013*m.x248 - 0.00122283*m.x249 + 0.0042178*m.x250 + 0.0162123*m.x251
+ 0.00321866*m.x252 + 0.0119365*m.x253 + 0.00419778*m.x254 + 0.0058935*m.x255
+ 0.00341215*m.x256 + 0.00564621*m.x257 + 0.00685513*m.x258 + 0.00177656*m.x259
+ 0.00378016*m.x260 - 0.00150618*m.x261 - 0.000587868*m.x262 + 0.00554875*m.x263
+ 0.00221597*m.x264 + 0.00434862*m.x265 - 0.00299895*m.x266 - 0.00477368*m.x267
- 0.00265918*m.x268 - 0.000721759*m.x269 + 0.00378933*m.x270 + 0.00108221*m.x271
+ 0.00344426*m.x272 + 0.00608886*m.x273 + 0.000718975*m.x274 + 0.010873*m.x275
+ 0.000887498*m.x276 - 0.00256622*m.x277 + 0.00643863*m.x278 + 0.00171019*m.x279
- 0.00191643*m.x280 + 0.00823346*m.x281 + 0.00164795*m.x282 - 0.00346789*m.x283
+ 0.000945652*m.x284 + 0.00400753*m.x285 + 0.084493*m.x286 + 0.000927117*m.x287
+ 0.000915556*m.x288 + 0.00112663*m.x289 - 0.000217029*m.x290 + 0.00462032*m.x291
+ 0.000489651*m.x292 + 0.00234328*m.x293 - 0.000240824*m.x294 + 0.00491409*m.x295
+ 0.00621639*m.x296 + 0.00557977*m.x297 + 0.00777728*m.x298 + 0.0170867*m.x299
+ 0.00237553*m.x300 + 0.00254531*m.x301 + 0.000729482*m.x302 + 0.000959806*m.x303 == 0)
m.c290 = Constraint(expr= - m.x185 - 0.00338701*m.x204 + 0.0022757*m.x205 + 0.00729708*m.x206 + 0.00111561*m.x207
+ 0.00784252*m.x208 + 0.00612747*m.x209 + 0.00465324*m.x210 + 0.00521946*m.x211
+ 0.010518*m.x212 + 0.00899061*m.x213 + 0.00267439*m.x214 + 0.00062359*m.x215
+ 0.000692709*m.x216 + 0.00697572*m.x217 + 0.00409136*m.x218 + 0.00633478*m.x219
+ 0.00209517*m.x220 - 0.00704698*m.x221 + 0.00290604*m.x222 + 0.00270192*m.x223
- 0.00351138*m.x224 + 0.003167*m.x225 + 0.00553188*m.x226 + 0.000631923*m.x227
- 0.000571967*m.x228 + 0.00445827*m.x229 + 0.00821988*m.x230 + 0.00409707*m.x231
- 0.000896178*m.x232 + 0.00790729*m.x233 - 0.00368101*m.x234 + 0.0109368*m.x235
+ 0.00445551*m.x236 + 0.00037716*m.x237 + 0.000588805*m.x238 + 0.0038775*m.x239
- 0.0025638*m.x240 + 0.00101753*m.x241 + 0.000387026*m.x242 + 0.00521645*m.x243
+ 0.00753955*m.x244 + 0.00389765*m.x245 + 0.00122307*m.x246 - 5.94885E-5*m.x247
+ 0.00952063*m.x248 + 0.000588542*m.x249 - 0.00044828*m.x250 + 0.00880031*m.x251
+ 0.000171898*m.x252 + 0.00806339*m.x253 + 0.0011744*m.x254 + 0.00461282*m.x255
+ 0.00259963*m.x256 + 0.00194367*m.x257 + 0.00349243*m.x258 + 0.00390817*m.x259
+ 0.00380959*m.x260 + 0.00164593*m.x261 - 0.0046356*m.x262 + 0.00340277*m.x263
+ 0.00470215*m.x264 - 0.00339015*m.x265 + 0.00239151*m.x266 - 0.0034161*m.x267
+ 0.00891526*m.x268 + 0.00479513*m.x269 + 0.00270045*m.x270 - 0.000509977*m.x271
- 0.000151734*m.x272 + 0.0134833*m.x273 + 0.000956443*m.x274 + 0.00656066*m.x275
+ 0.00438259*m.x276 + 0.00639915*m.x277 + 0.00424422*m.x278 + 0.0139977*m.x279
+ 0.00378979*m.x280 + 0.00765951*m.x281 - 0.00050972*m.x282 + 0.00325763*m.x283
+ 0.0102167*m.x284 + 0.00286442*m.x285 + 0.000927117*m.x286 + 0.0658614*m.x287
+ 0.0072399*m.x288 + 0.00430023*m.x289 + 0.00399968*m.x290 + 0.00579051*m.x291
+ 0.00604453*m.x292 + 0.00257419*m.x293 + 0.000750291*m.x294 + 0.00203007*m.x295
- 5.98431E-5*m.x296 + 0.00429026*m.x297 + 0.00994608*m.x298 - 0.00428917*m.x299
+ 0.00492553*m.x300 - 0.00183033*m.x301 + 0.00598074*m.x302 + 0.00348814*m.x303 == 0)
m.c291 = Constraint(expr= - m.x186 + 0.000632136*m.x204 + 0.00555164*m.x205 + 0.00314668*m.x206 + 0.00562859*m.x207
+ 0.00882019*m.x208 + 0.00350368*m.x209 + 0.00187347*m.x210 + 0.00597375*m.x211
+ 0.00605484*m.x212 + 0.00419388*m.x213 + 0.00393964*m.x214 + 0.000537233*m.x215
+ 0.00231345*m.x216 - 0.000459789*m.x217 + 0.00355076*m.x218 + 0.00470412*m.x219
+ 0.00294012*m.x220 + 0.00116945*m.x221 + 0.00297731*m.x222 + 0.000175467*m.x223
+ 0.000327824*m.x224 + 0.000670063*m.x225 + 0.00850491*m.x226 + 9.34236E-5*m.x227
+ 0.00428001*m.x228 - 0.000344244*m.x229 + 0.00442595*m.x230 + 0.00509678*m.x231
+ 0.00143506*m.x232 + 0.00874995*m.x233 + 0.00283946*m.x234 + 0.0240688*m.x235
+ 0.00496328*m.x236 + 0.00428731*m.x237 + 0.00709492*m.x238 + 0.000936991*m.x239
+ 0.00488446*m.x240 + 0.00966172*m.x241 - 0.000747807*m.x242 + 0.00442051*m.x243
+ 0.00801224*m.x244 + 0.0126359*m.x245 + 0.0034865*m.x246 + 0.00328713*m.x247
- 0.00220101*m.x248 + 0.00328499*m.x249 + 0.00548425*m.x250 - 0.00234105*m.x251
+ 0.00933104*m.x252 + 0.0103044*m.x253 + 0.000952343*m.x254 + 0.00333587*m.x255
- 0.00185458*m.x256 - 0.0052063*m.x257 + 0.00208497*m.x258 + 0.00522697*m.x259
+ 0.00449849*m.x260 - 0.00323282*m.x261 + 0.00523023*m.x262 + 0.00314873*m.x263
+ 0.00565729*m.x264 + 0.00162127*m.x265 + 0.00504485*m.x266 + 0.000222907*m.x267
+ 0.0041968*m.x268 + 0.00119802*m.x269 + 0.00133532*m.x270 + 0.00613474*m.x271
- 0.000959542*m.x272 + 0.00145221*m.x273 + 0.0024877*m.x274 + 0.00539259*m.x275
+ 0.00418985*m.x276 + 0.0101988*m.x277 + 0.0086924*m.x278 + 0.00246352*m.x279
+ 0.00355674*m.x280 + 0.00284298*m.x281 + 0.000377268*m.x282 + 0.00299874*m.x283
+ 0.00670296*m.x284 + 0.00446958*m.x285 + 0.000915556*m.x286 + 0.0072399*m.x287
+ 0.0438316*m.x288 + 0.00426318*m.x289 + 0.00639346*m.x290 + 0.00455512*m.x291
+ 0.00344782*m.x292 + 0.00233747*m.x293 + 0.0020567*m.x294 + 0.00460018*m.x295
+ 0.0005399*m.x296 + 0.00652496*m.x297 + 0.00480221*m.x298 + 0.00101452*m.x299
+ 0.00380777*m.x300 - 0.00364829*m.x301 + 0.003082*m.x302 - 0.000738294*m.x303 == 0)
m.c292 = Constraint(expr= - m.x187 + 0.00125905*m.x204 + 0.00580589*m.x205 + 0.00093968*m.x206 + 0.00605398*m.x207
+ 0.000598062*m.x208 + 0.000722427*m.x209 + 0.000428549*m.x210 - 0.000142638*m.x211
+ 0.000377649*m.x212 + 0.00126509*m.x213 + 0.00396771*m.x214 - 9.36397E-5*m.x215
+ 0.00276166*m.x216 + 0.00681506*m.x217 + 0.00265398*m.x218 + 0.0036723*m.x219
+ 0.00822675*m.x220 + 0.00506331*m.x221 + 0.00329549*m.x222 + 0.00337965*m.x223
+ 0.00252261*m.x224 + 0.00223027*m.x225 + 0.0052604*m.x226 + 0.00532323*m.x227
+ 0.00246929*m.x228 + 0.00160669*m.x229 + 9.7777E-5*m.x230 + 0.00201509*m.x231
- 0.00102564*m.x232 + 0.00108982*m.x233 + 0.0020167*m.x234 - 0.000216395*m.x235
+ 0.000556729*m.x236 + 0.0020993*m.x237 + 0.00428712*m.x238 - 0.00199242*m.x239
+ 0.00447164*m.x240 + 0.00687358*m.x241 + 0.00119059*m.x242 + 0.00558644*m.x243
+ 0.0112013*m.x244 + 0.00467816*m.x245 + 0.00960237*m.x246 + 0.00273221*m.x247
+ 0.00611291*m.x248 + 0.000580561*m.x249 + 0.00168605*m.x250 + 0.00247115*m.x251
+ 0.00315924*m.x252 + 0.00439893*m.x253 + 0.00341538*m.x254 + 0.00601159*m.x255
+ 0.00165765*m.x256 + 0.00164762*m.x257 + 0.000860289*m.x258 + 0.00419445*m.x259
+ 0.00350555*m.x260 + 0.00658013*m.x261 + 0.0033164*m.x262 + 0.00310593*m.x263
+ 0.000952909*m.x264 + 0.00452576*m.x265 + 0.00186508*m.x266 + 0.00216417*m.x267
+ 0.00379037*m.x268 + 0.00319581*m.x269 + 0.00280379*m.x270 + 0.0035637*m.x271
+ 0.0027039*m.x272 + 0.0071947*m.x273 + 0.00167048*m.x274 + 0.0115011*m.x275
+ 0.00590139*m.x276 + 0.00512473*m.x277 + 0.000133115*m.x278 + 0.00601652*m.x279
+ 0.00196838*m.x280 + 0.00246263*m.x281 + 0.00376524*m.x282 + 0.00620979*m.x283
- 0.00161202*m.x284 + 0.00111769*m.x285 + 0.00112663*m.x286 + 0.00430023*m.x287
+ 0.00426318*m.x288 + 0.0308378*m.x289 - 9.17476E-5*m.x290 + 0.00159558*m.x291
+ 0.00102348*m.x292 + 0.00266511*m.x293 + 0.00216533*m.x294 + 0.00403771*m.x295
+ 0.00164628*m.x296 - 0.00336155*m.x297 + 0.000136297*m.x298 + 0.000407005*m.x299
+ 0.00508056*m.x300 + 0.0027572*m.x301 + 0.00463908*m.x302 + 0.00143901*m.x303 == 0)
m.c293 = Constraint(expr= - m.x188 + 0.00498931*m.x204 + 0.00361309*m.x205 + 0.0046813*m.x206 + 0.00853829*m.x207
+ 0.0052387*m.x208 - 0.00222972*m.x209 - 0.00285777*m.x210 - 0.000178386*m.x211
+ 0.00919154*m.x212 - 5.10678E-6*m.x213 + 0.00290804*m.x214 + 0.000546637*m.x215
+ 0.00225276*m.x216 + 0.000426248*m.x217 + 0.00263496*m.x218 + 0.00419729*m.x219
+ 0.00373459*m.x220 + 0.00116521*m.x221 + 0.000545613*m.x222 + 0.00140219*m.x223
- 0.000723307*m.x224 - 0.0003553*m.x225 + 0.00630907*m.x226 + 0.00760376*m.x227
+ 0.00505738*m.x228 - 0.00276824*m.x229 + 0.00362104*m.x230 + 0.000363534*m.x231
+ 0.00929697*m.x232 + 0.00847563*m.x233 - 0.00442035*m.x234 + 0.00218847*m.x235
+ 0.00173871*m.x236 + 0.00773233*m.x237 + 0.00918313*m.x238 + 0.004542*m.x239
+ 0.00473894*m.x240 + 0.00303402*m.x241 + 0.00357163*m.x242 + 0.00249097*m.x243
+ 0.00334346*m.x244 + 0.00586578*m.x245 - 0.00545954*m.x246 + 0.00345779*m.x247
- 0.00609654*m.x248 + 0.000227831*m.x249 - 0.000888688*m.x250 + 0.00278431*m.x251
+ 0.00241389*m.x252 + 0.00688742*m.x253 - 0.00226972*m.x254 - 0.00295399*m.x255
+ 0.0036396*m.x256 - 0.000112278*m.x257 + 0.00190276*m.x258 + 0.00330037*m.x259
+ 0.00353625*m.x260 + 0.00524124*m.x261 + 0.00630061*m.x262 + 0.00234241*m.x263
- 0.00116189*m.x264 + 0.00597812*m.x265 - 0.00261967*m.x266 - 0.000119858*m.x267
+ 0.00152491*m.x268 + 0.00188211*m.x269 + 0.00340292*m.x270 + 0.00316685*m.x271
- 0.00101768*m.x272 + 0.00751873*m.x273 - 0.00563257*m.x274 + 0.00533348*m.x275
+ 0.00101318*m.x276 + 0.002495*m.x277 + 0.00342096*m.x278 + 0.00334106*m.x279
- 0.000454484*m.x280 - 0.000739706*m.x281 - 0.00196578*m.x282 + 0.0117406*m.x283
+ 0.00107191*m.x284 - 0.0020057*m.x285 - 0.000217029*m.x286 + 0.00399968*m.x287
+ 0.00639346*m.x288 - 9.17476E-5*m.x289 + 0.0546709*m.x290 - 0.00306556*m.x291
- 0.00130673*m.x292 + 0.00128925*m.x293 + 0.00382404*m.x294 - 0.00165847*m.x295
+ 0.0056648*m.x296 - 0.00388715*m.x297 - 0.00453289*m.x298 - 0.00269182*m.x299
+ 0.000442839*m.x300 - 0.00132366*m.x301 - 0.000573397*m.x302 - 0.00340939*m.x303 == 0)
m.c294 = Constraint(expr= - m.x189 - 0.00223203*m.x204 + 0.00918406*m.x205 + 0.00588727*m.x206 + 0.00794939*m.x207
+ 0.00384785*m.x208 + 0.00618374*m.x209 + 0.0153027*m.x210 - 0.00109134*m.x211
+ 0.00637465*m.x212 - 0.00500706*m.x213 + 0.00291132*m.x214 + 0.000119304*m.x215
+ 0.00887897*m.x216 + 0.00883306*m.x217 + 0.00340833*m.x218 + 0.00371118*m.x219
+ 0.0030272*m.x220 + 0.00400767*m.x221 + 0.0142805*m.x222 + 0.00504492*m.x223
- 0.00287027*m.x224 + 0.00805896*m.x225 + 0.00122268*m.x226 + 0.00424627*m.x227
+ 0.00244428*m.x228 + 0.00746466*m.x229 + 0.00715697*m.x230 + 0.000104518*m.x231
+ 0.000416892*m.x232 + 0.00467438*m.x233 - 0.00255785*m.x234 + 0.00462496*m.x235
- 0.00650082*m.x236 + 0.00108107*m.x237 + 0.00156534*m.x238 + 0.00331247*m.x239
+ 0.00741949*m.x240 + 0.008727*m.x241 + 0.0049149*m.x242 + 0.00567517*m.x243
- 0.0105804*m.x244 + 0.0112814*m.x245 - 0.000788822*m.x246 + 0.00419154*m.x247
+ 0.000316901*m.x248 + 0.0066509*m.x249 + 0.004772*m.x250 + 0.00463181*m.x251
+ 0.00336441*m.x252 + 0.00194067*m.x253 + 0.00121543*m.x254 + 0.0231083*m.x255
+ 0.00499705*m.x256 - 0.000255111*m.x257 + 0.00214593*m.x258 + 0.00952656*m.x259
+ 0.00557726*m.x260 + 0.00454456*m.x261 + 0.00551966*m.x262 + 0.00590393*m.x263
+ 0.00694876*m.x264 + 2.54983E-5*m.x265 - 0.00111953*m.x266 + 0.0183023*m.x267
+ 0.0102022*m.x268 + 0.00479563*m.x269 + 0.00122189*m.x270 + 0.000164365*m.x271
- 0.00789306*m.x272 - 0.00136694*m.x273 + 0.00591306*m.x274 + 0.000781568*m.x275
+ 0.00599692*m.x276 - 6.81269E-5*m.x277 + 0.00617057*m.x278 + 0.0025963*m.x279
+ 0.00629473*m.x280 + 0.0125211*m.x281 - 0.00288*m.x282 - 0.00806051*m.x283
+ 0.00331932*m.x284 + 0.00799239*m.x285 + 0.00462032*m.x286 + 0.00579051*m.x287
+ 0.00455512*m.x288 + 0.00159558*m.x289 - 0.00306556*m.x290 + 0.0687124*m.x291
+ 0.00092997*m.x292 + 0.00496772*m.x293 + 0.00101083*m.x294 + 0.0032872*m.x295
+ 0.00334433*m.x296 - 0.00233066*m.x297 + 0.00346403*m.x298 + 0.0134367*m.x299
+ 0.00640805*m.x300 - 0.00798533*m.x301 + 0.00189799*m.x302 + 0.00886188*m.x303 == 0)
m.c295 = Constraint(expr= - m.x190 - 0.00161161*m.x204 + 0.00175607*m.x205 + 0.00856972*m.x206 - 0.00108004*m.x207
+ 0.00503042*m.x208 + 0.00230392*m.x209 + 0.00159813*m.x210 + 0.00239336*m.x211
+ 0.00244105*m.x212 + 0.00495567*m.x213 + 0.00247734*m.x214 - 0.00155886*m.x215
+ 0.00177462*m.x216 - 0.00113*m.x217 + 0.00444299*m.x218 + 0.000251759*m.x219
+ 0.00252714*m.x220 - 0.00210903*m.x221 + 0.00236164*m.x222 - 0.00136526*m.x223
+ 0.00383752*m.x224 + 0.00447158*m.x225 + 0.00666929*m.x226 - 0.000984769*m.x227
- 0.00119322*m.x228 + 0.00694152*m.x229 + 0.00559812*m.x230 - 0.000217263*m.x231
+ 0.00340158*m.x232 + 0.0016858*m.x233 + 0.00125151*m.x234 - 0.00173756*m.x235
+ 0.00670699*m.x236 + 0.00180858*m.x237 + 0.00072917*m.x238 + 0.00015452*m.x239
- 0.00059291*m.x240 + 0.00345779*m.x241 - 0.000828779*m.x242 + 0.00151899*m.x243
+ 0.00626909*m.x244 + 0.00718189*m.x245 + 0.000621542*m.x246 + 0.00399493*m.x247
+ 0.00160516*m.x248 + 0.00019791*m.x249 + 0.000505019*m.x250 + 0.00075518*m.x251
+ 4.30958E-5*m.x252 + 0.00365679*m.x253 + 0.00119416*m.x254 + 0.00273013*m.x255
+ 0.000213845*m.x256 + 0.00261688*m.x257 + 0.00371348*m.x258 + 0.00213073*m.x259
+ 0.00162287*m.x260 + 0.00520983*m.x261 + 0.00626743*m.x262 + 0.000439495*m.x263
+ 0.00562572*m.x264 - 0.00247603*m.x265 + 0.00813916*m.x266 + 0.00146243*m.x267
+ 0.00836314*m.x268 + 0.00585396*m.x269 + 0.00282862*m.x270 + 0.000853601*m.x271
+ 0.000904711*m.x272 + 0.0032967*m.x273 + 0.00042396*m.x274 + 0.00196384*m.x275
- 0.00270112*m.x276 + 0.00306404*m.x277 + 0.00674858*m.x278 + 0.00713089*m.x279
+ 0.00580576*m.x280 - 0.000736787*m.x281 + 0.00939099*m.x282 + 0.00152584*m.x283
+ 0.00912186*m.x284 + 0.00470659*m.x285 + 0.000489651*m.x286 + 0.00604453*m.x287
+ 0.00344782*m.x288 + 0.00102348*m.x289 - 0.00130673*m.x290 + 0.00092997*m.x291
+ 0.0336811*m.x292 + 0.00253178*m.x293 - 0.00190276*m.x294 + 0.000244984*m.x295
+ 0.000960586*m.x296 - 0.00227507*m.x297 + 0.0029063*m.x298 + 0.00678876*m.x299
+ 0.0001247*m.x300 - 0.00371543*m.x301 + 0.00766411*m.x302 + 0.000597387*m.x303 == 0)
m.c296 = Constraint(expr= - m.x191 + 0.000698504*m.x204 + 0.0017579*m.x205 + 0.0014989*m.x206 + 0.00250493*m.x207
+ 0.0024631*m.x208 - 8.26039E-6*m.x209 - 0.00186303*m.x210 + 0.0002248*m.x211
+ 0.00434059*m.x212 - 0.00234243*m.x213 + 2.81248E-5*m.x214 - 0.00294322*m.x215
+ 0.000872704*m.x216 + 0.00170265*m.x217 + 0.0067512*m.x218 + 0.00531186*m.x219
+ 0.00343189*m.x220 - 0.00100077*m.x221 - 0.0011576*m.x222 - 0.00162571*m.x223
+ 0.00183226*m.x224 + 0.000707919*m.x225 + 0.00744101*m.x226 - 0.000472034*m.x227
+ 0.00181174*m.x228 - 0.00346329*m.x229 + 0.00126776*m.x230 + 0.000955159*m.x231
+ 0.00170814*m.x232 + 0.000365981*m.x233 - 0.00145108*m.x234 + 0.000369864*m.x235
- 0.000640342*m.x236 - 0.00124112*m.x237 + 0.00366701*m.x238 + 0.00451357*m.x239
+ 0.000506587*m.x240 + 0.00402615*m.x241 - 0.00332156*m.x242 + 0.00425113*m.x243
+ 0.000678624*m.x244 + 0.00473931*m.x245 + 8.36128E-5*m.x246 + 0.00448916*m.x247
+ 0.00470546*m.x248 + 0.00589171*m.x249 + 0.00313289*m.x250 - 0.00287996*m.x251
+ 0.00271535*m.x252 + 0.000101984*m.x253 + 0.00550828*m.x254 + 0.00101519*m.x255
+ 0.00251321*m.x256 + 0.00246219*m.x257 + 0.00255756*m.x258 - 0.00172869*m.x259
+ 0.00118145*m.x260 + 0.00135714*m.x261 + 0.00507348*m.x262 - 0.00164086*m.x263
+ 0.00278368*m.x264 + 0.0044097*m.x265 + 0.00116867*m.x266 + 0.00652183*m.x267
+ 0.00119311*m.x268 - 0.000300368*m.x269 + 0.00394438*m.x270 - 0.00132464*m.x271
- 0.000843722*m.x272 + 0.00352111*m.x273 + 3.84816E-5*m.x274 + 0.00184219*m.x275
- 0.000435065*m.x276 - 0.00158105*m.x277 + 0.00060276*m.x278 + 0.000877639*m.x279
+ 0.000568793*m.x280 + 0.00421174*m.x281 - 0.000222728*m.x282 - 0.00353569*m.x283
- 0.00120435*m.x284 - 0.000670353*m.x285 + 0.00234328*m.x286 + 0.00257419*m.x287
+ 0.00233747*m.x288 + 0.00266511*m.x289 + 0.00128925*m.x290 + 0.00496772*m.x291
+ 0.00253178*m.x292 + 0.0257082*m.x293 + 0.000305788*m.x294 + 0.00485521*m.x295
+ 0.00393184*m.x296 - 0.00207377*m.x297 + 0.00289386*m.x298 + 0.00146898*m.x299
- 0.000633614*m.x300 - 0.000187625*m.x301 + 0.00119486*m.x302 + 0.00260126*m.x303 == 0)
m.c297 = Constraint(expr= - m.x192 + 0.000973632*m.x204 - 0.00440575*m.x205 - 0.0012223*m.x206 + 6.36275E-5*m.x207
+ 0.00278995*m.x208 + 0.00470948*m.x209 + 0.00292004*m.x210 + 0.00134415*m.x211
- 0.00461254*m.x212 - 0.00102392*m.x213 + 0.000966712*m.x214 - 0.000986956*m.x215
+ 0.0042304*m.x216 + 0.00495909*m.x217 + 0.00225846*m.x218 + 0.00468134*m.x219
+ 0.00558036*m.x220 - 0.00232507*m.x221 - 0.000911744*m.x222 - 7.79346E-6*m.x223
- 0.000513898*m.x224 - 0.000179214*m.x225 + 0.000456284*m.x226 + 0.0032716*m.x227
- 0.000288904*m.x228 - 0.000701028*m.x229 + 0.000428826*m.x230 - 0.0064418*m.x231
+ 0.00314179*m.x232 + 0.0013091*m.x233 - 0.000936959*m.x234 + 0.00518077*m.x235
+ 0.00360938*m.x236 + 0.00633646*m.x237 - 0.00358706*m.x238 - 0.00325512*m.x239
+ 0.00202802*m.x240 + 0.000154347*m.x241 + 0.000844659*m.x242 + 0.000283697*m.x243
+ 0.00452262*m.x244 + 0.0022565*m.x245 + 0.00413836*m.x246 + 0.00118132*m.x247
- 0.00380484*m.x248 - 0.000623163*m.x249 + 0.00119693*m.x250 - 0.00533256*m.x251
+ 0.00462087*m.x252 + 0.00583528*m.x253 + 0.00304948*m.x254 + 0.00177864*m.x255
+ 7.57559E-5*m.x256 + 0.00318467*m.x257 - 0.00201343*m.x258 + 0.00143223*m.x259
+ 0.0018647*m.x260 + 0.00263088*m.x261 - 0.00112337*m.x262 - 0.00383165*m.x263
+ 0.00369458*m.x264 + 0.00452471*m.x265 - 0.000798317*m.x266 + 0.000896056*m.x267
- 0.000302283*m.x268 + 0.000255675*m.x269 + 0.00508295*m.x270 + 0.00386284*m.x271
+ 0.00193938*m.x272 + 0.00355609*m.x273 - 0.000816933*m.x274 + 0.00423463*m.x275
+ 0.00332285*m.x276 + 0.00146977*m.x277 + 0.00167034*m.x278 + 0.00380538*m.x279
- 0.000609214*m.x280 + 0.00453567*m.x281 + 0.0123212*m.x282 - 0.000134223*m.x283
+ 0.00090878*m.x284 - 0.00177383*m.x285 - 0.000240824*m.x286 + 0.000750291*m.x287
+ 0.0020567*m.x288 + 0.00216533*m.x289 + 0.00382404*m.x290 + 0.00101083*m.x291
- 0.00190276*m.x292 + 0.000305788*m.x293 + 0.0322277*m.x294 - 0.00106589*m.x295
+ 0.000467335*m.x296 - 0.000790828*m.x297 + 0.00499735*m.x298 + 0.00331171*m.x299
+ 0.00540673*m.x300 + 0.00460485*m.x301 + 0.000445662*m.x302 - 0.00218896*m.x303 == 0)
m.c298 = Constraint(expr= - m.x193 + 0.00322052*m.x204 + 0.000882362*m.x205 - 0.00398758*m.x206 + 0.00972923*m.x207
+ 0.00074696*m.x208 + 0.00203412*m.x209 + 0.000158573*m.x210 + 0.00625637*m.x211
+ 0.00181809*m.x212 + 0.000187615*m.x213 + 0.00204921*m.x214 + 0.0040052*m.x215
+ 0.00665568*m.x216 + 0.00711981*m.x217 + 0.00175025*m.x218 + 0.00142927*m.x219
+ 0.00282494*m.x220 + 0.0032323*m.x221 + 0.00290814*m.x222 + 0.00628695*m.x223
+ 0.00248209*m.x224 - 0.00343349*m.x225 + 0.00234935*m.x226 + 0.00763876*m.x227
- 0.00446445*m.x228 - 0.00834557*m.x229 - 0.00228492*m.x230 + 0.00195089*m.x231
+ 0.00196445*m.x232 + 0.00271448*m.x233 - 6.93028E-5*m.x234 + 0.00780177*m.x235
+ 0.00110968*m.x236 + 0.00394326*m.x237 + 0.000268238*m.x238 - 0.0021067*m.x239
+ 0.00774598*m.x240 + 0.0100018*m.x241 + 0.00455282*m.x242 + 0.00430656*m.x243
+ 0.00404098*m.x244 + 0.00361341*m.x245 - 0.000118642*m.x246 - 0.00106048*m.x247
- 0.00603313*m.x248 - 7.87584E-5*m.x249 + 0.00445284*m.x250 - 0.00290057*m.x251
+ 0.00710323*m.x252 + 0.00511653*m.x253 + 0.00596306*m.x254 + 0.00342669*m.x255
+ 0.00429343*m.x256 + 0.00561083*m.x257 - 0.0015187*m.x258 + 0.00862894*m.x259
+ 0.00331591*m.x260 + 0.00871316*m.x261 - 0.0002988*m.x262 + 0.0052497*m.x263
+ 0.0171593*m.x264 + 0.00474492*m.x265 + 0.00191161*m.x266 - 0.00583543*m.x267
+ 0.00138488*m.x268 + 6.76023E-5*m.x269 + 0.00752552*m.x270 + 0.00522755*m.x271
- 0.00169631*m.x272 - 0.000110801*m.x273 + 0.00214663*m.x274 - 0.00545762*m.x275
+ 0.0163644*m.x276 + 0.00374693*m.x277 - 0.000105586*m.x278 + 0.00122031*m.x279
+ 0.00275425*m.x280 + 0.0114023*m.x281 - 0.0056184*m.x282 + 0.000240556*m.x283
- 0.00195931*m.x284 + 0.00535235*m.x285 + 0.00491409*m.x286 + 0.00203007*m.x287
+ 0.00460018*m.x288 + 0.00403771*m.x289 - 0.00165847*m.x290 + 0.0032872*m.x291
+ 0.000244984*m.x292 + 0.00485521*m.x293 - 0.00106589*m.x294 + 0.0549514*m.x295
- 0.00146097*m.x296 + 0.000354106*m.x297 - 0.000860234*m.x298 + 0.00407885*m.x299
+ 0.00752741*m.x300 - 0.00356262*m.x301 - 0.000356019*m.x302 + 0.00248476*m.x303 == 0)
m.c299 = Constraint(expr= - m.x194 - 0.000732426*m.x204 + 0.00390306*m.x205 + 0.00447174*m.x206 + 0.0052055*m.x207
+ 0.00338877*m.x208 + 0.000810064*m.x209 + 0.00302037*m.x210 + 0.000559204*m.x211
- 0.0038537*m.x212 + 0.00745742*m.x213 + 0.00925901*m.x214 + 0.00261969*m.x215
+ 0.00556431*m.x216 + 0.00524342*m.x217 + 0.00823308*m.x218 + 0.00450063*m.x219
+ 0.00822193*m.x220 + 0.00578248*m.x221 - 0.00154701*m.x222 - 0.000897559*m.x223
+ 0.00536292*m.x224 - 0.00319077*m.x225 + 0.00264885*m.x226 + 0.00375527*m.x227
+ 0.00110999*m.x228 + 0.00667569*m.x229 - 0.00156275*m.x230 + 0.000572419*m.x231
+ 0.00232212*m.x232 + 0.00487642*m.x233 + 0.000707514*m.x234 - 0.000183456*m.x235
+ 0.00261151*m.x236 - 0.00068464*m.x237 + 0.00341113*m.x238 + 0.00769045*m.x239
+ 0.0082126*m.x240 + 0.00342953*m.x241 + 0.0027501*m.x242 + 0.00315729*m.x243
+ 0.00307669*m.x244 + 0.00304548*m.x245 + 0.00364867*m.x246 + 0.00275687*m.x247
+ 0.00178999*m.x248 + 0.00213016*m.x249 + 0.00521004*m.x250 - 0.000529075*m.x251
+ 0.000902586*m.x252 + 0.00527957*m.x253 + 0.000603395*m.x254 - 0.00362052*m.x255
+ 0.00214085*m.x256 + 0.00262766*m.x257 - 0.000662009*m.x258 + 0.000135119*m.x259
+ 0.00502936*m.x260 + 0.00786502*m.x261 - 0.00107607*m.x262 + 0.00231272*m.x263
- 0.00289371*m.x264 + 0.000287705*m.x265 + 0.00398234*m.x266 + 0.0021646*m.x267
+ 0.00217937*m.x268 - 0.000464781*m.x269 + 0.000133786*m.x270 + 0.00612756*m.x271
+ 0.00153401*m.x272 + 0.00541829*m.x273 + 0.00586755*m.x274 + 0.00496011*m.x275
+ 0.000961062*m.x276 + 0.000942883*m.x277 + 0.00482014*m.x278 + 0.00524552*m.x279
+ 0.0015505*m.x280 + 0.00705981*m.x281 - 0.00793664*m.x282 + 0.00454787*m.x283
- 0.000874528*m.x284 + 0.00245751*m.x285 + 0.00621639*m.x286 - 5.98431E-5*m.x287
+ 0.0005399*m.x288 + 0.00164628*m.x289 + 0.0056648*m.x290 + 0.00334433*m.x291
+ 0.000960586*m.x292 + 0.00393184*m.x293 + 0.000467335*m.x294 - 0.00146097*m.x295
+ 0.0402889*m.x296 + 0.00398843*m.x297 + 0.000265664*m.x298 + 0.00414142*m.x299
+ 0.000465545*m.x300 - 0.00356724*m.x301 + 0.00127797*m.x302 + 0.00234787*m.x303 == 0)
m.c300 = Constraint(expr= - m.x195 + 0.000574642*m.x204 - 0.00345893*m.x205 - 0.00894175*m.x206 + 0.00106842*m.x207
- 0.000458376*m.x208 - 0.00836969*m.x209 - 0.00583942*m.x210 + 0.00368139*m.x211
+ 0.0464725*m.x212 - 0.00228448*m.x213 - 0.00307712*m.x214 - 0.00299439*m.x215
- 0.00171402*m.x216 - 0.00676607*m.x217 - 0.00407677*m.x218 - 0.00308935*m.x219
- 0.0026527*m.x220 + 0.0134996*m.x221 + 0.000899911*m.x222 + 0.00605286*m.x223
- 0.00508668*m.x224 - 0.00467229*m.x225 + 0.000868196*m.x226 + 0.00235696*m.x227
- 0.00346431*m.x228 - 0.00651531*m.x229 - 0.0039415*m.x230 + 0.00151632*m.x231
- 0.00194288*m.x232 - 0.00289096*m.x233 - 0.00353193*m.x234 + 0.00313748*m.x235
- 0.00695241*m.x236 - 0.00580836*m.x237 - 0.00131877*m.x238 - 0.00143092*m.x239
- 0.00437163*m.x240 - 0.000843844*m.x241 + 0.00568815*m.x242 + 0.00297396*m.x243
+ 0.00364193*m.x244 - 0.000971214*m.x245 - 0.00345963*m.x246 - 0.00193635*m.x247
+ 0.017123*m.x248 - 0.00403433*m.x249 - 0.00282173*m.x250 + 0.000979263*m.x251
+ 0.00233291*m.x252 + 0.00036941*m.x253 - 0.00367719*m.x254 - 0.00643522*m.x255
- 0.00145961*m.x256 + 0.00179022*m.x257 - 0.00258788*m.x258 - 0.00196723*m.x259
+ 0.00976419*m.x260 + 0.000809943*m.x261 - 0.00762971*m.x262 - 0.00666127*m.x263
- 0.00430756*m.x264 - 0.00158663*m.x265 - 0.00142675*m.x266 - 0.00610058*m.x267
- 0.000402168*m.x268 + 0.00126493*m.x269 - 0.00111604*m.x270 - 0.000490773*m.x271
- 0.0051692*m.x272 - 0.00179873*m.x273 - 0.00378753*m.x274 - 0.00325598*m.x275
+ 0.00524417*m.x276 + 0.00282709*m.x277 + 0.00201782*m.x278 - 0.00317043*m.x279
+ 0.00365812*m.x280 - 0.000688029*m.x281 + 0.00208083*m.x282 + 0.00970541*m.x283
- 0.00561291*m.x284 + 0.00634908*m.x285 + 0.00557977*m.x286 + 0.00429026*m.x287
+ 0.00652496*m.x288 - 0.00336155*m.x289 - 0.00388715*m.x290 - 0.00233066*m.x291
- 0.00227507*m.x292 - 0.00207377*m.x293 - 0.000790828*m.x294 + 0.000354106*m.x295
+ 0.00398843*m.x296 + 0.271212*m.x297 - 0.00038029*m.x298 + 0.000400916*m.x299
- 0.00072593*m.x300 - 0.00426209*m.x301 - 0.000681229*m.x302 - 0.000137152*m.x303 == 0)
m.c301 = Constraint(expr= - m.x196 + 0.0043636*m.x204 + 0.00348614*m.x205 - 0.0106183*m.x206 + 0.00268821*m.x207
+ 0.00936944*m.x208 + 0.000538622*m.x209 + 0.00166923*m.x210 + 0.00134215*m.x211
+ 0.00125687*m.x212 - 0.000338838*m.x213 - 0.00248219*m.x214 + 0.0127287*m.x215
+ 0.00830996*m.x216 + 0.0151857*m.x217 + 0.00929486*m.x218 + 0.000400969*m.x219
+ 0.00739356*m.x220 + 9.34767E-5*m.x221 + 0.0024395*m.x222 - 0.000995666*m.x223
+ 0.00836202*m.x224 - 0.00299231*m.x225 + 0.00313515*m.x226 - 0.00404778*m.x227
+ 0.00415143*m.x228 - 0.00217122*m.x229 + 0.0184288*m.x230 + 0.000311369*m.x231
+ 0.000886071*m.x232 + 0.00354767*m.x233 - 0.00266393*m.x234 + 0.0108401*m.x235
- 0.00163906*m.x236 + 0.000271513*m.x237 + 0.00963574*m.x238 - 0.000148921*m.x239
+ 0.00034667*m.x240 + 0.00516692*m.x241 + 0.00312586*m.x242 + 0.00597381*m.x243
+ 0.00434876*m.x244 + 0.00232343*m.x245 + 0.000712721*m.x246 + 0.0035958*m.x247
+ 0.00424638*m.x248 + 0.00423746*m.x249 + 0.00291792*m.x250 + 0.00309003*m.x251
+ 0.00342174*m.x252 + 0.0020713*m.x253 + 0.00134408*m.x254 + 0.00632524*m.x255
+ 0.00499227*m.x256 + 0.00558577*m.x257 - 0.00124882*m.x258 + 0.00166645*m.x259
+ 0.00514689*m.x260 + 0.000294055*m.x261 - 0.00163559*m.x262 + 0.0119683*m.x263
+ 0.00677732*m.x264 + 0.00306085*m.x265 + 0.00441408*m.x266 - 0.006832*m.x267
+ 0.000850121*m.x268 + 0.00259808*m.x269 + 0.00508961*m.x270 - 0.00304139*m.x271
+ 0.004099*m.x272 + 0.00181925*m.x273 - 0.00130744*m.x274 + 0.00383461*m.x275
- 0.00131349*m.x276 + 0.000559935*m.x277 + 0.00319848*m.x278 + 0.00149389*m.x279
+ 0.00289131*m.x280 + 0.00418666*m.x281 - 0.00216442*m.x282 - 0.00292971*m.x283
+ 0.00316007*m.x284 + 0.00849798*m.x285 + 0.00777728*m.x286 + 0.00994608*m.x287
+ 0.00480221*m.x288 + 0.000136297*m.x289 - 0.00453289*m.x290 + 0.00346403*m.x291
+ 0.0029063*m.x292 + 0.00289386*m.x293 + 0.00499735*m.x294 - 0.000860234*m.x295
+ 0.000265664*m.x296 - 0.00038029*m.x297 + 0.205691*m.x298 - 0.0072076*m.x299
+ 0.0128346*m.x300 - 0.00289376*m.x301 + 0.00405259*m.x302 - 2.85501E-5*m.x303 == 0)
m.c302 = Constraint(expr= - m.x197 - 0.00725725*m.x204 + 0.0230969*m.x205 + 0.0196262*m.x206 - 0.00313171*m.x207
+ 0.00321093*m.x208 + 0.00916125*m.x209 + 0.00208712*m.x210 + 0.000562204*m.x211
+ 0.0104496*m.x212 + 0.00375325*m.x213 + 0.010692*m.x214 + 0.000449299*m.x215
+ 0.00411981*m.x216 + 0.0121187*m.x217 + 0.00454276*m.x218 + 0.0016857*m.x219
+ 0.00353478*m.x220 + 0.0123006*m.x221 + 0.00327313*m.x222 - 0.000170077*m.x223
+ 0.00215742*m.x224 + 0.0141819*m.x225 - 0.000643318*m.x226 - 8.08719E-5*m.x227
+ 0.00356873*m.x228 + 0.0161266*m.x229 + 0.00951648*m.x230 - 0.00581513*m.x231
+ 0.0271101*m.x232 + 0.00357909*m.x233 + 0.00983835*m.x234 + 0.00439792*m.x235
+ 0.000292171*m.x236 + 0.0112659*m.x237 - 0.00402802*m.x238 + 0.0048758*m.x239
+ 0.00832302*m.x240 + 0.000320143*m.x241 + 0.00643759*m.x242 + 0.00713407*m.x243
+ 0.0116213*m.x244 + 0.0058115*m.x245 + 0.00228836*m.x246 - 0.000537039*m.x247
+ 0.0127695*m.x248 + 0.00337871*m.x249 - 0.000120553*m.x250 + 0.00415618*m.x251
+ 0.00618718*m.x252 + 0.00787258*m.x253 + 0.00265743*m.x254 + 0.0195511*m.x255
- 0.00212278*m.x256 - 0.000513059*m.x257 + 0.00446219*m.x258 + 0.0017984*m.x259
+ 0.00345782*m.x260 + 0.0093328*m.x261 - 0.00594877*m.x262 - 0.00285395*m.x263
+ 0.00573494*m.x264 + 0.00331961*m.x265 + 0.00695092*m.x266 - 0.00455273*m.x267
+ 0.0110636*m.x268 + 0.00163564*m.x269 - 0.00259683*m.x270 + 0.00709659*m.x271
+ 0.00833415*m.x272 + 0.00435334*m.x273 + 0.00509215*m.x274 + 0.0116874*m.x275
- 0.00280069*m.x276 + 0.00395298*m.x277 + 0.00557589*m.x278 + 0.0117116*m.x279
+ 0.00281716*m.x280 + 0.00132274*m.x281 - 0.0058322*m.x282 + 0.0013331*m.x283
+ 0.00326358*m.x284 + 0.00413392*m.x285 + 0.0170867*m.x286 - 0.00428917*m.x287
+ 0.00101452*m.x288 + 0.000407005*m.x289 - 0.00269182*m.x290 + 0.0134367*m.x291
+ 0.00678876*m.x292 + 0.00146898*m.x293 + 0.00331171*m.x294 + 0.00407885*m.x295
+ 0.00414142*m.x296 + 0.000400916*m.x297 - 0.0072076*m.x298 + 0.131656*m.x299
+ 0.00805979*m.x300 - 0.00172414*m.x301 + 0.00419392*m.x302 + 0.00171227*m.x303 == 0)
m.c303 = Constraint(expr= - m.x198 + 0.00589969*m.x204 + 0.00744792*m.x205 + 0.00569151*m.x206 + 0.0047581*m.x207
+ 0.00494576*m.x208 + 0.00409619*m.x209 + 0.00468842*m.x210 + 0.00467534*m.x211
+ 0.0289754*m.x212 + 0.00589763*m.x213 - 0.00209988*m.x214 - 0.00213457*m.x215
+ 0.00605045*m.x216 + 0.00858*m.x217 - 0.00165032*m.x218 - 0.000503363*m.x219
+ 0.00736597*m.x220 + 0.000507185*m.x221 + 0.00413577*m.x222 + 0.000927962*m.x223
+ 0.00273144*m.x224 + 0.0104414*m.x225 + 0.00210871*m.x226 + 0.00955537*m.x227
+ 0.00160276*m.x228 + 0.00695292*m.x229 + 5.68864E-5*m.x230 + 0.00803792*m.x231
+ 0.00505307*m.x232 + 0.00585634*m.x233 - 0.0040378*m.x234 + 0.000633255*m.x235
+ 0.00495442*m.x236 + 0.00208455*m.x237 + 0.0104253*m.x238 + 0.00286852*m.x239
+ 0.0112749*m.x240 + 0.00463152*m.x241 + 0.0076711*m.x242 + 0.00444173*m.x243
+ 0.0135054*m.x244 + 0.000485725*m.x245 - 0.00517211*m.x246 - 0.000271199*m.x247
+ 0.00599775*m.x248 + 0.00204417*m.x249 + 0.000967824*m.x250 + 0.00182144*m.x251
+ 0.00291333*m.x252 + 0.00426053*m.x253 + 0.00432502*m.x254 - 0.00071887*m.x255
+ 0.00204967*m.x256 + 0.00353794*m.x257 + 0.000269906*m.x258 + 0.00455272*m.x259
+ 0.00507329*m.x260 + 0.000154729*m.x261 + 0.000798834*m.x262 + 0.00170996*m.x263
+ 0.00758548*m.x264 + 0.00420889*m.x265 - 0.00519564*m.x266 + 0.00534474*m.x267
+ 0.00498262*m.x268 + 0.00270092*m.x269 + 0.00158141*m.x270 + 0.00740449*m.x271
- 0.000558778*m.x272 + 0.00935992*m.x273 + 0.000940496*m.x274 + 0.0101529*m.x275
+ 0.00116913*m.x276 + 0.00461055*m.x277 + 0.00775337*m.x278 + 0.0269848*m.x279
+ 0.00374955*m.x280 + 0.00955838*m.x281 + 0.00684748*m.x282 + 0.00376435*m.x283
+ 0.0032359*m.x284 + 0.00433132*m.x285 + 0.00237553*m.x286 + 0.00492553*m.x287
+ 0.00380777*m.x288 + 0.00508056*m.x289 + 0.000442839*m.x290 + 0.00640805*m.x291
+ 0.0001247*m.x292 - 0.000633614*m.x293 + 0.00540673*m.x294 + 0.00752741*m.x295
+ 0.000465545*m.x296 - 0.00072593*m.x297 + 0.0128346*m.x298 + 0.00805979*m.x299
+ 0.0832903*m.x300 - 0.00109601*m.x301 + 0.00197016*m.x302 + 0.00475952*m.x303 == 0)
m.c304 = Constraint(expr= - m.x199 + 0.00253513*m.x204 + 0.0101415*m.x205 + 0.000408826*m.x206 - 0.00749006*m.x207
- 0.00489219*m.x208 + 0.0632661*m.x209 + 0.00124219*m.x210 - 0.00175434*m.x211
- 0.000502067*m.x212 + 0.00111933*m.x213 - 0.00513244*m.x214 - 0.0016146*m.x215
+ 0.00185019*m.x216 + 0.00987312*m.x217 - 0.00211125*m.x218 + 0.000255561*m.x219
- 0.00264635*m.x220 - 0.00357673*m.x221 - 0.00665285*m.x222 + 0.00910382*m.x223
- 0.00693562*m.x224 + 0.00771774*m.x225 + 0.0011722*m.x226 - 0.00665009*m.x227
- 0.00400958*m.x228 + 0.00190191*m.x229 + 0.0119542*m.x230 + 0.00503323*m.x231
- 0.00135319*m.x232 - 0.000870044*m.x233 + 0.00154164*m.x234 - 0.00249511*m.x235
+ 0.00511283*m.x236 + 0.0126192*m.x237 - 0.00123284*m.x238 - 0.00298357*m.x239
- 0.00281611*m.x240 - 0.0012355*m.x241 - 0.00311771*m.x242 - 0.00372007*m.x243
+ 0.00150838*m.x244 - 0.000130592*m.x245 + 0.00524662*m.x246 - 0.00288422*m.x247
+ 0.0107649*m.x248 + 0.00449024*m.x249 + 0.000698762*m.x250 + 0.00336642*m.x251
- 0.00120359*m.x252 - 0.00268282*m.x253 + 0.00252096*m.x254 - 0.00217301*m.x255
+ 0.00120533*m.x256 + 0.00615137*m.x257 - 6.39913E-6*m.x258 - 0.0033299*m.x259
- 0.00213912*m.x260 + 1.07515E-5*m.x261 + 0.00532067*m.x262 + 0.00942007*m.x263
- 0.000228625*m.x264 - 0.00957465*m.x265 - 0.00145915*m.x266 - 0.0104513*m.x267
+ 0.00115585*m.x268 + 0.00285028*m.x269 - 0.00346463*m.x270 - 0.000919619*m.x271
+ 0.00267992*m.x272 - 0.00673796*m.x273 + 5.42431E-5*m.x274 - 0.00447465*m.x275
+ 0.00450883*m.x276 + 0.00200426*m.x277 - 0.00196797*m.x278 - 0.00783374*m.x279
+ 0.0050992*m.x280 - 0.00343351*m.x281 + 0.00539178*m.x282 - 0.00118927*m.x283
+ 0.00478097*m.x284 + 0.00189491*m.x285 + 0.00254531*m.x286 - 0.00183033*m.x287
- 0.00364829*m.x288 + 0.0027572*m.x289 - 0.00132366*m.x290 - 0.00798533*m.x291
- 0.00371543*m.x292 - 0.000187625*m.x293 + 0.00460485*m.x294 - 0.00356262*m.x295
- 0.00356724*m.x296 - 0.00426209*m.x297 - 0.00289376*m.x298 - 0.00172414*m.x299
- 0.00109601*m.x300 + 0.150506*m.x301 + 0.0042098*m.x302 + 0.00571185*m.x303 == 0)
m.c305 = Constraint(expr= - m.x200 + 3.03939E-5*m.x204 + 0.00190622*m.x205 + 0.0107044*m.x206 + 0.00065076*m.x207
+ 0.00406797*m.x208 + 0.00174019*m.x209 + 0.00190019*m.x210 + 0.000310939*m.x211
+ 0.00848806*m.x212 + 0.000509737*m.x213 - 0.00106151*m.x214 - 0.00369472*m.x215
+ 0.000924558*m.x216 + 0.000447536*m.x217 + 0.0019068*m.x218 + 0.00297631*m.x219
+ 0.00202109*m.x220 + 0.000218257*m.x221 + 0.000253484*m.x222 + 0.00213483*m.x223
+ 0.00172953*m.x224 + 0.00187759*m.x225 + 0.00301842*m.x226 + 0.00353927*m.x227
+ 0.000129628*m.x228 + 0.00346113*m.x229 + 0.00888358*m.x230 + 0.00261585*m.x231
+ 0.000960311*m.x232 + 0.00817771*m.x233 + 0.00321227*m.x234 + 0.00187615*m.x235
+ 0.00311265*m.x236 + 0.000840037*m.x237 + 0.00267415*m.x238 + 0.000697231*m.x239
+ 0.00195298*m.x240 + 0.00336904*m.x241 + 0.000316259*m.x242 + 0.00227586*m.x243
+ 0.00321772*m.x244 + 0.0045291*m.x245 + 0.00987378*m.x246 + 0.00223441*m.x247
+ 0.00273511*m.x248 + 0.00140987*m.x249 + 0.00432741*m.x250 + 0.000262547*m.x251
+ 0.00135234*m.x252 + 0.0035967*m.x253 + 0.00261792*m.x254 + 0.00440766*m.x255
- 0.00154274*m.x256 + 0.000877291*m.x257 + 0.00128816*m.x258 + 0.00426249*m.x259
- 0.00213196*m.x260 + 0.00396114*m.x261 + 0.001777*m.x262 + 0.00238323*m.x263
+ 0.00247448*m.x264 + 0.000329151*m.x265 - 0.00269056*m.x266 - 0.00240116*m.x267
+ 0.00570291*m.x268 + 0.00895321*m.x269 + 0.000964003*m.x270 + 0.00139892*m.x271
+ 0.00290008*m.x272 + 0.0024774*m.x273 + 0.00377541*m.x274 + 0.00751902*m.x275
+ 0.000120926*m.x276 + 0.00214771*m.x277 + 0.000849566*m.x278 + 0.00544106*m.x279
+ 0.0100888*m.x280 + 0.00462039*m.x281 + 0.00822951*m.x282 + 0.0021784*m.x283
+ 0.00997826*m.x284 + 0.00149054*m.x285 + 0.000729482*m.x286 + 0.00598074*m.x287
+ 0.003082*m.x288 + 0.00463908*m.x289 - 0.000573397*m.x290 + 0.00189799*m.x291
+ 0.00766411*m.x292 + 0.00119486*m.x293 + 0.000445662*m.x294 - 0.000356019*m.x295
+ 0.00127797*m.x296 - 0.000681229*m.x297 + 0.00405259*m.x298 + 0.00419392*m.x299
+ 0.00197016*m.x300 + 0.0042098*m.x301 + 0.0223058*m.x302 - 0.00243994*m.x303 == 0)
m.c306 = Constraint(expr= - m.x201 + 0.0013209*m.x204 + 0.00972401*m.x205 + 0.00414926*m.x206 + 0.0033893*m.x207
+ 0.00689176*m.x208 + 0.0149843*m.x209 + 0.00317539*m.x210 - 0.000534117*m.x211
- 0.00199306*m.x212 + 0.00161055*m.x213 + 0.00607889*m.x214 + 0.00287968*m.x215
+ 0.00169926*m.x216 + 0.00177245*m.x217 + 0.00125766*m.x218 + 0.000851058*m.x219
+ 3.15874E-5*m.x220 + 0.00591064*m.x221 - 0.00179775*m.x222 + 0.00406122*m.x223
- 0.00148411*m.x224 + 0.00633113*m.x225 + 0.00345188*m.x226 + 0.00543525*m.x227
+ 0.00686574*m.x228 + 0.00542579*m.x229 - 0.000364621*m.x230 + 0.0020532*m.x231
+ 0.00806487*m.x232 + 0.00321544*m.x233 + 0.00627327*m.x234 + 0.00489037*m.x235
+ 0.00964866*m.x236 + 0.00862854*m.x237 + 0.00590155*m.x238 + 0.00549383*m.x239
- 0.000375713*m.x240 + 0.00227586*m.x241 - 0.000648959*m.x242 + 0.00205933*m.x243
+ 0.00468832*m.x244 + 0.00868416*m.x245 - 0.00153163*m.x246 + 0.00280782*m.x247
+ 0.00174594*m.x248 + 0.00259129*m.x249 + 0.00166067*m.x250 - 0.000847169*m.x251
- 0.000351985*m.x252 + 0.0019922*m.x253 + 0.00239977*m.x254 + 0.00538072*m.x255
+ 0.000846548*m.x256 + 0.000931697*m.x257 + 0.00584908*m.x258 + 0.00227416*m.x259
+ 0.00211323*m.x260 - 0.00289961*m.x261 - 0.00273965*m.x262 + 0.00381314*m.x263
+ 0.000632226*m.x264 + 0.000204814*m.x265 + 0.0029091*m.x266 + 0.00593878*m.x267
+ 0.00301803*m.x268 + 0.00219665*m.x269 - 0.00191532*m.x270 - 0.00120848*m.x271
+ 0.00401961*m.x272 + 0.00491578*m.x273 + 0.00950302*m.x274 + 0.00119155*m.x275
+ 0.0018262*m.x276 - 0.00562506*m.x277 + 0.00509184*m.x278 + 0.00418992*m.x279
+ 0.00362527*m.x280 + 0.00284859*m.x281 + 0.000459309*m.x282 - 0.00418691*m.x283
+ 0.00455818*m.x284 + 0.0067696*m.x285 + 0.000959806*m.x286 + 0.00348814*m.x287
- 0.000738294*m.x288 + 0.00143901*m.x289 - 0.00340939*m.x290 + 0.00886188*m.x291
+ 0.000597387*m.x292 + 0.00260126*m.x293 - 0.00218896*m.x294 + 0.00248476*m.x295
+ 0.00234787*m.x296 - 0.000137152*m.x297 - 2.85501E-5*m.x298 + 0.00171227*m.x299
+ 0.00475952*m.x300 + 0.00571185*m.x301 - 0.00243994*m.x302 + 0.0528559*m.x303 == 0)
m.c307 = Constraint(expr= - m.x202 - m.x203 + 0.0538941*m.x204 + 0.0734706*m.x205 + 0.171372*m.x206 + 0.0665048*m.x207
+ 0.0566217*m.x208 + 0.162419*m.x209 + 0.0368724*m.x210 + 0.0475631*m.x211 + 0.135883*m.x212
+ 0.106437*m.x213 + 0.0256378*m.x214 + 0.0541634*m.x215 + 0.0773545*m.x216 + 0.12584*m.x217
+ 0.0623269*m.x218 + 0.0292815*m.x219 + 0.0415958*m.x220 + 0.0801839*m.x221 + 0.176756*m.x222
+ 0.136693*m.x223 + 0.0279462*m.x224 + 0.106356*m.x225 + 0.00643121*m.x226 + 0.042286*m.x227
+ 0.0524719*m.x228 + 0.0798624*m.x229 + 0.00388665*m.x230 + 0.0205903*m.x231 + 0.128252*m.x232
+ 0.0598638*m.x233 + 0.0948967*m.x234 + 0.0460416*m.x235 + 0.0637387*m.x236 + 0.105905*m.x237
+ 0.0791172*m.x238 + 0.063726*m.x239 + 0.122605*m.x240 + 0.039237*m.x241 + 0.103167*m.x242
+ 0.00839736*m.x243 + 0.05064*m.x244 + 0.093967*m.x245 + 0.0495039*m.x246 + 0.039884*m.x247
+ 0.399937*m.x248 + 0.0402434*m.x249 + 0.00851723*m.x250 + 0.282509*m.x251 + 0.0521298*m.x252
+ 0.0384659*m.x253 + 0.0268375*m.x254 + 0.114978*m.x255 + 0.0658077*m.x256 + 0.0856842*m.x257
+ 0.0423549*m.x258 + 0.135346*m.x259 - 0.00660692*m.x260 + 0.105791*m.x261 + 0.165275*m.x262
+ 0.0962619*m.x263 + 0.0966325*m.x264 + 0.0339335*m.x265 + 0.12267*m.x266 + 0.281523*m.x267
+ 0.0499404*m.x268 + 0.00535998*m.x269 + 0.0413132*m.x270 + 0.0896855*m.x271
+ 0.0283013*m.x272 + 0.0723241*m.x273 + 0.0414486*m.x274 + 0.142596*m.x275 + 0.0601345*m.x276
+ 0.0135436*m.x277 + 0.0965978*m.x278 + 0.136929*m.x279 + 0.0110311*m.x280 + 0.102568*m.x281
+ 0.0695206*m.x282 + 0.167012*m.x283 + 0.0373343*m.x284 + 0.037078*m.x285 + 0.0946916*m.x286
+ 0.0181341*m.x287 + 0.0170914*m.x288 + 0.032172*m.x289 + 0.0900157*m.x290 + 0.0887704*m.x291
+ 0.021463*m.x292 + 0.0142077*m.x293 + 0.00787829*m.x294 + 0.0669671*m.x295 + 0.0176756*m.x296
+ 0.131904*m.x297 + 0.142251*m.x298 + 0.190895*m.x299 + 0.0913653*m.x300 + 0.119809*m.x301
- 0.00773506*m.x302 + 0.0479071*m.x303 == 0)
| 96.107308
| 120
| 0.537507
|
b9129792f8b6e792ba2e421edb63a9165f50120a
| 405
|
py
|
Python
|
env/Lib/site-packages/plotly/validators/ohlc/_customdata.py
|
andresgreen-byte/Laboratorio-1--Inversion-de-Capital
|
8a4707301d19c3826c31026c4077930bcd6a8182
|
[
"MIT"
] | 11,750
|
2015-10-12T07:03:39.000Z
|
2022-03-31T20:43:15.000Z
|
venv/Lib/site-packages/plotly/validators/ohlc/_customdata.py
|
wakisalvador/constructed-misdirection
|
74779e9ec640a11bc08d5d1967c85ac4fa44ea5e
|
[
"Unlicense"
] | 2,951
|
2015-10-12T00:41:25.000Z
|
2022-03-31T22:19:26.000Z
|
venv/Lib/site-packages/plotly/validators/ohlc/_customdata.py
|
wakisalvador/constructed-misdirection
|
74779e9ec640a11bc08d5d1967c85ac4fa44ea5e
|
[
"Unlicense"
] | 2,623
|
2015-10-15T14:40:27.000Z
|
2022-03-28T16:05:50.000Z
|
import _plotly_utils.basevalidators
class CustomdataValidator(_plotly_utils.basevalidators.DataArrayValidator):
def __init__(self, plotly_name="customdata", parent_name="ohlc", **kwargs):
super(CustomdataValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
**kwargs
)
| 33.75
| 79
| 0.681481
|
3539c821615db7989a55f7d4a55ad58e25a6612d
| 6,199
|
py
|
Python
|
models/DeformableConvNets/faster_rcnn/config/config.py
|
RamsteinWR/PneumoniaRSNA1
|
08bdba51292307a78ef711c6be4a63faea240ddf
|
[
"MIT"
] | null | null | null |
models/DeformableConvNets/faster_rcnn/config/config.py
|
RamsteinWR/PneumoniaRSNA1
|
08bdba51292307a78ef711c6be4a63faea240ddf
|
[
"MIT"
] | null | null | null |
models/DeformableConvNets/faster_rcnn/config/config.py
|
RamsteinWR/PneumoniaRSNA1
|
08bdba51292307a78ef711c6be4a63faea240ddf
|
[
"MIT"
] | null | null | null |
# --------------------------------------------------------
# Deformable Convolutional Networks
# Copyright (c) 2017 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Modified by Yuwen Xiong, Bin Xiao
# --------------------------------------------------------
# Based on:
# MX-RCNN
# Copyright (c) 2016 by Contributors
# Licence under The Apache 2.0 License
# https://github.com/ijkguo/mx-rcnn/
# --------------------------------------------------------
import numpy as np
import yaml
from easydict import EasyDict as edict
config = edict()
config.MXNET_VERSION = ''
config.output_path = ''
config.symbol = ''
config.gpus = ''
config.CLASS_AGNOSTIC = True
config.SCALES = [(600, 1000)] # first is scale (the shorter side); second is max size
# default training
config.default = edict()
config.default.frequent = 20
config.default.kvstore = 'device'
# network related params
config.network = edict()
config.network.pretrained = ''
config.network.pretrained_epoch = 0
config.network.PIXEL_MEANS = np.array([0, 0, 0])
config.network.IMAGE_STRIDE = 0
config.network.RPN_FEAT_STRIDE = 16
config.network.RCNN_FEAT_STRIDE = 16
config.network.FIXED_PARAMS = ['gamma', 'beta']
config.network.FIXED_PARAMS_SHARED = ['gamma', 'beta']
config.network.ANCHOR_SCALES = (8, 16, 32)
config.network.ANCHOR_RATIOS = (0.5, 1, 2)
config.network.NUM_ANCHORS = len(config.network.ANCHOR_SCALES) * len(config.network.ANCHOR_RATIOS)
# dataset related params
config.dataset = edict()
config.dataset.dataset = 'PascalVOC'
config.dataset.image_set = '2007_trainval'
config.dataset.test_image_set = '2007_test'
config.dataset.root_path = './data'
config.dataset.dataset_path = './data/VOCdevkit'
config.dataset.NUM_CLASSES = 21
config.TRAIN = edict()
config.TRAIN.lr = 0
config.TRAIN.lr_step = ''
config.TRAIN.lr_factor = 0.1
config.TRAIN.warmup = False
config.TRAIN.warmup_lr = 0
config.TRAIN.warmup_step = 0
config.TRAIN.momentum = 0.9
config.TRAIN.wd = 0.0005
config.TRAIN.begin_epoch = 0
config.TRAIN.end_epoch = 0
config.TRAIN.model_prefix = ''
config.TRAIN.ALTERNATE = edict()
config.TRAIN.ALTERNATE.RPN_BATCH_IMAGES = 0
config.TRAIN.ALTERNATE.RCNN_BATCH_IMAGES = 0
config.TRAIN.ALTERNATE.rpn1_lr = 0
config.TRAIN.ALTERNATE.rpn1_lr_step = '' # recommend '2'
config.TRAIN.ALTERNATE.rpn1_epoch = 0 # recommend 3
config.TRAIN.ALTERNATE.rfcn1_lr = 0
config.TRAIN.ALTERNATE.rfcn1_lr_step = '' # recommend '5'
config.TRAIN.ALTERNATE.rfcn1_epoch = 0 # recommend 8
config.TRAIN.ALTERNATE.rpn2_lr = 0
config.TRAIN.ALTERNATE.rpn2_lr_step = '' # recommend '2'
config.TRAIN.ALTERNATE.rpn2_epoch = 0 # recommend 3
config.TRAIN.ALTERNATE.rfcn2_lr = 0
config.TRAIN.ALTERNATE.rfcn2_lr_step = '' # recommend '5'
config.TRAIN.ALTERNATE.rfcn2_epoch = 0 # recommend 8
# optional
config.TRAIN.ALTERNATE.rpn3_lr = 0
config.TRAIN.ALTERNATE.rpn3_lr_step = '' # recommend '2'
config.TRAIN.ALTERNATE.rpn3_epoch = 0 # recommend 3
# whether resume training
config.TRAIN.RESUME = False
# whether flip image
config.TRAIN.FLIP = True
# whether shuffle image
config.TRAIN.SHUFFLE = True
# whether use OHEM
config.TRAIN.ENABLE_OHEM = False
# size of images for each device, 2 for rcnn, 1 for rpn and e2e
config.TRAIN.BATCH_IMAGES = 2
# e2e changes behavior of anchor loader and metric
config.TRAIN.END2END = False
# group images with similar aspect ratio
config.TRAIN.ASPECT_GROUPING = True
# R-CNN
# rcnn rois batch size
config.TRAIN.BATCH_ROIS = 128
config.TRAIN.BATCH_ROIS_OHEM = 128
# rcnn rois sampling params
config.TRAIN.FG_FRACTION = 0.25
config.TRAIN.FG_THRESH = 0.5
config.TRAIN.BG_THRESH_HI = 0.5
config.TRAIN.BG_THRESH_LO = 0.0
# rcnn bounding box regression params
config.TRAIN.BBOX_REGRESSION_THRESH = 0.5
config.TRAIN.BBOX_WEIGHTS = np.array([1.0, 1.0, 1.0, 1.0])
# RPN anchor loader
# rpn anchors batch size
config.TRAIN.RPN_BATCH_SIZE = 256
# rpn anchors sampling params
config.TRAIN.RPN_FG_FRACTION = 0.5
config.TRAIN.RPN_POSITIVE_OVERLAP = 0.7
config.TRAIN.RPN_NEGATIVE_OVERLAP = 0.3
config.TRAIN.RPN_CLOBBER_POSITIVES = False
# rpn bounding box regression params
config.TRAIN.RPN_BBOX_WEIGHTS = (1.0, 1.0, 1.0, 1.0)
config.TRAIN.RPN_POSITIVE_WEIGHT = -1.0
# used for end2end training
# RPN proposal
config.TRAIN.CXX_PROPOSAL = True
config.TRAIN.RPN_NMS_THRESH = 0.7
config.TRAIN.RPN_PRE_NMS_TOP_N = 12000
config.TRAIN.RPN_POST_NMS_TOP_N = 2000
config.TRAIN.RPN_MIN_SIZE = config.network.RPN_FEAT_STRIDE
# approximate bounding box regression
config.TRAIN.BBOX_NORMALIZATION_PRECOMPUTED = False
config.TRAIN.BBOX_MEANS = (0.0, 0.0, 0.0, 0.0)
config.TRAIN.BBOX_STDS = (0.1, 0.1, 0.2, 0.2)
config.TEST = edict()
# R-CNN testing
# use rpn to generate proposal
config.TEST.HAS_RPN = False
# size of images for each device
config.TEST.BATCH_IMAGES = 1
# RPN proposal
config.TEST.CXX_PROPOSAL = True
config.TEST.RPN_NMS_THRESH = 0.7
config.TEST.RPN_PRE_NMS_TOP_N = 6000
config.TEST.RPN_POST_NMS_TOP_N = 300
config.TEST.RPN_MIN_SIZE = config.network.RPN_FEAT_STRIDE
# RPN generate proposal
config.TEST.PROPOSAL_NMS_THRESH = 0.7
config.TEST.PROPOSAL_PRE_NMS_TOP_N = 20000
config.TEST.PROPOSAL_POST_NMS_TOP_N = 2000
config.TEST.PROPOSAL_MIN_SIZE = config.network.RPN_FEAT_STRIDE
# RCNN nms
config.TEST.NMS = 0.3
config.TEST.max_per_image = 300
# Test Model Epoch
config.TEST.test_epoch = 0
def update_config(config_file):
exp_config = None
with open(config_file) as f:
exp_config = edict(yaml.load(f))
for k, v in exp_config.items():
if k in config:
if isinstance(v, dict):
if k == 'TRAIN':
if 'BBOX_WEIGHTS' in v:
v['BBOX_WEIGHTS'] = np.array(v['BBOX_WEIGHTS'])
elif k == 'network':
if 'PIXEL_MEANS' in v:
v['PIXEL_MEANS'] = np.array(v['PIXEL_MEANS'])
for vk, vv in v.items():
config[k][vk] = vv
else:
if k == 'SCALES':
config[k][0] = (tuple(v))
else:
config[k] = v
else:
raise ValueError("key must exist in config.py")
| 32.119171
| 98
| 0.695273
|
d22220a8ca808e765159f350ab44dceaabe632d4
| 352
|
py
|
Python
|
reviewboard/scmtools/evolutions/repository_hosting_accounts.py
|
pombredanne/reviewboard
|
15f1d7236ec7a5cb4778ebfeb8b45d13a46ac71d
|
[
"MIT"
] | null | null | null |
reviewboard/scmtools/evolutions/repository_hosting_accounts.py
|
pombredanne/reviewboard
|
15f1d7236ec7a5cb4778ebfeb8b45d13a46ac71d
|
[
"MIT"
] | null | null | null |
reviewboard/scmtools/evolutions/repository_hosting_accounts.py
|
pombredanne/reviewboard
|
15f1d7236ec7a5cb4778ebfeb8b45d13a46ac71d
|
[
"MIT"
] | null | null | null |
from django_evolution.mutations import AddField
from django.db import models
from djblets.db.fields import JSONField
MUTATIONS = [
AddField('Repository', 'extra_data', JSONField, null=True),
AddField('Repository', 'hosting_account',
models.ForeignKey, null=True,
related_model='hostingsvcs.HostingServiceAccount')
]
| 29.333333
| 63
| 0.730114
|
e8b77eb6f3d90662212133d3e1b8f2a2bf5a4503
| 3,500
|
py
|
Python
|
freefeeds/migrations/0001_initial.py
|
ilvar/mokumdon
|
8f63a68708e33c6fe3579471716e3f31ec58fec4
|
[
"MIT"
] | null | null | null |
freefeeds/migrations/0001_initial.py
|
ilvar/mokumdon
|
8f63a68708e33c6fe3579471716e3f31ec58fec4
|
[
"MIT"
] | null | null | null |
freefeeds/migrations/0001_initial.py
|
ilvar/mokumdon
|
8f63a68708e33c6fe3579471716e3f31ec58fec4
|
[
"MIT"
] | null | null | null |
# Generated by Django 3.0 on 2019-12-14 20:57
from django.db import migrations, models
import django.db.models.deletion
import freefeeds.models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="User",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("feed_id", models.CharField(db_index=True, max_length=100)),
("username", models.CharField(max_length=100)),
("screen_name", models.CharField(max_length=100)),
("avatar_url", models.URLField()),
("created_at", models.DateTimeField()),
("updated_at", models.DateTimeField()),
],
bases=(models.Model, freefeeds.models.FfToMdConvertorMixin),
),
migrations.CreateModel(
name="Post",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("feed_id", models.CharField(db_index=True, max_length=100)),
("body", models.TextField()),
("comment_likes", models.IntegerField()),
("comments_disabled", models.BooleanField()),
("created_at", models.DateTimeField()),
("updated_at", models.DateTimeField()),
(
"parent",
models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="freefeeds.Post",
),
),
(
"user",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE, to="freefeeds.User"
),
),
],
bases=(models.Model, freefeeds.models.FfToMdConvertorMixin),
),
migrations.CreateModel(
name="Attachment",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("feed_id", models.CharField(db_index=True, max_length=100)),
("media_type", models.CharField(max_length=100)),
("url", models.CharField(max_length=256)),
("thumbnail_url", models.CharField(max_length=256)),
("width", models.IntegerField(null=True)),
("height", models.IntegerField(null=True)),
(
"post",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE, to="freefeeds.Post"
),
),
],
bases=(models.Model, freefeeds.models.FfToMdConvertorMixin),
),
]
| 35.353535
| 88
| 0.433429
|
fe285403bacb511cb2bef6599fdcc9e7bae58833
| 29,379
|
py
|
Python
|
sphinx/builders/_epub_base.py
|
zhsj/sphinx
|
169297d0b76bf0b503033dadeb14f9a2b735e422
|
[
"BSD-2-Clause"
] | 1
|
2021-06-17T13:38:42.000Z
|
2021-06-17T13:38:42.000Z
|
sphinx/builders/_epub_base.py
|
zhsj/sphinx
|
169297d0b76bf0b503033dadeb14f9a2b735e422
|
[
"BSD-2-Clause"
] | null | null | null |
sphinx/builders/_epub_base.py
|
zhsj/sphinx
|
169297d0b76bf0b503033dadeb14f9a2b735e422
|
[
"BSD-2-Clause"
] | null | null | null |
# -*- coding: utf-8 -*-
"""
sphinx.builders._epub_base
~~~~~~~~~~~~~~~~~~~~~~~~~~
Base class of epub2/epub3 builders.
:copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import os
import re
from collections import namedtuple
from os import path
from zipfile import ZIP_DEFLATED, ZIP_STORED, ZipFile
from docutils import nodes
from docutils.utils import smartquotes
from sphinx import addnodes
from sphinx.builders.html import BuildInfo, StandaloneHTMLBuilder
from sphinx.locale import __
from sphinx.util import logging
from sphinx.util import status_iterator
from sphinx.util.fileutil import copy_asset_file
from sphinx.util.i18n import format_date
from sphinx.util.osutil import ensuredir, copyfile
try:
from PIL import Image
except ImportError:
try:
import Image
except ImportError:
Image = None
if False:
# For type annotation
from typing import Any, Dict, List, Tuple # NOQA
from sphinx.application import Sphinx # NOQA
logger = logging.getLogger(__name__)
# (Fragment) templates from which the metainfo files content.opf and
# toc.ncx are created.
# This template section also defines strings that are embedded in the html
# output but that may be customized by (re-)setting module attributes,
# e.g. from conf.py.
COVERPAGE_NAME = u'epub-cover.xhtml'
TOCTREE_TEMPLATE = u'toctree-l%d'
LINK_TARGET_TEMPLATE = u' [%(uri)s]'
FOOTNOTE_LABEL_TEMPLATE = u'#%d'
FOOTNOTES_RUBRIC_NAME = u'Footnotes'
CSS_LINK_TARGET_CLASS = u'link-target'
# XXX These strings should be localized according to epub_language
GUIDE_TITLES = {
'toc': u'Table of Contents',
'cover': u'Cover'
}
MEDIA_TYPES = {
'.xhtml': 'application/xhtml+xml',
'.css': 'text/css',
'.png': 'image/png',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.otf': 'application/x-font-otf',
'.ttf': 'application/x-font-ttf',
'.woff': 'application/font-woff',
} # type: Dict[unicode, unicode]
VECTOR_GRAPHICS_EXTENSIONS = ('.svg',)
# Regular expression to match colons only in local fragment identifiers.
# If the URI contains a colon before the #,
# it is an external link that should not change.
REFURI_RE = re.compile("([^#:]*#)(.*)")
ManifestItem = namedtuple('ManifestItem', ['href', 'id', 'media_type'])
Spine = namedtuple('Spine', ['idref', 'linear'])
Guide = namedtuple('Guide', ['type', 'title', 'uri'])
NavPoint = namedtuple('NavPoint', ['navpoint', 'playorder', 'text', 'refuri', 'children'])
def sphinx_smarty_pants(t, language='en'):
# type: (unicode, str) -> unicode
t = t.replace('"', '"')
t = smartquotes.educateDashesOldSchool(t)
t = smartquotes.educateQuotes(t, language)
t = t.replace('"', '"')
return t
ssp = sphinx_smarty_pants
# The epub publisher
class EpubBuilder(StandaloneHTMLBuilder):
"""
Builder that outputs epub files.
It creates the metainfo files container.opf, toc.ncx, mimetype, and
META-INF/container.xml. Afterwards, all necessary files are zipped to an
epub file.
"""
# don't copy the reST source
copysource = False
supported_image_types = ['image/svg+xml', 'image/png', 'image/gif',
'image/jpeg']
supported_remote_images = False
# don't add links
add_permalinks = False
# don't use # as current path. ePub check reject it.
allow_sharp_as_current_path = False
# don't add sidebar etc.
embedded = True
# disable download role
download_support = False
# dont' create links to original images from images
html_scaled_image_link = False
# don't generate search index or include search page
search = False
# use html5 translator by default
default_html5_translator = True
coverpage_name = COVERPAGE_NAME
toctree_template = TOCTREE_TEMPLATE
link_target_template = LINK_TARGET_TEMPLATE
css_link_target_class = CSS_LINK_TARGET_CLASS
guide_titles = GUIDE_TITLES
media_types = MEDIA_TYPES
refuri_re = REFURI_RE
template_dir = ""
doctype = ""
def init(self):
# type: () -> None
StandaloneHTMLBuilder.init(self)
# the output files for epub must be .html only
self.out_suffix = '.xhtml'
self.link_suffix = '.xhtml'
self.playorder = 0
self.tocid = 0
self.id_cache = {} # type: Dict[unicode, unicode]
self.use_index = self.get_builder_config('use_index', 'epub')
def create_build_info(self):
# type: () -> BuildInfo
return BuildInfo(self.config, self.tags, ['html', 'epub'])
def get_theme_config(self):
# type: () -> Tuple[unicode, Dict]
return self.config.epub_theme, self.config.epub_theme_options
# generic support functions
def make_id(self, name):
# type: (unicode) -> unicode
# id_cache is intentionally mutable
"""Return a unique id for name."""
id = self.id_cache.get(name)
if not id:
id = 'epub-%d' % self.env.new_serialno('epub')
self.id_cache[name] = id
return id
def esc(self, name):
# type: (unicode) -> unicode
"""Replace all characters not allowed in text an attribute values."""
# Like cgi.escape, but also replace apostrophe
name = name.replace('&', '&')
name = name.replace('<', '<')
name = name.replace('>', '>')
name = name.replace('"', '"')
name = name.replace('\'', ''')
return name
def get_refnodes(self, doctree, result):
# type: (nodes.Node, List[Dict[unicode, Any]]) -> List[Dict[unicode, Any]]
"""Collect section titles, their depth in the toc and the refuri."""
# XXX: is there a better way than checking the attribute
# toctree-l[1-8] on the parent node?
if isinstance(doctree, nodes.reference) and 'refuri' in doctree:
refuri = doctree['refuri']
if refuri.startswith('http://') or refuri.startswith('https://') \
or refuri.startswith('irc:') or refuri.startswith('mailto:'):
return result
classes = doctree.parent.attributes['classes']
for level in range(8, 0, -1): # or range(1, 8)?
if (self.toctree_template % level) in classes:
result.append({
'level': level,
'refuri': self.esc(refuri),
'text': ssp(self.esc(doctree.astext()))
})
break
else:
for elem in doctree.children:
result = self.get_refnodes(elem, result)
return result
def get_toc(self):
# type: () -> None
"""Get the total table of contents, containing the master_doc
and pre and post files not managed by sphinx.
"""
doctree = self.env.get_and_resolve_doctree(self.config.master_doc,
self, prune_toctrees=False,
includehidden=True)
self.refnodes = self.get_refnodes(doctree, [])
master_dir = path.dirname(self.config.master_doc)
if master_dir:
master_dir += '/' # XXX or os.sep?
for item in self.refnodes:
item['refuri'] = master_dir + item['refuri']
self.toc_add_files(self.refnodes)
def toc_add_files(self, refnodes):
# type: (List[nodes.Node]) -> None
"""Add the master_doc, pre and post files to a list of refnodes.
"""
refnodes.insert(0, {
'level': 1,
'refuri': self.esc(self.config.master_doc + self.out_suffix),
'text': ssp(self.esc(
self.env.titles[self.config.master_doc].astext()))
})
for file, text in reversed(self.config.epub_pre_files):
refnodes.insert(0, {
'level': 1,
'refuri': self.esc(file),
'text': ssp(self.esc(text))
})
for file, text in self.config.epub_post_files:
refnodes.append({
'level': 1,
'refuri': self.esc(file),
'text': ssp(self.esc(text))
})
def fix_fragment(self, prefix, fragment):
# type: (unicode, unicode) -> unicode
"""Return a href/id attribute with colons replaced by hyphens."""
return prefix + fragment.replace(':', '-')
def fix_ids(self, tree):
# type: (nodes.Node) -> None
"""Replace colons with hyphens in href and id attributes.
Some readers crash because they interpret the part as a
transport protocol specification.
"""
for node in tree.traverse(nodes.reference):
if 'refuri' in node:
m = self.refuri_re.match(node['refuri'])
if m:
node['refuri'] = self.fix_fragment(m.group(1), m.group(2))
if 'refid' in node:
node['refid'] = self.fix_fragment('', node['refid'])
for node in tree.traverse(addnodes.desc_signature):
ids = node.attributes['ids']
newids = []
for id in ids:
newids.append(self.fix_fragment('', id))
node.attributes['ids'] = newids
def add_visible_links(self, tree, show_urls='inline'):
# type: (nodes.Node, unicode) -> None
"""Add visible link targets for external links"""
def make_footnote_ref(doc, label):
# type: (nodes.Node, unicode) -> nodes.footnote_reference
"""Create a footnote_reference node with children"""
footnote_ref = nodes.footnote_reference('[#]_')
footnote_ref.append(nodes.Text(label))
doc.note_autofootnote_ref(footnote_ref)
return footnote_ref
def make_footnote(doc, label, uri):
# type: (nodes.Node, unicode, unicode) -> nodes.footnote
"""Create a footnote node with children"""
footnote = nodes.footnote(uri)
para = nodes.paragraph()
para.append(nodes.Text(uri))
footnote.append(para)
footnote.insert(0, nodes.label('', label))
doc.note_autofootnote(footnote)
return footnote
def footnote_spot(tree):
# type: (nodes.Node) -> Tuple[nodes.Node, int]
"""Find or create a spot to place footnotes.
The function returns the tuple (parent, index)."""
# The code uses the following heuristic:
# a) place them after the last existing footnote
# b) place them after an (empty) Footnotes rubric
# c) create an empty Footnotes rubric at the end of the document
fns = tree.traverse(nodes.footnote)
if fns:
fn = fns[-1]
return fn.parent, fn.parent.index(fn) + 1
for node in tree.traverse(nodes.rubric):
if len(node.children) == 1 and \
node.children[0].astext() == FOOTNOTES_RUBRIC_NAME:
return node.parent, node.parent.index(node) + 1
doc = tree.traverse(nodes.document)[0]
rub = nodes.rubric()
rub.append(nodes.Text(FOOTNOTES_RUBRIC_NAME))
doc.append(rub)
return doc, doc.index(rub) + 1
if show_urls == 'no':
return
if show_urls == 'footnote':
doc = tree.traverse(nodes.document)[0]
fn_spot, fn_idx = footnote_spot(tree)
nr = 1
for node in tree.traverse(nodes.reference):
uri = node.get('refuri', '')
if (uri.startswith('http:') or uri.startswith('https:') or
uri.startswith('ftp:')) and uri not in node.astext():
idx = node.parent.index(node) + 1
if show_urls == 'inline':
uri = self.link_target_template % {'uri': uri}
link = nodes.inline(uri, uri)
link['classes'].append(self.css_link_target_class)
node.parent.insert(idx, link)
elif show_urls == 'footnote':
label = FOOTNOTE_LABEL_TEMPLATE % nr
nr += 1
footnote_ref = make_footnote_ref(doc, label)
node.parent.insert(idx, footnote_ref)
footnote = make_footnote(doc, label, uri)
fn_spot.insert(fn_idx, footnote)
footnote_ref['refid'] = footnote['ids'][0]
footnote.add_backref(footnote_ref['ids'][0])
fn_idx += 1
def write_doc(self, docname, doctree):
# type: (unicode, nodes.Node) -> None
"""Write one document file.
This method is overwritten in order to fix fragment identifiers
and to add visible external links.
"""
self.fix_ids(doctree)
self.add_visible_links(doctree, self.config.epub_show_urls)
StandaloneHTMLBuilder.write_doc(self, docname, doctree)
def fix_genindex(self, tree):
# type: (nodes.Node) -> None
"""Fix href attributes for genindex pages."""
# XXX: modifies tree inline
# Logic modeled from themes/basic/genindex.html
for key, columns in tree:
for entryname, (links, subitems, key_) in columns:
for (i, (ismain, link)) in enumerate(links):
m = self.refuri_re.match(link)
if m:
links[i] = (ismain,
self.fix_fragment(m.group(1), m.group(2)))
for subentryname, subentrylinks in subitems:
for (i, (ismain, link)) in enumerate(subentrylinks):
m = self.refuri_re.match(link)
if m:
subentrylinks[i] = (ismain,
self.fix_fragment(m.group(1), m.group(2)))
def is_vector_graphics(self, filename):
# type: (unicode) -> bool
"""Does the filename extension indicate a vector graphic format?"""
ext = path.splitext(filename)[-1]
return ext in VECTOR_GRAPHICS_EXTENSIONS
def copy_image_files_pil(self):
# type: () -> None
"""Copy images using the PIL.
The method tries to read and write the files with the PIL,
converting the format and resizing the image if necessary/possible.
"""
ensuredir(path.join(self.outdir, self.imagedir))
for src in status_iterator(self.images, 'copying images... ', "brown",
len(self.images), self.app.verbosity):
dest = self.images[src]
try:
img = Image.open(path.join(self.srcdir, src))
except IOError:
if not self.is_vector_graphics(src):
logger.warning(__('cannot read image file %r: copying it instead'),
path.join(self.srcdir, src))
try:
copyfile(path.join(self.srcdir, src),
path.join(self.outdir, self.imagedir, dest))
except (IOError, OSError) as err:
logger.warning(__('cannot copy image file %r: %s'),
path.join(self.srcdir, src), err)
continue
if self.config.epub_fix_images:
if img.mode in ('P',):
# See PIL documentation for Image.convert()
img = img.convert()
if self.config.epub_max_image_width > 0:
(width, height) = img.size
nw = self.config.epub_max_image_width
if width > nw:
nh = (height * nw) / width
img = img.resize((nw, nh), Image.BICUBIC)
try:
img.save(path.join(self.outdir, self.imagedir, dest))
except (IOError, OSError) as err:
logger.warning(__('cannot write image file %r: %s'),
path.join(self.srcdir, src), err)
def copy_image_files(self):
# type: () -> None
"""Copy image files to destination directory.
This overwritten method can use the PIL to convert image files.
"""
if self.images:
if self.config.epub_fix_images or self.config.epub_max_image_width:
if not Image:
logger.warning(__('PIL not found - copying image files'))
super(EpubBuilder, self).copy_image_files()
else:
self.copy_image_files_pil()
else:
super(EpubBuilder, self).copy_image_files()
def copy_download_files(self):
# type: () -> None
pass
def handle_page(self, pagename, addctx, templatename='page.html',
outfilename=None, event_arg=None):
# type: (unicode, Dict, unicode, unicode, Any) -> None
"""Create a rendered page.
This method is overwritten for genindex pages in order to fix href link
attributes.
"""
if pagename.startswith('genindex') and 'genindexentries' in addctx:
if not self.use_index:
return
self.fix_genindex(addctx['genindexentries'])
addctx['doctype'] = self.doctype
StandaloneHTMLBuilder.handle_page(self, pagename, addctx, templatename,
outfilename, event_arg)
def build_mimetype(self, outdir, outname):
# type: (unicode, unicode) -> None
"""Write the metainfo file mimetype."""
logger.info(__('writing %s file...'), outname)
copy_asset_file(path.join(self.template_dir, 'mimetype'),
path.join(outdir, outname))
def build_container(self, outdir, outname):
# type: (unicode, unicode) -> None
"""Write the metainfo file META-INF/container.xml."""
logger.info(__('writing %s file...'), outname)
filename = path.join(outdir, outname)
ensuredir(path.dirname(filename))
copy_asset_file(path.join(self.template_dir, 'container.xml'), filename)
def content_metadata(self):
# type: () -> Dict[unicode, Any]
"""Create a dictionary with all metadata for the content.opf
file properly escaped.
"""
metadata = {} # type: Dict[unicode, Any]
metadata['title'] = self.esc(self.config.epub_title)
metadata['author'] = self.esc(self.config.epub_author)
metadata['uid'] = self.esc(self.config.epub_uid)
metadata['lang'] = self.esc(self.config.epub_language)
metadata['publisher'] = self.esc(self.config.epub_publisher)
metadata['copyright'] = self.esc(self.config.epub_copyright)
metadata['scheme'] = self.esc(self.config.epub_scheme)
metadata['id'] = self.esc(self.config.epub_identifier)
metadata['date'] = self.esc(format_date("%Y-%m-%d"))
metadata['manifest_items'] = []
metadata['spines'] = []
metadata['guides'] = []
return metadata
def build_content(self, outdir, outname):
# type: (unicode, unicode) -> None
"""Write the metainfo file content.opf It contains bibliographic data,
a file list and the spine (the reading order).
"""
logger.info(__('writing %s file...'), outname)
metadata = self.content_metadata()
# files
if not outdir.endswith(os.sep):
outdir += os.sep
olen = len(outdir)
self.files = [] # type: List[unicode]
self.ignored_files = ['.buildinfo', 'mimetype', 'content.opf',
'toc.ncx', 'META-INF/container.xml',
'Thumbs.db', 'ehthumbs.db', '.DS_Store',
'nav.xhtml', self.config.epub_basename + '.epub'] + \
self.config.epub_exclude_files
if not self.use_index:
self.ignored_files.append('genindex' + self.out_suffix)
for root, dirs, files in os.walk(outdir):
dirs.sort()
for fn in sorted(files):
filename = path.join(root, fn)[olen:]
if filename in self.ignored_files:
continue
ext = path.splitext(filename)[-1]
if ext not in self.media_types:
# we always have JS and potentially OpenSearch files, don't
# always warn about them
if ext not in ('.js', '.xml'):
logger.warning(__('unknown mimetype for %s, ignoring'), filename,
type='epub', subtype='unknown_project_files')
continue
filename = filename.replace(os.sep, '/')
item = ManifestItem(self.esc(filename),
self.esc(self.make_id(filename)),
self.esc(self.media_types[ext]))
metadata['manifest_items'].append(item)
self.files.append(filename)
# spine
spinefiles = set()
for refnode in self.refnodes:
if '#' in refnode['refuri']:
continue
if refnode['refuri'] in self.ignored_files:
continue
spine = Spine(self.esc(self.make_id(refnode['refuri'])), True)
metadata['spines'].append(spine)
spinefiles.add(refnode['refuri'])
for info in self.domain_indices:
spine = Spine(self.esc(self.make_id(info[0] + self.out_suffix)), True)
metadata['spines'].append(spine)
spinefiles.add(info[0] + self.out_suffix)
if self.use_index:
spine = Spine(self.esc(self.make_id('genindex' + self.out_suffix)), True)
metadata['spines'].append(spine)
spinefiles.add('genindex' + self.out_suffix)
# add auto generated files
for name in self.files:
if name not in spinefiles and name.endswith(self.out_suffix):
spine = Spine(self.esc(self.make_id(name)), False)
metadata['spines'].append(spine)
# add the optional cover
html_tmpl = None
if self.config.epub_cover:
image, html_tmpl = self.config.epub_cover
image = image.replace(os.sep, '/')
metadata['cover'] = self.esc(self.make_id(image))
if html_tmpl:
spine = Spine(self.esc(self.make_id(self.coverpage_name)), True)
metadata['spines'].insert(0, spine)
if self.coverpage_name not in self.files:
ext = path.splitext(self.coverpage_name)[-1]
self.files.append(self.coverpage_name)
item = ManifestItem(self.esc(self.coverpage_name),
self.esc(self.make_id(self.coverpage_name)),
self.esc(self.media_types[ext]))
metadata['manifest_items'].append(item)
ctx = {'image': self.esc(image), 'title': self.config.project}
self.handle_page(
path.splitext(self.coverpage_name)[0], ctx, html_tmpl)
spinefiles.add(self.coverpage_name)
auto_add_cover = True
auto_add_toc = True
if self.config.epub_guide:
for type, uri, title in self.config.epub_guide:
file = uri.split('#')[0]
if file not in self.files:
self.files.append(file)
if type == 'cover':
auto_add_cover = False
if type == 'toc':
auto_add_toc = False
metadata['guides'].append(Guide(self.esc(type),
self.esc(title),
self.esc(uri)))
if auto_add_cover and html_tmpl:
metadata['guides'].append(Guide('cover',
self.guide_titles['cover'],
self.esc(self.coverpage_name)))
if auto_add_toc and self.refnodes:
metadata['guides'].append(Guide('toc',
self.guide_titles['toc'],
self.esc(self.refnodes[0]['refuri'])))
# write the project file
copy_asset_file(path.join(self.template_dir, 'content.opf_t'),
path.join(outdir, outname),
metadata)
def new_navpoint(self, node, level, incr=True):
# type: (nodes.Node, int, bool) -> NavPoint
"""Create a new entry in the toc from the node at given level."""
# XXX Modifies the node
if incr:
self.playorder += 1
self.tocid += 1
return NavPoint(self.esc('navPoint%d' % self.tocid), self.playorder,
node['text'], node['refuri'], [])
def build_navpoints(self, nodes):
# type: (nodes.Node) -> List[NavPoint]
"""Create the toc navigation structure.
Subelements of a node are nested inside the navpoint. For nested nodes
the parent node is reinserted in the subnav.
"""
navstack = [] # type: List[NavPoint]
navstack.append(NavPoint('dummy', '', '', '', []))
level = 0
lastnode = None
for node in nodes:
if not node['text']:
continue
file = node['refuri'].split('#')[0]
if file in self.ignored_files:
continue
if node['level'] > self.config.epub_tocdepth:
continue
if node['level'] == level:
navpoint = self.new_navpoint(node, level)
navstack.pop()
navstack[-1].children.append(navpoint)
navstack.append(navpoint)
elif node['level'] == level + 1:
level += 1
if lastnode and self.config.epub_tocdup:
# Insert starting point in subtoc with same playOrder
navstack[-1].children.append(self.new_navpoint(lastnode, level, False))
navpoint = self.new_navpoint(node, level)
navstack[-1].children.append(navpoint)
navstack.append(navpoint)
elif node['level'] < level:
while node['level'] < len(navstack):
navstack.pop()
level = node['level']
navpoint = self.new_navpoint(node, level)
navstack[-1].children.append(navpoint)
navstack.append(navpoint)
else:
raise
lastnode = node
return navstack[0].children
def toc_metadata(self, level, navpoints):
# type: (int, List[NavPoint]) -> Dict[unicode, Any]
"""Create a dictionary with all metadata for the toc.ncx file
properly escaped.
"""
metadata = {} # type: Dict[unicode, Any]
metadata['uid'] = self.config.epub_uid
metadata['title'] = self.esc(self.config.epub_title)
metadata['level'] = level
metadata['navpoints'] = navpoints
return metadata
def build_toc(self, outdir, outname):
# type: (unicode, unicode) -> None
"""Write the metainfo file toc.ncx."""
logger.info(__('writing %s file...'), outname)
if self.config.epub_tocscope == 'default':
doctree = self.env.get_and_resolve_doctree(self.config.master_doc,
self, prune_toctrees=False,
includehidden=False)
refnodes = self.get_refnodes(doctree, [])
self.toc_add_files(refnodes)
else:
# 'includehidden'
refnodes = self.refnodes
navpoints = self.build_navpoints(refnodes)
level = max(item['level'] for item in self.refnodes)
level = min(level, self.config.epub_tocdepth)
copy_asset_file(path.join(self.template_dir, 'toc.ncx_t'),
path.join(outdir, outname),
self.toc_metadata(level, navpoints))
def build_epub(self, outdir, outname):
# type: (unicode, unicode) -> None
"""Write the epub file.
It is a zip file with the mimetype file stored uncompressed as the first
entry.
"""
logger.info(__('writing %s file...'), outname)
epub_filename = path.join(outdir, outname)
with ZipFile(epub_filename, 'w', ZIP_DEFLATED) as epub:
epub.write(path.join(outdir, 'mimetype'), 'mimetype', ZIP_STORED)
for filename in [u'META-INF/container.xml', u'content.opf', u'toc.ncx']:
epub.write(path.join(outdir, filename), filename, ZIP_DEFLATED)
for filename in self.files:
epub.write(path.join(outdir, filename), filename, ZIP_DEFLATED)
| 40.974895
| 91
| 0.558596
|
7f3f0d62002859c20f63abe9e2ad36c7d7fcf360
| 21,019
|
py
|
Python
|
pysnmp/SNMP553S-MGMT-MIB.py
|
agustinhenze/mibs.snmplabs.com
|
1fc5c07860542b89212f4c8ab807057d9a9206c7
|
[
"Apache-2.0"
] | 11
|
2021-02-02T16:27:16.000Z
|
2021-08-31T06:22:49.000Z
|
pysnmp/SNMP553S-MGMT-MIB.py
|
agustinhenze/mibs.snmplabs.com
|
1fc5c07860542b89212f4c8ab807057d9a9206c7
|
[
"Apache-2.0"
] | 75
|
2021-02-24T17:30:31.000Z
|
2021-12-08T00:01:18.000Z
|
pysnmp/SNMP553S-MGMT-MIB.py
|
agustinhenze/mibs.snmplabs.com
|
1fc5c07860542b89212f4c8ab807057d9a9206c7
|
[
"Apache-2.0"
] | 10
|
2019-04-30T05:51:36.000Z
|
2022-02-16T03:33:41.000Z
|
#
# PySNMP MIB module SNMP553S-MGMT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SNMP553S-MGMT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:00:38 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, SingleValueConstraint, ValueSizeConstraint, ValueRangeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "SingleValueConstraint", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsUnion")
dsx1, = mibBuilder.importSymbols("GDCDSX1-MIB", "dsx1")
SCinstance, = mibBuilder.importSymbols("GDCMACRO-MIB", "SCinstance")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Integer32, NotificationType, Bits, IpAddress, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, Unsigned32, ModuleIdentity, ObjectIdentity, Gauge32, Counter32, Counter64, TimeTicks, iso = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "NotificationType", "Bits", "IpAddress", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Unsigned32", "ModuleIdentity", "ObjectIdentity", "Gauge32", "Counter32", "Counter64", "TimeTicks", "iso")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
snmp553s = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 6, 3))
snmp553sc = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 6, 4))
snmp553sAlarmData = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 6, 3, 1))
snmp553sNoResponseAlm = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 6, 3, 1, 1))
snmp553sDiagRxErrAlm = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 6, 3, 1, 2))
snmp553sPowerUpAlm = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 6, 3, 1, 3))
snmp553sNvRamCorrupt = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 6, 3, 1, 4))
snmp553sUnitFailure = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 6, 3, 1, 5))
snmp553sMbiLock = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 6, 3, 1, 6))
snmp553sLocalPwrFail = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 6, 3, 1, 7))
snmp553sTimingLoss = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 6, 3, 1, 8))
snmp553sStatusChange = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 6, 3, 1, 9))
snmp553sUnsoTest = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 6, 3, 1, 10))
snmp553sLossOfSignal = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 6, 3, 1, 11))
snmp553sLossOfFrame = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 6, 3, 1, 12))
snmp553sAis = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 6, 3, 1, 13))
snmp553sReceivedYellow = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 6, 3, 1, 14))
snmp553sUnavailSignalState = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 6, 3, 1, 15))
snmp553sExcessiveZeros = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 6, 3, 1, 16))
snmp553sLowAverageDensity = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 6, 3, 1, 17))
snmp553sControlledSlips = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 6, 3, 1, 18))
snmp553sBipolarViolations = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 6, 3, 1, 19))
snmp553sCrcErrors = MibIdentifier((1, 3, 6, 1, 4, 1, 498, 6, 3, 1, 20))
snmp553sMIBversion = MibScalar((1, 3, 6, 1, 4, 1, 498, 6, 3, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(5, 5)).setFixedLength(5)).setMaxAccess("readonly")
if mibBuilder.loadTexts: snmp553sMIBversion.setStatus('mandatory')
snmp553sMaintenanceTable = MibTable((1, 3, 6, 1, 4, 1, 498, 6, 3, 3), )
if mibBuilder.loadTexts: snmp553sMaintenanceTable.setStatus('mandatory')
snmp553sMaintenanceEntry = MibTableRow((1, 3, 6, 1, 4, 1, 498, 6, 3, 3, 1), ).setIndexNames((0, "SNMP553S-MGMT-MIB", "snmp553sMaintenanceIndex"))
if mibBuilder.loadTexts: snmp553sMaintenanceEntry.setStatus('mandatory')
snmp553sMaintenanceIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 3, 1, 1), SCinstance()).setMaxAccess("readonly")
if mibBuilder.loadTexts: snmp553sMaintenanceIndex.setStatus('mandatory')
snmp553sCascadePresent = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 3, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("notPresent", 1), ("present", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: snmp553sCascadePresent.setStatus('mandatory')
snmp553sExtModemPresent = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 3, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("notPresent", 1), ("present", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: snmp553sExtModemPresent.setStatus('mandatory')
snmp553sUnitType = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 3, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("master", 1), ("remote", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: snmp553sUnitType.setStatus('mandatory')
snmp553sManagementSource = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 3, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("modemSnmp", 1), ("secondaryChannel", 2), ("fdl", 3), ("daisyChain", 4), ("bus485", 5), ("localSnmp", 6)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: snmp553sManagementSource.setStatus('mandatory')
snmp553sProductType = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 3, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8))).clone(namedValues=NamedValues(("snmp553sd1ifp", 1), ("snmp553sd3ifp", 2), ("snmp553scifp", 3), ("nms553d1", 4), ("nms553d1ifp", 5), ("nms553d3ifp", 6), ("nms553c", 7), ("nms553cifp", 8)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: snmp553sProductType.setStatus('mandatory')
snmp553sLedStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 3, 1, 7), OctetString().subtype(subtypeSpec=ValueSizeConstraint(3, 3)).setFixedLength(3)).setMaxAccess("readonly")
if mibBuilder.loadTexts: snmp553sLedStatus.setStatus('mandatory')
snmp553sUnitSerialNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 3, 1, 8), OctetString().subtype(subtypeSpec=ValueSizeConstraint(16, 16)).setFixedLength(16)).setMaxAccess("readonly")
if mibBuilder.loadTexts: snmp553sUnitSerialNumber.setStatus('mandatory')
snmp553sSaveAllConfig = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 3, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("normal", 1), ("saveConfig", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: snmp553sSaveAllConfig.setStatus('mandatory')
snmp553sUnitConfigTable = MibTable((1, 3, 6, 1, 4, 1, 498, 6, 3, 4), )
if mibBuilder.loadTexts: snmp553sUnitConfigTable.setStatus('mandatory')
snmp553sUnitConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 498, 6, 3, 4, 1), ).setIndexNames((0, "SNMP553S-MGMT-MIB", "snmp553sUnitConfigIndex"))
if mibBuilder.loadTexts: snmp553sUnitConfigEntry.setStatus('mandatory')
snmp553sUnitConfigIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 4, 1, 1), SCinstance()).setMaxAccess("readonly")
if mibBuilder.loadTexts: snmp553sUnitConfigIndex.setStatus('mandatory')
snmp553sSaveCsuConfig = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 4, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("normal", 1), ("saveConfig", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: snmp553sSaveCsuConfig.setStatus('mandatory')
snmp553sShelfCommander = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 4, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("disabled", 1), ("enabled", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: snmp553sShelfCommander.setStatus('mandatory')
snmp553sForceFakeMaster = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 4, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: snmp553sForceFakeMaster.setStatus('mandatory')
snmp553sDaisyChainBps = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 4, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("none", 1), ("bps75", 2), ("bps9600", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: snmp553sDaisyChainBps.setStatus('mandatory')
snmp553sChannelConfigTable = MibTable((1, 3, 6, 1, 4, 1, 498, 6, 3, 5), )
if mibBuilder.loadTexts: snmp553sChannelConfigTable.setStatus('mandatory')
snmp553sChannelConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 498, 6, 3, 5, 1), ).setIndexNames((0, "SNMP553S-MGMT-MIB", "snmp553sChannelConfigIndex"))
if mibBuilder.loadTexts: snmp553sChannelConfigEntry.setStatus('mandatory')
snmp553sChannelConfigIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 5, 1, 1), SCinstance()).setMaxAccess("readonly")
if mibBuilder.loadTexts: snmp553sChannelConfigIndex.setStatus('mandatory')
snmp553sDCCCompatibilityMode = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 5, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("nms553", 1), ("nms510", 2), ("other", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: snmp553sDCCCompatibilityMode.setStatus('mandatory')
snmp553sSaveDsuConfig = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 5, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("normal", 1), ("saveConfig", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: snmp553sSaveDsuConfig.setStatus('mandatory')
snmp553sDiagTable = MibTable((1, 3, 6, 1, 4, 1, 498, 6, 3, 6), )
if mibBuilder.loadTexts: snmp553sDiagTable.setStatus('mandatory')
snmp553sDiagEntry = MibTableRow((1, 3, 6, 1, 4, 1, 498, 6, 3, 6, 1), ).setIndexNames((0, "SNMP553S-MGMT-MIB", "snmp553sDiagIndex"))
if mibBuilder.loadTexts: snmp553sDiagEntry.setStatus('mandatory')
snmp553sDiagIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 6, 1, 1), SCinstance()).setMaxAccess("readonly")
if mibBuilder.loadTexts: snmp553sDiagIndex.setStatus('mandatory')
snmp553sDiagTestDuration = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 6, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16))).clone(namedValues=NamedValues(("noLimit", 1), ("testTime1Min", 2), ("testTime2Mins", 3), ("testTime3Mins", 4), ("testTime4Mins", 5), ("testTime5Mins", 6), ("testTime6Mins", 7), ("testTime7Mins", 8), ("testTime8Mins", 9), ("testTime9Mins", 10), ("testTime10Mins", 11), ("testTime15Mins", 12), ("testTime20Mins", 13), ("testTime25Mins", 14), ("testTime30Mins", 15), ("testTime30Secs", 16)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: snmp553sDiagTestDuration.setStatus('mandatory')
snmp553sDiagProgPattern = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 6, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: snmp553sDiagProgPattern.setStatus('mandatory')
snmp553sAlarmHistoryTable = MibTable((1, 3, 6, 1, 4, 1, 498, 6, 3, 7), )
if mibBuilder.loadTexts: snmp553sAlarmHistoryTable.setStatus('mandatory')
snmp553sAlarmHistoryEntry = MibTableRow((1, 3, 6, 1, 4, 1, 498, 6, 3, 7, 1), ).setIndexNames((0, "SNMP553S-MGMT-MIB", "snmp553sAlarmHistoryIndex"), (0, "SNMP553S-MGMT-MIB", "snmp553sAlarmHistoryIdentifier"))
if mibBuilder.loadTexts: snmp553sAlarmHistoryEntry.setStatus('mandatory')
snmp553sAlarmHistoryIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 7, 1, 1), SCinstance()).setMaxAccess("readonly")
if mibBuilder.loadTexts: snmp553sAlarmHistoryIndex.setStatus('mandatory')
snmp553sAlarmHistoryIdentifier = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 7, 1, 2), ObjectIdentifier()).setMaxAccess("readonly")
if mibBuilder.loadTexts: snmp553sAlarmHistoryIdentifier.setStatus('mandatory')
snmp553sAlarmCount = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 7, 1, 3), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: snmp553sAlarmCount.setStatus('mandatory')
snmp553sAlarmFirstOccurrenceHours = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 7, 1, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: snmp553sAlarmFirstOccurrenceHours.setStatus('mandatory')
snmp553sAlarmFirstOccurrenceMinutes = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 7, 1, 5), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: snmp553sAlarmFirstOccurrenceMinutes.setStatus('mandatory')
snmp553sAlarmFirstOccurrenceSeconds = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 7, 1, 6), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: snmp553sAlarmFirstOccurrenceSeconds.setStatus('mandatory')
snmp553sAlarmFirstOccurrenceMonth = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 7, 1, 7), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: snmp553sAlarmFirstOccurrenceMonth.setStatus('mandatory')
snmp553sAlarmFirstOccurrenceDay = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 7, 1, 8), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: snmp553sAlarmFirstOccurrenceDay.setStatus('mandatory')
snmp553sAlarmFirstOccurrenceYear = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 7, 1, 9), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: snmp553sAlarmFirstOccurrenceYear.setStatus('mandatory')
snmp553sAlarmLastOccurrenceHours = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 7, 1, 10), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: snmp553sAlarmLastOccurrenceHours.setStatus('mandatory')
snmp553sAlarmLastOccurrenceMinutes = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 7, 1, 11), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: snmp553sAlarmLastOccurrenceMinutes.setStatus('mandatory')
snmp553sAlarmLastOccurrenceSeconds = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 7, 1, 12), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: snmp553sAlarmLastOccurrenceSeconds.setStatus('mandatory')
snmp553sAlarmLastOccurrenceMonth = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 7, 1, 13), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: snmp553sAlarmLastOccurrenceMonth.setStatus('mandatory')
snmp553sAlarmLastOccurrenceDay = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 7, 1, 14), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: snmp553sAlarmLastOccurrenceDay.setStatus('mandatory')
snmp553sAlarmLastOccurrenceYear = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 7, 1, 15), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: snmp553sAlarmLastOccurrenceYear.setStatus('mandatory')
snmp553sAlarmMaintenanceTable = MibTable((1, 3, 6, 1, 4, 1, 498, 6, 3, 8), )
if mibBuilder.loadTexts: snmp553sAlarmMaintenanceTable.setStatus('mandatory')
snmp553sAlarmMaintenanceEntry = MibTableRow((1, 3, 6, 1, 4, 1, 498, 6, 3, 8, 1), ).setIndexNames((0, "SNMP553S-MGMT-MIB", "snmp553sAlarmMaintenanceIndex"))
if mibBuilder.loadTexts: snmp553sAlarmMaintenanceEntry.setStatus('mandatory')
snmp553sAlarmMaintenanceIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 8, 1, 1), SCinstance()).setMaxAccess("readonly")
if mibBuilder.loadTexts: snmp553sAlarmMaintenanceIndex.setStatus('mandatory')
snmp553sClearAlarmHistory = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 8, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("clear", 1), ("norm", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: snmp553sClearAlarmHistory.setStatus('mandatory')
snmp553sRTCHours = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 8, 1, 3), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: snmp553sRTCHours.setStatus('mandatory')
snmp553sRTCMinutes = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 8, 1, 4), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: snmp553sRTCMinutes.setStatus('mandatory')
snmp553sRTCSeconds = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 8, 1, 5), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: snmp553sRTCSeconds.setStatus('mandatory')
snmp553sRTCMonth = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 8, 1, 6), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: snmp553sRTCMonth.setStatus('mandatory')
snmp553sRTCDay = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 8, 1, 7), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: snmp553sRTCDay.setStatus('mandatory')
snmp553sRTCYear = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 8, 1, 8), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: snmp553sRTCYear.setStatus('mandatory')
snmp553sTimeOfLastAlarmClear = MibTableColumn((1, 3, 6, 1, 4, 1, 498, 6, 3, 8, 1, 9), OctetString().subtype(subtypeSpec=ValueSizeConstraint(6, 6)).setFixedLength(6)).setMaxAccess("readonly")
if mibBuilder.loadTexts: snmp553sTimeOfLastAlarmClear.setStatus('mandatory')
mibBuilder.exportSymbols("SNMP553S-MGMT-MIB", snmp553sLossOfSignal=snmp553sLossOfSignal, snmp553sAlarmLastOccurrenceHours=snmp553sAlarmLastOccurrenceHours, snmp553sAis=snmp553sAis, snmp553sSaveAllConfig=snmp553sSaveAllConfig, snmp553sDiagRxErrAlm=snmp553sDiagRxErrAlm, snmp553sAlarmFirstOccurrenceHours=snmp553sAlarmFirstOccurrenceHours, snmp553sDiagTestDuration=snmp553sDiagTestDuration, snmp553sAlarmCount=snmp553sAlarmCount, snmp553sDiagEntry=snmp553sDiagEntry, snmp553sManagementSource=snmp553sManagementSource, snmp553sUnitConfigIndex=snmp553sUnitConfigIndex, snmp553sCrcErrors=snmp553sCrcErrors, snmp553sMaintenanceEntry=snmp553sMaintenanceEntry, snmp553sAlarmHistoryIndex=snmp553sAlarmHistoryIndex, snmp553sMaintenanceIndex=snmp553sMaintenanceIndex, snmp553sDiagTable=snmp553sDiagTable, snmp553sAlarmFirstOccurrenceYear=snmp553sAlarmFirstOccurrenceYear, snmp553sRTCMinutes=snmp553sRTCMinutes, snmp553sMIBversion=snmp553sMIBversion, snmp553sAlarmLastOccurrenceDay=snmp553sAlarmLastOccurrenceDay, snmp553sClearAlarmHistory=snmp553sClearAlarmHistory, snmp553sMbiLock=snmp553sMbiLock, snmp553sChannelConfigEntry=snmp553sChannelConfigEntry, snmp553s=snmp553s, snmp553sChannelConfigIndex=snmp553sChannelConfigIndex, snmp553sAlarmMaintenanceIndex=snmp553sAlarmMaintenanceIndex, snmp553sForceFakeMaster=snmp553sForceFakeMaster, snmp553sUnitType=snmp553sUnitType, snmp553sAlarmFirstOccurrenceDay=snmp553sAlarmFirstOccurrenceDay, snmp553sTimingLoss=snmp553sTimingLoss, snmp553sAlarmFirstOccurrenceMinutes=snmp553sAlarmFirstOccurrenceMinutes, snmp553sSaveDsuConfig=snmp553sSaveDsuConfig, snmp553sUnitConfigTable=snmp553sUnitConfigTable, snmp553sAlarmData=snmp553sAlarmData, snmp553sNoResponseAlm=snmp553sNoResponseAlm, snmp553sLedStatus=snmp553sLedStatus, snmp553sAlarmFirstOccurrenceSeconds=snmp553sAlarmFirstOccurrenceSeconds, snmp553sUnsoTest=snmp553sUnsoTest, snmp553sUnavailSignalState=snmp553sUnavailSignalState, snmp553sAlarmMaintenanceEntry=snmp553sAlarmMaintenanceEntry, snmp553sShelfCommander=snmp553sShelfCommander, snmp553sAlarmLastOccurrenceYear=snmp553sAlarmLastOccurrenceYear, snmp553sMaintenanceTable=snmp553sMaintenanceTable, snmp553sAlarmLastOccurrenceSeconds=snmp553sAlarmLastOccurrenceSeconds, snmp553sLowAverageDensity=snmp553sLowAverageDensity, snmp553sAlarmHistoryEntry=snmp553sAlarmHistoryEntry, snmp553sUnitFailure=snmp553sUnitFailure, snmp553sDiagProgPattern=snmp553sDiagProgPattern, snmp553sc=snmp553sc, snmp553sStatusChange=snmp553sStatusChange, snmp553sChannelConfigTable=snmp553sChannelConfigTable, snmp553sRTCYear=snmp553sRTCYear, snmp553sReceivedYellow=snmp553sReceivedYellow, snmp553sAlarmHistoryTable=snmp553sAlarmHistoryTable, snmp553sBipolarViolations=snmp553sBipolarViolations, snmp553sCascadePresent=snmp553sCascadePresent, snmp553sAlarmLastOccurrenceMinutes=snmp553sAlarmLastOccurrenceMinutes, snmp553sDCCCompatibilityMode=snmp553sDCCCompatibilityMode, snmp553sLossOfFrame=snmp553sLossOfFrame, snmp553sPowerUpAlm=snmp553sPowerUpAlm, snmp553sRTCMonth=snmp553sRTCMonth, snmp553sRTCDay=snmp553sRTCDay, snmp553sNvRamCorrupt=snmp553sNvRamCorrupt, snmp553sRTCHours=snmp553sRTCHours, snmp553sSaveCsuConfig=snmp553sSaveCsuConfig, snmp553sRTCSeconds=snmp553sRTCSeconds, snmp553sAlarmHistoryIdentifier=snmp553sAlarmHistoryIdentifier, snmp553sAlarmLastOccurrenceMonth=snmp553sAlarmLastOccurrenceMonth, snmp553sTimeOfLastAlarmClear=snmp553sTimeOfLastAlarmClear, snmp553sExcessiveZeros=snmp553sExcessiveZeros, snmp553sProductType=snmp553sProductType, snmp553sControlledSlips=snmp553sControlledSlips, snmp553sUnitConfigEntry=snmp553sUnitConfigEntry, snmp553sAlarmMaintenanceTable=snmp553sAlarmMaintenanceTable, snmp553sLocalPwrFail=snmp553sLocalPwrFail, snmp553sDiagIndex=snmp553sDiagIndex, snmp553sUnitSerialNumber=snmp553sUnitSerialNumber, snmp553sDaisyChainBps=snmp553sDaisyChainBps, snmp553sAlarmFirstOccurrenceMonth=snmp553sAlarmFirstOccurrenceMonth, snmp553sExtModemPresent=snmp553sExtModemPresent)
| 136.487013
| 3,925
| 0.77468
|
688e4c4b3845532ba72c323b82b7f6e03e5691e2
| 5,764
|
py
|
Python
|
sendSMSSkillLambda/package/ask_sdk_model/events/skillevents/permission_accepted_request.py
|
shneydor/aws-alexa-lambda-workshop
|
0fa6b7067b04fc85c46b9ce1c2cc04554ed5baf4
|
[
"Apache-2.0"
] | null | null | null |
sendSMSSkillLambda/package/ask_sdk_model/events/skillevents/permission_accepted_request.py
|
shneydor/aws-alexa-lambda-workshop
|
0fa6b7067b04fc85c46b9ce1c2cc04554ed5baf4
|
[
"Apache-2.0"
] | null | null | null |
sendSMSSkillLambda/package/ask_sdk_model/events/skillevents/permission_accepted_request.py
|
shneydor/aws-alexa-lambda-workshop
|
0fa6b7067b04fc85c46b9ce1c2cc04554ed5baf4
|
[
"Apache-2.0"
] | 1
|
2019-10-11T17:15:20.000Z
|
2019-10-11T17:15:20.000Z
|
# coding: utf-8
#
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
# except in compliance with the License. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for
# the specific language governing permissions and limitations under the License.
#
import pprint
import re # noqa: F401
import six
import typing
from enum import Enum
from ask_sdk_model.request import Request
if typing.TYPE_CHECKING:
from typing import Dict, List, Optional, Union
from datetime import datetime
from ask_sdk_model.events.skillevents.permission_body import PermissionBody
class PermissionAcceptedRequest(Request):
"""
:param request_id: Represents the unique identifier for the specific request.
:type request_id: (optional) str
:param timestamp: Provides the date and time when Alexa sent the request as an ISO 8601 formatted string. Used to verify the request when hosting your skill as a web service.
:type timestamp: (optional) datetime
:param locale: A string indicating the user’s locale. For example: en-US. This value is only provided with certain request types.
:type locale: (optional) str
:param body:
:type body: (optional) ask_sdk_model.events.skillevents.permission_body.PermissionBody
:param event_creation_time:
:type event_creation_time: (optional) datetime
:param event_publishing_time:
:type event_publishing_time: (optional) datetime
"""
deserialized_types = {
'object_type': 'str',
'request_id': 'str',
'timestamp': 'datetime',
'locale': 'str',
'body': 'ask_sdk_model.events.skillevents.permission_body.PermissionBody',
'event_creation_time': 'datetime',
'event_publishing_time': 'datetime'
} # type: Dict
attribute_map = {
'object_type': 'type',
'request_id': 'requestId',
'timestamp': 'timestamp',
'locale': 'locale',
'body': 'body',
'event_creation_time': 'eventCreationTime',
'event_publishing_time': 'eventPublishingTime'
} # type: Dict
def __init__(self, request_id=None, timestamp=None, locale=None, body=None, event_creation_time=None, event_publishing_time=None):
# type: (Optional[str], Optional[datetime], Optional[str], Optional[PermissionBody], Optional[datetime], Optional[datetime]) -> None
"""
:param request_id: Represents the unique identifier for the specific request.
:type request_id: (optional) str
:param timestamp: Provides the date and time when Alexa sent the request as an ISO 8601 formatted string. Used to verify the request when hosting your skill as a web service.
:type timestamp: (optional) datetime
:param locale: A string indicating the user’s locale. For example: en-US. This value is only provided with certain request types.
:type locale: (optional) str
:param body:
:type body: (optional) ask_sdk_model.events.skillevents.permission_body.PermissionBody
:param event_creation_time:
:type event_creation_time: (optional) datetime
:param event_publishing_time:
:type event_publishing_time: (optional) datetime
"""
self.__discriminator_value = "AlexaSkillEvent.SkillPermissionAccepted" # type: str
self.object_type = self.__discriminator_value
super(PermissionAcceptedRequest, self).__init__(object_type=self.__discriminator_value, request_id=request_id, timestamp=timestamp, locale=locale)
self.body = body
self.event_creation_time = event_creation_time
self.event_publishing_time = event_publishing_time
def to_dict(self):
# type: () -> Dict[str, object]
"""Returns the model properties as a dict"""
result = {} # type: Dict
for attr, _ in six.iteritems(self.deserialized_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else
x.value if isinstance(x, Enum) else x,
value
))
elif isinstance(value, Enum):
result[attr] = value.value
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else
(item[0], item[1].value)
if isinstance(item[1], Enum) else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
# type: () -> str
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
# type: () -> str
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
# type: (object) -> bool
"""Returns true if both objects are equal"""
if not isinstance(other, PermissionAcceptedRequest):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
# type: (object) -> bool
"""Returns true if both objects are not equal"""
return not self == other
| 40.027778
| 182
| 0.646773
|
87a8999de9c5738e1817ba8a8a3b93dcffcd8dee
| 9,838
|
py
|
Python
|
wandb/run-20210411_184444-3qt4iwcn/files/code/main.py
|
ccoltong1215/simple-lenet5-torch-mnist
|
3eaa25160525f89dd6b9fe1db5de26a2bfda2fea
|
[
"MIT"
] | null | null | null |
wandb/run-20210411_184444-3qt4iwcn/files/code/main.py
|
ccoltong1215/simple-lenet5-torch-mnist
|
3eaa25160525f89dd6b9fe1db5de26a2bfda2fea
|
[
"MIT"
] | 5
|
2021-09-08T03:09:50.000Z
|
2022-03-12T00:56:43.000Z
|
wandb/run-20210411_184444-3qt4iwcn/files/code/main.py
|
ccoltong1215/simple-lenet5-torch-mnist
|
3eaa25160525f89dd6b9fe1db5de26a2bfda2fea
|
[
"MIT"
] | null | null | null |
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from dataset import Dataset
from model import LeNet5, CustomMLP
import numpy as np
import matplotlib.pyplot as plt
import wandb
def train(model, trn_loader, device, criterion, optimizer,epoch,modelname):
""" Train function
Args:
model: network
trn_loader: torch.utils.data.DataLoader instance for training
device: device for computing, cpu or gpu
criterion: cost function
optimizer: optimization method, refer to torch.optim
Returns:
trn_loss: average loss value
acc: accuracy
"""
model.to(device)
trn_loss, acc = [], []
for m in range(epoch):
train_loss = 0
trainacc = 0
for i, (images, labels) in enumerate(trn_loader):
images = images.to(device)
labels = labels.to(device)
outputs = model(images)
loss = criterion(outputs, labels)
train_loss += loss
temp_acc = torch.mean(torch.eq(torch.argmax(outputs, dim=1), labels).to(dtype=torch.float64))
trainacc += temp_acc
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (i) % 1000 == 0:
print("\r {} Step [{}] Loss: {:.4f} acc: {:.4f}\nlabel".format(modelname,i, loss.item(), temp_acc),labels,"\n output", torch.argmax(outputs, dim=1))
trainacc = trainacc / trn_loader.__len__()
train_loss = train_loss / (trn_loader.__len__()) #10은 batchsize, 원래는 argument로 받아와서 사용가능
print("{} training {} epoch Loss: {:.4f} acc: {:.4f}".format(modelname,m, train_loss, trainacc))
trn_loss.append(train_loss.item())
acc.append(trainacc.item())
epochlist = range(epoch)
data = [[x, y] for (x, y) in zip( epochlist,acc)]
data2 = [[x, y] for (x, y) in zip(epochlist, trn_loss)]
table = wandb.Table(data=data, columns=[ "epoch","{}Acc".format(modelname)])
table2 = wandb.Table(data=data2, columns=["epoch", "{}loss".format(modelname)])
wandb.log({"{}Acc".format(modelname): wandb.plot.line(table, "epoch", "{}Acc".format(modelname),title= "{}Acc graph".format(modelname))})
wandb.log({"{}loss".format(modelname): wandb.plot.line(table2, "epoch", "{}loss".format(modelname),title="{}loss graph".format(modelname))})
trn_loss = np.array(trn_loss)
acc=np.array(acc)
dummy_input = torch.randn(1,1,28,28,device=device)
input_names = ["input_0"]
output_names = ["output_0"]
dummy_output = model(dummy_input)
torch.onnx.export(model, dummy_input, "{}.onnx".format(modelname), verbose=True, input_names=input_names,output_names=output_names)
return trn_loss, acc
def test(model, tst_loader, device, criterion,modelname):
""" Test function
Args:
model: network
tst_loader: torch.utils.data.DataLoader instance for testing
device: device for computing, cpu or gpu
criterion: cost function
Returns:
tst_loss: average loss value
acc: accuracy
"""
model.to(device)
tst_loss, acc = [],[]
test_loss=0
test_acc=0
with torch.no_grad(): # 미분 안함,
for i, (images, labels) in enumerate(tst_loader):
images = images.to(device)
labels = labels.to(device)
outputs = model(images)
loss = criterion(outputs, labels)
test_loss += loss
temp_acc = torch.mean(torch.eq(torch.argmax(outputs, dim=1), labels).to(dtype=torch.float64))
test_acc += temp_acc
if (i) % 100 == 0:
print(" Step [{}] Loss: {:.4f} acc: {:.4f}".format(i, loss.item(), temp_acc))
print("label", labels)
print("output", torch.argmax(outputs, dim=1))
tst_loss.append(loss.item())
acc.append(temp_acc.item())
test_acc = test_acc/tst_loader.__len__()
test_loss = test_loss / (tst_loader.__len__())
print("TEST Step [{}] Loss: {:.4f} acc: {:.4f}".format(tst_loader.__len__(), test_loss, test_acc))
tst_loss=np.array(tst_loss).astype(float)
acc=np.array(acc).astype(float)
wandb.log({"{}Acc_test".format(modelname): test_acc,
"{}loss_test".format(modelname): test_loss})
return tst_loss, acc
# import some packages you need here
def main():
""" Main function
Here, you should instantiate
1) Dataset objects for training and test datasets
2) DataLoaders for training and testing
3) model
4) optimizer: SGD with initial learning rate 0.01 and momentum 0.9
5) cost function: use torch.nn.CrossEntropyLoss
"""
wandb.init(project="simple_MNIST_report", config={
})
roottrain='data/train'
roottest ='data/test'
epoch = 100
# declare pipeline
trainloader = DataLoader(dataset=Dataset(root=roottrain), #################################################
batch_size=10,
shuffle=True)
testloader = DataLoader(dataset=Dataset(root=roottest), ################################################
batch_size=10,
shuffle=False)
device = torch.device("cuda:0")
#declare model and opt and loss
LeNet5_model = LeNet5()
criterionLeNet = torch.nn.CrossEntropyLoss()
optimizerLeNet = torch.optim.SGD(LeNet5_model.parameters(), lr=0.001, momentum=0.9)
LeNet5_regulized_model = LeNet5()
criterionLeNet_regulized = torch.nn.CrossEntropyLoss()
optimizerLeNet_regulized = torch.optim.SGD(LeNet5_regulized_model.parameters(), lr=0.001, momentum=0.9)
CustomMLP_model = CustomMLP()
criterionCustomMLP = torch.nn.CrossEntropyLoss()
optimizerCustomMLP = torch.optim.SGD(CustomMLP_model.parameters(), lr=0.001, momentum=0.9)
wandb.watch(
LeNet5_model
)
wandb.watch(
CustomMLP_model
)
####################################################################################
#start training
lenet5trnloss, lenet5trnacc = train(model=LeNet5_model, trn_loader=trainloader, device=device, criterion=criterionLeNet,
optimizer=optimizerLeNet,epoch=epoch,modelname="lenet")
lenet5tstloss, lenet5tstacc = test(model=LeNet5_model, tst_loader=testloader, device=device, criterion=criterionLeNet,modelname="lenet")
lenet5_regulizedtrnloss, lenet5_regulizedtrnacc = train(model=LeNet5_regulized_model, trn_loader=trainloader, device=device, criterion=criterionLeNet_regulized,
optimizer=optimizerLeNet_regulized,epoch=epoch,modelname="lenet_regulized")
lenet5_regulizedtstloss, lenet5_regulizedtstacc = test(model=LeNet5_regulized_model, tst_loader=testloader, device=device, criterion=criterionLeNet_regulized,modelname="lenet_regulized")
CustomMLPtrnloss, CustomMLPtrnacc = train(model=CustomMLP_model, trn_loader=trainloader, device=device,
criterion=criterionCustomMLP, optimizer=optimizerCustomMLP,epoch=epoch,modelname="custom")
CustomMLPtstloss, CustomMLPtstacc = test(model=CustomMLP_model, tst_loader=testloader, device=device, criterion=criterionCustomMLP,modelname="custom")
fig= plt.figure()
lossplt=fig.add_subplot(1, 2, 1)
plt.plot(range(epoch), lenet5trnloss, color='g', label='LeNet5 train loss')
plt.plot(range(epoch), lenet5_regulizedtrnloss,color='r' ,label='LeNet5_regulized train loss' )
plt.plot(range(epoch), CustomMLPtrnloss,color='b',label='Custom MLP train loss')
plt.legend(loc='upper right',bbox_to_anchor=(1.0, 1.0))
plt.xlabel('epoch (x100)')
plt.ylabel('loss')
plt.title('Loss')
accplt=fig.add_subplot(1, 2, 2)
plt.plot(range(epoch), lenet5trnacc,color='g' ,label='LeNet5 train accuracy' )
plt.plot(range(epoch), lenet5_regulizedtrnacc, color='r', label='LeNet5_regulized train loss')
plt.plot(range(epoch), CustomMLPtrnacc,color='b',label='Custom MLP train accuracy')
plt.legend(loc='upper right', bbox_to_anchor=(1.0, 1.0))
plt.xlabel('epoch (x100)')
plt.ylabel('acc')
plt.title('Accuracy')
#
# lenetplt=fig.add_subplot(2, 2, 3)
# plt.plot(range(int((trainloader.__len__())/100)), lenet5trnloss,color='g',label='train loss' )
# plt.plot(range(int((testloader .__len__())/100)), lenet5tstloss,color='r',label='test loss' )
# plt.plot(range(int((trainloader.__len__())/100)), lenet5trnacc,color='b' ,label='train accuracy')
# plt.plot(range(int((testloader .__len__())/100)), lenet5tstacc,color='m' ,label='test accuracy' )
# plt.legend(loc='upper right', bbox_to_anchor=(1.0, 1.0))
# plt.xlabel('epoch (x100)')
# plt.title('Loss and Accuracy of LeNet5')
# #
# # customplt=fig.add_subplot(2, 2, 4)
# # plt.plot(range(int((trainloader.__len__())/100)), CustomMLPtrnloss,color='g',label='train loss' )
# # plt.plot(range(int((testloader .__len__())/100)), CustomMLPtstloss,color='r',label='test loss' )
# # plt.plot(range(int((trainloader.__len__())/100)), CustomMLPtrnacc,color='b' ,label='train accuracy')
# # plt.plot(range(int((testloader .__len__())/100)), CustomMLPtstacc,color='m' ,label='test accuracy' )
# # plt.legend(loc='upper right', bbox_to_anchor=(1.0, 1.0))
# # plt.xlabel('epoch (x100)')
# # plt.title('Loss and Accuracy of Custom MLP')
plt.show()
plt.savefig('/fig.png')
if __name__ == '__main__':
main()
### MNIST WEB app with python - Flask http://hanwifi.iptime.org:9000/
### 19512062 young il han
### ccoltong1215@seoultech.ac.kr
### https://github.com/ccoltong1215/simple-lenet5-torch-mnist
| 41.86383
| 190
| 0.634275
|
2890c794bad8c5f8e6a540e5f6c96aad6fd0c504
| 18,162
|
py
|
Python
|
tests/collection.py
|
IvanMalison/invoke
|
322718d7f38ce04fc2bde947ba67ab4002f669b6
|
[
"BSD-2-Clause"
] | null | null | null |
tests/collection.py
|
IvanMalison/invoke
|
322718d7f38ce04fc2bde947ba67ab4002f669b6
|
[
"BSD-2-Clause"
] | null | null | null |
tests/collection.py
|
IvanMalison/invoke
|
322718d7f38ce04fc2bde947ba67ab4002f669b6
|
[
"BSD-2-Clause"
] | 1
|
2021-02-17T12:08:40.000Z
|
2021-02-17T12:08:40.000Z
|
import operator
from spec import Spec, eq_, ok_, raises, assert_raises
from invoke.collection import Collection
from invoke.tasks import task, Task
from invoke.vendor import six
from invoke.vendor.six.moves import reduce
from _util import load, support_path
@task
def _mytask(ctx):
six.print_("woo!")
def _func(ctx):
pass
class Collection_(Spec):
class init:
"__init__"
def can_accept_task_varargs(self):
"can accept tasks as *args"
@task
def task1(ctx):
pass
@task
def task2(ctx):
pass
c = Collection(task1, task2)
assert 'task1' in c
assert 'task2' in c
def can_accept_collections_as_varargs_too(self):
sub = Collection('sub')
ns = Collection(sub)
eq_(ns.collections['sub'], sub)
def kwargs_act_as_name_args_for_given_objects(self):
sub = Collection()
@task
def task1(ctx):
pass
ns = Collection(loltask=task1, notsub=sub)
eq_(ns['loltask'], task1)
eq_(ns.collections['notsub'], sub)
def initial_string_arg_acts_as_name(self):
sub = Collection('sub')
ns = Collection(sub)
eq_(ns.collections['sub'], sub)
def initial_string_arg_meshes_with_varargs_and_kwargs(self):
@task
def task1(ctx):
pass
@task
def task2(ctx):
pass
sub = Collection('sub')
ns = Collection('root', task1, sub, sometask=task2)
for x, y in (
(ns.name, 'root'),
(ns['task1'], task1),
(ns.collections['sub'], sub),
(ns['sometask'], task2),
):
eq_(x, y)
def accepts_load_path_kwarg(self):
eq_(Collection().loaded_from, None)
eq_(Collection(loaded_from='a/path').loaded_from, 'a/path')
class useful_special_methods:
def _meh(self):
@task
def task1(ctx):
pass
@task
def task2(ctx):
pass
return Collection('meh', task1=task1, task2=task2)
def setup(self):
self.c = self._meh()
def repr_(self):
"__repr__"
eq_(repr(self.c), "<Collection 'meh': task1, task2>")
def equality_should_be_useful(self):
eq_(self.c, self._meh())
class from_module:
def setup(self):
self.c = Collection.from_module(load('integration'))
class parameters:
def setup(self):
self.mod = load('integration')
self.fm = Collection.from_module
def name_override(self):
eq_(self.fm(self.mod).name, 'integration')
eq_(
self.fm(self.mod, name='not-integration').name,
'not-integration'
)
def inline_configuration(self):
# No configuration given, none gotten
eq_(self.fm(self.mod).configuration(), {})
# Config kwarg given is reflected when config obtained
eq_(
self.fm(self.mod, config={'foo': 'bar'}).configuration(),
{'foo': 'bar'}
)
def name_and_config_simultaneously(self):
# Test w/ posargs to enforce ordering, just for safety.
c = self.fm(self.mod, 'the name', {'the': 'config'})
eq_(c.name, 'the name')
eq_(c.configuration(), {'the': 'config'})
def adds_tasks(self):
assert 'print_foo' in self.c
def derives_collection_name_from_module_name(self):
eq_(self.c.name, 'integration')
def submodule_names_are_stripped_to_last_chunk(self):
with support_path():
from package import module
c = Collection.from_module(module)
eq_(module.__name__, 'package.module')
eq_(c.name, 'module')
assert 'mytask' in c # Sanity
def honors_explicit_collections(self):
coll = Collection.from_module(load('explicit_root'))
assert 'top_level' in coll.tasks
assert 'sub' in coll.collections
# The real key test
assert 'sub_task' not in coll.tasks
def allows_tasks_with_explicit_names_to_override_bound_name(self):
coll = Collection.from_module(load('subcollection_task_name'))
assert 'explicit_name' in coll.tasks # not 'implicit_name'
def returns_unique_Collection_objects_for_same_input_module(self):
# Ignoring self.c for now, just in case it changes later.
# First, a module with no root NS
mod = load('integration')
c1 = Collection.from_module(mod)
c2 = Collection.from_module(mod)
assert c1 is not c2
# Now one *with* a root NS (which was previously buggy)
mod2 = load('explicit_root')
c3 = Collection.from_module(mod2)
c4 = Collection.from_module(mod2)
assert c3 is not c4
class explicit_root_ns:
def setup(self):
mod = load('explicit_root')
mod.ns.configure({
'key': 'builtin',
'otherkey': 'yup',
'subconfig': {'mykey': 'myvalue'}
})
mod.ns.name = 'builtin_name'
self.unchanged = Collection.from_module(mod)
self.changed = Collection.from_module(
mod,
name='override_name',
config={
'key': 'override',
'subconfig': {'myotherkey': 'myothervalue'}
}
)
def inline_config_with_root_namespaces_overrides_builtin(self):
eq_(self.unchanged.configuration()['key'], 'builtin')
eq_(self.changed.configuration()['key'], 'override')
def inline_config_overrides_via_merge_not_replacement(self):
ok_('otherkey' in self.changed.configuration())
def config_override_merges_recursively(self):
eq_(
self.changed.configuration()['subconfig']['mykey'],
'myvalue'
)
def inline_name_overrides_root_namespace_object_name(self):
eq_(self.unchanged.name, 'builtin_name')
eq_(self.changed.name, 'override_name')
def root_namespace_object_name_overrides_module_name(self):
# Duplicates part of previous test for explicitness' sake.
# I.e. proves that the name doesn't end up 'explicit_root'.
eq_(self.unchanged.name, 'builtin_name')
class add_task:
def setup(self):
self.c = Collection()
def associates_given_callable_with_given_name(self):
self.c.add_task(_mytask, 'foo')
eq_(self.c['foo'], _mytask)
def uses_function_name_as_implicit_name(self):
self.c.add_task(_mytask)
assert '_mytask' in self.c
def prefers_name_kwarg_over_task_name_attr(self):
self.c.add_task(Task(_func, name='notfunc'), name='yesfunc')
assert 'yesfunc' in self.c
assert 'notfunc' not in self.c
def prefers_task_name_attr_over_function_name(self):
self.c.add_task(Task(_func, name='notfunc'))
assert 'notfunc' in self.c
assert '_func' not in self.c
@raises(ValueError)
def raises_ValueError_if_no_name_found(self):
# Can't use a lambda here as they are technically real functions.
class Callable(object):
def __call__(self):
pass
self.c.add_task(Task(Callable()))
@raises(ValueError)
def raises_ValueError_on_multiple_defaults(self):
t1 = Task(_func, default=True)
t2 = Task(_func, default=True)
self.c.add_task(t1, 'foo')
self.c.add_task(t2, 'bar')
@raises(ValueError)
def raises_ValueError_if_task_added_mirrors_subcollection_name(self):
self.c.add_collection(Collection('sub'))
self.c.add_task(_mytask, 'sub')
def allows_specifying_task_defaultness(self):
self.c.add_task(_mytask, default=True)
eq_(self.c.default, '_mytask')
def specifying_default_False_overrides_task_setting(self):
@task(default=True)
def its_me(ctx):
pass
self.c.add_task(its_me, default=False)
eq_(self.c.default, None)
class add_collection:
def setup(self):
self.c = Collection()
def adds_collection_as_subcollection_of_self(self):
c2 = Collection('foo')
self.c.add_collection(c2)
assert 'foo' in self.c.collections
def can_take_module_objects(self):
self.c.add_collection(load('integration'))
assert 'integration' in self.c.collections
@raises(ValueError)
def raises_ValueError_if_collection_without_name(self):
# Aka non-root collections must either have an explicit name given
# via kwarg, have a name attribute set, or be a module with
# __name__ defined.
root = Collection()
sub = Collection()
root.add_collection(sub)
@raises(ValueError)
def raises_ValueError_if_collection_named_same_as_task(self):
self.c.add_task(_mytask, 'sub')
self.c.add_collection(Collection('sub'))
class getitem:
"__getitem__"
def setup(self):
self.c = Collection()
def finds_own_tasks_by_name(self):
# TODO: duplicates an add_task test above, fix?
self.c.add_task(_mytask, 'foo')
eq_(self.c['foo'], _mytask)
def finds_subcollection_tasks_by_dotted_name(self):
sub = Collection('sub')
sub.add_task(_mytask)
self.c.add_collection(sub)
eq_(self.c['sub._mytask'], _mytask)
def honors_aliases_in_own_tasks(self):
t = Task(_func, aliases=['bar'])
self.c.add_task(t, 'foo')
eq_(self.c['bar'], t)
def honors_subcollection_task_aliases(self):
self.c.add_collection(load('decorator'))
assert 'decorator.bar' in self.c
def honors_own_default_task_with_no_args(self):
t = Task(_func, default=True)
self.c.add_task(t)
eq_(self.c[''], t)
def honors_subcollection_default_tasks_on_subcollection_name(self):
sub = Collection.from_module(load('decorator'))
self.c.add_collection(sub)
# Sanity
assert self.c['decorator.biz'] is sub['biz']
# Real test
assert self.c['decorator'] is self.c['decorator.biz']
@raises(ValueError)
def raises_ValueError_for_no_name_and_no_default(self):
self.c['']
@raises(ValueError)
def ValueError_for_empty_subcol_task_name_and_no_default(self):
self.c.add_collection(Collection('whatever'))
self.c['whatever']
class to_contexts:
def setup(self):
@task
def mytask(ctx, text, boolean=False, number=5):
six.print_(text)
@task(aliases=['mytask27'])
def mytask2(ctx):
pass
@task(aliases=['othertask'], default=True)
def subtask(ctx):
pass
sub = Collection('sub', subtask)
self.c = Collection(mytask, mytask2, sub)
self.contexts = self.c.to_contexts()
alias_tups = [list(x.aliases) for x in self.contexts]
self.aliases = reduce(operator.add, alias_tups, [])
# Focus on 'mytask' as it has the more interesting sig
self.context = [x for x in self.contexts if x.name == 'mytask'][0]
def returns_iterable_of_Contexts_corresponding_to_tasks(self):
eq_(self.context.name, 'mytask')
eq_(len(self.contexts), 3)
def allows_flaglike_access_via_flags(self):
assert '--text' in self.context.flags
def positional_arglist_preserves_order_given(self):
@task(positional=('second', 'first'))
def mytask(ctx, first, second, third):
pass
c = Collection()
c.add_task(mytask)
ctx = c.to_contexts()[0]
eq_(ctx.positional_args, [ctx.args['second'], ctx.args['first']])
def exposes_namespaced_task_names(self):
assert 'sub.subtask' in [x.name for x in self.contexts]
def exposes_namespaced_task_aliases(self):
assert 'sub.othertask' in self.aliases
def exposes_subcollection_default_tasks(self):
assert 'sub' in self.aliases
def exposes_aliases(self):
assert 'mytask27' in self.aliases
class task_names:
def setup(self):
self.c = Collection.from_module(load('explicit_root'))
def returns_all_task_names_including_subtasks(self):
eq_(
set(self.c.task_names.keys()),
set(['top_level', 'sub.sub_task'])
)
def includes_aliases_and_defaults_as_values(self):
names = self.c.task_names
eq_(names['top_level'], ['othertop'])
eq_(names['sub.sub_task'], ['sub.othersub', 'sub'])
class configuration:
"Configuration methods"
def setup(self):
self.root = Collection()
self.task = Task(_func, name='task')
def basic_set_and_get(self):
self.root.configure({'foo': 'bar'})
eq_(self.root.configuration(), {'foo': 'bar'})
def configure_performs_merging(self):
self.root.configure({'foo': 'bar'})
eq_(self.root.configuration()['foo'], 'bar')
self.root.configure({'biz': 'baz'})
eq_(set(self.root.configuration().keys()), set(['foo', 'biz']))
def configure_merging_is_recursive_for_nested_dicts(self):
self.root.configure({'foo': 'bar', 'biz': {'baz': 'boz'}})
self.root.configure({'biz': {'otherbaz': 'otherboz'}})
c = self.root.configuration()
eq_(c['biz']['baz'], 'boz')
eq_(c['biz']['otherbaz'], 'otherboz')
def configure_allows_overwriting(self):
self.root.configure({'foo': 'one'})
eq_(self.root.configuration()['foo'], 'one')
self.root.configure({'foo': 'two'})
eq_(self.root.configuration()['foo'], 'two')
def call_returns_dict(self):
eq_(self.root.configuration(), {})
self.root.configure({'foo': 'bar'})
eq_(self.root.configuration(), {'foo': 'bar'})
def access_merges_from_subcollections(self):
inner = Collection('inner', self.task)
inner.configure({'foo': 'bar'})
self.root.configure({'biz': 'baz'})
# With no inner collection
eq_(set(self.root.configuration().keys()), set(['biz']))
# With inner collection
self.root.add_collection(inner)
eq_(
set(self.root.configuration('inner.task').keys()),
set(['foo', 'biz'])
)
def parents_overwrite_children_in_path(self):
inner = Collection('inner', self.task)
inner.configure({'foo': 'inner'})
self.root.add_collection(inner)
# Before updating root collection's config, reflects inner
eq_(self.root.configuration('inner.task')['foo'], 'inner')
self.root.configure({'foo': 'outer'})
# After, reflects outer (since that now overrides)
eq_(self.root.configuration('inner.task')['foo'], 'outer')
def sibling_subcollections_ignored(self):
inner = Collection('inner', self.task)
inner.configure({'foo': 'hi there'})
inner2 = Collection('inner2', Task(_func, name='task2'))
inner2.configure({'foo': 'nope'})
root = Collection(inner, inner2)
eq_(root.configuration('inner.task')['foo'], 'hi there')
eq_(root.configuration('inner2.task2')['foo'], 'nope')
def subcollection_paths_may_be_dotted(self):
leaf = Collection('leaf', self.task)
leaf.configure({'key': 'leaf-value'})
middle = Collection('middle', leaf)
root = Collection('root', middle)
eq_(root.configuration('middle.leaf.task'), {'key': 'leaf-value'})
def invalid_subcollection_paths_result_in_KeyError(self):
# Straight up invalid
assert_raises(KeyError,
Collection('meh').configuration,
'nope.task'
)
# Exists but wrong level (should be 'root.task', not just
# 'task')
inner = Collection('inner', self.task)
assert_raises(KeyError,
Collection('root', inner).configuration, 'task')
def keys_dont_have_to_exist_in_full_path(self):
# Kinda duplicates earlier stuff; meh
# Key only stored on leaf
leaf = Collection('leaf', self.task)
leaf.configure({'key': 'leaf-value'})
middle = Collection('middle', leaf)
root = Collection('root', middle)
eq_(root.configuration('middle.leaf.task'), {'key': 'leaf-value'})
# Key stored on mid + leaf but not root
middle.configure({'key': 'whoa'})
eq_(root.configuration('middle.leaf.task'), {'key': 'whoa'})
| 36.989817
| 78
| 0.557483
|
d4dba390e797c7f415cfe225c68975bd26a32df3
| 14,549
|
py
|
Python
|
rastervision/protos/label_source_pb2.py
|
AirbusAerial/raster-vision
|
cfa7826169392e497fb57a540eb952fc6cee3a98
|
[
"Apache-2.0"
] | 2
|
2019-04-17T13:04:23.000Z
|
2020-10-04T10:28:27.000Z
|
rastervision/protos/label_source_pb2.py
|
Yochengliu/raster-vision
|
f5badc387df86ce02d84e0e274a08026dbf65bd6
|
[
"Apache-2.0"
] | null | null | null |
rastervision/protos/label_source_pb2.py
|
Yochengliu/raster-vision
|
f5badc387df86ce02d84e0e274a08026dbf65bd6
|
[
"Apache-2.0"
] | null | null | null |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: rastervision/protos/label_source.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from rastervision.protos import raster_source_pb2 as rastervision_dot_protos_dot_raster__source__pb2
from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2
from rastervision.protos import class_item_pb2 as rastervision_dot_protos_dot_class__item__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='rastervision/protos/label_source.proto',
package='rv.protos',
syntax='proto2',
serialized_pb=_b('\n&rastervision/protos/label_source.proto\x12\trv.protos\x1a\'rastervision/protos/raster_source.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a$rastervision/protos/class_item.proto\"\xb1\x06\n\x11LabelSourceConfig\x12\x13\n\x0bsource_type\x18\x01 \x02(\t\x12\x64\n\x1fobject_detection_geojson_source\x18\x02 \x01(\x0b\x32\x39.rv.protos.LabelSourceConfig.ObjectDetectionGeoJSONSourceH\x00\x12j\n\"chip_classification_geojson_source\x18\x03 \x01(\x0b\x32<.rv.protos.LabelSourceConfig.ChipClassificationGeoJSONSourceH\x00\x12l\n#semantic_segmentation_raster_source\x18\x04 \x01(\x0b\x32=.rv.protos.LabelSourceConfig.SemanticSegmentationRasterSourceH\x00\x12\x30\n\rcustom_config\x18\x05 \x01(\x0b\x32\x17.google.protobuf.StructH\x00\x1a+\n\x1cObjectDetectionGeoJSONSource\x12\x0b\n\x03uri\x18\x01 \x02(\t\x1a\xcd\x01\n\x1f\x43hipClassificationGeoJSONSource\x12\x0b\n\x03uri\x18\x01 \x02(\t\x12\x12\n\nioa_thresh\x18\x02 \x01(\x02\x12\"\n\x1ause_intersection_over_cell\x18\x03 \x01(\x08\x12\x19\n\x11pick_min_class_id\x18\x04 \x01(\x08\x12\x1b\n\x13\x62\x61\x63kground_class_id\x18\x05 \x01(\x05\x12\x11\n\tcell_size\x18\x06 \x01(\x05\x12\x1a\n\x0binfer_cells\x18\x07 \x01(\x08:\x05\x66\x61lse\x1a\x80\x01\n SemanticSegmentationRasterSource\x12-\n\x06source\x18\x01 \x02(\x0b\x32\x1d.rv.protos.RasterSourceConfig\x12-\n\x0frgb_class_items\x18\x02 \x03(\x0b\x32\x14.rv.protos.ClassItemB\x15\n\x13label_source_config')
,
dependencies=[rastervision_dot_protos_dot_raster__source__pb2.DESCRIPTOR,google_dot_protobuf_dot_struct__pb2.DESCRIPTOR,rastervision_dot_protos_dot_class__item__pb2.DESCRIPTOR,])
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
_LABELSOURCECONFIG_OBJECTDETECTIONGEOJSONSOURCE = _descriptor.Descriptor(
name='ObjectDetectionGeoJSONSource',
full_name='rv.protos.LabelSourceConfig.ObjectDetectionGeoJSONSource',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='uri', full_name='rv.protos.LabelSourceConfig.ObjectDetectionGeoJSONSource.uri', index=0,
number=1, type=9, cpp_type=9, label=2,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=575,
serialized_end=618,
)
_LABELSOURCECONFIG_CHIPCLASSIFICATIONGEOJSONSOURCE = _descriptor.Descriptor(
name='ChipClassificationGeoJSONSource',
full_name='rv.protos.LabelSourceConfig.ChipClassificationGeoJSONSource',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='uri', full_name='rv.protos.LabelSourceConfig.ChipClassificationGeoJSONSource.uri', index=0,
number=1, type=9, cpp_type=9, label=2,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='ioa_thresh', full_name='rv.protos.LabelSourceConfig.ChipClassificationGeoJSONSource.ioa_thresh', index=1,
number=2, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='use_intersection_over_cell', full_name='rv.protos.LabelSourceConfig.ChipClassificationGeoJSONSource.use_intersection_over_cell', index=2,
number=3, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='pick_min_class_id', full_name='rv.protos.LabelSourceConfig.ChipClassificationGeoJSONSource.pick_min_class_id', index=3,
number=4, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='background_class_id', full_name='rv.protos.LabelSourceConfig.ChipClassificationGeoJSONSource.background_class_id', index=4,
number=5, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='cell_size', full_name='rv.protos.LabelSourceConfig.ChipClassificationGeoJSONSource.cell_size', index=5,
number=6, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='infer_cells', full_name='rv.protos.LabelSourceConfig.ChipClassificationGeoJSONSource.infer_cells', index=6,
number=7, type=8, cpp_type=7, label=1,
has_default_value=True, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=621,
serialized_end=826,
)
_LABELSOURCECONFIG_SEMANTICSEGMENTATIONRASTERSOURCE = _descriptor.Descriptor(
name='SemanticSegmentationRasterSource',
full_name='rv.protos.LabelSourceConfig.SemanticSegmentationRasterSource',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='source', full_name='rv.protos.LabelSourceConfig.SemanticSegmentationRasterSource.source', index=0,
number=1, type=11, cpp_type=10, label=2,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='rgb_class_items', full_name='rv.protos.LabelSourceConfig.SemanticSegmentationRasterSource.rgb_class_items', index=1,
number=2, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=829,
serialized_end=957,
)
_LABELSOURCECONFIG = _descriptor.Descriptor(
name='LabelSourceConfig',
full_name='rv.protos.LabelSourceConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='source_type', full_name='rv.protos.LabelSourceConfig.source_type', index=0,
number=1, type=9, cpp_type=9, label=2,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='object_detection_geojson_source', full_name='rv.protos.LabelSourceConfig.object_detection_geojson_source', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='chip_classification_geojson_source', full_name='rv.protos.LabelSourceConfig.chip_classification_geojson_source', index=2,
number=3, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='semantic_segmentation_raster_source', full_name='rv.protos.LabelSourceConfig.semantic_segmentation_raster_source', index=3,
number=4, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='custom_config', full_name='rv.protos.LabelSourceConfig.custom_config', index=4,
number=5, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[_LABELSOURCECONFIG_OBJECTDETECTIONGEOJSONSOURCE, _LABELSOURCECONFIG_CHIPCLASSIFICATIONGEOJSONSOURCE, _LABELSOURCECONFIG_SEMANTICSEGMENTATIONRASTERSOURCE, ],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
_descriptor.OneofDescriptor(
name='label_source_config', full_name='rv.protos.LabelSourceConfig.label_source_config',
index=0, containing_type=None, fields=[]),
],
serialized_start=163,
serialized_end=980,
)
_LABELSOURCECONFIG_OBJECTDETECTIONGEOJSONSOURCE.containing_type = _LABELSOURCECONFIG
_LABELSOURCECONFIG_CHIPCLASSIFICATIONGEOJSONSOURCE.containing_type = _LABELSOURCECONFIG
_LABELSOURCECONFIG_SEMANTICSEGMENTATIONRASTERSOURCE.fields_by_name['source'].message_type = rastervision_dot_protos_dot_raster__source__pb2._RASTERSOURCECONFIG
_LABELSOURCECONFIG_SEMANTICSEGMENTATIONRASTERSOURCE.fields_by_name['rgb_class_items'].message_type = rastervision_dot_protos_dot_class__item__pb2._CLASSITEM
_LABELSOURCECONFIG_SEMANTICSEGMENTATIONRASTERSOURCE.containing_type = _LABELSOURCECONFIG
_LABELSOURCECONFIG.fields_by_name['object_detection_geojson_source'].message_type = _LABELSOURCECONFIG_OBJECTDETECTIONGEOJSONSOURCE
_LABELSOURCECONFIG.fields_by_name['chip_classification_geojson_source'].message_type = _LABELSOURCECONFIG_CHIPCLASSIFICATIONGEOJSONSOURCE
_LABELSOURCECONFIG.fields_by_name['semantic_segmentation_raster_source'].message_type = _LABELSOURCECONFIG_SEMANTICSEGMENTATIONRASTERSOURCE
_LABELSOURCECONFIG.fields_by_name['custom_config'].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT
_LABELSOURCECONFIG.oneofs_by_name['label_source_config'].fields.append(
_LABELSOURCECONFIG.fields_by_name['object_detection_geojson_source'])
_LABELSOURCECONFIG.fields_by_name['object_detection_geojson_source'].containing_oneof = _LABELSOURCECONFIG.oneofs_by_name['label_source_config']
_LABELSOURCECONFIG.oneofs_by_name['label_source_config'].fields.append(
_LABELSOURCECONFIG.fields_by_name['chip_classification_geojson_source'])
_LABELSOURCECONFIG.fields_by_name['chip_classification_geojson_source'].containing_oneof = _LABELSOURCECONFIG.oneofs_by_name['label_source_config']
_LABELSOURCECONFIG.oneofs_by_name['label_source_config'].fields.append(
_LABELSOURCECONFIG.fields_by_name['semantic_segmentation_raster_source'])
_LABELSOURCECONFIG.fields_by_name['semantic_segmentation_raster_source'].containing_oneof = _LABELSOURCECONFIG.oneofs_by_name['label_source_config']
_LABELSOURCECONFIG.oneofs_by_name['label_source_config'].fields.append(
_LABELSOURCECONFIG.fields_by_name['custom_config'])
_LABELSOURCECONFIG.fields_by_name['custom_config'].containing_oneof = _LABELSOURCECONFIG.oneofs_by_name['label_source_config']
DESCRIPTOR.message_types_by_name['LabelSourceConfig'] = _LABELSOURCECONFIG
LabelSourceConfig = _reflection.GeneratedProtocolMessageType('LabelSourceConfig', (_message.Message,), dict(
ObjectDetectionGeoJSONSource = _reflection.GeneratedProtocolMessageType('ObjectDetectionGeoJSONSource', (_message.Message,), dict(
DESCRIPTOR = _LABELSOURCECONFIG_OBJECTDETECTIONGEOJSONSOURCE,
__module__ = 'rastervision.protos.label_source_pb2'
# @@protoc_insertion_point(class_scope:rv.protos.LabelSourceConfig.ObjectDetectionGeoJSONSource)
))
,
ChipClassificationGeoJSONSource = _reflection.GeneratedProtocolMessageType('ChipClassificationGeoJSONSource', (_message.Message,), dict(
DESCRIPTOR = _LABELSOURCECONFIG_CHIPCLASSIFICATIONGEOJSONSOURCE,
__module__ = 'rastervision.protos.label_source_pb2'
# @@protoc_insertion_point(class_scope:rv.protos.LabelSourceConfig.ChipClassificationGeoJSONSource)
))
,
SemanticSegmentationRasterSource = _reflection.GeneratedProtocolMessageType('SemanticSegmentationRasterSource', (_message.Message,), dict(
DESCRIPTOR = _LABELSOURCECONFIG_SEMANTICSEGMENTATIONRASTERSOURCE,
__module__ = 'rastervision.protos.label_source_pb2'
# @@protoc_insertion_point(class_scope:rv.protos.LabelSourceConfig.SemanticSegmentationRasterSource)
))
,
DESCRIPTOR = _LABELSOURCECONFIG,
__module__ = 'rastervision.protos.label_source_pb2'
# @@protoc_insertion_point(class_scope:rv.protos.LabelSourceConfig)
))
_sym_db.RegisterMessage(LabelSourceConfig)
_sym_db.RegisterMessage(LabelSourceConfig.ObjectDetectionGeoJSONSource)
_sym_db.RegisterMessage(LabelSourceConfig.ChipClassificationGeoJSONSource)
_sym_db.RegisterMessage(LabelSourceConfig.SemanticSegmentationRasterSource)
# @@protoc_insertion_point(module_scope)
| 50.342561
| 1,430
| 0.797374
|
fe8ee41f200ccefb5af350b34fe49885e69e0f7e
| 56
|
py
|
Python
|
keycloak_api_client/exceptions.py
|
masterplandev/python-keycloak-api-client
|
60406dace35a4c9b2a0fd149823c09fd993d5b8b
|
[
"MIT"
] | 1
|
2021-07-16T11:40:03.000Z
|
2021-07-16T11:40:03.000Z
|
keycloak_api_client/exceptions.py
|
masterplandev/python-keycloak-api-client
|
60406dace35a4c9b2a0fd149823c09fd993d5b8b
|
[
"MIT"
] | 2
|
2021-07-29T14:42:15.000Z
|
2021-11-25T16:35:39.000Z
|
keycloak_api_client/exceptions.py
|
masterplandev/python-keycloak-api-client
|
60406dace35a4c9b2a0fd149823c09fd993d5b8b
|
[
"MIT"
] | null | null | null |
class KeycloakApiClientException(Exception):
pass
| 11.2
| 44
| 0.785714
|
7e81022bce5e8a5f29f569464336a5addd759631
| 6,175
|
py
|
Python
|
data/prepare_data.py
|
huitangtang/DisClusterDA
|
55268343623a119d058e07f92714f96bdb806463
|
[
"MIT"
] | 4
|
2020-09-02T14:51:24.000Z
|
2021-12-26T18:59:04.000Z
|
data/prepare_data.py
|
huitangtang/DisClusterDA
|
55268343623a119d058e07f92714f96bdb806463
|
[
"MIT"
] | 1
|
2022-03-15T15:27:17.000Z
|
2022-03-15T15:27:17.000Z
|
data/prepare_data.py
|
huitangtang/DisClusterDA
|
55268343623a119d058e07f92714f96bdb806463
|
[
"MIT"
] | null | null | null |
import os
import shutil
#import sys
#sys.path.append("..")
import torch
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torch.nn.functional as F
from utils.folder import ImageFolder
import numpy as np
import cv2
def generate_dataloader(args):
# data loading
traindir = os.path.join(args.data_path_source, args.src)
traindir_t = os.path.join(args.data_path_target_tr, args.tar_tr)
valdir = os.path.join(args.data_path_target_te, args.tar_te)
classes = os.listdir(traindir)
classes.sort()
ins_num_for_each_cls_src = torch.cuda.FloatTensor(args.num_classes)
for i,c in enumerate(classes):
ins_num_for_each_cls_src[i] = len(os.listdir(os.path.join(traindir, c)))
if not os.path.isdir(traindir):
raise ValueError ('The required data path does not exist!')
if args.no_da:
# transformation on the training data during training
data_transform_train = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
# transformation on the duplicated data during training
data_transform_train_dup = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Lambda(lambda x: _random_affine_augmentation(x)),
transforms.Lambda(lambda x: _gaussian_blur(x, sigma=args.sigma)),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
# transformation on the grayscale data during training
data_transform_train_gray = transforms.Compose([
transforms.Grayscale(3),
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
# transformation on the test data during test
data_transform_test = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
else:
# transformation on the training data during training
data_transform_train = transforms.Compose([
transforms.Resize(256),
transforms.RandomCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
# transformation on the duplicated data during training
data_transform_train_dup = transforms.Compose([
transforms.Resize(256),
transforms.RandomCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Lambda(lambda x: _random_affine_augmentation(x)),
transforms.Lambda(lambda x: _gaussian_blur(x, sigma=args.sigma)),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
# transformation on the grayscale data during training
data_transform_train_gray = transforms.Compose([
transforms.Grayscale(3),
transforms.Resize(256),
transforms.RandomCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
# transformation on the test data during test
data_transform_test = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
source_train_dataset = ImageFolder(root=traindir, transform=data_transform_train)
source_test_dataset = datasets.ImageFolder(root=traindir, transform=data_transform_test)
if args.aug_tar_agree and (not args.gray_tar_agree):
target_train_dataset = ImageFolder(root=traindir_t, transform=data_transform_train, transform_aug=data_transform_train_dup)
elif args.gray_tar_agree and (not args.aug_tar_agree):
target_train_dataset = ImageFolder(root=traindir_t, transform=data_transform_train, transform_gray=data_transform_train_gray)
elif args.aug_tar_agree and args.gray_tar_agree:
target_train_dataset = ImageFolder(root=traindir_t, transform=data_transform_train, transform_aug=data_transform_train_dup, transform_gray=data_transform_train_gray)
else:
target_train_dataset = ImageFolder(root=traindir_t, transform=data_transform_train)
target_test_dataset = ImageFolder(root=valdir, transform=data_transform_test)
source_train_loader = torch.utils.data.DataLoader(
source_train_dataset, batch_size=args.batch_size, shuffle=True,
num_workers=args.workers, pin_memory=True, sampler=None, drop_last=True
)
source_test_loader = torch.utils.data.DataLoader(
source_test_dataset, batch_size=63, shuffle=False,
num_workers=args.workers, pin_memory=True
)
target_train_loader = torch.utils.data.DataLoader(
target_train_dataset, batch_size=args.batch_size, shuffle=True,
num_workers=args.workers, pin_memory=True, sampler=None, drop_last=True
)
target_test_loader = torch.utils.data.DataLoader(
target_test_dataset, batch_size=63, shuffle=False,
num_workers=args.workers, pin_memory=True
)
return source_train_loader, target_train_loader, target_test_loader, source_test_loader
def _random_affine_augmentation(x):
M = np.float32([[1 + np.random.normal(0.0, 0.1), np.random.normal(0.0, 0.1), 0],
[np.random.normal(0.0, 0.1), 1 + np.random.normal(0.0, 0.1), 0]])
rows, cols = x.shape[1:3]
dst = cv2.warpAffine(np.transpose(x.numpy(), [1, 2, 0]), M, (cols,rows))
dst = np.transpose(dst, [2, 0, 1])
return torch.from_numpy(dst)
def _gaussian_blur(x, sigma=0.1):
ksize = int(sigma + 0.5) * 8 + 1
dst = cv2.GaussianBlur(x.numpy(), (ksize, ksize), sigma)
return torch.from_numpy(dst)
| 44.42446
| 173
| 0.682429
|
fbbf428102feb1d0b3a75d3457afb77bb90616ba
| 4,872
|
py
|
Python
|
detail_test.py
|
hukish/P_Locker
|
451c00185e6cdd91f607fa4460a05dd8e2d6fd68
|
[
"MIT"
] | null | null | null |
detail_test.py
|
hukish/P_Locker
|
451c00185e6cdd91f607fa4460a05dd8e2d6fd68
|
[
"MIT"
] | null | null | null |
detail_test.py
|
hukish/P_Locker
|
451c00185e6cdd91f607fa4460a05dd8e2d6fd68
|
[
"MIT"
] | null | null | null |
import unittest # Importing the unittest module
import pyperclip
from detail import Detail # Importing the detail class
class TestDetail(unittest.TestCase):
# import pyperclip
'''
Test class that defines test cases for the detail class behaviours.
Args:
unittest.TestCase: TestCase class that helps in creating test cases
'''
# Items up here .......
def setUp(self):
'''
Set up method to run before each test cases.
'''
self.new_detail = Detail(
"xyz", "xyz", "2222222222", "xyz@user.com") # create detail object
def test_init(self):
'''
test_init test case to test if the object is initialized properly
'''
self.assertEqual(self.new_detail.user_name, "xyz")
self.assertEqual(self.new_detail.user_name, "xyz")
self.assertEqual(self.new_detail.account_password, "2222222222")
self.assertEqual(self.new_detail.email, "xyz@user.com")
def test_save_detail(self):
'''
test_save_detail test case to test if the detail object is saved into
the detail list
'''
self.new_detail.save_detail() # saving the new detail
self.assertEqual(len(Detail.detail_list), 1)
# def test_sum():
# assert sum([1, 2, 3]) == 6, "Should be 6"
#
# test_sum()
# print("Everything passed")
# def test_save_multiple_detail(self):
# '''
# test_save_multiple_detail to check if we can save multiple detail
# objects to our detail_list
# '''
# self.new_detail.save_detail()
# test_detail = Detail(
# "Test", "user", "2222222222", "xyz@user.com") # new detail
# test_detail.save_detail()
# self.assertEqual(len(Detail.detail_list), 2)
# Items up here...
# def test_save_multiple_detail(self):
# '''
# test_save_multiple_detail to check if we can save multiple detail
# objects to our detail_list
# '''
# self.new_detail.save_detail()
# test_detail = Detail(
# "Test", "user", "2222222222", "xyz@user.com") # new detail
# test_detail.save_detail()
# self.assertEqual(len(Detail.detail_list), 2)
# setup and class creation up HERE
def tearDown(self):
"""
tearDown method that does clean up after each test case has runs
"""
Detail.detail_list = []
# Other test cases HERE
def test_save_multiple_detail(self):
"""
test_save_multiple_detail to check if we can save multiple detail objects
"""
self.new_detail.save_detail()
test_detail = Detail("Test", "user", "2222222222",
"xyz@user.com") # new detail_list
test_detail.save_detail()
self.assertEqual(len(Detail.detail_list), 2)
# More tests above
def test_delete_detail(self):
'''
test_delete_detail to test if we can remove a detail from our detail list
'''
self.new_detail.save_detail()
test_detail = Detail(
"Test", "user", "22222222222", "xyz@user.com") # new detail
test_detail.save_detail()
self.new_detail.delete_detail() # Deleting a detail object
self.assertEqual(len(Detail.detail_list), 1)
def test_find_detail_by_password(self):
'''
test to check if we can find a detail by account password and display information
'''
self.new_detail.save_detail()
test_detail = Detail("Test", "user", "2222222222",
"xyz@user.com") # new detail
test_detail.save_detail()
found_detail = Detail.find_by_password("2222222222")
self.assertEqual(found_detail.email, test_detail.email)
def test_detail_exists(self):
'''
test to check if we can return a Boolean if we cannot find the detail.
'''
self.new_detail.save_detail()
test_detail = Detail("Test", "user", "2222222222",
"xyz@user.com") # new detail
test_detail.save_detail()
detail_exists = Detail.detail_exist("2222222222")
self.assertTrue(detail_exists)
def test_display_all_details(self):
'''
method that returns a list of all details saved
'''
self.assertEqual(Detail.display_details(), Detail.detail_list)
def test_copy_email(self):
'''
Test to confirm that we are copying the email address from a found detail
'''
self.new_detail.save_detail()
Detail.copy_email("2222222222")
self.assertEqual(self.new_detail.email, pyperclip.paste())
if __name__ == '__main__':
unittest.main()
| 31.843137
| 89
| 0.597906
|
c958511c4228e9eb382572223b35fca7b6ad7770
| 1,730
|
py
|
Python
|
planning_and_simulation_modules/Tjulia/checks/JuliaOutputChecker.py
|
Planheat/Planheat-Tool
|
9764fcb86d3898b232c4cc333dab75ebe41cd421
|
[
"MIT"
] | 2
|
2020-04-07T03:43:33.000Z
|
2021-03-23T13:17:42.000Z
|
planning_and_simulation_modules/Tjulia/checks/JuliaOutputChecker.py
|
Planheat/Planheat-Tool
|
9764fcb86d3898b232c4cc333dab75ebe41cd421
|
[
"MIT"
] | 1
|
2020-07-20T09:56:13.000Z
|
2020-07-22T10:26:06.000Z
|
planning_and_simulation_modules/Tjulia/checks/JuliaOutputChecker.py
|
Planheat/Planheat-Tool
|
9764fcb86d3898b232c4cc333dab75ebe41cd421
|
[
"MIT"
] | 1
|
2020-07-20T09:40:15.000Z
|
2020-07-20T09:40:15.000Z
|
import os
import os.path
from .JuliaErrorVisualizer import JuliaErrorVisualizer
class JuliaOutputChecker:
def __init__(self, dr):
self.work_directory = dr
self.file_starts_string = "Result_"
self.file_ends_string = ".csv"
self.h8760 = 8760
self.report = {}
self.REPORT_ERROR_NOT_FLOAT = "CAN'T_CONVERT_TO_FLOAT"
self.REPORT_ERROR_NOT_A_NUMBER = "CONTENT IS Nan"
def check(self):
if not os.path.isdir(self.work_directory):
return
for f in os.listdir(self.work_directory):
file = os.path.join(self.work_directory, f)
if os.path.isfile(file):
if str(f).startswith(self.file_starts_string) and str(f).endswith(self.file_ends_string):
with open(file, "r") as fr:
for i in range(self.h8760):
line = fr.readline()
try:
line = float(line)
except:
self.add_to_report(f, self.REPORT_ERROR_NOT_FLOAT)
break
if not line == line:
self.add_to_report(f, self.REPORT_ERROR_NOT_A_NUMBER)
break
def visualize(self):
julia_error_visualizer = JuliaErrorVisualizer(self.report)
julia_error_visualizer.visualize()
def add_to_report(self, file, error):
self.report[str(file)] = error
def clear_report(self):
self.report = {}
def get_report(self):
return self.report
def set_folder(self, folder):
self.work_directory = folder
| 32.037037
| 105
| 0.547977
|
80d7333a07ab6cbc513d92e5bca4f131285935d4
| 55,646
|
py
|
Python
|
tests/test_datasets/test_dataset_functions.py
|
hp2500/openml-python
|
62cc534cd18e6e011a88a83816fec95a90399a9b
|
[
"BSD-3-Clause"
] | 1
|
2019-09-02T00:28:26.000Z
|
2019-09-02T00:28:26.000Z
|
tests/test_datasets/test_dataset_functions.py
|
hp2500/openml-python
|
62cc534cd18e6e011a88a83816fec95a90399a9b
|
[
"BSD-3-Clause"
] | null | null | null |
tests/test_datasets/test_dataset_functions.py
|
hp2500/openml-python
|
62cc534cd18e6e011a88a83816fec95a90399a9b
|
[
"BSD-3-Clause"
] | 1
|
2019-09-02T00:29:32.000Z
|
2019-09-02T00:29:32.000Z
|
import os
import random
from itertools import product
from unittest import mock
import arff
import pytest
import numpy as np
import pandas as pd
import scipy.sparse
from oslo_concurrency import lockutils
import openml
from openml import OpenMLDataset
from openml.exceptions import OpenMLCacheException, OpenMLHashException, \
OpenMLPrivateDatasetError
from openml.testing import TestBase
from openml.utils import _tag_entity, _create_cache_directory_for_id
from openml.datasets.functions import (create_dataset,
attributes_arff_from_df,
_get_cached_dataset,
_get_cached_dataset_features,
_get_cached_dataset_qualities,
_get_cached_datasets,
_get_dataset_arff,
_get_dataset_description,
_get_dataset_features,
_get_dataset_qualities,
_get_online_dataset_arff,
_get_online_dataset_format,
DATASETS_CACHE_DIR_NAME)
class TestOpenMLDataset(TestBase):
_multiprocess_can_split_ = True
def setUp(self):
super(TestOpenMLDataset, self).setUp()
def tearDown(self):
self._remove_pickle_files()
super(TestOpenMLDataset, self).tearDown()
def _remove_pickle_files(self):
self.lock_path = os.path.join(openml.config.get_cache_directory(), 'locks')
for did in ['-1', '2']:
with lockutils.external_lock(
name='datasets.functions.get_dataset:%s' % did,
lock_path=self.lock_path,
):
pickle_path = os.path.join(openml.config.get_cache_directory(), 'datasets',
did, 'dataset.pkl.py3')
try:
os.remove(pickle_path)
except (OSError, FileNotFoundError):
# Replaced a bare except. Not sure why either of these would be acceptable.
pass
def _get_empty_param_for_dataset(self):
return {
'name': None,
'description': None,
'creator': None,
'contributor': None,
'collection_date': None,
'language': None,
'licence': None,
'default_target_attribute': None,
'row_id_attribute': None,
'ignore_attribute': None,
'citation': None,
'attributes': None,
'data': None
}
def test__list_cached_datasets(self):
openml.config.cache_directory = self.static_cache_dir
cached_datasets = openml.datasets.functions._list_cached_datasets()
self.assertIsInstance(cached_datasets, list)
self.assertEqual(len(cached_datasets), 2)
self.assertIsInstance(cached_datasets[0], int)
@mock.patch('openml.datasets.functions._list_cached_datasets')
def test__get_cached_datasets(self, _list_cached_datasets_mock):
openml.config.cache_directory = self.static_cache_dir
_list_cached_datasets_mock.return_value = [-1, 2]
datasets = _get_cached_datasets()
self.assertIsInstance(datasets, dict)
self.assertEqual(len(datasets), 2)
self.assertIsInstance(list(datasets.values())[0], OpenMLDataset)
def test__get_cached_dataset(self, ):
openml.config.cache_directory = self.static_cache_dir
dataset = _get_cached_dataset(2)
features = _get_cached_dataset_features(2)
qualities = _get_cached_dataset_qualities(2)
self.assertIsInstance(dataset, OpenMLDataset)
self.assertTrue(len(dataset.features) > 0)
self.assertTrue(len(dataset.features) == len(features['oml:feature']))
self.assertTrue(len(dataset.qualities) == len(qualities))
def test_get_cached_dataset_description(self):
openml.config.cache_directory = self.static_cache_dir
description = openml.datasets.functions._get_cached_dataset_description(2)
self.assertIsInstance(description, dict)
def test_get_cached_dataset_description_not_cached(self):
openml.config.cache_directory = self.static_cache_dir
self.assertRaisesRegex(OpenMLCacheException,
"Dataset description for dataset id 3 not cached",
openml.datasets.functions._get_cached_dataset_description,
dataset_id=3)
def test_get_cached_dataset_arff(self):
openml.config.cache_directory = self.static_cache_dir
description = openml.datasets.functions._get_cached_dataset_arff(dataset_id=2)
self.assertIsInstance(description, str)
def test_get_cached_dataset_arff_not_cached(self):
openml.config.cache_directory = self.static_cache_dir
self.assertRaisesRegex(OpenMLCacheException,
"ARFF file for dataset id 3 not cached",
openml.datasets.functions._get_cached_dataset_arff,
dataset_id=3)
def _check_dataset(self, dataset):
self.assertEqual(type(dataset), dict)
self.assertGreaterEqual(len(dataset), 2)
self.assertIn('did', dataset)
self.assertIsInstance(dataset['did'], int)
self.assertIn('status', dataset)
self.assertIsInstance(dataset['status'], str)
self.assertIn(dataset['status'], ['in_preparation', 'active', 'deactivated'])
def _check_datasets(self, datasets):
for did in datasets:
self._check_dataset(datasets[did])
def test_tag_untag_dataset(self):
tag = 'test_tag_%d' % random.randint(1, 1000000)
all_tags = _tag_entity('data', 1, tag)
self.assertTrue(tag in all_tags)
all_tags = _tag_entity('data', 1, tag, untag=True)
self.assertTrue(tag not in all_tags)
def test_list_datasets(self):
# We can only perform a smoke test here because we test on dynamic
# data from the internet...
datasets = openml.datasets.list_datasets()
# 1087 as the number of datasets on openml.org
self.assertGreaterEqual(len(datasets), 100)
self._check_datasets(datasets)
def test_list_datasets_output_format(self):
datasets = openml.datasets.list_datasets(output_format='dataframe')
self.assertIsInstance(datasets, pd.DataFrame)
self.assertGreaterEqual(len(datasets), 100)
def test_list_datasets_by_tag(self):
datasets = openml.datasets.list_datasets(tag='study_14')
self.assertGreaterEqual(len(datasets), 100)
self._check_datasets(datasets)
def test_list_datasets_by_size(self):
datasets = openml.datasets.list_datasets(size=10050)
self.assertGreaterEqual(len(datasets), 120)
self._check_datasets(datasets)
def test_list_datasets_by_number_instances(self):
datasets = openml.datasets.list_datasets(number_instances="5..100")
self.assertGreaterEqual(len(datasets), 4)
self._check_datasets(datasets)
def test_list_datasets_by_number_features(self):
datasets = openml.datasets.list_datasets(number_features="50..100")
self.assertGreaterEqual(len(datasets), 8)
self._check_datasets(datasets)
def test_list_datasets_by_number_classes(self):
datasets = openml.datasets.list_datasets(number_classes="5")
self.assertGreaterEqual(len(datasets), 3)
self._check_datasets(datasets)
def test_list_datasets_by_number_missing_values(self):
datasets = openml.datasets.list_datasets(number_missing_values="5..100")
self.assertGreaterEqual(len(datasets), 5)
self._check_datasets(datasets)
def test_list_datasets_combined_filters(self):
datasets = openml.datasets.list_datasets(tag='study_14',
number_instances="100..1000",
number_missing_values="800..1000")
self.assertGreaterEqual(len(datasets), 1)
self._check_datasets(datasets)
def test_list_datasets_paginate(self):
size = 10
max = 100
for i in range(0, max, size):
datasets = openml.datasets.list_datasets(offset=i, size=size)
self.assertEqual(size, len(datasets))
self._check_datasets(datasets)
def test_list_datasets_empty(self):
datasets = openml.datasets.list_datasets(tag='NoOneWouldUseThisTagAnyway')
if len(datasets) > 0:
raise ValueError('UnitTest Outdated, tag was already used (please remove)')
self.assertIsInstance(datasets, dict)
def test_check_datasets_active(self):
# Have to test on live because there is no deactivated dataset on the test server.
openml.config.server = self.production_server
active = openml.datasets.check_datasets_active([2, 17])
self.assertTrue(active[2])
self.assertFalse(active[17])
self.assertRaisesRegex(
ValueError,
'Could not find dataset 79 in OpenML dataset list.',
openml.datasets.check_datasets_active,
[79],
)
openml.config.server = self.test_server
def _datasets_retrieved_successfully(self, dids, metadata_only=True):
""" Checks that all files for the given dids have been downloaded.
This includes:
- description
- qualities
- features
- absence of data arff if metadata_only, else it must be present too.
"""
for did in dids:
self.assertTrue(os.path.exists(os.path.join(
openml.config.get_cache_directory(), "datasets", str(did), "description.xml")))
self.assertTrue(os.path.exists(os.path.join(
openml.config.get_cache_directory(), "datasets", str(did), "qualities.xml")))
self.assertTrue(os.path.exists(os.path.join(
openml.config.get_cache_directory(), "datasets", str(did), "features.xml")))
data_assert = self.assertFalse if metadata_only else self.assertTrue
data_assert(os.path.exists(os.path.join(
openml.config.get_cache_directory(), "datasets", str(did), "dataset.arff")))
def test__name_to_id_with_deactivated(self):
""" Check that an activated dataset is returned if an earlier deactivated one exists. """
openml.config.server = self.production_server
# /d/1 was deactivated
self.assertEqual(openml.datasets.functions._name_to_id('anneal'), 2)
openml.config.server = self.test_server
def test__name_to_id_with_multiple_active(self):
""" With multiple active datasets, retrieve the least recent active. """
openml.config.server = self.production_server
self.assertEqual(openml.datasets.functions._name_to_id('iris'), 61)
def test__name_to_id_with_version(self):
""" With multiple active datasets, retrieve the least recent active. """
openml.config.server = self.production_server
self.assertEqual(openml.datasets.functions._name_to_id('iris', version=3), 969)
def test__name_to_id_with_multiple_active_error(self):
""" With multiple active datasets, retrieve the least recent active. """
self.assertRaisesRegex(
ValueError,
"Multiple active datasets exist with name iris",
openml.datasets.functions._name_to_id,
dataset_name='iris',
error_if_multiple=True
)
def test__name_to_id_name_does_not_exist(self):
""" With multiple active datasets, retrieve the least recent active. """
self.assertRaisesRegex(
RuntimeError,
"No active datasets exist with name does_not_exist",
openml.datasets.functions._name_to_id,
dataset_name='does_not_exist'
)
def test__name_to_id_version_does_not_exist(self):
""" With multiple active datasets, retrieve the least recent active. """
self.assertRaisesRegex(
RuntimeError,
"No active datasets exist with name iris and version 100000",
openml.datasets.functions._name_to_id,
dataset_name='iris',
version=100000
)
def test_get_datasets_by_name(self):
# did 1 and 2 on the test server:
dids = ['anneal', 'kr-vs-kp']
datasets = openml.datasets.get_datasets(dids, download_data=False)
self.assertEqual(len(datasets), 2)
self._datasets_retrieved_successfully([1, 2])
def test_get_datasets_by_mixed(self):
# did 1 and 2 on the test server:
dids = ['anneal', 2]
datasets = openml.datasets.get_datasets(dids, download_data=False)
self.assertEqual(len(datasets), 2)
self._datasets_retrieved_successfully([1, 2])
def test_get_datasets(self):
dids = [1, 2]
datasets = openml.datasets.get_datasets(dids)
self.assertEqual(len(datasets), 2)
self._datasets_retrieved_successfully([1, 2], metadata_only=False)
def test_get_datasets_lazy(self):
dids = [1, 2]
datasets = openml.datasets.get_datasets(dids, download_data=False)
self.assertEqual(len(datasets), 2)
self._datasets_retrieved_successfully([1, 2], metadata_only=True)
datasets[0].get_data()
datasets[1].get_data()
self._datasets_retrieved_successfully([1, 2], metadata_only=False)
def test_get_dataset_by_name(self):
dataset = openml.datasets.get_dataset('anneal')
self.assertEqual(type(dataset), OpenMLDataset)
self.assertEqual(dataset.dataset_id, 1)
self._datasets_retrieved_successfully([1], metadata_only=False)
self.assertGreater(len(dataset.features), 1)
self.assertGreater(len(dataset.qualities), 4)
# Issue324 Properly handle private datasets when trying to access them
openml.config.server = self.production_server
self.assertRaises(OpenMLPrivateDatasetError, openml.datasets.get_dataset, 45)
def test_get_dataset(self):
# This is the only non-lazy load to ensure default behaviour works.
dataset = openml.datasets.get_dataset(1)
self.assertEqual(type(dataset), OpenMLDataset)
self.assertEqual(dataset.name, 'anneal')
self._datasets_retrieved_successfully([1], metadata_only=False)
self.assertGreater(len(dataset.features), 1)
self.assertGreater(len(dataset.qualities), 4)
# Issue324 Properly handle private datasets when trying to access them
openml.config.server = self.production_server
self.assertRaises(OpenMLPrivateDatasetError, openml.datasets.get_dataset, 45)
def test_get_dataset_lazy(self):
dataset = openml.datasets.get_dataset(1, download_data=False)
self.assertEqual(type(dataset), OpenMLDataset)
self.assertEqual(dataset.name, 'anneal')
self._datasets_retrieved_successfully([1], metadata_only=True)
self.assertGreater(len(dataset.features), 1)
self.assertGreater(len(dataset.qualities), 4)
dataset.get_data()
self._datasets_retrieved_successfully([1], metadata_only=False)
# Issue324 Properly handle private datasets when trying to access them
openml.config.server = self.production_server
self.assertRaises(OpenMLPrivateDatasetError, openml.datasets.get_dataset, 45, False)
def test_get_dataset_lazy_all_functions(self):
""" Test that all expected functionality is available without downloading the dataset. """
dataset = openml.datasets.get_dataset(1, download_data=False)
# We only tests functions as general integrity is tested by test_get_dataset_lazy
def ensure_absence_of_real_data():
self.assertFalse(os.path.exists(os.path.join(
openml.config.get_cache_directory(), "datasets", "1", "dataset.arff")))
tag = 'test_lazy_tag_%d' % random.randint(1, 1000000)
dataset.push_tag(tag)
ensure_absence_of_real_data()
dataset.remove_tag(tag)
ensure_absence_of_real_data()
nominal_indices = dataset.get_features_by_type('nominal')
correct = [0, 1, 2, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 35, 36, 37, 38]
self.assertEqual(nominal_indices, correct)
ensure_absence_of_real_data()
classes = dataset.retrieve_class_labels()
self.assertEqual(classes, ['1', '2', '3', '4', '5', 'U'])
ensure_absence_of_real_data()
def test_get_dataset_sparse(self):
dataset = openml.datasets.get_dataset(102, download_data=False)
X, *_ = dataset.get_data(dataset_format='array')
self.assertIsInstance(X, scipy.sparse.csr_matrix)
def test_download_rowid(self):
# Smoke test which checks that the dataset has the row-id set correctly
did = 44
dataset = openml.datasets.get_dataset(did, download_data=False)
self.assertEqual(dataset.row_id_attribute, 'Counter')
def test__get_dataset_description(self):
description = _get_dataset_description(self.workdir, 2)
self.assertIsInstance(description, dict)
description_xml_path = os.path.join(self.workdir,
'description.xml')
self.assertTrue(os.path.exists(description_xml_path))
def test__getarff_path_dataset_arff(self):
openml.config.cache_directory = self.static_cache_dir
description = openml.datasets.functions._get_cached_dataset_description(2)
arff_path = _get_dataset_arff(description, cache_directory=self.workdir)
self.assertIsInstance(arff_path, str)
self.assertTrue(os.path.exists(arff_path))
def test__getarff_md5_issue(self):
description = {
'oml:id': 5,
'oml:md5_checksum': 'abc',
'oml:url': 'https://www.openml.org/data/download/61',
}
self.assertRaisesRegex(
OpenMLHashException,
'Checksum ad484452702105cbf3d30f8deaba39a9 of downloaded file '
'is unequal to the expected checksum abc. '
'Raised when downloading dataset 5.',
_get_dataset_arff,
description,
)
def test__get_dataset_features(self):
features = _get_dataset_features(self.workdir, 2)
self.assertIsInstance(features, dict)
features_xml_path = os.path.join(self.workdir, 'features.xml')
self.assertTrue(os.path.exists(features_xml_path))
def test__get_dataset_qualities(self):
# Only a smoke check
qualities = _get_dataset_qualities(self.workdir, 2)
self.assertIsInstance(qualities, list)
def test_deletion_of_cache_dir(self):
# Simple removal
did_cache_dir = _create_cache_directory_for_id(
DATASETS_CACHE_DIR_NAME, 1,
)
self.assertTrue(os.path.exists(did_cache_dir))
openml.utils._remove_cache_dir_for_id(
DATASETS_CACHE_DIR_NAME, did_cache_dir,
)
self.assertFalse(os.path.exists(did_cache_dir))
# Use _get_dataset_arff to load the description, trigger an exception in the
# test target and have a slightly higher coverage
@mock.patch('openml.datasets.functions._get_dataset_arff')
def test_deletion_of_cache_dir_faulty_download(self, patch):
patch.side_effect = Exception('Boom!')
self.assertRaisesRegex(Exception, 'Boom!', openml.datasets.get_dataset, dataset_id=1)
datasets_cache_dir = os.path.join(
self.workdir, 'org', 'openml', 'test', 'datasets'
)
self.assertEqual(len(os.listdir(datasets_cache_dir)), 0)
def test_publish_dataset(self):
# lazy loading not possible as we need the arff-file.
openml.datasets.get_dataset(3)
file_path = os.path.join(openml.config.get_cache_directory(),
"datasets", "3", "dataset.arff")
dataset = OpenMLDataset(
"anneal",
"test",
data_format="arff",
version=1,
licence="public",
default_target_attribute="class",
data_file=file_path,
)
dataset.publish()
TestBase._mark_entity_for_removal('data', dataset.dataset_id)
TestBase.logger.info("collected from {}: {}".format(__file__.split('/')[-1],
dataset.dataset_id))
self.assertIsInstance(dataset.dataset_id, int)
def test__retrieve_class_labels(self):
openml.config.cache_directory = self.static_cache_dir
labels = openml.datasets.get_dataset(2, download_data=False).retrieve_class_labels()
self.assertEqual(labels, ['1', '2', '3', '4', '5', 'U'])
labels = openml.datasets.get_dataset(2, download_data=False).retrieve_class_labels(
target_name='product-type')
self.assertEqual(labels, ['C', 'H', 'G'])
def test_upload_dataset_with_url(self):
dataset = OpenMLDataset(
"%s-UploadTestWithURL" % self._get_sentinel(),
"test",
data_format="arff",
version=1,
url="https://www.openml.org/data/download/61/dataset_61_iris.arff",
)
dataset.publish()
TestBase._mark_entity_for_removal('data', dataset.dataset_id)
TestBase.logger.info("collected from {}: {}".format(__file__.split('/')[-1],
dataset.dataset_id))
self.assertIsInstance(dataset.dataset_id, int)
def test_data_status(self):
dataset = OpenMLDataset(
"%s-UploadTestWithURL" % self._get_sentinel(),
"test", "ARFF",
version=1,
url="https://www.openml.org/data/download/61/dataset_61_iris.arff")
dataset.publish()
TestBase._mark_entity_for_removal('data', dataset.dataset_id)
TestBase.logger.info("collected from {}: {}".format(__file__.split('/')[-1],
dataset.dataset_id))
did = dataset.dataset_id
# admin key for test server (only adminds can activate datasets.
# all users can deactivate their own datasets)
openml.config.apikey = 'd488d8afd93b32331cf6ea9d7003d4c3'
openml.datasets.status_update(did, 'active')
# need to use listing fn, as this is immune to cache
result = openml.datasets.list_datasets(data_id=did, status='all')
self.assertEqual(len(result), 1)
self.assertEqual(result[did]['status'], 'active')
openml.datasets.status_update(did, 'deactivated')
# need to use listing fn, as this is immune to cache
result = openml.datasets.list_datasets(data_id=did, status='all')
self.assertEqual(len(result), 1)
self.assertEqual(result[did]['status'], 'deactivated')
openml.datasets.status_update(did, 'active')
# need to use listing fn, as this is immune to cache
result = openml.datasets.list_datasets(data_id=did, status='all')
self.assertEqual(len(result), 1)
self.assertEqual(result[did]['status'], 'active')
with self.assertRaises(ValueError):
openml.datasets.status_update(did, 'in_preparation')
# need to use listing fn, as this is immune to cache
result = openml.datasets.list_datasets(data_id=did, status='all')
self.assertEqual(len(result), 1)
self.assertEqual(result[did]['status'], 'active')
def test_attributes_arff_from_df(self):
# DataFrame case
df = pd.DataFrame(
[[1, 1.0, 'xxx', 'A', True], [2, 2.0, 'yyy', 'B', False]],
columns=['integer', 'floating', 'string', 'category', 'boolean']
)
df['category'] = df['category'].astype('category')
attributes = attributes_arff_from_df(df)
self.assertEqual(attributes, [('integer', 'INTEGER'),
('floating', 'REAL'),
('string', 'STRING'),
('category', ['A', 'B']),
('boolean', ['True', 'False'])])
# SparseDataFrame case
df = pd.SparseDataFrame([[1, 1.0],
[2, 2.0],
[0, 0]],
columns=['integer', 'floating'],
default_fill_value=0)
df['integer'] = df['integer'].astype(np.int64)
attributes = attributes_arff_from_df(df)
self.assertEqual(attributes, [('integer', 'INTEGER'),
('floating', 'REAL')])
def test_attributes_arff_from_df_mixed_dtype_categories(self):
# liac-arff imposed categorical attributes to be of sting dtype. We
# raise an error if this is not the case.
df = pd.DataFrame([[1], ['2'], [3.]])
df[0] = df[0].astype('category')
err_msg = "The column '0' of the dataframe is of 'category' dtype."
with pytest.raises(ValueError, match=err_msg):
attributes_arff_from_df(df)
def test_attributes_arff_from_df_unknown_dtype(self):
# check that an error is raised when the dtype is not supptagorted by
# liac-arff
data = [
[[1], ['2'], [3.]],
[pd.Timestamp('2012-05-01'), pd.Timestamp('2012-05-02')],
]
dtype = [
'mixed-integer',
'datetime64'
]
for arr, dt in zip(data, dtype):
df = pd.DataFrame(arr)
err_msg = ("The dtype '{}' of the column '0' is not currently "
"supported by liac-arff".format(dt))
with pytest.raises(ValueError, match=err_msg):
attributes_arff_from_df(df)
def test_create_dataset_numpy(self):
data = np.array(
[
[1, 2, 3],
[1.2, 2.5, 3.8],
[2, 5, 8],
[0, 1, 0]
]
).T
attributes = [('col_{}'.format(i), 'REAL')
for i in range(data.shape[1])]
dataset = create_dataset(
name='%s-NumPy_testing_dataset' % self._get_sentinel(),
description='Synthetic dataset created from a NumPy array',
creator='OpenML tester',
contributor=None,
collection_date='01-01-2018',
language='English',
licence='MIT',
default_target_attribute='col_{}'.format(data.shape[1] - 1),
row_id_attribute=None,
ignore_attribute=None,
citation='None',
attributes=attributes,
data=data,
version_label='test',
original_data_url='http://openml.github.io/openml-python',
paper_url='http://openml.github.io/openml-python'
)
upload_did = dataset.publish()
TestBase._mark_entity_for_removal('data', upload_did)
TestBase.logger.info("collected from {}: {}".format(__file__.split('/')[-1],
upload_did))
self.assertEqual(
_get_online_dataset_arff(upload_did),
dataset._dataset,
"Uploaded arff does not match original one"
)
self.assertEqual(
_get_online_dataset_format(upload_did),
'arff',
"Wrong format for dataset"
)
def test_create_dataset_list(self):
data = [
['a', 'sunny', 85.0, 85.0, 'FALSE', 'no'],
['b', 'sunny', 80.0, 90.0, 'TRUE', 'no'],
['c', 'overcast', 83.0, 86.0, 'FALSE', 'yes'],
['d', 'rainy', 70.0, 96.0, 'FALSE', 'yes'],
['e', 'rainy', 68.0, 80.0, 'FALSE', 'yes'],
['f', 'rainy', 65.0, 70.0, 'TRUE', 'no'],
['g', 'overcast', 64.0, 65.0, 'TRUE', 'yes'],
['h', 'sunny', 72.0, 95.0, 'FALSE', 'no'],
['i', 'sunny', 69.0, 70.0, 'FALSE', 'yes'],
['j', 'rainy', 75.0, 80.0, 'FALSE', 'yes'],
['k', 'sunny', 75.0, 70.0, 'TRUE', 'yes'],
['l', 'overcast', 72.0, 90.0, 'TRUE', 'yes'],
['m', 'overcast', 81.0, 75.0, 'FALSE', 'yes'],
['n', 'rainy', 71.0, 91.0, 'TRUE', 'no'],
]
attributes = [
('rnd_str', 'STRING'),
('outlook', ['sunny', 'overcast', 'rainy']),
('temperature', 'REAL'),
('humidity', 'REAL'),
('windy', ['TRUE', 'FALSE']),
('play', ['yes', 'no']),
]
dataset = create_dataset(
name="%s-ModifiedWeather" % self._get_sentinel(),
description=(
'Testing dataset upload when the data is a list of lists'
),
creator='OpenML test',
contributor=None,
collection_date='21-09-2018',
language='English',
licence='MIT',
default_target_attribute='play',
row_id_attribute=None,
ignore_attribute=None,
citation='None',
attributes=attributes,
data=data,
version_label='test',
original_data_url='http://openml.github.io/openml-python',
paper_url='http://openml.github.io/openml-python'
)
upload_did = dataset.publish()
TestBase._mark_entity_for_removal('data', upload_did)
TestBase.logger.info("collected from {}: {}".format(__file__.split('/')[-1],
upload_did))
self.assertEqual(
_get_online_dataset_arff(upload_did),
dataset._dataset,
"Uploaded ARFF does not match original one"
)
self.assertEqual(
_get_online_dataset_format(upload_did),
'arff',
"Wrong format for dataset"
)
def test_create_dataset_sparse(self):
# test the scipy.sparse.coo_matrix
sparse_data = scipy.sparse.coo_matrix((
[0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],
([0, 1, 1, 2, 2, 3, 3], [0, 1, 2, 0, 2, 0, 1])
))
column_names = [
('input1', 'REAL'),
('input2', 'REAL'),
('y', 'REAL'),
]
xor_dataset = create_dataset(
name="%s-XOR" % self._get_sentinel(),
description='Dataset representing the XOR operation',
creator=None,
contributor=None,
collection_date=None,
language='English',
licence=None,
default_target_attribute='y',
row_id_attribute=None,
ignore_attribute=None,
citation=None,
attributes=column_names,
data=sparse_data,
version_label='test',
)
upload_did = xor_dataset.publish()
TestBase._mark_entity_for_removal('data', upload_did)
TestBase.logger.info("collected from {}: {}".format(__file__.split('/')[-1],
upload_did))
self.assertEqual(
_get_online_dataset_arff(upload_did),
xor_dataset._dataset,
"Uploaded ARFF does not match original one"
)
self.assertEqual(
_get_online_dataset_format(upload_did),
'sparse_arff',
"Wrong format for dataset"
)
# test the list of dicts sparse representation
sparse_data = [
{0: 0.0},
{1: 1.0, 2: 1.0},
{0: 1.0, 2: 1.0},
{0: 1.0, 1: 1.0}
]
xor_dataset = create_dataset(
name="%s-XOR" % self._get_sentinel(),
description='Dataset representing the XOR operation',
creator=None,
contributor=None,
collection_date=None,
language='English',
licence=None,
default_target_attribute='y',
row_id_attribute=None,
ignore_attribute=None,
citation=None,
attributes=column_names,
data=sparse_data,
version_label='test',
)
upload_did = xor_dataset.publish()
TestBase._mark_entity_for_removal('data', upload_did)
TestBase.logger.info("collected from {}: {}".format(__file__.split('/')[-1],
upload_did))
self.assertEqual(
_get_online_dataset_arff(upload_did),
xor_dataset._dataset,
"Uploaded ARFF does not match original one"
)
self.assertEqual(
_get_online_dataset_format(upload_did),
'sparse_arff',
"Wrong format for dataset"
)
def test_create_invalid_dataset(self):
data = [
'sunny',
'overcast',
'overcast',
'rainy',
'rainy',
'rainy',
'overcast',
'sunny',
'sunny',
'rainy',
'sunny',
'overcast',
'overcast',
'rainy',
]
param = self._get_empty_param_for_dataset()
param['data'] = data
self.assertRaises(
ValueError,
create_dataset,
**param
)
param['data'] = data[0]
self.assertRaises(
ValueError,
create_dataset,
**param
)
def test_get_online_dataset_arff(self):
dataset_id = 100 # Australian
# lazy loading not used as arff file is checked.
dataset = openml.datasets.get_dataset(dataset_id)
decoder = arff.ArffDecoder()
# check if the arff from the dataset is
# the same as the arff from _get_arff function
d_format = (dataset.format).lower()
self.assertEqual(
dataset._get_arff(d_format),
decoder.decode(
_get_online_dataset_arff(dataset_id),
encode_nominal=True,
return_type=arff.DENSE
if d_format == 'arff' else arff.COO
),
"ARFF files are not equal"
)
def test_get_online_dataset_format(self):
# Phoneme dataset
dataset_id = 77
dataset = openml.datasets.get_dataset(dataset_id, download_data=False)
self.assertEqual(
(dataset.format).lower(),
_get_online_dataset_format(dataset_id),
"The format of the ARFF files is different"
)
def test_create_dataset_pandas(self):
data = [
['a', 'sunny', 85.0, 85.0, 'FALSE', 'no'],
['b', 'sunny', 80.0, 90.0, 'TRUE', 'no'],
['c', 'overcast', 83.0, 86.0, 'FALSE', 'yes'],
['d', 'rainy', 70.0, 96.0, 'FALSE', 'yes'],
['e', 'rainy', 68.0, 80.0, 'FALSE', 'yes']
]
column_names = ['rnd_str', 'outlook', 'temperature', 'humidity',
'windy', 'play']
df = pd.DataFrame(data, columns=column_names)
# enforce the type of each column
df['outlook'] = df['outlook'].astype('category')
df['windy'] = df['windy'].astype('bool')
df['play'] = df['play'].astype('category')
# meta-information
name = '%s-pandas_testing_dataset' % self._get_sentinel()
description = 'Synthetic dataset created from a Pandas DataFrame'
creator = 'OpenML tester'
collection_date = '01-01-2018'
language = 'English'
licence = 'MIT'
default_target_attribute = 'play'
citation = 'None'
original_data_url = 'http://openml.github.io/openml-python'
paper_url = 'http://openml.github.io/openml-python'
dataset = openml.datasets.functions.create_dataset(
name=name,
description=description,
creator=creator,
contributor=None,
collection_date=collection_date,
language=language,
licence=licence,
default_target_attribute=default_target_attribute,
row_id_attribute=None,
ignore_attribute=None,
citation=citation,
attributes='auto',
data=df,
version_label='test',
original_data_url=original_data_url,
paper_url=paper_url
)
upload_did = dataset.publish()
TestBase._mark_entity_for_removal('data', upload_did)
TestBase.logger.info("collected from {}: {}".format(__file__.split('/')[-1],
upload_did))
self.assertEqual(
_get_online_dataset_arff(upload_did),
dataset._dataset,
"Uploaded ARFF does not match original one"
)
# Check that SparseDataFrame are supported properly
sparse_data = scipy.sparse.coo_matrix((
[0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],
([0, 1, 1, 2, 2, 3, 3], [0, 1, 2, 0, 2, 0, 1])
))
column_names = ['input1', 'input2', 'y']
df = pd.SparseDataFrame(sparse_data, columns=column_names)
# meta-information
description = 'Synthetic dataset created from a Pandas SparseDataFrame'
dataset = openml.datasets.functions.create_dataset(
name=name,
description=description,
creator=creator,
contributor=None,
collection_date=collection_date,
language=language,
licence=licence,
default_target_attribute=default_target_attribute,
row_id_attribute=None,
ignore_attribute=None,
citation=citation,
attributes='auto',
data=df,
version_label='test',
original_data_url=original_data_url,
paper_url=paper_url
)
upload_did = dataset.publish()
TestBase._mark_entity_for_removal('data', upload_did)
TestBase.logger.info("collected from {}: {}".format(__file__.split('/')[-1],
upload_did))
self.assertEqual(
_get_online_dataset_arff(upload_did),
dataset._dataset,
"Uploaded ARFF does not match original one"
)
self.assertEqual(
_get_online_dataset_format(upload_did),
'sparse_arff',
"Wrong format for dataset"
)
# Check that we can overwrite the attributes
data = [['a'], ['b'], ['c'], ['d'], ['e']]
column_names = ['rnd_str']
df = pd.DataFrame(data, columns=column_names)
df['rnd_str'] = df['rnd_str'].astype('category')
attributes = {'rnd_str': ['a', 'b', 'c', 'd', 'e', 'f', 'g']}
dataset = openml.datasets.functions.create_dataset(
name=name,
description=description,
creator=creator,
contributor=None,
collection_date=collection_date,
language=language,
licence=licence,
default_target_attribute=default_target_attribute,
row_id_attribute=None,
ignore_attribute=None,
citation=citation,
attributes=attributes,
data=df,
version_label='test',
original_data_url=original_data_url,
paper_url=paper_url
)
upload_did = dataset.publish()
TestBase._mark_entity_for_removal('data', upload_did)
TestBase.logger.info("collected from {}: {}".format(__file__.split('/')[-1],
upload_did))
downloaded_data = _get_online_dataset_arff(upload_did)
self.assertEqual(
downloaded_data,
dataset._dataset,
"Uploaded ARFF does not match original one"
)
self.assertTrue(
'@ATTRIBUTE rnd_str {a, b, c, d, e, f, g}' in downloaded_data)
def test_ignore_attributes_dataset(self):
data = [
['a', 'sunny', 85.0, 85.0, 'FALSE', 'no'],
['b', 'sunny', 80.0, 90.0, 'TRUE', 'no'],
['c', 'overcast', 83.0, 86.0, 'FALSE', 'yes'],
['d', 'rainy', 70.0, 96.0, 'FALSE', 'yes'],
['e', 'rainy', 68.0, 80.0, 'FALSE', 'yes']
]
column_names = ['rnd_str', 'outlook', 'temperature', 'humidity',
'windy', 'play']
df = pd.DataFrame(data, columns=column_names)
# enforce the type of each column
df['outlook'] = df['outlook'].astype('category')
df['windy'] = df['windy'].astype('bool')
df['play'] = df['play'].astype('category')
# meta-information
name = '%s-pandas_testing_dataset' % self._get_sentinel()
description = 'Synthetic dataset created from a Pandas DataFrame'
creator = 'OpenML tester'
collection_date = '01-01-2018'
language = 'English'
licence = 'MIT'
default_target_attribute = 'play'
citation = 'None'
original_data_url = 'http://openml.github.io/openml-python'
paper_url = 'http://openml.github.io/openml-python'
# we use the create_dataset function which call the OpenMLDataset
# constructor
# pass a string to ignore_attribute
dataset = openml.datasets.functions.create_dataset(
name=name,
description=description,
creator=creator,
contributor=None,
collection_date=collection_date,
language=language,
licence=licence,
default_target_attribute=default_target_attribute,
row_id_attribute=None,
ignore_attribute='outlook',
citation=citation,
attributes='auto',
data=df,
version_label='test',
original_data_url=original_data_url,
paper_url=paper_url
)
self.assertEqual(dataset.ignore_attribute, ['outlook'])
# pass a list to ignore_attribute
ignore_attribute = ['outlook', 'windy']
dataset = openml.datasets.functions.create_dataset(
name=name,
description=description,
creator=creator,
contributor=None,
collection_date=collection_date,
language=language,
licence=licence,
default_target_attribute=default_target_attribute,
row_id_attribute=None,
ignore_attribute=ignore_attribute,
citation=citation,
attributes='auto',
data=df,
version_label='test',
original_data_url=original_data_url,
paper_url=paper_url
)
self.assertEqual(dataset.ignore_attribute, ignore_attribute)
# raise an error if unknown type
err_msg = 'Wrong data type for ignore_attribute. Should be list.'
with pytest.raises(ValueError, match=err_msg):
openml.datasets.functions.create_dataset(
name=name,
description=description,
creator=creator,
contributor=None,
collection_date=collection_date,
language=language,
licence=licence,
default_target_attribute=default_target_attribute,
row_id_attribute=None,
ignore_attribute=tuple(['outlook', 'windy']),
citation=citation,
attributes='auto',
data=df,
version_label='test',
original_data_url=original_data_url,
paper_url=paper_url
)
def test___publish_fetch_ignore_attribute(self):
"""(Part 1) Test to upload and retrieve dataset and check ignore_attributes
DEPENDS on test_publish_fetch_ignore_attribute() to be executed after this
This test is split into two parts:
1) test___publish_fetch_ignore_attribute()
This will be executed earlier, owing to alphabetical sorting.
This test creates and publish() a dataset and checks for a valid ID.
2) test_publish_fetch_ignore_attribute()
This will be executed after test___publish_fetch_ignore_attribute(),
owing to alphabetical sorting. The time gap is to allow the server
more time time to compute data qualities.
The dataset ID obtained previously is used to fetch the dataset.
The retrieved dataset is checked for valid ignore_attributes.
"""
# the returned fixt
data = [
['a', 'sunny', 85.0, 85.0, 'FALSE', 'no'],
['b', 'sunny', 80.0, 90.0, 'TRUE', 'no'],
['c', 'overcast', 83.0, 86.0, 'FALSE', 'yes'],
['d', 'rainy', 70.0, 96.0, 'FALSE', 'yes'],
['e', 'rainy', 68.0, 80.0, 'FALSE', 'yes']
]
column_names = ['rnd_str', 'outlook', 'temperature', 'humidity',
'windy', 'play']
df = pd.DataFrame(data, columns=column_names)
# enforce the type of each column
df['outlook'] = df['outlook'].astype('category')
df['windy'] = df['windy'].astype('bool')
df['play'] = df['play'].astype('category')
# meta-information
name = '%s-pandas_testing_dataset' % self._get_sentinel()
description = 'Synthetic dataset created from a Pandas DataFrame'
creator = 'OpenML tester'
collection_date = '01-01-2018'
language = 'English'
licence = 'MIT'
default_target_attribute = 'play'
citation = 'None'
original_data_url = 'http://openml.github.io/openml-python'
paper_url = 'http://openml.github.io/openml-python'
# pass a list to ignore_attribute
ignore_attribute = ['outlook', 'windy']
dataset = openml.datasets.functions.create_dataset(
name=name,
description=description,
creator=creator,
contributor=None,
collection_date=collection_date,
language=language,
licence=licence,
default_target_attribute=default_target_attribute,
row_id_attribute=None,
ignore_attribute=ignore_attribute,
citation=citation,
attributes='auto',
data=df,
version_label='test',
original_data_url=original_data_url,
paper_url=paper_url
)
# publish dataset
upload_did = dataset.publish()
TestBase._mark_entity_for_removal('data', upload_did)
TestBase.logger.info("collected from {}: {}".format(__file__.split('/')[-1],
upload_did))
# test if publish was successful
self.assertIsInstance(upload_did, int)
# variables to carry forward for test_publish_fetch_ignore_attribute()
self.__class__.test_publish_fetch_ignore_attribute_did = upload_did
self.__class__.test_publish_fetch_ignore_attribute_list = ignore_attribute
def test_publish_fetch_ignore_attribute(self):
"""(Part 2) Test to upload and retrieve dataset and check ignore_attributes
DEPENDS on test___publish_fetch_ignore_attribute() to be executed first
This will be executed after test___publish_fetch_ignore_attribute(),
owing to alphabetical sorting. The time gap is to allow the server
more time time to compute data qualities.
The dataset ID obtained previously is used to fetch the dataset.
The retrieved dataset is checked for valid ignore_attributes.
"""
# Retrieving variables from test___publish_fetch_ignore_attribute()
upload_did = self.__class__.test_publish_fetch_ignore_attribute_did
ignore_attribute = self.__class__.test_publish_fetch_ignore_attribute_list
trials = 1
timeout_limit = 200
dataset = None
# fetching from server
# loop till timeout or fetch not successful
while True:
if trials > timeout_limit:
break
try:
dataset = openml.datasets.get_dataset(upload_did)
break
except Exception as e:
# returned code 273: Dataset not processed yet
# returned code 362: No qualities found
print("Trial {}/{}: ".format(trials, timeout_limit))
print("\tFailed to fetch dataset:{} with '{}'.".format(upload_did, str(e)))
trials += 1
continue
if dataset is None:
raise ValueError("TIMEOUT: Failed to fetch uploaded dataset - {}".format(upload_did))
self.assertEqual(dataset.ignore_attribute, ignore_attribute)
def test_create_dataset_row_id_attribute_error(self):
# meta-information
name = '%s-pandas_testing_dataset' % self._get_sentinel()
description = 'Synthetic dataset created from a Pandas DataFrame'
creator = 'OpenML tester'
collection_date = '01-01-2018'
language = 'English'
licence = 'MIT'
default_target_attribute = 'target'
citation = 'None'
original_data_url = 'http://openml.github.io/openml-python'
paper_url = 'http://openml.github.io/openml-python'
# Check that the index name is well inferred.
data = [['a', 1, 0],
['b', 2, 1],
['c', 3, 0],
['d', 4, 1],
['e', 5, 0]]
column_names = ['rnd_str', 'integer', 'target']
df = pd.DataFrame(data, columns=column_names)
# affecting row_id_attribute to an unknown column should raise an error
err_msg = ("should be one of the data attribute.")
with pytest.raises(ValueError, match=err_msg):
openml.datasets.functions.create_dataset(
name=name,
description=description,
creator=creator,
contributor=None,
collection_date=collection_date,
language=language,
licence=licence,
default_target_attribute=default_target_attribute,
ignore_attribute=None,
citation=citation,
attributes='auto',
data=df,
row_id_attribute='unknown_row_id',
version_label='test',
original_data_url=original_data_url,
paper_url=paper_url
)
def test_create_dataset_row_id_attribute_inference(self):
# meta-information
name = '%s-pandas_testing_dataset' % self._get_sentinel()
description = 'Synthetic dataset created from a Pandas DataFrame'
creator = 'OpenML tester'
collection_date = '01-01-2018'
language = 'English'
licence = 'MIT'
default_target_attribute = 'target'
citation = 'None'
original_data_url = 'http://openml.github.io/openml-python'
paper_url = 'http://openml.github.io/openml-python'
# Check that the index name is well inferred.
data = [['a', 1, 0],
['b', 2, 1],
['c', 3, 0],
['d', 4, 1],
['e', 5, 0]]
column_names = ['rnd_str', 'integer', 'target']
df = pd.DataFrame(data, columns=column_names)
row_id_attr = [None, 'integer']
df_index_name = [None, 'index_name']
expected_row_id = [None, 'index_name', 'integer', 'integer']
for output_row_id, (row_id, index_name) in zip(expected_row_id,
product(row_id_attr,
df_index_name)):
df.index.name = index_name
dataset = openml.datasets.functions.create_dataset(
name=name,
description=description,
creator=creator,
contributor=None,
collection_date=collection_date,
language=language,
licence=licence,
default_target_attribute=default_target_attribute,
ignore_attribute=None,
citation=citation,
attributes='auto',
data=df,
row_id_attribute=row_id,
version_label='test',
original_data_url=original_data_url,
paper_url=paper_url
)
self.assertEqual(dataset.row_id_attribute, output_row_id)
upload_did = dataset.publish()
TestBase._mark_entity_for_removal('data', upload_did)
TestBase.logger.info("collected from {}: {}".format(__file__.split('/')[-1],
upload_did))
arff_dataset = arff.loads(_get_online_dataset_arff(upload_did))
arff_data = np.array(arff_dataset['data'], dtype=object)
# if we set the name of the index then the index will be added to
# the data
expected_shape = (5, 3) if index_name is None else (5, 4)
self.assertEqual(arff_data.shape, expected_shape)
def test_create_dataset_attributes_auto_without_df(self):
# attributes cannot be inferred without passing a dataframe
data = np.array([[1, 2, 3],
[1.2, 2.5, 3.8],
[2, 5, 8],
[0, 1, 0]]).T
attributes = 'auto'
name = 'NumPy_testing_dataset'
description = 'Synthetic dataset created from a NumPy array'
creator = 'OpenML tester'
collection_date = '01-01-2018'
language = 'English'
licence = 'MIT'
default_target_attribute = 'col_{}'.format(data.shape[1] - 1)
citation = 'None'
original_data_url = 'http://openml.github.io/openml-python'
paper_url = 'http://openml.github.io/openml-python'
err_msg = "Automatically inferring attributes requires a pandas"
with pytest.raises(ValueError, match=err_msg):
openml.datasets.functions.create_dataset(
name=name,
description=description,
creator=creator,
contributor=None,
collection_date=collection_date,
language=language,
licence=licence,
default_target_attribute=default_target_attribute,
row_id_attribute=None,
ignore_attribute=None,
citation=citation,
attributes=attributes,
data=data,
version_label='test',
original_data_url=original_data_url,
paper_url=paper_url
)
def test_list_qualities(self):
qualities = openml.datasets.list_qualities()
self.assertEqual(isinstance(qualities, list), True)
self.assertEqual(all([isinstance(q, str) for q in qualities]), True)
| 41.495899
| 98
| 0.587679
|
2e5948cf2a3e73516a0d9f3ee5b658d39ba324ec
| 9,753
|
py
|
Python
|
CarlaWorld.py
|
yeshas1994/carla-dataset-runner
|
c781b9d2b5cd748d062f775b65a86b5d569c8e64
|
[
"MIT"
] | null | null | null |
CarlaWorld.py
|
yeshas1994/carla-dataset-runner
|
c781b9d2b5cd748d062f775b65a86b5d569c8e64
|
[
"MIT"
] | null | null | null |
CarlaWorld.py
|
yeshas1994/carla-dataset-runner
|
c781b9d2b5cd748d062f775b65a86b5d569c8e64
|
[
"MIT"
] | null | null | null |
import sys
import os
import settings
sys.path.append(settings.CARLA_EGG_PATH)
import carla
import random
import time
import numpy as np
from spawn_npc import NPCClass
from client_bounding_boxes import ClientSideBoundingBoxes
from set_synchronous_mode import CarlaSyncMode
from bb_filter import apply_filters_to_3d_bb
from WeatherSelector import WeatherSelector
class CarlaWorld:
def __init__(self, HDF5_file):
self.HDF5_file = HDF5_file
# Carla initialization
client = carla.Client('localhost', 2000)
client.set_timeout(20.0)
#self.world = client.load_world('Town01')
self.world = client.get_world()
print('Successfully connected to CARLA')
self.blueprint_library = self.world.get_blueprint_library()
# Sensors stuff
self.camera_x_location = 1.0
self.camera_y_location = 0.0
self.camera_z_location = 2.0
self.sensors_list = []
# Weather stuff
self.weather_options = WeatherSelector().get_weather_options() # List with weather options
# Recording stuff
self.total_recorded_frames = 0
self.first_time_simulating = True
def set_weather(self, weather_option):
# Changing weather https://carla.readthedocs.io/en/stable/carla_settings/
# Weather_option is one item from the list self.weather_options, which contains a list with the parameters
weather = carla.WeatherParameters(*weather_option)
self.world.set_weather(weather)
def remove_npcs(self):
print('Destroying actors...')
self.NPC.remove_npcs()
print('Done destroying actors.')
def spawn_npcs(self, number_of_vehicles, number_of_walkers):
self.NPC = NPCClass()
self.vehicles_list, _ = self.NPC.create_npcs(number_of_vehicles, number_of_walkers)
# added by yeshas
def put_segmentation_sensor(self, vehicle, sensor_width=640, sensor_height=480, fov=110):
bp = self.blueprint_library.find('sensor.camera.semantic_segmentation')
bp.set_attribute('image_size_x', f'{sensor_width}')
bp.set_attribute('image_size_y', f'{sensor_height}')
bp.set_attribute('fov', f'{fov}')
spawn_point = carla.Transform(carla.Location(x=self.camera_x_location, z=self.camera_z_location))
self.seg_camera = self.world.spawn_actor(bp, spawn_point, attach_to=vehicle)
self.sensors_list.append(self.seg_camera)
return self.seg_camera
def put_rgb_sensor(self, vehicle, sensor_width=640, sensor_height=480, fov=110):
# https://carla.readthedocs.io/en/latest/cameras_and_sensors/
bp = self.blueprint_library.find('sensor.camera.rgb')
# bp.set_attribute('enable_postprocess_effects', 'True') # https://carla.readthedocs.io/en/latest/bp_library/
bp.set_attribute('image_size_x', f'{sensor_width}')
bp.set_attribute('image_size_y', f'{sensor_height}')
bp.set_attribute('fov', f'{fov}')
# Adjust sensor relative position to the vehicle
spawn_point = carla.Transform(carla.Location(x=self.camera_x_location, z=self.camera_z_location))
self.rgb_camera = self.world.spawn_actor(bp, spawn_point, attach_to=vehicle)
self.rgb_camera.blur_amount = 0.0
self.rgb_camera.motion_blur_intensity = 0
self.rgb_camera.motion_max_distortion = 0
# Camera calibration
calibration = np.identity(3)
calibration[0, 2] = sensor_width / 2.0
calibration[1, 2] = sensor_height / 2.0
calibration[0, 0] = calibration[1, 1] = sensor_width / (2.0 * np.tan(fov * np.pi / 360.0))
self.rgb_camera.calibration = calibration # Parameter K of the camera
self.sensors_list.append(self.rgb_camera)
return self.rgb_camera
def put_depth_sensor(self, vehicle, sensor_width=640, sensor_height=480, fov=110):
# https://carla.readthedocs.io/en/latest/cameras_and_sensors/
bp = self.blueprint_library.find('sensor.camera.depth')
bp.set_attribute('image_size_x', f'{sensor_width}')
bp.set_attribute('image_size_y', f'{sensor_height}')
bp.set_attribute('fov', f'{fov}')
# Adjust sensor relative position to the vehicle
spawn_point = carla.Transform(carla.Location(x=self.camera_x_location, z=self.camera_z_location))
self.depth_camera = self.world.spawn_actor(bp, spawn_point, attach_to=vehicle)
self.sensors_list.append(self.depth_camera)
return self.depth_camera
def process_depth_data(self, data, sensor_width, sensor_height):
"""
normalized = (R + G * 256 + B * 256 * 256) / (256 * 256 * 256 - 1)
in_meters = 1000 * normalized
"""
data = np.array(data.raw_data)
data = data.reshape((sensor_height, sensor_width, 4))
data = data.astype(np.float32)
# Apply (R + G * 256 + B * 256 * 256) / (256 * 256 * 256 - 1).
normalized_depth = np.dot(data[:, :, :3], [65536.0, 256.0, 1.0])
normalized_depth /= 16777215.0 # (256.0 * 256.0 * 256.0 - 1.0)
depth_meters = normalized_depth * 1000
return depth_meters
def get_bb_data(self):
vehicles_on_world = self.world.get_actors().filter('vehicle.*')
walkers_on_world = self.world.get_actors().filter('walker.*')
bounding_boxes_vehicles = ClientSideBoundingBoxes.get_bounding_boxes(vehicles_on_world, self.rgb_camera)
bounding_boxes_walkers = ClientSideBoundingBoxes.get_bounding_boxes(walkers_on_world, self.rgb_camera)
return [bounding_boxes_vehicles, bounding_boxes_walkers]
def process_rgb_img(self, img, sensor_width, sensor_height):
img = np.array(img.raw_data)
img = img.reshape((sensor_height, sensor_width, 4))
img = img[:, :, :3] # taking out opacity channel
return img
# bb = self.get_bb_data()
# return img, bb
def process_seg_img(self, img, sensor_width, sensor_height):
img = np.array(img.raw_data)
img = img.reshape((sensor_height, sensor_width, 4))
img = img[:, :, 2]
return img
def remove_sensors(self):
for sensor in self.sensors_list:
sensor.destroy()
self.sensors_list = []
def begin_data_acquisition(self, sensor_width, sensor_height, fov, frames_to_record_one_ego=1, timestamps=[], egos_to_run=10):
# Changes the ego vehicle to be put the sensor
current_ego_recorded_frames = 0
# These vehicles are not considered because the cameras get occluded without changing their absolute position
ego_vehicle = random.choice([x for x in self.world.get_actors().filter("vehicle.*") if x.type_id not in
['vehicle.audi.tt', 'vehicle.carlamotors.carlacola', 'vehicle.volkswagen.t2']])
self.put_rgb_sensor(ego_vehicle, sensor_width, sensor_height, fov)
# self.put_depth_sensor(ego_vehicle, sensor_width, sensor_height, fov)
self.put_segmentation_sensor(ego_vehicle, sensor_width, sensor_height, fov)
# Begin applying the sync mode
with CarlaSyncMode(self.world, self.rgb_camera, self.seg_camera, fps=30) as sync_mode:
# Skip initial frames where the car is being put on the ambient
if self.first_time_simulating:
for _ in range(30):
sync_mode.tick_no_data()
while True:
if current_ego_recorded_frames == frames_to_record_one_ego:
print('\n')
self.remove_sensors()
return timestamps
# Advance the simulation and wait for the data
# Skip every nth frame for data recording, so that one frame is not that similar to another
wait_frame_ticks = 0
while wait_frame_ticks < 5:
sync_mode.tick_no_data()
wait_frame_ticks += 1
# _, rgb_data, depth_data = sync_mode.tick(timeout=2.0) # If needed, self.frame can be obtained too
_, rgb_data, seg_data = sync_mode.tick(timeout=2.0)
# Processing raw data
# rgb_array, bounding_box = self.process_rgb_img(rgb_data, sensor_width, sensor_height)
rgb_array = self.process_rgb_img(rgb_data, sensor_width, sensor_height)
seg_array = self.process_seg_img(seg_data, sensor_width, sensor_height)
ego_speed = ego_vehicle.get_velocity()
ego_speed = np.array([ego_speed.x, ego_speed.y, ego_speed.z])
ego_acc = ego_vehicle.get_acceleration()
ego_acc = np.array([ego_acc.x, ego_acc.y, ego_acc.z])
ego_angular = ego_vehicle.get_angular_velocity()
ego_angular = np.array([ego_angular.x, ego_angular.y, ego_angular.z])
ego_control = ego_vehicle.get_control()
ego_control = np.array([ego_control.throttle, ego_control.steer, ego_control.brake])
# bounding_box = apply_filters_to_3d_bb(bounding_box, depth_array, sensor_width, sensor_height)
timestamp = round(time.time() * 1000.0)
# Saving into opened HDF5 dataset file
self.HDF5_file.record_data(rgb_array, seg_array, ego_speed, ego_acc, ego_angular, ego_control, timestamp)
current_ego_recorded_frames += 1
self.total_recorded_frames += 1
timestamps.append(timestamp)
sys.stdout.write("\r")
sys.stdout.write('Frame {0}/{1}'.format(
self.total_recorded_frames, frames_to_record_one_ego*egos_to_run*len(self.weather_options)))
sys.stdout.flush()
| 48.522388
| 130
| 0.660412
|
b399eca8d4001215d3ae161f4bbdad8582d0fb0e
| 2,141
|
py
|
Python
|
src/foremast/utils/deep_chain_map.py
|
gitter-badger/foremast
|
33530438ba5893a1d5cf822a63e03d7ab49dfcd7
|
[
"Apache-2.0"
] | null | null | null |
src/foremast/utils/deep_chain_map.py
|
gitter-badger/foremast
|
33530438ba5893a1d5cf822a63e03d7ab49dfcd7
|
[
"Apache-2.0"
] | null | null | null |
src/foremast/utils/deep_chain_map.py
|
gitter-badger/foremast
|
33530438ba5893a1d5cf822a63e03d7ab49dfcd7
|
[
"Apache-2.0"
] | null | null | null |
# Foremast - Pipeline Tooling
#
# Copyright 2016 Gogo, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""ChainMap modification to handle nested dict objects."""
import collections
class DeepChainMap(collections.ChainMap):
"""Deep lookups for collections.ChainMap objects.
When there are nested dicts, the first found, second level dict is returned
instead of overlaying alternative second level dicts.
>>> first = {'key1': {'key1_1': 'first_one'}}
>>> second = {'key1': {'key1_1': 'second_one', 'key1_2': 'second_two'}}
>>> collections.ChainMap(first, second)['key1']
{'key1_1': 'first_one'}
>>> collections.ChainMap(second, first)['key1']
{'key1_1': 'second_one', 'key1_2': 'second_two'}
# Deep lookup will flatten every level.
>>> DeepChainMap(first, second)['key1']
{'key1_1': 'first_one', 'key1_2': 'second_two'}
>>> DeepChainMap(second, first)['key1']
{'key1_1': 'second_one', 'key1_2': 'second_two'}
"""
def __getitem__(self, key):
"""Recursively retrieve value for _key_ in dict.
Args:
key (str): dict key to get all items for
"""
for mapping in self.maps:
try:
value = mapping[key]
if isinstance(value, dict):
return dict(DeepChainMap(*list(mapping.get(key, {})
for mapping in self.maps)))
else:
return value
except KeyError:
pass
return self.__missing__(key)
| 36.288136
| 79
| 0.607193
|
7495a42a6f9dd430051cc291f3e6a20122fb0961
| 8,390
|
py
|
Python
|
kakao/request.py
|
minionsong/korea-covid-19-remaining-vaccine-macro
|
154ac0f1b5ba4bcc3f270255b38ed270a54febad
|
[
"MIT"
] | null | null | null |
kakao/request.py
|
minionsong/korea-covid-19-remaining-vaccine-macro
|
154ac0f1b5ba4bcc3f270255b38ed270a54febad
|
[
"MIT"
] | null | null | null |
kakao/request.py
|
minionsong/korea-covid-19-remaining-vaccine-macro
|
154ac0f1b5ba4bcc3f270255b38ed270a54febad
|
[
"MIT"
] | null | null | null |
import json
import re
import time
from datetime import datetime
import requests
import urllib3
from kakao.common import close, count_json_response
urllib3.disable_warnings()
header_map = {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json;charset=utf-8",
"Origin": "https://vaccine-map.kakao.com",
"Accept-Language": "en-us",
"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 14_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 KAKAOTALK 9.4.2",
"Referer": "https://vaccine-map.kakao.com/",
"Accept-Encoding": "gzip, deflate",
"Connection": "Keep-Alive",
"Keep-Alive": "timeout=5, max=1000"
}
headers_vaccine = {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json;charset=utf-8",
"Origin": "https://vaccine.kakao.com",
"Accept-Language": "en-us",
"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 14_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 KAKAOTALK 9.4.2",
"Referer": "https://vaccine.kakao.com/",
"Accept-Encoding": "gzip, deflate",
"Connection": "Keep-Alive",
"Keep-Alive": "timeout=5, max=1000"
}
# pylint: disable=too-many-locals,too-many-statements,too-many-branches,too-many-arguments
def find_vaccine(cookie, search_time, vaccine_type, top_x, top_y, bottom_x, bottom_y, only_left):
url = 'https://vaccine-map.kakao.com/api/v3/vaccine/left_count_by_coords'
data = {"bottomRight": {"x": bottom_x, "y": bottom_y}, "onlyLeft": only_left, "order": "count",
"topLeft": {"x": top_x, "y": top_y}}
done = False
found = None
while not done:
try:
time.sleep(search_time)
response = requests.post(url, data=json.dumps(data), headers=header_map, verify=False, timeout=5)
try:
json_data = json.loads(response.text)
for x in json_data.get("organizations"):
if x.get('status') == "AVAILABLE" or x.get('leftCounts') != 0:
found = x
organization_code = x.get('orgCode')
check_organization_url = f'https://vaccine.kakao.com/api/v3/org/org_code/{organization_code}'
check_organization_response = requests.get(check_organization_url, headers=headers_vaccine,
cookies=cookie, verify=False)
check_organization_data = json.loads(check_organization_response.text).get("lefts")
log_str = x.get('orgName') + "\t"
for y in check_organization_data:
log_str = log_str + "\t/ " + y.get('vaccineName') + "(" + str(y.get('leftCount')) + ")"
if y.get('leftCount') != 0 and\
(y.get('vaccineCode') == 'VEN00013' or y.get('vaccineCode') == 'VEN00014'):
print(f"{y.get('vaccineName')} 백신을 {y.get('leftCount')}개 발견했습니다.")
done = True
break
print(log_str)
if not done:
# pretty_print(json_data)
print("Searched organizations # : " + str(count_json_response(json_data)))
print(datetime.now())
except json.decoder.JSONDecodeError as decodeerror:
print("JSONDecodeError : ", decodeerror)
print("JSON string : ", response.text)
close()
except requests.exceptions.Timeout as timeouterror:
print("Timeout Error : ", timeouterror)
except requests.exceptions.SSLError as sslerror:
print("SSL Error : ", sslerror)
close()
except requests.exceptions.ConnectionError as connectionerror:
print("Connection Error : ", connectionerror)
# See psf/requests#5430 to know why this is necessary.
if not re.search('Read timed out', str(connectionerror), re.IGNORECASE):
close()
except requests.exceptions.HTTPError as httperror:
print("Http Error : ", httperror)
close()
except requests.exceptions.RequestException as error:
print("AnyException : ", error)
close()
if found is None:
find_vaccine(cookie, search_time, vaccine_type, top_x, top_y, bottom_x, bottom_y, only_left)
return None
print(f"{found.get('orgName')} 에서 백신을 {found.get('leftCounts')}개 발견했습니다.")
print(f"주소는 : {found.get('address')} 입니다.")
organization_code = found.get('orgCode')
# 실제 백신 남은수량 확인
vaccine_found_code = None
# if vaccine_type == "ANY": # ANY 백신 선택
# check_organization_url = f'https://vaccine.kakao.com/api/v3/org/org_code/{organization_code}'
# check_organization_response = requests.get(check_organization_url, headers=headers_vaccine, cookies=cookie, verify=False)
# check_organization_data = json.loads(check_organization_response.text).get("lefts")
# for x in check_organization_data:
# if x.get('leftCount') != 0:
# print(f"{x.get('vaccineName')} 백신을 {x.get('leftCount')}개 발견했습니다.")
# vaccine_found_code = x.get('vaccineCode')
# break
# else:
# print(f"{x.get('vaccineName')} 백신이 없습니다.")
#
# else:
vaccine_found_code = vaccine_type
print(f"{vaccine_found_code} 으로 예약을 시도합니다.")
if vaccine_found_code and try_reservation(organization_code, vaccine_found_code, cookie):
return None
else:
find_vaccine(cookie, search_time, vaccine_type, top_x, top_y, bottom_x, bottom_y, only_left)
return None
def try_reservation(organization_code, vaccine_type, jar):
reservation_url = 'https://vaccine.kakao.com/api/v2/reservation'
data = {"from": "List", "vaccineCode": vaccine_type,
"orgCode": organization_code, "distance": None}
response = requests.post(reservation_url, data=json.dumps(data), headers=headers_vaccine, cookies=jar, verify=False)
response_json = json.loads(response.text)
for key in response_json:
value = response_json[key]
if key != 'code':
continue
if key == 'code' and value == "NO_VACANCY":
print("잔여백신 접종 신청이 선착순 마감되었습니다.")
elif key == 'code' and value == "TIMEOUT":
print("TIMEOUT, 예약을 재시도합니다.")
retry_reservation(organization_code, vaccine_type, jar)
elif key == 'code' and value == "SUCCESS":
print("백신접종신청 성공!!!")
organization_code_success = response_json.get("organization")
print(
f"병원이름: {organization_code_success.get('orgName')}\t" +
f"전화번호: {organization_code_success.get('phoneNumber')}\t" +
f"주소: {organization_code_success.get('address')}")
close(success=True)
else:
print("ERROR. 아래 메시지를 보고, 예약이 신청된 병원 또는 1339에 예약이 되었는지 확인해보세요.")
print(response.text)
close()
def retry_reservation(organization_code, vaccine_type, jar):
reservation_url = 'https://vaccine.kakao.com/api/v2/reservation/retry'
data = {"from": "List", "vaccineCode": vaccine_type,
"orgCode": organization_code, "distance": None}
response = requests.post(reservation_url, data=json.dumps(data), headers=headers_vaccine, cookies=jar, verify=False)
response_json = json.loads(response.text)
for key in response_json:
value = response_json[key]
if key != 'code':
continue
if key == 'code' and value == "NO_VACANCY":
print("잔여백신 접종 신청이 선착순 마감되었습니다.")
elif key == 'code' and value == "SUCCESS":
print("백신접종신청 성공!!!")
organization_code_success = response_json.get("organization")
print(
f"병원이름: {organization_code_success.get('orgName')}\t" +
f"전화번호: {organization_code_success.get('phoneNumber')}\t" +
f"주소: {organization_code_success.get('address')}")
close(success=True)
else:
print("ERROR. 아래 메시지를 보고, 예약이 신청된 병원 또는 1339에 예약이 되었는지 확인해보세요.")
print(response.text)
close()
| 44.391534
| 146
| 0.59559
|
983298d7530b47d9b5187a87123587b291df2704
| 789
|
py
|
Python
|
main.py
|
akshay-1612/Twitter_Bot
|
aa527d28252a77a6ca47a9dc4c29d13d3723bae6
|
[
"MIT"
] | null | null | null |
main.py
|
akshay-1612/Twitter_Bot
|
aa527d28252a77a6ca47a9dc4c29d13d3723bae6
|
[
"MIT"
] | null | null | null |
main.py
|
akshay-1612/Twitter_Bot
|
aa527d28252a77a6ca47a9dc4c29d13d3723bae6
|
[
"MIT"
] | 2
|
2021-01-20T06:09:59.000Z
|
2021-10-06T04:13:05.000Z
|
import tweepy
import time
api_key = ''
api_key_secreat = ''
access_token = ''
access_token_secreat =''
auth = tweepy.OAuthHandler(api_key,api_key_secreat)
auth.set_access_token(access_token,access_token_secreat)
api = tweepy.API(auth,wait_on_rate_limit=True,wait_on_rate_limit_notify=True)
user = api.me()
#search =["#python","#ML","#Data Science","#AI"] # search tag
search = "#python"
numTweets = 500 #rate limit
for tweet in tweepy.Cursor(api.search,search,lang="en").items(numTweets):
try:
print('Tweet liked')
tweet.favorite()
print('tweet retweeted')
tweet.retweet()
time.sleep(60*10) #sleep for 10 minutes
except tweepy.TweepError as e:
print(e.reason)
except StopAsyncIteration:
break
| 19.243902
| 77
| 0.674271
|
c3ddc761b71e57f7d84a44d606d052327407f56b
| 761
|
py
|
Python
|
step13_secret_manager/Python/example01_rotate_secret_with_lambda/lambda/index.py
|
fullstackwebdev/full-stack-serverless-cdk
|
798c98300b89cfb5eac6004cd348fa60d05f813b
|
[
"MIT"
] | 192
|
2020-11-01T17:45:01.000Z
|
2022-03-16T08:14:58.000Z
|
step13_secret_manager/Python/example01_rotate_secret_with_lambda/lambda/index.py
|
fullstackwebdev/full-stack-serverless-cdk
|
798c98300b89cfb5eac6004cd348fa60d05f813b
|
[
"MIT"
] | 16
|
2020-11-26T19:15:49.000Z
|
2020-12-27T00:26:21.000Z
|
step13_secret_manager/Python/example01_rotate_secret_with_lambda/lambda/index.py
|
fullstackwebdev/full-stack-serverless-cdk
|
798c98300b89cfb5eac6004cd348fa60d05f813b
|
[
"MIT"
] | 101
|
2020-11-02T08:03:05.000Z
|
2022-03-29T00:55:40.000Z
|
from __future__ import print_function
import os
import json
import boto3
import secrets
secretsManager = boto3.client('secretsmanager', region_name= os.environ['REGION'])
secretName = os.environ['SECRET_NAME']
keyInSecret = os.environ['KEY_IN_SECRET_NAME']
def handler(event, context):
print(event)
session = boto3.session.Session()
client = session.client(
service_name='secretsmanager',
region_name= os.environ['REGION'],
)
if event['Step'] == 'createSecret':
client.put_secret_value(
SecretId= secretName,
SecretString= json.dumps({
keyInSecret : json.dumps(secrets.token_hex(64))
}),
VersionStages=['AWSCURRENT']
)
| 26.241379
| 82
| 0.634691
|
93e0491304c58836491adaf2eefe355f62d8e62e
| 2,304
|
py
|
Python
|
PyBank/main-bank.py
|
gocurry1/python_challenge
|
15717fec6b179ea0a40725fc6d859f995f87c9a2
|
[
"MIT"
] | null | null | null |
PyBank/main-bank.py
|
gocurry1/python_challenge
|
15717fec6b179ea0a40725fc6d859f995f87c9a2
|
[
"MIT"
] | null | null | null |
PyBank/main-bank.py
|
gocurry1/python_challenge
|
15717fec6b179ea0a40725fc6d859f995f87c9a2
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import os
import csv
total_months = 0
net_amount = 0
monthly_change = []
month_count = []
greatest_increase = 0
greatest_increase_month = 0
greatest_decrease = 0
greatest_decrease_month = 0
csvpath = os.path.join('.', 'Resources', 'budget_data.csv')
with open(csvpath, newline='') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
csv_header = next(csvreader)
row = next(csvreader)
previous_row = int(row[1])
total_months += 1
net_amount += int(row[1])
greatest_increase = int(row[1])
greatest_increase_month = row[0]
for row in csvreader:
total_months += 1
net_amount += int(row[1])
revenue_change = int(row[1]) - previous_row
monthly_change.append(revenue_change)
previous_row = int(row[1])
month_count.append(row[0])
if int(row[1]) > greatest_increase:
greatest_increase = int(row[1])
greatest_increase_month = row[0]
if int(row[1]) < greatest_decrease:
greatest_decrease = int(row[1])
greatest_decrease_month = row[0]
average_change = sum(monthly_change)/ len(monthly_change)
highest = max(monthly_change)
lowest = min(monthly_change)
print(f"Financial Analysis")
print(f"---------------------------")
print(f"Total Months: {total_months}")
print(f"Total: ${net_amount}")
print(f"Average Change: ${average_change:.2f}")
print(f"Greatest Increase in Profits:, {greatest_increase_month}, (${highest})")
print(f"Greatest Decrease in Profits:, {greatest_decrease_month}, (${lowest})")
output_file = os.path.join('.', 'analysis', 'pybank_financial_analysis.text')
with open(output_file, 'w',) as txtfile:
txtfile.write(f"Financial Analysis\n")
txtfile.write(f"---------------------------\n")
txtfile.write(f"Total Months: {total_months}\n")
txtfile.write(f"Total: ${net_amount}\n")
txtfile.write(f"Average Change: ${average_change}\n")
txtfile.write(f"Greatest Increase in Profits:, {greatest_increase_month}, (${highest})\n")
txtfile.write(f"Greatest Decrease in Profits:, {greatest_decrease_month}, (${lowest})\n")
# In[ ]:
| 24.252632
| 94
| 0.624132
|
40cdfc331000d9f7ddf122ce575146e3abf699ba
| 6,148
|
py
|
Python
|
dsmr_parser/clients/protocol.py
|
mjkl-gh/dsmr_parser
|
63338fbf06fe96444c814b224f6aaca3d78f4581
|
[
"MIT"
] | null | null | null |
dsmr_parser/clients/protocol.py
|
mjkl-gh/dsmr_parser
|
63338fbf06fe96444c814b224f6aaca3d78f4581
|
[
"MIT"
] | null | null | null |
dsmr_parser/clients/protocol.py
|
mjkl-gh/dsmr_parser
|
63338fbf06fe96444c814b224f6aaca3d78f4581
|
[
"MIT"
] | null | null | null |
"""Asyncio protocol implementation for handling telegrams."""
from functools import partial
import asyncio
import logging
from serial_asyncio import create_serial_connection
from dsmr_parser import telegram_specifications
from dsmr_parser.clients.telegram_buffer import TelegramBuffer
from dsmr_parser.exceptions import ParseError, InvalidChecksumError
from dsmr_parser.parsers import TelegramParser
from dsmr_parser.clients.settings import SERIAL_SETTINGS_V2_2, \
SERIAL_SETTINGS_V4, SERIAL_SETTINGS_V5
def create_dsmr_protocol(dsmr_version, telegram_callback, loop=None, **kwargs):
"""Creates a DSMR asyncio protocol."""
protocol = _create_dsmr_protocol(dsmr_version, telegram_callback,
DSMRProtocol, loop, **kwargs)
return protocol
def _create_dsmr_protocol(dsmr_version, telegram_callback, protocol, loop=None, **kwargs):
"""Creates a DSMR asyncio protocol."""
if dsmr_version == '2.2':
specification = telegram_specifications.V2_2
serial_settings = SERIAL_SETTINGS_V2_2
elif dsmr_version == '4':
specification = telegram_specifications.V4
serial_settings = SERIAL_SETTINGS_V4
elif dsmr_version == '4+':
specification = telegram_specifications.V5
serial_settings = SERIAL_SETTINGS_V4
elif dsmr_version == '5':
specification = telegram_specifications.V5
serial_settings = SERIAL_SETTINGS_V5
elif dsmr_version == '5B':
specification = telegram_specifications.BELGIUM_FLUVIUS
serial_settings = SERIAL_SETTINGS_V5
elif dsmr_version == "5L":
specification = telegram_specifications.LUXEMBOURG_SMARTY
serial_settings = SERIAL_SETTINGS_V5
elif dsmr_version == "5S":
specification = telegram_specifications.SWEDEN
serial_settings = SERIAL_SETTINGS_V5
elif dsmr_version == "Q3D":
specification = telegram_specifications.Q3D
serial_settings = SERIAL_SETTINGS_V5
else:
raise NotImplementedError("No telegram parser found for version: %s",
dsmr_version)
protocol = partial(protocol, loop, TelegramParser(specification),
telegram_callback=telegram_callback, **kwargs)
return protocol, serial_settings
def create_dsmr_reader(port, dsmr_version, telegram_callback, loop=None):
"""Creates a DSMR asyncio protocol coroutine using serial port."""
protocol, serial_settings = create_dsmr_protocol(
dsmr_version, telegram_callback, loop=None)
serial_settings['url'] = port
conn = create_serial_connection(loop, protocol, **serial_settings)
return conn
def create_tcp_dsmr_reader(host, port, dsmr_version,
telegram_callback, loop=None,
keep_alive_interval=None):
"""Creates a DSMR asyncio protocol coroutine using TCP connection."""
if not loop:
loop = asyncio.get_event_loop()
protocol, _ = create_dsmr_protocol(
dsmr_version, telegram_callback, loop=loop,
keep_alive_interval=keep_alive_interval)
conn = loop.create_connection(protocol, host, port)
return conn
class DSMRProtocol(asyncio.Protocol):
"""Assemble and handle incoming data into complete DSM telegrams."""
transport = None
telegram_callback = None
def __init__(self, loop, telegram_parser,
telegram_callback=None, keep_alive_interval=None):
"""Initialize class."""
self.loop = loop
self.log = logging.getLogger(__name__)
self.telegram_parser = telegram_parser
# callback to call on complete telegram
self.telegram_callback = telegram_callback
# buffer to keep incomplete incoming data
self.telegram_buffer = TelegramBuffer()
# keep a lock until the connection is closed
self._closed = asyncio.Event()
self._keep_alive_interval = keep_alive_interval
self._active = True
def connection_made(self, transport):
"""Just logging for now."""
self.transport = transport
self.log.debug('connected')
self._active = False
if self.loop and self._keep_alive_interval:
self.loop.call_later(self._keep_alive_interval, self.keep_alive)
def data_received(self, data):
"""Add incoming data to buffer."""
# accept latin-1 (8-bit) on the line, to allow for non-ascii transport or padding
data = data.decode("latin1")
self._active = True
self.log.debug('received data: %s', data)
self.telegram_buffer.append(data)
for telegram in self.telegram_buffer.get_all():
# ensure actual telegram is ascii (7-bit) only (ISO 646:1991 IRV required in section 5.5 of IEC 62056-21)
telegram = telegram.encode("latin1").decode("ascii")
self.handle_telegram(telegram)
def keep_alive(self):
if self._active:
self.log.debug('keep-alive checked')
self._active = False
if self.loop:
self.loop.call_later(self._keep_alive_interval, self.keep_alive)
else:
self.log.warning('keep-alive check failed')
if self.transport:
self.transport.close()
def connection_lost(self, exc):
"""Stop when connection is lost."""
if exc:
self.log.exception('disconnected due to exception', exc_info=exc)
else:
self.log.info('disconnected because of close/abort.')
self._closed.set()
def handle_telegram(self, telegram):
"""Send off parsed telegram to handling callback."""
self.log.debug('got telegram: %s', telegram)
try:
parsed_telegram = self.telegram_parser.parse(telegram)
except InvalidChecksumError as e:
self.log.warning(str(e))
except ParseError:
self.log.exception("failed to parse telegram")
else:
self.telegram_callback(parsed_telegram)
async def wait_closed(self):
"""Wait until connection is closed."""
await self._closed.wait()
| 37.950617
| 117
| 0.675992
|
6e38d1e07486bbd81e80de1f3b3d8a5d30c05618
| 5,376
|
py
|
Python
|
nipyapi/registry/models/extension_repo_artifact.py
|
Jimvin/nipyapi
|
826beac376d4321bd2d69491f09086474c7e7bfb
|
[
"Apache-2.0"
] | 199
|
2017-08-24T12:19:41.000Z
|
2022-03-20T14:50:17.000Z
|
nipyapi/registry/models/extension_repo_artifact.py
|
Jimvin/nipyapi
|
826beac376d4321bd2d69491f09086474c7e7bfb
|
[
"Apache-2.0"
] | 275
|
2017-08-28T21:21:49.000Z
|
2022-03-29T17:57:26.000Z
|
nipyapi/registry/models/extension_repo_artifact.py
|
Jimvin/nipyapi
|
826beac376d4321bd2d69491f09086474c7e7bfb
|
[
"Apache-2.0"
] | 73
|
2017-09-07T10:13:56.000Z
|
2022-02-28T10:37:21.000Z
|
# coding: utf-8
"""
Apache NiFi Registry REST API
The REST API provides an interface to a registry with operations for saving, versioning, reading NiFi flows and components.
OpenAPI spec version: 1.15.0
Contact: dev@nifi.apache.org
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class ExtensionRepoArtifact(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'link': 'JaxbLink',
'bucket_name': 'str',
'group_id': 'str',
'artifact_id': 'str'
}
attribute_map = {
'link': 'link',
'bucket_name': 'bucketName',
'group_id': 'groupId',
'artifact_id': 'artifactId'
}
def __init__(self, link=None, bucket_name=None, group_id=None, artifact_id=None):
"""
ExtensionRepoArtifact - a model defined in Swagger
"""
self._link = None
self._bucket_name = None
self._group_id = None
self._artifact_id = None
if link is not None:
self.link = link
if bucket_name is not None:
self.bucket_name = bucket_name
if group_id is not None:
self.group_id = group_id
if artifact_id is not None:
self.artifact_id = artifact_id
@property
def link(self):
"""
Gets the link of this ExtensionRepoArtifact.
An WebLink to this entity.
:return: The link of this ExtensionRepoArtifact.
:rtype: JaxbLink
"""
return self._link
@link.setter
def link(self, link):
"""
Sets the link of this ExtensionRepoArtifact.
An WebLink to this entity.
:param link: The link of this ExtensionRepoArtifact.
:type: JaxbLink
"""
self._link = link
@property
def bucket_name(self):
"""
Gets the bucket_name of this ExtensionRepoArtifact.
The bucket name
:return: The bucket_name of this ExtensionRepoArtifact.
:rtype: str
"""
return self._bucket_name
@bucket_name.setter
def bucket_name(self, bucket_name):
"""
Sets the bucket_name of this ExtensionRepoArtifact.
The bucket name
:param bucket_name: The bucket_name of this ExtensionRepoArtifact.
:type: str
"""
self._bucket_name = bucket_name
@property
def group_id(self):
"""
Gets the group_id of this ExtensionRepoArtifact.
The group id
:return: The group_id of this ExtensionRepoArtifact.
:rtype: str
"""
return self._group_id
@group_id.setter
def group_id(self, group_id):
"""
Sets the group_id of this ExtensionRepoArtifact.
The group id
:param group_id: The group_id of this ExtensionRepoArtifact.
:type: str
"""
self._group_id = group_id
@property
def artifact_id(self):
"""
Gets the artifact_id of this ExtensionRepoArtifact.
The artifact id
:return: The artifact_id of this ExtensionRepoArtifact.
:rtype: str
"""
return self._artifact_id
@artifact_id.setter
def artifact_id(self, artifact_id):
"""
Sets the artifact_id of this ExtensionRepoArtifact.
The artifact id
:param artifact_id: The artifact_id of this ExtensionRepoArtifact.
:type: str
"""
self._artifact_id = artifact_id
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
if not isinstance(other, ExtensionRepoArtifact):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
| 25.6
| 127
| 0.567894
|
10bde5119dead7aef2e791df1241d226f176e8cd
| 49
|
py
|
Python
|
tests/__init__.py
|
ahmed-shariff/acm-dl-hci-searcher-
|
0c2b683d0440fe6240e2a660ccc1c92461180f1e
|
[
"MIT"
] | null | null | null |
tests/__init__.py
|
ahmed-shariff/acm-dl-hci-searcher-
|
0c2b683d0440fe6240e2a660ccc1c92461180f1e
|
[
"MIT"
] | null | null | null |
tests/__init__.py
|
ahmed-shariff/acm-dl-hci-searcher-
|
0c2b683d0440fe6240e2a660ccc1c92461180f1e
|
[
"MIT"
] | null | null | null |
"""Unit test package for acm_dl_hci_searcher."""
| 24.5
| 48
| 0.755102
|
2a8c2657da3340e273f57686ff8417e6dc429390
| 9,509
|
py
|
Python
|
romp/lib/maps_utils/centermap.py
|
iory/ROMP
|
d50bab681b5a60d15526fbeec1ed98cb020864b2
|
[
"MIT"
] | null | null | null |
romp/lib/maps_utils/centermap.py
|
iory/ROMP
|
d50bab681b5a60d15526fbeec1ed98cb020864b2
|
[
"MIT"
] | null | null | null |
romp/lib/maps_utils/centermap.py
|
iory/ROMP
|
d50bab681b5a60d15526fbeec1ed98cb020864b2
|
[
"MIT"
] | null | null | null |
import torch
import sys,os
import numpy as np
sys.path.append(os.path.abspath(__file__).replace('maps_utils/centermap.py',''))
from config import args
class CenterMap(object):
def __init__(self,style='heatmap_adaptive_scale'):
self.style=style
self.size = args().centermap_size
self.max_person = args().max_person
self.shrink_scale = float(args().input_size//self.size)
self.dims = 1
self.sigma = 1
self.conf_thresh= args().centermap_conf_thresh
self.gk_group, self.pool_group = self.generate_kernels(args().kernel_sizes)
if args().model_version>4:
self.prepare_parsing()
def prepare_parsing(self):
self.coordmap_3d = get_3Dcoord_maps(size=self.size)
self.maxpool3d = torch.nn.MaxPool3d(5, 1, (5-1)//2)
def generate_kernels(self, kernel_size_list):
gk_group, pool_group = {}, {}
for kernel_size in set(kernel_size_list):
x = np.arange(0, kernel_size, 1, float)
y = x[:, np.newaxis]
x0, y0 = (kernel_size-1)//2,(kernel_size-1)//2
gaussian_distribution = - ((x - x0) ** 2 + (y - y0) ** 2) / (2 * self.sigma ** 2)
gk_group[kernel_size] = np.exp(gaussian_distribution)
pool_group[kernel_size] = torch.nn.MaxPool2d(kernel_size, 1, (kernel_size-1)//2)
return gk_group, pool_group
def process_gt_CAM(self, center_normed):
center_list = []
valid_mask = center_normed[:,:,0]>-1
valid_inds = torch.where(valid_mask)
valid_batch_inds, valid_person_ids = valid_inds[0], valid_inds[1]
center_gt = ((center_normed+1)/2*self.size).long()
center_gt_valid = center_gt[valid_mask]
return (valid_batch_inds, valid_person_ids, center_gt_valid)
def generate_centermap(self, center_locs, **kwargs):
return self.generate_centermap_heatmap_adaptive_scale(center_locs, **kwargs)
def parse_centermap(self, center_map):
return self.parse_centermap_heatmap_adaptive_scale_batch(center_map)
def generate_centermap_heatmap_adaptive_scale(self, center_locs, bboxes_hw_norm, occluded_by_who=None,**kwargs):
'''
center_locs is in the order of (y,x), corresponding to (w,h), while in the loading data, we have rectified it to the correct (x, y) order
'''
radius_list = _calc_radius_(bboxes_hw_norm)
if args().collision_aware_centermap and occluded_by_who is not None:
# CAR : Collision-Aware Represenation
for cur_idx, occluded_idx in enumerate(occluded_by_who):
if occluded_idx>-1:
dist_onmap = np.sqrt(((center_locs[occluded_idx]-center_locs[cur_idx])**2).sum()) + 1e-4
least_dist = (radius_list[occluded_idx]+radius_list[cur_idx]+1)/self.size*2
if dist_onmap<least_dist:
offset = np.abs(((radius_list[occluded_idx]+radius_list[cur_idx]+1)/self.size*2-dist_onmap)/dist_onmap) \
* (center_locs[occluded_idx]-center_locs[cur_idx]+ 1e-4) * args().collision_factor
center_locs[cur_idx] -= offset/2
center_locs[occluded_idx] += offset/2
# restrcit the range from -1 to 1
center_locs = np.clip(center_locs, -1, 1)
center_locs[center_locs==-1] = -0.96
center_locs[center_locs==1] = 0.96
heatmap = self.generate_heatmap_adaptive_scale(center_locs, radius_list)
heatmap = torch.from_numpy(heatmap)
return heatmap
def generate_heatmap_adaptive_scale(self,center_locs, radius_list,k=1):
heatmap = np.zeros((1, self.size, self.size),dtype=np.float32)
for center, radius in zip(center_locs,radius_list):
diameter = 2 * radius + 1
gaussian = gaussian2D((diameter, diameter), sigma=float(diameter) / 6)
x, y = int((center[0]+1)/2*self.size), int((center[1]+1)/2*self.size)
if x < 0 or y < 0 or x >= self.size or y >= self.size:
continue
height, width = heatmap.shape[1:]
left, right = min(x, radius), min(width - x, radius + 1)
top, bottom = min(y, radius), min(height - y, radius + 1)
masked_heatmap = heatmap[0,y - top:y + bottom, x - left:x + right]
masked_gaussian = gaussian[radius - top:radius + bottom, radius - left:radius + right]
if min(masked_gaussian.shape) > 0 and min(masked_heatmap.shape) > 0: # TODO debug
np.maximum(masked_heatmap, masked_gaussian * k, out=masked_heatmap)
heatmap[0, y, x]=1
return heatmap
def parse_centermap_heatmap_adaptive_scale(self, center_maps):
center_map_nms = nms(center_maps, pool_func=self.pool_group[args().kernel_sizes[-1]])[0]
h, w = center_map_nms.shape
centermap = center_map_nms.view(-1)
confidence, index = centermap.topk(self.max_person)
x = index%w
y = (index/float(w)).long()
idx_topk = torch.stack((y,x),dim=1)
centers_pred, conf_pred = idx_topk[confidence>self.conf_thresh], confidence[confidence>self.conf_thresh]
return centers_pred, conf_pred
def parse_centermap_heatmap_adaptive_scale_batch(self, center_maps):
center_map_nms = nms(center_maps, pool_func=self.pool_group[args().kernel_sizes[-1]])
b, c, h, w = center_map_nms.shape
K = self.max_person
topk_scores, topk_inds = torch.topk(center_map_nms.reshape(b, c, -1), K)
topk_inds = topk_inds % (h * w)
topk_ys = (topk_inds // w).int().float()
topk_xs = (topk_inds % w).int().float()
# get all topk in in a batch
topk_score, index = torch.topk(topk_scores.reshape(b, -1), K)
# div by K because index is grouped by K(C x K shape)
topk_clses = (index // K).int()
topk_inds = gather_feature(topk_inds.view(b, -1, 1), index).reshape(b, K)
topk_ys = gather_feature(topk_ys.reshape(b, -1, 1), index).reshape(b, K)
topk_xs = gather_feature(topk_xs.reshape(b, -1, 1), index).reshape(b, K)
mask = topk_score>self.conf_thresh
batch_ids = torch.where(mask)[0]
center_yxs = torch.stack([topk_ys[mask], topk_xs[mask]]).permute((1,0))
return batch_ids, topk_inds[mask], center_yxs, topk_score[mask]
def nms(det, pool_func=None):
maxm = pool_func(det)
maxm = torch.eq(maxm, det).float()
det = det * maxm
return det
def _calc_radius_(bboxes_hw_norm):
radius_list = []
for bbox_norm in bboxes_hw_norm:
# bbox_hw is the bbox_height/image_height
bbox_hw_oncm = (bbox_norm+1)/2*args().centermap_size
radius = int(gaussian_radius_scale(bbox_hw_oncm,minimum=2.))
radius_list.append(radius)
return radius_list
def gather_feature(fmap, index, mask=None, use_transform=False):
if use_transform:
# change a (N, C, H, W) tenor to (N, HxW, C) shape
batch, channel = fmap.shape[:2]
fmap = fmap.view(batch, channel, -1).permute((0, 2, 1)).contiguous()
dim = fmap.size(-1)
index = index.unsqueeze(len(index.shape)).expand(*index.shape, dim)
fmap = fmap.gather(dim=1, index=index)
if mask is not None:
mask = mask.unsqueeze(2).expand_as(fmap)
fmap = fmap[mask]
fmap = fmap.reshape(-1, dim)
return fmap
def gaussian_radius_scale(det_size, min_overlap=0.3, k_low=1, k_range=7, minimum=2.):
# min_overlap reduce the radius when multiple person gathered togather to avoid center ambiguous.
height, width = det_size
bbox_size = np.sqrt(height**2+width**2)
radius = k_low + k_range * (bbox_size/(args().centermap_size*np.sqrt(2)))**2
return max(radius,minimum)
def gaussian2D(shape, sigma=1):
m, n = [(ss - 1.) / 2. for ss in shape]
y, x = np.ogrid[-m:m+1,-n:n+1]
h = np.exp(-(x * x + y * y) / (2 * sigma * sigma))
h[h < np.finfo(h.dtype).eps * h.max()] = 0
return h
def process_center(center_gt, centermap):
center_list = []
center_locs = torch.stack(torch.where(centermap[0]>0.25)).transpose(1,0)
dists = []
for center in center_gt:
dists.append(torch.norm(center_locs.float()-center[None].float(),dim=1))
dists = torch.stack(dists)
assign_id = torch.argmin(dists,0)
for center_id in range(len(center_gt)):
center_list.append(center_locs[assign_id==center_id])
return center_list
def print_matrix(matrix):
for k in matrix:
print_item = ''
for i in k:
print_item+='{:.2f} '.format(i)
print(print_item)
def test_centermaps():
batch_size = 2
CM = CenterMap()
CM.size=16
center_locs = np.array([[0,0],[-0.3,-0.7]])
bboxes = [np.array([0.2,0.3]),np.array([0.5,0.4])]
centermaps = []
for i in range(batch_size):
centermaps.append(torch.from_numpy(CM.generate_centermap(center_locs,bboxes_hw_norm=bboxes)))
centermaps = torch.stack(centermaps).cuda()
print_matrix(centermaps[0,0])
print('__'*10)
results = CM.parse_centermap_heatmap_adaptive_scale_batch(centermaps)
print(results)
#5CM.print_matrix(torch.nn.functional.softmax(centermap,1)[0])
for i in range(batch_size):
result = CM.parse_centermap(centermaps[i])
print(result)
center_list = process_center(result[0], centermaps[i])
print(center_list)
if __name__ == '__main__':
test_centermaps()
| 41.524017
| 148
| 0.637712
|
e44981d07c3ec290b13a182112575fa864d94fe7
| 6,576
|
py
|
Python
|
scripts/plot_hotfilm_stress_exp1.py
|
sustain-lab/asist-nsf-2018
|
2691bf7dc9d411e35db4e5a6c28d98f71730bee8
|
[
"MIT"
] | 1
|
2018-10-09T22:18:16.000Z
|
2018-10-09T22:18:16.000Z
|
scripts/plot_hotfilm_stress_exp1.py
|
sustain-lab/asist-nsf-2018
|
2691bf7dc9d411e35db4e5a6c28d98f71730bee8
|
[
"MIT"
] | null | null | null |
scripts/plot_hotfilm_stress_exp1.py
|
sustain-lab/asist-nsf-2018
|
2691bf7dc9d411e35db4e5a6c28d98f71730bee8
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python3
"""
Processes raw hotfilm voltages to velocities.
"""
from asist_nsf_2018.experiments import experiments
from asist_nsf_2018.process_level2 import clean_hotfilm_exp1
from asist.utility import binavg, limit_to_percentile_range, running_mean
from asist.hotfilm import effective_velocity, hotfilm_velocity, read_hotfilm_from_netcdf
from asist.pitot import read_pitot_from_netcdf
from datetime import datetime, timedelta
import numpy as np
import os
import matplotlib.pyplot as plt
def hotfilm_velocity(veff1, veff2, k1=0.3, k2=0.3):
"""For a pair effective velocities from wire 1 and 2,
calculates u and w components."""
un = np.sqrt((veff1**2 - k1**2 * veff2**2) / (1 - k1**2 * k2**2))
ut = np.sqrt((veff2**2 - k2**2 * veff1**2) / (1 - k1**2 * k2**2))
u = (ut + un) / np.sqrt(2.)
w = (ut - un) / np.sqrt(2.)
return u, w
def smooth_ust(u, z):
"""Given input velocity u at height z,
returns friction velocity of the smooth flow."""
z0 = 1e-3
kappa = 0.4
nu_air = 1.56e-5
for i in range(20):
ust = kappa * u / np.log(z / z0)
z0 = 0.132 * nu_air / ust
return ust
def rotate(u, w, th):
"""Rotates the vector (u, w) by angle th."""
ur = np.cos(th) * u + np.sin(th) * w
wr = -np.sin(th) * u + np.cos(th) * w
return ur, wr
plt.rcParams.update({'font.size': 16}) # global font size setting
np.warnings.filterwarnings('ignore') # ignore numpy warnings
L2_DATA_PATH = os.environ['L2_DATA_PATH']
exp_name = 'asist-windonly-fresh'
exp = experiments[exp_name]
origin, hotfilm_seconds, fan, ch1, ch2 = read_hotfilm_from_netcdf(L2_DATA_PATH + '/hotfilm_' + exp_name + '.nc')
origin, pitot_seconds, fan, u_pitot = read_pitot_from_netcdf(L2_DATA_PATH + '/pitot_' + exp_name + '.nc')
ch1, ch2 = clean_hotfilm_exp1(exp, ch1, ch2, hotfilm_seconds)
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111)
plt.plot(hotfilm_seconds, ch1, 'b-', lw=0.5, label='Channel 1')
plt.plot(hotfilm_seconds, ch2, 'r-', lw=0.5, label='Channel 2')
plt.legend(loc='upper left', fancybox=True, shadow=True)
plt.grid(True)
plt.xlabel('Time [s]')
plt.ylabel('Hot film output [V]')
plt.title('Raw hot film output [V], cleaned, ' + exp_name)
plt.savefig('hotfilm_output_' + exp_name + '.png', dpi=100)
plt.close(fig)
# start and end time of fitting period
t0 = exp.runs[1].start_time + timedelta(seconds=60)
t1 = exp.runs[-2].end_time
# start and end seconds of fitting period
t0_seconds = (t0 - origin).total_seconds()
t1_seconds = (t1 - origin).total_seconds()
# start index of pitot and hotfilm time series
n0 = np.argmin((pitot_seconds - t0_seconds)**2)
n1 = np.argmin((pitot_seconds - t1_seconds)**2)
pitot = u_pitot[n0-1:n1] # special case to handle dropped records in pressure files
n0 = np.argmin((hotfilm_seconds - t0_seconds)**2)
n1 = np.argmin((hotfilm_seconds - t1_seconds)**2)
ch1_binavg = binavg(ch1[n0:n1], 100)
ch2_binavg = binavg(ch2[n0:n1], 100)
# 4-th order polynomial -- ordered highest to lowest degree
p1 = np.polyfit(ch1_binavg, effective_velocity(pitot), 4)
p2 = np.polyfit(ch2_binavg, effective_velocity(pitot), 4)
# compute effective velocities
veff1 = np.polyval(p1, ch1)
veff2 = np.polyval(p2, ch2)
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111)
plt.plot(ch1_binavg, effective_velocity(pitot), 'k.', ms=0.1)
plt.plot(ch1, veff1, 'r.', ms=0.1)
plt.grid(True)
plt.xlabel('Input voltage [V]')
plt.ylabel('Velocity [m/s]')
plt.title('Polyfit of Ch1 -> pitot, ' + exp_name)
plt.savefig('hotfilm_ch1_polyfit_' + exp_name + '.png', dpi=100)
plt.close(fig)
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111)
plt.plot(ch2_binavg, effective_velocity(pitot), 'k.', ms=0.1)
plt.plot(ch2, veff2, 'r.', ms=0.1)
plt.grid(True)
plt.xlabel('Input voltage [V]')
plt.ylabel('Velocity [m/s]')
plt.title('Polyfit of Ch2 -> pitot, ' + exp_name)
plt.savefig('hotfilm_ch2_polyfit_' + exp_name + '.png', dpi=100)
plt.close(fig)
veff1[veff1 < 0.2] = 0.2
veff2[veff2 < 0.2] = 0.2
u, w = hotfilm_velocity(veff1, veff2)
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111)
plt.plot(hotfilm_seconds, u, 'b-', lw=0.1)
plt.plot(hotfilm_seconds, w, 'r-', lw=0.1)
plt.grid(True)
plt.xlabel('Time [s]')
plt.ylabel('Velocity [m/s]')
plt.title('Hot film velocity, ' + exp_name)
plt.savefig('hotfilm_velocity_' + exp_name + '.png', dpi=100)
plt.close(fig)
# averaging over full runs (5 minutes)
U, W, uw = [], [], []
for run in exp.runs[1:-1]:
t0 = run.start_time + timedelta(seconds=30)
t1 = run.end_time - timedelta(seconds=30)
t0_seconds = (t0 - origin).total_seconds()
t1_seconds = (t1 - origin).total_seconds()
mask = (hotfilm_seconds > t0_seconds) & (hotfilm_seconds < t1_seconds)
um, wm = np.mean(u[mask]), np.mean(w[mask])
U.append(um)
W.append(wm)
th = np.arctan2(wm, um)
up, wp = rotate(u[mask] - um, w[mask] - wm, th)
uw.append(np.mean(up * wp))
U = np.array(U)
W = np.array(W)
uw = np.array(uw)
ustc = smooth_ust(U, 0.31)
uwc = ustc**2
# averaging over 60-s bins:
U, W, uw = [], [], []
for run in exp.runs[1:-1]:
t0 = run.start_time + timedelta(seconds=30)
t1 = run.end_time - timedelta(seconds=30)
t0_seconds = (t0 - origin).total_seconds()
t1_seconds = (t1 - origin).total_seconds()
binsize = 60.
for tt in np.arange(t0_seconds, t1_seconds, binsize):
start, stop = tt, tt + binsize
mask = (hotfilm_seconds > start) & (hotfilm_seconds < stop)
um, wm = np.mean(u[mask]), np.mean(w[mask])
U.append(um)
W.append(wm)
uw.append(np.mean((u[mask] - um) * (w[mask] - wm)))
U = np.array(U)
W = np.array(W)
uw = np.array(uw)
ust = np.sqrt(- uw)
Cd = ust**2 / U**2
# u* vs U
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, xlim=(0, 35))
plt.plot(U, ust, 'k.', ms=12)
plt.xlabel(r'$U_z$ [m/s]')
plt.ylabel(r'$u^*$ [m/s]')
plt.grid()
plt.title(r'Hotfilm $u*$, fresh water')
plt.savefig('ust_hotfilm_fresh.png', dpi=100)
plt.close(fig)
# u'w' vs U
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, xlim=(0, 35))
plt.plot(U, -uw, 'k.', ms=12)
plt.xlabel(r'$U_z$ [m/s]')
plt.ylabel(r"$\overline{u'w'}$ [m/s]")
plt.grid()
plt.title(r"Hotfilm $\overline{u'w'}$, fresh water")
plt.savefig('uw_hotfilm_fresh.png', dpi=100)
plt.close(fig)
# Cd vs U
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, xlim=(0, 35), ylim=(0, 3e-3))
plt.plot(U, Cd, 'k.', ms=12)
plt.xlabel(r'$U_z$ [m/s]')
plt.ylabel(r"$C_D$")
plt.grid()
plt.title(r"Hotfilm $C_D$, fresh water")
plt.savefig('cd_hotfilm_fresh.png', dpi=100)
plt.close(fig)
| 32.078049
| 112
| 0.663321
|
a23f3f21958bd85503b67fb5a60a8d74bd5472b8
| 2,060
|
py
|
Python
|
src/scheduler/srt_scheduler.py
|
PatrickShaw/University-FIT2070-Assignment3
|
c45ed79ef35abb740b9591ef712a2d0eb1627592
|
[
"MIT"
] | 2
|
2021-05-14T08:30:06.000Z
|
2021-05-14T08:30:08.000Z
|
src/scheduler/srt_scheduler.py
|
PatrickShaw/scheduling-simulator
|
c45ed79ef35abb740b9591ef712a2d0eb1627592
|
[
"MIT"
] | null | null | null |
src/scheduler/srt_scheduler.py
|
PatrickShaw/scheduling-simulator
|
c45ed79ef35abb740b9591ef712a2d0eb1627592
|
[
"MIT"
] | null | null | null |
from scheduler.fcfs_scheduler import FirstComeFirstServedScheduler
from scheduler.process import Process
class ShortestRemainingTimeScheduler(FirstComeFirstServedScheduler):
"""
A preemptive scheduler that executes whichever process is estimated to finish first.
Note that the FCFS scheduler's increase_time(...) method is utilised for this scheduler since the preemption and
shortest remaining times are calculated during the enqueuing of the process.
"""
def enqueue_process(self, process: Process):
"""
Enqueues a process for execution such that the queue remains ordered by the remaining time, starting from
the shortest remaining time to the longest remaining time.
:param process:
The process to be enqueued by the scheduler
"""
self._on_process_enqueuing(process)
if self._executing_process is not None:
if self._executing_process.remaining_time > process.remaining_time:
"""
If the currently executing process is estimated to finish after the newly enqueued process, then
preempt the process and push it back onto the start of the ready queue.
Allow the new process to start executing (since it is estimated to finish first)
"""
self._ready_queue.appendleft(self._executing_process)
self._executing_process = process
return
# Figure out where abouts this process belongs within the queue
for p in range(len(self._ready_queue)-1, -1, -1):
other_process = self._ready_queue[p]
if other_process.remaining_time <= process.remaining_time:
self._ready_queue.insert(p + 1, process)
return
"""
At this point the process must belong at the start of the queue since we already checked if it was meant to be
executing and we checked everywhere else along the queue.
"""
self._ready_queue.appendleft(process)
| 50.243902
| 118
| 0.674272
|
3d165cc5d512dcfb88319e529b19655783e6a0bb
| 5,928
|
py
|
Python
|
tourism_train.py
|
sanowar-raihan/nerf-meta
|
dbb97431b613acb3dfdc7075344c6e1fd1b6cf51
|
[
"MIT"
] | 60
|
2021-05-10T20:06:10.000Z
|
2022-02-22T09:25:56.000Z
|
tourism_train.py
|
sanowar-raihan/nerf-meta
|
dbb97431b613acb3dfdc7075344c6e1fd1b6cf51
|
[
"MIT"
] | 3
|
2021-05-21T02:21:47.000Z
|
2021-05-27T20:32:00.000Z
|
tourism_train.py
|
sanowar-raihan/nerf-meta
|
dbb97431b613acb3dfdc7075344c6e1fd1b6cf51
|
[
"MIT"
] | 8
|
2021-05-14T01:43:34.000Z
|
2022-01-26T22:58:27.000Z
|
import argparse
import json
import copy
import torch
import torch.nn.functional as F
from torch.utils.data import DataLoader
from datasets.phototourism import build_tourism
from models.nerf import build_nerf
from models.rendering import get_rays_tourism, sample_points, volume_render
def inner_loop(model, optim, img, rays_o, rays_d, bound, num_samples, raybatch_size, inner_steps):
"""
train the inner model for a specified number of iterations
"""
pixels = img.reshape(-1, 3)
rays_o, rays_d = rays_o.reshape(-1, 3), rays_d.reshape(-1, 3)
num_rays = rays_d.shape[0]
for step in range(inner_steps):
indices = torch.randint(num_rays, size=[raybatch_size])
raybatch_o, raybatch_d = rays_o[indices], rays_d[indices]
pixelbatch = pixels[indices]
t_vals, xyz = sample_points(raybatch_o, raybatch_d, bound[0], bound[1],
num_samples, perturb=True)
optim.zero_grad()
rgbs, sigmas = model(xyz)
colors = volume_render(rgbs, sigmas, t_vals)
loss = F.mse_loss(colors, pixelbatch)
loss.backward()
optim.step()
def train_meta(args, meta_model, meta_optim, data_loader, device):
"""
train the meta_model for one epoch using reptile meta learning
https://arxiv.org/abs/1803.02999
"""
for img, pose, kinv, bound in data_loader:
img, pose, kinv, bound = img.to(device), pose.to(device), kinv.to(device), bound.to(device)
img, pose, kinv, bound = img.squeeze(), pose.squeeze(), kinv.squeeze(), bound.squeeze()
rays_o, rays_d = get_rays_tourism(img.shape[0], img.shape[1], kinv, pose)
meta_optim.zero_grad()
inner_model = copy.deepcopy(meta_model)
inner_optim = torch.optim.SGD(inner_model.parameters(), args.inner_lr)
inner_loop(inner_model, inner_optim, img, rays_o, rays_d, bound,
args.num_samples, args.train_batchsize, args.inner_steps)
with torch.no_grad():
for meta_param, inner_param in zip(meta_model.parameters(), inner_model.parameters()):
meta_param.grad = meta_param - inner_param
meta_optim.step()
def report_result(model, img, rays_o, rays_d, bound, num_samples, raybatch_size):
"""
report synthesis result on heldout view
"""
pixels = img.reshape(-1, 3)
rays_o, rays_d = rays_o.reshape(-1, 3), rays_d.reshape(-1, 3)
t_vals, xyz = sample_points(rays_o, rays_d, bound[0], bound[1],
num_samples, perturb=False)
synth = []
num_rays = rays_d.shape[0]
with torch.no_grad():
for i in range(0, num_rays, raybatch_size):
rgbs_batch, sigmas_batch = model(xyz[i:i+raybatch_size])
color_batch = volume_render(rgbs_batch, sigmas_batch, t_vals[i:i+raybatch_size])
synth.append(color_batch)
synth = torch.cat(synth, dim=0)
error = F.mse_loss(synth, pixels)
psnr = -10*torch.log10(error)
return psnr
def val_meta(args, model, val_loader, device):
"""
validate the meta trained model for phototourism
"""
meta_trained_state = model.state_dict()
val_model = copy.deepcopy(model)
val_psnrs = []
for img, pose, kinv, bound in val_loader:
img, pose, kinv, bound = img.to(device), pose.to(device), kinv.to(device), bound.to(device)
img, pose, kinv, bound = img.squeeze(), pose.squeeze(), kinv.squeeze(), bound.squeeze()
rays_o, rays_d = get_rays_tourism(img.shape[0], img.shape[1], kinv, pose)
# optimize on the left half, test on the right half
left_width = img.shape[1]//2
right_width = img.shape[1] - left_width
tto_img, test_img = torch.split(img, [left_width, right_width], dim=1)
tto_rays_o, test_rays_o = torch.split(rays_o, [left_width, right_width], dim=1)
tto_rays_d, test_rays_d = torch.split(rays_d, [left_width, right_width], dim=1)
val_model.load_state_dict(meta_trained_state)
val_optim = torch.optim.SGD(val_model.parameters(), args.inner_lr)
inner_loop(val_model, val_optim, tto_img, tto_rays_o, tto_rays_d,
bound, args.num_samples, args.train_batchsize, args.inner_steps)
psnr = report_result(val_model, test_img, test_rays_o, test_rays_d, bound,
args.num_samples, args.test_batchsize)
val_psnrs.append(psnr)
val_psnr = torch.stack(val_psnrs).mean()
return val_psnr
def main():
parser = argparse.ArgumentParser(description='phototourism with meta-learning')
parser.add_argument('--config', type=str, required=True,
help='config file for the scene')
args = parser.parse_args()
with open(args.config) as config:
info = json.load(config)
for key, value in info.items():
args.__dict__[key] = value
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
train_set = build_tourism(image_set="train", args=args)
train_loader = DataLoader(train_set, batch_size=1, shuffle=True)
val_set = build_tourism(image_set="val", args=args)
val_loader = DataLoader(val_set, batch_size=1, shuffle=False)
meta_model = build_nerf(args)
meta_model.to(device)
meta_optim = torch.optim.Adam(meta_model.parameters(), lr=args.meta_lr)
for epoch in range(1, args.meta_epochs+1):
train_meta(args, meta_model, meta_optim, train_loader, device)
val_psnr = val_meta(args, meta_model, val_loader, device)
print(f"Epoch: {epoch}, val psnr: {val_psnr:0.3f}")
torch.save({
'epoch': epoch,
'meta_model_state_dict': meta_model.state_dict(),
'meta_optim_state_dict': meta_optim.state_dict(),
}, f'meta_epoch{epoch}.pth')
if __name__ == '__main__':
main()
| 38.245161
| 99
| 0.65081
|
ce7944f454fdfdfd0876dd9115c3e19165f61eae
| 1,120
|
py
|
Python
|
python_code_tips/misc/example1.py
|
zdh45222/2021MyDevNet
|
d9b739675e1550d488b42af74f70a283c8fc9554
|
[
"MIT"
] | 156
|
2018-07-19T06:56:58.000Z
|
2022-03-20T19:30:57.000Z
|
python_code_tips/misc/example1.py
|
zdh45222/2021MyDevNet
|
d9b739675e1550d488b42af74f70a283c8fc9554
|
[
"MIT"
] | 4
|
2021-04-07T23:22:30.000Z
|
2021-09-23T23:29:58.000Z
|
python_code_tips/misc/example1.py
|
zdh45222/2021MyDevNet
|
d9b739675e1550d488b42af74f70a283c8fc9554
|
[
"MIT"
] | 130
|
2018-09-13T09:26:38.000Z
|
2022-03-20T19:34:48.000Z
|
#! /usr/bin/env python
"""Example Python script.
Copyright (c) 2018 Cisco and/or its affiliates."""
import os
def say_hello(name):
"""Function that will say hello to someone.
"""
# Print out a hello message to the name given
print("Hello there {name}. It's great to see you.".format(name = name))
def script_details():
"""Function that reports by printing to screen some details about the execution of the script."""
# Get the current directory and print it out.
cur_dir = os.getcwd()
print("Current directory is {}".format(cur_dir))
# Get the User ID and Group List for the User
user_id = os.getuid()
group_list = os.getgroups()
# Print to screen
print("The user id is {}".format(user_id))
print("The user is a member of the following groups:")
print(",".join(str(g) for g in group_list))
if __name__ == "__main__":
# If executed as a script, run this block.
# Check Script details
script_details()
# List of names, and say hello to them
names = ["Hank","Eric","Stuart","Bryan"]
for name in names:
say_hello(name)
| 26.046512
| 101
| 0.654464
|
2108ef1f85af5f5daf2c39855b2c64ed825311b7
| 3,773
|
py
|
Python
|
test/functional/p2p_dos_header_tree.py
|
TriCron/shirecoin
|
50ab7e5b7dc32350e4bcbe33ad728b3926212e5a
|
[
"MIT"
] | null | null | null |
test/functional/p2p_dos_header_tree.py
|
TriCron/shirecoin
|
50ab7e5b7dc32350e4bcbe33ad728b3926212e5a
|
[
"MIT"
] | null | null | null |
test/functional/p2p_dos_header_tree.py
|
TriCron/shirecoin
|
50ab7e5b7dc32350e4bcbe33ad728b3926212e5a
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python3
# Copyright (c) 2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test that we reject low difficulty headers to prevent our block tree from filling up with useless bloat"""
from test_framework.messages import (
CBlockHeader,
FromHex,
)
from test_framework.mininode import (
P2PInterface,
msg_headers,
)
from test_framework.test_framework import ShirecoinTestFramework
import os
class RejectLowDifficultyHeadersTest(ShirecoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.chain = 'testnet3' # Use testnet chain because it has an early checkpoint
self.num_nodes = 2
def add_options(self, parser):
parser.add_argument(
'--datafile',
default='data/blockheader_testnet3.hex',
help='Test data file (default: %(default)s)',
)
def run_test(self):
self.log.info("Read headers data")
self.headers_file_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), self.options.datafile)
with open(self.headers_file_path, encoding='utf-8') as headers_data:
h_lines = [l.strip() for l in headers_data.readlines()]
# The headers data is taken from testnet3 for early blocks from genesis until the first checkpoint. There are
# two headers with valid POW at height 1 and 2, forking off from genesis. They are indicated by the FORK_PREFIX.
FORK_PREFIX = 'fork:'
self.headers = [l for l in h_lines if not l.startswith(FORK_PREFIX)]
self.headers_fork = [l[len(FORK_PREFIX):] for l in h_lines if l.startswith(FORK_PREFIX)]
self.headers = [FromHex(CBlockHeader(), h) for h in self.headers]
self.headers_fork = [FromHex(CBlockHeader(), h) for h in self.headers_fork]
self.log.info("Feed all non-fork headers, including and up to the first checkpoint")
self.nodes[0].add_p2p_connection(P2PInterface())
self.nodes[0].p2p.send_and_ping(msg_headers(self.headers))
assert {
'height': 546,
'hash': '000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70',
'branchlen': 546,
'status': 'headers-only',
} in self.nodes[0].getchaintips()
self.log.info("Feed all fork headers (fails due to checkpoint)")
with self.nodes[0].assert_debug_log(['bad-fork-prior-to-checkpoint']):
self.nodes[0].p2p.send_message(msg_headers(self.headers_fork))
self.nodes[0].p2p.wait_for_disconnect()
self.log.info("Feed all fork headers (succeeds without checkpoint)")
# On node 0 it succeeds because checkpoints are disabled
self.restart_node(0, extra_args=['-nocheckpoints'])
self.nodes[0].add_p2p_connection(P2PInterface())
self.nodes[0].p2p.send_and_ping(msg_headers(self.headers_fork))
assert {
"height": 2,
"hash": "00000000b0494bd6c3d5ff79c497cfce40831871cbf39b1bc28bd1dac817dc39",
"branchlen": 2,
"status": "headers-only",
} in self.nodes[0].getchaintips()
# On node 1 it succeeds because no checkpoint has been reached yet by a chain tip
self.nodes[1].add_p2p_connection(P2PInterface())
self.nodes[1].p2p.send_and_ping(msg_headers(self.headers_fork))
assert {
"height": 2,
"hash": "00000000b0494bd6c3d5ff79c497cfce40831871cbf39b1bc28bd1dac817dc39",
"branchlen": 2,
"status": "headers-only",
} in self.nodes[1].getchaintips()
if __name__ == '__main__':
RejectLowDifficultyHeadersTest().main()
| 42.875
| 120
| 0.672939
|
0d03e91654bd945f38e4da3900ecbacc5605fd5b
| 52
|
py
|
Python
|
chunkedimage/__init__.py
|
ambrosejcarr/chunkedimage
|
635ef44feeb28b8b9d4cdb895fc1a0dd37c22d1e
|
[
"MIT"
] | null | null | null |
chunkedimage/__init__.py
|
ambrosejcarr/chunkedimage
|
635ef44feeb28b8b9d4cdb895fc1a0dd37c22d1e
|
[
"MIT"
] | null | null | null |
chunkedimage/__init__.py
|
ambrosejcarr/chunkedimage
|
635ef44feeb28b8b9d4cdb895fc1a0dd37c22d1e
|
[
"MIT"
] | null | null | null |
from .tile import Tile
from .tileset import TileSet
| 17.333333
| 28
| 0.807692
|
ba9121902170bc605733e082c53fb2ac7366a9d0
| 131,645
|
py
|
Python
|
mne/viz/_3d.py
|
High-East/mne-python
|
5b45394a3a0c16097ceda56ee2500348b9b1827a
|
[
"BSD-3-Clause"
] | 1
|
2021-11-15T06:11:51.000Z
|
2021-11-15T06:11:51.000Z
|
mne/viz/_3d.py
|
High-East/mne-python
|
5b45394a3a0c16097ceda56ee2500348b9b1827a
|
[
"BSD-3-Clause"
] | null | null | null |
mne/viz/_3d.py
|
High-East/mne-python
|
5b45394a3a0c16097ceda56ee2500348b9b1827a
|
[
"BSD-3-Clause"
] | null | null | null |
# -*- coding: utf-8 -*-
"""Functions to make 3D plots with M/EEG data."""
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Denis Engemann <denis.engemann@gmail.com>
# Martin Luessi <mluessi@nmr.mgh.harvard.edu>
# Eric Larson <larson.eric.d@gmail.com>
# Mainak Jas <mainak@neuro.hut.fi>
# Mark Wronkiewicz <wronk.mark@gmail.com>
#
# License: Simplified BSD
import base64
from distutils.version import LooseVersion
from io import BytesIO
from itertools import cycle
import os
import os.path as op
import warnings
from collections.abc import Iterable
from functools import partial
import numpy as np
from scipy import linalg, sparse
from ..defaults import DEFAULTS
from ..fixes import einsum, _crop_colorbar, _get_img_fdata
from ..io import _loc_to_coil_trans
from ..io.pick import pick_types, _picks_to_idx
from ..io.constants import FIFF
from ..io.meas_info import read_fiducials, create_info
from ..source_space import (_ensure_src, _create_surf_spacing, _check_spacing,
_read_mri_info)
from ..surface import (get_meg_helmet_surf, read_surface, _DistanceQuery,
transform_surface_to, _project_onto_surface,
mesh_edges, _reorder_ccw, _complete_sphere_surf)
from ..transforms import (_find_trans, apply_trans, rot_to_quat,
combine_transforms, _get_trans, _ensure_trans,
invert_transform, Transform,
read_ras_mni_t, _print_coord_trans)
from ..utils import (get_subjects_dir, logger, _check_subject, verbose, warn,
has_nibabel, check_version, fill_doc, _pl,
_ensure_int, _validate_type, _check_option)
from .utils import (mne_analyze_colormap, _prepare_trellis, _get_color_list,
plt_show, tight_layout, figure_nobar, _check_time_unit)
from ..bem import (ConductorModel, _bem_find_surface, _surf_dict, _surf_name,
read_bem_surfaces)
verbose_dec = verbose
FIDUCIAL_ORDER = (FIFF.FIFFV_POINT_LPA, FIFF.FIFFV_POINT_NASION,
FIFF.FIFFV_POINT_RPA)
# XXX: to unify with digitization
def _fiducial_coords(points, coord_frame=None):
"""Generate 3x3 array of fiducial coordinates."""
points = points or [] # None -> list
if coord_frame is not None:
points = [p for p in points if p['coord_frame'] == coord_frame]
points_ = {p['ident']: p for p in points if
p['kind'] == FIFF.FIFFV_POINT_CARDINAL}
if points_:
return np.array([points_[i]['r'] for i in FIDUCIAL_ORDER])
else:
# XXX eventually this should probably live in montage.py
if coord_frame is None or coord_frame == FIFF.FIFFV_COORD_HEAD:
# Try converting CTF HPI coils to fiducials
out = np.empty((3, 3))
out.fill(np.nan)
for p in points:
if p['kind'] == FIFF.FIFFV_POINT_HPI:
if np.isclose(p['r'][1:], 0, atol=1e-6).all():
out[0 if p['r'][0] < 0 else 2] = p['r']
elif np.isclose(p['r'][::2], 0, atol=1e-6).all():
out[1] = p['r']
if np.isfinite(out).all():
return out
return np.array([])
def plot_head_positions(pos, mode='traces', cmap='viridis', direction='z',
show=True, destination=None, info=None, color='k',
axes=None):
"""Plot head positions.
Parameters
----------
pos : ndarray, shape (n_pos, 10) | list of ndarray
The head position data. Can also be a list to treat as a
concatenation of runs.
mode : str
Can be 'traces' (default) to show position and quaternion traces,
or 'field' to show the position as a vector field over time.
The 'field' mode requires matplotlib 1.4+.
cmap : colormap
Colormap to use for the trace plot, default is "viridis".
direction : str
Can be any combination of "x", "y", or "z" (default: "z") to show
directional axes in "field" mode.
show : bool
Show figure if True. Defaults to True.
destination : str | array-like, shape (3,) | None
The destination location for the head, assumed to be in head
coordinates. See :func:`mne.preprocessing.maxwell_filter` for
details.
.. versionadded:: 0.16
info : instance of mne.Info | None
Measurement information. If provided, will be used to show the
destination position when ``destination is None``, and for
showing the MEG sensors.
.. versionadded:: 0.16
color : color object
The color to use for lines in ``mode == 'traces'`` and quiver
arrows in ``mode == 'field'``.
.. versionadded:: 0.16
axes : array-like, shape (3, 2)
The matplotlib axes to use. Only used for ``mode == 'traces'``.
.. versionadded:: 0.16
Returns
-------
fig : instance of matplotlib.figure.Figure
The figure.
"""
from ..chpi import head_pos_to_trans_rot_t
from ..preprocessing.maxwell import _check_destination
import matplotlib.pyplot as plt
_check_option('mode', mode, ['traces', 'field'])
dest_info = dict(dev_head_t=None) if info is None else info
destination = _check_destination(destination, dest_info, head_frame=True)
if destination is not None:
destination = _ensure_trans(destination, 'head', 'meg') # probably inv
destination = destination['trans'][:3].copy()
destination[:, 3] *= 1000
if not isinstance(pos, (list, tuple)):
pos = [pos]
for ii, p in enumerate(pos):
p = np.array(p, float)
if p.ndim != 2 or p.shape[1] != 10:
raise ValueError('pos (or each entry in pos if a list) must be '
'dimension (N, 10), got %s' % (p.shape,))
if ii > 0: # concatenation
p[:, 0] += pos[ii - 1][-1, 0] - p[0, 0]
pos[ii] = p
borders = np.cumsum([len(pp) for pp in pos])
pos = np.concatenate(pos, axis=0)
trans, rot, t = head_pos_to_trans_rot_t(pos) # also ensures pos is okay
# trans, rot, and t are for dev_head_t, but what we really want
# is head_dev_t (i.e., where the head origin is in device coords)
use_trans = einsum('ijk,ik->ij', rot[:, :3, :3].transpose([0, 2, 1]),
-trans) * 1000
use_rot = rot.transpose([0, 2, 1])
use_quats = -pos[:, 1:4] # inverse (like doing rot.T)
surf = rrs = lims = None
if info is not None:
meg_picks = pick_types(info, meg=True, ref_meg=False, exclude=())
if len(meg_picks) > 0:
rrs = 1000 * np.array([info['chs'][pick]['loc'][:3]
for pick in meg_picks], float)
if mode == 'traces':
lims = np.array((rrs.min(0), rrs.max(0))).T
else: # mode == 'field'
surf = get_meg_helmet_surf(info)
transform_surface_to(surf, 'meg', info['dev_head_t'],
copy=False)
surf['rr'] *= 1000.
helmet_color = (0.0, 0.0, 0.6)
if mode == 'traces':
if axes is None:
axes = plt.subplots(3, 2, sharex=True)[1]
else:
axes = np.array(axes)
if axes.shape != (3, 2):
raise ValueError('axes must have shape (3, 2), got %s'
% (axes.shape,))
fig = axes[0, 0].figure
labels = ['xyz', ('$q_1$', '$q_2$', '$q_3$')]
for ii, (quat, coord) in enumerate(zip(use_quats.T, use_trans.T)):
axes[ii, 0].plot(t, coord, color, lw=1., zorder=3)
axes[ii, 0].set(ylabel=labels[0][ii], xlim=t[[0, -1]])
axes[ii, 1].plot(t, quat, color, lw=1., zorder=3)
axes[ii, 1].set(ylabel=labels[1][ii], xlim=t[[0, -1]])
for b in borders[:-1]:
for jj in range(2):
axes[ii, jj].axvline(t[b], color='r')
for ii, title in enumerate(('Position (mm)', 'Rotation (quat)')):
axes[0, ii].set(title=title)
axes[-1, ii].set(xlabel='Time (s)')
if rrs is not None:
pos_bads = np.any([(use_trans[:, ii] <= lims[ii, 0]) |
(use_trans[:, ii] >= lims[ii, 1])
for ii in range(3)], axis=0)
for ii in range(3):
oidx = list(range(ii)) + list(range(ii + 1, 3))
# knowing it will generally be spherical, we can approximate
# how far away we are along the axis line by taking the
# point to the left and right with the smallest distance
from scipy.spatial.distance import cdist
dists = cdist(rrs[:, oidx], use_trans[:, oidx])
left = rrs[:, [ii]] < use_trans[:, ii]
left_dists_all = dists.copy()
left_dists_all[~left] = np.inf
# Don't show negative Z direction
if ii != 2 and np.isfinite(left_dists_all).any():
idx = np.argmin(left_dists_all, axis=0)
left_dists = rrs[idx, ii]
bads = ~np.isfinite(
left_dists_all[idx, np.arange(len(idx))]) | pos_bads
left_dists[bads] = np.nan
axes[ii, 0].plot(t, left_dists, color=helmet_color,
ls='-', lw=0.5, zorder=2)
else:
axes[ii, 0].axhline(lims[ii][0], color=helmet_color,
ls='-', lw=0.5, zorder=2)
right_dists_all = dists
right_dists_all[left] = np.inf
if np.isfinite(right_dists_all).any():
idx = np.argmin(right_dists_all, axis=0)
right_dists = rrs[idx, ii]
bads = ~np.isfinite(
right_dists_all[idx, np.arange(len(idx))]) | pos_bads
right_dists[bads] = np.nan
axes[ii, 0].plot(t, right_dists, color=helmet_color,
ls='-', lw=0.5, zorder=2)
else:
axes[ii, 0].axhline(lims[ii][1], color=helmet_color,
ls='-', lw=0.5, zorder=2)
for ii in range(3):
axes[ii, 1].set(ylim=[-1, 1])
if destination is not None:
vals = np.array([destination[:, 3],
rot_to_quat(destination[:, :3])]).T.ravel()
for ax, val in zip(fig.axes, vals):
ax.axhline(val, color='r', ls=':', zorder=2, lw=1.)
else: # mode == 'field':
from matplotlib.colors import Normalize
from mpl_toolkits.mplot3d.art3d import Line3DCollection
from mpl_toolkits.mplot3d import axes3d # noqa: F401, analysis:ignore
fig, ax = plt.subplots(1, subplot_kw=dict(projection='3d'))
# First plot the trajectory as a colormap:
# http://matplotlib.org/examples/pylab_examples/multicolored_line.html
pts = use_trans[:, np.newaxis]
segments = np.concatenate([pts[:-1], pts[1:]], axis=1)
norm = Normalize(t[0], t[-2])
lc = Line3DCollection(segments, cmap=cmap, norm=norm)
lc.set_array(t[:-1])
ax.add_collection(lc)
# now plot the head directions as a quiver
dir_idx = dict(x=0, y=1, z=2)
kwargs = dict(pivot='tail')
for d, length in zip(direction, [5., 2.5, 1.]):
use_dir = use_rot[:, :, dir_idx[d]]
# draws stems, then heads
array = np.concatenate((t, np.repeat(t, 2)))
ax.quiver(use_trans[:, 0], use_trans[:, 1], use_trans[:, 2],
use_dir[:, 0], use_dir[:, 1], use_dir[:, 2], norm=norm,
cmap=cmap, array=array, length=length, **kwargs)
if destination is not None:
ax.quiver(destination[0, 3],
destination[1, 3],
destination[2, 3],
destination[dir_idx[d], 0],
destination[dir_idx[d], 1],
destination[dir_idx[d], 2], color=color,
length=length, **kwargs)
mins = use_trans.min(0)
maxs = use_trans.max(0)
if surf is not None:
ax.plot_trisurf(*surf['rr'].T, triangles=surf['tris'],
color=helmet_color, alpha=0.1, shade=False)
ax.scatter(*rrs.T, s=1, color=helmet_color)
mins = np.minimum(mins, rrs.min(0))
maxs = np.maximum(maxs, rrs.max(0))
scale = (maxs - mins).max() / 2.
xlim, ylim, zlim = (maxs + mins)[:, np.newaxis] / 2. + [-scale, scale]
ax.set(xlabel='x', ylabel='y', zlabel='z',
xlim=xlim, ylim=ylim, zlim=zlim)
_set_aspect_equal(ax)
ax.view_init(30, 45)
tight_layout(fig=fig)
plt_show(show)
return fig
def _set_aspect_equal(ax):
# XXX recent MPL throws an error for 3D axis aspect setting, not much
# we can do about it at this point
try:
ax.set_aspect('equal')
except NotImplementedError:
pass
@verbose
def plot_evoked_field(evoked, surf_maps, time=None, time_label='t = %0.0f ms',
n_jobs=1, fig=None, verbose=None):
"""Plot MEG/EEG fields on head surface and helmet in 3D.
Parameters
----------
evoked : instance of mne.Evoked
The evoked object.
surf_maps : list
The surface mapping information obtained with make_field_map.
time : float | None
The time point at which the field map shall be displayed. If None,
the average peak latency (across sensor types) is used.
time_label : str
How to print info about the time instant visualized.
%(n_jobs)s
fig : instance of mayavi.core.api.Scene | None
If None (default), a new figure will be created, otherwise it will
plot into the given figure.
.. versionadded:: 0.20
%(verbose)s
Returns
-------
fig : instance of mayavi.mlab.Figure
The mayavi figure.
"""
# Update the backend
from .backends.renderer import _get_renderer
types = [t for t in ['eeg', 'grad', 'mag'] if t in evoked]
time_idx = None
if time is None:
time = np.mean([evoked.get_peak(ch_type=t)[1] for t in types])
del types
if not evoked.times[0] <= time <= evoked.times[-1]:
raise ValueError('`time` (%0.3f) must be inside `evoked.times`' % time)
time_idx = np.argmin(np.abs(evoked.times - time))
# Plot them
alphas = [1.0, 0.5]
colors = [(0.6, 0.6, 0.6), (1.0, 1.0, 1.0)]
colormap = mne_analyze_colormap(format='mayavi')
colormap_lines = np.concatenate([np.tile([0., 0., 255., 255.], (127, 1)),
np.tile([0., 0., 0., 255.], (2, 1)),
np.tile([255., 0., 0., 255.], (127, 1))])
renderer = _get_renderer(fig, bgcolor=(0.0, 0.0, 0.0), size=(600, 600))
for ii, this_map in enumerate(surf_maps):
surf = this_map['surf']
map_data = this_map['data']
map_type = this_map['kind']
map_ch_names = this_map['ch_names']
if map_type == 'eeg':
pick = pick_types(evoked.info, meg=False, eeg=True)
else:
pick = pick_types(evoked.info, meg=True, eeg=False, ref_meg=False)
ch_names = [evoked.ch_names[k] for k in pick]
set_ch_names = set(ch_names)
set_map_ch_names = set(map_ch_names)
if set_ch_names != set_map_ch_names:
message = ['Channels in map and data do not match.']
diff = set_map_ch_names - set_ch_names
if len(diff):
message += ['%s not in data file. ' % list(diff)]
diff = set_ch_names - set_map_ch_names
if len(diff):
message += ['%s not in map file.' % list(diff)]
raise RuntimeError(' '.join(message))
data = np.dot(map_data, evoked.data[pick, time_idx])
# Make a solid surface
vlim = np.max(np.abs(data))
alpha = alphas[ii]
renderer.surface(surface=surf, color=colors[ii],
opacity=alpha)
# Now show our field pattern
renderer.surface(surface=surf, vmin=-vlim, vmax=vlim,
scalars=data, colormap=colormap)
# And the field lines on top
renderer.contour(surface=surf, scalars=data, contours=21,
vmin=-vlim, vmax=vlim, opacity=alpha,
colormap=colormap_lines)
if '%' in time_label:
time_label %= (1e3 * evoked.times[time_idx])
renderer.text2d(x_window=0.01, y_window=0.01, text=time_label)
renderer.set_camera(azimuth=10, elevation=60)
renderer.show()
return renderer.scene()
def _plot_mri_contours(mri_fname, surf_fnames, orientation='coronal',
slices=None, show=True, img_output=False):
"""Plot BEM contours on anatomical slices.
Parameters
----------
mri_fname : str
The name of the file containing anatomical data.
surf_fnames : list of str
The filenames for the BEM surfaces in the format
['inner_skull.surf', 'outer_skull.surf', 'outer_skin.surf'].
orientation : str
'coronal' or 'transverse' or 'sagittal'
slices : list of int
Slice indices.
show : bool
Call pyplot.show() at the end.
img_output : None | tuple
If tuple (width and height), images will be produced instead of a
single figure with many axes. This mode is designed to reduce the
(substantial) overhead associated with making tens to hundreds
of matplotlib axes, instead opting to re-use a single Axes instance.
Returns
-------
fig : instance of matplotlib.figure.Figure | list
The figure. Will instead be a list of png images if
img_output is a tuple.
"""
import matplotlib.pyplot as plt
import nibabel as nib
_check_option('orientation', orientation, ['coronal', 'axial', 'sagittal'])
# Load the T1 data
nim = nib.load(mri_fname)
data = _get_img_fdata(nim)
try:
affine = nim.affine
except AttributeError: # old nibabel
affine = nim.get_affine()
n_sag, n_axi, n_cor = data.shape
orientation_name2axis = dict(sagittal=0, axial=1, coronal=2)
orientation_axis = orientation_name2axis[orientation]
if slices is None:
n_slices = data.shape[orientation_axis]
slices = np.linspace(0, n_slices, 12, endpoint=False).astype(np.int)
# create of list of surfaces
surfs = list()
trans = linalg.inv(affine)
# XXX : next line is a hack don't ask why
trans[:3, -1] = [n_sag // 2, n_axi // 2, n_cor // 2]
for surf_fname in surf_fnames:
surf = read_surface(surf_fname, return_dict=True)[-1]
# move back surface to MRI coordinate system
surf['rr'] = nib.affines.apply_affine(trans, surf['rr'])
surfs.append(surf)
if img_output is None:
fig, axs, _, _ = _prepare_trellis(len(slices), 4)
else:
fig, ax = plt.subplots(1, 1, figsize=(7.0, 7.0))
axs = [ax] * len(slices)
fig_size = fig.get_size_inches()
w, h = img_output[0], img_output[1]
w2 = fig_size[0]
fig.set_size_inches([(w2 / float(w)) * w, (w2 / float(w)) * h])
plt.close(fig)
inds = dict(coronal=[0, 1, 2], axial=[2, 0, 1],
sagittal=[2, 1, 0])[orientation]
outs = []
for ax, sl in zip(axs, slices):
# adjust the orientations for good view
if orientation == 'coronal':
dat = data[:, :, sl].transpose()
elif orientation == 'axial':
dat = data[:, sl, :]
elif orientation == 'sagittal':
dat = data[sl, :, :]
# First plot the anatomical data
if img_output is not None:
ax.clear()
ax.imshow(dat, cmap=plt.cm.gray)
ax.axis('off')
# and then plot the contours on top
for surf in surfs:
with warnings.catch_warnings(record=True): # no contours
warnings.simplefilter('ignore')
ax.tricontour(surf['rr'][:, inds[0]], surf['rr'][:, inds[1]],
surf['tris'], surf['rr'][:, inds[2]],
levels=[sl], colors='yellow', linewidths=2.0)
if img_output is not None:
ax.set_xticks([])
ax.set_yticks([])
ax.set_xlim(0, img_output[1])
ax.set_ylim(img_output[0], 0)
output = BytesIO()
fig.savefig(output, bbox_inches='tight',
pad_inches=0, format='png')
outs.append(base64.b64encode(output.getvalue()).decode('ascii'))
if show:
plt.subplots_adjust(left=0., bottom=0., right=1., top=1., wspace=0.,
hspace=0.)
plt_show(show)
return fig if img_output is None else outs
@verbose
def plot_alignment(info=None, trans=None, subject=None, subjects_dir=None,
surfaces='head', coord_frame='head',
meg=None, eeg='original', fwd=None,
dig=False, ecog=True, src=None, mri_fiducials=False,
bem=None, seeg=True, fnirs=True, show_axes=False, fig=None,
interaction='trackball', verbose=None):
"""Plot head, sensor, and source space alignment in 3D.
Parameters
----------
info : dict | None
The measurement info.
If None (default), no sensor information will be shown.
%(trans)s
subject : str | None
The subject name corresponding to FreeSurfer environment
variable SUBJECT. Can be omitted if ``src`` is provided.
%(subjects_dir)s
surfaces : str | list
Surfaces to plot. Supported values:
* scalp: one of 'head', 'outer_skin' (alias for 'head'),
'head-dense', or 'seghead' (alias for 'head-dense')
* skull: 'outer_skull', 'inner_skull', 'brain' (alias for
'inner_skull')
* brain: one of 'pial', 'white', 'inflated', or 'brain'
(alias for 'pial').
Defaults to 'head'.
.. note:: For single layer BEMs it is recommended to use 'brain'.
coord_frame : str
Coordinate frame to use, 'head', 'meg', or 'mri'.
meg : str | list | bool | None
Can be "helmet", "sensors" or "ref" to show the MEG helmet, sensors or
reference sensors respectively, or a combination like
``('helmet', 'sensors')`` (same as None, default). True translates to
``('helmet', 'sensors', 'ref')``.
eeg : bool | str | list
String options are:
- "original" (default; equivalent to ``True``)
Shows EEG sensors using their digitized locations (after
transformation to the chosen ``coord_frame``)
- "projected"
The EEG locations projected onto the scalp, as is done in forward
modeling
Can also be a list of these options, or an empty list (``[]``,
equivalent of ``False``).
fwd : instance of Forward
The forward solution. If present, the orientations of the dipoles
present in the forward solution are displayed.
dig : bool | 'fiducials'
If True, plot the digitization points; 'fiducials' to plot fiducial
points only.
ecog : bool
If True (default), show ECoG sensors.
src : instance of SourceSpaces | None
If not None, also plot the source space points.
mri_fiducials : bool | str
Plot MRI fiducials (default False). If ``True``, look for a file with
the canonical name (``bem/{subject}-fiducials.fif``). If ``str`` it
should provide the full path to the fiducials file.
bem : list of dict | instance of ConductorModel | None
Can be either the BEM surfaces (list of dict), a BEM solution or a
sphere model. If None, we first try loading
`'$SUBJECTS_DIR/$SUBJECT/bem/$SUBJECT-$SOURCE.fif'`, and then look for
`'$SUBJECT*$SOURCE.fif'` in the same directory. For `'outer_skin'`,
the subjects bem and bem/flash folders are searched. Defaults to None.
seeg : bool
If True (default), show sEEG electrodes.
fnirs : str | list | bool | None
Can be "channels" or "pairs" to show the fNIRS channel locations or
line between source-detector pairs, or a combination like
``('pairs', 'channels')``. True translates to ``('pairs',)``.
.. versionadded:: 0.20
show_axes : bool
If True (default False), coordinate frame axis indicators will be
shown:
* head in pink.
* MRI in gray (if ``trans is not None``).
* MEG in blue (if MEG sensors are present).
.. versionadded:: 0.16
fig : mayavi.mlab.Figure | None
Mayavi Scene in which to plot the alignment.
If ``None``, creates a new 600x600 pixel figure with black background.
.. versionadded:: 0.16
interaction : str
Can be "trackball" (default) or "terrain", i.e. a turntable-style
camera.
.. versionadded:: 0.16
%(verbose)s
Returns
-------
fig : instance of mayavi.mlab.Figure
The mayavi figure.
See Also
--------
mne.viz.plot_bem
Notes
-----
This function serves the purpose of checking the validity of the many
different steps of source reconstruction:
- Transform matrix (keywords ``trans``, ``meg`` and ``mri_fiducials``),
- BEM surfaces (keywords ``bem`` and ``surfaces``),
- sphere conductor model (keywords ``bem`` and ``surfaces``) and
- source space (keywords ``surfaces`` and ``src``).
.. versionadded:: 0.15
"""
from ..forward import _create_meg_coils, Forward
# Update the backend
from .backends.renderer import _get_renderer
if eeg is False:
eeg = list()
elif eeg is True:
eeg = 'original'
if meg is None:
meg = ('helmet', 'sensors')
# only consider warning if the value is explicit
warn_meg = False
else:
warn_meg = True
if meg is True:
meg = ('helmet', 'sensors', 'ref')
elif meg is False:
meg = list()
elif isinstance(meg, str):
meg = [meg]
if isinstance(eeg, str):
eeg = [eeg]
if fnirs is True:
fnirs = ['pairs']
elif fnirs is False:
fnirs = list()
elif isinstance(fnirs, str):
fnirs = [fnirs]
_check_option('interaction', interaction, ['trackball', 'terrain'])
for kind, var in zip(('eeg', 'meg', 'fnirs'), (eeg, meg, fnirs)):
if not isinstance(var, (list, tuple)) or \
not all(isinstance(x, str) for x in var):
raise TypeError('%s must be list or tuple of str, got %s'
% (kind, type(var)))
for xi, x in enumerate(meg):
_check_option('meg[%d]' % xi, x, ('helmet', 'sensors', 'ref'))
for xi, x in enumerate(eeg):
_check_option('eeg[%d]' % xi, x, ('original', 'projected'))
for xi, x in enumerate(fnirs):
_check_option('fnirs[%d]' % xi, x, ('channels', 'pairs'))
info = create_info(1, 1000., 'misc') if info is None else info
_validate_type(info, "info")
if isinstance(surfaces, str):
surfaces = [surfaces]
surfaces = list(surfaces)
for s in surfaces:
_validate_type(s, "str", "all entries in surfaces")
is_sphere = False
if isinstance(bem, ConductorModel) and bem['is_sphere']:
if len(bem['layers']) != 4 and len(surfaces) > 1:
raise ValueError('The sphere conductor model must have three '
'layers for plotting skull and head.')
is_sphere = True
_check_option('coord_frame', coord_frame, ['head', 'meg', 'mri'])
if src is not None:
src = _ensure_src(src)
src_subject = src._subject
subject = src_subject if subject is None else subject
if src_subject is not None and subject != src_subject:
raise ValueError('subject ("%s") did not match the subject name '
' in src ("%s")' % (subject, src_subject))
src_rr = np.concatenate([s['rr'][s['inuse'].astype(bool)]
for s in src])
src_nn = np.concatenate([s['nn'][s['inuse'].astype(bool)]
for s in src])
else:
src_rr = src_nn = np.empty((0, 3))
if fwd is not None:
_validate_type(fwd, [Forward])
fwd_rr = fwd['source_rr']
if fwd['source_ori'] == FIFF.FIFFV_MNE_FIXED_ORI:
fwd_nn = fwd['source_nn'].reshape(-1, 1, 3)
else:
fwd_nn = fwd['source_nn'].reshape(-1, 3, 3)
ref_meg = 'ref' in meg
meg_picks = pick_types(info, meg=True, ref_meg=ref_meg)
eeg_picks = pick_types(info, meg=False, eeg=True, ref_meg=False)
fnirs_picks = pick_types(info, meg=False, eeg=False,
ref_meg=False, fnirs=True)
other_bools = dict(ecog=ecog, seeg=seeg, fnirs=('channels' in fnirs))
del ecog, seeg
other_keys = sorted(other_bools.keys())
other_picks = {key: pick_types(info, meg=False, ref_meg=False,
**{key: True}) for key in other_keys}
if trans == 'auto':
# let's try to do this in MRI coordinates so they're easy to plot
subjects_dir = get_subjects_dir(subjects_dir, raise_error=True)
trans = _find_trans(subject, subjects_dir)
head_mri_t, _ = _get_trans(trans, 'head', 'mri')
dev_head_t, _ = _get_trans(info['dev_head_t'], 'meg', 'head')
del trans
# Figure out our transformations
if coord_frame == 'meg':
head_trans = invert_transform(dev_head_t)
meg_trans = Transform('meg', 'meg')
mri_trans = invert_transform(combine_transforms(
dev_head_t, head_mri_t, 'meg', 'mri'))
elif coord_frame == 'mri':
head_trans = head_mri_t
meg_trans = combine_transforms(dev_head_t, head_mri_t, 'meg', 'mri')
mri_trans = Transform('mri', 'mri')
else: # coord_frame == 'head'
head_trans = Transform('head', 'head')
meg_trans = dev_head_t
mri_trans = invert_transform(head_mri_t)
# both the head and helmet will be in MRI coordinates after this
surfs = dict()
# Head:
sphere_level = 4
head = False
for s in surfaces:
if s in ('head', 'outer_skin', 'head-dense', 'seghead'):
if head:
raise ValueError('Can only supply one head-like surface name')
surfaces.pop(surfaces.index(s))
head = True
head_surf = None
# Try the BEM if applicable
if s in ('head', 'outer_skin'):
if bem is not None:
head_missing = (
'Could not find the surface for '
'head in the provided BEM model, '
'looking in the subject directory.')
if isinstance(bem, ConductorModel):
if is_sphere:
head_surf = _complete_sphere_surf(
bem, 3, sphere_level, complete=False)
else: # BEM solution
try:
head_surf = _bem_find_surface(
bem, FIFF.FIFFV_BEM_SURF_ID_HEAD)
except RuntimeError:
logger.info(head_missing)
elif bem is not None: # list of dict
for this_surf in bem:
if this_surf['id'] == FIFF.FIFFV_BEM_SURF_ID_HEAD:
head_surf = this_surf
break
else:
logger.info(head_missing)
if head_surf is None:
if subject is None:
raise ValueError('To plot the head surface, the BEM/sphere'
' model must contain a head surface '
'or "subject" must be provided (got '
'None)')
subject_dir = op.join(
get_subjects_dir(subjects_dir, raise_error=True), subject)
if s in ('head-dense', 'seghead'):
try_fnames = [
op.join(subject_dir, 'bem', '%s-head-dense.fif'
% subject),
op.join(subject_dir, 'surf', 'lh.seghead'),
]
else:
try_fnames = [
op.join(subject_dir, 'bem', 'outer_skin.surf'),
op.join(subject_dir, 'bem', 'flash',
'outer_skin.surf'),
op.join(subject_dir, 'bem', '%s-head.fif'
% subject),
]
for fname in try_fnames:
if op.exists(fname):
logger.info('Using %s for head surface.'
% (op.basename(fname),))
if op.splitext(fname)[-1] == '.fif':
head_surf = read_bem_surfaces(fname)[0]
else:
head_surf = read_surface(
fname, return_dict=True)[2]
head_surf['rr'] /= 1000.
head_surf.update(coord_frame=FIFF.FIFFV_COORD_MRI)
break
else:
raise IOError('No head surface found for subject '
'%s after trying:\n%s'
% (subject, '\n'.join(try_fnames)))
surfs['head'] = head_surf
# Skull:
skull = list()
for name, id_ in (('outer_skull', FIFF.FIFFV_BEM_SURF_ID_SKULL),
('inner_skull', FIFF.FIFFV_BEM_SURF_ID_BRAIN)):
if name in surfaces:
surfaces.pop(surfaces.index(name))
if bem is None:
fname = op.join(
get_subjects_dir(subjects_dir, raise_error=True),
subject, 'bem', name + '.surf')
if not op.isfile(fname):
raise ValueError('bem is None and the the %s file cannot '
'be found:\n%s' % (name, fname))
surf = read_surface(fname, return_dict=True)[2]
surf.update(coord_frame=FIFF.FIFFV_COORD_MRI,
id=_surf_dict[name])
surf['rr'] /= 1000.
skull.append(surf)
elif isinstance(bem, ConductorModel):
if is_sphere:
if len(bem['layers']) != 4:
raise ValueError('The sphere model must have three '
'layers for plotting %s' % (name,))
this_idx = 1 if name == 'inner_skull' else 2
skull.append(_complete_sphere_surf(
bem, this_idx, sphere_level))
skull[-1]['id'] = _surf_dict[name]
else:
skull.append(_bem_find_surface(bem, id_))
else: # BEM model
for this_surf in bem:
if this_surf['id'] == _surf_dict[name]:
skull.append(this_surf)
break
else:
raise ValueError('Could not find the surface for %s.'
% name)
if mri_fiducials:
if mri_fiducials is True:
subjects_dir = get_subjects_dir(subjects_dir, raise_error=True)
if subject is None:
raise ValueError("Subject needs to be specified to "
"automatically find the fiducials file.")
mri_fiducials = op.join(subjects_dir, subject, 'bem',
subject + '-fiducials.fif')
if isinstance(mri_fiducials, str):
mri_fiducials, cf = read_fiducials(mri_fiducials)
if cf != FIFF.FIFFV_COORD_MRI:
raise ValueError("Fiducials are not in MRI space")
fid_loc = _fiducial_coords(mri_fiducials, FIFF.FIFFV_COORD_MRI)
fid_loc = apply_trans(mri_trans, fid_loc)
else:
fid_loc = []
if 'helmet' in meg and len(meg_picks) > 0:
surfs['helmet'] = get_meg_helmet_surf(info, head_mri_t)
assert surfs['helmet']['coord_frame'] == FIFF.FIFFV_COORD_MRI
# Brain:
brain = np.intersect1d(surfaces, ['brain', 'pial', 'white', 'inflated'])
if len(brain) > 1:
raise ValueError('Only one brain surface can be plotted. '
'Got %s.' % brain)
elif len(brain) == 0:
brain = False
else: # exactly 1
brain = brain[0]
surfaces.pop(surfaces.index(brain))
brain = 'pial' if brain == 'brain' else brain
if is_sphere:
if len(bem['layers']) > 0:
surfs['lh'] = _complete_sphere_surf(
bem, 0, sphere_level) # only plot 1
else:
subjects_dir = get_subjects_dir(subjects_dir, raise_error=True)
for hemi in ['lh', 'rh']:
fname = op.join(subjects_dir, subject, 'surf',
'%s.%s' % (hemi, brain))
surfs[hemi] = read_surface(fname, return_dict=True)[2]
surfs[hemi]['rr'] /= 1000.
surfs[hemi].update(coord_frame=FIFF.FIFFV_COORD_MRI)
brain = True
# we've looked through all of them, raise if some remain
if len(surfaces) > 0:
raise ValueError('Unknown surface type%s: %s'
% (_pl(surfaces), surfaces,))
skull_alpha = dict()
skull_colors = dict()
hemi_val = 0.5
if src is None or (brain and any(s['type'] == 'surf' for s in src)):
hemi_val = 1.
alphas = (4 - np.arange(len(skull) + 1)) * (0.5 / 4.)
for idx, this_skull in enumerate(skull):
if isinstance(this_skull, dict):
skull_surf = this_skull
this_skull = _surf_name[skull_surf['id']]
elif is_sphere: # this_skull == str
this_idx = 1 if this_skull == 'inner_skull' else 2
skull_surf = _complete_sphere_surf(bem, this_idx, sphere_level)
else: # str
skull_fname = op.join(subjects_dir, subject, 'bem', 'flash',
'%s.surf' % this_skull)
if not op.exists(skull_fname):
skull_fname = op.join(subjects_dir, subject, 'bem',
'%s.surf' % this_skull)
if not op.exists(skull_fname):
raise IOError('No skull surface %s found for subject %s.'
% (this_skull, subject))
logger.info('Using %s for head surface.' % skull_fname)
skull_surf = read_surface(skull_fname, return_dict=True)[2]
skull_surf['rr'] /= 1000.
skull_surf['coord_frame'] = FIFF.FIFFV_COORD_MRI
skull_alpha[this_skull] = alphas[idx + 1]
skull_colors[this_skull] = (0.95 - idx * 0.2, 0.85, 0.95 - idx * 0.2)
surfs[this_skull] = skull_surf
if src is None and brain is False and len(skull) == 0 and not show_axes:
head_alpha = 1.0
else:
head_alpha = alphas[0]
for key in surfs.keys():
# Surfs can sometimes be in head coords (e.g., if coming from sphere)
surfs[key] = transform_surface_to(surfs[key], coord_frame,
[mri_trans, head_trans], copy=True)
if src is not None:
src_rr, src_nn = _update_coord_frame(src[0], src_rr, src_nn,
mri_trans, head_trans)
if fwd is not None:
fwd_rr, fwd_nn = _update_coord_frame(fwd, fwd_rr, fwd_nn,
mri_trans, head_trans)
# determine points
meg_rrs, meg_tris = list(), list()
hpi_loc = list()
ext_loc = list()
car_loc = list()
eeg_loc = list()
eegp_loc = list()
other_loc = {key: list() for key in other_keys}
if len(eeg) > 0:
eeg_loc = np.array([info['chs'][k]['loc'][:3] for k in eeg_picks])
if len(eeg_loc) > 0:
eeg_loc = apply_trans(head_trans, eeg_loc)
# XXX do projections here if necessary
if 'projected' in eeg:
eegp_loc, eegp_nn = _project_onto_surface(
eeg_loc, surfs['head'], project_rrs=True,
return_nn=True)[2:4]
if 'original' not in eeg:
eeg_loc = list()
del eeg
if 'sensors' in meg:
coil_transs = [_loc_to_coil_trans(info['chs'][pick]['loc'])
for pick in meg_picks]
coils = _create_meg_coils([info['chs'][pick] for pick in meg_picks],
acc='normal')
offset = 0
for coil, coil_trans in zip(coils, coil_transs):
rrs, tris = _sensor_shape(coil)
rrs = apply_trans(coil_trans, rrs)
meg_rrs.append(rrs)
meg_tris.append(tris + offset)
offset += len(meg_rrs[-1])
if len(meg_rrs) == 0:
if warn_meg:
warn('MEG sensors not found. Cannot plot MEG locations.')
else:
meg_rrs = apply_trans(meg_trans, np.concatenate(meg_rrs, axis=0))
meg_tris = np.concatenate(meg_tris, axis=0)
del meg
if dig:
if dig == 'fiducials':
hpi_loc = ext_loc = []
elif dig is not True:
raise ValueError("dig needs to be True, False or 'fiducials', "
"not %s" % repr(dig))
else:
hpi_loc = np.array([
d['r'] for d in (info['dig'] or [])
if (d['kind'] == FIFF.FIFFV_POINT_HPI and
d['coord_frame'] == FIFF.FIFFV_COORD_HEAD)])
ext_loc = np.array([
d['r'] for d in (info['dig'] or [])
if (d['kind'] == FIFF.FIFFV_POINT_EXTRA and
d['coord_frame'] == FIFF.FIFFV_COORD_HEAD)])
car_loc = _fiducial_coords(info['dig'], FIFF.FIFFV_COORD_HEAD)
# Transform from head coords if necessary
if coord_frame == 'meg':
for loc in (hpi_loc, ext_loc, car_loc):
loc[:] = apply_trans(invert_transform(info['dev_head_t']), loc)
elif coord_frame == 'mri':
for loc in (hpi_loc, ext_loc, car_loc):
loc[:] = apply_trans(head_mri_t, loc)
if len(car_loc) == len(ext_loc) == len(hpi_loc) == 0:
warn('Digitization points not found. Cannot plot digitization.')
del dig
for key, picks in other_picks.items():
if other_bools[key] and len(picks):
other_loc[key] = np.array([info['chs'][pick]['loc'][:3]
for pick in picks])
logger.info('Plotting %d %s location%s'
% (len(other_loc[key]), key, _pl(other_loc[key])))
# initialize figure
renderer = _get_renderer(fig, bgcolor=(0.5, 0.5, 0.5), size=(800, 800))
if interaction == 'terrain':
renderer.set_interactive()
# plot surfaces
alphas = dict(head=head_alpha, helmet=0.25, lh=hemi_val, rh=hemi_val)
alphas.update(skull_alpha)
colors = dict(head=(0.6,) * 3, helmet=(0.0, 0.0, 0.6), lh=(0.5,) * 3,
rh=(0.5,) * 3)
colors.update(skull_colors)
for key, surf in surfs.items():
renderer.surface(surface=surf, color=colors[key],
opacity=alphas[key],
backface_culling=(key != 'helmet'))
if brain and 'lh' not in surfs: # one layer sphere
assert bem['coord_frame'] == FIFF.FIFFV_COORD_HEAD
center = bem['r0'].copy()
center = apply_trans(head_trans, center)
renderer.sphere(center, scale=0.01, color=colors['lh'],
opacity=alphas['lh'])
if show_axes:
axes = [(head_trans, (0.9, 0.3, 0.3))] # always show head
if not np.allclose(head_mri_t['trans'], np.eye(4)): # Show MRI
axes.append((mri_trans, (0.6, 0.6, 0.6)))
if len(meg_picks) > 0: # Show MEG
axes.append((meg_trans, (0., 0.6, 0.6)))
for ax in axes:
x, y, z = np.tile(ax[0]['trans'][:3, 3], 3).reshape((3, 3)).T
u, v, w = ax[0]['trans'][:3, :3]
renderer.sphere(center=np.column_stack((x[0], y[0], z[0])),
color=ax[1], scale=3e-3)
renderer.quiver3d(x=x, y=y, z=z, u=u, v=v, w=w, mode='arrow',
scale=2e-2, color=ax[1],
scale_mode='scalar', resolution=20,
scalars=[0.33, 0.66, 1.0])
# plot points
defaults = DEFAULTS['coreg']
datas = [eeg_loc,
hpi_loc,
ext_loc] + list(other_loc[key] for key in other_keys)
colors = [defaults['eeg_color'],
defaults['hpi_color'],
defaults['extra_color']
] + [defaults[key + '_color'] for key in other_keys]
alphas = [0.8,
0.5,
0.25] + [0.8] * len(other_keys)
scales = [defaults['eeg_scale'],
defaults['hpi_scale'],
defaults['extra_scale']
] + [defaults[key + '_scale'] for key in other_keys]
assert len(datas) == len(colors) == len(alphas) == len(scales)
for kind, loc in (('dig', car_loc), ('mri', fid_loc)):
if len(loc) > 0:
datas.extend(loc[:, np.newaxis])
colors.extend((defaults['lpa_color'],
defaults['nasion_color'],
defaults['rpa_color']))
alphas.extend(3 * (defaults[kind + '_fid_opacity'],))
scales.extend(3 * (defaults[kind + '_fid_scale'],))
for data, color, alpha, scale in zip(datas, colors, alphas, scales):
if len(data) > 0:
renderer.sphere(center=data, color=color, scale=scale,
opacity=alpha, backface_culling=True)
if len(eegp_loc) > 0:
renderer.quiver3d(
x=eegp_loc[:, 0], y=eegp_loc[:, 1], z=eegp_loc[:, 2],
u=eegp_nn[:, 0], v=eegp_nn[:, 1], w=eegp_nn[:, 2],
color=defaults['eegp_color'], mode='cylinder',
scale=defaults['eegp_scale'], opacity=0.6,
glyph_height=defaults['eegp_height'],
glyph_center=(0., -defaults['eegp_height'], 0),
glyph_resolution=20,
backface_culling=True)
if len(meg_rrs) > 0:
color, alpha = (0., 0.25, 0.5), 0.25
surf = dict(rr=meg_rrs, tris=meg_tris)
renderer.surface(surface=surf, color=color,
opacity=alpha, backface_culling=True)
if len(src_rr) > 0:
renderer.quiver3d(
x=src_rr[:, 0], y=src_rr[:, 1], z=src_rr[:, 2],
u=src_nn[:, 0], v=src_nn[:, 1], w=src_nn[:, 2],
color=(1., 1., 0.), mode='cylinder', scale=3e-3,
opacity=0.75, glyph_height=0.25,
glyph_center=(0., 0., 0.), glyph_resolution=20,
backface_culling=True)
if fwd is not None:
red = (1.0, 0.0, 0.0)
green = (0.0, 1.0, 0.0)
blue = (0.0, 0.0, 1.0)
for ori, color in zip(range(fwd_nn.shape[1]), (red, green, blue)):
renderer.quiver3d(fwd_rr[:, 0],
fwd_rr[:, 1],
fwd_rr[:, 2],
fwd_nn[:, ori, 0],
fwd_nn[:, ori, 1],
fwd_nn[:, ori, 2],
color=color, mode='arrow', scale=1.5e-3)
if 'pairs' in fnirs and len(fnirs_picks) > 0:
fnirs_loc = np.array([info['chs'][k]['loc'][3:9] for k in fnirs_picks])
logger.info('Plotting %d fnirs pairs' % (fnirs_loc.shape[0]))
renderer.tube(origin=fnirs_loc[:, :3],
destination=fnirs_loc[:, 3:])
renderer.set_camera(azimuth=90, elevation=90,
distance=0.6, focalpoint=(0., 0., 0.))
renderer.show()
return renderer.scene()
def _make_tris_fan(n_vert):
"""Make tris given a number of vertices of a circle-like obj."""
tris = np.zeros((n_vert - 2, 3), int)
tris[:, 2] = np.arange(2, n_vert)
tris[:, 1] = tris[:, 2] - 1
return tris
def _sensor_shape(coil):
"""Get the sensor shape vertices."""
from scipy.spatial import ConvexHull
id_ = coil['type'] & 0xFFFF
pad = True
# Square figure eight
if id_ in (FIFF.FIFFV_COIL_NM_122,
FIFF.FIFFV_COIL_VV_PLANAR_W,
FIFF.FIFFV_COIL_VV_PLANAR_T1,
FIFF.FIFFV_COIL_VV_PLANAR_T2,
):
# wound by right hand rule such that +x side is "up" (+z)
long_side = coil['size'] # length of long side (meters)
offset = 0.0025 # offset of the center portion of planar grad coil
rrs = np.array([
[offset, -long_side / 2.],
[long_side / 2., -long_side / 2.],
[long_side / 2., long_side / 2.],
[offset, long_side / 2.],
[-offset, -long_side / 2.],
[-long_side / 2., -long_side / 2.],
[-long_side / 2., long_side / 2.],
[-offset, long_side / 2.]])
tris = np.concatenate((_make_tris_fan(4),
_make_tris_fan(4)[:, ::-1] + 4), axis=0)
# Square
elif id_ in (FIFF.FIFFV_COIL_POINT_MAGNETOMETER,
FIFF.FIFFV_COIL_VV_MAG_T1,
FIFF.FIFFV_COIL_VV_MAG_T2,
FIFF.FIFFV_COIL_VV_MAG_T3,
FIFF.FIFFV_COIL_KIT_REF_MAG,
):
# square magnetometer (potentially point-type)
size = 0.001 if id_ == 2000 else (coil['size'] / 2.)
rrs = np.array([[-1., 1.], [1., 1.], [1., -1.], [-1., -1.]]) * size
tris = _make_tris_fan(4)
# Circle
elif id_ in (FIFF.FIFFV_COIL_MAGNES_MAG,
FIFF.FIFFV_COIL_MAGNES_REF_MAG,
FIFF.FIFFV_COIL_CTF_REF_MAG,
FIFF.FIFFV_COIL_BABY_MAG,
FIFF.FIFFV_COIL_BABY_REF_MAG,
FIFF.FIFFV_COIL_ARTEMIS123_REF_MAG,
):
n_pts = 15 # number of points for circle
circle = np.exp(2j * np.pi * np.arange(n_pts) / float(n_pts))
circle = np.concatenate(([0.], circle))
circle *= coil['size'] / 2. # radius of coil
rrs = np.array([circle.real, circle.imag]).T
tris = _make_tris_fan(n_pts + 1)
# Circle
elif id_ in (FIFF.FIFFV_COIL_MAGNES_GRAD,
FIFF.FIFFV_COIL_CTF_GRAD,
FIFF.FIFFV_COIL_CTF_REF_GRAD,
FIFF.FIFFV_COIL_CTF_OFFDIAG_REF_GRAD,
FIFF.FIFFV_COIL_MAGNES_REF_GRAD,
FIFF.FIFFV_COIL_MAGNES_OFFDIAG_REF_GRAD,
FIFF.FIFFV_COIL_KIT_GRAD,
FIFF.FIFFV_COIL_BABY_GRAD,
FIFF.FIFFV_COIL_ARTEMIS123_GRAD,
FIFF.FIFFV_COIL_ARTEMIS123_REF_GRAD,
):
# round coil 1st order (off-diagonal) gradiometer
baseline = coil['base'] if id_ in (5004, 4005) else 0.
n_pts = 16 # number of points for circle
# This time, go all the way around circle to close it fully
circle = np.exp(2j * np.pi * np.arange(-1, n_pts) / float(n_pts - 1))
circle[0] = 0 # center pt for triangulation
circle *= coil['size'] / 2.
rrs = np.array([ # first, second coil
np.concatenate([circle.real + baseline / 2.,
circle.real - baseline / 2.]),
np.concatenate([circle.imag, -circle.imag])]).T
tris = np.concatenate([_make_tris_fan(n_pts + 1),
_make_tris_fan(n_pts + 1) + n_pts + 1])
# 3D convex hull (will fail for 2D geometry, can extend later if needed)
else:
rrs = coil['rmag_orig'].copy()
pad = False
tris = _reorder_ccw(rrs, ConvexHull(rrs).simplices)
# Go from (x,y) -> (x,y,z)
if pad:
rrs = np.pad(rrs, ((0, 0), (0, 1)), mode='constant')
assert rrs.ndim == 2 and rrs.shape[1] == 3
return rrs, tris
def _process_clim(clim, colormap, transparent, data=0., allow_pos_lims=True):
"""Convert colormap/clim options to dict.
This fills in any "auto" entries properly such that round-trip
calling gives the same results.
"""
# Based on type of limits specified, get cmap control points
import matplotlib.pyplot as plt
from matplotlib.colors import Colormap
_validate_type(colormap, (str, Colormap), 'colormap')
data = np.asarray(data)
if isinstance(colormap, str):
if colormap == 'auto':
if clim == 'auto':
if allow_pos_lims and (data < 0).any():
colormap = 'mne'
else:
colormap = 'hot'
else:
if 'lims' in clim:
colormap = 'hot'
else: # 'pos_lims' in clim
colormap = 'mne'
if colormap in ('mne', 'mne_analyze'):
colormap = mne_analyze_colormap([0, 1, 2], format='matplotlib')
else:
colormap = plt.get_cmap(colormap)
assert isinstance(colormap, Colormap)
diverging_maps = ['PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu',
'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr',
'seismic']
diverging_maps += [d + '_r' for d in diverging_maps]
diverging_maps += ['mne', 'mne_analyze']
if clim == 'auto':
# this is merely a heuristic!
if allow_pos_lims and colormap.name in diverging_maps:
key = 'pos_lims'
else:
key = 'lims'
clim = {'kind': 'percent', key: [96, 97.5, 99.95]}
if not isinstance(clim, dict):
raise ValueError('"clim" must be "auto" or dict, got %s' % (clim,))
if ('lims' in clim) + ('pos_lims' in clim) != 1:
raise ValueError('Exactly one of lims and pos_lims must be specified '
'in clim, got %s' % (clim,))
if 'pos_lims' in clim and not allow_pos_lims:
raise ValueError('Cannot use "pos_lims" for clim, use "lims" '
'instead')
diverging = 'pos_lims' in clim
ctrl_pts = np.array(clim['pos_lims' if diverging else 'lims'], float)
ctrl_pts = np.array(ctrl_pts, float)
if ctrl_pts.shape != (3,):
raise ValueError('clim has shape %s, it must be (3,)'
% (ctrl_pts.shape,))
if (np.diff(ctrl_pts) < 0).any():
raise ValueError('colormap limits must be monotonically '
'increasing, got %s' % (ctrl_pts,))
clim_kind = clim.get('kind', 'percent')
_check_option("clim['kind']", clim_kind, ['value', 'values', 'percent'])
if clim_kind == 'percent':
perc_data = np.abs(data) if diverging else data
ctrl_pts = np.percentile(perc_data, ctrl_pts)
logger.info('Using control points %s' % (ctrl_pts,))
assert len(ctrl_pts) == 3
clim = dict(kind='value')
clim['pos_lims' if diverging else 'lims'] = ctrl_pts
mapdata = dict(clim=clim, colormap=colormap, transparent=transparent)
return mapdata
def _separate_map(mapdata):
"""Help plotters that cannot handle limit equality."""
diverging = 'pos_lims' in mapdata['clim']
key = 'pos_lims' if diverging else 'lims'
ctrl_pts = np.array(mapdata['clim'][key])
assert ctrl_pts.shape == (3,)
if len(set(ctrl_pts)) == 1: # three points match
if ctrl_pts[0] == 0: # all are zero
warn('All data were zero')
ctrl_pts = np.arange(3, dtype=float)
else:
ctrl_pts *= [0., 0.5, 1] # all nonzero pts == max
elif len(set(ctrl_pts)) == 2: # two points match
# if points one and two are identical, add a tiny bit to the
# control point two; if points two and three are identical,
# subtract a tiny bit from point two.
bump = 1e-5 if ctrl_pts[0] == ctrl_pts[1] else -1e-5
ctrl_pts[1] = ctrl_pts[0] + bump * (ctrl_pts[2] - ctrl_pts[0])
mapdata['clim'][key] = ctrl_pts
def _linearize_map(mapdata):
from matplotlib.colors import ListedColormap
diverging = 'pos_lims' in mapdata['clim']
scale_pts = mapdata['clim']['pos_lims' if diverging else 'lims']
if diverging:
lims = [-scale_pts[2], scale_pts[2]]
ctrl_norm = np.concatenate([-scale_pts[::-1] / scale_pts[2], [0],
scale_pts / scale_pts[2]]) / 2 + 0.5
linear_norm = [0, 0.25, 0.5, 0.5, 0.5, 0.75, 1]
trans_norm = [1, 1, 0, 0, 0, 1, 1]
else:
lims = [scale_pts[0], scale_pts[2]]
range_ = scale_pts[2] - scale_pts[0]
mid = (scale_pts[1] - scale_pts[0]) / range_ if range_ > 0 else 0.5
ctrl_norm = [0, mid, 1]
linear_norm = [0, 0.5, 1]
trans_norm = [0, 1, 1]
# do the piecewise linear transformation
interp_to = np.linspace(0, 1, 256)
colormap = np.array(mapdata['colormap'](
np.interp(interp_to, ctrl_norm, linear_norm)))
if mapdata['transparent']:
colormap[:, 3] = np.interp(interp_to, ctrl_norm, trans_norm)
lims = np.array([lims[0], np.mean(lims), lims[1]])
colormap = ListedColormap(colormap)
return colormap, lims
def _get_map_ticks(mapdata):
diverging = 'pos_lims' in mapdata['clim']
ticks = mapdata['clim']['pos_lims' if diverging else 'lims']
delta = 1e-2 * (ticks[2] - ticks[0])
if ticks[1] <= ticks[0] + delta: # Only two worth showing
ticks = ticks[::2]
if ticks[1] <= ticks[0] + delta: # Actually only one
ticks = ticks[::2]
if diverging:
idx = int(ticks[0] == 0)
ticks = list(-np.array(ticks[idx:])[::-1]) + [0] + list(ticks[idx:])
return np.array(ticks)
def _handle_time(time_label, time_unit, times):
"""Handle time label string and units."""
_validate_type(time_label, (None, str, 'callable'), 'time_label')
if time_label == 'auto':
if times is not None and len(times) > 1:
if time_unit == 's':
time_label = 'time=%0.3fs'
elif time_unit == 'ms':
time_label = 'time=%0.1fms'
else:
time_label = None
# convert to callable
if isinstance(time_label, str):
time_label_fmt = time_label
def time_label(x):
try:
return time_label_fmt % x
except Exception:
return time_label # in case it's static
assert time_label is None or callable(time_label)
if times is not None:
_, times = _check_time_unit(time_unit, times)
return time_label, times
def _key_pressed_slider(event, params):
"""Handle key presses for time_viewer slider."""
step = 1
if event.key.startswith('ctrl'):
step = 5
event.key = event.key.split('+')[-1]
if event.key not in ['left', 'right']:
return
time_viewer = event.canvas.figure
value = time_viewer.slider.val
times = params['stc'].times
if params['time_unit'] == 'ms':
times = times * 1000.
time_idx = np.argmin(np.abs(times - value))
if event.key == 'left':
time_idx = np.max((0, time_idx - step))
elif event.key == 'right':
time_idx = np.min((len(times) - 1, time_idx + step))
this_time = times[time_idx]
time_viewer.slider.set_val(this_time)
def _smooth_plot(this_time, params):
"""Smooth source estimate data and plot with mpl."""
from ..morph import _morph_buffer
ax = params['ax']
stc = params['stc']
ax.clear()
times = stc.times
scaler = 1000. if params['time_unit'] == 'ms' else 1.
if this_time is None:
time_idx = 0
else:
time_idx = np.argmin(np.abs(times - this_time / scaler))
if params['hemi_idx'] == 0:
data = stc.data[:len(stc.vertices[0]), time_idx:time_idx + 1]
else:
data = stc.data[len(stc.vertices[0]):, time_idx:time_idx + 1]
array_plot = _morph_buffer(data, params['vertices'], params['e'],
params['smoothing_steps'], params['n_verts'],
params['inuse'], params['maps'])
range_ = params['scale_pts'][2] - params['scale_pts'][0]
colors = (array_plot - params['scale_pts'][0]) / range_
faces = params['faces']
greymap = params['greymap']
cmap = params['cmap']
polyc = ax.plot_trisurf(*params['coords'].T, triangles=faces,
antialiased=False, vmin=0, vmax=1)
color_ave = np.mean(colors[faces], axis=1).flatten()
curv_ave = np.mean(params['curv'][faces], axis=1).flatten()
# matplotlib/matplotlib#11877
facecolors = polyc._facecolors3d
colors = cmap(color_ave)
# alpha blend
colors[:, :3] *= colors[:, [3]]
colors[:, :3] += greymap(curv_ave)[:, :3] * (1. - colors[:, [3]])
colors[:, 3] = 1.
facecolors[:] = colors
if params['time_label'] is not None:
ax.set_title(params['time_label'](times[time_idx] * scaler,),
color='w')
_set_aspect_equal(ax)
ax.axis('off')
ax.set(xlim=[-80, 80], ylim=(-80, 80), zlim=[-80, 80])
ax.figure.canvas.draw()
def _plot_mpl_stc(stc, subject=None, surface='inflated', hemi='lh',
colormap='auto', time_label='auto', smoothing_steps=10,
subjects_dir=None, views='lat', clim='auto', figure=None,
initial_time=None, time_unit='s', background='black',
spacing='oct6', time_viewer=False, colorbar=True,
transparent=True):
"""Plot source estimate using mpl."""
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.widgets import Slider
import nibabel as nib
from scipy import stats
from ..morph import _get_subject_sphere_tris
if hemi not in ['lh', 'rh']:
raise ValueError("hemi must be 'lh' or 'rh' when using matplotlib. "
"Got %s." % hemi)
lh_kwargs = {'lat': {'elev': 0, 'azim': 180},
'med': {'elev': 0, 'azim': 0},
'ros': {'elev': 0, 'azim': 90},
'cau': {'elev': 0, 'azim': -90},
'dor': {'elev': 90, 'azim': -90},
'ven': {'elev': -90, 'azim': -90},
'fro': {'elev': 0, 'azim': 106.739},
'par': {'elev': 30, 'azim': -120}}
rh_kwargs = {'lat': {'elev': 0, 'azim': 0},
'med': {'elev': 0, 'azim': 180},
'ros': {'elev': 0, 'azim': 90},
'cau': {'elev': 0, 'azim': -90},
'dor': {'elev': 90, 'azim': -90},
'ven': {'elev': -90, 'azim': -90},
'fro': {'elev': 16.739, 'azim': 60},
'par': {'elev': 30, 'azim': -60}}
time_viewer = False if time_viewer == 'auto' else time_viewer
kwargs = dict(lh=lh_kwargs, rh=rh_kwargs)
_check_option('views', views, sorted(lh_kwargs.keys()))
mapdata = _process_clim(clim, colormap, transparent, stc.data)
_separate_map(mapdata)
colormap, scale_pts = _linearize_map(mapdata)
del transparent, mapdata
time_label, times = _handle_time(time_label, time_unit, stc.times)
fig = plt.figure(figsize=(6, 6)) if figure is None else figure
ax = Axes3D(fig)
hemi_idx = 0 if hemi == 'lh' else 1
surf = op.join(subjects_dir, subject, 'surf', '%s.%s' % (hemi, surface))
if spacing == 'all':
coords, faces = nib.freesurfer.read_geometry(surf)
inuse = slice(None)
else:
stype, sval, ico_surf, src_type_str = _check_spacing(spacing)
surf = _create_surf_spacing(surf, hemi, subject, stype, ico_surf,
subjects_dir)
inuse = surf['vertno']
faces = surf['use_tris']
coords = surf['rr'][inuse]
shape = faces.shape
faces = stats.rankdata(faces, 'dense').reshape(shape) - 1
faces = np.round(faces).astype(int) # should really be int-like anyway
del surf
vertices = stc.vertices[hemi_idx]
n_verts = len(vertices)
tris = _get_subject_sphere_tris(subject, subjects_dir)[hemi_idx]
e = mesh_edges(tris)
e.data[e.data == 2] = 1
n_vertices = e.shape[0]
maps = sparse.identity(n_vertices).tocsr()
e = e + sparse.eye(n_vertices, n_vertices)
cmap = cm.get_cmap(colormap)
greymap = cm.get_cmap('Greys')
curv = nib.freesurfer.read_morph_data(
op.join(subjects_dir, subject, 'surf', '%s.curv' % hemi))[inuse]
curv = np.clip(np.array(curv > 0, np.int), 0.33, 0.66)
params = dict(ax=ax, stc=stc, coords=coords, faces=faces,
hemi_idx=hemi_idx, vertices=vertices, e=e,
smoothing_steps=smoothing_steps, n_verts=n_verts,
inuse=inuse, maps=maps, cmap=cmap, curv=curv,
scale_pts=scale_pts, greymap=greymap, time_label=time_label,
time_unit=time_unit)
_smooth_plot(initial_time, params)
ax.view_init(**kwargs[hemi][views])
try:
ax.set_facecolor(background)
except AttributeError:
ax.set_axis_bgcolor(background)
if time_viewer:
time_viewer = figure_nobar(figsize=(4.5, .25))
fig.time_viewer = time_viewer
ax_time = plt.axes()
if initial_time is None:
initial_time = 0
slider = Slider(ax=ax_time, label='Time', valmin=times[0],
valmax=times[-1], valinit=initial_time)
time_viewer.slider = slider
callback_slider = partial(_smooth_plot, params=params)
slider.on_changed(callback_slider)
callback_key = partial(_key_pressed_slider, params=params)
time_viewer.canvas.mpl_connect('key_press_event', callback_key)
time_viewer.subplots_adjust(left=0.12, bottom=0.05, right=0.75,
top=0.95)
fig.subplots_adjust(left=0., bottom=0., right=1., top=1.)
# add colorbar
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
sm = plt.cm.ScalarMappable(cmap=cmap,
norm=plt.Normalize(scale_pts[0], scale_pts[2]))
cax = inset_axes(ax, width="80%", height="5%", loc=8, borderpad=3.)
plt.setp(plt.getp(cax, 'xticklabels'), color='w')
sm.set_array(np.linspace(scale_pts[0], scale_pts[2], 256))
if colorbar:
cb = plt.colorbar(sm, cax=cax, orientation='horizontal')
cb_yticks = plt.getp(cax, 'yticklabels')
plt.setp(cb_yticks, color='w')
cax.tick_params(labelsize=16)
cb.patch.set_facecolor('0.5')
cax.set(xlim=(scale_pts[0], scale_pts[2]))
plt.show()
return fig
def link_brains(brains):
"""Plot multiple SourceEstimate objects with PyVista.
Parameters
----------
brains : list, tuple or np.ndarray
The collection of brains to plot.
"""
from .backends.renderer import _get_3d_backend
if _get_3d_backend() != 'pyvista':
raise NotImplementedError("Expected 3d backend is pyvista but"
" {} was given.".format(_get_3d_backend()))
from ._brain import _Brain, _TimeViewer, _LinkViewer
if not isinstance(brains, Iterable):
brains = [brains]
if len(brains) == 0:
raise ValueError("The collection of brains is empty.")
for brain in brains:
if isinstance(brain, _Brain):
# check if the _TimeViewer wrapping is not already applied
if not hasattr(brain, 'time_viewer') or brain.time_viewer is None:
brain = _TimeViewer(brain)
else:
raise TypeError("Expected type is Brain but"
" {} was given.".format(type(brain)))
# link brains properties
_LinkViewer(brains)
@verbose
def plot_source_estimates(stc, subject=None, surface='inflated', hemi='lh',
colormap='auto', time_label='auto',
smoothing_steps=10, transparent=True, alpha=1.0,
time_viewer='auto', subjects_dir=None, figure=None,
views='lat', colorbar=True, clim='auto',
cortex="classic", size=800, background="black",
foreground="white", initial_time=None,
time_unit='s', backend='auto', spacing='oct6',
title=None, show_traces='auto', verbose=None):
"""Plot SourceEstimate with PySurfer.
By default this function uses :mod:`mayavi.mlab` to plot the source
estimates. If Mayavi is not installed, the plotting is done with
:mod:`matplotlib.pyplot` (much slower, decimated source space by default).
Parameters
----------
stc : SourceEstimate
The source estimates to plot.
subject : str | None
The subject name corresponding to FreeSurfer environment
variable SUBJECT. If None stc.subject will be used. If that
is None, the environment will be used.
surface : str
The type of surface (inflated, white etc.).
hemi : str
Hemisphere id (ie 'lh', 'rh', 'both', or 'split'). In the case
of 'both', both hemispheres are shown in the same window.
In the case of 'split' hemispheres are displayed side-by-side
in different viewing panes.
%(colormap)s
The default ('auto') uses 'hot' for one-sided data and
'mne' for two-sided data.
%(time_label)s
smoothing_steps : int
The amount of smoothing.
%(transparent)s
alpha : float
Alpha value to apply globally to the overlay. Has no effect with mpl
backend.
time_viewer : bool | str
Display time viewer GUI. Can also be 'auto', which will mean True
for the PyVista backend and False otherwise.
.. versionchanged:: 0.20.0
"auto" mode added.
%(subjects_dir)s
figure : instance of mayavi.core.api.Scene | instance of matplotlib.figure.Figure | list | int | None
If None, a new figure will be created. If multiple views or a
split view is requested, this must be a list of the appropriate
length. If int is provided it will be used to identify the Mayavi
figure by it's id or create a new figure with the given id. If an
instance of matplotlib figure, mpl backend is used for plotting.
views : str | list
View to use. See `surfer.Brain`. Supported views: ['lat', 'med', 'ros',
'cau', 'dor' 'ven', 'fro', 'par']. Using multiple views is not
supported for mpl backend.
colorbar : bool
If True, display colorbar on scene.
%(clim)s
cortex : str or tuple
Specifies how binarized curvature values are rendered.
Either the name of a preset PySurfer cortex colorscheme (one of
'classic', 'bone', 'low_contrast', or 'high_contrast'), or the name of
mayavi colormap, or a tuple with values (colormap, min, max, reverse)
to fully specify the curvature colors. Has no effect with mpl backend.
size : float or tuple of float
The size of the window, in pixels. can be one number to specify
a square window, or the (width, height) of a rectangular window.
Has no effect with mpl backend.
background : matplotlib color
Color of the background of the display window.
foreground : matplotlib color
Color of the foreground of the display window. Has no effect with mpl
backend.
initial_time : float | None
The time to display on the plot initially. ``None`` to display the
first time sample (default).
time_unit : 's' | 'ms'
Whether time is represented in seconds ("s", default) or
milliseconds ("ms").
backend : 'auto' | 'mayavi' | 'matplotlib'
Which backend to use. If ``'auto'`` (default), tries to plot with
mayavi, but resorts to matplotlib if mayavi is not available.
.. versionadded:: 0.15.0
spacing : str
The spacing to use for the source space. Can be ``'ico#'`` for a
recursively subdivided icosahedron, ``'oct#'`` for a recursively
subdivided octahedron, or ``'all'`` for all points. In general, you can
speed up the plotting by selecting a sparser source space. Has no
effect with mayavi backend. Defaults to 'oct6'.
.. versionadded:: 0.15.0
title : str | None
Title for the figure. If None, the subject name will be used.
.. versionadded:: 0.17.0
%(show_traces)s
%(verbose)s
Returns
-------
figure : instance of surfer.Brain | matplotlib.figure.Figure
An instance of :class:`surfer.Brain` from PySurfer or
matplotlib figure.
""" # noqa: E501
from .backends.renderer import _get_3d_backend, set_3d_backend
# import here to avoid circular import problem
from ..source_estimate import SourceEstimate
_validate_type(stc, SourceEstimate, "stc", "Surface Source Estimate")
subjects_dir = get_subjects_dir(subjects_dir=subjects_dir,
raise_error=True)
subject = _check_subject(stc.subject, subject, True)
_check_option('backend', backend, ['auto', 'matplotlib', 'mayavi'])
plot_mpl = backend == 'matplotlib'
if not plot_mpl:
try:
set_3d_backend(_get_3d_backend())
except (ImportError, ModuleNotFoundError):
if backend == 'auto':
warn('No 3D backend found. Resorting to matplotlib 3d.')
plot_mpl = True
else: # 'mayavi'
raise
if plot_mpl:
return _plot_mpl_stc(stc, subject=subject, surface=surface, hemi=hemi,
colormap=colormap, time_label=time_label,
smoothing_steps=smoothing_steps,
subjects_dir=subjects_dir, views=views, clim=clim,
figure=figure, initial_time=initial_time,
time_unit=time_unit, background=background,
spacing=spacing, time_viewer=time_viewer,
colorbar=colorbar, transparent=transparent)
if _get_3d_backend() == "mayavi":
from surfer import Brain
else: # PyVista
from ._brain import _Brain as Brain
_check_option('hemi', hemi, ['lh', 'rh', 'split', 'both'])
time_label, times = _handle_time(time_label, time_unit, stc.times)
# convert control points to locations in colormap
mapdata = _process_clim(clim, colormap, transparent, stc.data)
# XXX we should only need to do this for PySurfer/Mayavi, the PyVista
# plotter should be smart enough to do this separation in the cmap-to-ctab
# conversion. But this will need to be another refactoring that will
# hopefully restore this line:
#
# if _get_3d_backend() == 'mayavi':
_separate_map(mapdata)
colormap = mapdata['colormap']
diverging = 'pos_lims' in mapdata['clim']
scale_pts = mapdata['clim']['pos_lims' if diverging else 'lims']
transparent = mapdata['transparent']
del mapdata
if hemi in ['both', 'split']:
hemis = ['lh', 'rh']
else:
hemis = [hemi]
if title is None:
title = subject if len(hemis) > 1 else '%s - %s' % (subject, hemis[0])
kwargs = {
"subject_id": subject, "hemi": hemi, "surf": surface,
"title": title, "cortex": cortex, "size": size,
"background": background, "foreground": foreground,
"figure": figure, "subjects_dir": subjects_dir,
"views": views
}
if _get_3d_backend() == "pyvista":
kwargs["show"] = not time_viewer
with warnings.catch_warnings(record=True): # traits warnings
brain = Brain(**kwargs)
center = 0. if diverging else None
for hemi in hemis:
hemi_idx = 0 if hemi == 'lh' else 1
data = getattr(stc, hemi + '_data')
vertices = stc.vertices[hemi_idx]
if len(data) > 0:
if transparent is None:
transparent = True
kwargs = {
"array": data, "colormap": colormap,
"vertices": vertices,
"smoothing_steps": smoothing_steps,
"time": times, "time_label": time_label,
"alpha": alpha, "hemi": hemi,
"colorbar": colorbar, "initial_time": initial_time,
"transparent": transparent, "center": center,
"verbose": False
}
if _get_3d_backend() == "mayavi":
kwargs["min"] = scale_pts[0]
kwargs["mid"] = scale_pts[1]
kwargs["max"] = scale_pts[2]
else: # pyvista
kwargs["fmin"] = scale_pts[0]
kwargs["fmid"] = scale_pts[1]
kwargs["fmax"] = scale_pts[2]
kwargs["clim"] = clim
with warnings.catch_warnings(record=True): # traits warnings
brain.add_data(**kwargs)
_check_time_viewer_compatibility(brain, time_viewer, show_traces)
return brain
def _check_time_viewer_compatibility(brain, time_viewer, show_traces):
from .backends.renderer import _get_3d_backend
using_mayavi = _get_3d_backend() == "mayavi"
_check_option('time_viewer', time_viewer, (True, False, 'auto'))
_check_option('show_traces', show_traces,
(True, False, 'auto', 'separate'))
if time_viewer == 'auto':
time_viewer = not using_mayavi
if show_traces == 'auto':
show_traces = (
not using_mayavi and
time_viewer and
brain._times is not None and
len(brain._times) > 1 and
# XXX temporary hidden workaround for memory problems on CircleCI
os.getenv('_MNE_BRAIN_TRACES_AUTO', 'true').lower() != 'false'
)
if _get_3d_backend() == "mayavi" and all([time_viewer, show_traces]):
raise NotImplementedError("Point picking is not available"
" for the mayavi 3d backend.")
if using_mayavi:
if not check_version('surfer', '0.9'):
raise RuntimeError('This function requires pysurfer version '
'>= 0.9')
if time_viewer:
if using_mayavi:
from surfer import TimeViewer
TimeViewer(brain)
else: # PyVista
from ._brain import _TimeViewer as TimeViewer
TimeViewer(brain, show_traces=show_traces)
def _glass_brain_crosshairs(params, x, y, z):
for ax, a, b in ((params['ax_y'], x, z),
(params['ax_x'], y, z),
(params['ax_z'], x, y)):
ax.axvline(a, color='0.75')
ax.axhline(b, color='0.75')
def _cut_coords_to_ijk(cut_coords, img):
ijk = apply_trans(linalg.inv(img.affine), cut_coords)
ijk = np.clip(np.round(ijk).astype(int), 0, np.array(img.shape[:3]) - 1)
return ijk
def _ijk_to_cut_coords(ijk, img):
return apply_trans(img.affine, ijk)
@verbose
def plot_volume_source_estimates(stc, src, subject=None, subjects_dir=None,
mode='stat_map', bg_img=None, colorbar=True,
colormap='auto', clim='auto',
transparent=None, show=True,
initial_time=None, initial_pos=None,
verbose=None):
"""Plot Nutmeg style volumetric source estimates using nilearn.
Parameters
----------
stc : VectorSourceEstimate
The vector source estimate to plot.
src : instance of SourceSpaces | instance of SourceMorph
The source space. Can also be a SourceMorph to morph the STC to
a new subject (see Examples).
.. versionchanged:: 0.18
Support for :class:`~nibabel.spatialimages.SpatialImage`.
subject : str | None
The subject name corresponding to FreeSurfer environment
variable SUBJECT. If None stc.subject will be used. If that
is None, the environment will be used.
%(subjects_dir)s
mode : str
The plotting mode to use. Either 'stat_map' (default) or 'glass_brain'.
For "glass_brain", activation absolute values are displayed
after being transformed to a standard MNI brain.
bg_img : instance of SpatialImage | None
The background image used in the nilearn plotting function.
If None, it is the T1.mgz file that is found in the subjects_dir.
Not used in "glass brain" plotting.
colorbar : bool, optional
If True, display a colorbar on the right of the plots.
%(colormap)s
%(clim)s
%(transparent)s
show : bool
Show figures if True. Defaults to True.
initial_time : float | None
The initial time to plot. Can be None (default) to use the time point
with the maximal absolute value activation across all voxels
or the ``initial_pos`` voxel (if ``initial_pos is None`` or not,
respectively).
.. versionadded:: 0.19
initial_pos : ndarray, shape (3,) | None
The initial position to use (in m). Can be None (default) to use the
voxel with the maximum absolute value activation across all time points
or at ``initial_time`` (if ``initial_time is None`` or not,
respectively).
.. versionadded:: 0.19
%(verbose)s
Returns
-------
fig : instance of Figure
The figure.
Notes
-----
Click on any of the anatomical slices to explore the time series.
Clicking on any time point will bring up the corresponding anatomical map.
The left and right arrow keys can be used to navigate in time.
To move in time by larger steps, use shift+left and shift+right.
In ``'glass_brain'`` mode, values are transformed to the standard MNI
brain using the FreeSurfer Talairach transformation
``$SUBJECTS_DIR/$SUBJECT/mri/transforms/talairach.xfm``.
.. versionadded:: 0.17
.. versionchanged:: 0.19
MRI volumes are automatically transformed to MNI space in
``'glass_brain'`` mode.
Examples
--------
Passing a :class:`mne.SourceMorph` as the ``src``
parameter can be useful for plotting in a different subject's space
(here, a ``'sample'`` STC in ``'fsaverage'``'s space)::
>>> morph = mne.compute_source_morph(src_sample, subject_to='fsaverage') # doctest: +SKIP
>>> fig = stc_vol_sample.plot(morph) # doctest: +SKIP
""" # noqa: E501
from matplotlib import pyplot as plt, colors
from matplotlib.cbook import mplDeprecation
import nibabel as nib
from ..source_estimate import VolSourceEstimate
from ..morph import SourceMorph
if not check_version('nilearn', '0.4'):
raise RuntimeError('This function requires nilearn >= 0.4')
from nilearn.plotting import plot_stat_map, plot_glass_brain
from nilearn.image import index_img
_check_option('mode', mode, ('stat_map', 'glass_brain'))
plot_func = dict(stat_map=plot_stat_map,
glass_brain=plot_glass_brain)[mode]
_validate_type(stc, VolSourceEstimate, 'stc')
if isinstance(src, SourceMorph):
img = src.apply(stc, 'nifti1', mri_resolution=False, mri_space=False)
stc = src.apply(stc, mri_resolution=False, mri_space=False)
kind, src_subject = 'morph.subject_to', src.subject_to
else:
src = _ensure_src(src, kind='volume', extra=' or SourceMorph')
img = stc.as_volume(src, mri_resolution=False)
kind, src_subject = 'src subject', src._subject
del src
_print_coord_trans(Transform('mri_voxel', 'ras', img.affine),
prefix='Image affine ', units='mm', level='debug')
subject = _check_subject(src_subject, subject, True, kind=kind)
stc_ijk = np.array(
np.unravel_index(stc.vertices[0], img.shape[:3], order='F')).T
assert stc_ijk.shape == (len(stc.vertices[0]), 3)
del kind
# XXX this assumes zooms are uniform, should probably mult by zooms...
dist_to_verts = _DistanceQuery(stc_ijk, allow_kdtree=True)
def _cut_coords_to_idx(cut_coords, img):
"""Convert voxel coordinates to index in stc.data."""
ijk = _cut_coords_to_ijk(cut_coords, img)
del cut_coords
logger.debug(' Affine remapped cut coords to [%d, %d, %d] idx'
% tuple(ijk))
dist, loc_idx = dist_to_verts.query(ijk[np.newaxis])
dist, loc_idx = dist[0], loc_idx[0]
logger.debug(' Using vertex %d at a distance of %d voxels'
% (stc.vertices[0][loc_idx], dist))
return loc_idx
ax_name = dict(x='X (saggital)', y='Y (coronal)', z='Z (axial)')
def _click_to_cut_coords(event, params):
"""Get voxel coordinates from mouse click."""
if event.inaxes is params['ax_x']:
ax = 'x'
x = params['ax_z'].lines[0].get_xdata()[0]
y, z = event.xdata, event.ydata
elif event.inaxes is params['ax_y']:
ax = 'y'
y = params['ax_x'].lines[0].get_xdata()[0]
x, z = event.xdata, event.ydata
elif event.inaxes is params['ax_z']:
ax = 'z'
x, y = event.xdata, event.ydata
z = params['ax_x'].lines[1].get_ydata()[0]
else:
logger.debug(' Click outside axes')
return None
cut_coords = np.array((x, y, z))
logger.debug('')
if params['mode'] == 'glass_brain': # find idx for MIP
# Figure out what XYZ in world coordinates is in our voxel data
codes = ''.join(nib.aff2axcodes(params['img_idx'].affine))
assert len(codes) == 3
# We don't care about directionality, just which is which dim
codes = codes.replace('L', 'R').replace('P', 'A').replace('I', 'S')
idx = codes.index(dict(x='R', y='A', z='S')[ax])
img_data = np.abs(_get_img_fdata(params['img_idx']))
ijk = _cut_coords_to_ijk(cut_coords, params['img_idx'])
if idx == 0:
ijk[0] = np.argmax(img_data[:, ijk[1], ijk[2]])
logger.debug(' MIP: i = %d idx' % (ijk[0],))
elif idx == 1:
ijk[1] = np.argmax(img_data[ijk[0], :, ijk[2]])
logger.debug(' MIP: j = %d idx' % (ijk[1],))
else:
ijk[2] = np.argmax(img_data[ijk[0], ijk[1], :])
logger.debug(' MIP: k = %d idx' % (ijk[2],))
cut_coords = _ijk_to_cut_coords(ijk, params['img_idx'])
logger.debug(' Cut coords for %s: (%0.1f, %0.1f, %0.1f) mm'
% ((ax_name[ax],) + tuple(cut_coords)))
return cut_coords
def _press(event, params):
"""Manage keypress on the plot."""
pos = params['lx'].get_xdata()
idx = params['stc'].time_as_index(pos)[0]
if event.key == 'left':
idx = max(0, idx - 2)
elif event.key == 'shift+left':
idx = max(0, idx - 10)
elif event.key == 'right':
idx = min(params['stc'].shape[1] - 1, idx + 2)
elif event.key == 'shift+right':
idx = min(params['stc'].shape[1] - 1, idx + 10)
_update_timeslice(idx, params)
params['fig'].canvas.draw()
def _update_timeslice(idx, params):
params['lx'].set_xdata(idx / params['stc'].sfreq +
params['stc'].tmin)
ax_x, ax_y, ax_z = params['ax_x'], params['ax_y'], params['ax_z']
plot_map_callback = params['plot_func']
# Crosshairs are the first thing plotted in stat_map, and the last
# in glass_brain
idxs = [0, 0, 1] if mode == 'stat_map' else [-2, -2, -1]
cut_coords = (
ax_y.lines[idxs[0]].get_xdata()[0],
ax_x.lines[idxs[1]].get_xdata()[0],
ax_x.lines[idxs[2]].get_ydata()[0])
ax_x.clear()
ax_y.clear()
ax_z.clear()
params.update({'img_idx': index_img(img, idx)})
params.update({'title': 'Activation (t=%.3f s.)'
% params['stc'].times[idx]})
plot_map_callback(
params['img_idx'], title='', cut_coords=cut_coords)
@verbose_dec
def _onclick(event, params, verbose=None):
"""Manage clicks on the plot."""
ax_x, ax_y, ax_z = params['ax_x'], params['ax_y'], params['ax_z']
plot_map_callback = params['plot_func']
if event.inaxes is params['ax_time']:
idx = params['stc'].time_as_index(
event.xdata, use_rounding=True)[0]
_update_timeslice(idx, params)
cut_coords = _click_to_cut_coords(event, params)
if cut_coords is None:
return # not in any axes
ax_x.clear()
ax_y.clear()
ax_z.clear()
plot_map_callback(params['img_idx'], title='',
cut_coords=cut_coords)
loc_idx = _cut_coords_to_idx(cut_coords, params['img_idx'])
ydata = stc.data[loc_idx]
if loc_idx is not None:
ax_time.lines[0].set_ydata(ydata)
else:
ax_time.lines[0].set_ydata(0.)
params['fig'].canvas.draw()
if mode == 'glass_brain':
subject = _check_subject(stc.subject, subject, True)
ras_mni_t = read_ras_mni_t(subject, subjects_dir)
if not np.allclose(ras_mni_t['trans'], np.eye(4)):
_print_coord_trans(
ras_mni_t, prefix='Transforming subject ', units='mm')
logger.info('')
# To get from voxel coords to world coords (i.e., define affine)
# we would apply img.affine, then also apply ras_mni_t, which
# transforms from the subject's RAS to MNI RAS. So we left-multiply
# these.
img = nib.Nifti1Image(
img.dataobj, np.dot(ras_mni_t['trans'], img.affine))
bg_img = None # not used
else: # stat_map
if bg_img is None:
subject = _check_subject(stc.subject, subject, True)
subjects_dir = get_subjects_dir(subjects_dir=subjects_dir,
raise_error=True)
t1_fname = op.join(subjects_dir, subject, 'mri', 'T1.mgz')
bg_img = nib.load(t1_fname)
if initial_time is None:
time_sl = slice(0, None)
else:
initial_time = float(initial_time)
logger.info('Fixing initial time: %s sec' % (initial_time,))
initial_time = np.argmin(np.abs(stc.times - initial_time))
time_sl = slice(initial_time, initial_time + 1)
if initial_pos is None: # find max pos and (maybe) time
loc_idx, time_idx = np.unravel_index(
np.abs(stc.data[:, time_sl]).argmax(), stc.data[:, time_sl].shape)
time_idx += time_sl.start
else: # position specified
initial_pos = np.array(initial_pos, float)
if initial_pos.shape != (3,):
raise ValueError('initial_pos must be float ndarray with shape '
'(3,), got shape %s' % (initial_pos.shape,))
initial_pos *= 1000
logger.info('Fixing initial position: %s mm'
% (initial_pos.tolist(),))
loc_idx = _cut_coords_to_idx(initial_pos, img)
if initial_time is not None: # time also specified
time_idx = time_sl.start
else: # find the max
time_idx = np.argmax(np.abs(stc.data[loc_idx]))
img_idx = index_img(img, time_idx)
assert img_idx.shape == img.shape[:3]
del initial_time, initial_pos
ijk = stc_ijk[loc_idx]
cut_coords = _ijk_to_cut_coords(ijk, img_idx)
np.testing.assert_allclose(_cut_coords_to_ijk(cut_coords, img_idx), ijk)
logger.info('Showing: t = %0.3f s, (%0.1f, %0.1f, %0.1f) mm, '
'[%d, %d, %d] vox, %d vertex'
% ((stc.times[time_idx],) + tuple(cut_coords) + tuple(ijk) +
(stc.vertices[0][loc_idx],)))
del ijk
# Plot initial figure
fig, (axes, ax_time) = plt.subplots(2)
axes.set(xticks=[], yticks=[])
marker = 'o' if len(stc.times) == 1 else None
ydata = stc.data[loc_idx]
ax_time.plot(stc.times, ydata, color='k', marker=marker)
if len(stc.times) > 1:
ax_time.set(xlim=stc.times[[0, -1]])
ax_time.set(xlabel='Time (s)', ylabel='Activation')
lx = ax_time.axvline(stc.times[time_idx], color='g')
fig.tight_layout()
allow_pos_lims = (mode != 'glass_brain')
mapdata = _process_clim(clim, colormap, transparent, stc.data,
allow_pos_lims)
_separate_map(mapdata)
diverging = 'pos_lims' in mapdata['clim']
ticks = _get_map_ticks(mapdata)
colormap, scale_pts = _linearize_map(mapdata)
del mapdata
ylim = [min((scale_pts[0], ydata.min())),
max((scale_pts[-1], ydata.max()))]
ylim = np.array(ylim) + np.array([-1, 1]) * 0.05 * np.diff(ylim)[0]
dup_neg = False
if stc.data.min() < 0:
ax_time.axhline(0., color='0.5', ls='-', lw=0.5, zorder=2)
dup_neg = not diverging # glass brain with signed data
yticks = list(ticks)
if dup_neg:
yticks += [0] + list(-np.array(ticks))
yticks = np.unique(yticks)
ax_time.set(yticks=yticks)
ax_time.set(ylim=ylim)
del yticks
if not diverging: # set eq above iff one-sided
# there is a bug in nilearn where this messes w/transparency
# Need to double the colormap
if (scale_pts < 0).any():
# XXX We should fix this, but it's hard to get nilearn to
# use arbitrary bounds :(
# Should get them to support non-mirrored colorbars, or
# at least a proper `vmin` for one-sided things.
# Hopefully this is a sufficiently rare use case!
raise ValueError('Negative colormap limits for sequential '
'control points clim["lims"] not supported '
'currently, consider shifting or flipping the '
'sign of your data for visualization purposes')
# due to nilearn plotting weirdness, extend this to go
# -scale_pts[2]->scale_pts[2] instead of scale_pts[0]->scale_pts[2]
colormap = plt.get_cmap(colormap)
colormap = colormap(
np.interp(np.linspace(-1, 1, 256),
scale_pts / scale_pts[2],
[0, 0.5, 1]))
colormap = colors.ListedColormap(colormap)
vmax = scale_pts[-1]
# black_bg = True is needed because of some matplotlib
# peculiarity. See: https://stackoverflow.com/a/34730204
# Otherwise, event.inaxes does not work for ax_x and ax_z
plot_kwargs = dict(
threshold=None, axes=axes,
resampling_interpolation='nearest', vmax=vmax, figure=fig,
colorbar=colorbar, bg_img=bg_img, cmap=colormap, black_bg=True,
symmetric_cbar=True)
def plot_and_correct(*args, **kwargs):
axes.clear()
if params.get('fig_anat') is not None and plot_kwargs['colorbar']:
params['fig_anat']._cbar.ax.clear()
with warnings.catch_warnings(record=True): # nilearn bug; ax recreated
warnings.simplefilter('ignore', mplDeprecation)
params['fig_anat'] = partial(
plot_func, **plot_kwargs)(*args, **kwargs)
params['fig_anat']._cbar.outline.set_visible(False)
for key in 'xyz':
params.update({'ax_' + key: params['fig_anat'].axes[key].ax})
# Fix nilearn bug w/cbar background being white
if plot_kwargs['colorbar']:
params['fig_anat']._cbar.patch.set_facecolor('0.5')
# adjust one-sided colorbars
if not diverging:
_crop_colorbar(params['fig_anat']._cbar, *scale_pts[[0, -1]])
params['fig_anat']._cbar.set_ticks(params['cbar_ticks'])
if mode == 'glass_brain':
_glass_brain_crosshairs(params, *kwargs['cut_coords'])
params = dict(stc=stc, ax_time=ax_time, plot_func=plot_and_correct,
img_idx=img_idx, fig=fig, lx=lx, mode=mode, cbar_ticks=ticks)
plot_and_correct(stat_map_img=params['img_idx'], title='',
cut_coords=cut_coords)
if show:
plt.show()
fig.canvas.mpl_connect('button_press_event',
partial(_onclick, params=params, verbose=verbose))
fig.canvas.mpl_connect('key_press_event',
partial(_press, params=params))
return fig
@verbose
def plot_vector_source_estimates(stc, subject=None, hemi='lh', colormap='hot',
time_label='auto', smoothing_steps=10,
transparent=None, brain_alpha=0.4,
overlay_alpha=None, vector_alpha=1.0,
scale_factor=None, time_viewer='auto',
subjects_dir=None, figure=None, views='lat',
colorbar=True, clim='auto', cortex='classic',
size=800, background='black',
foreground='white', initial_time=None,
time_unit='s', show_traces='auto',
verbose=None):
"""Plot VectorSourceEstimate with PySurfer.
A "glass brain" is drawn and all dipoles defined in the source estimate
are shown using arrows, depicting the direction and magnitude of the
current moment at the dipole. Additionally, an overlay is plotted on top of
the cortex with the magnitude of the current.
Parameters
----------
stc : VectorSourceEstimate
The vector source estimate to plot.
subject : str | None
The subject name corresponding to FreeSurfer environment
variable SUBJECT. If None stc.subject will be used. If that
is None, the environment will be used.
hemi : str, 'lh' | 'rh' | 'split' | 'both'
The hemisphere to display.
%(colormap)s
This should be a sequential colormap.
%(time_label)s
smoothing_steps : int
The amount of smoothing.
%(transparent)s
brain_alpha : float
Alpha value to apply globally to the surface meshes. Defaults to 0.4.
overlay_alpha : float
Alpha value to apply globally to the overlay. Defaults to
``brain_alpha``.
vector_alpha : float
Alpha value to apply globally to the vector glyphs. Defaults to 1.
scale_factor : float | None
Scaling factor for the vector glyphs. By default, an attempt is made to
automatically determine a sane value.
time_viewer : bool | str
Display time viewer GUI. Can be "auto", which is True for the PyVista
backend and False otherwise.
.. versionchanged:: 0.20
Added "auto" option and default.
subjects_dir : str
The path to the freesurfer subjects reconstructions.
It corresponds to Freesurfer environment variable SUBJECTS_DIR.
figure : instance of mayavi.core.api.Scene | list | int | None
If None, a new figure will be created. If multiple views or a
split view is requested, this must be a list of the appropriate
length. If int is provided it will be used to identify the Mayavi
figure by it's id or create a new figure with the given id.
views : str | list
View to use. See `surfer.Brain`.
colorbar : bool
If True, display colorbar on scene.
%(clim_onesided)s
cortex : str or tuple
Specifies how binarized curvature values are rendered.
either the name of a preset PySurfer cortex colorscheme (one of
'classic', 'bone', 'low_contrast', or 'high_contrast'), or the
name of mayavi colormap, or a tuple with values (colormap, min,
max, reverse) to fully specify the curvature colors.
size : float or tuple of float
The size of the window, in pixels. can be one number to specify
a square window, or the (width, height) of a rectangular window.
background : matplotlib color
Color of the background of the display window.
foreground : matplotlib color
Color of the foreground of the display window.
initial_time : float | None
The time to display on the plot initially. ``None`` to display the
first time sample (default).
time_unit : 's' | 'ms'
Whether time is represented in seconds ("s", default) or
milliseconds ("ms").
%(show_traces)s
%(verbose)s
Returns
-------
brain : surfer.Brain
A instance of :class:`surfer.Brain` from PySurfer.
Notes
-----
.. versionadded:: 0.15
If the current magnitude overlay is not desired, set ``overlay_alpha=0``
and ``smoothing_steps=1``.
"""
from .backends.renderer import _get_3d_backend
# Import here to avoid circular imports
if _get_3d_backend() == "mayavi":
from surfer import Brain
from surfer import __version__ as surfer_version
else: # PyVista
from ._brain import _Brain as Brain
from ..source_estimate import VectorSourceEstimate
_validate_type(stc, VectorSourceEstimate, "stc", "Vector Source Estimate")
subjects_dir = get_subjects_dir(subjects_dir=subjects_dir,
raise_error=True)
subject = _check_subject(stc.subject, subject, True)
_check_option('hemi', hemi, ['lh', 'rh', 'split', 'both'])
time_label, times = _handle_time(time_label, time_unit, stc.times)
# convert control points to locations in colormap
mapdata = _process_clim(clim, colormap, transparent, stc.data,
allow_pos_lims=False)
colormap = mapdata['colormap']
scale_pts = mapdata['clim']['lims'] # pos_lims not allowed
transparent = mapdata['transparent']
del mapdata
if hemi in ['both', 'split']:
hemis = ['lh', 'rh']
else:
hemis = [hemi]
if overlay_alpha is None:
overlay_alpha = brain_alpha
if overlay_alpha == 0:
smoothing_steps = 1 # Disable smoothing to save time.
title = subject if len(hemis) > 1 else '%s - %s' % (subject, hemis[0])
with warnings.catch_warnings(record=True): # traits warnings
brain = Brain(subject, hemi=hemi, surf='white',
title=title, cortex=cortex, size=size,
background=background, foreground=foreground,
figure=figure, subjects_dir=subjects_dir,
views=views, alpha=brain_alpha)
if scale_factor is None:
# Configure the glyphs scale directly
width = np.mean([np.ptp(brain.geo[hemi].coords[:, 1])
for hemi in hemis if hemi in brain.geo])
scale_factor = 0.025 * width / scale_pts[-1]
sd_kwargs = dict(transparent=transparent, verbose=False)
for hemi in hemis:
hemi_idx = 0 if hemi == 'lh' else 1
data = getattr(stc, hemi + '_data')
vertices = stc.vertices[hemi_idx]
if len(data) > 0:
kwargs = {
"array": data, "colormap": colormap,
"vertices": vertices,
"smoothing_steps": smoothing_steps,
"time": times, "time_label": time_label,
"alpha": overlay_alpha, "hemi": hemi,
"colorbar": colorbar,
"vector_alpha": vector_alpha,
"scale_factor": scale_factor,
"verbose": False,
}
if initial_time is not None:
kwargs['initial_time'] = initial_time
if _get_3d_backend() == "mayavi":
if surfer_version >= LooseVersion('0.9'):
kwargs["transparent"] = transparent
kwargs["min"] = scale_pts[0]
kwargs["mid"] = scale_pts[1]
kwargs["max"] = scale_pts[2]
else:
kwargs["transparent"] = transparent
kwargs["fmin"] = scale_pts[0]
kwargs["fmid"] = scale_pts[1]
kwargs["fmax"] = scale_pts[2]
with warnings.catch_warnings(record=True): # traits warnings
brain.add_data(**kwargs)
brain.scale_data_colormap(fmin=scale_pts[0], fmid=scale_pts[1],
fmax=scale_pts[2], **sd_kwargs)
if _get_3d_backend() == "mayavi":
for hemi in hemis:
for b in brain._brain_list:
for layer in b['brain'].data.values():
glyphs = layer['glyphs']
glyphs.glyph.glyph.scale_factor = scale_factor
glyphs.glyph.glyph.clamping = False
glyphs.glyph.glyph.range = (0., 1.)
# depth peeling patch
if brain_alpha < 1.0:
for ff in brain._figures:
for f in ff:
if f.scene is not None:
f.scene.renderer.use_depth_peeling = True
else:
if brain_alpha < 1.0:
brain.enable_depth_peeling()
_check_time_viewer_compatibility(brain, time_viewer, show_traces)
return brain
@verbose
def plot_sparse_source_estimates(src, stcs, colors=None, linewidth=2,
fontsize=18, bgcolor=(.05, 0, .1),
opacity=0.2, brain_color=(0.7,) * 3,
show=True, high_resolution=False,
fig_name=None, fig_number=None, labels=None,
modes=('cone', 'sphere'),
scale_factors=(1, 0.6),
verbose=None, **kwargs):
"""Plot source estimates obtained with sparse solver.
Active dipoles are represented in a "Glass" brain.
If the same source is active in multiple source estimates it is
displayed with a sphere otherwise with a cone in 3D.
Parameters
----------
src : dict
The source space.
stcs : instance of SourceEstimate or list of instances of SourceEstimate
The source estimates (up to 3).
colors : list
List of colors.
linewidth : int
Line width in 2D plot.
fontsize : int
Font size.
bgcolor : tuple of length 3
Background color in 3D.
opacity : float in [0, 1]
Opacity of brain mesh.
brain_color : tuple of length 3
Brain color.
show : bool
Show figures if True.
high_resolution : bool
If True, plot on the original (non-downsampled) cortical mesh.
fig_name : str
Mayavi figure name.
fig_number : int
Matplotlib figure number.
labels : ndarray or list of ndarray
Labels to show sources in clusters. Sources with the same
label and the waveforms within each cluster are presented in
the same color. labels should be a list of ndarrays when
stcs is a list ie. one label for each stc.
modes : list
Should be a list, with each entry being ``'cone'`` or ``'sphere'``
to specify how the dipoles should be shown.
scale_factors : list
List of floating point scale factors for the markers.
%(verbose)s
**kwargs : kwargs
Keyword arguments to pass to mlab.triangular_mesh.
Returns
-------
surface : instance of mayavi.mlab.pipeline.surface
The triangular mesh surface.
"""
import matplotlib.pyplot as plt
from matplotlib.colors import ColorConverter
# Update the backend
from .backends.renderer import _get_renderer
known_modes = ['cone', 'sphere']
if not isinstance(modes, (list, tuple)) or \
not all(mode in known_modes for mode in modes):
raise ValueError('mode must be a list containing only '
'"cone" or "sphere"')
if not isinstance(stcs, list):
stcs = [stcs]
if labels is not None and not isinstance(labels, list):
labels = [labels]
if colors is None:
colors = _get_color_list()
linestyles = ['-', '--', ':']
# Show 3D
lh_points = src[0]['rr']
rh_points = src[1]['rr']
points = np.r_[lh_points, rh_points]
lh_normals = src[0]['nn']
rh_normals = src[1]['nn']
normals = np.r_[lh_normals, rh_normals]
if high_resolution:
use_lh_faces = src[0]['tris']
use_rh_faces = src[1]['tris']
else:
use_lh_faces = src[0]['use_tris']
use_rh_faces = src[1]['use_tris']
use_faces = np.r_[use_lh_faces, lh_points.shape[0] + use_rh_faces]
points *= 170
vertnos = [np.r_[stc.lh_vertno, lh_points.shape[0] + stc.rh_vertno]
for stc in stcs]
unique_vertnos = np.unique(np.concatenate(vertnos).ravel())
color_converter = ColorConverter()
renderer = _get_renderer(bgcolor=bgcolor, size=(600, 600), name=fig_name)
surface = renderer.mesh(x=points[:, 0], y=points[:, 1],
z=points[:, 2], triangles=use_faces,
color=brain_color, opacity=opacity,
backface_culling=True, shading=True,
**kwargs)
# Show time courses
fig = plt.figure(fig_number)
fig.clf()
ax = fig.add_subplot(111)
colors = cycle(colors)
logger.info("Total number of active sources: %d" % len(unique_vertnos))
if labels is not None:
colors = [next(colors) for _ in
range(np.unique(np.concatenate(labels).ravel()).size)]
for idx, v in enumerate(unique_vertnos):
# get indices of stcs it belongs to
ind = [k for k, vertno in enumerate(vertnos) if v in vertno]
is_common = len(ind) > 1
if labels is None:
c = next(colors)
else:
# if vertex is in different stcs than take label from first one
c = colors[labels[ind[0]][vertnos[ind[0]] == v]]
mode = modes[1] if is_common else modes[0]
scale_factor = scale_factors[1] if is_common else scale_factors[0]
if (isinstance(scale_factor, (np.ndarray, list, tuple)) and
len(unique_vertnos) == len(scale_factor)):
scale_factor = scale_factor[idx]
x, y, z = points[v]
nx, ny, nz = normals[v]
renderer.quiver3d(x=x, y=y, z=z, u=nx, v=ny, w=nz,
color=color_converter.to_rgb(c),
mode=mode, scale=scale_factor)
for k in ind:
vertno = vertnos[k]
mask = (vertno == v)
assert np.sum(mask) == 1
linestyle = linestyles[k]
ax.plot(1e3 * stcs[k].times, 1e9 * stcs[k].data[mask].ravel(),
c=c, linewidth=linewidth, linestyle=linestyle)
ax.set_xlabel('Time (ms)', fontsize=18)
ax.set_ylabel('Source amplitude (nAm)', fontsize=18)
if fig_name is not None:
ax.set_title(fig_name)
plt_show(show)
renderer.show()
return surface
@verbose
def plot_dipole_locations(dipoles, trans=None, subject=None, subjects_dir=None,
mode='orthoview', coord_frame='mri', idx='gof',
show_all=True, ax=None, block=False, show=True,
scale=5e-3, color=None, highlight_color='r',
fig=None, verbose=None, title=None):
"""Plot dipole locations.
If mode is set to 'arrow' or 'sphere', only the location of the first
time point of each dipole is shown else use the show_all parameter.
The option mode='orthoview' was added in version 0.14.
Parameters
----------
dipoles : list of instances of Dipole | Dipole
The dipoles to plot.
trans : dict | None
The mri to head trans.
Can be None with mode set to '3d'.
subject : str | None
The subject name corresponding to FreeSurfer environment
variable SUBJECT.
Can be None with mode set to '3d'.
subjects_dir : None | str
The path to the freesurfer subjects reconstructions.
It corresponds to Freesurfer environment variable SUBJECTS_DIR.
The default is None.
mode : str
Can be ``'arrow'``, ``'sphere'`` or ``'orthoview'``.
.. versionadded:: 0.19.0
coord_frame : str
Coordinate frame to use, 'head' or 'mri'. Defaults to 'mri'.
.. versionadded:: 0.14.0
idx : int | 'gof' | 'amplitude'
Index of the initially plotted dipole. Can also be 'gof' to plot the
dipole with highest goodness of fit value or 'amplitude' to plot the
dipole with the highest amplitude. The dipoles can also be browsed
through using up/down arrow keys or mouse scroll. Defaults to 'gof'.
Only used if mode equals 'orthoview'.
.. versionadded:: 0.14.0
show_all : bool
Whether to always plot all the dipoles. If ``True`` (default), the
active dipole is plotted as a red dot and its location determines the
shown MRI slices. The non-active dipoles are plotted as small blue
dots. If ``False``, only the active dipole is plotted.
Only used if ``mode='orthoview'``.
.. versionadded:: 0.14.0
ax : instance of matplotlib Axes3D | None
Axes to plot into. If None (default), axes will be created.
Only used if mode equals 'orthoview'.
.. versionadded:: 0.14.0
block : bool
Whether to halt program execution until the figure is closed. Defaults
to False.
Only used if mode equals 'orthoview'.
.. versionadded:: 0.14.0
show : bool
Show figure if True. Defaults to True.
Only used if mode equals 'orthoview'.
scale : float
The scale of the dipoles if ``mode`` is 'arrow' or 'sphere'.
color : tuple
The color of the dipoles.
The default (None) will use ``'y'`` if mode is ``'orthoview'`` and
``show_all`` is True, else 'r'.
.. versionchanged:: 0.19.0
Color is now passed in orthoview mode.
highlight_color : color
The highlight color. Only used in orthoview mode with
``show_all=True``.
.. versionadded:: 0.19.0
fig : mayavi.mlab.Figure | None
3D Scene in which to plot the alignment.
If ``None``, creates a new 600x600 pixel figure with black background.
.. versionadded:: 0.19.0
%(verbose)s
%(dipole_locs_fig_title)s
.. versionadded:: 0.21.0
Returns
-------
fig : instance of mayavi.mlab.Figure or matplotlib.figure.Figure
The mayavi figure or matplotlib Figure.
Notes
-----
.. versionadded:: 0.9.0
"""
if mode == 'orthoview':
fig = _plot_dipole_mri_orthoview(
dipoles, trans=trans, subject=subject, subjects_dir=subjects_dir,
coord_frame=coord_frame, idx=idx, show_all=show_all,
ax=ax, block=block, show=show, color=color,
highlight_color=highlight_color, title=title)
elif mode in ['arrow', 'sphere']:
from .backends.renderer import _get_renderer
color = (1., 0., 0.) if color is None else color
renderer = _get_renderer(fig=fig, size=(600, 600))
pos = dipoles.pos
ori = dipoles.ori
if coord_frame != 'head':
trans = _get_trans(trans, fro='head', to=coord_frame)[0]
pos = apply_trans(trans, pos)
ori = apply_trans(trans, ori)
renderer.sphere(center=pos, color=color, scale=scale)
if mode == 'arrow':
x, y, z = pos.T
u, v, w = ori.T
renderer.quiver3d(x, y, z, u, v, w, scale=3 * scale,
color=color, mode='arrow')
fig = renderer.scene()
else:
raise ValueError('Mode must be "cone", "arrow" or orthoview", '
'got %s.' % (mode,))
return fig
def snapshot_brain_montage(fig, montage, hide_sensors=True):
"""Take a snapshot of a Mayavi Scene and project channels onto 2d coords.
Note that this will take the raw values for 3d coordinates of each channel,
without applying any transforms. If brain images are flipped up/dn upon
using `imshow`, check your matplotlib backend as this behavior changes.
Parameters
----------
fig : instance of ~mayavi.core.api.Scene
The figure on which you've plotted electrodes using
:func:`mne.viz.plot_alignment`.
montage : instance of DigMontage or Info | dict
The digital montage for the electrodes plotted in the scene. If `Info`,
channel positions will be pulled from the `loc` field of `chs`.
dict should have ch:xyz mappings.
hide_sensors : bool
Whether to remove the spheres in the scene before taking a snapshot.
Returns
-------
xy : array, shape (n_channels, 2)
The 2d location of each channel on the image of the current scene view.
im : array, shape (m, n, 3)
The screenshot of the current scene view.
"""
from ..channels import DigMontage
from .. import Info
# Update the backend
from .backends.renderer import _get_renderer
if fig is None:
raise ValueError('The figure must have a scene')
if isinstance(montage, DigMontage):
chs = montage._get_ch_pos()
ch_names, xyz = zip(*[(ich, ixyz) for ich, ixyz in chs.items()])
elif isinstance(montage, Info):
xyz = [ich['loc'][:3] for ich in montage['chs']]
ch_names = [ich['ch_name'] for ich in montage['chs']]
elif isinstance(montage, dict):
if not all(len(ii) == 3 for ii in montage.values()):
raise ValueError('All electrode positions must be length 3')
ch_names, xyz = zip(*[(ich, ixyz) for ich, ixyz in montage.items()])
else:
raise TypeError('montage must be an instance of `DigMontage`, `Info`,'
' or `dict`')
# initialize figure
renderer = _get_renderer(fig, show=True)
xyz = np.vstack(xyz)
proj = renderer.project(xyz=xyz, ch_names=ch_names)
if hide_sensors is True:
proj.visible(False)
im = renderer.screenshot()
proj.visible(True)
return proj.xy, im
@fill_doc
def plot_sensors_connectivity(info, con, picks=None):
"""Visualize the sensor connectivity in 3D.
Parameters
----------
info : dict | None
The measurement info.
con : array, shape (n_channels, n_channels)
The computed connectivity measure(s).
%(picks_good_data)s
Indices of selected channels.
Returns
-------
fig : instance of mayavi.mlab.Figure
The mayavi figure.
"""
_validate_type(info, "info")
from .backends.renderer import _get_renderer
renderer = _get_renderer(size=(600, 600), bgcolor=(0.5, 0.5, 0.5))
picks = _picks_to_idx(info, picks)
if len(picks) != len(con):
raise ValueError('The number of channels picked (%s) does not '
'correspond the size of the connectivity data '
'(%s)' % (len(picks), len(con)))
# Plot the sensor locations
sens_loc = [info['chs'][k]['loc'][:3] for k in picks]
sens_loc = np.array(sens_loc)
renderer.sphere(np.c_[sens_loc[:, 0], sens_loc[:, 1], sens_loc[:, 2]],
color=(1, 1, 1), opacity=1, scale=0.005)
# Get the strongest connections
n_con = 20 # show up to 20 connections
min_dist = 0.05 # exclude sensors that are less than 5cm apart
threshold = np.sort(con, axis=None)[-n_con]
ii, jj = np.where(con >= threshold)
# Remove close connections
con_nodes = list()
con_val = list()
for i, j in zip(ii, jj):
if linalg.norm(sens_loc[i] - sens_loc[j]) > min_dist:
con_nodes.append((i, j))
con_val.append(con[i, j])
con_val = np.array(con_val)
# Show the connections as tubes between sensors
vmax = np.max(con_val)
vmin = np.min(con_val)
for val, nodes in zip(con_val, con_nodes):
x1, y1, z1 = sens_loc[nodes[0]]
x2, y2, z2 = sens_loc[nodes[1]]
tube = renderer.tube(origin=np.c_[x1, y1, z1],
destination=np.c_[x2, y2, z2],
scalars=np.c_[val, val],
vmin=vmin, vmax=vmax,
reverse_lut=True)
renderer.scalarbar(source=tube, title='Phase Lag Index (PLI)')
# Add the sensor names for the connections shown
nodes_shown = list(set([n[0] for n in con_nodes] +
[n[1] for n in con_nodes]))
for node in nodes_shown:
x, y, z = sens_loc[node]
renderer.text3d(x, y, z, text=info['ch_names'][picks[node]],
scale=0.005,
color=(0, 0, 0))
renderer.set_camera(azimuth=-88.7, elevation=40.8,
distance=0.76,
focalpoint=np.array([-3.9e-4, -8.5e-3, -1e-2]))
renderer.show()
return renderer.scene()
def _plot_dipole_mri_orthoview(dipole, trans, subject, subjects_dir=None,
coord_frame='head', idx='gof', show_all=True,
ax=None, block=False, show=True, color=None,
highlight_color='r', title=None):
"""Plot dipoles on top of MRI slices in 3-D."""
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from .. import Dipole
if not has_nibabel():
raise ImportError('This function requires nibabel.')
_check_option('coord_frame', coord_frame, ['head', 'mri'])
if not isinstance(dipole, Dipole):
from ..dipole import _concatenate_dipoles
dipole = _concatenate_dipoles(dipole)
if idx == 'gof':
idx = np.argmax(dipole.gof)
elif idx == 'amplitude':
idx = np.argmax(np.abs(dipole.amplitude))
else:
idx = _ensure_int(idx, 'idx', 'an int or one of ["gof", "amplitude"]')
vox, ori, pos, data = _get_dipole_loc(
dipole, trans, subject, subjects_dir, coord_frame)
dims = len(data) # Symmetric size assumed.
dd = dims // 2
if ax is None:
fig = plt.figure()
ax = Axes3D(fig)
else:
_validate_type(ax, Axes3D, "ax", "Axes3D")
fig = ax.get_figure()
gridx, gridy = np.meshgrid(np.linspace(-dd, dd, dims),
np.linspace(-dd, dd, dims), indexing='ij')
params = {'ax': ax, 'data': data, 'idx': idx, 'dipole': dipole,
'vox': vox, 'gridx': gridx, 'gridy': gridy,
'ori': ori, 'coord_frame': coord_frame,
'show_all': show_all, 'pos': pos,
'color': color, 'highlight_color': highlight_color,
'title': title}
_plot_dipole(**params)
ax.view_init(elev=30, azim=-140)
callback_func = partial(_dipole_changed, params=params)
fig.canvas.mpl_connect('scroll_event', callback_func)
fig.canvas.mpl_connect('key_press_event', callback_func)
plt_show(show, block=block)
return fig
RAS_AFFINE = np.eye(4)
RAS_AFFINE[:3, 3] = [-128] * 3
RAS_SHAPE = (256, 256, 256)
def _get_dipole_loc(dipole, trans, subject, subjects_dir, coord_frame):
"""Get the dipole locations and orientations."""
import nibabel as nib
from nibabel.processing import resample_from_to
_check_option('coord_frame', coord_frame, ['head', 'mri'])
subjects_dir = get_subjects_dir(subjects_dir=subjects_dir,
raise_error=True)
t1_fname = op.join(subjects_dir, subject, 'mri', 'T1.mgz')
t1 = nib.load(t1_fname)
# Do everything in mm here to make life slightly easier
vox_ras_t, _, mri_ras_t, _, _ = _read_mri_info(
t1_fname, units='mm')
head_mri_t = _get_trans(trans, fro='head', to='mri')[0].copy()
head_mri_t['trans'][:3, 3] *= 1000 # m→mm
del trans
pos = dipole.pos * 1e3 # m→mm
ori = dipole.ori
# Figure out how to always resample to an identity, 256x256x256 RAS:
#
# 1. Resample to head or MRI surface RAS (the conditional), but also
# 2. Resample to what will work for the standard 1mm** RAS_AFFINE (resamp)
#
# We could do this with two resample_from_to calls, but it's cleaner,
# faster, and we get fewer boundary artifacts if we do it in one shot.
# So first olve usamp s.t. ``upsamp @ vox_ras_t == RAS_AFFINE``` (2):
upsamp = np.linalg.solve(vox_ras_t['trans'].T, RAS_AFFINE.T).T
# Now figure out how we would resample from RAS to head or MRI coords:
if coord_frame == 'head':
dest_ras_t = combine_transforms(
head_mri_t, mri_ras_t, 'head', 'ras')['trans']
else:
pos = apply_trans(head_mri_t, pos)
ori = apply_trans(head_mri_t, dipole.ori, move=False)
dest_ras_t = mri_ras_t['trans']
# The order here is wacky because we need `resample_from_to` to operate
# in a reverse order
affine = np.dot(np.dot(dest_ras_t, upsamp), vox_ras_t['trans'])
t1 = resample_from_to(t1, (RAS_SHAPE, affine), order=0)
# Now we could do:
#
# t1 = SpatialImage(t1.dataobj, RAS_AFFINE)
#
# And t1 would be in our destination (mri or head) space. But we don't
# need to construct the image -- let's just get our voxel coords and data:
vox = apply_trans(np.linalg.inv(RAS_AFFINE), pos)
t1_data = _get_img_fdata(t1)
return vox, ori, pos, t1_data
def _plot_dipole(ax, data, vox, idx, dipole, gridx, gridy, ori, coord_frame,
show_all, pos, color, highlight_color, title):
"""Plot dipoles."""
import matplotlib.pyplot as plt
from matplotlib.colors import ColorConverter
color_converter = ColorConverter()
xidx, yidx, zidx = np.round(vox[idx]).astype(int)
xslice = data[xidx]
yslice = data[:, yidx]
zslice = data[:, :, zidx]
ori = ori[idx]
if color is None:
color = 'y' if show_all else 'r'
color = np.array(color_converter.to_rgba(color))
highlight_color = np.array(color_converter.to_rgba(highlight_color))
if show_all:
colors = np.repeat(color[np.newaxis], len(vox), axis=0)
colors[idx] = highlight_color
size = np.repeat(5, len(vox))
size[idx] = 20
visible = np.arange(len(vox))
else:
colors = color
size = 20
visible = idx
offset = np.min(gridx)
xyz = pos
ax.scatter(xs=xyz[visible, 0], ys=xyz[visible, 1],
zs=xyz[visible, 2], zorder=2, s=size, facecolor=colors)
xx = np.linspace(offset, xyz[idx, 0], xidx)
yy = np.linspace(offset, xyz[idx, 1], yidx)
zz = np.linspace(offset, xyz[idx, 2], zidx)
ax.plot(xx, np.repeat(xyz[idx, 1], len(xx)), zs=xyz[idx, 2], zorder=1,
linestyle='-', color=highlight_color)
ax.plot(np.repeat(xyz[idx, 0], len(yy)), yy, zs=xyz[idx, 2], zorder=1,
linestyle='-', color=highlight_color)
ax.plot(np.repeat(xyz[idx, 0], len(zz)),
np.repeat(xyz[idx, 1], len(zz)), zs=zz, zorder=1,
linestyle='-', color=highlight_color)
ax.quiver(xyz[idx, 0], xyz[idx, 1], xyz[idx, 2], ori[0], ori[1],
ori[2], length=50, color=highlight_color,
pivot='tail')
dims = np.array([(len(data) / -2.), (len(data) / 2.)])
ax.set(xlim=-dims, ylim=-dims, zlim=dims)
# Plot slices.
ax.contourf(xslice, gridx, gridy, offset=offset, zdir='x',
cmap='gray', zorder=0, alpha=.5)
ax.contourf(gridx, yslice, gridy, offset=offset, zdir='y',
cmap='gray', zorder=0, alpha=.5)
ax.contourf(gridx, gridy, zslice, offset=offset, zdir='z',
cmap='gray', zorder=0, alpha=.5)
# These are the only two options
coord_frame_name = 'Head' if coord_frame == 'head' else 'MRI'
if title is None:
title = ('Dipole #%s / %s @ %.3fs, GOF: %.1f%%, %.1fnAm\n%s: ' % (
idx + 1, len(dipole.times), dipole.times[idx], dipole.gof[idx],
dipole.amplitude[idx] * 1e9, coord_frame_name) +
'(%0.1f, %0.1f, %0.1f) mm' % tuple(xyz[idx]))
ax.get_figure().suptitle(title)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.draw()
def _dipole_changed(event, params):
"""Handle dipole plotter scroll/key event."""
if event.key is not None:
if event.key == 'up':
params['idx'] += 1
elif event.key == 'down':
params['idx'] -= 1
else: # some other key
return
elif event.step > 0: # scroll event
params['idx'] += 1
else:
params['idx'] -= 1
params['idx'] = min(max(0, params['idx']), len(params['dipole'].pos) - 1)
params['ax'].clear()
_plot_dipole(**params)
def _update_coord_frame(obj, rr, nn, mri_trans, head_trans):
if obj['coord_frame'] == FIFF.FIFFV_COORD_MRI:
rr = apply_trans(mri_trans, rr)
nn = apply_trans(mri_trans, nn, move=False)
elif obj['coord_frame'] == FIFF.FIFFV_COORD_HEAD:
rr = apply_trans(head_trans, rr)
nn = apply_trans(head_trans, nn, move=False)
return rr, nn
@fill_doc
def plot_brain_colorbar(ax, clim, colormap='auto', transparent=True,
orientation='vertical', label='Activation',
bgcolor='0.5'):
"""Plot a colorbar that corresponds to a brain activation map.
Parameters
----------
ax : instance of Axes
The Axes to plot into.
%(clim)s
%(colormap)s
%(transparent)s
orientation : str
Orientation of the colorbar, can be "vertical" or "horizontal".
label : str
The colorbar label.
bgcolor : color
The color behind the colorbar (for alpha blending).
Returns
-------
cbar : instance of ColorbarBase
The colorbar.
Notes
-----
.. versionadded:: 0.19
"""
from matplotlib.colorbar import ColorbarBase
from matplotlib.colors import Normalize
mapdata = _process_clim(clim, colormap, transparent)
ticks = _get_map_ticks(mapdata)
colormap, lims = _linearize_map(mapdata)
del mapdata
norm = Normalize(vmin=lims[0], vmax=lims[2])
cbar = ColorbarBase(ax, colormap, norm=norm, ticks=ticks,
label=label, orientation=orientation)
# make the colorbar background match the brain color
cbar.patch.set(facecolor=bgcolor)
# remove the colorbar frame except for the line containing the ticks
cbar.outline.set_visible(False)
cbar.ax.set_frame_on(True)
for key in ('left', 'top',
'bottom' if orientation == 'vertical' else 'right'):
ax.spines[key].set_visible(False)
return cbar
| 40.90895
| 105
| 0.57333
|
bc204992002033aede1b719e8b519315cac7c322
| 200
|
py
|
Python
|
mongoenginetest/serializers.py
|
jonwhuang/diana-api
|
7872f0358d15312333bae42ffb3fd4bd9633297f
|
[
"MIT"
] | null | null | null |
mongoenginetest/serializers.py
|
jonwhuang/diana-api
|
7872f0358d15312333bae42ffb3fd4bd9633297f
|
[
"MIT"
] | null | null | null |
mongoenginetest/serializers.py
|
jonwhuang/diana-api
|
7872f0358d15312333bae42ffb3fd4bd9633297f
|
[
"MIT"
] | null | null | null |
from rest_framework_mongoengine import serializers
from mongoenginetest.models import Test
class TestSerializer(serializers.DocumentSerializer):
class Meta:
model = Test
fields = '__all__'
| 25
| 53
| 0.805
|
6eea670b8363788843cfd729ca9f02b6432ece8c
| 24,463
|
py
|
Python
|
statsmodels/discrete/tests/test_sandwich_cov.py
|
Aziiz1989/statsmodels
|
4c4a235f98aeba743517dd35b01da824594cb43c
|
[
"BSD-3-Clause"
] | null | null | null |
statsmodels/discrete/tests/test_sandwich_cov.py
|
Aziiz1989/statsmodels
|
4c4a235f98aeba743517dd35b01da824594cb43c
|
[
"BSD-3-Clause"
] | null | null | null |
statsmodels/discrete/tests/test_sandwich_cov.py
|
Aziiz1989/statsmodels
|
4c4a235f98aeba743517dd35b01da824594cb43c
|
[
"BSD-3-Clause"
] | null | null | null |
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 09 21:29:20 2013
Author: Josef Perktold
"""
import os
import numpy as np
import pandas as pd
import statsmodels.discrete.discrete_model as smd
from statsmodels.genmod.generalized_linear_model import GLM
from statsmodels.genmod import families
from statsmodels.genmod.families import links
from statsmodels.regression.linear_model import OLS
from statsmodels.base.covtype import get_robustcov_results
import statsmodels.stats.sandwich_covariance as sw
from statsmodels.tools.tools import add_constant
from numpy.testing import assert_allclose, assert_equal, assert_
import statsmodels.tools._testing as smt
# get data and results as module global for now, TODO: move to class
from .results import results_count_robust_cluster as results_st
cur_dir = os.path.dirname(os.path.abspath(__file__))
filepath = os.path.join(cur_dir, "results", "ships.csv")
data_raw = pd.read_csv(filepath, index_col=False)
data = data_raw.dropna()
#mod = smd.Poisson.from_formula('accident ~ yr_con + op_75_79', data=dat)
# Don't use formula for tests against Stata because intercept needs to be last
endog = data['accident']
exog_data = data['yr_con op_75_79'.split()]
exog = add_constant(exog_data, prepend=False)
group = np.asarray(data['ship'], int)
exposure = np.asarray(data['service'])
# TODO get the test methods from regression/tests
class CheckCountRobustMixin(object):
def test_basic(self):
res1 = self.res1
res2 = self.res2
if len(res1.params) == (len(res2.params) - 1):
# Stata includes lnalpha in table for NegativeBinomial
mask = np.ones(len(res2.params), np.bool_)
mask[-2] = False
res2_params = res2.params[mask]
res2_bse = res2.bse[mask]
else:
res2_params = res2.params
res2_bse = res2.bse
assert_allclose(res1._results.params, res2_params, 1e-4)
assert_allclose(self.bse_rob / self.corr_fact, res2_bse, 6e-5)
@classmethod
def get_robust_clu(cls):
res1 = cls.res1
cov_clu = sw.cov_cluster(res1, group)
cls.bse_rob = sw.se_cov(cov_clu)
nobs, k_vars = res1.model.exog.shape
k_params = len(res1.params)
#n_groups = len(np.unique(group))
corr_fact = (nobs-1.) / float(nobs - k_params)
# for bse we need sqrt of correction factor
cls.corr_fact = np.sqrt(corr_fact)
def test_oth(self):
res1 = self.res1
res2 = self.res2
assert_allclose(res1._results.llf, res2.ll, 1e-4)
assert_allclose(res1._results.llnull, res2.ll_0, 1e-4)
def test_ttest(self):
smt.check_ttest_tvalues(self.res1)
def test_waldtest(self):
smt.check_ftest_pvalues(self.res1)
class TestPoissonClu(CheckCountRobustMixin):
@classmethod
def setup_class(cls):
cls.res2 = results_st.results_poisson_clu
mod = smd.Poisson(endog, exog)
cls.res1 = mod.fit(disp=False)
cls.get_robust_clu()
class TestPoissonCluGeneric(CheckCountRobustMixin):
@classmethod
def setup_class(cls):
cls.res2 = results_st.results_poisson_clu
mod = smd.Poisson(endog, exog)
cls.res1 = res1 = mod.fit(disp=False)
debug = False
if debug:
# for debugging
cls.bse_nonrobust = cls.res1.bse.copy()
cls.res1 = res1 = mod.fit(disp=False)
cls.get_robust_clu()
cls.res3 = cls.res1
cls.bse_rob3 = cls.bse_rob.copy()
cls.res1 = res1 = mod.fit(disp=False)
from statsmodels.base.covtype import get_robustcov_results
#res_hc0_ = cls.res1.get_robustcov_results('HC1')
get_robustcov_results(cls.res1._results, 'cluster',
groups=group,
use_correction=True,
df_correction=True, #TODO has no effect
use_t=False, #True,
use_self=True)
cls.bse_rob = cls.res1.bse
nobs, k_vars = res1.model.exog.shape
k_params = len(res1.params)
#n_groups = len(np.unique(group))
corr_fact = (nobs-1.) / float(nobs - k_params)
# for bse we need sqrt of correction factor
cls.corr_fact = np.sqrt(corr_fact)
class TestPoissonHC1Generic(CheckCountRobustMixin):
@classmethod
def setup_class(cls):
cls.res2 = results_st.results_poisson_hc1
mod = smd.Poisson(endog, exog)
cls.res1 = mod.fit(disp=False)
from statsmodels.base.covtype import get_robustcov_results
#res_hc0_ = cls.res1.get_robustcov_results('HC1')
get_robustcov_results(cls.res1._results, 'HC1', use_self=True)
cls.bse_rob = cls.res1.bse
nobs, k_vars = mod.exog.shape
corr_fact = (nobs) / float(nobs - 1.)
# for bse we need sqrt of correction factor
cls.corr_fact = np.sqrt(1./corr_fact)
# TODO: refactor xxxFit to full testing results
class TestPoissonCluFit(CheckCountRobustMixin):
@classmethod
def setup_class(cls):
cls.res2 = results_st.results_poisson_clu
mod = smd.Poisson(endog, exog)
# scaling of cov_params_default to match Stata
# TODO should the default be changed?
nobs, k_params = mod.exog.shape
sc_fact = (nobs-1.) / float(nobs - k_params)
cls.res1 = mod.fit(disp=False, cov_type='cluster',
cov_kwds=dict(groups=group,
use_correction=True,
scaling_factor=1. / sc_fact,
df_correction=True), #TODO has no effect
use_t=False, #True,
)
# The model results, t_test, ... should also work without
# normalized_cov_params, see #2209
# Note: we cannot set on the wrapper res1, we need res1._results
cls.res1._results.normalized_cov_params = None
cls.bse_rob = cls.res1.bse
# backwards compatibility with inherited test methods
cls.corr_fact = 1
def test_basic_inference(self):
res1 = self.res1
res2 = self.res2
rtol = 1e-7
assert_allclose(res1.params, res2.params, rtol=1e-8)
assert_allclose(res1.bse, res2.bse, rtol=rtol)
assert_allclose(res1.tvalues, res2.tvalues, rtol=rtol, atol=1e-8)
assert_allclose(res1.pvalues, res2.pvalues, rtol=rtol, atol=1e-20)
ci = res2.params_table[:, 4:6]
assert_allclose(res1.conf_int(), ci, rtol=5e-7, atol=1e-20)
class TestPoissonHC1Fit(CheckCountRobustMixin):
@classmethod
def setup_class(cls):
cls.res2 = results_st.results_poisson_hc1
mod = smd.Poisson(endog, exog)
cls.res1 = mod.fit(disp=False, cov_type='HC1')
cls.bse_rob = cls.res1.bse
nobs, k_vars = mod.exog.shape
corr_fact = (nobs) / float(nobs - 1.)
# for bse we need sqrt of correction factor
cls.corr_fact = np.sqrt(1./corr_fact)
class TestPoissonHC1FitExposure(CheckCountRobustMixin):
@classmethod
def setup_class(cls):
cls.res2 = results_st.results_poisson_exposure_hc1
mod = smd.Poisson(endog, exog, exposure=exposure)
cls.res1 = mod.fit(disp=False, cov_type='HC1')
cls.bse_rob = cls.res1.bse
nobs, k_vars = mod.exog.shape
corr_fact = (nobs) / float(nobs - 1.)
# for bse we need sqrt of correction factor
cls.corr_fact = np.sqrt(1./corr_fact)
class TestPoissonCluExposure(CheckCountRobustMixin):
@classmethod
def setup_class(cls):
cls.res2 = results_st.results_poisson_exposure_clu #nonrobust
mod = smd.Poisson(endog, exog, exposure=exposure)
cls.res1 = mod.fit(disp=False)
cls.get_robust_clu()
class TestPoissonCluExposureGeneric(CheckCountRobustMixin):
@classmethod
def setup_class(cls):
cls.res2 = results_st.results_poisson_exposure_clu #nonrobust
mod = smd.Poisson(endog, exog, exposure=exposure)
cls.res1 = res1 = mod.fit(disp=False)
from statsmodels.base.covtype import get_robustcov_results
#res_hc0_ = cls.res1.get_robustcov_results('HC1')
get_robustcov_results(cls.res1._results, 'cluster',
groups=group,
use_correction=True,
df_correction=True, #TODO has no effect
use_t=False, #True,
use_self=True)
cls.bse_rob = cls.res1.bse #sw.se_cov(cov_clu)
nobs, k_vars = res1.model.exog.shape
k_params = len(res1.params)
#n_groups = len(np.unique(group))
corr_fact = (nobs-1.) / float(nobs - k_params)
# for bse we need sqrt of correction factor
cls.corr_fact = np.sqrt(corr_fact)
class TestGLMPoissonClu(CheckCountRobustMixin):
@classmethod
def setup_class(cls):
cls.res2 = results_st.results_poisson_clu
mod = smd.Poisson(endog, exog)
mod = GLM(endog, exog, family=families.Poisson())
cls.res1 = mod.fit()
cls.get_robust_clu()
class TestGLMPoissonCluGeneric(CheckCountRobustMixin):
@classmethod
def setup_class(cls):
cls.res2 = results_st.results_poisson_clu
mod = GLM(endog, exog, family=families.Poisson())
cls.res1 = res1 = mod.fit()
get_robustcov_results(cls.res1._results, 'cluster',
groups=group,
use_correction=True,
df_correction=True, #TODO has no effect
use_t=False, #True,
use_self=True)
cls.bse_rob = cls.res1.bse
nobs, k_vars = res1.model.exog.shape
k_params = len(res1.params)
#n_groups = len(np.unique(group))
corr_fact = (nobs-1.) / float(nobs - k_params)
# for bse we need sqrt of correction factor
cls.corr_fact = np.sqrt(corr_fact)
class TestGLMPoissonHC1Generic(CheckCountRobustMixin):
@classmethod
def setup_class(cls):
cls.res2 = results_st.results_poisson_hc1
mod = GLM(endog, exog, family=families.Poisson())
cls.res1 = mod.fit()
#res_hc0_ = cls.res1.get_robustcov_results('HC1')
get_robustcov_results(cls.res1._results, 'HC1', use_self=True)
cls.bse_rob = cls.res1.bse
nobs, k_vars = mod.exog.shape
corr_fact = (nobs) / float(nobs - 1.)
# for bse we need sqrt of correction factor
cls.corr_fact = np.sqrt(1./corr_fact)
# TODO: refactor xxxFit to full testing results
class TestGLMPoissonCluFit(CheckCountRobustMixin):
@classmethod
def setup_class(cls):
cls.res2 = results_st.results_poisson_clu
mod = GLM(endog, exog, family=families.Poisson())
cls.res1 = res1 = mod.fit(cov_type='cluster',
cov_kwds=dict(groups=group,
use_correction=True,
df_correction=True), #TODO has no effect
use_t=False, #True,
)
# The model results, t_test, ... should also work without
# normalized_cov_params, see #2209
# Note: we cannot set on the wrapper res1, we need res1._results
cls.res1._results.normalized_cov_params = None
cls.bse_rob = cls.res1.bse
nobs, k_vars = mod.exog.shape
k_params = len(cls.res1.params)
#n_groups = len(np.unique(group))
corr_fact = (nobs-1.) / float(nobs - k_params)
# for bse we need sqrt of correction factor
cls.corr_fact = np.sqrt(corr_fact)
class TestGLMPoissonHC1Fit(CheckCountRobustMixin):
@classmethod
def setup_class(cls):
cls.res2 = results_st.results_poisson_hc1
mod = GLM(endog, exog, family=families.Poisson())
cls.res1 = mod.fit(cov_type='HC1')
cls.bse_rob = cls.res1.bse
nobs, k_vars = mod.exog.shape
corr_fact = (nobs) / float(nobs - 1.)
# for bse we need sqrt of correction factor
cls.corr_fact = np.sqrt(1./corr_fact)
class TestNegbinClu(CheckCountRobustMixin):
@classmethod
def setup_class(cls):
cls.res2 = results_st.results_negbin_clu
mod = smd.NegativeBinomial(endog, exog)
cls.res1 = mod.fit(disp=False, gtol=1e-7)
cls.get_robust_clu()
class TestNegbinCluExposure(CheckCountRobustMixin):
@classmethod
def setup_class(cls):
cls.res2 = results_st.results_negbin_exposure_clu #nonrobust
mod = smd.NegativeBinomial(endog, exog, exposure=exposure)
cls.res1 = mod.fit(disp=False)
cls.get_robust_clu()
# mod_nbe = smd.NegativeBinomial(endog, exog, exposure=data['service'])
# res_nbe = mod_nbe.fit()
# mod_nb = smd.NegativeBinomial(endog, exog)
# res_nb = mod_nb.fit()
#
# cov_clu_nb = sw.cov_cluster(res_nb, group)
# k_params = k_vars + 1
# print sw.se_cov(cov_clu_nb / ((nobs-1.) / float(nobs - k_params)))
#
# wt = res_nb.wald_test(np.eye(len(res_nb.params))[1:3], cov_p=cov_clu_nb/((nobs-1.) / float(nobs - k_params)))
# print wt
#
# print dir(results_st)
class TestNegbinCluGeneric(CheckCountRobustMixin):
@classmethod
def setup_class(cls):
cls.res2 = results_st.results_negbin_clu
mod = smd.NegativeBinomial(endog, exog)
cls.res1 = res1 = mod.fit(disp=False, gtol=1e-7)
get_robustcov_results(cls.res1._results, 'cluster',
groups=group,
use_correction=True,
df_correction=True, #TODO has no effect
use_t=False, #True,
use_self=True)
cls.bse_rob = cls.res1.bse
nobs, k_vars = mod.exog.shape
k_params = len(cls.res1.params)
#n_groups = len(np.unique(group))
corr_fact = (nobs-1.) / float(nobs - k_params)
# for bse we need sqrt of correction factor
cls.corr_fact = np.sqrt(corr_fact)
class TestNegbinCluFit(CheckCountRobustMixin):
@classmethod
def setup_class(cls):
cls.res2 = results_st.results_negbin_clu
mod = smd.NegativeBinomial(endog, exog)
cls.res1 = res1 = mod.fit(disp=False, cov_type='cluster',
cov_kwds=dict(groups=group,
use_correction=True,
df_correction=True), #TODO has no effect
use_t=False, #True,
gtol=1e-7)
cls.bse_rob = cls.res1.bse
nobs, k_vars = mod.exog.shape
k_params = len(cls.res1.params)
#n_groups = len(np.unique(group))
corr_fact = (nobs-1.) / float(nobs - k_params)
# for bse we need sqrt of correction factor
cls.corr_fact = np.sqrt(corr_fact)
class TestNegbinCluExposureFit(CheckCountRobustMixin):
@classmethod
def setup_class(cls):
cls.res2 = results_st.results_negbin_exposure_clu #nonrobust
mod = smd.NegativeBinomial(endog, exog, exposure=exposure)
cls.res1 = res1 = mod.fit(disp=False, cov_type='cluster',
cov_kwds=dict(groups=group,
use_correction=True,
df_correction=True), #TODO has no effect
use_t=False, #True,
)
cls.bse_rob = cls.res1.bse
nobs, k_vars = mod.exog.shape
k_params = len(cls.res1.params)
#n_groups = len(np.unique(group))
corr_fact = (nobs-1.) / float(nobs - k_params)
# for bse we need sqrt of correction factor
cls.corr_fact = np.sqrt(corr_fact)
class CheckDiscreteGLM(object):
# compare GLM with other models, no verified reference results
def test_basic(self):
res1 = self.res1
res2 = self.res2
assert_equal(res1.cov_type, self.cov_type)
assert_equal(res2.cov_type, self.cov_type)
assert_allclose(res1.params, res2.params, rtol=1e-13)
# bug TODO res1.scale missing ? in Gaussian/OLS
assert_allclose(res1.bse, res2.bse, rtol=1e-13)
# if not self.cov_type == 'nonrobust':
# assert_allclose(res1.bse * res1.scale, res2.bse, rtol=1e-13)
# else:
# assert_allclose(res1.bse, res2.bse, rtol=1e-13)
class TestGLMLogit(CheckDiscreteGLM):
@classmethod
def setup_class(cls):
endog_bin = (endog > endog.mean()).astype(int)
cls.cov_type = 'cluster'
mod1 = GLM(endog_bin, exog, family=families.Binomial())
cls.res1 = mod1.fit(cov_type='cluster', cov_kwds=dict(groups=group))
mod1 = smd.Logit(endog_bin, exog)
cls.res2 = mod1.fit(cov_type='cluster', cov_kwds=dict(groups=group))
class T_estGLMProbit(CheckDiscreteGLM):
# invalid link. What's Probit as GLM?
@classmethod
def setup_class(cls):
endog_bin = (endog > endog.mean()).astype(int)
cls.cov_type = 'cluster'
mod1 = GLM(endog_bin, exog, family=families.Gaussian(link=links.CDFLink()))
cls.res1 = mod1.fit(cov_type='cluster', cov_kwds=dict(groups=group))
mod1 = smd.Probit(endog_bin, exog)
cls.res2 = mod1.fit(cov_type='cluster', cov_kwds=dict(groups=group))
class TestGLMGaussNonRobust(CheckDiscreteGLM):
@classmethod
def setup_class(cls):
cls.cov_type = 'nonrobust'
mod1 = GLM(endog, exog, family=families.Gaussian())
cls.res1 = mod1.fit()
mod2 = OLS(endog, exog)
cls.res2 = mod2.fit()
class TestGLMGaussClu(CheckDiscreteGLM):
@classmethod
def setup_class(cls):
cls.cov_type = 'cluster'
mod1 = GLM(endog, exog, family=families.Gaussian())
cls.res1 = mod1.fit(cov_type='cluster', cov_kwds=dict(groups=group))
mod2 = OLS(endog, exog)
cls.res2 = mod2.fit(cov_type='cluster', cov_kwds=dict(groups=group))
class TestGLMGaussHC(CheckDiscreteGLM):
@classmethod
def setup_class(cls):
cls.cov_type = 'HC0'
mod1 = GLM(endog, exog, family=families.Gaussian())
cls.res1 = mod1.fit(cov_type='HC0')
mod2 = OLS(endog, exog)
cls.res2 = mod2.fit(cov_type='HC0')
class TestGLMGaussHAC(CheckDiscreteGLM):
@classmethod
def setup_class(cls):
cls.cov_type = 'HAC'
kwds={'maxlags':2}
mod1 = GLM(endog, exog, family=families.Gaussian())
cls.res1 = mod1.fit(cov_type='HAC', cov_kwds=kwds)
mod2 = OLS(endog, exog)
cls.res2 = mod2.fit(cov_type='HAC', cov_kwds=kwds)
class TestGLMGaussHAC2(CheckDiscreteGLM):
@classmethod
def setup_class(cls):
cls.cov_type = 'HAC'
# check kernel specified as string
kwds = {'kernel': 'bartlett', 'maxlags': 2}
mod1 = GLM(endog, exog, family=families.Gaussian())
cls.res1 = mod1.fit(cov_type='HAC', cov_kwds=kwds)
mod2 = OLS(endog, exog)
kwds2 = {'maxlags': 2}
cls.res2 = mod2.fit(cov_type='HAC', cov_kwds=kwds2)
class TestGLMGaussHACUniform(CheckDiscreteGLM):
@classmethod
def setup_class(cls):
cls.cov_type = 'HAC'
kwds={'kernel':sw.weights_uniform, 'maxlags':2}
mod1 = GLM(endog, exog, family=families.Gaussian())
cls.res1 = mod1.fit(cov_type='HAC', cov_kwds=kwds)
mod2 = OLS(endog, exog)
cls.res2 = mod2.fit(cov_type='HAC', cov_kwds=kwds)
#for debugging
cls.res3 = mod2.fit(cov_type='HAC', cov_kwds={'maxlags':2})
def test_cov_options(self):
# check keyword `weights_func
kwdsa = {'weights_func': sw.weights_uniform, 'maxlags': 2}
res1a = self.res1.model.fit(cov_type='HAC', cov_kwds=kwdsa)
res2a = self.res2.model.fit(cov_type='HAC', cov_kwds=kwdsa)
assert_allclose(res1a.bse, self.res1.bse, rtol=1e-12)
assert_allclose(res2a.bse, self.res2.bse, rtol=1e-12)
# regression test for bse values
bse = np.array([ 2.82203924, 4.60199596, 11.01275064])
assert_allclose(res1a.bse, bse, rtol=1e-6)
assert_(res1a.cov_kwds['weights_func'] is sw.weights_uniform)
kwdsb = {'kernel': sw.weights_bartlett, 'maxlags': 2}
res1a = self.res1.model.fit(cov_type='HAC', cov_kwds=kwdsb)
res2a = self.res2.model.fit(cov_type='HAC', cov_kwds=kwdsb)
assert_allclose(res1a.bse, res2a.bse, rtol=1e-12)
# regression test for bse values
bse = np.array([ 2.502264, 3.697807, 9.193303])
assert_allclose(res1a.bse, bse, rtol=1e-6)
class TestGLMGaussHACUniform2(TestGLMGaussHACUniform):
@classmethod
def setup_class(cls):
cls.cov_type = 'HAC'
kwds={'kernel': sw.weights_uniform, 'maxlags': 2}
mod1 = GLM(endog, exog, family=families.Gaussian())
cls.res1 = mod1.fit(cov_type='HAC', cov_kwds=kwds)
# check kernel as string
mod2 = OLS(endog, exog)
kwds2 = {'kernel': 'uniform', 'maxlags': 2}
cls.res2 = mod2.fit(cov_type='HAC', cov_kwds=kwds)
class TestGLMGaussHACPanel(CheckDiscreteGLM):
@classmethod
def setup_class(cls):
cls.cov_type = 'hac-panel'
# time index is just made up to have a test case
time = np.tile(np.arange(7), 5)[:-1]
mod1 = GLM(endog.copy(), exog.copy(), family=families.Gaussian())
kwds = dict(time=time,
maxlags=2,
kernel=sw.weights_uniform,
use_correction='hac',
df_correction=False)
cls.res1 = mod1.fit(cov_type='hac-panel', cov_kwds=kwds)
cls.res1b = mod1.fit(cov_type='nw-panel', cov_kwds=kwds)
mod2 = OLS(endog, exog)
cls.res2 = mod2.fit(cov_type='hac-panel', cov_kwds=kwds)
def test_kwd(self):
# test corrected keyword name
assert_allclose(self.res1b.bse, self.res1.bse, rtol=1e-12)
class TestGLMGaussHACPanelGroups(CheckDiscreteGLM):
@classmethod
def setup_class(cls):
cls.cov_type = 'hac-panel'
# time index is just made up to have a test case
groups = np.repeat(np.arange(5), 7)[:-1]
mod1 = GLM(endog.copy(), exog.copy(), family=families.Gaussian())
kwds = dict(groups=pd.Series(groups), # check for #3606
maxlags=2,
kernel=sw.weights_uniform,
use_correction='hac',
df_correction=False)
cls.res1 = mod1.fit(cov_type='hac-panel', cov_kwds=kwds)
mod2 = OLS(endog, exog)
cls.res2 = mod2.fit(cov_type='hac-panel', cov_kwds=kwds)
class TestGLMGaussHACGroupsum(CheckDiscreteGLM):
@classmethod
def setup_class(cls):
cls.cov_type = 'hac-groupsum'
# time index is just made up to have a test case
time = np.tile(np.arange(7), 5)[:-1]
mod1 = GLM(endog, exog, family=families.Gaussian())
kwds = dict(time=pd.Series(time), # check for #3606
maxlags=2,
use_correction='hac',
df_correction=False)
cls.res1 = mod1.fit(cov_type='hac-groupsum', cov_kwds=kwds)
cls.res1b = mod1.fit(cov_type='nw-groupsum', cov_kwds=kwds)
mod2 = OLS(endog, exog)
cls.res2 = mod2.fit(cov_type='hac-groupsum', cov_kwds=kwds)
def test_kwd(self):
# test corrected keyword name
assert_allclose(self.res1b.bse, self.res1.bse, rtol=1e-12)
if __name__ == '__main__':
tt = TestPoissonClu()
tt.setup_class()
tt.test_basic()
tt = TestNegbinClu()
tt.setup_class()
tt.test_basic()
| 33.695592
| 118
| 0.601194
|
3dcd840b94e6994551f604c5a7877d66ec70141d
| 1,411
|
py
|
Python
|
mine/mine.py
|
Oyekunle-Mark/roaming-serpent
|
c9433234d42e4fc7ab2a36e6186a962e201ce1c1
|
[
"MIT"
] | null | null | null |
mine/mine.py
|
Oyekunle-Mark/roaming-serpent
|
c9433234d42e4fc7ab2a36e6186a962e201ce1c1
|
[
"MIT"
] | null | null | null |
mine/mine.py
|
Oyekunle-Mark/roaming-serpent
|
c9433234d42e4fc7ab2a36e6186a962e201ce1c1
|
[
"MIT"
] | null | null | null |
import requests
import time
import hashlib
from decouple import config
TOKEN = config("TOKEN")
auth = {"Authorization": "Token " + TOKEN}
def get_last_proof():
res = requests.get(
"https://lambda-treasure-hunt.herokuapp.com/api/bc/last_proof/",
headers=auth
)
return res.json()
def mine(new_proof):
res = requests.post(
"https://lambda-treasure-hunt.herokuapp.com/api/bc/mine/",
headers=auth,
json={"proof": new_proof}
)
print(res)
return res.json()
def valid_proof(last_proof, proof, difficulty):
checksum = '0' * difficulty
guess = f'{last_proof}{proof}'.encode()
guess_hash = hashlib.sha256(guess).hexdigest()
return guess_hash[:difficulty] == checksum
last_proof_obj = get_last_proof()
last_proof = last_proof_obj['proof']
diff = last_proof_obj['difficulty']
time.sleep(last_proof_obj['cooldown'])
def proof_of_work(start_point):
print("Mining new block")
start_time = time.time()
proof = int(start_point)
while valid_proof(last_proof, proof, diff) is False:
proof += 1
end_time = time.time()
print(
f'Block mined in {round(end_time-start_time, 2)}sec. Nonce: {str(proof)}')
print("Mining with proof...")
response = mine(proof)
return response
if __name__ == "__main__":
while True:
res = proof_of_work(0)
time.sleep(res["cooldown"])
| 22.396825
| 82
| 0.656272
|
8cf6a05a9545562378220792b7a91ee31b2fc19d
| 4,431
|
py
|
Python
|
chatbot/mybot-basic.py
|
LiamFraney/foodbot
|
f7805e0bc4d72287321342486cec1092dbc0eb61
|
[
"MIT"
] | null | null | null |
chatbot/mybot-basic.py
|
LiamFraney/foodbot
|
f7805e0bc4d72287321342486cec1092dbc0eb61
|
[
"MIT"
] | null | null | null |
chatbot/mybot-basic.py
|
LiamFraney/foodbot
|
f7805e0bc4d72287321342486cec1092dbc0eb61
|
[
"MIT"
] | null | null | null |
import spoonacular as sp
import json, requests, os
import aiml
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from xml.etree import ElementTree as ET
import tensorflow as tf
from tensorflow.keras import models, backend, layers
import urllib.request
import numpy
import cv2
kern = aiml.Kernel()
kern.setTextEncoding(None)
kern.bootstrap(learnFiles="chatbot/mybot-basic.xml")
model = models.load_model("cnn/model.h5")
APIkey = "13ffaf56553e48faab0c6ce7762f2e1c"
spoon_api = sp.API(APIkey)
print("Welcome to food bot")
patterns = []
tree = ET.parse("chatbot/mybot-basic.xml")
all_pattern = tree.findall("*/pattern")
for pattern in all_pattern:
if "*" not in pattern.text:
patterns.append(pattern.text)
classnames = []
with open("cnn/food41/meta/meta/classes.txt") as reader:
for line in reader:
classnames.append(line.strip())
def get_similar(phrase):
corpus = list(patterns)
corpus.append(phrase)
vectorizer = TfidfVectorizer()
tfidf_matrix = vectorizer.fit_transform(corpus)
similarity = list(cosine_similarity(tfidf_matrix, tfidf_matrix[-1]).flatten()[:-1])
if max(similarity) < 0.1:
print("Sorry I do not understand")
else:
similar_index = similarity.index(max(similarity))
# print(max(similarity))
# print(patterns[similar_index])
handle_answer(kern.respond(patterns[similar_index]))
def handle_answer(answer):
if answer[0] == '#':
params = answer[1:].split('$')
cmd = int(params[0])
if cmd == 0:
print(params[1])
return True
elif cmd == 1:
response = spoon_api.search_recipes_complex(params[1])
data = response.json()
if data["results"]:
recipe_id = data["results"][0]["id"]
response = spoon_api.get_recipe_information(recipe_id)
data = response.json()
print(data["sourceUrl"])
else:
print("There is no recipe for this")
elif cmd == 2:
response = spoon_api.get_a_random_food_joke()
data = response.json()
print(data["text"])
elif cmd == 3:
response = spoon_api.get_random_food_trivia()
data = response.json()
print(data["text"])
elif cmd == 4:
q = params[1]
response = spoon_api.quick_answer("How much " + q)
data = response.json()
print(data["answer"])
elif cmd == 5:
q = params[1]
name = 0
for part in q.split(" "):
if "jpg" in part or "png" in part:
name = part
if name == 0:
return "Input is neither a valid file nor url"
if os.path.exists(name):
npImage = cv2.imread(name)
else:
try:
filename = name.split("/")[-1]
urllib.request.urlretrieve(name, filename)
npImage = cv2.imread(filename)
os.remove(filename)
except Exception as e:
print(e)
return "Input is neither a valid file nor url"
rows = 150
cols = 150
color_bands = 3
input_shape = (rows, cols, color_bands)
scaledImage = cv2.resize(npImage, dsize=(rows, cols), interpolation=cv2.INTER_CUBIC)
scaledImage = scaledImage/255
imageArray = scaledImage.reshape(1, rows, cols, color_bands)
predictions = model.predict(imageArray)
print(classnames[numpy.argmax(predictions)])
elif cmd == 99:
get_similar(answer)
else:
print(answer)
while True:
#get user input
try:
userInput = input("> ")
userInput = userInput.split("?")[0]
except (KeyboardInterrupt, EOFError) as e:
print("Bye!")
break
#pre-process user input and determine response agent (if needed)
responseAgent = 'aiml'
#activate selected response agent
if responseAgent == 'aiml':
answer = kern.respond(userInput)
answer = answer.replace(" #99$", ".")
if handle_answer(answer):
break
| 31.425532
| 96
| 0.582938
|
12c98f78375b8a1d57d6593c328cfb6cfe9f7898
| 474
|
py
|
Python
|
shell/redirect.py
|
utep-cs-systems-courses/os-shell-Joshua-Zamora
|
e550935fae4ca1855706722736b380dbbfef6d61
|
[
"BSD-3-Clause"
] | null | null | null |
shell/redirect.py
|
utep-cs-systems-courses/os-shell-Joshua-Zamora
|
e550935fae4ca1855706722736b380dbbfef6d61
|
[
"BSD-3-Clause"
] | null | null | null |
shell/redirect.py
|
utep-cs-systems-courses/os-shell-Joshua-Zamora
|
e550935fae4ca1855706722736b380dbbfef6d61
|
[
"BSD-3-Clause"
] | null | null | null |
import os
import sys
def redirect(arg, symbol):
if symbol == '<' and arg.count("<") == 1:
os.close(0)
os.open(arg[arg.index(symbol) + 1], os.O_RDONLY)
os.set_inheritable(0, True)
elif symbol == '>' and arg.count(">") == 1:
os.close(1)
os.open(arg[arg.index(symbol) + 1], os.O_CREAT | os.O_WRONLY)
os.set_inheritable(1, True)
else:
os.write(2, "redirect error, exiting...".encode())
sys.exit(1)
| 24.947368
| 69
| 0.552743
|
3aa2bb85ff3fe26e6d2fe6094d146588de9da827
| 2,588
|
py
|
Python
|
qiskit/providers/ibmq/credentials/__init__.py
|
mtreinish/qiskit-ibmq-provider
|
3ace23a40a9a049c08b140bf0a16c68ed5647f74
|
[
"Apache-2.0"
] | 1
|
2020-07-14T20:09:52.000Z
|
2020-07-14T20:09:52.000Z
|
qiskit/providers/ibmq/credentials/__init__.py
|
mtreinish/qiskit-ibmq-provider
|
3ace23a40a9a049c08b140bf0a16c68ed5647f74
|
[
"Apache-2.0"
] | null | null | null |
qiskit/providers/ibmq/credentials/__init__.py
|
mtreinish/qiskit-ibmq-provider
|
3ace23a40a9a049c08b140bf0a16c68ed5647f74
|
[
"Apache-2.0"
] | null | null | null |
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Utilities for working with credentials for the IBMQ package."""
from collections import OrderedDict
import logging
from .credentials import Credentials
from .exceptions import CredentialsError
from .configrc import read_credentials_from_qiskitrc, store_credentials
from .environ import read_credentials_from_environ
from .qconfig import read_credentials_from_qconfig
logger = logging.getLogger(__name__)
def discover_credentials(qiskitrc_filename=None):
"""Automatically discover credentials for IBM Q.
This method looks for credentials in the following locations, in order,
and returning as soon as credentials are found::
1. in the `Qconfig.py` file in the current working directory.
2. in the environment variables.
3. in the `qiskitrc` configuration file
Args:
qiskitrc_filename (str): location for the `qiskitrc` configuration
file. If `None`, defaults to `{HOME}/.qiskitrc/qiskitrc`.
Returns:
dict: dictionary with the contents of the configuration file, with
the form::
{credentials_unique_id: Credentials}
"""
credentials = OrderedDict()
# dict[str:function] that defines the different locations for looking for
# credentials, and their precedence order.
readers = OrderedDict([
('qconfig', (read_credentials_from_qconfig, {})),
('environment variables', (read_credentials_from_environ, {})),
('qiskitrc', (read_credentials_from_qiskitrc,
{'filename': qiskitrc_filename}))
])
# Attempt to read the credentials from the different sources.
for display_name, (reader_function, kwargs) in readers.items():
try:
credentials = reader_function(**kwargs)
logger.info('Using credentials from %s', display_name)
if credentials:
break
except CredentialsError as ex:
logger.warning(
'Automatic discovery of %s credentials failed: %s',
display_name, str(ex))
return credentials
| 35.452055
| 77
| 0.696291
|
da7ac750647286e82468b2a3d27a38ace10538ca
| 4,810
|
py
|
Python
|
benchmarking/bridge/db.py
|
virtan/FAI-PEP
|
8641a54b2328c343ab0470f195a42da1021d1392
|
[
"Apache-2.0"
] | 1
|
2019-08-09T07:50:21.000Z
|
2019-08-09T07:50:21.000Z
|
benchmarking/bridge/db.py
|
virtan/FAI-PEP
|
8641a54b2328c343ab0470f195a42da1021d1392
|
[
"Apache-2.0"
] | null | null | null |
benchmarking/bridge/db.py
|
virtan/FAI-PEP
|
8641a54b2328c343ab0470f195a42da1021d1392
|
[
"Apache-2.0"
] | null | null | null |
#!/usr/bin/env python
##############################################################################
# Copyright 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
##############################################################################
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import json
from bridge.auth import Auth
from utils.custom_logger import getLogger
from utils.utilities import requestsJson
NETWORK_TIMEOUT = 150
class DBDriver(object):
def __init__(self, db, app_id, token, table, job_queue, is_test, benchmark_db_entry):
self.table = table
self.job_queue = job_queue
auth = Auth(db, app_id, token, is_test)
self.auth_params = auth.get_auth_params()
assert benchmark_db_entry != "", "Database entry cannot be empty"
self.benchmark_db_entry = benchmark_db_entry
def submitBenchmarks(self, data, devices, identifier, user, hashes=None):
json_data = json.dumps(data)
params = {
'table': self.table,
'job_queue': self.job_queue,
'action': 'add',
'identifier': identifier,
'devices': devices,
'benchmarks': json_data,
'user': user,
}
if hashes:
params['hashes'] = hashes
self._requestData(params)
def claimBenchmarks(self, server_id, devices, hashes=None):
params = {
'table': self.table,
'job_queue': self.job_queue,
'action': 'claim',
'claimer': server_id,
'devices': devices,
}
if hashes:
params['hashes'] = hashes
result_json = self._requestData(params)
return self._processBenchmarkResults(result_json['values'])
def releaseBenchmarks(self, server_id, ids):
params = {
'table': self.table,
'job_queue': self.job_queue,
'action': 'release',
'claimer': server_id,
'ids': ids,
}
self._requestData(params)
def runBenchmarks(self, server_id, ids):
params = {
'table': self.table,
'job_queue': self.job_queue,
'action': 'run',
'claimer': server_id,
'ids': ids,
}
self._requestData(params)
def doneBenchmarks(self, id, status, result, log):
params = {
'table': self.table,
'job_queue': self.job_queue,
'action': 'done',
'id': id,
'status': status,
'result': result,
'log': log,
}
self._requestData(params)
def statusBenchmarks(self, identifier):
params = {
'table': self.table,
'job_queue': self.job_queue,
'action': 'status',
'identifier': identifier,
}
request_json = self._requestData(params)
return request_json["values"]
def getBenchmarks(self, ids):
params = {
'table': self.table,
'job_queue': self.job_queue,
'action': 'get',
'ids': ids,
}
request_json = self._requestData(params)
return request_json["values"]
def updateDevices(self, server_id, devices, reset):
params = {
'table': self.table,
'job_queue': self.job_queue,
'action': 'update_devices',
'claimer': server_id,
'devices': devices,
}
if reset:
params["reset"] = "true"
self._requestData(params)
def listDevices(self, job_queue):
params = {
'table': self.table,
'job_queue': job_queue,
'action': 'list_devices',
}
result_json = self._requestData(params)
return result_json["values"]
def _requestData(self, params):
params.update(self.auth_params)
result_json = requestsJson(self.benchmark_db_entry,
data=params, timeout=NETWORK_TIMEOUT)
if "status" not in result_json or result_json['status'] != "success":
getLogger().error(
"DB post failed, params {}".format(json.dumps(params)))
return {
"status": "fail",
"values": [],
}
else:
return result_json
def _processBenchmarkResults(self, result_json):
for result in result_json:
benchmarks = json.loads(result["benchmarks"])
result["benchmarks"] = benchmarks
return result_json
| 31.032258
| 89
| 0.543451
|
ffedeeed0b866cc7ec953acea9737b88432086bd
| 59
|
py
|
Python
|
tda/__init__.py
|
imxly2/chinese_text_aug
|
141d6717292d93da5a1f964cb26150725cffd9d5
|
[
"MIT"
] | null | null | null |
tda/__init__.py
|
imxly2/chinese_text_aug
|
141d6717292d93da5a1f964cb26150725cffd9d5
|
[
"MIT"
] | null | null | null |
tda/__init__.py
|
imxly2/chinese_text_aug
|
141d6717292d93da5a1f964cb26150725cffd9d5
|
[
"MIT"
] | null | null | null |
from .translate import back_translate
from .eda import eda
| 19.666667
| 37
| 0.830508
|
d00d1926d5fdebe448777ecedfddce7b6cfa0e7a
| 98
|
py
|
Python
|
boxsdk/version.py
|
dtrodger/box-python-sdk
|
dba132e347e7b5a4a20feb148f316d0b145684a5
|
[
"Apache-2.0"
] | null | null | null |
boxsdk/version.py
|
dtrodger/box-python-sdk
|
dba132e347e7b5a4a20feb148f316d0b145684a5
|
[
"Apache-2.0"
] | null | null | null |
boxsdk/version.py
|
dtrodger/box-python-sdk
|
dba132e347e7b5a4a20feb148f316d0b145684a5
|
[
"Apache-2.0"
] | null | null | null |
# coding: utf-8
from __future__ import unicode_literals, absolute_import
__version__ = '2.7.1'
| 14
| 56
| 0.765306
|
286f89c52c18a75bf8c8b3146148906d9ebd1a1e
| 3,284
|
py
|
Python
|
studio/gcloud_artifact_store.py
|
NunoEdgarGFlowHub/studio
|
42b221892a81535842ff25cbbcc434d6422a19e5
|
[
"Apache-2.0"
] | null | null | null |
studio/gcloud_artifact_store.py
|
NunoEdgarGFlowHub/studio
|
42b221892a81535842ff25cbbcc434d6422a19e5
|
[
"Apache-2.0"
] | null | null | null |
studio/gcloud_artifact_store.py
|
NunoEdgarGFlowHub/studio
|
42b221892a81535842ff25cbbcc434d6422a19e5
|
[
"Apache-2.0"
] | null | null | null |
import time
import calendar
from .tartifact_store import TartifactStore
from . import logs
STORAGE_CLIENT_EXPIRATION = 3600
class GCloudArtifactStore(TartifactStore):
def __init__(self, config,
measure_timestamp_diff=False,
compression=None,
verbose=10):
self.logger = logs.getLogger('GCloudArtifactStore')
self.logger.setLevel(verbose)
self.config = config
self._client = None
self._client_timestamp = None
compression = compression if compression else config.get('compression')
super(GCloudArtifactStore, self).__init__(
measure_timestamp_diff,
compression=compression)
def _get_bucket_obj(self):
while True:
try:
bucket = self.get_client().get_bucket(self.config['bucket'])
break
except BaseException as e:
self.logger.exception(e)
try:
bucket = self.get_client().create_bucket(
self.config['bucket'])
break
except BaseException as e:
self.logger.exception(e)
time.sleep(5)
return bucket
def get_client(self):
if self._client is None or \
self._client_timestamp is None or \
time.time() - self._client_timestamp > STORAGE_CLIENT_EXPIRATION:
from google.cloud import storage
if 'credentials' in self.config.keys():
self._client = storage.Client \
.from_service_account_json(self.config['serviceAccount'])
else:
self._client = storage.Client()
self._client_timestamp = time.time()
return self._client
def _upload_file(self, key, local_path):
self._get_bucket_obj().blob(key).upload_from_filename(local_path)
def _download_file(self, key, local_path, bucket=None):
self._get_bucket_obj().get_blob(key).download_to_filename(local_path)
def _delete_file(self, key):
blob = self._get_bucket_obj().get_blob(key)
if blob:
blob.delete()
def _get_file_url(self, key, method='GET'):
expiration = int(time.time() + 100000)
return self._get_bucket_obj().blob(key).generate_signed_url(
expiration,
method=method)
def _get_file_timestamp(self, key):
blob = self._get_bucket_obj().get_blob(key)
if blob is None:
return None
time_updated = blob.updated
if time_updated:
timestamp = calendar.timegm(time_updated.timetuple())
return timestamp
else:
return None
def grant_write(self, key, user):
blob = self._get_bucket_obj().get_blob(key)
if not blob:
blob = self._get_bucket_obj().blob(key)
blob.upload_from_string("dummy")
acl = blob.acl
if user:
acl.user(user).grant_owner()
else:
acl.all().grant_owner()
acl.save()
def get_qualified_location(self, key):
return 'gs://' + self.get_bucket() + '/' + key
def get_bucket(self):
return self._get_bucket_obj().name
| 29.854545
| 79
| 0.589525
|
d240071c8b335853274a9867fbd9ffff23324af4
| 8,144
|
py
|
Python
|
pdb2pqr/utilities.py
|
stefdoerr/pdb2pqr
|
c48a97a17f75d6c97a81bfb9e138ab165c563841
|
[
"BSD-3-Clause"
] | null | null | null |
pdb2pqr/utilities.py
|
stefdoerr/pdb2pqr
|
c48a97a17f75d6c97a81bfb9e138ab165c563841
|
[
"BSD-3-Clause"
] | null | null | null |
pdb2pqr/utilities.py
|
stefdoerr/pdb2pqr
|
c48a97a17f75d6c97a81bfb9e138ab165c563841
|
[
"BSD-3-Clause"
] | null | null | null |
"""Utilities for the PDB2PQR software suite.
.. todo:
The functions in this module are great examples of why PDB2PQR needs
:mod:`numpy`.
More efforts should be made to subsitute with :mod:`numpy` data types and
functions wherever possible throughout the code base.
.. codeauthor:: Todd Dolinsky
.. codeauthor:: Yong Huang
.. codeauthor:: Nathan Baker
"""
import math
import logging
# from pathlib import Path
import numpy as np
from .config import SMALL_NUMBER, DIHEDRAL_WTF, CHARGE_ERROR
_LOGGER = logging.getLogger(__name__)
def noninteger_charge(charge, error_tol=CHARGE_ERROR) -> str:
"""Test whether a charge is an integer.
:param float charge: value to test
:param float error_tol: absolute error tolerance
:returns: string with descripton of problem or empty string if no problem
"""
abs_error = abs(charge - round(charge))
if abs_error > abs(error_tol):
return (
f"{charge} deviates by {abs_error} from integral, exceeding error "
f"tolerance {error_tol}"
)
return ""
def sort_dict_by_value(inputdict):
"""Sort a dictionary by its values.
:param inputdict: the dictionary to sort
:type inputdict: dict
:return: list of keys sorted by value
:rtype: list
"""
items = sorted(inputdict.items(), key=lambda x: x[1], reverse=True)
items = [v for v, k in items]
return items
def shortest_path(graph, start, end, path=[]):
"""Find the shortest path between two nodes.
Uses recursion to find the shortest path from one node to another in an
unweighted graph.
Adapted from http://www.python.org/doc/essays/graphs.html
:param graph: a mapping of the graph to analyze, of the form {0: [1,2],
1:[3,4], ...} . Each key has a list of edges.
:type graph: dict
:param start: the ID of the key to start the analysis from
:type start: str
:param end: the ID of the key to end the analysis
:type end: str
:param path: optional argument used during the recursive step to keep
the current path up to that point
:type path: list
:return: list of the shortest path or ``None`` if start and end are not
connected
:rtype: list
"""
path = path + [start]
if start == end:
return path
if start not in graph:
return None
shortest = None
for node in graph[start]:
if node not in path:
newpath = shortest_path(graph, node, end, path)
if newpath and (not shortest or len(newpath) < len(shortest)):
shortest = newpath
return shortest
def analyze_connectivity(map_, key):
"""Analyze the connectivity of a given map using the key value.
:param map: map to analyze
:type map: dict
:param key: key value
:type key: str
:return: list of connected values to the key
:rtype: list
"""
clist = []
keys = [key]
while keys:
key = keys[0]
if key not in clist:
clist.append(key)
if key in map_:
for value in map_[key]:
if value not in clist:
keys.append(value)
keys.pop(keys.index(key))
return clist
def angle(coords1, coords2, coords3):
"""Get the angle between three coordinates.
:param coords1: first coordinate set
:type coords1: [float, float, float]
:param coords2: second (vertex) coordinate set
:type coords2: [float, float, float]
:param coords3: third coordinate set
:type coords3: [float, float, float]
:return: angle between the atoms (in degrees)
:rtype: float
"""
diff32 = np.array(coords3) - np.array(coords2)
diff12 = np.array(coords1) - np.array(coords2)
norm1 = normalize(diff32)
norm2 = normalize(diff12)
dotted = np.inner(norm1, norm2)
if dotted > 1.0: # If normalized, this is due to rounding error
dotted = 1.0
elif dotted < -1.0:
dotted = -1.0
rad = np.absolute(np.arccos(dotted))
value = rad * 180.0 / np.pi
if value > 180.0:
value = 360.0 - value
return value
def distance(coords1, coords2):
"""Calculate the distance between two coordinates.
:param coords1: coordinates of form [x,y,z]
:type coords1: [float, float, float]
:param coords2: coordinates of form [x,y,z]
:type coords2: [float, float, float]
:return: distance between the two coordinates
:rtype: float
"""
coords1 = np.array(coords1)
coords2 = np.array(coords2)
return np.linalg.norm(coords1 - coords2)
def add(coords1, coords2):
"""Add one 3-dimensional point to another.
:param coords1: coordinates of form [x,y,z]
:type coords1: [float, float, float]
:param coords2: coordinates of form [x,y,z]
:type coords2: [float, float, float]
:return: list of coordinates equal to coords2 + coords1
:rtype: numpy.ndarray
"""
return np.array(coords1) + np.array(coords2)
def subtract(coords1, coords2):
"""Suntract one 3-dimensional point from another.
:param coords1: coordinates of form [x,y,z]
:type coords1: [float, float, float]
:param coords2: coordinates of form [x,y,z]
:type coords2: [float, float, float]
:return: list of coordinates equal to coords2 - coords1
:rtype: numpy.ndarray
"""
return np.array(coords1) - np.array(coords2)
def cross(coords1, coords2):
"""Find the cross-product of one 3-dimensional point with another.
:param coords1: coordinates of form [x,y,z]
:type coords1: [float, float, float]
:param coords2: coordinates of form [x,y,z]
:type coords2: [float, float, float]
:return: list of coordinates equal to coords2 cross coords1
:rtype: numpy.ndarray
"""
return np.cross(np.array(coords1), np.array(coords2))
def dot(coords1, coords2):
"""Find the dot-product of one 3-dimensional point with another.
:param coords1: coordinates of form [x,y,z]
:type coords1: [float, float, float]
:param coords2: coordinates of form [x,y,z]
:type coords2: [float, float, float]
:return: list of coordinates equal to the inner product of coords2 with
coords1
:rtype: numpy.ndarray
"""
return np.inner(np.array(coords1), np.array(coords2))
def normalize(coords):
"""Normalize a set of coordinates to unit vector.
:param coords: coordinates of form [x,y,z]
:type coords: [float, float, float]
:return: normalized coordinates
:rtype: numpy.ndarray
"""
return coords / np.linalg.norm(coords)
def factorial(num):
"""Returns the factorial of the given number.
:param num: number for which to compute factorial
:type num: int
:return: factorial of number
:rtype: int
"""
if num <= 1:
return 1
return num * factorial(num - 1)
def dihedral(coords1, coords2, coords3, coords4):
"""Calculate the dihedral angle from four atoms' coordinates.
:param coords1: one of four coordinates of form [x,y,z]
:type coords1: [float, float, float]
:param coords2: one of four coordinates of form [x,y,z]
:type coords2: [float, float, float]
:param coords3: one of four coordinates of form [x,y,z]
:type coords3: [float, float, float]
:param coords4: one of four coordinates of form [x,y,z]
:type coords4: [float, float, float]
:return: the angle (in degrees)
:rtype: float
"""
diff43 = np.array(coords4) - np.array(coords3)
diff32 = np.array(coords3) - np.array(coords2)
diff12 = np.array(coords1) - np.array(coords2)
c12_32 = np.cross(diff12, diff32)
c12_32 = normalize(c12_32)
c43_32 = np.cross(diff43, diff32)
c43_32 = normalize(c43_32)
scal = np.inner(c12_32, c43_32)
if np.absolute(scal + 1.0) < SMALL_NUMBER:
value = 180.0
elif np.absolute(scal - 1.0) < SMALL_NUMBER:
value = 0.0
else:
value = DIHEDRAL_WTF * math.acos(scal)
chiral = np.inner(np.cross(c12_32, c43_32), diff32)
if chiral < 0:
value *= -1.0
return value
| 30.616541
| 79
| 0.63998
|
503506b0fb3d1ced4547ebf19a8d442e6ffe7304
| 51,610
|
py
|
Python
|
src/twisted/internet/base.py
|
nielsavonds/twisted
|
64506ce3bb578d708372237872aa6b8b90890cb6
|
[
"Unlicense",
"MIT"
] | null | null | null |
src/twisted/internet/base.py
|
nielsavonds/twisted
|
64506ce3bb578d708372237872aa6b8b90890cb6
|
[
"Unlicense",
"MIT"
] | null | null | null |
src/twisted/internet/base.py
|
nielsavonds/twisted
|
64506ce3bb578d708372237872aa6b8b90890cb6
|
[
"Unlicense",
"MIT"
] | null | null | null |
# -*- test-case-name: twisted.test.test_internet,twisted.internet.test.test_core -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Very basic functionality for a Reactor implementation.
"""
from abc import ABC, abstractmethod
import builtins
from heapq import heappush, heappop, heapify
import socket # needed only for sync-dns
import sys
from traceback import format_stack
from types import FrameType
from typing import (
Any,
AnyStr,
Callable,
Dict,
List,
Mapping,
NewType,
Optional,
Sequence,
Set,
Tuple,
TYPE_CHECKING,
Union,
cast,
)
import warnings
from zope.interface import implementer, classImplements
from twisted.internet import fdesc, main, error, abstract, defer, threads
from twisted.internet._resolver import (
ComplexResolverSimplifier as _ComplexResolverSimplifier,
GAIResolver as _GAIResolver,
SimpleResolverComplexifier as _SimpleResolverComplexifier,
)
from twisted.internet.defer import Deferred, DeferredList
from twisted.internet.interfaces import (
_ISupportsExitSignalCapturing,
IAddress,
IConnector,
IDelayedCall,
IHostnameResolver,
IProtocol,
IReactorCore,
IReactorPluggableNameResolver,
IReactorPluggableResolver,
IReactorThreads,
IReactorTime,
IReadDescriptor,
IResolverSimple,
IWriteDescriptor,
)
from twisted.internet.protocol import ClientFactory
from twisted.python import log, reflect
from twisted.python.failure import Failure
from twisted.python.runtime import seconds as runtimeSeconds, platform
if TYPE_CHECKING:
from twisted.internet.tcp import Client
# This import is for side-effects! Even if you don't see any code using it
# in this module, don't delete it.
from twisted.python import threadable
if platform.supportsThreads():
from twisted.python.threadpool import ThreadPool
else:
ThreadPool = None # type: ignore[misc, assignment]
@implementer(IDelayedCall)
class DelayedCall:
# enable .debug to record creator call stack, and it will be logged if
# an exception occurs while the function is being run
debug = False
_repr: Optional[str] = None
def __init__(
self,
time: float,
func: Callable[..., Any],
args: Sequence[object],
kw: Dict[str, object],
cancel: Callable[["DelayedCall"], None],
reset: Callable[["DelayedCall"], None],
seconds: Callable[[], float] = runtimeSeconds,
) -> None:
"""
@param time: Seconds from the epoch at which to call C{func}.
@param func: The callable to call.
@param args: The positional arguments to pass to the callable.
@param kw: The keyword arguments to pass to the callable.
@param cancel: A callable which will be called with this
DelayedCall before cancellation.
@param reset: A callable which will be called with this
DelayedCall after changing this DelayedCall's scheduled
execution time. The callable should adjust any necessary
scheduling details to ensure this DelayedCall is invoked
at the new appropriate time.
@param seconds: If provided, a no-argument callable which will be
used to determine the current time any time that information is
needed.
"""
self.time, self.func, self.args, self.kw = time, func, args, kw
self.resetter = reset
self.canceller = cancel
self.seconds = seconds
self.cancelled = self.called = 0
self.delayed_time = 0.0
if self.debug:
self.creator = format_stack()[:-2]
def getTime(self) -> float:
"""
Return the time at which this call will fire
@return: The number of seconds after the epoch at which this call is
scheduled to be made.
"""
return self.time + self.delayed_time
def cancel(self) -> None:
"""
Unschedule this call
@raise AlreadyCancelled: Raised if this call has already been
unscheduled.
@raise AlreadyCalled: Raised if this call has already been made.
"""
if self.cancelled:
raise error.AlreadyCancelled
elif self.called:
raise error.AlreadyCalled
else:
self.canceller(self)
self.cancelled = 1
if self.debug:
self._repr = repr(self)
del self.func, self.args, self.kw
def reset(self, secondsFromNow: float) -> None:
"""
Reschedule this call for a different time
@param secondsFromNow: The number of seconds from the time of the
C{reset} call at which this call will be scheduled.
@raise AlreadyCancelled: Raised if this call has been cancelled.
@raise AlreadyCalled: Raised if this call has already been made.
"""
if self.cancelled:
raise error.AlreadyCancelled
elif self.called:
raise error.AlreadyCalled
else:
newTime = self.seconds() + secondsFromNow
if newTime < self.time:
self.delayed_time = 0.0
self.time = newTime
self.resetter(self)
else:
self.delayed_time = newTime - self.time
def delay(self, secondsLater: float) -> None:
"""
Reschedule this call for a later time
@param secondsLater: The number of seconds after the originally
scheduled time for which to reschedule this call.
@raise AlreadyCancelled: Raised if this call has been cancelled.
@raise AlreadyCalled: Raised if this call has already been made.
"""
if self.cancelled:
raise error.AlreadyCancelled
elif self.called:
raise error.AlreadyCalled
else:
self.delayed_time += secondsLater
if self.delayed_time < 0.0:
self.activate_delay()
self.resetter(self)
def activate_delay(self) -> None:
self.time += self.delayed_time
self.delayed_time = 0.0
def active(self) -> bool:
"""Determine whether this call is still pending
@return: True if this call has not yet been made or cancelled,
False otherwise.
"""
return not (self.cancelled or self.called)
def __le__(self, other: object) -> bool:
"""
Implement C{<=} operator between two L{DelayedCall} instances.
Comparison is based on the C{time} attribute (unadjusted by the
delayed time).
"""
if isinstance(other, DelayedCall):
return self.time <= other.time
else:
return NotImplemented
def __lt__(self, other: object) -> bool:
"""
Implement C{<} operator between two L{DelayedCall} instances.
Comparison is based on the C{time} attribute (unadjusted by the
delayed time).
"""
if isinstance(other, DelayedCall):
return self.time < other.time
else:
return NotImplemented
def __repr__(self) -> str:
"""
Implement C{repr()} for L{DelayedCall} instances.
@returns: String containing details of the L{DelayedCall}.
"""
if self._repr is not None:
return self._repr
if hasattr(self, "func"):
# This code should be replaced by a utility function in reflect;
# see ticket #6066:
if hasattr(self.func, "__qualname__"):
func: Optional[str] = self.func.__qualname__
elif hasattr(self.func, "__name__"):
func = self.func.func_name # type: ignore[attr-defined]
if hasattr(self.func, "im_class"):
func = self.func.im_class.__name__ + "." + func # type: ignore[attr-defined]
else:
func = reflect.safe_repr(self.func)
else:
func = None
now = self.seconds()
L = [
"<DelayedCall 0x%x [%ss] called=%s cancelled=%s"
% (id(self), self.time - now, self.called, self.cancelled)
]
if func is not None:
L.extend((" ", func, "("))
if self.args:
L.append(", ".join([reflect.safe_repr(e) for e in self.args]))
if self.kw:
L.append(", ")
if self.kw:
L.append(
", ".join(
[
"{}={}".format(k, reflect.safe_repr(v))
for (k, v) in self.kw.items()
]
)
)
L.append(")")
if self.debug:
L.append("\n\ntraceback at creation: \n\n%s" % (" ".join(self.creator)))
L.append(">")
return "".join(L)
@implementer(IResolverSimple)
class ThreadedResolver:
"""
L{ThreadedResolver} uses a reactor, a threadpool, and
L{socket.gethostbyname} to perform name lookups without blocking the
reactor thread. It also supports timeouts indepedently from whatever
timeout logic L{socket.gethostbyname} might have.
@ivar reactor: The reactor the threadpool of which will be used to call
L{socket.gethostbyname} and the I/O thread of which the result will be
delivered.
"""
def __init__(self, reactor: "ReactorBase") -> None:
self.reactor = reactor
self._runningQueries: Dict[
Deferred[str], Tuple[Deferred[str], IDelayedCall]
] = {}
def _fail(self, name: str, err: str) -> Failure:
lookupError = error.DNSLookupError(f"address {name!r} not found: {err}")
return Failure(lookupError)
def _cleanup(self, name: str, lookupDeferred: Deferred[str]) -> None:
userDeferred, cancelCall = self._runningQueries[lookupDeferred]
del self._runningQueries[lookupDeferred]
userDeferred.errback(self._fail(name, "timeout error"))
def _checkTimeout(
self, result: str, name: str, lookupDeferred: Deferred[str]
) -> None:
try:
userDeferred, cancelCall = self._runningQueries[lookupDeferred]
except KeyError:
pass
else:
del self._runningQueries[lookupDeferred]
cancelCall.cancel()
if isinstance(result, Failure):
userDeferred.errback(self._fail(name, result.getErrorMessage()))
else:
userDeferred.callback(result)
def getHostByName(
self, name: str, timeout: Sequence[int] = (1, 3, 11, 45)
) -> Deferred[str]:
"""
See L{twisted.internet.interfaces.IResolverSimple.getHostByName}.
Note that the elements of C{timeout} are summed and the result is used
as a timeout for the lookup. Any intermediate timeout or retry logic
is left up to the platform via L{socket.gethostbyname}.
"""
if timeout:
timeoutDelay = sum(timeout)
else:
timeoutDelay = 60
userDeferred = defer.Deferred() # type: Deferred[str]
lookupDeferred = threads.deferToThreadPool(
self.reactor,
cast(IReactorThreads, self.reactor).getThreadPool(),
socket.gethostbyname,
name,
)
cancelCall = cast(IReactorTime, self.reactor).callLater(
timeoutDelay, self._cleanup, name, lookupDeferred
)
self._runningQueries[lookupDeferred] = (userDeferred, cancelCall)
lookupDeferred.addBoth(self._checkTimeout, name, lookupDeferred)
return userDeferred
@implementer(IResolverSimple)
class BlockingResolver:
def getHostByName(
self, name: str, timeout: Sequence[int] = (1, 3, 11, 45)
) -> Deferred[str]:
try:
address = socket.gethostbyname(name)
except OSError:
msg = f"address {name!r} not found"
err = error.DNSLookupError(msg)
return defer.fail(err)
else:
return defer.succeed(address)
_ThreePhaseEventTriggerCallable = Callable[..., Any]
_ThreePhaseEventTrigger = Tuple[
_ThreePhaseEventTriggerCallable, Tuple[object, ...], Dict[str, object]
]
_ThreePhaseEventTriggerHandle = NewType(
"_ThreePhaseEventTriggerHandle",
Tuple[str, _ThreePhaseEventTriggerCallable, Tuple[object, ...], Dict[str, object]],
)
class _ThreePhaseEvent:
"""
Collection of callables (with arguments) which can be invoked as a group in
a particular order.
This provides the underlying implementation for the reactor's system event
triggers. An instance of this class tracks triggers for all phases of a
single type of event.
@ivar before: A list of the before-phase triggers containing three-tuples
of a callable, a tuple of positional arguments, and a dict of keyword
arguments
@ivar finishedBefore: A list of the before-phase triggers which have
already been executed. This is only populated in the C{'BEFORE'} state.
@ivar during: A list of the during-phase triggers containing three-tuples
of a callable, a tuple of positional arguments, and a dict of keyword
arguments
@ivar after: A list of the after-phase triggers containing three-tuples
of a callable, a tuple of positional arguments, and a dict of keyword
arguments
@ivar state: A string indicating what is currently going on with this
object. One of C{'BASE'} (for when nothing in particular is happening;
this is the initial value), C{'BEFORE'} (when the before-phase triggers
are in the process of being executed).
"""
def __init__(self) -> None:
self.before: List[_ThreePhaseEventTrigger] = []
self.during: List[_ThreePhaseEventTrigger] = []
self.after: List[_ThreePhaseEventTrigger] = []
self.state = "BASE"
def addTrigger(
self,
phase: str,
callable: _ThreePhaseEventTriggerCallable,
*args: object,
**kwargs: object,
) -> _ThreePhaseEventTriggerHandle:
"""
Add a trigger to the indicate phase.
@param phase: One of C{'before'}, C{'during'}, or C{'after'}.
@param callable: An object to be called when this event is triggered.
@param args: Positional arguments to pass to C{callable}.
@param kwargs: Keyword arguments to pass to C{callable}.
@return: An opaque handle which may be passed to L{removeTrigger} to
reverse the effects of calling this method.
"""
if phase not in ("before", "during", "after"):
raise KeyError("invalid phase")
getattr(self, phase).append((callable, args, kwargs))
return _ThreePhaseEventTriggerHandle((phase, callable, args, kwargs))
def removeTrigger(self, handle: _ThreePhaseEventTriggerHandle) -> None:
"""
Remove a previously added trigger callable.
@param handle: An object previously returned by L{addTrigger}. The
trigger added by that call will be removed.
@raise ValueError: If the trigger associated with C{handle} has already
been removed or if C{handle} is not a valid handle.
"""
getattr(self, "removeTrigger_" + self.state)(handle)
def removeTrigger_BASE(self, handle: _ThreePhaseEventTriggerHandle) -> None:
"""
Just try to remove the trigger.
@see: removeTrigger
"""
try:
phase, callable, args, kwargs = handle
except (TypeError, ValueError):
raise ValueError("invalid trigger handle")
else:
if phase not in ("before", "during", "after"):
raise KeyError("invalid phase")
getattr(self, phase).remove((callable, args, kwargs))
def removeTrigger_BEFORE(self, handle: _ThreePhaseEventTriggerHandle) -> None:
"""
Remove the trigger if it has yet to be executed, otherwise emit a
warning that in the future an exception will be raised when removing an
already-executed trigger.
@see: removeTrigger
"""
phase, callable, args, kwargs = handle
if phase != "before":
return self.removeTrigger_BASE(handle)
if (callable, args, kwargs) in self.finishedBefore:
warnings.warn(
"Removing already-fired system event triggers will raise an "
"exception in a future version of Twisted.",
category=DeprecationWarning,
stacklevel=3,
)
else:
self.removeTrigger_BASE(handle)
def fireEvent(self) -> None:
"""
Call the triggers added to this event.
"""
self.state = "BEFORE"
self.finishedBefore = []
beforeResults: List[Deferred[object]] = []
while self.before:
callable, args, kwargs = self.before.pop(0)
self.finishedBefore.append((callable, args, kwargs))
try:
result = callable(*args, **kwargs)
except BaseException:
log.err()
else:
if isinstance(result, Deferred):
beforeResults.append(result)
DeferredList(beforeResults).addCallback(self._continueFiring)
def _continueFiring(self, ignored: object) -> None:
"""
Call the during and after phase triggers for this event.
"""
self.state = "BASE"
self.finishedBefore = []
for phase in self.during, self.after:
while phase:
callable, args, kwargs = phase.pop(0)
try:
callable(*args, **kwargs)
except BaseException:
log.err()
@implementer(IReactorPluggableNameResolver, IReactorPluggableResolver)
class PluggableResolverMixin:
"""
A mixin which implements the pluggable resolver reactor interfaces.
@ivar resolver: The installed L{IResolverSimple}.
@ivar _nameResolver: The installed L{IHostnameResolver}.
"""
resolver: IResolverSimple = BlockingResolver()
_nameResolver: IHostnameResolver = _SimpleResolverComplexifier(resolver)
# IReactorPluggableResolver
def installResolver(self, resolver: IResolverSimple) -> IResolverSimple:
"""
See L{IReactorPluggableResolver}.
@param resolver: see L{IReactorPluggableResolver}.
@return: see L{IReactorPluggableResolver}.
"""
assert IResolverSimple.providedBy(resolver)
oldResolver = self.resolver
self.resolver = resolver
self._nameResolver = _SimpleResolverComplexifier(resolver)
return oldResolver
# IReactorPluggableNameResolver
def installNameResolver(self, resolver: IHostnameResolver) -> IHostnameResolver:
"""
See L{IReactorPluggableNameResolver}.
@param resolver: See L{IReactorPluggableNameResolver}.
@return: see L{IReactorPluggableNameResolver}.
"""
previousNameResolver = self._nameResolver
self._nameResolver = resolver
self.resolver = _ComplexResolverSimplifier(resolver)
return previousNameResolver
@property
def nameResolver(self) -> IHostnameResolver:
"""
Implementation of read-only
L{IReactorPluggableNameResolver.nameResolver}.
"""
return self._nameResolver
_SystemEventID = NewType("_SystemEventID", Tuple[str, _ThreePhaseEventTriggerHandle])
_ThreadCall = Tuple[Callable[..., Any], Tuple[object, ...], Dict[str, object]]
@implementer(IReactorCore, IReactorTime, _ISupportsExitSignalCapturing)
class ReactorBase(PluggableResolverMixin):
"""
Default base class for Reactors.
@ivar _stopped: A flag which is true between paired calls to C{reactor.run}
and C{reactor.stop}. This should be replaced with an explicit state
machine.
@ivar _justStopped: A flag which is true between the time C{reactor.stop}
is called and the time the shutdown system event is fired. This is
used to determine whether that event should be fired after each
iteration through the mainloop. This should be replaced with an
explicit state machine.
@ivar _started: A flag which is true from the time C{reactor.run} is called
until the time C{reactor.run} returns. This is used to prevent calls
to C{reactor.run} on a running reactor. This should be replaced with
an explicit state machine.
@ivar running: See L{IReactorCore.running}
@ivar _registerAsIOThread: A flag controlling whether the reactor will
register the thread it is running in as the I/O thread when it starts.
If C{True}, registration will be done, otherwise it will not be.
@ivar _exitSignal: See L{_ISupportsExitSignalCapturing._exitSignal}
"""
_registerAsIOThread = True
_stopped = True
installed = False
usingThreads = False
_exitSignal = None
__name__ = "twisted.internet.reactor"
def __init__(self) -> None:
super().__init__()
self.threadCallQueue: List[_ThreadCall] = []
self._eventTriggers: Dict[str, _ThreePhaseEvent] = {}
self._pendingTimedCalls: List[DelayedCall] = []
self._newTimedCalls: List[DelayedCall] = []
self._cancellations = 0
self.running = False
self._started = False
self._justStopped = False
self._startedBefore = False
# reactor internal readers, e.g. the waker.
# Using Any as the type here… unable to find a suitable defined interface
self._internalReaders: Set[Any] = set()
self.waker: Any = None
# Arrange for the running attribute to change to True at the right time
# and let a subclass possibly do other things at that time (eg install
# signal handlers).
self.addSystemEventTrigger("during", "startup", self._reallyStartRunning)
self.addSystemEventTrigger("during", "shutdown", self.crash)
self.addSystemEventTrigger("during", "shutdown", self.disconnectAll)
if platform.supportsThreads():
self._initThreads()
self.installWaker()
# override in subclasses
_lock = None
def installWaker(self) -> None:
raise NotImplementedError(
reflect.qual(self.__class__) + " did not implement installWaker"
)
def wakeUp(self) -> None:
"""
Wake up the event loop.
"""
if self.waker:
self.waker.wakeUp()
# if the waker isn't installed, the reactor isn't running, and
# therefore doesn't need to be woken up
def doIteration(self, delay: Optional[float]) -> None:
"""
Do one iteration over the readers and writers which have been added.
"""
raise NotImplementedError(
reflect.qual(self.__class__) + " did not implement doIteration"
)
def addReader(self, reader: IReadDescriptor) -> None:
raise NotImplementedError(
reflect.qual(self.__class__) + " did not implement addReader"
)
def addWriter(self, writer: IWriteDescriptor) -> None:
raise NotImplementedError(
reflect.qual(self.__class__) + " did not implement addWriter"
)
def removeReader(self, reader: IReadDescriptor) -> None:
raise NotImplementedError(
reflect.qual(self.__class__) + " did not implement removeReader"
)
def removeWriter(self, writer: IWriteDescriptor) -> None:
raise NotImplementedError(
reflect.qual(self.__class__) + " did not implement removeWriter"
)
def removeAll(self) -> List[Union[IReadDescriptor, IWriteDescriptor]]:
raise NotImplementedError(
reflect.qual(self.__class__) + " did not implement removeAll"
)
def getReaders(self) -> List[IReadDescriptor]:
raise NotImplementedError(
reflect.qual(self.__class__) + " did not implement getReaders"
)
def getWriters(self) -> List[IWriteDescriptor]:
raise NotImplementedError(
reflect.qual(self.__class__) + " did not implement getWriters"
)
# IReactorCore
def resolve(
self, name: str, timeout: Sequence[int] = (1, 3, 11, 45)
) -> Deferred[str]:
"""
Return a Deferred that will resolve a hostname."""
if not name:
# XXX - This is *less than* '::', and will screw up IPv6 servers
return defer.succeed("0.0.0.0")
if abstract.isIPAddress(name):
return defer.succeed(name)
return self.resolver.getHostByName(name, timeout)
def stop(self) -> None:
"""
See twisted.internet.interfaces.IReactorCore.stop.
"""
if self._stopped:
raise error.ReactorNotRunning("Can't stop reactor that isn't running.")
self._stopped = True
self._justStopped = True
self._startedBefore = True
def crash(self) -> None:
"""
See twisted.internet.interfaces.IReactorCore.crash.
Reset reactor state tracking attributes and re-initialize certain
state-transition helpers which were set up in C{__init__} but later
destroyed (through use).
"""
self._started = False
self.running = False
self.addSystemEventTrigger("during", "startup", self._reallyStartRunning)
def sigInt(self, number: int, frame: Optional[FrameType] = None) -> None:
"""
Handle a SIGINT interrupt.
@param number: See handler specification in L{signal.signal}
@param frame: See handler specification in L{signal.signal}
"""
log.msg("Received SIGINT, shutting down.")
self.callFromThread(self.stop)
self._exitSignal = number
def sigBreak(self, number: int, frame: Optional[FrameType] = None) -> None:
"""
Handle a SIGBREAK interrupt.
@param number: See handler specification in L{signal.signal}
@param frame: See handler specification in L{signal.signal}
"""
log.msg("Received SIGBREAK, shutting down.")
self.callFromThread(self.stop)
self._exitSignal = number
def sigTerm(self, number: int, frame: Optional[FrameType] = None) -> None:
"""
Handle a SIGTERM interrupt.
@param number: See handler specification in L{signal.signal}
@param frame: See handler specification in L{signal.signal}
"""
log.msg("Received SIGTERM, shutting down.")
self.callFromThread(self.stop)
self._exitSignal = number
def disconnectAll(self) -> None:
"""Disconnect every reader, and writer in the system."""
selectables = self.removeAll()
for reader in selectables:
log.callWithLogger(
reader, reader.connectionLost, Failure(main.CONNECTION_LOST)
)
def iterate(self, delay: float = 0.0) -> None:
"""
See twisted.internet.interfaces.IReactorCore.iterate.
"""
self.runUntilCurrent()
self.doIteration(delay)
def fireSystemEvent(self, eventType: str) -> None:
"""
See twisted.internet.interfaces.IReactorCore.fireSystemEvent.
"""
event = self._eventTriggers.get(eventType)
if event is not None:
event.fireEvent()
def addSystemEventTrigger(
self,
phase: str,
eventType: str,
callable: Callable[..., Any],
*args: object,
**kwargs: object,
) -> _SystemEventID:
"""
See twisted.internet.interfaces.IReactorCore.addSystemEventTrigger.
"""
assert builtins.callable(callable), f"{callable} is not callable"
if eventType not in self._eventTriggers:
self._eventTriggers[eventType] = _ThreePhaseEvent()
return _SystemEventID(
(
eventType,
self._eventTriggers[eventType].addTrigger(
phase, callable, *args, **kwargs
),
)
)
def removeSystemEventTrigger(self, triggerID: _SystemEventID) -> None:
"""
See twisted.internet.interfaces.IReactorCore.removeSystemEventTrigger.
"""
eventType, handle = triggerID
self._eventTriggers[eventType].removeTrigger(handle)
def callWhenRunning(
self, callable: Callable[..., Any], *args: object, **kwargs: object
) -> Optional[_SystemEventID]:
"""
See twisted.internet.interfaces.IReactorCore.callWhenRunning.
"""
if self.running:
callable(*args, **kwargs)
return None
else:
return self.addSystemEventTrigger(
"after", "startup", callable, *args, **kwargs
)
def startRunning(self) -> None:
"""
Method called when reactor starts: do some initialization and fire
startup events.
Don't call this directly, call reactor.run() instead: it should take
care of calling this.
This method is somewhat misnamed. The reactor will not necessarily be
in the running state by the time this method returns. The only
guarantee is that it will be on its way to the running state.
"""
if self._started:
raise error.ReactorAlreadyRunning()
if self._startedBefore:
raise error.ReactorNotRestartable()
self._started = True
self._stopped = False
if self._registerAsIOThread:
threadable.registerAsIOThread()
self.fireSystemEvent("startup")
def _reallyStartRunning(self) -> None:
"""
Method called to transition to the running state. This should happen
in the I{during startup} event trigger phase.
"""
self.running = True
def run(self) -> None:
# IReactorCore.run
raise NotImplementedError()
# IReactorTime
seconds = staticmethod(runtimeSeconds)
def callLater(
self, delay: float, callable: Callable[..., Any], *args: object, **kw: object
) -> DelayedCall:
"""
See twisted.internet.interfaces.IReactorTime.callLater.
"""
assert builtins.callable(callable), f"{callable} is not callable"
assert delay >= 0, f"{delay} is not greater than or equal to 0 seconds"
delayedCall = DelayedCall(
self.seconds() + delay,
callable,
args,
kw,
self._cancelCallLater,
self._moveCallLaterSooner,
seconds=self.seconds,
)
self._newTimedCalls.append(delayedCall)
return delayedCall
def _moveCallLaterSooner(self, delayedCall: DelayedCall) -> None:
# Linear time find: slow.
heap = self._pendingTimedCalls
try:
pos = heap.index(delayedCall)
# Move elt up the heap until it rests at the right place.
elt = heap[pos]
while pos != 0:
parent = (pos - 1) // 2
if heap[parent] <= elt:
break
# move parent down
heap[pos] = heap[parent]
pos = parent
heap[pos] = elt
except ValueError:
# element was not found in heap - oh well...
pass
def _cancelCallLater(self, delayedCall: DelayedCall) -> None:
self._cancellations += 1
def getDelayedCalls(self) -> List[IDelayedCall]:
"""
Return all the outstanding delayed calls in the system.
They are returned in no particular order.
This method is not efficient -- it is really only meant for
test cases.
@return: A list of outstanding delayed calls.
"""
return [
x
for x in (self._pendingTimedCalls + self._newTimedCalls)
if not x.cancelled
]
def _insertNewDelayedCalls(self) -> None:
for call in self._newTimedCalls:
if call.cancelled:
self._cancellations -= 1
else:
call.activate_delay()
heappush(self._pendingTimedCalls, call)
self._newTimedCalls = []
def timeout(self) -> Optional[float]:
"""
Determine the longest time the reactor may sleep (waiting on I/O
notification, perhaps) before it must wake up to service a time-related
event.
@return: The maximum number of seconds the reactor may sleep.
"""
# insert new delayed calls to make sure to include them in timeout value
self._insertNewDelayedCalls()
if not self._pendingTimedCalls:
return None
delay = self._pendingTimedCalls[0].time - cast(float, self.seconds())
# Pick a somewhat arbitrary maximum possible value for the timeout.
# This value is 2 ** 31 / 1000, which is the number of seconds which can
# be represented as an integer number of milliseconds in a signed 32 bit
# integer. This particular limit is imposed by the epoll_wait(3)
# interface which accepts a timeout as a C "int" type and treats it as
# representing a number of milliseconds.
longest = 2147483
# Don't let the delay be in the past (negative) or exceed a plausible
# maximum (platform-imposed) interval.
return max(0, min(longest, delay))
def runUntilCurrent(self) -> None:
"""
Run all pending timed calls.
"""
if self.threadCallQueue:
# Keep track of how many calls we actually make, as we're
# making them, in case another call is added to the queue
# while we're in this loop.
count = 0
total = len(self.threadCallQueue)
for (f, a, kw) in self.threadCallQueue:
try:
f(*a, **kw)
except BaseException:
log.err()
count += 1
if count == total:
break
del self.threadCallQueue[:count]
if self.threadCallQueue:
self.wakeUp()
# insert new delayed calls now
self._insertNewDelayedCalls()
now = self.seconds()
while self._pendingTimedCalls and (self._pendingTimedCalls[0].time <= now):
call = heappop(self._pendingTimedCalls)
if call.cancelled:
self._cancellations -= 1
continue
if call.delayed_time > 0.0:
call.activate_delay()
heappush(self._pendingTimedCalls, call)
continue
try:
call.called = 1
call.func(*call.args, **call.kw)
except BaseException:
log.deferr()
if hasattr(call, "creator"):
e = "\n"
e += (
" C: previous exception occurred in "
+ "a DelayedCall created here:\n"
)
e += " C:"
e += "".join(call.creator).rstrip().replace("\n", "\n C:")
e += "\n"
log.msg(e)
if (
self._cancellations > 50
and self._cancellations > len(self._pendingTimedCalls) >> 1
):
self._cancellations = 0
self._pendingTimedCalls = [
x for x in self._pendingTimedCalls if not x.cancelled
]
heapify(self._pendingTimedCalls)
if self._justStopped:
self._justStopped = False
self.fireSystemEvent("shutdown")
# IReactorProcess
def _checkProcessArgs(
self, args: List[Union[bytes, str]], env: Optional[Mapping[AnyStr, AnyStr]]
) -> Union[
Tuple[List[bytes], Optional[Dict[bytes, bytes]]],
Tuple[List[Union[bytes, str]], Optional[Mapping[AnyStr, AnyStr]]],
]:
"""
Check for valid arguments and environment to spawnProcess.
@return: A two element tuple giving values to use when creating the
process. The first element of the tuple is a C{list} of C{bytes}
giving the values for argv of the child process. The second element
of the tuple is either L{None} if C{env} was L{None} or a C{dict}
mapping C{bytes} environment keys to C{bytes} environment values.
"""
# Any unicode string which Python would successfully implicitly
# encode to a byte string would have worked before these explicit
# checks were added. Anything which would have failed with a
# UnicodeEncodeError during that implicit encoding step would have
# raised an exception in the child process and that would have been
# a pain in the butt to debug.
#
# So, we will explicitly attempt the same encoding which Python
# would implicitly do later. If it fails, we will report an error
# without ever spawning a child process. If it succeeds, we'll save
# the result so that Python doesn't need to do it implicitly later.
#
# -exarkun
# If any of the following environment variables:
# - PYTHONUTF8
# - PYTHONIOENCODING
#
# are set before the Python interpreter runs, they will affect the
# value of sys.stdout.encoding.
# In certain cases, such as a Windows GUI Application which has no
# console, sys.stdout is None. In this case,
# just return the args and env unmodified.
if not sys.stdout:
return args, env
# If a client application patches sys.stdout so that encoding is not
# set properly, try to fall back to sys.__stdout__.encoding.
defaultEncoding = sys.stdout.encoding or sys.__stdout__.encoding
if not defaultEncoding:
raise ValueError("sys.stdout does not have a valid encoding")
# Common check function
def argChecker(arg: Union[bytes, str]) -> Optional[bytes]:
"""
Return either L{bytes} or L{None}. If the given value is not
allowable for some reason, L{None} is returned. Otherwise, a
possibly different object which should be used in place of arg is
returned. This forces unicode encoding to happen now, rather than
implicitly later.
"""
if isinstance(arg, str):
try:
arg = arg.encode(defaultEncoding)
except UnicodeEncodeError:
return None
if isinstance(arg, bytes) and b"\0" not in arg:
return arg
return None
# Make a few tests to check input validity
if not isinstance(args, (tuple, list)):
raise TypeError("Arguments must be a tuple or list")
outputArgs = []
for arg in args:
_arg = argChecker(arg)
if _arg is None:
raise TypeError(f"Arguments contain a non-string value: {arg!r}")
else:
outputArgs.append(_arg)
outputEnv = None
if env is not None:
outputEnv = {}
for key, val in env.items():
_key = argChecker(key)
if _key is None:
raise TypeError(
"Environment contains a "
"non-string key: {!r}, using encoding: {}".format(
key, sys.stdout.encoding
)
)
_val = argChecker(val)
if _val is None:
raise TypeError(
"Environment contains a "
"non-string value: {!r}, using encoding {}".format(
val, sys.stdout.encoding
)
)
outputEnv[_key] = _val
return outputArgs, outputEnv
# IReactorThreads
if platform.supportsThreads():
assert ThreadPool is not None
threadpool = None
# ID of the trigger starting the threadpool
_threadpoolStartupID = None
# ID of the trigger stopping the threadpool
threadpoolShutdownID = None
def _initThreads(self) -> None:
self.installNameResolver(_GAIResolver(self, self.getThreadPool))
self.usingThreads = True
def callFromThread(
self, f: Callable[..., Any], *args: object, **kwargs: object
) -> None:
"""
See
L{twisted.internet.interfaces.IReactorFromThreads.callFromThread}.
"""
assert callable(f), f"{f} is not callable"
# lists are thread-safe in CPython, but not in Jython
# this is probably a bug in Jython, but until fixed this code
# won't work in Jython.
self.threadCallQueue.append((f, args, kwargs))
self.wakeUp()
def _initThreadPool(self) -> None:
"""
Create the threadpool accessible with callFromThread.
"""
self.threadpool = ThreadPool(0, 10, "twisted.internet.reactor")
self._threadpoolStartupID = self.callWhenRunning(self.threadpool.start)
self.threadpoolShutdownID = self.addSystemEventTrigger(
"during", "shutdown", self._stopThreadPool
)
def _uninstallHandler(self) -> None:
pass
def _stopThreadPool(self) -> None:
"""
Stop the reactor threadpool. This method is only valid if there
is currently a threadpool (created by L{_initThreadPool}). It
is not intended to be called directly; instead, it will be
called by a shutdown trigger created in L{_initThreadPool}.
"""
triggers = [self._threadpoolStartupID, self.threadpoolShutdownID]
for trigger in filter(None, triggers):
try:
self.removeSystemEventTrigger(trigger)
except ValueError:
pass
self._threadpoolStartupID = None
self.threadpoolShutdownID = None
assert self.threadpool is not None
self.threadpool.stop()
self.threadpool = None
def getThreadPool(self) -> ThreadPool:
"""
See L{twisted.internet.interfaces.IReactorThreads.getThreadPool}.
"""
if self.threadpool is None:
self._initThreadPool()
assert self.threadpool is not None
return self.threadpool
def callInThread(
self, _callable: Callable[..., Any], *args: object, **kwargs: object
) -> None:
"""
See L{twisted.internet.interfaces.IReactorInThreads.callInThread}.
"""
self.getThreadPool().callInThread(_callable, *args, **kwargs)
def suggestThreadPoolSize(self, size: int) -> None:
"""
See L{twisted.internet.interfaces.IReactorThreads.suggestThreadPoolSize}.
"""
self.getThreadPool().adjustPoolsize(maxthreads=size)
else:
# This is for signal handlers.
def callFromThread(
self, f: Callable[..., Any], *args: object, **kwargs: object
) -> None:
assert callable(f), f"{f} is not callable"
# See comment in the other callFromThread implementation.
self.threadCallQueue.append((f, args, kwargs))
if platform.supportsThreads():
classImplements(ReactorBase, IReactorThreads)
@implementer(IConnector)
class BaseConnector(ABC):
"""
Basic implementation of L{IConnector}.
State can be: "connecting", "connected", "disconnected"
"""
timeoutID = None
factoryStarted = 0
def __init__(
self, factory: ClientFactory, timeout: float, reactor: ReactorBase
) -> None:
self.state = "disconnected"
self.reactor = reactor
self.factory = factory
self.timeout = timeout
def disconnect(self) -> None:
"""Disconnect whatever our state is."""
if self.state == "connecting":
self.stopConnecting()
elif self.state == "connected":
assert self.transport is not None
self.transport.loseConnection()
@abstractmethod
def _makeTransport(self) -> "Client":
pass
def connect(self) -> None:
"""Start connection to remote server."""
if self.state != "disconnected":
raise RuntimeError("can't connect in this state")
self.state = "connecting"
if not self.factoryStarted:
self.factory.doStart()
self.factoryStarted = 1
self.transport: Optional[Client] = self._makeTransport()
if self.timeout is not None:
self.timeoutID = self.reactor.callLater(
self.timeout, self.transport.failIfNotConnected, error.TimeoutError()
)
self.factory.startedConnecting(self)
def stopConnecting(self) -> None:
"""Stop attempting to connect."""
if self.state != "connecting":
raise error.NotConnectingError("we're not trying to connect")
assert self.transport is not None
self.state = "disconnected"
self.transport.failIfNotConnected(error.UserError())
del self.transport
def cancelTimeout(self) -> None:
if self.timeoutID is not None:
try:
self.timeoutID.cancel()
except ValueError:
pass
del self.timeoutID
def buildProtocol(self, addr: Tuple[str, int]) -> IProtocol:
self.state = "connected"
self.cancelTimeout()
return self.factory.buildProtocol(addr)
def connectionFailed(self, reason: Failure) -> None:
self.cancelTimeout()
self.transport = None
self.state = "disconnected"
self.factory.clientConnectionFailed(self, reason)
if self.state == "disconnected":
# factory hasn't called our connect() method
self.factory.doStop()
self.factoryStarted = 0
def connectionLost(self, reason: Failure) -> None:
self.state = "disconnected"
self.factory.clientConnectionLost(self, reason)
if self.state == "disconnected":
# factory hasn't called our connect() method
self.factory.doStop()
self.factoryStarted = 0
def getDestination(self) -> IAddress:
raise NotImplementedError(
reflect.qual(self.__class__) + " did not implement " "getDestination"
)
def __repr__(self) -> str:
return "<{} instance at 0x{:x} {} {}>".format(
reflect.qual(self.__class__),
id(self),
self.state,
self.getDestination(),
)
class BasePort(abstract.FileDescriptor):
"""Basic implementation of a ListeningPort.
Note: This does not actually implement IListeningPort.
"""
addressFamily: socket.AddressFamily = None # type: ignore[assignment]
socketType: socket.SocketKind = None # type: ignore[assignment]
def createInternetSocket(self) -> socket.socket:
s = socket.socket(self.addressFamily, self.socketType)
s.setblocking(False)
fdesc._setCloseOnExec(s.fileno())
return s
def doWrite(self) -> Optional[Failure]:
"""Raises a RuntimeError"""
raise RuntimeError("doWrite called on a %s" % reflect.qual(self.__class__))
class _SignalReactorMixin:
"""
Private mixin to manage signals: it installs signal handlers at start time,
and define run method.
It can only be used mixed in with L{ReactorBase}, and has to be defined
first in the inheritance (so that method resolution order finds
startRunning first).
@ivar _installSignalHandlers: A flag which indicates whether any signal
handlers will be installed during startup. This includes handlers for
SIGCHLD to monitor child processes, and SIGINT, SIGTERM, and SIGBREAK
to stop the reactor.
"""
_installSignalHandlers = False
def _handleSignals(self) -> None:
"""
Install the signal handlers for the Twisted event loop.
"""
try:
import signal
except ImportError:
log.msg(
"Warning: signal module unavailable -- "
"not installing signal handlers."
)
return
reactorBaseSelf = cast(ReactorBase, self)
if signal.getsignal(signal.SIGINT) == signal.default_int_handler:
# only handle if there isn't already a handler, e.g. for Pdb.
signal.signal(signal.SIGINT, reactorBaseSelf.sigInt)
signal.signal(signal.SIGTERM, reactorBaseSelf.sigTerm)
# Catch Ctrl-Break in windows
SIGBREAK = getattr(signal, "SIGBREAK", None)
if SIGBREAK is not None:
signal.signal(SIGBREAK, reactorBaseSelf.sigBreak)
def startRunning(self, installSignalHandlers: bool = True) -> None:
"""
Extend the base implementation in order to remember whether signal
handlers should be installed later.
@param installSignalHandlers: A flag which, if set, indicates that
handlers for a number of (implementation-defined) signals should be
installed during startup.
"""
self._installSignalHandlers = installSignalHandlers
ReactorBase.startRunning(cast(ReactorBase, self))
def _reallyStartRunning(self) -> None:
"""
Extend the base implementation by also installing signal handlers, if
C{self._installSignalHandlers} is true.
"""
ReactorBase._reallyStartRunning(cast(ReactorBase, self))
if self._installSignalHandlers:
# Make sure this happens before after-startup events, since the
# expectation of after-startup is that the reactor is fully
# initialized. Don't do it right away for historical reasons
# (perhaps some before-startup triggers don't want there to be a
# custom SIGCHLD handler so that they can run child processes with
# some blocking api).
self._handleSignals()
def run(self, installSignalHandlers: bool = True) -> None:
self.startRunning(installSignalHandlers=installSignalHandlers)
self.mainLoop()
def mainLoop(self) -> None:
reactorBaseSelf = cast(ReactorBase, self)
while reactorBaseSelf._started:
try:
while reactorBaseSelf._started:
# Advance simulation time in delayed event
# processors.
reactorBaseSelf.runUntilCurrent()
t2 = reactorBaseSelf.timeout()
t = reactorBaseSelf.running and t2
reactorBaseSelf.doIteration(t)
except BaseException:
log.msg("Unexpected error in main loop.")
log.err()
else:
log.msg("Main loop terminated.")
__all__: List[str] = []
| 35.716263
| 97
| 0.605464
|
0cdc16ae9a1af59912e9c98eb3671e10e3c5d211
| 9,975
|
py
|
Python
|
contrib/spendfrom/spendfrom.py
|
aitracoinofficial/AITRA
|
b047e796c2352a30a12139ef562f29efd4db7578
|
[
"MIT"
] | 4
|
2020-12-11T15:34:15.000Z
|
2021-11-26T14:51:33.000Z
|
contrib/spendfrom/spendfrom.py
|
aitracoinofficial/AITRA
|
b047e796c2352a30a12139ef562f29efd4db7578
|
[
"MIT"
] | null | null | null |
contrib/spendfrom/spendfrom.py
|
aitracoinofficial/AITRA
|
b047e796c2352a30a12139ef562f29efd4db7578
|
[
"MIT"
] | 1
|
2020-10-28T18:10:38.000Z
|
2020-10-28T18:10:38.000Z
|
#!/usr/bin/env python
#
# Use the raw transactions API to spend AITRAs received on particular addresses,
# and send any change back to that same address.
#
# Example usage:
# spendfrom.py # Lists available funds
# spendfrom.py --from=ADDRESS --to=ADDRESS --amount=11.00
#
# Assumes it will talk to a aitrad or aitra-Qt running
# on localhost.
#
# Depends on jsonrpc
#
from decimal import *
import getpass
import math
import os
import os.path
import platform
import sys
import time
from jsonrpc import ServiceProxy, json
BASE_FEE=Decimal("0.001")
def check_json_precision():
"""Make sure json library being used does not lose precision converting BTC values"""
n = Decimal("20000000.00000003")
satoshis = int(json.loads(json.dumps(float(n)))*1.0e8)
if satoshis != 2000000000000003:
raise RuntimeError("JSON encode/decode loses precision")
def determine_db_dir():
"""Return the default location of the aitra data directory"""
if platform.system() == "Darwin":
return os.path.expanduser("~/Library/Application Support/AITRA_Coin/")
elif platform.system() == "Windows":
return os.path.join(os.environ['APPDATA'], "AITRA_Coin")
return os.path.expanduser("~/.aitra")
def read_bitcoin_config(dbdir):
"""Read the aitra.conf file from dbdir, returns dictionary of settings"""
from ConfigParser import SafeConfigParser
class FakeSecHead(object):
def __init__(self, fp):
self.fp = fp
self.sechead = '[all]\n'
def readline(self):
if self.sechead:
try: return self.sechead
finally: self.sechead = None
else:
s = self.fp.readline()
if s.find('#') != -1:
s = s[0:s.find('#')].strip() +"\n"
return s
config_parser = SafeConfigParser()
config_parser.readfp(FakeSecHead(open(os.path.join(dbdir, "aitra.conf"))))
return dict(config_parser.items("all"))
def connect_JSON(config):
"""Connect to a aitra JSON-RPC server"""
testnet = config.get('testnet', '0')
testnet = (int(testnet) > 0) # 0/1 in config file, convert to True/False
if not 'rpcport' in config:
config['rpcport'] = 51475 if testnet else 2608
connect = "http://%s:%s@127.0.0.1:%s"%(config['rpcuser'], config['rpcpassword'], config['rpcport'])
try:
result = ServiceProxy(connect)
# ServiceProxy is lazy-connect, so send an RPC command mostly to catch connection errors,
# but also make sure the aitrad we're talking to is/isn't testnet:
if result.getmininginfo()['testnet'] != testnet:
sys.stderr.write("RPC server at "+connect+" testnet setting mismatch\n")
sys.exit(1)
return result
except:
sys.stderr.write("Error connecting to RPC server at "+connect+"\n")
sys.exit(1)
def unlock_wallet(aitrad):
info = aitrad.getinfo()
if 'unlocked_until' not in info:
return True # wallet is not encrypted
t = int(info['unlocked_until'])
if t <= time.time():
try:
passphrase = getpass.getpass("Wallet is locked; enter passphrase: ")
aitrad.walletpassphrase(passphrase, 5)
except:
sys.stderr.write("Wrong passphrase\n")
info = aitrad.getinfo()
return int(info['unlocked_until']) > time.time()
def list_available(aitrad):
address_summary = dict()
address_to_account = dict()
for info in aitrad.listreceivedbyaddress(0):
address_to_account[info["address"]] = info["account"]
unspent = aitrad.listunspent(0)
for output in unspent:
# listunspent doesn't give addresses, so:
rawtx = aitrad.getrawtransaction(output['txid'], 1)
vout = rawtx["vout"][output['vout']]
pk = vout["scriptPubKey"]
# This code only deals with ordinary pay-to-aitra-address
# or pay-to-script-hash outputs right now; anything exotic is ignored.
if pk["type"] != "pubkeyhash" and pk["type"] != "scripthash":
continue
address = pk["addresses"][0]
if address in address_summary:
address_summary[address]["total"] += vout["value"]
address_summary[address]["outputs"].append(output)
else:
address_summary[address] = {
"total" : vout["value"],
"outputs" : [output],
"account" : address_to_account.get(address, "")
}
return address_summary
def select_coins(needed, inputs):
# Feel free to improve this, this is good enough for my simple needs:
outputs = []
have = Decimal("0.0")
n = 0
while have < needed and n < len(inputs):
outputs.append({ "txid":inputs[n]["txid"], "vout":inputs[n]["vout"]})
have += inputs[n]["amount"]
n += 1
return (outputs, have-needed)
def create_tx(aitrad, fromaddresses, toaddress, amount, fee):
all_coins = list_available(aitrad)
total_available = Decimal("0.0")
needed = amount+fee
potential_inputs = []
for addr in fromaddresses:
if addr not in all_coins:
continue
potential_inputs.extend(all_coins[addr]["outputs"])
total_available += all_coins[addr]["total"]
if total_available < needed:
sys.stderr.write("Error, only %f BTC available, need %f\n"%(total_available, needed));
sys.exit(1)
#
# Note:
# Python's json/jsonrpc modules have inconsistent support for Decimal numbers.
# Instead of wrestling with getting json.dumps() (used by jsonrpc) to encode
# Decimals, I'm casting amounts to float before sending them to aitrad.
#
outputs = { toaddress : float(amount) }
(inputs, change_amount) = select_coins(needed, potential_inputs)
if change_amount > BASE_FEE: # don't bother with zero or tiny change
change_address = fromaddresses[-1]
if change_address in outputs:
outputs[change_address] += float(change_amount)
else:
outputs[change_address] = float(change_amount)
rawtx = aitrad.createrawtransaction(inputs, outputs)
signed_rawtx = aitrad.signrawtransaction(rawtx)
if not signed_rawtx["complete"]:
sys.stderr.write("signrawtransaction failed\n")
sys.exit(1)
txdata = signed_rawtx["hex"]
return txdata
def compute_amount_in(aitrad, txinfo):
result = Decimal("0.0")
for vin in txinfo['vin']:
in_info = aitrad.getrawtransaction(vin['txid'], 1)
vout = in_info['vout'][vin['vout']]
result = result + vout['value']
return result
def compute_amount_out(txinfo):
result = Decimal("0.0")
for vout in txinfo['vout']:
result = result + vout['value']
return result
def sanity_test_fee(aitrad, txdata_hex, max_fee):
class FeeError(RuntimeError):
pass
try:
txinfo = aitrad.decoderawtransaction(txdata_hex)
total_in = compute_amount_in(aitrad, txinfo)
total_out = compute_amount_out(txinfo)
if total_in-total_out > max_fee:
raise FeeError("Rejecting transaction, unreasonable fee of "+str(total_in-total_out))
tx_size = len(txdata_hex)/2
kb = tx_size/1000 # integer division rounds down
if kb > 1 and fee < BASE_FEE:
raise FeeError("Rejecting no-fee transaction, larger than 1000 bytes")
if total_in < 0.01 and fee < BASE_FEE:
raise FeeError("Rejecting no-fee, tiny-amount transaction")
# Exercise for the reader: compute transaction priority, and
# warn if this is a very-low-priority transaction
except FeeError as err:
sys.stderr.write((str(err)+"\n"))
sys.exit(1)
def main():
import optparse
parser = optparse.OptionParser(usage="%prog [options]")
parser.add_option("--from", dest="fromaddresses", default=None,
help="addresses to get AITRAs from")
parser.add_option("--to", dest="to", default=None,
help="address to get send AITRAs to")
parser.add_option("--amount", dest="amount", default=None,
help="amount to send")
parser.add_option("--fee", dest="fee", default="0.0",
help="fee to include")
parser.add_option("--datadir", dest="datadir", default=determine_db_dir(),
help="location of aitra.conf file with RPC username/password (default: %default)")
parser.add_option("--testnet", dest="testnet", default=False, action="store_true",
help="Use the test network")
parser.add_option("--dry_run", dest="dry_run", default=False, action="store_true",
help="Don't broadcast the transaction, just create and print the transaction data")
(options, args) = parser.parse_args()
check_json_precision()
config = read_bitcoin_config(options.datadir)
if options.testnet: config['testnet'] = True
aitrad = connect_JSON(config)
if options.amount is None:
address_summary = list_available(aitrad)
for address,info in address_summary.iteritems():
n_transactions = len(info['outputs'])
if n_transactions > 1:
print("%s %.8f %s (%d transactions)"%(address, info['total'], info['account'], n_transactions))
else:
print("%s %.8f %s"%(address, info['total'], info['account']))
else:
fee = Decimal(options.fee)
amount = Decimal(options.amount)
while unlock_wallet(aitrad) == False:
pass # Keep asking for passphrase until they get it right
txdata = create_tx(aitrad, options.fromaddresses.split(","), options.to, amount, fee)
sanity_test_fee(aitrad, txdata, amount*Decimal("0.01"))
if options.dry_run:
print(txdata)
else:
txid = aitrad.sendrawtransaction(txdata)
print(txid)
if __name__ == '__main__':
main()
| 37.220149
| 111
| 0.630376
|
73430249b4ea605eeeab111db3cde0be50989f44
| 600
|
py
|
Python
|
nicos_virt_mlz/treff/setups/special/daemon.py
|
jkrueger1/nicos
|
5f4ce66c312dedd78995f9d91e8a6e3c891b262b
|
[
"CC-BY-3.0",
"Apache-2.0",
"CC-BY-4.0"
] | 12
|
2019-11-06T15:40:36.000Z
|
2022-01-01T16:23:00.000Z
|
nicos_virt_mlz/treff/setups/special/daemon.py
|
jkrueger1/nicos
|
5f4ce66c312dedd78995f9d91e8a6e3c891b262b
|
[
"CC-BY-3.0",
"Apache-2.0",
"CC-BY-4.0"
] | 91
|
2020-08-18T09:20:26.000Z
|
2022-02-01T11:07:14.000Z
|
nicos_virt_mlz/treff/setups/special/daemon.py
|
jkrueger1/nicos
|
5f4ce66c312dedd78995f9d91e8a6e3c891b262b
|
[
"CC-BY-3.0",
"Apache-2.0",
"CC-BY-4.0"
] | 6
|
2020-01-11T10:52:30.000Z
|
2022-02-25T12:35:23.000Z
|
description = 'setup for the execution daemon'
group = 'special'
devices = dict(
Auth = device('nicos.services.daemon.auth.list.Authenticator',
# the hashing maybe 'md5' or 'sha1'
hashing = 'md5',
passwd = [('guest', '', 'guest'),
('user', 'd3bde5ce3e546626df42771c58986d4e', 'user'),
('admin', 'f3309476bdb36550aa8fb90ae748c9cc', 'admin'),
],
),
Daemon = device('nicos.services.daemon.NicosDaemon',
server = '',
authenticators = ['Auth'], # and/or 'UserDB'
loglevel = 'info',
),
)
| 31.578947
| 73
| 0.551667
|
85dbeb03e27c793bd7832cf22412dcafed8236ae
| 9,715
|
py
|
Python
|
backend/flaskr/api_upload.py
|
TavonL/Question-Bank-Management-System
|
83116e347adb31b7294e70da7ec38b5d7e2d7cc1
|
[
"MIT"
] | null | null | null |
backend/flaskr/api_upload.py
|
TavonL/Question-Bank-Management-System
|
83116e347adb31b7294e70da7ec38b5d7e2d7cc1
|
[
"MIT"
] | 2
|
2020-12-04T17:52:38.000Z
|
2022-01-15T01:29:14.000Z
|
backend/flaskr/api_upload.py
|
TavonL/Question-Bank-Management-System
|
83116e347adb31b7294e70da7ec38b5d7e2d7cc1
|
[
"MIT"
] | null | null | null |
import functools
import json
import os
import re
from flask import (
Blueprint, g, request, session, url_for, jsonify, make_response
)
from flaskr.db import (
get_db, excute_select, excute_delete, excute_insert, excute_procedure, excute_update
)
from python_script.md2word import (
convertFile, addHeader, createMdFile, deleteFiles
)
from flaskr.uploader import Uploader
bp = Blueprint('upload', __name__, url_prefix='/api/upload', static_folder='static')
types = ['不限', '填空题', '单选题', '多选题', '应用题', '综合题']
# @bp.route('/', methods=('GET', ))
# def Hello_World():
# return jsonify(app.static_folder)
@bp.route('/Paper', methods=('POST', ))
def upload_Paper():
# 上传试卷试题 code 0成功 -1不成功
data = request.get_data()
data = json.loads(data)
# return jsonify(1)
paperForm = data["paperInfoForm"]
questionsForm = data["questionsForm"]
# 定义数据库连接
db = get_db()
# 插入试卷
sql = "INSERT INTO paper(paper_subject, grade, paper_info, source)\
VALUES ({subject},{grade},'{info}',{source})".format(
subject=paperForm["paper_subject"], grade=paperForm["paper_grade"],
info=paperForm["paper_year"]+paperForm["paper_name"],
source=paperForm["paper_source"]
)
db_res = excute_insert(db, sql)
if db_res == 'Error':
return jsonify({"code" : -1})
# 查看试卷号
sql = "SELECT paper_no FROM paper WHERE paper_subject={subject} AND grade={grade} \
AND paper_info='{info}' AND source={source}".format(
subject=paperForm["paper_subject"], grade=paperForm["paper_grade"],
info=paperForm["paper_year"]+paperForm["paper_name"],
source=paperForm["paper_source"]
)
db_res = excute_select(db, sql)
if db_res == ():
return jsonify({"code" : -1})
paper_no = db_res[0][0]
# return jsonify(paper_no)
# 插入题目
code = 0
error_result = []
for i in range(0, len(questionsForm)):
item = questionsForm[i]
if item["question_type"] != 5:
sql = "INSERT INTO question(paper_no, question_type, question_diff, \
question_content, question_answer, question_analy, know_no) \
VALUES ({paper},'{type}',{diff},'{content}','{answer}','{analy}',{know_no})".format(
paper=paper_no, type=types[item["question_type"]],
diff=item["question_diff"], content=item["question_content"],
answer=item["question_answer"], analy=item["question_analy"],
know_no=item["knowledge_point"]
)
db_res = excute_insert(db, sql)
# return jsonify(db_res)
if db_res == 'Error':
code = -1
error_result.append(i)
else:
sql = "INSERT INTO question(paper_no, question_type, question_diff, \
question_content, question_analy, know_no) \
VALUES ({paper},'{type}',{diff},'{content}','{analy}',{know_no})".format(
paper=paper_no, type=types[item["question_type"]],
diff=item["question_diff"], content=item["question_content"],
analy=item["question_analy"], know_no=item["knowledge_point"]
)
# return jsonify(sql)
db_res = excute_insert(db, sql)
# return jsonify(db_res)
if db_res == 'Error':
code = -1
error_result.append(i)
# 查看刚插入的编号
sql = "SELECT question_no FROM question WHERE paper_no={paper} AND \
question_type='{type}' AND question_diff={diff} AND question_content='{content}' \
AND question_analy='{analy}' AND know_no={know_no}".format(
paper=paper_no, type=types[item["question_type"]],
diff=item["question_diff"], content=item["question_content"],
analy=item["question_analy"], know_no=item["knowledge_point"]
)
db_res = excute_select(db, sql)
# return jsonify(db_res)
if db_res == ():
code = -1
else:
super_question_no = db_res[0][0]
# return jsonify(db_res[0][0])
for subitem in item["question_answer"]:
# return jsonify(subitem)
sql = "INSERT INTO little_question(little_question_type, \
little_question_content, little_question_answer, \
super_question_no) VALUES ('{type}','{content}','{answer}',\
{super_no})".format(type=types[subitem["question_type"]],
content=subitem["question_content"],
answer=subitem["question_answer"], super_no=super_question_no
)
# return jsonify(sql)
db_res = excute_insert(db, sql)
if db_res == 'Error':
code = -1
error_result.append(i)
if code == 0:
return jsonify({"code":0})
return jsonify({"code":-1, "error_result":error_result})
# @bp.route('/PaperInfo', methods=('POST', ))
# def upload_PaperInfo():
# # 上传试卷信息 code -1 有同名试卷 code -2 该年级没有该科目或者该学校不存在
# data = request.get_data()
# data = json.loads(data)
# # return jsonify(1)
# data = data["paperInfoForm"]
# # return jsonify("1")
# # 查有没有同名试卷
# db = get_db()
# sql = "SELECT * FROM paper WHERE paper_subject={subject} AND grade={grade} \
# AND paper_info='{info}' AND source={source}".format(
# subject=data["paper_subject"], grade=data["paper_grade"],
# info=data["paper_year"]+data["paper_name"],source=data["paper_source"]
# )
# db_res = excute_select(db, sql)
# if db_res != ():
# return jsonify({"code" : -1})
# # 插入,为了并发性考虑,我觉得最好创建触发器
# sql = "INSERT INTO paper(paper_subject, grade, paper_info, source)\
# VALUES ({subject},{grade},'{info}',{source})".format(
# subject=data["paper_subject"], grade=data["paper_grade"],
# info=data["paper_year"]+data["paper_name"],source=data["paper_source"]
# )
# db_res = excute_insert(db, sql)
# if db_res == 'Error':
# return jsonify({"code" : -2})
# # 查看试卷号
# sql = "SELECT paper_no FROM paper WHERE paper_subject={subject} AND grade={grade} \
# AND paper_info='{info}' AND source={source}".format(
# subject=data["paper_subject"], grade=data["paper_grade"],
# info=data["paper_year"]+data["paper_name"],source=data["paper_source"]
# )
# db_res = excute_select(db, sql)
# if db_res != ():
# db_res = db_res[0]
# return jsonify({"code" : 0, "paper_no":db_res[0]})
# return jsonify({"code" : -3})
# @bp.route('/Question', methods=('POST', ))
# def upload_Question():
# # 返回重复/错误 题号
# data = request.get_data()
# data = json.loads(data)
# # return jsonify(1)
# db = get_db()
# paper_no = data["paper_no"]
# sql = "SELECT paper_no FROM paper INNER JOIN (SELECT source FROM paper \
# WHERE paper_no = {0}) AS T1 ON paper.source = T1.source".format(paper_no)
# db_res = excute_select(db, sql)
# db_res =[list(item) for item in list(db_res)]
# paper_no = []
# for item in db_res:
# for i in item:
# paper_no.append(str(i))
# # return jsonify(paper_no)
# paper_no = ", ".join(paper_no)
# # return jsonify(paper_no)
# data = data["questionsForm"]
# db = get_db()
# for i in range(0, len(data)):
# tmp = data[i]
# # 题目查重, 最好略过url 进行查重
# sql = "SELECT * FROM question WHERE "
# return jsonify(1)
# @cross_origin()
@bp.route('/Fig', methods=('GET', 'POST', 'OPTIONS'))
def upload_Fig():
mimetype = 'application/json'
action = request.args.get('action')
result = {}
with open(os.path.join(bp.static_folder, 'ueditor', 'php',
'config.json'), encoding = 'utf-8') as fp:
try:
CONFIG = json.loads(re.sub(r'\/\*.*\*\/', '', fp.read()))
except:
CONFIG = {}
if action == 'config':
# 初始化时,返回配置文件给客户端
result = CONFIG
elif action == 'uploadimage':
fieldName = CONFIG.get('imageFieldName')
config = {
"pathFormat": CONFIG['imagePathFormat'],
# 上传保存路径,可以自定义保存路径和文件名格式
"maxSize": CONFIG['imageMaxSize'], # 上传大小限制
"allowFiles": CONFIG['imageAllowFiles']
}
if fieldName in request.files:
field = request.files[fieldName]
uploader = Uploader(field, config, bp.static_folder)
result = uploader.getFileInfo()
else:
result['state'] = '上传接口出错'
else:
result['state'] = '请求地址出错'
result = json.dumps(result)
if 'callback' in request.args:
callback = request.args.get('callback')
if re.match(r'^[\w_]+$', callback):
result = '%s(%s)' % (callback, result)
mimetype = 'application/javascript'
else:
result = json.dumps({'state': 'callback参数不合法'})
res = make_response(result)
print(res)
res.mimetype = mimetype
res.headers['Access-Control-Allow-Origin'] = '*'
res.headers['Access-Control-Allow-Headers'] = 'X-Requested-With,X_Requested_With'
return res
@bp.route('/Schools', methods=('POST', ))
def upload_Schools():
data = request.get_data()
data = json.loads(data)
code = 0
db = get_db()
# sql = "SELECT school_no FROM school WHERE school_name={super} \
# ".format(super=data["parent_name"])
# db_res = db.excute_select()
# if db_res == ():
# return jsonify({"code":-1})
# super_no = db_res[0][0]
if data["opt"] == "add":
sql = "INSERT INTO school(school_name, school_nature, super_no) VALUES \
('{name}', '{nature}', {super})".format(
name=data["school_name"], nature=data["school_nature"],
super=data["parent_no"]
)
db_res = excute_insert(db, sql)
elif data["opt"] == "del":
sql = "DELETE FROM school WHERE school_name='{name}'".format(
name=data["school_name"])
db_res = excute_delete(db, sql)
if db_res == 'Error':
code = -1
return jsonify({"code":code})
@bp.route('/KnowledgePoints', methods=('POST', ))
def upload_KnowledgePoints():
data = request.get_data()
data = json.loads(data)
code = 0
db = get_db()
# sql = "SELECT know_no FROM know WHERE know_name={super} \
# ".format(super=data["parent_name"])
# db_res = db.excute_select()
# if db_res == ():
# return jsonify({"code":-1})
# super_no = db_res[0][0]
if data["opt"] == "add":
sql = "INSERT INTO know(know_name, super_no) VALUES \
('{name}', {super})".format(
name=data["know_name"], super=data["parent_no"]
)
db_res = excute_insert(db, sql)
elif data["opt"] == "del":
sql = "DELETE FROM know WHERE know_name='{name}'".format(
name=data["know_name"])
db_res = excute_delete(db, sql)
if db_res == 'Error':
code = -1
return jsonify({"code":code})
| 32.491639
| 88
| 0.660319
|
49e942c2fe96e8d8001a933dd6f088836f593afe
| 5,645
|
py
|
Python
|
dev/local/vision/learner.py
|
vguerra/fastai_docs
|
95df902ef5cd08bcd58d5ca64bc8a6ea3f297531
|
[
"Apache-2.0"
] | null | null | null |
dev/local/vision/learner.py
|
vguerra/fastai_docs
|
95df902ef5cd08bcd58d5ca64bc8a6ea3f297531
|
[
"Apache-2.0"
] | null | null | null |
dev/local/vision/learner.py
|
vguerra/fastai_docs
|
95df902ef5cd08bcd58d5ca64bc8a6ea3f297531
|
[
"Apache-2.0"
] | null | null | null |
#AUTOGENERATED! DO NOT EDIT! File to edit: dev/22_vision_learner.ipynb (unless otherwise specified).
__all__ = ['has_pool_type', 'create_body', 'in_channels', 'num_features_model', 'create_head', 'create_cnn_model',
'model_meta', 'cnn_learner']
#Cell
from ..torch_basics import *
from ..test import *
from ..core import *
from ..layers import *
from ..data.all import *
from ..optimizer import *
from ..learner import *
from ..metrics import *
from ..callback.all import *
from .core import *
from .augment import *
from . import models
#Cell
def _is_pool_type(l): return re.search(r'Pool[123]d$', l.__class__.__name__)
#Cell
def has_pool_type(m):
"Return `True` if `m` is a pooling layer or has one in its children"
if _is_pool_type(m): return True
for l in m.children():
if has_pool_type(l): return True
return False
#Cell
def create_body(arch, pretrained=True, cut=None):
"Cut off the body of a typically pretrained `arch` as determined by `cut`"
model = arch(pretrained)
#cut = ifnone(cut, cnn_config(arch)['cut'])
if cut is None:
ll = list(enumerate(model.children()))
cut = next(i for i,o in reversed(ll) if has_pool_type(o))
if isinstance(cut, int): return nn.Sequential(*list(model.children())[:cut])
elif isinstance(cut, Callable): return cut(model)
else: raise NamedError("cut must be either integer or a function")
#Cell
def in_channels(m):
"Return the shape of the first weight layer in `m`."
for l in flatten_model(m):
if hasattr(l, 'weight'): return l.weight.shape[1]
raise Exception('No weight layer')
#Cell
def num_features_model(m):
"Return the number of output features for `m`."
sz = 32
ch_in = in_channels(m)
while True:
#Trying for a few sizes in case the model requires a big input size.
try:
with hook_output(m) as hook:
_ = m.eval()(one_param(m).new(1, ch_in, sz, sz).requires_grad_(False).uniform_(-1.,1.))
return hook.stored.shape[1]
except Exception as e:
sz *= 2
if sz > 2048: raise
#Cell
def create_head(nf, nc, lin_ftrs=None, ps=0.5, concat_pool=True, bn_final=False):
"Model head that takes `nf` features, runs through `lin_ftrs`, and out `nc` classes."
lin_ftrs = [nf, 512, nc] if lin_ftrs is None else [nf] + lin_ftrs + [nc]
ps = L(ps)
if len(ps) == 1: ps = [ps[0]/2] * (len(lin_ftrs)-2) + ps
actns = [nn.ReLU(inplace=True)] * (len(lin_ftrs)-2) + [None]
pool = AdaptiveConcatPool2d() if concat_pool else nn.AdaptiveAvgPool2d(1)
layers = [pool, Flatten()]
for ni,no,p,actn in zip(lin_ftrs[:-1], lin_ftrs[1:], ps, actns):
layers += BnDropLin(ni, no, True, p, actn)
if bn_final: layers.append(nn.BatchNorm1d(lin_ftrs[-1], momentum=0.01))
return nn.Sequential(*layers)
#Cell
def create_cnn_model(arch, nc, cut, pretrained=True, lin_ftrs=None, ps=0.5, custom_head=None,
bn_final=False, concat_pool=True):
"Create custom convnet architecture using `base_arch`"
body = create_body(arch, pretrained, cut)
if custom_head is None:
nf = num_features_model(nn.Sequential(*body.children())) * (2 if concat_pool else 1)
head = create_head(nf, nc, lin_ftrs, ps=ps, concat_pool=concat_pool, bn_final=bn_final)
else: head = custom_head
return nn.Sequential(body, head)
#Cell
def _default_split(m:nn.Module): return L(m[0], m[1]).mapped(trainable_params)
def _resnet_split(m): return L(m[0][:6], m[0][6:], m[1]).mapped(trainable_params)
def _squeezenet_split(m:nn.Module): return L(m[0][0][:5], m[0][0][5:], m[1]).mapped(trainable_params)
def _densenet_split(m:nn.Module): return L(m[0][0][:7],m[0][0][7:], m[1]).mapped(trainable_params)
def _vgg_split(m:nn.Module): return L(m[0][0][:22], m[0][0][22:], m[1]).mapped(trainable_params)
def _alexnet_split(m:nn.Module): return L(m[0][0][:6], m[0][0][6:], m[1]).mapped(trainable_params)
_default_meta = {'cut':None, 'split':_default_split}
_resnet_meta = {'cut':-2, 'split':_resnet_split }
_squeezenet_meta = {'cut':-1, 'split': _squeezenet_split}
_densenet_meta = {'cut':-1, 'split':_densenet_split}
_vgg_meta = {'cut':-2, 'split':_vgg_split}
_alexnet_meta = {'cut':-2, 'split':_alexnet_split}
#Cell
model_meta = {
models.resnet18 :{**_resnet_meta}, models.resnet34: {**_resnet_meta},
models.resnet50 :{**_resnet_meta}, models.resnet101:{**_resnet_meta},
models.resnet152:{**_resnet_meta},
models.squeezenet1_0:{**_squeezenet_meta},
models.squeezenet1_1:{**_squeezenet_meta},
models.densenet121:{**_densenet_meta}, models.densenet169:{**_densenet_meta},
models.densenet201:{**_densenet_meta}, models.densenet161:{**_densenet_meta},
models.vgg11_bn:{**_vgg_meta}, models.vgg13_bn:{**_vgg_meta}, models.vgg16_bn:{**_vgg_meta}, models.vgg19_bn:{**_vgg_meta},
models.alexnet:{**_alexnet_meta}}
#Cell
@delegates(Learner.__init__)
def cnn_learner(dbunch, arch, cut=None, pretrained=True, lin_ftrs=None, ps=0.5, custom_head=None, splitter=trainable_params, bn_final=False,
init=nn.init.kaiming_normal_, concat_pool=True, **kwargs):
"Build convnet style learner."
meta = model_meta.get(arch)
model = create_cnn_model(arch, get_c(dbunch), ifnone(cut, meta['cut']), pretrained, lin_ftrs, ps=ps, custom_head=custom_head,
bn_final=bn_final, concat_pool=concat_pool)
learn = Learner(model, dbunch, splitter=ifnone(splitter, meta['split']), **kwargs)
if pretrained: learn.freeze()
if init: apply_init(model[1], init)
return learn
| 43.423077
| 140
| 0.672099
|
4adece2bc1614bd527df674b2eb9059bd844cadb
| 1,215
|
py
|
Python
|
lib/surface/compute/sole_tenancy/node_templates/__init__.py
|
bshaffer/google-cloud-sdk
|
f587382fd112f238c0d6d5ca3dab8f52d2b5c5f9
|
[
"Apache-2.0"
] | null | null | null |
lib/surface/compute/sole_tenancy/node_templates/__init__.py
|
bshaffer/google-cloud-sdk
|
f587382fd112f238c0d6d5ca3dab8f52d2b5c5f9
|
[
"Apache-2.0"
] | null | null | null |
lib/surface/compute/sole_tenancy/node_templates/__init__.py
|
bshaffer/google-cloud-sdk
|
f587382fd112f238c0d6d5ca3dab8f52d2b5c5f9
|
[
"Apache-2.0"
] | null | null | null |
# -*- coding: utf-8 -*- #
# Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Package for the sole tenant node templates CLI commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
class SoleTenancyNodeTemplates(base.Group):
"""Read and manage Google Compute Engine sole-tenancy node templates.
Node templates are used to create the nodes in node groups. Nodes are
Compute Engine servers that are dedicated to your workload. Node templates
define either the node type or the requirements for a node in terms of
vCPU, memory, and localSSD.
"""
| 37.96875
| 76
| 0.772016
|
2704473b585c0ac0d3e41c954ce9be58dcca7cc0
| 141
|
py
|
Python
|
Exercicios/ex034.py
|
mauroalbuquerque/Python-CursoEmVideo
|
5a9fcbd878af49d7b8aa3f7d904b1f22e643edd8
|
[
"MIT"
] | null | null | null |
Exercicios/ex034.py
|
mauroalbuquerque/Python-CursoEmVideo
|
5a9fcbd878af49d7b8aa3f7d904b1f22e643edd8
|
[
"MIT"
] | null | null | null |
Exercicios/ex034.py
|
mauroalbuquerque/Python-CursoEmVideo
|
5a9fcbd878af49d7b8aa3f7d904b1f22e643edd8
|
[
"MIT"
] | null | null | null |
salario = float(input('Qual é o seu salário: R$ ').strip())
aumento = (salario * 1.10 if salario > 1250 else salario * 1.15)
print(aumento)
| 28.2
| 64
| 0.673759
|
462009eada33103417da568d9135ea499cbbbb65
| 7,548
|
py
|
Python
|
tests/test_blast/test_bioblast/test_bioblast.py
|
jvrana/pyblast
|
0f7ee7575e97470bfd05a2373d9c68247ec4ead0
|
[
"MIT"
] | null | null | null |
tests/test_blast/test_bioblast/test_bioblast.py
|
jvrana/pyblast
|
0f7ee7575e97470bfd05a2373d9c68247ec4ead0
|
[
"MIT"
] | 8
|
2017-10-19T22:02:05.000Z
|
2020-04-09T20:45:23.000Z
|
tests/test_blast/test_bioblast/test_bioblast.py
|
jvrana/pyblast
|
0f7ee7575e97470bfd05a2373d9c68247ec4ead0
|
[
"MIT"
] | null | null | null |
import json
from os.path import join
import pytest
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from pyblast import BioBlast
from pyblast.exceptions import PyBlastException
from pyblast.utils import force_unique_record_ids
from pyblast.utils import load_genbank_glob
from pyblast.utils import make_linear
def test_basic_run():
junk1 = "atgctatgctgatgctgctgtgctgatgctgatgtgtattgctgtatcgcgcgagttagc"
junk2 = "g" * 30
frag = "aaacttcccaccccataccctattaccactgccaattacctagtggtttcatttactctaaacctgtgattcctctgaattattttcatttta"
query = SeqRecord(seq=Seq(frag), annotations={"circular": False})
subject = SeqRecord(seq=Seq(junk1 + frag + junk2), annotations={"circular": False})
# print(type(query))
# print(type(subject))
blaster = BioBlast([subject], [query])
blaster.blastn()
alignments = blaster.results
print(alignments)
def test_basic_run_reverse_complement():
junk1 = "atgctatgctgatgctgctgtgctgatgctgatgtgtattgctgtatcgcgcgagttagc"
junk2 = "g" * 30
frag = "aaacttcccaccccataccctattaccactgccaattacctagtggtttcatttactctaaacctgtgattcctctgaattattttcatttta"
query = SeqRecord(
seq=Seq(frag), annotations={"circular": False}
).reverse_complement()
subject = SeqRecord(seq=Seq(junk1 + frag + junk2), annotations={"circular": False})
make_linear([query])
# print(type(query))
# print(type(subject))
blaster = BioBlast([subject], [query])
blaster.blastn()
alignments = blaster.results
for a in alignments:
print(json.dumps(a, indent=2))
assert a["subject"]["strand"] == -1
def test_run_bioblast_twice():
junk1 = "atgctatgctgatgctgctgtgctgatgctgatgtgtattgctgtatcgcgcgagttagc"
junk2 = "g" * 30
frag = "aaacttcccaccccataccctattaccactgccaattacctagtggtttcatttactctaaacctgtgattcctctgaattattttcatttta"
query = SeqRecord(seq=Seq(frag), annotations={"circular": False})
subject = SeqRecord(seq=Seq(junk1 + frag + junk2), annotations={"circular": False})
blaster = BioBlast([subject], [query])
blaster.blastn()
blaster.blastn()
alignments = blaster.results
print(alignments)
def test_perfect_match():
s = "aaacttcccaccccataccctattaccactgccaattacctagtggtttcatttactctaaacctgtgattcctctgaattattttcatttta"
r1 = SeqRecord(seq=Seq(s), annotations={"topology": "linear"})
r2 = SeqRecord(seq=Seq(s), annotations={"topology": "linear"})
blaster = BioBlast([r1], [r2])
blaster.blastn()
result = blaster.results[0]
assert result["query"]["start"] == 1
assert result["query"]["end"] == len(s)
assert result["subject"]["start"] == 1
assert result["subject"]["end"] == len(s)
# def test_valid_results(new_bio_blast):
# blast = new_bio_blast()
# blast.blastn()
# Validator.validate_blaster_results(blast)
def test_short_blastn(new_primer_blast):
blast = new_primer_blast()
blast.blastn()
assert blast.results
def test_blast_with_circular(new_circular_bio_blast):
blast = new_circular_bio_blast()
blast.blastn()
assert blast.results
def test_raises_pyblast_when_not_unique(here):
subjects = load_genbank_glob(join(here, "data/test_data/genbank/templates/*.gb"))
queries = load_genbank_glob(join(here, "data/test_data/genbank/designs/*.gb"))
print("n_queres: {}".format(len(queries)))
print("n_subjects: {}".format(len(subjects)))
with pytest.raises(PyBlastException):
BioBlast(subjects, queries)
def test_not_raise_pyblast_when_unique(here):
subjects = load_genbank_glob(join(here, "data/test_data/genbank/templates/*.gb"))
queries = load_genbank_glob(join(here, "data/test_data/genbank/designs/*.gb"))
force_unique_record_ids(subjects + queries)
print("n_queres: {}".format(len(queries)))
BioBlast(subjects, queries)
def test_multiquery_blast(here):
subjects = load_genbank_glob(
join(here, "data/test_data/genbank/templates/*.gb"), force_unique_ids=True
)
queries = load_genbank_glob(
join(here, "data/test_data/genbank/designs/*.gb"), force_unique_ids=True
)
print("n_queres: {}".format(len(queries)))
print("n_subjects: {}".format(len(subjects)))
bioblast = BioBlast(subjects, queries)
results = bioblast.blastn()
recids = set()
for res in results:
recid = res["query"]["origin_record_id"]
recids.add(recid)
print("n_records: {}".format(len(results)))
assert len(recids) == len(queries)
def test_unnamed_queries_raises_duplicate_error(here):
subjects = load_genbank_glob(
join(here, "data/test_data/genbank/templates/*.gb"), force_unique_ids=True
)
queries = [
SeqRecord(Seq(str(subjects[0][:1000].seq))),
SeqRecord(Seq(str(subjects[1][:1000].seq))),
# SeqRecord(Seq(str(subjects[1][:1000]))),
]
make_linear(queries)
with pytest.raises(PyBlastException):
BioBlast(subjects, queries)
def test_unnamed_queries(here):
subjects = load_genbank_glob(
join(here, "data/test_data/genbank/templates/*.gb"), force_unique_ids=True
)
queries = [
SeqRecord(Seq(str(subjects[0][:1000].seq))),
SeqRecord(Seq(str(subjects[1][:1000].seq))),
# SeqRecord(Seq(str(subjects[1][:1000]))),
]
force_unique_record_ids(make_linear(queries))
bioblast = BioBlast(subjects, queries)
results = bioblast.blastn()
recids = set()
for res in results:
recid = res["query"]["origin_record_id"]
recids.add(recid)
print("n_records: {}".format(len(results)))
assert len(recids) == len(queries)
def test_self_blast(here):
subjects = load_genbank_glob(
join(here, "data/test_data/genbank/templates/*.gb"), force_unique_ids=True
)
queries = [
SeqRecord(Seq(str(subjects[0][:1000].seq))),
# SeqRecord(Seq(str(subjects[1][:1000]))),
]
force_unique_record_ids(make_linear(queries))
bioblast = BioBlast(queries, queries)
results = bioblast.blastn()
assert not results
def test_with_flags(new_circular_bio_blast):
blast = new_circular_bio_blast()
blast.update_config({"ungapped": None})
blast.blastn()
assert blast.results
def test_ungapped():
frag = "GtctaaaggtgaagaattattcactggtgttgtcccaattttggttgaattagatggtgatgttaatggtcacaaattttctgtctccggtgaaggtgaaggtgatgctacttacggtaaattgaccttaaaatttatttgtactactggtaaattgccagttccatggccaaccttagtcactactttcggttatggtgttcaatgttttgcgagatacccagatcatatgaaacaacatgactttttcaagtctgccatgccagaaggttatgttcaagaaagaactatttttttcaaagatgacggtaactacaagaccagagctgaagtcaagtttgaaggtgataccttagttaatagaatcgaattaaaaggtattgattttaaagaagatggtaacattttaggtcacaaattggaatacaactataactctcacaatgtttacatcatggctgacaaacaaaagaatggtatcaaagttaacttcaaaattagacacaacattgaagatggttctgttcaattagctgaccattatcaacaaaatactccaattggtgatggtccagtcttgttaccagacaaccattacttatccactcaatctgccttatccaaagatccaaacgaaaagagagaccacatggtcttgttagaatttgttactgctgctggtattacccatggtatggatgaattgtacaaaTAGTGATACCGTCGACCTCGAGTCAattagttatgtcacgcttacattcacgccctccccccacatccgctctaaccgaaaaggaaggagttagacaacctgaagtctaggtccctatttatttttttatagttatgttagtattaagaacgttatttatatttcaaatttttcttt"
query = SeqRecord(seq=Seq(frag), annotations={"circular": False})
subject = SeqRecord(
seq=Seq(frag[:400] + "atgctatgctgatgctgctgtgctgat" + frag[400:]),
annotations={"circular": False},
)
# print(type(query))
# print(type(subject))
blaster = BioBlast([subject], [query])
blaster.update_config({"ungapped": None})
blaster.blastn()
alignments = blaster.results
print(alignments)
| 35.772512
| 902
| 0.729597
|
dfa94cfff7c4d5fd16ce4da22a4bd240d6e8312d
| 96
|
py
|
Python
|
NN/layerversions/__init__.py
|
nayyarv/CodeANet
|
30c8d95fff96bdca72b49de551f38e33cd59a5f6
|
[
"MIT"
] | null | null | null |
NN/layerversions/__init__.py
|
nayyarv/CodeANet
|
30c8d95fff96bdca72b49de551f38e33cd59a5f6
|
[
"MIT"
] | null | null | null |
NN/layerversions/__init__.py
|
nayyarv/CodeANet
|
30c8d95fff96bdca72b49de551f38e33cd59a5f6
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "Varun Nayyar <nayyarv@gmail.com>"
| 24
| 47
| 0.645833
|
9ed5614d4d491d8416c421182bd15a17c3fa2114
| 2,642
|
py
|
Python
|
scripts/bnftp_client.py
|
dkuwahara/bncs.py
|
ca88ae244df4d39316d81d1e894c657e1a980a6e
|
[
"MIT"
] | 1
|
2020-02-09T11:02:28.000Z
|
2020-02-09T11:02:28.000Z
|
scripts/bnftp_client.py
|
dkuwahara/bncs.py
|
ca88ae244df4d39316d81d1e894c657e1a980a6e
|
[
"MIT"
] | null | null | null |
scripts/bnftp_client.py
|
dkuwahara/bncs.py
|
ca88ae244df4d39316d81d1e894c657e1a980a6e
|
[
"MIT"
] | null | null | null |
from bnftp import BnftpClient
import argparse
from datetime import datetime
import hashlib
parser = argparse.ArgumentParser(description="Downloads a file from the Battle.net FTP service.")
parser.add_argument("file", help="The name of the file to download.")
parser.add_argument("--server", default="useast.battle.net", help="The hostname or IP of the BNFTP server.")
parser.add_argument("--port", type=int, default=6112, help="The port on the server where BNFTP is listening.")
parser.add_argument("--time", help="The expected filetime of the requested file.")
parser.add_argument("--platform", default="IX86", help="The 4-character platform code identifying the system.")
parser.add_argument("--product", default="D2DV", help="The 4-character game code associated with the file.")
parser.add_argument("--banner", default=[0, 0], nargs=2, metavar=('ID', 'EXT'),
help="The requested banner ID and extension.")
parser.add_argument("--position", default=0, help="The position in the file to start the download.")
parser.add_argument("--protocol", default=0x100, help="The BNFTP protocol version to use.")
parser.add_argument("--hash", const="md5", nargs='?', help="Prints the hash of the completed file.")
parser.add_argument("--no-write", dest="write", action='store_false',
help="Keeps the file in memory and does not write it to disk.")
args = parser.parse_args()
ft = None
if args.time:
if args.time.isdigit():
ft = int(args.time) # Normal int
elif args.time[0:2] == "0x":
ft = int(args.time, 16) # Hex int
else:
ft = datetime.strptime(args.time, "%Y-%m-%d %H:%M:%S")
kw = {
"filetime": ft,
"position": args.position,
"protocol": args.protocol,
"product": args.product,
"bannerID": args.banner[0],
"bannerExt": args.banner[1],
"write": args.write
}
def download_started(size, name, ftime):
print("Received BNFTP response:")
print("\tFile name: %s" % name)
print("\tSize : %i" % size)
print("\tFiletime : %s" % ftime)
def download_complete():
if args.hash:
print("Hash: %s" % client.hash.hexdigest())
print("Download complete.")
client = BnftpClient(args.server, args.port)
client.started_callback = download_started
client.completed_callback = download_complete
# If a hashing algorithm other than the default was specified, initialize it.
if args.hash and args.hash.lower() != "md5":
client.hash = hashlib.new(args.hash)
print("Requesting file '%s' as %s-%s from BNFTP at %s..." % (args.file, args.platform, args.product, args.server))
client.request(args.file, **kw)
| 38.289855
| 114
| 0.682059
|
305b318be47ab62eb64842bb01c784c6a1c0623e
| 8,596
|
py
|
Python
|
tensorflow_estimator/python/estimator/keras_premade_model_test.py
|
tirkarthi/estimator
|
5d962124f1c2ad5b2886ada53d5c604257b660b6
|
[
"Apache-2.0"
] | null | null | null |
tensorflow_estimator/python/estimator/keras_premade_model_test.py
|
tirkarthi/estimator
|
5d962124f1c2ad5b2886ada53d5c604257b660b6
|
[
"Apache-2.0"
] | null | null | null |
tensorflow_estimator/python/estimator/keras_premade_model_test.py
|
tirkarthi/estimator
|
5d962124f1c2ad5b2886ada53d5c604257b660b6
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for keras premade model in model_to_estimator routines."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import tensorflow as tf
import numpy as np
from tensorflow.python import keras
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.feature_column import dense_features
from tensorflow.python.feature_column import feature_column_v2 as feature_column
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import test_util
from tensorflow.python.keras.optimizer_v2 import adam
from tensorflow.python.keras.optimizer_v2 import gradient_descent
from tensorflow.python.keras.premade import linear
from tensorflow.python.keras.premade import wide_deep
from tensorflow.python.platform import gfile
from tensorflow.python.platform import test
from tensorflow.python.summary.writer import writer_cache
from tensorflow_estimator.python.estimator import keras as keras_lib
from tensorflow_estimator.python.estimator import run_config as run_config_lib
from tensorflow_estimator.python.estimator.inputs import numpy_io
_RANDOM_SEED = 1337
def gen_input_fn(x, y=None, batch_size=32, num_epochs=10, shuffle=False):
def input_fn():
ds = tf.compat.v1.data.Dataset.from_tensor_slices((x, y) if y is not None else x)
if shuffle:
ds = ds.shuffle(1000)
return ds.repeat(num_epochs).batch(batch_size)
return input_fn
def get_resource_for_simple_model():
input_name = 'input_1'
output_name = 'output_1'
np.random.seed(_RANDOM_SEED)
x_train = np.random.uniform(low=-5, high=5, size=(64, 2)).astype('f')
y_train = .3 * x_train[:, 0] + .2 * x_train[:, 1]
x_test = np.random.uniform(low=-5, high=5, size=(64, 2)).astype('f')
y_test = .3 * x_test[:, 0] + .2 * x_test[:, 1]
train_input_fn = gen_input_fn(
x=x_train, y=y_train, num_epochs=None, shuffle=False)
evaluate_input_fn = gen_input_fn(
x=randomize_io_type(x_test, input_name),
y=randomize_io_type(y_test, output_name),
num_epochs=1,
shuffle=False)
return (x_train, y_train), (x_test, y_test), train_input_fn, evaluate_input_fn
def randomize_io_type(array, name):
switch = np.random.random()
if switch > 0.5:
return array
else:
return {name: array}
class KerasPremadeModelTest(tf.test.TestCase):
def setUp(self):
self._base_dir = os.path.join(self.get_temp_dir(), 'keras_estimator_test')
tf.compat.v1.gfile.MakeDirs(self._base_dir)
self._config = run_config_lib.RunConfig(
tf_random_seed=_RANDOM_SEED, model_dir=self._base_dir)
super(KerasPremadeModelTest, self).setUp()
def tearDown(self):
# Make sure nothing is stuck in limbo.
tf.compat.v1.summary.FileWriterCache.clear()
if os.path.isdir(self._base_dir):
tf.compat.v1.gfile.DeleteRecursively(self._base_dir)
keras.backend.clear_session()
super(KerasPremadeModelTest, self).tearDown()
def test_train_premade_linear_model_with_dense_features(self):
vocab_list = ['alpha', 'beta', 'gamma']
vocab_val = [0.4, 0.6, 0.9]
data = np.random.choice(vocab_list, size=256)
y = np.zeros_like(data, dtype=np.float32)
for vocab, val in zip(vocab_list, vocab_val):
indices = np.where(data == vocab)
y[indices] = val + np.random.uniform(
low=-0.01, high=0.01, size=indices[0].shape)
cat_column = tf.feature_column.categorical_column_with_vocabulary_list(
key='symbol', vocabulary_list=vocab_list)
ind_column = tf.feature_column.indicator_column(cat_column)
keras_input = keras.layers.Input(
name='symbol', shape=3, dtype=tf.dtypes.string)
feature_layer = dense_features.DenseFeatures([ind_column])
h = feature_layer({'symbol': keras_input})
linear_model = linear.LinearModel(units=1)
h = linear_model(h)
model = keras.Model(inputs=keras_input, outputs=h)
opt = gradient_descent.SGD(0.1)
model.compile(opt, 'mse', ['mse'])
train_input_fn = numpy_io.numpy_input_fn(
x={'symbol': data}, y=y, num_epochs=20, shuffle=False)
eval_input_fn = numpy_io.numpy_input_fn(
x={'symbol': data}, y=y, num_epochs=20, shuffle=False)
est = keras_lib.model_to_estimator(
keras_model=model, config=self._config, checkpoint_format='saver')
before_eval_results = est.evaluate(input_fn=eval_input_fn, steps=1)
est.train(input_fn=train_input_fn, steps=30)
after_eval_results = est.evaluate(input_fn=eval_input_fn, steps=1)
self.assertLess(after_eval_results['loss'], before_eval_results['loss'])
self.assertLess(after_eval_results['loss'], 0.05)
def test_train_premade_linear_model(self):
(x_train,
y_train), _, train_inp_fn, eval_inp_fn = get_resource_for_simple_model()
linear_model = linear.LinearModel(units=1)
opt = gradient_descent.SGD(0.1)
linear_model.compile(opt, 'mse', ['mse'])
linear_model.fit(x_train, y_train, epochs=10)
est = keras_lib.model_to_estimator(
keras_model=linear_model,
config=self._config,
checkpoint_format='saver')
before_eval_results = est.evaluate(input_fn=eval_inp_fn, steps=1)
est.train(input_fn=train_inp_fn, steps=500)
after_eval_results = est.evaluate(input_fn=eval_inp_fn, steps=1)
self.assertLess(after_eval_results['loss'], before_eval_results['loss'])
self.assertLess(after_eval_results['loss'], 0.1)
def test_train_premade_widedeep_model_with_feature_layers(self):
vocab_list = ['alpha', 'beta', 'gamma']
vocab_val = [0.4, 0.6, 0.9]
data = np.random.choice(vocab_list, size=256)
y = np.zeros_like(data, dtype=np.float32)
for vocab, val in zip(vocab_list, vocab_val):
indices = np.where(data == vocab)
y[indices] = val + np.random.uniform(
low=-0.01, high=0.01, size=indices[0].shape)
cat_column = tf.feature_column.categorical_column_with_vocabulary_list(
key='symbol', vocabulary_list=vocab_list)
ind_column = tf.feature_column.indicator_column(cat_column)
# TODO(tanzheny): use emb column for dense part once b/139667019 is fixed.
# emb_column = feature_column.embedding_column(cat_column, dimension=5)
keras_input = keras.layers.Input(
name='symbol', shape=3, dtype=tf.dtypes.string)
# build linear part with feature layer.
linear_feature_layer = dense_features.DenseFeatures([ind_column])
linear_model = linear.LinearModel(
units=1, name='Linear', kernel_initializer='zeros')
combined_linear = keras.Sequential([linear_feature_layer, linear_model])
# build dnn part with feature layer.
dnn_feature_layer = dense_features.DenseFeatures([ind_column])
dense_layer = keras.layers.Dense(
units=1, name='DNNDense', kernel_initializer='zeros')
combined_dnn = keras.Sequential([dnn_feature_layer, dense_layer])
# build and compile wide deep.
wide_deep_model = wide_deep.WideDeepModel(combined_linear, combined_dnn)
wide_deep_model._set_inputs({'symbol': keras_input})
sgd_opt = gradient_descent.SGD(0.1)
adam_opt = adam.Adam(0.1)
wide_deep_model.compile([sgd_opt, adam_opt], 'mse', ['mse'])
# build estimator.
train_input_fn = numpy_io.numpy_input_fn(
x={'symbol': data}, y=y, num_epochs=20, shuffle=False)
eval_input_fn = numpy_io.numpy_input_fn(
x={'symbol': data}, y=y, num_epochs=20, shuffle=False)
est = keras_lib.model_to_estimator(
keras_model=wide_deep_model,
config=self._config,
checkpoint_format='saver')
before_eval_results = est.evaluate(input_fn=eval_input_fn, steps=1)
est.train(input_fn=train_input_fn, steps=20)
after_eval_results = est.evaluate(input_fn=eval_input_fn, steps=1)
self.assertLess(after_eval_results['loss'], before_eval_results['loss'])
self.assertLess(after_eval_results['loss'], 0.1)
if __name__ == '__main__':
tf.test.main()
| 40.54717
| 85
| 0.727897
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.