text:
import numpy as np
from scipy.integrate import solve_ivp
def multisite_1_to_7(a, x, kd1, kd2, kd3, kd4, kd5, kd6, kd7, interval=(0,1)):
	def ode_multisite_1_to_7(concs, t, kd1, kd2, kd3, kd4, kd5, kd6, kd7):
		a, x, a1_x, a2_x, a3_x, a4_x, a5_x, a6_x, a7_x, a1_2_x, a1_3_x, a1_4_x, a1_5_x, a1_6_x, a1_7_x, a2_3_x, a2_4_x, a2_5_x, a2_6_x, a2_7_x, a3_4_x, a3_5_x, a3_6_x, a3_7_x, a4_5_x, a4_6_x, a4_7_x, a5_6_x, a5_7_x, a6_7_x, a1_2_3_x, a1_2_4_x, a1_2_5_x, a1_2_6_x, a1_2_7_x, a1_3_4_x, a1_3_5_x, a1_3_6_x, a1_3_7_x, a1_4_5_x, a1_4_6_x, a1_4_7_x, a1_5_6_x, a1_5_7_x, a1_6_7_x, a2_3_4_x, a2_3_5_x, a2_3_6_x, a2_3_7_x, a2_4_5_x, a2_4_6_x, a2_4_7_x, a2_5_6_x, a2_5_7_x, a2_6_7_x, a3_4_5_x, a3_4_6_x, a3_4_7_x, a3_5_6_x, a3_5_7_x, a3_6_7_x, a4_5_6_x, a4_5_7_x, a4_6_7_x, a5_6_7_x, a1_2_3_4_x, a1_2_3_5_x, a1_2_3_6_x, a1_2_3_7_x, a1_2_4_5_x, a1_2_4_6_x, a1_2_4_7_x, a1_2_5_6_x, a1_2_5_7_x, a1_2_6_7_x, a1_3_4_5_x, a1_3_4_6_x, a1_3_4_7_x, a1_3_5_6_x, a1_3_5_7_x, a1_3_6_7_x, a1_4_5_6_x, a1_4_5_7_x, a1_4_6_7_x, a1_5_6_7_x, a2_3_4_5_x, a2_3_4_6_x, a2_3_4_7_x, a2_3_5_6_x, a2_3_5_7_x, a2_3_6_7_x, a2_4_5_6_x, a2_4_5_7_x, a2_4_6_7_x, a2_5_6_7_x, a3_4_5_6_x, a3_4_5_7_x, a3_4_6_7_x, a3_5_6_7_x, a4_5_6_7_x, a1_2_3_4_5_x, a1_2_3_4_6_x, a1_2_3_4_7_x, a1_2_3_5_6_x, a1_2_3_5_7_x, a1_2_3_6_7_x, a1_2_4_5_6_x, a1_2_4_5_7_x, a1_2_4_6_7_x, a1_2_5_6_7_x, a1_3_4_5_6_x, a1_3_4_5_7_x, a1_3_4_6_7_x, a1_3_5_6_7_x, a1_4_5_6_7_x, a2_3_4_5_6_x, a2_3_4_5_7_x, a2_3_4_6_7_x, a2_3_5_6_7_x, a2_4_5_6_7_x, a3_4_5_6_7_x, a1_2_3_4_5_6_x, a1_2_3_4_5_7_x, a1_2_3_4_6_7_x, a1_2_3_5_6_7_x, a1_2_4_5_6_7_x, a1_3_4_5_6_7_x, a2_3_4_5_6_7_x, a1_2_3_4_5_6_7_x = concs
		r1 = -a*x + kd1*a1_x
		r2 = -a*x + kd2*a2_x
		r3 = -a*x + kd3*a3_x
		r4 = -a*x + kd4*a4_x
		r5 = -a*x + kd5*a5_x
		r6 = -a*x + kd6*a6_x
		r7 = -a*x + kd7*a7_x
		r8 = -a1_x*x + kd2*a1_2_x
		r9 = -a2_x*x + kd1*a1_2_x
		r10 = -a1_x*x + kd3*a1_3_x
		r11 = -a3_x*x + kd1*a1_3_x
		r12 = -a1_x*x + kd4*a1_4_x
		r13 = -a4_x*x + kd1*a1_4_x
		r14 = -a1_x*x + kd5*a1_5_x
		r15 = -a5_x*x + kd1*a1_5_x
		r16 = -a1_x*x + kd6*a1_6_x
		r17 = -a6_x*x + kd1*a1_6_x
		r18 = -a1_x*x + kd7*a1_7_x
		r19 = -a7_x*x + kd1*a1_7_x
		r20 = -a2_x*x + kd3*a2_3_x
		r21 = -a3_x*x + kd2*a2_3_x
		r22 = -a2_x*x + kd4*a2_4_x
		r23 = -a4_x*x + kd2*a2_4_x
		r24 = -a2_x*x + kd5*a2_5_x
		r25 = -a5_x*x + kd2*a2_5_x
		r26 = -a2_x*x + kd6*a2_6_x
		r27 = -a6_x*x + kd2*a2_6_x
		r28 = -a2_x*x + kd7*a2_7_x
		r29 = -a7_x*x + kd2*a2_7_x
		r30 = -a3_x*x + kd4*a3_4_x
		r31 = -a4_x*x + kd3*a3_4_x
		r32 = -a3_x*x + kd5*a3_5_x
		r33 = -a5_x*x + kd3*a3_5_x
		r34 = -a3_x*x + kd6*a3_6_x
		r35 = -a6_x*x + kd3*a3_6_x
		r36 = -a3_x*x + kd7*a3_7_x
		r37 = -a7_x*x + kd3*a3_7_x
		r38 = -a4_x*x + kd5*a4_5_x
		r39 = -a5_x*x + kd4*a4_5_x
		r40 = -a4_x*x + kd6*a4_6_x
		r41 = -a6_x*x + kd4*a4_6_x
		r42 = -a4_x*x + kd7*a4_7_x
		r43 = -a7_x*x + kd4*a4_7_x
		r44 = -a5_x*x + kd6*a5_6_x
		r45 = -a6_x*x + kd5*a5_6_x
		r46 = -a5_x*x + kd7*a5_7_x
		r47 = -a7_x*x + kd5*a5_7_x
		r48 = -a6_x*x + kd7*a6_7_x
		r49 = -a7_x*x + kd6*a6_7_x
		r50 = -a1_2_x*x + kd3*a1_2_3_x
		r51 = -a1_3_x*x + kd2*a1_2_3_x
		r52 = -a2_3_x*x + kd1*a1_2_3_x
		r53 = -a1_2_x*x + kd4*a1_2_4_x
		r54 = -a1_4_x*x + kd2*a1_2_4_x
		r55 = -a2_4_x*x + kd1*a1_2_4_x
		r56 = -a1_2_x*x + kd5*a1_2_5_x
		r57 = -a1_5_x*x + kd2*a1_2_5_x
		r58 = -a2_5_x*x + kd1*a1_2_5_x
		r59 = -a1_2_x*x + kd6*a1_2_6_x
		r60 = -a1_6_x*x + kd2*a1_2_6_x
		r61 = -a2_6_x*x + kd1*a1_2_6_x
		r62 = -a1_2_x*x + kd7*a1_2_7_x
		r63 = -a1_7_x*x + kd2*a1_2_7_x
		r64 = -a2_7_x*x + kd1*a1_2_7_x
		r65 = -a1_3_x*x + kd4*a1_3_4_x
		r66 = -a1_4_x*x + kd3*a1_3_4_x
		r67 = -a3_4_x*x + kd1*a1_3_4_x
		r68 = -a1_3_x*x + kd5*a1_3_5_x
		r69 = -a1_5_x*x + kd3*a1_3_5_x
		r70 = -a3_5_x*x + kd1*a1_3_5_x
		r71 = -a1_3_x*x + kd6*a1_3_6_x
		r72 = -a1_6_x*x + kd3*a1_3_6_x
		r73 = -a3_6_x*x + kd1*a1_3_6_x
		r74 = -a1_3_x*x + kd7*a1_3_7_x
		r75 = -a1_7_x*x + kd3*a1_3_7_x
		r76 = -a3_7_x*x + kd1*a1_3_7_x
		r77 = -a1_4_x*x + kd5*a1_4_5_x
		r78 = -a1_5_x*x + kd4*a1_4_5_x
		r79 = -a4_5_x*x + kd1*a1_4_5_x
		r80 = -a1_4_x*x + kd6*a1_4_6_x
		r81 = -a1_6_x*x + kd4*a1_4_6_x
		r82 = -a4_6_x*x + kd1*a1_4_6_x
		r83 = -a1_4_x*x + kd7*a1_4_7_x
		r84 = -a1_7_x*x + kd4*a1_4_7_x
		r85 = -a4_7_x*x + kd1*a1_4_7_x
		r86 = -a1_5_x*x + kd6*a1_5_6_x
		r87 = -a1_6_x*x + kd5*a1_5_6_x
		r88 = -a5_6_x*x + kd1*a1_5_6_x
		r89 = -a1_5_x*x + kd7*a1_5_7_x
		r90 = -a1_7_x*x + kd5*a1_5_7_x
		r91 = -a5_7_x*x + kd1*a1_5_7_x
		r92 = -a1_6_x*x + kd7*a1_6_7_x
		r93 = -a1_7_x*x + kd6*a1_6_7_x
		r94 = -a6_7_x*x + kd1*a1_6_7_x
		r95 = -a2_3_x*x + kd4*a2_3_4_x
		r96 = -a2_4_x*x + kd3*a2_3_4_x
		r97 = -a3_4_x*x + kd2*a2_3_4_x
		r98 = -a2_3_x*x + kd5*a2_3_5_x
		r99 = -a2_5_x*x + kd3*a2_3_5_x
		r100 = -a3_5_x*x + kd2*a2_3_5_x
		r101 = -a2_3_x*x + kd6*a2_3_6_x
		r102 = -a2_6_x*x + kd3*a2_3_6_x
		r103 = -a3_6_x*x + kd2*a2_3_6_x
		r104 = -a2_3_x*x + kd7*a2_3_7_x
		r105 = -a2_7_x*x + kd3*a2_3_7_x
		r106 = -a3_7_x*x + kd2*a2_3_7_x
		r107 = -a2_4_x*x + kd5*a2_4_5_x
		r108 = -a2_5_x*x + kd4*a2_4_5_x
		r109 = -a4_5_x*x + kd2*a2_4_5_x
		r110 = -a2_4_x*x + kd6*a2_4_6_x
		r111 = -a2_6_x*x + kd4*a2_4_6_x
		r112 = -a4_6_x*x + kd2*a2_4_6_x
		r113 = -a2_4_x*x + kd7*a2_4_7_x
		r114 = -a2_7_x*x + kd4*a2_4_7_x
		r115 = -a4_7_x*x + kd2*a2_4_7_x
		r116 = -a2_5_x*x + kd6*a2_5_6_x
		r117 = -a2_6_x*x + kd5*a2_5_6_x
		r118 = -a5_6_x*x + kd2*a2_5_6_x
		r119 = -a2_5_x*x + kd7*a2_5_7_x
		r120 = -a2_7_x*x + kd5*a2_5_7_x
		r121 = -a5_7_x*x + kd2*a2_5_7_x
		r122 = -a2_6_x*x + kd7*a2_6_7_x
		r123 = -a2_7_x*x + kd6*a2_6_7_x
		r124 = -a6_7_x*x + kd2*a2_6_7_x
		r125 = -a3_4_x*x + kd5*a3_4_5_x
		r126 = -a3_5_x*x + kd4*a3_4_5_x
		r127 = -a4_5_x*x + kd3*a3_4_5_x
		r128 = -a3_4_x*x + kd6*a3_4_6_x
		r129 = -a3_6_x*x + kd4*a3_4_6_x
		r130 = -a4_6_x*x + kd3*a3_4_6_x
		r131 = -a3_4_x*x + kd7*a3_4_7_x
		r132 = -a3_7_x*x + kd4*a3_4_7_x
		r133 = -a4_7_x*x + kd3*a3_4_7_x
		r134 = -a3_5_x*x + kd6*a3_5_6_x
		r135 = -a3_6_x*x + kd5*a3_5_6_x
		r136 = -a5_6_x*x + kd3*a3_5_6_x
		r137 = -a3_5_x*x + kd7*a3_5_7_x
		r138 = -a3_7_x*x + kd5*a3_5_7_x
		r139 = -a5_7_x*x + kd3*a3_5_7_x
		r140 = -a3_6_x*x + kd7*a3_6_7_x
		r141 = -a3_7_x*x + kd6*a3_6_7_x
		r142 = -a6_7_x*x + kd3*a3_6_7_x
		r143 = -a4_5_x*x + kd6*a4_5_6_x
		r144 = -a4_6_x*x + kd5*a4_5_6_x
		r145 = -a5_6_x*x + kd4*a4_5_6_x
		r146 = -a4_5_x*x + kd7*a4_5_7_x
		r147 = -a4_7_x*x + kd5*a4_5_7_x
		r148 = -a5_7_x*x + kd4*a4_5_7_x
		r149 = -a4_6_x*x + kd7*a4_6_7_x
		r150 = -a4_7_x*x + kd6*a4_6_7_x
		r151 = -a6_7_x*x + kd4*a4_6_7_x
		r152 = -a5_6_x*x + kd7*a5_6_7_x
		r153 = -a5_7_x*x + kd6*a5_6_7_x
		r154 = -a6_7_x*x + kd5*a5_6_7_x
		r155 = -a1_2_3_x*x + kd4*a1_2_3_4_x
		r156 = -a1_2_4_x*x + kd3*a1_2_3_4_x
		r157 = -a1_3_4_x*x + kd2*a1_2_3_4_x
		r158 = -a2_3_4_x*x + kd1*a1_2_3_4_x
		r159 = -a1_2_3_x*x + kd5*a1_2_3_5_x
		r160 = -a1_2_5_x*x + kd3*a1_2_3_5_x
		r161 = -a1_3_5_x*x + kd2*a1_2_3_5_x
		r162 = -a2_3_5_x*x + kd1*a1_2_3_5_x
		r163 = -a1_2_3_x*x + kd6*a1_2_3_6_x
		r164 = -a1_2_6_x*x + kd3*a1_2_3_6_x
		r165 = -a1_3_6_x*x + kd2*a1_2_3_6_x
		r166 = -a2_3_6_x*x + kd1*a1_2_3_6_x
		r167 = -a1_2_3_x*x + kd7*a1_2_3_7_x
		r168 = -a1_2_7_x*x + kd3*a1_2_3_7_x
		r169 = -a1_3_7_x*x + kd2*a1_2_3_7_x
		r170 = -a2_3_7_x*x + kd1*a1_2_3_7_x
		r171 = -a1_2_4_x*x + kd5*a1_2_4_5_x
		r172 = -a1_2_5_x*x + kd4*a1_2_4_5_x
		r173 = -a1_4_5_x*x + kd2*a1_2_4_5_x
		r174 = -a2_4_5_x*x + kd1*a1_2_4_5_x
		r175 = -a1_2_4_x*x + kd6*a1_2_4_6_x
		r176 = -a1_2_6_x*x + kd4*a1_2_4_6_x
		r177 = -a1_4_6_x*x + kd2*a1_2_4_6_x
		r178 = -a2_4_6_x*x + kd1*a1_2_4_6_x
		r179 = -a1_2_4_x*x + kd7*a1_2_4_7_x
		r180 = -a1_2_7_x*x + kd4*a1_2_4_7_x
		r181 = -a1_4_7_x*x + kd2*a1_2_4_7_x
		r182 = -a2_4_7_x*x + kd1*a1_2_4_7_x
		r183 = -a1_2_5_x*x + kd6*a1_2_5_6_x
		r184 = -a1_2_6_x*x + kd5*a1_2_5_6_x
		r185 = -a1_5_6_x*x + kd2*a1_2_5_6_x
		r186 = -a2_5_6_x*x + kd1*a1_2_5_6_x
		r187 = -a1_2_5_x*x + kd7*a1_2_5_7_x
		r188 = -a1_2_7_x*x + kd5*a1_2_5_7_x
		r189 = -a1_5_7_x*x + kd2*a1_2_5_7_x
		r190 = -a2_5_7_x*x + kd1*a1_2_5_7_x
		r191 = -a1_2_6_x*x + kd7*a1_2_6_7_x
		r192 = -a1_2_7_x*x + kd6*a1_2_6_7_x
		r193 = -a1_6_7_x*x + kd2*a1_2_6_7_x
		r194 = -a2_6_7_x*x + kd1*a1_2_6_7_x
		r195 = -a1_3_4_x*x + kd5*a1_3_4_5_x
		r196 = -a1_3_5_x*x + kd4*a1_3_4_5_x
		r197 = -a1_4_5_x*x + kd3*a1_3_4_5_x
		r198 = -a3_4_5_x*x + kd1*a1_3_4_5_x
		r199 = -a1_3_4_x*x + kd6*a1_3_4_6_x
		r200 = -a1_3_6_x*x + kd4*a1_3_4_6_x
		r201 = -a1_4_6_x*x + kd3*a1_3_4_6_x
		r202 = -a3_4_6_x*x + kd1*a1_3_4_6_x
		r203 = -a1_3_4_x*x + kd7*a1_3_4_7_x
		r204 = -a1_3_7_x*x + kd4*a1_3_4_7_x
		r205 = -a1_4_7_x*x + kd3*a1_3_4_7_x
		r206 = -a3_4_7_x*x + kd1*a1_3_4_7_x
		r207 = -a1_3_5_x*x + kd6*a1_3_5_6_x
		r208 = -a1_3_6_x*x + kd5*a1_3_5_6_x
		r209 = -a1_5_6_x*x + kd3*a1_3_5_6_x
		r210 = -a3_5_6_x*x + kd1*a1_3_5_6_x
		r211 = -a1_3_5_x*x + kd7*a1_3_5_7_x
		r212 = -a1_3_7_x*x + kd5*a1_3_5_7_x
		r213 = -a1_5_7_x*x + kd3*a1_3_5_7_x
		r214 = -a3_5_7_x*x + kd1*a1_3_5_7_x
		r215 = -a1_3_6_x*x + kd7*a1_3_6_7_x
		r216 = -a1_3_7_x*x + kd6*a1_3_6_7_x
		r217 = -a1_6_7_x*x + kd3*a1_3_6_7_x
		r218 = -a3_6_7_x*x + kd1*a1_3_6_7_x
		r219 = -a1_4_5_x*x + kd6*a1_4_5_6_x
		r220 = -a1_4_6_x*x + kd5*a1_4_5_6_x
		r221 = -a1_5_6_x*x + kd4*a1_4_5_6_x
		r222 = -a4_5_6_x*x + kd1*a1_4_5_6_x
		r223 = -a1_4_5_x*x + kd7*a1_4_5_7_x
		r224 = -a1_4_7_x*x + kd5*a1_4_5_7_x
		r225 = -a1_5_7_x*x + kd4*a1_4_5_7_x
		r226 = -a4_5_7_x*x + kd1*a1_4_5_7_x
		r227 = -a1_4_6_x*x + kd7*a1_4_6_7_x
		r228 = -a1_4_7_x*x + kd6*a1_4_6_7_x
		r229 = -a1_6_7_x*x + kd4*a1_4_6_7_x
		r230 = -a4_6_7_x*x + kd1*a1_4_6_7_x
		r231 = -a1_5_6_x*x + kd7*a1_5_6_7_x
		r232 = -a1_5_7_x*x + kd6*a1_5_6_7_x
		r233 = -a1_6_7_x*x + kd5*a1_5_6_7_x
		r234 = -a5_6_7_x*x + kd1*a1_5_6_7_x
		r235 = -a2_3_4_x*x + kd5*a2_3_4_5_x
		r236 = -a2_3_5_x*x + kd4*a2_3_4_5_x
		r237 = -a2_4_5_x*x + kd3*a2_3_4_5_x
		r238 = -a3_4_5_x*x + kd2*a2_3_4_5_x
		r239 = -a2_3_4_x*x + kd6*a2_3_4_6_x
		r240 = -a2_3_6_x*x + kd4*a2_3_4_6_x
		r241 = -a2_4_6_x*x + kd3*a2_3_4_6_x
		r242 = -a3_4_6_x*x + kd2*a2_3_4_6_x
		r243 = -a2_3_4_x*x + kd7*a2_3_4_7_x
		r244 = -a2_3_7_x*x + kd4*a2_3_4_7_x
		r245 = -a2_4_7_x*x + kd3*a2_3_4_7_x
		r246 = -a3_4_7_x*x + kd2*a2_3_4_7_x
		r247 = -a2_3_5_x*x + kd6*a2_3_5_6_x
		r248 = -a2_3_6_x*x + kd5*a2_3_5_6_x
		r249 = -a2_5_6_x*x + kd3*a2_3_5_6_x
		r250 = -a3_5_6_x*x + kd2*a2_3_5_6_x
		r251 = -a2_3_5_x*x + kd7*a2_3_5_7_x
		r252 = -a2_3_7_x*x + kd5*a2_3_5_7_x
		r253 = -a2_5_7_x*x + kd3*a2_3_5_7_x
		r254 = -a3_5_7_x*x + kd2*a2_3_5_7_x
		r255 = -a2_3_6_x*x + kd7*a2_3_6_7_x
		r256 = -a2_3_7_x*x + kd6*a2_3_6_7_x
		r257 = -a2_6_7_x*x + kd3*a2_3_6_7_x
		r258 = -a3_6_7_x*x + kd2*a2_3_6_7_x
		r259 = -a2_4_5_x*x + kd6*a2_4_5_6_x
		r260 = -a2_4_6_x*x + kd5*a2_4_5_6_x
		r261 = -a2_5_6_x*x + kd4*a2_4_5_6_x
		r262 = -a4_5_6_x*x + kd2*a2_4_5_6_x
		r263 = -a2_4_5_x*x + kd7*a2_4_5_7_x
		r264 = -a2_4_7_x*x + kd5*a2_4_5_7_x
		r265 = -a2_5_7_x*x + kd4*a2_4_5_7_x
		r266 = -a4_5_7_x*x + kd2*a2_4_5_7_x
		r267 = -a2_4_6_x*x + kd7*a2_4_6_7_x
		r268 = -a2_4_7_x*x + kd6*a2_4_6_7_x
		r269 = -a2_6_7_x*x + kd4*a2_4_6_7_x
		r270 = -a4_6_7_x*x + kd2*a2_4_6_7_x
		r271 = -a2_5_6_x*x + kd7*a2_5_6_7_x
		r272 = -a2_5_7_x*x + kd6*a2_5_6_7_x
		r273 = -a2_6_7_x*x + kd5*a2_5_6_7_x
		r274 = -a5_6_7_x*x + kd2*a2_5_6_7_x
		r275 = -a3_4_5_x*x + kd6*a3_4_5_6_x
		r276 = -a3_4_6_x*x + kd5*a3_4_5_6_x
		r277 = -a3_5_6_x*x + kd4*a3_4_5_6_x
		r278 = -a4_5_6_x*x + kd3*a3_4_5_6_x
		r279 = -a3_4_5_x*x + kd7*a3_4_5_7_x
		r280 = -a3_4_7_x*x + kd5*a3_4_5_7_x
		r281 = -a3_5_7_x*x + kd4*a3_4_5_7_x
		r282 = -a4_5_7_x*x + kd3*a3_4_5_7_x
		r283 = -a3_4_6_x*x + kd7*a3_4_6_7_x
		r284 = -a3_4_7_x*x + kd6*a3_4_6_7_x
		r285 = -a3_6_7_x*x + kd4*a3_4_6_7_x
		r286 = -a4_6_7_x*x + kd3*a3_4_6_7_x
		r287 = -a3_5_6_x*x + kd7*a3_5_6_7_x
		r288 = -a3_5_7_x*x + kd6*a3_5_6_7_x
		r289 = -a3_6_7_x*x + kd5*a3_5_6_7_x
		r290 = -a5_6_7_x*x + kd3*a3_5_6_7_x
		r291 = -a4_5_6_x*x + kd7*a4_5_6_7_x
		r292 = -a4_5_7_x*x + kd6*a4_5_6_7_x
		r293 = -a4_6_7_x*x + kd5*a4_5_6_7_x
		r294 = -a5_6_7_x*x + kd4*a4_5_6_7_x
		r295 = -a1_2_3_4_x*x + kd5*a1_2_3_4_5_x
		r296 = -a1_2_3_5_x*x + kd4*a1_2_3_4_5_x
		r297 = -a1_2_4_5_x*x + kd3*a1_2_3_4_5_x
		r298 = -a1_3_4_5_x*x + kd2*a1_2_3_4_5_x
		r299 = -a2_3_4_5_x*x + kd1*a1_2_3_4_5_x
		r300 = -a1_2_3_4_x*x + kd6*a1_2_3_4_6_x
		r301 = -a1_2_3_6_x*x + kd4*a1_2_3_4_6_x
		r302 = -a1_2_4_6_x*x + kd3*a1_2_3_4_6_x
		r303 = -a1_3_4_6_x*x + kd2*a1_2_3_4_6_x
		r304 = -a2_3_4_6_x*x + kd1*a1_2_3_4_6_x
		r305 = -a1_2_3_4_x*x + kd7*a1_2_3_4_7_x
		r306 = -a1_2_3_7_x*x + kd4*a1_2_3_4_7_x
		r307 = -a1_2_4_7_x*x + kd3*a1_2_3_4_7_x
		r308 = -a1_3_4_7_x*x + kd2*a1_2_3_4_7_x
		r309 = -a2_3_4_7_x*x + kd1*a1_2_3_4_7_x
		r310 = -a1_2_3_5_x*x + kd6*a1_2_3_5_6_x
		r311 = -a1_2_3_6_x*x + kd5*a1_2_3_5_6_x
		r312 = -a1_2_5_6_x*x + kd3*a1_2_3_5_6_x
		r313 = -a1_3_5_6_x*x + kd2*a1_2_3_5_6_x
		r314 = -a2_3_5_6_x*x + kd1*a1_2_3_5_6_x
		r315 = -a1_2_3_5_x*x + kd7*a1_2_3_5_7_x
		r316 = -a1_2_3_7_x*x + kd5*a1_2_3_5_7_x
		r317 = -a1_2_5_7_x*x + kd3*a1_2_3_5_7_x
		r318 = -a1_3_5_7_x*x + kd2*a1_2_3_5_7_x
		r319 = -a2_3_5_7_x*x + kd1*a1_2_3_5_7_x
		r320 = -a1_2_3_6_x*x + kd7*a1_2_3_6_7_x
		r321 = -a1_2_3_7_x*x + kd6*a1_2_3_6_7_x
		r322 = -a1_2_6_7_x*x + kd3*a1_2_3_6_7_x
		r323 = -a1_3_6_7_x*x + kd2*a1_2_3_6_7_x
		r324 = -a2_3_6_7_x*x + kd1*a1_2_3_6_7_x
		r325 = -a1_2_4_5_x*x + kd6*a1_2_4_5_6_x
		r326 = -a1_2_4_6_x*x + kd5*a1_2_4_5_6_x
		r327 = -a1_2_5_6_x*x + kd4*a1_2_4_5_6_x
		r328 = -a1_4_5_6_x*x + kd2*a1_2_4_5_6_x
		r329 = -a2_4_5_6_x*x + kd1*a1_2_4_5_6_x
		r330 = -a1_2_4_5_x*x + kd7*a1_2_4_5_7_x
		r331 = -a1_2_4_7_x*x + kd5*a1_2_4_5_7_x
		r332 = -a1_2_5_7_x*x + kd4*a1_2_4_5_7_x
		r333 = -a1_4_5_7_x*x + kd2*a1_2_4_5_7_x
		r334 = -a2_4_5_7_x*x + kd1*a1_2_4_5_7_x
		r335 = -a1_2_4_6_x*x + kd7*a1_2_4_6_7_x
		r336 = -a1_2_4_7_x*x + kd6*a1_2_4_6_7_x
		r337 = -a1_2_6_7_x*x + kd4*a1_2_4_6_7_x
		r338 = -a1_4_6_7_x*x + kd2*a1_2_4_6_7_x
		r339 = -a2_4_6_7_x*x + kd1*a1_2_4_6_7_x
		r340 = -a1_2_5_6_x*x + kd7*a1_2_5_6_7_x
		r341 = -a1_2_5_7_x*x + kd6*a1_2_5_6_7_x
		r342 = -a1_2_6_7_x*x + kd5*a1_2_5_6_7_x
		r343 = -a1_5_6_7_x*x + kd2*a1_2_5_6_7_x
		r344 = -a2_5_6_7_x*x + kd1*a1_2_5_6_7_x
		r345 = -a1_3_4_5_x*x + kd6*a1_3_4_5_6_x
		r346 = -a1_3_4_6_x*x + kd5*a1_3_4_5_6_x
		r347 = -a1_3_5_6_x*x + kd4*a1_3_4_5_6_x
		r348 = -a1_4_5_6_x*x + kd3*a1_3_4_5_6_x
		r349 = -a3_4_5_6_x*x + kd1*a1_3_4_5_6_x
		r350 = -a1_3_4_5_x*x + kd7*a1_3_4_5_7_x
		r351 = -a1_3_4_7_x*x + kd5*a1_3_4_5_7_x
		r352 = -a1_3_5_7_x*x + kd4*a1_3_4_5_7_x
		r353 = -a1_4_5_7_x*x + kd3*a1_3_4_5_7_x
		r354 = -a3_4_5_7_x*x + kd1*a1_3_4_5_7_x
		r355 = -a1_3_4_6_x*x + kd7*a1_3_4_6_7_x
		r356 = -a1_3_4_7_x*x + kd6*a1_3_4_6_7_x
		r357 = -a1_3_6_7_x*x + kd4*a1_3_4_6_7_x
		r358 = -a1_4_6_7_x*x + kd3*a1_3_4_6_7_x
		r359 = -a3_4_6_7_x*x + kd1*a1_3_4_6_7_x
		r360 = -a1_3_5_6_x*x + kd7*a1_3_5_6_7_x
		r361 = -a1_3_5_7_x*x + kd6*a1_3_5_6_7_x
		r362 = -a1_3_6_7_x*x + kd5*a1_3_5_6_7_x
		r363 = -a1_5_6_7_x*x + kd3*a1_3_5_6_7_x
		r364 = -a3_5_6_7_x*x + kd1*a1_3_5_6_7_x
		r365 = -a1_4_5_6_x*x + kd7*a1_4_5_6_7_x
		r366 = -a1_4_5_7_x*x + kd6*a1_4_5_6_7_x
		r367 = -a1_4_6_7_x*x + kd5*a1_4_5_6_7_x
		r368 = -a1_5_6_7_x*x + kd4*a1_4_5_6_7_x
		r369 = -a4_5_6_7_x*x + kd1*a1_4_5_6_7_x
		r370 = -a2_3_4_5_x*x + kd6*a2_3_4_5_6_x
		r371 = -a2_3_4_6_x*x + kd5*a2_3_4_5_6_x
		r372 = -a2_3_5_6_x*x + kd4*a2_3_4_5_6_x
		r373 = -a2_4_5_6_x*x + kd3*a2_3_4_5_6_x
		r374 = -a3_4_5_6_x*x + kd2*a2_3_4_5_6_x
		r375 = -a2_3_4_5_x*x + kd7*a2_3_4_5_7_x
		r376 = -a2_3_4_7_x*x + kd5*a2_3_4_5_7_x
		r377 = -a2_3_5_7_x*x + kd4*a2_3_4_5_7_x
		r378 = -a2_4_5_7_x*x + kd3*a2_3_4_5_7_x
		r379 = -a3_4_5_7_x*x + kd2*a2_3_4_5_7_x
		r380 = -a2_3_4_6_x*x + kd7*a2_3_4_6_7_x
		r381 = -a2_3_4_7_x*x + kd6*a2_3_4_6_7_x
		r382 = -a2_3_6_7_x*x + kd4*a2_3_4_6_7_x
		r383 = -a2_4_6_7_x*x + kd3*a2_3_4_6_7_x
		r384 = -a3_4_6_7_x*x + kd2*a2_3_4_6_7_x
		r385 = -a2_3_5_6_x*x + kd7*a2_3_5_6_7_x
		r386 = -a2_3_5_7_x*x + kd6*a2_3_5_6_7_x
		r387 = -a2_3_6_7_x*x + kd5*a2_3_5_6_7_x
		r388 = -a2_5_6_7_x*x + kd3*a2_3_5_6_7_x
		r389 = -a3_5_6_7_x*x + kd2*a2_3_5_6_7_x
		r390 = -a2_4_5_6_x*x + kd7*a2_4_5_6_7_x
		r391 = -a2_4_5_7_x*x + kd6*a2_4_5_6_7_x
		r392 = -a2_4_6_7_x*x + kd5*a2_4_5_6_7_x
		r393 = -a2_5_6_7_x*x + kd4*a2_4_5_6_7_x
		r394 = -a4_5_6_7_x*x + kd2*a2_4_5_6_7_x
		r395 = -a3_4_5_6_x*x + kd7*a3_4_5_6_7_x
		r396 = -a3_4_5_7_x*x + kd6*a3_4_5_6_7_x
		r397 = -a3_4_6_7_x*x + kd5*a3_4_5_6_7_x
		r398 = -a3_5_6_7_x*x + kd4*a3_4_5_6_7_x
		r399 = -a4_5_6_7_x*x + kd3*a3_4_5_6_7_x
		r400 = -a1_2_3_4_5_x*x + kd6*a1_2_3_4_5_6_x
		r401 = -a1_2_3_4_6_x*x + kd5*a1_2_3_4_5_6_x
		r402 = -a1_2_3_5_6_x*x + kd4*a1_2_3_4_5_6_x
		r403 = -a1_2_4_5_6_x*x + kd3*a1_2_3_4_5_6_x
		r404 = -a1_3_4_5_6_x*x + kd2*a1_2_3_4_5_6_x
		r405 = -a2_3_4_5_6_x*x + kd1*a1_2_3_4_5_6_x
		r406 = -a1_2_3_4_5_x*x + kd7*a1_2_3_4_5_7_x
		r407 = -a1_2_3_4_7_x*x + kd5*a1_2_3_4_5_7_x
		r408 = -a1_2_3_5_7_x*x + kd4*a1_2_3_4_5_7_x
		r409 = -a1_2_4_5_7_x*x + kd3*a1_2_3_4_5_7_x
		r410 = -a1_3_4_5_7_x*x + kd2*a1_2_3_4_5_7_x
		r411 = -a2_3_4_5_7_x*x + kd1*a1_2_3_4_5_7_x
		r412 = -a1_2_3_4_6_x*x + kd7*a1_2_3_4_6_7_x
		r413 = -a1_2_3_4_7_x*x + kd6*a1_2_3_4_6_7_x
		r414 = -a1_2_3_6_7_x*x + kd4*a1_2_3_4_6_7_x
		r415 = -a1_2_4_6_7_x*x + kd3*a1_2_3_4_6_7_x
		r416 = -a1_3_4_6_7_x*x + kd2*a1_2_3_4_6_7_x
		r417 = -a2_3_4_6_7_x*x + kd1*a1_2_3_4_6_7_x
		r418 = -a1_2_3_5_6_x*x + kd7*a1_2_3_5_6_7_x
		r419 = -a1_2_3_5_7_x*x + kd6*a1_2_3_5_6_7_x
		r420 = -a1_2_3_6_7_x*x + kd5*a1_2_3_5_6_7_x
		r421 = -a1_2_5_6_7_x*x + kd3*a1_2_3_5_6_7_x
		r422 = -a1_3_5_6_7_x*x + kd2*a1_2_3_5_6_7_x
		r423 = -a2_3_5_6_7_x*x + kd1*a1_2_3_5_6_7_x
		r424 = -a1_2_4_5_6_x*x + kd7*a1_2_4_5_6_7_x
		r425 = -a1_2_4_5_7_x*x + kd6*a1_2_4_5_6_7_x
		r426 = -a1_2_4_6_7_x*x + kd5*a1_2_4_5_6_7_x
		r427 = -a1_2_5_6_7_x*x + kd4*a1_2_4_5_6_7_x
		r428 = -a1_4_5_6_7_x*x + kd2*a1_2_4_5_6_7_x
		r429 = -a2_4_5_6_7_x*x + kd1*a1_2_4_5_6_7_x
		r430 = -a1_3_4_5_6_x*x + kd7*a1_3_4_5_6_7_x
		r431 = -a1_3_4_5_7_x*x + kd6*a1_3_4_5_6_7_x
		r432 = -a1_3_4_6_7_x*x + kd5*a1_3_4_5_6_7_x
		r433 = -a1_3_5_6_7_x*x + kd4*a1_3_4_5_6_7_x
		r434 = -a1_4_5_6_7_x*x + kd3*a1_3_4_5_6_7_x
		r435 = -a3_4_5_6_7_x*x + kd1*a1_3_4_5_6_7_x
		r436 = -a2_3_4_5_6_x*x + kd7*a2_3_4_5_6_7_x
		r437 = -a2_3_4_5_7_x*x + kd6*a2_3_4_5_6_7_x
		r438 = -a2_3_4_6_7_x*x + kd5*a2_3_4_5_6_7_x
		r439 = -a2_3_5_6_7_x*x + kd4*a2_3_4_5_6_7_x
		r440 = -a2_4_5_6_7_x*x + kd3*a2_3_4_5_6_7_x
		r441 = -a3_4_5_6_7_x*x + kd2*a2_3_4_5_6_7_x
		r442 = -a1_2_3_4_5_6_x*x + kd7*a1_2_3_4_5_6_7_x
		r443 = -a1_2_3_4_5_7_x*x + kd6*a1_2_3_4_5_6_7_x
		r444 = -a1_2_3_4_6_7_x*x + kd5*a1_2_3_4_5_6_7_x
		r445 = -a1_2_3_5_6_7_x*x + kd4*a1_2_3_4_5_6_7_x
		r446 = -a1_2_4_5_6_7_x*x + kd3*a1_2_3_4_5_6_7_x
		r447 = -a1_3_4_5_6_7_x*x + kd2*a1_2_3_4_5_6_7_x
		r448 = -a2_3_4_5_6_7_x*x + kd1*a1_2_3_4_5_6_7_x
		dadt = 0.0 +r1 +r2 +r3 +r4 +r5 +r6 +r7
		da1_xdt = 0.0 -r1 +r8 +r10 +r12 +r14 +r16 +r18
		da2_xdt = 0.0 -r2 +r9 +r20 +r22 +r24 +r26 +r28
		da3_xdt = 0.0 -r3 +r11 +r21 +r30 +r32 +r34 +r36
		da4_xdt = 0.0 -r4 +r13 +r23 +r31 +r38 +r40 +r42
		da5_xdt = 0.0 -r5 +r15 +r25 +r33 +r39 +r44 +r46
		da6_xdt = 0.0 -r6 +r17 +r27 +r35 +r41 +r45 +r48
		da7_xdt = 0.0 -r7 +r19 +r29 +r37 +r43 +r47 +r49
		da1_2_xdt = 0.0 -r8 -r9 +r50 +r53 +r56 +r59 +r62
		da1_3_xdt = 0.0 -r10 -r11 +r51 +r65 +r68 +r71 +r74
		da1_4_xdt = 0.0 -r12 -r13 +r54 +r66 +r77 +r80 +r83
		da1_5_xdt = 0.0 -r14 -r15 +r57 +r69 +r78 +r86 +r89
		da1_6_xdt = 0.0 -r16 -r17 +r60 +r72 +r81 +r87 +r92
		da1_7_xdt = 0.0 -r18 -r19 +r63 +r75 +r84 +r90 +r93
		da2_3_xdt = 0.0 -r20 -r21 +r52 +r95 +r98 +r101 +r104
		da2_4_xdt = 0.0 -r22 -r23 +r55 +r96 +r107 +r110 +r113
		da2_5_xdt = 0.0 -r24 -r25 +r58 +r99 +r108 +r116 +r119
		da2_6_xdt = 0.0 -r26 -r27 +r61 +r102 +r111 +r117 +r122
		da2_7_xdt = 0.0 -r28 -r29 +r64 +r105 +r114 +r120 +r123
		da3_4_xdt = 0.0 -r30 -r31 +r67 +r97 +r125 +r128 +r131
		da3_5_xdt = 0.0 -r32 -r33 +r70 +r100 +r126 +r134 +r137
		da3_6_xdt = 0.0 -r34 -r35 +r73 +r103 +r129 +r135 +r140
		da3_7_xdt = 0.0 -r36 -r37 +r76 +r106 +r132 +r138 +r141
		da4_5_xdt = 0.0 -r38 -r39 +r79 +r109 +r127 +r143 +r146
		da4_6_xdt = 0.0 -r40 -r41 +r82 +r112 +r130 +r144 +r149
		da4_7_xdt = 0.0 -r42 -r43 +r85 +r115 +r133 +r147 +r150
		da5_6_xdt = 0.0 -r44 -r45 +r88 +r118 +r136 +r145 +r152
		da5_7_xdt = 0.0 -r46 -r47 +r91 +r121 +r139 +r148 +r153
		da6_7_xdt = 0.0 -r48 -r49 +r94 +r124 +r142 +r151 +r154
		da1_2_3_xdt = 0.0 -r50 -r51 -r52 +r155 +r159 +r163 +r167
		da1_2_4_xdt = 0.0 -r53 -r54 -r55 +r156 +r171 +r175 +r179
		da1_2_5_xdt = 0.0 -r56 -r57 -r58 +r160 +r172 +r183 +r187
		da1_2_6_xdt = 0.0 -r59 -r60 -r61 +r164 +r176 +r184 +r191
		da1_2_7_xdt = 0.0 -r62 -r63 -r64 +r168 +r180 +r188 +r192
		da1_3_4_xdt = 0.0 -r65 -r66 -r67 +r157 +r195 +r199 +r203
		da1_3_5_xdt = 0.0 -r68 -r69 -r70 +r161 +r196 +r207 +r211
		da1_3_6_xdt = 0.0 -r71 -r72 -r73 +r165 +r200 +r208 +r215
		da1_3_7_xdt = 0.0 -r74 -r75 -r76 +r169 +r204 +r212 +r216
		da1_4_5_xdt = 0.0 -r77 -r78 -r79 +r173 +r197 +r219 +r223
		da1_4_6_xdt = 0.0 -r80 -r81 -r82 +r177 +r201 +r220 +r227
		da1_4_7_xdt = 0.0 -r83 -r84 -r85 +r181 +r205 +r224 +r228
		da1_5_6_xdt = 0.0 -r86 -r87 -r88 +r185 +r209 +r221 +r231
		da1_5_7_xdt = 0.0 -r89 -r90 -r91 +r189 +r213 +r225 +r232
		da1_6_7_xdt = 0.0 -r92 -r93 -r94 +r193 +r217 +r229 +r233
		da2_3_4_xdt = 0.0 -r95 -r96 -r97 +r158 +r235 +r239 +r243
		da2_3_5_xdt = 0.0 -r98 -r99 -r100 +r162 +r236 +r247 +r251
		da2_3_6_xdt = 0.0 -r101 -r102 -r103 +r166 +r240 +r248 +r255
		da2_3_7_xdt = 0.0 -r104 -r105 -r106 +r170 +r244 +r252 +r256
		da2_4_5_xdt = 0.0 -r107 -r108 -r109 +r174 +r237 +r259 +r263
		da2_4_6_xdt = 0.0 -r110 -r111 -r112 +r178 +r241 +r260 +r267
		da2_4_7_xdt = 0.0 -r113 -r114 -r115 +r182 +r245 +r264 +r268
		da2_5_6_xdt = 0.0 -r116 -r117 -r118 +r186 +r249 +r261 +r271
		da2_5_7_xdt = 0.0 -r119 -r120 -r121 +r190 +r253 +r265 +r272
		da2_6_7_xdt = 0.0 -r122 -r123 -r124 +r194 +r257 +r269 +r273
		da3_4_5_xdt = 0.0 -r125 -r126 -r127 +r198 +r238 +r275 +r279
		da3_4_6_xdt = 0.0 -r128 -r129 -r130 +r202 +r242 +r276 +r283
		da3_4_7_xdt = 0.0 -r131 -r132 -r133 +r206 +r246 +r280 +r284
		da3_5_6_xdt = 0.0 -r134 -r135 -r136 +r210 +r250 +r277 +r287
		da3_5_7_xdt = 0.0 -r137 -r138 -r139 +r214 +r254 +r281 +r288
		da3_6_7_xdt = 0.0 -r140 -r141 -r142 +r218 +r258 +r285 +r289
		da4_5_6_xdt = 0.0 -r143 -r144 -r145 +r222 +r262 +r278 +r291
		da4_5_7_xdt = 0.0 -r146 -r147 -r148 +r226 +r266 +r282 +r292
		da4_6_7_xdt = 0.0 -r149 -r150 -r151 +r230 +r270 +r286 +r293
		da5_6_7_xdt = 0.0 -r152 -r153 -r154 +r234 +r274 +r290 +r294
		da1_2_3_4_xdt = 0.0 -r155 -r156 -r157 -r158 +r295 +r300 +r305
		da1_2_3_5_xdt = 0.0 -r159 -r160 -r161 -r162 +r296 +r310 +r315
		da1_2_3_6_xdt = 0.0 -r163 -r164 -r165 -r166 +r301 +r311 +r320
		da1_2_3_7_xdt = 0.0 -r167 -r168 -r169 -r170 +r306 +r316 +r321
		da1_2_4_5_xdt = 0.0 -r171 -r172 -r173 -r174 +r297 +r325 +r330
		da1_2_4_6_xdt = 0.0 -r175 -r176 -r177 -r178 +r302 +r326 +r335
		da1_2_4_7_xdt = 0.0 -r179 -r180 -r181 -r182 +r307 +r331 +r336
		da1_2_5_6_xdt = 0.0 -r183 -r184 -r185 -r186 +r312 +r327 +r340
		da1_2_5_7_xdt = 0.0 -r187 -r188 -r189 -r190 +r317 +r332 +r341
		da1_2_6_7_xdt = 0.0 -r191 -r192 -r193 -r194 +r322 +r337 +r342
		da1_3_4_5_xdt = 0.0 -r195 -r196 -r197 -r198 +r298 +r345 +r350
		da1_3_4_6_xdt = 0.0 -r199 -r200 -r201 -r202 +r303 +r346 +r355
		da1_3_4_7_xdt = 0.0 -r203 -r204 -r205 -r206 +r308 +r351 +r356
		da1_3_5_6_xdt = 0.0 -r207 -r208 -r209 -r210 +r313 +r347 +r360
		da1_3_5_7_xdt = 0.0 -r211 -r212 -r213 -r214 +r318 +r352 +r361
		da1_3_6_7_xdt = 0.0 -r215 -r216 -r217 -r218 +r323 +r357 +r362
		da1_4_5_6_xdt = 0.0 -r219 -r220 -r221 -r222 +r328 +r348 +r365
		da1_4_5_7_xdt = 0.0 -r223 -r224 -r225 -r226 +r333 +r353 +r366
		da1_4_6_7_xdt = 0.0 -r227 -r228 -r229 -r230 +r338 +r358 +r367
		da1_5_6_7_xdt = 0.0 -r231 -r232 -r233 -r234 +r343 +r363 +r368
		da2_3_4_5_xdt = 0.0 -r235 -r236 -r237 -r238 +r299 +r370 +r375
		da2_3_4_6_xdt = 0.0 -r239 -r240 -r241 -r242 +r304 +r371 +r380
		da2_3_4_7_xdt = 0.0 -r243 -r244 -r245 -r246 +r309 +r376 +r381
		da2_3_5_6_xdt = 0.0 -r247 -r248 -r249 -r250 +r314 +r372 +r385
		da2_3_5_7_xdt = 0.0 -r251 -r252 -r253 -r254 +r319 +r377 +r386
		da2_3_6_7_xdt = 0.0 -r255 -r256 -r257 -r258 +r324 +r382 +r387
		da2_4_5_6_xdt = 0.0 -r259 -r260 -r261 -r262 +r329 +r373 +r390
		da2_4_5_7_xdt = 0.0 -r263 -r264 -r265 -r266 +r334 +r378 +r391
		da2_4_6_7_xdt = 0.0 -r267 -r268 -r269 -r270 +r339 +r383 +r392
		da2_5_6_7_xdt = 0.0 -r271 -r272 -r273 -r274 +r344 +r388 +r393
		da3_4_5_6_xdt = 0.0 -r275 -r276 -r277 -r278 +r349 +r374 +r395
		da3_4_5_7_xdt = 0.0 -r279 -r280 -r281 -r282 +r354 +r379 +r396
		da3_4_6_7_xdt = 0.0 -r283 -r284 -r285 -r286 +r359 +r384 +r397
		da3_5_6_7_xdt = 0.0 -r287 -r288 -r289 -r290 +r364 +r389 +r398
		da4_5_6_7_xdt = 0.0 -r291 -r292 -r293 -r294 +r369 +r394 +r399
		da1_2_3_4_5_xdt = 0.0 -r295 -r296 -r297 -r298 -r299 +r400 +r406
		da1_2_3_4_6_xdt = 0.0 -r300 -r301 -r302 -r303 -r304 +r401 +r412
		da1_2_3_4_7_xdt = 0.0 -r305 -r306 -r307 -r308 -r309 +r407 +r413
		da1_2_3_5_6_xdt = 0.0 -r310 -r311 -r312 -r313 -r314 +r402 +r418
		da1_2_3_5_7_xdt = 0.0 -r315 -r316 -r317 -r318 -r319 +r408 +r419
		da1_2_3_6_7_xdt = 0.0 -r320 -r321 -r322 -r323 -r324 +r414 +r420
		da1_2_4_5_6_xdt = 0.0 -r325 -r326 -r327 -r328 -r329 +r403 +r424
		da1_2_4_5_7_xdt = 0.0 -r330 -r331 -r332 -r333 -r334 +r409 +r425
		da1_2_4_6_7_xdt = 0.0 -r335 -r336 -r337 -r338 -r339 +r415 +r426
		da1_2_5_6_7_xdt = 0.0 -r340 -r341 -r342 -r343 -r344 +r421 +r427
		da1_3_4_5_6_xdt = 0.0 -r345 -r346 -r347 -r348 -r349 +r404 +r430
		da1_3_4_5_7_xdt = 0.0 -r350 -r351 -r352 -r353 -r354 +r410 +r431
		da1_3_4_6_7_xdt = 0.0 -r355 -r356 -r357 -r358 -r359 +r416 +r432
		da1_3_5_6_7_xdt = 0.0 -r360 -r361 -r362 -r363 -r364 +r422 +r433
		da1_4_5_6_7_xdt = 0.0 -r365 -r366 -r367 -r368 -r369 +r428 +r434
		da2_3_4_5_6_xdt = 0.0 -r370 -r371 -r372 -r373 -r374 +r405 +r436
		da2_3_4_5_7_xdt = 0.0 -r375 -r376 -r377 -r378 -r379 +r411 +r437
		da2_3_4_6_7_xdt = 0.0 -r380 -r381 -r382 -r383 -r384 +r417 +r438
		da2_3_5_6_7_xdt = 0.0 -r385 -r386 -r387 -r388 -r389 +r423 +r439
		da2_4_5_6_7_xdt = 0.0 -r390 -r391 -r392 -r393 -r394 +r429 +r440
		da3_4_5_6_7_xdt = 0.0 -r395 -r396 -r397 -r398 -r399 +r435 +r441
		da1_2_3_4_5_6_xdt = 0.0 -r400 -r401 -r402 -r403 -r404 -r405 +r442
		da1_2_3_4_5_7_xdt = 0.0 -r406 -r407 -r408 -r409 -r410 -r411 +r443
		da1_2_3_4_6_7_xdt = 0.0 -r412 -r413 -r414 -r415 -r416 -r417 +r444
		da1_2_3_5_6_7_xdt = 0.0 -r418 -r419 -r420 -r421 -r422 -r423 +r445
		da1_2_4_5_6_7_xdt = 0.0 -r424 -r425 -r426 -r427 -r428 -r429 +r446
		da1_3_4_5_6_7_xdt = 0.0 -r430 -r431 -r432 -r433 -r434 -r435 +r447
		da2_3_4_5_6_7_xdt = 0.0 -r436 -r437 -r438 -r439 -r440 -r441 +r448
		da1_2_3_4_5_6_7_xdt = 0.0 -r442 -r443 -r444 -r445 -r446 -r447 -r448
		dxdt = r1+r2+r3+r4+r5+r6+r7+r8+r9+r10+r11+r12+r13+r14+r15+r16+r17+r18+r19+r20+r21+r22+r23+r24+r25+r26+r27+r28+r29+r30+r31+r32+r33+r34+r35+r36+r37+r38+r39+r40+r41+r42+r43+r44+r45+r46+r47+r48+r49+r50+r51+r52+r53+r54+r55+r56+r57+r58+r59+r60+r61+r62+r63+r64+r65+r66+r67+r68+r69+r70+r71+r72+r73+r74+r75+r76+r77+r78+r79+r80+r81+r82+r83+r84+r85+r86+r87+r88+r89+r90+r91+r92+r93+r94+r95+r96+r97+r98+r99+r100+r101+r102+r103+r104+r105+r106+r107+r108+r109+r110+r111+r112+r113+r114+r115+r116+r117+r118+r119+r120+r121+r122+r123+r124+r125+r126+r127+r128+r129+r130+r131+r132+r133+r134+r135+r136+r137+r138+r139+r140+r141+r142+r143+r144+r145+r146+r147+r148+r149+r150+r151+r152+r153+r154+r155+r156+r157+r158+r159+r160+r161+r162+r163+r164+r165+r166+r167+r168+r169+r170+r171+r172+r173+r174+r175+r176+r177+r178+r179+r180+r181+r182+r183+r184+r185+r186+r187+r188+r189+r190+r191+r192+r193+r194+r195+r196+r197+r198+r199+r200+r201+r202+r203+r204+r205+r206+r207+r208+r209+r210+r211+r212+r213+r214+r215+r216+r217+r218+r219+r220+r221+r222+r223+r224+r225+r226+r227+r228+r229+r230+r231+r232+r233+r234+r235+r236+r237+r238+r239+r240+r241+r242+r243+r244+r245+r246+r247+r248+r249+r250+r251+r252+r253+r254+r255+r256+r257+r258+r259+r260+r261+r262+r263+r264+r265+r266+r267+r268+r269+r270+r271+r272+r273+r274+r275+r276+r277+r278+r279+r280+r281+r282+r283+r284+r285+r286+r287+r288+r289+r290+r291+r292+r293+r294+r295+r296+r297+r298+r299+r300+r301+r302+r303+r304+r305+r306+r307+r308+r309+r310+r311+r312+r313+r314+r315+r316+r317+r318+r319+r320+r321+r322+r323+r324+r325+r326+r327+r328+r329+r330+r331+r332+r333+r334+r335+r336+r337+r338+r339+r340+r341+r342+r343+r344+r345+r346+r347+r348+r349+r350+r351+r352+r353+r354+r355+r356+r357+r358+r359+r360+r361+r362+r363+r364+r365+r366+r367+r368+r369+r370+r371+r372+r373+r374+r375+r376+r377+r378+r379+r380+r381+r382+r383+r384+r385+r386+r387+r388+r389+r390+r391+r392+r393+r394+r395+r396+r397+r398+r399+r400+r401+r402+r403+r404+r405+r406+r407+r408+r409+r410+r411+r412+r413+r414+r415+r416+r417+r418+r419+r420+r421+r422+r423+r424+r425+r426+r427+r428+r429+r430+r431+r432+r433+r434+r435+r436+r437+r438+r439+r440+r441+r442+r443+r444+r445+r446+r447+r448
		return [dadt, dxdt, da1_xdt, da2_xdt, da3_xdt, da4_xdt, da5_xdt, da6_xdt, da7_xdt, da1_2_xdt, da1_3_xdt, da1_4_xdt, da1_5_xdt, da1_6_xdt, da1_7_xdt, da2_3_xdt, da2_4_xdt, da2_5_xdt, da2_6_xdt, da2_7_xdt, da3_4_xdt, da3_5_xdt, da3_6_xdt, da3_7_xdt, da4_5_xdt, da4_6_xdt, da4_7_xdt, da5_6_xdt, da5_7_xdt, da6_7_xdt, da1_2_3_xdt, da1_2_4_xdt, da1_2_5_xdt, da1_2_6_xdt, da1_2_7_xdt, da1_3_4_xdt, da1_3_5_xdt, da1_3_6_xdt, da1_3_7_xdt, da1_4_5_xdt, da1_4_6_xdt, da1_4_7_xdt, da1_5_6_xdt, da1_5_7_xdt, da1_6_7_xdt, da2_3_4_xdt, da2_3_5_xdt, da2_3_6_xdt, da2_3_7_xdt, da2_4_5_xdt, da2_4_6_xdt, da2_4_7_xdt, da2_5_6_xdt, da2_5_7_xdt, da2_6_7_xdt, da3_4_5_xdt, da3_4_6_xdt, da3_4_7_xdt, da3_5_6_xdt, da3_5_7_xdt, da3_6_7_xdt, da4_5_6_xdt, da4_5_7_xdt, da4_6_7_xdt, da5_6_7_xdt, da1_2_3_4_xdt, da1_2_3_5_xdt, da1_2_3_6_xdt, da1_2_3_7_xdt, da1_2_4_5_xdt, da1_2_4_6_xdt, da1_2_4_7_xdt, da1_2_5_6_xdt, da1_2_5_7_xdt, da1_2_6_7_xdt, da1_3_4_5_xdt, da1_3_4_6_xdt, da1_3_4_7_xdt, da1_3_5_6_xdt, da1_3_5_7_xdt, da1_3_6_7_xdt, da1_4_5_6_xdt, da1_4_5_7_xdt, da1_4_6_7_xdt, da1_5_6_7_xdt, da2_3_4_5_xdt, da2_3_4_6_xdt, da2_3_4_7_xdt, da2_3_5_6_xdt, da2_3_5_7_xdt, da2_3_6_7_xdt, da2_4_5_6_xdt, da2_4_5_7_xdt, da2_4_6_7_xdt, da2_5_6_7_xdt, da3_4_5_6_xdt, da3_4_5_7_xdt, da3_4_6_7_xdt, da3_5_6_7_xdt, da4_5_6_7_xdt, da1_2_3_4_5_xdt, da1_2_3_4_6_xdt, da1_2_3_4_7_xdt, da1_2_3_5_6_xdt, da1_2_3_5_7_xdt, da1_2_3_6_7_xdt, da1_2_4_5_6_xdt, da1_2_4_5_7_xdt, da1_2_4_6_7_xdt, da1_2_5_6_7_xdt, da1_3_4_5_6_xdt, da1_3_4_5_7_xdt, da1_3_4_6_7_xdt, da1_3_5_6_7_xdt, da1_4_5_6_7_xdt, da2_3_4_5_6_xdt, da2_3_4_5_7_xdt, da2_3_4_6_7_xdt, da2_3_5_6_7_xdt, da2_4_5_6_7_xdt, da3_4_5_6_7_xdt, da1_2_3_4_5_6_xdt, da1_2_3_4_5_7_xdt, da1_2_3_4_6_7_xdt, da1_2_3_5_6_7_xdt, da1_2_4_5_6_7_xdt, da1_3_4_5_6_7_xdt, da2_3_4_5_6_7_xdt, da1_2_3_4_5_6_7_xdt]
	res = solve_ivp(lambda t, y: ode_multisite_1_to_7(y,t,kd1, kd2, kd3, kd4, kd5, kd6, kd7), interval, [a, x,0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]).y[2:,-1]
	return (1*(sum(res[0:7]))+2*(sum(res[7:28]))+3*(sum(res[28:63]))+4*(sum(res[63:98]))+5*(sum(res[98:119]))+6*(sum(res[119:126]))+7*res[126])/x

max_stars_repo_name: stevenshave/kinetic-multisite-binding

max_issues_repo_name: stevenshave/kinetic-multisite-binding

max_forks_repo_name: stevenshave/kinetic-multisite-binding

reason: import numpy,from scipy


text:
### LIBRARIES ###
# Global libraries
import os
import json
from termcolor import colored
from tqdm import tqdm

import numpy as np

import torch

# Custom libraries
from .get_node_embedding import NumberbatchConverter, GloveConverter
from .extract_infos import extract_nodes, compute_node_dictionary, compute_neighborhoods
from conceptBert.vilbert import get_txt_questions

### CLASS DEFINITION ###
class ConceptNet:
    """
        Class represents the ConceptNet graph

        Methods:
            - clean_nodes(): removes nodes that don't have any embedding in the chosen embedding method
            - test_has_embedding(node): tests if a given node has an embedding; returns it if it has one
            - get_node_embedding(node): given a node (word), returns its embedding
            - compute_wl_embedding(n_iterations): computes the Weisfeiler-Lehman embedding of each node, with `n_iterations` updates
            - get_wl_embedding(word): returns the previously-computed Weisfeiler-Lehman embedding of the given node
    """

    def __init__(self, embedding_method, split=None):
        """
        """
        # Loading the nodes
        print(colored("Loading the list of nodes...", "yellow"))
        if not os.path.exists(
            "/nas-data/vilbert/data2/conceptnet/processed/en_nodes.json"
        ):
            extract_nodes()
        with open(
            "/nas-data/vilbert/data2/conceptnet/processed/en_nodes.json", "r"
        ) as json_file:
            self.list_nodes = json.load(json_file)

        # Loading the node dictionary
        print(colored("Loading the dictionary of nodes...", "yellow"))
        if not os.path.exists(
            "/nas-data/vilbert/data2/conceptnet/processed/en_nodes_dictionary.json"
        ):
            compute_node_dictionary()
        with open(
            "/nas-data/vilbert/data2/conceptnet/processed/en_nodes_dictionary.json",
            "r",
        ) as json_file:
            self.nodes_dictionary = json.load(json_file)

        # Loading the nodes' neighborhoods
        print(colored("Loading the node neighborhoods...", "yellow"))
        if not os.path.exists(
            "/nas-data/vilbert/data2/conceptnet/processed/en_dict_neighbors.json"
        ):
            compute_neighborhoods()
        with open(
           "/nas-data/vilbert/data2/conceptnet/processed/en_dict_neighbors.json",
            "r",
        ) as json_file:
            dict_neighbors = json.load(json_file)

        self.dict_neighbors = {}
        for node, list_neighbors in dict_neighbors.items():
            self.dict_neighbors[node] = []
            for neighbor in list_neighbors:
                self.dict_neighbors[node].append(
                    [self.list_nodes[neighbor[0]], neighbor[1]]
                )

        # Loading the embedding method
        print(colored("Loading the embedding method...", "yellow"))
        if embedding_method == "glove":
            self.embedding_method = GloveConverter()
        elif embedding_method == "numberbatch":
            self.embedding_method = NumberbatchConverter()

        self.dim_word = len(self.embedding_method.convert_word_to_embedding("the"))

        # Variables for statistics
        self.count = 0
        self.created = 0
        self.counter = 0
        self.ok_count = 0

        # Filter the nodes, so that every node has an embedding
        self.filtered_dict_neighbors = self.clean_nodes()

        # Load the question texts
        if split != None:
            print(colored("Loading question texts...", "yellow"))
            self.token_dictionary = get_txt_questions(split)

    def clean_nodes(self):
        """
            Removes nodes if they don't have an embedding and they have less than two neighbors with an embedding
        """
        filtered_dict_neighbors = {}
        memory_node_embeddings = {}

        progress_bar = tqdm(total=len(self.dict_neighbors), desc="Filtering the nodes")

        for node, list_neighbors in self.dict_neighbors.items():
            if node in memory_node_embeddings:
                node_embedding = memory_node_embeddings[node]
            else:
                node_embedding = self.test_has_embedding(node)
                memory_node_embeddings[node] = node_embedding

            # Check if node has an embedding
            if type(self.test_has_embedding(node)) != bool:
                self.ok_count += 1
                filtered_dict_neighbors[node] = node_embedding

            else:
                self.counter += 1
                # The node doesn't have an embedding: check if at least two nodes have an embedding
                count_embeddings = 0
                sum_vectors = np.zeros(self.dim_word)
                for neighbor in list_neighbors:
                    if neighbor[0] in memory_node_embeddings:
                        neighbor_embedding = memory_node_embeddings[neighbor[0]]
                    else:
                        neighbor_embedding = self.test_has_embedding(neighbor[0])
                        memory_node_embeddings[neighbor[0]] = neighbor_embedding

                    if type(neighbor_embedding) != bool:
                        count_embeddings += 1
                        sum_vectors += neighbor_embedding

                if count_embeddings >= 2:
                    # More than 2 neighbors with an embedding, so we can generate an embedding for this node
                    filtered_dict_neighbors[node] = np.true_divide(
                        sum_vectors, count_embeddings
                    )
                    self.created += 1

            progress_bar.update(1)
        progress_bar.close()

        return filtered_dict_neighbors

    def test_has_embedding(self, node):
        """
            Tests if a given node has an embedding
        """
        try:
            node_embedding = self.get_node_embedding(node)
            if len(node_embedding) == 0:
                pass
            return node_embedding
        except:
            return False

    def get_node_embedding(self, word):
        """
            Given a node (word), return its embedding
        """
        try:
            return self.embedding_method.convert_word_to_embedding(word)
        except:
            self.count += 1

    def compute_wl_embedding(self, n_iterations):
        """
            Computes the Weisfeiler-Lehman continuous embedding for each node
        """
        self.wl_embedding = {}

        # Initialize with the previously computed embeddings
        for node in self.filtered_dict_neighbors:
            self.wl_embedding[node] = np.array(self.filtered_dict_neighbors[node])

        # Start the Weisfeiler-Lehman algorithm
        for _ in tqdm(range(n_iterations), desc="Iterations", position=0, leave=False):
            for node in tqdm(
                self.filtered_dict_neighbors,
                desc="Nodes updates",
                position=1,
                leave=False,
            ):
                neighbors_list = self.dict_neighbors[node]
                new_wl_embedding = 0
                total_weight = 0

                for neighbor in neighbors_list:
                    if neighbor[0] in self.filtered_dict_neighbors:
                        n_name, n_weight = neighbor
                        new_wl_embedding += n_weight * self.wl_embedding[n_name]
                        total_weight += n_weight

                # Normalizes update using the total weight
                if total_weight != 0:
                    new_wl_embedding = np.true_divide(new_wl_embedding, total_weight)

                new_wl_embedding = 0.5 * (
                    self.wl_embedding[node] + new_wl_embedding / len(neighbors_list)
                )

                self.wl_embedding[node] = new_wl_embedding

    def get_wl_embedding(self, word):
        """
            Returns the Weisfeiler-Lehman continuous embedding of the given node
        """
        try:
            return self.wl_embedding[word]
        except Exception as e:
            # print(colored("ERROR: {}".format(e), "red"))
            pass

    def get_wl_embedding_tensor(self, word):
        """
            Returns the Weisfeiler-Lehman continuous embedding (in a tensor) of the given node
        """
        try:
            return torch.from_numpy(self.wl_embedding[word]).double()
        except Exception as e:
            # print(colored("ERROR: {}".format(e), "red"))
            return torch.zeros(self.dim_word).double()

    def get_wl_embedding_from_q_id(self, list_q_ids, dim1, dim2):
        """
            Given a list of quetion IDs, returns the embeddings of each word in every question
        """

        # Go through the question IDs; for each question ID, load the words in it
        from copy import deepcopy
        question_txt = []
        question_id = deepcopy(list_q_ids)
        question_id = question_id.tolist()

        question_embedding = []

        for q_id in question_id:
            question_wl_embedding = []
            sentence = self.dict_txt_questions[q_id]
            print("QUESTION ID (q_id): ", q_id)
            print("SENTENCE: ", sentence)
            list_words = sentence.split(" ")
            for word in list_words:
                word_wl_embedding = self.get_wl_embedding_tensor(word)
                target_emb = torch.zeros((dim2))
                target_emb[:word_wl_embedding.size(0)] = word_wl_embedding
                question_wl_embedding.append(word_wl_embedding)

            q_emb = torch.stack(question_wl_embedding)
            target_wl = torch.zeros((dim1, dim2))
            target_wl[:q_emb.size(0), :q_emb.size(1)] = q_emb
            question_embedding.append(target_wl)

        return torch.stack(question_embedding)

    def get_wl_embedding_tokens(self, input_ids, dim1, dim2):
        """
            Given a list of tokens, returns the WL embedding of each word
        """
        wl_embedding = []

        # from copy import deepcopy
        # input_ids_copy = deepcopy(input_ids)
        # input_ids_copy = input_ids_copy.tolist()
        input_ids = input_ids.tolist()

        # for question in input_ids_copy:
        for question in input_ids:
            question_embedding = []
            for word_token in question:
                try:
                    word = self.token_dictionary[word_token]
                    word_wl_emb = self.get_wl_embedding_tensor(word)
                except:
                    word_wl_emb = torch.zeros(self.dim_word).double()
                target_emb = torch.zeros((dim2))
                target_emb[:word_wl_emb.size(0)] = word_wl_emb
                question_embedding.append(word_wl_emb)

            question_wl_emb = torch.stack(question_embedding)
            target_wl = torch.zeros((dim1, dim2))
            target_wl[:question_wl_emb.size(0), :question_wl_emb.size(1)] = question_wl_emb
            wl_embedding.append(target_wl)

        return torch.stack(wl_embedding)

    # def get_graph_embedding(self):
    #     """
    #         Returns a matrix, which is the embedding of the graph
    #     """
    #     try:
    #         return self.graph_embedding
    #     except:
    #         list_node_embeddings = []
    #
    #         for node in self.list_nodes:
    #             node_embedding = self.get_wl_embedding_tensor(node).float()
    #             list_node_embeddings.append(node_embedding)
    #         self.graph_embedding = torch.stack(list_node_embeddings)
    #
    #         return self.graph_embedding

ext: py

max_stars_repo_name: ThalesGroup/ConceptBERT

max_issues_repo_name: ThalesGroup/ConceptBERT

max_forks_repo_name: ThalesGroup/ConceptBERT

reason: import numpy


text:
#!/usr/bin/python3
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
import numpy as np

# Menu
def main():
    while(True):
        choice = int(input("Escolha a questão a exibir {1, 2, 3, 4, 5, 6, 7} \n0 para sair:\n"))

        if choice == 1:
            questOne()
        elif choice == 2:
            questTwo()
        elif choice == 3:
            questThree()
        elif choice == 4:
            questFour()
        elif choice == 5:
            questFive()
        elif choice == 6:
            questSix()
        elif choice == 7:
            questSeven()
        elif choice == 0:
            break

## Questão 1
def questOne():
    data = pd.read_csv("data/weight_chart.txt", usecols=['Age', 'Weight'], delim_whitespace=True) # Lendo os dados do arquivo

    data.plot.line(x='Age', y='Weight', marker='o', markerfacecolor='white', color="#000000", legend=False)

    #Alterando o limite do eixo y entre 1 e 11
    plt.ylim(1,11)

    plt.xlabel("Age (months)") # Texto do eixo x
    plt.ylabel("Weight (kg)") # Texto do eixo y
    plt.title("The relationship between age and weight in a growing infant", fontweight="bold") # Titulo do gráfico
    plt.savefig("Quest1.png") # Salvando a figura
    plt.show() # Exibindo o gráfico

## Questão 2
def questTwo():
    data = pd.read_csv("data/feature_counts.txt", delim_whitespace=True)

    # Separando eixo da figura para alterar as bordas do eixo cartesiano
    fig, ax = plt.subplots()
    ax.spines["right"].set_visible(False)
    ax.spines["top"].set_visible(False)

    data.plot.barh(x='Feature', y='Count', legend=False, color="lightgray", edgecolor='black', ax=ax)

    # Alterando os pontos exibidos no gráfico em X
    plt.xticks([0, (2*10**4), (4*10**4),(6*10**4)])

    plt.xlabel("Number of features")
    plt.tight_layout()
    plt.savefig("Quest2.png")
    plt.show()

    del fig
    del ax

## Questão 3
def questThree():
    data1 = np.random.normal(size=10**4)
    data2 = np.random.normal(loc=4, size=10**4)
    data = np.concatenate([data1, data2])

    fig, ax = plt.subplots()
    ax.spines["right"].set_visible(False)
    ax.spines["top"].set_visible(False)

    plt.hist(data, bins=100, edgecolor='black', color="lightgray")

    # Limitando o gráfico no eixo x entre -4 e 8
    plt.xlim(-4,8)

    plt.title("Mixed distribution histogram", fontweight="bold")
    plt.ylabel("Frequency")
    plt.xlabel("Values")
    plt.savefig("Quest3.png")
    plt.show()

    del fig
    del ax

## Questão 4
def questFour():
    data = pd.read_csv("data/male_female_counts.txt", delim_whitespace=True)

    colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
                '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']

    fig, ax = plt.subplots()
    ax.spines["right"].set_visible(False)
    ax.spines["top"].set_visible(False)

    data.plot.bar(x='Sample', y='Count', legend=False, color=colors, ax=ax)

    # Alterando os pontos exibidos no gráfico em Y
    plt.yticks([0, 5, 10, 15])

    # Alterando a rotação e o tamanho dos pontos exibidos no gráfico em X
    plt.xticks(rotation=0, fontsize=8)

    plt.xlabel("")
    plt.tight_layout()
    plt.savefig("Quest4.png")
    plt.show()

    del fig
    del ax

## Questão 5
def colorScatter(stateArray):
    output = []

    for x in stateArray:
        if x == "up":
            output.append("red")
        elif x == "down":
            output.append("blue")
        else:
            output.append("gray")

    return output

def questFive():
    data = pd.read_csv("data/up_down_expression.txt", delim_whitespace=True)

    ## Definindo a cor do ponto baseado no 'State'
    colorArray = colorScatter(data['State'])

    data.plot.scatter(x='Condition1', y='Condition2', c=colorArray, s=4)

    plt.yticks([0, 5, 10])
    plt.xticks([0, 5, 10])
    plt.savefig("Quest5.png")
    plt.show()

## Questão 6
def questSix():
    data = pd.read_csv("data/chromosome_position_data.txt", delim_whitespace=True)

    # Defininfo ax subsequentes para serem plotados no mesmo plano
    ax = data.plot.line(x='Position', y='Mut1', color="red")
    data.plot.line(x='Position', y='Mut2', ax=ax, color="blue")
    data.plot.line(x='Position', y='WT', ax=ax, color="limegreen")

    # Alterando simbolo das legendas
    legend_elements = [
        Patch(facecolor="red", edgecolor="black", label="Mut1"),
        Patch(facecolor="blue", edgecolor="black", label="Mut2"),
        Patch(facecolor="limegreen", edgecolor="black", label="WT"),
    ]
    plt.legend(handles=legend_elements, loc="upper left")

    plt.xlabel("Position within chromosome")
    plt.ylabel("Value")
    plt.gca().get_xaxis().get_major_formatter().set_scientific(False) # Desabilitando notação científica
    plt.savefig("Quest6.png")
    plt.show()

    del ax

## Questão 7
def questSeven():
    data = pd.read_csv("data/brain_bodyweight.txt", delim_whitespace=True)

    plt.errorbar(
        x=data['Brainweight'], y=data['Bodyweight'], xerr=data['Brainweight.SEM'],
        yerr=data['Bodyweight.SEM'], marker="D", markersize=3 , color="black", ls='none', capsize=5
    )
    # Adicionando texto embaixo do ponto
    for i, txt in enumerate(data['Species']):
        plt.annotate(txt, (data['Brainweight'][i], data['Bodyweight'][i]-0.25), size=5, ha='center')

    plt.xlabel("Brain weight")
    plt.ylabel("Body weight")
    plt.savefig("Quest7.png")
    plt.show()

# Chamando função principal (menu)
main()

max_stars_repo_name: MarechalLima/fictional-palm-tree

max_issues_repo_name: MarechalLima/fictional-palm-tree

max_forks_repo_name: MarechalLima/fictional-palm-tree


text:
import dash
import dash_core_components as dcc
import dash_bootstrap_components as dbc
import dash_html_components as html
import numpy as np
import json
import plotly.graph_objects as go
from dash.dependencies import Input, Output, State
from ampere import SingleParticleFD, SingleParticleFDSEI
from ampere.base_battery import ChargeResult
from scipy.interpolate import interp1d
from plotly.subplots import make_subplots
from colour import Color

def init_page(app):
    layout = html.Div([
        html.H1('Single Particle Model'),
        html.Div([], style={'height': '30px'}),
        dcc.Markdown(
            children='A model walkthrough is available for the [SPM Model](/articles/spm/), and the code that powers this interactive page is available in the python package [Ampere](/articles/ampere/)'),
        html.Div([], style={'height': '30px'}),
        html.Img(src='/img/spm/spm_3d.png'),
        html.Div([], style={'height': '30px'}),
        html.P('Select a current for the simulation below.'),
        dcc.Slider(id='spm-current', min=-10, max=10, value=4, step=0.1, updatemode='drag',
                   marks={i: f'{i} amps' for i in range(-10, 12, 2)}),
        html.Div([], style={'height': '30px'}),
        dbc.Button('Run Simulation', id='spm-start-button'),

        html.Div(id='spm-main-plots'),
        html.Div(id='spm-data-div', style={'display': 'none'})
    ])

    @app.callback([Output('spm-main-plots', 'children'),
                   Output('spm-data-div', 'children')],
                  [Input('spm-start-button', 'n_clicks')],
                  [State('spm-current', 'value')])
    def spm_callback(n_clicks, amps):
        if amps != 0:
            spm = SingleParticleFD()
            # run simulation with internal variables
            if amps > 0:
                amps = max(amps, 0.2)
                data = spm.discharge(current=amps, internal=True, trim=True)
            if amps <= 0:
                amps = min(amps, -0.2)
                data = spm.charge(current=abs(amps), internal=True, trim=True)

            internal_data = data.internal
            raw_times = internal_data[:, 0]
            delta_time = np.diff(raw_times)
            total_capacity = round(abs(delta_time * internal_data[1:, -1]).sum() / 3600 / 30, 2) # convert from seconds to hours

            start_color = "#b2d8ff"  # light blue
            end_color = "#00264c"  # dark blue

            # list of "N" colors between "start_color" and "end_color"
            colorscale = [x.hex for x in list(Color(start_color).range_to(Color(end_color), 5))][::-1]
            light_green = 'rgb(33, 209, 59)'
            dark_green = 'darkgreen'

            positive_potential = linearly_interpolate_concentrations(data.time, raw_times, internal_data[:, -4:-3])
            negative_potential = linearly_interpolate_concentrations(data.time, raw_times, internal_data[:, -3:-2])
            data = ChargeResult(data.time, data.voltage, None, None)

            pos_electrode = spm.initial_parameters['N1']
            neg_electrode = spm.initial_parameters['N2']
            initial_time = 1
            voltage_fig = go.Figure()
            voltage_fig.add_trace(go.Scatter(x=data.time, y=data.voltage, mode='lines', name='Voltage', marker={'color': dark_green}))
            voltage_fig.add_trace(go.Scatter(x=[data.time[initial_time], data.time[initial_time]], y=[2, 4.2], mode='lines', name='Time Slice', marker={'color': 'darkgrey'}))
            voltage_fig.update_layout(
                margin=dict(l=55, r=20, t=60, b=20),
                paper_bgcolor="rgb(240, 240, 240)",
                plot_bgcolor='rgb(220, 220, 220)',
                width=1000,
                height=350,
                title=f'Discharge Voltage vs Time at {amps} Amps with Current Time Indicator',
                xaxis_title="Time (s)",
                legend=dict(
                    x=0,
                    y=.5,
                    traceorder="normal",
                    font=dict(
                        family="sans-serif",
                        size=12,
                        color="black"
                    ),
                ),
            )

            internal_pot_fig = make_subplots(specs=[[{"secondary_y": True}]])

            internal_pot_fig.add_trace(go.Scatter(x=data.time, y=positive_potential.T[0], mode='lines', name='Positive Electrode Potential', marker={'color': dark_green}), secondary_y=False)
            internal_pot_fig.add_trace(go.Scatter(x=[data.time[4]], y=[positive_potential.T[0][4]], mode='markers', name='Current PE Potential', marker={'color': light_green, 'size': 10}), secondary_y=False)
            internal_pot_fig.add_trace(go.Scatter(x=data.time, y=negative_potential.T[0], mode='lines', name='Negative Electrode Potential', marker={'color': colorscale[0]}), secondary_y=True)
            internal_pot_fig.add_trace(go.Scatter(x=[data.time[4]], y=[negative_potential.T[0][4]], mode='markers', name='Current NE Potential', marker={'color': colorscale[1], 'size': 10}), secondary_y=True)
            internal_pot_fig.update_layout(
                margin=dict(l=55, r=20, t=60, b=20),
                paper_bgcolor="rgb(240, 240, 240)",
                plot_bgcolor='rgb(220, 220, 220)',
                width=1000,
                height=350,
                title='Positive and Negative Electrode Potentials',
                xaxis_title="Time (s)",
                legend=dict(
                    x=0.05,
                    y=.3,
                    traceorder="normal",
                    font=dict(
                        family="sans-serif",
                        size=12,
                        color="black"
                    ),
                ),
            )
            internal_pot_fig.update_yaxes(title_text="Positive Electrode Potential (V)", secondary_y=False)
            internal_pot_fig.update_yaxes(title_text="Negative Electrode Potential (V)", secondary_y=True)

            dict_data = {'voltage_data': {'time': list(data.time), 'voltage': list(data.voltage)}}

            pos_radius = np.linspace(0, 1, pos_electrode + 2) * spm.initial_parameters['Rp']
            neg_radius = np.linspace(0, 1, neg_electrode + 2) * spm.initial_parameters['Rn']

            pos_conc = internal_data[:, spm.internal_structure['positive_concentration']]
            pos_conc = linearly_interpolate_concentrations(data.time, raw_times, pos_conc) / spm.initial_parameters['cspmax']

            neg_conc = internal_data[:, spm.internal_structure['negative_concentration']]
            neg_conc = linearly_interpolate_concentrations(data.time, raw_times, neg_conc) / spm.initial_parameters['csnmax']

            pos_internal_fig = go.Figure()
            pos_internal_fig.add_trace(
                go.Scatter(x=pos_radius,
                           y=pos_conc[0, :].T,
                           mode='lines',
                           name='Original Li Concentration',
                           marker={'color': dark_green}))
            pos_internal_fig.add_trace(
                go.Scatter(x=pos_radius,
                           y=pos_conc[initial_time, :].T,
                           mode='lines',
                           name='Current Concentration',
                           marker={'color': light_green}))
            pos_internal_fig.update_layout(
                margin=dict(l=55, r=20, t=40, b=20),
                paper_bgcolor="rgb(240, 240, 240)",
                plot_bgcolor='rgb(220, 220, 220)',
                width=500,
                height=350,
                legend=dict(
                    x=0,
                    y=.5,
                    traceorder="normal",
                    font=dict(
                        family="sans-serif",
                        size=12,
                        color="black"
                    ),
                ),
                title='Positive Particle Li Concentration',
                xaxis_title="Distance From Center Of Particle (m)",
            )

            neg_internal_fig = go.Figure()
            neg_internal_fig.add_trace(go.Scatter(x=neg_radius,
                                                  y=neg_conc[0, :].T,
                                                  mode='lines',
                                                  name='Original Li Concentration',
                                                  marker={'color': colorscale[0]}))
            neg_internal_fig.add_trace(go.Scatter(x=neg_radius,
                                                  y=neg_conc[initial_time, :].T,
                                                  mode='lines',
                                                  name='Current Concentration',
                                                  marker={'color': colorscale[1]}))
            neg_internal_fig.update_layout(
                margin=dict(l=20, r=20, t=40, b=20),
                paper_bgcolor="rgb(240, 240, 240)",
                plot_bgcolor='rgb(220, 220, 220)',
                width=500,
                height=350,
                legend=dict(
                    x=0,
                    y=.3,
                    traceorder="normal",
                    font=dict(
                        family="sans-serif",
                        size=12,
                        color="black"
                    ),
                ),
                title='Negative Particle Li Concentration',
                xaxis_title="Distance From Center Of Particle (m)",
            )

            dict_data['internal_data'] = {
                'positive': [list(time_slice) for time_slice in pos_conc],
                'negative': [list(time_slice) for time_slice in neg_conc],
                'p_x': list(pos_radius),
                'n_x': list(neg_radius),
                'p_pot': list(positive_potential.T[0]),
                'n_pot': list(negative_potential.T[0])
            }

            l = html.Div([
                dbc.Row([
                    dcc.Graph(
                        id='spm-voltage-graph',
                        figure=voltage_fig
                    ),
                    html.Div([], style={'height': '40px'}),
                    html.P(f'Above is the discharge of the simulated battery. By scrubbing through time, you can examine the internal states of the cell. Based on the design parameters, the capacity of this cell is {total_capacity} AH'),
                    html.P('As current increases, the capacity will decrease due to Li depletion at the surface of the particles relative to total Li concentration.')
                ]),
                dcc.Slider(id='spm-time', min=0, max=len(data.time), value=4, step=1, updatemode='drag',
                           marks={i: f'{int(data.time[i])}s' for i in range(0, len(data.time), 30)}),
                dbc.Row([
                    html.Div([], style={'height': '20px'}),
                    html.P('During discharge, the positive electrode concentration rises. During charge, it falls.  The most interesting part of the discharge and charge is right at the beginning - Li is preferentially added or removed from the surface and the concentration gradients grow rapidly.  After a time, they become "pseudo-steady-state", and the entire curve moves upward or downward at a constant rate, with the relative values unchanged.'),
                    html.P('During charge, the same pattern occurs, but in reverse. However, as the current tapers off, the concentration gradients flatten out, allowing the battery to repeatedly reach the "full" state with only minor internal concentration gradients.'),
                    dcc.Graph(
                        id='spm-pos-graph',
                        figure=pos_internal_fig,
                        style={'width': '50%'}
                    ),
                    dcc.Graph(
                        id='spm-neg-graph',
                        figure=neg_internal_fig,
                        style={'width': '50%'}
                    ),
                ]),
                dbc.Row([
                    html.Div([], style={'height': '40px'}),
                    html.P('The potentials of the positive and negative electrode are based on the Li concentration at the surface of the particles that make up the electrode. It is the changing of these potentials that causes the battery voltage to change with use.'),
                    html.P('When we visualize the positive / negative electrode potentials like this, it becomes clear why the lithium-ion battery voltage seems to fall off a cliff as the battery nears empty - the negative electrode potential skyrockets as the particles near Lithium saturation.'),
                    dcc.Graph(
                        id='spm-potential-graph',
                        figure=internal_pot_fig
                    ),
                ]),
            ])

            return l, json.dumps(dict_data)
        return None, ''

    app.clientside_callback(
        """
        function(time, data) {
            // tuple is (dict of new data, target trace index, number of points to keep)
            const _data = JSON.parse(data)['voltage_data']['time'];
            return [{'x':[[_data[time], _data[time]]], 'y': [[2, 4.2]]}, [1], 2];
        }
        """, Output('spm-voltage-graph', 'extendData'), [Input('spm-time', 'value')], [State('spm-data-div', 'children')]
    )

    app.clientside_callback(
        """
        function(time, data) {
            // tuple is (dict of new data, target trace index, number of points to keep)
            const _data = JSON.parse(data);
            const _time = _data['voltage_data']['time'];
            const pot = _data['internal_data']['p_pot'];
            const npot = _data['internal_data']['n_pot'];
            return [{'x': [[_time[time]], [_time[time]]], 'y': [[pot[time]], [npot[time]]] }, [1, 3], 1];
        }
        """, Output('spm-potential-graph', 'extendData'), [Input('spm-time', 'value')],
        [State('spm-data-div', 'children')]
    )
    # @app.callback(Output('spm-potential-graph', 'extendData'), [Input('spm-time', 'value')],
    #     [State('spm-data-div', 'children')])
    # def update_potential(time, data):
    #     data = json.loads(data)
    #     _time = data['voltage_data']['time']
    #     pot = data['internal_data']['p_pot']
    #     npot = data['internal_data']['n_pot']
    #     return {'x': [[_time[time]], [_time[time]]], 'y': [[pot[time]], [npot[time]]]}, [1, 3], 1

    app.clientside_callback(
        """
        function(time, data) {
            // tuple is (dict of new data, target trace index, number of points to keep)
            const _data = JSON.parse(data);
            const positive = _data['internal_data']['positive'];
            const _px = _data['internal_data']['p_x'];
            return [{'x': [_px], 'y': [positive[time]]}, [1], _px.length];
        }
        """, Output('spm-pos-graph', 'extendData'), [Input('spm-time', 'value')],[State('spm-data-div', 'children')]
    )

    app.clientside_callback(
        """
        function(time, data) {
            // tuple is (dict of new data, target trace index, number of points to keep)
            const _data = JSON.parse(data);
            const negative = _data['internal_data']['negative'];
            const _nx = _data['internal_data']['n_x'];
            return [{'x': [_nx], 'y': [negative[time]]}, [1], _nx.length];
        }
        """, Output('spm-neg-graph', 'extendData'), [Input('spm-time', 'value')], [State('spm-data-div', 'children')]
    )

    return layout

def linearly_interpolate_concentrations(time, raw_time, concentrations):
    return np.concatenate([interp1d(raw_time, concentrations[:, i], kind='cubic', bounds_error=False)(time)[:, np.newaxis] for i in range(concentrations.shape[1])], axis=1)

max_stars_repo_name: nealde/dash-flask-application

max_issues_repo_name: nealde/dash-flask-application

max_forks_repo_name: nealde/dash-flask-application


text:
#!/usr/bin/python

'''
Purpose:
KaplanMeier Curves, logrank for mutational status

'''
import os
import lifelines
from lifelines import KaplanMeierFitter
from lifelines.statistics import logrank_test
import numpy as np
import pandas as pd

#-------------------------------------------------------------------------
def plotKaplanMeier(DF, GroupName):
	# Bring in matplotlib
	import matplotlib
	matplotlib.use('Agg')
	import matplotlib.pyplot as plt
	from matplotlib import colors
	matplotlib.style.use('seaborn-talk')
	import seaborn as sns
	# fit data
	sns.set(font_scale=.95)
	# plot baseline survival
	KMF = KaplanMeierFitter()
	# get log rank results
	Unique = sorted(DF[GroupName].unique())[::-1]
	G0 = Unique[0]
	G1 = Unique[1]
	Group0 = DF[DF[GroupName]==G0]
	Group1 = DF[DF[GroupName]==G1]
	LR_Results = logrank_test(Group0["OS (months)"].astype(float),
							Group1["OS (months)"].astype(float),
							Group0["Patient Status"].astype(int),
							Group1["Patient Status"].astype(int))
	# build figure
	fig, ax = plt.subplots(1,1,figsize=(7, 5))
	# add logrank to plot
	# iterate over unique groups and plot KM curves
	Median_Survival_List = []
	for Group in Unique:
		TempDF = DF[DF[GroupName]==Group]
		KMF = KaplanMeierFitter()
		KMF.fit(TempDF["OS (months)"].astype(float),
				TempDF["Patient Status"].astype(int),
				label=Group).plot(ax=ax)
		print("KMF.median_survival_time_", KMF.median_survival_time_)
		Median_Survival_List.append(float(KMF.median_survival_time_))
	Median_Survival_List = sorted(Median_Survival_List)
	Annotation = "logrank: "+str(round(LR_Results.test_statistic,3))+"\n"+\
					"pvalue: "+str(round(LR_Results.p_value,5))+"\n"+\
					"median survival times: "+str(Median_Survival_List)
	ax.text(.05, .05, Annotation,
			horizontalalignment='left',
			verticalalignment='bottom',
			transform=ax.transAxes)
	# set labels
	ax.set_xlabel("Time (months)")
	ax.set_ylabel("Overall survival probability")
	plt.tight_layout()
	fig.savefig("KaplanMeierSurvival.png")
	plt.clf()
	plt.close()
	return(LR_Results)

#------------------------------------------------------------------------------
def main():
	InputDF = pd.read_csv("InputData.txt",header="infer",sep="\t")
	plotKaplanMeier(DF, "MutationStatus")

#------------------------------------------------------------------------------
if __name__ == '__main__':
	# Parse the arguments
	main()


text:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 26 18:20:37 2018

@author: kazuki.onodera

separate gal & exgal

oversampling

"""

import numpy as np
import pandas as pd
import os, gc
from glob import glob
from tqdm import tqdm

import sys
sys.path.append(f'/home/{os.environ.get("USER")}/PythonLibrary')
import lgbextension as ex
import lightgbm as lgb
from multiprocessing import cpu_count

import utils, utils_metric
#utils.start(__file__)
#==============================================================================

SUBMIT_FILE_PATH = '../output/1126-1.csv.gz'

COMMENT = 'gal: 90 exgal: 112 / oversampling'

EXE_SUBMIT = True

SEED = np.random.randint(9999)
np.random.seed(SEED)
print('SEED:', SEED)

NFOLD = 5

LOOP = 3

param = {
         'objective': 'multiclass',
#         'num_class': 14,
         'metric': 'multi_logloss',

         'learning_rate': 0.5,
         'max_depth': 3,
         'num_leaves': 63,
         'max_bin': 255,

         'min_child_weight': 10,
         'min_data_in_leaf': 150,
         'reg_lambda': 0.5,  # L2 regularization term on weights.
         'reg_alpha': 0.5,  # L1 regularization term on weights.

         'colsample_bytree': 0.5,
         'subsample': 0.7,
#         'nthread': 32,
         'nthread': cpu_count(),
         'bagging_freq': 1,
         'verbose':-1,
         }

#USE_FEATURES = 100

# =============================================================================
# load
# =============================================================================
#COL_gal   = pd.read_csv('LOG/imp_802_cv_separate.py_gal.csv').head(USE_FEATURES ).feature.tolist()
#COL_exgal = pd.read_csv('LOG/imp_802_cv_separate.py_exgal.csv').head(USE_FEATURES ).feature.tolist()

COL_gal   = pd.read_pickle('../data/807_gal.pkl').columns.tolist()
COL_exgal = pd.read_pickle('../data/807_exgal.pkl').columns.tolist()

COL = list(set(COL_gal + COL_exgal))

PREFS = sorted(set([c.split('_')[0] for c in COL]))

files_tr = []
for pref in PREFS:
    files_tr += glob(f'../data/train_{pref}*.pkl')

files_te = [f'../feature/test_{c}.pkl' for c in COL]
files_te = sorted(files_te)
sw = False
for i in files_te:
    if os.path.exists(i)==False:
        print(i)
        sw = True
if sw:
    raise Exception()
else:
    print('all test file exist!')

X = pd.concat([
                pd.read_pickle(f) for f in tqdm(files_tr, mininterval=60)
               ], axis=1)[COL]
y = utils.load_target().target

target_dict = {}
target_dict_r = {}
for i,e in enumerate(y.sort_values().unique()):
    target_dict[e] = i
    target_dict_r[i] = e

y = y.replace(target_dict)

if X.columns.duplicated().sum()>0:
    raise Exception(f'duplicated!: { X.columns[X.columns.duplicated()] }')
print('no dup :) ')

gc.collect()

# =============================================================================
# separate
# =============================================================================

is_gal = pd.read_pickle('../data/tr_is_gal.pkl')

X_gal = X[is_gal][COL_gal]
y_gal = y[is_gal]

X_exgal = X[~is_gal][COL_exgal]
y_exgal = y[~is_gal]

def target_replace(y):
    target_dict = {}
    target_dict_r = {}
    for i,e in enumerate(y.sort_values().unique()):
        target_dict[e] = i
        target_dict_r[i] = e

    return y.replace(target_dict), target_dict_r

y_gal, di_gal = target_replace(y_gal)
y_exgal, di_exgal = target_replace(y_exgal)

del X, y
gc.collect()

print(f'X_gal.shape: {X_gal.shape}')
print(f'X_exgal.shape: {X_exgal.shape}')

# =============================================================================
# oversampling
# =============================================================================
"""
train:
    is_gal	False	True
    ddf
    0	3947	1785
    1	1576	540

test:
    is_gal	False	True
    ddf
    0	3069681	390283
    1	32699	227

(390283 / 227) / (1785 / 540) == 520
(3069681 / 32699) / (3947 / 1576) == 37

"""

print('oversampling')

from sklearn.model_selection import GroupKFold

is_ddf = pd.read_pickle('../data/train.pkl').ddf==1

# ======== for gal ========
X_gal['g'] = np.arange(X_gal.shape[0]) % NFOLD
X_gal_d0 = X_gal[~is_ddf]
X_gal_d1 = X_gal[is_ddf]
li = [X_gal_d0.copy() for i in range(520)]

X_gal = pd.concat([X_gal_d1]+li, ignore_index=True)

group_gal = X_gal.g

y_gal_d0 = y_gal[~is_ddf]
y_gal_d1 = y_gal[is_ddf]
li = [y_gal_d0.copy() for i in range(520)]
y_gal = pd.concat([y_gal_d1]+li, ignore_index=True)

del li, X_gal_d0, X_gal_d1, X_gal['g'], y_gal_d0, y_gal_d1

# ======== for exgal ========
X_exgal['g'] = np.arange(X_exgal.shape[0]) % NFOLD
X_exgal_d0 = X_exgal[~is_ddf]
X_exgal_d1 = X_exgal[is_ddf]
li = [X_exgal_d0.copy() for i in range(37)]

X_exgal = pd.concat([X_exgal_d1]+li, ignore_index=True)

group_exgal = X_exgal.g

y_exgal_d0 = y_exgal[~is_ddf]
y_exgal_d1 = y_exgal[is_ddf]
li = [y_exgal_d0.copy() for i in range(37)]
y_exgal = pd.concat([y_exgal_d1]+li, ignore_index=True)

del li, X_exgal_d0, X_exgal_d1, X_exgal['g'], y_exgal_d0, y_exgal_d1

group_kfold = GroupKFold(n_splits=NFOLD)

print(f'X_gal.shape: {X_gal.shape}')
print(f'X_exgal.shape: {X_exgal.shape}')

gc.collect()

# =============================================================================
# cv(gal)
# =============================================================================
print('==== GAL ====')
param['num_class'] = 5

dtrain = lgb.Dataset(X_gal, y_gal.values, #categorical_feature=CAT,
                     free_raw_data=False)
gc.collect()

#model_all = []
nround_mean = 0
wloss_list = []
oofs_gal = []
for i in range(2):

    gc.collect()
    param['seed'] = np.random.randint(9999)
    ret, models = lgb.cv(param, dtrain, 99999, nfold=NFOLD,
                         fobj=utils_metric.wloss_objective_gal,
                         feval=utils_metric.wloss_metric_gal,
                         early_stopping_rounds=100, verbose_eval=50,
                         folds=group_kfold.split(X_gal, y_gal, group_gal),
                         seed=SEED)
    oof = ex.eval_oob(X_gal, y_gal.values, models, SEED, stratified=True, shuffle=True,
                         n_class=True)
    oofs_gal.append(oof)
#    model_all += models
    nround_mean += len(ret['wloss-mean'])
    wloss_list.append( ret['wloss-mean'][-1] )

nround_mean = int((nround_mean/2) * 1.3)
utils.send_line(f'nround_mean: {nround_mean}')

result = f"CV GAL wloss: {np.mean(wloss_list)} + {np.std(wloss_list)}"
utils.send_line(result)

# =============================================================================
# model(gal)
# =============================================================================

gc.collect()

np.random.seed(SEED)

model_all_gal = []
for i in range(LOOP):

    gc.collect()

    print(f'LOOP:{i}')
    gc.collect()
    param['seed'] = np.random.randint(9999)
    model = lgb.train(param, dtrain, num_boost_round=nround_mean,
                      fobj=utils_metric.wloss_objective_gal,
                      feval=utils_metric.wloss_metric_gal,
                      valid_names=None, init_model=None,
                      feature_name='auto', categorical_feature='auto',
                      early_stopping_rounds=None, evals_result=None,
                      verbose_eval=True, learning_rates=None,
                      keep_training_booster=False, callbacks=None)

    model_all_gal.append(model)

del X_gal, y_gal

# =============================================================================
# cv(exgal)
# =============================================================================
print('==== EXGAL ====')
param['num_class'] = 9

dtrain = lgb.Dataset(X_exgal, y_exgal.values, #categorical_feature=CAT,
                     free_raw_data=False)
gc.collect()

#model_all = []
nround_mean = 0
wloss_list = []
oofs_exgal = []
for i in range(2):

    gc.collect()
    param['seed'] = np.random.randint(9999)
    ret, models = lgb.cv(param, dtrain, 99999, nfold=NFOLD,
                         fobj=utils_metric.wloss_objective_exgal,
                         feval=utils_metric.wloss_metric_exgal,
                         early_stopping_rounds=100, verbose_eval=50,
                         folds=group_kfold.split(X_exgal, y_exgal, group_exgal),
                         seed=SEED)
    oof = ex.eval_oob(X_exgal, y_exgal.values, models, SEED, stratified=True, shuffle=True,
                         n_class=True)
    oofs_exgal.append(oof)
#    model_all += models
    nround_mean += len(ret['wloss-mean'])
    wloss_list.append( ret['wloss-mean'][-1] )

nround_mean = int((nround_mean/2) * 1.3)
utils.send_line(f'nround_mean: {nround_mean}')

result = f"CV EXGAL wloss: {np.mean(wloss_list)} + {np.std(wloss_list)}"
print(result)
utils.send_line(result)

# =============================================================================
# model(exgal)
# =============================================================================

gc.collect()

np.random.seed(SEED)

model_all_exgal = []
for i in range(LOOP):

    gc.collect()

    print(f'LOOP:{i}')
    gc.collect()
    param['seed'] = np.random.randint(9999)
    model = lgb.train(param, dtrain, num_boost_round=nround_mean,
                      fobj=utils_metric.wloss_objective_exgal,
                      feval=utils_metric.wloss_metric_exgal,
                      valid_names=None, init_model=None,
                      feature_name='auto', categorical_feature='auto',
                      early_stopping_rounds=None, evals_result=None,
                      verbose_eval=True, learning_rates=None,
                      keep_training_booster=False, callbacks=None)

    model_all_exgal.append(model)

# =============================================================================
# test TODO: edit
# =============================================================================

X_test = pd.concat([
                pd.read_pickle(f) for f in tqdm(files_te, mininterval=10)
               ], axis=1)

gc.collect()

is_gal = pd.read_pickle('../data/te_is_gal.pkl')

X_test_gal   = X_test[is_gal][COL_gal]
X_test_exgal = X_test[~is_gal][COL_exgal]

del X_test; gc.collect()

for i,(model_gal,model_exgal) in enumerate(zip(model_all_gal, model_all_exgal)):
    y_pred_gal = model_gal.predict(X_test_gal)
    y_pred_gal = utils_metric.softmax(y_pred_gal)
    y_pred_exgal = model_exgal.predict(X_test_exgal)
    y_pred_exgal = utils_metric.softmax(y_pred_exgal)
    if i==0:
        y_pred_all_gal   = y_pred_gal
        y_pred_all_exgal = y_pred_exgal
    else:
        y_pred_all_gal   += y_pred_gal
        y_pred_all_exgal += y_pred_exgal

y_pred_all_gal /= int(LOOP)
y_pred_all_exgal /= int(LOOP)

sub_gal   = pd.read_pickle('../data/te_oid_gal.pkl')
sub_exgal = pd.read_pickle('../data/te_oid_exgal.pkl')

sub_gal = pd.concat([sub_gal, pd.DataFrame(y_pred_all_gal)], axis=1)
sub_gal.columns = ['object_id'] + [f'class_{i}' for i in [6, 16, 53, 65, 92]]

sub_exgal = pd.concat([sub_exgal, pd.DataFrame(y_pred_all_exgal)], axis=1)
sub_exgal.columns = ['object_id'] + [f'class_{i}' for i in [15, 42, 52, 62, 64, 67, 88, 90, 95]]

sub = pd.concat([sub_gal, sub_exgal], ignore_index=True).fillna(0)
col = ['object_id', 'class_6', 'class_15', 'class_16', 'class_42', 'class_52',
       'class_53', 'class_62', 'class_64', 'class_65', 'class_67', 'class_88',
       'class_90', 'class_92', 'class_95']

sub = sub[col]

# class_99
sub.to_pickle(f'../data/y_pred_raw_{__file__}.pkl')
utils.postprocess(sub, method='oli')

print(sub.iloc[:, 1:].idxmax(1).value_counts(normalize=True))

sub.to_csv(SUBMIT_FILE_PATH, index=False, compression='gzip')

png = f'LOG/sub_{__file__}.png'
utils.savefig_sub(sub, png)
utils.send_line('DONE!', png)

# =============================================================================
# submission
# =============================================================================
if EXE_SUBMIT:
    print('submit')
    utils.submit(SUBMIT_FILE_PATH, COMMENT)

#==============================================================================
utils.end(__file__)
utils.stop_instance()


text:
# Copyright 2018 Birkbeck College. All rights reserved.
#
# Licensed under the MIT license. See file LICENSE for details.
#
# Author(s): Cosmin Stamate

import sys
import logging

import numpy as np
import pandas as pd

from scipy import interpolate, signal, fft

from .utils import get_sampling_rate_from_timestamp, butter_lowpass_filter

class Processor:
    """
       This is the main Processor class. Once the data is loaded it will be
       accessible at data_frame, where it looks like:
       data_frame.x, data_frame.y, data_frame.z: x, y, z components of the acceleration
       data_frame.index is the datetime-like index

       This values are recommended by the author of the pilot study [1]

       sampling_frequency = 100.0Hz
       cutoff_frequency = 2.0Hz
       filter_order = 2
       window = 256
       lower_frequency = 2.0Hz
       upper_frequency = 10.0Hz

       [1] Developing a tool for remote digital assessment of Parkinson s disease
            Kassavetis	P,	Saifee	TA,	Roussos	G,	Drougas	L,	Kojovic	M,	Rothwell	JC,	Edwards	MJ,	Bhatia	KP

       [2] The use of the fast Fourier transform for the estimation of power spectra: A method based
            on time averaging over short, modified periodograms (IEEE Trans. Audio Electroacoust.
            vol. 15, pp. 70-73, 1967)
            P. Welch
    """

    def __init__(self, sampling_frequency=100.0, cutoff_frequency=2.0, filter_order=2,
                 window=256, lower_frequency=2.0, upper_frequency=10.0):
        try:
            self.sampling_frequency = sampling_frequency
            self.cutoff_frequency = cutoff_frequency
            self.filter_order = filter_order
            self.window = window
            self.lower_frequency = lower_frequency
            self.upper_frequency = upper_frequency

            logging.debug("Processor init")

        except IOError as e:
            ierr = "({}): {}".format(e.errno, e.strerror)
            logging.error("Processor I/O error %s", ierr)

        except ValueError as verr:
            logging.error("Processor ValueError ->%s", verr)

        except:
            logging.error("Unexpected error on Processor init: %s", sys.exc_info()[0])

    def resample_signal(self, data_frame):
        """
            Convenience method for frequency conversion and resampling of data frame.
            Object must have a DatetimeIndex. After re-sampling, this methods interpolate the time magnitude sum
            acceleration values and the x,y,z values of the data frame acceleration

            :param data_frame: the data frame to resample
            :param str sampling_frequency: the sampling frequency. Default is 100Hz, as recommended by the author of the pilot study [1]
        """
        new_freq = np.round(1 / self.sampling_frequency, decimals=6)
        df_resampled = data_frame.resample(str(new_freq) + 'S').mean()

        # f = interpolate.interp1d(data_frame.td, data_frame.mag_sum_acc)

        # new_timestamp = np.arange(data_frame.td[0], data_frame.td[-1], 1.0 / self.sampling_frequency)
        # df_resampled.mag_sum_acc = f(new_timestamp)

        logging.debug("resample signal")
        df_resampled = df_resampled.interpolate(method='linear')
        get_sampling_rate_from_timestamp(df_resampled)

        # df_resampled['td'] = df_resampled.index - df_resampled.index[0]

        return df_resampled

    def cut_data_frame(self, data_frame, start=0, stop=-1):

        df = data_frame.iloc[start: stop]
        # df.td = df.td - df.td[0]
        df.index = pd.to_datetime(df.index.values - df.index.values[0])

        return df

    def filter_data_frame(self, data_frame, centre=False, keep_cols=['anno']):
        """
            This method filters a data frame signal as suggested in [1]. First step is to high pass filter the data
            frame using a butter Butterworth digital and analog filter
            (https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.signal.butter.html). Then the method
            filter the data frame along one-dimension using a digital filter.
            (https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.lfilter.html)

            :param data_frame: the data frame
            :param str cutoff_frequency: The path to load data from
            :param str filter_order: format of the file. Default is CloudUPDRS. Set to mpower for mpower data.
        """
        b_f = lambda x: butter_lowpass_filter(x.values, self.sampling_frequency, cutoff=self.cutoff_frequency, order=self.filter_order)
        filtered_data_frame = data_frame.apply(b_f, 0)

        # we don't need to filter the time difference
        # filtered_data_frame.td = data_frame.td

        logging.debug("filtered whole dataframe!")

        # I need to fix this as I am losing some important information
        # one idea would be to look at where the sign changes (first and second peak)
        # and keep that information aswell.
        if centre:
            # de-mean
            filtered_data_frame -= filtered_data_frame.mean()

            for col in filtered_data_frame:
                first_zero_crossing = np.argwhere(filtered_data_frame[col] > 0)[0][0]
                filtered_data_frame[col][:first_zero_crossing] = 0

        # No python3 support :(
        # if {*keep_cols}.issubset(filtered_data_frame.columns):
        for c in keep_cols:
            if c not in filtered_data_frame.columns:
                return

        filtered_data_frame[keep_cols] = data_frame[keep_cols]
        return filtered_data_frame

    def filter_signal(self, data_frame):
        """
            This method filters a data frame signal as suggested in [1]. First step is to high pass filter the data
            frame using a butter Butterworth digital and analog filter
            (https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.signal.butter.html). Then the method
            filter the data frame along one-dimension using a digital filter.
            (https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.lfilter.html)

            :param data_frame: the data frame
            :param str cutoff_frequency: The path to load data from
            :param str filter_order: format of the file. Default is CloudUPDRS. Set to mpower for mpower data.
        """
        b, a = signal.butter(self.filter_order, 2 * self.cutoff_frequency / self.sampling_frequency, 'high', analog=False)
        filtered_signal = signal.lfilter(b, a, data_frame.mag_sum_acc.values)
        data_frame['filtered_signal'] = filtered_signal

        logging.debug("filter signal")
        return data_frame

    def fft_signal(self, data_frame):
        """
            This method perform Fast Fourier Transform on the data frame using a hanning window
            (https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.signal.hann.html)

            :param data_frame: the data frame
            :param str window: hanning window size
        """
        signal_length = len(data_frame.filtered_signal.values)
        ll = int ( signal_length / 2 - self.window / 2 )
        rr = int ( signal_length / 2 + self.window / 2 )
        msa = data_frame.filtered_signal[ll:rr].values
        hann_window = signal.hann(self.window)

        msa_window = (msa * hann_window)
        transformed_signal = fft(msa_window)

        data = {'filtered_signal': msa_window, 'transformed_signal': transformed_signal,
                'dt': data_frame.td[ll:rr].values}

        data_frame_fft = pd.DataFrame(data, index=data_frame.index[ll:rr],
                                      columns=['filtered_signal', 'transformed_signal', 'dt'])
        logging.debug("fft signal")
        return data_frame_fft

max_stars_repo_name: gkroussos/pdkit

max_issues_repo_name: gkroussos/pdkit

max_forks_repo_name: gkroussos/pdkit


text:
import cv2
import numpy as np

class FretboardRoiEstimator():

    hasFretboardKeyPoints = False
    fretboardKeyPoints = np.array(0)
    fretboardKeyPointsDes = None
    fretboardKeyPointsImage = np.array(0)

    def roiSelector(self, frame):
        r = cv2.selectROI(frame)

        # Crop image
        roi = frame[int(r[1]):int(r[1]+r[3]), int(r[0]):int(r[0]+r[2])]

        return roi

     #calibrate true only for inital roi detection of fretboard
    def detectORBKeypoints(self, frame, calibrate = False):

        # Initiate ORB detector
        orb = cv2.ORB_create()

        # find the keypoints and descriptors with ORB
        kp, des = orb.detectAndCompute(frame,None)

        if calibrate:
            self.fretboardKeyPoints = kp
            self.hasFretboardKeyPoints = True

            # draw only keypoints location,not size and orientation
            self.fretboardKeyPointsImage = cv2.drawKeypoints(frame, kp, None, color=(0,255,0), flags=0)
        else:
            return kp, des

    #calibrate true only for inital roi detection of fretboard
    def detectSIFTKeypoints(self, frame, calibrate = False):
        gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)

        #initialize SIFT object
        sift = cv2.SIFT_create()

        #get keypoints and descriptors
        kp,des = sift.detectAndCompute(gray,None)

        if calibrate:
            self.fretboardKeyPoints = kp
            self.hasFretboardKeyPoints = True
            #self.fretboardKeyPointsImage = cv2.drawKeypoints(frame,kp, None, color=(0,255,0),flags=0)
            self.fretboardKeyPointsImage = frame
            self.fretboardKeyPointsDes = des
        #return keypoints and descriptors
        else:
            return kp, des

    #return keypoints of fretboard if available
    def getFretboardKeypoints(self):
        if self.hasFretboardKeyPoints:
            return self.fretboardKeyPoints

    #return keypoints image of fretboard if available
    def getFretboardKeypointsImage(self):
        if self.hasFretboardKeyPoints:
            return self.fretboardKeyPointsImage

    #return matches between frame keypoints des and roi fretboar keypoint des
    def getKeyPointMatches(self, des2):

        des1 = self.fretboardKeyPointsDes
        #feature matching
        # bf = cv2.BFMatcher(cv2.NORM_L1, crossCheck=True)
        # matches = bf.match(des1, des2)
        # matches = sorted(matches, key = lambda x:x.distance)

        FLANN_INDEX_KDTREE = 0
        index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
        search_params = dict(checks = 50)

        flann = cv2.FlannBasedMatcher(index_params, search_params)
        matches = flann.knnMatch(des1,des2,k=2)

        good =[]

        for m,n in matches:
            if m.distance < 0.7*n.distance:
                good.append(m)
        return good
        #return matches

    #return matches between frame keypoints des and roi fretboar keypoint des
    def getKeyPointMatchesGeneric(self, des1, des2):

        #feature matching
        # bf = cv2.BFMatcher(cv2.NORM_L1, crossCheck=True)
        # matches = bf.match(des1, des2)
        # matches = sorted(matches, key = lambda x:x.distance)

        FLANN_INDEX_KDTREE = 0
        index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
        search_params = dict(checks = 50)

        flann = cv2.FlannBasedMatcher(index_params, search_params)
        matches = flann.knnMatch(des1,des2,k=2)

        good =[]

        for m,n in matches:
            if m.distance < 0.7*n.distance:
                good.append(m)
        return good
        #return matches

    def getHomographyMatrix(self, kp1, kp2, matches):

        # Sort them in the order of their distance.
        #matches = sorted(matches, key = lambda x:x.distance)
        #matches = matches[:10]

        src_pts = np.float32([ kp1[m.queryIdx].pt for m in matches ]).reshape(-1,1,2)
        dst_pts = np.float32([ kp2[m.trainIdx].pt for m in matches ]).reshape(-1,1,2)
        homographyMatrix, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC,5.0)

        mask = mask.ravel().tolist()

        return homographyMatrix, mask

    def getBoundingBox(self, homographyMatrix):
        h,w = self.getFretboardKeypointsImage().shape[:2]
        pts = np.float32([ [0,0],[0,h-1],[w-1,h-1],[w-1,0] ]).reshape(-1,1,2)
        dst = cv2.perspectiveTransform(pts,homographyMatrix)
        #dst += (w, 0)  # adding offset
        return dst

max_stars_repo_licenses: Unlicense MIT

max_issues_repo_licenses: Unlicense MIT

max_forks_repo_licenses: Unlicense MIT


text:
import os
import logging
import json
import numpy
import joblib
import numpy as np

import tensorflow_hub as hub

embed = hub.load("https://tfhub.dev/google/Wiki-words-250/2")

def get_word2vec_enc(reviews):
    """
    get word2vec value for each word in sentence.
    concatenate word in numpy array, so we can use it as RNN input
    """
    encoded_reviews = []
    for review in reviews:
        tokens = review.split(" ")
        word2vec_embedding = embed(tokens)
        #for num in word2vec_embedding:
        encoded_reviews.append(word2vec_embedding)
    return encoded_reviews

def get_padded_encoded_reviews(encoded_reviews,max_length):
    """
    for short sentences, we prepend zero padding so all input to RNN has same length
    """
    padded_reviews_encoding = []
    for enc_review in encoded_reviews:
        zero_padding_cnt = max_length - enc_review.shape[0]
        pad = np.zeros((1, 250))
        for i in range(zero_padding_cnt):
            enc_review = np.concatenate((pad, enc_review), axis=0)
        padded_reviews_encoding.append(enc_review)
    return padded_reviews_encoding

def init():
    """
    This function is called when the container is initialized/started, typically after create/update of the deployment.
    You can write the logic here to perform init operations like caching the model in memory
    """
    global model
    # AZUREML_MODEL_DIR is an environment variable created during deployment.
    # It is the path to the model folder (./azureml-models/$MODEL_NAME/$VERSION)
    model_path = os.path.join(
        os.getenv("AZUREML_MODEL_DIR"), "sklearn_regression_model.pkl"
    )
    # deserialize the model file back into a sklearn model
    model = joblib.load(model_path)
    logging.info("Init complete")

def run(raw_data):
    """
    This function is called for every invocation of the endpoint to perform the actual scoring/prediction.
    In the example we extract the data from the json input and call the scikit-learn model's predict()
    method and return the result back
    """
    logging.info("Request received")
    data = json.loads(raw_data)["data"]
    data = numpy.array(data)
    data = get_word2vec_enc(data)
    data = get_padded_encoded_reviews(data,290)
    data = np.array(data)
    result = model.predict(data)
    logging.info("Request processed")
    return result.tolist()

max_stars_repo_name: Ernestosaleh/FakeNewsBot

max_issues_repo_name: Ernestosaleh/FakeNewsBot

max_forks_repo_name: Ernestosaleh/FakeNewsBot


text:
from __future__ import division
from sys import exit
from math import sqrt
from numpy import array
from scipy.optimize import fmin_l_bfgs_b

def RMSE(params, *args):

	Y = args[0]
	type = args[1]
	rmse = 0

	if type == 'linear':

		alpha, beta = params
		s = [Y[0]]
		t = [Y[1] - Y[0]]
		y = [s[0] + t[0]]

		for i in range(len(Y)):

			s.append(alpha * Y[i] + (1 - alpha) * (s[i] + t[i]))
			t.append(beta * (s[i + 1] - s[i]) + (1 - beta) * t[i])
			y.append(s[i + 1] + t[i + 1])

	else:

		alpha, beta, gamma = params
		k = args[2]
		s = [sum(Y[0:k]) / float(k)]
		t = [(sum(Y[k:2 * k]) - sum(Y[0:k])) / k]

		if type == 'additive':

			p = [Y[i] - s[0] for i in range(k)]
			y = [s[0] + t[0] + p[0]]

			for i in range(len(Y)):

				s.append(alpha * (Y[i] - p[i]) + (1 - alpha) * (s[i] + t[i]))
				t.append(beta * (s[i + 1] - s[i]) + (1 - beta) * t[i])
				p.append(gamma * (Y[i] - s[i]) + (1 - gamma) * p[i])
				y.append(s[i + 1] + t[i + 1] + p[i + 1])

		elif type == 'multiplicative':

			p = [Y[i] / s[0] for i in range(k)]
			y = [(s[0] + t[0]) * p[0]]

			for i in range(len(Y)):

				s.append(alpha * (Y[i] / p[i]) + (1 - alpha) * (s[i] + t[i]))
				t.append(beta * (s[i + 1] - s[i]) + (1 - beta) * t[i])
				p.append(gamma * (Y[i] / (s[i]) + (1 - gamma) * p[i])
				y.append((s[i + 1] + t[i + 1]) * p[i + 1])

		else:

			exit('Type must be either linear, additive or multiplicative')

	rmse = sqrt(sum([(m - n) ** 2 for m, n in zip(Y, y[:-1])]) / len(Y))

	return y, Y, rmse

def linear(x, fc, alpha = None, beta = None):

	Y = x[:]

	if (alpha == None or beta == None):

		initial_values = array([0.3, 0.1])
		boundaries = [(0, 1), (0, 1)]
		type = 'linear'

		parameters = fmin_l_bfgs_b(RMSE, x0 = initial_values, args = (Y, type), bounds = boundaries, approx_grad = True)
		alpha, beta = parameters[0]

	s = [Y[0]]
	t = [Y[1] - Y[0]]
	y = [s[0] + t[0]]
	rmse = 0

	for i in range(len(Y) + fc):

		if i == len(Y):
			Y.append(s[-1] + t[-1])

		s.append(alpha * Y[i] + (1 - alpha) * (s[i] + t[i]))
		t.append(beta * (s[i + 1] - s[i]) + (1 - beta) * t[i])
		y.append(s[i + 1] + t[i + 1])

	rmse = sqrt(sum([(m - n) ** 2 for m, n in zip(Y[:-fc], y[:-fc - 1])]) / len(Y[:-fc]))

	return Y[-fc:], alpha, beta, rmse

def additive(x, k, fc, alpha = None, beta = None, gamma = None):

	Y = x[:]

	if (alpha == None or beta == None or gamma == None):

		initial_values = array([0.3, 0.1, 0.1])
		boundaries = [(0, 1), (0, 1), (0, 1)]
		type = 'additive'

		parameters = fmin_l_bfgs_b(RMSE, x0 = initial_values, args = (Y, type, k), bounds = boundaries, approx_grad = True)
		alpha, beta, gamma = parameters[0]

	s = [sum(Y[0:k]) / float(m)]
	t = [(sum(Y[k:2 * k]) - sum(Y[0:k])) / k]
	p = [Y[i] - s[0] for i in range(k)]
	y = [s[0] + t[0] + p[0]]
	rmse = 0

	for i in range(len(Y) + fc):

		if i == len(Y):
			Y.append(s[-1] + t[-1] + p[-k])

		s.append(alpha * (Y[i] - p[i]) + (1 - alpha) * (s[i] + t[i]))
		t.append(beta * (s[i + 1] - s[i]) + (1 - beta) * t[i])
		p.append(gamma * (Y[i] - s[i]) + (1 - gamma) * p[i])
		y.append(s[i + 1] + t[i + 1] + p[i + 1])

	rmse = sqrt(sum([(m - n) ** 2 for m, n in zip(Y[:-fc], y[:-fc - 1])]) / len(Y[:-fc]))

	return Y[-fc:], alpha, beta, gamma, rmse

def multiplicative(x, k, fc, alpha = None, beta = None, gamma = None):

	Y = x[:]

	if (alpha == None or beta == None or gamma == None):

		initial_values = array([0.0, 1.0, 0.0])
		boundaries = [(0, 1), (0, 1), (0, 1)]
		type = 'multiplicative'

		parameters = fmin_l_bfgs_b(RMSE, x0 = initial_values, args = (Y, type, k), bounds = boundaries, approx_grad = True)
		alpha, beta, gamma = parameters[0]

	s = [sum(Y[0:k]) / float(k)]
	t = [(sum(Y[k:2 * k]) - sum(Y[0:k])) / k]
	p = [Y[i] / s[0] for i in range(k)]
	y = [(s[0] + t[0]) * p[0]]
	rmse = 0

	for i in range(len(Y) + fc):

		if i == len(Y):
			Y.append((s[-1] + t[-1]) * p[-k])

		s.append(alpha * (Y[i] / p[i]) + (1 - alpha) * (s[i] + t[i]))
		t.append(beta * (s[i + 1] - s[i]) + (1 - beta) * t[i])
		p.append(gamma * (Y[i] / (s[i]) + (1 - gamma) * p[i])
		y.append((s[i + 1] + t[i + 1]) * p[i + 1])

	rmse = sqrt(sum([(m - n) ** 2 for m, n in zip(Y[:-fc], y[:-fc - 1])]) / len(Y[:-fc]))

	return Y[-fc:], alpha, beta, gamma, rmse

reason: from numpy,from scipy