def send(self, person, group=None): """ Sends this newsletter to "person" with optional "group". This works only with newsletters which are workflow newsletters. """ if not self.is_workflow(): raise exceptions.AttributeError('only newsletters with type workflow can be sent') # search newsletter job wich hash the same group or create it if it doesn't exist try: if group: ctype = ContentType.objects.get_for_model(group) job = self.jobs.get(content_type__pk=ctype.id, object_id=group.id) else: job = self.jobs.get(content_type=None) except models.ObjectDoesNotExist: if group: kw = {'group_object':group} else: kw = {} job=self.jobs.create(status=32, **kw) # 32=readonly self.replace_links(job) self.prepare_to_send() mail = job.create_mail(person) try: message = mail.get_message() message.send() except: raise else: mail.mark_sent()
def getScheduleInfo(self, **kwargs): """Формирует и возвращает информацию о расписании приёма врача Args: start: дата начала расписания (обязательный) end: дата окончания расписания (обязательный) doctor_uid: id врача (обязательный) hospital_uid_from: id ЛПУ, из которого производится запрос (необязательный) """ result = [] if kwargs['start'] and kwargs['end'] and kwargs['doctor_uid']: server_id = kwargs.get('server_id') doctor_uid = kwargs.get('doctor_uid') hospital_uid_from = kwargs.get('hospital_uid_from', '0') for i in xrange((kwargs['end'] - kwargs['start']).days): start = (kwargs['start'] + datetime.timedelta(days=i)) params = { 'serverId': server_id, 'personId': doctor_uid, 'date': start, 'hospitalUidFrom': hospital_uid_from, } timeslot = self.getWorkTimeAndStatus(**params) if timeslot: result.extend(timeslot) else: logger.error(exceptions.AttributeError(), extra=logger_tags) raise exceptions.AttributeError return {'timeslots': result}
def out(self, nstp, x, y, s, h): """ nstp is current step number, current values are x & y, Stepper is s and step size is h""" if not self.dense: e = exceptions.AttributeError('Dense output is not set in Output!') raise e if nstp == 1: self.save(x, y) self.xout += self.dxout else: while (x - self.xout) * (self.x2 - self.x1) > 0.0: self.save_dense(s, self.xout, h) self.xout += self.dxout
def phasematch(self, pump_wl_nm, sgnl_wl_nm, idlr_wl_nm, return_wavelength=False): """ Phase match mixing between pump (aligned to a mix of ne and no) and signal and idler (aligned to ordinary axis.)""" RET_WL = False new_wl = 0.0 if pump_wl_nm is None: pump_wl_nm = 1.0 / (1.0 / idlr_wl_nm + 1.0 / sgnl_wl_nm) print('Setting pump to ', pump_wl_nm) RET_WL = True new_wl = pump_wl_nm if sgnl_wl_nm is None: sgnl_wl_nm = 1.0 / (1.0 / pump_wl_nm - 1.0 / idlr_wl_nm) print('Setting signal to ', sgnl_wl_nm) RET_WL = True new_wl = sgnl_wl_nm if idlr_wl_nm is None: idlr_wl_nm = 1.0 / (1.0 / pump_wl_nm - 1.0 / sgnl_wl_nm) print('Setting idler to ', idlr_wl_nm) RET_WL = True new_wl = idlr_wl_nm kp_0 = 2 * np.pi / pump_wl_nm ks = self.n(sgnl_wl_nm, axis='o') * 2 * np.pi / sgnl_wl_nm ki = self.n(idlr_wl_nm, axis='o') * 2 * np.pi / idlr_wl_nm n_soln = (ks + ki) / kp_0 n_e = self.n(pump_wl_nm, 'e') n_o = self.n(pump_wl_nm, 'o') print('n_e @ pump: ', n_e, ';\t n_o @ pump: ', n_o) a = n_e**2 - n_o**2 b = 0.0 c = n_o**2 - n_e**2 * n_o**2 / (n_soln**2) x = (-b + np.sqrt(b**2 - 4 * a * c)) / (2.0 * a) if x < 0: x = (-b - np.sqrt(b**2 - 4 * a * c)) / (2.0 * a) if np.isnan(np.arccos(x)): raise exceptions.AttributeError('No phase matching condition.') theta = np.arccos(x) print('Angle set to ', 360 * theta / (2.0 * np.pi)) if RET_WL and return_wavelength: return (theta, new_wl) else: return theta
def isSupported(dataSection): """ This method checks an dataSection to see if all the Effects contained therein are supported by the current graphics setting. Currently the only issue is that cases are depth-based effects are not available if the MRTDepth setting is not turned on. """ optionIdx = BigWorld.getGraphicsSetting('MRT_DEPTH') if optionIdx == 0: return True else: ds = ResMgr.openSection(dataSection) if ds is None: raise exceptions.AttributeError(dataSection) effects = ds.readStrings('Effect') for name in effects: if name in ('Depth of Field (variable filter)', 'Depth of Field (bokeh control)', 'Depth of Field (multi-blur)', 'Rainbow', 'God Rays', 'Volume Light'): return False return True
def deriv(self, z, y, dydx): assert not np.isnan(z) if self.crystal.mode == 'PP': deff = self.poling(z) * self.crystal.deff elif self.crystal.mode == 'BPM' or self.crystal.mode == 'simple': deff = self.crystal.deff else: raise exceptions.AttributeError( 'Crystal type not known; deff not set.') # After epic translation of Dopri853 from Numerical Recipes' C++ to # native Python/NumPy, we can use complex numbers throughout: t = z / float(self.approx_pulse_speed) self.phi_p[:] = np.exp( 1j * ((self.k_p + self.k_p_0) * z - t * self.pump.W_mks)) self.phi_s[:] = np.exp( 1j * ((self.k_s + self.k_s_0) * z - t * self.sgnl.W_mks)) self.phi_i[:] = np.exp( 1j * ((self.k_i + self.k_i_0) * z - t * self.idlr.W_mks)) z_to_focus = z - self.crystal.length_mks / 2.0 if self._calc_gouy: self.phi_p *= self.pump_beam.calculate_gouy_phase( z_to_focus, self.n_p) self.phi_s *= self.sgnl_beam.calculate_gouy_phase( z_to_focus, self.n_s) self.phi_i *= self.idlr_beam.calculate_gouy_phase( z_to_focus, self.n_i) if not self.disable_SPM: self.gen_jl(y) if self._wg_mode == False: waist_p = self.pump_beam.calculate_waist(z_to_focus, n_s=self.n_p) waist_s = self.sgnl_beam.calculate_waist(z_to_focus, n_s=self.n_s) waist_i = self.idlr_beam.calculate_waist(z_to_focus, n_s=self.n_i) R_p = self.pump_beam.calculate_R(z_to_focus, n_s=self.n_p) R_s = self.sgnl_beam.calculate_R(z_to_focus, n_s=self.n_s) R_i = self.idlr_beam.calculate_R(z_to_focus, n_s=self.n_i) # Geometric scaling factors (Not used) # P_to_a is the conversion between average power and "effective intensity" # The smallest area is used, as this is the part of the field which is # interacting. THe larger fields must be scaled with a mode-match integral # THe mode-match integral-based scale factor for Gaussian beams is # 4 * w1**2 w2**2 # --------------- # (w1**2 + w2 **2)**2 # This is the power coupling, so multiply larger 2 fields by sqrt(MMI) # # Attempting to limit interaction via mode-match integrals appears to # (1) not conserve energy and (2) INCREASES the interaction strength. # I'm not totally sure why, but it seems like the best course of action # is to match confocal parameters (which is done in __init__, above). # Overlap integrals are left intact, in case we want to plot them. if self._wg_mode == False: if (np.mean(waist_p) <= np.mean(waist_s)) and (np.mean(waist_p) <= np.mean(waist_i)): self.pump_P_to_a = self.pump_beam.rtP_to_a_2( self.pump, self.crystal, z_to_focus) self.sgnl_P_to_a = self.sgnl_beam.rtP_to_a_2( self.sgnl, self.crystal, None, waist_p) self.idlr_P_to_a = self.idlr_beam.rtP_to_a_2( self.idlr, self.crystal, None, waist_p) self.overlap_pump = 1.0 self.overlap_sgnl = np.sqrt( self.sgnl_beam.calc_overlap_integral( z_to_focus, self.sgnl, self.pump, self.pump_beam, self.crystal)) self.overlap_idlr = np.sqrt( self.idlr_beam.calc_overlap_integral( z_to_focus, self.idlr, self.pump, self.pump_beam, self.crystal)) elif np.mean(waist_s) <= np.mean(waist_i): self.sgnl_P_to_a = self.sgnl_beam.rtP_to_a_2( self.sgnl, self.crystal, z_to_focus) self.pump_P_to_a = self.pump_beam.rtP_to_a_2( self.pump, self.crystal, None, waist_s) self.idlr_P_to_a = self.idlr_beam.rtP_to_a_2( self.idlr, self.crystal, None, waist_s) self.overlap_pump = np.sqrt( self.pump_beam.calc_overlap_integral( z_to_focus, self.pump, self.sgnl, self.sgnl_beam, self.crystal)) self.overlap_sgnl = 1.0 self.overlap_idlr = np.sqrt( self.idlr_beam.calc_overlap_integral( z_to_focus, self.idlr, self.sgnl, self.sgnl_beam, self.crystal)) else: self.idlr_P_to_a = self.idlr_beam.rtP_to_a_2( self.idlr, self.crystal, None, waist_i) self.sgnl_P_to_a = self.sgnl_beam.rtP_to_a_2( self.sgnl, self.crystal, None, waist_i) self.pump_P_to_a = self.pump_beam.rtP_to_a_2( self.pump, self.crystal, None, waist_i) self.overlap_pump = np.sqrt( self.pump_beam.calc_overlap_integral( z_to_focus, self.pump, self.idlr, self.idlr_beam, self.crystal)) self.overlap_sgnl = np.sqrt( self.sgnl_beam.calc_overlap_integral( z_to_focus, self.sgnl, self.idlr, self.idlr_beam, self.crystal)) self.overlap_idlr = 1.0 if self._plot_beam_overlaps and abs( z - self.last_calc_z) > self.crystal.length_mks * 0.001: plt.subplot(131) plt.plot(z * 1e3, np.mean(self.overlap_pump), '.b') plt.plot(z * 1e3, np.mean(self.overlap_sgnl), '.k') plt.plot(z * 1e3, np.mean(self.overlap_idlr), '.r') plt.subplot(132) plt.plot(z * 1e3, np.mean(waist_p) * 1e6, '.b') plt.plot(z * 1e3, np.mean(waist_s) * 1e6, '.k') plt.plot(z * 1e3, np.mean(waist_i) * 1e6, '.r') plt.subplot(133) plt.plot(z * 1e3, np.mean(R_p), '.b') plt.plot(z * 1e3, np.mean(R_s), '.k') plt.plot(z * 1e3, np.mean(R_i), '.r') self.last_calc_z = z else: # Life is simple in waveguide mode (for large V number WG) self.pump_P_to_a = self.pump_beam.rtP_to_a(self.n_p) self.sgnl_P_to_a = self.sgnl_beam.rtP_to_a(self.n_s) self.idlr_P_to_a = self.idlr_beam.rtP_to_a(self.n_i) self.AsAi[:] = np.power(self.phi_p, -1.0)*\ self.fftobject.conv(self.sgnl_P_to_a * self.As(y) * self.phi_s, self.idlr_P_to_a * self.Ai(y) * self.phi_i) self.ApAs[:] = np.power(self.phi_i, -1.0)*\ self.fftobject.corr(self.pump_P_to_a * self.Ap(y) * self.phi_p, self.sgnl_P_to_a * self.As(y) * self.phi_s) self.ApAi[:] = np.power(self.phi_s, -1.0)*\ self.fftobject.corr(self.pump_P_to_a * self.Ap(y) * self.phi_p, self.idlr_P_to_a * self.Ai(y) * self.phi_i) L = self.veclength # np.sqrt(2 / (c * eps * pi * waist**2)) converts to electric field # # From the Seres & Hebling paper, # das/dz + i k as = F(ap, ai) # The change of variables is as = As exp[-ikz], so that # # das/dz = dAs/dz exp[-ikz] - ik As exp[ikz] # das/dz + ik as = ( dAs/dz exp[-ikz] - ik As exp[-ikz] ) + i k As exp[-ikz] # = dAs/dz exp[-ikz] # The integration is done in the As variables, to remove the fast k # dependent term. The procedure is: # 1) Calculate F(ai(Ai), ap(Ap)) # 2) Multiply by exp[+ikz] # If the chi-3 terms are included: if not self.disable_SPM: logging.warn( 'Warning: this code not updated with correct field-are scaling. Fix it if you use it!' ) jpap = self.phi_p**-1 * self.fftobject.conv(self.jl_p, self.Ap(y) * self.phi_p) * \ np.sqrt(2. / (constants.speed_of_light * constants.epsilon_0 * np.pi * waist_p**2)) jsas = self.phi_s**-1 * self.fftobject.conv(self.jl_s, self.As(y) * self.phi_s) * \ np.sqrt(2. / (constants.speed_of_light* constants.epsilon_0 * np.pi * waist_s**2)) jiai = self.phi_i**-1 * self.fftobject.conv(self.jl_i, self.Ai(y) * self.phi_i) * \ np.sqrt(2. / (constants.speed_of_light* constants.epsilon_0 * np.pi * waist_i**2)) dydx[0 :L ] = 1j * 2 * self.AsAi * self.pump.W_mks * deff / (constants.speed_of_light* self.n_p) / \ self.pump_P_to_a -1j * self.pump.w_hz * self.crystal.n2 / (2.*np.pi*self.c) * jpap dydx[L :2*L] = 1j * 2 * self.ApAi * self.sgnl.W_mks * deff / (constants.speed_of_light* self.n_s) / \ self.sgnl_P_to_a -1j * self.sgnl.w_hz * self.crystal.n2 / (2.*np.pi*self.c) * jsas dydx[2*L:3*L] = 1j * 2 * self.ApAs * self.idlr.W_mks * deff / (constants.speed_of_light* self.n_i) / \ self.idlr_P_to_a -1j * self.idler.w_hz * self.crystal.n2 / (2.*np.pi*self.c) * jiai else: # Only chi-2: # pump dydx[0 :L ] = 1j * 2 * self.AsAi * self.pump.W_mks * deff / (constants.speed_of_light * self.n_p) / \ (self.pump_P_to_a) # signal dydx[L :2*L] = 1j * 2 * self.ApAi * self.sgnl.W_mks * deff / (constants.speed_of_light * self.n_s) / \ (self.sgnl_P_to_a) # idler dydx[2*L:3*L] = 1j * 2 * self.ApAs * self.idlr.W_mks * deff / (constants.speed_of_light * self.n_i) / \ (self.idlr_P_to_a)
streetKLADR=kwargs['streetKLADR'], flat=kwargs['flat'], ) try: result = self.client.findOrgStructureByAddress(params) except WebFault, e: print e logger.error(e, extra=logger_tags) except NotFoundException, e: logger.error(e, extra=logger_tags) return [] else: #return self.__unicode_result(result) return result else: logger.error(exceptions.AttributeError(), extra=logger_tags) raise exceptions.AttributeError return None def getScheduleInfo(self, **kwargs): """Формирует и возвращает информацию о расписании приёма врача Args: start: дата начала расписания (обязательный) end: дата окончания расписания (обязательный) doctor_uid: id врача (обязательный) hospital_uid_from: id ЛПУ, из которого производится запрос (необязательный) """ result = [] absences = []
def __init__(self, dims, cellclass, cellparams=None, label=None): """ dims should be a tuple containing the population dimensions, or a single integer, for a one-dimensional population. e.g., (10,10) will create a two-dimensional population of size 10x10. cellclass should either be a standardized cell class (a class inheriting from common.StandardCellType) or a string giving the name of the simulator-specific model that makes up the population. cellparams should be a dict which is passed to the neuron model constructor label is an optional name for the population. """ ##if isinstance(dims, int): # also allow a single integer, for a 1D population ## #print "Converting integer dims to tuple" ## dims = (dims,) ##elif len(dims) > 3: ## raise exceptions.AttributeError('PCSIM does not support populations with more than 3 dimensions') ## ##self.actual_ndim = len(dims) ##while len(dims) < 3: ## dims += (1,) ### There is a problem here, since self.dim should hold the nominal dimensions of the ### population, while in PCSIM the population is always really 3D, even if some of the ### dimensions have size 1. We should add a variable self._dims to hold the PCSIM dimensions, ### and make self.dims be the nominal dimensions. common.Population.__init__(self, dims, cellclass, cellparams, label) ### set the steps list, used by the __getitem__() method. ##self.steps = [1]*self.ndim ##for i in range(self.ndim-1): ## for j in range(i+1, self.ndim): ## self.steps[i] *= self.dim[j] if isinstance(cellclass, str): if not cellclass in dir(pypcsim): raise common.InvalidModelError( 'Trying to create non-existent cellclass ' + cellclass) cellclass = getattr(pypcsim, cellclass) self.celltype = cellclass if issubclass(cellclass, common.StandardCellType): self.celltype = cellclass(cellparams) self.cellfactory = self.celltype.simObjFactory else: self.celltype = cellclass if issubclass(cellclass, pypcsim.SimObject): self.cellfactory = apply(cellclass, (), cellparams) else: raise exceptions.AttributeError( 'Trying to create non-existent cellclass ' + cellclass.__name__) # CuboidGridPopulation(SimNetwork &net, GridPoint3D origin, Volume3DSize dims, SimObjectFactory &objFactory) ##self.pcsim_population = pypcsim.CuboidGridObjectPopulation( ## simulator.net, ## pypcsim.GridPoint3D(0,0,0), ## pypcsim.Volume3DSize(dims[0], dims[1], dims[2]), ## self.cellfactory) ##self.cell = numpy.array(self.pcsim_population.idVector()) ##self.first_id = 0 ##self.cell -= self.cell[0] ##self.all_cells = self.cell ##self.local_cells = numpy.array(self.pcsim_population.localIndexes()) ## self.all_cells, self._mask_local, self.first_id, self.last_id = simulator.create_cells( cellclass, cellparams, self.size, parent=self) self.local_cells = self.all_cells[self._mask_local] self.all_cells = self.all_cells.reshape(self.dim) self._mask_local = self._mask_local.reshape(self.dim) self.cell = self.all_cells # temporary, awaiting harmonisation self.recorders = { 'spikes': Recorder('spikes', population=self), 'v': Recorder('v', population=self), 'gsyn': Recorder('gsyn', population=self) }
def enqueue(self, **kwargs): """Записывает пациента на приём Args: person: словарь с данными о пациенте (обязательный): {'lastName': фамилия 'firstName': имя 'patronymic': отчество } timeslotStart: Желаемое время начала приёма (обязательный) hospitalUidFrom: id ЛПУ, из которого производится запись (необязательный) """ hospital_uid_from = kwargs.get('hospitalUidFrom') person = kwargs.get('person') if person is None: logger.error(exceptions.AttributeError(), extra=logger_tags) raise exceptions.AttributeError document = kwargs.get('document') birthDate = kwargs.get('birthday') if document and birthDate: patient = self.findPatient( serverId=kwargs.get('serverId'), lastName=person.get('lastName'), firstName=person.get('firstName'), patrName=person.get('patronymic'), omiPolicy=kwargs.get('omiPolicyNumber'), document=document, sex=kwargs.get('sex', 0), birthDate=birthDate, ) if not patient.success and hospital_uid_from and hospital_uid_from != '0': # TODO: запись с ЕПГУ тоже должна проходить? НЕТ! Без доп. идентификации нельзя. patient = self.addPatient(**kwargs) else: patient = self.findPatient(serverId=kwargs.get('serverId'), lastName=person.get('lastName'), firstName=person.get('firstName'), patrName=person.get('patronymic'), birthDate=birthDate) exception_code = int(patient.message.split()[0]) if exception_code == int(is_exceptions.IS_PatientNotRegistered()): if not patient.success and hospital_uid_from and hospital_uid_from != '0': # TODO: запись с ЕПГУ тоже должна проходить? patient = self.addPatient(**kwargs) if patient.success and patient.patientId: patient_id = patient.patientId else: # raise exceptions.LookupError return { 'result': False, 'error_code': patient.message, } try: date_time = kwargs.get('timeslotStart') if not date_time: date_time = datetime.datetime.now() params = { 'serverId': kwargs.get('serverId'), 'patientId': int(patient_id), 'personId': int(kwargs.get('doctorUid')), 'date': date_time.date(), 'time': date_time.time(), 'note': kwargs.get('email', 'E-mail'), 'hospitalUidFrom': kwargs.get('hospitalUidFrom'), } except: logger.error(exceptions.ValueError(), extra=logger_tags) raise exceptions.ValueError else: try: result = self.client.service.enqueuePatient(**params) except WebFault, e: print e logger.error(e, extra=logger_tags) else: